ftp.c 138 KB

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