consdiffmgr.c 64 KB

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