ftp.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138
  1. /*****************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2001, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * In order to be useful for every potential user, curl and libcurl are
  11. * dual-licensed under the MPL and the MIT/X-derivate licenses.
  12. *
  13. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  14. * copies of the Software, and permit persons to whom the Software is
  15. * furnished to do so, under the terms of the MPL or the MIT/X-derivate
  16. * licenses. You may pick one of these licenses.
  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. #include <stdio.h>
  25. #include <string.h>
  26. #include <stdlib.h>
  27. #include <stdarg.h>
  28. #include <ctype.h>
  29. #include <errno.h>
  30. #ifdef HAVE_UNISTD_H
  31. #include <unistd.h>
  32. #endif
  33. #ifdef HAVE_SYS_SELECT_H
  34. #include <sys/select.h>
  35. #endif
  36. #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
  37. #include <winsock.h>
  38. #else /* some kind of unix */
  39. #ifdef HAVE_SYS_SOCKET_H
  40. #include <sys/socket.h>
  41. #endif
  42. #include <sys/types.h>
  43. #ifdef HAVE_NETINET_IN_H
  44. #include <netinet/in.h>
  45. #endif
  46. #ifdef HAVE_ARPA_INET_H
  47. #include <arpa/inet.h>
  48. #endif
  49. #include <sys/utsname.h>
  50. #ifdef HAVE_NETDB_H
  51. #include <netdb.h>
  52. #endif
  53. #ifdef VMS
  54. #include <in.h>
  55. #include <inet.h>
  56. #endif
  57. #endif
  58. #if defined(WIN32) && defined(__GNUC__) || defined(__MINGW32__)
  59. #include <errno.h>
  60. #endif
  61. #include <curl/curl.h>
  62. #include "urldata.h"
  63. #include "sendf.h"
  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 KRB4
  72. #include "security.h"
  73. #include "krb4.h"
  74. #endif
  75. #include "strequal.h"
  76. #include "ssluse.h"
  77. #include "connect.h"
  78. #if defined(HAVE_INET_NTOA_R) && !defined(HAVE_INET_NTOA_R_DECL)
  79. #include "inet_ntoa_r.h"
  80. #endif
  81. #define _MPRINTF_REPLACE /* use our functions only */
  82. #include <curl/mprintf.h>
  83. /* The last #include file should be: */
  84. #ifdef MALLOCDEBUG
  85. #include "memdebug.h"
  86. #endif
  87. /* Local API functions */
  88. static CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote);
  89. static CURLcode ftp_cwd(struct connectdata *conn, char *path);
  90. /* easy-to-use macro: */
  91. #define FTPSENDF(x,y,z) if((result = Curl_ftpsendf(x,y,z))) return result
  92. /***********************************************************************
  93. *
  94. * AllowServerConnect()
  95. *
  96. * When we've issue the PORT command, we have told the server to connect
  97. * to us. This function will sit and wait here until the server has
  98. * connected.
  99. *
  100. */
  101. static CURLcode AllowServerConnect(struct SessionHandle *data,
  102. struct connectdata *conn,
  103. int sock)
  104. {
  105. fd_set rdset;
  106. struct timeval dt;
  107. FD_ZERO(&rdset);
  108. FD_SET(sock, &rdset);
  109. /* we give the server 10 seconds to connect to us */
  110. dt.tv_sec = 10;
  111. dt.tv_usec = 0;
  112. switch (select(sock+1, &rdset, NULL, NULL, &dt)) {
  113. case -1: /* error */
  114. /* let's die here */
  115. failf(data, "Error while waiting for server connect");
  116. return CURLE_FTP_PORT_FAILED;
  117. case 0: /* timeout */
  118. /* let's die here */
  119. failf(data, "Timeout while waiting for server connect");
  120. return CURLE_FTP_PORT_FAILED;
  121. default:
  122. /* we have received data here */
  123. {
  124. int s;
  125. size_t size = sizeof(struct sockaddr_in);
  126. struct sockaddr_in add;
  127. getsockname(sock, (struct sockaddr *) &add, (socklen_t *)&size);
  128. s=accept(sock, (struct sockaddr *) &add, (socklen_t *)&size);
  129. sclose(sock); /* close the first socket */
  130. if (-1 == s) {
  131. /* DIE! */
  132. failf(data, "Error accept()ing server connect");
  133. return CURLE_FTP_PORT_FAILED;
  134. }
  135. infof(data, "Connection accepted from server\n");
  136. conn->secondarysocket = s;
  137. }
  138. break;
  139. }
  140. return CURLE_OK;
  141. }
  142. /* --- parse FTP server responses --- */
  143. /*
  144. * Curl_GetFTPResponse() is supposed to be invoked after each command sent to
  145. * a remote FTP server. This function will wait and read all lines of the
  146. * response and extract the relevant return code for the invoking function.
  147. */
  148. int Curl_GetFTPResponse(char *buf,
  149. struct connectdata *conn,
  150. int *ftpcode)
  151. {
  152. /* Brand new implementation.
  153. * We cannot read just one byte per read() and then go back to select()
  154. * as it seems that the OpenSSL read() stuff doesn't grok that properly.
  155. *
  156. * Alas, read as much as possible, split up into lines, use the ending
  157. * line in a response or continue reading. */
  158. int sockfd = conn->firstsocket;
  159. int nread; /* total size read */
  160. int perline; /* count bytes per line */
  161. bool keepon=TRUE;
  162. ssize_t gotbytes;
  163. char *ptr;
  164. int timeout = 3600; /* default timeout in seconds */
  165. struct timeval interval;
  166. fd_set rkeepfd;
  167. fd_set readfd;
  168. struct SessionHandle *data = conn->data;
  169. char *line_start;
  170. int code=0; /* default "error code" to return */
  171. #define SELECT_OK 0
  172. #define SELECT_ERROR 1 /* select() problems */
  173. #define SELECT_TIMEOUT 2 /* took too long */
  174. #define SELECT_MEMORY 3 /* no available memory */
  175. #define SELECT_CALLBACK 4 /* aborted by callback */
  176. int error = SELECT_OK;
  177. struct FTP *ftp = conn->proto.ftp;
  178. if (ftpcode)
  179. *ftpcode = 0; /* 0 for errors */
  180. if(data->set.timeout) {
  181. /* if timeout is requested, find out how much remaining time we have */
  182. timeout = data->set.timeout - /* timeout time */
  183. Curl_tvdiff(Curl_tvnow(), conn->now)/1000; /* spent time */
  184. if(timeout <=0 ) {
  185. failf(data, "Transfer aborted due to timeout");
  186. return -SELECT_TIMEOUT; /* already too little time */
  187. }
  188. }
  189. FD_ZERO (&readfd); /* clear it */
  190. FD_SET (sockfd, &readfd); /* read socket */
  191. /* get this in a backup variable to be able to restore it on each lap in the
  192. select() loop */
  193. rkeepfd = readfd;
  194. ptr=buf;
  195. line_start = buf;
  196. nread=0;
  197. perline=0;
  198. keepon=TRUE;
  199. while((nread<BUFSIZE) && (keepon && !error)) {
  200. readfd = rkeepfd; /* set every lap */
  201. interval.tv_sec = timeout;
  202. interval.tv_usec = 0;
  203. if(!ftp->cache)
  204. switch (select (sockfd+1, &readfd, NULL, NULL, &interval)) {
  205. case -1: /* select() error, stop reading */
  206. error = SELECT_ERROR;
  207. failf(data, "Transfer aborted due to select() error");
  208. break;
  209. case 0: /* timeout */
  210. error = SELECT_TIMEOUT;
  211. failf(data, "Transfer aborted due to timeout");
  212. break;
  213. default:
  214. error = SELECT_OK;
  215. break;
  216. }
  217. if(SELECT_OK == error) {
  218. /*
  219. * This code previously didn't use the kerberos sec_read() code
  220. * to read, but when we use Curl_read() it may do so. Do confirm
  221. * that this is still ok and then remove this comment!
  222. */
  223. if(ftp->cache) {
  224. /* we had data in the "cache", copy that instead of doing an actual
  225. read */
  226. memcpy(ptr, ftp->cache, ftp->cache_size);
  227. gotbytes = ftp->cache_size;
  228. free(ftp->cache); /* free the cache */
  229. ftp->cache = NULL; /* clear the pointer */
  230. ftp->cache_size = 0; /* zero the size just in case */
  231. }
  232. else {
  233. int res = Curl_read(conn, sockfd, ptr,
  234. BUFSIZE-nread, &gotbytes);
  235. if(res < 0)
  236. /* EWOULDBLOCK */
  237. continue; /* go looping again */
  238. if(CURLE_OK != res)
  239. keepon = FALSE;
  240. }
  241. if(!keepon)
  242. ;
  243. else if(gotbytes <= 0) {
  244. keepon = FALSE;
  245. error = SELECT_ERROR;
  246. failf(data, "Connection aborted");
  247. }
  248. else {
  249. /* we got a whole chunk of data, which can be anything from one
  250. * byte to a set of lines and possible just a piece of the last
  251. * line */
  252. int i;
  253. nread += gotbytes;
  254. for(i = 0; i < gotbytes; ptr++, i++) {
  255. perline++;
  256. if(*ptr=='\n') {
  257. /* a newline is CRLF in ftp-talk, so the CR is ignored as
  258. the line isn't really terminated until the LF comes */
  259. CURLcode result;
  260. /* output debug output if that is requested */
  261. if(data->set.verbose) {
  262. fputs("< ", data->set.err);
  263. fwrite(line_start, perline, 1, data->set.err);
  264. /* no need to output LF here, it is part of the data */
  265. }
  266. /*
  267. * We pass all response-lines to the callback function registered
  268. * for "headers". The response lines can be seen as a kind of
  269. * headers.
  270. */
  271. result = Curl_client_write(data, CLIENTWRITE_HEADER,
  272. line_start, perline);
  273. if(result)
  274. return -SELECT_CALLBACK;
  275. #define lastline(line) (isdigit((int)line[0]) && isdigit((int)line[1]) && \
  276. isdigit((int)line[2]) && (' ' == line[3]))
  277. if(perline>3 && lastline(line_start)) {
  278. /* This is the end of the last line, copy the last
  279. * line to the start of the buffer and zero terminate,
  280. * for old times sake (and krb4)! */
  281. char *meow;
  282. int n;
  283. for(meow=line_start, n=0; meow<ptr; meow++, n++)
  284. buf[n] = *meow;
  285. *meow=0; /* zero terminate */
  286. keepon=FALSE;
  287. line_start = ptr+1; /* advance pointer */
  288. i++; /* skip this before getting out */
  289. break;
  290. }
  291. perline=0; /* line starts over here */
  292. line_start = ptr+1;
  293. }
  294. }
  295. if(!keepon && (i != gotbytes)) {
  296. /* We found the end of the response lines, but we didn't parse the
  297. full chunk of data we have read from the server. We therefore
  298. need to store the rest of the data to be checked on the next
  299. invoke as it may actually contain another end of response
  300. already! Cleverly figured out by Eric Lavigne in December
  301. 2001. */
  302. ftp->cache_size = gotbytes - i;
  303. ftp->cache = (char *)malloc(ftp->cache_size);
  304. if(ftp->cache)
  305. memcpy(ftp->cache, line_start, ftp->cache_size);
  306. else
  307. return -SELECT_MEMORY; /**BANG**/
  308. }
  309. } /* there was data */
  310. } /* if(no error) */
  311. } /* while there's buffer left and loop is requested */
  312. if(!error)
  313. code = atoi(buf);
  314. #ifdef KRB4
  315. /* handle the security-oriented responses 6xx ***/
  316. /* FIXME: some errorchecking perhaps... ***/
  317. switch(code) {
  318. case 631:
  319. Curl_sec_read_msg(conn, buf, prot_safe);
  320. break;
  321. case 632:
  322. Curl_sec_read_msg(conn, buf, prot_private);
  323. break;
  324. case 633:
  325. Curl_sec_read_msg(conn, buf, prot_confidential);
  326. break;
  327. default:
  328. /* normal ftp stuff we pass through! */
  329. break;
  330. }
  331. #endif
  332. if(error)
  333. return -error;
  334. if(ftpcode)
  335. *ftpcode=code; /* return the initial number like this */
  336. return nread; /* total amount of bytes read */
  337. }
  338. #ifndef ENABLE_IPV6
  339. /*
  340. * This function is only used by code that works on IPv4. When we add proper
  341. * support for that functionality with IPv6, this function can go in again.
  342. */
  343. /* -- who are we? -- */
  344. static char *getmyhost(char *buf, int buf_size)
  345. {
  346. #if defined(HAVE_GETHOSTNAME)
  347. gethostname(buf, buf_size);
  348. #elif defined(HAVE_UNAME)
  349. struct utsname ugnm;
  350. strncpy(buf, uname(&ugnm) < 0 ? "localhost" : ugnm.nodename, buf_size - 1);
  351. buf[buf_size - 1] = '\0';
  352. #else
  353. /* We have no means of finding the local host name! */
  354. strncpy(buf, "localhost", buf_size);
  355. buf[buf_size - 1] = '\0';
  356. #endif
  357. return buf;
  358. }
  359. #endif /* ipv4-only function */
  360. /* ftp_connect() should do everything that is to be considered a part
  361. of the connection phase. */
  362. CURLcode Curl_ftp_connect(struct connectdata *conn)
  363. {
  364. /* this is FTP and no proxy */
  365. int nread;
  366. struct SessionHandle *data=conn->data;
  367. char *buf = data->state.buffer; /* this is our buffer */
  368. struct FTP *ftp;
  369. CURLcode result;
  370. int ftpcode;
  371. ftp = (struct FTP *)malloc(sizeof(struct FTP));
  372. if(!ftp)
  373. return CURLE_OUT_OF_MEMORY;
  374. memset(ftp, 0, sizeof(struct FTP));
  375. conn->proto.ftp = ftp;
  376. /* We always support persistant connections on ftp */
  377. conn->bits.close = FALSE;
  378. /* get some initial data into the ftp struct */
  379. ftp->bytecountp = &conn->bytecount;
  380. /* no need to duplicate them, the data struct won't change */
  381. ftp->user = data->state.user;
  382. ftp->passwd = data->state.passwd;
  383. if (data->set.tunnel_thru_httpproxy) {
  384. /* We want "seamless" FTP operations through HTTP proxy tunnel */
  385. result = Curl_ConnectHTTPProxyTunnel(conn, conn->firstsocket,
  386. conn->hostname, conn->remote_port);
  387. if(CURLE_OK != result)
  388. return result;
  389. }
  390. if(conn->protocol & PROT_FTPS) {
  391. /* FTPS is simply ftp with SSL for the control channel */
  392. /* now, perform the SSL initialization for this socket */
  393. result = Curl_SSLConnect(conn);
  394. if(result)
  395. return result;
  396. }
  397. /* The first thing we do is wait for the "220*" line: */
  398. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  399. if(nread < 0)
  400. return CURLE_OPERATION_TIMEOUTED;
  401. if(ftpcode != 220) {
  402. failf(data, "This doesn't seem like a nice ftp-server response");
  403. return CURLE_FTP_WEIRD_SERVER_REPLY;
  404. }
  405. #ifdef KRB4
  406. /* if not anonymous login, try a secure login */
  407. if(data->set.krb4) {
  408. /* request data protection level (default is 'clear') */
  409. Curl_sec_request_prot(conn, "private");
  410. /* We set private first as default, in case the line below fails to
  411. set a valid level */
  412. Curl_sec_request_prot(conn, data->set.krb4_level);
  413. if(Curl_sec_login(conn) != 0)
  414. infof(data, "Logging in with password in cleartext!\n");
  415. else
  416. infof(data, "Authentication successful\n");
  417. }
  418. #endif
  419. /* send USER */
  420. FTPSENDF(conn, "USER %s", ftp->user);
  421. /* wait for feedback */
  422. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  423. if(nread < 0)
  424. return CURLE_OPERATION_TIMEOUTED;
  425. if(ftpcode == 530) {
  426. /* 530 User ... access denied
  427. (the server denies to log the specified user) */
  428. failf(data, "Access denied: %s", &buf[4]);
  429. return CURLE_FTP_ACCESS_DENIED;
  430. }
  431. else if(ftpcode == 331) {
  432. /* 331 Password required for ...
  433. (the server requires to send the user's password too) */
  434. FTPSENDF(conn, "PASS %s", ftp->passwd);
  435. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  436. if(nread < 0)
  437. return CURLE_OPERATION_TIMEOUTED;
  438. if(ftpcode == 530) {
  439. /* 530 Login incorrect.
  440. (the username and/or the password are incorrect) */
  441. failf(data, "the username and/or the password are incorrect");
  442. return CURLE_FTP_USER_PASSWORD_INCORRECT;
  443. }
  444. else if(ftpcode == 230) {
  445. /* 230 User ... logged in.
  446. (user successfully logged in) */
  447. infof(data, "We have successfully logged in\n");
  448. }
  449. else {
  450. failf(data, "Odd return code after PASS");
  451. return CURLE_FTP_WEIRD_PASS_REPLY;
  452. }
  453. }
  454. else if(buf[0] == '2') {
  455. /* 230 User ... logged in.
  456. (the user logged in without password) */
  457. infof(data, "We have successfully logged in\n");
  458. #ifdef KRB4
  459. /* we are logged in (with Kerberos)
  460. * now set the requested protection level
  461. */
  462. if(conn->sec_complete)
  463. Curl_sec_set_protection_level(conn);
  464. /* we may need to issue a KAUTH here to have access to the files
  465. * do it if user supplied a password
  466. */
  467. if(data->state.passwd && *data->state.passwd)
  468. Curl_krb_kauth(conn);
  469. #endif
  470. }
  471. else {
  472. failf(data, "Odd return code after USER");
  473. return CURLE_FTP_WEIRD_USER_REPLY;
  474. }
  475. /* send PWD to discover our entry point */
  476. FTPSENDF(conn, "PWD", NULL);
  477. /* wait for feedback */
  478. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  479. if(nread < 0)
  480. return CURLE_OPERATION_TIMEOUTED;
  481. if(ftpcode == 257) {
  482. char *dir = (char *)malloc(nread+1);
  483. char *store=dir;
  484. char *ptr=&buf[4]; /* start on the first letter */
  485. /* Reply format is like
  486. 257<space>"<directory-name>"<space><commentary> and the RFC959 says
  487. The directory name can contain any character; embedded double-quotes
  488. should be escaped by double-quotes (the "quote-doubling" convention).
  489. */
  490. if('\"' == *ptr) {
  491. /* it started good */
  492. ptr++;
  493. while(ptr && *ptr) {
  494. if('\"' == *ptr) {
  495. if('\"' == ptr[1]) {
  496. /* "quote-doubling" */
  497. *store = ptr[1];
  498. ptr++;
  499. }
  500. else {
  501. /* end of path */
  502. *store = '\0'; /* zero terminate */
  503. break; /* get out of this loop */
  504. }
  505. }
  506. else
  507. *store = *ptr;
  508. store++;
  509. ptr++;
  510. }
  511. ftp->entrypath =dir; /* remember this */
  512. infof(data, "Entry path is '%s'\n", ftp->entrypath);
  513. }
  514. else {
  515. /* couldn't get the path */
  516. }
  517. }
  518. else {
  519. /* We couldn't read the PWD response! */
  520. }
  521. return CURLE_OK;
  522. }
  523. /***********************************************************************
  524. *
  525. * Curl_ftp_done()
  526. *
  527. * The DONE function. This does what needs to be done after a single DO has
  528. * performed.
  529. *
  530. * Input argument is already checked for validity.
  531. */
  532. CURLcode Curl_ftp_done(struct connectdata *conn)
  533. {
  534. struct SessionHandle *data = conn->data;
  535. struct FTP *ftp = conn->proto.ftp;
  536. ssize_t nread;
  537. char *buf = data->state.buffer; /* this is our buffer */
  538. int ftpcode;
  539. CURLcode result=CURLE_OK;
  540. if(data->set.upload) {
  541. if((-1 != data->set.infilesize) && (data->set.infilesize != *ftp->bytecountp)) {
  542. failf(data, "Wrote only partial file (%d out of %d bytes)",
  543. *ftp->bytecountp, data->set.infilesize);
  544. return CURLE_PARTIAL_FILE;
  545. }
  546. }
  547. else {
  548. if((-1 != conn->size) && (conn->size != *ftp->bytecountp) &&
  549. (conn->maxdownload != *ftp->bytecountp)) {
  550. failf(data, "Received only partial file: %d bytes", *ftp->bytecountp);
  551. return CURLE_PARTIAL_FILE;
  552. }
  553. else if(!conn->bits.resume_done &&
  554. !data->set.no_body &&
  555. (0 == *ftp->bytecountp)) {
  556. /* We consider this an error, but there's no true FTP error received
  557. why we need to continue to "read out" the server response too.
  558. We don't want to leave a "waiting" server reply if we'll get told
  559. to make a second request on this same connection! */
  560. failf(data, "No data was received!");
  561. result = CURLE_FTP_COULDNT_RETR_FILE;
  562. }
  563. }
  564. #ifdef KRB4
  565. Curl_sec_fflush_fd(conn, conn->secondarysocket);
  566. #endif
  567. /* shut down the socket to inform the server we're done */
  568. sclose(conn->secondarysocket);
  569. conn->secondarysocket = -1;
  570. if(!data->set.no_body && !conn->bits.resume_done) {
  571. /* now let's see what the server says about the transfer we
  572. just performed: */
  573. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  574. if(nread < 0)
  575. return CURLE_OPERATION_TIMEOUTED;
  576. /* 226 Transfer complete, 250 Requested file action okay, completed. */
  577. if((ftpcode != 226) && (ftpcode != 250)) {
  578. failf(data, "server did not report OK, got %d", ftpcode);
  579. return CURLE_FTP_WRITE_ERROR;
  580. }
  581. }
  582. conn->bits.resume_done = FALSE; /* clean this for next connection */
  583. /* Send any post-transfer QUOTE strings? */
  584. if(!result && data->set.postquote)
  585. result = ftp_sendquote(conn, data->set.postquote);
  586. return result;
  587. }
  588. /***********************************************************************
  589. *
  590. * ftp_sendquote()
  591. *
  592. * Where a 'quote' means a list of custom commands to send to the server.
  593. * The quote list is passed as an argument.
  594. */
  595. static
  596. CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote)
  597. {
  598. struct curl_slist *item;
  599. ssize_t nread;
  600. int ftpcode;
  601. CURLcode result;
  602. item = quote;
  603. while (item) {
  604. if (item->data) {
  605. FTPSENDF(conn, "%s", item->data);
  606. nread = Curl_GetFTPResponse(conn->data->state.buffer, conn, &ftpcode);
  607. if (nread < 0)
  608. return CURLE_OPERATION_TIMEOUTED;
  609. if (ftpcode >= 400) {
  610. failf(conn->data, "QUOT string not accepted: %s", item->data);
  611. return CURLE_FTP_QUOTE_ERROR;
  612. }
  613. }
  614. item = item->next;
  615. }
  616. return CURLE_OK;
  617. }
  618. /***********************************************************************
  619. *
  620. * ftp_cwd()
  621. *
  622. * Send 'CWD' to the remote server to Change Working Directory.
  623. * It is the ftp version of the unix 'cd' command.
  624. */
  625. static
  626. CURLcode ftp_cwd(struct connectdata *conn, char *path)
  627. {
  628. ssize_t nread;
  629. int ftpcode;
  630. CURLcode result;
  631. FTPSENDF(conn, "CWD %s", path);
  632. nread = Curl_GetFTPResponse(
  633. conn->data->state.buffer, conn, &ftpcode);
  634. if (nread < 0)
  635. return CURLE_OPERATION_TIMEOUTED;
  636. if (ftpcode != 250) {
  637. failf(conn->data, "Couldn't cd to %s", path);
  638. return CURLE_FTP_ACCESS_DENIED;
  639. }
  640. return CURLE_OK;
  641. }
  642. /***********************************************************************
  643. *
  644. * ftp_getfiletime()
  645. *
  646. * Get the timestamp of the given file.
  647. */
  648. static
  649. CURLcode ftp_getfiletime(struct connectdata *conn, char *file)
  650. {
  651. CURLcode result=CURLE_OK;
  652. int ftpcode; /* for ftp status */
  653. ssize_t nread;
  654. char *buf = conn->data->state.buffer;
  655. /* we have requested to get the modified-time of the file, this is yet
  656. again a grey area as the MDTM is not kosher RFC959 */
  657. FTPSENDF(conn, "MDTM %s", file);
  658. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  659. if(nread < 0)
  660. return CURLE_OPERATION_TIMEOUTED;
  661. if(ftpcode == 213) {
  662. /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the
  663. last .sss part is optional and means fractions of a second */
  664. int year, month, day, hour, minute, second;
  665. if(6 == sscanf(buf+4, "%04d%02d%02d%02d%02d%02d",
  666. &year, &month, &day, &hour, &minute, &second)) {
  667. /* we have a time, reformat it */
  668. time_t secs=time(NULL);
  669. sprintf(buf, "%04d%02d%02d %02d:%02d:%02d",
  670. year, month, day, hour, minute, second);
  671. /* now, convert this into a time() value: */
  672. conn->data->info.filetime = curl_getdate(buf, &secs);
  673. }
  674. else {
  675. infof(conn->data, "unsupported MDTM reply format\n");
  676. }
  677. }
  678. return result;
  679. }
  680. /***********************************************************************
  681. *
  682. * ftp_transfertype()
  683. *
  684. * Set transfer type. We only deal with ASCII or BINARY so this function
  685. * sets one of them.
  686. */
  687. static CURLcode ftp_transfertype(struct connectdata *conn,
  688. bool ascii)
  689. {
  690. struct SessionHandle *data = conn->data;
  691. int ftpcode;
  692. ssize_t nread;
  693. char *buf=data->state.buffer;
  694. CURLcode result;
  695. FTPSENDF(conn, "TYPE %s", ascii?"A":"I");
  696. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  697. if(nread < 0)
  698. return CURLE_OPERATION_TIMEOUTED;
  699. if(ftpcode != 200) {
  700. failf(data, "Couldn't set %s mode",
  701. ascii?"ASCII":"binary");
  702. return ascii? CURLE_FTP_COULDNT_SET_ASCII:CURLE_FTP_COULDNT_SET_BINARY;
  703. }
  704. return CURLE_OK;
  705. }
  706. /***********************************************************************
  707. *
  708. * ftp_getsize()
  709. *
  710. * Returns the file size (in bytes) of the given remote file.
  711. */
  712. static
  713. CURLcode ftp_getsize(struct connectdata *conn, char *file,
  714. ssize_t *size)
  715. {
  716. struct SessionHandle *data = conn->data;
  717. int ftpcode;
  718. ssize_t nread;
  719. char *buf=data->state.buffer;
  720. CURLcode result;
  721. FTPSENDF(conn, "SIZE %s", file);
  722. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  723. if(nread < 0)
  724. return CURLE_OPERATION_TIMEOUTED;
  725. if(ftpcode == 213) {
  726. /* get the size from the ascii string: */
  727. *size = atoi(buf+4);
  728. }
  729. else
  730. return CURLE_FTP_COULDNT_GET_SIZE;
  731. return CURLE_OK;
  732. }
  733. /***************************************************************************
  734. *
  735. * ftp_pasv_verbose()
  736. *
  737. * This function only outputs some informationals about this second connection
  738. * when we've issued a PASV command before and thus we have connected to a
  739. * possibly new IP address.
  740. *
  741. */
  742. static void
  743. ftp_pasv_verbose(struct connectdata *conn,
  744. Curl_ipconnect *addr,
  745. char *newhost, /* ascii version */
  746. int port)
  747. {
  748. #ifndef ENABLE_IPV6
  749. /*****************************************************************
  750. *
  751. * IPv4-only code section
  752. */
  753. struct in_addr in;
  754. struct hostent * answer;
  755. #ifdef HAVE_INET_NTOA_R
  756. char ntoa_buf[64];
  757. #endif
  758. /* The array size trick below is to make this a large chunk of memory
  759. suitably 8-byte aligned on 64-bit platforms. This was thoughtfully
  760. suggested by Philip Gladstone. */
  761. long bigbuf[9000 / sizeof(long)];
  762. #if defined(HAVE_INET_ADDR)
  763. in_addr_t address;
  764. # if defined(HAVE_GETHOSTBYADDR_R)
  765. int h_errnop;
  766. # endif
  767. char *hostent_buf = (char *)bigbuf; /* get a char * to the buffer */
  768. address = inet_addr(newhost);
  769. # ifdef HAVE_GETHOSTBYADDR_R
  770. # ifdef HAVE_GETHOSTBYADDR_R_5
  771. /* AIX, Digital Unix (OSF1, Tru64) style:
  772. extern int gethostbyaddr_r(char *addr, size_t len, int type,
  773. struct hostent *htent, struct hostent_data *ht_data); */
  774. /* Fred Noz helped me try this out, now it at least compiles! */
  775. /* Bjorn Reese (November 28 2001):
  776. The Tru64 man page on gethostbyaddr_r() says that
  777. the hostent struct must be filled with zeroes before the call to
  778. gethostbyaddr_r(). */
  779. memset(hostent_buf, 0, sizeof(struct hostent));
  780. if(gethostbyaddr_r((char *) &address,
  781. sizeof(address), AF_INET,
  782. (struct hostent *)hostent_buf,
  783. hostent_buf + sizeof(*answer)))
  784. answer=NULL;
  785. # endif
  786. # ifdef HAVE_GETHOSTBYADDR_R_7
  787. /* Solaris and IRIX */
  788. answer = gethostbyaddr_r((char *) &address, sizeof(address), AF_INET,
  789. (struct hostent *)bigbuf,
  790. hostent_buf + sizeof(*answer),
  791. sizeof(hostent_buf) - sizeof(*answer),
  792. &h_errnop);
  793. # endif
  794. # ifdef HAVE_GETHOSTBYADDR_R_8
  795. /* Linux style */
  796. if(gethostbyaddr_r((char *) &address, sizeof(address), AF_INET,
  797. (struct hostent *)hostent_buf,
  798. hostent_buf + sizeof(*answer),
  799. sizeof(hostent_buf) - sizeof(*answer),
  800. &answer,
  801. &h_errnop))
  802. answer=NULL; /* error */
  803. # endif
  804. # else
  805. answer = gethostbyaddr((char *) &address, sizeof(address), AF_INET);
  806. # endif
  807. #else
  808. answer = NULL;
  809. #endif
  810. (void) memcpy(&in.s_addr, addr, sizeof (Curl_ipconnect));
  811. infof(conn->data, "Connecting to %s (%s) port %u\n",
  812. answer?answer->h_name:newhost,
  813. #if defined(HAVE_INET_NTOA_R)
  814. inet_ntoa_r(in, ntoa_buf, sizeof(ntoa_buf)),
  815. #else
  816. inet_ntoa(in),
  817. #endif
  818. port);
  819. #else
  820. /*****************************************************************
  821. *
  822. * IPv6-only code section
  823. */
  824. char hbuf[NI_MAXHOST]; /* ~1KB */
  825. char nbuf[NI_MAXHOST]; /* ~1KB */
  826. char sbuf[NI_MAXSERV]; /* around 32 */
  827. #ifdef NI_WITHSCOPEID
  828. const int niflags = NI_NUMERICHOST | NI_NUMERICSERV | NI_WITHSCOPEID;
  829. #else
  830. const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
  831. #endif
  832. port = 0; /* unused, prevent warning */
  833. if (getnameinfo(addr->ai_addr, addr->ai_addrlen,
  834. nbuf, sizeof(nbuf), sbuf, sizeof(sbuf), niflags)) {
  835. snprintf(nbuf, sizeof(nbuf), "?");
  836. snprintf(sbuf, sizeof(sbuf), "?");
  837. }
  838. if (getnameinfo(addr->ai_addr, addr->ai_addrlen,
  839. hbuf, sizeof(hbuf), NULL, 0, 0)) {
  840. infof(conn->data, "Connecting to %s (%s) port %s\n", nbuf, newhost, sbuf);
  841. }
  842. else {
  843. infof(conn->data, "Connecting to %s (%s) port %s\n", hbuf, nbuf, sbuf);
  844. }
  845. #endif
  846. }
  847. /***********************************************************************
  848. *
  849. * ftp_use_port()
  850. *
  851. * Send the proper PORT command. PORT is the ftp client's way of telling the
  852. * server that *WE* open a port that we listen on an awaits the server to
  853. * connect to. This is the opposite of PASV.
  854. */
  855. static
  856. CURLcode ftp_use_port(struct connectdata *conn)
  857. {
  858. struct SessionHandle *data=conn->data;
  859. int portsock=-1;
  860. ssize_t nread;
  861. char *buf = data->state.buffer; /* this is our buffer */
  862. int ftpcode; /* receive FTP response codes in this */
  863. CURLcode result;
  864. #ifdef ENABLE_IPV6
  865. /******************************************************************
  866. *
  867. * Here's a piece of IPv6-specific code coming up
  868. *
  869. */
  870. struct addrinfo hints, *res, *ai;
  871. struct sockaddr_storage ss;
  872. socklen_t sslen;
  873. char hbuf[NI_MAXHOST];
  874. struct sockaddr *sa=(struct sockaddr *)&ss;
  875. #ifdef NI_WITHSCOPEID
  876. const int niflags = NI_NUMERICHOST | NI_NUMERICSERV | NI_WITHSCOPEID;
  877. #else
  878. const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
  879. #endif
  880. unsigned char *ap;
  881. unsigned char *pp;
  882. int alen, plen;
  883. char portmsgbuf[4096], tmp[4096];
  884. const char *mode[] = { "EPRT", "LPRT", "PORT", NULL };
  885. char **modep;
  886. /*
  887. * we should use Curl_if2ip? given pickiness of recent ftpd,
  888. * I believe we should use the same address as the control connection.
  889. */
  890. sslen = sizeof(ss);
  891. if (getsockname(conn->firstsocket, (struct sockaddr *)&ss, &sslen) < 0)
  892. return CURLE_FTP_PORT_FAILED;
  893. if (getnameinfo((struct sockaddr *)&ss, sslen, hbuf, sizeof(hbuf), NULL, 0,
  894. niflags))
  895. return CURLE_FTP_PORT_FAILED;
  896. memset(&hints, 0, sizeof(hints));
  897. hints.ai_family = sa->sa_family;
  898. /*hints.ai_family = ss.ss_family;
  899. this way can be used if sockaddr_storage is properly defined, as glibc
  900. 2.1.X doesn't do*/
  901. hints.ai_socktype = SOCK_STREAM;
  902. hints.ai_flags = AI_PASSIVE;
  903. if (getaddrinfo(hbuf, (char *)"0", &hints, &res))
  904. return CURLE_FTP_PORT_FAILED;
  905. portsock = -1;
  906. for (ai = res; ai; ai = ai->ai_next) {
  907. portsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  908. if (portsock < 0)
  909. continue;
  910. if (bind(portsock, ai->ai_addr, ai->ai_addrlen) < 0) {
  911. sclose(portsock);
  912. portsock = -1;
  913. continue;
  914. }
  915. if (listen(portsock, 1) < 0) {
  916. sclose(portsock);
  917. portsock = -1;
  918. continue;
  919. }
  920. break;
  921. }
  922. freeaddrinfo(res);
  923. if (portsock < 0) {
  924. failf(data, strerror(errno));
  925. return CURLE_FTP_PORT_FAILED;
  926. }
  927. sslen = sizeof(ss);
  928. if (getsockname(portsock, sa, &sslen) < 0) {
  929. failf(data, strerror(errno));
  930. return CURLE_FTP_PORT_FAILED;
  931. }
  932. for (modep = (char **)mode; modep && *modep; modep++) {
  933. int lprtaf, eprtaf;
  934. switch (sa->sa_family) {
  935. case AF_INET:
  936. ap = (unsigned char *)&((struct sockaddr_in *)&ss)->sin_addr;
  937. alen = sizeof(((struct sockaddr_in *)&ss)->sin_addr);
  938. pp = (unsigned char *)&((struct sockaddr_in *)&ss)->sin_port;
  939. plen = sizeof(((struct sockaddr_in *)&ss)->sin_port);
  940. lprtaf = 4;
  941. eprtaf = 1;
  942. break;
  943. case AF_INET6:
  944. ap = (unsigned char *)&((struct sockaddr_in6 *)&ss)->sin6_addr;
  945. alen = sizeof(((struct sockaddr_in6 *)&ss)->sin6_addr);
  946. pp = (unsigned char *)&((struct sockaddr_in6 *)&ss)->sin6_port;
  947. plen = sizeof(((struct sockaddr_in6 *)&ss)->sin6_port);
  948. lprtaf = 6;
  949. eprtaf = 2;
  950. break;
  951. default:
  952. ap = pp = NULL;
  953. lprtaf = eprtaf = -1;
  954. break;
  955. }
  956. if (strcmp(*modep, "EPRT") == 0) {
  957. if (eprtaf < 0)
  958. continue;
  959. if (getnameinfo((struct sockaddr *)&ss, sslen,
  960. portmsgbuf, sizeof(portmsgbuf), tmp, sizeof(tmp), niflags))
  961. continue;
  962. /* do not transmit IPv6 scope identifier to the wire */
  963. if (sa->sa_family == AF_INET6) {
  964. char *q = strchr(portmsgbuf, '%');
  965. if (q)
  966. *q = '\0';
  967. }
  968. result = Curl_ftpsendf(conn, "%s |%d|%s|%s|", *modep, eprtaf,
  969. portmsgbuf, tmp);
  970. if(result)
  971. return result;
  972. } else if (strcmp(*modep, "LPRT") == 0 ||
  973. strcmp(*modep, "PORT") == 0) {
  974. int i;
  975. if (strcmp(*modep, "LPRT") == 0 && lprtaf < 0)
  976. continue;
  977. if (strcmp(*modep, "PORT") == 0 && sa->sa_family != AF_INET)
  978. continue;
  979. portmsgbuf[0] = '\0';
  980. if (strcmp(*modep, "LPRT") == 0) {
  981. snprintf(tmp, sizeof(tmp), "%d,%d", lprtaf, alen);
  982. if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >=
  983. sizeof(portmsgbuf)) {
  984. continue;
  985. }
  986. }
  987. for (i = 0; i < alen; i++) {
  988. if (portmsgbuf[0])
  989. snprintf(tmp, sizeof(tmp), ",%u", ap[i]);
  990. else
  991. snprintf(tmp, sizeof(tmp), "%u", ap[i]);
  992. if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >=
  993. sizeof(portmsgbuf)) {
  994. continue;
  995. }
  996. }
  997. if (strcmp(*modep, "LPRT") == 0) {
  998. snprintf(tmp, sizeof(tmp), ",%d", plen);
  999. if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >= sizeof(portmsgbuf))
  1000. continue;
  1001. }
  1002. for (i = 0; i < plen; i++) {
  1003. snprintf(tmp, sizeof(tmp), ",%u", pp[i]);
  1004. if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >=
  1005. sizeof(portmsgbuf)) {
  1006. continue;
  1007. }
  1008. }
  1009. result = Curl_ftpsendf(conn, "%s %s", *modep, portmsgbuf);
  1010. if(result)
  1011. return result;
  1012. }
  1013. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  1014. if(nread < 0)
  1015. return CURLE_OPERATION_TIMEOUTED;
  1016. if (ftpcode != 200) {
  1017. failf(data, "Server does not grok %s", *modep);
  1018. continue;
  1019. }
  1020. else
  1021. break;
  1022. }
  1023. if (!*modep) {
  1024. sclose(portsock);
  1025. return CURLE_FTP_PORT_FAILED;
  1026. }
  1027. /* we set the secondary socket variable to this for now, it
  1028. is only so that the cleanup function will close it in case
  1029. we fail before the true secondary stuff is made */
  1030. conn->secondarysocket = portsock;
  1031. #else
  1032. /******************************************************************
  1033. *
  1034. * Here's a piece of IPv4-specific code coming up
  1035. *
  1036. */
  1037. struct sockaddr_in sa;
  1038. struct hostent *h=NULL;
  1039. char *hostdataptr=NULL;
  1040. unsigned short porttouse;
  1041. char myhost[256] = "";
  1042. if(data->set.ftpport) {
  1043. if(Curl_if2ip(data->set.ftpport, myhost, sizeof(myhost))) {
  1044. h = Curl_resolv(data, myhost, 0, &hostdataptr);
  1045. }
  1046. else {
  1047. int len = strlen(data->set.ftpport);
  1048. if(len>1)
  1049. h = Curl_resolv(data, data->set.ftpport, 0, &hostdataptr);
  1050. if(h)
  1051. strcpy(myhost, data->set.ftpport); /* buffer overflow risk */
  1052. }
  1053. }
  1054. if(! *myhost) {
  1055. char *tmp_host = getmyhost(myhost, sizeof(myhost));
  1056. h=Curl_resolv(data, tmp_host, 0, &hostdataptr);
  1057. }
  1058. infof(data, "We connect from %s\n", myhost);
  1059. if ( h ) {
  1060. if( (portsock = socket(AF_INET, SOCK_STREAM, 0)) >= 0 ) {
  1061. int size;
  1062. /* we set the secondary socket variable to this for now, it
  1063. is only so that the cleanup function will close it in case
  1064. we fail before the true secondary stuff is made */
  1065. conn->secondarysocket = portsock;
  1066. memset((char *)&sa, 0, sizeof(sa));
  1067. memcpy((char *)&sa.sin_addr,
  1068. h->h_addr,
  1069. h->h_length);
  1070. sa.sin_family = AF_INET;
  1071. sa.sin_addr.s_addr = INADDR_ANY;
  1072. sa.sin_port = 0;
  1073. size = sizeof(sa);
  1074. if(bind(portsock, (struct sockaddr *)&sa, size) >= 0) {
  1075. /* we succeeded to bind */
  1076. struct sockaddr_in add;
  1077. socklen_t socksize = sizeof(add);
  1078. if(getsockname(portsock, (struct sockaddr *) &add,
  1079. &socksize)<0) {
  1080. failf(data, "getsockname() failed");
  1081. return CURLE_FTP_PORT_FAILED;
  1082. }
  1083. porttouse = ntohs(add.sin_port);
  1084. if ( listen(portsock, 1) < 0 ) {
  1085. failf(data, "listen(2) failed on socket");
  1086. free(hostdataptr);
  1087. return CURLE_FTP_PORT_FAILED;
  1088. }
  1089. }
  1090. else {
  1091. failf(data, "bind(2) failed on socket");
  1092. free(hostdataptr);
  1093. return CURLE_FTP_PORT_FAILED;
  1094. }
  1095. }
  1096. else {
  1097. failf(data, "socket(2) failed (%s)");
  1098. free(hostdataptr);
  1099. return CURLE_FTP_PORT_FAILED;
  1100. }
  1101. }
  1102. else {
  1103. failf(data, "could't find my own IP address (%s)", myhost);
  1104. return CURLE_FTP_PORT_FAILED;
  1105. }
  1106. {
  1107. #ifdef HAVE_INET_NTOA_R
  1108. char ntoa_buf[64];
  1109. #endif
  1110. struct in_addr in;
  1111. unsigned short ip[5];
  1112. (void) memcpy(&in.s_addr, *h->h_addr_list, sizeof (in.s_addr));
  1113. #ifdef HAVE_INET_NTOA_R
  1114. /* ignore the return code from inet_ntoa_r() as it is int or
  1115. char * depending on system */
  1116. inet_ntoa_r(in, ntoa_buf, sizeof(ntoa_buf));
  1117. sscanf( ntoa_buf, "%hu.%hu.%hu.%hu",
  1118. &ip[0], &ip[1], &ip[2], &ip[3]);
  1119. #else
  1120. sscanf( inet_ntoa(in), "%hu.%hu.%hu.%hu",
  1121. &ip[0], &ip[1], &ip[2], &ip[3]);
  1122. #endif
  1123. result=Curl_ftpsendf(conn, "PORT %d,%d,%d,%d,%d,%d",
  1124. ip[0], ip[1], ip[2], ip[3],
  1125. porttouse >> 8,
  1126. porttouse & 255);
  1127. if(result)
  1128. return result;
  1129. }
  1130. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  1131. if(nread < 0)
  1132. return CURLE_OPERATION_TIMEOUTED;
  1133. if(ftpcode != 200) {
  1134. failf(data, "Server does not grok PORT, try without it!");
  1135. return CURLE_FTP_PORT_FAILED;
  1136. }
  1137. #endif /* end of ipv4-specific code */
  1138. return CURLE_OK;
  1139. }
  1140. /***********************************************************************
  1141. *
  1142. * ftp_use_pasv()
  1143. *
  1144. * Send the PASV command. PASV is the ftp client's way of asking the server to
  1145. * open a second port that we can connect to (for the data transfer). This is
  1146. * the opposite of PORT.
  1147. */
  1148. static
  1149. CURLcode ftp_use_pasv(struct connectdata *conn)
  1150. {
  1151. struct SessionHandle *data = conn->data;
  1152. ssize_t nread;
  1153. char *buf = data->state.buffer; /* this is our buffer */
  1154. int ftpcode; /* receive FTP response codes in this */
  1155. CURLcode result;
  1156. Curl_addrinfo *addr=NULL;
  1157. Curl_ipconnect *conninfo;
  1158. /*
  1159. Here's the excecutive summary on what to do:
  1160. PASV is RFC959, expect:
  1161. 227 Entering Passive Mode (a1,a2,a3,a4,p1,p2)
  1162. LPSV is RFC1639, expect:
  1163. 228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2)
  1164. EPSV is RFC2428, expect:
  1165. 229 Entering Extended Passive Mode (|||port|)
  1166. */
  1167. #if 1
  1168. const char *mode[] = { "EPSV", "PASV", NULL };
  1169. int results[] = { 229, 227, 0 };
  1170. #else
  1171. #if 0
  1172. char *mode[] = { "EPSV", "LPSV", "PASV", NULL };
  1173. int results[] = { 229, 228, 227, 0 };
  1174. #else
  1175. const char *mode[] = { "PASV", NULL };
  1176. int results[] = { 227, 0 };
  1177. #endif
  1178. #endif
  1179. int modeoff;
  1180. unsigned short connectport; /* the local port connect() should use! */
  1181. unsigned short newport; /* remote port, not necessary the local one */
  1182. char *hostdataptr=NULL;
  1183. /* newhost must be able to hold a full IP-style address in ASCII, which
  1184. in the IPv6 case means 5*8-1 = 39 letters */
  1185. char newhost[48];
  1186. char *newhostp=NULL;
  1187. for (modeoff = (data->set.ftp_use_epsv?0:1);
  1188. mode[modeoff]; modeoff++) {
  1189. result = Curl_ftpsendf(conn, mode[modeoff]);
  1190. if(result)
  1191. return result;
  1192. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  1193. if(nread < 0)
  1194. return CURLE_OPERATION_TIMEOUTED;
  1195. if (ftpcode == results[modeoff])
  1196. break;
  1197. }
  1198. if (!mode[modeoff]) {
  1199. failf(data, "Odd return code after PASV");
  1200. return CURLE_FTP_WEIRD_PASV_REPLY;
  1201. }
  1202. else if (227 == results[modeoff]) {
  1203. int ip[4];
  1204. int port[2];
  1205. char *str=buf;
  1206. /*
  1207. * New 227-parser June 3rd 1999.
  1208. * It now scans for a sequence of six comma-separated numbers and
  1209. * will take them as IP+port indicators.
  1210. *
  1211. * Found reply-strings include:
  1212. * "227 Entering Passive Mode (127,0,0,1,4,51)"
  1213. * "227 Data transfer will passively listen to 127,0,0,1,4,51"
  1214. * "227 Entering passive mode. 127,0,0,1,4,51"
  1215. */
  1216. while(*str) {
  1217. if (6 == sscanf(str, "%d,%d,%d,%d,%d,%d",
  1218. &ip[0], &ip[1], &ip[2], &ip[3],
  1219. &port[0], &port[1]))
  1220. break;
  1221. str++;
  1222. }
  1223. if(!*str) {
  1224. failf(data, "Couldn't interpret this 227-reply: %s", buf);
  1225. return CURLE_FTP_WEIRD_227_FORMAT;
  1226. }
  1227. sprintf(newhost, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
  1228. newhostp = newhost;
  1229. newport = (port[0]<<8) + port[1];
  1230. }
  1231. #if 1
  1232. else if (229 == results[modeoff]) {
  1233. char *ptr = strchr(buf, '(');
  1234. if(ptr) {
  1235. unsigned int num;
  1236. char separator[4];
  1237. ptr++;
  1238. if(5 == sscanf(ptr, "%c%c%c%u%c",
  1239. &separator[0],
  1240. &separator[1],
  1241. &separator[2],
  1242. &num,
  1243. &separator[3])) {
  1244. /* the four separators should be identical */
  1245. newport = num;
  1246. /* we should use the same host we already are connected to */
  1247. newhostp = conn->name;
  1248. }
  1249. else
  1250. ptr=NULL;
  1251. }
  1252. if(!ptr) {
  1253. failf(data, "Weirdly formatted EPSV reply");
  1254. return CURLE_FTP_WEIRD_PASV_REPLY;
  1255. }
  1256. }
  1257. #endif
  1258. else
  1259. return CURLE_FTP_CANT_RECONNECT;
  1260. if(data->change.proxy) {
  1261. /*
  1262. * This is a tunnel through a http proxy and we need to connect to the
  1263. * proxy again here. We already have the name info for it since the
  1264. * previous lookup.
  1265. */
  1266. addr = conn->hostaddr;
  1267. connectport =
  1268. (unsigned short)conn->port; /* we connect to the proxy's port */
  1269. }
  1270. else {
  1271. /* normal, direct, ftp connection */
  1272. addr = Curl_resolv(data, newhostp, newport, &hostdataptr);
  1273. if(!addr) {
  1274. failf(data, "Can't resolve new host %s", newhost);
  1275. return CURLE_FTP_CANT_GET_HOST;
  1276. }
  1277. connectport = newport; /* we connect to the remote port */
  1278. }
  1279. result = Curl_connecthost(conn,
  1280. addr,
  1281. connectport,
  1282. &conn->secondarysocket,
  1283. &conninfo);
  1284. if((CURLE_OK == result) &&
  1285. data->set.verbose)
  1286. /* this just dumps information about this second connection */
  1287. ftp_pasv_verbose(conn, conninfo, newhost, connectport);
  1288. if(CURLE_OK != result)
  1289. return result;
  1290. if (data->set.tunnel_thru_httpproxy) {
  1291. /* We want "seamless" FTP operations through HTTP proxy tunnel */
  1292. result = Curl_ConnectHTTPProxyTunnel(conn, conn->secondarysocket,
  1293. newhost, newport);
  1294. if(CURLE_OK != result)
  1295. return result;
  1296. }
  1297. return CURLE_OK;
  1298. }
  1299. /***********************************************************************
  1300. *
  1301. * ftp_perform()
  1302. *
  1303. * This is the actual DO function for FTP. Get a file/directory according to
  1304. * the options previously setup.
  1305. */
  1306. static
  1307. CURLcode ftp_perform(struct connectdata *conn)
  1308. {
  1309. /* this is FTP and no proxy */
  1310. ssize_t nread;
  1311. CURLcode result;
  1312. struct SessionHandle *data=conn->data;
  1313. char *buf = data->state.buffer; /* this is our buffer */
  1314. /* the ftp struct is already inited in ftp_connect() */
  1315. struct FTP *ftp = conn->proto.ftp;
  1316. long *bytecountp = ftp->bytecountp;
  1317. int ftpcode; /* for ftp status */
  1318. /* Send any QUOTE strings? */
  1319. if(data->set.quote) {
  1320. if ((result = ftp_sendquote(conn, data->set.quote)) != CURLE_OK)
  1321. return result;
  1322. }
  1323. /* This is a re-used connection. Since we change directory to where the
  1324. transfer is taking place, we must now get back to the original dir
  1325. where we ended up after login: */
  1326. if (conn->bits.reuse) {
  1327. if ((result = ftp_cwd(conn, ftp->entrypath)) != CURLE_OK)
  1328. return result;
  1329. }
  1330. /* change directory first! */
  1331. if(ftp->dir && ftp->dir[0]) {
  1332. if ((result = ftp_cwd(conn, ftp->dir)) != CURLE_OK)
  1333. return result;
  1334. }
  1335. /* Requested time of file? */
  1336. if(data->set.get_filetime && ftp->file) {
  1337. result = ftp_getfiletime(conn, ftp->file);
  1338. if(result)
  1339. return result;
  1340. }
  1341. /* If we have selected NOBODY and HEADER, it means that we only want file
  1342. information. Which in FTP can't be much more than the file size and
  1343. date. */
  1344. if(data->set.no_body && data->set.include_header) {
  1345. /* The SIZE command is _not_ RFC 959 specified, and therefor many servers
  1346. may not support it! It is however the only way we have to get a file's
  1347. size! */
  1348. ssize_t filesize;
  1349. /* Some servers return different sizes for different modes, and thus we
  1350. must set the proper type before we check the size */
  1351. result = ftp_transfertype(conn, data->set.ftp_ascii);
  1352. if(result)
  1353. return result;
  1354. /* failing to get size is not a serious error */
  1355. result = ftp_getsize(conn, ftp->file, &filesize);
  1356. if(CURLE_OK == result) {
  1357. sprintf(buf, "Content-Length: %d\r\n", filesize);
  1358. result = Curl_client_write(data, CLIENTWRITE_BOTH, buf, 0);
  1359. if(result)
  1360. return result;
  1361. }
  1362. /* If we asked for a time of the file and we actually got one as
  1363. well, we "emulate" a HTTP-style header in our output. */
  1364. #ifdef HAVE_STRFTIME
  1365. if(data->set.get_filetime && data->info.filetime) {
  1366. struct tm *tm;
  1367. #ifdef HAVE_LOCALTIME_R
  1368. struct tm buffer;
  1369. tm = (struct tm *)localtime_r(&data->info.filetime, &buffer);
  1370. #else
  1371. tm = localtime((unsigned long *)&data->info.filetime);
  1372. #endif
  1373. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  1374. strftime(buf, BUFSIZE-1, "Last-Modified: %a, %d %b %Y %H:%M:%S %Z\r\n",
  1375. tm);
  1376. result = Curl_client_write(data, CLIENTWRITE_BOTH, buf, 0);
  1377. if(result)
  1378. return result;
  1379. }
  1380. #endif
  1381. return CURLE_OK;
  1382. }
  1383. if(data->set.no_body)
  1384. /* don't transfer the data */
  1385. ;
  1386. /* Get us a second connection up and connected */
  1387. else if(data->set.ftp_use_port) {
  1388. /* We have chosen to use the PORT command */
  1389. result = ftp_use_port(conn);
  1390. if(CURLE_OK == result)
  1391. /* we have the data connection ready */
  1392. infof(data, "Connected the data stream with PORT!\n");
  1393. }
  1394. else {
  1395. /* We have chosen (this is default) to use the PASV command */
  1396. result = ftp_use_pasv(conn);
  1397. if(CURLE_OK == result)
  1398. infof(data, "Connected the data stream with PASV!\n");
  1399. }
  1400. if(result)
  1401. return result;
  1402. if(data->set.upload) {
  1403. /* Set type to binary (unless specified ASCII) */
  1404. result = ftp_transfertype(conn, data->set.ftp_ascii);
  1405. if(result)
  1406. return result;
  1407. /* Send any PREQUOTE strings after transfer type is set? (Wesley Laxton)*/
  1408. if(data->set.prequote) {
  1409. if ((result = ftp_sendquote(conn, data->set.prequote)) != CURLE_OK)
  1410. return result;
  1411. }
  1412. if(conn->resume_from) {
  1413. /* we're about to continue the uploading of a file */
  1414. /* 1. get already existing file's size. We use the SIZE
  1415. command for this which may not exist in the server!
  1416. The SIZE command is not in RFC959. */
  1417. /* 2. This used to set REST. But since we can do append, we
  1418. don't another ftp command. We just skip the source file
  1419. offset and then we APPEND the rest on the file instead */
  1420. /* 3. pass file-size number of bytes in the source file */
  1421. /* 4. lower the infilesize counter */
  1422. /* => transfer as usual */
  1423. if(conn->resume_from < 0 ) {
  1424. /* we could've got a specified offset from the command line,
  1425. but now we know we didn't */
  1426. ssize_t gottensize;
  1427. if(CURLE_OK != ftp_getsize(conn, ftp->file, &gottensize)) {
  1428. failf(data, "Couldn't get remote file size");
  1429. return CURLE_FTP_COULDNT_GET_SIZE;
  1430. }
  1431. conn->resume_from = gottensize;
  1432. }
  1433. if(conn->resume_from) {
  1434. /* do we still game? */
  1435. int passed=0;
  1436. /* enable append instead */
  1437. data->set.ftp_append = 1;
  1438. /* Now, let's read off the proper amount of bytes from the
  1439. input. If we knew it was a proper file we could've just
  1440. fseek()ed but we only have a stream here */
  1441. do {
  1442. int readthisamountnow = (conn->resume_from - passed);
  1443. int actuallyread;
  1444. if(readthisamountnow > BUFSIZE)
  1445. readthisamountnow = BUFSIZE;
  1446. actuallyread =
  1447. data->set.fread(data->state.buffer, 1, readthisamountnow,
  1448. data->set.in);
  1449. passed += actuallyread;
  1450. if(actuallyread != readthisamountnow) {
  1451. failf(data, "Could only read %d bytes from the input", passed);
  1452. return CURLE_FTP_COULDNT_USE_REST;
  1453. }
  1454. }
  1455. while(passed != conn->resume_from);
  1456. /* now, decrease the size of the read */
  1457. if(data->set.infilesize>0) {
  1458. data->set.infilesize -= conn->resume_from;
  1459. if(data->set.infilesize <= 0) {
  1460. infof(data, "File already completely uploaded\n");
  1461. /* no data to transfer */
  1462. result=Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
  1463. /* Set resume done so that we won't get any error in
  1464. * Curl_ftp_done() because we didn't transfer the amount of bytes
  1465. * that the local file file obviously is */
  1466. conn->bits.resume_done = TRUE;
  1467. return CURLE_OK;
  1468. }
  1469. }
  1470. /* we've passed, proceed as normal */
  1471. }
  1472. }
  1473. /* Send everything on data->set.in to the socket */
  1474. if(data->set.ftp_append) {
  1475. /* we append onto the file instead of rewriting it */
  1476. FTPSENDF(conn, "APPE %s", ftp->file);
  1477. }
  1478. else {
  1479. FTPSENDF(conn, "STOR %s", ftp->file);
  1480. }
  1481. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  1482. if(nread < 0)
  1483. return CURLE_OPERATION_TIMEOUTED;
  1484. if(ftpcode>=400) {
  1485. failf(data, "Failed FTP upload:%s", buf+3);
  1486. /* oops, we never close the sockets! */
  1487. return CURLE_FTP_COULDNT_STOR_FILE;
  1488. }
  1489. if(data->set.ftp_use_port) {
  1490. /* PORT means we are now awaiting the server to connect to us. */
  1491. result = AllowServerConnect(data, conn, conn->secondarysocket);
  1492. if( result )
  1493. return result;
  1494. }
  1495. *bytecountp=0;
  1496. /* When we know we're uploading a specified file, we can get the file
  1497. size prior to the actual upload. */
  1498. Curl_pgrsSetUploadSize(data, data->set.infilesize);
  1499. result = Curl_Transfer(conn, -1, -1, FALSE, NULL, /* no download */
  1500. conn->secondarysocket, bytecountp);
  1501. if(result)
  1502. return result;
  1503. }
  1504. else if(!data->set.no_body) {
  1505. /* Retrieve file or directory */
  1506. bool dirlist=FALSE;
  1507. long downloadsize=-1;
  1508. if(conn->bits.use_range && conn->range) {
  1509. long from, to;
  1510. int totalsize=-1;
  1511. char *ptr;
  1512. char *ptr2;
  1513. from=strtol(conn->range, &ptr, 0);
  1514. while(ptr && *ptr && (isspace((int)*ptr) || (*ptr=='-')))
  1515. ptr++;
  1516. to=strtol(ptr, &ptr2, 0);
  1517. if(ptr == ptr2) {
  1518. /* we didn't get any digit */
  1519. to=-1;
  1520. }
  1521. if((-1 == to) && (from>=0)) {
  1522. /* X - */
  1523. conn->resume_from = from;
  1524. infof(data, "FTP RANGE %d to end of file\n", from);
  1525. }
  1526. else if(from < 0) {
  1527. /* -Y */
  1528. totalsize = -from;
  1529. conn->maxdownload = -from;
  1530. conn->resume_from = from;
  1531. infof(data, "FTP RANGE the last %d bytes\n", totalsize);
  1532. }
  1533. else {
  1534. /* X-Y */
  1535. totalsize = to-from;
  1536. conn->maxdownload = totalsize+1; /* include the last mentioned byte */
  1537. conn->resume_from = from;
  1538. infof(data, "FTP RANGE from %d getting %d bytes\n", from,
  1539. conn->maxdownload);
  1540. }
  1541. infof(data, "range-download from %d to %d, totally %d bytes\n",
  1542. from, to, totalsize);
  1543. }
  1544. if((data->set.ftp_list_only) || !ftp->file) {
  1545. /* The specified path ends with a slash, and therefore we think this
  1546. is a directory that is requested, use LIST. But before that we
  1547. need to set ASCII transfer mode. */
  1548. dirlist = TRUE;
  1549. /* Set type to ASCII */
  1550. result = ftp_transfertype(conn, TRUE /* ASCII enforced */);
  1551. if(result)
  1552. return result;
  1553. /* if this output is to be machine-parsed, the NLST command will be
  1554. better used since the LIST command output is not specified or
  1555. standard in any way */
  1556. FTPSENDF(conn, "%s",
  1557. data->set.customrequest?data->set.customrequest:
  1558. (data->set.ftp_list_only?"NLST":"LIST"));
  1559. }
  1560. else {
  1561. ssize_t foundsize;
  1562. /* Set type to binary (unless specified ASCII) */
  1563. result = ftp_transfertype(conn, data->set.ftp_ascii);
  1564. if(result)
  1565. return result;
  1566. /* Send any PREQUOTE strings after transfer type is set? (Wesley Laxton)*/
  1567. if(data->set.prequote) {
  1568. if ((result = ftp_sendquote(conn, data->set.prequote)) != CURLE_OK)
  1569. return result;
  1570. }
  1571. /* Attempt to get the size, it'll be useful in some cases: for resumed
  1572. downloads and when talking to servers that don't give away the size
  1573. in the RETR response line. */
  1574. result = ftp_getsize(conn, ftp->file, &foundsize);
  1575. if(CURLE_OK == result)
  1576. downloadsize = foundsize;
  1577. if(conn->resume_from) {
  1578. /* Daniel: (August 4, 1999)
  1579. *
  1580. * We start with trying to use the SIZE command to figure out the size
  1581. * of the file we're gonna get. If we can get the size, this is by far
  1582. * the best way to know if we're trying to resume beyond the EOF.
  1583. *
  1584. * Daniel, November 28, 2001. We *always* get the size on downloads
  1585. * now, so it is done before this even when not doing resumes. I saved
  1586. * the comment above for nostalgical reasons! ;-)
  1587. */
  1588. if(CURLE_OK != result) {
  1589. infof(data, "ftp server doesn't support SIZE\n");
  1590. /* We couldn't get the size and therefore we can't know if there
  1591. really is a part of the file left to get, although the server
  1592. will just close the connection when we start the connection so it
  1593. won't cause us any harm, just not make us exit as nicely. */
  1594. }
  1595. else {
  1596. /* We got a file size report, so we check that there actually is a
  1597. part of the file left to get, or else we go home. */
  1598. if(conn->resume_from< 0) {
  1599. /* We're supposed to download the last abs(from) bytes */
  1600. if(foundsize < -conn->resume_from) {
  1601. failf(data, "Offset (%d) was beyond file size (%d)",
  1602. conn->resume_from, foundsize);
  1603. return CURLE_FTP_BAD_DOWNLOAD_RESUME;
  1604. }
  1605. /* convert to size to download */
  1606. downloadsize = -conn->resume_from;
  1607. /* download from where? */
  1608. conn->resume_from = foundsize - downloadsize;
  1609. }
  1610. else {
  1611. if(foundsize < conn->resume_from) {
  1612. failf(data, "Offset (%d) was beyond file size (%d)",
  1613. conn->resume_from, foundsize);
  1614. return CURLE_FTP_BAD_DOWNLOAD_RESUME;
  1615. }
  1616. /* Now store the number of bytes we are expected to download */
  1617. downloadsize = foundsize-conn->resume_from;
  1618. }
  1619. }
  1620. if (downloadsize == 0) {
  1621. /* no data to transfer */
  1622. result=Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
  1623. infof(data, "File already completely downloaded\n");
  1624. /* Set resume done so that we won't get any error in Curl_ftp_done()
  1625. * because we didn't transfer the amount of bytes that the remote
  1626. * file obviously is */
  1627. conn->bits.resume_done = TRUE;
  1628. return CURLE_OK;
  1629. }
  1630. /* Set resume file transfer offset */
  1631. infof(data, "Instructs server to resume from offset %d\n",
  1632. conn->resume_from);
  1633. FTPSENDF(conn, "REST %d", conn->resume_from);
  1634. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  1635. if(nread < 0)
  1636. return CURLE_OPERATION_TIMEOUTED;
  1637. if(ftpcode != 350) {
  1638. failf(data, "Couldn't use REST: %s", buf+4);
  1639. return CURLE_FTP_COULDNT_USE_REST;
  1640. }
  1641. }
  1642. FTPSENDF(conn, "RETR %s", ftp->file);
  1643. }
  1644. nread = Curl_GetFTPResponse(buf, conn, &ftpcode);
  1645. if(nread < 0)
  1646. return CURLE_OPERATION_TIMEOUTED;
  1647. if((ftpcode == 150) || (ftpcode == 125)) {
  1648. /*
  1649. A;
  1650. 150 Opening BINARY mode data connection for /etc/passwd (2241
  1651. bytes). (ok, the file is being transfered)
  1652. B:
  1653. 150 Opening ASCII mode data connection for /bin/ls
  1654. C:
  1655. 150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes).
  1656. D:
  1657. 150 Opening ASCII mode data connection for /linux/fisk/kpanelrc (0.0.0.0,0) (545 bytes).
  1658. E:
  1659. 125 Data connection already open; Transfer starting. */
  1660. int size=-1; /* default unknown size */
  1661. if(!dirlist &&
  1662. !data->set.ftp_ascii &&
  1663. (-1 == downloadsize)) {
  1664. /*
  1665. * It seems directory listings either don't show the size or very
  1666. * often uses size 0 anyway. ASCII transfers may very well turn out
  1667. * that the transfered amount of data is not the same as this line
  1668. * tells, why using this number in those cases only confuses us.
  1669. *
  1670. * Example D above makes this parsing a little tricky */
  1671. char *bytes;
  1672. bytes=strstr(buf, " bytes");
  1673. if(bytes--) {
  1674. int index=bytes-buf;
  1675. /* this is a hint there is size information in there! ;-) */
  1676. while(--index) {
  1677. /* scan for the parenthesis and break there */
  1678. if('(' == *bytes)
  1679. break;
  1680. /* if only skip digits, or else we're in deep trouble */
  1681. if(!isdigit((int)*bytes)) {
  1682. bytes=NULL;
  1683. break;
  1684. }
  1685. /* one more estep backwards */
  1686. bytes--;
  1687. }
  1688. /* only if we have nothing but digits: */
  1689. if(bytes++) {
  1690. /* get the number! */
  1691. size = atoi(bytes);
  1692. }
  1693. }
  1694. }
  1695. else if(downloadsize > -1)
  1696. size = downloadsize;
  1697. if(data->set.ftp_use_port) {
  1698. result = AllowServerConnect(data, conn, conn->secondarysocket);
  1699. if( result )
  1700. return result;
  1701. }
  1702. infof(data, "Getting file with size: %d\n", size);
  1703. /* FTP download: */
  1704. result=Curl_Transfer(conn, conn->secondarysocket, size, FALSE,
  1705. bytecountp,
  1706. -1, NULL); /* no upload here */
  1707. if(result)
  1708. return result;
  1709. }
  1710. else {
  1711. failf(data, "%s", buf+4);
  1712. return CURLE_FTP_COULDNT_RETR_FILE;
  1713. }
  1714. }
  1715. /* end of transfer */
  1716. return CURLE_OK;
  1717. }
  1718. /***********************************************************************
  1719. *
  1720. * Curl_ftp()
  1721. *
  1722. * This function is registered as 'curl_do' function. It decodes the path
  1723. * parts etc as a wrapper to the actual DO function (ftp_perform).
  1724. *
  1725. * The input argument is already checked for validity.
  1726. */
  1727. CURLcode Curl_ftp(struct connectdata *conn)
  1728. {
  1729. CURLcode retcode;
  1730. struct SessionHandle *data = conn->data;
  1731. struct FTP *ftp;
  1732. int dirlength=0; /* 0 forces strlen() */
  1733. /* the ftp struct is already inited in ftp_connect() */
  1734. ftp = conn->proto.ftp;
  1735. /* We split the path into dir and file parts *before* we URLdecode
  1736. it */
  1737. ftp->file = strrchr(conn->ppath, '/');
  1738. if(ftp->file) {
  1739. if(ftp->file != conn->ppath)
  1740. dirlength=ftp->file-conn->ppath; /* don't count the traling slash */
  1741. ftp->file++; /* point to the first letter in the file name part or
  1742. remain NULL */
  1743. }
  1744. else {
  1745. ftp->file = conn->ppath; /* there's only a file part */
  1746. }
  1747. if(*ftp->file) {
  1748. ftp->file = curl_unescape(ftp->file, 0);
  1749. if(NULL == ftp->file) {
  1750. failf(data, "no memory");
  1751. return CURLE_OUT_OF_MEMORY;
  1752. }
  1753. }
  1754. else
  1755. ftp->file=NULL; /* instead of point to a zero byte, we make it a NULL
  1756. pointer */
  1757. ftp->urlpath = conn->ppath;
  1758. if(dirlength) {
  1759. ftp->dir = curl_unescape(ftp->urlpath, dirlength);
  1760. if(NULL == ftp->dir) {
  1761. if(ftp->file)
  1762. free(ftp->file);
  1763. failf(data, "no memory");
  1764. return CURLE_OUT_OF_MEMORY; /* failure */
  1765. }
  1766. }
  1767. else
  1768. ftp->dir = NULL;
  1769. retcode = ftp_perform(conn);
  1770. /* clean up here, success or error doesn't matter */
  1771. if(ftp->file)
  1772. free(ftp->file);
  1773. if(ftp->dir)
  1774. free(ftp->dir);
  1775. ftp->file = ftp->dir = NULL; /* zero */
  1776. return retcode;
  1777. }
  1778. /***********************************************************************
  1779. *
  1780. * Curl_ftpsendf()
  1781. *
  1782. * Sends the formated string as a ftp command to a ftp server
  1783. *
  1784. * NOTE: we build the command in a fixed-length buffer, which sets length
  1785. * restrictions on the command!
  1786. */
  1787. CURLcode Curl_ftpsendf(struct connectdata *conn,
  1788. const char *fmt, ...)
  1789. {
  1790. ssize_t bytes_written;
  1791. char s[256];
  1792. ssize_t write_len;
  1793. char *sptr=s;
  1794. CURLcode res = CURLE_OK;
  1795. va_list ap;
  1796. va_start(ap, fmt);
  1797. vsnprintf(s, 250, fmt, ap);
  1798. va_end(ap);
  1799. if(conn->data->set.verbose)
  1800. fprintf(conn->data->set.err, "> %s\n", s);
  1801. strcat(s, "\r\n"); /* append a trailing CRLF */
  1802. bytes_written=0;
  1803. write_len = strlen(s);
  1804. do {
  1805. res = Curl_write(conn, conn->firstsocket, sptr, write_len,
  1806. &bytes_written);
  1807. if(CURLE_OK != res)
  1808. break;
  1809. if(bytes_written != write_len) {
  1810. write_len -= bytes_written;
  1811. sptr += bytes_written;
  1812. }
  1813. else
  1814. break;
  1815. } while(1);
  1816. return res;
  1817. }
  1818. /***********************************************************************
  1819. *
  1820. * Curl_ftp_disconnect()
  1821. *
  1822. * Disconnect from an FTP server. Cleanup protocol-specific per-connection
  1823. * resources
  1824. */
  1825. CURLcode Curl_ftp_disconnect(struct connectdata *conn)
  1826. {
  1827. struct FTP *ftp= conn->proto.ftp;
  1828. /* The FTP session may or may not have been allocated/setup at this point! */
  1829. if(ftp) {
  1830. if(ftp->entrypath)
  1831. free(ftp->entrypath);
  1832. if(ftp->cache)
  1833. free(ftp->cache);
  1834. }
  1835. return CURLE_OK;
  1836. }
  1837. /*
  1838. * local variables:
  1839. * eval: (load-file "../curl-mode.el")
  1840. * end:
  1841. * vim600: fdm=marker
  1842. * vim: et sw=2 ts=2 sts=2 tw=78
  1843. */