microdesc.c 34 KB

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