storagedir.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 filers in a storage_dir_t: we need to approve file
  72. * operaitons 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, path);
  84. problems += sandbox_cfg_allow_open_filename(cfg, tmppath);
  85. problems += sandbox_cfg_allow_stat_filename(cfg, path);
  86. problems += sandbox_cfg_allow_stat_filename(cfg, tmppath);
  87. problems += sandbox_cfg_allow_rename(cfg, tmppath, path);
  88. tor_free(path);
  89. tor_free(tmppath);
  90. }
  91. return problems ? -1 : 0;
  92. }
  93. /**
  94. * Remove all files in <b>d</b> whose names end with ".tmp".
  95. *
  96. * Requires that the contents field of <b>d</b> is set.
  97. */
  98. static void
  99. storage_dir_clean_tmpfiles(storage_dir_t *d)
  100. {
  101. if (!d->contents)
  102. return;
  103. SMARTLIST_FOREACH_BEGIN(d->contents, char *, fname) {
  104. if (strcmpend(fname, ".tmp"))
  105. continue;
  106. char *path = NULL;
  107. tor_asprintf(&path, "%s/%s", d->directory, fname);
  108. if (unlink(sandbox_intern_string(path))) {
  109. log_warn(LD_FS, "Unable to unlink %s", escaped(path));
  110. tor_free(path);
  111. continue;
  112. }
  113. tor_free(path);
  114. SMARTLIST_DEL_CURRENT(d->contents, fname);
  115. tor_free(fname);
  116. } SMARTLIST_FOREACH_END(fname);
  117. d->usage_known = 0;
  118. }
  119. /**
  120. * Re-scan the directory <b>d</b> to learn its contents.
  121. */
  122. static int
  123. storage_dir_rescan(storage_dir_t *d)
  124. {
  125. if (d->contents) {
  126. SMARTLIST_FOREACH(d->contents, char *, cp, tor_free(cp));
  127. smartlist_free(d->contents);
  128. }
  129. d->usage = 0;
  130. d->usage_known = 0;
  131. if (NULL == (d->contents = tor_listdir(d->directory))) {
  132. return -1;
  133. }
  134. storage_dir_clean_tmpfiles(d);
  135. return 0;
  136. }
  137. /**
  138. * Return a smartlist containing the filenames within <b>d</b>.
  139. */
  140. const smartlist_t *
  141. storage_dir_list(storage_dir_t *d)
  142. {
  143. if (! d->contents)
  144. storage_dir_rescan(d);
  145. return d->contents;
  146. }
  147. /**
  148. * Return the total number of bytes used for storage in <b>d</b>.
  149. */
  150. uint64_t
  151. storage_dir_get_usage(storage_dir_t *d)
  152. {
  153. if (d->usage_known)
  154. return d->usage;
  155. uint64_t total = 0;
  156. SMARTLIST_FOREACH_BEGIN(storage_dir_list(d), const char *, cp) {
  157. char *path = NULL;
  158. struct stat st;
  159. tor_asprintf(&path, "%s/%s", d->directory, cp);
  160. if (stat(sandbox_intern_string(path), &st) == 0) {
  161. total += st.st_size;
  162. }
  163. tor_free(path);
  164. } SMARTLIST_FOREACH_END(cp);
  165. d->usage = total;
  166. d->usage_known = 1;
  167. return d->usage;
  168. }
  169. /** Mmap a specified file within <b>d</b>. */
  170. tor_mmap_t *
  171. storage_dir_map(storage_dir_t *d, const char *fname)
  172. {
  173. char *path = NULL;
  174. tor_asprintf(&path, "%s/%s", d->directory, fname);
  175. tor_mmap_t *result = tor_mmap_file(path);
  176. tor_free(path);
  177. return result;
  178. }
  179. /** Read a file within <b>d</b> into a newly allocated buffer. Set
  180. * *<b>sz_out</b> to its size. */
  181. uint8_t *
  182. storage_dir_read(storage_dir_t *d, const char *fname, int bin, size_t *sz_out)
  183. {
  184. const int flags = bin ? RFTS_BIN : 0;
  185. char *path = NULL;
  186. tor_asprintf(&path, "%s/%s", d->directory, fname);
  187. struct stat st;
  188. char *contents = read_file_to_str(path, flags, &st);
  189. if (contents && sz_out) {
  190. // it fits in RAM, so we know its size is less than SIZE_MAX
  191. tor_assert((uint64_t)st.st_size <= SIZE_MAX);
  192. *sz_out = (size_t) st.st_size;
  193. }
  194. tor_free(path);
  195. return (uint8_t *) contents;
  196. }
  197. /** Helper: Find an unused filename within the directory */
  198. static char *
  199. find_unused_fname(storage_dir_t *d)
  200. {
  201. if (!d->contents) {
  202. if (storage_dir_rescan(d) < 0)
  203. return NULL;
  204. }
  205. char buf[16];
  206. int i;
  207. /* Yuck; this is quadratic. Fortunately, that shouldn't matter much,
  208. * since disk writes are more expensive by a lot. */
  209. for (i = FNAME_MIN_NUM; i < FNAME_MIN_NUM + d->max_files; ++i) {
  210. tor_snprintf(buf, sizeof(buf), "%d", i);
  211. if (!smartlist_contains_string(d->contents, buf)) {
  212. return tor_strdup(buf);
  213. }
  214. }
  215. return NULL;
  216. }
  217. /** Helper: As storage_dir_save_bytes_to_file, but store a smartlist of
  218. * sized_chunk_t rather than a single byte array. */
  219. static int
  220. storage_dir_save_chunks_to_file(storage_dir_t *d,
  221. const smartlist_t *chunks,
  222. int binary,
  223. char **fname_out)
  224. {
  225. uint64_t total_length = 0;
  226. char *fname = find_unused_fname(d);
  227. if (!fname)
  228. return -1;
  229. SMARTLIST_FOREACH(chunks, const sized_chunk_t *, ch,
  230. total_length += ch->len);
  231. char *path = NULL;
  232. tor_asprintf(&path, "%s/%s", d->directory, fname);
  233. int r = write_chunks_to_file(path, chunks, binary, 0);
  234. if (r == 0) {
  235. if (d->usage_known)
  236. d->usage += total_length;
  237. if (fname_out) {
  238. *fname_out = tor_strdup(fname);
  239. }
  240. if (d->contents)
  241. smartlist_add(d->contents, tor_strdup(fname));
  242. }
  243. tor_free(fname);
  244. tor_free(path);
  245. return r;
  246. }
  247. /** Try to write the <b>length</b> bytes at <b>data</b> into a new file
  248. * in <b>d</b>. On success, return 0 and set *<b>fname_out</b> to a
  249. * newly allocated string containing the filename. On failure, return
  250. * -1. */
  251. int
  252. storage_dir_save_bytes_to_file(storage_dir_t *d,
  253. const uint8_t *data,
  254. size_t length,
  255. int binary,
  256. char **fname_out)
  257. {
  258. smartlist_t *chunks = smartlist_new();
  259. sized_chunk_t chunk = { (const char *)data, length };
  260. smartlist_add(chunks, &chunk);
  261. int r = storage_dir_save_chunks_to_file(d, chunks, binary, fname_out);
  262. smartlist_free(chunks);
  263. return r;
  264. }
  265. /**
  266. * As storage_dir_save_bytes_to_file, but saves a NUL-terminated string
  267. * <b>str</b>.
  268. */
  269. int
  270. storage_dir_save_string_to_file(storage_dir_t *d,
  271. const char *str,
  272. int binary,
  273. char **fname_out)
  274. {
  275. return storage_dir_save_bytes_to_file(d,
  276. (const uint8_t*)str, strlen(str), binary, fname_out);
  277. }
  278. /**
  279. * As storage_dir_save_bytes_to_file, but associates the data with the
  280. * key-value pairs in <b>labels</b>. Files
  281. * stored in this format can be recovered with storage_dir_map_labeled
  282. * or storage_dir_read_labeled().
  283. */
  284. int
  285. storage_dir_save_labeled_to_file(storage_dir_t *d,
  286. const config_line_t *labels,
  287. const uint8_t *data,
  288. size_t length,
  289. char **fname_out)
  290. {
  291. /*
  292. * The storage format is to prefix the data with the key-value pairs in
  293. * <b>labels</b>, and a single NUL separator. But code outside this module
  294. * MUST NOT rely on that format.
  295. */
  296. smartlist_t *chunks = smartlist_new();
  297. memarea_t *area = memarea_new();
  298. const config_line_t *line;
  299. for (line = labels; line; line = line->next) {
  300. sized_chunk_t *sz = memarea_alloc(area, sizeof(sized_chunk_t));
  301. sz->len = strlen(line->key) + 1 + strlen(line->value) + 1;
  302. const size_t allocated = sz->len + 1;
  303. char *bytes = memarea_alloc(area, allocated);
  304. tor_snprintf(bytes, allocated, "%s %s\n", line->key, line->value);
  305. sz->bytes = bytes;
  306. smartlist_add(chunks, sz);
  307. }
  308. sized_chunk_t *nul = memarea_alloc(area, sizeof(sized_chunk_t));
  309. nul->len = 1;
  310. nul->bytes = "\0";
  311. smartlist_add(chunks, nul);
  312. sized_chunk_t *datachunk = memarea_alloc(area, sizeof(sized_chunk_t));
  313. datachunk->bytes = (const char *)data;
  314. datachunk->len = length;
  315. smartlist_add(chunks, datachunk);
  316. int r = storage_dir_save_chunks_to_file(d, chunks, 1, fname_out);
  317. smartlist_free(chunks);
  318. memarea_drop_all(area);
  319. return r;
  320. }
  321. /**
  322. * Map a file that was created with storage_dir_save_labeled(). On failure,
  323. * return NULL. On success, write a set of newly allocated labels into to
  324. * *<b>labels_out</b>, a pointer to the into *<b>data_out</b>, and the data's
  325. * into *<b>sz_out</b>. On success, also return a tor_mmap_t object whose
  326. * contents should not be used -- it needs to be kept around, though, for as
  327. * long as <b>data_out</b> is going to be valid.
  328. */
  329. tor_mmap_t *
  330. storage_dir_map_labeled(storage_dir_t *dir,
  331. const char *fname,
  332. config_line_t **labels_out,
  333. const uint8_t **data_out,
  334. size_t *sz_out)
  335. {
  336. tor_mmap_t *m = storage_dir_map(dir, fname);
  337. if (! m)
  338. goto err;
  339. const char *nulp = memchr(m->data, '\0', m->size);
  340. if (! nulp)
  341. goto err;
  342. if (labels_out && config_get_lines(m->data, labels_out, 0) < 0)
  343. goto err;
  344. size_t offset = nulp - m->data + 1;
  345. tor_assert(offset <= m->size);
  346. *data_out = (const uint8_t *)(m->data + offset);
  347. *sz_out = m->size - offset;
  348. return m;
  349. err:
  350. tor_munmap_file(m);
  351. return NULL;
  352. }
  353. /** As storage_dir_map_labeled, but return a new byte array containing the
  354. * data. */
  355. uint8_t *
  356. storage_dir_read_labeled(storage_dir_t *dir,
  357. const char *fname,
  358. config_line_t **labels_out,
  359. size_t *sz_out)
  360. {
  361. const uint8_t *data = NULL;
  362. tor_mmap_t *m = storage_dir_map_labeled(dir, fname, labels_out,
  363. &data, sz_out);
  364. if (m == NULL)
  365. return NULL;
  366. uint8_t *result = tor_memdup(data, *sz_out);
  367. tor_munmap_file(m);
  368. return result;
  369. }
  370. /**
  371. * Remove the file called <b>fname</b> from <b>d</b>.
  372. */
  373. void
  374. storage_dir_remove_file(storage_dir_t *d,
  375. const char *fname)
  376. {
  377. char *path = NULL;
  378. tor_asprintf(&path, "%s/%s", d->directory, fname);
  379. const char *ipath = sandbox_intern_string(path);
  380. uint64_t size = 0;
  381. if (d->usage_known) {
  382. struct stat st;
  383. if (stat(ipath, &st) == 0) {
  384. size = st.st_size;
  385. }
  386. }
  387. if (unlink(ipath) == 0) {
  388. d->usage -= size;
  389. } else {
  390. log_warn(LD_FS, "Unable to unlink %s", escaped(path));
  391. tor_free(path);
  392. return;
  393. }
  394. if (d->contents) {
  395. smartlist_string_remove(d->contents, fname);
  396. }
  397. tor_free(path);
  398. }
  399. /** Helper type: used to sort the members of storage directory by mtime. */
  400. typedef struct shrinking_dir_entry_t {
  401. time_t mtime;
  402. uint64_t size;
  403. char *path;
  404. } shrinking_dir_entry_t;
  405. /** Helper: use with qsort to sort shrinking_dir_entry_t structs. */
  406. static int
  407. shrinking_dir_entry_compare(const void *a_, const void *b_)
  408. {
  409. const shrinking_dir_entry_t *a = a_;
  410. const shrinking_dir_entry_t *b = b_;
  411. if (a->mtime < b->mtime)
  412. return -1;
  413. else if (a->mtime > b->mtime)
  414. return 1;
  415. else
  416. return 0;
  417. }
  418. /**
  419. * Try to free space by removing the oldest files in <b>d</b>. Delete
  420. * until no more than <b>target_size</b> bytes are left, and at least
  421. * <b>min_to_remove</b> files have been removed... or until there is
  422. * nothing left to remove.
  423. *
  424. * Return 0 on success; -1 on failure.
  425. */
  426. int
  427. storage_dir_shrink(storage_dir_t *d,
  428. uint64_t target_size,
  429. int min_to_remove)
  430. {
  431. if (d->usage_known && d->usage <= target_size && !min_to_remove) {
  432. /* Already small enough. */
  433. return 0;
  434. }
  435. if (storage_dir_rescan(d) < 0)
  436. return -1;
  437. const uint64_t orig_usage = storage_dir_get_usage(d);
  438. if (orig_usage <= target_size && !min_to_remove) {
  439. /* Okay, small enough after rescan! */
  440. return 0;
  441. }
  442. const int n = smartlist_len(d->contents);
  443. shrinking_dir_entry_t *ents = tor_calloc(n, sizeof(shrinking_dir_entry_t));
  444. SMARTLIST_FOREACH_BEGIN(d->contents, const char *, fname) {
  445. shrinking_dir_entry_t *ent = &ents[fname_sl_idx];
  446. struct stat st;
  447. tor_asprintf(&ent->path, "%s/%s", d->directory, fname);
  448. if (stat(sandbox_intern_string(ent->path), &st) == 0) {
  449. ent->mtime = st.st_mtime;
  450. ent->size = st.st_size;
  451. }
  452. } SMARTLIST_FOREACH_END(fname);
  453. qsort(ents, n, sizeof(shrinking_dir_entry_t), shrinking_dir_entry_compare);
  454. int idx = 0;
  455. while ((d->usage > target_size || min_to_remove > 0) && idx < n) {
  456. if (unlink(sandbox_intern_string(ents[idx].path)) == 0) {
  457. if (! BUG(d->usage < ents[idx].size)) {
  458. d->usage -= ents[idx].size;
  459. }
  460. --min_to_remove;
  461. }
  462. ++idx;
  463. }
  464. for (idx = 0; idx < n; ++idx) {
  465. tor_free(ents[idx].path);
  466. }
  467. tor_free(ents);
  468. storage_dir_rescan(d);
  469. return 0;
  470. }
  471. /** Remove all files in <b>d</b>. */
  472. int
  473. storage_dir_remove_all(storage_dir_t *d)
  474. {
  475. return storage_dir_shrink(d, 0, d->max_files);
  476. }