file.c 17 KB

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