microdesc.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. /* Copyright (c) 2009-2013, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. #include "or.h"
  4. #include "circuitbuild.h"
  5. #include "config.h"
  6. #include "directory.h"
  7. #include "dirserv.h"
  8. #include "entrynodes.h"
  9. #include "microdesc.h"
  10. #include "networkstatus.h"
  11. #include "nodelist.h"
  12. #include "policies.h"
  13. #include "router.h"
  14. #include "routerlist.h"
  15. #include "routerparse.h"
  16. /** A data structure to hold a bunch of cached microdescriptors. There are
  17. * two active files in the cache: a "cache file" that we mmap, and a "journal
  18. * file" that we append to. Periodically, we rebuild the cache file to hold
  19. * only the microdescriptors that we want to keep */
  20. struct microdesc_cache_t {
  21. /** Map from sha256-digest to microdesc_t for every microdesc_t in the
  22. * cache. */
  23. HT_HEAD(microdesc_map, microdesc_t) map;
  24. /** Name of the cache file. */
  25. char *cache_fname;
  26. /** Name of the journal file. */
  27. char *journal_fname;
  28. /** Mmap'd contents of the cache file, or NULL if there is none. */
  29. tor_mmap_t *cache_content;
  30. /** Number of bytes used in the journal file. */
  31. size_t journal_len;
  32. /** Number of bytes in descriptors removed as too old. */
  33. size_t bytes_dropped;
  34. /** Total bytes of microdescriptor bodies we have added to this cache */
  35. uint64_t total_len_seen;
  36. /** Total number of microdescriptors we have added to this cache */
  37. unsigned n_seen;
  38. };
  39. /** Helper: computes a hash of <b>md</b> to place it in a hash table. */
  40. static INLINE unsigned int
  41. microdesc_hash_(microdesc_t *md)
  42. {
  43. unsigned *d = (unsigned*)md->digest;
  44. #if SIZEOF_INT == 4
  45. return d[0] ^ d[1] ^ d[2] ^ d[3] ^ d[4] ^ d[5] ^ d[6] ^ d[7];
  46. #else
  47. return d[0] ^ d[1] ^ d[2] ^ d[3];
  48. #endif
  49. }
  50. /** Helper: compares <b>a</b> and </b> for equality for hash-table purposes. */
  51. static INLINE int
  52. microdesc_eq_(microdesc_t *a, microdesc_t *b)
  53. {
  54. return tor_memeq(a->digest, b->digest, DIGEST256_LEN);
  55. }
  56. HT_PROTOTYPE(microdesc_map, microdesc_t, node,
  57. microdesc_hash_, microdesc_eq_);
  58. HT_GENERATE(microdesc_map, microdesc_t, node,
  59. microdesc_hash_, microdesc_eq_, 0.6,
  60. malloc, realloc, free);
  61. /** Write the body of <b>md</b> into <b>f</b>, with appropriate annotations.
  62. * On success, return the total number of bytes written, and set
  63. * *<b>annotation_len_out</b> to the number of bytes written as
  64. * annotations. */
  65. static ssize_t
  66. dump_microdescriptor(int fd, microdesc_t *md, size_t *annotation_len_out)
  67. {
  68. ssize_t r = 0;
  69. size_t written;
  70. /* XXXX drops unknown annotations. */
  71. if (md->last_listed) {
  72. char buf[ISO_TIME_LEN+1];
  73. char annotation[ISO_TIME_LEN+32];
  74. format_iso_time(buf, md->last_listed);
  75. tor_snprintf(annotation, sizeof(annotation), "@last-listed %s\n", buf);
  76. if (write_all(fd, annotation, strlen(annotation), 0) < 0) {
  77. log_warn(LD_DIR,
  78. "Couldn't write microdescriptor annotation: %s",
  79. strerror(errno));
  80. return -1;
  81. }
  82. r += strlen(annotation);
  83. *annotation_len_out = r;
  84. } else {
  85. *annotation_len_out = 0;
  86. }
  87. md->off = tor_fd_getpos(fd);
  88. written = write_all(fd, md->body, md->bodylen, 0);
  89. if (written != md->bodylen) {
  90. log_warn(LD_DIR,
  91. "Couldn't dump microdescriptor (wrote %lu out of %lu): %s",
  92. (unsigned long)written, (unsigned long)md->bodylen,
  93. strerror(errno));
  94. return -1;
  95. }
  96. r += md->bodylen;
  97. return r;
  98. }
  99. /** Holds a pointer to the current microdesc_cache_t object, or NULL if no
  100. * such object has been allocated. */
  101. static microdesc_cache_t *the_microdesc_cache = NULL;
  102. /** Return a pointer to the microdescriptor cache, loading it if necessary. */
  103. microdesc_cache_t *
  104. get_microdesc_cache(void)
  105. {
  106. if (PREDICT_UNLIKELY(the_microdesc_cache==NULL)) {
  107. microdesc_cache_t *cache = tor_malloc_zero(sizeof(microdesc_cache_t));
  108. HT_INIT(microdesc_map, &cache->map);
  109. cache->cache_fname = get_datadir_fname("cached-microdescs");
  110. cache->journal_fname = get_datadir_fname("cached-microdescs.new");
  111. microdesc_cache_reload(cache);
  112. the_microdesc_cache = cache;
  113. }
  114. return the_microdesc_cache;
  115. }
  116. /* There are three sources of microdescriptors:
  117. 1) Generated by us while acting as a directory authority.
  118. 2) Loaded from the cache on disk.
  119. 3) Downloaded.
  120. */
  121. /** Decode the microdescriptors from the string starting at <b>s</b> and
  122. * ending at <b>eos</b>, and store them in <b>cache</b>. If <b>no_save</b>,
  123. * mark them as non-writable to disk. If <b>where</b> is SAVED_IN_CACHE,
  124. * leave their bodies as pointers to the mmap'd cache. If where is
  125. * <b>SAVED_NOWHERE</b>, do not allow annotations. If listed_at is not -1,
  126. * set the last_listed field of every microdesc to listed_at. If
  127. * requested_digests is non-null, then it contains a list of digests we mean
  128. * to allow, so we should reject any non-requested microdesc with a different
  129. * digest, and alter the list to contain only the digests of those microdescs
  130. * we didn't find.
  131. * Return a newly allocated list of the added microdescriptors, or NULL */
  132. smartlist_t *
  133. microdescs_add_to_cache(microdesc_cache_t *cache,
  134. const char *s, const char *eos, saved_location_t where,
  135. int no_save, time_t listed_at,
  136. smartlist_t *requested_digests256)
  137. {
  138. smartlist_t *descriptors, *added;
  139. const int allow_annotations = (where != SAVED_NOWHERE);
  140. const int copy_body = (where != SAVED_IN_CACHE);
  141. descriptors = microdescs_parse_from_string(s, eos,
  142. allow_annotations,
  143. copy_body);
  144. if (listed_at != (time_t)-1) {
  145. SMARTLIST_FOREACH(descriptors, microdesc_t *, md,
  146. md->last_listed = listed_at);
  147. }
  148. if (requested_digests256) {
  149. digestmap_t *requested; /* XXXX actually we should just use a
  150. digest256map */
  151. requested = digestmap_new();
  152. SMARTLIST_FOREACH(requested_digests256, const char *, cp,
  153. digestmap_set(requested, cp, (void*)1));
  154. SMARTLIST_FOREACH_BEGIN(descriptors, microdesc_t *, md) {
  155. if (digestmap_get(requested, md->digest)) {
  156. digestmap_set(requested, md->digest, (void*)2);
  157. } else {
  158. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Received non-requested microdesc");
  159. microdesc_free(md);
  160. SMARTLIST_DEL_CURRENT(descriptors, md);
  161. }
  162. } SMARTLIST_FOREACH_END(md);
  163. SMARTLIST_FOREACH_BEGIN(requested_digests256, char *, cp) {
  164. if (digestmap_get(requested, cp) == (void*)2) {
  165. tor_free(cp);
  166. SMARTLIST_DEL_CURRENT(requested_digests256, cp);
  167. }
  168. } SMARTLIST_FOREACH_END(cp);
  169. digestmap_free(requested, NULL);
  170. }
  171. added = microdescs_add_list_to_cache(cache, descriptors, where, no_save);
  172. smartlist_free(descriptors);
  173. return added;
  174. }
  175. /** As microdescs_add_to_cache, but takes a list of microdescriptors instead of
  176. * a string to decode. Frees any members of <b>descriptors</b> that it does
  177. * not add. */
  178. smartlist_t *
  179. microdescs_add_list_to_cache(microdesc_cache_t *cache,
  180. smartlist_t *descriptors, saved_location_t where,
  181. int no_save)
  182. {
  183. smartlist_t *added;
  184. open_file_t *open_file = NULL;
  185. int fd = -1;
  186. // int n_added = 0;
  187. ssize_t size = 0;
  188. if (where == SAVED_NOWHERE && !no_save) {
  189. fd = start_writing_to_file(cache->journal_fname,
  190. OPEN_FLAGS_APPEND|O_BINARY,
  191. 0600, &open_file);
  192. if (fd < 0) {
  193. log_warn(LD_DIR, "Couldn't append to journal in %s: %s",
  194. cache->journal_fname, strerror(errno));
  195. return NULL;
  196. }
  197. }
  198. added = smartlist_new();
  199. SMARTLIST_FOREACH_BEGIN(descriptors, microdesc_t *, md) {
  200. microdesc_t *md2;
  201. md2 = HT_FIND(microdesc_map, &cache->map, md);
  202. if (md2) {
  203. /* We already had this one. */
  204. if (md2->last_listed < md->last_listed)
  205. md2->last_listed = md->last_listed;
  206. microdesc_free(md);
  207. if (where != SAVED_NOWHERE)
  208. cache->bytes_dropped += size;
  209. continue;
  210. }
  211. /* Okay, it's a new one. */
  212. if (fd >= 0) {
  213. size_t annotation_len;
  214. size = dump_microdescriptor(fd, md, &annotation_len);
  215. if (size < 0) {
  216. /* we already warned in dump_microdescriptor */
  217. abort_writing_to_file(open_file);
  218. smartlist_clear(added);
  219. return added;
  220. }
  221. md->saved_location = SAVED_IN_JOURNAL;
  222. cache->journal_len += size;
  223. } else {
  224. md->saved_location = where;
  225. }
  226. md->no_save = no_save;
  227. HT_INSERT(microdesc_map, &cache->map, md);
  228. md->held_in_map = 1;
  229. smartlist_add(added, md);
  230. ++cache->n_seen;
  231. cache->total_len_seen += md->bodylen;
  232. } SMARTLIST_FOREACH_END(md);
  233. if (fd >= 0) {
  234. if (finish_writing_to_file(open_file) < 0) {
  235. log_warn(LD_DIR, "Error appending to microdescriptor file: %s",
  236. strerror(errno));
  237. smartlist_clear(added);
  238. return added;
  239. }
  240. }
  241. {
  242. networkstatus_t *ns = networkstatus_get_latest_consensus();
  243. if (ns && ns->flavor == FLAV_MICRODESC)
  244. SMARTLIST_FOREACH(added, microdesc_t *, md, nodelist_add_microdesc(md));
  245. }
  246. if (smartlist_len(added))
  247. router_dir_info_changed();
  248. return added;
  249. }
  250. /** Remove every microdescriptor in <b>cache</b>. */
  251. void
  252. microdesc_cache_clear(microdesc_cache_t *cache)
  253. {
  254. microdesc_t **entry, **next;
  255. for (entry = HT_START(microdesc_map, &cache->map); entry; entry = next) {
  256. microdesc_t *md = *entry;
  257. next = HT_NEXT_RMV(microdesc_map, &cache->map, entry);
  258. md->held_in_map = 0;
  259. microdesc_free(md);
  260. }
  261. HT_CLEAR(microdesc_map, &cache->map);
  262. if (cache->cache_content) {
  263. tor_munmap_file(cache->cache_content);
  264. cache->cache_content = NULL;
  265. }
  266. cache->total_len_seen = 0;
  267. cache->n_seen = 0;
  268. cache->bytes_dropped = 0;
  269. }
  270. /** Reload the contents of <b>cache</b> from disk. If it is empty, load it
  271. * for the first time. Return 0 on success, -1 on failure. */
  272. int
  273. microdesc_cache_reload(microdesc_cache_t *cache)
  274. {
  275. struct stat st;
  276. char *journal_content;
  277. smartlist_t *added;
  278. tor_mmap_t *mm;
  279. int total = 0;
  280. microdesc_cache_clear(cache);
  281. mm = cache->cache_content = tor_mmap_file(cache->cache_fname);
  282. if (mm) {
  283. added = microdescs_add_to_cache(cache, mm->data, mm->data+mm->size,
  284. SAVED_IN_CACHE, 0, -1, NULL);
  285. if (added) {
  286. total += smartlist_len(added);
  287. smartlist_free(added);
  288. }
  289. }
  290. journal_content = read_file_to_str(cache->journal_fname,
  291. RFTS_IGNORE_MISSING, &st);
  292. if (journal_content) {
  293. cache->journal_len = (size_t) st.st_size;
  294. added = microdescs_add_to_cache(cache, journal_content,
  295. journal_content+st.st_size,
  296. SAVED_IN_JOURNAL, 0, -1, NULL);
  297. if (added) {
  298. total += smartlist_len(added);
  299. smartlist_free(added);
  300. }
  301. tor_free(journal_content);
  302. }
  303. log_info(LD_DIR, "Reloaded microdescriptor cache. Found %d descriptors.",
  304. total);
  305. microdesc_cache_rebuild(cache, 0 /* don't force */);
  306. return 0;
  307. }
  308. /** By default, we remove any microdescriptors that have gone at least this
  309. * long without appearing in a current consensus. */
  310. #define TOLERATE_MICRODESC_AGE (7*24*60*60)
  311. /** Remove all microdescriptors from <b>cache</b> that haven't been listed for
  312. * a long time. Does not rebuild the cache on disk. If <b>cutoff</b> is
  313. * positive, specifically remove microdescriptors that have been unlisted
  314. * since <b>cutoff</b>. If <b>force</b> is true, remove microdescriptors even
  315. * if we have no current live microdescriptor consensus.
  316. */
  317. void
  318. microdesc_cache_clean(microdesc_cache_t *cache, time_t cutoff, int force)
  319. {
  320. microdesc_t **mdp, *victim;
  321. int dropped=0, kept=0;
  322. size_t bytes_dropped = 0;
  323. time_t now = time(NULL);
  324. /* If we don't know a live consensus, don't believe last_listed values: we
  325. * might be starting up after being down for a while. */
  326. if (! force &&
  327. ! networkstatus_get_reasonably_live_consensus(now, FLAV_MICRODESC))
  328. return;
  329. if (cutoff <= 0)
  330. cutoff = now - TOLERATE_MICRODESC_AGE;
  331. for (mdp = HT_START(microdesc_map, &cache->map); mdp != NULL; ) {
  332. if ((*mdp)->last_listed < cutoff) {
  333. ++dropped;
  334. victim = *mdp;
  335. mdp = HT_NEXT_RMV(microdesc_map, &cache->map, mdp);
  336. victim->held_in_map = 0;
  337. bytes_dropped += victim->bodylen;
  338. microdesc_free(victim);
  339. } else {
  340. ++kept;
  341. mdp = HT_NEXT(microdesc_map, &cache->map, mdp);
  342. }
  343. }
  344. if (dropped) {
  345. log_info(LD_DIR, "Removed %d/%d microdescriptors as old.",
  346. dropped,dropped+kept);
  347. cache->bytes_dropped += bytes_dropped;
  348. }
  349. }
  350. static int
  351. should_rebuild_md_cache(microdesc_cache_t *cache)
  352. {
  353. const size_t old_len =
  354. cache->cache_content ? cache->cache_content->size : 0;
  355. const size_t journal_len = cache->journal_len;
  356. const size_t dropped = cache->bytes_dropped;
  357. if (journal_len < 16384)
  358. return 0; /* Don't bother, not enough has happened yet. */
  359. if (dropped > (journal_len + old_len) / 3)
  360. return 1; /* We could save 1/3 or more of the currently used space. */
  361. if (journal_len > old_len / 2)
  362. return 1; /* We should append to the regular file */
  363. return 0;
  364. }
  365. /** Regenerate the main cache file for <b>cache</b>, clear the journal file,
  366. * and update every microdesc_t in the cache with pointers to its new
  367. * location. If <b>force</b> is true, do this unconditionally. If
  368. * <b>force</b> is false, do it only if we expect to save space on disk. */
  369. int
  370. microdesc_cache_rebuild(microdesc_cache_t *cache, int force)
  371. {
  372. open_file_t *open_file;
  373. int fd = -1;
  374. microdesc_t **mdp;
  375. smartlist_t *wrote;
  376. ssize_t size;
  377. off_t off = 0, off_real;
  378. int orig_size, new_size;
  379. if (cache == NULL) {
  380. cache = the_microdesc_cache;
  381. if (cache == NULL)
  382. return 0;
  383. }
  384. /* Remove dead descriptors */
  385. microdesc_cache_clean(cache, 0/*cutoff*/, 0/*force*/);
  386. if (!force && !should_rebuild_md_cache(cache))
  387. return 0;
  388. log_info(LD_DIR, "Rebuilding the microdescriptor cache...");
  389. orig_size = (int)(cache->cache_content ? cache->cache_content->size : 0);
  390. orig_size += (int)cache->journal_len;
  391. fd = start_writing_to_file(cache->cache_fname,
  392. OPEN_FLAGS_REPLACE|O_BINARY,
  393. 0600, &open_file);
  394. if (fd < 0)
  395. return -1;
  396. wrote = smartlist_new();
  397. HT_FOREACH(mdp, microdesc_map, &cache->map) {
  398. microdesc_t *md = *mdp;
  399. size_t annotation_len;
  400. if (md->no_save)
  401. continue;
  402. size = dump_microdescriptor(fd, md, &annotation_len);
  403. if (size < 0) {
  404. /* XXX handle errors from dump_microdescriptor() */
  405. /* log? return -1? die? coredump the universe? */
  406. continue;
  407. }
  408. tor_assert(((size_t)size) == annotation_len + md->bodylen);
  409. md->off = off + annotation_len;
  410. off += size;
  411. off_real = tor_fd_getpos(fd);
  412. if (off_real != off) {
  413. log_warn(LD_BUG, "Discontinuity in position in microdescriptor cache."
  414. "By my count, I'm at "I64_FORMAT
  415. ", but I should be at "I64_FORMAT,
  416. I64_PRINTF_ARG(off), I64_PRINTF_ARG(off_real));
  417. off = off_real;
  418. }
  419. if (md->saved_location != SAVED_IN_CACHE) {
  420. tor_free(md->body);
  421. md->saved_location = SAVED_IN_CACHE;
  422. }
  423. smartlist_add(wrote, md);
  424. }
  425. if (finish_writing_to_file(open_file) < 0) {
  426. log_warn(LD_DIR, "Error rebuilding microdescriptor cache: %s",
  427. strerror(errno));
  428. return -1;
  429. }
  430. if (cache->cache_content)
  431. tor_munmap_file(cache->cache_content);
  432. cache->cache_content = tor_mmap_file(cache->cache_fname);
  433. if (!cache->cache_content && smartlist_len(wrote)) {
  434. log_err(LD_DIR, "Couldn't map file that we just wrote to %s!",
  435. cache->cache_fname);
  436. smartlist_free(wrote);
  437. return -1;
  438. }
  439. SMARTLIST_FOREACH_BEGIN(wrote, microdesc_t *, md) {
  440. tor_assert(md->saved_location == SAVED_IN_CACHE);
  441. md->body = (char*)cache->cache_content->data + md->off;
  442. if (PREDICT_UNLIKELY(
  443. md->bodylen < 9 || fast_memneq(md->body, "onion-key", 9) != 0)) {
  444. /* XXXX once bug 2022 is solved, we can kill this block and turn it
  445. * into just the tor_assert(fast_memeq) */
  446. off_t avail = cache->cache_content->size - md->off;
  447. char *bad_str;
  448. tor_assert(avail >= 0);
  449. bad_str = tor_strndup(md->body, MIN(128, (size_t)avail));
  450. log_err(LD_BUG, "After rebuilding microdesc cache, offsets seem wrong. "
  451. " At offset %d, I expected to find a microdescriptor starting "
  452. " with \"onion-key\". Instead I got %s.",
  453. (int)md->off, escaped(bad_str));
  454. tor_free(bad_str);
  455. tor_assert(fast_memeq(md->body, "onion-key", 9));
  456. }
  457. } SMARTLIST_FOREACH_END(md);
  458. smartlist_free(wrote);
  459. write_str_to_file(cache->journal_fname, "", 1);
  460. cache->journal_len = 0;
  461. cache->bytes_dropped = 0;
  462. new_size = cache->cache_content ? (int)cache->cache_content->size : 0;
  463. log_info(LD_DIR, "Done rebuilding microdesc cache. "
  464. "Saved %d bytes; %d still used.",
  465. orig_size-new_size, new_size);
  466. return 0;
  467. }
  468. /** Make sure that the reference count of every microdescriptor in cache is
  469. * accurate. */
  470. void
  471. microdesc_check_counts(void)
  472. {
  473. microdesc_t **mdp;
  474. if (!the_microdesc_cache)
  475. return;
  476. HT_FOREACH(mdp, microdesc_map, &the_microdesc_cache->map) {
  477. microdesc_t *md = *mdp;
  478. unsigned int found=0;
  479. const smartlist_t *nodes = nodelist_get_list();
  480. SMARTLIST_FOREACH(nodes, node_t *, node, {
  481. if (node->md == md) {
  482. ++found;
  483. }
  484. });
  485. tor_assert(found == md->held_by_nodes);
  486. }
  487. }
  488. /** Deallocate a single microdescriptor. Note: the microdescriptor MUST have
  489. * previously been removed from the cache if it had ever been inserted. */
  490. void
  491. microdesc_free_(microdesc_t *md, const char *fname, int lineno)
  492. {
  493. if (!md)
  494. return;
  495. /* Make sure that the microdesc was really removed from the appropriate data
  496. structures. */
  497. if (md->held_in_map) {
  498. microdesc_cache_t *cache = get_microdesc_cache();
  499. microdesc_t *md2 = HT_FIND(microdesc_map, &cache->map, md);
  500. if (md2 == md) {
  501. log_warn(LD_BUG, "microdesc_free() called from %s:%d, but md was still "
  502. "in microdesc_map", fname, lineno);
  503. HT_REMOVE(microdesc_map, &cache->map, md);
  504. } else {
  505. log_warn(LD_BUG, "microdesc_free() called from %s:%d with held_in_map "
  506. "set, but microdesc was not in the map.", fname, lineno);
  507. }
  508. tor_fragile_assert();
  509. }
  510. if (md->held_by_nodes) {
  511. int found=0;
  512. const smartlist_t *nodes = nodelist_get_list();
  513. SMARTLIST_FOREACH(nodes, node_t *, node, {
  514. if (node->md == md) {
  515. ++found;
  516. node->md = NULL;
  517. }
  518. });
  519. if (found) {
  520. log_warn(LD_BUG, "microdesc_free() called from %s:%d, but md was still "
  521. "referenced %d node(s); held_by_nodes == %u",
  522. fname, lineno, found, md->held_by_nodes);
  523. } else {
  524. log_warn(LD_BUG, "microdesc_free() called from %s:%d with held_by_nodes "
  525. "set to %u, but md was not referenced by any nodes",
  526. fname, lineno, md->held_by_nodes);
  527. }
  528. tor_fragile_assert();
  529. }
  530. //tor_assert(md->held_in_map == 0);
  531. //tor_assert(md->held_by_nodes == 0);
  532. if (md->onion_pkey)
  533. crypto_pk_free(md->onion_pkey);
  534. tor_free(md->onion_curve25519_pkey);
  535. if (md->body && md->saved_location != SAVED_IN_CACHE)
  536. tor_free(md->body);
  537. if (md->family) {
  538. SMARTLIST_FOREACH(md->family, char *, cp, tor_free(cp));
  539. smartlist_free(md->family);
  540. }
  541. short_policy_free(md->exit_policy);
  542. short_policy_free(md->ipv6_exit_policy);
  543. tor_free(md);
  544. }
  545. /** Free all storage held in the microdesc.c module. */
  546. void
  547. microdesc_free_all(void)
  548. {
  549. if (the_microdesc_cache) {
  550. microdesc_cache_clear(the_microdesc_cache);
  551. tor_free(the_microdesc_cache->cache_fname);
  552. tor_free(the_microdesc_cache->journal_fname);
  553. tor_free(the_microdesc_cache);
  554. }
  555. }
  556. /** If there is a microdescriptor in <b>cache</b> whose sha256 digest is
  557. * <b>d</b>, return it. Otherwise return NULL. */
  558. microdesc_t *
  559. microdesc_cache_lookup_by_digest256(microdesc_cache_t *cache, const char *d)
  560. {
  561. microdesc_t *md, search;
  562. if (!cache)
  563. cache = get_microdesc_cache();
  564. memcpy(search.digest, d, DIGEST256_LEN);
  565. md = HT_FIND(microdesc_map, &cache->map, &search);
  566. return md;
  567. }
  568. /** Return the mean size of decriptors added to <b>cache</b> since it was last
  569. * cleared. Used to estimate the size of large downloads. */
  570. size_t
  571. microdesc_average_size(microdesc_cache_t *cache)
  572. {
  573. if (!cache)
  574. cache = get_microdesc_cache();
  575. if (!cache->n_seen)
  576. return 512;
  577. return (size_t)(cache->total_len_seen / cache->n_seen);
  578. }
  579. /** Return a smartlist of all the sha256 digest of the microdescriptors that
  580. * are listed in <b>ns</b> but not present in <b>cache</b>. Returns pointers
  581. * to internals of <b>ns</b>; you should not free the members of the resulting
  582. * smartlist. Omit all microdescriptors whose digest appear in <b>skip</b>. */
  583. smartlist_t *
  584. microdesc_list_missing_digest256(networkstatus_t *ns, microdesc_cache_t *cache,
  585. int downloadable_only, digestmap_t *skip)
  586. {
  587. smartlist_t *result = smartlist_new();
  588. time_t now = time(NULL);
  589. tor_assert(ns->flavor == FLAV_MICRODESC);
  590. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  591. if (microdesc_cache_lookup_by_digest256(cache, rs->descriptor_digest))
  592. continue;
  593. if (downloadable_only &&
  594. !download_status_is_ready(&rs->dl_status, now,
  595. get_options()->TestingMicrodescMaxDownloadTries))
  596. continue;
  597. if (skip && digestmap_get(skip, rs->descriptor_digest))
  598. continue;
  599. if (tor_mem_is_zero(rs->descriptor_digest, DIGEST256_LEN))
  600. continue;
  601. /* XXXX Also skip if we're a noncache and wouldn't use this router.
  602. * XXXX NM Microdesc
  603. */
  604. smartlist_add(result, rs->descriptor_digest);
  605. } SMARTLIST_FOREACH_END(rs);
  606. return result;
  607. }
  608. /** Launch download requests for microdescriptors as appropriate.
  609. *
  610. * Specifically, we should launch download requests if we are configured to
  611. * download mirodescriptors, and there are some microdescriptors listed the
  612. * current microdesc consensus that we don't have, and either we never asked
  613. * for them, or we failed to download them but we're willing to retry.
  614. */
  615. void
  616. update_microdesc_downloads(time_t now)
  617. {
  618. const or_options_t *options = get_options();
  619. networkstatus_t *consensus;
  620. smartlist_t *missing;
  621. digestmap_t *pending;
  622. if (should_delay_dir_fetches(options))
  623. return;
  624. if (directory_too_idle_to_fetch_descriptors(options, now))
  625. return;
  626. consensus = networkstatus_get_reasonably_live_consensus(now, FLAV_MICRODESC);
  627. if (!consensus)
  628. return;
  629. if (!we_fetch_microdescriptors(options))
  630. return;
  631. pending = digestmap_new();
  632. list_pending_microdesc_downloads(pending);
  633. missing = microdesc_list_missing_digest256(consensus,
  634. get_microdesc_cache(),
  635. 1,
  636. pending);
  637. digestmap_free(pending, NULL);
  638. launch_descriptor_downloads(DIR_PURPOSE_FETCH_MICRODESC,
  639. missing, NULL, now);
  640. smartlist_free(missing);
  641. }
  642. /** For every microdescriptor listed in the current microdecriptor consensus,
  643. * update its last_listed field to be at least as recent as the publication
  644. * time of the current microdescriptor consensus.
  645. */
  646. void
  647. update_microdescs_from_networkstatus(time_t now)
  648. {
  649. microdesc_cache_t *cache = get_microdesc_cache();
  650. microdesc_t *md;
  651. networkstatus_t *ns =
  652. networkstatus_get_reasonably_live_consensus(now, FLAV_MICRODESC);
  653. if (! ns)
  654. return;
  655. tor_assert(ns->flavor == FLAV_MICRODESC);
  656. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  657. md = microdesc_cache_lookup_by_digest256(cache, rs->descriptor_digest);
  658. if (md && ns->valid_after > md->last_listed)
  659. md->last_listed = ns->valid_after;
  660. } SMARTLIST_FOREACH_END(rs);
  661. }
  662. /** Return true iff we should prefer to use microdescriptors rather than
  663. * routerdescs for building circuits. */
  664. int
  665. we_use_microdescriptors_for_circuits(const or_options_t *options)
  666. {
  667. int ret = options->UseMicrodescriptors;
  668. if (ret == -1) {
  669. /* UseMicrodescriptors is "auto"; we need to decide: */
  670. /* If we are configured to use bridges and none of our bridges
  671. * know what a microdescriptor is, the answer is no. */
  672. if (options->UseBridges && !any_bridge_supports_microdescriptors())
  673. return 0;
  674. /* Otherwise, we decide that we'll use microdescriptors iff we are
  675. * not a server, and we're not autofetching everything. */
  676. /* XXX023 what does not being a server have to do with it? also there's
  677. * a partitioning issue here where bridges differ from clients. */
  678. ret = !server_mode(options) && !options->FetchUselessDescriptors;
  679. }
  680. return ret;
  681. }
  682. /** Return true iff we should try to download microdescriptors at all. */
  683. int
  684. we_fetch_microdescriptors(const or_options_t *options)
  685. {
  686. if (directory_caches_dir_info(options))
  687. return 1;
  688. if (options->FetchUselessDescriptors)
  689. return 1;
  690. return we_use_microdescriptors_for_circuits(options);
  691. }
  692. /** Return true iff we should try to download router descriptors at all. */
  693. int
  694. we_fetch_router_descriptors(const or_options_t *options)
  695. {
  696. if (directory_caches_dir_info(options))
  697. return 1;
  698. if (options->FetchUselessDescriptors)
  699. return 1;
  700. return ! we_use_microdescriptors_for_circuits(options);
  701. }
  702. /** Return the consensus flavor we actually want to use to build circuits. */
  703. int
  704. usable_consensus_flavor(void)
  705. {
  706. if (we_use_microdescriptors_for_circuits(get_options())) {
  707. return FLAV_MICRODESC;
  708. } else {
  709. return FLAV_NS;
  710. }
  711. }