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 */
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
43 #include "circuitmux.h"
44 #include "circuitmux_ewma.h"
45 #include "circuitstats.h"
47 #include "connection.h"
48 #include "connection_or.h"
49 #include "consdiffmgr.h"
51 #include "directory.h"
54 #include "entrynodes.h"
56 #include "microdesc.h"
57 #include "networkstatus.h"
62 #include "routerlist.h"
63 #include "routerparse.h"
64 #include "scheduler.h"
65 #include "shared_random.h"
66 #include "transports.h"
68 #include "channelpadding.h"
70 /** Most recently received and validated v3 "ns"-flavored consensus network
72 STATIC networkstatus_t
*current_ns_consensus
= NULL
;
74 /** Most recently received and validated v3 "microdesc"-flavored consensus
76 STATIC networkstatus_t
*current_md_consensus
= NULL
;
78 /** A v3 consensus networkstatus that we've received, but which we don't
79 * have enough certificates to be happy about. */
80 typedef struct consensus_waiting_for_certs_t
{
81 /** The consensus itself. */
82 networkstatus_t
*consensus
;
83 /** The encoded version of the consensus, nul-terminated. */
85 /** When did we set the current value of consensus_waiting_for_certs? If
86 * this is too recent, we shouldn't try to fetch a new consensus for a
87 * little while, to give ourselves time to get certificates for this one. */
89 /** Set to 1 if we've been holding on to it for so long we should maybe
90 * treat it as being bad. */
92 } consensus_waiting_for_certs_t
;
94 /** An array, for each flavor of consensus we might want, of consensuses that
95 * we have downloaded, but which we cannot verify due to having insufficient
96 * authority certificates. */
97 static consensus_waiting_for_certs_t
98 consensus_waiting_for_certs
[N_CONSENSUS_FLAVORS
];
100 /** A time before which we shouldn't try to replace the current consensus:
101 * this will be at some point after the next consensus becomes valid, but
102 * before the current consensus becomes invalid. */
103 static time_t time_to_download_next_consensus
[N_CONSENSUS_FLAVORS
];
104 /** Download status for the current consensus networkstatus. */
105 static download_status_t consensus_dl_status
[N_CONSENSUS_FLAVORS
] =
107 { 0, 0, 0, DL_SCHED_CONSENSUS
, DL_WANT_ANY_DIRSERVER
,
108 DL_SCHED_INCREMENT_FAILURE
, DL_SCHED_RANDOM_EXPONENTIAL
, 0, 0 },
109 { 0, 0, 0, DL_SCHED_CONSENSUS
, DL_WANT_ANY_DIRSERVER
,
110 DL_SCHED_INCREMENT_FAILURE
, DL_SCHED_RANDOM_EXPONENTIAL
, 0, 0 },
113 #define N_CONSENSUS_BOOTSTRAP_SCHEDULES 2
114 #define CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY 0
115 #define CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER 1
117 /* Using DL_SCHED_INCREMENT_ATTEMPT on these schedules means that
118 * download_status_increment_failure won't increment these entries.
119 * However, any bootstrap connection failures that occur after we have
120 * a valid consensus will count against the failure counts on the non-bootstrap
121 * schedules. There should only be one of these, as all the others will have
122 * been cancelled. (This doesn't seem to be a significant issue.) */
123 static download_status_t
124 consensus_bootstrap_dl_status
[N_CONSENSUS_BOOTSTRAP_SCHEDULES
] =
126 { 0, 0, 0, DL_SCHED_CONSENSUS
, DL_WANT_AUTHORITY
,
127 DL_SCHED_INCREMENT_ATTEMPT
, DL_SCHED_RANDOM_EXPONENTIAL
, 0, 0 },
128 /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
129 { 0, 0, 0, DL_SCHED_CONSENSUS
, DL_WANT_ANY_DIRSERVER
,
130 DL_SCHED_INCREMENT_ATTEMPT
, DL_SCHED_RANDOM_EXPONENTIAL
, 0, 0 },
133 /** True iff we have logged a warning about this OR's version being older than
134 * listed by the authorities. */
135 static int have_warned_about_old_version
= 0;
136 /** True iff we have logged a warning about this OR's version being newer than
137 * listed by the authorities. */
138 static int have_warned_about_new_version
= 0;
140 static void update_consensus_bootstrap_multiple_downloads(
142 const or_options_t
*options
);
143 static int networkstatus_check_required_protocols(const networkstatus_t
*ns
,
147 /** Forget that we've warned about anything networkstatus-related, so we will
148 * give fresh warnings if the same behavior happens again. */
150 networkstatus_reset_warnings(void)
152 SMARTLIST_FOREACH(nodelist_get_list(), node_t
*, node
,
153 node
->name_lookup_warned
= 0);
155 have_warned_about_old_version
= 0;
156 have_warned_about_new_version
= 0;
159 /** Reset the descriptor download failure count on all networkstatus docs, so
160 * that we can retry any long-failed documents immediately.
163 networkstatus_reset_download_failures(void)
167 log_debug(LD_GENERAL
,
168 "In networkstatus_reset_download_failures()");
170 for (i
=0; i
< N_CONSENSUS_FLAVORS
; ++i
)
171 download_status_reset(&consensus_dl_status
[i
]);
173 for (i
=0; i
< N_CONSENSUS_BOOTSTRAP_SCHEDULES
; ++i
)
174 download_status_reset(&consensus_bootstrap_dl_status
[i
]);
178 * Read and and return the cached consensus of type <b>flavorname</b>. If
179 * <b>unverified</b> is false, get the one we haven't verified. Return NULL if
180 * the file isn't there. */
182 networkstatus_read_cached_consensus_impl(int flav
,
183 const char *flavorname
,
184 int unverified_consensus
)
188 if (unverified_consensus
) {
189 prefix
= "unverified";
193 if (flav
== FLAV_NS
) {
194 tor_snprintf(buf
, sizeof(buf
), "%s-consensus", prefix
);
196 tor_snprintf(buf
, sizeof(buf
), "%s-%s-consensus", prefix
, flavorname
);
199 char *filename
= get_datadir_fname(buf
);
200 char *result
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
205 /** Return a new string containing the current cached consensus of flavor
206 * <b>flavorname</b>. */
208 networkstatus_read_cached_consensus(const char *flavorname
)
210 int flav
= networkstatus_parse_flavor_name(flavorname
);
213 return networkstatus_read_cached_consensus_impl(flav
, flavorname
, 0);
216 /** Read every cached v3 consensus networkstatus from the disk. */
218 router_reload_consensus_networkstatus(void)
220 const unsigned int flags
= NSSET_FROM_CACHE
| NSSET_DONT_DOWNLOAD_CERTS
;
223 /* FFFF Suppress warnings if cached consensus is bad? */
224 for (flav
= 0; flav
< N_CONSENSUS_FLAVORS
; ++flav
) {
225 const char *flavor
= networkstatus_get_flavor_name(flav
);
226 char *s
= networkstatus_read_cached_consensus_impl(flav
, flavor
, 0);
228 if (networkstatus_set_current_consensus(s
, flavor
, flags
, NULL
) < -1) {
229 log_warn(LD_FS
, "Couldn't load consensus %s networkstatus from cache",
235 s
= networkstatus_read_cached_consensus_impl(flav
, flavor
, 1);
237 if (networkstatus_set_current_consensus(s
, flavor
,
238 flags
|NSSET_WAS_WAITING_FOR_CERTS
,
240 log_info(LD_FS
, "Couldn't load unverified consensus %s networkstatus "
241 "from cache", flavor
);
247 update_certificate_downloads(time(NULL
));
249 routers_update_all_from_networkstatus(time(NULL
), 3);
250 update_microdescs_from_networkstatus(time(NULL
));
255 /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
257 vote_routerstatus_free(vote_routerstatus_t
*rs
)
259 vote_microdesc_hash_t
*h
, *next
;
262 tor_free(rs
->version
);
263 tor_free(rs
->protocols
);
264 tor_free(rs
->status
.exitsummary
);
265 for (h
= rs
->microdesc
; h
; h
= next
) {
266 tor_free(h
->microdesc_hash_line
);
273 /** Free all storage held by the routerstatus object <b>rs</b>. */
275 routerstatus_free(routerstatus_t
*rs
)
279 tor_free(rs
->exitsummary
);
283 /** Free all storage held in <b>sig</b> */
285 document_signature_free(document_signature_t
*sig
)
287 tor_free(sig
->signature
);
291 /** Return a newly allocated copy of <b>sig</b> */
292 document_signature_t
*
293 document_signature_dup(const document_signature_t
*sig
)
295 document_signature_t
*r
= tor_memdup(sig
, sizeof(document_signature_t
));
297 r
->signature
= tor_memdup(sig
->signature
, sig
->signature_len
);
301 /** Free all storage held in <b>ns</b>. */
303 networkstatus_vote_free(networkstatus_t
*ns
)
308 tor_free(ns
->client_versions
);
309 tor_free(ns
->server_versions
);
310 tor_free(ns
->recommended_client_protocols
);
311 tor_free(ns
->recommended_relay_protocols
);
312 tor_free(ns
->required_client_protocols
);
313 tor_free(ns
->required_relay_protocols
);
315 if (ns
->known_flags
) {
316 SMARTLIST_FOREACH(ns
->known_flags
, char *, c
, tor_free(c
));
317 smartlist_free(ns
->known_flags
);
319 if (ns
->weight_params
) {
320 SMARTLIST_FOREACH(ns
->weight_params
, char *, c
, tor_free(c
));
321 smartlist_free(ns
->weight_params
);
323 if (ns
->net_params
) {
324 SMARTLIST_FOREACH(ns
->net_params
, char *, c
, tor_free(c
));
325 smartlist_free(ns
->net_params
);
327 if (ns
->supported_methods
) {
328 SMARTLIST_FOREACH(ns
->supported_methods
, char *, c
, tor_free(c
));
329 smartlist_free(ns
->supported_methods
);
331 if (ns
->package_lines
) {
332 SMARTLIST_FOREACH(ns
->package_lines
, char *, c
, tor_free(c
));
333 smartlist_free(ns
->package_lines
);
336 SMARTLIST_FOREACH_BEGIN(ns
->voters
, networkstatus_voter_info_t
*, voter
) {
337 tor_free(voter
->nickname
);
338 tor_free(voter
->address
);
339 tor_free(voter
->contact
);
341 SMARTLIST_FOREACH(voter
->sigs
, document_signature_t
*, sig
,
342 document_signature_free(sig
));
343 smartlist_free(voter
->sigs
);
346 } SMARTLIST_FOREACH_END(voter
);
347 smartlist_free(ns
->voters
);
349 authority_cert_free(ns
->cert
);
351 if (ns
->routerstatus_list
) {
352 if (ns
->type
== NS_TYPE_VOTE
|| ns
->type
== NS_TYPE_OPINION
) {
353 SMARTLIST_FOREACH(ns
->routerstatus_list
, vote_routerstatus_t
*, rs
,
354 vote_routerstatus_free(rs
));
356 SMARTLIST_FOREACH(ns
->routerstatus_list
, routerstatus_t
*, rs
,
357 routerstatus_free(rs
));
360 smartlist_free(ns
->routerstatus_list
);
363 digestmap_free(ns
->desc_digest_map
, NULL
);
365 if (ns
->sr_info
.commits
) {
366 SMARTLIST_FOREACH(ns
->sr_info
.commits
, sr_commit_t
*, c
,
368 smartlist_free(ns
->sr_info
.commits
);
370 tor_free(ns
->sr_info
.previous_srv
);
371 tor_free(ns
->sr_info
.current_srv
);
373 memwipe(ns
, 11, sizeof(*ns
));
377 /** Return the voter info from <b>vote</b> for the voter whose identity digest
378 * is <b>identity</b>, or NULL if no such voter is associated with
380 networkstatus_voter_info_t
*
381 networkstatus_get_voter_by_id(networkstatus_t
*vote
,
382 const char *identity
)
384 if (!vote
|| !vote
->voters
)
386 SMARTLIST_FOREACH(vote
->voters
, networkstatus_voter_info_t
*, voter
,
387 if (fast_memeq(voter
->identity_digest
, identity
, DIGEST_LEN
))
392 /** Check whether the signature <b>sig</b> is correctly signed with the
393 * signing key in <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
394 * signing key; otherwise set the good_signature or bad_signature flag on
395 * <b>voter</b>, and return 0. */
397 networkstatus_check_document_signature(const networkstatus_t
*consensus
,
398 document_signature_t
*sig
,
399 const authority_cert_t
*cert
)
401 char key_digest
[DIGEST_LEN
];
402 const int dlen
= sig
->alg
== DIGEST_SHA1
? DIGEST_LEN
: DIGEST256_LEN
;
404 size_t signed_digest_len
;
406 if (crypto_pk_get_digest(cert
->signing_key
, key_digest
)<0)
408 if (tor_memneq(sig
->signing_key_digest
, key_digest
, DIGEST_LEN
) ||
409 tor_memneq(sig
->identity_digest
, cert
->cache_info
.identity_digest
,
413 if (authority_cert_is_blacklisted(cert
)) {
414 /* We implement blacklisting for authority signing keys by treating
415 * all their signatures as always bad. That way we don't get into
416 * crazy loops of dropping and re-fetching signatures. */
417 log_warn(LD_DIR
, "Ignoring a consensus signature made with deprecated"
419 hex_str(cert
->signing_key_digest
, DIGEST_LEN
));
420 sig
->bad_signature
= 1;
424 signed_digest_len
= crypto_pk_keysize(cert
->signing_key
);
425 signed_digest
= tor_malloc(signed_digest_len
);
426 if (crypto_pk_public_checksig(cert
->signing_key
,
430 sig
->signature_len
) < dlen
||
431 tor_memneq(signed_digest
, consensus
->digests
.d
[sig
->alg
], dlen
)) {
432 log_warn(LD_DIR
, "Got a bad signature on a networkstatus vote");
433 sig
->bad_signature
= 1;
435 sig
->good_signature
= 1;
437 tor_free(signed_digest
);
441 /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
442 * as-yet-unchecked signature on <b>consensus</b>. Return 1 if there is a
443 * signature from every recognized authority on it, 0 if there are
444 * enough good signatures from recognized authorities on it, -1 if we might
445 * get enough good signatures by fetching missing certificates, and -2
446 * otherwise. Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
447 * about every problem; if warn is at least 1, warn only if we can't get
448 * enough signatures; if warn is negative, log nothing at all. */
450 networkstatus_check_consensus_signature(networkstatus_t
*consensus
,
454 int n_missing_key
= 0, n_dl_failed_key
= 0;
457 int n_no_signature
= 0;
458 int n_v3_authorities
= get_n_authorities(V3_DIRINFO
);
459 int n_required
= n_v3_authorities
/2 + 1;
460 smartlist_t
*list_good
= smartlist_new();
461 smartlist_t
*list_no_signature
= smartlist_new();
462 smartlist_t
*need_certs_from
= smartlist_new();
463 smartlist_t
*unrecognized
= smartlist_new();
464 smartlist_t
*missing_authorities
= smartlist_new();
466 time_t now
= time(NULL
);
468 tor_assert(consensus
->type
== NS_TYPE_CONSENSUS
);
470 SMARTLIST_FOREACH_BEGIN(consensus
->voters
, networkstatus_voter_info_t
*,
474 int unknown_here
= 0;
475 int missing_key_here
= 0, dl_failed_key_here
= 0;
476 SMARTLIST_FOREACH_BEGIN(voter
->sigs
, document_signature_t
*, sig
) {
477 if (!sig
->good_signature
&& !sig
->bad_signature
&&
479 /* we can try to check the signature. */
480 int is_v3_auth
= trusteddirserver_get_by_v3_auth_digest(
481 sig
->identity_digest
) != NULL
;
482 authority_cert_t
*cert
=
483 authority_cert_get_by_digests(sig
->identity_digest
,
484 sig
->signing_key_digest
);
485 tor_assert(tor_memeq(sig
->identity_digest
, voter
->identity_digest
,
489 smartlist_add(unrecognized
, voter
);
492 } else if (!cert
|| cert
->expires
< now
) {
493 smartlist_add(need_certs_from
, voter
);
495 if (authority_cert_dl_looks_uncertain(sig
->identity_digest
))
496 ++dl_failed_key_here
;
499 if (networkstatus_check_document_signature(consensus
, sig
, cert
) < 0) {
500 smartlist_add(need_certs_from
, voter
);
502 if (authority_cert_dl_looks_uncertain(sig
->identity_digest
))
503 ++dl_failed_key_here
;
507 if (sig
->good_signature
)
509 else if (sig
->bad_signature
)
511 } SMARTLIST_FOREACH_END(sig
);
515 smartlist_add(list_good
, voter
->nickname
);
516 } else if (bad_here
) {
518 } else if (missing_key_here
) {
520 if (dl_failed_key_here
)
522 } else if (unknown_here
) {
526 smartlist_add(list_no_signature
, voter
->nickname
);
528 } SMARTLIST_FOREACH_END(voter
);
530 /* Now see whether we're missing any voters entirely. */
531 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
534 if ((ds
->type
& V3_DIRINFO
) &&
535 !networkstatus_get_voter_by_id(consensus
, ds
->v3_identity_digest
))
536 smartlist_add(missing_authorities
, ds
);
539 if (warn
> 1 || (warn
>= 0 &&
540 (n_good
+ n_missing_key
- n_dl_failed_key
< n_required
))) {
547 SMARTLIST_FOREACH(unrecognized
, networkstatus_voter_info_t
*, voter
,
549 tor_log(severity
, LD_DIR
, "Consensus includes unrecognized authority "
550 "'%s' at %s:%d (contact %s; identity %s)",
551 voter
->nickname
, voter
->address
, (int)voter
->dir_port
,
552 voter
->contact
?voter
->contact
:"n/a",
553 hex_str(voter
->identity_digest
, DIGEST_LEN
));
555 SMARTLIST_FOREACH(need_certs_from
, networkstatus_voter_info_t
*, voter
,
557 tor_log(severity
, LD_DIR
, "Looks like we need to download a new "
558 "certificate from authority '%s' at %s:%d (contact %s; "
560 voter
->nickname
, voter
->address
, (int)voter
->dir_port
,
561 voter
->contact
?voter
->contact
:"n/a",
562 hex_str(voter
->identity_digest
, DIGEST_LEN
));
564 SMARTLIST_FOREACH(missing_authorities
, dir_server_t
*, ds
,
566 tor_log(severity
, LD_DIR
, "Consensus does not include configured "
567 "authority '%s' at %s:%d (identity %s)",
568 ds
->nickname
, ds
->address
, (int)ds
->dir_port
,
569 hex_str(ds
->v3_identity_digest
, DIGEST_LEN
));
573 smartlist_t
*sl
= smartlist_new();
574 char *tmp
= smartlist_join_strings(list_good
, " ", 0, NULL
);
575 smartlist_add_asprintf(sl
,
576 "A consensus needs %d good signatures from recognized "
577 "authorities for us to accept it. This one has %d (%s).",
578 n_required
, n_good
, tmp
);
580 if (n_no_signature
) {
581 tmp
= smartlist_join_strings(list_no_signature
, " ", 0, NULL
);
582 smartlist_add_asprintf(sl
,
583 "%d (%s) of the authorities we know didn't sign it.",
584 n_no_signature
, tmp
);
588 smartlist_add_asprintf(sl
,
589 "It has %d signatures from authorities we don't "
590 "recognize.", n_unknown
);
593 smartlist_add_asprintf(sl
, "%d of the signatures on it didn't verify "
594 "correctly.", n_bad
);
597 smartlist_add_asprintf(sl
,
598 "We were unable to check %d of the signatures, "
599 "because we were missing the keys.", n_missing_key
);
601 joined
= smartlist_join_strings(sl
, " ", 0, NULL
);
602 tor_log(severity
, LD_DIR
, "%s", joined
);
604 SMARTLIST_FOREACH(sl
, char *, c
, tor_free(c
));
609 smartlist_free(list_good
);
610 smartlist_free(list_no_signature
);
611 smartlist_free(unrecognized
);
612 smartlist_free(need_certs_from
);
613 smartlist_free(missing_authorities
);
615 if (n_good
== n_v3_authorities
)
617 else if (n_good
>= n_required
)
619 else if (n_good
+ n_missing_key
>= n_required
)
625 /** How far in the future do we allow a network-status to get before removing
627 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
629 /** Helper for bsearching a list of routerstatus_t pointers: compare a
630 * digest in the key to the identity digest of a routerstatus_t. */
632 compare_digest_to_routerstatus_entry(const void *_key
, const void **_member
)
634 const char *key
= _key
;
635 const routerstatus_t
*rs
= *_member
;
636 return tor_memcmp(key
, rs
->identity_digest
, DIGEST_LEN
);
639 /** Helper for bsearching a list of routerstatus_t pointers: compare a
640 * digest in the key to the identity digest of a routerstatus_t. */
642 compare_digest_to_vote_routerstatus_entry(const void *_key
,
643 const void **_member
)
645 const char *key
= _key
;
646 const vote_routerstatus_t
*vrs
= *_member
;
647 return tor_memcmp(key
, vrs
->status
.identity_digest
, DIGEST_LEN
);
650 /** As networkstatus_find_entry, but do not return a const pointer */
652 networkstatus_vote_find_mutable_entry(networkstatus_t
*ns
, const char *digest
)
654 return smartlist_bsearch(ns
->routerstatus_list
, digest
,
655 compare_digest_to_routerstatus_entry
);
658 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
659 * NULL if none was found. */
660 const routerstatus_t
*
661 networkstatus_vote_find_entry(networkstatus_t
*ns
, const char *digest
)
663 return networkstatus_vote_find_mutable_entry(ns
, digest
);
666 /*XXXX MOVE make this static once functions are moved into this file. */
667 /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
668 * <b>digest</b>. Return value and set *<b>found_out</b> as for
669 * smartlist_bsearch_idx(). */
671 networkstatus_vote_find_entry_idx(networkstatus_t
*ns
,
672 const char *digest
, int *found_out
)
674 return smartlist_bsearch_idx(ns
->routerstatus_list
, digest
,
675 compare_digest_to_routerstatus_entry
,
679 /** As router_get_consensus_status_by_descriptor_digest, but does not return
680 * a const pointer. */
681 MOCK_IMPL(routerstatus_t
*,
682 router_get_mutable_consensus_status_by_descriptor_digest
,(
683 networkstatus_t
*consensus
,
687 consensus
= networkstatus_get_latest_consensus();
690 if (!consensus
->desc_digest_map
) {
691 digestmap_t
*m
= consensus
->desc_digest_map
= digestmap_new();
692 SMARTLIST_FOREACH(consensus
->routerstatus_list
,
693 routerstatus_t
*, rs
,
695 digestmap_set(m
, rs
->descriptor_digest
, rs
);
698 return digestmap_get(consensus
->desc_digest_map
, digest
);
701 /** Return the consensus view of the status of the router whose current
702 * <i>descriptor</i> digest in <b>consensus</b> is <b>digest</b>, or NULL if
703 * no such router is known. */
704 const routerstatus_t
*
705 router_get_consensus_status_by_descriptor_digest(networkstatus_t
*consensus
,
708 return router_get_mutable_consensus_status_by_descriptor_digest(
712 /** Return a smartlist of all router descriptor digests in a consensus */
714 router_get_descriptor_digests_in_consensus(networkstatus_t
*consensus
)
716 smartlist_t
*result
= smartlist_new();
722 for (i
= digestmap_iter_init(consensus
->desc_digest_map
);
723 !(digestmap_iter_done(i
));
724 i
= digestmap_iter_next(consensus
->desc_digest_map
, i
)) {
725 digestmap_iter_get(i
, &digest
, &rs
);
726 digest_tmp
= tor_malloc(DIGEST_LEN
);
727 memcpy(digest_tmp
, digest
, DIGEST_LEN
);
728 smartlist_add(result
, digest_tmp
);
734 /** Return a smartlist of all router descriptor digests in the current
736 MOCK_IMPL(smartlist_t
*,
737 router_get_descriptor_digests
,(void))
739 smartlist_t
*result
= NULL
;
741 if (current_ns_consensus
) {
743 router_get_descriptor_digests_in_consensus(current_ns_consensus
);
749 /** Given the digest of a router descriptor, return its current download
750 * status, or NULL if the digest is unrecognized. */
751 MOCK_IMPL(download_status_t
*,
752 router_get_dl_status_by_descriptor_digest
,(const char *d
))
755 if (!current_ns_consensus
)
757 if ((rs
= router_get_mutable_consensus_status_by_descriptor_digest(
758 current_ns_consensus
, d
)))
759 return &rs
->dl_status
;
764 /** As router_get_consensus_status_by_id, but do not return a const pointer */
766 router_get_mutable_consensus_status_by_id(const char *digest
)
768 const networkstatus_t
*ns
= networkstatus_get_latest_consensus();
771 smartlist_t
*rslist
= ns
->routerstatus_list
;
772 return smartlist_bsearch(rslist
, digest
,
773 compare_digest_to_routerstatus_entry
);
776 /** Return the consensus view of the status of the router whose identity
777 * digest is <b>digest</b>, or NULL if we don't know about any such router. */
778 const routerstatus_t
*
779 router_get_consensus_status_by_id(const char *digest
)
781 return router_get_mutable_consensus_status_by_id(digest
);
784 /** How frequently do directory authorities re-download fresh networkstatus
786 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
788 /** How frequently do non-authority directory caches re-download fresh
789 * networkstatus documents? */
790 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
792 /** Return true iff, given the options listed in <b>options</b>, <b>flavor</b>
793 * is the flavor of a consensus networkstatus that we would like to fetch.
795 * For certificate fetches, use we_want_to_fetch_unknown_auth_certs, and
796 * for serving fetched documents, use directory_caches_dir_info. */
798 we_want_to_fetch_flavor(const or_options_t
*options
, int flavor
)
800 if (flavor
< 0 || flavor
> N_CONSENSUS_FLAVORS
) {
801 /* This flavor is crazy; we don't want it */
802 /*XXXX handle unrecognized flavors later */
805 if (authdir_mode_v3(options
) || directory_caches_dir_info(options
)) {
806 /* We want to serve all flavors to others, regardless if we would use
810 if (options
->FetchUselessDescriptors
) {
811 /* In order to get all descriptors, we need to fetch all consensuses. */
814 /* Otherwise, we want the flavor only if we want to use it to build
816 return flavor
== usable_consensus_flavor();
819 /** Return true iff, given the options listed in <b>options</b>, we would like
820 * to fetch and store unknown authority certificates.
822 * For consensus and descriptor fetches, use we_want_to_fetch_flavor, and
823 * for serving fetched certificates, use directory_caches_unknown_auth_certs.
826 we_want_to_fetch_unknown_auth_certs(const or_options_t
*options
)
828 if (authdir_mode_v3(options
) ||
829 directory_caches_unknown_auth_certs((options
))) {
830 /* We want to serve all certs to others, regardless if we would use
834 if (options
->FetchUselessDescriptors
) {
835 /* Unknown certificates are definitely useless. */
838 /* Otherwise, don't fetch unknown certificates. */
842 /** How long will we hang onto a possibly live consensus for which we're
843 * fetching certs before we check whether there is a better one? */
844 #define DELAY_WHILE_FETCHING_CERTS (20*60)
846 /** What is the minimum time we need to have waited fetching certs, before we
847 * increment the consensus download schedule on failure? */
848 #define MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE (1*60)
850 /* Check if a downloaded consensus flavor should still wait for certificates
851 * to download now. If we decide not to wait, check if enough time has passed
852 * to consider the certificate download failure a separate failure. If so,
854 * If waiting for certificates to download, return 1. If not, return 0. */
856 check_consensus_waiting_for_certs(int flavor
, time_t now
,
857 download_status_t
*dls
)
859 consensus_waiting_for_certs_t
*waiting
;
861 /* We should always have a known flavor, because we_want_to_fetch_flavor()
862 * filters out unknown flavors. */
863 tor_assert(flavor
>= 0 && flavor
< N_CONSENSUS_FLAVORS
);
865 waiting
= &consensus_waiting_for_certs
[flavor
];
866 if (waiting
->consensus
) {
867 /* XXXX make sure this doesn't delay sane downloads. */
868 if (waiting
->set_at
+ DELAY_WHILE_FETCHING_CERTS
> now
&&
869 waiting
->consensus
->valid_until
> now
) {
872 if (!waiting
->dl_failed
) {
873 if (waiting
->set_at
+ MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE
> now
) {
874 download_status_failed(dls
, 0);
876 waiting
->dl_failed
=1;
884 /** If we want to download a fresh consensus, launch a new download as
887 update_consensus_networkstatus_downloads(time_t now
)
890 const or_options_t
*options
= get_options();
891 const int we_are_bootstrapping
= networkstatus_consensus_is_bootstrapping(
893 const int use_multi_conn
=
894 networkstatus_consensus_can_use_multiple_directories(options
);
896 if (should_delay_dir_fetches(options
, NULL
))
899 for (i
=0; i
< N_CONSENSUS_FLAVORS
; ++i
) {
900 /* XXXX need some way to download unknown flavors if we are caching. */
901 const char *resource
;
903 int max_in_progress_conns
= 1;
905 if (! we_want_to_fetch_flavor(options
, i
))
908 c
= networkstatus_get_latest_consensus_by_flavor(i
);
909 if (! (c
&& c
->valid_after
<= now
&& now
<= c
->valid_until
)) {
910 /* No live consensus? Get one now!*/
911 time_to_download_next_consensus
[i
] = now
;
914 if (time_to_download_next_consensus
[i
] > now
)
915 continue; /* Wait until the current consensus is older. */
917 resource
= networkstatus_get_flavor_name(i
);
919 /* Check if we already have enough connections in progress */
920 if (we_are_bootstrapping
&& use_multi_conn
) {
921 max_in_progress_conns
=
922 options
->ClientBootstrapConsensusMaxInProgressTries
;
924 if (connection_dir_count_by_purpose_and_resource(
925 DIR_PURPOSE_FETCH_CONSENSUS
,
927 >= max_in_progress_conns
) {
931 /* Check if we want to launch another download for a usable consensus.
932 * Only used during bootstrap. */
933 if (we_are_bootstrapping
&& use_multi_conn
934 && i
== usable_consensus_flavor()) {
936 /* Check if we're already downloading a usable consensus */
937 if (networkstatus_consensus_is_already_downloading(resource
))
940 /* Make multiple connections for a bootstrap consensus download. */
941 update_consensus_bootstrap_multiple_downloads(now
, options
);
943 /* Check if we failed downloading a consensus too recently */
944 int max_dl_tries
= options
->TestingConsensusMaxDownloadTries
;
946 /* Let's make sure we remembered to update consensus_dl_status */
947 tor_assert(consensus_dl_status
[i
].schedule
== DL_SCHED_CONSENSUS
);
949 if (!download_status_is_ready(&consensus_dl_status
[i
],
955 /* Check if we're waiting for certificates to download */
956 if (check_consensus_waiting_for_certs(i
, now
, &consensus_dl_status
[i
]))
959 /* Try the requested attempt */
960 log_info(LD_DIR
, "Launching %s standard networkstatus consensus "
961 "download.", networkstatus_get_flavor_name(i
));
962 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS
,
963 ROUTER_PURPOSE_GENERAL
, resource
,
964 PDS_RETRY_IF_NO_SERVERS
,
965 consensus_dl_status
[i
].want_authority
);
970 /** When we're bootstrapping, launch one or more consensus download
971 * connections, if schedule indicates connection(s) should be made after now.
972 * If is_authority, connect to an authority, otherwise, use a fallback
976 update_consensus_bootstrap_attempt_downloads(
978 const or_options_t
*options
,
979 download_status_t
*dls
,
980 download_want_authority_t want_authority
)
982 int use_fallbacks
= networkstatus_consensus_can_use_extra_fallbacks(options
);
983 int max_dl_tries
= options
->ClientBootstrapConsensusMaxDownloadTries
;
984 if (!use_fallbacks
) {
986 options
->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
;
989 const char *resource
= networkstatus_get_flavor_name(
990 usable_consensus_flavor());
992 /* Let's make sure we remembered to update schedule */
993 tor_assert(dls
->schedule
== DL_SCHED_CONSENSUS
);
995 /* Allow for multiple connections in the same second, if the schedule value
997 while (download_status_is_ready(dls
, now
, max_dl_tries
)) {
998 log_info(LD_DIR
, "Launching %s bootstrap %s networkstatus consensus "
999 "download.", resource
, (want_authority
== DL_WANT_AUTHORITY
1003 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS
,
1004 ROUTER_PURPOSE_GENERAL
, resource
,
1005 PDS_RETRY_IF_NO_SERVERS
, want_authority
);
1006 /* schedule the next attempt */
1007 download_status_increment_attempt(dls
, resource
, now
);
1011 /** If we're bootstrapping, check the connection schedules and see if we want
1012 * to make additional, potentially concurrent, consensus download
1014 * Only call when bootstrapping, and when we want to make additional
1015 * connections. Only nodes that satisfy
1016 * networkstatus_consensus_can_use_multiple_directories make additional
1020 update_consensus_bootstrap_multiple_downloads(time_t now
,
1021 const or_options_t
*options
)
1023 const int usable_flavor
= usable_consensus_flavor();
1025 /* make sure we can use multiple connections */
1026 if (!networkstatus_consensus_can_use_multiple_directories(options
)) {
1030 /* Launch concurrent consensus download attempt(s) based on the mirror and
1031 * authority schedules. Try the mirror first - this makes it slightly more
1032 * likely that we'll connect to the fallback first, and then end the
1033 * authority connection attempt. */
1035 /* If a consensus download fails because it's waiting for certificates,
1036 * we'll fail both the authority and fallback schedules. This is better than
1037 * failing only one of the schedules, and having the other continue
1041 /* If we don't have or can't use extra fallbacks, don't try them. */
1042 if (networkstatus_consensus_can_use_extra_fallbacks(options
)) {
1043 download_status_t
*dls_f
=
1044 &consensus_bootstrap_dl_status
[CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER
];
1046 if (!check_consensus_waiting_for_certs(usable_flavor
, now
, dls_f
)) {
1047 /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
1048 update_consensus_bootstrap_attempt_downloads(now
, options
, dls_f
,
1049 DL_WANT_ANY_DIRSERVER
);
1053 /* Now try an authority. */
1054 download_status_t
*dls_a
=
1055 &consensus_bootstrap_dl_status
[CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY
];
1057 if (!check_consensus_waiting_for_certs(usable_flavor
, now
, dls_a
)) {
1058 update_consensus_bootstrap_attempt_downloads(now
, options
, dls_a
,
1063 /** Called when an attempt to download a consensus fails: note that the
1064 * failure occurred, and possibly retry. */
1066 networkstatus_consensus_download_failed(int status_code
, const char *flavname
)
1068 int flav
= networkstatus_parse_flavor_name(flavname
);
1070 tor_assert(flav
< N_CONSENSUS_FLAVORS
);
1071 /* XXXX handle unrecognized flavors */
1072 download_status_failed(&consensus_dl_status
[flav
], status_code
);
1073 /* Retry immediately, if appropriate. */
1074 update_consensus_networkstatus_downloads(time(NULL
));
1078 /** How long do we (as a cache) wait after a consensus becomes non-fresh
1079 * before trying to fetch another? */
1080 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
1082 /** Update the time at which we'll consider replacing the current
1083 * consensus of flavor <b>flav</b> */
1085 update_consensus_networkstatus_fetch_time_impl(time_t now
, int flav
)
1087 const or_options_t
*options
= get_options();
1088 networkstatus_t
*c
= networkstatus_get_latest_consensus_by_flavor(flav
);
1089 const char *flavor
= networkstatus_get_flavor_name(flav
);
1090 if (! we_want_to_fetch_flavor(get_options(), flav
))
1093 if (c
&& c
->valid_after
<= now
&& now
<= c
->valid_until
) {
1095 long interval
= c
->fresh_until
- c
->valid_after
;
1096 long min_sec_before_caching
= CONSENSUS_MIN_SECONDS_BEFORE_CACHING
;
1099 if (min_sec_before_caching
> interval
/16) {
1100 /* Usually we allow 2-minutes slop factor in case clocks get
1101 desynchronized a little. If we're on a private network with
1102 a crazy-fast voting interval, though, 2 minutes may be too
1104 min_sec_before_caching
= interval
/16;
1105 /* make sure we always delay by at least a second before caching */
1106 if (min_sec_before_caching
== 0) {
1107 min_sec_before_caching
= 1;
1111 if (directory_fetches_dir_info_early(options
)) {
1112 /* We want to cache the next one at some point after this one
1113 * is no longer fresh... */
1114 start
= (time_t)(c
->fresh_until
+ min_sec_before_caching
);
1115 /* Some clients may need the consensus sooner than others. */
1116 if (options
->FetchDirInfoExtraEarly
|| authdir_mode_v3(options
)) {
1118 if (min_sec_before_caching
+ dl_interval
> interval
)
1119 dl_interval
= interval
/2;
1121 /* But only in the first half-interval after that. */
1122 dl_interval
= interval
/2;
1125 /* We're an ordinary client, a bridge, or a hidden service.
1126 * Give all the caches enough time to download the consensus. */
1127 start
= (time_t)(c
->fresh_until
+ (interval
*3)/4);
1128 /* But download the next one well before this one is expired. */
1129 dl_interval
= ((c
->valid_until
- start
) * 7 )/ 8;
1131 /* If we're a bridge user, make use of the numbers we just computed
1132 * to choose the rest of the interval *after* them. */
1133 if (directory_fetches_dir_info_later(options
)) {
1134 /* Give all the *clients* enough time to download the consensus. */
1135 start
= (time_t)(start
+ dl_interval
+ min_sec_before_caching
);
1136 /* But try to get it before ours actually expires. */
1137 dl_interval
= (c
->valid_until
- start
) - min_sec_before_caching
;
1140 /* catch low dl_interval in crazy-fast networks */
1141 if (dl_interval
< 1)
1143 /* catch late start in crazy-fast networks */
1144 if (start
+dl_interval
>= c
->valid_until
)
1145 start
= c
->valid_until
- dl_interval
- 1;
1147 "fresh_until: %ld start: %ld "
1148 "dl_interval: %ld valid_until: %ld ",
1149 (long)c
->fresh_until
, (long)start
, dl_interval
,
1150 (long)c
->valid_until
);
1151 /* We must not try to replace c while it's still fresh: */
1152 tor_assert(c
->fresh_until
< start
);
1153 /* We must download the next one before c is invalid: */
1154 tor_assert(start
+dl_interval
< c
->valid_until
);
1155 time_to_download_next_consensus
[flav
] =
1156 start
+ crypto_rand_int((int)dl_interval
);
1158 char tbuf1
[ISO_TIME_LEN
+1];
1159 char tbuf2
[ISO_TIME_LEN
+1];
1160 char tbuf3
[ISO_TIME_LEN
+1];
1161 format_local_iso_time(tbuf1
, c
->fresh_until
);
1162 format_local_iso_time(tbuf2
, c
->valid_until
);
1163 format_local_iso_time(tbuf3
, time_to_download_next_consensus
[flav
]);
1164 log_info(LD_DIR
, "Live %s consensus %s the most recent until %s and "
1165 "will expire at %s; fetching the next one at %s.",
1166 flavor
, (c
->fresh_until
> now
) ? "will be" : "was",
1167 tbuf1
, tbuf2
, tbuf3
);
1170 time_to_download_next_consensus
[flav
] = now
;
1171 log_info(LD_DIR
, "No live %s consensus; we should fetch one immediately.",
1176 /** Update the time at which we'll consider replacing the current
1177 * consensus of flavor 'flavor' */
1179 update_consensus_networkstatus_fetch_time(time_t now
)
1182 for (i
= 0; i
< N_CONSENSUS_FLAVORS
; ++i
) {
1183 if (we_want_to_fetch_flavor(get_options(), i
))
1184 update_consensus_networkstatus_fetch_time_impl(now
, i
);
1188 /** Return 1 if there's a reason we shouldn't try any directory
1189 * fetches yet (e.g. we demand bridges and none are yet known).
1192 * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
1193 * to an explanation of why directory fetches are delayed. (If we
1194 * return 0, we set msg_out to NULL.)
1197 should_delay_dir_fetches(const or_options_t
*options
, const char **msg_out
)
1203 if (options
->DisableNetwork
) {
1205 *msg_out
= "DisableNetwork is set.";
1207 log_info(LD_DIR
, "Delaying dir fetches (DisableNetwork is set)");
1211 if (options
->UseBridges
) {
1212 if (num_bridges_usable() == 0) {
1214 *msg_out
= "No running bridges";
1216 log_info(LD_DIR
, "Delaying dir fetches (no running bridges known)");
1220 if (pt_proxies_configuration_pending()) {
1222 *msg_out
= "Pluggable transport proxies still configuring";
1224 log_info(LD_DIR
, "Delaying dir fetches (pt proxies still configuring)");
1232 /** Launch requests for networkstatus documents and authority certificates as
1235 update_networkstatus_downloads(time_t now
)
1237 const or_options_t
*options
= get_options();
1238 if (should_delay_dir_fetches(options
, NULL
))
1240 update_consensus_networkstatus_downloads(now
);
1241 update_certificate_downloads(now
);
1244 /** Launch requests as appropriate for missing directory authority
1247 update_certificate_downloads(time_t now
)
1250 for (i
= 0; i
< N_CONSENSUS_FLAVORS
; ++i
) {
1251 if (consensus_waiting_for_certs
[i
].consensus
)
1252 authority_certs_fetch_missing(consensus_waiting_for_certs
[i
].consensus
,
1256 if (current_ns_consensus
)
1257 authority_certs_fetch_missing(current_ns_consensus
, now
, NULL
);
1258 if (current_md_consensus
)
1259 authority_certs_fetch_missing(current_md_consensus
, now
, NULL
);
1262 /** Return 1 if we have a consensus but we don't have enough certificates
1263 * to start using it yet. */
1265 consensus_is_waiting_for_certs(void)
1267 return consensus_waiting_for_certs
[usable_consensus_flavor()].consensus
1271 /** Look up the currently active (depending on bootstrap status) download
1272 * status for this consensus flavor and return a pointer to it.
1274 MOCK_IMPL(download_status_t
*,
1275 networkstatus_get_dl_status_by_flavor
,(consensus_flavor_t flavor
))
1277 download_status_t
*dl
= NULL
;
1278 const int we_are_bootstrapping
=
1279 networkstatus_consensus_is_bootstrapping(time(NULL
));
1281 if ((int)flavor
<= N_CONSENSUS_FLAVORS
) {
1282 dl
= &((we_are_bootstrapping
?
1283 consensus_bootstrap_dl_status
: consensus_dl_status
)[flavor
]);
1289 /** Look up the bootstrap download status for this consensus flavor
1290 * and return a pointer to it. */
1291 MOCK_IMPL(download_status_t
*,
1292 networkstatus_get_dl_status_by_flavor_bootstrap
,(consensus_flavor_t flavor
))
1294 download_status_t
*dl
= NULL
;
1296 if ((int)flavor
<= N_CONSENSUS_FLAVORS
) {
1297 dl
= &(consensus_bootstrap_dl_status
[flavor
]);
1303 /** Look up the running (non-bootstrap) download status for this consensus
1304 * flavor and return a pointer to it. */
1305 MOCK_IMPL(download_status_t
*,
1306 networkstatus_get_dl_status_by_flavor_running
,(consensus_flavor_t flavor
))
1308 download_status_t
*dl
= NULL
;
1310 if ((int)flavor
<= N_CONSENSUS_FLAVORS
) {
1311 dl
= &(consensus_dl_status
[flavor
]);
1317 /** Return the most recent consensus that we have downloaded, or NULL if we
1318 * don't have one. */
1319 MOCK_IMPL(networkstatus_t
*,
1320 networkstatus_get_latest_consensus
,(void))
1322 if (we_use_microdescriptors_for_circuits(get_options()))
1323 return current_md_consensus
;
1325 return current_ns_consensus
;
1328 /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
1329 * if we don't have one. */
1330 MOCK_IMPL(networkstatus_t
*,
1331 networkstatus_get_latest_consensus_by_flavor
,(consensus_flavor_t f
))
1334 return current_ns_consensus
;
1335 else if (f
== FLAV_MICRODESC
)
1336 return current_md_consensus
;
1343 /** Return the most recent consensus that we have downloaded, or NULL if it is
1344 * no longer live. */
1345 MOCK_IMPL(networkstatus_t
*,
1346 networkstatus_get_live_consensus
,(time_t now
))
1348 networkstatus_t
*ns
= networkstatus_get_latest_consensus();
1349 if (ns
&& networkstatus_is_live(ns
, now
))
1355 /** Given a consensus in <b>ns</b>, return true iff currently live and
1358 networkstatus_is_live(const networkstatus_t
*ns
, time_t now
)
1360 return (ns
->valid_after
<= now
&& now
<= ns
->valid_until
);
1363 /** Determine if <b>consensus</b> is valid or expired recently enough that
1364 * we can still use it.
1366 * Return 1 if the consensus is reasonably live, or 0 if it is too old.
1369 networkstatus_consensus_reasonably_live(const networkstatus_t
*consensus
,
1372 if (BUG(!consensus
))
1375 return networkstatus_valid_until_is_reasonably_live(consensus
->valid_until
,
1379 /** As networkstatus_consensus_reasonably_live, but takes a valid_until
1380 * time rather than an entire consensus. */
1382 networkstatus_valid_until_is_reasonably_live(time_t valid_until
,
1385 #define REASONABLY_LIVE_TIME (24*60*60)
1386 return (now
<= valid_until
+ REASONABLY_LIVE_TIME
);
1389 /* XXXX remove this in favor of get_live_consensus. But actually,
1390 * leave something like it for bridge users, who need to not totally
1391 * lose if they spend a while fetching a new consensus. */
1392 /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
1395 networkstatus_get_reasonably_live_consensus(time_t now
, int flavor
)
1397 networkstatus_t
*consensus
=
1398 networkstatus_get_latest_consensus_by_flavor(flavor
);
1400 consensus
->valid_after
<= now
&&
1401 networkstatus_consensus_reasonably_live(consensus
, now
))
1407 /** Check if we need to download a consensus during tor's bootstrap phase.
1408 * If we have no consensus, or our consensus is unusably old, return 1.
1409 * As soon as we have received a consensus, return 0, even if we don't have
1410 * enough certificates to validate it.
1411 * If a fallback directory gives us a consensus we can never get certs for,
1412 * check_consensus_waiting_for_certs() will wait 20 minutes before failing
1413 * the cert downloads. After that, a new consensus will be fetched from a
1414 * randomly chosen fallback. */
1416 networkstatus_consensus_is_bootstrapping
,(time_t now
))
1418 /* If we have a validated, reasonably live consensus, we're not
1419 * bootstrapping a consensus at all. */
1420 if (networkstatus_get_reasonably_live_consensus(
1422 usable_consensus_flavor())) {
1426 /* If we have a consensus, but we're waiting for certificates,
1427 * we're not waiting for a consensus download while bootstrapping. */
1428 if (consensus_is_waiting_for_certs()) {
1432 /* If we have no consensus, or our consensus is very old, we are
1433 * bootstrapping, and we need to download a consensus. */
1437 /** Check if we can use multiple directories for a consensus download.
1438 * Only clients (including bridge relays, which act like clients) benefit
1439 * from multiple simultaneous consensus downloads. */
1441 networkstatus_consensus_can_use_multiple_directories(
1442 const or_options_t
*options
)
1444 /* If we are a client, bridge, bridge client, or hidden service */
1445 return !public_server_mode(options
);
1448 /** Check if we can use fallback directory mirrors for a consensus download.
1449 * If we have fallbacks and don't want to fetch from the authorities,
1450 * we can use them. */
1452 networkstatus_consensus_can_use_extra_fallbacks
,(const or_options_t
*options
))
1454 /* The list length comparisons are a quick way to check if we have any
1455 * non-authority fallback directories. If we ever have any authorities that
1456 * aren't fallback directories, we will need to change this code. */
1457 tor_assert(smartlist_len(router_get_fallback_dir_servers())
1458 >= smartlist_len(router_get_trusted_dir_servers()));
1459 /* If we don't fetch from the authorities, and we have additional mirrors,
1460 * we can use them. */
1461 return (!directory_fetches_from_authorities(options
)
1462 && (smartlist_len(router_get_fallback_dir_servers())
1463 > smartlist_len(router_get_trusted_dir_servers())));
1466 /* Is there a consensus fetch for flavor <b>resource</b> that's far
1467 * enough along to be attached to a circuit? */
1469 networkstatus_consensus_is_already_downloading(const char *resource
)
1473 /* First, get a list of all the dir conns that are fetching a consensus,
1474 * fetching *this* consensus, and are in state "reading" (meaning they
1475 * have already flushed their request onto the socks connection). */
1476 smartlist_t
*fetching_conns
=
1477 connection_dir_list_by_purpose_resource_and_state(
1478 DIR_PURPOSE_FETCH_CONSENSUS
, resource
, DIR_CONN_STATE_CLIENT_READING
);
1480 /* Then, walk through each conn, to see if its linked socks connection
1481 * is in an attached state. We have to check this separately, since with
1482 * the optimistic data feature, fetches can send their request to the
1483 * socks connection and go into state 'reading', even before they're
1484 * attached to any circuit. */
1485 SMARTLIST_FOREACH_BEGIN(fetching_conns
, dir_connection_t
*, dirconn
) {
1486 /* Do any of these other dir conns have a linked socks conn that is
1487 * attached to a circuit already? */
1488 connection_t
*base
= TO_CONN(dirconn
);
1489 if (base
->linked_conn
&&
1490 base
->linked_conn
->type
== CONN_TYPE_AP
&&
1491 !AP_CONN_STATE_IS_UNATTACHED(base
->linked_conn
->state
)) {
1493 break; /* stop looping, because we know the answer will be yes */
1495 } SMARTLIST_FOREACH_END(dirconn
);
1496 smartlist_free(fetching_conns
);
1501 /** Given two router status entries for the same router identity, return 1 if
1502 * if the contents have changed between them. Otherwise, return 0. */
1504 routerstatus_has_changed(const routerstatus_t
*a
, const routerstatus_t
*b
)
1506 tor_assert(tor_memeq(a
->identity_digest
, b
->identity_digest
, DIGEST_LEN
));
1508 return strcmp(a
->nickname
, b
->nickname
) ||
1509 fast_memneq(a
->descriptor_digest
, b
->descriptor_digest
, DIGEST_LEN
) ||
1510 a
->addr
!= b
->addr
||
1511 a
->or_port
!= b
->or_port
||
1512 a
->dir_port
!= b
->dir_port
||
1513 a
->is_authority
!= b
->is_authority
||
1514 a
->is_exit
!= b
->is_exit
||
1515 a
->is_stable
!= b
->is_stable
||
1516 a
->is_fast
!= b
->is_fast
||
1517 a
->is_flagged_running
!= b
->is_flagged_running
||
1518 a
->is_named
!= b
->is_named
||
1519 a
->is_unnamed
!= b
->is_unnamed
||
1520 a
->is_valid
!= b
->is_valid
||
1521 a
->is_possible_guard
!= b
->is_possible_guard
||
1522 a
->is_bad_exit
!= b
->is_bad_exit
||
1523 a
->is_hs_dir
!= b
->is_hs_dir
;
1524 // XXXX this function needs a huge refactoring; it has gotten out
1525 // XXXX of sync with routerstatus_t, and it will do so again.
1528 /** Notify controllers of any router status entries that changed between
1529 * <b>old_c</b> and <b>new_c</b>. */
1531 notify_control_networkstatus_changed(const networkstatus_t
*old_c
,
1532 const networkstatus_t
*new_c
)
1534 smartlist_t
*changed
;
1538 /* tell the controller exactly which relays are still listed, as well
1539 * as what they're listed as */
1540 control_event_newconsensus(new_c
);
1542 if (!control_event_is_interesting(EVENT_NS
))
1546 control_event_networkstatus_changed(new_c
->routerstatus_list
);
1549 changed
= smartlist_new();
1551 SMARTLIST_FOREACH_JOIN(
1552 old_c
->routerstatus_list
, const routerstatus_t
*, rs_old
,
1553 new_c
->routerstatus_list
, const routerstatus_t
*, rs_new
,
1554 tor_memcmp(rs_old
->identity_digest
,
1555 rs_new
->identity_digest
, DIGEST_LEN
),
1556 smartlist_add(changed
, (void*) rs_new
)) {
1557 if (routerstatus_has_changed(rs_old
, rs_new
))
1558 smartlist_add(changed
, (void*)rs_new
);
1559 } SMARTLIST_FOREACH_JOIN_END(rs_old
, rs_new
);
1561 control_event_networkstatus_changed(changed
);
1562 smartlist_free(changed
);
1565 /* Called when the consensus has changed from old_c to new_c. */
1567 notify_networkstatus_changed(const networkstatus_t
*old_c
,
1568 const networkstatus_t
*new_c
)
1570 notify_control_networkstatus_changed(old_c
, new_c
);
1571 scheduler_notify_networkstatus_changed(old_c
, new_c
);
1574 /** Copy all the ancillary information (like router download status and so on)
1575 * from <b>old_c</b> to <b>new_c</b>. */
1577 networkstatus_copy_old_consensus_info(networkstatus_t
*new_c
,
1578 const networkstatus_t
*old_c
)
1582 if (!old_c
|| !smartlist_len(old_c
->routerstatus_list
))
1585 SMARTLIST_FOREACH_JOIN(old_c
->routerstatus_list
, routerstatus_t
*, rs_old
,
1586 new_c
->routerstatus_list
, routerstatus_t
*, rs_new
,
1587 tor_memcmp(rs_old
->identity_digest
,
1588 rs_new
->identity_digest
, DIGEST_LEN
),
1590 /* Okay, so we're looking at the same identity. */
1591 rs_new
->last_dir_503_at
= rs_old
->last_dir_503_at
;
1593 if (tor_memeq(rs_old
->descriptor_digest
, rs_new
->descriptor_digest
,
1595 /* And the same descriptor too! */
1596 memcpy(&rs_new
->dl_status
, &rs_old
->dl_status
,sizeof(download_status_t
));
1598 } SMARTLIST_FOREACH_JOIN_END(rs_old
, rs_new
);
1601 #ifdef TOR_UNIT_TESTS
1602 /**Accept a <b>flavor</b> consensus <b>c</b> without any additional
1603 * validation. This is exclusively for unit tests.
1604 * We copy any ancillary information from a pre-existing consensus
1605 * and then free the current one and replace it with the newly
1606 * provided instance. Returns -1 on unrecognized flavor, 0 otherwise.
1609 networkstatus_set_current_consensus_from_ns(networkstatus_t
*c
,
1612 int flav
= networkstatus_parse_flavor_name(flavor
);
1615 if (current_ns_consensus
) {
1616 networkstatus_copy_old_consensus_info(c
, current_ns_consensus
);
1617 networkstatus_vote_free(current_ns_consensus
);
1619 current_ns_consensus
= c
;
1621 case FLAV_MICRODESC
:
1622 if (current_md_consensus
) {
1623 networkstatus_copy_old_consensus_info(c
, current_md_consensus
);
1624 networkstatus_vote_free(current_md_consensus
);
1626 current_md_consensus
= c
;
1629 return current_md_consensus
? 0 : -1;
1631 #endif /* defined(TOR_UNIT_TESTS) */
1634 * Return true if any option is set in <b>options</b> to make us behave
1637 * XXXX If we need this elsewhere at any point, we should make it nonstatic
1638 * XXXX and move it into another file.
1641 any_client_port_set(const or_options_t
*options
)
1643 return (options
->SocksPort_set
||
1644 options
->TransPort_set
||
1645 options
->NATDPort_set
||
1646 options
->ControlPort_set
||
1647 options
->DNSPort_set
||
1648 options
->HTTPTunnelPort_set
);
1652 * Helper for handle_missing_protocol_warning: handles either the
1653 * client case (if <b>is_client</b> is set) or the server case otherwise.
1656 handle_missing_protocol_warning_impl(const networkstatus_t
*c
,
1659 char *protocol_warning
= NULL
;
1661 int should_exit
= networkstatus_check_required_protocols(c
,
1664 if (protocol_warning
) {
1665 tor_log(should_exit
? LOG_ERR
: LOG_WARN
,
1667 "%s", protocol_warning
);
1670 tor_assert_nonfatal(protocol_warning
);
1672 tor_free(protocol_warning
);
1677 /** Called when we have received a networkstatus <b>c</b>. If there are
1678 * any _required_ protocols we are missing, log an error and exit
1679 * immediately. If there are any _recommended_ protocols we are missing,
1682 handle_missing_protocol_warning(const networkstatus_t
*c
,
1683 const or_options_t
*options
)
1685 const int is_server
= server_mode(options
);
1686 const int is_client
= any_client_port_set(options
) || !is_server
;
1689 handle_missing_protocol_warning_impl(c
, 0);
1691 handle_missing_protocol_warning_impl(c
, 1);
1694 /** Try to replace the current cached v3 networkstatus with the one in
1695 * <b>consensus</b>. If we don't have enough certificates to validate it,
1696 * store it in consensus_waiting_for_certs and launch a certificate fetch.
1698 * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
1699 * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
1700 * already received, but we were waiting for certificates on it. If flags &
1701 * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
1702 * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
1703 * consensus, even if it comes from many days in the past.
1705 * If source_dir is non-NULL, it's the identity digest for a directory that
1706 * we've just successfully retrieved a consensus or certificates from, so try
1707 * it first to fetch any missing certificates.
1709 * Return 0 on success, <0 on failure. On failure, caller should increment
1710 * the failure count as appropriate.
1712 * We return -1 for mild failures that don't need to be reported to the
1713 * user, and -2 for more serious problems.
1716 networkstatus_set_current_consensus(const char *consensus
,
1719 const char *source_dir
)
1721 networkstatus_t
*c
=NULL
;
1723 time_t now
= time(NULL
);
1724 const or_options_t
*options
= get_options();
1725 char *unverified_fname
= NULL
, *consensus_fname
= NULL
;
1726 int flav
= networkstatus_parse_flavor_name(flavor
);
1727 const unsigned from_cache
= flags
& NSSET_FROM_CACHE
;
1728 const unsigned was_waiting_for_certs
= flags
& NSSET_WAS_WAITING_FOR_CERTS
;
1729 const unsigned dl_certs
= !(flags
& NSSET_DONT_DOWNLOAD_CERTS
);
1730 const unsigned accept_obsolete
= flags
& NSSET_ACCEPT_OBSOLETE
;
1731 const unsigned require_flavor
= flags
& NSSET_REQUIRE_FLAVOR
;
1732 const common_digests_t
*current_digests
= NULL
;
1733 consensus_waiting_for_certs_t
*waiting
= NULL
;
1734 time_t current_valid_after
= 0;
1735 int free_consensus
= 1; /* Free 'c' at the end of the function */
1736 int old_ewma_enabled
;
1737 int checked_protocols_already
= 0;
1740 /* XXXX we don't handle unrecognized flavors yet. */
1741 log_warn(LD_BUG
, "Unrecognized consensus flavor %s", flavor
);
1745 /* Make sure it's parseable. */
1746 c
= networkstatus_parse_vote_from_string(consensus
, NULL
, NS_TYPE_CONSENSUS
);
1748 log_warn(LD_DIR
, "Unable to parse networkstatus consensus");
1753 if (from_cache
&& !was_waiting_for_certs
) {
1754 /* We previously stored this; check _now_ to make sure that version-kills
1755 * really work. This happens even before we check signatures: we did so
1756 * before when we stored this to disk. This does mean an attacker who can
1757 * write to the datadir can make us not start: such an attacker could
1758 * already harm us by replacing our guards, which would be worse. */
1759 checked_protocols_already
= 1;
1760 handle_missing_protocol_warning(c
, options
);
1763 if ((int)c
->flavor
!= flav
) {
1764 /* This wasn't the flavor we thought we were getting. */
1765 if (require_flavor
) {
1766 log_warn(LD_DIR
, "Got consensus with unexpected flavor %s (wanted %s)",
1767 networkstatus_get_flavor_name(c
->flavor
), flavor
);
1771 flavor
= networkstatus_get_flavor_name(flav
);
1774 if (flav
!= usable_consensus_flavor() &&
1775 !we_want_to_fetch_flavor(options
, flav
)) {
1776 /* This consensus is totally boring to us: we won't use it, we didn't want
1777 * it, and we won't serve it. Drop it. */
1781 if (from_cache
&& !accept_obsolete
&&
1782 c
->valid_until
< now
-OLD_ROUTER_DESC_MAX_AGE
) {
1783 log_info(LD_DIR
, "Loaded an expired consensus. Discarding.");
1787 if (!strcmp(flavor
, "ns")) {
1788 consensus_fname
= get_datadir_fname("cached-consensus");
1789 unverified_fname
= get_datadir_fname("unverified-consensus");
1790 if (current_ns_consensus
) {
1791 current_digests
= ¤t_ns_consensus
->digests
;
1792 current_valid_after
= current_ns_consensus
->valid_after
;
1794 } else if (!strcmp(flavor
, "microdesc")) {
1795 consensus_fname
= get_datadir_fname("cached-microdesc-consensus");
1796 unverified_fname
= get_datadir_fname("unverified-microdesc-consensus");
1797 if (current_md_consensus
) {
1798 current_digests
= ¤t_md_consensus
->digests
;
1799 current_valid_after
= current_md_consensus
->valid_after
;
1804 tor_snprintf(buf
, sizeof(buf
), "cached-%s-consensus", flavor
);
1805 consensus_fname
= get_datadir_fname(buf
);
1806 tor_snprintf(buf
, sizeof(buf
), "unverified-%s-consensus", flavor
);
1807 unverified_fname
= get_datadir_fname(buf
);
1808 cur
= dirserv_get_consensus(flavor
);
1810 current_digests
= &cur
->digests
;
1811 current_valid_after
= cur
->published
;
1815 if (current_digests
&&
1816 tor_memeq(&c
->digests
, current_digests
, sizeof(c
->digests
))) {
1817 /* We already have this one. That's a failure. */
1818 log_info(LD_DIR
, "Got a %s consensus we already have", flavor
);
1822 if (current_valid_after
&& c
->valid_after
<= current_valid_after
) {
1823 /* We have a newer one. There's no point in accepting this one,
1824 * even if it's great. */
1825 log_info(LD_DIR
, "Got a %s consensus at least as old as the one we have",
1830 /* Make sure it's signed enough. */
1831 if ((r
=networkstatus_check_consensus_signature(c
, 1))<0) {
1833 /* Okay, so it _might_ be signed enough if we get more certificates. */
1834 if (!was_waiting_for_certs
) {
1836 "Not enough certificates to check networkstatus consensus");
1838 if (!current_valid_after
||
1839 c
->valid_after
> current_valid_after
) {
1840 waiting
= &consensus_waiting_for_certs
[flav
];
1841 networkstatus_vote_free(waiting
->consensus
);
1842 tor_free(waiting
->body
);
1843 waiting
->consensus
= c
;
1845 waiting
->body
= tor_strdup(consensus
);
1846 waiting
->set_at
= now
;
1847 waiting
->dl_failed
= 0;
1849 write_str_to_file(unverified_fname
, consensus
, 0);
1852 authority_certs_fetch_missing(c
, now
, source_dir
);
1853 /* This case is not a success or a failure until we get the certs
1854 * or fail to get the certs. */
1857 /* Even if we had enough signatures, we'd never use this as the
1858 * latest consensus. */
1859 if (was_waiting_for_certs
&& from_cache
)
1860 if (unlink(unverified_fname
) != 0) {
1862 "Failed to unlink %s: %s",
1863 unverified_fname
, strerror(errno
));
1868 /* This can never be signed enough: Kill it. */
1869 if (!was_waiting_for_certs
) {
1870 log_warn(LD_DIR
, "Not enough good signatures on networkstatus "
1874 if (was_waiting_for_certs
&& (r
< -1) && from_cache
) {
1875 if (unlink(unverified_fname
) != 0) {
1877 "Failed to unlink %s: %s",
1878 unverified_fname
, strerror(errno
));
1885 if (!from_cache
&& flav
== usable_consensus_flavor())
1886 control_event_client_status(LOG_NOTICE
, "CONSENSUS_ARRIVED");
1888 if (!checked_protocols_already
) {
1889 handle_missing_protocol_warning(c
, options
);
1892 /* Are we missing any certificates at all? */
1893 if (r
!= 1 && dl_certs
)
1894 authority_certs_fetch_missing(c
, now
, source_dir
);
1896 const int is_usable_flavor
= flav
== usable_consensus_flavor();
1898 if (is_usable_flavor
) {
1899 notify_networkstatus_changed(networkstatus_get_latest_consensus(), c
);
1901 if (flav
== FLAV_NS
) {
1902 if (current_ns_consensus
) {
1903 networkstatus_copy_old_consensus_info(c
, current_ns_consensus
);
1904 networkstatus_vote_free(current_ns_consensus
);
1905 /* Defensive programming : we should set current_ns_consensus very soon
1906 * but we're about to call some stuff in the meantime, and leaving this
1907 * dangling pointer around has proven to be trouble. */
1908 current_ns_consensus
= NULL
;
1910 current_ns_consensus
= c
;
1911 free_consensus
= 0; /* avoid free */
1912 } else if (flav
== FLAV_MICRODESC
) {
1913 if (current_md_consensus
) {
1914 networkstatus_copy_old_consensus_info(c
, current_md_consensus
);
1915 networkstatus_vote_free(current_md_consensus
);
1916 /* more defensive programming */
1917 current_md_consensus
= NULL
;
1919 current_md_consensus
= c
;
1920 free_consensus
= 0; /* avoid free */
1923 waiting
= &consensus_waiting_for_certs
[flav
];
1924 if (waiting
->consensus
&&
1925 waiting
->consensus
->valid_after
<= c
->valid_after
) {
1926 networkstatus_vote_free(waiting
->consensus
);
1927 waiting
->consensus
= NULL
;
1928 if (consensus
!= waiting
->body
)
1929 tor_free(waiting
->body
);
1931 waiting
->body
= NULL
;
1932 waiting
->set_at
= 0;
1933 waiting
->dl_failed
= 0;
1934 if (unlink(unverified_fname
) != 0) {
1936 "Failed to unlink %s: %s",
1937 unverified_fname
, strerror(errno
));
1941 if (is_usable_flavor
) {
1942 /* The "current" consensus has just been set and it is a usable flavor so
1943 * the first thing we need to do is recalculate the voting schedule static
1944 * object so we can use the timings in there needed by some subsystems
1945 * such as hidden service and shared random. */
1946 dirvote_recalculate_timing(options
, now
);
1948 nodelist_set_consensus(c
);
1950 /* XXXXNM Microdescs: needs a non-ns variant. ???? NM*/
1951 update_consensus_networkstatus_fetch_time(now
);
1953 /* Update ewma and adjust policy if needed; first cache the old value */
1954 old_ewma_enabled
= cell_ewma_enabled();
1955 /* Change the cell EWMA settings */
1956 cell_ewma_set_scale_factor(options
, c
);
1957 /* If we just enabled ewma, set the cmux policy on all active channels */
1958 if (cell_ewma_enabled() && !old_ewma_enabled
) {
1959 channel_set_cmux_policy_everywhere(&ewma_policy
);
1960 } else if (!cell_ewma_enabled() && old_ewma_enabled
) {
1961 /* Turn it off everywhere */
1962 channel_set_cmux_policy_everywhere(NULL
);
1965 /* XXXX this call might be unnecessary here: can changing the
1966 * current consensus really alter our view of any OR's rate limits? */
1967 connection_or_update_token_buckets(get_connection_array(), options
);
1969 circuit_build_times_new_consensus_params(
1970 get_circuit_build_times_mutable(), c
);
1971 channelpadding_new_consensus_params(c
);
1974 /* Reset the failure count only if this consensus is actually valid. */
1975 if (c
->valid_after
<= now
&& now
<= c
->valid_until
) {
1976 download_status_reset(&consensus_dl_status
[flav
]);
1979 download_status_failed(&consensus_dl_status
[flav
], 0);
1982 if (we_want_to_fetch_flavor(options
, flav
)) {
1983 dirserv_set_cached_consensus_networkstatus(consensus
,
1986 c
->digest_sha3_as_signed
,
1988 if (dir_server_mode(get_options())) {
1989 consdiffmgr_add_consensus(consensus
, c
);
1994 write_str_to_file(consensus_fname
, consensus
, 0);
1997 /** If a consensus appears more than this many seconds before its declared
1998 * valid-after time, declare that our clock is skewed. */
1999 #define EARLY_CONSENSUS_NOTICE_SKEW 60
2001 if (now
< c
->valid_after
- EARLY_CONSENSUS_NOTICE_SKEW
) {
2002 char tbuf
[ISO_TIME_LEN
+1];
2004 long delta
= now
- c
->valid_after
;
2005 char *flavormsg
= NULL
;
2006 format_iso_time(tbuf
, c
->valid_after
);
2007 format_time_interval(dbuf
, sizeof(dbuf
), delta
);
2008 log_warn(LD_GENERAL
, "Our clock is %s behind the time published in the "
2009 "consensus network status document (%s UTC). Tor needs an "
2010 "accurate clock to work correctly. Please check your time and "
2011 "date settings!", dbuf
, tbuf
);
2012 tor_asprintf(&flavormsg
, "%s flavor consensus", flavor
);
2013 clock_skew_warning(NULL
, delta
, 1, LD_GENERAL
, flavormsg
, "CONSENSUS");
2014 tor_free(flavormsg
);
2017 /* We got a new consesus. Reset our md fetch fail cache */
2018 microdesc_reset_outdated_dirservers_list();
2020 router_dir_info_changed();
2025 networkstatus_vote_free(c
);
2026 tor_free(consensus_fname
);
2027 tor_free(unverified_fname
);
2031 /** Called when we have gotten more certificates: see whether we can
2032 * now verify a pending consensus.
2034 * If source_dir is non-NULL, it's the identity digest for a directory that
2035 * we've just successfully retrieved certificates from, so try it first to
2036 * fetch any missing certificates.
2039 networkstatus_note_certs_arrived(const char *source_dir
)
2042 for (i
=0; i
<N_CONSENSUS_FLAVORS
; ++i
) {
2043 consensus_waiting_for_certs_t
*waiting
= &consensus_waiting_for_certs
[i
];
2044 if (!waiting
->consensus
)
2046 if (networkstatus_check_consensus_signature(waiting
->consensus
, 0)>=0) {
2047 char *waiting_body
= waiting
->body
;
2048 if (!networkstatus_set_current_consensus(
2050 networkstatus_get_flavor_name(i
),
2051 NSSET_WAS_WAITING_FOR_CERTS
,
2053 tor_free(waiting_body
);
2059 /** If the network-status list has changed since the last time we called this
2060 * function, update the status of every routerinfo from the network-status
2061 * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
2062 * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
2065 routers_update_all_from_networkstatus(time_t now
, int dir_version
)
2067 routerlist_t
*rl
= router_get_routerlist();
2068 networkstatus_t
*consensus
= networkstatus_get_reasonably_live_consensus(now
,
2071 if (!consensus
|| dir_version
< 3) /* nothing more we should do */
2074 /* calls router_dir_info_changed() when it's done -- more routers
2075 * might be up or down now, which might affect whether there's enough
2076 * directory info. */
2077 routers_update_status_from_consensus_networkstatus(rl
->routers
, 0);
2079 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
,
2080 ri
->cache_info
.routerlist_index
= ri_sl_idx
);
2081 if (rl
->old_routers
)
2082 signed_descs_update_status_from_consensus_networkstatus(rl
->old_routers
);
2084 if (!have_warned_about_old_version
) {
2085 int is_server
= server_mode(get_options());
2086 version_status_t status
;
2087 const char *recommended
= is_server
?
2088 consensus
->server_versions
: consensus
->client_versions
;
2089 status
= tor_version_is_obsolete(VERSION
, recommended
);
2091 if (status
== VS_RECOMMENDED
) {
2092 log_info(LD_GENERAL
, "The directory authorities say my version is ok.");
2093 } else if (status
== VS_EMPTY
) {
2094 log_info(LD_GENERAL
,
2095 "The directory authorities don't recommend any versions.");
2096 } else if (status
== VS_NEW
|| status
== VS_NEW_IN_SERIES
) {
2097 if (!have_warned_about_new_version
) {
2098 log_notice(LD_GENERAL
, "This version of Tor (%s) is newer than any "
2099 "recommended version%s, according to the directory "
2100 "authorities. Recommended versions are: %s",
2102 status
== VS_NEW_IN_SERIES
? " in its series" : "",
2104 have_warned_about_new_version
= 1;
2105 control_event_general_status(LOG_WARN
, "DANGEROUS_VERSION "
2106 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
2107 VERSION
, "NEW", recommended
);
2110 log_warn(LD_GENERAL
, "Please upgrade! "
2111 "This version of Tor (%s) is %s, according to the directory "
2112 "authorities. Recommended versions are: %s",
2114 status
== VS_OLD
? "obsolete" : "not recommended",
2116 have_warned_about_old_version
= 1;
2117 control_event_general_status(LOG_WARN
, "DANGEROUS_VERSION "
2118 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
2119 VERSION
, status
== VS_OLD
? "OBSOLETE" : "UNRECOMMENDED",
2125 /** Given a list <b>routers</b> of routerinfo_t *, update each status field
2126 * according to our current consensus networkstatus. May re-order
2127 * <b>routers</b>. */
2129 routers_update_status_from_consensus_networkstatus(smartlist_t
*routers
,
2132 const or_options_t
*options
= get_options();
2133 int authdir
= authdir_mode_v3(options
);
2134 networkstatus_t
*ns
= networkstatus_get_latest_consensus();
2135 if (!ns
|| !smartlist_len(ns
->routerstatus_list
))
2138 routers_sort_by_identity(routers
);
2140 SMARTLIST_FOREACH_JOIN(ns
->routerstatus_list
, routerstatus_t
*, rs
,
2141 routers
, routerinfo_t
*, router
,
2142 tor_memcmp(rs
->identity_digest
,
2143 router
->cache_info
.identity_digest
, DIGEST_LEN
),
2146 /* Is it the same descriptor, or only the same identity? */
2147 if (tor_memeq(router
->cache_info
.signed_descriptor_digest
,
2148 rs
->descriptor_digest
, DIGEST_LEN
)) {
2149 if (ns
->valid_until
> router
->cache_info
.last_listed_as_valid_until
)
2150 router
->cache_info
.last_listed_as_valid_until
= ns
->valid_until
;
2154 /* If we _are_ an authority, we should check whether this router
2155 * is one that will cause us to need a reachability test. */
2156 routerinfo_t
*old_router
=
2157 router_get_mutable_by_digest(router
->cache_info
.identity_digest
);
2158 if (old_router
!= router
) {
2159 router
->needs_retest_if_added
=
2160 dirserv_should_launch_reachability_test(router
, old_router
);
2163 if (reset_failures
) {
2164 download_status_reset(&rs
->dl_status
);
2166 } SMARTLIST_FOREACH_JOIN_END(rs
, router
);
2168 router_dir_info_changed();
2171 /** Given a list of signed_descriptor_t, update their fields (mainly, when
2172 * they were last listed) from the most recent consensus. */
2174 signed_descs_update_status_from_consensus_networkstatus(smartlist_t
*descs
)
2176 networkstatus_t
*ns
= current_ns_consensus
;
2180 if (!ns
->desc_digest_map
) {
2181 char dummy
[DIGEST_LEN
];
2182 /* instantiates the digest map. */
2183 memset(dummy
, 0, sizeof(dummy
));
2184 router_get_consensus_status_by_descriptor_digest(ns
, dummy
);
2186 SMARTLIST_FOREACH(descs
, signed_descriptor_t
*, d
,
2188 const routerstatus_t
*rs
= digestmap_get(ns
->desc_digest_map
,
2189 d
->signed_descriptor_digest
);
2191 if (ns
->valid_until
> d
->last_listed_as_valid_until
)
2192 d
->last_listed_as_valid_until
= ns
->valid_until
;
2197 /** Generate networkstatus lines for a single routerstatus_t object, and
2198 * return the result in a newly allocated string. Used only by controller
2199 * interface (for now.) */
2201 networkstatus_getinfo_helper_single(const routerstatus_t
*rs
)
2203 return routerstatus_format_entry(rs
, NULL
, NULL
, NS_CONTROL_PORT
, NULL
);
2206 /** Alloc and return a string describing routerstatuses for the most
2207 * recent info of each router we know about that is of purpose
2208 * <b>purpose_string</b>. Return NULL if unrecognized purpose.
2210 * Right now this function is oriented toward listing bridges (you
2211 * shouldn't use this for general-purpose routers, since those
2212 * should be listed from the consensus, not from the routers list). */
2214 networkstatus_getinfo_by_purpose(const char *purpose_string
, time_t now
)
2216 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
2218 routerlist_t
*rl
= router_get_routerlist();
2219 smartlist_t
*statuses
;
2220 uint8_t purpose
= router_purpose_from_string(purpose_string
);
2222 int bridge_auth
= authdir_mode_bridge(get_options());
2224 if (purpose
== ROUTER_PURPOSE_UNKNOWN
) {
2225 log_info(LD_DIR
, "Unrecognized purpose '%s' when listing router statuses.",
2230 statuses
= smartlist_new();
2231 SMARTLIST_FOREACH_BEGIN(rl
->routers
, routerinfo_t
*, ri
) {
2232 node_t
*node
= node_get_mutable_by_id(ri
->cache_info
.identity_digest
);
2235 if (ri
->cache_info
.published_on
< cutoff
)
2237 if (ri
->purpose
!= purpose
)
2239 if (bridge_auth
&& ri
->purpose
== ROUTER_PURPOSE_BRIDGE
)
2240 dirserv_set_router_is_running(ri
, now
);
2241 /* then generate and write out status lines for each of them */
2242 set_routerstatus_from_routerinfo(&rs
, node
, ri
, now
, 0);
2243 smartlist_add(statuses
, networkstatus_getinfo_helper_single(&rs
));
2244 } SMARTLIST_FOREACH_END(ri
);
2246 answer
= smartlist_join_strings(statuses
, "", 0, NULL
);
2247 SMARTLIST_FOREACH(statuses
, char *, cp
, tor_free(cp
));
2248 smartlist_free(statuses
);
2252 /** Write out router status entries for all our bridge descriptors. */
2254 networkstatus_dump_bridge_status_to_file(time_t now
)
2256 char *status
= networkstatus_getinfo_by_purpose("bridge", now
);
2257 const or_options_t
*options
= get_options();
2259 char *thresholds
= NULL
;
2260 char *published_thresholds_and_status
= NULL
;
2261 char published
[ISO_TIME_LEN
+1];
2262 const routerinfo_t
*me
= router_get_my_routerinfo();
2263 char fingerprint
[FINGERPRINT_LEN
+1];
2264 char *fingerprint_line
= NULL
;
2266 if (me
&& crypto_pk_get_fingerprint(me
->identity_pkey
,
2267 fingerprint
, 0) >= 0) {
2268 tor_asprintf(&fingerprint_line
, "fingerprint %s\n", fingerprint
);
2270 log_warn(LD_BUG
, "Error computing fingerprint for bridge status.");
2272 format_iso_time(published
, now
);
2273 dirserv_compute_bridge_flag_thresholds();
2274 thresholds
= dirserv_get_flag_thresholds_line();
2275 tor_asprintf(&published_thresholds_and_status
,
2276 "published %s\nflag-thresholds %s\n%s%s",
2277 published
, thresholds
, fingerprint_line
? fingerprint_line
: "",
2279 tor_asprintf(&fname
, "%s"PATH_SEPARATOR
"networkstatus-bridges",
2280 options
->DataDirectory
);
2281 write_str_to_file(fname
,published_thresholds_and_status
,0);
2282 tor_free(thresholds
);
2283 tor_free(published_thresholds_and_status
);
2286 tor_free(fingerprint_line
);
2289 /* DOCDOC get_net_param_from_list */
2291 get_net_param_from_list(smartlist_t
*net_params
, const char *param_name
,
2292 int32_t default_val
, int32_t min_val
, int32_t max_val
)
2294 int32_t res
= default_val
;
2295 size_t name_len
= strlen(param_name
);
2297 tor_assert(max_val
> min_val
);
2298 tor_assert(min_val
<= default_val
);
2299 tor_assert(max_val
>= default_val
);
2301 SMARTLIST_FOREACH_BEGIN(net_params
, const char *, p
) {
2302 if (!strcmpstart(p
, param_name
) && p
[name_len
] == '=') {
2304 long v
= tor_parse_long(p
+name_len
+1, 10, INT32_MIN
,
2305 INT32_MAX
, &ok
, NULL
);
2311 } SMARTLIST_FOREACH_END(p
);
2313 if (res
< min_val
) {
2314 log_warn(LD_DIR
, "Consensus parameter %s is too small. Got %d, raising to "
2315 "%d.", param_name
, res
, min_val
);
2317 } else if (res
> max_val
) {
2318 log_warn(LD_DIR
, "Consensus parameter %s is too large. Got %d, capping to "
2319 "%d.", param_name
, res
, max_val
);
2326 /** Return the value of a integer parameter from the networkstatus <b>ns</b>
2327 * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
2328 * latest consensus ourselves. Return <b>default_val</b> if no latest
2329 * consensus, or if it has no parameter called <b>param_name</b>.
2330 * Make sure the value parsed from the consensus is at least
2331 * <b>min_val</b> and at most <b>max_val</b> and raise/cap the parsed value
2334 networkstatus_get_param
, (const networkstatus_t
*ns
, const char *param_name
,
2335 int32_t default_val
, int32_t min_val
, int32_t max_val
))
2337 if (!ns
) /* if they pass in null, go find it ourselves */
2338 ns
= networkstatus_get_latest_consensus();
2340 if (!ns
|| !ns
->net_params
)
2343 return get_net_param_from_list(ns
->net_params
, param_name
,
2344 default_val
, min_val
, max_val
);
2348 * As networkstatus_get_param(), but check torrc_value before checking the
2349 * consensus. If torrc_value is in-range, then return it instead of the
2350 * value from the consensus.
2353 networkstatus_get_overridable_param(const networkstatus_t
*ns
,
2354 int32_t torrc_value
,
2355 const char *param_name
,
2356 int32_t default_val
,
2357 int32_t min_val
, int32_t max_val
)
2359 if (torrc_value
>= min_val
&& torrc_value
<= max_val
)
2362 return networkstatus_get_param(
2363 ns
, param_name
, default_val
, min_val
, max_val
);
2367 * Retrieve the consensus parameter that governs the
2368 * fixed-point precision of our network balancing 'bandwidth-weights'
2369 * (which are themselves integer consensus values). We divide them
2370 * by this value and ensure they never exceed this value.
2373 networkstatus_get_weight_scale_param(networkstatus_t
*ns
)
2375 return networkstatus_get_param(ns
, "bwweightscale",
2377 BW_MIN_WEIGHT_SCALE
,
2378 BW_MAX_WEIGHT_SCALE
);
2381 /** Return the value of a integer bw weight parameter from the networkstatus
2382 * <b>ns</b> whose name is <b>weight_name</b>. If <b>ns</b> is NULL, try
2383 * loading the latest consensus ourselves. Return <b>default_val</b> if no
2384 * latest consensus, or if it has no parameter called <b>weight_name</b>. */
2386 networkstatus_get_bw_weight(networkstatus_t
*ns
, const char *weight_name
,
2387 int32_t default_val
)
2391 if (!ns
) /* if they pass in null, go find it ourselves */
2392 ns
= networkstatus_get_latest_consensus();
2394 if (!ns
|| !ns
->weight_params
)
2397 max
= networkstatus_get_weight_scale_param(ns
);
2398 param
= get_net_param_from_list(ns
->weight_params
, weight_name
,
2400 BW_MAX_WEIGHT_SCALE
);
2402 log_warn(LD_DIR
, "Value of consensus weight %s was too large, capping "
2403 "to %d", weight_name
, max
);
2409 /** Return the name of the consensus flavor <b>flav</b> as used to identify
2410 * the flavor in directory documents. */
2412 networkstatus_get_flavor_name(consensus_flavor_t flav
)
2417 case FLAV_MICRODESC
:
2420 tor_fragile_assert();
2425 /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
2426 * or -1 if the flavor is not recognized. */
2428 networkstatus_parse_flavor_name(const char *flavname
)
2430 if (!strcmp(flavname
, "ns"))
2432 else if (!strcmp(flavname
, "microdesc"))
2433 return FLAV_MICRODESC
;
2438 /** Return 0 if this routerstatus is obsolete, too new, isn't
2439 * running, or otherwise not a descriptor that we would make any
2440 * use of even if we had it. Else return 1. */
2442 client_would_use_router(const routerstatus_t
*rs
, time_t now
)
2444 if (!rs
->is_flagged_running
) {
2445 /* If we had this router descriptor, we wouldn't even bother using it.
2446 * (Fetching and storing depends on by we_want_to_fetch_flavor().) */
2449 if (rs
->published_on
+ OLD_ROUTER_DESC_MAX_AGE
< now
) {
2450 /* We'd drop it immediately for being too old. */
2453 if (!routerstatus_version_supports_extend2_cells(rs
, 1)) {
2454 /* We'd ignore it because it doesn't support EXTEND2 cells.
2455 * If we don't know the version, download the descriptor so we can
2456 * check if it supports EXTEND2 cells and ntor. */
2462 /** If <b>question</b> is a string beginning with "ns/" in a format the
2463 * control interface expects for a GETINFO question, set *<b>answer</b> to a
2464 * newly-allocated string containing networkstatus lines for the appropriate
2465 * ORs. Return 0 on success, -1 on unrecognized question format. */
2467 getinfo_helper_networkstatus(control_connection_t
*conn
,
2468 const char *question
, char **answer
,
2469 const char **errmsg
)
2471 const routerstatus_t
*status
;
2474 if (!networkstatus_get_latest_consensus()) {
2475 *answer
= tor_strdup("");
2479 if (!strcmp(question
, "ns/all")) {
2480 smartlist_t
*statuses
= smartlist_new();
2481 SMARTLIST_FOREACH(networkstatus_get_latest_consensus()->routerstatus_list
,
2482 const routerstatus_t
*, rs
,
2484 smartlist_add(statuses
, networkstatus_getinfo_helper_single(rs
));
2486 *answer
= smartlist_join_strings(statuses
, "", 0, NULL
);
2487 SMARTLIST_FOREACH(statuses
, char *, cp
, tor_free(cp
));
2488 smartlist_free(statuses
);
2490 } else if (!strcmpstart(question
, "ns/id/")) {
2492 const char *q
= question
+ 6;
2496 if (base16_decode(d
, DIGEST_LEN
, q
, strlen(q
)) != DIGEST_LEN
) {
2497 *errmsg
= "Data not decodeable as hex";
2500 status
= router_get_consensus_status_by_id(d
);
2501 } else if (!strcmpstart(question
, "ns/name/")) {
2502 const node_t
*n
= node_get_by_nickname(question
+8, 0);
2503 status
= n
? n
->rs
: NULL
;
2504 } else if (!strcmpstart(question
, "ns/purpose/")) {
2505 *answer
= networkstatus_getinfo_by_purpose(question
+11, time(NULL
));
2506 return *answer
? 0 : -1;
2507 } else if (!strcmp(question
, "consensus/packages")) {
2508 const networkstatus_t
*ns
= networkstatus_get_latest_consensus();
2509 if (ns
&& ns
->package_lines
)
2510 *answer
= smartlist_join_strings(ns
->package_lines
, "\n", 0, NULL
);
2512 *errmsg
= "No consensus available";
2513 return *answer
? 0 : -1;
2514 } else if (!strcmp(question
, "consensus/valid-after") ||
2515 !strcmp(question
, "consensus/fresh-until") ||
2516 !strcmp(question
, "consensus/valid-until")) {
2517 const networkstatus_t
*ns
= networkstatus_get_latest_consensus();
2520 if (!strcmp(question
, "consensus/valid-after"))
2521 t
= ns
->valid_after
;
2522 else if (!strcmp(question
, "consensus/fresh-until"))
2523 t
= ns
->fresh_until
;
2525 t
= ns
->valid_until
;
2527 char tbuf
[ISO_TIME_LEN
+1];
2528 format_iso_time(tbuf
, t
);
2529 *answer
= tor_strdup(tbuf
);
2531 *errmsg
= "No consensus available";
2533 return *answer
? 0 : -1;
2539 *answer
= networkstatus_getinfo_helper_single(status
);
2543 /** Check whether the networkstatus <b>ns</b> lists any protocol
2544 * versions as "required" or "recommended" that we do not support. If
2545 * so, set *<b>warning_out</b> to a newly allocated string describing
2548 * Return 1 if we should exit, 0 if we should not. */
2550 networkstatus_check_required_protocols(const networkstatus_t
*ns
,
2554 const char *func
= client_mode
? "client" : "relay";
2555 const char *required
, *recommended
;
2556 char *missing
= NULL
;
2558 tor_assert(warning_out
);
2561 required
= ns
->required_client_protocols
;
2562 recommended
= ns
->recommended_client_protocols
;
2564 required
= ns
->required_relay_protocols
;
2565 recommended
= ns
->recommended_relay_protocols
;
2568 if (!protover_all_supported(required
, &missing
)) {
2569 tor_asprintf(warning_out
, "At least one protocol listed as required in "
2570 "the consensus is not supported by this version of Tor. "
2571 "You should upgrade. This version of Tor will not work as a "
2572 "%s on the Tor network. The missing protocols are: %s",
2578 if (! protover_all_supported(recommended
, &missing
)) {
2579 tor_asprintf(warning_out
, "At least one protocol listed as recommended in "
2580 "the consensus is not supported by this version of Tor. "
2581 "You should upgrade. This version of Tor will eventually "
2582 "stop working as a %s on the Tor network. The missing "
2583 "protocols are: %s",
2588 tor_assert_nonfatal(missing
== NULL
);
2593 /** Free all storage held locally in this module. */
2595 networkstatus_free_all(void)
2598 networkstatus_vote_free(current_ns_consensus
);
2599 networkstatus_vote_free(current_md_consensus
);
2600 current_md_consensus
= current_ns_consensus
= NULL
;
2602 for (i
=0; i
< N_CONSENSUS_FLAVORS
; ++i
) {
2603 consensus_waiting_for_certs_t
*waiting
= &consensus_waiting_for_certs
[i
];
2604 if (waiting
->consensus
) {
2605 networkstatus_vote_free(waiting
->consensus
);
2606 waiting
->consensus
= NULL
;
2608 tor_free(waiting
->body
);