Fix a heap overflow found by debuger, and make it harder to make that mistake again
[tor/rransom.git] / src / or / networkstatus.c
blob7106294d549679630287a18611656113c43abc5c
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-2011, 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 static networkstatus_t *consensus_waiting_for_certs = NULL;
39 /** The encoded version of consensus_waiting_for_certs. */
40 static char *consensus_waiting_for_certs_body = NULL;
41 /** When did we set the current value of consensus_waiting_for_certs? If this
42 * is too recent, we shouldn't try to fetch a new consensus for a little while,
43 * to give ourselves time to get certificates for this one. */
44 static time_t consensus_waiting_for_certs_set_at = 0;
45 /** Set to 1 if we've been holding on to consensus_waiting_for_certs so long
46 * that we should treat it as maybe being bad. */
47 static int consensus_waiting_for_certs_dl_failed = 0;
49 /** The last time we tried to download a networkstatus, or 0 for "never". We
50 * use this to rate-limit download attempts for directory caches (including
51 * mirrors). Clients don't use this now. */
52 static time_t last_networkstatus_download_attempted = 0;
54 /** A time before which we shouldn't try to replace the current consensus:
55 * this will be at some point after the next consensus becomes valid, but
56 * before the current consensus becomes invalid. */
57 static time_t time_to_download_next_consensus = 0;
58 /** Download status for the current consensus networkstatus. */
59 static download_status_t consensus_dl_status = { 0, 0, DL_SCHED_CONSENSUS };
61 /** True iff we have logged a warning about this OR's version being older than
62 * listed by the authorities. */
63 static int have_warned_about_old_version = 0;
64 /** True iff we have logged a warning about this OR's version being newer than
65 * listed by the authorities. */
66 static int have_warned_about_new_version = 0;
68 static void download_status_map_update_from_v2_networkstatus(void);
69 static void routerstatus_list_update_named_server_map(void);
71 /** Forget that we've warned about anything networkstatus-related, so we will
72 * give fresh warnings if the same behavior happens again. */
73 void
74 networkstatus_reset_warnings(void)
76 if (current_consensus) {
77 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
78 routerstatus_t *, rs,
79 rs->name_lookup_warned = 0);
82 have_warned_about_old_version = 0;
83 have_warned_about_new_version = 0;
86 /** Reset the descriptor download failure count on all networkstatus docs, so
87 * that we can retry any long-failed documents immediately.
89 void
90 networkstatus_reset_download_failures(void)
92 const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
93 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
94 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
96 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
97 rs->need_to_mirror = 1;
98 }));;
100 download_status_reset(&consensus_dl_status);
101 if (v2_download_status_map) {
102 digestmap_iter_t *iter;
103 digestmap_t *map = v2_download_status_map;
104 const char *key;
105 void *val;
106 download_status_t *dls;
107 for (iter = digestmap_iter_init(map); !digestmap_iter_done(iter);
108 iter = digestmap_iter_next(map, iter) ) {
109 digestmap_iter_get(iter, &key, &val);
110 dls = val;
111 download_status_reset(dls);
116 /** Repopulate our list of network_status_t objects from the list cached on
117 * disk. Return 0 on success, -1 on failure. */
119 router_reload_v2_networkstatus(void)
121 smartlist_t *entries;
122 struct stat st;
123 char *s;
124 char *filename = get_datadir_fname("cached-status");
125 int maybe_delete = !directory_caches_v2_dir_info(get_options());
126 time_t now = time(NULL);
127 if (!networkstatus_v2_list)
128 networkstatus_v2_list = smartlist_create();
130 entries = tor_listdir(filename);
131 if (!entries) { /* dir doesn't exist */
132 tor_free(filename);
133 return 0;
134 } else if (!smartlist_len(entries) && maybe_delete) {
135 rmdir(filename);
136 tor_free(filename);
137 smartlist_free(entries);
138 return 0;
140 tor_free(filename);
141 SMARTLIST_FOREACH(entries, const char *, fn, {
142 char buf[DIGEST_LEN];
143 if (maybe_delete) {
144 filename = get_datadir_fname2("cached-status", fn);
145 remove_file_if_very_old(filename, now);
146 tor_free(filename);
147 continue;
149 if (strlen(fn) != HEX_DIGEST_LEN ||
150 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
151 log_info(LD_DIR,
152 "Skipping cached-status file with unexpected name \"%s\"",fn);
153 continue;
155 filename = get_datadir_fname2("cached-status", fn);
156 s = read_file_to_str(filename, 0, &st);
157 if (s) {
158 if (router_set_networkstatus_v2(s, st.st_mtime, NS_FROM_CACHE,
159 NULL)<0) {
160 log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
162 tor_free(s);
164 tor_free(filename);
166 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
167 smartlist_free(entries);
168 networkstatus_v2_list_clean(time(NULL));
169 routers_update_all_from_networkstatus(time(NULL), 2);
170 return 0;
173 /** Read the cached v3 consensus networkstatus from the disk. */
175 router_reload_consensus_networkstatus(void)
177 char *filename;
178 char *s;
179 struct stat st;
180 or_options_t *options = get_options();
181 const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
183 /* FFFF Suppress warnings if cached consensus is bad? */
185 filename = get_datadir_fname("cached-consensus");
186 s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
187 if (s) {
188 if (networkstatus_set_current_consensus(s, flags) < -1) {
189 log_warn(LD_FS, "Couldn't load consensus networkstatus from \"%s\"",
190 filename);
192 tor_free(s);
194 tor_free(filename);
196 filename = get_datadir_fname("unverified-consensus");
197 s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
198 if (s) {
199 if (networkstatus_set_current_consensus(s,
200 flags|NSSET_WAS_WAITING_FOR_CERTS)) {
201 log_info(LD_FS, "Couldn't load consensus networkstatus from \"%s\"",
202 filename);
204 tor_free(s);
206 tor_free(filename);
208 if (!current_consensus ||
209 (stat(options->FallbackNetworkstatusFile, &st)==0 &&
210 st.st_mtime > current_consensus->valid_after)) {
211 s = read_file_to_str(options->FallbackNetworkstatusFile,
212 RFTS_IGNORE_MISSING, NULL);
213 if (s) {
214 if (networkstatus_set_current_consensus(s,
215 flags|NSSET_ACCEPT_OBSOLETE)) {
216 log_info(LD_FS, "Couldn't load consensus networkstatus from \"%s\"",
217 options->FallbackNetworkstatusFile);
218 } else {
219 log_notice(LD_FS,
220 "Loaded fallback consensus networkstatus from \"%s\"",
221 options->FallbackNetworkstatusFile);
223 tor_free(s);
227 if (!current_consensus) {
228 if (!named_server_map)
229 named_server_map = strmap_new();
230 if (!unnamed_server_map)
231 unnamed_server_map = strmap_new();
234 update_certificate_downloads(time(NULL));
236 routers_update_all_from_networkstatus(time(NULL), 3);
238 return 0;
241 /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
242 static void
243 vote_routerstatus_free(vote_routerstatus_t *rs)
245 tor_free(rs->version);
246 tor_free(rs->status.exitsummary);
247 tor_free(rs);
250 /** Free all storage held by the routerstatus object <b>rs</b>. */
251 void
252 routerstatus_free(routerstatus_t *rs)
254 tor_free(rs->exitsummary);
255 tor_free(rs);
258 /** Free all storage held by the networkstatus object <b>ns</b>. */
259 void
260 networkstatus_v2_free(networkstatus_v2_t *ns)
262 tor_free(ns->source_address);
263 tor_free(ns->contact);
264 if (ns->signing_key)
265 crypto_free_pk_env(ns->signing_key);
266 tor_free(ns->client_versions);
267 tor_free(ns->server_versions);
268 if (ns->entries) {
269 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
270 routerstatus_free(rs));
271 smartlist_free(ns->entries);
273 tor_free(ns);
276 /** Clear all storage held in <b>ns</b>. */
277 void
278 networkstatus_vote_free(networkstatus_t *ns)
280 if (!ns)
281 return;
283 tor_free(ns->client_versions);
284 tor_free(ns->server_versions);
285 if (ns->known_flags) {
286 SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
287 smartlist_free(ns->known_flags);
289 if (ns->net_params) {
290 SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
291 smartlist_free(ns->net_params);
293 if (ns->supported_methods) {
294 SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
295 smartlist_free(ns->supported_methods);
297 if (ns->voters) {
298 SMARTLIST_FOREACH(ns->voters, networkstatus_voter_info_t *, voter,
300 tor_free(voter->nickname);
301 tor_free(voter->address);
302 tor_free(voter->contact);
303 tor_free(voter->signature);
304 tor_free(voter);
306 smartlist_free(ns->voters);
308 if (ns->cert)
309 authority_cert_free(ns->cert);
311 if (ns->routerstatus_list) {
312 if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
313 SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
314 vote_routerstatus_free(rs));
315 } else {
316 SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
317 routerstatus_free(rs));
320 smartlist_free(ns->routerstatus_list);
322 if (ns->desc_digest_map)
323 digestmap_free(ns->desc_digest_map, NULL);
325 memset(ns, 11, sizeof(*ns));
326 tor_free(ns);
329 /** Return the voter info from <b>vote</b> for the voter whose identity digest
330 * is <b>identity</b>, or NULL if no such voter is associated with
331 * <b>vote</b>. */
332 networkstatus_voter_info_t *
333 networkstatus_get_voter_by_id(networkstatus_t *vote,
334 const char *identity)
336 if (!vote || !vote->voters)
337 return NULL;
338 SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
339 if (!memcmp(voter->identity_digest, identity, DIGEST_LEN))
340 return voter);
341 return NULL;
344 /** Check whether the signature on <b>voter</b> is correctly signed by
345 * the signing key of <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
346 * signing key; otherwise set the good_signature or bad_signature flag on
347 * <b>voter</b>, and return 0. */
348 /* (private; exposed for testing.) */
350 networkstatus_check_voter_signature(networkstatus_t *consensus,
351 networkstatus_voter_info_t *voter,
352 authority_cert_t *cert)
354 char d[DIGEST_LEN];
355 char *signed_digest;
356 size_t signed_digest_len;
357 if (crypto_pk_get_digest(cert->signing_key, d)<0)
358 return -1;
359 if (memcmp(voter->signing_key_digest, d, DIGEST_LEN))
360 return -1;
361 signed_digest_len = crypto_pk_keysize(cert->signing_key);
362 signed_digest = tor_malloc(signed_digest_len);
363 if (crypto_pk_public_checksig(cert->signing_key,
364 signed_digest,
365 signed_digest_len,
366 voter->signature,
367 voter->signature_len) != DIGEST_LEN ||
368 memcmp(signed_digest, consensus->networkstatus_digest, DIGEST_LEN)) {
369 log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
370 voter->bad_signature = 1;
371 } else {
372 voter->good_signature = 1;
374 tor_free(signed_digest);
375 return 0;
378 /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
379 * as-yet-unchecked signature on <b>consensus</b>. Return 1 if there is a
380 * signature from every recognized authority on it, 0 if there are
381 * enough good signatures from recognized authorities on it, -1 if we might
382 * get enough good signatures by fetching missing certificates, and -2
383 * otherwise. Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
384 * about every problem; if warn is at least 1, warn only if we can't get
385 * enough signatures; if warn is negative, log nothing at all. */
387 networkstatus_check_consensus_signature(networkstatus_t *consensus,
388 int warn)
390 int n_good = 0;
391 int n_missing_key = 0;
392 int n_bad = 0;
393 int n_unknown = 0;
394 int n_no_signature = 0;
395 int n_v3_authorities = get_n_authorities(V3_AUTHORITY);
396 int n_required = n_v3_authorities/2 + 1;
397 smartlist_t *need_certs_from = smartlist_create();
398 smartlist_t *unrecognized = smartlist_create();
399 smartlist_t *missing_authorities = smartlist_create();
400 int severity;
401 time_t now = time(NULL);
403 tor_assert(consensus->type == NS_TYPE_CONSENSUS);
405 SMARTLIST_FOREACH(consensus->voters, networkstatus_voter_info_t *, voter,
407 if (!voter->good_signature && !voter->bad_signature && voter->signature) {
408 /* we can try to check the signature. */
409 int is_v3_auth = trusteddirserver_get_by_v3_auth_digest(
410 voter->identity_digest) != NULL;
411 authority_cert_t *cert =
412 authority_cert_get_by_digests(voter->identity_digest,
413 voter->signing_key_digest);
414 if (!is_v3_auth) {
415 smartlist_add(unrecognized, voter);
416 ++n_unknown;
417 continue;
418 } else if (!cert || cert->expires < now) {
419 smartlist_add(need_certs_from, voter);
420 ++n_missing_key;
421 continue;
423 if (networkstatus_check_voter_signature(consensus, voter, cert) < 0) {
424 smartlist_add(need_certs_from, voter);
425 ++n_missing_key;
426 continue;
429 if (voter->good_signature)
430 ++n_good;
431 else if (voter->bad_signature)
432 ++n_bad;
433 else
434 ++n_no_signature;
437 /* Now see whether we're missing any voters entirely. */
438 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
439 trusted_dir_server_t *, ds,
441 if ((ds->type & V3_AUTHORITY) &&
442 !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
443 smartlist_add(missing_authorities, ds);
446 if (warn > 1 || (warn >= 0 && n_good < n_required))
447 severity = LOG_WARN;
448 else
449 severity = LOG_INFO;
451 if (warn >= 0) {
452 SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
454 log_info(LD_DIR, "Consensus includes unrecognized authority '%s' "
455 "at %s:%d (contact %s; identity %s)",
456 voter->nickname, voter->address, (int)voter->dir_port,
457 voter->contact?voter->contact:"n/a",
458 hex_str(voter->identity_digest, DIGEST_LEN));
460 SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
462 log_info(LD_DIR, "Looks like we need to download a new certificate "
463 "from authority '%s' at %s:%d (contact %s; identity %s)",
464 voter->nickname, voter->address, (int)voter->dir_port,
465 voter->contact?voter->contact:"n/a",
466 hex_str(voter->identity_digest, DIGEST_LEN));
468 SMARTLIST_FOREACH(missing_authorities, trusted_dir_server_t *, ds,
470 log_info(LD_DIR, "Consensus does not include configured "
471 "authority '%s' at %s:%d (identity %s)",
472 ds->nickname, ds->address, (int)ds->dir_port,
473 hex_str(ds->v3_identity_digest, DIGEST_LEN));
475 log(severity, LD_DIR,
476 "%d unknown, %d missing key, %d good, %d bad, %d no signature, "
477 "%d required", n_unknown, n_missing_key, n_good, n_bad,
478 n_no_signature, n_required);
481 smartlist_free(unrecognized);
482 smartlist_free(need_certs_from);
483 smartlist_free(missing_authorities);
485 if (n_good == n_v3_authorities)
486 return 1;
487 else if (n_good >= n_required)
488 return 0;
489 else if (n_good + n_missing_key >= n_required)
490 return -1;
491 else
492 return -2;
495 /** Helper: return a newly allocated string containing the name of the filename
496 * where we plan to cache the network status with the given identity digest. */
497 char *
498 networkstatus_get_cache_filename(const char *identity_digest)
500 char fp[HEX_DIGEST_LEN+1];
501 base16_encode(fp, HEX_DIGEST_LEN+1, identity_digest, DIGEST_LEN);
502 return get_datadir_fname2("cached-status", fp);
505 /** Helper for smartlist_sort: Compare two networkstatus objects by
506 * publication date. */
507 static int
508 _compare_networkstatus_v2_published_on(const void **_a, const void **_b)
510 const networkstatus_v2_t *a = *_a, *b = *_b;
511 if (a->published_on < b->published_on)
512 return -1;
513 else if (a->published_on > b->published_on)
514 return 1;
515 else
516 return 0;
519 /** Add the parsed v2 networkstatus in <b>ns</b> (with original document in
520 * <b>s</b>) to the disk cache (and the in-memory directory server cache) as
521 * appropriate. */
522 static int
523 add_networkstatus_to_cache(const char *s,
524 v2_networkstatus_source_t source,
525 networkstatus_v2_t *ns)
527 if (source != NS_FROM_CACHE) {
528 char *fn = networkstatus_get_cache_filename(ns->identity_digest);
529 if (write_str_to_file(fn, s, 0)<0) {
530 log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
532 tor_free(fn);
535 if (directory_caches_v2_dir_info(get_options()))
536 dirserv_set_cached_networkstatus_v2(s,
537 ns->identity_digest,
538 ns->published_on);
540 return 0;
543 /** How far in the future do we allow a network-status to get before removing
544 * it? (seconds) */
545 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
547 /** Given a string <b>s</b> containing a network status that we received at
548 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
549 * store it, and put it into our cache as necessary.
551 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
552 * own networkstatus_t (if we're an authoritative directory server).
554 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
555 * cache.
557 * If <b>requested_fingerprints</b> is provided, it must contain a list of
558 * uppercased identity fingerprints. Do not update any networkstatus whose
559 * fingerprint is not on the list; after updating a networkstatus, remove its
560 * fingerprint from the list.
562 * Return 0 on success, -1 on failure.
564 * Callers should make sure that routers_update_all_from_networkstatus() is
565 * invoked after this function succeeds.
568 router_set_networkstatus_v2(const char *s, time_t arrived_at,
569 v2_networkstatus_source_t source,
570 smartlist_t *requested_fingerprints)
572 networkstatus_v2_t *ns;
573 int i, found;
574 time_t now;
575 int skewed = 0;
576 trusted_dir_server_t *trusted_dir = NULL;
577 const char *source_desc = NULL;
578 char fp[HEX_DIGEST_LEN+1];
579 char published[ISO_TIME_LEN+1];
581 if (!directory_caches_v2_dir_info(get_options()))
582 return 0; /* Don't bother storing it. */
584 ns = networkstatus_v2_parse_from_string(s);
585 if (!ns) {
586 log_warn(LD_DIR, "Couldn't parse network status.");
587 return -1;
589 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
590 if (!(trusted_dir =
591 router_get_trusteddirserver_by_digest(ns->identity_digest)) ||
592 !(trusted_dir->type & V2_AUTHORITY)) {
593 log_info(LD_DIR, "Network status was signed, but not by an authoritative "
594 "directory we recognize.");
595 source_desc = fp;
596 } else {
597 source_desc = trusted_dir->description;
599 now = time(NULL);
600 if (arrived_at > now)
601 arrived_at = now;
603 ns->received_on = arrived_at;
605 format_iso_time(published, ns->published_on);
607 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
608 char dbuf[64];
609 long delta = now - ns->published_on;
610 format_time_interval(dbuf, sizeof(dbuf), delta);
611 log_warn(LD_GENERAL, "Network status from %s was published %s in the "
612 "future (%s GMT). Check your time and date settings! "
613 "Not caching.",
614 source_desc, dbuf, published);
615 control_event_general_status(LOG_WARN,
616 "CLOCK_SKEW MIN_SKEW=%ld SOURCE=NETWORKSTATUS:%s:%d",
617 delta, ns->source_address, ns->source_dirport);
618 skewed = 1;
621 if (!networkstatus_v2_list)
622 networkstatus_v2_list = smartlist_create();
624 if ( (source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) &&
625 router_digest_is_me(ns->identity_digest)) {
626 /* Don't replace our own networkstatus when we get it from somebody else.*/
627 networkstatus_v2_free(ns);
628 return 0;
631 if (requested_fingerprints) {
632 if (smartlist_string_isin(requested_fingerprints, fp)) {
633 smartlist_string_remove(requested_fingerprints, fp);
634 } else {
635 if (source != NS_FROM_DIR_ALL) {
636 char *requested =
637 smartlist_join_strings(requested_fingerprints," ",0,NULL);
638 log_warn(LD_DIR,
639 "We received a network status with a fingerprint (%s) that we "
640 "never requested. (We asked for: %s.) Dropping.",
641 fp, requested);
642 tor_free(requested);
643 return 0;
648 if (!trusted_dir) {
649 if (!skewed) {
650 /* We got a non-trusted networkstatus, and we're a directory cache.
651 * This means that we asked an authority, and it told us about another
652 * authority we didn't recognize. */
653 log_info(LD_DIR,
654 "We do not recognize authority (%s) but we are willing "
655 "to cache it.", fp);
656 add_networkstatus_to_cache(s, source, ns);
657 networkstatus_v2_free(ns);
659 return 0;
662 found = 0;
663 for (i=0; i < smartlist_len(networkstatus_v2_list); ++i) {
664 networkstatus_v2_t *old_ns = smartlist_get(networkstatus_v2_list, i);
666 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
667 if (!memcmp(old_ns->networkstatus_digest,
668 ns->networkstatus_digest, DIGEST_LEN)) {
669 /* Same one we had before. */
670 networkstatus_v2_free(ns);
671 tor_assert(trusted_dir);
672 log_info(LD_DIR,
673 "Not replacing network-status from %s (published %s); "
674 "we already have it.",
675 trusted_dir->description, published);
676 if (old_ns->received_on < arrived_at) {
677 if (source != NS_FROM_CACHE) {
678 char *fn;
679 fn = networkstatus_get_cache_filename(old_ns->identity_digest);
680 /* We use mtime to tell when it arrived, so update that. */
681 touch_file(fn);
682 tor_free(fn);
684 old_ns->received_on = arrived_at;
686 download_status_failed(&trusted_dir->v2_ns_dl_status, 0);
687 return 0;
688 } else if (old_ns->published_on >= ns->published_on) {
689 char old_published[ISO_TIME_LEN+1];
690 format_iso_time(old_published, old_ns->published_on);
691 tor_assert(trusted_dir);
692 log_info(LD_DIR,
693 "Not replacing network-status from %s (published %s);"
694 " we have a newer one (published %s) for this authority.",
695 trusted_dir->description, published,
696 old_published);
697 networkstatus_v2_free(ns);
698 download_status_failed(&trusted_dir->v2_ns_dl_status, 0);
699 return 0;
700 } else {
701 networkstatus_v2_free(old_ns);
702 smartlist_set(networkstatus_v2_list, i, ns);
703 found = 1;
704 break;
709 if (source != NS_FROM_CACHE && trusted_dir) {
710 download_status_reset(&trusted_dir->v2_ns_dl_status);
713 if (!found)
714 smartlist_add(networkstatus_v2_list, ns);
716 /** Retain any routerinfo mentioned in a V2 networkstatus for at least this
717 * long. */
718 #define V2_NETWORKSTATUS_ROUTER_LIFETIME (3*60*60)
721 time_t live_until = ns->published_on + V2_NETWORKSTATUS_ROUTER_LIFETIME;
722 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
724 signed_descriptor_t *sd =
725 router_get_by_descriptor_digest(rs->descriptor_digest);
726 if (sd) {
727 if (sd->last_listed_as_valid_until < live_until)
728 sd->last_listed_as_valid_until = live_until;
729 } else {
730 rs->need_to_mirror = 1;
735 log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
736 source == NS_FROM_CACHE?"cached from":
737 ((source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) ?
738 "downloaded from":"generated for"),
739 trusted_dir->description, published);
740 networkstatus_v2_list_has_changed = 1;
742 smartlist_sort(networkstatus_v2_list,
743 _compare_networkstatus_v2_published_on);
745 if (!skewed)
746 add_networkstatus_to_cache(s, source, ns);
748 return 0;
751 /** Remove all very-old network_status_t objects from memory and from the
752 * disk cache. */
753 void
754 networkstatus_v2_list_clean(time_t now)
756 int i;
757 if (!networkstatus_v2_list)
758 return;
760 for (i = 0; i < smartlist_len(networkstatus_v2_list); ++i) {
761 networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
762 char *fname = NULL;
763 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
764 continue;
765 /* Okay, this one is too old. Remove it from the list, and delete it
766 * from the cache. */
767 smartlist_del(networkstatus_v2_list, i--);
768 fname = networkstatus_get_cache_filename(ns->identity_digest);
769 if (file_status(fname) == FN_FILE) {
770 log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
771 unlink(fname);
773 tor_free(fname);
774 if (directory_caches_v2_dir_info(get_options())) {
775 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
777 networkstatus_v2_free(ns);
780 /* And now go through the directory cache for any cached untrusted
781 * networkstatuses and other network info. */
782 dirserv_clear_old_networkstatuses(now - MAX_NETWORKSTATUS_AGE);
783 dirserv_clear_old_v1_info(now);
786 /** Helper for bsearching a list of routerstatus_t pointers: compare a
787 * digest in the key to the identity digest of a routerstatus_t. */
788 static int
789 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
791 const char *key = _key;
792 const routerstatus_t *rs = *_member;
793 return memcmp(key, rs->identity_digest, DIGEST_LEN);
796 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
797 * NULL if none was found. */
798 routerstatus_t *
799 networkstatus_v2_find_entry(networkstatus_v2_t *ns, const char *digest)
801 return smartlist_bsearch(ns->entries, digest,
802 _compare_digest_to_routerstatus_entry);
805 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
806 * NULL if none was found. */
807 routerstatus_t *
808 networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
810 return smartlist_bsearch(ns->routerstatus_list, digest,
811 _compare_digest_to_routerstatus_entry);
814 /*XXXX make this static once functions are moved into this file. */
815 /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
816 * <b>digest</b>. Return value and set *<b>found_out</b> as for
817 * smartlist_bsearch_idx(). */
819 networkstatus_vote_find_entry_idx(networkstatus_t *ns,
820 const char *digest, int *found_out)
822 return smartlist_bsearch_idx(ns->routerstatus_list, digest,
823 _compare_digest_to_routerstatus_entry,
824 found_out);
827 /** Return a list of the v2 networkstatus documents. */
828 const smartlist_t *
829 networkstatus_get_v2_list(void)
831 if (!networkstatus_v2_list)
832 networkstatus_v2_list = smartlist_create();
833 return networkstatus_v2_list;
836 /** Return the consensus view of the status of the router whose current
837 * <i>descriptor</i> digest is <b>digest</b>, or NULL if no such router is
838 * known. */
839 routerstatus_t *
840 router_get_consensus_status_by_descriptor_digest(const char *digest)
842 if (!current_consensus) return NULL;
843 if (!current_consensus->desc_digest_map) {
844 digestmap_t * m = current_consensus->desc_digest_map = digestmap_new();
845 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
846 routerstatus_t *, rs,
848 digestmap_set(m, rs->descriptor_digest, rs);
851 return digestmap_get(current_consensus->desc_digest_map, digest);
854 /** Given the digest of a router descriptor, return its current download
855 * status, or NULL if the digest is unrecognized. */
856 download_status_t *
857 router_get_dl_status_by_descriptor_digest(const char *d)
859 routerstatus_t *rs;
860 if ((rs = router_get_consensus_status_by_descriptor_digest(d)))
861 return &rs->dl_status;
862 if (v2_download_status_map)
863 return digestmap_get(v2_download_status_map, d);
865 return NULL;
868 /** Return the consensus view of the status of the router whose identity
869 * digest is <b>digest</b>, or NULL if we don't know about any such router. */
870 routerstatus_t *
871 router_get_consensus_status_by_id(const char *digest)
873 if (!current_consensus)
874 return NULL;
875 return smartlist_bsearch(current_consensus->routerstatus_list, digest,
876 _compare_digest_to_routerstatus_entry);
879 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
880 * the corresponding routerstatus_t, or NULL if none exists. Warn the
881 * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
882 * nickname, but the Named flag isn't set for that router. */
883 routerstatus_t *
884 router_get_consensus_status_by_nickname(const char *nickname,
885 int warn_if_unnamed)
887 char digest[DIGEST_LEN];
888 routerstatus_t *best=NULL;
889 smartlist_t *matches=NULL;
890 const char *named_id=NULL;
892 if (!current_consensus || !nickname)
893 return NULL;
895 /* Is this name really a hexadecimal identity digest? */
896 if (nickname[0] == '$') {
897 if (base16_decode(digest, DIGEST_LEN, nickname+1, strlen(nickname+1))<0)
898 return NULL;
899 return networkstatus_vote_find_entry(current_consensus, digest);
900 } else if (strlen(nickname) == HEX_DIGEST_LEN &&
901 (base16_decode(digest, DIGEST_LEN, nickname, strlen(nickname))==0)) {
902 return networkstatus_vote_find_entry(current_consensus, digest);
905 /* Is there a server that is Named with this name? */
906 if (named_server_map)
907 named_id = strmap_get_lc(named_server_map, nickname);
908 if (named_id)
909 return networkstatus_vote_find_entry(current_consensus, named_id);
911 /* Okay; is this name listed as Unnamed? */
912 if (unnamed_server_map &&
913 strmap_get_lc(unnamed_server_map, nickname)) {
914 log_info(LD_GENERAL, "The name %s is listed as Unnamed; it is not the "
915 "canonical name of any server we know.", escaped(nickname));
916 return NULL;
919 /* This name is not canonical for any server; go through the list and
920 * see who it matches. */
921 /*XXXX This is inefficient; optimize it if it matters. */
922 matches = smartlist_create();
923 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
924 routerstatus_t *, lrs,
926 if (!strcasecmp(lrs->nickname, nickname)) {
927 if (lrs->is_named) {
928 tor_fragile_assert() /* This should never happen. */
929 smartlist_free(matches);
930 return lrs;
931 } else {
932 if (lrs->is_unnamed) {
933 tor_fragile_assert(); /* nor should this. */
934 smartlist_clear(matches);
935 best=NULL;
936 break;
938 smartlist_add(matches, lrs);
939 best = lrs;
944 if (smartlist_len(matches)>1 && warn_if_unnamed) {
945 int any_unwarned=0;
946 SMARTLIST_FOREACH(matches, routerstatus_t *, lrs,
948 if (! lrs->name_lookup_warned) {
949 lrs->name_lookup_warned=1;
950 any_unwarned=1;
953 if (any_unwarned) {
954 log_warn(LD_CONFIG,"There are multiple matches for the nickname \"%s\","
955 " but none is listed as named by the directory authorities. "
956 "Choosing one arbitrarily.", nickname);
958 } else if (warn_if_unnamed && best && !best->name_lookup_warned) {
959 char fp[HEX_DIGEST_LEN+1];
960 base16_encode(fp, sizeof(fp),
961 best->identity_digest, DIGEST_LEN);
962 log_warn(LD_CONFIG,
963 "When looking up a status, you specified a server \"%s\" by name, "
964 "but the directory authorities do not have any key registered for "
965 "this nickname -- so it could be used by any server, "
966 "not just the one you meant. "
967 "To make sure you get the same server in the future, refer to "
968 "it by key, as \"$%s\".", nickname, fp);
969 best->name_lookup_warned = 1;
971 smartlist_free(matches);
972 return best;
975 /** Return the identity digest that's mapped to officially by
976 * <b>nickname</b>. */
977 const char *
978 networkstatus_get_router_digest_by_nickname(const char *nickname)
980 if (!named_server_map)
981 return NULL;
982 return strmap_get_lc(named_server_map, nickname);
985 /** Return true iff <b>nickname</b> is disallowed from being the nickname
986 * of any server. */
988 networkstatus_nickname_is_unnamed(const char *nickname)
990 if (!unnamed_server_map)
991 return 0;
992 return strmap_get_lc(unnamed_server_map, nickname) != NULL;
995 /** How frequently do directory authorities re-download fresh networkstatus
996 * documents? */
997 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
999 /** How frequently do non-authority directory caches re-download fresh
1000 * networkstatus documents? */
1001 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
1003 /** We are a directory server, and so cache network_status documents.
1004 * Initiate downloads as needed to update them. For v2 authorities,
1005 * this means asking each trusted directory for its network-status.
1006 * For caches, this means asking a random v2 authority for all
1007 * network-statuses.
1009 static void
1010 update_v2_networkstatus_cache_downloads(time_t now)
1012 int authority = authdir_mode_v2(get_options());
1013 int interval =
1014 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
1015 const smartlist_t *trusted_dir_servers = router_get_trusted_dir_servers();
1017 if (last_networkstatus_download_attempted + interval >= now)
1018 return;
1020 last_networkstatus_download_attempted = now;
1022 if (authority) {
1023 /* An authority launches a separate connection for everybody. */
1024 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds)
1026 char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
1027 tor_addr_t addr;
1028 if (!(ds->type & V2_AUTHORITY))
1029 continue;
1030 if (router_digest_is_me(ds->digest))
1031 continue;
1032 tor_addr_from_ipv4h(&addr, ds->addr);
1033 /* Is this quite sensible with IPv6 or multiple addresses? */
1034 if (connection_get_by_type_addr_port_purpose(
1035 CONN_TYPE_DIR, &addr, ds->dir_port,
1036 DIR_PURPOSE_FETCH_V2_NETWORKSTATUS)) {
1037 /* XXX the above dir_port won't be accurate if we're
1038 * doing a tunneled conn. In that case it should be or_port.
1039 * How to guess from here? Maybe make the function less general
1040 * and have it know that it's looking for dir conns. -RD */
1041 /* Only directory caches download v2 networkstatuses, and they
1042 * don't use tunneled connections. I think it's okay to ignore
1043 * this. */
1044 continue;
1046 strlcpy(resource, "fp/", sizeof(resource));
1047 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
1048 strlcat(resource, ".z", sizeof(resource));
1049 directory_initiate_command_routerstatus(
1050 &ds->fake_status, DIR_PURPOSE_FETCH_V2_NETWORKSTATUS,
1051 ROUTER_PURPOSE_GENERAL,
1052 0, /* Not private */
1053 resource,
1054 NULL, 0 /* No payload. */,
1055 0 /* No I-M-S. */);
1057 SMARTLIST_FOREACH_END(ds);
1058 } else {
1059 /* A non-authority cache launches one connection to a random authority. */
1060 /* (Check whether we're currently fetching network-status objects.) */
1061 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
1062 DIR_PURPOSE_FETCH_V2_NETWORKSTATUS))
1063 directory_get_from_dirserver(DIR_PURPOSE_FETCH_V2_NETWORKSTATUS,
1064 ROUTER_PURPOSE_GENERAL, "all.z",
1065 PDS_RETRY_IF_NO_SERVERS);
1069 /** How many times will we try to fetch a consensus before we give up? */
1070 #define CONSENSUS_NETWORKSTATUS_MAX_DL_TRIES 8
1071 /** How long will we hang onto a possibly live consensus for which we're
1072 * fetching certs before we check whether there is a better one? */
1073 #define DELAY_WHILE_FETCHING_CERTS (20*60)
1075 /** If we want to download a fresh consensus, launch a new download as
1076 * appropriate. */
1077 static void
1078 update_consensus_networkstatus_downloads(time_t now)
1080 or_options_t *options = get_options();
1081 if (!networkstatus_get_live_consensus(now))
1082 time_to_download_next_consensus = now; /* No live consensus? Get one now!*/
1083 if (time_to_download_next_consensus > now)
1084 return; /* Wait until the current consensus is older. */
1085 if (authdir_mode_v3(options))
1086 return; /* Authorities never fetch a consensus */
1087 if (!download_status_is_ready(&consensus_dl_status, now,
1088 CONSENSUS_NETWORKSTATUS_MAX_DL_TRIES))
1089 return; /* We failed downloading a consensus too recently. */
1090 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
1091 DIR_PURPOSE_FETCH_CONSENSUS))
1092 return; /* There's an in-progress download.*/
1094 if (consensus_waiting_for_certs) {
1095 /* XXXX make sure this doesn't delay sane downloads. */
1096 if (consensus_waiting_for_certs_set_at + DELAY_WHILE_FETCHING_CERTS > now)
1097 return; /* We're still getting certs for this one. */
1098 else {
1099 if (!consensus_waiting_for_certs_dl_failed) {
1100 download_status_failed(&consensus_dl_status, 0);
1101 consensus_waiting_for_certs_dl_failed=1;
1106 log_info(LD_DIR, "Launching networkstatus consensus download.");
1107 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
1108 ROUTER_PURPOSE_GENERAL, NULL,
1109 PDS_RETRY_IF_NO_SERVERS);
1112 /** Called when an attempt to download a consensus fails: note that the
1113 * failure occurred, and possibly retry. */
1114 void
1115 networkstatus_consensus_download_failed(int status_code)
1117 download_status_failed(&consensus_dl_status, status_code);
1118 /* Retry immediately, if appropriate. */
1119 update_consensus_networkstatus_downloads(time(NULL));
1122 /** How long do we (as a cache) wait after a consensus becomes non-fresh
1123 * before trying to fetch another? */
1124 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
1126 /** Update the time at which we'll consider replacing the current
1127 * consensus. */
1128 void
1129 update_consensus_networkstatus_fetch_time(time_t now)
1131 or_options_t *options = get_options();
1132 networkstatus_t *c = networkstatus_get_live_consensus(now);
1133 if (c) {
1134 long dl_interval;
1135 long interval = c->fresh_until - c->valid_after;
1136 long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
1137 time_t start;
1139 if (min_sec_before_caching > interval/16) {
1140 /* Usually we allow 2-minutes slop factor in case clocks get
1141 desynchronized a little. If we're on a private network with
1142 a crazy-fast voting interval, though, 2 minutes may be too
1143 much. */
1144 min_sec_before_caching = interval/16;
1147 if (directory_fetches_dir_info_early(options)) {
1148 /* We want to cache the next one at some point after this one
1149 * is no longer fresh... */
1150 start = c->fresh_until + min_sec_before_caching;
1151 /* But only in the first half-interval after that. */
1152 dl_interval = interval/2;
1153 } else {
1154 /* We're an ordinary client or a bridge. Give all the caches enough
1155 * time to download the consensus. */
1156 start = c->fresh_until + (interval*3)/4;
1157 /* But download the next one well before this one is expired. */
1158 dl_interval = ((c->valid_until - start) * 7 )/ 8;
1160 /* If we're a bridge user, make use of the numbers we just computed
1161 * to choose the rest of the interval *after* them. */
1162 if (directory_fetches_dir_info_later(options)) {
1163 /* Give all the *clients* enough time to download the consensus. */
1164 start = start + dl_interval + min_sec_before_caching;
1165 /* But try to get it before ours actually expires. */
1166 dl_interval = (c->valid_until - start) - min_sec_before_caching;
1169 if (dl_interval < 1)
1170 dl_interval = 1;
1171 /* We must not try to replace c while it's still the most valid: */
1172 tor_assert(c->fresh_until < start);
1173 /* We must download the next one before c is invalid: */
1174 tor_assert(start+dl_interval < c->valid_until);
1175 time_to_download_next_consensus = start +crypto_rand_int((int)dl_interval);
1177 char tbuf1[ISO_TIME_LEN+1];
1178 char tbuf2[ISO_TIME_LEN+1];
1179 char tbuf3[ISO_TIME_LEN+1];
1180 format_local_iso_time(tbuf1, c->fresh_until);
1181 format_local_iso_time(tbuf2, c->valid_until);
1182 format_local_iso_time(tbuf3, time_to_download_next_consensus);
1183 log_info(LD_DIR, "Live consensus %s the most recent until %s and will "
1184 "expire at %s; fetching the next one at %s.",
1185 (c->fresh_until > now) ? "will be" : "was",
1186 tbuf1, tbuf2, tbuf3);
1188 } else {
1189 time_to_download_next_consensus = now;
1190 log_info(LD_DIR, "No live consensus; we should fetch one immediately.");
1195 /** Return 1 if there's a reason we shouldn't try any directory
1196 * fetches yet (e.g. we demand bridges and none are yet known).
1197 * Else return 0. */
1199 should_delay_dir_fetches(or_options_t *options)
1201 if (options->UseBridges && !any_bridge_descriptors_known()) {
1202 log_info(LD_DIR, "delaying dir fetches (no running bridges known)");
1203 return 1;
1205 return 0;
1208 /** Launch requests for networkstatus documents and authority certificates as
1209 * appropriate. */
1210 void
1211 update_networkstatus_downloads(time_t now)
1213 or_options_t *options = get_options();
1214 if (should_delay_dir_fetches(options))
1215 return;
1216 if (directory_fetches_dir_info_early(options))
1217 update_v2_networkstatus_cache_downloads(now);
1218 update_consensus_networkstatus_downloads(now);
1219 update_certificate_downloads(now);
1222 /** Launch requests as appropriate for missing directory authority
1223 * certificates. */
1224 void
1225 update_certificate_downloads(time_t now)
1227 if (consensus_waiting_for_certs)
1228 authority_certs_fetch_missing(consensus_waiting_for_certs, now);
1229 else
1230 authority_certs_fetch_missing(current_consensus, now);
1233 /** Return 1 if we have a consensus but we don't have enough certificates
1234 * to start using it yet. */
1236 consensus_is_waiting_for_certs(void)
1238 return consensus_waiting_for_certs ? 1 : 0;
1241 /** Return the network status with a given identity digest. */
1242 networkstatus_v2_t *
1243 networkstatus_v2_get_by_digest(const char *digest)
1245 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
1247 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
1248 return ns;
1250 return NULL;
1253 /** Return the most recent consensus that we have downloaded, or NULL if we
1254 * don't have one. */
1255 networkstatus_t *
1256 networkstatus_get_latest_consensus(void)
1258 return current_consensus;
1261 /** Return the most recent consensus that we have downloaded, or NULL if it is
1262 * no longer live. */
1263 networkstatus_t *
1264 networkstatus_get_live_consensus(time_t now)
1266 if (current_consensus &&
1267 current_consensus->valid_after <= now &&
1268 now <= current_consensus->valid_until)
1269 return current_consensus;
1270 else
1271 return NULL;
1274 /* XXXX remove this in favor of get_live_consensus. But actually,
1275 * leave something like it for bridge users, who need to not totally
1276 * lose if they spend a while fetching a new consensus. */
1277 /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
1278 * consensuses. */
1279 networkstatus_t *
1280 networkstatus_get_reasonably_live_consensus(time_t now)
1282 #define REASONABLY_LIVE_TIME (24*60*60)
1283 if (current_consensus &&
1284 current_consensus->valid_after <= now &&
1285 now <= current_consensus->valid_until+REASONABLY_LIVE_TIME)
1286 return current_consensus;
1287 else
1288 return NULL;
1291 /** Given two router status entries for the same router identity, return 1 if
1292 * if the contents have changed between them. Otherwise, return 0. */
1293 static int
1294 routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
1296 tor_assert(!memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN));
1298 return strcmp(a->nickname, b->nickname) ||
1299 memcmp(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
1300 a->addr != b->addr ||
1301 a->or_port != b->or_port ||
1302 a->dir_port != b->dir_port ||
1303 a->is_authority != b->is_authority ||
1304 a->is_exit != b->is_exit ||
1305 a->is_stable != b->is_stable ||
1306 a->is_fast != b->is_fast ||
1307 a->is_running != b->is_running ||
1308 a->is_named != b->is_named ||
1309 a->is_unnamed != b->is_unnamed ||
1310 a->is_valid != b->is_valid ||
1311 a->is_v2_dir != b->is_v2_dir ||
1312 a->is_possible_guard != b->is_possible_guard ||
1313 a->is_bad_exit != b->is_bad_exit ||
1314 a->is_bad_directory != b->is_bad_directory ||
1315 a->is_hs_dir != b->is_hs_dir ||
1316 a->version_known != b->version_known ||
1317 a->version_supports_begindir != b->version_supports_begindir ||
1318 a->version_supports_extrainfo_upload !=
1319 b->version_supports_extrainfo_upload ||
1320 a->version_supports_conditional_consensus !=
1321 b->version_supports_conditional_consensus ||
1322 a->version_supports_v3_dir != b->version_supports_v3_dir;
1325 /** Notify controllers of any router status entries that changed between
1326 * <b>old_c</b> and <b>new_c</b>. */
1327 static void
1328 notify_control_networkstatus_changed(const networkstatus_t *old_c,
1329 const networkstatus_t *new_c)
1331 smartlist_t *changed;
1332 if (old_c == new_c)
1333 return;
1335 /* tell the controller exactly which relays are still listed, as well
1336 * as what they're listed as */
1337 control_event_newconsensus(new_c);
1339 if (!control_event_is_interesting(EVENT_NS))
1340 return;
1342 if (!old_c) {
1343 control_event_networkstatus_changed(new_c->routerstatus_list);
1344 return;
1346 changed = smartlist_create();
1348 SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
1349 new_c->routerstatus_list, routerstatus_t *, rs_new,
1350 memcmp(rs_old->identity_digest,
1351 rs_new->identity_digest, DIGEST_LEN),
1352 smartlist_add(changed, rs_new)) {
1353 if (routerstatus_has_changed(rs_old, rs_new))
1354 smartlist_add(changed, rs_new);
1355 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1357 control_event_networkstatus_changed(changed);
1358 smartlist_free(changed);
1361 /** Copy all the ancillary information (like router download status and so on)
1362 * from <b>old_c</b> to <b>new_c</b>. */
1363 static void
1364 networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
1365 const networkstatus_t *old_c)
1367 if (old_c == new_c)
1368 return;
1369 if (!old_c || !smartlist_len(old_c->routerstatus_list))
1370 return;
1372 SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
1373 new_c->routerstatus_list, routerstatus_t *, rs_new,
1374 memcmp(rs_old->identity_digest,
1375 rs_new->identity_digest, DIGEST_LEN),
1376 STMT_NIL) {
1377 /* Okay, so we're looking at the same identity. */
1378 rs_new->name_lookup_warned = rs_old->name_lookup_warned;
1379 rs_new->last_dir_503_at = rs_old->last_dir_503_at;
1381 if (!memcmp(rs_old->descriptor_digest, rs_new->descriptor_digest,
1382 DIGEST_LEN)) {
1383 /* And the same descriptor too! */
1384 memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
1386 } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1389 /** Try to replace the current cached v3 networkstatus with the one in
1390 * <b>consensus</b>. If we don't have enough certificates to validate it,
1391 * store it in consensus_waiting_for_certs and launch a certificate fetch.
1393 * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
1394 * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
1395 * already received, but we were waiting for certificates on it. If flags &
1396 * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
1397 * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
1398 * consensus, even if it comes from many days in the past.
1400 * Return 0 on success, <0 on failure. On failure, caller should increment
1401 * the failure count as appropriate.
1403 * We return -1 for mild failures that don't need to be reported to the
1404 * user, and -2 for more serious problems.
1407 networkstatus_set_current_consensus(const char *consensus, unsigned flags)
1409 networkstatus_t *c;
1410 int r, result = -1;
1411 time_t now = time(NULL);
1412 char *unverified_fname = NULL, *consensus_fname = NULL;
1413 const unsigned from_cache = flags & NSSET_FROM_CACHE;
1414 const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
1415 const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
1416 const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
1418 /* Make sure it's parseable. */
1419 c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
1420 if (!c) {
1421 log_warn(LD_DIR, "Unable to parse networkstatus consensus");
1422 result = -2;
1423 goto done;
1426 if (from_cache && !accept_obsolete &&
1427 c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
1428 /* XXX022 when we try to make fallbackconsensus work again, we should
1429 * consider taking this out. Until then, believing obsolete consensuses
1430 * is causing more harm than good. See also bug 887. */
1431 log_info(LD_DIR, "Loaded an obsolete consensus. Discarding.");
1432 goto done;
1435 if (current_consensus &&
1436 !memcmp(c->networkstatus_digest, current_consensus->networkstatus_digest,
1437 DIGEST_LEN)) {
1438 /* We already have this one. That's a failure. */
1439 log_info(LD_DIR, "Got a consensus we already have");
1440 goto done;
1443 if (current_consensus && c->valid_after <= current_consensus->valid_after) {
1444 /* We have a newer one. There's no point in accepting this one,
1445 * even if it's great. */
1446 log_info(LD_DIR, "Got a consensus at least as old as the one we have");
1447 goto done;
1450 consensus_fname = get_datadir_fname("cached-consensus");
1451 unverified_fname = get_datadir_fname("unverified-consensus");
1453 /* Make sure it's signed enough. */
1454 if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
1455 if (r == -1) {
1456 /* Okay, so it _might_ be signed enough if we get more certificates. */
1457 if (!was_waiting_for_certs) {
1458 log_info(LD_DIR,
1459 "Not enough certificates to check networkstatus consensus");
1461 if (!current_consensus ||
1462 c->valid_after > current_consensus->valid_after) {
1463 if (consensus_waiting_for_certs)
1464 networkstatus_vote_free(consensus_waiting_for_certs);
1465 tor_free(consensus_waiting_for_certs_body);
1466 consensus_waiting_for_certs = c;
1467 c = NULL; /* Prevent free. */
1468 consensus_waiting_for_certs_body = tor_strdup(consensus);
1469 consensus_waiting_for_certs_set_at = now;
1470 consensus_waiting_for_certs_dl_failed = 0;
1471 if (!from_cache) {
1472 write_str_to_file(unverified_fname, consensus, 0);
1474 if (dl_certs)
1475 authority_certs_fetch_missing(c, now);
1476 /* This case is not a success or a failure until we get the certs
1477 * or fail to get the certs. */
1478 result = 0;
1479 } else {
1480 /* Even if we had enough signatures, we'd never use this as the
1481 * latest consensus. */
1482 if (was_waiting_for_certs && from_cache)
1483 unlink(unverified_fname);
1485 goto done;
1486 } else {
1487 /* This can never be signed enough: Kill it. */
1488 if (!was_waiting_for_certs) {
1489 log_warn(LD_DIR, "Not enough good signatures on networkstatus "
1490 "consensus");
1491 result = -2;
1493 if (was_waiting_for_certs && (r < -1) && from_cache)
1494 unlink(unverified_fname);
1495 goto done;
1499 if (!from_cache)
1500 control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
1502 /* Are we missing any certificates at all? */
1503 if (r != 1 && dl_certs)
1504 authority_certs_fetch_missing(c, now);
1506 notify_control_networkstatus_changed(current_consensus, c);
1508 if (current_consensus) {
1509 networkstatus_copy_old_consensus_info(c, current_consensus);
1510 networkstatus_vote_free(current_consensus);
1513 if (consensus_waiting_for_certs &&
1514 consensus_waiting_for_certs->valid_after <= c->valid_after) {
1515 networkstatus_vote_free(consensus_waiting_for_certs);
1516 consensus_waiting_for_certs = NULL;
1517 if (consensus != consensus_waiting_for_certs_body)
1518 tor_free(consensus_waiting_for_certs_body);
1519 else
1520 consensus_waiting_for_certs_body = NULL;
1521 consensus_waiting_for_certs_set_at = 0;
1522 consensus_waiting_for_certs_dl_failed = 0;
1523 unlink(unverified_fname);
1526 /* Reset the failure count only if this consensus is actually valid. */
1527 if (c->valid_after <= now && now <= c->valid_until) {
1528 download_status_reset(&consensus_dl_status);
1529 } else {
1530 if (!from_cache)
1531 download_status_failed(&consensus_dl_status, 0);
1534 current_consensus = c;
1535 c = NULL; /* Prevent free. */
1537 update_consensus_networkstatus_fetch_time(now);
1538 dirvote_recalculate_timing(get_options(), now);
1539 routerstatus_list_update_named_server_map();
1541 if (!from_cache) {
1542 write_str_to_file(consensus_fname, consensus, 0);
1545 if (directory_caches_dir_info(get_options()))
1546 dirserv_set_cached_networkstatus_v3(consensus,
1547 current_consensus->valid_after);
1549 if (ftime_definitely_before(now, current_consensus->valid_after)) {
1550 char tbuf[ISO_TIME_LEN+1];
1551 char dbuf[64];
1552 long delta = now - current_consensus->valid_after;
1553 format_iso_time(tbuf, current_consensus->valid_after);
1554 format_time_interval(dbuf, sizeof(dbuf), delta);
1555 log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
1556 "consensus network status document (%s GMT). Tor needs an "
1557 "accurate clock to work correctly. Please check your time and "
1558 "date settings!", dbuf, tbuf);
1559 control_event_general_status(LOG_WARN,
1560 "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
1563 router_dir_info_changed();
1565 result = 0;
1566 done:
1567 if (c)
1568 networkstatus_vote_free(c);
1569 tor_free(consensus_fname);
1570 tor_free(unverified_fname);
1571 return result;
1574 /** Called when we have gotten more certificates: see whether we can
1575 * now verify a pending consensus. */
1576 void
1577 networkstatus_note_certs_arrived(void)
1579 if (consensus_waiting_for_certs) {
1580 if (networkstatus_check_consensus_signature(
1581 consensus_waiting_for_certs, 0)>=0) {
1582 if (!networkstatus_set_current_consensus(
1583 consensus_waiting_for_certs_body,
1584 NSSET_WAS_WAITING_FOR_CERTS)) {
1585 tor_free(consensus_waiting_for_certs_body);
1591 /** If the network-status list has changed since the last time we called this
1592 * function, update the status of every routerinfo from the network-status
1593 * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
1594 * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
1596 void
1597 routers_update_all_from_networkstatus(time_t now, int dir_version)
1599 routerlist_t *rl = router_get_routerlist();
1600 networkstatus_t *consensus = networkstatus_get_live_consensus(now);
1602 if (networkstatus_v2_list_has_changed)
1603 download_status_map_update_from_v2_networkstatus();
1605 if (!consensus || dir_version < 3) /* nothing more we should do */
1606 return;
1608 /* calls router_dir_info_changed() when it's done -- more routers
1609 * might be up or down now, which might affect whether there's enough
1610 * directory info. */
1611 routers_update_status_from_consensus_networkstatus(rl->routers, 0);
1613 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
1614 ri->cache_info.routerlist_index = ri_sl_idx);
1615 if (rl->old_routers)
1616 signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
1618 if (!have_warned_about_old_version) {
1619 int is_server = server_mode(get_options());
1620 version_status_t status;
1621 const char *recommended = is_server ?
1622 consensus->server_versions : consensus->client_versions;
1623 status = tor_version_is_obsolete(VERSION, recommended);
1625 if (status == VS_RECOMMENDED) {
1626 log_info(LD_GENERAL, "The directory authorities say my version is ok.");
1627 } else if (status == VS_EMPTY) {
1628 log_info(LD_GENERAL,
1629 "The directory authorities don't recommend any versions.");
1630 } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
1631 if (!have_warned_about_new_version) {
1632 log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
1633 "recommended version%s, according to the directory "
1634 "authorities. Recommended versions are: %s",
1635 VERSION,
1636 status == VS_NEW_IN_SERIES ? " in its series" : "",
1637 recommended);
1638 have_warned_about_new_version = 1;
1639 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
1640 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
1641 VERSION, "NEW", recommended);
1643 } else {
1644 log_warn(LD_GENERAL, "Please upgrade! "
1645 "This version of Tor (%s) is %s, according to the directory "
1646 "authorities. Recommended versions are: %s",
1647 VERSION,
1648 status == VS_OLD ? "obsolete" : "not recommended",
1649 recommended);
1650 have_warned_about_old_version = 1;
1651 control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
1652 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
1653 VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
1654 recommended);
1659 /** Update v2_download_status_map to contain an entry for every router
1660 * descriptor listed in the v2 networkstatuses. */
1661 static void
1662 download_status_map_update_from_v2_networkstatus(void)
1664 digestmap_t *dl_status;
1665 if (!networkstatus_v2_list)
1666 return;
1667 if (!v2_download_status_map)
1668 v2_download_status_map = digestmap_new();
1670 dl_status = digestmap_new();
1671 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
1673 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
1675 const char *d = rs->descriptor_digest;
1676 download_status_t *s;
1677 if (digestmap_get(dl_status, d))
1678 continue;
1679 if (!(s = digestmap_remove(v2_download_status_map, d))) {
1680 s = tor_malloc_zero(sizeof(download_status_t));
1682 digestmap_set(dl_status, d, s);
1685 digestmap_free(v2_download_status_map, _tor_free);
1686 v2_download_status_map = dl_status;
1687 networkstatus_v2_list_has_changed = 0;
1690 /** Update our view of the list of named servers from the most recently
1691 * retrieved networkstatus consensus. */
1692 static void
1693 routerstatus_list_update_named_server_map(void)
1695 if (!current_consensus)
1696 return;
1698 if (named_server_map)
1699 strmap_free(named_server_map, _tor_free);
1700 named_server_map = strmap_new();
1701 if (unnamed_server_map)
1702 strmap_free(unnamed_server_map, NULL);
1703 unnamed_server_map = strmap_new();
1704 SMARTLIST_FOREACH(current_consensus->routerstatus_list, routerstatus_t *, rs,
1706 if (rs->is_named) {
1707 strmap_set_lc(named_server_map, rs->nickname,
1708 tor_memdup(rs->identity_digest, DIGEST_LEN));
1710 if (rs->is_unnamed) {
1711 strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
1716 /** Given a list <b>routers</b> of routerinfo_t *, update each status field
1717 * according to our current consensus networkstatus. May re-order
1718 * <b>routers</b>. */
1719 void
1720 routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
1721 int reset_failures)
1723 trusted_dir_server_t *ds;
1724 or_options_t *options = get_options();
1725 int authdir = authdir_mode_v2(options) || authdir_mode_v3(options);
1726 int namingdir = authdir && options->NamingAuthoritativeDir;
1727 networkstatus_t *ns = current_consensus;
1728 if (!ns || !smartlist_len(ns->routerstatus_list))
1729 return;
1730 if (!networkstatus_v2_list)
1731 networkstatus_v2_list = smartlist_create();
1733 routers_sort_by_identity(routers);
1735 SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
1736 routers, routerinfo_t *, router,
1737 memcmp(rs->identity_digest,
1738 router->cache_info.identity_digest, DIGEST_LEN),
1740 /* We have no routerstatus for this router. Clear flags and skip it. */
1741 if (!namingdir)
1742 router->is_named = 0;
1743 if (!authdir) {
1744 if (router->purpose == ROUTER_PURPOSE_GENERAL)
1745 router_clear_status_flags(router);
1747 }) {
1748 /* We have a routerstatus for this router. */
1749 const char *digest = router->cache_info.identity_digest;
1751 ds = router_get_trusteddirserver_by_digest(digest);
1753 if (!namingdir) {
1754 if (rs->is_named && !strcasecmp(router->nickname, rs->nickname))
1755 router->is_named = 1;
1756 else
1757 router->is_named = 0;
1759 /* Is it the same descriptor, or only the same identity? */
1760 if (!memcmp(router->cache_info.signed_descriptor_digest,
1761 rs->descriptor_digest, DIGEST_LEN)) {
1762 if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
1763 router->cache_info.last_listed_as_valid_until = ns->valid_until;
1766 if (!authdir) {
1767 /* If we're not an authdir, believe others. */
1768 router->is_valid = rs->is_valid;
1769 router->is_running = rs->is_running;
1770 router->is_fast = rs->is_fast;
1771 router->is_stable = rs->is_stable;
1772 router->is_possible_guard = rs->is_possible_guard;
1773 router->is_exit = rs->is_exit;
1774 router->is_bad_directory = rs->is_bad_directory;
1775 router->is_bad_exit = rs->is_bad_exit;
1776 router->is_hs_dir = rs->is_hs_dir;
1778 if (router->is_running && ds) {
1779 download_status_reset(&ds->v2_ns_dl_status);
1781 if (reset_failures) {
1782 download_status_reset(&rs->dl_status);
1784 } SMARTLIST_FOREACH_JOIN_END(rs, router);
1786 /* Now update last_listed_as_valid_until from v2 networkstatuses. */
1787 /* XXXX If this is slow, we need to rethink the code. */
1788 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns, {
1789 time_t live_until = ns->published_on + V2_NETWORKSTATUS_ROUTER_LIFETIME;
1790 SMARTLIST_FOREACH_JOIN(ns->entries, routerstatus_t *, rs,
1791 routers, routerinfo_t *, ri,
1792 memcmp(rs->identity_digest,
1793 ri->cache_info.identity_digest, DIGEST_LEN),
1794 STMT_NIL) {
1795 if (!memcmp(ri->cache_info.signed_descriptor_digest,
1796 rs->descriptor_digest, DIGEST_LEN)) {
1797 if (live_until > ri->cache_info.last_listed_as_valid_until)
1798 ri->cache_info.last_listed_as_valid_until = live_until;
1800 } SMARTLIST_FOREACH_JOIN_END(rs, ri);
1803 router_dir_info_changed();
1806 /** Given a list of signed_descriptor_t, update their fields (mainly, when
1807 * they were last listed) from the most recent consensus. */
1808 void
1809 signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
1811 networkstatus_t *ns = current_consensus;
1812 if (!ns)
1813 return;
1815 if (!ns->desc_digest_map) {
1816 char dummy[DIGEST_LEN];
1817 /* instantiates the digest map. */
1818 memset(dummy, 0, sizeof(dummy));
1819 router_get_consensus_status_by_descriptor_digest(dummy);
1821 SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
1823 routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
1824 d->signed_descriptor_digest);
1825 if (rs) {
1826 if (ns->valid_until > d->last_listed_as_valid_until)
1827 d->last_listed_as_valid_until = ns->valid_until;
1832 /** Generate networkstatus lines for a single routerstatus_t object, and
1833 * return the result in a newly allocated string. Used only by controller
1834 * interface (for now.) */
1835 char *
1836 networkstatus_getinfo_helper_single(routerstatus_t *rs)
1838 char buf[RS_ENTRY_LEN+1];
1839 routerstatus_format_entry(buf, sizeof(buf), rs, NULL, 0, 1);
1840 return tor_strdup(buf);
1843 /** Alloc and return a string describing routerstatuses for the most
1844 * recent info of each router we know about that is of purpose
1845 * <b>purpose_string</b>. Return NULL if unrecognized purpose.
1847 * Right now this function is oriented toward listing bridges (you
1848 * shouldn't use this for general-purpose routers, since those
1849 * should be listed from the consensus, not from the routers list). */
1850 char *
1851 networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
1853 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
1854 char *answer;
1855 routerlist_t *rl = router_get_routerlist();
1856 smartlist_t *statuses;
1857 uint8_t purpose = router_purpose_from_string(purpose_string);
1858 routerstatus_t rs;
1859 int bridge_auth = authdir_mode_bridge(get_options());
1861 if (purpose == ROUTER_PURPOSE_UNKNOWN) {
1862 log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
1863 purpose_string);
1864 return NULL;
1867 statuses = smartlist_create();
1868 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
1869 if (ri->cache_info.published_on < cutoff)
1870 continue;
1871 if (ri->purpose != purpose)
1872 continue;
1873 if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
1874 dirserv_set_router_is_running(ri, now);
1875 /* then generate and write out status lines for each of them */
1876 set_routerstatus_from_routerinfo(&rs, ri, now, 0, 0, 0, 0);
1877 smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
1880 answer = smartlist_join_strings(statuses, "", 0, NULL);
1881 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
1882 smartlist_free(statuses);
1883 return answer;
1886 /** Write out router status entries for all our bridge descriptors. */
1887 void
1888 networkstatus_dump_bridge_status_to_file(time_t now)
1890 char *status = networkstatus_getinfo_by_purpose("bridge", now);
1891 or_options_t *options = get_options();
1892 size_t len = strlen(options->DataDirectory) + 32;
1893 char *fname = tor_malloc(len);
1894 tor_snprintf(fname, len, "%s"PATH_SEPARATOR"networkstatus-bridges",
1895 options->DataDirectory);
1896 write_str_to_file(fname,status,0);
1897 tor_free(fname);
1898 tor_free(status);
1901 /** Return the value of a integer parameter from the networkstatus <b>ns</b>
1902 * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
1903 * latest consensus ourselves. Return <b>default_val</b> if no latest
1904 * consensus, or if it has no parameter called <b>param_name</b>. */
1905 int32_t
1906 networkstatus_get_param(networkstatus_t *ns, const char *param_name,
1907 int32_t default_val)
1909 size_t name_len;
1911 if (!ns) /* if they pass in null, go find it ourselves */
1912 ns = networkstatus_get_latest_consensus();
1914 if (!ns || !ns->net_params)
1915 return default_val;
1917 name_len = strlen(param_name);
1919 SMARTLIST_FOREACH_BEGIN(ns->net_params, const char *, p) {
1920 if (!strcmpstart(p, param_name) && p[name_len] == '=') {
1921 int ok=0;
1922 long v = tor_parse_long(p+name_len+1, 10, INT32_MIN, INT32_MAX, &ok,
1923 NULL);
1924 if (ok)
1925 return (int32_t) v;
1927 } SMARTLIST_FOREACH_END(p);
1929 return default_val;
1932 /** If <b>question</b> is a string beginning with "ns/" in a format the
1933 * control interface expects for a GETINFO question, set *<b>answer</b> to a
1934 * newly-allocated string containing networkstatus lines for the appropriate
1935 * ORs. Return 0 on success, -1 on unrecognized question format. */
1937 getinfo_helper_networkstatus(control_connection_t *conn,
1938 const char *question, char **answer)
1940 routerstatus_t *status;
1941 (void) conn;
1943 if (!current_consensus) {
1944 *answer = tor_strdup("");
1945 return 0;
1948 if (!strcmp(question, "ns/all")) {
1949 smartlist_t *statuses = smartlist_create();
1950 SMARTLIST_FOREACH(current_consensus->routerstatus_list,
1951 routerstatus_t *, rs,
1953 smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
1955 *answer = smartlist_join_strings(statuses, "", 0, NULL);
1956 SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
1957 smartlist_free(statuses);
1958 return 0;
1959 } else if (!strcmpstart(question, "ns/id/")) {
1960 char d[DIGEST_LEN];
1962 if (base16_decode(d, DIGEST_LEN, question+6, strlen(question+6)))
1963 return -1;
1964 status = router_get_consensus_status_by_id(d);
1965 } else if (!strcmpstart(question, "ns/name/")) {
1966 status = router_get_consensus_status_by_nickname(question+8, 0);
1967 } else if (!strcmpstart(question, "ns/purpose/")) {
1968 *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
1969 return *answer ? 0 : -1;
1970 } else {
1971 return -1;
1974 if (status)
1975 *answer = networkstatus_getinfo_helper_single(status);
1976 return 0;
1979 /** Free all storage held locally in this module. */
1980 void
1981 networkstatus_free_all(void)
1983 if (networkstatus_v2_list) {
1984 SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
1985 networkstatus_v2_free(ns));
1986 smartlist_free(networkstatus_v2_list);
1987 networkstatus_v2_list = NULL;
1989 if (v2_download_status_map) {
1990 digestmap_free(v2_download_status_map, _tor_free);
1991 v2_download_status_map = NULL;
1993 if (current_consensus) {
1994 networkstatus_vote_free(current_consensus);
1995 current_consensus = NULL;
1997 if (consensus_waiting_for_certs) {
1998 networkstatus_vote_free(consensus_waiting_for_certs);
1999 consensus_waiting_for_certs = NULL;
2001 tor_free(consensus_waiting_for_certs_body);
2002 if (named_server_map) {
2003 strmap_free(named_server_map, _tor_free);
2005 if (unnamed_server_map) {
2006 strmap_free(unnamed_server_map, NULL);