storagedir.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. /* Copyright (c) 2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "container.h"
  4. #include "compat.h"
  5. #include "sandbox.h"
  6. #include "storagedir.h"
  7. #include "torlog.h"
  8. #include "util.h"
  9. #ifdef HAVE_SYS_TYPES_H
  10. #include <sys/types.h>
  11. #endif
  12. #ifdef HAVE_SYS_STAT_H
  13. #include <sys/stat.h>
  14. #endif
  15. #ifdef HAVE_UNISTD_H
  16. #include <unistd.h>
  17. #endif
  18. #define FNAME_MIN_NUM 1000
  19. /** A storage_dir_t represents a directory full of similar cached
  20. * files. Filenames are decimal integers. Files can be cleaned as needed
  21. * to limit total disk usage. */
  22. struct storage_dir_t {
  23. /** Directory holding the files for this storagedir. */
  24. char *directory;
  25. /** Either NULL, or a directory listing of the directory (as a smartlist
  26. * of strings */
  27. smartlist_t *contents;
  28. /** The largest number of non-temporary files we'll place in the
  29. * directory. */
  30. int max_files;
  31. /** If true, then 'usage' has been computed. */
  32. int usage_known;
  33. /** The total number of bytes used in this directory */
  34. uint64_t usage;
  35. };
  36. /** Create or open a new storage directory at <b>dirname</b>, with
  37. * capacity for up to <b>max_files</b> files.
  38. */
  39. storage_dir_t *
  40. storage_dir_new(const char *dirname, int max_files)
  41. {
  42. if (check_private_dir(dirname, CPD_CREATE, NULL) < 0)
  43. return NULL;
  44. storage_dir_t *d = tor_malloc_zero(sizeof(storage_dir_t));
  45. d->directory = tor_strdup(dirname);
  46. d->max_files = max_files;
  47. return d;
  48. }
  49. /**
  50. * Drop all in-RAM storage for <b>d</b>. Does not delete any files.
  51. */
  52. void
  53. storage_dir_free(storage_dir_t *d)
  54. {
  55. if (d == NULL)
  56. return;
  57. tor_free(d->directory);
  58. if (d->contents) {
  59. SMARTLIST_FOREACH(d->contents, char *, cp, tor_free(cp));
  60. smartlist_free(d->contents);
  61. }
  62. tor_free(d);
  63. }
  64. /**
  65. * Tell the sandbox (if any) configured by <b>cfg</b> to allow the
  66. * operations that <b>d</b> will need.
  67. *
  68. * The presence of this function is why we need an upper limit on the
  69. * number of filers in a storage_dir_t: we need to approve file
  70. * operaitons one by one.
  71. */
  72. int
  73. storage_dir_register_with_sandbox(storage_dir_t *d, sandbox_cfg_t **cfg)
  74. {
  75. int problems = 0;
  76. int idx;
  77. for (idx = FNAME_MIN_NUM; idx < FNAME_MIN_NUM + d->max_files; ++idx) {
  78. char *path = NULL, *tmppath = NULL;
  79. tor_asprintf(&path, "%s/%d", d->directory, idx);
  80. tor_asprintf(&tmppath, "%s/%d.tmp", d->directory, idx);
  81. problems += sandbox_cfg_allow_open_filename(cfg, path);
  82. problems += sandbox_cfg_allow_open_filename(cfg, tmppath);
  83. problems += sandbox_cfg_allow_stat_filename(cfg, path);
  84. problems += sandbox_cfg_allow_stat_filename(cfg, tmppath);
  85. problems += sandbox_cfg_allow_rename(cfg, tmppath, path);
  86. tor_free(path);
  87. tor_free(tmppath);
  88. }
  89. return problems ? -1 : 0;
  90. }
  91. /**
  92. * Remove all files in <b>d</b> whose names end with ".tmp".
  93. *
  94. * Requires that the contents field of <b>d</b> is set.
  95. */
  96. static void
  97. storage_dir_clean_tmpfiles(storage_dir_t *d)
  98. {
  99. if (!d->contents)
  100. return;
  101. SMARTLIST_FOREACH_BEGIN(d->contents, char *, fname) {
  102. if (strcmpend(fname, ".tmp"))
  103. continue;
  104. char *path = NULL;
  105. tor_asprintf(&path, "%s/%s", d->directory, fname);
  106. if (unlink(sandbox_intern_string(path))) {
  107. log_warn(LD_FS, "Unable to unlink %s", escaped(path));
  108. tor_free(path);
  109. continue;
  110. }
  111. tor_free(path);
  112. SMARTLIST_DEL_CURRENT(d->contents, fname);
  113. tor_free(fname);
  114. } SMARTLIST_FOREACH_END(fname);
  115. d->usage_known = 0;
  116. }
  117. /**
  118. * Re-scan the directory <b>d</b> to learn its contents.
  119. */
  120. static int
  121. storage_dir_rescan(storage_dir_t *d)
  122. {
  123. if (d->contents) {
  124. SMARTLIST_FOREACH(d->contents, char *, cp, tor_free(cp));
  125. smartlist_free(d->contents);
  126. }
  127. d->usage = 0;
  128. d->usage_known = 0;
  129. if (NULL == (d->contents = tor_listdir(d->directory))) {
  130. return -1;
  131. }
  132. storage_dir_clean_tmpfiles(d);
  133. return 0;
  134. }
  135. /**
  136. * Return a smartlist containing the filenames within <b>d</b>.
  137. */
  138. const smartlist_t *
  139. storage_dir_list(storage_dir_t *d)
  140. {
  141. if (! d->contents)
  142. storage_dir_rescan(d);
  143. return d->contents;
  144. }
  145. /**
  146. * Return the total number of bytes used for storage in <b>d</b>.
  147. */
  148. uint64_t
  149. storage_dir_get_usage(storage_dir_t *d)
  150. {
  151. if (d->usage_known)
  152. return d->usage;
  153. uint64_t total = 0;
  154. SMARTLIST_FOREACH_BEGIN(storage_dir_list(d), const char *, cp) {
  155. char *path = NULL;
  156. struct stat st;
  157. tor_asprintf(&path, "%s/%s", d->directory, cp);
  158. if (stat(sandbox_intern_string(path), &st) == 0) {
  159. total += st.st_size;
  160. }
  161. tor_free(path);
  162. } SMARTLIST_FOREACH_END(cp);
  163. d->usage = total;
  164. d->usage_known = 1;
  165. return d->usage;
  166. }
  167. /** Mmap a specified file within <b>d</b>. */
  168. tor_mmap_t *
  169. storage_dir_map(storage_dir_t *d, const char *fname)
  170. {
  171. char *path = NULL;
  172. tor_asprintf(&path, "%s/%s", d->directory, fname);
  173. tor_mmap_t *result = tor_mmap_file(path);
  174. tor_free(path);
  175. return result;
  176. }
  177. /** Read a file within <b>d</b> into a newly allocated buffer. Set
  178. * *<b>sz_out</b> to its size. */
  179. uint8_t *
  180. storage_dir_read(storage_dir_t *d, const char *fname, int bin, size_t *sz_out)
  181. {
  182. const int flags = bin ? RFTS_BIN : 0;
  183. char *path = NULL;
  184. tor_asprintf(&path, "%s/%s", d->directory, fname);
  185. struct stat st;
  186. char *contents = read_file_to_str(path, flags, &st);
  187. if (contents && sz_out)
  188. *sz_out = st.st_size;
  189. tor_free(path);
  190. return (uint8_t *) contents;
  191. }
  192. /** Helper: Find an unused filename within the directory */
  193. static char *
  194. find_unused_fname(storage_dir_t *d)
  195. {
  196. if (!d->contents) {
  197. if (storage_dir_rescan(d) < 0)
  198. return NULL;
  199. }
  200. char buf[16];
  201. int i;
  202. /* Yuck; this is quadratic. Fortunately, that shouldn't matter much,
  203. * since disk writes are more expensive by a lot. */
  204. for (i = FNAME_MIN_NUM; i < FNAME_MIN_NUM + d->max_files; ++i) {
  205. tor_snprintf(buf, sizeof(buf), "%d", i);
  206. if (!smartlist_contains_string(d->contents, buf)) {
  207. return tor_strdup(buf);
  208. }
  209. }
  210. return NULL;
  211. }
  212. /** Try to write the <b>length</b> bytes at <b>data</b> into a new file
  213. * in <b>d</b>. On success, return 0 and set *<b>fname_out</b> to a
  214. * newly allocated string containing the filename. On failure, return
  215. * -1. */
  216. int
  217. storage_dir_save_bytes_to_file(storage_dir_t *d,
  218. const uint8_t *data,
  219. size_t length,
  220. int binary,
  221. char **fname_out)
  222. {
  223. char *fname = find_unused_fname(d);
  224. if (!fname)
  225. return -1;
  226. char *path = NULL;
  227. tor_asprintf(&path, "%s/%s", d->directory, fname);
  228. int r = write_bytes_to_file(path, (const char *)data, length, binary);
  229. if (r == 0) {
  230. if (d->usage_known)
  231. d->usage += length;
  232. if (fname_out) {
  233. *fname_out = tor_strdup(fname);
  234. }
  235. if (d->contents)
  236. smartlist_add(d->contents, tor_strdup(fname));
  237. }
  238. tor_free(fname);
  239. tor_free(path);
  240. return r;
  241. }
  242. /**
  243. * As storage_dir_save_bytes_to_file, but saves a NUL-terminated string
  244. * <b>str</b>.
  245. */
  246. int
  247. storage_dir_save_string_to_file(storage_dir_t *d,
  248. const char *str,
  249. int binary,
  250. char **fname_out)
  251. {
  252. return storage_dir_save_bytes_to_file(d,
  253. (const uint8_t*)str, strlen(str), binary, fname_out);
  254. }
  255. /**
  256. * Remove the file called <b>fname</b> from <b>d</b>.
  257. */
  258. void
  259. storage_dir_remove_file(storage_dir_t *d,
  260. const char *fname)
  261. {
  262. char *path = NULL;
  263. tor_asprintf(&path, "%s/%s", d->directory, fname);
  264. const char *ipath = sandbox_intern_string(path);
  265. uint64_t size = 0;
  266. if (d->usage_known) {
  267. struct stat st;
  268. if (stat(ipath, &st) == 0) {
  269. size = st.st_size;
  270. }
  271. }
  272. if (unlink(ipath) == 0) {
  273. d->usage -= size;
  274. } else {
  275. log_warn(LD_FS, "Unable to unlink %s", escaped(path));
  276. tor_free(path);
  277. return;
  278. }
  279. if (d->contents) {
  280. smartlist_string_remove(d->contents, fname);
  281. }
  282. tor_free(path);
  283. }
  284. /** Helper type: used to sort the members of storage directory by mtime. */
  285. typedef struct shrinking_dir_entry_t {
  286. time_t mtime;
  287. uint64_t size;
  288. char *path;
  289. } shrinking_dir_entry_t;
  290. /** Helper: use with qsort to sort shrinking_dir_entry_t structs. */
  291. static int
  292. shrinking_dir_entry_compare(const void *a_, const void *b_)
  293. {
  294. const shrinking_dir_entry_t *a = a_;
  295. const shrinking_dir_entry_t *b = b_;
  296. if (a->mtime < b->mtime)
  297. return -1;
  298. else if (a->mtime > b->mtime)
  299. return 1;
  300. else
  301. return 0;
  302. }
  303. /**
  304. * Try to free space by removing the oldest files in <b>d</b>. Delete
  305. * until no more than <b>target_size</b> bytes are left, and at least
  306. * <b>min_to_remove</b> files have been removed... or until there is
  307. * nothing left to remove.
  308. *
  309. * Return 0 on success; -1 on failure.
  310. */
  311. int
  312. storage_dir_shrink(storage_dir_t *d,
  313. uint64_t target_size,
  314. int min_to_remove)
  315. {
  316. if (d->usage_known && d->usage <= target_size && !min_to_remove) {
  317. /* Already small enough. */
  318. return 0;
  319. }
  320. if (storage_dir_rescan(d) < 0)
  321. return -1;
  322. const uint64_t orig_usage = storage_dir_get_usage(d);
  323. if (orig_usage <= target_size && !min_to_remove) {
  324. /* Okay, small enough after rescan! */
  325. return 0;
  326. }
  327. const int n = smartlist_len(d->contents);
  328. shrinking_dir_entry_t *ents = tor_calloc(n, sizeof(shrinking_dir_entry_t));
  329. SMARTLIST_FOREACH_BEGIN(d->contents, const char *, fname) {
  330. shrinking_dir_entry_t *ent = &ents[fname_sl_idx];
  331. struct stat st;
  332. tor_asprintf(&ent->path, "%s/%s", d->directory, fname);
  333. if (stat(sandbox_intern_string(ent->path), &st) == 0) {
  334. ent->mtime = st.st_mtime;
  335. ent->size = st.st_size;
  336. }
  337. } SMARTLIST_FOREACH_END(fname);
  338. qsort(ents, n, sizeof(shrinking_dir_entry_t), shrinking_dir_entry_compare);
  339. int idx = 0;
  340. while ((d->usage > target_size || min_to_remove > 0) && idx < n) {
  341. if (unlink(sandbox_intern_string(ents[idx].path)) == 0) {
  342. if (! BUG(d->usage < ents[idx].size)) {
  343. d->usage -= ents[idx].size;
  344. }
  345. --min_to_remove;
  346. }
  347. ++idx;
  348. }
  349. for (idx = 0; idx < n; ++idx) {
  350. tor_free(ents[idx].path);
  351. }
  352. tor_free(ents);
  353. storage_dir_rescan(d);
  354. return 0;
  355. }
  356. /** Remove all files in <b>d</b>. */
  357. int
  358. storage_dir_remove_all(storage_dir_t *d)
  359. {
  360. return storage_dir_shrink(d, 0, d->max_files);
  361. }