ftp.py 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374
  1. # -*- test-case-name: twisted.test.test_ftp -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An FTP protocol implementation
  6. """
  7. # System Imports
  8. import os
  9. import time
  10. import re
  11. import stat
  12. import errno
  13. import fnmatch
  14. try:
  15. import pwd
  16. import grp
  17. except ImportError:
  18. pwd = grp = None
  19. from zope.interface import Interface, implementer
  20. # Twisted Imports
  21. from twisted import copyright
  22. from twisted.internet import reactor, interfaces, protocol, error, defer
  23. from twisted.protocols import basic, policies
  24. from twisted.python import log, failure, filepath
  25. from twisted.python.compat import range, unicode
  26. from twisted.cred import error as cred_error, portal, credentials, checkers
  27. # constants
  28. # response codes
  29. RESTART_MARKER_REPLY = "100"
  30. SERVICE_READY_IN_N_MINUTES = "120"
  31. DATA_CNX_ALREADY_OPEN_START_XFR = "125"
  32. FILE_STATUS_OK_OPEN_DATA_CNX = "150"
  33. CMD_OK = "200.1"
  34. TYPE_SET_OK = "200.2"
  35. ENTERING_PORT_MODE = "200.3"
  36. CMD_NOT_IMPLMNTD_SUPERFLUOUS = "202"
  37. SYS_STATUS_OR_HELP_REPLY = "211.1"
  38. FEAT_OK = '211.2'
  39. DIR_STATUS = "212"
  40. FILE_STATUS = "213"
  41. HELP_MSG = "214"
  42. NAME_SYS_TYPE = "215"
  43. SVC_READY_FOR_NEW_USER = "220.1"
  44. WELCOME_MSG = "220.2"
  45. SVC_CLOSING_CTRL_CNX = "221.1"
  46. GOODBYE_MSG = "221.2"
  47. DATA_CNX_OPEN_NO_XFR_IN_PROGRESS = "225"
  48. CLOSING_DATA_CNX = "226.1"
  49. TXFR_COMPLETE_OK = "226.2"
  50. ENTERING_PASV_MODE = "227"
  51. ENTERING_EPSV_MODE = "229"
  52. USR_LOGGED_IN_PROCEED = "230.1" # v1 of code 230
  53. GUEST_LOGGED_IN_PROCEED = "230.2" # v2 of code 230
  54. REQ_FILE_ACTN_COMPLETED_OK = "250"
  55. PWD_REPLY = "257.1"
  56. MKD_REPLY = "257.2"
  57. USR_NAME_OK_NEED_PASS = "331.1" # v1 of Code 331
  58. GUEST_NAME_OK_NEED_EMAIL = "331.2" # v2 of code 331
  59. NEED_ACCT_FOR_LOGIN = "332"
  60. REQ_FILE_ACTN_PENDING_FURTHER_INFO = "350"
  61. SVC_NOT_AVAIL_CLOSING_CTRL_CNX = "421.1"
  62. TOO_MANY_CONNECTIONS = "421.2"
  63. CANT_OPEN_DATA_CNX = "425"
  64. CNX_CLOSED_TXFR_ABORTED = "426"
  65. REQ_ACTN_ABRTD_FILE_UNAVAIL = "450"
  66. REQ_ACTN_ABRTD_LOCAL_ERR = "451"
  67. REQ_ACTN_ABRTD_INSUFF_STORAGE = "452"
  68. SYNTAX_ERR = "500"
  69. SYNTAX_ERR_IN_ARGS = "501"
  70. CMD_NOT_IMPLMNTD = "502.1"
  71. OPTS_NOT_IMPLEMENTED = '502.2'
  72. BAD_CMD_SEQ = "503"
  73. CMD_NOT_IMPLMNTD_FOR_PARAM = "504"
  74. NOT_LOGGED_IN = "530.1" # v1 of code 530 - please log in
  75. AUTH_FAILURE = "530.2" # v2 of code 530 - authorization failure
  76. NEED_ACCT_FOR_STOR = "532"
  77. FILE_NOT_FOUND = "550.1" # no such file or directory
  78. PERMISSION_DENIED = "550.2" # permission denied
  79. ANON_USER_DENIED = "550.3" # anonymous users can't alter filesystem
  80. IS_NOT_A_DIR = "550.4" # rmd called on a path that is not a directory
  81. REQ_ACTN_NOT_TAKEN = "550.5"
  82. FILE_EXISTS = "550.6"
  83. IS_A_DIR = "550.7"
  84. PAGE_TYPE_UNK = "551"
  85. EXCEEDED_STORAGE_ALLOC = "552"
  86. FILENAME_NOT_ALLOWED = "553"
  87. RESPONSE = {
  88. # -- 100's --
  89. # TODO: this must be fixed
  90. RESTART_MARKER_REPLY: '110 MARK yyyy-mmmm',
  91. SERVICE_READY_IN_N_MINUTES: '120 service ready in %s minutes',
  92. DATA_CNX_ALREADY_OPEN_START_XFR: '125 Data connection already open, '
  93. 'starting transfer',
  94. FILE_STATUS_OK_OPEN_DATA_CNX: '150 File status okay; about to open '
  95. 'data connection.',
  96. # -- 200's --
  97. CMD_OK: '200 Command OK',
  98. TYPE_SET_OK: '200 Type set to %s.',
  99. ENTERING_PORT_MODE: '200 PORT OK',
  100. CMD_NOT_IMPLMNTD_SUPERFLUOUS: '202 Command not implemented, '
  101. 'superfluous at this site',
  102. SYS_STATUS_OR_HELP_REPLY: '211 System status reply',
  103. FEAT_OK: ['211-Features:', '211 End'],
  104. DIR_STATUS: '212 %s',
  105. FILE_STATUS: '213 %s',
  106. HELP_MSG: '214 help: %s',
  107. NAME_SYS_TYPE: '215 UNIX Type: L8',
  108. WELCOME_MSG: "220 %s",
  109. SVC_READY_FOR_NEW_USER: '220 Service ready',
  110. SVC_CLOSING_CTRL_CNX: '221 Service closing control '
  111. 'connection',
  112. GOODBYE_MSG: '221 Goodbye.',
  113. DATA_CNX_OPEN_NO_XFR_IN_PROGRESS: '225 data connection open, no '
  114. 'transfer in progress',
  115. CLOSING_DATA_CNX: '226 Abort successful',
  116. TXFR_COMPLETE_OK: '226 Transfer Complete.',
  117. ENTERING_PASV_MODE: '227 Entering Passive Mode (%s).',
  118. # Where is EPSV defined in the RFCs?
  119. ENTERING_EPSV_MODE: '229 Entering Extended Passive Mode '
  120. '(|||%s|).',
  121. USR_LOGGED_IN_PROCEED: '230 User logged in, proceed',
  122. GUEST_LOGGED_IN_PROCEED: '230 Anonymous login ok, access '
  123. 'restrictions apply.',
  124. # i.e. CWD completed OK
  125. REQ_FILE_ACTN_COMPLETED_OK: '250 Requested File Action Completed '
  126. 'OK',
  127. PWD_REPLY: '257 "%s"',
  128. MKD_REPLY: '257 "%s" created',
  129. # -- 300's --
  130. USR_NAME_OK_NEED_PASS: '331 Password required for %s.',
  131. GUEST_NAME_OK_NEED_EMAIL: '331 Guest login ok, type your email '
  132. 'address as password.',
  133. NEED_ACCT_FOR_LOGIN: '332 Need account for login.',
  134. REQ_FILE_ACTN_PENDING_FURTHER_INFO: '350 Requested file action pending '
  135. 'further information.',
  136. # -- 400's --
  137. SVC_NOT_AVAIL_CLOSING_CTRL_CNX: '421 Service not available, closing '
  138. 'control connection.',
  139. TOO_MANY_CONNECTIONS: '421 Too many users right now, try '
  140. 'again in a few minutes.',
  141. CANT_OPEN_DATA_CNX: "425 Can't open data connection.",
  142. CNX_CLOSED_TXFR_ABORTED: '426 Transfer aborted. Data '
  143. 'connection closed.',
  144. REQ_ACTN_ABRTD_FILE_UNAVAIL: '450 Requested action aborted. '
  145. 'File unavailable.',
  146. REQ_ACTN_ABRTD_LOCAL_ERR: '451 Requested action aborted. '
  147. 'Local error in processing.',
  148. REQ_ACTN_ABRTD_INSUFF_STORAGE: '452 Requested action aborted. '
  149. 'Insufficient storage.',
  150. # -- 500's --
  151. SYNTAX_ERR: "500 Syntax error: %s",
  152. SYNTAX_ERR_IN_ARGS: '501 syntax error in argument(s) %s.',
  153. CMD_NOT_IMPLMNTD: "502 Command '%s' not implemented",
  154. OPTS_NOT_IMPLEMENTED: "502 Option '%s' not implemented.",
  155. BAD_CMD_SEQ: '503 Incorrect sequence of commands: '
  156. '%s',
  157. CMD_NOT_IMPLMNTD_FOR_PARAM: "504 Not implemented for parameter "
  158. "'%s'.",
  159. NOT_LOGGED_IN: '530 Please login with USER and PASS.',
  160. AUTH_FAILURE: '530 Sorry, Authentication failed.',
  161. NEED_ACCT_FOR_STOR: '532 Need an account for storing '
  162. 'files',
  163. FILE_NOT_FOUND: '550 %s: No such file or directory.',
  164. PERMISSION_DENIED: '550 %s: Permission denied.',
  165. ANON_USER_DENIED: '550 Anonymous users are forbidden to '
  166. 'change the filesystem',
  167. IS_NOT_A_DIR: '550 Cannot rmd, %s is not a '
  168. 'directory',
  169. FILE_EXISTS: '550 %s: File exists',
  170. IS_A_DIR: '550 %s: is a directory',
  171. REQ_ACTN_NOT_TAKEN: '550 Requested action not taken: %s',
  172. PAGE_TYPE_UNK: '551 Page type unknown',
  173. EXCEEDED_STORAGE_ALLOC: '552 Requested file action aborted, '
  174. 'exceeded file storage allocation',
  175. FILENAME_NOT_ALLOWED: '553 Requested action not taken, file '
  176. 'name not allowed'
  177. }
  178. class InvalidPath(Exception):
  179. """
  180. Internal exception used to signify an error during parsing a path.
  181. """
  182. def toSegments(cwd, path):
  183. """
  184. Normalize a path, as represented by a list of strings each
  185. representing one segment of the path.
  186. """
  187. if path.startswith('/'):
  188. segs = []
  189. else:
  190. segs = cwd[:]
  191. for s in path.split('/'):
  192. if s == '.' or s == '':
  193. continue
  194. elif s == '..':
  195. if segs:
  196. segs.pop()
  197. else:
  198. raise InvalidPath(cwd, path)
  199. elif '\0' in s or '/' in s:
  200. raise InvalidPath(cwd, path)
  201. else:
  202. segs.append(s)
  203. return segs
  204. def errnoToFailure(e, path):
  205. """
  206. Map C{OSError} and C{IOError} to standard FTP errors.
  207. """
  208. if e == errno.ENOENT:
  209. return defer.fail(FileNotFoundError(path))
  210. elif e == errno.EACCES or e == errno.EPERM:
  211. return defer.fail(PermissionDeniedError(path))
  212. elif e == errno.ENOTDIR:
  213. return defer.fail(IsNotADirectoryError(path))
  214. elif e == errno.EEXIST:
  215. return defer.fail(FileExistsError(path))
  216. elif e == errno.EISDIR:
  217. return defer.fail(IsADirectoryError(path))
  218. else:
  219. return defer.fail()
  220. _testTranslation = fnmatch.translate('TEST')
  221. def _isGlobbingExpression(segments=None):
  222. """
  223. Helper for checking if a FTPShell `segments` contains a wildcard Unix
  224. expression.
  225. Only filename globbing is supported.
  226. This means that wildcards can only be presents in the last element of
  227. `segments`.
  228. @type segments: C{list}
  229. @param segments: List of path elements as used by the FTP server protocol.
  230. @rtype: Boolean
  231. @return: True if `segments` contains a globbing expression.
  232. """
  233. if not segments:
  234. return False
  235. # To check that something is a glob expression, we convert it to
  236. # Regular Expression.
  237. # We compare it to the translation of a known non-glob expression.
  238. # If the result is the same as the original expression then it contains no
  239. # globbing expression.
  240. globCandidate = segments[-1]
  241. globTranslations = fnmatch.translate(globCandidate)
  242. nonGlobTranslations = _testTranslation.replace('TEST', globCandidate, 1)
  243. if nonGlobTranslations == globTranslations:
  244. return False
  245. else:
  246. return True
  247. class FTPCmdError(Exception):
  248. """
  249. Generic exception for FTP commands.
  250. """
  251. def __init__(self, *msg):
  252. Exception.__init__(self, *msg)
  253. self.errorMessage = msg
  254. def response(self):
  255. """
  256. Generate a FTP response message for this error.
  257. """
  258. return RESPONSE[self.errorCode] % self.errorMessage
  259. class FileNotFoundError(FTPCmdError):
  260. """
  261. Raised when trying to access a non existent file or directory.
  262. """
  263. errorCode = FILE_NOT_FOUND
  264. class AnonUserDeniedError(FTPCmdError):
  265. """
  266. Raised when an anonymous user issues a command that will alter the
  267. filesystem
  268. """
  269. errorCode = ANON_USER_DENIED
  270. class PermissionDeniedError(FTPCmdError):
  271. """
  272. Raised when access is attempted to a resource to which access is
  273. not allowed.
  274. """
  275. errorCode = PERMISSION_DENIED
  276. class IsNotADirectoryError(FTPCmdError):
  277. """
  278. Raised when RMD is called on a path that isn't a directory.
  279. """
  280. errorCode = IS_NOT_A_DIR
  281. class FileExistsError(FTPCmdError):
  282. """
  283. Raised when attempted to override an existing resource.
  284. """
  285. errorCode = FILE_EXISTS
  286. class IsADirectoryError(FTPCmdError):
  287. """
  288. Raised when DELE is called on a path that is a directory.
  289. """
  290. errorCode = IS_A_DIR
  291. class CmdSyntaxError(FTPCmdError):
  292. """
  293. Raised when a command syntax is wrong.
  294. """
  295. errorCode = SYNTAX_ERR
  296. class CmdArgSyntaxError(FTPCmdError):
  297. """
  298. Raised when a command is called with wrong value or a wrong number of
  299. arguments.
  300. """
  301. errorCode = SYNTAX_ERR_IN_ARGS
  302. class CmdNotImplementedError(FTPCmdError):
  303. """
  304. Raised when an unimplemented command is given to the server.
  305. """
  306. errorCode = CMD_NOT_IMPLMNTD
  307. class CmdNotImplementedForArgError(FTPCmdError):
  308. """
  309. Raised when the handling of a parameter for a command is not implemented by
  310. the server.
  311. """
  312. errorCode = CMD_NOT_IMPLMNTD_FOR_PARAM
  313. class FTPError(Exception):
  314. pass
  315. class PortConnectionError(Exception):
  316. pass
  317. class BadCmdSequenceError(FTPCmdError):
  318. """
  319. Raised when a client sends a series of commands in an illogical sequence.
  320. """
  321. errorCode = BAD_CMD_SEQ
  322. class AuthorizationError(FTPCmdError):
  323. """
  324. Raised when client authentication fails.
  325. """
  326. errorCode = AUTH_FAILURE
  327. def debugDeferred(self, *_):
  328. log.msg('debugDeferred(): %s' % str(_), debug=True)
  329. # -- DTP Protocol --
  330. _months = [
  331. None,
  332. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  333. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  334. @implementer(interfaces.IConsumer)
  335. class DTP(protocol.Protocol, object):
  336. isConnected = False
  337. _cons = None
  338. _onConnLost = None
  339. _buffer = None
  340. _encoding = 'latin-1'
  341. def connectionMade(self):
  342. self.isConnected = True
  343. self.factory.deferred.callback(None)
  344. self._buffer = []
  345. def connectionLost(self, reason):
  346. self.isConnected = False
  347. if self._onConnLost is not None:
  348. self._onConnLost.callback(None)
  349. def sendLine(self, line):
  350. """
  351. Send a line to data channel.
  352. @param line: The line to be sent.
  353. @type line: L{bytes}
  354. """
  355. self.transport.write(line + b'\r\n')
  356. def _formatOneListResponse(self, name, size, directory, permissions,
  357. hardlinks, modified, owner, group):
  358. """
  359. Helper method to format one entry's info into a text entry like:
  360. 'drwxrwxrwx 0 user group 0 Jan 01 1970 filename.txt'
  361. @param name: C{bytes} name of the entry (file or directory or link)
  362. @param size: C{int} size of the entry
  363. @param directory: evals to C{bool} - whether the entry is a directory
  364. @param permissions: L{twisted.python.filepath.Permissions} object
  365. representing that entry's permissions
  366. @param hardlinks: C{int} number of hardlinks
  367. @param modified: C{float} - entry's last modified time in seconds
  368. since the epoch
  369. @param owner: C{str} username of the owner
  370. @param group: C{str} group name of the owner
  371. @return: C{str} in the requisite format
  372. """
  373. def formatDate(mtime):
  374. now = time.gmtime()
  375. info = {
  376. 'month': _months[mtime.tm_mon],
  377. 'day': mtime.tm_mday,
  378. 'year': mtime.tm_year,
  379. 'hour': mtime.tm_hour,
  380. 'minute': mtime.tm_min
  381. }
  382. if now.tm_year != mtime.tm_year:
  383. return '%(month)s %(day)02d %(year)5d' % info
  384. else:
  385. return '%(month)s %(day)02d %(hour)02d:%(minute)02d' % info
  386. format = ('%(directory)s%(permissions)s%(hardlinks)4d '
  387. '%(owner)-9s %(group)-9s %(size)15d %(date)12s '
  388. )
  389. msg = (format % {
  390. 'directory': directory and 'd' or '-',
  391. 'permissions': permissions.shorthand(),
  392. 'hardlinks': hardlinks,
  393. 'owner': owner[:8],
  394. 'group': group[:8],
  395. 'size': size,
  396. 'date': formatDate(time.gmtime(modified)),
  397. }).encode(self._encoding)
  398. return msg + name
  399. def sendListResponse(self, name, response):
  400. self.sendLine(self._formatOneListResponse(name, *response))
  401. # Proxy IConsumer to our transport
  402. def registerProducer(self, producer, streaming):
  403. return self.transport.registerProducer(producer, streaming)
  404. def unregisterProducer(self):
  405. self.transport.unregisterProducer()
  406. self.transport.loseConnection()
  407. def write(self, data):
  408. if self.isConnected:
  409. return self.transport.write(data)
  410. raise Exception("Crap damn crap damn crap damn")
  411. # Pretend to be a producer, too.
  412. def _conswrite(self, bytes):
  413. try:
  414. self._cons.write(bytes)
  415. except:
  416. self._onConnLost.errback()
  417. def dataReceived(self, bytes):
  418. if self._cons is not None:
  419. self._conswrite(bytes)
  420. else:
  421. self._buffer.append(bytes)
  422. def _unregConsumer(self, ignored):
  423. self._cons.unregisterProducer()
  424. self._cons = None
  425. del self._onConnLost
  426. return ignored
  427. def registerConsumer(self, cons):
  428. assert self._cons is None
  429. self._cons = cons
  430. self._cons.registerProducer(self, True)
  431. for chunk in self._buffer:
  432. self._conswrite(chunk)
  433. self._buffer = None
  434. if self.isConnected:
  435. self._onConnLost = d = defer.Deferred()
  436. d.addBoth(self._unregConsumer)
  437. return d
  438. else:
  439. self._cons.unregisterProducer()
  440. self._cons = None
  441. return defer.succeed(None)
  442. def resumeProducing(self):
  443. self.transport.resumeProducing()
  444. def pauseProducing(self):
  445. self.transport.pauseProducing()
  446. def stopProducing(self):
  447. self.transport.stopProducing()
  448. class DTPFactory(protocol.ClientFactory):
  449. """
  450. Client factory for I{data transfer process} protocols.
  451. @ivar peerCheck: perform checks to make sure the ftp-pi's peer is the same
  452. as the dtp's
  453. @ivar pi: a reference to this factory's protocol interpreter
  454. @ivar _state: Indicates the current state of the DTPFactory. Initially,
  455. this is L{_IN_PROGRESS}. If the connection fails or times out, it is
  456. L{_FAILED}. If the connection succeeds before the timeout, it is
  457. L{_FINISHED}.
  458. @cvar _IN_PROGRESS: Token to signal that connection is active.
  459. @type _IN_PROGRESS: L{object}.
  460. @cvar _FAILED: Token to signal that connection has failed.
  461. @type _FAILED: L{object}.
  462. @cvar _FINISHED: Token to signal that connection was successfully closed.
  463. @type _FINISHED: L{object}.
  464. """
  465. _IN_PROGRESS = object()
  466. _FAILED = object()
  467. _FINISHED = object()
  468. _state = _IN_PROGRESS
  469. # -- configuration variables --
  470. peerCheck = False
  471. # -- class variables --
  472. def __init__(self, pi, peerHost=None, reactor=None):
  473. """
  474. Constructor
  475. @param pi: this factory's protocol interpreter
  476. @param peerHost: if peerCheck is True, this is the tuple that the
  477. generated instance will use to perform security checks
  478. """
  479. self.pi = pi
  480. self.peerHost = peerHost # from FTP.transport.peerHost()
  481. # deferred will fire when instance is connected
  482. self.deferred = defer.Deferred()
  483. self.delayedCall = None
  484. if reactor is None:
  485. from twisted.internet import reactor
  486. self._reactor = reactor
  487. def buildProtocol(self, addr):
  488. log.msg('DTPFactory.buildProtocol', debug=True)
  489. if self._state is not self._IN_PROGRESS:
  490. return None
  491. self._state = self._FINISHED
  492. self.cancelTimeout()
  493. p = DTP()
  494. p.factory = self
  495. p.pi = self.pi
  496. self.pi.dtpInstance = p
  497. return p
  498. def stopFactory(self):
  499. log.msg('dtpFactory.stopFactory', debug=True)
  500. self.cancelTimeout()
  501. def timeoutFactory(self):
  502. log.msg('timed out waiting for DTP connection')
  503. if self._state is not self._IN_PROGRESS:
  504. return
  505. self._state = self._FAILED
  506. d = self.deferred
  507. self.deferred = None
  508. d.errback(
  509. PortConnectionError(defer.TimeoutError("DTPFactory timeout")))
  510. def cancelTimeout(self):
  511. if self.delayedCall is not None and self.delayedCall.active():
  512. log.msg('cancelling DTP timeout', debug=True)
  513. self.delayedCall.cancel()
  514. def setTimeout(self, seconds):
  515. log.msg('DTPFactory.setTimeout set to %s seconds' % seconds)
  516. self.delayedCall = self._reactor.callLater(
  517. seconds, self.timeoutFactory)
  518. def clientConnectionFailed(self, connector, reason):
  519. if self._state is not self._IN_PROGRESS:
  520. return
  521. self._state = self._FAILED
  522. d = self.deferred
  523. self.deferred = None
  524. d.errback(PortConnectionError(reason))
  525. # -- FTP-PI (Protocol Interpreter) --
  526. class ASCIIConsumerWrapper(object):
  527. def __init__(self, cons):
  528. self.cons = cons
  529. self.registerProducer = cons.registerProducer
  530. self.unregisterProducer = cons.unregisterProducer
  531. assert os.linesep == "\r\n" or len(os.linesep) == 1, (
  532. "Unsupported platform (yea right like this even exists)")
  533. if os.linesep == "\r\n":
  534. self.write = cons.write
  535. def write(self, bytes):
  536. return self.cons.write(bytes.replace(os.linesep, "\r\n"))
  537. @implementer(interfaces.IConsumer)
  538. class FileConsumer(object):
  539. """
  540. A consumer for FTP input that writes data to a file.
  541. @ivar fObj: a file object opened for writing, used to write data received.
  542. @type fObj: C{file}
  543. """
  544. def __init__(self, fObj):
  545. self.fObj = fObj
  546. def registerProducer(self, producer, streaming):
  547. self.producer = producer
  548. assert streaming
  549. def unregisterProducer(self):
  550. self.producer = None
  551. self.fObj.close()
  552. def write(self, bytes):
  553. self.fObj.write(bytes)
  554. class FTPOverflowProtocol(basic.LineReceiver):
  555. """FTP mini-protocol for when there are too many connections."""
  556. _encoding = 'latin-1'
  557. def connectionMade(self):
  558. self.sendLine(RESPONSE[TOO_MANY_CONNECTIONS].encode(self._encoding))
  559. self.transport.loseConnection()
  560. class FTP(basic.LineReceiver, policies.TimeoutMixin, object):
  561. """
  562. Protocol Interpreter for the File Transfer Protocol
  563. @ivar state: The current server state. One of L{UNAUTH},
  564. L{INAUTH}, L{AUTHED}, L{RENAMING}.
  565. @ivar shell: The connected avatar
  566. @ivar binary: The transfer mode. If false, ASCII.
  567. @ivar dtpFactory: Generates a single DTP for this session
  568. @ivar dtpPort: Port returned from listenTCP
  569. @ivar listenFactory: A callable with the signature of
  570. L{twisted.internet.interfaces.IReactorTCP.listenTCP} which will be used
  571. to create Ports for passive connections (mainly for testing).
  572. @ivar passivePortRange: iterator used as source of passive port numbers.
  573. @type passivePortRange: C{iterator}
  574. @cvar UNAUTH: Command channel is not yet authenticated.
  575. @type UNAUTH: L{int}
  576. @cvar INAUTH: Command channel is in the process of being authenticated.
  577. @type INAUTH: L{int}
  578. @cvar AUTHED: Command channel was successfully authenticated.
  579. @type AUTHED: L{int}
  580. @cvar RENAMING: Command channel is between the renaming command sequence.
  581. @type RENAMING: L{int}
  582. """
  583. disconnected = False
  584. # States an FTP can be in
  585. UNAUTH, INAUTH, AUTHED, RENAMING = range(4)
  586. # how long the DTP waits for a connection
  587. dtpTimeout = 10
  588. portal = None
  589. shell = None
  590. dtpFactory = None
  591. dtpPort = None
  592. dtpInstance = None
  593. binary = True
  594. PUBLIC_COMMANDS = ['FEAT', 'QUIT']
  595. FEATURES = ['FEAT', 'MDTM', 'PASV', 'SIZE', 'TYPE A;I']
  596. passivePortRange = range(0, 1)
  597. listenFactory = reactor.listenTCP
  598. _encoding = 'latin-1'
  599. def reply(self, key, *args):
  600. msg = RESPONSE[key] % args
  601. self.sendLine(msg)
  602. def sendLine(self, line):
  603. """
  604. (Private) Encodes and sends a line
  605. @param line: L{bytes} or L{unicode}
  606. """
  607. if isinstance(line, unicode):
  608. line = line.encode(self._encoding)
  609. super(FTP, self).sendLine(line)
  610. def connectionMade(self):
  611. self.state = self.UNAUTH
  612. self.setTimeout(self.timeOut)
  613. self.reply(WELCOME_MSG, self.factory.welcomeMessage)
  614. def connectionLost(self, reason):
  615. # if we have a DTP protocol instance running and
  616. # we lose connection to the client's PI, kill the
  617. # DTP connection and close the port
  618. if self.dtpFactory:
  619. self.cleanupDTP()
  620. self.setTimeout(None)
  621. if hasattr(self.shell, 'logout') and self.shell.logout is not None:
  622. self.shell.logout()
  623. self.shell = None
  624. self.transport = None
  625. def timeoutConnection(self):
  626. self.transport.loseConnection()
  627. def lineReceived(self, line):
  628. self.resetTimeout()
  629. self.pauseProducing()
  630. if bytes != str:
  631. line = line.decode(self._encoding)
  632. def processFailed(err):
  633. if err.check(FTPCmdError):
  634. self.sendLine(err.value.response())
  635. elif (err.check(TypeError) and any((
  636. msg in err.value.args[0] for msg in (
  637. 'takes exactly', 'required positional argument')))):
  638. self.reply(SYNTAX_ERR, "%s requires an argument." % (cmd,))
  639. else:
  640. log.msg("Unexpected FTP error")
  641. log.err(err)
  642. self.reply(REQ_ACTN_NOT_TAKEN, "internal server error")
  643. def processSucceeded(result):
  644. if isinstance(result, tuple):
  645. self.reply(*result)
  646. elif result is not None:
  647. self.reply(result)
  648. def allDone(ignored):
  649. if not self.disconnected:
  650. self.resumeProducing()
  651. spaceIndex = line.find(' ')
  652. if spaceIndex != -1:
  653. cmd = line[:spaceIndex]
  654. args = (line[spaceIndex + 1:],)
  655. else:
  656. cmd = line
  657. args = ()
  658. d = defer.maybeDeferred(self.processCommand, cmd, *args)
  659. d.addCallbacks(processSucceeded, processFailed)
  660. d.addErrback(log.err)
  661. # XXX It burnsss
  662. # LineReceiver doesn't let you resumeProducing inside
  663. # lineReceived atm
  664. from twisted.internet import reactor
  665. reactor.callLater(0, d.addBoth, allDone)
  666. def processCommand(self, cmd, *params):
  667. def call_ftp_command(command):
  668. method = getattr(self, "ftp_" + command, None)
  669. if method is not None:
  670. return method(*params)
  671. return defer.fail(CmdNotImplementedError(command))
  672. cmd = cmd.upper()
  673. if cmd in self.PUBLIC_COMMANDS:
  674. return call_ftp_command(cmd)
  675. elif self.state == self.UNAUTH:
  676. if cmd == 'USER':
  677. return self.ftp_USER(*params)
  678. elif cmd == 'PASS':
  679. return BAD_CMD_SEQ, "USER required before PASS"
  680. else:
  681. return NOT_LOGGED_IN
  682. elif self.state == self.INAUTH:
  683. if cmd == 'PASS':
  684. return self.ftp_PASS(*params)
  685. else:
  686. return BAD_CMD_SEQ, "PASS required after USER"
  687. elif self.state == self.AUTHED:
  688. return call_ftp_command(cmd)
  689. elif self.state == self.RENAMING:
  690. if cmd == 'RNTO':
  691. return self.ftp_RNTO(*params)
  692. else:
  693. return BAD_CMD_SEQ, "RNTO required after RNFR"
  694. def getDTPPort(self, factory):
  695. """
  696. Return a port for passive access, using C{self.passivePortRange}
  697. attribute.
  698. """
  699. for portn in self.passivePortRange:
  700. try:
  701. dtpPort = self.listenFactory(portn, factory)
  702. except error.CannotListenError:
  703. continue
  704. else:
  705. return dtpPort
  706. raise error.CannotListenError(
  707. '', portn,
  708. "No port available in range %s" % (self.passivePortRange,))
  709. def ftp_USER(self, username):
  710. """
  711. First part of login. Get the username the peer wants to
  712. authenticate as.
  713. """
  714. if not username:
  715. return defer.fail(CmdSyntaxError('USER requires an argument'))
  716. self._user = username
  717. self.state = self.INAUTH
  718. if (self.factory.allowAnonymous and
  719. self._user == self.factory.userAnonymous):
  720. return GUEST_NAME_OK_NEED_EMAIL
  721. else:
  722. return (USR_NAME_OK_NEED_PASS, username)
  723. # TODO: add max auth try before timeout from ip...
  724. # TODO: need to implement minimal ABOR command
  725. def ftp_PASS(self, password):
  726. """
  727. Second part of login. Get the password the peer wants to
  728. authenticate with.
  729. """
  730. if (self.factory.allowAnonymous and
  731. self._user == self.factory.userAnonymous):
  732. # anonymous login
  733. creds = credentials.Anonymous()
  734. reply = GUEST_LOGGED_IN_PROCEED
  735. else:
  736. # user login
  737. creds = credentials.UsernamePassword(self._user, password)
  738. reply = USR_LOGGED_IN_PROCEED
  739. del self._user
  740. def _cbLogin(result):
  741. (interface, avatar, logout) = result
  742. assert interface is IFTPShell, "The realm is busted, jerk."
  743. self.shell = avatar
  744. self.logout = logout
  745. self.workingDirectory = []
  746. self.state = self.AUTHED
  747. return reply
  748. def _ebLogin(failure):
  749. failure.trap(
  750. cred_error.UnauthorizedLogin, cred_error.UnhandledCredentials)
  751. self.state = self.UNAUTH
  752. raise AuthorizationError
  753. d = self.portal.login(creds, None, IFTPShell)
  754. d.addCallbacks(_cbLogin, _ebLogin)
  755. return d
  756. def ftp_PASV(self):
  757. """
  758. Request for a passive connection
  759. from the rfc::
  760. This command requests the server-DTP to \"listen\" on a data port
  761. (which is not its default data port) and to wait for a connection
  762. rather than initiate one upon receipt of a transfer command. The
  763. response to this command includes the host and port address this
  764. server is listening on.
  765. """
  766. # if we have a DTP port set up, lose it.
  767. if self.dtpFactory is not None:
  768. # cleanupDTP sets dtpFactory to none. Later we'll do
  769. # cleanup here or something.
  770. self.cleanupDTP()
  771. self.dtpFactory = DTPFactory(pi=self)
  772. self.dtpFactory.setTimeout(self.dtpTimeout)
  773. self.dtpPort = self.getDTPPort(self.dtpFactory)
  774. host = self.transport.getHost().host
  775. port = self.dtpPort.getHost().port
  776. self.reply(ENTERING_PASV_MODE, encodeHostPort(host, port))
  777. return self.dtpFactory.deferred.addCallback(lambda ign: None)
  778. def ftp_PORT(self, address):
  779. addr = tuple(map(int, address.split(',')))
  780. ip = '%d.%d.%d.%d' % tuple(addr[:4])
  781. port = addr[4] << 8 | addr[5]
  782. # if we have a DTP port set up, lose it.
  783. if self.dtpFactory is not None:
  784. self.cleanupDTP()
  785. self.dtpFactory = DTPFactory(
  786. pi=self, peerHost=self.transport.getPeer().host)
  787. self.dtpFactory.setTimeout(self.dtpTimeout)
  788. self.dtpPort = reactor.connectTCP(ip, port, self.dtpFactory)
  789. def connected(ignored):
  790. return ENTERING_PORT_MODE
  791. def connFailed(err):
  792. err.trap(PortConnectionError)
  793. return CANT_OPEN_DATA_CNX
  794. return self.dtpFactory.deferred.addCallbacks(connected, connFailed)
  795. def _encodeName(self, name):
  796. """
  797. Encode C{name} to be sent over the wire.
  798. This encodes L{unicode} objects as UTF-8 and leaves L{bytes} as-is.
  799. As described by U{RFC 3659 section
  800. 2.2<https://tools.ietf.org/html/rfc3659#section-2.2>}::
  801. Various FTP commands take pathnames as arguments, or return
  802. pathnames in responses. When the MLST command is supported, as
  803. indicated in the response to the FEAT command, pathnames are to be
  804. transferred in one of the following two formats.
  805. pathname = utf-8-name / raw
  806. utf-8-name = <a UTF-8 encoded Unicode string>
  807. raw = <any string that is not a valid UTF-8 encoding>
  808. Which format is used is at the option of the user-PI or server-PI
  809. sending the pathname.
  810. @param name: Name to be encoded.
  811. @type name: L{bytes} or L{unicode}
  812. @return: Wire format of C{name}.
  813. @rtype: L{bytes}
  814. """
  815. if isinstance(name, unicode):
  816. return name.encode('utf-8')
  817. return name
  818. def ftp_LIST(self, path=''):
  819. """ This command causes a list to be sent from the server to the
  820. passive DTP. If the pathname specifies a directory or other
  821. group of files, the server should transfer a list of files
  822. in the specified directory. If the pathname specifies a
  823. file then the server should send current information on the
  824. file. A null argument implies the user's current working or
  825. default directory.
  826. """
  827. # XXX: why is this check different from ftp_RETR/ftp_STOR? See #4180
  828. if self.dtpInstance is None or not self.dtpInstance.isConnected:
  829. return defer.fail(
  830. BadCmdSequenceError('must send PORT or PASV before RETR'))
  831. # Various clients send flags like -L or -al etc. We just ignore them.
  832. if path.lower() in ['-a', '-l', '-la', '-al']:
  833. path = ''
  834. def gotListing(results):
  835. self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
  836. for (name, attrs) in results:
  837. name = self._encodeName(name)
  838. self.dtpInstance.sendListResponse(name, attrs)
  839. self.dtpInstance.transport.loseConnection()
  840. return (TXFR_COMPLETE_OK,)
  841. try:
  842. segments = toSegments(self.workingDirectory, path)
  843. except InvalidPath:
  844. return defer.fail(FileNotFoundError(path))
  845. d = self.shell.list(
  846. segments,
  847. ('size', 'directory', 'permissions', 'hardlinks',
  848. 'modified', 'owner', 'group'))
  849. d.addCallback(gotListing)
  850. return d
  851. def ftp_NLST(self, path):
  852. """
  853. This command causes a directory listing to be sent from the server to
  854. the client. The pathname should specify a directory or other
  855. system-specific file group descriptor. An empty path implies the
  856. current working directory. If the path is non-existent, send nothing.
  857. If the path is to a file, send only the file name.
  858. @type path: C{str}
  859. @param path: The path for which a directory listing should be returned.
  860. @rtype: L{Deferred}
  861. @return: a L{Deferred} which will be fired when the listing request
  862. is finished.
  863. """
  864. # XXX: why is this check different from ftp_RETR/ftp_STOR? See #4180
  865. if self.dtpInstance is None or not self.dtpInstance.isConnected:
  866. return defer.fail(
  867. BadCmdSequenceError('must send PORT or PASV before RETR'))
  868. try:
  869. segments = toSegments(self.workingDirectory, path)
  870. except InvalidPath:
  871. return defer.fail(FileNotFoundError(path))
  872. def cbList(results, glob):
  873. """
  874. Send, line by line, each matching file in the directory listing,
  875. and then close the connection.
  876. @type results: A C{list} of C{tuple}. The first element of each
  877. C{tuple} is a C{str} and the second element is a C{list}.
  878. @param results: The names of the files in the directory.
  879. @param glob: A shell-style glob through which to filter results
  880. (see U{http://docs.python.org/2/library/fnmatch.html}), or
  881. L{None} for no filtering.
  882. @type glob: L{str} or L{None}
  883. @return: A C{tuple} containing the status code for a successful
  884. transfer.
  885. @rtype: C{tuple}
  886. """
  887. self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
  888. for (name, ignored) in results:
  889. if not glob or (glob and fnmatch.fnmatch(name, glob)):
  890. name = self._encodeName(name)
  891. self.dtpInstance.sendLine(name)
  892. self.dtpInstance.transport.loseConnection()
  893. return (TXFR_COMPLETE_OK,)
  894. def listErr(results):
  895. """
  896. RFC 959 specifies that an NLST request may only return directory
  897. listings. Thus, send nothing and just close the connection.
  898. @type results: L{Failure}
  899. @param results: The L{Failure} wrapping a L{FileNotFoundError} that
  900. occurred while trying to list the contents of a nonexistent
  901. directory.
  902. @returns: A C{tuple} containing the status code for a successful
  903. transfer.
  904. @rtype: C{tuple}
  905. """
  906. self.dtpInstance.transport.loseConnection()
  907. return (TXFR_COMPLETE_OK,)
  908. if _isGlobbingExpression(segments):
  909. # Remove globbing expression from path
  910. # and keep to be used for filtering.
  911. glob = segments.pop()
  912. else:
  913. glob = None
  914. d = self.shell.list(segments)
  915. d.addCallback(cbList, glob)
  916. # self.shell.list will generate an error if the path is invalid
  917. d.addErrback(listErr)
  918. return d
  919. def ftp_CWD(self, path):
  920. try:
  921. segments = toSegments(self.workingDirectory, path)
  922. except InvalidPath:
  923. # XXX Eh, what to fail with here?
  924. return defer.fail(FileNotFoundError(path))
  925. def accessGranted(result):
  926. self.workingDirectory = segments
  927. return (REQ_FILE_ACTN_COMPLETED_OK,)
  928. return self.shell.access(segments).addCallback(accessGranted)
  929. def ftp_CDUP(self):
  930. return self.ftp_CWD('..')
  931. def ftp_PWD(self):
  932. return (PWD_REPLY, '/' + '/'.join(self.workingDirectory))
  933. def ftp_RETR(self, path):
  934. """
  935. This command causes the content of a file to be sent over the data
  936. transfer channel. If the path is to a folder, an error will be raised.
  937. @type path: C{str}
  938. @param path: The path to the file which should be transferred over the
  939. data transfer channel.
  940. @rtype: L{Deferred}
  941. @return: a L{Deferred} which will be fired when the transfer is done.
  942. """
  943. if self.dtpInstance is None:
  944. raise BadCmdSequenceError('PORT or PASV required before RETR')
  945. try:
  946. newsegs = toSegments(self.workingDirectory, path)
  947. except InvalidPath:
  948. return defer.fail(FileNotFoundError(path))
  949. # XXX For now, just disable the timeout. Later we'll want to
  950. # leave it active and have the DTP connection reset it
  951. # periodically.
  952. self.setTimeout(None)
  953. # Put it back later
  954. def enableTimeout(result):
  955. self.setTimeout(self.factory.timeOut)
  956. return result
  957. # And away she goes
  958. if not self.binary:
  959. cons = ASCIIConsumerWrapper(self.dtpInstance)
  960. else:
  961. cons = self.dtpInstance
  962. def cbSent(result):
  963. return (TXFR_COMPLETE_OK,)
  964. def ebSent(err):
  965. log.msg("Unexpected error attempting to transmit file to client:")
  966. log.err(err)
  967. if err.check(FTPCmdError):
  968. return err
  969. return (CNX_CLOSED_TXFR_ABORTED,)
  970. def cbOpened(file):
  971. # Tell them what to doooo
  972. if self.dtpInstance.isConnected:
  973. self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
  974. else:
  975. self.reply(FILE_STATUS_OK_OPEN_DATA_CNX)
  976. d = file.send(cons)
  977. d.addCallbacks(cbSent, ebSent)
  978. return d
  979. def ebOpened(err):
  980. if not err.check(
  981. PermissionDeniedError, FileNotFoundError,
  982. IsADirectoryError):
  983. log.msg(
  984. "Unexpected error attempting to open file for "
  985. "transmission:")
  986. log.err(err)
  987. if err.check(FTPCmdError):
  988. return (err.value.errorCode, '/'.join(newsegs))
  989. return (FILE_NOT_FOUND, '/'.join(newsegs))
  990. d = self.shell.openForReading(newsegs)
  991. d.addCallbacks(cbOpened, ebOpened)
  992. d.addBoth(enableTimeout)
  993. # Pass back Deferred that fires when the transfer is done
  994. return d
  995. def ftp_STOR(self, path):
  996. """
  997. STORE (STOR)
  998. This command causes the server-DTP to accept the data
  999. transferred via the data connection and to store the data as
  1000. a file at the server site. If the file specified in the
  1001. pathname exists at the server site, then its contents shall
  1002. be replaced by the data being transferred. A new file is
  1003. created at the server site if the file specified in the
  1004. pathname does not already exist.
  1005. """
  1006. if self.dtpInstance is None:
  1007. raise BadCmdSequenceError('PORT or PASV required before STOR')
  1008. try:
  1009. newsegs = toSegments(self.workingDirectory, path)
  1010. except InvalidPath:
  1011. return defer.fail(FileNotFoundError(path))
  1012. # XXX For now, just disable the timeout. Later we'll want to
  1013. # leave it active and have the DTP connection reset it
  1014. # periodically.
  1015. self.setTimeout(None)
  1016. # Put it back later
  1017. def enableTimeout(result):
  1018. self.setTimeout(self.factory.timeOut)
  1019. return result
  1020. def cbOpened(file):
  1021. """
  1022. File was open for reading. Launch the data transfer channel via
  1023. the file consumer.
  1024. """
  1025. d = file.receive()
  1026. d.addCallback(cbConsumer)
  1027. d.addCallback(lambda ignored: file.close())
  1028. d.addCallbacks(cbSent, ebSent)
  1029. return d
  1030. def ebOpened(err):
  1031. """
  1032. Called when failed to open the file for reading.
  1033. For known errors, return the FTP error code.
  1034. For all other, return a file not found error.
  1035. """
  1036. if isinstance(err.value, FTPCmdError):
  1037. return (err.value.errorCode, '/'.join(newsegs))
  1038. log.err(err, "Unexpected error received while opening file:")
  1039. return (FILE_NOT_FOUND, '/'.join(newsegs))
  1040. def cbConsumer(cons):
  1041. """
  1042. Called after the file was opended for reading.
  1043. Prepare the data transfer channel and send the response
  1044. to the command channel.
  1045. """
  1046. if not self.binary:
  1047. cons = ASCIIConsumerWrapper(cons)
  1048. d = self.dtpInstance.registerConsumer(cons)
  1049. # Tell them what to doooo
  1050. if self.dtpInstance.isConnected:
  1051. self.reply(DATA_CNX_ALREADY_OPEN_START_XFR)
  1052. else:
  1053. self.reply(FILE_STATUS_OK_OPEN_DATA_CNX)
  1054. return d
  1055. def cbSent(result):
  1056. """
  1057. Called from data transport when tranfer is done.
  1058. """
  1059. return (TXFR_COMPLETE_OK,)
  1060. def ebSent(err):
  1061. """
  1062. Called from data transport when there are errors during the
  1063. transfer.
  1064. """
  1065. log.err(err, "Unexpected error received during transfer:")
  1066. if err.check(FTPCmdError):
  1067. return err
  1068. return (CNX_CLOSED_TXFR_ABORTED,)
  1069. d = self.shell.openForWriting(newsegs)
  1070. d.addCallbacks(cbOpened, ebOpened)
  1071. d.addBoth(enableTimeout)
  1072. # Pass back Deferred that fires when the transfer is done
  1073. return d
  1074. def ftp_SIZE(self, path):
  1075. """
  1076. File SIZE
  1077. The FTP command, SIZE OF FILE (SIZE), is used to obtain the transfer
  1078. size of a file from the server-FTP process. This is the exact number
  1079. of octets (8 bit bytes) that would be transmitted over the data
  1080. connection should that file be transmitted. This value will change
  1081. depending on the current STRUcture, MODE, and TYPE of the data
  1082. connection or of a data connection that would be created were one
  1083. created now. Thus, the result of the SIZE command is dependent on
  1084. the currently established STRU, MODE, and TYPE parameters.
  1085. The SIZE command returns how many octets would be transferred if the
  1086. file were to be transferred using the current transfer structure,
  1087. mode, and type. This command is normally used in conjunction with
  1088. the RESTART (REST) command when STORing a file to a remote server in
  1089. STREAM mode, to determine the restart point. The server-PI might
  1090. need to read the partially transferred file, do any appropriate
  1091. conversion, and count the number of octets that would be generated
  1092. when sending the file in order to correctly respond to this command.
  1093. Estimates of the file transfer size MUST NOT be returned; only
  1094. precise information is acceptable.
  1095. http://tools.ietf.org/html/rfc3659
  1096. """
  1097. try:
  1098. newsegs = toSegments(self.workingDirectory, path)
  1099. except InvalidPath:
  1100. return defer.fail(FileNotFoundError(path))
  1101. def cbStat(result):
  1102. (size,) = result
  1103. return (FILE_STATUS, str(size))
  1104. return self.shell.stat(newsegs, ('size',)).addCallback(cbStat)
  1105. def ftp_MDTM(self, path):
  1106. """
  1107. File Modification Time (MDTM)
  1108. The FTP command, MODIFICATION TIME (MDTM), can be used to determine
  1109. when a file in the server NVFS was last modified. This command has
  1110. existed in many FTP servers for many years, as an adjunct to the REST
  1111. command for STREAM mode, thus is widely available. However, where
  1112. supported, the "modify" fact that can be provided in the result from
  1113. the new MLST command is recommended as a superior alternative.
  1114. http://tools.ietf.org/html/rfc3659
  1115. """
  1116. try:
  1117. newsegs = toSegments(self.workingDirectory, path)
  1118. except InvalidPath:
  1119. return defer.fail(FileNotFoundError(path))
  1120. def cbStat(result):
  1121. (modified,) = result
  1122. return (
  1123. FILE_STATUS,
  1124. time.strftime('%Y%m%d%H%M%S', time.gmtime(modified)))
  1125. return self.shell.stat(newsegs, ('modified',)).addCallback(cbStat)
  1126. def ftp_TYPE(self, type):
  1127. """
  1128. REPRESENTATION TYPE (TYPE)
  1129. The argument specifies the representation type as described
  1130. in the Section on Data Representation and Storage. Several
  1131. types take a second parameter. The first parameter is
  1132. denoted by a single Telnet character, as is the second
  1133. Format parameter for ASCII and EBCDIC; the second parameter
  1134. for local byte is a decimal integer to indicate Bytesize.
  1135. The parameters are separated by a <SP> (Space, ASCII code
  1136. 32).
  1137. """
  1138. p = type.upper()
  1139. if p:
  1140. f = getattr(self, 'type_' + p[0], None)
  1141. if f is not None:
  1142. return f(p[1:])
  1143. return self.type_UNKNOWN(p)
  1144. return (SYNTAX_ERR,)
  1145. def type_A(self, code):
  1146. if code == '' or code == 'N':
  1147. self.binary = False
  1148. return (TYPE_SET_OK, 'A' + code)
  1149. else:
  1150. return defer.fail(CmdArgSyntaxError(code))
  1151. def type_I(self, code):
  1152. if code == '':
  1153. self.binary = True
  1154. return (TYPE_SET_OK, 'I')
  1155. else:
  1156. return defer.fail(CmdArgSyntaxError(code))
  1157. def type_UNKNOWN(self, code):
  1158. return defer.fail(CmdNotImplementedForArgError(code))
  1159. def ftp_SYST(self):
  1160. return NAME_SYS_TYPE
  1161. def ftp_STRU(self, structure):
  1162. p = structure.upper()
  1163. if p == 'F':
  1164. return (CMD_OK,)
  1165. return defer.fail(CmdNotImplementedForArgError(structure))
  1166. def ftp_MODE(self, mode):
  1167. p = mode.upper()
  1168. if p == 'S':
  1169. return (CMD_OK,)
  1170. return defer.fail(CmdNotImplementedForArgError(mode))
  1171. def ftp_MKD(self, path):
  1172. try:
  1173. newsegs = toSegments(self.workingDirectory, path)
  1174. except InvalidPath:
  1175. return defer.fail(FileNotFoundError(path))
  1176. return self.shell.makeDirectory(newsegs).addCallback(
  1177. lambda ign: (MKD_REPLY, path))
  1178. def ftp_RMD(self, path):
  1179. try:
  1180. newsegs = toSegments(self.workingDirectory, path)
  1181. except InvalidPath:
  1182. return defer.fail(FileNotFoundError(path))
  1183. return self.shell.removeDirectory(newsegs).addCallback(
  1184. lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,))
  1185. def ftp_DELE(self, path):
  1186. try:
  1187. newsegs = toSegments(self.workingDirectory, path)
  1188. except InvalidPath:
  1189. return defer.fail(FileNotFoundError(path))
  1190. return self.shell.removeFile(newsegs).addCallback(
  1191. lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,))
  1192. def ftp_NOOP(self):
  1193. return (CMD_OK,)
  1194. def ftp_RNFR(self, fromName):
  1195. self._fromName = fromName
  1196. self.state = self.RENAMING
  1197. return (REQ_FILE_ACTN_PENDING_FURTHER_INFO,)
  1198. def ftp_RNTO(self, toName):
  1199. fromName = self._fromName
  1200. del self._fromName
  1201. self.state = self.AUTHED
  1202. try:
  1203. fromsegs = toSegments(self.workingDirectory, fromName)
  1204. tosegs = toSegments(self.workingDirectory, toName)
  1205. except InvalidPath:
  1206. return defer.fail(FileNotFoundError(fromName))
  1207. return self.shell.rename(fromsegs, tosegs).addCallback(
  1208. lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,))
  1209. def ftp_FEAT(self):
  1210. """
  1211. Advertise the features supported by the server.
  1212. http://tools.ietf.org/html/rfc2389
  1213. """
  1214. self.sendLine(RESPONSE[FEAT_OK][0])
  1215. for feature in self.FEATURES:
  1216. self.sendLine(' ' + feature)
  1217. self.sendLine(RESPONSE[FEAT_OK][1])
  1218. def ftp_OPTS(self, option):
  1219. """
  1220. Handle OPTS command.
  1221. http://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00
  1222. """
  1223. return self.reply(OPTS_NOT_IMPLEMENTED, option)
  1224. def ftp_QUIT(self):
  1225. self.reply(GOODBYE_MSG)
  1226. self.transport.loseConnection()
  1227. self.disconnected = True
  1228. def cleanupDTP(self):
  1229. """
  1230. Call when DTP connection exits
  1231. """
  1232. log.msg('cleanupDTP', debug=True)
  1233. log.msg(self.dtpPort)
  1234. dtpPort, self.dtpPort = self.dtpPort, None
  1235. if interfaces.IListeningPort.providedBy(dtpPort):
  1236. dtpPort.stopListening()
  1237. elif interfaces.IConnector.providedBy(dtpPort):
  1238. dtpPort.disconnect()
  1239. else:
  1240. assert False, (
  1241. "dtpPort should be an IListeningPort or IConnector, "
  1242. "instead is %r" % (dtpPort,))
  1243. self.dtpFactory.stopFactory()
  1244. self.dtpFactory = None
  1245. if self.dtpInstance is not None:
  1246. self.dtpInstance = None
  1247. class FTPFactory(policies.LimitTotalConnectionsFactory):
  1248. """
  1249. A factory for producing ftp protocol instances
  1250. @ivar timeOut: the protocol interpreter's idle timeout time in seconds,
  1251. default is 600 seconds.
  1252. @ivar passivePortRange: value forwarded to C{protocol.passivePortRange}.
  1253. @type passivePortRange: C{iterator}
  1254. """
  1255. protocol = FTP
  1256. overflowProtocol = FTPOverflowProtocol
  1257. allowAnonymous = True
  1258. userAnonymous = 'anonymous'
  1259. timeOut = 600
  1260. welcomeMessage = "Twisted %s FTP Server" % (copyright.version,)
  1261. passivePortRange = range(0, 1)
  1262. def __init__(self, portal=None, userAnonymous='anonymous'):
  1263. self.portal = portal
  1264. self.userAnonymous = userAnonymous
  1265. self.instances = []
  1266. def buildProtocol(self, addr):
  1267. p = policies.LimitTotalConnectionsFactory.buildProtocol(self, addr)
  1268. if p is not None:
  1269. p.wrappedProtocol.portal = self.portal
  1270. p.wrappedProtocol.timeOut = self.timeOut
  1271. p.wrappedProtocol.passivePortRange = self.passivePortRange
  1272. return p
  1273. def stopFactory(self):
  1274. # make sure ftp instance's timeouts are set to None
  1275. # to avoid reactor complaints
  1276. [p.setTimeout(None) for p in self.instances if p.timeOut is not None]
  1277. policies.LimitTotalConnectionsFactory.stopFactory(self)
  1278. # -- Cred Objects --
  1279. class IFTPShell(Interface):
  1280. """
  1281. An abstraction of the shell commands used by the FTP protocol for
  1282. a given user account.
  1283. All path names must be absolute.
  1284. """
  1285. def makeDirectory(path):
  1286. """
  1287. Create a directory.
  1288. @param path: The path, as a list of segments, to create
  1289. @type path: C{list} of C{unicode}
  1290. @return: A Deferred which fires when the directory has been
  1291. created, or which fails if the directory cannot be created.
  1292. """
  1293. def removeDirectory(path):
  1294. """
  1295. Remove a directory.
  1296. @param path: The path, as a list of segments, to remove
  1297. @type path: C{list} of C{unicode}
  1298. @return: A Deferred which fires when the directory has been
  1299. removed, or which fails if the directory cannot be removed.
  1300. """
  1301. def removeFile(path):
  1302. """
  1303. Remove a file.
  1304. @param path: The path, as a list of segments, to remove
  1305. @type path: C{list} of C{unicode}
  1306. @return: A Deferred which fires when the file has been
  1307. removed, or which fails if the file cannot be removed.
  1308. """
  1309. def rename(fromPath, toPath):
  1310. """
  1311. Rename a file or directory.
  1312. @param fromPath: The current name of the path.
  1313. @type fromPath: C{list} of C{unicode}
  1314. @param toPath: The desired new name of the path.
  1315. @type toPath: C{list} of C{unicode}
  1316. @return: A Deferred which fires when the path has been
  1317. renamed, or which fails if the path cannot be renamed.
  1318. """
  1319. def access(path):
  1320. """
  1321. Determine whether access to the given path is allowed.
  1322. @param path: The path, as a list of segments
  1323. @return: A Deferred which fires with None if access is allowed
  1324. or which fails with a specific exception type if access is
  1325. denied.
  1326. """
  1327. def stat(path, keys=()):
  1328. """
  1329. Retrieve information about the given path.
  1330. This is like list, except it will never return results about
  1331. child paths.
  1332. """
  1333. def list(path, keys=()):
  1334. """
  1335. Retrieve information about the given path.
  1336. If the path represents a non-directory, the result list should
  1337. have only one entry with information about that non-directory.
  1338. Otherwise, the result list should have an element for each
  1339. child of the directory.
  1340. @param path: The path, as a list of segments, to list
  1341. @type path: C{list} of C{unicode} or C{bytes}
  1342. @param keys: A tuple of keys desired in the resulting
  1343. dictionaries.
  1344. @return: A Deferred which fires with a list of (name, list),
  1345. where the name is the name of the entry as a unicode string or
  1346. bytes and each list contains values corresponding to the requested
  1347. keys. The following are possible elements of keys, and the
  1348. values which should be returned for them:
  1349. - C{'size'}: size in bytes, as an integer (this is kinda required)
  1350. - C{'directory'}: boolean indicating the type of this entry
  1351. - C{'permissions'}: a bitvector (see os.stat(foo).st_mode)
  1352. - C{'hardlinks'}: Number of hard links to this entry
  1353. - C{'modified'}: number of seconds since the epoch since entry was
  1354. modified
  1355. - C{'owner'}: string indicating the user owner of this entry
  1356. - C{'group'}: string indicating the group owner of this entry
  1357. """
  1358. def openForReading(path):
  1359. """
  1360. @param path: The path, as a list of segments, to open
  1361. @type path: C{list} of C{unicode}
  1362. @rtype: C{Deferred} which will fire with L{IReadFile}
  1363. """
  1364. def openForWriting(path):
  1365. """
  1366. @param path: The path, as a list of segments, to open
  1367. @type path: C{list} of C{unicode}
  1368. @rtype: C{Deferred} which will fire with L{IWriteFile}
  1369. """
  1370. class IReadFile(Interface):
  1371. """
  1372. A file out of which bytes may be read.
  1373. """
  1374. def send(consumer):
  1375. """
  1376. Produce the contents of the given path to the given consumer. This
  1377. method may only be invoked once on each provider.
  1378. @type consumer: C{IConsumer}
  1379. @return: A Deferred which fires when the file has been
  1380. consumed completely.
  1381. """
  1382. class IWriteFile(Interface):
  1383. """
  1384. A file into which bytes may be written.
  1385. """
  1386. def receive():
  1387. """
  1388. Create a consumer which will write to this file. This method may
  1389. only be invoked once on each provider.
  1390. @rtype: C{Deferred} of C{IConsumer}
  1391. """
  1392. def close():
  1393. """
  1394. Perform any post-write work that needs to be done. This method may
  1395. only be invoked once on each provider, and will always be invoked
  1396. after receive().
  1397. @rtype: C{Deferred} of anything: the value is ignored. The FTP client
  1398. will not see their upload request complete until this Deferred has
  1399. been fired.
  1400. """
  1401. def _getgroups(uid):
  1402. """
  1403. Return the primary and supplementary groups for the given UID.
  1404. @type uid: C{int}
  1405. """
  1406. result = []
  1407. pwent = pwd.getpwuid(uid)
  1408. result.append(pwent.pw_gid)
  1409. for grent in grp.getgrall():
  1410. if pwent.pw_name in grent.gr_mem:
  1411. result.append(grent.gr_gid)
  1412. return result
  1413. def _testPermissions(uid, gid, spath, mode='r'):
  1414. """
  1415. checks to see if uid has proper permissions to access path with mode
  1416. @type uid: C{int}
  1417. @param uid: numeric user id
  1418. @type gid: C{int}
  1419. @param gid: numeric group id
  1420. @type spath: C{str}
  1421. @param spath: the path on the server to test
  1422. @type mode: C{str}
  1423. @param mode: 'r' or 'w' (read or write)
  1424. @rtype: C{bool}
  1425. @return: True if the given credentials have the specified form of
  1426. access to the given path
  1427. """
  1428. if mode == 'r':
  1429. usr = stat.S_IRUSR
  1430. grp = stat.S_IRGRP
  1431. oth = stat.S_IROTH
  1432. amode = os.R_OK
  1433. elif mode == 'w':
  1434. usr = stat.S_IWUSR
  1435. grp = stat.S_IWGRP
  1436. oth = stat.S_IWOTH
  1437. amode = os.W_OK
  1438. else:
  1439. raise ValueError("Invalid mode %r: must specify 'r' or 'w'" % (mode,))
  1440. access = False
  1441. if os.path.exists(spath):
  1442. if uid == 0:
  1443. access = True
  1444. else:
  1445. s = os.stat(spath)
  1446. if usr & s.st_mode and uid == s.st_uid:
  1447. access = True
  1448. elif grp & s.st_mode and gid in _getgroups(uid):
  1449. access = True
  1450. elif oth & s.st_mode:
  1451. access = True
  1452. if access:
  1453. if not os.access(spath, amode):
  1454. access = False
  1455. log.msg(
  1456. "Filesystem grants permission to UID %d but it is "
  1457. "inaccessible to me running as UID %d" % (
  1458. uid, os.getuid()))
  1459. return access
  1460. @implementer(IFTPShell)
  1461. class FTPAnonymousShell(object):
  1462. """
  1463. An anonymous implementation of IFTPShell
  1464. @type filesystemRoot: L{twisted.python.filepath.FilePath}
  1465. @ivar filesystemRoot: The path which is considered the root of
  1466. this shell.
  1467. """
  1468. def __init__(self, filesystemRoot):
  1469. self.filesystemRoot = filesystemRoot
  1470. def _path(self, path):
  1471. return self.filesystemRoot.descendant(path)
  1472. def makeDirectory(self, path):
  1473. return defer.fail(AnonUserDeniedError())
  1474. def removeDirectory(self, path):
  1475. return defer.fail(AnonUserDeniedError())
  1476. def removeFile(self, path):
  1477. return defer.fail(AnonUserDeniedError())
  1478. def rename(self, fromPath, toPath):
  1479. return defer.fail(AnonUserDeniedError())
  1480. def receive(self, path):
  1481. path = self._path(path)
  1482. return defer.fail(AnonUserDeniedError())
  1483. def openForReading(self, path):
  1484. """
  1485. Open C{path} for reading.
  1486. @param path: The path, as a list of segments, to open.
  1487. @type path: C{list} of C{unicode}
  1488. @return: A L{Deferred} is returned that will fire with an object
  1489. implementing L{IReadFile} if the file is successfully opened. If
  1490. C{path} is a directory, or if an exception is raised while trying
  1491. to open the file, the L{Deferred} will fire with an error.
  1492. """
  1493. p = self._path(path)
  1494. if p.isdir():
  1495. # Normally, we would only check for EISDIR in open, but win32
  1496. # returns EACCES in this case, so we check before
  1497. return defer.fail(IsADirectoryError(path))
  1498. try:
  1499. f = p.open('r')
  1500. except (IOError, OSError) as e:
  1501. return errnoToFailure(e.errno, path)
  1502. except:
  1503. return defer.fail()
  1504. else:
  1505. return defer.succeed(_FileReader(f))
  1506. def openForWriting(self, path):
  1507. """
  1508. Reject write attempts by anonymous users with
  1509. L{PermissionDeniedError}.
  1510. """
  1511. return defer.fail(PermissionDeniedError("STOR not allowed"))
  1512. def access(self, path):
  1513. p = self._path(path)
  1514. if not p.exists():
  1515. # Again, win32 doesn't report a sane error after, so let's fail
  1516. # early if we can
  1517. return defer.fail(FileNotFoundError(path))
  1518. # For now, just see if we can os.listdir() it
  1519. try:
  1520. p.listdir()
  1521. except (IOError, OSError) as e:
  1522. return errnoToFailure(e.errno, path)
  1523. except:
  1524. return defer.fail()
  1525. else:
  1526. return defer.succeed(None)
  1527. def stat(self, path, keys=()):
  1528. p = self._path(path)
  1529. if p.isdir():
  1530. try:
  1531. statResult = self._statNode(p, keys)
  1532. except (IOError, OSError) as e:
  1533. return errnoToFailure(e.errno, path)
  1534. except:
  1535. return defer.fail()
  1536. else:
  1537. return defer.succeed(statResult)
  1538. else:
  1539. return self.list(path, keys).addCallback(lambda res: res[0][1])
  1540. def list(self, path, keys=()):
  1541. """
  1542. Return the list of files at given C{path}, adding C{keys} stat
  1543. informations if specified.
  1544. @param path: the directory or file to check.
  1545. @type path: C{str}
  1546. @param keys: the list of desired metadata
  1547. @type keys: C{list} of C{str}
  1548. """
  1549. filePath = self._path(path)
  1550. if filePath.isdir():
  1551. entries = filePath.listdir()
  1552. fileEntries = [filePath.child(p) for p in entries]
  1553. elif filePath.isfile():
  1554. entries = [
  1555. os.path.join(*filePath.segmentsFrom(self.filesystemRoot))]
  1556. fileEntries = [filePath]
  1557. else:
  1558. return defer.fail(FileNotFoundError(path))
  1559. results = []
  1560. for fileName, filePath in zip(entries, fileEntries):
  1561. ent = []
  1562. results.append((fileName, ent))
  1563. if keys:
  1564. try:
  1565. ent.extend(self._statNode(filePath, keys))
  1566. except (IOError, OSError) as e:
  1567. return errnoToFailure(e.errno, fileName)
  1568. except:
  1569. return defer.fail()
  1570. return defer.succeed(results)
  1571. def _statNode(self, filePath, keys):
  1572. """
  1573. Shortcut method to get stat info on a node.
  1574. @param filePath: the node to stat.
  1575. @type filePath: C{filepath.FilePath}
  1576. @param keys: the stat keys to get.
  1577. @type keys: C{iterable}
  1578. """
  1579. filePath.restat()
  1580. return [getattr(self, '_stat_' + k)(filePath) for k in keys]
  1581. def _stat_size(self, fp):
  1582. """
  1583. Get the filepath's size as an int
  1584. @param fp: L{twisted.python.filepath.FilePath}
  1585. @return: C{int} representing the size
  1586. """
  1587. return fp.getsize()
  1588. def _stat_permissions(self, fp):
  1589. """
  1590. Get the filepath's permissions object
  1591. @param fp: L{twisted.python.filepath.FilePath}
  1592. @return: L{twisted.python.filepath.Permissions} of C{fp}
  1593. """
  1594. return fp.getPermissions()
  1595. def _stat_hardlinks(self, fp):
  1596. """
  1597. Get the number of hardlinks for the filepath - if the number of
  1598. hardlinks is not yet implemented (say in Windows), just return 0 since
  1599. stat-ing a file in Windows seems to return C{st_nlink=0}.
  1600. (Reference:
  1601. U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})
  1602. @param fp: L{twisted.python.filepath.FilePath}
  1603. @return: C{int} representing the number of hardlinks
  1604. """
  1605. try:
  1606. return fp.getNumberOfHardLinks()
  1607. except NotImplementedError:
  1608. return 0
  1609. def _stat_modified(self, fp):
  1610. """
  1611. Get the filepath's last modified date
  1612. @param fp: L{twisted.python.filepath.FilePath}
  1613. @return: C{int} as seconds since the epoch
  1614. """
  1615. return fp.getModificationTime()
  1616. def _stat_owner(self, fp):
  1617. """
  1618. Get the filepath's owner's username. If this is not implemented
  1619. (say in Windows) return the string "0" since stat-ing a file in
  1620. Windows seems to return C{st_uid=0}.
  1621. (Reference:
  1622. U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})
  1623. @param fp: L{twisted.python.filepath.FilePath}
  1624. @return: C{str} representing the owner's username
  1625. """
  1626. try:
  1627. userID = fp.getUserID()
  1628. except NotImplementedError:
  1629. return "0"
  1630. else:
  1631. if pwd is not None:
  1632. try:
  1633. return pwd.getpwuid(userID)[0]
  1634. except KeyError:
  1635. pass
  1636. return str(userID)
  1637. def _stat_group(self, fp):
  1638. """
  1639. Get the filepath's owner's group. If this is not implemented
  1640. (say in Windows) return the string "0" since stat-ing a file in
  1641. Windows seems to return C{st_gid=0}.
  1642. (Reference:
  1643. U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})
  1644. @param fp: L{twisted.python.filepath.FilePath}
  1645. @return: C{str} representing the owner's group
  1646. """
  1647. try:
  1648. groupID = fp.getGroupID()
  1649. except NotImplementedError:
  1650. return "0"
  1651. else:
  1652. if grp is not None:
  1653. try:
  1654. return grp.getgrgid(groupID)[0]
  1655. except KeyError:
  1656. pass
  1657. return str(groupID)
  1658. def _stat_directory(self, fp):
  1659. """
  1660. Get whether the filepath is a directory
  1661. @param fp: L{twisted.python.filepath.FilePath}
  1662. @return: C{bool}
  1663. """
  1664. return fp.isdir()
  1665. @implementer(IReadFile)
  1666. class _FileReader(object):
  1667. def __init__(self, fObj):
  1668. self.fObj = fObj
  1669. self._send = False
  1670. def _close(self, passthrough):
  1671. self._send = True
  1672. self.fObj.close()
  1673. return passthrough
  1674. def send(self, consumer):
  1675. assert not self._send, (
  1676. "Can only call IReadFile.send *once* per instance")
  1677. self._send = True
  1678. d = basic.FileSender().beginFileTransfer(self.fObj, consumer)
  1679. d.addBoth(self._close)
  1680. return d
  1681. class FTPShell(FTPAnonymousShell):
  1682. """
  1683. An authenticated implementation of L{IFTPShell}.
  1684. """
  1685. def makeDirectory(self, path):
  1686. p = self._path(path)
  1687. try:
  1688. p.makedirs()
  1689. except (IOError, OSError) as e:
  1690. return errnoToFailure(e.errno, path)
  1691. except:
  1692. return defer.fail()
  1693. else:
  1694. return defer.succeed(None)
  1695. def removeDirectory(self, path):
  1696. p = self._path(path)
  1697. if p.isfile():
  1698. # Win32 returns the wrong errno when rmdir is called on a file
  1699. # instead of a directory, so as we have the info here, let's fail
  1700. # early with a pertinent error
  1701. return defer.fail(IsNotADirectoryError(path))
  1702. try:
  1703. os.rmdir(p.path)
  1704. except (IOError, OSError) as e:
  1705. return errnoToFailure(e.errno, path)
  1706. except:
  1707. return defer.fail()
  1708. else:
  1709. return defer.succeed(None)
  1710. def removeFile(self, path):
  1711. p = self._path(path)
  1712. if p.isdir():
  1713. # Win32 returns the wrong errno when remove is called on a
  1714. # directory instead of a file, so as we have the info here,
  1715. # let's fail early with a pertinent error
  1716. return defer.fail(IsADirectoryError(path))
  1717. try:
  1718. p.remove()
  1719. except (IOError, OSError) as e:
  1720. return errnoToFailure(e.errno, path)
  1721. except:
  1722. return defer.fail()
  1723. else:
  1724. return defer.succeed(None)
  1725. def rename(self, fromPath, toPath):
  1726. fp = self._path(fromPath)
  1727. tp = self._path(toPath)
  1728. try:
  1729. os.rename(fp.path, tp.path)
  1730. except (IOError, OSError) as e:
  1731. return errnoToFailure(e.errno, fromPath)
  1732. except:
  1733. return defer.fail()
  1734. else:
  1735. return defer.succeed(None)
  1736. def openForWriting(self, path):
  1737. """
  1738. Open C{path} for writing.
  1739. @param path: The path, as a list of segments, to open.
  1740. @type path: C{list} of C{unicode}
  1741. @return: A L{Deferred} is returned that will fire with an object
  1742. implementing L{IWriteFile} if the file is successfully opened. If
  1743. C{path} is a directory, or if an exception is raised while trying
  1744. to open the file, the L{Deferred} will fire with an error.
  1745. """
  1746. p = self._path(path)
  1747. if p.isdir():
  1748. # Normally, we would only check for EISDIR in open, but win32
  1749. # returns EACCES in this case, so we check before
  1750. return defer.fail(IsADirectoryError(path))
  1751. try:
  1752. fObj = p.open('w')
  1753. except (IOError, OSError) as e:
  1754. return errnoToFailure(e.errno, path)
  1755. except:
  1756. return defer.fail()
  1757. return defer.succeed(_FileWriter(fObj))
  1758. @implementer(IWriteFile)
  1759. class _FileWriter(object):
  1760. def __init__(self, fObj):
  1761. self.fObj = fObj
  1762. self._receive = False
  1763. def receive(self):
  1764. assert not self._receive, (
  1765. "Can only call IWriteFile.receive *once* per instance")
  1766. self._receive = True
  1767. # FileConsumer will close the file object
  1768. return defer.succeed(FileConsumer(self.fObj))
  1769. def close(self):
  1770. return defer.succeed(None)
  1771. @implementer(portal.IRealm)
  1772. class BaseFTPRealm:
  1773. """
  1774. Base class for simple FTP realms which provides an easy hook for specifying
  1775. the home directory for each user.
  1776. """
  1777. def __init__(self, anonymousRoot):
  1778. self.anonymousRoot = filepath.FilePath(anonymousRoot)
  1779. def getHomeDirectory(self, avatarId):
  1780. """
  1781. Return a L{FilePath} representing the home directory of the given
  1782. avatar. Override this in a subclass.
  1783. @param avatarId: A user identifier returned from a credentials checker.
  1784. @type avatarId: C{str}
  1785. @rtype: L{FilePath}
  1786. """
  1787. raise NotImplementedError(
  1788. "%r did not override getHomeDirectory" % (self.__class__,))
  1789. def requestAvatar(self, avatarId, mind, *interfaces):
  1790. for iface in interfaces:
  1791. if iface is IFTPShell:
  1792. if avatarId is checkers.ANONYMOUS:
  1793. avatar = FTPAnonymousShell(self.anonymousRoot)
  1794. else:
  1795. avatar = FTPShell(self.getHomeDirectory(avatarId))
  1796. return (IFTPShell, avatar,
  1797. getattr(avatar, 'logout', lambda: None))
  1798. raise NotImplementedError(
  1799. "Only IFTPShell interface is supported by this realm")
  1800. class FTPRealm(BaseFTPRealm):
  1801. """
  1802. @type anonymousRoot: L{twisted.python.filepath.FilePath}
  1803. @ivar anonymousRoot: Root of the filesystem to which anonymous
  1804. users will be granted access.
  1805. @type userHome: L{filepath.FilePath}
  1806. @ivar userHome: Root of the filesystem containing user home directories.
  1807. """
  1808. def __init__(self, anonymousRoot, userHome='/home'):
  1809. BaseFTPRealm.__init__(self, anonymousRoot)
  1810. self.userHome = filepath.FilePath(userHome)
  1811. def getHomeDirectory(self, avatarId):
  1812. """
  1813. Use C{avatarId} as a single path segment to construct a child of
  1814. C{self.userHome} and return that child.
  1815. """
  1816. return self.userHome.child(avatarId)
  1817. class SystemFTPRealm(BaseFTPRealm):
  1818. """
  1819. L{SystemFTPRealm} uses system user account information to decide what the
  1820. home directory for a particular avatarId is.
  1821. This works on POSIX but probably is not reliable on Windows.
  1822. """
  1823. def getHomeDirectory(self, avatarId):
  1824. """
  1825. Return the system-defined home directory of the system user account
  1826. with the name C{avatarId}.
  1827. """
  1828. path = os.path.expanduser('~' + avatarId)
  1829. if path.startswith('~'):
  1830. raise cred_error.UnauthorizedLogin()
  1831. return filepath.FilePath(path)
  1832. # --- FTP CLIENT -------------------------------------------------------------
  1833. ####
  1834. # And now for the client...
  1835. # Notes:
  1836. # * Reference: http://cr.yp.to/ftp.html
  1837. # * FIXME: Does not support pipelining (which is not supported by all
  1838. # servers anyway). This isn't a functionality limitation, just a
  1839. # small performance issue.
  1840. # * Only has a rudimentary understanding of FTP response codes (although
  1841. # the full response is passed to the caller if they so choose).
  1842. # * Assumes that USER and PASS should always be sent
  1843. # * Always sets TYPE I (binary mode)
  1844. # * Doesn't understand any of the weird, obscure TELNET stuff (\377...)
  1845. # * FIXME: Doesn't share any code with the FTPServer
  1846. class ConnectionLost(FTPError):
  1847. pass
  1848. class CommandFailed(FTPError):
  1849. pass
  1850. class BadResponse(FTPError):
  1851. pass
  1852. class UnexpectedResponse(FTPError):
  1853. pass
  1854. class UnexpectedData(FTPError):
  1855. pass
  1856. class FTPCommand:
  1857. def __init__(self, text=None, public=0):
  1858. self.text = text
  1859. self.deferred = defer.Deferred()
  1860. self.ready = 1
  1861. self.public = public
  1862. self.transferDeferred = None
  1863. def fail(self, failure):
  1864. if self.public:
  1865. self.deferred.errback(failure)
  1866. class ProtocolWrapper(protocol.Protocol):
  1867. def __init__(self, original, deferred):
  1868. self.original = original
  1869. self.deferred = deferred
  1870. def makeConnection(self, transport):
  1871. self.original.makeConnection(transport)
  1872. def dataReceived(self, data):
  1873. self.original.dataReceived(data)
  1874. def connectionLost(self, reason):
  1875. self.original.connectionLost(reason)
  1876. # Signal that transfer has completed
  1877. self.deferred.callback(None)
  1878. class IFinishableConsumer(interfaces.IConsumer):
  1879. """
  1880. A Consumer for producers that finish.
  1881. @since: 11.0
  1882. """
  1883. def finish():
  1884. """
  1885. The producer has finished producing.
  1886. """
  1887. @implementer(IFinishableConsumer)
  1888. class SenderProtocol(protocol.Protocol):
  1889. def __init__(self):
  1890. # Fired upon connection
  1891. self.connectedDeferred = defer.Deferred()
  1892. # Fired upon disconnection
  1893. self.deferred = defer.Deferred()
  1894. # Protocol stuff
  1895. def dataReceived(self, data):
  1896. raise UnexpectedData(
  1897. "Received data from the server on a "
  1898. "send-only data-connection"
  1899. )
  1900. def makeConnection(self, transport):
  1901. protocol.Protocol.makeConnection(self, transport)
  1902. self.connectedDeferred.callback(self)
  1903. def connectionLost(self, reason):
  1904. if reason.check(error.ConnectionDone):
  1905. self.deferred.callback('connection done')
  1906. else:
  1907. self.deferred.errback(reason)
  1908. # IFinishableConsumer stuff
  1909. def write(self, data):
  1910. self.transport.write(data)
  1911. def registerProducer(self, producer, streaming):
  1912. """
  1913. Register the given producer with our transport.
  1914. """
  1915. self.transport.registerProducer(producer, streaming)
  1916. def unregisterProducer(self):
  1917. """
  1918. Unregister the previously registered producer.
  1919. """
  1920. self.transport.unregisterProducer()
  1921. def finish(self):
  1922. self.transport.loseConnection()
  1923. def decodeHostPort(line):
  1924. """
  1925. Decode an FTP response specifying a host and port.
  1926. @return: a 2-tuple of (host, port).
  1927. """
  1928. abcdef = re.sub('[^0-9, ]', '', line)
  1929. parsed = [int(p.strip()) for p in abcdef.split(',')]
  1930. for x in parsed:
  1931. if x < 0 or x > 255:
  1932. raise ValueError("Out of range", line, x)
  1933. a, b, c, d, e, f = parsed
  1934. host = "%s.%s.%s.%s" % (a, b, c, d)
  1935. port = (int(e) << 8) + int(f)
  1936. return host, port
  1937. def encodeHostPort(host, port):
  1938. numbers = host.split('.') + [str(port >> 8), str(port % 256)]
  1939. return ','.join(numbers)
  1940. def _unwrapFirstError(failure):
  1941. failure.trap(defer.FirstError)
  1942. return failure.value.subFailure
  1943. class FTPDataPortFactory(protocol.ServerFactory):
  1944. """
  1945. Factory for data connections that use the PORT command
  1946. (i.e. "active" transfers)
  1947. """
  1948. noisy = 0
  1949. def buildProtocol(self, addr):
  1950. # This is a bit hackish -- we already have a Protocol instance,
  1951. # so just return it instead of making a new one
  1952. # FIXME: Reject connections from the wrong address/port
  1953. # (potential security problem)
  1954. self.protocol.factory = self
  1955. self.port.loseConnection()
  1956. return self.protocol
  1957. class FTPClientBasic(basic.LineReceiver):
  1958. """
  1959. Foundations of an FTP client.
  1960. """
  1961. debug = False
  1962. _encoding = 'latin-1'
  1963. def __init__(self):
  1964. self.actionQueue = []
  1965. self.greeting = None
  1966. self.nextDeferred = defer.Deferred().addCallback(self._cb_greeting)
  1967. self.nextDeferred.addErrback(self.fail)
  1968. self.response = []
  1969. self._failed = 0
  1970. def fail(self, error):
  1971. """
  1972. Give an error to any queued deferreds.
  1973. """
  1974. self._fail(error)
  1975. def _fail(self, error):
  1976. """
  1977. Errback all queued deferreds.
  1978. """
  1979. if self._failed:
  1980. # We're recursing; bail out here for simplicity
  1981. return error
  1982. self._failed = 1
  1983. if self.nextDeferred:
  1984. try:
  1985. self.nextDeferred.errback(failure.Failure(
  1986. ConnectionLost('FTP connection lost', error)))
  1987. except defer.AlreadyCalledError:
  1988. pass
  1989. for ftpCommand in self.actionQueue:
  1990. ftpCommand.fail(failure.Failure(
  1991. ConnectionLost('FTP connection lost', error)))
  1992. return error
  1993. def _cb_greeting(self, greeting):
  1994. self.greeting = greeting
  1995. def sendLine(self, line):
  1996. """
  1997. Sends a line, unless line is None.
  1998. @param line: Line to send
  1999. @type line: L{bytes} or L{unicode}
  2000. """
  2001. if line is None:
  2002. return
  2003. elif isinstance(line, unicode):
  2004. line = line.encode(self._encoding)
  2005. basic.LineReceiver.sendLine(self, line)
  2006. def sendNextCommand(self):
  2007. """
  2008. (Private) Processes the next command in the queue.
  2009. """
  2010. ftpCommand = self.popCommandQueue()
  2011. if ftpCommand is None:
  2012. self.nextDeferred = None
  2013. return
  2014. if not ftpCommand.ready:
  2015. self.actionQueue.insert(0, ftpCommand)
  2016. reactor.callLater(1.0, self.sendNextCommand)
  2017. self.nextDeferred = None
  2018. return
  2019. # FIXME: this if block doesn't belong in FTPClientBasic, it belongs in
  2020. # FTPClient.
  2021. if ftpCommand.text == 'PORT':
  2022. self.generatePortCommand(ftpCommand)
  2023. if self.debug:
  2024. log.msg('<-- %s' % ftpCommand.text)
  2025. self.nextDeferred = ftpCommand.deferred
  2026. self.sendLine(ftpCommand.text)
  2027. def queueCommand(self, ftpCommand):
  2028. """
  2029. Add an FTPCommand object to the queue.
  2030. If it's the only thing in the queue, and we are connected and we aren't
  2031. waiting for a response of an earlier command, the command will be sent
  2032. immediately.
  2033. @param ftpCommand: an L{FTPCommand}
  2034. """
  2035. self.actionQueue.append(ftpCommand)
  2036. if (len(self.actionQueue) == 1 and self.transport is not None and
  2037. self.nextDeferred is None):
  2038. self.sendNextCommand()
  2039. def queueStringCommand(self, command, public=1):
  2040. """
  2041. Queues a string to be issued as an FTP command
  2042. @param command: string of an FTP command to queue
  2043. @param public: a flag intended for internal use by FTPClient. Don't
  2044. change it unless you know what you're doing.
  2045. @return: a L{Deferred} that will be called when the response to the
  2046. command has been received.
  2047. """
  2048. ftpCommand = FTPCommand(command, public)
  2049. self.queueCommand(ftpCommand)
  2050. return ftpCommand.deferred
  2051. def popCommandQueue(self):
  2052. """
  2053. Return the front element of the command queue, or None if empty.
  2054. """
  2055. if self.actionQueue:
  2056. return self.actionQueue.pop(0)
  2057. else:
  2058. return None
  2059. def queueLogin(self, username, password):
  2060. """
  2061. Login: send the username, send the password.
  2062. If the password is L{None}, the PASS command won't be sent. Also, if
  2063. the response to the USER command has a response code of 230 (User
  2064. logged in), then PASS won't be sent either.
  2065. """
  2066. # Prepare the USER command
  2067. deferreds = []
  2068. userDeferred = self.queueStringCommand('USER ' + username, public=0)
  2069. deferreds.append(userDeferred)
  2070. # Prepare the PASS command (if a password is given)
  2071. if password is not None:
  2072. passwordCmd = FTPCommand('PASS ' + password, public=0)
  2073. self.queueCommand(passwordCmd)
  2074. deferreds.append(passwordCmd.deferred)
  2075. # Avoid sending PASS if the response to USER is 230.
  2076. # (ref: http://cr.yp.to/ftp/user.html#user)
  2077. def cancelPasswordIfNotNeeded(response):
  2078. if response[0].startswith('230'):
  2079. # No password needed!
  2080. self.actionQueue.remove(passwordCmd)
  2081. return response
  2082. userDeferred.addCallback(cancelPasswordIfNotNeeded)
  2083. # Error handling.
  2084. for deferred in deferreds:
  2085. # If something goes wrong, call fail
  2086. deferred.addErrback(self.fail)
  2087. # But also swallow the error, so we don't cause spurious errors
  2088. deferred.addErrback(lambda x: None)
  2089. def lineReceived(self, line):
  2090. """
  2091. (Private) Parses the response messages from the FTP server.
  2092. """
  2093. # Add this line to the current response
  2094. if bytes != str:
  2095. line = line.decode(self._encoding)
  2096. if self.debug:
  2097. log.msg('--> %s' % line)
  2098. self.response.append(line)
  2099. # Bail out if this isn't the last line of a response
  2100. # The last line of response starts with 3 digits followed by a space
  2101. codeIsValid = re.match(r'\d{3} ', line)
  2102. if not codeIsValid:
  2103. return
  2104. code = line[0:3]
  2105. # Ignore marks
  2106. if code[0] == '1':
  2107. return
  2108. # Check that we were expecting a response
  2109. if self.nextDeferred is None:
  2110. self.fail(UnexpectedResponse(self.response))
  2111. return
  2112. # Reset the response
  2113. response = self.response
  2114. self.response = []
  2115. # Look for a success or error code, and call the appropriate callback
  2116. if code[0] in ('2', '3'):
  2117. # Success
  2118. self.nextDeferred.callback(response)
  2119. elif code[0] in ('4', '5'):
  2120. # Failure
  2121. self.nextDeferred.errback(failure.Failure(CommandFailed(response)))
  2122. else:
  2123. # This shouldn't happen unless something screwed up.
  2124. log.msg('Server sent invalid response code %s' % (code,))
  2125. self.nextDeferred.errback(failure.Failure(BadResponse(response)))
  2126. # Run the next command
  2127. self.sendNextCommand()
  2128. def connectionLost(self, reason):
  2129. self._fail(reason)
  2130. class _PassiveConnectionFactory(protocol.ClientFactory):
  2131. noisy = False
  2132. def __init__(self, protoInstance):
  2133. self.protoInstance = protoInstance
  2134. def buildProtocol(self, ignored):
  2135. self.protoInstance.factory = self
  2136. return self.protoInstance
  2137. def clientConnectionFailed(self, connector, reason):
  2138. e = FTPError('Connection Failed', reason)
  2139. self.protoInstance.deferred.errback(e)
  2140. class FTPClient(FTPClientBasic):
  2141. """
  2142. L{FTPClient} is a client implementation of the FTP protocol which
  2143. exposes FTP commands as methods which return L{Deferred}s.
  2144. Each command method returns a L{Deferred} which is called back when a
  2145. successful response code (2xx or 3xx) is received from the server or
  2146. which is error backed if an error response code (4xx or 5xx) is received
  2147. from the server or if a protocol violation occurs. If an error response
  2148. code is received, the L{Deferred} fires with a L{Failure} wrapping a
  2149. L{CommandFailed} instance. The L{CommandFailed} instance is created
  2150. with a list of the response lines received from the server.
  2151. See U{RFC 959<http://www.ietf.org/rfc/rfc959.txt>} for error code
  2152. definitions.
  2153. Both active and passive transfers are supported.
  2154. @ivar passive: See description in __init__.
  2155. """
  2156. connectFactory = reactor.connectTCP
  2157. def __init__(self, username='anonymous',
  2158. password='twisted@twistedmatrix.com',
  2159. passive=1):
  2160. """
  2161. Constructor.
  2162. I will login as soon as I receive the welcome message from the server.
  2163. @param username: FTP username
  2164. @param password: FTP password
  2165. @param passive: flag that controls if I use active or passive data
  2166. connections. You can also change this after construction by
  2167. assigning to C{self.passive}.
  2168. """
  2169. FTPClientBasic.__init__(self)
  2170. self.queueLogin(username, password)
  2171. self.passive = passive
  2172. def fail(self, error):
  2173. """
  2174. Disconnect, and also give an error to any queued deferreds.
  2175. """
  2176. self.transport.loseConnection()
  2177. self._fail(error)
  2178. def receiveFromConnection(self, commands, protocol):
  2179. """
  2180. Retrieves a file or listing generated by the given command,
  2181. feeding it to the given protocol.
  2182. @param commands: list of strings of FTP commands to execute then
  2183. receive the results of (e.g. C{LIST}, C{RETR})
  2184. @param protocol: A L{Protocol} B{instance} e.g. an
  2185. L{FTPFileListProtocol}, or something that can be adapted to one.
  2186. Typically this will be an L{IConsumer} implementation.
  2187. @return: L{Deferred}.
  2188. """
  2189. protocol = interfaces.IProtocol(protocol)
  2190. wrapper = ProtocolWrapper(protocol, defer.Deferred())
  2191. return self._openDataConnection(commands, wrapper)
  2192. def queueLogin(self, username, password):
  2193. """
  2194. Login: send the username, send the password, and
  2195. set retrieval mode to binary
  2196. """
  2197. FTPClientBasic.queueLogin(self, username, password)
  2198. d = self.queueStringCommand('TYPE I', public=0)
  2199. # If something goes wrong, call fail
  2200. d.addErrback(self.fail)
  2201. # But also swallow the error, so we don't cause spurious errors
  2202. d.addErrback(lambda x: None)
  2203. def sendToConnection(self, commands):
  2204. """
  2205. XXX
  2206. @return: A tuple of two L{Deferred}s:
  2207. - L{Deferred} L{IFinishableConsumer}. You must call
  2208. the C{finish} method on the IFinishableConsumer when the
  2209. file is completely transferred.
  2210. - L{Deferred} list of control-connection responses.
  2211. """
  2212. s = SenderProtocol()
  2213. r = self._openDataConnection(commands, s)
  2214. return (s.connectedDeferred, r)
  2215. def _openDataConnection(self, commands, protocol):
  2216. """
  2217. This method returns a DeferredList.
  2218. """
  2219. cmds = [FTPCommand(command, public=1) for command in commands]
  2220. cmdsDeferred = defer.DeferredList(
  2221. [cmd.deferred for cmd in cmds],
  2222. fireOnOneErrback=True, consumeErrors=True)
  2223. cmdsDeferred.addErrback(_unwrapFirstError)
  2224. if self.passive:
  2225. # Hack: use a mutable object to sneak a variable out of the
  2226. # scope of doPassive
  2227. _mutable = [None]
  2228. def doPassive(response):
  2229. """Connect to the port specified in the response to PASV"""
  2230. host, port = decodeHostPort(response[-1][4:])
  2231. f = _PassiveConnectionFactory(protocol)
  2232. _mutable[0] = self.connectFactory(host, port, f)
  2233. pasvCmd = FTPCommand('PASV')
  2234. self.queueCommand(pasvCmd)
  2235. pasvCmd.deferred.addCallback(doPassive).addErrback(self.fail)
  2236. results = [cmdsDeferred, pasvCmd.deferred, protocol.deferred]
  2237. d = defer.DeferredList(
  2238. results, fireOnOneErrback=True, consumeErrors=True)
  2239. d.addErrback(_unwrapFirstError)
  2240. # Ensure the connection is always closed
  2241. def close(x, m=_mutable):
  2242. m[0] and m[0].disconnect()
  2243. return x
  2244. d.addBoth(close)
  2245. else:
  2246. # We just place a marker command in the queue, and will fill in
  2247. # the host and port numbers later (see generatePortCommand)
  2248. portCmd = FTPCommand('PORT')
  2249. # Ok, now we jump through a few hoops here.
  2250. # This is the problem: a transfer is not to be trusted as complete
  2251. # until we get both the "226 Transfer complete" message on the
  2252. # control connection, and the data socket is closed. Thus, we use
  2253. # a DeferredList to make sure we only fire the callback at the
  2254. # right time.
  2255. portCmd.transferDeferred = protocol.deferred
  2256. portCmd.protocol = protocol
  2257. portCmd.deferred.addErrback(portCmd.transferDeferred.errback)
  2258. self.queueCommand(portCmd)
  2259. # Create dummy functions for the next callback to call.
  2260. # These will also be replaced with real functions in
  2261. # generatePortCommand.
  2262. portCmd.loseConnection = lambda result: result
  2263. portCmd.fail = lambda error: error
  2264. # Ensure that the connection always gets closed
  2265. cmdsDeferred.addErrback(lambda e, pc=portCmd: pc.fail(e) or e)
  2266. results = [
  2267. cmdsDeferred, portCmd.deferred, portCmd.transferDeferred]
  2268. d = defer.DeferredList(
  2269. results, fireOnOneErrback=True, consumeErrors=True)
  2270. d.addErrback(_unwrapFirstError)
  2271. for cmd in cmds:
  2272. self.queueCommand(cmd)
  2273. return d
  2274. def generatePortCommand(self, portCmd):
  2275. """
  2276. (Private) Generates the text of a given PORT command.
  2277. """
  2278. # The problem is that we don't create the listening port until we need
  2279. # it for various reasons, and so we have to muck about to figure out
  2280. # what interface and port it's listening on, and then finally we can
  2281. # create the text of the PORT command to send to the FTP server.
  2282. # FIXME: This method is far too ugly.
  2283. # FIXME: The best solution is probably to only create the data port
  2284. # once per FTPClient, and just recycle it for each new download.
  2285. # This should be ok, because we don't pipeline commands.
  2286. # Start listening on a port
  2287. factory = FTPDataPortFactory()
  2288. factory.protocol = portCmd.protocol
  2289. listener = reactor.listenTCP(0, factory)
  2290. factory.port = listener
  2291. # Ensure we close the listening port if something goes wrong
  2292. def listenerFail(error, listener=listener):
  2293. if listener.connected:
  2294. listener.loseConnection()
  2295. return error
  2296. portCmd.fail = listenerFail
  2297. # Construct crufty FTP magic numbers that represent host & port
  2298. host = self.transport.getHost().host
  2299. port = listener.getHost().port
  2300. portCmd.text = 'PORT ' + encodeHostPort(host, port)
  2301. def escapePath(self, path):
  2302. """
  2303. Returns a FTP escaped path (replace newlines with nulls).
  2304. """
  2305. # Escape newline characters
  2306. return path.replace('\n', '\0')
  2307. def retrieveFile(self, path, protocol, offset=0):
  2308. """
  2309. Retrieve a file from the given path
  2310. This method issues the 'RETR' FTP command.
  2311. The file is fed into the given Protocol instance. The data connection
  2312. will be passive if self.passive is set.
  2313. @param path: path to file that you wish to receive.
  2314. @param protocol: a L{Protocol} instance.
  2315. @param offset: offset to start downloading from
  2316. @return: L{Deferred}
  2317. """
  2318. cmds = ['RETR ' + self.escapePath(path)]
  2319. if offset:
  2320. cmds.insert(0, ('REST ' + str(offset)))
  2321. return self.receiveFromConnection(cmds, protocol)
  2322. retr = retrieveFile
  2323. def storeFile(self, path, offset=0):
  2324. """
  2325. Store a file at the given path.
  2326. This method issues the 'STOR' FTP command.
  2327. @return: A tuple of two L{Deferred}s:
  2328. - L{Deferred} L{IFinishableConsumer}. You must call
  2329. the C{finish} method on the IFinishableConsumer when the
  2330. file is completely transferred.
  2331. - L{Deferred} list of control-connection responses.
  2332. """
  2333. cmds = ['STOR ' + self.escapePath(path)]
  2334. if offset:
  2335. cmds.insert(0, ('REST ' + str(offset)))
  2336. return self.sendToConnection(cmds)
  2337. stor = storeFile
  2338. def rename(self, pathFrom, pathTo):
  2339. """
  2340. Rename a file.
  2341. This method issues the I{RNFR}/I{RNTO} command sequence to rename
  2342. C{pathFrom} to C{pathTo}.
  2343. @param: pathFrom: the absolute path to the file to be renamed
  2344. @type pathFrom: C{str}
  2345. @param: pathTo: the absolute path to rename the file to.
  2346. @type pathTo: C{str}
  2347. @return: A L{Deferred} which fires when the rename operation has
  2348. succeeded or failed. If it succeeds, the L{Deferred} is called
  2349. back with a two-tuple of lists. The first list contains the
  2350. responses to the I{RNFR} command. The second list contains the
  2351. responses to the I{RNTO} command. If either I{RNFR} or I{RNTO}
  2352. fails, the L{Deferred} is errbacked with L{CommandFailed} or
  2353. L{BadResponse}.
  2354. @rtype: L{Deferred}
  2355. @since: 8.2
  2356. """
  2357. renameFrom = self.queueStringCommand(
  2358. 'RNFR ' + self.escapePath(pathFrom))
  2359. renameTo = self.queueStringCommand('RNTO ' + self.escapePath(pathTo))
  2360. fromResponse = []
  2361. # Use a separate Deferred for the ultimate result so that Deferred
  2362. # chaining can't interfere with its result.
  2363. result = defer.Deferred()
  2364. # Bundle up all the responses
  2365. result.addCallback(lambda toResponse: (fromResponse, toResponse))
  2366. def ebFrom(failure):
  2367. # Make sure the RNTO doesn't run if the RNFR failed.
  2368. self.popCommandQueue()
  2369. result.errback(failure)
  2370. # Save the RNFR response to pass to the result Deferred later
  2371. renameFrom.addCallbacks(fromResponse.extend, ebFrom)
  2372. # Hook up the RNTO to the result Deferred as well
  2373. renameTo.chainDeferred(result)
  2374. return result
  2375. def list(self, path, protocol):
  2376. """
  2377. Retrieve a file listing into the given protocol instance.
  2378. This method issues the 'LIST' FTP command.
  2379. @param path: path to get a file listing for.
  2380. @param protocol: a L{Protocol} instance, probably a
  2381. L{FTPFileListProtocol} instance. It can cope with most common file
  2382. listing formats.
  2383. @return: L{Deferred}
  2384. """
  2385. if path is None:
  2386. path = ''
  2387. return self.receiveFromConnection(
  2388. ['LIST ' + self.escapePath(path)], protocol)
  2389. def nlst(self, path, protocol):
  2390. """
  2391. Retrieve a short file listing into the given protocol instance.
  2392. This method issues the 'NLST' FTP command.
  2393. NLST (should) return a list of filenames, one per line.
  2394. @param path: path to get short file listing for.
  2395. @param protocol: a L{Protocol} instance.
  2396. """
  2397. if path is None:
  2398. path = ''
  2399. return self.receiveFromConnection(
  2400. ['NLST ' + self.escapePath(path)], protocol)
  2401. def cwd(self, path):
  2402. """
  2403. Issues the CWD (Change Working Directory) command.
  2404. @return: a L{Deferred} that will be called when done.
  2405. """
  2406. return self.queueStringCommand('CWD ' + self.escapePath(path))
  2407. def makeDirectory(self, path):
  2408. """
  2409. Make a directory
  2410. This method issues the MKD command.
  2411. @param path: The path to the directory to create.
  2412. @type path: C{str}
  2413. @return: A L{Deferred} which fires when the server responds. If the
  2414. directory is created, the L{Deferred} is called back with the
  2415. server response. If the server response indicates the directory
  2416. was not created, the L{Deferred} is errbacked with a L{Failure}
  2417. wrapping L{CommandFailed} or L{BadResponse}.
  2418. @rtype: L{Deferred}
  2419. @since: 8.2
  2420. """
  2421. return self.queueStringCommand('MKD ' + self.escapePath(path))
  2422. def removeFile(self, path):
  2423. """
  2424. Delete a file on the server.
  2425. L{removeFile} issues a I{DELE} command to the server to remove the
  2426. indicated file. Note that this command cannot remove a directory.
  2427. @param path: The path to the file to delete. May be relative to the
  2428. current dir.
  2429. @type path: C{str}
  2430. @return: A L{Deferred} which fires when the server responds. On error,
  2431. it is errbacked with either L{CommandFailed} or L{BadResponse}. On
  2432. success, it is called back with a list of response lines.
  2433. @rtype: L{Deferred}
  2434. @since: 8.2
  2435. """
  2436. return self.queueStringCommand('DELE ' + self.escapePath(path))
  2437. def removeDirectory(self, path):
  2438. """
  2439. Delete a directory on the server.
  2440. L{removeDirectory} issues a I{RMD} command to the server to remove the
  2441. indicated directory. Described in RFC959.
  2442. @param path: The path to the directory to delete. May be relative to
  2443. the current working directory.
  2444. @type path: C{str}
  2445. @return: A L{Deferred} which fires when the server responds. On error,
  2446. it is errbacked with either L{CommandFailed} or L{BadResponse}. On
  2447. success, it is called back with a list of response lines.
  2448. @rtype: L{Deferred}
  2449. @since: 11.1
  2450. """
  2451. return self.queueStringCommand('RMD ' + self.escapePath(path))
  2452. def cdup(self):
  2453. """
  2454. Issues the CDUP (Change Directory UP) command.
  2455. @return: a L{Deferred} that will be called when done.
  2456. """
  2457. return self.queueStringCommand('CDUP')
  2458. def pwd(self):
  2459. """
  2460. Issues the PWD (Print Working Directory) command.
  2461. The L{getDirectory} does the same job but automatically parses the
  2462. result.
  2463. @return: a L{Deferred} that will be called when done. It is up to the
  2464. caller to interpret the response, but the L{parsePWDResponse}
  2465. method in this module should work.
  2466. """
  2467. return self.queueStringCommand('PWD')
  2468. def getDirectory(self):
  2469. """
  2470. Returns the current remote directory.
  2471. @return: a L{Deferred} that will be called back with a C{str} giving
  2472. the remote directory or which will errback with L{CommandFailed}
  2473. if an error response is returned.
  2474. """
  2475. def cbParse(result):
  2476. try:
  2477. # The only valid code is 257
  2478. if int(result[0].split(' ', 1)[0]) != 257:
  2479. raise ValueError
  2480. except (IndexError, ValueError):
  2481. return failure.Failure(CommandFailed(result))
  2482. path = parsePWDResponse(result[0])
  2483. if path is None:
  2484. return failure.Failure(CommandFailed(result))
  2485. return path
  2486. return self.pwd().addCallback(cbParse)
  2487. def quit(self):
  2488. """
  2489. Issues the I{QUIT} command.
  2490. @return: A L{Deferred} that fires when the server acknowledges the
  2491. I{QUIT} command. The transport should not be disconnected until
  2492. this L{Deferred} fires.
  2493. """
  2494. return self.queueStringCommand('QUIT')
  2495. class FTPFileListProtocol(basic.LineReceiver):
  2496. """
  2497. Parser for standard FTP file listings
  2498. This is the evil required to match::
  2499. -rw-r--r-- 1 root other 531 Jan 29 03:26 README
  2500. If you need different evil for a wacky FTP server, you can
  2501. override either C{fileLinePattern} or C{parseDirectoryLine()}.
  2502. It populates the instance attribute self.files, which is a list containing
  2503. dicts with the following keys (examples from the above line):
  2504. - filetype: e.g. 'd' for directories, or '-' for an ordinary file
  2505. - perms: e.g. 'rw-r--r--'
  2506. - nlinks: e.g. 1
  2507. - owner: e.g. 'root'
  2508. - group: e.g. 'other'
  2509. - size: e.g. 531
  2510. - date: e.g. 'Jan 29 03:26'
  2511. - filename: e.g. 'README'
  2512. - linktarget: e.g. 'some/file'
  2513. Note that the 'date' value will be formatted differently depending on the
  2514. date. Check U{http://cr.yp.to/ftp.html} if you really want to try to parse
  2515. it.
  2516. It also matches the following::
  2517. -rw-r--r-- 1 root other 531 Jan 29 03:26 I HAVE\\ SPACE
  2518. - filename: e.g. 'I HAVE SPACE'
  2519. -rw-r--r-- 1 root other 531 Jan 29 03:26 LINK -> TARGET
  2520. - filename: e.g. 'LINK'
  2521. - linktarget: e.g. 'TARGET'
  2522. -rw-r--r-- 1 root other 531 Jan 29 03:26 N S -> L S
  2523. - filename: e.g. 'N S'
  2524. - linktarget: e.g. 'L S'
  2525. @ivar files: list of dicts describing the files in this listing
  2526. """
  2527. fileLinePattern = re.compile(
  2528. r'^(?P<filetype>.)(?P<perms>.{9})\s+(?P<nlinks>\d*)\s*'
  2529. r'(?P<owner>\S+)\s+(?P<group>\S+)\s+(?P<size>\d+)\s+'
  2530. r'(?P<date>...\s+\d+\s+[\d:]+)\s+(?P<filename>.{1,}?)'
  2531. r'( -> (?P<linktarget>[^\r]*))?\r?$'
  2532. )
  2533. delimiter = b'\n'
  2534. _encoding = 'latin-1'
  2535. def __init__(self):
  2536. self.files = []
  2537. def lineReceived(self, line):
  2538. if bytes != str:
  2539. line = line.decode(self._encoding)
  2540. d = self.parseDirectoryLine(line)
  2541. if d is None:
  2542. self.unknownLine(line)
  2543. else:
  2544. self.addFile(d)
  2545. def parseDirectoryLine(self, line):
  2546. """
  2547. Return a dictionary of fields, or None if line cannot be parsed.
  2548. @param line: line of text expected to contain a directory entry
  2549. @type line: str
  2550. @return: dict
  2551. """
  2552. match = self.fileLinePattern.match(line)
  2553. if match is None:
  2554. return None
  2555. else:
  2556. d = match.groupdict()
  2557. d['filename'] = d['filename'].replace(r'\ ', ' ')
  2558. d['nlinks'] = int(d['nlinks'])
  2559. d['size'] = int(d['size'])
  2560. if d['linktarget']:
  2561. d['linktarget'] = d['linktarget'].replace(r'\ ', ' ')
  2562. return d
  2563. def addFile(self, info):
  2564. """
  2565. Append file information dictionary to the list of known files.
  2566. Subclasses can override or extend this method to handle file
  2567. information differently without affecting the parsing of data
  2568. from the server.
  2569. @param info: dictionary containing the parsed representation
  2570. of the file information
  2571. @type info: dict
  2572. """
  2573. self.files.append(info)
  2574. def unknownLine(self, line):
  2575. """
  2576. Deal with received lines which could not be parsed as file
  2577. information.
  2578. Subclasses can override this to perform any special processing
  2579. needed.
  2580. @param line: unparsable line as received
  2581. @type line: str
  2582. """
  2583. pass
  2584. def parsePWDResponse(response):
  2585. """
  2586. Returns the path from a response to a PWD command.
  2587. Responses typically look like::
  2588. 257 "/home/andrew" is current directory.
  2589. For this example, I will return C{'/home/andrew'}.
  2590. If I can't find the path, I return L{None}.
  2591. """
  2592. match = re.search('"(.*)"', response)
  2593. if match:
  2594. return match.groups()[0]
  2595. else:
  2596. return None