tor

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

nodelist.c (97948B)


      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 nodelist.c
      9 *
     10 * \brief Structures and functions for tracking what we know about the routers
     11 *   on the Tor network, and correlating information from networkstatus,
     12 *   routerinfo, and microdescs.
     13 *
     14 * The key structure here is node_t: that's the canonical way to refer
     15 * to a Tor relay that we might want to build a circuit through.  Every
     16 * node_t has either a routerinfo_t, or a routerstatus_t from the current
     17 * networkstatus consensus.  If it has a routerstatus_t, it will also
     18 * need to have a microdesc_t before you can use it for circuits.
     19 *
     20 * The nodelist_t is a global singleton that maps identities to node_t
     21 * objects.  Access them with the node_get_*() functions.  The nodelist_t
     22 * is maintained by calls throughout the codebase
     23 *
     24 * Generally, other code should not have to reach inside a node_t to
     25 * see what information it has.  Instead, you should call one of the
     26 * many accessor functions that works on a generic node_t.  If there
     27 * isn't one that does what you need, it's better to make such a function,
     28 * and then use it.
     29 *
     30 * For historical reasons, some of the functions that select a node_t
     31 * from the list of all usable node_t objects are in the routerlist.c
     32 * module, since they originally selected a routerinfo_t. (TODO: They
     33 * should move!)
     34 *
     35 * (TODO: Perhaps someday we should abstract the remaining ways of
     36 * talking about a relay to also be node_t instances. Those would be
     37 * routerstatus_t as used for directory requests, and dir_server_t as
     38 * used for authorities and fallback directories.)
     39 */
     40 
     41 #define NODELIST_PRIVATE
     42 
     43 #include "core/or/or.h"
     44 #include "app/config/config.h"
     45 #include "core/mainloop/mainloop.h"
     46 #include "core/mainloop/netstatus.h"
     47 #include "core/or/address_set.h"
     48 #include "core/or/policies.h"
     49 #include "core/or/protover.h"
     50 #include "feature/client/bridges.h"
     51 #include "feature/client/entrynodes.h"
     52 #include "feature/control/control_events.h"
     53 #include "feature/dirauth/process_descs.h"
     54 #include "feature/dirclient/dirclient_modes.h"
     55 #include "feature/hs/hs_client.h"
     56 #include "feature/hs/hs_common.h"
     57 #include "feature/nodelist/describe.h"
     58 #include "feature/nodelist/dirlist.h"
     59 #include "feature/nodelist/microdesc.h"
     60 #include "feature/nodelist/networkstatus.h"
     61 #include "feature/nodelist/node_select.h"
     62 #include "feature/nodelist/nodefamily.h"
     63 #include "feature/nodelist/nodelist.h"
     64 #include "feature/nodelist/routerlist.h"
     65 #include "feature/nodelist/routerset.h"
     66 #include "feature/nodelist/torcert.h"
     67 #include "lib/encoding/binascii.h"
     68 #include "lib/err/backtrace.h"
     69 #include "lib/geoip/geoip.h"
     70 #include "lib/net/address.h"
     71 
     72 #include <string.h>
     73 
     74 #include "feature/dirauth/authmode.h"
     75 
     76 #include "feature/dirclient/dir_server_st.h"
     77 #include "feature/nodelist/microdesc_st.h"
     78 #include "feature/nodelist/networkstatus_st.h"
     79 #include "feature/nodelist/node_st.h"
     80 #include "feature/nodelist/routerinfo_st.h"
     81 #include "feature/nodelist/routerlist_st.h"
     82 #include "feature/nodelist/routerstatus_st.h"
     83 
     84 static void nodelist_drop_node(node_t *node, int remove_from_ht);
     85 #define node_free(val) \
     86  FREE_AND_NULL(node_t, node_free_, (val))
     87 static void node_free_(node_t *node);
     88 
     89 /** count_usable_descriptors counts descriptors with these flag(s)
     90 */
     91 typedef enum {
     92  /* All descriptors regardless of flags or exit policies */
     93  USABLE_DESCRIPTOR_ALL         = 0U,
     94  /* Only count descriptors with an exit policy that allows at least one port
     95   */
     96  USABLE_DESCRIPTOR_EXIT_POLICY = 1U << 0,
     97  /* Only count descriptors for relays that have the exit flag in the
     98   * consensus */
     99  USABLE_DESCRIPTOR_EXIT_FLAG   = 1U << 1,
    100  /* Only count descriptors for relays that have the policy and the flag */
    101  USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG = (USABLE_DESCRIPTOR_EXIT_POLICY |
    102                                            USABLE_DESCRIPTOR_EXIT_FLAG)
    103 } usable_descriptor_t;
    104 static void count_usable_descriptors(int *num_present,
    105                                     int *num_usable,
    106                                     smartlist_t *descs_out,
    107                                     const networkstatus_t *consensus,
    108                                     time_t now,
    109                                     routerset_t *in_set,
    110                                     usable_descriptor_t exit_only);
    111 static void update_router_have_minimum_dir_info(void);
    112 static double get_frac_paths_needed_for_circs(const or_options_t *options,
    113                                              const networkstatus_t *ns);
    114 static void node_add_to_address_set(const node_t *node);
    115 
    116 /** A nodelist_t holds a node_t object for every router we're "willing to use
    117 * for something".  Specifically, it should hold a node_t for every node that
    118 * is currently in the routerlist, or currently in the consensus we're using.
    119 */
    120 typedef struct nodelist_t {
    121  /* A list of all the nodes. */
    122  smartlist_t *nodes;
    123  /* Hash table to map from node ID digest to node. */
    124  HT_HEAD(nodelist_map, node_t) nodes_by_id;
    125  /* Hash table to map from node Ed25519 ID to node.
    126   *
    127   * Whenever a node's routerinfo or microdescriptor is about to change,
    128   * you should remove it from this map with node_remove_from_ed25519_map().
    129   * Whenever a node's routerinfo or microdescriptor has just changed,
    130   * you should add it to this map with node_add_to_ed25519_map().
    131   */
    132  HT_HEAD(nodelist_ed_map, node_t) nodes_by_ed_id;
    133 
    134  /* Set of addresses that belong to nodes we believe in. */
    135  address_set_t *node_addrs;
    136 
    137  /* Set of addresses + port that belong to nodes we know and that we don't
    138   * allow network re-entry towards them. */
    139  digestmap_t *reentry_set;
    140 
    141  /* The valid-after time of the last live consensus that initialized the
    142   * nodelist.  We use this to detect outdated nodelists that need to be
    143   * rebuilt using a newer consensus. */
    144  time_t live_consensus_valid_after;
    145 } nodelist_t;
    146 
    147 static inline unsigned int
    148 node_id_hash(const node_t *node)
    149 {
    150  return (unsigned) siphash24g(node->identity, DIGEST_LEN);
    151 }
    152 
    153 static inline unsigned int
    154 node_id_eq(const node_t *node1, const node_t *node2)
    155 {
    156  return tor_memeq(node1->identity, node2->identity, DIGEST_LEN);
    157 }
    158 
    159 HT_PROTOTYPE(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq);
    160 HT_GENERATE2(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq,
    161             0.6, tor_reallocarray_, tor_free_);
    162 
    163 static inline unsigned int
    164 node_ed_id_hash(const node_t *node)
    165 {
    166  return (unsigned) siphash24g(node->ed25519_id.pubkey, ED25519_PUBKEY_LEN);
    167 }
    168 
    169 static inline unsigned int
    170 node_ed_id_eq(const node_t *node1, const node_t *node2)
    171 {
    172  return ed25519_pubkey_eq(&node1->ed25519_id, &node2->ed25519_id);
    173 }
    174 
    175 HT_PROTOTYPE(nodelist_ed_map, node_t, ed_ht_ent, node_ed_id_hash,
    176             node_ed_id_eq);
    177 HT_GENERATE2(nodelist_ed_map, node_t, ed_ht_ent, node_ed_id_hash,
    178             node_ed_id_eq, 0.6, tor_reallocarray_, tor_free_);
    179 
    180 /** The global nodelist. */
    181 static nodelist_t *the_nodelist=NULL;
    182 
    183 /** Create an empty nodelist if we haven't done so already. */
    184 static void
    185 init_nodelist(void)
    186 {
    187  if (PREDICT_UNLIKELY(the_nodelist == NULL)) {
    188    the_nodelist = tor_malloc_zero(sizeof(nodelist_t));
    189    HT_INIT(nodelist_map, &the_nodelist->nodes_by_id);
    190    HT_INIT(nodelist_ed_map, &the_nodelist->nodes_by_ed_id);
    191    the_nodelist->nodes = smartlist_new();
    192  }
    193 }
    194 
    195 /** As node_get_by_id, but returns a non-const pointer */
    196 MOCK_IMPL(node_t *,
    197 node_get_mutable_by_id,(const char *identity_digest))
    198 {
    199  node_t search, *node;
    200  if (PREDICT_UNLIKELY(the_nodelist == NULL))
    201    return NULL;
    202 
    203  memcpy(&search.identity, identity_digest, DIGEST_LEN);
    204  node = HT_FIND(nodelist_map, &the_nodelist->nodes_by_id, &search);
    205  return node;
    206 }
    207 
    208 /** As node_get_by_ed25519_id, but returns a non-const pointer */
    209 node_t *
    210 node_get_mutable_by_ed25519_id(const ed25519_public_key_t *ed_id)
    211 {
    212  node_t search, *node;
    213  if (PREDICT_UNLIKELY(the_nodelist == NULL))
    214    return NULL;
    215  if (BUG(ed_id == NULL) || BUG(ed25519_public_key_is_zero(ed_id)))
    216    return NULL;
    217 
    218  memcpy(&search.ed25519_id, ed_id, sizeof(search.ed25519_id));
    219  node = HT_FIND(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, &search);
    220  return node;
    221 }
    222 
    223 /** Return the node_t whose identity is <b>identity_digest</b>, or NULL
    224 * if no such node exists. */
    225 MOCK_IMPL(const node_t *,
    226 node_get_by_id,(const char *identity_digest))
    227 {
    228  return node_get_mutable_by_id(identity_digest);
    229 }
    230 
    231 /** Return the node_t whose ed25519 identity is <b>ed_id</b>, or NULL
    232 * if no such node exists. */
    233 MOCK_IMPL(const node_t *,
    234 node_get_by_ed25519_id,(const ed25519_public_key_t *ed_id))
    235 {
    236  return node_get_mutable_by_ed25519_id(ed_id);
    237 }
    238 
    239 /** Internal: return the node_t whose identity_digest is
    240 * <b>identity_digest</b>.  If none exists, create a new one, add it to the
    241 * nodelist, and return it.
    242 *
    243 * Requires that the nodelist be initialized.
    244 */
    245 static node_t *
    246 node_get_or_create(const char *identity_digest)
    247 {
    248  node_t *node;
    249 
    250  if ((node = node_get_mutable_by_id(identity_digest)))
    251    return node;
    252 
    253  node = tor_malloc_zero(sizeof(node_t));
    254  memcpy(node->identity, identity_digest, DIGEST_LEN);
    255  HT_INSERT(nodelist_map, &the_nodelist->nodes_by_id, node);
    256 
    257  smartlist_add(the_nodelist->nodes, node);
    258  node->nodelist_idx = smartlist_len(the_nodelist->nodes) - 1;
    259 
    260  node->country = -1;
    261 
    262  return node;
    263 }
    264 
    265 /** Remove <b>node</b> from the ed25519 map (if it present), and
    266 * set its ed25519_id field to zero. */
    267 static int
    268 node_remove_from_ed25519_map(node_t *node)
    269 {
    270  tor_assert(the_nodelist);
    271  tor_assert(node);
    272 
    273  if (ed25519_public_key_is_zero(&node->ed25519_id)) {
    274    return 0;
    275  }
    276 
    277  int rv = 0;
    278  node_t *search =
    279    HT_FIND(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
    280  if (BUG(search != node)) {
    281    goto clear_and_return;
    282  }
    283 
    284  search = HT_REMOVE(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
    285  tor_assert(search == node);
    286  rv = 1;
    287 
    288 clear_and_return:
    289  memset(&node->ed25519_id, 0, sizeof(node->ed25519_id));
    290  return rv;
    291 }
    292 
    293 /** Helper function to log details of duplicated ed2559_ids */
    294 static void
    295 node_log_dup_ed_id(const node_t *old, const node_t *node, const char *ed_id)
    296 {
    297  char *s;
    298  char *olddesc = tor_strdup(node_describe(old));
    299 
    300  tor_asprintf(&s, "Reused ed25519_id %s: old %s new %s", ed_id,
    301               olddesc, node_describe(node));
    302  log_backtrace(LOG_NOTICE, LD_DIR, s);
    303  tor_free(olddesc);
    304  tor_free(s);
    305 }
    306 
    307 /** If <b>node</b> has an ed25519 id, and it is not already in the ed25519 id
    308 * map, set its ed25519_id field, and add it to the ed25519 map.
    309 */
    310 static int
    311 node_add_to_ed25519_map(node_t *node)
    312 {
    313  tor_assert(the_nodelist);
    314  tor_assert(node);
    315 
    316  if (! ed25519_public_key_is_zero(&node->ed25519_id)) {
    317    return 0;
    318  }
    319 
    320  const ed25519_public_key_t *key = node_get_ed25519_id(node);
    321  if (!key) {
    322    return 0;
    323  }
    324 
    325  node_t *old;
    326  memcpy(&node->ed25519_id, key, sizeof(node->ed25519_id));
    327  old = HT_FIND(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
    328  if (old) {
    329    char ed_id[BASE32_BUFSIZE(sizeof(key->pubkey))];
    330 
    331    base32_encode(ed_id, sizeof(ed_id), (const char *)key->pubkey,
    332                  sizeof(key->pubkey));
    333    if (BUG(old == node)) {
    334      /* Actual bug: all callers of this function call
    335       * node_remove_from_ed25519_map first. */
    336      log_err(LD_BUG,
    337              "Unexpectedly found deleted node with ed25519_id %s", ed_id);
    338    } else {
    339      /* Distinct nodes sharing a ed25519 id, possibly due to relay
    340       * misconfiguration.  The key pinning might not catch this,
    341       * possibly due to downloading a missing descriptor during
    342       * consensus voting. */
    343      node_log_dup_ed_id(old, node, ed_id);
    344      memset(&node->ed25519_id, 0, sizeof(node->ed25519_id));
    345    }
    346    return 0;
    347  }
    348 
    349  HT_INSERT(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
    350  return 1;
    351 }
    352 
    353 /* For a given <b>node</b> for the consensus <b>ns</b>, set the hsdir index
    354 * for the node, both current and next if possible. This can only fails if the
    355 * node_t ed25519 identity key can't be found which would be a bug. */
    356 STATIC void
    357 node_set_hsdir_index(node_t *node, const networkstatus_t *ns)
    358 {
    359  time_t now = approx_time();
    360  const ed25519_public_key_t *node_identity_pk;
    361  uint8_t *fetch_srv = NULL, *store_first_srv = NULL, *store_second_srv = NULL;
    362  uint64_t next_time_period_num, current_time_period_num;
    363  uint64_t fetch_tp, store_first_tp, store_second_tp;
    364 
    365  tor_assert(node);
    366  tor_assert(ns);
    367 
    368  if (!networkstatus_consensus_reasonably_live(ns, now)) {
    369    static struct ratelim_t live_consensus_ratelim = RATELIM_INIT(30 * 60);
    370    log_fn_ratelim(&live_consensus_ratelim, LOG_INFO, LD_GENERAL,
    371                   "Not setting hsdir index with a non-live consensus.");
    372    goto done;
    373  }
    374 
    375  node_identity_pk = node_get_ed25519_id(node);
    376  if (node_identity_pk == NULL) {
    377    log_debug(LD_GENERAL, "ed25519 identity public key not found when "
    378                          "trying to build the hsdir indexes for node %s",
    379              node_describe(node));
    380    goto done;
    381  }
    382 
    383  /* Get the current and next time period number. */
    384  current_time_period_num = hs_get_time_period_num(0);
    385  next_time_period_num = hs_get_next_time_period_num(0);
    386 
    387  /* We always use the current time period for fetching descs */
    388  fetch_tp = current_time_period_num;
    389 
    390  /* Now extract the needed SRVs and time periods for building hsdir indices */
    391  if (hs_in_period_between_tp_and_srv(ns, now)) {
    392    fetch_srv = hs_get_current_srv(fetch_tp, ns);
    393 
    394    store_first_tp = hs_get_previous_time_period_num(0);
    395    store_second_tp = current_time_period_num;
    396  } else {
    397    fetch_srv = hs_get_previous_srv(fetch_tp, ns);
    398 
    399    store_first_tp = current_time_period_num;
    400    store_second_tp = next_time_period_num;
    401  }
    402 
    403  /* We always use the old SRV for storing the first descriptor and the latest
    404   * SRV for storing the second descriptor */
    405  store_first_srv = hs_get_previous_srv(store_first_tp, ns);
    406  store_second_srv = hs_get_current_srv(store_second_tp, ns);
    407 
    408  /* Build the fetch index. */
    409  hs_build_hsdir_index(node_identity_pk, fetch_srv, fetch_tp,
    410                       node->hsdir_index.fetch);
    411 
    412  /* If we are in the time segment between SRV#N and TP#N, the fetch index is
    413     the same as the first store index */
    414  if (!hs_in_period_between_tp_and_srv(ns, now)) {
    415    memcpy(node->hsdir_index.store_first, node->hsdir_index.fetch,
    416           sizeof(node->hsdir_index.store_first));
    417  } else {
    418    hs_build_hsdir_index(node_identity_pk, store_first_srv, store_first_tp,
    419                         node->hsdir_index.store_first);
    420  }
    421 
    422  /* If we are in the time segment between TP#N and SRV#N+1, the fetch index is
    423     the same as the second store index */
    424  if (hs_in_period_between_tp_and_srv(ns, now)) {
    425    memcpy(node->hsdir_index.store_second, node->hsdir_index.fetch,
    426           sizeof(node->hsdir_index.store_second));
    427  } else {
    428    hs_build_hsdir_index(node_identity_pk, store_second_srv, store_second_tp,
    429                         node->hsdir_index.store_second);
    430  }
    431 
    432 done:
    433  tor_free(fetch_srv);
    434  tor_free(store_first_srv);
    435  tor_free(store_second_srv);
    436  return;
    437 }
    438 
    439 /** Called when a node's address changes. */
    440 static void
    441 node_addrs_changed(node_t *node)
    442 {
    443  node->last_reachable = node->last_reachable6 = 0;
    444  node->country = -1;
    445 }
    446 
    447 /** Add all address information about <b>node</b> to the current address
    448 * set (if there is one).
    449 */
    450 static void
    451 node_add_to_address_set(const node_t *node)
    452 {
    453  if (!the_nodelist ||
    454      !the_nodelist->node_addrs || !the_nodelist->reentry_set)
    455    return;
    456 
    457  /* These various address sources can be redundant, but it's likely faster to
    458   * add them all than to compare them all for equality.
    459   *
    460   * For relays, we only add the ORPort in the addr+port set since we want to
    461   * allow re-entry into the network to the DirPort so the self reachability
    462   * test succeeds and thus the 0 value for the DirPort. */
    463 
    464  if (node->rs) {
    465    if (!tor_addr_is_null(&node->rs->ipv4_addr))
    466      nodelist_add_addr_to_address_set(&node->rs->ipv4_addr,
    467                                       node->rs->ipv4_orport, 0);
    468    if (!tor_addr_is_null(&node->rs->ipv6_addr))
    469      nodelist_add_addr_to_address_set(&node->rs->ipv6_addr,
    470                                       node->rs->ipv6_orport, 0);
    471  }
    472  if (node->ri) {
    473    if (!tor_addr_is_null(&node->ri->ipv4_addr))
    474      nodelist_add_addr_to_address_set(&node->ri->ipv4_addr,
    475                                       node->ri->ipv4_orport, 0);
    476    if (!tor_addr_is_null(&node->ri->ipv6_addr))
    477      nodelist_add_addr_to_address_set(&node->ri->ipv6_addr,
    478                                       node->ri->ipv6_orport, 0);
    479  }
    480  if (node->md) {
    481    if (!tor_addr_is_null(&node->md->ipv6_addr))
    482      nodelist_add_addr_to_address_set(&node->md->ipv6_addr,
    483                                       node->md->ipv6_orport, 0);
    484  }
    485 }
    486 
    487 /** Build a construction for the reentry set consisting of an address and port
    488 * pair.
    489 *
    490 * If the given address is _not_ AF_INET or AF_INET6, then the item is an
    491 * array of 0s.
    492 *
    493 * Return a pointer to a static buffer containing the item. Next call to this
    494 * function invalidates its previous content. */
    495 static char *
    496 build_addr_port_item(const tor_addr_t *addr, const uint16_t port)
    497 {
    498  /* At most 16 bytes are put in this (IPv6) and then 2 bytes for the port
    499   * which is within the maximum of 20 bytes (DIGEST_LEN). */
    500  static char data[DIGEST_LEN];
    501 
    502  memset(data, 0, sizeof(data));
    503  switch (tor_addr_family(addr)) {
    504  case AF_INET:
    505    memcpy(data, &addr->addr.in_addr.s_addr, 4);
    506    break;
    507  case AF_INET6:
    508    memcpy(data, &addr->addr.in6_addr.s6_addr, 16);
    509    break;
    510  case AF_UNSPEC:
    511    /* Leave the 0. */
    512    break;
    513  default:
    514    /* LCOV_EXCL_START */
    515    tor_fragile_assert();
    516    /* LCOV_EXCL_STOP */
    517  }
    518 
    519  memcpy(data + 16, &port, sizeof(port));
    520  return data;
    521 }
    522 
    523 /** Add the given address into the nodelist address set. */
    524 void
    525 nodelist_add_addr_to_address_set(const tor_addr_t *addr,
    526                                 uint16_t or_port, uint16_t dir_port)
    527 {
    528  if (BUG(!addr) || tor_addr_is_null(addr) ||
    529      (!tor_addr_is_v4(addr) && !tor_addr_is_v6(addr)) ||
    530      !the_nodelist || !the_nodelist->node_addrs ||
    531      !the_nodelist->reentry_set) {
    532    return;
    533  }
    534  address_set_add(the_nodelist->node_addrs, addr);
    535  if (or_port != 0) {
    536    digestmap_set(the_nodelist->reentry_set,
    537                  build_addr_port_item(addr, or_port), (void*) 1);
    538  }
    539  if (dir_port != 0) {
    540    digestmap_set(the_nodelist->reentry_set,
    541                  build_addr_port_item(addr, dir_port), (void*) 1);
    542  }
    543 }
    544 
    545 /** Return true if <b>addr</b> is the address of some node in the nodelist.
    546 * If not, probably return false. */
    547 int
    548 nodelist_probably_contains_address(const tor_addr_t *addr)
    549 {
    550  if (BUG(!addr))
    551    return 0;
    552 
    553  if (!the_nodelist || !the_nodelist->node_addrs)
    554    return 0;
    555 
    556  return address_set_probably_contains(the_nodelist->node_addrs, addr);
    557 }
    558 
    559 /** Return true if <b>addr</b> is the address of some node in the nodelist and
    560 * corresponds also to the given port. If not, probably return false. */
    561 bool
    562 nodelist_reentry_contains(const tor_addr_t *addr, uint16_t port)
    563 {
    564  if (BUG(!addr) || BUG(!port))
    565    return false;
    566 
    567  if (!the_nodelist || !the_nodelist->reentry_set)
    568    return false;
    569 
    570  return digestmap_get(the_nodelist->reentry_set,
    571                       build_addr_port_item(addr, port)) != NULL;
    572 }
    573 
    574 /** Add <b>ri</b> to an appropriate node in the nodelist.  If we replace an
    575 * old routerinfo, and <b>ri_old_out</b> is not NULL, set *<b>ri_old_out</b>
    576 * to the previous routerinfo.
    577 */
    578 node_t *
    579 nodelist_set_routerinfo(routerinfo_t *ri, routerinfo_t **ri_old_out)
    580 {
    581  node_t *node;
    582  const char *id_digest;
    583  int had_router = 0;
    584  tor_assert(ri);
    585 
    586  init_nodelist();
    587  id_digest = ri->cache_info.identity_digest;
    588  node = node_get_or_create(id_digest);
    589 
    590  node_remove_from_ed25519_map(node);
    591 
    592  if (node->ri) {
    593    if (!routers_have_same_or_addrs(node->ri, ri)) {
    594      node_addrs_changed(node);
    595    }
    596    had_router = 1;
    597    if (ri_old_out)
    598      *ri_old_out = node->ri;
    599  } else {
    600    if (ri_old_out)
    601      *ri_old_out = NULL;
    602  }
    603  node->ri = ri;
    604 
    605  node_add_to_ed25519_map(node);
    606 
    607  if (node->country == -1)
    608    node_set_country(node);
    609 
    610  if (authdir_mode(get_options()) && !had_router) {
    611    const char *discard=NULL;
    612    uint32_t status = dirserv_router_get_status(ri, &discard, LOG_INFO);
    613    dirserv_set_node_flags_from_authoritative_status(node, status);
    614  }
    615 
    616  /* Setting the HSDir index requires the ed25519 identity key which can
    617   * only be found either in the ri or md. This is why this is called here.
    618   * Only nodes supporting HSDir=2 protocol version needs this index. */
    619  if (node->rs && node->rs->pv.supports_v3_hsdir) {
    620    node_set_hsdir_index(node,
    621                         networkstatus_get_latest_consensus());
    622  }
    623 
    624  node_add_to_address_set(node);
    625 
    626  return node;
    627 }
    628 
    629 /** Set the appropriate node_t to use <b>md</b> as its microdescriptor.
    630 *
    631 * Called when a new microdesc has arrived and the usable consensus flavor
    632 * is "microdesc".
    633 **/
    634 node_t *
    635 nodelist_add_microdesc(microdesc_t *md)
    636 {
    637  networkstatus_t *ns =
    638    networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
    639  const routerstatus_t *rs;
    640  node_t *node;
    641  if (ns == NULL)
    642    return NULL;
    643  init_nodelist();
    644 
    645  /* Microdescriptors don't carry an identity digest, so we need to figure
    646   * it out by looking up the routerstatus. */
    647  rs = router_get_consensus_status_by_descriptor_digest(ns, md->digest);
    648  if (rs == NULL)
    649    return NULL;
    650  node = node_get_mutable_by_id(rs->identity_digest);
    651  if (node == NULL)
    652    return NULL;
    653 
    654  node_remove_from_ed25519_map(node);
    655  if (node->md)
    656    node->md->held_by_nodes--;
    657 
    658  node->md = md;
    659  md->held_by_nodes++;
    660  /* Setting the HSDir index requires the ed25519 identity key which can
    661   * only be found either in the ri or md. This is why this is called here.
    662   * Only nodes supporting HSDir=2 protocol version needs this index. */
    663  if (rs->pv.supports_v3_hsdir) {
    664    node_set_hsdir_index(node, ns);
    665  }
    666  node_add_to_ed25519_map(node);
    667  node_add_to_address_set(node);
    668 
    669  return node;
    670 }
    671 
    672 /* Default value. */
    673 #define ESTIMATED_ADDRESS_PER_NODE 2
    674 
    675 /* Return the estimated number of address per node_t. This is used for the
    676 * size of the bloom filter in the nodelist (node_addrs). */
    677 MOCK_IMPL(int,
    678 get_estimated_address_per_node, (void))
    679 {
    680  return ESTIMATED_ADDRESS_PER_NODE;
    681 }
    682 
    683 /**
    684 * If true, we use relays' listed family members in order to
    685 * determine which relays are in the same family.
    686 */
    687 static int use_family_lists = 1;
    688 /**
    689 * If true, we use relays' validated family IDs in order to
    690 * determine which relays are in the same family.
    691 */
    692 static int use_family_ids = 1;
    693 
    694 /**
    695 * Update consensus parameters relevant to nodelist operations.
    696 *
    697 * We need to cache these values rather than searching for them every time
    698 * we check whether two relays are in the same family.
    699 **/
    700 static void
    701 nodelist_update_consensus_params(const networkstatus_t *ns)
    702 {
    703  use_family_lists = networkstatus_get_param(ns, "use-family-lists",
    704                                             1, 0, 1); // default, low, high
    705  use_family_ids = networkstatus_get_param(ns, "use-family-ids",
    706                                             1, 0, 1); // default, low, high
    707 }
    708 
    709 /** Tell the nodelist that the current usable consensus is <b>ns</b>.
    710 * This makes the nodelist change all of the routerstatus entries for
    711 * the nodes, drop nodes that no longer have enough info to get used,
    712 * and grab microdescriptors into nodes as appropriate.
    713 */
    714 void
    715 nodelist_set_consensus(const networkstatus_t *ns)
    716 {
    717  const or_options_t *options = get_options();
    718  int authdir = authdir_mode_v3(options);
    719 
    720  init_nodelist();
    721  if (ns->flavor == FLAV_MICRODESC)
    722    (void) get_microdesc_cache(); /* Make sure it exists first. */
    723 
    724  SMARTLIST_FOREACH(the_nodelist->nodes, node_t *, node,
    725                    node->rs = NULL);
    726 
    727  nodelist_update_consensus_params(ns);
    728 
    729  /* Conservatively estimate that every node will have 2 addresses (v4 and
    730   * v6). Then we add the number of configured trusted authorities we have. */
    731  int estimated_addresses = smartlist_len(ns->routerstatus_list) *
    732                            get_estimated_address_per_node();
    733  estimated_addresses += (get_n_authorities(V3_DIRINFO | BRIDGE_DIRINFO) *
    734                          get_estimated_address_per_node());
    735  /* Clear our sets because we will repopulate them with what this new
    736   * consensus contains. */
    737  address_set_free(the_nodelist->node_addrs);
    738  the_nodelist->node_addrs = address_set_new(estimated_addresses);
    739  digestmap_free(the_nodelist->reentry_set, NULL);
    740  the_nodelist->reentry_set = digestmap_new();
    741 
    742  SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
    743    node_t *node = node_get_or_create(rs->identity_digest);
    744    node->rs = rs;
    745    if (ns->flavor == FLAV_MICRODESC) {
    746      if (node->md == NULL ||
    747          tor_memneq(node->md->digest,rs->descriptor_digest,DIGEST256_LEN)) {
    748        node_remove_from_ed25519_map(node);
    749        if (node->md)
    750          node->md->held_by_nodes--;
    751        node->md = microdesc_cache_lookup_by_digest256(NULL,
    752                                                       rs->descriptor_digest);
    753        if (node->md)
    754          node->md->held_by_nodes++;
    755        node_add_to_ed25519_map(node);
    756      }
    757    }
    758 
    759    if (rs->pv.supports_v3_hsdir) {
    760      node_set_hsdir_index(node, ns);
    761    }
    762    node_set_country(node);
    763 
    764    /* Set node's flags based on rs's flags. */
    765    {
    766      node->is_valid = rs->is_valid;
    767      node->is_running = rs->is_flagged_running;
    768      node->is_fast = rs->is_fast;
    769      node->is_stable = rs->is_stable;
    770      node->is_possible_guard = rs->is_possible_guard;
    771      node->is_exit = rs->is_exit;
    772      if (!authdir) {
    773        /* Authdirs treat is_bad_exit specially in that they only assign
    774         * it when the descriptor arrives. So when a dir auth is reading
    775         * the flags from an existing consensus, don't believe the bit
    776         * here, else it will get stuck 'on' forever. */
    777        node->is_bad_exit = rs->is_bad_exit;
    778      }
    779      node->is_hs_dir = rs->is_hs_dir;
    780      node->ipv6_preferred = 0;
    781      if (reachable_addr_prefer_ipv6_orport(options) &&
    782          (tor_addr_is_null(&rs->ipv6_addr) == 0 ||
    783           (node->md && tor_addr_is_null(&node->md->ipv6_addr) == 0)))
    784        node->ipv6_preferred = 1;
    785    }
    786 
    787  } SMARTLIST_FOREACH_END(rs);
    788 
    789  nodelist_purge();
    790 
    791  /* Now add all the nodes we have to the address set. */
    792  SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
    793    node_add_to_address_set(node);
    794  } SMARTLIST_FOREACH_END(node);
    795  /* Then, add all trusted configured directories. Some might not be in the
    796   * consensus so make sure we know them. */
    797  dirlist_add_trusted_dir_addresses();
    798 
    799  if (! authdir) {
    800    SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
    801      /* We have no routerstatus for this router. Clear flags so we can skip
    802       * it, maybe.*/
    803      if (!node->rs) {
    804        tor_assert(node->ri); /* if it had only an md, or nothing, purge
    805                               * would have removed it. */
    806        if (node->ri->purpose == ROUTER_PURPOSE_GENERAL) {
    807          /* Clear all flags. */
    808          node->is_valid = node->is_running = node->is_hs_dir =
    809            node->is_fast = node->is_stable =
    810            node->is_possible_guard = node->is_exit =
    811            node->is_bad_exit = node->ipv6_preferred = 0;
    812        }
    813      }
    814    } SMARTLIST_FOREACH_END(node);
    815  }
    816 
    817  /* If the consensus is live, note down the consensus valid-after that formed
    818   * the nodelist. */
    819  if (networkstatus_is_live(ns, approx_time())) {
    820    the_nodelist->live_consensus_valid_after = ns->valid_after;
    821  }
    822 }
    823 
    824 /** Helper: return true iff a node has a usable amount of information*/
    825 static inline int
    826 node_is_usable(const node_t *node)
    827 {
    828  return (node->rs) || (node->ri);
    829 }
    830 
    831 /** Tell the nodelist that <b>md</b> is no longer a microdescriptor for the
    832 * node with <b>identity_digest</b>. */
    833 void
    834 nodelist_remove_microdesc(const char *identity_digest, microdesc_t *md)
    835 {
    836  node_t *node = node_get_mutable_by_id(identity_digest);
    837  if (node && node->md == md) {
    838    node->md = NULL;
    839    md->held_by_nodes--;
    840    if (! node_get_ed25519_id(node)) {
    841      node_remove_from_ed25519_map(node);
    842    }
    843  }
    844 }
    845 
    846 /** Tell the nodelist that <b>ri</b> is no longer in the routerlist. */
    847 void
    848 nodelist_remove_routerinfo(routerinfo_t *ri)
    849 {
    850  node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
    851  if (node && node->ri == ri) {
    852    node->ri = NULL;
    853    if (! node_is_usable(node)) {
    854      nodelist_drop_node(node, 1);
    855      node_free(node);
    856    }
    857  }
    858 }
    859 
    860 /** Remove <b>node</b> from the nodelist.  (Asserts that it was there to begin
    861 * with.) */
    862 static void
    863 nodelist_drop_node(node_t *node, int remove_from_ht)
    864 {
    865  node_t *tmp;
    866  int idx;
    867  if (remove_from_ht) {
    868    tmp = HT_REMOVE(nodelist_map, &the_nodelist->nodes_by_id, node);
    869    tor_assert(tmp == node);
    870  }
    871  node_remove_from_ed25519_map(node);
    872 
    873  idx = node->nodelist_idx;
    874  tor_assert(idx >= 0);
    875 
    876  tor_assert(node == smartlist_get(the_nodelist->nodes, idx));
    877  smartlist_del(the_nodelist->nodes, idx);
    878  if (idx < smartlist_len(the_nodelist->nodes)) {
    879    tmp = smartlist_get(the_nodelist->nodes, idx);
    880    tmp->nodelist_idx = idx;
    881  }
    882  node->nodelist_idx = -1;
    883 }
    884 
    885 /** Return a newly allocated smartlist of the nodes that have <b>md</b> as
    886 * their microdescriptor. */
    887 smartlist_t *
    888 nodelist_find_nodes_with_microdesc(const microdesc_t *md)
    889 {
    890  smartlist_t *result = smartlist_new();
    891 
    892  if (the_nodelist == NULL)
    893    return result;
    894 
    895  SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
    896    if (node->md == md) {
    897      smartlist_add(result, node);
    898    }
    899  } SMARTLIST_FOREACH_END(node);
    900 
    901  return result;
    902 }
    903 
    904 /** Release storage held by <b>node</b>  */
    905 static void
    906 node_free_(node_t *node)
    907 {
    908  if (!node)
    909    return;
    910  if (node->md)
    911    node->md->held_by_nodes--;
    912  tor_assert(node->nodelist_idx == -1);
    913  tor_free(node);
    914 }
    915 
    916 /** Remove all entries from the nodelist that don't have enough info to be
    917 * usable for anything. */
    918 void
    919 nodelist_purge(void)
    920 {
    921  node_t **iter;
    922  if (PREDICT_UNLIKELY(the_nodelist == NULL))
    923    return;
    924 
    925  /* Remove the non-usable nodes. */
    926  for (iter = HT_START(nodelist_map, &the_nodelist->nodes_by_id); iter; ) {
    927    node_t *node = *iter;
    928 
    929    if (node->md && !node->rs) {
    930      /* An md is only useful if there is an rs. */
    931      node->md->held_by_nodes--;
    932      node->md = NULL;
    933    }
    934 
    935    if (node_is_usable(node)) {
    936      iter = HT_NEXT(nodelist_map, &the_nodelist->nodes_by_id, iter);
    937    } else {
    938      iter = HT_NEXT_RMV(nodelist_map, &the_nodelist->nodes_by_id, iter);
    939      nodelist_drop_node(node, 0);
    940      node_free(node);
    941    }
    942  }
    943  nodelist_assert_ok();
    944 }
    945 
    946 /** Release all storage held by the nodelist. */
    947 void
    948 nodelist_free_all(void)
    949 {
    950  if (PREDICT_UNLIKELY(the_nodelist == NULL))
    951    return;
    952 
    953  HT_CLEAR(nodelist_map, &the_nodelist->nodes_by_id);
    954  HT_CLEAR(nodelist_ed_map, &the_nodelist->nodes_by_ed_id);
    955  SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
    956    node->nodelist_idx = -1;
    957    node_free(node);
    958  } SMARTLIST_FOREACH_END(node);
    959 
    960  smartlist_free(the_nodelist->nodes);
    961 
    962  address_set_free(the_nodelist->node_addrs);
    963  the_nodelist->node_addrs = NULL;
    964  digestmap_free(the_nodelist->reentry_set, NULL);
    965  the_nodelist->reentry_set = NULL;
    966 
    967  tor_free(the_nodelist);
    968 }
    969 
    970 /** Check that the nodelist is internally consistent, and consistent with
    971 * the directory info it's derived from.
    972 */
    973 void
    974 nodelist_assert_ok(void)
    975 {
    976  routerlist_t *rl = router_get_routerlist();
    977  networkstatus_t *ns = networkstatus_get_latest_consensus();
    978  digestmap_t *dm;
    979 
    980  if (!the_nodelist)
    981    return;
    982 
    983  dm = digestmap_new();
    984 
    985  /* every routerinfo in rl->routers should be in the nodelist. */
    986  if (rl) {
    987    SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
    988      const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
    989      tor_assert(node && node->ri == ri);
    990      tor_assert(fast_memeq(ri->cache_info.identity_digest,
    991                             node->identity, DIGEST_LEN));
    992      tor_assert(! digestmap_get(dm, node->identity));
    993      digestmap_set(dm, node->identity, (void*)node);
    994    } SMARTLIST_FOREACH_END(ri);
    995  }
    996 
    997  /* every routerstatus in ns should be in the nodelist */
    998  if (ns) {
    999    SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
   1000      const node_t *node = node_get_by_id(rs->identity_digest);
   1001      tor_assert(node && node->rs == rs);
   1002      tor_assert(fast_memeq(rs->identity_digest, node->identity, DIGEST_LEN));
   1003      digestmap_set(dm, node->identity, (void*)node);
   1004      if (ns->flavor == FLAV_MICRODESC) {
   1005        /* If it's a microdesc consensus, every entry that has a
   1006         * microdescriptor should be in the nodelist.
   1007         */
   1008        microdesc_t *md =
   1009          microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest);
   1010        tor_assert(md == node->md);
   1011        if (md)
   1012          tor_assert(md->held_by_nodes >= 1);
   1013      }
   1014    } SMARTLIST_FOREACH_END(rs);
   1015  }
   1016 
   1017  /* The nodelist should have no other entries, and its entries should be
   1018   * well-formed. */
   1019  SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
   1020    tor_assert(digestmap_get(dm, node->identity) != NULL);
   1021    tor_assert(node_sl_idx == node->nodelist_idx);
   1022  } SMARTLIST_FOREACH_END(node);
   1023 
   1024  /* Every node listed with an ed25519 identity should be listed by that
   1025   * identity.
   1026   */
   1027  SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
   1028    if (!ed25519_public_key_is_zero(&node->ed25519_id)) {
   1029      tor_assert(node == node_get_by_ed25519_id(&node->ed25519_id));
   1030    }
   1031  } SMARTLIST_FOREACH_END(node);
   1032 
   1033  node_t **idx;
   1034  HT_FOREACH(idx, nodelist_ed_map, &the_nodelist->nodes_by_ed_id) {
   1035    node_t *node = *idx;
   1036    tor_assert(node == node_get_by_ed25519_id(&node->ed25519_id));
   1037  }
   1038 
   1039  tor_assert((long)smartlist_len(the_nodelist->nodes) ==
   1040             (long)HT_SIZE(&the_nodelist->nodes_by_id));
   1041 
   1042  tor_assert((long)smartlist_len(the_nodelist->nodes) >=
   1043             (long)HT_SIZE(&the_nodelist->nodes_by_ed_id));
   1044 
   1045  digestmap_free(dm, NULL);
   1046 }
   1047 
   1048 /** Ensure that the nodelist has been created with the most recent consensus.
   1049 *  If that's not the case, make it so.  */
   1050 void
   1051 nodelist_ensure_freshness(const networkstatus_t *ns)
   1052 {
   1053  tor_assert(ns);
   1054 
   1055  /* We don't even have a nodelist: this is a NOP. */
   1056  if (!the_nodelist) {
   1057    return;
   1058  }
   1059 
   1060  if (the_nodelist->live_consensus_valid_after != ns->valid_after) {
   1061    log_info(LD_GENERAL, "Nodelist was not fresh: rebuilding. (%d / %d)",
   1062             (int) the_nodelist->live_consensus_valid_after,
   1063             (int) ns->valid_after);
   1064    nodelist_set_consensus(ns);
   1065  }
   1066 }
   1067 
   1068 /** Return a list of a node_t * for every node we know about.  The caller
   1069 * MUST NOT modify the list. (You can set and clear flags in the nodes if
   1070 * you must, but you must not add or remove nodes.) */
   1071 MOCK_IMPL(const smartlist_t *,
   1072 nodelist_get_list,(void))
   1073 {
   1074  init_nodelist();
   1075  return the_nodelist->nodes;
   1076 }
   1077 
   1078 /** Given a hex-encoded nickname of the format DIGEST, $DIGEST, $DIGEST=name,
   1079 * or $DIGEST~name, return the node with the matching identity digest and
   1080 * nickname (if any).  Return NULL if no such node exists, or if <b>hex_id</b>
   1081 * is not well-formed. DOCDOC flags */
   1082 const node_t *
   1083 node_get_by_hex_id(const char *hex_id, unsigned flags)
   1084 {
   1085  char digest_buf[DIGEST_LEN];
   1086  char nn_buf[MAX_NICKNAME_LEN+1];
   1087  char nn_char='\0';
   1088 
   1089  (void) flags; // XXXX
   1090 
   1091  if (hex_digest_nickname_decode(hex_id, digest_buf, &nn_char, nn_buf)==0) {
   1092    const node_t *node = node_get_by_id(digest_buf);
   1093    if (!node)
   1094      return NULL;
   1095    if (nn_char == '=') {
   1096      /* "=" indicates a Named relay, but there aren't any of those now. */
   1097      return NULL;
   1098    }
   1099    return node;
   1100  }
   1101 
   1102  return NULL;
   1103 }
   1104 
   1105 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
   1106 * the corresponding node_t, or NULL if none exists. Warn the user if they
   1107 * have specified a router by nickname, unless the NNF_NO_WARN_UNNAMED bit is
   1108 * set in <b>flags</b>. */
   1109 MOCK_IMPL(const node_t *,
   1110 node_get_by_nickname,(const char *nickname, unsigned flags))
   1111 {
   1112  const int warn_if_unnamed = !(flags & NNF_NO_WARN_UNNAMED);
   1113 
   1114  if (!the_nodelist)
   1115    return NULL;
   1116 
   1117  /* Handle these cases: DIGEST, $DIGEST, $DIGEST=name, $DIGEST~name. */
   1118  {
   1119    const node_t *node;
   1120    if ((node = node_get_by_hex_id(nickname, flags)) != NULL)
   1121      return node;
   1122  }
   1123 
   1124  if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
   1125    return NULL;
   1126 
   1127  /* Okay, so the name is not canonical for anybody. */
   1128  {
   1129    smartlist_t *matches = smartlist_new();
   1130    const node_t *choice = NULL;
   1131 
   1132    SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
   1133      if (!strcasecmp(node_get_nickname(node), nickname))
   1134        smartlist_add(matches, node);
   1135    } SMARTLIST_FOREACH_END(node);
   1136 
   1137    if (smartlist_len(matches)>1 && warn_if_unnamed) {
   1138      int any_unwarned = 0;
   1139      SMARTLIST_FOREACH_BEGIN(matches, node_t *, node) {
   1140        if (!node->name_lookup_warned) {
   1141          node->name_lookup_warned = 1;
   1142          any_unwarned = 1;
   1143        }
   1144      } SMARTLIST_FOREACH_END(node);
   1145 
   1146      if (any_unwarned) {
   1147        log_warn(LD_CONFIG, "There are multiple matches for the name %s. "
   1148                 "Choosing one arbitrarily.", nickname);
   1149      }
   1150    } else if (smartlist_len(matches)==1 && warn_if_unnamed) {
   1151      char fp[HEX_DIGEST_LEN+1];
   1152      node_t *node = smartlist_get(matches, 0);
   1153      if (! node->name_lookup_warned) {
   1154        base16_encode(fp, sizeof(fp), node->identity, DIGEST_LEN);
   1155        log_warn(LD_CONFIG,
   1156                 "You specified a relay \"%s\" by name, but nicknames can be "
   1157                 "used by any relay, not just the one you meant. "
   1158                 "To make sure you get the same relay in the future, refer "
   1159                 "to it by key, as \"$%s\".", nickname, fp);
   1160        node->name_lookup_warned = 1;
   1161      }
   1162    }
   1163 
   1164    if (smartlist_len(matches))
   1165      choice = smartlist_get(matches, 0);
   1166 
   1167    smartlist_free(matches);
   1168    return choice;
   1169  }
   1170 }
   1171 
   1172 /** Return the Ed25519 identity key for the provided node, or NULL if it
   1173 * doesn't have one. */
   1174 MOCK_IMPL(const ed25519_public_key_t *,
   1175 node_get_ed25519_id,(const node_t *node))
   1176 {
   1177  const ed25519_public_key_t *ri_pk = NULL;
   1178  const ed25519_public_key_t *md_pk = NULL;
   1179 
   1180  if (node->ri) {
   1181    if (node->ri->cache_info.signing_key_cert) {
   1182      ri_pk = &node->ri->cache_info.signing_key_cert->signing_key;
   1183      /* Checking whether routerinfo ed25519 is all zero.
   1184       * Our descriptor parser should make sure this never happens. */
   1185      if (BUG(ed25519_public_key_is_zero(ri_pk)))
   1186        ri_pk = NULL;
   1187    }
   1188  }
   1189 
   1190  if (node->md) {
   1191    if (node->md->ed25519_identity_pkey) {
   1192      md_pk = node->md->ed25519_identity_pkey;
   1193      /* Checking whether microdesc ed25519 is all zero.
   1194       * Our descriptor parser should make sure this never happens. */
   1195      if (BUG(ed25519_public_key_is_zero(md_pk)))
   1196        md_pk = NULL;
   1197    }
   1198  }
   1199 
   1200  if (ri_pk && md_pk) {
   1201    if (ed25519_pubkey_eq(ri_pk, md_pk)) {
   1202      return ri_pk;
   1203    } else {
   1204      /* This can happen if the relay gets flagged NoEdConsensus which will be
   1205       * triggered on all relays of the network. Thus a protocol warning. */
   1206      log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
   1207             "Inconsistent ed25519 identities in the nodelist");
   1208      return NULL;
   1209    }
   1210  } else if (ri_pk) {
   1211    return ri_pk;
   1212  } else {
   1213    return md_pk;
   1214  }
   1215 }
   1216 
   1217 /** Return true iff this node's Ed25519 identity matches <b>id</b>.
   1218 * (An absent Ed25519 identity matches NULL or zero.) */
   1219 int
   1220 node_ed25519_id_matches(const node_t *node, const ed25519_public_key_t *id)
   1221 {
   1222  const ed25519_public_key_t *node_id = node_get_ed25519_id(node);
   1223  if (node_id == NULL || ed25519_public_key_is_zero(node_id)) {
   1224    return id == NULL || ed25519_public_key_is_zero(id);
   1225  } else {
   1226    return id && ed25519_pubkey_eq(node_id, id);
   1227  }
   1228 }
   1229 
   1230 /** Dummy object that should be unreturnable.  Used to ensure that
   1231 * node_get_protover_summary_flags() always returns non-NULL. */
   1232 static const protover_summary_flags_t zero_protover_flags = {
   1233  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
   1234 };
   1235 
   1236 /** Return the protover_summary_flags for a given node. */
   1237 static const protover_summary_flags_t *
   1238 node_get_protover_summary_flags(const node_t *node)
   1239 {
   1240  if (node->rs) {
   1241    return &node->rs->pv;
   1242  } else if (node->ri) {
   1243    return &node->ri->pv;
   1244  } else {
   1245    /* This should be impossible: every node should have a routerstatus or a
   1246     * router descriptor or both. But just in case we've messed up somehow,
   1247     * return a nice empty set of flags to indicate "this node supports
   1248     * nothing." */
   1249    tor_assert_nonfatal_unreached_once();
   1250    return &zero_protover_flags;
   1251  }
   1252 }
   1253 
   1254 /** Return true iff <b>node</b> supports authenticating itself
   1255 * by ed25519 ID during the link handshake.  If <b>compatible_with_us</b>,
   1256 * it needs to be using a link authentication method that we understand.
   1257 * If not, any plausible link authentication method will do. */
   1258 MOCK_IMPL(bool,
   1259 node_supports_ed25519_link_authentication,(const node_t *node,
   1260                                           bool compatible_with_us))
   1261 {
   1262  if (! node_get_ed25519_id(node))
   1263    return 0;
   1264 
   1265  const protover_summary_flags_t *pv = node_get_protover_summary_flags(node);
   1266 
   1267  if (compatible_with_us)
   1268    return pv->supports_ed25519_link_handshake_compat;
   1269  else
   1270    return pv->supports_ed25519_link_handshake_any;
   1271 }
   1272 
   1273 /** Return true iff <b>node</b> supports the hidden service directory version
   1274 * 3 protocol (proposal 224). */
   1275 bool
   1276 node_supports_v3_hsdir(const node_t *node)
   1277 {
   1278  tor_assert(node);
   1279 
   1280  return node_get_protover_summary_flags(node)->supports_v3_hsdir;
   1281 }
   1282 
   1283 /** Return true iff <b>node</b> supports ed25519 authentication as an hidden
   1284 * service introduction point.*/
   1285 bool
   1286 node_supports_ed25519_hs_intro(const node_t *node)
   1287 {
   1288  tor_assert(node);
   1289 
   1290  return node_get_protover_summary_flags(node)->supports_ed25519_hs_intro;
   1291 }
   1292 
   1293 /** Return true iff <b>node</b> can be a rendezvous point for hidden
   1294 * service version 3 (HSRend=2). */
   1295 bool
   1296 node_supports_v3_rendezvous_point(const node_t *node)
   1297 {
   1298  tor_assert(node);
   1299 
   1300  /* We can't use a v3 rendezvous point without the curve25519 onion pk. */
   1301  if (!node_get_curve25519_onion_key(node)) {
   1302    return 0;
   1303  }
   1304 
   1305  return node_get_protover_summary_flags(node)->supports_v3_rendezvous_point;
   1306 }
   1307 
   1308 /** Return true iff <b>node</b> supports the DoS ESTABLISH_INTRO cell
   1309 * extension. */
   1310 bool
   1311 node_supports_establish_intro_dos_extension(const node_t *node)
   1312 {
   1313  tor_assert(node);
   1314 
   1315  return node_get_protover_summary_flags(node)->
   1316                           supports_establish_intro_dos_extension;
   1317 }
   1318 
   1319 /** Return true iff <b>node</b> can initiate IPv6 extends (Relay=3).
   1320 *
   1321 * This check should only be performed by client path selection code.
   1322 *
   1323 * Extending relays should check their own IPv6 support using
   1324 * router_can_extend_over_ipv6(). Like other extends, they should not verify
   1325 * the link specifiers in the extend cell against the consensus, because it
   1326 * may be out of date. */
   1327 bool
   1328 node_supports_initiating_ipv6_extends(const node_t *node)
   1329 {
   1330  tor_assert(node);
   1331 
   1332  /* Relays can't initiate an IPv6 extend, unless they have an IPv6 ORPort. */
   1333  if (!node_has_ipv6_orport(node)) {
   1334    return 0;
   1335  }
   1336 
   1337  /* Initiating relays also need to support the relevant protocol version. */
   1338  return
   1339    node_get_protover_summary_flags(node)->supports_initiating_ipv6_extends;
   1340 }
   1341 
   1342 /** Return true iff <b>node</b> can accept IPv6 extends (Relay=2 or Relay=3)
   1343 * from other relays. If <b>need_canonical_ipv6_conn</b> is true, also check
   1344 * if the relay supports canonical IPv6 connections (Relay=3 only).
   1345 *
   1346 * This check should only be performed by client path selection code.
   1347 */
   1348 bool
   1349 node_supports_accepting_ipv6_extends(const node_t *node,
   1350                                            bool need_canonical_ipv6_conn)
   1351 {
   1352  tor_assert(node);
   1353 
   1354  /* Relays can't accept an IPv6 extend, unless they have an IPv6 ORPort. */
   1355  if (!node_has_ipv6_orport(node)) {
   1356    return 0;
   1357  }
   1358 
   1359  /* Accepting relays also need to support the relevant protocol version. */
   1360  if (need_canonical_ipv6_conn) {
   1361    return
   1362      node_get_protover_summary_flags(node)->supports_canonical_ipv6_conns;
   1363  } else {
   1364    return
   1365      node_get_protover_summary_flags(node)->supports_accepting_ipv6_extends;
   1366  }
   1367 }
   1368 
   1369 /** Return true iff the given node supports conflux (Relay=5) */
   1370 bool
   1371 node_supports_conflux(const node_t *node)
   1372 {
   1373  tor_assert(node);
   1374 
   1375  return node_get_protover_summary_flags(node)->supports_conflux;
   1376 }
   1377 
   1378 /** Return the RSA ID key's SHA1 digest for the provided node. */
   1379 const uint8_t *
   1380 node_get_rsa_id_digest(const node_t *node)
   1381 {
   1382  tor_assert(node);
   1383  return (const uint8_t*)node->identity;
   1384 }
   1385 
   1386 /* Returns a new smartlist with all possible link specifiers from node:
   1387 *  - legacy ID is mandatory thus MUST be present in node;
   1388 *  - include ed25519 link specifier if present in the node, and the node
   1389 *    supports ed25519 link authentication, and:
   1390 *    - if direct_conn is true, its link versions are compatible with us,
   1391 *    - if direct_conn is false, regardless of its link versions;
   1392 *  - include IPv4 link specifier, if the primary address is not IPv4, log a
   1393 *    BUG() warning, and return an empty smartlist;
   1394 *  - include IPv6 link specifier if present in the node.
   1395 *
   1396 * If node is NULL, returns an empty smartlist.
   1397 *
   1398 * The smartlist must be freed using link_specifier_smartlist_free(). */
   1399 MOCK_IMPL(smartlist_t *,
   1400 node_get_link_specifier_smartlist,(const node_t *node, bool direct_conn))
   1401 {
   1402  link_specifier_t *ls;
   1403  tor_addr_port_t ap;
   1404  smartlist_t *lspecs = smartlist_new();
   1405 
   1406  if (!node)
   1407    return lspecs;
   1408 
   1409  /* Get the relay's IPv4 address. */
   1410  node_get_prim_orport(node, &ap);
   1411 
   1412  /* We expect the node's primary address to be a valid IPv4 address.
   1413   * This conforms to the protocol, which requires either an IPv4 or IPv6
   1414   * address (or both). */
   1415  if (BUG(!tor_addr_is_v4(&ap.addr)) ||
   1416      BUG(!tor_addr_port_is_valid_ap(&ap, 0))) {
   1417    return lspecs;
   1418  }
   1419 
   1420  ls = link_specifier_new();
   1421  link_specifier_set_ls_type(ls, LS_IPV4);
   1422  link_specifier_set_un_ipv4_addr(ls, tor_addr_to_ipv4h(&ap.addr));
   1423  link_specifier_set_un_ipv4_port(ls, ap.port);
   1424  /* Four bytes IPv4 and two bytes port. */
   1425  link_specifier_set_ls_len(ls, sizeof(ap.addr.addr.in_addr) +
   1426                            sizeof(ap.port));
   1427  smartlist_add(lspecs, ls);
   1428 
   1429  /* Legacy ID is mandatory and will always be present in node. */
   1430  ls = link_specifier_new();
   1431  link_specifier_set_ls_type(ls, LS_LEGACY_ID);
   1432  memcpy(link_specifier_getarray_un_legacy_id(ls), node->identity,
   1433         link_specifier_getlen_un_legacy_id(ls));
   1434  link_specifier_set_ls_len(ls, link_specifier_getlen_un_legacy_id(ls));
   1435  smartlist_add(lspecs, ls);
   1436 
   1437  /* ed25519 ID is only included if the node has it, and the node declares a
   1438   protocol version that supports ed25519 link authentication.
   1439   If direct_conn is true, we also require that the node's link version is
   1440   compatible with us. (Otherwise, we will be sending the ed25519 key
   1441   to another tor, which may support different link versions.) */
   1442  if (!ed25519_public_key_is_zero(&node->ed25519_id) &&
   1443      node_supports_ed25519_link_authentication(node, direct_conn)) {
   1444    ls = link_specifier_new();
   1445    link_specifier_set_ls_type(ls, LS_ED25519_ID);
   1446    memcpy(link_specifier_getarray_un_ed25519_id(ls), &node->ed25519_id,
   1447           link_specifier_getlen_un_ed25519_id(ls));
   1448    link_specifier_set_ls_len(ls, link_specifier_getlen_un_ed25519_id(ls));
   1449    smartlist_add(lspecs, ls);
   1450  }
   1451 
   1452  /* Check for IPv6. If so, include it as well. */
   1453  if (node_has_ipv6_orport(node)) {
   1454    ls = link_specifier_new();
   1455    node_get_pref_ipv6_orport(node, &ap);
   1456    link_specifier_set_ls_type(ls, LS_IPV6);
   1457    size_t addr_len = link_specifier_getlen_un_ipv6_addr(ls);
   1458    const uint8_t *in6_addr = tor_addr_to_in6_addr8(&ap.addr);
   1459    uint8_t *ipv6_array = link_specifier_getarray_un_ipv6_addr(ls);
   1460    memcpy(ipv6_array, in6_addr, addr_len);
   1461    link_specifier_set_un_ipv6_port(ls, ap.port);
   1462    /* Sixteen bytes IPv6 and two bytes port. */
   1463    link_specifier_set_ls_len(ls, addr_len + sizeof(ap.port));
   1464    smartlist_add(lspecs, ls);
   1465  }
   1466 
   1467  return lspecs;
   1468 }
   1469 
   1470 /* Free a link specifier list. */
   1471 void
   1472 link_specifier_smartlist_free_(smartlist_t *ls_list)
   1473 {
   1474  if (!ls_list)
   1475    return;
   1476 
   1477  SMARTLIST_FOREACH(ls_list, link_specifier_t *, lspec,
   1478                    link_specifier_free(lspec));
   1479  smartlist_free(ls_list);
   1480 }
   1481 
   1482 /** Return the nickname of <b>node</b>, or NULL if we can't find one. */
   1483 const char *
   1484 node_get_nickname(const node_t *node)
   1485 {
   1486  tor_assert(node);
   1487  if (node->rs)
   1488    return node->rs->nickname;
   1489  else if (node->ri)
   1490    return node->ri->nickname;
   1491  else
   1492    return NULL;
   1493 }
   1494 
   1495 /** Return true iff <b>node</b> appears to be a directory authority or
   1496 * directory cache */
   1497 int
   1498 node_is_dir(const node_t *node)
   1499 {
   1500  if (node->rs) {
   1501    routerstatus_t *rs = node->rs;
   1502    /* This is true if supports_tunnelled_dir_requests is true which
   1503     * indicates that we support directory request tunnelled or through the
   1504     * DirPort. */
   1505    return rs->is_v2_dir;
   1506  } else if (node->ri) {
   1507    routerinfo_t *ri = node->ri;
   1508    /* Both tunnelled request is supported or DirPort is set. */
   1509    return ri->supports_tunnelled_dir_requests;
   1510  } else {
   1511    return 0;
   1512  }
   1513 }
   1514 
   1515 /** Return true iff <b>node</b> has either kind of descriptor -- that
   1516 * is, a routerdescriptor or a microdescriptor.
   1517 *
   1518 * You should probably use node_has_preferred_descriptor() instead.
   1519 **/
   1520 int
   1521 node_has_any_descriptor(const node_t *node)
   1522 {
   1523  return (node->ri ||
   1524          (node->rs && node->md));
   1525 }
   1526 
   1527 /** Return true iff <b>node</b> has the kind of descriptor we would prefer to
   1528 * use for it, given our configuration and how we intend to use the node.
   1529 *
   1530 * If <b>for_direct_connect</b> is true, we intend to connect to the node
   1531 * directly, as the first hop of a circuit; otherwise, we intend to connect to
   1532 * it indirectly, or use it as if we were connecting to it indirectly. */
   1533 int
   1534 node_has_preferred_descriptor(const node_t *node,
   1535                              int for_direct_connect)
   1536 {
   1537  const int is_bridge = node_is_a_configured_bridge(node);
   1538  const int we_use_mds = we_use_microdescriptors_for_circuits(get_options());
   1539 
   1540  if ((is_bridge && for_direct_connect) || !we_use_mds) {
   1541    /* We need an ri in this case. */
   1542    if (!node->ri)
   1543      return 0;
   1544  } else {
   1545    /* Otherwise we need an rs and an md. */
   1546    if (node->rs == NULL || node->md == NULL)
   1547      return 0;
   1548  }
   1549 
   1550  return 1;
   1551 }
   1552 
   1553 /** Return the router_purpose of <b>node</b>. */
   1554 int
   1555 node_get_purpose(const node_t *node)
   1556 {
   1557  if (node->ri)
   1558    return node->ri->purpose;
   1559  else
   1560    return ROUTER_PURPOSE_GENERAL;
   1561 }
   1562 
   1563 /** Compute the verbose ("extended") nickname of <b>node</b> and store it
   1564 * into the MAX_VERBOSE_NICKNAME_LEN+1 character buffer at
   1565 * <b>verbose_name_out</b> */
   1566 void
   1567 node_get_verbose_nickname(const node_t *node,
   1568                          char *verbose_name_out)
   1569 {
   1570  const char *nickname = node_get_nickname(node);
   1571  verbose_name_out[0] = '$';
   1572  base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, node->identity,
   1573                DIGEST_LEN);
   1574  if (!nickname)
   1575    return;
   1576  verbose_name_out[1+HEX_DIGEST_LEN] = '~';
   1577  strlcpy(verbose_name_out+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
   1578 }
   1579 
   1580 /** Compute the verbose ("extended") nickname of node with
   1581 * given <b>id_digest</b> and store it into the MAX_VERBOSE_NICKNAME_LEN+1
   1582 * character buffer at <b>verbose_name_out</b>
   1583 *
   1584 * If node_get_by_id() returns NULL, base 16 encoding of
   1585 * <b>id_digest</b> is returned instead. */
   1586 void
   1587 node_get_verbose_nickname_by_id(const char *id_digest,
   1588                                char *verbose_name_out)
   1589 {
   1590  const node_t *node = node_get_by_id(id_digest);
   1591  if (!node) {
   1592    verbose_name_out[0] = '$';
   1593    base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
   1594  } else {
   1595    node_get_verbose_nickname(node, verbose_name_out);
   1596  }
   1597 }
   1598 
   1599 /** Return true iff it seems that <b>node</b> allows circuits to exit
   1600 * through it directlry from the client. */
   1601 int
   1602 node_allows_single_hop_exits(const node_t *node)
   1603 {
   1604  if (node && node->ri)
   1605    return node->ri->allow_single_hop_exits;
   1606  else
   1607    return 0;
   1608 }
   1609 
   1610 /** Return true iff it seems that <b>node</b> has an exit policy that doesn't
   1611 * actually permit anything to exit, or we don't know its exit policy */
   1612 int
   1613 node_exit_policy_rejects_all(const node_t *node)
   1614 {
   1615  if (node->rejects_all)
   1616    return 1;
   1617 
   1618  if (node->ri)
   1619    return node->ri->policy_is_reject_star;
   1620  else if (node->md)
   1621    return node->md->policy_is_reject_star;
   1622  else
   1623    return 1;
   1624 }
   1625 
   1626 /** Return true iff the exit policy for <b>node</b> is such that we can treat
   1627 * rejecting an address of type <b>family</b> unexpectedly as a sign of that
   1628 * node's failure. */
   1629 int
   1630 node_exit_policy_is_exact(const node_t *node, sa_family_t family)
   1631 {
   1632  if (family == AF_UNSPEC) {
   1633    return 1; /* Rejecting an address but not telling us what address
   1634               * is a bad sign. */
   1635  } else if (family == AF_INET) {
   1636    return node->ri != NULL;
   1637  } else if (family == AF_INET6) {
   1638    return 0;
   1639  }
   1640  tor_fragile_assert();
   1641  return 1;
   1642 }
   1643 
   1644 /* Check if the "addr" and port_field fields from r are a valid non-listening
   1645 * address/port. If so, set valid to true and add a newly allocated
   1646 * tor_addr_port_t containing "addr" and port_field to sl.
   1647 * "addr" is an IPv4 host-order address and port_field is a uint16_t.
   1648 * r is typically a routerinfo_t or routerstatus_t.
   1649 */
   1650 #define SL_ADD_NEW_AP(r, addr_field, port_field, sl, valid)             \
   1651  STMT_BEGIN                                                            \
   1652    if (tor_addr_port_is_valid(&(r)->addr_field, (r)->port_field, 0)) { \
   1653      valid = 1;                                                        \
   1654      tor_addr_port_t *ap = tor_addr_port_new(&(r)->addr_field,         \
   1655                                              (r)->port_field);         \
   1656      smartlist_add((sl), ap);                                          \
   1657    }                                                                   \
   1658  STMT_END
   1659 
   1660 /** Return list of tor_addr_port_t with all OR ports (in the sense IP
   1661 * addr + TCP port) for <b>node</b>.  Caller must free all elements
   1662 * using tor_free() and free the list using smartlist_free().
   1663 *
   1664 * XXX this is potentially a memory fragmentation hog -- if on
   1665 * critical path consider the option of having the caller allocate the
   1666 * memory
   1667 */
   1668 smartlist_t *
   1669 node_get_all_orports(const node_t *node)
   1670 {
   1671  smartlist_t *sl = smartlist_new();
   1672  int valid = 0;
   1673 
   1674  /* Find a valid IPv4 address and port */
   1675  if (node->ri != NULL) {
   1676    SL_ADD_NEW_AP(node->ri, ipv4_addr, ipv4_orport, sl, valid);
   1677  }
   1678 
   1679  /* If we didn't find a valid address/port in the ri, try the rs */
   1680  if (!valid && node->rs != NULL) {
   1681    SL_ADD_NEW_AP(node->rs, ipv4_addr, ipv4_orport, sl, valid);
   1682  }
   1683 
   1684  /* Find a valid IPv6 address and port */
   1685  valid = 0;
   1686  if (node->ri != NULL) {
   1687    SL_ADD_NEW_AP(node->ri, ipv6_addr, ipv6_orport, sl, valid);
   1688  }
   1689 
   1690  if (!valid && node->rs != NULL) {
   1691    SL_ADD_NEW_AP(node->rs, ipv6_addr, ipv6_orport, sl, valid);
   1692  }
   1693 
   1694  if (!valid && node->md != NULL) {
   1695    SL_ADD_NEW_AP(node->md, ipv6_addr, ipv6_orport, sl, valid);
   1696  }
   1697 
   1698  return sl;
   1699 }
   1700 
   1701 #undef SL_ADD_NEW_AP
   1702 
   1703 /** Wrapper around node_get_prim_orport for backward
   1704    compatibility.  */
   1705 void
   1706 node_get_addr(const node_t *node, tor_addr_t *addr_out)
   1707 {
   1708  tor_addr_port_t ap;
   1709  node_get_prim_orport(node, &ap);
   1710  tor_addr_copy(addr_out, &ap.addr);
   1711 }
   1712 
   1713 /** Return the IPv4 address for <b>node</b>, or NULL if none found. */
   1714 static const tor_addr_t *
   1715 node_get_prim_addr_ipv4(const node_t *node)
   1716 {
   1717  /* Don't check the ORPort or DirPort, as this function isn't port-specific,
   1718   * and the node might have a valid IPv4 address, yet have a zero
   1719   * ORPort or DirPort.
   1720   */
   1721  if (node->ri && tor_addr_is_valid(&node->ri->ipv4_addr, 0)) {
   1722    return &node->ri->ipv4_addr;
   1723  } else if (node->rs && tor_addr_is_valid(&node->rs->ipv4_addr, 0)) {
   1724    return &node->rs->ipv4_addr;
   1725  }
   1726  return NULL;
   1727 }
   1728 
   1729 /** Copy a string representation of an IP address for <b>node</b> into
   1730 * the <b>len</b>-byte buffer at <b>buf</b>.  */
   1731 void
   1732 node_get_address_string(const node_t *node, char *buf, size_t len)
   1733 {
   1734  const tor_addr_t *ipv4_addr = node_get_prim_addr_ipv4(node);
   1735 
   1736  if (ipv4_addr) {
   1737    tor_addr_to_str(buf, ipv4_addr, len, 0);
   1738  } else if (len > 0) {
   1739    buf[0] = '\0';
   1740  }
   1741 }
   1742 
   1743 /** Return <b>node</b>'s declared uptime, or -1 if it doesn't seem to have
   1744 * one. */
   1745 long
   1746 node_get_declared_uptime(const node_t *node)
   1747 {
   1748  if (node->ri)
   1749    return node->ri->uptime;
   1750  else
   1751    return -1;
   1752 }
   1753 
   1754 /** Return <b>node</b>'s platform string, or NULL if we don't know it. */
   1755 const char *
   1756 node_get_platform(const node_t *node)
   1757 {
   1758  /* If we wanted, we could record the version in the routerstatus_t, since
   1759   * the consensus lists it.  We don't, though, so this function just won't
   1760   * work with microdescriptors. */
   1761  if (node->ri)
   1762    return node->ri->platform;
   1763  else
   1764    return NULL;
   1765 }
   1766 
   1767 /** Return true iff <b>node</b> is one representing this router. */
   1768 int
   1769 node_is_me(const node_t *node)
   1770 {
   1771  return router_digest_is_me(node->identity);
   1772 }
   1773 
   1774 /* Does this node have a valid IPv6 address?
   1775 * Prefer node_has_ipv6_orport() or node_has_ipv6_dirport() for
   1776 * checking specific ports. */
   1777 int
   1778 node_has_ipv6_addr(const node_t *node)
   1779 {
   1780  /* Don't check the ORPort or DirPort, as this function isn't port-specific,
   1781   * and the node might have a valid IPv6 address, yet have a zero
   1782   * ORPort or DirPort.
   1783   */
   1784  if (node->ri && tor_addr_is_valid(&node->ri->ipv6_addr, 0))
   1785    return 1;
   1786  if (node->rs && tor_addr_is_valid(&node->rs->ipv6_addr, 0))
   1787    return 1;
   1788  if (node->md && tor_addr_is_valid(&node->md->ipv6_addr, 0))
   1789    return 1;
   1790 
   1791  return 0;
   1792 }
   1793 
   1794 /* Does this node have a valid IPv6 ORPort? */
   1795 int
   1796 node_has_ipv6_orport(const node_t *node)
   1797 {
   1798  tor_addr_port_t ipv6_orport;
   1799  node_get_pref_ipv6_orport(node, &ipv6_orport);
   1800  return tor_addr_port_is_valid_ap(&ipv6_orport, 0);
   1801 }
   1802 
   1803 /* Does this node have a valid IPv6 DirPort? */
   1804 int
   1805 node_has_ipv6_dirport(const node_t *node)
   1806 {
   1807  tor_addr_port_t ipv6_dirport;
   1808  node_get_pref_ipv6_dirport(node, &ipv6_dirport);
   1809  return tor_addr_port_is_valid_ap(&ipv6_dirport, 0);
   1810 }
   1811 
   1812 /** Return 1 if we prefer the IPv6 address and OR TCP port of
   1813 * <b>node</b>, else 0.
   1814 *
   1815 *  We prefer the IPv6 address if the router has an IPv6 address,
   1816 *  and we can use IPv6 addresses, and:
   1817 *  i) the node_t says that it prefers IPv6
   1818 *  or
   1819 *  ii) the router has no IPv4 OR address.
   1820 *
   1821 * If you don't have a node, consider looking it up.
   1822 * If there is no node, use reachable_addr_prefer_ipv6_orport().
   1823 */
   1824 int
   1825 node_ipv6_or_preferred(const node_t *node)
   1826 {
   1827  const or_options_t *options = get_options();
   1828  tor_addr_port_t ipv4_addr;
   1829  node_assert_ok(node);
   1830 
   1831  /* XX/teor - node->ipv6_preferred is set from
   1832   * reachable_addr_prefer_ipv6_orport() each time the consensus is loaded.
   1833   */
   1834  node_get_prim_orport(node, &ipv4_addr);
   1835  if (!reachable_addr_use_ipv6(options)) {
   1836    return 0;
   1837  } else if (node->ipv6_preferred ||
   1838             !tor_addr_port_is_valid_ap(&ipv4_addr, 0)) {
   1839    return node_has_ipv6_orport(node);
   1840  }
   1841  return 0;
   1842 }
   1843 
   1844 #define RETURN_IPV4_AP(r, port_field, ap_out)                               \
   1845  STMT_BEGIN                                                                \
   1846    if (r && tor_addr_port_is_valid(&(r)->ipv4_addr, (r)->port_field, 0)) { \
   1847      tor_addr_copy(&(ap_out)->addr, &(r)->ipv4_addr);                      \
   1848      (ap_out)->port = (r)->port_field;                                     \
   1849    }                                                                       \
   1850  STMT_END
   1851 
   1852 /** Copy the primary (IPv4) OR port (IP address and TCP port) for <b>node</b>
   1853 * into *<b>ap_out</b>. */
   1854 void
   1855 node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out)
   1856 {
   1857  node_assert_ok(node);
   1858  tor_assert(ap_out);
   1859 
   1860  /* Clear the address, as a safety precaution if calling functions ignore the
   1861   * return value */
   1862  tor_addr_make_null(&ap_out->addr, AF_INET);
   1863  ap_out->port = 0;
   1864 
   1865  /* Check ri first, because rewrite_node_address_for_bridge() updates
   1866   * node->ri with the configured bridge address. */
   1867 
   1868  RETURN_IPV4_AP(node->ri, ipv4_orport, ap_out);
   1869  RETURN_IPV4_AP(node->rs, ipv4_orport, ap_out);
   1870  /* Microdescriptors only have an IPv6 address */
   1871 }
   1872 
   1873 /** Copy the preferred OR port (IP address and TCP port) for
   1874 * <b>node</b> into *<b>ap_out</b>.  */
   1875 void
   1876 node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out)
   1877 {
   1878  tor_assert(ap_out);
   1879 
   1880  if (node_ipv6_or_preferred(node)) {
   1881    node_get_pref_ipv6_orport(node, ap_out);
   1882  } else {
   1883    /* the primary ORPort is always on IPv4 */
   1884    node_get_prim_orport(node, ap_out);
   1885  }
   1886 }
   1887 
   1888 /** Copy the preferred IPv6 OR port (IP address and TCP port) for
   1889 * <b>node</b> into *<b>ap_out</b>. */
   1890 void
   1891 node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out)
   1892 {
   1893  node_assert_ok(node);
   1894  tor_assert(ap_out);
   1895  memset(ap_out, 0, sizeof(*ap_out));
   1896 
   1897  /* Check ri first, because rewrite_node_address_for_bridge() updates
   1898   * node->ri with the configured bridge address.
   1899   * Prefer rs over md for consistency with the fascist_firewall_* functions.
   1900   * Check if the address or port are valid, and try another alternative
   1901   * if they are not. */
   1902 
   1903  if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr,
   1904                                         node->ri->ipv6_orport, 0)) {
   1905    tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr);
   1906    ap_out->port = node->ri->ipv6_orport;
   1907  } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr,
   1908                                                 node->rs->ipv6_orport, 0)) {
   1909    tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr);
   1910    ap_out->port = node->rs->ipv6_orport;
   1911  } else if (node->md && tor_addr_port_is_valid(&node->md->ipv6_addr,
   1912                                                 node->md->ipv6_orport, 0)) {
   1913    tor_addr_copy(&ap_out->addr, &node->md->ipv6_addr);
   1914    ap_out->port = node->md->ipv6_orport;
   1915  } else {
   1916    tor_addr_make_null(&ap_out->addr, AF_INET6);
   1917    ap_out->port = 0;
   1918  }
   1919 }
   1920 
   1921 /** Return 1 if we prefer the IPv6 address and Dir TCP port of
   1922 * <b>node</b>, else 0.
   1923 *
   1924 *  We prefer the IPv6 address if the router has an IPv6 address,
   1925 *  and we can use IPv6 addresses, and:
   1926 *  i) the router has no IPv4 Dir address.
   1927 *  or
   1928 *  ii) our preference is for IPv6 Dir addresses.
   1929 *
   1930 * If there is no node, use reachable_addr_prefer_ipv6_dirport().
   1931 */
   1932 int
   1933 node_ipv6_dir_preferred(const node_t *node)
   1934 {
   1935  const or_options_t *options = get_options();
   1936  tor_addr_port_t ipv4_addr;
   1937  node_assert_ok(node);
   1938 
   1939  /* node->ipv6_preferred is set from reachable_addr_prefer_ipv6_orport(),
   1940   * so we can't use it to determine DirPort IPv6 preference.
   1941   * This means that bridge clients will use IPv4 DirPorts by default.
   1942   */
   1943  node_get_prim_dirport(node, &ipv4_addr);
   1944  if (!reachable_addr_use_ipv6(options)) {
   1945    return 0;
   1946  } else if (!tor_addr_port_is_valid_ap(&ipv4_addr, 0)
   1947      || reachable_addr_prefer_ipv6_dirport(get_options())) {
   1948    return node_has_ipv6_dirport(node);
   1949  }
   1950  return 0;
   1951 }
   1952 
   1953 /** Copy the primary (IPv4) Dir port (IP address and TCP port) for <b>node</b>
   1954 * into *<b>ap_out</b>. */
   1955 void
   1956 node_get_prim_dirport(const node_t *node, tor_addr_port_t *ap_out)
   1957 {
   1958  node_assert_ok(node);
   1959  tor_assert(ap_out);
   1960 
   1961  /* Clear the address, as a safety precaution if calling functions ignore the
   1962   * return value */
   1963  tor_addr_make_null(&ap_out->addr, AF_INET);
   1964  ap_out->port = 0;
   1965 
   1966  /* Check ri first, because rewrite_node_address_for_bridge() updates
   1967   * node->ri with the configured bridge address. */
   1968 
   1969  RETURN_IPV4_AP(node->ri, ipv4_dirport, ap_out);
   1970  RETURN_IPV4_AP(node->rs, ipv4_dirport, ap_out);
   1971  /* Microdescriptors only have an IPv6 address */
   1972 }
   1973 
   1974 #undef RETURN_IPV4_AP
   1975 
   1976 /** Copy the preferred Dir port (IP address and TCP port) for
   1977 * <b>node</b> into *<b>ap_out</b>.  */
   1978 void
   1979 node_get_pref_dirport(const node_t *node, tor_addr_port_t *ap_out)
   1980 {
   1981  tor_assert(ap_out);
   1982 
   1983  if (node_ipv6_dir_preferred(node)) {
   1984    node_get_pref_ipv6_dirport(node, ap_out);
   1985  } else {
   1986    /* the primary DirPort is always on IPv4 */
   1987    node_get_prim_dirport(node, ap_out);
   1988  }
   1989 }
   1990 
   1991 /** Copy the preferred IPv6 Dir port (IP address and TCP port) for
   1992 * <b>node</b> into *<b>ap_out</b>. */
   1993 void
   1994 node_get_pref_ipv6_dirport(const node_t *node, tor_addr_port_t *ap_out)
   1995 {
   1996  node_assert_ok(node);
   1997  tor_assert(ap_out);
   1998 
   1999  /* Check ri first, because rewrite_node_address_for_bridge() updates
   2000   * node->ri with the configured bridge address.
   2001   * Prefer rs over md for consistency with the fascist_firewall_* functions.
   2002   * Check if the address or port are valid, and try another alternative
   2003   * if they are not. */
   2004 
   2005  /* Assume IPv4 and IPv6 dirports are the same */
   2006  if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr,
   2007                                         node->ri->ipv4_dirport, 0)) {
   2008    tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr);
   2009    ap_out->port = node->ri->ipv4_dirport;
   2010  } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr,
   2011                                                node->rs->ipv4_dirport, 0)) {
   2012    tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr);
   2013    ap_out->port = node->rs->ipv4_dirport;
   2014  } else {
   2015    tor_addr_make_null(&ap_out->addr, AF_INET6);
   2016    ap_out->port = 0;
   2017  }
   2018 }
   2019 
   2020 /** Return true iff <b>md</b> has a curve25519 onion key.
   2021 * Use node_has_curve25519_onion_key() instead of calling this directly. */
   2022 static int
   2023 microdesc_has_curve25519_onion_key(const microdesc_t *md)
   2024 {
   2025  if (!md) {
   2026    return 0;
   2027  }
   2028 
   2029  if (!md->onion_curve25519_pkey) {
   2030    return 0;
   2031  }
   2032 
   2033  if (fast_mem_is_zero((const char*)md->onion_curve25519_pkey->public_key,
   2034                      CURVE25519_PUBKEY_LEN)) {
   2035    return 0;
   2036  }
   2037 
   2038  return 1;
   2039 }
   2040 
   2041 /** Return true iff <b>node</b> has a curve25519 onion key. */
   2042 int
   2043 node_has_curve25519_onion_key(const node_t *node)
   2044 {
   2045  return node_get_curve25519_onion_key(node) != NULL;
   2046 }
   2047 
   2048 /** Return the curve25519 key of <b>node</b>, or NULL if none. */
   2049 const curve25519_public_key_t *
   2050 node_get_curve25519_onion_key(const node_t *node)
   2051 {
   2052  if (!node)
   2053    return NULL;
   2054  if (routerinfo_has_curve25519_onion_key(node->ri))
   2055    return node->ri->onion_curve25519_pkey;
   2056  else if (microdesc_has_curve25519_onion_key(node->md))
   2057    return node->md->onion_curve25519_pkey;
   2058  else
   2059    return NULL;
   2060 }
   2061 
   2062 /** Refresh the country code of <b>ri</b>.  This function MUST be called on
   2063 * each router when the GeoIP database is reloaded, and on all new routers. */
   2064 void
   2065 node_set_country(node_t *node)
   2066 {
   2067  const tor_addr_t *ipv4_addr = NULL;
   2068 
   2069  /* XXXXipv6 */
   2070  if (node->rs)
   2071    ipv4_addr = &node->rs->ipv4_addr;
   2072  else if (node->ri)
   2073    ipv4_addr = &node->ri->ipv4_addr;
   2074 
   2075  /* IPv4 is mandatory for a relay so this should not happen unless we are
   2076   * attempting to set the country code on a node without a descriptor. */
   2077  if (BUG(!ipv4_addr)) {
   2078    node->country = -1;
   2079    return;
   2080  }
   2081  node->country = geoip_get_country_by_addr(ipv4_addr);
   2082 }
   2083 
   2084 /** Set the country code of all routers in the routerlist. */
   2085 void
   2086 nodelist_refresh_countries(void)
   2087 {
   2088  const smartlist_t *nodes = nodelist_get_list();
   2089  SMARTLIST_FOREACH(nodes, node_t *, node,
   2090                    node_set_country(node));
   2091 }
   2092 
   2093 /** Return true iff router1 and router2 have similar enough network addresses
   2094 * that we should treat them as being in the same family */
   2095 int
   2096 router_addrs_in_same_network(const tor_addr_t *a1,
   2097                             const tor_addr_t *a2)
   2098 {
   2099  if (tor_addr_is_null(a1) || tor_addr_is_null(a2))
   2100    return 0;
   2101 
   2102  switch (tor_addr_family(a1)) {
   2103    case AF_INET:
   2104      return 0 == tor_addr_compare_masked(a1, a2, 16, CMP_SEMANTIC);
   2105    case AF_INET6:
   2106      return 0 == tor_addr_compare_masked(a1, a2, 32, CMP_SEMANTIC);
   2107    default:
   2108      /* If not IPv4 or IPv6, return 0. */
   2109      return 0;
   2110  }
   2111 }
   2112 
   2113 /** Return true if <b>node</b>'s nickname matches <b>nickname</b>
   2114 * (case-insensitive), or if <b>node's</b> identity key digest
   2115 * matches a hexadecimal value stored in <b>nickname</b>.  Return
   2116 * false otherwise. */
   2117 STATIC int
   2118 node_nickname_matches(const node_t *node, const char *nickname)
   2119 {
   2120  const char *n = node_get_nickname(node);
   2121  if (n && nickname[0]!='$' && !strcasecmp(n, nickname))
   2122    return 1;
   2123  return hex_digest_nickname_matches(nickname,
   2124                                     node->identity,
   2125                                     n);
   2126 }
   2127 
   2128 /** Return true iff <b>node</b> is named by some nickname in <b>lst</b>. */
   2129 STATIC int
   2130 node_in_nickname_smartlist(const smartlist_t *lst, const node_t *node)
   2131 {
   2132  if (!lst) return 0;
   2133  SMARTLIST_FOREACH(lst, const char *, name, {
   2134    if (node_nickname_matches(node, name))
   2135      return 1;
   2136  });
   2137  return 0;
   2138 }
   2139 
   2140 /** Return true iff n1's declared family contains n2. */
   2141 STATIC int
   2142 node_family_list_contains(const node_t *n1, const node_t *n2)
   2143 {
   2144  if (n1->ri && n1->ri->declared_family) {
   2145    return node_in_nickname_smartlist(n1->ri->declared_family, n2);
   2146  } else if (n1->md) {
   2147    return nodefamily_contains_node(n1->md->family, n2);
   2148  } else {
   2149    return 0;
   2150  }
   2151 }
   2152 
   2153 /**
   2154 * Return true iff <b>node</b> has declared a nonempty family.
   2155 **/
   2156 STATIC bool
   2157 node_has_declared_family_list(const node_t *node)
   2158 {
   2159  if (node->ri && node->ri->declared_family &&
   2160      smartlist_len(node->ri->declared_family)) {
   2161    return true;
   2162  }
   2163 
   2164  if (node->md && node->md->family) {
   2165    return true;
   2166  }
   2167 
   2168  return false;
   2169 }
   2170 
   2171 /**
   2172 * Return the listed family IDs of `a`, if it has any.
   2173 */
   2174 static const smartlist_t *
   2175 node_get_family_ids(const node_t *node)
   2176 {
   2177  if (node->ri && node->ri->family_ids) {
   2178    return node->ri->family_ids;
   2179  } else if (node->md && node->md->family_ids) {
   2180    return node->md->family_ids;
   2181  } else {
   2182    return NULL;
   2183  }
   2184 }
   2185 
   2186 /**
   2187 * Return true iff `a` and `b` have any family ID in common.
   2188 **/
   2189 static bool
   2190 nodes_have_common_family_id(const node_t *a, const node_t *b)
   2191 {
   2192  const smartlist_t *ids_a = node_get_family_ids(a);
   2193  const smartlist_t *ids_b = node_get_family_ids(b);
   2194  if (ids_a == NULL || ids_b == NULL)
   2195    return false;
   2196  SMARTLIST_FOREACH(ids_a, const char *, id, {
   2197      if (smartlist_contains_string(ids_b, id))
   2198        return true;
   2199    });
   2200  return false;
   2201 }
   2202 
   2203 /**
   2204 * Add to <b>out</b> every node_t that is listed by <b>node</b> as being in
   2205 * its family.  (Note that these nodes are not in node's family unless they
   2206 * also agree that node is in their family.)
   2207 **/
   2208 STATIC void
   2209 node_lookup_declared_family_list(smartlist_t *out, const node_t *node)
   2210 {
   2211  if (node->ri && node->ri->declared_family &&
   2212      smartlist_len(node->ri->declared_family)) {
   2213    SMARTLIST_FOREACH_BEGIN(node->ri->declared_family, const char *, name) {
   2214      const node_t *n2 = node_get_by_nickname(name, NNF_NO_WARN_UNNAMED);
   2215      if (n2) {
   2216        smartlist_add(out, (node_t *)n2);
   2217      }
   2218    } SMARTLIST_FOREACH_END(name);
   2219    return;
   2220  }
   2221 
   2222  if (node->md && node->md->family) {
   2223    nodefamily_add_nodes_to_smartlist(node->md->family, out);
   2224  }
   2225 }
   2226 
   2227 /** Return true iff r1 and r2 are in the same family, but not the same
   2228 * router. */
   2229 int
   2230 nodes_in_same_family(const node_t *node1, const node_t *node2)
   2231 {
   2232  const or_options_t *options = get_options();
   2233 
   2234  /* Are they in the same family because of their addresses? */
   2235  if (options->EnforceDistinctSubnets) {
   2236    tor_addr_t a1, a2;
   2237    node_get_addr(node1, &a1);
   2238    node_get_addr(node2, &a2);
   2239 
   2240    tor_addr_port_t ap6_1, ap6_2;
   2241    node_get_pref_ipv6_orport(node1, &ap6_1);
   2242    node_get_pref_ipv6_orport(node2, &ap6_2);
   2243 
   2244    if (router_addrs_in_same_network(&a1, &a2) ||
   2245        router_addrs_in_same_network(&ap6_1.addr, &ap6_2.addr))
   2246      return 1;
   2247  }
   2248 
   2249  /* Are they in the same family because they agree they are? */
   2250  if (use_family_lists &&
   2251      node_family_list_contains(node1, node2) &&
   2252      node_family_list_contains(node2, node1)) {
   2253    return 1;
   2254  }
   2255 
   2256  /* Are they in the same family because they have a common
   2257   * verified family ID? */
   2258  if (use_family_ids &&
   2259      nodes_have_common_family_id(node1, node2)) {
   2260    return 1;
   2261  }
   2262 
   2263  /* Are they in the same family because the user says they are? */
   2264  if (options->NodeFamilySets) {
   2265    SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
   2266        if (routerset_contains_node(rs, node1) &&
   2267            routerset_contains_node(rs, node2))
   2268          return 1;
   2269      });
   2270  }
   2271 
   2272  return 0;
   2273 }
   2274 
   2275 /**
   2276 * Add all the family of <b>node</b>, including <b>node</b> itself, to
   2277 * the smartlist <b>sl</b>.
   2278 *
   2279 * This is used to make sure we don't pick siblings in a single path, or
   2280 * pick more than one relay from a family for our entry guard list.
   2281 * Note that a node may be added to <b>sl</b> more than once if it is
   2282 * part of <b>node</b>'s family for more than one reason.
   2283 */
   2284 void
   2285 nodelist_add_node_and_family(smartlist_t *sl, const node_t *node)
   2286 {
   2287  const smartlist_t *all_nodes = nodelist_get_list();
   2288  const or_options_t *options = get_options();
   2289 
   2290  tor_assert(node);
   2291 
   2292  /* Let's make sure that we have the node itself, if it's a real node. */
   2293  {
   2294    const node_t *real_node = node_get_by_id(node->identity);
   2295    if (real_node)
   2296      smartlist_add(sl, (node_t*)real_node);
   2297  }
   2298 
   2299  /* First, add any nodes with similar network addresses. */
   2300  if (options->EnforceDistinctSubnets) {
   2301    tor_addr_t node_addr;
   2302    tor_addr_port_t node_ap6;
   2303    node_get_addr(node, &node_addr);
   2304    node_get_pref_ipv6_orport(node, &node_ap6);
   2305 
   2306    SMARTLIST_FOREACH_BEGIN(all_nodes, const node_t *, node2) {
   2307      tor_addr_t a;
   2308      tor_addr_port_t ap6;
   2309      node_get_addr(node2, &a);
   2310      node_get_pref_ipv6_orport(node2, &ap6);
   2311      if (router_addrs_in_same_network(&a, &node_addr) ||
   2312          router_addrs_in_same_network(&ap6.addr, &node_ap6.addr))
   2313        smartlist_add(sl, (void*)node2);
   2314    } SMARTLIST_FOREACH_END(node2);
   2315  }
   2316 
   2317  /* Now, add all nodes in the declared family of this node, if they
   2318   * also declare this node to be in their family. */
   2319  if (use_family_lists &&
   2320      node_has_declared_family_list(node)) {
   2321    smartlist_t *declared_family = smartlist_new();
   2322    node_lookup_declared_family_list(declared_family, node);
   2323 
   2324    /* Add every r such that router declares familyness with node, and node
   2325     * declares familyhood with router. */
   2326    SMARTLIST_FOREACH_BEGIN(declared_family, const node_t *, node2) {
   2327      if (node_family_list_contains(node2, node)) {
   2328        smartlist_add(sl, (void*)node2);
   2329      }
   2330    } SMARTLIST_FOREACH_END(node2);
   2331    smartlist_free(declared_family);
   2332  }
   2333 
   2334  /* Now add all the nodes that share a verified family ID with this node. */
   2335  if (use_family_ids &&
   2336      node_get_family_ids(node)) {
   2337    SMARTLIST_FOREACH(all_nodes, const node_t *, node2, {
   2338        if (nodes_have_common_family_id(node, node2)) {
   2339          smartlist_add(sl, (void *)node2);
   2340        }
   2341      });
   2342  }
   2343 
   2344  /* If the user declared any families locally, honor those too. */
   2345  if (options->NodeFamilySets) {
   2346    SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
   2347      if (routerset_contains_node(rs, node)) {
   2348        routerset_get_all_nodes(sl, rs, NULL, 0);
   2349      }
   2350    });
   2351  }
   2352 }
   2353 
   2354 /** Find a router that's up, that has this IP address, and
   2355 * that allows exit to this address:port, or return NULL if there
   2356 * isn't a good one.
   2357 * Don't exit enclave to excluded relays -- it wouldn't actually
   2358 * hurt anything, but this way there are fewer confused users.
   2359 */
   2360 const node_t *
   2361 router_find_exact_exit_enclave(const char *address, uint16_t port)
   2362 {/*XXXX MOVE*/
   2363  struct in_addr in;
   2364  tor_addr_t ipv4_addr;
   2365  const or_options_t *options = get_options();
   2366 
   2367  if (!tor_inet_aton(address, &in))
   2368    return NULL; /* it's not an IP already */
   2369  tor_addr_from_in(&ipv4_addr, &in);
   2370 
   2371  SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, {
   2372    if (tor_addr_eq(node_get_prim_addr_ipv4(node), &ipv4_addr) &&
   2373        node->is_running &&
   2374        compare_tor_addr_to_node_policy(&ipv4_addr, port, node) ==
   2375          ADDR_POLICY_ACCEPTED &&
   2376        !routerset_contains_node(options->ExcludeExitNodesUnion_, node))
   2377      return node;
   2378  });
   2379  return NULL;
   2380 }
   2381 
   2382 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
   2383 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
   2384 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
   2385 * bandwidth.
   2386 * If <b>need_guard</b>, we require that the router is a possible entry guard.
   2387 */
   2388 int
   2389 node_is_unreliable(const node_t *node, int need_uptime,
   2390                   int need_capacity, int need_guard)
   2391 {
   2392  if (need_uptime && !node->is_stable)
   2393    return 1;
   2394  if (need_capacity && !node->is_fast)
   2395    return 1;
   2396  if (need_guard && !node->is_possible_guard)
   2397    return 1;
   2398  return 0;
   2399 }
   2400 
   2401 /** Return 1 if all running sufficiently-stable routers we can use will reject
   2402 * addr:port. Return 0 if any might accept it. */
   2403 int
   2404 router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port,
   2405                                    int need_uptime)
   2406 {
   2407  addr_policy_result_t r;
   2408 
   2409  SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
   2410    if (node->is_running &&
   2411        !node_is_unreliable(node, need_uptime, 0, 0)) {
   2412 
   2413      r = compare_tor_addr_to_node_policy(addr, port, node);
   2414 
   2415      if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
   2416        return 0; /* this one could be ok. good enough. */
   2417    }
   2418  } SMARTLIST_FOREACH_END(node);
   2419  return 1; /* all will reject. */
   2420 }
   2421 
   2422 /** Mark the router with ID <b>digest</b> as running or non-running
   2423 * in our routerlist. */
   2424 void
   2425 router_set_status(const char *digest, int up)
   2426 {
   2427  node_t *node;
   2428  tor_assert(digest);
   2429 
   2430  SMARTLIST_FOREACH(router_get_fallback_dir_servers(),
   2431                    dir_server_t *, d,
   2432                    if (tor_memeq(d->digest, digest, DIGEST_LEN))
   2433                      d->is_running = up);
   2434 
   2435  SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
   2436                    dir_server_t *, d,
   2437                    if (tor_memeq(d->digest, digest, DIGEST_LEN))
   2438                      d->is_running = up);
   2439 
   2440  node = node_get_mutable_by_id(digest);
   2441  if (node) {
   2442 #if 0
   2443    log_debug(LD_DIR,"Marking router %s as %s.",
   2444              node_describe(node), up ? "up" : "down");
   2445 #endif
   2446    if (!up && node_is_me(node) && !net_is_disabled())
   2447      log_warn(LD_NET, "We just marked ourself as down. Are your external "
   2448               "addresses reachable?");
   2449 
   2450    if (bool_neq(node->is_running, up))
   2451      router_dir_info_changed();
   2452 
   2453    node->is_running = up;
   2454  }
   2455 }
   2456 
   2457 /** True iff, the last time we checked whether we had enough directory info
   2458 * to build circuits, the answer was "yes". If there are no exits in the
   2459 * consensus, we act as if we have 100% of the exit directory info. */
   2460 static int have_min_dir_info = 0;
   2461 
   2462 /** Does the consensus contain nodes that can exit? */
   2463 static consensus_path_type_t have_consensus_path = CONSENSUS_PATH_UNKNOWN;
   2464 
   2465 /** True iff enough has changed since the last time we checked whether we had
   2466 * enough directory info to build circuits that our old answer can no longer
   2467 * be trusted. */
   2468 static int need_to_update_have_min_dir_info = 1;
   2469 /** String describing what we're missing before we have enough directory
   2470 * info. */
   2471 static char dir_info_status[512] = "";
   2472 
   2473 /** Return true iff we have enough consensus information to
   2474 * start building circuits.  Right now, this means "a consensus that's
   2475 * less than a day old, and at least 60% of router descriptors (configurable),
   2476 * weighted by bandwidth. Treat the exit fraction as 100% if there are
   2477 * no exits in the consensus."
   2478 * To obtain the final weighted bandwidth, we multiply the
   2479 * weighted bandwidth fraction for each position (guard, middle, exit). */
   2480 MOCK_IMPL(int,
   2481 router_have_minimum_dir_info,(void))
   2482 {
   2483  static int logged_delay=0;
   2484  const char *delay_fetches_msg = NULL;
   2485  if (should_delay_dir_fetches(get_options(), &delay_fetches_msg)) {
   2486    if (!logged_delay)
   2487      log_notice(LD_DIR, "Delaying directory fetches: %s", delay_fetches_msg);
   2488    logged_delay=1;
   2489    strlcpy(dir_info_status, delay_fetches_msg,  sizeof(dir_info_status));
   2490    return 0;
   2491  }
   2492  logged_delay = 0; /* reset it if we get this far */
   2493 
   2494  if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
   2495    update_router_have_minimum_dir_info();
   2496  }
   2497 
   2498  return have_min_dir_info;
   2499 }
   2500 
   2501 /** Set to CONSENSUS_PATH_EXIT if there is at least one exit node
   2502 * in the consensus. We update this flag in compute_frac_paths_available if
   2503 * there is at least one relay that has an Exit flag in the consensus.
   2504 * Used to avoid building exit circuits when they will almost certainly fail.
   2505 * Set to CONSENSUS_PATH_INTERNAL if there are no exits in the consensus.
   2506 * (This situation typically occurs during bootstrap of a test network.)
   2507 * Set to CONSENSUS_PATH_UNKNOWN if we have never checked, or have
   2508 * reason to believe our last known value was invalid or has expired.
   2509 * If we're in a network with TestingDirAuthVoteExit set,
   2510 * this can cause router_have_consensus_path() to be set to
   2511 * CONSENSUS_PATH_EXIT, even if there are no nodes with accept exit policies.
   2512 */
   2513 MOCK_IMPL(consensus_path_type_t,
   2514 router_have_consensus_path, (void))
   2515 {
   2516  return have_consensus_path;
   2517 }
   2518 
   2519 /** Called when our internal view of the directory has changed.  This can be
   2520 * when the authorities change, networkstatuses change, the list of routerdescs
   2521 * changes, or number of running routers changes.
   2522 */
   2523 void
   2524 router_dir_info_changed(void)
   2525 {
   2526  need_to_update_have_min_dir_info = 1;
   2527  hs_service_dir_info_changed();
   2528  hs_client_dir_info_changed();
   2529 }
   2530 
   2531 /** Return a string describing what we're missing before we have enough
   2532 * directory info. */
   2533 const char *
   2534 get_dir_info_status_string(void)
   2535 {
   2536  return dir_info_status;
   2537 }
   2538 
   2539 /** Iterate over the servers listed in <b>consensus</b>, and count how many of
   2540 * them seem like ones we'd use (store this in *<b>num_usable</b>), and how
   2541 * many of <em>those</em> we have descriptors for (store this in
   2542 * *<b>num_present</b>).
   2543 *
   2544 * If <b>in_set</b> is non-NULL, only consider those routers in <b>in_set</b>.
   2545 * If <b>exit_only</b> & USABLE_DESCRIPTOR_EXIT_POLICY, only consider nodes
   2546 * present if they have an exit policy that accepts at least one port.
   2547 * If <b>exit_only</b> & USABLE_DESCRIPTOR_EXIT_FLAG, only consider nodes
   2548 * usable if they have the exit flag in the consensus.
   2549 *
   2550 * If *<b>descs_out</b> is present, add a node_t for each usable descriptor
   2551 * to it.
   2552 */
   2553 static void
   2554 count_usable_descriptors(int *num_present, int *num_usable,
   2555                         smartlist_t *descs_out,
   2556                         const networkstatus_t *consensus,
   2557                         time_t now,
   2558                         routerset_t *in_set,
   2559                         usable_descriptor_t exit_only)
   2560 {
   2561  const int md = (consensus->flavor == FLAV_MICRODESC);
   2562  *num_present = 0, *num_usable = 0;
   2563 
   2564  SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *, rs)
   2565    {
   2566       const node_t *node = node_get_by_id(rs->identity_digest);
   2567       if (!node)
   2568         continue; /* This would be a bug: every entry in the consensus is
   2569                    * supposed to have a node. */
   2570       if ((exit_only & USABLE_DESCRIPTOR_EXIT_FLAG) && ! rs->is_exit)
   2571         continue;
   2572       if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1))
   2573         continue;
   2574       if (client_would_use_router(rs, now)) {
   2575         const char * const digest = rs->descriptor_digest;
   2576         int present;
   2577         ++*num_usable; /* the consensus says we want it. */
   2578         if (md)
   2579           present = NULL != microdesc_cache_lookup_by_digest256(NULL, digest);
   2580         else
   2581           present = NULL != router_get_by_descriptor_digest(digest);
   2582         if (present) {
   2583           /* Do the policy check last, because it requires a descriptor,
   2584            * and is potentially expensive */
   2585           if ((exit_only & USABLE_DESCRIPTOR_EXIT_POLICY) &&
   2586               node_exit_policy_rejects_all(node)) {
   2587               continue;
   2588           }
   2589           /* we have the descriptor listed in the consensus, and it
   2590            * satisfies our exit constraints (if any) */
   2591           ++*num_present;
   2592         }
   2593         if (descs_out)
   2594           smartlist_add(descs_out, (node_t*)node);
   2595       }
   2596     }
   2597  SMARTLIST_FOREACH_END(rs);
   2598 
   2599  log_debug(LD_DIR, "%d usable, %d present (%s%s%s%s%s).",
   2600            *num_usable, *num_present,
   2601            md ? "microdesc" : "desc",
   2602            (exit_only & USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG) ?
   2603              " exit"     : "s",
   2604            (exit_only & USABLE_DESCRIPTOR_EXIT_POLICY) ?
   2605              " policies" : "" ,
   2606            (exit_only == USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG) ?
   2607              " and" : "" ,
   2608            (exit_only & USABLE_DESCRIPTOR_EXIT_FLAG) ?
   2609              " flags"    : "" );
   2610 }
   2611 
   2612 /** Return an estimate of which fraction of usable paths through the Tor
   2613 * network we have available for use.  Count how many routers seem like ones
   2614 * we'd use (store this in *<b>num_usable_out</b>), and how many of
   2615 * <em>those</em> we have descriptors for (store this in
   2616 * *<b>num_present_out</b>.)
   2617 *
   2618 * If **<b>status_out</b> is present, allocate a new string and print the
   2619 * available percentages of guard, middle, and exit nodes to it, noting
   2620 * whether there are exits in the consensus.
   2621 * If there are no exits in the consensus, we treat the exit fraction as 100%,
   2622 * but set router_have_consensus_path() so that we can only build internal
   2623 * paths. */
   2624 static double
   2625 compute_frac_paths_available(const networkstatus_t *consensus,
   2626                             const or_options_t *options, time_t now,
   2627                             int *num_present_out, int *num_usable_out,
   2628                             char **status_out)
   2629 {
   2630  smartlist_t *guards = smartlist_new();
   2631  smartlist_t *mid    = smartlist_new();
   2632  smartlist_t *exits  = smartlist_new();
   2633  double f_guard, f_mid, f_exit;
   2634  double f_path = 0.0;
   2635  /* Used to determine whether there are any exits in the consensus */
   2636  int np = 0;
   2637  /* Used to determine whether there are any exits with descriptors */
   2638  int nu = 0;
   2639  const int authdir = authdir_mode_v3(options);
   2640 
   2641  count_usable_descriptors(num_present_out, num_usable_out,
   2642                           mid, consensus, now, options->MiddleNodes,
   2643                           USABLE_DESCRIPTOR_ALL);
   2644  log_debug(LD_NET,
   2645            "%s: %d present, %d usable",
   2646            "mid",
   2647            np,
   2648            nu);
   2649 
   2650  if (options->EntryNodes) {
   2651    count_usable_descriptors(&np, &nu, guards, consensus, now,
   2652                             options->EntryNodes, USABLE_DESCRIPTOR_ALL);
   2653    log_debug(LD_NET,
   2654              "%s: %d present, %d usable",
   2655              "guard",
   2656              np,
   2657              nu);
   2658  } else {
   2659    SMARTLIST_FOREACH(mid, const node_t *, node, {
   2660      if (authdir) {
   2661        if (node->rs && node->rs->is_possible_guard)
   2662          smartlist_add(guards, (node_t*)node);
   2663      } else {
   2664        if (node->is_possible_guard)
   2665          smartlist_add(guards, (node_t*)node);
   2666      }
   2667    });
   2668    log_debug(LD_NET,
   2669              "%s: %d possible",
   2670              "guard",
   2671              smartlist_len(guards));
   2672  }
   2673 
   2674  /* All nodes with exit policy and flag */
   2675  count_usable_descriptors(&np, &nu, exits, consensus, now,
   2676                           NULL, USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG);
   2677  log_debug(LD_NET,
   2678            "%s: %d present, %d usable",
   2679            "exits",
   2680            np,
   2681            nu);
   2682 
   2683  /* We need at least 1 exit (flag and policy) in the consensus to consider
   2684   * building exit paths */
   2685  /* Update our understanding of whether the consensus has exits */
   2686  consensus_path_type_t old_have_consensus_path = have_consensus_path;
   2687  have_consensus_path = ((np > 0) ?
   2688                         CONSENSUS_PATH_EXIT :
   2689                         CONSENSUS_PATH_INTERNAL);
   2690 
   2691  if (old_have_consensus_path != have_consensus_path) {
   2692    if (have_consensus_path == CONSENSUS_PATH_INTERNAL) {
   2693      log_notice(LD_NET,
   2694                 "The current consensus has no exit nodes. "
   2695                 "Tor can only build internal paths, "
   2696                 "such as paths to onion services.");
   2697 
   2698      /* However, exit nodes can reachability self-test using this consensus,
   2699       * join the network, and appear in a later consensus. This will allow
   2700       * the network to build exit paths, such as paths for world wide web
   2701       * browsing (as distinct from hidden service web browsing). */
   2702    } else if (old_have_consensus_path == CONSENSUS_PATH_INTERNAL) {
   2703      log_notice(LD_NET,
   2704                 "The current consensus contains exit nodes. "
   2705                 "Tor can build exit and internal paths.");
   2706    }
   2707  }
   2708 
   2709  f_guard = frac_nodes_with_descriptors(guards, WEIGHT_FOR_GUARD, 1);
   2710  f_mid   = frac_nodes_with_descriptors(mid,    WEIGHT_FOR_MID,   0);
   2711  f_exit  = frac_nodes_with_descriptors(exits,  WEIGHT_FOR_EXIT,  0);
   2712 
   2713  /* If we are using bridges and have at least one bridge with a full
   2714   * descriptor, assume f_guard is 1.0. */
   2715  if (options->UseBridges && num_bridges_usable(0) > 0)
   2716    f_guard = 1.0;
   2717 
   2718  log_debug(LD_NET,
   2719            "f_guard: %.2f, f_mid: %.2f, f_exit: %.2f",
   2720             f_guard,
   2721             f_mid,
   2722             f_exit);
   2723 
   2724  smartlist_free(guards);
   2725  smartlist_free(mid);
   2726  smartlist_free(exits);
   2727 
   2728  if (options->ExitNodes) {
   2729    double f_myexit, f_myexit_unflagged;
   2730    smartlist_t *myexits= smartlist_new();
   2731    smartlist_t *myexits_unflagged = smartlist_new();
   2732 
   2733    /* All nodes with exit policy and flag in ExitNodes option */
   2734    count_usable_descriptors(&np, &nu, myexits, consensus, now,
   2735                             options->ExitNodes,
   2736                             USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG);
   2737    log_debug(LD_NET,
   2738              "%s: %d present, %d usable",
   2739              "myexits",
   2740              np,
   2741              nu);
   2742 
   2743    /* Now compute the nodes in the ExitNodes option where we know their exit
   2744     * policy permits something. */
   2745    count_usable_descriptors(&np, &nu, myexits_unflagged,
   2746                             consensus, now,
   2747                             options->ExitNodes,
   2748                             USABLE_DESCRIPTOR_EXIT_POLICY);
   2749    log_debug(LD_NET,
   2750              "%s: %d present, %d usable",
   2751              "myexits_unflagged (initial)",
   2752              np,
   2753              nu);
   2754 
   2755    f_myexit= frac_nodes_with_descriptors(myexits,WEIGHT_FOR_EXIT, 0);
   2756    f_myexit_unflagged=
   2757              frac_nodes_with_descriptors(myexits_unflagged,
   2758                                          WEIGHT_FOR_EXIT, 0);
   2759 
   2760    log_debug(LD_NET,
   2761              "f_exit: %.2f, f_myexit: %.2f, f_myexit_unflagged: %.2f",
   2762              f_exit,
   2763              f_myexit,
   2764              f_myexit_unflagged);
   2765 
   2766    /* If our ExitNodes list has eliminated every possible Exit node, and there
   2767     * were some possible Exit nodes, then instead consider nodes that permit
   2768     * exiting to some ports. */
   2769    if (smartlist_len(myexits) == 0 &&
   2770        smartlist_len(myexits_unflagged)) {
   2771      f_myexit = f_myexit_unflagged;
   2772    }
   2773 
   2774    smartlist_free(myexits);
   2775    smartlist_free(myexits_unflagged);
   2776 
   2777    /* This is a tricky point here: we don't want to make it easy for a
   2778     * directory to trickle exits to us until it learns which exits we have
   2779     * configured, so require that we have a threshold both of total exits
   2780     * and usable exits. */
   2781    if (f_myexit < f_exit)
   2782      f_exit = f_myexit;
   2783  }
   2784 
   2785  /* If the consensus has no exits that pass flag, descriptor, and policy
   2786   * checks, we can only build onion service paths, which are G - M - M. */
   2787  if (router_have_consensus_path() != CONSENSUS_PATH_EXIT) {
   2788    /* If the exit bandwidth weight fraction is not zero, we need to wait for
   2789     * descriptors for those exits. (The bandwidth weight fraction does not
   2790     * check for descriptors.)
   2791     * If the exit bandwidth fraction is zero, there are no exits in the
   2792     * consensus at all. So it is safe to replace f_exit with f_mid.
   2793     *
   2794     * f_exit is non-negative, but some compilers complain about float and ==
   2795     */
   2796    if (f_exit <= 0.0) {
   2797      f_exit = f_mid;
   2798    }
   2799  }
   2800 
   2801  f_path = f_guard * f_mid * f_exit;
   2802 
   2803  if (status_out)
   2804    tor_asprintf(status_out,
   2805                 "%d%% of guards bw, "
   2806                 "%d%% of midpoint bw, and "
   2807                 "%d%% of %s = "
   2808                 "%d%% of path bw",
   2809                 (int)(f_guard*100),
   2810                 (int)(f_mid*100),
   2811                 (int)(f_exit*100),
   2812                 (router_have_consensus_path() == CONSENSUS_PATH_EXIT ?
   2813                  "exit bw" :
   2814                  "end bw (no exits in consensus, using mid)"),
   2815                 (int)(f_path*100));
   2816 
   2817  return f_path;
   2818 }
   2819 
   2820 /** We just fetched a new set of descriptors. Compute how far through
   2821 * the "loading descriptors" bootstrapping phase we are, so we can inform
   2822 * the controller of our progress. */
   2823 int
   2824 count_loading_descriptors_progress(void)
   2825 {
   2826  int num_present = 0, num_usable=0;
   2827  time_t now = time(NULL);
   2828  const or_options_t *options = get_options();
   2829  const networkstatus_t *consensus =
   2830    networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
   2831  double paths, fraction;
   2832 
   2833  if (!consensus)
   2834    return 0; /* can't count descriptors if we have no list of them */
   2835 
   2836  paths = compute_frac_paths_available(consensus, options, now,
   2837                                       &num_present, &num_usable,
   2838                                       NULL);
   2839 
   2840  fraction = paths / get_frac_paths_needed_for_circs(options,consensus);
   2841  if (fraction > 1.0)
   2842    return 0; /* it's not the number of descriptors holding us back */
   2843  return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
   2844    (fraction*(BOOTSTRAP_STATUS_ENOUGH_DIRINFO-1 -
   2845               BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
   2846 }
   2847 
   2848 /** Return the fraction of paths needed before we're willing to build
   2849 * circuits, as configured in <b>options</b>, or in the consensus <b>ns</b>. */
   2850 static double
   2851 get_frac_paths_needed_for_circs(const or_options_t *options,
   2852                                const networkstatus_t *ns)
   2853 {
   2854 #define DFLT_PCT_USABLE_NEEDED 60
   2855  if (options->PathsNeededToBuildCircuits >= 0.0) {
   2856    return options->PathsNeededToBuildCircuits;
   2857  } else {
   2858    return networkstatus_get_param(ns, "min_paths_for_circs_pct",
   2859                                   DFLT_PCT_USABLE_NEEDED,
   2860                                   25, 95)/100.0;
   2861  }
   2862 }
   2863 
   2864 /** Change the value of have_min_dir_info, setting it true iff we have enough
   2865 * network and router information to build circuits.  Clear the value of
   2866 * need_to_update_have_min_dir_info. */
   2867 static void
   2868 update_router_have_minimum_dir_info(void)
   2869 {
   2870  time_t now = time(NULL);
   2871  int res;
   2872  int num_present=0, num_usable=0;
   2873  const or_options_t *options = get_options();
   2874  const networkstatus_t *consensus =
   2875    networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
   2876  int using_md;
   2877  static int be_loud_when_things_work_again = 0;
   2878 
   2879  if (!consensus) {
   2880    if (!networkstatus_get_latest_consensus())
   2881      strlcpy(dir_info_status, "We have no usable consensus.",
   2882              sizeof(dir_info_status));
   2883    else
   2884      strlcpy(dir_info_status, "We have no recent usable consensus.",
   2885              sizeof(dir_info_status));
   2886    res = 0;
   2887    goto done;
   2888  }
   2889 
   2890  using_md = consensus->flavor == FLAV_MICRODESC;
   2891 
   2892  /* Check fraction of available paths */
   2893  {
   2894    char *status = NULL;
   2895    double paths = compute_frac_paths_available(consensus, options, now,
   2896                                                &num_present, &num_usable,
   2897                                                &status);
   2898 
   2899    if (paths < get_frac_paths_needed_for_circs(options,consensus)) {
   2900      tor_snprintf(dir_info_status, sizeof(dir_info_status),
   2901                   "We need more %sdescriptors: we have %d/%d, and "
   2902                   "can only build %d%% of likely paths. (We have %s.)",
   2903                   using_md?"micro":"", num_present, num_usable,
   2904                   (int)(paths*100), status);
   2905      tor_free(status);
   2906      res = 0;
   2907      control_event_boot_dir(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
   2908      goto done;
   2909    }
   2910 
   2911    tor_free(status);
   2912    res = 1;
   2913  }
   2914 
   2915  { /* Check entry guard dirinfo status */
   2916    char *guard_error = entry_guards_get_err_str_if_dir_info_missing(using_md,
   2917                                                             num_present,
   2918                                                             num_usable);
   2919    if (guard_error) {
   2920      strlcpy(dir_info_status, guard_error, sizeof(dir_info_status));
   2921      tor_free(guard_error);
   2922      res = 0;
   2923      goto done;
   2924    }
   2925  }
   2926 
   2927 done:
   2928 
   2929  /* If paths have just become available in this update. */
   2930  if (res && !have_min_dir_info) {
   2931    control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
   2932    control_event_boot_dir(BOOTSTRAP_STATUS_ENOUGH_DIRINFO, 0);
   2933    tor_log(be_loud_when_things_work_again ? LOG_NOTICE : LOG_INFO, LD_DIR,
   2934            "We now have enough directory information to build circuits.");
   2935    be_loud_when_things_work_again = 0;
   2936  }
   2937 
   2938  /* If paths have just become unavailable in this update. */
   2939  if (!res && have_min_dir_info) {
   2940    int quiet = dirclient_too_idle_to_fetch_descriptors(options, now);
   2941    tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
   2942        "Our directory information is no longer up-to-date "
   2943        "enough to build circuits: %s", dir_info_status);
   2944    if (!quiet) {
   2945      /* remember to do a notice-level log when things come back */
   2946      be_loud_when_things_work_again = 1;
   2947    }
   2948 
   2949    /* a) make us log when we next complete a circuit, so we know when Tor
   2950     * is back up and usable, and b) disable some activities that Tor
   2951     * should only do while circuits are working, like reachability tests
   2952     * and fetching bridge descriptors only over circuits. */
   2953    note_that_we_maybe_cant_complete_circuits();
   2954    have_consensus_path = CONSENSUS_PATH_UNKNOWN;
   2955    control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
   2956  }
   2957  have_min_dir_info = res;
   2958  need_to_update_have_min_dir_info = 0;
   2959 }