filetransfer.py 37 KB

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