file.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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 https://curl.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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifndef CURL_DISABLE_FILE
  26. #ifdef HAVE_NETINET_IN_H
  27. #include <netinet/in.h>
  28. #endif
  29. #ifdef HAVE_NETDB_H
  30. #include <netdb.h>
  31. #endif
  32. #ifdef HAVE_ARPA_INET_H
  33. #include <arpa/inet.h>
  34. #endif
  35. #ifdef HAVE_NET_IF_H
  36. #include <net/if.h>
  37. #endif
  38. #ifdef HAVE_SYS_IOCTL_H
  39. #include <sys/ioctl.h>
  40. #endif
  41. #ifdef HAVE_SYS_PARAM_H
  42. #include <sys/param.h>
  43. #endif
  44. #ifdef HAVE_FCNTL_H
  45. #include <fcntl.h>
  46. #endif
  47. #ifdef HAVE_SYS_TYPES_H
  48. #include <sys/types.h>
  49. #endif
  50. #ifdef HAVE_DIRENT_H
  51. #include <dirent.h>
  52. #endif
  53. #include "strtoofft.h"
  54. #include "urldata.h"
  55. #include <curl/curl.h>
  56. #include "progress.h"
  57. #include "sendf.h"
  58. #include "escape.h"
  59. #include "file.h"
  60. #include "speedcheck.h"
  61. #include "getinfo.h"
  62. #include "multiif.h"
  63. #include "transfer.h"
  64. #include "url.h"
  65. #include "parsedate.h" /* for the week day and month names */
  66. #include "warnless.h"
  67. #include "curl_range.h"
  68. /* The last 3 #include files should be in this order */
  69. #include "curl_printf.h"
  70. #include "curl_memory.h"
  71. #include "memdebug.h"
  72. #if defined(_WIN32) || defined(MSDOS) || defined(__EMX__)
  73. #define DOS_FILESYSTEM 1
  74. #elif defined(__amigaos4__)
  75. #define AMIGA_FILESYSTEM 1
  76. #endif
  77. #ifdef OPEN_NEEDS_ARG3
  78. # define open_readonly(p,f) open((p),(f),(0))
  79. #else
  80. # define open_readonly(p,f) open((p),(f))
  81. #endif
  82. /*
  83. * Forward declarations.
  84. */
  85. static CURLcode file_do(struct Curl_easy *data, bool *done);
  86. static CURLcode file_done(struct Curl_easy *data,
  87. CURLcode status, bool premature);
  88. static CURLcode file_connect(struct Curl_easy *data, bool *done);
  89. static CURLcode file_disconnect(struct Curl_easy *data,
  90. struct connectdata *conn,
  91. bool dead_connection);
  92. static CURLcode file_setup_connection(struct Curl_easy *data,
  93. struct connectdata *conn);
  94. /*
  95. * FILE scheme handler.
  96. */
  97. const struct Curl_handler Curl_handler_file = {
  98. "file", /* scheme */
  99. file_setup_connection, /* setup_connection */
  100. file_do, /* do_it */
  101. file_done, /* done */
  102. ZERO_NULL, /* do_more */
  103. file_connect, /* connect_it */
  104. ZERO_NULL, /* connecting */
  105. ZERO_NULL, /* doing */
  106. ZERO_NULL, /* proto_getsock */
  107. ZERO_NULL, /* doing_getsock */
  108. ZERO_NULL, /* domore_getsock */
  109. ZERO_NULL, /* perform_getsock */
  110. file_disconnect, /* disconnect */
  111. ZERO_NULL, /* write_resp */
  112. ZERO_NULL, /* write_resp_hd */
  113. ZERO_NULL, /* connection_check */
  114. ZERO_NULL, /* attach connection */
  115. 0, /* defport */
  116. CURLPROTO_FILE, /* protocol */
  117. CURLPROTO_FILE, /* family */
  118. PROTOPT_NONETWORK | PROTOPT_NOURLQUERY /* flags */
  119. };
  120. static CURLcode file_setup_connection(struct Curl_easy *data,
  121. struct connectdata *conn)
  122. {
  123. (void)conn;
  124. /* allocate the FILE specific struct */
  125. data->req.p.file = calloc(1, sizeof(struct FILEPROTO));
  126. if(!data->req.p.file)
  127. return CURLE_OUT_OF_MEMORY;
  128. return CURLE_OK;
  129. }
  130. /*
  131. * file_connect() gets called from Curl_protocol_connect() to allow us to
  132. * do protocol-specific actions at connect-time. We emulate a
  133. * connect-then-transfer protocol and "connect" to the file here
  134. */
  135. static CURLcode file_connect(struct Curl_easy *data, bool *done)
  136. {
  137. char *real_path;
  138. struct FILEPROTO *file = data->req.p.file;
  139. int fd;
  140. #ifdef DOS_FILESYSTEM
  141. size_t i;
  142. char *actual_path;
  143. #endif
  144. size_t real_path_len;
  145. CURLcode result;
  146. if(file->path) {
  147. /* already connected.
  148. * the handler->connect_it() is normally only called once, but
  149. * FILE does a special check on setting up the connection which
  150. * calls this explicitly. */
  151. *done = TRUE;
  152. return CURLE_OK;
  153. }
  154. result = Curl_urldecode(data->state.up.path, 0, &real_path,
  155. &real_path_len, REJECT_ZERO);
  156. if(result)
  157. return result;
  158. #ifdef DOS_FILESYSTEM
  159. /* If the first character is a slash, and there is
  160. something that looks like a drive at the beginning of
  161. the path, skip the slash. If we remove the initial
  162. slash in all cases, paths without drive letters end up
  163. relative to the current directory which is not how
  164. browsers work.
  165. Some browsers accept | instead of : as the drive letter
  166. separator, so we do too.
  167. On other platforms, we need the slash to indicate an
  168. absolute pathname. On Windows, absolute paths start
  169. with a drive letter.
  170. */
  171. actual_path = real_path;
  172. if((actual_path[0] == '/') &&
  173. actual_path[1] &&
  174. (actual_path[2] == ':' || actual_path[2] == '|')) {
  175. actual_path[2] = ':';
  176. actual_path++;
  177. real_path_len--;
  178. }
  179. /* change path separators from '/' to '\\' for DOS, Windows and OS/2 */
  180. for(i = 0; i < real_path_len; ++i)
  181. if(actual_path[i] == '/')
  182. actual_path[i] = '\\';
  183. else if(!actual_path[i]) { /* binary zero */
  184. Curl_safefree(real_path);
  185. return CURLE_URL_MALFORMAT;
  186. }
  187. fd = open_readonly(actual_path, O_RDONLY|O_BINARY);
  188. file->path = actual_path;
  189. #else
  190. if(memchr(real_path, 0, real_path_len)) {
  191. /* binary zeroes indicate foul play */
  192. Curl_safefree(real_path);
  193. return CURLE_URL_MALFORMAT;
  194. }
  195. #ifdef AMIGA_FILESYSTEM
  196. /*
  197. * A leading slash in an AmigaDOS path denotes the parent
  198. * directory, and hence we block this as it is relative.
  199. * Absolute paths start with 'volumename:', so we check for
  200. * this first. Failing that, we treat the path as a real Unix
  201. * path, but only if the application was compiled with -lunix.
  202. */
  203. fd = -1;
  204. file->path = real_path;
  205. if(real_path[0] == '/') {
  206. extern int __unix_path_semantics;
  207. if(strchr(real_path + 1, ':')) {
  208. /* Amiga absolute path */
  209. fd = open_readonly(real_path + 1, O_RDONLY);
  210. file->path++;
  211. }
  212. else if(__unix_path_semantics) {
  213. /* -lunix fallback */
  214. fd = open_readonly(real_path, O_RDONLY);
  215. }
  216. }
  217. #else
  218. fd = open_readonly(real_path, O_RDONLY);
  219. file->path = real_path;
  220. #endif
  221. #endif
  222. Curl_safefree(file->freepath);
  223. file->freepath = real_path; /* free this when done */
  224. file->fd = fd;
  225. if(!data->state.upload && (fd == -1)) {
  226. failf(data, "Couldn't open file %s", data->state.up.path);
  227. file_done(data, CURLE_FILE_COULDNT_READ_FILE, FALSE);
  228. return CURLE_FILE_COULDNT_READ_FILE;
  229. }
  230. *done = TRUE;
  231. return CURLE_OK;
  232. }
  233. static CURLcode file_done(struct Curl_easy *data,
  234. CURLcode status, bool premature)
  235. {
  236. struct FILEPROTO *file = data->req.p.file;
  237. (void)status; /* not used */
  238. (void)premature; /* not used */
  239. if(file) {
  240. Curl_safefree(file->freepath);
  241. file->path = NULL;
  242. if(file->fd != -1)
  243. close(file->fd);
  244. file->fd = -1;
  245. }
  246. return CURLE_OK;
  247. }
  248. static CURLcode file_disconnect(struct Curl_easy *data,
  249. struct connectdata *conn,
  250. bool dead_connection)
  251. {
  252. (void)dead_connection; /* not used */
  253. (void)conn;
  254. return file_done(data, CURLE_OK, FALSE);
  255. }
  256. #ifdef DOS_FILESYSTEM
  257. #define DIRSEP '\\'
  258. #else
  259. #define DIRSEP '/'
  260. #endif
  261. static CURLcode file_upload(struct Curl_easy *data)
  262. {
  263. struct FILEPROTO *file = data->req.p.file;
  264. const char *dir = strchr(file->path, DIRSEP);
  265. int fd;
  266. int mode;
  267. CURLcode result = CURLE_OK;
  268. char *xfer_ulbuf;
  269. size_t xfer_ulblen;
  270. curl_off_t bytecount = 0;
  271. struct_stat file_stat;
  272. const char *sendbuf;
  273. bool eos = FALSE;
  274. /*
  275. * Since FILE: does not do the full init, we need to provide some extra
  276. * assignments here.
  277. */
  278. if(!dir)
  279. return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
  280. if(!dir[1])
  281. return CURLE_FILE_COULDNT_READ_FILE; /* fix: better error code */
  282. #ifdef O_BINARY
  283. #define MODE_DEFAULT O_WRONLY|O_CREAT|O_BINARY
  284. #else
  285. #define MODE_DEFAULT O_WRONLY|O_CREAT
  286. #endif
  287. if(data->state.resume_from)
  288. mode = MODE_DEFAULT|O_APPEND;
  289. else
  290. mode = MODE_DEFAULT|O_TRUNC;
  291. fd = open(file->path, mode, data->set.new_file_perms);
  292. if(fd < 0) {
  293. failf(data, "cannot open %s for writing", file->path);
  294. return CURLE_WRITE_ERROR;
  295. }
  296. if(-1 != data->state.infilesize)
  297. /* known size of data to "upload" */
  298. Curl_pgrsSetUploadSize(data, data->state.infilesize);
  299. /* treat the negative resume offset value as the case of "-" */
  300. if(data->state.resume_from < 0) {
  301. if(fstat(fd, &file_stat)) {
  302. close(fd);
  303. failf(data, "cannot get the size of %s", file->path);
  304. return CURLE_WRITE_ERROR;
  305. }
  306. data->state.resume_from = (curl_off_t)file_stat.st_size;
  307. }
  308. result = Curl_multi_xfer_ulbuf_borrow(data, &xfer_ulbuf, &xfer_ulblen);
  309. if(result)
  310. goto out;
  311. while(!result && !eos) {
  312. size_t nread;
  313. ssize_t nwrite;
  314. size_t readcount;
  315. result = Curl_client_read(data, xfer_ulbuf, xfer_ulblen, &readcount, &eos);
  316. if(result)
  317. break;
  318. if(!readcount)
  319. break;
  320. nread = 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. sendbuf = xfer_ulbuf;
  327. }
  328. else {
  329. sendbuf = xfer_ulbuf + data->state.resume_from;
  330. nread -= (size_t)data->state.resume_from;
  331. data->state.resume_from = 0;
  332. }
  333. }
  334. else
  335. sendbuf = xfer_ulbuf;
  336. /* write the data to the target */
  337. nwrite = write(fd, sendbuf, nread);
  338. if((size_t)nwrite != nread) {
  339. result = CURLE_SEND_ERROR;
  340. break;
  341. }
  342. bytecount += nread;
  343. Curl_pgrsSetUploadCounter(data, bytecount);
  344. if(Curl_pgrsUpdate(data))
  345. result = CURLE_ABORTED_BY_CALLBACK;
  346. else
  347. result = Curl_speedcheck(data, Curl_now());
  348. }
  349. if(!result && Curl_pgrsUpdate(data))
  350. result = CURLE_ABORTED_BY_CALLBACK;
  351. out:
  352. close(fd);
  353. Curl_multi_xfer_ulbuf_release(data, xfer_ulbuf);
  354. return result;
  355. }
  356. /*
  357. * file_do() is the protocol-specific function for the do-phase, separated
  358. * from the connect-phase above. Other protocols merely setup the transfer in
  359. * the do-phase, to have it done in the main transfer loop but since some
  360. * platforms we support do not allow select()ing etc on file handles (as
  361. * opposed to sockets) we instead perform the whole do-operation in this
  362. * function.
  363. */
  364. static CURLcode file_do(struct Curl_easy *data, bool *done)
  365. {
  366. /* This implementation ignores the hostname in conformance with
  367. RFC 1738. Only local files (reachable via the standard file system)
  368. are supported. This means that files on remotely mounted directories
  369. (via NFS, Samba, NT sharing) can be accessed through a file:// URL
  370. */
  371. CURLcode result = CURLE_OK;
  372. struct_stat statbuf; /* struct_stat instead of struct stat just to allow the
  373. Windows version to have a different struct without
  374. having to redefine the simple word 'stat' */
  375. curl_off_t expected_size = -1;
  376. bool size_known;
  377. bool fstated = FALSE;
  378. int fd;
  379. struct FILEPROTO *file;
  380. char *xfer_buf;
  381. size_t xfer_blen;
  382. *done = TRUE; /* unconditionally */
  383. if(data->state.upload)
  384. return file_upload(data);
  385. file = data->req.p.file;
  386. /* get the fd from the connection phase */
  387. fd = file->fd;
  388. /* VMS: This only works reliable for STREAMLF files */
  389. if(-1 != fstat(fd, &statbuf)) {
  390. if(!S_ISDIR(statbuf.st_mode))
  391. expected_size = statbuf.st_size;
  392. /* and store the modification time */
  393. data->info.filetime = statbuf.st_mtime;
  394. fstated = TRUE;
  395. }
  396. if(fstated && !data->state.range && data->set.timecondition &&
  397. !Curl_meets_timecondition(data, data->info.filetime))
  398. return CURLE_OK;
  399. if(fstated) {
  400. time_t filetime;
  401. struct tm buffer;
  402. const struct tm *tm = &buffer;
  403. char header[80];
  404. int headerlen;
  405. static const char accept_ranges[]= { "Accept-ranges: bytes\r\n" };
  406. if(expected_size >= 0) {
  407. headerlen =
  408. msnprintf(header, sizeof(header), "Content-Length: %" FMT_OFF_T "\r\n",
  409. expected_size);
  410. result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen);
  411. if(result)
  412. return result;
  413. result = Curl_client_write(data, CLIENTWRITE_HEADER,
  414. accept_ranges, sizeof(accept_ranges) - 1);
  415. if(result != CURLE_OK)
  416. return result;
  417. }
  418. filetime = (time_t)statbuf.st_mtime;
  419. result = Curl_gmtime(filetime, &buffer);
  420. if(result)
  421. return result;
  422. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  423. headerlen =
  424. msnprintf(header, sizeof(header),
  425. "Last-Modified: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
  426. Curl_wkday[tm->tm_wday ? tm->tm_wday-1 : 6],
  427. tm->tm_mday,
  428. Curl_month[tm->tm_mon],
  429. tm->tm_year + 1900,
  430. tm->tm_hour,
  431. tm->tm_min,
  432. tm->tm_sec);
  433. result = Curl_client_write(data, CLIENTWRITE_HEADER, header, headerlen);
  434. if(!result)
  435. /* end of headers */
  436. result = Curl_client_write(data, CLIENTWRITE_HEADER, "\r\n", 2);
  437. if(result)
  438. return result;
  439. /* set the file size to make it available post transfer */
  440. Curl_pgrsSetDownloadSize(data, expected_size);
  441. if(data->req.no_body)
  442. return CURLE_OK;
  443. }
  444. /* Check whether file range has been specified */
  445. result = Curl_range(data);
  446. if(result)
  447. return result;
  448. /* Adjust the start offset in case we want to get the N last bytes
  449. * of the stream if the filesize could be determined */
  450. if(data->state.resume_from < 0) {
  451. if(!fstated) {
  452. failf(data, "cannot get the size of file.");
  453. return CURLE_READ_ERROR;
  454. }
  455. data->state.resume_from += (curl_off_t)statbuf.st_size;
  456. }
  457. if(data->state.resume_from > 0) {
  458. /* We check explicitly if we have a start offset, because
  459. * expected_size may be -1 if we do not know how large the file is,
  460. * in which case we should not adjust it. */
  461. if(data->state.resume_from <= expected_size)
  462. expected_size -= data->state.resume_from;
  463. else {
  464. failf(data, "failed to resume file:// transfer");
  465. return CURLE_BAD_DOWNLOAD_RESUME;
  466. }
  467. }
  468. /* A high water mark has been specified so we obey... */
  469. if(data->req.maxdownload > 0)
  470. expected_size = data->req.maxdownload;
  471. if(!fstated || (expected_size <= 0))
  472. size_known = FALSE;
  473. else
  474. size_known = TRUE;
  475. /* The following is a shortcut implementation of file reading
  476. this is both more efficient than the former call to download() and
  477. it avoids problems with select() and recv() on file descriptors
  478. in Winsock */
  479. if(size_known)
  480. Curl_pgrsSetDownloadSize(data, expected_size);
  481. if(data->state.resume_from) {
  482. if(!S_ISDIR(statbuf.st_mode)) {
  483. if(data->state.resume_from !=
  484. lseek(fd, data->state.resume_from, SEEK_SET))
  485. return CURLE_BAD_DOWNLOAD_RESUME;
  486. }
  487. else {
  488. return CURLE_BAD_DOWNLOAD_RESUME;
  489. }
  490. }
  491. result = Curl_multi_xfer_buf_borrow(data, &xfer_buf, &xfer_blen);
  492. if(result)
  493. goto out;
  494. if(!S_ISDIR(statbuf.st_mode)) {
  495. while(!result) {
  496. ssize_t nread;
  497. /* Do not fill a whole buffer if we want less than all data */
  498. size_t bytestoread;
  499. if(size_known) {
  500. bytestoread = (expected_size < (curl_off_t)(xfer_blen-1)) ?
  501. curlx_sotouz(expected_size) : (xfer_blen-1);
  502. }
  503. else
  504. bytestoread = xfer_blen-1;
  505. nread = read(fd, xfer_buf, bytestoread);
  506. if(nread > 0)
  507. xfer_buf[nread] = 0;
  508. if(nread <= 0 || (size_known && (expected_size == 0)))
  509. break;
  510. if(size_known)
  511. expected_size -= nread;
  512. result = Curl_client_write(data, CLIENTWRITE_BODY, xfer_buf, nread);
  513. if(result)
  514. goto out;
  515. if(Curl_pgrsUpdate(data))
  516. result = CURLE_ABORTED_BY_CALLBACK;
  517. else
  518. result = Curl_speedcheck(data, Curl_now());
  519. if(result)
  520. goto out;
  521. }
  522. }
  523. else {
  524. #ifdef HAVE_OPENDIR
  525. DIR *dir = opendir(file->path);
  526. struct dirent *entry;
  527. if(!dir) {
  528. result = CURLE_READ_ERROR;
  529. goto out;
  530. }
  531. else {
  532. while((entry = readdir(dir))) {
  533. if(entry->d_name[0] != '.') {
  534. result = Curl_client_write(data, CLIENTWRITE_BODY,
  535. entry->d_name, strlen(entry->d_name));
  536. if(result)
  537. break;
  538. result = Curl_client_write(data, CLIENTWRITE_BODY, "\n", 1);
  539. if(result)
  540. break;
  541. }
  542. }
  543. closedir(dir);
  544. }
  545. #else
  546. failf(data, "Directory listing not yet implemented on this platform.");
  547. result = CURLE_READ_ERROR;
  548. #endif
  549. }
  550. if(Curl_pgrsUpdate(data))
  551. result = CURLE_ABORTED_BY_CALLBACK;
  552. out:
  553. Curl_multi_xfer_buf_release(data, xfer_buf);
  554. return result;
  555. }
  556. #endif