consdiffmgr.c 62 KB

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