ftp.c 133 KB

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