filetransfer.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. # -*- test-case-name: twisted.conch.test.test_filetransfer -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. from __future__ import division, absolute_import
  6. import errno
  7. import struct
  8. from zope.interface import implementer
  9. from twisted.conch.interfaces import ISFTPServer, ISFTPFile
  10. from twisted.conch.ssh.common import NS, getNS
  11. from twisted.internet import defer, protocol
  12. from twisted.python import failure, log
  13. from twisted.python.compat import (
  14. _PY3, range, itervalues, networkString, nativeString)
  15. class FileTransferBase(protocol.Protocol):
  16. versions = (3, )
  17. packetTypes = {}
  18. def __init__(self):
  19. self.buf = b''
  20. self.otherVersion = None # this gets set
  21. def sendPacket(self, kind, data):
  22. self.transport.write(struct.pack('!LB', len(data)+1, kind) + data)
  23. def dataReceived(self, data):
  24. self.buf += data
  25. while len(self.buf) > 5:
  26. length, kind = struct.unpack('!LB', self.buf[:5])
  27. if len(self.buf) < 4 + length:
  28. return
  29. data, self.buf = self.buf[5:4+length], self.buf[4+length:]
  30. packetType = self.packetTypes.get(kind, None)
  31. if not packetType:
  32. log.msg('no packet type for', kind)
  33. continue
  34. f = getattr(self, 'packet_%s' % packetType, None)
  35. if not f:
  36. log.msg('not implemented: %s' % packetType)
  37. log.msg(repr(data[4:]))
  38. reqId, = struct.unpack('!L', data[:4])
  39. self._sendStatus(reqId, FX_OP_UNSUPPORTED,
  40. "don't understand %s" % packetType)
  41. #XXX not implemented
  42. continue
  43. try:
  44. f(data)
  45. except Exception:
  46. log.err()
  47. continue
  48. def _parseAttributes(self, data):
  49. flags ,= struct.unpack('!L', data[:4])
  50. attrs = {}
  51. data = data[4:]
  52. if flags & FILEXFER_ATTR_SIZE == FILEXFER_ATTR_SIZE:
  53. size ,= struct.unpack('!Q', data[:8])
  54. attrs['size'] = size
  55. data = data[8:]
  56. if flags & FILEXFER_ATTR_OWNERGROUP == FILEXFER_ATTR_OWNERGROUP:
  57. uid, gid = struct.unpack('!2L', data[:8])
  58. attrs['uid'] = uid
  59. attrs['gid'] = gid
  60. data = data[8:]
  61. if flags & FILEXFER_ATTR_PERMISSIONS == FILEXFER_ATTR_PERMISSIONS:
  62. perms ,= struct.unpack('!L', data[:4])
  63. attrs['permissions'] = perms
  64. data = data[4:]
  65. if flags & FILEXFER_ATTR_ACMODTIME == FILEXFER_ATTR_ACMODTIME:
  66. atime, mtime = struct.unpack('!2L', data[:8])
  67. attrs['atime'] = atime
  68. attrs['mtime'] = mtime
  69. data = data[8:]
  70. if flags & FILEXFER_ATTR_EXTENDED == FILEXFER_ATTR_EXTENDED:
  71. extended_count ,= struct.unpack('!L', data[:4])
  72. data = data[4:]
  73. for i in range(extended_count):
  74. extended_type, data = getNS(data)
  75. extended_data, data = getNS(data)
  76. attrs['ext_%s' % nativeString(extended_type)] = extended_data
  77. return attrs, data
  78. def _packAttributes(self, attrs):
  79. flags = 0
  80. data = b''
  81. if 'size' in attrs:
  82. data += struct.pack('!Q', attrs['size'])
  83. flags |= FILEXFER_ATTR_SIZE
  84. if 'uid' in attrs and 'gid' in attrs:
  85. data += struct.pack('!2L', attrs['uid'], attrs['gid'])
  86. flags |= FILEXFER_ATTR_OWNERGROUP
  87. if 'permissions' in attrs:
  88. data += struct.pack('!L', attrs['permissions'])
  89. flags |= FILEXFER_ATTR_PERMISSIONS
  90. if 'atime' in attrs and 'mtime' in attrs:
  91. data += struct.pack('!2L', attrs['atime'], attrs['mtime'])
  92. flags |= FILEXFER_ATTR_ACMODTIME
  93. extended = []
  94. for k in attrs:
  95. if k.startswith('ext_'):
  96. ext_type = NS(networkString(k[4:]))
  97. ext_data = NS(attrs[k])
  98. extended.append(ext_type+ext_data)
  99. if extended:
  100. data += struct.pack('!L', len(extended))
  101. data += b''.join(extended)
  102. flags |= FILEXFER_ATTR_EXTENDED
  103. return struct.pack('!L', flags) + data
  104. class FileTransferServer(FileTransferBase):
  105. def __init__(self, data=None, avatar=None):
  106. FileTransferBase.__init__(self)
  107. self.client = ISFTPServer(avatar) # yay interfaces
  108. self.openFiles = {}
  109. self.openDirs = {}
  110. def packet_INIT(self, data):
  111. version ,= struct.unpack('!L', data[:4])
  112. self.version = min(list(self.versions) + [version])
  113. data = data[4:]
  114. ext = {}
  115. while data:
  116. ext_name, data = getNS(data)
  117. ext_data, data = getNS(data)
  118. ext[ext_name] = ext_data
  119. our_ext = self.client.gotVersion(version, ext)
  120. our_ext_data = b""
  121. for (k,v) in our_ext.items():
  122. our_ext_data += NS(k) + NS(v)
  123. self.sendPacket(FXP_VERSION, struct.pack('!L', self.version) + \
  124. our_ext_data)
  125. def packet_OPEN(self, data):
  126. requestId = data[:4]
  127. data = data[4:]
  128. filename, data = getNS(data)
  129. flags ,= struct.unpack('!L', data[:4])
  130. data = data[4:]
  131. attrs, data = self._parseAttributes(data)
  132. assert data == b'', 'still have data in OPEN: %s' % repr(data)
  133. d = defer.maybeDeferred(self.client.openFile, filename, flags, attrs)
  134. d.addCallback(self._cbOpenFile, requestId)
  135. d.addErrback(self._ebStatus, requestId, b"open failed")
  136. def _cbOpenFile(self, fileObj, requestId):
  137. fileId = networkString(str(hash(fileObj)))
  138. if fileId in self.openFiles:
  139. raise KeyError('id already open')
  140. self.openFiles[fileId] = fileObj
  141. self.sendPacket(FXP_HANDLE, requestId + NS(fileId))
  142. def packet_CLOSE(self, data):
  143. requestId = data[:4]
  144. data = data[4:]
  145. handle, data = getNS(data)
  146. assert data == b'', 'still have data in CLOSE: %s' % repr(data)
  147. if handle in self.openFiles:
  148. fileObj = self.openFiles[handle]
  149. d = defer.maybeDeferred(fileObj.close)
  150. d.addCallback(self._cbClose, handle, requestId)
  151. d.addErrback(self._ebStatus, requestId, b"close failed")
  152. elif handle in self.openDirs:
  153. dirObj = self.openDirs[handle][0]
  154. d = defer.maybeDeferred(dirObj.close)
  155. d.addCallback(self._cbClose, handle, requestId, 1)
  156. d.addErrback(self._ebStatus, requestId, b"close failed")
  157. else:
  158. self._ebClose(failure.Failure(KeyError()), requestId)
  159. def _cbClose(self, result, handle, requestId, isDir = 0):
  160. if isDir:
  161. del self.openDirs[handle]
  162. else:
  163. del self.openFiles[handle]
  164. self._sendStatus(requestId, FX_OK, b'file closed')
  165. def packet_READ(self, data):
  166. requestId = data[:4]
  167. data = data[4:]
  168. handle, data = getNS(data)
  169. (offset, length), data = struct.unpack('!QL', data[:12]), data[12:]
  170. assert data == b'', 'still have data in READ: %s' % repr(data)
  171. if handle not in self.openFiles:
  172. self._ebRead(failure.Failure(KeyError()), requestId)
  173. else:
  174. fileObj = self.openFiles[handle]
  175. d = defer.maybeDeferred(fileObj.readChunk, offset, length)
  176. d.addCallback(self._cbRead, requestId)
  177. d.addErrback(self._ebStatus, requestId, b"read failed")
  178. def _cbRead(self, result, requestId):
  179. if result == b'': # python's read will return this for EOF
  180. raise EOFError()
  181. self.sendPacket(FXP_DATA, requestId + NS(result))
  182. def packet_WRITE(self, data):
  183. requestId = data[:4]
  184. data = data[4:]
  185. handle, data = getNS(data)
  186. offset, = struct.unpack('!Q', data[:8])
  187. data = data[8:]
  188. writeData, data = getNS(data)
  189. assert data == b'', 'still have data in WRITE: %s' % repr(data)
  190. if handle not in self.openFiles:
  191. self._ebWrite(failure.Failure(KeyError()), requestId)
  192. else:
  193. fileObj = self.openFiles[handle]
  194. d = defer.maybeDeferred(fileObj.writeChunk, offset, writeData)
  195. d.addCallback(self._cbStatus, requestId, b"write succeeded")
  196. d.addErrback(self._ebStatus, requestId, b"write failed")
  197. def packet_REMOVE(self, data):
  198. requestId = data[:4]
  199. data = data[4:]
  200. filename, data = getNS(data)
  201. assert data == b'', 'still have data in REMOVE: %s' % repr(data)
  202. d = defer.maybeDeferred(self.client.removeFile, filename)
  203. d.addCallback(self._cbStatus, requestId, b"remove succeeded")
  204. d.addErrback(self._ebStatus, requestId, b"remove failed")
  205. def packet_RENAME(self, data):
  206. requestId = data[:4]
  207. data = data[4:]
  208. oldPath, data = getNS(data)
  209. newPath, data = getNS(data)
  210. assert data == b'', 'still have data in RENAME: %s' % repr(data)
  211. d = defer.maybeDeferred(self.client.renameFile, oldPath, newPath)
  212. d.addCallback(self._cbStatus, requestId, b"rename succeeded")
  213. d.addErrback(self._ebStatus, requestId, b"rename failed")
  214. def packet_MKDIR(self, data):
  215. requestId = data[:4]
  216. data = data[4:]
  217. path, data = getNS(data)
  218. attrs, data = self._parseAttributes(data)
  219. assert data == b'', 'still have data in MKDIR: %s' % repr(data)
  220. d = defer.maybeDeferred(self.client.makeDirectory, path, attrs)
  221. d.addCallback(self._cbStatus, requestId, b"mkdir succeeded")
  222. d.addErrback(self._ebStatus, requestId, b"mkdir failed")
  223. def packet_RMDIR(self, data):
  224. requestId = data[:4]
  225. data = data[4:]
  226. path, data = getNS(data)
  227. assert data == b'', 'still have data in RMDIR: %s' % repr(data)
  228. d = defer.maybeDeferred(self.client.removeDirectory, path)
  229. d.addCallback(self._cbStatus, requestId, b"rmdir succeeded")
  230. d.addErrback(self._ebStatus, requestId, b"rmdir failed")
  231. def packet_OPENDIR(self, data):
  232. requestId = data[:4]
  233. data = data[4:]
  234. path, data = getNS(data)
  235. assert data == b'', 'still have data in OPENDIR: %s' % repr(data)
  236. d = defer.maybeDeferred(self.client.openDirectory, path)
  237. d.addCallback(self._cbOpenDirectory, requestId)
  238. d.addErrback(self._ebStatus, requestId, b"opendir failed")
  239. def _cbOpenDirectory(self, dirObj, requestId):
  240. handle = networkString(str(hash(dirObj)))
  241. if handle in self.openDirs:
  242. raise KeyError("already opened this directory")
  243. self.openDirs[handle] = [dirObj, iter(dirObj)]
  244. self.sendPacket(FXP_HANDLE, requestId + NS(handle))
  245. def packet_READDIR(self, data):
  246. requestId = data[:4]
  247. data = data[4:]
  248. handle, data = getNS(data)
  249. assert data == b'', 'still have data in READDIR: %s' % repr(data)
  250. if handle not in self.openDirs:
  251. self._ebStatus(failure.Failure(KeyError()), requestId)
  252. else:
  253. dirObj, dirIter = self.openDirs[handle]
  254. d = defer.maybeDeferred(self._scanDirectory, dirIter, [])
  255. d.addCallback(self._cbSendDirectory, requestId)
  256. d.addErrback(self._ebStatus, requestId, b"scan directory failed")
  257. def _scanDirectory(self, dirIter, f):
  258. while len(f) < 250:
  259. try:
  260. info = dirIter.next()
  261. except StopIteration:
  262. if not f:
  263. raise EOFError
  264. return f
  265. if isinstance(info, defer.Deferred):
  266. info.addCallback(self._cbScanDirectory, dirIter, f)
  267. return
  268. else:
  269. f.append(info)
  270. return f
  271. def _cbScanDirectory(self, result, dirIter, f):
  272. f.append(result)
  273. return self._scanDirectory(dirIter, f)
  274. def _cbSendDirectory(self, result, requestId):
  275. data = b''
  276. for (filename, longname, attrs) in result:
  277. data += NS(filename)
  278. data += NS(longname)
  279. data += self._packAttributes(attrs)
  280. self.sendPacket(FXP_NAME, requestId +
  281. struct.pack('!L', len(result))+data)
  282. def packet_STAT(self, data, followLinks = 1):
  283. requestId = data[:4]
  284. data = data[4:]
  285. path, data = getNS(data)
  286. assert data == b'', 'still have data in STAT/LSTAT: %s' % repr(data)
  287. d = defer.maybeDeferred(self.client.getAttrs, path, followLinks)
  288. d.addCallback(self._cbStat, requestId)
  289. d.addErrback(self._ebStatus, requestId, b'stat/lstat failed')
  290. def packet_LSTAT(self, data):
  291. self.packet_STAT(data, 0)
  292. def packet_FSTAT(self, data):
  293. requestId = data[:4]
  294. data = data[4:]
  295. handle, data = getNS(data)
  296. assert data == b'', 'still have data in FSTAT: %s' % repr(data)
  297. if handle not in self.openFiles:
  298. self._ebStatus(failure.Failure(KeyError('%s not in self.openFiles'
  299. % handle)), requestId)
  300. else:
  301. fileObj = self.openFiles[handle]
  302. d = defer.maybeDeferred(fileObj.getAttrs)
  303. d.addCallback(self._cbStat, requestId)
  304. d.addErrback(self._ebStatus, requestId, b'fstat failed')
  305. def _cbStat(self, result, requestId):
  306. data = requestId + self._packAttributes(result)
  307. self.sendPacket(FXP_ATTRS, data)
  308. def packet_SETSTAT(self, data):
  309. requestId = data[:4]
  310. data = data[4:]
  311. path, data = getNS(data)
  312. attrs, data = self._parseAttributes(data)
  313. if data != b'':
  314. log.msg('WARN: still have data in SETSTAT: %s' % repr(data))
  315. d = defer.maybeDeferred(self.client.setAttrs, path, attrs)
  316. d.addCallback(self._cbStatus, requestId, b'setstat succeeded')
  317. d.addErrback(self._ebStatus, requestId, b'setstat failed')
  318. def packet_FSETSTAT(self, data):
  319. requestId = data[:4]
  320. data = data[4:]
  321. handle, data = getNS(data)
  322. attrs, data = self._parseAttributes(data)
  323. assert data == b'', 'still have data in FSETSTAT: %s' % repr(data)
  324. if handle not in self.openFiles:
  325. self._ebStatus(failure.Failure(KeyError()), requestId)
  326. else:
  327. fileObj = self.openFiles[handle]
  328. d = defer.maybeDeferred(fileObj.setAttrs, attrs)
  329. d.addCallback(self._cbStatus, requestId, b'fsetstat succeeded')
  330. d.addErrback(self._ebStatus, requestId, b'fsetstat failed')
  331. def packet_READLINK(self, data):
  332. requestId = data[:4]
  333. data = data[4:]
  334. path, data = getNS(data)
  335. assert data == b'', 'still have data in READLINK: %s' % repr(data)
  336. d = defer.maybeDeferred(self.client.readLink, path)
  337. d.addCallback(self._cbReadLink, requestId)
  338. d.addErrback(self._ebStatus, requestId, b'readlink failed')
  339. def _cbReadLink(self, result, requestId):
  340. self._cbSendDirectory([(result, b'', {})], requestId)
  341. def packet_SYMLINK(self, data):
  342. requestId = data[:4]
  343. data = data[4:]
  344. linkPath, data = getNS(data)
  345. targetPath, data = getNS(data)
  346. d = defer.maybeDeferred(self.client.makeLink, linkPath, targetPath)
  347. d.addCallback(self._cbStatus, requestId, b'symlink succeeded')
  348. d.addErrback(self._ebStatus, requestId, b'symlink failed')
  349. def packet_REALPATH(self, data):
  350. requestId = data[:4]
  351. data = data[4:]
  352. path, data = getNS(data)
  353. assert data == b'', 'still have data in REALPATH: %s' % repr(data)
  354. d = defer.maybeDeferred(self.client.realPath, path)
  355. d.addCallback(self._cbReadLink, requestId) # same return format
  356. d.addErrback(self._ebStatus, requestId, b'realpath failed')
  357. def packet_EXTENDED(self, data):
  358. requestId = data[:4]
  359. data = data[4:]
  360. extName, extData = getNS(data)
  361. d = defer.maybeDeferred(self.client.extendedRequest, extName, extData)
  362. d.addCallback(self._cbExtended, requestId)
  363. d.addErrback(self._ebStatus, requestId, networkString(
  364. 'extended %s failed' % extName))
  365. def _cbExtended(self, data, requestId):
  366. self.sendPacket(FXP_EXTENDED_REPLY, requestId + data)
  367. def _cbStatus(self, result, requestId, msg = b"request succeeded"):
  368. self._sendStatus(requestId, FX_OK, msg)
  369. def _ebStatus(self, reason, requestId, msg = b"request failed"):
  370. code = FX_FAILURE
  371. message = msg
  372. if isinstance(reason.value, (IOError, OSError)):
  373. if reason.value.errno == errno.ENOENT: # no such file
  374. code = FX_NO_SUCH_FILE
  375. message = networkString(reason.value.strerror)
  376. elif reason.value.errno == errno.EACCES: # permission denied
  377. code = FX_PERMISSION_DENIED
  378. message = networkString(reason.value.strerror)
  379. elif reason.value.errno == errno.EEXIST:
  380. code = FX_FILE_ALREADY_EXISTS
  381. else:
  382. log.err(reason)
  383. elif isinstance(reason.value, EOFError): # EOF
  384. code = FX_EOF
  385. if reason.value.args:
  386. message = networkString(reason.value.args[0])
  387. elif isinstance(reason.value, NotImplementedError):
  388. code = FX_OP_UNSUPPORTED
  389. if reason.value.args:
  390. message = networkString(reason.value.args[0])
  391. elif isinstance(reason.value, SFTPError):
  392. code = reason.value.code
  393. message = networkString(reason.value.message)
  394. else:
  395. log.err(reason)
  396. self._sendStatus(requestId, code, message)
  397. def _sendStatus(self, requestId, code, message, lang = b''):
  398. """
  399. Helper method to send a FXP_STATUS message.
  400. """
  401. data = requestId + struct.pack('!L', code)
  402. data += NS(message)
  403. data += NS(lang)
  404. self.sendPacket(FXP_STATUS, data)
  405. def connectionLost(self, reason):
  406. """
  407. Clean all opened files and directories.
  408. """
  409. for fileObj in self.openFiles.values():
  410. fileObj.close()
  411. self.openFiles = {}
  412. for (dirObj, dirIter) in self.openDirs.values():
  413. dirObj.close()
  414. self.openDirs = {}
  415. class FileTransferClient(FileTransferBase):
  416. def __init__(self, extData = {}):
  417. """
  418. @param extData: a dict of extended_name : extended_data items
  419. to be sent to the server.
  420. """
  421. FileTransferBase.__init__(self)
  422. self.extData = {}
  423. self.counter = 0
  424. self.openRequests = {} # id -> Deferred
  425. self.wasAFile = {} # Deferred -> 1 TERRIBLE HACK
  426. def connectionMade(self):
  427. data = struct.pack('!L', max(self.versions))
  428. for k,v in itervalues(self.extData):
  429. data += NS(k) + NS(v)
  430. self.sendPacket(FXP_INIT, data)
  431. def _sendRequest(self, msg, data):
  432. data = struct.pack('!L', self.counter) + data
  433. d = defer.Deferred()
  434. self.openRequests[self.counter] = d
  435. self.counter += 1
  436. self.sendPacket(msg, data)
  437. return d
  438. def _parseRequest(self, data):
  439. (id,) = struct.unpack('!L', data[:4])
  440. d = self.openRequests[id]
  441. del self.openRequests[id]
  442. return d, data[4:]
  443. def openFile(self, filename, flags, attrs):
  444. """
  445. Open a file.
  446. This method returns a L{Deferred} that is called back with an object
  447. that provides the L{ISFTPFile} interface.
  448. @type filename: L{bytes}
  449. @param filename: a string representing the file to open.
  450. @param flags: an integer of the flags to open the file with, ORed together.
  451. The flags and their values are listed at the bottom of this file.
  452. @param attrs: a list of attributes to open the file with. It is a
  453. dictionary, consisting of 0 or more keys. The possible keys are::
  454. size: the size of the file in bytes
  455. uid: the user ID of the file as an integer
  456. gid: the group ID of the file as an integer
  457. permissions: the permissions of the file with as an integer.
  458. the bit representation of this field is defined by POSIX.
  459. atime: the access time of the file as seconds since the epoch.
  460. mtime: the modification time of the file as seconds since the epoch.
  461. ext_*: extended attributes. The server is not required to
  462. understand this, but it may.
  463. NOTE: there is no way to indicate text or binary files. it is up
  464. to the SFTP client to deal with this.
  465. """
  466. data = NS(filename) + struct.pack('!L', flags) + self._packAttributes(attrs)
  467. d = self._sendRequest(FXP_OPEN, data)
  468. self.wasAFile[d] = (1, filename) # HACK
  469. return d
  470. def removeFile(self, filename):
  471. """
  472. Remove the given file.
  473. This method returns a Deferred that is called back when it succeeds.
  474. @type filename: L{bytes}
  475. @param filename: the name of the file as a string.
  476. """
  477. return self._sendRequest(FXP_REMOVE, NS(filename))
  478. def renameFile(self, oldpath, newpath):
  479. """
  480. Rename the given file.
  481. This method returns a Deferred that is called back when it succeeds.
  482. @type oldpath: L{bytes}
  483. @param oldpath: the current location of the file.
  484. @type newpath: L{bytes}
  485. @param newpath: the new file name.
  486. """
  487. return self._sendRequest(FXP_RENAME, NS(oldpath)+NS(newpath))
  488. def makeDirectory(self, path, attrs):
  489. """
  490. Make a directory.
  491. This method returns a Deferred that is called back when it is
  492. created.
  493. @type path: L{bytes}
  494. @param path: the name of the directory to create as a string.
  495. @param attrs: a dictionary of attributes to create the directory
  496. with. Its meaning is the same as the attrs in the openFile method.
  497. """
  498. return self._sendRequest(FXP_MKDIR, NS(path)+self._packAttributes(attrs))
  499. def removeDirectory(self, path):
  500. """
  501. Remove a directory (non-recursively)
  502. It is an error to remove a directory that has files or directories in
  503. it.
  504. This method returns a Deferred that is called back when it is removed.
  505. @type path: L{bytes}
  506. @param path: the directory to remove.
  507. """
  508. return self._sendRequest(FXP_RMDIR, NS(path))
  509. def openDirectory(self, path):
  510. """
  511. Open a directory for scanning.
  512. This method returns a Deferred that is called back with an iterable
  513. object that has a close() method.
  514. The close() method is called when the client is finished reading
  515. from the directory. At this point, the iterable will no longer
  516. be used.
  517. The iterable returns triples of the form (filename, longname, attrs)
  518. or a Deferred that returns the same. The sequence must support
  519. __getitem__, but otherwise may be any 'sequence-like' object.
  520. filename is the name of the file relative to the directory.
  521. logname is an expanded format of the filename. The recommended format
  522. is:
  523. -rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer
  524. 1234567890 123 12345678 12345678 12345678 123456789012
  525. The first line is sample output, the second is the length of the field.
  526. The fields are: permissions, link count, user owner, group owner,
  527. size in bytes, modification time.
  528. attrs is a dictionary in the format of the attrs argument to openFile.
  529. @type path: L{bytes}
  530. @param path: the directory to open.
  531. """
  532. d = self._sendRequest(FXP_OPENDIR, NS(path))
  533. self.wasAFile[d] = (0, path)
  534. return d
  535. def getAttrs(self, path, followLinks=0):
  536. """
  537. Return the attributes for the given path.
  538. This method returns a dictionary in the same format as the attrs
  539. argument to openFile or a Deferred that is called back with same.
  540. @type path: L{bytes}
  541. @param path: the path to return attributes for as a string.
  542. @param followLinks: a boolean. if it is True, follow symbolic links
  543. and return attributes for the real path at the base. if it is False,
  544. return attributes for the specified path.
  545. """
  546. if followLinks: m = FXP_STAT
  547. else: m = FXP_LSTAT
  548. return self._sendRequest(m, NS(path))
  549. def setAttrs(self, path, attrs):
  550. """
  551. Set the attributes for the path.
  552. This method returns when the attributes are set or a Deferred that is
  553. called back when they are.
  554. @type path: L{bytes}
  555. @param path: the path to set attributes for as a string.
  556. @param attrs: a dictionary in the same format as the attrs argument to
  557. openFile.
  558. """
  559. data = NS(path) + self._packAttributes(attrs)
  560. return self._sendRequest(FXP_SETSTAT, data)
  561. def readLink(self, path):
  562. """
  563. Find the root of a set of symbolic links.
  564. This method returns the target of the link, or a Deferred that
  565. returns the same.
  566. @type path: L{bytes}
  567. @param path: the path of the symlink to read.
  568. """
  569. d = self._sendRequest(FXP_READLINK, NS(path))
  570. return d.addCallback(self._cbRealPath)
  571. def makeLink(self, linkPath, targetPath):
  572. """
  573. Create a symbolic link.
  574. This method returns when the link is made, or a Deferred that
  575. returns the same.
  576. @type linkPath: L{bytes}
  577. @param linkPath: the pathname of the symlink as a string
  578. @type targetPath: L{bytes}
  579. @param targetPath: the path of the target of the link as a string.
  580. """
  581. return self._sendRequest(FXP_SYMLINK, NS(linkPath)+NS(targetPath))
  582. def realPath(self, path):
  583. """
  584. Convert any path to an absolute path.
  585. This method returns the absolute path as a string, or a Deferred
  586. that returns the same.
  587. @type path: L{bytes}
  588. @param path: the path to convert as a string.
  589. """
  590. d = self._sendRequest(FXP_REALPATH, NS(path))
  591. return d.addCallback(self._cbRealPath)
  592. def _cbRealPath(self, result):
  593. name, longname, attrs = result[0]
  594. if _PY3:
  595. name = name.decode("utf-8")
  596. return name
  597. def extendedRequest(self, request, data):
  598. """
  599. Make an extended request of the server.
  600. The method returns a Deferred that is called back with
  601. the result of the extended request.
  602. @type request: L{bytes}
  603. @param request: the name of the extended request to make.
  604. @type data: L{bytes}
  605. @param data: any other data that goes along with the request.
  606. """
  607. return self._sendRequest(FXP_EXTENDED, NS(request) + data)
  608. def packet_VERSION(self, data):
  609. version, = struct.unpack('!L', data[:4])
  610. data = data[4:]
  611. d = {}
  612. while data:
  613. k, data = getNS(data)
  614. v, data = getNS(data)
  615. d[k]=v
  616. self.version = version
  617. self.gotServerVersion(version, d)
  618. def packet_STATUS(self, data):
  619. d, data = self._parseRequest(data)
  620. code, = struct.unpack('!L', data[:4])
  621. data = data[4:]
  622. if len(data) >= 4:
  623. msg, data = getNS(data)
  624. if len(data) >= 4:
  625. lang, data = getNS(data)
  626. else:
  627. lang = b''
  628. else:
  629. msg = b''
  630. lang = b''
  631. if code == FX_OK:
  632. d.callback((msg, lang))
  633. elif code == FX_EOF:
  634. d.errback(EOFError(msg))
  635. elif code == FX_OP_UNSUPPORTED:
  636. d.errback(NotImplementedError(msg))
  637. else:
  638. d.errback(SFTPError(code, nativeString(msg), lang))
  639. def packet_HANDLE(self, data):
  640. d, data = self._parseRequest(data)
  641. isFile, name = self.wasAFile.pop(d)
  642. if isFile:
  643. cb = ClientFile(self, getNS(data)[0])
  644. else:
  645. cb = ClientDirectory(self, getNS(data)[0])
  646. cb.name = name
  647. d.callback(cb)
  648. def packet_DATA(self, data):
  649. d, data = self._parseRequest(data)
  650. d.callback(getNS(data)[0])
  651. def packet_NAME(self, data):
  652. d, data = self._parseRequest(data)
  653. count, = struct.unpack('!L', data[:4])
  654. data = data[4:]
  655. files = []
  656. for i in range(count):
  657. filename, data = getNS(data)
  658. longname, data = getNS(data)
  659. attrs, data = self._parseAttributes(data)
  660. files.append((filename, longname, attrs))
  661. d.callback(files)
  662. def packet_ATTRS(self, data):
  663. d, data = self._parseRequest(data)
  664. d.callback(self._parseAttributes(data)[0])
  665. def packet_EXTENDED_REPLY(self, data):
  666. d, data = self._parseRequest(data)
  667. d.callback(data)
  668. def gotServerVersion(self, serverVersion, extData):
  669. """
  670. Called when the client sends their version info.
  671. @param otherVersion: an integer representing the version of the SFTP
  672. protocol they are claiming.
  673. @param extData: a dictionary of extended_name : extended_data items.
  674. These items are sent by the client to indicate additional features.
  675. """
  676. @implementer(ISFTPFile)
  677. class ClientFile:
  678. def __init__(self, parent, handle):
  679. self.parent = parent
  680. self.handle = NS(handle)
  681. def close(self):
  682. return self.parent._sendRequest(FXP_CLOSE, self.handle)
  683. def readChunk(self, offset, length):
  684. data = self.handle + struct.pack("!QL", offset, length)
  685. return self.parent._sendRequest(FXP_READ, data)
  686. def writeChunk(self, offset, chunk):
  687. data = self.handle + struct.pack("!Q", offset) + NS(chunk)
  688. return self.parent._sendRequest(FXP_WRITE, data)
  689. def getAttrs(self):
  690. return self.parent._sendRequest(FXP_FSTAT, self.handle)
  691. def setAttrs(self, attrs):
  692. data = self.handle + self.parent._packAttributes(attrs)
  693. return self.parent._sendRequest(FXP_FSTAT, data)
  694. class ClientDirectory:
  695. def __init__(self, parent, handle):
  696. self.parent = parent
  697. self.handle = NS(handle)
  698. self.filesCache = []
  699. def read(self):
  700. d = self.parent._sendRequest(FXP_READDIR, self.handle)
  701. return d
  702. def close(self):
  703. return self.parent._sendRequest(FXP_CLOSE, self.handle)
  704. def __iter__(self):
  705. return self
  706. def next(self):
  707. if self.filesCache:
  708. return self.filesCache.pop(0)
  709. d = self.read()
  710. d.addCallback(self._cbReadDir)
  711. d.addErrback(self._ebReadDir)
  712. return d
  713. def _cbReadDir(self, names):
  714. self.filesCache = names[1:]
  715. return names[0]
  716. def _ebReadDir(self, reason):
  717. reason.trap(EOFError)
  718. def _():
  719. raise StopIteration
  720. self.next = _
  721. return reason
  722. class SFTPError(Exception):
  723. def __init__(self, errorCode, errorMessage, lang = ''):
  724. Exception.__init__(self)
  725. self.code = errorCode
  726. self._message = errorMessage
  727. self.lang = lang
  728. def message(self):
  729. """
  730. A string received over the network that explains the error to a human.
  731. """
  732. # Python 2.6 deprecates assigning to the 'message' attribute of an
  733. # exception. We define this read-only property here in order to
  734. # prevent the warning about deprecation while maintaining backwards
  735. # compatibility with object clients that rely on the 'message'
  736. # attribute being set correctly. See bug #3897.
  737. return self._message
  738. message = property(message)
  739. def __str__(self):
  740. return 'SFTPError %s: %s' % (self.code, self.message)
  741. FXP_INIT = 1
  742. FXP_VERSION = 2
  743. FXP_OPEN = 3
  744. FXP_CLOSE = 4
  745. FXP_READ = 5
  746. FXP_WRITE = 6
  747. FXP_LSTAT = 7
  748. FXP_FSTAT = 8
  749. FXP_SETSTAT = 9
  750. FXP_FSETSTAT = 10
  751. FXP_OPENDIR = 11
  752. FXP_READDIR = 12
  753. FXP_REMOVE = 13
  754. FXP_MKDIR = 14
  755. FXP_RMDIR = 15
  756. FXP_REALPATH = 16
  757. FXP_STAT = 17
  758. FXP_RENAME = 18
  759. FXP_READLINK = 19
  760. FXP_SYMLINK = 20
  761. FXP_STATUS = 101
  762. FXP_HANDLE = 102
  763. FXP_DATA = 103
  764. FXP_NAME = 104
  765. FXP_ATTRS = 105
  766. FXP_EXTENDED = 200
  767. FXP_EXTENDED_REPLY = 201
  768. FILEXFER_ATTR_SIZE = 0x00000001
  769. FILEXFER_ATTR_UIDGID = 0x00000002
  770. FILEXFER_ATTR_OWNERGROUP = FILEXFER_ATTR_UIDGID
  771. FILEXFER_ATTR_PERMISSIONS = 0x00000004
  772. FILEXFER_ATTR_ACMODTIME = 0x00000008
  773. FILEXFER_ATTR_EXTENDED = 0x80000000
  774. FILEXFER_TYPE_REGULAR = 1
  775. FILEXFER_TYPE_DIRECTORY = 2
  776. FILEXFER_TYPE_SYMLINK = 3
  777. FILEXFER_TYPE_SPECIAL = 4
  778. FILEXFER_TYPE_UNKNOWN = 5
  779. FXF_READ = 0x00000001
  780. FXF_WRITE = 0x00000002
  781. FXF_APPEND = 0x00000004
  782. FXF_CREAT = 0x00000008
  783. FXF_TRUNC = 0x00000010
  784. FXF_EXCL = 0x00000020
  785. FXF_TEXT = 0x00000040
  786. FX_OK = 0
  787. FX_EOF = 1
  788. FX_NO_SUCH_FILE = 2
  789. FX_PERMISSION_DENIED = 3
  790. FX_FAILURE = 4
  791. FX_BAD_MESSAGE = 5
  792. FX_NO_CONNECTION = 6
  793. FX_CONNECTION_LOST = 7
  794. FX_OP_UNSUPPORTED = 8
  795. FX_FILE_ALREADY_EXISTS = 11
  796. # http://tools.ietf.org/wg/secsh/draft-ietf-secsh-filexfer/ defines more
  797. # useful error codes, but so far OpenSSH doesn't implement them. We use them
  798. # internally for clarity, but for now define them all as FX_FAILURE to be
  799. # compatible with existing software.
  800. FX_NOT_A_DIRECTORY = FX_FAILURE
  801. FX_FILE_IS_A_DIRECTORY = FX_FAILURE
  802. # initialize FileTransferBase.packetTypes:
  803. g = globals()
  804. for name in list(g.keys()):
  805. if name.startswith('FXP_'):
  806. value = g[name]
  807. FileTransferBase.packetTypes[value] = name[4:]
  808. del g, name, value