microdesc.c 34 KB

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