tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

networkstatus.c (103470B)


      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-2021, The Tor Project, Inc. */
      5 /* See LICENSE for licensing information */
      6 
      7 /**
      8 * \file networkstatus.c
      9 * \brief Functions and structures for handling networkstatus documents as a
     10 * client or as a directory cache.
     11 *
     12 * A consensus networkstatus object is created by the directory
     13 * authorities.  It authenticates a set of network parameters--most
     14 * importantly, the list of all the relays in the network.  This list
     15 * of relays is represented as an array of routerstatus_t objects.
     16 *
     17 * There are currently two flavors of consensus.  With the older "NS"
     18 * flavor, each relay is associated with a digest of its router
     19 * descriptor. Tor instances that use this consensus keep the list of
     20 * router descriptors as routerinfo_t objects stored and managed in
     21 * routerlist.c.  With the newer "microdesc" flavor, each relay is
     22 * associated with a digest of the microdescriptor that the authorities
     23 * made for it.  These are stored and managed in microdesc.c. Information
     24 * about the router is divided between the the networkstatus and the
     25 * microdescriptor according to the general rule that microdescriptors
     26 * should hold information that changes much less frequently than the
     27 * information in the networkstatus.
     28 *
     29 * Modern clients use microdescriptor networkstatuses.  Directory caches
     30 * need to keep both kinds of networkstatus document, so they can serve them.
     31 *
     32 * This module manages fetching, holding, storing, updating, and
     33 * validating networkstatus objects.  The download-and-validate process
     34 * is slightly complicated by the fact that the keys you need to
     35 * validate a consensus are stored in the authority certificates, which
     36 * you might not have yet when you download the consensus.
     37 */
     38 
     39 #define NETWORKSTATUS_PRIVATE
     40 #include "core/or/or.h"
     41 #include "app/config/config.h"
     42 #include "core/mainloop/connection.h"
     43 #include "core/mainloop/cpuworker.h"
     44 #include "core/mainloop/mainloop.h"
     45 #include "core/mainloop/netstatus.h"
     46 #include "core/or/channel.h"
     47 #include "core/or/channelpadding.h"
     48 #include "core/or/circuitpadding.h"
     49 #include "core/or/congestion_control_common.h"
     50 #include "core/or/congestion_control_flow.h"
     51 #include "core/or/circuitmux.h"
     52 #include "core/or/circuitmux_ewma.h"
     53 #include "core/or/circuitstats.h"
     54 #include "core/or/conflux_params.h"
     55 #include "core/or/connection_edge.h"
     56 #include "core/or/connection_or.h"
     57 #include "core/or/dos.h"
     58 #include "core/or/protover.h"
     59 #include "core/or/relay.h"
     60 #include "core/or/scheduler.h"
     61 #include "core/or/versions.h"
     62 #include "feature/client/bridges.h"
     63 #include "feature/client/entrynodes.h"
     64 #include "feature/client/transports.h"
     65 #include "feature/control/control_events.h"
     66 #include "feature/dirauth/reachability.h"
     67 #include "feature/dircache/consdiffmgr.h"
     68 #include "feature/dircache/dirserv.h"
     69 #include "feature/dirclient/dirclient.h"
     70 #include "feature/dirclient/dirclient_modes.h"
     71 #include "feature/dirclient/dlstatus.h"
     72 #include "feature/dircommon/directory.h"
     73 #include "feature/dirauth/voting_schedule.h"
     74 #include "feature/dirparse/ns_parse.h"
     75 #include "feature/hibernate/hibernate.h"
     76 #include "feature/hs/hs_dos.h"
     77 #include "feature/nodelist/authcert.h"
     78 #include "feature/nodelist/dirlist.h"
     79 #include "feature/nodelist/fmt_routerstatus.h"
     80 #include "feature/nodelist/microdesc.h"
     81 #include "feature/nodelist/networkstatus.h"
     82 #include "feature/nodelist/node_select.h"
     83 #include "feature/nodelist/nodelist.h"
     84 #include "feature/nodelist/routerinfo.h"
     85 #include "feature/nodelist/routerlist.h"
     86 #include "feature/nodelist/torcert.h"
     87 #include "feature/relay/dns.h"
     88 #include "feature/relay/onion_queue.h"
     89 #include "feature/relay/routermode.h"
     90 #include "lib/crypt_ops/crypto_rand.h"
     91 #include "lib/crypt_ops/crypto_util.h"
     92 
     93 #include "feature/dirauth/dirauth_periodic.h"
     94 #include "feature/dirauth/dirvote.h"
     95 #include "feature/dirauth/authmode.h"
     96 #include "feature/dirauth/shared_random.h"
     97 #include "feature/dirauth/voteflags.h"
     98 
     99 #include "feature/nodelist/authority_cert_st.h"
    100 #include "feature/dircommon/dir_connection_st.h"
    101 #include "feature/dirclient/dir_server_st.h"
    102 #include "feature/nodelist/document_signature_st.h"
    103 #include "feature/nodelist/networkstatus_st.h"
    104 #include "feature/nodelist/networkstatus_voter_info_st.h"
    105 #include "feature/dirauth/ns_detached_signatures_st.h"
    106 #include "feature/nodelist/node_st.h"
    107 #include "feature/nodelist/routerinfo_st.h"
    108 #include "feature/nodelist/routerlist_st.h"
    109 #include "feature/dirauth/vote_microdesc_hash_st.h"
    110 #include "feature/nodelist/vote_routerstatus_st.h"
    111 #include "feature/nodelist/routerstatus_st.h"
    112 #include "feature/stats/rephist.h"
    113 
    114 #ifdef HAVE_UNISTD_H
    115 #include <unistd.h>
    116 #endif
    117 
    118 /** Most recently received and validated v3 "ns"-flavored consensus network
    119 * status. */
    120 STATIC networkstatus_t *current_ns_consensus = NULL;
    121 
    122 /** Most recently received and validated v3 "microdesc"-flavored consensus
    123 * network status. */
    124 STATIC networkstatus_t *current_md_consensus = NULL;
    125 
    126 /** A v3 consensus networkstatus that we've received, but which we don't
    127 * have enough certificates to be happy about. */
    128 typedef struct consensus_waiting_for_certs_t {
    129  /** The consensus itself. */
    130  networkstatus_t *consensus;
    131  /** When did we set the current value of consensus_waiting_for_certs?  If
    132   * this is too recent, we shouldn't try to fetch a new consensus for a
    133   * little while, to give ourselves time to get certificates for this one. */
    134  time_t set_at;
    135  /** Set to 1 if we've been holding on to it for so long we should maybe
    136   * treat it as being bad. */
    137  int dl_failed;
    138 } consensus_waiting_for_certs_t;
    139 
    140 /** An array, for each flavor of consensus we might want, of consensuses that
    141 * we have downloaded, but which we cannot verify due to having insufficient
    142 * authority certificates. */
    143 static consensus_waiting_for_certs_t
    144       consensus_waiting_for_certs[N_CONSENSUS_FLAVORS];
    145 
    146 /** A time before which we shouldn't try to replace the current consensus:
    147 * this will be at some point after the next consensus becomes valid, but
    148 * before the current consensus becomes invalid. */
    149 static time_t time_to_download_next_consensus[N_CONSENSUS_FLAVORS];
    150 /** Download status for the current consensus networkstatus. */
    151 static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS] =
    152  {
    153    { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
    154      DL_SCHED_INCREMENT_FAILURE, 0, 0 },
    155    { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
    156      DL_SCHED_INCREMENT_FAILURE, 0, 0 },
    157  };
    158 
    159 #define N_CONSENSUS_BOOTSTRAP_SCHEDULES 2
    160 #define CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY 0
    161 #define CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER  1
    162 
    163 /* Using DL_SCHED_INCREMENT_ATTEMPT on these schedules means that
    164 * download_status_increment_failure won't increment these entries.
    165 * However, any bootstrap connection failures that occur after we have
    166 * a valid consensus will count against the failure counts on the non-bootstrap
    167 * schedules. There should only be one of these, as all the others will have
    168 * been cancelled. (This doesn't seem to be a significant issue.) */
    169 static download_status_t
    170              consensus_bootstrap_dl_status[N_CONSENSUS_BOOTSTRAP_SCHEDULES] =
    171  {
    172    { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_AUTHORITY,
    173      DL_SCHED_INCREMENT_ATTEMPT, 0, 0 },
    174    /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
    175    { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
    176      DL_SCHED_INCREMENT_ATTEMPT, 0, 0 },
    177  };
    178 
    179 /** True iff we have logged a warning about this OR's version being older than
    180 * listed by the authorities. */
    181 static int have_warned_about_old_version = 0;
    182 /** True iff we have logged a warning about this OR's version being newer than
    183 * listed by the authorities. */
    184 static int have_warned_about_new_version = 0;
    185 
    186 static void update_consensus_bootstrap_multiple_downloads(
    187                                                  time_t now,
    188                                                  const or_options_t *options);
    189 static int networkstatus_check_required_protocols(const networkstatus_t *ns,
    190                                                  int client_mode,
    191                                                  char **warning_out);
    192 static int reload_consensus_from_file(const char *fname,
    193                                      const char *flavor,
    194                                      unsigned flags,
    195                                      const char *source_dir);
    196 
    197 /** Forget that we've warned about anything networkstatus-related, so we will
    198 * give fresh warnings if the same behavior happens again. */
    199 void
    200 networkstatus_reset_warnings(void)
    201 {
    202  SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
    203                    node->name_lookup_warned = 0);
    204 
    205  have_warned_about_old_version = 0;
    206  have_warned_about_new_version = 0;
    207 }
    208 
    209 /** Reset the descriptor download failure count on all networkstatus docs, so
    210 * that we can retry any long-failed documents immediately.
    211 */
    212 void
    213 networkstatus_reset_download_failures(void)
    214 {
    215  int i;
    216 
    217  log_debug(LD_GENERAL,
    218            "In networkstatus_reset_download_failures()");
    219 
    220  for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
    221    download_status_reset(&consensus_dl_status[i]);
    222 
    223  for (i=0; i < N_CONSENSUS_BOOTSTRAP_SCHEDULES; ++i)
    224    download_status_reset(&consensus_bootstrap_dl_status[i]);
    225 }
    226 
    227 /** Return the filename used to cache the consensus of a given flavor */
    228 MOCK_IMPL(char *,
    229 networkstatus_get_cache_fname,(int flav,
    230                               const char *flavorname,
    231                               int unverified_consensus))
    232 {
    233  char buf[128];
    234  const char *prefix;
    235  if (unverified_consensus) {
    236    prefix = "unverified";
    237  } else {
    238    prefix = "cached";
    239  }
    240  if (flav == FLAV_NS) {
    241    tor_snprintf(buf, sizeof(buf), "%s-consensus", prefix);
    242  } else {
    243    tor_snprintf(buf, sizeof(buf), "%s-%s-consensus", prefix, flavorname);
    244  }
    245 
    246  return get_cachedir_fname(buf);
    247 }
    248 
    249 /**
    250 * Read and return the cached consensus of type <b>flavorname</b>.  If
    251 * <b>unverified</b> is false, get the one we haven't verified. Return NULL if
    252 * the file isn't there. */
    253 static tor_mmap_t *
    254 networkstatus_map_cached_consensus_impl(int flav,
    255                                        const char *flavorname,
    256                                        int unverified_consensus)
    257 {
    258  char *filename = networkstatus_get_cache_fname(flav,
    259                                                 flavorname,
    260                                                 unverified_consensus);
    261  tor_mmap_t *result = tor_mmap_file(filename);
    262  tor_free(filename);
    263  return result;
    264 }
    265 
    266 /** Map the file containing the current cached consensus of flavor
    267 * <b>flavorname</b> */
    268 tor_mmap_t *
    269 networkstatus_map_cached_consensus(const char *flavorname)
    270 {
    271  int flav = networkstatus_parse_flavor_name(flavorname);
    272  if (flav < 0)
    273    return NULL;
    274  return networkstatus_map_cached_consensus_impl(flav, flavorname, 0);
    275 }
    276 
    277 /** Read every cached v3 consensus networkstatus from the disk. */
    278 int
    279 router_reload_consensus_networkstatus(void)
    280 {
    281  const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
    282  int flav;
    283 
    284  /* FFFF Suppress warnings if cached consensus is bad? */
    285  for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
    286    const char *flavor = networkstatus_get_flavor_name(flav);
    287    char *fname = networkstatus_get_cache_fname(flav, flavor, 0);
    288    reload_consensus_from_file(fname, flavor, flags, NULL);
    289    tor_free(fname);
    290 
    291    fname = networkstatus_get_cache_fname(flav, flavor, 1);
    292    reload_consensus_from_file(fname, flavor,
    293                               flags | NSSET_WAS_WAITING_FOR_CERTS,
    294                               NULL);
    295    tor_free(fname);
    296  }
    297 
    298  update_certificate_downloads(time(NULL));
    299 
    300  routers_update_all_from_networkstatus(time(NULL), 3);
    301  update_microdescs_from_networkstatus(time(NULL));
    302 
    303  return 0;
    304 }
    305 
    306 /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
    307 void
    308 vote_routerstatus_free_(vote_routerstatus_t *rs)
    309 {
    310  vote_microdesc_hash_t *h, *next;
    311  if (!rs)
    312    return;
    313  tor_free(rs->version);
    314  tor_free(rs->protocols);
    315  tor_free(rs->status.exitsummary);
    316  for (h = rs->microdesc; h; h = next) {
    317    tor_free(h->microdesc_hash_line);
    318    next = h->next;
    319    tor_free(h);
    320  }
    321  tor_free(rs);
    322 }
    323 
    324 /** Free all storage held by the routerstatus object <b>rs</b>. */
    325 void
    326 routerstatus_free_(routerstatus_t *rs)
    327 {
    328  if (!rs)
    329    return;
    330  tor_free(rs->exitsummary);
    331  tor_free(rs);
    332 }
    333 
    334 /** Free all storage held in <b>sig</b> */
    335 void
    336 document_signature_free_(document_signature_t *sig)
    337 {
    338  tor_free(sig->signature);
    339  tor_free(sig);
    340 }
    341 
    342 /** Return a newly allocated copy of <b>sig</b> */
    343 document_signature_t *
    344 document_signature_dup(const document_signature_t *sig)
    345 {
    346  document_signature_t *r = tor_memdup(sig, sizeof(document_signature_t));
    347  if (r->signature)
    348    r->signature = tor_memdup(sig->signature, sig->signature_len);
    349  return r;
    350 }
    351 
    352 /** Free all storage held in <b>ns</b>. */
    353 void
    354 networkstatus_vote_free_(networkstatus_t *ns)
    355 {
    356  if (!ns)
    357    return;
    358 
    359  tor_free(ns->client_versions);
    360  tor_free(ns->server_versions);
    361  tor_free(ns->recommended_client_protocols);
    362  tor_free(ns->recommended_relay_protocols);
    363  tor_free(ns->required_client_protocols);
    364  tor_free(ns->required_relay_protocols);
    365 
    366  if (ns->known_flags) {
    367    SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
    368    smartlist_free(ns->known_flags);
    369  }
    370  if (ns->weight_params) {
    371    SMARTLIST_FOREACH(ns->weight_params, char *, c, tor_free(c));
    372    smartlist_free(ns->weight_params);
    373  }
    374  if (ns->net_params) {
    375    SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
    376    smartlist_free(ns->net_params);
    377  }
    378  if (ns->supported_methods) {
    379    SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
    380    smartlist_free(ns->supported_methods);
    381  }
    382  if (ns->package_lines) {
    383    SMARTLIST_FOREACH(ns->package_lines, char *, c, tor_free(c));
    384    smartlist_free(ns->package_lines);
    385  }
    386  if (ns->voters) {
    387    SMARTLIST_FOREACH_BEGIN(ns->voters, networkstatus_voter_info_t *, voter) {
    388      tor_free(voter->nickname);
    389      tor_free(voter->address);
    390      tor_free(voter->contact);
    391      if (voter->sigs) {
    392        SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
    393                          document_signature_free(sig));
    394        smartlist_free(voter->sigs);
    395      }
    396      tor_free(voter);
    397    } SMARTLIST_FOREACH_END(voter);
    398    smartlist_free(ns->voters);
    399  }
    400  authority_cert_free(ns->cert);
    401 
    402  if (ns->routerstatus_list) {
    403    if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
    404      SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
    405                        vote_routerstatus_free(rs));
    406    } else {
    407      SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
    408                        routerstatus_free(rs));
    409    }
    410 
    411    smartlist_free(ns->routerstatus_list);
    412  }
    413 
    414  if (ns->bw_file_headers) {
    415    SMARTLIST_FOREACH(ns->bw_file_headers, char *, c, tor_free(c));
    416    smartlist_free(ns->bw_file_headers);
    417  }
    418 
    419  digestmap_free(ns->desc_digest_map, NULL);
    420 
    421  if (ns->sr_info.commits) {
    422    dirvote_clear_commits(ns);
    423  }
    424  tor_free(ns->sr_info.previous_srv);
    425  tor_free(ns->sr_info.current_srv);
    426 
    427  memwipe(ns, 11, sizeof(*ns));
    428  tor_free(ns);
    429 }
    430 
    431 /** Return the voter info from <b>vote</b> for the voter whose identity digest
    432 * is <b>identity</b>, or NULL if no such voter is associated with
    433 * <b>vote</b>. */
    434 networkstatus_voter_info_t *
    435 networkstatus_get_voter_by_id(networkstatus_t *vote,
    436                              const char *identity)
    437 {
    438  if (!vote || !vote->voters)
    439    return NULL;
    440  SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
    441    if (fast_memeq(voter->identity_digest, identity, DIGEST_LEN))
    442      return voter);
    443  return NULL;
    444 }
    445 
    446 /** Return the signature made by <b>voter</b> using the algorithm
    447 * <b>alg</b>, or NULL if none is found. */
    448 document_signature_t *
    449 networkstatus_get_voter_sig_by_alg(const networkstatus_voter_info_t *voter,
    450                                   digest_algorithm_t alg)
    451 {
    452  if (!voter->sigs)
    453    return NULL;
    454  SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
    455                    if (sig->alg == alg)
    456                    return sig);
    457  return NULL;
    458 }
    459 
    460 /** Check whether the signature <b>sig</b> is correctly signed with the
    461 * signing key in <b>cert</b>.  Return -1 if <b>cert</b> doesn't match the
    462 * signing key; otherwise set the good_signature or bad_signature flag on
    463 * <b>voter</b>, and return 0. */
    464 int
    465 networkstatus_check_document_signature(const networkstatus_t *consensus,
    466                                       document_signature_t *sig,
    467                                       const authority_cert_t *cert)
    468 {
    469  char key_digest[DIGEST_LEN];
    470  const int dlen = sig->alg == DIGEST_SHA1 ? DIGEST_LEN : DIGEST256_LEN;
    471  char *signed_digest;
    472  size_t signed_digest_len;
    473 
    474  if (crypto_pk_get_digest(cert->signing_key, key_digest)<0)
    475    return -1;
    476  if (tor_memneq(sig->signing_key_digest, key_digest, DIGEST_LEN) ||
    477      tor_memneq(sig->identity_digest, cert->cache_info.identity_digest,
    478                 DIGEST_LEN))
    479    return -1;
    480 
    481  if (authority_cert_is_denylisted(cert)) {
    482    /* We implement denylisting for authority signing keys by treating
    483     * all their signatures as always bad. That way we don't get into
    484     * crazy loops of dropping and re-fetching signatures. */
    485    log_warn(LD_DIR, "Ignoring a consensus signature made with deprecated"
    486             " signing key %s",
    487             hex_str(cert->signing_key_digest, DIGEST_LEN));
    488    sig->bad_signature = 1;
    489    return 0;
    490  }
    491 
    492  signed_digest_len = crypto_pk_keysize(cert->signing_key);
    493  signed_digest = tor_malloc(signed_digest_len);
    494  if (crypto_pk_public_checksig(cert->signing_key,
    495                                signed_digest,
    496                                signed_digest_len,
    497                                sig->signature,
    498                                sig->signature_len) < dlen ||
    499      tor_memneq(signed_digest, consensus->digests.d[sig->alg], dlen)) {
    500    log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
    501    sig->bad_signature = 1;
    502  } else {
    503    sig->good_signature = 1;
    504  }
    505  tor_free(signed_digest);
    506  return 0;
    507 }
    508 
    509 /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
    510 * as-yet-unchecked signature on <b>consensus</b>.  Return 1 if there is a
    511 * signature from every recognized authority on it, 0 if there are
    512 * enough good signatures from recognized authorities on it, -1 if we might
    513 * get enough good signatures by fetching missing certificates, and -2
    514 * otherwise.  Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
    515 * about every problem; if warn is at least 1, warn only if we can't get
    516 * enough signatures; if warn is negative, log nothing at all. */
    517 int
    518 networkstatus_check_consensus_signature(networkstatus_t *consensus,
    519                                        int warn)
    520 {
    521  int n_good = 0;
    522  int n_missing_key = 0, n_dl_failed_key = 0;
    523  int n_bad = 0;
    524  int n_unknown = 0;
    525  int n_no_signature = 0;
    526  int n_v3_authorities = get_n_authorities(V3_DIRINFO);
    527  int n_required = n_v3_authorities/2 + 1;
    528  smartlist_t *list_good = smartlist_new();
    529  smartlist_t *list_no_signature = smartlist_new();
    530  smartlist_t *need_certs_from = smartlist_new();
    531  smartlist_t *unrecognized = smartlist_new();
    532  smartlist_t *missing_authorities = smartlist_new();
    533  int severity;
    534  time_t now = time(NULL);
    535 
    536  tor_assert(consensus->type == NS_TYPE_CONSENSUS);
    537 
    538  SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *,
    539                          voter) {
    540    int good_here = 0;
    541    int bad_here = 0;
    542    int unknown_here = 0;
    543    int missing_key_here = 0, dl_failed_key_here = 0;
    544    SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
    545      if (!sig->good_signature && !sig->bad_signature &&
    546          sig->signature) {
    547        /* we can try to check the signature. */
    548        int is_v3_auth = trusteddirserver_get_by_v3_auth_digest(
    549                                              sig->identity_digest) != NULL;
    550        authority_cert_t *cert =
    551          authority_cert_get_by_digests(sig->identity_digest,
    552                                        sig->signing_key_digest);
    553        tor_assert(tor_memeq(sig->identity_digest, voter->identity_digest,
    554                           DIGEST_LEN));
    555 
    556        if (!is_v3_auth) {
    557          smartlist_add(unrecognized, voter);
    558          ++unknown_here;
    559          continue;
    560        } else if (!cert || cert->expires < now) {
    561          smartlist_add(need_certs_from, voter);
    562          ++missing_key_here;
    563          if (authority_cert_dl_looks_uncertain(sig->identity_digest))
    564            ++dl_failed_key_here;
    565          continue;
    566        }
    567        if (networkstatus_check_document_signature(consensus, sig, cert) < 0) {
    568          smartlist_add(need_certs_from, voter);
    569          ++missing_key_here;
    570          if (authority_cert_dl_looks_uncertain(sig->identity_digest))
    571            ++dl_failed_key_here;
    572          continue;
    573        }
    574      }
    575      if (sig->good_signature)
    576        ++good_here;
    577      else if (sig->bad_signature)
    578        ++bad_here;
    579    } SMARTLIST_FOREACH_END(sig);
    580 
    581    if (good_here) {
    582      ++n_good;
    583      smartlist_add(list_good, voter->nickname);
    584    } else if (bad_here) {
    585      ++n_bad;
    586    } else if (missing_key_here) {
    587      ++n_missing_key;
    588      if (dl_failed_key_here)
    589        ++n_dl_failed_key;
    590    } else if (unknown_here) {
    591      ++n_unknown;
    592    } else {
    593      ++n_no_signature;
    594      smartlist_add(list_no_signature, voter->nickname);
    595    }
    596  } SMARTLIST_FOREACH_END(voter);
    597 
    598  /* Now see whether we're missing any voters entirely. */
    599  SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
    600                    dir_server_t *, ds,
    601    {
    602      if ((ds->type & V3_DIRINFO) &&
    603          !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
    604        smartlist_add(missing_authorities, ds);
    605    });
    606 
    607  if (warn > 1 || (warn >= 0 &&
    608                   (n_good + n_missing_key - n_dl_failed_key < n_required))) {
    609    severity = LOG_WARN;
    610  } else {
    611    severity = LOG_INFO;
    612  }
    613 
    614  if (warn >= 0) {
    615    SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
    616      {
    617        tor_log(severity, LD_DIR, "Consensus includes unrecognized authority "
    618                 "'%s' at %s:%" PRIu16 " (contact %s; identity %s)",
    619                 voter->nickname, voter->address, voter->ipv4_dirport,
    620                 voter->contact?voter->contact:"n/a",
    621                 hex_str(voter->identity_digest, DIGEST_LEN));
    622      });
    623    SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
    624      {
    625        tor_log(severity, LD_DIR, "Looks like we need to download a new "
    626                 "certificate from authority '%s' at %s:%" PRIu16
    627                 " (contact %s; identity %s)",
    628                 voter->nickname, voter->address, voter->ipv4_dirport,
    629                 voter->contact?voter->contact:"n/a",
    630                 hex_str(voter->identity_digest, DIGEST_LEN));
    631      });
    632    SMARTLIST_FOREACH(missing_authorities, dir_server_t *, ds,
    633      {
    634        tor_log(severity, LD_DIR, "Consensus does not include configured "
    635                 "authority '%s' at %s:%" PRIu16 " (identity %s)",
    636                 ds->nickname, ds->address, ds->ipv4_dirport,
    637                 hex_str(ds->v3_identity_digest, DIGEST_LEN));
    638      });
    639    {
    640      char *joined;
    641      smartlist_t *sl = smartlist_new();
    642      char *tmp = smartlist_join_strings(list_good, " ", 0, NULL);
    643      smartlist_add_asprintf(sl,
    644                   "A consensus needs %d good signatures from recognized "
    645                   "authorities for us to accept it. "
    646                   "This %s one has %d (%s).",
    647                   n_required,
    648                   networkstatus_get_flavor_name(consensus->flavor),
    649                   n_good, tmp);
    650      tor_free(tmp);
    651      if (n_no_signature) {
    652        tmp = smartlist_join_strings(list_no_signature, " ", 0, NULL);
    653        smartlist_add_asprintf(sl,
    654                     "%d (%s) of the authorities we know didn't sign it.",
    655                     n_no_signature, tmp);
    656        tor_free(tmp);
    657      }
    658      if (n_unknown) {
    659        smartlist_add_asprintf(sl,
    660                      "It has %d signatures from authorities we don't "
    661                      "recognize.", n_unknown);
    662      }
    663      if (n_bad) {
    664        smartlist_add_asprintf(sl, "%d of the signatures on it didn't verify "
    665                      "correctly.", n_bad);
    666      }
    667      if (n_missing_key) {
    668        smartlist_add_asprintf(sl,
    669                      "We were unable to check %d of the signatures, "
    670                      "because we were missing the keys.", n_missing_key);
    671      }
    672      joined = smartlist_join_strings(sl, " ", 0, NULL);
    673      tor_log(severity, LD_DIR, "%s", joined);
    674      tor_free(joined);
    675      SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
    676      smartlist_free(sl);
    677    }
    678  }
    679 
    680  smartlist_free(list_good);
    681  smartlist_free(list_no_signature);
    682  smartlist_free(unrecognized);
    683  smartlist_free(need_certs_from);
    684  smartlist_free(missing_authorities);
    685 
    686  if (n_good == n_v3_authorities)
    687    return 1;
    688  else if (n_good >= n_required)
    689    return 0;
    690  else if (n_good + n_missing_key >= n_required)
    691    return -1;
    692  else
    693    return -2;
    694 }
    695 
    696 /** How far in the future do we allow a network-status to get before removing
    697 * it? (seconds) */
    698 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
    699 
    700 /** Helper for bsearching a list of routerstatus_t pointers: compare a
    701 * digest in the key to the identity digest of a routerstatus_t. */
    702 int
    703 compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
    704 {
    705  const char *key = _key;
    706  const routerstatus_t *rs = *_member;
    707  return tor_memcmp(key, rs->identity_digest, DIGEST_LEN);
    708 }
    709 
    710 /** Helper for bsearching a list of routerstatus_t pointers: compare a
    711 * digest in the key to the identity digest of a routerstatus_t. */
    712 int
    713 compare_digest_to_vote_routerstatus_entry(const void *_key,
    714                                          const void **_member)
    715 {
    716  const char *key = _key;
    717  const vote_routerstatus_t *vrs = *_member;
    718  return tor_memcmp(key, vrs->status.identity_digest, DIGEST_LEN);
    719 }
    720 
    721 /** As networkstatus_find_entry, but do not return a const pointer */
    722 routerstatus_t *
    723 networkstatus_vote_find_mutable_entry(networkstatus_t *ns, const char *digest)
    724 {
    725  return smartlist_bsearch(ns->routerstatus_list, digest,
    726                           compare_digest_to_routerstatus_entry);
    727 }
    728 
    729 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
    730 * NULL if none was found. */
    731 MOCK_IMPL(const routerstatus_t *,
    732 networkstatus_vote_find_entry,(networkstatus_t *ns, const char *digest))
    733 {
    734  return networkstatus_vote_find_mutable_entry(ns, digest);
    735 }
    736 
    737 /*XXXX MOVE make this static once functions are moved into this file. */
    738 /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
    739 * <b>digest</b>.  Return value and set *<b>found_out</b> as for
    740 * smartlist_bsearch_idx(). */
    741 int
    742 networkstatus_vote_find_entry_idx(networkstatus_t *ns,
    743                                  const char *digest, int *found_out)
    744 {
    745  return smartlist_bsearch_idx(ns->routerstatus_list, digest,
    746                               compare_digest_to_routerstatus_entry,
    747                               found_out);
    748 }
    749 
    750 /** As router_get_consensus_status_by_descriptor_digest, but does not return
    751 * a const pointer. */
    752 MOCK_IMPL(routerstatus_t *,
    753 router_get_mutable_consensus_status_by_descriptor_digest,(
    754                                                 networkstatus_t *consensus,
    755                                                 const char *digest))
    756 {
    757  if (!consensus)
    758    consensus = networkstatus_get_latest_consensus();
    759  if (!consensus)
    760    return NULL;
    761  if (!consensus->desc_digest_map) {
    762    digestmap_t *m = consensus->desc_digest_map = digestmap_new();
    763    SMARTLIST_FOREACH(consensus->routerstatus_list,
    764                      routerstatus_t *, rs,
    765     {
    766       digestmap_set(m, rs->descriptor_digest, rs);
    767     });
    768  }
    769  return digestmap_get(consensus->desc_digest_map, digest);
    770 }
    771 
    772 /** Return the consensus view of the status of the router whose current
    773 * <i>descriptor</i> digest in <b>consensus</b> is <b>digest</b>, or NULL if
    774 * no such router is known. */
    775 const routerstatus_t *
    776 router_get_consensus_status_by_descriptor_digest(networkstatus_t *consensus,
    777                                                 const char *digest)
    778 {
    779  return router_get_mutable_consensus_status_by_descriptor_digest(
    780                                                          consensus, digest);
    781 }
    782 
    783 /** Return a smartlist of all router descriptor digests in a consensus */
    784 static smartlist_t *
    785 router_get_descriptor_digests_in_consensus(networkstatus_t *consensus)
    786 {
    787  smartlist_t *result = smartlist_new();
    788  digestmap_iter_t *i;
    789  const char *digest;
    790  void *rs;
    791  char *digest_tmp;
    792 
    793  for (i = digestmap_iter_init(consensus->desc_digest_map);
    794       !(digestmap_iter_done(i));
    795       i = digestmap_iter_next(consensus->desc_digest_map, i)) {
    796    digestmap_iter_get(i, &digest, &rs);
    797    digest_tmp = tor_malloc(DIGEST_LEN);
    798    memcpy(digest_tmp, digest, DIGEST_LEN);
    799    smartlist_add(result, digest_tmp);
    800  }
    801 
    802  return result;
    803 }
    804 
    805 /** Return a smartlist of all router descriptor digests in the current
    806 * consensus */
    807 MOCK_IMPL(smartlist_t *,
    808 router_get_descriptor_digests,(void))
    809 {
    810  smartlist_t *result = NULL;
    811 
    812  if (current_ns_consensus) {
    813    result =
    814      router_get_descriptor_digests_in_consensus(current_ns_consensus);
    815  }
    816 
    817  return result;
    818 }
    819 
    820 /** Given the digest of a router descriptor, return its current download
    821 * status, or NULL if the digest is unrecognized. */
    822 MOCK_IMPL(download_status_t *,
    823 router_get_dl_status_by_descriptor_digest,(const char *d))
    824 {
    825  routerstatus_t *rs;
    826  if (!current_ns_consensus)
    827    return NULL;
    828  if ((rs = router_get_mutable_consensus_status_by_descriptor_digest(
    829                                              current_ns_consensus, d)))
    830    return &rs->dl_status;
    831 
    832  return NULL;
    833 }
    834 
    835 /** As router_get_consensus_status_by_id, but do not return a const pointer */
    836 routerstatus_t *
    837 router_get_mutable_consensus_status_by_id(const char *digest)
    838 {
    839  const networkstatus_t *ns = networkstatus_get_latest_consensus();
    840  if (!ns)
    841    return NULL;
    842  smartlist_t *rslist = ns->routerstatus_list;
    843  return smartlist_bsearch(rslist, digest,
    844                           compare_digest_to_routerstatus_entry);
    845 }
    846 
    847 /** Return the consensus view of the status of the router whose identity
    848 * digest is <b>digest</b>, or NULL if we don't know about any such router. */
    849 const routerstatus_t *
    850 router_get_consensus_status_by_id(const char *digest)
    851 {
    852  return router_get_mutable_consensus_status_by_id(digest);
    853 }
    854 
    855 /** How frequently do directory authorities re-download fresh networkstatus
    856 * documents? */
    857 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
    858 
    859 /** How frequently do non-authority directory caches re-download fresh
    860 * networkstatus documents? */
    861 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
    862 
    863 /** Return true iff, given the options listed in <b>options</b>, <b>flavor</b>
    864 *  is the flavor of a consensus networkstatus that we would like to fetch.
    865 *
    866 * For certificate fetches, use we_want_to_fetch_unknown_auth_certs, and
    867 * for serving fetched documents, use directory_caches_dir_info. */
    868 int
    869 we_want_to_fetch_flavor(const or_options_t *options, int flavor)
    870 {
    871  if (flavor < 0 || flavor > N_CONSENSUS_FLAVORS) {
    872    /* This flavor is crazy; we don't want it */
    873    /*XXXX handle unrecognized flavors later */
    874    return 0;
    875  }
    876  if (authdir_mode_v3(options) || directory_caches_dir_info(options)) {
    877    /* We want to serve all flavors to others, regardless if we would use
    878     * it ourselves. */
    879    return 1;
    880  }
    881  if (options->FetchUselessDescriptors) {
    882    /* In order to get all descriptors, we need to fetch all consensuses. */
    883    return 1;
    884  }
    885  /* Otherwise, we want the flavor only if we want to use it to build
    886   * circuits. */
    887  return flavor == usable_consensus_flavor();
    888 }
    889 
    890 /** Return true iff, given the options listed in <b>options</b>, we would like
    891 * to fetch and store unknown authority certificates.
    892 *
    893 * For consensus and descriptor fetches, use we_want_to_fetch_flavor, and
    894 * for serving fetched certificates, use directory_caches_unknown_auth_certs.
    895 */
    896 int
    897 we_want_to_fetch_unknown_auth_certs(const or_options_t *options)
    898 {
    899  if (authdir_mode_v3(options) ||
    900      directory_caches_unknown_auth_certs((options))) {
    901    /* We want to serve all certs to others, regardless if we would use
    902     * them ourselves. */
    903    return 1;
    904  }
    905  if (options->FetchUselessDescriptors) {
    906    /* Unknown certificates are definitely useless. */
    907    return 1;
    908  }
    909  /* Otherwise, don't fetch unknown certificates. */
    910  return 0;
    911 }
    912 
    913 /** How long will we hang onto a possibly live consensus for which we're
    914 * fetching certs before we check whether there is a better one? */
    915 #define DELAY_WHILE_FETCHING_CERTS (20*60)
    916 
    917 /** What is the minimum time we need to have waited fetching certs, before we
    918 * increment the consensus download schedule on failure? */
    919 #define MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE (1*60)
    920 
    921 /* Check if a downloaded consensus flavor should still wait for certificates
    922 * to download now. If we decide not to wait, check if enough time has passed
    923 * to consider the certificate download failure a separate failure. If so,
    924 * fail dls.
    925 * If waiting for certificates to download, return 1. If not, return 0. */
    926 static int
    927 check_consensus_waiting_for_certs(int flavor, time_t now,
    928                                  download_status_t *dls)
    929 {
    930  consensus_waiting_for_certs_t *waiting;
    931 
    932  /* We should always have a known flavor, because we_want_to_fetch_flavor()
    933   * filters out unknown flavors. */
    934  tor_assert(flavor >= 0 && flavor < N_CONSENSUS_FLAVORS);
    935 
    936  waiting = &consensus_waiting_for_certs[flavor];
    937  if (waiting->consensus) {
    938    /* XXXX make sure this doesn't delay sane downloads. */
    939    if (waiting->set_at + DELAY_WHILE_FETCHING_CERTS > now &&
    940        waiting->consensus->valid_until > now) {
    941      return 1;
    942    } else {
    943      if (!waiting->dl_failed) {
    944        if (waiting->set_at + MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE > now) {
    945          download_status_failed(dls, 0);
    946        }
    947        waiting->dl_failed=1;
    948      }
    949    }
    950  }
    951 
    952  return 0;
    953 }
    954 
    955 /** If we want to download a fresh consensus, launch a new download as
    956 * appropriate. */
    957 static void
    958 update_consensus_networkstatus_downloads(time_t now)
    959 {
    960  int i;
    961  const or_options_t *options = get_options();
    962  const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
    963                                                                        now);
    964  const int use_multi_conn =
    965    networkstatus_consensus_can_use_multiple_directories(options);
    966 
    967  if (should_delay_dir_fetches(options, NULL))
    968    return;
    969 
    970  for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
    971    /* XXXX need some way to download unknown flavors if we are caching. */
    972    const char *resource;
    973    networkstatus_t *c;
    974    int max_in_progress_conns = 1;
    975 
    976    if (! we_want_to_fetch_flavor(options, i))
    977      continue;
    978 
    979    c = networkstatus_get_latest_consensus_by_flavor(i);
    980    if (! (c && c->valid_after <= now && now <= c->valid_until)) {
    981      /* No live consensus? Get one now!*/
    982      time_to_download_next_consensus[i] = now;
    983    }
    984 
    985    if (time_to_download_next_consensus[i] > now)
    986      continue; /* Wait until the current consensus is older. */
    987 
    988    resource = networkstatus_get_flavor_name(i);
    989 
    990    /* Check if we already have enough connections in progress */
    991    if (we_are_bootstrapping && use_multi_conn) {
    992      max_in_progress_conns =
    993        options->ClientBootstrapConsensusMaxInProgressTries;
    994    }
    995    if (connection_dir_count_by_purpose_and_resource(
    996                                                  DIR_PURPOSE_FETCH_CONSENSUS,
    997                                                  resource)
    998        >= max_in_progress_conns) {
    999      continue;
   1000    }
   1001 
   1002    /* Check if we want to launch another download for a usable consensus.
   1003     * Only used during bootstrap. */
   1004    if (we_are_bootstrapping && use_multi_conn
   1005        && i == usable_consensus_flavor()) {
   1006 
   1007      /* Check if we're already downloading a usable consensus */
   1008      if (networkstatus_consensus_is_already_downloading(resource))
   1009        continue;
   1010 
   1011      /* Make multiple connections for a bootstrap consensus download. */
   1012      update_consensus_bootstrap_multiple_downloads(now, options);
   1013    } else {
   1014      /* Check if we failed downloading a consensus too recently */
   1015 
   1016      /* Let's make sure we remembered to update consensus_dl_status */
   1017      tor_assert(consensus_dl_status[i].schedule == DL_SCHED_CONSENSUS);
   1018 
   1019      if (!download_status_is_ready(&consensus_dl_status[i], now)) {
   1020        continue;
   1021      }
   1022 
   1023      /** Check if we're waiting for certificates to download. If we are,
   1024       * launch download for missing directory authority certificates. */
   1025      if (check_consensus_waiting_for_certs(i, now, &consensus_dl_status[i])) {
   1026        update_certificate_downloads(now);
   1027        continue;
   1028      }
   1029 
   1030      /* Try the requested attempt */
   1031      log_info(LD_DIR, "Launching %s standard networkstatus consensus "
   1032               "download.", networkstatus_get_flavor_name(i));
   1033      directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
   1034                                   ROUTER_PURPOSE_GENERAL, resource,
   1035                                   PDS_RETRY_IF_NO_SERVERS,
   1036                                   consensus_dl_status[i].want_authority);
   1037    }
   1038  }
   1039 }
   1040 
   1041 /** When we're bootstrapping, launch one or more consensus download
   1042 * connections, if schedule indicates connection(s) should be made after now.
   1043 * If is_authority, connect to an authority, otherwise, use a fallback
   1044 * directory mirror.
   1045 */
   1046 static void
   1047 update_consensus_bootstrap_attempt_downloads(
   1048                                      time_t now,
   1049                                      download_status_t *dls,
   1050                                      download_want_authority_t want_authority)
   1051 {
   1052  const char *resource = networkstatus_get_flavor_name(
   1053                                                  usable_consensus_flavor());
   1054 
   1055  /* Let's make sure we remembered to update schedule */
   1056  tor_assert(dls->schedule == DL_SCHED_CONSENSUS);
   1057 
   1058  /* Allow for multiple connections in the same second, if the schedule value
   1059   * is 0. */
   1060  while (download_status_is_ready(dls, now)) {
   1061    log_info(LD_DIR, "Launching %s bootstrap %s networkstatus consensus "
   1062             "download.", resource, (want_authority == DL_WANT_AUTHORITY
   1063                                     ? "authority"
   1064                                     : "mirror"));
   1065 
   1066    directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
   1067                                 ROUTER_PURPOSE_GENERAL, resource,
   1068                                 PDS_RETRY_IF_NO_SERVERS, want_authority);
   1069    /* schedule the next attempt */
   1070    download_status_increment_attempt(dls, resource, now);
   1071  }
   1072 }
   1073 
   1074 /** If we're bootstrapping, check the connection schedules and see if we want
   1075 * to make additional, potentially concurrent, consensus download
   1076 * connections.
   1077 * Only call when bootstrapping, and when we want to make additional
   1078 * connections. Only nodes that satisfy
   1079 * networkstatus_consensus_can_use_multiple_directories make additional
   1080 * connections.
   1081 */
   1082 static void
   1083 update_consensus_bootstrap_multiple_downloads(time_t now,
   1084                                              const or_options_t *options)
   1085 {
   1086  const int usable_flavor = usable_consensus_flavor();
   1087 
   1088  /* make sure we can use multiple connections */
   1089  if (!networkstatus_consensus_can_use_multiple_directories(options)) {
   1090    return;
   1091  }
   1092 
   1093  /* Launch concurrent consensus download attempt(s) based on the mirror and
   1094   * authority schedules. Try the mirror first - this makes it slightly more
   1095   * likely that we'll connect to the fallback first, and then end the
   1096   * authority connection attempt. */
   1097 
   1098  /* If a consensus download fails because it's waiting for certificates,
   1099   * we'll fail both the authority and fallback schedules. This is better than
   1100   * failing only one of the schedules, and having the other continue
   1101   * unchecked.
   1102   */
   1103 
   1104  /* If we don't have or can't use extra fallbacks, don't try them. */
   1105  if (networkstatus_consensus_can_use_extra_fallbacks(options)) {
   1106    download_status_t *dls_f =
   1107      &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER];
   1108 
   1109    if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_f)) {
   1110      /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
   1111      update_consensus_bootstrap_attempt_downloads(now, dls_f,
   1112                                                   DL_WANT_ANY_DIRSERVER);
   1113    }
   1114  }
   1115 
   1116  /* Now try an authority. */
   1117  download_status_t *dls_a =
   1118    &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY];
   1119 
   1120  if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_a)) {
   1121    update_consensus_bootstrap_attempt_downloads(now, dls_a,
   1122                                                 DL_WANT_AUTHORITY);
   1123  }
   1124 }
   1125 
   1126 /** Called when an attempt to download a consensus fails: note that the
   1127 * failure occurred, and possibly retry. */
   1128 void
   1129 networkstatus_consensus_download_failed(int status_code, const char *flavname)
   1130 {
   1131  int flav = networkstatus_parse_flavor_name(flavname);
   1132  if (flav >= 0) {
   1133    tor_assert(flav < N_CONSENSUS_FLAVORS);
   1134    /* XXXX handle unrecognized flavors */
   1135    download_status_failed(&consensus_dl_status[flav], status_code);
   1136    /* Retry immediately, if appropriate. */
   1137    update_consensus_networkstatus_downloads(time(NULL));
   1138  }
   1139 }
   1140 
   1141 /** How long do we (as a cache) wait after a consensus becomes non-fresh
   1142 * before trying to fetch another? */
   1143 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
   1144 
   1145 /** Update the time at which we'll consider replacing the current
   1146 * consensus of flavor <b>flav</b> */
   1147 static void
   1148 update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
   1149 {
   1150  const or_options_t *options = get_options();
   1151  networkstatus_t *c = networkstatus_get_latest_consensus_by_flavor(flav);
   1152  const char *flavor = networkstatus_get_flavor_name(flav);
   1153  if (! we_want_to_fetch_flavor(get_options(), flav))
   1154    return;
   1155 
   1156  if (c && c->valid_after <= now && now <= c->valid_until) {
   1157    long dl_interval;
   1158    long interval = c->fresh_until - c->valid_after;
   1159    long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
   1160    time_t start;
   1161 
   1162    if (min_sec_before_caching > interval/16) {
   1163      /* Usually we allow 2-minutes slop factor in case clocks get
   1164         desynchronized a little.  If we're on a private network with
   1165         a crazy-fast voting interval, though, 2 minutes may be too
   1166         much. */
   1167      min_sec_before_caching = interval/16;
   1168      /* make sure we always delay by at least a second before caching */
   1169      if (min_sec_before_caching == 0) {
   1170        min_sec_before_caching = 1;
   1171      }
   1172    }
   1173 
   1174    if (dirclient_fetches_dir_info_early(options)) {
   1175      /* We want to cache the next one at some point after this one
   1176       * is no longer fresh... */
   1177      start = (time_t)(c->fresh_until + min_sec_before_caching);
   1178      /* Some clients may need the consensus sooner than others. */
   1179      if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
   1180        dl_interval = 60;
   1181        if (min_sec_before_caching + dl_interval > interval)
   1182          dl_interval = interval/2;
   1183      } else {
   1184        /* But only in the first half-interval after that. */
   1185        dl_interval = interval/2;
   1186      }
   1187    } else {
   1188      /* We're an ordinary client, a bridge, or a hidden service.
   1189       * Give all the caches enough time to download the consensus. */
   1190      start = (time_t)(c->fresh_until + (interval*3)/4);
   1191      /* But download the next one well before this one is expired. */
   1192      dl_interval = ((c->valid_until - start) * 7 )/ 8;
   1193 
   1194      /* If we're a bridge user, make use of the numbers we just computed
   1195       * to choose the rest of the interval *after* them. */
   1196      if (dirclient_fetches_dir_info_later(options)) {
   1197        /* Give all the *clients* enough time to download the consensus. */
   1198        start = (time_t)(start + dl_interval + min_sec_before_caching);
   1199        /* But try to get it before ours actually expires. */
   1200        dl_interval = (c->valid_until - start) - min_sec_before_caching;
   1201      }
   1202    }
   1203    /* catch low dl_interval in crazy-fast networks */
   1204    if (dl_interval < 1)
   1205      dl_interval = 1;
   1206    /* catch late start in crazy-fast networks */
   1207    if (start+dl_interval >= c->valid_until)
   1208      start = c->valid_until - dl_interval - 1;
   1209    log_debug(LD_DIR,
   1210              "fresh_until: %ld start: %ld "
   1211              "dl_interval: %ld valid_until: %ld ",
   1212              (long)c->fresh_until, (long)start, dl_interval,
   1213              (long)c->valid_until);
   1214    /* We must not try to replace c while it's still fresh: */
   1215    tor_assert(c->fresh_until < start);
   1216    /* We must download the next one before c is invalid: */
   1217    tor_assert(start+dl_interval < c->valid_until);
   1218    time_to_download_next_consensus[flav] =
   1219      start + crypto_rand_int((int)dl_interval);
   1220    {
   1221      char tbuf1[ISO_TIME_LEN+1];
   1222      char tbuf2[ISO_TIME_LEN+1];
   1223      char tbuf3[ISO_TIME_LEN+1];
   1224      format_local_iso_time(tbuf1, c->fresh_until);
   1225      format_local_iso_time(tbuf2, c->valid_until);
   1226      format_local_iso_time(tbuf3, time_to_download_next_consensus[flav]);
   1227      log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
   1228               "will expire at %s; fetching the next one at %s.",
   1229               flavor, (c->fresh_until > now) ? "will be" : "was",
   1230               tbuf1, tbuf2, tbuf3);
   1231    }
   1232  } else {
   1233    time_to_download_next_consensus[flav] = now;
   1234    log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
   1235             flavor);
   1236  }
   1237 }
   1238 
   1239 /** Update the time at which we'll consider replacing the current
   1240 * consensus of flavor 'flavor' */
   1241 void
   1242 update_consensus_networkstatus_fetch_time(time_t now)
   1243 {
   1244  int i;
   1245  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
   1246    if (we_want_to_fetch_flavor(get_options(), i))
   1247      update_consensus_networkstatus_fetch_time_impl(now, i);
   1248  }
   1249 }
   1250 
   1251 /** Return 1 if there's a reason we shouldn't try any directory
   1252 * fetches yet (e.g. we demand bridges and none are yet known).
   1253 * Else return 0.
   1254 
   1255 * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
   1256 * to an explanation of why directory fetches are delayed. (If we
   1257 * return 0, we set msg_out to NULL.)
   1258 */
   1259 int
   1260 should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
   1261 {
   1262  if (msg_out) {
   1263    *msg_out = NULL;
   1264  }
   1265 
   1266  if (options->DisableNetwork) {
   1267    if (msg_out) {
   1268      *msg_out = "DisableNetwork is set.";
   1269    }
   1270    log_info(LD_DIR, "Delaying dir fetches (DisableNetwork is set)");
   1271    return 1;
   1272  }
   1273 
   1274  if (we_are_hibernating()) {
   1275    if (msg_out) {
   1276      *msg_out = "We are hibernating or shutting down.";
   1277    }
   1278    log_info(LD_DIR, "Delaying dir fetches (Hibernating or shutting down)");
   1279    return 1;
   1280  }
   1281 
   1282  if (options->UseBridges) {
   1283    /* If we know that none of our bridges can possibly work, avoid fetching
   1284     * directory documents. But if some of them might work, try again. */
   1285    if (num_bridges_usable(1) == 0) {
   1286      if (msg_out) {
   1287        *msg_out = "No running bridges";
   1288      }
   1289      log_info(LD_DIR, "Delaying dir fetches (no running bridges known)");
   1290      return 1;
   1291    }
   1292 
   1293    if (pt_proxies_configuration_pending()) {
   1294      if (msg_out) {
   1295        *msg_out = "Pluggable transport proxies still configuring";
   1296      }
   1297      log_info(LD_DIR, "Delaying dir fetches (pt proxies still configuring)");
   1298      return 1;
   1299    }
   1300  }
   1301 
   1302  return 0;
   1303 }
   1304 
   1305 /** Launch requests for networkstatus documents as appropriate. This is called
   1306 * when we retry all the connections on a SIGHUP and periodically by a Periodic
   1307 * event which checks whether we want to download any networkstatus documents.
   1308 */
   1309 void
   1310 update_networkstatus_downloads(time_t now)
   1311 {
   1312  const or_options_t *options = get_options();
   1313  if (should_delay_dir_fetches(options, NULL))
   1314    return;
   1315  /** Launch a consensus download request, we will wait for the consensus to
   1316   * download and when it completes we will launch a certificate download
   1317   * request. */
   1318  update_consensus_networkstatus_downloads(now);
   1319 }
   1320 
   1321 /** Launch requests as appropriate for missing directory authority
   1322 * certificates. */
   1323 void
   1324 update_certificate_downloads(time_t now)
   1325 {
   1326  int i;
   1327  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
   1328    if (consensus_waiting_for_certs[i].consensus)
   1329      authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
   1330                                    now, NULL);
   1331  }
   1332 
   1333  if (current_ns_consensus)
   1334    authority_certs_fetch_missing(current_ns_consensus, now, NULL);
   1335  if (current_md_consensus)
   1336    authority_certs_fetch_missing(current_md_consensus, now, NULL);
   1337 }
   1338 
   1339 /** Return 1 if we have a consensus but we don't have enough certificates
   1340 * to start using it yet. */
   1341 int
   1342 consensus_is_waiting_for_certs(void)
   1343 {
   1344  return consensus_waiting_for_certs[usable_consensus_flavor()].consensus
   1345    ? 1 : 0;
   1346 }
   1347 
   1348 /** Look up the currently active (depending on bootstrap status) download
   1349 * status for this consensus flavor and return a pointer to it.
   1350 */
   1351 MOCK_IMPL(download_status_t *,
   1352 networkstatus_get_dl_status_by_flavor,(consensus_flavor_t flavor))
   1353 {
   1354  download_status_t *dl = NULL;
   1355  const int we_are_bootstrapping =
   1356    networkstatus_consensus_is_bootstrapping(time(NULL));
   1357 
   1358  if ((int)flavor <= N_CONSENSUS_FLAVORS) {
   1359    dl = &((we_are_bootstrapping ?
   1360           consensus_bootstrap_dl_status : consensus_dl_status)[flavor]);
   1361  }
   1362 
   1363  return dl;
   1364 }
   1365 
   1366 /** Look up the bootstrap download status for this consensus flavor
   1367 * and return a pointer to it. */
   1368 MOCK_IMPL(download_status_t *,
   1369 networkstatus_get_dl_status_by_flavor_bootstrap,(consensus_flavor_t flavor))
   1370 {
   1371  download_status_t *dl = NULL;
   1372 
   1373  if ((int)flavor <= N_CONSENSUS_FLAVORS) {
   1374    dl = &(consensus_bootstrap_dl_status[flavor]);
   1375  }
   1376 
   1377  return dl;
   1378 }
   1379 
   1380 /** Look up the running (non-bootstrap) download status for this consensus
   1381 * flavor and return a pointer to it. */
   1382 MOCK_IMPL(download_status_t *,
   1383 networkstatus_get_dl_status_by_flavor_running,(consensus_flavor_t flavor))
   1384 {
   1385  download_status_t *dl = NULL;
   1386 
   1387  if ((int)flavor <= N_CONSENSUS_FLAVORS) {
   1388    dl = &(consensus_dl_status[flavor]);
   1389  }
   1390 
   1391  return dl;
   1392 }
   1393 
   1394 /** Return the most recent consensus that we have downloaded, or NULL if we
   1395 * don't have one. May return future or expired consensuses. */
   1396 MOCK_IMPL(networkstatus_t *,
   1397 networkstatus_get_latest_consensus,(void))
   1398 {
   1399  if (we_use_microdescriptors_for_circuits(get_options()))
   1400    return current_md_consensus;
   1401  else
   1402    return current_ns_consensus;
   1403 }
   1404 
   1405 /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
   1406 * if we don't have one. May return future or expired consensuses. */
   1407 MOCK_IMPL(networkstatus_t *,
   1408 networkstatus_get_latest_consensus_by_flavor,(consensus_flavor_t f))
   1409 {
   1410  if (f == FLAV_NS)
   1411    return current_ns_consensus;
   1412  else if (f == FLAV_MICRODESC)
   1413    return current_md_consensus;
   1414  else {
   1415    tor_assert(0);
   1416    return NULL;
   1417  }
   1418 }
   1419 
   1420 /** Return the most recent consensus that we have downloaded, or NULL if it is
   1421 * no longer live. */
   1422 MOCK_IMPL(networkstatus_t *,
   1423 networkstatus_get_live_consensus,(time_t now))
   1424 {
   1425  networkstatus_t *ns = networkstatus_get_latest_consensus();
   1426  if (ns && networkstatus_is_live(ns, now))
   1427    return ns;
   1428  else
   1429    return NULL;
   1430 }
   1431 
   1432 /** Given a consensus in <b>ns</b>, return true iff currently live and
   1433 *  unexpired. */
   1434 int
   1435 networkstatus_is_live(const networkstatus_t *ns, time_t now)
   1436 {
   1437  return (ns->valid_after <= now && now <= ns->valid_until);
   1438 }
   1439 
   1440 /** Determine if <b>consensus</b> is valid, or expired recently enough, or not
   1441 * too far in the future, so that we can still use it.
   1442 *
   1443 * Return 1 if the consensus is reasonably live, or 0 if it is too old or
   1444 * too new.
   1445 */
   1446 int
   1447 networkstatus_consensus_reasonably_live(const networkstatus_t *consensus,
   1448                                        time_t now)
   1449 {
   1450  if (BUG(!consensus))
   1451    return 0;
   1452 
   1453  return networkstatus_valid_after_is_reasonably_live(consensus->valid_after,
   1454                                                      now) &&
   1455         networkstatus_valid_until_is_reasonably_live(consensus->valid_until,
   1456                                                      now);
   1457 }
   1458 
   1459 #define REASONABLY_LIVE_TIME (24*60*60)
   1460 
   1461 /** As networkstatus_consensus_reasonably_live, but takes a valid_after
   1462 * time, and checks to see if it is in the past, or not too far in the future.
   1463 */
   1464 int
   1465 networkstatus_valid_after_is_reasonably_live(time_t valid_after,
   1466                                             time_t now)
   1467 {
   1468  return (now >= valid_after - REASONABLY_LIVE_TIME);
   1469 }
   1470 
   1471 /** As networkstatus_consensus_reasonably_live, but takes a valid_until
   1472 * time, and checks to see if it is in the future, or not too far in the past.
   1473 */
   1474 int
   1475 networkstatus_valid_until_is_reasonably_live(time_t valid_until,
   1476                                             time_t now)
   1477 {
   1478  return (now <= valid_until + REASONABLY_LIVE_TIME);
   1479 }
   1480 
   1481 /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
   1482 *  and future consensuses. */
   1483 MOCK_IMPL(networkstatus_t *,
   1484 networkstatus_get_reasonably_live_consensus,(time_t now, int flavor))
   1485 {
   1486  networkstatus_t *consensus =
   1487    networkstatus_get_latest_consensus_by_flavor(flavor);
   1488  if (consensus &&
   1489      networkstatus_consensus_reasonably_live(consensus, now))
   1490    return consensus;
   1491  else
   1492    return NULL;
   1493 }
   1494 
   1495 /** Check if we need to download a consensus during tor's bootstrap phase.
   1496 * If we have no consensus, or our consensus is unusably old, return 1.
   1497 * As soon as we have received a consensus, return 0, even if we don't have
   1498 * enough certificates to validate it.
   1499 * If a fallback directory gives us a consensus we can never get certs for,
   1500 * check_consensus_waiting_for_certs() will wait 20 minutes before failing
   1501 * the cert downloads. After that, a new consensus will be fetched from a
   1502 * randomly chosen fallback. */
   1503 MOCK_IMPL(int,
   1504 networkstatus_consensus_is_bootstrapping,(time_t now))
   1505 {
   1506  /* If we have a validated, reasonably live consensus, we're not
   1507   * bootstrapping a consensus at all. */
   1508  if (networkstatus_get_reasonably_live_consensus(
   1509                                                now,
   1510                                                usable_consensus_flavor())) {
   1511    return 0;
   1512  }
   1513 
   1514  /* If we have a consensus, but we're waiting for certificates,
   1515   * we're not waiting for a consensus download while bootstrapping. */
   1516  if (consensus_is_waiting_for_certs()) {
   1517    return 0;
   1518  }
   1519 
   1520  /* If we have no consensus, or our consensus is very old, we are
   1521   * bootstrapping, and we need to download a consensus. */
   1522  return 1;
   1523 }
   1524 
   1525 /** Check if we can use multiple directories for a consensus download.
   1526 * Only clients (including bridge relays, which act like clients) benefit
   1527 * from multiple simultaneous consensus downloads. */
   1528 int
   1529 networkstatus_consensus_can_use_multiple_directories(
   1530                                                  const or_options_t *options)
   1531 {
   1532  /* If we are a client, bridge, bridge client, or hidden service */
   1533  return !public_server_mode(options);
   1534 }
   1535 
   1536 /** Check if we can use fallback directory mirrors for a consensus download.
   1537 * If we have fallbacks and don't want to fetch from the authorities,
   1538 * we can use them. */
   1539 MOCK_IMPL(int,
   1540 networkstatus_consensus_can_use_extra_fallbacks,(const or_options_t *options))
   1541 {
   1542  /* The list length comparisons are a quick way to check if we have any
   1543   * non-authority fallback directories. If we ever have any authorities that
   1544   * aren't fallback directories, we will need to change this code. */
   1545  tor_assert(smartlist_len(router_get_fallback_dir_servers())
   1546             >= smartlist_len(router_get_trusted_dir_servers()));
   1547  /* If we don't fetch from the authorities, and we have additional mirrors,
   1548   * we can use them. */
   1549  return (!dirclient_fetches_from_authorities(options)
   1550          && (smartlist_len(router_get_fallback_dir_servers())
   1551              > smartlist_len(router_get_trusted_dir_servers())));
   1552 }
   1553 
   1554 /* Is there a consensus fetch for flavor <b>resource</b> that's far
   1555 * enough along to be attached to a circuit? */
   1556 int
   1557 networkstatus_consensus_is_already_downloading(const char *resource)
   1558 {
   1559  int answer = 0;
   1560 
   1561  /* First, get a list of all the dir conns that are fetching a consensus,
   1562   * fetching *this* consensus, and are in state "reading" (meaning they
   1563   * have already flushed their request onto the socks connection). */
   1564  smartlist_t *fetching_conns =
   1565    connection_dir_list_by_purpose_resource_and_state(
   1566      DIR_PURPOSE_FETCH_CONSENSUS, resource, DIR_CONN_STATE_CLIENT_READING);
   1567 
   1568  /* Then, walk through each conn, to see if its linked socks connection
   1569   * is in an attached state. We have to check this separately, since with
   1570   * the optimistic data feature, fetches can send their request to the
   1571   * socks connection and go into state 'reading', even before they're
   1572   * attached to any circuit. */
   1573  SMARTLIST_FOREACH_BEGIN(fetching_conns, dir_connection_t *, dirconn) {
   1574    /* Do any of these other dir conns have a linked socks conn that is
   1575     * attached to a circuit already? */
   1576    connection_t *base = TO_CONN(dirconn);
   1577    if (base->linked_conn &&
   1578        base->linked_conn->type == CONN_TYPE_AP &&
   1579        !AP_CONN_STATE_IS_UNATTACHED(base->linked_conn->state)) {
   1580      answer = 1;
   1581      break; /* stop looping, because we know the answer will be yes */
   1582    }
   1583  } SMARTLIST_FOREACH_END(dirconn);
   1584  smartlist_free(fetching_conns);
   1585 
   1586  return answer;
   1587 }
   1588 
   1589 /** Given two router status entries for the same router identity, return 1
   1590 * if the contents have changed between them. Otherwise, return 0.
   1591 * It only checks for fields that are output by control port.
   1592 * This should be kept in sync with the struct routerstatus_t
   1593 * and the printing function routerstatus_format_entry in
   1594 * NS_CONTROL_PORT mode.
   1595 **/
   1596 STATIC int
   1597 routerstatus_has_visibly_changed(const routerstatus_t *a,
   1598                                 const routerstatus_t *b)
   1599 {
   1600  tor_assert(tor_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN));
   1601 
   1602  return strcmp(a->nickname, b->nickname) ||
   1603         fast_memneq(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
   1604         !tor_addr_eq(&a->ipv4_addr, &b->ipv4_addr) ||
   1605         a->ipv4_orport != b->ipv4_orport ||
   1606         a->ipv4_dirport != b->ipv4_dirport ||
   1607         a->is_authority != b->is_authority ||
   1608         a->is_exit != b->is_exit ||
   1609         a->is_stable != b->is_stable ||
   1610         a->is_fast != b->is_fast ||
   1611         a->is_flagged_running != b->is_flagged_running ||
   1612         a->is_named != b->is_named ||
   1613         a->is_unnamed != b->is_unnamed ||
   1614         a->is_valid != b->is_valid ||
   1615         a->is_possible_guard != b->is_possible_guard ||
   1616         a->is_bad_exit != b->is_bad_exit ||
   1617         a->is_hs_dir != b->is_hs_dir ||
   1618         a->is_staledesc != b->is_staledesc ||
   1619         a->has_bandwidth != b->has_bandwidth ||
   1620         a->ipv6_orport != b->ipv6_orport ||
   1621         a->is_v2_dir != b->is_v2_dir ||
   1622         a->bandwidth_kb != b->bandwidth_kb ||
   1623         tor_addr_compare(&a->ipv6_addr, &b->ipv6_addr, CMP_EXACT);
   1624 }
   1625 
   1626 /** Notify controllers of any router status entries that changed between
   1627 * <b>old_c</b> and <b>new_c</b>. */
   1628 static void
   1629 notify_control_networkstatus_changed(const networkstatus_t *old_c,
   1630                                     const networkstatus_t *new_c)
   1631 {
   1632  smartlist_t *changed;
   1633  if (old_c == new_c)
   1634    return;
   1635 
   1636  /* tell the controller exactly which relays are still listed, as well
   1637   * as what they're listed as */
   1638  control_event_newconsensus(new_c);
   1639 
   1640  if (!control_event_is_interesting(EVENT_NS))
   1641    return;
   1642 
   1643  if (!old_c) {
   1644    control_event_networkstatus_changed(new_c->routerstatus_list);
   1645    return;
   1646  }
   1647  changed = smartlist_new();
   1648 
   1649  SMARTLIST_FOREACH_JOIN(
   1650                     old_c->routerstatus_list, const routerstatus_t *, rs_old,
   1651                     new_c->routerstatus_list, const routerstatus_t *, rs_new,
   1652                     tor_memcmp(rs_old->identity_digest,
   1653                            rs_new->identity_digest, DIGEST_LEN),
   1654                     smartlist_add(changed, (void*) rs_new)) {
   1655    if (routerstatus_has_visibly_changed(rs_old, rs_new))
   1656      smartlist_add(changed, (void*)rs_new);
   1657  } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
   1658 
   1659  control_event_networkstatus_changed(changed);
   1660  smartlist_free(changed);
   1661 }
   1662 
   1663 /* Called before the consensus changes from old_c to new_c. */
   1664 static void
   1665 notify_before_networkstatus_changes(const networkstatus_t *old_c,
   1666                                    const networkstatus_t *new_c)
   1667 {
   1668  notify_control_networkstatus_changed(old_c, new_c);
   1669  dos_consensus_has_changed(new_c);
   1670  relay_consensus_has_changed(new_c);
   1671  hs_dos_consensus_has_changed(new_c);
   1672  rep_hist_consensus_has_changed(new_c);
   1673  cpuworker_consensus_has_changed(new_c);
   1674  onion_consensus_has_changed(new_c);
   1675 }
   1676 
   1677 /* Called after a new consensus has been put in the global state. It is safe
   1678 * to use the consensus getters in this function. */
   1679 static void
   1680 notify_after_networkstatus_changes(void)
   1681 {
   1682  const networkstatus_t *c = networkstatus_get_latest_consensus();
   1683  const or_options_t *options = get_options();
   1684  const time_t now = approx_time();
   1685 
   1686  scheduler_notify_networkstatus_changed();
   1687 
   1688  /* The "current" consensus has just been set and it is a usable flavor so
   1689   * the first thing we need to do is recalculate the voting schedule static
   1690   * object so we can use the timings in there needed by some subsystems
   1691   * such as hidden service and shared random. */
   1692  dirauth_sched_recalculate_timing(options, now);
   1693  reschedule_dirvote(options);
   1694 
   1695  nodelist_set_consensus(c);
   1696 
   1697  update_consensus_networkstatus_fetch_time(now);
   1698 
   1699  /* Change the cell EWMA settings */
   1700  cmux_ewma_set_options(options, c);
   1701 
   1702  /* XXXX this call might be unnecessary here: can changing the
   1703   * current consensus really alter our view of any OR's rate limits? */
   1704  connection_or_update_token_buckets(get_connection_array(), options);
   1705 
   1706  circuit_build_times_new_consensus_params(
   1707                                 get_circuit_build_times_mutable(), c);
   1708  channelpadding_new_consensus_params(c);
   1709  circpad_new_consensus_params(c);
   1710  router_new_consensus_params(c);
   1711  congestion_control_new_consensus_params(c);
   1712  flow_control_new_consensus_params(c);
   1713  hs_service_new_consensus_params(c);
   1714  dns_new_consensus_params(c);
   1715  conflux_params_new_consensus(c);
   1716 
   1717  /* Maintenance of our L2 guard list */
   1718  maintain_layer2_guards();
   1719 }
   1720 
   1721 /** Copy all the ancillary information (like router download status and so on)
   1722 * from <b>old_c</b> to <b>new_c</b>. */
   1723 static void
   1724 networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
   1725                                      const networkstatus_t *old_c)
   1726 {
   1727  if (old_c == new_c)
   1728    return;
   1729  if (!old_c || !smartlist_len(old_c->routerstatus_list))
   1730    return;
   1731 
   1732  SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
   1733                         new_c->routerstatus_list, routerstatus_t *, rs_new,
   1734                         tor_memcmp(rs_old->identity_digest,
   1735                                rs_new->identity_digest, DIGEST_LEN),
   1736                         STMT_NIL) {
   1737    /* Okay, so we're looking at the same identity. */
   1738    rs_new->last_dir_503_at = rs_old->last_dir_503_at;
   1739 
   1740    if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
   1741                  DIGEST256_LEN)) {
   1742      /* And the same descriptor too! */
   1743      memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
   1744    }
   1745  } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
   1746 }
   1747 
   1748 #ifdef TOR_UNIT_TESTS
   1749 /**Accept a <b>flavor</b> consensus <b>c</b> without any additional
   1750 * validation. This is exclusively for unit tests.
   1751 * We copy any ancillary information from a pre-existing consensus
   1752 * and then free the current one and replace it with the newly
   1753 * provided instance. Returns -1 on unrecognized flavor, 0 otherwise.
   1754 */
   1755 int
   1756 networkstatus_set_current_consensus_from_ns(networkstatus_t *c,
   1757                                            const char *flavor)
   1758 {
   1759  int flav = networkstatus_parse_flavor_name(flavor);
   1760  switch (flav) {
   1761    case FLAV_NS:
   1762      if (current_ns_consensus) {
   1763        networkstatus_copy_old_consensus_info(c, current_ns_consensus);
   1764        networkstatus_vote_free(current_ns_consensus);
   1765      }
   1766      current_ns_consensus = c;
   1767      break;
   1768    case FLAV_MICRODESC:
   1769      if (current_md_consensus) {
   1770        networkstatus_copy_old_consensus_info(c, current_md_consensus);
   1771        networkstatus_vote_free(current_md_consensus);
   1772      }
   1773      current_md_consensus = c;
   1774      break;
   1775  }
   1776  return current_md_consensus ? 0 : -1;
   1777 }
   1778 #endif /* defined(TOR_UNIT_TESTS) */
   1779 
   1780 /**
   1781 * Helper: Read the current consensus of type <b>flavor</b> from
   1782 * <b>fname</b>.  Flags and return values are as for
   1783 * networkstatus_set_current_consensus().
   1784 **/
   1785 static int
   1786 reload_consensus_from_file(const char *fname,
   1787                           const char *flavor,
   1788                           unsigned flags,
   1789                           const char *source_dir)
   1790 {
   1791  tor_mmap_t *map = tor_mmap_file(fname);
   1792  if (!map)
   1793    return 0;
   1794 
   1795  int rv = networkstatus_set_current_consensus(map->data, map->size,
   1796                                               flavor, flags, source_dir);
   1797 #ifdef _WIN32
   1798  if (rv < 0 && tor_memstr(map->data, map->size, "\r\n")) {
   1799    log_notice(LD_GENERAL, "Looks like the above failures are probably "
   1800               "because of a CRLF in consensus file %s; falling back to "
   1801               "read_file_to_string. Nothing to worry about: this file "
   1802               "was probably saved by an earlier version of Tor.",
   1803               escaped(fname));
   1804    char *content = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
   1805    rv = networkstatus_set_current_consensus(content, strlen(content),
   1806                                             flavor, flags, source_dir);
   1807    tor_free(content);
   1808  }
   1809 #endif /* defined(_WIN32) */
   1810  if (rv < -1) {
   1811    log_warn(LD_GENERAL, "Couldn't set consensus from cache file %s",
   1812             escaped(fname));
   1813  }
   1814  tor_munmap_file(map);
   1815  return rv;
   1816 }
   1817 
   1818 /**
   1819 * Helper for handle_missing_protocol_warning: handles either the
   1820 * client case (if <b>is_client</b> is set) or the server case otherwise.
   1821 */
   1822 static void
   1823 handle_missing_protocol_warning_impl(const networkstatus_t *c,
   1824                                     int is_client)
   1825 {
   1826  char *protocol_warning = NULL;
   1827 
   1828  int should_exit = networkstatus_check_required_protocols(c,
   1829                                                   is_client,
   1830                                                   &protocol_warning);
   1831  if (protocol_warning) {
   1832    tor_log(should_exit ? LOG_ERR : LOG_WARN,
   1833            LD_GENERAL,
   1834            "%s", protocol_warning);
   1835  }
   1836  if (should_exit) {
   1837    tor_assert_nonfatal(protocol_warning);
   1838  }
   1839  tor_free(protocol_warning);
   1840  if (should_exit)
   1841    exit(1); // XXXX bad exit: should return from main.
   1842 }
   1843 
   1844 /** Called when we have received a networkstatus <b>c</b>. If there are
   1845 * any _required_ protocols we are missing, log an error and exit
   1846 * immediately. If there are any _recommended_ protocols we are missing,
   1847 * warn. */
   1848 static void
   1849 handle_missing_protocol_warning(const networkstatus_t *c,
   1850                                const or_options_t *options)
   1851 {
   1852  const int is_server = server_mode(options);
   1853  const int is_client = options_any_client_port_set(options) || !is_server;
   1854 
   1855  if (is_server)
   1856    handle_missing_protocol_warning_impl(c, 0);
   1857  if (is_client)
   1858    handle_missing_protocol_warning_impl(c, 1);
   1859 }
   1860 
   1861 /**
   1862 * Check whether we received a consensus that appears to be coming
   1863 * from the future.  Because we implicitly trust the directory
   1864 * authorities' idea of the current time, we produce a warning if we
   1865 * get an early consensus.
   1866 *
   1867 * If we got a consensus that is time stamped far in the past, that
   1868 * could simply have come from a stale cache.  Possible ways to get a
   1869 * consensus from the future can include:
   1870 *
   1871 * - enough directory authorities have wrong clocks
   1872 * - directory authorities collude to produce misleading time stamps
   1873 * - our own clock is wrong (this is by far the most likely)
   1874 *
   1875 * We neglect highly improbable scenarios that involve actual time
   1876 * travel.
   1877 */
   1878 STATIC void
   1879 warn_early_consensus(const networkstatus_t *c, const char *flavor,
   1880                     time_t now)
   1881 {
   1882  char tbuf[ISO_TIME_LEN+1];
   1883  char dbuf[64];
   1884  long delta = now - c->valid_after;
   1885  char *flavormsg = NULL;
   1886 
   1887 /** If a consensus appears more than this many seconds before it could
   1888 * possibly be a sufficiently-signed consensus, declare that our clock
   1889 * is skewed. */
   1890 #define EARLY_CONSENSUS_NOTICE_SKEW 60
   1891 
   1892  /* We assume that if a majority of dirauths have accurate clocks,
   1893   * the earliest that a dirauth with a skewed clock could possibly
   1894   * publish a sufficiently-signed consensus is (valid_after -
   1895   * dist_seconds).  Before that time, the skewed dirauth would be
   1896   * unable to obtain enough authority signatures for the consensus to
   1897   * be valid. */
   1898  if (now >= c->valid_after - c->dist_seconds - EARLY_CONSENSUS_NOTICE_SKEW)
   1899    return;
   1900 
   1901  format_iso_time(tbuf, c->valid_after);
   1902  format_time_interval(dbuf, sizeof(dbuf), delta);
   1903  log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
   1904           "consensus network status document (%s UTC).  Tor needs an "
   1905           "accurate clock to work correctly. Please check your time and "
   1906           "date settings!", dbuf, tbuf);
   1907  tor_asprintf(&flavormsg, "%s flavor consensus", flavor);
   1908  clock_skew_warning(NULL, delta, 1, LD_GENERAL, flavormsg, "CONSENSUS");
   1909  tor_free(flavormsg);
   1910 }
   1911 
   1912 /** Try to replace the current cached v3 networkstatus with the one in
   1913 * <b>consensus</b>.  If we don't have enough certificates to validate it,
   1914 * store it in consensus_waiting_for_certs and launch a certificate fetch.
   1915 *
   1916 * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
   1917 * cache.  If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
   1918 * already received, but we were waiting for certificates on it.  If flags &
   1919 * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
   1920 * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
   1921 * consensus, even if it comes from many days in the past.
   1922 *
   1923 * If source_dir is non-NULL, it's the identity digest for a directory that
   1924 * we've just successfully retrieved a consensus or certificates from, so try
   1925 * it first to fetch any missing certificates.
   1926 *
   1927 * Return 0 on success, <0 on failure.  On failure, caller should increment
   1928 * the failure count as appropriate.
   1929 *
   1930 * We return -1 for mild failures that don't need to be reported to the
   1931 * user, and -2 for more serious problems.
   1932 */
   1933 int
   1934 networkstatus_set_current_consensus(const char *consensus,
   1935                                    size_t consensus_len,
   1936                                    const char *flavor,
   1937                                    unsigned flags,
   1938                                    const char *source_dir)
   1939 {
   1940  networkstatus_t *c=NULL;
   1941  int r, result = -1;
   1942  time_t now = approx_time();
   1943  const or_options_t *options = get_options();
   1944  char *unverified_fname = NULL, *consensus_fname = NULL;
   1945  int flav = networkstatus_parse_flavor_name(flavor);
   1946  const unsigned from_cache = flags & NSSET_FROM_CACHE;
   1947  const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
   1948  const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
   1949  const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
   1950  const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
   1951  const common_digests_t *current_digests = NULL;
   1952  consensus_waiting_for_certs_t *waiting = NULL;
   1953  time_t current_valid_after = 0;
   1954  int free_consensus = 1; /* Free 'c' at the end of the function */
   1955  int checked_protocols_already = 0;
   1956 
   1957  if (flav < 0 || flav >= N_CONSENSUS_FLAVORS) {
   1958    /* XXXX we don't handle unrecognized flavors yet. */
   1959    log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
   1960    return -2;
   1961  }
   1962 
   1963  /* Make sure it's parseable. */
   1964  c = networkstatus_parse_vote_from_string(consensus,
   1965                                           consensus_len,
   1966                                           NULL, NS_TYPE_CONSENSUS);
   1967  if (!c) {
   1968    log_warn(LD_DIR, "Unable to parse networkstatus consensus");
   1969    result = -2;
   1970    goto done;
   1971  }
   1972 
   1973  if (from_cache && !was_waiting_for_certs) {
   1974    /* We previously stored this; check _now_ to make sure that version-kills
   1975     * really work. This happens even before we check signatures: we did so
   1976     * before when we stored this to disk. This does mean an attacker who can
   1977     * write to the datadir can make us not start: such an attacker could
   1978     * already harm us by replacing our guards, which would be worse. */
   1979    checked_protocols_already = 1;
   1980    handle_missing_protocol_warning(c, options);
   1981  }
   1982 
   1983  if ((int)c->flavor != flav) {
   1984    /* This wasn't the flavor we thought we were getting. */
   1985    tor_assert(c->flavor < N_CONSENSUS_FLAVORS);
   1986    if (require_flavor) {
   1987      log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
   1988               networkstatus_get_flavor_name(c->flavor), flavor);
   1989      goto done;
   1990    }
   1991    flav = c->flavor;
   1992    flavor = networkstatus_get_flavor_name(flav);
   1993  }
   1994 
   1995  if (flav != usable_consensus_flavor() &&
   1996      !we_want_to_fetch_flavor(options, flav)) {
   1997    /* This consensus is totally boring to us: we won't use it, we didn't want
   1998     * it, and we won't serve it.  Drop it. */
   1999    goto done;
   2000  }
   2001 
   2002  if (from_cache && !accept_obsolete &&
   2003      c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
   2004    log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
   2005    goto done;
   2006  }
   2007 
   2008  if (!strcmp(flavor, "ns")) {
   2009    consensus_fname = get_cachedir_fname("cached-consensus");
   2010    unverified_fname = get_cachedir_fname("unverified-consensus");
   2011    if (current_ns_consensus) {
   2012      current_digests = &current_ns_consensus->digests;
   2013      current_valid_after = current_ns_consensus->valid_after;
   2014    }
   2015  } else if (!strcmp(flavor, "microdesc")) {
   2016    consensus_fname = get_cachedir_fname("cached-microdesc-consensus");
   2017    unverified_fname = get_cachedir_fname("unverified-microdesc-consensus");
   2018    if (current_md_consensus) {
   2019      current_digests = &current_md_consensus->digests;
   2020      current_valid_after = current_md_consensus->valid_after;
   2021    }
   2022  } else {
   2023    tor_assert_nonfatal_unreached();
   2024    result = -2;
   2025    goto done;
   2026  }
   2027 
   2028  if (current_digests &&
   2029      tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
   2030    /* We already have this one. That's a failure. */
   2031    log_info(LD_DIR, "Got a %s consensus we already have", flavor);
   2032    goto done;
   2033  }
   2034 
   2035  if (current_valid_after && c->valid_after <= current_valid_after) {
   2036    /* We have a newer one.  There's no point in accepting this one,
   2037     * even if it's great. */
   2038    log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
   2039             flavor);
   2040    goto done;
   2041  }
   2042 
   2043  /* Make sure it's signed enough. */
   2044  if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
   2045    if (r == -1) {
   2046      /* Okay, so it _might_ be signed enough if we get more certificates. */
   2047      if (!was_waiting_for_certs) {
   2048        log_info(LD_DIR,
   2049                 "Not enough certificates to check networkstatus consensus");
   2050      }
   2051      if (!current_valid_after ||
   2052          c->valid_after > current_valid_after) {
   2053        waiting = &consensus_waiting_for_certs[flav];
   2054        networkstatus_vote_free(waiting->consensus);
   2055        waiting->consensus = c;
   2056        free_consensus = 0;
   2057        waiting->set_at = now;
   2058        waiting->dl_failed = 0;
   2059        if (!from_cache) {
   2060          write_bytes_to_file(unverified_fname, consensus, consensus_len, 1);
   2061        }
   2062        if (dl_certs)
   2063          authority_certs_fetch_missing(c, now, source_dir);
   2064        /* This case is not a success or a failure until we get the certs
   2065         * or fail to get the certs. */
   2066        result = 0;
   2067      } else {
   2068        /* Even if we had enough signatures, we'd never use this as the
   2069         * latest consensus. */
   2070        if (was_waiting_for_certs && from_cache)
   2071          if (unlink(unverified_fname) != 0) {
   2072            log_debug(LD_FS,
   2073                      "Failed to unlink %s: %s",
   2074                      unverified_fname, strerror(errno));
   2075          }
   2076      }
   2077      goto done;
   2078    } else {
   2079      /* This can never be signed enough:  Kill it. */
   2080      if (!was_waiting_for_certs) {
   2081        log_warn(LD_DIR, "Not enough good signatures on networkstatus "
   2082                 "consensus");
   2083        result = -2;
   2084      }
   2085      if (was_waiting_for_certs && (r < -1) && from_cache) {
   2086        if (unlink(unverified_fname) != 0) {
   2087            log_debug(LD_FS,
   2088                      "Failed to unlink %s: %s",
   2089                      unverified_fname, strerror(errno));
   2090        }
   2091      }
   2092      goto done;
   2093    }
   2094  }
   2095 
   2096  /* Signatures from the consensus are verified */
   2097  if (from_cache && was_waiting_for_certs) {
   2098    /* We check if the consensus is loaded from disk cache and that it
   2099     * it is an unverified consensus. If it is unverified, rename it to
   2100     * cached-*-consensus since it has been verified. */
   2101    log_info(LD_DIR, "Unverified consensus signatures verified.");
   2102    tor_rename(unverified_fname, consensus_fname);
   2103  }
   2104 
   2105  if (!from_cache && flav == usable_consensus_flavor())
   2106    control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
   2107 
   2108  if (!checked_protocols_already) {
   2109    handle_missing_protocol_warning(c, options);
   2110  }
   2111 
   2112  /* Are we missing any certificates at all? */
   2113  if (r != 1 && dl_certs)
   2114    authority_certs_fetch_missing(c, now, source_dir);
   2115 
   2116  const int is_usable_flavor = flav == usable_consensus_flavor();
   2117 
   2118  /* Before we switch to the new consensus, notify that we are about to change
   2119   * it using the old consensus and the new one. */
   2120  if (is_usable_flavor) {
   2121    notify_before_networkstatus_changes(networkstatus_get_latest_consensus(),
   2122                                        c);
   2123  }
   2124  if (flav == FLAV_NS) {
   2125    if (current_ns_consensus) {
   2126      networkstatus_copy_old_consensus_info(c, current_ns_consensus);
   2127      networkstatus_vote_free(current_ns_consensus);
   2128      /* Defensive programming : we should set current_ns_consensus very soon
   2129       * but we're about to call some stuff in the meantime, and leaving this
   2130       * dangling pointer around has proven to be trouble. */
   2131      current_ns_consensus = NULL;
   2132    }
   2133    current_ns_consensus = c;
   2134    free_consensus = 0; /* avoid free */
   2135  } else if (flav == FLAV_MICRODESC) {
   2136    if (current_md_consensus) {
   2137      networkstatus_copy_old_consensus_info(c, current_md_consensus);
   2138      networkstatus_vote_free(current_md_consensus);
   2139      /* more defensive programming */
   2140      current_md_consensus = NULL;
   2141    }
   2142    current_md_consensus = c;
   2143    free_consensus = 0; /* avoid free */
   2144  } else {
   2145    tor_assert_nonfatal_unreached();
   2146    result = -2;
   2147    goto done;
   2148  }
   2149 
   2150  waiting = &consensus_waiting_for_certs[flav];
   2151  if (waiting->consensus &&
   2152      waiting->consensus->valid_after <= c->valid_after) {
   2153    networkstatus_vote_free(waiting->consensus);
   2154    waiting->consensus = NULL;
   2155    waiting->set_at = 0;
   2156    waiting->dl_failed = 0;
   2157    if (unlink(unverified_fname) != 0) {
   2158      log_debug(LD_FS,
   2159                "Failed to unlink %s: %s",
   2160                unverified_fname, strerror(errno));
   2161    }
   2162  }
   2163 
   2164  if (is_usable_flavor) {
   2165    /* Notify that we just changed the consensus so the current global value
   2166     * can be looked at. */
   2167    notify_after_networkstatus_changes();
   2168  }
   2169 
   2170  /* Reset the failure count only if this consensus is actually valid. */
   2171  if (c->valid_after <= now && now <= c->valid_until) {
   2172    download_status_reset(&consensus_dl_status[flav]);
   2173  } else {
   2174    if (!from_cache)
   2175      download_status_failed(&consensus_dl_status[flav], 0);
   2176  }
   2177 
   2178  if (we_want_to_fetch_flavor(options, flav)) {
   2179    if (dir_server_mode(get_options())) {
   2180      dirserv_set_cached_consensus_networkstatus(consensus,
   2181                                                 consensus_len,
   2182                                                 flavor,
   2183                                                 &c->digests,
   2184                                                 c->digest_sha3_as_signed,
   2185                                                 c->valid_after);
   2186 
   2187      consdiffmgr_add_consensus(consensus, consensus_len, c);
   2188    }
   2189  }
   2190 
   2191  if (!from_cache) {
   2192    write_bytes_to_file(consensus_fname, consensus, consensus_len, 1);
   2193  }
   2194 
   2195  warn_early_consensus(c, flavor, now);
   2196 
   2197  /* We got a new consensus. Reset our md fetch fail cache */
   2198  microdesc_reset_outdated_dirservers_list();
   2199 
   2200  router_dir_info_changed();
   2201 
   2202  result = 0;
   2203 done:
   2204  if (free_consensus)
   2205    networkstatus_vote_free(c);
   2206  tor_free(consensus_fname);
   2207  tor_free(unverified_fname);
   2208  return result;
   2209 }
   2210 
   2211 /** Called when we have gotten more certificates: see whether we can
   2212 * now verify a pending consensus.
   2213 *
   2214 * If source_dir is non-NULL, it's the identity digest for a directory that
   2215 * we've just successfully retrieved certificates from, so try it first to
   2216 * fetch any missing certificates.
   2217 */
   2218 void
   2219 networkstatus_note_certs_arrived(const char *source_dir)
   2220 {
   2221  int i;
   2222  for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
   2223    const char *flavor_name = networkstatus_get_flavor_name(i);
   2224    consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
   2225    if (!waiting->consensus)
   2226      continue;
   2227    if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
   2228      char *fname = networkstatus_get_cache_fname(i, flavor_name, 1);
   2229      reload_consensus_from_file(fname, flavor_name,
   2230                                 NSSET_WAS_WAITING_FOR_CERTS, source_dir);
   2231      tor_free(fname);
   2232    }
   2233  }
   2234 }
   2235 
   2236 /** If the network-status list has changed since the last time we called this
   2237 * function, update the status of every routerinfo from the network-status
   2238 * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
   2239 * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
   2240 */
   2241 void
   2242 routers_update_all_from_networkstatus(time_t now, int dir_version)
   2243 {
   2244  routerlist_t *rl = router_get_routerlist();
   2245  networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,
   2246                                                                     FLAV_NS);
   2247 
   2248  if (!consensus || dir_version < 3) /* nothing more we should do */
   2249    return;
   2250 
   2251  /* calls router_dir_info_changed() when it's done -- more routers
   2252   * might be up or down now, which might affect whether there's enough
   2253   * directory info. */
   2254  routers_update_status_from_consensus_networkstatus(rl->routers, 0);
   2255 
   2256  SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
   2257                    ri->cache_info.routerlist_index = ri_sl_idx);
   2258  if (rl->old_routers)
   2259    signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
   2260 
   2261  if (!have_warned_about_old_version) {
   2262    int is_server = server_mode(get_options());
   2263    version_status_t status;
   2264    const char *recommended = is_server ?
   2265      consensus->server_versions : consensus->client_versions;
   2266    status = tor_version_is_obsolete(VERSION, recommended);
   2267 
   2268    if (status == VS_RECOMMENDED) {
   2269      log_info(LD_GENERAL, "The directory authorities say my version is ok.");
   2270    } else if (status == VS_EMPTY) {
   2271      log_info(LD_GENERAL,
   2272               "The directory authorities don't recommend any versions.");
   2273    } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
   2274      if (!have_warned_about_new_version) {
   2275        log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
   2276                   "recommended version%s, according to the directory "
   2277                   "authorities. Recommended versions are: %s",
   2278                   VERSION,
   2279                   status == VS_NEW_IN_SERIES ? " in its series" : "",
   2280                   recommended);
   2281        have_warned_about_new_version = 1;
   2282        control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
   2283                                     "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
   2284                                     VERSION, "NEW", recommended);
   2285      }
   2286    } else {
   2287      log_warn(LD_GENERAL, "Please upgrade! "
   2288               "This version of Tor (%s) is %s, according to the directory "
   2289               "authorities. Recommended versions are: %s",
   2290               VERSION,
   2291               status == VS_OLD ? "obsolete" : "not recommended",
   2292               recommended);
   2293      have_warned_about_old_version = 1;
   2294      control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
   2295           "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
   2296           VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
   2297           recommended);
   2298    }
   2299  }
   2300 }
   2301 
   2302 /** Given a list <b>routers</b> of routerinfo_t *, update each status field
   2303 * according to our current consensus networkstatus.  May re-order
   2304 * <b>routers</b>. */
   2305 void
   2306 routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
   2307                                                   int reset_failures)
   2308 {
   2309  const or_options_t *options = get_options();
   2310  int authdir = authdir_mode_v3(options);
   2311  networkstatus_t *ns = networkstatus_get_latest_consensus();
   2312  if (!ns || !smartlist_len(ns->routerstatus_list))
   2313    return;
   2314 
   2315  routers_sort_by_identity(routers);
   2316 
   2317  SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
   2318                         routers, routerinfo_t *, router,
   2319                         tor_memcmp(rs->identity_digest,
   2320                               router->cache_info.identity_digest, DIGEST_LEN),
   2321  {
   2322  }) {
   2323    /* Is it the same descriptor, or only the same identity? */
   2324    if (tor_memeq(router->cache_info.signed_descriptor_digest,
   2325                rs->descriptor_digest, DIGEST_LEN)) {
   2326      if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
   2327        router->cache_info.last_listed_as_valid_until = ns->valid_until;
   2328    }
   2329 
   2330    if (authdir) {
   2331      /* If we _are_ an authority, we should check whether this router
   2332       * is one that will cause us to need a reachability test. */
   2333      routerinfo_t *old_router =
   2334        router_get_mutable_by_digest(router->cache_info.identity_digest);
   2335      if (old_router != router) {
   2336        router->needs_retest_if_added =
   2337          dirserv_should_launch_reachability_test(router, old_router);
   2338      }
   2339    }
   2340    if (reset_failures) {
   2341      download_status_reset(&rs->dl_status);
   2342    }
   2343  } SMARTLIST_FOREACH_JOIN_END(rs, router);
   2344 
   2345  router_dir_info_changed();
   2346 }
   2347 
   2348 /** Given a list of signed_descriptor_t, update their fields (mainly, when
   2349 * they were last listed) from the most recent consensus. */
   2350 void
   2351 signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
   2352 {
   2353  networkstatus_t *ns = current_ns_consensus;
   2354  if (!ns)
   2355    return;
   2356 
   2357  if (!ns->desc_digest_map) {
   2358    char dummy[DIGEST_LEN];
   2359    /* instantiates the digest map. */
   2360    memset(dummy, 0, sizeof(dummy));
   2361    router_get_consensus_status_by_descriptor_digest(ns, dummy);
   2362  }
   2363  SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
   2364  {
   2365    const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
   2366                                       d->signed_descriptor_digest);
   2367    if (rs) {
   2368      if (ns->valid_until > d->last_listed_as_valid_until)
   2369        d->last_listed_as_valid_until = ns->valid_until;
   2370    }
   2371  });
   2372 }
   2373 
   2374 /** Generate networkstatus lines for a single routerstatus_t object, and
   2375 * return the result in a newly allocated string.  Used only by controller
   2376 * interface (for now.) */
   2377 char *
   2378 networkstatus_getinfo_helper_single(const routerstatus_t *rs)
   2379 {
   2380  return routerstatus_format_entry(rs, NULL, NULL, NS_CONTROL_PORT,
   2381                                   NULL, -1);
   2382 }
   2383 
   2384 /**
   2385 * Extract status information from <b>ri</b> and from other authority
   2386 * functions and store it in <b>rs</b>. <b>rs</b> is zeroed out before it is
   2387 * set.
   2388 *
   2389 * We assume that node-\>is_running has already been set, e.g. by
   2390 *   dirserv_set_router_is_running(ri, now);
   2391 */
   2392 void
   2393 set_routerstatus_from_routerinfo(routerstatus_t *rs,
   2394                                 const node_t *node,
   2395                                 const routerinfo_t *ri)
   2396 {
   2397  memset(rs, 0, sizeof(routerstatus_t));
   2398 
   2399  rs->is_authority =
   2400    router_digest_is_trusted_dir(ri->cache_info.identity_digest);
   2401 
   2402  /* Set by compute_performance_thresholds or from consensus */
   2403  rs->is_exit = node->is_exit;
   2404  rs->is_stable = node->is_stable;
   2405  rs->is_fast = node->is_fast;
   2406  rs->is_flagged_running = node->is_running;
   2407  rs->is_valid = node->is_valid;
   2408  rs->is_possible_guard = node->is_possible_guard;
   2409  rs->is_bad_exit = node->is_bad_exit;
   2410  rs->is_hs_dir = node->is_hs_dir;
   2411  rs->is_named = rs->is_unnamed = 0;
   2412 
   2413  memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
   2414  memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
   2415         DIGEST_LEN);
   2416  tor_addr_copy(&rs->ipv4_addr, &ri->ipv4_addr);
   2417  strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
   2418  rs->ipv4_orport = ri->ipv4_orport;
   2419  rs->ipv4_dirport = ri->ipv4_dirport;
   2420  rs->is_v2_dir = ri->supports_tunnelled_dir_requests;
   2421 
   2422  tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
   2423  rs->ipv6_orport = ri->ipv6_orport;
   2424 }
   2425 
   2426 /** Alloc and return a string describing routerstatuses for the most
   2427 * recent info of each router we know about that is of purpose
   2428 * <b>purpose_string</b>. Return NULL if unrecognized purpose.
   2429 *
   2430 * Right now this function is oriented toward listing bridges (you
   2431 * shouldn't use this for general-purpose routers, since those
   2432 * should be listed from the consensus, not from the routers list). */
   2433 char *
   2434 networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
   2435 {
   2436  const time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
   2437  char *answer;
   2438  routerlist_t *rl = router_get_routerlist();
   2439  smartlist_t *statuses;
   2440  const uint8_t purpose = router_purpose_from_string(purpose_string);
   2441  routerstatus_t rs;
   2442 
   2443  if (purpose == ROUTER_PURPOSE_UNKNOWN) {
   2444    log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
   2445             purpose_string);
   2446    return NULL;
   2447  }
   2448 
   2449  statuses = smartlist_new();
   2450  SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
   2451    node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
   2452    if (!node)
   2453      continue;
   2454    if (ri->cache_info.published_on < cutoff)
   2455      continue;
   2456    if (ri->purpose != purpose)
   2457      continue;
   2458    set_routerstatus_from_routerinfo(&rs, node, ri);
   2459    char *text = routerstatus_format_entry(
   2460      &rs, NULL, NULL, NS_CONTROL_PORT, NULL, ri->cache_info.published_on);
   2461    smartlist_add(statuses, text);
   2462  } SMARTLIST_FOREACH_END(ri);
   2463 
   2464  answer = smartlist_join_strings(statuses, "", 0, NULL);
   2465  SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
   2466  smartlist_free(statuses);
   2467  return answer;
   2468 }
   2469 
   2470 /**
   2471 * Search through a smartlist of "key=int32" strings for a value beginning
   2472 * with "param_name=". If one is found, clip it to be between min_val and
   2473 * max_val inclusive and return it.  If one is not found, return
   2474 * default_val.
   2475 ***/
   2476 static int32_t
   2477 get_net_param_from_list(smartlist_t *net_params, const char *param_name,
   2478                        int32_t default_val, int32_t min_val, int32_t max_val)
   2479 {
   2480  int32_t res = default_val;
   2481  size_t name_len = strlen(param_name);
   2482 
   2483  tor_assert(max_val > min_val);
   2484  tor_assert(min_val <= default_val);
   2485  tor_assert(max_val >= default_val);
   2486 
   2487  SMARTLIST_FOREACH_BEGIN(net_params, const char *, p) {
   2488    if (!strcmpstart(p, param_name) && p[name_len] == '=') {
   2489      int ok=0;
   2490      long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
   2491                              INT32_MAX, &ok, NULL);
   2492      if (ok) {
   2493        res = (int32_t) v;
   2494        break;
   2495      }
   2496    }
   2497  } SMARTLIST_FOREACH_END(p);
   2498 
   2499  if (res < min_val) {
   2500    log_warn(LD_DIR, "Consensus parameter %s is too small. Got %d, raising to "
   2501             "%d.", param_name, res, min_val);
   2502    res = min_val;
   2503  } else if (res > max_val) {
   2504    log_warn(LD_DIR, "Consensus parameter %s is too large. Got %d, capping to "
   2505             "%d.", param_name, res, max_val);
   2506    res = max_val;
   2507  }
   2508 
   2509  tor_assert(res >= min_val);
   2510  tor_assert(res <= max_val);
   2511  return res;
   2512 }
   2513 
   2514 /** Return the value of a integer parameter from the networkstatus <b>ns</b>
   2515 * whose name is <b>param_name</b>.  If <b>ns</b> is NULL, try loading the
   2516 * latest consensus ourselves. Return <b>default_val</b> if no latest
   2517 * consensus, or if it has no parameter called <b>param_name</b>.
   2518 * Make sure the value parsed from the consensus is at least
   2519 * <b>min_val</b> and at most <b>max_val</b> and raise/cap the parsed value
   2520 * if necessary. */
   2521 MOCK_IMPL(int32_t,
   2522 networkstatus_get_param, (const networkstatus_t *ns, const char *param_name,
   2523                        int32_t default_val, int32_t min_val, int32_t max_val))
   2524 {
   2525  if (!ns) /* if they pass in null, go find it ourselves */
   2526    ns = networkstatus_get_latest_consensus();
   2527 
   2528  if (!ns || !ns->net_params)
   2529    return default_val;
   2530 
   2531  return get_net_param_from_list(ns->net_params, param_name,
   2532                                 default_val, min_val, max_val);
   2533 }
   2534 
   2535 /**
   2536 * As networkstatus_get_param(), but check torrc_value before checking the
   2537 * consensus. If torrc_value is in-range, then return it instead of the
   2538 * value from the consensus.
   2539 */
   2540 int32_t
   2541 networkstatus_get_overridable_param(const networkstatus_t *ns,
   2542                                    int32_t torrc_value,
   2543                                    const char *param_name,
   2544                                    int32_t default_val,
   2545                                    int32_t min_val, int32_t max_val)
   2546 {
   2547  if (torrc_value >= min_val && torrc_value <= max_val)
   2548    return torrc_value;
   2549  else
   2550    return networkstatus_get_param(
   2551                         ns, param_name, default_val, min_val, max_val);
   2552 }
   2553 
   2554 /**
   2555 * Retrieve the consensus parameter that governs the
   2556 * fixed-point precision of our network balancing 'bandwidth-weights'
   2557 * (which are themselves integer consensus values). We divide them
   2558 * by this value and ensure they never exceed this value.
   2559 */
   2560 int
   2561 networkstatus_get_weight_scale_param(networkstatus_t *ns)
   2562 {
   2563  return networkstatus_get_param(ns, "bwweightscale",
   2564                                 BW_WEIGHT_SCALE,
   2565                                 BW_MIN_WEIGHT_SCALE,
   2566                                 BW_MAX_WEIGHT_SCALE);
   2567 }
   2568 
   2569 /** Return the value of a integer bw weight parameter from the networkstatus
   2570 * <b>ns</b> whose name is <b>weight_name</b>.  If <b>ns</b> is NULL, try
   2571 * loading the latest consensus ourselves. Return <b>default_val</b> if no
   2572 * latest consensus, or if it has no parameter called <b>weight_name</b>. */
   2573 int32_t
   2574 networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name,
   2575                            int32_t default_val)
   2576 {
   2577  int32_t param;
   2578  int max;
   2579  if (!ns) /* if they pass in null, go find it ourselves */
   2580    ns = networkstatus_get_latest_consensus();
   2581 
   2582  if (!ns || !ns->weight_params)
   2583    return default_val;
   2584 
   2585  max = networkstatus_get_weight_scale_param(ns);
   2586  param = get_net_param_from_list(ns->weight_params, weight_name,
   2587                                  default_val, -1,
   2588                                  BW_MAX_WEIGHT_SCALE);
   2589  if (param > max) {
   2590    log_warn(LD_DIR, "Value of consensus weight %s was too large, capping "
   2591             "to %d", weight_name, max);
   2592    param = max;
   2593  }
   2594  return param;
   2595 }
   2596 
   2597 /** Return the name of the consensus flavor <b>flav</b> as used to identify
   2598 * the flavor in directory documents. */
   2599 const char *
   2600 networkstatus_get_flavor_name(consensus_flavor_t flav)
   2601 {
   2602  switch (flav) {
   2603    case FLAV_NS:
   2604      return "ns";
   2605    case FLAV_MICRODESC:
   2606      return "microdesc";
   2607    default:
   2608      tor_fragile_assert();
   2609      return "??";
   2610  }
   2611 }
   2612 
   2613 /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
   2614 * or -1 if the flavor is not recognized. */
   2615 int
   2616 networkstatus_parse_flavor_name(const char *flavname)
   2617 {
   2618  if (!strcmp(flavname, "ns"))
   2619    return FLAV_NS;
   2620  else if (!strcmp(flavname, "microdesc"))
   2621    return FLAV_MICRODESC;
   2622  else
   2623    return -1;
   2624 }
   2625 
   2626 /** Return 0 if this routerstatus is obsolete, too new, isn't
   2627 * running, or otherwise not a descriptor that we would make any
   2628 * use of even if we had it. Else return 1. */
   2629 int
   2630 client_would_use_router(const routerstatus_t *rs, time_t now)
   2631 {
   2632  (void) now;
   2633  if (!rs->is_flagged_running) {
   2634    /* If we had this router descriptor, we wouldn't even bother using it.
   2635     * (Fetching and storing depends on by we_want_to_fetch_flavor().) */
   2636    return 0;
   2637  }
   2638  if (!routerstatus_version_supports_extend2_cells(rs, 1)) {
   2639    /* We'd ignore it because it doesn't support EXTEND2 cells.
   2640     * If we don't know the version, download the descriptor so we can
   2641     * check if it supports EXTEND2 cells and ntor. */
   2642    return 0;
   2643  }
   2644  return 1;
   2645 }
   2646 
   2647 /** If <b>question</b> is a string beginning with "ns/" in a format the
   2648 * control interface expects for a GETINFO question, set *<b>answer</b> to a
   2649 * newly-allocated string containing networkstatus lines for the appropriate
   2650 * ORs.  Return 0 on success, -1 on unrecognized question format. */
   2651 int
   2652 getinfo_helper_networkstatus(control_connection_t *conn,
   2653                             const char *question, char **answer,
   2654                             const char **errmsg)
   2655 {
   2656  const routerstatus_t *status;
   2657  (void) conn;
   2658 
   2659  if (!networkstatus_get_latest_consensus()) {
   2660    *answer = tor_strdup("");
   2661    return 0;
   2662  }
   2663 
   2664  if (!strcmp(question, "ns/all")) {
   2665    smartlist_t *statuses = smartlist_new();
   2666    SMARTLIST_FOREACH(networkstatus_get_latest_consensus()->routerstatus_list,
   2667                      const routerstatus_t *, rs,
   2668      {
   2669        smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
   2670      });
   2671    *answer = smartlist_join_strings(statuses, "", 0, NULL);
   2672    SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
   2673    smartlist_free(statuses);
   2674    return 0;
   2675  } else if (!strcmpstart(question, "ns/id/")) {
   2676    char d[DIGEST_LEN];
   2677    const char *q = question + 6;
   2678    if (*q == '$')
   2679      ++q;
   2680 
   2681    if (base16_decode(d, DIGEST_LEN, q, strlen(q)) != DIGEST_LEN) {
   2682      *errmsg = "Data not decodeable as hex";
   2683      return -1;
   2684    }
   2685    status = router_get_consensus_status_by_id(d);
   2686  } else if (!strcmpstart(question, "ns/name/")) {
   2687    const node_t *n = node_get_by_nickname(question+8, 0);
   2688    status = n ? n->rs : NULL;
   2689  } else if (!strcmpstart(question, "ns/purpose/")) {
   2690    *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
   2691    return *answer ? 0 : -1;
   2692  } else if (!strcmp(question, "consensus/packages")) {
   2693    const networkstatus_t *ns = networkstatus_get_latest_consensus();
   2694    if (ns && ns->package_lines)
   2695      *answer = smartlist_join_strings(ns->package_lines, "\n", 0, NULL);
   2696    else
   2697      *errmsg = "No consensus available";
   2698    return *answer ? 0 : -1;
   2699  } else if (!strcmp(question, "consensus/valid-after") ||
   2700             !strcmp(question, "consensus/fresh-until") ||
   2701             !strcmp(question, "consensus/valid-until")) {
   2702    const networkstatus_t *ns = networkstatus_get_latest_consensus();
   2703    if (ns) {
   2704      time_t t;
   2705      if (!strcmp(question, "consensus/valid-after"))
   2706        t = ns->valid_after;
   2707      else if (!strcmp(question, "consensus/fresh-until"))
   2708        t = ns->fresh_until;
   2709      else
   2710        t = ns->valid_until;
   2711 
   2712      char tbuf[ISO_TIME_LEN+1];
   2713      format_iso_time(tbuf, t);
   2714      *answer = tor_strdup(tbuf);
   2715    } else {
   2716      *errmsg = "No consensus available";
   2717    }
   2718    return *answer ? 0 : -1;
   2719  } else {
   2720    return 0;
   2721  }
   2722 
   2723  if (status)
   2724    *answer = networkstatus_getinfo_helper_single(status);
   2725  return 0;
   2726 }
   2727 
   2728 /** Check whether the networkstatus <b>ns</b> lists any protocol
   2729 * versions as "required" or "recommended" that we do not support.  If
   2730 * so, set *<b>warning_out</b> to a newly allocated string describing
   2731 * the problem.
   2732 *
   2733 * Return 1 if we should exit, 0 if we should not. */
   2734 int
   2735 networkstatus_check_required_protocols(const networkstatus_t *ns,
   2736                                       int client_mode,
   2737                                       char **warning_out)
   2738 {
   2739  const char *func = client_mode ? "client" : "relay";
   2740  const char *required, *recommended;
   2741  char *missing = NULL;
   2742 
   2743  const bool consensus_postdates_this_release =
   2744    ns->valid_after >= tor_get_approx_release_date();
   2745 
   2746  if (! consensus_postdates_this_release) {
   2747    // We can't meaningfully warn about this case: This consensus is from
   2748    // before we were released, so whatever is says about required or
   2749    // recommended versions may no longer be true.
   2750    return 0;
   2751  }
   2752 
   2753  tor_assert(warning_out);
   2754 
   2755  if (client_mode) {
   2756    required = ns->required_client_protocols;
   2757    recommended = ns->recommended_client_protocols;
   2758  } else {
   2759    required = ns->required_relay_protocols;
   2760    recommended = ns->recommended_relay_protocols;
   2761  }
   2762 
   2763  if (!protover_all_supported(required, &missing)) {
   2764    tor_asprintf(warning_out, "At least one protocol listed as required in "
   2765                 "the consensus is not supported by this version of Tor. "
   2766                 "You should upgrade. This version of Tor will not work as a "
   2767                 "%s on the Tor network. The missing protocols are: %s",
   2768                 func, missing);
   2769    tor_free(missing);
   2770    return 1;
   2771  }
   2772 
   2773  if (! protover_all_supported(recommended, &missing)) {
   2774    tor_asprintf(warning_out, "At least one protocol listed as recommended in "
   2775                 "the consensus is not supported by this version of Tor. "
   2776                 "You should upgrade. This version of Tor will eventually "
   2777                 "stop working as a %s on the Tor network. The missing "
   2778                 "protocols are: %s",
   2779                 func, missing);
   2780    tor_free(missing);
   2781  }
   2782 
   2783  tor_assert_nonfatal(missing == NULL);
   2784 
   2785  return 0;
   2786 }
   2787 
   2788 /** Free all storage held locally in this module. */
   2789 void
   2790 networkstatus_free_all(void)
   2791 {
   2792  int i;
   2793  networkstatus_vote_free(current_ns_consensus);
   2794  networkstatus_vote_free(current_md_consensus);
   2795  current_md_consensus = current_ns_consensus = NULL;
   2796 
   2797  for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
   2798    consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
   2799    if (waiting->consensus) {
   2800      networkstatus_vote_free(waiting->consensus);
   2801      waiting->consensus = NULL;
   2802    }
   2803  }
   2804 }
   2805 
   2806 /** Return the start of the next interval of size <b>interval</b> (in
   2807 * seconds) after <b>now</b>, plus <b>offset</b>. Midnight always
   2808 * starts a fresh interval, and if the last interval of a day would be
   2809 * truncated to less than half its size, it is rolled into the
   2810 * previous interval. */
   2811 time_t
   2812 voting_sched_get_start_of_interval_after(time_t now, int interval,
   2813                                           int offset)
   2814 {
   2815  struct tm tm;
   2816  time_t midnight_today=0;
   2817  time_t midnight_tomorrow;
   2818  time_t next;
   2819 
   2820  tor_gmtime_r(&now, &tm);
   2821  tm.tm_hour = 0;
   2822  tm.tm_min = 0;
   2823  tm.tm_sec = 0;
   2824 
   2825  if (tor_timegm(&tm, &midnight_today) < 0) {
   2826    // LCOV_EXCL_START
   2827    log_warn(LD_BUG, "Ran into an invalid time when trying to find midnight.");
   2828    // LCOV_EXCL_STOP
   2829  }
   2830  midnight_tomorrow = midnight_today + (24*60*60);
   2831 
   2832  next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
   2833 
   2834  /* Intervals never cross midnight. */
   2835  if (next > midnight_tomorrow)
   2836    next = midnight_tomorrow;
   2837 
   2838  /* If the interval would only last half as long as it's supposed to, then
   2839   * skip over to the next day. */
   2840  if (next + interval/2 > midnight_tomorrow)
   2841    next = midnight_tomorrow;
   2842 
   2843  next += offset;
   2844  if (next - interval > now)
   2845    next -= interval;
   2846 
   2847  return next;
   2848 }