microdesc.c 31 KB

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