Logs and debug info that I used for finding bug 16844
[tor.git] / src / or / dirvote.c
blobd8e6ee2229045f202ccd025b9c7b384b53d2cd00
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2015, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRVOTE_PRIVATE
7 #include "or.h"
8 #include "config.h"
9 #include "dircollate.h"
10 #include "directory.h"
11 #include "dirserv.h"
12 #include "dirvote.h"
13 #include "microdesc.h"
14 #include "networkstatus.h"
15 #include "policies.h"
16 #include "rephist.h"
17 #include "router.h"
18 #include "routerlist.h"
19 #include "routerparse.h"
20 #include "entrynodes.h" /* needed for guardfraction methods */
21 #include "torcert.h"
23 /**
24 * \file dirvote.c
25 * \brief Functions to compute directory consensus, and schedule voting.
26 **/
28 /** A consensus that we have built and are appending signatures to. Once it's
29 * time to publish it, it will become an active consensus if it accumulates
30 * enough signatures. */
31 typedef struct pending_consensus_t {
32 /** The body of the consensus that we're currently building. Once we
33 * have it built, it goes into dirserv.c */
34 char *body;
35 /** The parsed in-progress consensus document. */
36 networkstatus_t *consensus;
37 } pending_consensus_t;
39 /* DOCDOC dirvote_add_signatures_to_all_pending_consensuses */
40 static int dirvote_add_signatures_to_all_pending_consensuses(
41 const char *detached_signatures_body,
42 const char *source,
43 const char **msg_out);
44 static int dirvote_add_signatures_to_pending_consensus(
45 pending_consensus_t *pc,
46 ns_detached_signatures_t *sigs,
47 const char *source,
48 int severity,
49 const char **msg_out);
50 static char *list_v3_auth_ids(void);
51 static void dirvote_fetch_missing_votes(void);
52 static void dirvote_fetch_missing_signatures(void);
53 static int dirvote_perform_vote(void);
54 static void dirvote_clear_votes(int all_votes);
55 static int dirvote_compute_consensuses(void);
56 static int dirvote_publish_consensus(void);
57 static char *make_consensus_method_list(int low, int high, const char *sep);
59 /* =====
60 * Voting
61 * =====*/
63 /** Return a new string containing the string representation of the vote in
64 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
65 * For v3 authorities. */
66 STATIC char *
67 format_networkstatus_vote(crypto_pk_t *private_signing_key,
68 networkstatus_t *v3_ns)
70 smartlist_t *chunks = smartlist_new();
71 const char *client_versions = NULL, *server_versions = NULL;
72 char *packages = NULL;
73 char fingerprint[FINGERPRINT_LEN+1];
74 char digest[DIGEST_LEN];
75 uint32_t addr;
76 char *client_versions_line = NULL, *server_versions_line = NULL;
77 networkstatus_voter_info_t *voter;
78 char *status = NULL;
80 tor_assert(private_signing_key);
81 tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
83 voter = smartlist_get(v3_ns->voters, 0);
85 addr = voter->addr;
87 base16_encode(fingerprint, sizeof(fingerprint),
88 v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
89 client_versions = v3_ns->client_versions;
90 server_versions = v3_ns->server_versions;
92 if (client_versions) {
93 tor_asprintf(&client_versions_line, "client-versions %s\n",
94 client_versions);
95 } else {
96 client_versions_line = tor_strdup("");
98 if (server_versions) {
99 tor_asprintf(&server_versions_line, "server-versions %s\n",
100 server_versions);
101 } else {
102 server_versions_line = tor_strdup("");
105 if (v3_ns->package_lines) {
106 smartlist_t *tmp = smartlist_new();
107 SMARTLIST_FOREACH(v3_ns->package_lines, const char *, p,
108 if (validate_recommended_package_line(p))
109 smartlist_add_asprintf(tmp, "package %s\n", p));
110 packages = smartlist_join_strings(tmp, "", 0, NULL);
111 SMARTLIST_FOREACH(tmp, char *, cp, tor_free(cp));
112 smartlist_free(tmp);
113 } else {
114 packages = tor_strdup("");
118 char published[ISO_TIME_LEN+1];
119 char va[ISO_TIME_LEN+1];
120 char fu[ISO_TIME_LEN+1];
121 char vu[ISO_TIME_LEN+1];
122 char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
123 /* XXXX Abstraction violation: should be pulling a field out of v3_ns.*/
124 char *flag_thresholds = dirserv_get_flag_thresholds_line();
125 char *params;
126 authority_cert_t *cert = v3_ns->cert;
127 char *methods =
128 make_consensus_method_list(MIN_SUPPORTED_CONSENSUS_METHOD,
129 MAX_SUPPORTED_CONSENSUS_METHOD, " ");
130 format_iso_time(published, v3_ns->published);
131 format_iso_time(va, v3_ns->valid_after);
132 format_iso_time(fu, v3_ns->fresh_until);
133 format_iso_time(vu, v3_ns->valid_until);
135 if (v3_ns->net_params)
136 params = smartlist_join_strings(v3_ns->net_params, " ", 0, NULL);
137 else
138 params = tor_strdup("");
140 tor_assert(cert);
141 smartlist_add_asprintf(chunks,
142 "network-status-version 3\n"
143 "vote-status %s\n"
144 "consensus-methods %s\n"
145 "published %s\n"
146 "valid-after %s\n"
147 "fresh-until %s\n"
148 "valid-until %s\n"
149 "voting-delay %d %d\n"
150 "%s%s" /* versions */
151 "%s" /* packages */
152 "known-flags %s\n"
153 "flag-thresholds %s\n"
154 "params %s\n"
155 "dir-source %s %s %s %s %d %d\n"
156 "contact %s\n",
157 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
158 methods,
159 published, va, fu, vu,
160 v3_ns->vote_seconds, v3_ns->dist_seconds,
161 client_versions_line,
162 server_versions_line,
163 packages,
164 flags,
165 flag_thresholds,
166 params,
167 voter->nickname, fingerprint, voter->address,
168 fmt_addr32(addr), voter->dir_port, voter->or_port,
169 voter->contact);
171 tor_free(params);
172 tor_free(flags);
173 tor_free(flag_thresholds);
174 tor_free(methods);
176 if (!tor_digest_is_zero(voter->legacy_id_digest)) {
177 char fpbuf[HEX_DIGEST_LEN+1];
178 base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
179 smartlist_add_asprintf(chunks, "legacy-dir-key %s\n", fpbuf);
182 smartlist_add(chunks, tor_strndup(cert->cache_info.signed_descriptor_body,
183 cert->cache_info.signed_descriptor_len));
186 SMARTLIST_FOREACH_BEGIN(v3_ns->routerstatus_list, vote_routerstatus_t *,
187 vrs) {
188 char *rsf;
189 vote_microdesc_hash_t *h;
190 rsf = routerstatus_format_entry(&vrs->status,
191 vrs->version, NS_V3_VOTE, vrs);
192 if (rsf)
193 smartlist_add(chunks, rsf);
195 for (h = vrs->microdesc; h; h = h->next) {
196 smartlist_add(chunks, tor_strdup(h->microdesc_hash_line));
198 } SMARTLIST_FOREACH_END(vrs);
200 smartlist_add(chunks, tor_strdup("directory-footer\n"));
202 /* The digest includes everything up through the space after
203 * directory-signature. (Yuck.) */
204 crypto_digest_smartlist(digest, DIGEST_LEN, chunks,
205 "directory-signature ", DIGEST_SHA1);
208 char signing_key_fingerprint[FINGERPRINT_LEN+1];
209 if (crypto_pk_get_fingerprint(private_signing_key,
210 signing_key_fingerprint, 0)<0) {
211 log_warn(LD_BUG, "Unable to get fingerprint for signing key");
212 goto err;
215 smartlist_add_asprintf(chunks, "directory-signature %s %s\n", fingerprint,
216 signing_key_fingerprint);
219 note_crypto_pk_op(SIGN_DIR);
221 char *sig = router_get_dirobj_signature(digest, DIGEST_LEN,
222 private_signing_key);
223 if (!sig) {
224 log_warn(LD_BUG, "Unable to sign networkstatus vote.");
225 goto err;
227 smartlist_add(chunks, sig);
230 status = smartlist_join_strings(chunks, "", 0, NULL);
233 networkstatus_t *v;
234 if (!(v = networkstatus_parse_vote_from_string(status, NULL,
235 v3_ns->type))) {
236 log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
237 "<<%s>>",
238 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
239 goto err;
241 networkstatus_vote_free(v);
244 goto done;
246 err:
247 tor_free(status);
248 done:
249 tor_free(client_versions_line);
250 tor_free(server_versions_line);
251 tor_free(packages);
253 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
254 smartlist_free(chunks);
255 return status;
258 /* =====
259 * Consensus generation
260 * ===== */
262 /** Given a vote <b>vote</b> (not a consensus!), return its associated
263 * networkstatus_voter_info_t. */
264 static networkstatus_voter_info_t *
265 get_voter(const networkstatus_t *vote)
267 tor_assert(vote);
268 tor_assert(vote->type == NS_TYPE_VOTE);
269 tor_assert(vote->voters);
270 tor_assert(smartlist_len(vote->voters) == 1);
271 return smartlist_get(vote->voters, 0);
274 /** Return the signature made by <b>voter</b> using the algorithm
275 * <b>alg</b>, or NULL if none is found. */
276 document_signature_t *
277 voter_get_sig_by_algorithm(const networkstatus_voter_info_t *voter,
278 digest_algorithm_t alg)
280 if (!voter->sigs)
281 return NULL;
282 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
283 if (sig->alg == alg)
284 return sig);
285 return NULL;
288 /** Temporary structure used in constructing a list of dir-source entries
289 * for a consensus. One of these is generated for every vote, and one more
290 * for every legacy key in each vote. */
291 typedef struct dir_src_ent_t {
292 networkstatus_t *v;
293 const char *digest;
294 int is_legacy;
295 } dir_src_ent_t;
297 /** Helper for sorting networkstatus_t votes (not consensuses) by the
298 * hash of their voters' identity digests. */
299 static int
300 compare_votes_by_authority_id_(const void **_a, const void **_b)
302 const networkstatus_t *a = *_a, *b = *_b;
303 return fast_memcmp(get_voter(a)->identity_digest,
304 get_voter(b)->identity_digest, DIGEST_LEN);
307 /** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
308 * their identity digests, and return -1, 0, or 1 depending on their
309 * ordering */
310 static int
311 compare_dir_src_ents_by_authority_id_(const void **_a, const void **_b)
313 const dir_src_ent_t *a = *_a, *b = *_b;
314 const networkstatus_voter_info_t *a_v = get_voter(a->v),
315 *b_v = get_voter(b->v);
316 const char *a_id, *b_id;
317 a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
318 b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;
320 return fast_memcmp(a_id, b_id, DIGEST_LEN);
323 /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
324 * that occurs more than <b>min</b> times. */
325 static void
326 get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
328 char *cur = NULL;
329 int count = 0;
330 SMARTLIST_FOREACH_BEGIN(in, char *, cp) {
331 if (cur && !strcmp(cp, cur)) {
332 ++count;
333 } else {
334 if (count > min)
335 smartlist_add(out, cur);
336 cur = cp;
337 count = 1;
339 } SMARTLIST_FOREACH_END(cp);
340 if (count > min)
341 smartlist_add(out, cur);
344 /** Given a sorted list of strings <b>lst</b>, return the member that appears
345 * most. Break ties in favor of later-occurring members. */
346 #define get_most_frequent_member(lst) \
347 smartlist_get_most_frequent_string(lst)
349 /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
350 * that come from the same routerinfo, with the same derived elements.
352 static int
353 compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
355 int r;
356 tor_assert(a);
357 tor_assert(b);
359 if ((r = fast_memcmp(a->status.identity_digest, b->status.identity_digest,
360 DIGEST_LEN)))
361 return r;
362 if ((r = fast_memcmp(a->status.descriptor_digest,
363 b->status.descriptor_digest,
364 DIGEST_LEN)))
365 return r;
366 if ((r = (int)(b->status.published_on - a->status.published_on)))
367 return r;
368 if ((r = strcmp(b->status.nickname, a->status.nickname)))
369 return r;
370 if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
371 return r;
372 if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
373 return r;
374 if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
375 return r;
376 return 0;
379 /** Helper for sorting routerlists based on compare_vote_rs. */
380 static int
381 compare_vote_rs_(const void **_a, const void **_b)
383 const vote_routerstatus_t *a = *_a, *b = *_b;
384 return compare_vote_rs(a,b);
387 /** Helper for sorting OR ports. */
388 static int
389 compare_orports_(const void **_a, const void **_b)
391 const tor_addr_port_t *a = *_a, *b = *_b;
392 int r;
394 if ((r = tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
395 return r;
396 if ((r = (((int) b->port) - ((int) a->port))))
397 return r;
399 return 0;
402 /** Given a list of vote_routerstatus_t, all for the same router identity,
403 * return whichever is most frequent, breaking ties in favor of more
404 * recently published vote_routerstatus_t and in case of ties there,
405 * in favor of smaller descriptor digest.
407 static vote_routerstatus_t *
408 compute_routerstatus_consensus(smartlist_t *votes, int consensus_method,
409 char *microdesc_digest256_out,
410 tor_addr_port_t *best_alt_orport_out)
412 vote_routerstatus_t *most = NULL, *cur = NULL;
413 int most_n = 0, cur_n = 0;
414 time_t most_published = 0;
416 /* compare_vote_rs_() sorts the items by identity digest (all the same),
417 * then by SD digest. That way, if we have a tie that the published_on
418 * date cannot tie, we use the descriptor with the smaller digest.
420 smartlist_sort(votes, compare_vote_rs_);
421 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
422 if (cur && !compare_vote_rs(cur, rs)) {
423 ++cur_n;
424 } else {
425 if (cur && (cur_n > most_n ||
426 (cur_n == most_n &&
427 cur->status.published_on > most_published))) {
428 most = cur;
429 most_n = cur_n;
430 most_published = cur->status.published_on;
432 cur_n = 1;
433 cur = rs;
435 } SMARTLIST_FOREACH_END(rs);
437 if (cur_n > most_n ||
438 (cur && cur_n == most_n && cur->status.published_on > most_published)) {
439 most = cur;
440 most_n = cur_n;
441 most_published = cur->status.published_on;
444 tor_assert(most);
446 /* If we're producing "a" lines, vote on potential alternative (sets
447 * of) OR port(s) in the winning routerstatuses.
449 * XXX prop186 There's at most one alternative OR port (_the_ IPv6
450 * port) for now. */
451 if (consensus_method >= MIN_METHOD_FOR_A_LINES && best_alt_orport_out) {
452 smartlist_t *alt_orports = smartlist_new();
453 const tor_addr_port_t *most_alt_orport = NULL;
455 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
456 tor_assert(rs);
457 if (compare_vote_rs(most, rs) == 0 &&
458 !tor_addr_is_null(&rs->status.ipv6_addr)
459 && rs->status.ipv6_orport) {
460 smartlist_add(alt_orports, tor_addr_port_new(&rs->status.ipv6_addr,
461 rs->status.ipv6_orport));
463 } SMARTLIST_FOREACH_END(rs);
465 smartlist_sort(alt_orports, compare_orports_);
466 most_alt_orport = smartlist_get_most_frequent(alt_orports,
467 compare_orports_);
468 if (most_alt_orport) {
469 memcpy(best_alt_orport_out, most_alt_orport, sizeof(tor_addr_port_t));
470 log_debug(LD_DIR, "\"a\" line winner for %s is %s",
471 most->status.nickname,
472 fmt_addrport(&most_alt_orport->addr, most_alt_orport->port));
475 SMARTLIST_FOREACH(alt_orports, tor_addr_port_t *, ap, tor_free(ap));
476 smartlist_free(alt_orports);
479 if (microdesc_digest256_out) {
480 smartlist_t *digests = smartlist_new();
481 const uint8_t *best_microdesc_digest;
482 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
483 char d[DIGEST256_LEN];
484 if (compare_vote_rs(rs, most))
485 continue;
486 if (!vote_routerstatus_find_microdesc_hash(d, rs, consensus_method,
487 DIGEST_SHA256))
488 smartlist_add(digests, tor_memdup(d, sizeof(d)));
489 } SMARTLIST_FOREACH_END(rs);
490 smartlist_sort_digests256(digests);
491 best_microdesc_digest = smartlist_get_most_frequent_digest256(digests);
492 if (best_microdesc_digest)
493 memcpy(microdesc_digest256_out, best_microdesc_digest, DIGEST256_LEN);
494 SMARTLIST_FOREACH(digests, char *, cp, tor_free(cp));
495 smartlist_free(digests);
498 return most;
501 /** Sorting helper: compare two strings based on their values as base-ten
502 * positive integers. (Non-integers are treated as prior to all integers, and
503 * compared lexically.) */
504 static int
505 cmp_int_strings_(const void **_a, const void **_b)
507 const char *a = *_a, *b = *_b;
508 int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
509 int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
510 if (ai<bi) {
511 return -1;
512 } else if (ai==bi) {
513 if (ai == 0) /* Parsing failed. */
514 return strcmp(a, b);
515 return 0;
516 } else {
517 return 1;
521 /** Given a list of networkstatus_t votes, determine and return the number of
522 * the highest consensus method that is supported by 2/3 of the voters. */
523 static int
524 compute_consensus_method(smartlist_t *votes)
526 smartlist_t *all_methods = smartlist_new();
527 smartlist_t *acceptable_methods = smartlist_new();
528 smartlist_t *tmp = smartlist_new();
529 int min = (smartlist_len(votes) * 2) / 3;
530 int n_ok;
531 int result;
532 SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
534 tor_assert(vote->supported_methods);
535 smartlist_add_all(tmp, vote->supported_methods);
536 smartlist_sort(tmp, cmp_int_strings_);
537 smartlist_uniq(tmp, cmp_int_strings_, NULL);
538 smartlist_add_all(all_methods, tmp);
539 smartlist_clear(tmp);
542 smartlist_sort(all_methods, cmp_int_strings_);
543 get_frequent_members(acceptable_methods, all_methods, min);
544 n_ok = smartlist_len(acceptable_methods);
545 if (n_ok) {
546 const char *best = smartlist_get(acceptable_methods, n_ok-1);
547 result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
548 } else {
549 result = 1;
551 smartlist_free(tmp);
552 smartlist_free(all_methods);
553 smartlist_free(acceptable_methods);
554 return result;
557 /** Return true iff <b>method</b> is a consensus method that we support. */
558 static int
559 consensus_method_is_supported(int method)
561 return (method >= MIN_SUPPORTED_CONSENSUS_METHOD) &&
562 (method <= MAX_SUPPORTED_CONSENSUS_METHOD);
565 /** Return a newly allocated string holding the numbers between low and high
566 * (inclusive) that are supported consensus methods. */
567 static char *
568 make_consensus_method_list(int low, int high, const char *separator)
570 char *list;
572 int i;
573 smartlist_t *lst;
574 lst = smartlist_new();
575 for (i = low; i <= high; ++i) {
576 if (!consensus_method_is_supported(i))
577 continue;
578 smartlist_add_asprintf(lst, "%d", i);
580 list = smartlist_join_strings(lst, separator, 0, NULL);
581 tor_assert(list);
582 SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
583 smartlist_free(lst);
584 return list;
587 /** Helper: given <b>lst</b>, a list of version strings such that every
588 * version appears once for every versioning voter who recommends it, return a
589 * newly allocated string holding the resulting client-versions or
590 * server-versions list. May change contents of <b>lst</b> */
591 static char *
592 compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
594 int min = n_versioning / 2;
595 smartlist_t *good = smartlist_new();
596 char *result;
597 sort_version_list(lst, 0);
598 get_frequent_members(good, lst, min);
599 result = smartlist_join_strings(good, ",", 0, NULL);
600 smartlist_free(good);
601 return result;
604 /** Minimum number of directory authorities voting for a parameter to
605 * include it in the consensus, if consensus method 12 or later is to be
606 * used. See proposal 178 for details. */
607 #define MIN_VOTES_FOR_PARAM 3
609 /** Helper: given a list of valid networkstatus_t, return a new string
610 * containing the contents of the consensus network parameter set.
612 STATIC char *
613 dirvote_compute_params(smartlist_t *votes, int method, int total_authorities)
615 int i;
616 int32_t *vals;
618 int cur_param_len;
619 const char *cur_param;
620 const char *eq;
621 char *result;
623 const int n_votes = smartlist_len(votes);
624 smartlist_t *output;
625 smartlist_t *param_list = smartlist_new();
626 (void) method;
628 /* We require that the parameter lists in the votes are well-formed: that
629 is, that their keywords are unique and sorted, and that their values are
630 between INT32_MIN and INT32_MAX inclusive. This should be guaranteed by
631 the parsing code. */
633 vals = tor_calloc(n_votes, sizeof(int));
635 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
636 if (!v->net_params)
637 continue;
638 smartlist_add_all(param_list, v->net_params);
639 } SMARTLIST_FOREACH_END(v);
641 if (smartlist_len(param_list) == 0) {
642 tor_free(vals);
643 smartlist_free(param_list);
644 return NULL;
647 smartlist_sort_strings(param_list);
648 i = 0;
649 cur_param = smartlist_get(param_list, 0);
650 eq = strchr(cur_param, '=');
651 tor_assert(eq);
652 cur_param_len = (int)(eq+1 - cur_param);
654 output = smartlist_new();
656 SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
657 const char *next_param;
658 int ok=0;
659 eq = strchr(param, '=');
660 tor_assert(i<n_votes); /* Make sure we prevented vote-stuffing. */
661 vals[i++] = (int32_t)
662 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
663 tor_assert(ok); /* Already checked these when parsing. */
665 if (param_sl_idx+1 == smartlist_len(param_list))
666 next_param = NULL;
667 else
668 next_param = smartlist_get(param_list, param_sl_idx+1);
669 /* resolve spurious clang shallow analysis null pointer errors */
670 tor_assert(param);
671 if (!next_param || strncmp(next_param, param, cur_param_len)) {
672 /* We've reached the end of a series. */
673 /* Make sure enough authorities voted on this param, unless the
674 * the consensus method we use is too old for that. */
675 if (i > total_authorities/2 ||
676 i >= MIN_VOTES_FOR_PARAM) {
677 int32_t median = median_int32(vals, i);
678 char *out_string = tor_malloc(64+cur_param_len);
679 memcpy(out_string, param, cur_param_len);
680 tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
681 smartlist_add(output, out_string);
684 i = 0;
685 if (next_param) {
686 eq = strchr(next_param, '=');
687 cur_param_len = (int)(eq+1 - next_param);
690 } SMARTLIST_FOREACH_END(param);
692 result = smartlist_join_strings(output, " ", 0, NULL);
693 SMARTLIST_FOREACH(output, char *, cp, tor_free(cp));
694 smartlist_free(output);
695 smartlist_free(param_list);
696 tor_free(vals);
697 return result;
700 #define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
701 ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
702 (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
703 (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
704 (g) >= 0 && (g) <= (mx))
706 #define CHECK_EQ(a, b, margin) \
707 ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))
709 typedef enum {
710 BW_WEIGHTS_NO_ERROR = 0,
711 BW_WEIGHTS_RANGE_ERROR = 1,
712 BW_WEIGHTS_SUMG_ERROR = 2,
713 BW_WEIGHTS_SUME_ERROR = 3,
714 BW_WEIGHTS_SUMD_ERROR = 4,
715 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
716 BW_WEIGHTS_BALANCE_EG_ERROR = 6
717 } bw_weights_error_t;
720 * Verify that any weightings satisfy the balanced formulas.
722 static bw_weights_error_t
723 networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
724 int64_t Wme, int64_t Wmd, int64_t Wee,
725 int64_t Wed, int64_t scale, int64_t G,
726 int64_t M, int64_t E, int64_t D, int64_t T,
727 int64_t margin, int do_balance) {
728 bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;
730 // Wed + Wmd + Wgd == 1
731 if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
732 berr = BW_WEIGHTS_SUMD_ERROR;
733 goto out;
736 // Wmg + Wgg == 1
737 if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
738 berr = BW_WEIGHTS_SUMG_ERROR;
739 goto out;
742 // Wme + Wee == 1
743 if (!CHECK_EQ(Wme + Wee, scale, margin)) {
744 berr = BW_WEIGHTS_SUME_ERROR;
745 goto out;
748 // Verify weights within range 0->1
749 if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
750 berr = BW_WEIGHTS_RANGE_ERROR;
751 goto out;
754 if (do_balance) {
755 // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
756 if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
757 berr = BW_WEIGHTS_BALANCE_EG_ERROR;
758 goto out;
761 // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
762 if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
763 (margin*T)/3)) {
764 berr = BW_WEIGHTS_BALANCE_MID_ERROR;
765 goto out;
769 out:
770 if (berr) {
771 log_info(LD_DIR,
772 "Bw weight mismatch %d. G="I64_FORMAT" M="I64_FORMAT
773 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
774 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
775 " Wgd=%d Wgg=%d Wme=%d Wmg=%d",
776 berr,
777 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
778 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
779 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
780 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg);
783 return berr;
787 * This function computes the bandwidth weights for consensus method 10.
789 * It returns true if weights could be computed, false otherwise.
791 static int
792 networkstatus_compute_bw_weights_v10(smartlist_t *chunks, int64_t G,
793 int64_t M, int64_t E, int64_t D,
794 int64_t T, int64_t weight_scale)
796 bw_weights_error_t berr = 0;
797 int64_t Wgg = -1, Wgd = -1;
798 int64_t Wmg = -1, Wme = -1, Wmd = -1;
799 int64_t Wed = -1, Wee = -1;
800 const char *casename;
802 if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
803 log_warn(LD_DIR, "Consensus with empty bandwidth: "
804 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
805 " D="I64_FORMAT" T="I64_FORMAT,
806 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
807 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
808 return 0;
812 * Computed from cases in 3.4.3 of dir-spec.txt
814 * 1. Neither are scarce
815 * 2. Both Guard and Exit are scarce
816 * a. R+D <= S
817 * b. R+D > S
818 * 3. One of Guard or Exit is scarce
819 * a. S+D < T/3
820 * b. S+D >= T/3
822 if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
823 /* Case 1: Neither are scarce. */
824 casename = "Case 1 (Wgd=Wmd=Wed)";
825 Wgd = weight_scale/3;
826 Wed = weight_scale/3;
827 Wmd = weight_scale/3;
828 Wee = (weight_scale*(E+G+M))/(3*E);
829 Wme = weight_scale - Wee;
830 Wmg = (weight_scale*(2*G-E-M))/(3*G);
831 Wgg = weight_scale - Wmg;
833 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
834 weight_scale, G, M, E, D, T, 10, 1);
836 if (berr) {
837 log_warn(LD_DIR,
838 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
839 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
840 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
841 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
842 berr, casename,
843 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
844 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
845 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
846 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
847 return 0;
849 } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
850 int64_t R = MIN(E, G);
851 int64_t S = MAX(E, G);
853 * Case 2: Both Guards and Exits are scarce
854 * Balance D between E and G, depending upon
855 * D capacity and scarcity.
857 if (R+D < S) { // Subcase a
858 Wgg = weight_scale;
859 Wee = weight_scale;
860 Wmg = 0;
861 Wme = 0;
862 Wmd = 0;
863 if (E < G) {
864 casename = "Case 2a (E scarce)";
865 Wed = weight_scale;
866 Wgd = 0;
867 } else { /* E >= G */
868 casename = "Case 2a (G scarce)";
869 Wed = 0;
870 Wgd = weight_scale;
872 } else { // Subcase b: R+D >= S
873 casename = "Case 2b1 (Wgg=1, Wmd=Wgd)";
874 Wee = (weight_scale*(E - G + M))/E;
875 Wed = (weight_scale*(D - 2*E + 4*G - 2*M))/(3*D);
876 Wme = (weight_scale*(G-M))/E;
877 Wmg = 0;
878 Wgg = weight_scale;
879 Wmd = (weight_scale - Wed)/2;
880 Wgd = (weight_scale - Wed)/2;
882 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
883 weight_scale, G, M, E, D, T, 10, 1);
885 if (berr) {
886 casename = "Case 2b2 (Wgg=1, Wee=1)";
887 Wgg = weight_scale;
888 Wee = weight_scale;
889 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
890 Wmd = (weight_scale*(D - 2*M + G + E))/(3*D);
891 Wme = 0;
892 Wmg = 0;
894 if (Wmd < 0) { // Can happen if M > T/3
895 casename = "Case 2b3 (Wmd=0)";
896 Wmd = 0;
897 log_warn(LD_DIR,
898 "Too much Middle bandwidth on the network to calculate "
899 "balanced bandwidth-weights. Consider increasing the "
900 "number of Guard nodes by lowering the requirements.");
902 Wgd = weight_scale - Wed - Wmd;
903 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
904 Wed, weight_scale, G, M, E, D, T, 10, 1);
906 if (berr != BW_WEIGHTS_NO_ERROR &&
907 berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
908 log_warn(LD_DIR,
909 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
910 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
911 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
912 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
913 berr, casename,
914 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
915 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
916 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
917 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
918 return 0;
921 } else { // if (E < T/3 || G < T/3) {
922 int64_t S = MIN(E, G);
923 // Case 3: Exactly one of Guard or Exit is scarce
924 if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
925 log_warn(LD_BUG,
926 "Bw-Weights Case 3 v10 but with G="I64_FORMAT" M="
927 I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
928 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
929 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
932 if (3*(S+D) < T) { // Subcase a: S+D < T/3
933 if (G < E) {
934 casename = "Case 3a (G scarce)";
935 Wgg = Wgd = weight_scale;
936 Wmd = Wed = Wmg = 0;
937 // Minor subcase, if E is more scarce than M,
938 // keep its bandwidth in place.
939 if (E < M) Wme = 0;
940 else Wme = (weight_scale*(E-M))/(2*E);
941 Wee = weight_scale-Wme;
942 } else { // G >= E
943 casename = "Case 3a (E scarce)";
944 Wee = Wed = weight_scale;
945 Wmd = Wgd = Wme = 0;
946 // Minor subcase, if G is more scarce than M,
947 // keep its bandwidth in place.
948 if (G < M) Wmg = 0;
949 else Wmg = (weight_scale*(G-M))/(2*G);
950 Wgg = weight_scale-Wmg;
952 } else { // Subcase b: S+D >= T/3
953 // D != 0 because S+D >= T/3
954 if (G < E) {
955 casename = "Case 3bg (G scarce, Wgg=1, Wmd == Wed)";
956 Wgg = weight_scale;
957 Wgd = (weight_scale*(D - 2*G + E + M))/(3*D);
958 Wmg = 0;
959 Wee = (weight_scale*(E+M))/(2*E);
960 Wme = weight_scale - Wee;
961 Wmd = (weight_scale - Wgd)/2;
962 Wed = (weight_scale - Wgd)/2;
964 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
965 Wed, weight_scale, G, M, E, D, T, 10, 1);
966 } else { // G >= E
967 casename = "Case 3be (E scarce, Wee=1, Wmd == Wgd)";
968 Wee = weight_scale;
969 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
970 Wme = 0;
971 Wgg = (weight_scale*(G+M))/(2*G);
972 Wmg = weight_scale - Wgg;
973 Wmd = (weight_scale - Wed)/2;
974 Wgd = (weight_scale - Wed)/2;
976 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
977 Wed, weight_scale, G, M, E, D, T, 10, 1);
979 if (berr) {
980 log_warn(LD_DIR,
981 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
982 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
983 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
984 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
985 berr, casename,
986 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
987 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
988 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
989 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
990 return 0;
995 /* We cast down the weights to 32 bit ints on the assumption that
996 * weight_scale is ~= 10000. We need to ensure a rogue authority
997 * doesn't break this assumption to rig our weights */
998 tor_assert(0 < weight_scale && weight_scale <= INT32_MAX);
1001 * Provide Wgm=Wgg, Wmm=1, Wem=Wee, Weg=Wed. May later determine
1002 * that middle nodes need different bandwidth weights for dirport traffic,
1003 * or that weird exit policies need special weight, or that bridges
1004 * need special weight.
1006 * NOTE: This list is sorted.
1008 smartlist_add_asprintf(chunks,
1009 "bandwidth-weights Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
1010 "Wdb=%d "
1011 "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
1012 "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
1013 "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
1014 (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
1015 (int)weight_scale,
1016 (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
1017 (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
1018 (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
1020 log_notice(LD_CIRC, "Computed bandwidth weights for %s with v10: "
1021 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1022 " T="I64_FORMAT,
1023 casename,
1024 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1025 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1026 return 1;
1029 /** Update total bandwidth weights (G/M/E/D/T) with the bandwidth of
1030 * the router in <b>rs</b>. */
1031 static void
1032 update_total_bandwidth_weights(const routerstatus_t *rs,
1033 int is_exit, int is_guard,
1034 int64_t *G, int64_t *M, int64_t *E, int64_t *D,
1035 int64_t *T)
1037 int default_bandwidth = rs->bandwidth_kb;
1038 int guardfraction_bandwidth = 0;
1040 if (!rs->has_bandwidth) {
1041 log_info(LD_BUG, "Missing consensus bandwidth for router %s",
1042 rs->nickname);
1043 return;
1046 /* If this routerstatus represents a guard that we have
1047 * guardfraction information on, use it to calculate its actual
1048 * bandwidth. From proposal236:
1050 * Similarly, when calculating the bandwidth-weights line as in
1051 * section 3.8.3 of dir-spec.txt, directory authorities should treat N
1052 * as if fraction F of its bandwidth has the guard flag and (1-F) does
1053 * not. So when computing the totals G,M,E,D, each relay N with guard
1054 * visibility fraction F and bandwidth B should be added as follows:
1056 * G' = G + F*B, if N does not have the exit flag
1057 * M' = M + (1-F)*B, if N does not have the exit flag
1059 * or
1061 * D' = D + F*B, if N has the exit flag
1062 * E' = E + (1-F)*B, if N has the exit flag
1064 * In this block of code, we prepare the bandwidth values by setting
1065 * the default_bandwidth to F*B and guardfraction_bandwidth to (1-F)*B.
1067 if (rs->has_guardfraction) {
1068 guardfraction_bandwidth_t guardfraction_bw;
1070 tor_assert(is_guard);
1072 guard_get_guardfraction_bandwidth(&guardfraction_bw,
1073 rs->bandwidth_kb,
1074 rs->guardfraction_percentage);
1076 default_bandwidth = guardfraction_bw.guard_bw;
1077 guardfraction_bandwidth = guardfraction_bw.non_guard_bw;
1080 /* Now calculate the total bandwidth weights with or without
1081 * guardfraction. Depending on the flags of the relay, add its
1082 * bandwidth to the appropriate weight pool. If it's a guard and
1083 * guardfraction is enabled, add its bandwidth to both pools as
1084 * indicated by the previous comment.
1086 *T += default_bandwidth;
1087 if (is_exit && is_guard) {
1089 *D += default_bandwidth;
1090 if (rs->has_guardfraction) {
1091 *E += guardfraction_bandwidth;
1094 } else if (is_exit) {
1096 *E += default_bandwidth;
1098 } else if (is_guard) {
1100 *G += default_bandwidth;
1101 if (rs->has_guardfraction) {
1102 *M += guardfraction_bandwidth;
1105 } else {
1107 *M += default_bandwidth;
1111 /** Given a list of vote networkstatus_t in <b>votes</b>, our public
1112 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
1113 * and the number of <b>total_authorities</b> that we believe exist in our
1114 * voting quorum, generate the text of a new v3 consensus vote, and return the
1115 * value in a newly allocated string.
1117 * Note: this function DOES NOT check whether the votes are from
1118 * recognized authorities. (dirvote_add_vote does that.) */
1119 char *
1120 networkstatus_compute_consensus(smartlist_t *votes,
1121 int total_authorities,
1122 crypto_pk_t *identity_key,
1123 crypto_pk_t *signing_key,
1124 const char *legacy_id_key_digest,
1125 crypto_pk_t *legacy_signing_key,
1126 consensus_flavor_t flavor)
1128 smartlist_t *chunks;
1129 char *result = NULL;
1130 int consensus_method;
1131 time_t valid_after, fresh_until, valid_until;
1132 int vote_seconds, dist_seconds;
1133 char *client_versions = NULL, *server_versions = NULL;
1134 smartlist_t *flags;
1135 const char *flavor_name;
1136 uint32_t max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1137 int64_t G=0, M=0, E=0, D=0, T=0; /* For bandwidth weights */
1138 const routerstatus_format_type_t rs_format =
1139 flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
1140 char *params = NULL;
1141 char *packages = NULL;
1142 int added_weights = 0;
1143 dircollator_t *collator = NULL;
1144 tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
1145 tor_assert(total_authorities >= smartlist_len(votes));
1146 tor_assert(total_authorities > 0);
1148 flavor_name = networkstatus_get_flavor_name(flavor);
1150 if (!smartlist_len(votes)) {
1151 log_warn(LD_DIR, "Can't compute a consensus from no votes.");
1152 return NULL;
1154 flags = smartlist_new();
1156 consensus_method = compute_consensus_method(votes);
1157 if (consensus_method_is_supported(consensus_method)) {
1158 log_info(LD_DIR, "Generating consensus using method %d.",
1159 consensus_method);
1160 } else {
1161 log_warn(LD_DIR, "The other authorities will use consensus method %d, "
1162 "which I don't support. Maybe I should upgrade!",
1163 consensus_method);
1164 consensus_method = MAX_SUPPORTED_CONSENSUS_METHOD;
1167 /* Compute medians of time-related things, and figure out how many
1168 * routers we might need to talk about. */
1170 int n_votes = smartlist_len(votes);
1171 time_t *va_times = tor_calloc(n_votes, sizeof(time_t));
1172 time_t *fu_times = tor_calloc(n_votes, sizeof(time_t));
1173 time_t *vu_times = tor_calloc(n_votes, sizeof(time_t));
1174 int *votesec_list = tor_calloc(n_votes, sizeof(int));
1175 int *distsec_list = tor_calloc(n_votes, sizeof(int));
1176 int n_versioning_clients = 0, n_versioning_servers = 0;
1177 smartlist_t *combined_client_versions = smartlist_new();
1178 smartlist_t *combined_server_versions = smartlist_new();
1180 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1181 tor_assert(v->type == NS_TYPE_VOTE);
1182 va_times[v_sl_idx] = v->valid_after;
1183 fu_times[v_sl_idx] = v->fresh_until;
1184 vu_times[v_sl_idx] = v->valid_until;
1185 votesec_list[v_sl_idx] = v->vote_seconds;
1186 distsec_list[v_sl_idx] = v->dist_seconds;
1187 if (v->client_versions) {
1188 smartlist_t *cv = smartlist_new();
1189 ++n_versioning_clients;
1190 smartlist_split_string(cv, v->client_versions, ",",
1191 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1192 sort_version_list(cv, 1);
1193 smartlist_add_all(combined_client_versions, cv);
1194 smartlist_free(cv); /* elements get freed later. */
1196 if (v->server_versions) {
1197 smartlist_t *sv = smartlist_new();
1198 ++n_versioning_servers;
1199 smartlist_split_string(sv, v->server_versions, ",",
1200 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1201 sort_version_list(sv, 1);
1202 smartlist_add_all(combined_server_versions, sv);
1203 smartlist_free(sv); /* elements get freed later. */
1205 SMARTLIST_FOREACH(v->known_flags, const char *, cp,
1206 smartlist_add(flags, tor_strdup(cp)));
1207 } SMARTLIST_FOREACH_END(v);
1208 valid_after = median_time(va_times, n_votes);
1209 fresh_until = median_time(fu_times, n_votes);
1210 valid_until = median_time(vu_times, n_votes);
1211 vote_seconds = median_int(votesec_list, n_votes);
1212 dist_seconds = median_int(distsec_list, n_votes);
1214 tor_assert(valid_after +
1215 (get_options()->TestingTorNetwork ?
1216 MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) <= fresh_until);
1217 tor_assert(fresh_until +
1218 (get_options()->TestingTorNetwork ?
1219 MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) <= valid_until);
1220 tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
1221 tor_assert(dist_seconds >= MIN_DIST_SECONDS);
1223 server_versions = compute_consensus_versions_list(combined_server_versions,
1224 n_versioning_servers);
1225 client_versions = compute_consensus_versions_list(combined_client_versions,
1226 n_versioning_clients);
1227 if (consensus_method >= MIN_METHOD_FOR_PACKAGE_LINES) {
1228 packages = compute_consensus_package_lines(votes);
1229 } else {
1230 packages = tor_strdup("");
1233 SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
1234 SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
1235 smartlist_free(combined_server_versions);
1236 smartlist_free(combined_client_versions);
1238 smartlist_sort_strings(flags);
1239 smartlist_uniq_strings(flags);
1241 tor_free(va_times);
1242 tor_free(fu_times);
1243 tor_free(vu_times);
1244 tor_free(votesec_list);
1245 tor_free(distsec_list);
1248 chunks = smartlist_new();
1251 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
1252 vu_buf[ISO_TIME_LEN+1];
1253 char *flaglist;
1254 format_iso_time(va_buf, valid_after);
1255 format_iso_time(fu_buf, fresh_until);
1256 format_iso_time(vu_buf, valid_until);
1257 flaglist = smartlist_join_strings(flags, " ", 0, NULL);
1259 smartlist_add_asprintf(chunks, "network-status-version 3%s%s\n"
1260 "vote-status consensus\n",
1261 flavor == FLAV_NS ? "" : " ",
1262 flavor == FLAV_NS ? "" : flavor_name);
1264 smartlist_add_asprintf(chunks, "consensus-method %d\n",
1265 consensus_method);
1267 smartlist_add_asprintf(chunks,
1268 "valid-after %s\n"
1269 "fresh-until %s\n"
1270 "valid-until %s\n"
1271 "voting-delay %d %d\n"
1272 "client-versions %s\n"
1273 "server-versions %s\n"
1274 "%s" /* packages */
1275 "known-flags %s\n",
1276 va_buf, fu_buf, vu_buf,
1277 vote_seconds, dist_seconds,
1278 client_versions, server_versions,
1279 packages,
1280 flaglist);
1282 tor_free(flaglist);
1285 params = dirvote_compute_params(votes, consensus_method,
1286 total_authorities);
1287 if (params) {
1288 smartlist_add(chunks, tor_strdup("params "));
1289 smartlist_add(chunks, params);
1290 smartlist_add(chunks, tor_strdup("\n"));
1293 /* Sort the votes. */
1294 smartlist_sort(votes, compare_votes_by_authority_id_);
1295 /* Add the authority sections. */
1297 smartlist_t *dir_sources = smartlist_new();
1298 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1299 dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
1300 e->v = v;
1301 e->digest = get_voter(v)->identity_digest;
1302 e->is_legacy = 0;
1303 smartlist_add(dir_sources, e);
1304 if (!tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
1305 dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
1306 e_legacy->v = v;
1307 e_legacy->digest = get_voter(v)->legacy_id_digest;
1308 e_legacy->is_legacy = 1;
1309 smartlist_add(dir_sources, e_legacy);
1311 } SMARTLIST_FOREACH_END(v);
1312 smartlist_sort(dir_sources, compare_dir_src_ents_by_authority_id_);
1314 SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
1315 char fingerprint[HEX_DIGEST_LEN+1];
1316 char votedigest[HEX_DIGEST_LEN+1];
1317 networkstatus_t *v = e->v;
1318 networkstatus_voter_info_t *voter = get_voter(v);
1320 base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
1321 base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
1322 DIGEST_LEN);
1324 smartlist_add_asprintf(chunks,
1325 "dir-source %s%s %s %s %s %d %d\n",
1326 voter->nickname, e->is_legacy ? "-legacy" : "",
1327 fingerprint, voter->address, fmt_addr32(voter->addr),
1328 voter->dir_port,
1329 voter->or_port);
1330 if (! e->is_legacy) {
1331 smartlist_add_asprintf(chunks,
1332 "contact %s\n"
1333 "vote-digest %s\n",
1334 voter->contact,
1335 votedigest);
1337 } SMARTLIST_FOREACH_END(e);
1338 SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
1339 smartlist_free(dir_sources);
1342 if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW) {
1343 char *max_unmeasured_param = NULL;
1344 /* XXXX Extract this code into a common function */
1345 if (params) {
1346 if (strcmpstart(params, "maxunmeasuredbw=") == 0)
1347 max_unmeasured_param = params;
1348 else
1349 max_unmeasured_param = strstr(params, " maxunmeasuredbw=");
1351 if (max_unmeasured_param) {
1352 int ok = 0;
1353 char *eq = strchr(max_unmeasured_param, '=');
1354 if (eq) {
1355 max_unmeasured_bw_kb = (uint32_t)
1356 tor_parse_ulong(eq+1, 10, 1, UINT32_MAX, &ok, NULL);
1357 if (!ok) {
1358 log_warn(LD_DIR, "Bad element '%s' in max unmeasured bw param",
1359 escaped(max_unmeasured_param));
1360 max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1366 /* Add the actual router entries. */
1368 int *index; /* index[j] is the current index into votes[j]. */
1369 int *size; /* size[j] is the number of routerstatuses in votes[j]. */
1370 int *flag_counts; /* The number of voters that list flag[j] for the
1371 * currently considered router. */
1372 int i;
1373 smartlist_t *matching_descs = smartlist_new();
1374 smartlist_t *chosen_flags = smartlist_new();
1375 smartlist_t *versions = smartlist_new();
1376 smartlist_t *exitsummaries = smartlist_new();
1377 uint32_t *bandwidths_kb = tor_calloc(smartlist_len(votes),
1378 sizeof(uint32_t));
1379 uint32_t *measured_bws_kb = tor_calloc(smartlist_len(votes),
1380 sizeof(uint32_t));
1381 uint32_t *measured_guardfraction = tor_calloc(smartlist_len(votes),
1382 sizeof(uint32_t));
1383 int num_bandwidths;
1384 int num_mbws;
1385 int num_guardfraction_inputs;
1387 int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
1388 * votes[j] knows about. */
1389 int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
1390 * about flags[f]. */
1391 int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
1392 * is the same flag as votes[j]->known_flags[b]. */
1393 int *named_flag; /* Index of the flag "Named" for votes[j] */
1394 int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
1395 int n_authorities_measuring_bandwidth;
1397 strmap_t *name_to_id_map = strmap_new();
1398 char conflict[DIGEST_LEN];
1399 char unknown[DIGEST_LEN];
1400 memset(conflict, 0, sizeof(conflict));
1401 memset(unknown, 0xff, sizeof(conflict));
1403 index = tor_calloc(smartlist_len(votes), sizeof(int));
1404 size = tor_calloc(smartlist_len(votes), sizeof(int));
1405 n_voter_flags = tor_calloc(smartlist_len(votes), sizeof(int));
1406 n_flag_voters = tor_calloc(smartlist_len(flags), sizeof(int));
1407 flag_map = tor_calloc(smartlist_len(votes), sizeof(int *));
1408 named_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1409 unnamed_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1410 for (i = 0; i < smartlist_len(votes); ++i)
1411 unnamed_flag[i] = named_flag[i] = -1;
1413 /* Build the flag indexes. Note that no vote can have more than 64 members
1414 * for known_flags, so no value will be greater than 63, so it's safe to
1415 * do U64_LITERAL(1) << index on these values. But note also that
1416 * named_flag and unnamed_flag are initialized to -1, so we need to check
1417 * that they're actually set before doing U64_LITERAL(1) << index with
1418 * them.*/
1419 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1420 flag_map[v_sl_idx] = tor_calloc(smartlist_len(v->known_flags),
1421 sizeof(int));
1422 if (smartlist_len(v->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
1423 log_warn(LD_BUG, "Somehow, a vote has %d entries in known_flags",
1424 smartlist_len(v->known_flags));
1426 SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
1427 int p = smartlist_string_pos(flags, fl);
1428 tor_assert(p >= 0);
1429 flag_map[v_sl_idx][fl_sl_idx] = p;
1430 ++n_flag_voters[p];
1431 if (!strcmp(fl, "Named"))
1432 named_flag[v_sl_idx] = fl_sl_idx;
1433 if (!strcmp(fl, "Unnamed"))
1434 unnamed_flag[v_sl_idx] = fl_sl_idx;
1435 } SMARTLIST_FOREACH_END(fl);
1436 n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
1437 size[v_sl_idx] = smartlist_len(v->routerstatus_list);
1438 } SMARTLIST_FOREACH_END(v);
1440 /* Named and Unnamed get treated specially */
1442 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1443 uint64_t nf;
1444 if (named_flag[v_sl_idx]<0)
1445 continue;
1446 nf = U64_LITERAL(1) << named_flag[v_sl_idx];
1447 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1448 vote_routerstatus_t *, rs) {
1450 if ((rs->flags & nf) != 0) {
1451 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1452 if (!d) {
1453 /* We have no name officially mapped to this digest. */
1454 strmap_set_lc(name_to_id_map, rs->status.nickname,
1455 rs->status.identity_digest);
1456 } else if (d != conflict &&
1457 fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
1458 /* Authorities disagree about this nickname. */
1459 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1460 } else {
1461 /* It's already a conflict, or it's already this ID. */
1464 } SMARTLIST_FOREACH_END(rs);
1465 } SMARTLIST_FOREACH_END(v);
1467 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1468 uint64_t uf;
1469 if (unnamed_flag[v_sl_idx]<0)
1470 continue;
1471 uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
1472 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1473 vote_routerstatus_t *, rs) {
1474 if ((rs->flags & uf) != 0) {
1475 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1476 if (d == conflict || d == unknown) {
1477 /* Leave it alone; we know what it is. */
1478 } else if (!d) {
1479 /* We have no name officially mapped to this digest. */
1480 strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
1481 } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
1482 /* Authorities disagree about this nickname. */
1483 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1484 } else {
1485 /* It's mapped to a different name. */
1488 } SMARTLIST_FOREACH_END(rs);
1489 } SMARTLIST_FOREACH_END(v);
1492 /* We need to know how many votes measure bandwidth. */
1493 n_authorities_measuring_bandwidth = 0;
1494 SMARTLIST_FOREACH(votes, const networkstatus_t *, v,
1495 if (v->has_measured_bws) {
1496 ++n_authorities_measuring_bandwidth;
1500 /* Populate the collator */
1501 collator = dircollator_new(smartlist_len(votes), total_authorities);
1502 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1503 dircollator_add_vote(collator, v);
1504 } SMARTLIST_FOREACH_END(v);
1506 dircollator_collate(collator, consensus_method);
1508 /* Now go through all the votes */
1509 flag_counts = tor_calloc(smartlist_len(flags), sizeof(int));
1510 const int num_routers = dircollator_n_routers(collator);
1511 for (i = 0; i < num_routers; ++i) {
1512 vote_routerstatus_t **vrs_lst =
1513 dircollator_get_votes_for_router(collator, i);
1515 vote_routerstatus_t *rs;
1516 routerstatus_t rs_out;
1517 const char *current_rsa_id = NULL;
1518 const char *chosen_version;
1519 const char *chosen_name = NULL;
1520 int exitsummary_disagreement = 0;
1521 int is_named = 0, is_unnamed = 0, is_running = 0;
1522 int is_guard = 0, is_exit = 0, is_bad_exit = 0;
1523 int naming_conflict = 0;
1524 int n_listing = 0;
1525 char microdesc_digest[DIGEST256_LEN];
1526 tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
1528 memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
1529 smartlist_clear(matching_descs);
1530 smartlist_clear(chosen_flags);
1531 smartlist_clear(versions);
1532 num_bandwidths = 0;
1533 num_mbws = 0;
1534 num_guardfraction_inputs = 0;
1536 /* Okay, go through all the entries for this digest. */
1537 for (int voter_idx = 0; voter_idx < smartlist_len(votes); ++voter_idx) {
1538 if (vrs_lst[voter_idx] == NULL)
1539 continue; /* This voter had nothing to say about this entry. */
1540 rs = vrs_lst[voter_idx];
1541 ++n_listing;
1543 current_rsa_id = rs->status.identity_digest;
1545 smartlist_add(matching_descs, rs);
1546 if (rs->version && rs->version[0])
1547 smartlist_add(versions, rs->version);
1549 /* Tally up all the flags. */
1550 for (int flag = 0; flag < n_voter_flags[voter_idx]; ++flag) {
1551 if (rs->flags & (U64_LITERAL(1) << flag))
1552 ++flag_counts[flag_map[voter_idx][flag]];
1554 if (named_flag[voter_idx] >= 0 &&
1555 (rs->flags & (U64_LITERAL(1) << named_flag[voter_idx]))) {
1556 if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
1557 log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
1558 chosen_name, rs->status.nickname);
1559 naming_conflict = 1;
1561 chosen_name = rs->status.nickname;
1564 /* Count guardfraction votes and note down the values. */
1565 if (rs->status.has_guardfraction) {
1566 measured_guardfraction[num_guardfraction_inputs++] =
1567 rs->status.guardfraction_percentage;
1570 /* count bandwidths */
1571 if (rs->has_measured_bw)
1572 measured_bws_kb[num_mbws++] = rs->measured_bw_kb;
1574 if (rs->status.has_bandwidth)
1575 bandwidths_kb[num_bandwidths++] = rs->status.bandwidth_kb;
1578 /* We don't include this router at all unless more than half of
1579 * the authorities we believe in list it. */
1580 if (n_listing <= total_authorities/2)
1581 continue;
1583 /* The clangalyzer can't figure out that this will never be NULL
1584 * if n_listing is at least 1 */
1585 tor_assert(current_rsa_id);
1587 /* Figure out the most popular opinion of what the most recent
1588 * routerinfo and its contents are. */
1589 memset(microdesc_digest, 0, sizeof(microdesc_digest));
1590 rs = compute_routerstatus_consensus(matching_descs, consensus_method,
1591 microdesc_digest, &alt_orport);
1592 /* Copy bits of that into rs_out. */
1593 memset(&rs_out, 0, sizeof(rs_out));
1594 tor_assert(fast_memeq(current_rsa_id,
1595 rs->status.identity_digest,DIGEST_LEN));
1596 memcpy(rs_out.identity_digest, current_rsa_id, DIGEST_LEN);
1597 memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
1598 DIGEST_LEN);
1599 rs_out.addr = rs->status.addr;
1600 rs_out.published_on = rs->status.published_on;
1601 rs_out.dir_port = rs->status.dir_port;
1602 rs_out.or_port = rs->status.or_port;
1603 if (consensus_method >= MIN_METHOD_FOR_A_LINES) {
1604 tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
1605 rs_out.ipv6_orport = alt_orport.port;
1607 rs_out.has_bandwidth = 0;
1608 rs_out.has_exitsummary = 0;
1610 if (chosen_name && !naming_conflict) {
1611 strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
1612 } else {
1613 strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
1617 const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
1618 if (!d) {
1619 is_named = is_unnamed = 0;
1620 } else if (fast_memeq(d, current_rsa_id, DIGEST_LEN)) {
1621 is_named = 1; is_unnamed = 0;
1622 } else {
1623 is_named = 0; is_unnamed = 1;
1627 /* Set the flags. */
1628 smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
1629 SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
1630 if (!strcmp(fl, "Named")) {
1631 if (is_named)
1632 smartlist_add(chosen_flags, (char*)fl);
1633 } else if (!strcmp(fl, "Unnamed")) {
1634 if (is_unnamed)
1635 smartlist_add(chosen_flags, (char*)fl);
1636 } else {
1637 if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
1638 smartlist_add(chosen_flags, (char*)fl);
1639 if (!strcmp(fl, "Exit"))
1640 is_exit = 1;
1641 else if (!strcmp(fl, "Guard"))
1642 is_guard = 1;
1643 else if (!strcmp(fl, "Running"))
1644 is_running = 1;
1645 else if (!strcmp(fl, "BadExit"))
1646 is_bad_exit = 1;
1649 } SMARTLIST_FOREACH_END(fl);
1651 /* Starting with consensus method 4 we do not list servers
1652 * that are not running in a consensus. See Proposal 138 */
1653 if (!is_running)
1654 continue;
1656 /* Pick the version. */
1657 if (smartlist_len(versions)) {
1658 sort_version_list(versions, 0);
1659 chosen_version = get_most_frequent_member(versions);
1660 } else {
1661 chosen_version = NULL;
1664 /* If it's a guard and we have enough guardfraction votes,
1665 calculate its consensus guardfraction value. */
1666 if (is_guard && num_guardfraction_inputs > 2 &&
1667 consensus_method >= MIN_METHOD_FOR_GUARDFRACTION) {
1668 rs_out.has_guardfraction = 1;
1669 rs_out.guardfraction_percentage = median_uint32(measured_guardfraction,
1670 num_guardfraction_inputs);
1671 /* final value should be an integer percentage! */
1672 tor_assert(rs_out.guardfraction_percentage <= 100);
1675 /* Pick a bandwidth */
1676 if (num_mbws > 2) {
1677 rs_out.has_bandwidth = 1;
1678 rs_out.bw_is_unmeasured = 0;
1679 rs_out.bandwidth_kb = median_uint32(measured_bws_kb, num_mbws);
1680 } else if (num_bandwidths > 0) {
1681 rs_out.has_bandwidth = 1;
1682 rs_out.bw_is_unmeasured = 1;
1683 rs_out.bandwidth_kb = median_uint32(bandwidths_kb, num_bandwidths);
1684 if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW &&
1685 n_authorities_measuring_bandwidth > 2) {
1686 /* Cap non-measured bandwidths. */
1687 if (rs_out.bandwidth_kb > max_unmeasured_bw_kb) {
1688 rs_out.bandwidth_kb = max_unmeasured_bw_kb;
1693 /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
1694 is_exit = is_exit && !is_bad_exit;
1696 /* Update total bandwidth weights with the bandwidths of this router. */
1698 update_total_bandwidth_weights(&rs_out,
1699 is_exit, is_guard,
1700 &G, &M, &E, &D, &T);
1703 /* Ok, we already picked a descriptor digest we want to list
1704 * previously. Now we want to use the exit policy summary from
1705 * that descriptor. If everybody plays nice all the voters who
1706 * listed that descriptor will have the same summary. If not then
1707 * something is fishy and we'll use the most common one (breaking
1708 * ties in favor of lexicographically larger one (only because it
1709 * lets me reuse more existing code)).
1711 * The other case that can happen is that no authority that voted
1712 * for that descriptor has an exit policy summary. That's
1713 * probably quite unlikely but can happen. In that case we use
1714 * the policy that was most often listed in votes, again breaking
1715 * ties like in the previous case.
1718 /* Okay, go through all the votes for this router. We prepared
1719 * that list previously */
1720 const char *chosen_exitsummary = NULL;
1721 smartlist_clear(exitsummaries);
1722 SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
1723 /* Check if the vote where this status comes from had the
1724 * proper descriptor */
1725 tor_assert(fast_memeq(rs_out.identity_digest,
1726 vsr->status.identity_digest,
1727 DIGEST_LEN));
1728 if (vsr->status.has_exitsummary &&
1729 fast_memeq(rs_out.descriptor_digest,
1730 vsr->status.descriptor_digest,
1731 DIGEST_LEN)) {
1732 tor_assert(vsr->status.exitsummary);
1733 smartlist_add(exitsummaries, vsr->status.exitsummary);
1734 if (!chosen_exitsummary) {
1735 chosen_exitsummary = vsr->status.exitsummary;
1736 } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
1737 /* Great. There's disagreement among the voters. That
1738 * really shouldn't be */
1739 exitsummary_disagreement = 1;
1742 } SMARTLIST_FOREACH_END(vsr);
1744 if (exitsummary_disagreement) {
1745 char id[HEX_DIGEST_LEN+1];
1746 char dd[HEX_DIGEST_LEN+1];
1747 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1748 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1749 log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
1750 " for router %s with descriptor %s. This really shouldn't"
1751 " have happened.", id, dd);
1753 smartlist_sort_strings(exitsummaries);
1754 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1755 } else if (!chosen_exitsummary) {
1756 char id[HEX_DIGEST_LEN+1];
1757 char dd[HEX_DIGEST_LEN+1];
1758 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1759 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1760 log_warn(LD_DIR, "Not one of the voters that made us select"
1761 "descriptor %s for router %s had an exit policy"
1762 "summary", dd, id);
1764 /* Ok, none of those voting for the digest we chose had an
1765 * exit policy for us. Well, that kinda sucks.
1767 smartlist_clear(exitsummaries);
1768 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
1769 if (vsr->status.has_exitsummary)
1770 smartlist_add(exitsummaries, vsr->status.exitsummary);
1772 smartlist_sort_strings(exitsummaries);
1773 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1775 if (!chosen_exitsummary)
1776 log_warn(LD_DIR, "Wow, not one of the voters had an exit "
1777 "policy summary for %s. Wow.", id);
1780 if (chosen_exitsummary) {
1781 rs_out.has_exitsummary = 1;
1782 /* yea, discards the const */
1783 rs_out.exitsummary = (char *)chosen_exitsummary;
1787 if (flavor == FLAV_MICRODESC &&
1788 tor_digest256_is_zero(microdesc_digest)) {
1789 /* With no microdescriptor digest, we omit the entry entirely. */
1790 continue;
1794 char *buf;
1795 /* Okay!! Now we can write the descriptor... */
1796 /* First line goes into "buf". */
1797 buf = routerstatus_format_entry(&rs_out, NULL, rs_format, NULL);
1798 if (buf)
1799 smartlist_add(chunks, buf);
1801 /* Now an m line, if applicable. */
1802 if (flavor == FLAV_MICRODESC &&
1803 !tor_digest256_is_zero(microdesc_digest)) {
1804 char m[BASE64_DIGEST256_LEN+1];
1805 digest256_to_base64(m, microdesc_digest);
1806 smartlist_add_asprintf(chunks, "m %s\n", m);
1808 /* Next line is all flags. The "\n" is missing. */
1809 smartlist_add(chunks,
1810 smartlist_join_strings(chosen_flags, " ", 0, NULL));
1811 /* Now the version line. */
1812 if (chosen_version) {
1813 smartlist_add(chunks, tor_strdup("\nv "));
1814 smartlist_add(chunks, tor_strdup(chosen_version));
1816 smartlist_add(chunks, tor_strdup("\n"));
1817 /* Now the weight line. */
1818 if (rs_out.has_bandwidth) {
1819 char *guardfraction_str = NULL;
1820 int unmeasured = rs_out.bw_is_unmeasured &&
1821 consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW;
1823 /* If we have guardfraction info, include it in the 'w' line. */
1824 if (rs_out.has_guardfraction) {
1825 tor_asprintf(&guardfraction_str,
1826 " GuardFraction=%u", rs_out.guardfraction_percentage);
1828 smartlist_add_asprintf(chunks, "w Bandwidth=%d%s%s\n",
1829 rs_out.bandwidth_kb,
1830 unmeasured?" Unmeasured=1":"",
1831 guardfraction_str ? guardfraction_str : "");
1833 tor_free(guardfraction_str);
1836 /* Now the exitpolicy summary line. */
1837 if (rs_out.has_exitsummary && flavor == FLAV_NS) {
1838 smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
1841 /* And the loop is over and we move on to the next router */
1844 tor_free(index);
1845 tor_free(size);
1846 tor_free(n_voter_flags);
1847 tor_free(n_flag_voters);
1848 for (i = 0; i < smartlist_len(votes); ++i)
1849 tor_free(flag_map[i]);
1850 tor_free(flag_map);
1851 tor_free(flag_counts);
1852 tor_free(named_flag);
1853 tor_free(unnamed_flag);
1854 strmap_free(name_to_id_map, NULL);
1855 smartlist_free(matching_descs);
1856 smartlist_free(chosen_flags);
1857 smartlist_free(versions);
1858 smartlist_free(exitsummaries);
1859 tor_free(bandwidths_kb);
1860 tor_free(measured_bws_kb);
1861 tor_free(measured_guardfraction);
1864 /* Mark the directory footer region */
1865 smartlist_add(chunks, tor_strdup("directory-footer\n"));
1868 int64_t weight_scale = BW_WEIGHT_SCALE;
1869 char *bw_weight_param = NULL;
1871 // Parse params, extract BW_WEIGHT_SCALE if present
1872 // DO NOT use consensus_param_bw_weight_scale() in this code!
1873 // The consensus is not formed yet!
1874 /* XXXX Extract this code into a common function */
1875 if (params) {
1876 if (strcmpstart(params, "bwweightscale=") == 0)
1877 bw_weight_param = params;
1878 else
1879 bw_weight_param = strstr(params, " bwweightscale=");
1882 if (bw_weight_param) {
1883 int ok=0;
1884 char *eq = strchr(bw_weight_param, '=');
1885 if (eq) {
1886 weight_scale = tor_parse_long(eq+1, 10, 1, INT32_MAX, &ok,
1887 NULL);
1888 if (!ok) {
1889 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
1890 escaped(bw_weight_param));
1891 weight_scale = BW_WEIGHT_SCALE;
1893 } else {
1894 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
1895 escaped(bw_weight_param));
1896 weight_scale = BW_WEIGHT_SCALE;
1900 added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
1901 T, weight_scale);
1904 /* Add a signature. */
1906 char digest[DIGEST256_LEN];
1907 char fingerprint[HEX_DIGEST_LEN+1];
1908 char signing_key_fingerprint[HEX_DIGEST_LEN+1];
1909 digest_algorithm_t digest_alg =
1910 flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
1911 size_t digest_len =
1912 flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
1913 const char *algname = crypto_digest_algorithm_get_name(digest_alg);
1914 char *signature;
1916 smartlist_add(chunks, tor_strdup("directory-signature "));
1918 /* Compute the hash of the chunks. */
1919 crypto_digest_smartlist(digest, digest_len, chunks, "", digest_alg);
1921 /* Get the fingerprints */
1922 crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
1923 crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
1925 /* add the junk that will go at the end of the line. */
1926 if (flavor == FLAV_NS) {
1927 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
1928 signing_key_fingerprint);
1929 } else {
1930 smartlist_add_asprintf(chunks, "%s %s %s\n",
1931 algname, fingerprint,
1932 signing_key_fingerprint);
1934 /* And the signature. */
1935 if (!(signature = router_get_dirobj_signature(digest, digest_len,
1936 signing_key))) {
1937 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1938 goto done;
1940 smartlist_add(chunks, signature);
1942 if (legacy_id_key_digest && legacy_signing_key) {
1943 smartlist_add(chunks, tor_strdup("directory-signature "));
1944 base16_encode(fingerprint, sizeof(fingerprint),
1945 legacy_id_key_digest, DIGEST_LEN);
1946 crypto_pk_get_fingerprint(legacy_signing_key,
1947 signing_key_fingerprint, 0);
1948 if (flavor == FLAV_NS) {
1949 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
1950 signing_key_fingerprint);
1951 } else {
1952 smartlist_add_asprintf(chunks, "%s %s %s\n",
1953 algname, fingerprint,
1954 signing_key_fingerprint);
1957 if (!(signature = router_get_dirobj_signature(digest, digest_len,
1958 legacy_signing_key))) {
1959 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1960 goto done;
1962 smartlist_add(chunks, signature);
1966 result = smartlist_join_strings(chunks, "", 0, NULL);
1969 networkstatus_t *c;
1970 if (!(c = networkstatus_parse_vote_from_string(result, NULL,
1971 NS_TYPE_CONSENSUS))) {
1972 log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
1973 "parse.");
1974 tor_free(result);
1975 goto done;
1977 // Verify balancing parameters
1978 if (added_weights) {
1979 networkstatus_verify_bw_weights(c, consensus_method);
1981 networkstatus_vote_free(c);
1984 done:
1986 dircollator_free(collator);
1987 tor_free(client_versions);
1988 tor_free(server_versions);
1989 tor_free(packages);
1990 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
1991 smartlist_free(flags);
1992 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
1993 smartlist_free(chunks);
1995 return result;
1998 /** Given a list of networkstatus_t for each vote, return a newly allocated
1999 * string containing the "package" lines for the vote. */
2000 STATIC char *
2001 compute_consensus_package_lines(smartlist_t *votes)
2003 const int n_votes = smartlist_len(votes);
2005 /* This will be a map from "packagename version" strings to arrays
2006 * of const char *, with the i'th member of the array corresponding to the
2007 * package line from the i'th vote.
2009 strmap_t *package_status = strmap_new();
2011 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
2012 if (! v->package_lines)
2013 continue;
2014 SMARTLIST_FOREACH_BEGIN(v->package_lines, const char *, line) {
2015 if (! validate_recommended_package_line(line))
2016 continue;
2018 /* Skip 'cp' to the second space in the line. */
2019 const char *cp = strchr(line, ' ');
2020 if (!cp) continue;
2021 ++cp;
2022 cp = strchr(cp, ' ');
2023 if (!cp) continue;
2025 char *key = tor_strndup(line, cp - line);
2027 const char **status = strmap_get(package_status, key);
2028 if (!status) {
2029 status = tor_calloc(n_votes, sizeof(const char *));
2030 strmap_set(package_status, key, status);
2032 status[v_sl_idx] = line; /* overwrite old value */
2033 tor_free(key);
2034 } SMARTLIST_FOREACH_END(line);
2035 } SMARTLIST_FOREACH_END(v);
2037 smartlist_t *entries = smartlist_new(); /* temporary */
2038 smartlist_t *result_list = smartlist_new(); /* output */
2039 STRMAP_FOREACH(package_status, key, const char **, values) {
2040 int i, count=-1;
2041 for (i = 0; i < n_votes; ++i) {
2042 if (values[i])
2043 smartlist_add(entries, (void*) values[i]);
2045 smartlist_sort_strings(entries);
2046 int n_voting_for_entry = smartlist_len(entries);
2047 const char *most_frequent =
2048 smartlist_get_most_frequent_string_(entries, &count);
2050 if (n_voting_for_entry >= 3 && count > n_voting_for_entry / 2) {
2051 smartlist_add_asprintf(result_list, "package %s\n", most_frequent);
2054 smartlist_clear(entries);
2056 } STRMAP_FOREACH_END;
2058 smartlist_sort_strings(result_list);
2060 char *result = smartlist_join_strings(result_list, "", 0, NULL);
2062 SMARTLIST_FOREACH(result_list, char *, cp, tor_free(cp));
2063 smartlist_free(result_list);
2064 smartlist_free(entries);
2065 strmap_free(package_status, tor_free_);
2067 return result;
2070 /** Given a consensus vote <b>target</b> and a set of detached signatures in
2071 * <b>sigs</b> that correspond to the same consensus, check whether there are
2072 * any new signatures in <b>src_voter_list</b> that should be added to
2073 * <b>target</b>. (A signature should be added if we have no signature for that
2074 * voter in <b>target</b> yet, or if we have no verifiable signature and the
2075 * new signature is verifiable.) Return the number of signatures added or
2076 * changed, or -1 if the document signed by <b>sigs</b> isn't the same
2077 * document as <b>target</b>. */
2079 networkstatus_add_detached_signatures(networkstatus_t *target,
2080 ns_detached_signatures_t *sigs,
2081 const char *source,
2082 int severity,
2083 const char **msg_out)
2085 int r = 0;
2086 const char *flavor;
2087 smartlist_t *siglist;
2088 tor_assert(sigs);
2089 tor_assert(target);
2090 tor_assert(target->type == NS_TYPE_CONSENSUS);
2092 flavor = networkstatus_get_flavor_name(target->flavor);
2094 /* Do the times seem right? */
2095 if (target->valid_after != sigs->valid_after) {
2096 *msg_out = "Valid-After times do not match "
2097 "when adding detached signatures to consensus";
2098 return -1;
2100 if (target->fresh_until != sigs->fresh_until) {
2101 *msg_out = "Fresh-until times do not match "
2102 "when adding detached signatures to consensus";
2103 return -1;
2105 if (target->valid_until != sigs->valid_until) {
2106 *msg_out = "Valid-until times do not match "
2107 "when adding detached signatures to consensus";
2108 return -1;
2110 siglist = strmap_get(sigs->signatures, flavor);
2111 if (!siglist) {
2112 *msg_out = "No signatures for given consensus flavor";
2113 return -1;
2116 /** Make sure all the digests we know match, and at least one matches. */
2118 digests_t *digests = strmap_get(sigs->digests, flavor);
2119 int n_matches = 0;
2120 int alg;
2121 if (!digests) {
2122 *msg_out = "No digests for given consensus flavor";
2123 return -1;
2125 for (alg = DIGEST_SHA1; alg < N_DIGEST_ALGORITHMS; ++alg) {
2126 if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
2127 if (fast_memeq(target->digests.d[alg], digests->d[alg],
2128 DIGEST256_LEN)) {
2129 ++n_matches;
2130 } else {
2131 *msg_out = "Mismatched digest.";
2132 return -1;
2136 if (!n_matches) {
2137 *msg_out = "No regognized digests for given consensus flavor";
2141 /* For each voter in src... */
2142 SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
2143 char voter_identity[HEX_DIGEST_LEN+1];
2144 networkstatus_voter_info_t *target_voter =
2145 networkstatus_get_voter_by_id(target, sig->identity_digest);
2146 authority_cert_t *cert = NULL;
2147 const char *algorithm;
2148 document_signature_t *old_sig = NULL;
2150 algorithm = crypto_digest_algorithm_get_name(sig->alg);
2152 base16_encode(voter_identity, sizeof(voter_identity),
2153 sig->identity_digest, DIGEST_LEN);
2154 log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
2155 algorithm);
2156 /* If the target doesn't know about this voter, then forget it. */
2157 if (!target_voter) {
2158 log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
2159 continue;
2162 old_sig = voter_get_sig_by_algorithm(target_voter, sig->alg);
2164 /* If the target already has a good signature from this voter, then skip
2165 * this one. */
2166 if (old_sig && old_sig->good_signature) {
2167 log_info(LD_DIR, "We already have a good signature from %s using %s",
2168 voter_identity, algorithm);
2169 continue;
2172 /* Try checking the signature if we haven't already. */
2173 if (!sig->good_signature && !sig->bad_signature) {
2174 cert = authority_cert_get_by_digests(sig->identity_digest,
2175 sig->signing_key_digest);
2176 if (cert) {
2177 /* Not checking the return value here, since we are going to look
2178 * at the status of sig->good_signature in a moment. */
2179 (void) networkstatus_check_document_signature(target, sig, cert);
2183 /* If this signature is good, or we don't have any signature yet,
2184 * then maybe add it. */
2185 if (sig->good_signature || !old_sig || old_sig->bad_signature) {
2186 log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
2187 algorithm);
2188 tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
2189 target_voter->nickname, source);
2190 ++r;
2191 if (old_sig) {
2192 smartlist_remove(target_voter->sigs, old_sig);
2193 document_signature_free(old_sig);
2195 smartlist_add(target_voter->sigs, document_signature_dup(sig));
2196 } else {
2197 log_info(LD_DIR, "Not adding signature from %s", voter_identity);
2199 } SMARTLIST_FOREACH_END(sig);
2201 return r;
2204 /** Return a newly allocated string containing all the signatures on
2205 * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
2206 * then the signatures will be put in a detached signatures document, so
2207 * prefix any non-NS-flavored signatures with "additional-signature" rather
2208 * than "directory-signature". */
2209 static char *
2210 networkstatus_format_signatures(networkstatus_t *consensus,
2211 int for_detached_signatures)
2213 smartlist_t *elements;
2214 char buf[4096];
2215 char *result = NULL;
2216 int n_sigs = 0;
2217 const consensus_flavor_t flavor = consensus->flavor;
2218 const char *flavor_name = networkstatus_get_flavor_name(flavor);
2219 const char *keyword;
2221 if (for_detached_signatures && flavor != FLAV_NS)
2222 keyword = "additional-signature";
2223 else
2224 keyword = "directory-signature";
2226 elements = smartlist_new();
2228 SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
2229 SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
2230 char sk[HEX_DIGEST_LEN+1];
2231 char id[HEX_DIGEST_LEN+1];
2232 if (!sig->signature || sig->bad_signature)
2233 continue;
2234 ++n_sigs;
2235 base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
2236 base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
2237 if (flavor == FLAV_NS) {
2238 smartlist_add_asprintf(elements,
2239 "%s %s %s\n-----BEGIN SIGNATURE-----\n",
2240 keyword, id, sk);
2241 } else {
2242 const char *digest_name =
2243 crypto_digest_algorithm_get_name(sig->alg);
2244 smartlist_add_asprintf(elements,
2245 "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
2246 keyword,
2247 for_detached_signatures ? " " : "",
2248 for_detached_signatures ? flavor_name : "",
2249 digest_name, id, sk);
2251 base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len,
2252 BASE64_ENCODE_MULTILINE);
2253 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
2254 smartlist_add(elements, tor_strdup(buf));
2255 } SMARTLIST_FOREACH_END(sig);
2256 } SMARTLIST_FOREACH_END(v);
2258 result = smartlist_join_strings(elements, "", 0, NULL);
2259 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2260 smartlist_free(elements);
2261 if (!n_sigs)
2262 tor_free(result);
2263 return result;
2266 /** Return a newly allocated string holding the detached-signatures document
2267 * corresponding to the signatures on <b>consensuses</b>, which must contain
2268 * exactly one FLAV_NS consensus, and no more than one consensus for each
2269 * other flavor. */
2270 char *
2271 networkstatus_get_detached_signatures(smartlist_t *consensuses)
2273 smartlist_t *elements;
2274 char *result = NULL, *sigs = NULL;
2275 networkstatus_t *consensus_ns = NULL;
2276 tor_assert(consensuses);
2278 SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
2279 tor_assert(ns);
2280 tor_assert(ns->type == NS_TYPE_CONSENSUS);
2281 if (ns && ns->flavor == FLAV_NS)
2282 consensus_ns = ns;
2284 if (!consensus_ns) {
2285 log_warn(LD_BUG, "No NS consensus given.");
2286 return NULL;
2289 elements = smartlist_new();
2292 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
2293 vu_buf[ISO_TIME_LEN+1];
2294 char d[HEX_DIGEST_LEN+1];
2296 base16_encode(d, sizeof(d),
2297 consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
2298 format_iso_time(va_buf, consensus_ns->valid_after);
2299 format_iso_time(fu_buf, consensus_ns->fresh_until);
2300 format_iso_time(vu_buf, consensus_ns->valid_until);
2302 smartlist_add_asprintf(elements,
2303 "consensus-digest %s\n"
2304 "valid-after %s\n"
2305 "fresh-until %s\n"
2306 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
2309 /* Get all the digests for the non-FLAV_NS consensuses */
2310 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2311 const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
2312 int alg;
2313 if (ns->flavor == FLAV_NS)
2314 continue;
2316 /* start with SHA256; we don't include SHA1 for anything but the basic
2317 * consensus. */
2318 for (alg = DIGEST_SHA256; alg < N_DIGEST_ALGORITHMS; ++alg) {
2319 char d[HEX_DIGEST256_LEN+1];
2320 const char *alg_name =
2321 crypto_digest_algorithm_get_name(alg);
2322 if (tor_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
2323 continue;
2324 base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
2325 smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
2326 flavor_name, alg_name, d);
2328 } SMARTLIST_FOREACH_END(ns);
2330 /* Now get all the sigs for non-FLAV_NS consensuses */
2331 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2332 char *sigs;
2333 if (ns->flavor == FLAV_NS)
2334 continue;
2335 sigs = networkstatus_format_signatures(ns, 1);
2336 if (!sigs) {
2337 log_warn(LD_DIR, "Couldn't format signatures");
2338 goto err;
2340 smartlist_add(elements, sigs);
2341 } SMARTLIST_FOREACH_END(ns);
2343 /* Now add the FLAV_NS consensus signatrures. */
2344 sigs = networkstatus_format_signatures(consensus_ns, 1);
2345 if (!sigs)
2346 goto err;
2347 smartlist_add(elements, sigs);
2349 result = smartlist_join_strings(elements, "", 0, NULL);
2350 err:
2351 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2352 smartlist_free(elements);
2353 return result;
2356 /** Return a newly allocated string holding a detached-signatures document for
2357 * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
2358 * <b>pending</b>. */
2359 static char *
2360 get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
2361 int n_flavors)
2363 int flav;
2364 char *signatures;
2365 smartlist_t *c = smartlist_new();
2366 for (flav = 0; flav < n_flavors; ++flav) {
2367 if (pending[flav].consensus)
2368 smartlist_add(c, pending[flav].consensus);
2370 signatures = networkstatus_get_detached_signatures(c);
2371 smartlist_free(c);
2372 return signatures;
2375 /** Release all storage held in <b>s</b>. */
2376 void
2377 ns_detached_signatures_free(ns_detached_signatures_t *s)
2379 if (!s)
2380 return;
2381 if (s->signatures) {
2382 STRMAP_FOREACH(s->signatures, flavor, smartlist_t *, sigs) {
2383 SMARTLIST_FOREACH(sigs, document_signature_t *, sig,
2384 document_signature_free(sig));
2385 smartlist_free(sigs);
2386 } STRMAP_FOREACH_END;
2387 strmap_free(s->signatures, NULL);
2388 strmap_free(s->digests, tor_free_);
2391 tor_free(s);
2394 /* =====
2395 * Certificate functions
2396 * ===== */
2398 /** Allocate and return a new authority_cert_t with the same contents as
2399 * <b>cert</b>. */
2400 authority_cert_t *
2401 authority_cert_dup(authority_cert_t *cert)
2403 authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
2404 tor_assert(cert);
2406 memcpy(out, cert, sizeof(authority_cert_t));
2407 /* Now copy pointed-to things. */
2408 out->cache_info.signed_descriptor_body =
2409 tor_strndup(cert->cache_info.signed_descriptor_body,
2410 cert->cache_info.signed_descriptor_len);
2411 out->cache_info.saved_location = SAVED_NOWHERE;
2412 out->identity_key = crypto_pk_dup_key(cert->identity_key);
2413 out->signing_key = crypto_pk_dup_key(cert->signing_key);
2415 return out;
2418 /* =====
2419 * Vote scheduling
2420 * ===== */
2422 /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
2423 * Note that these aren't the intervals we'll use to vote; they're the ones
2424 * that we'll vote to use. */
2425 void
2426 dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
2428 const or_options_t *options = get_options();
2430 tor_assert(timing_out);
2432 timing_out->vote_interval = options->V3AuthVotingInterval;
2433 timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
2434 timing_out->vote_delay = options->V3AuthVoteDelay;
2435 timing_out->dist_delay = options->V3AuthDistDelay;
2438 /** Return the start of the next interval of size <b>interval</b> (in
2439 * seconds) after <b>now</b>, plus <b>offset</b>. Midnight always
2440 * starts a fresh interval, and if the last interval of a day would be
2441 * truncated to less than half its size, it is rolled into the
2442 * previous interval. */
2443 time_t
2444 dirvote_get_start_of_next_interval(time_t now, int interval, int offset)
2446 struct tm tm;
2447 time_t midnight_today=0;
2448 time_t midnight_tomorrow;
2449 time_t next;
2451 tor_gmtime_r(&now, &tm);
2452 tm.tm_hour = 0;
2453 tm.tm_min = 0;
2454 tm.tm_sec = 0;
2456 if (tor_timegm(&tm, &midnight_today) < 0) {
2457 log_warn(LD_BUG, "Ran into an invalid time when trying to find midnight.");
2459 midnight_tomorrow = midnight_today + (24*60*60);
2461 next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
2463 /* Intervals never cross midnight. */
2464 if (next > midnight_tomorrow)
2465 next = midnight_tomorrow;
2467 /* If the interval would only last half as long as it's supposed to, then
2468 * skip over to the next day. */
2469 if (next + interval/2 > midnight_tomorrow)
2470 next = midnight_tomorrow;
2472 next += offset;
2473 if (next - interval > now)
2474 next -= interval;
2476 return next;
2479 /** Scheduling information for a voting interval. */
2480 static struct {
2481 /** When do we generate and distribute our vote for this interval? */
2482 time_t voting_starts;
2483 /** When do we send an HTTP request for any votes that we haven't
2484 * been posted yet?*/
2485 time_t fetch_missing_votes;
2486 /** When do we give up on getting more votes and generate a consensus? */
2487 time_t voting_ends;
2488 /** When do we send an HTTP request for any signatures we're expecting to
2489 * see on the consensus? */
2490 time_t fetch_missing_signatures;
2491 /** When do we publish the consensus? */
2492 time_t interval_starts;
2494 /* True iff we have generated and distributed our vote. */
2495 int have_voted;
2496 /* True iff we've requested missing votes. */
2497 int have_fetched_missing_votes;
2498 /* True iff we have built a consensus and sent the signatures around. */
2499 int have_built_consensus;
2500 /* True iff we've fetched missing signatures. */
2501 int have_fetched_missing_signatures;
2502 /* True iff we have published our consensus. */
2503 int have_published_consensus;
2504 } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
2506 /** Set voting_schedule to hold the timing for the next vote we should be
2507 * doing. */
2508 void
2509 dirvote_recalculate_timing(const or_options_t *options, time_t now)
2511 int interval, vote_delay, dist_delay;
2512 time_t start;
2513 time_t end;
2514 networkstatus_t *consensus;
2516 if (!authdir_mode_v3(options))
2517 return;
2519 consensus = networkstatus_get_live_consensus(now);
2521 memset(&voting_schedule, 0, sizeof(voting_schedule));
2523 if (consensus) {
2524 interval = (int)( consensus->fresh_until - consensus->valid_after );
2525 vote_delay = consensus->vote_seconds;
2526 dist_delay = consensus->dist_seconds;
2527 } else {
2528 interval = options->TestingV3AuthInitialVotingInterval;
2529 vote_delay = options->TestingV3AuthInitialVoteDelay;
2530 dist_delay = options->TestingV3AuthInitialDistDelay;
2533 tor_assert(interval > 0);
2535 if (vote_delay + dist_delay > interval/2)
2536 vote_delay = dist_delay = interval / 4;
2538 start = voting_schedule.interval_starts =
2539 dirvote_get_start_of_next_interval(now,interval,
2540 options->TestingV3AuthVotingStartOffset);
2541 end = dirvote_get_start_of_next_interval(start+1, interval,
2542 options->TestingV3AuthVotingStartOffset);
2544 tor_assert(end > start);
2546 voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
2547 voting_schedule.voting_ends = start - dist_delay;
2548 voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
2549 voting_schedule.voting_starts = start - dist_delay - vote_delay;
2552 char tbuf[ISO_TIME_LEN+1];
2553 format_iso_time(tbuf, voting_schedule.interval_starts);
2554 log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
2555 "consensus_set=%d, interval=%d",
2556 tbuf, consensus?1:0, interval);
2560 /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
2561 void
2562 dirvote_act(const or_options_t *options, time_t now)
2564 if (!authdir_mode_v3(options))
2565 return;
2566 if (!voting_schedule.voting_starts) {
2567 char *keys = list_v3_auth_ids();
2568 authority_cert_t *c = get_my_v3_authority_cert();
2569 log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
2570 "Mine is %s.",
2571 keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
2572 tor_free(keys);
2573 dirvote_recalculate_timing(options, now);
2575 if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
2576 log_notice(LD_DIR, "Time to vote.");
2577 dirvote_perform_vote();
2578 voting_schedule.have_voted = 1;
2580 if (voting_schedule.fetch_missing_votes < now &&
2581 !voting_schedule.have_fetched_missing_votes) {
2582 log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
2583 dirvote_fetch_missing_votes();
2584 voting_schedule.have_fetched_missing_votes = 1;
2586 if (voting_schedule.voting_ends < now &&
2587 !voting_schedule.have_built_consensus) {
2588 log_notice(LD_DIR, "Time to compute a consensus.");
2589 dirvote_compute_consensuses();
2590 /* XXXX We will want to try again later if we haven't got enough
2591 * votes yet. Implement this if it turns out to ever happen. */
2592 voting_schedule.have_built_consensus = 1;
2594 if (voting_schedule.fetch_missing_signatures < now &&
2595 !voting_schedule.have_fetched_missing_signatures) {
2596 log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
2597 dirvote_fetch_missing_signatures();
2598 voting_schedule.have_fetched_missing_signatures = 1;
2600 if (voting_schedule.interval_starts < now &&
2601 !voting_schedule.have_published_consensus) {
2602 log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
2603 dirvote_publish_consensus();
2604 dirvote_clear_votes(0);
2605 voting_schedule.have_published_consensus = 1;
2606 /* XXXX We will want to try again later if we haven't got enough
2607 * signatures yet. Implement this if it turns out to ever happen. */
2608 dirvote_recalculate_timing(options, now);
2612 /** A vote networkstatus_t and its unparsed body: held around so we can
2613 * use it to generate a consensus (at voting_ends) and so we can serve it to
2614 * other authorities that might want it. */
2615 typedef struct pending_vote_t {
2616 cached_dir_t *vote_body;
2617 networkstatus_t *vote;
2618 } pending_vote_t;
2620 /** List of pending_vote_t for the current vote. Before we've used them to
2621 * build a consensus, the votes go here. */
2622 static smartlist_t *pending_vote_list = NULL;
2623 /** List of pending_vote_t for the previous vote. After we've used them to
2624 * build a consensus, the votes go here for the next period. */
2625 static smartlist_t *previous_vote_list = NULL;
2627 /* DOCDOC pending_consensuses */
2628 static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
2630 /** The detached signatures for the consensus that we're currently
2631 * building. */
2632 static char *pending_consensus_signatures = NULL;
2634 /** List of ns_detached_signatures_t: hold signatures that get posted to us
2635 * before we have generated the consensus on our own. */
2636 static smartlist_t *pending_consensus_signature_list = NULL;
2638 /** Generate a networkstatus vote and post it to all the v3 authorities.
2639 * (V3 Authority only) */
2640 static int
2641 dirvote_perform_vote(void)
2643 crypto_pk_t *key = get_my_v3_authority_signing_key();
2644 authority_cert_t *cert = get_my_v3_authority_cert();
2645 networkstatus_t *ns;
2646 char *contents;
2647 pending_vote_t *pending_vote;
2648 time_t now = time(NULL);
2650 int status;
2651 const char *msg = "";
2653 if (!cert || !key) {
2654 log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
2655 return -1;
2656 } else if (cert->expires < now) {
2657 log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
2658 return -1;
2660 if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
2661 return -1;
2663 contents = format_networkstatus_vote(key, ns);
2664 networkstatus_vote_free(ns);
2665 if (!contents)
2666 return -1;
2668 pending_vote = dirvote_add_vote(contents, &msg, &status);
2669 tor_free(contents);
2670 if (!pending_vote) {
2671 log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
2672 msg);
2673 return -1;
2676 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
2677 ROUTER_PURPOSE_GENERAL,
2678 V3_DIRINFO,
2679 pending_vote->vote_body->dir,
2680 pending_vote->vote_body->dir_len, 0);
2681 log_notice(LD_DIR, "Vote posted.");
2682 return 0;
2685 /** Send an HTTP request to every other v3 authority, for the votes of every
2686 * authority for which we haven't received a vote yet in this period. (V3
2687 * authority only) */
2688 static void
2689 dirvote_fetch_missing_votes(void)
2691 smartlist_t *missing_fps = smartlist_new();
2692 char *resource;
2694 SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
2695 dir_server_t *, ds) {
2696 if (!(ds->type & V3_DIRINFO))
2697 continue;
2698 if (!dirvote_get_vote(ds->v3_identity_digest,
2699 DGV_BY_ID|DGV_INCLUDE_PENDING)) {
2700 char *cp = tor_malloc(HEX_DIGEST_LEN+1);
2701 base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
2702 DIGEST_LEN);
2703 smartlist_add(missing_fps, cp);
2705 } SMARTLIST_FOREACH_END(ds);
2707 if (!smartlist_len(missing_fps)) {
2708 smartlist_free(missing_fps);
2709 return;
2712 char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
2713 log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
2714 "Asking every other authority for a copy.",
2715 smartlist_len(missing_fps), tmp);
2716 tor_free(tmp);
2718 resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
2719 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
2720 0, resource);
2721 tor_free(resource);
2722 SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
2723 smartlist_free(missing_fps);
2726 /** Send a request to every other authority for its detached signatures,
2727 * unless we have signatures from all other v3 authorities already. */
2728 static void
2729 dirvote_fetch_missing_signatures(void)
2731 int need_any = 0;
2732 int i;
2733 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
2734 networkstatus_t *consensus = pending_consensuses[i].consensus;
2735 if (!consensus ||
2736 networkstatus_check_consensus_signature(consensus, -1) == 1) {
2737 /* We have no consensus, or we have one that's signed by everybody. */
2738 continue;
2740 need_any = 1;
2742 if (!need_any)
2743 return;
2745 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
2746 0, NULL);
2749 /** Release all storage held by pending consensuses (those waiting for
2750 * signatures). */
2751 static void
2752 dirvote_clear_pending_consensuses(void)
2754 int i;
2755 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
2756 pending_consensus_t *pc = &pending_consensuses[i];
2757 tor_free(pc->body);
2759 networkstatus_vote_free(pc->consensus);
2760 pc->consensus = NULL;
2764 /** Drop all currently pending votes, consensus, and detached signatures. */
2765 static void
2766 dirvote_clear_votes(int all_votes)
2768 if (!previous_vote_list)
2769 previous_vote_list = smartlist_new();
2770 if (!pending_vote_list)
2771 pending_vote_list = smartlist_new();
2773 /* All "previous" votes are now junk. */
2774 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
2775 cached_dir_decref(v->vote_body);
2776 v->vote_body = NULL;
2777 networkstatus_vote_free(v->vote);
2778 tor_free(v);
2780 smartlist_clear(previous_vote_list);
2782 if (all_votes) {
2783 /* If we're dumping all the votes, we delete the pending ones. */
2784 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
2785 cached_dir_decref(v->vote_body);
2786 v->vote_body = NULL;
2787 networkstatus_vote_free(v->vote);
2788 tor_free(v);
2790 } else {
2791 /* Otherwise, we move them into "previous". */
2792 smartlist_add_all(previous_vote_list, pending_vote_list);
2794 smartlist_clear(pending_vote_list);
2796 if (pending_consensus_signature_list) {
2797 SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
2798 tor_free(cp));
2799 smartlist_clear(pending_consensus_signature_list);
2801 tor_free(pending_consensus_signatures);
2802 dirvote_clear_pending_consensuses();
2805 /** Return a newly allocated string containing the hex-encoded v3 authority
2806 identity digest of every recognized v3 authority. */
2807 static char *
2808 list_v3_auth_ids(void)
2810 smartlist_t *known_v3_keys = smartlist_new();
2811 char *keys;
2812 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2813 dir_server_t *, ds,
2814 if ((ds->type & V3_DIRINFO) &&
2815 !tor_digest_is_zero(ds->v3_identity_digest))
2816 smartlist_add(known_v3_keys,
2817 tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
2818 keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
2819 SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
2820 smartlist_free(known_v3_keys);
2821 return keys;
2824 /** Called when we have received a networkstatus vote in <b>vote_body</b>.
2825 * Parse and validate it, and on success store it as a pending vote (which we
2826 * then return). Return NULL on failure. Sets *<b>msg_out</b> and
2827 * *<b>status_out</b> to an HTTP response and status code. (V3 authority
2828 * only) */
2829 pending_vote_t *
2830 dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
2832 networkstatus_t *vote;
2833 networkstatus_voter_info_t *vi;
2834 dir_server_t *ds;
2835 pending_vote_t *pending_vote = NULL;
2836 const char *end_of_vote = NULL;
2837 int any_failed = 0;
2838 tor_assert(vote_body);
2839 tor_assert(msg_out);
2840 tor_assert(status_out);
2842 if (!pending_vote_list)
2843 pending_vote_list = smartlist_new();
2844 *status_out = 0;
2845 *msg_out = NULL;
2847 again:
2848 vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
2849 NS_TYPE_VOTE);
2850 if (!end_of_vote)
2851 end_of_vote = vote_body + strlen(vote_body);
2852 if (!vote) {
2853 log_warn(LD_DIR, "Couldn't parse vote: length was %d",
2854 (int)strlen(vote_body));
2855 *msg_out = "Unable to parse vote";
2856 goto err;
2858 tor_assert(smartlist_len(vote->voters) == 1);
2859 vi = get_voter(vote);
2861 int any_sig_good = 0;
2862 SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
2863 if (sig->good_signature)
2864 any_sig_good = 1);
2865 tor_assert(any_sig_good);
2867 ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
2868 if (!ds) {
2869 char *keys = list_v3_auth_ids();
2870 log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
2871 "with authority key ID %s. "
2872 "This key ID is not recognized. Known v3 key IDs are: %s",
2873 vi->nickname, vi->address,
2874 hex_str(vi->identity_digest, DIGEST_LEN), keys);
2875 tor_free(keys);
2876 *msg_out = "Vote not from a recognized v3 authority";
2877 goto err;
2879 tor_assert(vote->cert);
2880 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2881 vote->cert->signing_key_digest)) {
2882 /* Hey, it's a new cert! */
2883 trusted_dirs_load_certs_from_string(
2884 vote->cert->cache_info.signed_descriptor_body,
2885 TRUSTED_DIRS_CERTS_SRC_FROM_VOTE, 1 /*flush*/);
2886 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2887 vote->cert->signing_key_digest)) {
2888 log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
2892 /* Is it for the right period? */
2893 if (vote->valid_after != voting_schedule.interval_starts) {
2894 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
2895 format_iso_time(tbuf1, vote->valid_after);
2896 format_iso_time(tbuf2, voting_schedule.interval_starts);
2897 log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
2898 "we were expecting %s", vi->address, tbuf1, tbuf2);
2899 *msg_out = "Bad valid-after time";
2900 goto err;
2903 /* Fetch any new router descriptors we just learned about */
2904 update_consensus_router_descriptor_downloads(time(NULL), 1, vote);
2906 /* Now see whether we already have a vote from this authority. */
2907 SMARTLIST_FOREACH_BEGIN(pending_vote_list, pending_vote_t *, v) {
2908 if (fast_memeq(v->vote->cert->cache_info.identity_digest,
2909 vote->cert->cache_info.identity_digest,
2910 DIGEST_LEN)) {
2911 networkstatus_voter_info_t *vi_old = get_voter(v->vote);
2912 if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
2913 /* Ah, it's the same vote. Not a problem. */
2914 log_info(LD_DIR, "Discarding a vote we already have (from %s).",
2915 vi->address);
2916 if (*status_out < 200)
2917 *status_out = 200;
2918 goto discard;
2919 } else if (v->vote->published < vote->published) {
2920 log_notice(LD_DIR, "Replacing an older pending vote from this "
2921 "directory (%s)", vi->address);
2922 cached_dir_decref(v->vote_body);
2923 networkstatus_vote_free(v->vote);
2924 v->vote_body = new_cached_dir(tor_strndup(vote_body,
2925 end_of_vote-vote_body),
2926 vote->published);
2927 v->vote = vote;
2928 if (end_of_vote &&
2929 !strcmpstart(end_of_vote, "network-status-version"))
2930 goto again;
2932 if (*status_out < 200)
2933 *status_out = 200;
2934 if (!*msg_out)
2935 *msg_out = "OK";
2936 return v;
2937 } else {
2938 *msg_out = "Already have a newer pending vote";
2939 goto err;
2942 } SMARTLIST_FOREACH_END(v);
2944 pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
2945 pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
2946 end_of_vote-vote_body),
2947 vote->published);
2948 pending_vote->vote = vote;
2949 smartlist_add(pending_vote_list, pending_vote);
2951 if (!strcmpstart(end_of_vote, "network-status-version ")) {
2952 vote_body = end_of_vote;
2953 goto again;
2956 goto done;
2958 err:
2959 any_failed = 1;
2960 if (!*msg_out)
2961 *msg_out = "Error adding vote";
2962 if (*status_out < 400)
2963 *status_out = 400;
2965 discard:
2966 networkstatus_vote_free(vote);
2968 if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
2969 vote_body = end_of_vote;
2970 goto again;
2973 done:
2975 if (*status_out < 200)
2976 *status_out = 200;
2977 if (!*msg_out) {
2978 if (!any_failed && !pending_vote) {
2979 *msg_out = "Duplicate discarded";
2980 } else {
2981 *msg_out = "ok";
2985 return any_failed ? NULL : pending_vote;
2988 /** Try to compute a v3 networkstatus consensus from the currently pending
2989 * votes. Return 0 on success, -1 on failure. Store the consensus in
2990 * pending_consensus: it won't be ready to be published until we have
2991 * everybody else's signatures collected too. (V3 Authority only) */
2992 static int
2993 dirvote_compute_consensuses(void)
2995 /* Have we got enough votes to try? */
2996 int n_votes, n_voters, n_vote_running = 0;
2997 smartlist_t *votes = NULL, *votestrings = NULL;
2998 char *consensus_body = NULL, *signatures = NULL, *votefile;
2999 networkstatus_t *consensus = NULL;
3000 authority_cert_t *my_cert;
3001 pending_consensus_t pending[N_CONSENSUS_FLAVORS];
3002 int flav;
3004 memset(pending, 0, sizeof(pending));
3006 if (!pending_vote_list)
3007 pending_vote_list = smartlist_new();
3009 n_voters = get_n_authorities(V3_DIRINFO);
3010 n_votes = smartlist_len(pending_vote_list);
3011 if (n_votes <= n_voters/2) {
3012 log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
3013 "%d of %d", n_votes, n_voters/2+1);
3014 goto err;
3016 tor_assert(pending_vote_list);
3017 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
3018 if (smartlist_contains_string(v->vote->known_flags, "Running"))
3019 n_vote_running++;
3021 if (!n_vote_running) {
3022 /* See task 1066. */
3023 log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
3024 "and publishing a consensus without Running nodes "
3025 "would make many clients stop working. Not "
3026 "generating a consensus!");
3027 goto err;
3030 if (!(my_cert = get_my_v3_authority_cert())) {
3031 log_warn(LD_DIR, "Can't generate consensus without a certificate.");
3032 goto err;
3035 votes = smartlist_new();
3036 votestrings = smartlist_new();
3037 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
3039 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
3040 c->bytes = v->vote_body->dir;
3041 c->len = v->vote_body->dir_len;
3042 smartlist_add(votestrings, c); /* collect strings to write to disk */
3044 smartlist_add(votes, v->vote); /* collect votes to compute consensus */
3047 votefile = get_datadir_fname("v3-status-votes");
3048 write_chunks_to_file(votefile, votestrings, 0, 0);
3049 tor_free(votefile);
3050 SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
3051 smartlist_free(votestrings);
3054 char legacy_dbuf[DIGEST_LEN];
3055 crypto_pk_t *legacy_sign=NULL;
3056 char *legacy_id_digest = NULL;
3057 int n_generated = 0;
3058 if (get_options()->V3AuthUseLegacyKey) {
3059 authority_cert_t *cert = get_my_v3_legacy_cert();
3060 legacy_sign = get_my_v3_legacy_signing_key();
3061 if (cert) {
3062 if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
3063 log_warn(LD_BUG,
3064 "Unable to compute digest of legacy v3 identity key");
3065 } else {
3066 legacy_id_digest = legacy_dbuf;
3071 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
3072 const char *flavor_name = networkstatus_get_flavor_name(flav);
3073 consensus_body = networkstatus_compute_consensus(
3074 votes, n_voters,
3075 my_cert->identity_key,
3076 get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
3077 flav);
3079 if (!consensus_body) {
3080 log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
3081 flavor_name);
3082 continue;
3084 consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
3085 NS_TYPE_CONSENSUS);
3086 if (!consensus) {
3087 log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
3088 flavor_name);
3089 tor_free(consensus_body);
3090 continue;
3093 /* 'Check' our own signature, to mark it valid. */
3094 networkstatus_check_consensus_signature(consensus, -1);
3096 pending[flav].body = consensus_body;
3097 pending[flav].consensus = consensus;
3098 n_generated++;
3099 consensus_body = NULL;
3100 consensus = NULL;
3102 if (!n_generated) {
3103 log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
3104 goto err;
3108 signatures = get_detached_signatures_from_pending_consensuses(
3109 pending, N_CONSENSUS_FLAVORS);
3111 if (!signatures) {
3112 log_warn(LD_DIR, "Couldn't extract signatures.");
3113 goto err;
3116 dirvote_clear_pending_consensuses();
3117 memcpy(pending_consensuses, pending, sizeof(pending));
3119 tor_free(pending_consensus_signatures);
3120 pending_consensus_signatures = signatures;
3122 if (pending_consensus_signature_list) {
3123 int n_sigs = 0;
3124 /* we may have gotten signatures for this consensus before we built
3125 * it ourself. Add them now. */
3126 SMARTLIST_FOREACH_BEGIN(pending_consensus_signature_list, char *, sig) {
3127 const char *msg = NULL;
3128 int r = dirvote_add_signatures_to_all_pending_consensuses(sig,
3129 "pending", &msg);
3130 if (r >= 0)
3131 n_sigs += r;
3132 else
3133 log_warn(LD_DIR,
3134 "Could not add queued signature to new consensus: %s",
3135 msg);
3136 tor_free(sig);
3137 } SMARTLIST_FOREACH_END(sig);
3138 if (n_sigs)
3139 log_notice(LD_DIR, "Added %d pending signatures while building "
3140 "consensus.", n_sigs);
3141 smartlist_clear(pending_consensus_signature_list);
3144 log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
3146 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
3147 ROUTER_PURPOSE_GENERAL,
3148 V3_DIRINFO,
3149 pending_consensus_signatures,
3150 strlen(pending_consensus_signatures), 0);
3151 log_notice(LD_DIR, "Signature(s) posted.");
3153 smartlist_free(votes);
3154 return 0;
3155 err:
3156 smartlist_free(votes);
3157 tor_free(consensus_body);
3158 tor_free(signatures);
3159 networkstatus_vote_free(consensus);
3161 return -1;
3164 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3165 * signatures on the currently pending consensus. Add them to <b>pc</b>
3166 * as appropriate. Return the number of signatures added. (?) */
3167 static int
3168 dirvote_add_signatures_to_pending_consensus(
3169 pending_consensus_t *pc,
3170 ns_detached_signatures_t *sigs,
3171 const char *source,
3172 int severity,
3173 const char **msg_out)
3175 const char *flavor_name;
3176 int r = -1;
3178 /* Only call if we have a pending consensus right now. */
3179 tor_assert(pc->consensus);
3180 tor_assert(pc->body);
3181 tor_assert(pending_consensus_signatures);
3183 flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
3184 *msg_out = NULL;
3187 smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
3188 log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
3189 sig_list ? smartlist_len(sig_list) : 0, flavor_name);
3191 r = networkstatus_add_detached_signatures(pc->consensus, sigs,
3192 source, severity, msg_out);
3193 log_info(LD_DIR,"Added %d signatures to consensus.", r);
3195 if (r >= 1) {
3196 char *new_signatures =
3197 networkstatus_format_signatures(pc->consensus, 0);
3198 char *dst, *dst_end;
3199 size_t new_consensus_len;
3200 if (!new_signatures) {
3201 *msg_out = "No signatures to add";
3202 goto err;
3204 new_consensus_len =
3205 strlen(pc->body) + strlen(new_signatures) + 1;
3206 pc->body = tor_realloc(pc->body, new_consensus_len);
3207 dst_end = pc->body + new_consensus_len;
3208 dst = strstr(pc->body, "directory-signature ");
3209 tor_assert(dst);
3210 strlcpy(dst, new_signatures, dst_end-dst);
3212 /* We remove this block once it has failed to crash for a while. But
3213 * unless it shows up in profiles, we're probably better leaving it in,
3214 * just in case we break detached signature processing at some point. */
3216 networkstatus_t *v = networkstatus_parse_vote_from_string(
3217 pc->body, NULL,
3218 NS_TYPE_CONSENSUS);
3219 tor_assert(v);
3220 networkstatus_vote_free(v);
3222 *msg_out = "Signatures added";
3223 tor_free(new_signatures);
3224 } else if (r == 0) {
3225 *msg_out = "Signatures ignored";
3226 } else {
3227 goto err;
3230 goto done;
3231 err:
3232 if (!*msg_out)
3233 *msg_out = "Unrecognized error while adding detached signatures.";
3234 done:
3235 return r;
3238 static int
3239 dirvote_add_signatures_to_all_pending_consensuses(
3240 const char *detached_signatures_body,
3241 const char *source,
3242 const char **msg_out)
3244 int r=0, i, n_added = 0, errors = 0;
3245 ns_detached_signatures_t *sigs;
3246 tor_assert(detached_signatures_body);
3247 tor_assert(msg_out);
3248 tor_assert(pending_consensus_signatures);
3250 if (!(sigs = networkstatus_parse_detached_signatures(
3251 detached_signatures_body, NULL))) {
3252 *msg_out = "Couldn't parse detached signatures.";
3253 goto err;
3256 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3257 int res;
3258 int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
3259 pending_consensus_t *pc = &pending_consensuses[i];
3260 if (!pc->consensus)
3261 continue;
3262 res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
3263 severity, msg_out);
3264 if (res < 0)
3265 errors++;
3266 else
3267 n_added += res;
3270 if (errors && !n_added) {
3271 r = -1;
3272 goto err;
3275 if (n_added && pending_consensuses[FLAV_NS].consensus) {
3276 char *new_detached =
3277 get_detached_signatures_from_pending_consensuses(
3278 pending_consensuses, N_CONSENSUS_FLAVORS);
3279 if (new_detached) {
3280 tor_free(pending_consensus_signatures);
3281 pending_consensus_signatures = new_detached;
3285 r = n_added;
3286 goto done;
3287 err:
3288 if (!*msg_out)
3289 *msg_out = "Unrecognized error while adding detached signatures.";
3290 done:
3291 ns_detached_signatures_free(sigs);
3292 /* XXXX NM Check how return is used. We can now have an error *and*
3293 signatures added. */
3294 return r;
3297 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3298 * signatures on the currently pending consensus. Add them to the pending
3299 * consensus (if we have one); otherwise queue them until we have a
3300 * consensus. Return negative on failure, nonnegative on success. */
3302 dirvote_add_signatures(const char *detached_signatures_body,
3303 const char *source,
3304 const char **msg)
3306 if (pending_consensuses[FLAV_NS].consensus) {
3307 log_notice(LD_DIR, "Got a signature from %s. "
3308 "Adding it to the pending consensus.", source);
3309 return dirvote_add_signatures_to_all_pending_consensuses(
3310 detached_signatures_body, source, msg);
3311 } else {
3312 log_notice(LD_DIR, "Got a signature from %s. "
3313 "Queuing it for the next consensus.", source);
3314 if (!pending_consensus_signature_list)
3315 pending_consensus_signature_list = smartlist_new();
3316 smartlist_add(pending_consensus_signature_list,
3317 tor_strdup(detached_signatures_body));
3318 *msg = "Signature queued";
3319 return 0;
3323 /** Replace the consensus that we're currently serving with the one that we've
3324 * been building. (V3 Authority only) */
3325 static int
3326 dirvote_publish_consensus(void)
3328 int i;
3330 /* Now remember all the other consensuses as if we were a directory cache. */
3331 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3332 pending_consensus_t *pending = &pending_consensuses[i];
3333 const char *name;
3334 name = networkstatus_get_flavor_name(i);
3335 tor_assert(name);
3336 if (!pending->consensus ||
3337 networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
3338 log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
3339 continue;
3342 if (networkstatus_set_current_consensus(pending->body, name, 0))
3343 log_warn(LD_DIR, "Error publishing %s consensus", name);
3344 else
3345 log_notice(LD_DIR, "Published %s consensus", name);
3348 return 0;
3351 /** Release all static storage held in dirvote.c */
3352 void
3353 dirvote_free_all(void)
3355 dirvote_clear_votes(1);
3356 /* now empty as a result of dirvote_clear_votes(). */
3357 smartlist_free(pending_vote_list);
3358 pending_vote_list = NULL;
3359 smartlist_free(previous_vote_list);
3360 previous_vote_list = NULL;
3362 dirvote_clear_pending_consensuses();
3363 tor_free(pending_consensus_signatures);
3364 if (pending_consensus_signature_list) {
3365 /* now empty as a result of dirvote_clear_votes(). */
3366 smartlist_free(pending_consensus_signature_list);
3367 pending_consensus_signature_list = NULL;
3371 /* ====
3372 * Access to pending items.
3373 * ==== */
3375 /** Return the body of the consensus that we're currently trying to build. */
3376 const char *
3377 dirvote_get_pending_consensus(consensus_flavor_t flav)
3379 tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
3380 return pending_consensuses[flav].body;
3383 /** Return the signatures that we know for the consensus that we're currently
3384 * trying to build. */
3385 const char *
3386 dirvote_get_pending_detached_signatures(void)
3388 return pending_consensus_signatures;
3391 /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
3392 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
3393 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
3394 * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
3395 * false, do not consider any votes for a consensus that's already been built.
3396 * If <b>include_pending</b> is false, do not consider any votes for the
3397 * consensus that's in progress. May return NULL if we have no vote for the
3398 * authority in question. */
3399 const cached_dir_t *
3400 dirvote_get_vote(const char *fp, int flags)
3402 int by_id = flags & DGV_BY_ID;
3403 const int include_pending = flags & DGV_INCLUDE_PENDING;
3404 const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
3406 if (!pending_vote_list && !previous_vote_list)
3407 return NULL;
3408 if (fp == NULL) {
3409 authority_cert_t *c = get_my_v3_authority_cert();
3410 if (c) {
3411 fp = c->cache_info.identity_digest;
3412 by_id = 1;
3413 } else
3414 return NULL;
3416 if (by_id) {
3417 if (pending_vote_list && include_pending) {
3418 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3419 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3420 return pv->vote_body);
3422 if (previous_vote_list && include_previous) {
3423 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3424 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3425 return pv->vote_body);
3427 } else {
3428 if (pending_vote_list && include_pending) {
3429 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3430 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3431 return pv->vote_body);
3433 if (previous_vote_list && include_previous) {
3434 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3435 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3436 return pv->vote_body);
3439 return NULL;
3442 /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
3443 * according to <b>consensus_method</b>.
3445 microdesc_t *
3446 dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
3448 microdesc_t *result = NULL;
3449 char *key = NULL, *summary = NULL, *family = NULL;
3450 size_t keylen;
3451 smartlist_t *chunks = smartlist_new();
3452 char *output = NULL;
3454 if (crypto_pk_write_public_key_to_string(ri->onion_pkey, &key, &keylen)<0)
3455 goto done;
3456 summary = policy_summarize(ri->exit_policy, AF_INET);
3457 if (ri->declared_family)
3458 family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
3460 smartlist_add_asprintf(chunks, "onion-key\n%s", key);
3462 if (consensus_method >= MIN_METHOD_FOR_NTOR_KEY &&
3463 ri->onion_curve25519_pkey) {
3464 char kbuf[128];
3465 base64_encode(kbuf, sizeof(kbuf),
3466 (const char*)ri->onion_curve25519_pkey->public_key,
3467 CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
3468 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
3471 if (consensus_method >= MIN_METHOD_FOR_A_LINES &&
3472 !tor_addr_is_null(&ri->ipv6_addr) && ri->ipv6_orport)
3473 smartlist_add_asprintf(chunks, "a %s\n",
3474 fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
3476 if (family)
3477 smartlist_add_asprintf(chunks, "family %s\n", family);
3479 if (summary && strcmp(summary, "reject 1-65535"))
3480 smartlist_add_asprintf(chunks, "p %s\n", summary);
3482 if (consensus_method >= MIN_METHOD_FOR_P6_LINES &&
3483 ri->ipv6_exit_policy) {
3484 /* XXXX024 This doesn't match proposal 208, which says these should
3485 * be taken unchanged from the routerinfo. That's bogosity, IMO:
3486 * the proposal should have said to do this instead.*/
3487 char *p6 = write_short_policy(ri->ipv6_exit_policy);
3488 if (p6 && strcmp(p6, "reject 1-65535"))
3489 smartlist_add_asprintf(chunks, "p6 %s\n", p6);
3490 tor_free(p6);
3493 if (consensus_method >= MIN_METHOD_FOR_ID_HASH_IN_MD) {
3494 char idbuf[ED25519_BASE64_LEN+1];
3495 const char *keytype;
3496 if (consensus_method >= MIN_METHOD_FOR_ED25519_ID_IN_MD &&
3497 ri->signing_key_cert &&
3498 ri->signing_key_cert->signing_key_included) {
3499 keytype = "ed25519";
3500 ed25519_public_to_base64(idbuf, &ri->signing_key_cert->signing_key);
3501 } else {
3502 keytype = "rsa1024";
3503 digest_to_base64(idbuf, ri->cache_info.identity_digest);
3505 smartlist_add_asprintf(chunks, "id %s %s\n", keytype, idbuf);
3508 output = smartlist_join_strings(chunks, "", 0, NULL);
3511 smartlist_t *lst = microdescs_parse_from_string(output,
3512 output+strlen(output), 0,
3513 SAVED_NOWHERE, NULL);
3514 if (smartlist_len(lst) != 1) {
3515 log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
3516 SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
3517 smartlist_free(lst);
3518 goto done;
3520 result = smartlist_get(lst, 0);
3521 smartlist_free(lst);
3524 done:
3525 tor_free(output);
3526 tor_free(key);
3527 tor_free(summary);
3528 tor_free(family);
3529 if (chunks) {
3530 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
3531 smartlist_free(chunks);
3533 return result;
3536 /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
3537 * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
3538 * in <b>out</b>. Return -1 on failure and the number of characters written
3539 * on success. */
3540 ssize_t
3541 dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
3542 const microdesc_t *md,
3543 int consensus_method_low,
3544 int consensus_method_high)
3546 ssize_t ret = -1;
3547 char d64[BASE64_DIGEST256_LEN+1];
3548 char *microdesc_consensus_methods =
3549 make_consensus_method_list(consensus_method_low,
3550 consensus_method_high,
3551 ",");
3552 tor_assert(microdesc_consensus_methods);
3554 if (digest256_to_base64(d64, md->digest)<0)
3555 goto out;
3557 if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
3558 microdesc_consensus_methods, d64)<0)
3559 goto out;
3561 ret = strlen(out_buf);
3563 out:
3564 tor_free(microdesc_consensus_methods);
3565 return ret;
3568 /** Array of start and end of consensus methods used for supported
3569 microdescriptor formats. */
3570 static const struct consensus_method_range_t {
3571 int low;
3572 int high;
3573 } microdesc_consensus_methods[] = {
3574 {MIN_SUPPORTED_CONSENSUS_METHOD, MIN_METHOD_FOR_A_LINES - 1},
3575 {MIN_METHOD_FOR_A_LINES, MIN_METHOD_FOR_P6_LINES - 1},
3576 {MIN_METHOD_FOR_P6_LINES, MIN_METHOD_FOR_NTOR_KEY - 1},
3577 {MIN_METHOD_FOR_NTOR_KEY, MIN_METHOD_FOR_ID_HASH_IN_MD - 1},
3578 {MIN_METHOD_FOR_ID_HASH_IN_MD, MIN_METHOD_FOR_ED25519_ID_IN_MD - 1},
3579 {MIN_METHOD_FOR_ED25519_ID_IN_MD, MAX_SUPPORTED_CONSENSUS_METHOD},
3580 {-1, -1}
3583 /** Helper type used when generating the microdescriptor lines in a directory
3584 * vote. */
3585 typedef struct microdesc_vote_line_t {
3586 int low;
3587 int high;
3588 microdesc_t *md;
3589 struct microdesc_vote_line_t *next;
3590 } microdesc_vote_line_t;
3592 /** Generate and return a linked list of all the lines that should appear to
3593 * describe a router's microdescriptor versions in a directory vote.
3594 * Add the generated microdescriptors to <b>microdescriptors_out</b>. */
3595 vote_microdesc_hash_t *
3596 dirvote_format_all_microdesc_vote_lines(const routerinfo_t *ri, time_t now,
3597 smartlist_t *microdescriptors_out)
3599 const struct consensus_method_range_t *cmr;
3600 microdesc_vote_line_t *entries = NULL, *ep;
3601 vote_microdesc_hash_t *result = NULL;
3603 /* Generate the microdescriptors. */
3604 for (cmr = microdesc_consensus_methods;
3605 cmr->low != -1 && cmr->high != -1;
3606 cmr++) {
3607 microdesc_t *md = dirvote_create_microdescriptor(ri, cmr->low);
3608 if (md) {
3609 microdesc_vote_line_t *e =
3610 tor_malloc_zero(sizeof(microdesc_vote_line_t));
3611 e->md = md;
3612 e->low = cmr->low;
3613 e->high = cmr->high;
3614 e->next = entries;
3615 entries = e;
3619 /* Compress adjacent identical ones */
3620 for (ep = entries; ep; ep = ep->next) {
3621 while (ep->next &&
3622 fast_memeq(ep->md->digest, ep->next->md->digest, DIGEST256_LEN) &&
3623 ep->low == ep->next->high + 1) {
3624 microdesc_vote_line_t *next = ep->next;
3625 ep->low = next->low;
3626 microdesc_free(next->md);
3627 ep->next = next->next;
3628 tor_free(next);
3632 /* Format them into vote_microdesc_hash_t, and add to microdescriptors_out.*/
3633 while ((ep = entries)) {
3634 char buf[128];
3635 vote_microdesc_hash_t *h;
3636 dirvote_format_microdesc_vote_line(buf, sizeof(buf), ep->md,
3637 ep->low, ep->high);
3638 h = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
3639 h->microdesc_hash_line = tor_strdup(buf);
3640 h->next = result;
3641 result = h;
3642 ep->md->last_listed = now;
3643 smartlist_add(microdescriptors_out, ep->md);
3644 entries = ep->next;
3645 tor_free(ep);
3648 return result;
3651 /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
3652 * the digest algorithm <b>alg</b>, decode it and copy it into
3653 * <b>digest256_out</b> and return 0. Otherwise return -1. */
3655 vote_routerstatus_find_microdesc_hash(char *digest256_out,
3656 const vote_routerstatus_t *vrs,
3657 int method,
3658 digest_algorithm_t alg)
3660 /* XXXX only returns the sha256 method. */
3661 const vote_microdesc_hash_t *h;
3662 char mstr[64];
3663 size_t mlen;
3664 char dstr[64];
3666 tor_snprintf(mstr, sizeof(mstr), "%d", method);
3667 mlen = strlen(mstr);
3668 tor_snprintf(dstr, sizeof(dstr), " %s=",
3669 crypto_digest_algorithm_get_name(alg));
3671 for (h = vrs->microdesc; h; h = h->next) {
3672 const char *cp = h->microdesc_hash_line;
3673 size_t num_len;
3674 /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
3675 * the first part. */
3676 while (1) {
3677 num_len = strspn(cp, "1234567890");
3678 if (num_len == mlen && fast_memeq(mstr, cp, mlen)) {
3679 /* This is the line. */
3680 char buf[BASE64_DIGEST256_LEN+1];
3681 /* XXXX ignores extraneous stuff if the digest is too long. This
3682 * seems harmless enough, right? */
3683 cp = strstr(cp, dstr);
3684 if (!cp)
3685 return -1;
3686 cp += strlen(dstr);
3687 strlcpy(buf, cp, sizeof(buf));
3688 return digest256_from_base64(digest256_out, buf);
3690 if (num_len == 0 || cp[num_len] != ',')
3691 break;
3692 cp += num_len + 1;
3695 return -1;