microdesc.c 34 KB

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