file.c 17 KB

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