file.c 16 KB

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