microdesc.c 35 KB

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