microdesc.c 34 KB

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