You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1351 lines
47 KiB

7 years ago
  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  18. """
  19. Abstraction for an SSH2 channel.
  20. """
  21. import binascii
  22. import os
  23. import socket
  24. import time
  25. import threading
  26. # TODO: switch as much of py3compat.py to 'six' as possible, then use six.wraps
  27. from functools import wraps
  28. from paramiko import util
  29. from paramiko.common import (
  30. cMSG_CHANNEL_REQUEST, cMSG_CHANNEL_WINDOW_ADJUST, cMSG_CHANNEL_DATA,
  31. cMSG_CHANNEL_EXTENDED_DATA, DEBUG, ERROR, cMSG_CHANNEL_SUCCESS,
  32. cMSG_CHANNEL_FAILURE, cMSG_CHANNEL_EOF, cMSG_CHANNEL_CLOSE,
  33. )
  34. from paramiko.message import Message
  35. from paramiko.py3compat import bytes_types
  36. from paramiko.ssh_exception import SSHException
  37. from paramiko.file import BufferedFile
  38. from paramiko.buffered_pipe import BufferedPipe, PipeTimeout
  39. from paramiko import pipe
  40. from paramiko.util import ClosingContextManager
  41. def open_only(func):
  42. """
  43. Decorator for `.Channel` methods which performs an openness check.
  44. :raises:
  45. `.SSHException` -- If the wrapped method is called on an unopened
  46. `.Channel`.
  47. """
  48. @wraps(func)
  49. def _check(self, *args, **kwds):
  50. if (
  51. self.closed or
  52. self.eof_received or
  53. self.eof_sent or
  54. not self.active
  55. ):
  56. raise SSHException('Channel is not open')
  57. return func(self, *args, **kwds)
  58. return _check
  59. class Channel (ClosingContextManager):
  60. """
  61. A secure tunnel across an SSH `.Transport`. A Channel is meant to behave
  62. like a socket, and has an API that should be indistinguishable from the
  63. Python socket API.
  64. Because SSH2 has a windowing kind of flow control, if you stop reading data
  65. from a Channel and its buffer fills up, the server will be unable to send
  66. you any more data until you read some of it. (This won't affect other
  67. channels on the same transport -- all channels on a single transport are
  68. flow-controlled independently.) Similarly, if the server isn't reading
  69. data you send, calls to `send` may block, unless you set a timeout. This
  70. is exactly like a normal network socket, so it shouldn't be too surprising.
  71. Instances of this class may be used as context managers.
  72. """
  73. def __init__(self, chanid):
  74. """
  75. Create a new channel. The channel is not associated with any
  76. particular session or `.Transport` until the Transport attaches it.
  77. Normally you would only call this method from the constructor of a
  78. subclass of `.Channel`.
  79. :param int chanid:
  80. the ID of this channel, as passed by an existing `.Transport`.
  81. """
  82. #: Channel ID
  83. self.chanid = chanid
  84. #: Remote channel ID
  85. self.remote_chanid = 0
  86. #: `.Transport` managing this channel
  87. self.transport = None
  88. #: Whether the connection is presently active
  89. self.active = False
  90. self.eof_received = 0
  91. self.eof_sent = 0
  92. self.in_buffer = BufferedPipe()
  93. self.in_stderr_buffer = BufferedPipe()
  94. self.timeout = None
  95. #: Whether the connection has been closed
  96. self.closed = False
  97. self.ultra_debug = False
  98. self.lock = threading.Lock()
  99. self.out_buffer_cv = threading.Condition(self.lock)
  100. self.in_window_size = 0
  101. self.out_window_size = 0
  102. self.in_max_packet_size = 0
  103. self.out_max_packet_size = 0
  104. self.in_window_threshold = 0
  105. self.in_window_sofar = 0
  106. self.status_event = threading.Event()
  107. self._name = str(chanid)
  108. self.logger = util.get_logger('paramiko.transport')
  109. self._pipe = None
  110. self.event = threading.Event()
  111. self.event_ready = False
  112. self.combine_stderr = False
  113. self.exit_status = -1
  114. self.origin_addr = None
  115. def __del__(self):
  116. try:
  117. self.close()
  118. except:
  119. pass
  120. def __repr__(self):
  121. """
  122. Return a string representation of this object, for debugging.
  123. """
  124. out = '<paramiko.Channel {}'.format(self.chanid)
  125. if self.closed:
  126. out += ' (closed)'
  127. elif self.active:
  128. if self.eof_received:
  129. out += ' (EOF received)'
  130. if self.eof_sent:
  131. out += ' (EOF sent)'
  132. out += ' (open) window={}'.format(self.out_window_size)
  133. if len(self.in_buffer) > 0:
  134. out += ' in-buffer={}'.format(len(self.in_buffer))
  135. out += ' -> ' + repr(self.transport)
  136. out += '>'
  137. return out
  138. @open_only
  139. def get_pty(self, term='vt100', width=80, height=24, width_pixels=0,
  140. height_pixels=0):
  141. """
  142. Request a pseudo-terminal from the server. This is usually used right
  143. after creating a client channel, to ask the server to provide some
  144. basic terminal semantics for a shell invoked with `invoke_shell`.
  145. It isn't necessary (or desirable) to call this method if you're going
  146. to execute a single command with `exec_command`.
  147. :param str term: the terminal type to emulate
  148. (for example, ``'vt100'``)
  149. :param int width: width (in characters) of the terminal screen
  150. :param int height: height (in characters) of the terminal screen
  151. :param int width_pixels: width (in pixels) of the terminal screen
  152. :param int height_pixels: height (in pixels) of the terminal screen
  153. :raises:
  154. `.SSHException` -- if the request was rejected or the channel was
  155. closed
  156. """
  157. m = Message()
  158. m.add_byte(cMSG_CHANNEL_REQUEST)
  159. m.add_int(self.remote_chanid)
  160. m.add_string('pty-req')
  161. m.add_boolean(True)
  162. m.add_string(term)
  163. m.add_int(width)
  164. m.add_int(height)
  165. m.add_int(width_pixels)
  166. m.add_int(height_pixels)
  167. m.add_string(bytes())
  168. self._event_pending()
  169. self.transport._send_user_message(m)
  170. self._wait_for_event()
  171. @open_only
  172. def invoke_shell(self):
  173. """
  174. Request an interactive shell session on this channel. If the server
  175. allows it, the channel will then be directly connected to the stdin,
  176. stdout, and stderr of the shell.
  177. Normally you would call `get_pty` before this, in which case the
  178. shell will operate through the pty, and the channel will be connected
  179. to the stdin and stdout of the pty.
  180. When the shell exits, the channel will be closed and can't be reused.
  181. You must open a new channel if you wish to open another shell.
  182. :raises:
  183. `.SSHException` -- if the request was rejected or the channel was
  184. closed
  185. """
  186. m = Message()
  187. m.add_byte(cMSG_CHANNEL_REQUEST)
  188. m.add_int(self.remote_chanid)
  189. m.add_string('shell')
  190. m.add_boolean(True)
  191. self._event_pending()
  192. self.transport._send_user_message(m)
  193. self._wait_for_event()
  194. @open_only
  195. def exec_command(self, command):
  196. """
  197. Execute a command on the server. If the server allows it, the channel
  198. will then be directly connected to the stdin, stdout, and stderr of
  199. the command being executed.
  200. When the command finishes executing, the channel will be closed and
  201. can't be reused. You must open a new channel if you wish to execute
  202. another command.
  203. :param str command: a shell command to execute.
  204. :raises:
  205. `.SSHException` -- if the request was rejected or the channel was
  206. closed
  207. """
  208. m = Message()
  209. m.add_byte(cMSG_CHANNEL_REQUEST)
  210. m.add_int(self.remote_chanid)
  211. m.add_string('exec')
  212. m.add_boolean(True)
  213. m.add_string(command)
  214. self._event_pending()
  215. self.transport._send_user_message(m)
  216. self._wait_for_event()
  217. @open_only
  218. def invoke_subsystem(self, subsystem):
  219. """
  220. Request a subsystem on the server (for example, ``sftp``). If the
  221. server allows it, the channel will then be directly connected to the
  222. requested subsystem.
  223. When the subsystem finishes, the channel will be closed and can't be
  224. reused.
  225. :param str subsystem: name of the subsystem being requested.
  226. :raises:
  227. `.SSHException` -- if the request was rejected or the channel was
  228. closed
  229. """
  230. m = Message()
  231. m.add_byte(cMSG_CHANNEL_REQUEST)
  232. m.add_int(self.remote_chanid)
  233. m.add_string('subsystem')
  234. m.add_boolean(True)
  235. m.add_string(subsystem)
  236. self._event_pending()
  237. self.transport._send_user_message(m)
  238. self._wait_for_event()
  239. @open_only
  240. def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0):
  241. """
  242. Resize the pseudo-terminal. This can be used to change the width and
  243. height of the terminal emulation created in a previous `get_pty` call.
  244. :param int width: new width (in characters) of the terminal screen
  245. :param int height: new height (in characters) of the terminal screen
  246. :param int width_pixels: new width (in pixels) of the terminal screen
  247. :param int height_pixels: new height (in pixels) of the terminal screen
  248. :raises:
  249. `.SSHException` -- if the request was rejected or the channel was
  250. closed
  251. """
  252. m = Message()
  253. m.add_byte(cMSG_CHANNEL_REQUEST)
  254. m.add_int(self.remote_chanid)
  255. m.add_string('window-change')
  256. m.add_boolean(False)
  257. m.add_int(width)
  258. m.add_int(height)
  259. m.add_int(width_pixels)
  260. m.add_int(height_pixels)
  261. self.transport._send_user_message(m)
  262. @open_only
  263. def update_environment(self, environment):
  264. """
  265. Updates this channel's remote shell environment.
  266. .. note::
  267. This operation is additive - i.e. the current environment is not
  268. reset before the given environment variables are set.
  269. .. warning::
  270. Servers may silently reject some environment variables; see the
  271. warning in `set_environment_variable` for details.
  272. :param dict environment:
  273. a dictionary containing the name and respective values to set
  274. :raises:
  275. `.SSHException` -- if any of the environment variables was rejected
  276. by the server or the channel was closed
  277. """
  278. for name, value in environment.items():
  279. try:
  280. self.set_environment_variable(name, value)
  281. except SSHException as e:
  282. err = "Failed to set environment variable \"{}\"."
  283. raise SSHException(err.format(name), e)
  284. @open_only
  285. def set_environment_variable(self, name, value):
  286. """
  287. Set the value of an environment variable.
  288. .. warning::
  289. The server may reject this request depending on its ``AcceptEnv``
  290. setting; such rejections will fail silently (which is common client
  291. practice for this particular request type). Make sure you
  292. understand your server's configuration before using!
  293. :param str name: name of the environment variable
  294. :param str value: value of the environment variable
  295. :raises:
  296. `.SSHException` -- if the request was rejected or the channel was
  297. closed
  298. """
  299. m = Message()
  300. m.add_byte(cMSG_CHANNEL_REQUEST)
  301. m.add_int(self.remote_chanid)
  302. m.add_string('env')
  303. m.add_boolean(False)
  304. m.add_string(name)
  305. m.add_string(value)
  306. self.transport._send_user_message(m)
  307. def exit_status_ready(self):
  308. """
  309. Return true if the remote process has exited and returned an exit
  310. status. You may use this to poll the process status if you don't
  311. want to block in `recv_exit_status`. Note that the server may not
  312. return an exit status in some cases (like bad servers).
  313. :return:
  314. ``True`` if `recv_exit_status` will return immediately, else
  315. ``False``.
  316. .. versionadded:: 1.7.3
  317. """
  318. return self.closed or self.status_event.is_set()
  319. def recv_exit_status(self):
  320. """
  321. Return the exit status from the process on the server. This is
  322. mostly useful for retrieving the results of an `exec_command`.
  323. If the command hasn't finished yet, this method will wait until
  324. it does, or until the channel is closed. If no exit status is
  325. provided by the server, -1 is returned.
  326. .. warning::
  327. In some situations, receiving remote output larger than the current
  328. `.Transport` or session's ``window_size`` (e.g. that set by the
  329. ``default_window_size`` kwarg for `.Transport.__init__`) will cause
  330. `.recv_exit_status` to hang indefinitely if it is called prior to a
  331. sufficiently large `.Channel.recv` (or if there are no threads
  332. calling `.Channel.recv` in the background).
  333. In these cases, ensuring that `.recv_exit_status` is called *after*
  334. `.Channel.recv` (or, again, using threads) can avoid the hang.
  335. :return: the exit code (as an `int`) of the process on the server.
  336. .. versionadded:: 1.2
  337. """
  338. self.status_event.wait()
  339. assert self.status_event.is_set()
  340. return self.exit_status
  341. def send_exit_status(self, status):
  342. """
  343. Send the exit status of an executed command to the client. (This
  344. really only makes sense in server mode.) Many clients expect to
  345. get some sort of status code back from an executed command after
  346. it completes.
  347. :param int status: the exit code of the process
  348. .. versionadded:: 1.2
  349. """
  350. # in many cases, the channel will not still be open here.
  351. # that's fine.
  352. m = Message()
  353. m.add_byte(cMSG_CHANNEL_REQUEST)
  354. m.add_int(self.remote_chanid)
  355. m.add_string('exit-status')
  356. m.add_boolean(False)
  357. m.add_int(status)
  358. self.transport._send_user_message(m)
  359. @open_only
  360. def request_x11(
  361. self,
  362. screen_number=0,
  363. auth_protocol=None,
  364. auth_cookie=None,
  365. single_connection=False,
  366. handler=None
  367. ):
  368. """
  369. Request an x11 session on this channel. If the server allows it,
  370. further x11 requests can be made from the server to the client,
  371. when an x11 application is run in a shell session.
  372. From :rfc:`4254`::
  373. It is RECOMMENDED that the 'x11 authentication cookie' that is
  374. sent be a fake, random cookie, and that the cookie be checked and
  375. replaced by the real cookie when a connection request is received.
  376. If you omit the auth_cookie, a new secure random 128-bit value will be
  377. generated, used, and returned. You will need to use this value to
  378. verify incoming x11 requests and replace them with the actual local
  379. x11 cookie (which requires some knowledge of the x11 protocol).
  380. If a handler is passed in, the handler is called from another thread
  381. whenever a new x11 connection arrives. The default handler queues up
  382. incoming x11 connections, which may be retrieved using
  383. `.Transport.accept`. The handler's calling signature is::
  384. handler(channel: Channel, (address: str, port: int))
  385. :param int screen_number: the x11 screen number (0, 10, etc.)
  386. :param str auth_protocol:
  387. the name of the X11 authentication method used; if none is given,
  388. ``"MIT-MAGIC-COOKIE-1"`` is used
  389. :param str auth_cookie:
  390. hexadecimal string containing the x11 auth cookie; if none is
  391. given, a secure random 128-bit value is generated
  392. :param bool single_connection:
  393. if True, only a single x11 connection will be forwarded (by
  394. default, any number of x11 connections can arrive over this
  395. session)
  396. :param handler:
  397. an optional callable handler to use for incoming X11 connections
  398. :return: the auth_cookie used
  399. """
  400. if auth_protocol is None:
  401. auth_protocol = 'MIT-MAGIC-COOKIE-1'
  402. if auth_cookie is None:
  403. auth_cookie = binascii.hexlify(os.urandom(16))
  404. m = Message()
  405. m.add_byte(cMSG_CHANNEL_REQUEST)
  406. m.add_int(self.remote_chanid)
  407. m.add_string('x11-req')
  408. m.add_boolean(True)
  409. m.add_boolean(single_connection)
  410. m.add_string(auth_protocol)
  411. m.add_string(auth_cookie)
  412. m.add_int(screen_number)
  413. self._event_pending()
  414. self.transport._send_user_message(m)
  415. self._wait_for_event()
  416. self.transport._set_x11_handler(handler)
  417. return auth_cookie
  418. @open_only
  419. def request_forward_agent(self, handler):
  420. """
  421. Request for a forward SSH Agent on this channel.
  422. This is only valid for an ssh-agent from OpenSSH !!!
  423. :param handler:
  424. a required callable handler to use for incoming SSH Agent
  425. connections
  426. :return: True if we are ok, else False
  427. (at that time we always return ok)
  428. :raises: SSHException in case of channel problem.
  429. """
  430. m = Message()
  431. m.add_byte(cMSG_CHANNEL_REQUEST)
  432. m.add_int(self.remote_chanid)
  433. m.add_string('auth-agent-req@openssh.com')
  434. m.add_boolean(False)
  435. self.transport._send_user_message(m)
  436. self.transport._set_forward_agent_handler(handler)
  437. return True
  438. def get_transport(self):
  439. """
  440. Return the `.Transport` associated with this channel.
  441. """
  442. return self.transport
  443. def set_name(self, name):
  444. """
  445. Set a name for this channel. Currently it's only used to set the name
  446. of the channel in logfile entries. The name can be fetched with the
  447. `get_name` method.
  448. :param str name: new channel name
  449. """
  450. self._name = name
  451. def get_name(self):
  452. """
  453. Get the name of this channel that was previously set by `set_name`.
  454. """
  455. return self._name
  456. def get_id(self):
  457. """
  458. Return the `int` ID # for this channel.
  459. The channel ID is unique across a `.Transport` and usually a small
  460. number. It's also the number passed to
  461. `.ServerInterface.check_channel_request` when determining whether to
  462. accept a channel request in server mode.
  463. """
  464. return self.chanid
  465. def set_combine_stderr(self, combine):
  466. """
  467. Set whether stderr should be combined into stdout on this channel.
  468. The default is ``False``, but in some cases it may be convenient to
  469. have both streams combined.
  470. If this is ``False``, and `exec_command` is called (or ``invoke_shell``
  471. with no pty), output to stderr will not show up through the `recv`
  472. and `recv_ready` calls. You will have to use `recv_stderr` and
  473. `recv_stderr_ready` to get stderr output.
  474. If this is ``True``, data will never show up via `recv_stderr` or
  475. `recv_stderr_ready`.
  476. :param bool combine:
  477. ``True`` if stderr output should be combined into stdout on this
  478. channel.
  479. :return: the previous setting (a `bool`).
  480. .. versionadded:: 1.1
  481. """
  482. data = bytes()
  483. self.lock.acquire()
  484. try:
  485. old = self.combine_stderr
  486. self.combine_stderr = combine
  487. if combine and not old:
  488. # copy old stderr buffer into primary buffer
  489. data = self.in_stderr_buffer.empty()
  490. finally:
  491. self.lock.release()
  492. if len(data) > 0:
  493. self._feed(data)
  494. return old
  495. # ...socket API...
  496. def settimeout(self, timeout):
  497. """
  498. Set a timeout on blocking read/write operations. The ``timeout``
  499. argument can be a nonnegative float expressing seconds, or ``None``.
  500. If a float is given, subsequent channel read/write operations will
  501. raise a timeout exception if the timeout period value has elapsed
  502. before the operation has completed. Setting a timeout of ``None``
  503. disables timeouts on socket operations.
  504. ``chan.settimeout(0.0)`` is equivalent to ``chan.setblocking(0)``;
  505. ``chan.settimeout(None)`` is equivalent to ``chan.setblocking(1)``.
  506. :param float timeout:
  507. seconds to wait for a pending read/write operation before raising
  508. ``socket.timeout``, or ``None`` for no timeout.
  509. """
  510. self.timeout = timeout
  511. def gettimeout(self):
  512. """
  513. Returns the timeout in seconds (as a float) associated with socket
  514. operations, or ``None`` if no timeout is set. This reflects the last
  515. call to `setblocking` or `settimeout`.
  516. """
  517. return self.timeout
  518. def setblocking(self, blocking):
  519. """
  520. Set blocking or non-blocking mode of the channel: if ``blocking`` is 0,
  521. the channel is set to non-blocking mode; otherwise it's set to blocking
  522. mode. Initially all channels are in blocking mode.
  523. In non-blocking mode, if a `recv` call doesn't find any data, or if a
  524. `send` call can't immediately dispose of the data, an error exception
  525. is raised. In blocking mode, the calls block until they can proceed. An
  526. EOF condition is considered "immediate data" for `recv`, so if the
  527. channel is closed in the read direction, it will never block.
  528. ``chan.setblocking(0)`` is equivalent to ``chan.settimeout(0)``;
  529. ``chan.setblocking(1)`` is equivalent to ``chan.settimeout(None)``.
  530. :param int blocking:
  531. 0 to set non-blocking mode; non-0 to set blocking mode.
  532. """
  533. if blocking:
  534. self.settimeout(None)
  535. else:
  536. self.settimeout(0.0)
  537. def getpeername(self):
  538. """
  539. Return the address of the remote side of this Channel, if possible.
  540. This simply wraps `.Transport.getpeername`, used to provide enough of a
  541. socket-like interface to allow asyncore to work. (asyncore likes to
  542. call ``'getpeername'``.)
  543. """
  544. return self.transport.getpeername()
  545. def close(self):
  546. """
  547. Close the channel. All future read/write operations on the channel
  548. will fail. The remote end will receive no more data (after queued data
  549. is flushed). Channels are automatically closed when their `.Transport`
  550. is closed or when they are garbage collected.
  551. """
  552. self.lock.acquire()
  553. try:
  554. # only close the pipe when the user explicitly closes the channel.
  555. # otherwise they will get unpleasant surprises. (and do it before
  556. # checking self.closed, since the remote host may have already
  557. # closed the connection.)
  558. if self._pipe is not None:
  559. self._pipe.close()
  560. self._pipe = None
  561. if not self.active or self.closed:
  562. return
  563. msgs = self._close_internal()
  564. finally:
  565. self.lock.release()
  566. for m in msgs:
  567. if m is not None:
  568. self.transport._send_user_message(m)
  569. def recv_ready(self):
  570. """
  571. Returns true if data is buffered and ready to be read from this
  572. channel. A ``False`` result does not mean that the channel has closed;
  573. it means you may need to wait before more data arrives.
  574. :return:
  575. ``True`` if a `recv` call on this channel would immediately return
  576. at least one byte; ``False`` otherwise.
  577. """
  578. return self.in_buffer.read_ready()
  579. def recv(self, nbytes):
  580. """
  581. Receive data from the channel. The return value is a string
  582. representing the data received. The maximum amount of data to be
  583. received at once is specified by ``nbytes``. If a string of
  584. length zero is returned, the channel stream has closed.
  585. :param int nbytes: maximum number of bytes to read.
  586. :return: received data, as a ``str``/``bytes``.
  587. :raises socket.timeout:
  588. if no data is ready before the timeout set by `settimeout`.
  589. """
  590. try:
  591. out = self.in_buffer.read(nbytes, self.timeout)
  592. except PipeTimeout:
  593. raise socket.timeout()
  594. ack = self._check_add_window(len(out))
  595. # no need to hold the channel lock when sending this
  596. if ack > 0:
  597. m = Message()
  598. m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST)
  599. m.add_int(self.remote_chanid)
  600. m.add_int(ack)
  601. self.transport._send_user_message(m)
  602. return out
  603. def recv_stderr_ready(self):
  604. """
  605. Returns true if data is buffered and ready to be read from this
  606. channel's stderr stream. Only channels using `exec_command` or
  607. `invoke_shell` without a pty will ever have data on the stderr
  608. stream.
  609. :return:
  610. ``True`` if a `recv_stderr` call on this channel would immediately
  611. return at least one byte; ``False`` otherwise.
  612. .. versionadded:: 1.1
  613. """
  614. return self.in_stderr_buffer.read_ready()
  615. def recv_stderr(self, nbytes):
  616. """
  617. Receive data from the channel's stderr stream. Only channels using
  618. `exec_command` or `invoke_shell` without a pty will ever have data
  619. on the stderr stream. The return value is a string representing the
  620. data received. The maximum amount of data to be received at once is
  621. specified by ``nbytes``. If a string of length zero is returned, the
  622. channel stream has closed.
  623. :param int nbytes: maximum number of bytes to read.
  624. :return: received data as a `str`
  625. :raises socket.timeout: if no data is ready before the timeout set by
  626. `settimeout`.
  627. .. versionadded:: 1.1
  628. """
  629. try:
  630. out = self.in_stderr_buffer.read(nbytes, self.timeout)
  631. except PipeTimeout:
  632. raise socket.timeout()
  633. ack = self._check_add_window(len(out))
  634. # no need to hold the channel lock when sending this
  635. if ack > 0:
  636. m = Message()
  637. m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST)
  638. m.add_int(self.remote_chanid)
  639. m.add_int(ack)
  640. self.transport._send_user_message(m)
  641. return out
  642. def send_ready(self):
  643. """
  644. Returns true if data can be written to this channel without blocking.
  645. This means the channel is either closed (so any write attempt would
  646. return immediately) or there is at least one byte of space in the
  647. outbound buffer. If there is at least one byte of space in the
  648. outbound buffer, a `send` call will succeed immediately and return
  649. the number of bytes actually written.
  650. :return:
  651. ``True`` if a `send` call on this channel would immediately succeed
  652. or fail
  653. """
  654. self.lock.acquire()
  655. try:
  656. if self.closed or self.eof_sent:
  657. return True
  658. return self.out_window_size > 0
  659. finally:
  660. self.lock.release()
  661. def send(self, s):
  662. """
  663. Send data to the channel. Returns the number of bytes sent, or 0 if
  664. the channel stream is closed. Applications are responsible for
  665. checking that all data has been sent: if only some of the data was
  666. transmitted, the application needs to attempt delivery of the remaining
  667. data.
  668. :param str s: data to send
  669. :return: number of bytes actually sent, as an `int`
  670. :raises socket.timeout: if no data could be sent before the timeout set
  671. by `settimeout`.
  672. """
  673. m = Message()
  674. m.add_byte(cMSG_CHANNEL_DATA)
  675. m.add_int(self.remote_chanid)
  676. return self._send(s, m)
  677. def send_stderr(self, s):
  678. """
  679. Send data to the channel on the "stderr" stream. This is normally
  680. only used by servers to send output from shell commands -- clients
  681. won't use this. Returns the number of bytes sent, or 0 if the channel
  682. stream is closed. Applications are responsible for checking that all
  683. data has been sent: if only some of the data was transmitted, the
  684. application needs to attempt delivery of the remaining data.
  685. :param str s: data to send.
  686. :return: number of bytes actually sent, as an `int`.
  687. :raises socket.timeout:
  688. if no data could be sent before the timeout set by `settimeout`.
  689. .. versionadded:: 1.1
  690. """
  691. m = Message()
  692. m.add_byte(cMSG_CHANNEL_EXTENDED_DATA)
  693. m.add_int(self.remote_chanid)
  694. m.add_int(1)
  695. return self._send(s, m)
  696. def sendall(self, s):
  697. """
  698. Send data to the channel, without allowing partial results. Unlike
  699. `send`, this method continues to send data from the given string until
  700. either all data has been sent or an error occurs. Nothing is returned.
  701. :param str s: data to send.
  702. :raises socket.timeout:
  703. if sending stalled for longer than the timeout set by `settimeout`.
  704. :raises socket.error:
  705. if an error occurred before the entire string was sent.
  706. .. note::
  707. If the channel is closed while only part of the data has been
  708. sent, there is no way to determine how much data (if any) was sent.
  709. This is irritating, but identically follows Python's API.
  710. """
  711. while s:
  712. sent = self.send(s)
  713. s = s[sent:]
  714. return None
  715. def sendall_stderr(self, s):
  716. """
  717. Send data to the channel's "stderr" stream, without allowing partial
  718. results. Unlike `send_stderr`, this method continues to send data
  719. from the given string until all data has been sent or an error occurs.
  720. Nothing is returned.
  721. :param str s: data to send to the client as "stderr" output.
  722. :raises socket.timeout:
  723. if sending stalled for longer than the timeout set by `settimeout`.
  724. :raises socket.error:
  725. if an error occurred before the entire string was sent.
  726. .. versionadded:: 1.1
  727. """
  728. while s:
  729. sent = self.send_stderr(s)
  730. s = s[sent:]
  731. return None
  732. def makefile(self, *params):
  733. """
  734. Return a file-like object associated with this channel. The optional
  735. ``mode`` and ``bufsize`` arguments are interpreted the same way as by
  736. the built-in ``file()`` function in Python.
  737. :return: `.ChannelFile` object which can be used for Python file I/O.
  738. """
  739. return ChannelFile(*([self] + list(params)))
  740. def makefile_stderr(self, *params):
  741. """
  742. Return a file-like object associated with this channel's stderr
  743. stream. Only channels using `exec_command` or `invoke_shell`
  744. without a pty will ever have data on the stderr stream.
  745. The optional ``mode`` and ``bufsize`` arguments are interpreted the
  746. same way as by the built-in ``file()`` function in Python. For a
  747. client, it only makes sense to open this file for reading. For a
  748. server, it only makes sense to open this file for writing.
  749. :return: `.ChannelFile` object which can be used for Python file I/O.
  750. .. versionadded:: 1.1
  751. """
  752. return ChannelStderrFile(*([self] + list(params)))
  753. def fileno(self):
  754. """
  755. Returns an OS-level file descriptor which can be used for polling, but
  756. but not for reading or writing. This is primarily to allow Python's
  757. ``select`` module to work.
  758. The first time ``fileno`` is called on a channel, a pipe is created to
  759. simulate real OS-level file descriptor (FD) behavior. Because of this,
  760. two OS-level FDs are created, which will use up FDs faster than normal.
  761. (You won't notice this effect unless you have hundreds of channels
  762. open at the same time.)
  763. :return: an OS-level file descriptor (`int`)
  764. .. warning::
  765. This method causes channel reads to be slightly less efficient.
  766. """
  767. self.lock.acquire()
  768. try:
  769. if self._pipe is not None:
  770. return self._pipe.fileno()
  771. # create the pipe and feed in any existing data
  772. self._pipe = pipe.make_pipe()
  773. p1, p2 = pipe.make_or_pipe(self._pipe)
  774. self.in_buffer.set_event(p1)
  775. self.in_stderr_buffer.set_event(p2)
  776. return self._pipe.fileno()
  777. finally:
  778. self.lock.release()
  779. def shutdown(self, how):
  780. """
  781. Shut down one or both halves of the connection. If ``how`` is 0,
  782. further receives are disallowed. If ``how`` is 1, further sends
  783. are disallowed. If ``how`` is 2, further sends and receives are
  784. disallowed. This closes the stream in one or both directions.
  785. :param int how:
  786. 0 (stop receiving), 1 (stop sending), or 2 (stop receiving and
  787. sending).
  788. """
  789. if (how == 0) or (how == 2):
  790. # feign "read" shutdown
  791. self.eof_received = 1
  792. if (how == 1) or (how == 2):
  793. self.lock.acquire()
  794. try:
  795. m = self._send_eof()
  796. finally:
  797. self.lock.release()
  798. if m is not None:
  799. self.transport._send_user_message(m)
  800. def shutdown_read(self):
  801. """
  802. Shutdown the receiving side of this socket, closing the stream in
  803. the incoming direction. After this call, future reads on this
  804. channel will fail instantly. This is a convenience method, equivalent
  805. to ``shutdown(0)``, for people who don't make it a habit to
  806. memorize unix constants from the 1970s.
  807. .. versionadded:: 1.2
  808. """
  809. self.shutdown(0)
  810. def shutdown_write(self):
  811. """
  812. Shutdown the sending side of this socket, closing the stream in
  813. the outgoing direction. After this call, future writes on this
  814. channel will fail instantly. This is a convenience method, equivalent
  815. to ``shutdown(1)``, for people who don't make it a habit to
  816. memorize unix constants from the 1970s.
  817. .. versionadded:: 1.2
  818. """
  819. self.shutdown(1)
  820. @property
  821. def _closed(self):
  822. # Concession to Python 3's socket API, which has a private ._closed
  823. # attribute instead of a semipublic .closed attribute.
  824. return self.closed
  825. # ...calls from Transport
  826. def _set_transport(self, transport):
  827. self.transport = transport
  828. self.logger = util.get_logger(self.transport.get_log_channel())
  829. def _set_window(self, window_size, max_packet_size):
  830. self.in_window_size = window_size
  831. self.in_max_packet_size = max_packet_size
  832. # threshold of bytes we receive before we bother to send
  833. # a window update
  834. self.in_window_threshold = window_size // 10
  835. self.in_window_sofar = 0
  836. self._log(DEBUG, 'Max packet in: {} bytes'.format(max_packet_size))
  837. def _set_remote_channel(self, chanid, window_size, max_packet_size):
  838. self.remote_chanid = chanid
  839. self.out_window_size = window_size
  840. self.out_max_packet_size = self.transport._sanitize_packet_size(
  841. max_packet_size
  842. )
  843. self.active = 1
  844. self._log(DEBUG,
  845. 'Max packet out: {} bytes'.format(self.out_max_packet_size))
  846. def _request_success(self, m):
  847. self._log(DEBUG, 'Sesch channel {} request ok'.format(self.chanid))
  848. self.event_ready = True
  849. self.event.set()
  850. return
  851. def _request_failed(self, m):
  852. self.lock.acquire()
  853. try:
  854. msgs = self._close_internal()
  855. finally:
  856. self.lock.release()
  857. for m in msgs:
  858. if m is not None:
  859. self.transport._send_user_message(m)
  860. def _feed(self, m):
  861. if isinstance(m, bytes_types):
  862. # passed from _feed_extended
  863. s = m
  864. else:
  865. s = m.get_binary()
  866. self.in_buffer.feed(s)
  867. def _feed_extended(self, m):
  868. code = m.get_int()
  869. s = m.get_binary()
  870. if code != 1:
  871. self._log(
  872. ERROR,
  873. 'unknown extended_data type {}; discarding'.format(code)
  874. )
  875. return
  876. if self.combine_stderr:
  877. self._feed(s)
  878. else:
  879. self.in_stderr_buffer.feed(s)
  880. def _window_adjust(self, m):
  881. nbytes = m.get_int()
  882. self.lock.acquire()
  883. try:
  884. if self.ultra_debug:
  885. self._log(DEBUG, 'window up {}'.format(nbytes))
  886. self.out_window_size += nbytes
  887. self.out_buffer_cv.notifyAll()
  888. finally:
  889. self.lock.release()
  890. def _handle_request(self, m):
  891. key = m.get_text()
  892. want_reply = m.get_boolean()
  893. server = self.transport.server_object
  894. ok = False
  895. if key == 'exit-status':
  896. self.exit_status = m.get_int()
  897. self.status_event.set()
  898. ok = True
  899. elif key == 'xon-xoff':
  900. # ignore
  901. ok = True
  902. elif key == 'pty-req':
  903. term = m.get_string()
  904. width = m.get_int()
  905. height = m.get_int()
  906. pixelwidth = m.get_int()
  907. pixelheight = m.get_int()
  908. modes = m.get_string()
  909. if server is None:
  910. ok = False
  911. else:
  912. ok = server.check_channel_pty_request(
  913. self,
  914. term,
  915. width,
  916. height,
  917. pixelwidth,
  918. pixelheight,
  919. modes
  920. )
  921. elif key == 'shell':
  922. if server is None:
  923. ok = False
  924. else:
  925. ok = server.check_channel_shell_request(self)
  926. elif key == 'env':
  927. name = m.get_string()
  928. value = m.get_string()
  929. if server is None:
  930. ok = False
  931. else:
  932. ok = server.check_channel_env_request(self, name, value)
  933. elif key == 'exec':
  934. cmd = m.get_string()
  935. if server is None:
  936. ok = False
  937. else:
  938. ok = server.check_channel_exec_request(self, cmd)
  939. elif key == 'subsystem':
  940. name = m.get_text()
  941. if server is None:
  942. ok = False
  943. else:
  944. ok = server.check_channel_subsystem_request(self, name)
  945. elif key == 'window-change':
  946. width = m.get_int()
  947. height = m.get_int()
  948. pixelwidth = m.get_int()
  949. pixelheight = m.get_int()
  950. if server is None:
  951. ok = False
  952. else:
  953. ok = server.check_channel_window_change_request(
  954. self, width, height, pixelwidth, pixelheight)
  955. elif key == 'x11-req':
  956. single_connection = m.get_boolean()
  957. auth_proto = m.get_text()
  958. auth_cookie = m.get_binary()
  959. screen_number = m.get_int()
  960. if server is None:
  961. ok = False
  962. else:
  963. ok = server.check_channel_x11_request(
  964. self,
  965. single_connection,
  966. auth_proto,
  967. auth_cookie,
  968. screen_number
  969. )
  970. elif key == 'auth-agent-req@openssh.com':
  971. if server is None:
  972. ok = False
  973. else:
  974. ok = server.check_channel_forward_agent_request(self)
  975. else:
  976. self._log(DEBUG, 'Unhandled channel request "{}"'.format(key))
  977. ok = False
  978. if want_reply:
  979. m = Message()
  980. if ok:
  981. m.add_byte(cMSG_CHANNEL_SUCCESS)
  982. else:
  983. m.add_byte(cMSG_CHANNEL_FAILURE)
  984. m.add_int(self.remote_chanid)
  985. self.transport._send_user_message(m)
  986. def _handle_eof(self, m):
  987. self.lock.acquire()
  988. try:
  989. if not self.eof_received:
  990. self.eof_received = True
  991. self.in_buffer.close()
  992. self.in_stderr_buffer.close()
  993. if self._pipe is not None:
  994. self._pipe.set_forever()
  995. finally:
  996. self.lock.release()
  997. self._log(DEBUG, 'EOF received ({})'.format(self._name))
  998. def _handle_close(self, m):
  999. self.lock.acquire()
  1000. try:
  1001. msgs = self._close_internal()
  1002. self.transport._unlink_channel(self.chanid)
  1003. finally:
  1004. self.lock.release()
  1005. for m in msgs:
  1006. if m is not None:
  1007. self.transport._send_user_message(m)
  1008. # ...internals...
  1009. def _send(self, s, m):
  1010. size = len(s)
  1011. self.lock.acquire()
  1012. try:
  1013. if self.closed:
  1014. # this doesn't seem useful, but it is the documented behavior
  1015. # of Socket
  1016. raise socket.error('Socket is closed')
  1017. size = self._wait_for_send_window(size)
  1018. if size == 0:
  1019. # eof or similar
  1020. return 0
  1021. m.add_string(s[:size])
  1022. finally:
  1023. self.lock.release()
  1024. # Note: We release self.lock before calling _send_user_message.
  1025. # Otherwise, we can deadlock during re-keying.
  1026. self.transport._send_user_message(m)
  1027. return size
  1028. def _log(self, level, msg, *args):
  1029. self.logger.log(level, "[chan " + self._name + "] " + msg, *args)
  1030. def _event_pending(self):
  1031. self.event.clear()
  1032. self.event_ready = False
  1033. def _wait_for_event(self):
  1034. self.event.wait()
  1035. assert self.event.is_set()
  1036. if self.event_ready:
  1037. return
  1038. e = self.transport.get_exception()
  1039. if e is None:
  1040. e = SSHException('Channel closed.')
  1041. raise e
  1042. def _set_closed(self):
  1043. # you are holding the lock.
  1044. self.closed = True
  1045. self.in_buffer.close()
  1046. self.in_stderr_buffer.close()
  1047. self.out_buffer_cv.notifyAll()
  1048. # Notify any waiters that we are closed
  1049. self.event.set()
  1050. self.status_event.set()
  1051. if self._pipe is not None:
  1052. self._pipe.set_forever()
  1053. def _send_eof(self):
  1054. # you are holding the lock.
  1055. if self.eof_sent:
  1056. return None
  1057. m = Message()
  1058. m.add_byte(cMSG_CHANNEL_EOF)
  1059. m.add_int(self.remote_chanid)
  1060. self.eof_sent = True
  1061. self._log(DEBUG, 'EOF sent ({})'.format(self._name))
  1062. return m
  1063. def _close_internal(self):
  1064. # you are holding the lock.
  1065. if not self.active or self.closed:
  1066. return None, None
  1067. m1 = self._send_eof()
  1068. m2 = Message()
  1069. m2.add_byte(cMSG_CHANNEL_CLOSE)
  1070. m2.add_int(self.remote_chanid)
  1071. self._set_closed()
  1072. # can't unlink from the Transport yet -- the remote side may still
  1073. # try to send meta-data (exit-status, etc)
  1074. return m1, m2
  1075. def _unlink(self):
  1076. # server connection could die before we become active:
  1077. # still signal the close!
  1078. if self.closed:
  1079. return
  1080. self.lock.acquire()
  1081. try:
  1082. self._set_closed()
  1083. self.transport._unlink_channel(self.chanid)
  1084. finally:
  1085. self.lock.release()
  1086. def _check_add_window(self, n):
  1087. self.lock.acquire()
  1088. try:
  1089. if self.closed or self.eof_received or not self.active:
  1090. return 0
  1091. if self.ultra_debug:
  1092. self._log(DEBUG, 'addwindow {}'.format(n))
  1093. self.in_window_sofar += n
  1094. if self.in_window_sofar <= self.in_window_threshold:
  1095. return 0
  1096. if self.ultra_debug:
  1097. self._log(DEBUG,
  1098. 'addwindow send {}'.format(self.in_window_sofar))
  1099. out = self.in_window_sofar
  1100. self.in_window_sofar = 0
  1101. return out
  1102. finally:
  1103. self.lock.release()
  1104. def _wait_for_send_window(self, size):
  1105. """
  1106. (You are already holding the lock.)
  1107. Wait for the send window to open up, and allocate up to ``size`` bytes
  1108. for transmission. If no space opens up before the timeout, a timeout
  1109. exception is raised. Returns the number of bytes available to send
  1110. (may be less than requested).
  1111. """
  1112. # you are already holding the lock
  1113. if self.closed or self.eof_sent:
  1114. return 0
  1115. if self.out_window_size == 0:
  1116. # should we block?
  1117. if self.timeout == 0.0:
  1118. raise socket.timeout()
  1119. # loop here in case we get woken up but a different thread has
  1120. # filled the buffer
  1121. timeout = self.timeout
  1122. while self.out_window_size == 0:
  1123. if self.closed or self.eof_sent:
  1124. return 0
  1125. then = time.time()
  1126. self.out_buffer_cv.wait(timeout)
  1127. if timeout is not None:
  1128. timeout -= time.time() - then
  1129. if timeout <= 0.0:
  1130. raise socket.timeout()
  1131. # we have some window to squeeze into
  1132. if self.closed or self.eof_sent:
  1133. return 0
  1134. if self.out_window_size < size:
  1135. size = self.out_window_size
  1136. if self.out_max_packet_size - 64 < size:
  1137. size = self.out_max_packet_size - 64
  1138. self.out_window_size -= size
  1139. if self.ultra_debug:
  1140. self._log(DEBUG, 'window down to {}'.format(self.out_window_size))
  1141. return size
  1142. class ChannelFile (BufferedFile):
  1143. """
  1144. A file-like wrapper around `.Channel`. A ChannelFile is created by calling
  1145. `Channel.makefile`.
  1146. .. warning::
  1147. To correctly emulate the file object created from a socket's `makefile
  1148. <python:socket.socket.makefile>` method, a `.Channel` and its
  1149. `.ChannelFile` should be able to be closed or garbage-collected
  1150. independently. Currently, closing the `ChannelFile` does nothing but
  1151. flush the buffer.
  1152. """
  1153. def __init__(self, channel, mode='r', bufsize=-1):
  1154. self.channel = channel
  1155. BufferedFile.__init__(self)
  1156. self._set_mode(mode, bufsize)
  1157. def __repr__(self):
  1158. """
  1159. Returns a string representation of this object, for debugging.
  1160. """
  1161. return '<paramiko.ChannelFile from ' + repr(self.channel) + '>'
  1162. def _read(self, size):
  1163. return self.channel.recv(size)
  1164. def _write(self, data):
  1165. self.channel.sendall(data)
  1166. return len(data)
  1167. class ChannelStderrFile (ChannelFile):
  1168. def __init__(self, channel, mode='r', bufsize=-1):
  1169. ChannelFile.__init__(self, channel, mode, bufsize)
  1170. def _read(self, size):
  1171. return self.channel.recv_stderr(size)
  1172. def _write(self, data):
  1173. self.channel.sendall_stderr(data)
  1174. return len(data)
  1175. # vim: set shiftwidth=4 expandtab :

Powered by TurnKey Linux.