microdesc.c 31 KB

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