consdiffmgr.c 57 KB

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