microdesc.c 34 KB

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