file.c 16 KB

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