Now that FOO_free(NULL) always works, remove checks before calling it.
[tor.git] / src / or / networkstatus.c
blobf3925f1b89ae1c1827652baf728ac493b242824a
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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file networkstatus.c
9 * \brief Functions and structures for handling network status documents as a
10 * client or cache.
13 #include "or.h"
15 /* For tracking v2 networkstatus documents. Only caches do this now. */
17 /** Map from descriptor digest of routers listed in the v2 networkstatus
18 * documents to download_status_t* */
19 static digestmap_t *v2_download_status_map = NULL;
20 /** Global list of all of the current v2 network_status documents that we know
21 * about. This list is kept sorted by published_on. */
22 static smartlist_t *networkstatus_v2_list = NULL;
23 /** True iff any member of networkstatus_v2_list has changed since the last
24 * time we called download_status_map_update_from_v2_networkstatus() */
25 static int networkstatus_v2_list_has_changed = 0;
27 /** Map from lowercase nickname to identity digest of named server, if any. */
28 static strmap_t *named_server_map = NULL;
29 /** Map from lowercase nickname to (void*)1 for all names that are listed
30 * as unnamed for some server in the consensus. */
31 static strmap_t *unnamed_server_map = NULL;
33 /** Most recently received and validated v3 consensus network status. */
34 static networkstatus_t *current_consensus = NULL;
36 /** A v3 consensus networkstatus that we've received, but which we don't
37 * have enough certificates to be happy about. */
38 typedef struct consensus_waiting_for_certs_t {
39 /** The consensus itself. */
40 networkstatus_t *consensus;
41 /** The encoded version of the consensus, nul-terminated. */
42 char *body;
43 /** When did we set the current value of consensus_waiting_for_certs? If
44 * this is too recent, we shouldn't try to fetch a new consensus for a
45 * little while, to give ourselves time to get certificates for this one. */
46 time_t set_at;
47 /** Set to 1 if we've been holding on to it for so long we should maybe
48 * treat it as being bad. */
49 int dl_failed;
50 } consensus_waiting_for_certs_t;
52 static consensus_waiting_for_certs_t
53 consensus_waiting_for_certs[N_CONSENSUS_FLAVORS];
55 /** The last time we tried to download a networkstatus, or 0 for "never". We
56 * use this to rate-limit download attempts for directory caches (including
57 * mirrors). Clients don't use this now. */
58 static time_t last_networkstatus_download_attempted = 0;
60 /** A time before which we shouldn't try to replace the current consensus:
61 * this will be at some point after the next consensus becomes valid, but
62 * before the current consensus becomes invalid. */
63 static time_t time_to_download_next_consensus = 0;
64 /** Download status for the current consensus networkstatus. */
65 static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS];
67 /** True iff we have logged a warning about this OR's version being older than
68 * listed by the authorities. */
69 static int have_warned_about_old_version = 0;
70 /** True iff we have logged a warning about this OR's version being newer than
71 * listed by the authorities. */
72 static int have_warned_about_new_version = 0;
74 static void download_status_map_update_from_v2_networkstatus(void);
75 static void routerstatus_list_update_named_server_map(void);
77 /** Forget that we've warned about anything networkstatus-related, so we will
78 * give fresh warnings if the same behavior happens again. */
79 void
80 networkstatus_reset_warnings(void)
82 if (current_consensus) {
83 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
84 routerstatus_t *, rs,
85 rs->name_lookup_warned = 0);
88 have_warned_about_old_version = 0;
89 have_warned_about_new_version = 0;
92 /** Reset the descriptor download failure count on all networkstatus docs, so
93 * that we can retry any long-failed documents immediately.
95 void
96 networkstatus_reset_download_failures(void)
98 int i;
99 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
100 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
101 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
103 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
104 rs->need_to_mirror = 1;
105 }));;
107 for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
108 download_status_reset(&consensus_dl_status[i]);
109 if (v2_download_status_map) {
110 digestmap_iter_t *iter;
111 digestmap_t *map = v2_download_status_map;
112 const char *key;
113 void *val;
114 download_status_t *dls;
115 for (iter = digestmap_iter_init(map); !digestmap_iter_done(iter);
116 iter = digestmap_iter_next(map, iter) ) {
117 digestmap_iter_get(iter, &key, &val);
118 dls = val;
119 download_status_reset(dls);
124 /** Repopulate our list of network_status_t objects from the list cached on
125 * disk. Return 0 on success, -1 on failure. */
127 router_reload_v2_networkstatus(void)
129 smartlist_t *entries;
130 struct stat st;
131 char *s;
132 char *filename = get_datadir_fname("cached-status");
133 int maybe_delete = !directory_caches_v2_dir_info(get_options());
134 time_t now = time(NULL);
135 if (!networkstatus_v2_list)
136 networkstatus_v2_list = smartlist_create();
138 entries = tor_listdir(filename);
139 if (!entries) { /* dir doesn't exist */
140 tor_free(filename);
141 return 0;
142 } else if (!smartlist_len(entries) && maybe_delete) {
143 rmdir(filename);
144 tor_free(filename);
145 smartlist_free(entries);
146 return 0;
148 tor_free(filename);
149 SMARTLIST_FOREACH(entries, const char *, fn, {
150 char buf[DIGEST_LEN];
151 if (maybe_delete) {
152 filename = get_datadir_fname2("cached-status", fn);
153 remove_file_if_very_old(filename, now);
154 tor_free(filename);
155 continue;
157 if (strlen(fn) != HEX_DIGEST_LEN ||
158 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
159 log_info(LD_DIR,
160 "Skipping cached-status file with unexpected name \"%s\"",fn);
161 continue;
163 filename = get_datadir_fname2("cached-status", fn);
164 s = read_file_to_str(filename, 0, &st);
165 if (s) {
166 if (router_set_networkstatus_v2(s, st.st_mtime, NS_FROM_CACHE,
167 NULL)<0) {
168 log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
170 tor_free(s);
172 tor_free(filename);
174 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
175 smartlist_free(entries);
176 networkstatus_v2_list_clean(time(NULL));
177 routers_update_all_from_networkstatus(time(NULL), 2);
178 return 0;
181 /** Read every cached v3 consensus networkstatus from the disk. */
183 router_reload_consensus_networkstatus(void)
185 char *filename;
186 char *s;
187 struct stat st;
188 or_options_t *options = get_options();
189 const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
190 int flav;
192 /* FFFF Suppress warnings if cached consensus is bad? */
193 for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
194 char buf[128];
195 const char *flavor = networkstatus_get_flavor_name(flav);
196 if (flav == FLAV_NS) {
197 filename = get_datadir_fname("cached-consensus");
198 } else {
199 tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
200 filename = get_datadir_fname(buf);
202 s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
203 if (s) {
204 if (networkstatus_set_current_consensus(s, flavor, flags) < -1) {
205 log_warn(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
206 flavor, filename);
208 tor_free(s);
210 tor_free(filename);
212 if (flav == FLAV_NS) {
213 filename = get_datadir_fname("unverified-consensus");
214 } else {
215 tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
216 filename = get_datadir_fname(buf);
219 s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
220 if (s) {
221 if (networkstatus_set_current_consensus(s, flavor,
222 flags|NSSET_WAS_WAITING_FOR_CERTS)) {
223 log_info(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
224 flavor, filename);
226 tor_free(s);
228 tor_free(filename);
231 if (!current_consensus ||
232 (stat(options->FallbackNetworkstatusFile, &st)==0 &&
233 st.st_mtime > current_consensus->valid_after)) {
234 s = read_file_to_str(options->FallbackNetworkstatusFile,
235 RFTS_IGNORE_MISSING, NULL);
236 if (s) {
237 if (networkstatus_set_current_consensus(s, "ns",
238 flags|NSSET_ACCEPT_OBSOLETE)) {
239 log_info(LD_FS, "Couldn't load consensus networkstatus from \"%s\"",
240 options->FallbackNetworkstatusFile);
241 } else {
242 log_notice(LD_FS,
243 "Loaded fallback consensus networkstatus from \"%s\"",
244 options->FallbackNetworkstatusFile);
246 tor_free(s);
250 if (!current_consensus) {
251 if (!named_server_map)
252 named_server_map = strmap_new();
253 if (!unnamed_server_map)
254 unnamed_server_map = strmap_new();
257 update_certificate_downloads(time(NULL));
259 routers_update_all_from_networkstatus(time(NULL), 3);
261 return 0;
264 /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
265 static void
266 vote_routerstatus_free(vote_routerstatus_t *rs)
268 vote_microdesc_hash_t *h, *next;
269 if (!rs)
270 return;
271 tor_free(rs->version);
272 tor_free(rs->status.exitsummary);
273 for (h = rs->microdesc; h; h = next) {
274 tor_free(h->microdesc_hash_line);
275 next = h->next;
276 tor_free(h);
278 tor_free(rs);
281 /** Free all storage held by the routerstatus object <b>rs</b>. */
282 void
283 routerstatus_free(routerstatus_t *rs)
285 if (!rs)
286 return;
287 tor_free(rs->exitsummary);
288 tor_free(rs);
291 /** Free all storage held by the networkstatus object <b>ns</b>. */
292 void
293 networkstatus_v2_free(networkstatus_v2_t *ns)
295 if (!ns)
296 return;
297 tor_free(ns->source_address);
298 tor_free(ns->contact);
299 if (ns->signing_key)
300 crypto_free_pk_env(ns->signing_key);
301 tor_free(ns->client_versions);
302 tor_free(ns->server_versions);
303 if (ns->entries) {
304 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
305 routerstatus_free(rs));
306 smartlist_free(ns->entries);
308 tor_free(ns);
311 /** Free all storage held in <b>sig</b> */
312 void
313 document_signature_free(document_signature_t *sig)
315 tor_free(sig->signature);
316 tor_free(sig);
319 /** Return a newly allocated copy of <b>sig</b> */
320 document_signature_t *
321 document_signature_dup(const document_signature_t *sig)
323 document_signature_t *r = tor_memdup(sig, sizeof(document_signature_t));
324 if (r->signature)
325 r->signature = tor_memdup(sig->signature, sig->signature_len);
326 return r;
329 /** Free all storage held in <b>ns</b>. */
330 void
331 networkstatus_vote_free(networkstatus_t *ns)
333 if (!ns)
334 return;
336 tor_free(ns->client_versions);
337 tor_free(ns->server_versions);
338 if (ns->known_flags) {
339 SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
340 smartlist_free(ns->known_flags);
342 if (ns->net_params) {
343 SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
344 smartlist_free(ns->net_params);
346 if (ns->supported_methods) {
347 SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
348 smartlist_free(ns->supported_methods);
350 if (ns->voters) {
351 SMARTLIST_FOREACH_BEGIN(ns->voters, networkstatus_voter_info_t *, voter) {
352 tor_free(voter->nickname);
353 tor_free(voter->address);
354 tor_free(voter->contact);
355 if (voter->sigs) {
356 SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
357 document_signature_free(sig));
358 smartlist_free(voter->sigs);
360 tor_free(voter);
361 } SMARTLIST_FOREACH_END(voter);
362 smartlist_free(ns->voters);
364 authority_cert_free(ns->cert);
366 if (ns->routerstatus_list) {
367 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
368 SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
369 vote_routerstatus_free(rs));
370 } else {
371 SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
372 routerstatus_free(rs));
375 smartlist_free(ns->routerstatus_list);
378 digestmap_free(ns->desc_digest_map, NULL);
380 memset(ns, 11, sizeof(*ns));
381 tor_free(ns);
384 /** Return the voter info from <b>vote</b> for the voter whose identity digest
385 * is <b>identity</b>, or NULL if no such voter is associated with
386 * <b>vote</b>. */
387 networkstatus_voter_info_t *
388 networkstatus_get_voter_by_id(networkstatus_t *vote,
389 const char *identity)
391 if (!vote || !vote->voters)
392 return NULL;
393 SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
394 if (!memcmp(voter->identity_digest, identity, DIGEST_LEN))
395 return voter);
396 return NULL;
399 /** Check whether the signature <b>sig</b> is correctly signed with the
400 * signing key in <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
401 * signing key; otherwise set the good_signature or bad_signature flag on
402 * <b>voter</b>, and return 0. */
404 networkstatus_check_document_signature(const networkstatus_t *consensus,
405 document_signature_t *sig,
406 const authority_cert_t *cert)
408 char key_digest[DIGEST_LEN];
409 const int dlen = sig->alg == DIGEST_SHA1 ? DIGEST_LEN : DIGEST256_LEN;
410 char *signed_digest;
411 size_t signed_digest_len;
413 if (crypto_pk_get_digest(cert->signing_key, key_digest)<0)
414 return -1;
415 if (memcmp(sig->signing_key_digest, key_digest, DIGEST_LEN) ||
416 memcmp(sig->identity_digest, cert->cache_info.identity_digest,
417 DIGEST_LEN))
418 return -1;
420 signed_digest_len = crypto_pk_keysize(cert->signing_key);
421 signed_digest = tor_malloc(signed_digest_len);
422 if (crypto_pk_public_checksig(cert->signing_key,
423 signed_digest,
424 sig->signature,
425 sig->signature_len) < dlen ||
426 memcmp(signed_digest, consensus->digests.d[sig->alg], dlen)) {
427 log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
428 sig->bad_signature = 1;
429 } else {
430 sig->good_signature = 1;
432 tor_free(signed_digest);
433 return 0;
436 /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
437 * as-yet-unchecked signature on <b>consensus</b>. Return 1 if there is a
438 * signature from every recognized authority on it, 0 if there are
439 * enough good signatures from recognized authorities on it, -1 if we might
440 * get enough good signatures by fetching missing certificates, and -2
441 * otherwise. Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
442 * about every problem; if warn is at least 1, warn only if we can't get
443 * enough signatures; if warn is negative, log nothing at all. */
445 networkstatus_check_consensus_signature(networkstatus_t *consensus,
446 int warn)
448 int n_good = 0;
449 int n_missing_key = 0;
450 int n_bad = 0;
451 int n_unknown = 0;
452 int n_no_signature = 0;
453 int n_v3_authorities = get_n_authorities(V3_AUTHORITY);
454 int n_required = n_v3_authorities/2 + 1;
455 smartlist_t *need_certs_from = smartlist_create();
456 smartlist_t *unrecognized = smartlist_create();
457 smartlist_t *missing_authorities = smartlist_create();
458 int severity;
459 time_t now = time(NULL);
461 tor_assert(consensus->type == NS_TYPE_CONSENSUS);
463 SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *,
464 voter) {
465 int good_here = 0;
466 int bad_here = 0;
467 int missing_key_here = 0;
468 SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
469 if (!sig->good_signature && !sig->bad_signature &&
470 sig->signature) {
471 /* we can try to check the signature. */
472 int is_v3_auth = trusteddirserver_get_by_v3_auth_digest(
473 sig->identity_digest) != NULL;
474 authority_cert_t *cert =
475 authority_cert_get_by_digests(sig->identity_digest,
476 sig->signing_key_digest);
477 tor_assert(!memcmp(sig->identity_digest, voter->identity_digest,
478 DIGEST_LEN));
480 if (!is_v3_auth) {
481 smartlist_add(unrecognized, voter);
482 ++n_unknown;
483 continue;
484 } else if (!cert || cert->expires < now) {
485 smartlist_add(need_certs_from, voter);
486 ++missing_key_here;
487 continue;
489 if (networkstatus_check_document_signature(consensus, sig, cert) < 0) {
490 smartlist_add(need_certs_from, voter);
491 ++missing_key_here;
492 continue;
495 if (sig->good_signature)
496 ++good_here;
497 else if (sig->bad_signature)
498 ++bad_here;
499 } SMARTLIST_FOREACH_END(sig);
500 if (good_here)
501 ++n_good;
502 else if (bad_here)
503 ++n_bad;
504 else if (missing_key_here)
505 ++n_missing_key;
506 else
507 ++n_no_signature;
508 } SMARTLIST_FOREACH_END(voter);
510 /* Now see whether we're missing any voters entirely. */
511 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
512 trusted_dir_server_t *, ds,
514 if ((ds->type & V3_AUTHORITY) &&
515 !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
516 smartlist_add(missing_authorities, ds);
519 if (warn > 1 || (warn >= 0 && n_good < n_required))
520 severity = LOG_WARN;
521 else
522 severity = LOG_INFO;
524 if (warn >= 0) {
525 SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
527 log_info(LD_DIR, "Consensus includes unrecognized authority '%s' "
528 "at %s:%d (contact %s; identity %s)",
529 voter->nickname, voter->address, (int)voter->dir_port,
530 voter->contact?voter->contact:"n/a",
531 hex_str(voter->identity_digest, DIGEST_LEN));
533 SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
535 log_info(LD_DIR, "Looks like we need to download a new certificate "
536 "from authority '%s' at %s:%d (contact %s; identity %s)",
537 voter->nickname, voter->address, (int)voter->dir_port,
538 voter->contact?voter->contact:"n/a",
539 hex_str(voter->identity_digest, DIGEST_LEN));
541 SMARTLIST_FOREACH(missing_authorities, trusted_dir_server_t *, ds,
543 log_info(LD_DIR, "Consensus does not include configured "
544 "authority '%s' at %s:%d (identity %s)",
545 ds->nickname, ds->address, (int)ds->dir_port,
546 hex_str(ds->v3_identity_digest, DIGEST_LEN));
548 log(severity, LD_DIR,
549 "%d unknown, %d missing key, %d good, %d bad, %d no signature, "
550 "%d required", n_unknown, n_missing_key, n_good, n_bad,
551 n_no_signature, n_required);
554 smartlist_free(unrecognized);
555 smartlist_free(need_certs_from);
556 smartlist_free(missing_authorities);
558 if (n_good == n_v3_authorities)
559 return 1;
560 else if (n_good >= n_required)
561 return 0;
562 else if (n_good + n_missing_key >= n_required)
563 return -1;
564 else
565 return -2;
568 /** Helper: return a newly allocated string containing the name of the filename
569 * where we plan to cache the network status with the given identity digest. */
570 char *
571 networkstatus_get_cache_filename(const char *identity_digest)
573 char fp[HEX_DIGEST_LEN+1];
574 base16_encode(fp, HEX_DIGEST_LEN+1, identity_digest, DIGEST_LEN);
575 return get_datadir_fname2("cached-status", fp);
578 /** Helper for smartlist_sort: Compare two networkstatus objects by
579 * publication date. */
580 static int
581 _compare_networkstatus_v2_published_on(const void **_a, const void **_b)
583 const networkstatus_v2_t *a = *_a, *b = *_b;
584 if (a->published_on < b->published_on)
585 return -1;
586 else if (a->published_on > b->published_on)
587 return 1;
588 else
589 return 0;
592 /** Add the parsed v2 networkstatus in <b>ns</b> (with original document in
593 * <b>s</b>) to the disk cache (and the in-memory directory server cache) as
594 * appropriate. */
595 static int
596 add_networkstatus_to_cache(const char *s,
597 v2_networkstatus_source_t source,
598 networkstatus_v2_t *ns)
600 if (source != NS_FROM_CACHE) {
601 char *fn = networkstatus_get_cache_filename(ns->identity_digest);
602 if (write_str_to_file(fn, s, 0)<0) {
603 log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
605 tor_free(fn);
608 if (directory_caches_v2_dir_info(get_options()))
609 dirserv_set_cached_networkstatus_v2(s,
610 ns->identity_digest,
611 ns->published_on);
613 return 0;
616 /** How far in the future do we allow a network-status to get before removing
617 * it? (seconds) */
618 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
620 /** Given a string <b>s</b> containing a network status that we received at
621 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
622 * store it, and put it into our cache as necessary.
624 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
625 * own networkstatus_t (if we're an authoritative directory server).
627 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
628 * cache.
630 * If <b>requested_fingerprints</b> is provided, it must contain a list of
631 * uppercased identity fingerprints. Do not update any networkstatus whose
632 * fingerprint is not on the list; after updating a networkstatus, remove its
633 * fingerprint from the list.
635 * Return 0 on success, -1 on failure.
637 * Callers should make sure that routers_update_all_from_networkstatus() is
638 * invoked after this function succeeds.
641 router_set_networkstatus_v2(const char *s, time_t arrived_at,
642 v2_networkstatus_source_t source,
643 smartlist_t *requested_fingerprints)
645 networkstatus_v2_t *ns;
646 int i, found;
647 time_t now;
648 int skewed = 0;
649 trusted_dir_server_t *trusted_dir = NULL;
650 const char *source_desc = NULL;
651 char fp[HEX_DIGEST_LEN+1];
652 char published[ISO_TIME_LEN+1];
654 if (!directory_caches_v2_dir_info(get_options()))
655 return 0; /* Don't bother storing it. */
657 ns = networkstatus_v2_parse_from_string(s);
658 if (!ns) {
659 log_warn(LD_DIR, "Couldn't parse network status.");
660 return -1;
662 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
663 if (!(trusted_dir =
664 router_get_trusteddirserver_by_digest(ns->identity_digest)) ||
665 !(trusted_dir->type & V2_AUTHORITY)) {
666 log_info(LD_DIR, "Network status was signed, but not by an authoritative "
667 "directory we recognize.");
668 source_desc = fp;
669 } else {
670 source_desc = trusted_dir->description;
672 now = time(NULL);
673 if (arrived_at > now)
674 arrived_at = now;
676 ns->received_on = arrived_at;
678 format_iso_time(published, ns->published_on);
680 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
681 char dbuf[64];
682 long delta = now - ns->published_on;
683 format_time_interval(dbuf, sizeof(dbuf), delta);
684 log_warn(LD_GENERAL, "Network status from %s was published %s in the "
685 "future (%s GMT). Check your time and date settings! "
686 "Not caching.",
687 source_desc, dbuf, published);
688 control_event_general_status(LOG_WARN,
689 "CLOCK_SKEW MIN_SKEW=%ld SOURCE=NETWORKSTATUS:%s:%d",
690 delta, ns->source_address, ns->source_dirport);
691 skewed = 1;
694 if (!networkstatus_v2_list)
695 networkstatus_v2_list = smartlist_create();
697 if ( (source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) &&
698 router_digest_is_me(ns->identity_digest)) {
699 /* Don't replace our own networkstatus when we get it from somebody else.*/
700 networkstatus_v2_free(ns);
701 return 0;
704 if (requested_fingerprints) {
705 if (smartlist_string_isin(requested_fingerprints, fp)) {
706 smartlist_string_remove(requested_fingerprints, fp);
707 } else {
708 if (source != NS_FROM_DIR_ALL) {
709 char *requested =
710 smartlist_join_strings(requested_fingerprints," ",0,NULL);
711 log_warn(LD_DIR,
712 "We received a network status with a fingerprint (%s) that we "
713 "never requested. (We asked for: %s.) Dropping.",
714 fp, requested);
715 tor_free(requested);
716 return 0;
721 if (!trusted_dir) {
722 if (!skewed) {
723 /* We got a non-trusted networkstatus, and we're a directory cache.
724 * This means that we asked an authority, and it told us about another
725 * authority we didn't recognize. */
726 log_info(LD_DIR,
727 "We do not recognize authority (%s) but we are willing "
728 "to cache it.", fp);
729 add_networkstatus_to_cache(s, source, ns);
730 networkstatus_v2_free(ns);
732 return 0;
735 found = 0;
736 for (i=0; i < smartlist_len(networkstatus_v2_list); ++i) {
737 networkstatus_v2_t *old_ns = smartlist_get(networkstatus_v2_list, i);
739 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
740 if (!memcmp(old_ns->networkstatus_digest,
741 ns->networkstatus_digest, DIGEST_LEN)) {
742 /* Same one we had before. */
743 networkstatus_v2_free(ns);
744 tor_assert(trusted_dir);
745 log_info(LD_DIR,
746 "Not replacing network-status from %s (published %s); "
747 "we already have it.",
748 trusted_dir->description, published);
749 if (old_ns->received_on < arrived_at) {
750 if (source != NS_FROM_CACHE) {
751 char *fn;
752 fn = networkstatus_get_cache_filename(old_ns->identity_digest);
753 /* We use mtime to tell when it arrived, so update that. */
754 touch_file(fn);
755 tor_free(fn);
757 old_ns->received_on = arrived_at;
759 download_status_failed(&trusted_dir->v2_ns_dl_status, 0);
760 return 0;
761 } else if (old_ns->published_on >= ns->published_on) {
762 char old_published[ISO_TIME_LEN+1];
763 format_iso_time(old_published, old_ns->published_on);
764 tor_assert(trusted_dir);
765 log_info(LD_DIR,
766 "Not replacing network-status from %s (published %s);"
767 " we have a newer one (published %s) for this authority.",
768 trusted_dir->description, published,
769 old_published);
770 networkstatus_v2_free(ns);
771 download_status_failed(&trusted_dir->v2_ns_dl_status, 0);
772 return 0;
773 } else {
774 networkstatus_v2_free(old_ns);
775 smartlist_set(networkstatus_v2_list, i, ns);
776 found = 1;
777 break;
782 if (source != NS_FROM_CACHE && trusted_dir) {
783 download_status_reset(&trusted_dir->v2_ns_dl_status);
786 if (!found)
787 smartlist_add(networkstatus_v2_list, ns);
789 /** Retain any routerinfo mentioned in a V2 networkstatus for at least this
790 * long. */
791 #define V2_NETWORKSTATUS_ROUTER_LIFETIME (3*60*60)
794 time_t live_until = ns->published_on + V2_NETWORKSTATUS_ROUTER_LIFETIME;
795 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
797 signed_descriptor_t *sd =
798 router_get_by_descriptor_digest(rs->descriptor_digest);
799 if (sd) {
800 if (sd->last_listed_as_valid_until < live_until)
801 sd->last_listed_as_valid_until = live_until;
802 } else {
803 rs->need_to_mirror = 1;
808 log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
809 source == NS_FROM_CACHE?"cached from":
810 ((source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) ?
811 "downloaded from":"generated for"),
812 trusted_dir->description, published);
813 networkstatus_v2_list_has_changed = 1;
815 smartlist_sort(networkstatus_v2_list,
816 _compare_networkstatus_v2_published_on);
818 if (!skewed)
819 add_networkstatus_to_cache(s, source, ns);
821 return 0;
824 /** Remove all very-old network_status_t objects from memory and from the
825 * disk cache. */
826 void
827 networkstatus_v2_list_clean(time_t now)
829 int i;
830 if (!networkstatus_v2_list)
831 return;
833 for (i = 0; i < smartlist_len(networkstatus_v2_list); ++i) {
834 networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
835 char *fname = NULL;
836 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
837 continue;
838 /* Okay, this one is too old. Remove it from the list, and delete it
839 * from the cache. */
840 smartlist_del(networkstatus_v2_list, i--);
841 fname = networkstatus_get_cache_filename(ns->identity_digest);
842 if (file_status(fname) == FN_FILE) {
843 log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
844 unlink(fname);
846 tor_free(fname);
847 if (directory_caches_v2_dir_info(get_options())) {
848 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
850 networkstatus_v2_free(ns);
853 /* And now go through the directory cache for any cached untrusted
854 * networkstatuses and other network info. */
855 dirserv_clear_old_networkstatuses(now - MAX_NETWORKSTATUS_AGE);
856 dirserv_clear_old_v1_info(now);
859 /** Helper for bsearching a list of routerstatus_t pointers: compare a
860 * digest in the key to the identity digest of a routerstatus_t. */
862 compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
864 const char *key = _key;
865 const routerstatus_t *rs = *_member;
866 return memcmp(key, rs->identity_digest, DIGEST_LEN);
869 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
870 * NULL if none was found. */
871 routerstatus_t *
872 networkstatus_v2_find_entry(networkstatus_v2_t *ns, const char *digest)
874 return smartlist_bsearch(ns->entries, digest,
875 compare_digest_to_routerstatus_entry);
878 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
879 * NULL if none was found. */
880 routerstatus_t *
881 networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
883 return smartlist_bsearch(ns->routerstatus_list, digest,
884 compare_digest_to_routerstatus_entry);
887 /*XXXX make this static once functions are moved into this file. */
888 /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
889 * <b>digest</b>. Return value and set *<b>found_out</b> as for
890 * smartlist_bsearch_idx(). */
892 networkstatus_vote_find_entry_idx(networkstatus_t *ns,
893 const char *digest, int *found_out)
895 return smartlist_bsearch_idx(ns->routerstatus_list, digest,
896 compare_digest_to_routerstatus_entry,
897 found_out);
900 /** Return a list of the v2 networkstatus documents. */
901 const smartlist_t *
902 networkstatus_get_v2_list(void)
904 if (!networkstatus_v2_list)
905 networkstatus_v2_list = smartlist_create();
906 return networkstatus_v2_list;
909 /** Return the consensus view of the status of the router whose current
910 * <i>descriptor</i> digest is <b>digest</b>, or NULL if no such router is
911 * known. */
912 routerstatus_t *
913 router_get_consensus_status_by_descriptor_digest(const char *digest)
915 if (!current_consensus) return NULL;
916 if (!current_consensus->desc_digest_map) {
917 digestmap_t * m = current_consensus->desc_digest_map = digestmap_new();
918 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
919 routerstatus_t *, rs,
921 digestmap_set(m, rs->descriptor_digest, rs);
924 return digestmap_get(current_consensus->desc_digest_map, digest);
927 /** Given the digest of a router descriptor, return its current download
928 * status, or NULL if the digest is unrecognized. */
929 download_status_t *
930 router_get_dl_status_by_descriptor_digest(const char *d)
932 routerstatus_t *rs;
933 if ((rs = router_get_consensus_status_by_descriptor_digest(d)))
934 return &rs->dl_status;
935 if (v2_download_status_map)
936 return digestmap_get(v2_download_status_map, d);
938 return NULL;
941 /** Return the consensus view of the status of the router whose identity
942 * digest is <b>digest</b>, or NULL if we don't know about any such router. */
943 routerstatus_t *
944 router_get_consensus_status_by_id(const char *digest)
946 if (!current_consensus)
947 return NULL;
948 return smartlist_bsearch(current_consensus->routerstatus_list, digest,
949 compare_digest_to_routerstatus_entry);
952 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
953 * the corresponding routerstatus_t, or NULL if none exists. Warn the
954 * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
955 * nickname, but the Named flag isn't set for that router. */
956 routerstatus_t *
957 router_get_consensus_status_by_nickname(const char *nickname,
958 int warn_if_unnamed)
960 char digest[DIGEST_LEN];
961 routerstatus_t *best=NULL;
962 smartlist_t *matches=NULL;
963 const char *named_id=NULL;
965 if (!current_consensus || !nickname)
966 return NULL;
968 /* Is this name really a hexadecimal identity digest? */
969 if (nickname[0] == '$') {
970 if (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname+1))<0)
971 return NULL;
972 return networkstatus_vote_find_entry(current_consensus, digest);
973 } else if (strlen(nickname) == HEX_DIGEST_LEN &&
974 (base16_decode(digest, DIGEST_LEN, nickname, strlen(nickname))==0)) {
975 return networkstatus_vote_find_entry(current_consensus, digest);
978 /* Is there a server that is Named with this name? */
979 if (named_server_map)
980 named_id = strmap_get_lc(named_server_map, nickname);
981 if (named_id)
982 return networkstatus_vote_find_entry(current_consensus, named_id);
984 /* Okay; is this name listed as Unnamed? */
985 if (unnamed_server_map &&
986 strmap_get_lc(unnamed_server_map, nickname)) {
987 log_info(LD_GENERAL, "The name %s is listed as Unnamed; it is not the "
988 "canonical name of any server we know.", escaped(nickname));
989 return NULL;
992 /* This name is not canonical for any server; go through the list and
993 * see who it matches. */
994 /*XXXX This is inefficient; optimize it if it matters. */
995 matches = smartlist_create();
996 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
997 routerstatus_t *, lrs,
999 if (!strcasecmp(lrs->nickname, nickname)) {
1000 if (lrs->is_named) {
1001 tor_fragile_assert() /* This should never happen. */
1002 smartlist_free(matches);
1003 return lrs;
1004 } else {
1005 if (lrs->is_unnamed) {
1006 tor_fragile_assert(); /* nor should this. */
1007 smartlist_clear(matches);
1008 best=NULL;
1009 break;
1011 smartlist_add(matches, lrs);
1012 best = lrs;
1017 if (smartlist_len(matches)>1 && warn_if_unnamed) {
1018 int any_unwarned=0;
1019 SMARTLIST_FOREACH(matches, routerstatus_t *, lrs,
1021 if (! lrs->name_lookup_warned) {
1022 lrs->name_lookup_warned=1;
1023 any_unwarned=1;
1026 if (any_unwarned) {
1027 log_warn(LD_CONFIG,"There are multiple matches for the nickname \"%s\","
1028 " but none is listed as named by the directory authorities. "
1029 "Choosing one arbitrarily.", nickname);
1031 } else if (warn_if_unnamed && best && !best->name_lookup_warned) {
1032 char fp[HEX_DIGEST_LEN+1];
1033 base16_encode(fp, sizeof(fp),
1034 best->identity_digest, DIGEST_LEN);
1035 log_warn(LD_CONFIG,
1036 "When looking up a status, you specified a server \"%s\" by name, "
1037 "but the directory authorities do not have any key registered for "
1038 "this nickname -- so it could be used by any server, "
1039 "not just the one you meant. "
1040 "To make sure you get the same server in the future, refer to "
1041 "it by key, as \"$%s\".", nickname, fp);
1042 best->name_lookup_warned = 1;
1044 smartlist_free(matches);
1045 return best;
1048 /** Return the identity digest that's mapped to officially by
1049 * <b>nickname</b>. */
1050 const char *
1051 networkstatus_get_router_digest_by_nickname(const char *nickname)
1053 if (!named_server_map)
1054 return NULL;
1055 return strmap_get_lc(named_server_map, nickname);
1058 /** Return true iff <b>nickname</b> is disallowed from being the nickname
1059 * of any server. */
1061 networkstatus_nickname_is_unnamed(const char *nickname)
1063 if (!unnamed_server_map)
1064 return 0;
1065 return strmap_get_lc(unnamed_server_map, nickname) != NULL;
1068 /** How frequently do directory authorities re-download fresh networkstatus
1069 * documents? */
1070 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
1072 /** How frequently do non-authority directory caches re-download fresh
1073 * networkstatus documents? */
1074 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
1076 /** We are a directory server, and so cache network_status documents.
1077 * Initiate downloads as needed to update them. For v2 authorities,
1078 * this means asking each trusted directory for its network-status.
1079 * For caches, this means asking a random v2 authority for all
1080 * network-statuses.
1082 static void
1083 update_v2_networkstatus_cache_downloads(time_t now)
1085 int authority = authdir_mode_v2(get_options());
1086 int interval =
1087 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
1088 const smartlist_t *trusted_dir_servers = router_get_trusted_dir_servers();
1090 if (last_networkstatus_download_attempted + interval >= now)
1091 return;
1093 last_networkstatus_download_attempted = now;
1095 if (authority) {
1096 /* An authority launches a separate connection for everybody. */
1097 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds)
1099 char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
1100 tor_addr_t addr;
1101 if (!(ds->type & V2_AUTHORITY))
1102 continue;
1103 if (router_digest_is_me(ds->digest))
1104 continue;
1105 tor_addr_from_ipv4h(&addr, ds->addr);
1106 /* Is this quite sensible with IPv6 or multiple addresses? */
1107 if (connection_get_by_type_addr_port_purpose(
1108 CONN_TYPE_DIR, &addr, ds->dir_port,
1109 DIR_PURPOSE_FETCH_V2_NETWORKSTATUS)) {
1110 /* XXX the above dir_port won't be accurate if we're
1111 * doing a tunneled conn. In that case it should be or_port.
1112 * How to guess from here? Maybe make the function less general
1113 * and have it know that it's looking for dir conns. -RD */
1114 /* Only directory caches download v2 networkstatuses, and they
1115 * don't use tunneled connections. I think it's okay to ignore
1116 * this. */
1117 continue;
1119 strlcpy(resource, "fp/", sizeof(resource));
1120 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
1121 strlcat(resource, ".z", sizeof(resource));
1122 directory_initiate_command_routerstatus(
1123 &ds->fake_status, DIR_PURPOSE_FETCH_V2_NETWORKSTATUS,
1124 ROUTER_PURPOSE_GENERAL,
1125 0, /* Not private */
1126 resource,
1127 NULL, 0 /* No payload. */,
1128 0 /* No I-M-S. */);
1130 SMARTLIST_FOREACH_END(ds);
1131 } else {
1132 /* A non-authority cache launches one connection to a random authority. */
1133 /* (Check whether we're currently fetching network-status objects.) */
1134 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
1135 DIR_PURPOSE_FETCH_V2_NETWORKSTATUS))
1136 directory_get_from_dirserver(DIR_PURPOSE_FETCH_V2_NETWORKSTATUS,
1137 ROUTER_PURPOSE_GENERAL, "all.z",
1138 PDS_RETRY_IF_NO_SERVERS);
1142 /** How many times will we try to fetch a consensus before we give up? */
1143 #define CONSENSUS_NETWORKSTATUS_MAX_DL_TRIES 8
1144 /** How long will we hang onto a possibly live consensus for which we're
1145 * fetching certs before we check whether there is a better one? */
1146 #define DELAY_WHILE_FETCHING_CERTS (20*60)
1148 /** If we want to download a fresh consensus, launch a new download as
1149 * appropriate. */
1150 static void
1151 update_consensus_networkstatus_downloads(time_t now)
1153 or_options_t *options = get_options();
1154 int i;
1155 if (!networkstatus_get_live_consensus(now))
1156 time_to_download_next_consensus = now; /* No live consensus? Get one now!*/
1157 if (time_to_download_next_consensus > now)
1158 return; /* Wait until the current consensus is older. */
1159 if (authdir_mode_v3(options))
1160 return; /* Authorities never fetch a consensus */
1161 /* XXXXNM Microdescs: may need to download more types. */
1162 if (!download_status_is_ready(&consensus_dl_status[FLAV_NS], now,
1163 CONSENSUS_NETWORKSTATUS_MAX_DL_TRIES))
1164 return; /* We failed downloading a consensus too recently. */
1165 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
1166 DIR_PURPOSE_FETCH_CONSENSUS))
1167 return; /* There's an in-progress download.*/
1169 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
1170 consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
1171 if (waiting->consensus) {
1172 /* XXXX make sure this doesn't delay sane downloads. */
1173 if (waiting->set_at + DELAY_WHILE_FETCHING_CERTS > now)
1174 return; /* We're still getting certs for this one. */
1175 else {
1176 if (!waiting->dl_failed) {
1177 download_status_failed(&consensus_dl_status[FLAV_NS], 0);
1178 waiting->dl_failed=1;
1184 log_info(LD_DIR, "Launching networkstatus consensus download.");
1185 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
1186 ROUTER_PURPOSE_GENERAL, NULL,
1187 PDS_RETRY_IF_NO_SERVERS);
1190 /** Called when an attempt to download a consensus fails: note that the
1191 * failure occurred, and possibly retry. */
1192 void
1193 networkstatus_consensus_download_failed(int status_code)
1195 /* XXXXNM Microdescs: may need to handle more types. */
1196 download_status_failed(&consensus_dl_status[FLAV_NS], status_code);
1197 /* Retry immediately, if appropriate. */
1198 update_consensus_networkstatus_downloads(time(NULL));
1201 /** How long do we (as a cache) wait after a consensus becomes non-fresh
1202 * before trying to fetch another? */
1203 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
1205 /** Update the time at which we'll consider replacing the current
1206 * consensus. */
1207 void
1208 update_consensus_networkstatus_fetch_time(time_t now)
1210 or_options_t *options = get_options();
1211 networkstatus_t *c = networkstatus_get_live_consensus(now);
1212 if (c) {
1213 long dl_interval;
1214 long interval = c->fresh_until - c->valid_after;
1215 time_t start;
1216 if (directory_fetches_dir_info_early(options)) {
1217 /* We want to cache the next one at some point after this one
1218 * is no longer fresh... */
1219 start = c->fresh_until + CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
1220 /* Some clients may need the consensus sooner than others. */
1221 if (options->FetchDirInfoExtraEarly) {
1222 dl_interval = 60;
1223 } else {
1224 /* But only in the first half-interval after that. */
1225 dl_interval = interval/2;
1227 } else {
1228 /* We're an ordinary client or a bridge. Give all the caches enough
1229 * time to download the consensus. */
1230 start = c->fresh_until + (interval*3)/4;
1231 /* But download the next one well before this one is expired. */
1232 dl_interval = ((c->valid_until - start) * 7 )/ 8;
1234 /* If we're a bridge user, make use of the numbers we just computed
1235 * to choose the rest of the interval *after* them. */
1236 if (directory_fetches_dir_info_later(options)) {
1237 /* Give all the *clients* enough time to download the consensus. */
1238 start = start + dl_interval + CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
1239 /* But try to get it before ours actually expires. */
1240 dl_interval = (c->valid_until - start) -
1241 CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
1244 if (dl_interval < 1)
1245 dl_interval = 1;
1246 /* We must not try to replace c while it's still fresh: */
1247 tor_assert(c->fresh_until < start);
1248 /* We must download the next one before c is invalid: */
1249 tor_assert(start+dl_interval < c->valid_until);
1250 time_to_download_next_consensus = start +crypto_rand_int((int)dl_interval);
1252 char tbuf1[ISO_TIME_LEN+1];
1253 char tbuf2[ISO_TIME_LEN+1];
1254 char tbuf3[ISO_TIME_LEN+1];
1255 format_local_iso_time(tbuf1, c->fresh_until);
1256 format_local_iso_time(tbuf2, c->valid_until);
1257 format_local_iso_time(tbuf3, time_to_download_next_consensus);
1258 log_info(LD_DIR, "Live consensus %s the most recent until %s and will "
1259 "expire at %s; fetching the next one at %s.",
1260 (c->fresh_until > now) ? "will be" : "was",
1261 tbuf1, tbuf2, tbuf3);
1263 } else {
1264 time_to_download_next_consensus = now;
1265 log_info(LD_DIR, "No live consensus; we should fetch one immediately.");
1270 /** Return 1 if there's a reason we shouldn't try any directory
1271 * fetches yet (e.g. we demand bridges and none are yet known).
1272 * Else return 0. */
1274 should_delay_dir_fetches(or_options_t *options)
1276 if (options->UseBridges && !any_bridge_descriptors_known()) {
1277 log_info(LD_DIR, "delaying dir fetches (no running bridges known)");
1278 return 1;
1280 return 0;
1283 /** Launch requests for networkstatus documents and authority certificates as
1284 * appropriate. */
1285 void
1286 update_networkstatus_downloads(time_t now)
1288 or_options_t *options = get_options();
1289 if (should_delay_dir_fetches(options))
1290 return;
1291 if (directory_fetches_dir_info_early(options))
1292 update_v2_networkstatus_cache_downloads(now);
1293 update_consensus_networkstatus_downloads(now);
1294 update_certificate_downloads(now);
1297 /** Launch requests as appropriate for missing directory authority
1298 * certificates. */
1299 void
1300 update_certificate_downloads(time_t now)
1302 int i;
1303 for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
1304 if (consensus_waiting_for_certs[i].consensus)
1305 authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
1306 now);
1309 authority_certs_fetch_missing(current_consensus, now);
1312 /** Return 1 if we have a consensus but we don't have enough certificates
1313 * to start using it yet. */
1315 consensus_is_waiting_for_certs(void)
1317 return consensus_waiting_for_certs[USABLE_CONSENSUS_FLAVOR].consensus
1318 ? 1 : 0;
1321 /** Return the network status with a given identity digest. */
1322 networkstatus_v2_t *
1323 networkstatus_v2_get_by_digest(const char *digest)
1325 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
1327 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
1328 return ns;
1330 return NULL;
1333 /** Return the most recent consensus that we have downloaded, or NULL if we
1334 * don't have one. */
1335 networkstatus_t *
1336 networkstatus_get_latest_consensus(void)
1338 return current_consensus;
1341 /** Return the most recent consensus that we have downloaded, or NULL if it is
1342 * no longer live. */
1343 networkstatus_t *
1344 networkstatus_get_live_consensus(time_t now)
1346 if (current_consensus &&
1347 current_consensus->valid_after <= now &&
1348 now <= current_consensus->valid_until)
1349 return current_consensus;
1350 else
1351 return NULL;
1354 /* XXXX remove this in favor of get_live_consensus. But actually,
1355 * leave something like it for bridge users, who need to not totally
1356 * lose if they spend a while fetching a new consensus. */
1357 /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
1358 * consensuses. */
1359 networkstatus_t *
1360 networkstatus_get_reasonably_live_consensus(time_t now)
1362 #define REASONABLY_LIVE_TIME (24*60*60)
1363 if (current_consensus &&
1364 current_consensus->valid_after <= now &&
1365 now <= current_consensus->valid_until+REASONABLY_LIVE_TIME)
1366 return current_consensus;
1367 else
1368 return NULL;
1371 /** Given two router status entries for the same router identity, return 1 if
1372 * if the contents have changed between them. Otherwise, return 0. */
1373 static int
1374 routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
1376 tor_assert(!memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN));
1378 return strcmp(a->nickname, b->nickname) ||
1379 memcmp(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
1380 a->addr != b->addr ||
1381 a->or_port != b->or_port ||
1382 a->dir_port != b->dir_port ||
1383 a->is_authority != b->is_authority ||
1384 a->is_exit != b->is_exit ||
1385 a->is_stable != b->is_stable ||
1386 a->is_fast != b->is_fast ||
1387 a->is_running != b->is_running ||
1388 a->is_named != b->is_named ||
1389 a->is_unnamed != b->is_unnamed ||
1390 a->is_valid != b->is_valid ||
1391 a->is_v2_dir != b->is_v2_dir ||
1392 a->is_possible_guard != b->is_possible_guard ||
1393 a->is_bad_exit != b->is_bad_exit ||
1394 a->is_bad_directory != b->is_bad_directory ||
1395 a->is_hs_dir != b->is_hs_dir ||
1396 a->version_known != b->version_known ||
1397 a->version_supports_begindir != b->version_supports_begindir ||
1398 a->version_supports_extrainfo_upload !=
1399 b->version_supports_extrainfo_upload ||
1400 a->version_supports_conditional_consensus !=
1401 b->version_supports_conditional_consensus ||
1402 a->version_supports_v3_dir != b->version_supports_v3_dir;
1405 /** Notify controllers of any router status entries that changed between
1406 * <b>old_c</b> and <b>new_c</b>. */
1407 static void
1408 notify_control_networkstatus_changed(const networkstatus_t *old_c,
1409 const networkstatus_t *new_c)
1411 smartlist_t *changed;
1412 if (old_c == new_c)
1413 return;
1415 /* tell the controller exactly which relays are still listed, as well
1416 * as what they're listed as */
1417 control_event_newconsensus(new_c);
1419 if (!control_event_is_interesting(EVENT_NS))
1420 return;
1422 if (!old_c) {
1423 control_event_networkstatus_changed(new_c->routerstatus_list);
1424 return;
1426 changed = smartlist_create();
1428 SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
1429 new_c->routerstatus_list, routerstatus_t *, rs_new,
1430 memcmp(rs_old->identity_digest,
1431 rs_new->identity_digest, DIGEST_LEN),
1432 smartlist_add(changed, rs_new)) {
1433 if (routerstatus_has_changed(rs_old, rs_new))
1434 smartlist_add(changed, rs_new);
1435 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1437 control_event_networkstatus_changed(changed);
1438 smartlist_free(changed);
1441 /** Copy all the ancillary information (like router download status and so on)
1442 * from <b>old_c</b> to <b>new_c</b>. */
1443 static void
1444 networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
1445 const networkstatus_t *old_c)
1447 if (old_c == new_c)
1448 return;
1449 if (!old_c || !smartlist_len(old_c->routerstatus_list))
1450 return;
1452 SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
1453 new_c->routerstatus_list, routerstatus_t *, rs_new,
1454 memcmp(rs_old->identity_digest,
1455 rs_new->identity_digest, DIGEST_LEN),
1456 STMT_NIL) {
1457 /* Okay, so we're looking at the same identity. */
1458 rs_new->name_lookup_warned = rs_old->name_lookup_warned;
1459 rs_new->last_dir_503_at = rs_old->last_dir_503_at;
1461 if (!memcmp(rs_old->descriptor_digest, rs_new->descriptor_digest,
1462 DIGEST_LEN)) {
1463 /* And the same descriptor too! */
1464 memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
1466 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1469 /** Try to replace the current cached v3 networkstatus with the one in
1470 * <b>consensus</b>. If we don't have enough certificates to validate it,
1471 * store it in consensus_waiting_for_certs and launch a certificate fetch.
1473 * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
1474 * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
1475 * already received, but we were waiting for certificates on it. If flags &
1476 * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
1477 * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
1478 * consensus, even if it comes from many days in the past.
1480 * Return 0 on success, <0 on failure. On failure, caller should increment
1481 * the failure count as appropriate.
1483 * We return -1 for mild failures that don't need to be reported to the
1484 * user, and -2 for more serious problems.
1487 networkstatus_set_current_consensus(const char *consensus,
1488 const char *flavor,
1489 unsigned flags)
1491 networkstatus_t *c=NULL;
1492 int r, result = -1;
1493 time_t now = time(NULL);
1494 char *unverified_fname = NULL, *consensus_fname = NULL;
1495 int flav = networkstatus_parse_flavor_name(flavor);
1496 const unsigned from_cache = flags & NSSET_FROM_CACHE;
1497 const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
1498 const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
1499 const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
1500 const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
1501 const digests_t *current_digests = NULL;
1502 consensus_waiting_for_certs_t *waiting = NULL;
1503 time_t current_valid_after = 0;
1505 if (flav < 0) {
1506 /* XXXX we don't handle unrecognized flavors yet. */
1507 log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
1508 return -2;
1511 /* Make sure it's parseable. */
1512 c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
1513 if (!c) {
1514 log_warn(LD_DIR, "Unable to parse networkstatus consensus");
1515 result = -2;
1516 goto done;
1519 if (c->flavor != flav) {
1520 /* This wasn't the flavor we thought we were getting. */
1521 if (require_flavor) {
1522 log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
1523 networkstatus_get_flavor_name(c->flavor), flavor);
1524 goto done;
1526 flav = c->flavor;
1527 flavor = networkstatus_get_flavor_name(flav);
1530 if (flav != USABLE_CONSENSUS_FLAVOR &&
1531 !directory_caches_dir_info(get_options())) {
1532 /* This consensus is totally boring to us: we won't use it, and we won't
1533 * serve it. Drop it. */
1534 result = -1;
1535 goto done;
1538 if (from_cache && !accept_obsolete &&
1539 c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
1540 /* XXX022 when we try to make fallbackconsensus work again, we should
1541 * consider taking this out. Until then, believing obsolete consensuses
1542 * is causing more harm than good. See also bug 887. */
1543 log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
1544 goto done;
1547 if (!strcmp(flavor, "ns")) {
1548 consensus_fname = get_datadir_fname("cached-consensus");
1549 unverified_fname = get_datadir_fname("unverified-consensus");
1550 if (current_consensus) {
1551 current_digests = &current_consensus->digests;
1552 current_valid_after = current_consensus->valid_after;
1554 } else {
1555 cached_dir_t *cur;
1556 char buf[128];
1557 tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
1558 consensus_fname = get_datadir_fname(buf);
1559 tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
1560 unverified_fname = get_datadir_fname(buf);
1561 cur = dirserv_get_consensus(flavor);
1562 if (cur) {
1563 current_digests = &cur->digests;
1564 current_valid_after = cur->published;
1568 if (current_digests &&
1569 !memcmp(&c->digests, current_digests, sizeof(c->digests))) {
1570 /* We already have this one. That's a failure. */
1571 log_info(LD_DIR, "Got a %s consensus we already have", flavor);
1572 goto done;
1575 if (current_valid_after && c->valid_after <= current_valid_after) {
1576 /* We have a newer one. There's no point in accepting this one,
1577 * even if it's great. */
1578 log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
1579 flavor);
1580 goto done;
1583 /* Make sure it's signed enough. */
1584 if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
1585 if (r == -1) {
1586 /* Okay, so it _might_ be signed enough if we get more certificates. */
1587 if (!was_waiting_for_certs) {
1588 log_info(LD_DIR,
1589 "Not enough certificates to check networkstatus consensus");
1591 if (!current_valid_after ||
1592 c->valid_after > current_valid_after) {
1593 waiting = &consensus_waiting_for_certs[flav];
1594 networkstatus_vote_free(waiting->consensus);
1595 tor_free(waiting->body);
1596 waiting->consensus = c;
1597 c = NULL; /* Prevent free. */
1598 waiting->body = tor_strdup(consensus);
1599 waiting->set_at = now;
1600 waiting->dl_failed = 0;
1601 if (!from_cache) {
1602 write_str_to_file(unverified_fname, consensus, 0);
1604 if (dl_certs)
1605 authority_certs_fetch_missing(c, now);
1606 /* This case is not a success or a failure until we get the certs
1607 * or fail to get the certs. */
1608 result = 0;
1609 } else {
1610 /* Even if we had enough signatures, we'd never use this as the
1611 * latest consensus. */
1612 if (was_waiting_for_certs && from_cache)
1613 unlink(unverified_fname);
1615 goto done;
1616 } else {
1617 /* This can never be signed enough: Kill it. */
1618 if (!was_waiting_for_certs) {
1619 log_warn(LD_DIR, "Not enough good signatures on networkstatus "
1620 "consensus");
1621 result = -2;
1623 if (was_waiting_for_certs && (r < -1) && from_cache)
1624 unlink(unverified_fname);
1625 goto done;
1629 if (!from_cache && flav == USABLE_CONSENSUS_FLAVOR)
1630 control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
1632 /* Are we missing any certificates at all? */
1633 if (r != 1 && dl_certs)
1634 authority_certs_fetch_missing(c, now);
1636 if (flav == USABLE_CONSENSUS_FLAVOR) {
1637 notify_control_networkstatus_changed(current_consensus, c);
1639 if (current_consensus) {
1640 networkstatus_copy_old_consensus_info(c, current_consensus);
1641 networkstatus_vote_free(current_consensus);
1645 waiting = &consensus_waiting_for_certs[flav];
1646 if (waiting->consensus &&
1647 waiting->consensus->valid_after <= c->valid_after) {
1648 networkstatus_vote_free(waiting->consensus);
1649 waiting->consensus = NULL;
1650 if (consensus != waiting->body)
1651 tor_free(waiting->body);
1652 else
1653 waiting->body = NULL;
1654 waiting->set_at = 0;
1655 waiting->dl_failed = 0;
1656 unlink(unverified_fname);
1659 /* Reset the failure count only if this consensus is actually valid. */
1660 if (c->valid_after <= now && now <= c->valid_until) {
1661 download_status_reset(&consensus_dl_status[flav]);
1662 } else {
1663 if (!from_cache)
1664 download_status_failed(&consensus_dl_status[flav], 0);
1667 if (directory_caches_dir_info(get_options())) {
1668 dirserv_set_cached_consensus_networkstatus(consensus,
1669 flavor,
1670 &c->digests,
1671 c->valid_after);
1674 if (flav == USABLE_CONSENSUS_FLAVOR) {
1675 current_consensus = c;
1676 c = NULL; /* Prevent free. */
1678 /* XXXXNM Microdescs: needs a non-ns variant. */
1679 update_consensus_networkstatus_fetch_time(now);
1680 dirvote_recalculate_timing(get_options(), now);
1681 routerstatus_list_update_named_server_map();
1684 if (!from_cache) {
1685 write_str_to_file(consensus_fname, consensus, 0);
1688 if (ftime_definitely_before(now, current_consensus->valid_after)) {
1689 char tbuf[ISO_TIME_LEN+1];
1690 char dbuf[64];
1691 long delta = now - current_consensus->valid_after;
1692 format_iso_time(tbuf, current_consensus->valid_after);
1693 format_time_interval(dbuf, sizeof(dbuf), delta);
1694 log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
1695 "consensus network status document (%s GMT). Tor needs an "
1696 "accurate clock to work correctly. Please check your time and "
1697 "date settings!", dbuf, tbuf);
1698 control_event_general_status(LOG_WARN,
1699 "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
1702 router_dir_info_changed();
1704 result = 0;
1705 done:
1706 networkstatus_vote_free(c);
1707 tor_free(consensus_fname);
1708 tor_free(unverified_fname);
1709 return result;
1712 /** Called when we have gotten more certificates: see whether we can
1713 * now verify a pending consensus. */
1714 void
1715 networkstatus_note_certs_arrived(void)
1717 int i;
1718 for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
1719 consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
1720 if (!waiting->consensus)
1721 continue;
1722 if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
1723 if (!networkstatus_set_current_consensus(
1724 waiting->body,
1725 networkstatus_get_flavor_name(i),
1726 NSSET_WAS_WAITING_FOR_CERTS)) {
1727 tor_free(waiting->body);
1733 /** If the network-status list has changed since the last time we called this
1734 * function, update the status of every routerinfo from the network-status
1735 * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
1736 * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
1738 void
1739 routers_update_all_from_networkstatus(time_t now, int dir_version)
1741 routerlist_t *rl = router_get_routerlist();
1742 networkstatus_t *consensus = networkstatus_get_live_consensus(now);
1744 if (networkstatus_v2_list_has_changed)
1745 download_status_map_update_from_v2_networkstatus();
1747 if (!consensus || dir_version < 3) /* nothing more we should do */
1748 return;
1750 /* calls router_dir_info_changed() when it's done -- more routers
1751 * might be up or down now, which might affect whether there's enough
1752 * directory info. */
1753 routers_update_status_from_consensus_networkstatus(rl->routers, 0);
1755 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
1756 ri->cache_info.routerlist_index = ri_sl_idx);
1757 if (rl->old_routers)
1758 signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
1760 if (!have_warned_about_old_version) {
1761 int is_server = server_mode(get_options());
1762 version_status_t status;
1763 const char *recommended = is_server ?
1764 consensus->server_versions : consensus->client_versions;
1765 status = tor_version_is_obsolete(VERSION, recommended);
1767 if (status == VS_RECOMMENDED) {
1768 log_info(LD_GENERAL, "The directory authorities say my version is ok.");
1769 } else if (status == VS_EMPTY) {
1770 log_info(LD_GENERAL,
1771 "The directory authorities don't recommend any versions.");
1772 } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
1773 if (!have_warned_about_new_version) {
1774 log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
1775 "recommended version%s, according to the directory "
1776 "authorities. Recommended versions are: %s",
1777 VERSION,
1778 status == VS_NEW_IN_SERIES ? " in its series" : "",
1779 recommended);
1780 have_warned_about_new_version = 1;
1781 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
1782 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
1783 VERSION, "NEW", recommended);
1785 } else {
1786 log_warn(LD_GENERAL, "Please upgrade! "
1787 "This version of Tor (%s) is %s, according to the directory "
1788 "authorities. Recommended versions are: %s",
1789 VERSION,
1790 status == VS_OLD ? "obsolete" : "not recommended",
1791 recommended);
1792 have_warned_about_old_version = 1;
1793 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
1794 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
1795 VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
1796 recommended);
1801 /** Update v2_download_status_map to contain an entry for every router
1802 * descriptor listed in the v2 networkstatuses. */
1803 static void
1804 download_status_map_update_from_v2_networkstatus(void)
1806 digestmap_t *dl_status;
1807 if (!networkstatus_v2_list)
1808 return;
1809 if (!v2_download_status_map)
1810 v2_download_status_map = digestmap_new();
1812 dl_status = digestmap_new();
1813 SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
1814 SMARTLIST_FOREACH_BEGIN(ns->entries, routerstatus_t *, rs) {
1815 const char *d = rs->descriptor_digest;
1816 download_status_t *s;
1817 if (digestmap_get(dl_status, d))
1818 continue;
1819 if (!(s = digestmap_remove(v2_download_status_map, d))) {
1820 s = tor_malloc_zero(sizeof(download_status_t));
1822 digestmap_set(dl_status, d, s);
1823 } SMARTLIST_FOREACH_END(rs);
1824 } SMARTLIST_FOREACH_END(ns);
1825 digestmap_free(v2_download_status_map, _tor_free);
1826 v2_download_status_map = dl_status;
1827 networkstatus_v2_list_has_changed = 0;
1830 /** Update our view of the list of named servers from the most recently
1831 * retrieved networkstatus consensus. */
1832 static void
1833 routerstatus_list_update_named_server_map(void)
1835 if (!current_consensus)
1836 return;
1838 strmap_free(named_server_map, _tor_free);
1839 named_server_map = strmap_new();
1840 strmap_free(unnamed_server_map, NULL);
1841 unnamed_server_map = strmap_new();
1842 SMARTLIST_FOREACH(current_consensus->routerstatus_list, routerstatus_t *, rs,
1844 if (rs->is_named) {
1845 strmap_set_lc(named_server_map, rs->nickname,
1846 tor_memdup(rs->identity_digest, DIGEST_LEN));
1848 if (rs->is_unnamed) {
1849 strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
1854 /** Given a list <b>routers</b> of routerinfo_t *, update each status field
1855 * according to our current consensus networkstatus. May re-order
1856 * <b>routers</b>. */
1857 void
1858 routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
1859 int reset_failures)
1861 trusted_dir_server_t *ds;
1862 or_options_t *options = get_options();
1863 int authdir = authdir_mode_v2(options) || authdir_mode_v3(options);
1864 int namingdir = authdir && options->NamingAuthoritativeDir;
1865 networkstatus_t *ns = current_consensus;
1866 if (!ns || !smartlist_len(ns->routerstatus_list))
1867 return;
1868 if (!networkstatus_v2_list)
1869 networkstatus_v2_list = smartlist_create();
1871 routers_sort_by_identity(routers);
1873 SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
1874 routers, routerinfo_t *, router,
1875 memcmp(rs->identity_digest,
1876 router->cache_info.identity_digest, DIGEST_LEN),
1878 /* We have no routerstatus for this router. Clear flags and skip it. */
1879 if (!namingdir)
1880 router->is_named = 0;
1881 if (!authdir) {
1882 if (router->purpose == ROUTER_PURPOSE_GENERAL)
1883 router_clear_status_flags(router);
1885 }) {
1886 /* We have a routerstatus for this router. */
1887 const char *digest = router->cache_info.identity_digest;
1889 ds = router_get_trusteddirserver_by_digest(digest);
1891 if (!namingdir) {
1892 if (rs->is_named && !strcasecmp(router->nickname, rs->nickname))
1893 router->is_named = 1;
1894 else
1895 router->is_named = 0;
1897 /* Is it the same descriptor, or only the same identity? */
1898 if (!memcmp(router->cache_info.signed_descriptor_digest,
1899 rs->descriptor_digest, DIGEST_LEN)) {
1900 if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
1901 router->cache_info.last_listed_as_valid_until = ns->valid_until;
1904 if (!authdir) {
1905 /* If we're not an authdir, believe others. */
1906 router->is_valid = rs->is_valid;
1907 router->is_running = rs->is_running;
1908 router->is_fast = rs->is_fast;
1909 router->is_stable = rs->is_stable;
1910 router->is_possible_guard = rs->is_possible_guard;
1911 router->is_exit = rs->is_exit;
1912 router->is_bad_directory = rs->is_bad_directory;
1913 router->is_bad_exit = rs->is_bad_exit;
1914 router->is_hs_dir = rs->is_hs_dir;
1916 if (router->is_running && ds) {
1917 download_status_reset(&ds->v2_ns_dl_status);
1919 if (reset_failures) {
1920 download_status_reset(&rs->dl_status);
1922 } SMARTLIST_FOREACH_JOIN_END(rs, router);
1924 /* Now update last_listed_as_valid_until from v2 networkstatuses. */
1925 /* XXXX If this is slow, we need to rethink the code. */
1926 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns, {
1927 time_t live_until = ns->published_on + V2_NETWORKSTATUS_ROUTER_LIFETIME;
1928 SMARTLIST_FOREACH_JOIN(ns->entries, routerstatus_t *, rs,
1929 routers, routerinfo_t *, ri,
1930 memcmp(rs->identity_digest,
1931 ri->cache_info.identity_digest, DIGEST_LEN),
1932 STMT_NIL) {
1933 if (!memcmp(ri->cache_info.signed_descriptor_digest,
1934 rs->descriptor_digest, DIGEST_LEN)) {
1935 if (live_until > ri->cache_info.last_listed_as_valid_until)
1936 ri->cache_info.last_listed_as_valid_until = live_until;
1938 } SMARTLIST_FOREACH_JOIN_END(rs, ri);
1941 router_dir_info_changed();
1944 /** Given a list of signed_descriptor_t, update their fields (mainly, when
1945 * they were last listed) from the most recent consensus. */
1946 void
1947 signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
1949 networkstatus_t *ns = current_consensus;
1950 if (!ns)
1951 return;
1953 if (!ns->desc_digest_map) {
1954 char dummy[DIGEST_LEN];
1955 /* instantiates the digest map. */
1956 memset(dummy, 0, sizeof(dummy));
1957 router_get_consensus_status_by_descriptor_digest(dummy);
1959 SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
1961 routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
1962 d->signed_descriptor_digest);
1963 if (rs) {
1964 if (ns->valid_until > d->last_listed_as_valid_until)
1965 d->last_listed_as_valid_until = ns->valid_until;
1970 /** Generate networkstatus lines for a single routerstatus_t object, and
1971 * return the result in a newly allocated string. Used only by controller
1972 * interface (for now.) */
1973 char *
1974 networkstatus_getinfo_helper_single(routerstatus_t *rs)
1976 char buf[RS_ENTRY_LEN+1];
1977 routerstatus_format_entry(buf, sizeof(buf), rs, NULL, NS_CONTROL_PORT);
1978 return tor_strdup(buf);
1981 /** Alloc and return a string describing routerstatuses for the most
1982 * recent info of each router we know about that is of purpose
1983 * <b>purpose_string</b>. Return NULL if unrecognized purpose.
1985 * Right now this function is oriented toward listing bridges (you
1986 * shouldn't use this for general-purpose routers, since those
1987 * should be listed from the consensus, not from the routers list). */
1988 char *
1989 networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
1991 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
1992 char *answer;
1993 routerlist_t *rl = router_get_routerlist();
1994 smartlist_t *statuses;
1995 uint8_t purpose = router_purpose_from_string(purpose_string);
1996 routerstatus_t rs;
1997 int bridge_auth = authdir_mode_bridge(get_options());
1999 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2000 log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
2001 purpose_string);
2002 return NULL;
2005 statuses = smartlist_create();
2006 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2007 if (ri->cache_info.published_on < cutoff)
2008 continue;
2009 if (ri->purpose != purpose)
2010 continue;
2011 if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
2012 dirserv_set_router_is_running(ri, now);
2013 /* then generate and write out status lines for each of them */
2014 set_routerstatus_from_routerinfo(&rs, ri, now, 0, 0, 0, 0);
2015 smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
2018 answer = smartlist_join_strings(statuses, "", 0, NULL);
2019 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
2020 smartlist_free(statuses);
2021 return answer;
2024 /** Write out router status entries for all our bridge descriptors. */
2025 void
2026 networkstatus_dump_bridge_status_to_file(time_t now)
2028 char *status = networkstatus_getinfo_by_purpose("bridge", now);
2029 or_options_t *options = get_options();
2030 size_t len = strlen(options->DataDirectory) + 32;
2031 char *fname = tor_malloc(len);
2032 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"networkstatus-bridges",
2033 options->DataDirectory);
2034 write_str_to_file(fname,status,0);
2035 tor_free(fname);
2036 tor_free(status);
2039 /** Return the value of a integer parameter from the networkstatus <b>ns</b>
2040 * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
2041 * latest consensus ourselves. Return <b>default_val</b> if no latest
2042 * consensus, or if it has no parameter called <b>param_name</b>. */
2043 int32_t
2044 networkstatus_get_param(networkstatus_t *ns, const char *param_name,
2045 int32_t default_val)
2047 size_t name_len;
2049 if (!ns) /* if they pass in null, go find it ourselves */
2050 ns = networkstatus_get_latest_consensus();
2052 if (!ns || !ns->net_params)
2053 return default_val;
2055 name_len = strlen(param_name);
2057 SMARTLIST_FOREACH_BEGIN(ns->net_params, const char *, p) {
2058 if (!strcmpstart(p, param_name) && p[name_len] == '=') {
2059 int ok=0;
2060 long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
2061 INT32_MAX, &ok, NULL);
2062 if (ok)
2063 return (int32_t) v;
2065 } SMARTLIST_FOREACH_END(p);
2067 return default_val;
2070 /** Return the name of the consensus flavor <b>flav</b> as used to identify
2071 * the flavor in directory documents. */
2072 const char *
2073 networkstatus_get_flavor_name(consensus_flavor_t flav)
2075 switch (flav) {
2076 case FLAV_NS:
2077 return "ns";
2078 case FLAV_MICRODESC:
2079 return "microdesc";
2080 default:
2081 tor_fragile_assert();
2082 return "??";
2086 /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
2087 * or -1 if the flavor is not recongized. */
2089 networkstatus_parse_flavor_name(const char *flavname)
2091 if (!strcmp(flavname, "ns"))
2092 return FLAV_NS;
2093 else if (!strcmp(flavname, "microdesc"))
2094 return FLAV_MICRODESC;
2095 else
2096 return -1;
2099 /** If <b>question</b> is a string beginning with "ns/" in a format the
2100 * control interface expects for a GETINFO question, set *<b>answer</b> to a
2101 * newly-allocated string containing networkstatus lines for the appropriate
2102 * ORs. Return 0 on success, -1 on unrecognized question format. */
2104 getinfo_helper_networkstatus(control_connection_t *conn,
2105 const char *question, char **answer)
2107 routerstatus_t *status;
2108 (void) conn;
2110 if (!current_consensus) {
2111 *answer = tor_strdup("");
2112 return 0;
2115 if (!strcmp(question, "ns/all")) {
2116 smartlist_t *statuses = smartlist_create();
2117 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
2118 routerstatus_t *, rs,
2120 smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
2122 *answer = smartlist_join_strings(statuses, "", 0, NULL);
2123 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
2124 smartlist_free(statuses);
2125 return 0;
2126 } else if (!strcmpstart(question, "ns/id/")) {
2127 char d[DIGEST_LEN];
2129 if (base16_decode(d, DIGEST_LEN, question+6, strlen(question+6)))
2130 return -1;
2131 status = router_get_consensus_status_by_id(d);
2132 } else if (!strcmpstart(question, "ns/name/")) {
2133 status = router_get_consensus_status_by_nickname(question+8, 0);
2134 } else if (!strcmpstart(question, "ns/purpose/")) {
2135 *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
2136 return *answer ? 0 : -1;
2137 } else {
2138 return -1;
2141 if (status)
2142 *answer = networkstatus_getinfo_helper_single(status);
2143 return 0;
2146 /** Free all storage held locally in this module. */
2147 void
2148 networkstatus_free_all(void)
2150 int i;
2151 if (networkstatus_v2_list) {
2152 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
2153 networkstatus_v2_free(ns));
2154 smartlist_free(networkstatus_v2_list);
2155 networkstatus_v2_list = NULL;
2158 digestmap_free(v2_download_status_map, _tor_free);
2159 v2_download_status_map = NULL;
2160 networkstatus_vote_free(current_consensus);
2161 current_consensus = NULL;
2163 for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
2164 consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
2165 if (waiting->consensus) {
2166 networkstatus_vote_free(waiting->consensus);
2167 waiting->consensus = NULL;
2169 tor_free(waiting->body);
2172 strmap_free(named_server_map, _tor_free);
2173 strmap_free(unnamed_server_map, NULL);