ftp.c 126 KB

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