microdesc.c 26 KB

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