consdiffmgr.c 45 KB

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