-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathchannel.pyx
572 lines (477 loc) · 19.5 KB
/
channel.pyx
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
# This file is part of ssh2-python.
# Copyright (C) 2017-2020 Panos Kittenis
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, version 2.1.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from libc.stdlib cimport malloc, free
from .exceptions import ChannelError
from .session cimport Session
from .utils cimport to_bytes, handle_error_codes
from . cimport c_ssh2
from . cimport sftp
from . cimport error_codes
cdef object PyChannel(c_ssh2.LIBSSH2_CHANNEL *channel, Session session):
cdef Channel _channel = Channel.__new__(Channel, session)
_channel._channel = channel
return _channel
cdef class Channel:
def __cinit__(self, Session session):
self._session = session
def __dealloc__(self):
if self._session is not None and self._session._session is not NULL and self._channel is not NULL:
c_ssh2.libssh2_channel_free(self._channel)
self._channel = NULL
@property
def session(self):
"""Originating session."""
return self._session
def pty(self, term="vt100"):
"""Request a PTY (physical terminal emulation) on the channel.
:param term: Terminal type to emulate.
:type term: str
"""
cdef bytes b_term = to_bytes(term)
cdef const char *_term = b_term
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_request_pty(
self._channel, _term)
return handle_error_codes(rc)
def execute(self, command not None):
"""Execute command.
:param command: Command to execute
:type command: str
:raises: :py:class:`ssh2.exceptions.ChannelError` on errors executing
command
:rtype: int
"""
cdef int rc
cdef bytes b_command = to_bytes(command)
cdef char *_command = b_command
with nogil:
rc = c_ssh2.libssh2_channel_exec(
self._channel, _command)
return handle_error_codes(rc)
def subsystem(self, subsystem not None):
"""Request subsystem from channel.
:param subsystem: Name of subsystem
:type subsystem: str"""
cdef int rc
cdef bytes b_subsystem = to_bytes(subsystem)
cdef char *_subsystem = b_subsystem
with nogil:
rc = c_ssh2.libssh2_channel_subsystem(
self._channel, _subsystem)
return handle_error_codes(rc)
def shell(self):
"""Request interactive shell from channel.
:raises: :py:class:`ssh2.exceptions.ChannelError` on errors requesting
interactive shell.
"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_shell(self._channel)
return handle_error_codes(rc)
def read(self, size_t size=1024):
"""Read the stdout stream.
Returns return code and output buffer tuple.
Return code is the size of the buffer when positive.
Negative values are error codes.
:param size: Max buffer size to read.
:type size: int
:rtype: (int, bytes)"""
return self.read_ex(size=size, stream_id=0)
def read_ex(self, size_t size=1024, int stream_id=0):
"""Read the stream with given id.
Returns return code and output buffer tuple.
Return code is the size of the buffer when positive.
Negative values are error codes.
:param size: Max buffer size to read.
:type size: int
:rtype: (int, bytes)"""
cdef bytes buf = b''
cdef char *cbuf
cdef ssize_t rc
with nogil:
cbuf = <char *>malloc(sizeof(char)*size)
if cbuf is NULL:
with gil:
raise MemoryError
rc = c_ssh2.libssh2_channel_read_ex(
self._channel, stream_id, cbuf, size)
try:
if rc > 0:
buf = cbuf[:rc]
finally:
free(cbuf)
handle_error_codes(rc)
return rc, buf
def read_stderr(self, size_t size=1024):
"""Read the stderr stream.
Returns return code and output buffer tuple.
Return code is the size of the buffer when positive.
Negative values are error codes.
:rtype: (int, bytes)"""
return self.read_ex(
size=size, stream_id=c_ssh2.SSH_EXTENDED_DATA_STDERR)
def eof(self):
"""Get channel EOF status.
:rtype: bool"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_eof(self._channel)
return bool(rc)
def send_eof(self):
"""Tell the remote host that no further data will be sent on the
specified channel. Processes typically interpret this as a closed stdin
descriptor.
Returns 0 on success or negative on failure.
It returns ``LIBSSH2_ERROR_EAGAIN`` when it would otherwise block.
:rtype: int
"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_send_eof(self._channel)
return handle_error_codes(rc)
def wait_eof(self):
"""Wait for the remote end to acknowledge an EOF request.
Returns 0 on success or negative on failure. It returns
:py:class:`ssh2.error_codes.LIBSSH2_ERROR_EAGAIN` when it
would otherwise block.
:rtype: int
"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_wait_eof(self._channel)
return handle_error_codes(rc)
def close(self):
"""Close channel. Typically done to be able to get exit status."""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_close(self._channel)
return handle_error_codes(rc)
def flush(self):
"""Flush stdout stream"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_flush(self._channel)
return handle_error_codes(rc)
def flush_ex(self, int stream_id):
"""Flush stream with id"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_flush_ex(self._channel, stream_id)
return handle_error_codes(rc)
def flush_stderr(self):
"""Flush stderr stream"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_flush_stderr(self._channel)
return handle_error_codes(rc)
def wait_closed(self):
"""Wait for server to acknowledge channel close command."""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_wait_closed(self._channel)
return handle_error_codes(rc)
def get_exit_status(self):
"""Get exit status of command.
Note that ``0`` is also failure code for this function.
Best used in non-blocking mode to avoid it being impossible to tell if
``0`` indicates failure or an actual exit status of ``0``.
Exceptions are raised as with all functions in case of an SSH2Error.
:rtype: int
"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_get_exit_status(self._channel)
handle_error_codes(rc)
return rc
def get_exit_signal(self):
"""Get exit signal, message and language tag, if any, for command.
Returns (`returncode``, ``exit signal``, ``error message``,
``language tag``) tuple.
:rtype: tuple(int, bytes, bytes, bytes)
"""
cdef char *exitsignal = <char *>b'none'
cdef size_t *exitsignal_len = <size_t *>0
cdef char *errmsg = <char *>b'none'
cdef size_t *errmsg_len = <size_t *>0
cdef char *langtag = <char *>b'none'
cdef size_t *langtag_len = <size_t *>0
cdef int rc
cdef bytes py_exitsignal = None
cdef bytes py_errmsg = None
cdef bytes py_langtag = None
cdef size_t py_siglen = 0
cdef size_t py_errlen = 0
cdef size_t py_langlen = 0
with nogil:
rc = c_ssh2.libssh2_channel_get_exit_signal(
self._channel, &exitsignal, exitsignal_len, &errmsg,
errmsg_len, &langtag, langtag_len)
if exitsignal_len is not NULL:
py_siglen = <size_t>exitsignal_len
if errmsg_len is not NULL:
py_errlen = <size_t>errmsg_len
if langtag_len is not NULL:
py_langlen = <size_t>langtag_len
if py_siglen > 0:
py_exitsignal = exitsignal[:py_siglen]
if py_errlen > 0:
py_errmsg = errmsg[:py_errlen]
if py_langlen > 0:
py_langtag = langtag[:py_langlen]
handle_error_codes(rc)
return rc, py_exitsignal, py_errmsg, py_langtag
def setenv(self, varname not None, value not None):
"""Set environment variable on channel.
:param varname: Name of variable to set.
:type varname: str
:param value: Value of variable.
:type value: str
:rtype: int"""
cdef int rc
cdef bytes b_varname = to_bytes(varname)
cdef bytes b_value = to_bytes(value)
cdef char *_varname = b_varname
cdef char *_value = b_value
with nogil:
rc = c_ssh2.libssh2_channel_setenv(
self._channel, _varname, _value)
return handle_error_codes(rc)
def window_read_ex(self, unsigned long read_avail,
unsigned long window_size_initial):
cdef unsigned long rc
with nogil:
rc = c_ssh2.libssh2_channel_window_read_ex(
self._channel, &read_avail, &window_size_initial)
return handle_error_codes(rc)
def window_read(self):
cdef unsigned long rc
with nogil:
rc = c_ssh2.libssh2_channel_window_read(self._channel)
return handle_error_codes(rc)
def window_write_ex(self, unsigned long window_size_initial):
cdef unsigned long rc
with nogil:
rc = c_ssh2.libssh2_channel_window_write_ex(
self._channel, &window_size_initial)
return handle_error_codes(rc)
def window_write(self):
cdef unsigned long rc
with nogil:
rc = c_ssh2.libssh2_channel_window_write(self._channel)
return handle_error_codes(rc)
def receive_window_adjust(self, unsigned long adjustment,
unsigned long force):
cdef unsigned long rc
with nogil:
rc = c_ssh2.libssh2_channel_receive_window_adjust(
self._channel, adjustment, force)
return handle_error_codes(rc)
def receive_window_adjust2(self, unsigned long adjustment,
unsigned long force):
cdef unsigned long rc
cdef unsigned int storewindow = 0
with nogil:
rc = c_ssh2.libssh2_channel_receive_window_adjust2(
self._channel, adjustment, force, &storewindow)
return handle_error_codes(rc)
def write(self, buf not None):
"""Write buffer to stdin.
Returns tuple of (``return_code``, ``bytes_written``).
In blocking mode ``bytes_written`` will always equal ``len(buf)`` if no
errors have occurred which would raise exception.
In non-blocking mode ``return_code`` can be LIBSSH2_ERROR_EAGAIN and
``bytes_written`` *can be less than* ``len(buf)``.
Clients should resume from that point on next call to the function, ie
``buf[bytes_written_in_last_call:]``.
.. note::
While this function handles unicode strings for ``buf``
argument, ``bytes_written`` offset will always be for the *bytes*
representation thereof as returned by the C function calls which only
handle byte strings.
:param buf: Buffer to write
:type buf: str
:rtype: tuple(int, int)
"""
cdef bytes b_buf = to_bytes(buf)
cdef const char *_buf = b_buf
cdef size_t buf_remainder = len(b_buf)
cdef size_t buf_tot_size = buf_remainder
cdef ssize_t rc
cdef size_t bytes_written = 0
with nogil:
while buf_remainder > 0:
rc = c_ssh2.libssh2_channel_write(
self._channel, _buf, buf_remainder)
if rc < 0 and rc != c_ssh2.LIBSSH2_ERROR_EAGAIN:
# Error that will raise exception
with gil:
return handle_error_codes(rc)
elif rc == c_ssh2.LIBSSH2_ERROR_EAGAIN:
break
_buf += rc
buf_remainder -= rc
bytes_written = buf_tot_size - buf_remainder
return rc, bytes_written
def write_ex(self, int stream_id, buf not None):
"""Write buffer to specified stream id.
Returns tuple of (``return_code``, ``bytes_written``).
In blocking mode ``bytes_written`` will always equal ``len(buf)`` if no
errors have occurred which would raise exception.
In non-blocking mode ``return_code`` can be LIBSSH2_ERROR_EAGAIN and
``bytes_written`` *can be less than* ``len(buf)``.
Clients should resume from that point on next call to the function, ie
``buf[bytes_written_in_last_call:]``.
.. note::
While this function handles unicode strings for ``buf``
argument, ``bytes_written`` offset will always be for the *bytes*
representation thereof as returned by the C function calls which only
handle byte strings.
:param stream_id: Id of stream to write to
:type stream_id: int
:param buf: Buffer to write
:type buf: str
:rtype: tuple(int, int)
"""
cdef bytes b_buf = to_bytes(buf)
cdef const char *_buf = b_buf
cdef size_t buf_remainder = len(b_buf)
cdef size_t buf_tot_size = buf_remainder
cdef ssize_t rc
cdef size_t bytes_written = 0
with nogil:
# Write until buffer has been fully written or socket is blocked
while buf_remainder > 0:
rc = c_ssh2.libssh2_channel_write_ex(
self._channel, stream_id, _buf, buf_remainder)
if rc < 0 and rc != c_ssh2.LIBSSH2_ERROR_EAGAIN:
# Error that will raise exception
with gil:
return handle_error_codes(rc)
elif rc == c_ssh2.LIBSSH2_ERROR_EAGAIN:
break
_buf += rc
buf_remainder -= rc
bytes_written = buf_tot_size - buf_remainder
return rc, bytes_written
def write_stderr(self, buf not None):
"""Write buffer to stderr.
Returns tuple of (``return_code``, ``bytes_written``).
In blocking mode ``bytes_written`` will always equal ``len(buf)`` if no
errors have occurred which would raise exception.
In non-blocking mode ``return_code`` can be LIBSSH2_ERROR_EAGAIN and
``bytes_written`` *can be less than* ``len(buf)``.
Clients should resume from that point on next call to ``write``, ie
``buf[bytes_written_in_last_call:]``.
.. note::
While this function handles unicode strings for ``buf``
argument, ``bytes_written`` offset will always be for the *bytes*
representation thereof as returned by the C function calls which only
handle byte strings.
:param buf: Buffer to write
:type buf: str
:rtype: tuple(int, int)
"""
cdef bytes b_buf = to_bytes(buf)
cdef const char *_buf = b_buf
cdef size_t buf_remainder = len(b_buf)
cdef size_t buf_tot_size = buf_remainder
cdef ssize_t rc
cdef size_t bytes_written = 0
with nogil:
while buf_remainder > 0:
rc = c_ssh2.libssh2_channel_write_stderr(
self._channel, _buf, buf_remainder)
if rc < 0 and rc != c_ssh2.LIBSSH2_ERROR_EAGAIN:
# Error that will raise exception
with gil:
return handle_error_codes(rc)
elif rc == c_ssh2.LIBSSH2_ERROR_EAGAIN:
break
_buf += rc
buf_remainder -= rc
bytes_written = buf_tot_size - buf_remainder
return rc, bytes_written
def x11_req(self, int screen_number):
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_x11_req(
self._channel, screen_number)
return handle_error_codes(rc)
def x11_req_ex(self, int single_connection,
const char *auth_proto,
const char *auth_cookie,
int screen_number):
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_x11_req_ex(
self._channel, single_connection,
auth_proto, auth_cookie, screen_number)
return handle_error_codes(rc)
def process_startup(self, request, message=None):
"""Startup process on server for request with message.
Request is a supported SSH subsystem and clients would typically use
one of execute/shell/subsystem functions depending on request type.
:param request: Request type (exec/shell/subsystem).
:type request: str
:param message: Request message. Content depends on request type
and can be ``None``.
:type message: str or ``None``
"""
cdef bytes b_request = to_bytes(request)
cdef bytes b_message = None
cdef char *_request = b_request
cdef char *_message = NULL
cdef size_t r_len = len(b_request)
cdef size_t m_len = 0
if message is not None:
b_message = to_bytes(message)
_message = b_message
m_len = len(b_message)
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_process_startup(
self._channel, _request, r_len, _message, m_len)
return handle_error_codes(rc)
def poll_channel_read(self, int extended):
"""Deprecated - use session.block_directions and socket polling
instead"""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_poll_channel_read(self._channel, extended)
return handle_error_codes(rc)
def handle_extended_data(self, int ignore_mode):
"""Deprecated, use handle_extended_data2"""
with nogil:
c_ssh2.libssh2_channel_handle_extended_data(
self._channel, ignore_mode)
def handle_extended_data2(self, int ignore_mode):
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_handle_extended_data2(
self._channel, ignore_mode)
return handle_error_codes(rc)
def ignore_extended_data(self, int ignore_mode):
"""Deprecated, use handle_extended_data2"""
with nogil:
c_ssh2.libssh2_channel_handle_extended_data(
self._channel, ignore_mode)
def request_auth_agent(self):
"""Request SSH agent authentication forwarding on channel."""
cdef int rc
with nogil:
rc = c_ssh2.libssh2_channel_request_auth_agent(self._channel)
return handle_error_codes(rc)