2
0

ftp.c 134 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifndef CURL_DISABLE_FTP
  26. #ifdef HAVE_NETINET_IN_H
  27. #include <netinet/in.h>
  28. #endif
  29. #ifdef HAVE_ARPA_INET_H
  30. #include <arpa/inet.h>
  31. #endif
  32. #ifdef HAVE_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(data->req.no_body &&
  1838. ftpc->file &&
  1839. data->set.get_filetime &&
  1840. (data->info.filetime >= 0) ) {
  1841. char headerbuf[128];
  1842. int headerbuflen;
  1843. time_t filetime = data->info.filetime;
  1844. struct tm buffer;
  1845. const struct tm *tm = &buffer;
  1846. result = Curl_gmtime(filetime, &buffer);
  1847. if(result)
  1848. return result;
  1849. /* format: "Tue, 15 Nov 1994 12:45:26" */
  1850. headerbuflen =
  1851. msnprintf(headerbuf, sizeof(headerbuf),
  1852. "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
  1853. Curl_wkday[tm->tm_wday ? tm->tm_wday-1 : 6],
  1854. tm->tm_mday,
  1855. Curl_month[tm->tm_mon],
  1856. tm->tm_year + 1900,
  1857. tm->tm_hour,
  1858. tm->tm_min,
  1859. tm->tm_sec);
  1860. result = client_write_header(data, headerbuf, headerbuflen);
  1861. if(result)
  1862. return result;
  1863. } /* end of a ridiculous amount of conditionals */
  1864. #endif
  1865. }
  1866. break;
  1867. default:
  1868. infof(data, "unsupported MDTM reply format");
  1869. break;
  1870. case 550: /* 550 is used for several different problems, e.g.
  1871. "No such file or directory" or "Permission denied".
  1872. It does not mean that the file does not exist at all. */
  1873. infof(data, "MDTM failed: file does not exist or permission problem,"
  1874. " continuing");
  1875. break;
  1876. }
  1877. if(data->set.timecondition) {
  1878. if((data->info.filetime > 0) && (data->set.timevalue > 0)) {
  1879. switch(data->set.timecondition) {
  1880. case CURL_TIMECOND_IFMODSINCE:
  1881. default:
  1882. if(data->info.filetime <= data->set.timevalue) {
  1883. infof(data, "The requested document is not new enough");
  1884. ftp->transfer = PPTRANSFER_NONE; /* mark to not transfer data */
  1885. data->info.timecond = TRUE;
  1886. ftp_state(data, FTP_STOP);
  1887. return CURLE_OK;
  1888. }
  1889. break;
  1890. case CURL_TIMECOND_IFUNMODSINCE:
  1891. if(data->info.filetime > data->set.timevalue) {
  1892. infof(data, "The requested document is not old 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. } /* switch */
  1900. }
  1901. else {
  1902. infof(data, "Skipping time comparison");
  1903. }
  1904. }
  1905. if(!result)
  1906. result = ftp_state_type(data);
  1907. return result;
  1908. }
  1909. static CURLcode ftp_state_type_resp(struct Curl_easy *data,
  1910. int ftpcode,
  1911. ftpstate instate)
  1912. {
  1913. CURLcode result = CURLE_OK;
  1914. struct connectdata *conn = data->conn;
  1915. if(ftpcode/100 != 2) {
  1916. /* "sasserftpd" and "(u)r(x)bot ftpd" both responds with 226 after a
  1917. successful 'TYPE I'. While that is not as RFC959 says, it is still a
  1918. positive response code and we allow that. */
  1919. failf(data, "Couldn't set desired mode");
  1920. return CURLE_FTP_COULDNT_SET_TYPE;
  1921. }
  1922. if(ftpcode != 200)
  1923. infof(data, "Got a %03d response code instead of the assumed 200",
  1924. ftpcode);
  1925. if(instate == FTP_TYPE)
  1926. result = ftp_state_size(data, conn);
  1927. else if(instate == FTP_LIST_TYPE)
  1928. result = ftp_state_list(data);
  1929. else if(instate == FTP_RETR_TYPE)
  1930. result = ftp_state_retr_prequote(data);
  1931. else if(instate == FTP_STOR_TYPE)
  1932. result = ftp_state_stor_prequote(data);
  1933. return result;
  1934. }
  1935. static CURLcode ftp_state_retr(struct Curl_easy *data,
  1936. curl_off_t filesize)
  1937. {
  1938. CURLcode result = CURLE_OK;
  1939. struct FTP *ftp = data->req.p.ftp;
  1940. struct connectdata *conn = data->conn;
  1941. struct ftp_conn *ftpc = &conn->proto.ftpc;
  1942. CURL_TRC_FTP(data, "[%s] ftp_state_retr()", FTP_DSTATE(data));
  1943. if(data->set.max_filesize && (filesize > data->set.max_filesize)) {
  1944. failf(data, "Maximum file size exceeded");
  1945. return CURLE_FILESIZE_EXCEEDED;
  1946. }
  1947. ftp->downloadsize = filesize;
  1948. if(data->state.resume_from) {
  1949. /* We always (attempt to) get the size of downloads, so it is done before
  1950. this even when not doing resumes. */
  1951. if(filesize == -1) {
  1952. infof(data, "ftp server does not support SIZE");
  1953. /* We could not get the size and therefore we cannot know if there really
  1954. is a part of the file left to get, although the server will just
  1955. close the connection when we start the connection so it will not cause
  1956. us any harm, just not make us exit as nicely. */
  1957. }
  1958. else {
  1959. /* We got a file size report, so we check that there actually is a
  1960. part of the file left to get, or else we go home. */
  1961. if(data->state.resume_from < 0) {
  1962. /* We are supposed to download the last abs(from) bytes */
  1963. if(filesize < -data->state.resume_from) {
  1964. failf(data, "Offset (%" FMT_OFF_T
  1965. ") was beyond file size (%" FMT_OFF_T ")",
  1966. data->state.resume_from, filesize);
  1967. return CURLE_BAD_DOWNLOAD_RESUME;
  1968. }
  1969. /* convert to size to download */
  1970. ftp->downloadsize = -data->state.resume_from;
  1971. /* download from where? */
  1972. data->state.resume_from = filesize - ftp->downloadsize;
  1973. }
  1974. else {
  1975. if(filesize < data->state.resume_from) {
  1976. failf(data, "Offset (%" FMT_OFF_T
  1977. ") was beyond file size (%" FMT_OFF_T ")",
  1978. data->state.resume_from, filesize);
  1979. return CURLE_BAD_DOWNLOAD_RESUME;
  1980. }
  1981. /* Now store the number of bytes we are expected to download */
  1982. ftp->downloadsize = filesize-data->state.resume_from;
  1983. }
  1984. }
  1985. if(ftp->downloadsize == 0) {
  1986. /* no data to transfer */
  1987. Curl_xfer_setup_nop(data);
  1988. infof(data, "File already completely downloaded");
  1989. /* Set ->transfer so that we will not get any error in ftp_done()
  1990. * because we did not transfer the any file */
  1991. ftp->transfer = PPTRANSFER_NONE;
  1992. ftp_state(data, FTP_STOP);
  1993. return CURLE_OK;
  1994. }
  1995. /* Set resume file transfer offset */
  1996. infof(data, "Instructs server to resume from offset %" FMT_OFF_T,
  1997. data->state.resume_from);
  1998. result = Curl_pp_sendf(data, &ftpc->pp, "REST %" FMT_OFF_T,
  1999. data->state.resume_from);
  2000. if(!result)
  2001. ftp_state(data, FTP_RETR_REST);
  2002. }
  2003. else {
  2004. /* no resume */
  2005. result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
  2006. if(!result)
  2007. ftp_state(data, FTP_RETR);
  2008. }
  2009. return result;
  2010. }
  2011. static CURLcode ftp_state_size_resp(struct Curl_easy *data,
  2012. int ftpcode,
  2013. ftpstate instate)
  2014. {
  2015. CURLcode result = CURLE_OK;
  2016. curl_off_t filesize = -1;
  2017. char *buf = Curl_dyn_ptr(&data->conn->proto.ftpc.pp.recvbuf);
  2018. size_t len = data->conn->proto.ftpc.pp.nfinal;
  2019. /* get the size from the ascii string: */
  2020. if(ftpcode == 213) {
  2021. /* To allow servers to prepend "rubbish" in the response string, we scan
  2022. for all the digits at the end of the response and parse only those as a
  2023. number. */
  2024. char *start = &buf[4];
  2025. char *fdigit = memchr(start, '\r', len);
  2026. if(fdigit) {
  2027. fdigit--;
  2028. if(*fdigit == '\n')
  2029. fdigit--;
  2030. while(ISDIGIT(fdigit[-1]) && (fdigit > start))
  2031. fdigit--;
  2032. }
  2033. else
  2034. fdigit = start;
  2035. /* ignores parsing errors, which will make the size remain unknown */
  2036. (void)curlx_strtoofft(fdigit, NULL, 10, &filesize);
  2037. }
  2038. else if(ftpcode == 550) { /* "No such file or directory" */
  2039. /* allow a SIZE failure for (resumed) uploads, when probing what command
  2040. to use */
  2041. if(instate != FTP_STOR_SIZE) {
  2042. failf(data, "The file does not exist");
  2043. return CURLE_REMOTE_FILE_NOT_FOUND;
  2044. }
  2045. }
  2046. if(instate == FTP_SIZE) {
  2047. #ifdef CURL_FTP_HTTPSTYLE_HEAD
  2048. if(-1 != filesize) {
  2049. char clbuf[128];
  2050. int clbuflen = msnprintf(clbuf, sizeof(clbuf),
  2051. "Content-Length: %" FMT_OFF_T "\r\n", filesize);
  2052. result = client_write_header(data, clbuf, clbuflen);
  2053. if(result)
  2054. return result;
  2055. }
  2056. #endif
  2057. Curl_pgrsSetDownloadSize(data, filesize);
  2058. result = ftp_state_rest(data, data->conn);
  2059. }
  2060. else if(instate == FTP_RETR_SIZE) {
  2061. Curl_pgrsSetDownloadSize(data, filesize);
  2062. result = ftp_state_retr(data, filesize);
  2063. }
  2064. else if(instate == FTP_STOR_SIZE) {
  2065. data->state.resume_from = filesize;
  2066. result = ftp_state_ul_setup(data, TRUE);
  2067. }
  2068. return result;
  2069. }
  2070. static CURLcode ftp_state_rest_resp(struct Curl_easy *data,
  2071. struct connectdata *conn,
  2072. int ftpcode,
  2073. ftpstate instate)
  2074. {
  2075. CURLcode result = CURLE_OK;
  2076. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2077. switch(instate) {
  2078. case FTP_REST:
  2079. default:
  2080. #ifdef CURL_FTP_HTTPSTYLE_HEAD
  2081. if(ftpcode == 350) {
  2082. char buffer[24]= { "Accept-ranges: bytes\r\n" };
  2083. result = client_write_header(data, buffer, strlen(buffer));
  2084. if(result)
  2085. return result;
  2086. }
  2087. #endif
  2088. result = ftp_state_prepare_transfer(data);
  2089. break;
  2090. case FTP_RETR_REST:
  2091. if(ftpcode != 350) {
  2092. failf(data, "Couldn't use REST");
  2093. result = CURLE_FTP_COULDNT_USE_REST;
  2094. }
  2095. else {
  2096. result = Curl_pp_sendf(data, &ftpc->pp, "RETR %s", ftpc->file);
  2097. if(!result)
  2098. ftp_state(data, FTP_RETR);
  2099. }
  2100. break;
  2101. }
  2102. return result;
  2103. }
  2104. static CURLcode ftp_state_stor_resp(struct Curl_easy *data,
  2105. int ftpcode, ftpstate instate)
  2106. {
  2107. CURLcode result = CURLE_OK;
  2108. struct connectdata *conn = data->conn;
  2109. if(ftpcode >= 400) {
  2110. failf(data, "Failed FTP upload: %0d", ftpcode);
  2111. ftp_state(data, FTP_STOP);
  2112. /* oops, we never close the sockets! */
  2113. return CURLE_UPLOAD_FAILED;
  2114. }
  2115. conn->proto.ftpc.state_saved = instate;
  2116. /* PORT means we are now awaiting the server to connect to us. */
  2117. if(data->set.ftp_use_port) {
  2118. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2119. bool connected;
  2120. ftp_state(data, FTP_STOP); /* no longer in STOR state */
  2121. result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected);
  2122. if(result)
  2123. return result;
  2124. if(!connected) {
  2125. infof(data, "Data conn was not available immediately");
  2126. ftpc->wait_data_conn = TRUE;
  2127. return ftp_check_ctrl_on_data_wait(data);
  2128. }
  2129. ftpc->wait_data_conn = FALSE;
  2130. }
  2131. return InitiateTransfer(data);
  2132. }
  2133. /* for LIST and RETR responses */
  2134. static CURLcode ftp_state_get_resp(struct Curl_easy *data,
  2135. int ftpcode,
  2136. ftpstate instate)
  2137. {
  2138. CURLcode result = CURLE_OK;
  2139. struct FTP *ftp = data->req.p.ftp;
  2140. struct connectdata *conn = data->conn;
  2141. if((ftpcode == 150) || (ftpcode == 125)) {
  2142. /*
  2143. A;
  2144. 150 Opening BINARY mode data connection for /etc/passwd (2241
  2145. bytes). (ok, the file is being transferred)
  2146. B:
  2147. 150 Opening ASCII mode data connection for /bin/ls
  2148. C:
  2149. 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes).
  2150. D:
  2151. 150 Opening ASCII mode data connection for [file] (0.0.0.0,0) (545 bytes)
  2152. E:
  2153. 125 Data connection already open; Transfer starting. */
  2154. curl_off_t size = -1; /* default unknown size */
  2155. /*
  2156. * It appears that there are FTP-servers that return size 0 for files when
  2157. * SIZE is used on the file while being in BINARY mode. To work around
  2158. * that (stupid) behavior, we attempt to parse the RETR response even if
  2159. * the SIZE returned size zero.
  2160. *
  2161. * Debugging help from Salvatore Sorrentino on February 26, 2003.
  2162. */
  2163. if((instate != FTP_LIST) &&
  2164. !data->state.prefer_ascii &&
  2165. !data->set.ignorecl &&
  2166. (ftp->downloadsize < 1)) {
  2167. /*
  2168. * It seems directory listings either do not show the size or often uses
  2169. * size 0 anyway. ASCII transfers may cause that the transferred amount
  2170. * of data is not the same as this line tells, why using this number in
  2171. * those cases only confuses us.
  2172. *
  2173. * Example D above makes this parsing a little tricky */
  2174. char *bytes;
  2175. char *buf = Curl_dyn_ptr(&conn->proto.ftpc.pp.recvbuf);
  2176. bytes = strstr(buf, " bytes");
  2177. if(bytes) {
  2178. long in = (long)(--bytes-buf);
  2179. /* this is a hint there is size information in there! ;-) */
  2180. while(--in) {
  2181. /* scan for the left parenthesis and break there */
  2182. if('(' == *bytes)
  2183. break;
  2184. /* skip only digits */
  2185. if(!ISDIGIT(*bytes)) {
  2186. bytes = NULL;
  2187. break;
  2188. }
  2189. /* one more estep backwards */
  2190. bytes--;
  2191. }
  2192. /* if we have nothing but digits: */
  2193. if(bytes) {
  2194. ++bytes;
  2195. /* get the number! */
  2196. (void)curlx_strtoofft(bytes, NULL, 10, &size);
  2197. }
  2198. }
  2199. }
  2200. else if(ftp->downloadsize > -1)
  2201. size = ftp->downloadsize;
  2202. if(size > data->req.maxdownload && data->req.maxdownload > 0)
  2203. size = data->req.size = data->req.maxdownload;
  2204. else if((instate != FTP_LIST) && (data->state.prefer_ascii))
  2205. size = -1; /* kludge for servers that understate ASCII mode file size */
  2206. infof(data, "Maxdownload = %" FMT_OFF_T, data->req.maxdownload);
  2207. if(instate != FTP_LIST)
  2208. infof(data, "Getting file with size: %" FMT_OFF_T, size);
  2209. /* FTP download: */
  2210. conn->proto.ftpc.state_saved = instate;
  2211. conn->proto.ftpc.retr_size_saved = size;
  2212. if(data->set.ftp_use_port) {
  2213. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2214. bool connected;
  2215. result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected);
  2216. if(result)
  2217. return result;
  2218. if(!connected) {
  2219. infof(data, "Data conn was not available immediately");
  2220. ftp_state(data, FTP_STOP);
  2221. ftpc->wait_data_conn = TRUE;
  2222. return ftp_check_ctrl_on_data_wait(data);
  2223. }
  2224. ftpc->wait_data_conn = FALSE;
  2225. }
  2226. return InitiateTransfer(data);
  2227. }
  2228. else {
  2229. if((instate == FTP_LIST) && (ftpcode == 450)) {
  2230. /* simply no matching files in the dir listing */
  2231. ftp->transfer = PPTRANSFER_NONE; /* do not download anything */
  2232. ftp_state(data, FTP_STOP); /* this phase is over */
  2233. }
  2234. else {
  2235. failf(data, "RETR response: %03d", ftpcode);
  2236. return instate == FTP_RETR && ftpcode == 550 ?
  2237. CURLE_REMOTE_FILE_NOT_FOUND :
  2238. CURLE_FTP_COULDNT_RETR_FILE;
  2239. }
  2240. }
  2241. return result;
  2242. }
  2243. /* after USER, PASS and ACCT */
  2244. static CURLcode ftp_state_loggedin(struct Curl_easy *data)
  2245. {
  2246. CURLcode result = CURLE_OK;
  2247. struct connectdata *conn = data->conn;
  2248. if(conn->bits.ftp_use_control_ssl) {
  2249. /* PBSZ = PROTECTION BUFFER SIZE.
  2250. The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says:
  2251. Specifically, the PROT command MUST be preceded by a PBSZ
  2252. command and a PBSZ command MUST be preceded by a successful
  2253. security data exchange (the TLS negotiation in this case)
  2254. ... (and on page 8):
  2255. Thus the PBSZ command must still be issued, but must have a
  2256. parameter of '0' to indicate that no buffering is taking place
  2257. and the data connection should not be encapsulated.
  2258. */
  2259. result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "PBSZ %d", 0);
  2260. if(!result)
  2261. ftp_state(data, FTP_PBSZ);
  2262. }
  2263. else {
  2264. result = ftp_state_pwd(data, conn);
  2265. }
  2266. return result;
  2267. }
  2268. /* for USER and PASS responses */
  2269. static CURLcode ftp_state_user_resp(struct Curl_easy *data,
  2270. int ftpcode)
  2271. {
  2272. CURLcode result = CURLE_OK;
  2273. struct connectdata *conn = data->conn;
  2274. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2275. /* some need password anyway, and others just return 2xx ignored */
  2276. if((ftpcode == 331) && (ftpc->state == FTP_USER)) {
  2277. /* 331 Password required for ...
  2278. (the server requires to send the user's password too) */
  2279. result = Curl_pp_sendf(data, &ftpc->pp, "PASS %s",
  2280. conn->passwd ? conn->passwd : "");
  2281. if(!result)
  2282. ftp_state(data, FTP_PASS);
  2283. }
  2284. else if(ftpcode/100 == 2) {
  2285. /* 230 User ... logged in.
  2286. (the user logged in with or without password) */
  2287. result = ftp_state_loggedin(data);
  2288. }
  2289. else if(ftpcode == 332) {
  2290. if(data->set.str[STRING_FTP_ACCOUNT]) {
  2291. result = Curl_pp_sendf(data, &ftpc->pp, "ACCT %s",
  2292. data->set.str[STRING_FTP_ACCOUNT]);
  2293. if(!result)
  2294. ftp_state(data, FTP_ACCT);
  2295. }
  2296. else {
  2297. failf(data, "ACCT requested but none available");
  2298. result = CURLE_LOGIN_DENIED;
  2299. }
  2300. }
  2301. else {
  2302. /* All other response codes, like:
  2303. 530 User ... access denied
  2304. (the server denies to log the specified user) */
  2305. if(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER] &&
  2306. !ftpc->ftp_trying_alternative) {
  2307. /* Ok, USER failed. Let's try the supplied command. */
  2308. result =
  2309. Curl_pp_sendf(data, &ftpc->pp, "%s",
  2310. data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]);
  2311. if(!result) {
  2312. ftpc->ftp_trying_alternative = TRUE;
  2313. ftp_state(data, FTP_USER);
  2314. }
  2315. }
  2316. else {
  2317. failf(data, "Access denied: %03d", ftpcode);
  2318. result = CURLE_LOGIN_DENIED;
  2319. }
  2320. }
  2321. return result;
  2322. }
  2323. /* for ACCT response */
  2324. static CURLcode ftp_state_acct_resp(struct Curl_easy *data,
  2325. int ftpcode)
  2326. {
  2327. CURLcode result = CURLE_OK;
  2328. if(ftpcode != 230) {
  2329. failf(data, "ACCT rejected by server: %03d", ftpcode);
  2330. result = CURLE_FTP_WEIRD_PASS_REPLY; /* FIX */
  2331. }
  2332. else
  2333. result = ftp_state_loggedin(data);
  2334. return result;
  2335. }
  2336. static CURLcode ftp_statemachine(struct Curl_easy *data,
  2337. struct connectdata *conn)
  2338. {
  2339. CURLcode result;
  2340. int ftpcode;
  2341. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2342. struct pingpong *pp = &ftpc->pp;
  2343. static const char * const ftpauth[] = { "SSL", "TLS" };
  2344. size_t nread = 0;
  2345. if(pp->sendleft)
  2346. return Curl_pp_flushsend(data, pp);
  2347. result = ftp_readresp(data, FIRSTSOCKET, pp, &ftpcode, &nread);
  2348. if(result)
  2349. return result;
  2350. if(ftpcode) {
  2351. /* we have now received a full FTP server response */
  2352. switch(ftpc->state) {
  2353. case FTP_WAIT220:
  2354. if(ftpcode == 230) {
  2355. /* 230 User logged in - already! Take as 220 if TLS required. */
  2356. if(data->set.use_ssl <= CURLUSESSL_TRY ||
  2357. conn->bits.ftp_use_control_ssl)
  2358. return ftp_state_user_resp(data, ftpcode);
  2359. }
  2360. else if(ftpcode != 220) {
  2361. failf(data, "Got a %03d ftp-server response when 220 was expected",
  2362. ftpcode);
  2363. return CURLE_WEIRD_SERVER_REPLY;
  2364. }
  2365. /* We have received a 220 response fine, now we proceed. */
  2366. #ifdef HAVE_GSSAPI
  2367. if(data->set.krb) {
  2368. /* If not anonymous login, try a secure login. Note that this
  2369. procedure is still BLOCKING. */
  2370. Curl_sec_request_prot(conn, "private");
  2371. /* We set private first as default, in case the line below fails to
  2372. set a valid level */
  2373. Curl_sec_request_prot(conn, data->set.str[STRING_KRB_LEVEL]);
  2374. if(Curl_sec_login(data, conn)) {
  2375. failf(data, "secure login failed");
  2376. return CURLE_WEIRD_SERVER_REPLY;
  2377. }
  2378. infof(data, "Authentication successful");
  2379. }
  2380. #endif
  2381. if(data->set.use_ssl && !conn->bits.ftp_use_control_ssl) {
  2382. /* We do not have a SSL/TLS control connection yet, but FTPS is
  2383. requested. Try a FTPS connection now */
  2384. ftpc->count3 = 0;
  2385. switch(data->set.ftpsslauth) {
  2386. case CURLFTPAUTH_DEFAULT:
  2387. case CURLFTPAUTH_SSL:
  2388. ftpc->count2 = 1; /* add one to get next */
  2389. ftpc->count1 = 0;
  2390. break;
  2391. case CURLFTPAUTH_TLS:
  2392. ftpc->count2 = -1; /* subtract one to get next */
  2393. ftpc->count1 = 1;
  2394. break;
  2395. default:
  2396. failf(data, "unsupported parameter to CURLOPT_FTPSSLAUTH: %d",
  2397. (int)data->set.ftpsslauth);
  2398. return CURLE_UNKNOWN_OPTION; /* we do not know what to do */
  2399. }
  2400. result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s",
  2401. ftpauth[ftpc->count1]);
  2402. if(!result)
  2403. ftp_state(data, FTP_AUTH);
  2404. }
  2405. else
  2406. result = ftp_state_user(data, conn);
  2407. break;
  2408. case FTP_AUTH:
  2409. /* we have gotten the response to a previous AUTH command */
  2410. if(pp->overflow)
  2411. return CURLE_WEIRD_SERVER_REPLY; /* Forbid pipelining in response. */
  2412. /* RFC2228 (page 5) says:
  2413. *
  2414. * If the server is willing to accept the named security mechanism,
  2415. * and does not require any security data, it must respond with
  2416. * reply code 234/334.
  2417. */
  2418. if((ftpcode == 234) || (ftpcode == 334)) {
  2419. /* this was BLOCKING, keep it so for now */
  2420. bool done;
  2421. if(!Curl_conn_is_ssl(conn, FIRSTSOCKET)) {
  2422. result = Curl_ssl_cfilter_add(data, conn, FIRSTSOCKET);
  2423. if(result) {
  2424. /* we failed and bail out */
  2425. return CURLE_USE_SSL_FAILED;
  2426. }
  2427. }
  2428. result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, &done);
  2429. if(!result) {
  2430. conn->bits.ftp_use_data_ssl = FALSE; /* clear-text data */
  2431. conn->bits.ftp_use_control_ssl = TRUE; /* SSL on control */
  2432. result = ftp_state_user(data, conn);
  2433. }
  2434. }
  2435. else if(ftpc->count3 < 1) {
  2436. ftpc->count3++;
  2437. ftpc->count1 += ftpc->count2; /* get next attempt */
  2438. result = Curl_pp_sendf(data, &ftpc->pp, "AUTH %s",
  2439. ftpauth[ftpc->count1]);
  2440. /* remain in this same state */
  2441. }
  2442. else {
  2443. if(data->set.use_ssl > CURLUSESSL_TRY)
  2444. /* we failed and CURLUSESSL_CONTROL or CURLUSESSL_ALL is set */
  2445. result = CURLE_USE_SSL_FAILED;
  2446. else
  2447. /* ignore the failure and continue */
  2448. result = ftp_state_user(data, conn);
  2449. }
  2450. break;
  2451. case FTP_USER:
  2452. case FTP_PASS:
  2453. result = ftp_state_user_resp(data, ftpcode);
  2454. break;
  2455. case FTP_ACCT:
  2456. result = ftp_state_acct_resp(data, ftpcode);
  2457. break;
  2458. case FTP_PBSZ:
  2459. result =
  2460. Curl_pp_sendf(data, &ftpc->pp, "PROT %c",
  2461. data->set.use_ssl == CURLUSESSL_CONTROL ? 'C' : 'P');
  2462. if(!result)
  2463. ftp_state(data, FTP_PROT);
  2464. break;
  2465. case FTP_PROT:
  2466. if(ftpcode/100 == 2)
  2467. /* We have enabled SSL for the data connection! */
  2468. conn->bits.ftp_use_data_ssl =
  2469. (data->set.use_ssl != CURLUSESSL_CONTROL);
  2470. /* FTP servers typically responds with 500 if they decide to reject
  2471. our 'P' request */
  2472. else if(data->set.use_ssl > CURLUSESSL_CONTROL)
  2473. /* we failed and bails out */
  2474. return CURLE_USE_SSL_FAILED;
  2475. if(data->set.ftp_ccc) {
  2476. /* CCC - Clear Command Channel
  2477. */
  2478. result = Curl_pp_sendf(data, &ftpc->pp, "%s", "CCC");
  2479. if(!result)
  2480. ftp_state(data, FTP_CCC);
  2481. }
  2482. else
  2483. result = ftp_state_pwd(data, conn);
  2484. break;
  2485. case FTP_CCC:
  2486. if(ftpcode < 500) {
  2487. /* First shut down the SSL layer (note: this call will block) */
  2488. /* This has only been tested on the proftpd server, and the mod_tls
  2489. * code sends a close notify alert without waiting for a close notify
  2490. * alert in response. Thus we wait for a close notify alert from the
  2491. * server, but we do not send one. Let's hope other servers do
  2492. * the same... */
  2493. result = Curl_ssl_cfilter_remove(data, FIRSTSOCKET,
  2494. (data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE));
  2495. if(result)
  2496. failf(data, "Failed to clear the command channel (CCC)");
  2497. }
  2498. if(!result)
  2499. /* Then continue as normal */
  2500. result = ftp_state_pwd(data, conn);
  2501. break;
  2502. case FTP_PWD:
  2503. if(ftpcode == 257) {
  2504. char *ptr = Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first
  2505. letter */
  2506. bool entry_extracted = FALSE;
  2507. struct dynbuf out;
  2508. Curl_dyn_init(&out, 1000);
  2509. /* Reply format is like
  2510. 257<space>[rubbish]"<directory-name>"<space><commentary> and the
  2511. RFC959 says
  2512. The directory name can contain any character; embedded
  2513. double-quotes should be escaped by double-quotes (the
  2514. "quote-doubling" convention).
  2515. */
  2516. /* scan for the first double-quote for non-standard responses */
  2517. while(*ptr != '\n' && *ptr != '\0' && *ptr != '"')
  2518. ptr++;
  2519. if('\"' == *ptr) {
  2520. /* it started good */
  2521. for(ptr++; *ptr; ptr++) {
  2522. if('\"' == *ptr) {
  2523. if('\"' == ptr[1]) {
  2524. /* "quote-doubling" */
  2525. result = Curl_dyn_addn(&out, &ptr[1], 1);
  2526. ptr++;
  2527. }
  2528. else {
  2529. /* end of path */
  2530. if(Curl_dyn_len(&out))
  2531. entry_extracted = TRUE;
  2532. break; /* get out of this loop */
  2533. }
  2534. }
  2535. else
  2536. result = Curl_dyn_addn(&out, ptr, 1);
  2537. if(result)
  2538. return result;
  2539. }
  2540. }
  2541. if(entry_extracted) {
  2542. /* If the path name does not look like an absolute path (i.e.: it
  2543. does not start with a '/'), we probably need some server-dependent
  2544. adjustments. For example, this is the case when connecting to
  2545. an OS400 FTP server: this server supports two name syntaxes,
  2546. the default one being incompatible with standard paths. In
  2547. addition, this server switches automatically to the regular path
  2548. syntax when one is encountered in a command: this results in
  2549. having an entrypath in the wrong syntax when later used in CWD.
  2550. The method used here is to check the server OS: we do it only
  2551. if the path name looks strange to minimize overhead on other
  2552. systems. */
  2553. char *dir = Curl_dyn_ptr(&out);
  2554. if(!ftpc->server_os && dir[0] != '/') {
  2555. result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SYST");
  2556. if(result) {
  2557. free(dir);
  2558. return result;
  2559. }
  2560. Curl_safefree(ftpc->entrypath);
  2561. ftpc->entrypath = dir; /* remember this */
  2562. infof(data, "Entry path is '%s'", ftpc->entrypath);
  2563. /* also save it where getinfo can access it: */
  2564. data->state.most_recent_ftp_entrypath = ftpc->entrypath;
  2565. ftp_state(data, FTP_SYST);
  2566. break;
  2567. }
  2568. Curl_safefree(ftpc->entrypath);
  2569. ftpc->entrypath = dir; /* remember this */
  2570. infof(data, "Entry path is '%s'", ftpc->entrypath);
  2571. /* also save it where getinfo can access it: */
  2572. data->state.most_recent_ftp_entrypath = ftpc->entrypath;
  2573. }
  2574. else {
  2575. /* could not get the path */
  2576. Curl_dyn_free(&out);
  2577. infof(data, "Failed to figure out path");
  2578. }
  2579. }
  2580. ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */
  2581. CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data));
  2582. break;
  2583. case FTP_SYST:
  2584. if(ftpcode == 215) {
  2585. char *ptr = Curl_dyn_ptr(&pp->recvbuf) + 4; /* start on the first
  2586. letter */
  2587. char *os;
  2588. char *start;
  2589. /* Reply format is like
  2590. 215<space><OS-name><space><commentary>
  2591. */
  2592. while(*ptr == ' ')
  2593. ptr++;
  2594. for(start = ptr; *ptr && *ptr != ' '; ptr++)
  2595. ;
  2596. os = Curl_memdup0(start, ptr - start);
  2597. if(!os)
  2598. return CURLE_OUT_OF_MEMORY;
  2599. /* Check for special servers here. */
  2600. if(strcasecompare(os, "OS/400")) {
  2601. /* Force OS400 name format 1. */
  2602. result = Curl_pp_sendf(data, &ftpc->pp, "%s", "SITE NAMEFMT 1");
  2603. if(result) {
  2604. free(os);
  2605. return result;
  2606. }
  2607. /* remember target server OS */
  2608. Curl_safefree(ftpc->server_os);
  2609. ftpc->server_os = os;
  2610. ftp_state(data, FTP_NAMEFMT);
  2611. break;
  2612. }
  2613. /* Nothing special for the target server. */
  2614. /* remember target server OS */
  2615. Curl_safefree(ftpc->server_os);
  2616. ftpc->server_os = os;
  2617. }
  2618. else {
  2619. /* Cannot identify server OS. Continue anyway and cross fingers. */
  2620. }
  2621. ftp_state(data, FTP_STOP); /* we are done with the CONNECT phase! */
  2622. CURL_TRC_FTP(data, "[%s] protocol connect phase DONE", FTP_DSTATE(data));
  2623. break;
  2624. case FTP_NAMEFMT:
  2625. if(ftpcode == 250) {
  2626. /* Name format change successful: reload initial path. */
  2627. ftp_state_pwd(data, conn);
  2628. break;
  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_QUOTE:
  2634. case FTP_POSTQUOTE:
  2635. case FTP_RETR_PREQUOTE:
  2636. case FTP_STOR_PREQUOTE:
  2637. if((ftpcode >= 400) && !ftpc->count2) {
  2638. /* failure response code, and not allowed to fail */
  2639. failf(data, "QUOT command failed with %03d", ftpcode);
  2640. result = CURLE_QUOTE_ERROR;
  2641. }
  2642. else
  2643. result = ftp_state_quote(data, FALSE, ftpc->state);
  2644. break;
  2645. case FTP_CWD:
  2646. if(ftpcode/100 != 2) {
  2647. /* failure to CWD there */
  2648. if(data->set.ftp_create_missing_dirs &&
  2649. ftpc->cwdcount && !ftpc->count2) {
  2650. /* try making it */
  2651. ftpc->count2++; /* counter to prevent CWD-MKD loops */
  2652. /* count3 is set to allow MKD to fail once per dir. In the case when
  2653. CWD fails and then MKD fails (due to another session raced it to
  2654. create the dir) this then allows for a second try to CWD to it. */
  2655. ftpc->count3 = (data->set.ftp_create_missing_dirs == 2) ? 1 : 0;
  2656. result = Curl_pp_sendf(data, &ftpc->pp, "MKD %s",
  2657. ftpc->dirs[ftpc->cwdcount - 1]);
  2658. if(!result)
  2659. ftp_state(data, FTP_MKD);
  2660. }
  2661. else {
  2662. /* return failure */
  2663. failf(data, "Server denied you to change to the given directory");
  2664. ftpc->cwdfail = TRUE; /* do not remember this path as we failed
  2665. to enter it */
  2666. result = CURLE_REMOTE_ACCESS_DENIED;
  2667. }
  2668. }
  2669. else {
  2670. /* success */
  2671. ftpc->count2 = 0;
  2672. if(++ftpc->cwdcount <= ftpc->dirdepth)
  2673. /* send next CWD */
  2674. result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s",
  2675. ftpc->dirs[ftpc->cwdcount - 1]);
  2676. else
  2677. result = ftp_state_mdtm(data);
  2678. }
  2679. break;
  2680. case FTP_MKD:
  2681. if((ftpcode/100 != 2) && !ftpc->count3--) {
  2682. /* failure to MKD the dir */
  2683. failf(data, "Failed to MKD dir: %03d", ftpcode);
  2684. result = CURLE_REMOTE_ACCESS_DENIED;
  2685. }
  2686. else {
  2687. ftp_state(data, FTP_CWD);
  2688. /* send CWD */
  2689. result = Curl_pp_sendf(data, &ftpc->pp, "CWD %s",
  2690. ftpc->dirs[ftpc->cwdcount - 1]);
  2691. }
  2692. break;
  2693. case FTP_MDTM:
  2694. result = ftp_state_mdtm_resp(data, ftpcode);
  2695. break;
  2696. case FTP_TYPE:
  2697. case FTP_LIST_TYPE:
  2698. case FTP_RETR_TYPE:
  2699. case FTP_STOR_TYPE:
  2700. result = ftp_state_type_resp(data, ftpcode, ftpc->state);
  2701. break;
  2702. case FTP_SIZE:
  2703. case FTP_RETR_SIZE:
  2704. case FTP_STOR_SIZE:
  2705. result = ftp_state_size_resp(data, ftpcode, ftpc->state);
  2706. break;
  2707. case FTP_REST:
  2708. case FTP_RETR_REST:
  2709. result = ftp_state_rest_resp(data, conn, ftpcode, ftpc->state);
  2710. break;
  2711. case FTP_PRET:
  2712. if(ftpcode != 200) {
  2713. /* there only is this one standard OK return code. */
  2714. failf(data, "PRET command not accepted: %03d", ftpcode);
  2715. return CURLE_FTP_PRET_FAILED;
  2716. }
  2717. result = ftp_state_use_pasv(data, conn);
  2718. break;
  2719. case FTP_PASV:
  2720. result = ftp_state_pasv_resp(data, ftpcode);
  2721. break;
  2722. case FTP_PORT:
  2723. result = ftp_state_port_resp(data, ftpcode);
  2724. break;
  2725. case FTP_LIST:
  2726. case FTP_RETR:
  2727. result = ftp_state_get_resp(data, ftpcode, ftpc->state);
  2728. break;
  2729. case FTP_STOR:
  2730. result = ftp_state_stor_resp(data, ftpcode, ftpc->state);
  2731. break;
  2732. case FTP_QUIT:
  2733. default:
  2734. /* internal error */
  2735. ftp_state(data, FTP_STOP);
  2736. break;
  2737. }
  2738. } /* if(ftpcode) */
  2739. return result;
  2740. }
  2741. /* called repeatedly until done from multi.c */
  2742. static CURLcode ftp_multi_statemach(struct Curl_easy *data,
  2743. bool *done)
  2744. {
  2745. struct connectdata *conn = data->conn;
  2746. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2747. CURLcode result = Curl_pp_statemach(data, &ftpc->pp, FALSE, FALSE);
  2748. /* Check for the state outside of the Curl_socket_check() return code checks
  2749. since at times we are in fact already in this state when this function
  2750. gets called. */
  2751. *done = (ftpc->state == FTP_STOP);
  2752. return result;
  2753. }
  2754. static CURLcode ftp_block_statemach(struct Curl_easy *data,
  2755. struct connectdata *conn)
  2756. {
  2757. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2758. struct pingpong *pp = &ftpc->pp;
  2759. CURLcode result = CURLE_OK;
  2760. while(ftpc->state != FTP_STOP) {
  2761. result = Curl_pp_statemach(data, pp, TRUE, TRUE /* disconnecting */);
  2762. if(result)
  2763. break;
  2764. }
  2765. return result;
  2766. }
  2767. /*
  2768. * ftp_connect() should do everything that is to be considered a part of
  2769. * the connection phase.
  2770. *
  2771. * The variable 'done' points to will be TRUE if the protocol-layer connect
  2772. * phase is done when this function returns, or FALSE if not.
  2773. *
  2774. */
  2775. static CURLcode ftp_connect(struct Curl_easy *data,
  2776. bool *done) /* see description above */
  2777. {
  2778. CURLcode result;
  2779. struct connectdata *conn = data->conn;
  2780. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2781. struct pingpong *pp = &ftpc->pp;
  2782. *done = FALSE; /* default to not done yet */
  2783. /* We always support persistent connections on ftp */
  2784. connkeep(conn, "FTP default");
  2785. PINGPONG_SETUP(pp, ftp_statemachine, ftp_endofresp);
  2786. if(conn->handler->flags & PROTOPT_SSL) {
  2787. /* BLOCKING */
  2788. result = Curl_conn_connect(data, FIRSTSOCKET, TRUE, done);
  2789. if(result)
  2790. return result;
  2791. conn->bits.ftp_use_control_ssl = TRUE;
  2792. }
  2793. Curl_pp_init(pp); /* once per transfer */
  2794. /* When we connect, we start in the state where we await the 220
  2795. response */
  2796. ftp_state(data, FTP_WAIT220);
  2797. result = ftp_multi_statemach(data, done);
  2798. return result;
  2799. }
  2800. /***********************************************************************
  2801. *
  2802. * ftp_done()
  2803. *
  2804. * The DONE function. This does what needs to be done after a single DO has
  2805. * performed.
  2806. *
  2807. * Input argument is already checked for validity.
  2808. */
  2809. static CURLcode ftp_done(struct Curl_easy *data, CURLcode status,
  2810. bool premature)
  2811. {
  2812. struct connectdata *conn = data->conn;
  2813. struct FTP *ftp = data->req.p.ftp;
  2814. struct ftp_conn *ftpc = &conn->proto.ftpc;
  2815. struct pingpong *pp = &ftpc->pp;
  2816. ssize_t nread;
  2817. int ftpcode;
  2818. CURLcode result = CURLE_OK;
  2819. char *rawPath = NULL;
  2820. size_t pathLen = 0;
  2821. if(!ftp)
  2822. return CURLE_OK;
  2823. switch(status) {
  2824. case CURLE_BAD_DOWNLOAD_RESUME:
  2825. case CURLE_FTP_WEIRD_PASV_REPLY:
  2826. case CURLE_FTP_PORT_FAILED:
  2827. case CURLE_FTP_ACCEPT_FAILED:
  2828. case CURLE_FTP_ACCEPT_TIMEOUT:
  2829. case CURLE_FTP_COULDNT_SET_TYPE:
  2830. case CURLE_FTP_COULDNT_RETR_FILE:
  2831. case CURLE_PARTIAL_FILE:
  2832. case CURLE_UPLOAD_FAILED:
  2833. case CURLE_REMOTE_ACCESS_DENIED:
  2834. case CURLE_FILESIZE_EXCEEDED:
  2835. case CURLE_REMOTE_FILE_NOT_FOUND:
  2836. case CURLE_WRITE_ERROR:
  2837. /* the connection stays alive fine even though this happened */
  2838. case CURLE_OK: /* does not affect the control connection's status */
  2839. if(!premature)
  2840. break;
  2841. /* until we cope better with prematurely ended requests, let them
  2842. * fallback as if in complete failure */
  2843. FALLTHROUGH();
  2844. default: /* by default, an error means the control connection is
  2845. wedged and should not be used anymore */
  2846. ftpc->ctl_valid = FALSE;
  2847. ftpc->cwdfail = TRUE; /* set this TRUE to prevent us to remember the
  2848. current path, as this connection is going */
  2849. connclose(conn, "FTP ended with bad error code");
  2850. result = status; /* use the already set error code */
  2851. break;
  2852. }
  2853. if(data->state.wildcardmatch) {
  2854. if(data->set.chunk_end && ftpc->file) {
  2855. Curl_set_in_callback(data, TRUE);
  2856. data->set.chunk_end(data->set.wildcardptr);
  2857. Curl_set_in_callback(data, FALSE);
  2858. }
  2859. ftpc->known_filesize = -1;
  2860. }
  2861. if(!result)
  2862. /* get the url-decoded "raw" path */
  2863. result = Curl_urldecode(ftp->path, 0, &rawPath, &pathLen,
  2864. REJECT_CTRL);
  2865. if(result) {
  2866. /* We can limp along anyway (and should try to since we may already be in
  2867. * the error path) */
  2868. ftpc->ctl_valid = FALSE; /* mark control connection as bad */
  2869. connclose(conn, "FTP: out of memory!"); /* mark for connection closure */
  2870. free(ftpc->prevpath);
  2871. ftpc->prevpath = NULL; /* no path remembering */
  2872. }
  2873. else { /* remember working directory for connection reuse */
  2874. if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
  2875. free(rawPath); /* full path => no CWDs happened => keep ftpc->prevpath */
  2876. else {
  2877. free(ftpc->prevpath);
  2878. if(!ftpc->cwdfail) {
  2879. if(data->set.ftp_filemethod == FTPFILE_NOCWD)
  2880. pathLen = 0; /* relative path => working directory is FTP home */
  2881. else
  2882. /* file is url-decoded */
  2883. pathLen -= ftpc->file ? strlen(ftpc->file) : 0;
  2884. rawPath[pathLen] = '\0';
  2885. ftpc->prevpath = rawPath;
  2886. }
  2887. else {
  2888. free(rawPath);
  2889. ftpc->prevpath = NULL; /* no path */
  2890. }
  2891. }
  2892. if(ftpc->prevpath)
  2893. infof(data, "Remembering we are in dir \"%s\"", ftpc->prevpath);
  2894. }
  2895. /* free the dir tree and file parts */
  2896. freedirs(ftpc);
  2897. /* shut down the socket to inform the server we are done */
  2898. #ifdef _WIN32_WCE
  2899. shutdown(conn->sock[SECONDARYSOCKET], 2); /* SD_BOTH */
  2900. #endif
  2901. if(conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD) {
  2902. if(!result && ftpc->dont_check && data->req.maxdownload > 0) {
  2903. /* partial download completed */
  2904. result = Curl_pp_sendf(data, pp, "%s", "ABOR");
  2905. if(result) {
  2906. failf(data, "Failure sending ABOR command: %s",
  2907. curl_easy_strerror(result));
  2908. ftpc->ctl_valid = FALSE; /* mark control connection as bad */
  2909. connclose(conn, "ABOR command failed"); /* connection closure */
  2910. }
  2911. }
  2912. close_secondarysocket(data);
  2913. }
  2914. if(!result && (ftp->transfer == PPTRANSFER_BODY) && ftpc->ctl_valid &&
  2915. pp->pending_resp && !premature) {
  2916. /*
  2917. * Let's see what the server says about the transfer we just performed,
  2918. * but lower the timeout as sometimes this connection has died while the
  2919. * data has been transferred. This happens when doing through NATs etc that
  2920. * abandon old silent connections.
  2921. */
  2922. timediff_t old_time = pp->response_time;
  2923. pp->response_time = 60*1000; /* give it only a minute for now */
  2924. pp->response = Curl_now(); /* timeout relative now */
  2925. result = Curl_GetFTPResponse(data, &nread, &ftpcode);
  2926. pp->response_time = old_time; /* set this back to previous value */
  2927. if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) {
  2928. failf(data, "control connection looks dead");
  2929. ftpc->ctl_valid = FALSE; /* mark control connection as bad */
  2930. connclose(conn, "Timeout or similar in FTP DONE operation"); /* close */
  2931. }
  2932. if(result) {
  2933. Curl_safefree(ftp->pathalloc);
  2934. return result;
  2935. }
  2936. if(ftpc->dont_check && data->req.maxdownload > 0) {
  2937. /* we have just sent ABOR and there is no reliable way to check if it was
  2938. * successful or not; we have to close the connection now */
  2939. infof(data, "partial download completed, closing connection");
  2940. connclose(conn, "Partial download with no ability to check");
  2941. return result;
  2942. }
  2943. if(!ftpc->dont_check) {
  2944. /* 226 Transfer complete, 250 Requested file action okay, completed. */
  2945. switch(ftpcode) {
  2946. case 226:
  2947. case 250:
  2948. break;
  2949. case 552:
  2950. failf(data, "Exceeded storage allocation");
  2951. result = CURLE_REMOTE_DISK_FULL;
  2952. break;
  2953. default:
  2954. failf(data, "server did not report OK, got %d", ftpcode);
  2955. result = CURLE_PARTIAL_FILE;
  2956. break;
  2957. }
  2958. }
  2959. }
  2960. if(result || premature)
  2961. /* the response code from the transfer showed an error already so no
  2962. use checking further */
  2963. ;
  2964. else if(data->state.upload) {
  2965. if((-1 != data->state.infilesize) &&
  2966. (data->state.infilesize != data->req.writebytecount) &&
  2967. !data->set.crlf &&
  2968. (ftp->transfer == PPTRANSFER_BODY)) {
  2969. failf(data, "Uploaded unaligned file size (%" FMT_OFF_T
  2970. " out of %" FMT_OFF_T " bytes)",
  2971. data->req.writebytecount, data->state.infilesize);
  2972. result = CURLE_PARTIAL_FILE;
  2973. }
  2974. }
  2975. else {
  2976. if((-1 != data->req.size) &&
  2977. (data->req.size != data->req.bytecount) &&
  2978. (data->req.maxdownload != data->req.bytecount)) {
  2979. failf(data, "Received only partial file: %" FMT_OFF_T " bytes",
  2980. data->req.bytecount);
  2981. result = CURLE_PARTIAL_FILE;
  2982. }
  2983. else if(!ftpc->dont_check &&
  2984. !data->req.bytecount &&
  2985. (data->req.size > 0)) {
  2986. failf(data, "No data was received");
  2987. result = CURLE_FTP_COULDNT_RETR_FILE;
  2988. }
  2989. }
  2990. /* clear these for next connection */
  2991. ftp->transfer = PPTRANSFER_BODY;
  2992. ftpc->dont_check = FALSE;
  2993. /* Send any post-transfer QUOTE strings? */
  2994. if(!status && !result && !premature && data->set.postquote)
  2995. result = ftp_sendquote(data, conn, data->set.postquote);
  2996. CURL_TRC_FTP(data, "[%s] done, result=%d", FTP_DSTATE(data), result);
  2997. Curl_safefree(ftp->pathalloc);
  2998. return result;
  2999. }
  3000. /***********************************************************************
  3001. *
  3002. * ftp_sendquote()
  3003. *
  3004. * Where a 'quote' means a list of custom commands to send to the server.
  3005. * The quote list is passed as an argument.
  3006. *
  3007. * BLOCKING
  3008. */
  3009. static
  3010. CURLcode ftp_sendquote(struct Curl_easy *data,
  3011. struct connectdata *conn, struct curl_slist *quote)
  3012. {
  3013. struct curl_slist *item;
  3014. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3015. struct pingpong *pp = &ftpc->pp;
  3016. item = quote;
  3017. while(item) {
  3018. if(item->data) {
  3019. ssize_t nread;
  3020. char *cmd = item->data;
  3021. bool acceptfail = FALSE;
  3022. CURLcode result;
  3023. int ftpcode = 0;
  3024. /* if a command starts with an asterisk, which a legal FTP command never
  3025. can, the command will be allowed to fail without it causing any
  3026. aborts or cancels etc. It will cause libcurl to act as if the command
  3027. is successful, whatever the server responds. */
  3028. if(cmd[0] == '*') {
  3029. cmd++;
  3030. acceptfail = TRUE;
  3031. }
  3032. result = Curl_pp_sendf(data, &ftpc->pp, "%s", cmd);
  3033. if(!result) {
  3034. pp->response = Curl_now(); /* timeout relative now */
  3035. result = Curl_GetFTPResponse(data, &nread, &ftpcode);
  3036. }
  3037. if(result)
  3038. return result;
  3039. if(!acceptfail && (ftpcode >= 400)) {
  3040. failf(data, "QUOT string not accepted: %s", cmd);
  3041. return CURLE_QUOTE_ERROR;
  3042. }
  3043. }
  3044. item = item->next;
  3045. }
  3046. return CURLE_OK;
  3047. }
  3048. /***********************************************************************
  3049. *
  3050. * ftp_need_type()
  3051. *
  3052. * Returns TRUE if we in the current situation should send TYPE
  3053. */
  3054. static int ftp_need_type(struct connectdata *conn,
  3055. bool ascii_wanted)
  3056. {
  3057. return conn->proto.ftpc.transfertype != (ascii_wanted ? 'A' : 'I');
  3058. }
  3059. /***********************************************************************
  3060. *
  3061. * ftp_nb_type()
  3062. *
  3063. * Set TYPE. We only deal with ASCII or BINARY so this function
  3064. * sets one of them.
  3065. * If the transfer type is not sent, simulate on OK response in newstate
  3066. */
  3067. static CURLcode ftp_nb_type(struct Curl_easy *data,
  3068. struct connectdata *conn,
  3069. bool ascii, ftpstate newstate)
  3070. {
  3071. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3072. CURLcode result;
  3073. char want = (char)(ascii ? 'A' : 'I');
  3074. if(ftpc->transfertype == want) {
  3075. ftp_state(data, newstate);
  3076. return ftp_state_type_resp(data, 200, newstate);
  3077. }
  3078. result = Curl_pp_sendf(data, &ftpc->pp, "TYPE %c", want);
  3079. if(!result) {
  3080. ftp_state(data, newstate);
  3081. /* keep track of our current transfer type */
  3082. ftpc->transfertype = want;
  3083. }
  3084. return result;
  3085. }
  3086. /***************************************************************************
  3087. *
  3088. * ftp_pasv_verbose()
  3089. *
  3090. * This function only outputs some informationals about this second connection
  3091. * when we have issued a PASV command before and thus we have connected to a
  3092. * possibly new IP address.
  3093. *
  3094. */
  3095. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  3096. static void
  3097. ftp_pasv_verbose(struct Curl_easy *data,
  3098. struct Curl_addrinfo *ai,
  3099. char *newhost, /* ASCII version */
  3100. int port)
  3101. {
  3102. char buf[256];
  3103. Curl_printable_address(ai, buf, sizeof(buf));
  3104. infof(data, "Connecting to %s (%s) port %d", newhost, buf, port);
  3105. }
  3106. #endif
  3107. /*
  3108. * ftp_do_more()
  3109. *
  3110. * This function shall be called when the second FTP (data) connection is
  3111. * connected.
  3112. *
  3113. * 'complete' can return 0 for incomplete, 1 for done and -1 for go back
  3114. * (which basically is only for when PASV is being sent to retry a failed
  3115. * EPSV).
  3116. */
  3117. static CURLcode ftp_do_more(struct Curl_easy *data, int *completep)
  3118. {
  3119. struct connectdata *conn = data->conn;
  3120. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3121. CURLcode result = CURLE_OK;
  3122. bool connected = FALSE;
  3123. bool complete = FALSE;
  3124. /* the ftp struct is inited in ftp_connect(). If we are connecting to an HTTP
  3125. * proxy then the state will not be valid until after that connection is
  3126. * complete */
  3127. struct FTP *ftp = NULL;
  3128. /* if the second connection has been set up, try to connect it fully
  3129. * to the remote host. This may not complete at this time, for several
  3130. * reasons:
  3131. * - we do EPTR and the server will not connect to our listen socket
  3132. * until we send more FTP commands
  3133. * - an SSL filter is in place and the server will not start the TLS
  3134. * handshake until we send more FTP commands
  3135. */
  3136. if(conn->cfilter[SECONDARYSOCKET]) {
  3137. bool is_eptr = Curl_conn_is_tcp_listen(data, SECONDARYSOCKET);
  3138. result = Curl_conn_connect(data, SECONDARYSOCKET, FALSE, &connected);
  3139. if(result || (!connected && !is_eptr &&
  3140. !Curl_conn_is_ip_connected(data, SECONDARYSOCKET))) {
  3141. if(result && !is_eptr && (ftpc->count1 == 0)) {
  3142. *completep = -1; /* go back to DOING please */
  3143. /* this is a EPSV connect failing, try PASV instead */
  3144. return ftp_epsv_disable(data, conn);
  3145. }
  3146. *completep = (int)complete;
  3147. return result;
  3148. }
  3149. }
  3150. /* Curl_proxy_connect might have moved the protocol state */
  3151. ftp = data->req.p.ftp;
  3152. if(ftpc->state) {
  3153. /* already in a state so skip the initial commands.
  3154. They are only done to kickstart the do_more state */
  3155. result = ftp_multi_statemach(data, &complete);
  3156. *completep = (int)complete;
  3157. /* if we got an error or if we do not wait for a data connection return
  3158. immediately */
  3159. if(result || !ftpc->wait_data_conn)
  3160. return result;
  3161. /* if we reach the end of the FTP state machine here, *complete will be
  3162. TRUE but so is ftpc->wait_data_conn, which says we need to wait for the
  3163. data connection and therefore we are not actually complete */
  3164. *completep = 0;
  3165. }
  3166. if(ftp->transfer <= PPTRANSFER_INFO) {
  3167. /* a transfer is about to take place, or if not a filename was given so we
  3168. will do a SIZE on it later and then we need the right TYPE first */
  3169. if(ftpc->wait_data_conn) {
  3170. bool serv_conned;
  3171. result = Curl_conn_connect(data, SECONDARYSOCKET, TRUE, &serv_conned);
  3172. if(result)
  3173. return result; /* Failed to accept data connection */
  3174. if(serv_conned) {
  3175. /* It looks data connection is established */
  3176. ftpc->wait_data_conn = FALSE;
  3177. result = InitiateTransfer(data);
  3178. if(result)
  3179. return result;
  3180. *completep = 1; /* this state is now complete when the server has
  3181. connected back to us */
  3182. }
  3183. else {
  3184. result = ftp_check_ctrl_on_data_wait(data);
  3185. if(result)
  3186. return result;
  3187. }
  3188. }
  3189. else if(data->state.upload) {
  3190. result = ftp_nb_type(data, conn, data->state.prefer_ascii,
  3191. FTP_STOR_TYPE);
  3192. if(result)
  3193. return result;
  3194. result = ftp_multi_statemach(data, &complete);
  3195. *completep = (int)complete;
  3196. }
  3197. else {
  3198. /* download */
  3199. ftp->downloadsize = -1; /* unknown as of yet */
  3200. result = Curl_range(data);
  3201. if(result == CURLE_OK && data->req.maxdownload >= 0) {
  3202. /* Do not check for successful transfer */
  3203. ftpc->dont_check = TRUE;
  3204. }
  3205. if(result)
  3206. ;
  3207. else if(data->state.list_only || !ftpc->file) {
  3208. /* The specified path ends with a slash, and therefore we think this
  3209. is a directory that is requested, use LIST. But before that we
  3210. need to set ASCII transfer mode. */
  3211. /* But only if a body transfer was requested. */
  3212. if(ftp->transfer == PPTRANSFER_BODY) {
  3213. result = ftp_nb_type(data, conn, TRUE, FTP_LIST_TYPE);
  3214. if(result)
  3215. return result;
  3216. }
  3217. /* otherwise just fall through */
  3218. }
  3219. else {
  3220. result = ftp_nb_type(data, conn, data->state.prefer_ascii,
  3221. FTP_RETR_TYPE);
  3222. if(result)
  3223. return result;
  3224. }
  3225. result = ftp_multi_statemach(data, &complete);
  3226. *completep = (int)complete;
  3227. }
  3228. return result;
  3229. }
  3230. /* no data to transfer */
  3231. Curl_xfer_setup_nop(data);
  3232. if(!ftpc->wait_data_conn) {
  3233. /* no waiting for the data connection so this is now complete */
  3234. *completep = 1;
  3235. CURL_TRC_FTP(data, "[%s] DO-MORE phase ends with %d", FTP_DSTATE(data),
  3236. (int)result);
  3237. }
  3238. return result;
  3239. }
  3240. /***********************************************************************
  3241. *
  3242. * ftp_perform()
  3243. *
  3244. * This is the actual DO function for FTP. Get a file/directory according to
  3245. * the options previously setup.
  3246. */
  3247. static
  3248. CURLcode ftp_perform(struct Curl_easy *data,
  3249. bool *connected, /* connect status after PASV / PORT */
  3250. bool *dophase_done)
  3251. {
  3252. /* this is FTP and no proxy */
  3253. CURLcode result = CURLE_OK;
  3254. CURL_TRC_FTP(data, "[%s] DO phase starts", FTP_DSTATE(data));
  3255. if(data->req.no_body) {
  3256. /* requested no body means no transfer... */
  3257. struct FTP *ftp = data->req.p.ftp;
  3258. ftp->transfer = PPTRANSFER_INFO;
  3259. }
  3260. *dophase_done = FALSE; /* not done yet */
  3261. /* start the first command in the DO phase */
  3262. result = ftp_state_quote(data, TRUE, FTP_QUOTE);
  3263. if(result)
  3264. return result;
  3265. /* run the state-machine */
  3266. result = ftp_multi_statemach(data, dophase_done);
  3267. *connected = Curl_conn_is_connected(data->conn, SECONDARYSOCKET);
  3268. if(*connected)
  3269. infof(data, "[FTP] [%s] perform, DATA connection established",
  3270. FTP_DSTATE(data));
  3271. else
  3272. CURL_TRC_FTP(data, "[%s] perform, awaiting DATA connect",
  3273. FTP_DSTATE(data));
  3274. if(*dophase_done)
  3275. CURL_TRC_FTP(data, "[%s] DO phase is complete1", FTP_DSTATE(data));
  3276. return result;
  3277. }
  3278. static void wc_data_dtor(void *ptr)
  3279. {
  3280. struct ftp_wc *ftpwc = ptr;
  3281. if(ftpwc && ftpwc->parser)
  3282. Curl_ftp_parselist_data_free(&ftpwc->parser);
  3283. free(ftpwc);
  3284. }
  3285. static CURLcode init_wc_data(struct Curl_easy *data)
  3286. {
  3287. char *last_slash;
  3288. struct FTP *ftp = data->req.p.ftp;
  3289. char *path = ftp->path;
  3290. struct WildcardData *wildcard = data->wildcard;
  3291. CURLcode result = CURLE_OK;
  3292. struct ftp_wc *ftpwc = NULL;
  3293. last_slash = strrchr(ftp->path, '/');
  3294. if(last_slash) {
  3295. last_slash++;
  3296. if(last_slash[0] == '\0') {
  3297. wildcard->state = CURLWC_CLEAN;
  3298. return ftp_parse_url_path(data);
  3299. }
  3300. wildcard->pattern = strdup(last_slash);
  3301. if(!wildcard->pattern)
  3302. return CURLE_OUT_OF_MEMORY;
  3303. last_slash[0] = '\0'; /* cut file from path */
  3304. }
  3305. else { /* there is only 'wildcard pattern' or nothing */
  3306. if(path[0]) {
  3307. wildcard->pattern = strdup(path);
  3308. if(!wildcard->pattern)
  3309. return CURLE_OUT_OF_MEMORY;
  3310. path[0] = '\0';
  3311. }
  3312. else { /* only list */
  3313. wildcard->state = CURLWC_CLEAN;
  3314. return ftp_parse_url_path(data);
  3315. }
  3316. }
  3317. /* program continues only if URL is not ending with slash, allocate needed
  3318. resources for wildcard transfer */
  3319. /* allocate ftp protocol specific wildcard data */
  3320. ftpwc = calloc(1, sizeof(struct ftp_wc));
  3321. if(!ftpwc) {
  3322. result = CURLE_OUT_OF_MEMORY;
  3323. goto fail;
  3324. }
  3325. /* INITIALIZE parselist structure */
  3326. ftpwc->parser = Curl_ftp_parselist_data_alloc();
  3327. if(!ftpwc->parser) {
  3328. result = CURLE_OUT_OF_MEMORY;
  3329. goto fail;
  3330. }
  3331. wildcard->ftpwc = ftpwc; /* put it to the WildcardData tmp pointer */
  3332. wildcard->dtor = wc_data_dtor;
  3333. /* wildcard does not support NOCWD option (assert it?) */
  3334. if(data->set.ftp_filemethod == FTPFILE_NOCWD)
  3335. data->set.ftp_filemethod = FTPFILE_MULTICWD;
  3336. /* try to parse ftp URL */
  3337. result = ftp_parse_url_path(data);
  3338. if(result) {
  3339. goto fail;
  3340. }
  3341. wildcard->path = strdup(ftp->path);
  3342. if(!wildcard->path) {
  3343. result = CURLE_OUT_OF_MEMORY;
  3344. goto fail;
  3345. }
  3346. /* backup old write_function */
  3347. ftpwc->backup.write_function = data->set.fwrite_func;
  3348. /* parsing write function */
  3349. data->set.fwrite_func = Curl_ftp_parselist;
  3350. /* backup old file descriptor */
  3351. ftpwc->backup.file_descriptor = data->set.out;
  3352. /* let the writefunc callback know the transfer */
  3353. data->set.out = data;
  3354. infof(data, "Wildcard - Parsing started");
  3355. return CURLE_OK;
  3356. fail:
  3357. if(ftpwc) {
  3358. Curl_ftp_parselist_data_free(&ftpwc->parser);
  3359. free(ftpwc);
  3360. }
  3361. Curl_safefree(wildcard->pattern);
  3362. wildcard->dtor = ZERO_NULL;
  3363. wildcard->ftpwc = NULL;
  3364. return result;
  3365. }
  3366. static CURLcode wc_statemach(struct Curl_easy *data)
  3367. {
  3368. struct WildcardData * const wildcard = data->wildcard;
  3369. struct connectdata *conn = data->conn;
  3370. CURLcode result = CURLE_OK;
  3371. for(;;) {
  3372. switch(wildcard->state) {
  3373. case CURLWC_INIT:
  3374. result = init_wc_data(data);
  3375. if(wildcard->state == CURLWC_CLEAN)
  3376. /* only listing! */
  3377. return result;
  3378. wildcard->state = result ? CURLWC_ERROR : CURLWC_MATCHING;
  3379. return result;
  3380. case CURLWC_MATCHING: {
  3381. /* In this state is LIST response successfully parsed, so lets restore
  3382. previous WRITEFUNCTION callback and WRITEDATA pointer */
  3383. struct ftp_wc *ftpwc = wildcard->ftpwc;
  3384. data->set.fwrite_func = ftpwc->backup.write_function;
  3385. data->set.out = ftpwc->backup.file_descriptor;
  3386. ftpwc->backup.write_function = ZERO_NULL;
  3387. ftpwc->backup.file_descriptor = NULL;
  3388. wildcard->state = CURLWC_DOWNLOADING;
  3389. if(Curl_ftp_parselist_geterror(ftpwc->parser)) {
  3390. /* error found in LIST parsing */
  3391. wildcard->state = CURLWC_CLEAN;
  3392. continue;
  3393. }
  3394. if(Curl_llist_count(&wildcard->filelist) == 0) {
  3395. /* no corresponding file */
  3396. wildcard->state = CURLWC_CLEAN;
  3397. return CURLE_REMOTE_FILE_NOT_FOUND;
  3398. }
  3399. continue;
  3400. }
  3401. case CURLWC_DOWNLOADING: {
  3402. /* filelist has at least one file, lets get first one */
  3403. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3404. struct Curl_llist_node *head = Curl_llist_head(&wildcard->filelist);
  3405. struct curl_fileinfo *finfo = Curl_node_elem(head);
  3406. struct FTP *ftp = data->req.p.ftp;
  3407. char *tmp_path = aprintf("%s%s", wildcard->path, finfo->filename);
  3408. if(!tmp_path)
  3409. return CURLE_OUT_OF_MEMORY;
  3410. /* switch default ftp->path and tmp_path */
  3411. free(ftp->pathalloc);
  3412. ftp->pathalloc = ftp->path = tmp_path;
  3413. infof(data, "Wildcard - START of \"%s\"", finfo->filename);
  3414. if(data->set.chunk_bgn) {
  3415. long userresponse;
  3416. Curl_set_in_callback(data, TRUE);
  3417. userresponse = data->set.chunk_bgn(
  3418. finfo, data->set.wildcardptr,
  3419. (int)Curl_llist_count(&wildcard->filelist));
  3420. Curl_set_in_callback(data, FALSE);
  3421. switch(userresponse) {
  3422. case CURL_CHUNK_BGN_FUNC_SKIP:
  3423. infof(data, "Wildcard - \"%s\" skipped by user",
  3424. finfo->filename);
  3425. wildcard->state = CURLWC_SKIP;
  3426. continue;
  3427. case CURL_CHUNK_BGN_FUNC_FAIL:
  3428. return CURLE_CHUNK_FAILED;
  3429. }
  3430. }
  3431. if(finfo->filetype != CURLFILETYPE_FILE) {
  3432. wildcard->state = CURLWC_SKIP;
  3433. continue;
  3434. }
  3435. if(finfo->flags & CURLFINFOFLAG_KNOWN_SIZE)
  3436. ftpc->known_filesize = finfo->size;
  3437. result = ftp_parse_url_path(data);
  3438. if(result)
  3439. return result;
  3440. /* we do not need the Curl_fileinfo of first file anymore */
  3441. Curl_node_remove(Curl_llist_head(&wildcard->filelist));
  3442. if(Curl_llist_count(&wildcard->filelist) == 0) {
  3443. /* remains only one file to down. */
  3444. wildcard->state = CURLWC_CLEAN;
  3445. /* after that will be ftp_do called once again and no transfer
  3446. will be done because of CURLWC_CLEAN state */
  3447. return CURLE_OK;
  3448. }
  3449. return result;
  3450. }
  3451. case CURLWC_SKIP: {
  3452. if(data->set.chunk_end) {
  3453. Curl_set_in_callback(data, TRUE);
  3454. data->set.chunk_end(data->set.wildcardptr);
  3455. Curl_set_in_callback(data, FALSE);
  3456. }
  3457. Curl_node_remove(Curl_llist_head(&wildcard->filelist));
  3458. wildcard->state = (Curl_llist_count(&wildcard->filelist) == 0) ?
  3459. CURLWC_CLEAN : CURLWC_DOWNLOADING;
  3460. continue;
  3461. }
  3462. case CURLWC_CLEAN: {
  3463. struct ftp_wc *ftpwc = wildcard->ftpwc;
  3464. result = CURLE_OK;
  3465. if(ftpwc)
  3466. result = Curl_ftp_parselist_geterror(ftpwc->parser);
  3467. wildcard->state = result ? CURLWC_ERROR : CURLWC_DONE;
  3468. return result;
  3469. }
  3470. case CURLWC_DONE:
  3471. case CURLWC_ERROR:
  3472. case CURLWC_CLEAR:
  3473. if(wildcard->dtor) {
  3474. wildcard->dtor(wildcard->ftpwc);
  3475. wildcard->ftpwc = NULL;
  3476. }
  3477. return result;
  3478. }
  3479. }
  3480. /* UNREACHABLE */
  3481. }
  3482. /***********************************************************************
  3483. *
  3484. * ftp_do()
  3485. *
  3486. * This function is registered as 'curl_do' function. It decodes the path
  3487. * parts etc as a wrapper to the actual DO function (ftp_perform).
  3488. *
  3489. * The input argument is already checked for validity.
  3490. */
  3491. static CURLcode ftp_do(struct Curl_easy *data, bool *done)
  3492. {
  3493. CURLcode result = CURLE_OK;
  3494. struct connectdata *conn = data->conn;
  3495. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3496. *done = FALSE; /* default to false */
  3497. ftpc->wait_data_conn = FALSE; /* default to no such wait */
  3498. #ifdef CURL_PREFER_LF_LINEENDS
  3499. {
  3500. /* FTP data may need conversion. */
  3501. struct Curl_cwriter *ftp_lc_writer;
  3502. result = Curl_cwriter_create(&ftp_lc_writer, data, &ftp_cw_lc,
  3503. CURL_CW_CONTENT_DECODE);
  3504. if(result)
  3505. return result;
  3506. result = Curl_cwriter_add(data, ftp_lc_writer);
  3507. if(result) {
  3508. Curl_cwriter_free(data, ftp_lc_writer);
  3509. return result;
  3510. }
  3511. }
  3512. #endif /* CURL_PREFER_LF_LINEENDS */
  3513. if(data->state.wildcardmatch) {
  3514. result = wc_statemach(data);
  3515. if(data->wildcard->state == CURLWC_SKIP ||
  3516. data->wildcard->state == CURLWC_DONE) {
  3517. /* do not call ftp_regular_transfer */
  3518. return CURLE_OK;
  3519. }
  3520. if(result) /* error, loop or skipping the file */
  3521. return result;
  3522. }
  3523. else { /* no wildcard FSM needed */
  3524. result = ftp_parse_url_path(data);
  3525. if(result)
  3526. return result;
  3527. }
  3528. result = ftp_regular_transfer(data, done);
  3529. return result;
  3530. }
  3531. /***********************************************************************
  3532. *
  3533. * ftp_quit()
  3534. *
  3535. * This should be called before calling sclose() on an ftp control connection
  3536. * (not data connections). We should then wait for the response from the
  3537. * server before returning. The calling code should then try to close the
  3538. * connection.
  3539. *
  3540. */
  3541. static CURLcode ftp_quit(struct Curl_easy *data, struct connectdata *conn)
  3542. {
  3543. CURLcode result = CURLE_OK;
  3544. if(conn->proto.ftpc.ctl_valid) {
  3545. result = Curl_pp_sendf(data, &conn->proto.ftpc.pp, "%s", "QUIT");
  3546. if(result) {
  3547. failf(data, "Failure sending QUIT command: %s",
  3548. curl_easy_strerror(result));
  3549. conn->proto.ftpc.ctl_valid = FALSE; /* mark control connection as bad */
  3550. connclose(conn, "QUIT command failed"); /* mark for connection closure */
  3551. ftp_state(data, FTP_STOP);
  3552. return result;
  3553. }
  3554. ftp_state(data, FTP_QUIT);
  3555. result = ftp_block_statemach(data, conn);
  3556. }
  3557. return result;
  3558. }
  3559. /***********************************************************************
  3560. *
  3561. * ftp_disconnect()
  3562. *
  3563. * Disconnect from an FTP server. Cleanup protocol-specific per-connection
  3564. * resources. BLOCKING.
  3565. */
  3566. static CURLcode ftp_disconnect(struct Curl_easy *data,
  3567. struct connectdata *conn,
  3568. bool dead_connection)
  3569. {
  3570. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3571. struct pingpong *pp = &ftpc->pp;
  3572. /* We cannot send quit unconditionally. If this connection is stale or
  3573. bad in any way, sending quit and waiting around here will make the
  3574. disconnect wait in vain and cause more problems than we need to.
  3575. ftp_quit() will check the state of ftp->ctl_valid. If it is ok it
  3576. will try to send the QUIT command, otherwise it will just return.
  3577. */
  3578. if(dead_connection)
  3579. ftpc->ctl_valid = FALSE;
  3580. /* The FTP session may or may not have been allocated/setup at this point! */
  3581. (void)ftp_quit(data, conn); /* ignore errors on the QUIT */
  3582. if(ftpc->entrypath) {
  3583. if(data->state.most_recent_ftp_entrypath == ftpc->entrypath) {
  3584. data->state.most_recent_ftp_entrypath = NULL;
  3585. }
  3586. Curl_safefree(ftpc->entrypath);
  3587. }
  3588. freedirs(ftpc);
  3589. Curl_safefree(ftpc->account);
  3590. Curl_safefree(ftpc->alternative_to_user);
  3591. Curl_safefree(ftpc->prevpath);
  3592. Curl_safefree(ftpc->server_os);
  3593. Curl_pp_disconnect(pp);
  3594. Curl_sec_end(conn);
  3595. return CURLE_OK;
  3596. }
  3597. #ifdef _MSC_VER
  3598. /* warning C4706: assignment within conditional expression */
  3599. #pragma warning(disable:4706)
  3600. #endif
  3601. /***********************************************************************
  3602. *
  3603. * ftp_parse_url_path()
  3604. *
  3605. * Parse the URL path into separate path components.
  3606. *
  3607. */
  3608. static
  3609. CURLcode ftp_parse_url_path(struct Curl_easy *data)
  3610. {
  3611. /* the ftp struct is already inited in ftp_connect() */
  3612. struct FTP *ftp = data->req.p.ftp;
  3613. struct connectdata *conn = data->conn;
  3614. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3615. const char *slashPos = NULL;
  3616. const char *fileName = NULL;
  3617. CURLcode result = CURLE_OK;
  3618. char *rawPath = NULL; /* url-decoded "raw" path */
  3619. size_t pathLen = 0;
  3620. ftpc->ctl_valid = FALSE;
  3621. ftpc->cwdfail = FALSE;
  3622. /* url-decode ftp path before further evaluation */
  3623. result = Curl_urldecode(ftp->path, 0, &rawPath, &pathLen, REJECT_CTRL);
  3624. if(result) {
  3625. failf(data, "path contains control characters");
  3626. return result;
  3627. }
  3628. switch(data->set.ftp_filemethod) {
  3629. case FTPFILE_NOCWD: /* fastest, but less standard-compliant */
  3630. if((pathLen > 0) && (rawPath[pathLen - 1] != '/'))
  3631. fileName = rawPath; /* this is a full file path */
  3632. /*
  3633. else: ftpc->file is not used anywhere other than for operations on
  3634. a file. In other words, never for directory operations.
  3635. So we can safely leave filename as NULL here and use it as a
  3636. argument in dir/file decisions.
  3637. */
  3638. break;
  3639. case FTPFILE_SINGLECWD:
  3640. slashPos = strrchr(rawPath, '/');
  3641. if(slashPos) {
  3642. /* get path before last slash, except for / */
  3643. size_t dirlen = slashPos - rawPath;
  3644. if(dirlen == 0)
  3645. dirlen = 1;
  3646. ftpc->dirs = calloc(1, sizeof(ftpc->dirs[0]));
  3647. if(!ftpc->dirs) {
  3648. free(rawPath);
  3649. return CURLE_OUT_OF_MEMORY;
  3650. }
  3651. ftpc->dirs[0] = Curl_memdup0(rawPath, dirlen);
  3652. if(!ftpc->dirs[0]) {
  3653. free(rawPath);
  3654. return CURLE_OUT_OF_MEMORY;
  3655. }
  3656. ftpc->dirdepth = 1; /* we consider it to be a single dir */
  3657. fileName = slashPos + 1; /* rest is filename */
  3658. }
  3659. else
  3660. fileName = rawPath; /* filename only (or empty) */
  3661. break;
  3662. default: /* allow pretty much anything */
  3663. case FTPFILE_MULTICWD: {
  3664. /* current position: begin of next path component */
  3665. const char *curPos = rawPath;
  3666. /* number of entries allocated for the 'dirs' array */
  3667. size_t dirAlloc = 0;
  3668. const char *str = rawPath;
  3669. for(; *str != 0; ++str)
  3670. if(*str == '/')
  3671. ++dirAlloc;
  3672. if(dirAlloc) {
  3673. ftpc->dirs = calloc(dirAlloc, sizeof(ftpc->dirs[0]));
  3674. if(!ftpc->dirs) {
  3675. free(rawPath);
  3676. return CURLE_OUT_OF_MEMORY;
  3677. }
  3678. /* parse the URL path into separate path components */
  3679. while((slashPos = strchr(curPos, '/'))) {
  3680. size_t compLen = slashPos - curPos;
  3681. /* path starts with a slash: add that as a directory */
  3682. if((compLen == 0) && (ftpc->dirdepth == 0))
  3683. ++compLen;
  3684. /* we skip empty path components, like "x//y" since the FTP command
  3685. CWD requires a parameter and a non-existent parameter a) does not
  3686. work on many servers and b) has no effect on the others. */
  3687. if(compLen > 0) {
  3688. char *comp = Curl_memdup0(curPos, compLen);
  3689. if(!comp) {
  3690. free(rawPath);
  3691. return CURLE_OUT_OF_MEMORY;
  3692. }
  3693. ftpc->dirs[ftpc->dirdepth++] = comp;
  3694. }
  3695. curPos = slashPos + 1;
  3696. }
  3697. }
  3698. DEBUGASSERT((size_t)ftpc->dirdepth <= dirAlloc);
  3699. fileName = curPos; /* the rest is the filename (or empty) */
  3700. }
  3701. break;
  3702. } /* switch */
  3703. if(fileName && *fileName)
  3704. ftpc->file = strdup(fileName);
  3705. else
  3706. ftpc->file = NULL; /* instead of point to a zero byte,
  3707. we make it a NULL pointer */
  3708. if(data->state.upload && !ftpc->file && (ftp->transfer == PPTRANSFER_BODY)) {
  3709. /* We need a filename when uploading. Return error! */
  3710. failf(data, "Uploading to a URL without a filename");
  3711. free(rawPath);
  3712. return CURLE_URL_MALFORMAT;
  3713. }
  3714. ftpc->cwddone = FALSE; /* default to not done */
  3715. if((data->set.ftp_filemethod == FTPFILE_NOCWD) && (rawPath[0] == '/'))
  3716. ftpc->cwddone = TRUE; /* skip CWD for absolute paths */
  3717. else { /* newly created FTP connections are already in entry path */
  3718. const char *oldPath = conn->bits.reuse ? ftpc->prevpath : "";
  3719. if(oldPath) {
  3720. size_t n = pathLen;
  3721. if(data->set.ftp_filemethod == FTPFILE_NOCWD)
  3722. n = 0; /* CWD to entry for relative paths */
  3723. else
  3724. n -= ftpc->file ? strlen(ftpc->file) : 0;
  3725. if((strlen(oldPath) == n) && !strncmp(rawPath, oldPath, n)) {
  3726. infof(data, "Request has same path as previous transfer");
  3727. ftpc->cwddone = TRUE;
  3728. }
  3729. }
  3730. }
  3731. free(rawPath);
  3732. return CURLE_OK;
  3733. }
  3734. /* call this when the DO phase has completed */
  3735. static CURLcode ftp_dophase_done(struct Curl_easy *data, bool connected)
  3736. {
  3737. struct connectdata *conn = data->conn;
  3738. struct FTP *ftp = data->req.p.ftp;
  3739. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3740. if(connected) {
  3741. int completed;
  3742. CURLcode result = ftp_do_more(data, &completed);
  3743. if(result) {
  3744. close_secondarysocket(data);
  3745. return result;
  3746. }
  3747. }
  3748. if(ftp->transfer != PPTRANSFER_BODY)
  3749. /* no data to transfer */
  3750. Curl_xfer_setup_nop(data);
  3751. else if(!connected)
  3752. /* since we did not connect now, we want do_more to get called */
  3753. conn->bits.do_more = TRUE;
  3754. ftpc->ctl_valid = TRUE; /* seems good */
  3755. return CURLE_OK;
  3756. }
  3757. /* called from multi.c while DOing */
  3758. static CURLcode ftp_doing(struct Curl_easy *data,
  3759. bool *dophase_done)
  3760. {
  3761. CURLcode result = ftp_multi_statemach(data, dophase_done);
  3762. if(result)
  3763. CURL_TRC_FTP(data, "[%s] DO phase failed", FTP_DSTATE(data));
  3764. else if(*dophase_done) {
  3765. result = ftp_dophase_done(data, FALSE /* not connected */);
  3766. CURL_TRC_FTP(data, "[%s] DO phase is complete2", FTP_DSTATE(data));
  3767. }
  3768. return result;
  3769. }
  3770. /***********************************************************************
  3771. *
  3772. * ftp_regular_transfer()
  3773. *
  3774. * The input argument is already checked for validity.
  3775. *
  3776. * Performs all commands done before a regular transfer between a local and a
  3777. * remote host.
  3778. *
  3779. * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the
  3780. * ftp_done() function without finding any major problem.
  3781. */
  3782. static
  3783. CURLcode ftp_regular_transfer(struct Curl_easy *data,
  3784. bool *dophase_done)
  3785. {
  3786. CURLcode result = CURLE_OK;
  3787. bool connected = FALSE;
  3788. struct connectdata *conn = data->conn;
  3789. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3790. data->req.size = -1; /* make sure this is unknown at this point */
  3791. Curl_pgrsSetUploadCounter(data, 0);
  3792. Curl_pgrsSetDownloadCounter(data, 0);
  3793. Curl_pgrsSetUploadSize(data, -1);
  3794. Curl_pgrsSetDownloadSize(data, -1);
  3795. ftpc->ctl_valid = TRUE; /* starts good */
  3796. result = ftp_perform(data,
  3797. &connected, /* have we connected after PASV/PORT */
  3798. dophase_done); /* all commands in the DO-phase done? */
  3799. if(!result) {
  3800. if(!*dophase_done)
  3801. /* the DO phase has not completed yet */
  3802. return CURLE_OK;
  3803. result = ftp_dophase_done(data, connected);
  3804. if(result)
  3805. return result;
  3806. }
  3807. else
  3808. freedirs(ftpc);
  3809. return result;
  3810. }
  3811. static CURLcode ftp_setup_connection(struct Curl_easy *data,
  3812. struct connectdata *conn)
  3813. {
  3814. char *type;
  3815. struct FTP *ftp;
  3816. CURLcode result = CURLE_OK;
  3817. struct ftp_conn *ftpc = &conn->proto.ftpc;
  3818. ftp = calloc(1, sizeof(struct FTP));
  3819. if(!ftp)
  3820. return CURLE_OUT_OF_MEMORY;
  3821. /* clone connection related data that is FTP specific */
  3822. if(data->set.str[STRING_FTP_ACCOUNT]) {
  3823. ftpc->account = strdup(data->set.str[STRING_FTP_ACCOUNT]);
  3824. if(!ftpc->account) {
  3825. free(ftp);
  3826. return CURLE_OUT_OF_MEMORY;
  3827. }
  3828. }
  3829. if(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]) {
  3830. ftpc->alternative_to_user =
  3831. strdup(data->set.str[STRING_FTP_ALTERNATIVE_TO_USER]);
  3832. if(!ftpc->alternative_to_user) {
  3833. Curl_safefree(ftpc->account);
  3834. free(ftp);
  3835. return CURLE_OUT_OF_MEMORY;
  3836. }
  3837. }
  3838. data->req.p.ftp = ftp;
  3839. ftp->path = &data->state.up.path[1]; /* do not include the initial slash */
  3840. /* FTP URLs support an extension like ";type=<typecode>" that
  3841. * we will try to get now! */
  3842. type = strstr(ftp->path, ";type=");
  3843. if(!type)
  3844. type = strstr(conn->host.rawalloc, ";type=");
  3845. if(type) {
  3846. char command;
  3847. *type = 0; /* it was in the middle of the hostname */
  3848. command = Curl_raw_toupper(type[6]);
  3849. switch(command) {
  3850. case 'A': /* ASCII mode */
  3851. data->state.prefer_ascii = TRUE;
  3852. break;
  3853. case 'D': /* directory mode */
  3854. data->state.list_only = TRUE;
  3855. break;
  3856. case 'I': /* binary mode */
  3857. default:
  3858. /* switch off ASCII */
  3859. data->state.prefer_ascii = FALSE;
  3860. break;
  3861. }
  3862. }
  3863. /* get some initial data into the ftp struct */
  3864. ftp->transfer = PPTRANSFER_BODY;
  3865. ftp->downloadsize = 0;
  3866. ftpc->known_filesize = -1; /* unknown size for now */
  3867. ftpc->use_ssl = data->set.use_ssl;
  3868. ftpc->ccc = data->set.ftp_ccc;
  3869. CURL_TRC_FTP(data, "[%s] setup connection -> %d", FTP_CSTATE(conn), result);
  3870. return result;
  3871. }
  3872. #endif /* CURL_DISABLE_FTP */