files.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #ifdef _WIN32
  6. #include <windows.h>
  7. #endif
  8. #include "lib/fs/files.h"
  9. #include "lib/fs/path.h"
  10. #include "lib/container/smartlist.h"
  11. #include "lib/log/torlog.h"
  12. #include "lib/log/util_bug.h"
  13. #include "lib/log/escape.h"
  14. #include "lib/err/torerr.h"
  15. #include "lib/malloc/util_malloc.h"
  16. #include "lib/sandbox/sandbox.h"
  17. #include "lib/string/printf.h"
  18. #include "lib/string/util_string.h"
  19. #include "lib/fdio/fdio.h"
  20. #ifdef HAVE_SYS_TYPES_H
  21. #include <sys/types.h>
  22. #endif
  23. #ifdef HAVE_SYS_STAT_H
  24. #include <sys/stat.h>
  25. #endif
  26. #ifdef HAVE_UTIME_H
  27. #include <utime.h>
  28. #endif
  29. #ifdef HAVE_SYS_TIME_H
  30. #include <sys/time.h>
  31. #endif
  32. #ifdef HAVE_FCNTL_H
  33. #include <fcntl.h>
  34. #endif
  35. #ifdef HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #include <errno.h>
  39. #include <stdio.h>
  40. #include <string.h>
  41. /** As open(path, flags, mode), but return an fd with the close-on-exec mode
  42. * set. */
  43. int
  44. tor_open_cloexec(const char *path, int flags, unsigned mode)
  45. {
  46. int fd;
  47. const char *p = sandbox_intern_string(path);
  48. #ifdef O_CLOEXEC
  49. fd = open(p, flags|O_CLOEXEC, mode);
  50. if (fd >= 0)
  51. return fd;
  52. /* If we got an error, see if it is EINVAL. EINVAL might indicate that,
  53. * even though we were built on a system with O_CLOEXEC support, we
  54. * are running on one without. */
  55. if (errno != EINVAL)
  56. return -1;
  57. #endif /* defined(O_CLOEXEC) */
  58. log_debug(LD_FS, "Opening %s with flags %x", p, flags);
  59. fd = open(p, flags, mode);
  60. #ifdef FD_CLOEXEC
  61. if (fd >= 0) {
  62. if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
  63. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  64. close(fd);
  65. return -1;
  66. }
  67. }
  68. #endif /* defined(FD_CLOEXEC) */
  69. return fd;
  70. }
  71. /** As fopen(path,mode), but ensures that the O_CLOEXEC bit is set on the
  72. * underlying file handle. */
  73. FILE *
  74. tor_fopen_cloexec(const char *path, const char *mode)
  75. {
  76. FILE *result = fopen(path, mode);
  77. #ifdef FD_CLOEXEC
  78. if (result != NULL) {
  79. if (fcntl(fileno(result), F_SETFD, FD_CLOEXEC) == -1) {
  80. log_warn(LD_FS,"Couldn't set FD_CLOEXEC: %s", strerror(errno));
  81. fclose(result);
  82. return NULL;
  83. }
  84. }
  85. #endif /* defined(FD_CLOEXEC) */
  86. return result;
  87. }
  88. /** As rename(), but work correctly with the sandbox. */
  89. int
  90. tor_rename(const char *path_old, const char *path_new)
  91. {
  92. log_debug(LD_FS, "Renaming %s to %s", path_old, path_new);
  93. return rename(sandbox_intern_string(path_old),
  94. sandbox_intern_string(path_new));
  95. }
  96. /**
  97. * Rename the file <b>from</b> to the file <b>to</b>. On Unix, this is
  98. * the same as rename(2). On windows, this removes <b>to</b> first if
  99. * it already exists.
  100. * Returns 0 on success. Returns -1 and sets errno on failure.
  101. */
  102. int
  103. replace_file(const char *from, const char *to)
  104. {
  105. #ifndef _WIN32
  106. return tor_rename(from, to);
  107. #else
  108. switch (file_status(to))
  109. {
  110. case FN_NOENT:
  111. break;
  112. case FN_FILE:
  113. case FN_EMPTY:
  114. if (unlink(to)) return -1;
  115. break;
  116. case FN_ERROR:
  117. return -1;
  118. case FN_DIR:
  119. errno = EISDIR;
  120. return -1;
  121. }
  122. return tor_rename(from,to);
  123. #endif /* !defined(_WIN32) */
  124. }
  125. /** Change <b>fname</b>'s modification time to now. */
  126. int
  127. touch_file(const char *fname)
  128. {
  129. if (utime(fname, NULL)!=0)
  130. return -1;
  131. return 0;
  132. }
  133. /** Wrapper for unlink() to make it mockable for the test suite; returns 0
  134. * if unlinking the file succeeded, -1 and sets errno if unlinking fails.
  135. */
  136. MOCK_IMPL(int,
  137. tor_unlink,(const char *pathname))
  138. {
  139. return unlink(pathname);
  140. }
  141. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. Return the number
  142. * of bytes written, or -1 on error. Only use if fd is a blocking fd. */
  143. ssize_t
  144. write_all_to_fd(int fd, const char *buf, size_t count)
  145. {
  146. size_t written = 0;
  147. ssize_t result;
  148. raw_assert(count < SSIZE_MAX);
  149. while (written != count) {
  150. result = write(fd, buf+written, count-written);
  151. if (result<0)
  152. return -1;
  153. written += result;
  154. }
  155. return (ssize_t)count;
  156. }
  157. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes or
  158. * reach the end of the file. Return the number of bytes read, or -1 on
  159. * error. Only use if fd is a blocking fd. */
  160. ssize_t
  161. read_all_from_fd(int fd, char *buf, size_t count)
  162. {
  163. size_t numread = 0;
  164. ssize_t result;
  165. if (count > SIZE_T_CEILING || count > SSIZE_MAX) {
  166. errno = EINVAL;
  167. return -1;
  168. }
  169. while (numread < count) {
  170. result = read(fd, buf+numread, count-numread);
  171. if (result<0)
  172. return -1;
  173. else if (result == 0)
  174. break;
  175. numread += result;
  176. }
  177. return (ssize_t)numread;
  178. }
  179. /** Return:
  180. * FN_ERROR if filename can't be read, is NULL, or is zero-length,
  181. * FN_NOENT if it doesn't exist,
  182. * FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems,
  183. * FN_EMPTY for zero-byte regular files,
  184. * FN_DIR if it's a directory, and
  185. * FN_ERROR for any other file type.
  186. * On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR
  187. * is returned due to an unhandled file type.) */
  188. file_status_t
  189. file_status(const char *fname)
  190. {
  191. struct stat st;
  192. char *f;
  193. int r;
  194. if (!fname || strlen(fname) == 0) {
  195. return FN_ERROR;
  196. }
  197. f = tor_strdup(fname);
  198. clean_fname_for_stat(f);
  199. log_debug(LD_FS, "stat()ing %s", f);
  200. r = stat(sandbox_intern_string(f), &st);
  201. tor_free(f);
  202. if (r) {
  203. if (errno == ENOENT) {
  204. return FN_NOENT;
  205. }
  206. return FN_ERROR;
  207. }
  208. if (st.st_mode & S_IFDIR) {
  209. return FN_DIR;
  210. } else if (st.st_mode & S_IFREG) {
  211. if (st.st_size > 0) {
  212. return FN_FILE;
  213. } else if (st.st_size == 0) {
  214. return FN_EMPTY;
  215. } else {
  216. return FN_ERROR;
  217. }
  218. #ifndef _WIN32
  219. } else if (st.st_mode & S_IFIFO) {
  220. return FN_FILE;
  221. #endif
  222. } else {
  223. return FN_ERROR;
  224. }
  225. }
  226. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  227. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  228. *
  229. * This function replaces the old file atomically, if possible. This
  230. * function, and all other functions in util.c that create files, create them
  231. * with mode 0600.
  232. */
  233. MOCK_IMPL(int,
  234. write_str_to_file,(const char *fname, const char *str, int bin))
  235. {
  236. #ifdef _WIN32
  237. if (!bin && strchr(str, '\r')) {
  238. log_warn(LD_BUG,
  239. "We're writing a text string that already contains a CR to %s",
  240. escaped(fname));
  241. }
  242. #endif /* defined(_WIN32) */
  243. return write_bytes_to_file(fname, str, strlen(str), bin);
  244. }
  245. /** Represents a file that we're writing to, with support for atomic commit:
  246. * we can write into a temporary file, and either remove the file on
  247. * failure, or replace the original file on success. */
  248. struct open_file_t {
  249. char *tempname; /**< Name of the temporary file. */
  250. char *filename; /**< Name of the original file. */
  251. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  252. unsigned binary:1; /**< Did we open in binary mode? */
  253. int fd; /**< fd for the open file. */
  254. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  255. };
  256. /** Try to start writing to the file in <b>fname</b>, passing the flags
  257. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  258. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  259. * original file. Otherwise, we open a new temporary file in the same
  260. * directory, and either replace the original or remove the temporary file
  261. * when we're done.
  262. *
  263. * Return the fd for the newly opened file, and store working data in
  264. * *<b>data_out</b>. The caller should not close the fd manually:
  265. * instead, call finish_writing_to_file() or abort_writing_to_file().
  266. * Returns -1 on failure.
  267. *
  268. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  269. * as true and the flag O_EXCL is treated as false.
  270. *
  271. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  272. * write()". We don't do that.
  273. */
  274. int
  275. start_writing_to_file(const char *fname, int open_flags, int mode,
  276. open_file_t **data_out)
  277. {
  278. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  279. const char *open_name;
  280. int append = 0;
  281. tor_assert(fname);
  282. tor_assert(data_out);
  283. #if (O_BINARY != 0 && O_TEXT != 0)
  284. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  285. #endif
  286. new_file->fd = -1;
  287. new_file->filename = tor_strdup(fname);
  288. if (open_flags & O_APPEND) {
  289. open_name = fname;
  290. new_file->rename_on_close = 0;
  291. append = 1;
  292. open_flags &= ~O_APPEND;
  293. } else {
  294. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  295. open_name = new_file->tempname;
  296. /* We always replace an existing temporary file if there is one. */
  297. open_flags |= O_CREAT|O_TRUNC;
  298. open_flags &= ~O_EXCL;
  299. new_file->rename_on_close = 1;
  300. }
  301. #if O_BINARY != 0
  302. if (open_flags & O_BINARY)
  303. new_file->binary = 1;
  304. #endif
  305. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  306. if (new_file->fd < 0) {
  307. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  308. open_name, fname, strerror(errno));
  309. goto err;
  310. }
  311. if (append) {
  312. if (tor_fd_seekend(new_file->fd) < 0) {
  313. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  314. strerror(errno));
  315. goto err;
  316. }
  317. }
  318. *data_out = new_file;
  319. return new_file->fd;
  320. err:
  321. if (new_file->fd >= 0)
  322. close(new_file->fd);
  323. *data_out = NULL;
  324. tor_free(new_file->filename);
  325. tor_free(new_file->tempname);
  326. tor_free(new_file);
  327. return -1;
  328. }
  329. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  330. * that can be used to write to the same file. The caller should not mix
  331. * stdio calls with non-stdio calls. */
  332. FILE *
  333. fdopen_file(open_file_t *file_data)
  334. {
  335. tor_assert(file_data);
  336. if (file_data->stdio_file)
  337. return file_data->stdio_file;
  338. tor_assert(file_data->fd >= 0);
  339. if (!(file_data->stdio_file = fdopen(file_data->fd,
  340. file_data->binary?"ab":"a"))) {
  341. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  342. file_data->fd, strerror(errno));
  343. }
  344. return file_data->stdio_file;
  345. }
  346. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  347. * for start_writing_to_file, but */
  348. FILE *
  349. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  350. open_file_t **data_out)
  351. {
  352. FILE *res;
  353. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  354. return NULL;
  355. if (!(res = fdopen_file(*data_out))) {
  356. abort_writing_to_file(*data_out);
  357. *data_out = NULL;
  358. }
  359. return res;
  360. }
  361. /** Helper function: close and free the underlying file and memory in
  362. * <b>file_data</b>. If we were writing into a temporary file, then delete
  363. * that file (if abort_write is true) or replaces the target file with
  364. * the temporary file (if abort_write is false). */
  365. static int
  366. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  367. {
  368. int r = 0;
  369. tor_assert(file_data && file_data->filename);
  370. if (file_data->stdio_file) {
  371. if (fclose(file_data->stdio_file)) {
  372. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  373. strerror(errno));
  374. abort_write = r = -1;
  375. }
  376. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  377. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  378. strerror(errno));
  379. abort_write = r = -1;
  380. }
  381. if (file_data->rename_on_close) {
  382. tor_assert(file_data->tempname && file_data->filename);
  383. if (!abort_write) {
  384. tor_assert(strcmp(file_data->filename, file_data->tempname));
  385. if (replace_file(file_data->tempname, file_data->filename)) {
  386. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  387. strerror(errno));
  388. abort_write = r = -1;
  389. }
  390. }
  391. if (abort_write) {
  392. int res = unlink(file_data->tempname);
  393. if (res != 0) {
  394. /* We couldn't unlink and we'll leave a mess behind */
  395. log_warn(LD_FS, "Failed to unlink %s: %s",
  396. file_data->tempname, strerror(errno));
  397. r = -1;
  398. }
  399. }
  400. }
  401. tor_free(file_data->filename);
  402. tor_free(file_data->tempname);
  403. tor_free(file_data);
  404. return r;
  405. }
  406. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  407. * needed, and if using a temporary file, replace the original file with
  408. * the temporary file. */
  409. int
  410. finish_writing_to_file(open_file_t *file_data)
  411. {
  412. return finish_writing_to_file_impl(file_data, 0);
  413. }
  414. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  415. * needed, and if using a temporary file, delete it. */
  416. int
  417. abort_writing_to_file(open_file_t *file_data)
  418. {
  419. return finish_writing_to_file_impl(file_data, 1);
  420. }
  421. /** Helper: given a set of flags as passed to open(2), open the file
  422. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  423. * the file. Do so as atomically as possible e.g. by opening temp files and
  424. * renaming. */
  425. static int
  426. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  427. int open_flags)
  428. {
  429. open_file_t *file = NULL;
  430. int fd;
  431. ssize_t result;
  432. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  433. if (fd<0)
  434. return -1;
  435. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  436. {
  437. result = write_all_to_fd(fd, chunk->bytes, chunk->len);
  438. if (result < 0) {
  439. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  440. strerror(errno));
  441. goto err;
  442. }
  443. tor_assert((size_t)result == chunk->len);
  444. });
  445. return finish_writing_to_file(file);
  446. err:
  447. abort_writing_to_file(file);
  448. return -1;
  449. }
  450. /** Given a smartlist of sized_chunk_t, write them to a file
  451. * <b>fname</b>, overwriting or creating the file as necessary.
  452. * If <b>no_tempfile</b> is 0 then the file will be written
  453. * atomically. */
  454. int
  455. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin,
  456. int no_tempfile)
  457. {
  458. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  459. if (no_tempfile) {
  460. /* O_APPEND stops write_chunks_to_file from using tempfiles */
  461. flags |= O_APPEND;
  462. }
  463. return write_chunks_to_file_impl(fname, chunks, flags);
  464. }
  465. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  466. using the open() flags passed in <b>flags</b>. */
  467. static int
  468. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  469. int flags)
  470. {
  471. int r;
  472. sized_chunk_t c = { str, len };
  473. smartlist_t *chunks = smartlist_new();
  474. smartlist_add(chunks, &c);
  475. r = write_chunks_to_file_impl(fname, chunks, flags);
  476. smartlist_free(chunks);
  477. return r;
  478. }
  479. /** As write_str_to_file, but does not assume a NUL-terminated
  480. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  481. MOCK_IMPL(int,
  482. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  483. int bin))
  484. {
  485. return write_bytes_to_file_impl(fname, str, len,
  486. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  487. }
  488. /** As write_bytes_to_file, but if the file already exists, append the bytes
  489. * to the end of the file instead of overwriting it. */
  490. int
  491. append_bytes_to_file(const char *fname, const char *str, size_t len,
  492. int bin)
  493. {
  494. return write_bytes_to_file_impl(fname, str, len,
  495. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  496. }
  497. /** Like write_str_to_file(), but also return -1 if there was a file
  498. already residing in <b>fname</b>. */
  499. int
  500. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  501. int bin)
  502. {
  503. return write_bytes_to_file_impl(fname, str, len,
  504. OPEN_FLAGS_DONT_REPLACE|
  505. (bin?O_BINARY:O_TEXT));
  506. }
  507. /**
  508. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  509. * (or similar) file descriptor for which the size of the file isn't
  510. * known ahead of time. Return NULL on failure, and a NUL-terminated
  511. * string on success. On success, set <b>sz_out</b> to the number of
  512. * bytes read.
  513. */
  514. char *
  515. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  516. {
  517. ssize_t r;
  518. size_t pos = 0;
  519. char *string = NULL;
  520. size_t string_max = 0;
  521. if (max_bytes_to_read+1 >= SIZE_T_CEILING) {
  522. errno = EINVAL;
  523. return NULL;
  524. }
  525. do {
  526. /* XXXX This "add 1K" approach is a little goofy; if we care about
  527. * performance here, we should be doubling. But in practice we shouldn't
  528. * be using this function on big files anyway. */
  529. string_max = pos + 1024;
  530. if (string_max > max_bytes_to_read)
  531. string_max = max_bytes_to_read + 1;
  532. string = tor_realloc(string, string_max);
  533. r = read(fd, string + pos, string_max - pos - 1);
  534. if (r < 0) {
  535. int save_errno = errno;
  536. tor_free(string);
  537. errno = save_errno;
  538. return NULL;
  539. }
  540. pos += r;
  541. } while (r > 0 && pos < max_bytes_to_read);
  542. tor_assert(pos < string_max);
  543. *sz_out = pos;
  544. string[pos] = '\0';
  545. return string;
  546. }
  547. /** Read the contents of <b>filename</b> into a newly allocated
  548. * string; return the string on success or NULL on failure.
  549. *
  550. * If <b>stat_out</b> is provided, store the result of stat()ing the
  551. * file into <b>stat_out</b>.
  552. *
  553. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  554. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  555. * doesn't exist.
  556. */
  557. /*
  558. * This function <em>may</em> return an erroneous result if the file
  559. * is modified while it is running, but must not crash or overflow.
  560. * Right now, the error case occurs when the file length grows between
  561. * the call to stat and the call to read_all: the resulting string will
  562. * be truncated.
  563. */
  564. MOCK_IMPL(char *,
  565. read_file_to_str, (const char *filename, int flags, struct stat *stat_out))
  566. {
  567. int fd; /* router file */
  568. struct stat statbuf;
  569. char *string;
  570. ssize_t r;
  571. int bin = flags & RFTS_BIN;
  572. tor_assert(filename);
  573. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  574. if (fd<0) {
  575. int severity = LOG_WARN;
  576. int save_errno = errno;
  577. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  578. severity = LOG_INFO;
  579. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  580. strerror(errno));
  581. errno = save_errno;
  582. return NULL;
  583. }
  584. if (fstat(fd, &statbuf)<0) {
  585. int save_errno = errno;
  586. close(fd);
  587. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  588. errno = save_errno;
  589. return NULL;
  590. }
  591. #ifndef _WIN32
  592. /** When we detect that we're reading from a FIFO, don't read more than
  593. * this many bytes. It's insane overkill for most uses. */
  594. #define FIFO_READ_MAX (1024*1024)
  595. if (S_ISFIFO(statbuf.st_mode)) {
  596. size_t sz = 0;
  597. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  598. int save_errno = errno;
  599. if (string && stat_out) {
  600. statbuf.st_size = sz;
  601. memcpy(stat_out, &statbuf, sizeof(struct stat));
  602. }
  603. close(fd);
  604. if (!string)
  605. errno = save_errno;
  606. return string;
  607. }
  608. #endif /* !defined(_WIN32) */
  609. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  610. close(fd);
  611. errno = EINVAL;
  612. return NULL;
  613. }
  614. string = tor_malloc((size_t)(statbuf.st_size+1));
  615. r = read_all_from_fd(fd,string,(size_t)statbuf.st_size);
  616. if (r<0) {
  617. int save_errno = errno;
  618. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  619. strerror(errno));
  620. tor_free(string);
  621. close(fd);
  622. errno = save_errno;
  623. return NULL;
  624. }
  625. string[r] = '\0'; /* NUL-terminate the result. */
  626. #if defined(_WIN32) || defined(__CYGWIN__)
  627. if (!bin && strchr(string, '\r')) {
  628. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  629. "when reading %s. Coping.",
  630. filename);
  631. tor_strstrip(string, "\r");
  632. r = strlen(string);
  633. }
  634. if (!bin) {
  635. statbuf.st_size = (size_t) r;
  636. } else
  637. #endif /* defined(_WIN32) || defined(__CYGWIN__) */
  638. if (r != statbuf.st_size) {
  639. /* Unless we're using text mode on win32, we'd better have an exact
  640. * match for size. */
  641. int save_errno = errno;
  642. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  643. (int)r, (long)statbuf.st_size,filename);
  644. tor_free(string);
  645. close(fd);
  646. errno = save_errno;
  647. return NULL;
  648. }
  649. close(fd);
  650. if (stat_out) {
  651. memcpy(stat_out, &statbuf, sizeof(struct stat));
  652. }
  653. return string;
  654. }