consdiffmgr.c 65 KB

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