consdiffmgr.c 42 KB

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