Fixes to spelling fixes. Thanks, Roger!
[tor.git] / src / or / dirvote.c
blob0156e273bed605427ef6098e17d9ef6031aa9572
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRVOTE_PRIVATE
7 #include "or.h"
9 /**
10 * \file dirvote.c
11 * \brief Functions to compute directory consensus, and schedule voting.
12 **/
14 static int dirvote_add_signatures_to_pending_consensus(
15 const char *detached_signatures_body,
16 const char **msg_out);
17 static char *list_v3_auth_ids(void);
18 static void dirvote_fetch_missing_votes(void);
19 static void dirvote_fetch_missing_signatures(void);
20 static int dirvote_perform_vote(void);
21 static void dirvote_clear_votes(int all_votes);
22 static int dirvote_compute_consensus(void);
23 static int dirvote_publish_consensus(void);
25 /* =====
26 * Voting
27 * =====*/
29 /** Return a new string containing the string representation of the vote in
30 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
31 * For v3 authorities. */
32 char *
33 format_networkstatus_vote(crypto_pk_env_t *private_signing_key,
34 networkstatus_t *v3_ns)
36 size_t len;
37 char *status = NULL;
38 const char *client_versions = NULL, *server_versions = NULL;
39 char *outp, *endp;
40 char fingerprint[FINGERPRINT_LEN+1];
41 char ipaddr[INET_NTOA_BUF_LEN];
42 char digest[DIGEST_LEN];
43 struct in_addr in;
44 uint32_t addr;
45 routerlist_t *rl = router_get_routerlist();
46 char *version_lines = NULL;
47 networkstatus_voter_info_t *voter;
49 tor_assert(private_signing_key);
50 tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
52 voter = smartlist_get(v3_ns->voters, 0);
54 addr = voter->addr;
55 in.s_addr = htonl(addr);
56 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
58 base16_encode(fingerprint, sizeof(fingerprint),
59 v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
60 client_versions = v3_ns->client_versions;
61 server_versions = v3_ns->server_versions;
63 if (client_versions || server_versions) {
64 size_t v_len = 64;
65 char *cp;
66 if (client_versions)
67 v_len += strlen(client_versions);
68 if (server_versions)
69 v_len += strlen(server_versions);
70 version_lines = tor_malloc(v_len);
71 cp = version_lines;
72 if (client_versions) {
73 tor_snprintf(cp, v_len-(cp-version_lines),
74 "client-versions %s\n", client_versions);
75 cp += strlen(cp);
77 if (server_versions)
78 tor_snprintf(cp, v_len-(cp-version_lines),
79 "server-versions %s\n", server_versions);
80 } else {
81 version_lines = tor_strdup("");
84 len = 8192;
85 len += strlen(version_lines);
86 len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
87 len += v3_ns->cert->cache_info.signed_descriptor_len;
89 status = tor_malloc(len);
91 char published[ISO_TIME_LEN+1];
92 char va[ISO_TIME_LEN+1];
93 char fu[ISO_TIME_LEN+1];
94 char vu[ISO_TIME_LEN+1];
95 char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
96 authority_cert_t *cert = v3_ns->cert;
97 format_iso_time(published, v3_ns->published);
98 format_iso_time(va, v3_ns->valid_after);
99 format_iso_time(fu, v3_ns->fresh_until);
100 format_iso_time(vu, v3_ns->valid_until);
102 tor_assert(cert);
103 tor_snprintf(status, len,
104 "network-status-version 3\n"
105 "vote-status %s\n"
106 "consensus-methods 1 2 3 4 5\n"
107 "published %s\n"
108 "valid-after %s\n"
109 "fresh-until %s\n"
110 "valid-until %s\n"
111 "voting-delay %d %d\n"
112 "%s" /* versions */
113 "known-flags %s\n"
114 "dir-source %s %s %s %s %d %d\n"
115 "contact %s\n",
116 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
117 published, va, fu, vu,
118 v3_ns->vote_seconds, v3_ns->dist_seconds,
119 version_lines,
120 flags,
121 voter->nickname, fingerprint, voter->address,
122 ipaddr, voter->dir_port, voter->or_port, voter->contact);
124 tor_free(flags);
125 outp = status + strlen(status);
126 endp = status + len;
128 if (!tor_digest_is_zero(voter->legacy_id_digest)) {
129 char fpbuf[HEX_DIGEST_LEN+1];
130 base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
131 tor_snprintf(outp, endp-outp, "legacy-dir-key %s\n", fpbuf);
132 outp += strlen(outp);
135 tor_assert(outp + cert->cache_info.signed_descriptor_len < endp);
136 memcpy(outp, cert->cache_info.signed_descriptor_body,
137 cert->cache_info.signed_descriptor_len);
139 outp += cert->cache_info.signed_descriptor_len;
142 SMARTLIST_FOREACH(v3_ns->routerstatus_list, vote_routerstatus_t *, vrs,
144 if (routerstatus_format_entry(outp, endp-outp, &vrs->status,
145 vrs->version, 0, 0) < 0) {
146 log_warn(LD_BUG, "Unable to print router status.");
147 goto err;
149 outp += strlen(outp);
153 char signing_key_fingerprint[FINGERPRINT_LEN+1];
154 if (tor_snprintf(outp, endp-outp, "directory-signature ")<0) {
155 log_warn(LD_BUG, "Unable to start signature line.");
156 goto err;
158 outp += strlen(outp);
160 if (crypto_pk_get_fingerprint(private_signing_key,
161 signing_key_fingerprint, 0)<0) {
162 log_warn(LD_BUG, "Unable to get fingerprint for signing key");
163 goto err;
165 if (tor_snprintf(outp, endp-outp, "%s %s\n", fingerprint,
166 signing_key_fingerprint)<0) {
167 log_warn(LD_BUG, "Unable to end signature line.");
168 goto err;
170 outp += strlen(outp);
173 if (router_get_networkstatus_v3_hash(status, digest)<0)
174 goto err;
175 note_crypto_pk_op(SIGN_DIR);
176 if (router_append_dirobj_signature(outp,endp-outp,digest,
177 private_signing_key)<0) {
178 log_warn(LD_BUG, "Unable to sign networkstatus vote.");
179 goto err;
183 networkstatus_t *v;
184 if (!(v = networkstatus_parse_vote_from_string(status, NULL,
185 v3_ns->type))) {
186 log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
187 "<<%s>>",
188 v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
189 goto err;
191 networkstatus_vote_free(v);
194 goto done;
196 err:
197 tor_free(status);
198 done:
199 tor_free(version_lines);
200 return status;
203 /* =====
204 * Consensus generation
205 * ===== */
207 /** Given a vote <b>vote</b> (not a consensus!), return its associated
208 * networkstatus_voter_info_t. */
209 static networkstatus_voter_info_t *
210 get_voter(const networkstatus_t *vote)
212 tor_assert(vote);
213 tor_assert(vote->type == NS_TYPE_VOTE);
214 tor_assert(vote->voters);
215 tor_assert(smartlist_len(vote->voters) == 1);
216 return smartlist_get(vote->voters, 0);
219 /** Temporary structure used in constructing a list of dir-source entries
220 * for a consensus. One of these is generated for every vote, and one more
221 * for every legacy key in each vote. */
222 typedef struct dir_src_ent_t {
223 networkstatus_t *v;
224 const char *digest;
225 int is_legacy;
226 } dir_src_ent_t;
228 /** Helper for sorting networkstatus_t votes (not consensuses) by the
229 * hash of their voters' identity digests. */
230 static int
231 _compare_votes_by_authority_id(const void **_a, const void **_b)
233 const networkstatus_t *a = *_a, *b = *_b;
234 return memcmp(get_voter(a)->identity_digest,
235 get_voter(b)->identity_digest, DIGEST_LEN);
238 /** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
239 * their identity digests, and return -1, 0, or 1 depending on their
240 * ordering */
241 static int
242 _compare_dir_src_ents_by_authority_id(const void **_a, const void **_b)
244 const dir_src_ent_t *a = *_a, *b = *_b;
245 const networkstatus_voter_info_t *a_v = get_voter(a->v),
246 *b_v = get_voter(b->v);
247 const char *a_id, *b_id;
248 a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
249 b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;
251 return memcmp(a_id, b_id, DIGEST_LEN);
254 /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
255 * that occurs more than <b>min</b> times. */
256 static void
257 get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
259 char *cur = NULL;
260 int count = 0;
261 SMARTLIST_FOREACH(in, char *, cp,
263 if (cur && !strcmp(cp, cur)) {
264 ++count;
265 } else {
266 if (count > min)
267 smartlist_add(out, cur);
268 cur = cp;
269 count = 1;
272 if (count > min)
273 smartlist_add(out, cur);
276 /** Given a sorted list of strings <b>lst</b>, return the member that appears
277 * most. Break ties in favor of later-occurring members. */
278 static const char *
279 get_most_frequent_member(smartlist_t *lst)
281 const char *most_frequent = NULL;
282 int most_frequent_count = 0;
284 const char *cur = NULL;
285 int count = 0;
287 SMARTLIST_FOREACH(lst, const char *, s,
289 if (cur && !strcmp(s, cur)) {
290 ++count;
291 } else {
292 if (count >= most_frequent_count) {
293 most_frequent = cur;
294 most_frequent_count = count;
296 cur = s;
297 count = 1;
300 if (count >= most_frequent_count) {
301 most_frequent = cur;
302 most_frequent_count = count;
304 return most_frequent;
307 /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
308 * that come from the same routerinfo, with the same derived elements.
310 static int
311 compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
313 int r;
314 if ((r = memcmp(a->status.identity_digest, b->status.identity_digest,
315 DIGEST_LEN)))
316 return r;
317 if ((r = memcmp(a->status.descriptor_digest, b->status.descriptor_digest,
318 DIGEST_LEN)))
319 return r;
320 if ((r = (int)(b->status.published_on - a->status.published_on)))
321 return r;
322 if ((r = strcmp(b->status.nickname, a->status.nickname)))
323 return r;
324 if ((r = (((int)b->status.addr) - ((int)a->status.addr))))
325 return r;
326 if ((r = (((int)b->status.or_port) - ((int)a->status.or_port))))
327 return r;
328 if ((r = (((int)b->status.dir_port) - ((int)a->status.dir_port))))
329 return r;
330 return 0;
333 /** Helper for sorting routerlists based on compare_vote_rs. */
334 static int
335 _compare_vote_rs(const void **_a, const void **_b)
337 const vote_routerstatus_t *a = *_a, *b = *_b;
338 return compare_vote_rs(a,b);
341 /** Given a list of vote_routerstatus_t, all for the same router identity,
342 * return whichever is most frequent, breaking ties in favor of more
343 * recently published vote_routerstatus_t and in case of ties there,
344 * in favor of smaller descriptor digest.
346 static vote_routerstatus_t *
347 compute_routerstatus_consensus(smartlist_t *votes)
349 vote_routerstatus_t *most = NULL, *cur = NULL;
350 int most_n = 0, cur_n = 0;
351 time_t most_published = 0;
353 /* _compare_vote_rs() sorts the items by identity digest (all the same),
354 * then by SD digest. That way, if we have a tie that the published_on
355 * date cannot tie, we use the descriptor with the smaller digest.
357 smartlist_sort(votes, _compare_vote_rs);
358 SMARTLIST_FOREACH(votes, vote_routerstatus_t *, rs,
360 if (cur && !compare_vote_rs(cur, rs)) {
361 ++cur_n;
362 } else {
363 if (cur_n > most_n ||
364 (cur && cur_n == most_n &&
365 cur->status.published_on > most_published)) {
366 most = cur;
367 most_n = cur_n;
368 most_published = cur->status.published_on;
370 cur_n = 1;
371 cur = rs;
375 if (cur_n > most_n ||
376 (cur && cur_n == most_n && cur->status.published_on > most_published)) {
377 most = cur;
378 most_n = cur_n;
379 most_published = cur->status.published_on;
382 tor_assert(most);
383 return most;
386 /** Given a list of strings in <b>lst</b>, set the DIGEST_LEN-byte digest at
387 * <b>digest_out</b> to the hash of the concatenation of those strings. */
388 static void
389 hash_list_members(char *digest_out, smartlist_t *lst)
391 crypto_digest_env_t *d = crypto_new_digest_env();
392 SMARTLIST_FOREACH(lst, const char *, cp,
393 crypto_digest_add_bytes(d, cp, strlen(cp)));
394 crypto_digest_get_digest(d, digest_out, DIGEST_LEN);
395 crypto_free_digest_env(d);
398 /** Sorting helper: compare two strings based on their values as base-ten
399 * positive integers. (Non-integers are treated as prior to all integers, and
400 * compared lexically.) */
401 static int
402 _cmp_int_strings(const void **_a, const void **_b)
404 const char *a = *_a, *b = *_b;
405 int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
406 int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
407 if (ai<bi) {
408 return -1;
409 } else if (ai==bi) {
410 if (ai == 0) /* Parsing failed. */
411 return strcmp(a, b);
412 return 0;
413 } else {
414 return 1;
418 /** Given a list of networkstatus_t votes, determine and return the number of
419 * the highest consensus method that is supported by 2/3 of the voters. */
420 static int
421 compute_consensus_method(smartlist_t *votes)
423 smartlist_t *all_methods = smartlist_create();
424 smartlist_t *acceptable_methods = smartlist_create();
425 smartlist_t *tmp = smartlist_create();
426 int min = (smartlist_len(votes) * 2) / 3;
427 int n_ok;
428 int result;
429 SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
431 tor_assert(vote->supported_methods);
432 smartlist_add_all(tmp, vote->supported_methods);
433 smartlist_sort(tmp, _cmp_int_strings);
434 smartlist_uniq(tmp, _cmp_int_strings, NULL);
435 smartlist_add_all(all_methods, tmp);
436 smartlist_clear(tmp);
439 smartlist_sort(all_methods, _cmp_int_strings);
440 get_frequent_members(acceptable_methods, all_methods, min);
441 n_ok = smartlist_len(acceptable_methods);
442 if (n_ok) {
443 const char *best = smartlist_get(acceptable_methods, n_ok-1);
444 result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
445 } else {
446 result = 1;
448 smartlist_free(tmp);
449 smartlist_free(all_methods);
450 smartlist_free(acceptable_methods);
451 return result;
454 /** Return true iff <b>method</b> is a consensus method that we support. */
455 static int
456 consensus_method_is_supported(int method)
458 return (method >= 1) && (method <= 5);
461 /** Helper: given <b>lst</b>, a list of version strings such that every
462 * version appears once for every versioning voter who recommends it, return a
463 * newly allocated string holding the resulting client-versions or
464 * server-versions list. May change contents of <b>lst</b> */
465 static char *
466 compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
468 int min = n_versioning / 2;
469 smartlist_t *good = smartlist_create();
470 char *result;
471 sort_version_list(lst, 0);
472 get_frequent_members(good, lst, min);
473 result = smartlist_join_strings(good, ",", 0, NULL);
474 smartlist_free(good);
475 return result;
478 /** Given a list of vote networkstatus_t in <b>votes</b>, our public
479 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
480 * and the number of <b>total_authorities</b> that we believe exist in our
481 * voting quorum, generate the text of a new v3 consensus vote, and return the
482 * value in a newly allocated string.
484 * Note: this function DOES NOT check whether the votes are from
485 * recognized authorities. (dirvote_add_vote does that.) */
486 char *
487 networkstatus_compute_consensus(smartlist_t *votes,
488 int total_authorities,
489 crypto_pk_env_t *identity_key,
490 crypto_pk_env_t *signing_key,
491 const char *legacy_id_key_digest,
492 crypto_pk_env_t *legacy_signing_key)
494 smartlist_t *chunks;
495 char *result = NULL;
496 int consensus_method;
498 time_t valid_after, fresh_until, valid_until;
499 int vote_seconds, dist_seconds;
500 char *client_versions = NULL, *server_versions = NULL;
501 smartlist_t *flags;
502 tor_assert(total_authorities >= smartlist_len(votes));
504 if (!smartlist_len(votes)) {
505 log_warn(LD_DIR, "Can't compute a consensus from no votes.");
506 return NULL;
508 flags = smartlist_create();
510 consensus_method = compute_consensus_method(votes);
511 if (consensus_method_is_supported(consensus_method)) {
512 log_info(LD_DIR, "Generating consensus using method %d.",
513 consensus_method);
514 } else {
515 log_warn(LD_DIR, "The other authorities will use consensus method %d, "
516 "which I don't support. Maybe I should upgrade!",
517 consensus_method);
518 consensus_method = 1;
521 /* Compute medians of time-related things, and figure out how many
522 * routers we might need to talk about. */
524 int n_votes = smartlist_len(votes);
525 time_t *va_times = tor_malloc(n_votes * sizeof(time_t));
526 time_t *fu_times = tor_malloc(n_votes * sizeof(time_t));
527 time_t *vu_times = tor_malloc(n_votes * sizeof(time_t));
528 int *votesec_list = tor_malloc(n_votes * sizeof(int));
529 int *distsec_list = tor_malloc(n_votes * sizeof(int));
530 int n_versioning_clients = 0, n_versioning_servers = 0;
531 smartlist_t *combined_client_versions = smartlist_create();
532 smartlist_t *combined_server_versions = smartlist_create();
534 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
535 tor_assert(v->type == NS_TYPE_VOTE);
536 va_times[v_sl_idx] = v->valid_after;
537 fu_times[v_sl_idx] = v->fresh_until;
538 vu_times[v_sl_idx] = v->valid_until;
539 votesec_list[v_sl_idx] = v->vote_seconds;
540 distsec_list[v_sl_idx] = v->dist_seconds;
541 if (v->client_versions) {
542 smartlist_t *cv = smartlist_create();
543 ++n_versioning_clients;
544 smartlist_split_string(cv, v->client_versions, ",",
545 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
546 sort_version_list(cv, 1);
547 smartlist_add_all(combined_client_versions, cv);
548 smartlist_free(cv); /* elements get freed later. */
550 if (v->server_versions) {
551 smartlist_t *sv = smartlist_create();
552 ++n_versioning_servers;
553 smartlist_split_string(sv, v->server_versions, ",",
554 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
555 sort_version_list(sv, 1);
556 smartlist_add_all(combined_server_versions, sv);
557 smartlist_free(sv); /* elements get freed later. */
559 SMARTLIST_FOREACH(v->known_flags, const char *, cp,
560 smartlist_add(flags, tor_strdup(cp)));
561 } SMARTLIST_FOREACH_END(v);
562 valid_after = median_time(va_times, n_votes);
563 fresh_until = median_time(fu_times, n_votes);
564 valid_until = median_time(vu_times, n_votes);
565 vote_seconds = median_int(votesec_list, n_votes);
566 dist_seconds = median_int(distsec_list, n_votes);
568 tor_assert(valid_after+MIN_VOTE_INTERVAL <= fresh_until);
569 tor_assert(fresh_until+MIN_VOTE_INTERVAL <= valid_until);
570 tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
571 tor_assert(dist_seconds >= MIN_DIST_SECONDS);
573 server_versions = compute_consensus_versions_list(combined_server_versions,
574 n_versioning_servers);
575 client_versions = compute_consensus_versions_list(combined_client_versions,
576 n_versioning_clients);
578 SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
579 SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
580 smartlist_free(combined_server_versions);
581 smartlist_free(combined_client_versions);
583 smartlist_sort_strings(flags);
584 smartlist_uniq_strings(flags);
586 tor_free(va_times);
587 tor_free(fu_times);
588 tor_free(vu_times);
589 tor_free(votesec_list);
590 tor_free(distsec_list);
593 chunks = smartlist_create();
596 char buf[1024];
597 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
598 vu_buf[ISO_TIME_LEN+1];
599 char *flaglist;
600 format_iso_time(va_buf, valid_after);
601 format_iso_time(fu_buf, fresh_until);
602 format_iso_time(vu_buf, valid_until);
603 flaglist = smartlist_join_strings(flags, " ", 0, NULL);
605 smartlist_add(chunks, tor_strdup("network-status-version 3\n"
606 "vote-status consensus\n"));
608 if (consensus_method >= 2) {
609 tor_snprintf(buf, sizeof(buf), "consensus-method %d\n",
610 consensus_method);
611 smartlist_add(chunks, tor_strdup(buf));
614 tor_snprintf(buf, sizeof(buf),
615 "valid-after %s\n"
616 "fresh-until %s\n"
617 "valid-until %s\n"
618 "voting-delay %d %d\n"
619 "client-versions %s\n"
620 "server-versions %s\n"
621 "known-flags %s\n",
622 va_buf, fu_buf, vu_buf,
623 vote_seconds, dist_seconds,
624 client_versions, server_versions, flaglist);
625 smartlist_add(chunks, tor_strdup(buf));
627 tor_free(flaglist);
630 /* Sort the votes. */
631 smartlist_sort(votes, _compare_votes_by_authority_id);
632 /* Add the authority sections. */
634 smartlist_t *dir_sources = smartlist_create();
635 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
637 dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
638 e->v = v;
639 e->digest = get_voter(v)->identity_digest;
640 e->is_legacy = 0;
641 smartlist_add(dir_sources, e);
642 if (consensus_method >= 3 &&
643 !tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
644 dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
645 e_legacy->v = v;
646 e_legacy->digest = get_voter(v)->legacy_id_digest;
647 e_legacy->is_legacy = 1;
648 smartlist_add(dir_sources, e_legacy);
651 smartlist_sort(dir_sources, _compare_dir_src_ents_by_authority_id);
653 SMARTLIST_FOREACH(dir_sources, const dir_src_ent_t *, e,
655 char buf[1024];
656 struct in_addr in;
657 char ip[INET_NTOA_BUF_LEN];
658 char fingerprint[HEX_DIGEST_LEN+1];
659 char votedigest[HEX_DIGEST_LEN+1];
660 networkstatus_t *v = e->v;
661 networkstatus_voter_info_t *voter = get_voter(v);
663 if (e->is_legacy)
664 tor_assert(consensus_method >= 2);
666 in.s_addr = htonl(voter->addr);
667 tor_inet_ntoa(&in, ip, sizeof(ip));
668 base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
669 base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
670 DIGEST_LEN);
672 tor_snprintf(buf, sizeof(buf),
673 "dir-source %s%s %s %s %s %d %d\n",
674 voter->nickname, e->is_legacy ? "-legacy" : "",
675 fingerprint, voter->address, ip,
676 voter->dir_port,
677 voter->or_port);
678 smartlist_add(chunks, tor_strdup(buf));
679 if (! e->is_legacy) {
680 tor_snprintf(buf, sizeof(buf),
681 "contact %s\n"
682 "vote-digest %s\n",
683 voter->contact,
684 votedigest);
685 smartlist_add(chunks, tor_strdup(buf));
688 SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
689 smartlist_free(dir_sources);
692 /* Add the actual router entries. */
694 int *index; /* index[j] is the current index into votes[j]. */
695 int *size; /* size[j] is the number of routerstatuses in votes[j]. */
696 int *flag_counts; /* The number of voters that list flag[j] for the
697 * currently considered router. */
698 int i;
699 smartlist_t *matching_descs = smartlist_create();
700 smartlist_t *chosen_flags = smartlist_create();
701 smartlist_t *versions = smartlist_create();
702 smartlist_t *exitsummaries = smartlist_create();
703 uint32_t *bandwidths = tor_malloc(sizeof(uint32_t) * smartlist_len(votes));
704 int num_bandwidths;
706 int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
707 * votes[j] knows about. */
708 int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
709 * about flags[f]. */
710 int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
711 * is the same flag as votes[j]->known_flags[b]. */
712 int *named_flag; /* Index of the flag "Named" for votes[j] */
713 int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
714 int chosen_named_idx, chosen_unnamed_idx;
716 strmap_t *name_to_id_map = strmap_new();
717 char conflict[DIGEST_LEN];
718 char unknown[DIGEST_LEN];
719 memset(conflict, 0, sizeof(conflict));
720 memset(unknown, 0xff, sizeof(conflict));
722 index = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
723 size = tor_malloc_zero(sizeof(int)*smartlist_len(votes));
724 n_voter_flags = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
725 n_flag_voters = tor_malloc_zero(sizeof(int) * smartlist_len(flags));
726 flag_map = tor_malloc_zero(sizeof(int*) * smartlist_len(votes));
727 named_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
728 unnamed_flag = tor_malloc_zero(sizeof(int) * smartlist_len(votes));
729 for (i = 0; i < smartlist_len(votes); ++i)
730 unnamed_flag[i] = named_flag[i] = -1;
731 chosen_named_idx = smartlist_string_pos(flags, "Named");
732 chosen_unnamed_idx = smartlist_string_pos(flags, "Unnamed");
734 /* Build the flag index. */
735 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
737 flag_map[v_sl_idx] = tor_malloc_zero(
738 sizeof(int)*smartlist_len(v->known_flags));
739 SMARTLIST_FOREACH(v->known_flags, const char *, fl,
741 int p = smartlist_string_pos(flags, fl);
742 tor_assert(p >= 0);
743 flag_map[v_sl_idx][fl_sl_idx] = p;
744 ++n_flag_voters[p];
745 if (!strcmp(fl, "Named"))
746 named_flag[v_sl_idx] = fl_sl_idx;
747 if (!strcmp(fl, "Unnamed"))
748 unnamed_flag[v_sl_idx] = fl_sl_idx;
750 n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
751 size[v_sl_idx] = smartlist_len(v->routerstatus_list);
754 /* Named and Unnamed get treated specially */
755 if (consensus_method >= 2) {
756 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
758 uint64_t nf;
759 if (named_flag[v_sl_idx]<0)
760 continue;
761 nf = U64_LITERAL(1) << named_flag[v_sl_idx];
762 SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
764 if ((rs->flags & nf) != 0) {
765 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
766 if (!d) {
767 /* We have no name officially mapped to this digest. */
768 strmap_set_lc(name_to_id_map, rs->status.nickname,
769 rs->status.identity_digest);
770 } else if (d != conflict &&
771 memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
772 /* Authorities disagree about this nickname. */
773 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
774 } else {
775 /* It's already a conflict, or it's already this ID. */
780 SMARTLIST_FOREACH(votes, networkstatus_t *, v,
782 uint64_t uf;
783 if (unnamed_flag[v_sl_idx]<0)
784 continue;
785 uf = U64_LITERAL(1) << unnamed_flag[v_sl_idx];
786 SMARTLIST_FOREACH(v->routerstatus_list, vote_routerstatus_t *, rs,
788 if ((rs->flags & uf) != 0) {
789 const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
790 if (d == conflict || d == unknown) {
791 /* Leave it alone; we know what it is. */
792 } else if (!d) {
793 /* We have no name officially mapped to this digest. */
794 strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
795 } else if (!memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
796 /* Authorities disagree about this nickname. */
797 strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
798 } else {
799 /* It's mapped to a different name. */
806 /* Now go through all the votes */
807 flag_counts = tor_malloc(sizeof(int) * smartlist_len(flags));
808 while (1) {
809 vote_routerstatus_t *rs;
810 routerstatus_t rs_out;
811 const char *lowest_id = NULL;
812 const char *chosen_version;
813 const char *chosen_name = NULL;
814 int exitsummary_disagreement = 0;
815 int is_named = 0, is_unnamed = 0, is_running = 0;
816 int naming_conflict = 0;
817 int n_listing = 0;
818 int i;
819 char buf[256];
821 /* Of the next-to-be-considered digest in each voter, which is first? */
822 SMARTLIST_FOREACH(votes, networkstatus_t *, v, {
823 if (index[v_sl_idx] < size[v_sl_idx]) {
824 rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
825 if (!lowest_id ||
826 memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN) < 0)
827 lowest_id = rs->status.identity_digest;
830 if (!lowest_id) /* we're out of routers. */
831 break;
833 memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
834 smartlist_clear(matching_descs);
835 smartlist_clear(chosen_flags);
836 smartlist_clear(versions);
837 num_bandwidths = 0;
839 /* Okay, go through all the entries for this digest. */
840 SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
841 if (index[v_sl_idx] >= size[v_sl_idx])
842 continue; /* out of entries. */
843 rs = smartlist_get(v->routerstatus_list, index[v_sl_idx]);
844 if (memcmp(rs->status.identity_digest, lowest_id, DIGEST_LEN))
845 continue; /* doesn't include this router. */
846 /* At this point, we know that we're looking at a routerstatus with
847 * identity "lowest".
849 ++index[v_sl_idx];
850 ++n_listing;
852 smartlist_add(matching_descs, rs);
853 if (rs->version && rs->version[0])
854 smartlist_add(versions, rs->version);
856 /* Tally up all the flags. */
857 for (i = 0; i < n_voter_flags[v_sl_idx]; ++i) {
858 if (rs->flags & (U64_LITERAL(1) << i))
859 ++flag_counts[flag_map[v_sl_idx][i]];
861 if (rs->flags & (U64_LITERAL(1) << named_flag[v_sl_idx])) {
862 if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
863 log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
864 chosen_name, rs->status.nickname);
865 naming_conflict = 1;
867 chosen_name = rs->status.nickname;
870 /* count bandwidths */
871 if (rs->status.has_bandwidth)
872 bandwidths[num_bandwidths++] = rs->status.bandwidth;
873 } SMARTLIST_FOREACH_END(v);
875 /* We don't include this router at all unless more than half of
876 * the authorities we believe in list it. */
877 if (n_listing <= total_authorities/2)
878 continue;
880 /* Figure out the most popular opinion of what the most recent
881 * routerinfo and its contents are. */
882 rs = compute_routerstatus_consensus(matching_descs);
883 /* Copy bits of that into rs_out. */
884 tor_assert(!memcmp(lowest_id, rs->status.identity_digest, DIGEST_LEN));
885 memcpy(rs_out.identity_digest, lowest_id, DIGEST_LEN);
886 memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
887 DIGEST_LEN);
888 rs_out.addr = rs->status.addr;
889 rs_out.published_on = rs->status.published_on;
890 rs_out.dir_port = rs->status.dir_port;
891 rs_out.or_port = rs->status.or_port;
892 rs_out.has_bandwidth = 0;
893 rs_out.has_exitsummary = 0;
895 if (chosen_name && !naming_conflict) {
896 strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
897 } else {
898 strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
901 if (consensus_method == 1) {
902 is_named = chosen_named_idx >= 0 &&
903 (!naming_conflict && flag_counts[chosen_named_idx]);
904 } else {
905 const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
906 if (!d) {
907 is_named = is_unnamed = 0;
908 } else if (!memcmp(d, lowest_id, DIGEST_LEN)) {
909 is_named = 1; is_unnamed = 0;
910 } else {
911 is_named = 0; is_unnamed = 1;
915 /* Set the flags. */
916 smartlist_add(chosen_flags, (char*)"s"); /* for the start of the line. */
917 SMARTLIST_FOREACH(flags, const char *, fl,
919 if (!strcmp(fl, "Named")) {
920 if (is_named)
921 smartlist_add(chosen_flags, (char*)fl);
922 } else if (!strcmp(fl, "Unnamed") && consensus_method >= 2) {
923 if (is_unnamed)
924 smartlist_add(chosen_flags, (char*)fl);
925 } else {
926 if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
927 smartlist_add(chosen_flags, (char*)fl);
928 if (!strcmp(fl, "Running"))
929 is_running = 1;
934 /* Starting with consensus method 4 we do not list servers
935 * that are not running in a consensus. See Proposal 138 */
936 if (consensus_method >= 4 && !is_running)
937 continue;
939 /* Pick the version. */
940 if (smartlist_len(versions)) {
941 sort_version_list(versions, 0);
942 chosen_version = get_most_frequent_member(versions);
943 } else {
944 chosen_version = NULL;
947 /* Pick a bandwidth */
948 if (consensus_method >= 5 && num_bandwidths > 0) {
949 rs_out.has_bandwidth = 1;
950 rs_out.bandwidth = median_uint32(bandwidths, num_bandwidths);
953 /* Ok, we already picked a descriptor digest we want to list
954 * previously. Now we want to use the exit policy summary from
955 * that descriptor. If everybody plays nice all the voters who
956 * listed that descriptor will have the same summary. If not then
957 * something is fishy and we'll use the most common one (breaking
958 * ties in favor of lexicographically larger one (only because it
959 * lets me reuse more existing code.
961 * The other case that can happen is that no authority that voted
962 * for that descriptor has an exit policy summary. That's
963 * probably quite unlikely but can happen. In that case we use
964 * the policy that was most often listed in votes, again breaking
965 * ties like in the previous case.
967 if (consensus_method >= 5) {
968 /* Okay, go through all the votes for this router. We prepared
969 * that list previously */
970 const char *chosen_exitsummary = NULL;
971 smartlist_clear(exitsummaries);
972 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
973 /* Check if the vote where this status comes from had the
974 * proper descriptor */
975 tor_assert(!memcmp(rs_out.identity_digest,
976 vsr->status.identity_digest,
977 DIGEST_LEN));
978 if (vsr->status.has_exitsummary &&
979 !memcmp(rs_out.descriptor_digest,
980 vsr->status.descriptor_digest,
981 DIGEST_LEN)) {
982 tor_assert(vsr->status.exitsummary);
983 smartlist_add(exitsummaries, vsr->status.exitsummary);
984 if (!chosen_exitsummary) {
985 chosen_exitsummary = vsr->status.exitsummary;
986 } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
987 /* Great. There's disagreement among the voters. That
988 * really shouldn't be */
989 exitsummary_disagreement = 1;
994 if (exitsummary_disagreement) {
995 char id[HEX_DIGEST_LEN+1];
996 char dd[HEX_DIGEST_LEN+1];
997 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
998 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
999 log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
1000 " for router %s with descriptor %s. This really shouldn't"
1001 " have happened.", id, dd);
1003 smartlist_sort_strings(exitsummaries);
1004 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1005 } else if (!chosen_exitsummary) {
1006 char id[HEX_DIGEST_LEN+1];
1007 char dd[HEX_DIGEST_LEN+1];
1008 base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
1009 base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
1010 log_warn(LD_DIR, "Not one of the voters that made us select"
1011 "descriptor %s for router %s had an exit policy"
1012 "summary", dd, id);
1014 /* Ok, none of those voting for the digest we chose had an
1015 * exit policy for us. Well, that kinda sucks.
1017 smartlist_clear(exitsummaries);
1018 SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
1019 if (vsr->status.has_exitsummary)
1020 smartlist_add(exitsummaries, vsr->status.exitsummary);
1022 smartlist_sort_strings(exitsummaries);
1023 chosen_exitsummary = get_most_frequent_member(exitsummaries);
1025 if (!chosen_exitsummary)
1026 log_warn(LD_DIR, "Wow, not one of the voters had an exit "
1027 "policy summary for %s. Wow.", id);
1030 if (chosen_exitsummary) {
1031 rs_out.has_exitsummary = 1;
1032 /* yea, discards the const */
1033 rs_out.exitsummary = (char *)chosen_exitsummary;
1037 /* Okay!! Now we can write the descriptor... */
1038 /* First line goes into "buf". */
1039 routerstatus_format_entry(buf, sizeof(buf), &rs_out, NULL, 1, 0);
1040 smartlist_add(chunks, tor_strdup(buf));
1041 /* Second line is all flags. The "\n" is missing. */
1042 smartlist_add(chunks,
1043 smartlist_join_strings(chosen_flags, " ", 0, NULL));
1044 /* Now the version line. */
1045 if (chosen_version) {
1046 smartlist_add(chunks, tor_strdup("\nv "));
1047 smartlist_add(chunks, tor_strdup(chosen_version));
1049 smartlist_add(chunks, tor_strdup("\n"));
1050 /* Now the weight line. */
1051 if (rs_out.has_bandwidth) {
1052 int r = tor_snprintf(buf, sizeof(buf),
1053 "w Bandwidth=%d\n", rs_out.bandwidth);
1054 if (r<0) {
1055 log_warn(LD_BUG, "Not enough space in buffer for weight line.");
1056 *buf = '\0';
1058 smartlist_add(chunks, tor_strdup(buf));
1060 /* Now the exitpolicy summary line. */
1061 if (rs_out.has_exitsummary) {
1062 char buf[MAX_POLICY_LINE_LEN+1];
1063 int r = tor_snprintf(buf, sizeof(buf), "p %s\n", rs_out.exitsummary);
1064 if (r<0) {
1065 log_warn(LD_BUG, "Not enough space in buffer for exitpolicy line.");
1066 *buf = '\0';
1068 smartlist_add(chunks, tor_strdup(buf));
1071 /* And the loop is over and we move on to the next router */
1074 tor_free(index);
1075 tor_free(size);
1076 tor_free(n_voter_flags);
1077 tor_free(n_flag_voters);
1078 for (i = 0; i < smartlist_len(votes); ++i)
1079 tor_free(flag_map[i]);
1080 tor_free(flag_map);
1081 tor_free(flag_counts);
1082 tor_free(named_flag);
1083 tor_free(unnamed_flag);
1084 strmap_free(name_to_id_map, NULL);
1085 smartlist_free(matching_descs);
1086 smartlist_free(chosen_flags);
1087 smartlist_free(versions);
1088 smartlist_free(exitsummaries);
1089 tor_free(bandwidths);
1092 /* Add a signature. */
1094 char digest[DIGEST_LEN];
1095 char fingerprint[HEX_DIGEST_LEN+1];
1096 char signing_key_fingerprint[HEX_DIGEST_LEN+1];
1098 char buf[4096];
1099 smartlist_add(chunks, tor_strdup("directory-signature "));
1101 /* Compute the hash of the chunks. */
1102 hash_list_members(digest, chunks);
1104 /* Get the fingerprints */
1105 crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
1106 crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
1108 /* add the junk that will go at the end of the line. */
1109 tor_snprintf(buf, sizeof(buf), "%s %s\n", fingerprint,
1110 signing_key_fingerprint);
1111 /* And the signature. */
1112 if (router_append_dirobj_signature(buf, sizeof(buf), digest,
1113 signing_key)) {
1114 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1115 return NULL; /* This leaks, but it should never happen. */
1117 smartlist_add(chunks, tor_strdup(buf));
1119 if (legacy_id_key_digest && legacy_signing_key && consensus_method >= 3) {
1120 smartlist_add(chunks, tor_strdup("directory-signature "));
1121 base16_encode(fingerprint, sizeof(fingerprint),
1122 legacy_id_key_digest, DIGEST_LEN);
1123 crypto_pk_get_fingerprint(legacy_signing_key,
1124 signing_key_fingerprint, 0);
1125 tor_snprintf(buf, sizeof(buf), "%s %s\n", fingerprint,
1126 signing_key_fingerprint);
1127 if (router_append_dirobj_signature(buf, sizeof(buf), digest,
1128 legacy_signing_key)) {
1129 log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
1130 return NULL; /* This leaks, but it should never happen. */
1132 smartlist_add(chunks, tor_strdup(buf));
1136 result = smartlist_join_strings(chunks, "", 0, NULL);
1138 tor_free(client_versions);
1139 tor_free(server_versions);
1140 SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
1141 smartlist_free(flags);
1142 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
1143 smartlist_free(chunks);
1146 networkstatus_t *c;
1147 if (!(c = networkstatus_parse_vote_from_string(result, NULL,
1148 NS_TYPE_CONSENSUS))) {
1149 log_err(LD_BUG,"Generated a networkstatus consensus we couldn't "
1150 "parse.");
1151 tor_free(result);
1152 return NULL;
1154 networkstatus_vote_free(c);
1157 return result;
1160 /** Given a consensus vote <b>target</b> and a set of detached signatures in
1161 * <b>sigs</b> that correspond to the same consensus, check whether there are
1162 * any new signatures in <b>src_voter_list</b> that should be added to
1163 * <b>target</b>. (A signature should be added if we have no signature for that
1164 * voter in <b>target</b> yet, or if we have no verifiable signature and the
1165 * new signature is verifiable.) Return the number of signatures added or
1166 * changed, or -1 if the document signed by <b>sigs</b> isn't the same
1167 * document as <b>target</b>. */
1169 networkstatus_add_detached_signatures(networkstatus_t *target,
1170 ns_detached_signatures_t *sigs,
1171 const char **msg_out)
1173 int r = 0;
1174 tor_assert(sigs);
1175 tor_assert(target);
1176 tor_assert(target->type == NS_TYPE_CONSENSUS);
1178 /* Do the times seem right? */
1179 if (target->valid_after != sigs->valid_after) {
1180 *msg_out = "Valid-After times do not match "
1181 "when adding detached signatures to consensus";
1182 return -1;
1184 if (target->fresh_until != sigs->fresh_until) {
1185 *msg_out = "Fresh-until times do not match "
1186 "when adding detached signatures to consensus";
1187 return -1;
1189 if (target->valid_until != sigs->valid_until) {
1190 *msg_out = "Valid-until times do not match "
1191 "when adding detached signatures to consensus";
1192 return -1;
1194 /* Are they the same consensus? */
1195 if (memcmp(target->networkstatus_digest, sigs->networkstatus_digest,
1196 DIGEST_LEN)) {
1197 *msg_out = "Digest mismatch when adding detached signatures to consensus";
1198 return -1;
1201 /* For each voter in src... */
1202 SMARTLIST_FOREACH_BEGIN(sigs->signatures, networkstatus_voter_info_t *,
1203 src_voter) {
1204 char voter_identity[HEX_DIGEST_LEN+1];
1205 networkstatus_voter_info_t *target_voter =
1206 networkstatus_get_voter_by_id(target, src_voter->identity_digest);
1207 authority_cert_t *cert = NULL;
1209 base16_encode(voter_identity, sizeof(voter_identity),
1210 src_voter->identity_digest, DIGEST_LEN);
1211 log_info(LD_DIR, "Looking at signature from %s", voter_identity);
1212 /* If the target doesn't know about this voter, then forget it. */
1213 if (!target_voter) {
1214 log_info(LD_DIR, "We do not know about %s", voter_identity);
1215 continue;
1218 /* If the target already has a good signature from this voter, then skip
1219 * this one. */
1220 if (target_voter->good_signature) {
1221 log_info(LD_DIR, "We already have a good signature from %s",
1222 voter_identity);
1223 continue;
1226 /* Try checking the signature if we haven't already. */
1227 if (!src_voter->good_signature && !src_voter->bad_signature) {
1228 cert = authority_cert_get_by_digests(src_voter->identity_digest,
1229 src_voter->signing_key_digest);
1230 if (cert) {
1231 networkstatus_check_voter_signature(target, src_voter, cert);
1235 /* If this signature is good, or we don't have any signature yet,
1236 * then add it. */
1237 if (src_voter->good_signature || !target_voter->signature) {
1238 log_info(LD_DIR, "Adding signature from %s", voter_identity);
1239 ++r;
1240 tor_free(target_voter->signature);
1241 target_voter->signature =
1242 tor_memdup(src_voter->signature, src_voter->signature_len);
1243 memcpy(target_voter->signing_key_digest, src_voter->signing_key_digest,
1244 DIGEST_LEN);
1245 target_voter->signature_len = src_voter->signature_len;
1246 target_voter->good_signature = src_voter->good_signature;
1247 target_voter->bad_signature = src_voter->bad_signature;
1248 } else {
1249 log_info(LD_DIR, "Not adding signature from %s", voter_identity);
1251 } SMARTLIST_FOREACH_END(src_voter);
1253 return r;
1256 /** Return a newly allocated string holding the detached-signatures document
1257 * corresponding to the signatures on <b>consensus</b>. */
1258 char *
1259 networkstatus_get_detached_signatures(networkstatus_t *consensus)
1261 smartlist_t *elements;
1262 char buf[4096];
1263 char *result = NULL;
1264 int n_sigs = 0;
1265 tor_assert(consensus);
1266 tor_assert(consensus->type == NS_TYPE_CONSENSUS);
1268 elements = smartlist_create();
1271 char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
1272 vu_buf[ISO_TIME_LEN+1];
1273 char d[HEX_DIGEST_LEN+1];
1275 base16_encode(d, sizeof(d), consensus->networkstatus_digest, DIGEST_LEN);
1276 format_iso_time(va_buf, consensus->valid_after);
1277 format_iso_time(fu_buf, consensus->fresh_until);
1278 format_iso_time(vu_buf, consensus->valid_until);
1280 tor_snprintf(buf, sizeof(buf),
1281 "consensus-digest %s\n"
1282 "valid-after %s\n"
1283 "fresh-until %s\n"
1284 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
1285 smartlist_add(elements, tor_strdup(buf));
1288 SMARTLIST_FOREACH(consensus->voters, networkstatus_voter_info_t *, v,
1290 char sk[HEX_DIGEST_LEN+1];
1291 char id[HEX_DIGEST_LEN+1];
1292 if (!v->signature || v->bad_signature)
1293 continue;
1294 ++n_sigs;
1295 base16_encode(sk, sizeof(sk), v->signing_key_digest, DIGEST_LEN);
1296 base16_encode(id, sizeof(id), v->identity_digest, DIGEST_LEN);
1297 tor_snprintf(buf, sizeof(buf),
1298 "directory-signature %s %s\n-----BEGIN SIGNATURE-----\n",
1299 id, sk);
1300 smartlist_add(elements, tor_strdup(buf));
1301 base64_encode(buf, sizeof(buf), v->signature, v->signature_len);
1302 strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
1303 smartlist_add(elements, tor_strdup(buf));
1306 result = smartlist_join_strings(elements, "", 0, NULL);
1308 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
1309 smartlist_free(elements);
1310 if (!n_sigs)
1311 tor_free(result);
1312 return result;
1315 /** Release all storage held in <b>s</b>. */
1316 void
1317 ns_detached_signatures_free(ns_detached_signatures_t *s)
1319 if (s->signatures) {
1320 SMARTLIST_FOREACH(s->signatures, networkstatus_voter_info_t *, v,
1322 tor_free(v->signature);
1323 tor_free(v);
1325 smartlist_free(s->signatures);
1327 tor_free(s);
1330 /* =====
1331 * Certificate functions
1332 * ===== */
1334 /** Allocate and return a new authority_cert_t with the same contents as
1335 * <b>cert</b>. */
1336 authority_cert_t *
1337 authority_cert_dup(authority_cert_t *cert)
1339 authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
1340 tor_assert(cert);
1342 memcpy(out, cert, sizeof(authority_cert_t));
1343 /* Now copy pointed-to things. */
1344 out->cache_info.signed_descriptor_body =
1345 tor_strndup(cert->cache_info.signed_descriptor_body,
1346 cert->cache_info.signed_descriptor_len);
1347 out->cache_info.saved_location = SAVED_NOWHERE;
1348 out->identity_key = crypto_pk_dup_key(cert->identity_key);
1349 out->signing_key = crypto_pk_dup_key(cert->signing_key);
1351 return out;
1354 /* =====
1355 * Vote scheduling
1356 * ===== */
1358 /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
1359 * Note that these aren't the intervals we'll use to vote; they're the ones
1360 * that we'll vote to use. */
1361 void
1362 dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
1364 or_options_t *options = get_options();
1366 tor_assert(timing_out);
1368 timing_out->vote_interval = options->V3AuthVotingInterval;
1369 timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
1370 timing_out->vote_delay = options->V3AuthVoteDelay;
1371 timing_out->dist_delay = options->V3AuthDistDelay;
1374 /** Return the start of the next interval of size <b>interval</b> (in seconds)
1375 * after <b>now</b>. Midnight always starts a fresh interval, and if the last
1376 * interval of a day would be truncated to less than half its size, it is
1377 * rolled into the previous interval. */
1378 time_t
1379 dirvote_get_start_of_next_interval(time_t now, int interval)
1381 struct tm tm;
1382 time_t midnight_today;
1383 time_t midnight_tomorrow;
1384 time_t next;
1386 tor_gmtime_r(&now, &tm);
1387 tm.tm_hour = 0;
1388 tm.tm_min = 0;
1389 tm.tm_sec = 0;
1391 midnight_today = tor_timegm(&tm);
1392 midnight_tomorrow = midnight_today + (24*60*60);
1394 next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
1396 /* Intervals never cross midnight. */
1397 if (next > midnight_tomorrow)
1398 next = midnight_tomorrow;
1400 /* If the interval would only last half as long as it's supposed to, then
1401 * skip over to the next day. */
1402 if (next + interval/2 > midnight_tomorrow)
1403 next = midnight_tomorrow;
1405 return next;
1408 /** Scheduling information for a voting interval. */
1409 static struct {
1410 /** When do we generate and distribute our vote for this interval? */
1411 time_t voting_starts;
1412 /** When do we send an HTTP request for any votes that we haven't
1413 * been posted yet?*/
1414 time_t fetch_missing_votes;
1415 /** When do we give up on getting more votes and generate a consensus? */
1416 time_t voting_ends;
1417 /** When do we send an HTTP request for any signatures we're expecting to
1418 * see on the consensus? */
1419 time_t fetch_missing_signatures;
1420 /** When do we publish the consensus? */
1421 time_t interval_starts;
1423 /* True iff we have generated and distributed our vote. */
1424 int have_voted;
1425 /* True iff we've requested missing votes. */
1426 int have_fetched_missing_votes;
1427 /* True iff we have built a consensus and sent the signatures around. */
1428 int have_built_consensus;
1429 /* True iff we've fetched missing signatures. */
1430 int have_fetched_missing_signatures;
1431 /* True iff we have published our consensus. */
1432 int have_published_consensus;
1433 } voting_schedule = {0,0,0,0,0,0,0,0,0,0};
1435 /** Set voting_schedule to hold the timing for the next vote we should be
1436 * doing. */
1437 void
1438 dirvote_recalculate_timing(or_options_t *options, time_t now)
1440 int interval, vote_delay, dist_delay;
1441 time_t start;
1442 time_t end;
1443 networkstatus_t *consensus;
1445 if (!authdir_mode_v3(options))
1446 return;
1448 consensus = networkstatus_get_live_consensus(now);
1450 memset(&voting_schedule, 0, sizeof(voting_schedule));
1452 if (consensus) {
1453 interval = (int)( consensus->fresh_until - consensus->valid_after );
1454 vote_delay = consensus->vote_seconds;
1455 dist_delay = consensus->dist_seconds;
1456 } else {
1457 interval = options->TestingV3AuthInitialVotingInterval;
1458 vote_delay = options->TestingV3AuthInitialVoteDelay;
1459 dist_delay = options->TestingV3AuthInitialDistDelay;
1462 tor_assert(interval > 0);
1464 if (vote_delay + dist_delay > interval/2)
1465 vote_delay = dist_delay = interval / 4;
1467 start = voting_schedule.interval_starts =
1468 dirvote_get_start_of_next_interval(now,interval);
1469 end = dirvote_get_start_of_next_interval(start+1, interval);
1471 tor_assert(end > start);
1473 voting_schedule.fetch_missing_signatures = start - (dist_delay/2);
1474 voting_schedule.voting_ends = start - dist_delay;
1475 voting_schedule.fetch_missing_votes = start - dist_delay - (vote_delay/2);
1476 voting_schedule.voting_starts = start - dist_delay - vote_delay;
1479 char tbuf[ISO_TIME_LEN+1];
1480 format_iso_time(tbuf, voting_schedule.interval_starts);
1481 log_notice(LD_DIR,"Choosing expected valid-after time as %s: "
1482 "consensus_set=%d, interval=%d",
1483 tbuf, consensus?1:0, interval);
1487 /** Entry point: Take whatever voting actions are pending as of <b>now</b>. */
1488 void
1489 dirvote_act(or_options_t *options, time_t now)
1491 if (!authdir_mode_v3(options))
1492 return;
1493 if (!voting_schedule.voting_starts) {
1494 char *keys = list_v3_auth_ids();
1495 authority_cert_t *c = get_my_v3_authority_cert();
1496 log_notice(LD_DIR, "Scheduling voting. Known authority IDs are %s. "
1497 "Mine is %s.",
1498 keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
1499 tor_free(keys);
1500 dirvote_recalculate_timing(options, now);
1502 if (voting_schedule.voting_starts < now && !voting_schedule.have_voted) {
1503 log_notice(LD_DIR, "Time to vote.");
1504 dirvote_perform_vote();
1505 voting_schedule.have_voted = 1;
1507 if (voting_schedule.fetch_missing_votes < now &&
1508 !voting_schedule.have_fetched_missing_votes) {
1509 log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
1510 dirvote_fetch_missing_votes();
1511 voting_schedule.have_fetched_missing_votes = 1;
1513 if (voting_schedule.voting_ends < now &&
1514 !voting_schedule.have_built_consensus) {
1515 log_notice(LD_DIR, "Time to compute a consensus.");
1516 dirvote_compute_consensus();
1517 /* XXXX We will want to try again later if we haven't got enough
1518 * votes yet. Implement this if it turns out to ever happen. */
1519 voting_schedule.have_built_consensus = 1;
1521 if (voting_schedule.fetch_missing_signatures < now &&
1522 !voting_schedule.have_fetched_missing_signatures) {
1523 log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
1524 dirvote_fetch_missing_signatures();
1525 voting_schedule.have_fetched_missing_signatures = 1;
1527 if (voting_schedule.interval_starts < now &&
1528 !voting_schedule.have_published_consensus) {
1529 log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
1530 dirvote_publish_consensus();
1531 dirvote_clear_votes(0);
1532 voting_schedule.have_published_consensus = 1;
1533 /* XXXX We will want to try again later if we haven't got enough
1534 * signatures yet. Implement this if it turns out to ever happen. */
1535 dirvote_recalculate_timing(options, now);
1539 /** A vote networkstatus_t and its unparsed body: held around so we can
1540 * use it to generate a consensus (at voting_ends) and so we can serve it to
1541 * other authorities that might want it. */
1542 typedef struct pending_vote_t {
1543 cached_dir_t *vote_body;
1544 networkstatus_t *vote;
1545 } pending_vote_t;
1547 /** List of pending_vote_t for the current vote. Before we've used them to
1548 * build a consensus, the votes go here. */
1549 static smartlist_t *pending_vote_list = NULL;
1550 /** List of pending_vote_t for the previous vote. After we've used them to
1551 * build a consensus, the votes go here for the next period. */
1552 static smartlist_t *previous_vote_list = NULL;
1553 /** The body of the consensus that we're currently building. Once we
1554 * have it built, it goes into dirserv.c */
1555 static char *pending_consensus_body = NULL;
1556 /** The detached signatures for the consensus that we're currently
1557 * building. */
1558 static char *pending_consensus_signatures = NULL;
1559 /** The parsed in-progress consensus document. */
1560 static networkstatus_t *pending_consensus = NULL;
1561 /** List of ns_detached_signatures_t: hold signatures that get posted to us
1562 * before we have generated the consensus on our own. */
1563 static smartlist_t *pending_consensus_signature_list = NULL;
1565 /** Generate a networkstatus vote and post it to all the v3 authorities.
1566 * (V3 Authority only) */
1567 static int
1568 dirvote_perform_vote(void)
1570 crypto_pk_env_t *key = get_my_v3_authority_signing_key();
1571 authority_cert_t *cert = get_my_v3_authority_cert();
1572 networkstatus_t *ns;
1573 char *contents;
1574 pending_vote_t *pending_vote;
1575 time_t now = time(NULL);
1577 int status;
1578 const char *msg = "";
1580 if (!cert || !key) {
1581 log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
1582 return -1;
1583 } else if (cert->expires < now) {
1584 log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
1585 return -1;
1587 if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
1588 return -1;
1590 contents = format_networkstatus_vote(key, ns);
1591 networkstatus_vote_free(ns);
1592 if (!contents)
1593 return -1;
1595 pending_vote = dirvote_add_vote(contents, &msg, &status);
1596 tor_free(contents);
1597 if (!pending_vote) {
1598 log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
1599 msg);
1600 return -1;
1603 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
1604 ROUTER_PURPOSE_GENERAL,
1605 V3_AUTHORITY,
1606 pending_vote->vote_body->dir,
1607 pending_vote->vote_body->dir_len, 0);
1608 log_notice(LD_DIR, "Vote posted.");
1609 return 0;
1612 /** Send an HTTP request to every other v3 authority, for the votes of every
1613 * authority for which we haven't received a vote yet in this period. (V3
1614 * authority only) */
1615 static void
1616 dirvote_fetch_missing_votes(void)
1618 smartlist_t *missing_fps = smartlist_create();
1619 char *resource;
1621 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
1622 trusted_dir_server_t *, ds,
1624 if (!(ds->type & V3_AUTHORITY))
1625 continue;
1626 if (!dirvote_get_vote(ds->v3_identity_digest,
1627 DGV_BY_ID|DGV_INCLUDE_PENDING)) {
1628 char *cp = tor_malloc(HEX_DIGEST_LEN+1);
1629 base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
1630 DIGEST_LEN);
1631 smartlist_add(missing_fps, cp);
1635 if (!smartlist_len(missing_fps)) {
1636 smartlist_free(missing_fps);
1637 return;
1639 log_notice(LOG_NOTICE, "We're missing votes from %d authorities. Asking "
1640 "every other authority for a copy.", smartlist_len(missing_fps));
1641 resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
1642 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
1643 0, resource);
1644 tor_free(resource);
1645 SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
1646 smartlist_free(missing_fps);
1649 /** Send a request to every other authority for its detached signatures,
1650 * unless we have signatures from all other v3 authorities already. */
1651 static void
1652 dirvote_fetch_missing_signatures(void)
1654 if (!pending_consensus)
1655 return;
1656 if (networkstatus_check_consensus_signature(pending_consensus, -1) == 1)
1657 return; /* we have a signature from everybody. */
1659 directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
1660 0, NULL);
1663 /** Drop all currently pending votes, consensus, and detached signatures. */
1664 static void
1665 dirvote_clear_votes(int all_votes)
1667 if (!previous_vote_list)
1668 previous_vote_list = smartlist_create();
1669 if (!pending_vote_list)
1670 pending_vote_list = smartlist_create();
1672 /* All "previous" votes are now junk. */
1673 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
1674 cached_dir_decref(v->vote_body);
1675 v->vote_body = NULL;
1676 networkstatus_vote_free(v->vote);
1677 tor_free(v);
1679 smartlist_clear(previous_vote_list);
1681 if (all_votes) {
1682 /* If we're dumping all the votes, we delete the pending ones. */
1683 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
1684 cached_dir_decref(v->vote_body);
1685 v->vote_body = NULL;
1686 networkstatus_vote_free(v->vote);
1687 tor_free(v);
1689 } else {
1690 /* Otherwise, we move them into "previous". */
1691 smartlist_add_all(previous_vote_list, pending_vote_list);
1693 smartlist_clear(pending_vote_list);
1695 if (pending_consensus_signature_list) {
1696 SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
1697 tor_free(cp));
1698 smartlist_clear(pending_consensus_signature_list);
1700 tor_free(pending_consensus_body);
1701 tor_free(pending_consensus_signatures);
1702 if (pending_consensus) {
1703 networkstatus_vote_free(pending_consensus);
1704 pending_consensus = NULL;
1708 /** Return a newly allocated string containing the hex-encoded v3 authority
1709 identity digest of every recognized v3 authority. */
1710 static char *
1711 list_v3_auth_ids(void)
1713 smartlist_t *known_v3_keys = smartlist_create();
1714 char *keys;
1715 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
1716 trusted_dir_server_t *, ds,
1717 if ((ds->type & V3_AUTHORITY) &&
1718 !tor_digest_is_zero(ds->v3_identity_digest))
1719 smartlist_add(known_v3_keys,
1720 tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
1721 keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
1722 SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
1723 smartlist_free(known_v3_keys);
1724 return keys;
1727 /** Called when we have received a networkstatus vote in <b>vote_body</b>.
1728 * Parse and validate it, and on success store it as a pending vote (which we
1729 * then return). Return NULL on failure. Sets *<b>msg_out</b> and
1730 * *<b>status_out</b> to an HTTP response and status code. (V3 authority
1731 * only) */
1732 pending_vote_t *
1733 dirvote_add_vote(const char *vote_body, const char **msg_out, int *status_out)
1735 networkstatus_t *vote;
1736 networkstatus_voter_info_t *vi;
1737 trusted_dir_server_t *ds;
1738 pending_vote_t *pending_vote = NULL;
1739 const char *end_of_vote = NULL;
1740 int any_failed = 0;
1741 tor_assert(vote_body);
1742 tor_assert(msg_out);
1743 tor_assert(status_out);
1745 if (!pending_vote_list)
1746 pending_vote_list = smartlist_create();
1747 *status_out = 0;
1748 *msg_out = NULL;
1750 again:
1751 vote = networkstatus_parse_vote_from_string(vote_body, &end_of_vote,
1752 NS_TYPE_VOTE);
1753 if (!end_of_vote)
1754 end_of_vote = vote_body + strlen(vote_body);
1755 if (!vote) {
1756 log_warn(LD_DIR, "Couldn't parse vote: length was %d",
1757 (int)strlen(vote_body));
1758 *msg_out = "Unable to parse vote";
1759 goto err;
1761 tor_assert(smartlist_len(vote->voters) == 1);
1762 vi = get_voter(vote);
1763 tor_assert(vi->good_signature == 1);
1764 ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
1765 if (!ds) {
1766 char *keys = list_v3_auth_ids();
1767 log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
1768 "with authority key ID %s. "
1769 "This key ID is not recognized. Known v3 key IDs are: %s",
1770 vi->nickname, vi->address,
1771 hex_str(vi->identity_digest, DIGEST_LEN), keys);
1772 tor_free(keys);
1773 *msg_out = "Vote not from a recognized v3 authority";
1774 goto err;
1776 tor_assert(vote->cert);
1777 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
1778 vote->cert->signing_key_digest)) {
1779 /* Hey, it's a new cert! */
1780 trusted_dirs_load_certs_from_string(
1781 vote->cert->cache_info.signed_descriptor_body,
1782 0 /* from_store */, 1 /*flush*/);
1783 if (!authority_cert_get_by_digests(vote->cert->cache_info.identity_digest,
1784 vote->cert->signing_key_digest)) {
1785 log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
1789 /* Is it for the right period? */
1790 if (vote->valid_after != voting_schedule.interval_starts) {
1791 char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
1792 format_iso_time(tbuf1, vote->valid_after);
1793 format_iso_time(tbuf2, voting_schedule.interval_starts);
1794 log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
1795 "we were expecting %s", vi->address, tbuf1, tbuf2);
1796 *msg_out = "Bad valid-after time";
1797 goto err;
1800 /* Now see whether we already have a vote from this authority. */
1801 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
1802 if (! memcmp(v->vote->cert->cache_info.identity_digest,
1803 vote->cert->cache_info.identity_digest,
1804 DIGEST_LEN)) {
1805 networkstatus_voter_info_t *vi_old = get_voter(v->vote);
1806 if (!memcmp(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
1807 /* Ah, it's the same vote. Not a problem. */
1808 log_info(LD_DIR, "Discarding a vote we already have.");
1809 if (*status_out < 200)
1810 *status_out = 200;
1811 goto discard;
1812 } else if (v->vote->published < vote->published) {
1813 log_notice(LD_DIR, "Replacing an older pending vote from this "
1814 "directory.");
1815 cached_dir_decref(v->vote_body);
1816 networkstatus_vote_free(v->vote);
1817 v->vote_body = new_cached_dir(tor_strndup(vote_body,
1818 end_of_vote-vote_body),
1819 vote->published);
1820 v->vote = vote;
1821 if (end_of_vote &&
1822 !strcmpstart(end_of_vote, "network-status-version"))
1823 goto again;
1825 if (*status_out < 200)
1826 *status_out = 200;
1827 if (!*msg_out)
1828 *msg_out = "OK";
1829 return v;
1830 } else {
1831 *msg_out = "Already have a newer pending vote";
1832 goto err;
1837 pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
1838 pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
1839 end_of_vote-vote_body),
1840 vote->published);
1841 pending_vote->vote = vote;
1842 smartlist_add(pending_vote_list, pending_vote);
1844 if (!strcmpstart(end_of_vote, "network-status-version ")) {
1845 vote_body = end_of_vote;
1846 goto again;
1849 goto done;
1851 err:
1852 any_failed = 1;
1853 if (!*msg_out)
1854 *msg_out = "Error adding vote";
1855 if (*status_out < 400)
1856 *status_out = 400;
1858 discard:
1859 if (vote)
1860 networkstatus_vote_free(vote);
1862 if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
1863 vote_body = end_of_vote;
1864 goto again;
1867 done:
1869 if (*status_out < 200)
1870 *status_out = 200;
1871 if (!*msg_out) {
1872 if (!any_failed && !pending_vote) {
1873 *msg_out = "Duplicate discarded";
1874 } else {
1875 *msg_out = "ok";
1879 return any_failed ? NULL : pending_vote;
1882 /** Try to compute a v3 networkstatus consensus from the currently pending
1883 * votes. Return 0 on success, -1 on failure. Store the consensus in
1884 * pending_consensus: it won't be ready to be published until we have
1885 * everybody else's signatures collected too. (V3 Authority only) */
1886 static int
1887 dirvote_compute_consensus(void)
1889 /* Have we got enough votes to try? */
1890 int n_votes, n_voters;
1891 smartlist_t *votes = NULL, *votestrings = NULL;
1892 char *consensus_body = NULL, *signatures = NULL, *votefile;
1893 networkstatus_t *consensus = NULL;
1894 authority_cert_t *my_cert;
1896 if (!pending_vote_list)
1897 pending_vote_list = smartlist_create();
1899 n_voters = get_n_authorities(V3_AUTHORITY);
1900 n_votes = smartlist_len(pending_vote_list);
1901 if (n_votes <= n_voters/2) {
1902 log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
1903 "%d of %d", n_votes, n_voters/2);
1904 goto err;
1907 if (!(my_cert = get_my_v3_authority_cert())) {
1908 log_warn(LD_DIR, "Can't generate consensus without a certificate.");
1909 goto err;
1912 votes = smartlist_create();
1913 votestrings = smartlist_create();
1914 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
1916 sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
1917 c->bytes = v->vote_body->dir;
1918 c->len = v->vote_body->dir_len;
1919 smartlist_add(votestrings, c); /* collect strings to write to disk */
1921 smartlist_add(votes, v->vote); /* collect votes to compute consensus */
1924 votefile = get_datadir_fname("v3-status-votes");
1925 write_chunks_to_file(votefile, votestrings, 0);
1926 tor_free(votefile);
1927 SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
1928 smartlist_free(votestrings);
1931 char legacy_dbuf[DIGEST_LEN];
1932 crypto_pk_env_t *legacy_sign=NULL;
1933 char *legacy_id_digest = NULL;
1934 if (get_options()->V3AuthUseLegacyKey) {
1935 authority_cert_t *cert = get_my_v3_legacy_cert();
1936 legacy_sign = get_my_v3_legacy_signing_key();
1937 if (cert) {
1938 crypto_pk_get_digest(cert->identity_key, legacy_dbuf);
1939 legacy_id_digest = legacy_dbuf;
1942 consensus_body = networkstatus_compute_consensus(
1943 votes, n_voters,
1944 my_cert->identity_key,
1945 get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign);
1947 if (!consensus_body) {
1948 log_warn(LD_DIR, "Couldn't generate a consensus at all!");
1949 goto err;
1951 consensus = networkstatus_parse_vote_from_string(consensus_body, NULL,
1952 NS_TYPE_CONSENSUS);
1953 if (!consensus) {
1954 log_warn(LD_DIR, "Couldn't parse consensus we generated!");
1955 goto err;
1957 /* 'Check' our own signature, to mark it valid. */
1958 networkstatus_check_consensus_signature(consensus, -1);
1960 signatures = networkstatus_get_detached_signatures(consensus);
1961 if (!signatures) {
1962 log_warn(LD_DIR, "Couldn't extract signatures.");
1963 goto err;
1966 tor_free(pending_consensus_body);
1967 pending_consensus_body = consensus_body;
1968 tor_free(pending_consensus_signatures);
1969 pending_consensus_signatures = signatures;
1971 if (pending_consensus)
1972 networkstatus_vote_free(pending_consensus);
1973 pending_consensus = consensus;
1975 if (pending_consensus_signature_list) {
1976 int n_sigs = 0;
1977 /* we may have gotten signatures for this consensus before we built
1978 * it ourself. Add them now. */
1979 SMARTLIST_FOREACH(pending_consensus_signature_list, char *, sig,
1981 const char *msg = NULL;
1982 int r = dirvote_add_signatures_to_pending_consensus(sig, &msg);
1983 if (r >= 0)
1984 n_sigs += r;
1985 else
1986 log_warn(LD_DIR,
1987 "Could not add queued signature to new consensus: %s",
1988 msg);
1989 tor_free(sig);
1991 if (n_sigs)
1992 log_notice(LD_DIR, "Added %d pending signatures while building "
1993 "consensus.", n_sigs);
1994 smartlist_clear(pending_consensus_signature_list);
1997 log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
1999 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
2000 ROUTER_PURPOSE_GENERAL,
2001 V3_AUTHORITY,
2002 pending_consensus_signatures,
2003 strlen(pending_consensus_signatures), 0);
2004 log_notice(LD_DIR, "Signature(s) posted.");
2006 return 0;
2007 err:
2008 if (votes)
2009 smartlist_free(votes);
2010 tor_free(consensus_body);
2011 tor_free(signatures);
2012 networkstatus_vote_free(consensus);
2014 return -1;
2017 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
2018 * signatures on the currently pending consensus. Add them to the consensus
2019 * as appropriate. Return the number of signatures added. (?) */
2020 static int
2021 dirvote_add_signatures_to_pending_consensus(
2022 const char *detached_signatures_body,
2023 const char **msg_out)
2025 ns_detached_signatures_t *sigs = NULL;
2026 int r = -1;
2028 tor_assert(detached_signatures_body);
2029 tor_assert(msg_out);
2031 /* Only call if we have a pending consensus right now. */
2032 tor_assert(pending_consensus);
2033 tor_assert(pending_consensus_body);
2034 tor_assert(pending_consensus_signatures);
2036 *msg_out = NULL;
2038 if (!(sigs = networkstatus_parse_detached_signatures(
2039 detached_signatures_body, NULL))) {
2040 *msg_out = "Couldn't parse detached signatures.";
2041 goto err;
2044 log_info(LD_DIR, "Have %d signatures for adding to consensus.",
2045 smartlist_len(sigs->signatures));
2046 r = networkstatus_add_detached_signatures(pending_consensus,
2047 sigs, msg_out);
2048 log_info(LD_DIR,"Added %d signatures to consensus.", r);
2050 if (r >= 1) {
2051 char *new_detached =
2052 networkstatus_get_detached_signatures(pending_consensus);
2053 const char *src;
2054 char *dst, *dst_end;
2055 size_t new_consensus_len;
2056 if (!new_detached) {
2057 *msg_out = "No signatures to add";
2058 goto err;
2060 new_consensus_len =
2061 strlen(pending_consensus_body) + strlen(new_detached) + 1;
2062 pending_consensus_body = tor_realloc(pending_consensus_body,
2063 new_consensus_len);
2064 dst_end = pending_consensus_body + new_consensus_len;
2065 dst = strstr(pending_consensus_body, "directory-signature ");
2066 tor_assert(dst);
2067 src = strstr(new_detached, "directory-signature ");
2068 tor_assert(src);
2069 strlcpy(dst, src, dst_end-dst);
2071 /* We remove this block once it has failed to crash for a while. But
2072 * unless it shows up in profiles, we're probably better leaving it in,
2073 * just in case we break detached signature processing at some point. */
2075 ns_detached_signatures_t *sigs =
2076 networkstatus_parse_detached_signatures(new_detached, NULL);
2077 networkstatus_t *v = networkstatus_parse_vote_from_string(
2078 pending_consensus_body, NULL,
2079 NS_TYPE_CONSENSUS);
2080 tor_assert(sigs);
2081 ns_detached_signatures_free(sigs);
2082 tor_assert(v);
2083 networkstatus_vote_free(v);
2085 tor_free(pending_consensus_signatures);
2086 pending_consensus_signatures = new_detached;
2087 *msg_out = "Signatures added";
2088 } else if (r == 0) {
2089 *msg_out = "Signatures ignored";
2090 } else {
2091 goto err;
2094 goto done;
2095 err:
2096 if (!*msg_out)
2097 *msg_out = "Unrecognized error while adding detached signatures.";
2098 done:
2099 if (sigs)
2100 ns_detached_signatures_free(sigs);
2101 return r;
2104 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
2105 * signatures on the currently pending consensus. Add them to the pending
2106 * consensus (if we have one); otherwise queue them until we have a
2107 * consensus. Return negative on failure, nonnegative on success. */
2109 dirvote_add_signatures(const char *detached_signatures_body,
2110 const char *source,
2111 const char **msg)
2113 if (pending_consensus) {
2114 log_notice(LD_DIR, "Got a signature from %s. "
2115 "Adding it to the pending consensus.", source);
2116 return dirvote_add_signatures_to_pending_consensus(
2117 detached_signatures_body, msg);
2118 } else {
2119 log_notice(LD_DIR, "Got a signature from %s. "
2120 "Queuing it for the next consensus.", source);
2121 if (!pending_consensus_signature_list)
2122 pending_consensus_signature_list = smartlist_create();
2123 smartlist_add(pending_consensus_signature_list,
2124 tor_strdup(detached_signatures_body));
2125 *msg = "Signature queued";
2126 return 0;
2130 /** Replace the consensus that we're currently serving with the one that we've
2131 * been building. (V3 Authority only) */
2132 static int
2133 dirvote_publish_consensus(void)
2135 /* Can we actually publish it yet? */
2136 if (!pending_consensus ||
2137 networkstatus_check_consensus_signature(pending_consensus, 1)<0) {
2138 log_warn(LD_DIR, "Not enough info to publish pending consensus");
2139 return -1;
2142 if (networkstatus_set_current_consensus(pending_consensus_body, 0))
2143 log_warn(LD_DIR, "Error publishing consensus");
2144 else
2145 log_notice(LD_DIR, "Consensus published.");
2147 return 0;
2150 /** Release all static storage held in dirvote.c */
2151 void
2152 dirvote_free_all(void)
2154 dirvote_clear_votes(1);
2155 /* now empty as a result of clear_pending_votes. */
2156 smartlist_free(pending_vote_list);
2157 pending_vote_list = NULL;
2158 smartlist_free(previous_vote_list);
2159 previous_vote_list = NULL;
2161 tor_free(pending_consensus_body);
2162 tor_free(pending_consensus_signatures);
2163 if (pending_consensus) {
2164 networkstatus_vote_free(pending_consensus);
2165 pending_consensus = NULL;
2167 if (pending_consensus_signature_list) {
2168 /* now empty as a result of clear_pending_votes. */
2169 smartlist_free(pending_consensus_signature_list);
2170 pending_consensus_signature_list = NULL;
2174 /* ====
2175 * Access to pending items.
2176 * ==== */
2178 /** Return the body of the consensus that we're currently trying to build. */
2179 const char *
2180 dirvote_get_pending_consensus(void)
2182 return pending_consensus_body;
2185 /** Return the signatures that we know for the consensus that we're currently
2186 * trying to build */
2187 const char *
2188 dirvote_get_pending_detached_signatures(void)
2190 return pending_consensus_signatures;
2193 /** Return a given vote specified by <b>fp</b>. If <b>by_id</b>, return the
2194 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
2195 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>. If
2196 * <b>fp</b> is NULL, return our own vote. If <b>include_previous</b> is
2197 * false, do not consider any votes for a consensus that's already been built.
2198 * If <b>include_pending</b> is false, do not consider any votes for the
2199 * consensus that's in progress. May return NULL if we have no vote for the
2200 * authority in question. */
2201 const cached_dir_t *
2202 dirvote_get_vote(const char *fp, int flags)
2204 int by_id = flags & DGV_BY_ID;
2205 const int include_pending = flags & DGV_INCLUDE_PENDING;
2206 const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
2208 if (!pending_vote_list && !previous_vote_list)
2209 return NULL;
2210 if (fp == NULL) {
2211 authority_cert_t *c = get_my_v3_authority_cert();
2212 if (c) {
2213 fp = c->cache_info.identity_digest;
2214 by_id = 1;
2215 } else
2216 return NULL;
2218 if (by_id) {
2219 if (pending_vote_list && include_pending) {
2220 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
2221 if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
2222 return pv->vote_body);
2224 if (previous_vote_list && include_previous) {
2225 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
2226 if (!memcmp(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
2227 return pv->vote_body);
2229 } else {
2230 if (pending_vote_list && include_pending) {
2231 SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
2232 if (!memcmp(pv->vote->networkstatus_digest, fp, DIGEST_LEN))
2233 return pv->vote_body);
2235 if (previous_vote_list && include_previous) {
2236 SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
2237 if (!memcmp(pv->vote->networkstatus_digest, fp, DIGEST_LEN))
2238 return pv->vote_body);
2241 return NULL;