Merge remote-tracking branch 'karsten/task-18460-2' into maint-0.2.8
[tor.git] / src / or / dirvote.c
blob9854af7d7f16ce307f92340b533ddb454b9d00c5
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2016, 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);
58 /* =====
59 * Voting
60 * =====*/
62 /** Return a new string containing the string representation of the vote in
63 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
64 * For v3 authorities. */
65 STATIC char *
66 format_networkstatus_vote(crypto_pk_t *private_signing_key,
67 networkstatus_t *v3_ns)
69 smartlist_t *chunks = smartlist_new();
70 const char *client_versions = NULL, *server_versions = NULL;
71 char *packages = NULL;
72 char fingerprint[FINGERPRINT_LEN+1];
73 char digest[DIGEST_LEN];
74 uint32_t addr;
75 char *client_versions_line = NULL, *server_versions_line = NULL;
76 networkstatus_voter_info_t *voter;
77 char *status = NULL;
79 tor_assert(private_signing_key);
80 tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
82 voter = smartlist_get(v3_ns->voters, 0);
84 addr = voter->addr;
86 base16_encode(fingerprint, sizeof(fingerprint),
87 v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
88 client_versions = v3_ns->client_versions;
89 server_versions = v3_ns->server_versions;
91 if (client_versions) {
92 tor_asprintf(&client_versions_line, "client-versions %s\n",
93 client_versions);
94 } else {
95 client_versions_line = tor_strdup("");
97 if (server_versions) {
98 tor_asprintf(&server_versions_line, "server-versions %s\n",
99 server_versions);
100 } else {
101 server_versions_line = tor_strdup("");
104 if (v3_ns->package_lines) {
105 smartlist_t *tmp = smartlist_new();
106 SMARTLIST_FOREACH(v3_ns->package_lines, const char *, p,
107 if (validate_recommended_package_line(p))
108 smartlist_add_asprintf(tmp, "package %s\n", p));
109 packages = smartlist_join_strings(tmp, "", 0, NULL);
110 SMARTLIST_FOREACH(tmp, char *, cp, tor_free(cp));
111 smartlist_free(tmp);
112 } else {
113 packages = tor_strdup("");
117 char published[ISO_TIME_LEN+1];
118 char va[ISO_TIME_LEN+1];
119 char fu[ISO_TIME_LEN+1];
120 char vu[ISO_TIME_LEN+1];
121 char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
122 /* XXXX Abstraction violation: should be pulling a field out of v3_ns.*/
123 char *flag_thresholds = dirserv_get_flag_thresholds_line();
124 char *params;
125 authority_cert_t *cert = v3_ns->cert;
126 char *methods =
127 make_consensus_method_list(MIN_SUPPORTED_CONSENSUS_METHOD,
128 MAX_SUPPORTED_CONSENSUS_METHOD, " ");
129 format_iso_time(published, v3_ns->published);
130 format_iso_time(va, v3_ns->valid_after);
131 format_iso_time(fu, v3_ns->fresh_until);
132 format_iso_time(vu, v3_ns->valid_until);
134 if (v3_ns->net_params)
135 params = smartlist_join_strings(v3_ns->net_params, " ", 0, NULL);
136 else
137 params = tor_strdup("");
139 tor_assert(cert);
140 smartlist_add_asprintf(chunks,
141 "network-status-version 3\n"
142 "vote-status %s\n"
143 "consensus-methods %s\n"
144 "published %s\n"
145 "valid-after %s\n"
146 "fresh-until %s\n"
147 "valid-until %s\n"
148 "voting-delay %d %d\n"
149 "%s%s" /* versions */
150 "%s" /* packages */
151 "known-flags %s\n"
152 "flag-thresholds %s\n"
153 "params %s\n"
154 "dir-source %s %s %s %s %d %d\n"
155 "contact %s\n",
156 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
157 methods,
158 published, va, fu, vu,
159 v3_ns->vote_seconds, v3_ns->dist_seconds,
160 client_versions_line,
161 server_versions_line,
162 packages,
163 flags,
164 flag_thresholds,
165 params,
166 voter->nickname, fingerprint, voter->address,
167 fmt_addr32(addr), voter->dir_port, voter->or_port,
168 voter->contact);
170 tor_free(params);
171 tor_free(flags);
172 tor_free(flag_thresholds);
173 tor_free(methods);
175 if (!tor_digest_is_zero(voter->legacy_id_digest)) {
176 char fpbuf[HEX_DIGEST_LEN+1];
177 base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
178 smartlist_add_asprintf(chunks, "legacy-dir-key %s\n", fpbuf);
181 smartlist_add(chunks, tor_strndup(cert->cache_info.signed_descriptor_body,
182 cert->cache_info.signed_descriptor_len));
185 SMARTLIST_FOREACH_BEGIN(v3_ns->routerstatus_list, vote_routerstatus_t *,
186 vrs) {
187 char *rsf;
188 vote_microdesc_hash_t *h;
189 rsf = routerstatus_format_entry(&vrs->status,
190 vrs->version, NS_V3_VOTE, vrs);
191 if (rsf)
192 smartlist_add(chunks, rsf);
194 for (h = vrs->microdesc; h; h = h->next) {
195 smartlist_add(chunks, tor_strdup(h->microdesc_hash_line));
197 } SMARTLIST_FOREACH_END(vrs);
199 smartlist_add(chunks, tor_strdup("directory-footer\n"));
201 /* The digest includes everything up through the space after
202 * directory-signature. (Yuck.) */
203 crypto_digest_smartlist(digest, DIGEST_LEN, chunks,
204 "directory-signature ", DIGEST_SHA1);
207 char signing_key_fingerprint[FINGERPRINT_LEN+1];
208 if (crypto_pk_get_fingerprint(private_signing_key,
209 signing_key_fingerprint, 0)<0) {
210 log_warn(LD_BUG, "Unable to get fingerprint for signing key");
211 goto err;
214 smartlist_add_asprintf(chunks, "directory-signature %s %s\n", fingerprint,
215 signing_key_fingerprint);
218 note_crypto_pk_op(SIGN_DIR);
220 char *sig = router_get_dirobj_signature(digest, DIGEST_LEN,
221 private_signing_key);
222 if (!sig) {
223 log_warn(LD_BUG, "Unable to sign networkstatus vote.");
224 goto err;
226 smartlist_add(chunks, sig);
229 status = smartlist_join_strings(chunks, "", 0, NULL);
232 networkstatus_t *v;
233 if (!(v = networkstatus_parse_vote_from_string(status, NULL,
234 v3_ns->type))) {
235 log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
236 "<<%s>>",
237 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
238 goto err;
240 networkstatus_vote_free(v);
243 goto done;
245 err:
246 tor_free(status);
247 done:
248 tor_free(client_versions_line);
249 tor_free(server_versions_line);
250 tor_free(packages);
252 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
253 smartlist_free(chunks);
254 return status;
257 /* =====
258 * Consensus generation
259 * ===== */
261 /** Given a vote <b>vote</b> (not a consensus!), return its associated
262 * networkstatus_voter_info_t. */
263 static networkstatus_voter_info_t *
264 get_voter(const networkstatus_t *vote)
266 tor_assert(vote);
267 tor_assert(vote->type == NS_TYPE_VOTE);
268 tor_assert(vote->voters);
269 tor_assert(smartlist_len(vote->voters) == 1);
270 return smartlist_get(vote->voters, 0);
273 /** Return the signature made by <b>voter</b> using the algorithm
274 * <b>alg</b>, or NULL if none is found. */
275 document_signature_t *
276 voter_get_sig_by_algorithm(const networkstatus_voter_info_t *voter,
277 digest_algorithm_t alg)
279 if (!voter->sigs)
280 return NULL;
281 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
282 if (sig->alg == alg)
283 return sig);
284 return NULL;
287 /** Temporary structure used in constructing a list of dir-source entries
288 * for a consensus. One of these is generated for every vote, and one more
289 * for every legacy key in each vote. */
290 typedef struct dir_src_ent_t {
291 networkstatus_t *v;
292 const char *digest;
293 int is_legacy;
294 } dir_src_ent_t;
296 /** Helper for sorting networkstatus_t votes (not consensuses) by the
297 * hash of their voters' identity digests. */
298 static int
299 compare_votes_by_authority_id_(const void **_a, const void **_b)
301 const networkstatus_t *a = *_a, *b = *_b;
302 return fast_memcmp(get_voter(a)->identity_digest,
303 get_voter(b)->identity_digest, DIGEST_LEN);
306 /** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
307 * their identity digests, and return -1, 0, or 1 depending on their
308 * ordering */
309 static int
310 compare_dir_src_ents_by_authority_id_(const void **_a, const void **_b)
312 const dir_src_ent_t *a = *_a, *b = *_b;
313 const networkstatus_voter_info_t *a_v = get_voter(a->v),
314 *b_v = get_voter(b->v);
315 const char *a_id, *b_id;
316 a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
317 b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;
319 return fast_memcmp(a_id, b_id, DIGEST_LEN);
322 /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
323 * that occurs more than <b>min</b> times. */
324 static void
325 get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
327 char *cur = NULL;
328 int count = 0;
329 SMARTLIST_FOREACH_BEGIN(in, char *, cp) {
330 if (cur && !strcmp(cp, cur)) {
331 ++count;
332 } else {
333 if (count > min)
334 smartlist_add(out, cur);
335 cur = cp;
336 count = 1;
338 } SMARTLIST_FOREACH_END(cp);
339 if (count > min)
340 smartlist_add(out, cur);
343 /** Given a sorted list of strings <b>lst</b>, return the member that appears
344 * most. Break ties in favor of later-occurring members. */
345 #define get_most_frequent_member(lst) \
346 smartlist_get_most_frequent_string(lst)
348 /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
349 * that come from the same routerinfo, with the same derived elements.
351 static int
352 compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
354 int r;
355 tor_assert(a);
356 tor_assert(b);
358 if ((r = fast_memcmp(a->status.identity_digest, b->status.identity_digest,
359 DIGEST_LEN)))
360 return r;
361 if ((r = fast_memcmp(a->status.descriptor_digest,
362 b->status.descriptor_digest,
363 DIGEST_LEN)))
364 return r;
365 if ((r = (int)(b->status.published_on - a->status.published_on)))
366 return r;
367 if ((r = strcmp(b->status.nickname, a->status.nickname)))
368 return r;
369 if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
370 return r;
371 if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
372 return r;
373 if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
374 return r;
375 return 0;
378 /** Helper for sorting routerlists based on compare_vote_rs. */
379 static int
380 compare_vote_rs_(const void **_a, const void **_b)
382 const vote_routerstatus_t *a = *_a, *b = *_b;
383 return compare_vote_rs(a,b);
386 /** Helper for sorting OR ports. */
387 static int
388 compare_orports_(const void **_a, const void **_b)
390 const tor_addr_port_t *a = *_a, *b = *_b;
391 int r;
393 if ((r = tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
394 return r;
395 if ((r = (((int) b->port) - ((int) a->port))))
396 return r;
398 return 0;
401 /** Given a list of vote_routerstatus_t, all for the same router identity,
402 * return whichever is most frequent, breaking ties in favor of more
403 * recently published vote_routerstatus_t and in case of ties there,
404 * in favor of smaller descriptor digest.
406 static vote_routerstatus_t *
407 compute_routerstatus_consensus(smartlist_t *votes, int consensus_method,
408 char *microdesc_digest256_out,
409 tor_addr_port_t *best_alt_orport_out)
411 vote_routerstatus_t *most = NULL, *cur = NULL;
412 int most_n = 0, cur_n = 0;
413 time_t most_published = 0;
415 /* compare_vote_rs_() sorts the items by identity digest (all the same),
416 * then by SD digest. That way, if we have a tie that the published_on
417 * date cannot tie, we use the descriptor with the smaller digest.
419 smartlist_sort(votes, compare_vote_rs_);
420 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
421 if (cur && !compare_vote_rs(cur, rs)) {
422 ++cur_n;
423 } else {
424 if (cur && (cur_n > most_n ||
425 (cur_n == most_n &&
426 cur->status.published_on > most_published))) {
427 most = cur;
428 most_n = cur_n;
429 most_published = cur->status.published_on;
431 cur_n = 1;
432 cur = rs;
434 } SMARTLIST_FOREACH_END(rs);
436 if (cur_n > most_n ||
437 (cur && cur_n == most_n && cur->status.published_on > most_published)) {
438 most = cur;
439 most_n = cur_n;
440 most_published = cur->status.published_on;
443 tor_assert(most);
445 /* If we're producing "a" lines, vote on potential alternative (sets
446 * of) OR port(s) in the winning routerstatuses.
448 * XXX prop186 There's at most one alternative OR port (_the_ IPv6
449 * port) for now. */
450 if (consensus_method >= MIN_METHOD_FOR_A_LINES && best_alt_orport_out) {
451 smartlist_t *alt_orports = smartlist_new();
452 const tor_addr_port_t *most_alt_orport = NULL;
454 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
455 tor_assert(rs);
456 if (compare_vote_rs(most, rs) == 0 &&
457 !tor_addr_is_null(&rs->status.ipv6_addr)
458 && rs->status.ipv6_orport) {
459 smartlist_add(alt_orports, tor_addr_port_new(&rs->status.ipv6_addr,
460 rs->status.ipv6_orport));
462 } SMARTLIST_FOREACH_END(rs);
464 smartlist_sort(alt_orports, compare_orports_);
465 most_alt_orport = smartlist_get_most_frequent(alt_orports,
466 compare_orports_);
467 if (most_alt_orport) {
468 memcpy(best_alt_orport_out, most_alt_orport, sizeof(tor_addr_port_t));
469 log_debug(LD_DIR, "\"a\" line winner for %s is %s",
470 most->status.nickname,
471 fmt_addrport(&most_alt_orport->addr, most_alt_orport->port));
474 SMARTLIST_FOREACH(alt_orports, tor_addr_port_t *, ap, tor_free(ap));
475 smartlist_free(alt_orports);
478 if (microdesc_digest256_out) {
479 smartlist_t *digests = smartlist_new();
480 const uint8_t *best_microdesc_digest;
481 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
482 char d[DIGEST256_LEN];
483 if (compare_vote_rs(rs, most))
484 continue;
485 if (!vote_routerstatus_find_microdesc_hash(d, rs, consensus_method,
486 DIGEST_SHA256))
487 smartlist_add(digests, tor_memdup(d, sizeof(d)));
488 } SMARTLIST_FOREACH_END(rs);
489 smartlist_sort_digests256(digests);
490 best_microdesc_digest = smartlist_get_most_frequent_digest256(digests);
491 if (best_microdesc_digest)
492 memcpy(microdesc_digest256_out, best_microdesc_digest, DIGEST256_LEN);
493 SMARTLIST_FOREACH(digests, char *, cp, tor_free(cp));
494 smartlist_free(digests);
497 return most;
500 /** Sorting helper: compare two strings based on their values as base-ten
501 * positive integers. (Non-integers are treated as prior to all integers, and
502 * compared lexically.) */
503 static int
504 cmp_int_strings_(const void **_a, const void **_b)
506 const char *a = *_a, *b = *_b;
507 int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
508 int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
509 if (ai<bi) {
510 return -1;
511 } else if (ai==bi) {
512 if (ai == 0) /* Parsing failed. */
513 return strcmp(a, b);
514 return 0;
515 } else {
516 return 1;
520 /** Given a list of networkstatus_t votes, determine and return the number of
521 * the highest consensus method that is supported by 2/3 of the voters. */
522 static int
523 compute_consensus_method(smartlist_t *votes)
525 smartlist_t *all_methods = smartlist_new();
526 smartlist_t *acceptable_methods = smartlist_new();
527 smartlist_t *tmp = smartlist_new();
528 int min = (smartlist_len(votes) * 2) / 3;
529 int n_ok;
530 int result;
531 SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
533 tor_assert(vote->supported_methods);
534 smartlist_add_all(tmp, vote->supported_methods);
535 smartlist_sort(tmp, cmp_int_strings_);
536 smartlist_uniq(tmp, cmp_int_strings_, NULL);
537 smartlist_add_all(all_methods, tmp);
538 smartlist_clear(tmp);
541 smartlist_sort(all_methods, cmp_int_strings_);
542 get_frequent_members(acceptable_methods, all_methods, min);
543 n_ok = smartlist_len(acceptable_methods);
544 if (n_ok) {
545 const char *best = smartlist_get(acceptable_methods, n_ok-1);
546 result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
547 } else {
548 result = 1;
550 smartlist_free(tmp);
551 smartlist_free(all_methods);
552 smartlist_free(acceptable_methods);
553 return result;
556 /** Return true iff <b>method</b> is a consensus method that we support. */
557 static int
558 consensus_method_is_supported(int method)
560 if (method == MIN_METHOD_FOR_ED25519_ID_IN_MD) {
561 /* This method was broken due to buggy code accidently left in
562 * dircollate.c; do not actually use it.
564 return 0;
567 return (method >= MIN_SUPPORTED_CONSENSUS_METHOD) &&
568 (method <= MAX_SUPPORTED_CONSENSUS_METHOD);
571 /** Return a newly allocated string holding the numbers between low and high
572 * (inclusive) that are supported consensus methods. */
573 STATIC char *
574 make_consensus_method_list(int low, int high, const char *separator)
576 char *list;
578 int i;
579 smartlist_t *lst;
580 lst = smartlist_new();
581 for (i = low; i <= high; ++i) {
582 if (!consensus_method_is_supported(i))
583 continue;
584 smartlist_add_asprintf(lst, "%d", i);
586 list = smartlist_join_strings(lst, separator, 0, NULL);
587 tor_assert(list);
588 SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
589 smartlist_free(lst);
590 return list;
593 /** Helper: given <b>lst</b>, a list of version strings such that every
594 * version appears once for every versioning voter who recommends it, return a
595 * newly allocated string holding the resulting client-versions or
596 * server-versions list. May change contents of <b>lst</b> */
597 static char *
598 compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
600 int min = n_versioning / 2;
601 smartlist_t *good = smartlist_new();
602 char *result;
603 sort_version_list(lst, 0);
604 get_frequent_members(good, lst, min);
605 result = smartlist_join_strings(good, ",", 0, NULL);
606 smartlist_free(good);
607 return result;
610 /** Minimum number of directory authorities voting for a parameter to
611 * include it in the consensus, if consensus method 12 or later is to be
612 * used. See proposal 178 for details. */
613 #define MIN_VOTES_FOR_PARAM 3
615 /** Helper: given a list of valid networkstatus_t, return a new string
616 * containing the contents of the consensus network parameter set.
618 STATIC char *
619 dirvote_compute_params(smartlist_t *votes, int method, int total_authorities)
621 int i;
622 int32_t *vals;
624 int cur_param_len;
625 const char *cur_param;
626 const char *eq;
627 char *result;
629 const int n_votes = smartlist_len(votes);
630 smartlist_t *output;
631 smartlist_t *param_list = smartlist_new();
632 (void) method;
634 /* We require that the parameter lists in the votes are well-formed: that
635 is, that their keywords are unique and sorted, and that their values are
636 between INT32_MIN and INT32_MAX inclusive. This should be guaranteed by
637 the parsing code. */
639 vals = tor_calloc(n_votes, sizeof(int));
641 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
642 if (!v->net_params)
643 continue;
644 smartlist_add_all(param_list, v->net_params);
645 } SMARTLIST_FOREACH_END(v);
647 if (smartlist_len(param_list) == 0) {
648 tor_free(vals);
649 smartlist_free(param_list);
650 return NULL;
653 smartlist_sort_strings(param_list);
654 i = 0;
655 cur_param = smartlist_get(param_list, 0);
656 eq = strchr(cur_param, '=');
657 tor_assert(eq);
658 cur_param_len = (int)(eq+1 - cur_param);
660 output = smartlist_new();
662 SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
663 const char *next_param;
664 int ok=0;
665 eq = strchr(param, '=');
666 tor_assert(i<n_votes); /* Make sure we prevented vote-stuffing. */
667 vals[i++] = (int32_t)
668 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
669 tor_assert(ok); /* Already checked these when parsing. */
671 if (param_sl_idx+1 == smartlist_len(param_list))
672 next_param = NULL;
673 else
674 next_param = smartlist_get(param_list, param_sl_idx+1);
675 /* resolve spurious clang shallow analysis null pointer errors */
676 tor_assert(param);
677 if (!next_param || strncmp(next_param, param, cur_param_len)) {
678 /* We've reached the end of a series. */
679 /* Make sure enough authorities voted on this param, unless the
680 * the consensus method we use is too old for that. */
681 if (i > total_authorities/2 ||
682 i >= MIN_VOTES_FOR_PARAM) {
683 int32_t median = median_int32(vals, i);
684 char *out_string = tor_malloc(64+cur_param_len);
685 memcpy(out_string, param, cur_param_len);
686 tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
687 smartlist_add(output, out_string);
690 i = 0;
691 if (next_param) {
692 eq = strchr(next_param, '=');
693 cur_param_len = (int)(eq+1 - next_param);
696 } SMARTLIST_FOREACH_END(param);
698 result = smartlist_join_strings(output, " ", 0, NULL);
699 SMARTLIST_FOREACH(output, char *, cp, tor_free(cp));
700 smartlist_free(output);
701 smartlist_free(param_list);
702 tor_free(vals);
703 return result;
706 #define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
707 ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
708 (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
709 (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
710 (g) >= 0 && (g) <= (mx))
712 #define CHECK_EQ(a, b, margin) \
713 ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))
715 typedef enum {
716 BW_WEIGHTS_NO_ERROR = 0,
717 BW_WEIGHTS_RANGE_ERROR = 1,
718 BW_WEIGHTS_SUMG_ERROR = 2,
719 BW_WEIGHTS_SUME_ERROR = 3,
720 BW_WEIGHTS_SUMD_ERROR = 4,
721 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
722 BW_WEIGHTS_BALANCE_EG_ERROR = 6
723 } bw_weights_error_t;
726 * Verify that any weightings satisfy the balanced formulas.
728 static bw_weights_error_t
729 networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
730 int64_t Wme, int64_t Wmd, int64_t Wee,
731 int64_t Wed, int64_t scale, int64_t G,
732 int64_t M, int64_t E, int64_t D, int64_t T,
733 int64_t margin, int do_balance) {
734 bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;
736 // Wed + Wmd + Wgd == 1
737 if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
738 berr = BW_WEIGHTS_SUMD_ERROR;
739 goto out;
742 // Wmg + Wgg == 1
743 if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
744 berr = BW_WEIGHTS_SUMG_ERROR;
745 goto out;
748 // Wme + Wee == 1
749 if (!CHECK_EQ(Wme + Wee, scale, margin)) {
750 berr = BW_WEIGHTS_SUME_ERROR;
751 goto out;
754 // Verify weights within range 0->1
755 if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
756 berr = BW_WEIGHTS_RANGE_ERROR;
757 goto out;
760 if (do_balance) {
761 // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
762 if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
763 berr = BW_WEIGHTS_BALANCE_EG_ERROR;
764 goto out;
767 // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
768 if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
769 (margin*T)/3)) {
770 berr = BW_WEIGHTS_BALANCE_MID_ERROR;
771 goto out;
775 out:
776 if (berr) {
777 log_info(LD_DIR,
778 "Bw weight mismatch %d. G="I64_FORMAT" M="I64_FORMAT
779 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
780 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
781 " Wgd=%d Wgg=%d Wme=%d Wmg=%d",
782 berr,
783 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
784 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
785 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
786 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg);
789 return berr;
793 * This function computes the bandwidth weights for consensus method 10.
795 * It returns true if weights could be computed, false otherwise.
797 static int
798 networkstatus_compute_bw_weights_v10(smartlist_t *chunks, int64_t G,
799 int64_t M, int64_t E, int64_t D,
800 int64_t T, int64_t weight_scale)
802 bw_weights_error_t berr = 0;
803 int64_t Wgg = -1, Wgd = -1;
804 int64_t Wmg = -1, Wme = -1, Wmd = -1;
805 int64_t Wed = -1, Wee = -1;
806 const char *casename;
808 if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
809 log_warn(LD_DIR, "Consensus with empty bandwidth: "
810 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
811 " D="I64_FORMAT" T="I64_FORMAT,
812 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
813 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
814 return 0;
818 * Computed from cases in 3.4.3 of dir-spec.txt
820 * 1. Neither are scarce
821 * 2. Both Guard and Exit are scarce
822 * a. R+D <= S
823 * b. R+D > S
824 * 3. One of Guard or Exit is scarce
825 * a. S+D < T/3
826 * b. S+D >= T/3
828 if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
829 /* Case 1: Neither are scarce. */
830 casename = "Case 1 (Wgd=Wmd=Wed)";
831 Wgd = weight_scale/3;
832 Wed = weight_scale/3;
833 Wmd = weight_scale/3;
834 Wee = (weight_scale*(E+G+M))/(3*E);
835 Wme = weight_scale - Wee;
836 Wmg = (weight_scale*(2*G-E-M))/(3*G);
837 Wgg = weight_scale - Wmg;
839 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
840 weight_scale, G, M, E, D, T, 10, 1);
842 if (berr) {
843 log_warn(LD_DIR,
844 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
845 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
846 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
847 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
848 berr, casename,
849 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
850 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
851 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
852 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
853 return 0;
855 } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
856 int64_t R = MIN(E, G);
857 int64_t S = MAX(E, G);
859 * Case 2: Both Guards and Exits are scarce
860 * Balance D between E and G, depending upon
861 * D capacity and scarcity.
863 if (R+D < S) { // Subcase a
864 Wgg = weight_scale;
865 Wee = weight_scale;
866 Wmg = 0;
867 Wme = 0;
868 Wmd = 0;
869 if (E < G) {
870 casename = "Case 2a (E scarce)";
871 Wed = weight_scale;
872 Wgd = 0;
873 } else { /* E >= G */
874 casename = "Case 2a (G scarce)";
875 Wed = 0;
876 Wgd = weight_scale;
878 } else { // Subcase b: R+D >= S
879 casename = "Case 2b1 (Wgg=1, Wmd=Wgd)";
880 Wee = (weight_scale*(E - G + M))/E;
881 Wed = (weight_scale*(D - 2*E + 4*G - 2*M))/(3*D);
882 Wme = (weight_scale*(G-M))/E;
883 Wmg = 0;
884 Wgg = weight_scale;
885 Wmd = (weight_scale - Wed)/2;
886 Wgd = (weight_scale - Wed)/2;
888 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
889 weight_scale, G, M, E, D, T, 10, 1);
891 if (berr) {
892 casename = "Case 2b2 (Wgg=1, Wee=1)";
893 Wgg = weight_scale;
894 Wee = weight_scale;
895 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
896 Wmd = (weight_scale*(D - 2*M + G + E))/(3*D);
897 Wme = 0;
898 Wmg = 0;
900 if (Wmd < 0) { // Can happen if M > T/3
901 casename = "Case 2b3 (Wmd=0)";
902 Wmd = 0;
903 log_warn(LD_DIR,
904 "Too much Middle bandwidth on the network to calculate "
905 "balanced bandwidth-weights. Consider increasing the "
906 "number of Guard nodes by lowering the requirements.");
908 Wgd = weight_scale - Wed - Wmd;
909 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
910 Wed, weight_scale, G, M, E, D, T, 10, 1);
912 if (berr != BW_WEIGHTS_NO_ERROR &&
913 berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
914 log_warn(LD_DIR,
915 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
916 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
917 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
918 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
919 berr, casename,
920 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
921 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
922 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
923 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
924 return 0;
927 } else { // if (E < T/3 || G < T/3) {
928 int64_t S = MIN(E, G);
929 // Case 3: Exactly one of Guard or Exit is scarce
930 if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
931 log_warn(LD_BUG,
932 "Bw-Weights Case 3 v10 but with G="I64_FORMAT" M="
933 I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
934 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
935 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
938 if (3*(S+D) < T) { // Subcase a: S+D < T/3
939 if (G < E) {
940 casename = "Case 3a (G scarce)";
941 Wgg = Wgd = weight_scale;
942 Wmd = Wed = Wmg = 0;
943 // Minor subcase, if E is more scarce than M,
944 // keep its bandwidth in place.
945 if (E < M) Wme = 0;
946 else Wme = (weight_scale*(E-M))/(2*E);
947 Wee = weight_scale-Wme;
948 } else { // G >= E
949 casename = "Case 3a (E scarce)";
950 Wee = Wed = weight_scale;
951 Wmd = Wgd = Wme = 0;
952 // Minor subcase, if G is more scarce than M,
953 // keep its bandwidth in place.
954 if (G < M) Wmg = 0;
955 else Wmg = (weight_scale*(G-M))/(2*G);
956 Wgg = weight_scale-Wmg;
958 } else { // Subcase b: S+D >= T/3
959 // D != 0 because S+D >= T/3
960 if (G < E) {
961 casename = "Case 3bg (G scarce, Wgg=1, Wmd == Wed)";
962 Wgg = weight_scale;
963 Wgd = (weight_scale*(D - 2*G + E + M))/(3*D);
964 Wmg = 0;
965 Wee = (weight_scale*(E+M))/(2*E);
966 Wme = weight_scale - Wee;
967 Wmd = (weight_scale - Wgd)/2;
968 Wed = (weight_scale - Wgd)/2;
970 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
971 Wed, weight_scale, G, M, E, D, T, 10, 1);
972 } else { // G >= E
973 casename = "Case 3be (E scarce, Wee=1, Wmd == Wgd)";
974 Wee = weight_scale;
975 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
976 Wme = 0;
977 Wgg = (weight_scale*(G+M))/(2*G);
978 Wmg = weight_scale - Wgg;
979 Wmd = (weight_scale - Wed)/2;
980 Wgd = (weight_scale - Wed)/2;
982 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
983 Wed, weight_scale, G, M, E, D, T, 10, 1);
985 if (berr) {
986 log_warn(LD_DIR,
987 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
988 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
989 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
990 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
991 berr, casename,
992 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
993 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
994 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
995 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
996 return 0;
1001 /* We cast down the weights to 32 bit ints on the assumption that
1002 * weight_scale is ~= 10000. We need to ensure a rogue authority
1003 * doesn't break this assumption to rig our weights */
1004 tor_assert(0 < weight_scale && weight_scale <= INT32_MAX);
1007 * Provide Wgm=Wgg, Wmm=1, Wem=Wee, Weg=Wed. May later determine
1008 * that middle nodes need different bandwidth weights for dirport traffic,
1009 * or that weird exit policies need special weight, or that bridges
1010 * need special weight.
1012 * NOTE: This list is sorted.
1014 smartlist_add_asprintf(chunks,
1015 "bandwidth-weights Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
1016 "Wdb=%d "
1017 "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
1018 "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
1019 "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
1020 (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
1021 (int)weight_scale,
1022 (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
1023 (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
1024 (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
1026 log_notice(LD_CIRC, "Computed bandwidth weights for %s with v10: "
1027 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1028 " T="I64_FORMAT,
1029 casename,
1030 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1031 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1032 return 1;
1035 /** Update total bandwidth weights (G/M/E/D/T) with the bandwidth of
1036 * the router in <b>rs</b>. */
1037 static void
1038 update_total_bandwidth_weights(const routerstatus_t *rs,
1039 int is_exit, int is_guard,
1040 int64_t *G, int64_t *M, int64_t *E, int64_t *D,
1041 int64_t *T)
1043 int default_bandwidth = rs->bandwidth_kb;
1044 int guardfraction_bandwidth = 0;
1046 if (!rs->has_bandwidth) {
1047 log_info(LD_BUG, "Missing consensus bandwidth for router %s",
1048 rs->nickname);
1049 return;
1052 /* If this routerstatus represents a guard that we have
1053 * guardfraction information on, use it to calculate its actual
1054 * bandwidth. From proposal236:
1056 * Similarly, when calculating the bandwidth-weights line as in
1057 * section 3.8.3 of dir-spec.txt, directory authorities should treat N
1058 * as if fraction F of its bandwidth has the guard flag and (1-F) does
1059 * not. So when computing the totals G,M,E,D, each relay N with guard
1060 * visibility fraction F and bandwidth B should be added as follows:
1062 * G' = G + F*B, if N does not have the exit flag
1063 * M' = M + (1-F)*B, if N does not have the exit flag
1065 * or
1067 * D' = D + F*B, if N has the exit flag
1068 * E' = E + (1-F)*B, if N has the exit flag
1070 * In this block of code, we prepare the bandwidth values by setting
1071 * the default_bandwidth to F*B and guardfraction_bandwidth to (1-F)*B.
1073 if (rs->has_guardfraction) {
1074 guardfraction_bandwidth_t guardfraction_bw;
1076 tor_assert(is_guard);
1078 guard_get_guardfraction_bandwidth(&guardfraction_bw,
1079 rs->bandwidth_kb,
1080 rs->guardfraction_percentage);
1082 default_bandwidth = guardfraction_bw.guard_bw;
1083 guardfraction_bandwidth = guardfraction_bw.non_guard_bw;
1086 /* Now calculate the total bandwidth weights with or without
1087 * guardfraction. Depending on the flags of the relay, add its
1088 * bandwidth to the appropriate weight pool. If it's a guard and
1089 * guardfraction is enabled, add its bandwidth to both pools as
1090 * indicated by the previous comment.
1092 *T += default_bandwidth;
1093 if (is_exit && is_guard) {
1095 *D += default_bandwidth;
1096 if (rs->has_guardfraction) {
1097 *E += guardfraction_bandwidth;
1100 } else if (is_exit) {
1102 *E += default_bandwidth;
1104 } else if (is_guard) {
1106 *G += default_bandwidth;
1107 if (rs->has_guardfraction) {
1108 *M += guardfraction_bandwidth;
1111 } else {
1113 *M += default_bandwidth;
1117 /** Given a list of vote networkstatus_t in <b>votes</b>, our public
1118 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
1119 * and the number of <b>total_authorities</b> that we believe exist in our
1120 * voting quorum, generate the text of a new v3 consensus vote, and return the
1121 * value in a newly allocated string.
1123 * Note: this function DOES NOT check whether the votes are from
1124 * recognized authorities. (dirvote_add_vote does that.) */
1125 char *
1126 networkstatus_compute_consensus(smartlist_t *votes,
1127 int total_authorities,
1128 crypto_pk_t *identity_key,
1129 crypto_pk_t *signing_key,
1130 const char *legacy_id_key_digest,
1131 crypto_pk_t *legacy_signing_key,
1132 consensus_flavor_t flavor)
1134 smartlist_t *chunks;
1135 char *result = NULL;
1136 int consensus_method;
1137 time_t valid_after, fresh_until, valid_until;
1138 int vote_seconds, dist_seconds;
1139 char *client_versions = NULL, *server_versions = NULL;
1140 smartlist_t *flags;
1141 const char *flavor_name;
1142 uint32_t max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1143 int64_t G=0, M=0, E=0, D=0, T=0; /* For bandwidth weights */
1144 const routerstatus_format_type_t rs_format =
1145 flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
1146 char *params = NULL;
1147 char *packages = NULL;
1148 int added_weights = 0;
1149 dircollator_t *collator = NULL;
1150 tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
1151 tor_assert(total_authorities >= smartlist_len(votes));
1152 tor_assert(total_authorities > 0);
1154 flavor_name = networkstatus_get_flavor_name(flavor);
1156 if (!smartlist_len(votes)) {
1157 log_warn(LD_DIR, "Can't compute a consensus from no votes.");
1158 return NULL;
1160 flags = smartlist_new();
1162 consensus_method = compute_consensus_method(votes);
1163 if (consensus_method_is_supported(consensus_method)) {
1164 log_info(LD_DIR, "Generating consensus using method %d.",
1165 consensus_method);
1166 } else {
1167 log_warn(LD_DIR, "The other authorities will use consensus method %d, "
1168 "which I don't support. Maybe I should upgrade!",
1169 consensus_method);
1170 consensus_method = MAX_SUPPORTED_CONSENSUS_METHOD;
1173 /* Compute medians of time-related things, and figure out how many
1174 * routers we might need to talk about. */
1176 int n_votes = smartlist_len(votes);
1177 time_t *va_times = tor_calloc(n_votes, sizeof(time_t));
1178 time_t *fu_times = tor_calloc(n_votes, sizeof(time_t));
1179 time_t *vu_times = tor_calloc(n_votes, sizeof(time_t));
1180 int *votesec_list = tor_calloc(n_votes, sizeof(int));
1181 int *distsec_list = tor_calloc(n_votes, sizeof(int));
1182 int n_versioning_clients = 0, n_versioning_servers = 0;
1183 smartlist_t *combined_client_versions = smartlist_new();
1184 smartlist_t *combined_server_versions = smartlist_new();
1186 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1187 tor_assert(v->type == NS_TYPE_VOTE);
1188 va_times[v_sl_idx] = v->valid_after;
1189 fu_times[v_sl_idx] = v->fresh_until;
1190 vu_times[v_sl_idx] = v->valid_until;
1191 votesec_list[v_sl_idx] = v->vote_seconds;
1192 distsec_list[v_sl_idx] = v->dist_seconds;
1193 if (v->client_versions) {
1194 smartlist_t *cv = smartlist_new();
1195 ++n_versioning_clients;
1196 smartlist_split_string(cv, v->client_versions, ",",
1197 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1198 sort_version_list(cv, 1);
1199 smartlist_add_all(combined_client_versions, cv);
1200 smartlist_free(cv); /* elements get freed later. */
1202 if (v->server_versions) {
1203 smartlist_t *sv = smartlist_new();
1204 ++n_versioning_servers;
1205 smartlist_split_string(sv, v->server_versions, ",",
1206 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1207 sort_version_list(sv, 1);
1208 smartlist_add_all(combined_server_versions, sv);
1209 smartlist_free(sv); /* elements get freed later. */
1211 SMARTLIST_FOREACH(v->known_flags, const char *, cp,
1212 smartlist_add(flags, tor_strdup(cp)));
1213 } SMARTLIST_FOREACH_END(v);
1214 valid_after = median_time(va_times, n_votes);
1215 fresh_until = median_time(fu_times, n_votes);
1216 valid_until = median_time(vu_times, n_votes);
1217 vote_seconds = median_int(votesec_list, n_votes);
1218 dist_seconds = median_int(distsec_list, n_votes);
1220 tor_assert(valid_after +
1221 (get_options()->TestingTorNetwork ?
1222 MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) <= fresh_until);
1223 tor_assert(fresh_until +
1224 (get_options()->TestingTorNetwork ?
1225 MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) <= valid_until);
1226 tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
1227 tor_assert(dist_seconds >= MIN_DIST_SECONDS);
1229 server_versions = compute_consensus_versions_list(combined_server_versions,
1230 n_versioning_servers);
1231 client_versions = compute_consensus_versions_list(combined_client_versions,
1232 n_versioning_clients);
1233 if (consensus_method >= MIN_METHOD_FOR_PACKAGE_LINES) {
1234 packages = compute_consensus_package_lines(votes);
1235 } else {
1236 packages = tor_strdup("");
1239 SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
1240 SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
1241 smartlist_free(combined_server_versions);
1242 smartlist_free(combined_client_versions);
1244 if (consensus_method >= MIN_METHOD_FOR_ED25519_ID_VOTING)
1245 smartlist_add(flags, tor_strdup("NoEdConsensus"));
1247 smartlist_sort_strings(flags);
1248 smartlist_uniq_strings(flags);
1250 tor_free(va_times);
1251 tor_free(fu_times);
1252 tor_free(vu_times);
1253 tor_free(votesec_list);
1254 tor_free(distsec_list);
1257 chunks = smartlist_new();
1260 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
1261 vu_buf[ISO_TIME_LEN+1];
1262 char *flaglist;
1263 format_iso_time(va_buf, valid_after);
1264 format_iso_time(fu_buf, fresh_until);
1265 format_iso_time(vu_buf, valid_until);
1266 flaglist = smartlist_join_strings(flags, " ", 0, NULL);
1268 smartlist_add_asprintf(chunks, "network-status-version 3%s%s\n"
1269 "vote-status consensus\n",
1270 flavor == FLAV_NS ? "" : " ",
1271 flavor == FLAV_NS ? "" : flavor_name);
1273 smartlist_add_asprintf(chunks, "consensus-method %d\n",
1274 consensus_method);
1276 smartlist_add_asprintf(chunks,
1277 "valid-after %s\n"
1278 "fresh-until %s\n"
1279 "valid-until %s\n"
1280 "voting-delay %d %d\n"
1281 "client-versions %s\n"
1282 "server-versions %s\n"
1283 "%s" /* packages */
1284 "known-flags %s\n",
1285 va_buf, fu_buf, vu_buf,
1286 vote_seconds, dist_seconds,
1287 client_versions, server_versions,
1288 packages,
1289 flaglist);
1291 tor_free(flaglist);
1294 params = dirvote_compute_params(votes, consensus_method,
1295 total_authorities);
1296 if (params) {
1297 smartlist_add(chunks, tor_strdup("params "));
1298 smartlist_add(chunks, params);
1299 smartlist_add(chunks, tor_strdup("\n"));
1302 /* Sort the votes. */
1303 smartlist_sort(votes, compare_votes_by_authority_id_);
1304 /* Add the authority sections. */
1306 smartlist_t *dir_sources = smartlist_new();
1307 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1308 dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
1309 e->v = v;
1310 e->digest = get_voter(v)->identity_digest;
1311 e->is_legacy = 0;
1312 smartlist_add(dir_sources, e);
1313 if (!tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
1314 dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
1315 e_legacy->v = v;
1316 e_legacy->digest = get_voter(v)->legacy_id_digest;
1317 e_legacy->is_legacy = 1;
1318 smartlist_add(dir_sources, e_legacy);
1320 } SMARTLIST_FOREACH_END(v);
1321 smartlist_sort(dir_sources, compare_dir_src_ents_by_authority_id_);
1323 SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
1324 char fingerprint[HEX_DIGEST_LEN+1];
1325 char votedigest[HEX_DIGEST_LEN+1];
1326 networkstatus_t *v = e->v;
1327 networkstatus_voter_info_t *voter = get_voter(v);
1329 base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
1330 base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
1331 DIGEST_LEN);
1333 smartlist_add_asprintf(chunks,
1334 "dir-source %s%s %s %s %s %d %d\n",
1335 voter->nickname, e->is_legacy ? "-legacy" : "",
1336 fingerprint, voter->address, fmt_addr32(voter->addr),
1337 voter->dir_port,
1338 voter->or_port);
1339 if (! e->is_legacy) {
1340 smartlist_add_asprintf(chunks,
1341 "contact %s\n"
1342 "vote-digest %s\n",
1343 voter->contact,
1344 votedigest);
1346 } SMARTLIST_FOREACH_END(e);
1347 SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
1348 smartlist_free(dir_sources);
1351 if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW) {
1352 char *max_unmeasured_param = NULL;
1353 /* XXXX Extract this code into a common function */
1354 if (params) {
1355 if (strcmpstart(params, "maxunmeasuredbw=") == 0)
1356 max_unmeasured_param = params;
1357 else
1358 max_unmeasured_param = strstr(params, " maxunmeasuredbw=");
1360 if (max_unmeasured_param) {
1361 int ok = 0;
1362 char *eq = strchr(max_unmeasured_param, '=');
1363 if (eq) {
1364 max_unmeasured_bw_kb = (uint32_t)
1365 tor_parse_ulong(eq+1, 10, 1, UINT32_MAX, &ok, NULL);
1366 if (!ok) {
1367 log_warn(LD_DIR, "Bad element '%s' in max unmeasured bw param",
1368 escaped(max_unmeasured_param));
1369 max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1375 /* Add the actual router entries. */
1377 int *index; /* index[j] is the current index into votes[j]. */
1378 int *size; /* size[j] is the number of routerstatuses in votes[j]. */
1379 int *flag_counts; /* The number of voters that list flag[j] for the
1380 * currently considered router. */
1381 int i;
1382 smartlist_t *matching_descs = smartlist_new();
1383 smartlist_t *chosen_flags = smartlist_new();
1384 smartlist_t *versions = smartlist_new();
1385 smartlist_t *exitsummaries = smartlist_new();
1386 uint32_t *bandwidths_kb = tor_calloc(smartlist_len(votes),
1387 sizeof(uint32_t));
1388 uint32_t *measured_bws_kb = tor_calloc(smartlist_len(votes),
1389 sizeof(uint32_t));
1390 uint32_t *measured_guardfraction = tor_calloc(smartlist_len(votes),
1391 sizeof(uint32_t));
1392 int num_bandwidths;
1393 int num_mbws;
1394 int num_guardfraction_inputs;
1396 int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
1397 * votes[j] knows about. */
1398 int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
1399 * about flags[f]. */
1400 int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
1401 * is the same flag as votes[j]->known_flags[b]. */
1402 int *named_flag; /* Index of the flag "Named" for votes[j] */
1403 int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
1404 int n_authorities_measuring_bandwidth;
1406 strmap_t *name_to_id_map = strmap_new();
1407 char conflict[DIGEST_LEN];
1408 char unknown[DIGEST_LEN];
1409 memset(conflict, 0, sizeof(conflict));
1410 memset(unknown, 0xff, sizeof(conflict));
1412 index = tor_calloc(smartlist_len(votes), sizeof(int));
1413 size = tor_calloc(smartlist_len(votes), sizeof(int));
1414 n_voter_flags = tor_calloc(smartlist_len(votes), sizeof(int));
1415 n_flag_voters = tor_calloc(smartlist_len(flags), sizeof(int));
1416 flag_map = tor_calloc(smartlist_len(votes), sizeof(int *));
1417 named_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1418 unnamed_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1419 for (i = 0; i < smartlist_len(votes); ++i)
1420 unnamed_flag[i] = named_flag[i] = -1;
1422 /* Build the flag indexes. Note that no vote can have more than 64 members
1423 * for known_flags, so no value will be greater than 63, so it's safe to
1424 * do U64_LITERAL(1) << index on these values. But note also that
1425 * named_flag and unnamed_flag are initialized to -1, so we need to check
1426 * that they're actually set before doing U64_LITERAL(1) << index with
1427 * them.*/
1428 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1429 flag_map[v_sl_idx] = tor_calloc(smartlist_len(v->known_flags),
1430 sizeof(int));
1431 if (smartlist_len(v->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
1432 log_warn(LD_BUG, "Somehow, a vote has %d entries in known_flags",
1433 smartlist_len(v->known_flags));
1435 SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
1436 int p = smartlist_string_pos(flags, fl);
1437 tor_assert(p >= 0);
1438 flag_map[v_sl_idx][fl_sl_idx] = p;
1439 ++n_flag_voters[p];
1440 if (!strcmp(fl, "Named"))
1441 named_flag[v_sl_idx] = fl_sl_idx;
1442 if (!strcmp(fl, "Unnamed"))
1443 unnamed_flag[v_sl_idx] = fl_sl_idx;
1444 } SMARTLIST_FOREACH_END(fl);
1445 n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
1446 size[v_sl_idx] = smartlist_len(v->routerstatus_list);
1447 } SMARTLIST_FOREACH_END(v);
1449 /* Named and Unnamed get treated specially */
1451 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1452 uint64_t nf;
1453 if (named_flag[v_sl_idx]<0)
1454 continue;
1455 nf = U64_LITERAL(1) << named_flag[v_sl_idx];
1456 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1457 vote_routerstatus_t *, rs) {
1459 if ((rs->flags & nf) != 0) {
1460 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1461 if (!d) {
1462 /* We have no name officially mapped to this digest. */
1463 strmap_set_lc(name_to_id_map, rs->status.nickname,
1464 rs->status.identity_digest);
1465 } else if (d != conflict &&
1466 fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
1467 /* Authorities disagree about this nickname. */
1468 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1469 } else {
1470 /* It's already a conflict, or it's already this ID. */
1473 } SMARTLIST_FOREACH_END(rs);
1474 } SMARTLIST_FOREACH_END(v);
1476 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1477 uint64_t uf;
1478 if (unnamed_flag[v_sl_idx]<0)
1479 continue;
1480 uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
1481 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1482 vote_routerstatus_t *, rs) {
1483 if ((rs->flags & uf) != 0) {
1484 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1485 if (d == conflict || d == unknown) {
1486 /* Leave it alone; we know what it is. */
1487 } else if (!d) {
1488 /* We have no name officially mapped to this digest. */
1489 strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
1490 } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
1491 /* Authorities disagree about this nickname. */
1492 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1493 } else {
1494 /* It's mapped to a different name. */
1497 } SMARTLIST_FOREACH_END(rs);
1498 } SMARTLIST_FOREACH_END(v);
1501 /* We need to know how many votes measure bandwidth. */
1502 n_authorities_measuring_bandwidth = 0;
1503 SMARTLIST_FOREACH(votes, const networkstatus_t *, v,
1504 if (v->has_measured_bws) {
1505 ++n_authorities_measuring_bandwidth;
1509 /* Populate the collator */
1510 collator = dircollator_new(smartlist_len(votes), total_authorities);
1511 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1512 dircollator_add_vote(collator, v);
1513 } SMARTLIST_FOREACH_END(v);
1515 dircollator_collate(collator, consensus_method);
1517 /* Now go through all the votes */
1518 flag_counts = tor_calloc(smartlist_len(flags), sizeof(int));
1519 const int num_routers = dircollator_n_routers(collator);
1520 for (i = 0; i < num_routers; ++i) {
1521 vote_routerstatus_t **vrs_lst =
1522 dircollator_get_votes_for_router(collator, i);
1524 vote_routerstatus_t *rs;
1525 routerstatus_t rs_out;
1526 const char *current_rsa_id = NULL;
1527 const char *chosen_version;
1528 const char *chosen_name = NULL;
1529 int exitsummary_disagreement = 0;
1530 int is_named = 0, is_unnamed = 0, is_running = 0;
1531 int is_guard = 0, is_exit = 0, is_bad_exit = 0;
1532 int naming_conflict = 0;
1533 int n_listing = 0;
1534 char microdesc_digest[DIGEST256_LEN];
1535 tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
1537 memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
1538 smartlist_clear(matching_descs);
1539 smartlist_clear(chosen_flags);
1540 smartlist_clear(versions);
1541 num_bandwidths = 0;
1542 num_mbws = 0;
1543 num_guardfraction_inputs = 0;
1544 int ed_consensus = 0;
1545 const uint8_t *ed_consensus_val = NULL;
1547 /* Okay, go through all the entries for this digest. */
1548 for (int voter_idx = 0; voter_idx < smartlist_len(votes); ++voter_idx) {
1549 if (vrs_lst[voter_idx] == NULL)
1550 continue; /* This voter had nothing to say about this entry. */
1551 rs = vrs_lst[voter_idx];
1552 ++n_listing;
1554 current_rsa_id = rs->status.identity_digest;
1556 smartlist_add(matching_descs, rs);
1557 if (rs->version && rs->version[0])
1558 smartlist_add(versions, rs->version);
1560 /* Tally up all the flags. */
1561 for (int flag = 0; flag < n_voter_flags[voter_idx]; ++flag) {
1562 if (rs->flags & (U64_LITERAL(1) << flag))
1563 ++flag_counts[flag_map[voter_idx][flag]];
1565 if (named_flag[voter_idx] >= 0 &&
1566 (rs->flags & (U64_LITERAL(1) << named_flag[voter_idx]))) {
1567 if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
1568 log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
1569 chosen_name, rs->status.nickname);
1570 naming_conflict = 1;
1572 chosen_name = rs->status.nickname;
1575 /* Count guardfraction votes and note down the values. */
1576 if (rs->status.has_guardfraction) {
1577 measured_guardfraction[num_guardfraction_inputs++] =
1578 rs->status.guardfraction_percentage;
1581 /* count bandwidths */
1582 if (rs->has_measured_bw)
1583 measured_bws_kb[num_mbws++] = rs->measured_bw_kb;
1585 if (rs->status.has_bandwidth)
1586 bandwidths_kb[num_bandwidths++] = rs->status.bandwidth_kb;
1588 /* Count number for which ed25519 is canonical. */
1589 if (rs->ed25519_reflects_consensus) {
1590 ++ed_consensus;
1591 if (ed_consensus_val) {
1592 tor_assert(fast_memeq(ed_consensus_val, rs->ed25519_id,
1593 ED25519_PUBKEY_LEN));
1594 } else {
1595 ed_consensus_val = rs->ed25519_id;
1600 /* We don't include this router at all unless more than half of
1601 * the authorities we believe in list it. */
1602 if (n_listing <= total_authorities/2)
1603 continue;
1605 if (ed_consensus > 0) {
1606 tor_assert(consensus_method >= MIN_METHOD_FOR_ED25519_ID_VOTING);
1607 if (ed_consensus <= total_authorities / 2) {
1608 log_warn(LD_BUG, "Not enough entries had ed_consensus set; how "
1609 "can we have a consensus of %d?", ed_consensus);
1613 /* The clangalyzer can't figure out that this will never be NULL
1614 * if n_listing is at least 1 */
1615 tor_assert(current_rsa_id);
1617 /* Figure out the most popular opinion of what the most recent
1618 * routerinfo and its contents are. */
1619 memset(microdesc_digest, 0, sizeof(microdesc_digest));
1620 rs = compute_routerstatus_consensus(matching_descs, consensus_method,
1621 microdesc_digest, &alt_orport);
1622 /* Copy bits of that into rs_out. */
1623 memset(&rs_out, 0, sizeof(rs_out));
1624 tor_assert(fast_memeq(current_rsa_id,
1625 rs->status.identity_digest,DIGEST_LEN));
1626 memcpy(rs_out.identity_digest, current_rsa_id, DIGEST_LEN);
1627 memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
1628 DIGEST_LEN);
1629 rs_out.addr = rs->status.addr;
1630 rs_out.published_on = rs->status.published_on;
1631 rs_out.dir_port = rs->status.dir_port;
1632 rs_out.or_port = rs->status.or_port;
1633 if (consensus_method >= MIN_METHOD_FOR_A_LINES) {
1634 tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
1635 rs_out.ipv6_orport = alt_orport.port;
1637 rs_out.has_bandwidth = 0;
1638 rs_out.has_exitsummary = 0;
1640 if (chosen_name && !naming_conflict) {
1641 strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
1642 } else {
1643 strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
1647 const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
1648 if (!d) {
1649 is_named = is_unnamed = 0;
1650 } else if (fast_memeq(d, current_rsa_id, DIGEST_LEN)) {
1651 is_named = 1; is_unnamed = 0;
1652 } else {
1653 is_named = 0; is_unnamed = 1;
1657 /* Set the flags. */
1658 smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
1659 SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
1660 if (!strcmp(fl, "Named")) {
1661 if (is_named)
1662 smartlist_add(chosen_flags, (char*)fl);
1663 } else if (!strcmp(fl, "Unnamed")) {
1664 if (is_unnamed)
1665 smartlist_add(chosen_flags, (char*)fl);
1666 } else if (!strcmp(fl, "NoEdConsensus") &&
1667 consensus_method >= MIN_METHOD_FOR_ED25519_ID_VOTING) {
1668 if (ed_consensus <= total_authorities/2)
1669 smartlist_add(chosen_flags, (char*)fl);
1670 } else {
1671 if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
1672 smartlist_add(chosen_flags, (char*)fl);
1673 if (!strcmp(fl, "Exit"))
1674 is_exit = 1;
1675 else if (!strcmp(fl, "Guard"))
1676 is_guard = 1;
1677 else if (!strcmp(fl, "Running"))
1678 is_running = 1;
1679 else if (!strcmp(fl, "BadExit"))
1680 is_bad_exit = 1;
1683 } SMARTLIST_FOREACH_END(fl);
1685 /* Starting with consensus method 4 we do not list servers
1686 * that are not running in a consensus. See Proposal 138 */
1687 if (!is_running)
1688 continue;
1690 /* Pick the version. */
1691 if (smartlist_len(versions)) {
1692 sort_version_list(versions, 0);
1693 chosen_version = get_most_frequent_member(versions);
1694 } else {
1695 chosen_version = NULL;
1698 /* If it's a guard and we have enough guardfraction votes,
1699 calculate its consensus guardfraction value. */
1700 if (is_guard && num_guardfraction_inputs > 2 &&
1701 consensus_method >= MIN_METHOD_FOR_GUARDFRACTION) {
1702 rs_out.has_guardfraction = 1;
1703 rs_out.guardfraction_percentage = median_uint32(measured_guardfraction,
1704 num_guardfraction_inputs);
1705 /* final value should be an integer percentage! */
1706 tor_assert(rs_out.guardfraction_percentage <= 100);
1709 /* Pick a bandwidth */
1710 if (num_mbws > 2) {
1711 rs_out.has_bandwidth = 1;
1712 rs_out.bw_is_unmeasured = 0;
1713 rs_out.bandwidth_kb = median_uint32(measured_bws_kb, num_mbws);
1714 } else if (num_bandwidths > 0) {
1715 rs_out.has_bandwidth = 1;
1716 rs_out.bw_is_unmeasured = 1;
1717 rs_out.bandwidth_kb = median_uint32(bandwidths_kb, num_bandwidths);
1718 if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW &&
1719 n_authorities_measuring_bandwidth > 2) {
1720 /* Cap non-measured bandwidths. */
1721 if (rs_out.bandwidth_kb > max_unmeasured_bw_kb) {
1722 rs_out.bandwidth_kb = max_unmeasured_bw_kb;
1727 /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
1728 is_exit = is_exit && !is_bad_exit;
1730 /* Update total bandwidth weights with the bandwidths of this router. */
1732 update_total_bandwidth_weights(&rs_out,
1733 is_exit, is_guard,
1734 &G, &M, &E, &D, &T);
1737 /* Ok, we already picked a descriptor digest we want to list
1738 * previously. Now we want to use the exit policy summary from
1739 * that descriptor. If everybody plays nice all the voters who
1740 * listed that descriptor will have the same summary. If not then
1741 * something is fishy and we'll use the most common one (breaking
1742 * ties in favor of lexicographically larger one (only because it
1743 * lets me reuse more existing code)).
1745 * The other case that can happen is that no authority that voted
1746 * for that descriptor has an exit policy summary. That's
1747 * probably quite unlikely but can happen. In that case we use
1748 * the policy that was most often listed in votes, again breaking
1749 * ties like in the previous case.
1752 /* Okay, go through all the votes for this router. We prepared
1753 * that list previously */
1754 const char *chosen_exitsummary = NULL;
1755 smartlist_clear(exitsummaries);
1756 SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
1757 /* Check if the vote where this status comes from had the
1758 * proper descriptor */
1759 tor_assert(fast_memeq(rs_out.identity_digest,
1760 vsr->status.identity_digest,
1761 DIGEST_LEN));
1762 if (vsr->status.has_exitsummary &&
1763 fast_memeq(rs_out.descriptor_digest,
1764 vsr->status.descriptor_digest,
1765 DIGEST_LEN)) {
1766 tor_assert(vsr->status.exitsummary);
1767 smartlist_add(exitsummaries, vsr->status.exitsummary);
1768 if (!chosen_exitsummary) {
1769 chosen_exitsummary = vsr->status.exitsummary;
1770 } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
1771 /* Great. There's disagreement among the voters. That
1772 * really shouldn't be */
1773 exitsummary_disagreement = 1;
1776 } SMARTLIST_FOREACH_END(vsr);
1778 if (exitsummary_disagreement) {
1779 char id[HEX_DIGEST_LEN+1];
1780 char dd[HEX_DIGEST_LEN+1];
1781 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1782 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1783 log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
1784 " for router %s with descriptor %s. This really shouldn't"
1785 " have happened.", id, dd);
1787 smartlist_sort_strings(exitsummaries);
1788 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1789 } else if (!chosen_exitsummary) {
1790 char id[HEX_DIGEST_LEN+1];
1791 char dd[HEX_DIGEST_LEN+1];
1792 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1793 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1794 log_warn(LD_DIR, "Not one of the voters that made us select"
1795 "descriptor %s for router %s had an exit policy"
1796 "summary", dd, id);
1798 /* Ok, none of those voting for the digest we chose had an
1799 * exit policy for us. Well, that kinda sucks.
1801 smartlist_clear(exitsummaries);
1802 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
1803 if (vsr->status.has_exitsummary)
1804 smartlist_add(exitsummaries, vsr->status.exitsummary);
1806 smartlist_sort_strings(exitsummaries);
1807 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1809 if (!chosen_exitsummary)
1810 log_warn(LD_DIR, "Wow, not one of the voters had an exit "
1811 "policy summary for %s. Wow.", id);
1814 if (chosen_exitsummary) {
1815 rs_out.has_exitsummary = 1;
1816 /* yea, discards the const */
1817 rs_out.exitsummary = (char *)chosen_exitsummary;
1821 if (flavor == FLAV_MICRODESC &&
1822 tor_digest256_is_zero(microdesc_digest)) {
1823 /* With no microdescriptor digest, we omit the entry entirely. */
1824 continue;
1828 char *buf;
1829 /* Okay!! Now we can write the descriptor... */
1830 /* First line goes into "buf". */
1831 buf = routerstatus_format_entry(&rs_out, NULL, rs_format, NULL);
1832 if (buf)
1833 smartlist_add(chunks, buf);
1835 /* Now an m line, if applicable. */
1836 if (flavor == FLAV_MICRODESC &&
1837 !tor_digest256_is_zero(microdesc_digest)) {
1838 char m[BASE64_DIGEST256_LEN+1];
1839 digest256_to_base64(m, microdesc_digest);
1840 smartlist_add_asprintf(chunks, "m %s\n", m);
1842 /* Next line is all flags. The "\n" is missing. */
1843 smartlist_add(chunks,
1844 smartlist_join_strings(chosen_flags, " ", 0, NULL));
1845 /* Now the version line. */
1846 if (chosen_version) {
1847 smartlist_add(chunks, tor_strdup("\nv "));
1848 smartlist_add(chunks, tor_strdup(chosen_version));
1850 smartlist_add(chunks, tor_strdup("\n"));
1851 /* Now the weight line. */
1852 if (rs_out.has_bandwidth) {
1853 char *guardfraction_str = NULL;
1854 int unmeasured = rs_out.bw_is_unmeasured &&
1855 consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW;
1857 /* If we have guardfraction info, include it in the 'w' line. */
1858 if (rs_out.has_guardfraction) {
1859 tor_asprintf(&guardfraction_str,
1860 " GuardFraction=%u", rs_out.guardfraction_percentage);
1862 smartlist_add_asprintf(chunks, "w Bandwidth=%d%s%s\n",
1863 rs_out.bandwidth_kb,
1864 unmeasured?" Unmeasured=1":"",
1865 guardfraction_str ? guardfraction_str : "");
1867 tor_free(guardfraction_str);
1870 /* Now the exitpolicy summary line. */
1871 if (rs_out.has_exitsummary && flavor == FLAV_NS) {
1872 smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
1875 /* And the loop is over and we move on to the next router */
1878 tor_free(index);
1879 tor_free(size);
1880 tor_free(n_voter_flags);
1881 tor_free(n_flag_voters);
1882 for (i = 0; i < smartlist_len(votes); ++i)
1883 tor_free(flag_map[i]);
1884 tor_free(flag_map);
1885 tor_free(flag_counts);
1886 tor_free(named_flag);
1887 tor_free(unnamed_flag);
1888 strmap_free(name_to_id_map, NULL);
1889 smartlist_free(matching_descs);
1890 smartlist_free(chosen_flags);
1891 smartlist_free(versions);
1892 smartlist_free(exitsummaries);
1893 tor_free(bandwidths_kb);
1894 tor_free(measured_bws_kb);
1895 tor_free(measured_guardfraction);
1898 /* Mark the directory footer region */
1899 smartlist_add(chunks, tor_strdup("directory-footer\n"));
1902 int64_t weight_scale = BW_WEIGHT_SCALE;
1903 char *bw_weight_param = NULL;
1905 // Parse params, extract BW_WEIGHT_SCALE if present
1906 // DO NOT use consensus_param_bw_weight_scale() in this code!
1907 // The consensus is not formed yet!
1908 /* XXXX Extract this code into a common function */
1909 if (params) {
1910 if (strcmpstart(params, "bwweightscale=") == 0)
1911 bw_weight_param = params;
1912 else
1913 bw_weight_param = strstr(params, " bwweightscale=");
1916 if (bw_weight_param) {
1917 int ok=0;
1918 char *eq = strchr(bw_weight_param, '=');
1919 if (eq) {
1920 weight_scale = tor_parse_long(eq+1, 10, 1, INT32_MAX, &ok,
1921 NULL);
1922 if (!ok) {
1923 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
1924 escaped(bw_weight_param));
1925 weight_scale = BW_WEIGHT_SCALE;
1927 } else {
1928 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
1929 escaped(bw_weight_param));
1930 weight_scale = BW_WEIGHT_SCALE;
1934 added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
1935 T, weight_scale);
1938 /* Add a signature. */
1940 char digest[DIGEST256_LEN];
1941 char fingerprint[HEX_DIGEST_LEN+1];
1942 char signing_key_fingerprint[HEX_DIGEST_LEN+1];
1943 digest_algorithm_t digest_alg =
1944 flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
1945 size_t digest_len =
1946 flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
1947 const char *algname = crypto_digest_algorithm_get_name(digest_alg);
1948 char *signature;
1950 smartlist_add(chunks, tor_strdup("directory-signature "));
1952 /* Compute the hash of the chunks. */
1953 crypto_digest_smartlist(digest, digest_len, chunks, "", digest_alg);
1955 /* Get the fingerprints */
1956 crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
1957 crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
1959 /* add the junk that will go at the end of the line. */
1960 if (flavor == FLAV_NS) {
1961 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
1962 signing_key_fingerprint);
1963 } else {
1964 smartlist_add_asprintf(chunks, "%s %s %s\n",
1965 algname, fingerprint,
1966 signing_key_fingerprint);
1968 /* And the signature. */
1969 if (!(signature = router_get_dirobj_signature(digest, digest_len,
1970 signing_key))) {
1971 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1972 goto done;
1974 smartlist_add(chunks, signature);
1976 if (legacy_id_key_digest && legacy_signing_key) {
1977 smartlist_add(chunks, tor_strdup("directory-signature "));
1978 base16_encode(fingerprint, sizeof(fingerprint),
1979 legacy_id_key_digest, DIGEST_LEN);
1980 crypto_pk_get_fingerprint(legacy_signing_key,
1981 signing_key_fingerprint, 0);
1982 if (flavor == FLAV_NS) {
1983 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
1984 signing_key_fingerprint);
1985 } else {
1986 smartlist_add_asprintf(chunks, "%s %s %s\n",
1987 algname, fingerprint,
1988 signing_key_fingerprint);
1991 if (!(signature = router_get_dirobj_signature(digest, digest_len,
1992 legacy_signing_key))) {
1993 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1994 goto done;
1996 smartlist_add(chunks, signature);
2000 result = smartlist_join_strings(chunks, "", 0, NULL);
2003 networkstatus_t *c;
2004 if (!(c = networkstatus_parse_vote_from_string(result, NULL,
2005 NS_TYPE_CONSENSUS))) {
2006 log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
2007 "parse.");
2008 tor_free(result);
2009 goto done;
2011 // Verify balancing parameters
2012 if (added_weights) {
2013 networkstatus_verify_bw_weights(c, consensus_method);
2015 networkstatus_vote_free(c);
2018 done:
2020 dircollator_free(collator);
2021 tor_free(client_versions);
2022 tor_free(server_versions);
2023 tor_free(packages);
2024 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
2025 smartlist_free(flags);
2026 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2027 smartlist_free(chunks);
2029 return result;
2032 /** Given a list of networkstatus_t for each vote, return a newly allocated
2033 * string containing the "package" lines for the vote. */
2034 STATIC char *
2035 compute_consensus_package_lines(smartlist_t *votes)
2037 const int n_votes = smartlist_len(votes);
2039 /* This will be a map from "packagename version" strings to arrays
2040 * of const char *, with the i'th member of the array corresponding to the
2041 * package line from the i'th vote.
2043 strmap_t *package_status = strmap_new();
2045 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
2046 if (! v->package_lines)
2047 continue;
2048 SMARTLIST_FOREACH_BEGIN(v->package_lines, const char *, line) {
2049 if (! validate_recommended_package_line(line))
2050 continue;
2052 /* Skip 'cp' to the second space in the line. */
2053 const char *cp = strchr(line, ' ');
2054 if (!cp) continue;
2055 ++cp;
2056 cp = strchr(cp, ' ');
2057 if (!cp) continue;
2059 char *key = tor_strndup(line, cp - line);
2061 const char **status = strmap_get(package_status, key);
2062 if (!status) {
2063 status = tor_calloc(n_votes, sizeof(const char *));
2064 strmap_set(package_status, key, status);
2066 status[v_sl_idx] = line; /* overwrite old value */
2067 tor_free(key);
2068 } SMARTLIST_FOREACH_END(line);
2069 } SMARTLIST_FOREACH_END(v);
2071 smartlist_t *entries = smartlist_new(); /* temporary */
2072 smartlist_t *result_list = smartlist_new(); /* output */
2073 STRMAP_FOREACH(package_status, key, const char **, values) {
2074 int i, count=-1;
2075 for (i = 0; i < n_votes; ++i) {
2076 if (values[i])
2077 smartlist_add(entries, (void*) values[i]);
2079 smartlist_sort_strings(entries);
2080 int n_voting_for_entry = smartlist_len(entries);
2081 const char *most_frequent =
2082 smartlist_get_most_frequent_string_(entries, &count);
2084 if (n_voting_for_entry >= 3 && count > n_voting_for_entry / 2) {
2085 smartlist_add_asprintf(result_list, "package %s\n", most_frequent);
2088 smartlist_clear(entries);
2090 } STRMAP_FOREACH_END;
2092 smartlist_sort_strings(result_list);
2094 char *result = smartlist_join_strings(result_list, "", 0, NULL);
2096 SMARTLIST_FOREACH(result_list, char *, cp, tor_free(cp));
2097 smartlist_free(result_list);
2098 smartlist_free(entries);
2099 strmap_free(package_status, tor_free_);
2101 return result;
2104 /** Given a consensus vote <b>target</b> and a set of detached signatures in
2105 * <b>sigs</b> that correspond to the same consensus, check whether there are
2106 * any new signatures in <b>src_voter_list</b> that should be added to
2107 * <b>target</b>. (A signature should be added if we have no signature for that
2108 * voter in <b>target</b> yet, or if we have no verifiable signature and the
2109 * new signature is verifiable.) Return the number of signatures added or
2110 * changed, or -1 if the document signed by <b>sigs</b> isn't the same
2111 * document as <b>target</b>. */
2113 networkstatus_add_detached_signatures(networkstatus_t *target,
2114 ns_detached_signatures_t *sigs,
2115 const char *source,
2116 int severity,
2117 const char **msg_out)
2119 int r = 0;
2120 const char *flavor;
2121 smartlist_t *siglist;
2122 tor_assert(sigs);
2123 tor_assert(target);
2124 tor_assert(target->type == NS_TYPE_CONSENSUS);
2126 flavor = networkstatus_get_flavor_name(target->flavor);
2128 /* Do the times seem right? */
2129 if (target->valid_after != sigs->valid_after) {
2130 *msg_out = "Valid-After times do not match "
2131 "when adding detached signatures to consensus";
2132 return -1;
2134 if (target->fresh_until != sigs->fresh_until) {
2135 *msg_out = "Fresh-until times do not match "
2136 "when adding detached signatures to consensus";
2137 return -1;
2139 if (target->valid_until != sigs->valid_until) {
2140 *msg_out = "Valid-until times do not match "
2141 "when adding detached signatures to consensus";
2142 return -1;
2144 siglist = strmap_get(sigs->signatures, flavor);
2145 if (!siglist) {
2146 *msg_out = "No signatures for given consensus flavor";
2147 return -1;
2150 /** Make sure all the digests we know match, and at least one matches. */
2152 common_digests_t *digests = strmap_get(sigs->digests, flavor);
2153 int n_matches = 0;
2154 int alg;
2155 if (!digests) {
2156 *msg_out = "No digests for given consensus flavor";
2157 return -1;
2159 for (alg = DIGEST_SHA1; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
2160 if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
2161 if (fast_memeq(target->digests.d[alg], digests->d[alg],
2162 DIGEST256_LEN)) {
2163 ++n_matches;
2164 } else {
2165 *msg_out = "Mismatched digest.";
2166 return -1;
2170 if (!n_matches) {
2171 *msg_out = "No regognized digests for given consensus flavor";
2175 /* For each voter in src... */
2176 SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
2177 char voter_identity[HEX_DIGEST_LEN+1];
2178 networkstatus_voter_info_t *target_voter =
2179 networkstatus_get_voter_by_id(target, sig->identity_digest);
2180 authority_cert_t *cert = NULL;
2181 const char *algorithm;
2182 document_signature_t *old_sig = NULL;
2184 algorithm = crypto_digest_algorithm_get_name(sig->alg);
2186 base16_encode(voter_identity, sizeof(voter_identity),
2187 sig->identity_digest, DIGEST_LEN);
2188 log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
2189 algorithm);
2190 /* If the target doesn't know about this voter, then forget it. */
2191 if (!target_voter) {
2192 log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
2193 continue;
2196 old_sig = voter_get_sig_by_algorithm(target_voter, sig->alg);
2198 /* If the target already has a good signature from this voter, then skip
2199 * this one. */
2200 if (old_sig && old_sig->good_signature) {
2201 log_info(LD_DIR, "We already have a good signature from %s using %s",
2202 voter_identity, algorithm);
2203 continue;
2206 /* Try checking the signature if we haven't already. */
2207 if (!sig->good_signature && !sig->bad_signature) {
2208 cert = authority_cert_get_by_digests(sig->identity_digest,
2209 sig->signing_key_digest);
2210 if (cert) {
2211 /* Not checking the return value here, since we are going to look
2212 * at the status of sig->good_signature in a moment. */
2213 (void) networkstatus_check_document_signature(target, sig, cert);
2217 /* If this signature is good, or we don't have any signature yet,
2218 * then maybe add it. */
2219 if (sig->good_signature || !old_sig || old_sig->bad_signature) {
2220 log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
2221 algorithm);
2222 tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
2223 target_voter->nickname, source);
2224 ++r;
2225 if (old_sig) {
2226 smartlist_remove(target_voter->sigs, old_sig);
2227 document_signature_free(old_sig);
2229 smartlist_add(target_voter->sigs, document_signature_dup(sig));
2230 } else {
2231 log_info(LD_DIR, "Not adding signature from %s", voter_identity);
2233 } SMARTLIST_FOREACH_END(sig);
2235 return r;
2238 /** Return a newly allocated string containing all the signatures on
2239 * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
2240 * then the signatures will be put in a detached signatures document, so
2241 * prefix any non-NS-flavored signatures with "additional-signature" rather
2242 * than "directory-signature". */
2243 static char *
2244 networkstatus_format_signatures(networkstatus_t *consensus,
2245 int for_detached_signatures)
2247 smartlist_t *elements;
2248 char buf[4096];
2249 char *result = NULL;
2250 int n_sigs = 0;
2251 const consensus_flavor_t flavor = consensus->flavor;
2252 const char *flavor_name = networkstatus_get_flavor_name(flavor);
2253 const char *keyword;
2255 if (for_detached_signatures && flavor != FLAV_NS)
2256 keyword = "additional-signature";
2257 else
2258 keyword = "directory-signature";
2260 elements = smartlist_new();
2262 SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
2263 SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
2264 char sk[HEX_DIGEST_LEN+1];
2265 char id[HEX_DIGEST_LEN+1];
2266 if (!sig->signature || sig->bad_signature)
2267 continue;
2268 ++n_sigs;
2269 base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
2270 base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
2271 if (flavor == FLAV_NS) {
2272 smartlist_add_asprintf(elements,
2273 "%s %s %s\n-----BEGIN SIGNATURE-----\n",
2274 keyword, id, sk);
2275 } else {
2276 const char *digest_name =
2277 crypto_digest_algorithm_get_name(sig->alg);
2278 smartlist_add_asprintf(elements,
2279 "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
2280 keyword,
2281 for_detached_signatures ? " " : "",
2282 for_detached_signatures ? flavor_name : "",
2283 digest_name, id, sk);
2285 base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len,
2286 BASE64_ENCODE_MULTILINE);
2287 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
2288 smartlist_add(elements, tor_strdup(buf));
2289 } SMARTLIST_FOREACH_END(sig);
2290 } SMARTLIST_FOREACH_END(v);
2292 result = smartlist_join_strings(elements, "", 0, NULL);
2293 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2294 smartlist_free(elements);
2295 if (!n_sigs)
2296 tor_free(result);
2297 return result;
2300 /** Return a newly allocated string holding the detached-signatures document
2301 * corresponding to the signatures on <b>consensuses</b>, which must contain
2302 * exactly one FLAV_NS consensus, and no more than one consensus for each
2303 * other flavor. */
2304 char *
2305 networkstatus_get_detached_signatures(smartlist_t *consensuses)
2307 smartlist_t *elements;
2308 char *result = NULL, *sigs = NULL;
2309 networkstatus_t *consensus_ns = NULL;
2310 tor_assert(consensuses);
2312 SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
2313 tor_assert(ns);
2314 tor_assert(ns->type == NS_TYPE_CONSENSUS);
2315 if (ns && ns->flavor == FLAV_NS)
2316 consensus_ns = ns;
2318 if (!consensus_ns) {
2319 log_warn(LD_BUG, "No NS consensus given.");
2320 return NULL;
2323 elements = smartlist_new();
2326 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
2327 vu_buf[ISO_TIME_LEN+1];
2328 char d[HEX_DIGEST_LEN+1];
2330 base16_encode(d, sizeof(d),
2331 consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
2332 format_iso_time(va_buf, consensus_ns->valid_after);
2333 format_iso_time(fu_buf, consensus_ns->fresh_until);
2334 format_iso_time(vu_buf, consensus_ns->valid_until);
2336 smartlist_add_asprintf(elements,
2337 "consensus-digest %s\n"
2338 "valid-after %s\n"
2339 "fresh-until %s\n"
2340 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
2343 /* Get all the digests for the non-FLAV_NS consensuses */
2344 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2345 const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
2346 int alg;
2347 if (ns->flavor == FLAV_NS)
2348 continue;
2350 /* start with SHA256; we don't include SHA1 for anything but the basic
2351 * consensus. */
2352 for (alg = DIGEST_SHA256; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
2353 char d[HEX_DIGEST256_LEN+1];
2354 const char *alg_name =
2355 crypto_digest_algorithm_get_name(alg);
2356 if (tor_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
2357 continue;
2358 base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
2359 smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
2360 flavor_name, alg_name, d);
2362 } SMARTLIST_FOREACH_END(ns);
2364 /* Now get all the sigs for non-FLAV_NS consensuses */
2365 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2366 char *sigs;
2367 if (ns->flavor == FLAV_NS)
2368 continue;
2369 sigs = networkstatus_format_signatures(ns, 1);
2370 if (!sigs) {
2371 log_warn(LD_DIR, "Couldn't format signatures");
2372 goto err;
2374 smartlist_add(elements, sigs);
2375 } SMARTLIST_FOREACH_END(ns);
2377 /* Now add the FLAV_NS consensus signatrures. */
2378 sigs = networkstatus_format_signatures(consensus_ns, 1);
2379 if (!sigs)
2380 goto err;
2381 smartlist_add(elements, sigs);
2383 result = smartlist_join_strings(elements, "", 0, NULL);
2384 err:
2385 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2386 smartlist_free(elements);
2387 return result;
2390 /** Return a newly allocated string holding a detached-signatures document for
2391 * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
2392 * <b>pending</b>. */
2393 static char *
2394 get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
2395 int n_flavors)
2397 int flav;
2398 char *signatures;
2399 smartlist_t *c = smartlist_new();
2400 for (flav = 0; flav < n_flavors; ++flav) {
2401 if (pending[flav].consensus)
2402 smartlist_add(c, pending[flav].consensus);
2404 signatures = networkstatus_get_detached_signatures(c);
2405 smartlist_free(c);
2406 return signatures;
2409 /** Release all storage held in <b>s</b>. */
2410 void
2411 ns_detached_signatures_free(ns_detached_signatures_t *s)
2413 if (!s)
2414 return;
2415 if (s->signatures) {
2416 STRMAP_FOREACH(s->signatures, flavor, smartlist_t *, sigs) {
2417 SMARTLIST_FOREACH(sigs, document_signature_t *, sig,
2418 document_signature_free(sig));
2419 smartlist_free(sigs);
2420 } STRMAP_FOREACH_END;
2421 strmap_free(s->signatures, NULL);
2422 strmap_free(s->digests, tor_free_);
2425 tor_free(s);
2428 /* =====
2429 * Certificate functions
2430 * ===== */
2432 /** Allocate and return a new authority_cert_t with the same contents as
2433 * <b>cert</b>. */
2434 authority_cert_t *
2435 authority_cert_dup(authority_cert_t *cert)
2437 authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
2438 tor_assert(cert);
2440 memcpy(out, cert, sizeof(authority_cert_t));
2441 /* Now copy pointed-to things. */
2442 out->cache_info.signed_descriptor_body =
2443 tor_strndup(cert->cache_info.signed_descriptor_body,
2444 cert->cache_info.signed_descriptor_len);
2445 out->cache_info.saved_location = SAVED_NOWHERE;
2446 out->identity_key = crypto_pk_dup_key(cert->identity_key);
2447 out->signing_key = crypto_pk_dup_key(cert->signing_key);
2449 return out;
2452 /* =====
2453 * Vote scheduling
2454 * ===== */
2456 /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
2457 * Note that these aren't the intervals we'll use to vote; they're the ones
2458 * that we'll vote to use. */
2459 void
2460 dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
2462 const or_options_t *options = get_options();
2464 tor_assert(timing_out);
2466 timing_out->vote_interval = options->V3AuthVotingInterval;
2467 timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
2468 timing_out->vote_delay = options->V3AuthVoteDelay;
2469 timing_out->dist_delay = options->V3AuthDistDelay;
2472 /** Return the start of the next interval of size <b>interval</b> (in
2473 * seconds) after <b>now</b>, plus <b>offset</b>. Midnight always
2474 * starts a fresh interval, and if the last interval of a day would be
2475 * truncated to less than half its size, it is rolled into the
2476 * previous interval. */
2477 time_t
2478 dirvote_get_start_of_next_interval(time_t now, int interval, int offset)
2480 struct tm tm;
2481 time_t midnight_today=0;
2482 time_t midnight_tomorrow;
2483 time_t next;
2485 tor_gmtime_r(&now, &tm);
2486 tm.tm_hour = 0;
2487 tm.tm_min = 0;
2488 tm.tm_sec = 0;
2490 if (tor_timegm(&tm, &midnight_today) < 0) {
2491 log_warn(LD_BUG, "Ran into an invalid time when trying to find midnight.");
2493 midnight_tomorrow = midnight_today + (24*60*60);
2495 next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
2497 /* Intervals never cross midnight. */
2498 if (next > midnight_tomorrow)
2499 next = midnight_tomorrow;
2501 /* If the interval would only last half as long as it's supposed to, then
2502 * skip over to the next day. */
2503 if (next + interval/2 > midnight_tomorrow)
2504 next = midnight_tomorrow;
2506 next += offset;
2507 if (next - interval > now)
2508 next -= interval;
2510 return next;
2513 /** Scheduling information for a voting interval. */
2514 static struct {
2515 /** When do we generate and distribute our vote for this interval? */
2516 time_t voting_starts;
2517 /** When do we send an HTTP request for any votes that we haven't
2518 * been posted yet?*/
2519 time_t fetch_missing_votes;
2520 /** When do we give up on getting more votes and generate a consensus? */
2521 time_t voting_ends;
2522 /** When do we send an HTTP request for any signatures we're expecting to
2523 * see on the consensus? */
2524 time_t fetch_missing_signatures;
2525 /** When do we publish the consensus? */
2526 time_t interval_starts;
2528 /* True iff we have generated and distributed our vote. */
2529 int have_voted;
2530 /* True iff we've requested missing votes. */
2531 int have_fetched_missing_votes;
2532 /* True iff we have built a consensus and sent the signatures around. */
2533 int have_built_consensus;
2534 /* True iff we've fetched missing signatures. */
2535 int have_fetched_missing_signatures;
2536 /* True iff we have published our consensus. */
2537 int have_published_consensus;
2538 } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
2540 /** Set voting_schedule to hold the timing for the next vote we should be
2541 * doing. */
2542 void
2543 dirvote_recalculate_timing(const or_options_t *options, time_t now)
2545 int interval, vote_delay, dist_delay;
2546 time_t start;
2547 time_t end;
2548 networkstatus_t *consensus;
2550 if (!authdir_mode_v3(options))
2551 return;
2553 consensus = networkstatus_get_live_consensus(now);
2555 memset(&voting_schedule, 0, sizeof(voting_schedule));
2557 if (consensus) {
2558 interval = (int)( consensus->fresh_until - consensus->valid_after );
2559 vote_delay = consensus->vote_seconds;
2560 dist_delay = consensus->dist_seconds;
2561 } else {
2562 interval = options->TestingV3AuthInitialVotingInterval;
2563 vote_delay = options->TestingV3AuthInitialVoteDelay;
2564 dist_delay = options->TestingV3AuthInitialDistDelay;
2567 tor_assert(interval > 0);
2569 if (vote_delay + dist_delay > interval/2)
2570 vote_delay = dist_delay = interval / 4;
2572 start = voting_schedule.interval_starts =
2573 dirvote_get_start_of_next_interval(now,interval,
2574 options->TestingV3AuthVotingStartOffset);
2575 end = dirvote_get_start_of_next_interval(start+1, interval,
2576 options->TestingV3AuthVotingStartOffset);
2578 tor_assert(end > start);
2580 voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
2581 voting_schedule.voting_ends = start - dist_delay;
2582 voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
2583 voting_schedule.voting_starts = start - dist_delay - vote_delay;
2586 char tbuf[ISO_TIME_LEN+1];
2587 format_iso_time(tbuf, voting_schedule.interval_starts);
2588 log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
2589 "consensus_set=%d, interval=%d",
2590 tbuf, consensus?1:0, interval);
2594 /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
2595 void
2596 dirvote_act(const or_options_t *options, time_t now)
2598 if (!authdir_mode_v3(options))
2599 return;
2600 if (!voting_schedule.voting_starts) {
2601 char *keys = list_v3_auth_ids();
2602 authority_cert_t *c = get_my_v3_authority_cert();
2603 log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
2604 "Mine is %s.",
2605 keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
2606 tor_free(keys);
2607 dirvote_recalculate_timing(options, now);
2609 if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
2610 log_notice(LD_DIR, "Time to vote.");
2611 dirvote_perform_vote();
2612 voting_schedule.have_voted = 1;
2614 if (voting_schedule.fetch_missing_votes < now &&
2615 !voting_schedule.have_fetched_missing_votes) {
2616 log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
2617 dirvote_fetch_missing_votes();
2618 voting_schedule.have_fetched_missing_votes = 1;
2620 if (voting_schedule.voting_ends < now &&
2621 !voting_schedule.have_built_consensus) {
2622 log_notice(LD_DIR, "Time to compute a consensus.");
2623 dirvote_compute_consensuses();
2624 /* XXXX We will want to try again later if we haven't got enough
2625 * votes yet. Implement this if it turns out to ever happen. */
2626 voting_schedule.have_built_consensus = 1;
2628 if (voting_schedule.fetch_missing_signatures < now &&
2629 !voting_schedule.have_fetched_missing_signatures) {
2630 log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
2631 dirvote_fetch_missing_signatures();
2632 voting_schedule.have_fetched_missing_signatures = 1;
2634 if (voting_schedule.interval_starts < now &&
2635 !voting_schedule.have_published_consensus) {
2636 log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
2637 dirvote_publish_consensus();
2638 dirvote_clear_votes(0);
2639 voting_schedule.have_published_consensus = 1;
2640 /* XXXX We will want to try again later if we haven't got enough
2641 * signatures yet. Implement this if it turns out to ever happen. */
2642 dirvote_recalculate_timing(options, now);
2646 /** A vote networkstatus_t and its unparsed body: held around so we can
2647 * use it to generate a consensus (at voting_ends) and so we can serve it to
2648 * other authorities that might want it. */
2649 typedef struct pending_vote_t {
2650 cached_dir_t *vote_body;
2651 networkstatus_t *vote;
2652 } pending_vote_t;
2654 /** List of pending_vote_t for the current vote. Before we've used them to
2655 * build a consensus, the votes go here. */
2656 static smartlist_t *pending_vote_list = NULL;
2657 /** List of pending_vote_t for the previous vote. After we've used them to
2658 * build a consensus, the votes go here for the next period. */
2659 static smartlist_t *previous_vote_list = NULL;
2661 /* DOCDOC pending_consensuses */
2662 static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
2664 /** The detached signatures for the consensus that we're currently
2665 * building. */
2666 static char *pending_consensus_signatures = NULL;
2668 /** List of ns_detached_signatures_t: hold signatures that get posted to us
2669 * before we have generated the consensus on our own. */
2670 static smartlist_t *pending_consensus_signature_list = NULL;
2672 /** Generate a networkstatus vote and post it to all the v3 authorities.
2673 * (V3 Authority only) */
2674 static int
2675 dirvote_perform_vote(void)
2677 crypto_pk_t *key = get_my_v3_authority_signing_key();
2678 authority_cert_t *cert = get_my_v3_authority_cert();
2679 networkstatus_t *ns;
2680 char *contents;
2681 pending_vote_t *pending_vote;
2682 time_t now = time(NULL);
2684 int status;
2685 const char *msg = "";
2687 if (!cert || !key) {
2688 log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
2689 return -1;
2690 } else if (cert->expires < now) {
2691 log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
2692 return -1;
2694 if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
2695 return -1;
2697 contents = format_networkstatus_vote(key, ns);
2698 networkstatus_vote_free(ns);
2699 if (!contents)
2700 return -1;
2702 pending_vote = dirvote_add_vote(contents, &msg, &status);
2703 tor_free(contents);
2704 if (!pending_vote) {
2705 log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
2706 msg);
2707 return -1;
2710 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
2711 ROUTER_PURPOSE_GENERAL,
2712 V3_DIRINFO,
2713 pending_vote->vote_body->dir,
2714 pending_vote->vote_body->dir_len, 0);
2715 log_notice(LD_DIR, "Vote posted.");
2716 return 0;
2719 /** Send an HTTP request to every other v3 authority, for the votes of every
2720 * authority for which we haven't received a vote yet in this period. (V3
2721 * authority only) */
2722 static void
2723 dirvote_fetch_missing_votes(void)
2725 smartlist_t *missing_fps = smartlist_new();
2726 char *resource;
2728 SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
2729 dir_server_t *, ds) {
2730 if (!(ds->type & V3_DIRINFO))
2731 continue;
2732 if (!dirvote_get_vote(ds->v3_identity_digest,
2733 DGV_BY_ID|DGV_INCLUDE_PENDING)) {
2734 char *cp = tor_malloc(HEX_DIGEST_LEN+1);
2735 base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
2736 DIGEST_LEN);
2737 smartlist_add(missing_fps, cp);
2739 } SMARTLIST_FOREACH_END(ds);
2741 if (!smartlist_len(missing_fps)) {
2742 smartlist_free(missing_fps);
2743 return;
2746 char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
2747 log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
2748 "Asking every other authority for a copy.",
2749 smartlist_len(missing_fps), tmp);
2750 tor_free(tmp);
2752 resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
2753 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
2754 0, resource);
2755 tor_free(resource);
2756 SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
2757 smartlist_free(missing_fps);
2760 /** Send a request to every other authority for its detached signatures,
2761 * unless we have signatures from all other v3 authorities already. */
2762 static void
2763 dirvote_fetch_missing_signatures(void)
2765 int need_any = 0;
2766 int i;
2767 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
2768 networkstatus_t *consensus = pending_consensuses[i].consensus;
2769 if (!consensus ||
2770 networkstatus_check_consensus_signature(consensus, -1) == 1) {
2771 /* We have no consensus, or we have one that's signed by everybody. */
2772 continue;
2774 need_any = 1;
2776 if (!need_any)
2777 return;
2779 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
2780 0, NULL);
2783 /** Release all storage held by pending consensuses (those waiting for
2784 * signatures). */
2785 static void
2786 dirvote_clear_pending_consensuses(void)
2788 int i;
2789 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
2790 pending_consensus_t *pc = &pending_consensuses[i];
2791 tor_free(pc->body);
2793 networkstatus_vote_free(pc->consensus);
2794 pc->consensus = NULL;
2798 /** Drop all currently pending votes, consensus, and detached signatures. */
2799 static void
2800 dirvote_clear_votes(int all_votes)
2802 if (!previous_vote_list)
2803 previous_vote_list = smartlist_new();
2804 if (!pending_vote_list)
2805 pending_vote_list = smartlist_new();
2807 /* All "previous" votes are now junk. */
2808 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
2809 cached_dir_decref(v->vote_body);
2810 v->vote_body = NULL;
2811 networkstatus_vote_free(v->vote);
2812 tor_free(v);
2814 smartlist_clear(previous_vote_list);
2816 if (all_votes) {
2817 /* If we're dumping all the votes, we delete the pending ones. */
2818 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
2819 cached_dir_decref(v->vote_body);
2820 v->vote_body = NULL;
2821 networkstatus_vote_free(v->vote);
2822 tor_free(v);
2824 } else {
2825 /* Otherwise, we move them into "previous". */
2826 smartlist_add_all(previous_vote_list, pending_vote_list);
2828 smartlist_clear(pending_vote_list);
2830 if (pending_consensus_signature_list) {
2831 SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
2832 tor_free(cp));
2833 smartlist_clear(pending_consensus_signature_list);
2835 tor_free(pending_consensus_signatures);
2836 dirvote_clear_pending_consensuses();
2839 /** Return a newly allocated string containing the hex-encoded v3 authority
2840 identity digest of every recognized v3 authority. */
2841 static char *
2842 list_v3_auth_ids(void)
2844 smartlist_t *known_v3_keys = smartlist_new();
2845 char *keys;
2846 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2847 dir_server_t *, ds,
2848 if ((ds->type & V3_DIRINFO) &&
2849 !tor_digest_is_zero(ds->v3_identity_digest))
2850 smartlist_add(known_v3_keys,
2851 tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
2852 keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
2853 SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
2854 smartlist_free(known_v3_keys);
2855 return keys;
2858 /** Called when we have received a networkstatus vote in <b>vote_body</b>.
2859 * Parse and validate it, and on success store it as a pending vote (which we
2860 * then return). Return NULL on failure. Sets *<b>msg_out</b> and
2861 * *<b>status_out</b> to an HTTP response and status code. (V3 authority
2862 * only) */
2863 pending_vote_t *
2864 dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
2866 networkstatus_t *vote;
2867 networkstatus_voter_info_t *vi;
2868 dir_server_t *ds;
2869 pending_vote_t *pending_vote = NULL;
2870 const char *end_of_vote = NULL;
2871 int any_failed = 0;
2872 tor_assert(vote_body);
2873 tor_assert(msg_out);
2874 tor_assert(status_out);
2876 if (!pending_vote_list)
2877 pending_vote_list = smartlist_new();
2878 *status_out = 0;
2879 *msg_out = NULL;
2881 again:
2882 vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
2883 NS_TYPE_VOTE);
2884 if (!end_of_vote)
2885 end_of_vote = vote_body + strlen(vote_body);
2886 if (!vote) {
2887 log_warn(LD_DIR, "Couldn't parse vote: length was %d",
2888 (int)strlen(vote_body));
2889 *msg_out = "Unable to parse vote";
2890 goto err;
2892 tor_assert(smartlist_len(vote->voters) == 1);
2893 vi = get_voter(vote);
2895 int any_sig_good = 0;
2896 SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
2897 if (sig->good_signature)
2898 any_sig_good = 1);
2899 tor_assert(any_sig_good);
2901 ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
2902 if (!ds) {
2903 char *keys = list_v3_auth_ids();
2904 log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
2905 "with authority key ID %s. "
2906 "This key ID is not recognized. Known v3 key IDs are: %s",
2907 vi->nickname, vi->address,
2908 hex_str(vi->identity_digest, DIGEST_LEN), keys);
2909 tor_free(keys);
2910 *msg_out = "Vote not from a recognized v3 authority";
2911 goto err;
2913 tor_assert(vote->cert);
2914 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2915 vote->cert->signing_key_digest)) {
2916 /* Hey, it's a new cert! */
2917 trusted_dirs_load_certs_from_string(
2918 vote->cert->cache_info.signed_descriptor_body,
2919 TRUSTED_DIRS_CERTS_SRC_FROM_VOTE, 1 /*flush*/);
2920 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2921 vote->cert->signing_key_digest)) {
2922 log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
2926 /* Is it for the right period? */
2927 if (vote->valid_after != voting_schedule.interval_starts) {
2928 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
2929 format_iso_time(tbuf1, vote->valid_after);
2930 format_iso_time(tbuf2, voting_schedule.interval_starts);
2931 log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
2932 "we were expecting %s", vi->address, tbuf1, tbuf2);
2933 *msg_out = "Bad valid-after time";
2934 goto err;
2937 /* Fetch any new router descriptors we just learned about */
2938 update_consensus_router_descriptor_downloads(time(NULL), 1, vote);
2940 /* Now see whether we already have a vote from this authority. */
2941 SMARTLIST_FOREACH_BEGIN(pending_vote_list, pending_vote_t *, v) {
2942 if (fast_memeq(v->vote->cert->cache_info.identity_digest,
2943 vote->cert->cache_info.identity_digest,
2944 DIGEST_LEN)) {
2945 networkstatus_voter_info_t *vi_old = get_voter(v->vote);
2946 if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
2947 /* Ah, it's the same vote. Not a problem. */
2948 log_info(LD_DIR, "Discarding a vote we already have (from %s).",
2949 vi->address);
2950 if (*status_out < 200)
2951 *status_out = 200;
2952 goto discard;
2953 } else if (v->vote->published < vote->published) {
2954 log_notice(LD_DIR, "Replacing an older pending vote from this "
2955 "directory (%s)", vi->address);
2956 cached_dir_decref(v->vote_body);
2957 networkstatus_vote_free(v->vote);
2958 v->vote_body = new_cached_dir(tor_strndup(vote_body,
2959 end_of_vote-vote_body),
2960 vote->published);
2961 v->vote = vote;
2962 if (end_of_vote &&
2963 !strcmpstart(end_of_vote, "network-status-version"))
2964 goto again;
2966 if (*status_out < 200)
2967 *status_out = 200;
2968 if (!*msg_out)
2969 *msg_out = "OK";
2970 return v;
2971 } else {
2972 *msg_out = "Already have a newer pending vote";
2973 goto err;
2976 } SMARTLIST_FOREACH_END(v);
2978 pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
2979 pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
2980 end_of_vote-vote_body),
2981 vote->published);
2982 pending_vote->vote = vote;
2983 smartlist_add(pending_vote_list, pending_vote);
2985 if (!strcmpstart(end_of_vote, "network-status-version ")) {
2986 vote_body = end_of_vote;
2987 goto again;
2990 goto done;
2992 err:
2993 any_failed = 1;
2994 if (!*msg_out)
2995 *msg_out = "Error adding vote";
2996 if (*status_out < 400)
2997 *status_out = 400;
2999 discard:
3000 networkstatus_vote_free(vote);
3002 if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
3003 vote_body = end_of_vote;
3004 goto again;
3007 done:
3009 if (*status_out < 200)
3010 *status_out = 200;
3011 if (!*msg_out) {
3012 if (!any_failed && !pending_vote) {
3013 *msg_out = "Duplicate discarded";
3014 } else {
3015 *msg_out = "ok";
3019 return any_failed ? NULL : pending_vote;
3022 /** Try to compute a v3 networkstatus consensus from the currently pending
3023 * votes. Return 0 on success, -1 on failure. Store the consensus in
3024 * pending_consensus: it won't be ready to be published until we have
3025 * everybody else's signatures collected too. (V3 Authority only) */
3026 static int
3027 dirvote_compute_consensuses(void)
3029 /* Have we got enough votes to try? */
3030 int n_votes, n_voters, n_vote_running = 0;
3031 smartlist_t *votes = NULL, *votestrings = NULL;
3032 char *consensus_body = NULL, *signatures = NULL, *votefile;
3033 networkstatus_t *consensus = NULL;
3034 authority_cert_t *my_cert;
3035 pending_consensus_t pending[N_CONSENSUS_FLAVORS];
3036 int flav;
3038 memset(pending, 0, sizeof(pending));
3040 if (!pending_vote_list)
3041 pending_vote_list = smartlist_new();
3043 n_voters = get_n_authorities(V3_DIRINFO);
3044 n_votes = smartlist_len(pending_vote_list);
3045 if (n_votes <= n_voters/2) {
3046 log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
3047 "%d of %d", n_votes, n_voters/2+1);
3048 goto err;
3050 tor_assert(pending_vote_list);
3051 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
3052 if (smartlist_contains_string(v->vote->known_flags, "Running"))
3053 n_vote_running++;
3055 if (!n_vote_running) {
3056 /* See task 1066. */
3057 log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
3058 "and publishing a consensus without Running nodes "
3059 "would make many clients stop working. Not "
3060 "generating a consensus!");
3061 goto err;
3064 if (!(my_cert = get_my_v3_authority_cert())) {
3065 log_warn(LD_DIR, "Can't generate consensus without a certificate.");
3066 goto err;
3069 votes = smartlist_new();
3070 votestrings = smartlist_new();
3071 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
3073 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
3074 c->bytes = v->vote_body->dir;
3075 c->len = v->vote_body->dir_len;
3076 smartlist_add(votestrings, c); /* collect strings to write to disk */
3078 smartlist_add(votes, v->vote); /* collect votes to compute consensus */
3081 votefile = get_datadir_fname("v3-status-votes");
3082 write_chunks_to_file(votefile, votestrings, 0, 0);
3083 tor_free(votefile);
3084 SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
3085 smartlist_free(votestrings);
3088 char legacy_dbuf[DIGEST_LEN];
3089 crypto_pk_t *legacy_sign=NULL;
3090 char *legacy_id_digest = NULL;
3091 int n_generated = 0;
3092 if (get_options()->V3AuthUseLegacyKey) {
3093 authority_cert_t *cert = get_my_v3_legacy_cert();
3094 legacy_sign = get_my_v3_legacy_signing_key();
3095 if (cert) {
3096 if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
3097 log_warn(LD_BUG,
3098 "Unable to compute digest of legacy v3 identity key");
3099 } else {
3100 legacy_id_digest = legacy_dbuf;
3105 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
3106 const char *flavor_name = networkstatus_get_flavor_name(flav);
3107 consensus_body = networkstatus_compute_consensus(
3108 votes, n_voters,
3109 my_cert->identity_key,
3110 get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
3111 flav);
3113 if (!consensus_body) {
3114 log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
3115 flavor_name);
3116 continue;
3118 consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
3119 NS_TYPE_CONSENSUS);
3120 if (!consensus) {
3121 log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
3122 flavor_name);
3123 tor_free(consensus_body);
3124 continue;
3127 /* 'Check' our own signature, to mark it valid. */
3128 networkstatus_check_consensus_signature(consensus, -1);
3130 pending[flav].body = consensus_body;
3131 pending[flav].consensus = consensus;
3132 n_generated++;
3133 consensus_body = NULL;
3134 consensus = NULL;
3136 if (!n_generated) {
3137 log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
3138 goto err;
3142 signatures = get_detached_signatures_from_pending_consensuses(
3143 pending, N_CONSENSUS_FLAVORS);
3145 if (!signatures) {
3146 log_warn(LD_DIR, "Couldn't extract signatures.");
3147 goto err;
3150 dirvote_clear_pending_consensuses();
3151 memcpy(pending_consensuses, pending, sizeof(pending));
3153 tor_free(pending_consensus_signatures);
3154 pending_consensus_signatures = signatures;
3156 if (pending_consensus_signature_list) {
3157 int n_sigs = 0;
3158 /* we may have gotten signatures for this consensus before we built
3159 * it ourself. Add them now. */
3160 SMARTLIST_FOREACH_BEGIN(pending_consensus_signature_list, char *, sig) {
3161 const char *msg = NULL;
3162 int r = dirvote_add_signatures_to_all_pending_consensuses(sig,
3163 "pending", &msg);
3164 if (r >= 0)
3165 n_sigs += r;
3166 else
3167 log_warn(LD_DIR,
3168 "Could not add queued signature to new consensus: %s",
3169 msg);
3170 tor_free(sig);
3171 } SMARTLIST_FOREACH_END(sig);
3172 if (n_sigs)
3173 log_notice(LD_DIR, "Added %d pending signatures while building "
3174 "consensus.", n_sigs);
3175 smartlist_clear(pending_consensus_signature_list);
3178 log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
3180 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
3181 ROUTER_PURPOSE_GENERAL,
3182 V3_DIRINFO,
3183 pending_consensus_signatures,
3184 strlen(pending_consensus_signatures), 0);
3185 log_notice(LD_DIR, "Signature(s) posted.");
3187 smartlist_free(votes);
3188 return 0;
3189 err:
3190 smartlist_free(votes);
3191 tor_free(consensus_body);
3192 tor_free(signatures);
3193 networkstatus_vote_free(consensus);
3195 return -1;
3198 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3199 * signatures on the currently pending consensus. Add them to <b>pc</b>
3200 * as appropriate. Return the number of signatures added. (?) */
3201 static int
3202 dirvote_add_signatures_to_pending_consensus(
3203 pending_consensus_t *pc,
3204 ns_detached_signatures_t *sigs,
3205 const char *source,
3206 int severity,
3207 const char **msg_out)
3209 const char *flavor_name;
3210 int r = -1;
3212 /* Only call if we have a pending consensus right now. */
3213 tor_assert(pc->consensus);
3214 tor_assert(pc->body);
3215 tor_assert(pending_consensus_signatures);
3217 flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
3218 *msg_out = NULL;
3221 smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
3222 log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
3223 sig_list ? smartlist_len(sig_list) : 0, flavor_name);
3225 r = networkstatus_add_detached_signatures(pc->consensus, sigs,
3226 source, severity, msg_out);
3227 log_info(LD_DIR,"Added %d signatures to consensus.", r);
3229 if (r >= 1) {
3230 char *new_signatures =
3231 networkstatus_format_signatures(pc->consensus, 0);
3232 char *dst, *dst_end;
3233 size_t new_consensus_len;
3234 if (!new_signatures) {
3235 *msg_out = "No signatures to add";
3236 goto err;
3238 new_consensus_len =
3239 strlen(pc->body) + strlen(new_signatures) + 1;
3240 pc->body = tor_realloc(pc->body, new_consensus_len);
3241 dst_end = pc->body + new_consensus_len;
3242 dst = strstr(pc->body, "directory-signature ");
3243 tor_assert(dst);
3244 strlcpy(dst, new_signatures, dst_end-dst);
3246 /* We remove this block once it has failed to crash for a while. But
3247 * unless it shows up in profiles, we're probably better leaving it in,
3248 * just in case we break detached signature processing at some point. */
3250 networkstatus_t *v = networkstatus_parse_vote_from_string(
3251 pc->body, NULL,
3252 NS_TYPE_CONSENSUS);
3253 tor_assert(v);
3254 networkstatus_vote_free(v);
3256 *msg_out = "Signatures added";
3257 tor_free(new_signatures);
3258 } else if (r == 0) {
3259 *msg_out = "Signatures ignored";
3260 } else {
3261 goto err;
3264 goto done;
3265 err:
3266 if (!*msg_out)
3267 *msg_out = "Unrecognized error while adding detached signatures.";
3268 done:
3269 return r;
3272 static int
3273 dirvote_add_signatures_to_all_pending_consensuses(
3274 const char *detached_signatures_body,
3275 const char *source,
3276 const char **msg_out)
3278 int r=0, i, n_added = 0, errors = 0;
3279 ns_detached_signatures_t *sigs;
3280 tor_assert(detached_signatures_body);
3281 tor_assert(msg_out);
3282 tor_assert(pending_consensus_signatures);
3284 if (!(sigs = networkstatus_parse_detached_signatures(
3285 detached_signatures_body, NULL))) {
3286 *msg_out = "Couldn't parse detached signatures.";
3287 goto err;
3290 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3291 int res;
3292 int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
3293 pending_consensus_t *pc = &pending_consensuses[i];
3294 if (!pc->consensus)
3295 continue;
3296 res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
3297 severity, msg_out);
3298 if (res < 0)
3299 errors++;
3300 else
3301 n_added += res;
3304 if (errors && !n_added) {
3305 r = -1;
3306 goto err;
3309 if (n_added && pending_consensuses[FLAV_NS].consensus) {
3310 char *new_detached =
3311 get_detached_signatures_from_pending_consensuses(
3312 pending_consensuses, N_CONSENSUS_FLAVORS);
3313 if (new_detached) {
3314 tor_free(pending_consensus_signatures);
3315 pending_consensus_signatures = new_detached;
3319 r = n_added;
3320 goto done;
3321 err:
3322 if (!*msg_out)
3323 *msg_out = "Unrecognized error while adding detached signatures.";
3324 done:
3325 ns_detached_signatures_free(sigs);
3326 /* XXXX NM Check how return is used. We can now have an error *and*
3327 signatures added. */
3328 return r;
3331 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3332 * signatures on the currently pending consensus. Add them to the pending
3333 * consensus (if we have one); otherwise queue them until we have a
3334 * consensus. Return negative on failure, nonnegative on success. */
3336 dirvote_add_signatures(const char *detached_signatures_body,
3337 const char *source,
3338 const char **msg)
3340 if (pending_consensuses[FLAV_NS].consensus) {
3341 log_notice(LD_DIR, "Got a signature from %s. "
3342 "Adding it to the pending consensus.", source);
3343 return dirvote_add_signatures_to_all_pending_consensuses(
3344 detached_signatures_body, source, msg);
3345 } else {
3346 log_notice(LD_DIR, "Got a signature from %s. "
3347 "Queuing it for the next consensus.", source);
3348 if (!pending_consensus_signature_list)
3349 pending_consensus_signature_list = smartlist_new();
3350 smartlist_add(pending_consensus_signature_list,
3351 tor_strdup(detached_signatures_body));
3352 *msg = "Signature queued";
3353 return 0;
3357 /** Replace the consensus that we're currently serving with the one that we've
3358 * been building. (V3 Authority only) */
3359 static int
3360 dirvote_publish_consensus(void)
3362 int i;
3364 /* Now remember all the other consensuses as if we were a directory cache. */
3365 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3366 pending_consensus_t *pending = &pending_consensuses[i];
3367 const char *name;
3368 name = networkstatus_get_flavor_name(i);
3369 tor_assert(name);
3370 if (!pending->consensus ||
3371 networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
3372 log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
3373 continue;
3376 if (networkstatus_set_current_consensus(pending->body, name, 0))
3377 log_warn(LD_DIR, "Error publishing %s consensus", name);
3378 else
3379 log_notice(LD_DIR, "Published %s consensus", name);
3382 return 0;
3385 /** Release all static storage held in dirvote.c */
3386 void
3387 dirvote_free_all(void)
3389 dirvote_clear_votes(1);
3390 /* now empty as a result of dirvote_clear_votes(). */
3391 smartlist_free(pending_vote_list);
3392 pending_vote_list = NULL;
3393 smartlist_free(previous_vote_list);
3394 previous_vote_list = NULL;
3396 dirvote_clear_pending_consensuses();
3397 tor_free(pending_consensus_signatures);
3398 if (pending_consensus_signature_list) {
3399 /* now empty as a result of dirvote_clear_votes(). */
3400 smartlist_free(pending_consensus_signature_list);
3401 pending_consensus_signature_list = NULL;
3405 /* ====
3406 * Access to pending items.
3407 * ==== */
3409 /** Return the body of the consensus that we're currently trying to build. */
3410 MOCK_IMPL(const char *,
3411 dirvote_get_pending_consensus, (consensus_flavor_t flav))
3413 tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
3414 return pending_consensuses[flav].body;
3417 /** Return the signatures that we know for the consensus that we're currently
3418 * trying to build. */
3419 MOCK_IMPL(const char *,
3420 dirvote_get_pending_detached_signatures, (void))
3422 return pending_consensus_signatures;
3425 /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
3426 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
3427 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
3428 * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
3429 * false, do not consider any votes for a consensus that's already been built.
3430 * If <b>include_pending</b> is false, do not consider any votes for the
3431 * consensus that's in progress. May return NULL if we have no vote for the
3432 * authority in question. */
3433 const cached_dir_t *
3434 dirvote_get_vote(const char *fp, int flags)
3436 int by_id = flags & DGV_BY_ID;
3437 const int include_pending = flags & DGV_INCLUDE_PENDING;
3438 const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
3440 if (!pending_vote_list && !previous_vote_list)
3441 return NULL;
3442 if (fp == NULL) {
3443 authority_cert_t *c = get_my_v3_authority_cert();
3444 if (c) {
3445 fp = c->cache_info.identity_digest;
3446 by_id = 1;
3447 } else
3448 return NULL;
3450 if (by_id) {
3451 if (pending_vote_list && include_pending) {
3452 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3453 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3454 return pv->vote_body);
3456 if (previous_vote_list && include_previous) {
3457 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3458 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3459 return pv->vote_body);
3461 } else {
3462 if (pending_vote_list && include_pending) {
3463 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3464 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3465 return pv->vote_body);
3467 if (previous_vote_list && include_previous) {
3468 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3469 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3470 return pv->vote_body);
3473 return NULL;
3476 /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
3477 * according to <b>consensus_method</b>.
3479 microdesc_t *
3480 dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
3482 microdesc_t *result = NULL;
3483 char *key = NULL, *summary = NULL, *family = NULL;
3484 size_t keylen;
3485 smartlist_t *chunks = smartlist_new();
3486 char *output = NULL;
3488 if (crypto_pk_write_public_key_to_string(ri->onion_pkey, &key, &keylen)<0)
3489 goto done;
3490 summary = policy_summarize(ri->exit_policy, AF_INET);
3491 if (ri->declared_family)
3492 family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
3494 smartlist_add_asprintf(chunks, "onion-key\n%s", key);
3496 if (consensus_method >= MIN_METHOD_FOR_NTOR_KEY &&
3497 ri->onion_curve25519_pkey) {
3498 char kbuf[128];
3499 base64_encode(kbuf, sizeof(kbuf),
3500 (const char*)ri->onion_curve25519_pkey->public_key,
3501 CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
3502 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
3505 if (consensus_method >= MIN_METHOD_FOR_A_LINES &&
3506 !tor_addr_is_null(&ri->ipv6_addr) && ri->ipv6_orport)
3507 smartlist_add_asprintf(chunks, "a %s\n",
3508 fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
3510 if (family)
3511 smartlist_add_asprintf(chunks, "family %s\n", family);
3513 if (summary && strcmp(summary, "reject 1-65535"))
3514 smartlist_add_asprintf(chunks, "p %s\n", summary);
3516 if (consensus_method >= MIN_METHOD_FOR_P6_LINES &&
3517 ri->ipv6_exit_policy) {
3518 /* XXXX024 This doesn't match proposal 208, which says these should
3519 * be taken unchanged from the routerinfo. That's bogosity, IMO:
3520 * the proposal should have said to do this instead.*/
3521 char *p6 = write_short_policy(ri->ipv6_exit_policy);
3522 if (p6 && strcmp(p6, "reject 1-65535"))
3523 smartlist_add_asprintf(chunks, "p6 %s\n", p6);
3524 tor_free(p6);
3527 if (consensus_method >= MIN_METHOD_FOR_ID_HASH_IN_MD) {
3528 char idbuf[ED25519_BASE64_LEN+1];
3529 const char *keytype;
3530 if (consensus_method >= MIN_METHOD_FOR_ED25519_ID_IN_MD &&
3531 ri->signing_key_cert &&
3532 ri->signing_key_cert->signing_key_included) {
3533 keytype = "ed25519";
3534 ed25519_public_to_base64(idbuf, &ri->signing_key_cert->signing_key);
3535 } else {
3536 keytype = "rsa1024";
3537 digest_to_base64(idbuf, ri->cache_info.identity_digest);
3539 smartlist_add_asprintf(chunks, "id %s %s\n", keytype, idbuf);
3542 output = smartlist_join_strings(chunks, "", 0, NULL);
3545 smartlist_t *lst = microdescs_parse_from_string(output,
3546 output+strlen(output), 0,
3547 SAVED_NOWHERE, NULL);
3548 if (smartlist_len(lst) != 1) {
3549 log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
3550 SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
3551 smartlist_free(lst);
3552 goto done;
3554 result = smartlist_get(lst, 0);
3555 smartlist_free(lst);
3558 done:
3559 tor_free(output);
3560 tor_free(key);
3561 tor_free(summary);
3562 tor_free(family);
3563 if (chunks) {
3564 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
3565 smartlist_free(chunks);
3567 return result;
3570 /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
3571 * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
3572 * in <b>out</b>. Return -1 on failure and the number of characters written
3573 * on success. */
3574 ssize_t
3575 dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
3576 const microdesc_t *md,
3577 int consensus_method_low,
3578 int consensus_method_high)
3580 ssize_t ret = -1;
3581 char d64[BASE64_DIGEST256_LEN+1];
3582 char *microdesc_consensus_methods =
3583 make_consensus_method_list(consensus_method_low,
3584 consensus_method_high,
3585 ",");
3586 tor_assert(microdesc_consensus_methods);
3588 if (digest256_to_base64(d64, md->digest)<0)
3589 goto out;
3591 if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
3592 microdesc_consensus_methods, d64)<0)
3593 goto out;
3595 ret = strlen(out_buf);
3597 out:
3598 tor_free(microdesc_consensus_methods);
3599 return ret;
3602 /** Array of start and end of consensus methods used for supported
3603 microdescriptor formats. */
3604 static const struct consensus_method_range_t {
3605 int low;
3606 int high;
3607 } microdesc_consensus_methods[] = {
3608 {MIN_SUPPORTED_CONSENSUS_METHOD, MIN_METHOD_FOR_A_LINES - 1},
3609 {MIN_METHOD_FOR_A_LINES, MIN_METHOD_FOR_P6_LINES - 1},
3610 {MIN_METHOD_FOR_P6_LINES, MIN_METHOD_FOR_NTOR_KEY - 1},
3611 {MIN_METHOD_FOR_NTOR_KEY, MIN_METHOD_FOR_ID_HASH_IN_MD - 1},
3612 {MIN_METHOD_FOR_ID_HASH_IN_MD, MIN_METHOD_FOR_ED25519_ID_IN_MD - 1},
3613 {MIN_METHOD_FOR_ED25519_ID_IN_MD, MAX_SUPPORTED_CONSENSUS_METHOD},
3614 {-1, -1}
3617 /** Helper type used when generating the microdescriptor lines in a directory
3618 * vote. */
3619 typedef struct microdesc_vote_line_t {
3620 int low;
3621 int high;
3622 microdesc_t *md;
3623 struct microdesc_vote_line_t *next;
3624 } microdesc_vote_line_t;
3626 /** Generate and return a linked list of all the lines that should appear to
3627 * describe a router's microdescriptor versions in a directory vote.
3628 * Add the generated microdescriptors to <b>microdescriptors_out</b>. */
3629 vote_microdesc_hash_t *
3630 dirvote_format_all_microdesc_vote_lines(const routerinfo_t *ri, time_t now,
3631 smartlist_t *microdescriptors_out)
3633 const struct consensus_method_range_t *cmr;
3634 microdesc_vote_line_t *entries = NULL, *ep;
3635 vote_microdesc_hash_t *result = NULL;
3637 /* Generate the microdescriptors. */
3638 for (cmr = microdesc_consensus_methods;
3639 cmr->low != -1 && cmr->high != -1;
3640 cmr++) {
3641 microdesc_t *md = dirvote_create_microdescriptor(ri, cmr->low);
3642 if (md) {
3643 microdesc_vote_line_t *e =
3644 tor_malloc_zero(sizeof(microdesc_vote_line_t));
3645 e->md = md;
3646 e->low = cmr->low;
3647 e->high = cmr->high;
3648 e->next = entries;
3649 entries = e;
3653 /* Compress adjacent identical ones */
3654 for (ep = entries; ep; ep = ep->next) {
3655 while (ep->next &&
3656 fast_memeq(ep->md->digest, ep->next->md->digest, DIGEST256_LEN) &&
3657 ep->low == ep->next->high + 1) {
3658 microdesc_vote_line_t *next = ep->next;
3659 ep->low = next->low;
3660 microdesc_free(next->md);
3661 ep->next = next->next;
3662 tor_free(next);
3666 /* Format them into vote_microdesc_hash_t, and add to microdescriptors_out.*/
3667 while ((ep = entries)) {
3668 char buf[128];
3669 vote_microdesc_hash_t *h;
3670 dirvote_format_microdesc_vote_line(buf, sizeof(buf), ep->md,
3671 ep->low, ep->high);
3672 h = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
3673 h->microdesc_hash_line = tor_strdup(buf);
3674 h->next = result;
3675 result = h;
3676 ep->md->last_listed = now;
3677 smartlist_add(microdescriptors_out, ep->md);
3678 entries = ep->next;
3679 tor_free(ep);
3682 return result;
3685 /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
3686 * the digest algorithm <b>alg</b>, decode it and copy it into
3687 * <b>digest256_out</b> and return 0. Otherwise return -1. */
3689 vote_routerstatus_find_microdesc_hash(char *digest256_out,
3690 const vote_routerstatus_t *vrs,
3691 int method,
3692 digest_algorithm_t alg)
3694 /* XXXX only returns the sha256 method. */
3695 const vote_microdesc_hash_t *h;
3696 char mstr[64];
3697 size_t mlen;
3698 char dstr[64];
3700 tor_snprintf(mstr, sizeof(mstr), "%d", method);
3701 mlen = strlen(mstr);
3702 tor_snprintf(dstr, sizeof(dstr), " %s=",
3703 crypto_digest_algorithm_get_name(alg));
3705 for (h = vrs->microdesc; h; h = h->next) {
3706 const char *cp = h->microdesc_hash_line;
3707 size_t num_len;
3708 /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
3709 * the first part. */
3710 while (1) {
3711 num_len = strspn(cp, "1234567890");
3712 if (num_len == mlen && fast_memeq(mstr, cp, mlen)) {
3713 /* This is the line. */
3714 char buf[BASE64_DIGEST256_LEN+1];
3715 /* XXXX ignores extraneous stuff if the digest is too long. This
3716 * seems harmless enough, right? */
3717 cp = strstr(cp, dstr);
3718 if (!cp)
3719 return -1;
3720 cp += strlen(dstr);
3721 strlcpy(buf, cp, sizeof(buf));
3722 return digest256_from_base64(digest256_out, buf);
3724 if (num_len == 0 || cp[num_len] != ',')
3725 break;
3726 cp += num_len + 1;
3729 return -1;