consdiffmgr.c 60 KB

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