microdesc.c 34 KB

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