ftp.c 63 KB

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