consdiffmgr.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. /* Copyright (c) 2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file consdiffmsr.c
  5. *
  6. * \brief consensus diff manager functions
  7. *
  8. * This module is run by directory authorities and caches in order
  9. * to remember a number of past consensus documents, and to generate
  10. * and serve the diffs from those documents to the latest consensus.
  11. */
  12. #define CONSDIFFMGR_PRIVATE
  13. #include "or.h"
  14. #include "conscache.h"
  15. #include "consdiff.h"
  16. #include "consdiffmgr.h"
  17. #include "cpuworker.h"
  18. #include "networkstatus.h"
  19. #include "routerparse.h"
  20. #include "workqueue.h"
  21. /**
  22. * Labels to apply to items in the conscache object.
  23. *
  24. * @{
  25. */
  26. /* One of DOCTYPE_CONSENSUS or DOCTYPE_CONSENSUS_DIFF */
  27. #define LABEL_DOCTYPE "document-type"
  28. /* The valid-after time for a consensus (or for the target consensus of a
  29. * diff), encoded as ISO UTC. */
  30. #define LABEL_VALID_AFTER "consensus-valid-after"
  31. /* A hex encoded SHA3 digest of the object, as compressed (if any) */
  32. #define LABEL_SHA3_DIGEST "sha3-digest"
  33. /* A hex encoded SHA3 digest of the object before compression. */
  34. #define LABEL_SHA3_DIGEST_UNCOMPRESSED "sha3-digest-uncompressed"
  35. /* A hex encoded SHA3 digest-as-signed of a consensus */
  36. #define LABEL_SHA3_DIGEST_AS_SIGNED "sha3-digest-as-signed"
  37. /* The flavor of the consensus or consensuses diff */
  38. #define LABEL_FLAVOR "consensus-flavor"
  39. /* Diff only: the SHA3 digest-as-signed of the source consensus. */
  40. #define LABEL_FROM_SHA3_DIGEST "from-sha3-digest"
  41. /* Diff only: the SHA3 digest-in-full of the target consensus. */
  42. #define LABEL_TARGET_SHA3_DIGEST "target-sha3-digest"
  43. /* Diff only: the valid-after date of the source consensus. */
  44. #define LABEL_FROM_VALID_AFTER "from-valid-after"
  45. /* What kind of compression was used? */
  46. #define LABEL_COMPRESSION_TYPE "compression"
  47. /** @} */
  48. #define DOCTYPE_CONSENSUS "consensus"
  49. #define DOCTYPE_CONSENSUS_DIFF "consensus-diff"
  50. /**
  51. * Underlying directory that stores consensuses and consensus diffs. Don't
  52. * use this directly: use cdm_cache_get() instead.
  53. */
  54. static consensus_cache_t *cons_diff_cache = NULL;
  55. /**
  56. * If true, we have learned at least one new consensus since the
  57. * consensus cache was last up-to-date.
  58. */
  59. static int cdm_cache_dirty = 0;
  60. /**
  61. * If true, we have scanned the cache to update our hashtable of diffs.
  62. */
  63. static int cdm_cache_loaded = 0;
  64. /**
  65. * Possible status values for cdm_diff_t.cdm_diff_status
  66. **/
  67. typedef enum cdm_diff_status_t {
  68. CDM_DIFF_PRESENT=1,
  69. CDM_DIFF_IN_PROGRESS=2,
  70. CDM_DIFF_ERROR=3,
  71. } cdm_diff_status_t;
  72. /** Which methods do we use for precompressing diffs? */
  73. static const compress_method_t compress_diffs_with[] = {
  74. NO_METHOD,
  75. GZIP_METHOD,
  76. #ifdef HAVE_LZMA
  77. LZMA_METHOD,
  78. #endif
  79. #ifdef HAVE_ZSTD
  80. ZSTD_METHOD,
  81. #endif
  82. };
  83. /** How many different methods will we try to use for diff compression? */
  84. STATIC unsigned
  85. n_diff_compression_methods(void)
  86. {
  87. return ARRAY_LENGTH(compress_diffs_with);
  88. }
  89. /** Which methods do we use for precompressing consensuses? */
  90. static const compress_method_t compress_consensus_with[] = {
  91. ZLIB_METHOD,
  92. #ifdef HAVE_LZMA
  93. LZMA_METHOD,
  94. #endif
  95. #ifdef HAVE_ZSTD
  96. ZSTD_METHOD,
  97. #endif
  98. };
  99. /** How many different methods will we try to use for diff compression? */
  100. static unsigned
  101. n_consensus_compression_methods(void)
  102. {
  103. return ARRAY_LENGTH(compress_consensus_with);
  104. }
  105. /** For which compression method do we retain old consensuses? There's no
  106. * need to keep all of them, since we won't be serving them. We'll
  107. * go with ZLIB_METHOD because it's pretty fast and everyone has it.
  108. */
  109. #define RETAIN_CONSENSUS_COMPRESSED_WITH_METHOD ZLIB_METHOD
  110. /** Hashtable node used to remember the current status of the diff
  111. * from a given sha3 digest to the current consensus. */
  112. typedef struct cdm_diff_t {
  113. HT_ENTRY(cdm_diff_t) node;
  114. /** Consensus flavor for this diff (part of ht key) */
  115. consensus_flavor_t flavor;
  116. /** SHA3-256 digest of the consensus that this diff is _from_. (part of the
  117. * ht key) */
  118. uint8_t from_sha3[DIGEST256_LEN];
  119. /** Method by which the diff is compressed. (part of the ht key */
  120. compress_method_t compress_method;
  121. /** One of the CDM_DIFF_* values, depending on whether this diff
  122. * is available, in progress, or impossible to compute. */
  123. cdm_diff_status_t cdm_diff_status;
  124. /** SHA3-256 digest of the consensus that this diff is _to. */
  125. uint8_t target_sha3[DIGEST256_LEN];
  126. /** Handle to the cache entry for this diff, if any. We use a handle here
  127. * to avoid thinking too hard about cache entry lifetime issues. */
  128. consensus_cache_entry_handle_t *entry;
  129. } cdm_diff_t;
  130. /** Hashtable mapping flavor and source consensus digest to status. */
  131. static HT_HEAD(cdm_diff_ht, cdm_diff_t) cdm_diff_ht = HT_INITIALIZER();
  132. /**
  133. * Configuration for this module
  134. */
  135. static consdiff_cfg_t consdiff_cfg = {
  136. /* .cache_max_age_hours = */ 24 * 90,
  137. // XXXX I'd like to make this number bigger, but it interferes with the
  138. // XXXX seccomp2 syscall filter, which tops out at BPF_MAXINS (4096)
  139. // XXXX rules.
  140. /* .cache_max_num = */ 128
  141. };
  142. static int consdiffmgr_ensure_space_for_files(int n);
  143. static int consensus_queue_compression_work(const char *consensus,
  144. consensus_flavor_t flavor,
  145. time_t valid_after);
  146. static int consensus_diff_queue_diff_work(consensus_cache_entry_t *diff_from,
  147. consensus_cache_entry_t *diff_to);
  148. static void consdiffmgr_set_cache_flags(void);
  149. /* =====
  150. * Hashtable setup
  151. * ===== */
  152. /** Helper: hash the key of a cdm_diff_t. */
  153. static unsigned
  154. cdm_diff_hash(const cdm_diff_t *diff)
  155. {
  156. uint8_t tmp[DIGEST256_LEN + 2];
  157. memcpy(tmp, diff->from_sha3, DIGEST256_LEN);
  158. tmp[DIGEST256_LEN] = (uint8_t) diff->flavor;
  159. tmp[DIGEST256_LEN+1] = (uint8_t) diff->compress_method;
  160. return (unsigned) siphash24g(tmp, sizeof(tmp));
  161. }
  162. /** Helper: compare two cdm_diff_t objects for key equality */
  163. static int
  164. cdm_diff_eq(const cdm_diff_t *diff1, const cdm_diff_t *diff2)
  165. {
  166. return fast_memeq(diff1->from_sha3, diff2->from_sha3, DIGEST256_LEN) &&
  167. diff1->flavor == diff2->flavor &&
  168. diff1->compress_method == diff2->compress_method;
  169. }
  170. HT_PROTOTYPE(cdm_diff_ht, cdm_diff_t, node, cdm_diff_hash, cdm_diff_eq)
  171. HT_GENERATE2(cdm_diff_ht, cdm_diff_t, node, cdm_diff_hash, cdm_diff_eq,
  172. 0.6, tor_reallocarray, tor_free_)
  173. /** Release all storage held in <b>diff</b>. */
  174. static void
  175. cdm_diff_free(cdm_diff_t *diff)
  176. {
  177. if (!diff)
  178. return;
  179. consensus_cache_entry_handle_free(diff->entry);
  180. tor_free(diff);
  181. }
  182. /** Create and return a new cdm_diff_t with the given values. Does not
  183. * add it to the hashtable. */
  184. static cdm_diff_t *
  185. cdm_diff_new(consensus_flavor_t flav,
  186. const uint8_t *from_sha3,
  187. const uint8_t *target_sha3,
  188. compress_method_t method)
  189. {
  190. cdm_diff_t *ent;
  191. ent = tor_malloc_zero(sizeof(cdm_diff_t));
  192. ent->flavor = flav;
  193. memcpy(ent->from_sha3, from_sha3, DIGEST256_LEN);
  194. memcpy(ent->target_sha3, target_sha3, DIGEST256_LEN);
  195. ent->compress_method = method;
  196. return ent;
  197. }
  198. /**
  199. * Examine the diff hashtable to see whether we know anything about computing
  200. * a diff of type <b>flav</b> between consensuses with the two provided
  201. * SHA3-256 digests. If a computation is in progress, or if the computation
  202. * has already been tried and failed, return 1. Otherwise, note the
  203. * computation as "in progress" so that we don't reattempt it later, and
  204. * return 0.
  205. */
  206. static int
  207. cdm_diff_ht_check_and_note_pending(consensus_flavor_t flav,
  208. const uint8_t *from_sha3,
  209. const uint8_t *target_sha3)
  210. {
  211. struct cdm_diff_t search, *ent;
  212. unsigned u;
  213. int result = 0;
  214. for (u = 0; u < n_diff_compression_methods(); ++u) {
  215. compress_method_t method = compress_diffs_with[u];
  216. memset(&search, 0, sizeof(cdm_diff_t));
  217. search.flavor = flav;
  218. search.compress_method = method;
  219. memcpy(search.from_sha3, from_sha3, DIGEST256_LEN);
  220. ent = HT_FIND(cdm_diff_ht, &cdm_diff_ht, &search);
  221. if (ent) {
  222. tor_assert_nonfatal(ent->cdm_diff_status != CDM_DIFF_PRESENT);
  223. result = 1;
  224. continue;
  225. }
  226. ent = cdm_diff_new(flav, from_sha3, target_sha3, method);
  227. ent->cdm_diff_status = CDM_DIFF_IN_PROGRESS;
  228. HT_INSERT(cdm_diff_ht, &cdm_diff_ht, ent);
  229. }
  230. return result;
  231. }
  232. /**
  233. * Update the status of the diff of type <b>flav</b> between consensuses with
  234. * the two provided SHA3-256 digests, so that its status becomes
  235. * <b>status</b>, and its value becomes the <b>handle</b>. If <b>handle</b>
  236. * is NULL, then the old handle (if any) is freed, and replaced with NULL.
  237. */
  238. static void
  239. cdm_diff_ht_set_status(consensus_flavor_t flav,
  240. const uint8_t *from_sha3,
  241. const uint8_t *to_sha3,
  242. compress_method_t method,
  243. int status,
  244. consensus_cache_entry_handle_t *handle)
  245. {
  246. struct cdm_diff_t search, *ent;
  247. memset(&search, 0, sizeof(cdm_diff_t));
  248. search.flavor = flav;
  249. search.compress_method = method,
  250. memcpy(search.from_sha3, from_sha3, DIGEST256_LEN);
  251. ent = HT_FIND(cdm_diff_ht, &cdm_diff_ht, &search);
  252. if (!ent) {
  253. ent = cdm_diff_new(flav, from_sha3, to_sha3, method);
  254. ent->cdm_diff_status = CDM_DIFF_IN_PROGRESS;
  255. HT_INSERT(cdm_diff_ht, &cdm_diff_ht, ent);
  256. } else if (fast_memneq(ent->target_sha3, to_sha3, DIGEST256_LEN)) {
  257. // This can happen under certain really pathological conditions
  258. // if we decide we don't care about a diff before it is actually
  259. // done computing.
  260. return;
  261. }
  262. tor_assert_nonfatal(ent->cdm_diff_status == CDM_DIFF_IN_PROGRESS);
  263. ent->cdm_diff_status = status;
  264. consensus_cache_entry_handle_free(ent->entry);
  265. ent->entry = handle;
  266. }
  267. /**
  268. * Helper: Remove from the hash table every present (actually computed) diff
  269. * of type <b>flav</b> whose target digest does not match
  270. * <b>unless_target_sha3_matches</b>.
  271. *
  272. * This function is used for the hash table to throw away references to diffs
  273. * that do not lead to the most given consensus of a given flavor.
  274. */
  275. static void
  276. cdm_diff_ht_purge(consensus_flavor_t flav,
  277. const uint8_t *unless_target_sha3_matches)
  278. {
  279. cdm_diff_t **diff, **next;
  280. for (diff = HT_START(cdm_diff_ht, &cdm_diff_ht); diff; diff = next) {
  281. cdm_diff_t *this = *diff;
  282. if ((*diff)->cdm_diff_status == CDM_DIFF_PRESENT &&
  283. flav == (*diff)->flavor) {
  284. if (consensus_cache_entry_handle_get((*diff)->entry) == NULL) {
  285. /* the underlying entry has gone away; drop this. */
  286. next = HT_NEXT_RMV(cdm_diff_ht, &cdm_diff_ht, diff);
  287. cdm_diff_free(this);
  288. continue;
  289. }
  290. if (unless_target_sha3_matches &&
  291. fast_memneq(unless_target_sha3_matches, (*diff)->target_sha3,
  292. DIGEST256_LEN)) {
  293. /* target hash doesn't match; drop this. */
  294. next = HT_NEXT_RMV(cdm_diff_ht, &cdm_diff_ht, diff);
  295. cdm_diff_free(this);
  296. continue;
  297. }
  298. }
  299. next = HT_NEXT(cdm_diff_ht, &cdm_diff_ht, diff);
  300. }
  301. }
  302. /**
  303. * Helper: initialize <b>cons_diff_cache</b>.
  304. */
  305. static void
  306. cdm_cache_init(void)
  307. {
  308. unsigned n_entries = consdiff_cfg.cache_max_num * 2;
  309. tor_assert(cons_diff_cache == NULL);
  310. cons_diff_cache = consensus_cache_open("diff-cache", n_entries);
  311. if (cons_diff_cache == NULL) {
  312. // LCOV_EXCL_START
  313. log_err(LD_FS, "Error: Couldn't open storage for consensus diffs.");
  314. tor_assert_unreached();
  315. // LCOV_EXCL_STOP
  316. } else {
  317. consdiffmgr_set_cache_flags();
  318. }
  319. cdm_cache_dirty = 1;
  320. cdm_cache_loaded = 0;
  321. }
  322. /**
  323. * Helper: return the consensus_cache_t * that backs this manager,
  324. * initializing it if needed.
  325. */
  326. STATIC consensus_cache_t *
  327. cdm_cache_get(void)
  328. {
  329. if (PREDICT_UNLIKELY(cons_diff_cache == NULL)) {
  330. cdm_cache_init();
  331. }
  332. return cons_diff_cache;
  333. }
  334. /**
  335. * Helper: given a list of labels, prepend the hex-encoded SHA3 digest
  336. * of the <b>bodylen</b>-byte object at <b>body</b> to those labels,
  337. * with <b>label</b> as its label.
  338. */
  339. static void
  340. cdm_labels_prepend_sha3(config_line_t **labels,
  341. const char *label,
  342. const uint8_t *body,
  343. size_t bodylen)
  344. {
  345. uint8_t sha3_digest[DIGEST256_LEN];
  346. char hexdigest[HEX_DIGEST256_LEN+1];
  347. crypto_digest256((char *)sha3_digest,
  348. (const char *)body, bodylen, DIGEST_SHA3_256);
  349. base16_encode(hexdigest, sizeof(hexdigest),
  350. (const char *)sha3_digest, sizeof(sha3_digest));
  351. config_line_prepend(labels, label, hexdigest);
  352. }
  353. /** Helper: if there is a sha3-256 hex-encoded digest in <b>ent</b> with the
  354. * given label, set <b>digest_out</b> to that value (decoded), and return 0.
  355. *
  356. * Return -1 if there is no such label, and -2 if it is badly formatted. */
  357. STATIC int
  358. cdm_entry_get_sha3_value(uint8_t *digest_out,
  359. consensus_cache_entry_t *ent,
  360. const char *label)
  361. {
  362. if (ent == NULL)
  363. return -1;
  364. const char *hex = consensus_cache_entry_get_value(ent, label);
  365. if (hex == NULL)
  366. return -1;
  367. int n = base16_decode((char*)digest_out, DIGEST256_LEN, hex, strlen(hex));
  368. if (n != DIGEST256_LEN)
  369. return -2;
  370. else
  371. return 0;
  372. }
  373. /**
  374. * Helper: look for a consensus with the given <b>flavor</b> and
  375. * <b>valid_after</b> time in the cache. Return that consensus if it's
  376. * present, or NULL if it's missing.
  377. */
  378. STATIC consensus_cache_entry_t *
  379. cdm_cache_lookup_consensus(consensus_flavor_t flavor, time_t valid_after)
  380. {
  381. char formatted_time[ISO_TIME_LEN+1];
  382. format_iso_time_nospace(formatted_time, valid_after);
  383. const char *flavname = networkstatus_get_flavor_name(flavor);
  384. /* We'll filter by valid-after time first, since that should
  385. * match the fewest documents. */
  386. /* We could add an extra hashtable here, but since we only do this scan
  387. * when adding a new consensus, it probably doesn't matter much. */
  388. smartlist_t *matches = smartlist_new();
  389. consensus_cache_find_all(matches, cdm_cache_get(),
  390. LABEL_VALID_AFTER, formatted_time);
  391. consensus_cache_filter_list(matches, LABEL_FLAVOR, flavname);
  392. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  393. consensus_cache_entry_t *result = NULL;
  394. if (smartlist_len(matches)) {
  395. result = smartlist_get(matches, 0);
  396. }
  397. smartlist_free(matches);
  398. return result;
  399. }
  400. /**
  401. * Given a string containing a networkstatus consensus, and the results of
  402. * having parsed that consensus, add that consensus to the cache if it is not
  403. * already present and not too old. Create new consensus diffs from or to
  404. * that consensus as appropriate.
  405. *
  406. * Return 0 on success and -1 on failure.
  407. */
  408. int
  409. consdiffmgr_add_consensus(const char *consensus,
  410. const networkstatus_t *as_parsed)
  411. {
  412. if (BUG(consensus == NULL) || BUG(as_parsed == NULL))
  413. return -1; // LCOV_EXCL_LINE
  414. if (BUG(as_parsed->type != NS_TYPE_CONSENSUS))
  415. return -1; // LCOV_EXCL_LINE
  416. const consensus_flavor_t flavor = as_parsed->flavor;
  417. const time_t valid_after = as_parsed->valid_after;
  418. if (valid_after < approx_time() - 3600 * consdiff_cfg.cache_max_age_hours) {
  419. log_info(LD_DIRSERV, "We don't care about this consensus document; it's "
  420. "too old.");
  421. return -1;
  422. }
  423. /* Do we already have this one? */
  424. consensus_cache_entry_t *entry =
  425. cdm_cache_lookup_consensus(flavor, valid_after);
  426. if (entry) {
  427. log_info(LD_DIRSERV, "We already have a copy of that consensus");
  428. return -1;
  429. }
  430. /* We don't have it. Add it to the cache. */
  431. return consensus_queue_compression_work(consensus, flavor, valid_after);
  432. }
  433. /**
  434. * Helper: used to sort two smartlists of consensus_cache_entry_t by their
  435. * LABEL_VALID_AFTER labels.
  436. */
  437. static int
  438. compare_by_valid_after_(const void **a, const void **b)
  439. {
  440. const consensus_cache_entry_t *e1 = *a;
  441. const consensus_cache_entry_t *e2 = *b;
  442. /* We're in luck here: sorting UTC iso-encoded values lexically will work
  443. * fine (until 9999). */
  444. return strcmp_opt(consensus_cache_entry_get_value(e1, LABEL_VALID_AFTER),
  445. consensus_cache_entry_get_value(e2, LABEL_VALID_AFTER));
  446. }
  447. /**
  448. * Helper: Sort <b>lst</b> by LABEL_VALID_AFTER and return the most recent
  449. * entry.
  450. */
  451. static consensus_cache_entry_t *
  452. sort_and_find_most_recent(smartlist_t *lst)
  453. {
  454. smartlist_sort(lst, compare_by_valid_after_);
  455. if (smartlist_len(lst)) {
  456. return smartlist_get(lst, smartlist_len(lst) - 1);
  457. } else {
  458. return NULL;
  459. }
  460. }
  461. /**
  462. * Look up consensus_cache_entry_t for the consensus of type <b>flavor</b>,
  463. * from the source consensus with the specified digest (which must be SHA3).
  464. *
  465. * If the diff is present, store it into *<b>entry_out</b> and return
  466. * CONSDIFF_AVAILABLE. Otherwise return CONSDIFF_NOT_FOUND or
  467. * CONSDIFF_IN_PROGRESS.
  468. */
  469. consdiff_status_t
  470. consdiffmgr_find_diff_from(consensus_cache_entry_t **entry_out,
  471. consensus_flavor_t flavor,
  472. int digest_type,
  473. const uint8_t *digest,
  474. size_t digestlen,
  475. compress_method_t method)
  476. {
  477. if (BUG(digest_type != DIGEST_SHA3_256) ||
  478. BUG(digestlen != DIGEST256_LEN)) {
  479. return CONSDIFF_NOT_FOUND; // LCOV_EXCL_LINE
  480. }
  481. // Try to look up the entry in the hashtable.
  482. cdm_diff_t search, *ent;
  483. memset(&search, 0, sizeof(search));
  484. search.flavor = flavor;
  485. search.compress_method = method;
  486. memcpy(search.from_sha3, digest, DIGEST256_LEN);
  487. ent = HT_FIND(cdm_diff_ht, &cdm_diff_ht, &search);
  488. if (ent == NULL ||
  489. ent->cdm_diff_status == CDM_DIFF_ERROR) {
  490. return CONSDIFF_NOT_FOUND;
  491. } else if (ent->cdm_diff_status == CDM_DIFF_IN_PROGRESS) {
  492. return CONSDIFF_IN_PROGRESS;
  493. } else if (BUG(ent->cdm_diff_status != CDM_DIFF_PRESENT)) {
  494. return CONSDIFF_IN_PROGRESS;
  495. }
  496. *entry_out = consensus_cache_entry_handle_get(ent->entry);
  497. return (*entry_out) ? CONSDIFF_AVAILABLE : CONSDIFF_NOT_FOUND;
  498. #if 0
  499. // XXXX Remove this. I'm keeping it around for now in case we need to
  500. // XXXX debug issues in the hashtable.
  501. char hex[HEX_DIGEST256_LEN+1];
  502. base16_encode(hex, sizeof(hex), (const char *)digest, digestlen);
  503. const char *flavname = networkstatus_get_flavor_name(flavor);
  504. smartlist_t *matches = smartlist_new();
  505. consensus_cache_find_all(matches, cdm_cache_get(),
  506. LABEL_FROM_SHA3_DIGEST, hex);
  507. consensus_cache_filter_list(matches, LABEL_FLAVOR, flavname);
  508. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  509. *entry_out = sort_and_find_most_recent(matches);
  510. consdiff_status_t result =
  511. (*entry_out) ? CONSDIFF_AVAILABLE : CONSDIFF_NOT_FOUND;
  512. smartlist_free(matches);
  513. return result;
  514. #endif
  515. }
  516. /**
  517. * Perform periodic cleanup tasks on the consensus diff cache. Return
  518. * the number of objects marked for deletion.
  519. */
  520. int
  521. consdiffmgr_cleanup(void)
  522. {
  523. smartlist_t *objects = smartlist_new();
  524. smartlist_t *consensuses = smartlist_new();
  525. smartlist_t *diffs = smartlist_new();
  526. int n_to_delete = 0;
  527. log_debug(LD_DIRSERV, "Looking for consdiffmgr entries to remove");
  528. // 1. Delete any consensus or diff or anything whose valid_after is too old.
  529. const time_t valid_after_cutoff =
  530. approx_time() - 3600 * consdiff_cfg.cache_max_age_hours;
  531. consensus_cache_find_all(objects, cdm_cache_get(),
  532. NULL, NULL);
  533. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  534. const char *lv_valid_after =
  535. consensus_cache_entry_get_value(ent, LABEL_VALID_AFTER);
  536. if (! lv_valid_after) {
  537. log_debug(LD_DIRSERV, "Ignoring entry because it had no %s label",
  538. LABEL_VALID_AFTER);
  539. continue;
  540. }
  541. time_t valid_after = 0;
  542. if (parse_iso_time_nospace(lv_valid_after, &valid_after) < 0) {
  543. log_debug(LD_DIRSERV, "Ignoring entry because its %s value (%s) was "
  544. "unparseable", LABEL_VALID_AFTER, escaped(lv_valid_after));
  545. continue;
  546. }
  547. if (valid_after < valid_after_cutoff) {
  548. log_debug(LD_DIRSERV, "Deleting entry because its %s value (%s) was "
  549. "too old", LABEL_VALID_AFTER, lv_valid_after);
  550. consensus_cache_entry_mark_for_removal(ent);
  551. ++n_to_delete;
  552. }
  553. } SMARTLIST_FOREACH_END(ent);
  554. // 2. Delete all diffs that lead to a consensus whose valid-after is not the
  555. // latest.
  556. for (int flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  557. const char *flavname = networkstatus_get_flavor_name(flav);
  558. /* Determine the most recent consensus of this flavor */
  559. consensus_cache_find_all(consensuses, cdm_cache_get(),
  560. LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  561. consensus_cache_filter_list(consensuses, LABEL_FLAVOR, flavname);
  562. consensus_cache_entry_t *most_recent =
  563. sort_and_find_most_recent(consensuses);
  564. if (most_recent == NULL)
  565. continue;
  566. const char *most_recent_sha3 =
  567. consensus_cache_entry_get_value(most_recent,
  568. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  569. if (BUG(most_recent_sha3 == NULL))
  570. continue; // LCOV_EXCL_LINE
  571. /* consider all such-flavored diffs, and look to see if they match. */
  572. consensus_cache_find_all(diffs, cdm_cache_get(),
  573. LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  574. consensus_cache_filter_list(diffs, LABEL_FLAVOR, flavname);
  575. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  576. const char *this_diff_target_sha3 =
  577. consensus_cache_entry_get_value(diff, LABEL_TARGET_SHA3_DIGEST);
  578. if (!this_diff_target_sha3)
  579. continue;
  580. if (strcmp(this_diff_target_sha3, most_recent_sha3)) {
  581. consensus_cache_entry_mark_for_removal(diff);
  582. ++n_to_delete;
  583. }
  584. } SMARTLIST_FOREACH_END(diff);
  585. smartlist_clear(consensuses);
  586. smartlist_clear(diffs);
  587. }
  588. // 3. Delete all consensuses except the most recent that are compressed with
  589. // an un-preferred method.
  590. for (int flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  591. const char *flavname = networkstatus_get_flavor_name(flav);
  592. /* Determine the most recent consensus of this flavor */
  593. consensus_cache_find_all(consensuses, cdm_cache_get(),
  594. LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  595. consensus_cache_filter_list(consensuses, LABEL_FLAVOR, flavname);
  596. consensus_cache_entry_t *most_recent =
  597. sort_and_find_most_recent(consensuses);
  598. if (most_recent == NULL)
  599. continue;
  600. const char *most_recent_sha3_uncompressed =
  601. consensus_cache_entry_get_value(most_recent,
  602. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  603. const char *retain_methodname = compression_method_get_name(
  604. RETAIN_CONSENSUS_COMPRESSED_WITH_METHOD);
  605. if (BUG(most_recent_sha3_uncompressed == NULL))
  606. continue;
  607. SMARTLIST_FOREACH_BEGIN(consensuses, consensus_cache_entry_t *, ent) {
  608. const char *lv_sha3_uncompressed =
  609. consensus_cache_entry_get_value(ent, LABEL_SHA3_DIGEST_UNCOMPRESSED);
  610. if (BUG(! lv_sha3_uncompressed))
  611. continue;
  612. if (!strcmp(lv_sha3_uncompressed, most_recent_sha3_uncompressed))
  613. continue; // This _is_ the most recent.
  614. const char *lv_methodname =
  615. consensus_cache_entry_get_value(ent, LABEL_COMPRESSION_TYPE);
  616. if (! lv_methodname || strcmp(lv_methodname, retain_methodname)) {
  617. consensus_cache_entry_mark_for_removal(ent);
  618. ++n_to_delete;
  619. }
  620. } SMARTLIST_FOREACH_END(ent);
  621. }
  622. smartlist_free(objects);
  623. smartlist_free(consensuses);
  624. smartlist_free(diffs);
  625. // Actually remove files, if they're not used.
  626. consensus_cache_delete_pending(cdm_cache_get(), 0);
  627. return n_to_delete;
  628. }
  629. /**
  630. * Initialize the consensus diff manager and its cache, and configure
  631. * its parameters based on the latest torrc and networkstatus parameters.
  632. */
  633. void
  634. consdiffmgr_configure(const consdiff_cfg_t *cfg)
  635. {
  636. if (cfg)
  637. memcpy(&consdiff_cfg, cfg, sizeof(consdiff_cfg));
  638. (void) cdm_cache_get();
  639. }
  640. /**
  641. * Tell the sandbox (if any) configured by <b>cfg</b> to allow the
  642. * operations that the consensus diff manager will need.
  643. */
  644. int
  645. consdiffmgr_register_with_sandbox(struct sandbox_cfg_elem **cfg)
  646. {
  647. return consensus_cache_register_with_sandbox(cdm_cache_get(), cfg);
  648. }
  649. /**
  650. * Scan the consensus diff manager's cache for any grossly malformed entries,
  651. * and mark them as deletable. Return 0 if no problems were found; 1
  652. * if problems were found and fixed.
  653. */
  654. int
  655. consdiffmgr_validate(void)
  656. {
  657. /* Right now, we only check for entries that have bad sha3 values */
  658. int problems = 0;
  659. smartlist_t *objects = smartlist_new();
  660. consensus_cache_find_all(objects, cdm_cache_get(),
  661. NULL, NULL);
  662. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, obj) {
  663. uint8_t sha3_expected[DIGEST256_LEN];
  664. uint8_t sha3_received[DIGEST256_LEN];
  665. int r = cdm_entry_get_sha3_value(sha3_expected, obj, LABEL_SHA3_DIGEST);
  666. if (r == -1) {
  667. /* digest isn't there; that's allowed */
  668. continue;
  669. } else if (r == -2) {
  670. /* digest is malformed; that's not allowed */
  671. problems = 1;
  672. consensus_cache_entry_mark_for_removal(obj);
  673. continue;
  674. }
  675. const uint8_t *body;
  676. size_t bodylen;
  677. consensus_cache_entry_incref(obj);
  678. r = consensus_cache_entry_get_body(obj, &body, &bodylen);
  679. if (r == 0) {
  680. crypto_digest256((char *)sha3_received, (const char *)body, bodylen,
  681. DIGEST_SHA3_256);
  682. }
  683. consensus_cache_entry_decref(obj);
  684. if (r < 0)
  685. continue;
  686. // Deconfuse coverity about the possibility of sha3_received being
  687. // uninitialized
  688. tor_assert(r <= 0);
  689. if (fast_memneq(sha3_received, sha3_expected, DIGEST256_LEN)) {
  690. problems = 1;
  691. consensus_cache_entry_mark_for_removal(obj);
  692. continue;
  693. }
  694. } SMARTLIST_FOREACH_END(obj);
  695. smartlist_free(objects);
  696. return problems;
  697. }
  698. /**
  699. * Helper: build new diffs of <b>flavor</b> as needed
  700. */
  701. static void
  702. consdiffmgr_rescan_flavor_(consensus_flavor_t flavor)
  703. {
  704. smartlist_t *matches = NULL;
  705. smartlist_t *diffs = NULL;
  706. smartlist_t *compute_diffs_from = NULL;
  707. strmap_t *have_diff_from = NULL;
  708. // look for the most recent consensus, and for all previous in-range
  709. // consensuses. Do they all have diffs to it?
  710. const char *flavname = networkstatus_get_flavor_name(flavor);
  711. // 1. find the most recent consensus, and the ones that we might want
  712. // to diff to it.
  713. const char *methodname = compression_method_get_name(
  714. RETAIN_CONSENSUS_COMPRESSED_WITH_METHOD);
  715. matches = smartlist_new();
  716. consensus_cache_find_all(matches, cdm_cache_get(),
  717. LABEL_FLAVOR, flavname);
  718. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  719. consensus_cache_filter_list(matches, LABEL_COMPRESSION_TYPE, methodname);
  720. consensus_cache_entry_t *most_recent = sort_and_find_most_recent(matches);
  721. if (!most_recent) {
  722. log_info(LD_DIRSERV, "No 'most recent' %s consensus found; "
  723. "not making diffs", flavname);
  724. goto done;
  725. }
  726. tor_assert(smartlist_len(matches));
  727. smartlist_del(matches, smartlist_len(matches) - 1);
  728. const char *most_recent_valid_after =
  729. consensus_cache_entry_get_value(most_recent, LABEL_VALID_AFTER);
  730. if (BUG(most_recent_valid_after == NULL))
  731. goto done; //LCOV_EXCL_LINE
  732. uint8_t most_recent_sha3[DIGEST256_LEN];
  733. if (BUG(cdm_entry_get_sha3_value(most_recent_sha3, most_recent,
  734. LABEL_SHA3_DIGEST_UNCOMPRESSED) < 0))
  735. goto done; //LCOV_EXCL_LINE
  736. // 2. Find all the relevant diffs _to_ this consensus. These are ones
  737. // that we don't need to compute.
  738. diffs = smartlist_new();
  739. consensus_cache_find_all(diffs, cdm_cache_get(),
  740. LABEL_VALID_AFTER, most_recent_valid_after);
  741. consensus_cache_filter_list(diffs, LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  742. consensus_cache_filter_list(diffs, LABEL_FLAVOR, flavname);
  743. have_diff_from = strmap_new();
  744. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  745. const char *va = consensus_cache_entry_get_value(diff,
  746. LABEL_FROM_VALID_AFTER);
  747. if (BUG(va == NULL))
  748. continue; // LCOV_EXCL_LINE
  749. strmap_set(have_diff_from, va, diff);
  750. } SMARTLIST_FOREACH_END(diff);
  751. // 3. See which consensuses in 'matches' don't have diffs yet.
  752. smartlist_reverse(matches); // from newest to oldest.
  753. compute_diffs_from = smartlist_new();
  754. SMARTLIST_FOREACH_BEGIN(matches, consensus_cache_entry_t *, ent) {
  755. const char *va = consensus_cache_entry_get_value(ent, LABEL_VALID_AFTER);
  756. if (BUG(va == NULL))
  757. continue; // LCOV_EXCL_LINE
  758. if (strmap_get(have_diff_from, va) != NULL)
  759. continue; /* we already have this one. */
  760. smartlist_add(compute_diffs_from, ent);
  761. /* Since we are not going to serve this as the most recent consensus
  762. * any more, we should stop keeping it mmap'd when it's not in use.
  763. */
  764. consensus_cache_entry_mark_for_aggressive_release(ent);
  765. } SMARTLIST_FOREACH_END(ent);
  766. log_info(LD_DIRSERV,
  767. "The most recent %s consensus is valid-after %s. We have diffs to "
  768. "this consensus for %d/%d older %s consensuses. Generating diffs "
  769. "for the other %d.",
  770. flavname,
  771. most_recent_valid_after,
  772. smartlist_len(matches) - smartlist_len(compute_diffs_from),
  773. smartlist_len(matches),
  774. flavname,
  775. smartlist_len(compute_diffs_from));
  776. // 4. Update the hashtable; remove entries in this flavor to other
  777. // target consensuses.
  778. cdm_diff_ht_purge(flavor, most_recent_sha3);
  779. // 5. Actually launch the requests.
  780. SMARTLIST_FOREACH_BEGIN(compute_diffs_from, consensus_cache_entry_t *, c) {
  781. if (BUG(c == most_recent))
  782. continue; // LCOV_EXCL_LINE
  783. uint8_t this_sha3[DIGEST256_LEN];
  784. if (cdm_entry_get_sha3_value(this_sha3, c,
  785. LABEL_SHA3_DIGEST_AS_SIGNED)<0) {
  786. // Not actually a bug, since we might be running with a directory
  787. // with stale files from before the #22143 fixes.
  788. continue;
  789. }
  790. if (cdm_diff_ht_check_and_note_pending(flavor,
  791. this_sha3, most_recent_sha3)) {
  792. // This is already pending, or we encountered an error.
  793. continue;
  794. }
  795. consensus_diff_queue_diff_work(c, most_recent);
  796. } SMARTLIST_FOREACH_END(c);
  797. done:
  798. smartlist_free(matches);
  799. smartlist_free(diffs);
  800. smartlist_free(compute_diffs_from);
  801. strmap_free(have_diff_from, NULL);
  802. }
  803. /**
  804. * Scan the cache for diffs, and add them to the hashtable.
  805. */
  806. static void
  807. consdiffmgr_diffs_load(void)
  808. {
  809. smartlist_t *diffs = smartlist_new();
  810. consensus_cache_find_all(diffs, cdm_cache_get(),
  811. LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  812. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  813. const char *lv_flavor =
  814. consensus_cache_entry_get_value(diff, LABEL_FLAVOR);
  815. if (!lv_flavor)
  816. continue;
  817. int flavor = networkstatus_parse_flavor_name(lv_flavor);
  818. if (flavor < 0)
  819. continue;
  820. const char *lv_compression =
  821. consensus_cache_entry_get_value(diff, LABEL_COMPRESSION_TYPE);
  822. compress_method_t method = NO_METHOD;
  823. if (lv_compression) {
  824. method = compression_method_get_by_name(lv_compression);
  825. if (method == UNKNOWN_METHOD) {
  826. continue;
  827. }
  828. }
  829. uint8_t from_sha3[DIGEST256_LEN];
  830. uint8_t to_sha3[DIGEST256_LEN];
  831. if (cdm_entry_get_sha3_value(from_sha3, diff, LABEL_FROM_SHA3_DIGEST)<0)
  832. continue;
  833. if (cdm_entry_get_sha3_value(to_sha3, diff, LABEL_TARGET_SHA3_DIGEST)<0)
  834. continue;
  835. cdm_diff_ht_set_status(flavor, from_sha3, to_sha3,
  836. method,
  837. CDM_DIFF_PRESENT,
  838. consensus_cache_entry_handle_new(diff));
  839. } SMARTLIST_FOREACH_END(diff);
  840. smartlist_free(diffs);
  841. }
  842. /**
  843. * Build new diffs as needed.
  844. */
  845. void
  846. consdiffmgr_rescan(void)
  847. {
  848. if (cdm_cache_dirty == 0)
  849. return;
  850. // Clean up here to make room for new diffs, and to ensure that older
  851. // consensuses do not have any entries.
  852. consdiffmgr_cleanup();
  853. if (cdm_cache_loaded == 0) {
  854. consdiffmgr_diffs_load();
  855. cdm_cache_loaded = 1;
  856. }
  857. for (int flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  858. consdiffmgr_rescan_flavor_((consensus_flavor_t) flav);
  859. }
  860. cdm_cache_dirty = 0;
  861. }
  862. /**
  863. * Helper: compare two files by their from-valid-after and valid-after labels,
  864. * trying to sort in ascending order by from-valid-after (when present) and
  865. * valid-after (when not). Place everything that has neither label first in
  866. * the list.
  867. */
  868. static int
  869. compare_by_staleness_(const void **a, const void **b)
  870. {
  871. const consensus_cache_entry_t *e1 = *a;
  872. const consensus_cache_entry_t *e2 = *b;
  873. const char *va1, *fva1, *va2, *fva2;
  874. va1 = consensus_cache_entry_get_value(e1, LABEL_VALID_AFTER);
  875. va2 = consensus_cache_entry_get_value(e2, LABEL_VALID_AFTER);
  876. fva1 = consensus_cache_entry_get_value(e1, LABEL_FROM_VALID_AFTER);
  877. fva2 = consensus_cache_entry_get_value(e2, LABEL_FROM_VALID_AFTER);
  878. if (fva1)
  879. va1 = fva1;
  880. if (fva2)
  881. va2 = fva2;
  882. /* See note about iso-encoded values in compare_by_valid_after_. Also note
  883. * that missing dates will get placed first. */
  884. return strcmp_opt(va1, va2);
  885. }
  886. /** If there are not enough unused filenames to store <b>n</b> files, then
  887. * delete old consensuses until there are. (We have to keep track of the
  888. * number of filenames because of the way that the seccomp2 cache works.)
  889. *
  890. * Return 0 on success, -1 on failure.
  891. **/
  892. static int
  893. consdiffmgr_ensure_space_for_files(int n)
  894. {
  895. consensus_cache_t *cache = cdm_cache_get();
  896. if (consensus_cache_get_n_filenames_available(cache) >= n) {
  897. // there are already enough unused filenames.
  898. return 0;
  899. }
  900. // Try a cheap deletion of stuff that's waiting to get deleted.
  901. consensus_cache_delete_pending(cache, 0);
  902. if (consensus_cache_get_n_filenames_available(cache) >= n) {
  903. // okay, _that_ made enough filenames available.
  904. return 0;
  905. }
  906. // Let's get more assertive: clean out unused stuff, and force-remove
  907. // the files.
  908. consdiffmgr_cleanup();
  909. consensus_cache_delete_pending(cache, 1);
  910. const int n_to_remove = n - consensus_cache_get_n_filenames_available(cache);
  911. if (n_to_remove <= 0) {
  912. // okay, finally!
  913. return 0;
  914. }
  915. // At this point, we're going to have to throw out objects that will be
  916. // missed. Too bad!
  917. smartlist_t *objects = smartlist_new();
  918. consensus_cache_find_all(objects, cache, NULL, NULL);
  919. smartlist_sort(objects, compare_by_staleness_);
  920. int n_marked = 0;
  921. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  922. consensus_cache_entry_mark_for_removal(ent);
  923. if (++n_marked >= n_to_remove)
  924. break;
  925. } SMARTLIST_FOREACH_END(ent);
  926. consensus_cache_delete_pending(cache, 1);
  927. if (BUG(n_marked < n_to_remove))
  928. return -1;
  929. else
  930. return 0;
  931. }
  932. /**
  933. * Set consensus cache flags on the objects in this consdiffmgr.
  934. */
  935. static void
  936. consdiffmgr_set_cache_flags(void)
  937. {
  938. /* Right now, we just mark the consensus objects for aggressive release,
  939. * so that they get mmapped for as little time as possible. */
  940. smartlist_t *objects = smartlist_new();
  941. consensus_cache_find_all(objects, cdm_cache_get(), LABEL_DOCTYPE,
  942. DOCTYPE_CONSENSUS);
  943. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  944. consensus_cache_entry_mark_for_aggressive_release(ent);
  945. } SMARTLIST_FOREACH_END(ent);
  946. smartlist_free(objects);
  947. }
  948. /**
  949. * Called before shutdown: drop all storage held by the consdiffmgr.c module.
  950. */
  951. void
  952. consdiffmgr_free_all(void)
  953. {
  954. cdm_diff_t **diff, **next;
  955. for (diff = HT_START(cdm_diff_ht, &cdm_diff_ht); diff; diff = next) {
  956. cdm_diff_t *this = *diff;
  957. next = HT_NEXT_RMV(cdm_diff_ht, &cdm_diff_ht, diff);
  958. cdm_diff_free(this);
  959. }
  960. consensus_cache_free(cons_diff_cache);
  961. cons_diff_cache = NULL;
  962. }
  963. /* =====
  964. Thread workers
  965. =====*/
  966. typedef struct compressed_result_t {
  967. config_line_t *labels;
  968. /**
  969. * Output: Body of the diff, as compressed.
  970. */
  971. uint8_t *body;
  972. /**
  973. * Output: length of body_out
  974. */
  975. size_t bodylen;
  976. } compressed_result_t;
  977. /**
  978. * Compress the bytestring <b>input</b> of length <b>len</b> using the
  979. * <n>n_methods</b> compression methods listed in the array <b>methods</b>.
  980. *
  981. * For each successful compression, set the fields in the <b>results_out</b>
  982. * array in the position corresponding to the compression method. Use
  983. * <b>labels_in</b> as a basis for the labels of the result.
  984. *
  985. * Return 0 if all compression succeeded; -1 if any failed.
  986. */
  987. static int
  988. compress_multiple(compressed_result_t *results_out, int n_methods,
  989. const compress_method_t *methods,
  990. const uint8_t *input, size_t len,
  991. const config_line_t *labels_in)
  992. {
  993. int rv = 0;
  994. int i;
  995. for (i = 0; i < n_methods; ++i) {
  996. compress_method_t method = methods[i];
  997. const char *methodname = compression_method_get_name(method);
  998. char *result;
  999. size_t sz;
  1000. if (0 == tor_compress(&result, &sz, (const char*)input, len, method)) {
  1001. results_out[i].body = (uint8_t*)result;
  1002. results_out[i].bodylen = sz;
  1003. results_out[i].labels = config_lines_dup(labels_in);
  1004. cdm_labels_prepend_sha3(&results_out[i].labels, LABEL_SHA3_DIGEST,
  1005. results_out[i].body,
  1006. results_out[i].bodylen);
  1007. config_line_prepend(&results_out[i].labels,
  1008. LABEL_COMPRESSION_TYPE,
  1009. methodname);
  1010. } else {
  1011. rv = -1;
  1012. }
  1013. }
  1014. return rv;
  1015. }
  1016. /**
  1017. * Given an array of <b>n</b> compressed_result_t in <b>results</b>,
  1018. * as produced by compress_multiple, store them all into the
  1019. * consdiffmgr, and store handles to them in the <b>handles_out</b>
  1020. * array.
  1021. *
  1022. * Return CDM_DIFF_PRESENT if any was stored, and CDM_DIFF_ERROR if none
  1023. * was stored.
  1024. */
  1025. static cdm_diff_status_t
  1026. store_multiple(consensus_cache_entry_handle_t **handles_out,
  1027. int n,
  1028. const compress_method_t *methods,
  1029. const compressed_result_t *results,
  1030. const char *description)
  1031. {
  1032. cdm_diff_status_t status = CDM_DIFF_ERROR;
  1033. consdiffmgr_ensure_space_for_files(n);
  1034. int i;
  1035. for (i = 0; i < n; ++i) {
  1036. compress_method_t method = methods[i];
  1037. uint8_t *body_out = results[i].body;
  1038. size_t bodylen_out = results[i].bodylen;
  1039. config_line_t *labels = results[i].labels;
  1040. const char *methodname = compression_method_get_name(method);
  1041. if (body_out && bodylen_out && labels) {
  1042. /* Success! Store the results */
  1043. log_info(LD_DIRSERV, "Adding %s, compressed with %s",
  1044. description, methodname);
  1045. consensus_cache_entry_t *ent =
  1046. consensus_cache_add(cdm_cache_get(),
  1047. labels,
  1048. body_out,
  1049. bodylen_out);
  1050. if (BUG(ent == NULL))
  1051. continue;
  1052. status = CDM_DIFF_PRESENT;
  1053. handles_out[i] = consensus_cache_entry_handle_new(ent);
  1054. consensus_cache_entry_decref(ent);
  1055. }
  1056. }
  1057. return status;
  1058. }
  1059. /**
  1060. * An object passed to a worker thread that will try to produce a consensus
  1061. * diff.
  1062. */
  1063. typedef struct consensus_diff_worker_job_t {
  1064. /**
  1065. * Input: The consensus to compute the diff from. Holds a reference to the
  1066. * cache entry, which must not be released until the job is passed back to
  1067. * the main thread. The body must be mapped into memory in the main thread.
  1068. */
  1069. consensus_cache_entry_t *diff_from;
  1070. /**
  1071. * Input: The consensus to compute the diff to. Holds a reference to the
  1072. * cache entry, which must not be released until the job is passed back to
  1073. * the main thread. The body must be mapped into memory in the main thread.
  1074. */
  1075. consensus_cache_entry_t *diff_to;
  1076. /** Output: labels and bodies */
  1077. compressed_result_t out[ARRAY_LENGTH(compress_diffs_with)];
  1078. } consensus_diff_worker_job_t;
  1079. /** Given a consensus_cache_entry_t, check whether it has a label claiming
  1080. * that it was compressed. If so, uncompress its contents into <b>out</b> and
  1081. * set <b>outlen</b> to hold their size. If not, just copy the body into
  1082. * <b>out</b> and set <b>outlen</b> to its length. Return 0 on success,
  1083. * -1 on failure.
  1084. *
  1085. * In all cases, the output is nul-terminated. */
  1086. STATIC int
  1087. uncompress_or_copy(char **out, size_t *outlen,
  1088. consensus_cache_entry_t *ent)
  1089. {
  1090. const uint8_t *body;
  1091. size_t bodylen;
  1092. if (consensus_cache_entry_get_body(ent, &body, &bodylen) < 0)
  1093. return -1;
  1094. const char *lv_compression =
  1095. consensus_cache_entry_get_value(ent, LABEL_COMPRESSION_TYPE);
  1096. compress_method_t method = NO_METHOD;
  1097. if (lv_compression)
  1098. method = compression_method_get_by_name(lv_compression);
  1099. return tor_uncompress(out, outlen, (const char *)body, bodylen,
  1100. method, 1, LOG_WARN);
  1101. }
  1102. /**
  1103. * Worker function. This function runs inside a worker thread and receives
  1104. * a consensus_diff_worker_job_t as its input.
  1105. */
  1106. static workqueue_reply_t
  1107. consensus_diff_worker_threadfn(void *state_, void *work_)
  1108. {
  1109. (void)state_;
  1110. consensus_diff_worker_job_t *job = work_;
  1111. const uint8_t *diff_from, *diff_to;
  1112. size_t len_from, len_to;
  1113. int r;
  1114. /* We need to have the body already mapped into RAM here.
  1115. */
  1116. r = consensus_cache_entry_get_body(job->diff_from, &diff_from, &len_from);
  1117. if (BUG(r < 0))
  1118. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1119. r = consensus_cache_entry_get_body(job->diff_to, &diff_to, &len_to);
  1120. if (BUG(r < 0))
  1121. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1122. const char *lv_to_valid_after =
  1123. consensus_cache_entry_get_value(job->diff_to, LABEL_VALID_AFTER);
  1124. const char *lv_from_valid_after =
  1125. consensus_cache_entry_get_value(job->diff_from, LABEL_VALID_AFTER);
  1126. const char *lv_from_digest =
  1127. consensus_cache_entry_get_value(job->diff_from,
  1128. LABEL_SHA3_DIGEST_AS_SIGNED);
  1129. const char *lv_from_flavor =
  1130. consensus_cache_entry_get_value(job->diff_from, LABEL_FLAVOR);
  1131. const char *lv_to_flavor =
  1132. consensus_cache_entry_get_value(job->diff_to, LABEL_FLAVOR);
  1133. const char *lv_to_digest =
  1134. consensus_cache_entry_get_value(job->diff_to,
  1135. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1136. if (! lv_from_digest) {
  1137. /* This isn't a bug right now, since it can happen if you're migrating
  1138. * from an older version of master to a newer one. The older ones didn't
  1139. * annotate their stored consensus objects with sha3-digest-as-signed.
  1140. */
  1141. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1142. }
  1143. /* All these values are mandatory on the input */
  1144. if (BUG(!lv_to_valid_after) ||
  1145. BUG(!lv_from_valid_after) ||
  1146. BUG(!lv_from_flavor) ||
  1147. BUG(!lv_to_flavor)) {
  1148. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1149. }
  1150. /* The flavors need to match */
  1151. if (BUG(strcmp(lv_from_flavor, lv_to_flavor))) {
  1152. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1153. }
  1154. char *consensus_diff;
  1155. {
  1156. char *diff_from_nt = NULL, *diff_to_nt = NULL;
  1157. size_t diff_from_nt_len, diff_to_nt_len;
  1158. if (uncompress_or_copy(&diff_from_nt, &diff_from_nt_len,
  1159. job->diff_from) < 0) {
  1160. return WQ_RPL_REPLY;
  1161. }
  1162. if (uncompress_or_copy(&diff_to_nt, &diff_to_nt_len,
  1163. job->diff_to) < 0) {
  1164. tor_free(diff_from_nt);
  1165. return WQ_RPL_REPLY;
  1166. }
  1167. tor_assert(diff_from_nt);
  1168. tor_assert(diff_to_nt);
  1169. // XXXX ugh; this is going to calculate the SHA3 of both its
  1170. // XXXX inputs again, even though we already have that. Maybe it's time
  1171. // XXXX to change the API here?
  1172. consensus_diff = consensus_diff_generate(diff_from_nt, diff_to_nt);
  1173. tor_free(diff_from_nt);
  1174. tor_free(diff_to_nt);
  1175. }
  1176. if (!consensus_diff) {
  1177. /* Couldn't generate consensus; we'll leave the reply blank. */
  1178. return WQ_RPL_REPLY;
  1179. }
  1180. /* Compress the results and send the reply */
  1181. tor_assert(compress_diffs_with[0] == NO_METHOD);
  1182. size_t difflen = strlen(consensus_diff);
  1183. job->out[0].body = (uint8_t *) consensus_diff;
  1184. job->out[0].bodylen = difflen;
  1185. config_line_t *common_labels = NULL;
  1186. cdm_labels_prepend_sha3(&common_labels,
  1187. LABEL_SHA3_DIGEST_UNCOMPRESSED,
  1188. job->out[0].body,
  1189. job->out[0].bodylen);
  1190. config_line_prepend(&common_labels, LABEL_FROM_VALID_AFTER,
  1191. lv_from_valid_after);
  1192. config_line_prepend(&common_labels, LABEL_VALID_AFTER,
  1193. lv_to_valid_after);
  1194. config_line_prepend(&common_labels, LABEL_FLAVOR, lv_from_flavor);
  1195. config_line_prepend(&common_labels, LABEL_FROM_SHA3_DIGEST,
  1196. lv_from_digest);
  1197. config_line_prepend(&common_labels, LABEL_TARGET_SHA3_DIGEST,
  1198. lv_to_digest);
  1199. config_line_prepend(&common_labels, LABEL_DOCTYPE,
  1200. DOCTYPE_CONSENSUS_DIFF);
  1201. job->out[0].labels = config_lines_dup(common_labels);
  1202. cdm_labels_prepend_sha3(&job->out[0].labels,
  1203. LABEL_SHA3_DIGEST,
  1204. job->out[0].body,
  1205. job->out[0].bodylen);
  1206. compress_multiple(job->out+1,
  1207. n_diff_compression_methods()-1,
  1208. compress_diffs_with+1,
  1209. (const uint8_t*)consensus_diff, difflen, common_labels);
  1210. config_free_lines(common_labels);
  1211. return WQ_RPL_REPLY;
  1212. }
  1213. /**
  1214. * Helper: release all storage held in <b>job</b>.
  1215. */
  1216. static void
  1217. consensus_diff_worker_job_free(consensus_diff_worker_job_t *job)
  1218. {
  1219. if (!job)
  1220. return;
  1221. unsigned u;
  1222. for (u = 0; u < n_diff_compression_methods(); ++u) {
  1223. config_free_lines(job->out[u].labels);
  1224. tor_free(job->out[u].body);
  1225. }
  1226. consensus_cache_entry_decref(job->diff_from);
  1227. consensus_cache_entry_decref(job->diff_to);
  1228. tor_free(job);
  1229. }
  1230. /**
  1231. * Worker function: This function runs in the main thread, and receives
  1232. * a consensus_diff_worker_job_t that the worker thread has already
  1233. * processed.
  1234. */
  1235. static void
  1236. consensus_diff_worker_replyfn(void *work_)
  1237. {
  1238. tor_assert(in_main_thread());
  1239. tor_assert(work_);
  1240. consensus_diff_worker_job_t *job = work_;
  1241. const char *lv_from_digest =
  1242. consensus_cache_entry_get_value(job->diff_from,
  1243. LABEL_SHA3_DIGEST_AS_SIGNED);
  1244. const char *lv_to_digest =
  1245. consensus_cache_entry_get_value(job->diff_to,
  1246. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1247. const char *lv_flavor =
  1248. consensus_cache_entry_get_value(job->diff_to, LABEL_FLAVOR);
  1249. if (BUG(lv_from_digest == NULL))
  1250. lv_from_digest = "???"; // LCOV_EXCL_LINE
  1251. if (BUG(lv_to_digest == NULL))
  1252. lv_to_digest = "???"; // LCOV_EXCL_LINE
  1253. uint8_t from_sha3[DIGEST256_LEN];
  1254. uint8_t to_sha3[DIGEST256_LEN];
  1255. int flav = -1;
  1256. int cache = 1;
  1257. if (BUG(cdm_entry_get_sha3_value(from_sha3, job->diff_from,
  1258. LABEL_SHA3_DIGEST_AS_SIGNED) < 0))
  1259. cache = 0;
  1260. if (BUG(cdm_entry_get_sha3_value(to_sha3, job->diff_to,
  1261. LABEL_SHA3_DIGEST_UNCOMPRESSED) < 0))
  1262. cache = 0;
  1263. if (BUG(lv_flavor == NULL)) {
  1264. cache = 0;
  1265. } else if ((flav = networkstatus_parse_flavor_name(lv_flavor)) < 0) {
  1266. cache = 0;
  1267. }
  1268. consensus_cache_entry_handle_t *handles[ARRAY_LENGTH(compress_diffs_with)];
  1269. memset(handles, 0, sizeof(handles));
  1270. char description[128];
  1271. tor_snprintf(description, sizeof(description),
  1272. "consensus diff from %s to %s",
  1273. lv_from_digest, lv_to_digest);
  1274. int status = store_multiple(handles,
  1275. n_diff_compression_methods(),
  1276. compress_diffs_with,
  1277. job->out,
  1278. description);
  1279. if (status != CDM_DIFF_PRESENT) {
  1280. /* Failure! Nothing to do but complain */
  1281. log_warn(LD_DIRSERV,
  1282. "Worker was unable to compute consensus diff "
  1283. "from %s to %s", lv_from_digest, lv_to_digest);
  1284. /* Cache this error so we don't try to compute this one again. */
  1285. status = CDM_DIFF_ERROR;
  1286. }
  1287. unsigned u;
  1288. for (u = 0; u < ARRAY_LENGTH(handles); ++u) {
  1289. compress_method_t method = compress_diffs_with[u];
  1290. if (cache) {
  1291. cdm_diff_ht_set_status(flav, from_sha3, to_sha3, method, status,
  1292. handles[u]);
  1293. } else {
  1294. consensus_cache_entry_handle_free(handles[u]);
  1295. }
  1296. }
  1297. consensus_diff_worker_job_free(job);
  1298. }
  1299. /**
  1300. * Queue the job of computing the diff from <b>diff_from</b> to <b>diff_to</b>
  1301. * in a worker thread.
  1302. */
  1303. static int
  1304. consensus_diff_queue_diff_work(consensus_cache_entry_t *diff_from,
  1305. consensus_cache_entry_t *diff_to)
  1306. {
  1307. tor_assert(in_main_thread());
  1308. consensus_cache_entry_incref(diff_from);
  1309. consensus_cache_entry_incref(diff_to);
  1310. consensus_diff_worker_job_t *job = tor_malloc_zero(sizeof(*job));
  1311. job->diff_from = diff_from;
  1312. job->diff_to = diff_to;
  1313. /* Make sure body is mapped. */
  1314. const uint8_t *body;
  1315. size_t bodylen;
  1316. int r1 = consensus_cache_entry_get_body(diff_from, &body, &bodylen);
  1317. int r2 = consensus_cache_entry_get_body(diff_to, &body, &bodylen);
  1318. if (r1 < 0 || r2 < 0)
  1319. goto err;
  1320. workqueue_entry_t *work;
  1321. work = cpuworker_queue_work(consensus_diff_worker_threadfn,
  1322. consensus_diff_worker_replyfn,
  1323. job);
  1324. if (!work)
  1325. goto err;
  1326. return 0;
  1327. err:
  1328. consensus_diff_worker_job_free(job); // includes decrefs.
  1329. return -1;
  1330. }
  1331. /**
  1332. * Holds requests and replies for consensus_compress_workers.
  1333. */
  1334. typedef struct consensus_compress_worker_job_t {
  1335. char *consensus;
  1336. size_t consensus_len;
  1337. consensus_flavor_t flavor;
  1338. time_t valid_after;
  1339. compressed_result_t out[ARRAY_LENGTH(compress_consensus_with)];
  1340. } consensus_compress_worker_job_t;
  1341. /**
  1342. * Free all resources held in <b>job</b>
  1343. */
  1344. static void
  1345. consensus_compress_worker_job_free(consensus_compress_worker_job_t *job)
  1346. {
  1347. if (!job)
  1348. return;
  1349. tor_free(job->consensus);
  1350. unsigned u;
  1351. for (u = 0; u < n_consensus_compression_methods(); ++u) {
  1352. config_free_lines(job->out[u].labels);
  1353. tor_free(job->out[u].body);
  1354. }
  1355. tor_free(job);
  1356. }
  1357. /**
  1358. * Worker function. This function runs inside a worker thread and receives
  1359. * a consensus_compress_worker_job_t as its input.
  1360. */
  1361. static workqueue_reply_t
  1362. consensus_compress_worker_threadfn(void *state_, void *work_)
  1363. {
  1364. (void)state_;
  1365. consensus_compress_worker_job_t *job = work_;
  1366. consensus_flavor_t flavor = job->flavor;
  1367. const char *consensus = job->consensus;
  1368. size_t bodylen = job->consensus_len;
  1369. time_t valid_after = job->valid_after;
  1370. config_line_t *labels = NULL;
  1371. char formatted_time[ISO_TIME_LEN+1];
  1372. format_iso_time_nospace(formatted_time, valid_after);
  1373. const char *flavname = networkstatus_get_flavor_name(flavor);
  1374. cdm_labels_prepend_sha3(&labels, LABEL_SHA3_DIGEST_UNCOMPRESSED,
  1375. (const uint8_t *)consensus, bodylen);
  1376. {
  1377. const char *start, *end;
  1378. if (router_get_networkstatus_v3_signed_boundaries(consensus,
  1379. &start, &end) < 0) {
  1380. start = consensus;
  1381. end = consensus+bodylen;
  1382. }
  1383. cdm_labels_prepend_sha3(&labels, LABEL_SHA3_DIGEST_AS_SIGNED,
  1384. (const uint8_t *)start,
  1385. end - start);
  1386. }
  1387. config_line_prepend(&labels, LABEL_FLAVOR, flavname);
  1388. config_line_prepend(&labels, LABEL_VALID_AFTER, formatted_time);
  1389. config_line_prepend(&labels, LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  1390. compress_multiple(job->out,
  1391. n_consensus_compression_methods(),
  1392. compress_consensus_with,
  1393. (const uint8_t*)consensus, bodylen, labels);
  1394. config_free_lines(labels);
  1395. return WQ_RPL_REPLY;
  1396. }
  1397. /**
  1398. * Worker function: This function runs in the main thread, and receives
  1399. * a consensus_diff_compress_job_t that the worker thread has already
  1400. * processed.
  1401. */
  1402. static void
  1403. consensus_compress_worker_replyfn(void *work_)
  1404. {
  1405. consensus_compress_worker_job_t *job = work_;
  1406. consensus_cache_entry_handle_t *handles[
  1407. ARRAY_LENGTH(compress_consensus_with)];
  1408. memset(handles, 0, sizeof(handles));
  1409. store_multiple(handles,
  1410. n_consensus_compression_methods(),
  1411. compress_consensus_with,
  1412. job->out,
  1413. "consensus");
  1414. cdm_cache_dirty = 1;
  1415. consensus_compress_worker_job_free(job);
  1416. }
  1417. /**
  1418. * If true, we compress in worker threads.
  1419. */
  1420. static int background_compression = 0;
  1421. /**
  1422. * Queue a job to compress <b>consensus</b> and store its compressed
  1423. * text in the cache.
  1424. */
  1425. static int
  1426. consensus_queue_compression_work(const char *consensus,
  1427. consensus_flavor_t flavor,
  1428. time_t valid_after)
  1429. {
  1430. consensus_compress_worker_job_t *job = tor_malloc_zero(sizeof(*job));
  1431. job->consensus = tor_strdup(consensus);
  1432. job->consensus_len = strlen(consensus);
  1433. job->flavor = flavor;
  1434. job->valid_after = valid_after;
  1435. if (background_compression) {
  1436. workqueue_entry_t *work;
  1437. work = cpuworker_queue_work(consensus_compress_worker_threadfn,
  1438. consensus_compress_worker_replyfn,
  1439. job);
  1440. if (!work) {
  1441. consensus_compress_worker_job_free(job);
  1442. return -1;
  1443. }
  1444. return 0;
  1445. } else {
  1446. consensus_compress_worker_threadfn(NULL, job);
  1447. consensus_compress_worker_replyfn(job);
  1448. return 0;
  1449. }
  1450. }
  1451. /**
  1452. * Tell the consdiffmgr backend to compress consensuses in worker threads.
  1453. */
  1454. void
  1455. consdiffmgr_enable_background_compression(void)
  1456. {
  1457. // This isn't the default behavior because it would break unit tests.
  1458. background_compression = 1;
  1459. }