ftp.c 135 KB

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