microdesc.c 34 KB

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