-
Notifications
You must be signed in to change notification settings - Fork 143
/
sftp.py
3921 lines (2817 loc) · 127 KB
/
sftp.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) 2015-2016 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
# Jonathan Slenders - proposed changes to allow SFTP server callbacks
# to be coroutines
"""SFTP handlers"""
import asyncio
from collections import OrderedDict
import errno
from fnmatch import fnmatch
import os
from os import SEEK_SET, SEEK_CUR, SEEK_END
import posixpath
import stat
import sys
import time
from .constants import DEFAULT_LANG
from .constants import FXP_INIT, FXP_VERSION, FXP_OPEN, FXP_CLOSE, FXP_READ
from .constants import FXP_WRITE, FXP_LSTAT, FXP_FSTAT, FXP_SETSTAT
from .constants import FXP_FSETSTAT, FXP_OPENDIR, FXP_READDIR, FXP_REMOVE
from .constants import FXP_MKDIR, FXP_RMDIR, FXP_REALPATH, FXP_STAT, FXP_RENAME
from .constants import FXP_READLINK, FXP_SYMLINK, FXP_STATUS, FXP_HANDLE
from .constants import FXP_DATA, FXP_NAME, FXP_ATTRS, FXP_EXTENDED
from .constants import FXP_EXTENDED_REPLY
from .constants import FXF_READ, FXF_WRITE, FXF_APPEND
from .constants import FXF_CREAT, FXF_TRUNC, FXF_EXCL
from .constants import FILEXFER_ATTR_SIZE, FILEXFER_ATTR_UIDGID
from .constants import FILEXFER_ATTR_PERMISSIONS, FILEXFER_ATTR_ACMODTIME
from .constants import FILEXFER_ATTR_EXTENDED, FILEXFER_ATTR_UNDEFINED
from .constants import FX_OK, FX_EOF, FX_NO_SUCH_FILE, FX_PERMISSION_DENIED
from .constants import FX_FAILURE, FX_BAD_MESSAGE, FX_NO_CONNECTION
from .constants import FX_CONNECTION_LOST, FX_OP_UNSUPPORTED
from .misc import async_context_manager, Error, Record
from .packet import Byte, String, UInt32, UInt64, PacketDecodeError, SSHPacket
_SFTP_VERSION = 3
_SFTP_BLOCK_SIZE = 16384
_MAX_SFTP_REQUESTS = 128
_MAX_READDIR_NAMES = 128
def _get_user_name(uid):
"""Return the user name associated with a uid"""
if uid is not None:
try:
import pwd
user = pwd.getpwuid(uid).pw_name
except (ImportError, KeyError):
user = str(uid)
else:
user = ''
return user
def _get_group_name(gid):
"""Return the group name associated with a gid"""
if gid is not None:
try:
import grp
group = grp.getgrgid(gid).gr_name
except (ImportError, KeyError):
group = str(gid)
else:
group = ''
return group
def _setstat(path, attrs):
"""Utility function to set file attributes"""
if attrs.size is not None:
os.truncate(path, attrs.size)
if attrs.uid is not None and attrs.gid is not None:
try:
os.chown(path, attrs.uid, attrs.gid)
except AttributeError: # pragma: no cover
raise NotImplementedError
if attrs.permissions is not None:
os.chmod(path, stat.S_IMODE(attrs.permissions))
if attrs.atime is not None and attrs.mtime is not None:
os.utime(path, times=(attrs.atime, attrs.mtime))
class _LocalFile:
"""A coroutine wrapper around local file I/O"""
def __init__(self, f):
self._file = f
@classmethod
def encode(cls, path):
"""Encode path name using filesystem native encoding
This method has no effect if the path is already bytes.
"""
return os.fsencode(path)
@classmethod
def decode(cls, path, want_string=True):
"""Decode path name using filesystem native encoding
This method has no effect if want_string is set to ``False``.
"""
if want_string:
path = os.fsdecode(path)
return path
@classmethod
def compose_path(cls, path, parent=None):
"""Compose a path
If parent is not specified, just encode the path.
"""
path = cls.encode(path)
return os.path.join(parent, path) if parent else path
@classmethod
@asyncio.coroutine
def open(cls, *args):
"""Open a local file"""
return cls(open(*args))
@classmethod
@asyncio.coroutine
def stat(cls, path):
"""Get attributes of a local file or directory, following symlinks"""
return SFTPAttrs.from_local(os.stat(path))
@classmethod
@asyncio.coroutine
def lstat(cls, path):
"""Get attributes of a local file, directory, or symlink"""
return SFTPAttrs.from_local(os.lstat(path))
@classmethod
@asyncio.coroutine
def setstat(cls, path, attrs):
"""Set attributes of a local file or directory"""
_setstat(path, attrs)
@classmethod
@asyncio.coroutine
def isdir(cls, path):
"""Return if the local path refers to a directory"""
return os.path.isdir(path)
@classmethod
@asyncio.coroutine
def listdir(cls, path):
"""Read the names of the files in a local directory"""
return os.listdir(path)
@classmethod
@asyncio.coroutine
def mkdir(cls, path):
"""Create a local directory with the specified attributes"""
os.mkdir(path)
@classmethod
@asyncio.coroutine
def readlink(cls, path):
"""Return the target of a local symbolic link"""
if sys.platform == 'win32': # pragma: no cover
path = os.fsdecode(path)
return os.readlink(path)
@classmethod
@asyncio.coroutine
def symlink(cls, oldpath, newpath):
"""Create a local symbolic link"""
if sys.platform == 'win32': # pragma: no cover
oldpath = os.fsdecode(oldpath)
newpath = os.fsdecode(newpath)
os.symlink(oldpath, newpath)
@asyncio.coroutine
def read(self, size, offset):
"""Read data from the local file"""
self._file.seek(offset)
return self._file.read(size)
@asyncio.coroutine
def write(self, data, offset):
"""Write data to the local file"""
self._file.seek(offset)
return self._file.write(data)
@asyncio.coroutine
def close(self):
"""Close the local file"""
self._file.close()
class _SFTPFileCopier:
"""SFTP file copier
This class parforms an SFTP file copy, initiating multiple
read and write requests to copy chunks of the file in parallel.
"""
def __init__(self, loop):
self._loop = loop
self._src = None
self._dst = None
self._bytes_left = 0
self._offset = 0
self._pending = set()
@asyncio.coroutine
def _copy_block(self, offset, size):
"""Copy the next block of the file"""
data = yield from self._src.read(size, offset)
yield from self._dst.write(data, offset)
def _copy_blocks(self):
"""Create parallel requests to copy blocks from one file to another"""
while self._bytes_left and len(self._pending) < _MAX_SFTP_REQUESTS:
size = min(self._bytes_left, _SFTP_BLOCK_SIZE)
task = asyncio.Task(self._copy_block(self._offset, size),
loop=self._loop)
self._pending.add(task)
self._offset += size
self._bytes_left -= size
@asyncio.coroutine
def copy(self, srcfs, dstfs, srcpath, dstpath, size):
"""Copy a file"""
try:
self._src = yield from srcfs.open(srcpath, 'rb')
self._dst = yield from dstfs.open(dstpath, 'wb')
self._bytes_left = size
self._copy_blocks()
while self._pending:
done, self._pending = yield from asyncio.wait(
self._pending, return_when=asyncio.FIRST_COMPLETED)
exceptions = [task.exception() for task in done
if task.exception()]
if exceptions:
for task in self._pending:
task.cancel()
raise exceptions[0]
self._copy_blocks()
finally:
if self._src: # pragma: no branch
yield from self._src.close()
if self._dst: # pragma: no branch
yield from self._dst.close()
class SFTPError(Error):
"""SFTP error
This exception is raised when an error occurs while processing
an SFTP request. Exception codes should be taken from
:ref:`SFTP error codes <SFTPErrorCodes>`.
:param int code:
Disconnect reason, taken from :ref:`disconnect reason
codes <DisconnectReasons>`
:param str reason:
A human-readable reason for the disconnect
:param str lang:
The language the reason is in
"""
def __init__(self, code, reason, lang=DEFAULT_LANG):
super().__init__('SFTP', code, reason, lang)
class SFTPAttrs(Record):
"""SFTP file attributes
SFTPAttrs is a simple record class with the following fields:
============ =========================================== ======
Field Description Type
============ =========================================== ======
size File size in bytes uint64
uid User id of file owner uint32
gid Group id of file owner uint32
permissions Bit mask of POSIX file permissions, uint32
atime Last access time, UNIX epoch seconds uint32
mtime Last modification time, UNIX epoch seconds uint32
============ =========================================== ======
In addition to the above, an ``nlink`` field is provided which
stores the number of links to this file, but it is not encoded
in the SFTP protocol. It's included here only so that it can be
used to create the default ``longname`` string in :class:`SFTPName`
objects.
Extended attributes can also be added via a field named
``extended`` which is a list of string name/value pairs.
When setting attributes using an :class:`SFTPAttrs`, only fields
which have been initialized will be changed on the selected file.
"""
# Unfortunately, pylint can't handle attributes defined with setattr
# pylint: disable=attribute-defined-outside-init
__slots__ = OrderedDict((('size', None), ('uid', None), ('gid', None),
('permissions', None), ('atime', None),
('mtime', None), ('nlink', None),
('extended', [])))
def encode(self):
"""Encode SFTP attributes as bytes in an SSH packet"""
flags = 0
attrs = []
if self.size is not None:
flags |= FILEXFER_ATTR_SIZE
attrs.append(UInt64(self.size))
if self.uid is not None and self.gid is not None:
flags |= FILEXFER_ATTR_UIDGID
attrs.append(UInt32(self.uid) + UInt32(self.gid))
if self.permissions is not None:
flags |= FILEXFER_ATTR_PERMISSIONS
attrs.append(UInt32(self.permissions))
if self.atime is not None and self.mtime is not None:
flags |= FILEXFER_ATTR_ACMODTIME
attrs.append(UInt32(int(self.atime)) + UInt32(int(self.mtime)))
if self.extended:
flags |= FILEXFER_ATTR_EXTENDED
attrs.append(UInt32(len(self.extended)))
attrs.extend(String(type) + String(data)
for type, data in self.extended)
return UInt32(flags) + b''.join(attrs)
@classmethod
def decode(cls, packet):
"""Decode bytes in an SSH packet as SFTP attributes"""
flags = packet.get_uint32()
attrs = cls()
if flags & FILEXFER_ATTR_UNDEFINED:
raise SFTPError(FX_BAD_MESSAGE, 'Unsupported attribute flags')
if flags & FILEXFER_ATTR_SIZE:
attrs.size = packet.get_uint64()
if flags & FILEXFER_ATTR_UIDGID:
attrs.uid = packet.get_uint32()
attrs.gid = packet.get_uint32()
if flags & FILEXFER_ATTR_PERMISSIONS:
attrs.permissions = packet.get_uint32()
if flags & FILEXFER_ATTR_ACMODTIME:
attrs.atime = packet.get_uint32()
attrs.mtime = packet.get_uint32()
if flags & FILEXFER_ATTR_EXTENDED:
count = packet.get_uint32()
attrs.extended = []
for _ in range(count):
attr = packet.get_string()
data = packet.get_string()
attrs.extended.append((attr, data))
return attrs
@classmethod
def from_local(cls, result):
"""Convert from local stat attributes"""
return cls(result.st_size, result.st_uid, result.st_gid,
result.st_mode, result.st_atime, result.st_mtime,
result.st_nlink)
class SFTPVFSAttrs(Record):
"""SFTP file system attributes
SFTPVFSAttrs is a simple record class with the following fields:
============ =========================================== ======
Field Description Type
============ =========================================== ======
bsize File system block size (I/O size) uint64
frsize Fundamental block size (allocation size) uint64
blocks Total data blocks (in frsize units) uint64
bfree Free data blocks uint64
bavail Available data blocks (for non-root) uint64
files Total file inodes uint64
ffree Free file inodes uint64
favail Available file inodes (for non-root) uint64
fsid File system id uint64
flags File system flags (read-only, no-setuid) uint64
namemax Maximum filename length uint64
============ =========================================== ======
"""
# Unfortunately, pylint can't handle attributes defined with setattr
# pylint: disable=attribute-defined-outside-init
__slots__ = OrderedDict((('bsize', 0), ('frsize', 0), ('blocks', 0),
('bfree', 0), ('bavail', 0), ('files', 0),
('ffree', 0), ('favail', 0), ('fsid', 0),
('flags', 0), ('namemax', 0)))
def encode(self):
"""Encode SFTP statvfs attributes as bytes in an SSH packet"""
return b''.join((UInt64(self.bsize), UInt64(self.frsize),
UInt64(self.blocks), UInt64(self.bfree),
UInt64(self.bavail), UInt64(self.files),
UInt64(self.ffree), UInt64(self.favail),
UInt64(self.fsid), UInt64(self.flags),
UInt64(self.namemax)))
@classmethod
def decode(cls, packet):
"""Decode bytes in an SSH packet as SFTP statvfs attributes"""
vfsattrs = cls()
vfsattrs.bsize = packet.get_uint64()
vfsattrs.frsize = packet.get_uint64()
vfsattrs.blocks = packet.get_uint64()
vfsattrs.bfree = packet.get_uint64()
vfsattrs.bavail = packet.get_uint64()
vfsattrs.files = packet.get_uint64()
vfsattrs.ffree = packet.get_uint64()
vfsattrs.favail = packet.get_uint64()
vfsattrs.fsid = packet.get_uint64()
vfsattrs.flags = packet.get_uint64()
vfsattrs.namemax = packet.get_uint64()
return vfsattrs
@classmethod
def from_local(cls, result):
"""Convert from local statvfs attributes"""
return cls(result.f_bsize, result.f_frsize, result.f_blocks,
result.f_bfree, result.f_bavail, result.f_files,
result.f_ffree, result.f_favail, 0, result.f_flag,
result.f_namemax)
class SFTPName(Record):
"""SFTP file name and attributes
SFTPName is a simple record class with the following fields:
========= ================================== ==================
Field Description Type
========= ================================== ==================
filename Filename str or bytes
longname Expanded form of filename & attrs str or bytes
attrs File attributes :class:`SFTPAttrs`
========= ================================== ==================
A list of these is returned by :meth:`readdir() <SFTPClient.readdir>`
in :class:`SFTPClient` when retrieving the contents of a directory.
"""
__slots__ = OrderedDict((('filename', ''), ('longname', ''),
('attrs', SFTPAttrs())))
def encode(self):
"""Encode an SFTP name as bytes in an SSH packet"""
# pylint: disable=no-member
return (String(self.filename) + String(self.longname) +
self.attrs.encode())
@classmethod
def decode(cls, packet):
"""Decode bytes in an SSH packet as an SFTP name"""
filename = packet.get_string()
longname = packet.get_string()
attrs = SFTPAttrs.decode(packet)
return cls(filename, longname, attrs)
class SFTPHandler:
"""SFTP session handler"""
# SFTP implementations with broken order for SYMLINK arguments
_nonstandard_symlink_impls = ['OpenSSH', 'paramiko']
# Return types by message -- unlisted entries always return FXP_STATUS,
# those below return FXP_STATUS on error
_return_types = {
FXP_OPEN: FXP_HANDLE,
FXP_READ: FXP_DATA,
FXP_LSTAT: FXP_ATTRS,
FXP_FSTAT: FXP_ATTRS,
FXP_OPENDIR: FXP_HANDLE,
FXP_READDIR: FXP_NAME,
FXP_REALPATH: FXP_NAME,
FXP_STAT: FXP_ATTRS,
FXP_READLINK: FXP_NAME,
b'statvfs@openssh.com': FXP_EXTENDED_REPLY,
b'fstatvfs@openssh.com': FXP_EXTENDED_REPLY
}
def __init__(self, conn, reader, writer):
self._conn = conn
self._reader = reader
self._writer = writer
@asyncio.coroutine
def _cleanup(self, exc):
"""Clean up this SFTP session"""
# pylint: disable=unused-argument
if self._writer: # pragma: no branch
self._writer.close()
self._reader = None
self._writer = None
@asyncio.coroutine
def _process_packet(self, pkttype, pktid, packet):
"""Abstract method for processing SFTP packets"""
raise NotImplementedError
def create_task(self, coro):
"""Create an asynchronous task which catches and reports errors"""
return self._conn.create_task(coro)
def send_packet(self, *args):
"""Send an SFTP packet"""
payload = b''.join(args)
try:
self._writer.write(UInt32(len(payload)) + payload)
except ConnectionError as exc:
raise SFTPError(FX_CONNECTION_LOST, str(exc)) from None
@asyncio.coroutine
def recv_packet(self):
"""Receive an SFTP packet"""
try:
pktlen = yield from self._reader.readexactly(4)
pktlen = int.from_bytes(pktlen, 'big')
packet = yield from self._reader.readexactly(pktlen)
packet = SSHPacket(packet)
except EOFError:
raise SFTPError(FX_CONNECTION_LOST, 'Channel closed') from None
return packet
@asyncio.coroutine
def recv_packets(self):
"""Receive and process SFTP packets"""
try:
while self._reader: # pragma: no branch
packet = yield from self.recv_packet()
pkttype = packet.get_byte()
pktid = packet.get_uint32()
yield from self._process_packet(pkttype, pktid, packet)
except PacketDecodeError as exc:
yield from self._cleanup(SFTPError(FX_BAD_MESSAGE, str(exc)))
except (OSError, SFTPError) as exc:
yield from self._cleanup(exc)
class SFTPClientHandler(SFTPHandler):
"""An SFTP client session handler"""
_extensions = []
def __init__(self, conn, loop, reader, writer):
super().__init__(conn, reader, writer)
self._loop = loop
self._version = None
self._next_pktid = 0
self._requests = {}
self._nonstandard_symlink = False
self._supports_posix_rename = False
self._supports_statvfs = False
self._supports_fstatvfs = False
self._supports_hardlink = False
self._supports_fsync = False
@asyncio.coroutine
def _cleanup(self, exc):
"""Clean up this SFTP client session"""
for waiter in self._requests.values():
if waiter and not waiter.cancelled():
waiter.set_exception(exc)
self._requests = {}
yield from super()._cleanup(exc)
@asyncio.coroutine
def _process_packet(self, pkttype, pktid, packet):
"""Process incoming SFTP responses"""
try:
waiter = self._requests.pop(pktid)
except KeyError:
yield from self._cleanup(SFTPError(FX_BAD_MESSAGE,
'Invalid response id'))
else:
if waiter and not waiter.cancelled():
waiter.set_result((pkttype, packet))
def _send_request(self, pkttype, *args, waiter=None):
"""Send an SFTP request"""
if not self._writer:
raise SFTPError(FX_NO_CONNECTION, 'Connection not open')
pktid = self._next_pktid
self._next_pktid = (self._next_pktid + 1) & 0xffffffff
self._requests[pktid] = waiter
if isinstance(pkttype, bytes):
hdr = Byte(FXP_EXTENDED) + UInt32(pktid) + String(pkttype)
else:
hdr = Byte(pkttype) + UInt32(pktid)
self.send_packet(hdr, *args)
@asyncio.coroutine
def _make_request(self, pkttype, *args):
"""Make an SFTP request and wait for a response"""
waiter = asyncio.Future(loop=self._loop)
self._send_request(pkttype, *args, waiter=waiter)
resptype, resp = yield from waiter
return_type = self._return_types.get(pkttype)
if resptype not in (FXP_STATUS, return_type):
raise SFTPError(FX_BAD_MESSAGE,
'Unexpected response type: %s' % resptype)
result = self._packet_handlers[resptype](self, resp)
if result is not None or return_type is None:
return result
else:
raise SFTPError(FX_BAD_MESSAGE, 'Unexpected FX_OK response')
def _process_status(self, packet):
"""Process an incoming SFTP status response"""
# pylint: disable=no-self-use
code = packet.get_uint32()
try:
reason = packet.get_string().decode('utf-8')
lang = packet.get_string().decode('ascii')
except UnicodeDecodeError:
raise SFTPError(FX_BAD_MESSAGE, 'Invalid status message') from None
packet.check_end()
if code == FX_OK:
return None
else:
raise SFTPError(code, reason, lang)
def _process_handle(self, packet):
"""Process an incoming SFTP handle response"""
# pylint: disable=no-self-use
handle = packet.get_string()
packet.check_end()
return handle
def _process_data(self, packet):
"""Process an incoming SFTP data response"""
# pylint: disable=no-self-use
data = packet.get_string()
packet.check_end()
return data
def _process_name(self, packet):
"""Process an incoming SFTP name response"""
# pylint: disable=no-self-use
count = packet.get_uint32()
names = [SFTPName.decode(packet) for i in range(count)]
packet.check_end()
return names
def _process_attrs(self, packet):
"""Process an incoming SFTP attributes response"""
# pylint: disable=no-self-use
attrs = SFTPAttrs().decode(packet)
packet.check_end()
return attrs
def _process_extended_reply(self, packet):
"""Process an incoming SFTP extended reply response"""
# pylint: disable=no-self-use
# Let the caller do the decoding for extended replies
return packet
_packet_handlers = {
FXP_STATUS: _process_status,
FXP_HANDLE: _process_handle,
FXP_DATA: _process_data,
FXP_NAME: _process_name,
FXP_ATTRS: _process_attrs,
FXP_EXTENDED_REPLY: _process_extended_reply
}
@asyncio.coroutine
def start(self):
"""Start a new SFTP client"""
extensions = (String(name) + String(data)
for name, data in self._extensions)
self.send_packet(Byte(FXP_INIT), UInt32(_SFTP_VERSION), *extensions)
resp = yield from self.recv_packet()
resptype = resp.get_byte()
if resptype != FXP_VERSION:
raise SFTPError(FX_BAD_MESSAGE, 'Expected version message')
version = resp.get_uint32()
extensions = []
while resp:
name = resp.get_string()
data = resp.get_string()
extensions.append((name, data))
if version != _SFTP_VERSION:
raise SFTPError(FX_BAD_MESSAGE,
'Unsupported version: %d' % version)
self._version = version
for name, data in extensions:
if name == b'posix-rename@openssh.com' and data == b'1':
self._supports_posix_rename = True
elif name == b'statvfs@openssh.com' and data == b'2':
self._supports_statvfs = True
elif name == b'fstatvfs@openssh.com' and data == b'2':
self._supports_fstatvfs = True
elif name == b'hardlink@openssh.com' and data == b'1':
self._supports_hardlink = True
elif name == b'fsync@openssh.com' and data == b'1':
self._supports_fsync = True
if version == 3:
# Check if the server has a buggy SYMLINK implementation
server_version = self._reader.get_extra_info('server_version', '')
if any(name in server_version
for name in self._nonstandard_symlink_impls):
self._nonstandard_symlink = True
self.create_task(self.recv_packets())
@asyncio.coroutine
def open(self, filename, pflags, attrs):
"""Make an SFTP open request"""
return (yield from self._make_request(FXP_OPEN, String(filename),
UInt32(pflags), attrs.encode()))
@asyncio.coroutine
def close(self, handle):
"""Make an SFTP close request"""
return (yield from self._make_request(FXP_CLOSE, String(handle)))
def nonblocking_close(self, handle):
"""Send an SFTP close request without blocking on the response"""
# Used by context managers, since they can't block to wait for a reply
self._send_request(FXP_CLOSE, String(handle))
@asyncio.coroutine
def read(self, handle, offset, length):
"""Make an SFTP read request"""
return (yield from self._make_request(FXP_READ, String(handle),
UInt64(offset), UInt32(length)))
@asyncio.coroutine
def write(self, handle, offset, data):
"""Make an SFTP write request"""
return (yield from self._make_request(FXP_WRITE, String(handle),
UInt64(offset), String(data)))
@asyncio.coroutine
def stat(self, path):
"""Make an SFTP stat request"""
return (yield from self._make_request(FXP_STAT, String(path)))
@asyncio.coroutine
def lstat(self, path):
"""Make an SFTP lstat request"""
return (yield from self._make_request(FXP_LSTAT, String(path)))
@asyncio.coroutine
def fstat(self, handle):
"""Make an SFTP fstat request"""
return (yield from self._make_request(FXP_FSTAT, String(handle)))
@asyncio.coroutine
def setstat(self, path, attrs):
"""Make an SFTP setstat request"""
return (yield from self._make_request(FXP_SETSTAT, String(path),
attrs.encode()))
@asyncio.coroutine
def fsetstat(self, handle, attrs):
"""Make an SFTP fsetstat request"""
return (yield from self._make_request(FXP_FSETSTAT, String(handle),
attrs.encode()))
@asyncio.coroutine
def statvfs(self, path):
"""Make an SFTP statvfs request"""
if self._supports_statvfs:
packet = yield from self._make_request(b'statvfs@openssh.com',
String(path))
vfsattrs = SFTPVFSAttrs.decode(packet)
packet.check_end()
return vfsattrs
else:
raise SFTPError(FX_OP_UNSUPPORTED, 'statvfs not supported')
@asyncio.coroutine
def fstatvfs(self, handle):
"""Make an SFTP fstatvfs request"""
if self._supports_fstatvfs:
packet = yield from self._make_request(b'fstatvfs@openssh.com',
String(handle))
vfsattrs = SFTPVFSAttrs.decode(packet)
packet.check_end()
return vfsattrs
else:
raise SFTPError(FX_OP_UNSUPPORTED, 'fstatvfs not supported')
@asyncio.coroutine
def remove(self, path):
"""Make an SFTP remove request"""
return (yield from self._make_request(FXP_REMOVE, String(path)))
@asyncio.coroutine
def rename(self, oldpath, newpath):
"""Make an SFTP rename request"""
return (yield from self._make_request(FXP_RENAME, String(oldpath),
String(newpath)))
@asyncio.coroutine
def posix_rename(self, oldpath, newpath):
"""Make an SFTP POSIX rename request"""
if self._supports_posix_rename:
return (yield from self._make_request(b'posix-rename@openssh.com',
String(oldpath),
String(newpath)))
else:
raise SFTPError(FX_OP_UNSUPPORTED, 'POSIX rename not supported')
@asyncio.coroutine
def opendir(self, path):
"""Make an SFTP opendir request"""
return (yield from self._make_request(FXP_OPENDIR, String(path)))
@asyncio.coroutine
def readdir(self, handle):
"""Make an SFTP readdir request"""
return (yield from self._make_request(FXP_READDIR, String(handle)))
@asyncio.coroutine
def mkdir(self, path, attrs):
"""Make an SFTP mkdir request"""
return (yield from self._make_request(FXP_MKDIR, String(path),
attrs.encode()))
@asyncio.coroutine
def rmdir(self, path):
"""Make an SFTP rmdir request"""
return (yield from self._make_request(FXP_RMDIR, String(path)))
@asyncio.coroutine
def realpath(self, path):
"""Make an SFTP realpath request"""
return (yield from self._make_request(FXP_REALPATH, String(path)))