consdiffmgr.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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. /* A hex encoded SHA3 digest of the object, as compressed (if any) */
  32. #define LABEL_SHA3_DIGEST "sha3-digest"
  33. /* A hex encoded SHA3 digest of the object before compression. */
  34. #define LABEL_SHA3_DIGEST_UNCOMPRESSED "sha3-digest-uncompressed"
  35. /* A hex encoded SHA3 digest-as-signed of a consensus */
  36. #define LABEL_SHA3_DIGEST_AS_SIGNED "sha3-digest-as-signed"
  37. /* The flavor of the consensus or consensuses diff */
  38. #define LABEL_FLAVOR "consensus-flavor"
  39. /* Diff only: the SHA3 digest-as-signed of the source consensus. */
  40. #define LABEL_FROM_SHA3_DIGEST "from-sha3-digest"
  41. /* Diff only: the SHA3 digest-in-full of the target consensus. */
  42. #define LABEL_TARGET_SHA3_DIGEST "target-sha3-digest"
  43. /* Diff only: the valid-after date of the source consensus. */
  44. #define LABEL_FROM_VALID_AFTER "from-valid-after"
  45. /* What kind of compression was used? */
  46. #define LABEL_COMPRESSION_TYPE "compression"
  47. /** @} */
  48. #define DOCTYPE_CONSENSUS "consensus"
  49. #define DOCTYPE_CONSENSUS_DIFF "consensus-diff"
  50. /**
  51. * Underlying directory that stores consensuses and consensus diffs. Don't
  52. * use this directly: use cdm_cache_get() instead.
  53. */
  54. static consensus_cache_t *cons_diff_cache = NULL;
  55. /**
  56. * If true, we have learned at least one new consensus since the
  57. * consensus cache was last up-to-date.
  58. */
  59. static int cdm_cache_dirty = 0;
  60. /**
  61. * If true, we have scanned the cache to update our hashtable of diffs.
  62. */
  63. static int cdm_cache_loaded = 0;
  64. /**
  65. * Possible status values for cdm_diff_t.cdm_diff_status
  66. **/
  67. typedef enum cdm_diff_status_t {
  68. CDM_DIFF_PRESENT=1,
  69. CDM_DIFF_IN_PROGRESS=2,
  70. CDM_DIFF_ERROR=3,
  71. } cdm_diff_status_t;
  72. /** Which methods do we use for precompressing diffs? */
  73. static const compress_method_t compress_diffs_with[] = {
  74. NO_METHOD,
  75. GZIP_METHOD,
  76. #ifdef HAVE_LZMA
  77. LZMA_METHOD,
  78. #endif
  79. #ifdef HAVE_ZSTD
  80. ZSTD_METHOD,
  81. #endif
  82. };
  83. /** How many different methods will we try to use for diff compression? */
  84. STATIC unsigned
  85. n_diff_compression_methods(void)
  86. {
  87. return ARRAY_LENGTH(compress_diffs_with);
  88. }
  89. /** Hashtable node used to remember the current status of the diff
  90. * from a given sha3 digest to the current consensus. */
  91. typedef struct cdm_diff_t {
  92. HT_ENTRY(cdm_diff_t) node;
  93. /** Consensus flavor for this diff (part of ht key) */
  94. consensus_flavor_t flavor;
  95. /** SHA3-256 digest of the consensus that this diff is _from_. (part of the
  96. * ht key) */
  97. uint8_t from_sha3[DIGEST256_LEN];
  98. /** Method by which the diff is compressed. (part of the ht key */
  99. compress_method_t compress_method;
  100. /** One of the CDM_DIFF_* values, depending on whether this diff
  101. * is available, in progress, or impossible to compute. */
  102. cdm_diff_status_t cdm_diff_status;
  103. /** SHA3-256 digest of the consensus that this diff is _to. */
  104. uint8_t target_sha3[DIGEST256_LEN];
  105. /** Handle to the cache entry for this diff, if any. We use a handle here
  106. * to avoid thinking too hard about cache entry lifetime issues. */
  107. consensus_cache_entry_handle_t *entry;
  108. } cdm_diff_t;
  109. /** Hashtable mapping flavor and source consensus digest to status. */
  110. static HT_HEAD(cdm_diff_ht, cdm_diff_t) cdm_diff_ht = HT_INITIALIZER();
  111. /**
  112. * Configuration for this module
  113. */
  114. static consdiff_cfg_t consdiff_cfg = {
  115. /* .cache_max_age_hours = */ 24 * 90,
  116. // XXXX I'd like to make this number bigger, but it interferes with the
  117. // XXXX seccomp2 syscall filter, which tops out at BPF_MAXINS (4096)
  118. // XXXX rules.
  119. /* .cache_max_num = */ 128
  120. };
  121. static int consdiffmgr_ensure_space_for_files(int n);
  122. static int consensus_diff_queue_diff_work(consensus_cache_entry_t *diff_from,
  123. consensus_cache_entry_t *diff_to);
  124. static void consdiffmgr_set_cache_flags(void);
  125. /* Just gzip consensuses for now. */
  126. #define COMPRESS_CONSENSUS_WITH GZIP_METHOD
  127. /* =====
  128. * Hashtable setup
  129. * ===== */
  130. /** Helper: hash the key of a cdm_diff_t. */
  131. static unsigned
  132. cdm_diff_hash(const cdm_diff_t *diff)
  133. {
  134. uint8_t tmp[DIGEST256_LEN + 2];
  135. memcpy(tmp, diff->from_sha3, DIGEST256_LEN);
  136. tmp[DIGEST256_LEN] = (uint8_t) diff->flavor;
  137. tmp[DIGEST256_LEN+1] = (uint8_t) diff->compress_method;
  138. return (unsigned) siphash24g(tmp, sizeof(tmp));
  139. }
  140. /** Helper: compare two cdm_diff_t objects for key equality */
  141. static int
  142. cdm_diff_eq(const cdm_diff_t *diff1, const cdm_diff_t *diff2)
  143. {
  144. return fast_memeq(diff1->from_sha3, diff2->from_sha3, DIGEST256_LEN) &&
  145. diff1->flavor == diff2->flavor &&
  146. diff1->compress_method == diff2->compress_method;
  147. }
  148. HT_PROTOTYPE(cdm_diff_ht, cdm_diff_t, node, cdm_diff_hash, cdm_diff_eq)
  149. HT_GENERATE2(cdm_diff_ht, cdm_diff_t, node, cdm_diff_hash, cdm_diff_eq,
  150. 0.6, tor_reallocarray, tor_free_)
  151. /** Release all storage held in <b>diff</b>. */
  152. static void
  153. cdm_diff_free(cdm_diff_t *diff)
  154. {
  155. if (!diff)
  156. return;
  157. consensus_cache_entry_handle_free(diff->entry);
  158. tor_free(diff);
  159. }
  160. /** Create and return a new cdm_diff_t with the given values. Does not
  161. * add it to the hashtable. */
  162. static cdm_diff_t *
  163. cdm_diff_new(consensus_flavor_t flav,
  164. const uint8_t *from_sha3,
  165. const uint8_t *target_sha3,
  166. compress_method_t method)
  167. {
  168. cdm_diff_t *ent;
  169. ent = tor_malloc_zero(sizeof(cdm_diff_t));
  170. ent->flavor = flav;
  171. memcpy(ent->from_sha3, from_sha3, DIGEST256_LEN);
  172. memcpy(ent->target_sha3, target_sha3, DIGEST256_LEN);
  173. ent->compress_method = method;
  174. return ent;
  175. }
  176. /**
  177. * Examine the diff hashtable to see whether we know anything about computing
  178. * a diff of type <b>flav</b> between consensuses with the two provided
  179. * SHA3-256 digests. If a computation is in progress, or if the computation
  180. * has already been tried and failed, return 1. Otherwise, note the
  181. * computation as "in progress" so that we don't reattempt it later, and
  182. * return 0.
  183. */
  184. static int
  185. cdm_diff_ht_check_and_note_pending(consensus_flavor_t flav,
  186. const uint8_t *from_sha3,
  187. const uint8_t *target_sha3)
  188. {
  189. struct cdm_diff_t search, *ent;
  190. unsigned u;
  191. int result = 0;
  192. for (u = 0; u < n_diff_compression_methods(); ++u) {
  193. compress_method_t method = compress_diffs_with[u];
  194. memset(&search, 0, sizeof(cdm_diff_t));
  195. search.flavor = flav;
  196. search.compress_method = method;
  197. memcpy(search.from_sha3, from_sha3, DIGEST256_LEN);
  198. ent = HT_FIND(cdm_diff_ht, &cdm_diff_ht, &search);
  199. if (ent) {
  200. tor_assert_nonfatal(ent->cdm_diff_status != CDM_DIFF_PRESENT);
  201. result = 1;
  202. continue;
  203. }
  204. ent = cdm_diff_new(flav, from_sha3, target_sha3, method);
  205. ent->cdm_diff_status = CDM_DIFF_IN_PROGRESS;
  206. HT_INSERT(cdm_diff_ht, &cdm_diff_ht, ent);
  207. }
  208. return result;
  209. }
  210. /**
  211. * Update the status of the diff of type <b>flav</b> between consensuses with
  212. * the two provided SHA3-256 digests, so that its status becomes
  213. * <b>status</b>, and its value becomes the <b>handle</b>. If <b>handle</b>
  214. * is NULL, then the old handle (if any) is freed, and replaced with NULL.
  215. */
  216. static void
  217. cdm_diff_ht_set_status(consensus_flavor_t flav,
  218. const uint8_t *from_sha3,
  219. const uint8_t *to_sha3,
  220. compress_method_t method,
  221. int status,
  222. consensus_cache_entry_handle_t *handle)
  223. {
  224. struct cdm_diff_t search, *ent;
  225. memset(&search, 0, sizeof(cdm_diff_t));
  226. search.flavor = flav;
  227. search.compress_method = method,
  228. memcpy(search.from_sha3, from_sha3, DIGEST256_LEN);
  229. ent = HT_FIND(cdm_diff_ht, &cdm_diff_ht, &search);
  230. if (!ent) {
  231. ent = cdm_diff_new(flav, from_sha3, to_sha3, method);
  232. ent->cdm_diff_status = CDM_DIFF_IN_PROGRESS;
  233. HT_INSERT(cdm_diff_ht, &cdm_diff_ht, ent);
  234. } else if (fast_memneq(ent->target_sha3, to_sha3, DIGEST256_LEN)) {
  235. // This can happen under certain really pathological conditions
  236. // if we decide we don't care about a diff before it is actually
  237. // done computing.
  238. return;
  239. }
  240. tor_assert_nonfatal(ent->cdm_diff_status == CDM_DIFF_IN_PROGRESS);
  241. ent->cdm_diff_status = status;
  242. consensus_cache_entry_handle_free(ent->entry);
  243. ent->entry = handle;
  244. }
  245. /**
  246. * Helper: Remove from the hash table every present (actually computed) diff
  247. * of type <b>flav</b> whose target digest does not match
  248. * <b>unless_target_sha3_matches</b>.
  249. *
  250. * This function is used for the hash table to throw away references to diffs
  251. * that do not lead to the most given consensus of a given flavor.
  252. */
  253. static void
  254. cdm_diff_ht_purge(consensus_flavor_t flav,
  255. const uint8_t *unless_target_sha3_matches)
  256. {
  257. cdm_diff_t **diff, **next;
  258. for (diff = HT_START(cdm_diff_ht, &cdm_diff_ht); diff; diff = next) {
  259. cdm_diff_t *this = *diff;
  260. if ((*diff)->cdm_diff_status == CDM_DIFF_PRESENT &&
  261. flav == (*diff)->flavor) {
  262. if (consensus_cache_entry_handle_get((*diff)->entry) == NULL) {
  263. /* the underlying entry has gone away; drop this. */
  264. next = HT_NEXT_RMV(cdm_diff_ht, &cdm_diff_ht, diff);
  265. cdm_diff_free(this);
  266. continue;
  267. }
  268. if (unless_target_sha3_matches &&
  269. fast_memneq(unless_target_sha3_matches, (*diff)->target_sha3,
  270. DIGEST256_LEN)) {
  271. /* target hash doesn't match; drop this. */
  272. next = HT_NEXT_RMV(cdm_diff_ht, &cdm_diff_ht, diff);
  273. cdm_diff_free(this);
  274. continue;
  275. }
  276. }
  277. next = HT_NEXT(cdm_diff_ht, &cdm_diff_ht, diff);
  278. }
  279. }
  280. /**
  281. * Helper: initialize <b>cons_diff_cache</b>.
  282. */
  283. static void
  284. cdm_cache_init(void)
  285. {
  286. unsigned n_entries = consdiff_cfg.cache_max_num * 2;
  287. tor_assert(cons_diff_cache == NULL);
  288. cons_diff_cache = consensus_cache_open("diff-cache", n_entries);
  289. if (cons_diff_cache == NULL) {
  290. // LCOV_EXCL_START
  291. log_err(LD_FS, "Error: Couldn't open storage for consensus diffs.");
  292. tor_assert_unreached();
  293. // LCOV_EXCL_STOP
  294. } else {
  295. consdiffmgr_set_cache_flags();
  296. }
  297. cdm_cache_dirty = 1;
  298. cdm_cache_loaded = 0;
  299. }
  300. /**
  301. * Helper: return the consensus_cache_t * that backs this manager,
  302. * initializing it if needed.
  303. */
  304. STATIC consensus_cache_t *
  305. cdm_cache_get(void)
  306. {
  307. if (PREDICT_UNLIKELY(cons_diff_cache == NULL)) {
  308. cdm_cache_init();
  309. }
  310. return cons_diff_cache;
  311. }
  312. /**
  313. * Helper: given a list of labels, prepend the hex-encoded SHA3 digest
  314. * of the <b>bodylen</b>-byte object at <b>body</b> to those labels,
  315. * with <b>label</b> as its label.
  316. */
  317. static void
  318. cdm_labels_prepend_sha3(config_line_t **labels,
  319. const char *label,
  320. const uint8_t *body,
  321. size_t bodylen)
  322. {
  323. uint8_t sha3_digest[DIGEST256_LEN];
  324. char hexdigest[HEX_DIGEST256_LEN+1];
  325. crypto_digest256((char *)sha3_digest,
  326. (const char *)body, bodylen, DIGEST_SHA3_256);
  327. base16_encode(hexdigest, sizeof(hexdigest),
  328. (const char *)sha3_digest, sizeof(sha3_digest));
  329. config_line_prepend(labels, label, hexdigest);
  330. }
  331. /** Helper: if there is a sha3-256 hex-encoded digest in <b>ent</b> with the
  332. * given label, set <b>digest_out</b> to that value (decoded), and return 0.
  333. *
  334. * Return -1 if there is no such label, and -2 if it is badly formatted. */
  335. STATIC int
  336. cdm_entry_get_sha3_value(uint8_t *digest_out,
  337. consensus_cache_entry_t *ent,
  338. const char *label)
  339. {
  340. if (ent == NULL)
  341. return -1;
  342. const char *hex = consensus_cache_entry_get_value(ent, label);
  343. if (hex == NULL)
  344. return -1;
  345. int n = base16_decode((char*)digest_out, DIGEST256_LEN, hex, strlen(hex));
  346. if (n != DIGEST256_LEN)
  347. return -2;
  348. else
  349. return 0;
  350. }
  351. /**
  352. * Helper: look for a consensus with the given <b>flavor</b> and
  353. * <b>valid_after</b> time in the cache. Return that consensus if it's
  354. * present, or NULL if it's missing.
  355. */
  356. STATIC consensus_cache_entry_t *
  357. cdm_cache_lookup_consensus(consensus_flavor_t flavor, time_t valid_after)
  358. {
  359. char formatted_time[ISO_TIME_LEN+1];
  360. format_iso_time_nospace(formatted_time, valid_after);
  361. const char *flavname = networkstatus_get_flavor_name(flavor);
  362. /* We'll filter by valid-after time first, since that should
  363. * match the fewest documents. */
  364. /* We could add an extra hashtable here, but since we only do this scan
  365. * when adding a new consensus, it probably doesn't matter much. */
  366. smartlist_t *matches = smartlist_new();
  367. consensus_cache_find_all(matches, cdm_cache_get(),
  368. LABEL_VALID_AFTER, formatted_time);
  369. consensus_cache_filter_list(matches, LABEL_FLAVOR, flavname);
  370. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  371. consensus_cache_entry_t *result = NULL;
  372. if (smartlist_len(matches) > 1) {
  373. log_warn(LD_BUG, "How odd; there appear to be two matching consensuses "
  374. "with flavor %s published at %s.",
  375. flavname, formatted_time);
  376. }
  377. if (smartlist_len(matches)) {
  378. result = smartlist_get(matches, 0);
  379. }
  380. smartlist_free(matches);
  381. return result;
  382. }
  383. /**
  384. * Given a string containing a networkstatus consensus, and the results of
  385. * having parsed that consensus, add that consensus to the cache if it is not
  386. * already present and not too old. Create new consensus diffs from or to
  387. * that consensus as appropriate.
  388. *
  389. * Return 0 on success and -1 on failure.
  390. */
  391. int
  392. consdiffmgr_add_consensus(const char *consensus,
  393. const networkstatus_t *as_parsed)
  394. {
  395. if (BUG(consensus == NULL) || BUG(as_parsed == NULL))
  396. return -1; // LCOV_EXCL_LINE
  397. if (BUG(as_parsed->type != NS_TYPE_CONSENSUS))
  398. return -1; // LCOV_EXCL_LINE
  399. const consensus_flavor_t flavor = as_parsed->flavor;
  400. const time_t valid_after = as_parsed->valid_after;
  401. if (valid_after < approx_time() - 3600 * consdiff_cfg.cache_max_age_hours) {
  402. log_info(LD_DIRSERV, "We don't care about this consensus document; it's "
  403. "too old.");
  404. return -1;
  405. }
  406. /* Do we already have this one? */
  407. consensus_cache_entry_t *entry =
  408. cdm_cache_lookup_consensus(flavor, valid_after);
  409. if (entry) {
  410. log_info(LD_DIRSERV, "We already have a copy of that consensus");
  411. return -1;
  412. }
  413. /* We don't have it. Add it to the cache. */
  414. consdiffmgr_ensure_space_for_files(1);
  415. {
  416. size_t bodylen = strlen(consensus);
  417. config_line_t *labels = NULL;
  418. char formatted_time[ISO_TIME_LEN+1];
  419. format_iso_time_nospace(formatted_time, valid_after);
  420. const char *flavname = networkstatus_get_flavor_name(flavor);
  421. cdm_labels_prepend_sha3(&labels, LABEL_SHA3_DIGEST_UNCOMPRESSED,
  422. (const uint8_t *)consensus, bodylen);
  423. {
  424. const char *start, *end;
  425. if (router_get_networkstatus_v3_signed_boundaries(consensus,
  426. &start, &end) < 0) {
  427. start = consensus;
  428. end = consensus+bodylen;
  429. }
  430. cdm_labels_prepend_sha3(&labels, LABEL_SHA3_DIGEST_AS_SIGNED,
  431. (const uint8_t *)start,
  432. end - start);
  433. }
  434. char *body_compressed = NULL;
  435. size_t size_compressed = 0;
  436. if (tor_compress(&body_compressed, &size_compressed,
  437. consensus, bodylen, COMPRESS_CONSENSUS_WITH) < 0) {
  438. config_free_lines(labels);
  439. return -1;
  440. }
  441. cdm_labels_prepend_sha3(&labels, LABEL_SHA3_DIGEST,
  442. (const uint8_t *)body_compressed, size_compressed);
  443. config_line_prepend(&labels, LABEL_COMPRESSION_TYPE,
  444. compression_method_get_name(COMPRESS_CONSENSUS_WITH));
  445. config_line_prepend(&labels, LABEL_FLAVOR, flavname);
  446. config_line_prepend(&labels, LABEL_VALID_AFTER, formatted_time);
  447. config_line_prepend(&labels, LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  448. entry = consensus_cache_add(cdm_cache_get(),
  449. labels,
  450. (const uint8_t *)body_compressed,
  451. size_compressed);
  452. tor_free(body_compressed);
  453. config_free_lines(labels);
  454. }
  455. if (entry) {
  456. consensus_cache_entry_mark_for_aggressive_release(entry);
  457. consensus_cache_entry_decref(entry);
  458. }
  459. cdm_cache_dirty = 1;
  460. return entry ? 0 : -1;
  461. }
  462. /**
  463. * Helper: used to sort two smartlists of consensus_cache_entry_t by their
  464. * LABEL_VALID_AFTER labels.
  465. */
  466. static int
  467. compare_by_valid_after_(const void **a, const void **b)
  468. {
  469. const consensus_cache_entry_t *e1 = *a;
  470. const consensus_cache_entry_t *e2 = *b;
  471. /* We're in luck here: sorting UTC iso-encoded values lexically will work
  472. * fine (until 9999). */
  473. return strcmp_opt(consensus_cache_entry_get_value(e1, LABEL_VALID_AFTER),
  474. consensus_cache_entry_get_value(e2, LABEL_VALID_AFTER));
  475. }
  476. /**
  477. * Helper: Sort <b>lst</b> by LABEL_VALID_AFTER and return the most recent
  478. * entry.
  479. */
  480. static consensus_cache_entry_t *
  481. sort_and_find_most_recent(smartlist_t *lst)
  482. {
  483. smartlist_sort(lst, compare_by_valid_after_);
  484. if (smartlist_len(lst)) {
  485. return smartlist_get(lst, smartlist_len(lst) - 1);
  486. } else {
  487. return NULL;
  488. }
  489. }
  490. /**
  491. * Look up consensus_cache_entry_t for the consensus of type <b>flavor</b>,
  492. * from the source consensus with the specified digest (which must be SHA3).
  493. *
  494. * If the diff is present, store it into *<b>entry_out</b> and return
  495. * CONSDIFF_AVAILABLE. Otherwise return CONSDIFF_NOT_FOUND or
  496. * CONSDIFF_IN_PROGRESS.
  497. */
  498. consdiff_status_t
  499. consdiffmgr_find_diff_from(consensus_cache_entry_t **entry_out,
  500. consensus_flavor_t flavor,
  501. int digest_type,
  502. const uint8_t *digest,
  503. size_t digestlen,
  504. compress_method_t method)
  505. {
  506. if (BUG(digest_type != DIGEST_SHA3_256) ||
  507. BUG(digestlen != DIGEST256_LEN)) {
  508. return CONSDIFF_NOT_FOUND; // LCOV_EXCL_LINE
  509. }
  510. // Try to look up the entry in the hashtable.
  511. cdm_diff_t search, *ent;
  512. memset(&search, 0, sizeof(search));
  513. search.flavor = flavor;
  514. search.compress_method = method;
  515. memcpy(search.from_sha3, digest, DIGEST256_LEN);
  516. ent = HT_FIND(cdm_diff_ht, &cdm_diff_ht, &search);
  517. if (ent == NULL ||
  518. ent->cdm_diff_status == CDM_DIFF_ERROR) {
  519. return CONSDIFF_NOT_FOUND;
  520. } else if (ent->cdm_diff_status == CDM_DIFF_IN_PROGRESS) {
  521. return CONSDIFF_IN_PROGRESS;
  522. } else if (BUG(ent->cdm_diff_status != CDM_DIFF_PRESENT)) {
  523. return CONSDIFF_IN_PROGRESS;
  524. }
  525. *entry_out = consensus_cache_entry_handle_get(ent->entry);
  526. return (*entry_out) ? CONSDIFF_AVAILABLE : CONSDIFF_NOT_FOUND;
  527. #if 0
  528. // XXXX Remove this. I'm keeping it around for now in case we need to
  529. // XXXX debug issues in the hashtable.
  530. char hex[HEX_DIGEST256_LEN+1];
  531. base16_encode(hex, sizeof(hex), (const char *)digest, digestlen);
  532. const char *flavname = networkstatus_get_flavor_name(flavor);
  533. smartlist_t *matches = smartlist_new();
  534. consensus_cache_find_all(matches, cdm_cache_get(),
  535. LABEL_FROM_SHA3_DIGEST, hex);
  536. consensus_cache_filter_list(matches, LABEL_FLAVOR, flavname);
  537. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  538. *entry_out = sort_and_find_most_recent(matches);
  539. consdiff_status_t result =
  540. (*entry_out) ? CONSDIFF_AVAILABLE : CONSDIFF_NOT_FOUND;
  541. smartlist_free(matches);
  542. return result;
  543. #endif
  544. }
  545. /**
  546. * Perform periodic cleanup tasks on the consensus diff cache. Return
  547. * the number of objects marked for deletion.
  548. */
  549. int
  550. consdiffmgr_cleanup(void)
  551. {
  552. smartlist_t *objects = smartlist_new();
  553. smartlist_t *consensuses = smartlist_new();
  554. smartlist_t *diffs = smartlist_new();
  555. int n_to_delete = 0;
  556. log_debug(LD_DIRSERV, "Looking for consdiffmgr entries to remove");
  557. // 1. Delete any consensus or diff or anything whose valid_after is too old.
  558. const time_t valid_after_cutoff =
  559. approx_time() - 3600 * consdiff_cfg.cache_max_age_hours;
  560. consensus_cache_find_all(objects, cdm_cache_get(),
  561. NULL, NULL);
  562. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  563. const char *lv_valid_after =
  564. consensus_cache_entry_get_value(ent, LABEL_VALID_AFTER);
  565. if (! lv_valid_after) {
  566. log_debug(LD_DIRSERV, "Ignoring entry because it had no %s label",
  567. LABEL_VALID_AFTER);
  568. continue;
  569. }
  570. time_t valid_after = 0;
  571. if (parse_iso_time_nospace(lv_valid_after, &valid_after) < 0) {
  572. log_debug(LD_DIRSERV, "Ignoring entry because its %s value (%s) was "
  573. "unparseable", LABEL_VALID_AFTER, escaped(lv_valid_after));
  574. continue;
  575. }
  576. if (valid_after < valid_after_cutoff) {
  577. log_debug(LD_DIRSERV, "Deleting entry because its %s value (%s) was "
  578. "too old", LABEL_VALID_AFTER, lv_valid_after);
  579. consensus_cache_entry_mark_for_removal(ent);
  580. ++n_to_delete;
  581. }
  582. } SMARTLIST_FOREACH_END(ent);
  583. // 2. Delete all diffs that lead to a consensus whose valid-after is not the
  584. // latest.
  585. for (int flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  586. const char *flavname = networkstatus_get_flavor_name(flav);
  587. /* Determine the most recent consensus of this flavor */
  588. consensus_cache_find_all(consensuses, cdm_cache_get(),
  589. LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  590. consensus_cache_filter_list(consensuses, LABEL_FLAVOR, flavname);
  591. consensus_cache_entry_t *most_recent =
  592. sort_and_find_most_recent(consensuses);
  593. if (most_recent == NULL)
  594. continue;
  595. const char *most_recent_sha3 =
  596. consensus_cache_entry_get_value(most_recent,
  597. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  598. if (BUG(most_recent_sha3 == NULL))
  599. continue; // LCOV_EXCL_LINE
  600. /* consider all such-flavored diffs, and look to see if they match. */
  601. consensus_cache_find_all(diffs, cdm_cache_get(),
  602. LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  603. consensus_cache_filter_list(diffs, LABEL_FLAVOR, flavname);
  604. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  605. const char *this_diff_target_sha3 =
  606. consensus_cache_entry_get_value(diff, LABEL_TARGET_SHA3_DIGEST);
  607. if (!this_diff_target_sha3)
  608. continue;
  609. if (strcmp(this_diff_target_sha3, most_recent_sha3)) {
  610. consensus_cache_entry_mark_for_removal(diff);
  611. ++n_to_delete;
  612. }
  613. } SMARTLIST_FOREACH_END(diff);
  614. smartlist_clear(consensuses);
  615. smartlist_clear(diffs);
  616. }
  617. smartlist_free(objects);
  618. smartlist_free(consensuses);
  619. smartlist_free(diffs);
  620. // Actually remove files, if they're not used.
  621. consensus_cache_delete_pending(cdm_cache_get(), 0);
  622. return n_to_delete;
  623. }
  624. /**
  625. * Initialize the consensus diff manager and its cache, and configure
  626. * its parameters based on the latest torrc and networkstatus parameters.
  627. */
  628. void
  629. consdiffmgr_configure(const consdiff_cfg_t *cfg)
  630. {
  631. if (cfg)
  632. memcpy(&consdiff_cfg, cfg, sizeof(consdiff_cfg));
  633. (void) cdm_cache_get();
  634. }
  635. /**
  636. * Tell the sandbox (if any) configured by <b>cfg</b> to allow the
  637. * operations that the consensus diff manager will need.
  638. */
  639. int
  640. consdiffmgr_register_with_sandbox(struct sandbox_cfg_elem **cfg)
  641. {
  642. return consensus_cache_register_with_sandbox(cdm_cache_get(), cfg);
  643. }
  644. /**
  645. * Scan the consensus diff manager's cache for any grossly malformed entries,
  646. * and mark them as deletable. Return 0 if no problems were found; 1
  647. * if problems were found and fixed.
  648. */
  649. int
  650. consdiffmgr_validate(void)
  651. {
  652. /* Right now, we only check for entries that have bad sha3 values */
  653. int problems = 0;
  654. smartlist_t *objects = smartlist_new();
  655. consensus_cache_find_all(objects, cdm_cache_get(),
  656. NULL, NULL);
  657. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, obj) {
  658. uint8_t sha3_expected[DIGEST256_LEN];
  659. uint8_t sha3_received[DIGEST256_LEN];
  660. int r = cdm_entry_get_sha3_value(sha3_expected, obj, LABEL_SHA3_DIGEST);
  661. if (r == -1) {
  662. /* digest isn't there; that's allowed */
  663. continue;
  664. } else if (r == -2) {
  665. /* digest is malformed; that's not allowed */
  666. problems = 1;
  667. consensus_cache_entry_mark_for_removal(obj);
  668. continue;
  669. }
  670. const uint8_t *body;
  671. size_t bodylen;
  672. consensus_cache_entry_incref(obj);
  673. r = consensus_cache_entry_get_body(obj, &body, &bodylen);
  674. if (r == 0) {
  675. crypto_digest256((char *)sha3_received, (const char *)body, bodylen,
  676. DIGEST_SHA3_256);
  677. }
  678. consensus_cache_entry_decref(obj);
  679. if (r < 0)
  680. continue;
  681. // Deconfuse coverity about the possibility of sha3_received being
  682. // uninitialized
  683. tor_assert(r <= 0);
  684. if (fast_memneq(sha3_received, sha3_expected, DIGEST256_LEN)) {
  685. problems = 1;
  686. consensus_cache_entry_mark_for_removal(obj);
  687. continue;
  688. }
  689. } SMARTLIST_FOREACH_END(obj);
  690. smartlist_free(objects);
  691. return problems;
  692. }
  693. /**
  694. * Helper: build new diffs of <b>flavor</b> as needed
  695. */
  696. static void
  697. consdiffmgr_rescan_flavor_(consensus_flavor_t flavor)
  698. {
  699. smartlist_t *matches = NULL;
  700. smartlist_t *diffs = NULL;
  701. smartlist_t *compute_diffs_from = NULL;
  702. strmap_t *have_diff_from = NULL;
  703. // look for the most recent consensus, and for all previous in-range
  704. // consensuses. Do they all have diffs to it?
  705. const char *flavname = networkstatus_get_flavor_name(flavor);
  706. // 1. find the most recent consensus, and the ones that we might want
  707. // to diff to it.
  708. matches = smartlist_new();
  709. consensus_cache_find_all(matches, cdm_cache_get(),
  710. LABEL_FLAVOR, flavname);
  711. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  712. consensus_cache_entry_t *most_recent = sort_and_find_most_recent(matches);
  713. if (!most_recent) {
  714. log_info(LD_DIRSERV, "No 'most recent' %s consensus found; "
  715. "not making diffs", flavname);
  716. goto done;
  717. }
  718. tor_assert(smartlist_len(matches));
  719. smartlist_del(matches, smartlist_len(matches) - 1);
  720. const char *most_recent_valid_after =
  721. consensus_cache_entry_get_value(most_recent, LABEL_VALID_AFTER);
  722. if (BUG(most_recent_valid_after == NULL))
  723. goto done; //LCOV_EXCL_LINE
  724. uint8_t most_recent_sha3[DIGEST256_LEN];
  725. if (BUG(cdm_entry_get_sha3_value(most_recent_sha3, most_recent,
  726. LABEL_SHA3_DIGEST_UNCOMPRESSED) < 0))
  727. goto done; //LCOV_EXCL_LINE
  728. // 2. Find all the relevant diffs _to_ this consensus. These are ones
  729. // that we don't need to compute.
  730. diffs = smartlist_new();
  731. consensus_cache_find_all(diffs, cdm_cache_get(),
  732. LABEL_VALID_AFTER, most_recent_valid_after);
  733. consensus_cache_filter_list(diffs, LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  734. consensus_cache_filter_list(diffs, LABEL_FLAVOR, flavname);
  735. have_diff_from = strmap_new();
  736. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  737. const char *va = consensus_cache_entry_get_value(diff,
  738. LABEL_FROM_VALID_AFTER);
  739. if (BUG(va == NULL))
  740. continue; // LCOV_EXCL_LINE
  741. strmap_set(have_diff_from, va, diff);
  742. } SMARTLIST_FOREACH_END(diff);
  743. // 3. See which consensuses in 'matches' don't have diffs yet.
  744. smartlist_reverse(matches); // from newest to oldest.
  745. compute_diffs_from = smartlist_new();
  746. SMARTLIST_FOREACH_BEGIN(matches, consensus_cache_entry_t *, ent) {
  747. const char *va = consensus_cache_entry_get_value(ent, LABEL_VALID_AFTER);
  748. if (BUG(va == NULL))
  749. continue; // LCOV_EXCL_LINE
  750. if (strmap_get(have_diff_from, va) != NULL)
  751. continue; /* we already have this one. */
  752. smartlist_add(compute_diffs_from, ent);
  753. } SMARTLIST_FOREACH_END(ent);
  754. log_info(LD_DIRSERV,
  755. "The most recent %s consensus is valid-after %s. We have diffs to "
  756. "this consensus for %d/%d older %s consensuses. Generating diffs "
  757. "for the other %d.",
  758. flavname,
  759. most_recent_valid_after,
  760. smartlist_len(matches) - smartlist_len(compute_diffs_from),
  761. smartlist_len(matches),
  762. flavname,
  763. smartlist_len(compute_diffs_from));
  764. // 4. Update the hashtable; remove entries in this flavor to other
  765. // target consensuses.
  766. cdm_diff_ht_purge(flavor, most_recent_sha3);
  767. // 5. Actually launch the requests.
  768. SMARTLIST_FOREACH_BEGIN(compute_diffs_from, consensus_cache_entry_t *, c) {
  769. if (BUG(c == most_recent))
  770. continue; // LCOV_EXCL_LINE
  771. uint8_t this_sha3[DIGEST256_LEN];
  772. if (BUG(cdm_entry_get_sha3_value(this_sha3, c,
  773. LABEL_SHA3_DIGEST_AS_SIGNED)<0))
  774. continue; // LCOV_EXCL_LINE
  775. if (cdm_diff_ht_check_and_note_pending(flavor,
  776. this_sha3, most_recent_sha3)) {
  777. // This is already pending, or we encountered an error.
  778. continue;
  779. }
  780. consensus_diff_queue_diff_work(c, most_recent);
  781. } SMARTLIST_FOREACH_END(c);
  782. done:
  783. smartlist_free(matches);
  784. smartlist_free(diffs);
  785. smartlist_free(compute_diffs_from);
  786. strmap_free(have_diff_from, NULL);
  787. }
  788. /**
  789. * Scan the cache for diffs, and add them to the hashtable.
  790. */
  791. static void
  792. consdiffmgr_diffs_load(void)
  793. {
  794. smartlist_t *diffs = smartlist_new();
  795. consensus_cache_find_all(diffs, cdm_cache_get(),
  796. LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  797. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  798. const char *lv_flavor =
  799. consensus_cache_entry_get_value(diff, LABEL_FLAVOR);
  800. if (!lv_flavor)
  801. continue;
  802. int flavor = networkstatus_parse_flavor_name(lv_flavor);
  803. if (flavor < 0)
  804. continue;
  805. const char *lv_compression =
  806. consensus_cache_entry_get_value(diff, LABEL_COMPRESSION_TYPE);
  807. compress_method_t method = NO_METHOD;
  808. if (lv_compression) {
  809. method = compression_method_get_by_name(lv_compression);
  810. if (method == UNKNOWN_METHOD) {
  811. continue;
  812. }
  813. }
  814. uint8_t from_sha3[DIGEST256_LEN];
  815. uint8_t to_sha3[DIGEST256_LEN];
  816. if (cdm_entry_get_sha3_value(from_sha3, diff, LABEL_FROM_SHA3_DIGEST)<0)
  817. continue;
  818. if (cdm_entry_get_sha3_value(to_sha3, diff, LABEL_TARGET_SHA3_DIGEST)<0)
  819. continue;
  820. cdm_diff_ht_set_status(flavor, from_sha3, to_sha3,
  821. method,
  822. CDM_DIFF_PRESENT,
  823. consensus_cache_entry_handle_new(diff));
  824. } SMARTLIST_FOREACH_END(diff);
  825. smartlist_free(diffs);
  826. }
  827. /**
  828. * Build new diffs as needed.
  829. */
  830. void
  831. consdiffmgr_rescan(void)
  832. {
  833. if (cdm_cache_dirty == 0)
  834. return;
  835. // Clean up here to make room for new diffs, and to ensure that older
  836. // consensuses do not have any entries.
  837. consdiffmgr_cleanup();
  838. if (cdm_cache_loaded == 0) {
  839. consdiffmgr_diffs_load();
  840. cdm_cache_loaded = 1;
  841. }
  842. for (int flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  843. consdiffmgr_rescan_flavor_((consensus_flavor_t) flav);
  844. }
  845. cdm_cache_dirty = 0;
  846. }
  847. /**
  848. * Helper: compare two files by their from-valid-after and valid-after labels,
  849. * trying to sort in ascending order by from-valid-after (when present) and
  850. * valid-after (when not). Place everything that has neither label first in
  851. * the list.
  852. */
  853. static int
  854. compare_by_staleness_(const void **a, const void **b)
  855. {
  856. const consensus_cache_entry_t *e1 = *a;
  857. const consensus_cache_entry_t *e2 = *b;
  858. const char *va1, *fva1, *va2, *fva2;
  859. va1 = consensus_cache_entry_get_value(e1, LABEL_VALID_AFTER);
  860. va2 = consensus_cache_entry_get_value(e2, LABEL_VALID_AFTER);
  861. fva1 = consensus_cache_entry_get_value(e1, LABEL_FROM_VALID_AFTER);
  862. fva2 = consensus_cache_entry_get_value(e2, LABEL_FROM_VALID_AFTER);
  863. if (fva1)
  864. va1 = fva1;
  865. if (fva2)
  866. va2 = fva2;
  867. /* See note about iso-encoded values in compare_by_valid_after_. Also note
  868. * that missing dates will get placed first. */
  869. return strcmp_opt(va1, va2);
  870. }
  871. /** If there are not enough unused filenames to store <b>n</b> files, then
  872. * delete old consensuses until there are. (We have to keep track of the
  873. * number of filenames because of the way that the seccomp2 cache works.)
  874. *
  875. * Return 0 on success, -1 on failure.
  876. **/
  877. static int
  878. consdiffmgr_ensure_space_for_files(int n)
  879. {
  880. consensus_cache_t *cache = cdm_cache_get();
  881. if (consensus_cache_get_n_filenames_available(cache) >= n) {
  882. // there are already enough unused filenames.
  883. return 0;
  884. }
  885. // Try a cheap deletion of stuff that's waiting to get deleted.
  886. consensus_cache_delete_pending(cache, 0);
  887. if (consensus_cache_get_n_filenames_available(cache) >= n) {
  888. // okay, _that_ made enough filenames available.
  889. return 0;
  890. }
  891. // Let's get more assertive: clean out unused stuff, and force-remove
  892. // the files.
  893. consdiffmgr_cleanup();
  894. consensus_cache_delete_pending(cache, 1);
  895. const int n_to_remove = n - consensus_cache_get_n_filenames_available(cache);
  896. if (n_to_remove <= 0) {
  897. // okay, finally!
  898. return 0;
  899. }
  900. // At this point, we're going to have to throw out objects that will be
  901. // missed. Too bad!
  902. smartlist_t *objects = smartlist_new();
  903. consensus_cache_find_all(objects, cache, NULL, NULL);
  904. smartlist_sort(objects, compare_by_staleness_);
  905. int n_marked = 0;
  906. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  907. consensus_cache_entry_mark_for_removal(ent);
  908. if (++n_marked >= n_to_remove)
  909. break;
  910. } SMARTLIST_FOREACH_END(ent);
  911. consensus_cache_delete_pending(cache, 1);
  912. if (BUG(n_marked < n_to_remove))
  913. return -1;
  914. else
  915. return 0;
  916. }
  917. /**
  918. * Set consensus cache flags on the objects in this consdiffmgr.
  919. */
  920. static void
  921. consdiffmgr_set_cache_flags(void)
  922. {
  923. /* Right now, we just mark the consensus objects for aggressive release,
  924. * so that they get mmapped for as little time as possible. */
  925. smartlist_t *objects = smartlist_new();
  926. consensus_cache_find_all(objects, cdm_cache_get(), LABEL_DOCTYPE,
  927. DOCTYPE_CONSENSUS);
  928. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  929. consensus_cache_entry_mark_for_aggressive_release(ent);
  930. } SMARTLIST_FOREACH_END(ent);
  931. smartlist_free(objects);
  932. }
  933. /**
  934. * Called before shutdown: drop all storage held by the consdiffmgr.c module.
  935. */
  936. void
  937. consdiffmgr_free_all(void)
  938. {
  939. cdm_diff_t **diff, **next;
  940. for (diff = HT_START(cdm_diff_ht, &cdm_diff_ht); diff; diff = next) {
  941. cdm_diff_t *this = *diff;
  942. next = HT_NEXT_RMV(cdm_diff_ht, &cdm_diff_ht, diff);
  943. cdm_diff_free(this);
  944. }
  945. consensus_cache_free(cons_diff_cache);
  946. cons_diff_cache = NULL;
  947. }
  948. /* =====
  949. Thread workers
  950. =====*/
  951. typedef struct compressed_result_t {
  952. config_line_t *labels;
  953. /**
  954. * Output: Body of the diff, as compressed.
  955. */
  956. uint8_t *body;
  957. /**
  958. * Output: length of body_out
  959. */
  960. size_t bodylen;
  961. } compressed_result_t;
  962. /**
  963. * An object passed to a worker thread that will try to produce a consensus
  964. * diff.
  965. */
  966. typedef struct consensus_diff_worker_job_t {
  967. /**
  968. * Input: The consensus to compute the diff from. Holds a reference to the
  969. * cache entry, which must not be released until the job is passed back to
  970. * the main thread. The body must be mapped into memory in the main thread.
  971. */
  972. consensus_cache_entry_t *diff_from;
  973. /**
  974. * Input: The consensus to compute the diff to. Holds a reference to the
  975. * cache entry, which must not be released until the job is passed back to
  976. * the main thread. The body must be mapped into memory in the main thread.
  977. */
  978. consensus_cache_entry_t *diff_to;
  979. /** Output: labels and bodies */
  980. compressed_result_t out[ARRAY_LENGTH(compress_diffs_with)];
  981. } consensus_diff_worker_job_t;
  982. /** Given a consensus_cache_entry_t, check whether it has a label claiming
  983. * that it was compressed. If so, uncompress its contents into <b>out</b> and
  984. * set <b>outlen</b> to hold their size. If not, just copy the body into
  985. * <b>out</b> and set <b>outlen</b> to its length. Return 0 on success,
  986. * -1 on failure.
  987. *
  988. * In all cases, the output is nul-terminated. */
  989. STATIC int
  990. uncompress_or_copy(char **out, size_t *outlen,
  991. consensus_cache_entry_t *ent)
  992. {
  993. const uint8_t *body;
  994. size_t bodylen;
  995. if (consensus_cache_entry_get_body(ent, &body, &bodylen) < 0)
  996. return -1;
  997. const char *lv_compression =
  998. consensus_cache_entry_get_value(ent, LABEL_COMPRESSION_TYPE);
  999. compress_method_t method = NO_METHOD;
  1000. if (lv_compression)
  1001. method = compression_method_get_by_name(lv_compression);
  1002. return tor_uncompress(out, outlen, (const char *)body, bodylen,
  1003. method, 1, LOG_WARN);
  1004. }
  1005. /**
  1006. * Worker function. This function runs inside a worker thread and receives
  1007. * a consensus_diff_worker_job_t as its input.
  1008. */
  1009. static workqueue_reply_t
  1010. consensus_diff_worker_threadfn(void *state_, void *work_)
  1011. {
  1012. (void)state_;
  1013. consensus_diff_worker_job_t *job = work_;
  1014. const uint8_t *diff_from, *diff_to;
  1015. size_t len_from, len_to;
  1016. int r;
  1017. /* We need to have the body already mapped into RAM here.
  1018. */
  1019. r = consensus_cache_entry_get_body(job->diff_from, &diff_from, &len_from);
  1020. if (BUG(r < 0))
  1021. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1022. r = consensus_cache_entry_get_body(job->diff_to, &diff_to, &len_to);
  1023. if (BUG(r < 0))
  1024. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1025. const char *lv_to_valid_after =
  1026. consensus_cache_entry_get_value(job->diff_to, LABEL_VALID_AFTER);
  1027. const char *lv_from_valid_after =
  1028. consensus_cache_entry_get_value(job->diff_from, LABEL_VALID_AFTER);
  1029. const char *lv_from_digest =
  1030. consensus_cache_entry_get_value(job->diff_from,
  1031. LABEL_SHA3_DIGEST_AS_SIGNED);
  1032. const char *lv_from_flavor =
  1033. consensus_cache_entry_get_value(job->diff_from, LABEL_FLAVOR);
  1034. const char *lv_to_flavor =
  1035. consensus_cache_entry_get_value(job->diff_to, LABEL_FLAVOR);
  1036. const char *lv_to_digest =
  1037. consensus_cache_entry_get_value(job->diff_to,
  1038. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1039. if (! lv_from_digest) {
  1040. /* This isn't a bug right now, since it can happen if you're migrating
  1041. * from an older version of master to a newer one. The older ones didn't
  1042. * annotate their stored consensus objects with sha3-digest-as-signed.
  1043. */
  1044. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1045. }
  1046. /* All these values are mandatory on the input */
  1047. if (BUG(!lv_to_valid_after) ||
  1048. BUG(!lv_from_valid_after) ||
  1049. BUG(!lv_from_flavor) ||
  1050. BUG(!lv_to_flavor)) {
  1051. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1052. }
  1053. /* The flavors need to match */
  1054. if (BUG(strcmp(lv_from_flavor, lv_to_flavor))) {
  1055. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1056. }
  1057. char *consensus_diff;
  1058. {
  1059. char *diff_from_nt = NULL, *diff_to_nt = NULL;
  1060. size_t diff_from_nt_len, diff_to_nt_len;
  1061. if (uncompress_or_copy(&diff_from_nt, &diff_from_nt_len,
  1062. job->diff_from) < 0) {
  1063. return WQ_RPL_REPLY;
  1064. }
  1065. if (uncompress_or_copy(&diff_to_nt, &diff_to_nt_len,
  1066. job->diff_to) < 0) {
  1067. tor_free(diff_from_nt);
  1068. return WQ_RPL_REPLY;
  1069. }
  1070. tor_assert(diff_from_nt);
  1071. tor_assert(diff_to_nt);
  1072. // XXXX ugh; this is going to calculate the SHA3 of both its
  1073. // XXXX inputs again, even though we already have that. Maybe it's time
  1074. // XXXX to change the API here?
  1075. consensus_diff = consensus_diff_generate(diff_from_nt, diff_to_nt);
  1076. tor_free(diff_from_nt);
  1077. tor_free(diff_to_nt);
  1078. }
  1079. if (!consensus_diff) {
  1080. /* Couldn't generate consensus; we'll leave the reply blank. */
  1081. return WQ_RPL_REPLY;
  1082. }
  1083. /* Compress the results and send the reply */
  1084. tor_assert(compress_diffs_with[0] == NO_METHOD);
  1085. size_t difflen = strlen(consensus_diff);
  1086. job->out[0].body = (uint8_t *) consensus_diff;
  1087. job->out[0].bodylen = difflen;
  1088. config_line_t *common_labels = NULL;
  1089. cdm_labels_prepend_sha3(&common_labels,
  1090. LABEL_SHA3_DIGEST_UNCOMPRESSED,
  1091. job->out[0].body,
  1092. job->out[0].bodylen);
  1093. config_line_prepend(&common_labels, LABEL_FROM_VALID_AFTER,
  1094. lv_from_valid_after);
  1095. config_line_prepend(&common_labels, LABEL_VALID_AFTER,
  1096. lv_to_valid_after);
  1097. config_line_prepend(&common_labels, LABEL_FLAVOR, lv_from_flavor);
  1098. config_line_prepend(&common_labels, LABEL_FROM_SHA3_DIGEST,
  1099. lv_from_digest);
  1100. config_line_prepend(&common_labels, LABEL_TARGET_SHA3_DIGEST,
  1101. lv_to_digest);
  1102. config_line_prepend(&common_labels, LABEL_DOCTYPE,
  1103. DOCTYPE_CONSENSUS_DIFF);
  1104. job->out[0].labels = config_lines_dup(common_labels);
  1105. cdm_labels_prepend_sha3(&job->out[0].labels,
  1106. LABEL_SHA3_DIGEST,
  1107. job->out[0].body,
  1108. job->out[0].bodylen);
  1109. unsigned u;
  1110. for (u = 1; u < n_diff_compression_methods(); ++u) {
  1111. compress_method_t method = compress_diffs_with[u];
  1112. const char *methodname = compression_method_get_name(method);
  1113. char *result;
  1114. size_t sz;
  1115. if (0 == tor_compress(&result, &sz, consensus_diff, difflen, method)) {
  1116. job->out[u].body = (uint8_t*)result;
  1117. job->out[u].bodylen = sz;
  1118. job->out[u].labels = config_lines_dup(common_labels);
  1119. cdm_labels_prepend_sha3(&job->out[u].labels, LABEL_SHA3_DIGEST,
  1120. job->out[u].body,
  1121. job->out[u].bodylen);
  1122. config_line_prepend(&job->out[u].labels,
  1123. LABEL_COMPRESSION_TYPE,
  1124. methodname);
  1125. }
  1126. }
  1127. config_free_lines(common_labels);
  1128. return WQ_RPL_REPLY;
  1129. }
  1130. /**
  1131. * Helper: release all storage held in <b>job</b>.
  1132. */
  1133. static void
  1134. consensus_diff_worker_job_free(consensus_diff_worker_job_t *job)
  1135. {
  1136. if (!job)
  1137. return;
  1138. unsigned u;
  1139. for (u = 0; u < n_diff_compression_methods(); ++u) {
  1140. config_free_lines(job->out[u].labels);
  1141. tor_free(job->out[u].body);
  1142. }
  1143. consensus_cache_entry_decref(job->diff_from);
  1144. consensus_cache_entry_decref(job->diff_to);
  1145. tor_free(job);
  1146. }
  1147. /**
  1148. * Worker function: This function runs in the main thread, and receives
  1149. * a consensus_diff_worker_job_t that the worker thread has already
  1150. * processed.
  1151. */
  1152. static void
  1153. consensus_diff_worker_replyfn(void *work_)
  1154. {
  1155. tor_assert(in_main_thread());
  1156. tor_assert(work_);
  1157. consensus_diff_worker_job_t *job = work_;
  1158. const char *lv_from_digest =
  1159. consensus_cache_entry_get_value(job->diff_from,
  1160. LABEL_SHA3_DIGEST_AS_SIGNED);
  1161. const char *lv_to_digest =
  1162. consensus_cache_entry_get_value(job->diff_to,
  1163. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1164. const char *lv_flavor =
  1165. consensus_cache_entry_get_value(job->diff_to, LABEL_FLAVOR);
  1166. if (BUG(lv_from_digest == NULL))
  1167. lv_from_digest = "???"; // LCOV_EXCL_LINE
  1168. if (BUG(lv_to_digest == NULL))
  1169. lv_to_digest = "???"; // LCOV_EXCL_LINE
  1170. uint8_t from_sha3[DIGEST256_LEN];
  1171. uint8_t to_sha3[DIGEST256_LEN];
  1172. int flav = -1;
  1173. int cache = 1;
  1174. if (BUG(cdm_entry_get_sha3_value(from_sha3, job->diff_from,
  1175. LABEL_SHA3_DIGEST_AS_SIGNED) < 0))
  1176. cache = 0;
  1177. if (BUG(cdm_entry_get_sha3_value(to_sha3, job->diff_to,
  1178. LABEL_SHA3_DIGEST_UNCOMPRESSED) < 0))
  1179. cache = 0;
  1180. if (BUG(lv_flavor == NULL)) {
  1181. cache = 0;
  1182. } else if ((flav = networkstatus_parse_flavor_name(lv_flavor)) < 0) {
  1183. cache = 0;
  1184. }
  1185. int status = CDM_DIFF_ERROR;
  1186. consensus_cache_entry_handle_t *handles[ARRAY_LENGTH(compress_diffs_with)];
  1187. memset(handles, 0, sizeof(handles));
  1188. consdiffmgr_ensure_space_for_files(n_diff_compression_methods());
  1189. unsigned u;
  1190. for (u = 0; u < n_diff_compression_methods(); ++u) {
  1191. compress_method_t method = compress_diffs_with[u];
  1192. uint8_t *body_out = job->out[u].body;
  1193. size_t bodylen_out = job->out[u].bodylen;
  1194. config_line_t *labels = job->out[u].labels;
  1195. const char *methodname = compression_method_get_name(method);
  1196. if (body_out && bodylen_out && labels) {
  1197. /* Success! Store the results */
  1198. log_info(LD_DIRSERV, "Adding consensus diff from %s to %s, "
  1199. "compressed with %s",
  1200. lv_from_digest, lv_to_digest, methodname);
  1201. consensus_cache_entry_t *ent =
  1202. consensus_cache_add(cdm_cache_get(),
  1203. labels,
  1204. body_out,
  1205. bodylen_out);
  1206. status = CDM_DIFF_PRESENT;
  1207. handles[u] = consensus_cache_entry_handle_new(ent);
  1208. consensus_cache_entry_decref(ent);
  1209. }
  1210. }
  1211. if (status != CDM_DIFF_PRESENT) {
  1212. /* Failure! Nothing to do but complain */
  1213. log_warn(LD_DIRSERV,
  1214. "Worker was unable to compute consensus diff "
  1215. "from %s to %s", lv_from_digest, lv_to_digest);
  1216. /* Cache this error so we don't try to compute this one again. */
  1217. status = CDM_DIFF_ERROR;
  1218. }
  1219. for (u = 0; u < ARRAY_LENGTH(handles); ++u) {
  1220. compress_method_t method = compress_diffs_with[u];
  1221. if (cache) {
  1222. cdm_diff_ht_set_status(flav, from_sha3, to_sha3, method, status,
  1223. handles[u]);
  1224. } else {
  1225. consensus_cache_entry_handle_free(handles[u]);
  1226. }
  1227. }
  1228. consensus_diff_worker_job_free(job);
  1229. }
  1230. /**
  1231. * Queue the job of computing the diff from <b>diff_from</b> to <b>diff_to</b>
  1232. * in a worker thread.
  1233. */
  1234. static int
  1235. consensus_diff_queue_diff_work(consensus_cache_entry_t *diff_from,
  1236. consensus_cache_entry_t *diff_to)
  1237. {
  1238. tor_assert(in_main_thread());
  1239. consensus_cache_entry_incref(diff_from);
  1240. consensus_cache_entry_incref(diff_to);
  1241. consensus_diff_worker_job_t *job = tor_malloc_zero(sizeof(*job));
  1242. job->diff_from = diff_from;
  1243. job->diff_to = diff_to;
  1244. /* Make sure body is mapped. */
  1245. const uint8_t *body;
  1246. size_t bodylen;
  1247. int r1 = consensus_cache_entry_get_body(diff_from, &body, &bodylen);
  1248. int r2 = consensus_cache_entry_get_body(diff_to, &body, &bodylen);
  1249. if (r1 < 0 || r2 < 0)
  1250. goto err;
  1251. workqueue_entry_t *work;
  1252. work = cpuworker_queue_work(consensus_diff_worker_threadfn,
  1253. consensus_diff_worker_replyfn,
  1254. job);
  1255. if (!work)
  1256. goto err;
  1257. return 0;
  1258. err:
  1259. consensus_diff_worker_job_free(job); // includes decrefs.
  1260. return -1;
  1261. }