consdiffmgr.c 51 KB

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