general formatting / whitespace / typo fixes
[tor.git] / src / or / networkstatus.c
bloba9a6227cd607155adeac77ab546ca81f4ec8fb2a
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file networkstatus.c
9 * \brief Functions and structures for handling networkstatus documents as a
10 * client or as a directory cache.
12 * A consensus networkstatus object is created by the directory
13 * authorities. It authenticates a set of network parameters--most
14 * importantly, the list of all the relays in the network. This list
15 * of relays is represented as an array of routerstatus_t objects.
17 * There are currently two flavors of consensus. With the older "NS"
18 * flavor, each relay is associated with a digest of its router
19 * descriptor. Tor instances that use this consensus keep the list of
20 * router descriptors as routerinfo_t objects stored and managed in
21 * routerlist.c. With the newer "microdesc" flavor, each relay is
22 * associated with a digest of the microdescriptor that the authorities
23 * made for it. These are stored and managed in microdesc.c. Information
24 * about the router is divided between the the networkstatus and the
25 * microdescriptor according to the general rule that microdescriptors
26 * should hold information that changes much less frequently than the
27 * information in the networkstatus.
29 * Modern clients use microdescriptor networkstatuses. Directory caches
30 * need to keep both kinds of networkstatus document, so they can serve them.
32 * This module manages fetching, holding, storing, updating, and
33 * validating networkstatus objects. The download-and-validate process
34 * is slightly complicated by the fact that the keys you need to
35 * validate a consensus are stored in the authority certificates, which
36 * you might not have yet when you download the consensus.
39 #define NETWORKSTATUS_PRIVATE
40 #include "or.h"
41 #include "bridges.h"
42 #include "channel.h"
43 #include "circuitmux.h"
44 #include "circuitmux_ewma.h"
45 #include "circuitstats.h"
46 #include "config.h"
47 #include "connection.h"
48 #include "connection_or.h"
49 #include "consdiffmgr.h"
50 #include "control.h"
51 #include "directory.h"
52 #include "dirserv.h"
53 #include "dirvote.h"
54 #include "entrynodes.h"
55 #include "main.h"
56 #include "microdesc.h"
57 #include "networkstatus.h"
58 #include "nodelist.h"
59 #include "protover.h"
60 #include "relay.h"
61 #include "router.h"
62 #include "routerlist.h"
63 #include "routerparse.h"
64 #include "shared_random.h"
65 #include "transports.h"
66 #include "torcert.h"
67 #include "channelpadding.h"
69 /** Map from lowercase nickname to identity digest of named server, if any. */
70 static strmap_t *named_server_map = NULL;
71 /** Map from lowercase nickname to (void*)1 for all names that are listed
72 * as unnamed for some server in the consensus. */
73 static strmap_t *unnamed_server_map = NULL;
75 /** Most recently received and validated v3 "ns"-flavored consensus network
76 * status. */
77 STATIC networkstatus_t *current_ns_consensus = NULL;
79 /** Most recently received and validated v3 "microdesc"-flavored consensus
80 * network status. */
81 STATIC networkstatus_t *current_md_consensus = NULL;
83 /** A v3 consensus networkstatus that we've received, but which we don't
84 * have enough certificates to be happy about. */
85 typedef struct consensus_waiting_for_certs_t {
86 /** The consensus itself. */
87 networkstatus_t *consensus;
88 /** The encoded version of the consensus, nul-terminated. */
89 char *body;
90 /** When did we set the current value of consensus_waiting_for_certs? If
91 * this is too recent, we shouldn't try to fetch a new consensus for a
92 * little while, to give ourselves time to get certificates for this one. */
93 time_t set_at;
94 /** Set to 1 if we've been holding on to it for so long we should maybe
95 * treat it as being bad. */
96 int dl_failed;
97 } consensus_waiting_for_certs_t;
99 /** An array, for each flavor of consensus we might want, of consensuses that
100 * we have downloaded, but which we cannot verify due to having insufficient
101 * authority certificates. */
102 static consensus_waiting_for_certs_t
103 consensus_waiting_for_certs[N_CONSENSUS_FLAVORS];
105 /** A time before which we shouldn't try to replace the current consensus:
106 * this will be at some point after the next consensus becomes valid, but
107 * before the current consensus becomes invalid. */
108 static time_t time_to_download_next_consensus[N_CONSENSUS_FLAVORS];
109 /** Download status for the current consensus networkstatus. */
110 static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS] =
112 { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
113 DL_SCHED_INCREMENT_FAILURE, DL_SCHED_RANDOM_EXPONENTIAL, 0, 0 },
114 { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
115 DL_SCHED_INCREMENT_FAILURE, DL_SCHED_RANDOM_EXPONENTIAL, 0, 0 },
118 #define N_CONSENSUS_BOOTSTRAP_SCHEDULES 2
119 #define CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY 0
120 #define CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER 1
122 /* Using DL_SCHED_INCREMENT_ATTEMPT on these schedules means that
123 * download_status_increment_failure won't increment these entries.
124 * However, any bootstrap connection failures that occur after we have
125 * a valid consensus will count against the failure counts on the non-bootstrap
126 * schedules. There should only be one of these, as all the others will have
127 * been cancelled. (This doesn't seem to be a significant issue.) */
128 static download_status_t
129 consensus_bootstrap_dl_status[N_CONSENSUS_BOOTSTRAP_SCHEDULES] =
131 { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_AUTHORITY,
132 DL_SCHED_INCREMENT_ATTEMPT, DL_SCHED_RANDOM_EXPONENTIAL, 0, 0 },
133 /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
134 { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
135 DL_SCHED_INCREMENT_ATTEMPT, DL_SCHED_RANDOM_EXPONENTIAL, 0, 0 },
138 /** True iff we have logged a warning about this OR's version being older than
139 * listed by the authorities. */
140 static int have_warned_about_old_version = 0;
141 /** True iff we have logged a warning about this OR's version being newer than
142 * listed by the authorities. */
143 static int have_warned_about_new_version = 0;
145 static void routerstatus_list_update_named_server_map(void);
146 static void update_consensus_bootstrap_multiple_downloads(
147 time_t now,
148 const or_options_t *options);
149 static int networkstatus_check_required_protocols(const networkstatus_t *ns,
150 int client_mode,
151 char **warning_out);
153 /** Forget that we've warned about anything networkstatus-related, so we will
154 * give fresh warnings if the same behavior happens again. */
155 void
156 networkstatus_reset_warnings(void)
158 SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
159 node->name_lookup_warned = 0);
161 have_warned_about_old_version = 0;
162 have_warned_about_new_version = 0;
165 /** Reset the descriptor download failure count on all networkstatus docs, so
166 * that we can retry any long-failed documents immediately.
168 void
169 networkstatus_reset_download_failures(void)
171 int i;
173 log_debug(LD_GENERAL,
174 "In networkstatus_reset_download_failures()");
176 for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
177 download_status_reset(&consensus_dl_status[i]);
179 for (i=0; i < N_CONSENSUS_BOOTSTRAP_SCHEDULES; ++i)
180 download_status_reset(&consensus_bootstrap_dl_status[i]);
184 * Read and and return the cached consensus of type <b>flavorname</b>. If
185 * <b>unverified</b> is false, get the one we haven't verified. Return NULL if
186 * the file isn't there. */
187 static char *
188 networkstatus_read_cached_consensus_impl(int flav,
189 const char *flavorname,
190 int unverified_consensus)
192 char buf[128];
193 const char *prefix;
194 if (unverified_consensus) {
195 prefix = "unverified";
196 } else {
197 prefix = "cached";
199 if (flav == FLAV_NS) {
200 tor_snprintf(buf, sizeof(buf), "%s-consensus", prefix);
201 } else {
202 tor_snprintf(buf, sizeof(buf), "%s-%s-consensus", prefix, flavorname);
205 char *filename = get_datadir_fname(buf);
206 char *result = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
207 tor_free(filename);
208 return result;
211 /** Return a new string containing the current cached consensus of flavor
212 * <b>flavorname</b>. */
213 char *
214 networkstatus_read_cached_consensus(const char *flavorname)
216 int flav = networkstatus_parse_flavor_name(flavorname);
217 if (flav < 0)
218 return NULL;
219 return networkstatus_read_cached_consensus_impl(flav, flavorname, 0);
222 /** Read every cached v3 consensus networkstatus from the disk. */
224 router_reload_consensus_networkstatus(void)
226 const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
227 int flav;
229 /* FFFF Suppress warnings if cached consensus is bad? */
230 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
231 const char *flavor = networkstatus_get_flavor_name(flav);
232 char *s = networkstatus_read_cached_consensus_impl(flav, flavor, 0);
233 if (s) {
234 if (networkstatus_set_current_consensus(s, flavor, flags, NULL) < -1) {
235 log_warn(LD_FS, "Couldn't load consensus %s networkstatus from cache",
236 flavor);
238 tor_free(s);
241 s = networkstatus_read_cached_consensus_impl(flav, flavor, 1);
242 if (s) {
243 if (networkstatus_set_current_consensus(s, flavor,
244 flags|NSSET_WAS_WAITING_FOR_CERTS,
245 NULL)) {
246 log_info(LD_FS, "Couldn't load unverified consensus %s networkstatus "
247 "from cache", flavor);
249 tor_free(s);
253 if (!networkstatus_get_latest_consensus()) {
254 if (!named_server_map)
255 named_server_map = strmap_new();
256 if (!unnamed_server_map)
257 unnamed_server_map = strmap_new();
260 update_certificate_downloads(time(NULL));
262 routers_update_all_from_networkstatus(time(NULL), 3);
263 update_microdescs_from_networkstatus(time(NULL));
265 return 0;
268 /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
269 void
270 vote_routerstatus_free(vote_routerstatus_t *rs)
272 vote_microdesc_hash_t *h, *next;
273 if (!rs)
274 return;
275 tor_free(rs->version);
276 tor_free(rs->protocols);
277 tor_free(rs->status.exitsummary);
278 for (h = rs->microdesc; h; h = next) {
279 tor_free(h->microdesc_hash_line);
280 next = h->next;
281 tor_free(h);
283 tor_free(rs);
286 /** Free all storage held by the routerstatus object <b>rs</b>. */
287 void
288 routerstatus_free(routerstatus_t *rs)
290 if (!rs)
291 return;
292 tor_free(rs->exitsummary);
293 tor_free(rs);
296 /** Free all storage held in <b>sig</b> */
297 void
298 document_signature_free(document_signature_t *sig)
300 tor_free(sig->signature);
301 tor_free(sig);
304 /** Return a newly allocated copy of <b>sig</b> */
305 document_signature_t *
306 document_signature_dup(const document_signature_t *sig)
308 document_signature_t *r = tor_memdup(sig, sizeof(document_signature_t));
309 if (r->signature)
310 r->signature = tor_memdup(sig->signature, sig->signature_len);
311 return r;
314 /** Free all storage held in <b>ns</b>. */
315 void
316 networkstatus_vote_free(networkstatus_t *ns)
318 if (!ns)
319 return;
321 tor_free(ns->client_versions);
322 tor_free(ns->server_versions);
323 tor_free(ns->recommended_client_protocols);
324 tor_free(ns->recommended_relay_protocols);
325 tor_free(ns->required_client_protocols);
326 tor_free(ns->required_relay_protocols);
328 if (ns->known_flags) {
329 SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
330 smartlist_free(ns->known_flags);
332 if (ns->weight_params) {
333 SMARTLIST_FOREACH(ns->weight_params, char *, c, tor_free(c));
334 smartlist_free(ns->weight_params);
336 if (ns->net_params) {
337 SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
338 smartlist_free(ns->net_params);
340 if (ns->supported_methods) {
341 SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
342 smartlist_free(ns->supported_methods);
344 if (ns->package_lines) {
345 SMARTLIST_FOREACH(ns->package_lines, char *, c, tor_free(c));
346 smartlist_free(ns->package_lines);
348 if (ns->voters) {
349 SMARTLIST_FOREACH_BEGIN(ns->voters, networkstatus_voter_info_t *, voter) {
350 tor_free(voter->nickname);
351 tor_free(voter->address);
352 tor_free(voter->contact);
353 if (voter->sigs) {
354 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
355 document_signature_free(sig));
356 smartlist_free(voter->sigs);
358 tor_free(voter);
359 } SMARTLIST_FOREACH_END(voter);
360 smartlist_free(ns->voters);
362 authority_cert_free(ns->cert);
364 if (ns->routerstatus_list) {
365 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
366 SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
367 vote_routerstatus_free(rs));
368 } else {
369 SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
370 routerstatus_free(rs));
373 smartlist_free(ns->routerstatus_list);
376 digestmap_free(ns->desc_digest_map, NULL);
378 if (ns->sr_info.commits) {
379 SMARTLIST_FOREACH(ns->sr_info.commits, sr_commit_t *, c,
380 sr_commit_free(c));
381 smartlist_free(ns->sr_info.commits);
383 tor_free(ns->sr_info.previous_srv);
384 tor_free(ns->sr_info.current_srv);
386 memwipe(ns, 11, sizeof(*ns));
387 tor_free(ns);
390 /** Return the voter info from <b>vote</b> for the voter whose identity digest
391 * is <b>identity</b>, or NULL if no such voter is associated with
392 * <b>vote</b>. */
393 networkstatus_voter_info_t *
394 networkstatus_get_voter_by_id(networkstatus_t *vote,
395 const char *identity)
397 if (!vote || !vote->voters)
398 return NULL;
399 SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
400 if (fast_memeq(voter->identity_digest, identity, DIGEST_LEN))
401 return voter);
402 return NULL;
405 /** Check whether the signature <b>sig</b> is correctly signed with the
406 * signing key in <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
407 * signing key; otherwise set the good_signature or bad_signature flag on
408 * <b>voter</b>, and return 0. */
410 networkstatus_check_document_signature(const networkstatus_t *consensus,
411 document_signature_t *sig,
412 const authority_cert_t *cert)
414 char key_digest[DIGEST_LEN];
415 const int dlen = sig->alg == DIGEST_SHA1 ? DIGEST_LEN : DIGEST256_LEN;
416 char *signed_digest;
417 size_t signed_digest_len;
419 if (crypto_pk_get_digest(cert->signing_key, key_digest)<0)
420 return -1;
421 if (tor_memneq(sig->signing_key_digest, key_digest, DIGEST_LEN) ||
422 tor_memneq(sig->identity_digest, cert->cache_info.identity_digest,
423 DIGEST_LEN))
424 return -1;
426 if (authority_cert_is_blacklisted(cert)) {
427 /* We implement blacklisting for authority signing keys by treating
428 * all their signatures as always bad. That way we don't get into
429 * crazy loops of dropping and re-fetching signatures. */
430 log_warn(LD_DIR, "Ignoring a consensus signature made with deprecated"
431 " signing key %s",
432 hex_str(cert->signing_key_digest, DIGEST_LEN));
433 sig->bad_signature = 1;
434 return 0;
437 signed_digest_len = crypto_pk_keysize(cert->signing_key);
438 signed_digest = tor_malloc(signed_digest_len);
439 if (crypto_pk_public_checksig(cert->signing_key,
440 signed_digest,
441 signed_digest_len,
442 sig->signature,
443 sig->signature_len) < dlen ||
444 tor_memneq(signed_digest, consensus->digests.d[sig->alg], dlen)) {
445 log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
446 sig->bad_signature = 1;
447 } else {
448 sig->good_signature = 1;
450 tor_free(signed_digest);
451 return 0;
454 /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
455 * as-yet-unchecked signature on <b>consensus</b>. Return 1 if there is a
456 * signature from every recognized authority on it, 0 if there are
457 * enough good signatures from recognized authorities on it, -1 if we might
458 * get enough good signatures by fetching missing certificates, and -2
459 * otherwise. Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
460 * about every problem; if warn is at least 1, warn only if we can't get
461 * enough signatures; if warn is negative, log nothing at all. */
463 networkstatus_check_consensus_signature(networkstatus_t *consensus,
464 int warn)
466 int n_good = 0;
467 int n_missing_key = 0, n_dl_failed_key = 0;
468 int n_bad = 0;
469 int n_unknown = 0;
470 int n_no_signature = 0;
471 int n_v3_authorities = get_n_authorities(V3_DIRINFO);
472 int n_required = n_v3_authorities/2 + 1;
473 smartlist_t *list_good = smartlist_new();
474 smartlist_t *list_no_signature = smartlist_new();
475 smartlist_t *need_certs_from = smartlist_new();
476 smartlist_t *unrecognized = smartlist_new();
477 smartlist_t *missing_authorities = smartlist_new();
478 int severity;
479 time_t now = time(NULL);
481 tor_assert(consensus->type == NS_TYPE_CONSENSUS);
483 SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *,
484 voter) {
485 int good_here = 0;
486 int bad_here = 0;
487 int unknown_here = 0;
488 int missing_key_here = 0, dl_failed_key_here = 0;
489 SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
490 if (!sig->good_signature && !sig->bad_signature &&
491 sig->signature) {
492 /* we can try to check the signature. */
493 int is_v3_auth = trusteddirserver_get_by_v3_auth_digest(
494 sig->identity_digest) != NULL;
495 authority_cert_t *cert =
496 authority_cert_get_by_digests(sig->identity_digest,
497 sig->signing_key_digest);
498 tor_assert(tor_memeq(sig->identity_digest, voter->identity_digest,
499 DIGEST_LEN));
501 if (!is_v3_auth) {
502 smartlist_add(unrecognized, voter);
503 ++unknown_here;
504 continue;
505 } else if (!cert || cert->expires < now) {
506 smartlist_add(need_certs_from, voter);
507 ++missing_key_here;
508 if (authority_cert_dl_looks_uncertain(sig->identity_digest))
509 ++dl_failed_key_here;
510 continue;
512 if (networkstatus_check_document_signature(consensus, sig, cert) < 0) {
513 smartlist_add(need_certs_from, voter);
514 ++missing_key_here;
515 if (authority_cert_dl_looks_uncertain(sig->identity_digest))
516 ++dl_failed_key_here;
517 continue;
520 if (sig->good_signature)
521 ++good_here;
522 else if (sig->bad_signature)
523 ++bad_here;
524 } SMARTLIST_FOREACH_END(sig);
526 if (good_here) {
527 ++n_good;
528 smartlist_add(list_good, voter->nickname);
529 } else if (bad_here) {
530 ++n_bad;
531 } else if (missing_key_here) {
532 ++n_missing_key;
533 if (dl_failed_key_here)
534 ++n_dl_failed_key;
535 } else if (unknown_here) {
536 ++n_unknown;
537 } else {
538 ++n_no_signature;
539 smartlist_add(list_no_signature, voter->nickname);
541 } SMARTLIST_FOREACH_END(voter);
543 /* Now see whether we're missing any voters entirely. */
544 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
545 dir_server_t *, ds,
547 if ((ds->type & V3_DIRINFO) &&
548 !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
549 smartlist_add(missing_authorities, ds);
552 if (warn > 1 || (warn >= 0 &&
553 (n_good + n_missing_key - n_dl_failed_key < n_required))) {
554 severity = LOG_WARN;
555 } else {
556 severity = LOG_INFO;
559 if (warn >= 0) {
560 SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
562 tor_log(severity, LD_DIR, "Consensus includes unrecognized authority "
563 "'%s' at %s:%d (contact %s; identity %s)",
564 voter->nickname, voter->address, (int)voter->dir_port,
565 voter->contact?voter->contact:"n/a",
566 hex_str(voter->identity_digest, DIGEST_LEN));
568 SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
570 tor_log(severity, LD_DIR, "Looks like we need to download a new "
571 "certificate from authority '%s' at %s:%d (contact %s; "
572 "identity %s)",
573 voter->nickname, voter->address, (int)voter->dir_port,
574 voter->contact?voter->contact:"n/a",
575 hex_str(voter->identity_digest, DIGEST_LEN));
577 SMARTLIST_FOREACH(missing_authorities, dir_server_t *, ds,
579 tor_log(severity, LD_DIR, "Consensus does not include configured "
580 "authority '%s' at %s:%d (identity %s)",
581 ds->nickname, ds->address, (int)ds->dir_port,
582 hex_str(ds->v3_identity_digest, DIGEST_LEN));
585 char *joined;
586 smartlist_t *sl = smartlist_new();
587 char *tmp = smartlist_join_strings(list_good, " ", 0, NULL);
588 smartlist_add_asprintf(sl,
589 "A consensus needs %d good signatures from recognized "
590 "authorities for us to accept it. This one has %d (%s).",
591 n_required, n_good, tmp);
592 tor_free(tmp);
593 if (n_no_signature) {
594 tmp = smartlist_join_strings(list_no_signature, " ", 0, NULL);
595 smartlist_add_asprintf(sl,
596 "%d (%s) of the authorities we know didn't sign it.",
597 n_no_signature, tmp);
598 tor_free(tmp);
600 if (n_unknown) {
601 smartlist_add_asprintf(sl,
602 "It has %d signatures from authorities we don't "
603 "recognize.", n_unknown);
605 if (n_bad) {
606 smartlist_add_asprintf(sl, "%d of the signatures on it didn't verify "
607 "correctly.", n_bad);
609 if (n_missing_key) {
610 smartlist_add_asprintf(sl,
611 "We were unable to check %d of the signatures, "
612 "because we were missing the keys.", n_missing_key);
614 joined = smartlist_join_strings(sl, " ", 0, NULL);
615 tor_log(severity, LD_DIR, "%s", joined);
616 tor_free(joined);
617 SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
618 smartlist_free(sl);
622 smartlist_free(list_good);
623 smartlist_free(list_no_signature);
624 smartlist_free(unrecognized);
625 smartlist_free(need_certs_from);
626 smartlist_free(missing_authorities);
628 if (n_good == n_v3_authorities)
629 return 1;
630 else if (n_good >= n_required)
631 return 0;
632 else if (n_good + n_missing_key >= n_required)
633 return -1;
634 else
635 return -2;
638 /** How far in the future do we allow a network-status to get before removing
639 * it? (seconds) */
640 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
642 /** Helper for bsearching a list of routerstatus_t pointers: compare a
643 * digest in the key to the identity digest of a routerstatus_t. */
645 compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
647 const char *key = _key;
648 const routerstatus_t *rs = *_member;
649 return tor_memcmp(key, rs->identity_digest, DIGEST_LEN);
652 /** Helper for bsearching a list of routerstatus_t pointers: compare a
653 * digest in the key to the identity digest of a routerstatus_t. */
655 compare_digest_to_vote_routerstatus_entry(const void *_key,
656 const void **_member)
658 const char *key = _key;
659 const vote_routerstatus_t *vrs = *_member;
660 return tor_memcmp(key, vrs->status.identity_digest, DIGEST_LEN);
663 /** As networkstatus_find_entry, but do not return a const pointer */
664 routerstatus_t *
665 networkstatus_vote_find_mutable_entry(networkstatus_t *ns, const char *digest)
667 return smartlist_bsearch(ns->routerstatus_list, digest,
668 compare_digest_to_routerstatus_entry);
671 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
672 * NULL if none was found. */
673 const routerstatus_t *
674 networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
676 return networkstatus_vote_find_mutable_entry(ns, digest);
679 /*XXXX MOVE make this static once functions are moved into this file. */
680 /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
681 * <b>digest</b>. Return value and set *<b>found_out</b> as for
682 * smartlist_bsearch_idx(). */
684 networkstatus_vote_find_entry_idx(networkstatus_t *ns,
685 const char *digest, int *found_out)
687 return smartlist_bsearch_idx(ns->routerstatus_list, digest,
688 compare_digest_to_routerstatus_entry,
689 found_out);
692 /** As router_get_consensus_status_by_descriptor_digest, but does not return
693 * a const pointer. */
694 MOCK_IMPL(routerstatus_t *,
695 router_get_mutable_consensus_status_by_descriptor_digest,(
696 networkstatus_t *consensus,
697 const char *digest))
699 if (!consensus)
700 consensus = networkstatus_get_latest_consensus();
701 if (!consensus)
702 return NULL;
703 if (!consensus->desc_digest_map) {
704 digestmap_t *m = consensus->desc_digest_map = digestmap_new();
705 SMARTLIST_FOREACH(consensus->routerstatus_list,
706 routerstatus_t *, rs,
708 digestmap_set(m, rs->descriptor_digest, rs);
711 return digestmap_get(consensus->desc_digest_map, digest);
714 /** Return the consensus view of the status of the router whose current
715 * <i>descriptor</i> digest in <b>consensus</b> is <b>digest</b>, or NULL if
716 * no such router is known. */
717 const routerstatus_t *
718 router_get_consensus_status_by_descriptor_digest(networkstatus_t *consensus,
719 const char *digest)
721 return router_get_mutable_consensus_status_by_descriptor_digest(
722 consensus, digest);
725 /** Return a smartlist of all router descriptor digests in a consensus */
726 static smartlist_t *
727 router_get_descriptor_digests_in_consensus(networkstatus_t *consensus)
729 smartlist_t *result = smartlist_new();
730 digestmap_iter_t *i;
731 const char *digest;
732 void *rs;
733 char *digest_tmp;
735 for (i = digestmap_iter_init(consensus->desc_digest_map);
736 !(digestmap_iter_done(i));
737 i = digestmap_iter_next(consensus->desc_digest_map, i)) {
738 digestmap_iter_get(i, &digest, &rs);
739 digest_tmp = tor_malloc(DIGEST_LEN);
740 memcpy(digest_tmp, digest, DIGEST_LEN);
741 smartlist_add(result, digest_tmp);
744 return result;
747 /** Return a smartlist of all router descriptor digests in the current
748 * consensus */
749 MOCK_IMPL(smartlist_t *,
750 router_get_descriptor_digests,(void))
752 smartlist_t *result = NULL;
754 if (current_ns_consensus) {
755 result =
756 router_get_descriptor_digests_in_consensus(current_ns_consensus);
759 return result;
762 /** Given the digest of a router descriptor, return its current download
763 * status, or NULL if the digest is unrecognized. */
764 MOCK_IMPL(download_status_t *,
765 router_get_dl_status_by_descriptor_digest,(const char *d))
767 routerstatus_t *rs;
768 if (!current_ns_consensus)
769 return NULL;
770 if ((rs = router_get_mutable_consensus_status_by_descriptor_digest(
771 current_ns_consensus, d)))
772 return &rs->dl_status;
774 return NULL;
777 /** As router_get_consensus_status_by_id, but do not return a const pointer */
778 routerstatus_t *
779 router_get_mutable_consensus_status_by_id(const char *digest)
781 const networkstatus_t *ns = networkstatus_get_latest_consensus();
782 if (!ns)
783 return NULL;
784 smartlist_t *rslist = ns->routerstatus_list;
785 return smartlist_bsearch(rslist, digest,
786 compare_digest_to_routerstatus_entry);
789 /** Return the consensus view of the status of the router whose identity
790 * digest is <b>digest</b>, or NULL if we don't know about any such router. */
791 const routerstatus_t *
792 router_get_consensus_status_by_id(const char *digest)
794 return router_get_mutable_consensus_status_by_id(digest);
797 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
798 * the corresponding routerstatus_t, or NULL if none exists. Warn the
799 * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
800 * nickname, but the Named flag isn't set for that router. */
801 const routerstatus_t *
802 router_get_consensus_status_by_nickname(const char *nickname,
803 int warn_if_unnamed)
805 const node_t *node = node_get_by_nickname(nickname, warn_if_unnamed);
806 if (node)
807 return node->rs;
808 else
809 return NULL;
812 /** Return the identity digest that's mapped to officially by
813 * <b>nickname</b>. */
814 const char *
815 networkstatus_get_router_digest_by_nickname(const char *nickname)
817 if (!named_server_map)
818 return NULL;
819 return strmap_get_lc(named_server_map, nickname);
822 /** Return true iff <b>nickname</b> is disallowed from being the nickname
823 * of any server. */
825 networkstatus_nickname_is_unnamed(const char *nickname)
827 if (!unnamed_server_map)
828 return 0;
829 return strmap_get_lc(unnamed_server_map, nickname) != NULL;
832 /** How frequently do directory authorities re-download fresh networkstatus
833 * documents? */
834 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
836 /** How frequently do non-authority directory caches re-download fresh
837 * networkstatus documents? */
838 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
840 /** Return true iff, given the options listed in <b>options</b>, <b>flavor</b>
841 * is the flavor of a consensus networkstatus that we would like to fetch.
843 * For certificate fetches, use we_want_to_fetch_unknown_auth_certs, and
844 * for serving fetched documents, use directory_caches_dir_info. */
846 we_want_to_fetch_flavor(const or_options_t *options, int flavor)
848 if (flavor < 0 || flavor > N_CONSENSUS_FLAVORS) {
849 /* This flavor is crazy; we don't want it */
850 /*XXXX handle unrecognized flavors later */
851 return 0;
853 if (authdir_mode_v3(options) || directory_caches_dir_info(options)) {
854 /* We want to serve all flavors to others, regardless if we would use
855 * it ourselves. */
856 return 1;
858 if (options->FetchUselessDescriptors) {
859 /* In order to get all descriptors, we need to fetch all consensuses. */
860 return 1;
862 /* Otherwise, we want the flavor only if we want to use it to build
863 * circuits. */
864 return flavor == usable_consensus_flavor();
867 /** Return true iff, given the options listed in <b>options</b>, we would like
868 * to fetch and store unknown authority certificates.
870 * For consensus and descriptor fetches, use we_want_to_fetch_flavor, and
871 * for serving fetched certificates, use directory_caches_unknown_auth_certs.
874 we_want_to_fetch_unknown_auth_certs(const or_options_t *options)
876 if (authdir_mode_v3(options) ||
877 directory_caches_unknown_auth_certs((options))) {
878 /* We want to serve all certs to others, regardless if we would use
879 * them ourselves. */
880 return 1;
882 if (options->FetchUselessDescriptors) {
883 /* Unknown certificates are definitely useless. */
884 return 1;
886 /* Otherwise, don't fetch unknown certificates. */
887 return 0;
890 /** How long will we hang onto a possibly live consensus for which we're
891 * fetching certs before we check whether there is a better one? */
892 #define DELAY_WHILE_FETCHING_CERTS (20*60)
894 /** What is the minimum time we need to have waited fetching certs, before we
895 * increment the consensus download schedule on failure? */
896 #define MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE (1*60)
898 /* Check if a downloaded consensus flavor should still wait for certificates
899 * to download now. If we decide not to wait, check if enough time has passed
900 * to consider the certificate download failure a separate failure. If so,
901 * fail dls.
902 * If waiting for certificates to download, return 1. If not, return 0. */
903 static int
904 check_consensus_waiting_for_certs(int flavor, time_t now,
905 download_status_t *dls)
907 consensus_waiting_for_certs_t *waiting;
909 /* We should always have a known flavor, because we_want_to_fetch_flavor()
910 * filters out unknown flavors. */
911 tor_assert(flavor >= 0 && flavor < N_CONSENSUS_FLAVORS);
913 waiting = &consensus_waiting_for_certs[flavor];
914 if (waiting->consensus) {
915 /* XXXX make sure this doesn't delay sane downloads. */
916 if (waiting->set_at + DELAY_WHILE_FETCHING_CERTS > now &&
917 waiting->consensus->valid_until > now) {
918 return 1;
919 } else {
920 if (!waiting->dl_failed) {
921 if (waiting->set_at + MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE > now) {
922 download_status_failed(dls, 0);
924 waiting->dl_failed=1;
929 return 0;
932 /** If we want to download a fresh consensus, launch a new download as
933 * appropriate. */
934 static void
935 update_consensus_networkstatus_downloads(time_t now)
937 int i;
938 const or_options_t *options = get_options();
939 const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
940 now);
941 const int use_multi_conn =
942 networkstatus_consensus_can_use_multiple_directories(options);
944 if (should_delay_dir_fetches(options, NULL))
945 return;
947 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
948 /* XXXX need some way to download unknown flavors if we are caching. */
949 const char *resource;
950 networkstatus_t *c;
951 int max_in_progress_conns = 1;
953 if (! we_want_to_fetch_flavor(options, i))
954 continue;
956 c = networkstatus_get_latest_consensus_by_flavor(i);
957 if (! (c && c->valid_after <= now && now <= c->valid_until)) {
958 /* No live consensus? Get one now!*/
959 time_to_download_next_consensus[i] = now;
962 if (time_to_download_next_consensus[i] > now)
963 continue; /* Wait until the current consensus is older. */
965 resource = networkstatus_get_flavor_name(i);
967 /* Check if we already have enough connections in progress */
968 if (we_are_bootstrapping && use_multi_conn) {
969 max_in_progress_conns =
970 options->ClientBootstrapConsensusMaxInProgressTries;
972 if (connection_dir_count_by_purpose_and_resource(
973 DIR_PURPOSE_FETCH_CONSENSUS,
974 resource)
975 >= max_in_progress_conns) {
976 continue;
979 /* Check if we want to launch another download for a usable consensus.
980 * Only used during bootstrap. */
981 if (we_are_bootstrapping && use_multi_conn
982 && i == usable_consensus_flavor()) {
984 /* Check if we're already downloading a usable consensus */
985 if (networkstatus_consensus_is_already_downloading(resource))
986 continue;
988 /* Make multiple connections for a bootstrap consensus download. */
989 update_consensus_bootstrap_multiple_downloads(now, options);
990 } else {
991 /* Check if we failed downloading a consensus too recently */
992 int max_dl_tries = options->TestingConsensusMaxDownloadTries;
994 /* Let's make sure we remembered to update consensus_dl_status */
995 tor_assert(consensus_dl_status[i].schedule == DL_SCHED_CONSENSUS);
997 if (!download_status_is_ready(&consensus_dl_status[i],
998 now,
999 max_dl_tries)) {
1000 continue;
1003 /* Check if we're waiting for certificates to download */
1004 if (check_consensus_waiting_for_certs(i, now, &consensus_dl_status[i]))
1005 continue;
1007 /* Try the requested attempt */
1008 log_info(LD_DIR, "Launching %s standard networkstatus consensus "
1009 "download.", networkstatus_get_flavor_name(i));
1010 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
1011 ROUTER_PURPOSE_GENERAL, resource,
1012 PDS_RETRY_IF_NO_SERVERS,
1013 consensus_dl_status[i].want_authority);
1018 /** When we're bootstrapping, launch one or more consensus download
1019 * connections, if schedule indicates connection(s) should be made after now.
1020 * If is_authority, connect to an authority, otherwise, use a fallback
1021 * directory mirror.
1023 static void
1024 update_consensus_bootstrap_attempt_downloads(
1025 time_t now,
1026 const or_options_t *options,
1027 download_status_t *dls,
1028 download_want_authority_t want_authority)
1030 int use_fallbacks = networkstatus_consensus_can_use_extra_fallbacks(options);
1031 int max_dl_tries = options->ClientBootstrapConsensusMaxDownloadTries;
1032 if (!use_fallbacks) {
1033 max_dl_tries =
1034 options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries;
1037 const char *resource = networkstatus_get_flavor_name(
1038 usable_consensus_flavor());
1040 /* Let's make sure we remembered to update schedule */
1041 tor_assert(dls->schedule == DL_SCHED_CONSENSUS);
1043 /* Allow for multiple connections in the same second, if the schedule value
1044 * is 0. */
1045 while (download_status_is_ready(dls, now, max_dl_tries)) {
1046 log_info(LD_DIR, "Launching %s bootstrap %s networkstatus consensus "
1047 "download.", resource, (want_authority == DL_WANT_AUTHORITY
1048 ? "authority"
1049 : "mirror"));
1051 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
1052 ROUTER_PURPOSE_GENERAL, resource,
1053 PDS_RETRY_IF_NO_SERVERS, want_authority);
1054 /* schedule the next attempt */
1055 download_status_increment_attempt(dls, resource, now);
1059 /** If we're bootstrapping, check the connection schedules and see if we want
1060 * to make additional, potentially concurrent, consensus download
1061 * connections.
1062 * Only call when bootstrapping, and when we want to make additional
1063 * connections. Only nodes that satisfy
1064 * networkstatus_consensus_can_use_multiple_directories make additional
1065 * connections.
1067 static void
1068 update_consensus_bootstrap_multiple_downloads(time_t now,
1069 const or_options_t *options)
1071 const int usable_flavor = usable_consensus_flavor();
1073 /* make sure we can use multiple connections */
1074 if (!networkstatus_consensus_can_use_multiple_directories(options)) {
1075 return;
1078 /* Launch concurrent consensus download attempt(s) based on the mirror and
1079 * authority schedules. Try the mirror first - this makes it slightly more
1080 * likely that we'll connect to the fallback first, and then end the
1081 * authority connection attempt. */
1083 /* If a consensus download fails because it's waiting for certificates,
1084 * we'll fail both the authority and fallback schedules. This is better than
1085 * failing only one of the schedules, and having the other continue
1086 * unchecked.
1089 /* If we don't have or can't use extra fallbacks, don't try them. */
1090 if (networkstatus_consensus_can_use_extra_fallbacks(options)) {
1091 download_status_t *dls_f =
1092 &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER];
1094 if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_f)) {
1095 /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
1096 update_consensus_bootstrap_attempt_downloads(now, options, dls_f,
1097 DL_WANT_ANY_DIRSERVER);
1101 /* Now try an authority. */
1102 download_status_t *dls_a =
1103 &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY];
1105 if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_a)) {
1106 update_consensus_bootstrap_attempt_downloads(now, options, dls_a,
1107 DL_WANT_AUTHORITY);
1111 /** Called when an attempt to download a consensus fails: note that the
1112 * failure occurred, and possibly retry. */
1113 void
1114 networkstatus_consensus_download_failed(int status_code, const char *flavname)
1116 int flav = networkstatus_parse_flavor_name(flavname);
1117 if (flav >= 0) {
1118 tor_assert(flav < N_CONSENSUS_FLAVORS);
1119 /* XXXX handle unrecognized flavors */
1120 download_status_failed(&consensus_dl_status[flav], status_code);
1121 /* Retry immediately, if appropriate. */
1122 update_consensus_networkstatus_downloads(time(NULL));
1126 /** How long do we (as a cache) wait after a consensus becomes non-fresh
1127 * before trying to fetch another? */
1128 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
1130 /** Update the time at which we'll consider replacing the current
1131 * consensus of flavor <b>flav</b> */
1132 static void
1133 update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
1135 const or_options_t *options = get_options();
1136 networkstatus_t *c = networkstatus_get_latest_consensus_by_flavor(flav);
1137 const char *flavor = networkstatus_get_flavor_name(flav);
1138 if (! we_want_to_fetch_flavor(get_options(), flav))
1139 return;
1141 if (c && c->valid_after <= now && now <= c->valid_until) {
1142 long dl_interval;
1143 long interval = c->fresh_until - c->valid_after;
1144 long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
1145 time_t start;
1147 if (min_sec_before_caching > interval/16) {
1148 /* Usually we allow 2-minutes slop factor in case clocks get
1149 desynchronized a little. If we're on a private network with
1150 a crazy-fast voting interval, though, 2 minutes may be too
1151 much. */
1152 min_sec_before_caching = interval/16;
1153 /* make sure we always delay by at least a second before caching */
1154 if (min_sec_before_caching == 0) {
1155 min_sec_before_caching = 1;
1159 if (directory_fetches_dir_info_early(options)) {
1160 /* We want to cache the next one at some point after this one
1161 * is no longer fresh... */
1162 start = (time_t)(c->fresh_until + min_sec_before_caching);
1163 /* Some clients may need the consensus sooner than others. */
1164 if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
1165 dl_interval = 60;
1166 if (min_sec_before_caching + dl_interval > interval)
1167 dl_interval = interval/2;
1168 } else {
1169 /* But only in the first half-interval after that. */
1170 dl_interval = interval/2;
1172 } else {
1173 /* We're an ordinary client, a bridge, or a hidden service.
1174 * Give all the caches enough time to download the consensus. */
1175 start = (time_t)(c->fresh_until + (interval*3)/4);
1176 /* But download the next one well before this one is expired. */
1177 dl_interval = ((c->valid_until - start) * 7 )/ 8;
1179 /* If we're a bridge user, make use of the numbers we just computed
1180 * to choose the rest of the interval *after* them. */
1181 if (directory_fetches_dir_info_later(options)) {
1182 /* Give all the *clients* enough time to download the consensus. */
1183 start = (time_t)(start + dl_interval + min_sec_before_caching);
1184 /* But try to get it before ours actually expires. */
1185 dl_interval = (c->valid_until - start) - min_sec_before_caching;
1188 /* catch low dl_interval in crazy-fast networks */
1189 if (dl_interval < 1)
1190 dl_interval = 1;
1191 /* catch late start in crazy-fast networks */
1192 if (start+dl_interval >= c->valid_until)
1193 start = c->valid_until - dl_interval - 1;
1194 log_debug(LD_DIR,
1195 "fresh_until: %ld start: %ld "
1196 "dl_interval: %ld valid_until: %ld ",
1197 (long)c->fresh_until, (long)start, dl_interval,
1198 (long)c->valid_until);
1199 /* We must not try to replace c while it's still fresh: */
1200 tor_assert(c->fresh_until < start);
1201 /* We must download the next one before c is invalid: */
1202 tor_assert(start+dl_interval < c->valid_until);
1203 time_to_download_next_consensus[flav] =
1204 start + crypto_rand_int((int)dl_interval);
1206 char tbuf1[ISO_TIME_LEN+1];
1207 char tbuf2[ISO_TIME_LEN+1];
1208 char tbuf3[ISO_TIME_LEN+1];
1209 format_local_iso_time(tbuf1, c->fresh_until);
1210 format_local_iso_time(tbuf2, c->valid_until);
1211 format_local_iso_time(tbuf3, time_to_download_next_consensus[flav]);
1212 log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
1213 "will expire at %s; fetching the next one at %s.",
1214 flavor, (c->fresh_until > now) ? "will be" : "was",
1215 tbuf1, tbuf2, tbuf3);
1217 } else {
1218 time_to_download_next_consensus[flav] = now;
1219 log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
1220 flavor);
1224 /** Update the time at which we'll consider replacing the current
1225 * consensus of flavor 'flavor' */
1226 void
1227 update_consensus_networkstatus_fetch_time(time_t now)
1229 int i;
1230 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
1231 if (we_want_to_fetch_flavor(get_options(), i))
1232 update_consensus_networkstatus_fetch_time_impl(now, i);
1236 /** Return 1 if there's a reason we shouldn't try any directory
1237 * fetches yet (e.g. we demand bridges and none are yet known).
1238 * Else return 0.
1240 * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
1241 * to an explanation of why directory fetches are delayed. (If we
1242 * return 0, we set msg_out to NULL.)
1245 should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
1247 if (msg_out) {
1248 *msg_out = NULL;
1251 if (options->DisableNetwork) {
1252 if (msg_out) {
1253 *msg_out = "DisableNetwork is set.";
1255 log_info(LD_DIR, "Delaying dir fetches (DisableNetwork is set)");
1256 return 1;
1259 if (options->UseBridges) {
1260 if (!any_bridge_descriptors_known()) {
1261 if (msg_out) {
1262 *msg_out = "No running bridges";
1264 log_info(LD_DIR, "Delaying dir fetches (no running bridges known)");
1265 return 1;
1268 if (pt_proxies_configuration_pending()) {
1269 if (msg_out) {
1270 *msg_out = "Pluggable transport proxies still configuring";
1272 log_info(LD_DIR, "Delaying dir fetches (pt proxies still configuring)");
1273 return 1;
1277 return 0;
1280 /** Launch requests for networkstatus documents and authority certificates as
1281 * appropriate. */
1282 void
1283 update_networkstatus_downloads(time_t now)
1285 const or_options_t *options = get_options();
1286 if (should_delay_dir_fetches(options, NULL))
1287 return;
1288 update_consensus_networkstatus_downloads(now);
1289 update_certificate_downloads(now);
1292 /** Launch requests as appropriate for missing directory authority
1293 * certificates. */
1294 void
1295 update_certificate_downloads(time_t now)
1297 int i;
1298 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
1299 if (consensus_waiting_for_certs[i].consensus)
1300 authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
1301 now, NULL);
1304 if (current_ns_consensus)
1305 authority_certs_fetch_missing(current_ns_consensus, now, NULL);
1306 if (current_md_consensus)
1307 authority_certs_fetch_missing(current_md_consensus, now, NULL);
1310 /** Return 1 if we have a consensus but we don't have enough certificates
1311 * to start using it yet. */
1313 consensus_is_waiting_for_certs(void)
1315 return consensus_waiting_for_certs[usable_consensus_flavor()].consensus
1316 ? 1 : 0;
1319 /** Look up the currently active (depending on bootstrap status) download
1320 * status for this consensus flavor and return a pointer to it.
1322 MOCK_IMPL(download_status_t *,
1323 networkstatus_get_dl_status_by_flavor,(consensus_flavor_t flavor))
1325 download_status_t *dl = NULL;
1326 const int we_are_bootstrapping =
1327 networkstatus_consensus_is_bootstrapping(time(NULL));
1329 if ((int)flavor <= N_CONSENSUS_FLAVORS) {
1330 dl = &((we_are_bootstrapping ?
1331 consensus_bootstrap_dl_status : consensus_dl_status)[flavor]);
1334 return dl;
1337 /** Look up the bootstrap download status for this consensus flavor
1338 * and return a pointer to it. */
1339 MOCK_IMPL(download_status_t *,
1340 networkstatus_get_dl_status_by_flavor_bootstrap,(consensus_flavor_t flavor))
1342 download_status_t *dl = NULL;
1344 if ((int)flavor <= N_CONSENSUS_FLAVORS) {
1345 dl = &(consensus_bootstrap_dl_status[flavor]);
1348 return dl;
1351 /** Look up the running (non-bootstrap) download status for this consensus
1352 * flavor and return a pointer to it. */
1353 MOCK_IMPL(download_status_t *,
1354 networkstatus_get_dl_status_by_flavor_running,(consensus_flavor_t flavor))
1356 download_status_t *dl = NULL;
1358 if ((int)flavor <= N_CONSENSUS_FLAVORS) {
1359 dl = &(consensus_dl_status[flavor]);
1362 return dl;
1365 /** Return the most recent consensus that we have downloaded, or NULL if we
1366 * don't have one. */
1367 MOCK_IMPL(networkstatus_t *,
1368 networkstatus_get_latest_consensus,(void))
1370 if (we_use_microdescriptors_for_circuits(get_options()))
1371 return current_md_consensus;
1372 else
1373 return current_ns_consensus;
1376 /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
1377 * if we don't have one. */
1378 MOCK_IMPL(networkstatus_t *,
1379 networkstatus_get_latest_consensus_by_flavor,(consensus_flavor_t f))
1381 if (f == FLAV_NS)
1382 return current_ns_consensus;
1383 else if (f == FLAV_MICRODESC)
1384 return current_md_consensus;
1385 else {
1386 tor_assert(0);
1387 return NULL;
1391 /** Return the most recent consensus that we have downloaded, or NULL if it is
1392 * no longer live. */
1393 MOCK_IMPL(networkstatus_t *,
1394 networkstatus_get_live_consensus,(time_t now))
1396 if (networkstatus_get_latest_consensus() &&
1397 networkstatus_get_latest_consensus()->valid_after <= now &&
1398 now <= networkstatus_get_latest_consensus()->valid_until)
1399 return networkstatus_get_latest_consensus();
1400 else
1401 return NULL;
1404 /** Determine if <b>consensus</b> is valid or expired recently enough that
1405 * we can still use it.
1407 * Return 1 if the consensus is reasonably live, or 0 if it is too old.
1410 networkstatus_consensus_reasonably_live(const networkstatus_t *consensus,
1411 time_t now)
1413 if (BUG(!consensus))
1414 return 0;
1416 return networkstatus_valid_until_is_reasonably_live(consensus->valid_until,
1417 now);
1420 /** As networkstatus_consensus_reasonably_live, but takes a valid_until
1421 * time rather than an entire consensus. */
1423 networkstatus_valid_until_is_reasonably_live(time_t valid_until,
1424 time_t now)
1426 #define REASONABLY_LIVE_TIME (24*60*60)
1427 return (now <= valid_until + REASONABLY_LIVE_TIME);
1430 /* XXXX remove this in favor of get_live_consensus. But actually,
1431 * leave something like it for bridge users, who need to not totally
1432 * lose if they spend a while fetching a new consensus. */
1433 /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
1434 * consensuses. */
1435 networkstatus_t *
1436 networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
1438 networkstatus_t *consensus =
1439 networkstatus_get_latest_consensus_by_flavor(flavor);
1440 if (consensus &&
1441 consensus->valid_after <= now &&
1442 networkstatus_consensus_reasonably_live(consensus, now))
1443 return consensus;
1444 else
1445 return NULL;
1448 /** Check if we need to download a consensus during tor's bootstrap phase.
1449 * If we have no consensus, or our consensus is unusably old, return 1.
1450 * As soon as we have received a consensus, return 0, even if we don't have
1451 * enough certificates to validate it.
1452 * If a fallback directory gives us a consensus we can never get certs for,
1453 * check_consensus_waiting_for_certs() will wait 20 minutes before failing
1454 * the cert downloads. After that, a new consensus will be fetched from a
1455 * randomly chosen fallback. */
1456 MOCK_IMPL(int,
1457 networkstatus_consensus_is_bootstrapping,(time_t now))
1459 /* If we have a validated, reasonably live consensus, we're not
1460 * bootstrapping a consensus at all. */
1461 if (networkstatus_get_reasonably_live_consensus(
1462 now,
1463 usable_consensus_flavor())) {
1464 return 0;
1467 /* If we have a consensus, but we're waiting for certificates,
1468 * we're not waiting for a consensus download while bootstrapping. */
1469 if (consensus_is_waiting_for_certs()) {
1470 return 0;
1473 /* If we have no consensus, or our consensus is very old, we are
1474 * bootstrapping, and we need to download a consensus. */
1475 return 1;
1478 /** Check if we can use multiple directories for a consensus download.
1479 * Only clients (including bridge relays, which act like clients) benefit
1480 * from multiple simultaneous consensus downloads. */
1482 networkstatus_consensus_can_use_multiple_directories(
1483 const or_options_t *options)
1485 /* If we are a client, bridge, bridge client, or hidden service */
1486 return !public_server_mode(options);
1489 /** Check if we can use fallback directory mirrors for a consensus download.
1490 * If we have fallbacks and don't want to fetch from the authorities,
1491 * we can use them. */
1492 MOCK_IMPL(int,
1493 networkstatus_consensus_can_use_extra_fallbacks,(const or_options_t *options))
1495 /* The list length comparisons are a quick way to check if we have any
1496 * non-authority fallback directories. If we ever have any authorities that
1497 * aren't fallback directories, we will need to change this code. */
1498 tor_assert(smartlist_len(router_get_fallback_dir_servers())
1499 >= smartlist_len(router_get_trusted_dir_servers()));
1500 /* If we don't fetch from the authorities, and we have additional mirrors,
1501 * we can use them. */
1502 return (!directory_fetches_from_authorities(options)
1503 && (smartlist_len(router_get_fallback_dir_servers())
1504 > smartlist_len(router_get_trusted_dir_servers())));
1507 /* Is there a consensus fetch for flavor <b>resource</b> that's far
1508 * enough along to be attached to a circuit? */
1510 networkstatus_consensus_is_already_downloading(const char *resource)
1512 int answer = 0;
1514 /* First, get a list of all the dir conns that are fetching a consensus,
1515 * fetching *this* consensus, and are in state "reading" (meaning they
1516 * have already flushed their request onto the socks connection). */
1517 smartlist_t *fetching_conns =
1518 connection_dir_list_by_purpose_resource_and_state(
1519 DIR_PURPOSE_FETCH_CONSENSUS, resource, DIR_CONN_STATE_CLIENT_READING);
1521 /* Then, walk through each conn, to see if its linked socks connection
1522 * is in an attached state. We have to check this separately, since with
1523 * the optimistic data feature, fetches can send their request to the
1524 * socks connection and go into state 'reading', even before they're
1525 * attached to any circuit. */
1526 SMARTLIST_FOREACH_BEGIN(fetching_conns, dir_connection_t *, dirconn) {
1527 /* Do any of these other dir conns have a linked socks conn that is
1528 * attached to a circuit already? */
1529 connection_t *base = TO_CONN(dirconn);
1530 if (base->linked_conn &&
1531 base->linked_conn->type == CONN_TYPE_AP &&
1532 !AP_CONN_STATE_IS_UNATTACHED(base->linked_conn->state)) {
1533 answer = 1;
1534 break; /* stop looping, because we know the answer will be yes */
1536 } SMARTLIST_FOREACH_END(dirconn);
1537 smartlist_free(fetching_conns);
1539 return answer;
1542 /** Given two router status entries for the same router identity, return 1 if
1543 * if the contents have changed between them. Otherwise, return 0. */
1544 static int
1545 routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
1547 tor_assert(tor_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN));
1549 return strcmp(a->nickname, b->nickname) ||
1550 fast_memneq(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
1551 a->addr != b->addr ||
1552 a->or_port != b->or_port ||
1553 a->dir_port != b->dir_port ||
1554 a->is_authority != b->is_authority ||
1555 a->is_exit != b->is_exit ||
1556 a->is_stable != b->is_stable ||
1557 a->is_fast != b->is_fast ||
1558 a->is_flagged_running != b->is_flagged_running ||
1559 a->is_named != b->is_named ||
1560 a->is_unnamed != b->is_unnamed ||
1561 a->is_valid != b->is_valid ||
1562 a->is_possible_guard != b->is_possible_guard ||
1563 a->is_bad_exit != b->is_bad_exit ||
1564 a->is_hs_dir != b->is_hs_dir;
1565 // XXXX this function needs a huge refactoring; it has gotten out
1566 // XXXX of sync with routerstatus_t, and it will do so again.
1569 /** Notify controllers of any router status entries that changed between
1570 * <b>old_c</b> and <b>new_c</b>. */
1571 static void
1572 notify_control_networkstatus_changed(const networkstatus_t *old_c,
1573 const networkstatus_t *new_c)
1575 smartlist_t *changed;
1576 if (old_c == new_c)
1577 return;
1579 /* tell the controller exactly which relays are still listed, as well
1580 * as what they're listed as */
1581 control_event_newconsensus(new_c);
1583 if (!control_event_is_interesting(EVENT_NS))
1584 return;
1586 if (!old_c) {
1587 control_event_networkstatus_changed(new_c->routerstatus_list);
1588 return;
1590 changed = smartlist_new();
1592 SMARTLIST_FOREACH_JOIN(
1593 old_c->routerstatus_list, const routerstatus_t *, rs_old,
1594 new_c->routerstatus_list, const routerstatus_t *, rs_new,
1595 tor_memcmp(rs_old->identity_digest,
1596 rs_new->identity_digest, DIGEST_LEN),
1597 smartlist_add(changed, (void*) rs_new)) {
1598 if (routerstatus_has_changed(rs_old, rs_new))
1599 smartlist_add(changed, (void*)rs_new);
1600 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1602 control_event_networkstatus_changed(changed);
1603 smartlist_free(changed);
1606 /** Copy all the ancillary information (like router download status and so on)
1607 * from <b>old_c</b> to <b>new_c</b>. */
1608 static void
1609 networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
1610 const networkstatus_t *old_c)
1612 if (old_c == new_c)
1613 return;
1614 if (!old_c || !smartlist_len(old_c->routerstatus_list))
1615 return;
1617 SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
1618 new_c->routerstatus_list, routerstatus_t *, rs_new,
1619 tor_memcmp(rs_old->identity_digest,
1620 rs_new->identity_digest, DIGEST_LEN),
1621 STMT_NIL) {
1622 /* Okay, so we're looking at the same identity. */
1623 rs_new->last_dir_503_at = rs_old->last_dir_503_at;
1625 if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
1626 DIGEST256_LEN)) {
1627 /* And the same descriptor too! */
1628 memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
1630 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1633 #ifdef TOR_UNIT_TESTS
1634 /**Accept a <b>flavor</b> consensus <b>c</b> without any additional
1635 * validation. This is exclusively for unit tests.
1636 * We copy any ancillary information from a pre-existing consensus
1637 * and then free the current one and replace it with the newly
1638 * provided instance. Returns -1 on unrecognized flavor, 0 otherwise.
1641 networkstatus_set_current_consensus_from_ns(networkstatus_t *c,
1642 const char *flavor)
1644 int flav = networkstatus_parse_flavor_name(flavor);
1645 switch (flav) {
1646 case FLAV_NS:
1647 if (current_ns_consensus) {
1648 networkstatus_copy_old_consensus_info(c, current_ns_consensus);
1649 networkstatus_vote_free(current_ns_consensus);
1651 current_ns_consensus = c;
1652 break;
1653 case FLAV_MICRODESC:
1654 if (current_md_consensus) {
1655 networkstatus_copy_old_consensus_info(c, current_md_consensus);
1656 networkstatus_vote_free(current_md_consensus);
1658 current_md_consensus = c;
1659 break;
1661 return current_md_consensus ? 0 : -1;
1663 #endif //TOR_UNIT_TESTS
1666 * Return true if any option is set in <b>options</b> to make us behave
1667 * as a client.
1669 * XXXX If we need this elsewhere at any point, we should make it nonstatic
1670 * XXXX and move it into another file.
1672 static int
1673 any_client_port_set(const or_options_t *options)
1675 return (options->SocksPort_set ||
1676 options->TransPort_set ||
1677 options->NATDPort_set ||
1678 options->ControlPort_set ||
1679 options->DNSPort_set);
1683 * Helper for handle_missing_protocol_warning: handles either the
1684 * client case (if <b>is_client</b> is set) or the server case otherwise.
1686 static void
1687 handle_missing_protocol_warning_impl(const networkstatus_t *c,
1688 int is_client)
1690 char *protocol_warning = NULL;
1692 int should_exit = networkstatus_check_required_protocols(c,
1693 is_client,
1694 &protocol_warning);
1695 if (protocol_warning) {
1696 tor_log(should_exit ? LOG_ERR : LOG_WARN,
1697 LD_GENERAL,
1698 "%s", protocol_warning);
1700 if (should_exit) {
1701 tor_assert_nonfatal(protocol_warning);
1703 tor_free(protocol_warning);
1704 if (should_exit)
1705 exit(1);
1708 /** Called when we have received a networkstatus <b>c</b>. If there are
1709 * any _required_ protocols we are missing, log an error and exit
1710 * immediately. If there are any _recommended_ protocols we are missing,
1711 * warn. */
1712 static void
1713 handle_missing_protocol_warning(const networkstatus_t *c,
1714 const or_options_t *options)
1716 const int is_server = server_mode(options);
1717 const int is_client = any_client_port_set(options) || !is_server;
1719 if (is_server)
1720 handle_missing_protocol_warning_impl(c, 0);
1721 if (is_client)
1722 handle_missing_protocol_warning_impl(c, 1);
1725 /** Try to replace the current cached v3 networkstatus with the one in
1726 * <b>consensus</b>. If we don't have enough certificates to validate it,
1727 * store it in consensus_waiting_for_certs and launch a certificate fetch.
1729 * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
1730 * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
1731 * already received, but we were waiting for certificates on it. If flags &
1732 * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
1733 * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
1734 * consensus, even if it comes from many days in the past.
1736 * If source_dir is non-NULL, it's the identity digest for a directory that
1737 * we've just successfully retrieved a consensus or certificates from, so try
1738 * it first to fetch any missing certificates.
1740 * Return 0 on success, <0 on failure. On failure, caller should increment
1741 * the failure count as appropriate.
1743 * We return -1 for mild failures that don't need to be reported to the
1744 * user, and -2 for more serious problems.
1747 networkstatus_set_current_consensus(const char *consensus,
1748 const char *flavor,
1749 unsigned flags,
1750 const char *source_dir)
1752 networkstatus_t *c=NULL;
1753 int r, result = -1;
1754 time_t now = time(NULL);
1755 const or_options_t *options = get_options();
1756 char *unverified_fname = NULL, *consensus_fname = NULL;
1757 int flav = networkstatus_parse_flavor_name(flavor);
1758 const unsigned from_cache = flags & NSSET_FROM_CACHE;
1759 const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
1760 const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
1761 const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
1762 const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
1763 const common_digests_t *current_digests = NULL;
1764 consensus_waiting_for_certs_t *waiting = NULL;
1765 time_t current_valid_after = 0;
1766 int free_consensus = 1; /* Free 'c' at the end of the function */
1767 int old_ewma_enabled;
1768 int checked_protocols_already = 0;
1770 if (flav < 0) {
1771 /* XXXX we don't handle unrecognized flavors yet. */
1772 log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
1773 return -2;
1776 /* Make sure it's parseable. */
1777 c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
1778 if (!c) {
1779 log_warn(LD_DIR, "Unable to parse networkstatus consensus");
1780 result = -2;
1781 goto done;
1784 if (from_cache && !was_waiting_for_certs) {
1785 /* We previously stored this; check _now_ to make sure that version-kills
1786 * really work. This happens even before we check signatures: we did so
1787 * before when we stored this to disk. This does mean an attacker who can
1788 * write to the datadir can make us not start: such an attacker could
1789 * already harm us by replacing our guards, which would be worse. */
1790 checked_protocols_already = 1;
1791 handle_missing_protocol_warning(c, options);
1794 if ((int)c->flavor != flav) {
1795 /* This wasn't the flavor we thought we were getting. */
1796 if (require_flavor) {
1797 log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
1798 networkstatus_get_flavor_name(c->flavor), flavor);
1799 goto done;
1801 flav = c->flavor;
1802 flavor = networkstatus_get_flavor_name(flav);
1805 if (flav != usable_consensus_flavor() &&
1806 !we_want_to_fetch_flavor(options, flav)) {
1807 /* This consensus is totally boring to us: we won't use it, we didn't want
1808 * it, and we won't serve it. Drop it. */
1809 goto done;
1812 if (from_cache && !accept_obsolete &&
1813 c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
1814 log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
1815 goto done;
1818 if (!strcmp(flavor, "ns")) {
1819 consensus_fname = get_datadir_fname("cached-consensus");
1820 unverified_fname = get_datadir_fname("unverified-consensus");
1821 if (current_ns_consensus) {
1822 current_digests = &current_ns_consensus->digests;
1823 current_valid_after = current_ns_consensus->valid_after;
1825 } else if (!strcmp(flavor, "microdesc")) {
1826 consensus_fname = get_datadir_fname("cached-microdesc-consensus");
1827 unverified_fname = get_datadir_fname("unverified-microdesc-consensus");
1828 if (current_md_consensus) {
1829 current_digests = &current_md_consensus->digests;
1830 current_valid_after = current_md_consensus->valid_after;
1832 } else {
1833 cached_dir_t *cur;
1834 char buf[128];
1835 tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
1836 consensus_fname = get_datadir_fname(buf);
1837 tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
1838 unverified_fname = get_datadir_fname(buf);
1839 cur = dirserv_get_consensus(flavor);
1840 if (cur) {
1841 current_digests = &cur->digests;
1842 current_valid_after = cur->published;
1846 if (current_digests &&
1847 tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
1848 /* We already have this one. That's a failure. */
1849 log_info(LD_DIR, "Got a %s consensus we already have", flavor);
1850 goto done;
1853 if (current_valid_after && c->valid_after <= current_valid_after) {
1854 /* We have a newer one. There's no point in accepting this one,
1855 * even if it's great. */
1856 log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
1857 flavor);
1858 goto done;
1861 /* Make sure it's signed enough. */
1862 if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
1863 if (r == -1) {
1864 /* Okay, so it _might_ be signed enough if we get more certificates. */
1865 if (!was_waiting_for_certs) {
1866 log_info(LD_DIR,
1867 "Not enough certificates to check networkstatus consensus");
1869 if (!current_valid_after ||
1870 c->valid_after > current_valid_after) {
1871 waiting = &consensus_waiting_for_certs[flav];
1872 networkstatus_vote_free(waiting->consensus);
1873 tor_free(waiting->body);
1874 waiting->consensus = c;
1875 free_consensus = 0;
1876 waiting->body = tor_strdup(consensus);
1877 waiting->set_at = now;
1878 waiting->dl_failed = 0;
1879 if (!from_cache) {
1880 write_str_to_file(unverified_fname, consensus, 0);
1882 if (dl_certs)
1883 authority_certs_fetch_missing(c, now, source_dir);
1884 /* This case is not a success or a failure until we get the certs
1885 * or fail to get the certs. */
1886 result = 0;
1887 } else {
1888 /* Even if we had enough signatures, we'd never use this as the
1889 * latest consensus. */
1890 if (was_waiting_for_certs && from_cache)
1891 if (unlink(unverified_fname) != 0) {
1892 log_warn(LD_FS,
1893 "Failed to unlink %s: %s",
1894 unverified_fname, strerror(errno));
1897 goto done;
1898 } else {
1899 /* This can never be signed enough: Kill it. */
1900 if (!was_waiting_for_certs) {
1901 log_warn(LD_DIR, "Not enough good signatures on networkstatus "
1902 "consensus");
1903 result = -2;
1905 if (was_waiting_for_certs && (r < -1) && from_cache) {
1906 if (unlink(unverified_fname) != 0) {
1907 log_warn(LD_FS,
1908 "Failed to unlink %s: %s",
1909 unverified_fname, strerror(errno));
1912 goto done;
1916 if (!from_cache && flav == usable_consensus_flavor())
1917 control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
1919 if (!checked_protocols_already) {
1920 handle_missing_protocol_warning(c, options);
1923 /* Are we missing any certificates at all? */
1924 if (r != 1 && dl_certs)
1925 authority_certs_fetch_missing(c, now, source_dir);
1927 const int is_usable_flavor = flav == usable_consensus_flavor();
1929 if (is_usable_flavor) {
1930 notify_control_networkstatus_changed(
1931 networkstatus_get_latest_consensus(), c);
1933 if (flav == FLAV_NS) {
1934 if (current_ns_consensus) {
1935 networkstatus_copy_old_consensus_info(c, current_ns_consensus);
1936 networkstatus_vote_free(current_ns_consensus);
1937 /* Defensive programming : we should set current_ns_consensus very soon
1938 * but we're about to call some stuff in the meantime, and leaving this
1939 * dangling pointer around has proven to be trouble. */
1940 current_ns_consensus = NULL;
1942 current_ns_consensus = c;
1943 free_consensus = 0; /* avoid free */
1944 } else if (flav == FLAV_MICRODESC) {
1945 if (current_md_consensus) {
1946 networkstatus_copy_old_consensus_info(c, current_md_consensus);
1947 networkstatus_vote_free(current_md_consensus);
1948 /* more defensive programming */
1949 current_md_consensus = NULL;
1951 current_md_consensus = c;
1952 free_consensus = 0; /* avoid free */
1955 waiting = &consensus_waiting_for_certs[flav];
1956 if (waiting->consensus &&
1957 waiting->consensus->valid_after <= c->valid_after) {
1958 networkstatus_vote_free(waiting->consensus);
1959 waiting->consensus = NULL;
1960 if (consensus != waiting->body)
1961 tor_free(waiting->body);
1962 else
1963 waiting->body = NULL;
1964 waiting->set_at = 0;
1965 waiting->dl_failed = 0;
1966 if (unlink(unverified_fname) != 0) {
1967 log_warn(LD_FS,
1968 "Failed to unlink %s: %s",
1969 unverified_fname, strerror(errno));
1973 if (is_usable_flavor) {
1974 nodelist_set_consensus(c);
1976 /* XXXXNM Microdescs: needs a non-ns variant. ???? NM*/
1977 update_consensus_networkstatus_fetch_time(now);
1979 dirvote_recalculate_timing(options, now);
1980 routerstatus_list_update_named_server_map();
1982 /* Update ewma and adjust policy if needed; first cache the old value */
1983 old_ewma_enabled = cell_ewma_enabled();
1984 /* Change the cell EWMA settings */
1985 cell_ewma_set_scale_factor(options, c);
1986 /* If we just enabled ewma, set the cmux policy on all active channels */
1987 if (cell_ewma_enabled() && !old_ewma_enabled) {
1988 channel_set_cmux_policy_everywhere(&ewma_policy);
1989 } else if (!cell_ewma_enabled() && old_ewma_enabled) {
1990 /* Turn it off everywhere */
1991 channel_set_cmux_policy_everywhere(NULL);
1994 /* XXXX this call might be unnecessary here: can changing the
1995 * current consensus really alter our view of any OR's rate limits? */
1996 connection_or_update_token_buckets(get_connection_array(), options);
1998 circuit_build_times_new_consensus_params(
1999 get_circuit_build_times_mutable(), c);
2000 channelpadding_new_consensus_params(c);
2003 /* Reset the failure count only if this consensus is actually valid. */
2004 if (c->valid_after <= now && now <= c->valid_until) {
2005 download_status_reset(&consensus_dl_status[flav]);
2006 } else {
2007 if (!from_cache)
2008 download_status_failed(&consensus_dl_status[flav], 0);
2011 if (we_want_to_fetch_flavor(options, flav)) {
2012 dirserv_set_cached_consensus_networkstatus(consensus,
2013 flavor,
2014 &c->digests,
2015 c->digest_sha3_as_signed,
2016 c->valid_after);
2017 if (server_mode(get_options())) {
2018 consdiffmgr_add_consensus(consensus, c);
2022 if (!from_cache) {
2023 write_str_to_file(consensus_fname, consensus, 0);
2026 /** If a consensus appears more than this many seconds before its declared
2027 * valid-after time, declare that our clock is skewed. */
2028 #define EARLY_CONSENSUS_NOTICE_SKEW 60
2030 if (now < c->valid_after - EARLY_CONSENSUS_NOTICE_SKEW) {
2031 char tbuf[ISO_TIME_LEN+1];
2032 char dbuf[64];
2033 long delta = now - c->valid_after;
2034 format_iso_time(tbuf, c->valid_after);
2035 format_time_interval(dbuf, sizeof(dbuf), delta);
2036 log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
2037 "consensus network status document (%s UTC). Tor needs an "
2038 "accurate clock to work correctly. Please check your time and "
2039 "date settings!", dbuf, tbuf);
2040 control_event_general_status(LOG_WARN,
2041 "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
2044 router_dir_info_changed();
2046 result = 0;
2047 done:
2048 if (free_consensus)
2049 networkstatus_vote_free(c);
2050 tor_free(consensus_fname);
2051 tor_free(unverified_fname);
2052 return result;
2055 /** Called when we have gotten more certificates: see whether we can
2056 * now verify a pending consensus.
2058 * If source_dir is non-NULL, it's the identity digest for a directory that
2059 * we've just successfully retrieved certificates from, so try it first to
2060 * fetch any missing certificates.
2062 void
2063 networkstatus_note_certs_arrived(const char *source_dir)
2065 int i;
2066 for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
2067 consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
2068 if (!waiting->consensus)
2069 continue;
2070 if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
2071 char *waiting_body = waiting->body;
2072 if (!networkstatus_set_current_consensus(
2073 waiting_body,
2074 networkstatus_get_flavor_name(i),
2075 NSSET_WAS_WAITING_FOR_CERTS,
2076 source_dir)) {
2077 tor_free(waiting_body);
2083 /** If the network-status list has changed since the last time we called this
2084 * function, update the status of every routerinfo from the network-status
2085 * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
2086 * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
2088 void
2089 routers_update_all_from_networkstatus(time_t now, int dir_version)
2091 routerlist_t *rl = router_get_routerlist();
2092 networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,
2093 FLAV_NS);
2095 if (!consensus || dir_version < 3) /* nothing more we should do */
2096 return;
2098 /* calls router_dir_info_changed() when it's done -- more routers
2099 * might be up or down now, which might affect whether there's enough
2100 * directory info. */
2101 routers_update_status_from_consensus_networkstatus(rl->routers, 0);
2103 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
2104 ri->cache_info.routerlist_index = ri_sl_idx);
2105 if (rl->old_routers)
2106 signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
2108 if (!have_warned_about_old_version) {
2109 int is_server = server_mode(get_options());
2110 version_status_t status;
2111 const char *recommended = is_server ?
2112 consensus->server_versions : consensus->client_versions;
2113 status = tor_version_is_obsolete(VERSION, recommended);
2115 if (status == VS_RECOMMENDED) {
2116 log_info(LD_GENERAL, "The directory authorities say my version is ok.");
2117 } else if (status == VS_EMPTY) {
2118 log_info(LD_GENERAL,
2119 "The directory authorities don't recommend any versions.");
2120 } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
2121 if (!have_warned_about_new_version) {
2122 log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
2123 "recommended version%s, according to the directory "
2124 "authorities. Recommended versions are: %s",
2125 VERSION,
2126 status == VS_NEW_IN_SERIES ? " in its series" : "",
2127 recommended);
2128 have_warned_about_new_version = 1;
2129 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
2130 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
2131 VERSION, "NEW", recommended);
2133 } else {
2134 log_warn(LD_GENERAL, "Please upgrade! "
2135 "This version of Tor (%s) is %s, according to the directory "
2136 "authorities. Recommended versions are: %s",
2137 VERSION,
2138 status == VS_OLD ? "obsolete" : "not recommended",
2139 recommended);
2140 have_warned_about_old_version = 1;
2141 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
2142 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
2143 VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
2144 recommended);
2149 /** Update our view of the list of named servers from the most recently
2150 * retrieved networkstatus consensus. */
2151 static void
2152 routerstatus_list_update_named_server_map(void)
2154 networkstatus_t *ns = networkstatus_get_latest_consensus();
2155 if (!ns)
2156 return;
2158 strmap_free(named_server_map, tor_free_);
2159 named_server_map = strmap_new();
2160 strmap_free(unnamed_server_map, NULL);
2161 unnamed_server_map = strmap_new();
2162 smartlist_t *rslist = ns->routerstatus_list;
2163 SMARTLIST_FOREACH_BEGIN(rslist, const routerstatus_t *, rs) {
2164 if (rs->is_named) {
2165 strmap_set_lc(named_server_map, rs->nickname,
2166 tor_memdup(rs->identity_digest, DIGEST_LEN));
2168 if (rs->is_unnamed) {
2169 strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
2171 } SMARTLIST_FOREACH_END(rs);
2174 /** Given a list <b>routers</b> of routerinfo_t *, update each status field
2175 * according to our current consensus networkstatus. May re-order
2176 * <b>routers</b>. */
2177 void
2178 routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
2179 int reset_failures)
2181 const or_options_t *options = get_options();
2182 int authdir = authdir_mode_v3(options);
2183 networkstatus_t *ns = networkstatus_get_latest_consensus();
2184 if (!ns || !smartlist_len(ns->routerstatus_list))
2185 return;
2187 routers_sort_by_identity(routers);
2189 SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
2190 routers, routerinfo_t *, router,
2191 tor_memcmp(rs->identity_digest,
2192 router->cache_info.identity_digest, DIGEST_LEN),
2194 }) {
2195 /* Is it the same descriptor, or only the same identity? */
2196 if (tor_memeq(router->cache_info.signed_descriptor_digest,
2197 rs->descriptor_digest, DIGEST_LEN)) {
2198 if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
2199 router->cache_info.last_listed_as_valid_until = ns->valid_until;
2202 if (authdir) {
2203 /* If we _are_ an authority, we should check whether this router
2204 * is one that will cause us to need a reachability test. */
2205 routerinfo_t *old_router =
2206 router_get_mutable_by_digest(router->cache_info.identity_digest);
2207 if (old_router != router) {
2208 router->needs_retest_if_added =
2209 dirserv_should_launch_reachability_test(router, old_router);
2212 if (reset_failures) {
2213 download_status_reset(&rs->dl_status);
2215 } SMARTLIST_FOREACH_JOIN_END(rs, router);
2217 router_dir_info_changed();
2220 /** Given a list of signed_descriptor_t, update their fields (mainly, when
2221 * they were last listed) from the most recent consensus. */
2222 void
2223 signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
2225 networkstatus_t *ns = current_ns_consensus;
2226 if (!ns)
2227 return;
2229 if (!ns->desc_digest_map) {
2230 char dummy[DIGEST_LEN];
2231 /* instantiates the digest map. */
2232 memset(dummy, 0, sizeof(dummy));
2233 router_get_consensus_status_by_descriptor_digest(ns, dummy);
2235 SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
2237 const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
2238 d->signed_descriptor_digest);
2239 if (rs) {
2240 if (ns->valid_until > d->last_listed_as_valid_until)
2241 d->last_listed_as_valid_until = ns->valid_until;
2246 /** Generate networkstatus lines for a single routerstatus_t object, and
2247 * return the result in a newly allocated string. Used only by controller
2248 * interface (for now.) */
2249 char *
2250 networkstatus_getinfo_helper_single(const routerstatus_t *rs)
2252 return routerstatus_format_entry(rs, NULL, NULL, NS_CONTROL_PORT, NULL);
2255 /** Alloc and return a string describing routerstatuses for the most
2256 * recent info of each router we know about that is of purpose
2257 * <b>purpose_string</b>. Return NULL if unrecognized purpose.
2259 * Right now this function is oriented toward listing bridges (you
2260 * shouldn't use this for general-purpose routers, since those
2261 * should be listed from the consensus, not from the routers list). */
2262 char *
2263 networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
2265 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2266 char *answer;
2267 routerlist_t *rl = router_get_routerlist();
2268 smartlist_t *statuses;
2269 uint8_t purpose = router_purpose_from_string(purpose_string);
2270 routerstatus_t rs;
2271 int bridge_auth = authdir_mode_bridge(get_options());
2273 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2274 log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
2275 purpose_string);
2276 return NULL;
2279 statuses = smartlist_new();
2280 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
2281 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2282 if (!node)
2283 continue;
2284 if (ri->cache_info.published_on < cutoff)
2285 continue;
2286 if (ri->purpose != purpose)
2287 continue;
2288 if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
2289 dirserv_set_router_is_running(ri, now);
2290 /* then generate and write out status lines for each of them */
2291 set_routerstatus_from_routerinfo(&rs, node, ri, now, 0);
2292 smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
2293 } SMARTLIST_FOREACH_END(ri);
2295 answer = smartlist_join_strings(statuses, "", 0, NULL);
2296 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
2297 smartlist_free(statuses);
2298 return answer;
2301 /** Write out router status entries for all our bridge descriptors. */
2302 void
2303 networkstatus_dump_bridge_status_to_file(time_t now)
2305 char *status = networkstatus_getinfo_by_purpose("bridge", now);
2306 const or_options_t *options = get_options();
2307 char *fname = NULL;
2308 char *thresholds = NULL;
2309 char *published_thresholds_and_status = NULL;
2310 char published[ISO_TIME_LEN+1];
2312 format_iso_time(published, now);
2313 dirserv_compute_bridge_flag_thresholds();
2314 thresholds = dirserv_get_flag_thresholds_line();
2315 tor_asprintf(&published_thresholds_and_status,
2316 "published %s\nflag-thresholds %s\n%s",
2317 published, thresholds, status);
2318 tor_asprintf(&fname, "%s"PATH_SEPARATOR"networkstatus-bridges",
2319 options->DataDirectory);
2320 write_str_to_file(fname,published_thresholds_and_status,0);
2321 tor_free(thresholds);
2322 tor_free(published_thresholds_and_status);
2323 tor_free(fname);
2324 tor_free(status);
2327 /* DOCDOC get_net_param_from_list */
2328 static int32_t
2329 get_net_param_from_list(smartlist_t *net_params, const char *param_name,
2330 int32_t default_val, int32_t min_val, int32_t max_val)
2332 int32_t res = default_val;
2333 size_t name_len = strlen(param_name);
2335 tor_assert(max_val > min_val);
2336 tor_assert(min_val <= default_val);
2337 tor_assert(max_val >= default_val);
2339 SMARTLIST_FOREACH_BEGIN(net_params, const char *, p) {
2340 if (!strcmpstart(p, param_name) && p[name_len] == '=') {
2341 int ok=0;
2342 long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
2343 INT32_MAX, &ok, NULL);
2344 if (ok) {
2345 res = (int32_t) v;
2346 break;
2349 } SMARTLIST_FOREACH_END(p);
2351 if (res < min_val) {
2352 log_warn(LD_DIR, "Consensus parameter %s is too small. Got %d, raising to "
2353 "%d.", param_name, res, min_val);
2354 res = min_val;
2355 } else if (res > max_val) {
2356 log_warn(LD_DIR, "Consensus parameter %s is too large. Got %d, capping to "
2357 "%d.", param_name, res, max_val);
2358 res = max_val;
2361 return res;
2364 /** Return the value of a integer parameter from the networkstatus <b>ns</b>
2365 * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
2366 * latest consensus ourselves. Return <b>default_val</b> if no latest
2367 * consensus, or if it has no parameter called <b>param_name</b>.
2368 * Make sure the value parsed from the consensus is at least
2369 * <b>min_val</b> and at most <b>max_val</b> and raise/cap the parsed value
2370 * if necessary. */
2371 int32_t
2372 networkstatus_get_param(const networkstatus_t *ns, const char *param_name,
2373 int32_t default_val, int32_t min_val, int32_t max_val)
2375 if (!ns) /* if they pass in null, go find it ourselves */
2376 ns = networkstatus_get_latest_consensus();
2378 if (!ns || !ns->net_params)
2379 return default_val;
2381 return get_net_param_from_list(ns->net_params, param_name,
2382 default_val, min_val, max_val);
2386 * As networkstatus_get_param(), but check torrc_value before checking the
2387 * consensus. If torrc_value is in-range, then return it instead of the
2388 * value from the consensus.
2390 int32_t
2391 networkstatus_get_overridable_param(const networkstatus_t *ns,
2392 int32_t torrc_value,
2393 const char *param_name,
2394 int32_t default_val,
2395 int32_t min_val, int32_t max_val)
2397 if (torrc_value >= min_val && torrc_value <= max_val)
2398 return torrc_value;
2399 else
2400 return networkstatus_get_param(
2401 ns, param_name, default_val, min_val, max_val);
2405 * Retrieve the consensus parameter that governs the
2406 * fixed-point precision of our network balancing 'bandwidth-weights'
2407 * (which are themselves integer consensus values). We divide them
2408 * by this value and ensure they never exceed this value.
2411 networkstatus_get_weight_scale_param(networkstatus_t *ns)
2413 return networkstatus_get_param(ns, "bwweightscale",
2414 BW_WEIGHT_SCALE,
2415 BW_MIN_WEIGHT_SCALE,
2416 BW_MAX_WEIGHT_SCALE);
2419 /** Return the value of a integer bw weight parameter from the networkstatus
2420 * <b>ns</b> whose name is <b>weight_name</b>. If <b>ns</b> is NULL, try
2421 * loading the latest consensus ourselves. Return <b>default_val</b> if no
2422 * latest consensus, or if it has no parameter called <b>weight_name</b>. */
2423 int32_t
2424 networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name,
2425 int32_t default_val)
2427 int32_t param;
2428 int max;
2429 if (!ns) /* if they pass in null, go find it ourselves */
2430 ns = networkstatus_get_latest_consensus();
2432 if (!ns || !ns->weight_params)
2433 return default_val;
2435 max = networkstatus_get_weight_scale_param(ns);
2436 param = get_net_param_from_list(ns->weight_params, weight_name,
2437 default_val, -1,
2438 BW_MAX_WEIGHT_SCALE);
2439 if (param > max) {
2440 log_warn(LD_DIR, "Value of consensus weight %s was too large, capping "
2441 "to %d", weight_name, max);
2442 param = max;
2444 return param;
2447 /** Return the name of the consensus flavor <b>flav</b> as used to identify
2448 * the flavor in directory documents. */
2449 const char *
2450 networkstatus_get_flavor_name(consensus_flavor_t flav)
2452 switch (flav) {
2453 case FLAV_NS:
2454 return "ns";
2455 case FLAV_MICRODESC:
2456 return "microdesc";
2457 default:
2458 tor_fragile_assert();
2459 return "??";
2463 /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
2464 * or -1 if the flavor is not recognized. */
2466 networkstatus_parse_flavor_name(const char *flavname)
2468 if (!strcmp(flavname, "ns"))
2469 return FLAV_NS;
2470 else if (!strcmp(flavname, "microdesc"))
2471 return FLAV_MICRODESC;
2472 else
2473 return -1;
2476 /** Return 0 if this routerstatus is obsolete, too new, isn't
2477 * running, or otherwise not a descriptor that we would make any
2478 * use of even if we had it. Else return 1. */
2480 client_would_use_router(const routerstatus_t *rs, time_t now)
2482 if (!rs->is_flagged_running) {
2483 /* If we had this router descriptor, we wouldn't even bother using it.
2484 * (Fetching and storing depends on by we_want_to_fetch_flavor().) */
2485 return 0;
2487 if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
2488 /* We'd drop it immediately for being too old. */
2489 return 0;
2491 if (!routerstatus_version_supports_extend2_cells(rs, 1)) {
2492 /* We'd ignore it because it doesn't support EXTEND2 cells.
2493 * If we don't know the version, download the descriptor so we can
2494 * check if it supports EXTEND2 cells and ntor. */
2495 return 0;
2497 return 1;
2500 /** If <b>question</b> is a string beginning with "ns/" in a format the
2501 * control interface expects for a GETINFO question, set *<b>answer</b> to a
2502 * newly-allocated string containing networkstatus lines for the appropriate
2503 * ORs. Return 0 on success, -1 on unrecognized question format. */
2505 getinfo_helper_networkstatus(control_connection_t *conn,
2506 const char *question, char **answer,
2507 const char **errmsg)
2509 const routerstatus_t *status;
2510 (void) conn;
2512 if (!networkstatus_get_latest_consensus()) {
2513 *answer = tor_strdup("");
2514 return 0;
2517 if (!strcmp(question, "ns/all")) {
2518 smartlist_t *statuses = smartlist_new();
2519 SMARTLIST_FOREACH(networkstatus_get_latest_consensus()->routerstatus_list,
2520 const routerstatus_t *, rs,
2522 smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
2524 *answer = smartlist_join_strings(statuses, "", 0, NULL);
2525 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
2526 smartlist_free(statuses);
2527 return 0;
2528 } else if (!strcmpstart(question, "ns/id/")) {
2529 char d[DIGEST_LEN];
2530 const char *q = question + 6;
2531 if (*q == '$')
2532 ++q;
2534 if (base16_decode(d, DIGEST_LEN, q, strlen(q)) != DIGEST_LEN) {
2535 *errmsg = "Data not decodeable as hex";
2536 return -1;
2538 status = router_get_consensus_status_by_id(d);
2539 } else if (!strcmpstart(question, "ns/name/")) {
2540 status = router_get_consensus_status_by_nickname(question+8, 0);
2541 } else if (!strcmpstart(question, "ns/purpose/")) {
2542 *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
2543 return *answer ? 0 : -1;
2544 } else if (!strcmp(question, "consensus/packages")) {
2545 const networkstatus_t *ns = networkstatus_get_latest_consensus();
2546 if (ns && ns->package_lines)
2547 *answer = smartlist_join_strings(ns->package_lines, "\n", 0, NULL);
2548 else
2549 *errmsg = "No consensus available";
2550 return *answer ? 0 : -1;
2551 } else if (!strcmp(question, "consensus/valid-after") ||
2552 !strcmp(question, "consensus/fresh-until") ||
2553 !strcmp(question, "consensus/valid-until")) {
2554 const networkstatus_t *ns = networkstatus_get_latest_consensus();
2555 if (ns) {
2556 time_t t;
2557 if (!strcmp(question, "consensus/valid-after"))
2558 t = ns->valid_after;
2559 else if (!strcmp(question, "consensus/fresh-until"))
2560 t = ns->fresh_until;
2561 else
2562 t = ns->valid_until;
2564 char tbuf[ISO_TIME_LEN+1];
2565 format_iso_time(tbuf, t);
2566 *answer = tor_strdup(tbuf);
2567 } else {
2568 *errmsg = "No consensus available";
2570 return *answer ? 0 : -1;
2571 } else {
2572 return 0;
2575 if (status)
2576 *answer = networkstatus_getinfo_helper_single(status);
2577 return 0;
2580 /** Check whether the networkstatus <b>ns</b> lists any protocol
2581 * versions as "required" or "recommended" that we do not support. If
2582 * so, set *<b>warning_out</b> to a newly allocated string describing
2583 * the problem.
2585 * Return 1 if we should exit, 0 if we should not. */
2587 networkstatus_check_required_protocols(const networkstatus_t *ns,
2588 int client_mode,
2589 char **warning_out)
2591 const char *func = client_mode ? "client" : "relay";
2592 const char *required, *recommended;
2593 char *missing = NULL;
2595 tor_assert(warning_out);
2597 if (client_mode) {
2598 required = ns->required_client_protocols;
2599 recommended = ns->recommended_client_protocols;
2600 } else {
2601 required = ns->required_relay_protocols;
2602 recommended = ns->recommended_relay_protocols;
2605 if (!protover_all_supported(required, &missing)) {
2606 tor_asprintf(warning_out, "At least one protocol listed as required in "
2607 "the consensus is not supported by this version of Tor. "
2608 "You should upgrade. This version of Tor will not work as a "
2609 "%s on the Tor network. The missing protocols are: %s",
2610 func, missing);
2611 tor_free(missing);
2612 return 1;
2615 if (! protover_all_supported(recommended, &missing)) {
2616 tor_asprintf(warning_out, "At least one protocol listed as recommended in "
2617 "the consensus is not supported by this version of Tor. "
2618 "You should upgrade. This version of Tor will eventually "
2619 "stop working as a %s on the Tor network. The missing "
2620 "protocols are: %s",
2621 func, missing);
2622 tor_free(missing);
2625 tor_assert_nonfatal(missing == NULL);
2627 return 0;
2630 /** Free all storage held locally in this module. */
2631 void
2632 networkstatus_free_all(void)
2634 int i;
2635 networkstatus_vote_free(current_ns_consensus);
2636 networkstatus_vote_free(current_md_consensus);
2637 current_md_consensus = current_ns_consensus = NULL;
2639 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
2640 consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
2641 if (waiting->consensus) {
2642 networkstatus_vote_free(waiting->consensus);
2643 waiting->consensus = NULL;
2645 tor_free(waiting->body);
2648 strmap_free(named_server_map, tor_free_);
2649 strmap_free(unnamed_server_map, NULL);