consdiffmgr.c 64 KB

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