file.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2008, 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_FILE
  25. /* -- WIN32 approved -- */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdarg.h>
  29. #include <stdlib.h>
  30. #include <ctype.h>
  31. #ifdef WIN32
  32. #include <time.h>
  33. #include <io.h>
  34. #include <fcntl.h>
  35. #else
  36. #ifdef HAVE_SYS_SOCKET_H
  37. #include <sys/socket.h>
  38. #endif
  39. #ifdef HAVE_NETINET_IN_H
  40. #include <netinet/in.h>
  41. #endif
  42. #ifdef HAVE_SYS_TIME_H
  43. #include <sys/time.h>
  44. #endif
  45. #ifdef HAVE_UNISTD_H
  46. #include <unistd.h>
  47. #endif
  48. #ifdef HAVE_NETDB_H
  49. #include <netdb.h>
  50. #endif
  51. #ifdef HAVE_ARPA_INET_H
  52. #include <arpa/inet.h>
  53. #endif
  54. #ifdef HAVE_NET_IF_H
  55. #include <net/if.h>
  56. #endif
  57. #include <sys/ioctl.h>
  58. #include <signal.h>
  59. #ifdef HAVE_SYS_PARAM_H
  60. #include <sys/param.h>
  61. #endif
  62. #ifdef HAVE_FCNTL_H
  63. #include <fcntl.h>
  64. #endif
  65. #endif /* WIN32 */
  66. #include "strtoofft.h"
  67. #include "urldata.h"
  68. #include <curl/curl.h>
  69. #include "progress.h"
  70. #include "sendf.h"
  71. #include "escape.h"
  72. #include "file.h"
  73. #include "speedcheck.h"
  74. #include "getinfo.h"
  75. #include "transfer.h"
  76. #include "url.h"
  77. #include "memory.h"
  78. #include "parsedate.h" /* for the week day and month names */
  79. #define _MPRINTF_REPLACE /* use our functions only */
  80. #include <curl/mprintf.h>
  81. /* The last #include file should be: */
  82. #include "memdebug.h"
  83. #if defined(WIN32) || defined(MSDOS) || defined(__EMX__) || defined(__SYMBIAN32__)
  84. #define DOS_FILESYSTEM 1
  85. #endif
  86. /*
  87. * Forward declarations.
  88. */
  89. static CURLcode file_do(struct connectdata *, bool *done);
  90. static CURLcode file_done(struct connectdata *conn,
  91. CURLcode status, bool premature);
  92. static CURLcode file_connect(struct connectdata *conn, bool *done);
  93. /*
  94. * FILE scheme handler.
  95. */
  96. const struct Curl_handler Curl_handler_file = {
  97. "FILE", /* scheme */
  98. ZERO_NULL, /* setup_connection */
  99. file_do, /* do_it */
  100. file_done, /* done */
  101. ZERO_NULL, /* do_more */
  102. file_connect, /* connect_it */
  103. ZERO_NULL, /* connecting */
  104. ZERO_NULL, /* doing */
  105. ZERO_NULL, /* proto_getsock */
  106. ZERO_NULL, /* doing_getsock */
  107. ZERO_NULL, /* disconnect */
  108. 0, /* defport */
  109. PROT_FILE /* protocol */
  110. };
  111. /*
  112. Check if this is a range download, and if so, set the internal variables
  113. properly. This code is copied from the FTP implementation and might as
  114. well be factored out.
  115. */
  116. static CURLcode file_range(struct connectdata *conn)
  117. {
  118. curl_off_t from, to;
  119. curl_off_t totalsize=-1;
  120. char *ptr;
  121. char *ptr2;
  122. struct SessionHandle *data = conn->data;
  123. if(data->state.use_range && data->state.range) {
  124. from=curlx_strtoofft(data->state.range, &ptr, 0);
  125. while(ptr && *ptr && (isspace((int)*ptr) || (*ptr=='-')))
  126. ptr++;
  127. to=curlx_strtoofft(ptr, &ptr2, 0);
  128. if(ptr == ptr2) {
  129. /* we didn't get any digit */
  130. to=-1;
  131. }
  132. if((-1 == to) && (from>=0)) {
  133. /* X - */
  134. data->state.resume_from = from;
  135. DEBUGF(infof(data, "RANGE %" FORMAT_OFF_T " to end of file\n",
  136. from));
  137. }
  138. else if(from < 0) {
  139. /* -Y */
  140. totalsize = -from;
  141. data->req.maxdownload = -from;
  142. data->state.resume_from = from;
  143. DEBUGF(infof(data, "RANGE the last %" FORMAT_OFF_T " bytes\n",
  144. totalsize));
  145. }
  146. else {
  147. /* X-Y */
  148. totalsize = to-from;
  149. data->req.maxdownload = totalsize+1; /* include last byte */
  150. data->state.resume_from = from;
  151. DEBUGF(infof(data, "RANGE from %" FORMAT_OFF_T
  152. " getting %" FORMAT_OFF_T " bytes\n",
  153. from, data->req.maxdownload));
  154. }
  155. DEBUGF(infof(data, "range-download from %" FORMAT_OFF_T
  156. " to %" FORMAT_OFF_T ", totally %" FORMAT_OFF_T " bytes\n",
  157. from, to, data->req.maxdownload));
  158. }
  159. else
  160. data->req.maxdownload = -1;
  161. return CURLE_OK;
  162. }
  163. /*
  164. * file_connect() gets called from Curl_protocol_connect() to allow us to
  165. * do protocol-specific actions at connect-time. We emulate a
  166. * connect-then-transfer protocol and "connect" to the file here
  167. */
  168. static CURLcode file_connect(struct connectdata *conn, bool *done)
  169. {
  170. struct SessionHandle *data = conn->data;
  171. char *real_path = curl_easy_unescape(data, data->state.path, 0, NULL);
  172. struct FILEPROTO *file;
  173. int fd;
  174. #ifdef DOS_FILESYSTEM
  175. int i;
  176. char *actual_path;
  177. #endif
  178. if(!real_path)
  179. return CURLE_OUT_OF_MEMORY;
  180. /* If there already is a protocol-specific struct allocated for this
  181. sessionhandle, deal with it */
  182. Curl_reset_reqproto(conn);
  183. if(!data->state.proto.file) {
  184. file = (struct FILEPROTO *)calloc(sizeof(struct FILEPROTO), 1);
  185. if(!file) {
  186. free(real_path);
  187. return CURLE_OUT_OF_MEMORY;
  188. }
  189. data->state.proto.file = file;
  190. }
  191. else {
  192. /* file is not a protocol that can deal with "persistancy" */
  193. file = data->state.proto.file;
  194. Curl_safefree(file->freepath);
  195. if(file->fd != -1)
  196. close(file->fd);
  197. file->path = NULL;
  198. file->freepath = NULL;
  199. file->fd = -1;
  200. }
  201. #ifdef DOS_FILESYSTEM
  202. /* If the first character is a slash, and there's
  203. something that looks like a drive at the beginning of
  204. the path, skip the slash. If we remove the initial
  205. slash in all cases, paths without drive letters end up
  206. relative to the current directory which isn't how
  207. browsers work.
  208. Some browsers accept | instead of : as the drive letter
  209. separator, so we do too.
  210. On other platforms, we need the slash to indicate an
  211. absolute pathname. On Windows, absolute paths start
  212. with a drive letter.
  213. */
  214. actual_path = real_path;
  215. if((actual_path[0] == '/') &&
  216. actual_path[1] &&
  217. (actual_path[2] == ':' || actual_path[2] == '|'))
  218. {
  219. actual_path[2] = ':';
  220. actual_path++;
  221. }
  222. /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */
  223. for (i=0; actual_path[i] != '\0'; ++i)
  224. if(actual_path[i] == '/')
  225. actual_path[i] = '\\';
  226. fd = open(actual_path, O_RDONLY | O_BINARY); /* no CR/LF translation! */
  227. file->path = actual_path;
  228. #else
  229. fd = open(real_path, O_RDONLY);
  230. file->path = real_path;
  231. #endif
  232. file->freepath = real_path; /* free this when done */
  233. file->fd = fd;
  234. if(!data->set.upload && (fd == -1)) {
  235. failf(data, "Couldn't open file %s", data->state.path);
  236. file_done(conn, CURLE_FILE_COULDNT_READ_FILE, FALSE);
  237. return CURLE_FILE_COULDNT_READ_FILE;
  238. }
  239. *done = TRUE;
  240. return CURLE_OK;
  241. }
  242. static CURLcode file_done(struct connectdata *conn,
  243. CURLcode status, bool premature)
  244. {
  245. struct FILEPROTO *file = conn->data->state.proto.file;
  246. (void)status; /* not used */
  247. (void)premature; /* not used */
  248. Curl_safefree(file->freepath);
  249. if(file->fd != -1)
  250. close(file->fd);
  251. return CURLE_OK;
  252. }
  253. #ifdef DOS_FILESYSTEM
  254. #define DIRSEP '\\'
  255. #else
  256. #define DIRSEP '/'
  257. #endif
  258. static CURLcode file_upload(struct connectdata *conn)
  259. {
  260. struct FILEPROTO *file = conn->data->state.proto.file;
  261. const char *dir = strchr(file->path, DIRSEP);
  262. FILE *fp;
  263. CURLcode res=CURLE_OK;
  264. struct SessionHandle *data = conn->data;
  265. char *buf = data->state.buffer;
  266. size_t nread;
  267. size_t nwrite;
  268. curl_off_t bytecount = 0;
  269. struct timeval now = Curl_tvnow();
  270. struct_stat file_stat;
  271. const char* buf2;
  272. /*
  273. * Since FILE: doesn't do the full init, we need to provide some extra
  274. * assignments here.
  275. */
  276. conn->fread_func = data->set.fread_func;
  277. conn->fread_in = data->set.in;
  278. conn->data->req.upload_fromhere = buf;
  279. if(!dir)
  280. return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
  281. if(!dir[1])
  282. return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
  283. if(data->state.resume_from)
  284. fp = fopen( file->path, "ab" );
  285. else {
  286. int fd;
  287. #ifdef DOS_FILESYSTEM
  288. fd = open(file->path, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY,
  289. conn->data->set.new_file_perms);
  290. #else
  291. fd = open(file->path, O_WRONLY|O_CREAT|O_TRUNC,
  292. conn->data->set.new_file_perms);
  293. #endif
  294. if(fd < 0) {
  295. failf(data, "Can't open %s for writing", file->path);
  296. return CURLE_WRITE_ERROR;
  297. }
  298. fp = fdopen(fd, "wb");
  299. }
  300. if(!fp) {
  301. failf(data, "Can't open %s for writing", file->path);
  302. return CURLE_WRITE_ERROR;
  303. }
  304. if(-1 != data->set.infilesize)
  305. /* known size of data to "upload" */
  306. Curl_pgrsSetUploadSize(data, data->set.infilesize);
  307. /* treat the negative resume offset value as the case of "-" */
  308. if(data->state.resume_from < 0) {
  309. if(stat(file->path, &file_stat)) {
  310. fclose(fp);
  311. failf(data, "Can't get the size of %s", file->path);
  312. return CURLE_WRITE_ERROR;
  313. }
  314. else
  315. data->state.resume_from = (curl_off_t)file_stat.st_size;
  316. }
  317. while(res == CURLE_OK) {
  318. int readcount;
  319. res = Curl_fillreadbuffer(conn, BUFSIZE, &readcount);
  320. if(res)
  321. break;
  322. if(readcount <= 0) /* fix questionable compare error. curlvms */
  323. break;
  324. nread = (size_t)readcount;
  325. /*skip bytes before resume point*/
  326. if(data->state.resume_from) {
  327. if( (curl_off_t)nread <= data->state.resume_from ) {
  328. data->state.resume_from -= nread;
  329. nread = 0;
  330. buf2 = buf;
  331. }
  332. else {
  333. buf2 = buf + data->state.resume_from;
  334. nread -= (size_t)data->state.resume_from;
  335. data->state.resume_from = 0;
  336. }
  337. }
  338. else
  339. buf2 = buf;
  340. /* write the data to the target */
  341. nwrite = fwrite(buf2, 1, nread, fp);
  342. if(nwrite != nread) {
  343. res = CURLE_SEND_ERROR;
  344. break;
  345. }
  346. bytecount += nread;
  347. Curl_pgrsSetUploadCounter(data, bytecount);
  348. if(Curl_pgrsUpdate(conn))
  349. res = CURLE_ABORTED_BY_CALLBACK;
  350. else
  351. res = Curl_speedcheck(data, now);
  352. }
  353. if(!res && Curl_pgrsUpdate(conn))
  354. res = CURLE_ABORTED_BY_CALLBACK;
  355. fclose(fp);
  356. return res;
  357. }
  358. /*
  359. * file_do() is the protocol-specific function for the do-phase, separated
  360. * from the connect-phase above. Other protocols merely setup the transfer in
  361. * the do-phase, to have it done in the main transfer loop but since some
  362. * platforms we support don't allow select()ing etc on file handles (as
  363. * opposed to sockets) we instead perform the whole do-operation in this
  364. * function.
  365. */
  366. static CURLcode file_do(struct connectdata *conn, bool *done)
  367. {
  368. /* This implementation ignores the host name in conformance with
  369. RFC 1738. Only local files (reachable via the standard file system)
  370. are supported. This means that files on remotely mounted directories
  371. (via NFS, Samba, NT sharing) can be accessed through a file:// URL
  372. */
  373. CURLcode res = CURLE_OK;
  374. struct_stat statbuf; /* struct_stat instead of struct stat just to allow the
  375. Windows version to have a different struct without
  376. having to redefine the simple word 'stat' */
  377. curl_off_t expected_size=0;
  378. bool fstated=FALSE;
  379. ssize_t nread;
  380. size_t bytestoread;
  381. struct SessionHandle *data = conn->data;
  382. char *buf = data->state.buffer;
  383. curl_off_t bytecount = 0;
  384. int fd;
  385. struct timeval now = Curl_tvnow();
  386. *done = TRUE; /* unconditionally */
  387. Curl_initinfo(data);
  388. Curl_pgrsStartNow(data);
  389. if(data->set.upload)
  390. return file_upload(conn);
  391. /* get the fd from the connection phase */
  392. fd = conn->data->state.proto.file->fd;
  393. /* VMS: This only works reliable for STREAMLF files */
  394. if( -1 != fstat(fd, &statbuf)) {
  395. /* we could stat it, then read out the size */
  396. expected_size = statbuf.st_size;
  397. fstated = TRUE;
  398. }
  399. /* If we have selected NOBODY and HEADER, it means that we only want file
  400. information. Which for FILE can't be much more than the file size and
  401. date. */
  402. if(data->set.opt_no_body && data->set.include_header && fstated) {
  403. CURLcode result;
  404. snprintf(buf, sizeof(data->state.buffer),
  405. "Content-Length: %" FORMAT_OFF_T "\r\n", expected_size);
  406. result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0);
  407. if(result)
  408. return result;
  409. result = Curl_client_write(conn, CLIENTWRITE_BOTH,
  410. (char *)"Accept-ranges: bytes\r\n", 0);
  411. if(result)
  412. return result;
  413. if(fstated) {
  414. const struct tm *tm;
  415. time_t filetime = (time_t)statbuf.st_mtime;
  416. #ifdef HAVE_GMTIME_R
  417. struct tm buffer;
  418. tm = (const struct tm *)gmtime_r(&filetime, &buffer);
  419. #else
  420. tm = gmtime(&filetime);
  421. #endif
  422. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  423. snprintf(buf, BUFSIZE-1,
  424. "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
  425. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  426. tm->tm_mday,
  427. Curl_month[tm->tm_mon],
  428. tm->tm_year + 1900,
  429. tm->tm_hour,
  430. tm->tm_min,
  431. tm->tm_sec);
  432. result = Curl_client_write(conn, CLIENTWRITE_BOTH, buf, 0);
  433. }
  434. return result;
  435. }
  436. /* Check whether file range has been specified */
  437. file_range(conn);
  438. /* Adjust the start offset in case we want to get the N last bytes
  439. * of the stream iff the filesize could be determined */
  440. if(data->state.resume_from < 0) {
  441. if(!fstated) {
  442. failf(data, "Can't get the size of file.");
  443. return CURLE_READ_ERROR;
  444. }
  445. else
  446. data->state.resume_from += (curl_off_t)statbuf.st_size;
  447. }
  448. if(data->state.resume_from <= expected_size)
  449. expected_size -= data->state.resume_from;
  450. else {
  451. failf(data, "failed to resume file:// transfer");
  452. return CURLE_BAD_DOWNLOAD_RESUME;
  453. }
  454. /* A high water mark has been specified so we obey... */
  455. if (data->req.maxdownload > 0)
  456. expected_size = data->req.maxdownload;
  457. if(fstated && (expected_size == 0))
  458. return CURLE_OK;
  459. /* The following is a shortcut implementation of file reading
  460. this is both more efficient than the former call to download() and
  461. it avoids problems with select() and recv() on file descriptors
  462. in Winsock */
  463. if(fstated)
  464. Curl_pgrsSetDownloadSize(data, expected_size);
  465. if(data->state.resume_from) {
  466. if(data->state.resume_from !=
  467. lseek(fd, data->state.resume_from, SEEK_SET))
  468. return CURLE_BAD_DOWNLOAD_RESUME;
  469. }
  470. Curl_pgrsTime(data, TIMER_STARTTRANSFER);
  471. while(res == CURLE_OK) {
  472. /* Don't fill a whole buffer if we want less than all data */
  473. bytestoread = (expected_size < BUFSIZE-1)?(size_t)expected_size:BUFSIZE-1;
  474. nread = read(fd, buf, bytestoread);
  475. if( nread > 0)
  476. buf[nread] = 0;
  477. if (nread <= 0 || expected_size == 0)
  478. break;
  479. bytecount += nread;
  480. expected_size -= nread;
  481. res = Curl_client_write(conn, CLIENTWRITE_BODY, buf, nread);
  482. if(res)
  483. return res;
  484. Curl_pgrsSetDownloadCounter(data, bytecount);
  485. if(Curl_pgrsUpdate(conn))
  486. res = CURLE_ABORTED_BY_CALLBACK;
  487. else
  488. res = Curl_speedcheck(data, now);
  489. }
  490. if(Curl_pgrsUpdate(conn))
  491. res = CURLE_ABORTED_BY_CALLBACK;
  492. return res;
  493. }
  494. #endif