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/nodefamily.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. /* If we have a reasonably live consensus, then most of our dirservers should
  94. * still be caching all the microdescriptors in it. Reasonably live
  95. * consensuses are up to a day old (or a day in the future). But
  96. * microdescriptors expire 7 days after the last consensus that referenced
  97. * them. */
  98. if (!networkstatus_get_reasonably_live_consensus(approx_time(),
  99. FLAV_MICRODESC)) {
  100. return;
  101. }
  102. if (!outdated_dirserver_list) {
  103. outdated_dirserver_list = smartlist_new();
  104. }
  105. tor_assert(outdated_dirserver_list);
  106. /* If the list grows too big, clean it up */
  107. if (BUG(smartlist_len(outdated_dirserver_list) >
  108. TOO_MANY_OUTDATED_DIRSERVERS)) {
  109. microdesc_reset_outdated_dirservers_list();
  110. }
  111. /* Turn the binary relay digest to a hex since smartlists have better support
  112. * for strings than digests. */
  113. base16_encode(relay_hexdigest,sizeof(relay_hexdigest),
  114. relay_digest, DIGEST_LEN);
  115. /* Make sure we don't add a dirauth as an outdated dirserver */
  116. if (router_get_trusteddirserver_by_digest(relay_digest)) {
  117. log_info(LD_GENERAL, "Auth %s gave us outdated dirinfo.", relay_hexdigest);
  118. return;
  119. }
  120. /* Don't double-add outdated dirservers */
  121. if (smartlist_contains_string(outdated_dirserver_list, relay_hexdigest)) {
  122. return;
  123. }
  124. /* Add it to the list of outdated dirservers */
  125. smartlist_add_strdup(outdated_dirserver_list, relay_hexdigest);
  126. log_info(LD_GENERAL, "Noted %s as outdated md dirserver", relay_hexdigest);
  127. }
  128. /** Return True if the relay with <b>relay_digest</b> (size DIGEST_LEN) is an
  129. * outdated dirserver */
  130. int
  131. microdesc_relay_is_outdated_dirserver(const char *relay_digest)
  132. {
  133. char relay_hexdigest[HEX_DIGEST_LEN+1];
  134. if (!outdated_dirserver_list) {
  135. return 0;
  136. }
  137. /* Convert identity digest to hex digest */
  138. base16_encode(relay_hexdigest, sizeof(relay_hexdigest),
  139. relay_digest, DIGEST_LEN);
  140. /* Last time we tried to fetch microdescs, was this directory mirror missing
  141. * any mds we asked for? */
  142. if (smartlist_contains_string(outdated_dirserver_list, relay_hexdigest)) {
  143. return 1;
  144. }
  145. return 0;
  146. }
  147. /** Reset the list of outdated dirservers. */
  148. void
  149. microdesc_reset_outdated_dirservers_list(void)
  150. {
  151. if (!outdated_dirserver_list) {
  152. return;
  153. }
  154. SMARTLIST_FOREACH(outdated_dirserver_list, char *, cp, tor_free(cp));
  155. smartlist_clear(outdated_dirserver_list);
  156. }
  157. /****************************************************************************/
  158. /** Write the body of <b>md</b> into <b>f</b>, with appropriate annotations.
  159. * On success, return the total number of bytes written, and set
  160. * *<b>annotation_len_out</b> to the number of bytes written as
  161. * annotations. */
  162. static ssize_t
  163. dump_microdescriptor(int fd, microdesc_t *md, size_t *annotation_len_out)
  164. {
  165. ssize_t r = 0;
  166. ssize_t written;
  167. if (md->body == NULL) {
  168. *annotation_len_out = 0;
  169. return 0;
  170. }
  171. /* XXXX drops unknown annotations. */
  172. if (md->last_listed) {
  173. char buf[ISO_TIME_LEN+1];
  174. char annotation[ISO_TIME_LEN+32];
  175. format_iso_time(buf, md->last_listed);
  176. tor_snprintf(annotation, sizeof(annotation), "@last-listed %s\n", buf);
  177. if (write_all_to_fd(fd, annotation, strlen(annotation)) < 0) {
  178. log_warn(LD_DIR,
  179. "Couldn't write microdescriptor annotation: %s",
  180. strerror(errno));
  181. return -1;
  182. }
  183. r += strlen(annotation);
  184. *annotation_len_out = r;
  185. } else {
  186. *annotation_len_out = 0;
  187. }
  188. md->off = tor_fd_getpos(fd);
  189. written = write_all_to_fd(fd, md->body, md->bodylen);
  190. if (written != (ssize_t)md->bodylen) {
  191. written = written < 0 ? 0 : written;
  192. log_warn(LD_DIR,
  193. "Couldn't dump microdescriptor (wrote %ld out of %lu): %s",
  194. (long)written, (unsigned long)md->bodylen,
  195. strerror(errno));
  196. return -1;
  197. }
  198. r += md->bodylen;
  199. return r;
  200. }
  201. /** Holds a pointer to the current microdesc_cache_t object, or NULL if no
  202. * such object has been allocated. */
  203. static microdesc_cache_t *the_microdesc_cache = NULL;
  204. /** Return a pointer to the microdescriptor cache, loading it if necessary. */
  205. microdesc_cache_t *
  206. get_microdesc_cache(void)
  207. {
  208. microdesc_cache_t *cache = get_microdesc_cache_noload();
  209. if (PREDICT_UNLIKELY(cache->is_loaded == 0)) {
  210. microdesc_cache_reload(cache);
  211. }
  212. return cache;
  213. }
  214. /** Return a pointer to the microdescriptor cache, creating (but not loading)
  215. * it if necessary. */
  216. static microdesc_cache_t *
  217. get_microdesc_cache_noload(void)
  218. {
  219. if (PREDICT_UNLIKELY(the_microdesc_cache==NULL)) {
  220. microdesc_cache_t *cache = tor_malloc_zero(sizeof(*cache));
  221. HT_INIT(microdesc_map, &cache->map);
  222. cache->cache_fname = get_cachedir_fname("cached-microdescs");
  223. cache->journal_fname = get_cachedir_fname("cached-microdescs.new");
  224. the_microdesc_cache = cache;
  225. }
  226. return the_microdesc_cache;
  227. }
  228. /* There are three sources of microdescriptors:
  229. 1) Generated by us while acting as a directory authority.
  230. 2) Loaded from the cache on disk.
  231. 3) Downloaded.
  232. */
  233. /** Decode the microdescriptors from the string starting at <b>s</b> and
  234. * ending at <b>eos</b>, and store them in <b>cache</b>. If <b>no_save</b>,
  235. * mark them as non-writable to disk. If <b>where</b> is SAVED_IN_CACHE,
  236. * leave their bodies as pointers to the mmap'd cache. If where is
  237. * <b>SAVED_NOWHERE</b>, do not allow annotations. If listed_at is not -1,
  238. * set the last_listed field of every microdesc to listed_at. If
  239. * requested_digests is non-null, then it contains a list of digests we mean
  240. * to allow, so we should reject any non-requested microdesc with a different
  241. * digest, and alter the list to contain only the digests of those microdescs
  242. * we didn't find.
  243. * Return a newly allocated list of the added microdescriptors, or NULL */
  244. smartlist_t *
  245. microdescs_add_to_cache(microdesc_cache_t *cache,
  246. const char *s, const char *eos, saved_location_t where,
  247. int no_save, time_t listed_at,
  248. smartlist_t *requested_digests256)
  249. {
  250. void * const DIGEST_REQUESTED = (void*)1;
  251. void * const DIGEST_RECEIVED = (void*)2;
  252. void * const DIGEST_INVALID = (void*)3;
  253. smartlist_t *descriptors, *added;
  254. const int allow_annotations = (where != SAVED_NOWHERE);
  255. smartlist_t *invalid_digests = smartlist_new();
  256. descriptors = microdescs_parse_from_string(s, eos,
  257. allow_annotations,
  258. where, invalid_digests);
  259. if (listed_at != (time_t)-1) {
  260. SMARTLIST_FOREACH(descriptors, microdesc_t *, md,
  261. md->last_listed = listed_at);
  262. }
  263. if (requested_digests256) {
  264. digest256map_t *requested;
  265. requested = digest256map_new();
  266. /* Set requested[d] to DIGEST_REQUESTED for every md we requested. */
  267. SMARTLIST_FOREACH(requested_digests256, const uint8_t *, cp,
  268. digest256map_set(requested, cp, DIGEST_REQUESTED));
  269. /* Set requested[d] to DIGEST_INVALID for every md we requested which we
  270. * will never be able to parse. Remove the ones we didn't request from
  271. * invalid_digests.
  272. */
  273. SMARTLIST_FOREACH_BEGIN(invalid_digests, uint8_t *, cp) {
  274. if (digest256map_get(requested, cp)) {
  275. digest256map_set(requested, cp, DIGEST_INVALID);
  276. } else {
  277. tor_free(cp);
  278. SMARTLIST_DEL_CURRENT(invalid_digests, cp);
  279. }
  280. } SMARTLIST_FOREACH_END(cp);
  281. /* Update requested[d] to 2 for the mds we asked for and got. Delete the
  282. * ones we never requested from the 'descriptors' smartlist.
  283. */
  284. SMARTLIST_FOREACH_BEGIN(descriptors, microdesc_t *, md) {
  285. if (digest256map_get(requested, (const uint8_t*)md->digest)) {
  286. digest256map_set(requested, (const uint8_t*)md->digest,
  287. DIGEST_RECEIVED);
  288. } else {
  289. log_fn(LOG_PROTOCOL_WARN, LD_DIR, "Received non-requested microdesc");
  290. microdesc_free(md);
  291. SMARTLIST_DEL_CURRENT(descriptors, md);
  292. }
  293. } SMARTLIST_FOREACH_END(md);
  294. /* Remove the ones we got or the invalid ones from requested_digests256.
  295. */
  296. SMARTLIST_FOREACH_BEGIN(requested_digests256, uint8_t *, cp) {
  297. void *status = digest256map_get(requested, cp);
  298. if (status == DIGEST_RECEIVED || status == DIGEST_INVALID) {
  299. tor_free(cp);
  300. SMARTLIST_DEL_CURRENT(requested_digests256, cp);
  301. }
  302. } SMARTLIST_FOREACH_END(cp);
  303. digest256map_free(requested, NULL);
  304. }
  305. /* For every requested microdescriptor that was unparseable, mark it
  306. * as not to be retried. */
  307. if (smartlist_len(invalid_digests)) {
  308. networkstatus_t *ns =
  309. networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  310. if (ns) {
  311. SMARTLIST_FOREACH_BEGIN(invalid_digests, char *, d) {
  312. routerstatus_t *rs =
  313. router_get_mutable_consensus_status_by_descriptor_digest(ns, d);
  314. if (rs && tor_memeq(d, rs->descriptor_digest, DIGEST256_LEN)) {
  315. download_status_mark_impossible(&rs->dl_status);
  316. }
  317. } SMARTLIST_FOREACH_END(d);
  318. }
  319. }
  320. SMARTLIST_FOREACH(invalid_digests, uint8_t *, d, tor_free(d));
  321. smartlist_free(invalid_digests);
  322. added = microdescs_add_list_to_cache(cache, descriptors, where, no_save);
  323. smartlist_free(descriptors);
  324. return added;
  325. }
  326. /** As microdescs_add_to_cache, but takes a list of microdescriptors instead of
  327. * a string to decode. Frees any members of <b>descriptors</b> that it does
  328. * not add. */
  329. smartlist_t *
  330. microdescs_add_list_to_cache(microdesc_cache_t *cache,
  331. smartlist_t *descriptors, saved_location_t where,
  332. int no_save)
  333. {
  334. smartlist_t *added;
  335. open_file_t *open_file = NULL;
  336. int fd = -1;
  337. // int n_added = 0;
  338. ssize_t size = 0;
  339. if (where == SAVED_NOWHERE && !no_save) {
  340. fd = start_writing_to_file(cache->journal_fname,
  341. OPEN_FLAGS_APPEND|O_BINARY,
  342. 0600, &open_file);
  343. if (fd < 0) {
  344. log_warn(LD_DIR, "Couldn't append to journal in %s: %s",
  345. cache->journal_fname, strerror(errno));
  346. }
  347. }
  348. added = smartlist_new();
  349. SMARTLIST_FOREACH_BEGIN(descriptors, microdesc_t *, md) {
  350. microdesc_t *md2;
  351. md2 = HT_FIND(microdesc_map, &cache->map, md);
  352. if (md2) {
  353. /* We already had this one. */
  354. if (md2->last_listed < md->last_listed)
  355. md2->last_listed = md->last_listed;
  356. microdesc_free(md);
  357. if (where != SAVED_NOWHERE)
  358. cache->bytes_dropped += size;
  359. continue;
  360. }
  361. /* Okay, it's a new one. */
  362. if (fd >= 0) {
  363. size_t annotation_len;
  364. size = dump_microdescriptor(fd, md, &annotation_len);
  365. if (size < 0) {
  366. /* we already warned in dump_microdescriptor */
  367. abort_writing_to_file(open_file);
  368. fd = -1;
  369. } else {
  370. md->saved_location = SAVED_IN_JOURNAL;
  371. cache->journal_len += size;
  372. }
  373. } else {
  374. md->saved_location = where;
  375. }
  376. md->no_save = no_save;
  377. HT_INSERT(microdesc_map, &cache->map, md);
  378. md->held_in_map = 1;
  379. smartlist_add(added, md);
  380. ++cache->n_seen;
  381. cache->total_len_seen += md->bodylen;
  382. } SMARTLIST_FOREACH_END(md);
  383. if (fd >= 0) {
  384. if (finish_writing_to_file(open_file) < 0) {
  385. log_warn(LD_DIR, "Error appending to microdescriptor file: %s",
  386. strerror(errno));
  387. smartlist_clear(added);
  388. return added;
  389. }
  390. }
  391. {
  392. networkstatus_t *ns = networkstatus_get_latest_consensus();
  393. if (ns && ns->flavor == FLAV_MICRODESC)
  394. SMARTLIST_FOREACH(added, microdesc_t *, md, nodelist_add_microdesc(md));
  395. }
  396. if (smartlist_len(added))
  397. router_dir_info_changed();
  398. return added;
  399. }
  400. /** Remove every microdescriptor in <b>cache</b>. */
  401. void
  402. microdesc_cache_clear(microdesc_cache_t *cache)
  403. {
  404. microdesc_t **entry, **next;
  405. for (entry = HT_START(microdesc_map, &cache->map); entry; entry = next) {
  406. microdesc_t *md = *entry;
  407. next = HT_NEXT_RMV(microdesc_map, &cache->map, entry);
  408. md->held_in_map = 0;
  409. microdesc_free(md);
  410. }
  411. HT_CLEAR(microdesc_map, &cache->map);
  412. if (cache->cache_content) {
  413. int res = tor_munmap_file(cache->cache_content);
  414. if (res != 0) {
  415. log_warn(LD_FS,
  416. "tor_munmap_file() failed clearing microdesc cache; "
  417. "we are probably about to leak memory.");
  418. /* TODO something smarter? */
  419. }
  420. cache->cache_content = NULL;
  421. }
  422. cache->total_len_seen = 0;
  423. cache->n_seen = 0;
  424. cache->bytes_dropped = 0;
  425. }
  426. /** Reload the contents of <b>cache</b> from disk. If it is empty, load it
  427. * for the first time. Return 0 on success, -1 on failure. */
  428. int
  429. microdesc_cache_reload(microdesc_cache_t *cache)
  430. {
  431. struct stat st;
  432. char *journal_content;
  433. smartlist_t *added;
  434. tor_mmap_t *mm;
  435. int total = 0;
  436. microdesc_cache_clear(cache);
  437. cache->is_loaded = 1;
  438. mm = cache->cache_content = tor_mmap_file(cache->cache_fname);
  439. if (mm) {
  440. added = microdescs_add_to_cache(cache, mm->data, mm->data+mm->size,
  441. SAVED_IN_CACHE, 0, -1, NULL);
  442. if (added) {
  443. total += smartlist_len(added);
  444. smartlist_free(added);
  445. }
  446. }
  447. journal_content = read_file_to_str(cache->journal_fname,
  448. RFTS_IGNORE_MISSING, &st);
  449. if (journal_content) {
  450. cache->journal_len = (size_t) st.st_size;
  451. added = microdescs_add_to_cache(cache, journal_content,
  452. journal_content+st.st_size,
  453. SAVED_IN_JOURNAL, 0, -1, NULL);
  454. if (added) {
  455. total += smartlist_len(added);
  456. smartlist_free(added);
  457. }
  458. tor_free(journal_content);
  459. }
  460. log_info(LD_DIR, "Reloaded microdescriptor cache. Found %d descriptors.",
  461. total);
  462. microdesc_cache_rebuild(cache, 0 /* don't force */);
  463. return 0;
  464. }
  465. /** By default, we remove any microdescriptors that have gone at least this
  466. * long without appearing in a current consensus. */
  467. #define TOLERATE_MICRODESC_AGE (7*24*60*60)
  468. /** Remove all microdescriptors from <b>cache</b> that haven't been listed for
  469. * a long time. Does not rebuild the cache on disk. If <b>cutoff</b> is
  470. * positive, specifically remove microdescriptors that have been unlisted
  471. * since <b>cutoff</b>. If <b>force</b> is true, remove microdescriptors even
  472. * if we have no current live microdescriptor consensus.
  473. */
  474. void
  475. microdesc_cache_clean(microdesc_cache_t *cache, time_t cutoff, int force)
  476. {
  477. microdesc_t **mdp, *victim;
  478. int dropped=0, kept=0;
  479. size_t bytes_dropped = 0;
  480. time_t now = time(NULL);
  481. /* If we don't know a reasonably live consensus, don't believe last_listed
  482. * values: we might be starting up after being down for a while. */
  483. if (! force &&
  484. ! networkstatus_get_reasonably_live_consensus(now, FLAV_MICRODESC))
  485. return;
  486. if (cutoff <= 0)
  487. cutoff = now - TOLERATE_MICRODESC_AGE;
  488. for (mdp = HT_START(microdesc_map, &cache->map); mdp != NULL; ) {
  489. const int is_old = (*mdp)->last_listed < cutoff;
  490. const unsigned held_by_nodes = (*mdp)->held_by_nodes;
  491. if (is_old && !held_by_nodes) {
  492. ++dropped;
  493. victim = *mdp;
  494. mdp = HT_NEXT_RMV(microdesc_map, &cache->map, mdp);
  495. victim->held_in_map = 0;
  496. bytes_dropped += victim->bodylen;
  497. microdesc_free(victim);
  498. } else {
  499. if (is_old) {
  500. /* It's old, but it has held_by_nodes set. That's not okay. */
  501. /* Let's try to diagnose and fix #7164 . */
  502. smartlist_t *nodes = nodelist_find_nodes_with_microdesc(*mdp);
  503. const networkstatus_t *ns = networkstatus_get_latest_consensus();
  504. long networkstatus_age = -1;
  505. const int ht_badness = HT_REP_IS_BAD_(microdesc_map, &cache->map);
  506. if (ns) {
  507. networkstatus_age = now - ns->valid_after;
  508. }
  509. log_warn(LD_BUG, "Microdescriptor seemed very old "
  510. "(last listed %d hours ago vs %d hour cutoff), but is still "
  511. "marked as being held by %d node(s). I found %d node(s) "
  512. "holding it. Current networkstatus is %ld hours old. "
  513. "Hashtable badness is %d.",
  514. (int)((now - (*mdp)->last_listed) / 3600),
  515. (int)((now - cutoff) / 3600),
  516. held_by_nodes,
  517. smartlist_len(nodes),
  518. networkstatus_age / 3600,
  519. ht_badness);
  520. SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
  521. const char *rs_match = "No RS";
  522. const char *rs_present = "";
  523. if (node->rs) {
  524. if (tor_memeq(node->rs->descriptor_digest,
  525. (*mdp)->digest, DIGEST256_LEN)) {
  526. rs_match = "Microdesc digest in RS matches";
  527. } else {
  528. rs_match = "Microdesc digest in RS does match";
  529. }
  530. if (ns) {
  531. /* This should be impossible, but let's see! */
  532. rs_present = " RS not present in networkstatus.";
  533. SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *,rs, {
  534. if (rs == node->rs) {
  535. rs_present = " RS okay in networkstatus.";
  536. }
  537. });
  538. }
  539. }
  540. log_warn(LD_BUG, " [%d]: ID=%s. md=%p, rs=%p, ri=%p. %s.%s",
  541. node_sl_idx,
  542. hex_str(node->identity, DIGEST_LEN),
  543. node->md, node->rs, node->ri, rs_match, rs_present);
  544. } SMARTLIST_FOREACH_END(node);
  545. smartlist_free(nodes);
  546. (*mdp)->last_listed = now;
  547. }
  548. ++kept;
  549. mdp = HT_NEXT(microdesc_map, &cache->map, mdp);
  550. }
  551. }
  552. if (dropped) {
  553. log_info(LD_DIR, "Removed %d/%d microdescriptors as old.",
  554. dropped,dropped+kept);
  555. cache->bytes_dropped += bytes_dropped;
  556. }
  557. }
  558. static int
  559. should_rebuild_md_cache(microdesc_cache_t *cache)
  560. {
  561. const size_t old_len =
  562. cache->cache_content ? cache->cache_content->size : 0;
  563. const size_t journal_len = cache->journal_len;
  564. const size_t dropped = cache->bytes_dropped;
  565. if (journal_len < 16384)
  566. return 0; /* Don't bother, not enough has happened yet. */
  567. if (dropped > (journal_len + old_len) / 3)
  568. return 1; /* We could save 1/3 or more of the currently used space. */
  569. if (journal_len > old_len / 2)
  570. return 1; /* We should append to the regular file */
  571. return 0;
  572. }
  573. /**
  574. * Mark <b>md</b> as having no body, and release any storage previously held
  575. * by its body.
  576. */
  577. static void
  578. microdesc_wipe_body(microdesc_t *md)
  579. {
  580. if (!md)
  581. return;
  582. if (md->saved_location != SAVED_IN_CACHE)
  583. tor_free(md->body);
  584. md->off = 0;
  585. md->saved_location = SAVED_NOWHERE;
  586. md->body = NULL;
  587. md->bodylen = 0;
  588. md->no_save = 1;
  589. }
  590. /** Regenerate the main cache file for <b>cache</b>, clear the journal file,
  591. * and update every microdesc_t in the cache with pointers to its new
  592. * location. If <b>force</b> is true, do this unconditionally. If
  593. * <b>force</b> is false, do it only if we expect to save space on disk. */
  594. int
  595. microdesc_cache_rebuild(microdesc_cache_t *cache, int force)
  596. {
  597. open_file_t *open_file;
  598. int fd = -1, res;
  599. microdesc_t **mdp;
  600. smartlist_t *wrote;
  601. ssize_t size;
  602. off_t off = 0, off_real;
  603. int orig_size, new_size;
  604. if (cache == NULL) {
  605. cache = the_microdesc_cache;
  606. if (cache == NULL)
  607. return 0;
  608. }
  609. /* Remove dead descriptors */
  610. microdesc_cache_clean(cache, 0/*cutoff*/, 0/*force*/);
  611. if (!force && !should_rebuild_md_cache(cache))
  612. return 0;
  613. log_info(LD_DIR, "Rebuilding the microdescriptor cache...");
  614. orig_size = (int)(cache->cache_content ? cache->cache_content->size : 0);
  615. orig_size += (int)cache->journal_len;
  616. fd = start_writing_to_file(cache->cache_fname,
  617. OPEN_FLAGS_REPLACE|O_BINARY,
  618. 0600, &open_file);
  619. if (fd < 0)
  620. return -1;
  621. wrote = smartlist_new();
  622. HT_FOREACH(mdp, microdesc_map, &cache->map) {
  623. microdesc_t *md = *mdp;
  624. size_t annotation_len;
  625. if (md->no_save || !md->body)
  626. continue;
  627. size = dump_microdescriptor(fd, md, &annotation_len);
  628. if (size < 0) {
  629. microdesc_wipe_body(md);
  630. /* rewind, in case it was a partial write. */
  631. tor_fd_setpos(fd, off);
  632. continue;
  633. }
  634. tor_assert(((size_t)size) == annotation_len + md->bodylen);
  635. md->off = off + annotation_len;
  636. off += size;
  637. off_real = tor_fd_getpos(fd);
  638. if (off_real != off) {
  639. log_warn(LD_BUG, "Discontinuity in position in microdescriptor cache."
  640. "By my count, I'm at %"PRId64
  641. ", but I should be at %"PRId64,
  642. (int64_t)(off), (int64_t)(off_real));
  643. if (off_real >= 0)
  644. off = off_real;
  645. }
  646. if (md->saved_location != SAVED_IN_CACHE) {
  647. tor_free(md->body);
  648. md->saved_location = SAVED_IN_CACHE;
  649. }
  650. smartlist_add(wrote, md);
  651. }
  652. /* We must do this unmap _before_ we call finish_writing_to_file(), or
  653. * windows will not actually replace the file. */
  654. if (cache->cache_content) {
  655. res = tor_munmap_file(cache->cache_content);
  656. if (res != 0) {
  657. log_warn(LD_FS,
  658. "Failed to unmap old microdescriptor cache while rebuilding");
  659. }
  660. cache->cache_content = NULL;
  661. }
  662. if (finish_writing_to_file(open_file) < 0) {
  663. log_warn(LD_DIR, "Error rebuilding microdescriptor cache: %s",
  664. strerror(errno));
  665. /* Okay. Let's prevent from making things worse elsewhere. */
  666. cache->cache_content = NULL;
  667. HT_FOREACH(mdp, microdesc_map, &cache->map) {
  668. microdesc_t *md = *mdp;
  669. if (md->saved_location == SAVED_IN_CACHE) {
  670. microdesc_wipe_body(md);
  671. }
  672. }
  673. smartlist_free(wrote);
  674. return -1;
  675. }
  676. cache->cache_content = tor_mmap_file(cache->cache_fname);
  677. if (!cache->cache_content && smartlist_len(wrote)) {
  678. log_err(LD_DIR, "Couldn't map file that we just wrote to %s!",
  679. cache->cache_fname);
  680. smartlist_free(wrote);
  681. return -1;
  682. }
  683. SMARTLIST_FOREACH_BEGIN(wrote, microdesc_t *, md) {
  684. tor_assert(md->saved_location == SAVED_IN_CACHE);
  685. md->body = (char*)cache->cache_content->data + md->off;
  686. if (PREDICT_UNLIKELY(
  687. md->bodylen < 9 || fast_memneq(md->body, "onion-key", 9) != 0)) {
  688. /* XXXX once bug 2022 is solved, we can kill this block and turn it
  689. * into just the tor_assert(fast_memeq) */
  690. off_t avail = cache->cache_content->size - md->off;
  691. char *bad_str;
  692. tor_assert(avail >= 0);
  693. bad_str = tor_strndup(md->body, MIN(128, (size_t)avail));
  694. log_err(LD_BUG, "After rebuilding microdesc cache, offsets seem wrong. "
  695. " At offset %d, I expected to find a microdescriptor starting "
  696. " with \"onion-key\". Instead I got %s.",
  697. (int)md->off, escaped(bad_str));
  698. tor_free(bad_str);
  699. tor_assert(fast_memeq(md->body, "onion-key", 9));
  700. }
  701. } SMARTLIST_FOREACH_END(md);
  702. smartlist_free(wrote);
  703. write_str_to_file(cache->journal_fname, "", 1);
  704. cache->journal_len = 0;
  705. cache->bytes_dropped = 0;
  706. new_size = cache->cache_content ? (int)cache->cache_content->size : 0;
  707. log_info(LD_DIR, "Done rebuilding microdesc cache. "
  708. "Saved %d bytes; %d still used.",
  709. orig_size-new_size, new_size);
  710. return 0;
  711. }
  712. /** Make sure that the reference count of every microdescriptor in cache is
  713. * accurate. */
  714. void
  715. microdesc_check_counts(void)
  716. {
  717. microdesc_t **mdp;
  718. if (!the_microdesc_cache)
  719. return;
  720. HT_FOREACH(mdp, microdesc_map, &the_microdesc_cache->map) {
  721. microdesc_t *md = *mdp;
  722. unsigned int found=0;
  723. const smartlist_t *nodes = nodelist_get_list();
  724. SMARTLIST_FOREACH(nodes, node_t *, node, {
  725. if (node->md == md) {
  726. ++found;
  727. }
  728. });
  729. tor_assert(found == md->held_by_nodes);
  730. }
  731. }
  732. /** Deallocate a single microdescriptor. Note: the microdescriptor MUST have
  733. * previously been removed from the cache if it had ever been inserted. */
  734. void
  735. microdesc_free_(microdesc_t *md, const char *fname, int lineno)
  736. {
  737. if (!md)
  738. return;
  739. /* Make sure that the microdesc was really removed from the appropriate data
  740. structures. */
  741. if (md->held_in_map) {
  742. microdesc_cache_t *cache = get_microdesc_cache_noload();
  743. microdesc_t *md2 = HT_FIND(microdesc_map, &cache->map, md);
  744. if (md2 == md) {
  745. log_warn(LD_BUG, "microdesc_free() called from %s:%d, but md was still "
  746. "in microdesc_map", fname, lineno);
  747. HT_REMOVE(microdesc_map, &cache->map, md);
  748. } else {
  749. log_warn(LD_BUG, "microdesc_free() called from %s:%d with held_in_map "
  750. "set, but microdesc was not in the map.", fname, lineno);
  751. }
  752. tor_fragile_assert();
  753. }
  754. if (md->held_by_nodes) {
  755. microdesc_cache_t *cache = get_microdesc_cache_noload();
  756. int found=0;
  757. const smartlist_t *nodes = nodelist_get_list();
  758. const int ht_badness = HT_REP_IS_BAD_(microdesc_map, &cache->map);
  759. SMARTLIST_FOREACH(nodes, node_t *, node, {
  760. if (node->md == md) {
  761. ++found;
  762. node->md = NULL;
  763. }
  764. });
  765. if (found) {
  766. log_warn(LD_BUG, "microdesc_free() called from %s:%d, but md was still "
  767. "referenced %d node(s); held_by_nodes == %u, ht_badness == %d",
  768. fname, lineno, found, md->held_by_nodes, ht_badness);
  769. } else {
  770. log_warn(LD_BUG, "microdesc_free() called from %s:%d with held_by_nodes "
  771. "set to %u, but md was not referenced by any nodes. "
  772. "ht_badness == %d",
  773. fname, lineno, md->held_by_nodes, ht_badness);
  774. }
  775. tor_fragile_assert();
  776. }
  777. //tor_assert(md->held_in_map == 0);
  778. //tor_assert(md->held_by_nodes == 0);
  779. if (md->onion_pkey)
  780. tor_free(md->onion_pkey);
  781. tor_free(md->onion_curve25519_pkey);
  782. tor_free(md->ed25519_identity_pkey);
  783. if (md->body && md->saved_location != SAVED_IN_CACHE)
  784. tor_free(md->body);
  785. nodefamily_free(md->family);
  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. /* Give up if we don't have a reasonably live consensus. */
  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. }