consdiffmgr.c 61 KB

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