Tor 0.4.9.13
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 if (get_options()->AuthDirSupport048Clients &&
835 return 0;
836 }
837
838 return (method >= MIN_SUPPORTED_CONSENSUS_METHOD) &&
840}
841
842/** Return a newly allocated string holding the numbers between low and high
843 * (inclusive) that are supported consensus methods. */
844STATIC char *
845make_consensus_method_list(int low, int high, const char *separator)
846{
847 char *list;
848
849 int i;
850 smartlist_t *lst;
851 lst = smartlist_new();
852 for (i = low; i <= high; ++i) {
854 continue;
855 smartlist_add_asprintf(lst, "%d", i);
856 }
857 list = smartlist_join_strings(lst, separator, 0, NULL);
858 tor_assert(list);
859 SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
860 smartlist_free(lst);
861 return list;
862}
863
864/** Helper: given <b>lst</b>, a list of version strings such that every
865 * version appears once for every versioning voter who recommends it, return a
866 * newly allocated string holding the resulting client-versions or
867 * server-versions list. May change contents of <b>lst</b> */
868static char *
870{
871 int min = n_versioning / 2;
872 smartlist_t *good = smartlist_new();
873 char *result;
874 SMARTLIST_FOREACH_BEGIN(lst, const char *, v) {
875 if (strchr(v, ' ')) {
876 log_warn(LD_DIR, "At least one authority has voted for a version %s "
877 "that contains a space. This probably wasn't intentional, and "
878 "is likely to cause trouble. Please tell them to stop it.",
879 escaped(v));
880 }
881 } SMARTLIST_FOREACH_END(v);
882 sort_version_list(lst, 0);
883 get_frequent_members(good, lst, min);
884 result = smartlist_join_strings(good, ",", 0, NULL);
885 smartlist_free(good);
886 return result;
887}
888
889/** Given a list of K=V values, return the int32_t value corresponding to
890 * KEYWORD=, or default_val if no such value exists, or if the value is
891 * corrupt.
892 */
893STATIC int32_t
895 const char *keyword,
896 int32_t default_val)
897{
898 unsigned int n_found = 0;
899 int32_t value = default_val;
900
901 SMARTLIST_FOREACH_BEGIN(param_list, const char *, k_v_pair) {
902 if (!strcmpstart(k_v_pair, keyword) && k_v_pair[strlen(keyword)] == '=') {
903 const char *integer_str = &k_v_pair[strlen(keyword)+1];
904 int ok;
905 value = (int32_t)
906 tor_parse_long(integer_str, 10, INT32_MIN, INT32_MAX, &ok, NULL);
907 if (BUG(!ok))
908 return default_val;
909 ++n_found;
910 }
911 } SMARTLIST_FOREACH_END(k_v_pair);
912
913 if (n_found == 1) {
914 return value;
915 } else {
916 tor_assert_nonfatal(n_found == 0);
917 return default_val;
918 }
919}
920
921/** Minimum number of directory authorities voting for a parameter to
922 * include it in the consensus, if consensus method 12 or later is to be
923 * used. See proposal 178 for details. */
924#define MIN_VOTES_FOR_PARAM 3
925
926/** Helper: given a list of valid networkstatus_t, return a new smartlist
927 * containing the contents of the consensus network parameter set.
928 */
930dirvote_compute_params(smartlist_t *votes, int method, int total_authorities)
931{
932 int i;
933 int32_t *vals;
934
935 int cur_param_len;
936 const char *cur_param;
937 const char *eq;
938
939 const int n_votes = smartlist_len(votes);
940 smartlist_t *output;
941 smartlist_t *param_list = smartlist_new();
942 (void) method;
943
944 /* We require that the parameter lists in the votes are well-formed: that
945 is, that their keywords are unique and sorted, and that their values are
946 between INT32_MIN and INT32_MAX inclusive. This should be guaranteed by
947 the parsing code. */
948
949 vals = tor_calloc(n_votes, sizeof(int));
950
952 if (!v->net_params)
953 continue;
954 smartlist_add_all(param_list, v->net_params);
955 } SMARTLIST_FOREACH_END(v);
956
957 if (smartlist_len(param_list) == 0) {
958 tor_free(vals);
959 return param_list;
960 }
961
962 smartlist_sort_strings(param_list);
963 i = 0;
964 cur_param = smartlist_get(param_list, 0);
965 eq = strchr(cur_param, '=');
966 tor_assert(eq);
967 cur_param_len = (int)(eq+1 - cur_param);
968
969 output = smartlist_new();
970
971 SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
972 /* resolve spurious clang shallow analysis null pointer errors */
973 tor_assert(param);
974
975 const char *next_param;
976 int ok=0;
977 eq = strchr(param, '=');
978 tor_assert(i<n_votes); /* Make sure we prevented vote-stuffing. */
979 vals[i++] = (int32_t)
980 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
981 tor_assert(ok); /* Already checked these when parsing. */
982
983 if (param_sl_idx+1 == smartlist_len(param_list))
984 next_param = NULL;
985 else
986 next_param = smartlist_get(param_list, param_sl_idx+1);
987
988 if (!next_param || strncmp(next_param, param, cur_param_len)) {
989 /* We've reached the end of a series. */
990 /* Make sure enough authorities voted on this param, unless the
991 * the consensus method we use is too old for that. */
992 if (i > total_authorities/2 ||
993 i >= MIN_VOTES_FOR_PARAM) {
994 int32_t median = median_int32(vals, i);
995 char *out_string = tor_malloc(64+cur_param_len);
996 memcpy(out_string, param, cur_param_len);
997 tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
998 smartlist_add(output, out_string);
999 }
1000
1001 i = 0;
1002 if (next_param) {
1003 eq = strchr(next_param, '=');
1004 cur_param_len = (int)(eq+1 - next_param);
1005 }
1006 }
1007 } SMARTLIST_FOREACH_END(param);
1008
1009 smartlist_free(param_list);
1010 tor_free(vals);
1011 return output;
1012}
1013
1014#define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
1015 ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
1016 (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
1017 (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
1018 (g) >= 0 && (g) <= (mx))
1019
1020#define CHECK_EQ(a, b, margin) \
1021 ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))
1022
1023typedef enum {
1024 BW_WEIGHTS_NO_ERROR = 0,
1025 BW_WEIGHTS_RANGE_ERROR = 1,
1026 BW_WEIGHTS_SUMG_ERROR = 2,
1027 BW_WEIGHTS_SUME_ERROR = 3,
1028 BW_WEIGHTS_SUMD_ERROR = 4,
1029 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
1030 BW_WEIGHTS_BALANCE_EG_ERROR = 6
1031} bw_weights_error_t;
1032
1033/**
1034 * Verify that any weightings satisfy the balanced formulas.
1035 */
1036static bw_weights_error_t
1037networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
1038 int64_t Wme, int64_t Wmd, int64_t Wee,
1039 int64_t Wed, int64_t scale, int64_t G,
1040 int64_t M, int64_t E, int64_t D, int64_t T,
1041 int64_t margin, int do_balance) {
1042 bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;
1043
1044 // Wed + Wmd + Wgd == 1
1045 if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
1046 berr = BW_WEIGHTS_SUMD_ERROR;
1047 goto out;
1048 }
1049
1050 // Wmg + Wgg == 1
1051 if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
1052 berr = BW_WEIGHTS_SUMG_ERROR;
1053 goto out;
1054 }
1055
1056 // Wme + Wee == 1
1057 if (!CHECK_EQ(Wme + Wee, scale, margin)) {
1058 berr = BW_WEIGHTS_SUME_ERROR;
1059 goto out;
1060 }
1061
1062 // Verify weights within range 0->1
1063 if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
1064 berr = BW_WEIGHTS_RANGE_ERROR;
1065 goto out;
1066 }
1067
1068 if (do_balance) {
1069 // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
1070 if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
1071 berr = BW_WEIGHTS_BALANCE_EG_ERROR;
1072 goto out;
1073 }
1074
1075 // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
1076 if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
1077 (margin*T)/3)) {
1078 berr = BW_WEIGHTS_BALANCE_MID_ERROR;
1079 goto out;
1080 }
1081 }
1082
1083 out:
1084 if (berr) {
1085 log_info(LD_DIR,
1086 "Bw weight mismatch %d. G=%"PRId64" M=%"PRId64
1087 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1088 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1089 " Wgd=%d Wgg=%d Wme=%d Wmg=%d",
1090 berr,
1091 (G), (M), (E),
1092 (D), (T),
1093 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1094 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg);
1095 }
1096
1097 return berr;
1098}
1099
1100/**
1101 * This function computes the bandwidth weights for consensus method 10.
1102 *
1103 * It returns true if weights could be computed, false otherwise.
1104 */
1105int
1107 int64_t M, int64_t E, int64_t D,
1108 int64_t T, int64_t weight_scale)
1109{
1110 bw_weights_error_t berr = 0;
1111 int64_t Wgg = -1, Wgd = -1;
1112 int64_t Wmg = -1, Wme = -1, Wmd = -1;
1113 int64_t Wed = -1, Wee = -1;
1114 const char *casename;
1115
1116 if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
1117 log_warn(LD_DIR, "Consensus with empty bandwidth: "
1118 "G=%"PRId64" M=%"PRId64" E=%"PRId64
1119 " D=%"PRId64" T=%"PRId64,
1120 (G), (M), (E),
1121 (D), (T));
1122 return 0;
1123 }
1124
1125 /*
1126 * Computed from cases in 3.8.3 of dir-spec.txt
1127 *
1128 * 1. Neither are scarce
1129 * 2. Both Guard and Exit are scarce
1130 * a. R+D <= S
1131 * b. R+D > S
1132 * 3. One of Guard or Exit is scarce
1133 * a. S+D < T/3
1134 * b. S+D >= T/3
1135 */
1136 if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
1137 /* Case 1: Neither are scarce. */
1138 casename = "Case 1 (Wgd=Wmd=Wed)";
1139 Wgd = weight_scale/3;
1140 Wed = weight_scale/3;
1141 Wmd = weight_scale/3;
1142 Wee = (weight_scale*(E+G+M))/(3*E);
1143 Wme = weight_scale - Wee;
1144 Wmg = (weight_scale*(2*G-E-M))/(3*G);
1145 Wgg = weight_scale - Wmg;
1146
1147 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
1148 weight_scale, G, M, E, D, T, 10, 1);
1149
1150 if (berr) {
1151 log_warn(LD_DIR,
1152 "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
1153 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1154 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1155 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
1156 berr, casename,
1157 (G), (M), (E),
1158 (D), (T),
1159 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1160 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
1161 return 0;
1162 }
1163 } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
1164 int64_t R = MIN(E, G);
1165 int64_t S = MAX(E, G);
1166 /*
1167 * Case 2: Both Guards and Exits are scarce
1168 * Balance D between E and G, depending upon
1169 * D capacity and scarcity.
1170 */
1171 if (R+D < S) { // Subcase a
1172 Wgg = weight_scale;
1173 Wee = weight_scale;
1174 Wmg = 0;
1175 Wme = 0;
1176 Wmd = 0;
1177 if (E < G) {
1178 casename = "Case 2a (E scarce)";
1179 Wed = weight_scale;
1180 Wgd = 0;
1181 } else { /* E >= G */
1182 casename = "Case 2a (G scarce)";
1183 Wed = 0;
1184 Wgd = weight_scale;
1185 }
1186 } else { // Subcase b: R+D >= S
1187 casename = "Case 2b1 (Wgg=weight_scale, Wmd=Wgd)";
1188 Wee = (weight_scale*(E - G + M))/E;
1189 Wed = (weight_scale*(D - 2*E + 4*G - 2*M))/(3*D);
1190 Wme = (weight_scale*(G-M))/E;
1191 Wmg = 0;
1192 Wgg = weight_scale;
1193 Wmd = (weight_scale - Wed)/2;
1194 Wgd = (weight_scale - Wed)/2;
1195
1196 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
1197 weight_scale, G, M, E, D, T, 10, 1);
1198
1199 if (berr) {
1200 casename = "Case 2b2 (Wgg=weight_scale, Wee=weight_scale)";
1201 Wgg = weight_scale;
1202 Wee = weight_scale;
1203 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
1204 Wmd = (weight_scale*(D - 2*M + G + E))/(3*D);
1205 Wme = 0;
1206 Wmg = 0;
1207
1208 if (Wmd < 0) { // Can happen if M > T/3
1209 casename = "Case 2b3 (Wmd=0)";
1210 Wmd = 0;
1211 log_warn(LD_DIR,
1212 "Too much Middle bandwidth on the network to calculate "
1213 "balanced bandwidth-weights. Consider increasing the "
1214 "number of Guard nodes by lowering the requirements.");
1215 }
1216 Wgd = weight_scale - Wed - Wmd;
1217 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1218 Wed, weight_scale, G, M, E, D, T, 10, 1);
1219 }
1220 if (berr != BW_WEIGHTS_NO_ERROR &&
1221 berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
1222 log_warn(LD_DIR,
1223 "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
1224 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1225 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1226 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
1227 berr, casename,
1228 (G), (M), (E),
1229 (D), (T),
1230 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1231 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
1232 return 0;
1233 }
1234 }
1235 } else { // if (E < T/3 || G < T/3) {
1236 int64_t S = MIN(E, G);
1237 // Case 3: Exactly one of Guard or Exit is scarce
1238 if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
1239 log_warn(LD_BUG,
1240 "Bw-Weights Case 3 v10 but with G=%"PRId64" M="
1241 "%"PRId64" E=%"PRId64" D=%"PRId64" T=%"PRId64,
1242 (G), (M), (E),
1243 (D), (T));
1244 }
1245
1246 if (3*(S+D) < T) { // Subcase a: S+D < T/3
1247 if (G < E) {
1248 casename = "Case 3a (G scarce)";
1249 Wgg = Wgd = weight_scale;
1250 Wmd = Wed = Wmg = 0;
1251 // Minor subcase, if E is more scarce than M,
1252 // keep its bandwidth in place.
1253 if (E < M) Wme = 0;
1254 else Wme = (weight_scale*(E-M))/(2*E);
1255 Wee = weight_scale-Wme;
1256 } else { // G >= E
1257 casename = "Case 3a (E scarce)";
1258 Wee = Wed = weight_scale;
1259 Wmd = Wgd = Wme = 0;
1260 // Minor subcase, if G is more scarce than M,
1261 // keep its bandwidth in place.
1262 if (G < M) Wmg = 0;
1263 else Wmg = (weight_scale*(G-M))/(2*G);
1264 Wgg = weight_scale-Wmg;
1265 }
1266 } else { // Subcase b: S+D >= T/3
1267 // D != 0 because S+D >= T/3
1268 if (G < E) {
1269 casename = "Case 3bg (G scarce, Wgg=weight_scale, Wmd == Wed)";
1270 Wgg = weight_scale;
1271 Wgd = (weight_scale*(D - 2*G + E + M))/(3*D);
1272 Wmg = 0;
1273 Wee = (weight_scale*(E+M))/(2*E);
1274 Wme = weight_scale - Wee;
1275 Wmd = (weight_scale - Wgd)/2;
1276 Wed = (weight_scale - Wgd)/2;
1277
1278 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1279 Wed, weight_scale, G, M, E, D, T, 10, 1);
1280 } else { // G >= E
1281 casename = "Case 3be (E scarce, Wee=weight_scale, Wmd == Wgd)";
1282 Wee = weight_scale;
1283 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
1284 Wme = 0;
1285 Wgg = (weight_scale*(G+M))/(2*G);
1286 Wmg = weight_scale - Wgg;
1287 Wmd = (weight_scale - Wed)/2;
1288 Wgd = (weight_scale - Wed)/2;
1289
1290 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1291 Wed, weight_scale, G, M, E, D, T, 10, 1);
1292 }
1293 if (berr) {
1294 log_warn(LD_DIR,
1295 "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
1296 " E=%"PRId64" D=%"PRId64" T=%"PRId64
1297 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
1298 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
1299 berr, casename,
1300 (G), (M), (E),
1301 (D), (T),
1302 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
1303 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
1304 return 0;
1305 }
1306 }
1307 }
1308
1309 /* We cast down the weights to 32 bit ints on the assumption that
1310 * weight_scale is ~= 10000. We need to ensure a rogue authority
1311 * doesn't break this assumption to rig our weights */
1312 tor_assert(0 < weight_scale && weight_scale <= INT32_MAX);
1313
1314 /*
1315 * Provide Wgm=Wgg, Wmm=weight_scale, Wem=Wee, Weg=Wed. May later determine
1316 * that middle nodes need different bandwidth weights for dirport traffic,
1317 * or that weird exit policies need special weight, or that bridges
1318 * need special weight.
1319 *
1320 * NOTE: This list is sorted.
1321 */
1323 "bandwidth-weights Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
1324 "Wdb=%d "
1325 "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
1326 "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
1327 "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
1328 (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
1329 (int)weight_scale,
1330 (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
1331 (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
1332 (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
1333
1334 log_notice(LD_CIRC, "Computed bandwidth weights for %s with v10: "
1335 "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
1336 " T=%"PRId64,
1337 casename,
1338 (G), (M), (E),
1339 (D), (T));
1340 return 1;
1341}
1342
1343/** Update total bandwidth weights (G/M/E/D/T) with the bandwidth of
1344 * the router in <b>rs</b>. */
1345static void
1347 int is_exit, int is_guard,
1348 int64_t *G, int64_t *M, int64_t *E, int64_t *D,
1349 int64_t *T)
1350{
1351 int default_bandwidth = rs->bandwidth_kb;
1352 int guardfraction_bandwidth = 0;
1353
1354 if (!rs->has_bandwidth) {
1355 log_info(LD_BUG, "Missing consensus bandwidth for router %s",
1356 rs->nickname);
1357 return;
1358 }
1359
1360 /* If this routerstatus represents a guard that we have
1361 * guardfraction information on, use it to calculate its actual
1362 * bandwidth. From proposal236:
1363 *
1364 * Similarly, when calculating the bandwidth-weights line as in
1365 * section 3.8.3 of dir-spec.txt, directory authorities should treat N
1366 * as if fraction F of its bandwidth has the guard flag and (1-F) does
1367 * not. So when computing the totals G,M,E,D, each relay N with guard
1368 * visibility fraction F and bandwidth B should be added as follows:
1369 *
1370 * G' = G + F*B, if N does not have the exit flag
1371 * M' = M + (1-F)*B, if N does not have the exit flag
1372 *
1373 * or
1374 *
1375 * D' = D + F*B, if N has the exit flag
1376 * E' = E + (1-F)*B, if N has the exit flag
1377 *
1378 * In this block of code, we prepare the bandwidth values by setting
1379 * the default_bandwidth to F*B and guardfraction_bandwidth to (1-F)*B.
1380 */
1381 if (rs->has_guardfraction) {
1382 guardfraction_bandwidth_t guardfraction_bw;
1383
1384 tor_assert(is_guard);
1385
1386 guard_get_guardfraction_bandwidth(&guardfraction_bw,
1387 rs->bandwidth_kb,
1389
1390 default_bandwidth = guardfraction_bw.guard_bw;
1391 guardfraction_bandwidth = guardfraction_bw.non_guard_bw;
1392 }
1393
1394 /* Now calculate the total bandwidth weights with or without
1395 * guardfraction. Depending on the flags of the relay, add its
1396 * bandwidth to the appropriate weight pool. If it's a guard and
1397 * guardfraction is enabled, add its bandwidth to both pools as
1398 * indicated by the previous comment.
1399 */
1400 *T += default_bandwidth;
1401 if (is_exit && is_guard) {
1402
1403 *D += default_bandwidth;
1404 if (rs->has_guardfraction) {
1405 *E += guardfraction_bandwidth;
1406 }
1407
1408 } else if (is_exit) {
1409
1410 *E += default_bandwidth;
1411
1412 } else if (is_guard) {
1413
1414 *G += default_bandwidth;
1415 if (rs->has_guardfraction) {
1416 *M += guardfraction_bandwidth;
1417 }
1418
1419 } else {
1420
1421 *M += default_bandwidth;
1422 }
1423}
1424
1425/** Considering the different recommended/required protocols sets as a
1426 * 4-element array, return the element from <b>vote</b> for that protocol
1427 * set.
1428 */
1429static const char *
1431{
1432 switch (n) {
1433 case 0: return vote->recommended_client_protocols;
1434 case 1: return vote->recommended_relay_protocols;
1435 case 2: return vote->required_client_protocols;
1436 case 3: return vote->required_relay_protocols;
1437 default:
1438 tor_assert_unreached();
1439 return NULL;
1440 }
1441}
1442
1443/** Considering the different recommended/required protocols sets as a
1444 * 4-element array, return a newly allocated string for the consensus value
1445 * for the n'th set.
1446 */
1447static char *
1448compute_nth_protocol_set(int n, int n_voters, const smartlist_t *votes)
1449{
1450 const char *keyword;
1451 smartlist_t *proto_votes = smartlist_new();
1452 int threshold;
1453 switch (n) {
1454 case 0:
1455 keyword = "recommended-client-protocols";
1456 threshold = CEIL_DIV(n_voters, 2);
1457 break;
1458 case 1:
1459 keyword = "recommended-relay-protocols";
1460 threshold = CEIL_DIV(n_voters, 2);
1461 break;
1462 case 2:
1463 keyword = "required-client-protocols";
1464 threshold = CEIL_DIV(n_voters * 2, 3);
1465 break;
1466 case 3:
1467 keyword = "required-relay-protocols";
1468 threshold = CEIL_DIV(n_voters * 2, 3);
1469 break;
1470 default:
1471 tor_assert_unreached();
1472 return NULL;
1473 }
1474
1475 SMARTLIST_FOREACH_BEGIN(votes, const networkstatus_t *, ns) {
1476 const char *v = get_nth_protocol_set_vote(n, ns);
1477 if (v)
1478 smartlist_add(proto_votes, (void*)v);
1479 } SMARTLIST_FOREACH_END(ns);
1480
1481 char *protocols = protover_compute_vote(proto_votes, threshold);
1482 smartlist_free(proto_votes);
1483
1484 char *result = NULL;
1485 tor_asprintf(&result, "%s %s\n", keyword, protocols);
1486 tor_free(protocols);
1487
1488 return result;
1489}
1490
1491/** Helper: Takes a smartlist of `const char *` flags, and a flag to remove.
1492 *
1493 * Removes that flag if it is present in the list. Doesn't free it.
1494 */
1495static void
1496remove_flag(smartlist_t *sl, const char *flag)
1497{
1498 /* We can't use smartlist_string_remove() here, since that doesn't preserve
1499 * order, and since it frees elements from the string. */
1500
1501 int idx = smartlist_string_pos(sl, flag);
1502 if (idx >= 0)
1503 smartlist_del_keeporder(sl, idx);
1504}
1505
1506/** Given a list of vote networkstatus_t in <b>votes</b>, our public
1507 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
1508 * and the number of <b>total_authorities</b> that we believe exist in our
1509 * voting quorum, generate the text of a new v3 consensus or microdescriptor
1510 * consensus (depending on <b>flavor</b>), and return the value in a newly
1511 * allocated string.
1512 *
1513 * Note: this function DOES NOT check whether the votes are from
1514 * recognized authorities. (dirvote_add_vote does that.)
1515 *
1516 * <strong>WATCH OUT</strong>: You need to think before you change the
1517 * behavior of this function, or of the functions it calls! If some
1518 * authorities compute the consensus with a different algorithm than
1519 * others, they will not reach the same result, and they will not all
1520 * sign the same thing! If you really need to change the algorithm
1521 * here, you should allocate a new "consensus_method" for the new
1522 * behavior, and make the new behavior conditional on a new-enough
1523 * consensus_method.
1524 **/
1525STATIC char *
1527 int total_authorities,
1528 crypto_pk_t *identity_key,
1529 crypto_pk_t *signing_key,
1530 const char *legacy_id_key_digest,
1532 consensus_flavor_t flavor)
1533{
1534 smartlist_t *chunks;
1535 char *result = NULL;
1536 int consensus_method;
1537 time_t valid_after, fresh_until, valid_until;
1538 int vote_seconds, dist_seconds;
1539 char *client_versions = NULL, *server_versions = NULL;
1540 smartlist_t *flags;
1541 const char *flavor_name;
1542 uint32_t max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1543 int64_t G, M, E, D, T; /* For bandwidth weights */
1544 const routerstatus_format_type_t rs_format =
1545 flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
1546 char *params = NULL;
1547 char *packages = NULL;
1548 int added_weights = 0;
1549 dircollator_t *collator = NULL;
1550 smartlist_t *param_list = NULL;
1551
1552 tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
1553 tor_assert(total_authorities >= smartlist_len(votes));
1554 tor_assert(total_authorities > 0);
1555
1556 flavor_name = networkstatus_get_flavor_name(flavor);
1557
1558 if (!smartlist_len(votes)) {
1559 log_warn(LD_DIR, "Can't compute a consensus from no votes.");
1560 return NULL;
1561 }
1562 flags = smartlist_new();
1563
1564 consensus_method = compute_consensus_method(votes);
1565 if (consensus_method_is_supported(consensus_method)) {
1566 log_info(LD_DIR, "Generating consensus using method %d.",
1567 consensus_method);
1568 } else {
1569 log_warn(LD_DIR, "The other authorities will use consensus method %d, "
1570 "which I don't support. Maybe I should upgrade!",
1571 consensus_method);
1572 consensus_method = MAX_SUPPORTED_CONSENSUS_METHOD;
1573 }
1574
1575 {
1576 /* It's smarter to initialize these weights to 1, so that later on,
1577 * we can't accidentally divide by zero. */
1578 G = M = E = D = 1;
1579 T = 4;
1580 }
1581
1582 /* Compute medians of time-related things, and figure out how many
1583 * routers we might need to talk about. */
1584 {
1585 int n_votes = smartlist_len(votes);
1586 time_t *va_times = tor_calloc(n_votes, sizeof(time_t));
1587 time_t *fu_times = tor_calloc(n_votes, sizeof(time_t));
1588 time_t *vu_times = tor_calloc(n_votes, sizeof(time_t));
1589 int *votesec_list = tor_calloc(n_votes, sizeof(int));
1590 int *distsec_list = tor_calloc(n_votes, sizeof(int));
1591 int n_versioning_clients = 0, n_versioning_servers = 0;
1592 smartlist_t *combined_client_versions = smartlist_new();
1593 smartlist_t *combined_server_versions = smartlist_new();
1594
1596 tor_assert(v->type == NS_TYPE_VOTE);
1597 va_times[v_sl_idx] = v->valid_after;
1598 fu_times[v_sl_idx] = v->fresh_until;
1599 vu_times[v_sl_idx] = v->valid_until;
1600 votesec_list[v_sl_idx] = v->vote_seconds;
1601 distsec_list[v_sl_idx] = v->dist_seconds;
1602 if (v->client_versions) {
1603 smartlist_t *cv = smartlist_new();
1604 ++n_versioning_clients;
1605 smartlist_split_string(cv, v->client_versions, ",",
1606 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1607 sort_version_list(cv, 1);
1608 smartlist_add_all(combined_client_versions, cv);
1609 smartlist_free(cv); /* elements get freed later. */
1610 }
1611 if (v->server_versions) {
1612 smartlist_t *sv = smartlist_new();
1613 ++n_versioning_servers;
1614 smartlist_split_string(sv, v->server_versions, ",",
1615 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1616 sort_version_list(sv, 1);
1617 smartlist_add_all(combined_server_versions, sv);
1618 smartlist_free(sv); /* elements get freed later. */
1619 }
1620 SMARTLIST_FOREACH(v->known_flags, const char *, cp,
1621 smartlist_add_strdup(flags, cp));
1622 } SMARTLIST_FOREACH_END(v);
1623 valid_after = median_time(va_times, n_votes);
1624 fresh_until = median_time(fu_times, n_votes);
1625 valid_until = median_time(vu_times, n_votes);
1626 vote_seconds = median_int(votesec_list, n_votes);
1627 dist_seconds = median_int(distsec_list, n_votes);
1628
1629 tor_assert(valid_after +
1630 (get_options()->TestingTorNetwork ?
1632 tor_assert(fresh_until +
1633 (get_options()->TestingTorNetwork ?
1635 tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
1636 tor_assert(dist_seconds >= MIN_DIST_SECONDS);
1637
1638 server_versions = compute_consensus_versions_list(combined_server_versions,
1639 n_versioning_servers);
1640 client_versions = compute_consensus_versions_list(combined_client_versions,
1641 n_versioning_clients);
1642
1643 if (consensus_method >= MIN_METHOD_TO_OMIT_PACKAGE_FINGERPRINTS)
1644 packages = tor_strdup("");
1645 else
1646 packages = compute_consensus_package_lines(votes);
1647
1648 SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
1649 SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
1650 smartlist_free(combined_server_versions);
1651 smartlist_free(combined_client_versions);
1652
1653 smartlist_add_strdup(flags, "NoEdConsensus");
1654
1657
1658 tor_free(va_times);
1659 tor_free(fu_times);
1660 tor_free(vu_times);
1661 tor_free(votesec_list);
1662 tor_free(distsec_list);
1663 }
1664 // True if anybody is voting on the BadExit flag.
1665 const bool badexit_flag_is_listed =
1666 smartlist_contains_string(flags, "BadExit");
1667
1668 chunks = smartlist_new();
1669
1670 {
1671 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
1672 vu_buf[ISO_TIME_LEN+1];
1673 char *flaglist;
1674 format_iso_time(va_buf, valid_after);
1675 format_iso_time(fu_buf, fresh_until);
1676 format_iso_time(vu_buf, valid_until);
1677 flaglist = smartlist_join_strings(flags, " ", 0, NULL);
1678
1679 smartlist_add_asprintf(chunks, "network-status-version 3%s%s\n"
1680 "vote-status consensus\n",
1681 flavor == FLAV_NS ? "" : " ",
1682 flavor == FLAV_NS ? "" : flavor_name);
1683
1684 smartlist_add_asprintf(chunks, "consensus-method %d\n",
1685 consensus_method);
1686
1688 "valid-after %s\n"
1689 "fresh-until %s\n"
1690 "valid-until %s\n"
1691 "voting-delay %d %d\n"
1692 "client-versions %s\n"
1693 "server-versions %s\n"
1694 "%s" /* packages */
1695 "known-flags %s\n",
1696 va_buf, fu_buf, vu_buf,
1697 vote_seconds, dist_seconds,
1698 client_versions, server_versions,
1699 packages,
1700 flaglist);
1701
1702 tor_free(flaglist);
1703 }
1704
1705 {
1706 int num_dirauth = get_n_authorities(V3_DIRINFO);
1707 int idx;
1708 for (idx = 0; idx < 4; ++idx) {
1709 char *proto_line = compute_nth_protocol_set(idx, num_dirauth, votes);
1710 if (BUG(!proto_line))
1711 continue;
1712 smartlist_add(chunks, proto_line);
1713 }
1714 }
1715
1716 param_list = dirvote_compute_params(votes, consensus_method,
1717 total_authorities);
1718 if (smartlist_len(param_list)) {
1719 params = smartlist_join_strings(param_list, " ", 0, NULL);
1720 smartlist_add_strdup(chunks, "params ");
1721 smartlist_add(chunks, params);
1722 smartlist_add_strdup(chunks, "\n");
1723 }
1724
1725 {
1726 int num_dirauth = get_n_authorities(V3_DIRINFO);
1727 /* Default value of this is 2/3 of the total number of authorities. For
1728 * instance, if we have 9 dirauth, the default value is 6. The following
1729 * calculation will round it down. */
1730 int32_t num_srv_agreements =
1732 "AuthDirNumSRVAgreements",
1733 (num_dirauth * 2) / 3);
1734 /* Add the shared random value. */
1735 char *srv_lines = sr_get_string_for_consensus(votes, num_srv_agreements);
1736 if (srv_lines != NULL) {
1737 smartlist_add(chunks, srv_lines);
1738 }
1739 }
1740
1741 /* Sort the votes. */
1743 /* Add the authority sections. */
1744 {
1745 smartlist_t *dir_sources = smartlist_new();
1747 dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
1748 e->v = v;
1749 e->digest = get_voter(v)->identity_digest;
1750 e->is_legacy = 0;
1751 smartlist_add(dir_sources, e);
1752 if (!tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
1753 dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
1754 e_legacy->v = v;
1755 e_legacy->digest = get_voter(v)->legacy_id_digest;
1756 e_legacy->is_legacy = 1;
1757 smartlist_add(dir_sources, e_legacy);
1758 }
1759 } SMARTLIST_FOREACH_END(v);
1761
1762 SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
1763 char fingerprint[HEX_DIGEST_LEN+1];
1764 char votedigest[HEX_DIGEST_LEN+1];
1765 networkstatus_t *v = e->v;
1767
1768 base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
1769 base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
1770 DIGEST_LEN);
1771
1773 "dir-source %s%s %s %s %s %d %d\n",
1774 voter->nickname, e->is_legacy ? "-legacy" : "",
1775 fingerprint, voter->address, fmt_addr(&voter->ipv4_addr),
1776 voter->ipv4_dirport,
1777 voter->ipv4_orport);
1778 if (! e->is_legacy) {
1780 "contact %s\n"
1781 "vote-digest %s\n",
1782 voter->contact,
1783 votedigest);
1784 }
1785 } SMARTLIST_FOREACH_END(e);
1786 SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
1787 smartlist_free(dir_sources);
1788 }
1789
1790 {
1791 max_unmeasured_bw_kb = dirvote_get_intermediate_param_value(
1792 param_list, "maxunmeasuredbw", DEFAULT_MAX_UNMEASURED_BW_KB);
1793 if (max_unmeasured_bw_kb < 1)
1794 max_unmeasured_bw_kb = 1;
1795 }
1796
1797 /* Add the actual router entries. */
1798 {
1799 int *size; /* size[j] is the number of routerstatuses in votes[j]. */
1800 int *flag_counts; /* The number of voters that list flag[j] for the
1801 * currently considered router. */
1802 int i;
1803 smartlist_t *matching_descs = smartlist_new();
1804 smartlist_t *chosen_flags = smartlist_new();
1805 smartlist_t *versions = smartlist_new();
1806 smartlist_t *protocols = smartlist_new();
1807 smartlist_t *exitsummaries = smartlist_new();
1808 uint32_t *bandwidths_kb = tor_calloc(smartlist_len(votes),
1809 sizeof(uint32_t));
1810 uint32_t *measured_bws_kb = tor_calloc(smartlist_len(votes),
1811 sizeof(uint32_t));
1812 uint32_t *measured_guardfraction = tor_calloc(smartlist_len(votes),
1813 sizeof(uint32_t));
1814 int num_bandwidths;
1815 int num_mbws;
1816 int num_guardfraction_inputs;
1817
1818 int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
1819 * votes[j] knows about. */
1820 int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
1821 * about flags[f]. */
1822 int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
1823 * is the same flag as votes[j]->known_flags[b]. */
1824 int *named_flag; /* Index of the flag "Named" for votes[j] */
1825 int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
1826 int n_authorities_measuring_bandwidth;
1827
1828 strmap_t *name_to_id_map = strmap_new();
1829 char conflict[DIGEST_LEN];
1830 char unknown[DIGEST_LEN];
1831 memset(conflict, 0, sizeof(conflict));
1832 memset(unknown, 0xff, sizeof(conflict));
1833
1834 size = tor_calloc(smartlist_len(votes), sizeof(int));
1835 n_voter_flags = tor_calloc(smartlist_len(votes), sizeof(int));
1836 n_flag_voters = tor_calloc(smartlist_len(flags), sizeof(int));
1837 flag_map = tor_calloc(smartlist_len(votes), sizeof(int *));
1838 named_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1839 unnamed_flag = tor_calloc(smartlist_len(votes), sizeof(int));
1840 for (i = 0; i < smartlist_len(votes); ++i)
1841 unnamed_flag[i] = named_flag[i] = -1;
1842
1843 /* Build the flag indexes. Note that no vote can have more than 64 members
1844 * for known_flags, so no value will be greater than 63, so it's safe to
1845 * do UINT64_C(1) << index on these values. But note also that
1846 * named_flag and unnamed_flag are initialized to -1, so we need to check
1847 * that they're actually set before doing UINT64_C(1) << index with
1848 * them.*/
1850 flag_map[v_sl_idx] = tor_calloc(smartlist_len(v->known_flags),
1851 sizeof(int));
1852 if (smartlist_len(v->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
1853 log_warn(LD_BUG, "Somehow, a vote has %d entries in known_flags",
1854 smartlist_len(v->known_flags));
1855 }
1856 SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
1857 int p = smartlist_string_pos(flags, fl);
1858 tor_assert(p >= 0);
1859 flag_map[v_sl_idx][fl_sl_idx] = p;
1860 ++n_flag_voters[p];
1861 if (!strcmp(fl, "Named"))
1862 named_flag[v_sl_idx] = fl_sl_idx;
1863 if (!strcmp(fl, "Unnamed"))
1864 unnamed_flag[v_sl_idx] = fl_sl_idx;
1865 } SMARTLIST_FOREACH_END(fl);
1866 n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
1867 size[v_sl_idx] = smartlist_len(v->routerstatus_list);
1868 } SMARTLIST_FOREACH_END(v);
1869
1870 /* Named and Unnamed get treated specially */
1871 {
1873 uint64_t nf;
1874 if (named_flag[v_sl_idx]<0)
1875 continue;
1876 nf = UINT64_C(1) << named_flag[v_sl_idx];
1877 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1878 vote_routerstatus_t *, rs) {
1879
1880 if ((rs->flags & nf) != 0) {
1881 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1882 if (!d) {
1883 /* We have no name officially mapped to this digest. */
1884 strmap_set_lc(name_to_id_map, rs->status.nickname,
1885 rs->status.identity_digest);
1886 } else if (d != conflict &&
1887 fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
1888 /* Authorities disagree about this nickname. */
1889 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1890 } else {
1891 /* It's already a conflict, or it's already this ID. */
1892 }
1893 }
1894 } SMARTLIST_FOREACH_END(rs);
1895 } SMARTLIST_FOREACH_END(v);
1896
1898 uint64_t uf;
1899 if (unnamed_flag[v_sl_idx]<0)
1900 continue;
1901 uf = UINT64_C(1) << unnamed_flag[v_sl_idx];
1902 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1903 vote_routerstatus_t *, rs) {
1904 if ((rs->flags & uf) != 0) {
1905 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1906 if (d == conflict || d == unknown) {
1907 /* Leave it alone; we know what it is. */
1908 } else if (!d) {
1909 /* We have no name officially mapped to this digest. */
1910 strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
1911 } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
1912 /* Authorities disagree about this nickname. */
1913 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1914 } else {
1915 /* It's mapped to a different name. */
1916 }
1917 }
1918 } SMARTLIST_FOREACH_END(rs);
1919 } SMARTLIST_FOREACH_END(v);
1920 }
1921
1922 /* We need to know how many votes measure bandwidth. */
1923 n_authorities_measuring_bandwidth = 0;
1924 SMARTLIST_FOREACH(votes, const networkstatus_t *, v,
1925 if (v->has_measured_bws) {
1926 ++n_authorities_measuring_bandwidth;
1927 }
1928 );
1929
1930 /* Populate the collator */
1931 collator = dircollator_new(smartlist_len(votes), total_authorities);
1933 dircollator_add_vote(collator, v);
1934 } SMARTLIST_FOREACH_END(v);
1935
1936 dircollator_collate(collator, consensus_method);
1937
1938 /* Now go through all the votes */
1939 flag_counts = tor_calloc(smartlist_len(flags), sizeof(int));
1940 const int num_routers = dircollator_n_routers(collator);
1941 for (i = 0; i < num_routers; ++i) {
1942 vote_routerstatus_t **vrs_lst =
1944
1946 routerstatus_t rs_out;
1947 const char *current_rsa_id = NULL;
1948 const char *chosen_version;
1949 const char *chosen_protocol_list;
1950 const char *chosen_name = NULL;
1951 int exitsummary_disagreement = 0;
1952 int is_named = 0, is_unnamed = 0, is_running = 0, is_valid = 0;
1953 int is_guard = 0, is_exit = 0, is_bad_exit = 0, is_middle_only = 0;
1954 int naming_conflict = 0;
1955 int n_listing = 0;
1956 char microdesc_digest[DIGEST256_LEN];
1957 tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
1958
1959 memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
1960 smartlist_clear(matching_descs);
1961 smartlist_clear(chosen_flags);
1962 smartlist_clear(versions);
1963 smartlist_clear(protocols);
1964 num_bandwidths = 0;
1965 num_mbws = 0;
1966 num_guardfraction_inputs = 0;
1967 int ed_consensus = 0;
1968 const uint8_t *ed_consensus_val = NULL;
1969
1970 /* Okay, go through all the entries for this digest. */
1971 for (int voter_idx = 0; voter_idx < smartlist_len(votes); ++voter_idx) {
1972 if (vrs_lst[voter_idx] == NULL)
1973 continue; /* This voter had nothing to say about this entry. */
1974 rs = vrs_lst[voter_idx];
1975 ++n_listing;
1976
1977 current_rsa_id = rs->status.identity_digest;
1978
1979 smartlist_add(matching_descs, rs);
1980 if (rs->version && rs->version[0])
1981 smartlist_add(versions, rs->version);
1982
1983 if (rs->protocols) {
1984 /* We include this one even if it's empty: voting for an
1985 * empty protocol list actually is meaningful. */
1986 smartlist_add(protocols, rs->protocols);
1987 }
1988
1989 /* Tally up all the flags. */
1990 for (int flag = 0; flag < n_voter_flags[voter_idx]; ++flag) {
1991 if (rs->flags & (UINT64_C(1) << flag))
1992 ++flag_counts[flag_map[voter_idx][flag]];
1993 }
1994 if (named_flag[voter_idx] >= 0 &&
1995 (rs->flags & (UINT64_C(1) << named_flag[voter_idx]))) {
1996 if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
1997 log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
1998 chosen_name, rs->status.nickname);
1999 naming_conflict = 1;
2000 }
2001 chosen_name = rs->status.nickname;
2002 }
2003
2004 /* Count guardfraction votes and note down the values. */
2005 if (rs->status.has_guardfraction) {
2006 measured_guardfraction[num_guardfraction_inputs++] =
2008 }
2009
2010 /* count bandwidths */
2011 if (rs->has_measured_bw)
2012 measured_bws_kb[num_mbws++] = rs->measured_bw_kb;
2013
2014 if (rs->status.has_bandwidth)
2015 bandwidths_kb[num_bandwidths++] = rs->status.bandwidth_kb;
2016
2017 /* Count number for which ed25519 is canonical. */
2019 ++ed_consensus;
2020 if (ed_consensus_val) {
2021 tor_assert(fast_memeq(ed_consensus_val, rs->ed25519_id,
2023 } else {
2024 ed_consensus_val = rs->ed25519_id;
2025 }
2026 }
2027 }
2028
2029 /* We don't include this router at all unless more than half of
2030 * the authorities we believe in list it. */
2031 if (n_listing <= total_authorities/2)
2032 continue;
2033
2034 if (ed_consensus > 0) {
2035 if (ed_consensus <= total_authorities / 2) {
2036 log_warn(LD_BUG, "Not enough entries had ed_consensus set; how "
2037 "can we have a consensus of %d?", ed_consensus);
2038 }
2039 }
2040
2041 /* The clangalyzer can't figure out that this will never be NULL
2042 * if n_listing is at least 1 */
2043 tor_assert(current_rsa_id);
2044
2045 /* Figure out the most popular opinion of what the most recent
2046 * routerinfo and its contents are. */
2047 memset(microdesc_digest, 0, sizeof(microdesc_digest));
2048 rs = compute_routerstatus_consensus(matching_descs, consensus_method,
2049 microdesc_digest, &alt_orport);
2050 /* Copy bits of that into rs_out. */
2051 memset(&rs_out, 0, sizeof(rs_out));
2052 tor_assert(fast_memeq(current_rsa_id,
2054 memcpy(rs_out.identity_digest, current_rsa_id, DIGEST_LEN);
2055 memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
2056 DIGEST_LEN);
2057 tor_addr_copy(&rs_out.ipv4_addr, &rs->status.ipv4_addr);
2058 rs_out.ipv4_dirport = rs->status.ipv4_dirport;
2059 rs_out.ipv4_orport = rs->status.ipv4_orport;
2060 tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
2061 rs_out.ipv6_orport = alt_orport.port;
2062 rs_out.has_bandwidth = 0;
2063 rs_out.has_exitsummary = 0;
2064
2065 time_t published_on = rs->published_on;
2066
2067 /* Starting with this consensus method, we no longer include a
2068 meaningful published_on time for microdescriptor consensuses. This
2069 makes their diffs smaller and more compressible.
2070
2071 We need to keep including a meaningful published_on time for NS
2072 consensuses, however, until 035 relays are all obsolete. (They use
2073 it for a purpose similar to the current StaleDesc flag.)
2074 */
2075 if (consensus_method >= MIN_METHOD_TO_SUPPRESS_MD_PUBLISHED &&
2076 flavor == FLAV_MICRODESC) {
2077 published_on = -1;
2078 }
2079
2080 if (chosen_name && !naming_conflict) {
2081 strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
2082 } else {
2083 strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
2084 }
2085
2086 {
2087 const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
2088 if (!d) {
2089 is_named = is_unnamed = 0;
2090 } else if (fast_memeq(d, current_rsa_id, DIGEST_LEN)) {
2091 is_named = 1; is_unnamed = 0;
2092 } else {
2093 is_named = 0; is_unnamed = 1;
2094 }
2095 }
2096
2097 /* Set the flags. */
2098 SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
2099 if (!strcmp(fl, "Named")) {
2100 if (is_named)
2101 smartlist_add(chosen_flags, (char*)fl);
2102 } else if (!strcmp(fl, "Unnamed")) {
2103 if (is_unnamed)
2104 smartlist_add(chosen_flags, (char*)fl);
2105 } else if (!strcmp(fl, "NoEdConsensus")) {
2106 if (ed_consensus <= total_authorities/2)
2107 smartlist_add(chosen_flags, (char*)fl);
2108 } else {
2109 if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
2110 smartlist_add(chosen_flags, (char*)fl);
2111 if (!strcmp(fl, "Exit"))
2112 is_exit = 1;
2113 else if (!strcmp(fl, "Guard"))
2114 is_guard = 1;
2115 else if (!strcmp(fl, "Running"))
2116 is_running = 1;
2117 else if (!strcmp(fl, "BadExit"))
2118 is_bad_exit = 1;
2119 else if (!strcmp(fl, "MiddleOnly"))
2120 is_middle_only = 1;
2121 else if (!strcmp(fl, "Valid"))
2122 is_valid = 1;
2123 }
2124 }
2125 } SMARTLIST_FOREACH_END(fl);
2126
2127 /* Starting with consensus method 4 we do not list servers
2128 * that are not running in a consensus. See Proposal 138 */
2129 if (!is_running)
2130 continue;
2131
2132 /* Starting with consensus method 24, we don't list servers
2133 * that are not valid in a consensus. See Proposal 272 */
2134 if (!is_valid)
2135 continue;
2136
2137 /* Starting with consensus method 32, we handle the middle-only
2138 * flag specially: when it is present, we clear some flags, and
2139 * set others. */
2140 if (is_middle_only) {
2141 remove_flag(chosen_flags, "Exit");
2142 remove_flag(chosen_flags, "V2Dir");
2143 remove_flag(chosen_flags, "Guard");
2144 remove_flag(chosen_flags, "HSDir");
2145 is_exit = is_guard = 0;
2146 if (! is_bad_exit && badexit_flag_is_listed) {
2147 is_bad_exit = 1;
2148 smartlist_add(chosen_flags, (char *)"BadExit");
2149 smartlist_sort_strings(chosen_flags); // restore order.
2150 }
2151 }
2152
2153 /* Pick the version. */
2154 if (smartlist_len(versions)) {
2155 sort_version_list(versions, 0);
2156 chosen_version = get_most_frequent_member(versions);
2157 } else {
2158 chosen_version = NULL;
2159 }
2160
2161 /* Pick the protocol list */
2162 if (smartlist_len(protocols)) {
2163 smartlist_sort_strings(protocols);
2164 chosen_protocol_list = get_most_frequent_member(protocols);
2165 } else {
2166 chosen_protocol_list = NULL;
2167 }
2168
2169 /* If it's a guard and we have enough guardfraction votes,
2170 calculate its consensus guardfraction value. */
2171 if (is_guard && num_guardfraction_inputs > 2) {
2172 rs_out.has_guardfraction = 1;
2173 rs_out.guardfraction_percentage = median_uint32(measured_guardfraction,
2174 num_guardfraction_inputs);
2175 /* final value should be an integer percentage! */
2176 tor_assert(rs_out.guardfraction_percentage <= 100);
2177 }
2178
2179 /* Pick a bandwidth */
2180 if (num_mbws > 2) {
2181 rs_out.has_bandwidth = 1;
2182 rs_out.bw_is_unmeasured = 0;
2183 rs_out.bandwidth_kb = median_uint32(measured_bws_kb, num_mbws);
2184 } else if (num_bandwidths > 0) {
2185 rs_out.has_bandwidth = 1;
2186 rs_out.bw_is_unmeasured = 1;
2187 rs_out.bandwidth_kb = median_uint32(bandwidths_kb, num_bandwidths);
2188 if (n_authorities_measuring_bandwidth > 2) {
2189 /* Cap non-measured bandwidths. */
2190 if (rs_out.bandwidth_kb > max_unmeasured_bw_kb) {
2191 rs_out.bandwidth_kb = max_unmeasured_bw_kb;
2192 }
2193 }
2194 }
2195
2196 /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
2197 is_exit = is_exit && !is_bad_exit;
2198
2199 /* Update total bandwidth weights with the bandwidths of this router. */
2200 {
2202 is_exit, is_guard,
2203 &G, &M, &E, &D, &T);
2204 }
2205
2206 /* Ok, we already picked a descriptor digest we want to list
2207 * previously. Now we want to use the exit policy summary from
2208 * that descriptor. If everybody plays nice all the voters who
2209 * listed that descriptor will have the same summary. If not then
2210 * something is fishy and we'll use the most common one (breaking
2211 * ties in favor of lexicographically larger one (only because it
2212 * lets me reuse more existing code)).
2213 *
2214 * The other case that can happen is that no authority that voted
2215 * for that descriptor has an exit policy summary. That's
2216 * probably quite unlikely but can happen. In that case we use
2217 * the policy that was most often listed in votes, again breaking
2218 * ties like in the previous case.
2219 */
2220 {
2221 /* Okay, go through all the votes for this router. We prepared
2222 * that list previously */
2223 const char *chosen_exitsummary = NULL;
2224 smartlist_clear(exitsummaries);
2225 SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
2226 /* Check if the vote where this status comes from had the
2227 * proper descriptor */
2229 vsr->status.identity_digest,
2230 DIGEST_LEN));
2231 if (vsr->status.has_exitsummary &&
2233 vsr->status.descriptor_digest,
2234 DIGEST_LEN)) {
2235 tor_assert(vsr->status.exitsummary);
2236 smartlist_add(exitsummaries, vsr->status.exitsummary);
2237 if (!chosen_exitsummary) {
2238 chosen_exitsummary = vsr->status.exitsummary;
2239 } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
2240 /* Great. There's disagreement among the voters. That
2241 * really shouldn't be */
2242 exitsummary_disagreement = 1;
2243 }
2244 }
2245 } SMARTLIST_FOREACH_END(vsr);
2246
2247 if (exitsummary_disagreement) {
2248 char id[HEX_DIGEST_LEN+1];
2249 char dd[HEX_DIGEST_LEN+1];
2250 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
2251 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
2252 log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
2253 " for router %s with descriptor %s. This really shouldn't"
2254 " have happened.", id, dd);
2255
2256 smartlist_sort_strings(exitsummaries);
2257 chosen_exitsummary = get_most_frequent_member(exitsummaries);
2258 } else if (!chosen_exitsummary) {
2259 char id[HEX_DIGEST_LEN+1];
2260 char dd[HEX_DIGEST_LEN+1];
2261 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
2262 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
2263 log_warn(LD_DIR, "Not one of the voters that made us select"
2264 "descriptor %s for router %s had an exit policy"
2265 "summary", dd, id);
2266
2267 /* Ok, none of those voting for the digest we chose had an
2268 * exit policy for us. Well, that kinda sucks.
2269 */
2270 smartlist_clear(exitsummaries);
2271 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
2272 if (vsr->status.has_exitsummary)
2273 smartlist_add(exitsummaries, vsr->status.exitsummary);
2274 });
2275 smartlist_sort_strings(exitsummaries);
2276 chosen_exitsummary = get_most_frequent_member(exitsummaries);
2277
2278 if (!chosen_exitsummary)
2279 log_warn(LD_DIR, "Wow, not one of the voters had an exit "
2280 "policy summary for %s. Wow.", id);
2281 }
2282
2283 if (chosen_exitsummary) {
2284 rs_out.has_exitsummary = 1;
2285 /* yea, discards the const */
2286 rs_out.exitsummary = (char *)chosen_exitsummary;
2287 }
2288 }
2289
2290 if (flavor == FLAV_MICRODESC &&
2291 tor_digest256_is_zero(microdesc_digest)) {
2292 /* With no microdescriptor digest, we omit the entry entirely. */
2293 continue;
2294 }
2295
2296 {
2297 char *buf;
2298 /* Okay!! Now we can write the descriptor... */
2299 /* First line goes into "buf". */
2300 buf = routerstatus_format_entry(&rs_out, NULL, NULL,
2301 rs_format, NULL, published_on);
2302 if (buf)
2303 smartlist_add(chunks, buf);
2304 }
2305 /* Now an m line, if applicable. */
2306 if (flavor == FLAV_MICRODESC &&
2307 !tor_digest256_is_zero(microdesc_digest)) {
2308 char m[BASE64_DIGEST256_LEN+1];
2309 digest256_to_base64(m, microdesc_digest);
2310 smartlist_add_asprintf(chunks, "m %s\n", m);
2311 }
2312 /* Next line is all flags. The "\n" is missing. */
2313 smartlist_add_asprintf(chunks, "s%s",
2314 smartlist_len(chosen_flags)?" ":"");
2315 smartlist_add(chunks,
2316 smartlist_join_strings(chosen_flags, " ", 0, NULL));
2317 /* Now the version line. */
2318 if (chosen_version) {
2319 smartlist_add_strdup(chunks, "\nv ");
2320 smartlist_add_strdup(chunks, chosen_version);
2321 }
2322 smartlist_add_strdup(chunks, "\n");
2323 if (chosen_protocol_list) {
2324 smartlist_add_asprintf(chunks, "pr %s\n", chosen_protocol_list);
2325 }
2326 /* Now the weight line. */
2327 if (rs_out.has_bandwidth) {
2328 char *guardfraction_str = NULL;
2329 int unmeasured = rs_out.bw_is_unmeasured;
2330
2331 /* If we have guardfraction info, include it in the 'w' line. */
2332 if (rs_out.has_guardfraction) {
2333 tor_asprintf(&guardfraction_str,
2334 " GuardFraction=%u", rs_out.guardfraction_percentage);
2335 }
2336 smartlist_add_asprintf(chunks, "w Bandwidth=%d%s%s\n",
2337 rs_out.bandwidth_kb,
2338 unmeasured?" Unmeasured=1":"",
2339 guardfraction_str ? guardfraction_str : "");
2340
2341 tor_free(guardfraction_str);
2342 }
2343
2344 /* Now the exitpolicy summary line. */
2345 if (rs_out.has_exitsummary && flavor == FLAV_NS) {
2346 smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
2347 }
2348
2349 /* And the loop is over and we move on to the next router */
2350 }
2351
2352 tor_free(size);
2353 tor_free(n_voter_flags);
2354 tor_free(n_flag_voters);
2355 for (i = 0; i < smartlist_len(votes); ++i)
2356 tor_free(flag_map[i]);
2357 tor_free(flag_map);
2358 tor_free(flag_counts);
2359 tor_free(named_flag);
2360 tor_free(unnamed_flag);
2361 strmap_free(name_to_id_map, NULL);
2362 smartlist_free(matching_descs);
2363 smartlist_free(chosen_flags);
2364 smartlist_free(versions);
2365 smartlist_free(protocols);
2366 smartlist_free(exitsummaries);
2367 tor_free(bandwidths_kb);
2368 tor_free(measured_bws_kb);
2369 tor_free(measured_guardfraction);
2370 }
2371
2372 /* Mark the directory footer region */
2373 smartlist_add_strdup(chunks, "directory-footer\n");
2374
2375 {
2376 int64_t weight_scale;
2378 param_list, "bwweightscale", BW_WEIGHT_SCALE);
2379 if (weight_scale < 1)
2380 weight_scale = 1;
2381 added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
2382 T, weight_scale);
2383 }
2384
2385 /* Write the unsigned proposed consensus text to disk, for dir auth
2386 * debugging purposes, and also to put a sig-less consensus file in
2387 * place for (with luck) later export to the consensus transparency
2388 * module. */
2389 {
2390 char *unsigned_consensus = smartlist_join_strings(chunks, "", 0, NULL);
2391 char *filename = NULL;
2392 tor_asprintf(&filename, "my-consensus-%s", flavor_name);
2393 char *fpath = get_datadir_fname(filename);
2394 write_str_to_file(fpath, unsigned_consensus, 0);
2395 tor_free(filename);
2396 tor_free(fpath);
2397 tor_free(unsigned_consensus);
2398 }
2399
2400 /* Add a signature. */
2401 {
2402 char digest[DIGEST256_LEN];
2403 char fingerprint[HEX_DIGEST_LEN+1];
2404 char signing_key_fingerprint[HEX_DIGEST_LEN+1];
2405 digest_algorithm_t digest_alg =
2406 flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
2407 size_t digest_len =
2408 flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
2409 const char *algname = crypto_digest_algorithm_get_name(digest_alg);
2410 char *signature;
2411
2412 smartlist_add_strdup(chunks, "directory-signature ");
2413
2414 /* Compute the hash of the chunks. */
2415 crypto_digest_smartlist(digest, digest_len, chunks, "", digest_alg);
2416
2417 /* Get the fingerprints */
2418 crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
2419 crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
2420
2421 /* add the junk that will go at the end of the line. */
2422 if (flavor == FLAV_NS) {
2423 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
2424 signing_key_fingerprint);
2425 } else {
2426 smartlist_add_asprintf(chunks, "%s %s %s\n",
2427 algname, fingerprint,
2428 signing_key_fingerprint);
2429 }
2430 /* And the signature. */
2431 if (!(signature = router_get_dirobj_signature(digest, digest_len,
2432 signing_key))) {
2433 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
2434 goto done;
2435 }
2436 smartlist_add(chunks, signature);
2437
2438 if (legacy_id_key_digest && legacy_signing_key) {
2439 smartlist_add_strdup(chunks, "directory-signature ");
2440 base16_encode(fingerprint, sizeof(fingerprint),
2441 legacy_id_key_digest, DIGEST_LEN);
2443 signing_key_fingerprint, 0);
2444 if (flavor == FLAV_NS) {
2445 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
2446 signing_key_fingerprint);
2447 } else {
2448 smartlist_add_asprintf(chunks, "%s %s %s\n",
2449 algname, fingerprint,
2450 signing_key_fingerprint);
2451 }
2452
2453 if (!(signature = router_get_dirobj_signature(digest, digest_len,
2455 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
2456 goto done;
2457 }
2458 smartlist_add(chunks, signature);
2459 }
2460 }
2461
2462 result = smartlist_join_strings(chunks, "", 0, NULL);
2463
2464 {
2465 networkstatus_t *c;
2466 if (!(c = networkstatus_parse_vote_from_string(result, strlen(result),
2467 NULL,
2468 NS_TYPE_CONSENSUS))) {
2469 log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
2470 "parse.");
2471 tor_free(result);
2472 goto done;
2473 }
2474 // Verify balancing parameters
2475 if (added_weights) {
2476 networkstatus_verify_bw_weights(c, consensus_method);
2477 }
2478 networkstatus_vote_free(c);
2479 }
2480
2481 done:
2482
2483 dircollator_free(collator);
2484 tor_free(client_versions);
2485 tor_free(server_versions);
2486 tor_free(packages);
2487 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
2488 smartlist_free(flags);
2489 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2490 smartlist_free(chunks);
2491 SMARTLIST_FOREACH(param_list, char *, cp, tor_free(cp));
2492 smartlist_free(param_list);
2493
2494 return result;
2495}
2496
2497/** Given a list of networkstatus_t for each vote, return a newly allocated
2498 * string containing the "package" lines for the vote. */
2499STATIC char *
2501{
2502 const int n_votes = smartlist_len(votes);
2503
2504 /* This will be a map from "packagename version" strings to arrays
2505 * of const char *, with the i'th member of the array corresponding to the
2506 * package line from the i'th vote.
2507 */
2508 strmap_t *package_status = strmap_new();
2509
2511 if (! v->package_lines)
2512 continue;
2513 SMARTLIST_FOREACH_BEGIN(v->package_lines, const char *, line) {
2515 continue;
2516
2517 /* Skip 'cp' to the second space in the line. */
2518 const char *cp = strchr(line, ' ');
2519 if (!cp) continue;
2520 ++cp;
2521 cp = strchr(cp, ' ');
2522 if (!cp) continue;
2523
2524 char *key = tor_strndup(line, cp - line);
2525
2526 const char **status = strmap_get(package_status, key);
2527 if (!status) {
2528 status = tor_calloc(n_votes, sizeof(const char *));
2529 strmap_set(package_status, key, status);
2530 }
2531 status[v_sl_idx] = line; /* overwrite old value */
2532 tor_free(key);
2533 } SMARTLIST_FOREACH_END(line);
2534 } SMARTLIST_FOREACH_END(v);
2535
2536 smartlist_t *entries = smartlist_new(); /* temporary */
2537 smartlist_t *result_list = smartlist_new(); /* output */
2538 STRMAP_FOREACH(package_status, key, const char **, values) {
2539 int i, count=-1;
2540 for (i = 0; i < n_votes; ++i) {
2541 if (values[i])
2542 smartlist_add(entries, (void*) values[i]);
2543 }
2544 smartlist_sort_strings(entries);
2545 int n_voting_for_entry = smartlist_len(entries);
2546 const char *most_frequent =
2547 smartlist_get_most_frequent_string_(entries, &count);
2548
2549 if (n_voting_for_entry >= 3 && count > n_voting_for_entry / 2) {
2550 smartlist_add_asprintf(result_list, "package %s\n", most_frequent);
2551 }
2552
2553 smartlist_clear(entries);
2554
2555 } STRMAP_FOREACH_END;
2556
2557 smartlist_sort_strings(result_list);
2558
2559 char *result = smartlist_join_strings(result_list, "", 0, NULL);
2560
2561 SMARTLIST_FOREACH(result_list, char *, cp, tor_free(cp));
2562 smartlist_free(result_list);
2563 smartlist_free(entries);
2564 strmap_free(package_status, tor_free_);
2565
2566 return result;
2567}
2568
2569/** Given a consensus vote <b>target</b> and a set of detached signatures in
2570 * <b>sigs</b> that correspond to the same consensus, check whether there are
2571 * any new signatures in <b>src_voter_list</b> that should be added to
2572 * <b>target</b>. (A signature should be added if we have no signature for that
2573 * voter in <b>target</b> yet, or if we have no verifiable signature and the
2574 * new signature is verifiable.)
2575 *
2576 * Return the number of signatures added or changed, or -1 if the document
2577 * signatures are invalid. Sets *<b>msg_out</b> to a string constant
2578 * describing the signature status.
2579 */
2580STATIC int
2583 const char *source,
2584 int severity,
2585 const char **msg_out)
2586{
2587 int r = 0;
2588 const char *flavor;
2589 smartlist_t *siglist;
2590 tor_assert(sigs);
2591 tor_assert(target);
2592 tor_assert(target->type == NS_TYPE_CONSENSUS);
2593
2594 flavor = networkstatus_get_flavor_name(target->flavor);
2595
2596 /* Do the times seem right? */
2597 if (target->valid_after != sigs->valid_after) {
2598 *msg_out = "Valid-After times do not match "
2599 "when adding detached signatures to consensus";
2600 return -1;
2601 }
2602 if (target->fresh_until != sigs->fresh_until) {
2603 *msg_out = "Fresh-until times do not match "
2604 "when adding detached signatures to consensus";
2605 return -1;
2606 }
2607 if (target->valid_until != sigs->valid_until) {
2608 *msg_out = "Valid-until times do not match "
2609 "when adding detached signatures to consensus";
2610 return -1;
2611 }
2612 siglist = strmap_get(sigs->signatures, flavor);
2613 if (!siglist) {
2614 *msg_out = "No signatures for given consensus flavor";
2615 return -1;
2616 }
2617
2618 /** Make sure all the digests we know match, and at least one matches. */
2619 {
2620 common_digests_t *digests = strmap_get(sigs->digests, flavor);
2621 int n_matches = 0;
2622 int alg;
2623 if (!digests) {
2624 *msg_out = "No digests for given consensus flavor";
2625 return -1;
2626 }
2627 for (alg = DIGEST_SHA1; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
2628 if (!fast_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
2629 if (fast_memeq(target->digests.d[alg], digests->d[alg],
2630 DIGEST256_LEN)) {
2631 ++n_matches;
2632 } else {
2633 *msg_out = "Mismatched digest.";
2634 return -1;
2635 }
2636 }
2637 }
2638 if (!n_matches) {
2639 *msg_out = "No recognized digests for given consensus flavor";
2640 }
2641 }
2642
2643 /* For each voter in src... */
2645 char voter_identity[HEX_DIGEST_LEN+1];
2646 networkstatus_voter_info_t *target_voter =
2647 networkstatus_get_voter_by_id(target, sig->identity_digest);
2648 authority_cert_t *cert = NULL;
2649 const char *algorithm;
2650 document_signature_t *old_sig = NULL;
2651
2652 algorithm = crypto_digest_algorithm_get_name(sig->alg);
2653
2654 base16_encode(voter_identity, sizeof(voter_identity),
2655 sig->identity_digest, DIGEST_LEN);
2656 log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
2657 algorithm);
2658 /* If the target doesn't know about this voter, then forget it. */
2659 if (!target_voter) {
2660 log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
2661 continue;
2662 }
2663
2664 old_sig = networkstatus_get_voter_sig_by_alg(target_voter, sig->alg);
2665
2666 /* If the target already has a good signature from this voter, then skip
2667 * this one. */
2668 if (old_sig && old_sig->good_signature) {
2669 log_info(LD_DIR, "We already have a good signature from %s using %s",
2670 voter_identity, algorithm);
2671 continue;
2672 }
2673
2674 /* Try checking the signature if we haven't already. */
2675 if (!sig->good_signature && !sig->bad_signature) {
2676 cert = authority_cert_get_by_digests(sig->identity_digest,
2677 sig->signing_key_digest);
2678 if (cert) {
2679 /* Not checking the return value here, since we are going to look
2680 * at the status of sig->good_signature in a moment. */
2681 (void) networkstatus_check_document_signature(target, sig, cert);
2682 }
2683 }
2684
2685 /* If this signature is good, or we don't have any signature yet,
2686 * then maybe add it. */
2687 if (sig->good_signature || !old_sig || old_sig->bad_signature) {
2688 log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
2689 algorithm);
2690 tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
2691 target_voter->nickname, source);
2692 ++r;
2693 if (old_sig) {
2694 smartlist_remove(target_voter->sigs, old_sig);
2695 document_signature_free(old_sig);
2696 }
2697 smartlist_add(target_voter->sigs, document_signature_dup(sig));
2698 } else {
2699 log_info(LD_DIR, "Not adding signature from %s", voter_identity);
2700 }
2701 } SMARTLIST_FOREACH_END(sig);
2702
2703 return r;
2704}
2705
2706/** Return a newly allocated string containing all the signatures on
2707 * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
2708 * then the signatures will be put in a detached signatures document, so
2709 * prefix any non-NS-flavored signatures with "additional-signature" rather
2710 * than "directory-signature". */
2711static char *
2713 int for_detached_signatures)
2714{
2715 smartlist_t *elements;
2716 char buf[4096];
2717 char *result = NULL;
2718 int n_sigs = 0;
2719 const consensus_flavor_t flavor = consensus->flavor;
2720 const char *flavor_name = networkstatus_get_flavor_name(flavor);
2721 const char *keyword;
2722
2723 if (for_detached_signatures && flavor != FLAV_NS)
2724 keyword = "additional-signature";
2725 else
2726 keyword = "directory-signature";
2727
2728 elements = smartlist_new();
2729
2732 char sk[HEX_DIGEST_LEN+1];
2733 char id[HEX_DIGEST_LEN+1];
2734 if (!sig->signature || sig->bad_signature)
2735 continue;
2736 ++n_sigs;
2737 base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
2738 base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
2739 if (flavor == FLAV_NS) {
2740 smartlist_add_asprintf(elements,
2741 "%s %s %s\n-----BEGIN SIGNATURE-----\n",
2742 keyword, id, sk);
2743 } else {
2744 const char *digest_name =
2746 smartlist_add_asprintf(elements,
2747 "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
2748 keyword,
2749 for_detached_signatures ? " " : "",
2750 for_detached_signatures ? flavor_name : "",
2751 digest_name, id, sk);
2752 }
2753 base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len,
2754 BASE64_ENCODE_MULTILINE);
2755 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
2756 smartlist_add_strdup(elements, buf);
2757 } SMARTLIST_FOREACH_END(sig);
2758 } SMARTLIST_FOREACH_END(v);
2759
2760 result = smartlist_join_strings(elements, "", 0, NULL);
2761 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2762 smartlist_free(elements);
2763 if (!n_sigs)
2764 tor_free(result);
2765 return result;
2766}
2767
2768/** Return a newly allocated string holding the detached-signatures document
2769 * corresponding to the signatures on <b>consensuses</b>, which must contain
2770 * exactly one FLAV_NS consensus, and no more than one consensus for each
2771 * other flavor. */
2772STATIC char *
2774{
2775 smartlist_t *elements;
2776 char *result = NULL, *sigs = NULL;
2777 networkstatus_t *consensus_ns = NULL;
2778 tor_assert(consensuses);
2779
2780 SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
2781 tor_assert(ns);
2782 tor_assert(ns->type == NS_TYPE_CONSENSUS);
2783 if (ns && ns->flavor == FLAV_NS)
2784 consensus_ns = ns;
2785 });
2786 if (!consensus_ns) {
2787 log_warn(LD_BUG, "No NS consensus given.");
2788 return NULL;
2789 }
2790
2791 elements = smartlist_new();
2792
2793 {
2794 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
2795 vu_buf[ISO_TIME_LEN+1];
2796 char d[HEX_DIGEST_LEN+1];
2797
2798 base16_encode(d, sizeof(d),
2799 consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
2800 format_iso_time(va_buf, consensus_ns->valid_after);
2801 format_iso_time(fu_buf, consensus_ns->fresh_until);
2802 format_iso_time(vu_buf, consensus_ns->valid_until);
2803
2804 smartlist_add_asprintf(elements,
2805 "consensus-digest %s\n"
2806 "valid-after %s\n"
2807 "fresh-until %s\n"
2808 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
2809 }
2810
2811 /* Get all the digests for the non-FLAV_NS consensuses */
2812 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2813 const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
2814 int alg;
2815 if (ns->flavor == FLAV_NS)
2816 continue;
2817
2818 /* start with SHA256; we don't include SHA1 for anything but the basic
2819 * consensus. */
2820 for (alg = DIGEST_SHA256; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
2821 char d[HEX_DIGEST256_LEN+1];
2822 const char *alg_name =
2824 if (fast_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
2825 continue;
2826 base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
2827 smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
2828 flavor_name, alg_name, d);
2829 }
2830 } SMARTLIST_FOREACH_END(ns);
2831
2832 /* Now get all the sigs for non-FLAV_NS consensuses */
2833 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2834 char *sigs_on_this_consensus;
2835 if (ns->flavor == FLAV_NS)
2836 continue;
2837 sigs_on_this_consensus = networkstatus_format_signatures(ns, 1);
2838 if (!sigs_on_this_consensus) {
2839 log_warn(LD_DIR, "Couldn't format signatures");
2840 goto err;
2841 }
2842 smartlist_add(elements, sigs_on_this_consensus);
2843 } SMARTLIST_FOREACH_END(ns);
2844
2845 /* Now add the FLAV_NS consensus signatrures. */
2846 sigs = networkstatus_format_signatures(consensus_ns, 1);
2847 if (!sigs)
2848 goto err;
2849 smartlist_add(elements, sigs);
2850
2851 result = smartlist_join_strings(elements, "", 0, NULL);
2852 err:
2853 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2854 smartlist_free(elements);
2855 return result;
2856}
2857
2858/** Return a newly allocated string holding a detached-signatures document for
2859 * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
2860 * <b>pending</b>. */
2861static char *
2863 int n_flavors)
2864{
2865 int flav;
2866 char *signatures;
2868 for (flav = 0; flav < n_flavors; ++flav) {
2869 if (pending[flav].consensus)
2870 smartlist_add(c, pending[flav].consensus);
2871 }
2873 smartlist_free(c);
2874 return signatures;
2875}
2876
2877/**
2878 * Entry point: Take whatever voting actions are pending as of <b>now</b>.
2879 *
2880 * Return the time at which the next action should be taken.
2881 */
2882time_t
2883dirvote_act(const or_options_t *options, time_t now)
2884{
2885 if (!authdir_mode_v3(options))
2886 return TIME_MAX;
2887 tor_assert_nonfatal(voting_schedule.voting_starts);
2888 /* If we haven't initialized this object through this codeflow, we need to
2889 * recalculate the timings to match our vote. The reason to do that is if we
2890 * have a voting schedule initialized 1 minute ago, the voting timings might
2891 * not be aligned to what we should expect with "now". This is especially
2892 * true for TestingTorNetwork using smaller timings. */
2893 if (voting_schedule.created_on_demand) {
2894 char *keys = list_v3_auth_ids();
2896 log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
2897 "Mine is %s.",
2899 tor_free(keys);
2900 dirauth_sched_recalculate_timing(options, now);
2901 }
2902
2903#define IF_TIME_FOR_NEXT_ACTION(when_field, done_field) \
2904 if (! voting_schedule.done_field) { \
2905 if (voting_schedule.when_field > now) { \
2906 return voting_schedule.when_field; \
2907 } else {
2908#define ENDIF \
2909 } \
2910 }
2911
2912 IF_TIME_FOR_NEXT_ACTION(voting_starts, have_voted) {
2913 log_notice(LD_DIR, "Time to vote.");
2915 voting_schedule.have_voted = 1;
2916 } ENDIF
2917 IF_TIME_FOR_NEXT_ACTION(fetch_missing_votes, have_fetched_missing_votes) {
2918 log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
2920 voting_schedule.have_fetched_missing_votes = 1;
2921 } ENDIF
2922 IF_TIME_FOR_NEXT_ACTION(voting_ends, have_built_consensus) {
2923 log_notice(LD_DIR, "Time to compute a consensus.");
2925 /* XXXX We will want to try again later if we haven't got enough
2926 * votes yet. Implement this if it turns out to ever happen. */
2927 voting_schedule.have_built_consensus = 1;
2928 } ENDIF
2929 IF_TIME_FOR_NEXT_ACTION(fetch_missing_signatures,
2930 have_fetched_missing_signatures) {
2931 log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
2933 voting_schedule.have_fetched_missing_signatures = 1;
2934 } ENDIF
2935 IF_TIME_FOR_NEXT_ACTION(interval_starts,
2936 have_published_consensus) {
2937 log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
2940 voting_schedule.have_published_consensus = 1;
2941 /* Update our shared random state with the consensus just published. */
2944 /* XXXX We will want to try again later if we haven't got enough
2945 * signatures yet. Implement this if it turns out to ever happen. */
2946 dirauth_sched_recalculate_timing(options, now);
2947 return voting_schedule.voting_starts;
2948 } ENDIF
2949
2951 return now + 1;
2952
2953#undef ENDIF
2954#undef IF_TIME_FOR_NEXT_ACTION
2955}
2956
2957/** A vote networkstatus_t and its unparsed body: held around so we can
2958 * use it to generate a consensus (at voting_ends) and so we can serve it to
2959 * other authorities that might want it. */
2960typedef struct pending_vote_t {
2961 cached_dir_t *vote_body;
2962 networkstatus_t *vote;
2964
2965/** List of pending_vote_t for the current vote. Before we've used them to
2966 * build a consensus, the votes go here. */
2968/** List of pending_vote_t for the previous vote. After we've used them to
2969 * build a consensus, the votes go here for the next period. */
2971
2972/* DOCDOC pending_consensuses */
2973static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
2974
2975/** The detached signatures for the consensus that we're currently
2976 * building. */
2978
2979/** List of ns_detached_signatures_t: hold signatures that get posted to us
2980 * before we have generated the consensus on our own. */
2982
2983/** Generate a networkstatus vote and post it to all the v3 authorities.
2984 * (V3 Authority only) */
2985static int
2987{
2990 networkstatus_t *ns;
2991 char *contents;
2992 pending_vote_t *pending_vote;
2993 time_t now = time(NULL);
2994
2995 int status;
2996 const char *msg = "";
2997
2998 if (!cert || !key) {
2999 log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
3000 return -1;
3001 } else if (cert->expires < now) {
3002 log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
3003 return -1;
3004 }
3005 if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
3006 return -1;
3007
3008 contents = format_networkstatus_vote(key, ns);
3009 networkstatus_vote_free(ns);
3010 if (!contents)
3011 return -1;
3012
3013 pending_vote = dirvote_add_vote(contents, 0, "self", &msg, &status);
3014 tor_free(contents);
3015 if (!pending_vote) {
3016 log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
3017 msg);
3018 return -1;
3019 }
3020
3023 V3_DIRINFO,
3024 pending_vote->vote_body->dir,
3025 pending_vote->vote_body->dir_len, 0);
3026 log_notice(LD_DIR, "Vote posted.");
3027 return 0;
3028}
3029
3030/** Send an HTTP request to every other v3 authority, for the votes of every
3031 * authority for which we haven't received a vote yet in this period. (V3
3032 * authority only) */
3033static void
3035{
3036 smartlist_t *missing_fps = smartlist_new();
3037 char *resource;
3038
3039 SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
3040 dir_server_t *, ds) {
3041 if (!(ds->type & V3_DIRINFO))
3042 continue;
3043 if (!dirvote_get_vote(ds->v3_identity_digest,
3044 DGV_BY_ID|DGV_INCLUDE_PENDING)) {
3045 char *cp = tor_malloc(HEX_DIGEST_LEN+1);
3046 base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
3047 DIGEST_LEN);
3048 smartlist_add(missing_fps, cp);
3049 }
3050 } SMARTLIST_FOREACH_END(ds);
3051
3052 if (!smartlist_len(missing_fps)) {
3053 smartlist_free(missing_fps);
3054 return;
3055 }
3056 {
3057 char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
3058 log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
3059 "Asking every other authority for a copy.",
3060 smartlist_len(missing_fps), tmp);
3061 tor_free(tmp);
3062 }
3063 resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
3065 0, resource);
3066 tor_free(resource);
3067 SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
3068 smartlist_free(missing_fps);
3069}
3070
3071/** Send a request to every other authority for its detached signatures,
3072 * unless we have signatures from all other v3 authorities already. */
3073static void
3075{
3076 int need_any = 0;
3077 int i;
3078 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
3079 networkstatus_t *consensus = pending_consensuses[i].consensus;
3080 if (!consensus ||
3081 networkstatus_check_consensus_signature(consensus, -1) == 1) {
3082 /* We have no consensus, or we have one that's signed by everybody. */
3083 continue;
3084 }
3085 need_any = 1;
3086 }
3087 if (!need_any)
3088 return;
3089
3091 0, NULL);
3092}
3093
3094/** Release all storage held by pending consensuses (those waiting for
3095 * signatures). */
3096static void
3098{
3099 int i;
3100 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3101 pending_consensus_t *pc = &pending_consensuses[i];
3102 tor_free(pc->body);
3103
3104 networkstatus_vote_free(pc->consensus);
3105 pc->consensus = NULL;
3106 }
3107}
3108
3109/** Drop all currently pending votes, consensus, and detached signatures. */
3110static void
3112{
3113 if (!previous_vote_list)
3115 if (!pending_vote_list)
3117
3118 /* All "previous" votes are now junk. */
3120 cached_dir_decref(v->vote_body);
3121 v->vote_body = NULL;
3122 networkstatus_vote_free(v->vote);
3123 tor_free(v);
3124 });
3126
3127 if (all_votes) {
3128 /* If we're dumping all the votes, we delete the pending ones. */
3130 cached_dir_decref(v->vote_body);
3131 v->vote_body = NULL;
3132 networkstatus_vote_free(v->vote);
3133 tor_free(v);
3134 });
3135 } else {
3136 /* Otherwise, we move them into "previous". */
3138 }
3140
3143 tor_free(cp));
3145 }
3148}
3149
3150/** Return a newly allocated string containing the hex-encoded v3 authority
3151 identity digest of every recognized v3 authority. */
3152static char *
3154{
3155 smartlist_t *known_v3_keys = smartlist_new();
3156 char *keys;
3157 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
3158 dir_server_t *, ds,
3159 if ((ds->type & V3_DIRINFO) &&
3160 !tor_digest_is_zero(ds->v3_identity_digest))
3161 smartlist_add(known_v3_keys,
3162 tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
3163 keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
3164 SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
3165 smartlist_free(known_v3_keys);
3166 return keys;
3167}
3168
3169/* Check the voter information <b>vi</b>, and assert that at least one
3170 * signature is good. Asserts on failure. */
3171static void
3172assert_any_sig_good(const networkstatus_voter_info_t *vi)
3173{
3174 int any_sig_good = 0;
3176 if (sig->good_signature)
3177 any_sig_good = 1);
3178 tor_assert(any_sig_good);
3179}
3180
3181/* Add <b>cert</b> to our list of known authority certificates. */
3182static void
3183add_new_cert_if_needed(const struct authority_cert_t *cert)
3184{
3185 tor_assert(cert);
3187 cert->signing_key_digest)) {
3188 /* Hey, it's a new cert! */
3191 TRUSTED_DIRS_CERTS_SRC_FROM_VOTE, 1 /*flush*/,
3192 NULL);
3194 cert->signing_key_digest)) {
3195 log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
3196 }
3197 }
3198}
3199
3200/** Called when we have received a networkstatus vote in <b>vote_body</b>.
3201 * Parse and validate it, and on success store it as a pending vote (which we
3202 * then return). Return NULL on failure. Sets *<b>msg_out</b> and
3203 * *<b>status_out</b> to an HTTP response and status code. (V3 authority
3204 * only) */
3206dirvote_add_vote(const char *vote_body, time_t time_posted,
3207 const char *where_from,
3208 const char **msg_out, int *status_out)
3209{
3210 networkstatus_t *vote;
3212 dir_server_t *ds;
3213 pending_vote_t *pending_vote = NULL;
3214 const char *end_of_vote = NULL;
3215 int any_failed = 0;
3216 tor_assert(vote_body);
3217 tor_assert(msg_out);
3218 tor_assert(status_out);
3219
3220 if (!pending_vote_list)
3222 *status_out = 0;
3223 *msg_out = NULL;
3224
3225 again:
3226 vote = networkstatus_parse_vote_from_string(vote_body, strlen(vote_body),
3227 &end_of_vote,
3228 NS_TYPE_VOTE);
3229 if (!end_of_vote)
3230 end_of_vote = vote_body + strlen(vote_body);
3231 if (!vote) {
3232 log_warn(LD_DIR, "Couldn't parse vote: length was %d",
3233 (int)strlen(vote_body));
3234 *msg_out = "Unable to parse vote";
3235 goto err;
3236 }
3237 tor_assert(smartlist_len(vote->voters) == 1);
3238 vi = get_voter(vote);
3239 assert_any_sig_good(vi);
3241 if (!ds) {
3242 char *keys = list_v3_auth_ids();
3243 log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
3244 "with authority key ID %s. "
3245 "This key ID is not recognized. Known v3 key IDs are: %s",
3246 vi->nickname, vi->address,
3247 hex_str(vi->identity_digest, DIGEST_LEN), keys);
3248 tor_free(keys);
3249 *msg_out = "Vote not from a recognized v3 authority";
3250 goto err;
3251 }
3252 add_new_cert_if_needed(vote->cert);
3253
3254 /* Is it for the right period? */
3255 if (vote->valid_after != voting_schedule.interval_starts) {
3256 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
3257 format_iso_time(tbuf1, vote->valid_after);
3258 format_iso_time(tbuf2, voting_schedule.interval_starts);
3259 log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
3260 "we were expecting %s", vi->address, tbuf1, tbuf2);
3261 *msg_out = "Bad valid-after time";
3262 goto err;
3263 }
3264
3265 if (time_posted) { /* they sent it to me via a POST */
3266 log_notice(LD_DIR, "%s posted a vote to me from %s.",
3267 vi->nickname, where_from);
3268 } else { /* I imported this one myself */
3269 log_notice(LD_DIR, "Retrieved %s's vote from %s.",
3270 vi->nickname, where_from);
3271 }
3272
3273 /* Check if we received it, as a post, after the cutoff when we
3274 * start asking other dir auths for it. If we do, the best plan
3275 * is to discard it, because using it greatly increases the chances
3276 * of a split vote for this round (some dir auths got it in time,
3277 * some didn't). */
3278 if (time_posted && time_posted > voting_schedule.fetch_missing_votes) {
3279 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
3280 format_iso_time(tbuf1, time_posted);
3281 format_iso_time(tbuf2, voting_schedule.fetch_missing_votes);
3282 log_warn(LD_DIR, "Rejecting %s's posted vote from %s received at %s; "
3283 "our cutoff for received votes is %s. Check your clock, "
3284 "CPU load, and network load. Also check the authority that "
3285 "posted the vote.", vi->nickname, vi->address, tbuf1, tbuf2);
3286 *msg_out = "Posted vote received too late, would be dangerous to count it";
3287 goto err;
3288 }
3289
3290 /* Fetch any new router descriptors we just learned about */
3292
3293 /* Now see whether we already have a vote from this authority. */
3295 if (fast_memeq(v->vote->cert->cache_info.identity_digest,
3297 DIGEST_LEN)) {
3298 networkstatus_voter_info_t *vi_old = get_voter(v->vote);
3299 if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
3300 /* Ah, it's the same vote. Not a problem. */
3301 log_notice(LD_DIR, "Discarding a vote we already have (from %s).",
3302 vi->address);
3303 if (*status_out < 200)
3304 *status_out = 200;
3305 goto discard;
3306 } else if (v->vote->published < vote->published) {
3307 log_notice(LD_DIR, "Replacing an older pending vote from this "
3308 "directory (%s)", vi->address);
3309 cached_dir_decref(v->vote_body);
3310 networkstatus_vote_free(v->vote);
3311 v->vote_body = new_cached_dir(tor_strndup(vote_body,
3312 end_of_vote-vote_body),
3313 vote->published);
3314 v->vote = vote;
3315 if (end_of_vote &&
3316 !strcmpstart(end_of_vote, "network-status-version"))
3317 goto again;
3318
3319 if (*status_out < 200)
3320 *status_out = 200;
3321 if (!*msg_out)
3322 *msg_out = "OK";
3323 return v;
3324 } else {
3325 log_notice(LD_DIR, "Discarding vote from %s because we have "
3326 "a newer one already.", vi->address);
3327 *msg_out = "Already have a newer pending vote";
3328 goto err;
3329 }
3330 }
3331 } SMARTLIST_FOREACH_END(v);
3332
3333 /* This a valid vote, update our shared random state. */
3334 sr_handle_received_commits(vote->sr_info.commits,
3335 vote->cert->identity_key);
3336
3337 pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
3338 pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
3339 end_of_vote-vote_body),
3340 vote->published);
3341 pending_vote->vote = vote;
3342 smartlist_add(pending_vote_list, pending_vote);
3343
3344 if (!strcmpstart(end_of_vote, "network-status-version ")) {
3345 vote_body = end_of_vote;
3346 goto again;
3347 }
3348
3349 goto done;
3350
3351 err:
3352 any_failed = 1;
3353 if (!*msg_out)
3354 *msg_out = "Error adding vote";
3355 if (*status_out < 400)
3356 *status_out = 400;
3357
3358 discard:
3359 networkstatus_vote_free(vote);
3360
3361 if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
3362 vote_body = end_of_vote;
3363 goto again;
3364 }
3365
3366 done:
3367
3368 if (*status_out < 200)
3369 *status_out = 200;
3370 if (!*msg_out) {
3371 if (!any_failed && !pending_vote) {
3372 *msg_out = "Duplicate discarded";
3373 } else {
3374 *msg_out = "ok";
3375 }
3376 }
3377
3378 return any_failed ? NULL : pending_vote;
3379}
3380
3381/* Write the votes in <b>pending_vote_list</b> to disk. */
3382static void
3383write_v3_votes_to_disk(const smartlist_t *pending_votes)
3384{
3385 smartlist_t *votestrings = smartlist_new();
3386 char *votefile = NULL;
3387
3388 SMARTLIST_FOREACH(pending_votes, pending_vote_t *, v,
3389 {
3390 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
3391 c->bytes = v->vote_body->dir;
3392 c->len = v->vote_body->dir_len;
3393 smartlist_add(votestrings, c); /* collect strings to write to disk */
3394 });
3395
3396 votefile = get_datadir_fname("v3-status-votes");
3397 write_chunks_to_file(votefile, votestrings, 0, 0);
3398 log_debug(LD_DIR, "Wrote votes to disk (%s)!", votefile);
3399
3400 tor_free(votefile);
3401 SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
3402 smartlist_free(votestrings);
3403}
3404
3405/** Try to compute a v3 networkstatus consensus from the currently pending
3406 * votes. Return 0 on success, -1 on failure. Store the consensus in
3407 * pending_consensus: it won't be ready to be published until we have
3408 * everybody else's signatures collected too. (V3 Authority only) */
3409static int
3411{
3412 /* Have we got enough votes to try? */
3413 int n_votes, n_voters, n_vote_running = 0;
3414 smartlist_t *votes = NULL;
3415 char *consensus_body = NULL, *signatures = NULL;
3416 networkstatus_t *consensus = NULL;
3417 authority_cert_t *my_cert;
3419 int flav;
3420
3421 memset(pending, 0, sizeof(pending));
3422
3423 if (!pending_vote_list)
3425
3426 /* Write votes to disk */
3427 write_v3_votes_to_disk(pending_vote_list);
3428
3429 /* Setup votes smartlist */
3430 votes = smartlist_new();
3432 {
3433 smartlist_add(votes, v->vote); /* collect votes to compute consensus */
3434 });
3435
3436 /* See if consensus managed to achieve majority */
3437 n_voters = get_n_authorities(V3_DIRINFO);
3438 n_votes = smartlist_len(pending_vote_list);
3439 if (n_votes <= n_voters/2) {
3440 log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
3441 "%d of %d", n_votes, n_voters/2+1);
3442 goto err;
3443 }
3446 if (smartlist_contains_string(v->vote->known_flags, "Running"))
3447 n_vote_running++;
3448 });
3449 if (!n_vote_running) {
3450 /* See task 1066. */
3451 log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
3452 "and publishing a consensus without Running nodes "
3453 "would make many clients stop working. Not "
3454 "generating a consensus!");
3455 goto err;
3456 }
3457
3458 if (!(my_cert = get_my_v3_authority_cert())) {
3459 log_warn(LD_DIR, "Can't generate consensus without a certificate.");
3460 goto err;
3461 }
3462
3463 {
3464 char legacy_dbuf[DIGEST_LEN];
3465 crypto_pk_t *legacy_sign=NULL;
3466 char *legacy_id_digest = NULL;
3467 int n_generated = 0;
3468 if (get_options()->V3AuthUseLegacyKey) {
3470 legacy_sign = get_my_v3_legacy_signing_key();
3471 if (cert) {
3472 if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
3473 log_warn(LD_BUG,
3474 "Unable to compute digest of legacy v3 identity key");
3475 } else {
3476 legacy_id_digest = legacy_dbuf;
3477 }
3478 }
3479 }
3480
3481 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
3482 const char *flavor_name = networkstatus_get_flavor_name(flav);
3483 consensus_body = networkstatus_compute_consensus(
3484 votes, n_voters,
3485 my_cert->identity_key,
3486 get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
3487 flav);
3488
3489 if (!consensus_body) {
3490 log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
3491 flavor_name);
3492 continue;
3493 }
3494 consensus = networkstatus_parse_vote_from_string(consensus_body,
3495 strlen(consensus_body),
3496 NULL,
3497 NS_TYPE_CONSENSUS);
3498 if (!consensus) {
3499 log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
3500 flavor_name);
3501 tor_free(consensus_body);
3502 continue;
3503 }
3504
3505 /* 'Check' our own signature, to mark it valid. */
3507
3508 pending[flav].body = consensus_body;
3509 pending[flav].consensus = consensus;
3510 n_generated++;
3511
3512 consensus_body = NULL;
3513 consensus = NULL;
3514 }
3515 if (!n_generated) {
3516 log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
3517 goto err;
3518 }
3519 }
3520
3522 pending, N_CONSENSUS_FLAVORS);
3523
3524 if (!signatures) {
3525 log_warn(LD_DIR, "Couldn't extract signatures.");
3526 goto err;
3527 }
3528
3530 memcpy(pending_consensuses, pending, sizeof(pending));
3531
3533 pending_consensus_signatures = signatures;
3534
3536 int n_sigs = 0;
3537 /* we may have gotten signatures for this consensus before we built
3538 * it ourself. Add them now. */
3540 const char *msg = NULL;
3542 "pending", &msg);
3543 if (r >= 0)
3544 n_sigs += r;
3545 else
3546 log_warn(LD_DIR,
3547 "Could not add queued signature to new consensus: %s",
3548 msg);
3549 tor_free(sig);
3550 } SMARTLIST_FOREACH_END(sig);
3551 if (n_sigs)
3552 log_notice(LD_DIR, "Added %d pending signatures while building "
3553 "consensus.", n_sigs);
3555 }
3556
3557 log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
3558
3561 V3_DIRINFO,
3563 strlen(pending_consensus_signatures), 0);
3564 log_notice(LD_DIR, "Signature(s) posted.");
3565
3566 smartlist_free(votes);
3567 return 0;
3568 err:
3569 smartlist_free(votes);
3570 tor_free(consensus_body);
3571 tor_free(signatures);
3572 networkstatus_vote_free(consensus);
3573
3574 return -1;
3575}
3576
3577/** We just got enough sigs on the pending <b>flavor_name</b>-flavor
3578 * consensus that it is time to export it to the consensus transparency
3579 * module. We do this by writing a "consensus-transparency-%s" file which
3580 * the module will detect and act on.
3581 *
3582 * The file needs to be just the bare consensus, with no signatures, so we
3583 * are registering a hash that everybody can agree on. */
3584static void
3586{
3587 char *filename = NULL;
3588 tor_asprintf(&filename, "my-consensus-%s", flavor_name);
3589 char *fpath_from = get_datadir_fname(filename);
3590 tor_free(filename);
3591 tor_asprintf(&filename, "consensus-transparency-%s", flavor_name);
3592 char *fpath_to = get_datadir_fname(filename);
3593 tor_free(filename);
3594
3595 replace_file(fpath_from, fpath_to);
3596
3597 log_notice(LD_DIR, "Exported consensus transparency file %s.",
3598 fpath_to);
3599
3600 tor_free(fpath_from);
3601 tor_free(fpath_to);
3602}
3603
3604/** Helper: we just received <b>sigs</b> as
3605 * signatures on the currently pending consensus. Add them to <b>pc</b>
3606 * as appropriate. Return the number of signatures added, or -1 if error. */
3607static int
3611 const char *source,
3612 int severity,
3613 const char **msg_out)
3614{
3615 const char *flavor_name;
3616 int r = -1;
3617
3618 /* Only call if we have a pending consensus right now. */
3619 tor_assert(pc->consensus);
3620 tor_assert(pc->body);
3622
3624 *msg_out = NULL;
3625
3626 {
3627 smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
3628 log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
3629 sig_list ? smartlist_len(sig_list) : 0, flavor_name);
3630 }
3632 source, severity, msg_out);
3633 if (r >= 0) {
3634 log_info(LD_DIR,"Added %d signatures to consensus.", r);
3635 } else {
3636 log_fn(LOG_PROTOCOL_WARN, LD_DIR,
3637 "Unable to add signatures to consensus: %s",
3638 *msg_out ? *msg_out : "(unknown)");
3639 }
3640
3641 if (r >= 1) {
3642 char *new_signatures =
3644 char *dst, *dst_end;
3645 size_t new_consensus_len;
3646 if (!new_signatures) {
3647 *msg_out = "No signatures to add";
3648 goto err;
3649 }
3650 new_consensus_len =
3651 strlen(pc->body) + strlen(new_signatures) + 1;
3652 pc->body = tor_realloc(pc->body, new_consensus_len);
3653 dst_end = pc->body + new_consensus_len;
3654 dst = (char *) find_str_at_start_of_line(pc->body, "directory-signature ");
3655 tor_assert(dst);
3656 strlcpy(dst, new_signatures, dst_end-dst);
3657
3658 /* We remove this block once it has failed to crash for a while. But
3659 * unless it shows up in profiles, we're probably better leaving it in,
3660 * just in case we break detached signature processing at some point. */
3661 {
3662 networkstatus_t *v = networkstatus_parse_vote_from_string(
3663 pc->body, strlen(pc->body), NULL,
3664 NS_TYPE_CONSENSUS);
3665 tor_assert(v);
3666 networkstatus_vote_free(v);
3667 }
3668 *msg_out = "Signatures added";
3669 tor_free(new_signatures);
3670
3671 /* Check if we now have enough sigs that we are confident this
3672 * will be our consensus. */
3675 /* Yes! Send it to the consensus transparency module. */
3678 }
3679
3680 } else if (r == 0) {
3681 *msg_out = "Signatures ignored";
3682 } else {
3683 goto err;
3684 }
3685
3686 goto done;
3687 err:
3688 if (!*msg_out)
3689 *msg_out = "Unrecognized error while adding detached signatures.";
3690 done:
3691 return r;
3692}
3693
3694/** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3695 * signatures on the currently pending consensus. Add them to the pending
3696 * consensus (if we have one).
3697 *
3698 * Set *<b>msg</b> to a string constant describing the status, regardless of
3699 * success or failure.
3700 *
3701 * Return negative on failure, nonnegative on success. */
3702static int
3704 const char *detached_signatures_body,
3705 const char *source,
3706 const char **msg_out)
3707{
3708 int r=0, i, n_added = 0, errors = 0;
3710 tor_assert(detached_signatures_body);
3711 tor_assert(msg_out);
3713
3714 if (!(sigs = networkstatus_parse_detached_signatures(
3715 detached_signatures_body, NULL))) {
3716 *msg_out = "Couldn't parse detached signatures.";
3717 goto err;
3718 }
3719
3720 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3721 int res;
3722 int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
3723 pending_consensus_t *pc = &pending_consensuses[i];
3724 if (!pc->consensus)
3725 continue;
3726 res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
3727 severity, msg_out);
3728 if (res < 0)
3729 errors++;
3730 else
3731 n_added += res;
3732 }
3733
3734 if (errors && !n_added) {
3735 r = -1;
3736 goto err;
3737 }
3738
3739 if (n_added && pending_consensuses[FLAV_NS].consensus) {
3740 char *new_detached =
3742 pending_consensuses, N_CONSENSUS_FLAVORS);
3743 if (new_detached) {
3745 pending_consensus_signatures = new_detached;
3746 }
3747 }
3748
3749 r = n_added;
3750 goto done;
3751 err:
3752 if (!*msg_out)
3753 *msg_out = "Unrecognized error while adding detached signatures.";
3754 done:
3755 ns_detached_signatures_free(sigs);
3756 /* XXXX NM Check how return is used. We can now have an error *and*
3757 signatures added. */
3758 return r;
3759}
3760
3761/** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3762 * signatures on the currently pending consensus. Add them to the pending
3763 * consensus (if we have one); otherwise queue them until we have a
3764 * consensus.
3765 *
3766 * Set *<b>msg</b> to a string constant describing the status, regardless of
3767 * success or failure.
3768 *
3769 * Return negative on failure, nonnegative on success. */
3770int
3771dirvote_add_signatures(const char *detached_signatures_body,
3772 const char *source,
3773 const char **msg)
3774{
3775 if (pending_consensuses[FLAV_NS].consensus) {
3776 log_notice(LD_DIR, "Got a signature from %s. "
3777 "Adding it to the pending consensus.", source);
3779 detached_signatures_body, source, msg);
3780 } else {
3781 log_notice(LD_DIR, "Got a signature from %s. "
3782 "Queuing it for the next consensus.", source);
3786 detached_signatures_body);
3787 *msg = "Signature queued";
3788 return 0;
3789 }
3790}
3791
3792/** Replace the consensus that we're currently serving with the one that we've
3793 * been building. (V3 Authority only) */
3794static int
3796{
3797 int i;
3798
3799 /* Now remember all the other consensuses as if we were a directory cache. */
3800 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3801 pending_consensus_t *pending = &pending_consensuses[i];
3802 const char *name;
3805 if (!pending->consensus ||
3807 log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
3808 continue;
3809 }
3810
3812 strlen(pending->body),
3813 name, 0, NULL))
3814 log_warn(LD_DIR, "Error publishing %s consensus", name);
3815 else
3816 log_notice(LD_DIR, "Published %s consensus", name);
3817 }
3818
3819 return 0;
3820}
3821
3822/** Release all static storage held in dirvote.c */
3823void
3825{
3827 /* now empty as a result of dirvote_clear_votes(). */
3828 smartlist_free(pending_vote_list);
3829 pending_vote_list = NULL;
3830 smartlist_free(previous_vote_list);
3831 previous_vote_list = NULL;
3832
3836 /* now empty as a result of dirvote_clear_votes(). */
3837 smartlist_free(pending_consensus_signature_list);
3839 }
3840}
3841
3842/* ====
3843 * Access to pending items.
3844 * ==== */
3845
3846/** Return the body of the consensus that we're currently trying to build. */
3847MOCK_IMPL(const char *,
3849{
3850 tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
3851 return pending_consensuses[flav].body;
3852}
3853
3854/** Return the signatures that we know for the consensus that we're currently
3855 * trying to build. */
3856MOCK_IMPL(const char *,
3861
3862/** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
3863 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
3864 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
3865 * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
3866 * false, do not consider any votes for a consensus that's already been built.
3867 * If <b>include_pending</b> is false, do not consider any votes for the
3868 * consensus that's in progress. May return NULL if we have no vote for the
3869 * authority in question. */
3870const cached_dir_t *
3871dirvote_get_vote(const char *fp, int flags)
3872{
3873 int by_id = flags & DGV_BY_ID;
3874 const int include_pending = flags & DGV_INCLUDE_PENDING;
3875 const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
3876
3878 return NULL;
3879 if (fp == NULL) {
3881 if (c) {
3883 by_id = 1;
3884 } else
3885 return NULL;
3886 }
3887 if (by_id) {
3888 if (pending_vote_list && include_pending) {
3890 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3891 return pv->vote_body);
3892 }
3893 if (previous_vote_list && include_previous) {
3895 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3896 return pv->vote_body);
3897 }
3898 } else {
3899 if (pending_vote_list && include_pending) {
3901 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3902 return pv->vote_body);
3903 }
3904 if (previous_vote_list && include_previous) {
3906 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3907 return pv->vote_body);
3908 }
3909 }
3910 return NULL;
3911}
3912
3913/** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
3914 * according to <b>consensus_method</b>.
3915 **/
3917dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
3918{
3919 (void) consensus_method; // Currently unneeded...
3920 microdesc_t *result = NULL;
3921 char *key = NULL, *summary = NULL, *family = NULL;
3922 size_t keylen;
3923 smartlist_t *chunks = smartlist_new();
3924 char *output = NULL;
3925 crypto_pk_t *rsa_pubkey = router_get_rsa_onion_pkey(ri->tap_onion_pkey,
3926 ri->tap_onion_pkey_len);
3927 if (!rsa_pubkey) {
3928 if (consensus_method < MIN_METHOD_TO_PERMIT_ABSENT_TAP_KEYS) {
3929 /* This method does not support generating MDs without TAP keys. */
3930 goto done;
3931 }
3932 key = tor_strdup("");
3933 } else {
3934 if (crypto_pk_write_public_key_to_string(rsa_pubkey, &key, &keylen)<0)
3935 goto done;
3936 }
3937
3938 summary = policy_summarize(ri->exit_policy, AF_INET);
3939 if (ri->declared_family)
3940 family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
3941
3942 smartlist_add_asprintf(chunks, "onion-key\n%s", key);
3943
3944 if (ri->onion_curve25519_pkey) {
3945 char kbuf[CURVE25519_BASE64_PADDED_LEN + 1];
3947 smartlist_add_asprintf(chunks, "ntor-onion-key %s\n", kbuf);
3948 }
3949
3950 if (family) {
3951 const uint8_t *id = (const uint8_t *)ri->cache_info.identity_digest;
3952 char *canonical_family = nodefamily_canonicalize(family, id, 0);
3953 smartlist_add_asprintf(chunks, "family %s\n", canonical_family);
3954 tor_free(canonical_family);
3955 }
3956
3957 if (consensus_method >= MIN_METHOD_FOR_FAMILY_IDS &&
3958 ri->family_ids && smartlist_len(ri->family_ids)) {
3959 char *family_ids = smartlist_join_strings(ri->family_ids, " ", 0, NULL);
3960 smartlist_add_asprintf(chunks, "family-ids %s\n", family_ids);
3961 tor_free(family_ids);
3962 }
3963
3964 if (summary && strcmp(summary, "reject 1-65535"))
3965 smartlist_add_asprintf(chunks, "p %s\n", summary);
3966
3967 if (ri->ipv6_exit_policy) {
3968 /* XXXX+++ This doesn't match proposal 208, which says these should
3969 * be taken unchanged from the routerinfo. That's bogosity, IMO:
3970 * the proposal should have said to do this instead.*/
3971 char *p6 = write_short_policy(ri->ipv6_exit_policy);
3972 if (p6 && strcmp(p6, "reject 1-65535"))
3973 smartlist_add_asprintf(chunks, "p6 %s\n", p6);
3974 tor_free(p6);
3975 }
3976
3977 {
3978 char idbuf[ED25519_BASE64_LEN+1];
3979 const char *keytype;
3980 if (ri->cache_info.signing_key_cert &&
3981 ri->cache_info.signing_key_cert->signing_key_included) {
3982 keytype = "ed25519";
3984 &ri->cache_info.signing_key_cert->signing_key);
3985 } else {
3986 keytype = "rsa1024";
3987 digest_to_base64(idbuf, ri->cache_info.identity_digest);
3988 }
3989 smartlist_add_asprintf(chunks, "id %s %s\n", keytype, idbuf);
3990 }
3991
3992 output = smartlist_join_strings(chunks, "", 0, NULL);
3993
3994 {
3996 output+strlen(output), 0,
3997 SAVED_NOWHERE, NULL);
3998 if (smartlist_len(lst) != 1) {
3999 log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
4000 SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
4001 smartlist_free(lst);
4002 goto done;
4003 }
4004 result = smartlist_get(lst, 0);
4005 smartlist_free(lst);
4006 }
4007
4008 done:
4009 crypto_pk_free(rsa_pubkey);
4010 tor_free(output);
4011 tor_free(key);
4012 tor_free(summary);
4013 tor_free(family);
4014 if (chunks) {
4015 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
4016 smartlist_free(chunks);
4017 }
4018 return result;
4019}
4020
4021/** Format the appropriate vote line to describe the microdescriptor <b>md</b>
4022 * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
4023 * in <b>out</b>. Return -1 on failure and the number of characters written
4024 * on success. */
4025static ssize_t
4026dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
4027 const microdesc_t *md,
4028 int consensus_method_low,
4029 int consensus_method_high)
4030{
4031 ssize_t ret = -1;
4032 char d64[BASE64_DIGEST256_LEN+1];
4033 char *microdesc_consensus_methods =
4034 make_consensus_method_list(consensus_method_low,
4035 consensus_method_high,
4036 ",");
4037 tor_assert(microdesc_consensus_methods);
4038
4039 digest256_to_base64(d64, md->digest);
4040
4041 if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
4042 microdesc_consensus_methods, d64)<0)
4043 goto out;
4044
4045 ret = strlen(out_buf);
4046
4047 out:
4048 tor_free(microdesc_consensus_methods);
4049 return ret;
4050}
4051
4052/** Array of start and end of consensus methods used for supported
4053 microdescriptor formats. */
4054static const struct consensus_method_range_t {
4055 int low;
4056 int high;
4057} microdesc_consensus_methods[] = {
4064 {-1, -1}
4065};
4066
4067/** Helper type used when generating the microdescriptor lines in a directory
4068 * vote. */
4070 int low;
4071 int high;
4072 microdesc_t *md;
4073 struct microdesc_vote_line_t *next;
4075
4076/** Generate and return a linked list of all the lines that should appear to
4077 * describe a router's microdescriptor versions in a directory vote.
4078 * Add the generated microdescriptors to <b>microdescriptors_out</b>. */
4081 smartlist_t *microdescriptors_out)
4082{
4083 const struct consensus_method_range_t *cmr;
4084 microdesc_vote_line_t *entries = NULL, *ep;
4085 vote_microdesc_hash_t *result = NULL;
4086
4087 /* Generate the microdescriptors. */
4088 for (cmr = microdesc_consensus_methods;
4089 cmr->low != -1 && cmr->high != -1;
4090 cmr++) {
4091 if (! consensus_method_is_supported(cmr->low)) {
4092 continue;
4093 }
4094 microdesc_t *md = dirvote_create_microdescriptor(ri, cmr->low);
4095 if (md) {
4097 tor_malloc_zero(sizeof(microdesc_vote_line_t));
4098 e->md = md;
4099 e->low = cmr->low;
4100 e->high = cmr->high;
4101 e->next = entries;
4102 entries = e;
4103 }
4104 }
4105
4106 /* Compress adjacent identical ones */
4107 for (ep = entries; ep; ep = ep->next) {
4108 while (ep->next &&
4109 fast_memeq(ep->md->digest, ep->next->md->digest, DIGEST256_LEN) &&
4110 ep->low == ep->next->high + 1) {
4111 microdesc_vote_line_t *next = ep->next;
4112 ep->low = next->low;
4113 microdesc_free(next->md);
4114 ep->next = next->next;
4115 tor_free(next);
4116 }
4117 }
4118
4119 /* Format them into vote_microdesc_hash_t, and add to microdescriptors_out.*/
4120 while ((ep = entries)) {
4121 char buf[128];
4123 if (dirvote_format_microdesc_vote_line(buf, sizeof(buf), ep->md,
4124 ep->low, ep->high) >= 0) {
4125 h = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
4126 h->microdesc_hash_line = tor_strdup(buf);
4127 h->next = result;
4128 result = h;
4129 ep->md->last_listed = now;
4130 smartlist_add(microdescriptors_out, ep->md);
4131 }
4132 entries = ep->next;
4133 tor_free(ep);
4134 }
4135
4136 return result;
4137}
4138
4139/** Parse and extract all SR commits from <b>tokens</b> and place them in
4140 * <b>ns</b>. */
4141static void
4143{
4144 smartlist_t *chunks = NULL;
4145
4146 tor_assert(ns);
4147 tor_assert(tokens);
4148 /* Commits are only present in a vote. */
4149 tor_assert(ns->type == NS_TYPE_VOTE);
4150
4151 ns->sr_info.commits = smartlist_new();
4152
4153 smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
4154 /* It's normal that a vote might contain no commits even if it participates
4155 * in the SR protocol. Don't treat it as an error. */
4156 if (commits == NULL) {
4157 goto end;
4158 }
4159
4160 /* Parse the commit. We do NO validation of number of arguments or ordering
4161 * for forward compatibility, it's the parse commit job to inform us if it's
4162 * supported or not. */
4163 chunks = smartlist_new();
4165 /* Extract all arguments and put them in the chunks list. */
4166 for (int i = 0; i < tok->n_args; i++) {
4167 smartlist_add(chunks, tok->args[i]);
4168 }
4169 sr_commit_t *commit = sr_parse_commit(chunks);
4170 smartlist_clear(chunks);
4171 if (commit == NULL) {
4172 /* Get voter identity so we can warn that this dirauth vote contains
4173 * commit we can't parse. */
4174 networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
4175 tor_assert(voter);
4176 log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
4177 escaped(tok->object_body),
4178 hex_str(voter->identity_digest,
4179 sizeof(voter->identity_digest)));
4180 /* Commitment couldn't be parsed. Continue onto the next commit because
4181 * this one could be unsupported for instance. */
4182 continue;
4183 }
4184 /* Add newly created commit object to the vote. */
4185 smartlist_add(ns->sr_info.commits, commit);
4186 } SMARTLIST_FOREACH_END(tok);
4187
4188 end:
4189 smartlist_free(chunks);
4190 smartlist_free(commits);
4191}
4192
4193/* Using the given directory tokens in tokens, parse the shared random commits
4194 * and put them in the given vote document ns.
4195 *
4196 * This also sets the SR participation flag if present in the vote. */
4197void
4198dirvote_parse_sr_commits(networkstatus_t *ns, const smartlist_t *tokens)
4199{
4200 /* Does this authority participates in the SR protocol? */
4201 directory_token_t *tok = find_opt_by_keyword(tokens, K_SR_FLAG);
4202 if (tok) {
4203 ns->sr_info.participate = 1;
4204 /* Get the SR commitments and reveals from the vote. */
4206 }
4207}
4208
4209/* For the given vote, free the shared random commits if any. */
4210void
4211dirvote_clear_commits(networkstatus_t *ns)
4212{
4213 tor_assert(ns->type == NS_TYPE_VOTE);
4214
4215 if (ns->sr_info.commits) {
4216 SMARTLIST_FOREACH(ns->sr_info.commits, sr_commit_t *, c,
4217 sr_commit_free(c));
4218 smartlist_free(ns->sr_info.commits);
4219 }
4220}
4221
4222/* The given url is the /tor/status-vote GET directory request. Populates the
4223 * items list with strings that we can compress on the fly and dir_items with
4224 * cached_dir_t objects that have a precompressed deflated version. */
4225void
4226dirvote_dirreq_get_status_vote(const char *url, smartlist_t *items,
4227 smartlist_t *dir_items)
4228{
4229 int current;
4230
4231 url += strlen("/tor/status-vote/");
4232 current = !strcmpstart(url, "current/");
4233 url = strchr(url, '/');
4234 tor_assert(url);
4235 ++url;
4236 if (!strcmp(url, "consensus")) {
4237 const char *item;
4238 tor_assert(!current); /* we handle current consensus specially above,
4239 * since it wants to be spooled. */
4240 if ((item = dirvote_get_pending_consensus(FLAV_NS)))
4241 smartlist_add(items, (char*)item);
4242 } else if (!current && !strcmp(url, "consensus-signatures")) {
4243 /* XXXX the spec says that we should implement
4244 * current/consensus-signatures too. It doesn't seem to be needed,
4245 * though. */
4246 const char *item;
4248 smartlist_add(items, (char*)item);
4249 } else if (!strcmp(url, "authority")) {
4250 const cached_dir_t *d;
4251 int flags = DGV_BY_ID |
4252 (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
4253 if ((d=dirvote_get_vote(NULL, flags)))
4254 smartlist_add(dir_items, (cached_dir_t*)d);
4255 } else {
4256 const cached_dir_t *d;
4257 smartlist_t *fps = smartlist_new();
4258 int flags;
4259 if (!strcmpstart(url, "d/")) {
4260 url += 2;
4261 flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
4262 } else {
4263 flags = DGV_BY_ID |
4264 (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
4265 }
4267 DSR_HEX|DSR_SORT_UNIQ);
4268 SMARTLIST_FOREACH(fps, char *, fp, {
4269 if ((d = dirvote_get_vote(fp, flags)))
4270 smartlist_add(dir_items, (cached_dir_t*)d);
4271 tor_free(fp);
4272 });
4273 smartlist_free(fps);
4274 }
4275}
4276
4277/** Get the best estimate of a router's bandwidth for dirauth purposes,
4278 * preferring measured to advertised values if available. */
4280 (const routerinfo_t *ri))
4281{
4282 uint32_t bw_kb = 0;
4283 /*
4284 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
4285 * signed) longs and the ones router_get_advertised_bandwidth() returns
4286 * are uint32_t.
4287 */
4288 long mbw_kb = 0;
4289
4290 if (ri) {
4291 /*
4292 * * First try to see if we have a measured bandwidth; don't bother with
4293 * as_of_out here, on the theory that a stale measured bandwidth is still
4294 * better to trust than an advertised one.
4295 */
4297 &mbw_kb, NULL)) {
4298 /* Got one! */
4299 bw_kb = (uint32_t)mbw_kb;
4300 } else {
4301 /* If not, fall back to advertised */
4302 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
4303 }
4304 }
4305
4306 return bw_kb;
4307}
4308
4309/**
4310 * Helper: compare the address of family `family` in `a` with the address in
4311 * `b`. The family must be one of `AF_INET` and `AF_INET6`.
4312 **/
4313static int
4315 const routerinfo_t *b,
4316 int family)
4317{
4318 const tor_addr_t *addr1 = (family==AF_INET) ? &a->ipv4_addr : &a->ipv6_addr;
4319 const tor_addr_t *addr2 = (family==AF_INET) ? &b->ipv4_addr : &b->ipv6_addr;
4320 return tor_addr_compare(addr1, addr2, CMP_EXACT);
4321}
4322
4323/** Helper for sorting: compares two ipv4 routerinfos first by ipv4 address,
4324 * and then by descending order of "usefulness"
4325 * (see compare_routerinfo_usefulness)
4326 **/
4327STATIC int
4328compare_routerinfo_by_ipv4(const void **a, const void **b)
4329{
4330 const routerinfo_t *first = *(const routerinfo_t **)a;
4331 const routerinfo_t *second = *(const routerinfo_t **)b;
4332 int comparison = compare_routerinfo_addrs_by_family(first, second, AF_INET);
4333 if (comparison == 0) {
4334 // If addresses are equal, use other comparison criteria
4335 return compare_routerinfo_usefulness(first, second);
4336 } else {
4337 return comparison;
4338 }
4339}
4340
4341/** Helper for sorting: compares two ipv6 routerinfos first by ipv6 address,
4342 * and then by descending order of "usefulness"
4343 * (see compare_routerinfo_usefulness)
4344 **/
4345STATIC int
4346compare_routerinfo_by_ipv6(const void **a, const void **b)
4347{
4348 const routerinfo_t *first = *(const routerinfo_t **)a;
4349 const routerinfo_t *second = *(const routerinfo_t **)b;
4350 int comparison = compare_routerinfo_addrs_by_family(first, second, AF_INET6);
4351 // If addresses are equal, use other comparison criteria
4352 if (comparison == 0)
4353 return compare_routerinfo_usefulness(first, second);
4354 else
4355 return comparison;
4356}
4357
4358/**
4359* Compare routerinfos by descending order of "usefulness" :
4360* An authority is more useful than a non-authority; a running router is
4361* more useful than a non-running router; and a router with more bandwidth
4362* is more useful than one with less.
4363**/
4364STATIC int
4366 const routerinfo_t *second)
4367{
4368 int first_is_auth, second_is_auth;
4369 const node_t *node_first, *node_second;
4370 int first_is_running, second_is_running;
4371 uint32_t bw_kb_first, bw_kb_second;
4372 /* Potentially, this next bit could cause k n lg n memeq calls. But in
4373 * reality, we will almost never get here, since addresses will usually be
4374 * different. */
4375 first_is_auth =
4376 router_digest_is_trusted_dir(first->cache_info.identity_digest);
4377 second_is_auth =
4378 router_digest_is_trusted_dir(second->cache_info.identity_digest);
4379
4380 if (first_is_auth && !second_is_auth)
4381 return -1;
4382 else if (!first_is_auth && second_is_auth)
4383 return 1;
4384
4385 node_first = node_get_by_id(first->cache_info.identity_digest);
4386 node_second = node_get_by_id(second->cache_info.identity_digest);
4387 first_is_running = node_first && node_first->is_running;
4388 second_is_running = node_second && node_second->is_running;
4389 if (first_is_running && !second_is_running)
4390 return -1;
4391 else if (!first_is_running && second_is_running)
4392 return 1;
4393
4394 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
4395 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
4396
4397 if (bw_kb_first > bw_kb_second)
4398 return -1;
4399 else if (bw_kb_first < bw_kb_second)
4400 return 1;
4401
4402 /* They're equal! Compare by identity digest, so there's a
4403 * deterministic order and we avoid flapping. */
4404 return fast_memcmp(first->cache_info.identity_digest,
4405 second->cache_info.identity_digest,
4406 DIGEST_LEN);
4407}
4408
4409/** Given a list of routerinfo_t in <b>routers</b> that all use the same
4410 * IP version, specified in <b>family</b>, return a new digestmap_t whose keys
4411 * are the identity digests of those routers that we're going to exclude for
4412 * Sybil-like appearance.
4413 */
4414STATIC digestmap_t *
4416{
4417 const dirauth_options_t *options = dirauth_get_options();
4418 digestmap_t *omit_as_sybil = digestmap_new();
4419 smartlist_t *routers_by_ip = smartlist_new();
4420 int addr_count = 0;
4421 routerinfo_t *last_ri = NULL;
4422 /* Allow at most this number of Tor servers on a single IP address, ... */
4423 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
4424 if (max_with_same_addr <= 0)
4425 max_with_same_addr = INT_MAX;
4426
4427 smartlist_add_all(routers_by_ip, routers);
4428 if (family == AF_INET6)
4430 else
4432
4433 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
4434 bool addrs_equal;
4435 if (last_ri)
4436 addrs_equal = !compare_routerinfo_addrs_by_family(last_ri, ri, family);
4437 else
4438 addrs_equal = false;
4439
4440 if (! addrs_equal) {
4441 last_ri = ri;
4442 addr_count = 1;
4443 } else if (++addr_count > max_with_same_addr) {
4444 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
4445 }
4446 } SMARTLIST_FOREACH_END(ri);
4447 smartlist_free(routers_by_ip);
4448 return omit_as_sybil;
4449}
4450
4451/** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
4452 * whose keys are the identity digests of those routers that we're going to
4453 * exclude for Sybil-like appearance. */
4454STATIC digestmap_t *
4456{
4457 smartlist_t *routers_ipv6, *routers_ipv4;
4458 routers_ipv6 = smartlist_new();
4459 routers_ipv4 = smartlist_new();
4460 digestmap_t *omit_as_sybil_ipv4;
4461 digestmap_t *omit_as_sybil_ipv6;
4462 digestmap_t *omit_as_sybil = digestmap_new();
4463 // Sort the routers in two lists depending on their IP version
4464 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
4465 // If the router has an IPv6 address
4466 if (tor_addr_family(&(ri->ipv6_addr)) == AF_INET6) {
4467 smartlist_add(routers_ipv6, ri);
4468 }
4469 // If the router has an IPv4 address
4470 if (tor_addr_family(&(ri->ipv4_addr)) == AF_INET) {
4471 smartlist_add(routers_ipv4, ri);
4472 }
4473 } SMARTLIST_FOREACH_END(ri);
4474 omit_as_sybil_ipv4 = get_sybil_list_by_ip_version(routers_ipv4, AF_INET);
4475 omit_as_sybil_ipv6 = get_sybil_list_by_ip_version(routers_ipv6, AF_INET6);
4476
4477 // Add all possible sybils to the common digestmap
4478 DIGESTMAP_FOREACH (omit_as_sybil_ipv4, sybil_id, routerinfo_t *, ri) {
4479 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
4481 DIGESTMAP_FOREACH (omit_as_sybil_ipv6, sybil_id, routerinfo_t *, ri) {
4482 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
4484 // Clean the temp variables
4485 smartlist_free(routers_ipv4);
4486 smartlist_free(routers_ipv6);
4487 digestmap_free(omit_as_sybil_ipv4, NULL);
4488 digestmap_free(omit_as_sybil_ipv6, NULL);
4489 // Return the digestmap: it now contains all the possible sybils
4490 return omit_as_sybil;
4491}
4492
4493/** Given a platform string as in a routerinfo_t (possibly null), return a
4494 * newly allocated version string for a networkstatus document, or NULL if the
4495 * platform doesn't give a Tor version. */
4496static char *
4497version_from_platform(const char *platform)
4498{
4499 if (platform && !strcmpstart(platform, "Tor ")) {
4500 const char *eos = find_whitespace(platform+4);
4501 if (eos && !strcmpstart(eos, " (r")) {
4502 /* XXXX Unify this logic with the other version extraction
4503 * logic in routerparse.c. */
4504 eos = find_whitespace(eos+1);
4505 }
4506 if (eos) {
4507 return tor_strndup(platform, eos-platform);
4508 }
4509 }
4510 return NULL;
4511}
4512
4513/** Given a (possibly empty) list of config_line_t, each line of which contains
4514 * a list of comma-separated version numbers surrounded by optional space,
4515 * allocate and return a new string containing the version numbers, in order,
4516 * separated by commas. Used to generate Recommended(Client|Server)?Versions
4517 */
4518char *
4520{
4521 smartlist_t *versions;
4522 char *result;
4523 versions = smartlist_new();
4524 for ( ; ln; ln = ln->next) {
4525 smartlist_split_string(versions, ln->value, ",",
4526 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4527 }
4528
4529 /* Handle the case where a dirauth operator has accidentally made some
4530 * versions space-separated instead of comma-separated. */
4531 smartlist_t *more_versions = smartlist_new();
4532 SMARTLIST_FOREACH_BEGIN(versions, char *, v) {
4533 if (strchr(v, ' ')) {
4534 if (warn)
4535 log_warn(LD_DIRSERV, "Unexpected space in versions list member %s. "
4536 "(These are supposed to be comma-separated; I'll pretend you "
4537 "used commas instead.)", escaped(v));
4538 SMARTLIST_DEL_CURRENT(versions, v);
4539 smartlist_split_string(more_versions, v, NULL,
4540 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4541 tor_free(v);
4542 }
4543 } SMARTLIST_FOREACH_END(v);
4544 smartlist_add_all(versions, more_versions);
4545 smartlist_free(more_versions);
4546
4547 /* Check to make sure everything looks like a version. */
4548 if (warn) {
4549 SMARTLIST_FOREACH_BEGIN(versions, const char *, v) {
4550 tor_version_t ver;
4551 if (tor_version_parse(v, &ver) < 0) {
4552 log_warn(LD_DIRSERV, "Recommended version %s does not look valid. "
4553 " (I'll include it anyway, since you told me to.)",
4554 escaped(v));
4555 }
4556 } SMARTLIST_FOREACH_END(v);
4557 }
4558
4559 sort_version_list(versions, 1);
4560 result = smartlist_join_strings(versions,",",0,NULL);
4561 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
4562 smartlist_free(versions);
4563 return result;
4564}
4565
4566/** If there are entries in <b>routers</b> with exactly the same ed25519 keys,
4567 * remove the older one. If they are exactly the same age, remove the one
4568 * with the greater descriptor digest. May alter the order of the list. */
4569static void
4571{
4572 routerinfo_t *ri2;
4573 digest256map_t *by_ed_key = digest256map_new();
4574
4575 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
4576 ri->omit_from_vote = 0;
4577 if (ri->cache_info.signing_key_cert == NULL)
4578 continue; /* No ed key */
4579 const uint8_t *pk = ri->cache_info.signing_key_cert->signing_key.pubkey;
4580 if ((ri2 = digest256map_get(by_ed_key, pk))) {
4581 /* Duplicate; must omit one. Set the omit_from_vote flag in whichever
4582 * one has the earlier published_on. */
4583 const time_t ri_pub = ri->cache_info.published_on;
4584 const time_t ri2_pub = ri2->cache_info.published_on;
4585 if (ri2_pub < ri_pub ||
4586 (ri2_pub == ri_pub &&
4587 fast_memcmp(ri->cache_info.signed_descriptor_digest,
4588 ri2->cache_info.signed_descriptor_digest,DIGEST_LEN)<0)) {
4589 digest256map_set(by_ed_key, pk, ri);
4590 ri2->omit_from_vote = 1;
4591 } else {
4592 ri->omit_from_vote = 1;
4593 }
4594 } else {
4595 /* Add to map */
4596 digest256map_set(by_ed_key, pk, ri);
4597 }
4598 } SMARTLIST_FOREACH_END(ri);
4599
4600 digest256map_free(by_ed_key, NULL);
4601
4602 /* Now remove every router where the omit_from_vote flag got set. */
4603 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
4604 if (ri->omit_from_vote) {
4605 SMARTLIST_DEL_CURRENT(routers, ri);
4606 }
4607 } SMARTLIST_FOREACH_END(ri);
4608}
4609
4610/** Routerstatus <b>rs</b> is part of a group of routers that are on too
4611 * narrow an IP-space. Clear out its flags since we don't want it be used
4612 * because of its Sybil-like appearance.
4613 *
4614 * Leave its BadExit flag alone though, since if we think it's a bad exit,
4615 * we want to vote that way in case all the other authorities are voting
4616 * Running and Exit.
4617 *
4618 * Also set the Sybil flag in order to let a relay operator know that's
4619 * why their relay hasn't been voted on.
4620 */
4621static void
4623{
4624 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
4625 rs->is_flagged_running = rs->is_named = rs->is_valid =
4626 rs->is_hs_dir = rs->is_v2_dir = rs->is_possible_guard = 0;
4627 rs->is_sybil = 1;
4628 /* FFFF we might want some mechanism to check later on if we
4629 * missed zeroing any flags: it's easy to add a new flag but
4630 * forget to add it to this clause. */
4631}
4632
4633/** Space-separated list of all the flags that we will always vote on. */
4635 "Authority "
4636 "Exit "
4637 "Fast "
4638 "Guard "
4639 "HSDir "
4640 "Stable "
4641 "StaleDesc "
4642 "Sybil "
4643 "V2Dir "
4644 "Valid";
4645/** Space-separated list of all flags that we may or may not vote on,
4646 * depending on our configuration. */
4648 "BadExit "
4649 "MiddleOnly "
4650 "Running";
4651
4652/** Return a new networkstatus_t* containing our current opinion. (For v3
4653 * authorities) */
4656 authority_cert_t *cert)
4657{
4658 const or_options_t *options = get_options();
4659 const dirauth_options_t *d_options = dirauth_get_options();
4660 networkstatus_t *v3_out = NULL;
4661 tor_addr_t addr;
4662 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
4663 const char *contact;
4664 smartlist_t *routers, *routerstatuses;
4665 char identity_digest[DIGEST_LEN];
4666 char signing_key_digest[DIGEST_LEN];
4667 const int list_bad_exits = d_options->AuthDirListBadExits;
4668 const int list_middle_only = d_options->AuthDirListMiddleOnly;
4670 time_t now = time(NULL);
4671 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
4672 networkstatus_voter_info_t *voter = NULL;
4673 vote_timing_t timing;
4674 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
4675 smartlist_t *microdescriptors = NULL;
4676 smartlist_t *bw_file_headers = NULL;
4677 uint8_t bw_file_digest256[DIGEST256_LEN] = {0};
4678
4679 tor_assert(private_key);
4680 tor_assert(cert);
4681
4682 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
4683 log_err(LD_BUG, "Error computing signing key digest");
4684 return NULL;
4685 }
4686 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
4687 log_err(LD_BUG, "Error computing identity key digest");
4688 return NULL;
4689 }
4690 if (!find_my_address(options, AF_INET, LOG_WARN, &addr, NULL, &hostname)) {
4691 log_warn(LD_NET, "Couldn't resolve my hostname");
4692 return NULL;
4693 }
4694 if (!hostname || !strchr(hostname, '.')) {
4695 tor_free(hostname);
4696 hostname = tor_addr_to_str_dup(&addr);
4697 }
4698
4699 if (!hostname) {
4700 log_err(LD_BUG, "Failed to determine hostname AND duplicate address");
4701 return NULL;
4702 }
4703
4704 if (d_options->VersioningAuthoritativeDirectory) {
4705 client_versions =
4707 server_versions =
4709 }
4710
4711 contact = get_options()->ContactInfo;
4712 if (!contact)
4713 contact = "(none)";
4714
4715 /*
4716 * Do this so dirserv_compute_performance_thresholds() and
4717 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
4718 */
4719 if (options->V3BandwidthsFile) {
4721 NULL);
4722 } else {
4723 /*
4724 * No bandwidths file; clear the measured bandwidth cache in case we had
4725 * one last time around.
4726 */
4729 }
4730 }
4731
4732 /* precompute this part, since we need it to decide what "stable"
4733 * means. */
4735 dirserv_set_router_is_running(ri, now);
4736 });
4737
4738 routers = smartlist_new();
4739 smartlist_add_all(routers, rl->routers);
4741 /* After this point, don't use rl->routers; use 'routers' instead. */
4742 routers_sort_by_identity(routers);
4743 /* Get a digestmap of possible sybil routers, IPv4 or IPv6 */
4744 digestmap_t *omit_as_sybil = get_all_possible_sybil(routers);
4745 DIGESTMAP_FOREACH (omit_as_sybil, sybil_id, void *, ignore) {
4746 (void)ignore;
4747 rep_hist_make_router_pessimal(sybil_id, now);
4749 /* Count how many have measured bandwidths so we know how to assign flags;
4750 * this must come before dirserv_compute_performance_thresholds() */
4753 routerstatuses = smartlist_new();
4754 microdescriptors = smartlist_new();
4755
4756 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
4757 /* If it has a protover list and contains a protocol name greater than
4758 * MAX_PROTOCOL_NAME_LENGTH, skip it. */
4759 if (ri->protocol_list &&
4760 protover_list_is_invalid(ri->protocol_list)) {
4761 continue;
4762 }
4763 if (ri->cache_info.published_on >= cutoff) {
4764 routerstatus_t *rs;
4766 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
4767 if (!node)
4768 continue;
4769
4770 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
4771 rs = &vrs->status;
4773 list_bad_exits,
4774 list_middle_only);
4775 vrs->published_on = ri->cache_info.published_on;
4776
4777 if (ri->cache_info.signing_key_cert) {
4778 memcpy(vrs->ed25519_id,
4779 ri->cache_info.signing_key_cert->signing_key.pubkey,
4781 }
4782 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
4784
4785 if (!vote_on_reachability)
4786 rs->is_flagged_running = 0;
4787
4788 vrs->version = version_from_platform(ri->platform);
4789 if (ri->protocol_list) {
4790 vrs->protocols = tor_strdup(ri->protocol_list);
4791 } else {
4792 vrs->protocols = tor_strdup(
4794 }
4796 microdescriptors);
4797
4798 smartlist_add(routerstatuses, vrs);
4799 }
4800 } SMARTLIST_FOREACH_END(ri);
4801
4802 {
4803 smartlist_t *added =
4805 microdescriptors, SAVED_NOWHERE, 0);
4806 smartlist_free(added);
4807 smartlist_free(microdescriptors);
4808 }
4809
4810 smartlist_free(routers);
4811 digestmap_free(omit_as_sybil, NULL);
4812
4813 /* Apply guardfraction information to routerstatuses. */
4814 if (options->GuardfractionFile) {
4815 dirserv_read_guardfraction_file(options->GuardfractionFile,
4816 routerstatuses);
4817 }
4818
4819 /* This pass through applies the measured bw lines to the routerstatuses */
4820 if (options->V3BandwidthsFile) {
4821 /* Only set bw_file_headers when V3BandwidthsFile is configured */
4822 bw_file_headers = smartlist_new();
4824 routerstatuses, bw_file_headers,
4825 bw_file_digest256);
4826 } else {
4827 /*
4828 * No bandwidths file; clear the measured bandwidth cache in case we had
4829 * one last time around.
4830 */
4833 }
4834 }
4835
4836 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
4837
4838 v3_out->type = NS_TYPE_VOTE;
4840 v3_out->published = now;
4841 {
4842 char tbuf[ISO_TIME_LEN+1];
4843 networkstatus_t *current_consensus =
4845 long last_consensus_interval; /* only used to pick a valid_after */
4846 if (current_consensus)
4847 last_consensus_interval = current_consensus->fresh_until -
4848 current_consensus->valid_after;
4849 else
4850 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
4851 v3_out->valid_after =
4853 (int)last_consensus_interval,
4855 format_iso_time(tbuf, v3_out->valid_after);
4856 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
4857 "consensus_set=%d, last_interval=%d",
4858 tbuf, current_consensus?1:0, (int)last_consensus_interval);
4859 }
4860 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
4861 v3_out->valid_until = v3_out->valid_after +
4862 (timing.vote_interval * timing.n_intervals_valid);
4863 v3_out->vote_seconds = timing.vote_delay;
4864 v3_out->dist_seconds = timing.dist_delay;
4865 tor_assert(v3_out->vote_seconds > 0);
4866 tor_assert(v3_out->dist_seconds > 0);
4867 tor_assert(timing.n_intervals_valid > 0);
4868
4869 v3_out->client_versions = client_versions;
4870 v3_out->server_versions = server_versions;
4871
4874 v3_out->recommended_client_protocols =
4876 v3_out->required_client_protocols =
4878 v3_out->required_relay_protocols =
4880
4881 /* We are not allowed to vote to require anything we don't have. */
4882 tor_assert(protover_all_supported(v3_out->required_relay_protocols, NULL));
4883 tor_assert(protover_all_supported(v3_out->required_client_protocols, NULL));
4884
4885 /* We should not recommend anything we don't have. */
4886 tor_assert_nonfatal(protover_all_supported(
4887 v3_out->recommended_relay_protocols, NULL));
4888 tor_assert_nonfatal(protover_all_supported(
4889 v3_out->recommended_client_protocols, NULL));
4890
4891 v3_out->known_flags = smartlist_new();
4894 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
4895 if (vote_on_reachability)
4896 smartlist_add_strdup(v3_out->known_flags, "Running");
4897 if (list_bad_exits)
4898 smartlist_add_strdup(v3_out->known_flags, "BadExit");
4899 if (list_middle_only)
4900 smartlist_add_strdup(v3_out->known_flags, "MiddleOnly");
4902
4903 if (d_options->ConsensusParams) {
4904 config_line_t *paramline = d_options->ConsensusParams;
4905 v3_out->net_params = smartlist_new();
4906 for ( ; paramline; paramline = paramline->next) {
4908 paramline->value, NULL, 0, 0);
4909 }
4910
4911 /* for transparency and visibility, include our current value of
4912 * AuthDirMaxServersPerAddr in our consensus params. Once enough dir
4913 * auths do this, external tools should be able to use that value to
4914 * help understand which relays are allowed into the consensus. */
4915 smartlist_add_asprintf(v3_out->net_params, "AuthDirMaxServersPerAddr=%d",
4916 d_options->AuthDirMaxServersPerAddr);
4917
4919 }
4920 v3_out->bw_file_headers = bw_file_headers;
4921 memcpy(v3_out->bw_file_digest256, bw_file_digest256, DIGEST256_LEN);
4922
4923 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
4924 voter->nickname = tor_strdup(options->Nickname);
4925 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
4926 voter->sigs = smartlist_new();
4927 voter->address = hostname;
4928 tor_addr_copy(&voter->ipv4_addr, &addr);
4929 voter->ipv4_dirport = routerconf_find_dir_port(options, 0);
4930 voter->ipv4_orport = routerconf_find_or_port(options, AF_INET);
4931 voter->contact = tor_strdup(contact);
4932 if (options->V3AuthUseLegacyKey) {
4934 if (c) {
4936 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
4937 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
4938 }
4939 }
4940 }
4941
4942 v3_out->voters = smartlist_new();
4943 smartlist_add(v3_out->voters, voter);
4944 v3_out->cert = authority_cert_dup(cert);
4945 v3_out->routerstatus_list = routerstatuses;
4946 /* Note: networkstatus_digest is unset; it won't get set until we actually
4947 * format the vote. */
4948
4949 return v3_out;
4950}
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:189
#define fmt_addr(a)
Definition address.h:241
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:2475
const or_options_t * get_options(void)
Definition config.c:949
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:2712
STATIC microdesc_t * dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
Definition dirvote.c:3917
static int dirvote_add_signatures_to_all_pending_consensuses(const char *detached_signatures_body, const char *source, const char **msg_out)
Definition dirvote.c:3703
static void dirvote_fetch_missing_signatures(void)
Definition dirvote.c:3074
static void dirvote_clear_pending_consensuses(void)
Definition dirvote.c:3097
STATIC int compare_routerinfo_usefulness(const routerinfo_t *first, const routerinfo_t *second)
Definition dirvote.c:4365
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:4655
static void export_consensus_for_transparency(const char *flavor_name)
Definition dirvote.c:3585
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:3206
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:4519
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:1037
static void remove_flag(smartlist_t *sl, const char *flag)
Definition dirvote.c:1496
static int compare_routerinfo_addrs_by_family(const routerinfo_t *a, const routerinfo_t *b, int family)
Definition dirvote.c:4314
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:4346
static int dirvote_perform_vote(void)
Definition dirvote.c:2986
STATIC char * make_consensus_method_list(int low, int high, const char *separator)
Definition dirvote.c:845
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:4455
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:4142
time_t dirvote_act(const or_options_t *options, time_t now)
Definition dirvote.c:2883
const cached_dir_t * dirvote_get_vote(const char *fp, int flags)
Definition dirvote.c:3871
static void dirvote_clear_votes(int all_votes)
Definition dirvote.c:3111
static char * compute_nth_protocol_set(int n, int n_voters, const smartlist_t *votes)
Definition dirvote.c:1448
static char * pending_consensus_signatures
Definition dirvote.c:2977
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:894
const char * dirvote_get_pending_consensus(consensus_flavor_t flav)
Definition dirvote.c:3848
static int dirvote_publish_consensus(void)
Definition dirvote.c:3795
static const char * get_nth_protocol_set_vote(int n, const networkstatus_t *vote)
Definition dirvote.c:1430
void dirvote_free_all(void)
Definition dirvote.c:3824
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:930
static char * version_from_platform(const char *platform)
Definition dirvote.c:4497
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:3771
static void dirvote_fetch_missing_votes(void)
Definition dirvote.c:3034
STATIC char * networkstatus_get_detached_signatures(smartlist_t *consensuses)
Definition dirvote.c:2773
static char * compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
Definition dirvote.c:869
static char * get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending, int n_flavors)
Definition dirvote.c:2862
uint32_t dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
Definition dirvote.c:4280
static void routers_make_ed_keys_unique(smartlist_t *routers)
Definition dirvote.c:4570
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:1106
static char * list_v3_auth_ids(void)
Definition dirvote.c:3153
#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:2581
static smartlist_t * pending_vote_list
Definition dirvote.c:2967
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:3608
const char DIRVOTE_OPTIONAL_FLAGS[]
Definition dirvote.c:4647
STATIC char * compute_consensus_package_lines(smartlist_t *votes)
Definition dirvote.c:2500
#define MIN_VOTES_FOR_PARAM
Definition dirvote.c:924
STATIC digestmap_t * get_sybil_list_by_ip_version(const smartlist_t *routers, sa_family_t family)
Definition dirvote.c:4415
static smartlist_t * pending_consensus_signature_list
Definition dirvote.c:2981
static void clear_status_flags_on_sybil(routerstatus_t *rs)
Definition dirvote.c:4622
const char * dirvote_get_pending_detached_signatures(void)
Definition dirvote.c:3857
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:4026
static int dirvote_compute_consensuses(void)
Definition dirvote.c:3410
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:1346
STATIC int compare_routerinfo_by_ipv4(const void **a, const void **b)
Definition dirvote.c:4328
static smartlist_t * previous_vote_list
Definition dirvote.c:2970
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:4634
vote_microdesc_hash_t * dirvote_format_all_microdesc_vote_lines(const routerinfo_t *ri, time_t now, smartlist_t *microdescriptors_out)
Definition dirvote.c:4080
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:1526
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_METHOD_TO_PERMIT_ABSENT_TAP_KEYS
Definition dirvote.h:81
#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:86
#define MAX_BW_FILE_HEADERS_LINE_LEN
Definition dirvote.h:94
#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:536
const char * protover_get_required_relay_protocols(void)
Definition protover.c:569
const char * protover_get_required_client_protocols(void)
Definition protover.c:555
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:692
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:880
int protover_all_supported(const char *s, char **missing_out)
Definition protover.c:781
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