consdiffmgr.c 62 KB

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