-
Notifications
You must be signed in to change notification settings - Fork 143
/
channel.py
1944 lines (1396 loc) · 66.6 KB
/
channel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2013-2019 by Ron Frederick <ronf@timeheart.net> and others.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v2.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-2.0/
#
# This program may also be made available under the following secondary
# licenses when the conditions for such availability set forth in the
# Eclipse Public License v2.0 are satisfied:
#
# GNU General Public License, Version 2.0, or any later versions of
# that license
#
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""SSH channel and session handlers"""
import asyncio
import binascii
import codecs
import inspect
import re
import signal as _signal
from .constants import DEFAULT_LANG, EXTENDED_DATA_STDERR
from .constants import MSG_CHANNEL_OPEN, MSG_CHANNEL_WINDOW_ADJUST
from .constants import MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA
from .constants import MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MSG_CHANNEL_REQUEST
from .constants import MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE
from .constants import OPEN_CONNECT_FAILED, PTY_OP_RESERVED, PTY_OP_END
from .constants import OPEN_REQUEST_X11_FORWARDING_FAILED
from .constants import OPEN_REQUEST_PTY_FAILED, OPEN_REQUEST_SESSION_FAILED
from .constants import __dict__ as constants
from .editor import SSHLineEditorChannel, SSHLineEditorSession
from .misc import ChannelOpenError, ProtocolError
from .misc import get_symbol_names, map_handler_name
from .packet import Boolean, Byte, String, UInt32, SSHPacketHandler
_pty_mode_names = get_symbol_names(constants, 'PTY_', 4)
_data_type_names = get_symbol_names(constants, 'EXTENDED_DATA_', 14)
_signal_regex = re.compile(r'SIG[^_]')
_signal_numbers = {k[3:]: int(v) for (k, v) in vars(_signal).items()
if _signal_regex.match(k)}
_signal_names = {v: k for (k, v) in _signal_numbers.items()}
class SSHChannel(SSHPacketHandler):
"""Parent class for SSH channels"""
_handler_names = get_symbol_names(globals(), 'MSG_CHANNEL_')
_read_datatypes = set()
_write_datatypes = set()
def __init__(self, conn, loop, encoding, errors, window, max_pktsize):
"""Initialize an SSH channel
If encoding is set, data sent and received will be in the form
of strings, converted on the wire to bytes using the specified
encoding. If encoding is None, data sent and received must be
provided as bytes.
Window specifies the initial receive window size.
Max_pktsize specifies the maximum length of a single data packet.
"""
self._conn = conn
self._loop = loop
self._session = None
self._extra = {'connection': conn}
self._env = {}
self._command = None
self._subsystem = None
self._send_state = 'closed'
self._send_chan = None
self._send_window = None
self._send_pktsize = None
self._send_paused = False
self._send_buf = []
self._send_buf_len = 0
self._recv_state = 'closed'
self._init_recv_window = window
self._recv_window = window
self._recv_pktsize = max_pktsize
self._recv_paused = 'starting'
self._recv_buf = []
self._request_queue = []
self._open_waiter = None
self._request_waiters = []
self._close_event = asyncio.Event()
self._recv_chan = conn.add_channel(self)
self._logger = conn.logger.get_child(context='chan=%d' %
self._recv_chan)
self.set_encoding(encoding, errors)
self.set_write_buffer_limits()
@property
def logger(self):
"""A logger associated with this channel"""
return self._logger
def get_connection(self):
"""Return the connection used by this channel"""
return self._conn
def get_loop(self):
"""Return the event loop used by this channel"""
return self._loop
def get_encoding(self):
"""Return the encoding used by this channel"""
return self._encoding, self._errors
def set_encoding(self, encoding, errors='strict'):
"""Set the encoding on this channel"""
self._encoding = encoding
self._errors = errors
if encoding:
self._encoder = codecs.getincrementalencoder(encoding)(errors)
self._decoder = codecs.getincrementaldecoder(encoding)(errors)
else:
self._encoder = None
self._decoder = None
def get_recv_window(self):
"""Return the configured receive window for this channel"""
return self._init_recv_window
def get_read_datatypes(self):
"""Return the legal read data types for this channel"""
return self._read_datatypes
def get_write_datatypes(self):
"""Return the legal write data types for this channel"""
return self._write_datatypes
def _cleanup(self, exc=None):
"""Clean up this channel"""
if self._open_waiter:
if not self._open_waiter.cancelled(): # pragma: no branch
self._open_waiter.set_exception(
ChannelOpenError(OPEN_CONNECT_FAILED,
'SSH connection closed'))
self._open_waiter = None
if self._request_waiters:
for waiter in self._request_waiters:
if not waiter.cancelled(): # pragma: no cover
if exc:
waiter.set_exception(exc)
else:
waiter.set_result(False)
self._request_waiters = []
if self._session is not None:
self._session.connection_lost(exc)
self._session = None
self._close_event.set()
if self._conn: # pragma: no branch
self.logger.info('Channel closed%s',
': ' + str(exc) if exc else '')
self._conn.detach_x11_listener(self)
self._conn.remove_channel(self._recv_chan)
self._send_chan = None
self._recv_chan = None
self._conn = None
def _close_send(self):
"""Discard unsent data and close the channel for sending"""
# Discard unsent data
self._send_buf = []
self._send_buf_len = 0
if self._send_state != 'closed':
self.send_packet(MSG_CHANNEL_CLOSE)
self._send_chan = None
self._send_state = 'closed'
def _discard_recv(self):
"""Discard unreceived data and clean up if close received"""
# Discard unreceived data
self._recv_buf = []
self._recv_paused = False
# If recv is close_pending, we know send is already closed
if self._recv_state == 'close_pending':
self._recv_state = 'closed'
self._loop.call_soon(self._cleanup)
async def _start_reading(self):
"""Start processing data on a new connection"""
# If owner of the channel didn't explicitly pause it at
# startup, begin processing incoming data.
if self._recv_paused == 'starting':
self.logger.debug2('Reading from channel started')
self._recv_paused = False
self._flush_recv_buf()
def _pause_resume_writing(self):
"""Pause or resume writing based on send buffer low/high water marks"""
if self._send_paused:
if self._send_buf_len <= self._send_low_water:
self.logger.debug2('Writing from session resumed')
self._send_paused = False
self._session.resume_writing()
else:
if self._send_buf_len > self._send_high_water:
self.logger.debug2('Writing from session paused')
self._send_paused = True
self._session.pause_writing()
def _flush_send_buf(self):
"""Flush as much data in send buffer as the send window allows"""
while self._send_buf and self._send_window:
pktsize = min(self._send_window, self._send_pktsize)
buf, datatype = self._send_buf[0]
if len(buf) > pktsize:
data = buf[:pktsize]
del buf[:pktsize]
else:
data = buf
del self._send_buf[0]
self._send_buf_len -= len(data)
self._send_window -= len(data)
if datatype is None:
self.send_packet(MSG_CHANNEL_DATA, String(data))
else:
self.send_packet(MSG_CHANNEL_EXTENDED_DATA,
UInt32(datatype), String(data))
self._pause_resume_writing()
if not self._send_buf:
if self._send_state == 'eof_pending':
self.send_packet(MSG_CHANNEL_EOF)
self._send_state = 'eof'
elif self._send_state == 'close_pending':
self._close_send()
def _flush_recv_buf(self, exc=None):
"""Flush as much data in the recv buffer as the application allows"""
while self._recv_buf and not self._recv_paused:
self._deliver_data(*self._recv_buf.pop(0))
if not self._recv_buf:
if self._encoding and not exc and \
self._recv_state in ('eof_pending', 'close_pending'):
try:
self._decoder.decode(b'', True)
except UnicodeDecodeError as unicode_exc:
raise ProtocolError(str(unicode_exc)) from None
if self._recv_state == 'eof_pending':
self._recv_state = 'eof'
if (not self._session.eof_received() and
self._send_state == 'open'):
self.write_eof()
elif self._recv_state == 'close_pending':
self._recv_state = 'closed'
self._loop.call_soon(self._cleanup, exc)
def _deliver_data(self, data, datatype):
"""Deliver incoming data to the session"""
self._recv_window -= len(data)
if self._recv_window < self._init_recv_window / 2:
adjust = self._init_recv_window - self._recv_window
self.logger.debug2('Sending window adjust of %d bytes, '
'new window %d', adjust, self._init_recv_window)
self.send_packet(MSG_CHANNEL_WINDOW_ADJUST, UInt32(adjust))
self._recv_window = self._init_recv_window
if self._encoding:
try:
data = self._decoder.decode(data)
except UnicodeDecodeError as unicode_exc:
raise ProtocolError(str(unicode_exc)) from None
if self._session is not None:
self._session.data_received(data, datatype)
def _accept_data(self, data, datatype=None):
"""Accept new data on the channel
This method accepts new data on the channel, immediately
delivering it to the session if it hasn't paused reading.
If it has paused, data is buffered until reading is resumed.
Data sent after the channel has been closed by the session
is dropped.
"""
if not data:
return
if self._send_state in {'close_pending', 'closed'}:
return
datalen = len(data)
if datalen > self._recv_window:
raise ProtocolError('Window exceeded')
if datatype:
typename = ' from %s' % _data_type_names[datatype]
else:
typename = ''
self.logger.debug2('Received %d data byte%s%s', datalen,
's' if datalen > 1 else '', typename)
if self._recv_paused:
self._recv_buf.append((data, datatype))
else:
self._deliver_data(data, datatype)
def _service_next_request(self):
"""Process next item on channel request queue"""
request, packet, _ = self._request_queue[0]
name = '_process_' + map_handler_name(request) + '_request'
handler = getattr(self, name, None)
if callable(handler):
result = handler(packet)
else:
self.logger.debug1('Received unknown channel request: %s', request)
result = False
if result is not None:
self._report_response(result)
def _report_response(self, result):
"""Report back the response to a previously issued channel request"""
request, _, want_reply = self._request_queue.pop(0)
if want_reply and self._send_state not in {'close_pending', 'closed'}:
if result:
self.send_packet(MSG_CHANNEL_SUCCESS)
else:
self.send_packet(MSG_CHANNEL_FAILURE)
if result and request in {'shell', 'exec', 'subsystem'}:
self._session.session_started()
self.resume_reading()
if self._request_queue:
self._service_next_request()
def process_connection_close(self, exc):
"""Process the SSH connection closing"""
self.logger.info('Closing channel due to connection close')
self._cleanup(exc)
def process_open(self, send_chan, send_window, send_pktsize, session):
"""Process a channel open request"""
self._send_chan = send_chan
self._send_window = send_window
self._send_pktsize = send_pktsize
self.logger.debug2(' Initial send window %d, packet size %d',
send_window, send_pktsize)
self._conn.create_task(self._finish_open_request(session), self.logger)
def _wrap_session(self, session):
"""Hook to optionally wrap channel and session objects"""
# By default, return the original channel and session objects
return self, session
async def _finish_open_request(self, session):
"""Finish processing a channel open request"""
try:
if inspect.isawaitable(session):
session = await session
if not self._conn:
raise ChannelOpenError(OPEN_CONNECT_FAILED,
'SSH connection closed')
chan, self._session = self._wrap_session(session)
self.logger.debug2(' Initial recv window %d, packet size %d',
self._recv_window, self._recv_pktsize)
self._conn.send_channel_open_confirmation(self._send_chan,
self._recv_chan,
self._recv_window,
self._recv_pktsize)
self._send_state = 'open'
self._recv_state = 'open'
self._session.connection_made(chan)
except ChannelOpenError as exc:
if self._conn:
self._conn.send_channel_open_failure(self._send_chan, exc.code,
exc.reason, exc.lang)
self._loop.call_soon(self._cleanup)
def process_open_confirmation(self, send_chan, send_window,
send_pktsize, packet):
"""Process a channel open confirmation"""
if not self._open_waiter:
raise ProtocolError('Channel not being opened')
self._send_chan = send_chan
self._send_window = send_window
self._send_pktsize = send_pktsize
self.logger.debug2(' Initial send window %d, packet size %d',
send_window, send_pktsize)
self._send_state = 'open'
self._recv_state = 'open'
if not self._open_waiter.cancelled(): # pragma: no branch
self._open_waiter.set_result(packet)
self._open_waiter = None
def process_open_failure(self, code, reason, lang):
"""Process a channel open failure"""
if not self._open_waiter:
raise ProtocolError('Channel not being opened')
if not self._open_waiter.cancelled(): # pragma: no branch
self._open_waiter.set_exception(
ChannelOpenError(code, reason, lang))
self._open_waiter = None
self._loop.call_soon(self._cleanup)
def _process_window_adjust(self, _pkttype, _pktid, packet):
"""Process a send window adjustment"""
if self._recv_state not in {'open', 'eof_pending', 'eof'}:
raise ProtocolError('Channel not open')
adjust = packet.get_uint32()
packet.check_end()
self._send_window += adjust
self.logger.debug2('Received window adjust of %d bytes, '
'new window %d', adjust, self._send_window)
self._flush_send_buf()
def _process_data(self, _pkttype, _pktid, packet):
"""Process incoming data"""
if self._recv_state != 'open':
raise ProtocolError('Channel not open for sending')
data = packet.get_string()
packet.check_end()
self._accept_data(data)
def _process_extended_data(self, _pkttype, _pktid, packet):
"""Process incoming extended data"""
if self._recv_state != 'open':
raise ProtocolError('Channel not open for sending')
datatype = packet.get_uint32()
data = packet.get_string()
packet.check_end()
if datatype not in self._read_datatypes:
raise ProtocolError('Invalid extended data type')
self._accept_data(data, datatype)
def _process_eof(self, _pkttype, _pktid, packet):
"""Process an incoming end of file"""
if self._recv_state != 'open':
raise ProtocolError('Channel not open for sending')
packet.check_end()
self.logger.debug2('Received EOF')
self._recv_state = 'eof_pending'
self._flush_recv_buf()
def _process_close(self, _pkttype, _pktid, packet):
"""Process an incoming channel close"""
if self._recv_state not in {'open', 'eof_pending', 'eof'}:
raise ProtocolError('Channel not open')
packet.check_end()
self.logger.info('Received channel close')
self._close_send()
self._recv_state = 'close_pending'
self._flush_recv_buf()
def _process_request(self, _pkttype, _pktid, packet):
"""Process an incoming channel request"""
if self._recv_state not in {'open', 'eof_pending', 'eof'}:
raise ProtocolError('Channel not open')
request = packet.get_string()
want_reply = packet.get_boolean()
try:
request = request.decode('ascii')
except UnicodeDecodeError:
raise ProtocolError('Invalid channel request') from None
self._request_queue.append((request, packet, want_reply))
if len(self._request_queue) == 1:
self._service_next_request()
def _process_response(self, pkttype, _pktid, packet):
"""Process a success or failure response"""
packet.check_end()
if self._request_waiters:
waiter = self._request_waiters.pop(0)
if not waiter.cancelled(): # pragma: no branch
waiter.set_result(pkttype == MSG_CHANNEL_SUCCESS)
else:
raise ProtocolError('Unexpected channel response')
def _process_keepalive_at_openssh_dot_com_request(self, packet):
"""Process an incoming OpenSSH keepalive request"""
packet.check_end()
self.logger.debug2('Received OpenSSH keepalive channel request')
return True
_packet_handlers = {
MSG_CHANNEL_WINDOW_ADJUST: _process_window_adjust,
MSG_CHANNEL_DATA: _process_data,
MSG_CHANNEL_EXTENDED_DATA: _process_extended_data,
MSG_CHANNEL_EOF: _process_eof,
MSG_CHANNEL_CLOSE: _process_close,
MSG_CHANNEL_REQUEST: _process_request,
MSG_CHANNEL_SUCCESS: _process_response,
MSG_CHANNEL_FAILURE: _process_response
}
async def _open(self, chantype, *args):
"""Make a request to open the channel"""
if self._send_state != 'closed':
raise OSError('Channel already open')
self._open_waiter = self._loop.create_future()
self.logger.debug2(' Initial recv window %d, packet size %d',
self._recv_window, self._recv_pktsize)
self._conn.send_packet(MSG_CHANNEL_OPEN, String(chantype),
UInt32(self._recv_chan),
UInt32(self._recv_window),
UInt32(self._recv_pktsize), *args, handler=self)
return await self._open_waiter
def send_packet(self, pkttype, *args):
"""Send a packet on the channel"""
if self._send_chan is None: # pragma: no cover
return
payload = UInt32(self._send_chan) + b''.join(args)
self._conn.send_packet(pkttype, payload, handler=self)
def _send_request(self, request, *args, want_reply=False):
"""Send a channel request"""
self.send_packet(MSG_CHANNEL_REQUEST, String(request),
Boolean(want_reply), *args)
async def _make_request(self, request, *args):
"""Make a channel request and wait for the response"""
if self._send_chan is None:
return False
waiter = self._loop.create_future()
self._request_waiters.append(waiter)
self._send_request(request, *args, want_reply=True)
return await waiter
def abort(self):
"""Forcibly close the channel
This method can be called to forcibly close the channel, after
which no more data can be sent or received. Any unsent buffered
data and any incoming data in flight will be discarded.
"""
self.logger.info('Aborting channel')
if self._send_state not in {'close_pending', 'closed'}:
# Send an immediate close, discarding unsent data
self._close_send()
if self._recv_state != 'closed':
# Discard unreceived data
self._discard_recv()
def close(self):
"""Cleanly close the channel
This method can be called to cleanly close the channel, after
which no more data can be sent or received. Any unsent buffered
data will be flushed asynchronously before the channel is
closed.
"""
self.logger.info('Closing channel')
if self._send_state not in {'close_pending', 'closed'}:
# Send a close only after sending unsent data
self._send_state = 'close_pending'
self._flush_send_buf()
if self._recv_state != 'closed':
# Discard unreceived data
self._discard_recv()
def is_closing(self):
"""Return if the channel is closing or is closed"""
return self._send_state != 'open'
async def wait_closed(self):
"""Wait for this channel to close
This method is a coroutine which can be called to block until
this channel has finished closing.
"""
await self._close_event.wait()
def get_extra_info(self, name, default=None):
"""Get additional information about the channel
This method returns extra information about the channel once
it is established. Supported values include `'connection'`
to return the SSH connection this channel is running over plus
all of the values supported on that connection.
For TCP channels, the values `'local_peername'` and
`'remote_peername'` are added to return the local and remote
host and port information for the tunneled TCP connection.
For UNIX channels, the values `'local_peername'` and
`'remote_peername'` are added to return the local and remote
path information for the tunneled UNIX domain socket connection.
Since UNIX domain sockets provide no "source" address, only
one of these will be filled in.
See :meth:`get_extra_info() <SSHClientConnection.get_extra_info>`
on :class:`SSHClientConnection` for more information.
Additional information stored on the channel by calling
:meth:`set_extra_info` can also be returned here.
"""
return self._extra.get(name, self._conn.get_extra_info(name, default)
if self._conn else default)
def set_extra_info(self, **kwargs):
"""Store additional information associated with the channel
This method allows extra information to be associated with the
channel. The information to store should be passed in as
keyword parameters and can later be returned by calling
:meth:`get_extra_info` with one of the keywords as the name
to retrieve.
"""
self._extra.update(**kwargs)
def can_write_eof(self):
"""Return whether the channel supports :meth:`write_eof`
This method always returns `True`.
"""
# pylint: disable=no-self-use
return True
def get_write_buffer_size(self):
"""Return the current size of the channel's output buffer
This method returns how many bytes are currently in the
channel's output buffer waiting to be written.
"""
return self._send_buf_len
def set_write_buffer_limits(self, high=None, low=None):
"""Set the high- and low-water limits for write flow control
This method sets the limits used when deciding when to call
the :meth:`pause_writing() <SSHClientSession.pause_writing>`
and :meth:`resume_writing() <SSHClientSession.resume_writing>`
methods on SSH sessions. Writing will be paused when the write
buffer size exceeds the high-water mark, and resumed when the
write buffer size equals or drops below the low-water mark.
"""
if high is None:
high = 4*low if low is not None else 65536
if low is None:
low = high // 4
if not 0 <= low <= high:
raise ValueError('high (%r) must be >= low (%r) must be >= 0' %
(high, low))
self.logger.debug1('Set write buffer limits: low-water=%d, '
'high-water=%d', low, high)
self._send_high_water = high
self._send_low_water = low
self._pause_resume_writing()
def write(self, data, datatype=None):
"""Write data on the channel
This method can be called to send data on the channel. If
an encoding was specified when the channel was created, the
data should be provided as a string and will be converted
using that encoding. Otherwise, the data should be provided
as bytes.
An extended data type can optionally be provided. For
instance, this is used from a :class:`SSHServerSession`
to write data to `stderr`.
:param data:
The data to send on the channel
:param datatype: (optional)
The extended data type of the data, from :ref:`extended
data types <ExtendedDataTypes>`
:type data: `str` or `bytes`
:type datatype: `int`
:raises: :exc:`OSError` if the channel isn't open for sending
or the extended data type is not valid for this type
of channel
"""
if self._send_state != 'open':
raise BrokenPipeError('Channel not open for sending')
if datatype is not None and datatype not in self._write_datatypes:
raise OSError('Invalid extended data type')
datalen = len(data)
if datalen == 0:
return
if self._encoding:
data = self._encoder.encode(data)
if datatype:
typename = ' to %s' % _data_type_names[datatype]
else:
typename = ''
self.logger.debug2('Sending %d data byte%s%s', datalen,
's' if datalen > 1 else '', typename)
self._send_buf.append((bytearray(data), datatype))
self._send_buf_len += datalen
self._flush_send_buf()
def writelines(self, list_of_data, datatype=None):
"""Write a list of data bytes on the channel
This method can be called to write a list (or any iterable) of
data bytes to the channel. It is functionality equivalent to
calling :meth:`write` on each element in the list.
:param list_of_data:
The data to send on the channel
:param datatype: (optional)
The extended data type of the data, from :ref:`extended
data types <ExtendedDataTypes>`
:type list_of_data: iterable of `str` or `bytes`
:type datatype: `int`
:raises: :exc:`OSError` if the channel isn't open for sending
or the extended data type is not valid for this type
of channel
"""
sep = '' if self._encoding else b''
return self.write(sep.join(list_of_data), datatype)
def write_eof(self):
"""Write EOF on the channel
This method sends an end-of-file indication on the
channel, after which no more data can be sent. The
channel remains open, though, and data may still be
sent in the other direction.
:raises: :exc:`OSError` if the channel isn't open for sending
"""
self.logger.debug2('Sending EOF')
if self._send_state == 'open':
self._send_state = 'eof_pending'
self._flush_send_buf()
def pause_reading(self):
"""Pause delivery of incoming data
This method is used to temporarily suspend delivery of incoming
channel data. After this call, incoming data will no longer
be delivered until :meth:`resume_reading` is called. Data will be
buffered locally up to the configured SSH channel window size,
but window updates will no longer be sent, eventually causing
back pressure on the remote system.
.. note:: Channel close notifications are not suspended by this
call. If the remote system closes the channel while
delivery is suspended, the channel will be closed even
though some buffered data may not have been delivered.
"""
self.logger.debug2('Reading from channel paused')
self._recv_paused = True
def resume_reading(self):
"""Resume delivery of incoming data
This method can be called to resume delivery of incoming data
which was suspended by a call to :meth:`pause_reading`. As soon
as this method is called, any buffered data will be delivered
immediately. A pending end-of-file notication may also be
delivered if one was queued while reading was paused.
"""
if self._recv_paused:
self.logger.debug2('Reading from channel resumed')
self._recv_paused = False
self._flush_recv_buf()
def get_environment(self):
"""Return the environment for this session
This method returns the environment set by the client when
the session was opened. On the server, calls to this method
should only be made after :meth:`session_started
<SSHServerSession.session_started>` has been called on the
:class:`SSHServerSession`. When using the stream-based API,
calls to this can be made at any time after the handler
function has started up.
:returns: A dictionary containing the environment variables
set by the client
"""
return self._env
def get_command(self):
"""Return the command the client requested to execute, if any
This method returns the command the client requested to
execute when the session was opened, if any. If the client
did not request that a command be executed, this method
will return `None`. On the server, alls to this method
should only be made after :meth:`session_started
<SSHServerSession.session_started>` has been called on the
:class:`SSHServerSession`. When using the stream-based API,
calls to this can be made at any time after the handler
function has started up.
"""
return self._command
def get_subsystem(self):
"""Return the subsystem the client requested to open, if any
This method returns the subsystem the client requested to
open when the session was opened, if any. If the client
did not request that a subsystem be opened, this method will
return `None`. On the server, calls to this method should
only be made after :meth:`session_started
<SSHServerSession.session_started>` has been called on the
:class:`SSHServerSession`. When using the stream-based API,
calls to this can be made at any time after the handler
function has started up.
"""
return self._subsystem
class SSHClientChannel(SSHChannel):
"""SSH client channel"""
_read_datatypes = {EXTENDED_DATA_STDERR}
def __init__(self, conn, loop, encoding, errors, window, max_pktsize):
super().__init__(conn, loop, encoding, errors, window, max_pktsize)