filetransfer.py 34 KB

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