ftp.c 137 KB

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