2
0

ftp.c 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifndef CURL_DISABLE_FTP
  26. #ifdef HAVE_NETINET_IN_H
  27. #include <netinet/in.h>
  28. #endif
  29. #ifdef HAVE_ARPA_INET_H
  30. #include <arpa/inet.h>
  31. #endif
  32. #ifdef HAVE_NETDB_H
  33. #include <netdb.h>
  34. #endif
  35. #ifdef __VMS
  36. #include <in.h>
  37. #include <inet.h>
  38. #endif
  39. #include <curl/curl.h>
  40. #include "urldata.h"
  41. #include "sendf.h"
  42. #include "if2ip.h"
  43. #include "hostip.h"
  44. #include "progress.h"
  45. #include "transfer.h"
  46. #include "escape.h"
  47. #include "http.h" /* for HTTP proxy tunnel stuff */
  48. #include "ftp.h"
  49. #include "fileinfo.h"
  50. #include "ftplistparser.h"
  51. #include "curl_range.h"
  52. #include "curl_krb5.h"
  53. #include "strtoofft.h"
  54. #include "strcase.h"
  55. #include "vtls/vtls.h"
  56. #include "cfilters.h"
  57. #include "cf-socket.h"
  58. #include "connect.h"
  59. #include "strerror.h"
  60. #include "inet_ntop.h"
  61. #include "inet_pton.h"
  62. #include "select.h"
  63. #include "parsedate.h" /* for the week day and month names */
  64. #include "sockaddr.h" /* required for Curl_sockaddr_storage */
  65. #include "multiif.h"
  66. #include "url.h"
  67. #include "speedcheck.h"
  68. #include "warnless.h"
  69. #include "http_proxy.h"
  70. #include "socks.h"
  71. #include "strdup.h"
  72. /* The last 3 #include files should be in this order */
  73. #include "curl_printf.h"
  74. #include "curl_memory.h"
  75. #include "memdebug.h"
  76. #ifndef NI_MAXHOST
  77. #define NI_MAXHOST 1025
  78. #endif
  79. #ifndef INET_ADDRSTRLEN
  80. #define INET_ADDRSTRLEN 16
  81. #endif
  82. /* macro to check for a three-digit ftp status code at the start of the
  83. given string */
  84. #define STATUSCODE(line) (ISDIGIT(line[0]) && ISDIGIT(line[1]) && \
  85. ISDIGIT(line[2]))
  86. /* macro to check for the last line in an FTP server response */
  87. #define LASTLINE(line) (STATUSCODE(line) && (' ' == line[3]))
  88. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  89. #define ftp_pasv_verbose(a,b,c,d) Curl_nop_stmt
  90. #define FTP_CSTATE(c) ""
  91. #define FTP_DSTATE(d) ""
  92. #else /* CURL_DISABLE_VERBOSE_STRINGS */
  93. /* for tracing purposes */
  94. static const char * const ftp_state_names[]={
  95. "STOP",
  96. "WAIT220",
  97. "AUTH",
  98. "USER",
  99. "PASS",
  100. "ACCT",
  101. "PBSZ",
  102. "PROT",
  103. "CCC",
  104. "PWD",
  105. "SYST",
  106. "NAMEFMT",
  107. "QUOTE",
  108. "RETR_PREQUOTE",
  109. "STOR_PREQUOTE",
  110. "POSTQUOTE",
  111. "CWD",
  112. "MKD",
  113. "MDTM",
  114. "TYPE",
  115. "LIST_TYPE",
  116. "RETR_TYPE",
  117. "STOR_TYPE",
  118. "SIZE",
  119. "RETR_SIZE",
  120. "STOR_SIZE",
  121. "REST",
  122. "RETR_REST",
  123. "PORT",
  124. "PRET",
  125. "PASV",
  126. "LIST",
  127. "RETR",
  128. "STOR",
  129. "QUIT"
  130. };
  131. #define FTP_CSTATE(c) ((c)? ftp_state_names[(c)->proto.ftpc.state] : "???")
  132. #define FTP_DSTATE(d) (((d) && (d)->conn)? \
  133. ftp_state_names[(d)->conn->proto.ftpc.state] : "???")
  134. #endif /* !CURL_DISABLE_VERBOSE_STRINGS */
  135. /* This is the ONLY way to change FTP state! */
  136. static void _ftp_state(struct Curl_easy *data,
  137. ftpstate newstate
  138. #ifdef DEBUGBUILD
  139. , int lineno
  140. #endif
  141. )
  142. {
  143. struct connectdata *conn = data->conn;
  144. struct ftp_conn *ftpc = &conn->proto.ftpc;
  145. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  146. #ifdef DEBUGBUILD
  147. (void)lineno;
  148. #endif
  149. #else /* CURL_DISABLE_VERBOSE_STRINGS */
  150. if(ftpc->state != newstate)
  151. #ifdef DEBUGBUILD
  152. CURL_TRC_FTP(data, "[%s] -> [%s] (line %d)", FTP_DSTATE(data),
  153. ftp_state_names[newstate], lineno);
  154. #else
  155. CURL_TRC_FTP(data, "[%s] -> [%s]", FTP_DSTATE(data),
  156. ftp_state_names[newstate]);
  157. #endif
  158. #endif /* !CURL_DISABLE_VERBOSE_STRINGS */
  159. ftpc->state = newstate;
  160. }
  161. /* Local API functions */
  162. #ifndef DEBUGBUILD
  163. #define ftp_state(x,y) _ftp_state(x,y)
  164. #else /* !DEBUGBUILD */
  165. #define ftp_state(x,y) _ftp_state(x,y,__LINE__)
  166. #endif /* DEBUGBUILD */
  167. static CURLcode ftp_sendquote(struct Curl_easy *data,
  168. struct connectdata *conn,
  169. struct curl_slist *quote);
  170. static CURLcode ftp_quit(struct Curl_easy *data, struct connectdata *conn);
  171. static CURLcode ftp_parse_url_path(struct Curl_easy *data);
  172. static CURLcode ftp_regular_transfer(struct Curl_easy *data, bool *done);
  173. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  174. static void ftp_pasv_verbose(struct Curl_easy *data,
  175. struct Curl_addrinfo *ai,
  176. char *newhost, /* ASCII version */
  177. int port);
  178. #endif
  179. static CURLcode ftp_state_prepare_transfer(struct Curl_easy *data);
  180. static CURLcode ftp_state_mdtm(struct Curl_easy *data);
  181. static CURLcode ftp_state_quote(struct Curl_easy *data,
  182. bool init, ftpstate instate);
  183. static CURLcode ftp_nb_type(struct Curl_easy *data,
  184. struct connectdata *conn,
  185. bool ascii, ftpstate newstate);
  186. static int ftp_need_type(struct connectdata *conn,
  187. bool ascii);
  188. static CURLcode ftp_do(struct Curl_easy *data, bool *done);
  189. static CURLcode ftp_done(struct Curl_easy *data,
  190. CURLcode, bool premature);
  191. static CURLcode ftp_connect(struct Curl_easy *data, bool *done);
  192. static CURLcode ftp_disconnect(struct Curl_easy *data,
  193. struct connectdata *conn, bool dead_connection);
  194. static CURLcode ftp_do_more(struct Curl_easy *data, int *completed);
  195. static CURLcode ftp_multi_statemach(struct Curl_easy *data, bool *done);
  196. static int ftp_getsock(struct Curl_easy *data, struct connectdata *conn,
  197. curl_socket_t *socks);
  198. static int ftp_domore_getsock(struct Curl_easy *data,
  199. struct connectdata *conn, curl_socket_t *socks);
  200. static CURLcode ftp_doing(struct Curl_easy *data,
  201. bool *dophase_done);
  202. static CURLcode ftp_setup_connection(struct Curl_easy *data,
  203. struct connectdata *conn);
  204. static CURLcode init_wc_data(struct Curl_easy *data);
  205. static CURLcode wc_statemach(struct Curl_easy *data);
  206. static void wc_data_dtor(void *ptr);
  207. static CURLcode ftp_state_retr(struct Curl_easy *data, curl_off_t filesize);
  208. static CURLcode ftp_readresp(struct Curl_easy *data,
  209. int sockindex,
  210. struct pingpong *pp,
  211. int *ftpcode,
  212. size_t *size);
  213. static CURLcode ftp_dophase_done(struct Curl_easy *data,
  214. bool connected);
  215. /*
  216. * FTP protocol handler.
  217. */
  218. const struct Curl_handler Curl_handler_ftp = {
  219. "ftp", /* scheme */
  220. ftp_setup_connection, /* setup_connection */
  221. ftp_do, /* do_it */
  222. ftp_done, /* done */
  223. ftp_do_more, /* do_more */
  224. ftp_connect, /* connect_it */
  225. ftp_multi_statemach, /* connecting */
  226. ftp_doing, /* doing */
  227. ftp_getsock, /* proto_getsock */
  228. ftp_getsock, /* doing_getsock */
  229. ftp_domore_getsock, /* domore_getsock */
  230. ZERO_NULL, /* perform_getsock */
  231. ftp_disconnect, /* disconnect */
  232. ZERO_NULL, /* write_resp */
  233. ZERO_NULL, /* write_resp_hd */
  234. ZERO_NULL, /* connection_check */
  235. ZERO_NULL, /* attach connection */
  236. PORT_FTP, /* defport */
  237. CURLPROTO_FTP, /* protocol */
  238. CURLPROTO_FTP, /* family */
  239. PROTOPT_DUAL | PROTOPT_CLOSEACTION | PROTOPT_NEEDSPWD |
  240. PROTOPT_NOURLQUERY | PROTOPT_PROXY_AS_HTTP |
  241. PROTOPT_WILDCARD /* flags */
  242. };
  243. #ifdef USE_SSL
  244. /*
  245. * FTPS protocol handler.
  246. */
  247. const struct Curl_handler Curl_handler_ftps = {
  248. "ftps", /* scheme */
  249. ftp_setup_connection, /* setup_connection */
  250. ftp_do, /* do_it */
  251. ftp_done, /* done */
  252. ftp_do_more, /* do_more */
  253. ftp_connect, /* connect_it */
  254. ftp_multi_statemach, /* connecting */
  255. ftp_doing, /* doing */
  256. ftp_getsock, /* proto_getsock */
  257. ftp_getsock, /* doing_getsock */
  258. ftp_domore_getsock, /* domore_getsock */
  259. ZERO_NULL, /* perform_getsock */
  260. ftp_disconnect, /* disconnect */
  261. ZERO_NULL, /* write_resp */
  262. ZERO_NULL, /* write_resp_hd */
  263. ZERO_NULL, /* connection_check */
  264. ZERO_NULL, /* attach connection */
  265. PORT_FTPS, /* defport */
  266. CURLPROTO_FTPS, /* protocol */
  267. CURLPROTO_FTP, /* family */
  268. PROTOPT_SSL | PROTOPT_DUAL | PROTOPT_CLOSEACTION |
  269. PROTOPT_NEEDSPWD | PROTOPT_NOURLQUERY | PROTOPT_WILDCARD /* flags */
  270. };
  271. #endif
  272. static void close_secondarysocket(struct Curl_easy *data)
  273. {
  274. CURL_TRC_FTP(data, "[%s] closing DATA connection", FTP_DSTATE(data));
  275. Curl_conn_close(data, SECONDARYSOCKET);
  276. Curl_conn_cf_discard_all(data, data->conn, SECONDARYSOCKET);
  277. }
  278. /*
  279. * NOTE: back in the old days, we added code in the FTP code that made NOBODY
  280. * requests on files respond with headers passed to the client/stdout that
  281. * looked like HTTP ones.
  282. *
  283. * This approach is not very elegant, it causes confusion and is error-prone.
  284. * It is subject for removal at the next (or at least a future) soname bump.
  285. * Until then you can test the effects of the removal by undefining the
  286. * following define named CURL_FTP_HTTPSTYLE_HEAD.
  287. */
  288. #define CURL_FTP_HTTPSTYLE_HEAD 1
  289. static void freedirs(struct ftp_conn *ftpc)
  290. {
  291. if(ftpc->dirs) {
  292. int i;
  293. for(i = 0; i < ftpc->dirdepth; i++) {
  294. free(ftpc->dirs[i]);
  295. ftpc->dirs[i] = NULL;
  296. }
  297. free(ftpc->dirs);
  298. ftpc->dirs = NULL;
  299. ftpc->dirdepth = 0;
  300. }
  301. Curl_safefree(ftpc->file);
  302. /* no longer of any use */
  303. Curl_safefree(ftpc->newhost);
  304. }
  305. #ifdef CURL_PREFER_LF_LINEENDS
  306. /***********************************************************************
  307. *
  308. * Lineend Conversions
  309. * On ASCII transfers, e.g. directory listings, we might get lines
  310. * ending in '\r\n' and we prefer just '\n'.
  311. * We might also get a lonely '\r' which we convert into a '\n'.
  312. */
  313. struct ftp_cw_lc_ctx {
  314. struct Curl_cwriter super;
  315. bool newline_pending;
  316. };
  317. static CURLcode ftp_cw_lc_write(struct Curl_easy *data,
  318. struct Curl_cwriter *writer, int type,
  319. const char *buf, size_t blen)
  320. {
  321. static const char nl = '\n';
  322. struct ftp_cw_lc_ctx *ctx = writer->ctx;
  323. if(!(type & CLIENTWRITE_BODY) ||
  324. data->conn->proto.ftpc.transfertype != 'A')
  325. return Curl_cwriter_write(data, writer->next, type, buf, blen);
  326. /* ASCII mode BODY data, convert lineends */
  327. while(blen) {
  328. /* do not pass EOS when writing parts */
  329. int chunk_type = (type & ~CLIENTWRITE_EOS);
  330. const char *cp;
  331. size_t chunk_len;
  332. CURLcode result;
  333. if(ctx->newline_pending) {
  334. if(buf[0] != '\n') {
  335. /* previous chunk ended in '\r' and we do not see a '\n' in this one,
  336. * need to write a newline. */
  337. result = Curl_cwriter_write(data, writer->next, chunk_type, &nl, 1);
  338. if(result)
  339. return result;
  340. }
  341. /* either we just wrote the newline or it is part of the next
  342. * chunk of bytes we write. */
  343. ctx->newline_pending = FALSE;
  344. }
  345. cp = memchr(buf, '\r', blen);
  346. if(!cp)
  347. break;
  348. /* write the bytes before the '\r', excluding the '\r' */
  349. chunk_len = cp - buf;
  350. if(chunk_len) {
  351. result = Curl_cwriter_write(data, writer->next, chunk_type,
  352. buf, chunk_len);
  353. if(result)
  354. return result;
  355. }
  356. /* skip the '\r', we now have a newline pending */
  357. buf = cp + 1;
  358. blen = blen - chunk_len - 1;
  359. ctx->newline_pending = TRUE;
  360. }
  361. /* Any remaining data does not contain a '\r' */
  362. if(blen) {
  363. DEBUGASSERT(!ctx->newline_pending);
  364. return Curl_cwriter_write(data, writer->next, type, buf, blen);
  365. }
  366. else if(type & CLIENTWRITE_EOS) {
  367. /* EndOfStream, if we have a trailing cr, now is the time to write it */
  368. if(ctx->newline_pending) {
  369. ctx->newline_pending = FALSE;
  370. return Curl_cwriter_write(data, writer->next, type, &nl, 1);
  371. }
  372. /* Always pass on the EOS type indicator */
  373. return Curl_cwriter_write(data, writer->next, type, buf, 0);
  374. }
  375. return CURLE_OK;
  376. }
  377. static const struct Curl_cwtype ftp_cw_lc = {
  378. "ftp-lineconv",
  379. NULL,
  380. Curl_cwriter_def_init,
  381. ftp_cw_lc_write,
  382. Curl_cwriter_def_close,
  383. sizeof(struct ftp_cw_lc_ctx)
  384. };
  385. #endif /* CURL_PREFER_LF_LINEENDS */
  386. /***********************************************************************
  387. *
  388. * AcceptServerConnect()
  389. *
  390. * After connection request is received from the server this function is
  391. * called to accept the connection and close the listening socket
  392. *
  393. */
  394. static CURLcode AcceptServerConnect(struct Curl_easy *data)
  395. {
  396. struct connectdata *conn = data->conn;
  397. curl_socket_t sock = conn->sock[SECONDARYSOCKET];
  398. curl_socket_t s = CURL_SOCKET_BAD;
  399. #ifdef USE_IPV6
  400. struct Curl_sockaddr_storage add;
  401. #else
  402. struct sockaddr_in add;
  403. #endif
  404. curl_socklen_t size = (curl_socklen_t) sizeof(add);
  405. CURLcode result;
  406. if(0 == getsockname(sock, (struct sockaddr *) &add, &size)) {
  407. size = sizeof(add);
  408. s = accept(sock, (struct sockaddr *) &add, &size);
  409. }
  410. if(CURL_SOCKET_BAD == s) {
  411. failf(data, "Error accept()ing server connect");
  412. return CURLE_FTP_PORT_FAILED;
  413. }
  414. infof(data, "Connection accepted from server");
  415. /* when this happens within the DO state it is important that we mark us as
  416. not needing DO_MORE anymore */
  417. conn->bits.do_more = FALSE;
  418. (void)curlx_nonblock(s, TRUE); /* enable non-blocking */
  419. /* Replace any filter on SECONDARY with one listening on this socket */
  420. result = Curl_conn_tcp_accepted_set(data, conn, SECONDARYSOCKET, &s);
  421. if(result) {
  422. sclose(s);
  423. return result;
  424. }
  425. if(data->set.fsockopt) {
  426. int error = 0;
  427. /* activate callback for setting socket options */
  428. Curl_set_in_callback(data, true);
  429. error = data->set.fsockopt(data->set.sockopt_client,
  430. s,
  431. CURLSOCKTYPE_ACCEPT);
  432. Curl_set_in_callback(data, false);
  433. if(error) {
  434. close_secondarysocket(data);
  435. return CURLE_ABORTED_BY_CALLBACK;
  436. }
  437. }
  438. return CURLE_OK;
  439. }
  440. /*
  441. * ftp_timeleft_accept() returns the amount of milliseconds left allowed for
  442. * waiting server to connect. If the value is negative, the timeout time has
  443. * already elapsed.
  444. *
  445. * The start time is stored in progress.t_acceptdata - as set with
  446. * Curl_pgrsTime(..., TIMER_STARTACCEPT);
  447. *
  448. */
  449. static timediff_t ftp_timeleft_accept(struct Curl_easy *data)
  450. {
  451. timediff_t timeout_ms = DEFAULT_ACCEPT_TIMEOUT;
  452. timediff_t other;
  453. struct curltime now;
  454. if(data->set.accepttimeout > 0)
  455. timeout_ms = data->set.accepttimeout;
  456. now = Curl_now();
  457. /* check if the generic timeout possibly is set shorter */
  458. other = Curl_timeleft(data, &now, FALSE);
  459. if(other && (other < timeout_ms))
  460. /* note that this also works fine for when other happens to be negative
  461. due to it already having elapsed */
  462. timeout_ms = other;
  463. else {
  464. /* subtract elapsed time */
  465. timeout_ms -= Curl_timediff(now, data->progress.t_acceptdata);
  466. if(!timeout_ms)
  467. /* avoid returning 0 as that means no timeout! */
  468. return -1;
  469. }
  470. return timeout_ms;
  471. }
  472. /***********************************************************************
  473. *
  474. * ReceivedServerConnect()
  475. *
  476. * After allowing server to connect to us from data port, this function
  477. * checks both data connection for connection establishment and ctrl
  478. * connection for a negative response regarding a failure in connecting
  479. *
  480. */
  481. static CURLcode ReceivedServerConnect(struct Curl_easy *data, bool *received)
  482. {
  483. struct connectdata *conn = data->conn;
  484. curl_socket_t ctrl_sock = conn->sock[FIRSTSOCKET];
  485. curl_socket_t data_sock = conn->sock[SECONDARYSOCKET];
  486. struct ftp_conn *ftpc = &conn->proto.ftpc;
  487. struct pingpong *pp = &ftpc->pp;
  488. int socketstate = 0;
  489. timediff_t timeout_ms;
  490. ssize_t nread;
  491. int ftpcode;
  492. bool response = FALSE;
  493. *received = FALSE;
  494. timeout_ms = ftp_timeleft_accept(data);
  495. infof(data, "Checking for server connect");
  496. if(timeout_ms < 0) {
  497. /* if a timeout was already reached, bail out */
  498. failf(data, "Accept timeout occurred while waiting server connect");
  499. return CURLE_FTP_ACCEPT_TIMEOUT;
  500. }
  501. /* First check whether there is a cached response from server */
  502. if(Curl_dyn_len(&pp->recvbuf) && (*Curl_dyn_ptr(&pp->recvbuf) > '3')) {
  503. /* Data connection could not be established, let's return */
  504. infof(data, "There is negative response in cache while serv connect");
  505. (void)Curl_GetFTPResponse(data, &nread, &ftpcode);
  506. return CURLE_FTP_ACCEPT_FAILED;
  507. }
  508. if(pp->overflow)
  509. /* there is pending control data still in the buffer to read */
  510. response = TRUE;
  511. else
  512. socketstate = Curl_socket_check(ctrl_sock, data_sock, CURL_SOCKET_BAD, 0);
  513. /* see if the connection request is already here */
  514. switch(socketstate) {
  515. case -1: /* error */
  516. /* let's die here */
  517. failf(data, "Error while waiting for server connect");
  518. return CURLE_FTP_ACCEPT_FAILED;
  519. case 0: /* Server connect is not received yet */
  520. break; /* loop */
  521. default:
  522. if(socketstate & CURL_CSELECT_IN2) {
  523. infof(data, "Ready to accept data connection from server");
  524. *received = TRUE;
  525. }
  526. else if(socketstate & CURL_CSELECT_IN)
  527. response = TRUE;
  528. break;
  529. }
  530. if(response) {
  531. infof(data, "Ctrl conn has data while waiting for data conn");
  532. if(pp->overflow > 3) {
  533. char *r = Curl_dyn_ptr(&pp->recvbuf);
  534. DEBUGASSERT((pp->overflow + pp->nfinal) <=
  535. Curl_dyn_len(&pp->recvbuf));
  536. /* move over the most recently handled response line */
  537. r += pp->nfinal;
  538. if(LASTLINE(r)) {
  539. int status = curlx_sltosi(strtol(r, NULL, 10));
  540. if(status == 226) {
  541. /* funny timing situation where we get the final message on the
  542. control connection before traffic on the data connection has been
  543. noticed. Leave the 226 in there and use this as a trigger to read
  544. the data socket. */
  545. infof(data, "Got 226 before data activity");
  546. *received = TRUE;
  547. return CURLE_OK;
  548. }
  549. }
  550. }
  551. (void)Curl_GetFTPResponse(data, &nread, &ftpcode);
  552. infof(data, "FTP code: %03d", ftpcode);
  553. if(ftpcode/100 > 3)
  554. return CURLE_FTP_ACCEPT_FAILED;
  555. return CURLE_WEIRD_SERVER_REPLY;
  556. }
  557. return CURLE_OK;
  558. }
  559. /***********************************************************************
  560. *
  561. * InitiateTransfer()
  562. *
  563. * After connection from server is accepted this function is called to
  564. * setup transfer parameters and initiate the data transfer.
  565. *
  566. */
  567. static CURLcode InitiateTransfer(struct Curl_easy *data)
  568. {
  569. CURLcode result = CURLE_OK;
  570. struct connectdata *conn = data->conn;
  571. bool connected;
  572. CURL_TRC_FTP(data, "InitiateTransfer()");
  573. if(conn->bits.ftp_use_data_ssl && data->set.ftp_use_port &&
  574. !Curl_conn_is_ssl(conn, SECONDARYSOCKET)) {
  575. result = Curl_ssl_cfilter_add(data, conn, SECONDARYSOCKET);
  576. if(result)
  577. return result;
  578. }
  579. result = Curl_conn_connect(data, SECONDARYSOCKET, TRUE, &connected);
  580. if(result || !connected)
  581. return result;
  582. if(conn->proto.ftpc.state_saved == FTP_STOR) {
  583. /* When we know we are uploading a specified file, we can get the file
  584. size prior to the actual upload. */
  585. Curl_pgrsSetUploadSize(data, data->state.infilesize);
  586. /* set the SO_SNDBUF for the secondary socket for those who need it */
  587. Curl_sndbuf_init(conn->sock[SECONDARYSOCKET]);
  588. Curl_xfer_setup2(data, CURL_XFER_SEND, -1, TRUE);
  589. }
  590. else {
  591. /* FTP download: */
  592. Curl_xfer_setup2(data, CURL_XFER_RECV,
  593. conn->proto.ftpc.retr_size_saved, TRUE);
  594. }
  595. conn->proto.ftpc.pp.pending_resp = TRUE; /* expect server response */
  596. ftp_state(data, FTP_STOP);
  597. return CURLE_OK;
  598. }
  599. /***********************************************************************
  600. *
  601. * AllowServerConnect()
  602. *
  603. * When we have issue the PORT command, we have told the server to connect to
  604. * us. This function checks whether data connection is established if so it is
  605. * accepted.
  606. *
  607. */
  608. static CURLcode AllowServerConnect(struct Curl_easy *data, bool *connected)
  609. {
  610. timediff_t timeout_ms;
  611. CURLcode result = CURLE_OK;
  612. *connected = FALSE;
  613. infof(data, "Preparing for accepting server on data port");
  614. /* Save the time we start accepting server connect */
  615. Curl_pgrsTime(data, TIMER_STARTACCEPT);
  616. timeout_ms = ftp_timeleft_accept(data);
  617. if(timeout_ms < 0) {
  618. /* if a timeout was already reached, bail out */
  619. failf(data, "Accept timeout occurred while waiting server connect");
  620. result = CURLE_FTP_ACCEPT_TIMEOUT;
  621. goto out;
  622. }
  623. /* see if the connection request is already here */
  624. result = ReceivedServerConnect(data, connected);
  625. if(result)
  626. goto out;
  627. if(*connected) {
  628. result = AcceptServerConnect(data);
  629. if(result)
  630. goto out;
  631. result = InitiateTransfer(data);
  632. if(result)
  633. goto out;
  634. }
  635. else {
  636. /* Add timeout to multi handle and break out of the loop */
  637. Curl_expire(data, data->set.accepttimeout ?
  638. data->set.accepttimeout: DEFAULT_ACCEPT_TIMEOUT,
  639. EXPIRE_FTP_ACCEPT);
  640. }
  641. out:
  642. CURL_TRC_FTP(data, "AllowServerConnect() -> %d", result);
  643. return result;
  644. }
  645. static bool ftp_endofresp(struct Curl_easy *data, struct connectdata *conn,
  646. char *line, size_t len, int *code)
  647. {
  648. (void)data;
  649. (void)conn;
  650. if((len > 3) && LASTLINE(line)) {
  651. *code = curlx_sltosi(strtol(line, NULL, 10));
  652. return TRUE;
  653. }
  654. return FALSE;
  655. }
  656. static CURLcode ftp_readresp(struct Curl_easy *data,
  657. int sockindex,
  658. struct pingpong *pp,
  659. int *ftpcode, /* return the ftp-code if done */
  660. size_t *size) /* size of the response */
  661. {
  662. int code;
  663. CURLcode result = Curl_pp_readresp(data, sockindex, pp, &code, size);
  664. #ifdef HAVE_GSSAPI
  665. {
  666. struct connectdata *conn = data->conn;
  667. char * const buf = Curl_dyn_ptr(&data->conn->proto.ftpc.pp.recvbuf);
  668. /* handle the security-oriented responses 6xx ***/
  669. switch(code) {
  670. case 631:
  671. code = Curl_sec_read_msg(data, conn, buf, PROT_SAFE);
  672. break;
  673. case 632:
  674. code = Curl_sec_read_msg(data, conn, buf, PROT_PRIVATE);
  675. break;
  676. case 633:
  677. code = Curl_sec_read_msg(data, conn, buf, PROT_CONFIDENTIAL);
  678. break;
  679. default:
  680. /* normal ftp stuff we pass through! */
  681. break;
  682. }
  683. }
  684. #endif
  685. /* store the latest code for later retrieval */
  686. data->info.httpcode = code;
  687. if(ftpcode)
  688. *ftpcode = code;
  689. if(421 == code) {
  690. /* 421 means "Service not available, closing control connection." and FTP
  691. * servers use it to signal that idle session timeout has been exceeded.
  692. * If we ignored the response, it could end up hanging in some cases.
  693. *
  694. * This response code can come at any point so having it treated
  695. * generically is a good idea.
  696. */
  697. infof(data, "We got a 421 - timeout");
  698. ftp_state(data, FTP_STOP);
  699. return CURLE_OPERATION_TIMEDOUT;
  700. }
  701. return result;
  702. }
  703. /* --- parse FTP server responses --- */
  704. /*
  705. * Curl_GetFTPResponse() is a BLOCKING function to read the full response
  706. * from a server after a command.
  707. *
  708. */
  709. CURLcode Curl_GetFTPResponse(struct Curl_easy *data,
  710. ssize_t *nreadp, /* return number of bytes read */
  711. int *ftpcode) /* return the ftp-code */
  712. {
  713. /*
  714. * We cannot read just one byte per read() and then go back to select() as
  715. * the OpenSSL read() does not grok that properly.
  716. *
  717. * Alas, read as much as possible, split up into lines, use the ending
  718. * line in a response or continue reading. */
  719. struct connectdata *conn = data->conn;
  720. curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
  721. CURLcode result = CURLE_OK;
  722. struct ftp_conn *ftpc = &conn->proto.ftpc;
  723. struct pingpong *pp = &ftpc->pp;
  724. size_t nread;
  725. int cache_skip = 0;
  726. int value_to_be_ignored = 0;
  727. CURL_TRC_FTP(data, "getFTPResponse start");
  728. if(ftpcode)
  729. *ftpcode = 0; /* 0 for errors */
  730. else
  731. /* make the pointer point to something for the rest of this function */
  732. ftpcode = &value_to_be_ignored;
  733. *nreadp = 0;
  734. while(!*ftpcode && !result) {
  735. /* check and reset timeout value every lap */
  736. timediff_t timeout = Curl_pp_state_timeout(data, pp, FALSE);
  737. timediff_t interval_ms;
  738. if(timeout <= 0) {
  739. failf(data, "FTP response timeout");
  740. return CURLE_OPERATION_TIMEDOUT; /* already too little time */
  741. }
  742. interval_ms = 1000; /* use 1 second timeout intervals */
  743. if(timeout < interval_ms)
  744. interval_ms = timeout;
  745. /*
  746. * Since this function is blocking, we need to wait here for input on the
  747. * connection and only then we call the response reading function. We do
  748. * timeout at least every second to make the timeout check run.
  749. *
  750. * A caution here is that the ftp_readresp() function has a cache that may
  751. * contain pieces of a response from the previous invoke and we need to
  752. * make sure we do not just wait for input while there is unhandled data in
  753. * that cache. But also, if the cache is there, we call ftp_readresp() and
  754. * the cache was not good enough to continue we must not just busy-loop
  755. * around this function.
  756. *
  757. */
  758. if(Curl_dyn_len(&pp->recvbuf) && (cache_skip < 2)) {
  759. /*
  760. * There is a cache left since before. We then skipping the wait for
  761. * socket action, unless this is the same cache like the previous round
  762. * as then the cache was deemed not enough to act on and we then need to
  763. * wait for more data anyway.
  764. */
  765. }
  766. else if(!Curl_conn_data_pending(data, FIRSTSOCKET)) {
  767. curl_socket_t wsock = Curl_pp_needs_flush(data, pp)?
  768. sockfd : CURL_SOCKET_BAD;
  769. int ev = Curl_socket_check(sockfd, CURL_SOCKET_BAD, wsock, interval_ms);
  770. if(ev < 0) {
  771. failf(data, "FTP response aborted due to select/poll error: %d",
  772. SOCKERRNO);
  773. return CURLE_RECV_ERROR;
  774. }
  775. else if(ev == 0) {
  776. if(Curl_pgrsUpdate(data))
  777. return CURLE_ABORTED_BY_CALLBACK;
  778. continue; /* just continue in our loop for the timeout duration */
  779. }
  780. }
  781. if(Curl_pp_needs_flush(data, pp)) {
  782. result = Curl_pp_flushsend(data, pp);
  783. if(result)
  784. break;
  785. }
  786. result = ftp_readresp(data, FIRSTSOCKET, pp, ftpcode, &nread);
  787. if(result)
  788. break;
  789. if(!nread && Curl_dyn_len(&pp->recvbuf))
  790. /* bump cache skip counter as on repeated skips we must wait for more
  791. data */
  792. cache_skip++;
  793. else
  794. /* when we got data or there is no cache left, we reset the cache skip
  795. counter */
  796. cache_skip = 0;
  797. *nreadp += nread;
  798. } /* while there is buffer left and loop is requested */
  799. pp->pending_resp = FALSE;
  800. CURL_TRC_FTP(data, "getFTPResponse -> result=%d, nread=%zd, ftpcode=%d",
  801. result, *nreadp, *ftpcode);
  802. return result;
  803. }
  804. static CURLcode ftp_state_user(struct Curl_easy *data,
  805. struct connectdata *conn)
  806. {
  807. CURLcode result = Curl_pp_sendf(data,
  808. &conn->proto.ftpc.pp, "USER %s",
  809. conn->user?conn->user:"");
  810. if(!result) {
  811. struct ftp_conn *ftpc = &conn->proto.ftpc;
  812. ftpc->ftp_trying_alternative = FALSE;
  813. ftp_state(data, FTP_USER);
  814. }
  815. return result;
  816. }
  817. static CURLcode ftp_state_pwd(struct Curl_easy *data,
  818. struct connectdata *conn)
  819. {
  820. CURLcode result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", "PWD");
  821. if(!result)
  822. ftp_state(data, FTP_PWD);
  823. return result;
  824. }
  825. /* For the FTP "protocol connect" and "doing" phases only */
  826. static int ftp_getsock(struct Curl_easy *data,
  827. struct connectdata *conn,
  828. curl_socket_t *socks)
  829. {
  830. return Curl_pp_getsock(data, &conn->proto.ftpc.pp, socks);
  831. }
  832. /* For the FTP "DO_MORE" phase only */
  833. static int ftp_domore_getsock(struct Curl_easy *data,
  834. struct connectdata *conn, curl_socket_t *socks)
  835. {
  836. struct ftp_conn *ftpc = &conn->proto.ftpc;
  837. (void)data;
  838. /* When in DO_MORE state, we could be either waiting for us to connect to a
  839. * remote site, or we could wait for that site to connect to us. Or just
  840. * handle ordinary commands.
  841. */
  842. CURL_TRC_FTP(data, "[%s] ftp_domore_getsock()", FTP_DSTATE(data));
  843. if(FTP_STOP == ftpc->state) {
  844. /* if stopped and still in this state, then we are also waiting for a
  845. connect on the secondary connection */
  846. DEBUGASSERT(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD ||
  847. (conn->cfilter[SECONDARYSOCKET] &&
  848. !Curl_conn_is_connected(conn, SECONDARYSOCKET)));
  849. socks[0] = conn->sock[FIRSTSOCKET];
  850. /* An unconnected SECONDARY will add its socket by itself
  851. * via its adjust_pollset() */
  852. return GETSOCK_READSOCK(0);
  853. }
  854. return Curl_pp_getsock(data, &conn->proto.ftpc.pp, socks);
  855. }
  856. /* This is called after the FTP_QUOTE state is passed.
  857. ftp_state_cwd() sends the range of CWD commands to the server to change to
  858. the correct directory. It may also need to send MKD commands to create
  859. missing ones, if that option is enabled.
  860. */
  861. static CURLcode ftp_state_cwd(struct Curl_easy *data,
  862. struct connectdata *conn)
  863. {
  864. CURLcode result = CURLE_OK;
  865. struct ftp_conn *ftpc = &conn->proto.ftpc;
  866. if(ftpc->cwddone)
  867. /* already done and fine */
  868. result = ftp_state_mdtm(data);
  869. else {
  870. /* FTPFILE_NOCWD with full path: expect ftpc->cwddone! */
  871. DEBUGASSERT((data->set.ftp_filemethod != FTPFILE_NOCWD) ||
  872. !(ftpc->dirdepth && ftpc->dirs[0][0] == '/'));
  873. ftpc->count2 = 0; /* count2 counts failed CWDs */
  874. if(conn->bits.reuse && ftpc->entrypath &&
  875. /* no need to go to entrypath when we have an absolute path */
  876. !(ftpc->dirdepth && ftpc->dirs[0][0] == '/')) {
  877. /* This is a reused connection. Since we change directory to where the
  878. transfer is taking place, we must first get back to the original dir
  879. where we ended up after login: */
  880. ftpc->cwdcount = 0; /* we count this as the first path, then we add one
  881. for all upcoming ones in the ftp->dirs[] array */
  882. result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s", ftpc->entrypath);
  883. if(!result)
  884. ftp_state(data, FTP_CWD);
  885. }
  886. else {
  887. if(ftpc->dirdepth) {
  888. ftpc->cwdcount = 1;
  889. /* issue the first CWD, the rest is sent when the CWD responses are
  890. received... */
  891. result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s",
  892. ftpc->dirs[ftpc->cwdcount -1]);
  893. if(!result)
  894. ftp_state(data, FTP_CWD);
  895. }
  896. else {
  897. /* No CWD necessary */
  898. result = ftp_state_mdtm(data);
  899. }
  900. }
  901. }
  902. return result;
  903. }
  904. typedef enum {
  905. EPRT,
  906. PORT,
  907. DONE
  908. } ftpport;
  909. static CURLcode ftp_state_use_port(struct Curl_easy *data,
  910. ftpport fcmd) /* start with this */
  911. {
  912. CURLcode result = CURLE_FTP_PORT_FAILED;
  913. struct connectdata *conn = data->conn;
  914. struct ftp_conn *ftpc = &conn->proto.ftpc;
  915. curl_socket_t portsock = CURL_SOCKET_BAD;
  916. char myhost[MAX_IPADR_LEN + 1] = "";
  917. struct Curl_sockaddr_storage ss;
  918. struct Curl_addrinfo *res, *ai;
  919. curl_socklen_t sslen;
  920. char hbuf[NI_MAXHOST];
  921. struct sockaddr *sa = (struct sockaddr *)&ss;
  922. struct sockaddr_in * const sa4 = (void *)sa;
  923. #ifdef USE_IPV6
  924. struct sockaddr_in6 * const sa6 = (void *)sa;
  925. #endif
  926. static const char mode[][5] = { "EPRT", "PORT" };
  927. enum resolve_t rc;
  928. int error;
  929. char *host = NULL;
  930. char *string_ftpport = data->set.str[STRING_FTPPORT];
  931. struct Curl_dns_entry *dns_entry = NULL;
  932. unsigned short port_min = 0;
  933. unsigned short port_max = 0;
  934. unsigned short port;
  935. bool possibly_non_local = TRUE;
  936. char buffer[STRERROR_LEN];
  937. char *addr = NULL;
  938. size_t addrlen = 0;
  939. char ipstr[50];
  940. /* Step 1, figure out what is requested,
  941. * accepted format :
  942. * (ipv4|ipv6|domain|interface)?(:port(-range)?)?
  943. */
  944. if(data->set.str[STRING_FTPPORT] &&
  945. (strlen(data->set.str[STRING_FTPPORT]) > 1)) {
  946. char *ip_end = NULL;
  947. #ifdef USE_IPV6
  948. if(*string_ftpport == '[') {
  949. /* [ipv6]:port(-range) */
  950. char *ip_start = string_ftpport + 1;
  951. ip_end = strchr(ip_start, ']');
  952. if(ip_end) {
  953. addrlen = ip_end - ip_start;
  954. addr = ip_start;
  955. }
  956. }
  957. else
  958. #endif
  959. if(*string_ftpport == ':') {
  960. /* :port */
  961. ip_end = string_ftpport;
  962. }
  963. else {
  964. ip_end = strchr(string_ftpport, ':');
  965. addr = string_ftpport;
  966. if(ip_end) {
  967. /* either ipv6 or (ipv4|domain|interface):port(-range) */
  968. addrlen = ip_end - string_ftpport;
  969. #ifdef USE_IPV6
  970. if(Curl_inet_pton(AF_INET6, string_ftpport, &sa6->sin6_addr) == 1) {
  971. /* ipv6 */
  972. port_min = port_max = 0;
  973. ip_end = NULL; /* this got no port ! */
  974. }
  975. #endif
  976. }
  977. else
  978. /* ipv4|interface */
  979. addrlen = strlen(string_ftpport);
  980. }
  981. /* parse the port */
  982. if(ip_end) {
  983. char *port_sep = NULL;
  984. char *port_start = strchr(ip_end, ':');
  985. if(port_start) {
  986. port_min = curlx_ultous(strtoul(port_start + 1, NULL, 10));
  987. port_sep = strchr(port_start, '-');
  988. if(port_sep) {
  989. port_max = curlx_ultous(strtoul(port_sep + 1, NULL, 10));
  990. }
  991. else
  992. port_max = port_min;
  993. }
  994. }
  995. /* correct errors like:
  996. * :1234-1230
  997. * :-4711, in this case port_min is (unsigned)-1,
  998. * therefore port_min > port_max for all cases
  999. * but port_max = (unsigned)-1
  1000. */
  1001. if(port_min > port_max)
  1002. port_min = port_max = 0;
  1003. if(addrlen) {
  1004. DEBUGASSERT(addr);
  1005. if(addrlen >= sizeof(ipstr))
  1006. goto out;
  1007. memcpy(ipstr, addr, addrlen);
  1008. ipstr[addrlen] = 0;
  1009. /* attempt to get the address of the given interface name */
  1010. switch(Curl_if2ip(conn->remote_addr->family,
  1011. #ifdef USE_IPV6
  1012. Curl_ipv6_scope(&conn->remote_addr->sa_addr),
  1013. conn->scope_id,
  1014. #endif
  1015. ipstr, hbuf, sizeof(hbuf))) {
  1016. case IF2IP_NOT_FOUND:
  1017. /* not an interface, use the given string as hostname instead */
  1018. host = ipstr;
  1019. break;
  1020. case IF2IP_AF_NOT_SUPPORTED:
  1021. goto out;
  1022. case IF2IP_FOUND:
  1023. host = hbuf; /* use the hbuf for hostname */
  1024. break;
  1025. }
  1026. }
  1027. else
  1028. /* there was only a port(-range) given, default the host */
  1029. host = NULL;
  1030. } /* data->set.ftpport */
  1031. if(!host) {
  1032. const char *r;
  1033. /* not an interface and not a hostname, get default by extracting
  1034. the IP from the control connection */
  1035. sslen = sizeof(ss);
  1036. if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) {
  1037. failf(data, "getsockname() failed: %s",
  1038. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  1039. goto out;
  1040. }
  1041. switch(sa->sa_family) {
  1042. #ifdef USE_IPV6
  1043. case AF_INET6:
  1044. r = Curl_inet_ntop(sa->sa_family, &sa6->sin6_addr, hbuf, sizeof(hbuf));
  1045. break;
  1046. #endif
  1047. default:
  1048. r = Curl_inet_ntop(sa->sa_family, &sa4->sin_addr, hbuf, sizeof(hbuf));
  1049. break;
  1050. }
  1051. if(!r) {
  1052. goto out;
  1053. }
  1054. host = hbuf; /* use this hostname */
  1055. possibly_non_local = FALSE; /* we know it is local now */
  1056. }
  1057. /* resolv ip/host to ip */
  1058. rc = Curl_resolv(data, host, 0, FALSE, &dns_entry);
  1059. if(rc == CURLRESOLV_PENDING)
  1060. (void)Curl_resolver_wait_resolv(data, &dns_entry);
  1061. if(dns_entry) {
  1062. res = dns_entry->addr;
  1063. }
  1064. else
  1065. res = NULL; /* failure! */
  1066. if(!res) {
  1067. failf(data, "failed to resolve the address provided to PORT: %s", host);
  1068. goto out;
  1069. }
  1070. host = NULL;
  1071. /* step 2, create a socket for the requested address */
  1072. error = 0;
  1073. for(ai = res; ai; ai = ai->ai_next) {
  1074. if(Curl_socket_open(data, ai, NULL, conn->transport, &portsock)) {
  1075. error = SOCKERRNO;
  1076. continue;
  1077. }
  1078. break;
  1079. }
  1080. if(!ai) {
  1081. failf(data, "socket failure: %s",
  1082. Curl_strerror(error, buffer, sizeof(buffer)));
  1083. goto out;
  1084. }
  1085. CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), opened socket",
  1086. FTP_DSTATE(data));
  1087. /* step 3, bind to a suitable local address */
  1088. memcpy(sa, ai->ai_addr, ai->ai_addrlen);
  1089. sslen = ai->ai_addrlen;
  1090. for(port = port_min; port <= port_max;) {
  1091. if(sa->sa_family == AF_INET)
  1092. sa4->sin_port = htons(port);
  1093. #ifdef USE_IPV6
  1094. else
  1095. sa6->sin6_port = htons(port);
  1096. #endif
  1097. /* Try binding the given address. */
  1098. if(bind(portsock, sa, sslen) ) {
  1099. /* It failed. */
  1100. error = SOCKERRNO;
  1101. if(possibly_non_local && (error == EADDRNOTAVAIL)) {
  1102. /* The requested bind address is not local. Use the address used for
  1103. * the control connection instead and restart the port loop
  1104. */
  1105. infof(data, "bind(port=%hu) on non-local address failed: %s", port,
  1106. Curl_strerror(error, buffer, sizeof(buffer)));
  1107. sslen = sizeof(ss);
  1108. if(getsockname(conn->sock[FIRSTSOCKET], sa, &sslen)) {
  1109. failf(data, "getsockname() failed: %s",
  1110. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  1111. goto out;
  1112. }
  1113. port = port_min;
  1114. possibly_non_local = FALSE; /* do not try this again */
  1115. continue;
  1116. }
  1117. if(error != EADDRINUSE && error != EACCES) {
  1118. failf(data, "bind(port=%hu) failed: %s", port,
  1119. Curl_strerror(error, buffer, sizeof(buffer)));
  1120. goto out;
  1121. }
  1122. }
  1123. else
  1124. break;
  1125. port++;
  1126. }
  1127. /* maybe all ports were in use already */
  1128. if(port > port_max) {
  1129. failf(data, "bind() failed, we ran out of ports");
  1130. goto out;
  1131. }
  1132. /* get the name again after the bind() so that we can extract the
  1133. port number it uses now */
  1134. sslen = sizeof(ss);
  1135. if(getsockname(portsock, sa, &sslen)) {
  1136. failf(data, "getsockname() failed: %s",
  1137. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  1138. goto out;
  1139. }
  1140. CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), socket bound to port %d",
  1141. FTP_DSTATE(data), port);
  1142. /* step 4, listen on the socket */
  1143. if(listen(portsock, 1)) {
  1144. failf(data, "socket failure: %s",
  1145. Curl_strerror(SOCKERRNO, buffer, sizeof(buffer)));
  1146. goto out;
  1147. }
  1148. CURL_TRC_FTP(data, "[%s] ftp_state_use_port(), listening on %d",
  1149. FTP_DSTATE(data), port);
  1150. /* step 5, send the proper FTP command */
  1151. /* get a plain printable version of the numerical address to work with
  1152. below */
  1153. Curl_printable_address(ai, myhost, sizeof(myhost));
  1154. #ifdef USE_IPV6
  1155. if(!conn->bits.ftp_use_eprt && conn->bits.ipv6)
  1156. /* EPRT is disabled but we are connected to a IPv6 host, so we ignore the
  1157. request and enable EPRT again! */
  1158. conn->bits.ftp_use_eprt = TRUE;
  1159. #endif
  1160. /* Replace any filter on SECONDARY with one listening on this socket */
  1161. result = Curl_conn_tcp_listen_set(data, conn, SECONDARYSOCKET, &portsock);
  1162. if(result)
  1163. goto out;
  1164. portsock = CURL_SOCKET_BAD; /* now held in filter */
  1165. for(; fcmd != DONE; fcmd++) {
  1166. if(!conn->bits.ftp_use_eprt && (EPRT == fcmd))
  1167. /* if disabled, goto next */
  1168. continue;
  1169. if((PORT == fcmd) && sa->sa_family != AF_INET)
  1170. /* PORT is IPv4 only */
  1171. continue;
  1172. switch(sa->sa_family) {
  1173. case AF_INET:
  1174. port = ntohs(sa4->sin_port);
  1175. break;
  1176. #ifdef USE_IPV6
  1177. case AF_INET6:
  1178. port = ntohs(sa6->sin6_port);
  1179. break;
  1180. #endif
  1181. default:
  1182. continue; /* might as well skip this */
  1183. }
  1184. if(EPRT == fcmd) {
  1185. /*
  1186. * Two fine examples from RFC2428;
  1187. *
  1188. * EPRT |1|132.235.1.2|6275|
  1189. *
  1190. * EPRT |2|1080::8:800:200C:417A|5282|
  1191. */
  1192. result = Curl_pp_sendf(data, &ftpc->pp, "%s |%d|%s|%hu|", mode[fcmd],
  1193. sa->sa_family == AF_INET?1:2,
  1194. myhost, port);
  1195. if(result) {
  1196. failf(data, "Failure sending EPRT command: %s",
  1197. curl_easy_strerror(result));
  1198. goto out;
  1199. }
  1200. break;
  1201. }
  1202. if(PORT == fcmd) {
  1203. /* large enough for [IP address],[num],[num] */
  1204. char target[sizeof(myhost) + 20];
  1205. char *source = myhost;
  1206. char *dest = target;
  1207. /* translate x.x.x.x to x,x,x,x */
  1208. while(*source) {
  1209. if(*source == '.')
  1210. *dest = ',';
  1211. else
  1212. *dest = *source;
  1213. dest++;
  1214. source++;
  1215. }
  1216. *dest = 0;
  1217. msnprintf(dest, 20, ",%d,%d", (int)(port>>8), (int)(port&0xff));
  1218. result = Curl_pp_sendf(data, &ftpc->pp, "%s %s", mode[fcmd], target);
  1219. if(result) {
  1220. failf(data, "Failure sending PORT command: %s",
  1221. curl_easy_strerror(result));
  1222. goto out;
  1223. }
  1224. break;
  1225. }
  1226. }
  1227. /* store which command was sent */
  1228. ftpc->count1 = fcmd;
  1229. ftp_state(data, FTP_PORT);
  1230. out:
  1231. /* If we looked up a dns_entry, now is the time to safely release it */
  1232. if(dns_entry)
  1233. Curl_resolv_unlink(data, &dns_entry);
  1234. if(result) {
  1235. ftp_state(data, FTP_STOP);
  1236. }
  1237. if(portsock != CURL_SOCKET_BAD)
  1238. Curl_socket_close(data, conn, portsock);
  1239. return result;
  1240. }
  1241. static CURLcode ftp_state_use_pasv(struct Curl_easy *data,
  1242. struct connectdata *conn)
  1243. {
  1244. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1245. CURLcode result = CURLE_OK;
  1246. /*
  1247. Here's the executive summary on what to do:
  1248. PASV is RFC959, expect:
  1249. 227 Entering Passive Mode (a1,a2,a3,a4,p1,p2)
  1250. LPSV is RFC1639, expect:
  1251. 228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2)
  1252. EPSV is RFC2428, expect:
  1253. 229 Entering Extended Passive Mode (|||port|)
  1254. */
  1255. static const char mode[][5] = { "EPSV", "PASV" };
  1256. int modeoff;
  1257. #ifdef PF_INET6
  1258. if(!conn->bits.ftp_use_epsv && conn->bits.ipv6)
  1259. /* EPSV is disabled but we are connected to a IPv6 host, so we ignore the
  1260. request and enable EPSV again! */
  1261. conn->bits.ftp_use_epsv = TRUE;
  1262. #endif
  1263. modeoff = conn->bits.ftp_use_epsv?0:1;
  1264. result = Curl_pp_sendf(data, &ftpc->pp, "%s", mode[modeoff]);
  1265. if(!result) {
  1266. ftpc->count1 = modeoff;
  1267. ftp_state(data, FTP_PASV);
  1268. infof(data, "Connect data stream passively");
  1269. }
  1270. return result;
  1271. }
  1272. /*
  1273. * ftp_state_prepare_transfer() starts PORT, PASV or PRET etc.
  1274. *
  1275. * REST is the last command in the chain of commands when a "head"-like
  1276. * request is made. Thus, if an actual transfer is to be made this is where we
  1277. * take off for real.
  1278. */
  1279. static CURLcode ftp_state_prepare_transfer(struct Curl_easy *data)
  1280. {
  1281. CURLcode result = CURLE_OK;
  1282. struct FTP *ftp = data->req.p.ftp;
  1283. struct connectdata *conn = data->conn;
  1284. if(ftp->transfer != PPTRANSFER_BODY) {
  1285. /* does not transfer any data */
  1286. /* still possibly do PRE QUOTE jobs */
  1287. ftp_state(data, FTP_RETR_PREQUOTE);
  1288. result = ftp_state_quote(data, TRUE, FTP_RETR_PREQUOTE);
  1289. }
  1290. else if(data->set.ftp_use_port) {
  1291. /* We have chosen to use the PORT (or similar) command */
  1292. result = ftp_state_use_port(data, EPRT);
  1293. }
  1294. else {
  1295. /* We have chosen (this is default) to use the PASV (or similar) command */
  1296. if(data->set.ftp_use_pret) {
  1297. /* The user has requested that we send a PRET command
  1298. to prepare the server for the upcoming PASV */
  1299. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1300. if(!conn->proto.ftpc.file)
  1301. result = Curl_pp_sendf(data, &ftpc->pp, "PRET %s",
  1302. data->set.str[STRING_CUSTOMREQUEST]?
  1303. data->set.str[STRING_CUSTOMREQUEST]:
  1304. (data->state.list_only?"NLST":"LIST"));
  1305. else if(data->state.upload)
  1306. result = Curl_pp_sendf(data, &ftpc->pp, "PRET STOR %s",
  1307. conn->proto.ftpc.file);
  1308. else
  1309. result = Curl_pp_sendf(data, &ftpc->pp, "PRET RETR %s",
  1310. conn->proto.ftpc.file);
  1311. if(!result)
  1312. ftp_state(data, FTP_PRET);
  1313. }
  1314. else
  1315. result = ftp_state_use_pasv(data, conn);
  1316. }
  1317. return result;
  1318. }
  1319. static CURLcode ftp_state_rest(struct Curl_easy *data,
  1320. struct connectdata *conn)
  1321. {
  1322. CURLcode result = CURLE_OK;
  1323. struct FTP *ftp = data->req.p.ftp;
  1324. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1325. if((ftp->transfer != PPTRANSFER_BODY) && ftpc->file) {
  1326. /* if a "head"-like request is being made (on a file) */
  1327. /* Determine if server can respond to REST command and therefore
  1328. whether it supports range */
  1329. result = Curl_pp_sendf(data, &ftpc->pp, "REST %d", 0);
  1330. if(!result)
  1331. ftp_state(data, FTP_REST);
  1332. }
  1333. else
  1334. result = ftp_state_prepare_transfer(data);
  1335. return result;
  1336. }
  1337. static CURLcode ftp_state_size(struct Curl_easy *data,
  1338. struct connectdata *conn)
  1339. {
  1340. CURLcode result = CURLE_OK;
  1341. struct FTP *ftp = data->req.p.ftp;
  1342. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1343. if((ftp->transfer == PPTRANSFER_INFO) && ftpc->file) {
  1344. /* if a "head"-like request is being made (on a file) */
  1345. /* we know ftpc->file is a valid pointer to a filename */
  1346. result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file);
  1347. if(!result)
  1348. ftp_state(data, FTP_SIZE);
  1349. }
  1350. else
  1351. result = ftp_state_rest(data, conn);
  1352. return result;
  1353. }
  1354. static CURLcode ftp_state_list(struct Curl_easy *data)
  1355. {
  1356. CURLcode result = CURLE_OK;
  1357. struct FTP *ftp = data->req.p.ftp;
  1358. struct connectdata *conn = data->conn;
  1359. /* If this output is to be machine-parsed, the NLST command might be better
  1360. to use, since the LIST command output is not specified or standard in any
  1361. way. It has turned out that the NLST list output is not the same on all
  1362. servers either... */
  1363. /*
  1364. if FTPFILE_NOCWD was specified, we should add the path
  1365. as argument for the LIST / NLST / or custom command.
  1366. Whether the server will support this, is uncertain.
  1367. The other ftp_filemethods will CWD into dir/dir/ first and
  1368. then just do LIST (in that case: nothing to do here)
  1369. */
  1370. char *lstArg = NULL;
  1371. char *cmd;
  1372. if((data->set.ftp_filemethod == FTPFILE_NOCWD) && ftp->path) {
  1373. /* url-decode before evaluation: e.g. paths starting/ending with %2f */
  1374. const char *slashPos = NULL;
  1375. char *rawPath = NULL;
  1376. result = Curl_urldecode(ftp->path, 0, &rawPath, NULL, REJECT_CTRL);
  1377. if(result)
  1378. return result;
  1379. slashPos = strrchr(rawPath, '/');
  1380. if(slashPos) {
  1381. /* chop off the file part if format is dir/file otherwise remove
  1382. the trailing slash for dir/dir/ except for absolute path / */
  1383. size_t n = slashPos - rawPath;
  1384. if(n == 0)
  1385. ++n;
  1386. lstArg = rawPath;
  1387. lstArg[n] = '\0';
  1388. }
  1389. else
  1390. free(rawPath);
  1391. }
  1392. cmd = aprintf("%s%s%s",
  1393. data->set.str[STRING_CUSTOMREQUEST]?
  1394. data->set.str[STRING_CUSTOMREQUEST]:
  1395. (data->state.list_only?"NLST":"LIST"),
  1396. lstArg? " ": "",
  1397. lstArg? lstArg: "");
  1398. free(lstArg);
  1399. if(!cmd)
  1400. return CURLE_OUT_OF_MEMORY;
  1401. result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", cmd);
  1402. free(cmd);
  1403. if(!result)
  1404. ftp_state(data, FTP_LIST);
  1405. return result;
  1406. }
  1407. static CURLcode ftp_state_retr_prequote(struct Curl_easy *data)
  1408. {
  1409. /* We have sent the TYPE, now we must send the list of prequote strings */
  1410. return ftp_state_quote(data, TRUE, FTP_RETR_PREQUOTE);
  1411. }
  1412. static CURLcode ftp_state_stor_prequote(struct Curl_easy *data)
  1413. {
  1414. /* We have sent the TYPE, now we must send the list of prequote strings */
  1415. return ftp_state_quote(data, TRUE, FTP_STOR_PREQUOTE);
  1416. }
  1417. static CURLcode ftp_state_type(struct Curl_easy *data)
  1418. {
  1419. CURLcode result = CURLE_OK;
  1420. struct FTP *ftp = data->req.p.ftp;
  1421. struct connectdata *conn = data->conn;
  1422. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1423. /* If we have selected NOBODY and HEADER, it means that we only want file
  1424. information. Which in FTP cannot be much more than the file size and
  1425. date. */
  1426. if(data->req.no_body && ftpc->file &&
  1427. ftp_need_type(conn, data->state.prefer_ascii)) {
  1428. /* The SIZE command is _not_ RFC 959 specified, and therefore many servers
  1429. may not support it! It is however the only way we have to get a file's
  1430. size! */
  1431. ftp->transfer = PPTRANSFER_INFO;
  1432. /* this means no actual transfer will be made */
  1433. /* Some servers return different sizes for different modes, and thus we
  1434. must set the proper type before we check the size */
  1435. result = ftp_nb_type(data, conn, data->state.prefer_ascii, FTP_TYPE);
  1436. if(result)
  1437. return result;
  1438. }
  1439. else
  1440. result = ftp_state_size(data, conn);
  1441. return result;
  1442. }
  1443. /* This is called after the CWD commands have been done in the beginning of
  1444. the DO phase */
  1445. static CURLcode ftp_state_mdtm(struct Curl_easy *data)
  1446. {
  1447. CURLcode result = CURLE_OK;
  1448. struct connectdata *conn = data->conn;
  1449. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1450. /* Requested time of file or time-depended transfer? */
  1451. if((data->set.get_filetime || data->set.timecondition) && ftpc->file) {
  1452. /* we have requested to get the modified-time of the file, this is a white
  1453. spot as the MDTM is not mentioned in RFC959 */
  1454. result = Curl_pp_sendf(data, &ftpc->pp, "MDTM %s", ftpc->file);
  1455. if(!result)
  1456. ftp_state(data, FTP_MDTM);
  1457. }
  1458. else
  1459. result = ftp_state_type(data);
  1460. return result;
  1461. }
  1462. /* This is called after the TYPE and possible quote commands have been sent */
  1463. static CURLcode ftp_state_ul_setup(struct Curl_easy *data,
  1464. bool sizechecked)
  1465. {
  1466. CURLcode result = CURLE_OK;
  1467. struct connectdata *conn = data->conn;
  1468. struct FTP *ftp = data->req.p.ftp;
  1469. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1470. bool append = data->set.remote_append;
  1471. if((data->state.resume_from && !sizechecked) ||
  1472. ((data->state.resume_from > 0) && sizechecked)) {
  1473. /* we are about to continue the uploading of a file */
  1474. /* 1. get already existing file's size. We use the SIZE command for this
  1475. which may not exist in the server! The SIZE command is not in
  1476. RFC959. */
  1477. /* 2. This used to set REST. But since we can do append, we
  1478. do not another ftp command. We just skip the source file
  1479. offset and then we APPEND the rest on the file instead */
  1480. /* 3. pass file-size number of bytes in the source file */
  1481. /* 4. lower the infilesize counter */
  1482. /* => transfer as usual */
  1483. int seekerr = CURL_SEEKFUNC_OK;
  1484. if(data->state.resume_from < 0) {
  1485. /* Got no given size to start from, figure it out */
  1486. result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file);
  1487. if(!result)
  1488. ftp_state(data, FTP_STOR_SIZE);
  1489. return result;
  1490. }
  1491. /* enable append */
  1492. append = TRUE;
  1493. /* Let's read off the proper amount of bytes from the input. */
  1494. if(data->set.seek_func) {
  1495. Curl_set_in_callback(data, true);
  1496. seekerr = data->set.seek_func(data->set.seek_client,
  1497. data->state.resume_from, SEEK_SET);
  1498. Curl_set_in_callback(data, false);
  1499. }
  1500. if(seekerr != CURL_SEEKFUNC_OK) {
  1501. curl_off_t passed = 0;
  1502. if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
  1503. failf(data, "Could not seek stream");
  1504. return CURLE_FTP_COULDNT_USE_REST;
  1505. }
  1506. /* seekerr == CURL_SEEKFUNC_CANTSEEK (cannot seek to offset) */
  1507. do {
  1508. char scratch[4*1024];
  1509. size_t readthisamountnow =
  1510. (data->state.resume_from - passed > (curl_off_t)sizeof(scratch)) ?
  1511. sizeof(scratch) :
  1512. curlx_sotouz(data->state.resume_from - passed);
  1513. size_t actuallyread =
  1514. data->state.fread_func(scratch, 1, readthisamountnow,
  1515. data->state.in);
  1516. passed += actuallyread;
  1517. if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
  1518. /* this checks for greater-than only to make sure that the
  1519. CURL_READFUNC_ABORT return code still aborts */
  1520. failf(data, "Failed to read data");
  1521. return CURLE_FTP_COULDNT_USE_REST;
  1522. }
  1523. } while(passed < data->state.resume_from);
  1524. }
  1525. /* now, decrease the size of the read */
  1526. if(data->state.infilesize>0) {
  1527. data->state.infilesize -= data->state.resume_from;
  1528. if(data->state.infilesize <= 0) {
  1529. infof(data, "File already completely uploaded");
  1530. /* no data to transfer */
  1531. Curl_xfer_setup_nop(data);
  1532. /* Set ->transfer so that we will not get any error in
  1533. * ftp_done() because we did not transfer anything! */
  1534. ftp->transfer = PPTRANSFER_NONE;
  1535. ftp_state(data, FTP_STOP);
  1536. return CURLE_OK;
  1537. }
  1538. }
  1539. /* we have passed, proceed as normal */
  1540. } /* resume_from */
  1541. result = Curl_pp_sendf(data, &ftpc->pp, append?"APPE %s":"STOR %s",
  1542. ftpc->file);
  1543. if(!result)
  1544. ftp_state(data, FTP_STOR);
  1545. return result;
  1546. }
  1547. static CURLcode ftp_state_quote(struct Curl_easy *data,
  1548. bool init,
  1549. ftpstate instate)
  1550. {
  1551. CURLcode result = CURLE_OK;
  1552. struct FTP *ftp = data->req.p.ftp;
  1553. struct connectdata *conn = data->conn;
  1554. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1555. bool quote = FALSE;
  1556. struct curl_slist *item;
  1557. switch(instate) {
  1558. case FTP_QUOTE:
  1559. default:
  1560. item = data->set.quote;
  1561. break;
  1562. case FTP_RETR_PREQUOTE:
  1563. case FTP_STOR_PREQUOTE:
  1564. item = data->set.prequote;
  1565. break;
  1566. case FTP_POSTQUOTE:
  1567. item = data->set.postquote;
  1568. break;
  1569. }
  1570. /*
  1571. * This state uses:
  1572. * 'count1' to iterate over the commands to send
  1573. * 'count2' to store whether to allow commands to fail
  1574. */
  1575. if(init)
  1576. ftpc->count1 = 0;
  1577. else
  1578. ftpc->count1++;
  1579. if(item) {
  1580. int i = 0;
  1581. /* Skip count1 items in the linked list */
  1582. while((i< ftpc->count1) && item) {
  1583. item = item->next;
  1584. i++;
  1585. }
  1586. if(item) {
  1587. char *cmd = item->data;
  1588. if(cmd[0] == '*') {
  1589. cmd++;
  1590. ftpc->count2 = 1; /* the sent command is allowed to fail */
  1591. }
  1592. else
  1593. ftpc->count2 = 0; /* failure means cancel operation */
  1594. result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd);
  1595. if(result)
  1596. return result;
  1597. ftp_state(data, instate);
  1598. quote = TRUE;
  1599. }
  1600. }
  1601. if(!quote) {
  1602. /* No more quote to send, continue to ... */
  1603. switch(instate) {
  1604. case FTP_QUOTE:
  1605. default:
  1606. result = ftp_state_cwd(data, conn);
  1607. break;
  1608. case FTP_RETR_PREQUOTE:
  1609. if(ftp->transfer != PPTRANSFER_BODY)
  1610. ftp_state(data, FTP_STOP);
  1611. else {
  1612. if(ftpc->known_filesize != -1) {
  1613. Curl_pgrsSetDownloadSize(data, ftpc->known_filesize);
  1614. result = ftp_state_retr(data, ftpc->known_filesize);
  1615. }
  1616. else {
  1617. if(data->set.ignorecl || data->state.prefer_ascii) {
  1618. /* 'ignorecl' is used to support download of growing files. It
  1619. prevents the state machine from requesting the file size from
  1620. the server. With an unknown file size the download continues
  1621. until the server terminates it, otherwise the client stops if
  1622. the received byte count exceeds the reported file size. Set
  1623. option CURLOPT_IGNORE_CONTENT_LENGTH to 1 to enable this
  1624. behavior.
  1625. In addition: asking for the size for 'TYPE A' transfers is not
  1626. constructive since servers do not report the converted size. So
  1627. skip it.
  1628. */
  1629. result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
  1630. if(!result)
  1631. ftp_state(data, FTP_RETR);
  1632. }
  1633. else {
  1634. result = Curl_pp_sendf(data, &ftpc->pp, "SIZE %s", ftpc->file);
  1635. if(!result)
  1636. ftp_state(data, FTP_RETR_SIZE);
  1637. }
  1638. }
  1639. }
  1640. break;
  1641. case FTP_STOR_PREQUOTE:
  1642. result = ftp_state_ul_setup(data, FALSE);
  1643. break;
  1644. case FTP_POSTQUOTE:
  1645. break;
  1646. }
  1647. }
  1648. return result;
  1649. }
  1650. /* called from ftp_state_pasv_resp to switch to PASV in case of EPSV
  1651. problems */
  1652. static CURLcode ftp_epsv_disable(struct Curl_easy *data,
  1653. struct connectdata *conn)
  1654. {
  1655. CURLcode result = CURLE_OK;
  1656. if(conn->bits.ipv6
  1657. #ifndef CURL_DISABLE_PROXY
  1658. && !(conn->bits.tunnel_proxy || conn->bits.socksproxy)
  1659. #endif
  1660. ) {
  1661. /* We cannot disable EPSV when doing IPv6, so this is instead a fail */
  1662. failf(data, "Failed EPSV attempt, exiting");
  1663. return CURLE_WEIRD_SERVER_REPLY;
  1664. }
  1665. infof(data, "Failed EPSV attempt. Disabling EPSV");
  1666. /* disable it for next transfer */
  1667. conn->bits.ftp_use_epsv = FALSE;
  1668. Curl_conn_close(data, SECONDARYSOCKET);
  1669. Curl_conn_cf_discard_all(data, conn, SECONDARYSOCKET);
  1670. data->state.errorbuf = FALSE; /* allow error message to get
  1671. rewritten */
  1672. result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", "PASV");
  1673. if(!result) {
  1674. conn->proto.ftpc.count1++;
  1675. /* remain in/go to the FTP_PASV state */
  1676. ftp_state(data, FTP_PASV);
  1677. }
  1678. return result;
  1679. }
  1680. static char *control_address(struct connectdata *conn)
  1681. {
  1682. /* Returns the control connection IP address.
  1683. If a proxy tunnel is used, returns the original hostname instead, because
  1684. the effective control connection address is the proxy address,
  1685. not the ftp host. */
  1686. #ifndef CURL_DISABLE_PROXY
  1687. if(conn->bits.tunnel_proxy || conn->bits.socksproxy)
  1688. return conn->host.name;
  1689. #endif
  1690. return conn->primary.remote_ip;
  1691. }
  1692. static bool match_pasv_6nums(const char *p,
  1693. unsigned int *array) /* 6 numbers */
  1694. {
  1695. int i;
  1696. for(i = 0; i < 6; i++) {
  1697. unsigned long num;
  1698. char *endp;
  1699. if(i) {
  1700. if(*p != ',')
  1701. return FALSE;
  1702. p++;
  1703. }
  1704. if(!ISDIGIT(*p))
  1705. return FALSE;
  1706. num = strtoul(p, &endp, 10);
  1707. if(num > 255)
  1708. return FALSE;
  1709. array[i] = (unsigned int)num;
  1710. p = endp;
  1711. }
  1712. return TRUE;
  1713. }
  1714. static CURLcode ftp_state_pasv_resp(struct Curl_easy *data,
  1715. int ftpcode)
  1716. {
  1717. struct connectdata *conn = data->conn;
  1718. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1719. CURLcode result;
  1720. struct Curl_dns_entry *addr = NULL;
  1721. enum resolve_t rc;
  1722. unsigned short connectport; /* the local port connect() should use! */
  1723. struct pingpong *pp = &ftpc->pp;
  1724. char *str =
  1725. Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first letter */
  1726. /* if we come here again, make sure the former name is cleared */
  1727. Curl_safefree(ftpc->newhost);
  1728. if((ftpc->count1 == 0) &&
  1729. (ftpcode == 229)) {
  1730. /* positive EPSV response */
  1731. char *ptr = strchr(str, '(');
  1732. if(ptr) {
  1733. char sep;
  1734. ptr++;
  1735. /* |||12345| */
  1736. sep = ptr[0];
  1737. /* the ISDIGIT() check here is because strtoul() accepts leading minus
  1738. etc */
  1739. if((ptr[1] == sep) && (ptr[2] == sep) && ISDIGIT(ptr[3])) {
  1740. char *endp;
  1741. unsigned long num = strtoul(&ptr[3], &endp, 10);
  1742. if(*endp != sep)
  1743. ptr = NULL;
  1744. else if(num > 0xffff) {
  1745. failf(data, "Illegal port number in EPSV reply");
  1746. return CURLE_FTP_WEIRD_PASV_REPLY;
  1747. }
  1748. if(ptr) {
  1749. ftpc->newport = (unsigned short)(num & 0xffff);
  1750. ftpc->newhost = strdup(control_address(conn));
  1751. if(!ftpc->newhost)
  1752. return CURLE_OUT_OF_MEMORY;
  1753. }
  1754. }
  1755. else
  1756. ptr = NULL;
  1757. }
  1758. if(!ptr) {
  1759. failf(data, "Weirdly formatted EPSV reply");
  1760. return CURLE_FTP_WEIRD_PASV_REPLY;
  1761. }
  1762. }
  1763. else if((ftpc->count1 == 1) &&
  1764. (ftpcode == 227)) {
  1765. /* positive PASV response */
  1766. unsigned int ip[6];
  1767. /*
  1768. * Scan for a sequence of six comma-separated numbers and use them as
  1769. * IP+port indicators.
  1770. *
  1771. * Found reply-strings include:
  1772. * "227 Entering Passive Mode (127,0,0,1,4,51)"
  1773. * "227 Data transfer will passively listen to 127,0,0,1,4,51"
  1774. * "227 Entering passive mode. 127,0,0,1,4,51"
  1775. */
  1776. while(*str) {
  1777. if(match_pasv_6nums(str, ip))
  1778. break;
  1779. str++;
  1780. }
  1781. if(!*str) {
  1782. failf(data, "Couldn't interpret the 227-response");
  1783. return CURLE_FTP_WEIRD_227_FORMAT;
  1784. }
  1785. /* we got OK from server */
  1786. if(data->set.ftp_skip_ip) {
  1787. /* told to ignore the remotely given IP but instead use the host we used
  1788. for the control connection */
  1789. infof(data, "Skip %u.%u.%u.%u for data connection, reuse %s instead",
  1790. ip[0], ip[1], ip[2], ip[3],
  1791. conn->host.name);
  1792. ftpc->newhost = strdup(control_address(conn));
  1793. }
  1794. else
  1795. ftpc->newhost = aprintf("%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
  1796. if(!ftpc->newhost)
  1797. return CURLE_OUT_OF_MEMORY;
  1798. ftpc->newport = (unsigned short)(((ip[4]<<8) + ip[5]) & 0xffff);
  1799. }
  1800. else if(ftpc->count1 == 0) {
  1801. /* EPSV failed, move on to PASV */
  1802. return ftp_epsv_disable(data, conn);
  1803. }
  1804. else {
  1805. failf(data, "Bad PASV/EPSV response: %03d", ftpcode);
  1806. return CURLE_FTP_WEIRD_PASV_REPLY;
  1807. }
  1808. #ifndef CURL_DISABLE_PROXY
  1809. if(conn->bits.proxy) {
  1810. /*
  1811. * This connection uses a proxy and we need to connect to the proxy again
  1812. * here. We do not want to rely on a former host lookup that might've
  1813. * expired now, instead we remake the lookup here and now!
  1814. */
  1815. const char * const host_name = conn->bits.socksproxy ?
  1816. conn->socks_proxy.host.name : conn->http_proxy.host.name;
  1817. rc = Curl_resolv(data, host_name, conn->primary.remote_port, FALSE, &addr);
  1818. if(rc == CURLRESOLV_PENDING)
  1819. /* BLOCKING, ignores the return code but 'addr' will be NULL in
  1820. case of failure */
  1821. (void)Curl_resolver_wait_resolv(data, &addr);
  1822. /* we connect to the proxy's port */
  1823. connectport = (unsigned short)conn->primary.remote_port;
  1824. if(!addr) {
  1825. failf(data, "cannot resolve proxy host %s:%hu", host_name, connectport);
  1826. return CURLE_COULDNT_RESOLVE_PROXY;
  1827. }
  1828. }
  1829. else
  1830. #endif
  1831. {
  1832. /* normal, direct, ftp connection */
  1833. DEBUGASSERT(ftpc->newhost);
  1834. /* postponed address resolution in case of tcp fastopen */
  1835. if(conn->bits.tcp_fastopen && !conn->bits.reuse && !ftpc->newhost[0]) {
  1836. Curl_safefree(ftpc->newhost);
  1837. ftpc->newhost = strdup(control_address(conn));
  1838. if(!ftpc->newhost)
  1839. return CURLE_OUT_OF_MEMORY;
  1840. }
  1841. rc = Curl_resolv(data, ftpc->newhost, ftpc->newport, FALSE, &addr);
  1842. if(rc == CURLRESOLV_PENDING)
  1843. /* BLOCKING */
  1844. (void)Curl_resolver_wait_resolv(data, &addr);
  1845. connectport = ftpc->newport; /* we connect to the remote port */
  1846. if(!addr) {
  1847. failf(data, "cannot resolve new host %s:%hu",
  1848. ftpc->newhost, connectport);
  1849. return CURLE_FTP_CANT_GET_HOST;
  1850. }
  1851. }
  1852. result = Curl_conn_setup(data, conn, SECONDARYSOCKET, addr,
  1853. conn->bits.ftp_use_data_ssl?
  1854. CURL_CF_SSL_ENABLE : CURL_CF_SSL_DISABLE);
  1855. if(result) {
  1856. Curl_resolv_unlink(data, &addr); /* we are done using this address */
  1857. if(ftpc->count1 == 0 && ftpcode == 229)
  1858. return ftp_epsv_disable(data, conn);
  1859. return result;
  1860. }
  1861. /*
  1862. * When this is used from the multi interface, this might've returned with
  1863. * the 'connected' set to FALSE and thus we are now awaiting a non-blocking
  1864. * connect to connect.
  1865. */
  1866. if(data->set.verbose)
  1867. /* this just dumps information about this second connection */
  1868. ftp_pasv_verbose(data, addr->addr, ftpc->newhost, connectport);
  1869. Curl_resolv_unlink(data, &addr); /* we are done using this address */
  1870. Curl_safefree(conn->secondaryhostname);
  1871. conn->secondary_port = ftpc->newport;
  1872. conn->secondaryhostname = strdup(ftpc->newhost);
  1873. if(!conn->secondaryhostname)
  1874. return CURLE_OUT_OF_MEMORY;
  1875. conn->bits.do_more = TRUE;
  1876. ftp_state(data, FTP_STOP); /* this phase is completed */
  1877. return result;
  1878. }
  1879. static CURLcode ftp_state_port_resp(struct Curl_easy *data,
  1880. int ftpcode)
  1881. {
  1882. struct connectdata *conn = data->conn;
  1883. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1884. ftpport fcmd = (ftpport)ftpc->count1;
  1885. CURLcode result = CURLE_OK;
  1886. /* The FTP spec tells a positive response should have code 200.
  1887. Be more permissive here to tolerate deviant servers. */
  1888. if(ftpcode / 100 != 2) {
  1889. /* the command failed */
  1890. if(EPRT == fcmd) {
  1891. infof(data, "disabling EPRT usage");
  1892. conn->bits.ftp_use_eprt = FALSE;
  1893. }
  1894. fcmd++;
  1895. if(fcmd == DONE) {
  1896. failf(data, "Failed to do PORT");
  1897. result = CURLE_FTP_PORT_FAILED;
  1898. }
  1899. else
  1900. /* try next */
  1901. result = ftp_state_use_port(data, fcmd);
  1902. }
  1903. else {
  1904. infof(data, "Connect data stream actively");
  1905. ftp_state(data, FTP_STOP); /* end of DO phase */
  1906. result = ftp_dophase_done(data, FALSE);
  1907. }
  1908. return result;
  1909. }
  1910. static int twodigit(const char *p)
  1911. {
  1912. return (p[0]-'0') * 10 + (p[1]-'0');
  1913. }
  1914. static bool ftp_213_date(const char *p, int *year, int *month, int *day,
  1915. int *hour, int *minute, int *second)
  1916. {
  1917. size_t len = strlen(p);
  1918. if(len < 14)
  1919. return FALSE;
  1920. *year = twodigit(&p[0]) * 100 + twodigit(&p[2]);
  1921. *month = twodigit(&p[4]);
  1922. *day = twodigit(&p[6]);
  1923. *hour = twodigit(&p[8]);
  1924. *minute = twodigit(&p[10]);
  1925. *second = twodigit(&p[12]);
  1926. if((*month > 12) || (*day > 31) || (*hour > 23) || (*minute > 59) ||
  1927. (*second > 60))
  1928. return FALSE;
  1929. return TRUE;
  1930. }
  1931. static CURLcode client_write_header(struct Curl_easy *data,
  1932. char *buf, size_t blen)
  1933. {
  1934. /* Some replies from an FTP server are written to the client
  1935. * as CLIENTWRITE_HEADER, formatted as if they came from a
  1936. * HTTP conversation.
  1937. * In all protocols, CLIENTWRITE_HEADER data is only passed to
  1938. * the body write callback when data->set.include_header is set
  1939. * via CURLOPT_HEADER.
  1940. * For historic reasons, FTP never played this game and expects
  1941. * all its HEADERs to do that always. Set that flag during the
  1942. * call to Curl_client_write() so it does the right thing.
  1943. *
  1944. * Notice that we cannot enable this flag for FTP in general,
  1945. * as an FTP transfer might involve an HTTP proxy connection and
  1946. * headers from CONNECT should not automatically be part of the
  1947. * output. */
  1948. CURLcode result;
  1949. int save = data->set.include_header;
  1950. data->set.include_header = TRUE;
  1951. result = Curl_client_write(data, CLIENTWRITE_HEADER, buf, blen);
  1952. data->set.include_header = save? TRUE:FALSE;
  1953. return result;
  1954. }
  1955. static CURLcode ftp_state_mdtm_resp(struct Curl_easy *data,
  1956. int ftpcode)
  1957. {
  1958. CURLcode result = CURLE_OK;
  1959. struct FTP *ftp = data->req.p.ftp;
  1960. struct connectdata *conn = data->conn;
  1961. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1962. switch(ftpcode) {
  1963. case 213:
  1964. {
  1965. /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the
  1966. last .sss part is optional and means fractions of a second */
  1967. int year, month, day, hour, minute, second;
  1968. struct pingpong *pp = &ftpc->pp;
  1969. char *resp = Curl_dyn_ptr(&pp->recvbuf) + 4;
  1970. if(ftp_213_date(resp, &year, &month, &day, &hour, &minute, &second)) {
  1971. /* we have a time, reformat it */
  1972. char timebuf[24];
  1973. msnprintf(timebuf, sizeof(timebuf),
  1974. "%04d%02d%02d %02d:%02d:%02d GMT",
  1975. year, month, day, hour, minute, second);
  1976. /* now, convert this into a time() value: */
  1977. data->info.filetime = Curl_getdate_capped(timebuf);
  1978. }
  1979. #ifdef CURL_FTP_HTTPSTYLE_HEAD
  1980. /* If we asked for a time of the file and we actually got one as well,
  1981. we "emulate" an HTTP-style header in our output. */
  1982. if(data->req.no_body &&
  1983. ftpc->file &&
  1984. data->set.get_filetime &&
  1985. (data->info.filetime >= 0) ) {
  1986. char headerbuf[128];
  1987. int headerbuflen;
  1988. time_t filetime = data->info.filetime;
  1989. struct tm buffer;
  1990. const struct tm *tm = &buffer;
  1991. result = Curl_gmtime(filetime, &buffer);
  1992. if(result)
  1993. return result;
  1994. /* format: "Tue, 15 Nov 1994 12:45:26" */
  1995. headerbuflen = msnprintf(headerbuf, sizeof(headerbuf),
  1996. "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
  1997. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  1998. tm->tm_mday,
  1999. Curl_month[tm->tm_mon],
  2000. tm->tm_year + 1900,
  2001. tm->tm_hour,
  2002. tm->tm_min,
  2003. tm->tm_sec);
  2004. result = client_write_header(data, headerbuf, headerbuflen);
  2005. if(result)
  2006. return result;
  2007. } /* end of a ridiculous amount of conditionals */
  2008. #endif
  2009. }
  2010. break;
  2011. default:
  2012. infof(data, "unsupported MDTM reply format");
  2013. break;
  2014. case 550: /* 550 is used for several different problems, e.g.
  2015. "No such file or directory" or "Permission denied".
  2016. It does not mean that the file does not exist at all. */
  2017. infof(data, "MDTM failed: file does not exist or permission problem,"
  2018. " continuing");
  2019. break;
  2020. }
  2021. if(data->set.timecondition) {
  2022. if((data->info.filetime > 0) && (data->set.timevalue > 0)) {
  2023. switch(data->set.timecondition) {
  2024. case CURL_TIMECOND_IFMODSINCE:
  2025. default:
  2026. if(data->info.filetime <= data->set.timevalue) {
  2027. infof(data, "The requested document is not new enough");
  2028. ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */
  2029. data->info.timecond = TRUE;
  2030. ftp_state(data, FTP_STOP);
  2031. return CURLE_OK;
  2032. }
  2033. break;
  2034. case CURL_TIMECOND_IFUNMODSINCE:
  2035. if(data->info.filetime > data->set.timevalue) {
  2036. infof(data, "The requested document is not old enough");
  2037. ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */
  2038. data->info.timecond = TRUE;
  2039. ftp_state(data, FTP_STOP);
  2040. return CURLE_OK;
  2041. }
  2042. break;
  2043. } /* switch */
  2044. }
  2045. else {
  2046. infof(data, "Skipping time comparison");
  2047. }
  2048. }
  2049. if(!result)
  2050. result = ftp_state_type(data);
  2051. return result;
  2052. }
  2053. static CURLcode ftp_state_type_resp(struct Curl_easy *data,
  2054. int ftpcode,
  2055. ftpstate instate)
  2056. {
  2057. CURLcode result = CURLE_OK;
  2058. struct connectdata *conn = data->conn;
  2059. if(ftpcode/100 != 2) {
  2060. /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a
  2061. successful 'TYPE I'. While that is not as RFC959 says, it is still a
  2062. positive response code and we allow that. */
  2063. failf(data, "Couldn't set desired mode");
  2064. return CURLE_FTP_COULDNT_SET_TYPE;
  2065. }
  2066. if(ftpcode != 200)
  2067. infof(data, "Got a %03d response code instead of the assumed 200",
  2068. ftpcode);
  2069. if(instate == FTP_TYPE)
  2070. result = ftp_state_size(data, conn);
  2071. else if(instate == FTP_LIST_TYPE)
  2072. result = ftp_state_list(data);
  2073. else if(instate == FTP_RETR_TYPE)
  2074. result = ftp_state_retr_prequote(data);
  2075. else if(instate == FTP_STOR_TYPE)
  2076. result = ftp_state_stor_prequote(data);
  2077. return result;
  2078. }
  2079. static CURLcode ftp_state_retr(struct Curl_easy *data,
  2080. curl_off_t filesize)
  2081. {
  2082. CURLcode result = CURLE_OK;
  2083. struct FTP *ftp = data->req.p.ftp;
  2084. struct connectdata *conn = data->conn;
  2085. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2086. CURL_TRC_FTP(data, "[%s] ftp_state_retr()", FTP_DSTATE(data));
  2087. if(data->set.max_filesize && (filesize > data->set.max_filesize)) {
  2088. failf(data, "Maximum file size exceeded");
  2089. return CURLE_FILESIZE_EXCEEDED;
  2090. }
  2091. ftp->downloadsize = filesize;
  2092. if(data->state.resume_from) {
  2093. /* We always (attempt to) get the size of downloads, so it is done before
  2094. this even when not doing resumes. */
  2095. if(filesize == -1) {
  2096. infof(data, "ftp server does not support SIZE");
  2097. /* We could not get the size and therefore we cannot know if there really
  2098. is a part of the file left to get, although the server will just
  2099. close the connection when we start the connection so it will not cause
  2100. us any harm, just not make us exit as nicely. */
  2101. }
  2102. else {
  2103. /* We got a file size report, so we check that there actually is a
  2104. part of the file left to get, or else we go home. */
  2105. if(data->state.resume_from< 0) {
  2106. /* We are supposed to download the last abs(from) bytes */
  2107. if(filesize < -data->state.resume_from) {
  2108. failf(data, "Offset (%" FMT_OFF_T
  2109. ") was beyond file size (%" FMT_OFF_T ")",
  2110. data->state.resume_from, filesize);
  2111. return CURLE_BAD_DOWNLOAD_RESUME;
  2112. }
  2113. /* convert to size to download */
  2114. ftp->downloadsize = -data->state.resume_from;
  2115. /* download from where? */
  2116. data->state.resume_from = filesize - ftp->downloadsize;
  2117. }
  2118. else {
  2119. if(filesize < data->state.resume_from) {
  2120. failf(data, "Offset (%" FMT_OFF_T
  2121. ") was beyond file size (%" FMT_OFF_T ")",
  2122. data->state.resume_from, filesize);
  2123. return CURLE_BAD_DOWNLOAD_RESUME;
  2124. }
  2125. /* Now store the number of bytes we are expected to download */
  2126. ftp->downloadsize = filesize-data->state.resume_from;
  2127. }
  2128. }
  2129. if(ftp->downloadsize == 0) {
  2130. /* no data to transfer */
  2131. Curl_xfer_setup_nop(data);
  2132. infof(data, "File already completely downloaded");
  2133. /* Set ->transfer so that we will not get any error in ftp_done()
  2134. * because we did not transfer the any file */
  2135. ftp->transfer = PPTRANSFER_NONE;
  2136. ftp_state(data, FTP_STOP);
  2137. return CURLE_OK;
  2138. }
  2139. /* Set resume file transfer offset */
  2140. infof(data, "Instructs server to resume from offset %" FMT_OFF_T,
  2141. data->state.resume_from);
  2142. result = Curl_pp_sendf(data, &ftpc->pp, "REST %" FMT_OFF_T,
  2143. data->state.resume_from);
  2144. if(!result)
  2145. ftp_state(data, FTP_RETR_REST);
  2146. }
  2147. else {
  2148. /* no resume */
  2149. result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
  2150. if(!result)
  2151. ftp_state(data, FTP_RETR);
  2152. }
  2153. return result;
  2154. }
  2155. static CURLcode ftp_state_size_resp(struct Curl_easy *data,
  2156. int ftpcode,
  2157. ftpstate instate)
  2158. {
  2159. CURLcode result = CURLE_OK;
  2160. curl_off_t filesize = -1;
  2161. char *buf = Curl_dyn_ptr(&data->conn->proto.ftpc.pp.recvbuf);
  2162. size_t len = data->conn->proto.ftpc.pp.nfinal;
  2163. /* get the size from the ascii string: */
  2164. if(ftpcode == 213) {
  2165. /* To allow servers to prepend "rubbish" in the response string, we scan
  2166. for all the digits at the end of the response and parse only those as a
  2167. number. */
  2168. char *start = &buf[4];
  2169. char *fdigit = memchr(start, '\r', len);
  2170. if(fdigit) {
  2171. fdigit--;
  2172. if(*fdigit == '\n')
  2173. fdigit--;
  2174. while(ISDIGIT(fdigit[-1]) && (fdigit > start))
  2175. fdigit--;
  2176. }
  2177. else
  2178. fdigit = start;
  2179. /* ignores parsing errors, which will make the size remain unknown */
  2180. (void)curlx_strtoofft(fdigit, NULL, 10, &filesize);
  2181. }
  2182. else if(ftpcode == 550) { /* "No such file or directory" */
  2183. /* allow a SIZE failure for (resumed) uploads, when probing what command
  2184. to use */
  2185. if(instate != FTP_STOR_SIZE) {
  2186. failf(data, "The file does not exist");
  2187. return CURLE_REMOTE_FILE_NOT_FOUND;
  2188. }
  2189. }
  2190. if(instate == FTP_SIZE) {
  2191. #ifdef CURL_FTP_HTTPSTYLE_HEAD
  2192. if(-1 != filesize) {
  2193. char clbuf[128];
  2194. int clbuflen = msnprintf(clbuf, sizeof(clbuf),
  2195. "Content-Length: %" FMT_OFF_T "\r\n", filesize);
  2196. result = client_write_header(data, clbuf, clbuflen);
  2197. if(result)
  2198. return result;
  2199. }
  2200. #endif
  2201. Curl_pgrsSetDownloadSize(data, filesize);
  2202. result = ftp_state_rest(data, data->conn);
  2203. }
  2204. else if(instate == FTP_RETR_SIZE) {
  2205. Curl_pgrsSetDownloadSize(data, filesize);
  2206. result = ftp_state_retr(data, filesize);
  2207. }
  2208. else if(instate == FTP_STOR_SIZE) {
  2209. data->state.resume_from = filesize;
  2210. result = ftp_state_ul_setup(data, TRUE);
  2211. }
  2212. return result;
  2213. }
  2214. static CURLcode ftp_state_rest_resp(struct Curl_easy *data,
  2215. struct connectdata *conn,
  2216. int ftpcode,
  2217. ftpstate instate)
  2218. {
  2219. CURLcode result = CURLE_OK;
  2220. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2221. switch(instate) {
  2222. case FTP_REST:
  2223. default:
  2224. #ifdef CURL_FTP_HTTPSTYLE_HEAD
  2225. if(ftpcode == 350) {
  2226. char buffer[24]= { "Accept-ranges: bytes\r\n" };
  2227. result = client_write_header(data, buffer, strlen(buffer));
  2228. if(result)
  2229. return result;
  2230. }
  2231. #endif
  2232. result = ftp_state_prepare_transfer(data);
  2233. break;
  2234. case FTP_RETR_REST:
  2235. if(ftpcode != 350) {
  2236. failf(data, "Couldn't use REST");
  2237. result = CURLE_FTP_COULDNT_USE_REST;
  2238. }
  2239. else {
  2240. result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
  2241. if(!result)
  2242. ftp_state(data, FTP_RETR);
  2243. }
  2244. break;
  2245. }
  2246. return result;
  2247. }
  2248. static CURLcode ftp_state_stor_resp(struct Curl_easy *data,
  2249. int ftpcode, ftpstate instate)
  2250. {
  2251. CURLcode result = CURLE_OK;
  2252. struct connectdata *conn = data->conn;
  2253. if(ftpcode >= 400) {
  2254. failf(data, "Failed FTP upload: %0d", ftpcode);
  2255. ftp_state(data, FTP_STOP);
  2256. /* oops, we never close the sockets! */
  2257. return CURLE_UPLOAD_FAILED;
  2258. }
  2259. conn->proto.ftpc.state_saved = instate;
  2260. /* PORT means we are now awaiting the server to connect to us. */
  2261. if(data->set.ftp_use_port) {
  2262. bool connected;
  2263. ftp_state(data, FTP_STOP); /* no longer in STOR state */
  2264. result = AllowServerConnect(data, &connected);
  2265. if(result)
  2266. return result;
  2267. if(!connected) {
  2268. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2269. infof(data, "Data conn was not available immediately");
  2270. ftpc->wait_data_conn = TRUE;
  2271. }
  2272. return CURLE_OK;
  2273. }
  2274. return InitiateTransfer(data);
  2275. }
  2276. /* for LIST and RETR responses */
  2277. static CURLcode ftp_state_get_resp(struct Curl_easy *data,
  2278. int ftpcode,
  2279. ftpstate instate)
  2280. {
  2281. CURLcode result = CURLE_OK;
  2282. struct FTP *ftp = data->req.p.ftp;
  2283. struct connectdata *conn = data->conn;
  2284. if((ftpcode == 150) || (ftpcode == 125)) {
  2285. /*
  2286. A;
  2287. 150 Opening BINARY mode data connection for /etc/passwd (2241
  2288. bytes). (ok, the file is being transferred)
  2289. B:
  2290. 150 Opening ASCII mode data connection for /bin/ls
  2291. C:
  2292. 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes).
  2293. D:
  2294. 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes)
  2295. E:
  2296. 125 Data connection already open; Transfer starting. */
  2297. curl_off_t size = -1; /* default unknown size */
  2298. /*
  2299. * It appears that there are FTP-servers that return size 0 for files when
  2300. * SIZE is used on the file while being in BINARY mode. To work around
  2301. * that (stupid) behavior, we attempt to parse the RETR response even if
  2302. * the SIZE returned size zero.
  2303. *
  2304. * Debugging help from Salvatore Sorrentino on February 26, 2003.
  2305. */
  2306. if((instate != FTP_LIST) &&
  2307. !data->state.prefer_ascii &&
  2308. !data->set.ignorecl &&
  2309. (ftp->downloadsize < 1)) {
  2310. /*
  2311. * It seems directory listings either do not show the size or very
  2312. * often uses size 0 anyway. ASCII transfers may very well turn out
  2313. * that the transferred amount of data is not the same as this line
  2314. * tells, why using this number in those cases only confuses us.
  2315. *
  2316. * Example D above makes this parsing a little tricky */
  2317. char *bytes;
  2318. char *buf = Curl_dyn_ptr(&conn->proto.ftpc.pp.recvbuf);
  2319. bytes = strstr(buf, " bytes");
  2320. if(bytes) {
  2321. long in = (long)(--bytes-buf);
  2322. /* this is a hint there is size information in there! ;-) */
  2323. while(--in) {
  2324. /* scan for the left parenthesis and break there */
  2325. if('(' == *bytes)
  2326. break;
  2327. /* skip only digits */
  2328. if(!ISDIGIT(*bytes)) {
  2329. bytes = NULL;
  2330. break;
  2331. }
  2332. /* one more estep backwards */
  2333. bytes--;
  2334. }
  2335. /* if we have nothing but digits: */
  2336. if(bytes) {
  2337. ++bytes;
  2338. /* get the number! */
  2339. (void)curlx_strtoofft(bytes, NULL, 10, &size);
  2340. }
  2341. }
  2342. }
  2343. else if(ftp->downloadsize > -1)
  2344. size = ftp->downloadsize;
  2345. if(size > data->req.maxdownload && data->req.maxdownload > 0)
  2346. size = data->req.size = data->req.maxdownload;
  2347. else if((instate != FTP_LIST) && (data->state.prefer_ascii))
  2348. size = -1; /* kludge for servers that understate ASCII mode file size */
  2349. infof(data, "Maxdownload = %" FMT_OFF_T, data->req.maxdownload);
  2350. if(instate != FTP_LIST)
  2351. infof(data, "Getting file with size: %" FMT_OFF_T, size);
  2352. /* FTP download: */
  2353. conn->proto.ftpc.state_saved = instate;
  2354. conn->proto.ftpc.retr_size_saved = size;
  2355. if(data->set.ftp_use_port) {
  2356. bool connected;
  2357. result = AllowServerConnect(data, &connected);
  2358. if(result)
  2359. return result;
  2360. if(!connected) {
  2361. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2362. infof(data, "Data conn was not available immediately");
  2363. ftp_state(data, FTP_STOP);
  2364. ftpc->wait_data_conn = TRUE;
  2365. }
  2366. }
  2367. else
  2368. return InitiateTransfer(data);
  2369. }
  2370. else {
  2371. if((instate == FTP_LIST) && (ftpcode == 450)) {
  2372. /* simply no matching files in the dir listing */
  2373. ftp->transfer = PPTRANSFER_NONE; /* do not download anything */
  2374. ftp_state(data, FTP_STOP); /* this phase is over */
  2375. }
  2376. else {
  2377. failf(data, "RETR response: %03d", ftpcode);
  2378. return instate == FTP_RETR && ftpcode == 550?
  2379. CURLE_REMOTE_FILE_NOT_FOUND:
  2380. CURLE_FTP_COULDNT_RETR_FILE;
  2381. }
  2382. }
  2383. return result;
  2384. }
  2385. /* after USER, PASS and ACCT */
  2386. static CURLcode ftp_state_loggedin(struct Curl_easy *data)
  2387. {
  2388. CURLcode result = CURLE_OK;
  2389. struct connectdata *conn = data->conn;
  2390. if(conn->bits.ftp_use_control_ssl) {
  2391. /* PBSZ = PROTECTION BUFFER SIZE.
  2392. The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says:
  2393. Specifically, the PROT command MUST be preceded by a PBSZ
  2394. command and a PBSZ command MUST be preceded by a successful
  2395. security data exchange (the TLS negotiation in this case)
  2396. ... (and on page 8):
  2397. Thus the PBSZ command must still be issued, but must have a
  2398. parameter of '0' to indicate that no buffering is taking place
  2399. and the data connection should not be encapsulated.
  2400. */
  2401. result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "PBSZ %d", 0);
  2402. if(!result)
  2403. ftp_state(data, FTP_PBSZ);
  2404. }
  2405. else {
  2406. result = ftp_state_pwd(data, conn);
  2407. }
  2408. return result;
  2409. }
  2410. /* for USER and PASS responses */
  2411. static CURLcode ftp_state_user_resp(struct Curl_easy *data,
  2412. int ftpcode)
  2413. {
  2414. CURLcode result = CURLE_OK;
  2415. struct connectdata *conn = data->conn;
  2416. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2417. /* some need password anyway, and others just return 2xx ignored */
  2418. if((ftpcode == 331) && (ftpc->state == FTP_USER)) {
  2419. /* 331 Password required for ...
  2420. (the server requires to send the user's password too) */
  2421. result = Curl_pp_sendf(data, &ftpc->pp, "PASS %s",
  2422. conn->passwd?conn->passwd:"");
  2423. if(!result)
  2424. ftp_state(data, FTP_PASS);
  2425. }
  2426. else if(ftpcode/100 == 2) {
  2427. /* 230 User ... logged in.
  2428. (the user logged in with or without password) */
  2429. result = ftp_state_loggedin(data);
  2430. }
  2431. else if(ftpcode == 332) {
  2432. if(data->set.str[STRING_FTP_ACCOUNT]) {
  2433. result = Curl_pp_sendf(data, &ftpc->pp, "ACCT %s",
  2434. data->set.str[STRING_FTP_ACCOUNT]);
  2435. if(!result)
  2436. ftp_state(data, FTP_ACCT);
  2437. }
  2438. else {
  2439. failf(data, "ACCT requested but none available");
  2440. result = CURLE_LOGIN_DENIED;
  2441. }
  2442. }
  2443. else {
  2444. /* All other response codes, like:
  2445. 530 User ... access denied
  2446. (the server denies to log the specified user) */
  2447. if(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER] &&
  2448. !ftpc->ftp_trying_alternative) {
  2449. /* Ok, USER failed. Let's try the supplied command. */
  2450. result =
  2451. Curl_pp_sendf(data, &ftpc->pp, "%s",
  2452. data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]);
  2453. if(!result) {
  2454. ftpc->ftp_trying_alternative = TRUE;
  2455. ftp_state(data, FTP_USER);
  2456. }
  2457. }
  2458. else {
  2459. failf(data, "Access denied: %03d", ftpcode);
  2460. result = CURLE_LOGIN_DENIED;
  2461. }
  2462. }
  2463. return result;
  2464. }
  2465. /* for ACCT response */
  2466. static CURLcode ftp_state_acct_resp(struct Curl_easy *data,
  2467. int ftpcode)
  2468. {
  2469. CURLcode result = CURLE_OK;
  2470. if(ftpcode != 230) {
  2471. failf(data, "ACCT rejected by server: %03d", ftpcode);
  2472. result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */
  2473. }
  2474. else
  2475. result = ftp_state_loggedin(data);
  2476. return result;
  2477. }
  2478. static CURLcode ftp_statemachine(struct Curl_easy *data,
  2479. struct connectdata *conn)
  2480. {
  2481. CURLcode result;
  2482. int ftpcode;
  2483. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2484. struct pingpong *pp = &ftpc->pp;
  2485. static const char * const ftpauth[] = { "SSL", "TLS" };
  2486. size_t nread = 0;
  2487. if(pp->sendleft)
  2488. return Curl_pp_flushsend(data, pp);
  2489. result = ftp_readresp(data, FIRSTSOCKET, pp, &ftpcode, &nread);
  2490. if(result)
  2491. return result;
  2492. if(ftpcode) {
  2493. /* we have now received a full FTP server response */
  2494. switch(ftpc->state) {
  2495. case FTP_WAIT220:
  2496. if(ftpcode == 230) {
  2497. /* 230 User logged in - already! Take as 220 if TLS required. */
  2498. if(data->set.use_ssl <= CURLUSESSL_TRY ||
  2499. conn->bits.ftp_use_control_ssl)
  2500. return ftp_state_user_resp(data, ftpcode);
  2501. }
  2502. else if(ftpcode != 220) {
  2503. failf(data, "Got a %03d ftp-server response when 220 was expected",
  2504. ftpcode);
  2505. return CURLE_WEIRD_SERVER_REPLY;
  2506. }
  2507. /* We have received a 220 response fine, now we proceed. */
  2508. #ifdef HAVE_GSSAPI
  2509. if(data->set.krb) {
  2510. /* If not anonymous login, try a secure login. Note that this
  2511. procedure is still BLOCKING. */
  2512. Curl_sec_request_prot(conn, "private");
  2513. /* We set private first as default, in case the line below fails to
  2514. set a valid level */
  2515. Curl_sec_request_prot(conn, data->set.str[STRING_KRB_LEVEL]);
  2516. if(Curl_sec_login(data, conn)) {
  2517. failf(data, "secure login failed");
  2518. return CURLE_WEIRD_SERVER_REPLY;
  2519. }
  2520. infof(data, "Authentication successful");
  2521. }
  2522. #endif
  2523. if(data->set.use_ssl && !conn->bits.ftp_use_control_ssl) {
  2524. /* We do not have a SSL/TLS control connection yet, but FTPS is
  2525. requested. Try a FTPS connection now */
  2526. ftpc->count3 = 0;
  2527. switch(data->set.ftpsslauth) {
  2528. case CURLFTPAUTH_DEFAULT:
  2529. case CURLFTPAUTH_SSL:
  2530. ftpc->count2 = 1; /* add one to get next */
  2531. ftpc->count1 = 0;
  2532. break;
  2533. case CURLFTPAUTH_TLS:
  2534. ftpc->count2 = -1; /* subtract one to get next */
  2535. ftpc->count1 = 1;
  2536. break;
  2537. default:
  2538. failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d",
  2539. (int)data->set.ftpsslauth);
  2540. return CURLE_UNKNOWN_OPTION; /* we do not know what to do */
  2541. }
  2542. result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s",
  2543. ftpauth[ftpc->count1]);
  2544. if(!result)
  2545. ftp_state(data, FTP_AUTH);
  2546. }
  2547. else
  2548. result = ftp_state_user(data, conn);
  2549. break;
  2550. case FTP_AUTH:
  2551. /* we have gotten the response to a previous AUTH command */
  2552. if(pp->overflow)
  2553. return CURLE_WEIRD_SERVER_REPLY; /* Forbid pipelining in response. */
  2554. /* RFC2228 (page 5) says:
  2555. *
  2556. * If the server is willing to accept the named security mechanism,
  2557. * and does not require any security data, it must respond with
  2558. * reply code 234/334.
  2559. */
  2560. if((ftpcode == 234) || (ftpcode == 334)) {
  2561. /* this was BLOCKING, keep it so for now */
  2562. bool done;
  2563. if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) {
  2564. result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET);
  2565. if(result) {
  2566. /* we failed and bail out */
  2567. return CURLE_USE_SSL_FAILED;
  2568. }
  2569. }
  2570. result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, &done);
  2571. if(!result) {
  2572. conn->bits.ftp_use_data_ssl = FALSE; /* clear-text data */
  2573. conn->bits.ftp_use_control_ssl = TRUE; /* SSL on control */
  2574. result = ftp_state_user(data, conn);
  2575. }
  2576. }
  2577. else if(ftpc->count3 < 1) {
  2578. ftpc->count3++;
  2579. ftpc->count1 += ftpc->count2; /* get next attempt */
  2580. result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s",
  2581. ftpauth[ftpc->count1]);
  2582. /* remain in this same state */
  2583. }
  2584. else {
  2585. if(data->set.use_ssl > CURLUSESSL_TRY)
  2586. /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */
  2587. result = CURLE_USE_SSL_FAILED;
  2588. else
  2589. /* ignore the failure and continue */
  2590. result = ftp_state_user(data, conn);
  2591. }
  2592. break;
  2593. case FTP_USER:
  2594. case FTP_PASS:
  2595. result = ftp_state_user_resp(data, ftpcode);
  2596. break;
  2597. case FTP_ACCT:
  2598. result = ftp_state_acct_resp(data, ftpcode);
  2599. break;
  2600. case FTP_PBSZ:
  2601. result =
  2602. Curl_pp_sendf(data, &ftpc->pp, "PROT %c",
  2603. data->set.use_ssl == CURLUSESSL_CONTROL ? 'C' : 'P');
  2604. if(!result)
  2605. ftp_state(data, FTP_PROT);
  2606. break;
  2607. case FTP_PROT:
  2608. if(ftpcode/100 == 2)
  2609. /* We have enabled SSL for the data connection! */
  2610. conn->bits.ftp_use_data_ssl =
  2611. (data->set.use_ssl != CURLUSESSL_CONTROL) ? TRUE : FALSE;
  2612. /* FTP servers typically responds with 500 if they decide to reject
  2613. our 'P' request */
  2614. else if(data->set.use_ssl > CURLUSESSL_CONTROL)
  2615. /* we failed and bails out */
  2616. return CURLE_USE_SSL_FAILED;
  2617. if(data->set.ftp_ccc) {
  2618. /* CCC - Clear Command Channel
  2619. */
  2620. result = Curl_pp_sendf(data, &ftpc->pp, "%s", "CCC");
  2621. if(!result)
  2622. ftp_state(data, FTP_CCC);
  2623. }
  2624. else
  2625. result = ftp_state_pwd(data, conn);
  2626. break;
  2627. case FTP_CCC:
  2628. if(ftpcode < 500) {
  2629. /* First shut down the SSL layer (note: this call will block) */
  2630. /* This has only been tested on the proftpd server, and the mod_tls
  2631. * code sends a close notify alert without waiting for a close notify
  2632. * alert in response. Thus we wait for a close notify alert from the
  2633. * server, but we do not send one. Let's hope other servers do
  2634. * the same... */
  2635. result = Curl_ssl_cfilter_remove(data, FIRSTSOCKET,
  2636. (data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE));
  2637. if(result)
  2638. failf(data, "Failed to clear the command channel (CCC)");
  2639. }
  2640. if(!result)
  2641. /* Then continue as normal */
  2642. result = ftp_state_pwd(data, conn);
  2643. break;
  2644. case FTP_PWD:
  2645. if(ftpcode == 257) {
  2646. char *ptr = Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first
  2647. letter */
  2648. bool entry_extracted = FALSE;
  2649. struct dynbuf out;
  2650. Curl_dyn_init(&out, 1000);
  2651. /* Reply format is like
  2652. 257<space>[rubbish]"<directory-name>"<space><commentary> and the
  2653. RFC959 says
  2654. The directory name can contain any character; embedded
  2655. double-quotes should be escaped by double-quotes (the
  2656. "quote-doubling" convention).
  2657. */
  2658. /* scan for the first double-quote for non-standard responses */
  2659. while(*ptr != '\n' && *ptr != '\0' && *ptr != '"')
  2660. ptr++;
  2661. if('\"' == *ptr) {
  2662. /* it started good */
  2663. for(ptr++; *ptr; ptr++) {
  2664. if('\"' == *ptr) {
  2665. if('\"' == ptr[1]) {
  2666. /* "quote-doubling" */
  2667. result = Curl_dyn_addn(&out, &ptr[1], 1);
  2668. ptr++;
  2669. }
  2670. else {
  2671. /* end of path */
  2672. if(Curl_dyn_len(&out))
  2673. entry_extracted = TRUE;
  2674. break; /* get out of this loop */
  2675. }
  2676. }
  2677. else
  2678. result = Curl_dyn_addn(&out, ptr, 1);
  2679. if(result)
  2680. return result;
  2681. }
  2682. }
  2683. if(entry_extracted) {
  2684. /* If the path name does not look like an absolute path (i.e.: it
  2685. does not start with a '/'), we probably need some server-dependent
  2686. adjustments. For example, this is the case when connecting to
  2687. an OS400 FTP server: this server supports two name syntaxes,
  2688. the default one being incompatible with standard paths. In
  2689. addition, this server switches automatically to the regular path
  2690. syntax when one is encountered in a command: this results in
  2691. having an entrypath in the wrong syntax when later used in CWD.
  2692. The method used here is to check the server OS: we do it only
  2693. if the path name looks strange to minimize overhead on other
  2694. systems. */
  2695. char *dir = Curl_dyn_ptr(&out);
  2696. if(!ftpc->server_os && dir[0] != '/') {
  2697. result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SYST");
  2698. if(result) {
  2699. free(dir);
  2700. return result;
  2701. }
  2702. Curl_safefree(ftpc->entrypath);
  2703. ftpc->entrypath = dir; /* remember this */
  2704. infof(data, "Entry path is '%s'", ftpc->entrypath);
  2705. /* also save it where getinfo can access it: */
  2706. data->state.most_recent_ftp_entrypath = ftpc->entrypath;
  2707. ftp_state(data, FTP_SYST);
  2708. break;
  2709. }
  2710. Curl_safefree(ftpc->entrypath);
  2711. ftpc->entrypath = dir; /* remember this */
  2712. infof(data, "Entry path is '%s'", ftpc->entrypath);
  2713. /* also save it where getinfo can access it: */
  2714. data->state.most_recent_ftp_entrypath = ftpc->entrypath;
  2715. }
  2716. else {
  2717. /* could not get the path */
  2718. Curl_dyn_free(&out);
  2719. infof(data, "Failed to figure out path");
  2720. }
  2721. }
  2722. ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */
  2723. CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data));
  2724. break;
  2725. case FTP_SYST:
  2726. if(ftpcode == 215) {
  2727. char *ptr = Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first
  2728. letter */
  2729. char *os;
  2730. char *start;
  2731. /* Reply format is like
  2732. 215<space><OS-name><space><commentary>
  2733. */
  2734. while(*ptr == ' ')
  2735. ptr++;
  2736. for(start = ptr; *ptr && *ptr != ' '; ptr++)
  2737. ;
  2738. os = Curl_memdup0(start, ptr - start);
  2739. if(!os)
  2740. return CURLE_OUT_OF_MEMORY;
  2741. /* Check for special servers here. */
  2742. if(strcasecompare(os, "OS/400")) {
  2743. /* Force OS400 name format 1. */
  2744. result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SITE NAMEFMT 1");
  2745. if(result) {
  2746. free(os);
  2747. return result;
  2748. }
  2749. /* remember target server OS */
  2750. Curl_safefree(ftpc->server_os);
  2751. ftpc->server_os = os;
  2752. ftp_state(data, FTP_NAMEFMT);
  2753. break;
  2754. }
  2755. /* Nothing special for the target server. */
  2756. /* remember target server OS */
  2757. Curl_safefree(ftpc->server_os);
  2758. ftpc->server_os = os;
  2759. }
  2760. else {
  2761. /* Cannot identify server OS. Continue anyway and cross fingers. */
  2762. }
  2763. ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */
  2764. CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data));
  2765. break;
  2766. case FTP_NAMEFMT:
  2767. if(ftpcode == 250) {
  2768. /* Name format change successful: reload initial path. */
  2769. ftp_state_pwd(data, conn);
  2770. break;
  2771. }
  2772. ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */
  2773. CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data));
  2774. break;
  2775. case FTP_QUOTE:
  2776. case FTP_POSTQUOTE:
  2777. case FTP_RETR_PREQUOTE:
  2778. case FTP_STOR_PREQUOTE:
  2779. if((ftpcode >= 400) && !ftpc->count2) {
  2780. /* failure response code, and not allowed to fail */
  2781. failf(data, "QUOT command failed with %03d", ftpcode);
  2782. result = CURLE_QUOTE_ERROR;
  2783. }
  2784. else
  2785. result = ftp_state_quote(data, FALSE, ftpc->state);
  2786. break;
  2787. case FTP_CWD:
  2788. if(ftpcode/100 != 2) {
  2789. /* failure to CWD there */
  2790. if(data->set.ftp_create_missing_dirs &&
  2791. ftpc->cwdcount && !ftpc->count2) {
  2792. /* try making it */
  2793. ftpc->count2++; /* counter to prevent CWD-MKD loops */
  2794. /* count3 is set to allow MKD to fail once per dir. In the case when
  2795. CWD fails and then MKD fails (due to another session raced it to
  2796. create the dir) this then allows for a second try to CWD to it. */
  2797. ftpc->count3 = (data->set.ftp_create_missing_dirs == 2) ? 1 : 0;
  2798. result = Curl_pp_sendf(data, &ftpc->pp, "MKD %s",
  2799. ftpc->dirs[ftpc->cwdcount - 1]);
  2800. if(!result)
  2801. ftp_state(data, FTP_MKD);
  2802. }
  2803. else {
  2804. /* return failure */
  2805. failf(data, "Server denied you to change to the given directory");
  2806. ftpc->cwdfail = TRUE; /* do not remember this path as we failed
  2807. to enter it */
  2808. result = CURLE_REMOTE_ACCESS_DENIED;
  2809. }
  2810. }
  2811. else {
  2812. /* success */
  2813. ftpc->count2 = 0;
  2814. if(++ftpc->cwdcount <= ftpc->dirdepth)
  2815. /* send next CWD */
  2816. result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s",
  2817. ftpc->dirs[ftpc->cwdcount - 1]);
  2818. else
  2819. result = ftp_state_mdtm(data);
  2820. }
  2821. break;
  2822. case FTP_MKD:
  2823. if((ftpcode/100 != 2) && !ftpc->count3--) {
  2824. /* failure to MKD the dir */
  2825. failf(data, "Failed to MKD dir: %03d", ftpcode);
  2826. result = CURLE_REMOTE_ACCESS_DENIED;
  2827. }
  2828. else {
  2829. ftp_state(data, FTP_CWD);
  2830. /* send CWD */
  2831. result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s",
  2832. ftpc->dirs[ftpc->cwdcount - 1]);
  2833. }
  2834. break;
  2835. case FTP_MDTM:
  2836. result = ftp_state_mdtm_resp(data, ftpcode);
  2837. break;
  2838. case FTP_TYPE:
  2839. case FTP_LIST_TYPE:
  2840. case FTP_RETR_TYPE:
  2841. case FTP_STOR_TYPE:
  2842. result = ftp_state_type_resp(data, ftpcode, ftpc->state);
  2843. break;
  2844. case FTP_SIZE:
  2845. case FTP_RETR_SIZE:
  2846. case FTP_STOR_SIZE:
  2847. result = ftp_state_size_resp(data, ftpcode, ftpc->state);
  2848. break;
  2849. case FTP_REST:
  2850. case FTP_RETR_REST:
  2851. result = ftp_state_rest_resp(data, conn, ftpcode, ftpc->state);
  2852. break;
  2853. case FTP_PRET:
  2854. if(ftpcode != 200) {
  2855. /* there only is this one standard OK return code. */
  2856. failf(data, "PRET command not accepted: %03d", ftpcode);
  2857. return CURLE_FTP_PRET_FAILED;
  2858. }
  2859. result = ftp_state_use_pasv(data, conn);
  2860. break;
  2861. case FTP_PASV:
  2862. result = ftp_state_pasv_resp(data, ftpcode);
  2863. break;
  2864. case FTP_PORT:
  2865. result = ftp_state_port_resp(data, ftpcode);
  2866. break;
  2867. case FTP_LIST:
  2868. case FTP_RETR:
  2869. result = ftp_state_get_resp(data, ftpcode, ftpc->state);
  2870. break;
  2871. case FTP_STOR:
  2872. result = ftp_state_stor_resp(data, ftpcode, ftpc->state);
  2873. break;
  2874. case FTP_QUIT:
  2875. default:
  2876. /* internal error */
  2877. ftp_state(data, FTP_STOP);
  2878. break;
  2879. }
  2880. } /* if(ftpcode) */
  2881. return result;
  2882. }
  2883. /* called repeatedly until done from multi.c */
  2884. static CURLcode ftp_multi_statemach(struct Curl_easy *data,
  2885. bool *done)
  2886. {
  2887. struct connectdata *conn = data->conn;
  2888. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2889. CURLcode result = Curl_pp_statemach(data, &ftpc->pp, FALSE, FALSE);
  2890. /* Check for the state outside of the Curl_socket_check() return code checks
  2891. since at times we are in fact already in this state when this function
  2892. gets called. */
  2893. *done = (ftpc->state == FTP_STOP) ? TRUE : FALSE;
  2894. return result;
  2895. }
  2896. static CURLcode ftp_block_statemach(struct Curl_easy *data,
  2897. struct connectdata *conn)
  2898. {
  2899. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2900. struct pingpong *pp = &ftpc->pp;
  2901. CURLcode result = CURLE_OK;
  2902. while(ftpc->state != FTP_STOP) {
  2903. result = Curl_pp_statemach(data, pp, TRUE, TRUE /* disconnecting */);
  2904. if(result)
  2905. break;
  2906. }
  2907. return result;
  2908. }
  2909. /*
  2910. * ftp_connect() should do everything that is to be considered a part of
  2911. * the connection phase.
  2912. *
  2913. * The variable 'done' points to will be TRUE if the protocol-layer connect
  2914. * phase is done when this function returns, or FALSE if not.
  2915. *
  2916. */
  2917. static CURLcode ftp_connect(struct Curl_easy *data,
  2918. bool *done) /* see description above */
  2919. {
  2920. CURLcode result;
  2921. struct connectdata *conn = data->conn;
  2922. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2923. struct pingpong *pp = &ftpc->pp;
  2924. *done = FALSE; /* default to not done yet */
  2925. /* We always support persistent connections on ftp */
  2926. connkeep(conn, "FTP default");
  2927. PINGPONG_SETUP(pp, ftp_statemachine, ftp_endofresp);
  2928. if(conn->handler->flags & PROTOPT_SSL) {
  2929. /* BLOCKING */
  2930. result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, done);
  2931. if(result)
  2932. return result;
  2933. conn->bits.ftp_use_control_ssl = TRUE;
  2934. }
  2935. Curl_pp_init(pp); /* once per transfer */
  2936. /* When we connect, we start in the state where we await the 220
  2937. response */
  2938. ftp_state(data, FTP_WAIT220);
  2939. result = ftp_multi_statemach(data, done);
  2940. return result;
  2941. }
  2942. /***********************************************************************
  2943. *
  2944. * ftp_done()
  2945. *
  2946. * The DONE function. This does what needs to be done after a single DO has
  2947. * performed.
  2948. *
  2949. * Input argument is already checked for validity.
  2950. */
  2951. static CURLcode ftp_done(struct Curl_easy *data, CURLcode status,
  2952. bool premature)
  2953. {
  2954. struct connectdata *conn = data->conn;
  2955. struct FTP *ftp = data->req.p.ftp;
  2956. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2957. struct pingpong *pp = &ftpc->pp;
  2958. ssize_t nread;
  2959. int ftpcode;
  2960. CURLcode result = CURLE_OK;
  2961. char *rawPath = NULL;
  2962. size_t pathLen = 0;
  2963. if(!ftp)
  2964. return CURLE_OK;
  2965. switch(status) {
  2966. case CURLE_BAD_DOWNLOAD_RESUME:
  2967. case CURLE_FTP_WEIRD_PASV_REPLY:
  2968. case CURLE_FTP_PORT_FAILED:
  2969. case CURLE_FTP_ACCEPT_FAILED:
  2970. case CURLE_FTP_ACCEPT_TIMEOUT:
  2971. case CURLE_FTP_COULDNT_SET_TYPE:
  2972. case CURLE_FTP_COULDNT_RETR_FILE:
  2973. case CURLE_PARTIAL_FILE:
  2974. case CURLE_UPLOAD_FAILED:
  2975. case CURLE_REMOTE_ACCESS_DENIED:
  2976. case CURLE_FILESIZE_EXCEEDED:
  2977. case CURLE_REMOTE_FILE_NOT_FOUND:
  2978. case CURLE_WRITE_ERROR:
  2979. /* the connection stays alive fine even though this happened */
  2980. case CURLE_OK: /* does not affect the control connection's status */
  2981. if(!premature)
  2982. break;
  2983. /* until we cope better with prematurely ended requests, let them
  2984. * fallback as if in complete failure */
  2985. FALLTHROUGH();
  2986. default: /* by default, an error means the control connection is
  2987. wedged and should not be used anymore */
  2988. ftpc->ctl_valid = FALSE;
  2989. ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the
  2990. current path, as this connection is going */
  2991. connclose(conn, "FTP ended with bad error code");
  2992. result = status; /* use the already set error code */
  2993. break;
  2994. }
  2995. if(data->state.wildcardmatch) {
  2996. if(data->set.chunk_end && ftpc->file) {
  2997. Curl_set_in_callback(data, true);
  2998. data->set.chunk_end(data->set.wildcardptr);
  2999. Curl_set_in_callback(data, false);
  3000. }
  3001. ftpc->known_filesize = -1;
  3002. }
  3003. if(!result)
  3004. /* get the url-decoded "raw" path */
  3005. result = Curl_urldecode(ftp->path, 0, &rawPath, &pathLen,
  3006. REJECT_CTRL);
  3007. if(result) {
  3008. /* We can limp along anyway (and should try to since we may already be in
  3009. * the error path) */
  3010. ftpc->ctl_valid = FALSE; /* mark control connection as bad */
  3011. connclose(conn, "FTP: out of memory!"); /* mark for connection closure */
  3012. free(ftpc->prevpath);
  3013. ftpc->prevpath = NULL; /* no path remembering */
  3014. }
  3015. else { /* remember working directory for connection reuse */
  3016. if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
  3017. free(rawPath); /* full path => no CWDs happened => keep ftpc->prevpath */
  3018. else {
  3019. free(ftpc->prevpath);
  3020. if(!ftpc->cwdfail) {
  3021. if(data->set.ftp_filemethod == FTPFILE_NOCWD)
  3022. pathLen = 0; /* relative path => working directory is FTP home */
  3023. else
  3024. pathLen -= ftpc->file?strlen(ftpc->file):0; /* file is url-decoded */
  3025. rawPath[pathLen] = '\0';
  3026. ftpc->prevpath = rawPath;
  3027. }
  3028. else {
  3029. free(rawPath);
  3030. ftpc->prevpath = NULL; /* no path */
  3031. }
  3032. }
  3033. if(ftpc->prevpath)
  3034. infof(data, "Remembering we are in dir \"%s\"", ftpc->prevpath);
  3035. }
  3036. /* free the dir tree and file parts */
  3037. freedirs(ftpc);
  3038. /* shut down the socket to inform the server we are done */
  3039. #ifdef _WIN32_WCE
  3040. shutdown(conn->sock[SECONDARYSOCKET], 2); /* SD_BOTH */
  3041. #endif
  3042. if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) {
  3043. if(!result && ftpc->dont_check && data->req.maxdownload > 0) {
  3044. /* partial download completed */
  3045. result = Curl_pp_sendf(data, pp, "%s", "ABOR");
  3046. if(result) {
  3047. failf(data, "Failure sending ABOR command: %s",
  3048. curl_easy_strerror(result));
  3049. ftpc->ctl_valid = FALSE; /* mark control connection as bad */
  3050. connclose(conn, "ABOR command failed"); /* connection closure */
  3051. }
  3052. }
  3053. close_secondarysocket(data);
  3054. }
  3055. if(!result && (ftp->transfer == PPTRANSFER_BODY) && ftpc->ctl_valid &&
  3056. pp->pending_resp && !premature) {
  3057. /*
  3058. * Let's see what the server says about the transfer we just performed,
  3059. * but lower the timeout as sometimes this connection has died while the
  3060. * data has been transferred. This happens when doing through NATs etc that
  3061. * abandon old silent connections.
  3062. */
  3063. timediff_t old_time = pp->response_time;
  3064. pp->response_time = 60*1000; /* give it only a minute for now */
  3065. pp->response = Curl_now(); /* timeout relative now */
  3066. result = Curl_GetFTPResponse(data, &nread, &ftpcode);
  3067. pp->response_time = old_time; /* set this back to previous value */
  3068. if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) {
  3069. failf(data, "control connection looks dead");
  3070. ftpc->ctl_valid = FALSE; /* mark control connection as bad */
  3071. connclose(conn, "Timeout or similar in FTP DONE operation"); /* close */
  3072. }
  3073. if(result) {
  3074. Curl_safefree(ftp->pathalloc);
  3075. return result;
  3076. }
  3077. if(ftpc->dont_check && data->req.maxdownload > 0) {
  3078. /* we have just sent ABOR and there is no reliable way to check if it was
  3079. * successful or not; we have to close the connection now */
  3080. infof(data, "partial download completed, closing connection");
  3081. connclose(conn, "Partial download with no ability to check");
  3082. return result;
  3083. }
  3084. if(!ftpc->dont_check) {
  3085. /* 226 Transfer complete, 250 Requested file action okay, completed. */
  3086. switch(ftpcode) {
  3087. case 226:
  3088. case 250:
  3089. break;
  3090. case 552:
  3091. failf(data, "Exceeded storage allocation");
  3092. result = CURLE_REMOTE_DISK_FULL;
  3093. break;
  3094. default:
  3095. failf(data, "server did not report OK, got %d", ftpcode);
  3096. result = CURLE_PARTIAL_FILE;
  3097. break;
  3098. }
  3099. }
  3100. }
  3101. if(result || premature)
  3102. /* the response code from the transfer showed an error already so no
  3103. use checking further */
  3104. ;
  3105. else if(data->state.upload) {
  3106. if((-1 != data->state.infilesize) &&
  3107. (data->state.infilesize != data->req.writebytecount) &&
  3108. !data->set.crlf &&
  3109. (ftp->transfer == PPTRANSFER_BODY)) {
  3110. failf(data, "Uploaded unaligned file size (%" FMT_OFF_T
  3111. " out of %" FMT_OFF_T " bytes)",
  3112. data->req.writebytecount, data->state.infilesize);
  3113. result = CURLE_PARTIAL_FILE;
  3114. }
  3115. }
  3116. else {
  3117. if((-1 != data->req.size) &&
  3118. (data->req.size != data->req.bytecount) &&
  3119. (data->req.maxdownload != data->req.bytecount)) {
  3120. failf(data, "Received only partial file: %" FMT_OFF_T " bytes",
  3121. data->req.bytecount);
  3122. result = CURLE_PARTIAL_FILE;
  3123. }
  3124. else if(!ftpc->dont_check &&
  3125. !data->req.bytecount &&
  3126. (data->req.size>0)) {
  3127. failf(data, "No data was received");
  3128. result = CURLE_FTP_COULDNT_RETR_FILE;
  3129. }
  3130. }
  3131. /* clear these for next connection */
  3132. ftp->transfer = PPTRANSFER_BODY;
  3133. ftpc->dont_check = FALSE;
  3134. /* Send any post-transfer QUOTE strings? */
  3135. if(!status && !result && !premature && data->set.postquote)
  3136. result = ftp_sendquote(data, conn, data->set.postquote);
  3137. CURL_TRC_FTP(data, "[%s] done, result=%d", FTP_DSTATE(data), result);
  3138. Curl_safefree(ftp->pathalloc);
  3139. return result;
  3140. }
  3141. /***********************************************************************
  3142. *
  3143. * ftp_sendquote()
  3144. *
  3145. * Where a 'quote' means a list of custom commands to send to the server.
  3146. * The quote list is passed as an argument.
  3147. *
  3148. * BLOCKING
  3149. */
  3150. static
  3151. CURLcode ftp_sendquote(struct Curl_easy *data,
  3152. struct connectdata *conn, struct curl_slist *quote)
  3153. {
  3154. struct curl_slist *item;
  3155. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3156. struct pingpong *pp = &ftpc->pp;
  3157. item = quote;
  3158. while(item) {
  3159. if(item->data) {
  3160. ssize_t nread;
  3161. char *cmd = item->data;
  3162. bool acceptfail = FALSE;
  3163. CURLcode result;
  3164. int ftpcode = 0;
  3165. /* if a command starts with an asterisk, which a legal FTP command never
  3166. can, the command will be allowed to fail without it causing any
  3167. aborts or cancels etc. It will cause libcurl to act as if the command
  3168. is successful, whatever the server responds. */
  3169. if(cmd[0] == '*') {
  3170. cmd++;
  3171. acceptfail = TRUE;
  3172. }
  3173. result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd);
  3174. if(!result) {
  3175. pp->response = Curl_now(); /* timeout relative now */
  3176. result = Curl_GetFTPResponse(data, &nread, &ftpcode);
  3177. }
  3178. if(result)
  3179. return result;
  3180. if(!acceptfail && (ftpcode >= 400)) {
  3181. failf(data, "QUOT string not accepted: %s", cmd);
  3182. return CURLE_QUOTE_ERROR;
  3183. }
  3184. }
  3185. item = item->next;
  3186. }
  3187. return CURLE_OK;
  3188. }
  3189. /***********************************************************************
  3190. *
  3191. * ftp_need_type()
  3192. *
  3193. * Returns TRUE if we in the current situation should send TYPE
  3194. */
  3195. static int ftp_need_type(struct connectdata *conn,
  3196. bool ascii_wanted)
  3197. {
  3198. return conn->proto.ftpc.transfertype != (ascii_wanted?'A':'I');
  3199. }
  3200. /***********************************************************************
  3201. *
  3202. * ftp_nb_type()
  3203. *
  3204. * Set TYPE. We only deal with ASCII or BINARY so this function
  3205. * sets one of them.
  3206. * If the transfer type is not sent, simulate on OK response in newstate
  3207. */
  3208. static CURLcode ftp_nb_type(struct Curl_easy *data,
  3209. struct connectdata *conn,
  3210. bool ascii, ftpstate newstate)
  3211. {
  3212. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3213. CURLcode result;
  3214. char want = (char)(ascii?'A':'I');
  3215. if(ftpc->transfertype == want) {
  3216. ftp_state(data, newstate);
  3217. return ftp_state_type_resp(data, 200, newstate);
  3218. }
  3219. result = Curl_pp_sendf(data, &ftpc->pp, "TYPE %c", want);
  3220. if(!result) {
  3221. ftp_state(data, newstate);
  3222. /* keep track of our current transfer type */
  3223. ftpc->transfertype = want;
  3224. }
  3225. return result;
  3226. }
  3227. /***************************************************************************
  3228. *
  3229. * ftp_pasv_verbose()
  3230. *
  3231. * This function only outputs some informationals about this second connection
  3232. * when we have issued a PASV command before and thus we have connected to a
  3233. * possibly new IP address.
  3234. *
  3235. */
  3236. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  3237. static void
  3238. ftp_pasv_verbose(struct Curl_easy *data,
  3239. struct Curl_addrinfo *ai,
  3240. char *newhost, /* ASCII version */
  3241. int port)
  3242. {
  3243. char buf[256];
  3244. Curl_printable_address(ai, buf, sizeof(buf));
  3245. infof(data, "Connecting to %s (%s) port %d", newhost, buf, port);
  3246. }
  3247. #endif
  3248. /*
  3249. * ftp_do_more()
  3250. *
  3251. * This function shall be called when the second FTP (data) connection is
  3252. * connected.
  3253. *
  3254. * 'complete' can return 0 for incomplete, 1 for done and -1 for go back
  3255. * (which basically is only for when PASV is being sent to retry a failed
  3256. * EPSV).
  3257. */
  3258. static CURLcode ftp_do_more(struct Curl_easy *data, int *completep)
  3259. {
  3260. struct connectdata *conn = data->conn;
  3261. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3262. CURLcode result = CURLE_OK;
  3263. bool connected = FALSE;
  3264. bool complete = FALSE;
  3265. /* the ftp struct is inited in ftp_connect(). If we are connecting to an HTTP
  3266. * proxy then the state will not be valid until after that connection is
  3267. * complete */
  3268. struct FTP *ftp = NULL;
  3269. /* if the second connection is not done yet, wait for it to have
  3270. * connected to the remote host. When using proxy tunneling, this
  3271. * means the tunnel needs to have been establish. However, we
  3272. * can not expect the remote host to talk to us in any way yet.
  3273. * So, when using ftps: the SSL handshake will not start until we
  3274. * tell the remote server that we are there. */
  3275. if(conn->cfilter[SECONDARYSOCKET]) {
  3276. result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected);
  3277. if(result || !Curl_conn_is_ip_connected(data, SECONDARYSOCKET)) {
  3278. if(result && (ftpc->count1 == 0)) {
  3279. *completep = -1; /* go back to DOING please */
  3280. /* this is a EPSV connect failing, try PASV instead */
  3281. return ftp_epsv_disable(data, conn);
  3282. }
  3283. return result;
  3284. }
  3285. }
  3286. /* Curl_proxy_connect might have moved the protocol state */
  3287. ftp = data->req.p.ftp;
  3288. if(ftpc->state) {
  3289. /* already in a state so skip the initial commands.
  3290. They are only done to kickstart the do_more state */
  3291. result = ftp_multi_statemach(data, &complete);
  3292. *completep = (int)complete;
  3293. /* if we got an error or if we do not wait for a data connection return
  3294. immediately */
  3295. if(result || !ftpc->wait_data_conn)
  3296. return result;
  3297. /* if we reach the end of the FTP state machine here, *complete will be
  3298. TRUE but so is ftpc->wait_data_conn, which says we need to wait for the
  3299. data connection and therefore we are not actually complete */
  3300. *completep = 0;
  3301. }
  3302. if(ftp->transfer <= PPTRANSFER_INFO) {
  3303. /* a transfer is about to take place, or if not a filename was given so we
  3304. will do a SIZE on it later and then we need the right TYPE first */
  3305. if(ftpc->wait_data_conn) {
  3306. bool serv_conned;
  3307. result = ReceivedServerConnect(data, &serv_conned);
  3308. if(result)
  3309. return result; /* Failed to accept data connection */
  3310. if(serv_conned) {
  3311. /* It looks data connection is established */
  3312. result = AcceptServerConnect(data);
  3313. ftpc->wait_data_conn = FALSE;
  3314. if(!result)
  3315. result = InitiateTransfer(data);
  3316. if(result)
  3317. return result;
  3318. *completep = 1; /* this state is now complete when the server has
  3319. connected back to us */
  3320. }
  3321. }
  3322. else if(data->state.upload) {
  3323. result = ftp_nb_type(data, conn, data->state.prefer_ascii,
  3324. FTP_STOR_TYPE);
  3325. if(result)
  3326. return result;
  3327. result = ftp_multi_statemach(data, &complete);
  3328. *completep = (int)complete;
  3329. }
  3330. else {
  3331. /* download */
  3332. ftp->downloadsize = -1; /* unknown as of yet */
  3333. result = Curl_range(data);
  3334. if(result == CURLE_OK && data->req.maxdownload >= 0) {
  3335. /* Do not check for successful transfer */
  3336. ftpc->dont_check = TRUE;
  3337. }
  3338. if(result)
  3339. ;
  3340. else if(data->state.list_only || !ftpc->file) {
  3341. /* The specified path ends with a slash, and therefore we think this
  3342. is a directory that is requested, use LIST. But before that we
  3343. need to set ASCII transfer mode. */
  3344. /* But only if a body transfer was requested. */
  3345. if(ftp->transfer == PPTRANSFER_BODY) {
  3346. result = ftp_nb_type(data, conn, TRUE, FTP_LIST_TYPE);
  3347. if(result)
  3348. return result;
  3349. }
  3350. /* otherwise just fall through */
  3351. }
  3352. else {
  3353. result = ftp_nb_type(data, conn, data->state.prefer_ascii,
  3354. FTP_RETR_TYPE);
  3355. if(result)
  3356. return result;
  3357. }
  3358. result = ftp_multi_statemach(data, &complete);
  3359. *completep = (int)complete;
  3360. }
  3361. return result;
  3362. }
  3363. /* no data to transfer */
  3364. Curl_xfer_setup_nop(data);
  3365. if(!ftpc->wait_data_conn) {
  3366. /* no waiting for the data connection so this is now complete */
  3367. *completep = 1;
  3368. CURL_TRC_FTP(data, "[%s] DO-MORE phase ends with %d", FTP_DSTATE(data),
  3369. (int)result);
  3370. }
  3371. return result;
  3372. }
  3373. /***********************************************************************
  3374. *
  3375. * ftp_perform()
  3376. *
  3377. * This is the actual DO function for FTP. Get a file/directory according to
  3378. * the options previously setup.
  3379. */
  3380. static
  3381. CURLcode ftp_perform(struct Curl_easy *data,
  3382. bool *connected, /* connect status after PASV / PORT */
  3383. bool *dophase_done)
  3384. {
  3385. /* this is FTP and no proxy */
  3386. CURLcode result = CURLE_OK;
  3387. CURL_TRC_FTP(data, "[%s] DO phase starts", FTP_DSTATE(data));
  3388. if(data->req.no_body) {
  3389. /* requested no body means no transfer... */
  3390. struct FTP *ftp = data->req.p.ftp;
  3391. ftp->transfer = PPTRANSFER_INFO;
  3392. }
  3393. *dophase_done = FALSE; /* not done yet */
  3394. /* start the first command in the DO phase */
  3395. result = ftp_state_quote(data, TRUE, FTP_QUOTE);
  3396. if(result)
  3397. return result;
  3398. /* run the state-machine */
  3399. result = ftp_multi_statemach(data, dophase_done);
  3400. *connected = Curl_conn_is_connected(data->conn, SECONDARYSOCKET);
  3401. if(*connected)
  3402. infof(data, "[FTP] [%s] perform, DATA connection established",
  3403. FTP_DSTATE(data));
  3404. else
  3405. CURL_TRC_FTP(data, "[%s] perform, awaiting DATA connect",
  3406. FTP_DSTATE(data));
  3407. if(*dophase_done)
  3408. CURL_TRC_FTP(data, "[%s] DO phase is complete1", FTP_DSTATE(data));
  3409. return result;
  3410. }
  3411. static void wc_data_dtor(void *ptr)
  3412. {
  3413. struct ftp_wc *ftpwc = ptr;
  3414. if(ftpwc && ftpwc->parser)
  3415. Curl_ftp_parselist_data_free(&ftpwc->parser);
  3416. free(ftpwc);
  3417. }
  3418. static CURLcode init_wc_data(struct Curl_easy *data)
  3419. {
  3420. char *last_slash;
  3421. struct FTP *ftp = data->req.p.ftp;
  3422. char *path = ftp->path;
  3423. struct WildcardData *wildcard = data->wildcard;
  3424. CURLcode result = CURLE_OK;
  3425. struct ftp_wc *ftpwc = NULL;
  3426. last_slash = strrchr(ftp->path, '/');
  3427. if(last_slash) {
  3428. last_slash++;
  3429. if(last_slash[0] == '\0') {
  3430. wildcard->state = CURLWC_CLEAN;
  3431. result = ftp_parse_url_path(data);
  3432. return result;
  3433. }
  3434. wildcard->pattern = strdup(last_slash);
  3435. if(!wildcard->pattern)
  3436. return CURLE_OUT_OF_MEMORY;
  3437. last_slash[0] = '\0'; /* cut file from path */
  3438. }
  3439. else { /* there is only 'wildcard pattern' or nothing */
  3440. if(path[0]) {
  3441. wildcard->pattern = strdup(path);
  3442. if(!wildcard->pattern)
  3443. return CURLE_OUT_OF_MEMORY;
  3444. path[0] = '\0';
  3445. }
  3446. else { /* only list */
  3447. wildcard->state = CURLWC_CLEAN;
  3448. result = ftp_parse_url_path(data);
  3449. return result;
  3450. }
  3451. }
  3452. /* program continues only if URL is not ending with slash, allocate needed
  3453. resources for wildcard transfer */
  3454. /* allocate ftp protocol specific wildcard data */
  3455. ftpwc = calloc(1, sizeof(struct ftp_wc));
  3456. if(!ftpwc) {
  3457. result = CURLE_OUT_OF_MEMORY;
  3458. goto fail;
  3459. }
  3460. /* INITIALIZE parselist structure */
  3461. ftpwc->parser = Curl_ftp_parselist_data_alloc();
  3462. if(!ftpwc->parser) {
  3463. result = CURLE_OUT_OF_MEMORY;
  3464. goto fail;
  3465. }
  3466. wildcard->ftpwc = ftpwc; /* put it to the WildcardData tmp pointer */
  3467. wildcard->dtor = wc_data_dtor;
  3468. /* wildcard does not support NOCWD option (assert it?) */
  3469. if(data->set.ftp_filemethod == FTPFILE_NOCWD)
  3470. data->set.ftp_filemethod = FTPFILE_MULTICWD;
  3471. /* try to parse ftp URL */
  3472. result = ftp_parse_url_path(data);
  3473. if(result) {
  3474. goto fail;
  3475. }
  3476. wildcard->path = strdup(ftp->path);
  3477. if(!wildcard->path) {
  3478. result = CURLE_OUT_OF_MEMORY;
  3479. goto fail;
  3480. }
  3481. /* backup old write_function */
  3482. ftpwc->backup.write_function = data->set.fwrite_func;
  3483. /* parsing write function */
  3484. data->set.fwrite_func = Curl_ftp_parselist;
  3485. /* backup old file descriptor */
  3486. ftpwc->backup.file_descriptor = data->set.out;
  3487. /* let the writefunc callback know the transfer */
  3488. data->set.out = data;
  3489. infof(data, "Wildcard - Parsing started");
  3490. return CURLE_OK;
  3491. fail:
  3492. if(ftpwc) {
  3493. Curl_ftp_parselist_data_free(&ftpwc->parser);
  3494. free(ftpwc);
  3495. }
  3496. Curl_safefree(wildcard->pattern);
  3497. wildcard->dtor = ZERO_NULL;
  3498. wildcard->ftpwc = NULL;
  3499. return result;
  3500. }
  3501. static CURLcode wc_statemach(struct Curl_easy *data)
  3502. {
  3503. struct WildcardData * const wildcard = data->wildcard;
  3504. struct connectdata *conn = data->conn;
  3505. CURLcode result = CURLE_OK;
  3506. for(;;) {
  3507. switch(wildcard->state) {
  3508. case CURLWC_INIT:
  3509. result = init_wc_data(data);
  3510. if(wildcard->state == CURLWC_CLEAN)
  3511. /* only listing! */
  3512. return result;
  3513. wildcard->state = result ? CURLWC_ERROR : CURLWC_MATCHING;
  3514. return result;
  3515. case CURLWC_MATCHING: {
  3516. /* In this state is LIST response successfully parsed, so lets restore
  3517. previous WRITEFUNCTION callback and WRITEDATA pointer */
  3518. struct ftp_wc *ftpwc = wildcard->ftpwc;
  3519. data->set.fwrite_func = ftpwc->backup.write_function;
  3520. data->set.out = ftpwc->backup.file_descriptor;
  3521. ftpwc->backup.write_function = ZERO_NULL;
  3522. ftpwc->backup.file_descriptor = NULL;
  3523. wildcard->state = CURLWC_DOWNLOADING;
  3524. if(Curl_ftp_parselist_geterror(ftpwc->parser)) {
  3525. /* error found in LIST parsing */
  3526. wildcard->state = CURLWC_CLEAN;
  3527. continue;
  3528. }
  3529. if(Curl_llist_count(&wildcard->filelist) == 0) {
  3530. /* no corresponding file */
  3531. wildcard->state = CURLWC_CLEAN;
  3532. return CURLE_REMOTE_FILE_NOT_FOUND;
  3533. }
  3534. continue;
  3535. }
  3536. case CURLWC_DOWNLOADING: {
  3537. /* filelist has at least one file, lets get first one */
  3538. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3539. struct Curl_llist_node *head = Curl_llist_head(&wildcard->filelist);
  3540. struct curl_fileinfo *finfo = Curl_node_elem(head);
  3541. struct FTP *ftp = data->req.p.ftp;
  3542. char *tmp_path = aprintf("%s%s", wildcard->path, finfo->filename);
  3543. if(!tmp_path)
  3544. return CURLE_OUT_OF_MEMORY;
  3545. /* switch default ftp->path and tmp_path */
  3546. free(ftp->pathalloc);
  3547. ftp->pathalloc = ftp->path = tmp_path;
  3548. infof(data, "Wildcard - START of \"%s\"", finfo->filename);
  3549. if(data->set.chunk_bgn) {
  3550. long userresponse;
  3551. Curl_set_in_callback(data, true);
  3552. userresponse = data->set.chunk_bgn(
  3553. finfo, data->set.wildcardptr,
  3554. (int)Curl_llist_count(&wildcard->filelist));
  3555. Curl_set_in_callback(data, false);
  3556. switch(userresponse) {
  3557. case CURL_CHUNK_BGN_FUNC_SKIP:
  3558. infof(data, "Wildcard - \"%s\" skipped by user",
  3559. finfo->filename);
  3560. wildcard->state = CURLWC_SKIP;
  3561. continue;
  3562. case CURL_CHUNK_BGN_FUNC_FAIL:
  3563. return CURLE_CHUNK_FAILED;
  3564. }
  3565. }
  3566. if(finfo->filetype != CURLFILETYPE_FILE) {
  3567. wildcard->state = CURLWC_SKIP;
  3568. continue;
  3569. }
  3570. if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE)
  3571. ftpc->known_filesize = finfo->size;
  3572. result = ftp_parse_url_path(data);
  3573. if(result)
  3574. return result;
  3575. /* we do not need the Curl_fileinfo of first file anymore */
  3576. Curl_node_remove(Curl_llist_head(&wildcard->filelist));
  3577. if(Curl_llist_count(&wildcard->filelist) == 0) {
  3578. /* remains only one file to down. */
  3579. wildcard->state = CURLWC_CLEAN;
  3580. /* after that will be ftp_do called once again and no transfer
  3581. will be done because of CURLWC_CLEAN state */
  3582. return CURLE_OK;
  3583. }
  3584. return result;
  3585. }
  3586. case CURLWC_SKIP: {
  3587. if(data->set.chunk_end) {
  3588. Curl_set_in_callback(data, true);
  3589. data->set.chunk_end(data->set.wildcardptr);
  3590. Curl_set_in_callback(data, false);
  3591. }
  3592. Curl_node_remove(Curl_llist_head(&wildcard->filelist));
  3593. wildcard->state = (Curl_llist_count(&wildcard->filelist) == 0) ?
  3594. CURLWC_CLEAN : CURLWC_DOWNLOADING;
  3595. continue;
  3596. }
  3597. case CURLWC_CLEAN: {
  3598. struct ftp_wc *ftpwc = wildcard->ftpwc;
  3599. result = CURLE_OK;
  3600. if(ftpwc)
  3601. result = Curl_ftp_parselist_geterror(ftpwc->parser);
  3602. wildcard->state = result ? CURLWC_ERROR : CURLWC_DONE;
  3603. return result;
  3604. }
  3605. case CURLWC_DONE:
  3606. case CURLWC_ERROR:
  3607. case CURLWC_CLEAR:
  3608. if(wildcard->dtor) {
  3609. wildcard->dtor(wildcard->ftpwc);
  3610. wildcard->ftpwc = NULL;
  3611. }
  3612. return result;
  3613. }
  3614. }
  3615. /* UNREACHABLE */
  3616. }
  3617. /***********************************************************************
  3618. *
  3619. * ftp_do()
  3620. *
  3621. * This function is registered as 'curl_do' function. It decodes the path
  3622. * parts etc as a wrapper to the actual DO function (ftp_perform).
  3623. *
  3624. * The input argument is already checked for validity.
  3625. */
  3626. static CURLcode ftp_do(struct Curl_easy *data, bool *done)
  3627. {
  3628. CURLcode result = CURLE_OK;
  3629. struct connectdata *conn = data->conn;
  3630. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3631. *done = FALSE; /* default to false */
  3632. ftpc->wait_data_conn = FALSE; /* default to no such wait */
  3633. #ifdef CURL_PREFER_LF_LINEENDS
  3634. {
  3635. /* FTP data may need conversion. */
  3636. struct Curl_cwriter *ftp_lc_writer;
  3637. result = Curl_cwriter_create(&ftp_lc_writer, data, &ftp_cw_lc,
  3638. CURL_CW_CONTENT_DECODE);
  3639. if(result)
  3640. return result;
  3641. result = Curl_cwriter_add(data, ftp_lc_writer);
  3642. if(result) {
  3643. Curl_cwriter_free(data, ftp_lc_writer);
  3644. return result;
  3645. }
  3646. }
  3647. #endif /* CURL_PREFER_LF_LINEENDS */
  3648. if(data->state.wildcardmatch) {
  3649. result = wc_statemach(data);
  3650. if(data->wildcard->state == CURLWC_SKIP ||
  3651. data->wildcard->state == CURLWC_DONE) {
  3652. /* do not call ftp_regular_transfer */
  3653. return CURLE_OK;
  3654. }
  3655. if(result) /* error, loop or skipping the file */
  3656. return result;
  3657. }
  3658. else { /* no wildcard FSM needed */
  3659. result = ftp_parse_url_path(data);
  3660. if(result)
  3661. return result;
  3662. }
  3663. result = ftp_regular_transfer(data, done);
  3664. return result;
  3665. }
  3666. /***********************************************************************
  3667. *
  3668. * ftp_quit()
  3669. *
  3670. * This should be called before calling sclose() on an ftp control connection
  3671. * (not data connections). We should then wait for the response from the
  3672. * server before returning. The calling code should then try to close the
  3673. * connection.
  3674. *
  3675. */
  3676. static CURLcode ftp_quit(struct Curl_easy *data, struct connectdata *conn)
  3677. {
  3678. CURLcode result = CURLE_OK;
  3679. if(conn->proto.ftpc.ctl_valid) {
  3680. result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", "QUIT");
  3681. if(result) {
  3682. failf(data, "Failure sending QUIT command: %s",
  3683. curl_easy_strerror(result));
  3684. conn->proto.ftpc.ctl_valid = FALSE; /* mark control connection as bad */
  3685. connclose(conn, "QUIT command failed"); /* mark for connection closure */
  3686. ftp_state(data, FTP_STOP);
  3687. return result;
  3688. }
  3689. ftp_state(data, FTP_QUIT);
  3690. result = ftp_block_statemach(data, conn);
  3691. }
  3692. return result;
  3693. }
  3694. /***********************************************************************
  3695. *
  3696. * ftp_disconnect()
  3697. *
  3698. * Disconnect from an FTP server. Cleanup protocol-specific per-connection
  3699. * resources. BLOCKING.
  3700. */
  3701. static CURLcode ftp_disconnect(struct Curl_easy *data,
  3702. struct connectdata *conn,
  3703. bool dead_connection)
  3704. {
  3705. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3706. struct pingpong *pp = &ftpc->pp;
  3707. /* We cannot send quit unconditionally. If this connection is stale or
  3708. bad in any way, sending quit and waiting around here will make the
  3709. disconnect wait in vain and cause more problems than we need to.
  3710. ftp_quit() will check the state of ftp->ctl_valid. If it is ok it
  3711. will try to send the QUIT command, otherwise it will just return.
  3712. */
  3713. if(dead_connection)
  3714. ftpc->ctl_valid = FALSE;
  3715. /* The FTP session may or may not have been allocated/setup at this point! */
  3716. (void)ftp_quit(data, conn); /* ignore errors on the QUIT */
  3717. if(ftpc->entrypath) {
  3718. if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) {
  3719. data->state.most_recent_ftp_entrypath = NULL;
  3720. }
  3721. Curl_safefree(ftpc->entrypath);
  3722. }
  3723. freedirs(ftpc);
  3724. Curl_safefree(ftpc->account);
  3725. Curl_safefree(ftpc->alternative_to_user);
  3726. Curl_safefree(ftpc->prevpath);
  3727. Curl_safefree(ftpc->server_os);
  3728. Curl_pp_disconnect(pp);
  3729. Curl_sec_end(conn);
  3730. return CURLE_OK;
  3731. }
  3732. #ifdef _MSC_VER
  3733. /* warning C4706: assignment within conditional expression */
  3734. #pragma warning(disable:4706)
  3735. #endif
  3736. /***********************************************************************
  3737. *
  3738. * ftp_parse_url_path()
  3739. *
  3740. * Parse the URL path into separate path components.
  3741. *
  3742. */
  3743. static
  3744. CURLcode ftp_parse_url_path(struct Curl_easy *data)
  3745. {
  3746. /* the ftp struct is already inited in ftp_connect() */
  3747. struct FTP *ftp = data->req.p.ftp;
  3748. struct connectdata *conn = data->conn;
  3749. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3750. const char *slashPos = NULL;
  3751. const char *fileName = NULL;
  3752. CURLcode result = CURLE_OK;
  3753. char *rawPath = NULL; /* url-decoded "raw" path */
  3754. size_t pathLen = 0;
  3755. ftpc->ctl_valid = FALSE;
  3756. ftpc->cwdfail = FALSE;
  3757. /* url-decode ftp path before further evaluation */
  3758. result = Curl_urldecode(ftp->path, 0, &rawPath, &pathLen, REJECT_CTRL);
  3759. if(result) {
  3760. failf(data, "path contains control characters");
  3761. return result;
  3762. }
  3763. switch(data->set.ftp_filemethod) {
  3764. case FTPFILE_NOCWD: /* fastest, but less standard-compliant */
  3765. if((pathLen > 0) && (rawPath[pathLen - 1] != '/'))
  3766. fileName = rawPath; /* this is a full file path */
  3767. /*
  3768. else: ftpc->file is not used anywhere other than for operations on
  3769. a file. In other words, never for directory operations.
  3770. So we can safely leave filename as NULL here and use it as a
  3771. argument in dir/file decisions.
  3772. */
  3773. break;
  3774. case FTPFILE_SINGLECWD:
  3775. slashPos = strrchr(rawPath, '/');
  3776. if(slashPos) {
  3777. /* get path before last slash, except for / */
  3778. size_t dirlen = slashPos - rawPath;
  3779. if(dirlen == 0)
  3780. dirlen = 1;
  3781. ftpc->dirs = calloc(1, sizeof(ftpc->dirs[0]));
  3782. if(!ftpc->dirs) {
  3783. free(rawPath);
  3784. return CURLE_OUT_OF_MEMORY;
  3785. }
  3786. ftpc->dirs[0] = Curl_memdup0(rawPath, dirlen);
  3787. if(!ftpc->dirs[0]) {
  3788. free(rawPath);
  3789. return CURLE_OUT_OF_MEMORY;
  3790. }
  3791. ftpc->dirdepth = 1; /* we consider it to be a single dir */
  3792. fileName = slashPos + 1; /* rest is filename */
  3793. }
  3794. else
  3795. fileName = rawPath; /* filename only (or empty) */
  3796. break;
  3797. default: /* allow pretty much anything */
  3798. case FTPFILE_MULTICWD: {
  3799. /* current position: begin of next path component */
  3800. const char *curPos = rawPath;
  3801. /* number of entries allocated for the 'dirs' array */
  3802. size_t dirAlloc = 0;
  3803. const char *str = rawPath;
  3804. for(; *str != 0; ++str)
  3805. if(*str == '/')
  3806. ++dirAlloc;
  3807. if(dirAlloc) {
  3808. ftpc->dirs = calloc(dirAlloc, sizeof(ftpc->dirs[0]));
  3809. if(!ftpc->dirs) {
  3810. free(rawPath);
  3811. return CURLE_OUT_OF_MEMORY;
  3812. }
  3813. /* parse the URL path into separate path components */
  3814. while((slashPos = strchr(curPos, '/'))) {
  3815. size_t compLen = slashPos - curPos;
  3816. /* path starts with a slash: add that as a directory */
  3817. if((compLen == 0) && (ftpc->dirdepth == 0))
  3818. ++compLen;
  3819. /* we skip empty path components, like "x//y" since the FTP command
  3820. CWD requires a parameter and a non-existent parameter a) does not
  3821. work on many servers and b) has no effect on the others. */
  3822. if(compLen > 0) {
  3823. char *comp = Curl_memdup0(curPos, compLen);
  3824. if(!comp) {
  3825. free(rawPath);
  3826. return CURLE_OUT_OF_MEMORY;
  3827. }
  3828. ftpc->dirs[ftpc->dirdepth++] = comp;
  3829. }
  3830. curPos = slashPos + 1;
  3831. }
  3832. }
  3833. DEBUGASSERT((size_t)ftpc->dirdepth <= dirAlloc);
  3834. fileName = curPos; /* the rest is the filename (or empty) */
  3835. }
  3836. break;
  3837. } /* switch */
  3838. if(fileName && *fileName)
  3839. ftpc->file = strdup(fileName);
  3840. else
  3841. ftpc->file = NULL; /* instead of point to a zero byte,
  3842. we make it a NULL pointer */
  3843. if(data->state.upload && !ftpc->file && (ftp->transfer == PPTRANSFER_BODY)) {
  3844. /* We need a filename when uploading. Return error! */
  3845. failf(data, "Uploading to a URL without a filename");
  3846. free(rawPath);
  3847. return CURLE_URL_MALFORMAT;
  3848. }
  3849. ftpc->cwddone = FALSE; /* default to not done */
  3850. if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
  3851. ftpc->cwddone = TRUE; /* skip CWD for absolute paths */
  3852. else { /* newly created FTP connections are already in entry path */
  3853. const char *oldPath = conn->bits.reuse ? ftpc->prevpath : "";
  3854. if(oldPath) {
  3855. size_t n = pathLen;
  3856. if(data->set.ftp_filemethod == FTPFILE_NOCWD)
  3857. n = 0; /* CWD to entry for relative paths */
  3858. else
  3859. n -= ftpc->file?strlen(ftpc->file):0;
  3860. if((strlen(oldPath) == n) && !strncmp(rawPath, oldPath, n)) {
  3861. infof(data, "Request has same path as previous transfer");
  3862. ftpc->cwddone = TRUE;
  3863. }
  3864. }
  3865. }
  3866. free(rawPath);
  3867. return CURLE_OK;
  3868. }
  3869. /* call this when the DO phase has completed */
  3870. static CURLcode ftp_dophase_done(struct Curl_easy *data, bool connected)
  3871. {
  3872. struct connectdata *conn = data->conn;
  3873. struct FTP *ftp = data->req.p.ftp;
  3874. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3875. if(connected) {
  3876. int completed;
  3877. CURLcode result = ftp_do_more(data, &completed);
  3878. if(result) {
  3879. close_secondarysocket(data);
  3880. return result;
  3881. }
  3882. }
  3883. if(ftp->transfer != PPTRANSFER_BODY)
  3884. /* no data to transfer */
  3885. Curl_xfer_setup_nop(data);
  3886. else if(!connected)
  3887. /* since we did not connect now, we want do_more to get called */
  3888. conn->bits.do_more = TRUE;
  3889. ftpc->ctl_valid = TRUE; /* seems good */
  3890. return CURLE_OK;
  3891. }
  3892. /* called from multi.c while DOing */
  3893. static CURLcode ftp_doing(struct Curl_easy *data,
  3894. bool *dophase_done)
  3895. {
  3896. CURLcode result = ftp_multi_statemach(data, dophase_done);
  3897. if(result)
  3898. CURL_TRC_FTP(data, "[%s] DO phase failed", FTP_DSTATE(data));
  3899. else if(*dophase_done) {
  3900. result = ftp_dophase_done(data, FALSE /* not connected */);
  3901. CURL_TRC_FTP(data, "[%s] DO phase is complete2", FTP_DSTATE(data));
  3902. }
  3903. return result;
  3904. }
  3905. /***********************************************************************
  3906. *
  3907. * ftp_regular_transfer()
  3908. *
  3909. * The input argument is already checked for validity.
  3910. *
  3911. * Performs all commands done before a regular transfer between a local and a
  3912. * remote host.
  3913. *
  3914. * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the
  3915. * ftp_done() function without finding any major problem.
  3916. */
  3917. static
  3918. CURLcode ftp_regular_transfer(struct Curl_easy *data,
  3919. bool *dophase_done)
  3920. {
  3921. CURLcode result = CURLE_OK;
  3922. bool connected = FALSE;
  3923. struct connectdata *conn = data->conn;
  3924. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3925. data->req.size = -1; /* make sure this is unknown at this point */
  3926. Curl_pgrsSetUploadCounter(data, 0);
  3927. Curl_pgrsSetDownloadCounter(data, 0);
  3928. Curl_pgrsSetUploadSize(data, -1);
  3929. Curl_pgrsSetDownloadSize(data, -1);
  3930. ftpc->ctl_valid = TRUE; /* starts good */
  3931. result = ftp_perform(data,
  3932. &connected, /* have we connected after PASV/PORT */
  3933. dophase_done); /* all commands in the DO-phase done? */
  3934. if(!result) {
  3935. if(!*dophase_done)
  3936. /* the DO phase has not completed yet */
  3937. return CURLE_OK;
  3938. result = ftp_dophase_done(data, connected);
  3939. if(result)
  3940. return result;
  3941. }
  3942. else
  3943. freedirs(ftpc);
  3944. return result;
  3945. }
  3946. static CURLcode ftp_setup_connection(struct Curl_easy *data,
  3947. struct connectdata *conn)
  3948. {
  3949. char *type;
  3950. struct FTP *ftp;
  3951. CURLcode result = CURLE_OK;
  3952. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3953. ftp = calloc(1, sizeof(struct FTP));
  3954. if(!ftp)
  3955. return CURLE_OUT_OF_MEMORY;
  3956. /* clone connection related data that is FTP specific */
  3957. if(data->set.str[STRING_FTP_ACCOUNT]) {
  3958. ftpc->account = strdup(data->set.str[STRING_FTP_ACCOUNT]);
  3959. if(!ftpc->account) {
  3960. free(ftp);
  3961. return CURLE_OUT_OF_MEMORY;
  3962. }
  3963. }
  3964. if(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]) {
  3965. ftpc->alternative_to_user =
  3966. strdup(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]);
  3967. if(!ftpc->alternative_to_user) {
  3968. Curl_safefree(ftpc->account);
  3969. free(ftp);
  3970. return CURLE_OUT_OF_MEMORY;
  3971. }
  3972. }
  3973. data->req.p.ftp = ftp;
  3974. ftp->path = &data->state.up.path[1]; /* do not include the initial slash */
  3975. /* FTP URLs support an extension like ";type=<typecode>" that
  3976. * we will try to get now! */
  3977. type = strstr(ftp->path, ";type=");
  3978. if(!type)
  3979. type = strstr(conn->host.rawalloc, ";type=");
  3980. if(type) {
  3981. char command;
  3982. *type = 0; /* it was in the middle of the hostname */
  3983. command = Curl_raw_toupper(type[6]);
  3984. switch(command) {
  3985. case 'A': /* ASCII mode */
  3986. data->state.prefer_ascii = TRUE;
  3987. break;
  3988. case 'D': /* directory mode */
  3989. data->state.list_only = TRUE;
  3990. break;
  3991. case 'I': /* binary mode */
  3992. default:
  3993. /* switch off ASCII */
  3994. data->state.prefer_ascii = FALSE;
  3995. break;
  3996. }
  3997. }
  3998. /* get some initial data into the ftp struct */
  3999. ftp->transfer = PPTRANSFER_BODY;
  4000. ftp->downloadsize = 0;
  4001. ftpc->known_filesize = -1; /* unknown size for now */
  4002. ftpc->use_ssl = data->set.use_ssl;
  4003. ftpc->ccc = data->set.ftp_ccc;
  4004. CURL_TRC_FTP(data, "[%s] setup connection -> %d", FTP_CSTATE(conn), result);
  4005. return result;
  4006. }
  4007. #endif /* CURL_DISABLE_FTP */