consdiffmgr.c 47 KB

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