ftp.c 132 KB

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