consdiffmgr.c 61 KB

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