microdesc.c 31 KB

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