Send control port events for timeouts.
[tor.git] / src / or / dirvote.c
blobeae3bc8a40d51497afaac6958475b2375be11060
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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 static int dirvote_add_signatures_to_all_pending_consensuses(
37 const char *detached_signatures_body,
38 const char **msg_out);
39 static int dirvote_add_signatures_to_pending_consensus(
40 pending_consensus_t *pc,
41 ns_detached_signatures_t *sigs,
42 const char **msg_out);
43 static char *list_v3_auth_ids(void);
44 static void dirvote_fetch_missing_votes(void);
45 static void dirvote_fetch_missing_signatures(void);
46 static int dirvote_perform_vote(void);
47 static void dirvote_clear_votes(int all_votes);
48 static int dirvote_compute_consensuses(void);
49 static int dirvote_publish_consensus(void);
50 static char *make_consensus_method_list(int low, int high, const char *sep);
52 /** The highest consensus method that we currently support. */
53 #define MAX_SUPPORTED_CONSENSUS_METHOD 9
55 /** Lowest consensus method that contains a 'directory-footer' marker */
56 #define MIN_METHOD_FOR_FOOTER 9
58 /** Lowest consensus method that contains bandwidth weights */
59 #define MIN_METHOD_FOR_BW_WEIGHTS 9
61 /** Lowest consensus method that contains consensus params */
62 #define MIN_METHOD_FOR_PARAMS 7
64 /** Lowest consensus method that generates microdescriptors */
65 #define MIN_METHOD_FOR_MICRODESC 8
67 /* =====
68 * Voting
69 * =====*/
71 /* Overestimated. */
72 #define MICRODESC_LINE_LEN 80
74 /** Return a new string containing the string representation of the vote in
75 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
76 * For v3 authorities. */
77 char *
78 format_networkstatus_vote(crypto_pk_env_t *private_signing_key,
79 networkstatus_t *v3_ns)
81 size_t len;
82 char *status = NULL;
83 const char *client_versions = NULL, *server_versions = NULL;
84 char *outp, *endp;
85 char fingerprint[FINGERPRINT_LEN+1];
86 char ipaddr[INET_NTOA_BUF_LEN];
87 char digest[DIGEST_LEN];
88 struct in_addr in;
89 uint32_t addr;
90 routerlist_t *rl = router_get_routerlist();
91 char *version_lines = NULL;
92 int r;
93 networkstatus_voter_info_t *voter;
95 tor_assert(private_signing_key);
96 tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
98 voter = smartlist_get(v3_ns->voters, 0);
100 addr = voter->addr;
101 in.s_addr = htonl(addr);
102 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
104 base16_encode(fingerprint, sizeof(fingerprint),
105 v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
106 client_versions = v3_ns->client_versions;
107 server_versions = v3_ns->server_versions;
109 if (client_versions || server_versions) {
110 size_t v_len = 64;
111 char *cp;
112 if (client_versions)
113 v_len += strlen(client_versions);
114 if (server_versions)
115 v_len += strlen(server_versions);
116 version_lines = tor_malloc(v_len);
117 cp = version_lines;
118 if (client_versions) {
119 r = tor_snprintf(cp, v_len-(cp-version_lines),
120 "client-versions %s\n", client_versions);
121 if (r < 0) {
122 log_err(LD_BUG, "Insufficient memory for client-versions line");
123 tor_assert(0);
125 cp += strlen(cp);
127 if (server_versions) {
128 r = tor_snprintf(cp, v_len-(cp-version_lines),
129 "server-versions %s\n", server_versions);
130 if (r < 0) {
131 log_err(LD_BUG, "Insufficient memory for server-versions line");
132 tor_assert(0);
135 } else {
136 version_lines = tor_strdup("");
139 len = 8192;
140 len += strlen(version_lines);
141 len += (RS_ENTRY_LEN+MICRODESC_LINE_LEN)*smartlist_len(rl->routers);
142 len += strlen("\ndirectory-footer\n");
143 len += v3_ns->cert->cache_info.signed_descriptor_len;
145 status = tor_malloc(len);
147 char published[ISO_TIME_LEN+1];
148 char va[ISO_TIME_LEN+1];
149 char fu[ISO_TIME_LEN+1];
150 char vu[ISO_TIME_LEN+1];
151 char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
152 char *params;
153 authority_cert_t *cert = v3_ns->cert;
154 char *methods =
155 make_consensus_method_list(1, MAX_SUPPORTED_CONSENSUS_METHOD, " ");
156 format_iso_time(published, v3_ns->published);
157 format_iso_time(va, v3_ns->valid_after);
158 format_iso_time(fu, v3_ns->fresh_until);
159 format_iso_time(vu, v3_ns->valid_until);
161 if (v3_ns->net_params)
162 params = smartlist_join_strings(v3_ns->net_params, " ", 0, NULL);
163 else
164 params = tor_strdup("");
166 tor_assert(cert);
167 r = tor_snprintf(status, len,
168 "network-status-version 3\n"
169 "vote-status %s\n"
170 "consensus-methods %s\n"
171 "published %s\n"
172 "valid-after %s\n"
173 "fresh-until %s\n"
174 "valid-until %s\n"
175 "voting-delay %d %d\n"
176 "%s" /* versions */
177 "known-flags %s\n"
178 "params %s\n"
179 "dir-source %s %s %s %s %d %d\n"
180 "contact %s\n",
181 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
182 methods,
183 published, va, fu, vu,
184 v3_ns->vote_seconds, v3_ns->dist_seconds,
185 version_lines,
186 flags,
187 params,
188 voter->nickname, fingerprint, voter->address,
189 ipaddr, voter->dir_port, voter->or_port, voter->contact);
191 if (r < 0) {
192 log_err(LD_BUG, "Insufficient memory for network status line");
193 tor_assert(0);
196 tor_free(params);
197 tor_free(flags);
198 tor_free(methods);
199 outp = status + strlen(status);
200 endp = status + len;
202 if (!tor_digest_is_zero(voter->legacy_id_digest)) {
203 char fpbuf[HEX_DIGEST_LEN+1];
204 base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
205 r = tor_snprintf(outp, endp-outp, "legacy-dir-key %s\n", fpbuf);
206 if (r < 0) {
207 log_err(LD_BUG, "Insufficient memory for legacy-dir-key line");
208 tor_assert(0);
210 outp += strlen(outp);
213 tor_assert(outp + cert->cache_info.signed_descriptor_len < endp);
214 memcpy(outp, cert->cache_info.signed_descriptor_body,
215 cert->cache_info.signed_descriptor_len);
217 outp += cert->cache_info.signed_descriptor_len;
220 SMARTLIST_FOREACH_BEGIN(v3_ns->routerstatus_list, vote_routerstatus_t *,
221 vrs) {
222 vote_microdesc_hash_t *h;
223 if (routerstatus_format_entry(outp, endp-outp, &vrs->status,
224 vrs->version, NS_V3_VOTE) < 0) {
225 log_warn(LD_BUG, "Unable to print router status.");
226 goto err;
228 outp += strlen(outp);
230 for (h = vrs->microdesc; h; h = h->next) {
231 size_t mlen = strlen(h->microdesc_hash_line);
232 if (outp+mlen >= endp) {
233 log_warn(LD_BUG, "Can't fit microdesc line in vote.");
235 memcpy(outp, h->microdesc_hash_line, mlen+1);
236 outp += strlen(outp);
238 } SMARTLIST_FOREACH_END(vrs);
240 r = tor_snprintf(outp, endp-outp, "directory-footer\n");
241 if (r < 0) {
242 log_err(LD_BUG, "Insufficient memory for directory-footer line");
243 tor_assert(0);
245 outp += strlen(outp);
248 char signing_key_fingerprint[FINGERPRINT_LEN+1];
249 if (tor_snprintf(outp, endp-outp, "directory-signature ")<0) {
250 log_warn(LD_BUG, "Unable to start signature line.");
251 goto err;
253 outp += strlen(outp);
255 if (crypto_pk_get_fingerprint(private_signing_key,
256 signing_key_fingerprint, 0)<0) {
257 log_warn(LD_BUG, "Unable to get fingerprint for signing key");
258 goto err;
260 if (tor_snprintf(outp, endp-outp, "%s %s\n", fingerprint,
261 signing_key_fingerprint)<0) {
262 log_warn(LD_BUG, "Unable to end signature line.");
263 goto err;
265 outp += strlen(outp);
268 if (router_get_networkstatus_v3_hash(status, digest, DIGEST_SHA1)<0)
269 goto err;
270 note_crypto_pk_op(SIGN_DIR);
271 if (router_append_dirobj_signature(outp,endp-outp,digest, DIGEST_LEN,
272 private_signing_key)<0) {
273 log_warn(LD_BUG, "Unable to sign networkstatus vote.");
274 goto err;
278 networkstatus_t *v;
279 if (!(v = networkstatus_parse_vote_from_string(status, NULL,
280 v3_ns->type))) {
281 log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
282 "<<%s>>",
283 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
284 goto err;
286 networkstatus_vote_free(v);
289 goto done;
291 err:
292 tor_free(status);
293 done:
294 tor_free(version_lines);
295 return status;
298 /* =====
299 * Consensus generation
300 * ===== */
302 /** Given a vote <b>vote</b> (not a consensus!), return its associated
303 * networkstatus_voter_info_t. */
304 static networkstatus_voter_info_t *
305 get_voter(const networkstatus_t *vote)
307 tor_assert(vote);
308 tor_assert(vote->type == NS_TYPE_VOTE);
309 tor_assert(vote->voters);
310 tor_assert(smartlist_len(vote->voters) == 1);
311 return smartlist_get(vote->voters, 0);
314 /** Return the signature made by <b>voter</b> using the algorithm
315 * <b>alg</b>, or NULL if none is found. */
316 document_signature_t *
317 voter_get_sig_by_algorithm(const networkstatus_voter_info_t *voter,
318 digest_algorithm_t alg)
320 if (!voter->sigs)
321 return NULL;
322 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
323 if (sig->alg == alg)
324 return sig);
325 return NULL;
328 /** Temporary structure used in constructing a list of dir-source entries
329 * for a consensus. One of these is generated for every vote, and one more
330 * for every legacy key in each vote. */
331 typedef struct dir_src_ent_t {
332 networkstatus_t *v;
333 const char *digest;
334 int is_legacy;
335 } dir_src_ent_t;
337 /** Helper for sorting networkstatus_t votes (not consensuses) by the
338 * hash of their voters' identity digests. */
339 static int
340 _compare_votes_by_authority_id(const void **_a, const void **_b)
342 const networkstatus_t *a = *_a, *b = *_b;
343 return memcmp(get_voter(a)->identity_digest,
344 get_voter(b)->identity_digest, DIGEST_LEN);
347 /** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
348 * their identity digests, and return -1, 0, or 1 depending on their
349 * ordering */
350 static int
351 _compare_dir_src_ents_by_authority_id(const void **_a, const void **_b)
353 const dir_src_ent_t *a = *_a, *b = *_b;
354 const networkstatus_voter_info_t *a_v = get_voter(a->v),
355 *b_v = get_voter(b->v);
356 const char *a_id, *b_id;
357 a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
358 b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;
360 return memcmp(a_id, b_id, DIGEST_LEN);
363 /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
364 * that occurs more than <b>min</b> times. */
365 static void
366 get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
368 char *cur = NULL;
369 int count = 0;
370 SMARTLIST_FOREACH(in, char *, cp,
372 if (cur && !strcmp(cp, cur)) {
373 ++count;
374 } else {
375 if (count > min)
376 smartlist_add(out, cur);
377 cur = cp;
378 count = 1;
381 if (count > min)
382 smartlist_add(out, cur);
385 /** Given a sorted list of strings <b>lst</b>, return the member that appears
386 * most. Break ties in favor of later-occurring members. */
387 #define get_most_frequent_member(lst) \
388 smartlist_get_most_frequent_string(lst)
390 /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
391 * that come from the same routerinfo, with the same derived elements.
393 static int
394 compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
396 int r;
397 if ((r = memcmp(a->status.identity_digest, b->status.identity_digest,
398 DIGEST_LEN)))
399 return r;
400 if ((r = memcmp(a->status.descriptor_digest, b->status.descriptor_digest,
401 DIGEST_LEN)))
402 return r;
403 if ((r = (int)(b->status.published_on - a->status.published_on)))
404 return r;
405 if ((r = strcmp(b->status.nickname, a->status.nickname)))
406 return r;
407 if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
408 return r;
409 if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
410 return r;
411 if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
412 return r;
413 return 0;
416 /** Helper for sorting routerlists based on compare_vote_rs. */
417 static int
418 _compare_vote_rs(const void **_a, const void **_b)
420 const vote_routerstatus_t *a = *_a, *b = *_b;
421 return compare_vote_rs(a,b);
424 /** Given a list of vote_routerstatus_t, all for the same router identity,
425 * return whichever is most frequent, breaking ties in favor of more
426 * recently published vote_routerstatus_t and in case of ties there,
427 * in favor of smaller descriptor digest.
429 static vote_routerstatus_t *
430 compute_routerstatus_consensus(smartlist_t *votes, int consensus_method,
431 char *microdesc_digest256_out)
433 vote_routerstatus_t *most = NULL, *cur = NULL;
434 int most_n = 0, cur_n = 0;
435 time_t most_published = 0;
437 /* _compare_vote_rs() sorts the items by identity digest (all the same),
438 * then by SD digest. That way, if we have a tie that the published_on
439 * date cannot tie, we use the descriptor with the smaller digest.
441 smartlist_sort(votes, _compare_vote_rs);
442 SMARTLIST_FOREACH(votes, vote_routerstatus_t *, rs,
444 if (cur && !compare_vote_rs(cur, rs)) {
445 ++cur_n;
446 } else {
447 if (cur_n > most_n ||
448 (cur && cur_n == most_n &&
449 cur->status.published_on > most_published)) {
450 most = cur;
451 most_n = cur_n;
452 most_published = cur->status.published_on;
454 cur_n = 1;
455 cur = rs;
459 if (cur_n > most_n ||
460 (cur && cur_n == most_n && cur->status.published_on > most_published)) {
461 most = cur;
462 most_n = cur_n;
463 most_published = cur->status.published_on;
466 tor_assert(most);
468 if (consensus_method >= MIN_METHOD_FOR_MICRODESC &&
469 microdesc_digest256_out) {
470 smartlist_t *digests = smartlist_create();
471 const char *best_microdesc_digest;
472 SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
473 char d[DIGEST256_LEN];
474 if (compare_vote_rs(rs, most))
475 continue;
476 if (!vote_routerstatus_find_microdesc_hash(d, rs, consensus_method,
477 DIGEST_SHA256))
478 smartlist_add(digests, tor_memdup(d, sizeof(d)));
479 } SMARTLIST_FOREACH_END(rs);
480 smartlist_sort_digests256(digests);
481 best_microdesc_digest = smartlist_get_most_frequent_digest256(digests);
482 if (best_microdesc_digest)
483 memcpy(microdesc_digest256_out, best_microdesc_digest, DIGEST256_LEN);
484 SMARTLIST_FOREACH(digests, char *, cp, tor_free(cp));
485 smartlist_free(digests);
488 return most;
491 /** Given a list of strings in <b>lst</b>, set the <b>len_out</b>-byte digest
492 * at <b>digest_out</b> to the hash of the concatenation of those strings,
493 * computed with the algorithm <b>alg</b>. */
494 static void
495 hash_list_members(char *digest_out, size_t len_out,
496 smartlist_t *lst, digest_algorithm_t alg)
498 crypto_digest_env_t *d;
499 if (alg == DIGEST_SHA1)
500 d = crypto_new_digest_env();
501 else
502 d = crypto_new_digest256_env(alg);
503 SMARTLIST_FOREACH(lst, const char *, cp,
504 crypto_digest_add_bytes(d, cp, strlen(cp)));
505 crypto_digest_get_digest(d, digest_out, len_out);
506 crypto_free_digest_env(d);
509 /** Sorting helper: compare two strings based on their values as base-ten
510 * positive integers. (Non-integers are treated as prior to all integers, and
511 * compared lexically.) */
512 static int
513 _cmp_int_strings(const void **_a, const void **_b)
515 const char *a = *_a, *b = *_b;
516 int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
517 int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
518 if (ai<bi) {
519 return -1;
520 } else if (ai==bi) {
521 if (ai == 0) /* Parsing failed. */
522 return strcmp(a, b);
523 return 0;
524 } else {
525 return 1;
529 /** Given a list of networkstatus_t votes, determine and return the number of
530 * the highest consensus method that is supported by 2/3 of the voters. */
531 static int
532 compute_consensus_method(smartlist_t *votes)
534 smartlist_t *all_methods = smartlist_create();
535 smartlist_t *acceptable_methods = smartlist_create();
536 smartlist_t *tmp = smartlist_create();
537 int min = (smartlist_len(votes) * 2) / 3;
538 int n_ok;
539 int result;
540 SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
542 tor_assert(vote->supported_methods);
543 smartlist_add_all(tmp, vote->supported_methods);
544 smartlist_sort(tmp, _cmp_int_strings);
545 smartlist_uniq(tmp, _cmp_int_strings, NULL);
546 smartlist_add_all(all_methods, tmp);
547 smartlist_clear(tmp);
550 smartlist_sort(all_methods, _cmp_int_strings);
551 get_frequent_members(acceptable_methods, all_methods, min);
552 n_ok = smartlist_len(acceptable_methods);
553 if (n_ok) {
554 const char *best = smartlist_get(acceptable_methods, n_ok-1);
555 result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
556 } else {
557 result = 1;
559 smartlist_free(tmp);
560 smartlist_free(all_methods);
561 smartlist_free(acceptable_methods);
562 return result;
565 /** Return true iff <b>method</b> is a consensus method that we support. */
566 static int
567 consensus_method_is_supported(int method)
569 return (method >= 1) && (method <= MAX_SUPPORTED_CONSENSUS_METHOD);
572 /** Return a newly allocated string holding the numbers between low and high
573 * (inclusive) that are supported consensus methods. */
574 static char *
575 make_consensus_method_list(int low, int high, const char *separator)
577 char *list;
579 char b[32];
580 int i;
581 smartlist_t *lst;
582 lst = smartlist_create();
583 for (i = low; i <= high; ++i) {
584 if (!consensus_method_is_supported(i))
585 continue;
586 tor_snprintf(b, sizeof(b), "%d", i);
587 smartlist_add(lst, tor_strdup(b));
589 list = smartlist_join_strings(lst, separator, 0, NULL);
590 tor_assert(list);
591 SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
592 smartlist_free(lst);
593 return list;
596 /** Helper: given <b>lst</b>, a list of version strings such that every
597 * version appears once for every versioning voter who recommends it, return a
598 * newly allocated string holding the resulting client-versions or
599 * server-versions list. May change contents of <b>lst</b> */
600 static char *
601 compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
603 int min = n_versioning / 2;
604 smartlist_t *good = smartlist_create();
605 char *result;
606 sort_version_list(lst, 0);
607 get_frequent_members(good, lst, min);
608 result = smartlist_join_strings(good, ",", 0, NULL);
609 smartlist_free(good);
610 return result;
613 /** Helper: given a list of valid networkstatus_t, return a new string
614 * containing the contents of the consensus network parameter set.
616 /* private */ char *
617 dirvote_compute_params(smartlist_t *votes)
619 int i;
620 int32_t *vals;
622 int cur_param_len;
623 const char *cur_param;
624 const char *eq;
625 char *result;
627 const int n_votes = smartlist_len(votes);
628 smartlist_t *output;
629 smartlist_t *param_list = smartlist_create();
631 /* We require that the parameter lists in the votes are well-formed: that
632 is, that their keywords are unique and sorted, and that their values are
633 between INT32_MIN and INT32_MAX inclusive. This should be guaranteed by
634 the parsing code. */
636 vals = tor_malloc(sizeof(int)*n_votes);
638 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
639 if (!v->net_params)
640 continue;
641 smartlist_add_all(param_list, v->net_params);
642 } SMARTLIST_FOREACH_END(v);
644 if (smartlist_len(param_list) == 0) {
645 tor_free(vals);
646 smartlist_free(param_list);
647 return NULL;
650 smartlist_sort_strings(param_list);
651 i = 0;
652 cur_param = smartlist_get(param_list, 0);
653 eq = strchr(cur_param, '=');
654 tor_assert(eq);
655 cur_param_len = (int)(eq+1 - cur_param);
657 output = smartlist_create();
659 SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
660 const char *next_param;
661 int ok=0;
662 eq = strchr(param, '=');
663 tor_assert(i<n_votes);
664 vals[i++] = (int32_t)
665 tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
666 tor_assert(ok);
668 if (param_sl_idx+1 == smartlist_len(param_list))
669 next_param = NULL;
670 else
671 next_param = smartlist_get(param_list, param_sl_idx+1);
672 if (!next_param || strncmp(next_param, param, cur_param_len)) {
673 /* We've reached the end of a series. */
674 int32_t median = median_int32(vals, i);
675 char *out_string = tor_malloc(64+cur_param_len);
676 memcpy(out_string, param, cur_param_len);
677 tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
678 smartlist_add(output, out_string);
680 i = 0;
681 if (next_param) {
682 eq = strchr(next_param, '=');
683 cur_param_len = (int)(eq+1 - next_param);
686 } SMARTLIST_FOREACH_END(param);
688 result = smartlist_join_strings(output, " ", 0, NULL);
689 SMARTLIST_FOREACH(output, char *, cp, tor_free(cp));
690 smartlist_free(output);
691 smartlist_free(param_list);
692 tor_free(vals);
693 return result;
696 #define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
697 ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
698 (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
699 (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
700 (g) >= 0 && (g) <= (mx))
702 #define CHECK_EQ(a, b, margin) \
703 ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))
705 typedef enum {
706 BW_WEIGHTS_NO_ERROR = 0,
707 BW_WEIGHTS_RANGE_ERROR = 1,
708 BW_WEIGHTS_SUMG_ERROR = 2,
709 BW_WEIGHTS_SUME_ERROR = 3,
710 BW_WEIGHTS_SUMD_ERROR = 4,
711 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
712 BW_WEIGHTS_BALANCE_EG_ERROR = 6
713 } bw_weights_error_t;
716 * Verify that any weightings satisfy the balanced formulas.
718 static bw_weights_error_t
719 networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
720 int64_t Wme, int64_t Wmd, int64_t Wee,
721 int64_t Wed, int64_t scale, int64_t G,
722 int64_t M, int64_t E, int64_t D, int64_t T,
723 int64_t margin, int do_balance) {
724 bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;
726 // Wed + Wmd + Wgd == 1
727 if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
728 berr = BW_WEIGHTS_SUMD_ERROR;
729 goto out;
732 // Wmg + Wgg == 1
733 if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
734 berr = BW_WEIGHTS_SUMG_ERROR;
735 goto out;
738 // Wme + Wee == 1
739 if (!CHECK_EQ(Wme + Wee, scale, margin)) {
740 berr = BW_WEIGHTS_SUME_ERROR;
741 goto out;
744 // Verify weights within range 0->1
745 if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
746 berr = BW_WEIGHTS_RANGE_ERROR;
747 goto out;
750 if (do_balance) {
751 // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
752 if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
753 berr = BW_WEIGHTS_BALANCE_EG_ERROR;
754 goto out;
757 // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
758 if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
759 (margin*T)/3)) {
760 berr = BW_WEIGHTS_BALANCE_MID_ERROR;
761 goto out;
765 out:
766 if (berr) {
767 log_info(LD_DIR,
768 "Bw weight mismatch %d. G="I64_FORMAT" M="I64_FORMAT
769 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
770 berr,
771 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
772 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
775 return berr;
778 static void
779 networkstatus_compute_bw_weights_v9(smartlist_t *chunks, int64_t G, int64_t M,
780 int64_t E, int64_t D, int64_t T,
781 int64_t weight_scale)
783 int64_t Wgg = -1, Wgd = -1;
784 int64_t Wmg = -1, Wme = -1, Wmd = -1;
785 int64_t Wed = -1, Wee = -1;
786 const char *casename;
787 char buf[512];
788 int r;
790 if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
791 log_warn(LD_DIR, "Consensus with empty bandwidth: "
792 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
793 " D="I64_FORMAT" T="I64_FORMAT,
794 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
795 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
796 return;
800 * Computed from cases in 3.4.3 of dir-spec.txt
802 * 1. Neither are scarce
803 * 2. Both Guard and Exit are scarce
804 * a. R+D <= S
805 * b. R+D > S
806 * 3. One of Guard or Exit is scarce
807 * a. S+D < T/3
808 * b. S+D >= T/3
810 if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
811 bw_weights_error_t berr = 0;
812 /* Case 1: Neither are scarce.
814 * Attempt to ensure that we have a large amount of exit bandwidth
815 * in the middle position.
817 casename = "Case 1 (Wme*E = Wmd*D)";
818 Wgg = (weight_scale*(D+E+G+M))/(3*G);
819 if (D==0) Wmd = 0;
820 else Wmd = (weight_scale*(2*D + 2*E - G - M))/(6*D);
821 Wme = (weight_scale*(2*D + 2*E - G - M))/(6*E);
822 Wee = (weight_scale*(-2*D + 4*E + G + M))/(6*E);
823 Wgd = 0;
824 Wmg = weight_scale - Wgg;
825 Wed = weight_scale - Wmd;
827 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
828 weight_scale, G, M, E, D, T, 10, 1);
830 if (berr) {
831 log_warn(LD_DIR, "Bw Weights error %d for case %s. "
832 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
833 " D="I64_FORMAT" T="I64_FORMAT,
834 berr, casename,
835 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
836 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
838 } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
839 int64_t R = MIN(E, G);
840 int64_t S = MAX(E, G);
842 * Case 2: Both Guards and Exits are scarce
843 * Balance D between E and G, depending upon
844 * D capacity and scarcity.
846 if (R+D < S) { // Subcase a
847 Wgg = weight_scale;
848 Wee = weight_scale;
849 Wmg = 0;
850 Wme = 0;
851 Wmd = 0;
852 if (E < G) {
853 casename = "Case 2a (E scarce)";
854 Wed = weight_scale;
855 Wgd = 0;
856 } else { /* E >= G */
857 casename = "Case 2a (G scarce)";
858 Wed = 0;
859 Wgd = weight_scale;
861 } else { // Subcase b: R+D > S
862 bw_weights_error_t berr = 0;
863 casename = "Case 2b (Wme*E == Wmd*D)";
864 if (D != 0) {
865 Wgg = weight_scale;
866 Wgd = (weight_scale*(D + E - 2*G + M))/(3*D); // T/3 >= G (Ok)
867 Wmd = (weight_scale*(D + E + G - 2*M))/(6*D); // T/3 >= M
868 Wme = (weight_scale*(D + E + G - 2*M))/(6*E);
869 Wee = (weight_scale*(-D + 5*E - G + 2*M))/(6*E); // 2E+M >= T/3
870 Wmg = 0;
871 Wed = weight_scale - Wgd - Wmd;
873 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
874 weight_scale, G, M, E, D, T, 10, 1);
877 if (D == 0 || berr) { // Can happen if M > T/3
878 casename = "Case 2b (E=G)";
879 Wgg = weight_scale;
880 Wee = weight_scale;
881 Wmg = 0;
882 Wme = 0;
883 Wmd = 0;
884 if (D == 0) Wgd = 0;
885 else Wgd = (weight_scale*(D+E-G))/(2*D);
886 Wed = weight_scale - Wgd;
887 berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
888 Wed, weight_scale, G, M, E, D, T, 10, 1);
890 if (berr != BW_WEIGHTS_NO_ERROR &&
891 berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
892 log_warn(LD_DIR, "Bw Weights error %d for case %s. "
893 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT
894 " D="I64_FORMAT" T="I64_FORMAT,
895 berr, casename,
896 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
897 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
900 } else { // if (E < T/3 || G < T/3) {
901 int64_t S = MIN(E, G);
902 // Case 3: Exactly one of Guard or Exit is scarce
903 if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
904 log_warn(LD_BUG,
905 "Bw-Weights Case 3 but with G="I64_FORMAT" M="
906 I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
907 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
908 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
911 if (3*(S+D) < T) { // Subcase a: S+D < T/3
912 if (G < E) {
913 casename = "Case 3a (G scarce)";
914 Wgg = Wgd = weight_scale;
915 Wmd = Wed = Wmg = 0;
916 // Minor subcase, if E is more scarce than M,
917 // keep its bandwidth in place.
918 if (E < M) Wme = 0;
919 else Wme = (weight_scale*(E-M))/(2*E);
920 Wee = weight_scale-Wme;
921 } else { // G >= E
922 casename = "Case 3a (E scarce)";
923 Wee = Wed = weight_scale;
924 Wmd = Wgd = Wme = 0;
925 // Minor subcase, if G is more scarce than M,
926 // keep its bandwidth in place.
927 if (G < M) Wmg = 0;
928 else Wmg = (weight_scale*(G-M))/(2*G);
929 Wgg = weight_scale-Wmg;
931 } else { // Subcase b: S+D >= T/3
932 bw_weights_error_t berr = 0;
933 // D != 0 because S+D >= T/3
934 if (G < E) {
935 casename = "Case 3b (G scarce, Wme*E == Wmd*D)";
936 Wgd = (weight_scale*(D + E - 2*G + M))/(3*D);
937 Wmd = (weight_scale*(D + E + G - 2*M))/(6*D);
938 Wme = (weight_scale*(D + E + G - 2*M))/(6*E);
939 Wee = (weight_scale*(-D + 5*E - G + 2*M))/(6*E);
940 Wgg = weight_scale;
941 Wmg = 0;
942 Wed = weight_scale - Wgd - Wmd;
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 3b (E scarce, Wme*E == Wmd*D)";
948 Wgg = (weight_scale*(D + E + G + M))/(3*G);
949 Wmd = (weight_scale*(2*D + 2*E - G - M))/(6*D);
950 Wme = (weight_scale*(2*D + 2*E - G - M))/(6*E);
951 Wee = (weight_scale*(-2*D + 4*E + G + M))/(6*E);
952 Wgd = 0;
953 Wmg = weight_scale - Wgg;
954 Wed = weight_scale - Wmd;
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, "Bw Weights error %d for case %s. "
961 "G="I64_FORMAT" M="I64_FORMAT
962 " E="I64_FORMAT" D="I64_FORMAT" T="I64_FORMAT,
963 berr, casename,
964 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
965 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
970 /* We cast down the weights to 32 bit ints on the assumption that
971 * weight_scale is ~= 10000. We need to ensure a rogue authority
972 * doesn't break this assumption to rig our weights */
973 tor_assert(0 < weight_scale && weight_scale < INT32_MAX);
975 if (Wgg < 0 || Wgg > weight_scale) {
976 log_warn(LD_DIR, "Bw %s: Wgg="I64_FORMAT"! G="I64_FORMAT
977 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
978 " T="I64_FORMAT,
979 casename, I64_PRINTF_ARG(Wgg),
980 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
981 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
983 Wgg = MAX(MIN(Wgg, weight_scale), 0);
985 if (Wgd < 0 || Wgd > weight_scale) {
986 log_warn(LD_DIR, "Bw %s: Wgd="I64_FORMAT"! G="I64_FORMAT
987 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
988 " T="I64_FORMAT,
989 casename, I64_PRINTF_ARG(Wgd),
990 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
991 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
992 Wgd = MAX(MIN(Wgd, weight_scale), 0);
994 if (Wmg < 0 || Wmg > weight_scale) {
995 log_warn(LD_DIR, "Bw %s: Wmg="I64_FORMAT"! G="I64_FORMAT
996 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
997 " T="I64_FORMAT,
998 casename, I64_PRINTF_ARG(Wmg),
999 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1000 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1001 Wmg = MAX(MIN(Wmg, weight_scale), 0);
1003 if (Wme < 0 || Wme > weight_scale) {
1004 log_warn(LD_DIR, "Bw %s: Wme="I64_FORMAT"! G="I64_FORMAT
1005 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1006 " T="I64_FORMAT,
1007 casename, I64_PRINTF_ARG(Wme),
1008 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1009 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1010 Wme = MAX(MIN(Wme, weight_scale), 0);
1012 if (Wmd < 0 || Wmd > weight_scale) {
1013 log_warn(LD_DIR, "Bw %s: Wmd="I64_FORMAT"! G="I64_FORMAT
1014 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1015 " T="I64_FORMAT,
1016 casename, I64_PRINTF_ARG(Wmd),
1017 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1018 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1019 Wmd = MAX(MIN(Wmd, weight_scale), 0);
1021 if (Wee < 0 || Wee > weight_scale) {
1022 log_warn(LD_DIR, "Bw %s: Wee="I64_FORMAT"! G="I64_FORMAT
1023 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1024 " T="I64_FORMAT,
1025 casename, I64_PRINTF_ARG(Wee),
1026 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1027 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1028 Wee = MAX(MIN(Wee, weight_scale), 0);
1030 if (Wed < 0 || Wed > weight_scale) {
1031 log_warn(LD_DIR, "Bw %s: Wed="I64_FORMAT"! G="I64_FORMAT
1032 " M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1033 " T="I64_FORMAT,
1034 casename, I64_PRINTF_ARG(Wed),
1035 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1036 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1037 Wed = MAX(MIN(Wed, weight_scale), 0);
1040 // Add consensus weight keywords
1041 smartlist_add(chunks, tor_strdup("bandwidth-weights "));
1043 * Provide Wgm=Wgg, Wmm=1, Wem=Wee, Weg=Wed. May later determine
1044 * that middle nodes need different bandwidth weights for dirport traffic,
1045 * or that weird exit policies need special weight, or that bridges
1046 * need special weight.
1048 * NOTE: This list is sorted.
1050 r = tor_snprintf(buf, sizeof(buf),
1051 "Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
1052 "Wdb=%d "
1053 "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
1054 "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
1055 "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
1056 (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
1057 (int)weight_scale,
1058 (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
1059 (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
1060 (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
1061 if (r<0) {
1062 log_warn(LD_BUG,
1063 "Not enough space in buffer for bandwidth-weights line.");
1064 *buf = '\0';
1066 smartlist_add(chunks, tor_strdup(buf));
1067 log_notice(LD_CIRC, "Computed bandwidth weights for %s: "
1068 "G="I64_FORMAT" M="I64_FORMAT" E="I64_FORMAT" D="I64_FORMAT
1069 " T="I64_FORMAT,
1070 casename,
1071 I64_PRINTF_ARG(G), I64_PRINTF_ARG(M), I64_PRINTF_ARG(E),
1072 I64_PRINTF_ARG(D), I64_PRINTF_ARG(T));
1075 /** Given a list of vote networkstatus_t in <b>votes</b>, our public
1076 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
1077 * and the number of <b>total_authorities</b> that we believe exist in our
1078 * voting quorum, generate the text of a new v3 consensus vote, and return the
1079 * value in a newly allocated string.
1081 * Note: this function DOES NOT check whether the votes are from
1082 * recognized authorities. (dirvote_add_vote does that.) */
1083 char *
1084 networkstatus_compute_consensus(smartlist_t *votes,
1085 int total_authorities,
1086 crypto_pk_env_t *identity_key,
1087 crypto_pk_env_t *signing_key,
1088 const char *legacy_id_key_digest,
1089 crypto_pk_env_t *legacy_signing_key,
1090 consensus_flavor_t flavor)
1092 smartlist_t *chunks;
1093 char *result = NULL;
1094 int consensus_method;
1095 time_t valid_after, fresh_until, valid_until;
1096 int vote_seconds, dist_seconds;
1097 char *client_versions = NULL, *server_versions = NULL;
1098 smartlist_t *flags;
1099 const char *flavor_name;
1100 int64_t G=0, M=0, E=0, D=0, T=0; /* For bandwidth weights */
1101 const routerstatus_format_type_t rs_format =
1102 flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
1103 char *params = NULL;
1104 tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
1105 tor_assert(total_authorities >= smartlist_len(votes));
1107 flavor_name = networkstatus_get_flavor_name(flavor);
1109 if (!smartlist_len(votes)) {
1110 log_warn(LD_DIR, "Can't compute a consensus from no votes.");
1111 return NULL;
1113 flags = smartlist_create();
1115 consensus_method = compute_consensus_method(votes);
1116 if (consensus_method_is_supported(consensus_method)) {
1117 log_info(LD_DIR, "Generating consensus using method %d.",
1118 consensus_method);
1119 } else {
1120 log_warn(LD_DIR, "The other authorities will use consensus method %d, "
1121 "which I don't support. Maybe I should upgrade!",
1122 consensus_method);
1123 consensus_method = 1;
1126 /* Compute medians of time-related things, and figure out how many
1127 * routers we might need to talk about. */
1129 int n_votes = smartlist_len(votes);
1130 time_t *va_times = tor_malloc(n_votes * sizeof(time_t));
1131 time_t *fu_times = tor_malloc(n_votes * sizeof(time_t));
1132 time_t *vu_times = tor_malloc(n_votes * sizeof(time_t));
1133 int *votesec_list = tor_malloc(n_votes * sizeof(int));
1134 int *distsec_list = tor_malloc(n_votes * sizeof(int));
1135 int n_versioning_clients = 0, n_versioning_servers = 0;
1136 smartlist_t *combined_client_versions = smartlist_create();
1137 smartlist_t *combined_server_versions = smartlist_create();
1139 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1140 tor_assert(v->type == NS_TYPE_VOTE);
1141 va_times[v_sl_idx] = v->valid_after;
1142 fu_times[v_sl_idx] = v->fresh_until;
1143 vu_times[v_sl_idx] = v->valid_until;
1144 votesec_list[v_sl_idx] = v->vote_seconds;
1145 distsec_list[v_sl_idx] = v->dist_seconds;
1146 if (v->client_versions) {
1147 smartlist_t *cv = smartlist_create();
1148 ++n_versioning_clients;
1149 smartlist_split_string(cv, v->client_versions, ",",
1150 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1151 sort_version_list(cv, 1);
1152 smartlist_add_all(combined_client_versions, cv);
1153 smartlist_free(cv); /* elements get freed later. */
1155 if (v->server_versions) {
1156 smartlist_t *sv = smartlist_create();
1157 ++n_versioning_servers;
1158 smartlist_split_string(sv, v->server_versions, ",",
1159 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1160 sort_version_list(sv, 1);
1161 smartlist_add_all(combined_server_versions, sv);
1162 smartlist_free(sv); /* elements get freed later. */
1164 SMARTLIST_FOREACH(v->known_flags, const char *, cp,
1165 smartlist_add(flags, tor_strdup(cp)));
1166 } SMARTLIST_FOREACH_END(v);
1167 valid_after = median_time(va_times, n_votes);
1168 fresh_until = median_time(fu_times, n_votes);
1169 valid_until = median_time(vu_times, n_votes);
1170 vote_seconds = median_int(votesec_list, n_votes);
1171 dist_seconds = median_int(distsec_list, n_votes);
1173 tor_assert(valid_after+MIN_VOTE_INTERVAL <= fresh_until);
1174 tor_assert(fresh_until+MIN_VOTE_INTERVAL <= valid_until);
1175 tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
1176 tor_assert(dist_seconds >= MIN_DIST_SECONDS);
1178 server_versions = compute_consensus_versions_list(combined_server_versions,
1179 n_versioning_servers);
1180 client_versions = compute_consensus_versions_list(combined_client_versions,
1181 n_versioning_clients);
1183 SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
1184 SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
1185 smartlist_free(combined_server_versions);
1186 smartlist_free(combined_client_versions);
1188 smartlist_sort_strings(flags);
1189 smartlist_uniq_strings(flags);
1191 tor_free(va_times);
1192 tor_free(fu_times);
1193 tor_free(vu_times);
1194 tor_free(votesec_list);
1195 tor_free(distsec_list);
1198 chunks = smartlist_create();
1201 char *buf=NULL;
1202 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
1203 vu_buf[ISO_TIME_LEN+1];
1204 char *flaglist;
1205 format_iso_time(va_buf, valid_after);
1206 format_iso_time(fu_buf, fresh_until);
1207 format_iso_time(vu_buf, valid_until);
1208 flaglist = smartlist_join_strings(flags, " ", 0, NULL);
1210 tor_asprintf(&buf, "network-status-version 3%s%s\n"
1211 "vote-status consensus\n",
1212 flavor == FLAV_NS ? "" : " ",
1213 flavor == FLAV_NS ? "" : flavor_name);
1215 smartlist_add(chunks, buf);
1217 if (consensus_method >= 2) {
1218 tor_asprintf(&buf, "consensus-method %d\n",
1219 consensus_method);
1220 smartlist_add(chunks, buf);
1223 tor_asprintf(&buf,
1224 "valid-after %s\n"
1225 "fresh-until %s\n"
1226 "valid-until %s\n"
1227 "voting-delay %d %d\n"
1228 "client-versions %s\n"
1229 "server-versions %s\n"
1230 "known-flags %s\n",
1231 va_buf, fu_buf, vu_buf,
1232 vote_seconds, dist_seconds,
1233 client_versions, server_versions, flaglist);
1234 smartlist_add(chunks, buf);
1236 tor_free(flaglist);
1239 if (consensus_method >= MIN_METHOD_FOR_PARAMS) {
1240 params = dirvote_compute_params(votes);
1241 if (params) {
1242 smartlist_add(chunks, tor_strdup("params "));
1243 smartlist_add(chunks, params);
1244 smartlist_add(chunks, tor_strdup("\n"));
1248 /* Sort the votes. */
1249 smartlist_sort(votes, _compare_votes_by_authority_id);
1250 /* Add the authority sections. */
1252 smartlist_t *dir_sources = smartlist_create();
1253 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1254 dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
1255 e->v = v;
1256 e->digest = get_voter(v)->identity_digest;
1257 e->is_legacy = 0;
1258 smartlist_add(dir_sources, e);
1259 if (consensus_method >= 3 &&
1260 !tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
1261 dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
1262 e_legacy->v = v;
1263 e_legacy->digest = get_voter(v)->legacy_id_digest;
1264 e_legacy->is_legacy = 1;
1265 smartlist_add(dir_sources, e_legacy);
1267 } SMARTLIST_FOREACH_END(v);
1268 smartlist_sort(dir_sources, _compare_dir_src_ents_by_authority_id);
1270 SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
1271 struct in_addr in;
1272 char ip[INET_NTOA_BUF_LEN];
1273 char fingerprint[HEX_DIGEST_LEN+1];
1274 char votedigest[HEX_DIGEST_LEN+1];
1275 networkstatus_t *v = e->v;
1276 networkstatus_voter_info_t *voter = get_voter(v);
1277 char *buf = NULL;
1279 if (e->is_legacy)
1280 tor_assert(consensus_method >= 2);
1282 in.s_addr = htonl(voter->addr);
1283 tor_inet_ntoa(&in, ip, sizeof(ip));
1284 base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
1285 base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
1286 DIGEST_LEN);
1288 tor_asprintf(&buf,
1289 "dir-source %s%s %s %s %s %d %d\n",
1290 voter->nickname, e->is_legacy ? "-legacy" : "",
1291 fingerprint, voter->address, ip,
1292 voter->dir_port,
1293 voter->or_port);
1294 smartlist_add(chunks, buf);
1295 if (! e->is_legacy) {
1296 tor_asprintf(&buf,
1297 "contact %s\n"
1298 "vote-digest %s\n",
1299 voter->contact,
1300 votedigest);
1301 smartlist_add(chunks, buf);
1303 } SMARTLIST_FOREACH_END(e);
1304 SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
1305 smartlist_free(dir_sources);
1308 /* Add the actual router entries. */
1310 int *index; /* index[j] is the current index into votes[j]. */
1311 int *size; /* size[j] is the number of routerstatuses in votes[j]. */
1312 int *flag_counts; /* The number of voters that list flag[j] for the
1313 * currently considered router. */
1314 int i;
1315 smartlist_t *matching_descs = smartlist_create();
1316 smartlist_t *chosen_flags = smartlist_create();
1317 smartlist_t *versions = smartlist_create();
1318 smartlist_t *exitsummaries = smartlist_create();
1319 uint32_t *bandwidths = tor_malloc(sizeof(uint32_t) * smartlist_len(votes));
1320 uint32_t *measured_bws = tor_malloc(sizeof(uint32_t) *
1321 smartlist_len(votes));
1322 int num_bandwidths;
1323 int num_mbws;
1325 int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
1326 * votes[j] knows about. */
1327 int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
1328 * about flags[f]. */
1329 int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
1330 * is the same flag as votes[j]->known_flags[b]. */
1331 int *named_flag; /* Index of the flag "Named" for votes[j] */
1332 int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
1333 int chosen_named_idx, chosen_unnamed_idx;
1335 strmap_t *name_to_id_map = strmap_new();
1336 char conflict[DIGEST_LEN];
1337 char unknown[DIGEST_LEN];
1338 memset(conflict, 0, sizeof(conflict));
1339 memset(unknown, 0xff, sizeof(conflict));
1341 index = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
1342 size = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
1343 n_voter_flags = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
1344 n_flag_voters = tor_malloc_zero(sizeof(int) * smartlist_len(flags));
1345 flag_map = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
1346 named_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
1347 unnamed_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
1348 for (i = 0; i < smartlist_len(votes); ++i)
1349 unnamed_flag[i] = named_flag[i] = -1;
1350 chosen_named_idx = smartlist_string_pos(flags, "Named");
1351 chosen_unnamed_idx = smartlist_string_pos(flags, "Unnamed");
1353 /* Build the flag index. */
1354 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
1356 flag_map[v_sl_idx] = tor_malloc_zero(
1357 sizeof(int)*smartlist_len(v->known_flags));
1358 SMARTLIST_FOREACH(v->known_flags, const char *, fl,
1360 int p = smartlist_string_pos(flags, fl);
1361 tor_assert(p >= 0);
1362 flag_map[v_sl_idx][fl_sl_idx] = p;
1363 ++n_flag_voters[p];
1364 if (!strcmp(fl, "Named"))
1365 named_flag[v_sl_idx] = fl_sl_idx;
1366 if (!strcmp(fl, "Unnamed"))
1367 unnamed_flag[v_sl_idx] = fl_sl_idx;
1369 n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
1370 size[v_sl_idx] = smartlist_len(v->routerstatus_list);
1373 /* Named and Unnamed get treated specially */
1374 if (consensus_method >= 2) {
1375 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
1377 uint64_t nf;
1378 if (named_flag[v_sl_idx]<0)
1379 continue;
1380 nf = U64_LITERAL(1) << named_flag[v_sl_idx];
1381 SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
1383 if ((rs->flags & nf) != 0) {
1384 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1385 if (!d) {
1386 /* We have no name officially mapped to this digest. */
1387 strmap_set_lc(name_to_id_map, rs->status.nickname,
1388 rs->status.identity_digest);
1389 } else if (d != conflict &&
1390 memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
1391 /* Authorities disagree about this nickname. */
1392 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1393 } else {
1394 /* It's already a conflict, or it's already this ID. */
1399 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
1401 uint64_t uf;
1402 if (unnamed_flag[v_sl_idx]<0)
1403 continue;
1404 uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
1405 SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
1407 if ((rs->flags & uf) != 0) {
1408 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
1409 if (d == conflict || d == unknown) {
1410 /* Leave it alone; we know what it is. */
1411 } else if (!d) {
1412 /* We have no name officially mapped to this digest. */
1413 strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
1414 } else if (!memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
1415 /* Authorities disagree about this nickname. */
1416 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
1417 } else {
1418 /* It's mapped to a different name. */
1425 /* Now go through all the votes */
1426 flag_counts = tor_malloc(sizeof(int) * smartlist_len(flags));
1427 while (1) {
1428 vote_routerstatus_t *rs;
1429 routerstatus_t rs_out;
1430 const char *lowest_id = NULL;
1431 const char *chosen_version;
1432 const char *chosen_name = NULL;
1433 int exitsummary_disagreement = 0;
1434 int is_named = 0, is_unnamed = 0, is_running = 0;
1435 int is_guard = 0, is_exit = 0;
1436 int naming_conflict = 0;
1437 int n_listing = 0;
1438 int i;
1439 char *buf=NULL;
1440 char microdesc_digest[DIGEST256_LEN];
1442 /* Of the next-to-be-considered digest in each voter, which is first? */
1443 SMARTLIST_FOREACH(votes, networkstatus_t *, v, {
1444 if (index[v_sl_idx] < size[v_sl_idx]) {
1445 rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
1446 if (!lowest_id ||
1447 memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN) < 0)
1448 lowest_id = rs->status.identity_digest;
1451 if (!lowest_id) /* we're out of routers. */
1452 break;
1454 memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
1455 smartlist_clear(matching_descs);
1456 smartlist_clear(chosen_flags);
1457 smartlist_clear(versions);
1458 num_bandwidths = 0;
1459 num_mbws = 0;
1461 /* Okay, go through all the entries for this digest. */
1462 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
1463 if (index[v_sl_idx] >= size[v_sl_idx])
1464 continue; /* out of entries. */
1465 rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
1466 if (memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN))
1467 continue; /* doesn't include this router. */
1468 /* At this point, we know that we're looking at a routerstatus with
1469 * identity "lowest".
1471 ++index[v_sl_idx];
1472 ++n_listing;
1474 smartlist_add(matching_descs, rs);
1475 if (rs->version && rs->version[0])
1476 smartlist_add(versions, rs->version);
1478 /* Tally up all the flags. */
1479 for (i = 0; i < n_voter_flags[v_sl_idx]; ++i) {
1480 if (rs->flags & (U64_LITERAL(1) << i))
1481 ++flag_counts[flag_map[v_sl_idx][i]];
1483 if (rs->flags & (U64_LITERAL(1) << named_flag[v_sl_idx])) {
1484 if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
1485 log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
1486 chosen_name, rs->status.nickname);
1487 naming_conflict = 1;
1489 chosen_name = rs->status.nickname;
1492 /* count bandwidths */
1493 if (rs->status.has_measured_bw)
1494 measured_bws[num_mbws++] = rs->status.measured_bw;
1496 if (rs->status.has_bandwidth)
1497 bandwidths[num_bandwidths++] = rs->status.bandwidth;
1498 } SMARTLIST_FOREACH_END(v);
1500 /* We don't include this router at all unless more than half of
1501 * the authorities we believe in list it. */
1502 if (n_listing <= total_authorities/2)
1503 continue;
1505 /* Figure out the most popular opinion of what the most recent
1506 * routerinfo and its contents are. */
1507 memset(microdesc_digest, 0, sizeof(microdesc_digest));
1508 rs = compute_routerstatus_consensus(matching_descs, consensus_method,
1509 microdesc_digest);
1510 /* Copy bits of that into rs_out. */
1511 tor_assert(!memcmp(lowest_id, rs->status.identity_digest, DIGEST_LEN));
1512 memcpy(rs_out.identity_digest, lowest_id, DIGEST_LEN);
1513 memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
1514 DIGEST_LEN);
1515 rs_out.addr = rs->status.addr;
1516 rs_out.published_on = rs->status.published_on;
1517 rs_out.dir_port = rs->status.dir_port;
1518 rs_out.or_port = rs->status.or_port;
1519 rs_out.has_bandwidth = 0;
1520 rs_out.has_exitsummary = 0;
1522 if (chosen_name && !naming_conflict) {
1523 strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
1524 } else {
1525 strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
1528 if (consensus_method == 1) {
1529 is_named = chosen_named_idx >= 0 &&
1530 (!naming_conflict && flag_counts[chosen_named_idx]);
1531 } else {
1532 const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
1533 if (!d) {
1534 is_named = is_unnamed = 0;
1535 } else if (!memcmp(d, lowest_id, DIGEST_LEN)) {
1536 is_named = 1; is_unnamed = 0;
1537 } else {
1538 is_named = 0; is_unnamed = 1;
1542 /* Set the flags. */
1543 smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
1544 SMARTLIST_FOREACH(flags, const char *, fl,
1546 if (!strcmp(fl, "Named")) {
1547 if (is_named)
1548 smartlist_add(chosen_flags, (char*)fl);
1549 } else if (!strcmp(fl, "Unnamed") && consensus_method >= 2) {
1550 if (is_unnamed)
1551 smartlist_add(chosen_flags, (char*)fl);
1552 } else {
1553 if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
1554 smartlist_add(chosen_flags, (char*)fl);
1555 if (!strcmp(fl, "Exit"))
1556 is_exit = 1;
1557 else if (!strcmp(fl, "Guard"))
1558 is_guard = 1;
1559 else if (!strcmp(fl, "Running"))
1560 is_running = 1;
1565 /* Starting with consensus method 4 we do not list servers
1566 * that are not running in a consensus. See Proposal 138 */
1567 if (consensus_method >= 4 && !is_running)
1568 continue;
1570 /* Pick the version. */
1571 if (smartlist_len(versions)) {
1572 sort_version_list(versions, 0);
1573 chosen_version = get_most_frequent_member(versions);
1574 } else {
1575 chosen_version = NULL;
1578 /* Pick a bandwidth */
1579 if (consensus_method >= 6 && num_mbws > 2) {
1580 rs_out.has_bandwidth = 1;
1581 rs_out.bandwidth = median_uint32(measured_bws, num_mbws);
1582 } else if (consensus_method >= 5 && num_bandwidths > 0) {
1583 rs_out.has_bandwidth = 1;
1584 rs_out.bandwidth = median_uint32(bandwidths, num_bandwidths);
1587 if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS) {
1588 if (rs_out.has_bandwidth) {
1589 T += rs_out.bandwidth;
1590 if (is_exit && is_guard)
1591 D += rs_out.bandwidth;
1592 else if (is_exit)
1593 E += rs_out.bandwidth;
1594 else if (is_guard)
1595 G += rs_out.bandwidth;
1596 else
1597 M += rs_out.bandwidth;
1598 } else {
1599 log_warn(LD_BUG, "Missing consensus bandwidth for router %s",
1600 rs_out.nickname);
1604 /* Ok, we already picked a descriptor digest we want to list
1605 * previously. Now we want to use the exit policy summary from
1606 * that descriptor. If everybody plays nice all the voters who
1607 * listed that descriptor will have the same summary. If not then
1608 * something is fishy and we'll use the most common one (breaking
1609 * ties in favor of lexicographically larger one (only because it
1610 * lets me reuse more existing code.
1612 * The other case that can happen is that no authority that voted
1613 * for that descriptor has an exit policy summary. That's
1614 * probably quite unlikely but can happen. In that case we use
1615 * the policy that was most often listed in votes, again breaking
1616 * ties like in the previous case.
1618 if (consensus_method >= 5) {
1619 /* Okay, go through all the votes for this router. We prepared
1620 * that list previously */
1621 const char *chosen_exitsummary = NULL;
1622 smartlist_clear(exitsummaries);
1623 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
1624 /* Check if the vote where this status comes from had the
1625 * proper descriptor */
1626 tor_assert(!memcmp(rs_out.identity_digest,
1627 vsr->status.identity_digest,
1628 DIGEST_LEN));
1629 if (vsr->status.has_exitsummary &&
1630 !memcmp(rs_out.descriptor_digest,
1631 vsr->status.descriptor_digest,
1632 DIGEST_LEN)) {
1633 tor_assert(vsr->status.exitsummary);
1634 smartlist_add(exitsummaries, vsr->status.exitsummary);
1635 if (!chosen_exitsummary) {
1636 chosen_exitsummary = vsr->status.exitsummary;
1637 } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
1638 /* Great. There's disagreement among the voters. That
1639 * really shouldn't be */
1640 exitsummary_disagreement = 1;
1645 if (exitsummary_disagreement) {
1646 char id[HEX_DIGEST_LEN+1];
1647 char dd[HEX_DIGEST_LEN+1];
1648 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1649 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1650 log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
1651 " for router %s with descriptor %s. This really shouldn't"
1652 " have happened.", id, dd);
1654 smartlist_sort_strings(exitsummaries);
1655 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1656 } else if (!chosen_exitsummary) {
1657 char id[HEX_DIGEST_LEN+1];
1658 char dd[HEX_DIGEST_LEN+1];
1659 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1660 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1661 log_warn(LD_DIR, "Not one of the voters that made us select"
1662 "descriptor %s for router %s had an exit policy"
1663 "summary", dd, id);
1665 /* Ok, none of those voting for the digest we chose had an
1666 * exit policy for us. Well, that kinda sucks.
1668 smartlist_clear(exitsummaries);
1669 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
1670 if (vsr->status.has_exitsummary)
1671 smartlist_add(exitsummaries, vsr->status.exitsummary);
1673 smartlist_sort_strings(exitsummaries);
1674 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1676 if (!chosen_exitsummary)
1677 log_warn(LD_DIR, "Wow, not one of the voters had an exit "
1678 "policy summary for %s. Wow.", id);
1681 if (chosen_exitsummary) {
1682 rs_out.has_exitsummary = 1;
1683 /* yea, discards the const */
1684 rs_out.exitsummary = (char *)chosen_exitsummary;
1689 char buf[4096];
1690 /* Okay!! Now we can write the descriptor... */
1691 /* First line goes into "buf". */
1692 routerstatus_format_entry(buf, sizeof(buf), &rs_out, NULL,
1693 rs_format);
1694 smartlist_add(chunks, tor_strdup(buf));
1696 /* Now an m line, if applicable. */
1697 if (flavor == FLAV_MICRODESC &&
1698 !tor_digest256_is_zero(microdesc_digest)) {
1699 char m[BASE64_DIGEST256_LEN+1], *cp;
1700 digest256_to_base64(m, microdesc_digest);
1701 tor_asprintf(&cp, "m %s\n", m);
1702 smartlist_add(chunks, cp);
1704 /* Next line is all flags. The "\n" is missing. */
1705 smartlist_add(chunks,
1706 smartlist_join_strings(chosen_flags, " ", 0, NULL));
1707 /* Now the version line. */
1708 if (chosen_version) {
1709 smartlist_add(chunks, tor_strdup("\nv "));
1710 smartlist_add(chunks, tor_strdup(chosen_version));
1712 smartlist_add(chunks, tor_strdup("\n"));
1713 /* Now the weight line. */
1714 if (rs_out.has_bandwidth) {
1715 char *cp=NULL;
1716 tor_asprintf(&cp, "w Bandwidth=%d\n", rs_out.bandwidth);
1717 smartlist_add(chunks, cp);
1720 /* Now the exitpolicy summary line. */
1721 if (rs_out.has_exitsummary && flavor == FLAV_NS) {
1722 tor_asprintf(&buf, "p %s\n", rs_out.exitsummary);
1723 smartlist_add(chunks, buf);
1726 /* And the loop is over and we move on to the next router */
1729 tor_free(index);
1730 tor_free(size);
1731 tor_free(n_voter_flags);
1732 tor_free(n_flag_voters);
1733 for (i = 0; i < smartlist_len(votes); ++i)
1734 tor_free(flag_map[i]);
1735 tor_free(flag_map);
1736 tor_free(flag_counts);
1737 tor_free(named_flag);
1738 tor_free(unnamed_flag);
1739 strmap_free(name_to_id_map, NULL);
1740 smartlist_free(matching_descs);
1741 smartlist_free(chosen_flags);
1742 smartlist_free(versions);
1743 smartlist_free(exitsummaries);
1744 tor_free(bandwidths);
1745 tor_free(measured_bws);
1748 if (consensus_method >= MIN_METHOD_FOR_FOOTER) {
1749 /* Starting with consensus method 9, we clearly mark the directory
1750 * footer region */
1751 smartlist_add(chunks, tor_strdup("directory-footer\n"));
1754 if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS) {
1755 int64_t weight_scale = BW_WEIGHT_SCALE;
1756 char *bw_weight_param = NULL;
1758 // Parse params, extract BW_WEIGHT_SCALE if present
1759 // DO NOT use consensus_param_bw_weight_scale() in this code!
1760 // The consensus is not formed yet!
1761 if (params) {
1762 if (strcmpstart(params, "bwweightscale=") == 0)
1763 bw_weight_param = params;
1764 else
1765 bw_weight_param = strstr(params, " bwweightscale=");
1768 if (bw_weight_param) {
1769 int ok=0;
1770 char *eq = strchr(bw_weight_param, '=');
1771 if (eq) {
1772 weight_scale = tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok,
1773 NULL);
1774 if (!ok) {
1775 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
1776 escaped(bw_weight_param));
1777 weight_scale = BW_WEIGHT_SCALE;
1779 } else {
1780 log_warn(LD_DIR, "Bad element '%s' in bw weight param",
1781 escaped(bw_weight_param));
1782 weight_scale = BW_WEIGHT_SCALE;
1786 networkstatus_compute_bw_weights_v9(chunks, G, M, E, D, T, weight_scale);
1789 /* Add a signature. */
1791 char digest[DIGEST256_LEN];
1792 char fingerprint[HEX_DIGEST_LEN+1];
1793 char signing_key_fingerprint[HEX_DIGEST_LEN+1];
1794 digest_algorithm_t digest_alg =
1795 flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
1796 size_t digest_len =
1797 flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
1798 const char *algname = crypto_digest_algorithm_get_name(digest_alg);
1799 char *buf = NULL;
1800 char sigbuf[4096];
1802 smartlist_add(chunks, tor_strdup("directory-signature "));
1804 /* Compute the hash of the chunks. */
1805 hash_list_members(digest, digest_len, chunks, digest_alg);
1807 /* Get the fingerprints */
1808 crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
1809 crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
1811 /* add the junk that will go at the end of the line. */
1812 if (flavor == FLAV_NS) {
1813 tor_asprintf(&buf, "%s %s\n", fingerprint,
1814 signing_key_fingerprint);
1815 } else {
1816 tor_asprintf(&buf, "%s %s %s\n",
1817 algname, fingerprint,
1818 signing_key_fingerprint);
1820 smartlist_add(chunks, buf);
1821 /* And the signature. */
1822 sigbuf[0] = '\0';
1823 if (router_append_dirobj_signature(sigbuf, sizeof(sigbuf),
1824 digest, digest_len,
1825 signing_key)) {
1826 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1827 return NULL; /* This leaks, but it should never happen. */
1829 smartlist_add(chunks, tor_strdup(sigbuf));
1831 if (legacy_id_key_digest && legacy_signing_key && consensus_method >= 3) {
1832 smartlist_add(chunks, tor_strdup("directory-signature "));
1833 base16_encode(fingerprint, sizeof(fingerprint),
1834 legacy_id_key_digest, DIGEST_LEN);
1835 crypto_pk_get_fingerprint(legacy_signing_key,
1836 signing_key_fingerprint, 0);
1837 if (flavor == FLAV_NS) {
1838 tor_asprintf(&buf, "%s %s\n", fingerprint,
1839 signing_key_fingerprint);
1840 } else {
1841 tor_asprintf(&buf, "%s %s %s\n",
1842 algname, fingerprint,
1843 signing_key_fingerprint);
1845 smartlist_add(chunks, buf);
1846 sigbuf[0] = '\0';
1847 if (router_append_dirobj_signature(sigbuf, sizeof(sigbuf),
1848 digest, digest_len,
1849 legacy_signing_key)) {
1850 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1851 return NULL; /* This leaks, but it should never happen. */
1853 smartlist_add(chunks, tor_strdup(sigbuf));
1857 result = smartlist_join_strings(chunks, "", 0, NULL);
1859 tor_free(client_versions);
1860 tor_free(server_versions);
1861 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
1862 smartlist_free(flags);
1863 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
1864 smartlist_free(chunks);
1867 networkstatus_t *c;
1868 if (!(c = networkstatus_parse_vote_from_string(result, NULL,
1869 NS_TYPE_CONSENSUS))) {
1870 log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
1871 "parse.");
1872 tor_free(result);
1873 return NULL;
1875 // Verify balancing parameters
1876 if (consensus_method >= MIN_METHOD_FOR_BW_WEIGHTS) {
1877 networkstatus_verify_bw_weights(c);
1879 networkstatus_vote_free(c);
1882 return result;
1885 /** Given a consensus vote <b>target</b> and a set of detached signatures in
1886 * <b>sigs</b> that correspond to the same consensus, check whether there are
1887 * any new signatures in <b>src_voter_list</b> that should be added to
1888 * <b>target</b>. (A signature should be added if we have no signature for that
1889 * voter in <b>target</b> yet, or if we have no verifiable signature and the
1890 * new signature is verifiable.) Return the number of signatures added or
1891 * changed, or -1 if the document signed by <b>sigs</b> isn't the same
1892 * document as <b>target</b>. */
1894 networkstatus_add_detached_signatures(networkstatus_t *target,
1895 ns_detached_signatures_t *sigs,
1896 const char **msg_out)
1898 int r = 0;
1899 const char *flavor;
1900 smartlist_t *siglist;
1901 tor_assert(sigs);
1902 tor_assert(target);
1903 tor_assert(target->type == NS_TYPE_CONSENSUS);
1905 flavor = networkstatus_get_flavor_name(target->flavor);
1907 /* Do the times seem right? */
1908 if (target->valid_after != sigs->valid_after) {
1909 *msg_out = "Valid-After times do not match "
1910 "when adding detached signatures to consensus";
1911 return -1;
1913 if (target->fresh_until != sigs->fresh_until) {
1914 *msg_out = "Fresh-until times do not match "
1915 "when adding detached signatures to consensus";
1916 return -1;
1918 if (target->valid_until != sigs->valid_until) {
1919 *msg_out = "Valid-until times do not match "
1920 "when adding detached signatures to consensus";
1921 return -1;
1923 siglist = strmap_get(sigs->signatures, flavor);
1924 if (!siglist) {
1925 *msg_out = "No signatures for given consensus flavor";
1926 return -1;
1929 /** Make sure all the digests we know match, and at least one matches. */
1931 digests_t *digests = strmap_get(sigs->digests, flavor);
1932 int n_matches = 0;
1933 digest_algorithm_t alg;
1934 if (!digests) {
1935 *msg_out = "No digests for given consensus flavor";
1936 return -1;
1938 for (alg = DIGEST_SHA1; alg < N_DIGEST_ALGORITHMS; ++alg) {
1939 if (!tor_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
1940 if (!memcmp(target->digests.d[alg], digests->d[alg], DIGEST256_LEN)) {
1941 ++n_matches;
1942 } else {
1943 *msg_out = "Mismatched digest.";
1944 return -1;
1948 if (!n_matches) {
1949 *msg_out = "No regognized digests for given consensus flavor";
1953 /* For each voter in src... */
1954 SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
1955 char voter_identity[HEX_DIGEST_LEN+1];
1956 networkstatus_voter_info_t *target_voter =
1957 networkstatus_get_voter_by_id(target, sig->identity_digest);
1958 authority_cert_t *cert = NULL;
1959 const char *algorithm;
1960 document_signature_t *old_sig = NULL;
1962 algorithm = crypto_digest_algorithm_get_name(sig->alg);
1964 base16_encode(voter_identity, sizeof(voter_identity),
1965 sig->identity_digest, DIGEST_LEN);
1966 log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
1967 algorithm);
1968 /* If the target doesn't know about this voter, then forget it. */
1969 if (!target_voter) {
1970 log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
1971 continue;
1974 old_sig = voter_get_sig_by_algorithm(target_voter, sig->alg);
1976 /* If the target already has a good signature from this voter, then skip
1977 * this one. */
1978 if (old_sig && old_sig->good_signature) {
1979 log_info(LD_DIR, "We already have a good signature from %s using %s",
1980 voter_identity, algorithm);
1981 continue;
1984 /* Try checking the signature if we haven't already. */
1985 if (!sig->good_signature && !sig->bad_signature) {
1986 cert = authority_cert_get_by_digests(sig->identity_digest,
1987 sig->signing_key_digest);
1988 if (cert)
1989 networkstatus_check_document_signature(target, sig, cert);
1992 /* If this signature is good, or we don't have any signature yet,
1993 * then maybe add it. */
1994 if (sig->good_signature || !old_sig || old_sig->bad_signature) {
1995 log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
1996 algorithm);
1997 ++r;
1998 if (old_sig) {
1999 smartlist_remove(target_voter->sigs, old_sig);
2000 document_signature_free(old_sig);
2002 smartlist_add(target_voter->sigs, document_signature_dup(sig));
2003 } else {
2004 log_info(LD_DIR, "Not adding signature from %s", voter_identity);
2006 } SMARTLIST_FOREACH_END(sig);
2008 return r;
2011 /** Return a newly allocated string containing all the signatures on
2012 * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
2013 * then the signatures will be put in a detached signatures document, so
2014 * prefix any non-NS-flavored signatures with "additional-signature" rather
2015 * than "directory-signature". */
2016 static char *
2017 networkstatus_format_signatures(networkstatus_t *consensus,
2018 int for_detached_signatures)
2020 smartlist_t *elements;
2021 char buf[4096];
2022 char *result = NULL;
2023 int n_sigs = 0;
2024 const consensus_flavor_t flavor = consensus->flavor;
2025 const char *flavor_name = networkstatus_get_flavor_name(flavor);
2026 const char *keyword;
2028 if (for_detached_signatures && flavor != FLAV_NS)
2029 keyword = "additional-signature";
2030 else
2031 keyword = "directory-signature";
2033 elements = smartlist_create();
2035 SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
2036 SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
2037 char sk[HEX_DIGEST_LEN+1];
2038 char id[HEX_DIGEST_LEN+1];
2039 if (!sig->signature || sig->bad_signature)
2040 continue;
2041 ++n_sigs;
2042 base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
2043 base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
2044 if (flavor == FLAV_NS) {
2045 tor_snprintf(buf, sizeof(buf),
2046 "%s %s %s\n-----BEGIN SIGNATURE-----\n",
2047 keyword, id, sk);
2048 } else {
2049 const char *digest_name =
2050 crypto_digest_algorithm_get_name(sig->alg);
2051 tor_snprintf(buf, sizeof(buf),
2052 "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
2053 keyword,
2054 for_detached_signatures ? " " : "",
2055 for_detached_signatures ? flavor_name : "",
2056 digest_name, id, sk);
2058 smartlist_add(elements, tor_strdup(buf));
2059 base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len);
2060 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
2061 smartlist_add(elements, tor_strdup(buf));
2062 } SMARTLIST_FOREACH_END(sig);
2063 } SMARTLIST_FOREACH_END(v);
2065 result = smartlist_join_strings(elements, "", 0, NULL);
2066 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2067 smartlist_free(elements);
2068 if (!n_sigs)
2069 tor_free(result);
2070 return result;
2073 /** Return a newly allocated string holding the detached-signatures document
2074 * corresponding to the signatures on <b>consensuses</b>, which must contain
2075 * exactly one FLAV_NS consensus, and no more than one consensus for each
2076 * other flavor. */
2077 char *
2078 networkstatus_get_detached_signatures(smartlist_t *consensuses)
2080 smartlist_t *elements;
2081 char buf[4096];
2082 char *result = NULL, *sigs = NULL;
2083 networkstatus_t *consensus_ns = NULL;
2084 tor_assert(consensuses);
2086 SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
2087 tor_assert(ns);
2088 tor_assert(ns->type == NS_TYPE_CONSENSUS);
2089 if (ns && ns->flavor == FLAV_NS)
2090 consensus_ns = ns;
2092 if (!consensus_ns) {
2093 log_warn(LD_BUG, "No NS consensus given.");
2094 return NULL;
2097 elements = smartlist_create();
2100 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
2101 vu_buf[ISO_TIME_LEN+1];
2102 char d[HEX_DIGEST_LEN+1];
2104 base16_encode(d, sizeof(d),
2105 consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
2106 format_iso_time(va_buf, consensus_ns->valid_after);
2107 format_iso_time(fu_buf, consensus_ns->fresh_until);
2108 format_iso_time(vu_buf, consensus_ns->valid_until);
2110 tor_snprintf(buf, sizeof(buf),
2111 "consensus-digest %s\n"
2112 "valid-after %s\n"
2113 "fresh-until %s\n"
2114 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
2115 smartlist_add(elements, tor_strdup(buf));
2118 /* Get all the digests for the non-FLAV_NS consensuses */
2119 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2120 const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
2121 int alg;
2122 if (ns->flavor == FLAV_NS)
2123 continue;
2125 /* start with SHA256; we don't include SHA1 for anything but the basic
2126 * consensus. */
2127 for (alg = DIGEST_SHA256; alg < N_DIGEST_ALGORITHMS; ++alg) {
2128 char d[HEX_DIGEST256_LEN+1];
2129 const char *alg_name =
2130 crypto_digest_algorithm_get_name(alg);
2131 if (tor_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
2132 continue;
2133 base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
2134 tor_snprintf(buf, sizeof(buf), "additional-digest %s %s %s\n",
2135 flavor_name, alg_name, d);
2136 smartlist_add(elements, tor_strdup(buf));
2138 } SMARTLIST_FOREACH_END(ns);
2140 /* Now get all the sigs for non-FLAV_NS consensuses */
2141 SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
2142 char *sigs;
2143 if (ns->flavor == FLAV_NS)
2144 continue;
2145 sigs = networkstatus_format_signatures(ns, 1);
2146 if (!sigs) {
2147 log_warn(LD_DIR, "Couldn't format signatures");
2148 goto err;
2150 smartlist_add(elements, sigs);
2151 } SMARTLIST_FOREACH_END(ns);
2153 /* Now add the FLAV_NS consensus signatrures. */
2154 sigs = networkstatus_format_signatures(consensus_ns, 1);
2155 if (!sigs)
2156 goto err;
2157 smartlist_add(elements, sigs);
2159 result = smartlist_join_strings(elements, "", 0, NULL);
2160 err:
2161 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
2162 smartlist_free(elements);
2163 return result;
2166 /** Return a newly allocated string holding a detached-signatures document for
2167 * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
2168 * <b>pending</b>. */
2169 static char *
2170 get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
2171 int n_flavors)
2173 int flav;
2174 char *signatures;
2175 smartlist_t *c = smartlist_create();
2176 for (flav = 0; flav < n_flavors; ++flav) {
2177 if (pending[flav].consensus)
2178 smartlist_add(c, pending[flav].consensus);
2180 signatures = networkstatus_get_detached_signatures(c);
2181 smartlist_free(c);
2182 return signatures;
2185 /** Release all storage held in <b>s</b>. */
2186 void
2187 ns_detached_signatures_free(ns_detached_signatures_t *s)
2189 if (!s)
2190 return;
2191 if (s->signatures) {
2192 STRMAP_FOREACH(s->signatures, flavor, smartlist_t *, sigs) {
2193 SMARTLIST_FOREACH(sigs, document_signature_t *, sig,
2194 document_signature_free(sig));
2195 smartlist_free(sigs);
2196 } STRMAP_FOREACH_END;
2197 strmap_free(s->signatures, NULL);
2198 strmap_free(s->digests, _tor_free);
2201 tor_free(s);
2204 /* =====
2205 * Certificate functions
2206 * ===== */
2208 /** Allocate and return a new authority_cert_t with the same contents as
2209 * <b>cert</b>. */
2210 authority_cert_t *
2211 authority_cert_dup(authority_cert_t *cert)
2213 authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
2214 tor_assert(cert);
2216 memcpy(out, cert, sizeof(authority_cert_t));
2217 /* Now copy pointed-to things. */
2218 out->cache_info.signed_descriptor_body =
2219 tor_strndup(cert->cache_info.signed_descriptor_body,
2220 cert->cache_info.signed_descriptor_len);
2221 out->cache_info.saved_location = SAVED_NOWHERE;
2222 out->identity_key = crypto_pk_dup_key(cert->identity_key);
2223 out->signing_key = crypto_pk_dup_key(cert->signing_key);
2225 return out;
2228 /* =====
2229 * Vote scheduling
2230 * ===== */
2232 /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
2233 * Note that these aren't the intervals we'll use to vote; they're the ones
2234 * that we'll vote to use. */
2235 void
2236 dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
2238 or_options_t *options = get_options();
2240 tor_assert(timing_out);
2242 timing_out->vote_interval = options->V3AuthVotingInterval;
2243 timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
2244 timing_out->vote_delay = options->V3AuthVoteDelay;
2245 timing_out->dist_delay = options->V3AuthDistDelay;
2248 /** Return the start of the next interval of size <b>interval</b> (in seconds)
2249 * after <b>now</b>. Midnight always starts a fresh interval, and if the last
2250 * interval of a day would be truncated to less than half its size, it is
2251 * rolled into the previous interval. */
2252 time_t
2253 dirvote_get_start_of_next_interval(time_t now, int interval)
2255 struct tm tm;
2256 time_t midnight_today;
2257 time_t midnight_tomorrow;
2258 time_t next;
2260 tor_gmtime_r(&now, &tm);
2261 tm.tm_hour = 0;
2262 tm.tm_min = 0;
2263 tm.tm_sec = 0;
2265 midnight_today = tor_timegm(&tm);
2266 midnight_tomorrow = midnight_today + (24*60*60);
2268 next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
2270 /* Intervals never cross midnight. */
2271 if (next > midnight_tomorrow)
2272 next = midnight_tomorrow;
2274 /* If the interval would only last half as long as it's supposed to, then
2275 * skip over to the next day. */
2276 if (next + interval/2 > midnight_tomorrow)
2277 next = midnight_tomorrow;
2279 return next;
2282 /** Scheduling information for a voting interval. */
2283 static struct {
2284 /** When do we generate and distribute our vote for this interval? */
2285 time_t voting_starts;
2286 /** When do we send an HTTP request for any votes that we haven't
2287 * been posted yet?*/
2288 time_t fetch_missing_votes;
2289 /** When do we give up on getting more votes and generate a consensus? */
2290 time_t voting_ends;
2291 /** When do we send an HTTP request for any signatures we're expecting to
2292 * see on the consensus? */
2293 time_t fetch_missing_signatures;
2294 /** When do we publish the consensus? */
2295 time_t interval_starts;
2297 /* True iff we have generated and distributed our vote. */
2298 int have_voted;
2299 /* True iff we've requested missing votes. */
2300 int have_fetched_missing_votes;
2301 /* True iff we have built a consensus and sent the signatures around. */
2302 int have_built_consensus;
2303 /* True iff we've fetched missing signatures. */
2304 int have_fetched_missing_signatures;
2305 /* True iff we have published our consensus. */
2306 int have_published_consensus;
2307 } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
2309 /** Set voting_schedule to hold the timing for the next vote we should be
2310 * doing. */
2311 void
2312 dirvote_recalculate_timing(or_options_t *options, time_t now)
2314 int interval, vote_delay, dist_delay;
2315 time_t start;
2316 time_t end;
2317 networkstatus_t *consensus;
2319 if (!authdir_mode_v3(options))
2320 return;
2322 consensus = networkstatus_get_live_consensus(now);
2324 memset(&voting_schedule, 0, sizeof(voting_schedule));
2326 if (consensus) {
2327 interval = (int)( consensus->fresh_until - consensus->valid_after );
2328 vote_delay = consensus->vote_seconds;
2329 dist_delay = consensus->dist_seconds;
2330 } else {
2331 interval = options->TestingV3AuthInitialVotingInterval;
2332 vote_delay = options->TestingV3AuthInitialVoteDelay;
2333 dist_delay = options->TestingV3AuthInitialDistDelay;
2336 tor_assert(interval > 0);
2338 if (vote_delay + dist_delay > interval/2)
2339 vote_delay = dist_delay = interval / 4;
2341 start = voting_schedule.interval_starts =
2342 dirvote_get_start_of_next_interval(now,interval);
2343 end = dirvote_get_start_of_next_interval(start+1, interval);
2345 tor_assert(end > start);
2347 voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
2348 voting_schedule.voting_ends = start - dist_delay;
2349 voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
2350 voting_schedule.voting_starts = start - dist_delay - vote_delay;
2353 char tbuf[ISO_TIME_LEN+1];
2354 format_iso_time(tbuf, voting_schedule.interval_starts);
2355 log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
2356 "consensus_set=%d, interval=%d",
2357 tbuf, consensus?1:0, interval);
2361 /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
2362 void
2363 dirvote_act(or_options_t *options, time_t now)
2365 if (!authdir_mode_v3(options))
2366 return;
2367 if (!voting_schedule.voting_starts) {
2368 char *keys = list_v3_auth_ids();
2369 authority_cert_t *c = get_my_v3_authority_cert();
2370 log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
2371 "Mine is %s.",
2372 keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
2373 tor_free(keys);
2374 dirvote_recalculate_timing(options, now);
2376 if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
2377 log_notice(LD_DIR, "Time to vote.");
2378 dirvote_perform_vote();
2379 voting_schedule.have_voted = 1;
2381 if (voting_schedule.fetch_missing_votes < now &&
2382 !voting_schedule.have_fetched_missing_votes) {
2383 log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
2384 dirvote_fetch_missing_votes();
2385 voting_schedule.have_fetched_missing_votes = 1;
2387 if (voting_schedule.voting_ends < now &&
2388 !voting_schedule.have_built_consensus) {
2389 log_notice(LD_DIR, "Time to compute a consensus.");
2390 dirvote_compute_consensuses();
2391 /* XXXX We will want to try again later if we haven't got enough
2392 * votes yet. Implement this if it turns out to ever happen. */
2393 voting_schedule.have_built_consensus = 1;
2395 if (voting_schedule.fetch_missing_signatures < now &&
2396 !voting_schedule.have_fetched_missing_signatures) {
2397 log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
2398 dirvote_fetch_missing_signatures();
2399 voting_schedule.have_fetched_missing_signatures = 1;
2401 if (voting_schedule.interval_starts < now &&
2402 !voting_schedule.have_published_consensus) {
2403 log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
2404 dirvote_publish_consensus();
2405 dirvote_clear_votes(0);
2406 voting_schedule.have_published_consensus = 1;
2407 /* XXXX We will want to try again later if we haven't got enough
2408 * signatures yet. Implement this if it turns out to ever happen. */
2409 dirvote_recalculate_timing(options, now);
2413 /** A vote networkstatus_t and its unparsed body: held around so we can
2414 * use it to generate a consensus (at voting_ends) and so we can serve it to
2415 * other authorities that might want it. */
2416 typedef struct pending_vote_t {
2417 cached_dir_t *vote_body;
2418 networkstatus_t *vote;
2419 } pending_vote_t;
2421 /** List of pending_vote_t for the current vote. Before we've used them to
2422 * build a consensus, the votes go here. */
2423 static smartlist_t *pending_vote_list = NULL;
2424 /** List of pending_vote_t for the previous vote. After we've used them to
2425 * build a consensus, the votes go here for the next period. */
2426 static smartlist_t *previous_vote_list = NULL;
2428 static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
2430 /** The detached signatures for the consensus that we're currently
2431 * building. */
2432 static char *pending_consensus_signatures = NULL;
2434 /** List of ns_detached_signatures_t: hold signatures that get posted to us
2435 * before we have generated the consensus on our own. */
2436 static smartlist_t *pending_consensus_signature_list = NULL;
2438 /** Generate a networkstatus vote and post it to all the v3 authorities.
2439 * (V3 Authority only) */
2440 static int
2441 dirvote_perform_vote(void)
2443 crypto_pk_env_t *key = get_my_v3_authority_signing_key();
2444 authority_cert_t *cert = get_my_v3_authority_cert();
2445 networkstatus_t *ns;
2446 char *contents;
2447 pending_vote_t *pending_vote;
2448 time_t now = time(NULL);
2450 int status;
2451 const char *msg = "";
2453 if (!cert || !key) {
2454 log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
2455 return -1;
2456 } else if (cert->expires < now) {
2457 log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
2458 return -1;
2460 if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
2461 return -1;
2463 contents = format_networkstatus_vote(key, ns);
2464 networkstatus_vote_free(ns);
2465 if (!contents)
2466 return -1;
2468 pending_vote = dirvote_add_vote(contents, &msg, &status);
2469 tor_free(contents);
2470 if (!pending_vote) {
2471 log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
2472 msg);
2473 return -1;
2476 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
2477 ROUTER_PURPOSE_GENERAL,
2478 V3_AUTHORITY,
2479 pending_vote->vote_body->dir,
2480 pending_vote->vote_body->dir_len, 0);
2481 log_notice(LD_DIR, "Vote posted.");
2482 return 0;
2485 /** Send an HTTP request to every other v3 authority, for the votes of every
2486 * authority for which we haven't received a vote yet in this period. (V3
2487 * authority only) */
2488 static void
2489 dirvote_fetch_missing_votes(void)
2491 smartlist_t *missing_fps = smartlist_create();
2492 char *resource;
2494 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2495 trusted_dir_server_t *, ds,
2497 if (!(ds->type & V3_AUTHORITY))
2498 continue;
2499 if (!dirvote_get_vote(ds->v3_identity_digest,
2500 DGV_BY_ID|DGV_INCLUDE_PENDING)) {
2501 char *cp = tor_malloc(HEX_DIGEST_LEN+1);
2502 base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
2503 DIGEST_LEN);
2504 smartlist_add(missing_fps, cp);
2508 if (!smartlist_len(missing_fps)) {
2509 smartlist_free(missing_fps);
2510 return;
2512 log_notice(LOG_NOTICE, "We're missing votes from %d authorities. Asking "
2513 "every other authority for a copy.", smartlist_len(missing_fps));
2514 resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
2515 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
2516 0, resource);
2517 tor_free(resource);
2518 SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
2519 smartlist_free(missing_fps);
2522 /** Send a request to every other authority for its detached signatures,
2523 * unless we have signatures from all other v3 authorities already. */
2524 static void
2525 dirvote_fetch_missing_signatures(void)
2527 int need_any = 0;
2528 int i;
2529 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
2530 networkstatus_t *consensus = pending_consensuses[i].consensus;
2531 if (!consensus ||
2532 networkstatus_check_consensus_signature(consensus, -1) == 1) {
2533 /* We have no consensus, or we have one that's signed by everybody. */
2534 continue;
2536 need_any = 1;
2538 if (!need_any)
2539 return;
2541 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
2542 0, NULL);
2545 /** Release all storage held by pending consensuses (those waiting for
2546 * signatures). */
2547 static void
2548 dirvote_clear_pending_consensuses(void)
2550 int i;
2551 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
2552 pending_consensus_t *pc = &pending_consensuses[i];
2553 tor_free(pc->body);
2555 networkstatus_vote_free(pc->consensus);
2556 pc->consensus = NULL;
2560 /** Drop all currently pending votes, consensus, and detached signatures. */
2561 static void
2562 dirvote_clear_votes(int all_votes)
2564 if (!previous_vote_list)
2565 previous_vote_list = smartlist_create();
2566 if (!pending_vote_list)
2567 pending_vote_list = smartlist_create();
2569 /* All "previous" votes are now junk. */
2570 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
2571 cached_dir_decref(v->vote_body);
2572 v->vote_body = NULL;
2573 networkstatus_vote_free(v->vote);
2574 tor_free(v);
2576 smartlist_clear(previous_vote_list);
2578 if (all_votes) {
2579 /* If we're dumping all the votes, we delete the pending ones. */
2580 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
2581 cached_dir_decref(v->vote_body);
2582 v->vote_body = NULL;
2583 networkstatus_vote_free(v->vote);
2584 tor_free(v);
2586 } else {
2587 /* Otherwise, we move them into "previous". */
2588 smartlist_add_all(previous_vote_list, pending_vote_list);
2590 smartlist_clear(pending_vote_list);
2592 if (pending_consensus_signature_list) {
2593 SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
2594 tor_free(cp));
2595 smartlist_clear(pending_consensus_signature_list);
2597 tor_free(pending_consensus_signatures);
2598 dirvote_clear_pending_consensuses();
2601 /** Return a newly allocated string containing the hex-encoded v3 authority
2602 identity digest of every recognized v3 authority. */
2603 static char *
2604 list_v3_auth_ids(void)
2606 smartlist_t *known_v3_keys = smartlist_create();
2607 char *keys;
2608 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2609 trusted_dir_server_t *, ds,
2610 if ((ds->type & V3_AUTHORITY) &&
2611 !tor_digest_is_zero(ds->v3_identity_digest))
2612 smartlist_add(known_v3_keys,
2613 tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
2614 keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
2615 SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
2616 smartlist_free(known_v3_keys);
2617 return keys;
2620 /** Called when we have received a networkstatus vote in <b>vote_body</b>.
2621 * Parse and validate it, and on success store it as a pending vote (which we
2622 * then return). Return NULL on failure. Sets *<b>msg_out</b> and
2623 * *<b>status_out</b> to an HTTP response and status code. (V3 authority
2624 * only) */
2625 pending_vote_t *
2626 dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
2628 networkstatus_t *vote;
2629 networkstatus_voter_info_t *vi;
2630 trusted_dir_server_t *ds;
2631 pending_vote_t *pending_vote = NULL;
2632 const char *end_of_vote = NULL;
2633 int any_failed = 0;
2634 tor_assert(vote_body);
2635 tor_assert(msg_out);
2636 tor_assert(status_out);
2638 if (!pending_vote_list)
2639 pending_vote_list = smartlist_create();
2640 *status_out = 0;
2641 *msg_out = NULL;
2643 again:
2644 vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
2645 NS_TYPE_VOTE);
2646 if (!end_of_vote)
2647 end_of_vote = vote_body + strlen(vote_body);
2648 if (!vote) {
2649 log_warn(LD_DIR, "Couldn't parse vote: length was %d",
2650 (int)strlen(vote_body));
2651 *msg_out = "Unable to parse vote";
2652 goto err;
2654 tor_assert(smartlist_len(vote->voters) == 1);
2655 vi = get_voter(vote);
2657 int any_sig_good = 0;
2658 SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
2659 if (sig->good_signature)
2660 any_sig_good = 1);
2661 tor_assert(any_sig_good);
2663 ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
2664 if (!ds) {
2665 char *keys = list_v3_auth_ids();
2666 log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
2667 "with authority key ID %s. "
2668 "This key ID is not recognized. Known v3 key IDs are: %s",
2669 vi->nickname, vi->address,
2670 hex_str(vi->identity_digest, DIGEST_LEN), keys);
2671 tor_free(keys);
2672 *msg_out = "Vote not from a recognized v3 authority";
2673 goto err;
2675 tor_assert(vote->cert);
2676 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2677 vote->cert->signing_key_digest)) {
2678 /* Hey, it's a new cert! */
2679 trusted_dirs_load_certs_from_string(
2680 vote->cert->cache_info.signed_descriptor_body,
2681 0 /* from_store */, 1 /*flush*/);
2682 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
2683 vote->cert->signing_key_digest)) {
2684 log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
2688 /* Is it for the right period? */
2689 if (vote->valid_after != voting_schedule.interval_starts) {
2690 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
2691 format_iso_time(tbuf1, vote->valid_after);
2692 format_iso_time(tbuf2, voting_schedule.interval_starts);
2693 log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
2694 "we were expecting %s", vi->address, tbuf1, tbuf2);
2695 *msg_out = "Bad valid-after time";
2696 goto err;
2699 /* Fetch any new router descriptors we just learned about */
2700 update_consensus_router_descriptor_downloads(time(NULL), 1, vote);
2702 /* Now see whether we already have a vote from this authority. */
2703 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
2704 if (! memcmp(v->vote->cert->cache_info.identity_digest,
2705 vote->cert->cache_info.identity_digest,
2706 DIGEST_LEN)) {
2707 networkstatus_voter_info_t *vi_old = get_voter(v->vote);
2708 if (!memcmp(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
2709 /* Ah, it's the same vote. Not a problem. */
2710 log_info(LD_DIR, "Discarding a vote we already have (from %s).",
2711 vi->address);
2712 if (*status_out < 200)
2713 *status_out = 200;
2714 goto discard;
2715 } else if (v->vote->published < vote->published) {
2716 log_notice(LD_DIR, "Replacing an older pending vote from this "
2717 "directory.");
2718 cached_dir_decref(v->vote_body);
2719 networkstatus_vote_free(v->vote);
2720 v->vote_body = new_cached_dir(tor_strndup(vote_body,
2721 end_of_vote-vote_body),
2722 vote->published);
2723 v->vote = vote;
2724 if (end_of_vote &&
2725 !strcmpstart(end_of_vote, "network-status-version"))
2726 goto again;
2728 if (*status_out < 200)
2729 *status_out = 200;
2730 if (!*msg_out)
2731 *msg_out = "OK";
2732 return v;
2733 } else {
2734 *msg_out = "Already have a newer pending vote";
2735 goto err;
2740 pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
2741 pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
2742 end_of_vote-vote_body),
2743 vote->published);
2744 pending_vote->vote = vote;
2745 smartlist_add(pending_vote_list, pending_vote);
2747 if (!strcmpstart(end_of_vote, "network-status-version ")) {
2748 vote_body = end_of_vote;
2749 goto again;
2752 goto done;
2754 err:
2755 any_failed = 1;
2756 if (!*msg_out)
2757 *msg_out = "Error adding vote";
2758 if (*status_out < 400)
2759 *status_out = 400;
2761 discard:
2762 networkstatus_vote_free(vote);
2764 if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
2765 vote_body = end_of_vote;
2766 goto again;
2769 done:
2771 if (*status_out < 200)
2772 *status_out = 200;
2773 if (!*msg_out) {
2774 if (!any_failed && !pending_vote) {
2775 *msg_out = "Duplicate discarded";
2776 } else {
2777 *msg_out = "ok";
2781 return any_failed ? NULL : pending_vote;
2784 /** Try to compute a v3 networkstatus consensus from the currently pending
2785 * votes. Return 0 on success, -1 on failure. Store the consensus in
2786 * pending_consensus: it won't be ready to be published until we have
2787 * everybody else's signatures collected too. (V3 Authority only) */
2788 static int
2789 dirvote_compute_consensuses(void)
2791 /* Have we got enough votes to try? */
2792 int n_votes, n_voters, n_vote_running = 0;
2793 smartlist_t *votes = NULL, *votestrings = NULL;
2794 char *consensus_body = NULL, *signatures = NULL, *votefile;
2795 networkstatus_t *consensus = NULL;
2796 authority_cert_t *my_cert;
2797 pending_consensus_t pending[N_CONSENSUS_FLAVORS];
2798 int flav;
2800 memset(pending, 0, sizeof(pending));
2802 if (!pending_vote_list)
2803 pending_vote_list = smartlist_create();
2805 n_voters = get_n_authorities(V3_AUTHORITY);
2806 n_votes = smartlist_len(pending_vote_list);
2807 if (n_votes <= n_voters/2) {
2808 log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
2809 "%d of %d", n_votes, n_voters/2);
2810 goto err;
2812 tor_assert(pending_vote_list);
2813 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
2814 if (smartlist_string_isin(v->vote->known_flags, "Running"))
2815 n_vote_running++;
2817 if (!n_vote_running) {
2818 /* See task 1066. */
2819 log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
2820 "and publishing a consensus without Running nodes "
2821 "would make many clients stop working. Not "
2822 "generating a consensus!");
2823 goto err;
2826 if (!(my_cert = get_my_v3_authority_cert())) {
2827 log_warn(LD_DIR, "Can't generate consensus without a certificate.");
2828 goto err;
2831 votes = smartlist_create();
2832 votestrings = smartlist_create();
2833 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
2835 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
2836 c->bytes = v->vote_body->dir;
2837 c->len = v->vote_body->dir_len;
2838 smartlist_add(votestrings, c); /* collect strings to write to disk */
2840 smartlist_add(votes, v->vote); /* collect votes to compute consensus */
2843 votefile = get_datadir_fname("v3-status-votes");
2844 write_chunks_to_file(votefile, votestrings, 0);
2845 tor_free(votefile);
2846 SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
2847 smartlist_free(votestrings);
2850 char legacy_dbuf[DIGEST_LEN];
2851 crypto_pk_env_t *legacy_sign=NULL;
2852 char *legacy_id_digest = NULL;
2853 int n_generated = 0;
2854 if (get_options()->V3AuthUseLegacyKey) {
2855 authority_cert_t *cert = get_my_v3_legacy_cert();
2856 legacy_sign = get_my_v3_legacy_signing_key();
2857 if (cert) {
2858 crypto_pk_get_digest(cert->identity_key, legacy_dbuf);
2859 legacy_id_digest = legacy_dbuf;
2863 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
2864 const char *flavor_name = networkstatus_get_flavor_name(flav);
2865 consensus_body = networkstatus_compute_consensus(
2866 votes, n_voters,
2867 my_cert->identity_key,
2868 get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
2869 flav);
2871 if (!consensus_body) {
2872 log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
2873 flavor_name);
2874 continue;
2876 consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
2877 NS_TYPE_CONSENSUS);
2878 if (!consensus) {
2879 log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
2880 flavor_name);
2881 tor_free(consensus_body);
2882 continue;
2885 /* 'Check' our own signature, to mark it valid. */
2886 networkstatus_check_consensus_signature(consensus, -1);
2888 pending[flav].body = consensus_body;
2889 pending[flav].consensus = consensus;
2890 n_generated++;
2891 consensus_body = NULL;
2892 consensus = NULL;
2894 if (!n_generated) {
2895 log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
2896 goto err;
2900 signatures = get_detached_signatures_from_pending_consensuses(
2901 pending, N_CONSENSUS_FLAVORS);
2903 if (!signatures) {
2904 log_warn(LD_DIR, "Couldn't extract signatures.");
2905 goto err;
2908 dirvote_clear_pending_consensuses();
2909 memcpy(pending_consensuses, pending, sizeof(pending));
2911 tor_free(pending_consensus_signatures);
2912 pending_consensus_signatures = signatures;
2914 if (pending_consensus_signature_list) {
2915 int n_sigs = 0;
2916 /* we may have gotten signatures for this consensus before we built
2917 * it ourself. Add them now. */
2918 SMARTLIST_FOREACH(pending_consensus_signature_list, char *, sig,
2920 const char *msg = NULL;
2921 int r = dirvote_add_signatures_to_all_pending_consensuses(sig, &msg);
2922 if (r >= 0)
2923 n_sigs += r;
2924 else
2925 log_warn(LD_DIR,
2926 "Could not add queued signature to new consensus: %s",
2927 msg);
2928 tor_free(sig);
2930 if (n_sigs)
2931 log_notice(LD_DIR, "Added %d pending signatures while building "
2932 "consensus.", n_sigs);
2933 smartlist_clear(pending_consensus_signature_list);
2936 log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
2938 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
2939 ROUTER_PURPOSE_GENERAL,
2940 V3_AUTHORITY,
2941 pending_consensus_signatures,
2942 strlen(pending_consensus_signatures), 0);
2943 log_notice(LD_DIR, "Signature(s) posted.");
2945 smartlist_free(votes);
2946 return 0;
2947 err:
2948 smartlist_free(votes);
2949 tor_free(consensus_body);
2950 tor_free(signatures);
2951 networkstatus_vote_free(consensus);
2953 return -1;
2956 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
2957 * signatures on the currently pending consensus. Add them to <b>pc</b>
2958 * as appropriate. Return the number of signatures added. (?) */
2959 static int
2960 dirvote_add_signatures_to_pending_consensus(
2961 pending_consensus_t *pc,
2962 ns_detached_signatures_t *sigs,
2963 const char **msg_out)
2965 const char *flavor_name;
2966 int r = -1;
2968 /* Only call if we have a pending consensus right now. */
2969 tor_assert(pc->consensus);
2970 tor_assert(pc->body);
2971 tor_assert(pending_consensus_signatures);
2973 flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
2974 *msg_out = NULL;
2977 smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
2978 log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
2979 sig_list ? smartlist_len(sig_list) : 0, flavor_name);
2981 r = networkstatus_add_detached_signatures(pc->consensus, sigs, msg_out);
2982 log_info(LD_DIR,"Added %d signatures to consensus.", r);
2984 if (r >= 1) {
2985 char *new_signatures =
2986 networkstatus_format_signatures(pc->consensus, 0);
2987 char *dst, *dst_end;
2988 size_t new_consensus_len;
2989 if (!new_signatures) {
2990 *msg_out = "No signatures to add";
2991 goto err;
2993 new_consensus_len =
2994 strlen(pc->body) + strlen(new_signatures) + 1;
2995 pc->body = tor_realloc(pc->body, new_consensus_len);
2996 dst_end = pc->body + new_consensus_len;
2997 dst = strstr(pc->body, "directory-signature ");
2998 tor_assert(dst);
2999 strlcpy(dst, new_signatures, dst_end-dst);
3001 /* We remove this block once it has failed to crash for a while. But
3002 * unless it shows up in profiles, we're probably better leaving it in,
3003 * just in case we break detached signature processing at some point. */
3005 networkstatus_t *v = networkstatus_parse_vote_from_string(
3006 pc->body, NULL,
3007 NS_TYPE_CONSENSUS);
3008 tor_assert(v);
3009 networkstatus_vote_free(v);
3011 *msg_out = "Signatures added";
3012 tor_free(new_signatures);
3013 } else if (r == 0) {
3014 *msg_out = "Signatures ignored";
3015 } else {
3016 goto err;
3019 goto done;
3020 err:
3021 if (!*msg_out)
3022 *msg_out = "Unrecognized error while adding detached signatures.";
3023 done:
3024 return r;
3027 static int
3028 dirvote_add_signatures_to_all_pending_consensuses(
3029 const char *detached_signatures_body,
3030 const char **msg_out)
3032 int r=0, i, n_added = 0, errors = 0;
3033 ns_detached_signatures_t *sigs;
3034 tor_assert(detached_signatures_body);
3035 tor_assert(msg_out);
3036 tor_assert(pending_consensus_signatures);
3038 if (!(sigs = networkstatus_parse_detached_signatures(
3039 detached_signatures_body, NULL))) {
3040 *msg_out = "Couldn't parse detached signatures.";
3041 goto err;
3044 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3045 int res;
3046 pending_consensus_t *pc = &pending_consensuses[i];
3047 if (!pc->consensus)
3048 continue;
3049 res = dirvote_add_signatures_to_pending_consensus(pc, sigs, msg_out);
3050 if (res < 0)
3051 errors++;
3052 else
3053 n_added += res;
3056 if (errors && !n_added) {
3057 r = -1;
3058 goto err;
3061 if (n_added && pending_consensuses[FLAV_NS].consensus) {
3062 char *new_detached =
3063 get_detached_signatures_from_pending_consensuses(
3064 pending_consensuses, N_CONSENSUS_FLAVORS);
3065 if (new_detached) {
3066 tor_free(pending_consensus_signatures);
3067 pending_consensus_signatures = new_detached;
3071 r = n_added;
3072 goto done;
3073 err:
3074 if (!*msg_out)
3075 *msg_out = "Unrecognized error while adding detached signatures.";
3076 done:
3077 ns_detached_signatures_free(sigs);
3078 /* XXXX NM Check how return is used. We can now have an error *and*
3079 signatures added. */
3080 return r;
3083 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
3084 * signatures on the currently pending consensus. Add them to the pending
3085 * consensus (if we have one); otherwise queue them until we have a
3086 * consensus. Return negative on failure, nonnegative on success. */
3088 dirvote_add_signatures(const char *detached_signatures_body,
3089 const char *source,
3090 const char **msg)
3092 if (pending_consensuses[FLAV_NS].consensus) {
3093 log_notice(LD_DIR, "Got a signature from %s. "
3094 "Adding it to the pending consensus.", source);
3095 return dirvote_add_signatures_to_all_pending_consensuses(
3096 detached_signatures_body, msg);
3097 } else {
3098 log_notice(LD_DIR, "Got a signature from %s. "
3099 "Queuing it for the next consensus.", source);
3100 if (!pending_consensus_signature_list)
3101 pending_consensus_signature_list = smartlist_create();
3102 smartlist_add(pending_consensus_signature_list,
3103 tor_strdup(detached_signatures_body));
3104 *msg = "Signature queued";
3105 return 0;
3109 /** Replace the consensus that we're currently serving with the one that we've
3110 * been building. (V3 Authority only) */
3111 static int
3112 dirvote_publish_consensus(void)
3114 int i;
3116 /* Now remember all the other consensuses as if we were a directory cache. */
3117 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
3118 pending_consensus_t *pending = &pending_consensuses[i];
3119 const char *name;
3120 name = networkstatus_get_flavor_name(i);
3121 tor_assert(name);
3122 if (!pending->consensus ||
3123 networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
3124 log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
3125 continue;
3128 if (networkstatus_set_current_consensus(pending->body, name, 0))
3129 log_warn(LD_DIR, "Error publishing %s consensus", name);
3130 else
3131 log_notice(LD_DIR, "Published %s consensus", name);
3134 return 0;
3137 /** Release all static storage held in dirvote.c */
3138 void
3139 dirvote_free_all(void)
3141 dirvote_clear_votes(1);
3142 /* now empty as a result of dirvote_clear_votes(). */
3143 smartlist_free(pending_vote_list);
3144 pending_vote_list = NULL;
3145 smartlist_free(previous_vote_list);
3146 previous_vote_list = NULL;
3148 dirvote_clear_pending_consensuses();
3149 tor_free(pending_consensus_signatures);
3150 if (pending_consensus_signature_list) {
3151 /* now empty as a result of dirvote_clear_votes(). */
3152 smartlist_free(pending_consensus_signature_list);
3153 pending_consensus_signature_list = NULL;
3157 /* ====
3158 * Access to pending items.
3159 * ==== */
3161 /** Return the body of the consensus that we're currently trying to build. */
3162 const char *
3163 dirvote_get_pending_consensus(consensus_flavor_t flav)
3165 tor_assert(((int)flav) >= 0 && flav < N_CONSENSUS_FLAVORS);
3166 return pending_consensuses[flav].body;
3169 /** Return the signatures that we know for the consensus that we're currently
3170 * trying to build. */
3171 const char *
3172 dirvote_get_pending_detached_signatures(void)
3174 return pending_consensus_signatures;
3177 /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
3178 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
3179 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
3180 * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
3181 * false, do not consider any votes for a consensus that's already been built.
3182 * If <b>include_pending</b> is false, do not consider any votes for the
3183 * consensus that's in progress. May return NULL if we have no vote for the
3184 * authority in question. */
3185 const cached_dir_t *
3186 dirvote_get_vote(const char *fp, int flags)
3188 int by_id = flags & DGV_BY_ID;
3189 const int include_pending = flags & DGV_INCLUDE_PENDING;
3190 const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
3192 if (!pending_vote_list && !previous_vote_list)
3193 return NULL;
3194 if (fp == NULL) {
3195 authority_cert_t *c = get_my_v3_authority_cert();
3196 if (c) {
3197 fp = c->cache_info.identity_digest;
3198 by_id = 1;
3199 } else
3200 return NULL;
3202 if (by_id) {
3203 if (pending_vote_list && include_pending) {
3204 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3205 if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3206 return pv->vote_body);
3208 if (previous_vote_list && include_previous) {
3209 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3210 if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
3211 return pv->vote_body);
3213 } else {
3214 if (pending_vote_list && include_pending) {
3215 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
3216 if (!memcmp(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3217 return pv->vote_body);
3219 if (previous_vote_list && include_previous) {
3220 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
3221 if (!memcmp(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
3222 return pv->vote_body);
3225 return NULL;
3228 /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>.
3230 * XXX Right now, there is only one way to generate microdescriptors from
3231 * router descriptors. This may change in future consensus methods. If so,
3232 * we'll need an internal way to remember which method we used, and ask for a
3233 * particular method.
3235 microdesc_t *
3236 dirvote_create_microdescriptor(const routerinfo_t *ri)
3238 microdesc_t *result = NULL;
3239 char *key = NULL, *summary = NULL, *family = NULL;
3240 char buf[1024];
3241 size_t keylen;
3242 char *out = buf, *end = buf+sizeof(buf);
3244 if (crypto_pk_write_public_key_to_string(ri->onion_pkey, &key, &keylen)<0)
3245 goto done;
3246 summary = policy_summarize(ri->exit_policy);
3247 if (ri->declared_family)
3248 family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
3250 if (tor_snprintf(out, end-out, "onion-key\n%s", key)<0)
3251 goto done;
3252 out += strlen(out);
3253 if (family) {
3254 if (tor_snprintf(out, end-out, "family %s\n", family)<0)
3255 goto done;
3256 out += strlen(out);
3258 if (summary && strcmp(summary, "reject 1-65535")) {
3259 if (tor_snprintf(out, end-out, "p %s\n", summary)<0)
3260 goto done;
3261 out += strlen(out);
3263 *out = '\0'; /* Make sure it's nul-terminated. This should be a no-op */
3266 smartlist_t *lst = microdescs_parse_from_string(buf, out, 0, 1);
3267 if (smartlist_len(lst) != 1) {
3268 log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
3269 SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
3270 smartlist_free(lst);
3271 goto done;
3273 result = smartlist_get(lst, 0);
3274 smartlist_free(lst);
3277 done:
3278 tor_free(key);
3279 tor_free(summary);
3280 tor_free(family);
3281 return result;
3284 /** Cached space-separated string to hold */
3285 static char *microdesc_consensus_methods = NULL;
3287 /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
3288 * in a consensus vote document. Write it into the <b>out_len</b>-byte buffer
3289 * in <b>out</b>. Return -1 on failure and the number of characters written
3290 * on success. */
3291 ssize_t
3292 dirvote_format_microdesc_vote_line(char *out, size_t out_len,
3293 const microdesc_t *md)
3295 char d64[BASE64_DIGEST256_LEN+1];
3296 if (!microdesc_consensus_methods) {
3297 microdesc_consensus_methods =
3298 make_consensus_method_list(MIN_METHOD_FOR_MICRODESC,
3299 MAX_SUPPORTED_CONSENSUS_METHOD,
3300 ",");
3301 tor_assert(microdesc_consensus_methods);
3303 if (digest256_to_base64(d64, md->digest)<0)
3304 return -1;
3306 if (tor_snprintf(out, out_len, "m %s sha256=%s\n",
3307 microdesc_consensus_methods, d64)<0)
3308 return -1;
3310 return strlen(out);
3313 /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
3314 * the digest algorithm <b>alg</b>, decode it and copy it into
3315 * <b>digest256_out</b> and return 0. Otherwise return -1. */
3317 vote_routerstatus_find_microdesc_hash(char *digest256_out,
3318 const vote_routerstatus_t *vrs,
3319 int method,
3320 digest_algorithm_t alg)
3322 /* XXXX only returns the sha256 method. */
3323 const vote_microdesc_hash_t *h;
3324 char mstr[64];
3325 size_t mlen;
3326 char dstr[64];
3328 tor_snprintf(mstr, sizeof(mstr), "%d", method);
3329 mlen = strlen(mstr);
3330 tor_snprintf(dstr, sizeof(dstr), " %s=",
3331 crypto_digest_algorithm_get_name(alg));
3333 for (h = vrs->microdesc; h; h = h->next) {
3334 const char *cp = h->microdesc_hash_line;
3335 size_t num_len;
3336 /* cp looks like \d+(,\d+)* (digesttype=val )+ . Let's hunt for mstr in
3337 * the first part. */
3338 while (1) {
3339 num_len = strspn(cp, "1234567890");
3340 if (num_len == mlen && !memcmp(mstr, cp, mlen)) {
3341 /* This is the line. */
3342 char buf[BASE64_DIGEST256_LEN+1];
3343 /* XXXX ignores extraneous stuff if the digest is too long. This
3344 * seems harmless enough, right? */
3345 cp = strstr(cp, dstr);
3346 if (!cp)
3347 return -1;
3348 cp += strlen(dstr);
3349 strlcpy(buf, cp, sizeof(buf));
3350 return digest256_from_base64(digest256_out, buf);
3352 if (num_len == 0 || cp[num_len] != ',')
3353 break;
3354 cp += num_len + 1;
3357 return -1;