ftp.c 138 KB

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