microdesc.c 34 KB

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