microdesc.c 34 KB

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