microdesc.c 34 KB

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