2
0

ftp.c 138 KB

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