storagedir.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /* Copyright (c) 2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "container.h"
  4. #include "compat.h"
  5. #include "confline.h"
  6. #include "memarea.h"
  7. #include "sandbox.h"
  8. #include "storagedir.h"
  9. #include "torlog.h"
  10. #include "util.h"
  11. #ifdef HAVE_SYS_TYPES_H
  12. #include <sys/types.h>
  13. #endif
  14. #ifdef HAVE_SYS_STAT_H
  15. #include <sys/stat.h>
  16. #endif
  17. #ifdef HAVE_UNISTD_H
  18. #include <unistd.h>
  19. #endif
  20. #define FNAME_MIN_NUM 1000
  21. /** A storage_dir_t represents a directory full of similar cached
  22. * files. Filenames are decimal integers. Files can be cleaned as needed
  23. * to limit total disk usage. */
  24. struct storage_dir_t {
  25. /** Directory holding the files for this storagedir. */
  26. char *directory;
  27. /** Either NULL, or a directory listing of the directory (as a smartlist
  28. * of strings */
  29. smartlist_t *contents;
  30. /** The largest number of non-temporary files we'll place in the
  31. * directory. */
  32. int max_files;
  33. /** If true, then 'usage' has been computed. */
  34. int usage_known;
  35. /** The total number of bytes used in this directory */
  36. uint64_t usage;
  37. };
  38. /** Create or open a new storage directory at <b>dirname</b>, with
  39. * capacity for up to <b>max_files</b> files.
  40. */
  41. storage_dir_t *
  42. storage_dir_new(const char *dirname, int max_files)
  43. {
  44. if (check_private_dir(dirname, CPD_CREATE, NULL) < 0)
  45. return NULL;
  46. storage_dir_t *d = tor_malloc_zero(sizeof(storage_dir_t));
  47. d->directory = tor_strdup(dirname);
  48. d->max_files = max_files;
  49. return d;
  50. }
  51. /**
  52. * Drop all in-RAM storage for <b>d</b>. Does not delete any files.
  53. */
  54. void
  55. storage_dir_free(storage_dir_t *d)
  56. {
  57. if (d == NULL)
  58. return;
  59. tor_free(d->directory);
  60. if (d->contents) {
  61. SMARTLIST_FOREACH(d->contents, char *, cp, tor_free(cp));
  62. smartlist_free(d->contents);
  63. }
  64. tor_free(d);
  65. }
  66. /**
  67. * Tell the sandbox (if any) configured by <b>cfg</b> to allow the
  68. * operations that <b>d</b> will need.
  69. *
  70. * The presence of this function is why we need an upper limit on the
  71. * number of files in a storage_dir_t: we need to approve file operations
  72. * one by one.
  73. */
  74. int
  75. storage_dir_register_with_sandbox(storage_dir_t *d, sandbox_cfg_t **cfg)
  76. {
  77. int problems = 0;
  78. int idx;
  79. for (idx = FNAME_MIN_NUM; idx < FNAME_MIN_NUM + d->max_files; ++idx) {
  80. char *path = NULL, *tmppath = NULL;
  81. tor_asprintf(&path, "%s/%d", d->directory, idx);
  82. tor_asprintf(&tmppath, "%s/%d.tmp", d->directory, idx);
  83. problems += sandbox_cfg_allow_open_filename(cfg, tor_strdup(path));
  84. problems += sandbox_cfg_allow_open_filename(cfg, tor_strdup(tmppath));
  85. problems += sandbox_cfg_allow_stat_filename(cfg, tor_strdup(path));
  86. problems += sandbox_cfg_allow_stat_filename(cfg, tor_strdup(tmppath));
  87. problems += sandbox_cfg_allow_rename(cfg,
  88. tor_strdup(tmppath), tor_strdup(path));
  89. tor_free(path);
  90. tor_free(tmppath);
  91. }
  92. return problems ? -1 : 0;
  93. }
  94. /**
  95. * Remove all files in <b>d</b> whose names end with ".tmp".
  96. *
  97. * Requires that the contents field of <b>d</b> is set.
  98. */
  99. static void
  100. storage_dir_clean_tmpfiles(storage_dir_t *d)
  101. {
  102. if (!d->contents)
  103. return;
  104. SMARTLIST_FOREACH_BEGIN(d->contents, char *, fname) {
  105. if (strcmpend(fname, ".tmp"))
  106. continue;
  107. char *path = NULL;
  108. tor_asprintf(&path, "%s/%s", d->directory, fname);
  109. if (unlink(sandbox_intern_string(path))) {
  110. log_warn(LD_FS, "Unable to unlink %s", escaped(path));
  111. tor_free(path);
  112. continue;
  113. }
  114. tor_free(path);
  115. SMARTLIST_DEL_CURRENT(d->contents, fname);
  116. tor_free(fname);
  117. } SMARTLIST_FOREACH_END(fname);
  118. d->usage_known = 0;
  119. }
  120. /**
  121. * Re-scan the directory <b>d</b> to learn its contents.
  122. */
  123. static int
  124. storage_dir_rescan(storage_dir_t *d)
  125. {
  126. if (d->contents) {
  127. SMARTLIST_FOREACH(d->contents, char *, cp, tor_free(cp));
  128. smartlist_free(d->contents);
  129. }
  130. d->usage = 0;
  131. d->usage_known = 0;
  132. if (NULL == (d->contents = tor_listdir(d->directory))) {
  133. return -1;
  134. }
  135. storage_dir_clean_tmpfiles(d);
  136. return 0;
  137. }
  138. /**
  139. * Return a smartlist containing the filenames within <b>d</b>.
  140. */
  141. const smartlist_t *
  142. storage_dir_list(storage_dir_t *d)
  143. {
  144. if (! d->contents)
  145. storage_dir_rescan(d);
  146. return d->contents;
  147. }
  148. /**
  149. * Return the total number of bytes used for storage in <b>d</b>.
  150. */
  151. uint64_t
  152. storage_dir_get_usage(storage_dir_t *d)
  153. {
  154. if (d->usage_known)
  155. return d->usage;
  156. uint64_t total = 0;
  157. SMARTLIST_FOREACH_BEGIN(storage_dir_list(d), const char *, cp) {
  158. char *path = NULL;
  159. struct stat st;
  160. tor_asprintf(&path, "%s/%s", d->directory, cp);
  161. if (stat(sandbox_intern_string(path), &st) == 0) {
  162. total += st.st_size;
  163. }
  164. tor_free(path);
  165. } SMARTLIST_FOREACH_END(cp);
  166. d->usage = total;
  167. d->usage_known = 1;
  168. return d->usage;
  169. }
  170. /** Mmap a specified file within <b>d</b>. */
  171. tor_mmap_t *
  172. storage_dir_map(storage_dir_t *d, const char *fname)
  173. {
  174. char *path = NULL;
  175. tor_asprintf(&path, "%s/%s", d->directory, fname);
  176. tor_mmap_t *result = tor_mmap_file(path);
  177. tor_free(path);
  178. return result;
  179. }
  180. /** Read a file within <b>d</b> into a newly allocated buffer. Set
  181. * *<b>sz_out</b> to its size. */
  182. uint8_t *
  183. storage_dir_read(storage_dir_t *d, const char *fname, int bin, size_t *sz_out)
  184. {
  185. const int flags = bin ? RFTS_BIN : 0;
  186. char *path = NULL;
  187. tor_asprintf(&path, "%s/%s", d->directory, fname);
  188. struct stat st;
  189. char *contents = read_file_to_str(path, flags, &st);
  190. if (contents && sz_out) {
  191. // it fits in RAM, so we know its size is less than SIZE_MAX
  192. #if UINT64_MAX > SIZE_MAX
  193. tor_assert((uint64_t)st.st_size <= SIZE_MAX);
  194. #endif
  195. *sz_out = (size_t) st.st_size;
  196. }
  197. tor_free(path);
  198. return (uint8_t *) contents;
  199. }
  200. /** Helper: Find an unused filename within the directory */
  201. static char *
  202. find_unused_fname(storage_dir_t *d)
  203. {
  204. if (!d->contents) {
  205. if (storage_dir_rescan(d) < 0)
  206. return NULL;
  207. }
  208. char buf[16];
  209. int i;
  210. /* Yuck; this is quadratic. Fortunately, that shouldn't matter much,
  211. * since disk writes are more expensive by a lot. */
  212. for (i = FNAME_MIN_NUM; i < FNAME_MIN_NUM + d->max_files; ++i) {
  213. tor_snprintf(buf, sizeof(buf), "%d", i);
  214. if (!smartlist_contains_string(d->contents, buf)) {
  215. return tor_strdup(buf);
  216. }
  217. }
  218. return NULL;
  219. }
  220. /** Helper: As storage_dir_save_bytes_to_file, but store a smartlist of
  221. * sized_chunk_t rather than a single byte array. */
  222. static int
  223. storage_dir_save_chunks_to_file(storage_dir_t *d,
  224. const smartlist_t *chunks,
  225. int binary,
  226. char **fname_out)
  227. {
  228. uint64_t total_length = 0;
  229. char *fname = find_unused_fname(d);
  230. if (!fname)
  231. return -1;
  232. SMARTLIST_FOREACH(chunks, const sized_chunk_t *, ch,
  233. total_length += ch->len);
  234. char *path = NULL;
  235. tor_asprintf(&path, "%s/%s", d->directory, fname);
  236. int r = write_chunks_to_file(path, chunks, binary, 0);
  237. if (r == 0) {
  238. if (d->usage_known)
  239. d->usage += total_length;
  240. if (fname_out) {
  241. *fname_out = tor_strdup(fname);
  242. }
  243. if (d->contents)
  244. smartlist_add(d->contents, tor_strdup(fname));
  245. }
  246. tor_free(fname);
  247. tor_free(path);
  248. return r;
  249. }
  250. /** Try to write the <b>length</b> bytes at <b>data</b> into a new file
  251. * in <b>d</b>. On success, return 0 and set *<b>fname_out</b> to a
  252. * newly allocated string containing the filename. On failure, return
  253. * -1. */
  254. int
  255. storage_dir_save_bytes_to_file(storage_dir_t *d,
  256. const uint8_t *data,
  257. size_t length,
  258. int binary,
  259. char **fname_out)
  260. {
  261. smartlist_t *chunks = smartlist_new();
  262. sized_chunk_t chunk = { (const char *)data, length };
  263. smartlist_add(chunks, &chunk);
  264. int r = storage_dir_save_chunks_to_file(d, chunks, binary, fname_out);
  265. smartlist_free(chunks);
  266. return r;
  267. }
  268. /**
  269. * As storage_dir_save_bytes_to_file, but saves a NUL-terminated string
  270. * <b>str</b>.
  271. */
  272. int
  273. storage_dir_save_string_to_file(storage_dir_t *d,
  274. const char *str,
  275. int binary,
  276. char **fname_out)
  277. {
  278. return storage_dir_save_bytes_to_file(d,
  279. (const uint8_t*)str, strlen(str), binary, fname_out);
  280. }
  281. /**
  282. * As storage_dir_save_bytes_to_file, but associates the data with the
  283. * key-value pairs in <b>labels</b>. Files stored in this format can be
  284. * recovered with storage_dir_map_labeled() or storage_dir_read_labeled().
  285. */
  286. int
  287. storage_dir_save_labeled_to_file(storage_dir_t *d,
  288. const config_line_t *labels,
  289. const uint8_t *data,
  290. size_t length,
  291. char **fname_out)
  292. {
  293. /*
  294. * The storage format is to prefix the data with the key-value pairs in
  295. * <b>labels</b>, and a single NUL separator. But code outside this module
  296. * MUST NOT rely on that format.
  297. */
  298. smartlist_t *chunks = smartlist_new();
  299. memarea_t *area = memarea_new();
  300. const config_line_t *line;
  301. for (line = labels; line; line = line->next) {
  302. sized_chunk_t *sz = memarea_alloc(area, sizeof(sized_chunk_t));
  303. sz->len = strlen(line->key) + 1 + strlen(line->value) + 1;
  304. const size_t allocated = sz->len + 1;
  305. char *bytes = memarea_alloc(area, allocated);
  306. tor_snprintf(bytes, allocated, "%s %s\n", line->key, line->value);
  307. sz->bytes = bytes;
  308. smartlist_add(chunks, sz);
  309. }
  310. sized_chunk_t *nul = memarea_alloc(area, sizeof(sized_chunk_t));
  311. nul->len = 1;
  312. nul->bytes = "\0";
  313. smartlist_add(chunks, nul);
  314. sized_chunk_t *datachunk = memarea_alloc(area, sizeof(sized_chunk_t));
  315. datachunk->bytes = (const char *)data;
  316. datachunk->len = length;
  317. smartlist_add(chunks, datachunk);
  318. int r = storage_dir_save_chunks_to_file(d, chunks, 1, fname_out);
  319. smartlist_free(chunks);
  320. memarea_drop_all(area);
  321. return r;
  322. }
  323. /**
  324. * Map a file that was created with storage_dir_save_labeled_to_file(). On
  325. * failure, return NULL. On success, write a set of newly allocated labels
  326. * into *<b>labels_out</b>, a pointer to the data into *<b>data_out</b>, and
  327. * the data's size into *<b>sz_out</b>. On success, also return a tor_mmap_t
  328. * object whose contents should not be used -- it needs to be kept around,
  329. * though, for as long as <b>data_out</b> is going to be valid.
  330. */
  331. tor_mmap_t *
  332. storage_dir_map_labeled(storage_dir_t *dir,
  333. const char *fname,
  334. config_line_t **labels_out,
  335. const uint8_t **data_out,
  336. size_t *sz_out)
  337. {
  338. tor_mmap_t *m = storage_dir_map(dir, fname);
  339. if (! m)
  340. goto err;
  341. const char *nulp = memchr(m->data, '\0', m->size);
  342. if (! nulp)
  343. goto err;
  344. if (labels_out && config_get_lines(m->data, labels_out, 0) < 0)
  345. goto err;
  346. size_t offset = nulp - m->data + 1;
  347. tor_assert(offset <= m->size);
  348. *data_out = (const uint8_t *)(m->data + offset);
  349. *sz_out = m->size - offset;
  350. return m;
  351. err:
  352. tor_munmap_file(m);
  353. return NULL;
  354. }
  355. /** As storage_dir_map_labeled, but return a new byte array containing the
  356. * data. */
  357. uint8_t *
  358. storage_dir_read_labeled(storage_dir_t *dir,
  359. const char *fname,
  360. config_line_t **labels_out,
  361. size_t *sz_out)
  362. {
  363. const uint8_t *data = NULL;
  364. tor_mmap_t *m = storage_dir_map_labeled(dir, fname, labels_out,
  365. &data, sz_out);
  366. if (m == NULL)
  367. return NULL;
  368. uint8_t *result = tor_memdup(data, *sz_out);
  369. tor_munmap_file(m);
  370. return result;
  371. }
  372. /* Reduce the cached usage amount in <b>d</b> by <b>removed_file_size</b>.
  373. * This function is a no-op if <b>d->usage_known</b> is 0. */
  374. static void
  375. storage_dir_reduce_usage(storage_dir_t *d, uint64_t removed_file_size)
  376. {
  377. if (d->usage_known) {
  378. if (! BUG(d->usage < removed_file_size)) {
  379. /* This bug can also be triggered if an external process resized a file
  380. * between the call to storage_dir_get_usage() that last checked
  381. * actual usage (rather than relaying on cached usage), and the call to
  382. * this function. */
  383. d->usage -= removed_file_size;
  384. } else {
  385. /* If we underflowed the cached directory size, re-check the sizes of all
  386. * the files in the directory. This makes storage_dir_shrink() quadratic,
  387. * but only if a process is continually changing file sizes in the
  388. * storage directory (in which case, we have bigger issues).
  389. *
  390. * We can't just reset usage_known, because storage_dir_shrink() relies
  391. * on knowing the usage. */
  392. storage_dir_rescan(d);
  393. (void)storage_dir_get_usage(d);
  394. }
  395. }
  396. }
  397. /**
  398. * Remove the file called <b>fname</b> from <b>d</b>.
  399. */
  400. void
  401. storage_dir_remove_file(storage_dir_t *d,
  402. const char *fname)
  403. {
  404. char *path = NULL;
  405. tor_asprintf(&path, "%s/%s", d->directory, fname);
  406. const char *ipath = sandbox_intern_string(path);
  407. uint64_t size = 0;
  408. if (d->usage_known) {
  409. struct stat st;
  410. if (stat(ipath, &st) == 0) {
  411. size = st.st_size;
  412. }
  413. }
  414. if (unlink(ipath) == 0) {
  415. storage_dir_reduce_usage(d, size);
  416. } else {
  417. log_warn(LD_FS, "Unable to unlink %s", escaped(path));
  418. tor_free(path);
  419. return;
  420. }
  421. if (d->contents) {
  422. smartlist_string_remove(d->contents, fname);
  423. }
  424. tor_free(path);
  425. }
  426. /** Helper type: used to sort the members of storage directory by mtime. */
  427. typedef struct shrinking_dir_entry_t {
  428. time_t mtime;
  429. uint64_t size;
  430. char *path;
  431. } shrinking_dir_entry_t;
  432. /** Helper: use with qsort to sort shrinking_dir_entry_t structs. */
  433. static int
  434. shrinking_dir_entry_compare(const void *a_, const void *b_)
  435. {
  436. const shrinking_dir_entry_t *a = a_;
  437. const shrinking_dir_entry_t *b = b_;
  438. if (a->mtime < b->mtime)
  439. return -1;
  440. else if (a->mtime > b->mtime)
  441. return 1;
  442. else
  443. return 0;
  444. }
  445. /**
  446. * Try to free space by removing the oldest files in <b>d</b>. Delete
  447. * until no more than <b>target_size</b> bytes are left, and at least
  448. * <b>min_to_remove</b> files have been removed... or until there is
  449. * nothing left to remove.
  450. *
  451. * Return 0 on success; -1 on failure.
  452. */
  453. int
  454. storage_dir_shrink(storage_dir_t *d,
  455. uint64_t target_size,
  456. int min_to_remove)
  457. {
  458. if (d->usage_known && d->usage <= target_size && !min_to_remove) {
  459. /* Already small enough. */
  460. return 0;
  461. }
  462. if (storage_dir_rescan(d) < 0)
  463. return -1;
  464. const uint64_t orig_usage = storage_dir_get_usage(d);
  465. if (orig_usage <= target_size && !min_to_remove) {
  466. /* Okay, small enough after rescan! */
  467. return 0;
  468. }
  469. const int n = smartlist_len(d->contents);
  470. shrinking_dir_entry_t *ents = tor_calloc(n, sizeof(shrinking_dir_entry_t));
  471. SMARTLIST_FOREACH_BEGIN(d->contents, const char *, fname) {
  472. shrinking_dir_entry_t *ent = &ents[fname_sl_idx];
  473. struct stat st;
  474. tor_asprintf(&ent->path, "%s/%s", d->directory, fname);
  475. if (stat(sandbox_intern_string(ent->path), &st) == 0) {
  476. ent->mtime = st.st_mtime;
  477. ent->size = st.st_size;
  478. }
  479. } SMARTLIST_FOREACH_END(fname);
  480. qsort(ents, n, sizeof(shrinking_dir_entry_t), shrinking_dir_entry_compare);
  481. int idx = 0;
  482. while ((d->usage > target_size || min_to_remove > 0) && idx < n) {
  483. if (unlink(sandbox_intern_string(ents[idx].path)) == 0) {
  484. storage_dir_reduce_usage(d, ents[idx].size);
  485. --min_to_remove;
  486. }
  487. ++idx;
  488. }
  489. for (idx = 0; idx < n; ++idx) {
  490. tor_free(ents[idx].path);
  491. }
  492. tor_free(ents);
  493. storage_dir_rescan(d);
  494. return 0;
  495. }
  496. /** Remove all files in <b>d</b>. */
  497. int
  498. storage_dir_remove_all(storage_dir_t *d)
  499. {
  500. return storage_dir_shrink(d, 0, d->max_files);
  501. }
  502. /**
  503. * Return the largest number of non-temporary files we're willing to
  504. * store in <b>d</b>.
  505. */
  506. int
  507. storage_dir_get_max_files(storage_dir_t *d)
  508. {
  509. return d->max_files;
  510. }