2
0

ftp.c 134 KB

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