microdesc.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /* Copyright (c) 2009-2010, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "or.h"
  4. #include "config.h"
  5. #include "directory.h"
  6. #include "microdesc.h"
  7. #include "routerparse.h"
  8. #include "networkstatus.h"
  9. #include "routerlist.h"
  10. #include "dirserv.h"
  11. /** A data structure to hold a bunch of cached microdescriptors. There are
  12. * two active files in the cache: a "cache file" that we mmap, and a "journal
  13. * file" that we append to. Periodically, we rebuild the cache file to hold
  14. * only the microdescriptors that we want to keep */
  15. struct microdesc_cache_t {
  16. /** Map from sha256-digest to microdesc_t for every microdesc_t in the
  17. * cache. */
  18. HT_HEAD(microdesc_map, microdesc_t) map;
  19. /** Name of the cache file. */
  20. char *cache_fname;
  21. /** Name of the journal file. */
  22. char *journal_fname;
  23. /** Mmap'd contents of the cache file, or NULL if there is none. */
  24. tor_mmap_t *cache_content;
  25. /** Number of bytes used in the journal file. */
  26. size_t journal_len;
  27. /** Total bytes of microdescriptor bodies we have added to this cache */
  28. uint64_t total_len_seen;
  29. /** Total number of microdescriptors we have added to this cache */
  30. unsigned n_seen;
  31. };
  32. /** Helper: computes a hash of <b>md</b> to place it in a hash table. */
  33. static INLINE unsigned int
  34. _microdesc_hash(microdesc_t *md)
  35. {
  36. unsigned *d = (unsigned*)md->digest;
  37. #if SIZEOF_INT == 4
  38. return d[0] ^ d[1] ^ d[2] ^ d[3] ^ d[4] ^ d[5] ^ d[6] ^ d[7];
  39. #else
  40. return d[0] ^ d[1] ^ d[2] ^ d[3];
  41. #endif
  42. }
  43. /** Helper: compares <b>a</b> and </b> for equality for hash-table purposes. */
  44. static INLINE int
  45. _microdesc_eq(microdesc_t *a, microdesc_t *b)
  46. {
  47. return !memcmp(a->digest, b->digest, DIGEST256_LEN);
  48. }
  49. HT_PROTOTYPE(microdesc_map, microdesc_t, node,
  50. _microdesc_hash, _microdesc_eq);
  51. HT_GENERATE(microdesc_map, microdesc_t, node,
  52. _microdesc_hash, _microdesc_eq, 0.6,
  53. malloc, realloc, free);
  54. /** Write the body of <b>md</b> into <b>f</b>, with appropriate annotations.
  55. * On success, return the total number of bytes written, and set
  56. * *<b>annotation_len_out</b> to the number of bytes written as
  57. * annotations. */
  58. static ssize_t
  59. dump_microdescriptor(FILE *f, microdesc_t *md, size_t *annotation_len_out)
  60. {
  61. ssize_t r = 0;
  62. size_t written;
  63. /* XXXX drops unkown annotations. */
  64. if (md->last_listed) {
  65. char buf[ISO_TIME_LEN+1];
  66. char annotation[ISO_TIME_LEN+32];
  67. format_iso_time(buf, md->last_listed);
  68. tor_snprintf(annotation, sizeof(annotation), "@last-listed %s\n", buf);
  69. fputs(annotation, f);
  70. r += strlen(annotation);
  71. *annotation_len_out = r;
  72. } else {
  73. *annotation_len_out = 0;
  74. }
  75. md->off = (off_t) ftell(f);
  76. written = fwrite(md->body, 1, md->bodylen, f);
  77. if (written != md->bodylen) {
  78. log_warn(LD_DIR,
  79. "Couldn't dump microdescriptor (wrote %lu out of %lu): %s",
  80. (unsigned long)written, (unsigned long)md->bodylen,
  81. strerror(ferror(f)));
  82. return -1;
  83. }
  84. r += md->bodylen;
  85. return r;
  86. }
  87. /** Holds a pointer to the current microdesc_cache_t object, or NULL if no
  88. * such object has been allocated. */
  89. static microdesc_cache_t *the_microdesc_cache = NULL;
  90. /** Return a pointer to the microdescriptor cache, loading it if necessary. */
  91. microdesc_cache_t *
  92. get_microdesc_cache(void)
  93. {
  94. if (PREDICT_UNLIKELY(the_microdesc_cache==NULL)) {
  95. microdesc_cache_t *cache = tor_malloc_zero(sizeof(microdesc_cache_t));
  96. HT_INIT(microdesc_map, &cache->map);
  97. cache->cache_fname = get_datadir_fname("cached-microdescs");
  98. cache->journal_fname = get_datadir_fname("cached-microdescs.new");
  99. microdesc_cache_reload(cache);
  100. the_microdesc_cache = cache;
  101. }
  102. return the_microdesc_cache;
  103. }
  104. /* There are three sources of microdescriptors:
  105. 1) Generated by us while acting as a directory authority.
  106. 2) Loaded from the cache on disk.
  107. 3) Downloaded.
  108. */
  109. /** Decode the microdescriptors from the string starting at <b>s</b> and
  110. * ending at <b>eos</b>, and store them in <b>cache</b>. If <b>no-save</b>,
  111. * mark them as non-writable to disk. If <b>where</b> is SAVED_IN_CACHE,
  112. * leave their bodies as pointers to the mmap'd cache. If where is
  113. * <b>SAVED_NOWHERE</b>, do not allow annotations. If listed_at is positive,
  114. * set the last_listed field of every microdesc to listed_at. If
  115. * requested_digests is non-null, then it contains a list of digests we mean
  116. * to allow, so we should reject any non-requested microdesc with a different
  117. * digest, and alter the list to contain only the digests of those microdescs we
  118. * didn't find.
  119. * Return a list of the added microdescriptors. */
  120. smartlist_t *
  121. microdescs_add_to_cache(microdesc_cache_t *cache,
  122. const char *s, const char *eos, saved_location_t where,
  123. int no_save, time_t listed_at,
  124. smartlist_t *requested_digests256)
  125. {
  126. smartlist_t *descriptors, *added;
  127. const int allow_annotations = (where != SAVED_NOWHERE);
  128. const int copy_body = (where != SAVED_IN_CACHE);
  129. descriptors = microdescs_parse_from_string(s, eos,
  130. allow_annotations,
  131. copy_body);
  132. if (listed_at > 0) {
  133. SMARTLIST_FOREACH(descriptors, microdesc_t *, md,
  134. md->last_listed = listed_at);
  135. }
  136. if (requested_digests256) {
  137. digestmap_t *requested; /* XXXX actuqlly we should just use a
  138. digest256map */
  139. requested = digestmap_new();
  140. SMARTLIST_FOREACH(requested_digests256, const char *, cp,
  141. digestmap_set(requested, cp, (void*)1));
  142. SMARTLIST_FOREACH_BEGIN(descriptors, microdesc_t *, md) {
  143. if (digestmap_get(requested, md->digest)) {
  144. digestmap_set(requested, md->digest, (void*)2);
  145. } else {
  146. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Received non-requested microcdesc");
  147. microdesc_free(md);
  148. SMARTLIST_DEL_CURRENT(descriptors, md);
  149. }
  150. } SMARTLIST_FOREACH_END(md);
  151. SMARTLIST_FOREACH_BEGIN(requested_digests256, char *, cp) {
  152. if (digestmap_get(requested, cp) == (void*)2) {
  153. tor_free(cp);
  154. SMARTLIST_DEL_CURRENT(requested_digests256, cp);
  155. }
  156. } SMARTLIST_FOREACH_END(cp);
  157. digestmap_free(requested, NULL);
  158. }
  159. added = microdescs_add_list_to_cache(cache, descriptors, where, no_save);
  160. smartlist_free(descriptors);
  161. return added;
  162. }
  163. /* As microdescs_add_to_cache, but takes a list of micrdescriptors instead of
  164. * a string to encode. Frees any members of <b>descriptors</b> that it does
  165. * not add. */
  166. smartlist_t *
  167. microdescs_add_list_to_cache(microdesc_cache_t *cache,
  168. smartlist_t *descriptors, saved_location_t where,
  169. int no_save)
  170. {
  171. smartlist_t *added;
  172. open_file_t *open_file = NULL;
  173. FILE *f = NULL;
  174. // int n_added = 0;
  175. ssize_t size = 0;
  176. if (where == SAVED_NOWHERE && !no_save) {
  177. f = start_writing_to_stdio_file(cache->journal_fname,
  178. OPEN_FLAGS_APPEND|O_BINARY,
  179. 0600, &open_file);
  180. if (!f) {
  181. log_warn(LD_DIR, "Couldn't append to journal in %s: %s",
  182. cache->journal_fname, strerror(errno));
  183. return NULL;
  184. }
  185. }
  186. added = smartlist_create();
  187. SMARTLIST_FOREACH_BEGIN(descriptors, microdesc_t *, md) {
  188. microdesc_t *md2;
  189. md2 = HT_FIND(microdesc_map, &cache->map, md);
  190. if (md2) {
  191. /* We already had this one. */
  192. if (md2->last_listed < md->last_listed)
  193. md2->last_listed = md->last_listed;
  194. microdesc_free(md);
  195. continue;
  196. }
  197. /* Okay, it's a new one. */
  198. if (f) {
  199. size_t annotation_len;
  200. size = dump_microdescriptor(f, md, &annotation_len);
  201. if (size < 0) {
  202. /* XXX handle errors from dump_microdescriptor() */
  203. /* log? return -1? die? coredump the universe? */
  204. continue;
  205. }
  206. md->saved_location = SAVED_IN_JOURNAL;
  207. cache->journal_len += size;
  208. } else {
  209. md->saved_location = where;
  210. }
  211. md->no_save = no_save;
  212. HT_INSERT(microdesc_map, &cache->map, md);
  213. smartlist_add(added, md);
  214. ++cache->n_seen;
  215. cache->total_len_seen += md->bodylen;
  216. } SMARTLIST_FOREACH_END(md);
  217. if (f)
  218. finish_writing_to_file(open_file); /*XXX Check me.*/
  219. {
  220. size_t old_content_len =
  221. cache->cache_content ? cache->cache_content->size : 0;
  222. if (cache->journal_len > 16384 + old_content_len &&
  223. cache->journal_len > old_content_len * 2) {
  224. microdesc_cache_rebuild(cache);
  225. }
  226. }
  227. return added;
  228. }
  229. /** Remove every microdescriptor in <b>cache</b>. */
  230. void
  231. microdesc_cache_clear(microdesc_cache_t *cache)
  232. {
  233. microdesc_t **entry, **next;
  234. for (entry = HT_START(microdesc_map, &cache->map); entry; entry = next) {
  235. microdesc_t *md = *entry;
  236. next = HT_NEXT_RMV(microdesc_map, &cache->map, entry);
  237. microdesc_free(md);
  238. }
  239. HT_CLEAR(microdesc_map, &cache->map);
  240. if (cache->cache_content) {
  241. tor_munmap_file(cache->cache_content);
  242. cache->cache_content = NULL;
  243. }
  244. cache->total_len_seen = 0;
  245. cache->n_seen = 0;
  246. }
  247. /** Reload the contents of <b>cache</b> from disk. If it is empty, load it
  248. * for the first time. Return 0 on success, -1 on failure. */
  249. int
  250. microdesc_cache_reload(microdesc_cache_t *cache)
  251. {
  252. struct stat st;
  253. char *journal_content;
  254. smartlist_t *added;
  255. tor_mmap_t *mm;
  256. int total = 0;
  257. microdesc_cache_clear(cache);
  258. mm = cache->cache_content = tor_mmap_file(cache->cache_fname);
  259. if (mm) {
  260. added = microdescs_add_to_cache(cache, mm->data, mm->data+mm->size,
  261. SAVED_IN_CACHE, 0, -1, NULL);
  262. if (added) {
  263. total += smartlist_len(added);
  264. smartlist_free(added);
  265. }
  266. }
  267. journal_content = read_file_to_str(cache->journal_fname,
  268. RFTS_IGNORE_MISSING, &st);
  269. if (journal_content) {
  270. added = microdescs_add_to_cache(cache, journal_content,
  271. journal_content+st.st_size,
  272. SAVED_IN_JOURNAL, 0, -1, NULL);
  273. if (added) {
  274. total += smartlist_len(added);
  275. smartlist_free(added);
  276. }
  277. tor_free(journal_content);
  278. }
  279. log_notice(LD_DIR, "Reloaded microdescriptor cache. Found %d descriptors.",
  280. total);
  281. return 0;
  282. }
  283. /** Regenerate the main cache file for <b>cache</b>, clear the journal file,
  284. * and update every microdesc_t in the cache with pointers to its new
  285. * location. */
  286. int
  287. microdesc_cache_rebuild(microdesc_cache_t *cache)
  288. {
  289. open_file_t *open_file;
  290. FILE *f;
  291. microdesc_t **mdp;
  292. smartlist_t *wrote;
  293. ssize_t size;
  294. off_t off = 0;
  295. int orig_size, new_size;
  296. log_info(LD_DIR, "Rebuilding the microdescriptor cache...");
  297. orig_size = (int)(cache->cache_content ? cache->cache_content->size : 0);
  298. orig_size += (int)cache->journal_len;
  299. f = start_writing_to_stdio_file(cache->cache_fname,
  300. OPEN_FLAGS_REPLACE|O_BINARY,
  301. 0600, &open_file);
  302. if (!f)
  303. return -1;
  304. wrote = smartlist_create();
  305. HT_FOREACH(mdp, microdesc_map, &cache->map) {
  306. microdesc_t *md = *mdp;
  307. size_t annotation_len;
  308. if (md->no_save)
  309. continue;
  310. size = dump_microdescriptor(f, md, &annotation_len);
  311. if (size < 0) {
  312. /* XXX handle errors from dump_microdescriptor() */
  313. /* log? return -1? die? coredump the universe? */
  314. continue;
  315. }
  316. md->off = off + annotation_len;
  317. off += size;
  318. if (md->saved_location != SAVED_IN_CACHE) {
  319. tor_free(md->body);
  320. md->saved_location = SAVED_IN_CACHE;
  321. }
  322. smartlist_add(wrote, md);
  323. }
  324. finish_writing_to_file(open_file); /*XXX Check me.*/
  325. if (cache->cache_content)
  326. tor_munmap_file(cache->cache_content);
  327. cache->cache_content = tor_mmap_file(cache->cache_fname);
  328. if (!cache->cache_content && smartlist_len(wrote)) {
  329. log_err(LD_DIR, "Couldn't map file that we just wrote to %s!",
  330. cache->cache_fname);
  331. smartlist_free(wrote);
  332. return -1;
  333. }
  334. SMARTLIST_FOREACH_BEGIN(wrote, microdesc_t *, md) {
  335. tor_assert(md->saved_location == SAVED_IN_CACHE);
  336. md->body = (char*)cache->cache_content->data + md->off;
  337. tor_assert(!memcmp(md->body, "onion-key", 9));
  338. } SMARTLIST_FOREACH_END(md);
  339. smartlist_free(wrote);
  340. write_str_to_file(cache->journal_fname, "", 1);
  341. cache->journal_len = 0;
  342. new_size = (int)cache->cache_content->size;
  343. log_info(LD_DIR, "Done rebuilding microdesc cache. "
  344. "Saved %d bytes; %d still used.",
  345. orig_size-new_size, new_size);
  346. return 0;
  347. }
  348. /** Deallocate a single microdescriptor. Note: the microdescriptor MUST have
  349. * previously been removed from the cache if it had ever been inserted. */
  350. void
  351. microdesc_free(microdesc_t *md)
  352. {
  353. if (!md)
  354. return;
  355. /* Must be removed from hash table! */
  356. if (md->onion_pkey)
  357. crypto_free_pk_env(md->onion_pkey);
  358. if (md->body && md->saved_location != SAVED_IN_CACHE)
  359. tor_free(md->body);
  360. if (md->family) {
  361. SMARTLIST_FOREACH(md->family, char *, cp, tor_free(cp));
  362. smartlist_free(md->family);
  363. }
  364. tor_free(md->exitsummary);
  365. tor_free(md);
  366. }
  367. /** Free all storage held in the microdesc.c module. */
  368. void
  369. microdesc_free_all(void)
  370. {
  371. if (the_microdesc_cache) {
  372. microdesc_cache_clear(the_microdesc_cache);
  373. tor_free(the_microdesc_cache->cache_fname);
  374. tor_free(the_microdesc_cache->journal_fname);
  375. tor_free(the_microdesc_cache);
  376. }
  377. }
  378. /** If there is a microdescriptor in <b>cache</b> whose sha256 digest is
  379. * <b>d</b>, return it. Otherwise return NULL. */
  380. microdesc_t *
  381. microdesc_cache_lookup_by_digest256(microdesc_cache_t *cache, const char *d)
  382. {
  383. microdesc_t *md, search;
  384. if (!cache)
  385. cache = get_microdesc_cache();
  386. memcpy(search.digest, d, DIGEST256_LEN);
  387. md = HT_FIND(microdesc_map, &cache->map, &search);
  388. return md;
  389. }
  390. /** Return the mean size of decriptors added to <b>cache</b> since it was last
  391. * cleared. Used to estimate the size of large downloads. */
  392. size_t
  393. microdesc_average_size(microdesc_cache_t *cache)
  394. {
  395. if (!cache)
  396. cache = get_microdesc_cache();
  397. if (!cache->n_seen)
  398. return 512;
  399. return (size_t)(cache->total_len_seen / cache->n_seen);
  400. }
  401. /** Return a smartlist of all the sha256 digest of the microdescriptors that
  402. * are listed in <b>ns</b> but not present in <b>cache</b>. Returns pointers
  403. * to internals of <b>ns</b>; you should not free the members of the resulting
  404. * smartlist. Omit all microdescriptors whose digest appear in <b>skip</b>. */
  405. smartlist_t *
  406. microdesc_list_missing_digest256(networkstatus_t *ns, microdesc_cache_t *cache,
  407. int downloadable_only, digestmap_t *skip)
  408. {
  409. smartlist_t *result = smartlist_create();
  410. time_t now = time(NULL);
  411. tor_assert(ns->flavor == FLAV_MICRODESC);
  412. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  413. if (microdesc_cache_lookup_by_digest256(cache, rs->descriptor_digest))
  414. continue;
  415. if (downloadable_only &&
  416. !download_status_is_ready(&rs->dl_status, now,
  417. MAX_MICRODESC_DOWNLOAD_FAILURES))
  418. continue;
  419. if (skip && digestmap_get(skip, rs->descriptor_digest))
  420. continue;
  421. /* XXXX Also skip if we're a noncache and wouldn't use this router.
  422. * XXXX NM Microdesc
  423. */
  424. smartlist_add(result, rs->descriptor_digest);
  425. } SMARTLIST_FOREACH_END(rs);
  426. return result;
  427. }
  428. /** DOCDOC */
  429. void
  430. update_microdesc_downloads(time_t now)
  431. {
  432. or_options_t *options = get_options();
  433. networkstatus_t *consensus;
  434. smartlist_t *missing;
  435. digestmap_t *pending;
  436. if (should_delay_dir_fetches(options))
  437. return;
  438. if (directory_too_idle_to_fetch_descriptors(options, now))
  439. return;
  440. consensus = networkstatus_get_reasonably_live_consensus(now, FLAV_MICRODESC);
  441. if (!consensus)
  442. return;
  443. if (!directory_caches_dir_info(options)) {
  444. /* Right now, only caches fetch microdescriptors.
  445. * XXXX NM Microdescs */
  446. return;
  447. }
  448. pending = digestmap_new();
  449. list_pending_microdesc_downloads(pending);
  450. missing = microdesc_list_missing_digest256(consensus,
  451. get_microdesc_cache(),
  452. 1,
  453. pending);
  454. digestmap_free(pending, NULL);
  455. launch_descriptor_downloads(DIR_PURPOSE_FETCH_MICRODESC,
  456. missing, NULL, now);
  457. smartlist_free(missing);
  458. }