ftp.c 63 KB

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