TOR: update to v0.2.5.12
[tomato.git] / release / src-rt-6.x.4708 / router / tor / src / or / dirvote.c
blob137d6c1a8c2b583d36a82941834fb3e07ddcb233
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRVOTE_PRIVATE
7 #include "or.h"
8 #include "config.h"
9 #include "directory.h"
10 #include "dirserv.h"
11 #include "dirvote.h"
12 #include "microdesc.h"
13 #include "networkstatus.h"
14 #include "policies.h"
15 #include "rephist.h"
16 #include "router.h"
17 #include "routerlist.h"
18 #include "routerparse.h"
20 /**
21 * \file dirvote.c
22 * \brief Functions to compute directory consensus, and schedule voting.
23 **/
25 /** A consensus that we have built and are appending signatures to. Once it's
26 * time to publish it, it will become an active consensus if it accumulates
27 * enough signatures. */
28 typedef struct pending_consensus_t {
29 /** The body of the consensus that we're currently building. Once we
30 * have it built, it goes into dirserv.c */
31 char *body;
32 /** The parsed in-progress consensus document. */
33 networkstatus_t *consensus;
34 } pending_consensus_t;
36 /* DOCDOC dirvote_add_signatures_to_all_pending_consensuses */
37 static int dirvote_add_signatures_to_all_pending_consensuses(
38 const char *detached_signatures_body,
39 const char *source,
40 const char **msg_out);
41 static int dirvote_add_signatures_to_pending_consensus(
42 pending_consensus_t *pc,
43 ns_detached_signatures_t *sigs,
44 const char *source,
45 int severity,
46 const char **msg_out);
47 static char *list_v3_auth_ids(void);
48 static void dirvote_fetch_missing_votes(void);
49 static void dirvote_fetch_missing_signatures(void);
50 static int dirvote_perform_vote(void);
51 static void dirvote_clear_votes(int all_votes);
52 static int dirvote_compute_consensuses(void);
53 static int dirvote_publish_consensus(void);
54 static char *make_consensus_method_list(int low, int high, const char *sep);
56 /* =====
57 * Voting
58 * =====*/
60 /** Return a new string containing the string representation of the vote in
61 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
62 * For v3 authorities. */
63 STATIC char *
64 format_networkstatus_vote(crypto_pk_t *private_signing_key,
65 networkstatus_t *v3_ns)
67 smartlist_t *chunks;
68 const char *client_versions = NULL, *server_versions = NULL;
69 char fingerprint[FINGERPRINT_LEN+1];
70 char digest[DIGEST_LEN];
71 uint32_t addr;
72 char *client_versions_line = NULL, *server_versions_line = NULL;
73 networkstatus_voter_info_t *voter;
74 char *status = NULL;
76 tor_assert(private_signing_key);
77 tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
79 voter = smartlist_get(v3_ns->voters, 0);
81 addr = voter->addr;
83 base16_encode(fingerprint, sizeof(fingerprint),
84 v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
85 client_versions = v3_ns->client_versions;
86 server_versions = v3_ns->server_versions;
88 if (client_versions) {
89 tor_asprintf(&client_versions_line, "client-versions %s\n",
90 client_versions);
91 } else {
92 client_versions_line = tor_strdup("");
94 if (server_versions) {
95 tor_asprintf(&server_versions_line, "server-versions %s\n",
96 server_versions);
97 } else {
98 server_versions_line = tor_strdup("");
101 chunks = smartlist_new();
103 char published[ISO_TIME_LEN+1];
104 char va[ISO_TIME_LEN+1];
105 char fu[ISO_TIME_LEN+1];
106 char vu[ISO_TIME_LEN+1];
107 char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
108 /* XXXX Abstraction violation: should be pulling a field out of v3_ns.*/
109 char *flag_thresholds = dirserv_get_flag_thresholds_line();
110 char *params;
111 authority_cert_t *cert = v3_ns->cert;
112 char *methods =
113 make_consensus_method_list(1, MAX_SUPPORTED_CONSENSUS_METHOD, " ");
114 format_iso_time(published, v3_ns->published);
115 format_iso_time(va, v3_ns->valid_after);
116 format_iso_time(fu, v3_ns->fresh_until);
117 format_iso_time(vu, v3_ns->valid_until);
119 if (v3_ns->net_params)
120 params = smartlist_join_strings(v3_ns->net_params, " ", 0, NULL);
121 else
122 params = tor_strdup("");
124 tor_assert(cert);
125 smartlist_add_asprintf(chunks,
126 "network-status-version 3\n"
127 "vote-status %s\n"
128 "consensus-methods %s\n"
129 "published %s\n"
130 "valid-after %s\n"
131 "fresh-until %s\n"
132 "valid-until %s\n"
133 "voting-delay %d %d\n"
134 "%s%s" /* versions */
135 "known-flags %s\n"
136 "flag-thresholds %s\n"
137 "params %s\n"
138 "dir-source %s %s %s %s %d %d\n"
139 "contact %s\n",
140 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
141 methods,
142 published, va, fu, vu,
143 v3_ns->vote_seconds, v3_ns->dist_seconds,
144 client_versions_line,
145 server_versions_line,
146 flags,
147 flag_thresholds,
148 params,
149 voter->nickname, fingerprint, voter->address,
150 fmt_addr32(addr), voter->dir_port, voter->or_port,
151 voter->contact);
153 tor_free(params);
154 tor_free(flags);
155 tor_free(flag_thresholds);
156 tor_free(methods);
158 if (!tor_digest_is_zero(voter->legacy_id_digest)) {
159 char fpbuf[HEX_DIGEST_LEN+1];
160 base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
161 smartlist_add_asprintf(chunks, "legacy-dir-key %s\n", fpbuf);
164 smartlist_add(chunks, tor_strndup(cert->cache_info.signed_descriptor_body,
165 cert->cache_info.signed_descriptor_len));
168 SMARTLIST_FOREACH_BEGIN(v3_ns->routerstatus_list, vote_routerstatus_t *,
169 vrs) {
170 char *rsf;
171 vote_microdesc_hash_t *h;
172 rsf = routerstatus_format_entry(&vrs->status,
173 vrs->version, NS_V3_VOTE, vrs);
174 if (rsf)
175 smartlist_add(chunks, rsf);
177 for (h = vrs->microdesc; h; h = h->next) {
178 smartlist_add(chunks, tor_strdup(h->microdesc_hash_line));
180 } SMARTLIST_FOREACH_END(vrs);
182 smartlist_add(chunks, tor_strdup("directory-footer\n"));
184 /* The digest includes everything up through the space after
185 * directory-signature. (Yuck.) */
186 crypto_digest_smartlist(digest, DIGEST_LEN, chunks,
187 "directory-signature ", DIGEST_SHA1);
190 char signing_key_fingerprint[FINGERPRINT_LEN+1];
191 if (crypto_pk_get_fingerprint(private_signing_key,
192 signing_key_fingerprint, 0)<0) {
193 log_warn(LD_BUG, "Unable to get fingerprint for signing key");
194 goto err;
197 smartlist_add_asprintf(chunks, "directory-signature %s %s\n", fingerprint,
198 signing_key_fingerprint);
201 note_crypto_pk_op(SIGN_DIR);
203 char *sig = router_get_dirobj_signature(digest, DIGEST_LEN,
204 private_signing_key);
205 if (!sig) {
206 log_warn(LD_BUG, "Unable to sign networkstatus vote.");
207 goto err;
209 smartlist_add(chunks, sig);
212 status = smartlist_join_strings(chunks, "", 0, NULL);
215 networkstatus_t *v;
216 if (!(v = networkstatus_parse_vote_from_string(status, NULL,
217 v3_ns->type))) {
218 log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
219 "<<%s>>",
220 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
221 goto err;
223 networkstatus_vote_free(v);
226 goto done;
228 err:
229 tor_free(status);
230 done:
231 tor_free(client_versions_line);
232 tor_free(server_versions_line);
233 if (chunks) {
234 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
235 smartlist_free(chunks);
237 return status;
240 /* =====
241 * Consensus generation
242 * ===== */
244 /** Given a vote <b>vote</b> (not a consensus!), return its associated
245 * networkstatus_voter_info_t. */
246 static networkstatus_voter_info_t *
247 get_voter(const networkstatus_t *vote)
249 tor_assert(vote);
250 tor_assert(vote->type == NS_TYPE_VOTE);
251 tor_assert(vote->voters);
252 tor_assert(smartlist_len(vote->voters) == 1);
253 return smartlist_get(vote->voters, 0);
256 /** Return the signature made by <b>voter</b> using the algorithm
257 * <b>alg</b>, or NULL if none is found. */
258 document_signature_t *
259 voter_get_sig_by_algorithm(const networkstatus_voter_info_t *voter,
260 digest_algorithm_t alg)
262 if (!voter->sigs)
263 return NULL;
264 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
265 if (sig->alg == alg)
266 return sig);
267 return NULL;
270 /** Temporary structure used in constructing a list of dir-source entries
271 * for a consensus. One of these is generated for every vote, and one more
272 * for every legacy key in each vote. */
273 typedef struct dir_src_ent_t {
274 networkstatus_t *v;
275 const char *digest;
276 int is_legacy;
277 } dir_src_ent_t;
279 /** Helper for sorting networkstatus_t votes (not consensuses) by the
280 * hash of their voters' identity digests. */
281 static int
282 compare_votes_by_authority_id_(const void **_a, const void **_b)
284 const networkstatus_t *a = *_a, *b = *_b;
285 return fast_memcmp(get_voter(a)->identity_digest,
286 get_voter(b)->identity_digest, DIGEST_LEN);
289 /** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
290 * their identity digests, and return -1, 0, or 1 depending on their
291 * ordering */
292 static int
293 compare_dir_src_ents_by_authority_id_(const void **_a, const void **_b)
295 const dir_src_ent_t *a = *_a, *b = *_b;
296 const networkstatus_voter_info_t *a_v = get_voter(a->v),
297 *b_v = get_voter(b->v);
298 const char *a_id, *b_id;
299 a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
300 b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;
302 return fast_memcmp(a_id, b_id, DIGEST_LEN);
305 /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
306 * that occurs more than <b>min</b> times. */
307 static void
308 get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
310 char *cur = NULL;
311 int count = 0;
312 SMARTLIST_FOREACH_BEGIN(in, char *, cp) {
313 if (cur && !strcmp(cp, cur)) {
314 ++count;
315 } else {
316 if (count > min)
317 smartlist_add(out, cur);
318 cur = cp;
319 count = 1;
321 } SMARTLIST_FOREACH_END(cp);
322 if (count > min)
323 smartlist_add(out, cur);
326 /** Given a sorted list of strings <b>lst</b>, return the member that appears
327 * most. Break ties in favor of later-occurring members. */
328 #define get_most_frequent_member(lst) \
329 smartlist_get_most_frequent_string(lst)
331 /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
332 * that come from the same routerinfo, with the same derived elements.
334 static int
335 compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
337 int r;
338 tor_assert(a);
339 tor_assert(b);
341 if ((r = fast_memcmp(a->status.identity_digest, b->status.identity_digest,
342 DIGEST_LEN)))
343 return r;
344 if ((r = fast_memcmp(a->status.descriptor_digest,
345 b->status.descriptor_digest,
346 DIGEST_LEN)))
347 return r;
348 if ((r = (int)(b->status.published_on - a->status.published_on)))
349 return r;
350 if ((r = strcmp(b->status.nickname, a->status.nickname)))
351 return r;
352 if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
353 return r;
354 if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
355 return r;
356 if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
357 return r;
358 return 0;
361 /** Helper for sorting routerlists based on compare_vote_rs. */
362 static int
363 compare_vote_rs_(const void **_a, const void **_b)
365 const vote_routerstatus_t *a = *_a, *b = *_b;
366 return compare_vote_rs(a,b);
369 /** Helper for sorting OR ports. */
370 static int
371 compare_orports_(const void **_a, const void **_b)
373 const tor_addr_port_t *a = *_a, *b = *_b;
374 int r;
376 if ((r = tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
377 return r;
378 if ((r = (((int) b->port) - ((int) a->port))))
379 return r;
381 return 0;
384 /** Given a list of vote_routerstatus_t, all for the same router identity,
385 * return whichever is most frequent, breaking ties in favor of more
386 * recently published vote_routerstatus_t and in case of ties there,
387 * in favor of smaller descriptor digest.
389 static vote_routerstatus_t *
390 compute_routerstatus_consensus(smartlist_t *votes, int consensus_method,
391 char *microdesc_digest256_out,
392 tor_addr_port_t *best_alt_orport_out)
394 vote_routerstatus_t *most = NULL, *cur = NULL;
395 int most_n = 0, cur_n = 0;
396 time_t most_published = 0;
398 /* compare_vote_rs_() sorts the items by identity digest (all the same),
399 * then by SD digest. That way, if we have a tie that the published_on
400 * date cannot tie, we use the descriptor with the smaller digest.
402 smartlist_sort(votes, compare_vote_rs_);
403 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
404 if (cur && !compare_vote_rs(cur, rs)) {
405 ++cur_n;
406 } else {
407 if (cur && (cur_n > most_n ||
408 (cur_n == most_n &&
409 cur->status.published_on > most_published))) {
410 most = cur;
411 most_n = cur_n;
412 most_published = cur->status.published_on;
414 cur_n = 1;
415 cur = rs;
417 } SMARTLIST_FOREACH_END(rs);
419 if (cur_n > most_n ||
420 (cur && cur_n == most_n && cur->status.published_on > most_published)) {
421 most = cur;
422 most_n = cur_n;
423 most_published = cur->status.published_on;
426 tor_assert(most);
428 /* If we're producing "a" lines, vote on potential alternative (sets
429 * of) OR port(s) in the winning routerstatuses.
431 * XXX prop186 There's at most one alternative OR port (_the_ IPv6
432 * port) for now. */
433 if (consensus_method >= MIN_METHOD_FOR_A_LINES && best_alt_orport_out) {
434 smartlist_t *alt_orports = smartlist_new();
435 const tor_addr_port_t *most_alt_orport = NULL;
437 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
438 tor_assert(rs);
439 if (compare_vote_rs(most, rs) == 0 &&
440 !tor_addr_is_null(&rs->status.ipv6_addr)
441 && rs->status.ipv6_orport) {
442 smartlist_add(alt_orports, tor_addr_port_new(&rs->status.ipv6_addr,
443 rs->status.ipv6_orport));
445 } SMARTLIST_FOREACH_END(rs);
447 smartlist_sort(alt_orports, compare_orports_);
448 most_alt_orport = smartlist_get_most_frequent(alt_orports,
449 compare_orports_);
450 if (most_alt_orport) {
451 memcpy(best_alt_orport_out, most_alt_orport, sizeof(tor_addr_port_t));
452 log_debug(LD_DIR, "\"a\" line winner for %s is %s",
453 most->status.nickname,
454 fmt_addrport(&most_alt_orport->addr, most_alt_orport->port));
457 SMARTLIST_FOREACH(alt_orports, tor_addr_port_t *, ap, tor_free(ap));
458 smartlist_free(alt_orports);
461 if (consensus_method >= MIN_METHOD_FOR_MICRODESC &&
462 microdesc_digest256_out) {
463 smartlist_t *digests = smartlist_new();
464 const char *best_microdesc_digest;
465 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
466 char d[DIGEST256_LEN];
467 if (compare_vote_rs(rs, most))
468 continue;
469 if (!vote_routerstatus_find_microdesc_hash(d, rs, consensus_method,
470 DIGEST_SHA256))
471 smartlist_add(digests, tor_memdup(d, sizeof(d)));
472 } SMARTLIST_FOREACH_END(rs);
473 smartlist_sort_digests256(digests);
474 best_microdesc_digest = smartlist_get_most_frequent_digest256(digests);
475 if (best_microdesc_digest)
476 memcpy(microdesc_digest256_out, best_microdesc_digest, DIGEST256_LEN);
477 SMARTLIST_FOREACH(digests, char *, cp, tor_free(cp));
478 smartlist_free(digests);
481 return most;
484 /** Sorting helper: compare two strings based on their values as base-ten
485 * positive integers. (Non-integers are treated as prior to all integers, and
486 * compared lexically.) */
487 static int
488 cmp_int_strings_(const void **_a, const void **_b)
490 const char *a = *_a, *b = *_b;
491 int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
492 int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
493 if (ai<bi) {
494 return -1;
495 } else if (ai==bi) {
496 if (ai == 0) /* Parsing failed. */
497 return strcmp(a, b);
498 return 0;
499 } else {
500 return 1;
504 /** Given a list of networkstatus_t votes, determine and return the number of
505 * the highest consensus method that is supported by 2/3 of the voters. */
506 static int
507 compute_consensus_method(smartlist_t *votes)
509 smartlist_t *all_methods = smartlist_new();
510 smartlist_t *acceptable_methods = smartlist_new();
511 smartlist_t *tmp = smartlist_new();
512 int min = (smartlist_len(votes) * 2) / 3;
513 int n_ok;
514 int result;
515 SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
517 tor_assert(vote->supported_methods);
518 smartlist_add_all(tmp, vote->supported_methods);
519 smartlist_sort(tmp, cmp_int_strings_);
520 smartlist_uniq(tmp, cmp_int_strings_, NULL);
521 smartlist_add_all(all_methods, tmp);
522 smartlist_clear(tmp);
525 smartlist_sort(all_methods, cmp_int_strings_);
526 get_frequent_members(acceptable_methods, all_methods, min);
527 n_ok = smartlist_len(acceptable_methods);
528 if (n_ok) {
529 const char *best = smartlist_get(acceptable_methods, n_ok-1);
530 result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
531 } else {
532 result = 1;
534 smartlist_free(tmp);
535 smartlist_free(all_methods);
536 smartlist_free(acceptable_methods);
537 return result;
540 /** Return true iff <b>method</b> is a consensus method that we support. */
541 static int
542 consensus_method_is_supported(int method)
544 return (method >= 1) && (method <= MAX_SUPPORTED_CONSENSUS_METHOD);
547 /** Return a newly allocated string holding the numbers between low and high
548 * (inclusive) that are supported consensus methods. */
549 static char *
550 make_consensus_method_list(int low, int high, const char *separator)
552 char *list;
554 int i;
555 smartlist_t *lst;
556 lst = smartlist_new();
557 for (i = low; i <= high; ++i) {
558 if (!consensus_method_is_supported(i))
559 continue;
560 smartlist_add_asprintf(lst, "%d", i);
562 list = smartlist_join_strings(lst, separator, 0, NULL);
563 tor_assert(list);
564 SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
565 smartlist_free(lst);
566 return list;
569 /** Helper: given <b>lst</b>, a list of version strings such that every
570 * version appears once for every versioning voter who recommends it, return a
571 * newly allocated string holding the resulting client-versions or
572 * server-versions list. May change contents of <b>lst</b> */
573 static char *
574 compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
576 int min = n_versioning / 2;
577 smartlist_t *good = smartlist_new();
578 char *result;
579 sort_version_list(lst, 0);
580 get_frequent_members(good, lst, min);
581 result = smartlist_join_strings(good, ",", 0, NULL);
582 smartlist_free(good);
583 return result;
586 /** Minimum number of directory authorities voting for a parameter to
587 * include it in the consensus, if consensus method 12 or later is to be
588 * used. See proposal 178 for details. */
589 #define MIN_VOTES_FOR_PARAM 3
591 /** Helper: given a list of valid networkstatus_t, return a new string
592 * containing the contents of the consensus network parameter set.
594 STATIC char *
595 dirvote_compute_params(smartlist_t *votes, int method, int total_authorities)
597 int i;
598 int32_t *vals;
600 int cur_param_len;
601 const char *cur_param;
602 const char *eq;
603 char *result;
605 const int n_votes = smartlist_len(votes);
606 smartlist_t *output;
607 smartlist_t *param_list = smartlist_new();
609 /* We require that the parameter lists in the votes are well-formed: that
610 is, that their keywords are unique and sorted, and that their values are
611 between INT32_MIN and INT32_MAX inclusive. This should be guaranteed by
612 the parsing code. */
614 vals = tor_malloc(sizeof(int)*n_votes);
616 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
617 if (!v->net_params)
618 continue;
619 smartlist_add_all(param_list, v->net_params);
620 } SMARTLIST_FOREACH_END(v);
622 if (smartlist_len(param_list) == 0) {
623 tor_free(vals);
624 smartlist_free(param_list);
625 return NULL;
628 smartlist_sort_strings(param_list);
629 i = 0;
630 cur_param = smartlist_get(param_list, 0);
631 eq = strchr(cur_param, '=');
632 tor_assert(eq);
633 cur_param_len = (int)(eq+1 - cur_param);
635 output = smartlist_new();
637 SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
638 const char *next_param;
639 int ok=0;
640 eq = strchr(param, '=');
641 tor_assert(i<n_votes); /* Make sure we prevented vote-stuffing. */
642 vals[i++] = (int32_t)
643 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
644 tor_assert(ok); /* Already checked these when parsing. */
646 if (param_sl_idx+1 == smartlist_len(param_list))
647 next_param = NULL;
648 else
649 next_param = smartlist_get(param_list, param_sl_idx+1);
650 if (!next_param || strncmp(next_param, param, cur_param_len)) {
651 /* We've reached the end of a series. */
652 /* Make sure enough authorities voted on this param, unless the
653 * the consensus method we use is too old for that. */
654 if (method < MIN_METHOD_FOR_MAJORITY_PARAMS ||
655 i > total_authorities/2 ||
656 i >= MIN_VOTES_FOR_PARAM) {
657 int32_t median = median_int32(vals, i);
658 char *out_string = tor_malloc(64+cur_param_len);
659 memcpy(out_string, param, cur_param_len);
660 tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
661 smartlist_add(output, out_string);
664 i = 0;
665 if (next_param) {
666 eq = strchr(next_param, '=');
667 cur_param_len = (int)(eq+1 - next_param);
670 } SMARTLIST_FOREACH_END(param);
672 result = smartlist_join_strings(output, " ", 0, NULL);
673 SMARTLIST_FOREACH(output, char *, cp, tor_free(cp));
674 smartlist_free(output);
675 smartlist_free(param_list);
676 tor_free(vals);
677 return result;
680 #define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
681 ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
682 (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
683 (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
684 (g) >= 0 && (g) <= (mx))
686 #define CHECK_EQ(a, b, margin) \
687 ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))
689 typedef enum {
690 BW_WEIGHTS_NO_ERROR = 0,
691 BW_WEIGHTS_RANGE_ERROR = 1,
692 BW_WEIGHTS_SUMG_ERROR = 2,
693 BW_WEIGHTS_SUME_ERROR = 3,
694 BW_WEIGHTS_SUMD_ERROR = 4,
695 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
696 BW_WEIGHTS_BALANCE_EG_ERROR = 6
697 } bw_weights_error_t;
700 * Verify that any weightings satisfy the balanced formulas.
702 static bw_weights_error_t
703 networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
704 int64_t Wme, int64_t Wmd, int64_t Wee,
705 int64_t Wed, int64_t scale, int64_t G,
706 int64_t M, int64_t E, int64_t D, int64_t T,
707 int64_t margin, int do_balance) {
708 bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;
710 // Wed + Wmd + Wgd == 1
711 if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
712 berr = BW_WEIGHTS_SUMD_ERROR;
713 goto out;
716 // Wmg + Wgg == 1
717 if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
718 berr = BW_WEIGHTS_SUMG_ERROR;
719 goto out;
722 // Wme + Wee == 1
723 if (!CHECK_EQ(Wme + Wee, scale, margin)) {
724 berr = BW_WEIGHTS_SUME_ERROR;
725 goto out;
728 // Verify weights within range 0->1
729 if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
730 berr = BW_WEIGHTS_RANGE_ERROR;
731 goto out;
734 if (do_balance) {
735 // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
736 if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
737 berr = BW_WEIGHTS_BALANCE_EG_ERROR;
738 goto out;
741 // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
742 if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
743 (margin*T)/3)) {
744 berr = BW_WEIGHTS_BALANCE_MID_ERROR;
745 goto out;
749 out:
750 if (berr) {
751 log_info(LD_DIR,
752 "Bw weight mismatch %d. G="I64_FORMAT" M="I64_FORMAT
753 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
754 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
755 " Wgd=%d Wgg=%d Wme=%d Wmg=%d",
756 berr,
757 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
758 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
759 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
760 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg);
763 return berr;
767 * This function computes the bandwidth weights for consensus method 10.
769 * It returns true if weights could be computed, false otherwise.
771 static int
772 networkstatus_compute_bw_weights_v10(smartlist_t *chunks, int64_t G,
773 int64_t M, int64_t E, int64_t D,
774 int64_t T, int64_t weight_scale)
776 bw_weights_error_t berr = 0;
777 int64_t Wgg = -1, Wgd = -1;
778 int64_t Wmg = -1, Wme = -1, Wmd = -1;
779 int64_t Wed = -1, Wee = -1;
780 const char *casename;
782 if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
783 log_warn(LD_DIR, "Consensus with empty bandwidth: "
784 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
785 " D="I64_FORMAT" T="I64_FORMAT,
786 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
787 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
788 return 0;
792 * Computed from cases in 3.4.3 of dir-spec.txt
794 * 1. Neither are scarce
795 * 2. Both Guard and Exit are scarce
796 * a. R+D <= S
797 * b. R+D > S
798 * 3. One of Guard or Exit is scarce
799 * a. S+D < T/3
800 * b. S+D >= T/3
802 if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
803 /* Case 1: Neither are scarce. */
804 casename = "Case 1 (Wgd=Wmd=Wed)";
805 Wgd = weight_scale/3;
806 Wed = weight_scale/3;
807 Wmd = weight_scale/3;
808 Wee = (weight_scale*(E+G+M))/(3*E);
809 Wme = weight_scale - Wee;
810 Wmg = (weight_scale*(2*G-E-M))/(3*G);
811 Wgg = weight_scale - Wmg;
813 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
814 weight_scale, G, M, E, D, T, 10, 1);
816 if (berr) {
817 log_warn(LD_DIR,
818 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
819 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
820 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
821 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
822 berr, casename,
823 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
824 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
825 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
826 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
827 return 0;
829 } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
830 int64_t R = MIN(E, G);
831 int64_t S = MAX(E, G);
833 * Case 2: Both Guards and Exits are scarce
834 * Balance D between E and G, depending upon
835 * D capacity and scarcity.
837 if (R+D < S) { // Subcase a
838 Wgg = weight_scale;
839 Wee = weight_scale;
840 Wmg = 0;
841 Wme = 0;
842 Wmd = 0;
843 if (E < G) {
844 casename = "Case 2a (E scarce)";
845 Wed = weight_scale;
846 Wgd = 0;
847 } else { /* E >= G */
848 casename = "Case 2a (G scarce)";
849 Wed = 0;
850 Wgd = weight_scale;
852 } else { // Subcase b: R+D >= S
853 casename = "Case 2b1 (Wgg=1, Wmd=Wgd)";
854 Wee = (weight_scale*(E - G + M))/E;
855 Wed = (weight_scale*(D - 2*E + 4*G - 2*M))/(3*D);
856 Wme = (weight_scale*(G-M))/E;
857 Wmg = 0;
858 Wgg = weight_scale;
859 Wmd = (weight_scale - Wed)/2;
860 Wgd = (weight_scale - Wed)/2;
862 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
863 weight_scale, G, M, E, D, T, 10, 1);
865 if (berr) {
866 casename = "Case 2b2 (Wgg=1, Wee=1)";
867 Wgg = weight_scale;
868 Wee = weight_scale;
869 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
870 Wmd = (weight_scale*(D - 2*M + G + E))/(3*D);
871 Wme = 0;
872 Wmg = 0;
874 if (Wmd < 0) { // Can happen if M > T/3
875 casename = "Case 2b3 (Wmd=0)";
876 Wmd = 0;
877 log_warn(LD_DIR,
878 "Too much Middle bandwidth on the network to calculate "
879 "balanced bandwidth-weights. Consider increasing the "
880 "number of Guard nodes by lowering the requirements.");
882 Wgd = weight_scale - Wed - Wmd;
883 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
884 Wed, weight_scale, G, M, E, D, T, 10, 1);
886 if (berr != BW_WEIGHTS_NO_ERROR &&
887 berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
888 log_warn(LD_DIR,
889 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
890 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
891 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
892 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
893 berr, casename,
894 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
895 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
896 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
897 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
898 return 0;
901 } else { // if (E < T/3 || G < T/3) {
902 int64_t S = MIN(E, G);
903 // Case 3: Exactly one of Guard or Exit is scarce
904 if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
905 log_warn(LD_BUG,
906 "Bw-Weights Case 3 v10 but with G="I64_FORMAT" M="
907 I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
908 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
909 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
912 if (3*(S+D) < T) { // Subcase a: S+D < T/3
913 if (G < E) {
914 casename = "Case 3a (G scarce)";
915 Wgg = Wgd = weight_scale;
916 Wmd = Wed = Wmg = 0;
917 // Minor subcase, if E is more scarce than M,
918 // keep its bandwidth in place.
919 if (E < M) Wme = 0;
920 else Wme = (weight_scale*(E-M))/(2*E);
921 Wee = weight_scale-Wme;
922 } else { // G >= E
923 casename = "Case 3a (E scarce)";
924 Wee = Wed = weight_scale;
925 Wmd = Wgd = Wme = 0;
926 // Minor subcase, if G is more scarce than M,
927 // keep its bandwidth in place.
928 if (G < M) Wmg = 0;
929 else Wmg = (weight_scale*(G-M))/(2*G);
930 Wgg = weight_scale-Wmg;
932 } else { // Subcase b: S+D >= T/3
933 // D != 0 because S+D >= T/3
934 if (G < E) {
935 casename = "Case 3bg (G scarce, Wgg=1, Wmd == Wed)";
936 Wgg = weight_scale;
937 Wgd = (weight_scale*(D - 2*G + E + M))/(3*D);
938 Wmg = 0;
939 Wee = (weight_scale*(E+M))/(2*E);
940 Wme = weight_scale - Wee;
941 Wmd = (weight_scale - Wgd)/2;
942 Wed = (weight_scale - Wgd)/2;
944 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
945 Wed, weight_scale, G, M, E, D, T, 10, 1);
946 } else { // G >= E
947 casename = "Case 3be (E scarce, Wee=1, Wmd == Wgd)";
948 Wee = weight_scale;
949 Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
950 Wme = 0;
951 Wgg = (weight_scale*(G+M))/(2*G);
952 Wmg = weight_scale - Wgg;
953 Wmd = (weight_scale - Wed)/2;
954 Wgd = (weight_scale - Wed)/2;
956 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
957 Wed, weight_scale, G, M, E, D, T, 10, 1);
959 if (berr) {
960 log_warn(LD_DIR,
961 "Bw Weights error %d for %s v10. G="I64_FORMAT" M="I64_FORMAT
962 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT
963 " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
964 " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
965 berr, casename,
966 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
967 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T),
968 (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
969 (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
970 return 0;
975 /* We cast down the weights to 32 bit ints on the assumption that
976 * weight_scale is ~= 10000. We need to ensure a rogue authority
977 * doesn't break this assumption to rig our weights */
978 tor_assert(0 < weight_scale && weight_scale <= INT32_MAX);
981 * Provide Wgm=Wgg, Wmm=1, Wem=Wee, Weg=Wed. May later determine
982 * that middle nodes need different bandwidth weights for dirport traffic,
983 * or that weird exit policies need special weight, or that bridges
984 * need special weight.
986 * NOTE: This list is sorted.
988 smartlist_add_asprintf(chunks,
989 "bandwidth-weights Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
990 "Wdb=%d "
991 "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
992 "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
993 "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
994 (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
995 (int)weight_scale,
996 (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
997 (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
998 (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
1000 log_notice(LD_CIRC, "Computed bandwidth weights for %s with v10: "
1001 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1002 " T="I64_FORMAT,
1003 casename,
1004 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1005 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1006 return 1;
1009 * This function computes the bandwidth weights for consensus method 9.
1011 * It has been obsoleted in favor of consensus method 10.
1013 static void
1014 networkstatus_compute_bw_weights_v9(smartlist_t *chunks, int64_t G, int64_t M,
1015 int64_t E, int64_t D, int64_t T,
1016 int64_t weight_scale)
1018 int64_t Wgg = -1, Wgd = -1;
1019 int64_t Wmg = -1, Wme = -1, Wmd = -1;
1020 int64_t Wed = -1, Wee = -1;
1021 const char *casename;
1023 if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
1024 log_warn(LD_DIR, "Consensus with empty bandwidth: "
1025 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
1026 " D="I64_FORMAT" T="I64_FORMAT,
1027 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1028 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1029 return;
1033 * Computed from cases in 3.4.3 of dir-spec.txt
1035 * 1. Neither are scarce
1036 * 2. Both Guard and Exit are scarce
1037 * a. R+D <= S
1038 * b. R+D > S
1039 * 3. One of Guard or Exit is scarce
1040 * a. S+D < T/3
1041 * b. S+D >= T/3
1043 if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
1044 bw_weights_error_t berr = 0;
1045 /* Case 1: Neither are scarce.
1047 * Attempt to ensure that we have a large amount of exit bandwidth
1048 * in the middle position.
1050 casename = "Case 1 (Wme*E = Wmd*D)";
1051 Wgg = (weight_scale*(D+E+G+M))/(3*G);
1052 if (D==0) Wmd = 0;
1053 else Wmd = (weight_scale*(2*D + 2*E - G - M))/(6*D);
1054 Wme = (weight_scale*(2*D + 2*E - G - M))/(6*E);
1055 Wee = (weight_scale*(-2*D + 4*E + G + M))/(6*E);
1056 Wgd = 0;
1057 Wmg = weight_scale - Wgg;
1058 Wed = weight_scale - Wmd;
1060 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
1061 weight_scale, G, M, E, D, T, 10, 1);
1063 if (berr) {
1064 log_warn(LD_DIR, "Bw Weights error %d for case %s. "
1065 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
1066 " D="I64_FORMAT" T="I64_FORMAT,
1067 berr, casename,
1068 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1069 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1071 } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
1072 int64_t R = MIN(E, G);
1073 int64_t S = MAX(E, G);
1075 * Case 2: Both Guards and Exits are scarce
1076 * Balance D between E and G, depending upon
1077 * D capacity and scarcity.
1079 if (R+D < S) { // Subcase a
1080 Wgg = weight_scale;
1081 Wee = weight_scale;
1082 Wmg = 0;
1083 Wme = 0;
1084 Wmd = 0;
1085 if (E < G) {
1086 casename = "Case 2a (E scarce)";
1087 Wed = weight_scale;
1088 Wgd = 0;
1089 } else { /* E >= G */
1090 casename = "Case 2a (G scarce)";
1091 Wed = 0;
1092 Wgd = weight_scale;
1094 } else { // Subcase b: R+D > S
1095 bw_weights_error_t berr = 0;
1096 casename = "Case 2b (Wme*E == Wmd*D)";
1097 if (D != 0) {
1098 Wgg = weight_scale;
1099 Wgd = (weight_scale*(D + E - 2*G + M))/(3*D); // T/3 >= G (Ok)
1100 Wmd = (weight_scale*(D + E + G - 2*M))/(6*D); // T/3 >= M
1101 Wme = (weight_scale*(D + E + G - 2*M))/(6*E);
1102 Wee = (weight_scale*(-D + 5*E - G + 2*M))/(6*E); // 2E+M >= T/3
1103 Wmg = 0;
1104 Wed = weight_scale - Wgd - Wmd;
1106 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
1107 weight_scale, G, M, E, D, T, 10, 1);
1110 if (D == 0 || berr) { // Can happen if M > T/3
1111 casename = "Case 2b (E=G)";
1112 Wgg = weight_scale;
1113 Wee = weight_scale;
1114 Wmg = 0;
1115 Wme = 0;
1116 Wmd = 0;
1117 if (D == 0) Wgd = 0;
1118 else Wgd = (weight_scale*(D+E-G))/(2*D);
1119 Wed = weight_scale - Wgd;
1120 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1121 Wed, weight_scale, G, M, E, D, T, 10, 1);
1123 if (berr != BW_WEIGHTS_NO_ERROR &&
1124 berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
1125 log_warn(LD_DIR, "Bw Weights error %d for case %s. "
1126 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
1127 " D="I64_FORMAT" T="I64_FORMAT,
1128 berr, casename,
1129 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1130 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1133 } else { // if (E < T/3 || G < T/3) {
1134 int64_t S = MIN(E, G);
1135 // Case 3: Exactly one of Guard or Exit is scarce
1136 if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
1137 log_warn(LD_BUG,
1138 "Bw-Weights Case 3 but with G="I64_FORMAT" M="
1139 I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
1140 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1141 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1144 if (3*(S+D) < T) { // Subcase a: S+D < T/3
1145 if (G < E) {
1146 casename = "Case 3a (G scarce)";
1147 Wgg = Wgd = weight_scale;
1148 Wmd = Wed = Wmg = 0;
1149 // Minor subcase, if E is more scarce than M,
1150 // keep its bandwidth in place.
1151 if (E < M) Wme = 0;
1152 else Wme = (weight_scale*(E-M))/(2*E);
1153 Wee = weight_scale-Wme;
1154 } else { // G >= E
1155 casename = "Case 3a (E scarce)";
1156 Wee = Wed = weight_scale;
1157 Wmd = Wgd = Wme = 0;
1158 // Minor subcase, if G is more scarce than M,
1159 // keep its bandwidth in place.
1160 if (G < M) Wmg = 0;
1161 else Wmg = (weight_scale*(G-M))/(2*G);
1162 Wgg = weight_scale-Wmg;
1164 } else { // Subcase b: S+D >= T/3
1165 bw_weights_error_t berr = 0;
1166 // D != 0 because S+D >= T/3
1167 if (G < E) {
1168 casename = "Case 3b (G scarce, Wme*E == Wmd*D)";
1169 Wgd = (weight_scale*(D + E - 2*G + M))/(3*D);
1170 Wmd = (weight_scale*(D + E + G - 2*M))/(6*D);
1171 Wme = (weight_scale*(D + E + G - 2*M))/(6*E);
1172 Wee = (weight_scale*(-D + 5*E - G + 2*M))/(6*E);
1173 Wgg = weight_scale;
1174 Wmg = 0;
1175 Wed = weight_scale - Wgd - Wmd;
1177 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1178 Wed, weight_scale, G, M, E, D, T, 10, 1);
1179 } else { // G >= E
1180 casename = "Case 3b (E scarce, Wme*E == Wmd*D)";
1181 Wgg = (weight_scale*(D + E + G + M))/(3*G);
1182 Wmd = (weight_scale*(2*D + 2*E - G - M))/(6*D);
1183 Wme = (weight_scale*(2*D + 2*E - G - M))/(6*E);
1184 Wee = (weight_scale*(-2*D + 4*E + G + M))/(6*E);
1185 Wgd = 0;
1186 Wmg = weight_scale - Wgg;
1187 Wed = weight_scale - Wmd;
1189 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
1190 Wed, weight_scale, G, M, E, D, T, 10, 1);
1192 if (berr) {
1193 log_warn(LD_DIR, "Bw Weights error %d for case %s. "
1194 "G="I64_FORMAT" M="I64_FORMAT
1195 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
1196 berr, casename,
1197 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1198 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1203 /* We cast down the weights to 32 bit ints on the assumption that
1204 * weight_scale is ~= 10000. We need to ensure a rogue authority
1205 * doesn't break this assumption to rig our weights */
1206 tor_assert(0 < weight_scale && weight_scale <= INT32_MAX);
1208 if (Wgg < 0 || Wgg > weight_scale) {
1209 log_warn(LD_DIR, "Bw %s: Wgg="I64_FORMAT"! G="I64_FORMAT
1210 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1211 " T="I64_FORMAT,
1212 casename, I64_PRINTF_ARG(Wgg),
1213 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1214 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1216 Wgg = MAX(MIN(Wgg, weight_scale), 0);
1218 if (Wgd < 0 || Wgd > weight_scale) {
1219 log_warn(LD_DIR, "Bw %s: Wgd="I64_FORMAT"! G="I64_FORMAT
1220 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1221 " T="I64_FORMAT,
1222 casename, I64_PRINTF_ARG(Wgd),
1223 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1224 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1225 Wgd = MAX(MIN(Wgd, weight_scale), 0);
1227 if (Wmg < 0 || Wmg > weight_scale) {
1228 log_warn(LD_DIR, "Bw %s: Wmg="I64_FORMAT"! G="I64_FORMAT
1229 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1230 " T="I64_FORMAT,
1231 casename, I64_PRINTF_ARG(Wmg),
1232 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1233 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1234 Wmg = MAX(MIN(Wmg, weight_scale), 0);
1236 if (Wme < 0 || Wme > weight_scale) {
1237 log_warn(LD_DIR, "Bw %s: Wme="I64_FORMAT"! G="I64_FORMAT
1238 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1239 " T="I64_FORMAT,
1240 casename, I64_PRINTF_ARG(Wme),
1241 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1242 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1243 Wme = MAX(MIN(Wme, weight_scale), 0);
1245 if (Wmd < 0 || Wmd > weight_scale) {
1246 log_warn(LD_DIR, "Bw %s: Wmd="I64_FORMAT"! G="I64_FORMAT
1247 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1248 " T="I64_FORMAT,
1249 casename, I64_PRINTF_ARG(Wmd),
1250 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1251 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1252 Wmd = MAX(MIN(Wmd, weight_scale), 0);
1254 if (Wee < 0 || Wee > weight_scale) {
1255 log_warn(LD_DIR, "Bw %s: Wee="I64_FORMAT"! G="I64_FORMAT
1256 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1257 " T="I64_FORMAT,
1258 casename, I64_PRINTF_ARG(Wee),
1259 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1260 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1261 Wee = MAX(MIN(Wee, weight_scale), 0);
1263 if (Wed < 0 || Wed > weight_scale) {
1264 log_warn(LD_DIR, "Bw %s: Wed="I64_FORMAT"! G="I64_FORMAT
1265 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1266 " T="I64_FORMAT,
1267 casename, I64_PRINTF_ARG(Wed),
1268 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1269 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1270 Wed = MAX(MIN(Wed, weight_scale), 0);
1273 // Add consensus weight keywords
1274 smartlist_add(chunks, tor_strdup("bandwidth-weights "));
1276 * Provide Wgm=Wgg, Wmm=1, Wem=Wee, Weg=Wed. May later determine
1277 * that middle nodes need different bandwidth weights for dirport traffic,
1278 * or that weird exit policies need special weight, or that bridges
1279 * need special weight.
1281 * NOTE: This list is sorted.
1283 smartlist_add_asprintf(chunks,
1284 "Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
1285 "Wdb=%d "
1286 "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
1287 "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
1288 "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
1289 (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
1290 (int)weight_scale,
1291 (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
1292 (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
1293 (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
1295 log_notice(LD_CIRC, "Computed bandwidth weights for %s with v9: "
1296 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1297 " T="I64_FORMAT,
1298 casename,
1299 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1300 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1303 /** Given a list of vote networkstatus_t in <b>votes</b>, our public
1304 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
1305 * and the number of <b>total_authorities</b> that we believe exist in our
1306 * voting quorum, generate the text of a new v3 consensus vote, and return the
1307 * value in a newly allocated string.
1309 * Note: this function DOES NOT check whether the votes are from
1310 * recognized authorities. (dirvote_add_vote does that.) */
1311 char *
1312 networkstatus_compute_consensus(smartlist_t *votes,
1313 int total_authorities,
1314 crypto_pk_t *identity_key,
1315 crypto_pk_t *signing_key,
1316 const char *legacy_id_key_digest,
1317 crypto_pk_t *legacy_signing_key,
1318 consensus_flavor_t flavor)
1320 smartlist_t *chunks;
1321 char *result = NULL;
1322 int consensus_method;
1323 time_t valid_after, fresh_until, valid_until;
1324 int vote_seconds, dist_seconds;
1325 char *client_versions = NULL, *server_versions = NULL;
1326 smartlist_t *flags;
1327 const char *flavor_name;
1328 uint32_t max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1329 int64_t G=0, M=0, E=0, D=0, T=0; /* For bandwidth weights */
1330 const routerstatus_format_type_t rs_format =
1331 flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
1332 char *params = NULL;
1333 int added_weights = 0;
1334 tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
1335 tor_assert(total_authorities >= smartlist_len(votes));
1337 flavor_name = networkstatus_get_flavor_name(flavor);
1339 if (!smartlist_len(votes)) {
1340 log_warn(LD_DIR, "Can't compute a consensus from no votes.");
1341 return NULL;
1343 flags = smartlist_new();
1345 consensus_method = compute_consensus_method(votes);
1346 if (consensus_method_is_supported(consensus_method)) {
1347 log_info(LD_DIR, "Generating consensus using method %d.",
1348 consensus_method);
1349 } else {
1350 log_warn(LD_DIR, "The other authorities will use consensus method %d, "
1351 "which I don't support. Maybe I should upgrade!",
1352 consensus_method);
1353 consensus_method = 1;
1356 /* Compute medians of time-related things, and figure out how many
1357 * routers we might need to talk about. */
1359 int n_votes = smartlist_len(votes);
1360 time_t *va_times = tor_malloc(n_votes * sizeof(time_t));
1361 time_t *fu_times = tor_malloc(n_votes * sizeof(time_t));
1362 time_t *vu_times = tor_malloc(n_votes * sizeof(time_t));
1363 int *votesec_list = tor_malloc(n_votes * sizeof(int));
1364 int *distsec_list = tor_malloc(n_votes * sizeof(int));
1365 int n_versioning_clients = 0, n_versioning_servers = 0;
1366 smartlist_t *combined_client_versions = smartlist_new();
1367 smartlist_t *combined_server_versions = smartlist_new();
1369 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1370 tor_assert(v->type == NS_TYPE_VOTE);
1371 va_times[v_sl_idx] = v->valid_after;
1372 fu_times[v_sl_idx] = v->fresh_until;
1373 vu_times[v_sl_idx] = v->valid_until;
1374 votesec_list[v_sl_idx] = v->vote_seconds;
1375 distsec_list[v_sl_idx] = v->dist_seconds;
1376 if (v->client_versions) {
1377 smartlist_t *cv = smartlist_new();
1378 ++n_versioning_clients;
1379 smartlist_split_string(cv, v->client_versions, ",",
1380 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1381 sort_version_list(cv, 1);
1382 smartlist_add_all(combined_client_versions, cv);
1383 smartlist_free(cv); /* elements get freed later. */
1385 if (v->server_versions) {
1386 smartlist_t *sv = smartlist_new();
1387 ++n_versioning_servers;
1388 smartlist_split_string(sv, v->server_versions, ",",
1389 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1390 sort_version_list(sv, 1);
1391 smartlist_add_all(combined_server_versions, sv);
1392 smartlist_free(sv); /* elements get freed later. */
1394 SMARTLIST_FOREACH(v->known_flags, const char *, cp,
1395 smartlist_add(flags, tor_strdup(cp)));
1396 } SMARTLIST_FOREACH_END(v);
1397 valid_after = median_time(va_times, n_votes);
1398 fresh_until = median_time(fu_times, n_votes);
1399 valid_until = median_time(vu_times, n_votes);
1400 vote_seconds = median_int(votesec_list, n_votes);
1401 dist_seconds = median_int(distsec_list, n_votes);
1403 tor_assert(valid_after+MIN_VOTE_INTERVAL <= fresh_until);
1404 tor_assert(fresh_until+MIN_VOTE_INTERVAL <= valid_until);
1405 tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
1406 tor_assert(dist_seconds >= MIN_DIST_SECONDS);
1408 server_versions = compute_consensus_versions_list(combined_server_versions,
1409 n_versioning_servers);
1410 client_versions = compute_consensus_versions_list(combined_client_versions,
1411 n_versioning_clients);
1413 SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
1414 SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
1415 smartlist_free(combined_server_versions);
1416 smartlist_free(combined_client_versions);
1418 smartlist_sort_strings(flags);
1419 smartlist_uniq_strings(flags);
1421 tor_free(va_times);
1422 tor_free(fu_times);
1423 tor_free(vu_times);
1424 tor_free(votesec_list);
1425 tor_free(distsec_list);
1428 chunks = smartlist_new();
1431 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
1432 vu_buf[ISO_TIME_LEN+1];
1433 char *flaglist;
1434 format_iso_time(va_buf, valid_after);
1435 format_iso_time(fu_buf, fresh_until);
1436 format_iso_time(vu_buf, valid_until);
1437 flaglist = smartlist_join_strings(flags, " ", 0, NULL);
1439 smartlist_add_asprintf(chunks, "network-status-version 3%s%s\n"
1440 "vote-status consensus\n",
1441 flavor == FLAV_NS ? "" : " ",
1442 flavor == FLAV_NS ? "" : flavor_name);
1444 if (consensus_method >= 2) {
1445 smartlist_add_asprintf(chunks, "consensus-method %d\n",
1446 consensus_method);
1449 smartlist_add_asprintf(chunks,
1450 "valid-after %s\n"
1451 "fresh-until %s\n"
1452 "valid-until %s\n"
1453 "voting-delay %d %d\n"
1454 "client-versions %s\n"
1455 "server-versions %s\n"
1456 "known-flags %s\n",
1457 va_buf, fu_buf, vu_buf,
1458 vote_seconds, dist_seconds,
1459 client_versions, server_versions, flaglist);
1461 tor_free(flaglist);
1464 if (consensus_method >= MIN_METHOD_FOR_PARAMS) {
1465 params = dirvote_compute_params(votes, consensus_method,
1466 total_authorities);
1467 if (params) {
1468 smartlist_add(chunks, tor_strdup("params "));
1469 smartlist_add(chunks, params);
1470 smartlist_add(chunks, tor_strdup("\n"));
1474 /* Sort the votes. */
1475 smartlist_sort(votes, compare_votes_by_authority_id_);
1476 /* Add the authority sections. */
1478 smartlist_t *dir_sources = smartlist_new();
1479 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1480 dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
1481 e->v = v;
1482 e->digest = get_voter(v)->identity_digest;
1483 e->is_legacy = 0;
1484 smartlist_add(dir_sources, e);
1485 if (consensus_method >= 3 &&
1486 !tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
1487 dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
1488 e_legacy->v = v;
1489 e_legacy->digest = get_voter(v)->legacy_id_digest;
1490 e_legacy->is_legacy = 1;
1491 smartlist_add(dir_sources, e_legacy);
1493 } SMARTLIST_FOREACH_END(v);
1494 smartlist_sort(dir_sources, compare_dir_src_ents_by_authority_id_);
1496 SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
1497 char fingerprint[HEX_DIGEST_LEN+1];
1498 char votedigest[HEX_DIGEST_LEN+1];
1499 networkstatus_t *v = e->v;
1500 networkstatus_voter_info_t *voter = get_voter(v);
1502 if (e->is_legacy)
1503 tor_assert(consensus_method >= 2);
1505 base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
1506 base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
1507 DIGEST_LEN);
1509 smartlist_add_asprintf(chunks,
1510 "dir-source %s%s %s %s %s %d %d\n",
1511 voter->nickname, e->is_legacy ? "-legacy" : "",
1512 fingerprint, voter->address, fmt_addr32(voter->addr),
1513 voter->dir_port,
1514 voter->or_port);
1515 if (! e->is_legacy) {
1516 smartlist_add_asprintf(chunks,
1517 "contact %s\n"
1518 "vote-digest %s\n",
1519 voter->contact,
1520 votedigest);
1522 } SMARTLIST_FOREACH_END(e);
1523 SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
1524 smartlist_free(dir_sources);
1527 if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW) {
1528 char *max_unmeasured_param = NULL;
1529 /* XXXX Extract this code into a common function */
1530 if (params) {
1531 if (strcmpstart(params, "maxunmeasuredbw=") == 0)
1532 max_unmeasured_param = params;
1533 else
1534 max_unmeasured_param = strstr(params, " maxunmeasuredbw=");
1536 if (max_unmeasured_param) {
1537 int ok = 0;
1538 char *eq = strchr(max_unmeasured_param, '=');
1539 if (eq) {
1540 max_unmeasured_bw_kb = (uint32_t)
1541 tor_parse_ulong(eq+1, 10, 1, UINT32_MAX, &ok, NULL);
1542 if (!ok) {
1543 log_warn(LD_DIR, "Bad element '%s' in max unmeasured bw param",
1544 escaped(max_unmeasured_param));
1545 max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
1551 /* Add the actual router entries. */
1553 int *index; /* index[j] is the current index into votes[j]. */
1554 int *size; /* size[j] is the number of routerstatuses in votes[j]. */
1555 int *flag_counts; /* The number of voters that list flag[j] for the
1556 * currently considered router. */
1557 int i;
1558 smartlist_t *matching_descs = smartlist_new();
1559 smartlist_t *chosen_flags = smartlist_new();
1560 smartlist_t *versions = smartlist_new();
1561 smartlist_t *exitsummaries = smartlist_new();
1562 uint32_t *bandwidths_kb = tor_malloc(sizeof(uint32_t) *
1563 smartlist_len(votes));
1564 uint32_t *measured_bws_kb = tor_malloc(sizeof(uint32_t) *
1565 smartlist_len(votes));
1566 int num_bandwidths;
1567 int num_mbws;
1569 int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
1570 * votes[j] knows about. */
1571 int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
1572 * about flags[f]. */
1573 int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
1574 * is the same flag as votes[j]->known_flags[b]. */
1575 int *named_flag; /* Index of the flag "Named" for votes[j] */
1576 int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
1577 int chosen_named_idx;
1578 int n_authorities_measuring_bandwidth;
1580 strmap_t *name_to_id_map = strmap_new();
1581 char conflict[DIGEST_LEN];
1582 char unknown[DIGEST_LEN];
1583 memset(conflict, 0, sizeof(conflict));
1584 memset(unknown, 0xff, sizeof(conflict));
1586 index = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
1587 size = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
1588 n_voter_flags = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
1589 n_flag_voters = tor_malloc_zero(sizeof(int) * smartlist_len(flags));
1590 flag_map = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
1591 named_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
1592 unnamed_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
1593 for (i = 0; i < smartlist_len(votes); ++i)
1594 unnamed_flag[i] = named_flag[i] = -1;
1595 chosen_named_idx = smartlist_string_pos(flags, "Named");
1597 /* Build the flag indexes. Note that no vote can have more than 64 members
1598 * for known_flags, so no value will be greater than 63, so it's safe to
1599 * do U64_LITERAL(1) << index on these values. But note also that
1600 * named_flag and unnamed_flag are initialized to -1, so we need to check
1601 * that they're actually set before doing U64_LITERAL(1) << index with
1602 * them.*/
1603 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1604 flag_map[v_sl_idx] = tor_malloc_zero(
1605 sizeof(int)*smartlist_len(v->known_flags));
1606 if (smartlist_len(v->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
1607 log_warn(LD_BUG, "Somehow, a vote has %d entries in known_flags",
1608 smartlist_len(v->known_flags));
1610 SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
1611 int p = smartlist_string_pos(flags, fl);
1612 tor_assert(p >= 0);
1613 flag_map[v_sl_idx][fl_sl_idx] = p;
1614 ++n_flag_voters[p];
1615 if (!strcmp(fl, "Named"))
1616 named_flag[v_sl_idx] = fl_sl_idx;
1617 if (!strcmp(fl, "Unnamed"))
1618 unnamed_flag[v_sl_idx] = fl_sl_idx;
1619 } SMARTLIST_FOREACH_END(fl);
1620 n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
1621 size[v_sl_idx] = smartlist_len(v->routerstatus_list);
1622 } SMARTLIST_FOREACH_END(v);
1624 /* Named and Unnamed get treated specially */
1625 if (consensus_method >= 2) {
1626 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1627 uint64_t nf;
1628 if (named_flag[v_sl_idx]<0)
1629 continue;
1630 nf = U64_LITERAL(1) << named_flag[v_sl_idx];
1631 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1632 vote_routerstatus_t *, rs) {
1634 if ((rs->flags & nf) != 0) {
1635 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1636 if (!d) {
1637 /* We have no name officially mapped to this digest. */
1638 strmap_set_lc(name_to_id_map, rs->status.nickname,
1639 rs->status.identity_digest);
1640 } else if (d != conflict &&
1641 fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
1642 /* Authorities disagree about this nickname. */
1643 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1644 } else {
1645 /* It's already a conflict, or it's already this ID. */
1648 } SMARTLIST_FOREACH_END(rs);
1649 } SMARTLIST_FOREACH_END(v);
1651 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1652 uint64_t uf;
1653 if (unnamed_flag[v_sl_idx]<0)
1654 continue;
1655 uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
1656 SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
1657 vote_routerstatus_t *, rs) {
1658 if ((rs->flags & uf) != 0) {
1659 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1660 if (d == conflict || d == unknown) {
1661 /* Leave it alone; we know what it is. */
1662 } else if (!d) {
1663 /* We have no name officially mapped to this digest. */
1664 strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
1665 } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
1666 /* Authorities disagree about this nickname. */
1667 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1668 } else {
1669 /* It's mapped to a different name. */
1672 } SMARTLIST_FOREACH_END(rs);
1673 } SMARTLIST_FOREACH_END(v);
1676 /* We need to know how many votes measure bandwidth. */
1677 n_authorities_measuring_bandwidth = 0;
1678 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
1679 if (v->has_measured_bws) {
1680 ++n_authorities_measuring_bandwidth;
1684 /* Now go through all the votes */
1685 flag_counts = tor_malloc(sizeof(int) * smartlist_len(flags));
1686 while (1) {
1687 vote_routerstatus_t *rs;
1688 routerstatus_t rs_out;
1689 const char *lowest_id = NULL;
1690 const char *chosen_version;
1691 const char *chosen_name = NULL;
1692 int exitsummary_disagreement = 0;
1693 int is_named = 0, is_unnamed = 0, is_running = 0;
1694 int is_guard = 0, is_exit = 0, is_bad_exit = 0;
1695 int naming_conflict = 0;
1696 int n_listing = 0;
1697 int i;
1698 char microdesc_digest[DIGEST256_LEN];
1699 tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
1701 /* Of the next-to-be-considered digest in each voter, which is first? */
1702 SMARTLIST_FOREACH(votes, networkstatus_t *, v, {
1703 if (index[v_sl_idx] < size[v_sl_idx]) {
1704 rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
1705 if (!lowest_id ||
1706 fast_memcmp(rs->status.identity_digest,
1707 lowest_id, DIGEST_LEN) < 0)
1708 lowest_id = rs->status.identity_digest;
1711 if (!lowest_id) /* we're out of routers. */
1712 break;
1714 memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
1715 smartlist_clear(matching_descs);
1716 smartlist_clear(chosen_flags);
1717 smartlist_clear(versions);
1718 num_bandwidths = 0;
1719 num_mbws = 0;
1721 /* Okay, go through all the entries for this digest. */
1722 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1723 if (index[v_sl_idx] >= size[v_sl_idx])
1724 continue; /* out of entries. */
1725 rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
1726 if (fast_memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN))
1727 continue; /* doesn't include this router. */
1728 /* At this point, we know that we're looking at a routerstatus with
1729 * identity "lowest".
1731 ++index[v_sl_idx];
1732 ++n_listing;
1734 smartlist_add(matching_descs, rs);
1735 if (rs->version && rs->version[0])
1736 smartlist_add(versions, rs->version);
1738 /* Tally up all the flags. */
1739 for (i = 0; i < n_voter_flags[v_sl_idx]; ++i) {
1740 if (rs->flags & (U64_LITERAL(1) << i))
1741 ++flag_counts[flag_map[v_sl_idx][i]];
1743 if (named_flag[v_sl_idx] >= 0 &&
1744 (rs->flags & (U64_LITERAL(1) << named_flag[v_sl_idx]))) {
1745 if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
1746 log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
1747 chosen_name, rs->status.nickname);
1748 naming_conflict = 1;
1750 chosen_name = rs->status.nickname;
1753 /* count bandwidths */
1754 if (rs->has_measured_bw)
1755 measured_bws_kb[num_mbws++] = rs->measured_bw_kb;
1757 if (rs->status.has_bandwidth)
1758 bandwidths_kb[num_bandwidths++] = rs->status.bandwidth_kb;
1759 } SMARTLIST_FOREACH_END(v);
1761 /* We don't include this router at all unless more than half of
1762 * the authorities we believe in list it. */
1763 if (n_listing <= total_authorities/2)
1764 continue;
1766 /* Figure out the most popular opinion of what the most recent
1767 * routerinfo and its contents are. */
1768 memset(microdesc_digest, 0, sizeof(microdesc_digest));
1769 rs = compute_routerstatus_consensus(matching_descs, consensus_method,
1770 microdesc_digest, &alt_orport);
1771 /* Copy bits of that into rs_out. */
1772 memset(&rs_out, 0, sizeof(rs_out));
1773 tor_assert(fast_memeq(lowest_id, rs->status.identity_digest,DIGEST_LEN));
1774 memcpy(rs_out.identity_digest, lowest_id, DIGEST_LEN);
1775 memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
1776 DIGEST_LEN);
1777 rs_out.addr = rs->status.addr;
1778 rs_out.published_on = rs->status.published_on;
1779 rs_out.dir_port = rs->status.dir_port;
1780 rs_out.or_port = rs->status.or_port;
1781 if (consensus_method >= MIN_METHOD_FOR_A_LINES) {
1782 tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
1783 rs_out.ipv6_orport = alt_orport.port;
1785 rs_out.has_bandwidth = 0;
1786 rs_out.has_exitsummary = 0;
1788 if (chosen_name && !naming_conflict) {
1789 strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
1790 } else {
1791 strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
1794 if (consensus_method == 1) {
1795 is_named = chosen_named_idx >= 0 &&
1796 (!naming_conflict && flag_counts[chosen_named_idx]);
1797 } else {
1798 const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
1799 if (!d) {
1800 is_named = is_unnamed = 0;
1801 } else if (fast_memeq(d, lowest_id, DIGEST_LEN)) {
1802 is_named = 1; is_unnamed = 0;
1803 } else {
1804 is_named = 0; is_unnamed = 1;
1808 /* Set the flags. */
1809 smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
1810 SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
1811 if (!strcmp(fl, "Named")) {
1812 if (is_named)
1813 smartlist_add(chosen_flags, (char*)fl);
1814 } else if (!strcmp(fl, "Unnamed") && consensus_method >= 2) {
1815 if (is_unnamed)
1816 smartlist_add(chosen_flags, (char*)fl);
1817 } else {
1818 if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
1819 smartlist_add(chosen_flags, (char*)fl);
1820 if (!strcmp(fl, "Exit"))
1821 is_exit = 1;
1822 else if (!strcmp(fl, "Guard"))
1823 is_guard = 1;
1824 else if (!strcmp(fl, "Running"))
1825 is_running = 1;
1826 else if (!strcmp(fl, "BadExit"))
1827 is_bad_exit = 1;
1830 } SMARTLIST_FOREACH_END(fl);
1832 /* Starting with consensus method 4 we do not list servers
1833 * that are not running in a consensus. See Proposal 138 */
1834 if (consensus_method >= 4 && !is_running)
1835 continue;
1837 /* Pick the version. */
1838 if (smartlist_len(versions)) {
1839 sort_version_list(versions, 0);
1840 chosen_version = get_most_frequent_member(versions);
1841 } else {
1842 chosen_version = NULL;
1845 /* Pick a bandwidth */
1846 if (consensus_method >= 6 && num_mbws > 2) {
1847 rs_out.has_bandwidth = 1;
1848 rs_out.bw_is_unmeasured = 0;
1849 rs_out.bandwidth_kb = median_uint32(measured_bws_kb, num_mbws);
1850 } else if (consensus_method >= 5 && num_bandwidths > 0) {
1851 rs_out.has_bandwidth = 1;
1852 rs_out.bw_is_unmeasured = 1;
1853 rs_out.bandwidth_kb = median_uint32(bandwidths_kb, num_bandwidths);
1854 if (consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW &&
1855 n_authorities_measuring_bandwidth > 2) {
1856 /* Cap non-measured bandwidths. */
1857 if (rs_out.bandwidth_kb > max_unmeasured_bw_kb) {
1858 rs_out.bandwidth_kb = max_unmeasured_bw_kb;
1863 /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
1864 if (consensus_method >= MIN_METHOD_TO_CUT_BADEXIT_WEIGHT) {
1865 is_exit = is_exit && !is_bad_exit;
1868 if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS) {
1869 if (rs_out.has_bandwidth) {
1870 T += rs_out.bandwidth_kb;
1871 if (is_exit && is_guard)
1872 D += rs_out.bandwidth_kb;
1873 else if (is_exit)
1874 E += rs_out.bandwidth_kb;
1875 else if (is_guard)
1876 G += rs_out.bandwidth_kb;
1877 else
1878 M += rs_out.bandwidth_kb;
1879 } else {
1880 log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
1881 rs_out.nickname);
1885 /* Ok, we already picked a descriptor digest we want to list
1886 * previously. Now we want to use the exit policy summary from
1887 * that descriptor. If everybody plays nice all the voters who
1888 * listed that descriptor will have the same summary. If not then
1889 * something is fishy and we'll use the most common one (breaking
1890 * ties in favor of lexicographically larger one (only because it
1891 * lets me reuse more existing code)).
1893 * The other case that can happen is that no authority that voted
1894 * for that descriptor has an exit policy summary. That's
1895 * probably quite unlikely but can happen. In that case we use
1896 * the policy that was most often listed in votes, again breaking
1897 * ties like in the previous case.
1899 if (consensus_method >= 5) {
1900 /* Okay, go through all the votes for this router. We prepared
1901 * that list previously */
1902 const char *chosen_exitsummary = NULL;
1903 smartlist_clear(exitsummaries);
1904 SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
1905 /* Check if the vote where this status comes from had the
1906 * proper descriptor */
1907 tor_assert(fast_memeq(rs_out.identity_digest,
1908 vsr->status.identity_digest,
1909 DIGEST_LEN));
1910 if (vsr->status.has_exitsummary &&
1911 fast_memeq(rs_out.descriptor_digest,
1912 vsr->status.descriptor_digest,
1913 DIGEST_LEN)) {
1914 tor_assert(vsr->status.exitsummary);
1915 smartlist_add(exitsummaries, vsr->status.exitsummary);
1916 if (!chosen_exitsummary) {
1917 chosen_exitsummary = vsr->status.exitsummary;
1918 } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
1919 /* Great. There's disagreement among the voters. That
1920 * really shouldn't be */
1921 exitsummary_disagreement = 1;
1924 } SMARTLIST_FOREACH_END(vsr);
1926 if (exitsummary_disagreement) {
1927 char id[HEX_DIGEST_LEN+1];
1928 char dd[HEX_DIGEST_LEN+1];
1929 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1930 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1931 log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
1932 " for router %s with descriptor %s. This really shouldn't"
1933 " have happened.", id, dd);
1935 smartlist_sort_strings(exitsummaries);
1936 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1937 } else if (!chosen_exitsummary) {
1938 char id[HEX_DIGEST_LEN+1];
1939 char dd[HEX_DIGEST_LEN+1];
1940 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1941 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1942 log_warn(LD_DIR, "Not one of the voters that made us select"
1943 "descriptor %s for router %s had an exit policy"
1944 "summary", dd, id);
1946 /* Ok, none of those voting for the digest we chose had an
1947 * exit policy for us. Well, that kinda sucks.
1949 smartlist_clear(exitsummaries);
1950 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
1951 if (vsr->status.has_exitsummary)
1952 smartlist_add(exitsummaries, vsr->status.exitsummary);
1954 smartlist_sort_strings(exitsummaries);
1955 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1957 if (!chosen_exitsummary)
1958 log_warn(LD_DIR, "Wow, not one of the voters had an exit "
1959 "policy summary for %s. Wow.", id);
1962 if (chosen_exitsummary) {
1963 rs_out.has_exitsummary = 1;
1964 /* yea, discards the const */
1965 rs_out.exitsummary = (char *)chosen_exitsummary;
1969 if (flavor == FLAV_MICRODESC &&
1970 consensus_method >= MIN_METHOD_FOR_MANDATORY_MICRODESC &&
1971 tor_digest256_is_zero(microdesc_digest)) {
1972 /* With no microdescriptor digest, we omit the entry entirely. */
1973 continue;
1977 char *buf;
1978 /* Okay!! Now we can write the descriptor... */
1979 /* First line goes into "buf". */
1980 buf = routerstatus_format_entry(&rs_out, NULL, rs_format, NULL);
1981 if (buf)
1982 smartlist_add(chunks, buf);
1984 /* Now an m line, if applicable. */
1985 if (flavor == FLAV_MICRODESC &&
1986 !tor_digest256_is_zero(microdesc_digest)) {
1987 char m[BASE64_DIGEST256_LEN+1];
1988 digest256_to_base64(m, microdesc_digest);
1989 smartlist_add_asprintf(chunks, "m %s\n", m);
1991 /* Next line is all flags. The "\n" is missing. */
1992 smartlist_add(chunks,
1993 smartlist_join_strings(chosen_flags, " ", 0, NULL));
1994 /* Now the version line. */
1995 if (chosen_version) {
1996 smartlist_add(chunks, tor_strdup("\nv "));
1997 smartlist_add(chunks, tor_strdup(chosen_version));
1999 smartlist_add(chunks, tor_strdup("\n"));
2000 /* Now the weight line. */
2001 if (rs_out.has_bandwidth) {
2002 int unmeasured = rs_out.bw_is_unmeasured &&
2003 consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW;
2004 smartlist_add_asprintf(chunks, "w Bandwidth=%d%s\n",
2005 rs_out.bandwidth_kb,
2006 unmeasured?" Unmeasured=1":"");
2009 /* Now the exitpolicy summary line. */
2010 if (rs_out.has_exitsummary && flavor == FLAV_NS) {
2011 smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
2014 /* And the loop is over and we move on to the next router */
2017 tor_free(index);
2018 tor_free(size);
2019 tor_free(n_voter_flags);
2020 tor_free(n_flag_voters);
2021 for (i = 0; i < smartlist_len(votes); ++i)
2022 tor_free(flag_map[i]);
2023 tor_free(flag_map);
2024 tor_free(flag_counts);
2025 tor_free(named_flag);
2026 tor_free(unnamed_flag);
2027 strmap_free(name_to_id_map, NULL);
2028 smartlist_free(matching_descs);
2029 smartlist_free(chosen_flags);
2030 smartlist_free(versions);
2031 smartlist_free(exitsummaries);
2032 tor_free(bandwidths_kb);
2033 tor_free(measured_bws_kb);
2036 if (consensus_method >= MIN_METHOD_FOR_FOOTER) {
2037 /* Starting with consensus method 9, we clearly mark the directory
2038 * footer region */
2039 smartlist_add(chunks, tor_strdup("directory-footer\n"));
2042 if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS) {
2043 int64_t weight_scale = BW_WEIGHT_SCALE;
2044 char *bw_weight_param = NULL;
2046 // Parse params, extract BW_WEIGHT_SCALE if present
2047 // DO NOT use consensus_param_bw_weight_scale() in this code!
2048 // The consensus is not formed yet!
2049 /* XXXX Extract this code into a common function */
2050 if (params) {
2051 if (strcmpstart(params, "bwweightscale=") == 0)
2052 bw_weight_param = params;
2053 else
2054 bw_weight_param = strstr(params, " bwweightscale=");
2057 if (bw_weight_param) {
2058 int ok=0;
2059 char *eq = strchr(bw_weight_param, '=');
2060 if (eq) {
2061 weight_scale = tor_parse_long(eq+1, 10, 1, INT32_MAX, &ok,
2062 NULL);
2063 if (!ok) {
2064 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
2065 escaped(bw_weight_param));
2066 weight_scale = BW_WEIGHT_SCALE;
2068 } else {
2069 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
2070 escaped(bw_weight_param));
2071 weight_scale = BW_WEIGHT_SCALE;
2075 if (consensus_method < 10) {
2076 networkstatus_compute_bw_weights_v9(chunks, G, M, E, D, T, weight_scale);
2077 added_weights = 1;
2078 } else {
2079 added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
2080 T, weight_scale);
2084 /* Add a signature. */
2086 char digest[DIGEST256_LEN];
2087 char fingerprint[HEX_DIGEST_LEN+1];
2088 char signing_key_fingerprint[HEX_DIGEST_LEN+1];
2089 digest_algorithm_t digest_alg =
2090 flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
2091 size_t digest_len =
2092 flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
2093 const char *algname = crypto_digest_algorithm_get_name(digest_alg);
2094 char *signature;
2096 smartlist_add(chunks, tor_strdup("directory-signature "));
2098 /* Compute the hash of the chunks. */
2099 crypto_digest_smartlist(digest, digest_len, chunks, "", digest_alg);
2101 /* Get the fingerprints */
2102 crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
2103 crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
2105 /* add the junk that will go at the end of the line. */
2106 if (flavor == FLAV_NS) {
2107 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
2108 signing_key_fingerprint);
2109 } else {
2110 smartlist_add_asprintf(chunks, "%s %s %s\n",
2111 algname, fingerprint,
2112 signing_key_fingerprint);
2114 /* And the signature. */
2115 if (!(signature = router_get_dirobj_signature(digest, digest_len,
2116 signing_key))) {
2117 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
2118 goto done;
2120 smartlist_add(chunks, signature);
2122 if (legacy_id_key_digest && legacy_signing_key && consensus_method >= 3) {
2123 smartlist_add(chunks, tor_strdup("directory-signature "));
2124 base16_encode(fingerprint, sizeof(fingerprint),
2125 legacy_id_key_digest, DIGEST_LEN);
2126 crypto_pk_get_fingerprint(legacy_signing_key,
2127 signing_key_fingerprint, 0);
2128 if (flavor == FLAV_NS) {
2129 smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
2130 signing_key_fingerprint);
2131 } else {
2132 smartlist_add_asprintf(chunks, "%s %s %s\n",
2133 algname, fingerprint,
2134 signing_key_fingerprint);
2137 if (!(signature = router_get_dirobj_signature(digest, digest_len,
2138 legacy_signing_key))) {
2139 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
2140 goto done;
2142 smartlist_add(chunks, signature);
2146 result = smartlist_join_strings(chunks, "", 0, NULL);
2149 networkstatus_t *c;
2150 if (!(c = networkstatus_parse_vote_from_string(result, NULL,
2151 NS_TYPE_CONSENSUS))) {
2152 log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
2153 "parse.");
2154 tor_free(result);
2155 goto done;
2157 // Verify balancing parameters
2158 if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS && added_weights) {
2159 networkstatus_verify_bw_weights(c, consensus_method);
2161 networkstatus_vote_free(c);
2164 done:
2166 tor_free(client_versions);
2167 tor_free(server_versions);
2168 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
2169 smartlist_free(flags);
2170 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2171 smartlist_free(chunks);
2173 return result;
2176 /** Given a consensus vote <b>target</b> and a set of detached signatures in
2177 * <b>sigs</b> that correspond to the same consensus, check whether there are
2178 * any new signatures in <b>src_voter_list</b> that should be added to
2179 * <b>target</b>. (A signature should be added if we have no signature for that
2180 * voter in <b>target</b> yet, or if we have no verifiable signature and the
2181 * new signature is verifiable.) Return the number of signatures added or
2182 * changed, or -1 if the document signed by <b>sigs</b> isn't the same
2183 * document as <b>target</b>. */
2185 networkstatus_add_detached_signatures(networkstatus_t *target,
2186 ns_detached_signatures_t *sigs,
2187 const char *source,
2188 int severity,
2189 const char **msg_out)
2191 int r = 0;
2192 const char *flavor;
2193 smartlist_t *siglist;
2194 tor_assert(sigs);
2195 tor_assert(target);
2196 tor_assert(target->type == NS_TYPE_CONSENSUS);
2198 flavor = networkstatus_get_flavor_name(target->flavor);
2200 /* Do the times seem right? */
2201 if (target->valid_after != sigs->valid_after) {
2202 *msg_out = "Valid-After times do not match "
2203 "when adding detached signatures to consensus";
2204 return -1;
2206 if (target->fresh_until != sigs->fresh_until) {
2207 *msg_out = "Fresh-until times do not match "
2208 "when adding detached signatures to consensus";
2209 return -1;
2211 if (target->valid_until != sigs->valid_until) {
2212 *msg_out = "Valid-until times do not match "
2213 "when adding detached signatures to consensus";
2214 return -1;
2216 siglist = strmap_get(sigs->signatures, flavor);
2217 if (!siglist) {
2218 *msg_out = "No signatures for given consensus flavor";
2219 return -1;
2222 /** Make sure all the digests we know match, and at least one matches. */
2224 digests_t *digests = strmap_get(sigs->digests, flavor);
2225 int n_matches = 0;
2226 int alg;
2227 if (!digests) {
2228 *msg_out = "No digests for given consensus flavor";
2229 return -1;
2231 for (alg = DIGEST_SHA1; alg < N_DIGEST_ALGORITHMS; ++alg) {
2232 if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
2233 if (fast_memeq(target->digests.d[alg], digests->d[alg],
2234 DIGEST256_LEN)) {
2235 ++n_matches;
2236 } else {
2237 *msg_out = "Mismatched digest.";
2238 return -1;
2242 if (!n_matches) {
2243 *msg_out = "No regognized digests for given consensus flavor";
2247 /* For each voter in src... */
2248 SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
2249 char voter_identity[HEX_DIGEST_LEN+1];
2250 networkstatus_voter_info_t *target_voter =
2251 networkstatus_get_voter_by_id(target, sig->identity_digest);
2252 authority_cert_t *cert = NULL;
2253 const char *algorithm;
2254 document_signature_t *old_sig = NULL;
2256 algorithm = crypto_digest_algorithm_get_name(sig->alg);
2258 base16_encode(voter_identity, sizeof(voter_identity),
2259 sig->identity_digest, DIGEST_LEN);
2260 log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
2261 algorithm);
2262 /* If the target doesn't know about this voter, then forget it. */
2263 if (!target_voter) {
2264 log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
2265 continue;
2268 old_sig = voter_get_sig_by_algorithm(target_voter, sig->alg);
2270 /* If the target already has a good signature from this voter, then skip
2271 * this one. */
2272 if (old_sig && old_sig->good_signature) {
2273 log_info(LD_DIR, "We already have a good signature from %s using %s",
2274 voter_identity, algorithm);
2275 continue;
2278 /* Try checking the signature if we haven't already. */
2279 if (!sig->good_signature && !sig->bad_signature) {
2280 cert = authority_cert_get_by_digests(sig->identity_digest,
2281 sig->signing_key_digest);
2282 if (cert)
2283 networkstatus_check_document_signature(target, sig, cert);
2286 /* If this signature is good, or we don't have any signature yet,
2287 * then maybe add it. */
2288 if (sig->good_signature || !old_sig || old_sig->bad_signature) {
2289 log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
2290 algorithm);
2291 tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
2292 target_voter->nickname, source);
2293 ++r;
2294 if (old_sig) {
2295 smartlist_remove(target_voter->sigs, old_sig);
2296 document_signature_free(old_sig);
2298 smartlist_add(target_voter->sigs, document_signature_dup(sig));
2299 } else {
2300 log_info(LD_DIR, "Not adding signature from %s", voter_identity);
2302 } SMARTLIST_FOREACH_END(sig);
2304 return r;
2307 /** Return a newly allocated string containing all the signatures on
2308 * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
2309 * then the signatures will be put in a detached signatures document, so
2310 * prefix any non-NS-flavored signatures with "additional-signature" rather
2311 * than "directory-signature". */
2312 static char *
2313 networkstatus_format_signatures(networkstatus_t *consensus,
2314 int for_detached_signatures)
2316 smartlist_t *elements;
2317 char buf[4096];
2318 char *result = NULL;
2319 int n_sigs = 0;
2320 const consensus_flavor_t flavor = consensus->flavor;
2321 const char *flavor_name = networkstatus_get_flavor_name(flavor);
2322 const char *keyword;
2324 if (for_detached_signatures && flavor != FLAV_NS)
2325 keyword = "additional-signature";
2326 else
2327 keyword = "directory-signature";
2329 elements = smartlist_new();
2331 SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
2332 SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
2333 char sk[HEX_DIGEST_LEN+1];
2334 char id[HEX_DIGEST_LEN+1];
2335 if (!sig->signature || sig->bad_signature)
2336 continue;
2337 ++n_sigs;
2338 base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
2339 base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
2340 if (flavor == FLAV_NS) {
2341 smartlist_add_asprintf(elements,
2342 "%s %s %s\n-----BEGIN SIGNATURE-----\n",
2343 keyword, id, sk);
2344 } else {
2345 const char *digest_name =
2346 crypto_digest_algorithm_get_name(sig->alg);
2347 smartlist_add_asprintf(elements,
2348 "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
2349 keyword,
2350 for_detached_signatures ? " " : "",
2351 for_detached_signatures ? flavor_name : "",
2352 digest_name, id, sk);
2354 base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len);
2355 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
2356 smartlist_add(elements, tor_strdup(buf));
2357 } SMARTLIST_FOREACH_END(sig);
2358 } SMARTLIST_FOREACH_END(v);
2360 result = smartlist_join_strings(elements, "", 0, NULL);
2361 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2362 smartlist_free(elements);
2363 if (!n_sigs)
2364 tor_free(result);
2365 return result;
2368 /** Return a newly allocated string holding the detached-signatures document
2369 * corresponding to the signatures on <b>consensuses</b>, which must contain
2370 * exactly one FLAV_NS consensus, and no more than one consensus for each
2371 * other flavor. */
2372 char *
2373 networkstatus_get_detached_signatures(smartlist_t *consensuses)
2375 smartlist_t *elements;
2376 char *result = NULL, *sigs = NULL;
2377 networkstatus_t *consensus_ns = NULL;
2378 tor_assert(consensuses);
2380 SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
2381 tor_assert(ns);
2382 tor_assert(ns->type == NS_TYPE_CONSENSUS);
2383 if (ns && ns->flavor == FLAV_NS)
2384 consensus_ns = ns;
2386 if (!consensus_ns) {
2387 log_warn(LD_BUG, "No NS consensus given.");
2388 return NULL;
2391 elements = smartlist_new();
2394 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
2395 vu_buf[ISO_TIME_LEN+1];
2396 char d[HEX_DIGEST_LEN+1];
2398 base16_encode(d, sizeof(d),
2399 consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
2400 format_iso_time(va_buf, consensus_ns->valid_after);
2401 format_iso_time(fu_buf, consensus_ns->fresh_until);
2402 format_iso_time(vu_buf, consensus_ns->valid_until);
2404 smartlist_add_asprintf(elements,
2405 "consensus-digest %s\n"
2406 "valid-after %s\n"
2407 "fresh-until %s\n"
2408 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
2411 /* Get all the digests for the non-FLAV_NS consensuses */
2412 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2413 const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
2414 int alg;
2415 if (ns->flavor == FLAV_NS)
2416 continue;
2418 /* start with SHA256; we don't include SHA1 for anything but the basic
2419 * consensus. */
2420 for (alg = DIGEST_SHA256; alg < N_DIGEST_ALGORITHMS; ++alg) {
2421 char d[HEX_DIGEST256_LEN+1];
2422 const char *alg_name =
2423 crypto_digest_algorithm_get_name(alg);
2424 if (tor_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
2425 continue;
2426 base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
2427 smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
2428 flavor_name, alg_name, d);
2430 } SMARTLIST_FOREACH_END(ns);
2432 /* Now get all the sigs for non-FLAV_NS consensuses */
2433 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2434 char *sigs;
2435 if (ns->flavor == FLAV_NS)
2436 continue;
2437 sigs = networkstatus_format_signatures(ns, 1);
2438 if (!sigs) {
2439 log_warn(LD_DIR, "Couldn't format signatures");
2440 goto err;
2442 smartlist_add(elements, sigs);
2443 } SMARTLIST_FOREACH_END(ns);
2445 /* Now add the FLAV_NS consensus signatrures. */
2446 sigs = networkstatus_format_signatures(consensus_ns, 1);
2447 if (!sigs)
2448 goto err;
2449 smartlist_add(elements, sigs);
2451 result = smartlist_join_strings(elements, "", 0, NULL);
2452 err:
2453 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2454 smartlist_free(elements);
2455 return result;
2458 /** Return a newly allocated string holding a detached-signatures document for
2459 * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
2460 * <b>pending</b>. */
2461 static char *
2462 get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
2463 int n_flavors)
2465 int flav;
2466 char *signatures;
2467 smartlist_t *c = smartlist_new();
2468 for (flav = 0; flav < n_flavors; ++flav) {
2469 if (pending[flav].consensus)
2470 smartlist_add(c, pending[flav].consensus);
2472 signatures = networkstatus_get_detached_signatures(c);
2473 smartlist_free(c);
2474 return signatures;
2477 /** Release all storage held in <b>s</b>. */
2478 void
2479 ns_detached_signatures_free(ns_detached_signatures_t *s)
2481 if (!s)
2482 return;
2483 if (s->signatures) {
2484 STRMAP_FOREACH(s->signatures, flavor, smartlist_t *, sigs) {
2485 SMARTLIST_FOREACH(sigs, document_signature_t *, sig,
2486 document_signature_free(sig));
2487 smartlist_free(sigs);
2488 } STRMAP_FOREACH_END;
2489 strmap_free(s->signatures, NULL);
2490 strmap_free(s->digests, tor_free_);
2493 tor_free(s);
2496 /* =====
2497 * Certificate functions
2498 * ===== */
2500 /** Allocate and return a new authority_cert_t with the same contents as
2501 * <b>cert</b>. */
2502 authority_cert_t *
2503 authority_cert_dup(authority_cert_t *cert)
2505 authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
2506 tor_assert(cert);
2508 memcpy(out, cert, sizeof(authority_cert_t));
2509 /* Now copy pointed-to things. */
2510 out->cache_info.signed_descriptor_body =
2511 tor_strndup(cert->cache_info.signed_descriptor_body,
2512 cert->cache_info.signed_descriptor_len);
2513 out->cache_info.saved_location = SAVED_NOWHERE;
2514 out->identity_key = crypto_pk_dup_key(cert->identity_key);
2515 out->signing_key = crypto_pk_dup_key(cert->signing_key);
2517 return out;
2520 /* =====
2521 * Vote scheduling
2522 * ===== */
2524 /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
2525 * Note that these aren't the intervals we'll use to vote; they're the ones
2526 * that we'll vote to use. */
2527 void
2528 dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
2530 const or_options_t *options = get_options();
2532 tor_assert(timing_out);
2534 timing_out->vote_interval = options->V3AuthVotingInterval;
2535 timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
2536 timing_out->vote_delay = options->V3AuthVoteDelay;
2537 timing_out->dist_delay = options->V3AuthDistDelay;
2540 /** Return the start of the next interval of size <b>interval</b> (in
2541 * seconds) after <b>now</b>, plus <b>offset</b>. Midnight always
2542 * starts a fresh interval, and if the last interval of a day would be
2543 * truncated to less than half its size, it is rolled into the
2544 * previous interval. */
2545 time_t
2546 dirvote_get_start_of_next_interval(time_t now, int interval, int offset)
2548 struct tm tm;
2549 time_t midnight_today=0;
2550 time_t midnight_tomorrow;
2551 time_t next;
2553 tor_gmtime_r(&now, &tm);
2554 tm.tm_hour = 0;
2555 tm.tm_min = 0;
2556 tm.tm_sec = 0;
2558 if (tor_timegm(&tm, &midnight_today) < 0) {
2559 log_warn(LD_BUG, "Ran into an invalid time when trying to find midnight.");
2561 midnight_tomorrow = midnight_today + (24*60*60);
2563 next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
2565 /* Intervals never cross midnight. */
2566 if (next > midnight_tomorrow)
2567 next = midnight_tomorrow;
2569 /* If the interval would only last half as long as it's supposed to, then
2570 * skip over to the next day. */
2571 if (next + interval/2 > midnight_tomorrow)
2572 next = midnight_tomorrow;
2574 next += offset;
2575 if (next - interval > now)
2576 next -= interval;
2578 return next;
2581 /** Scheduling information for a voting interval. */
2582 static struct {
2583 /** When do we generate and distribute our vote for this interval? */
2584 time_t voting_starts;
2585 /** When do we send an HTTP request for any votes that we haven't
2586 * been posted yet?*/
2587 time_t fetch_missing_votes;
2588 /** When do we give up on getting more votes and generate a consensus? */
2589 time_t voting_ends;
2590 /** When do we send an HTTP request for any signatures we're expecting to
2591 * see on the consensus? */
2592 time_t fetch_missing_signatures;
2593 /** When do we publish the consensus? */
2594 time_t interval_starts;
2596 /* True iff we have generated and distributed our vote. */
2597 int have_voted;
2598 /* True iff we've requested missing votes. */
2599 int have_fetched_missing_votes;
2600 /* True iff we have built a consensus and sent the signatures around. */
2601 int have_built_consensus;
2602 /* True iff we've fetched missing signatures. */
2603 int have_fetched_missing_signatures;
2604 /* True iff we have published our consensus. */
2605 int have_published_consensus;
2606 } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
2608 /** Set voting_schedule to hold the timing for the next vote we should be
2609 * doing. */
2610 void
2611 dirvote_recalculate_timing(const or_options_t *options, time_t now)
2613 int interval, vote_delay, dist_delay;
2614 time_t start;
2615 time_t end;
2616 networkstatus_t *consensus;
2618 if (!authdir_mode_v3(options))
2619 return;
2621 consensus = networkstatus_get_live_consensus(now);
2623 memset(&voting_schedule, 0, sizeof(voting_schedule));
2625 if (consensus) {
2626 interval = (int)( consensus->fresh_until - consensus->valid_after );
2627 vote_delay = consensus->vote_seconds;
2628 dist_delay = consensus->dist_seconds;
2629 } else {
2630 interval = options->TestingV3AuthInitialVotingInterval;
2631 vote_delay = options->TestingV3AuthInitialVoteDelay;
2632 dist_delay = options->TestingV3AuthInitialDistDelay;
2635 tor_assert(interval > 0);
2637 if (vote_delay + dist_delay > interval/2)
2638 vote_delay = dist_delay = interval / 4;
2640 start = voting_schedule.interval_starts =
2641 dirvote_get_start_of_next_interval(now,interval,
2642 options->TestingV3AuthVotingStartOffset);
2643 end = dirvote_get_start_of_next_interval(start+1, interval,
2644 options->TestingV3AuthVotingStartOffset);
2646 tor_assert(end > start);
2648 voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
2649 voting_schedule.voting_ends = start - dist_delay;
2650 voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
2651 voting_schedule.voting_starts = start - dist_delay - vote_delay;
2654 char tbuf[ISO_TIME_LEN+1];
2655 format_iso_time(tbuf, voting_schedule.interval_starts);
2656 log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
2657 "consensus_set=%d, interval=%d",
2658 tbuf, consensus?1:0, interval);
2662 /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
2663 void
2664 dirvote_act(const or_options_t *options, time_t now)
2666 if (!authdir_mode_v3(options))
2667 return;
2668 if (!voting_schedule.voting_starts) {
2669 char *keys = list_v3_auth_ids();
2670 authority_cert_t *c = get_my_v3_authority_cert();
2671 log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
2672 "Mine is %s.",
2673 keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
2674 tor_free(keys);
2675 dirvote_recalculate_timing(options, now);
2677 if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
2678 log_notice(LD_DIR, "Time to vote.");
2679 dirvote_perform_vote();
2680 voting_schedule.have_voted = 1;
2682 if (voting_schedule.fetch_missing_votes < now &&
2683 !voting_schedule.have_fetched_missing_votes) {
2684 log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
2685 dirvote_fetch_missing_votes();
2686 voting_schedule.have_fetched_missing_votes = 1;
2688 if (voting_schedule.voting_ends < now &&
2689 !voting_schedule.have_built_consensus) {
2690 log_notice(LD_DIR, "Time to compute a consensus.");
2691 dirvote_compute_consensuses();
2692 /* XXXX We will want to try again later if we haven't got enough
2693 * votes yet. Implement this if it turns out to ever happen. */
2694 voting_schedule.have_built_consensus = 1;
2696 if (voting_schedule.fetch_missing_signatures < now &&
2697 !voting_schedule.have_fetched_missing_signatures) {
2698 log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
2699 dirvote_fetch_missing_signatures();
2700 voting_schedule.have_fetched_missing_signatures = 1;
2702 if (voting_schedule.interval_starts < now &&
2703 !voting_schedule.have_published_consensus) {
2704 log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
2705 dirvote_publish_consensus();
2706 dirvote_clear_votes(0);
2707 voting_schedule.have_published_consensus = 1;
2708 /* XXXX We will want to try again later if we haven't got enough
2709 * signatures yet. Implement this if it turns out to ever happen. */
2710 dirvote_recalculate_timing(options, now);
2714 /** A vote networkstatus_t and its unparsed body: held around so we can
2715 * use it to generate a consensus (at voting_ends) and so we can serve it to
2716 * other authorities that might want it. */
2717 typedef struct pending_vote_t {
2718 cached_dir_t *vote_body;
2719 networkstatus_t *vote;
2720 } pending_vote_t;
2722 /** List of pending_vote_t for the current vote. Before we've used them to
2723 * build a consensus, the votes go here. */
2724 static smartlist_t *pending_vote_list = NULL;
2725 /** List of pending_vote_t for the previous vote. After we've used them to
2726 * build a consensus, the votes go here for the next period. */
2727 static smartlist_t *previous_vote_list = NULL;
2729 /* DOCDOC pending_consensuses */
2730 static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
2732 /** The detached signatures for the consensus that we're currently
2733 * building. */
2734 static char *pending_consensus_signatures = NULL;
2736 /** List of ns_detached_signatures_t: hold signatures that get posted to us
2737 * before we have generated the consensus on our own. */
2738 static smartlist_t *pending_consensus_signature_list = NULL;
2740 /** Generate a networkstatus vote and post it to all the v3 authorities.
2741 * (V3 Authority only) */
2742 static int
2743 dirvote_perform_vote(void)
2745 crypto_pk_t *key = get_my_v3_authority_signing_key();
2746 authority_cert_t *cert = get_my_v3_authority_cert();
2747 networkstatus_t *ns;
2748 char *contents;
2749 pending_vote_t *pending_vote;
2750 time_t now = time(NULL);
2752 int status;
2753 const char *msg = "";
2755 if (!cert || !key) {
2756 log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
2757 return -1;
2758 } else if (cert->expires < now) {
2759 log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
2760 return -1;
2762 if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
2763 return -1;
2765 contents = format_networkstatus_vote(key, ns);
2766 networkstatus_vote_free(ns);
2767 if (!contents)
2768 return -1;
2770 pending_vote = dirvote_add_vote(contents, &msg, &status);
2771 tor_free(contents);
2772 if (!pending_vote) {
2773 log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
2774 msg);
2775 return -1;
2778 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
2779 ROUTER_PURPOSE_GENERAL,
2780 V3_DIRINFO,
2781 pending_vote->vote_body->dir,
2782 pending_vote->vote_body->dir_len, 0);
2783 log_notice(LD_DIR, "Vote posted.");
2784 return 0;
2787 /** Send an HTTP request to every other v3 authority, for the votes of every
2788 * authority for which we haven't received a vote yet in this period. (V3
2789 * authority only) */
2790 static void
2791 dirvote_fetch_missing_votes(void)
2793 smartlist_t *missing_fps = smartlist_new();
2794 char *resource;
2796 SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
2797 dir_server_t *, ds) {
2798 if (!(ds->type & V3_DIRINFO))
2799 continue;
2800 if (!dirvote_get_vote(ds->v3_identity_digest,
2801 DGV_BY_ID|DGV_INCLUDE_PENDING)) {
2802 char *cp = tor_malloc(HEX_DIGEST_LEN+1);
2803 base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
2804 DIGEST_LEN);
2805 smartlist_add(missing_fps, cp);
2807 } SMARTLIST_FOREACH_END(ds);
2809 if (!smartlist_len(missing_fps)) {
2810 smartlist_free(missing_fps);
2811 return;
2814 char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
2815 log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
2816 "Asking every other authority for a copy.",
2817 smartlist_len(missing_fps), tmp);
2818 tor_free(tmp);
2820 resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
2821 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
2822 0, resource);
2823 tor_free(resource);
2824 SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
2825 smartlist_free(missing_fps);
2828 /** Send a request to every other authority for its detached signatures,
2829 * unless we have signatures from all other v3 authorities already. */
2830 static void
2831 dirvote_fetch_missing_signatures(void)
2833 int need_any = 0;
2834 int i;
2835 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
2836 networkstatus_t *consensus = pending_consensuses[i].consensus;
2837 if (!consensus ||
2838 networkstatus_check_consensus_signature(consensus, -1) == 1) {
2839 /* We have no consensus, or we have one that's signed by everybody. */
2840 continue;
2842 need_any = 1;
2844 if (!need_any)
2845 return;
2847 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
2848 0, NULL);
2851 /** Release all storage held by pending consensuses (those waiting for
2852 * signatures). */
2853 static void
2854 dirvote_clear_pending_consensuses(void)
2856 int i;
2857 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
2858 pending_consensus_t *pc = &pending_consensuses[i];
2859 tor_free(pc->body);
2861 networkstatus_vote_free(pc->consensus);
2862 pc->consensus = NULL;
2866 /** Drop all currently pending votes, consensus, and detached signatures. */
2867 static void
2868 dirvote_clear_votes(int all_votes)
2870 if (!previous_vote_list)
2871 previous_vote_list = smartlist_new();
2872 if (!pending_vote_list)
2873 pending_vote_list = smartlist_new();
2875 /* All "previous" votes are now junk. */
2876 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
2877 cached_dir_decref(v->vote_body);
2878 v->vote_body = NULL;
2879 networkstatus_vote_free(v->vote);
2880 tor_free(v);
2882 smartlist_clear(previous_vote_list);
2884 if (all_votes) {
2885 /* If we're dumping all the votes, we delete the pending ones. */
2886 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
2887 cached_dir_decref(v->vote_body);
2888 v->vote_body = NULL;
2889 networkstatus_vote_free(v->vote);
2890 tor_free(v);
2892 } else {
2893 /* Otherwise, we move them into "previous". */
2894 smartlist_add_all(previous_vote_list, pending_vote_list);
2896 smartlist_clear(pending_vote_list);
2898 if (pending_consensus_signature_list) {
2899 SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
2900 tor_free(cp));
2901 smartlist_clear(pending_consensus_signature_list);
2903 tor_free(pending_consensus_signatures);
2904 dirvote_clear_pending_consensuses();
2907 /** Return a newly allocated string containing the hex-encoded v3 authority
2908 identity digest of every recognized v3 authority. */
2909 static char *
2910 list_v3_auth_ids(void)
2912 smartlist_t *known_v3_keys = smartlist_new();
2913 char *keys;
2914 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2915 dir_server_t *, ds,
2916 if ((ds->type & V3_DIRINFO) &&
2917 !tor_digest_is_zero(ds->v3_identity_digest))
2918 smartlist_add(known_v3_keys,
2919 tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
2920 keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
2921 SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
2922 smartlist_free(known_v3_keys);
2923 return keys;
2926 /** Called when we have received a networkstatus vote in <b>vote_body</b>.
2927 * Parse and validate it, and on success store it as a pending vote (which we
2928 * then return). Return NULL on failure. Sets *<b>msg_out</b> and
2929 * *<b>status_out</b> to an HTTP response and status code. (V3 authority
2930 * only) */
2931 pending_vote_t *
2932 dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
2934 networkstatus_t *vote;
2935 networkstatus_voter_info_t *vi;
2936 dir_server_t *ds;
2937 pending_vote_t *pending_vote = NULL;
2938 const char *end_of_vote = NULL;
2939 int any_failed = 0;
2940 tor_assert(vote_body);
2941 tor_assert(msg_out);
2942 tor_assert(status_out);
2944 if (!pending_vote_list)
2945 pending_vote_list = smartlist_new();
2946 *status_out = 0;
2947 *msg_out = NULL;
2949 again:
2950 vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
2951 NS_TYPE_VOTE);
2952 if (!end_of_vote)
2953 end_of_vote = vote_body + strlen(vote_body);
2954 if (!vote) {
2955 log_warn(LD_DIR, "Couldn't parse vote: length was %d",
2956 (int)strlen(vote_body));
2957 *msg_out = "Unable to parse vote";
2958 goto err;
2960 tor_assert(smartlist_len(vote->voters) == 1);
2961 vi = get_voter(vote);
2963 int any_sig_good = 0;
2964 SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
2965 if (sig->good_signature)
2966 any_sig_good = 1);
2967 tor_assert(any_sig_good);
2969 ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
2970 if (!ds) {
2971 char *keys = list_v3_auth_ids();
2972 log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
2973 "with authority key ID %s. "
2974 "This key ID is not recognized. Known v3 key IDs are: %s",
2975 vi->nickname, vi->address,
2976 hex_str(vi->identity_digest, DIGEST_LEN), keys);
2977 tor_free(keys);
2978 *msg_out = "Vote not from a recognized v3 authority";
2979 goto err;
2981 tor_assert(vote->cert);
2982 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2983 vote->cert->signing_key_digest)) {
2984 /* Hey, it's a new cert! */
2985 trusted_dirs_load_certs_from_string(
2986 vote->cert->cache_info.signed_descriptor_body,
2987 TRUSTED_DIRS_CERTS_SRC_FROM_VOTE, 1 /*flush*/);
2988 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2989 vote->cert->signing_key_digest)) {
2990 log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
2994 /* Is it for the right period? */
2995 if (vote->valid_after != voting_schedule.interval_starts) {
2996 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
2997 format_iso_time(tbuf1, vote->valid_after);
2998 format_iso_time(tbuf2, voting_schedule.interval_starts);
2999 log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
3000 "we were expecting %s", vi->address, tbuf1, tbuf2);
3001 *msg_out = "Bad valid-after time";
3002 goto err;
3005 /* Fetch any new router descriptors we just learned about */
3006 update_consensus_router_descriptor_downloads(time(NULL), 1, vote);
3008 /* Now see whether we already have a vote from this authority. */
3009 SMARTLIST_FOREACH_BEGIN(pending_vote_list, pending_vote_t *, v) {
3010 if (fast_memeq(v->vote->cert->cache_info.identity_digest,
3011 vote->cert->cache_info.identity_digest,
3012 DIGEST_LEN)) {
3013 networkstatus_voter_info_t *vi_old = get_voter(v->vote);
3014 if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
3015 /* Ah, it's the same vote. Not a problem. */
3016 log_info(LD_DIR, "Discarding a vote we already have (from %s).",
3017 vi->address);
3018 if (*status_out < 200)
3019 *status_out = 200;
3020 goto discard;
3021 } else if (v->vote->published < vote->published) {
3022 log_notice(LD_DIR, "Replacing an older pending vote from this "
3023 "directory.");
3024 cached_dir_decref(v->vote_body);
3025 networkstatus_vote_free(v->vote);
3026 v->vote_body = new_cached_dir(tor_strndup(vote_body,
3027 end_of_vote-vote_body),
3028 vote->published);
3029 v->vote = vote;
3030 if (end_of_vote &&
3031 !strcmpstart(end_of_vote, "network-status-version"))
3032 goto again;
3034 if (*status_out < 200)
3035 *status_out = 200;
3036 if (!*msg_out)
3037 *msg_out = "OK";
3038 return v;
3039 } else {
3040 *msg_out = "Already have a newer pending vote";
3041 goto err;
3044 } SMARTLIST_FOREACH_END(v);
3046 pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
3047 pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
3048 end_of_vote-vote_body),
3049 vote->published);
3050 pending_vote->vote = vote;
3051 smartlist_add(pending_vote_list, pending_vote);
3053 if (!strcmpstart(end_of_vote, "network-status-version ")) {
3054 vote_body = end_of_vote;
3055 goto again;
3058 goto done;
3060 err:
3061 any_failed = 1;
3062 if (!*msg_out)
3063 *msg_out = "Error adding vote";
3064 if (*status_out < 400)
3065 *status_out = 400;
3067 discard:
3068 networkstatus_vote_free(vote);
3070 if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
3071 vote_body = end_of_vote;
3072 goto again;
3075 done:
3077 if (*status_out < 200)
3078 *status_out = 200;
3079 if (!*msg_out) {
3080 if (!any_failed && !pending_vote) {
3081 *msg_out = "Duplicate discarded";
3082 } else {
3083 *msg_out = "ok";
3087 return any_failed ? NULL : pending_vote;
3090 /** Try to compute a v3 networkstatus consensus from the currently pending
3091 * votes. Return 0 on success, -1 on failure. Store the consensus in
3092 * pending_consensus: it won't be ready to be published until we have
3093 * everybody else's signatures collected too. (V3 Authority only) */
3094 static int
3095 dirvote_compute_consensuses(void)
3097 /* Have we got enough votes to try? */
3098 int n_votes, n_voters, n_vote_running = 0;
3099 smartlist_t *votes = NULL, *votestrings = NULL;
3100 char *consensus_body = NULL, *signatures = NULL, *votefile;
3101 networkstatus_t *consensus = NULL;
3102 authority_cert_t *my_cert;
3103 pending_consensus_t pending[N_CONSENSUS_FLAVORS];
3104 int flav;
3106 memset(pending, 0, sizeof(pending));
3108 if (!pending_vote_list)
3109 pending_vote_list = smartlist_new();
3111 n_voters = get_n_authorities(V3_DIRINFO);
3112 n_votes = smartlist_len(pending_vote_list);
3113 if (n_votes <= n_voters/2) {
3114 log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
3115 "%d of %d", n_votes, n_voters/2+1);
3116 goto err;
3118 tor_assert(pending_vote_list);
3119 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
3120 if (smartlist_contains_string(v->vote->known_flags, "Running"))
3121 n_vote_running++;
3123 if (!n_vote_running) {
3124 /* See task 1066. */
3125 log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
3126 "and publishing a consensus without Running nodes "
3127 "would make many clients stop working. Not "
3128 "generating a consensus!");
3129 goto err;
3132 if (!(my_cert = get_my_v3_authority_cert())) {
3133 log_warn(LD_DIR, "Can't generate consensus without a certificate.");
3134 goto err;
3137 votes = smartlist_new();
3138 votestrings = smartlist_new();
3139 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
3141 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
3142 c->bytes = v->vote_body->dir;
3143 c->len = v->vote_body->dir_len;
3144 smartlist_add(votestrings, c); /* collect strings to write to disk */
3146 smartlist_add(votes, v->vote); /* collect votes to compute consensus */
3149 votefile = get_datadir_fname("v3-status-votes");
3150 write_chunks_to_file(votefile, votestrings, 0, 0);
3151 tor_free(votefile);
3152 SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
3153 smartlist_free(votestrings);
3156 char legacy_dbuf[DIGEST_LEN];
3157 crypto_pk_t *legacy_sign=NULL;
3158 char *legacy_id_digest = NULL;
3159 int n_generated = 0;
3160 if (get_options()->V3AuthUseLegacyKey) {
3161 authority_cert_t *cert = get_my_v3_legacy_cert();
3162 legacy_sign = get_my_v3_legacy_signing_key();
3163 if (cert) {
3164 if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
3165 log_warn(LD_BUG,
3166 "Unable to compute digest of legacy v3 identity key");
3167 } else {
3168 legacy_id_digest = legacy_dbuf;
3173 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
3174 const char *flavor_name = networkstatus_get_flavor_name(flav);
3175 consensus_body = networkstatus_compute_consensus(
3176 votes, n_voters,
3177 my_cert->identity_key,
3178 get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
3179 flav);
3181 if (!consensus_body) {
3182 log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
3183 flavor_name);
3184 continue;
3186 consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
3187 NS_TYPE_CONSENSUS);
3188 if (!consensus) {
3189 log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
3190 flavor_name);
3191 tor_free(consensus_body);
3192 continue;
3195 /* 'Check' our own signature, to mark it valid. */
3196 networkstatus_check_consensus_signature(consensus, -1);
3198 pending[flav].body = consensus_body;
3199 pending[flav].consensus = consensus;
3200 n_generated++;
3201 consensus_body = NULL;
3202 consensus = NULL;
3204 if (!n_generated) {
3205 log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
3206 goto err;
3210 signatures = get_detached_signatures_from_pending_consensuses(
3211 pending, N_CONSENSUS_FLAVORS);
3213 if (!signatures) {
3214 log_warn(LD_DIR, "Couldn't extract signatures.");
3215 goto err;
3218 dirvote_clear_pending_consensuses();
3219 memcpy(pending_consensuses, pending, sizeof(pending));
3221 tor_free(pending_consensus_signatures);
3222 pending_consensus_signatures = signatures;
3224 if (pending_consensus_signature_list) {
3225 int n_sigs = 0;
3226 /* we may have gotten signatures for this consensus before we built
3227 * it ourself. Add them now. */
3228 SMARTLIST_FOREACH_BEGIN(pending_consensus_signature_list, char *, sig) {
3229 const char *msg = NULL;
3230 int r = dirvote_add_signatures_to_all_pending_consensuses(sig,
3231 "pending", &msg);
3232 if (r >= 0)
3233 n_sigs += r;
3234 else
3235 log_warn(LD_DIR,
3236 "Could not add queued signature to new consensus: %s",
3237 msg);
3238 tor_free(sig);
3239 } SMARTLIST_FOREACH_END(sig);
3240 if (n_sigs)
3241 log_notice(LD_DIR, "Added %d pending signatures while building "
3242 "consensus.", n_sigs);
3243 smartlist_clear(pending_consensus_signature_list);
3246 log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
3248 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
3249 ROUTER_PURPOSE_GENERAL,
3250 V3_DIRINFO,
3251 pending_consensus_signatures,
3252 strlen(pending_consensus_signatures), 0);
3253 log_notice(LD_DIR, "Signature(s) posted.");
3255 smartlist_free(votes);
3256 return 0;
3257 err:
3258 smartlist_free(votes);
3259 tor_free(consensus_body);
3260 tor_free(signatures);
3261 networkstatus_vote_free(consensus);
3263 return -1;
3266 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3267 * signatures on the currently pending consensus. Add them to <b>pc</b>
3268 * as appropriate. Return the number of signatures added. (?) */
3269 static int
3270 dirvote_add_signatures_to_pending_consensus(
3271 pending_consensus_t *pc,
3272 ns_detached_signatures_t *sigs,
3273 const char *source,
3274 int severity,
3275 const char **msg_out)
3277 const char *flavor_name;
3278 int r = -1;
3280 /* Only call if we have a pending consensus right now. */
3281 tor_assert(pc->consensus);
3282 tor_assert(pc->body);
3283 tor_assert(pending_consensus_signatures);
3285 flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
3286 *msg_out = NULL;
3289 smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
3290 log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
3291 sig_list ? smartlist_len(sig_list) : 0, flavor_name);
3293 r = networkstatus_add_detached_signatures(pc->consensus, sigs,
3294 source, severity, msg_out);
3295 log_info(LD_DIR,"Added %d signatures to consensus.", r);
3297 if (r >= 1) {
3298 char *new_signatures =
3299 networkstatus_format_signatures(pc->consensus, 0);
3300 char *dst, *dst_end;
3301 size_t new_consensus_len;
3302 if (!new_signatures) {
3303 *msg_out = "No signatures to add";
3304 goto err;
3306 new_consensus_len =
3307 strlen(pc->body) + strlen(new_signatures) + 1;
3308 pc->body = tor_realloc(pc->body, new_consensus_len);
3309 dst_end = pc->body + new_consensus_len;
3310 dst = strstr(pc->body, "directory-signature ");
3311 tor_assert(dst);
3312 strlcpy(dst, new_signatures, dst_end-dst);
3314 /* We remove this block once it has failed to crash for a while. But
3315 * unless it shows up in profiles, we're probably better leaving it in,
3316 * just in case we break detached signature processing at some point. */
3318 networkstatus_t *v = networkstatus_parse_vote_from_string(
3319 pc->body, NULL,
3320 NS_TYPE_CONSENSUS);
3321 tor_assert(v);
3322 networkstatus_vote_free(v);
3324 *msg_out = "Signatures added";
3325 tor_free(new_signatures);
3326 } else if (r == 0) {
3327 *msg_out = "Signatures ignored";
3328 } else {
3329 goto err;
3332 goto done;
3333 err:
3334 if (!*msg_out)
3335 *msg_out = "Unrecognized error while adding detached signatures.";
3336 done:
3337 return r;
3340 static int
3341 dirvote_add_signatures_to_all_pending_consensuses(
3342 const char *detached_signatures_body,
3343 const char *source,
3344 const char **msg_out)
3346 int r=0, i, n_added = 0, errors = 0;
3347 ns_detached_signatures_t *sigs;
3348 tor_assert(detached_signatures_body);
3349 tor_assert(msg_out);
3350 tor_assert(pending_consensus_signatures);
3352 if (!(sigs = networkstatus_parse_detached_signatures(
3353 detached_signatures_body, NULL))) {
3354 *msg_out = "Couldn't parse detached signatures.";
3355 goto err;
3358 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3359 int res;
3360 int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
3361 pending_consensus_t *pc = &pending_consensuses[i];
3362 if (!pc->consensus)
3363 continue;
3364 res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
3365 severity, msg_out);
3366 if (res < 0)
3367 errors++;
3368 else
3369 n_added += res;
3372 if (errors && !n_added) {
3373 r = -1;
3374 goto err;
3377 if (n_added && pending_consensuses[FLAV_NS].consensus) {
3378 char *new_detached =
3379 get_detached_signatures_from_pending_consensuses(
3380 pending_consensuses, N_CONSENSUS_FLAVORS);
3381 if (new_detached) {
3382 tor_free(pending_consensus_signatures);
3383 pending_consensus_signatures = new_detached;
3387 r = n_added;
3388 goto done;
3389 err:
3390 if (!*msg_out)
3391 *msg_out = "Unrecognized error while adding detached signatures.";
3392 done:
3393 ns_detached_signatures_free(sigs);
3394 /* XXXX NM Check how return is used. We can now have an error *and*
3395 signatures added. */
3396 return r;
3399 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3400 * signatures on the currently pending consensus. Add them to the pending
3401 * consensus (if we have one); otherwise queue them until we have a
3402 * consensus. Return negative on failure, nonnegative on success. */
3404 dirvote_add_signatures(const char *detached_signatures_body,
3405 const char *source,
3406 const char **msg)
3408 if (pending_consensuses[FLAV_NS].consensus) {
3409 log_notice(LD_DIR, "Got a signature from %s. "
3410 "Adding it to the pending consensus.", source);
3411 return dirvote_add_signatures_to_all_pending_consensuses(
3412 detached_signatures_body, source, msg);
3413 } else {
3414 log_notice(LD_DIR, "Got a signature from %s. "
3415 "Queuing it for the next consensus.", source);
3416 if (!pending_consensus_signature_list)
3417 pending_consensus_signature_list = smartlist_new();
3418 smartlist_add(pending_consensus_signature_list,
3419 tor_strdup(detached_signatures_body));
3420 *msg = "Signature queued";
3421 return 0;
3425 /** Replace the consensus that we're currently serving with the one that we've
3426 * been building. (V3 Authority only) */
3427 static int
3428 dirvote_publish_consensus(void)
3430 int i;
3432 /* Now remember all the other consensuses as if we were a directory cache. */
3433 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3434 pending_consensus_t *pending = &pending_consensuses[i];
3435 const char *name;
3436 name = networkstatus_get_flavor_name(i);
3437 tor_assert(name);
3438 if (!pending->consensus ||
3439 networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
3440 log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
3441 continue;
3444 if (networkstatus_set_current_consensus(pending->body, name, 0))
3445 log_warn(LD_DIR, "Error publishing %s consensus", name);
3446 else
3447 log_notice(LD_DIR, "Published %s consensus", name);
3450 return 0;
3453 /** Release all static storage held in dirvote.c */
3454 void
3455 dirvote_free_all(void)
3457 dirvote_clear_votes(1);
3458 /* now empty as a result of dirvote_clear_votes(). */
3459 smartlist_free(pending_vote_list);
3460 pending_vote_list = NULL;
3461 smartlist_free(previous_vote_list);
3462 previous_vote_list = NULL;
3464 dirvote_clear_pending_consensuses();
3465 tor_free(pending_consensus_signatures);
3466 if (pending_consensus_signature_list) {
3467 /* now empty as a result of dirvote_clear_votes(). */
3468 smartlist_free(pending_consensus_signature_list);
3469 pending_consensus_signature_list = NULL;
3473 /* ====
3474 * Access to pending items.
3475 * ==== */
3477 /** Return the body of the consensus that we're currently trying to build. */
3478 const char *
3479 dirvote_get_pending_consensus(consensus_flavor_t flav)
3481 tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
3482 return pending_consensuses[flav].body;
3485 /** Return the signatures that we know for the consensus that we're currently
3486 * trying to build. */
3487 const char *
3488 dirvote_get_pending_detached_signatures(void)
3490 return pending_consensus_signatures;
3493 /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
3494 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
3495 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
3496 * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
3497 * false, do not consider any votes for a consensus that's already been built.
3498 * If <b>include_pending</b> is false, do not consider any votes for the
3499 * consensus that's in progress. May return NULL if we have no vote for the
3500 * authority in question. */
3501 const cached_dir_t *
3502 dirvote_get_vote(const char *fp, int flags)
3504 int by_id = flags & DGV_BY_ID;
3505 const int include_pending = flags & DGV_INCLUDE_PENDING;
3506 const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
3508 if (!pending_vote_list && !previous_vote_list)
3509 return NULL;
3510 if (fp == NULL) {
3511 authority_cert_t *c = get_my_v3_authority_cert();
3512 if (c) {
3513 fp = c->cache_info.identity_digest;
3514 by_id = 1;
3515 } else
3516 return NULL;
3518 if (by_id) {
3519 if (pending_vote_list && include_pending) {
3520 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3521 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3522 return pv->vote_body);
3524 if (previous_vote_list && include_previous) {
3525 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3526 if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3527 return pv->vote_body);
3529 } else {
3530 if (pending_vote_list && include_pending) {
3531 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3532 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3533 return pv->vote_body);
3535 if (previous_vote_list && include_previous) {
3536 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3537 if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3538 return pv->vote_body);
3541 return NULL;
3544 /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
3545 * according to <b>consensus_method</b>.
3547 microdesc_t *
3548 dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
3550 microdesc_t *result = NULL;
3551 char *key = NULL, *summary = NULL, *family = NULL;
3552 size_t keylen;
3553 smartlist_t *chunks = smartlist_new();
3554 char *output = NULL;
3556 if (crypto_pk_write_public_key_to_string(ri->onion_pkey, &key, &keylen)<0)
3557 goto done;
3558 summary = policy_summarize(ri->exit_policy, AF_INET);
3559 if (ri->declared_family)
3560 family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
3562 smartlist_add_asprintf(chunks, "onion-key\n%s", key);
3564 if (consensus_method >= MIN_METHOD_FOR_NTOR_KEY &&
3565 ri->onion_curve25519_pkey) {
3566 char kbuf[128];
3567 base64_encode(kbuf, sizeof(kbuf),
3568 (const char*)ri->onion_curve25519_pkey->public_key,
3569 CURVE25519_PUBKEY_LEN);
3570 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
3573 if (consensus_method >= MIN_METHOD_FOR_A_LINES &&
3574 !tor_addr_is_null(&ri->ipv6_addr) && ri->ipv6_orport)
3575 smartlist_add_asprintf(chunks, "a %s\n",
3576 fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
3578 if (family)
3579 smartlist_add_asprintf(chunks, "family %s\n", family);
3581 if (summary && strcmp(summary, "reject 1-65535"))
3582 smartlist_add_asprintf(chunks, "p %s\n", summary);
3584 if (consensus_method >= MIN_METHOD_FOR_P6_LINES &&
3585 ri->ipv6_exit_policy) {
3586 /* XXXX024 This doesn't match proposal 208, which says these should
3587 * be taken unchanged from the routerinfo. That's bogosity, IMO:
3588 * the proposal should have said to do this instead.*/
3589 char *p6 = write_short_policy(ri->ipv6_exit_policy);
3590 if (p6 && strcmp(p6, "reject 1-65535"))
3591 smartlist_add_asprintf(chunks, "p6 %s\n", p6);
3592 tor_free(p6);
3595 if (consensus_method >= MIN_METHOD_FOR_ID_HASH_IN_MD) {
3596 char idbuf[BASE64_DIGEST_LEN+1];
3597 digest_to_base64(idbuf, ri->cache_info.identity_digest);
3598 smartlist_add_asprintf(chunks, "id rsa1024 %s\n", idbuf);
3601 output = smartlist_join_strings(chunks, "", 0, NULL);
3604 smartlist_t *lst = microdescs_parse_from_string(output,
3605 output+strlen(output), 0,
3606 SAVED_NOWHERE);
3607 if (smartlist_len(lst) != 1) {
3608 log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
3609 SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
3610 smartlist_free(lst);
3611 goto done;
3613 result = smartlist_get(lst, 0);
3614 smartlist_free(lst);
3617 done:
3618 tor_free(output);
3619 tor_free(key);
3620 tor_free(summary);
3621 tor_free(family);
3622 if (chunks) {
3623 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
3624 smartlist_free(chunks);
3626 return result;
3629 /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
3630 * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
3631 * in <b>out</b>. Return -1 on failure and the number of characters written
3632 * on success. */
3633 ssize_t
3634 dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
3635 const microdesc_t *md,
3636 int consensus_method_low,
3637 int consensus_method_high)
3639 ssize_t ret = -1;
3640 char d64[BASE64_DIGEST256_LEN+1];
3641 char *microdesc_consensus_methods =
3642 make_consensus_method_list(consensus_method_low,
3643 consensus_method_high,
3644 ",");
3645 tor_assert(microdesc_consensus_methods);
3647 if (digest256_to_base64(d64, md->digest)<0)
3648 goto out;
3650 if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
3651 microdesc_consensus_methods, d64)<0)
3652 goto out;
3654 ret = strlen(out_buf);
3656 out:
3657 tor_free(microdesc_consensus_methods);
3658 return ret;
3661 /** Array of start and end of consensus methods used for supported
3662 microdescriptor formats. */
3663 static const struct consensus_method_range_t {
3664 int low;
3665 int high;
3666 } microdesc_consensus_methods[] = {
3667 {MIN_METHOD_FOR_MICRODESC, MIN_METHOD_FOR_A_LINES - 1},
3668 {MIN_METHOD_FOR_A_LINES, MIN_METHOD_FOR_P6_LINES - 1},
3669 {MIN_METHOD_FOR_P6_LINES, MIN_METHOD_FOR_NTOR_KEY - 1},
3670 {MIN_METHOD_FOR_NTOR_KEY, MIN_METHOD_FOR_ID_HASH_IN_MD - 1},
3671 {MIN_METHOD_FOR_ID_HASH_IN_MD, MAX_SUPPORTED_CONSENSUS_METHOD},
3672 {-1, -1}
3675 /** Helper type used when generating the microdescriptor lines in a directory
3676 * vote. */
3677 typedef struct microdesc_vote_line_t {
3678 int low;
3679 int high;
3680 microdesc_t *md;
3681 struct microdesc_vote_line_t *next;
3682 } microdesc_vote_line_t;
3684 /** Generate and return a linked list of all the lines that should appear to
3685 * describe a router's microdescriptor versions in a directory vote.
3686 * Add the generated microdescriptors to <b>microdescriptors_out</b>. */
3687 vote_microdesc_hash_t *
3688 dirvote_format_all_microdesc_vote_lines(const routerinfo_t *ri, time_t now,
3689 smartlist_t *microdescriptors_out)
3691 const struct consensus_method_range_t *cmr;
3692 microdesc_vote_line_t *entries = NULL, *ep;
3693 vote_microdesc_hash_t *result = NULL;
3695 /* Generate the microdescriptors. */
3696 for (cmr = microdesc_consensus_methods;
3697 cmr->low != -1 && cmr->high != -1;
3698 cmr++) {
3699 microdesc_t *md = dirvote_create_microdescriptor(ri, cmr->low);
3700 if (md) {
3701 microdesc_vote_line_t *e =
3702 tor_malloc_zero(sizeof(microdesc_vote_line_t));
3703 e->md = md;
3704 e->low = cmr->low;
3705 e->high = cmr->high;
3706 e->next = entries;
3707 entries = e;
3711 /* Compress adjacent identical ones */
3712 for (ep = entries; ep; ep = ep->next) {
3713 while (ep->next &&
3714 fast_memeq(ep->md->digest, ep->next->md->digest, DIGEST256_LEN) &&
3715 ep->low == ep->next->high + 1) {
3716 microdesc_vote_line_t *next = ep->next;
3717 ep->low = next->low;
3718 microdesc_free(next->md);
3719 ep->next = next->next;
3720 tor_free(next);
3724 /* Format them into vote_microdesc_hash_t, and add to microdescriptors_out.*/
3725 while ((ep = entries)) {
3726 char buf[128];
3727 vote_microdesc_hash_t *h;
3728 dirvote_format_microdesc_vote_line(buf, sizeof(buf), ep->md,
3729 ep->low, ep->high);
3730 h = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
3731 h->microdesc_hash_line = tor_strdup(buf);
3732 h->next = result;
3733 result = h;
3734 ep->md->last_listed = now;
3735 smartlist_add(microdescriptors_out, ep->md);
3736 entries = ep->next;
3737 tor_free(ep);
3740 return result;
3743 /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
3744 * the digest algorithm <b>alg</b>, decode it and copy it into
3745 * <b>digest256_out</b> and return 0. Otherwise return -1. */
3747 vote_routerstatus_find_microdesc_hash(char *digest256_out,
3748 const vote_routerstatus_t *vrs,
3749 int method,
3750 digest_algorithm_t alg)
3752 /* XXXX only returns the sha256 method. */
3753 const vote_microdesc_hash_t *h;
3754 char mstr[64];
3755 size_t mlen;
3756 char dstr[64];
3758 tor_snprintf(mstr, sizeof(mstr), "%d", method);
3759 mlen = strlen(mstr);
3760 tor_snprintf(dstr, sizeof(dstr), " %s=",
3761 crypto_digest_algorithm_get_name(alg));
3763 for (h = vrs->microdesc; h; h = h->next) {
3764 const char *cp = h->microdesc_hash_line;
3765 size_t num_len;
3766 /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
3767 * the first part. */
3768 while (1) {
3769 num_len = strspn(cp, "1234567890");
3770 if (num_len == mlen && fast_memeq(mstr, cp, mlen)) {
3771 /* This is the line. */
3772 char buf[BASE64_DIGEST256_LEN+1];
3773 /* XXXX ignores extraneous stuff if the digest is too long. This
3774 * seems harmless enough, right? */
3775 cp = strstr(cp, dstr);
3776 if (!cp)
3777 return -1;
3778 cp += strlen(dstr);
3779 strlcpy(buf, cp, sizeof(buf));
3780 return digest256_from_base64(digest256_out, buf);
3782 if (num_len == 0 || cp[num_len] != ',')
3783 break;
3784 cp += num_len + 1;
3787 return -1;