Tor 0.5.0-alpha-dev
Loading...
Searching...
No Matches
dirvote.c
Go to the documentation of this file.
1/* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
4/* See LICENSE for licensing information */
5
6#define DIRVOTE_PRIVATE
7
8#include "core/or/or.h"
9#include "app/config/config.h"
11#include "core/or/policies.h"
12#include "core/or/protover.h"
14#include "core/or/versions.h"
39#include "feature/client/entrynodes.h" /* needed for guardfraction methods */
42
47
63
64#include "lib/container/order.h"
67
68/* Algorithm to use for the bandwidth file digest. */
69#define DIGEST_ALG_BW_FILE DIGEST_SHA256
70
71/**
72 * \file dirvote.c
73 * \brief Functions to compute directory consensus, and schedule voting.
74 *
75 * This module is the center of the consensus-voting based directory
76 * authority system. With this system, a set of authorities first
77 * publish vote based on their opinions of the network, and then compute
78 * a consensus from those votes. Each authority signs the consensus,
79 * and clients trust the consensus if enough known authorities have
80 * signed it.
81 *
82 * The code in this module is only invoked on directory authorities. It's
83 * responsible for:
84 *
85 * <ul>
86 * <li>Generating this authority's vote networkstatus, based on the
87 * authority's view of the network as represented in dirserv.c
88 * <li>Formatting the vote networkstatus objects.
89 * <li>Generating the microdescriptors that correspond to our own
90 * vote.
91 * <li>Sending votes to all the other authorities.
92 * <li>Trying to fetch missing votes from other authorities.
93 * <li>Computing the consensus from a set of votes, as well as
94 * a "detached signature" object for other authorities to fetch.
95 * <li>Collecting other authorities' signatures on the same consensus,
96 * until there are enough.
97 * <li>Publishing the consensus to the reset of the directory system.
98 * <li>Scheduling all of the above operations.
99 * </ul>
100 *
101 * The main entry points are in dirvote_act(), which handles scheduled
102 * actions; and dirvote_add_vote() and dirvote_add_signatures(), which
103 * handle uploaded and downloaded votes and signatures.
104 *
105 * (See dir-spec.txt from torspec.git for a complete specification of
106 * the directory protocol and voting algorithms.)
107 **/
108
109/** A consensus that we have built and are appending signatures to. Once it's
110 * time to publish it, it will become an active consensus if it accumulates
111 * enough signatures. */
112typedef struct pending_consensus_t {
113 /** The body of the consensus that we're currently building. Once we
114 * have it built, it goes into dirserv.c */
115 char *body;
116 /** The parsed in-progress consensus document. */
118 /** Have we reached the critical number of sigs on this consensus, and
119 * exported it for the consensus transparency module? */
122
123/* DOCDOC dirvote_add_signatures_to_all_pending_consensuses */
125 const char *detached_signatures_body,
126 const char *source,
127 const char **msg_out);
131 const char *source,
132 int severity,
133 const char **msg_out);
134static char *list_v3_auth_ids(void);
135static void dirvote_fetch_missing_votes(void);
136static void dirvote_fetch_missing_signatures(void);
137static int dirvote_perform_vote(void);
138static void dirvote_clear_votes(int all_votes);
139static int dirvote_compute_consensuses(void);
140static int dirvote_publish_consensus(void);
141
142/* =====
143 * Certificate functions
144 * ===== */
145
146/** Allocate and return a new authority_cert_t with the same contents as
147 * <b>cert</b>. */
150{
151 authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
152 tor_assert(cert);
153
154 memcpy(out, cert, sizeof(authority_cert_t));
155 /* Now copy pointed-to things. */
157 tor_strndup(cert->cache_info.signed_descriptor_body,
162
163 return out;
164}
165
166/* =====
167 * Voting
168 * =====*/
169
170/* If <b>opt_value</b> is non-NULL, return "keyword opt_value\n" in a new
171 * string. Otherwise return a new empty string. */
172static char *
173format_line_if_present(const char *keyword, const char *opt_value)
174{
175 if (opt_value) {
176 char *result = NULL;
177 tor_asprintf(&result, "%s %s\n", keyword, opt_value);
178 return result;
179 } else {
180 return tor_strdup("");
181 }
182}
183
184/** Format the recommended/required-relay-client protocols lines for a vote in
185 * a newly allocated string, and return that string. */
186static char *
188{
189 char *recommended_relay_protocols_line = NULL;
190 char *recommended_client_protocols_line = NULL;
191 char *required_relay_protocols_line = NULL;
192 char *required_client_protocols_line = NULL;
193
194 recommended_relay_protocols_line =
195 format_line_if_present("recommended-relay-protocols",
197 recommended_client_protocols_line =
198 format_line_if_present("recommended-client-protocols",
199 v3_ns->recommended_client_protocols);
200 required_relay_protocols_line =
201 format_line_if_present("required-relay-protocols",
202 v3_ns->required_relay_protocols);
203 required_client_protocols_line =
204 format_line_if_present("required-client-protocols",
205 v3_ns->required_client_protocols);
206
207 char *result = NULL;
208 tor_asprintf(&result, "%s%s%s%s",
209 recommended_relay_protocols_line,
210 recommended_client_protocols_line,
211 required_relay_protocols_line,
212 required_client_protocols_line);
213
214 tor_free(recommended_relay_protocols_line);
215 tor_free(recommended_client_protocols_line);
216 tor_free(required_relay_protocols_line);
217 tor_free(required_client_protocols_line);
218
219 return result;
220}
221
222/** Return a new string containing the string representation of the vote in
223 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
224 * For v3 authorities. */
225STATIC char *
227 networkstatus_t *v3_ns)
228{
229 smartlist_t *chunks = smartlist_new();
230 char fingerprint[FINGERPRINT_LEN+1];
231 char digest[DIGEST_LEN];
232 char *protocols_lines = NULL;
233 char *client_versions_line = NULL, *server_versions_line = NULL;
234 char *shared_random_vote_str = NULL;
236 char *status = NULL;
237
238 tor_assert(private_signing_key);
239 tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
240
241 voter = smartlist_get(v3_ns->voters, 0);
242
243 base16_encode(fingerprint, sizeof(fingerprint),
245
246 client_versions_line = format_line_if_present("client-versions",
247 v3_ns->client_versions);
248 server_versions_line = format_line_if_present("server-versions",
249 v3_ns->server_versions);
250 protocols_lines = format_protocols_lines_for_vote(v3_ns);
251
252 /* Get shared random commitments/reveals line(s). */
253 shared_random_vote_str = sr_get_string_for_vote();
254
255 {
256 char published[ISO_TIME_LEN+1];
257 char va[ISO_TIME_LEN+1];
258 char fu[ISO_TIME_LEN+1];
259 char vu[ISO_TIME_LEN+1];
260 char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
261 /* XXXX Abstraction violation: should be pulling a field out of v3_ns.*/
262 char *flag_thresholds = dirserv_get_flag_thresholds_line();
263 char *params;
264 char *bw_headers_line = NULL;
265 char *bw_file_digest = NULL;
266 authority_cert_t *cert = v3_ns->cert;
267 char *methods =
270 format_iso_time(published, v3_ns->published);
271 format_iso_time(va, v3_ns->valid_after);
272 format_iso_time(fu, v3_ns->fresh_until);
273 format_iso_time(vu, v3_ns->valid_until);
274
275 if (v3_ns->net_params)
276 params = smartlist_join_strings(v3_ns->net_params, " ", 0, NULL);
277 else
278 params = tor_strdup("");
279 tor_assert(cert);
280
281 /* v3_ns->bw_file_headers is only set when V3BandwidthsFile is
282 * configured */
283 if (v3_ns->bw_file_headers) {
284 char *bw_file_headers = NULL;
285 /* If there are too many headers, leave the header string NULL */
286 if (! BUG(smartlist_len(v3_ns->bw_file_headers)
288 bw_file_headers = smartlist_join_strings(v3_ns->bw_file_headers, " ",
289 0, NULL);
290 if (BUG(strlen(bw_file_headers) > MAX_BW_FILE_HEADERS_LINE_LEN)) {
291 /* Free and set to NULL, because the line was too long */
292 tor_free(bw_file_headers);
293 }
294 }
295 if (!bw_file_headers) {
296 /* If parsing failed, add a bandwidth header line with no entries */
297 bw_file_headers = tor_strdup("");
298 }
299 /* At this point, the line will always be present */
300 bw_headers_line = format_line_if_present("bandwidth-file-headers",
301 bw_file_headers);
302 tor_free(bw_file_headers);
303 }
304
305 /* Create bandwidth-file-digest if applicable.
306 * v3_ns->b64_digest_bw_file will contain the digest when V3BandwidthsFile
307 * is configured and the bandwidth file could be read, even if it was not
308 * parseable.
309 */
310 if (!tor_digest256_is_zero((const char *)v3_ns->bw_file_digest256)) {
311 /* Encode the digest. */
312 char b64_digest_bw_file[BASE64_DIGEST256_LEN+1] = {0};
313 digest256_to_base64(b64_digest_bw_file,
314 (const char *)v3_ns->bw_file_digest256);
315 /* "bandwidth-file-digest" 1*(SP algorithm "=" digest) NL */
316 char *digest_algo_b64_digest_bw_file = NULL;
317 tor_asprintf(&digest_algo_b64_digest_bw_file, "%s=%s",
318 crypto_digest_algorithm_get_name(DIGEST_ALG_BW_FILE),
319 b64_digest_bw_file);
320 /* No need for tor_strdup(""), format_line_if_present does it. */
321 bw_file_digest = format_line_if_present(
322 "bandwidth-file-digest", digest_algo_b64_digest_bw_file);
323 tor_free(digest_algo_b64_digest_bw_file);
324 }
325
326 const char *ip_str = fmt_addr(&voter->ipv4_addr);
327
328 if (ip_str[0]) {
330 "network-status-version 3\n"
331 "vote-status %s\n"
332 "consensus-methods %s\n"
333 "published %s\n"
334 "valid-after %s\n"
335 "fresh-until %s\n"
336 "valid-until %s\n"
337 "voting-delay %d %d\n"
338 "%s%s" /* versions */
339 "%s" /* protocols */
340 "known-flags %s\n"
341 "flag-thresholds %s\n"
342 "params %s\n"
343 "%s" /* bandwidth file headers */
344 "%s" /* bandwidth file digest */
345 "dir-source %s %s %s %s %d %d\n"
346 "contact %s\n"
347 "%s" /* shared randomness information */
348 ,
349 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
350 methods,
351 published, va, fu, vu,
352 v3_ns->vote_seconds, v3_ns->dist_seconds,
353 client_versions_line,
354 server_versions_line,
355 protocols_lines,
356 flags,
357 flag_thresholds,
358 params,
359 bw_headers_line ? bw_headers_line : "",
360 bw_file_digest ? bw_file_digest: "",
361 voter->nickname, fingerprint, voter->address,
362 ip_str, voter->ipv4_dirport, voter->ipv4_orport,
363 voter->contact,
364 shared_random_vote_str ?
365 shared_random_vote_str : "");
366 }
367
368 tor_free(params);
369 tor_free(flags);
370 tor_free(flag_thresholds);
371 tor_free(methods);
372 tor_free(shared_random_vote_str);
373 tor_free(bw_headers_line);
374 tor_free(bw_file_digest);
375
376 if (ip_str[0] == '\0')
377 goto err;
378
380 char fpbuf[HEX_DIGEST_LEN+1];
381 base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
382 smartlist_add_asprintf(chunks, "legacy-dir-key %s\n", fpbuf);
383 }
384
385 smartlist_add(chunks, tor_strndup(cert->cache_info.signed_descriptor_body,
387 }
388
390 vrs) {
391 char *rsf;
393 rsf = routerstatus_format_entry(&vrs->status,
394 vrs->version, vrs->protocols,
396 vrs,
397 -1);
398 if (rsf)
399 smartlist_add(chunks, rsf);
400
401 for (h = vrs->microdesc; h; h = h->next) {
403 }
404 } SMARTLIST_FOREACH_END(vrs);
405
406 smartlist_add_strdup(chunks, "directory-footer\n");
407
408 /* The digest includes everything up through the space after
409 * directory-signature. (Yuck.) */
410 crypto_digest_smartlist(digest, DIGEST_LEN, chunks,
411 "directory-signature ", DIGEST_SHA1);
412
413 {
414 char signing_key_fingerprint[FINGERPRINT_LEN+1];
415 if (crypto_pk_get_fingerprint(private_signing_key,
416 signing_key_fingerprint, 0)<0) {
417 log_warn(LD_BUG, "Unable to get fingerprint for signing key");
418 goto err;
419 }
420
421 smartlist_add_asprintf(chunks, "directory-signature %s %s\n", fingerprint,
422 signing_key_fingerprint);
423 }
424
425 {
426 char *sig = router_get_dirobj_signature(digest, DIGEST_LEN,
427 private_signing_key);
428 if (!sig) {
429 log_warn(LD_BUG, "Unable to sign networkstatus vote.");
430 goto err;
431 }
432 smartlist_add(chunks, sig);
433 }
434
435 status = smartlist_join_strings(chunks, "", 0, NULL);
436
437 {
439 if (!(v = networkstatus_parse_vote_from_string(status, strlen(status),
440 NULL,
441 v3_ns->type))) {
442 log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
443 "<<%s>>",
444 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
445 goto err;
446 }
447 networkstatus_vote_free(v);
448 }
449
450 goto done;
451
452 err:
453 tor_free(status);
454 done:
455 tor_free(client_versions_line);
456 tor_free(server_versions_line);
457 tor_free(protocols_lines);
458
459 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
460 smartlist_free(chunks);
461 return status;
462}
463
464/** Set *<b>timing_out</b> to the intervals at which we would like to vote.
465 * Note that these aren't the intervals we'll use to vote; they're the ones
466 * that we'll vote to use. */
467static void
469{
470 const or_options_t *options = get_options();
471
472 tor_assert(timing_out);
473
474 timing_out->vote_interval = options->V3AuthVotingInterval;
475 timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
476 timing_out->vote_delay = options->V3AuthVoteDelay;
477 timing_out->dist_delay = options->V3AuthDistDelay;
478}
479
480/* =====
481 * Consensus generation
482 * ===== */
483
484/** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
485 * the digest algorithm <b>alg</b>, decode it and copy it into
486 * <b>digest256_out</b> and return 0. Otherwise return -1. */
487static int
489 const vote_routerstatus_t *vrs,
490 int method,
492{
493 /* XXXX only returns the sha256 method. */
494 const vote_microdesc_hash_t *h;
495 char mstr[64];
496 size_t mlen;
497 char dstr[64];
498
499 tor_snprintf(mstr, sizeof(mstr), "%d", method);
500 mlen = strlen(mstr);
501 tor_snprintf(dstr, sizeof(dstr), " %s=",
503
504 for (h = vrs->microdesc; h; h = h->next) {
505 const char *cp = h->microdesc_hash_line;
506 size_t num_len;
507 /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
508 * the first part. */
509 while (1) {
510 num_len = strspn(cp, "1234567890");
511 if (num_len == mlen && fast_memeq(mstr, cp, mlen)) {
512 /* This is the line. */
513 char buf[BASE64_DIGEST256_LEN+1];
514 /* XXXX ignores extraneous stuff if the digest is too long. This
515 * seems harmless enough, right? */
516 cp = strstr(cp, dstr);
517 if (!cp)
518 return -1;
519 cp += strlen(dstr);
520 strlcpy(buf, cp, sizeof(buf));
521 return digest256_from_base64(digest256_out, buf);
522 }
523 if (num_len == 0 || cp[num_len] != ',')
524 break;
525 cp += num_len + 1;
526 }
527 }
528 return -1;
529}
530
531/** Given a vote <b>vote</b> (not a consensus!), return its associated
532 * networkstatus_voter_info_t. */
535{
536 tor_assert(vote);
537 tor_assert(vote->type == NS_TYPE_VOTE);
538 tor_assert(vote->voters);
539 tor_assert(smartlist_len(vote->voters) == 1);
540 return smartlist_get(vote->voters, 0);
541}
542
543/** Temporary structure used in constructing a list of dir-source entries
544 * for a consensus. One of these is generated for every vote, and one more
545 * for every legacy key in each vote. */
546typedef struct dir_src_ent_t {
548 const char *digest;
549 int is_legacy;
551
552/** Helper for sorting networkstatus_t votes (not consensuses) by the
553 * hash of their voters' identity digests. */
554static int
555compare_votes_by_authority_id_(const void **_a, const void **_b)
556{
557 const networkstatus_t *a = *_a, *b = *_b;
558 return fast_memcmp(get_voter(a)->identity_digest,
559 get_voter(b)->identity_digest, DIGEST_LEN);
560}
561
562/** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
563 * their identity digests, and return -1, 0, or 1 depending on their
564 * ordering */
565static int
566compare_dir_src_ents_by_authority_id_(const void **_a, const void **_b)
567{
568 const dir_src_ent_t *a = *_a, *b = *_b;
569 const networkstatus_voter_info_t *a_v = get_voter(a->v),
570 *b_v = get_voter(b->v);
571 const char *a_id, *b_id;
572 a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
573 b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;
574
575 return fast_memcmp(a_id, b_id, DIGEST_LEN);
576}
577
578/** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
579 * that occurs more than <b>min</b> times. */
580static void
582{
583 char *cur = NULL;
584 int count = 0;
585 SMARTLIST_FOREACH_BEGIN(in, char *, cp) {
586 if (cur && !strcmp(cp, cur)) {
587 ++count;
588 } else {
589 if (count > min)
590 smartlist_add(out, cur);
591 cur = cp;
592 count = 1;
593 }
594 } SMARTLIST_FOREACH_END(cp);
595 if (count > min)
596 smartlist_add(out, cur);
597}
598
599/** Given a sorted list of strings <b>lst</b>, return the member that appears
600 * most. Break ties in favor of later-occurring members. */
601#define get_most_frequent_member(lst) \
602 smartlist_get_most_frequent_string(lst)
603
604/** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
605 * that come from the same routerinfo, with the same derived elements.
606 */
607static int
609{
610 int r;
611 tor_assert(a);
612 tor_assert(b);
613
615 DIGEST_LEN)))
616 return r;
619 DIGEST_LEN)))
620 return r;
621 /* If we actually reached this point, then the identities and
622 * the descriptor digests matched, so somebody is making SHA1 collisions.
623 */
624#define CMP_FIELD(utype, itype, field) do { \
625 utype aval = (utype) (itype) a->field; \
626 utype bval = (utype) (itype) b->field; \
627 utype u = bval - aval; \
628 itype r2 = (itype) u; \
629 if (r2 < 0) { \
630 return -1; \
631 } else if (r2 > 0) { \
632 return 1; \
633 } \
634 } while (0)
635
636 CMP_FIELD(uint64_t, int64_t, published_on);
637
638 if ((r = strcmp(b->status.nickname, a->status.nickname)))
639 return r;
640
641 if ((r = tor_addr_compare(&a->status.ipv4_addr, &b->status.ipv4_addr,
642 CMP_EXACT))) {
643 return r;
644 }
645 CMP_FIELD(unsigned, int, status.ipv4_orport);
646 CMP_FIELD(unsigned, int, status.ipv4_dirport);
647
648 return 0;
649}
650
651/** Helper for sorting routerlists based on compare_vote_rs. */
652static int
653compare_vote_rs_(const void **_a, const void **_b)
654{
655 const vote_routerstatus_t *a = *_a, *b = *_b;
656 return compare_vote_rs(a,b);
657}
658
659/** Helper for sorting OR ports. */
660static int
661compare_orports_(const void **_a, const void **_b)
662{
663 const tor_addr_port_t *a = *_a, *b = *_b;
664 int r;
665
666 if ((r = tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
667 return r;
668 if ((r = (((int) b->port) - ((int) a->port))))
669 return r;
670
671 return 0;
672}
673
674/** Given a list of vote_routerstatus_t, all for the same router identity,
675 * return whichever is most frequent, breaking ties in favor of more
676 * recently published vote_routerstatus_t and in case of ties there,
677 * in favor of smaller descriptor digest.
678 */
679static vote_routerstatus_t *
680compute_routerstatus_consensus(smartlist_t *votes, int consensus_method,
681 char *microdesc_digest256_out,
682 tor_addr_port_t *best_alt_orport_out)
683{
684 vote_routerstatus_t *most = NULL, *cur = NULL;
685 int most_n = 0, cur_n = 0;
686 time_t most_published = 0;
687
688 /* compare_vote_rs_() sorts the items by identity digest (all the same),
689 * then by SD digest. That way, if we have a tie that the published_on
690 * date cannot break, we use the descriptor with the smaller digest.
691 */
694 if (cur && !compare_vote_rs(cur, rs)) {
695 ++cur_n;
696 } else {
697 if (cur && (cur_n > most_n ||
698 (cur_n == most_n &&
699 cur->published_on > most_published))) {
700 most = cur;
701 most_n = cur_n;
702 most_published = cur->published_on;
703 }
704 cur_n = 1;
705 cur = rs;
706 }
707 } SMARTLIST_FOREACH_END(rs);
708
709 if (cur_n > most_n ||
710 (cur && cur_n == most_n && cur->published_on > most_published)) {
711 most = cur;
712 // most_n = cur_n; // unused after this point.
713 // most_published = cur->status.published_on; // unused after this point.
714 }
715
716 tor_assert(most);
717
718 /* Vote on potential alternative (sets of) OR port(s) in the winning
719 * routerstatuses.
720 *
721 * XXX prop186 There's at most one alternative OR port (_the_ IPv6
722 * port) for now. */
723 if (best_alt_orport_out) {
724 smartlist_t *alt_orports = smartlist_new();
725 const tor_addr_port_t *most_alt_orport = NULL;
726
728 tor_assert(rs);
729 if (compare_vote_rs(most, rs) == 0 &&
730 !tor_addr_is_null(&rs->status.ipv6_addr)
731 && rs->status.ipv6_orport) {
732 smartlist_add(alt_orports, tor_addr_port_new(&rs->status.ipv6_addr,
733 rs->status.ipv6_orport));
734 }
735 } SMARTLIST_FOREACH_END(rs);
736
737 smartlist_sort(alt_orports, compare_orports_);
738 most_alt_orport = smartlist_get_most_frequent(alt_orports,
740 if (most_alt_orport) {
741 memcpy(best_alt_orport_out, most_alt_orport, sizeof(tor_addr_port_t));
742 log_debug(LD_DIR, "\"a\" line winner for %s is %s",
743 most->status.nickname,
744 fmt_addrport(&most_alt_orport->addr, most_alt_orport->port));
745 }
746
747 SMARTLIST_FOREACH(alt_orports, tor_addr_port_t *, ap, tor_free(ap));
748 smartlist_free(alt_orports);
749 }
750
751 if (microdesc_digest256_out) {
752 smartlist_t *digests = smartlist_new();
753 const uint8_t *best_microdesc_digest;
755 char d[DIGEST256_LEN];
756 if (compare_vote_rs(rs, most))
757 continue;
758 if (!vote_routerstatus_find_microdesc_hash(d, rs, consensus_method,
759 DIGEST_SHA256))
760 smartlist_add(digests, tor_memdup(d, sizeof(d)));
761 } SMARTLIST_FOREACH_END(rs);
763 best_microdesc_digest = smartlist_get_most_frequent_digest256(digests);
764 if (best_microdesc_digest)
765 memcpy(microdesc_digest256_out, best_microdesc_digest, DIGEST256_LEN);
766 SMARTLIST_FOREACH(digests, char *, cp, tor_free(cp));
767 smartlist_free(digests);
768 }
769
770 return most;
771}
772
773/** Sorting helper: compare two strings based on their values as base-ten
774 * positive integers. (Non-integers are treated as prior to all integers, and
775 * compared lexically.) */
776static int
777cmp_int_strings_(const void **_a, const void **_b)
778{
779 const char *a = *_a, *b = *_b;
780 int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
781 int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
782 if (ai<bi) {
783 return -1;
784 } else if (ai==bi) {
785 if (ai == 0) /* Parsing failed. */
786 return strcmp(a, b);
787 return 0;
788 } else {
789 return 1;
790 }
791}
792
793/** Given a list of networkstatus_t votes, determine and return the number of
794 * the highest consensus method that is supported by 2/3 of the voters. */
795static int
797{
798 smartlist_t *all_methods = smartlist_new();
799 smartlist_t *acceptable_methods = smartlist_new();
800 smartlist_t *tmp = smartlist_new();
801 int min = (smartlist_len(votes) * 2) / 3;
802 int n_ok;
803 int result;
804 SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
805 {
806 tor_assert(vote->supported_methods);
807 smartlist_add_all(tmp, vote->supported_methods);
810 smartlist_add_all(all_methods, tmp);
811 smartlist_clear(tmp);
812 });
813
814 smartlist_sort(all_methods, cmp_int_strings_);
815 get_frequent_members(acceptable_methods, all_methods, min);
816 n_ok = smartlist_len(acceptable_methods);
817 if (n_ok) {
818 const char *best = smartlist_get(acceptable_methods, n_ok-1);
819 result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
820 } else {
821 result = 1;
822 }
823 smartlist_free(tmp);
824 smartlist_free(all_methods);
825 smartlist_free(acceptable_methods);
826 return result;
827}
828
829/** Return true iff <b>method</b> is a consensus method that we support. */
830static int
832{
833 return (method >= MIN_SUPPORTED_CONSENSUS_METHOD) &&
835}
836
837/** Return a newly allocated string holding the numbers between low and high
838 * (inclusive) that are supported consensus methods. */
839STATIC char *
840make_consensus_method_list(int low, int high, const char *separator)
841{
842 char *list;
843
844 int i;
845 smartlist_t *lst;
846 lst = smartlist_new();
847 for (i = low; i <= high; ++i) {
849 continue;
850 smartlist_add_asprintf(lst, "%d", i);
851 }
852 list = smartlist_join_strings(lst, separator, 0, NULL);
853 tor_assert(list);
854 SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
855 smartlist_free(lst);
856 return list;
857}
858
859/** Helper: given <b>lst</b>, a list of version strings such that every
860 * version appears once for every versioning voter who recommends it, return a
861 * newly allocated string holding the resulting client-versions or
862 * server-versions list. May change contents of <b>lst</b> */
863static char *
865{
866 int min = n_versioning / 2;
867 smartlist_t *good = smartlist_new();
868 char *result;
869 SMARTLIST_FOREACH_BEGIN(lst, const char *, v) {
870 if (strchr(v, ' ')) {
871 log_warn(LD_DIR, "At least one authority has voted for a version %s "
872 "that contains a space. This probably wasn't intentional, and "
873 "is likely to cause trouble. Please tell them to stop it.",
874 escaped(v));
875 }
876 } SMARTLIST_FOREACH_END(v);
877 sort_version_list(lst, 0);
878 get_frequent_members(good, lst, min);
879 result = smartlist_join_strings(good, ",", 0, NULL);
880 smartlist_free(good);
881 return result;
882}
883
884/** Given a list of K=V values, return the int32_t value corresponding to
885 * KEYWORD=, or default_val if no such value exists, or if the value is
886 * corrupt.
887 */
888STATIC int32_t
890 const char *keyword,
891 int32_t default_val)
892{
893 unsigned int n_found = 0;
894 int32_t value = default_val;
895
896 SMARTLIST_FOREACH_BEGIN(param_list, const char *, k_v_pair) {
897 if (!strcmpstart(k_v_pair, keyword) && k_v_pair[strlen(keyword)] == '=') {
898 const char *integer_str = &k_v_pair[strlen(keyword)+1];
899 int ok;
900 value = (int32_t)
901 tor_parse_long(integer_str, 10, INT32_MIN, INT32_MAX, &ok, NULL);
902 if (BUG(!ok))
903 return default_val;
904 ++n_found;
905 }
906 } SMARTLIST_FOREACH_END(k_v_pair);
907
908 if (n_found == 1) {
909 return value;
910 } else {
911 tor_assert_nonfatal(n_found == 0);
912 return default_val;
913 }
914}
915
916/** Minimum number of directory authorities voting for a parameter to
917 * include it in the consensus, if consensus method 12 or later is to be
918 * used. See proposal 178 for details. */
919#define MIN_VOTES_FOR_PARAM 3
920
921/** Helper: given a list of valid networkstatus_t, return a new smartlist
922 * containing the contents of the consensus network parameter set.
923 */
925dirvote_compute_params(smartlist_t *votes, int method, int total_authorities)
926{
927 int i;
928 int32_t *vals;
929
930 int cur_param_len;
931 const char *cur_param;
932 const char *eq;
933
934 const int n_votes = smartlist_len(votes);
935 smartlist_t *output;
936 smartlist_t *param_list = smartlist_new();
937 (void) method;
938
939 /* We require that the parameter lists in the votes are well-formed: that
940 is, that their keywords are unique and sorted, and that their values are
941 between INT32_MIN and INT32_MAX inclusive. This should be guaranteed by
942 the parsing code. */
943
944 vals = tor_calloc(n_votes, sizeof(int));
945
947 if (!v->net_params)
948 continue;
949 smartlist_add_all(param_list, v->net_params);
950 } SMARTLIST_FOREACH_END(v);
951
952 if (smartlist_len(param_list) == 0) {
953 tor_free(vals);
954 return param_list;
955 }
956
957 smartlist_sort_strings(param_list);
958 i = 0;
959 cur_param = smartlist_get(param_list, 0);
960 eq = strchr(cur_param, '=');
961 tor_assert(eq);
962 cur_param_len = (int)(eq+1 - cur_param);
963
964 output = smartlist_new();
965
966 SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
967 /* resolve spurious clang shallow analysis null pointer errors */
968 tor_assert(param);
969
970 const char *next_param;
971 int ok=0;
972 eq = strchr(param, '=');
973 tor_assert(i<n_votes); /* Make sure we prevented vote-stuffing. */
974 vals[i++] = (int32_t)
975 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
976 tor_assert(ok); /* Already checked these when parsing. */
977
978 if (param_sl_idx+1 == smartlist_len(param_list))
979 next_param = NULL;
980 else
981 next_param = smartlist_get(param_list, param_sl_idx+1);
982
983 if (!next_param || strncmp(next_param, param, cur_param_len)) {
984 /* We've reached the end of a series. */
985 /* Make sure enough authorities voted on this param, unless the
986 * the consensus method we use is too old for that. */
987 if (i > total_authorities/2 ||
988 i >= MIN_VOTES_FOR_PARAM) {
989 int32_t median = median_int32(vals, i);
990 char *out_string = tor_malloc(64+cur_param_len);
991 memcpy(out_string, param, cur_param_len);
992 tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
993 smartlist_add(output, out_string);
994 }
995
996 i = 0;
997 if (next_param) {
998 eq = strchr(next_param, '=');
999 cur_param_len = (int)(eq+1 - next_param);
1000 }
1001 }
1002 } SMARTLIST_FOREACH_END(param);
1003
1004 smartlist_free(param_list);
1005 tor_free(vals);
1006 return output;
1007}
1008
1009#define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
1010 ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
1011 (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
1012 (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
1013 (g) >= 0 && (g) <= (mx))
1014
1015#define CHECK_EQ(a, b, margin) \
1016 ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))
1017
1018typedef enum {
1019 BW_WEIGHTS_NO_ERROR = 0,
1020 BW_WEIGHTS_RANGE_ERROR = 1,
1021 BW_WEIGHTS_SUMG_ERROR = 2,
1022 BW_WEIGHTS_SUME_ERROR = 3,
1023 BW_WEIGHTS_SUMD_ERROR = 4,
1024 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
1025 BW_WEIGHTS_BALANCE_EG_ERROR = 6
1026} bw_weights_error_t;
1027
1028/**
1029 * Verify that any weightings satisfy the balanced formulas.
1030 */
1031static bw_weights_error_t
1032networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
1033 int64_t Wme, int64_t Wmd, int64_t Wee,
1034 int64_t Wed, int64_t scale, int64_t G,
1035 int64_t M, int64_t E, int64_t D, int64_t T,
1036 int64_t margin, int do_balance) {
1037 bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;
1038
1039 // Wed + Wmd + Wgd == 1
1040 if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
1041 berr = BW_WEIGHTS_SUMD_ERROR;
1042 goto out;
1043 }
1044
1045 // Wmg + Wgg == 1
1046 if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
1047 berr = BW_WEIGHTS_SUMG_ERROR;
1048 goto out;
1049 }
1050
1051 // Wme + Wee == 1
1052 if (!CHECK_EQ(Wme + Wee, scale, margin)) {
1053 berr = BW_WEIGHTS_SUME_ERROR;
1054 goto out;
1055 }
1056
1057 // Verify weights within range 0->1
1058 if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
1059 berr = BW_WEIGHTS_RANGE_ERROR;
1060 goto out;
1061 }
1062
1063 if (do_balance) {
1064 // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
1065 if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
1066 berr = BW_WEIGHTS_BALANCE_EG_ERROR;
1067 goto out;
1068 }
1069
1070 // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
1071 if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
1072 (margin*T)/3)) {
1073 berr = BW_WEIGHTS_BALANCE_MID_ERROR;
1074 goto out;
1075 }
1076 }
1077
1078 out:
1079 if (berr) {
1080 log_info(LD_DIR,
1081 "Bw weight mismatch %d. G=%"PRId64" M=%"PRId64
1082 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1083 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1084 " Wgd=%d Wgg=%d Wme=%d Wmg=%d",
1085 berr,
1086 (G), (M), (E),
1087 (D), (T),
1088 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1089 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg);
1090 }
1091
1092 return berr;
1093}
1094
1095/**
1096 * This function computes the bandwidth weights for consensus method 10.
1097 *
1098 * It returns true if weights could be computed, false otherwise.
1099 */
1100int
1102 int64_t M, int64_t E, int64_t D,
1103 int64_t T, int64_t weight_scale)
1104{
1105 bw_weights_error_t berr = 0;
1106 int64_t Wgg = -1, Wgd = -1;
1107 int64_t Wmg = -1, Wme = -1, Wmd = -1;
1108 int64_t Wed = -1, Wee = -1;
1109 const char *casename;
1110
1111 if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
1112 log_warn(LD_DIR, "Consensus with empty bandwidth: "
1113 "G=%"PRId64" M=%"PRId64" E=%"PRId64
1114 " D=%"PRId64" T=%"PRId64,
1115 (G), (M), (E),
1116 (D), (T));
1117 return 0;
1118 }
1119
1120 /*
1121 * Computed from cases in 3.8.3 of dir-spec.txt
1122 *
1123 * 1. Neither are scarce
1124 * 2. Both Guard and Exit are scarce
1125 * a. R+D <= S
1126 * b. R+D > S
1127 * 3. One of Guard or Exit is scarce
1128 * a. S+D < T/3
1129 * b. S+D >= T/3
1130 */
1131 if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
1132 /* Case 1: Neither are scarce. */
1133 casename = "Case 1 (Wgd=Wmd=Wed)";
1134 Wgd = weight_scale/3;
1135 Wed = weight_scale/3;
1136 Wmd = weight_scale/3;
1137 Wee = (weight_scale*(E+G+M))/(3*E);
1138 Wme = weight_scale - Wee;
1139 Wmg = (weight_scale*(2*G-E-M))/(3*G);
1140 Wgg = weight_scale - Wmg;
1141
1142 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
1143 weight_scale, G, M, E, D, T, 10, 1);
1144
1145 if (berr) {
1146 log_warn(LD_DIR,
1147 "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
1148 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1149 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1150 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
1151 berr, casename,
1152 (G), (M), (E),
1153 (D), (T),
1154 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1155 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
1156 return 0;
1157 }
1158 } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
1159 int64_t R = MIN(E, G);
1160 int64_t S = MAX(E, G);
1161 /*
1162 * Case 2: Both Guards and Exits are scarce
1163 * Balance D between E and G, depending upon
1164 * D capacity and scarcity.
1165 */
1166 if (R+D < S) { // Subcase a
1167 Wgg = weight_scale;
1168 Wee = weight_scale;
1169 Wmg = 0;
1170 Wme = 0;
1171 Wmd = 0;
1172 if (E < G) {
1173 casename = "Case 2a (E scarce)";
1174 Wed = weight_scale;
1175 Wgd = 0;
1176 } else { /* E >= G */
1177 casename = "Case 2a (G scarce)";
1178 Wed = 0;
1179 Wgd = weight_scale;
1180 }
1181 } else { // Subcase b: R+D >= S
1182 casename = "Case 2b1 (Wgg=weight_scale, Wmd=Wgd)";
1183 Wee = (weight_scale*(E - G + M))/E;
1184 Wed = (weight_scale*(D - 2*E + 4*G - 2*M))/(3*D);
1185 Wme = (weight_scale*(G-M))/E;
1186 Wmg = 0;
1187 Wgg = weight_scale;
1188 Wmd = (weight_scale - Wed)/2;
1189 Wgd = (weight_scale - Wed)/2;
1190
1191 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
1192 weight_scale, G, M, E, D, T, 10, 1);
1193
1194 if (berr) {
1195 casename = "Case 2b2 (Wgg=weight_scale, Wee=weight_scale)";
1196 Wgg = weight_scale;
1197 Wee = weight_scale;
1198 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
1199 Wmd = (weight_scale*(D - 2*M + G + E))/(3*D);
1200 Wme = 0;
1201 Wmg = 0;
1202
1203 if (Wmd < 0) { // Can happen if M > T/3
1204 casename = "Case 2b3 (Wmd=0)";
1205 Wmd = 0;
1206 log_warn(LD_DIR,
1207 "Too much Middle bandwidth on the network to calculate "
1208 "balanced bandwidth-weights. Consider increasing the "
1209 "number of Guard nodes by lowering the requirements.");
1210 }
1211 Wgd = weight_scale - Wed - Wmd;
1212 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1213 Wed, weight_scale, G, M, E, D, T, 10, 1);
1214 }
1215 if (berr != BW_WEIGHTS_NO_ERROR &&
1216 berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
1217 log_warn(LD_DIR,
1218 "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
1219 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1220 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1221 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
1222 berr, casename,
1223 (G), (M), (E),
1224 (D), (T),
1225 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1226 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
1227 return 0;
1228 }
1229 }
1230 } else { // if (E < T/3 || G < T/3) {
1231 int64_t S = MIN(E, G);
1232 // Case 3: Exactly one of Guard or Exit is scarce
1233 if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
1234 log_warn(LD_BUG,
1235 "Bw-Weights Case 3 v10 but with G=%"PRId64" M="
1236 "%"PRId64" E=%"PRId64" D=%"PRId64" T=%"PRId64,
1237 (G), (M), (E),
1238 (D), (T));
1239 }
1240
1241 if (3*(S+D) < T) { // Subcase a: S+D < T/3
1242 if (G < E) {
1243 casename = "Case 3a (G scarce)";
1244 Wgg = Wgd = weight_scale;
1245 Wmd = Wed = Wmg = 0;
1246 // Minor subcase, if E is more scarce than M,
1247 // keep its bandwidth in place.
1248 if (E < M) Wme = 0;
1249 else Wme = (weight_scale*(E-M))/(2*E);
1250 Wee = weight_scale-Wme;
1251 } else { // G >= E
1252 casename = "Case 3a (E scarce)";
1253 Wee = Wed = weight_scale;
1254 Wmd = Wgd = Wme = 0;
1255 // Minor subcase, if G is more scarce than M,
1256 // keep its bandwidth in place.
1257 if (G < M) Wmg = 0;
1258 else Wmg = (weight_scale*(G-M))/(2*G);
1259 Wgg = weight_scale-Wmg;
1260 }
1261 } else { // Subcase b: S+D >= T/3
1262 // D != 0 because S+D >= T/3
1263 if (G < E) {
1264 casename = "Case 3bg (G scarce, Wgg=weight_scale, Wmd == Wed)";
1265 Wgg = weight_scale;
1266 Wgd = (weight_scale*(D - 2*G + E + M))/(3*D);
1267 Wmg = 0;
1268 Wee = (weight_scale*(E+M))/(2*E);
1269 Wme = weight_scale - Wee;
1270 Wmd = (weight_scale - Wgd)/2;
1271 Wed = (weight_scale - Wgd)/2;
1272
1273 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1274 Wed, weight_scale, G, M, E, D, T, 10, 1);
1275 } else { // G >= E
1276 casename = "Case 3be (E scarce, Wee=weight_scale, Wmd == Wgd)";
1277 Wee = weight_scale;
1278 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
1279 Wme = 0;
1280 Wgg = (weight_scale*(G+M))/(2*G);
1281 Wmg = weight_scale - Wgg;
1282 Wmd = (weight_scale - Wed)/2;
1283 Wgd = (weight_scale - Wed)/2;
1284
1285 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1286 Wed, weight_scale, G, M, E, D, T, 10, 1);
1287 }
1288 if (berr) {
1289 log_warn(LD_DIR,
1290 "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
1291 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1292 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1293 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
1294 berr, casename,
1295 (G), (M), (E),
1296 (D), (T),
1297 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1298 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
1299 return 0;
1300 }
1301 }
1302 }
1303
1304 /* We cast down the weights to 32 bit ints on the assumption that
1305 * weight_scale is ~= 10000. We need to ensure a rogue authority
1306 * doesn't break this assumption to rig our weights */
1307 tor_assert(0 < weight_scale && weight_scale <= INT32_MAX);
1308
1309 /*
1310 * Provide Wgm=Wgg, Wmm=weight_scale, Wem=Wee, Weg=Wed. May later determine
1311 * that middle nodes need different bandwidth weights for dirport traffic,
1312 * or that weird exit policies need special weight, or that bridges
1313 * need special weight.
1314 *
1315 * NOTE: This list is sorted.
1316 */
1318 "bandwidth-weights Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
1319 "Wdb=%d "
1320 "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
1321 "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
1322 "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
1323 (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
1324 (int)weight_scale,
1325 (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
1326 (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
1327 (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
1328
1329 log_notice(LD_CIRC, "Computed bandwidth weights for %s with v10: "
1330 "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
1331 " T=%"PRId64,
1332 casename,
1333 (G), (M), (E),
1334 (D), (T));
1335 return 1;
1336}
1337
1338/** Update total bandwidth weights (G/M/E/D/T) with the bandwidth of
1339 * the router in <b>rs</b>. */
1340static void
1342 int is_exit, int is_guard,
1343 int64_t *G, int64_t *M, int64_t *E, int64_t *D,
1344 int64_t *T)
1345{
1346 int default_bandwidth = rs->bandwidth_kb;
1347 int guardfraction_bandwidth = 0;
1348
1349 if (!rs->has_bandwidth) {
1350 log_info(LD_BUG, "Missing consensus bandwidth for router %s",
1351 rs->nickname);
1352 return;
1353 }
1354
1355 /* If this routerstatus represents a guard that we have
1356 * guardfraction information on, use it to calculate its actual
1357 * bandwidth. From proposal236:
1358 *
1359 * Similarly, when calculating the bandwidth-weights line as in
1360 * section 3.8.3 of dir-spec.txt, directory authorities should treat N
1361 * as if fraction F of its bandwidth has the guard flag and (1-F) does
1362 * not. So when computing the totals G,M,E,D, each relay N with guard
1363 * visibility fraction F and bandwidth B should be added as follows:
1364 *
1365 * G' = G + F*B, if N does not have the exit flag
1366 * M' = M + (1-F)*B, if N does not have the exit flag
1367 *
1368 * or
1369 *
1370 * D' = D + F*B, if N has the exit flag
1371 * E' = E + (1-F)*B, if N has the exit flag
1372 *
1373 * In this block of code, we prepare the bandwidth values by setting
1374 * the default_bandwidth to F*B and guardfraction_bandwidth to (1-F)*B.
1375 */
1376 if (rs->has_guardfraction) {
1377 guardfraction_bandwidth_t guardfraction_bw;
1378
1379 tor_assert(is_guard);
1380
1381 guard_get_guardfraction_bandwidth(&guardfraction_bw,
1382 rs->bandwidth_kb,
1384
1385 default_bandwidth = guardfraction_bw.guard_bw;
1386 guardfraction_bandwidth = guardfraction_bw.non_guard_bw;
1387 }
1388
1389 /* Now calculate the total bandwidth weights with or without
1390 * guardfraction. Depending on the flags of the relay, add its
1391 * bandwidth to the appropriate weight pool. If it's a guard and
1392 * guardfraction is enabled, add its bandwidth to both pools as
1393 * indicated by the previous comment.
1394 */
1395 *T += default_bandwidth;
1396 if (is_exit && is_guard) {
1397
1398 *D += default_bandwidth;
1399 if (rs->has_guardfraction) {
1400 *E += guardfraction_bandwidth;
1401 }
1402
1403 } else if (is_exit) {
1404
1405 *E += default_bandwidth;
1406
1407 } else if (is_guard) {
1408
1409 *G += default_bandwidth;
1410 if (rs->has_guardfraction) {
1411 *M += guardfraction_bandwidth;
1412 }
1413
1414 } else {
1415
1416 *M += default_bandwidth;
1417 }
1418}
1419
1420/** Considering the different recommended/required protocols sets as a
1421 * 4-element array, return the element from <b>vote</b> for that protocol
1422 * set.
1423 */
1424static const char *
1426{
1427 switch (n) {
1428 case 0: return vote->recommended_client_protocols;
1429 case 1: return vote->recommended_relay_protocols;
1430 case 2: return vote->required_client_protocols;
1431 case 3: return vote->required_relay_protocols;
1432 default:
1433 tor_assert_unreached();
1434 return NULL;
1435 }
1436}
1437
1438/** Considering the different recommended/required protocols sets as a
1439 * 4-element array, return a newly allocated string for the consensus value
1440 * for the n'th set.
1441 */
1442static char *
1443compute_nth_protocol_set(int n, int n_voters, const smartlist_t *votes)
1444{
1445 const char *keyword;
1446 smartlist_t *proto_votes = smartlist_new();
1447 int threshold;
1448 switch (n) {
1449 case 0:
1450 keyword = "recommended-client-protocols";
1451 threshold = CEIL_DIV(n_voters, 2);
1452 break;
1453 case 1:
1454 keyword = "recommended-relay-protocols";
1455 threshold = CEIL_DIV(n_voters, 2);
1456 break;
1457 case 2:
1458 keyword = "required-client-protocols";
1459 threshold = CEIL_DIV(n_voters * 2, 3);
1460 break;
1461 case 3:
1462 keyword = "required-relay-protocols";
1463 threshold = CEIL_DIV(n_voters * 2, 3);
1464 break;
1465 default:
1466 tor_assert_unreached();
1467 return NULL;
1468 }
1469
1470 SMARTLIST_FOREACH_BEGIN(votes, const networkstatus_t *, ns) {
1471 const char *v = get_nth_protocol_set_vote(n, ns);
1472 if (v)
1473 smartlist_add(proto_votes, (void*)v);
1474 } SMARTLIST_FOREACH_END(ns);
1475
1476 char *protocols = protover_compute_vote(proto_votes, threshold);
1477 smartlist_free(proto_votes);
1478
1479 char *result = NULL;
1480 tor_asprintf(&result, "%s %s\n", keyword, protocols);
1481 tor_free(protocols);
1482
1483 return result;
1484}
1485
1486/** Helper: Takes a smartlist of `const char *` flags, and a flag to remove.
1487 *
1488 * Removes that flag if it is present in the list. Doesn't free it.
1489 */
1490static void
1491remove_flag(smartlist_t *sl, const char *flag)
1492{
1493 /* We can't use smartlist_string_remove() here, since that doesn't preserve
1494 * order, and since it frees elements from the string. */
1495
1496 int idx = smartlist_string_pos(sl, flag);
1497 if (idx >= 0)
1498 smartlist_del_keeporder(sl, idx);
1499}
1500
1501/** Given a list of vote networkstatus_t in <b>votes</b>, our public
1502 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
1503 * and the number of <b>total_authorities</b> that we believe exist in our
1504 * voting quorum, generate the text of a new v3 consensus or microdescriptor
1505 * consensus (depending on <b>flavor</b>), and return the value in a newly
1506 * allocated string.
1507 *
1508 * Note: this function DOES NOT check whether the votes are from
1509 * recognized authorities. (dirvote_add_vote does that.)
1510 *
1511 * <strong>WATCH OUT</strong>: You need to think before you change the
1512 * behavior of this function, or of the functions it calls! If some
1513 * authorities compute the consensus with a different algorithm than
1514 * others, they will not reach the same result, and they will not all
1515 * sign the same thing! If you really need to change the algorithm
1516 * here, you should allocate a new "consensus_method" for the new
1517 * behavior, and make the new behavior conditional on a new-enough
1518 * consensus_method.
1519 **/
1520STATIC char *
1522 int total_authorities,
1523 crypto_pk_t *identity_key,
1524 crypto_pk_t *signing_key,
1525 const char *legacy_id_key_digest,
1527 consensus_flavor_t flavor)
1528{
1529 smartlist_t *chunks;
1530 char *result = NULL;
1531 int consensus_method;
1532 time_t valid_after, fresh_until, valid_until;
1533 int vote_seconds, dist_seconds;
1534 char *client_versions = NULL, *server_versions = NULL;
1535 smartlist_t *flags;
1536 const char *flavor_name;
1537 uint32_t max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1538 int64_t G, M, E, D, T; /* For bandwidth weights */
1539 const routerstatus_format_type_t rs_format =
1540 flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
1541 char *params = NULL;
1542 char *packages = NULL;
1543 int added_weights = 0;
1544 dircollator_t *collator = NULL;
1545 smartlist_t *param_list = NULL;
1546
1547 tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
1548 tor_assert(total_authorities >= smartlist_len(votes));
1549 tor_assert(total_authorities > 0);
1550
1551 flavor_name = networkstatus_get_flavor_name(flavor);
1552
1553 if (!smartlist_len(votes)) {
1554 log_warn(LD_DIR, "Can't compute a consensus from no votes.");
1555 return NULL;
1556 }
1557 flags = smartlist_new();
1558
1559 consensus_method = compute_consensus_method(votes);
1560 if (consensus_method_is_supported(consensus_method)) {
1561 log_info(LD_DIR, "Generating consensus using method %d.",
1562 consensus_method);
1563 } else {
1564 log_warn(LD_DIR, "The other authorities will use consensus method %d, "
1565 "which I don't support. Maybe I should upgrade!",
1566 consensus_method);
1567 consensus_method = MAX_SUPPORTED_CONSENSUS_METHOD;
1568 }
1569
1570 {
1571 /* It's smarter to initialize these weights to 1, so that later on,
1572 * we can't accidentally divide by zero. */
1573 G = M = E = D = 1;
1574 T = 4;
1575 }
1576
1577 /* Compute medians of time-related things, and figure out how many
1578 * routers we might need to talk about. */
1579 {
1580 int n_votes = smartlist_len(votes);
1581 time_t *va_times = tor_calloc(n_votes, sizeof(time_t));
1582 time_t *fu_times = tor_calloc(n_votes, sizeof(time_t));
1583 time_t *vu_times = tor_calloc(n_votes, sizeof(time_t));
1584 int *votesec_list = tor_calloc(n_votes, sizeof(int));
1585 int *distsec_list = tor_calloc(n_votes, sizeof(int));
1586 int n_versioning_clients = 0, n_versioning_servers = 0;
1587 smartlist_t *combined_client_versions = smartlist_new();
1588 smartlist_t *combined_server_versions = smartlist_new();
1589
1591 tor_assert(v->type == NS_TYPE_VOTE);
1592 va_times[v_sl_idx] = v->valid_after;
1593 fu_times[v_sl_idx] = v->fresh_until;
1594 vu_times[v_sl_idx] = v->valid_until;
1595 votesec_list[v_sl_idx] = v->vote_seconds;
1596 distsec_list[v_sl_idx] = v->dist_seconds;
1597 if (v->client_versions) {
1598 smartlist_t *cv = smartlist_new();
1599 ++n_versioning_clients;
1600 smartlist_split_string(cv, v->client_versions, ",",
1601 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1602 sort_version_list(cv, 1);
1603 smartlist_add_all(combined_client_versions, cv);
1604 smartlist_free(cv); /* elements get freed later. */
1605 }
1606 if (v->server_versions) {
1607 smartlist_t *sv = smartlist_new();
1608 ++n_versioning_servers;
1609 smartlist_split_string(sv, v->server_versions, ",",
1610 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1611 sort_version_list(sv, 1);
1612 smartlist_add_all(combined_server_versions, sv);
1613 smartlist_free(sv); /* elements get freed later. */
1614 }
1615 SMARTLIST_FOREACH(v->known_flags, const char *, cp,
1616 smartlist_add_strdup(flags, cp));
1617 } SMARTLIST_FOREACH_END(v);
1618 valid_after = median_time(va_times, n_votes);
1619 fresh_until = median_time(fu_times, n_votes);
1620 valid_until = median_time(vu_times, n_votes);
1621 vote_seconds = median_int(votesec_list, n_votes);
1622 dist_seconds = median_int(distsec_list, n_votes);
1623
1624 tor_assert(valid_after +
1625 (get_options()->TestingTorNetwork ?
1627 tor_assert(fresh_until +
1628 (get_options()->TestingTorNetwork ?
1630 tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
1631 tor_assert(dist_seconds >= MIN_DIST_SECONDS);
1632
1633 server_versions = compute_consensus_versions_list(combined_server_versions,
1634 n_versioning_servers);
1635 client_versions = compute_consensus_versions_list(combined_client_versions,
1636 n_versioning_clients);
1637
1638 if (consensus_method < MIN_METHOD_TO_OMIT_PACKAGE_FINGERPRINTS)
1639 packages = tor_strdup("");
1640 else
1641 packages = compute_consensus_package_lines(votes);
1642
1643 SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
1644 SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
1645 smartlist_free(combined_server_versions);
1646 smartlist_free(combined_client_versions);
1647
1648 smartlist_add_strdup(flags, "NoEdConsensus");
1649
1652
1653 tor_free(va_times);
1654 tor_free(fu_times);
1655 tor_free(vu_times);
1656 tor_free(votesec_list);
1657 tor_free(distsec_list);
1658 }
1659 // True if anybody is voting on the BadExit flag.
1660 const bool badexit_flag_is_listed =
1661 smartlist_contains_string(flags, "BadExit");
1662
1663 chunks = smartlist_new();
1664
1665 {
1666 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
1667 vu_buf[ISO_TIME_LEN+1];
1668 char *flaglist;
1669 format_iso_time(va_buf, valid_after);
1670 format_iso_time(fu_buf, fresh_until);
1671 format_iso_time(vu_buf, valid_until);
1672 flaglist = smartlist_join_strings(flags, " ", 0, NULL);
1673
1674 smartlist_add_asprintf(chunks, "network-status-version 3%s%s\n"
1675 "vote-status consensus\n",
1676 flavor == FLAV_NS ? "" : " ",
1677 flavor == FLAV_NS ? "" : flavor_name);
1678
1679 smartlist_add_asprintf(chunks, "consensus-method %d\n",
1680 consensus_method);
1681
1683 "valid-after %s\n"
1684 "fresh-until %s\n"
1685 "valid-until %s\n"
1686 "voting-delay %d %d\n"
1687 "client-versions %s\n"
1688 "server-versions %s\n"
1689 "%s" /* packages */
1690 "known-flags %s\n",
1691 va_buf, fu_buf, vu_buf,
1692 vote_seconds, dist_seconds,
1693 client_versions, server_versions,
1694 packages,
1695 flaglist);
1696
1697 tor_free(flaglist);
1698 }
1699
1700 {
1701 int num_dirauth = get_n_authorities(V3_DIRINFO);
1702 int idx;
1703 for (idx = 0; idx < 4; ++idx) {
1704 char *proto_line = compute_nth_protocol_set(idx, num_dirauth, votes);
1705 if (BUG(!proto_line))
1706 continue;
1707 smartlist_add(chunks, proto_line);
1708 }
1709 }
1710
1711 param_list = dirvote_compute_params(votes, consensus_method,
1712 total_authorities);
1713 if (smartlist_len(param_list)) {
1714 params = smartlist_join_strings(param_list, " ", 0, NULL);
1715 smartlist_add_strdup(chunks, "params ");
1716 smartlist_add(chunks, params);
1717 smartlist_add_strdup(chunks, "\n");
1718 }
1719
1720 {
1721 int num_dirauth = get_n_authorities(V3_DIRINFO);
1722 /* Default value of this is 2/3 of the total number of authorities. For
1723 * instance, if we have 9 dirauth, the default value is 6. The following
1724 * calculation will round it down. */
1725 int32_t num_srv_agreements =
1727 "AuthDirNumSRVAgreements",
1728 (num_dirauth * 2) / 3);
1729 /* Add the shared random value. */
1730 char *srv_lines = sr_get_string_for_consensus(votes, num_srv_agreements);
1731 if (srv_lines != NULL) {
1732 smartlist_add(chunks, srv_lines);
1733 }
1734 }
1735
1736 /* Sort the votes. */
1738 /* Add the authority sections. */
1739 {
1740 smartlist_t *dir_sources = smartlist_new();
1742 dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
1743 e->v = v;
1744 e->digest = get_voter(v)->identity_digest;
1745 e->is_legacy = 0;
1746 smartlist_add(dir_sources, e);
1747 if (!tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
1748 dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
1749 e_legacy->v = v;
1750 e_legacy->digest = get_voter(v)->legacy_id_digest;
1751 e_legacy->is_legacy = 1;
1752 smartlist_add(dir_sources, e_legacy);
1753 }
1754 } SMARTLIST_FOREACH_END(v);
1756
1757 SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
1758 char fingerprint[HEX_DIGEST_LEN+1];
1759 char votedigest[HEX_DIGEST_LEN+1];
1760 networkstatus_t *v = e->v;
1762
1763 base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
1764 base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
1765 DIGEST_LEN);
1766
1768 "dir-source %s%s %s %s %s %d %d\n",
1769 voter->nickname, e->is_legacy ? "-legacy" : "",
1770 fingerprint, voter->address, fmt_addr(&voter->ipv4_addr),
1771 voter->ipv4_dirport,
1772 voter->ipv4_orport);
1773 if (! e->is_legacy) {
1775 "contact %s\n"
1776 "vote-digest %s\n",
1777 voter->contact,
1778 votedigest);
1779 }
1780 } SMARTLIST_FOREACH_END(e);
1781 SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
1782 smartlist_free(dir_sources);
1783 }
1784
1785 {
1786 max_unmeasured_bw_kb = dirvote_get_intermediate_param_value(
1787 param_list, "maxunmeasuredbw", DEFAULT_MAX_UNMEASURED_BW_KB);
1788 if (max_unmeasured_bw_kb < 1)
1789 max_unmeasured_bw_kb = 1;
1790 }
1791
1792 /* Add the actual router entries. */
1793 {
1794 int *size; /* size[j] is the number of routerstatuses in votes[j]. */
1795 int *flag_counts; /* The number of voters that list flag[j] for the
1796 * currently considered router. */
1797 int i;
1798 smartlist_t *matching_descs = smartlist_new();
1799 smartlist_t *chosen_flags = smartlist_new();
1800 smartlist_t *versions = smartlist_new();
1801 smartlist_t *protocols = smartlist_new();
1802 smartlist_t *exitsummaries = smartlist_new();
1803 uint32_t *bandwidths_kb = tor_calloc(smartlist_len(votes),
1804 sizeof(uint32_t));
1805 uint32_t *measured_bws_kb = tor_calloc(smartlist_len(votes),
1806 sizeof(uint32_t));
1807 uint32_t *measured_guardfraction = tor_calloc(smartlist_len(votes),
1808 sizeof(uint32_t));
1809 int num_bandwidths;
1810 int num_mbws;
1811 int num_guardfraction_inputs;
1812
1813 int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
1814 * votes[j] knows about. */
1815 int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
1816 * about flags[f]. */
1817 int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
1818 * is the same flag as votes[j]->known_flags[b]. */
1819 int *named_flag; /* Index of the flag "Named" for votes[j] */
1820 int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
1821 int n_authorities_measuring_bandwidth;
1822
1823 strmap_t *name_to_id_map = strmap_new();
1824 char conflict[DIGEST_LEN];
1825 char unknown[DIGEST_LEN];
1826 memset(conflict, 0, sizeof(conflict));
1827 memset(unknown, 0xff, sizeof(conflict));
1828
1829 size = tor_calloc(smartlist_len(votes), sizeof(int));
1830 n_voter_flags = tor_calloc(smartlist_len(votes), sizeof(int));
1831 n_flag_voters = tor_calloc(smartlist_len(flags), sizeof(int));
1832 flag_map = tor_calloc(smartlist_len(votes), sizeof(int *));
1833 named_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1834 unnamed_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1835 for (i = 0; i < smartlist_len(votes); ++i)
1836 unnamed_flag[i] = named_flag[i] = -1;
1837
1838 /* Build the flag indexes. Note that no vote can have more than 64 members
1839 * for known_flags, so no value will be greater than 63, so it's safe to
1840 * do UINT64_C(1) << index on these values. But note also that
1841 * named_flag and unnamed_flag are initialized to -1, so we need to check
1842 * that they're actually set before doing UINT64_C(1) << index with
1843 * them.*/
1845 flag_map[v_sl_idx] = tor_calloc(smartlist_len(v->known_flags),
1846 sizeof(int));
1847 if (smartlist_len(v->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
1848 log_warn(LD_BUG, "Somehow, a vote has %d entries in known_flags",
1849 smartlist_len(v->known_flags));
1850 }
1851 SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
1852 int p = smartlist_string_pos(flags, fl);
1853 tor_assert(p >= 0);
1854 flag_map[v_sl_idx][fl_sl_idx] = p;
1855 ++n_flag_voters[p];
1856 if (!strcmp(fl, "Named"))
1857 named_flag[v_sl_idx] = fl_sl_idx;
1858 if (!strcmp(fl, "Unnamed"))
1859 unnamed_flag[v_sl_idx] = fl_sl_idx;
1860 } SMARTLIST_FOREACH_END(fl);
1861 n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
1862 size[v_sl_idx] = smartlist_len(v->routerstatus_list);
1863 } SMARTLIST_FOREACH_END(v);
1864
1865 /* Named and Unnamed get treated specially */
1866 {
1868 uint64_t nf;
1869 if (named_flag[v_sl_idx]<0)
1870 continue;
1871 nf = UINT64_C(1) << named_flag[v_sl_idx];
1872 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1873 vote_routerstatus_t *, rs) {
1874
1875 if ((rs->flags & nf) != 0) {
1876 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1877 if (!d) {
1878 /* We have no name officially mapped to this digest. */
1879 strmap_set_lc(name_to_id_map, rs->status.nickname,
1880 rs->status.identity_digest);
1881 } else if (d != conflict &&
1882 fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
1883 /* Authorities disagree about this nickname. */
1884 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1885 } else {
1886 /* It's already a conflict, or it's already this ID. */
1887 }
1888 }
1889 } SMARTLIST_FOREACH_END(rs);
1890 } SMARTLIST_FOREACH_END(v);
1891
1893 uint64_t uf;
1894 if (unnamed_flag[v_sl_idx]<0)
1895 continue;
1896 uf = UINT64_C(1) << unnamed_flag[v_sl_idx];
1897 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1898 vote_routerstatus_t *, rs) {
1899 if ((rs->flags & uf) != 0) {
1900 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1901 if (d == conflict || d == unknown) {
1902 /* Leave it alone; we know what it is. */
1903 } else if (!d) {
1904 /* We have no name officially mapped to this digest. */
1905 strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
1906 } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
1907 /* Authorities disagree about this nickname. */
1908 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1909 } else {
1910 /* It's mapped to a different name. */
1911 }
1912 }
1913 } SMARTLIST_FOREACH_END(rs);
1914 } SMARTLIST_FOREACH_END(v);
1915 }
1916
1917 /* We need to know how many votes measure bandwidth. */
1918 n_authorities_measuring_bandwidth = 0;
1919 SMARTLIST_FOREACH(votes, const networkstatus_t *, v,
1920 if (v->has_measured_bws) {
1921 ++n_authorities_measuring_bandwidth;
1922 }
1923 );
1924
1925 /* Populate the collator */
1926 collator = dircollator_new(smartlist_len(votes), total_authorities);
1928 dircollator_add_vote(collator, v);
1929 } SMARTLIST_FOREACH_END(v);
1930
1931 dircollator_collate(collator, consensus_method);
1932
1933 /* Now go through all the votes */
1934 flag_counts = tor_calloc(smartlist_len(flags), sizeof(int));
1935 const int num_routers = dircollator_n_routers(collator);
1936 for (i = 0; i < num_routers; ++i) {
1937 vote_routerstatus_t **vrs_lst =
1939
1941 routerstatus_t rs_out;
1942 const char *current_rsa_id = NULL;
1943 const char *chosen_version;
1944 const char *chosen_protocol_list;
1945 const char *chosen_name = NULL;
1946 int exitsummary_disagreement = 0;
1947 int is_named = 0, is_unnamed = 0, is_running = 0, is_valid = 0;
1948 int is_guard = 0, is_exit = 0, is_bad_exit = 0, is_middle_only = 0;
1949 int naming_conflict = 0;
1950 int n_listing = 0;
1951 char microdesc_digest[DIGEST256_LEN];
1952 tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
1953
1954 memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
1955 smartlist_clear(matching_descs);
1956 smartlist_clear(chosen_flags);
1957 smartlist_clear(versions);
1958 smartlist_clear(protocols);
1959 num_bandwidths = 0;
1960 num_mbws = 0;
1961 num_guardfraction_inputs = 0;
1962 int ed_consensus = 0;
1963 const uint8_t *ed_consensus_val = NULL;
1964
1965 /* Okay, go through all the entries for this digest. */
1966 for (int voter_idx = 0; voter_idx < smartlist_len(votes); ++voter_idx) {
1967 if (vrs_lst[voter_idx] == NULL)
1968 continue; /* This voter had nothing to say about this entry. */
1969 rs = vrs_lst[voter_idx];
1970 ++n_listing;
1971
1972 current_rsa_id = rs->status.identity_digest;
1973
1974 smartlist_add(matching_descs, rs);
1975 if (rs->version && rs->version[0])
1976 smartlist_add(versions, rs->version);
1977
1978 if (rs->protocols) {
1979 /* We include this one even if it's empty: voting for an
1980 * empty protocol list actually is meaningful. */
1981 smartlist_add(protocols, rs->protocols);
1982 }
1983
1984 /* Tally up all the flags. */
1985 for (int flag = 0; flag < n_voter_flags[voter_idx]; ++flag) {
1986 if (rs->flags & (UINT64_C(1) << flag))
1987 ++flag_counts[flag_map[voter_idx][flag]];
1988 }
1989 if (named_flag[voter_idx] >= 0 &&
1990 (rs->flags & (UINT64_C(1) << named_flag[voter_idx]))) {
1991 if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
1992 log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
1993 chosen_name, rs->status.nickname);
1994 naming_conflict = 1;
1995 }
1996 chosen_name = rs->status.nickname;
1997 }
1998
1999 /* Count guardfraction votes and note down the values. */
2000 if (rs->status.has_guardfraction) {
2001 measured_guardfraction[num_guardfraction_inputs++] =
2003 }
2004
2005 /* count bandwidths */
2006 if (rs->has_measured_bw)
2007 measured_bws_kb[num_mbws++] = rs->measured_bw_kb;
2008
2009 if (rs->status.has_bandwidth)
2010 bandwidths_kb[num_bandwidths++] = rs->status.bandwidth_kb;
2011
2012 /* Count number for which ed25519 is canonical. */
2014 ++ed_consensus;
2015 if (ed_consensus_val) {
2016 tor_assert(fast_memeq(ed_consensus_val, rs->ed25519_id,
2018 } else {
2019 ed_consensus_val = rs->ed25519_id;
2020 }
2021 }
2022 }
2023
2024 /* We don't include this router at all unless more than half of
2025 * the authorities we believe in list it. */
2026 if (n_listing <= total_authorities/2)
2027 continue;
2028
2029 if (ed_consensus > 0) {
2030 if (ed_consensus <= total_authorities / 2) {
2031 log_warn(LD_BUG, "Not enough entries had ed_consensus set; how "
2032 "can we have a consensus of %d?", ed_consensus);
2033 }
2034 }
2035
2036 /* The clangalyzer can't figure out that this will never be NULL
2037 * if n_listing is at least 1 */
2038 tor_assert(current_rsa_id);
2039
2040 /* Figure out the most popular opinion of what the most recent
2041 * routerinfo and its contents are. */
2042 memset(microdesc_digest, 0, sizeof(microdesc_digest));
2043 rs = compute_routerstatus_consensus(matching_descs, consensus_method,
2044 microdesc_digest, &alt_orport);
2045 /* Copy bits of that into rs_out. */
2046 memset(&rs_out, 0, sizeof(rs_out));
2047 tor_assert(fast_memeq(current_rsa_id,
2049 memcpy(rs_out.identity_digest, current_rsa_id, DIGEST_LEN);
2050 memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
2051 DIGEST_LEN);
2052 tor_addr_copy(&rs_out.ipv4_addr, &rs->status.ipv4_addr);
2053 rs_out.ipv4_dirport = rs->status.ipv4_dirport;
2054 rs_out.ipv4_orport = rs->status.ipv4_orport;
2055 tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
2056 rs_out.ipv6_orport = alt_orport.port;
2057 rs_out.has_bandwidth = 0;
2058 rs_out.has_exitsummary = 0;
2059
2060 time_t published_on = rs->published_on;
2061
2062 /* Starting with this consensus method, we no longer include a
2063 meaningful published_on time for microdescriptor consensuses. This
2064 makes their diffs smaller and more compressible.
2065
2066 We need to keep including a meaningful published_on time for NS
2067 consensuses, however, until 035 relays are all obsolete. (They use
2068 it for a purpose similar to the current StaleDesc flag.)
2069 */
2070 if (consensus_method >= MIN_METHOD_TO_SUPPRESS_MD_PUBLISHED &&
2071 flavor == FLAV_MICRODESC) {
2072 published_on = -1;
2073 }
2074
2075 if (chosen_name && !naming_conflict) {
2076 strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
2077 } else {
2078 strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
2079 }
2080
2081 {
2082 const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
2083 if (!d) {
2084 is_named = is_unnamed = 0;
2085 } else if (fast_memeq(d, current_rsa_id, DIGEST_LEN)) {
2086 is_named = 1; is_unnamed = 0;
2087 } else {
2088 is_named = 0; is_unnamed = 1;
2089 }
2090 }
2091
2092 /* Set the flags. */
2093 SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
2094 if (!strcmp(fl, "Named")) {
2095 if (is_named)
2096 smartlist_add(chosen_flags, (char*)fl);
2097 } else if (!strcmp(fl, "Unnamed")) {
2098 if (is_unnamed)
2099 smartlist_add(chosen_flags, (char*)fl);
2100 } else if (!strcmp(fl, "NoEdConsensus")) {
2101 if (ed_consensus <= total_authorities/2)
2102 smartlist_add(chosen_flags, (char*)fl);
2103 } else {
2104 if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
2105 smartlist_add(chosen_flags, (char*)fl);
2106 if (!strcmp(fl, "Exit"))
2107 is_exit = 1;
2108 else if (!strcmp(fl, "Guard"))
2109 is_guard = 1;
2110 else if (!strcmp(fl, "Running"))
2111 is_running = 1;
2112 else if (!strcmp(fl, "BadExit"))
2113 is_bad_exit = 1;
2114 else if (!strcmp(fl, "MiddleOnly"))
2115 is_middle_only = 1;
2116 else if (!strcmp(fl, "Valid"))
2117 is_valid = 1;
2118 }
2119 }
2120 } SMARTLIST_FOREACH_END(fl);
2121
2122 /* Starting with consensus method 4 we do not list servers
2123 * that are not running in a consensus. See Proposal 138 */
2124 if (!is_running)
2125 continue;
2126
2127 /* Starting with consensus method 24, we don't list servers
2128 * that are not valid in a consensus. See Proposal 272 */
2129 if (!is_valid)
2130 continue;
2131
2132 /* Starting with consensus method 32, we handle the middle-only
2133 * flag specially: when it is present, we clear some flags, and
2134 * set others. */
2135 if (is_middle_only) {
2136 remove_flag(chosen_flags, "Exit");
2137 remove_flag(chosen_flags, "V2Dir");
2138 remove_flag(chosen_flags, "Guard");
2139 remove_flag(chosen_flags, "HSDir");
2140 is_exit = is_guard = 0;
2141 if (! is_bad_exit && badexit_flag_is_listed) {
2142 is_bad_exit = 1;
2143 smartlist_add(chosen_flags, (char *)"BadExit");
2144 smartlist_sort_strings(chosen_flags); // restore order.
2145 }
2146 }
2147
2148 /* Pick the version. */
2149 if (smartlist_len(versions)) {
2150 sort_version_list(versions, 0);
2151 chosen_version = get_most_frequent_member(versions);
2152 } else {
2153 chosen_version = NULL;
2154 }
2155
2156 /* Pick the protocol list */
2157 if (smartlist_len(protocols)) {
2158 smartlist_sort_strings(protocols);
2159 chosen_protocol_list = get_most_frequent_member(protocols);
2160 } else {
2161 chosen_protocol_list = NULL;
2162 }
2163
2164 /* If it's a guard and we have enough guardfraction votes,
2165 calculate its consensus guardfraction value. */
2166 if (is_guard && num_guardfraction_inputs > 2) {
2167 rs_out.has_guardfraction = 1;
2168 rs_out.guardfraction_percentage = median_uint32(measured_guardfraction,
2169 num_guardfraction_inputs);
2170 /* final value should be an integer percentage! */
2171 tor_assert(rs_out.guardfraction_percentage <= 100);
2172 }
2173
2174 /* Pick a bandwidth */
2175 if (num_mbws > 2) {
2176 rs_out.has_bandwidth = 1;
2177 rs_out.bw_is_unmeasured = 0;
2178 rs_out.bandwidth_kb = median_uint32(measured_bws_kb, num_mbws);
2179 } else if (num_bandwidths > 0) {
2180 rs_out.has_bandwidth = 1;
2181 rs_out.bw_is_unmeasured = 1;
2182 rs_out.bandwidth_kb = median_uint32(bandwidths_kb, num_bandwidths);
2183 if (n_authorities_measuring_bandwidth > 2) {
2184 /* Cap non-measured bandwidths. */
2185 if (rs_out.bandwidth_kb > max_unmeasured_bw_kb) {
2186 rs_out.bandwidth_kb = max_unmeasured_bw_kb;
2187 }
2188 }
2189 }
2190
2191 /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
2192 is_exit = is_exit && !is_bad_exit;
2193
2194 /* Update total bandwidth weights with the bandwidths of this router. */
2195 {
2197 is_exit, is_guard,
2198 &G, &M, &E, &D, &T);
2199 }
2200
2201 /* Ok, we already picked a descriptor digest we want to list
2202 * previously. Now we want to use the exit policy summary from
2203 * that descriptor. If everybody plays nice all the voters who
2204 * listed that descriptor will have the same summary. If not then
2205 * something is fishy and we'll use the most common one (breaking
2206 * ties in favor of lexicographically larger one (only because it
2207 * lets me reuse more existing code)).
2208 *
2209 * The other case that can happen is that no authority that voted
2210 * for that descriptor has an exit policy summary. That's
2211 * probably quite unlikely but can happen. In that case we use
2212 * the policy that was most often listed in votes, again breaking
2213 * ties like in the previous case.
2214 */
2215 {
2216 /* Okay, go through all the votes for this router. We prepared
2217 * that list previously */
2218 const char *chosen_exitsummary = NULL;
2219 smartlist_clear(exitsummaries);
2220 SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
2221 /* Check if the vote where this status comes from had the
2222 * proper descriptor */
2224 vsr->status.identity_digest,
2225 DIGEST_LEN));
2226 if (vsr->status.has_exitsummary &&
2228 vsr->status.descriptor_digest,
2229 DIGEST_LEN)) {
2230 tor_assert(vsr->status.exitsummary);
2231 smartlist_add(exitsummaries, vsr->status.exitsummary);
2232 if (!chosen_exitsummary) {
2233 chosen_exitsummary = vsr->status.exitsummary;
2234 } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
2235 /* Great. There's disagreement among the voters. That
2236 * really shouldn't be */
2237 exitsummary_disagreement = 1;
2238 }
2239 }
2240 } SMARTLIST_FOREACH_END(vsr);
2241
2242 if (exitsummary_disagreement) {
2243 char id[HEX_DIGEST_LEN+1];
2244 char dd[HEX_DIGEST_LEN+1];
2245 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
2246 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
2247 log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
2248 " for router %s with descriptor %s. This really shouldn't"
2249 " have happened.", id, dd);
2250
2251 smartlist_sort_strings(exitsummaries);
2252 chosen_exitsummary = get_most_frequent_member(exitsummaries);
2253 } else if (!chosen_exitsummary) {
2254 char id[HEX_DIGEST_LEN+1];
2255 char dd[HEX_DIGEST_LEN+1];
2256 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
2257 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
2258 log_warn(LD_DIR, "Not one of the voters that made us select"
2259 "descriptor %s for router %s had an exit policy"
2260 "summary", dd, id);
2261
2262 /* Ok, none of those voting for the digest we chose had an
2263 * exit policy for us. Well, that kinda sucks.
2264 */
2265 smartlist_clear(exitsummaries);
2266 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
2267 if (vsr->status.has_exitsummary)
2268 smartlist_add(exitsummaries, vsr->status.exitsummary);
2269 });
2270 smartlist_sort_strings(exitsummaries);
2271 chosen_exitsummary = get_most_frequent_member(exitsummaries);
2272
2273 if (!chosen_exitsummary)
2274 log_warn(LD_DIR, "Wow, not one of the voters had an exit "
2275 "policy summary for %s. Wow.", id);
2276 }
2277
2278 if (chosen_exitsummary) {
2279 rs_out.has_exitsummary = 1;
2280 /* yea, discards the const */
2281 rs_out.exitsummary = (char *)chosen_exitsummary;
2282 }
2283 }
2284
2285 if (flavor == FLAV_MICRODESC &&
2286 tor_digest256_is_zero(microdesc_digest)) {
2287 /* With no microdescriptor digest, we omit the entry entirely. */
2288 continue;
2289 }
2290
2291 {
2292 char *buf;
2293 /* Okay!! Now we can write the descriptor... */
2294 /* First line goes into "buf". */
2295 buf = routerstatus_format_entry(&rs_out, NULL, NULL,
2296 rs_format, NULL, published_on);
2297 if (buf)
2298 smartlist_add(chunks, buf);
2299 }
2300 /* Now an m line, if applicable. */
2301 if (flavor == FLAV_MICRODESC &&
2302 !tor_digest256_is_zero(microdesc_digest)) {
2303 char m[BASE64_DIGEST256_LEN+1];
2304 digest256_to_base64(m, microdesc_digest);
2305 smartlist_add_asprintf(chunks, "m %s\n", m);
2306 }
2307 /* Next line is all flags. The "\n" is missing. */
2308 smartlist_add_asprintf(chunks, "s%s",
2309 smartlist_len(chosen_flags)?" ":"");
2310 smartlist_add(chunks,
2311 smartlist_join_strings(chosen_flags, " ", 0, NULL));
2312 /* Now the version line. */
2313 if (chosen_version) {
2314 smartlist_add_strdup(chunks, "\nv ");
2315 smartlist_add_strdup(chunks, chosen_version);
2316 }
2317 smartlist_add_strdup(chunks, "\n");
2318 if (chosen_protocol_list) {
2319 smartlist_add_asprintf(chunks, "pr %s\n", chosen_protocol_list);
2320 }
2321 /* Now the weight line. */
2322 if (rs_out.has_bandwidth) {
2323 char *guardfraction_str = NULL;
2324 int unmeasured = rs_out.bw_is_unmeasured;
2325
2326 /* If we have guardfraction info, include it in the 'w' line. */
2327 if (rs_out.has_guardfraction) {
2328 tor_asprintf(&guardfraction_str,
2329 " GuardFraction=%u", rs_out.guardfraction_percentage);
2330 }
2331 smartlist_add_asprintf(chunks, "w Bandwidth=%d%s%s\n",
2332 rs_out.bandwidth_kb,
2333 unmeasured?" Unmeasured=1":"",
2334 guardfraction_str ? guardfraction_str : "");
2335
2336 tor_free(guardfraction_str);
2337 }
2338
2339 /* Now the exitpolicy summary line. */
2340 if (rs_out.has_exitsummary && flavor == FLAV_NS) {
2341 smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
2342 }
2343
2344 /* And the loop is over and we move on to the next router */
2345 }
2346
2347 tor_free(size);
2348 tor_free(n_voter_flags);
2349 tor_free(n_flag_voters);
2350 for (i = 0; i < smartlist_len(votes); ++i)
2351 tor_free(flag_map[i]);
2352 tor_free(flag_map);
2353 tor_free(flag_counts);
2354 tor_free(named_flag);
2355 tor_free(unnamed_flag);
2356 strmap_free(name_to_id_map, NULL);
2357 smartlist_free(matching_descs);
2358 smartlist_free(chosen_flags);
2359 smartlist_free(versions);
2360 smartlist_free(protocols);
2361 smartlist_free(exitsummaries);
2362 tor_free(bandwidths_kb);
2363 tor_free(measured_bws_kb);
2364 tor_free(measured_guardfraction);
2365 }
2366
2367 /* Mark the directory footer region */
2368 smartlist_add_strdup(chunks, "directory-footer\n");
2369
2370 {
2371 int64_t weight_scale;
2373 param_list, "bwweightscale", BW_WEIGHT_SCALE);
2374 if (weight_scale < 1)
2375 weight_scale = 1;
2376 added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
2377 T, weight_scale);
2378 }
2379
2380 /* Write the unsigned proposed consensus text to disk, for dir auth
2381 * debugging purposes, and also to put a sig-less consensus file in
2382 * place for (with luck) later export to the consensus transparency
2383 * module. */
2384 {
2385 char *unsigned_consensus = smartlist_join_strings(chunks, "", 0, NULL);
2386 char *filename = NULL;
2387 tor_asprintf(&filename, "my-consensus-%s", flavor_name);
2388 char *fpath = get_datadir_fname(filename);
2389 write_str_to_file(fpath, unsigned_consensus, 0);
2390 tor_free(filename);
2391 tor_free(fpath);
2392 tor_free(unsigned_consensus);
2393 }
2394
2395 /* Add a signature. */
2396 {
2397 char digest[DIGEST256_LEN];
2398 char fingerprint[HEX_DIGEST_LEN+1];
2399 char signing_key_fingerprint[HEX_DIGEST_LEN+1];
2400 digest_algorithm_t digest_alg =
2401 flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
2402 size_t digest_len =
2403 flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
2404 const char *algname = crypto_digest_algorithm_get_name(digest_alg);
2405 char *signature;
2406
2407 smartlist_add_strdup(chunks, "directory-signature ");
2408
2409 /* Compute the hash of the chunks. */
2410 crypto_digest_smartlist(digest, digest_len, chunks, "", digest_alg);
2411
2412 /* Get the fingerprints */
2413 crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
2414 crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
2415
2416 /* add the junk that will go at the end of the line. */
2417 if (flavor == FLAV_NS) {
2418 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
2419 signing_key_fingerprint);
2420 } else {
2421 smartlist_add_asprintf(chunks, "%s %s %s\n",
2422 algname, fingerprint,
2423 signing_key_fingerprint);
2424 }
2425 /* And the signature. */
2426 if (!(signature = router_get_dirobj_signature(digest, digest_len,
2427 signing_key))) {
2428 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
2429 goto done;
2430 }
2431 smartlist_add(chunks, signature);
2432
2433 if (legacy_id_key_digest && legacy_signing_key) {
2434 smartlist_add_strdup(chunks, "directory-signature ");
2435 base16_encode(fingerprint, sizeof(fingerprint),
2436 legacy_id_key_digest, DIGEST_LEN);
2438 signing_key_fingerprint, 0);
2439 if (flavor == FLAV_NS) {
2440 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
2441 signing_key_fingerprint);
2442 } else {
2443 smartlist_add_asprintf(chunks, "%s %s %s\n",
2444 algname, fingerprint,
2445 signing_key_fingerprint);
2446 }
2447
2448 if (!(signature = router_get_dirobj_signature(digest, digest_len,
2450 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
2451 goto done;
2452 }
2453 smartlist_add(chunks, signature);
2454 }
2455 }
2456
2457 result = smartlist_join_strings(chunks, "", 0, NULL);
2458
2459 {
2460 networkstatus_t *c;
2461 if (!(c = networkstatus_parse_vote_from_string(result, strlen(result),
2462 NULL,
2463 NS_TYPE_CONSENSUS))) {
2464 log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
2465 "parse.");
2466 tor_free(result);
2467 goto done;
2468 }
2469 // Verify balancing parameters
2470 if (added_weights) {
2471 networkstatus_verify_bw_weights(c, consensus_method);
2472 }
2473 networkstatus_vote_free(c);
2474 }
2475
2476 done:
2477
2478 dircollator_free(collator);
2479 tor_free(client_versions);
2480 tor_free(server_versions);
2481 tor_free(packages);
2482 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
2483 smartlist_free(flags);
2484 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2485 smartlist_free(chunks);
2486 SMARTLIST_FOREACH(param_list, char *, cp, tor_free(cp));
2487 smartlist_free(param_list);
2488
2489 return result;
2490}
2491
2492/** Given a list of networkstatus_t for each vote, return a newly allocated
2493 * string containing the "package" lines for the vote. */
2494STATIC char *
2496{
2497 const int n_votes = smartlist_len(votes);
2498
2499 /* This will be a map from "packagename version" strings to arrays
2500 * of const char *, with the i'th member of the array corresponding to the
2501 * package line from the i'th vote.
2502 */
2503 strmap_t *package_status = strmap_new();
2504
2506 if (! v->package_lines)
2507 continue;
2508 SMARTLIST_FOREACH_BEGIN(v->package_lines, const char *, line) {
2510 continue;
2511
2512 /* Skip 'cp' to the second space in the line. */
2513 const char *cp = strchr(line, ' ');
2514 if (!cp) continue;
2515 ++cp;
2516 cp = strchr(cp, ' ');
2517 if (!cp) continue;
2518
2519 char *key = tor_strndup(line, cp - line);
2520
2521 const char **status = strmap_get(package_status, key);
2522 if (!status) {
2523 status = tor_calloc(n_votes, sizeof(const char *));
2524 strmap_set(package_status, key, status);
2525 }
2526 status[v_sl_idx] = line; /* overwrite old value */
2527 tor_free(key);
2528 } SMARTLIST_FOREACH_END(line);
2529 } SMARTLIST_FOREACH_END(v);
2530
2531 smartlist_t *entries = smartlist_new(); /* temporary */
2532 smartlist_t *result_list = smartlist_new(); /* output */
2533 STRMAP_FOREACH(package_status, key, const char **, values) {
2534 int i, count=-1;
2535 for (i = 0; i < n_votes; ++i) {
2536 if (values[i])
2537 smartlist_add(entries, (void*) values[i]);
2538 }
2539 smartlist_sort_strings(entries);
2540 int n_voting_for_entry = smartlist_len(entries);
2541 const char *most_frequent =
2542 smartlist_get_most_frequent_string_(entries, &count);
2543
2544 if (n_voting_for_entry >= 3 && count > n_voting_for_entry / 2) {
2545 smartlist_add_asprintf(result_list, "package %s\n", most_frequent);
2546 }
2547
2548 smartlist_clear(entries);
2549
2550 } STRMAP_FOREACH_END;
2551
2552 smartlist_sort_strings(result_list);
2553
2554 char *result = smartlist_join_strings(result_list, "", 0, NULL);
2555
2556 SMARTLIST_FOREACH(result_list, char *, cp, tor_free(cp));
2557 smartlist_free(result_list);
2558 smartlist_free(entries);
2559 strmap_free(package_status, tor_free_);
2560
2561 return result;
2562}
2563
2564/** Given a consensus vote <b>target</b> and a set of detached signatures in
2565 * <b>sigs</b> that correspond to the same consensus, check whether there are
2566 * any new signatures in <b>src_voter_list</b> that should be added to
2567 * <b>target</b>. (A signature should be added if we have no signature for that
2568 * voter in <b>target</b> yet, or if we have no verifiable signature and the
2569 * new signature is verifiable.)
2570 *
2571 * Return the number of signatures added or changed, or -1 if the document
2572 * signatures are invalid. Sets *<b>msg_out</b> to a string constant
2573 * describing the signature status.
2574 */
2575STATIC int
2578 const char *source,
2579 int severity,
2580 const char **msg_out)
2581{
2582 int r = 0;
2583 const char *flavor;
2584 smartlist_t *siglist;
2585 tor_assert(sigs);
2586 tor_assert(target);
2587 tor_assert(target->type == NS_TYPE_CONSENSUS);
2588
2589 flavor = networkstatus_get_flavor_name(target->flavor);
2590
2591 /* Do the times seem right? */
2592 if (target->valid_after != sigs->valid_after) {
2593 *msg_out = "Valid-After times do not match "
2594 "when adding detached signatures to consensus";
2595 return -1;
2596 }
2597 if (target->fresh_until != sigs->fresh_until) {
2598 *msg_out = "Fresh-until times do not match "
2599 "when adding detached signatures to consensus";
2600 return -1;
2601 }
2602 if (target->valid_until != sigs->valid_until) {
2603 *msg_out = "Valid-until times do not match "
2604 "when adding detached signatures to consensus";
2605 return -1;
2606 }
2607 siglist = strmap_get(sigs->signatures, flavor);
2608 if (!siglist) {
2609 *msg_out = "No signatures for given consensus flavor";
2610 return -1;
2611 }
2612
2613 /** Make sure all the digests we know match, and at least one matches. */
2614 {
2615 common_digests_t *digests = strmap_get(sigs->digests, flavor);
2616 int n_matches = 0;
2617 int alg;
2618 if (!digests) {
2619 *msg_out = "No digests for given consensus flavor";
2620 return -1;
2621 }
2622 for (alg = DIGEST_SHA1; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
2623 if (!fast_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
2624 if (fast_memeq(target->digests.d[alg], digests->d[alg],
2625 DIGEST256_LEN)) {
2626 ++n_matches;
2627 } else {
2628 *msg_out = "Mismatched digest.";
2629 return -1;
2630 }
2631 }
2632 }
2633 if (!n_matches) {
2634 *msg_out = "No recognized digests for given consensus flavor";
2635 }
2636 }
2637
2638 /* For each voter in src... */
2640 char voter_identity[HEX_DIGEST_LEN+1];
2641 networkstatus_voter_info_t *target_voter =
2642 networkstatus_get_voter_by_id(target, sig->identity_digest);
2643 authority_cert_t *cert = NULL;
2644 const char *algorithm;
2645 document_signature_t *old_sig = NULL;
2646
2647 algorithm = crypto_digest_algorithm_get_name(sig->alg);
2648
2649 base16_encode(voter_identity, sizeof(voter_identity),
2650 sig->identity_digest, DIGEST_LEN);
2651 log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
2652 algorithm);
2653 /* If the target doesn't know about this voter, then forget it. */
2654 if (!target_voter) {
2655 log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
2656 continue;
2657 }
2658
2659 old_sig = networkstatus_get_voter_sig_by_alg(target_voter, sig->alg);
2660
2661 /* If the target already has a good signature from this voter, then skip
2662 * this one. */
2663 if (old_sig && old_sig->good_signature) {
2664 log_info(LD_DIR, "We already have a good signature from %s using %s",
2665 voter_identity, algorithm);
2666 continue;
2667 }
2668
2669 /* Try checking the signature if we haven't already. */
2670 if (!sig->good_signature && !sig->bad_signature) {
2671 cert = authority_cert_get_by_digests(sig->identity_digest,
2672 sig->signing_key_digest);
2673 if (cert) {
2674 /* Not checking the return value here, since we are going to look
2675 * at the status of sig->good_signature in a moment. */
2676 (void) networkstatus_check_document_signature(target, sig, cert);
2677 }
2678 }
2679
2680 /* If this signature is good, or we don't have any signature yet,
2681 * then maybe add it. */
2682 if (sig->good_signature || !old_sig || old_sig->bad_signature) {
2683 log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
2684 algorithm);
2685 tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
2686 target_voter->nickname, source);
2687 ++r;
2688 if (old_sig) {
2689 smartlist_remove(target_voter->sigs, old_sig);
2690 document_signature_free(old_sig);
2691 }
2692 smartlist_add(target_voter->sigs, document_signature_dup(sig));
2693 } else {
2694 log_info(LD_DIR, "Not adding signature from %s", voter_identity);
2695 }
2696 } SMARTLIST_FOREACH_END(sig);
2697
2698 return r;
2699}
2700
2701/** Return a newly allocated string containing all the signatures on
2702 * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
2703 * then the signatures will be put in a detached signatures document, so
2704 * prefix any non-NS-flavored signatures with "additional-signature" rather
2705 * than "directory-signature". */
2706static char *
2708 int for_detached_signatures)
2709{
2710 smartlist_t *elements;
2711 char buf[4096];
2712 char *result = NULL;
2713 int n_sigs = 0;
2714 const consensus_flavor_t flavor = consensus->flavor;
2715 const char *flavor_name = networkstatus_get_flavor_name(flavor);
2716 const char *keyword;
2717
2718 if (for_detached_signatures && flavor != FLAV_NS)
2719 keyword = "additional-signature";
2720 else
2721 keyword = "directory-signature";
2722
2723 elements = smartlist_new();
2724
2727 char sk[HEX_DIGEST_LEN+1];
2728 char id[HEX_DIGEST_LEN+1];
2729 if (!sig->signature || sig->bad_signature)
2730 continue;
2731 ++n_sigs;
2732 base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
2733 base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
2734 if (flavor == FLAV_NS) {
2735 smartlist_add_asprintf(elements,
2736 "%s %s %s\n-----BEGIN SIGNATURE-----\n",
2737 keyword, id, sk);
2738 } else {
2739 const char *digest_name =
2741 smartlist_add_asprintf(elements,
2742 "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
2743 keyword,
2744 for_detached_signatures ? " " : "",
2745 for_detached_signatures ? flavor_name : "",
2746 digest_name, id, sk);
2747 }
2748 base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len,
2749 BASE64_ENCODE_MULTILINE);
2750 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
2751 smartlist_add_strdup(elements, buf);
2752 } SMARTLIST_FOREACH_END(sig);
2753 } SMARTLIST_FOREACH_END(v);
2754
2755 result = smartlist_join_strings(elements, "", 0, NULL);
2756 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2757 smartlist_free(elements);
2758 if (!n_sigs)
2759 tor_free(result);
2760 return result;
2761}
2762
2763/** Return a newly allocated string holding the detached-signatures document
2764 * corresponding to the signatures on <b>consensuses</b>, which must contain
2765 * exactly one FLAV_NS consensus, and no more than one consensus for each
2766 * other flavor. */
2767STATIC char *
2769{
2770 smartlist_t *elements;
2771 char *result = NULL, *sigs = NULL;
2772 networkstatus_t *consensus_ns = NULL;
2773 tor_assert(consensuses);
2774
2775 SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
2776 tor_assert(ns);
2777 tor_assert(ns->type == NS_TYPE_CONSENSUS);
2778 if (ns && ns->flavor == FLAV_NS)
2779 consensus_ns = ns;
2780 });
2781 if (!consensus_ns) {
2782 log_warn(LD_BUG, "No NS consensus given.");
2783 return NULL;
2784 }
2785
2786 elements = smartlist_new();
2787
2788 {
2789 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
2790 vu_buf[ISO_TIME_LEN+1];
2791 char d[HEX_DIGEST_LEN+1];
2792
2793 base16_encode(d, sizeof(d),
2794 consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
2795 format_iso_time(va_buf, consensus_ns->valid_after);
2796 format_iso_time(fu_buf, consensus_ns->fresh_until);
2797 format_iso_time(vu_buf, consensus_ns->valid_until);
2798
2799 smartlist_add_asprintf(elements,
2800 "consensus-digest %s\n"
2801 "valid-after %s\n"
2802 "fresh-until %s\n"
2803 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
2804 }
2805
2806 /* Get all the digests for the non-FLAV_NS consensuses */
2807 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2808 const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
2809 int alg;
2810 if (ns->flavor == FLAV_NS)
2811 continue;
2812
2813 /* start with SHA256; we don't include SHA1 for anything but the basic
2814 * consensus. */
2815 for (alg = DIGEST_SHA256; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
2816 char d[HEX_DIGEST256_LEN+1];
2817 const char *alg_name =
2819 if (fast_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
2820 continue;
2821 base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
2822 smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
2823 flavor_name, alg_name, d);
2824 }
2825 } SMARTLIST_FOREACH_END(ns);
2826
2827 /* Now get all the sigs for non-FLAV_NS consensuses */
2828 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2829 char *sigs_on_this_consensus;
2830 if (ns->flavor == FLAV_NS)
2831 continue;
2832 sigs_on_this_consensus = networkstatus_format_signatures(ns, 1);
2833 if (!sigs_on_this_consensus) {
2834 log_warn(LD_DIR, "Couldn't format signatures");
2835 goto err;
2836 }
2837 smartlist_add(elements, sigs_on_this_consensus);
2838 } SMARTLIST_FOREACH_END(ns);
2839
2840 /* Now add the FLAV_NS consensus signatrures. */
2841 sigs = networkstatus_format_signatures(consensus_ns, 1);
2842 if (!sigs)
2843 goto err;
2844 smartlist_add(elements, sigs);
2845
2846 result = smartlist_join_strings(elements, "", 0, NULL);
2847 err:
2848 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2849 smartlist_free(elements);
2850 return result;
2851}
2852
2853/** Return a newly allocated string holding a detached-signatures document for
2854 * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
2855 * <b>pending</b>. */
2856static char *
2858 int n_flavors)
2859{
2860 int flav;
2861 char *signatures;
2863 for (flav = 0; flav < n_flavors; ++flav) {
2864 if (pending[flav].consensus)
2865 smartlist_add(c, pending[flav].consensus);
2866 }
2868 smartlist_free(c);
2869 return signatures;
2870}
2871
2872/**
2873 * Entry point: Take whatever voting actions are pending as of <b>now</b>.
2874 *
2875 * Return the time at which the next action should be taken.
2876 */
2877time_t
2878dirvote_act(const or_options_t *options, time_t now)
2879{
2880 if (!authdir_mode_v3(options))
2881 return TIME_MAX;
2882 tor_assert_nonfatal(voting_schedule.voting_starts);
2883 /* If we haven't initialized this object through this codeflow, we need to
2884 * recalculate the timings to match our vote. The reason to do that is if we
2885 * have a voting schedule initialized 1 minute ago, the voting timings might
2886 * not be aligned to what we should expect with "now". This is especially
2887 * true for TestingTorNetwork using smaller timings. */
2888 if (voting_schedule.created_on_demand) {
2889 char *keys = list_v3_auth_ids();
2891 log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
2892 "Mine is %s.",
2894 tor_free(keys);
2895 dirauth_sched_recalculate_timing(options, now);
2896 }
2897
2898#define IF_TIME_FOR_NEXT_ACTION(when_field, done_field) \
2899 if (! voting_schedule.done_field) { \
2900 if (voting_schedule.when_field > now) { \
2901 return voting_schedule.when_field; \
2902 } else {
2903#define ENDIF \
2904 } \
2905 }
2906
2907 IF_TIME_FOR_NEXT_ACTION(voting_starts, have_voted) {
2908 log_notice(LD_DIR, "Time to vote.");
2910 voting_schedule.have_voted = 1;
2911 } ENDIF
2912 IF_TIME_FOR_NEXT_ACTION(fetch_missing_votes, have_fetched_missing_votes) {
2913 log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
2915 voting_schedule.have_fetched_missing_votes = 1;
2916 } ENDIF
2917 IF_TIME_FOR_NEXT_ACTION(voting_ends, have_built_consensus) {
2918 log_notice(LD_DIR, "Time to compute a consensus.");
2920 /* XXXX We will want to try again later if we haven't got enough
2921 * votes yet. Implement this if it turns out to ever happen. */
2922 voting_schedule.have_built_consensus = 1;
2923 } ENDIF
2924 IF_TIME_FOR_NEXT_ACTION(fetch_missing_signatures,
2925 have_fetched_missing_signatures) {
2926 log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
2928 voting_schedule.have_fetched_missing_signatures = 1;
2929 } ENDIF
2930 IF_TIME_FOR_NEXT_ACTION(interval_starts,
2931 have_published_consensus) {
2932 log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
2935 voting_schedule.have_published_consensus = 1;
2936 /* Update our shared random state with the consensus just published. */
2939 /* XXXX We will want to try again later if we haven't got enough
2940 * signatures yet. Implement this if it turns out to ever happen. */
2941 dirauth_sched_recalculate_timing(options, now);
2942 return voting_schedule.voting_starts;
2943 } ENDIF
2944
2946 return now + 1;
2947
2948#undef ENDIF
2949#undef IF_TIME_FOR_NEXT_ACTION
2950}
2951
2952/** A vote networkstatus_t and its unparsed body: held around so we can
2953 * use it to generate a consensus (at voting_ends) and so we can serve it to
2954 * other authorities that might want it. */
2955typedef struct pending_vote_t {
2956 cached_dir_t *vote_body;
2957 networkstatus_t *vote;
2959
2960/** List of pending_vote_t for the current vote. Before we've used them to
2961 * build a consensus, the votes go here. */
2963/** List of pending_vote_t for the previous vote. After we've used them to
2964 * build a consensus, the votes go here for the next period. */
2966
2967/* DOCDOC pending_consensuses */
2968static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
2969
2970/** The detached signatures for the consensus that we're currently
2971 * building. */
2973
2974/** List of ns_detached_signatures_t: hold signatures that get posted to us
2975 * before we have generated the consensus on our own. */
2977
2978/** Generate a networkstatus vote and post it to all the v3 authorities.
2979 * (V3 Authority only) */
2980static int
2982{
2985 networkstatus_t *ns;
2986 char *contents;
2987 pending_vote_t *pending_vote;
2988 time_t now = time(NULL);
2989
2990 int status;
2991 const char *msg = "";
2992
2993 if (!cert || !key) {
2994 log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
2995 return -1;
2996 } else if (cert->expires < now) {
2997 log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
2998 return -1;
2999 }
3000 if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
3001 return -1;
3002
3003 contents = format_networkstatus_vote(key, ns);
3004 networkstatus_vote_free(ns);
3005 if (!contents)
3006 return -1;
3007
3008 pending_vote = dirvote_add_vote(contents, 0, "self", &msg, &status);
3009 tor_free(contents);
3010 if (!pending_vote) {
3011 log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
3012 msg);
3013 return -1;
3014 }
3015
3018 V3_DIRINFO,
3019 pending_vote->vote_body->dir,
3020 pending_vote->vote_body->dir_len, 0);
3021 log_notice(LD_DIR, "Vote posted.");
3022 return 0;
3023}
3024
3025/** Send an HTTP request to every other v3 authority, for the votes of every
3026 * authority for which we haven't received a vote yet in this period. (V3
3027 * authority only) */
3028static void
3030{
3031 smartlist_t *missing_fps = smartlist_new();
3032 char *resource;
3033
3034 SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
3035 dir_server_t *, ds) {
3036 if (!(ds->type & V3_DIRINFO))
3037 continue;
3038 if (!dirvote_get_vote(ds->v3_identity_digest,
3039 DGV_BY_ID|DGV_INCLUDE_PENDING)) {
3040 char *cp = tor_malloc(HEX_DIGEST_LEN+1);
3041 base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
3042 DIGEST_LEN);
3043 smartlist_add(missing_fps, cp);
3044 }
3045 } SMARTLIST_FOREACH_END(ds);
3046
3047 if (!smartlist_len(missing_fps)) {
3048 smartlist_free(missing_fps);
3049 return;
3050 }
3051 {
3052 char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
3053 log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
3054 "Asking every other authority for a copy.",
3055 smartlist_len(missing_fps), tmp);
3056 tor_free(tmp);
3057 }
3058 resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
3060 0, resource);
3061 tor_free(resource);
3062 SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
3063 smartlist_free(missing_fps);
3064}
3065
3066/** Send a request to every other authority for its detached signatures,
3067 * unless we have signatures from all other v3 authorities already. */
3068static void
3070{
3071 int need_any = 0;
3072 int i;
3073 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
3074 networkstatus_t *consensus = pending_consensuses[i].consensus;
3075 if (!consensus ||
3076 networkstatus_check_consensus_signature(consensus, -1) == 1) {
3077 /* We have no consensus, or we have one that's signed by everybody. */
3078 continue;
3079 }
3080 need_any = 1;
3081 }
3082 if (!need_any)
3083 return;
3084
3086 0, NULL);
3087}
3088
3089/** Release all storage held by pending consensuses (those waiting for
3090 * signatures). */
3091static void
3093{
3094 int i;
3095 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3096 pending_consensus_t *pc = &pending_consensuses[i];
3097 tor_free(pc->body);
3098
3099 networkstatus_vote_free(pc->consensus);
3100 pc->consensus = NULL;
3101 }
3102}
3103
3104/** Drop all currently pending votes, consensus, and detached signatures. */
3105static void
3107{
3108 if (!previous_vote_list)
3110 if (!pending_vote_list)
3112
3113 /* All "previous" votes are now junk. */
3115 cached_dir_decref(v->vote_body);
3116 v->vote_body = NULL;
3117 networkstatus_vote_free(v->vote);
3118 tor_free(v);
3119 });
3121
3122 if (all_votes) {
3123 /* If we're dumping all the votes, we delete the pending ones. */
3125 cached_dir_decref(v->vote_body);
3126 v->vote_body = NULL;
3127 networkstatus_vote_free(v->vote);
3128 tor_free(v);
3129 });
3130 } else {
3131 /* Otherwise, we move them into "previous". */
3133 }
3135
3138 tor_free(cp));
3140 }
3143}
3144
3145/** Return a newly allocated string containing the hex-encoded v3 authority
3146 identity digest of every recognized v3 authority. */
3147static char *
3149{
3150 smartlist_t *known_v3_keys = smartlist_new();
3151 char *keys;
3152 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
3153 dir_server_t *, ds,
3154 if ((ds->type & V3_DIRINFO) &&
3155 !tor_digest_is_zero(ds->v3_identity_digest))
3156 smartlist_add(known_v3_keys,
3157 tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
3158 keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
3159 SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
3160 smartlist_free(known_v3_keys);
3161 return keys;
3162}
3163
3164/* Check the voter information <b>vi</b>, and assert that at least one
3165 * signature is good. Asserts on failure. */
3166static void
3167assert_any_sig_good(const networkstatus_voter_info_t *vi)
3168{
3169 int any_sig_good = 0;
3171 if (sig->good_signature)
3172 any_sig_good = 1);
3173 tor_assert(any_sig_good);
3174}
3175
3176/* Add <b>cert</b> to our list of known authority certificates. */
3177static void
3178add_new_cert_if_needed(const struct authority_cert_t *cert)
3179{
3180 tor_assert(cert);
3182 cert->signing_key_digest)) {
3183 /* Hey, it's a new cert! */
3186 TRUSTED_DIRS_CERTS_SRC_FROM_VOTE, 1 /*flush*/,
3187 NULL);
3189 cert->signing_key_digest)) {
3190 log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
3191 }
3192 }
3193}
3194
3195/** Called when we have received a networkstatus vote in <b>vote_body</b>.
3196 * Parse and validate it, and on success store it as a pending vote (which we
3197 * then return). Return NULL on failure. Sets *<b>msg_out</b> and
3198 * *<b>status_out</b> to an HTTP response and status code. (V3 authority
3199 * only) */
3201dirvote_add_vote(const char *vote_body, time_t time_posted,
3202 const char *where_from,
3203 const char **msg_out, int *status_out)
3204{
3205 networkstatus_t *vote;
3207 dir_server_t *ds;
3208 pending_vote_t *pending_vote = NULL;
3209 const char *end_of_vote = NULL;
3210 int any_failed = 0;
3211 tor_assert(vote_body);
3212 tor_assert(msg_out);
3213 tor_assert(status_out);
3214
3215 if (!pending_vote_list)
3217 *status_out = 0;
3218 *msg_out = NULL;
3219
3220 again:
3221 vote = networkstatus_parse_vote_from_string(vote_body, strlen(vote_body),
3222 &end_of_vote,
3223 NS_TYPE_VOTE);
3224 if (!end_of_vote)
3225 end_of_vote = vote_body + strlen(vote_body);
3226 if (!vote) {
3227 log_warn(LD_DIR, "Couldn't parse vote: length was %d",
3228 (int)strlen(vote_body));
3229 *msg_out = "Unable to parse vote";
3230 goto err;
3231 }
3232 tor_assert(smartlist_len(vote->voters) == 1);
3233 vi = get_voter(vote);
3234 assert_any_sig_good(vi);
3236 if (!ds) {
3237 char *keys = list_v3_auth_ids();
3238 log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
3239 "with authority key ID %s. "
3240 "This key ID is not recognized. Known v3 key IDs are: %s",
3241 vi->nickname, vi->address,
3242 hex_str(vi->identity_digest, DIGEST_LEN), keys);
3243 tor_free(keys);
3244 *msg_out = "Vote not from a recognized v3 authority";
3245 goto err;
3246 }
3247 add_new_cert_if_needed(vote->cert);
3248
3249 /* Is it for the right period? */
3250 if (vote->valid_after != voting_schedule.interval_starts) {
3251 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
3252 format_iso_time(tbuf1, vote->valid_after);
3253 format_iso_time(tbuf2, voting_schedule.interval_starts);
3254 log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
3255 "we were expecting %s", vi->address, tbuf1, tbuf2);
3256 *msg_out = "Bad valid-after time";
3257 goto err;
3258 }
3259
3260 if (time_posted) { /* they sent it to me via a POST */
3261 log_notice(LD_DIR, "%s posted a vote to me from %s.",
3262 vi->nickname, where_from);
3263 } else { /* I imported this one myself */
3264 log_notice(LD_DIR, "Retrieved %s's vote from %s.",
3265 vi->nickname, where_from);
3266 }
3267
3268 /* Check if we received it, as a post, after the cutoff when we
3269 * start asking other dir auths for it. If we do, the best plan
3270 * is to discard it, because using it greatly increases the chances
3271 * of a split vote for this round (some dir auths got it in time,
3272 * some didn't). */
3273 if (time_posted && time_posted > voting_schedule.fetch_missing_votes) {
3274 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
3275 format_iso_time(tbuf1, time_posted);
3276 format_iso_time(tbuf2, voting_schedule.fetch_missing_votes);
3277 log_warn(LD_DIR, "Rejecting %s's posted vote from %s received at %s; "
3278 "our cutoff for received votes is %s. Check your clock, "
3279 "CPU load, and network load. Also check the authority that "
3280 "posted the vote.", vi->nickname, vi->address, tbuf1, tbuf2);
3281 *msg_out = "Posted vote received too late, would be dangerous to count it";
3282 goto err;
3283 }
3284
3285 /* Fetch any new router descriptors we just learned about */
3287
3288 /* Now see whether we already have a vote from this authority. */
3290 if (fast_memeq(v->vote->cert->cache_info.identity_digest,
3292 DIGEST_LEN)) {
3293 networkstatus_voter_info_t *vi_old = get_voter(v->vote);
3294 if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
3295 /* Ah, it's the same vote. Not a problem. */
3296 log_notice(LD_DIR, "Discarding a vote we already have (from %s).",
3297 vi->address);
3298 if (*status_out < 200)
3299 *status_out = 200;
3300 goto discard;
3301 } else if (v->vote->published < vote->published) {
3302 log_notice(LD_DIR, "Replacing an older pending vote from this "
3303 "directory (%s)", vi->address);
3304 cached_dir_decref(v->vote_body);
3305 networkstatus_vote_free(v->vote);
3306 v->vote_body = new_cached_dir(tor_strndup(vote_body,
3307 end_of_vote-vote_body),
3308 vote->published);
3309 v->vote = vote;
3310 if (end_of_vote &&
3311 !strcmpstart(end_of_vote, "network-status-version"))
3312 goto again;
3313
3314 if (*status_out < 200)
3315 *status_out = 200;
3316 if (!*msg_out)
3317 *msg_out = "OK";
3318 return v;
3319 } else {
3320 log_notice(LD_DIR, "Discarding vote from %s because we have "
3321 "a newer one already.", vi->address);
3322 *msg_out = "Already have a newer pending vote";
3323 goto err;
3324 }
3325 }
3326 } SMARTLIST_FOREACH_END(v);
3327
3328 /* This a valid vote, update our shared random state. */
3329 sr_handle_received_commits(vote->sr_info.commits,
3330 vote->cert->identity_key);
3331
3332 pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
3333 pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
3334 end_of_vote-vote_body),
3335 vote->published);
3336 pending_vote->vote = vote;
3337 smartlist_add(pending_vote_list, pending_vote);
3338
3339 if (!strcmpstart(end_of_vote, "network-status-version ")) {
3340 vote_body = end_of_vote;
3341 goto again;
3342 }
3343
3344 goto done;
3345
3346 err:
3347 any_failed = 1;
3348 if (!*msg_out)
3349 *msg_out = "Error adding vote";
3350 if (*status_out < 400)
3351 *status_out = 400;
3352
3353 discard:
3354 networkstatus_vote_free(vote);
3355
3356 if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
3357 vote_body = end_of_vote;
3358 goto again;
3359 }
3360
3361 done:
3362
3363 if (*status_out < 200)
3364 *status_out = 200;
3365 if (!*msg_out) {
3366 if (!any_failed && !pending_vote) {
3367 *msg_out = "Duplicate discarded";
3368 } else {
3369 *msg_out = "ok";
3370 }
3371 }
3372
3373 return any_failed ? NULL : pending_vote;
3374}
3375
3376/* Write the votes in <b>pending_vote_list</b> to disk. */
3377static void
3378write_v3_votes_to_disk(const smartlist_t *pending_votes)
3379{
3380 smartlist_t *votestrings = smartlist_new();
3381 char *votefile = NULL;
3382
3383 SMARTLIST_FOREACH(pending_votes, pending_vote_t *, v,
3384 {
3385 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
3386 c->bytes = v->vote_body->dir;
3387 c->len = v->vote_body->dir_len;
3388 smartlist_add(votestrings, c); /* collect strings to write to disk */
3389 });
3390
3391 votefile = get_datadir_fname("v3-status-votes");
3392 write_chunks_to_file(votefile, votestrings, 0, 0);
3393 log_debug(LD_DIR, "Wrote votes to disk (%s)!", votefile);
3394
3395 tor_free(votefile);
3396 SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
3397 smartlist_free(votestrings);
3398}
3399
3400/** Try to compute a v3 networkstatus consensus from the currently pending
3401 * votes. Return 0 on success, -1 on failure. Store the consensus in
3402 * pending_consensus: it won't be ready to be published until we have
3403 * everybody else's signatures collected too. (V3 Authority only) */
3404static int
3406{
3407 /* Have we got enough votes to try? */
3408 int n_votes, n_voters, n_vote_running = 0;
3409 smartlist_t *votes = NULL;
3410 char *consensus_body = NULL, *signatures = NULL;
3411 networkstatus_t *consensus = NULL;
3412 authority_cert_t *my_cert;
3414 int flav;
3415
3416 memset(pending, 0, sizeof(pending));
3417
3418 if (!pending_vote_list)
3420
3421 /* Write votes to disk */
3422 write_v3_votes_to_disk(pending_vote_list);
3423
3424 /* Setup votes smartlist */
3425 votes = smartlist_new();
3427 {
3428 smartlist_add(votes, v->vote); /* collect votes to compute consensus */
3429 });
3430
3431 /* See if consensus managed to achieve majority */
3432 n_voters = get_n_authorities(V3_DIRINFO);
3433 n_votes = smartlist_len(pending_vote_list);
3434 if (n_votes <= n_voters/2) {
3435 log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
3436 "%d of %d", n_votes, n_voters/2+1);
3437 goto err;
3438 }
3441 if (smartlist_contains_string(v->vote->known_flags, "Running"))
3442 n_vote_running++;
3443 });
3444 if (!n_vote_running) {
3445 /* See task 1066. */
3446 log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
3447 "and publishing a consensus without Running nodes "
3448 "would make many clients stop working. Not "
3449 "generating a consensus!");
3450 goto err;
3451 }
3452
3453 if (!(my_cert = get_my_v3_authority_cert())) {
3454 log_warn(LD_DIR, "Can't generate consensus without a certificate.");
3455 goto err;
3456 }
3457
3458 {
3459 char legacy_dbuf[DIGEST_LEN];
3460 crypto_pk_t *legacy_sign=NULL;
3461 char *legacy_id_digest = NULL;
3462 int n_generated = 0;
3463 if (get_options()->V3AuthUseLegacyKey) {
3465 legacy_sign = get_my_v3_legacy_signing_key();
3466 if (cert) {
3467 if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
3468 log_warn(LD_BUG,
3469 "Unable to compute digest of legacy v3 identity key");
3470 } else {
3471 legacy_id_digest = legacy_dbuf;
3472 }
3473 }
3474 }
3475
3476 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
3477 const char *flavor_name = networkstatus_get_flavor_name(flav);
3478 consensus_body = networkstatus_compute_consensus(
3479 votes, n_voters,
3480 my_cert->identity_key,
3481 get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
3482 flav);
3483
3484 if (!consensus_body) {
3485 log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
3486 flavor_name);
3487 continue;
3488 }
3489 consensus = networkstatus_parse_vote_from_string(consensus_body,
3490 strlen(consensus_body),
3491 NULL,
3492 NS_TYPE_CONSENSUS);
3493 if (!consensus) {
3494 log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
3495 flavor_name);
3496 tor_free(consensus_body);
3497 continue;
3498 }
3499
3500 /* 'Check' our own signature, to mark it valid. */
3502
3503 pending[flav].body = consensus_body;
3504 pending[flav].consensus = consensus;
3505 n_generated++;
3506
3507 consensus_body = NULL;
3508 consensus = NULL;
3509 }
3510 if (!n_generated) {
3511 log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
3512 goto err;
3513 }
3514 }
3515
3517 pending, N_CONSENSUS_FLAVORS);
3518
3519 if (!signatures) {
3520 log_warn(LD_DIR, "Couldn't extract signatures.");
3521 goto err;
3522 }
3523
3525 memcpy(pending_consensuses, pending, sizeof(pending));
3526
3528 pending_consensus_signatures = signatures;
3529
3531 int n_sigs = 0;
3532 /* we may have gotten signatures for this consensus before we built
3533 * it ourself. Add them now. */
3535 const char *msg = NULL;
3537 "pending", &msg);
3538 if (r >= 0)
3539 n_sigs += r;
3540 else
3541 log_warn(LD_DIR,
3542 "Could not add queued signature to new consensus: %s",
3543 msg);
3544 tor_free(sig);
3545 } SMARTLIST_FOREACH_END(sig);
3546 if (n_sigs)
3547 log_notice(LD_DIR, "Added %d pending signatures while building "
3548 "consensus.", n_sigs);
3550 }
3551
3552 log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
3553
3556 V3_DIRINFO,
3558 strlen(pending_consensus_signatures), 0);
3559 log_notice(LD_DIR, "Signature(s) posted.");
3560
3561 smartlist_free(votes);
3562 return 0;
3563 err:
3564 smartlist_free(votes);
3565 tor_free(consensus_body);
3566 tor_free(signatures);
3567 networkstatus_vote_free(consensus);
3568
3569 return -1;
3570}
3571
3572/** We just got enough sigs on the pending <b>flavor_name</b>-flavor
3573 * consensus that it is time to export it to the consensus transparency
3574 * module. We do this by writing a "consensus-transparency-%s" file which
3575 * the module will detect and act on.
3576 *
3577 * The file needs to be just the bare consensus, with no signatures, so we
3578 * are registering a hash that everybody can agree on. */
3579static void
3581{
3582 char *filename = NULL;
3583 tor_asprintf(&filename, "my-consensus-%s", flavor_name);
3584 char *fpath_from = get_datadir_fname(filename);
3585 tor_free(filename);
3586 tor_asprintf(&filename, "consensus-transparency-%s", flavor_name);
3587 char *fpath_to = get_datadir_fname(filename);
3588 tor_free(filename);
3589
3590 replace_file(fpath_from, fpath_to);
3591
3592 log_notice(LD_DIR, "Exported consensus transparency file %s.",
3593 fpath_to);
3594
3595 tor_free(fpath_from);
3596 tor_free(fpath_to);
3597}
3598
3599/** Helper: we just received <b>sigs</b> as
3600 * signatures on the currently pending consensus. Add them to <b>pc</b>
3601 * as appropriate. Return the number of signatures added, or -1 if error. */
3602static int
3606 const char *source,
3607 int severity,
3608 const char **msg_out)
3609{
3610 const char *flavor_name;
3611 int r = -1;
3612
3613 /* Only call if we have a pending consensus right now. */
3614 tor_assert(pc->consensus);
3615 tor_assert(pc->body);
3617
3619 *msg_out = NULL;
3620
3621 {
3622 smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
3623 log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
3624 sig_list ? smartlist_len(sig_list) : 0, flavor_name);
3625 }
3627 source, severity, msg_out);
3628 if (r >= 0) {
3629 log_info(LD_DIR,"Added %d signatures to consensus.", r);
3630 } else {
3631 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
3632 "Unable to add signatures to consensus: %s",
3633 *msg_out ? *msg_out : "(unknown)");
3634 }
3635
3636 if (r >= 1) {
3637 char *new_signatures =
3639 char *dst, *dst_end;
3640 size_t new_consensus_len;
3641 if (!new_signatures) {
3642 *msg_out = "No signatures to add";
3643 goto err;
3644 }
3645 new_consensus_len =
3646 strlen(pc->body) + strlen(new_signatures) + 1;
3647 pc->body = tor_realloc(pc->body, new_consensus_len);
3648 dst_end = pc->body + new_consensus_len;
3649 dst = (char *) find_str_at_start_of_line(pc->body, "directory-signature ");
3650 tor_assert(dst);
3651 strlcpy(dst, new_signatures, dst_end-dst);
3652
3653 /* We remove this block once it has failed to crash for a while. But
3654 * unless it shows up in profiles, we're probably better leaving it in,
3655 * just in case we break detached signature processing at some point. */
3656 {
3657 networkstatus_t *v = networkstatus_parse_vote_from_string(
3658 pc->body, strlen(pc->body), NULL,
3659 NS_TYPE_CONSENSUS);
3660 tor_assert(v);
3661 networkstatus_vote_free(v);
3662 }
3663 *msg_out = "Signatures added";
3664 tor_free(new_signatures);
3665
3666 /* Check if we now have enough sigs that we are confident this
3667 * will be our consensus. */
3670 /* Yes! Send it to the consensus transparency module. */
3673 }
3674
3675 } else if (r == 0) {
3676 *msg_out = "Signatures ignored";
3677 } else {
3678 goto err;
3679 }
3680
3681 goto done;
3682 err:
3683 if (!*msg_out)
3684 *msg_out = "Unrecognized error while adding detached signatures.";
3685 done:
3686 return r;
3687}
3688
3689/** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3690 * signatures on the currently pending consensus. Add them to the pending
3691 * consensus (if we have one).
3692 *
3693 * Set *<b>msg</b> to a string constant describing the status, regardless of
3694 * success or failure.
3695 *
3696 * Return negative on failure, nonnegative on success. */
3697static int
3699 const char *detached_signatures_body,
3700 const char *source,
3701 const char **msg_out)
3702{
3703 int r=0, i, n_added = 0, errors = 0;
3705 tor_assert(detached_signatures_body);
3706 tor_assert(msg_out);
3708
3709 if (!(sigs = networkstatus_parse_detached_signatures(
3710 detached_signatures_body, NULL))) {
3711 *msg_out = "Couldn't parse detached signatures.";
3712 goto err;
3713 }
3714
3715 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3716 int res;
3717 int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
3718 pending_consensus_t *pc = &pending_consensuses[i];
3719 if (!pc->consensus)
3720 continue;
3721 res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
3722 severity, msg_out);
3723 if (res < 0)
3724 errors++;
3725 else
3726 n_added += res;
3727 }
3728
3729 if (errors && !n_added) {
3730 r = -1;
3731 goto err;
3732 }
3733
3734 if (n_added && pending_consensuses[FLAV_NS].consensus) {
3735 char *new_detached =
3737 pending_consensuses, N_CONSENSUS_FLAVORS);
3738 if (new_detached) {
3740 pending_consensus_signatures = new_detached;
3741 }
3742 }
3743
3744 r = n_added;
3745 goto done;
3746 err:
3747 if (!*msg_out)
3748 *msg_out = "Unrecognized error while adding detached signatures.";
3749 done:
3750 ns_detached_signatures_free(sigs);
3751 /* XXXX NM Check how return is used. We can now have an error *and*
3752 signatures added. */
3753 return r;
3754}
3755
3756/** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3757 * signatures on the currently pending consensus. Add them to the pending
3758 * consensus (if we have one); otherwise queue them until we have a
3759 * consensus.
3760 *
3761 * Set *<b>msg</b> to a string constant describing the status, regardless of
3762 * success or failure.
3763 *
3764 * Return negative on failure, nonnegative on success. */
3765int
3766dirvote_add_signatures(const char *detached_signatures_body,
3767 const char *source,
3768 const char **msg)
3769{
3770 if (pending_consensuses[FLAV_NS].consensus) {
3771 log_notice(LD_DIR, "Got a signature from %s. "
3772 "Adding it to the pending consensus.", source);
3774 detached_signatures_body, source, msg);
3775 } else {
3776 log_notice(LD_DIR, "Got a signature from %s. "
3777 "Queuing it for the next consensus.", source);
3781 detached_signatures_body);
3782 *msg = "Signature queued";
3783 return 0;
3784 }
3785}
3786
3787/** Replace the consensus that we're currently serving with the one that we've
3788 * been building. (V3 Authority only) */
3789static int
3791{
3792 int i;
3793
3794 /* Now remember all the other consensuses as if we were a directory cache. */
3795 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3796 pending_consensus_t *pending = &pending_consensuses[i];
3797 const char *name;
3800 if (!pending->consensus ||
3802 log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
3803 continue;
3804 }
3805
3807 strlen(pending->body),
3808 name, 0, NULL))
3809 log_warn(LD_DIR, "Error publishing %s consensus", name);
3810 else
3811 log_notice(LD_DIR, "Published %s consensus", name);
3812 }
3813
3814 return 0;
3815}
3816
3817/** Release all static storage held in dirvote.c */
3818void
3820{
3822 /* now empty as a result of dirvote_clear_votes(). */
3823 smartlist_free(pending_vote_list);
3824 pending_vote_list = NULL;
3825 smartlist_free(previous_vote_list);
3826 previous_vote_list = NULL;
3827
3831 /* now empty as a result of dirvote_clear_votes(). */
3832 smartlist_free(pending_consensus_signature_list);
3834 }
3835}
3836
3837/* ====
3838 * Access to pending items.
3839 * ==== */
3840
3841/** Return the body of the consensus that we're currently trying to build. */
3842MOCK_IMPL(const char *,
3844{
3845 tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
3846 return pending_consensuses[flav].body;
3847}
3848
3849/** Return the signatures that we know for the consensus that we're currently
3850 * trying to build. */
3851MOCK_IMPL(const char *,
3856
3857/** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
3858 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
3859 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
3860 * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
3861 * false, do not consider any votes for a consensus that's already been built.
3862 * If <b>include_pending</b> is false, do not consider any votes for the
3863 * consensus that's in progress. May return NULL if we have no vote for the
3864 * authority in question. */
3865const cached_dir_t *
3866dirvote_get_vote(const char *fp, int flags)
3867{
3868 int by_id = flags & DGV_BY_ID;
3869 const int include_pending = flags & DGV_INCLUDE_PENDING;
3870 const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
3871
3873 return NULL;
3874 if (fp == NULL) {
3876 if (c) {
3878 by_id = 1;
3879 } else
3880 return NULL;
3881 }
3882 if (by_id) {
3883 if (pending_vote_list && include_pending) {
3885 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3886 return pv->vote_body);
3887 }
3888 if (previous_vote_list && include_previous) {
3890 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3891 return pv->vote_body);
3892 }
3893 } else {
3894 if (pending_vote_list && include_pending) {
3896 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3897 return pv->vote_body);
3898 }
3899 if (previous_vote_list && include_previous) {
3901 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3902 return pv->vote_body);
3903 }
3904 }
3905 return NULL;
3906}
3907
3908/** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
3909 * according to <b>consensus_method</b>.
3910 **/
3912dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
3913{
3914 (void) consensus_method; // Currently unneeded...
3915 microdesc_t *result = NULL;
3916 char *key = NULL, *summary = NULL, *family = NULL;
3917 size_t keylen;
3918 smartlist_t *chunks = smartlist_new();
3919 char *output = NULL;
3920 crypto_pk_t *rsa_pubkey = router_get_rsa_onion_pkey(ri->tap_onion_pkey,
3921 ri->tap_onion_pkey_len);
3922 if (!rsa_pubkey) {
3923 /* We do not yet support creating MDs for relays without TAP onion keys. */
3924 goto done;
3925 }
3926
3927 if (crypto_pk_write_public_key_to_string(rsa_pubkey, &key, &keylen)<0)
3928 goto done;
3929 summary = policy_summarize(ri->exit_policy, AF_INET);
3930 if (ri->declared_family)
3931 family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
3932
3933 smartlist_add_asprintf(chunks, "onion-key\n%s", key);
3934
3935 if (ri->onion_curve25519_pkey) {
3936 char kbuf[CURVE25519_BASE64_PADDED_LEN + 1];
3938 smartlist_add_asprintf(chunks, "ntor-onion-key %s\n", kbuf);
3939 }
3940
3941 if (family) {
3942 const uint8_t *id = (const uint8_t *)ri->cache_info.identity_digest;
3943 char *canonical_family = nodefamily_canonicalize(family, id, 0);
3944 smartlist_add_asprintf(chunks, "family %s\n", canonical_family);
3945 tor_free(canonical_family);
3946 }
3947
3948 if (consensus_method >= MIN_METHOD_FOR_FAMILY_IDS &&
3949 ri->family_ids && smartlist_len(ri->family_ids)) {
3950 char *family_ids = smartlist_join_strings(ri->family_ids, " ", 0, NULL);
3951 smartlist_add_asprintf(chunks, "family-ids %s\n", family_ids);
3952 tor_free(family_ids);
3953 }
3954
3955 if (summary && strcmp(summary, "reject 1-65535"))
3956 smartlist_add_asprintf(chunks, "p %s\n", summary);
3957
3958 if (ri->ipv6_exit_policy) {
3959 /* XXXX+++ This doesn't match proposal 208, which says these should
3960 * be taken unchanged from the routerinfo. That's bogosity, IMO:
3961 * the proposal should have said to do this instead.*/
3962 char *p6 = write_short_policy(ri->ipv6_exit_policy);
3963 if (p6 && strcmp(p6, "reject 1-65535"))
3964 smartlist_add_asprintf(chunks, "p6 %s\n", p6);
3965 tor_free(p6);
3966 }
3967
3968 {
3969 char idbuf[ED25519_BASE64_LEN+1];
3970 const char *keytype;
3971 if (ri->cache_info.signing_key_cert &&
3972 ri->cache_info.signing_key_cert->signing_key_included) {
3973 keytype = "ed25519";
3975 &ri->cache_info.signing_key_cert->signing_key);
3976 } else {
3977 keytype = "rsa1024";
3978 digest_to_base64(idbuf, ri->cache_info.identity_digest);
3979 }
3980 smartlist_add_asprintf(chunks, "id %s %s\n", keytype, idbuf);
3981 }
3982
3983 output = smartlist_join_strings(chunks, "", 0, NULL);
3984
3985 {
3987 output+strlen(output), 0,
3988 SAVED_NOWHERE, NULL);
3989 if (smartlist_len(lst) != 1) {
3990 log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
3991 SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
3992 smartlist_free(lst);
3993 goto done;
3994 }
3995 result = smartlist_get(lst, 0);
3996 smartlist_free(lst);
3997 }
3998
3999 done:
4000 crypto_pk_free(rsa_pubkey);
4001 tor_free(output);
4002 tor_free(key);
4003 tor_free(summary);
4004 tor_free(family);
4005 if (chunks) {
4006 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
4007 smartlist_free(chunks);
4008 }
4009 return result;
4010}
4011
4012/** Format the appropriate vote line to describe the microdescriptor <b>md</b>
4013 * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
4014 * in <b>out</b>. Return -1 on failure and the number of characters written
4015 * on success. */
4016static ssize_t
4017dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
4018 const microdesc_t *md,
4019 int consensus_method_low,
4020 int consensus_method_high)
4021{
4022 ssize_t ret = -1;
4023 char d64[BASE64_DIGEST256_LEN+1];
4024 char *microdesc_consensus_methods =
4025 make_consensus_method_list(consensus_method_low,
4026 consensus_method_high,
4027 ",");
4028 tor_assert(microdesc_consensus_methods);
4029
4030 digest256_to_base64(d64, md->digest);
4031
4032 if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
4033 microdesc_consensus_methods, d64)<0)
4034 goto out;
4035
4036 ret = strlen(out_buf);
4037
4038 out:
4039 tor_free(microdesc_consensus_methods);
4040 return ret;
4041}
4042
4043/** Array of start and end of consensus methods used for supported
4044 microdescriptor formats. */
4045static const struct consensus_method_range_t {
4046 int low;
4047 int high;
4048} microdesc_consensus_methods[] = {
4053 {-1, -1}
4054};
4055
4056/** Helper type used when generating the microdescriptor lines in a directory
4057 * vote. */
4059 int low;
4060 int high;
4061 microdesc_t *md;
4062 struct microdesc_vote_line_t *next;
4064
4065/** Generate and return a linked list of all the lines that should appear to
4066 * describe a router's microdescriptor versions in a directory vote.
4067 * Add the generated microdescriptors to <b>microdescriptors_out</b>. */
4070 smartlist_t *microdescriptors_out)
4071{
4072 const struct consensus_method_range_t *cmr;
4073 microdesc_vote_line_t *entries = NULL, *ep;
4074 vote_microdesc_hash_t *result = NULL;
4075
4076 /* Generate the microdescriptors. */
4077 for (cmr = microdesc_consensus_methods;
4078 cmr->low != -1 && cmr->high != -1;
4079 cmr++) {
4080 microdesc_t *md = dirvote_create_microdescriptor(ri, cmr->low);
4081 if (md) {
4083 tor_malloc_zero(sizeof(microdesc_vote_line_t));
4084 e->md = md;
4085 e->low = cmr->low;
4086 e->high = cmr->high;
4087 e->next = entries;
4088 entries = e;
4089 }
4090 }
4091
4092 /* Compress adjacent identical ones */
4093 for (ep = entries; ep; ep = ep->next) {
4094 while (ep->next &&
4095 fast_memeq(ep->md->digest, ep->next->md->digest, DIGEST256_LEN) &&
4096 ep->low == ep->next->high + 1) {
4097 microdesc_vote_line_t *next = ep->next;
4098 ep->low = next->low;
4099 microdesc_free(next->md);
4100 ep->next = next->next;
4101 tor_free(next);
4102 }
4103 }
4104
4105 /* Format them into vote_microdesc_hash_t, and add to microdescriptors_out.*/
4106 while ((ep = entries)) {
4107 char buf[128];
4109 if (dirvote_format_microdesc_vote_line(buf, sizeof(buf), ep->md,
4110 ep->low, ep->high) >= 0) {
4111 h = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
4112 h->microdesc_hash_line = tor_strdup(buf);
4113 h->next = result;
4114 result = h;
4115 ep->md->last_listed = now;
4116 smartlist_add(microdescriptors_out, ep->md);
4117 }
4118 entries = ep->next;
4119 tor_free(ep);
4120 }
4121
4122 return result;
4123}
4124
4125/** Parse and extract all SR commits from <b>tokens</b> and place them in
4126 * <b>ns</b>. */
4127static void
4129{
4130 smartlist_t *chunks = NULL;
4131
4132 tor_assert(ns);
4133 tor_assert(tokens);
4134 /* Commits are only present in a vote. */
4135 tor_assert(ns->type == NS_TYPE_VOTE);
4136
4137 ns->sr_info.commits = smartlist_new();
4138
4139 smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
4140 /* It's normal that a vote might contain no commits even if it participates
4141 * in the SR protocol. Don't treat it as an error. */
4142 if (commits == NULL) {
4143 goto end;
4144 }
4145
4146 /* Parse the commit. We do NO validation of number of arguments or ordering
4147 * for forward compatibility, it's the parse commit job to inform us if it's
4148 * supported or not. */
4149 chunks = smartlist_new();
4151 /* Extract all arguments and put them in the chunks list. */
4152 for (int i = 0; i < tok->n_args; i++) {
4153 smartlist_add(chunks, tok->args[i]);
4154 }
4155 sr_commit_t *commit = sr_parse_commit(chunks);
4156 smartlist_clear(chunks);
4157 if (commit == NULL) {
4158 /* Get voter identity so we can warn that this dirauth vote contains
4159 * commit we can't parse. */
4160 networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
4161 tor_assert(voter);
4162 log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
4163 escaped(tok->object_body),
4164 hex_str(voter->identity_digest,
4165 sizeof(voter->identity_digest)));
4166 /* Commitment couldn't be parsed. Continue onto the next commit because
4167 * this one could be unsupported for instance. */
4168 continue;
4169 }
4170 /* Add newly created commit object to the vote. */
4171 smartlist_add(ns->sr_info.commits, commit);
4172 } SMARTLIST_FOREACH_END(tok);
4173
4174 end:
4175 smartlist_free(chunks);
4176 smartlist_free(commits);
4177}
4178
4179/* Using the given directory tokens in tokens, parse the shared random commits
4180 * and put them in the given vote document ns.
4181 *
4182 * This also sets the SR participation flag if present in the vote. */
4183void
4184dirvote_parse_sr_commits(networkstatus_t *ns, const smartlist_t *tokens)
4185{
4186 /* Does this authority participates in the SR protocol? */
4187 directory_token_t *tok = find_opt_by_keyword(tokens, K_SR_FLAG);
4188 if (tok) {
4189 ns->sr_info.participate = 1;
4190 /* Get the SR commitments and reveals from the vote. */
4192 }
4193}
4194
4195/* For the given vote, free the shared random commits if any. */
4196void
4197dirvote_clear_commits(networkstatus_t *ns)
4198{
4199 tor_assert(ns->type == NS_TYPE_VOTE);
4200
4201 if (ns->sr_info.commits) {
4202 SMARTLIST_FOREACH(ns->sr_info.commits, sr_commit_t *, c,
4203 sr_commit_free(c));
4204 smartlist_free(ns->sr_info.commits);
4205 }
4206}
4207
4208/* The given url is the /tor/status-vote GET directory request. Populates the
4209 * items list with strings that we can compress on the fly and dir_items with
4210 * cached_dir_t objects that have a precompressed deflated version. */
4211void
4212dirvote_dirreq_get_status_vote(const char *url, smartlist_t *items,
4213 smartlist_t *dir_items)
4214{
4215 int current;
4216
4217 url += strlen("/tor/status-vote/");
4218 current = !strcmpstart(url, "current/");
4219 url = strchr(url, '/');
4220 tor_assert(url);
4221 ++url;
4222 if (!strcmp(url, "consensus")) {
4223 const char *item;
4224 tor_assert(!current); /* we handle current consensus specially above,
4225 * since it wants to be spooled. */
4226 if ((item = dirvote_get_pending_consensus(FLAV_NS)))
4227 smartlist_add(items, (char*)item);
4228 } else if (!current && !strcmp(url, "consensus-signatures")) {
4229 /* XXXX the spec says that we should implement
4230 * current/consensus-signatures too. It doesn't seem to be needed,
4231 * though. */
4232 const char *item;
4234 smartlist_add(items, (char*)item);
4235 } else if (!strcmp(url, "authority")) {
4236 const cached_dir_t *d;
4237 int flags = DGV_BY_ID |
4238 (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
4239 if ((d=dirvote_get_vote(NULL, flags)))
4240 smartlist_add(dir_items, (cached_dir_t*)d);
4241 } else {
4242 const cached_dir_t *d;
4243 smartlist_t *fps = smartlist_new();
4244 int flags;
4245 if (!strcmpstart(url, "d/")) {
4246 url += 2;
4247 flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
4248 } else {
4249 flags = DGV_BY_ID |
4250 (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
4251 }
4253 DSR_HEX|DSR_SORT_UNIQ);
4254 SMARTLIST_FOREACH(fps, char *, fp, {
4255 if ((d = dirvote_get_vote(fp, flags)))
4256 smartlist_add(dir_items, (cached_dir_t*)d);
4257 tor_free(fp);
4258 });
4259 smartlist_free(fps);
4260 }
4261}
4262
4263/** Get the best estimate of a router's bandwidth for dirauth purposes,
4264 * preferring measured to advertised values if available. */
4266 (const routerinfo_t *ri))
4267{
4268 uint32_t bw_kb = 0;
4269 /*
4270 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
4271 * signed) longs and the ones router_get_advertised_bandwidth() returns
4272 * are uint32_t.
4273 */
4274 long mbw_kb = 0;
4275
4276 if (ri) {
4277 /*
4278 * * First try to see if we have a measured bandwidth; don't bother with
4279 * as_of_out here, on the theory that a stale measured bandwidth is still
4280 * better to trust than an advertised one.
4281 */
4283 &mbw_kb, NULL)) {
4284 /* Got one! */
4285 bw_kb = (uint32_t)mbw_kb;
4286 } else {
4287 /* If not, fall back to advertised */
4288 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
4289 }
4290 }
4291
4292 return bw_kb;
4293}
4294
4295/**
4296 * Helper: compare the address of family `family` in `a` with the address in
4297 * `b`. The family must be one of `AF_INET` and `AF_INET6`.
4298 **/
4299static int
4301 const routerinfo_t *b,
4302 int family)
4303{
4304 const tor_addr_t *addr1 = (family==AF_INET) ? &a->ipv4_addr : &a->ipv6_addr;
4305 const tor_addr_t *addr2 = (family==AF_INET) ? &b->ipv4_addr : &b->ipv6_addr;
4306 return tor_addr_compare(addr1, addr2, CMP_EXACT);
4307}
4308
4309/** Helper for sorting: compares two ipv4 routerinfos first by ipv4 address,
4310 * and then by descending order of "usefulness"
4311 * (see compare_routerinfo_usefulness)
4312 **/
4313STATIC int
4314compare_routerinfo_by_ipv4(const void **a, const void **b)
4315{
4316 const routerinfo_t *first = *(const routerinfo_t **)a;
4317 const routerinfo_t *second = *(const routerinfo_t **)b;
4318 int comparison = compare_routerinfo_addrs_by_family(first, second, AF_INET);
4319 if (comparison == 0) {
4320 // If addresses are equal, use other comparison criteria
4321 return compare_routerinfo_usefulness(first, second);
4322 } else {
4323 return comparison;
4324 }
4325}
4326
4327/** Helper for sorting: compares two ipv6 routerinfos first by ipv6 address,
4328 * and then by descending order of "usefulness"
4329 * (see compare_routerinfo_usefulness)
4330 **/
4331STATIC int
4332compare_routerinfo_by_ipv6(const void **a, const void **b)
4333{
4334 const routerinfo_t *first = *(const routerinfo_t **)a;
4335 const routerinfo_t *second = *(const routerinfo_t **)b;
4336 int comparison = compare_routerinfo_addrs_by_family(first, second, AF_INET6);
4337 // If addresses are equal, use other comparison criteria
4338 if (comparison == 0)
4339 return compare_routerinfo_usefulness(first, second);
4340 else
4341 return comparison;
4342}
4343
4344/**
4345* Compare routerinfos by descending order of "usefulness" :
4346* An authority is more useful than a non-authority; a running router is
4347* more useful than a non-running router; and a router with more bandwidth
4348* is more useful than one with less.
4349**/
4350STATIC int
4352 const routerinfo_t *second)
4353{
4354 int first_is_auth, second_is_auth;
4355 const node_t *node_first, *node_second;
4356 int first_is_running, second_is_running;
4357 uint32_t bw_kb_first, bw_kb_second;
4358 /* Potentially, this next bit could cause k n lg n memeq calls. But in
4359 * reality, we will almost never get here, since addresses will usually be
4360 * different. */
4361 first_is_auth =
4362 router_digest_is_trusted_dir(first->cache_info.identity_digest);
4363 second_is_auth =
4364 router_digest_is_trusted_dir(second->cache_info.identity_digest);
4365
4366 if (first_is_auth && !second_is_auth)
4367 return -1;
4368 else if (!first_is_auth && second_is_auth)
4369 return 1;
4370
4371 node_first = node_get_by_id(first->cache_info.identity_digest);
4372 node_second = node_get_by_id(second->cache_info.identity_digest);
4373 first_is_running = node_first && node_first->is_running;
4374 second_is_running = node_second && node_second->is_running;
4375 if (first_is_running && !second_is_running)
4376 return -1;
4377 else if (!first_is_running && second_is_running)
4378 return 1;
4379
4380 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
4381 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
4382
4383 if (bw_kb_first > bw_kb_second)
4384 return -1;
4385 else if (bw_kb_first < bw_kb_second)
4386 return 1;
4387
4388 /* They're equal! Compare by identity digest, so there's a
4389 * deterministic order and we avoid flapping. */
4390 return fast_memcmp(first->cache_info.identity_digest,
4391 second->cache_info.identity_digest,
4392 DIGEST_LEN);
4393}
4394
4395/** Given a list of routerinfo_t in <b>routers</b> that all use the same
4396 * IP version, specified in <b>family</b>, return a new digestmap_t whose keys
4397 * are the identity digests of those routers that we're going to exclude for
4398 * Sybil-like appearance.
4399 */
4400STATIC digestmap_t *
4402{
4403 const dirauth_options_t *options = dirauth_get_options();
4404 digestmap_t *omit_as_sybil = digestmap_new();
4405 smartlist_t *routers_by_ip = smartlist_new();
4406 int addr_count = 0;
4407 routerinfo_t *last_ri = NULL;
4408 /* Allow at most this number of Tor servers on a single IP address, ... */
4409 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
4410 if (max_with_same_addr <= 0)
4411 max_with_same_addr = INT_MAX;
4412
4413 smartlist_add_all(routers_by_ip, routers);
4414 if (family == AF_INET6)
4416 else
4418
4419 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
4420 bool addrs_equal;
4421 if (last_ri)
4422 addrs_equal = !compare_routerinfo_addrs_by_family(last_ri, ri, family);
4423 else
4424 addrs_equal = false;
4425
4426 if (! addrs_equal) {
4427 last_ri = ri;
4428 addr_count = 1;
4429 } else if (++addr_count > max_with_same_addr) {
4430 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
4431 }
4432 } SMARTLIST_FOREACH_END(ri);
4433 smartlist_free(routers_by_ip);
4434 return omit_as_sybil;
4435}
4436
4437/** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
4438 * whose keys are the identity digests of those routers that we're going to
4439 * exclude for Sybil-like appearance. */
4440STATIC digestmap_t *
4442{
4443 smartlist_t *routers_ipv6, *routers_ipv4;
4444 routers_ipv6 = smartlist_new();
4445 routers_ipv4 = smartlist_new();
4446 digestmap_t *omit_as_sybil_ipv4;
4447 digestmap_t *omit_as_sybil_ipv6;
4448 digestmap_t *omit_as_sybil = digestmap_new();
4449 // Sort the routers in two lists depending on their IP version
4450 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
4451 // If the router has an IPv6 address
4452 if (tor_addr_family(&(ri->ipv6_addr)) == AF_INET6) {
4453 smartlist_add(routers_ipv6, ri);
4454 }
4455 // If the router has an IPv4 address
4456 if (tor_addr_family(&(ri->ipv4_addr)) == AF_INET) {
4457 smartlist_add(routers_ipv4, ri);
4458 }
4459 } SMARTLIST_FOREACH_END(ri);
4460 omit_as_sybil_ipv4 = get_sybil_list_by_ip_version(routers_ipv4, AF_INET);
4461 omit_as_sybil_ipv6 = get_sybil_list_by_ip_version(routers_ipv6, AF_INET6);
4462
4463 // Add all possible sybils to the common digestmap
4464 DIGESTMAP_FOREACH (omit_as_sybil_ipv4, sybil_id, routerinfo_t *, ri) {
4465 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
4467 DIGESTMAP_FOREACH (omit_as_sybil_ipv6, sybil_id, routerinfo_t *, ri) {
4468 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
4470 // Clean the temp variables
4471 smartlist_free(routers_ipv4);
4472 smartlist_free(routers_ipv6);
4473 digestmap_free(omit_as_sybil_ipv4, NULL);
4474 digestmap_free(omit_as_sybil_ipv6, NULL);
4475 // Return the digestmap: it now contains all the possible sybils
4476 return omit_as_sybil;
4477}
4478
4479/** Given a platform string as in a routerinfo_t (possibly null), return a
4480 * newly allocated version string for a networkstatus document, or NULL if the
4481 * platform doesn't give a Tor version. */
4482static char *
4483version_from_platform(const char *platform)
4484{
4485 if (platform && !strcmpstart(platform, "Tor ")) {
4486 const char *eos = find_whitespace(platform+4);
4487 if (eos && !strcmpstart(eos, " (r")) {
4488 /* XXXX Unify this logic with the other version extraction
4489 * logic in routerparse.c. */
4490 eos = find_whitespace(eos+1);
4491 }
4492 if (eos) {
4493 return tor_strndup(platform, eos-platform);
4494 }
4495 }
4496 return NULL;
4497}
4498
4499/** Given a (possibly empty) list of config_line_t, each line of which contains
4500 * a list of comma-separated version numbers surrounded by optional space,
4501 * allocate and return a new string containing the version numbers, in order,
4502 * separated by commas. Used to generate Recommended(Client|Server)?Versions
4503 */
4504char *
4506{
4507 smartlist_t *versions;
4508 char *result;
4509 versions = smartlist_new();
4510 for ( ; ln; ln = ln->next) {
4511 smartlist_split_string(versions, ln->value, ",",
4512 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4513 }
4514
4515 /* Handle the case where a dirauth operator has accidentally made some
4516 * versions space-separated instead of comma-separated. */
4517 smartlist_t *more_versions = smartlist_new();
4518 SMARTLIST_FOREACH_BEGIN(versions, char *, v) {
4519 if (strchr(v, ' ')) {
4520 if (warn)
4521 log_warn(LD_DIRSERV, "Unexpected space in versions list member %s. "
4522 "(These are supposed to be comma-separated; I'll pretend you "
4523 "used commas instead.)", escaped(v));
4524 SMARTLIST_DEL_CURRENT(versions, v);
4525 smartlist_split_string(more_versions, v, NULL,
4526 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4527 tor_free(v);
4528 }
4529 } SMARTLIST_FOREACH_END(v);
4530 smartlist_add_all(versions, more_versions);
4531 smartlist_free(more_versions);
4532
4533 /* Check to make sure everything looks like a version. */
4534 if (warn) {
4535 SMARTLIST_FOREACH_BEGIN(versions, const char *, v) {
4536 tor_version_t ver;
4537 if (tor_version_parse(v, &ver) < 0) {
4538 log_warn(LD_DIRSERV, "Recommended version %s does not look valid. "
4539 " (I'll include it anyway, since you told me to.)",
4540 escaped(v));
4541 }
4542 } SMARTLIST_FOREACH_END(v);
4543 }
4544
4545 sort_version_list(versions, 1);
4546 result = smartlist_join_strings(versions,",",0,NULL);
4547 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
4548 smartlist_free(versions);
4549 return result;
4550}
4551
4552/** If there are entries in <b>routers</b> with exactly the same ed25519 keys,
4553 * remove the older one. If they are exactly the same age, remove the one
4554 * with the greater descriptor digest. May alter the order of the list. */
4555static void
4557{
4558 routerinfo_t *ri2;
4559 digest256map_t *by_ed_key = digest256map_new();
4560
4561 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
4562 ri->omit_from_vote = 0;
4563 if (ri->cache_info.signing_key_cert == NULL)
4564 continue; /* No ed key */
4565 const uint8_t *pk = ri->cache_info.signing_key_cert->signing_key.pubkey;
4566 if ((ri2 = digest256map_get(by_ed_key, pk))) {
4567 /* Duplicate; must omit one. Set the omit_from_vote flag in whichever
4568 * one has the earlier published_on. */
4569 const time_t ri_pub = ri->cache_info.published_on;
4570 const time_t ri2_pub = ri2->cache_info.published_on;
4571 if (ri2_pub < ri_pub ||
4572 (ri2_pub == ri_pub &&
4573 fast_memcmp(ri->cache_info.signed_descriptor_digest,
4574 ri2->cache_info.signed_descriptor_digest,DIGEST_LEN)<0)) {
4575 digest256map_set(by_ed_key, pk, ri);
4576 ri2->omit_from_vote = 1;
4577 } else {
4578 ri->omit_from_vote = 1;
4579 }
4580 } else {
4581 /* Add to map */
4582 digest256map_set(by_ed_key, pk, ri);
4583 }
4584 } SMARTLIST_FOREACH_END(ri);
4585
4586 digest256map_free(by_ed_key, NULL);
4587
4588 /* Now remove every router where the omit_from_vote flag got set. */
4589 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
4590 if (ri->omit_from_vote) {
4591 SMARTLIST_DEL_CURRENT(routers, ri);
4592 }
4593 } SMARTLIST_FOREACH_END(ri);
4594}
4595
4596/** Routerstatus <b>rs</b> is part of a group of routers that are on too
4597 * narrow an IP-space. Clear out its flags since we don't want it be used
4598 * because of its Sybil-like appearance.
4599 *
4600 * Leave its BadExit flag alone though, since if we think it's a bad exit,
4601 * we want to vote that way in case all the other authorities are voting
4602 * Running and Exit.
4603 *
4604 * Also set the Sybil flag in order to let a relay operator know that's
4605 * why their relay hasn't been voted on.
4606 */
4607static void
4609{
4610 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
4611 rs->is_flagged_running = rs->is_named = rs->is_valid =
4612 rs->is_hs_dir = rs->is_v2_dir = rs->is_possible_guard = 0;
4613 rs->is_sybil = 1;
4614 /* FFFF we might want some mechanism to check later on if we
4615 * missed zeroing any flags: it's easy to add a new flag but
4616 * forget to add it to this clause. */
4617}
4618
4619/** Space-separated list of all the flags that we will always vote on. */
4621 "Authority "
4622 "Exit "
4623 "Fast "
4624 "Guard "
4625 "HSDir "
4626 "Stable "
4627 "StaleDesc "
4628 "Sybil "
4629 "V2Dir "
4630 "Valid";
4631/** Space-separated list of all flags that we may or may not vote on,
4632 * depending on our configuration. */
4634 "BadExit "
4635 "MiddleOnly "
4636 "Running";
4637
4638/** Return a new networkstatus_t* containing our current opinion. (For v3
4639 * authorities) */
4642 authority_cert_t *cert)
4643{
4644 const or_options_t *options = get_options();
4645 const dirauth_options_t *d_options = dirauth_get_options();
4646 networkstatus_t *v3_out = NULL;
4647 tor_addr_t addr;
4648 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
4649 const char *contact;
4650 smartlist_t *routers, *routerstatuses;
4651 char identity_digest[DIGEST_LEN];
4652 char signing_key_digest[DIGEST_LEN];
4653 const int list_bad_exits = d_options->AuthDirListBadExits;
4654 const int list_middle_only = d_options->AuthDirListMiddleOnly;
4656 time_t now = time(NULL);
4657 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
4658 networkstatus_voter_info_t *voter = NULL;
4659 vote_timing_t timing;
4660 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
4661 smartlist_t *microdescriptors = NULL;
4662 smartlist_t *bw_file_headers = NULL;
4663 uint8_t bw_file_digest256[DIGEST256_LEN] = {0};
4664
4665 tor_assert(private_key);
4666 tor_assert(cert);
4667
4668 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
4669 log_err(LD_BUG, "Error computing signing key digest");
4670 return NULL;
4671 }
4672 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
4673 log_err(LD_BUG, "Error computing identity key digest");
4674 return NULL;
4675 }
4676 if (!find_my_address(options, AF_INET, LOG_WARN, &addr, NULL, &hostname)) {
4677 log_warn(LD_NET, "Couldn't resolve my hostname");
4678 return NULL;
4679 }
4680 if (!hostname || !strchr(hostname, '.')) {
4681 tor_free(hostname);
4682 hostname = tor_addr_to_str_dup(&addr);
4683 }
4684
4685 if (!hostname) {
4686 log_err(LD_BUG, "Failed to determine hostname AND duplicate address");
4687 return NULL;
4688 }
4689
4690 if (d_options->VersioningAuthoritativeDirectory) {
4691 client_versions =
4693 server_versions =
4695 }
4696
4697 contact = get_options()->ContactInfo;
4698 if (!contact)
4699 contact = "(none)";
4700
4701 /*
4702 * Do this so dirserv_compute_performance_thresholds() and
4703 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
4704 */
4705 if (options->V3BandwidthsFile) {
4707 NULL);
4708 } else {
4709 /*
4710 * No bandwidths file; clear the measured bandwidth cache in case we had
4711 * one last time around.
4712 */
4715 }
4716 }
4717
4718 /* precompute this part, since we need it to decide what "stable"
4719 * means. */
4721 dirserv_set_router_is_running(ri, now);
4722 });
4723
4724 routers = smartlist_new();
4725 smartlist_add_all(routers, rl->routers);
4727 /* After this point, don't use rl->routers; use 'routers' instead. */
4728 routers_sort_by_identity(routers);
4729 /* Get a digestmap of possible sybil routers, IPv4 or IPv6 */
4730 digestmap_t *omit_as_sybil = get_all_possible_sybil(routers);
4731 DIGESTMAP_FOREACH (omit_as_sybil, sybil_id, void *, ignore) {
4732 (void)ignore;
4733 rep_hist_make_router_pessimal(sybil_id, now);
4735 /* Count how many have measured bandwidths so we know how to assign flags;
4736 * this must come before dirserv_compute_performance_thresholds() */
4739 routerstatuses = smartlist_new();
4740 microdescriptors = smartlist_new();
4741
4742 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
4743 /* If it has a protover list and contains a protocol name greater than
4744 * MAX_PROTOCOL_NAME_LENGTH, skip it. */
4745 if (ri->protocol_list &&
4746 protover_list_is_invalid(ri->protocol_list)) {
4747 continue;
4748 }
4749 if (ri->cache_info.published_on >= cutoff) {
4750 routerstatus_t *rs;
4752 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
4753 if (!node)
4754 continue;
4755
4756 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
4757 rs = &vrs->status;
4759 list_bad_exits,
4760 list_middle_only);
4761 vrs->published_on = ri->cache_info.published_on;
4762
4763 if (ri->cache_info.signing_key_cert) {
4764 memcpy(vrs->ed25519_id,
4765 ri->cache_info.signing_key_cert->signing_key.pubkey,
4767 }
4768 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
4770
4771 if (!vote_on_reachability)
4772 rs->is_flagged_running = 0;
4773
4774 vrs->version = version_from_platform(ri->platform);
4775 if (ri->protocol_list) {
4776 vrs->protocols = tor_strdup(ri->protocol_list);
4777 } else {
4778 vrs->protocols = tor_strdup(
4780 }
4782 microdescriptors);
4783
4784 smartlist_add(routerstatuses, vrs);
4785 }
4786 } SMARTLIST_FOREACH_END(ri);
4787
4788 {
4789 smartlist_t *added =
4791 microdescriptors, SAVED_NOWHERE, 0);
4792 smartlist_free(added);
4793 smartlist_free(microdescriptors);
4794 }
4795
4796 smartlist_free(routers);
4797 digestmap_free(omit_as_sybil, NULL);
4798
4799 /* Apply guardfraction information to routerstatuses. */
4800 if (options->GuardfractionFile) {
4801 dirserv_read_guardfraction_file(options->GuardfractionFile,
4802 routerstatuses);
4803 }
4804
4805 /* This pass through applies the measured bw lines to the routerstatuses */
4806 if (options->V3BandwidthsFile) {
4807 /* Only set bw_file_headers when V3BandwidthsFile is configured */
4808 bw_file_headers = smartlist_new();
4810 routerstatuses, bw_file_headers,
4811 bw_file_digest256);
4812 } else {
4813 /*
4814 * No bandwidths file; clear the measured bandwidth cache in case we had
4815 * one last time around.
4816 */
4819 }
4820 }
4821
4822 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
4823
4824 v3_out->type = NS_TYPE_VOTE;
4826 v3_out->published = now;
4827 {
4828 char tbuf[ISO_TIME_LEN+1];
4829 networkstatus_t *current_consensus =
4831 long last_consensus_interval; /* only used to pick a valid_after */
4832 if (current_consensus)
4833 last_consensus_interval = current_consensus->fresh_until -
4834 current_consensus->valid_after;
4835 else
4836 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
4837 v3_out->valid_after =
4839 (int)last_consensus_interval,
4841 format_iso_time(tbuf, v3_out->valid_after);
4842 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
4843 "consensus_set=%d, last_interval=%d",
4844 tbuf, current_consensus?1:0, (int)last_consensus_interval);
4845 }
4846 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
4847 v3_out->valid_until = v3_out->valid_after +
4848 (timing.vote_interval * timing.n_intervals_valid);
4849 v3_out->vote_seconds = timing.vote_delay;
4850 v3_out->dist_seconds = timing.dist_delay;
4851 tor_assert(v3_out->vote_seconds > 0);
4852 tor_assert(v3_out->dist_seconds > 0);
4853 tor_assert(timing.n_intervals_valid > 0);
4854
4855 v3_out->client_versions = client_versions;
4856 v3_out->server_versions = server_versions;
4857
4860 v3_out->recommended_client_protocols =
4862 v3_out->required_client_protocols =
4864 v3_out->required_relay_protocols =
4866
4867 /* We are not allowed to vote to require anything we don't have. */
4868 tor_assert(protover_all_supported(v3_out->required_relay_protocols, NULL));
4869 tor_assert(protover_all_supported(v3_out->required_client_protocols, NULL));
4870
4871 /* We should not recommend anything we don't have. */
4872 tor_assert_nonfatal(protover_all_supported(
4873 v3_out->recommended_relay_protocols, NULL));
4874 tor_assert_nonfatal(protover_all_supported(
4875 v3_out->recommended_client_protocols, NULL));
4876
4877 v3_out->known_flags = smartlist_new();
4880 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4881 if (vote_on_reachability)
4882 smartlist_add_strdup(v3_out->known_flags, "Running");
4883 if (list_bad_exits)
4884 smartlist_add_strdup(v3_out->known_flags, "BadExit");
4885 if (list_middle_only)
4886 smartlist_add_strdup(v3_out->known_flags, "MiddleOnly");
4888
4889 if (d_options->ConsensusParams) {
4890 config_line_t *paramline = d_options->ConsensusParams;
4891 v3_out->net_params = smartlist_new();
4892 for ( ; paramline; paramline = paramline->next) {
4894 paramline->value, NULL, 0, 0);
4895 }
4896
4897 /* for transparency and visibility, include our current value of
4898 * AuthDirMaxServersPerAddr in our consensus params. Once enough dir
4899 * auths do this, external tools should be able to use that value to
4900 * help understand which relays are allowed into the consensus. */
4901 smartlist_add_asprintf(v3_out->net_params, "AuthDirMaxServersPerAddr=%d",
4902 d_options->AuthDirMaxServersPerAddr);
4903
4905 }
4906 v3_out->bw_file_headers = bw_file_headers;
4907 memcpy(v3_out->bw_file_digest256, bw_file_digest256, DIGEST256_LEN);
4908
4909 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
4910 voter->nickname = tor_strdup(options->Nickname);
4911 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
4912 voter->sigs = smartlist_new();
4913 voter->address = hostname;
4914 tor_addr_copy(&voter->ipv4_addr, &addr);
4915 voter->ipv4_dirport = routerconf_find_dir_port(options, 0);
4916 voter->ipv4_orport = routerconf_find_or_port(options, AF_INET);
4917 voter->contact = tor_strdup(contact);
4918 if (options->V3AuthUseLegacyKey) {
4920 if (c) {
4922 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
4923 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
4924 }
4925 }
4926 }
4927
4928 v3_out->voters = smartlist_new();
4929 smartlist_add(v3_out->voters, voter);
4930 v3_out->cert = authority_cert_dup(cert);
4931 v3_out->routerstatus_list = routerstatuses;
4932 /* Note: networkstatus_digest is unset; it won't get set until we actually
4933 * format the vote. */
4934
4935 return v3_out;
4936}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition address.c:933
tor_addr_port_t * tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
Definition address.c:2100
int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, tor_addr_comparison_t how)
Definition address.c:984
int tor_addr_is_null(const tor_addr_t *addr)
Definition address.c:780
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition address.c:1164
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition address.c:1199
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition address.h:187
#define fmt_addr(a)
Definition address.h:239
int trusted_dirs_load_certs_from_string(const char *contents, int source, int flush, const char *source_dir)
Definition authcert.c:373
authority_cert_t * authority_cert_get_by_digests(const char *id_digest, const char *sk_digest)
Definition authcert.c:648
Header file for authcert.c.
Header file for directory authority mode.
Authority certificate structure.
const char * hex_str(const char *from, size_t fromlen)
Definition binascii.c:34
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition binascii.c:215
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition binascii.c:478
int dirserv_get_measured_bw_cache_size(void)
Definition bwauth.c:166
int dirserv_read_measured_bandwidths(const char *from_file, smartlist_t *routerstatuses, smartlist_t *bw_file_headers, uint8_t *digest_out)
Definition bwauth.c:232
void dirserv_count_measured_bws(const smartlist_t *routers)
Definition bwauth.c:39
int dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out, time_t *as_of_out)
Definition bwauth.c:138
void dirserv_clear_measured_bw_cache(void)
Definition bwauth.c:103
Header file for bwauth.c.
#define MAX_BW_FILE_HEADER_COUNT_IN_VOTE
Definition bwauth.h:16
Cached large directory object structure.
const char * name
Definition config.c:2472
const or_options_t * get_options(void)
Definition config.c:948
Header file for config.c.
Header for confline.c.
void curve25519_public_to_base64(char *output, const curve25519_public_key_t *pkey, bool pad)
const char * crypto_digest_algorithm_get_name(digest_algorithm_t alg)
#define BASE64_DIGEST256_LEN
#define HEX_DIGEST256_LEN
digest_algorithm_t
#define HEX_DIGEST_LEN
#define N_COMMON_DIGEST_ALGORITHMS
void digest256_to_base64(char *d64, const char *digest)
void ed25519_public_to_base64(char *output, const ed25519_public_key_t *pkey)
int digest256_from_base64(char *digest, const char *d64)
void digest_to_base64(char *d64, const char *digest)
Header for crypto_format.c.
int crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
Definition crypto_rsa.c:229
int crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest, size_t *len)
Definition crypto_rsa.c:466
int crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
Definition crypto_rsa.c:356
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
#define FINGERPRINT_LEN
Definition crypto_rsa.h:34
#define fast_memeq(a, b, c)
Definition di_ops.h:35
#define fast_memcmp(a, b, c)
Definition di_ops.h:28
#define DIGEST_LEN
#define DIGEST256_LEN
Trusted/fallback directory server structure.
Structure dirauth_options_t to hold directory authority options.
Header for dirauth_sys.c.
void directory_get_from_all_authorities(uint8_t dir_purpose, uint8_t router_purpose, const char *resource)
Definition dirclient.c:585
void directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose, dirinfo_type_t type, const char *payload, size_t payload_len, size_t extrainfo_len)
Definition dirclient.c:229
Header file for dirclient.c.
int dircollator_n_routers(dircollator_t *dc)
Definition dircollate.c:305
dircollator_t * dircollator_new(int n_votes, int n_authorities)
Definition dircollate.c:149
void dircollator_collate(dircollator_t *dc, int consensus_method)
Definition dircollate.c:211
void dircollator_add_vote(dircollator_t *dc, networkstatus_t *v)
Definition dircollate.c:194
vote_routerstatus_t ** dircollator_get_votes_for_router(dircollator_t *dc, int idx)
Definition dircollate.c:320
Header file for dircollate.c.
int dir_split_resource_into_fingerprints(const char *resource, smartlist_t *fp_out, int *compressed_out, int flags)
Definition directory.c:684
Header file for directory.c.
#define DIR_PURPOSE_UPLOAD_VOTE
Definition directory.h:43
#define DIR_PURPOSE_FETCH_DETACHED_SIGNATURES
Definition directory.h:51
#define DIR_PURPOSE_UPLOAD_SIGNATURES
Definition directory.h:45
#define DIR_PURPOSE_FETCH_STATUS_VOTE
Definition directory.h:48
int get_n_authorities(dirinfo_type_t type)
Definition dirlist.c:103
dir_server_t * trusteddirserver_get_by_v3_auth_digest(const char *digest)
Definition dirlist.c:215
Header file for dirlist.c.
void cached_dir_decref(cached_dir_t *d)
Definition dirserv.c:125
cached_dir_t * new_cached_dir(char *s, time_t published)
Definition dirserv.c:136
Header file for dirserv.c.
static char * networkstatus_format_signatures(networkstatus_t *consensus, int for_detached_signatures)
Definition dirvote.c:2707
STATIC microdesc_t * dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
Definition dirvote.c:3912
static int dirvote_add_signatures_to_all_pending_consensuses(const char *detached_signatures_body, const char *source, const char **msg_out)
Definition dirvote.c:3698
static void dirvote_fetch_missing_signatures(void)
Definition dirvote.c:3069
static void dirvote_clear_pending_consensuses(void)
Definition dirvote.c:3092
STATIC int compare_routerinfo_usefulness(const routerinfo_t *first, const routerinfo_t *second)
Definition dirvote.c:4351
static int cmp_int_strings_(const void **_a, const void **_b)
Definition dirvote.c:777
networkstatus_t * dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key, authority_cert_t *cert)
Definition dirvote.c:4641
static void export_consensus_for_transparency(const char *flavor_name)
Definition dirvote.c:3580
pending_vote_t * dirvote_add_vote(const char *vote_body, time_t time_posted, const char *where_from, const char **msg_out, int *status_out)
Definition dirvote.c:3201
static int consensus_method_is_supported(int method)
Definition dirvote.c:831
static vote_routerstatus_t * compute_routerstatus_consensus(smartlist_t *votes, int consensus_method, char *microdesc_digest256_out, tor_addr_port_t *best_alt_orport_out)
Definition dirvote.c:680
char * format_recommended_version_list(const config_line_t *ln, int warn)
Definition dirvote.c:4505
static void get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
Definition dirvote.c:581
static bw_weights_error_t networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg, int64_t Wme, int64_t Wmd, int64_t Wee, int64_t Wed, int64_t scale, int64_t G, int64_t M, int64_t E, int64_t D, int64_t T, int64_t margin, int do_balance)
Definition dirvote.c:1032
static void remove_flag(smartlist_t *sl, const char *flag)
Definition dirvote.c:1491
static int compare_routerinfo_addrs_by_family(const routerinfo_t *a, const routerinfo_t *b, int family)
Definition dirvote.c:4300
STATIC authority_cert_t * authority_cert_dup(authority_cert_t *cert)
Definition dirvote.c:149
STATIC int compare_routerinfo_by_ipv6(const void **a, const void **b)
Definition dirvote.c:4332
static int dirvote_perform_vote(void)
Definition dirvote.c:2981
STATIC char * make_consensus_method_list(int low, int high, const char *separator)
Definition dirvote.c:840
static int compare_orports_(const void **_a, const void **_b)
Definition dirvote.c:661
STATIC digestmap_t * get_all_possible_sybil(const smartlist_t *routers)
Definition dirvote.c:4441
static char * format_protocols_lines_for_vote(const networkstatus_t *v3_ns)
Definition dirvote.c:187
static void extract_shared_random_commits(networkstatus_t *ns, const smartlist_t *tokens)
Definition dirvote.c:4128
time_t dirvote_act(const or_options_t *options, time_t now)
Definition dirvote.c:2878
const cached_dir_t * dirvote_get_vote(const char *fp, int flags)
Definition dirvote.c:3866
static void dirvote_clear_votes(int all_votes)
Definition dirvote.c:3106
static char * compute_nth_protocol_set(int n, int n_voters, const smartlist_t *votes)
Definition dirvote.c:1443
static char * pending_consensus_signatures
Definition dirvote.c:2972
STATIC char * format_networkstatus_vote(crypto_pk_t *private_signing_key, networkstatus_t *v3_ns)
Definition dirvote.c:226
STATIC int32_t dirvote_get_intermediate_param_value(const smartlist_t *param_list, const char *keyword, int32_t default_val)
Definition dirvote.c:889
const char * dirvote_get_pending_consensus(consensus_flavor_t flav)
Definition dirvote.c:3843
static int dirvote_publish_consensus(void)
Definition dirvote.c:3790
static const char * get_nth_protocol_set_vote(int n, const networkstatus_t *vote)
Definition dirvote.c:1425
void dirvote_free_all(void)
Definition dirvote.c:3819
static int compare_votes_by_authority_id_(const void **_a, const void **_b)
Definition dirvote.c:555
STATIC smartlist_t * dirvote_compute_params(smartlist_t *votes, int method, int total_authorities)
Definition dirvote.c:925
static char * version_from_platform(const char *platform)
Definition dirvote.c:4483
static int vote_routerstatus_find_microdesc_hash(char *digest256_out, const vote_routerstatus_t *vrs, int method, digest_algorithm_t alg)
Definition dirvote.c:488
static int compare_vote_rs_(const void **_a, const void **_b)
Definition dirvote.c:653
int dirvote_add_signatures(const char *detached_signatures_body, const char *source, const char **msg)
Definition dirvote.c:3766
static void dirvote_fetch_missing_votes(void)
Definition dirvote.c:3029
STATIC char * networkstatus_get_detached_signatures(smartlist_t *consensuses)
Definition dirvote.c:2768
static char * compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
Definition dirvote.c:864
static char * get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending, int n_flavors)
Definition dirvote.c:2857
uint32_t dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
Definition dirvote.c:4266
static void routers_make_ed_keys_unique(smartlist_t *routers)
Definition dirvote.c:4556
static void dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
Definition dirvote.c:468
int networkstatus_compute_bw_weights_v10(smartlist_t *chunks, int64_t G, int64_t M, int64_t E, int64_t D, int64_t T, int64_t weight_scale)
Definition dirvote.c:1101
static char * list_v3_auth_ids(void)
Definition dirvote.c:3148
#define get_most_frequent_member(lst)
Definition dirvote.c:601
STATIC int networkstatus_add_detached_signatures(networkstatus_t *target, ns_detached_signatures_t *sigs, const char *source, int severity, const char **msg_out)
Definition dirvote.c:2576
static smartlist_t * pending_vote_list
Definition dirvote.c:2962
static int dirvote_add_signatures_to_pending_consensus(pending_consensus_t *pc, ns_detached_signatures_t *sigs, const char *source, int severity, const char **msg_out)
Definition dirvote.c:3603
const char DIRVOTE_OPTIONAL_FLAGS[]
Definition dirvote.c:4633
STATIC char * compute_consensus_package_lines(smartlist_t *votes)
Definition dirvote.c:2495
#define MIN_VOTES_FOR_PARAM
Definition dirvote.c:919
STATIC digestmap_t * get_sybil_list_by_ip_version(const smartlist_t *routers, sa_family_t family)
Definition dirvote.c:4401
static smartlist_t * pending_consensus_signature_list
Definition dirvote.c:2976
static void clear_status_flags_on_sybil(routerstatus_t *rs)
Definition dirvote.c:4608
const char * dirvote_get_pending_detached_signatures(void)
Definition dirvote.c:3852
static ssize_t dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len, const microdesc_t *md, int consensus_method_low, int consensus_method_high)
Definition dirvote.c:4017
static int dirvote_compute_consensuses(void)
Definition dirvote.c:3405
static int compute_consensus_method(smartlist_t *votes)
Definition dirvote.c:796
static void update_total_bandwidth_weights(const routerstatus_t *rs, int is_exit, int is_guard, int64_t *G, int64_t *M, int64_t *E, int64_t *D, int64_t *T)
Definition dirvote.c:1341
STATIC int compare_routerinfo_by_ipv4(const void **a, const void **b)
Definition dirvote.c:4314
static smartlist_t * previous_vote_list
Definition dirvote.c:2965
static int compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
Definition dirvote.c:608
static int compare_dir_src_ents_by_authority_id_(const void **_a, const void **_b)
Definition dirvote.c:566
const char DIRVOTE_UNIVERSAL_FLAGS[]
Definition dirvote.c:4620
vote_microdesc_hash_t * dirvote_format_all_microdesc_vote_lines(const routerinfo_t *ri, time_t now, smartlist_t *microdescriptors_out)
Definition dirvote.c:4069
STATIC char * networkstatus_compute_consensus(smartlist_t *votes, int total_authorities, crypto_pk_t *identity_key, crypto_pk_t *signing_key, const char *legacy_id_key_digest, crypto_pk_t *legacy_signing_key, consensus_flavor_t flavor)
Definition dirvote.c:1521
static networkstatus_voter_info_t * get_voter(const networkstatus_t *vote)
Definition dirvote.c:534
Header file for dirvote.c.
#define MIN_VOTE_INTERVAL_TESTING
Definition dirvote.h:46
#define MIN_VOTE_INTERVAL
Definition dirvote.h:37
#define MIN_METHOD_TO_SUPPRESS_MD_PUBLISHED
Definition dirvote.h:62
#define MIN_SUPPORTED_CONSENSUS_METHOD
Definition dirvote.h:53
#define MIN_METHOD_FOR_FAMILY_IDS
Definition dirvote.h:74
#define MIN_METHOD_TO_OMIT_PACKAGE_FINGERPRINTS
Definition dirvote.h:68
#define DEFAULT_MAX_UNMEASURED_BW_KB
Definition dirvote.h:79
#define MAX_BW_FILE_HEADERS_LINE_LEN
Definition dirvote.h:87
#define MIN_DIST_SECONDS
Definition dirvote.h:32
#define MIN_VOTE_SECONDS
Definition dirvote.h:27
#define MAX_SUPPORTED_CONSENSUS_METHOD
Definition dirvote.h:56
Authority signature structure.
Code to parse and validate detached-signature objects.
Header file for circuitbuild.c.
const char * escaped(const char *s)
Definition escape.c:126
Format routerstatus entries for controller, vote, or consensus.
routerstatus_format_type_t
@ NS_V3_VOTE
@ NS_V3_CONSENSUS
@ NS_V3_CONSENSUS_MICRODESC
Header file for guardfraction.c.
uint16_t sa_family_t
Definition inaddr_st.h:77
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition log.c:591
#define log_fn(severity, domain, args,...)
Definition log.h:283
#define LD_DIRSERV
Definition log.h:90
#define LD_BUG
Definition log.h:86
#define LD_NET
Definition log.h:66
#define LD_DIR
Definition log.h:88
#define LOG_NOTICE
Definition log.h:50
#define LD_CIRC
Definition log.h:82
#define LOG_WARN
Definition log.h:53
#define LOG_INFO
Definition log.h:45
void tor_free_(void *mem)
Definition malloc.c:227
#define tor_free(p)
Definition malloc.h:56
void * strmap_get_lc(const strmap_t *map, const char *key)
Definition map.c:360
void * strmap_set_lc(strmap_t *map, const char *key, void *val)
Definition map.c:346
#define DIGESTMAP_FOREACH_END
Definition map.h:168
#define DIGESTMAP_FOREACH(map, keyvar, valtype, valvar)
Definition map.h:154
smartlist_t * microdescs_add_list_to_cache(microdesc_cache_t *cache, smartlist_t *descriptors, saved_location_t where, int no_save)
Definition microdesc.c:383
microdesc_cache_t * get_microdesc_cache(void)
Definition microdesc.c:251
Header file for microdesc.c.
smartlist_t * microdescs_parse_from_string(const char *s, const char *eos, int allow_annotations, saved_location_t where, smartlist_t *invalid_digests_out)
Header file for microdesc_parse.c.
Microdescriptor structure.
networkstatus_t * networkstatus_get_latest_consensus_by_flavor(consensus_flavor_t f)
int networkstatus_check_document_signature(const networkstatus_t *consensus, document_signature_t *sig, const authority_cert_t *cert)
const char * networkstatus_get_flavor_name(consensus_flavor_t flav)
int networkstatus_set_current_consensus(const char *consensus, size_t consensus_len, const char *flavor, unsigned flags, const char *source_dir)
document_signature_t * networkstatus_get_voter_sig_by_alg(const networkstatus_voter_info_t *voter, digest_algorithm_t alg)
time_t voting_sched_get_start_of_interval_after(time_t now, int interval, int offset)
networkstatus_voter_info_t * networkstatus_get_voter_by_id(networkstatus_t *vote, const char *identity)
int networkstatus_check_consensus_signature(networkstatus_t *consensus, int warn)
document_signature_t * document_signature_dup(const document_signature_t *sig)
networkstatus_t * networkstatus_get_live_consensus(time_t now)
Header file for networkstatus.c.
Networkstatus consensus/vote structure.
Single consensus voter structure.
Node information structure.
char * nodefamily_canonicalize(const char *s, const uint8_t *rsa_id_self, unsigned flags)
Definition nodefamily.c:111
Header file for nodefamily.c.
const node_t * node_get_by_id(const char *identity_digest)
Definition nodelist.c:226
node_t * node_get_mutable_by_id(const char *identity_digest)
Definition nodelist.c:197
Header file for nodelist.c.
Detached consensus signatures structure.
Header file for ns_parse.c.
Master header file for Tor-specific functionality.
@ SAVED_NOWHERE
Definition or.h:723
#define BW_WEIGHT_SCALE
Definition or.h:1010
consensus_flavor_t
Definition or.h:866
#define ROUTER_MAX_AGE_TO_PUBLISH
Definition or.h:161
@ V3_DIRINFO
Definition or.h:893
#define N_CONSENSUS_FLAVORS
Definition or.h:872
Header for order.c.
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition parse_int.c:59
smartlist_t * find_all_by_keyword(const smartlist_t *s, directory_keyword k)
directory_token_t * find_opt_by_keyword(const smartlist_t *s, directory_keyword keyword)
Header file for parsecommon.c.
#define T(s, t, a, o)
char * write_short_policy(const short_policy_t *policy)
Definition policies.c:2808
char * policy_summarize(smartlist_t *policy, sa_family_t family)
Definition policies.c:2595
Header file for policies.c.
int tor_asprintf(char **strp, const char *fmt,...)
Definition printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition printf.c:27
bool protover_list_is_invalid(const char *s)
Definition protover.c:301
const char * protover_get_recommended_relay_protocols(void)
Definition protover.c:527
const char * protover_get_required_relay_protocols(void)
Definition protover.c:544
const char * protover_get_required_client_protocols(void)
Definition protover.c:536
const char * protover_get_recommended_client_protocols(void)
Definition protover.c:518
char * protover_compute_vote(const smartlist_t *list_of_proto_strings, int threshold)
Definition protover.c:657
const char * protover_compute_for_old_tor(const char *version)
C_RUST_COUPLED: src/rust/protover/protover.rs compute_for_old_tor
Definition protover.c:845
int protover_all_supported(const char *s, char **missing_out)
Definition protover.c:746
Headers and type declarations for protover.c.
int validate_recommended_package_line(const char *line)
Header file for recommend_pkg.c.
void rep_hist_make_router_pessimal(const char *id, time_t when)
Definition rephist.c:760
Header file for rephist.c.
bool find_my_address(const or_options_t *options, int family, int warn_severity, tor_addr_t *addr_out, resolved_addr_method_t *method_out, char **hostname_out)
Attempt to find our IP address that can be used as our external reachable address.
Header file for resolve_addr.c.
uint16_t routerconf_find_or_port(const or_options_t *options, sa_family_t family)
Definition router.c:1518
crypto_pk_t * get_my_v3_legacy_signing_key(void)
Definition router.c:499
crypto_pk_t * get_my_v3_authority_signing_key(void)
Definition router.c:482
static crypto_pk_t * legacy_signing_key
Definition router.c:131
authority_cert_t * get_my_v3_authority_cert(void)
Definition router.c:474
uint16_t routerconf_find_dir_port(const or_options_t *options, uint16_t dirport)
Definition router.c:1623
authority_cert_t * get_my_v3_legacy_cert(void)
Definition router.c:491
Header file for router.c.
Router descriptor structure.
#define ROUTER_PURPOSE_GENERAL
Header for routerkeys.c.
void update_consensus_router_descriptor_downloads(time_t now, int is_vote, networkstatus_t *consensus)
routerlist_t * router_get_routerlist(void)
Definition routerlist.c:897
uint32_t router_get_advertised_bandwidth(const routerinfo_t *router)
Definition routerlist.c:645
void routers_sort_by_identity(smartlist_t *routers)
Header file for routerlist.c.
Router descriptor list structure.
char * sr_get_string_for_consensus(const smartlist_t *votes, int32_t num_srv_agreements)
char * sr_get_string_for_vote(void)
void sr_act_post_consensus(const networkstatus_t *consensus)
void sr_handle_received_commits(smartlist_t *commits, crypto_pk_t *voter_key)
sr_commit_t * sr_parse_commit(const smartlist_t *args)
Header for shared_random_state.c.
char * router_get_dirobj_signature(const char *digest, size_t digest_len, const crypto_pk_t *private_key)
Definition signing.c:22
Header file for signing.c.
void smartlist_sort_digests256(smartlist_t *sl)
Definition smartlist.c:846
const uint8_t * smartlist_get_most_frequent_digest256(smartlist_t *sl)
Definition smartlist.c:854
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition smartlist.c:36
void smartlist_uniq_strings(smartlist_t *sl)
Definition smartlist.c:574
void smartlist_sort_strings(smartlist_t *sl)
Definition smartlist.c:549
int smartlist_contains_string(const smartlist_t *sl, const char *element)
Definition smartlist.c:93
const char * smartlist_get_most_frequent_string_(smartlist_t *sl, int *count_out)
Definition smartlist.c:566
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition smartlist.c:279
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition smartlist.c:334
int smartlist_string_pos(const smartlist_t *sl, const char *element)
Definition smartlist.c:106
void smartlist_uniq(smartlist_t *sl, int(*compare)(const void **a, const void **b), void(*free_fn)(void *a))
Definition smartlist.c:390
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
void smartlist_clear(smartlist_t *sl)
void smartlist_remove(smartlist_t *sl, const void *element)
void smartlist_del_keeporder(smartlist_t *sl, int idx)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
#define SMARTLIST_DEL_CURRENT(sl, var)
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
crypto_pk_t * identity_key
crypto_pk_t * signing_key
char signing_key_digest[DIGEST_LEN]
signed_descriptor_t cache_info
char d[N_COMMON_DIGEST_ALGORITHMS][DIGEST256_LEN]
LINELIST RecommendedServerVersions
LINELIST RecommendedClientVersions
char digest[DIGEST256_LEN]
smartlist_t * known_flags
common_digests_t digests
char * recommended_relay_protocols
smartlist_t * voters
smartlist_t * net_params
smartlist_t * routerstatus_list
uint8_t bw_file_digest256[DIGEST256_LEN]
networkstatus_sr_info_t sr_info
struct authority_cert_t * cert
consensus_flavor_t flavor
networkstatus_type_t type
smartlist_t * bw_file_headers
unsigned int is_running
Definition node_st.h:63
int V3AuthNIntervalsValid
char * GuardfractionFile
char * V3BandwidthsFile
int TestingV3AuthInitialVotingInterval
int TestingV3AuthVotingStartOffset
networkstatus_t * consensus
Definition dirvote.c:117
bool have_exported_for_transparency
Definition dirvote.c:120
unsigned int omit_from_vote
tor_addr_t ipv6_addr
tor_addr_t ipv4_addr
smartlist_t * exit_policy
smartlist_t * declared_family
size_t tap_onion_pkey_len
struct curve25519_public_key_t * onion_curve25519_pkey
struct smartlist_t * family_ids
char * tap_onion_pkey
struct short_policy_t * ipv6_exit_policy
smartlist_t * routers
tor_addr_t ipv6_addr
unsigned int is_sybil
char descriptor_digest[DIGEST256_LEN]
unsigned int has_exitsummary
char identity_digest[DIGEST_LEN]
unsigned int is_hs_dir
unsigned int has_guardfraction
unsigned int is_valid
unsigned int bw_is_unmeasured
char nickname[MAX_NICKNAME_LEN+1]
unsigned int has_bandwidth
uint16_t ipv4_dirport
unsigned int is_named
unsigned int is_possible_guard
unsigned int is_stable
unsigned int is_flagged_running
unsigned int is_exit
unsigned int is_authority
uint32_t guardfraction_percentage
unsigned int is_fast
uint32_t bandwidth_kb
char signed_descriptor_digest[DIGEST_LEN]
char identity_digest[DIGEST_LEN]
struct tor_cert_st * signing_key_cert
saved_location_t saved_location
struct vote_microdesc_hash_t * next
uint8_t ed25519_id[ED25519_PUBKEY_LEN]
vote_microdesc_hash_t * microdesc
unsigned int ed25519_reflects_consensus
#define STATIC
Definition testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
void format_iso_time(char *buf, time_t t)
Definition time_fmt.c:326
Parsed Tor version structure.
Header for torcert.c.
#define tor_assert_nonfatal_unreached()
Definition util_bug.h:177
#define tor_assert(expr)
Definition util_bug.h:103
int strcmpstart(const char *s1, const char *s2)
const char * find_whitespace(const char *s)
int tor_digest256_is_zero(const char *digest)
int fast_mem_is_zero(const char *mem, size_t len)
Definition util_string.c:76
const char * find_str_at_start_of_line(const char *haystack, const char *needle)
int tor_digest_is_zero(const char *digest)
Definition util_string.c:98
void sort_version_list(smartlist_t *versions, int remove_duplicates)
Definition versions.c:391
int tor_version_parse(const char *s, tor_version_t *out)
Definition versions.c:206
Header file for versions.c.
Microdescriptor-hash voting structure.
Routerstatus (vote entry) structure.
#define MAX_KNOWN_FLAGS_IN_VOTE
Directory voting schedule structure.
int running_long_enough_to_decide_unreachable(void)
Definition voteflags.c:451
void dirserv_compute_performance_thresholds(digestmap_t *omit_as_sybil)
Definition voteflags.c:206
void dirauth_set_routerstatus_from_routerinfo(routerstatus_t *rs, node_t *node, const routerinfo_t *ri, time_t now, int listbadexits, int listmiddleonly)
Definition voteflags.c:568
char * dirserv_get_flag_thresholds_line(void)
Definition voteflags.c:403
Header file for voteflags.c.
Header file for voting_schedule.c.
#define CURVE25519_BASE64_PADDED_LEN
#define ED25519_BASE64_LEN
#define ED25519_PUBKEY_LEN