consdiffmgr.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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. config_free_lines(labels);
  439. }
  440. if (entry) {
  441. consensus_cache_entry_mark_for_aggressive_release(entry);
  442. consensus_cache_entry_decref(entry);
  443. }
  444. cdm_cache_dirty = 1;
  445. return entry ? 0 : -1;
  446. }
  447. /**
  448. * Helper: used to sort two smartlists of consensus_cache_entry_t by their
  449. * LABEL_VALID_AFTER labels.
  450. */
  451. static int
  452. compare_by_valid_after_(const void **a, const void **b)
  453. {
  454. const consensus_cache_entry_t *e1 = *a;
  455. const consensus_cache_entry_t *e2 = *b;
  456. /* We're in luck here: sorting UTC iso-encoded values lexically will work
  457. * fine (until 9999). */
  458. return strcmp_opt(consensus_cache_entry_get_value(e1, LABEL_VALID_AFTER),
  459. consensus_cache_entry_get_value(e2, LABEL_VALID_AFTER));
  460. }
  461. /**
  462. * Helper: Sort <b>lst</b> by LABEL_VALID_AFTER and return the most recent
  463. * entry.
  464. */
  465. static consensus_cache_entry_t *
  466. sort_and_find_most_recent(smartlist_t *lst)
  467. {
  468. smartlist_sort(lst, compare_by_valid_after_);
  469. if (smartlist_len(lst)) {
  470. return smartlist_get(lst, smartlist_len(lst) - 1);
  471. } else {
  472. return NULL;
  473. }
  474. }
  475. /**
  476. * Look up consensus_cache_entry_t for the consensus of type <b>flavor</b>,
  477. * from the source consensus with the specified digest (which must be SHA3).
  478. *
  479. * If the diff is present, store it into *<b>entry_out</b> and return
  480. * CONSDIFF_AVAILABLE. Otherwise return CONSDIFF_NOT_FOUND or
  481. * CONSDIFF_IN_PROGRESS.
  482. */
  483. consdiff_status_t
  484. consdiffmgr_find_diff_from(consensus_cache_entry_t **entry_out,
  485. consensus_flavor_t flavor,
  486. int digest_type,
  487. const uint8_t *digest,
  488. size_t digestlen,
  489. compress_method_t method)
  490. {
  491. if (BUG(digest_type != DIGEST_SHA3_256) ||
  492. BUG(digestlen != DIGEST256_LEN)) {
  493. return CONSDIFF_NOT_FOUND; // LCOV_EXCL_LINE
  494. }
  495. // Try to look up the entry in the hashtable.
  496. cdm_diff_t search, *ent;
  497. memset(&search, 0, sizeof(search));
  498. search.flavor = flavor;
  499. search.compress_method = method;
  500. memcpy(search.from_sha3, digest, DIGEST256_LEN);
  501. ent = HT_FIND(cdm_diff_ht, &cdm_diff_ht, &search);
  502. if (ent == NULL ||
  503. ent->cdm_diff_status == CDM_DIFF_ERROR) {
  504. return CONSDIFF_NOT_FOUND;
  505. } else if (ent->cdm_diff_status == CDM_DIFF_IN_PROGRESS) {
  506. return CONSDIFF_IN_PROGRESS;
  507. } else if (BUG(ent->cdm_diff_status != CDM_DIFF_PRESENT)) {
  508. return CONSDIFF_IN_PROGRESS;
  509. }
  510. *entry_out = consensus_cache_entry_handle_get(ent->entry);
  511. return (*entry_out) ? CONSDIFF_AVAILABLE : CONSDIFF_NOT_FOUND;
  512. #if 0
  513. // XXXX Remove this. I'm keeping it around for now in case we need to
  514. // XXXX debug issues in the hashtable.
  515. char hex[HEX_DIGEST256_LEN+1];
  516. base16_encode(hex, sizeof(hex), (const char *)digest, digestlen);
  517. const char *flavname = networkstatus_get_flavor_name(flavor);
  518. smartlist_t *matches = smartlist_new();
  519. consensus_cache_find_all(matches, cdm_cache_get(),
  520. LABEL_FROM_SHA3_DIGEST, hex);
  521. consensus_cache_filter_list(matches, LABEL_FLAVOR, flavname);
  522. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  523. *entry_out = sort_and_find_most_recent(matches);
  524. consdiff_status_t result =
  525. (*entry_out) ? CONSDIFF_AVAILABLE : CONSDIFF_NOT_FOUND;
  526. smartlist_free(matches);
  527. return result;
  528. #endif
  529. }
  530. /**
  531. * Perform periodic cleanup tasks on the consensus diff cache. Return
  532. * the number of objects marked for deletion.
  533. */
  534. int
  535. consdiffmgr_cleanup(void)
  536. {
  537. smartlist_t *objects = smartlist_new();
  538. smartlist_t *consensuses = smartlist_new();
  539. smartlist_t *diffs = smartlist_new();
  540. int n_to_delete = 0;
  541. log_debug(LD_DIRSERV, "Looking for consdiffmgr entries to remove");
  542. // 1. Delete any consensus or diff or anything whose valid_after is too old.
  543. const time_t valid_after_cutoff =
  544. approx_time() - 3600 * consdiff_cfg.cache_max_age_hours;
  545. consensus_cache_find_all(objects, cdm_cache_get(),
  546. NULL, NULL);
  547. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  548. const char *lv_valid_after =
  549. consensus_cache_entry_get_value(ent, LABEL_VALID_AFTER);
  550. if (! lv_valid_after) {
  551. log_debug(LD_DIRSERV, "Ignoring entry because it had no %s label",
  552. LABEL_VALID_AFTER);
  553. continue;
  554. }
  555. time_t valid_after = 0;
  556. if (parse_iso_time_nospace(lv_valid_after, &valid_after) < 0) {
  557. log_debug(LD_DIRSERV, "Ignoring entry because its %s value (%s) was "
  558. "unparseable", LABEL_VALID_AFTER, escaped(lv_valid_after));
  559. continue;
  560. }
  561. if (valid_after < valid_after_cutoff) {
  562. log_debug(LD_DIRSERV, "Deleting entry because its %s value (%s) was "
  563. "too old", LABEL_VALID_AFTER, lv_valid_after);
  564. consensus_cache_entry_mark_for_removal(ent);
  565. ++n_to_delete;
  566. }
  567. } SMARTLIST_FOREACH_END(ent);
  568. // 2. Delete all diffs that lead to a consensus whose valid-after is not the
  569. // latest.
  570. for (int flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  571. const char *flavname = networkstatus_get_flavor_name(flav);
  572. /* Determine the most recent consensus of this flavor */
  573. consensus_cache_find_all(consensuses, cdm_cache_get(),
  574. LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  575. consensus_cache_filter_list(consensuses, LABEL_FLAVOR, flavname);
  576. consensus_cache_entry_t *most_recent =
  577. sort_and_find_most_recent(consensuses);
  578. if (most_recent == NULL)
  579. continue;
  580. const char *most_recent_sha3 =
  581. consensus_cache_entry_get_value(most_recent,
  582. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  583. if (BUG(most_recent_sha3 == NULL))
  584. continue; // LCOV_EXCL_LINE
  585. /* consider all such-flavored diffs, and look to see if they match. */
  586. consensus_cache_find_all(diffs, cdm_cache_get(),
  587. LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  588. consensus_cache_filter_list(diffs, LABEL_FLAVOR, flavname);
  589. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  590. const char *this_diff_target_sha3 =
  591. consensus_cache_entry_get_value(diff, LABEL_TARGET_SHA3_DIGEST);
  592. if (!this_diff_target_sha3)
  593. continue;
  594. if (strcmp(this_diff_target_sha3, most_recent_sha3)) {
  595. consensus_cache_entry_mark_for_removal(diff);
  596. ++n_to_delete;
  597. }
  598. } SMARTLIST_FOREACH_END(diff);
  599. smartlist_clear(consensuses);
  600. smartlist_clear(diffs);
  601. }
  602. smartlist_free(objects);
  603. smartlist_free(consensuses);
  604. smartlist_free(diffs);
  605. // Actually remove files, if they're not used.
  606. consensus_cache_delete_pending(cdm_cache_get(), 0);
  607. return n_to_delete;
  608. }
  609. /**
  610. * Initialize the consensus diff manager and its cache, and configure
  611. * its parameters based on the latest torrc and networkstatus parameters.
  612. */
  613. void
  614. consdiffmgr_configure(const consdiff_cfg_t *cfg)
  615. {
  616. if (cfg)
  617. memcpy(&consdiff_cfg, cfg, sizeof(consdiff_cfg));
  618. (void) cdm_cache_get();
  619. }
  620. /**
  621. * Tell the sandbox (if any) configured by <b>cfg</b> to allow the
  622. * operations that the consensus diff manager will need.
  623. */
  624. int
  625. consdiffmgr_register_with_sandbox(struct sandbox_cfg_elem **cfg)
  626. {
  627. return consensus_cache_register_with_sandbox(cdm_cache_get(), cfg);
  628. }
  629. /**
  630. * Scan the consensus diff manager's cache for any grossly malformed entries,
  631. * and mark them as deletable. Return 0 if no problems were found; 1
  632. * if problems were found and fixed.
  633. */
  634. int
  635. consdiffmgr_validate(void)
  636. {
  637. /* Right now, we only check for entries that have bad sha3 values */
  638. int problems = 0;
  639. smartlist_t *objects = smartlist_new();
  640. consensus_cache_find_all(objects, cdm_cache_get(),
  641. NULL, NULL);
  642. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, obj) {
  643. uint8_t sha3_expected[DIGEST256_LEN];
  644. uint8_t sha3_received[DIGEST256_LEN];
  645. int r = cdm_entry_get_sha3_value(sha3_expected, obj, LABEL_SHA3_DIGEST);
  646. if (r == -1) {
  647. /* digest isn't there; that's allowed */
  648. continue;
  649. } else if (r == -2) {
  650. /* digest is malformed; that's not allowed */
  651. problems = 1;
  652. consensus_cache_entry_mark_for_removal(obj);
  653. continue;
  654. }
  655. const uint8_t *body;
  656. size_t bodylen;
  657. consensus_cache_entry_incref(obj);
  658. r = consensus_cache_entry_get_body(obj, &body, &bodylen);
  659. if (r == 0) {
  660. crypto_digest256((char *)sha3_received, (const char *)body, bodylen,
  661. DIGEST_SHA3_256);
  662. }
  663. consensus_cache_entry_decref(obj);
  664. if (r < 0)
  665. continue;
  666. // Deconfuse coverity about the possibility of sha3_received being
  667. // uninitialized
  668. tor_assert(r <= 0);
  669. if (fast_memneq(sha3_received, sha3_expected, DIGEST256_LEN)) {
  670. problems = 1;
  671. consensus_cache_entry_mark_for_removal(obj);
  672. continue;
  673. }
  674. } SMARTLIST_FOREACH_END(obj);
  675. smartlist_free(objects);
  676. return problems;
  677. }
  678. /**
  679. * Helper: build new diffs of <b>flavor</b> as needed
  680. */
  681. static void
  682. consdiffmgr_rescan_flavor_(consensus_flavor_t flavor)
  683. {
  684. smartlist_t *matches = NULL;
  685. smartlist_t *diffs = NULL;
  686. smartlist_t *compute_diffs_from = NULL;
  687. strmap_t *have_diff_from = NULL;
  688. // look for the most recent consensus, and for all previous in-range
  689. // consensuses. Do they all have diffs to it?
  690. const char *flavname = networkstatus_get_flavor_name(flavor);
  691. // 1. find the most recent consensus, and the ones that we might want
  692. // to diff to it.
  693. matches = smartlist_new();
  694. consensus_cache_find_all(matches, cdm_cache_get(),
  695. LABEL_FLAVOR, flavname);
  696. consensus_cache_filter_list(matches, LABEL_DOCTYPE, DOCTYPE_CONSENSUS);
  697. consensus_cache_entry_t *most_recent = sort_and_find_most_recent(matches);
  698. if (!most_recent) {
  699. log_info(LD_DIRSERV, "No 'most recent' %s consensus found; "
  700. "not making diffs", flavname);
  701. goto done;
  702. }
  703. tor_assert(smartlist_len(matches));
  704. smartlist_del(matches, smartlist_len(matches) - 1);
  705. const char *most_recent_valid_after =
  706. consensus_cache_entry_get_value(most_recent, LABEL_VALID_AFTER);
  707. if (BUG(most_recent_valid_after == NULL))
  708. goto done; //LCOV_EXCL_LINE
  709. uint8_t most_recent_sha3[DIGEST256_LEN];
  710. if (BUG(cdm_entry_get_sha3_value(most_recent_sha3, most_recent,
  711. LABEL_SHA3_DIGEST_UNCOMPRESSED) < 0))
  712. goto done; //LCOV_EXCL_LINE
  713. // 2. Find all the relevant diffs _to_ this consensus. These are ones
  714. // that we don't need to compute.
  715. diffs = smartlist_new();
  716. consensus_cache_find_all(diffs, cdm_cache_get(),
  717. LABEL_VALID_AFTER, most_recent_valid_after);
  718. consensus_cache_filter_list(diffs, LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  719. consensus_cache_filter_list(diffs, LABEL_FLAVOR, flavname);
  720. have_diff_from = strmap_new();
  721. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  722. const char *va = consensus_cache_entry_get_value(diff,
  723. LABEL_FROM_VALID_AFTER);
  724. if (BUG(va == NULL))
  725. continue; // LCOV_EXCL_LINE
  726. strmap_set(have_diff_from, va, diff);
  727. } SMARTLIST_FOREACH_END(diff);
  728. // 3. See which consensuses in 'matches' don't have diffs yet.
  729. smartlist_reverse(matches); // from newest to oldest.
  730. compute_diffs_from = smartlist_new();
  731. SMARTLIST_FOREACH_BEGIN(matches, consensus_cache_entry_t *, ent) {
  732. const char *va = consensus_cache_entry_get_value(ent, LABEL_VALID_AFTER);
  733. if (BUG(va == NULL))
  734. continue; // LCOV_EXCL_LINE
  735. if (strmap_get(have_diff_from, va) != NULL)
  736. continue; /* we already have this one. */
  737. smartlist_add(compute_diffs_from, ent);
  738. } SMARTLIST_FOREACH_END(ent);
  739. log_info(LD_DIRSERV,
  740. "The most recent %s consensus is valid-after %s. We have diffs to "
  741. "this consensus for %d/%d older %s consensuses. Generating diffs "
  742. "for the other %d.",
  743. flavname,
  744. most_recent_valid_after,
  745. smartlist_len(matches) - smartlist_len(compute_diffs_from),
  746. smartlist_len(matches),
  747. flavname,
  748. smartlist_len(compute_diffs_from));
  749. // 4. Update the hashtable; remove entries in this flavor to other
  750. // target consensuses.
  751. cdm_diff_ht_purge(flavor, most_recent_sha3);
  752. // 5. Actually launch the requests.
  753. SMARTLIST_FOREACH_BEGIN(compute_diffs_from, consensus_cache_entry_t *, c) {
  754. if (BUG(c == most_recent))
  755. continue; // LCOV_EXCL_LINE
  756. uint8_t this_sha3[DIGEST256_LEN];
  757. if (BUG(cdm_entry_get_sha3_value(this_sha3, c,
  758. LABEL_SHA3_DIGEST_UNCOMPRESSED)<0))
  759. continue; // LCOV_EXCL_LINE
  760. if (cdm_diff_ht_check_and_note_pending(flavor,
  761. this_sha3, most_recent_sha3)) {
  762. // This is already pending, or we encountered an error.
  763. continue;
  764. }
  765. consensus_diff_queue_diff_work(c, most_recent);
  766. } SMARTLIST_FOREACH_END(c);
  767. done:
  768. smartlist_free(matches);
  769. smartlist_free(diffs);
  770. smartlist_free(compute_diffs_from);
  771. strmap_free(have_diff_from, NULL);
  772. }
  773. /**
  774. * Scan the cache for diffs, and add them to the hashtable.
  775. */
  776. static void
  777. consdiffmgr_diffs_load(void)
  778. {
  779. smartlist_t *diffs = smartlist_new();
  780. consensus_cache_find_all(diffs, cdm_cache_get(),
  781. LABEL_DOCTYPE, DOCTYPE_CONSENSUS_DIFF);
  782. SMARTLIST_FOREACH_BEGIN(diffs, consensus_cache_entry_t *, diff) {
  783. const char *lv_flavor =
  784. consensus_cache_entry_get_value(diff, LABEL_FLAVOR);
  785. if (!lv_flavor)
  786. continue;
  787. int flavor = networkstatus_parse_flavor_name(lv_flavor);
  788. if (flavor < 0)
  789. continue;
  790. const char *lv_compression =
  791. consensus_cache_entry_get_value(diff, LABEL_COMPRESSION_TYPE);
  792. compress_method_t method = NO_METHOD;
  793. if (lv_compression) {
  794. method = compression_method_get_by_name(lv_compression);
  795. if (method == UNKNOWN_METHOD) {
  796. continue;
  797. }
  798. }
  799. uint8_t from_sha3[DIGEST256_LEN];
  800. uint8_t to_sha3[DIGEST256_LEN];
  801. if (cdm_entry_get_sha3_value(from_sha3, diff, LABEL_FROM_SHA3_DIGEST)<0)
  802. continue;
  803. if (cdm_entry_get_sha3_value(to_sha3, diff, LABEL_TARGET_SHA3_DIGEST)<0)
  804. continue;
  805. cdm_diff_ht_set_status(flavor, from_sha3, to_sha3,
  806. method,
  807. CDM_DIFF_PRESENT,
  808. consensus_cache_entry_handle_new(diff));
  809. } SMARTLIST_FOREACH_END(diff);
  810. smartlist_free(diffs);
  811. }
  812. /**
  813. * Build new diffs as needed.
  814. */
  815. void
  816. consdiffmgr_rescan(void)
  817. {
  818. if (cdm_cache_dirty == 0)
  819. return;
  820. // Clean up here to make room for new diffs, and to ensure that older
  821. // consensuses do not have any entries.
  822. consdiffmgr_cleanup();
  823. if (cdm_cache_loaded == 0) {
  824. consdiffmgr_diffs_load();
  825. cdm_cache_loaded = 1;
  826. }
  827. for (int flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  828. consdiffmgr_rescan_flavor_((consensus_flavor_t) flav);
  829. }
  830. cdm_cache_dirty = 0;
  831. }
  832. /**
  833. * Helper: compare two files by their from-valid-after and valid-after labels,
  834. * trying to sort in ascending order by from-valid-after (when present) and
  835. * valid-after (when not). Place everything that has neither label first in
  836. * the list.
  837. */
  838. static int
  839. compare_by_staleness_(const void **a, const void **b)
  840. {
  841. const consensus_cache_entry_t *e1 = *a;
  842. const consensus_cache_entry_t *e2 = *b;
  843. const char *va1, *fva1, *va2, *fva2;
  844. va1 = consensus_cache_entry_get_value(e1, LABEL_VALID_AFTER);
  845. va2 = consensus_cache_entry_get_value(e2, LABEL_VALID_AFTER);
  846. fva1 = consensus_cache_entry_get_value(e1, LABEL_FROM_VALID_AFTER);
  847. fva2 = consensus_cache_entry_get_value(e2, LABEL_FROM_VALID_AFTER);
  848. if (fva1)
  849. va1 = fva1;
  850. if (fva2)
  851. va2 = fva2;
  852. /* See note about iso-encoded values in compare_by_valid_after_. Also note
  853. * that missing dates will get placed first. */
  854. return strcmp_opt(va1, va2);
  855. }
  856. /** If there are not enough unused filenames to store <b>n</b> files, then
  857. * delete old consensuses until there are. (We have to keep track of the
  858. * number of filenames because of the way that the seccomp2 cache works.)
  859. *
  860. * Return 0 on success, -1 on failure.
  861. **/
  862. static int
  863. consdiffmgr_ensure_space_for_files(int n)
  864. {
  865. consensus_cache_t *cache = cdm_cache_get();
  866. if (consensus_cache_get_n_filenames_available(cache) >= n) {
  867. // there are already enough unused filenames.
  868. return 0;
  869. }
  870. // Try a cheap deletion of stuff that's waiting to get deleted.
  871. consensus_cache_delete_pending(cache, 0);
  872. if (consensus_cache_get_n_filenames_available(cache) >= n) {
  873. // okay, _that_ made enough filenames available.
  874. return 0;
  875. }
  876. // Let's get more assertive: clean out unused stuff, and force-remove
  877. // the files.
  878. consdiffmgr_cleanup();
  879. consensus_cache_delete_pending(cache, 1);
  880. const int n_to_remove = n - consensus_cache_get_n_filenames_available(cache);
  881. if (n_to_remove <= 0) {
  882. // okay, finally!
  883. return 0;
  884. }
  885. // At this point, we're going to have to throw out objects that will be
  886. // missed. Too bad!
  887. smartlist_t *objects = smartlist_new();
  888. consensus_cache_find_all(objects, cache, NULL, NULL);
  889. smartlist_sort(objects, compare_by_staleness_);
  890. int n_marked = 0;
  891. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  892. consensus_cache_entry_mark_for_removal(ent);
  893. if (++n_marked >= n_to_remove)
  894. break;
  895. } SMARTLIST_FOREACH_END(ent);
  896. consensus_cache_delete_pending(cache, 1);
  897. if (BUG(n_marked < n_to_remove))
  898. return -1;
  899. else
  900. return 0;
  901. }
  902. /**
  903. * Set consensus cache flags on the objects in this consdiffmgr.
  904. */
  905. static void
  906. consdiffmgr_set_cache_flags(void)
  907. {
  908. /* Right now, we just mark the consensus objects for aggressive release,
  909. * so that they get mmapped for as little time as possible. */
  910. smartlist_t *objects = smartlist_new();
  911. consensus_cache_find_all(objects, cdm_cache_get(), LABEL_DOCTYPE,
  912. DOCTYPE_CONSENSUS);
  913. SMARTLIST_FOREACH_BEGIN(objects, consensus_cache_entry_t *, ent) {
  914. consensus_cache_entry_mark_for_aggressive_release(ent);
  915. } SMARTLIST_FOREACH_END(ent);
  916. smartlist_free(objects);
  917. }
  918. /**
  919. * Called before shutdown: drop all storage held by the consdiffmgr.c module.
  920. */
  921. void
  922. consdiffmgr_free_all(void)
  923. {
  924. cdm_diff_t **diff, **next;
  925. for (diff = HT_START(cdm_diff_ht, &cdm_diff_ht); diff; diff = next) {
  926. cdm_diff_t *this = *diff;
  927. next = HT_NEXT_RMV(cdm_diff_ht, &cdm_diff_ht, diff);
  928. cdm_diff_free(this);
  929. }
  930. consensus_cache_free(cons_diff_cache);
  931. cons_diff_cache = NULL;
  932. }
  933. /* =====
  934. Thread workers
  935. =====*/
  936. typedef struct compressed_result_t {
  937. config_line_t *labels;
  938. /**
  939. * Output: Body of the diff, as compressed.
  940. */
  941. uint8_t *body;
  942. /**
  943. * Output: length of body_out
  944. */
  945. size_t bodylen;
  946. } compressed_result_t;
  947. /**
  948. * An object passed to a worker thread that will try to produce a consensus
  949. * diff.
  950. */
  951. typedef struct consensus_diff_worker_job_t {
  952. /**
  953. * Input: The consensus to compute the diff from. Holds a reference to the
  954. * cache entry, which must not be released until the job is passed back to
  955. * the main thread. The body must be mapped into memory in the main thread.
  956. */
  957. consensus_cache_entry_t *diff_from;
  958. /**
  959. * Input: The consensus to compute the diff to. Holds a reference to the
  960. * cache entry, which must not be released until the job is passed back to
  961. * the main thread. The body must be mapped into memory in the main thread.
  962. */
  963. consensus_cache_entry_t *diff_to;
  964. /** Output: labels and bodies */
  965. compressed_result_t out[ARRAY_LENGTH(compress_diffs_with)];
  966. } consensus_diff_worker_job_t;
  967. /** Given a consensus_cache_entry_t, check whether it has a label claiming
  968. * that it was compressed. If so, uncompress its contents into <b>out</b> and
  969. * set <b>outlen</b> to hold their size. If not, just copy the body into
  970. * <b>out</b> and set <b>outlen</b> to its length. Return 0 on success,
  971. * -1 on failure.
  972. *
  973. * In all cases, the output is nul-terminated. */
  974. STATIC int
  975. uncompress_or_copy(char **out, size_t *outlen,
  976. consensus_cache_entry_t *ent)
  977. {
  978. const uint8_t *body;
  979. size_t bodylen;
  980. if (consensus_cache_entry_get_body(ent, &body, &bodylen) < 0)
  981. return -1;
  982. const char *lv_compression =
  983. consensus_cache_entry_get_value(ent, LABEL_COMPRESSION_TYPE);
  984. compress_method_t method = NO_METHOD;
  985. if (lv_compression)
  986. method = compression_method_get_by_name(lv_compression);
  987. if (method == NO_METHOD) {
  988. *out = tor_memdup_nulterm(body, bodylen);
  989. *outlen = bodylen;
  990. return 0;
  991. } else {
  992. return tor_uncompress(out, outlen, (const char *)body, bodylen,
  993. method, 1, LOG_WARN);
  994. }
  995. }
  996. /**
  997. * Worker function. This function runs inside a worker thread and receives
  998. * a consensus_diff_worker_job_t as its input.
  999. */
  1000. static workqueue_reply_t
  1001. consensus_diff_worker_threadfn(void *state_, void *work_)
  1002. {
  1003. (void)state_;
  1004. consensus_diff_worker_job_t *job = work_;
  1005. const uint8_t *diff_from, *diff_to;
  1006. size_t len_from, len_to;
  1007. int r;
  1008. /* We need to have the body already mapped into RAM here.
  1009. */
  1010. r = consensus_cache_entry_get_body(job->diff_from, &diff_from, &len_from);
  1011. if (BUG(r < 0))
  1012. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1013. r = consensus_cache_entry_get_body(job->diff_to, &diff_to, &len_to);
  1014. if (BUG(r < 0))
  1015. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1016. const char *lv_to_valid_after =
  1017. consensus_cache_entry_get_value(job->diff_to, LABEL_VALID_AFTER);
  1018. const char *lv_from_valid_after =
  1019. consensus_cache_entry_get_value(job->diff_from, LABEL_VALID_AFTER);
  1020. const char *lv_from_digest =
  1021. consensus_cache_entry_get_value(job->diff_from,
  1022. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1023. const char *lv_from_flavor =
  1024. consensus_cache_entry_get_value(job->diff_from, LABEL_FLAVOR);
  1025. const char *lv_to_flavor =
  1026. consensus_cache_entry_get_value(job->diff_to, LABEL_FLAVOR);
  1027. const char *lv_to_digest =
  1028. consensus_cache_entry_get_value(job->diff_to,
  1029. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1030. /* All these values are mandatory on the input */
  1031. if (BUG(!lv_to_valid_after) ||
  1032. BUG(!lv_from_valid_after) ||
  1033. BUG(!lv_from_digest) ||
  1034. BUG(!lv_from_flavor) ||
  1035. BUG(!lv_to_flavor)) {
  1036. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1037. }
  1038. /* The flavors need to match */
  1039. if (BUG(strcmp(lv_from_flavor, lv_to_flavor))) {
  1040. return WQ_RPL_REPLY; // LCOV_EXCL_LINE
  1041. }
  1042. char *consensus_diff;
  1043. {
  1044. char *diff_from_nt = NULL, *diff_to_nt = NULL;
  1045. size_t diff_from_nt_len, diff_to_nt_len;
  1046. if (uncompress_or_copy(&diff_from_nt, &diff_from_nt_len,
  1047. job->diff_from) < 0) {
  1048. return WQ_RPL_REPLY;
  1049. }
  1050. if (uncompress_or_copy(&diff_to_nt, &diff_to_nt_len,
  1051. job->diff_to) < 0) {
  1052. tor_free(diff_from_nt);
  1053. return WQ_RPL_REPLY;
  1054. }
  1055. tor_assert(diff_from_nt);
  1056. tor_assert(diff_to_nt);
  1057. // XXXX ugh; this is going to calculate the SHA3 of both its
  1058. // XXXX inputs again, even though we already have that. Maybe it's time
  1059. // XXXX to change the API here?
  1060. consensus_diff = consensus_diff_generate(diff_from_nt, diff_to_nt);
  1061. tor_free(diff_from_nt);
  1062. tor_free(diff_to_nt);
  1063. }
  1064. if (!consensus_diff) {
  1065. /* Couldn't generate consensus; we'll leave the reply blank. */
  1066. return WQ_RPL_REPLY;
  1067. }
  1068. /* Compress the results and send the reply */
  1069. tor_assert(compress_diffs_with[0] == NO_METHOD);
  1070. size_t difflen = strlen(consensus_diff);
  1071. job->out[0].body = (uint8_t *) consensus_diff;
  1072. job->out[0].bodylen = difflen;
  1073. config_line_t *common_labels = NULL;
  1074. cdm_labels_prepend_sha3(&common_labels,
  1075. LABEL_SHA3_DIGEST_UNCOMPRESSED,
  1076. job->out[0].body,
  1077. job->out[0].bodylen);
  1078. config_line_prepend(&common_labels, LABEL_FROM_VALID_AFTER,
  1079. lv_from_valid_after);
  1080. config_line_prepend(&common_labels, LABEL_VALID_AFTER,
  1081. lv_to_valid_after);
  1082. config_line_prepend(&common_labels, LABEL_FLAVOR, lv_from_flavor);
  1083. config_line_prepend(&common_labels, LABEL_FROM_SHA3_DIGEST,
  1084. lv_from_digest);
  1085. config_line_prepend(&common_labels, LABEL_TARGET_SHA3_DIGEST,
  1086. lv_to_digest);
  1087. config_line_prepend(&common_labels, LABEL_DOCTYPE,
  1088. DOCTYPE_CONSENSUS_DIFF);
  1089. job->out[0].labels = config_lines_dup(common_labels);
  1090. cdm_labels_prepend_sha3(&job->out[0].labels,
  1091. LABEL_SHA3_DIGEST,
  1092. job->out[0].body,
  1093. job->out[0].bodylen);
  1094. unsigned u;
  1095. for (u = 1; u < n_diff_compression_methods(); ++u) {
  1096. compress_method_t method = compress_diffs_with[u];
  1097. const char *methodname = compression_method_get_name(method);
  1098. char *result;
  1099. size_t sz;
  1100. if (0 == tor_compress(&result, &sz, consensus_diff, difflen, method)) {
  1101. job->out[u].body = (uint8_t*)result;
  1102. job->out[u].bodylen = sz;
  1103. job->out[u].labels = config_lines_dup(common_labels);
  1104. cdm_labels_prepend_sha3(&job->out[u].labels, LABEL_SHA3_DIGEST,
  1105. job->out[u].body,
  1106. job->out[u].bodylen);
  1107. config_line_prepend(&job->out[u].labels,
  1108. LABEL_COMPRESSION_TYPE,
  1109. methodname);
  1110. }
  1111. }
  1112. config_free_lines(common_labels);
  1113. return WQ_RPL_REPLY;
  1114. }
  1115. /**
  1116. * Helper: release all storage held in <b>job</b>.
  1117. */
  1118. static void
  1119. consensus_diff_worker_job_free(consensus_diff_worker_job_t *job)
  1120. {
  1121. if (!job)
  1122. return;
  1123. unsigned u;
  1124. for (u = 0; u < n_diff_compression_methods(); ++u) {
  1125. config_free_lines(job->out[u].labels);
  1126. tor_free(job->out[u].body);
  1127. }
  1128. consensus_cache_entry_decref(job->diff_from);
  1129. consensus_cache_entry_decref(job->diff_to);
  1130. tor_free(job);
  1131. }
  1132. /**
  1133. * Worker function: This function runs in the main thread, and receives
  1134. * a consensus_diff_worker_job_t that the worker thread has already
  1135. * processed.
  1136. */
  1137. static void
  1138. consensus_diff_worker_replyfn(void *work_)
  1139. {
  1140. tor_assert(in_main_thread());
  1141. tor_assert(work_);
  1142. consensus_diff_worker_job_t *job = work_;
  1143. const char *lv_from_digest =
  1144. consensus_cache_entry_get_value(job->diff_from,
  1145. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1146. const char *lv_to_digest =
  1147. consensus_cache_entry_get_value(job->diff_to,
  1148. LABEL_SHA3_DIGEST_UNCOMPRESSED);
  1149. const char *lv_flavor =
  1150. consensus_cache_entry_get_value(job->diff_to, LABEL_FLAVOR);
  1151. if (BUG(lv_from_digest == NULL))
  1152. lv_from_digest = "???"; // LCOV_EXCL_LINE
  1153. if (BUG(lv_to_digest == NULL))
  1154. lv_to_digest = "???"; // LCOV_EXCL_LINE
  1155. uint8_t from_sha3[DIGEST256_LEN];
  1156. uint8_t to_sha3[DIGEST256_LEN];
  1157. int flav = -1;
  1158. int cache = 1;
  1159. if (BUG(cdm_entry_get_sha3_value(from_sha3, job->diff_from,
  1160. LABEL_SHA3_DIGEST_UNCOMPRESSED) < 0))
  1161. cache = 0;
  1162. if (BUG(cdm_entry_get_sha3_value(to_sha3, job->diff_to,
  1163. LABEL_SHA3_DIGEST_UNCOMPRESSED) < 0))
  1164. cache = 0;
  1165. if (BUG(lv_flavor == NULL)) {
  1166. cache = 0;
  1167. } else if ((flav = networkstatus_parse_flavor_name(lv_flavor)) < 0) {
  1168. cache = 0;
  1169. }
  1170. int status = CDM_DIFF_ERROR;
  1171. consensus_cache_entry_handle_t *handles[ARRAY_LENGTH(compress_diffs_with)];
  1172. memset(handles, 0, sizeof(handles));
  1173. consdiffmgr_ensure_space_for_files(n_diff_compression_methods());
  1174. unsigned u;
  1175. for (u = 0; u < n_diff_compression_methods(); ++u) {
  1176. compress_method_t method = compress_diffs_with[u];
  1177. uint8_t *body_out = job->out[u].body;
  1178. size_t bodylen_out = job->out[u].bodylen;
  1179. config_line_t *labels = job->out[u].labels;
  1180. const char *methodname = compression_method_get_name(method);
  1181. if (body_out && bodylen_out && labels) {
  1182. /* Success! Store the results */
  1183. log_info(LD_DIRSERV, "Adding consensus diff from %s to %s, "
  1184. "compressed with %s",
  1185. lv_from_digest, lv_to_digest, methodname);
  1186. consensus_cache_entry_t *ent =
  1187. consensus_cache_add(cdm_cache_get(),
  1188. labels,
  1189. body_out,
  1190. bodylen_out);
  1191. status = CDM_DIFF_PRESENT;
  1192. handles[u] = consensus_cache_entry_handle_new(ent);
  1193. consensus_cache_entry_decref(ent);
  1194. }
  1195. }
  1196. if (status != CDM_DIFF_PRESENT) {
  1197. /* Failure! Nothing to do but complain */
  1198. log_warn(LD_DIRSERV,
  1199. "Worker was unable to compute consensus diff "
  1200. "from %s to %s", lv_from_digest, lv_to_digest);
  1201. /* Cache this error so we don't try to compute this one again. */
  1202. status = CDM_DIFF_ERROR;
  1203. }
  1204. for (u = 0; u < ARRAY_LENGTH(handles); ++u) {
  1205. compress_method_t method = compress_diffs_with[u];
  1206. if (cache) {
  1207. cdm_diff_ht_set_status(flav, from_sha3, to_sha3, method, status,
  1208. handles[u]);
  1209. } else {
  1210. consensus_cache_entry_handle_free(handles[u]);
  1211. }
  1212. }
  1213. consensus_diff_worker_job_free(job);
  1214. }
  1215. /**
  1216. * Queue the job of computing the diff from <b>diff_from</b> to <b>diff_to</b>
  1217. * in a worker thread.
  1218. */
  1219. static int
  1220. consensus_diff_queue_diff_work(consensus_cache_entry_t *diff_from,
  1221. consensus_cache_entry_t *diff_to)
  1222. {
  1223. tor_assert(in_main_thread());
  1224. consensus_cache_entry_incref(diff_from);
  1225. consensus_cache_entry_incref(diff_to);
  1226. consensus_diff_worker_job_t *job = tor_malloc_zero(sizeof(*job));
  1227. job->diff_from = diff_from;
  1228. job->diff_to = diff_to;
  1229. /* Make sure body is mapped. */
  1230. const uint8_t *body;
  1231. size_t bodylen;
  1232. int r1 = consensus_cache_entry_get_body(diff_from, &body, &bodylen);
  1233. int r2 = consensus_cache_entry_get_body(diff_to, &body, &bodylen);
  1234. if (r1 < 0 || r2 < 0)
  1235. goto err;
  1236. workqueue_entry_t *work;
  1237. work = cpuworker_queue_work(consensus_diff_worker_threadfn,
  1238. consensus_diff_worker_replyfn,
  1239. job);
  1240. if (!work)
  1241. goto err;
  1242. return 0;
  1243. err:
  1244. consensus_diff_worker_job_free(job); // includes decrefs.
  1245. return -1;
  1246. }