TOR: update to v0.2.5.12
[tomato.git] / release / src / router / tor / src / or / networkstatus.c
blob890da0ad17f152ddbf959dbf1bc403a600086ed1
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file networkstatus.c
9 * \brief Functions and structures for handling network status documents as a
10 * client or cache.
13 #define NETWORKSTATUS_PRIVATE
14 #include "or.h"
15 #include "channel.h"
16 #include "circuitmux.h"
17 #include "circuitmux_ewma.h"
18 #include "circuitstats.h"
19 #include "config.h"
20 #include "connection.h"
21 #include "connection_or.h"
22 #include "control.h"
23 #include "directory.h"
24 #include "dirserv.h"
25 #include "dirvote.h"
26 #include "entrynodes.h"
27 #include "main.h"
28 #include "microdesc.h"
29 #include "networkstatus.h"
30 #include "nodelist.h"
31 #include "relay.h"
32 #include "router.h"
33 #include "routerlist.h"
34 #include "routerparse.h"
35 #include "transports.h"
37 /** Map from lowercase nickname to identity digest of named server, if any. */
38 static strmap_t *named_server_map = NULL;
39 /** Map from lowercase nickname to (void*)1 for all names that are listed
40 * as unnamed for some server in the consensus. */
41 static strmap_t *unnamed_server_map = NULL;
43 /** Most recently received and validated v3 consensus network status,
44 * of whichever type we are using for our own circuits. This will be the same
45 * as one of current_ns_consensus or current_md_consensus.
47 #define current_consensus \
48 (we_use_microdescriptors_for_circuits(get_options()) ? \
49 current_md_consensus : current_ns_consensus)
51 /** Most recently received and validated v3 "ns"-flavored consensus network
52 * status. */
53 static networkstatus_t *current_ns_consensus = NULL;
55 /** Most recently received and validated v3 "microdec"-flavored consensus
56 * network status. */
57 static networkstatus_t *current_md_consensus = NULL;
59 /** A v3 consensus networkstatus that we've received, but which we don't
60 * have enough certificates to be happy about. */
61 typedef struct consensus_waiting_for_certs_t {
62 /** The consensus itself. */
63 networkstatus_t *consensus;
64 /** The encoded version of the consensus, nul-terminated. */
65 char *body;
66 /** When did we set the current value of consensus_waiting_for_certs? If
67 * this is too recent, we shouldn't try to fetch a new consensus for a
68 * little while, to give ourselves time to get certificates for this one. */
69 time_t set_at;
70 /** Set to 1 if we've been holding on to it for so long we should maybe
71 * treat it as being bad. */
72 int dl_failed;
73 } consensus_waiting_for_certs_t;
75 /** An array, for each flavor of consensus we might want, of consensuses that
76 * we have downloaded, but which we cannot verify due to having insufficient
77 * authority certificates. */
78 static consensus_waiting_for_certs_t
79 consensus_waiting_for_certs[N_CONSENSUS_FLAVORS];
81 /** A time before which we shouldn't try to replace the current consensus:
82 * this will be at some point after the next consensus becomes valid, but
83 * before the current consensus becomes invalid. */
84 static time_t time_to_download_next_consensus[N_CONSENSUS_FLAVORS];
85 /** Download status for the current consensus networkstatus. */
86 static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS];
88 /** True iff we have logged a warning about this OR's version being older than
89 * listed by the authorities. */
90 static int have_warned_about_old_version = 0;
91 /** True iff we have logged a warning about this OR's version being newer than
92 * listed by the authorities. */
93 static int have_warned_about_new_version = 0;
95 static void routerstatus_list_update_named_server_map(void);
97 /** Forget that we've warned about anything networkstatus-related, so we will
98 * give fresh warnings if the same behavior happens again. */
99 void
100 networkstatus_reset_warnings(void)
102 if (current_consensus) {
103 SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
104 node->name_lookup_warned = 0);
107 have_warned_about_old_version = 0;
108 have_warned_about_new_version = 0;
111 /** Reset the descriptor download failure count on all networkstatus docs, so
112 * that we can retry any long-failed documents immediately.
114 void
115 networkstatus_reset_download_failures(void)
117 int i;
119 for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
120 download_status_reset(&consensus_dl_status[i]);
123 /** Read every cached v3 consensus networkstatus from the disk. */
125 router_reload_consensus_networkstatus(void)
127 char *filename;
128 char *s;
129 const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
130 int flav;
132 /* FFFF Suppress warnings if cached consensus is bad? */
133 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
134 char buf[128];
135 const char *flavor = networkstatus_get_flavor_name(flav);
136 if (flav == FLAV_NS) {
137 filename = get_datadir_fname("cached-consensus");
138 } else {
139 tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
140 filename = get_datadir_fname(buf);
142 s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
143 if (s) {
144 if (networkstatus_set_current_consensus(s, flavor, flags) < -1) {
145 log_warn(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
146 flavor, filename);
148 tor_free(s);
150 tor_free(filename);
152 if (flav == FLAV_NS) {
153 filename = get_datadir_fname("unverified-consensus");
154 } else {
155 tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
156 filename = get_datadir_fname(buf);
159 s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
160 if (s) {
161 if (networkstatus_set_current_consensus(s, flavor,
162 flags|NSSET_WAS_WAITING_FOR_CERTS)) {
163 log_info(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
164 flavor, filename);
166 tor_free(s);
168 tor_free(filename);
171 if (!current_consensus) {
172 if (!named_server_map)
173 named_server_map = strmap_new();
174 if (!unnamed_server_map)
175 unnamed_server_map = strmap_new();
178 update_certificate_downloads(time(NULL));
180 routers_update_all_from_networkstatus(time(NULL), 3);
181 update_microdescs_from_networkstatus(time(NULL));
183 return 0;
186 /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
187 STATIC void
188 vote_routerstatus_free(vote_routerstatus_t *rs)
190 vote_microdesc_hash_t *h, *next;
191 if (!rs)
192 return;
193 tor_free(rs->version);
194 tor_free(rs->status.exitsummary);
195 for (h = rs->microdesc; h; h = next) {
196 tor_free(h->microdesc_hash_line);
197 next = h->next;
198 tor_free(h);
200 tor_free(rs);
203 /** Free all storage held by the routerstatus object <b>rs</b>. */
204 void
205 routerstatus_free(routerstatus_t *rs)
207 if (!rs)
208 return;
209 tor_free(rs->exitsummary);
210 tor_free(rs);
213 /** Free all storage held in <b>sig</b> */
214 void
215 document_signature_free(document_signature_t *sig)
217 tor_free(sig->signature);
218 tor_free(sig);
221 /** Return a newly allocated copy of <b>sig</b> */
222 document_signature_t *
223 document_signature_dup(const document_signature_t *sig)
225 document_signature_t *r = tor_memdup(sig, sizeof(document_signature_t));
226 if (r->signature)
227 r->signature = tor_memdup(sig->signature, sig->signature_len);
228 return r;
231 /** Free all storage held in <b>ns</b>. */
232 void
233 networkstatus_vote_free(networkstatus_t *ns)
235 if (!ns)
236 return;
238 tor_free(ns->client_versions);
239 tor_free(ns->server_versions);
240 if (ns->known_flags) {
241 SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
242 smartlist_free(ns->known_flags);
244 if (ns->weight_params) {
245 SMARTLIST_FOREACH(ns->weight_params, char *, c, tor_free(c));
246 smartlist_free(ns->weight_params);
248 if (ns->net_params) {
249 SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
250 smartlist_free(ns->net_params);
252 if (ns->supported_methods) {
253 SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
254 smartlist_free(ns->supported_methods);
256 if (ns->voters) {
257 SMARTLIST_FOREACH_BEGIN(ns->voters, networkstatus_voter_info_t *, voter) {
258 tor_free(voter->nickname);
259 tor_free(voter->address);
260 tor_free(voter->contact);
261 if (voter->sigs) {
262 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
263 document_signature_free(sig));
264 smartlist_free(voter->sigs);
266 tor_free(voter);
267 } SMARTLIST_FOREACH_END(voter);
268 smartlist_free(ns->voters);
270 authority_cert_free(ns->cert);
272 if (ns->routerstatus_list) {
273 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
274 SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
275 vote_routerstatus_free(rs));
276 } else {
277 SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
278 routerstatus_free(rs));
281 smartlist_free(ns->routerstatus_list);
284 digestmap_free(ns->desc_digest_map, NULL);
286 memwipe(ns, 11, sizeof(*ns));
287 tor_free(ns);
290 /** Return the voter info from <b>vote</b> for the voter whose identity digest
291 * is <b>identity</b>, or NULL if no such voter is associated with
292 * <b>vote</b>. */
293 networkstatus_voter_info_t *
294 networkstatus_get_voter_by_id(networkstatus_t *vote,
295 const char *identity)
297 if (!vote || !vote->voters)
298 return NULL;
299 SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
300 if (fast_memeq(voter->identity_digest, identity, DIGEST_LEN))
301 return voter);
302 return NULL;
305 /** Check whether the signature <b>sig</b> is correctly signed with the
306 * signing key in <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
307 * signing key; otherwise set the good_signature or bad_signature flag on
308 * <b>voter</b>, and return 0. */
310 networkstatus_check_document_signature(const networkstatus_t *consensus,
311 document_signature_t *sig,
312 const authority_cert_t *cert)
314 char key_digest[DIGEST_LEN];
315 const int dlen = sig->alg == DIGEST_SHA1 ? DIGEST_LEN : DIGEST256_LEN;
316 char *signed_digest;
317 size_t signed_digest_len;
319 if (crypto_pk_get_digest(cert->signing_key, key_digest)<0)
320 return -1;
321 if (tor_memneq(sig->signing_key_digest, key_digest, DIGEST_LEN) ||
322 tor_memneq(sig->identity_digest, cert->cache_info.identity_digest,
323 DIGEST_LEN))
324 return -1;
326 if (authority_cert_is_blacklisted(cert)) {
327 /* We implement blacklisting for authority signing keys by treating
328 * all their signatures as always bad. That way we don't get into
329 * crazy loops of dropping and re-fetching signatures. */
330 log_warn(LD_DIR, "Ignoring a consensus signature made with deprecated"
331 " signing key %s",
332 hex_str(cert->signing_key_digest, DIGEST_LEN));
333 sig->bad_signature = 1;
334 return 0;
337 signed_digest_len = crypto_pk_keysize(cert->signing_key);
338 signed_digest = tor_malloc(signed_digest_len);
339 if (crypto_pk_public_checksig(cert->signing_key,
340 signed_digest,
341 signed_digest_len,
342 sig->signature,
343 sig->signature_len) < dlen ||
344 tor_memneq(signed_digest, consensus->digests.d[sig->alg], dlen)) {
345 log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
346 sig->bad_signature = 1;
347 } else {
348 sig->good_signature = 1;
350 tor_free(signed_digest);
351 return 0;
354 /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
355 * as-yet-unchecked signature on <b>consensus</b>. Return 1 if there is a
356 * signature from every recognized authority on it, 0 if there are
357 * enough good signatures from recognized authorities on it, -1 if we might
358 * get enough good signatures by fetching missing certificates, and -2
359 * otherwise. Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
360 * about every problem; if warn is at least 1, warn only if we can't get
361 * enough signatures; if warn is negative, log nothing at all. */
363 networkstatus_check_consensus_signature(networkstatus_t *consensus,
364 int warn)
366 int n_good = 0;
367 int n_missing_key = 0, n_dl_failed_key = 0;
368 int n_bad = 0;
369 int n_unknown = 0;
370 int n_no_signature = 0;
371 int n_v3_authorities = get_n_authorities(V3_DIRINFO);
372 int n_required = n_v3_authorities/2 + 1;
373 smartlist_t *list_good = smartlist_new();
374 smartlist_t *list_no_signature = smartlist_new();
375 smartlist_t *need_certs_from = smartlist_new();
376 smartlist_t *unrecognized = smartlist_new();
377 smartlist_t *missing_authorities = smartlist_new();
378 int severity;
379 time_t now = time(NULL);
381 tor_assert(consensus->type == NS_TYPE_CONSENSUS);
383 SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *,
384 voter) {
385 int good_here = 0;
386 int bad_here = 0;
387 int unknown_here = 0;
388 int missing_key_here = 0, dl_failed_key_here = 0;
389 SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
390 if (!sig->good_signature && !sig->bad_signature &&
391 sig->signature) {
392 /* we can try to check the signature. */
393 int is_v3_auth = trusteddirserver_get_by_v3_auth_digest(
394 sig->identity_digest) != NULL;
395 authority_cert_t *cert =
396 authority_cert_get_by_digests(sig->identity_digest,
397 sig->signing_key_digest);
398 tor_assert(tor_memeq(sig->identity_digest, voter->identity_digest,
399 DIGEST_LEN));
401 if (!is_v3_auth) {
402 smartlist_add(unrecognized, voter);
403 ++unknown_here;
404 continue;
405 } else if (!cert || cert->expires < now) {
406 smartlist_add(need_certs_from, voter);
407 ++missing_key_here;
408 if (authority_cert_dl_looks_uncertain(sig->identity_digest))
409 ++dl_failed_key_here;
410 continue;
412 if (networkstatus_check_document_signature(consensus, sig, cert) < 0) {
413 smartlist_add(need_certs_from, voter);
414 ++missing_key_here;
415 if (authority_cert_dl_looks_uncertain(sig->identity_digest))
416 ++dl_failed_key_here;
417 continue;
420 if (sig->good_signature)
421 ++good_here;
422 else if (sig->bad_signature)
423 ++bad_here;
424 } SMARTLIST_FOREACH_END(sig);
426 if (good_here) {
427 ++n_good;
428 smartlist_add(list_good, voter->nickname);
429 } else if (bad_here) {
430 ++n_bad;
431 } else if (missing_key_here) {
432 ++n_missing_key;
433 if (dl_failed_key_here)
434 ++n_dl_failed_key;
435 } else if (unknown_here) {
436 ++n_unknown;
437 } else {
438 ++n_no_signature;
439 smartlist_add(list_no_signature, voter->nickname);
441 } SMARTLIST_FOREACH_END(voter);
443 /* Now see whether we're missing any voters entirely. */
444 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
445 dir_server_t *, ds,
447 if ((ds->type & V3_DIRINFO) &&
448 !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
449 smartlist_add(missing_authorities, ds);
452 if (warn > 1 || (warn >= 0 &&
453 (n_good + n_missing_key - n_dl_failed_key < n_required))) {
454 severity = LOG_WARN;
455 } else {
456 severity = LOG_INFO;
459 if (warn >= 0) {
460 SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
462 tor_log(severity, LD_DIR, "Consensus includes unrecognized authority "
463 "'%s' at %s:%d (contact %s; identity %s)",
464 voter->nickname, voter->address, (int)voter->dir_port,
465 voter->contact?voter->contact:"n/a",
466 hex_str(voter->identity_digest, DIGEST_LEN));
468 SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
470 tor_log(severity, LD_DIR, "Looks like we need to download a new "
471 "certificate from authority '%s' at %s:%d (contact %s; "
472 "identity %s)",
473 voter->nickname, voter->address, (int)voter->dir_port,
474 voter->contact?voter->contact:"n/a",
475 hex_str(voter->identity_digest, DIGEST_LEN));
477 SMARTLIST_FOREACH(missing_authorities, dir_server_t *, ds,
479 tor_log(severity, LD_DIR, "Consensus does not include configured "
480 "authority '%s' at %s:%d (identity %s)",
481 ds->nickname, ds->address, (int)ds->dir_port,
482 hex_str(ds->v3_identity_digest, DIGEST_LEN));
485 char *joined;
486 smartlist_t *sl = smartlist_new();
487 char *tmp = smartlist_join_strings(list_good, " ", 0, NULL);
488 smartlist_add_asprintf(sl,
489 "A consensus needs %d good signatures from recognized "
490 "authorities for us to accept it. This one has %d (%s).",
491 n_required, n_good, tmp);
492 tor_free(tmp);
493 if (n_no_signature) {
494 tmp = smartlist_join_strings(list_no_signature, " ", 0, NULL);
495 smartlist_add_asprintf(sl,
496 "%d (%s) of the authorities we know didn't sign it.",
497 n_no_signature, tmp);
498 tor_free(tmp);
500 if (n_unknown) {
501 smartlist_add_asprintf(sl,
502 "It has %d signatures from authorities we don't "
503 "recognize.", n_unknown);
505 if (n_bad) {
506 smartlist_add_asprintf(sl, "%d of the signatures on it didn't verify "
507 "correctly.", n_bad);
509 if (n_missing_key) {
510 smartlist_add_asprintf(sl,
511 "We were unable to check %d of the signatures, "
512 "because we were missing the keys.", n_missing_key);
514 joined = smartlist_join_strings(sl, " ", 0, NULL);
515 tor_log(severity, LD_DIR, "%s", joined);
516 tor_free(joined);
517 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
518 smartlist_free(sl);
522 smartlist_free(list_good);
523 smartlist_free(list_no_signature);
524 smartlist_free(unrecognized);
525 smartlist_free(need_certs_from);
526 smartlist_free(missing_authorities);
528 if (n_good == n_v3_authorities)
529 return 1;
530 else if (n_good >= n_required)
531 return 0;
532 else if (n_good + n_missing_key >= n_required)
533 return -1;
534 else
535 return -2;
538 /** How far in the future do we allow a network-status to get before removing
539 * it? (seconds) */
540 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
542 /** Helper for bsearching a list of routerstatus_t pointers: compare a
543 * digest in the key to the identity digest of a routerstatus_t. */
545 compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
547 const char *key = _key;
548 const routerstatus_t *rs = *_member;
549 return tor_memcmp(key, rs->identity_digest, DIGEST_LEN);
552 /** Helper for bsearching a list of routerstatus_t pointers: compare a
553 * digest in the key to the identity digest of a routerstatus_t. */
555 compare_digest_to_vote_routerstatus_entry(const void *_key,
556 const void **_member)
558 const char *key = _key;
559 const vote_routerstatus_t *vrs = *_member;
560 return tor_memcmp(key, vrs->status.identity_digest, DIGEST_LEN);
563 /** As networkstatus_find_entry, but do not return a const pointer */
564 routerstatus_t *
565 networkstatus_vote_find_mutable_entry(networkstatus_t *ns, const char *digest)
567 return smartlist_bsearch(ns->routerstatus_list, digest,
568 compare_digest_to_routerstatus_entry);
571 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
572 * NULL if none was found. */
573 const routerstatus_t *
574 networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
576 return networkstatus_vote_find_mutable_entry(ns, digest);
579 /*XXXX MOVE make this static once functions are moved into this file. */
580 /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
581 * <b>digest</b>. Return value and set *<b>found_out</b> as for
582 * smartlist_bsearch_idx(). */
584 networkstatus_vote_find_entry_idx(networkstatus_t *ns,
585 const char *digest, int *found_out)
587 return smartlist_bsearch_idx(ns->routerstatus_list, digest,
588 compare_digest_to_routerstatus_entry,
589 found_out);
592 /** As router_get_consensus_status_by_descriptor_digest, but does not return
593 * a const pointer. */
594 routerstatus_t *
595 router_get_mutable_consensus_status_by_descriptor_digest(
596 networkstatus_t *consensus,
597 const char *digest)
599 if (!consensus)
600 consensus = current_consensus;
601 if (!consensus)
602 return NULL;
603 if (!consensus->desc_digest_map) {
604 digestmap_t *m = consensus->desc_digest_map = digestmap_new();
605 SMARTLIST_FOREACH(consensus->routerstatus_list,
606 routerstatus_t *, rs,
608 digestmap_set(m, rs->descriptor_digest, rs);
611 return digestmap_get(consensus->desc_digest_map, digest);
614 /** Return the consensus view of the status of the router whose current
615 * <i>descriptor</i> digest in <b>consensus</b> is <b>digest</b>, or NULL if
616 * no such router is known. */
617 const routerstatus_t *
618 router_get_consensus_status_by_descriptor_digest(networkstatus_t *consensus,
619 const char *digest)
621 return router_get_mutable_consensus_status_by_descriptor_digest(
622 consensus, digest);
625 /** Given the digest of a router descriptor, return its current download
626 * status, or NULL if the digest is unrecognized. */
627 download_status_t *
628 router_get_dl_status_by_descriptor_digest(const char *d)
630 routerstatus_t *rs;
631 if (!current_ns_consensus)
632 return NULL;
633 if ((rs = router_get_mutable_consensus_status_by_descriptor_digest(
634 current_ns_consensus, d)))
635 return &rs->dl_status;
637 return NULL;
640 /** As router_get_consensus_status_by_id, but do not return a const pointer */
641 routerstatus_t *
642 router_get_mutable_consensus_status_by_id(const char *digest)
644 if (!current_consensus)
645 return NULL;
646 return smartlist_bsearch(current_consensus->routerstatus_list, digest,
647 compare_digest_to_routerstatus_entry);
650 /** Return the consensus view of the status of the router whose identity
651 * digest is <b>digest</b>, or NULL if we don't know about any such router. */
652 const routerstatus_t *
653 router_get_consensus_status_by_id(const char *digest)
655 return router_get_mutable_consensus_status_by_id(digest);
658 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
659 * the corresponding routerstatus_t, or NULL if none exists. Warn the
660 * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
661 * nickname, but the Named flag isn't set for that router. */
662 const routerstatus_t *
663 router_get_consensus_status_by_nickname(const char *nickname,
664 int warn_if_unnamed)
666 const node_t *node = node_get_by_nickname(nickname, warn_if_unnamed);
667 if (node)
668 return node->rs;
669 else
670 return NULL;
673 /** Return the identity digest that's mapped to officially by
674 * <b>nickname</b>. */
675 const char *
676 networkstatus_get_router_digest_by_nickname(const char *nickname)
678 if (!named_server_map)
679 return NULL;
680 return strmap_get_lc(named_server_map, nickname);
683 /** Return true iff <b>nickname</b> is disallowed from being the nickname
684 * of any server. */
686 networkstatus_nickname_is_unnamed(const char *nickname)
688 if (!unnamed_server_map)
689 return 0;
690 return strmap_get_lc(unnamed_server_map, nickname) != NULL;
693 /** How frequently do directory authorities re-download fresh networkstatus
694 * documents? */
695 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
697 /** How frequently do non-authority directory caches re-download fresh
698 * networkstatus documents? */
699 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
701 /** Return true iff, given the options listed in <b>options</b>, <b>flavor</b>
702 * is the flavor of a consensus networkstatus that we would like to fetch. */
703 static int
704 we_want_to_fetch_flavor(const or_options_t *options, int flavor)
706 if (flavor < 0 || flavor > N_CONSENSUS_FLAVORS) {
707 /* This flavor is crazy; we don't want it */
708 /*XXXX handle unrecognized flavors later */
709 return 0;
711 if (authdir_mode_v3(options) || directory_caches_dir_info(options)) {
712 /* We want to serve all flavors to others, regardless if we would use
713 * it ourselves. */
714 return 1;
716 if (options->FetchUselessDescriptors) {
717 /* In order to get all descriptors, we need to fetch all consensuses. */
718 return 1;
720 /* Otherwise, we want the flavor only if we want to use it to build
721 * circuits. */
722 return flavor == usable_consensus_flavor();
725 /** How long will we hang onto a possibly live consensus for which we're
726 * fetching certs before we check whether there is a better one? */
727 #define DELAY_WHILE_FETCHING_CERTS (20*60)
729 /** If we want to download a fresh consensus, launch a new download as
730 * appropriate. */
731 static void
732 update_consensus_networkstatus_downloads(time_t now)
734 int i;
735 const or_options_t *options = get_options();
737 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
738 /* XXXX need some way to download unknown flavors if we are caching. */
739 const char *resource;
740 consensus_waiting_for_certs_t *waiting;
741 networkstatus_t *c;
743 if (! we_want_to_fetch_flavor(options, i))
744 continue;
746 c = networkstatus_get_latest_consensus_by_flavor(i);
747 if (! (c && c->valid_after <= now && now <= c->valid_until)) {
748 /* No live consensus? Get one now!*/
749 time_to_download_next_consensus[i] = now;
752 if (time_to_download_next_consensus[i] > now)
753 continue; /* Wait until the current consensus is older. */
755 resource = networkstatus_get_flavor_name(i);
757 if (!download_status_is_ready(&consensus_dl_status[i], now,
758 options->TestingConsensusMaxDownloadTries))
759 continue; /* We failed downloading a consensus too recently. */
760 if (connection_dir_get_by_purpose_and_resource(
761 DIR_PURPOSE_FETCH_CONSENSUS, resource))
762 continue; /* There's an in-progress download.*/
764 waiting = &consensus_waiting_for_certs[i];
765 if (waiting->consensus) {
766 /* XXXX make sure this doesn't delay sane downloads. */
767 if (waiting->set_at + DELAY_WHILE_FETCHING_CERTS > now) {
768 continue; /* We're still getting certs for this one. */
769 } else {
770 if (!waiting->dl_failed) {
771 download_status_failed(&consensus_dl_status[i], 0);
772 waiting->dl_failed=1;
777 log_info(LD_DIR, "Launching %s networkstatus consensus download.",
778 networkstatus_get_flavor_name(i));
780 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
781 ROUTER_PURPOSE_GENERAL, resource,
782 PDS_RETRY_IF_NO_SERVERS);
786 /** Called when an attempt to download a consensus fails: note that the
787 * failure occurred, and possibly retry. */
788 void
789 networkstatus_consensus_download_failed(int status_code, const char *flavname)
791 int flav = networkstatus_parse_flavor_name(flavname);
792 if (flav >= 0) {
793 tor_assert(flav < N_CONSENSUS_FLAVORS);
794 /* XXXX handle unrecognized flavors */
795 download_status_failed(&consensus_dl_status[flav], status_code);
796 /* Retry immediately, if appropriate. */
797 update_consensus_networkstatus_downloads(time(NULL));
801 /** How long do we (as a cache) wait after a consensus becomes non-fresh
802 * before trying to fetch another? */
803 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
805 /** Update the time at which we'll consider replacing the current
806 * consensus of flavor <b>flav</b> */
807 static void
808 update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
810 const or_options_t *options = get_options();
811 networkstatus_t *c = networkstatus_get_latest_consensus_by_flavor(flav);
812 const char *flavor = networkstatus_get_flavor_name(flav);
813 if (! we_want_to_fetch_flavor(get_options(), flav))
814 return;
816 if (c && c->valid_after <= now && now <= c->valid_until) {
817 long dl_interval;
818 long interval = c->fresh_until - c->valid_after;
819 long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
820 time_t start;
822 if (min_sec_before_caching > interval/16) {
823 /* Usually we allow 2-minutes slop factor in case clocks get
824 desynchronized a little. If we're on a private network with
825 a crazy-fast voting interval, though, 2 minutes may be too
826 much. */
827 min_sec_before_caching = interval/16;
830 if (directory_fetches_dir_info_early(options)) {
831 /* We want to cache the next one at some point after this one
832 * is no longer fresh... */
833 start = (time_t)(c->fresh_until + min_sec_before_caching);
834 /* Some clients may need the consensus sooner than others. */
835 if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
836 dl_interval = 60;
837 if (min_sec_before_caching + dl_interval > interval)
838 dl_interval = interval/2;
839 } else {
840 /* But only in the first half-interval after that. */
841 dl_interval = interval/2;
843 } else {
844 /* We're an ordinary client or a bridge. Give all the caches enough
845 * time to download the consensus. */
846 start = (time_t)(c->fresh_until + (interval*3)/4);
847 /* But download the next one well before this one is expired. */
848 dl_interval = ((c->valid_until - start) * 7 )/ 8;
850 /* If we're a bridge user, make use of the numbers we just computed
851 * to choose the rest of the interval *after* them. */
852 if (directory_fetches_dir_info_later(options)) {
853 /* Give all the *clients* enough time to download the consensus. */
854 start = (time_t)(start + dl_interval + min_sec_before_caching);
855 /* But try to get it before ours actually expires. */
856 dl_interval = (c->valid_until - start) - min_sec_before_caching;
859 if (dl_interval < 1)
860 dl_interval = 1;
861 /* We must not try to replace c while it's still fresh: */
862 tor_assert(c->fresh_until < start);
863 /* We must download the next one before c is invalid: */
864 tor_assert(start+dl_interval < c->valid_until);
865 time_to_download_next_consensus[flav] =
866 start + crypto_rand_int((int)dl_interval);
868 char tbuf1[ISO_TIME_LEN+1];
869 char tbuf2[ISO_TIME_LEN+1];
870 char tbuf3[ISO_TIME_LEN+1];
871 format_local_iso_time(tbuf1, c->fresh_until);
872 format_local_iso_time(tbuf2, c->valid_until);
873 format_local_iso_time(tbuf3, time_to_download_next_consensus[flav]);
874 log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
875 "will expire at %s; fetching the next one at %s.",
876 flavor, (c->fresh_until > now) ? "will be" : "was",
877 tbuf1, tbuf2, tbuf3);
879 } else {
880 time_to_download_next_consensus[flav] = now;
881 log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
882 flavor);
886 /** Update the time at which we'll consider replacing the current
887 * consensus of flavor 'flavor' */
888 void
889 update_consensus_networkstatus_fetch_time(time_t now)
891 int i;
892 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
893 if (we_want_to_fetch_flavor(get_options(), i))
894 update_consensus_networkstatus_fetch_time_impl(now, i);
898 /** Return 1 if there's a reason we shouldn't try any directory
899 * fetches yet (e.g. we demand bridges and none are yet known).
900 * Else return 0.
902 * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
903 * to an explanation of why directory fetches are delayed. (If we
904 * return 0, we set msg_out to NULL.)
907 should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
909 if (msg_out) {
910 *msg_out = NULL;
913 if (options->DisableNetwork) {
914 if (msg_out) {
915 *msg_out = "DisableNetwork is set.";
917 log_info(LD_DIR, "Delaying dir fetches (DisableNetwork is set)");
918 return 1;
921 if (options->UseBridges) {
922 if (!any_bridge_descriptors_known()) {
923 if (msg_out) {
924 *msg_out = "No running bridges";
926 log_info(LD_DIR, "Delaying dir fetches (no running bridges known)");
927 return 1;
930 if (pt_proxies_configuration_pending()) {
931 if (msg_out) {
932 *msg_out = "Pluggable transport proxies still configuring";
934 log_info(LD_DIR, "Delaying dir fetches (pt proxies still configuring)");
935 return 1;
939 return 0;
942 /** Launch requests for networkstatus documents and authority certificates as
943 * appropriate. */
944 void
945 update_networkstatus_downloads(time_t now)
947 const or_options_t *options = get_options();
948 if (should_delay_dir_fetches(options, NULL))
949 return;
950 update_consensus_networkstatus_downloads(now);
951 update_certificate_downloads(now);
954 /** Launch requests as appropriate for missing directory authority
955 * certificates. */
956 void
957 update_certificate_downloads(time_t now)
959 int i;
960 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
961 if (consensus_waiting_for_certs[i].consensus)
962 authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
963 now);
966 if (current_ns_consensus)
967 authority_certs_fetch_missing(current_ns_consensus, now);
968 if (current_md_consensus)
969 authority_certs_fetch_missing(current_md_consensus, now);
972 /** Return 1 if we have a consensus but we don't have enough certificates
973 * to start using it yet. */
975 consensus_is_waiting_for_certs(void)
977 return consensus_waiting_for_certs[usable_consensus_flavor()].consensus
978 ? 1 : 0;
981 /** Return the most recent consensus that we have downloaded, or NULL if we
982 * don't have one. */
983 networkstatus_t *
984 networkstatus_get_latest_consensus(void)
986 return current_consensus;
989 /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
990 * if we don't have one. */
991 networkstatus_t *
992 networkstatus_get_latest_consensus_by_flavor(consensus_flavor_t f)
994 if (f == FLAV_NS)
995 return current_ns_consensus;
996 else if (f == FLAV_MICRODESC)
997 return current_md_consensus;
998 else {
999 tor_assert(0);
1000 return NULL;
1004 /** Return the most recent consensus that we have downloaded, or NULL if it is
1005 * no longer live. */
1006 networkstatus_t *
1007 networkstatus_get_live_consensus(time_t now)
1009 if (current_consensus &&
1010 current_consensus->valid_after <= now &&
1011 now <= current_consensus->valid_until)
1012 return current_consensus;
1013 else
1014 return NULL;
1017 /* XXXX remove this in favor of get_live_consensus. But actually,
1018 * leave something like it for bridge users, who need to not totally
1019 * lose if they spend a while fetching a new consensus. */
1020 /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
1021 * consensuses. */
1022 networkstatus_t *
1023 networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
1025 #define REASONABLY_LIVE_TIME (24*60*60)
1026 networkstatus_t *consensus =
1027 networkstatus_get_latest_consensus_by_flavor(flavor);
1028 if (consensus &&
1029 consensus->valid_after <= now &&
1030 now <= consensus->valid_until+REASONABLY_LIVE_TIME)
1031 return consensus;
1032 else
1033 return NULL;
1036 /** Given two router status entries for the same router identity, return 1 if
1037 * if the contents have changed between them. Otherwise, return 0. */
1038 static int
1039 routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
1041 tor_assert(tor_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN));
1043 return strcmp(a->nickname, b->nickname) ||
1044 fast_memneq(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
1045 a->addr != b->addr ||
1046 a->or_port != b->or_port ||
1047 a->dir_port != b->dir_port ||
1048 a->is_authority != b->is_authority ||
1049 a->is_exit != b->is_exit ||
1050 a->is_stable != b->is_stable ||
1051 a->is_fast != b->is_fast ||
1052 a->is_flagged_running != b->is_flagged_running ||
1053 a->is_named != b->is_named ||
1054 a->is_unnamed != b->is_unnamed ||
1055 a->is_valid != b->is_valid ||
1056 a->is_possible_guard != b->is_possible_guard ||
1057 a->is_bad_exit != b->is_bad_exit ||
1058 a->is_bad_directory != b->is_bad_directory ||
1059 a->is_hs_dir != b->is_hs_dir ||
1060 a->version_known != b->version_known;
1063 /** Notify controllers of any router status entries that changed between
1064 * <b>old_c</b> and <b>new_c</b>. */
1065 static void
1066 notify_control_networkstatus_changed(const networkstatus_t *old_c,
1067 const networkstatus_t *new_c)
1069 smartlist_t *changed;
1070 if (old_c == new_c)
1071 return;
1073 /* tell the controller exactly which relays are still listed, as well
1074 * as what they're listed as */
1075 control_event_newconsensus(new_c);
1077 if (!control_event_is_interesting(EVENT_NS))
1078 return;
1080 if (!old_c) {
1081 control_event_networkstatus_changed(new_c->routerstatus_list);
1082 return;
1084 changed = smartlist_new();
1086 SMARTLIST_FOREACH_JOIN(
1087 old_c->routerstatus_list, const routerstatus_t *, rs_old,
1088 new_c->routerstatus_list, const routerstatus_t *, rs_new,
1089 tor_memcmp(rs_old->identity_digest,
1090 rs_new->identity_digest, DIGEST_LEN),
1091 smartlist_add(changed, (void*) rs_new)) {
1092 if (routerstatus_has_changed(rs_old, rs_new))
1093 smartlist_add(changed, (void*)rs_new);
1094 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1096 control_event_networkstatus_changed(changed);
1097 smartlist_free(changed);
1100 /** Copy all the ancillary information (like router download status and so on)
1101 * from <b>old_c</b> to <b>new_c</b>. */
1102 static void
1103 networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
1104 const networkstatus_t *old_c)
1106 if (old_c == new_c)
1107 return;
1108 if (!old_c || !smartlist_len(old_c->routerstatus_list))
1109 return;
1111 SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
1112 new_c->routerstatus_list, routerstatus_t *, rs_new,
1113 tor_memcmp(rs_old->identity_digest,
1114 rs_new->identity_digest, DIGEST_LEN),
1115 STMT_NIL) {
1116 /* Okay, so we're looking at the same identity. */
1117 rs_new->last_dir_503_at = rs_old->last_dir_503_at;
1119 if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
1120 DIGEST_LEN)) {
1121 /* And the same descriptor too! */
1122 memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
1124 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1127 /** Try to replace the current cached v3 networkstatus with the one in
1128 * <b>consensus</b>. If we don't have enough certificates to validate it,
1129 * store it in consensus_waiting_for_certs and launch a certificate fetch.
1131 * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
1132 * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
1133 * already received, but we were waiting for certificates on it. If flags &
1134 * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
1135 * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
1136 * consensus, even if it comes from many days in the past.
1138 * Return 0 on success, <0 on failure. On failure, caller should increment
1139 * the failure count as appropriate.
1141 * We return -1 for mild failures that don't need to be reported to the
1142 * user, and -2 for more serious problems.
1145 networkstatus_set_current_consensus(const char *consensus,
1146 const char *flavor,
1147 unsigned flags)
1149 networkstatus_t *c=NULL;
1150 int r, result = -1;
1151 time_t now = time(NULL);
1152 const or_options_t *options = get_options();
1153 char *unverified_fname = NULL, *consensus_fname = NULL;
1154 int flav = networkstatus_parse_flavor_name(flavor);
1155 const unsigned from_cache = flags & NSSET_FROM_CACHE;
1156 const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
1157 const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
1158 const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
1159 const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
1160 const digests_t *current_digests = NULL;
1161 consensus_waiting_for_certs_t *waiting = NULL;
1162 time_t current_valid_after = 0;
1163 int free_consensus = 1; /* Free 'c' at the end of the function */
1164 int old_ewma_enabled;
1166 if (flav < 0) {
1167 /* XXXX we don't handle unrecognized flavors yet. */
1168 log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
1169 return -2;
1172 /* Make sure it's parseable. */
1173 c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
1174 if (!c) {
1175 log_warn(LD_DIR, "Unable to parse networkstatus consensus");
1176 result = -2;
1177 goto done;
1180 if ((int)c->flavor != flav) {
1181 /* This wasn't the flavor we thought we were getting. */
1182 if (require_flavor) {
1183 log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
1184 networkstatus_get_flavor_name(c->flavor), flavor);
1185 goto done;
1187 flav = c->flavor;
1188 flavor = networkstatus_get_flavor_name(flav);
1191 if (flav != usable_consensus_flavor() &&
1192 !directory_caches_dir_info(options)) {
1193 /* This consensus is totally boring to us: we won't use it, and we won't
1194 * serve it. Drop it. */
1195 goto done;
1198 if (from_cache && !accept_obsolete &&
1199 c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
1200 log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
1201 goto done;
1204 if (!strcmp(flavor, "ns")) {
1205 consensus_fname = get_datadir_fname("cached-consensus");
1206 unverified_fname = get_datadir_fname("unverified-consensus");
1207 if (current_ns_consensus) {
1208 current_digests = &current_ns_consensus->digests;
1209 current_valid_after = current_ns_consensus->valid_after;
1211 } else if (!strcmp(flavor, "microdesc")) {
1212 consensus_fname = get_datadir_fname("cached-microdesc-consensus");
1213 unverified_fname = get_datadir_fname("unverified-microdesc-consensus");
1214 if (current_md_consensus) {
1215 current_digests = &current_md_consensus->digests;
1216 current_valid_after = current_md_consensus->valid_after;
1218 } else {
1219 cached_dir_t *cur;
1220 char buf[128];
1221 tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
1222 consensus_fname = get_datadir_fname(buf);
1223 tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
1224 unverified_fname = get_datadir_fname(buf);
1225 cur = dirserv_get_consensus(flavor);
1226 if (cur) {
1227 current_digests = &cur->digests;
1228 current_valid_after = cur->published;
1232 if (current_digests &&
1233 tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
1234 /* We already have this one. That's a failure. */
1235 log_info(LD_DIR, "Got a %s consensus we already have", flavor);
1236 goto done;
1239 if (current_valid_after && c->valid_after <= current_valid_after) {
1240 /* We have a newer one. There's no point in accepting this one,
1241 * even if it's great. */
1242 log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
1243 flavor);
1244 goto done;
1247 /* Make sure it's signed enough. */
1248 if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
1249 if (r == -1) {
1250 /* Okay, so it _might_ be signed enough if we get more certificates. */
1251 if (!was_waiting_for_certs) {
1252 log_info(LD_DIR,
1253 "Not enough certificates to check networkstatus consensus");
1255 if (!current_valid_after ||
1256 c->valid_after > current_valid_after) {
1257 waiting = &consensus_waiting_for_certs[flav];
1258 networkstatus_vote_free(waiting->consensus);
1259 tor_free(waiting->body);
1260 waiting->consensus = c;
1261 free_consensus = 0;
1262 waiting->body = tor_strdup(consensus);
1263 waiting->set_at = now;
1264 waiting->dl_failed = 0;
1265 if (!from_cache) {
1266 write_str_to_file(unverified_fname, consensus, 0);
1268 if (dl_certs)
1269 authority_certs_fetch_missing(c, now);
1270 /* This case is not a success or a failure until we get the certs
1271 * or fail to get the certs. */
1272 result = 0;
1273 } else {
1274 /* Even if we had enough signatures, we'd never use this as the
1275 * latest consensus. */
1276 if (was_waiting_for_certs && from_cache)
1277 if (unlink(unverified_fname) != 0) {
1278 log_warn(LD_FS,
1279 "Failed to unlink %s: %s",
1280 unverified_fname, strerror(errno));
1283 goto done;
1284 } else {
1285 /* This can never be signed enough: Kill it. */
1286 if (!was_waiting_for_certs) {
1287 log_warn(LD_DIR, "Not enough good signatures on networkstatus "
1288 "consensus");
1289 result = -2;
1291 if (was_waiting_for_certs && (r < -1) && from_cache) {
1292 if (unlink(unverified_fname) != 0) {
1293 log_warn(LD_FS,
1294 "Failed to unlink %s: %s",
1295 unverified_fname, strerror(errno));
1298 goto done;
1302 if (!from_cache && flav == usable_consensus_flavor())
1303 control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
1305 /* Are we missing any certificates at all? */
1306 if (r != 1 && dl_certs)
1307 authority_certs_fetch_missing(c, now);
1309 if (flav == usable_consensus_flavor()) {
1310 notify_control_networkstatus_changed(current_consensus, c);
1312 if (flav == FLAV_NS) {
1313 if (current_ns_consensus) {
1314 networkstatus_copy_old_consensus_info(c, current_ns_consensus);
1315 networkstatus_vote_free(current_ns_consensus);
1316 /* Defensive programming : we should set current_consensus very soon,
1317 * but we're about to call some stuff in the meantime, and leaving this
1318 * dangling pointer around has proven to be trouble. */
1319 current_ns_consensus = NULL;
1321 current_ns_consensus = c;
1322 free_consensus = 0; /* avoid free */
1323 } else if (flav == FLAV_MICRODESC) {
1324 if (current_md_consensus) {
1325 networkstatus_copy_old_consensus_info(c, current_md_consensus);
1326 networkstatus_vote_free(current_md_consensus);
1327 /* more defensive programming */
1328 current_md_consensus = NULL;
1330 current_md_consensus = c;
1331 free_consensus = 0; /* avoid free */
1334 waiting = &consensus_waiting_for_certs[flav];
1335 if (waiting->consensus &&
1336 waiting->consensus->valid_after <= c->valid_after) {
1337 networkstatus_vote_free(waiting->consensus);
1338 waiting->consensus = NULL;
1339 if (consensus != waiting->body)
1340 tor_free(waiting->body);
1341 else
1342 waiting->body = NULL;
1343 waiting->set_at = 0;
1344 waiting->dl_failed = 0;
1345 if (unlink(unverified_fname) != 0) {
1346 log_warn(LD_FS,
1347 "Failed to unlink %s: %s",
1348 unverified_fname, strerror(errno));
1352 /* Reset the failure count only if this consensus is actually valid. */
1353 if (c->valid_after <= now && now <= c->valid_until) {
1354 download_status_reset(&consensus_dl_status[flav]);
1355 } else {
1356 if (!from_cache)
1357 download_status_failed(&consensus_dl_status[flav], 0);
1360 if (flav == usable_consensus_flavor()) {
1361 /* XXXXNM Microdescs: needs a non-ns variant. ???? NM*/
1362 update_consensus_networkstatus_fetch_time(now);
1364 nodelist_set_consensus(current_consensus);
1366 dirvote_recalculate_timing(options, now);
1367 routerstatus_list_update_named_server_map();
1369 /* Update ewma and adjust policy if needed; first cache the old value */
1370 old_ewma_enabled = cell_ewma_enabled();
1371 /* Change the cell EWMA settings */
1372 cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
1373 /* If we just enabled ewma, set the cmux policy on all active channels */
1374 if (cell_ewma_enabled() && !old_ewma_enabled) {
1375 channel_set_cmux_policy_everywhere(&ewma_policy);
1376 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1377 /* Turn it off everywhere */
1378 channel_set_cmux_policy_everywhere(NULL);
1381 /* XXXX024 this call might be unnecessary here: can changing the
1382 * current consensus really alter our view of any OR's rate limits? */
1383 connection_or_update_token_buckets(get_connection_array(), options);
1385 circuit_build_times_new_consensus_params(get_circuit_build_times_mutable(),
1386 current_consensus);
1389 if (directory_caches_dir_info(options)) {
1390 dirserv_set_cached_consensus_networkstatus(consensus,
1391 flavor,
1392 &c->digests,
1393 c->valid_after);
1396 if (!from_cache) {
1397 write_str_to_file(consensus_fname, consensus, 0);
1400 /** If a consensus appears more than this many seconds before its declared
1401 * valid-after time, declare that our clock is skewed. */
1402 #define EARLY_CONSENSUS_NOTICE_SKEW 60
1404 if (now < c->valid_after - EARLY_CONSENSUS_NOTICE_SKEW) {
1405 char tbuf[ISO_TIME_LEN+1];
1406 char dbuf[64];
1407 long delta = now - c->valid_after;
1408 format_iso_time(tbuf, c->valid_after);
1409 format_time_interval(dbuf, sizeof(dbuf), delta);
1410 log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
1411 "consensus network status document (%s UTC). Tor needs an "
1412 "accurate clock to work correctly. Please check your time and "
1413 "date settings!", dbuf, tbuf);
1414 control_event_general_status(LOG_WARN,
1415 "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
1418 router_dir_info_changed();
1420 result = 0;
1421 done:
1422 if (free_consensus)
1423 networkstatus_vote_free(c);
1424 tor_free(consensus_fname);
1425 tor_free(unverified_fname);
1426 return result;
1429 /** Called when we have gotten more certificates: see whether we can
1430 * now verify a pending consensus. */
1431 void
1432 networkstatus_note_certs_arrived(void)
1434 int i;
1435 for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
1436 consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
1437 if (!waiting->consensus)
1438 continue;
1439 if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
1440 char *waiting_body = waiting->body;
1441 if (!networkstatus_set_current_consensus(
1442 waiting_body,
1443 networkstatus_get_flavor_name(i),
1444 NSSET_WAS_WAITING_FOR_CERTS)) {
1445 tor_free(waiting_body);
1451 /** If the network-status list has changed since the last time we called this
1452 * function, update the status of every routerinfo from the network-status
1453 * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
1454 * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
1456 void
1457 routers_update_all_from_networkstatus(time_t now, int dir_version)
1459 routerlist_t *rl = router_get_routerlist();
1460 networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,
1461 FLAV_NS);
1463 if (!consensus || dir_version < 3) /* nothing more we should do */
1464 return;
1466 /* calls router_dir_info_changed() when it's done -- more routers
1467 * might be up or down now, which might affect whether there's enough
1468 * directory info. */
1469 routers_update_status_from_consensus_networkstatus(rl->routers, 0);
1471 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
1472 ri->cache_info.routerlist_index = ri_sl_idx);
1473 if (rl->old_routers)
1474 signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
1476 if (!have_warned_about_old_version) {
1477 int is_server = server_mode(get_options());
1478 version_status_t status;
1479 const char *recommended = is_server ?
1480 consensus->server_versions : consensus->client_versions;
1481 status = tor_version_is_obsolete(VERSION, recommended);
1483 if (status == VS_RECOMMENDED) {
1484 log_info(LD_GENERAL, "The directory authorities say my version is ok.");
1485 } else if (status == VS_EMPTY) {
1486 log_info(LD_GENERAL,
1487 "The directory authorities don't recommend any versions.");
1488 } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
1489 if (!have_warned_about_new_version) {
1490 log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
1491 "recommended version%s, according to the directory "
1492 "authorities. Recommended versions are: %s",
1493 VERSION,
1494 status == VS_NEW_IN_SERIES ? " in its series" : "",
1495 recommended);
1496 have_warned_about_new_version = 1;
1497 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
1498 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
1499 VERSION, "NEW", recommended);
1501 } else {
1502 log_warn(LD_GENERAL, "Please upgrade! "
1503 "This version of Tor (%s) is %s, according to the directory "
1504 "authorities. Recommended versions are: %s",
1505 VERSION,
1506 status == VS_OLD ? "obsolete" : "not recommended",
1507 recommended);
1508 have_warned_about_old_version = 1;
1509 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
1510 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
1511 VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
1512 recommended);
1517 /** Update our view of the list of named servers from the most recently
1518 * retrieved networkstatus consensus. */
1519 static void
1520 routerstatus_list_update_named_server_map(void)
1522 if (!current_consensus)
1523 return;
1525 strmap_free(named_server_map, tor_free_);
1526 named_server_map = strmap_new();
1527 strmap_free(unnamed_server_map, NULL);
1528 unnamed_server_map = strmap_new();
1529 SMARTLIST_FOREACH_BEGIN(current_consensus->routerstatus_list,
1530 const routerstatus_t *, rs) {
1531 if (rs->is_named) {
1532 strmap_set_lc(named_server_map, rs->nickname,
1533 tor_memdup(rs->identity_digest, DIGEST_LEN));
1535 if (rs->is_unnamed) {
1536 strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
1538 } SMARTLIST_FOREACH_END(rs);
1541 /** Given a list <b>routers</b> of routerinfo_t *, update each status field
1542 * according to our current consensus networkstatus. May re-order
1543 * <b>routers</b>. */
1544 void
1545 routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
1546 int reset_failures)
1548 const or_options_t *options = get_options();
1549 int authdir = authdir_mode_v3(options);
1550 networkstatus_t *ns = current_consensus;
1551 if (!ns || !smartlist_len(ns->routerstatus_list))
1552 return;
1554 routers_sort_by_identity(routers);
1556 SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
1557 routers, routerinfo_t *, router,
1558 tor_memcmp(rs->identity_digest,
1559 router->cache_info.identity_digest, DIGEST_LEN),
1561 }) {
1562 /* Is it the same descriptor, or only the same identity? */
1563 if (tor_memeq(router->cache_info.signed_descriptor_digest,
1564 rs->descriptor_digest, DIGEST_LEN)) {
1565 if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
1566 router->cache_info.last_listed_as_valid_until = ns->valid_until;
1569 if (authdir) {
1570 /* If we _are_ an authority, we should check whether this router
1571 * is one that will cause us to need a reachability test. */
1572 routerinfo_t *old_router =
1573 router_get_mutable_by_digest(router->cache_info.identity_digest);
1574 if (old_router != router) {
1575 router->needs_retest_if_added =
1576 dirserv_should_launch_reachability_test(router, old_router);
1579 if (reset_failures) {
1580 download_status_reset(&rs->dl_status);
1582 } SMARTLIST_FOREACH_JOIN_END(rs, router);
1584 router_dir_info_changed();
1587 /** Given a list of signed_descriptor_t, update their fields (mainly, when
1588 * they were last listed) from the most recent consensus. */
1589 void
1590 signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
1592 networkstatus_t *ns = current_ns_consensus;
1593 if (!ns)
1594 return;
1596 if (!ns->desc_digest_map) {
1597 char dummy[DIGEST_LEN];
1598 /* instantiates the digest map. */
1599 memset(dummy, 0, sizeof(dummy));
1600 router_get_consensus_status_by_descriptor_digest(ns, dummy);
1602 SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
1604 const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
1605 d->signed_descriptor_digest);
1606 if (rs) {
1607 if (ns->valid_until > d->last_listed_as_valid_until)
1608 d->last_listed_as_valid_until = ns->valid_until;
1613 /** Generate networkstatus lines for a single routerstatus_t object, and
1614 * return the result in a newly allocated string. Used only by controller
1615 * interface (for now.) */
1616 char *
1617 networkstatus_getinfo_helper_single(const routerstatus_t *rs)
1619 return routerstatus_format_entry(rs, NULL, NS_CONTROL_PORT, NULL);
1622 /** Alloc and return a string describing routerstatuses for the most
1623 * recent info of each router we know about that is of purpose
1624 * <b>purpose_string</b>. Return NULL if unrecognized purpose.
1626 * Right now this function is oriented toward listing bridges (you
1627 * shouldn't use this for general-purpose routers, since those
1628 * should be listed from the consensus, not from the routers list). */
1629 char *
1630 networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
1632 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
1633 char *answer;
1634 routerlist_t *rl = router_get_routerlist();
1635 smartlist_t *statuses;
1636 uint8_t purpose = router_purpose_from_string(purpose_string);
1637 routerstatus_t rs;
1638 int bridge_auth = authdir_mode_bridge(get_options());
1640 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
1641 log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
1642 purpose_string);
1643 return NULL;
1646 statuses = smartlist_new();
1647 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
1648 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
1649 if (!node)
1650 continue;
1651 if (ri->cache_info.published_on < cutoff)
1652 continue;
1653 if (ri->purpose != purpose)
1654 continue;
1655 if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
1656 dirserv_set_router_is_running(ri, now);
1657 /* then generate and write out status lines for each of them */
1658 set_routerstatus_from_routerinfo(&rs, node, ri, now, 0, 0, 0, 0);
1659 smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
1660 } SMARTLIST_FOREACH_END(ri);
1662 answer = smartlist_join_strings(statuses, "", 0, NULL);
1663 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
1664 smartlist_free(statuses);
1665 return answer;
1668 /** Write out router status entries for all our bridge descriptors. */
1669 void
1670 networkstatus_dump_bridge_status_to_file(time_t now)
1672 char *status = networkstatus_getinfo_by_purpose("bridge", now);
1673 const or_options_t *options = get_options();
1674 char *fname = NULL;
1675 char *thresholds = NULL, *thresholds_and_status = NULL;
1676 routerlist_t *rl = router_get_routerlist();
1677 dirserv_compute_bridge_flag_thresholds(rl);
1678 thresholds = dirserv_get_flag_thresholds_line();
1679 tor_asprintf(&thresholds_and_status, "flag-thresholds %s\n%s",
1680 thresholds, status);
1681 tor_asprintf(&fname, "%s"PATH_SEPARATOR"networkstatus-bridges",
1682 options->DataDirectory);
1683 write_str_to_file(fname,thresholds_and_status,0);
1684 tor_free(thresholds);
1685 tor_free(thresholds_and_status);
1686 tor_free(fname);
1687 tor_free(status);
1690 /* DOCDOC get_net_param_from_list */
1691 static int32_t
1692 get_net_param_from_list(smartlist_t *net_params, const char *param_name,
1693 int32_t default_val, int32_t min_val, int32_t max_val)
1695 int32_t res = default_val;
1696 size_t name_len = strlen(param_name);
1698 tor_assert(max_val > min_val);
1699 tor_assert(min_val <= default_val);
1700 tor_assert(max_val >= default_val);
1702 SMARTLIST_FOREACH_BEGIN(net_params, const char *, p) {
1703 if (!strcmpstart(p, param_name) && p[name_len] == '=') {
1704 int ok=0;
1705 long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
1706 INT32_MAX, &ok, NULL);
1707 if (ok) {
1708 res = (int32_t) v;
1709 break;
1712 } SMARTLIST_FOREACH_END(p);
1714 if (res < min_val) {
1715 log_warn(LD_DIR, "Consensus parameter %s is too small. Got %d, raising to "
1716 "%d.", param_name, res, min_val);
1717 res = min_val;
1718 } else if (res > max_val) {
1719 log_warn(LD_DIR, "Consensus parameter %s is too large. Got %d, capping to "
1720 "%d.", param_name, res, max_val);
1721 res = max_val;
1724 return res;
1727 /** Return the value of a integer parameter from the networkstatus <b>ns</b>
1728 * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
1729 * latest consensus ourselves. Return <b>default_val</b> if no latest
1730 * consensus, or if it has no parameter called <b>param_name</b>.
1731 * Make sure the value parsed from the consensus is at least
1732 * <b>min_val</b> and at most <b>max_val</b> and raise/cap the parsed value
1733 * if necessary. */
1734 int32_t
1735 networkstatus_get_param(const networkstatus_t *ns, const char *param_name,
1736 int32_t default_val, int32_t min_val, int32_t max_val)
1738 if (!ns) /* if they pass in null, go find it ourselves */
1739 ns = networkstatus_get_latest_consensus();
1741 if (!ns || !ns->net_params)
1742 return default_val;
1744 return get_net_param_from_list(ns->net_params, param_name,
1745 default_val, min_val, max_val);
1749 * Retrieve the consensus parameter that governs the
1750 * fixed-point precision of our network balancing 'bandwidth-weights'
1751 * (which are themselves integer consensus values). We divide them
1752 * by this value and ensure they never exceed this value.
1755 networkstatus_get_weight_scale_param(networkstatus_t *ns)
1757 return networkstatus_get_param(ns, "bwweightscale",
1758 BW_WEIGHT_SCALE,
1759 BW_MIN_WEIGHT_SCALE,
1760 BW_MAX_WEIGHT_SCALE);
1763 /** Return the value of a integer bw weight parameter from the networkstatus
1764 * <b>ns</b> whose name is <b>weight_name</b>. If <b>ns</b> is NULL, try
1765 * loading the latest consensus ourselves. Return <b>default_val</b> if no
1766 * latest consensus, or if it has no parameter called <b>weight_name</b>. */
1767 int32_t
1768 networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name,
1769 int32_t default_val)
1771 int32_t param;
1772 int max;
1773 if (!ns) /* if they pass in null, go find it ourselves */
1774 ns = networkstatus_get_latest_consensus();
1776 if (!ns || !ns->weight_params)
1777 return default_val;
1779 max = networkstatus_get_weight_scale_param(ns);
1780 param = get_net_param_from_list(ns->weight_params, weight_name,
1781 default_val, -1,
1782 BW_MAX_WEIGHT_SCALE);
1783 if (param > max) {
1784 log_warn(LD_DIR, "Value of consensus weight %s was too large, capping "
1785 "to %d", weight_name, max);
1786 param = max;
1788 return param;
1791 /** Return the name of the consensus flavor <b>flav</b> as used to identify
1792 * the flavor in directory documents. */
1793 const char *
1794 networkstatus_get_flavor_name(consensus_flavor_t flav)
1796 switch (flav) {
1797 case FLAV_NS:
1798 return "ns";
1799 case FLAV_MICRODESC:
1800 return "microdesc";
1801 default:
1802 tor_fragile_assert();
1803 return "??";
1807 /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
1808 * or -1 if the flavor is not recognized. */
1810 networkstatus_parse_flavor_name(const char *flavname)
1812 if (!strcmp(flavname, "ns"))
1813 return FLAV_NS;
1814 else if (!strcmp(flavname, "microdesc"))
1815 return FLAV_MICRODESC;
1816 else
1817 return -1;
1820 /** Return 0 if this routerstatus is obsolete, too new, isn't
1821 * running, or otherwise not a descriptor that we would make any
1822 * use of even if we had it. Else return 1. */
1824 client_would_use_router(const routerstatus_t *rs, time_t now,
1825 const or_options_t *options)
1827 if (!rs->is_flagged_running && !options->FetchUselessDescriptors) {
1828 /* If we had this router descriptor, we wouldn't even bother using it.
1829 * But, if we want to have a complete list, fetch it anyway. */
1830 return 0;
1832 if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
1833 > now) {
1834 /* Most caches probably don't have this descriptor yet. */
1835 return 0;
1837 if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
1838 /* We'd drop it immediately for being too old. */
1839 return 0;
1841 return 1;
1844 /** If <b>question</b> is a string beginning with "ns/" in a format the
1845 * control interface expects for a GETINFO question, set *<b>answer</b> to a
1846 * newly-allocated string containing networkstatus lines for the appropriate
1847 * ORs. Return 0 on success, -1 on unrecognized question format. */
1849 getinfo_helper_networkstatus(control_connection_t *conn,
1850 const char *question, char **answer,
1851 const char **errmsg)
1853 const routerstatus_t *status;
1854 (void) conn;
1856 if (!current_consensus) {
1857 *answer = tor_strdup("");
1858 return 0;
1861 if (!strcmp(question, "ns/all")) {
1862 smartlist_t *statuses = smartlist_new();
1863 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
1864 const routerstatus_t *, rs,
1866 smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
1868 *answer = smartlist_join_strings(statuses, "", 0, NULL);
1869 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
1870 smartlist_free(statuses);
1871 return 0;
1872 } else if (!strcmpstart(question, "ns/id/")) {
1873 char d[DIGEST_LEN];
1874 const char *q = question + 6;
1875 if (*q == '$')
1876 ++q;
1878 if (base16_decode(d, DIGEST_LEN, q, strlen(q))) {
1879 *errmsg = "Data not decodeable as hex";
1880 return -1;
1882 status = router_get_consensus_status_by_id(d);
1883 } else if (!strcmpstart(question, "ns/name/")) {
1884 status = router_get_consensus_status_by_nickname(question+8, 0);
1885 } else if (!strcmpstart(question, "ns/purpose/")) {
1886 *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
1887 return *answer ? 0 : -1;
1888 } else {
1889 return 0;
1892 if (status)
1893 *answer = networkstatus_getinfo_helper_single(status);
1894 return 0;
1897 /** Free all storage held locally in this module. */
1898 void
1899 networkstatus_free_all(void)
1901 int i;
1902 networkstatus_vote_free(current_ns_consensus);
1903 networkstatus_vote_free(current_md_consensus);
1904 current_md_consensus = current_ns_consensus = NULL;
1906 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
1907 consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
1908 if (waiting->consensus) {
1909 networkstatus_vote_free(waiting->consensus);
1910 waiting->consensus = NULL;
1912 tor_free(waiting->body);
1915 strmap_free(named_server_map, tor_free_);
1916 strmap_free(unnamed_server_map, NULL);