2
0

ftp.c 132 KB

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