consdiffmgr.c 65 KB

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