consdiffmgr.c 48 KB

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