consdiffmgr.c 62 KB

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