Back to index

tor  0.2.3.19-rc
networkstatus.c
Go to the documentation of this file.
00001 /* Copyright (c) 2001 Matej Pfajfar.
00002  * Copyright (c) 2001-2004, Roger Dingledine.
00003  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00004  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00005 /* See LICENSE for licensing information */
00006 
00013 #include "or.h"
00014 #include "circuitbuild.h"
00015 #include "config.h"
00016 #include "connection.h"
00017 #include "connection_or.h"
00018 #include "control.h"
00019 #include "directory.h"
00020 #include "dirserv.h"
00021 #include "dirvote.h"
00022 #include "main.h"
00023 #include "microdesc.h"
00024 #include "networkstatus.h"
00025 #include "nodelist.h"
00026 #include "relay.h"
00027 #include "router.h"
00028 #include "routerlist.h"
00029 #include "routerparse.h"
00030 
00031 /* For tracking v2 networkstatus documents.  Only caches do this now. */
00032 
00035 static digestmap_t *v2_download_status_map = NULL;
00038 static smartlist_t *networkstatus_v2_list = NULL;
00041 static int networkstatus_v2_list_has_changed = 0;
00042 
00044 static strmap_t *named_server_map = NULL;
00047 static strmap_t *unnamed_server_map = NULL;
00048 
00053 #define current_consensus                                       \
00054   (we_use_microdescriptors_for_circuits(get_options()) ?        \
00055    current_md_consensus : current_ns_consensus)
00056 
00059 static networkstatus_t *current_ns_consensus = NULL;
00060 
00063 static networkstatus_t *current_md_consensus = NULL;
00064 
00067 typedef struct consensus_waiting_for_certs_t {
00069   networkstatus_t *consensus;
00071   char *body;
00075   time_t set_at;
00078   int dl_failed;
00079 } consensus_waiting_for_certs_t;
00080 
00084 static consensus_waiting_for_certs_t
00085        consensus_waiting_for_certs[N_CONSENSUS_FLAVORS];
00086 
00090 static time_t last_networkstatus_download_attempted = 0;
00091 
00095 static time_t time_to_download_next_consensus[N_CONSENSUS_FLAVORS];
00097 static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS];
00098 
00101 static int have_warned_about_old_version = 0;
00104 static int have_warned_about_new_version = 0;
00105 
00106 static void download_status_map_update_from_v2_networkstatus(void);
00107 static void routerstatus_list_update_named_server_map(void);
00108 
00111 void
00112 networkstatus_reset_warnings(void)
00113 {
00114   if (current_consensus) {
00115     SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
00116                       node->name_lookup_warned = 0);
00117   }
00118 
00119   have_warned_about_old_version = 0;
00120   have_warned_about_new_version = 0;
00121 }
00122 
00126 void
00127 networkstatus_reset_download_failures(void)
00128 {
00129   int i;
00130   const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
00131   SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
00132      SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
00133        {
00134          if (!router_get_by_descriptor_digest(rs->descriptor_digest))
00135            rs->need_to_mirror = 1;
00136        }));;
00137 
00138   for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
00139     download_status_reset(&consensus_dl_status[i]);
00140   if (v2_download_status_map) {
00141     digestmap_iter_t *iter;
00142     digestmap_t *map = v2_download_status_map;
00143     const char *key;
00144     void *val;
00145     download_status_t *dls;
00146     for (iter = digestmap_iter_init(map); !digestmap_iter_done(iter);
00147          iter = digestmap_iter_next(map, iter) ) {
00148       digestmap_iter_get(iter, &key, &val);
00149       dls = val;
00150       download_status_reset(dls);
00151     }
00152   }
00153 }
00154 
00157 int
00158 router_reload_v2_networkstatus(void)
00159 {
00160   smartlist_t *entries;
00161   struct stat st;
00162   char *s;
00163   char *filename = get_datadir_fname("cached-status");
00164   int maybe_delete = !directory_caches_v2_dir_info(get_options());
00165   time_t now = time(NULL);
00166   if (!networkstatus_v2_list)
00167     networkstatus_v2_list = smartlist_new();
00168 
00169   entries = tor_listdir(filename);
00170   if (!entries) { /* dir doesn't exist */
00171     tor_free(filename);
00172     return 0;
00173   } else if (!smartlist_len(entries) && maybe_delete) {
00174     rmdir(filename);
00175     tor_free(filename);
00176     smartlist_free(entries);
00177     return 0;
00178   }
00179   tor_free(filename);
00180   SMARTLIST_FOREACH(entries, const char *, fn, {
00181       char buf[DIGEST_LEN];
00182       if (maybe_delete) {
00183         filename = get_datadir_fname2("cached-status", fn);
00184         remove_file_if_very_old(filename, now);
00185         tor_free(filename);
00186         continue;
00187       }
00188       if (strlen(fn) != HEX_DIGEST_LEN ||
00189           base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
00190         log_info(LD_DIR,
00191                  "Skipping cached-status file with unexpected name \"%s\"",fn);
00192         continue;
00193       }
00194       filename = get_datadir_fname2("cached-status", fn);
00195       s = read_file_to_str(filename, 0, &st);
00196       if (s) {
00197         if (router_set_networkstatus_v2(s, st.st_mtime, NS_FROM_CACHE,
00198                                         NULL)<0) {
00199           log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
00200         }
00201         tor_free(s);
00202       }
00203       tor_free(filename);
00204     });
00205   SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
00206   smartlist_free(entries);
00207   networkstatus_v2_list_clean(time(NULL));
00208   routers_update_all_from_networkstatus(time(NULL), 2);
00209   return 0;
00210 }
00211 
00213 int
00214 router_reload_consensus_networkstatus(void)
00215 {
00216   char *filename;
00217   char *s;
00218   struct stat st;
00219   const or_options_t *options = get_options();
00220   const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
00221   int flav;
00222 
00223   /* FFFF Suppress warnings if cached consensus is bad? */
00224   for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
00225     char buf[128];
00226     const char *flavor = networkstatus_get_flavor_name(flav);
00227     if (flav == FLAV_NS) {
00228       filename = get_datadir_fname("cached-consensus");
00229     } else {
00230       tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
00231       filename = get_datadir_fname(buf);
00232     }
00233     s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
00234     if (s) {
00235       if (networkstatus_set_current_consensus(s, flavor, flags) < -1) {
00236         log_warn(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
00237                  flavor, filename);
00238       }
00239       tor_free(s);
00240     }
00241     tor_free(filename);
00242 
00243     if (flav == FLAV_NS) {
00244       filename = get_datadir_fname("unverified-consensus");
00245     } else {
00246       tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
00247       filename = get_datadir_fname(buf);
00248     }
00249 
00250     s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
00251     if (s) {
00252       if (networkstatus_set_current_consensus(s, flavor,
00253                                      flags|NSSET_WAS_WAITING_FOR_CERTS)) {
00254       log_info(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
00255                flavor, filename);
00256     }
00257       tor_free(s);
00258     }
00259     tor_free(filename);
00260   }
00261 
00262   if (!current_consensus ||
00263       (stat(options->FallbackNetworkstatusFile, &st)==0 &&
00264        st.st_mtime > current_consensus->valid_after)) {
00265     s = read_file_to_str(options->FallbackNetworkstatusFile,
00266                          RFTS_IGNORE_MISSING, NULL);
00267     if (s) {
00268       if (networkstatus_set_current_consensus(s, "ns",
00269                                               flags|NSSET_ACCEPT_OBSOLETE)) {
00270         log_info(LD_FS, "Couldn't load consensus networkstatus from \"%s\"",
00271                  options->FallbackNetworkstatusFile);
00272       } else {
00273         log_notice(LD_FS,
00274                    "Loaded fallback consensus networkstatus from \"%s\"",
00275                    options->FallbackNetworkstatusFile);
00276       }
00277       tor_free(s);
00278     }
00279   }
00280 
00281   if (!current_consensus) {
00282     if (!named_server_map)
00283       named_server_map = strmap_new();
00284     if (!unnamed_server_map)
00285       unnamed_server_map = strmap_new();
00286   }
00287 
00288   update_certificate_downloads(time(NULL));
00289 
00290   routers_update_all_from_networkstatus(time(NULL), 3);
00291   update_microdescs_from_networkstatus(time(NULL));
00292 
00293   return 0;
00294 }
00295 
00297 static void
00298 vote_routerstatus_free(vote_routerstatus_t *rs)
00299 {
00300   vote_microdesc_hash_t *h, *next;
00301   if (!rs)
00302     return;
00303   tor_free(rs->version);
00304   tor_free(rs->status.exitsummary);
00305   for (h = rs->microdesc; h; h = next) {
00306     tor_free(h->microdesc_hash_line);
00307     next = h->next;
00308     tor_free(h);
00309   }
00310   tor_free(rs);
00311 }
00312 
00314 void
00315 routerstatus_free(routerstatus_t *rs)
00316 {
00317   if (!rs)
00318     return;
00319   tor_free(rs->exitsummary);
00320   tor_free(rs);
00321 }
00322 
00324 void
00325 networkstatus_v2_free(networkstatus_v2_t *ns)
00326 {
00327   if (!ns)
00328     return;
00329   tor_free(ns->source_address);
00330   tor_free(ns->contact);
00331   if (ns->signing_key)
00332     crypto_pk_free(ns->signing_key);
00333   tor_free(ns->client_versions);
00334   tor_free(ns->server_versions);
00335   if (ns->entries) {
00336     SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
00337                       routerstatus_free(rs));
00338     smartlist_free(ns->entries);
00339   }
00340   tor_free(ns);
00341 }
00342 
00344 void
00345 document_signature_free(document_signature_t *sig)
00346 {
00347   tor_free(sig->signature);
00348   tor_free(sig);
00349 }
00350 
00352 document_signature_t *
00353 document_signature_dup(const document_signature_t *sig)
00354 {
00355   document_signature_t *r = tor_memdup(sig, sizeof(document_signature_t));
00356   if (r->signature)
00357     r->signature = tor_memdup(sig->signature, sig->signature_len);
00358   return r;
00359 }
00360 
00362 void
00363 networkstatus_vote_free(networkstatus_t *ns)
00364 {
00365   if (!ns)
00366     return;
00367 
00368   tor_free(ns->client_versions);
00369   tor_free(ns->server_versions);
00370   if (ns->known_flags) {
00371     SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
00372     smartlist_free(ns->known_flags);
00373   }
00374   if (ns->weight_params) {
00375     SMARTLIST_FOREACH(ns->weight_params, char *, c, tor_free(c));
00376     smartlist_free(ns->weight_params);
00377   }
00378   if (ns->net_params) {
00379     SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
00380     smartlist_free(ns->net_params);
00381   }
00382   if (ns->supported_methods) {
00383     SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
00384     smartlist_free(ns->supported_methods);
00385   }
00386   if (ns->voters) {
00387     SMARTLIST_FOREACH_BEGIN(ns->voters, networkstatus_voter_info_t *, voter) {
00388       tor_free(voter->nickname);
00389       tor_free(voter->address);
00390       tor_free(voter->contact);
00391       if (voter->sigs) {
00392         SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
00393                           document_signature_free(sig));
00394         smartlist_free(voter->sigs);
00395       }
00396       tor_free(voter);
00397     } SMARTLIST_FOREACH_END(voter);
00398     smartlist_free(ns->voters);
00399   }
00400   authority_cert_free(ns->cert);
00401 
00402   if (ns->routerstatus_list) {
00403     if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
00404       SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
00405                         vote_routerstatus_free(rs));
00406     } else {
00407       SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
00408                         routerstatus_free(rs));
00409     }
00410 
00411     smartlist_free(ns->routerstatus_list);
00412   }
00413 
00414   digestmap_free(ns->desc_digest_map, NULL);
00415 
00416   memset(ns, 11, sizeof(*ns));
00417   tor_free(ns);
00418 }
00419 
00423 networkstatus_voter_info_t *
00424 networkstatus_get_voter_by_id(networkstatus_t *vote,
00425                               const char *identity)
00426 {
00427   if (!vote || !vote->voters)
00428     return NULL;
00429   SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
00430     if (fast_memeq(voter->identity_digest, identity, DIGEST_LEN))
00431       return voter);
00432   return NULL;
00433 }
00434 
00439 int
00440 networkstatus_check_document_signature(const networkstatus_t *consensus,
00441                                        document_signature_t *sig,
00442                                        const authority_cert_t *cert)
00443 {
00444   char key_digest[DIGEST_LEN];
00445   const int dlen = sig->alg == DIGEST_SHA1 ? DIGEST_LEN : DIGEST256_LEN;
00446   char *signed_digest;
00447   size_t signed_digest_len;
00448 
00449   if (crypto_pk_get_digest(cert->signing_key, key_digest)<0)
00450     return -1;
00451   if (tor_memneq(sig->signing_key_digest, key_digest, DIGEST_LEN) ||
00452       tor_memneq(sig->identity_digest, cert->cache_info.identity_digest,
00453                  DIGEST_LEN))
00454     return -1;
00455 
00456   signed_digest_len = crypto_pk_keysize(cert->signing_key);
00457   signed_digest = tor_malloc(signed_digest_len);
00458   if (crypto_pk_public_checksig(cert->signing_key,
00459                                 signed_digest,
00460                                 signed_digest_len,
00461                                 sig->signature,
00462                                 sig->signature_len) < dlen ||
00463       tor_memneq(signed_digest, consensus->digests.d[sig->alg], dlen)) {
00464     log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
00465     sig->bad_signature = 1;
00466   } else {
00467     sig->good_signature = 1;
00468   }
00469   tor_free(signed_digest);
00470   return 0;
00471 }
00472 
00481 int
00482 networkstatus_check_consensus_signature(networkstatus_t *consensus,
00483                                         int warn)
00484 {
00485   int n_good = 0;
00486   int n_missing_key = 0, n_dl_failed_key = 0;
00487   int n_bad = 0;
00488   int n_unknown = 0;
00489   int n_no_signature = 0;
00490   int n_v3_authorities = get_n_authorities(V3_DIRINFO);
00491   int n_required = n_v3_authorities/2 + 1;
00492   smartlist_t *list_good = smartlist_new();
00493   smartlist_t *list_no_signature = smartlist_new();
00494   smartlist_t *need_certs_from = smartlist_new();
00495   smartlist_t *unrecognized = smartlist_new();
00496   smartlist_t *missing_authorities = smartlist_new();
00497   int severity;
00498   time_t now = time(NULL);
00499 
00500   tor_assert(consensus->type == NS_TYPE_CONSENSUS);
00501 
00502   SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *,
00503                           voter) {
00504     int good_here = 0;
00505     int bad_here = 0;
00506     int unknown_here = 0;
00507     int missing_key_here = 0, dl_failed_key_here = 0;
00508     SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
00509       if (!sig->good_signature && !sig->bad_signature &&
00510           sig->signature) {
00511         /* we can try to check the signature. */
00512         int is_v3_auth = trusteddirserver_get_by_v3_auth_digest(
00513                                               sig->identity_digest) != NULL;
00514         authority_cert_t *cert =
00515           authority_cert_get_by_digests(sig->identity_digest,
00516                                         sig->signing_key_digest);
00517         tor_assert(tor_memeq(sig->identity_digest, voter->identity_digest,
00518                            DIGEST_LEN));
00519 
00520         if (!is_v3_auth) {
00521           smartlist_add(unrecognized, voter);
00522           ++unknown_here;
00523           continue;
00524         } else if (!cert || cert->expires < now) {
00525           smartlist_add(need_certs_from, voter);
00526           ++missing_key_here;
00527           if (authority_cert_dl_looks_uncertain(sig->identity_digest))
00528             ++dl_failed_key_here;
00529           continue;
00530         }
00531         if (networkstatus_check_document_signature(consensus, sig, cert) < 0) {
00532           smartlist_add(need_certs_from, voter);
00533           ++missing_key_here;
00534           if (authority_cert_dl_looks_uncertain(sig->identity_digest))
00535             ++dl_failed_key_here;
00536           continue;
00537         }
00538       }
00539       if (sig->good_signature)
00540         ++good_here;
00541       else if (sig->bad_signature)
00542         ++bad_here;
00543     } SMARTLIST_FOREACH_END(sig);
00544 
00545     if (good_here) {
00546       ++n_good;
00547       smartlist_add(list_good, voter->nickname);
00548     } else if (bad_here) {
00549       ++n_bad;
00550     } else if (missing_key_here) {
00551       ++n_missing_key;
00552       if (dl_failed_key_here)
00553         ++n_dl_failed_key;
00554     } else if (unknown_here) {
00555       ++n_unknown;
00556     } else {
00557       ++n_no_signature;
00558       smartlist_add(list_no_signature, voter->nickname);
00559     }
00560   } SMARTLIST_FOREACH_END(voter);
00561 
00562   /* Now see whether we're missing any voters entirely. */
00563   SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
00564                     trusted_dir_server_t *, ds,
00565     {
00566       if ((ds->type & V3_DIRINFO) &&
00567           !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
00568         smartlist_add(missing_authorities, ds);
00569     });
00570 
00571   if (warn > 1 || (warn >= 0 &&
00572                    (n_good + n_missing_key - n_dl_failed_key < n_required))) {
00573     severity = LOG_WARN;
00574   } else {
00575     severity = LOG_INFO;
00576   }
00577 
00578   if (warn >= 0) {
00579     SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
00580       {
00581         log(severity, LD_DIR, "Consensus includes unrecognized authority "
00582                  "'%s' at %s:%d (contact %s; identity %s)",
00583                  voter->nickname, voter->address, (int)voter->dir_port,
00584                  voter->contact?voter->contact:"n/a",
00585                  hex_str(voter->identity_digest, DIGEST_LEN));
00586       });
00587     SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
00588       {
00589         log(severity, LD_DIR, "Looks like we need to download a new "
00590                  "certificate from authority '%s' at %s:%d (contact %s; "
00591                  "identity %s)",
00592                  voter->nickname, voter->address, (int)voter->dir_port,
00593                  voter->contact?voter->contact:"n/a",
00594                  hex_str(voter->identity_digest, DIGEST_LEN));
00595       });
00596     SMARTLIST_FOREACH(missing_authorities, trusted_dir_server_t *, ds,
00597       {
00598         log(severity, LD_DIR, "Consensus does not include configured "
00599                  "authority '%s' at %s:%d (identity %s)",
00600                  ds->nickname, ds->address, (int)ds->dir_port,
00601                  hex_str(ds->v3_identity_digest, DIGEST_LEN));
00602       });
00603     {
00604       char *joined;
00605       smartlist_t *sl = smartlist_new();
00606       char *tmp = smartlist_join_strings(list_good, " ", 0, NULL);
00607       smartlist_add_asprintf(sl,
00608                    "A consensus needs %d good signatures from recognized "
00609                    "authorities for us to accept it. This one has %d (%s).",
00610                    n_required, n_good, tmp);
00611       tor_free(tmp);
00612       if (n_no_signature) {
00613         tmp = smartlist_join_strings(list_no_signature, " ", 0, NULL);
00614         smartlist_add_asprintf(sl,
00615                      "%d (%s) of the authorities we know didn't sign it.",
00616                      n_no_signature, tmp);
00617         tor_free(tmp);
00618       }
00619       if (n_unknown) {
00620         smartlist_add_asprintf(sl,
00621                       "It has %d signatures from authorities we don't "
00622                       "recognize.", n_unknown);
00623       }
00624       if (n_bad) {
00625         smartlist_add_asprintf(sl, "%d of the signatures on it didn't verify "
00626                       "correctly.", n_bad);
00627       }
00628       if (n_missing_key) {
00629         smartlist_add_asprintf(sl,
00630                       "We were unable to check %d of the signatures, "
00631                       "because we were missing the keys.", n_missing_key);
00632       }
00633       joined = smartlist_join_strings(sl, " ", 0, NULL);
00634       log(severity, LD_DIR, "%s", joined);
00635       tor_free(joined);
00636       SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
00637       smartlist_free(sl);
00638     }
00639   }
00640 
00641   smartlist_free(list_good);
00642   smartlist_free(list_no_signature);
00643   smartlist_free(unrecognized);
00644   smartlist_free(need_certs_from);
00645   smartlist_free(missing_authorities);
00646 
00647   if (n_good == n_v3_authorities)
00648     return 1;
00649   else if (n_good >= n_required)
00650     return 0;
00651   else if (n_good + n_missing_key >= n_required)
00652     return -1;
00653   else
00654     return -2;
00655 }
00656 
00659 char *
00660 networkstatus_get_cache_filename(const char *identity_digest)
00661 {
00662   char fp[HEX_DIGEST_LEN+1];
00663   base16_encode(fp, HEX_DIGEST_LEN+1, identity_digest, DIGEST_LEN);
00664   return get_datadir_fname2("cached-status", fp);
00665 }
00666 
00669 static int
00670 _compare_networkstatus_v2_published_on(const void **_a, const void **_b)
00671 {
00672   const networkstatus_v2_t *a = *_a, *b = *_b;
00673   if (a->published_on < b->published_on)
00674     return -1;
00675   else if (a->published_on > b->published_on)
00676     return 1;
00677   else
00678     return 0;
00679 }
00680 
00684 static int
00685 add_networkstatus_to_cache(const char *s,
00686                            v2_networkstatus_source_t source,
00687                            networkstatus_v2_t *ns)
00688 {
00689   if (source != NS_FROM_CACHE) {
00690     char *fn = networkstatus_get_cache_filename(ns->identity_digest);
00691     if (write_str_to_file(fn, s, 0)<0) {
00692       log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
00693     }
00694     tor_free(fn);
00695   }
00696 
00697   if (directory_caches_v2_dir_info(get_options()))
00698     dirserv_set_cached_networkstatus_v2(s,
00699                                         ns->identity_digest,
00700                                         ns->published_on);
00701 
00702   return 0;
00703 }
00704 
00707 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
00708 
00729 int
00730 router_set_networkstatus_v2(const char *s, time_t arrived_at,
00731                             v2_networkstatus_source_t source,
00732                             smartlist_t *requested_fingerprints)
00733 {
00734   networkstatus_v2_t *ns;
00735   int i, found;
00736   time_t now;
00737   int skewed = 0;
00738   trusted_dir_server_t *trusted_dir = NULL;
00739   const char *source_desc = NULL;
00740   char fp[HEX_DIGEST_LEN+1];
00741   char published[ISO_TIME_LEN+1];
00742 
00743   if (!directory_caches_v2_dir_info(get_options()))
00744     return 0; /* Don't bother storing it. */
00745 
00746   ns = networkstatus_v2_parse_from_string(s);
00747   if (!ns) {
00748     log_warn(LD_DIR, "Couldn't parse network status.");
00749     return -1;
00750   }
00751   base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
00752   if (!(trusted_dir =
00753         router_get_trusteddirserver_by_digest(ns->identity_digest)) ||
00754       !(trusted_dir->type & V2_DIRINFO)) {
00755     log_info(LD_DIR, "Network status was signed, but not by an authoritative "
00756              "directory we recognize.");
00757     source_desc = fp;
00758   } else {
00759     source_desc = trusted_dir->description;
00760   }
00761   now = time(NULL);
00762   if (arrived_at > now)
00763     arrived_at = now;
00764 
00765   ns->received_on = arrived_at;
00766 
00767   format_iso_time(published, ns->published_on);
00768 
00769   if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
00770     char dbuf[64];
00771     long delta = now - ns->published_on;
00772     format_time_interval(dbuf, sizeof(dbuf), delta);
00773     log_warn(LD_GENERAL, "Network status from %s was published %s in the "
00774              "future (%s GMT). Check your time and date settings! "
00775              "Not caching.",
00776              source_desc, dbuf, published);
00777     control_event_general_status(LOG_WARN,
00778                        "CLOCK_SKEW MIN_SKEW=%ld SOURCE=NETWORKSTATUS:%s:%d",
00779                        delta, ns->source_address, ns->source_dirport);
00780     skewed = 1;
00781   }
00782 
00783   if (!networkstatus_v2_list)
00784     networkstatus_v2_list = smartlist_new();
00785 
00786   if ( (source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) &&
00787        router_digest_is_me(ns->identity_digest)) {
00788     /* Don't replace our own networkstatus when we get it from somebody else.*/
00789     networkstatus_v2_free(ns);
00790     return 0;
00791   }
00792 
00793   if (requested_fingerprints) {
00794     if (smartlist_string_isin(requested_fingerprints, fp)) {
00795       smartlist_string_remove(requested_fingerprints, fp);
00796     } else {
00797       if (source != NS_FROM_DIR_ALL) {
00798         char *requested =
00799           smartlist_join_strings(requested_fingerprints," ",0,NULL);
00800         log_warn(LD_DIR,
00801                "We received a network status with a fingerprint (%s) that we "
00802                "never requested. (We asked for: %s.) Dropping.",
00803                fp, requested);
00804         tor_free(requested);
00805         return 0;
00806       }
00807     }
00808   }
00809 
00810   if (!trusted_dir) {
00811     if (!skewed) {
00812       /* We got a non-trusted networkstatus, and we're a directory cache.
00813        * This means that we asked an authority, and it told us about another
00814        * authority we didn't recognize. */
00815       log_info(LD_DIR,
00816                "We do not recognize authority (%s) but we are willing "
00817                "to cache it.", fp);
00818       add_networkstatus_to_cache(s, source, ns);
00819       networkstatus_v2_free(ns);
00820     }
00821     return 0;
00822   }
00823 
00824   found = 0;
00825   for (i=0; i < smartlist_len(networkstatus_v2_list); ++i) {
00826     networkstatus_v2_t *old_ns = smartlist_get(networkstatus_v2_list, i);
00827 
00828     if (tor_memeq(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
00829       if (tor_memeq(old_ns->networkstatus_digest,
00830                   ns->networkstatus_digest, DIGEST_LEN)) {
00831         /* Same one we had before. */
00832         networkstatus_v2_free(ns);
00833         tor_assert(trusted_dir);
00834         log_info(LD_DIR,
00835                  "Not replacing network-status from %s (published %s); "
00836                  "we already have it.",
00837                  trusted_dir->description, published);
00838         if (old_ns->received_on < arrived_at) {
00839           if (source != NS_FROM_CACHE) {
00840             char *fn;
00841             fn = networkstatus_get_cache_filename(old_ns->identity_digest);
00842             /* We use mtime to tell when it arrived, so update that. */
00843             touch_file(fn);
00844             tor_free(fn);
00845           }
00846           old_ns->received_on = arrived_at;
00847         }
00848         download_status_failed(&trusted_dir->v2_ns_dl_status, 0);
00849         return 0;
00850       } else if (old_ns->published_on >= ns->published_on) {
00851         char old_published[ISO_TIME_LEN+1];
00852         format_iso_time(old_published, old_ns->published_on);
00853         tor_assert(trusted_dir);
00854         log_info(LD_DIR,
00855                  "Not replacing network-status from %s (published %s);"
00856                  " we have a newer one (published %s) for this authority.",
00857                  trusted_dir->description, published,
00858                  old_published);
00859         networkstatus_v2_free(ns);
00860         download_status_failed(&trusted_dir->v2_ns_dl_status, 0);
00861         return 0;
00862       } else {
00863         networkstatus_v2_free(old_ns);
00864         smartlist_set(networkstatus_v2_list, i, ns);
00865         found = 1;
00866         break;
00867       }
00868     }
00869   }
00870 
00871   if (source != NS_FROM_CACHE && trusted_dir) {
00872     download_status_reset(&trusted_dir->v2_ns_dl_status);
00873   }
00874 
00875   if (!found)
00876     smartlist_add(networkstatus_v2_list, ns);
00877 
00880 #define V2_NETWORKSTATUS_ROUTER_LIFETIME (3*60*60)
00881 
00882   {
00883     time_t live_until = ns->published_on + V2_NETWORKSTATUS_ROUTER_LIFETIME;
00884     SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
00885     {
00886       signed_descriptor_t *sd =
00887         router_get_by_descriptor_digest(rs->descriptor_digest);
00888       if (sd) {
00889         if (sd->last_listed_as_valid_until < live_until)
00890           sd->last_listed_as_valid_until = live_until;
00891       } else {
00892         rs->need_to_mirror = 1;
00893       }
00894     });
00895   }
00896 
00897   log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
00898            source == NS_FROM_CACHE?"cached from":
00899            ((source == NS_FROM_DIR_BY_FP || source == NS_FROM_DIR_ALL) ?
00900              "downloaded from":"generated for"),
00901            trusted_dir->description, published);
00902   networkstatus_v2_list_has_changed = 1;
00903 
00904   smartlist_sort(networkstatus_v2_list,
00905                  _compare_networkstatus_v2_published_on);
00906 
00907   if (!skewed)
00908     add_networkstatus_to_cache(s, source, ns);
00909 
00910   return 0;
00911 }
00912 
00915 void
00916 networkstatus_v2_list_clean(time_t now)
00917 {
00918   int i;
00919   if (!networkstatus_v2_list)
00920     return;
00921 
00922   for (i = 0; i < smartlist_len(networkstatus_v2_list); ++i) {
00923     networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
00924     char *fname = NULL;
00925     if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
00926       continue;
00927     /* Okay, this one is too old.  Remove it from the list, and delete it
00928      * from the cache. */
00929     smartlist_del(networkstatus_v2_list, i--);
00930     fname = networkstatus_get_cache_filename(ns->identity_digest);
00931     if (file_status(fname) == FN_FILE) {
00932       log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
00933       unlink(fname);
00934     }
00935     tor_free(fname);
00936     if (directory_caches_v2_dir_info(get_options())) {
00937       dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
00938     }
00939     networkstatus_v2_free(ns);
00940   }
00941 
00942   /* And now go through the directory cache for any cached untrusted
00943    * networkstatuses and other network info. */
00944   dirserv_clear_old_networkstatuses(now - MAX_NETWORKSTATUS_AGE);
00945   dirserv_clear_old_v1_info(now);
00946 }
00947 
00950 int
00951 compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
00952 {
00953   const char *key = _key;
00954   const routerstatus_t *rs = *_member;
00955   return tor_memcmp(key, rs->identity_digest, DIGEST_LEN);
00956 }
00957 
00959 routerstatus_t *
00960 networkstatus_v2_find_mutable_entry(networkstatus_v2_t *ns, const char *digest)
00961 {
00962   return smartlist_bsearch(ns->entries, digest,
00963                            compare_digest_to_routerstatus_entry);
00964 }
00965 
00968 const routerstatus_t *
00969 networkstatus_v2_find_entry(networkstatus_v2_t *ns, const char *digest)
00970 {
00971   return networkstatus_v2_find_mutable_entry(ns, digest);
00972 }
00973 
00975 routerstatus_t *
00976 networkstatus_vote_find_mutable_entry(networkstatus_t *ns, const char *digest)
00977 {
00978   return smartlist_bsearch(ns->routerstatus_list, digest,
00979                            compare_digest_to_routerstatus_entry);
00980 }
00981 
00984 const routerstatus_t *
00985 networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
00986 {
00987   return networkstatus_vote_find_mutable_entry(ns, digest);
00988 }
00989 
00990 /*XXXX MOVE make this static once functions are moved into this file. */
00994 int
00995 networkstatus_vote_find_entry_idx(networkstatus_t *ns,
00996                                   const char *digest, int *found_out)
00997 {
00998   return smartlist_bsearch_idx(ns->routerstatus_list, digest,
00999                                compare_digest_to_routerstatus_entry,
01000                                found_out);
01001 }
01002 
01004 const smartlist_t *
01005 networkstatus_get_v2_list(void)
01006 {
01007   if (!networkstatus_v2_list)
01008     networkstatus_v2_list = smartlist_new();
01009   return networkstatus_v2_list;
01010 }
01011 
01014 routerstatus_t *
01015 router_get_mutable_consensus_status_by_descriptor_digest(
01016                                                  networkstatus_t *consensus,
01017                                                  const char *digest)
01018 {
01019   if (!consensus)
01020     consensus = current_consensus;
01021   if (!consensus)
01022     return NULL;
01023   if (!consensus->desc_digest_map) {
01024     digestmap_t *m = consensus->desc_digest_map = digestmap_new();
01025     SMARTLIST_FOREACH(consensus->routerstatus_list,
01026                       routerstatus_t *, rs,
01027      {
01028        digestmap_set(m, rs->descriptor_digest, rs);
01029      });
01030   }
01031   return digestmap_get(consensus->desc_digest_map, digest);
01032 }
01033 
01037 const routerstatus_t *
01038 router_get_consensus_status_by_descriptor_digest(networkstatus_t *consensus,
01039                                                  const char *digest)
01040 {
01041   return router_get_mutable_consensus_status_by_descriptor_digest(
01042                                                           consensus, digest);
01043 }
01044 
01047 download_status_t *
01048 router_get_dl_status_by_descriptor_digest(const char *d)
01049 {
01050   routerstatus_t *rs;
01051   if (!current_ns_consensus)
01052     return NULL;
01053   if ((rs = router_get_mutable_consensus_status_by_descriptor_digest(
01054                                               current_ns_consensus, d)))
01055     return &rs->dl_status;
01056   if (v2_download_status_map)
01057     return digestmap_get(v2_download_status_map, d);
01058 
01059   return NULL;
01060 }
01061 
01063 routerstatus_t *
01064 router_get_mutable_consensus_status_by_id(const char *digest)
01065 {
01066   if (!current_consensus)
01067     return NULL;
01068   return smartlist_bsearch(current_consensus->routerstatus_list, digest,
01069                            compare_digest_to_routerstatus_entry);
01070 }
01071 
01074 const routerstatus_t *
01075 router_get_consensus_status_by_id(const char *digest)
01076 {
01077   return router_get_mutable_consensus_status_by_id(digest);
01078 }
01079 
01084 const routerstatus_t *
01085 router_get_consensus_status_by_nickname(const char *nickname,
01086                                         int warn_if_unnamed)
01087 {
01088   const node_t *node = node_get_by_nickname(nickname, warn_if_unnamed);
01089   if (node)
01090     return node->rs;
01091   else
01092     return NULL;
01093 }
01094 
01097 const char *
01098 networkstatus_get_router_digest_by_nickname(const char *nickname)
01099 {
01100   if (!named_server_map)
01101     return NULL;
01102   return strmap_get_lc(named_server_map, nickname);
01103 }
01104 
01107 int
01108 networkstatus_nickname_is_unnamed(const char *nickname)
01109 {
01110   if (!unnamed_server_map)
01111     return 0;
01112   return strmap_get_lc(unnamed_server_map, nickname) != NULL;
01113 }
01114 
01117 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
01118 
01121 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
01122 
01129 static void
01130 update_v2_networkstatus_cache_downloads(time_t now)
01131 {
01132   int authority = authdir_mode_v2(get_options());
01133   int interval =
01134     authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
01135   const smartlist_t *trusted_dir_servers = router_get_trusted_dir_servers();
01136 
01137   if (last_networkstatus_download_attempted + interval >= now)
01138     return;
01139 
01140   last_networkstatus_download_attempted = now;
01141 
01142   if (authority) {
01143     /* An authority launches a separate connection for everybody. */
01144     SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds)
01145       {
01146          char resource[HEX_DIGEST_LEN+6]; /* fp/hexdigit.z\0 */
01147          tor_addr_t addr;
01148          if (!(ds->type & V2_DIRINFO))
01149            continue;
01150          if (router_digest_is_me(ds->digest))
01151            continue;
01152          tor_addr_from_ipv4h(&addr, ds->addr);
01153          /* Is this quite sensible with IPv6 or multiple addresses? */
01154          if (connection_get_by_type_addr_port_purpose(
01155                 CONN_TYPE_DIR, &addr, ds->dir_port,
01156                 DIR_PURPOSE_FETCH_V2_NETWORKSTATUS)) {
01157            /* XXX the above dir_port won't be accurate if we're
01158             * doing a tunneled conn. In that case it should be or_port.
01159             * How to guess from here? Maybe make the function less general
01160             * and have it know that it's looking for dir conns. -RD */
01161            /* Only directory caches download v2 networkstatuses, and they
01162             * don't use tunneled connections.  I think it's okay to ignore
01163             * this. */
01164            continue;
01165          }
01166          strlcpy(resource, "fp/", sizeof(resource));
01167          base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
01168          strlcat(resource, ".z", sizeof(resource));
01169          directory_initiate_command_routerstatus(
01170                &ds->fake_status, DIR_PURPOSE_FETCH_V2_NETWORKSTATUS,
01171                ROUTER_PURPOSE_GENERAL,
01172                0, /* Not private */
01173                resource,
01174                NULL, 0 /* No payload. */,
01175                0 /* No I-M-S. */);
01176       }
01177     SMARTLIST_FOREACH_END(ds);
01178   } else {
01179     /* A non-authority cache launches one connection to a random authority. */
01180     /* (Check whether we're currently fetching network-status objects.) */
01181     if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
01182                                         DIR_PURPOSE_FETCH_V2_NETWORKSTATUS))
01183       directory_get_from_dirserver(DIR_PURPOSE_FETCH_V2_NETWORKSTATUS,
01184                                    ROUTER_PURPOSE_GENERAL, "all.z",
01185                                    PDS_RETRY_IF_NO_SERVERS);
01186   }
01187 }
01188 
01191 static int
01192 we_want_to_fetch_flavor(const or_options_t *options, int flavor)
01193 {
01194   if (flavor < 0 || flavor > N_CONSENSUS_FLAVORS) {
01195     /* This flavor is crazy; we don't want it */
01196     /*XXXX handle unrecognized flavors later */
01197     return 0;
01198   }
01199   if (authdir_mode_v3(options) || directory_caches_dir_info(options)) {
01200     /* We want to serve all flavors to others, regardless if we would use
01201      * it ourselves. */
01202     return 1;
01203   }
01204   if (options->FetchUselessDescriptors) {
01205     /* In order to get all descriptors, we need to fetch all consensuses. */
01206     return 1;
01207   }
01208   /* Otherwise, we want the flavor only if we want to use it to build
01209    * circuits. */
01210   return flavor == usable_consensus_flavor();
01211 }
01212 
01214 #define CONSENSUS_NETWORKSTATUS_MAX_DL_TRIES 8
01215 
01217 #define DELAY_WHILE_FETCHING_CERTS (20*60)
01218 
01221 static void
01222 update_consensus_networkstatus_downloads(time_t now)
01223 {
01224   int i;
01225   const or_options_t *options = get_options();
01226 
01227   for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
01228     /* XXXX need some way to download unknown flavors if we are caching. */
01229     const char *resource;
01230     consensus_waiting_for_certs_t *waiting;
01231     networkstatus_t *c;
01232 
01233     if (! we_want_to_fetch_flavor(options, i))
01234       continue;
01235 
01236     c = networkstatus_get_latest_consensus_by_flavor(i);
01237     if (! (c && c->valid_after <= now && now <= c->valid_until)) {
01238       /* No live consensus? Get one now!*/
01239       time_to_download_next_consensus[i] = now;
01240     }
01241 
01242     if (time_to_download_next_consensus[i] > now)
01243       return; /* Wait until the current consensus is older. */
01244 
01245     resource = networkstatus_get_flavor_name(i);
01246 
01247     if (!download_status_is_ready(&consensus_dl_status[i], now,
01248                                   CONSENSUS_NETWORKSTATUS_MAX_DL_TRIES))
01249       continue; /* We failed downloading a consensus too recently. */
01250     if (connection_dir_get_by_purpose_and_resource(
01251                                 DIR_PURPOSE_FETCH_CONSENSUS, resource))
01252       continue; /* There's an in-progress download.*/
01253 
01254     waiting = &consensus_waiting_for_certs[i];
01255     if (waiting->consensus) {
01256       /* XXXX make sure this doesn't delay sane downloads. */
01257       if (waiting->set_at + DELAY_WHILE_FETCHING_CERTS > now) {
01258         continue; /* We're still getting certs for this one. */
01259       } else {
01260         if (!waiting->dl_failed) {
01261           download_status_failed(&consensus_dl_status[i], 0);
01262           waiting->dl_failed=1;
01263         }
01264       }
01265     }
01266 
01267     log_info(LD_DIR, "Launching %s networkstatus consensus download.",
01268              networkstatus_get_flavor_name(i));
01269 
01270     directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
01271                                  ROUTER_PURPOSE_GENERAL, resource,
01272                                  PDS_RETRY_IF_NO_SERVERS);
01273   }
01274 }
01275 
01278 void
01279 networkstatus_consensus_download_failed(int status_code, const char *flavname)
01280 {
01281   int flav = networkstatus_parse_flavor_name(flavname);
01282   if (flav >= 0) {
01283     tor_assert(flav < N_CONSENSUS_FLAVORS);
01284     /* XXXX handle unrecognized flavors */
01285     download_status_failed(&consensus_dl_status[flav], status_code);
01286     /* Retry immediately, if appropriate. */
01287     update_consensus_networkstatus_downloads(time(NULL));
01288   }
01289 }
01290 
01293 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
01294 
01297 static void
01298 update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
01299 {
01300   const or_options_t *options = get_options();
01301   networkstatus_t *c = networkstatus_get_latest_consensus_by_flavor(flav);
01302   const char *flavor = networkstatus_get_flavor_name(flav);
01303   if (! we_want_to_fetch_flavor(get_options(), flav))
01304     return;
01305 
01306   if (c && c->valid_after <= now && now <= c->valid_until) {
01307     long dl_interval;
01308     long interval = c->fresh_until - c->valid_after;
01309     long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
01310     time_t start;
01311 
01312     if (min_sec_before_caching > interval/16) {
01313       /* Usually we allow 2-minutes slop factor in case clocks get
01314          desynchronized a little.  If we're on a private network with
01315          a crazy-fast voting interval, though, 2 minutes may be too
01316          much. */
01317       min_sec_before_caching = interval/16;
01318     }
01319 
01320     if (directory_fetches_dir_info_early(options)) {
01321       /* We want to cache the next one at some point after this one
01322        * is no longer fresh... */
01323       start = c->fresh_until + min_sec_before_caching;
01324       /* Some clients may need the consensus sooner than others. */
01325       if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
01326         dl_interval = 60;
01327         if (min_sec_before_caching + dl_interval > interval)
01328           dl_interval = interval/2;
01329       } else {
01330         /* But only in the first half-interval after that. */
01331         dl_interval = interval/2;
01332       }
01333     } else {
01334       /* We're an ordinary client or a bridge. Give all the caches enough
01335        * time to download the consensus. */
01336       start = c->fresh_until + (interval*3)/4;
01337       /* But download the next one well before this one is expired. */
01338       dl_interval = ((c->valid_until - start) * 7 )/ 8;
01339 
01340       /* If we're a bridge user, make use of the numbers we just computed
01341        * to choose the rest of the interval *after* them. */
01342       if (directory_fetches_dir_info_later(options)) {
01343         /* Give all the *clients* enough time to download the consensus. */
01344         start = start + dl_interval + min_sec_before_caching;
01345         /* But try to get it before ours actually expires. */
01346         dl_interval = (c->valid_until - start) - min_sec_before_caching;
01347       }
01348     }
01349     if (dl_interval < 1)
01350       dl_interval = 1;
01351     /* We must not try to replace c while it's still fresh: */
01352     tor_assert(c->fresh_until < start);
01353     /* We must download the next one before c is invalid: */
01354     tor_assert(start+dl_interval < c->valid_until);
01355     time_to_download_next_consensus[flav] =
01356       start + crypto_rand_int((int)dl_interval);
01357     {
01358       char tbuf1[ISO_TIME_LEN+1];
01359       char tbuf2[ISO_TIME_LEN+1];
01360       char tbuf3[ISO_TIME_LEN+1];
01361       format_local_iso_time(tbuf1, c->fresh_until);
01362       format_local_iso_time(tbuf2, c->valid_until);
01363       format_local_iso_time(tbuf3, time_to_download_next_consensus[flav]);
01364       log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
01365                "will expire at %s; fetching the next one at %s.",
01366                flavor, (c->fresh_until > now) ? "will be" : "was",
01367                tbuf1, tbuf2, tbuf3);
01368     }
01369   } else {
01370     time_to_download_next_consensus[flav] = now;
01371     log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
01372              flavor);
01373   }
01374 }
01375 
01378 void
01379 update_consensus_networkstatus_fetch_time(time_t now)
01380 {
01381   int i;
01382   for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
01383     if (we_want_to_fetch_flavor(get_options(), i))
01384       update_consensus_networkstatus_fetch_time_impl(now, i);
01385   }
01386 }
01387 
01391 int
01392 should_delay_dir_fetches(const or_options_t *options)
01393 {
01394   if (options->UseBridges && !any_bridge_descriptors_known()) {
01395     log_info(LD_DIR, "delaying dir fetches (no running bridges known)");
01396     return 1;
01397   }
01398   return 0;
01399 }
01400 
01403 void
01404 update_networkstatus_downloads(time_t now)
01405 {
01406   const or_options_t *options = get_options();
01407   if (should_delay_dir_fetches(options))
01408     return;
01409   if (authdir_mode_any_main(options) || options->FetchV2Networkstatus)
01410     update_v2_networkstatus_cache_downloads(now);
01411   update_consensus_networkstatus_downloads(now);
01412   update_certificate_downloads(now);
01413 }
01414 
01417 void
01418 update_certificate_downloads(time_t now)
01419 {
01420   int i;
01421   for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
01422     if (consensus_waiting_for_certs[i].consensus)
01423       authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
01424                                     now);
01425   }
01426 
01427   if (current_ns_consensus)
01428     authority_certs_fetch_missing(current_ns_consensus, now);
01429   if (current_md_consensus)
01430     authority_certs_fetch_missing(current_md_consensus, now);
01431 }
01432 
01435 int
01436 consensus_is_waiting_for_certs(void)
01437 {
01438   return consensus_waiting_for_certs[usable_consensus_flavor()].consensus
01439     ? 1 : 0;
01440 }
01441 
01443 networkstatus_v2_t *
01444 networkstatus_v2_get_by_digest(const char *digest)
01445 {
01446   SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
01447     {
01448       if (tor_memeq(ns->identity_digest, digest, DIGEST_LEN))
01449         return ns;
01450     });
01451   return NULL;
01452 }
01453 
01456 networkstatus_t *
01457 networkstatus_get_latest_consensus(void)
01458 {
01459   return current_consensus;
01460 }
01461 
01464 networkstatus_t *
01465 networkstatus_get_latest_consensus_by_flavor(consensus_flavor_t f)
01466 {
01467   if (f == FLAV_NS)
01468     return current_ns_consensus;
01469   else if (f == FLAV_MICRODESC)
01470     return current_md_consensus;
01471   else {
01472     tor_assert(0);
01473     return NULL;
01474   }
01475 }
01476 
01479 networkstatus_t *
01480 networkstatus_get_live_consensus(time_t now)
01481 {
01482   if (current_consensus &&
01483       current_consensus->valid_after <= now &&
01484       now <= current_consensus->valid_until)
01485     return current_consensus;
01486   else
01487     return NULL;
01488 }
01489 
01490 /* XXXX remove this in favor of get_live_consensus. But actually,
01491  * leave something like it for bridge users, who need to not totally
01492  * lose if they spend a while fetching a new consensus. */
01495 networkstatus_t *
01496 networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
01497 {
01498 #define REASONABLY_LIVE_TIME (24*60*60)
01499   networkstatus_t *consensus =
01500     networkstatus_get_latest_consensus_by_flavor(flavor);
01501   if (consensus &&
01502       consensus->valid_after <= now &&
01503       now <= consensus->valid_until+REASONABLY_LIVE_TIME)
01504     return consensus;
01505   else
01506     return NULL;
01507 }
01508 
01511 static int
01512 routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
01513 {
01514   tor_assert(tor_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN));
01515 
01516   return strcmp(a->nickname, b->nickname) ||
01517          fast_memneq(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
01518          a->addr != b->addr ||
01519          a->or_port != b->or_port ||
01520          a->dir_port != b->dir_port ||
01521          a->is_authority != b->is_authority ||
01522          a->is_exit != b->is_exit ||
01523          a->is_stable != b->is_stable ||
01524          a->is_fast != b->is_fast ||
01525          a->is_flagged_running != b->is_flagged_running ||
01526          a->is_named != b->is_named ||
01527          a->is_unnamed != b->is_unnamed ||
01528          a->is_valid != b->is_valid ||
01529          a->is_v2_dir != b->is_v2_dir ||
01530          a->is_possible_guard != b->is_possible_guard ||
01531          a->is_bad_exit != b->is_bad_exit ||
01532          a->is_bad_directory != b->is_bad_directory ||
01533          a->is_hs_dir != b->is_hs_dir ||
01534          a->version_known != b->version_known ||
01535          a->version_supports_begindir != b->version_supports_begindir ||
01536          a->version_supports_extrainfo_upload !=
01537            b->version_supports_extrainfo_upload ||
01538          a->version_supports_conditional_consensus !=
01539            b->version_supports_conditional_consensus ||
01540          a->version_supports_v3_dir != b->version_supports_v3_dir;
01541 }
01542 
01545 static void
01546 notify_control_networkstatus_changed(const networkstatus_t *old_c,
01547                                      const networkstatus_t *new_c)
01548 {
01549   smartlist_t *changed;
01550   if (old_c == new_c)
01551     return;
01552 
01553   /* tell the controller exactly which relays are still listed, as well
01554    * as what they're listed as */
01555   control_event_newconsensus(new_c);
01556 
01557   if (!control_event_is_interesting(EVENT_NS))
01558     return;
01559 
01560   if (!old_c) {
01561     control_event_networkstatus_changed(new_c->routerstatus_list);
01562     return;
01563   }
01564   changed = smartlist_new();
01565 
01566   SMARTLIST_FOREACH_JOIN(
01567                      old_c->routerstatus_list, const routerstatus_t *, rs_old,
01568                      new_c->routerstatus_list, const routerstatus_t *, rs_new,
01569                      tor_memcmp(rs_old->identity_digest,
01570                             rs_new->identity_digest, DIGEST_LEN),
01571                      smartlist_add(changed, (void*) rs_new)) {
01572     if (routerstatus_has_changed(rs_old, rs_new))
01573       smartlist_add(changed, (void*)rs_new);
01574   } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
01575 
01576   control_event_networkstatus_changed(changed);
01577   smartlist_free(changed);
01578 }
01579 
01582 static void
01583 networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
01584                                       const networkstatus_t *old_c)
01585 {
01586   if (old_c == new_c)
01587     return;
01588   if (!old_c || !smartlist_len(old_c->routerstatus_list))
01589     return;
01590 
01591   SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
01592                          new_c->routerstatus_list, routerstatus_t *, rs_new,
01593                          tor_memcmp(rs_old->identity_digest,
01594                                 rs_new->identity_digest, DIGEST_LEN),
01595                          STMT_NIL) {
01596     /* Okay, so we're looking at the same identity. */
01597     rs_new->last_dir_503_at = rs_old->last_dir_503_at;
01598 
01599     if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
01600                 DIGEST_LEN)) {
01601       /* And the same descriptor too! */
01602       memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
01603     }
01604   } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
01605 }
01606 
01624 int
01625 networkstatus_set_current_consensus(const char *consensus,
01626                                     const char *flavor,
01627                                     unsigned flags)
01628 {
01629   networkstatus_t *c=NULL;
01630   int r, result = -1;
01631   time_t now = time(NULL);
01632   const or_options_t *options = get_options();
01633   char *unverified_fname = NULL, *consensus_fname = NULL;
01634   int flav = networkstatus_parse_flavor_name(flavor);
01635   const unsigned from_cache = flags & NSSET_FROM_CACHE;
01636   const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
01637   const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
01638   const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
01639   const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
01640   const digests_t *current_digests = NULL;
01641   consensus_waiting_for_certs_t *waiting = NULL;
01642   time_t current_valid_after = 0;
01643   int free_consensus = 1; /* Free 'c' at the end of the function */
01644 
01645   if (flav < 0) {
01646     /* XXXX we don't handle unrecognized flavors yet. */
01647     log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
01648     return -2;
01649   }
01650 
01651   /* Make sure it's parseable. */
01652   c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
01653   if (!c) {
01654     log_warn(LD_DIR, "Unable to parse networkstatus consensus");
01655     result = -2;
01656     goto done;
01657   }
01658 
01659   if ((int)c->flavor != flav) {
01660     /* This wasn't the flavor we thought we were getting. */
01661     if (require_flavor) {
01662       log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
01663                networkstatus_get_flavor_name(c->flavor), flavor);
01664       goto done;
01665     }
01666     flav = c->flavor;
01667     flavor = networkstatus_get_flavor_name(flav);
01668   }
01669 
01670   if (flav != usable_consensus_flavor() &&
01671       !directory_caches_dir_info(options)) {
01672     /* This consensus is totally boring to us: we won't use it, and we won't
01673      * serve it.  Drop it. */
01674     goto done;
01675   }
01676 
01677   if (from_cache && !accept_obsolete &&
01678       c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
01679     /* XXXX If we try to make fallbackconsensus work again, we should
01680      * consider taking this out. Until then, believing obsolete consensuses
01681      * is causing more harm than good. See also bug 887. */
01682     log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
01683     goto done;
01684   }
01685 
01686   if (!strcmp(flavor, "ns")) {
01687     consensus_fname = get_datadir_fname("cached-consensus");
01688     unverified_fname = get_datadir_fname("unverified-consensus");
01689     if (current_ns_consensus) {
01690       current_digests = &current_ns_consensus->digests;
01691       current_valid_after = current_ns_consensus->valid_after;
01692     }
01693   } else if (!strcmp(flavor, "microdesc")) {
01694     consensus_fname = get_datadir_fname("cached-microdesc-consensus");
01695     unverified_fname = get_datadir_fname("unverified-microdesc-consensus");
01696     if (current_md_consensus) {
01697       current_digests = &current_md_consensus->digests;
01698       current_valid_after = current_md_consensus->valid_after;
01699     }
01700   } else {
01701     cached_dir_t *cur;
01702     char buf[128];
01703     tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
01704     consensus_fname = get_datadir_fname(buf);
01705     tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
01706     unverified_fname = get_datadir_fname(buf);
01707     cur = dirserv_get_consensus(flavor);
01708     if (cur) {
01709       current_digests = &cur->digests;
01710       current_valid_after = cur->published;
01711     }
01712   }
01713 
01714   if (current_digests &&
01715       tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
01716     /* We already have this one. That's a failure. */
01717     log_info(LD_DIR, "Got a %s consensus we already have", flavor);
01718     goto done;
01719   }
01720 
01721   if (current_valid_after && c->valid_after <= current_valid_after) {
01722     /* We have a newer one.  There's no point in accepting this one,
01723      * even if it's great. */
01724     log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
01725              flavor);
01726     goto done;
01727   }
01728 
01729   /* Make sure it's signed enough. */
01730   if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
01731     if (r == -1) {
01732       /* Okay, so it _might_ be signed enough if we get more certificates. */
01733       if (!was_waiting_for_certs) {
01734         log_info(LD_DIR,
01735                  "Not enough certificates to check networkstatus consensus");
01736       }
01737       if (!current_valid_after ||
01738           c->valid_after > current_valid_after) {
01739         waiting = &consensus_waiting_for_certs[flav];
01740         networkstatus_vote_free(waiting->consensus);
01741         tor_free(waiting->body);
01742         waiting->consensus = c;
01743         free_consensus = 0;
01744         waiting->body = tor_strdup(consensus);
01745         waiting->set_at = now;
01746         waiting->dl_failed = 0;
01747         if (!from_cache) {
01748           write_str_to_file(unverified_fname, consensus, 0);
01749         }
01750         if (dl_certs)
01751           authority_certs_fetch_missing(c, now);
01752         /* This case is not a success or a failure until we get the certs
01753          * or fail to get the certs. */
01754         result = 0;
01755       } else {
01756         /* Even if we had enough signatures, we'd never use this as the
01757          * latest consensus. */
01758         if (was_waiting_for_certs && from_cache)
01759           unlink(unverified_fname);
01760       }
01761       goto done;
01762     } else {
01763       /* This can never be signed enough:  Kill it. */
01764       if (!was_waiting_for_certs) {
01765         log_warn(LD_DIR, "Not enough good signatures on networkstatus "
01766                  "consensus");
01767         result = -2;
01768       }
01769       if (was_waiting_for_certs && (r < -1) && from_cache)
01770         unlink(unverified_fname);
01771       goto done;
01772     }
01773   }
01774 
01775   if (!from_cache && flav == usable_consensus_flavor())
01776     control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
01777 
01778   /* Are we missing any certificates at all? */
01779   if (r != 1 && dl_certs)
01780     authority_certs_fetch_missing(c, now);
01781 
01782   if (flav == usable_consensus_flavor()) {
01783     notify_control_networkstatus_changed(current_consensus, c);
01784   }
01785   if (flav == FLAV_NS) {
01786     if (current_ns_consensus) {
01787       networkstatus_copy_old_consensus_info(c, current_ns_consensus);
01788       networkstatus_vote_free(current_ns_consensus);
01789       /* Defensive programming : we should set current_consensus very soon,
01790        * but we're about to call some stuff in the meantime, and leaving this
01791        * dangling pointer around has proven to be trouble. */
01792       current_ns_consensus = NULL;
01793     }
01794     current_ns_consensus = c;
01795     free_consensus = 0; /* avoid free */
01796   } else if (flav == FLAV_MICRODESC) {
01797     if (current_md_consensus) {
01798       networkstatus_copy_old_consensus_info(c, current_md_consensus);
01799       networkstatus_vote_free(current_md_consensus);
01800       /* more defensive programming */
01801       current_md_consensus = NULL;
01802     }
01803     current_md_consensus = c;
01804     free_consensus = 0; /* avoid free */
01805   }
01806 
01807   waiting = &consensus_waiting_for_certs[flav];
01808   if (waiting->consensus &&
01809       waiting->consensus->valid_after <= c->valid_after) {
01810     networkstatus_vote_free(waiting->consensus);
01811     waiting->consensus = NULL;
01812     if (consensus != waiting->body)
01813       tor_free(waiting->body);
01814     else
01815       waiting->body = NULL;
01816     waiting->set_at = 0;
01817     waiting->dl_failed = 0;
01818     unlink(unverified_fname);
01819   }
01820 
01821   /* Reset the failure count only if this consensus is actually valid. */
01822   if (c->valid_after <= now && now <= c->valid_until) {
01823     download_status_reset(&consensus_dl_status[flav]);
01824   } else {
01825     if (!from_cache)
01826       download_status_failed(&consensus_dl_status[flav], 0);
01827   }
01828 
01829   if (flav == usable_consensus_flavor()) {
01830     /* XXXXNM Microdescs: needs a non-ns variant. ???? NM*/
01831     update_consensus_networkstatus_fetch_time(now);
01832 
01833     nodelist_set_consensus(current_consensus);
01834 
01835     dirvote_recalculate_timing(options, now);
01836     routerstatus_list_update_named_server_map();
01837     cell_ewma_set_scale_factor(options, current_consensus);
01838 
01839     /* XXXX024 this call might be unnecessary here: can changing the
01840      * current consensus really alter our view of any OR's rate limits? */
01841     connection_or_update_token_buckets(get_connection_array(), options);
01842 
01843     circuit_build_times_new_consensus_params(&circ_times, current_consensus);
01844   }
01845 
01846   if (directory_caches_dir_info(options)) {
01847     dirserv_set_cached_consensus_networkstatus(consensus,
01848                                                flavor,
01849                                                &c->digests,
01850                                                c->valid_after);
01851   }
01852 
01853   if (!from_cache) {
01854     write_str_to_file(consensus_fname, consensus, 0);
01855   }
01856 
01859 #define EARLY_CONSENSUS_NOTICE_SKEW 60
01860 
01861   if (now < c->valid_after - EARLY_CONSENSUS_NOTICE_SKEW) {
01862     char tbuf[ISO_TIME_LEN+1];
01863     char dbuf[64];
01864     long delta = now - c->valid_after;
01865     format_iso_time(tbuf, c->valid_after);
01866     format_time_interval(dbuf, sizeof(dbuf), delta);
01867     log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
01868              "consensus network status document (%s GMT).  Tor needs an "
01869              "accurate clock to work correctly. Please check your time and "
01870              "date settings!", dbuf, tbuf);
01871     control_event_general_status(LOG_WARN,
01872                     "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
01873   }
01874 
01875   router_dir_info_changed();
01876 
01877   result = 0;
01878  done:
01879   if (free_consensus)
01880     networkstatus_vote_free(c);
01881   tor_free(consensus_fname);
01882   tor_free(unverified_fname);
01883   return result;
01884 }
01885 
01888 void
01889 networkstatus_note_certs_arrived(void)
01890 {
01891   int i;
01892   for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
01893     consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
01894     if (!waiting->consensus)
01895       continue;
01896     if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
01897       if (!networkstatus_set_current_consensus(
01898                                  waiting->body,
01899                                  networkstatus_get_flavor_name(i),
01900                                  NSSET_WAS_WAITING_FOR_CERTS)) {
01901         tor_free(waiting->body);
01902       }
01903     }
01904   }
01905 }
01906 
01912 void
01913 routers_update_all_from_networkstatus(time_t now, int dir_version)
01914 {
01915   routerlist_t *rl = router_get_routerlist();
01916   networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,
01917                                                                      FLAV_NS);
01918 
01919   if (networkstatus_v2_list_has_changed)
01920     download_status_map_update_from_v2_networkstatus();
01921 
01922   if (!consensus || dir_version < 3) /* nothing more we should do */
01923     return;
01924 
01925   /* calls router_dir_info_changed() when it's done -- more routers
01926    * might be up or down now, which might affect whether there's enough
01927    * directory info. */
01928   routers_update_status_from_consensus_networkstatus(rl->routers, 0);
01929 
01930   SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
01931                     ri->cache_info.routerlist_index = ri_sl_idx);
01932   if (rl->old_routers)
01933     signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
01934 
01935   if (!have_warned_about_old_version) {
01936     int is_server = server_mode(get_options());
01937     version_status_t status;
01938     const char *recommended = is_server ?
01939       consensus->server_versions : consensus->client_versions;
01940     status = tor_version_is_obsolete(VERSION, recommended);
01941 
01942     if (status == VS_RECOMMENDED) {
01943       log_info(LD_GENERAL, "The directory authorities say my version is ok.");
01944     } else if (status == VS_EMPTY) {
01945       log_info(LD_GENERAL,
01946                "The directory authorities don't recommend any versions.");
01947     } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
01948       if (!have_warned_about_new_version) {
01949         log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
01950                    "recommended version%s, according to the directory "
01951                    "authorities. Recommended versions are: %s",
01952                    VERSION,
01953                    status == VS_NEW_IN_SERIES ? " in its series" : "",
01954                    recommended);
01955         have_warned_about_new_version = 1;
01956         control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
01957                                      "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
01958                                      VERSION, "NEW", recommended);
01959       }
01960     } else {
01961       log_warn(LD_GENERAL, "Please upgrade! "
01962                "This version of Tor (%s) is %s, according to the directory "
01963                "authorities. Recommended versions are: %s",
01964                VERSION,
01965                status == VS_OLD ? "obsolete" : "not recommended",
01966                recommended);
01967       have_warned_about_old_version = 1;
01968       control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
01969            "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
01970            VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
01971            recommended);
01972     }
01973   }
01974 }
01975 
01978 static void
01979 download_status_map_update_from_v2_networkstatus(void)
01980 {
01981   digestmap_t *dl_status;
01982   if (!networkstatus_v2_list)
01983     return;
01984   if (!v2_download_status_map)
01985     v2_download_status_map = digestmap_new();
01986 
01987   dl_status = digestmap_new();
01988   SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
01989     SMARTLIST_FOREACH_BEGIN(ns->entries, const routerstatus_t *, rs) {
01990       const char *d = rs->descriptor_digest;
01991       download_status_t *s;
01992       if (digestmap_get(dl_status, d))
01993         continue;
01994       if (!(s = digestmap_remove(v2_download_status_map, d))) {
01995         s = tor_malloc_zero(sizeof(download_status_t));
01996       }
01997       digestmap_set(dl_status, d, s);
01998     } SMARTLIST_FOREACH_END(rs);
01999   } SMARTLIST_FOREACH_END(ns);
02000   digestmap_free(v2_download_status_map, _tor_free);
02001   v2_download_status_map = dl_status;
02002   networkstatus_v2_list_has_changed = 0;
02003 }
02004 
02007 static void
02008 routerstatus_list_update_named_server_map(void)
02009 {
02010   if (!current_consensus)
02011     return;
02012 
02013   strmap_free(named_server_map, _tor_free);
02014   named_server_map = strmap_new();
02015   strmap_free(unnamed_server_map, NULL);
02016   unnamed_server_map = strmap_new();
02017   SMARTLIST_FOREACH(current_consensus->routerstatus_list,
02018                                                    const routerstatus_t *, rs,
02019     {
02020       if (rs->is_named) {
02021         strmap_set_lc(named_server_map, rs->nickname,
02022                       tor_memdup(rs->identity_digest, DIGEST_LEN));
02023       }
02024       if (rs->is_unnamed) {
02025         strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
02026       }
02027     });
02028 }
02029 
02033 void
02034 routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
02035                                                    int reset_failures)
02036 {
02037   trusted_dir_server_t *ds;
02038   const or_options_t *options = get_options();
02039   int authdir = authdir_mode_v2(options) || authdir_mode_v3(options);
02040   networkstatus_t *ns = current_consensus;
02041   if (!ns || !smartlist_len(ns->routerstatus_list))
02042     return;
02043   if (!networkstatus_v2_list)
02044     networkstatus_v2_list = smartlist_new();
02045 
02046   routers_sort_by_identity(routers);
02047 
02048   SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
02049                          routers, routerinfo_t *, router,
02050                          tor_memcmp(rs->identity_digest,
02051                                router->cache_info.identity_digest, DIGEST_LEN),
02052   {
02053   }) {
02054     /* We have a routerstatus for this router. */
02055     const char *digest = router->cache_info.identity_digest;
02056 
02057     ds = router_get_trusteddirserver_by_digest(digest);
02058 
02059     /* Is it the same descriptor, or only the same identity? */
02060     if (tor_memeq(router->cache_info.signed_descriptor_digest,
02061                 rs->descriptor_digest, DIGEST_LEN)) {
02062       if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
02063         router->cache_info.last_listed_as_valid_until = ns->valid_until;
02064     }
02065 
02066     if (authdir) {
02067       /* If we _are_ an authority, we should check whether this router
02068        * is one that will cause us to need a reachability test. */
02069       routerinfo_t *old_router =
02070         router_get_mutable_by_digest(router->cache_info.identity_digest);
02071       if (old_router != router) {
02072         router->needs_retest_if_added =
02073           dirserv_should_launch_reachability_test(router, old_router);
02074       }
02075     }
02076     if (rs->is_flagged_running && ds) {
02077       download_status_reset(&ds->v2_ns_dl_status);
02078     }
02079     if (reset_failures) {
02080       download_status_reset(&rs->dl_status);
02081     }
02082   } SMARTLIST_FOREACH_JOIN_END(rs, router);
02083 
02084   /* Now update last_listed_as_valid_until from v2 networkstatuses. */
02085   SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns, {
02086     time_t live_until = ns->published_on + V2_NETWORKSTATUS_ROUTER_LIFETIME;
02087     SMARTLIST_FOREACH_JOIN(ns->entries, const routerstatus_t *, rs,
02088                          routers, routerinfo_t *, ri,
02089                          tor_memcmp(rs->identity_digest,
02090                                 ri->cache_info.identity_digest, DIGEST_LEN),
02091                          STMT_NIL) {
02092       if (tor_memeq(ri->cache_info.signed_descriptor_digest,
02093                   rs->descriptor_digest, DIGEST_LEN)) {
02094         if (live_until > ri->cache_info.last_listed_as_valid_until)
02095           ri->cache_info.last_listed_as_valid_until = live_until;
02096       }
02097     } SMARTLIST_FOREACH_JOIN_END(rs, ri);
02098   });
02099 
02100   router_dir_info_changed();
02101 }
02102 
02105 void
02106 signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
02107 {
02108   networkstatus_t *ns = current_ns_consensus;
02109   if (!ns)
02110     return;
02111 
02112   if (!ns->desc_digest_map) {
02113     char dummy[DIGEST_LEN];
02114     /* instantiates the digest map. */
02115     memset(dummy, 0, sizeof(dummy));
02116     router_get_consensus_status_by_descriptor_digest(ns, dummy);
02117   }
02118   SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
02119   {
02120     const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
02121                                        d->signed_descriptor_digest);
02122     if (rs) {
02123       if (ns->valid_until > d->last_listed_as_valid_until)
02124         d->last_listed_as_valid_until = ns->valid_until;
02125     }
02126   });
02127 }
02128 
02132 char *
02133 networkstatus_getinfo_helper_single(const routerstatus_t *rs)
02134 {
02135   char buf[RS_ENTRY_LEN+1];
02136   routerstatus_format_entry(buf, sizeof(buf), rs, NULL, NS_CONTROL_PORT);
02137   return tor_strdup(buf);
02138 }
02139 
02147 char *
02148 networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
02149 {
02150   time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
02151   char *answer;
02152   routerlist_t *rl = router_get_routerlist();
02153   smartlist_t *statuses;
02154   uint8_t purpose = router_purpose_from_string(purpose_string);
02155   routerstatus_t rs;
02156   int bridge_auth = authdir_mode_bridge(get_options());
02157 
02158   if (purpose == ROUTER_PURPOSE_UNKNOWN) {
02159     log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
02160              purpose_string);
02161     return NULL;
02162   }
02163 
02164   statuses = smartlist_new();
02165   SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
02166     node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
02167     if (!node)
02168       continue;
02169     if (ri->cache_info.published_on < cutoff)
02170       continue;
02171     if (ri->purpose != purpose)
02172       continue;
02173     if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
02174       dirserv_set_router_is_running(ri, now);
02175     /* then generate and write out status lines for each of them */
02176     set_routerstatus_from_routerinfo(&rs, node, ri, now, 0, 0, 0, 0);
02177     smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
02178   });
02179 
02180   answer = smartlist_join_strings(statuses, "", 0, NULL);
02181   SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
02182   smartlist_free(statuses);
02183   return answer;
02184 }
02185 
02187 void
02188 networkstatus_dump_bridge_status_to_file(time_t now)
02189 {
02190   char *status = networkstatus_getinfo_by_purpose("bridge", now);
02191   const or_options_t *options = get_options();
02192   char *fname = NULL;
02193   tor_asprintf(&fname, "%s"PATH_SEPARATOR"networkstatus-bridges",
02194                options->DataDirectory);
02195   write_str_to_file(fname,status,0);
02196   tor_free(fname);
02197   tor_free(status);
02198 }
02199 
02200 /* DOCDOC get_net_param_from_list */
02201 static int32_t
02202 get_net_param_from_list(smartlist_t *net_params, const char *param_name,
02203                         int32_t default_val, int32_t min_val, int32_t max_val)
02204 {
02205   int32_t res = default_val;
02206   size_t name_len = strlen(param_name);
02207 
02208   tor_assert(max_val > min_val);
02209   tor_assert(min_val <= default_val);
02210   tor_assert(max_val >= default_val);
02211 
02212   SMARTLIST_FOREACH_BEGIN(net_params, const char *, p) {
02213     if (!strcmpstart(p, param_name) && p[name_len] == '=') {
02214       int ok=0;
02215       long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
02216                               INT32_MAX, &ok, NULL);
02217       if (ok) {
02218         res = (int32_t) v;
02219         break;
02220       }
02221     }
02222   } SMARTLIST_FOREACH_END(p);
02223 
02224   if (res < min_val) {
02225     log_warn(LD_DIR, "Consensus parameter %s is too small. Got %d, raising to "
02226              "%d.", param_name, res, min_val);
02227     res = min_val;
02228   } else if (res > max_val) {
02229     log_warn(LD_DIR, "Consensus parameter %s is too large. Got %d, capping to "
02230              "%d.", param_name, res, max_val);
02231     res = max_val;
02232   }
02233 
02234   return res;
02235 }
02236 
02244 int32_t
02245 networkstatus_get_param(const networkstatus_t *ns, const char *param_name,
02246                         int32_t default_val, int32_t min_val, int32_t max_val)
02247 {
02248   if (!ns) /* if they pass in null, go find it ourselves */
02249     ns = networkstatus_get_latest_consensus();
02250 
02251   if (!ns || !ns->net_params)
02252     return default_val;
02253 
02254   return get_net_param_from_list(ns->net_params, param_name,
02255                                  default_val, min_val, max_val);
02256 }
02257 
02262 int32_t
02263 networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name,
02264                             int32_t default_val)
02265 {
02266   int32_t param;
02267   int max;
02268   if (!ns) /* if they pass in null, go find it ourselves */
02269     ns = networkstatus_get_latest_consensus();
02270 
02271   if (!ns || !ns->weight_params)
02272     return default_val;
02273 
02274   max = circuit_build_times_get_bw_scale(ns);
02275   param = get_net_param_from_list(ns->weight_params, weight_name,
02276                                   default_val, -1,
02277                                   BW_MAX_WEIGHT_SCALE);
02278   if (param > max) {
02279     log_warn(LD_DIR, "Value of consensus weight %s was too large, capping "
02280              "to %d", weight_name, max);
02281     param = max;
02282   }
02283   return param;
02284 }
02285 
02288 const char *
02289 networkstatus_get_flavor_name(consensus_flavor_t flav)
02290 {
02291   switch (flav) {
02292     case FLAV_NS:
02293       return "ns";
02294     case FLAV_MICRODESC:
02295       return "microdesc";
02296     default:
02297       tor_fragile_assert();
02298       return "??";
02299   }
02300 }
02301 
02304 int
02305 networkstatus_parse_flavor_name(const char *flavname)
02306 {
02307   if (!strcmp(flavname, "ns"))
02308     return FLAV_NS;
02309   else if (!strcmp(flavname, "microdesc"))
02310     return FLAV_MICRODESC;
02311   else
02312     return -1;
02313 }
02314 
02319 int
02320 getinfo_helper_networkstatus(control_connection_t *conn,
02321                              const char *question, char **answer,
02322                              const char **errmsg)
02323 {
02324   const routerstatus_t *status;
02325   (void) conn;
02326 
02327   if (!current_consensus) {
02328     *answer = tor_strdup("");
02329     return 0;
02330   }
02331 
02332   if (!strcmp(question, "ns/all")) {
02333     smartlist_t *statuses = smartlist_new();
02334     SMARTLIST_FOREACH(current_consensus->routerstatus_list,
02335                       const routerstatus_t *, rs,
02336       {
02337         smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
02338       });
02339     *answer = smartlist_join_strings(statuses, "", 0, NULL);
02340     SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
02341     smartlist_free(statuses);
02342     return 0;
02343   } else if (!strcmpstart(question, "ns/id/")) {
02344     char d[DIGEST_LEN];
02345 
02346     if (base16_decode(d, DIGEST_LEN, question+6, strlen(question+6))) {
02347       *errmsg = "Data not decodeable as hex";
02348       return -1;
02349     }
02350     status = router_get_consensus_status_by_id(d);
02351   } else if (!strcmpstart(question, "ns/name/")) {
02352     status = router_get_consensus_status_by_nickname(question+8, 0);
02353   } else if (!strcmpstart(question, "ns/purpose/")) {
02354     *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
02355     return *answer ? 0 : -1;
02356   } else {
02357     return 0;
02358   }
02359 
02360   if (status)
02361     *answer = networkstatus_getinfo_helper_single(status);
02362   return 0;
02363 }
02364 
02366 void
02367 networkstatus_free_all(void)
02368 {
02369   int i;
02370   if (networkstatus_v2_list) {
02371     SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
02372                       networkstatus_v2_free(ns));
02373     smartlist_free(networkstatus_v2_list);
02374     networkstatus_v2_list = NULL;
02375   }
02376 
02377   digestmap_free(v2_download_status_map, _tor_free);
02378   v2_download_status_map = NULL;
02379   networkstatus_vote_free(current_ns_consensus);
02380   networkstatus_vote_free(current_md_consensus);
02381   current_md_consensus = current_ns_consensus = NULL;
02382 
02383   for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
02384     consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
02385     if (waiting->consensus) {
02386       networkstatus_vote_free(waiting->consensus);
02387       waiting->consensus = NULL;
02388     }
02389     tor_free(waiting->body);
02390   }
02391 
02392   strmap_free(named_server_map, _tor_free);
02393   strmap_free(unnamed_server_map, NULL);
02394 }
02395