microdesc.c 34 KB

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