ftp.c 112 KB

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