Back to index

tor  0.2.3.19-rc
Defines | Functions
routerlist.h File Reference

Header file for routerlist.c. More...

This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Defines

#define router_digest_is_trusted_dir(d)   router_digest_is_trusted_dir_type((d), NO_DIRINFO)

Functions

int get_n_authorities (dirinfo_type_t type)
 Return the number of directory authorities whose type matches some bit set in type
int trusted_dirs_reload_certs (void)
 Reload the cached v3 key certificates from the cached-certs file in the data directory.
int trusted_dirs_load_certs_from_string (const char *contents, int from_store, int flush)
 Load a bunch of new key certificates from the string contents.
void trusted_dirs_flush_certs_to_disk (void)
 Save all v3 key certificates to the cached-certs file.
authority_cert_tauthority_cert_get_newest_by_id (const char *id_digest)
 Return the newest v3 authority certificate whose v3 authority identity key has digest id_digest.
authority_cert_tauthority_cert_get_by_sk_digest (const char *sk_digest)
 Return the newest v3 authority certificate whose directory signing key has digest sk_digest.
authority_cert_tauthority_cert_get_by_digests (const char *id_digest, const char *sk_digest)
 Return the v3 authority certificate with signing key matching sk_digest, for the authority with identity digest id_digest.
void authority_cert_get_all (smartlist_t *certs_out)
 Add every known authority_cert_t to certs_out.
void authority_cert_dl_failed (const char *id_digest, int status)
 Called when an attempt to download a certificate with the authority with ID id_digest fails with HTTP response code status: remember the failure, so we don't try again immediately.
void authority_certs_fetch_missing (networkstatus_t *status, time_t now)
 Try to download any v3 authority certificates that we may be missing.
int router_reload_router_list (void)
 Load all cached router descriptors and extra-info documents from the store.
int authority_cert_dl_looks_uncertain (const char *id_digest)
 Return true iff when we've been getting enough failures when trying to download the certificate with ID digest id_digest that we're willing to start bugging the user about it.
smartlist_trouter_get_trusted_dir_servers (void)
 Return a smartlist containing a list of trusted_dir_server_t * for all known trusted dirservers.
const routerstatus_trouter_pick_directory_server (dirinfo_type_t type, int flags)
 Try to find a running dirserver that supports operations of type.
trusted_dir_server_trouter_get_trusteddirserver_by_digest (const char *d)
 Return the trusted_dir_server_t for the directory authority whose identity key hashes to digest, or NULL if no such authority is known.
trusted_dir_server_ttrusteddirserver_get_by_v3_auth_digest (const char *d)
 Return the trusted_dir_server_t for the directory authority whose v3 identity key hashes to digest, or NULL if no such authority is known.
const routerstatus_trouter_pick_trusteddirserver (dirinfo_type_t type, int flags)
 Try to find a running trusted dirserver.
int router_get_my_share_of_directory_requests (double *v2_share_out, double *v3_share_out)
 Try to determine which fraction of v2 and v3 directory requests aimed at caches will be sent to us.
void router_reset_status_download_failures (void)
 Reset all internal variables used to count failed downloads of network status objects.
int routers_have_same_or_addr (const routerinfo_t *r1, const routerinfo_t *r2)
 Return true iff r1 and r2 have the same address and OR port.
int router_nickname_is_in_list (const routerinfo_t *router, const char *list)
 Return 1 iff any member of the (possibly NULL) comma-separated list list is an acceptable nickname or hexdigest for router.
const routerinfo_trouterlist_find_my_routerinfo (void)
 Look through the routerlist until we find a router that has my key.
const node_trouter_find_exact_exit_enclave (const char *address, uint16_t port)
 Find a router that's up, that has this IP address, and that allows exit to this address:port, or return NULL if there isn't a good one.
int node_is_unreliable (const node_t *router, int need_uptime, int need_capacity, int need_guard)
 Return 1 if router is not suitable for these parameters, else 0.
uint32_t router_get_advertised_bandwidth (const routerinfo_t *router)
 Return the smaller of the router's configured BandwidthRate and its advertised capacity.
uint32_t router_get_advertised_bandwidth_capped (const routerinfo_t *router)
 Return the smaller of the router's configured BandwidthRate and its advertised capacity, capped by max-believe-bw.
const node_tnode_sl_choose_by_bandwidth (smartlist_t *sl, bandwidth_weight_rule_t rule)
 Choose a random element of status list sl, weighted by the advertised bandwidth of each node.
const node_trouter_choose_random_node (smartlist_t *excludedsmartlist, struct routerset_t *excludedset, router_crn_flags_t flags)
 Return a random running node from the nodelist.
const routerinfo_trouter_get_by_nickname (const char *nickname, int warn_if_unnamed)
 Return the router in our routerlist whose (case-insensitive) nickname or (case-sensitive) hexadecimal key digest is nickname.
int router_is_named (const routerinfo_t *router)
 Return true iff router is listed as named in the current consensus.
int router_digest_is_trusted_dir_type (const char *digest, dirinfo_type_t type)
 Return true iff digest is the digest of the identity key of a trusted directory matching at least one bit of type.
int router_addr_is_trusted_dir (uint32_t addr)
 Return true iff addr is the address of one of our trusted directory authorities.
int hexdigest_to_digest (const char *hexdigest, char *digest)
 If hexdigest is correctly formed, base16_decode it into digest, which must have DIGEST_LEN space in it.
const routerinfo_trouter_get_by_hexdigest (const char *hexdigest)
 Return the router in our routerlist whose hexadecimal key digest is hexdigest.
const routerinfo_trouter_get_by_id_digest (const char *digest)
 Return the router in our routerlist whose 20-byte key digest is digest.
routerinfo_trouter_get_mutable_by_digest (const char *digest)
 As router_get_by_id_digest,but return a pointer that you're allowed to modify.
signed_descriptor_trouter_get_by_descriptor_digest (const char *digest)
 Return the router in our routerlist whose 20-byte descriptor is digest.
signed_descriptor_trouter_get_by_extrainfo_digest (const char *digest)
 Return the signed descriptor for the router in our routerlist whose 20-byte extra-info digest is digest.
signed_descriptor_textrainfo_get_by_descriptor_digest (const char *digest)
 Return the signed descriptor for the extrainfo_t in our routerlist whose extra-info-digest is digest.
const char * signed_descriptor_get_body (const signed_descriptor_t *desc)
 Return a pointer to the signed textual representation of a descriptor.
const char * signed_descriptor_get_annotations (const signed_descriptor_t *desc)
 As signed_descriptor_get_body(), but points to the beginning of the annotations section rather than the beginning of the descriptor.
routerlist_trouter_get_routerlist (void)
 Return the current list of all known routers.
void routerinfo_free (routerinfo_t *router)
 Free all storage held by router.
void extrainfo_free (extrainfo_t *extrainfo)
 Release all storage held by extrainfo
void routerlist_free (routerlist_t *rl)
 Free all storage held by a routerlist rl.
void dump_routerlist_mem_usage (int severity)
 Log information about how much memory is being used for routerlist, at log level severity.
void routerlist_remove (routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
 Remove an item ri from the routerlist rl, updating indices as needed.
void routerlist_free_all (void)
 Free all memory held by the routerlist module.
void routerlist_reset_warnings (void)
 Forget that we have issued any router-related warnings, so that we'll warn again if we see the same errors.
void router_set_status (const char *digest, int up)
 Mark the router with ID digest as running or non-running in our routerlist.
static int WRA_WAS_ADDED (was_router_added_t s)
 Return true iff the outcome code in s indicates that the descriptor was added.
static int WRA_WAS_OUTDATED (was_router_added_t s)
 Return true iff the outcome code in s indicates that the descriptor was not added because it was either:
static int WRA_WAS_REJECTED (was_router_added_t s)
 Return true iff the outcome code in s indicates that the descriptor was flat-out rejected.
was_router_added_t router_add_to_routerlist (routerinfo_t *router, const char **msg, int from_cache, int from_fetch)
 Add router to the routerlist, if we don't already have it.
was_router_added_t router_add_extrainfo_to_routerlist (extrainfo_t *ei, const char **msg, int from_cache, int from_fetch)
 Insert ei into the routerlist, or free it.
void routerlist_descriptors_added (smartlist_t *sl, int from_cache)
 We just added a new set of descriptors.
void routerlist_remove_old_routers (void)
 Deactivate any routers from the routerlist that are more than ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses; remove old routers from the list of cached routers if we have too many.
int router_load_single_router (const char *s, uint8_t purpose, int cache, const char **msg)
 Code to parse a single router descriptor and insert it into the routerlist.
int router_load_routers_from_string (const char *s, const char *eos, saved_location_t saved_location, smartlist_t *requested_fingerprints, int descriptor_digests, const char *prepend_annotations)
 Given a string s containing some routerdescs, parse it and put the routers into our directory.
void router_load_extrainfo_from_string (const char *s, const char *eos, saved_location_t saved_location, smartlist_t *requested_fingerprints, int descriptor_digests)
 Parse one or more extrainfos from s (ending immediately before eos if eos is present).
void routerlist_retry_directory_downloads (time_t now)
 Clear all our timeouts for fetching v2 and v3 directory stuff, and then give it all a try again.
int router_exit_policy_all_nodes_reject (const tor_addr_t *addr, uint16_t port, int need_uptime)
 Return 1 if all running sufficiently-stable routers we can use will reject addr:port, return 0 if any might accept it.
int router_exit_policy_rejects_all (const routerinfo_t *router)
 Return true iff router does not permit exit streams.
trusted_dir_server_tadd_trusted_dir_server (const char *nickname, const char *address, uint16_t dir_port, uint16_t or_port, const char *digest, const char *v3_auth_digest, dirinfo_type_t type)
 Add to the list of authoritative directory servers one at address:port, with identity key digest.
void authority_cert_free (authority_cert_t *cert)
 Free storage held in cert.
void clear_trusted_dir_servers (void)
 Remove all members from the list of trusted dir servers.
int any_trusted_dir_is_v1_authority (void)
 Return 1 if any trusted dir server supports v1 directories, else return 0.
void update_consensus_router_descriptor_downloads (time_t now, int is_vote, networkstatus_t *consensus)
 For any descriptor that we want that's currently listed in consensus, download it as appropriate.
void update_router_descriptor_downloads (time_t now)
 Launch downloads for router status as needed.
void update_all_descriptor_downloads (time_t now)
 Update downloads for router descriptors and/or microdescriptors as appropriate.
void update_extrainfo_downloads (time_t now)
 Launch extrainfo downloads as needed.
int router_have_minimum_dir_info (void)
 Return true iff we have enough networkstatus and router information to start building circuits.
void router_dir_info_changed (void)
 Called when our internal view of the directory has changed.
const char * get_dir_info_status_string (void)
 Return a string describing what we're missing before we have enough directory info.
int count_loading_descriptors_progress (void)
 We just fetched a new set of descriptors.
void router_reset_descriptor_download_failures (void)
 Reset the descriptor download failure count on all routers, so that we can retry any long-failed routers immediately.
int router_differences_are_cosmetic (const routerinfo_t *r1, const routerinfo_t *r2)
 Return true iff the only differences between r1 and r2 are such that would not cause a recent (post 0.1.1.6) dirserver to republish.
int routerinfo_incompatible_with_extrainfo (const routerinfo_t *ri, extrainfo_t *ei, signed_descriptor_t *sd, const char **msg)
 Check whether ri (a.k.a.
void routerlist_assert_ok (const routerlist_t *rl)
 Assert that the internal representation of rl is self-consistent.
const char * esc_router_info (const routerinfo_t *router)
 Allocate and return a new string representing the contact info and platform string for router, surrounded by quotes and using standard C escapes.
void routers_sort_by_identity (smartlist_t *routers)
 Sort a list of routerinfo_t in ascending order of identity digest.
routerset_trouterset_new (void)
 Return a new empty routerset.
void routerset_refresh_countries (routerset_t *rs)
 Update the routerset's countries bitarray_t.
int routerset_parse (routerset_t *target, const char *s, const char *description)
 Parse the string s to create a set of routerset entries, and add them to target.
void routerset_union (routerset_t *target, const routerset_t *source)
 Add all members of the set source to target.
int routerset_is_list (const routerset_t *set)
 Return true iff set lists only nicknames and digests, and includes no IP ranges or countries.
int routerset_needs_geoip (const routerset_t *set)
 Return true iff we need a GeoIP IP-to-country database to make sense of set.
int routerset_is_empty (const routerset_t *set)
 Return true iff there are no entries in set.
int routerset_contains_router (const routerset_t *set, const routerinfo_t *ri, country_t country)
 Return true iff ri is in set.
int routerset_contains_routerstatus (const routerset_t *set, const routerstatus_t *rs, country_t country)
 Return true iff rs is in set.
int routerset_contains_extendinfo (const routerset_t *set, const extend_info_t *ei)
 Return true iff we can tell that ei is a member of set.
int routerset_contains_node (const routerset_t *set, const node_t *node)
 Return true iff node is in set.
void routerset_get_all_nodes (smartlist_t *out, const routerset_t *routerset, const routerset_t *excludeset, int running_only)
 Add every known node_t that is a member of routerset to out, but never add any that are part of excludeset.
void routerset_subtract_nodes (smartlist_t *out, const routerset_t *routerset)
 Remove every node_t from lst that is in routerset.
char * routerset_to_string (const routerset_t *routerset)
 Return a new string that when parsed by routerset_parse_string() will yield set.
int routerset_equal (const routerset_t *old, const routerset_t *new)
 Helper: return true iff old and new are both NULL, or both non-NULL equal routersets.
void routerset_free (routerset_t *routerset)
 Free all storage held in routerset.
void refresh_all_country_info (void)
 Called when we change a node set, or when we reload the geoip list: recompute all country info in all configuration node sets and in the routerlist.
int hid_serv_get_responsible_directories (smartlist_t *responsible_dirs, const char *id)
 Determine the routers that are responsible for id (binary) and add pointers to those routers' routerstatus_t to responsible_dirs.
int hid_serv_acting_as_directory (void)
 Return true if this node is currently acting as hidden service directory, false otherwise.
int hid_serv_responsible_for_desc_id (const char *id)
 Return true if this node is responsible for storing the descriptor ID in query and false otherwise.
void list_pending_microdesc_downloads (digestmap_t *result)
 For every microdescriptor we are currently downloading by descriptor digest, set result[d] to (void*)1.
void launch_descriptor_downloads (int purpose, smartlist_t *downloadable, const routerstatus_t *source, time_t now)
 Given a purpose (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of router descriptor digests or microdescriptor digest256s in downloadable, decide whether to delay fetching until we have more.
int hex_digest_nickname_decode (const char *hexdigest, char *digest_out, char *nickname_qualifier_out, char *nickname_out)
 Helper: given an extended nickname in hexdigest try to decode it.

Detailed Description

Header file for routerlist.c.

Definition in file routerlist.h.


Define Documentation

Definition at line 61 of file routerlist.h.


Function Documentation

trusted_dir_server_t* add_trusted_dir_server ( const char *  nickname,
const char *  address,
uint16_t  dir_port,
uint16_t  or_port,
const char *  digest,
const char *  v3_auth_digest,
dirinfo_type_t  type 
)

Add to the list of authoritative directory servers one at address:port, with identity key digest.

If address is NULL, add ourself. Return the new trusted directory server entry on success or NULL if we couldn't add it.

Definition at line 4093 of file routerlist.c.

{
  trusted_dir_server_t *ent;
  uint32_t a;
  char *hostname = NULL;
  if (!trusted_dir_servers)
    trusted_dir_servers = smartlist_new();

  if (!address) { /* The address is us; we should guess. */
    if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
      log_warn(LD_CONFIG,
               "Couldn't find a suitable address when adding ourself as a "
               "trusted directory server.");
      return NULL;
    }
  } else {
    if (tor_lookup_hostname(address, &a)) {
      log_warn(LD_CONFIG,
               "Unable to lookup address for directory server at '%s'",
               address);
      return NULL;
    }
    hostname = tor_strdup(address);
  }

  ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  ent->address = hostname;
  ent->addr = a;
  ent->dir_port = dir_port;
  ent->or_port = or_port;
  ent->is_running = 1;
  ent->type = type;
  memcpy(ent->digest, digest, DIGEST_LEN);
  if (v3_auth_digest && (type & V3_DIRINFO))
    memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);

  if (nickname)
    tor_asprintf(&ent->description, "directory server \"%s\" at %s:%d",
                 nickname, hostname, (int)dir_port);
  else
    tor_asprintf(&ent->description, "directory server at %s:%d",
                 hostname, (int)dir_port);

  ent->fake_status.addr = ent->addr;
  memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  if (nickname)
    strlcpy(ent->fake_status.nickname, nickname,
            sizeof(ent->fake_status.nickname));
  else
    ent->fake_status.nickname[0] = '\0';
  ent->fake_status.dir_port = ent->dir_port;
  ent->fake_status.or_port = ent->or_port;

  if (ent->or_port)
    ent->fake_status.version_supports_begindir = 1;

  ent->fake_status.version_supports_conditional_consensus = 1;

  smartlist_add(trusted_dir_servers, ent);
  router_dir_info_changed();
  return ent;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return 1 if any trusted dir server supports v1 directories, else return 0.

Definition at line 4204 of file routerlist.c.

{
  if (trusted_dir_servers)
    return get_n_authorities(V1_DIRINFO) > 0;

  return 0;
}

Here is the call graph for this function:

void authority_cert_dl_failed ( const char *  id_digest,
int  status 
)

Called when an attempt to download a certificate with the authority with ID id_digest fails with HTTP response code status: remember the failure, so we don't try again immediately.

Definition at line 451 of file routerlist.c.

{
  cert_list_t *cl;
  if (!trusted_dir_certs ||
      !(cl = digestmap_get(trusted_dir_certs, id_digest)))
    return;

  download_status_failed(&cl->dl_status, status);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int authority_cert_dl_looks_uncertain ( const char *  id_digest)

Return true iff when we've been getting enough failures when trying to download the certificate with ID digest id_digest that we're willing to start bugging the user about it.

Definition at line 465 of file routerlist.c.

{
#define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
  cert_list_t *cl;
  int n_failures;
  if (!trusted_dir_certs ||
      !(cl = digestmap_get(trusted_dir_certs, id_digest)))
    return 0;

  n_failures = download_status_get_n_failures(&cl->dl_status);
  return n_failures >= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Free storage held in cert.

Definition at line 4162 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

void authority_cert_get_all ( smartlist_t certs_out)

Add every known authority_cert_t to certs_out.

Definition at line 435 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

authority_cert_t* authority_cert_get_by_digests ( const char *  id_digest,
const char *  sk_digest 
)

Return the v3 authority certificate with signing key matching sk_digest, for the authority with identity digest id_digest.

Return NULL if no such authority is known.

Definition at line 419 of file routerlist.c.

{
  cert_list_t *cl;
  if (!trusted_dir_certs ||
      !(cl = digestmap_get(trusted_dir_certs, id_digest)))
    return NULL;
  SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
    if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
      return cert; );

  return NULL;
}

Here is the call graph for this function:

Here is the caller graph for this function:

authority_cert_t* authority_cert_get_by_sk_digest ( const char *  sk_digest)

Return the newest v3 authority certificate whose directory signing key has digest sk_digest.

Return NULL if no such certificate is known.

Definition at line 392 of file routerlist.c.

{
  authority_cert_t *c;
  if (!trusted_dir_certs)
    return NULL;

  if ((c = get_my_v3_authority_cert()) &&
      tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
    return c;
  if ((c = get_my_v3_legacy_cert()) &&
      tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
    return c;

  DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
    SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
    {
      if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
        return cert;
    });
  } DIGESTMAP_FOREACH_END;
  return NULL;
}

Here is the call graph for this function:

Here is the caller graph for this function:

authority_cert_t* authority_cert_get_newest_by_id ( const char *  id_digest)

Return the newest v3 authority certificate whose v3 authority identity key has digest id_digest.

Return NULL if no such authority is known, or it has no certificate.

Definition at line 372 of file routerlist.c.

{
  cert_list_t *cl;
  authority_cert_t *best = NULL;
  if (!trusted_dir_certs ||
      !(cl = digestmap_get(trusted_dir_certs, id_digest)))
    return NULL;

  SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  {
    if (!best || cert->cache_info.published_on > best->cache_info.published_on)
      best = cert;
  });
  return best;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void authority_certs_fetch_missing ( networkstatus_t status,
time_t  now 
)

Try to download any v3 authority certificates that we may be missing.

If status is provided, try to get all the ones that were used to sign status. Additionally, try to have a non-expired certificate for every V3 authority in trusted_dir_servers. Don't fetch certificates we already have.

Definition at line 488 of file routerlist.c.

{
  digestmap_t *pending;
  authority_cert_t *cert;
  smartlist_t *missing_digests;
  char *resource = NULL;
  cert_list_t *cl;
  const int cache = directory_caches_unknown_auth_certs(get_options());

  if (should_delay_dir_fetches(get_options()))
    return;

  pending = digestmap_new();
  missing_digests = smartlist_new();

  list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
  if (status) {
    SMARTLIST_FOREACH_BEGIN(status->voters, networkstatus_voter_info_t *,
                            voter) {
      if (!smartlist_len(voter->sigs))
        continue; /* This authority never signed this consensus, so don't
                   * go looking for a cert with key digest 0000000000. */
      if (!cache &&
          !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
        continue; /* We are not a cache, and we don't know this authority.*/
      cl = get_cert_list(voter->identity_digest);
      SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
        cert = authority_cert_get_by_digests(voter->identity_digest,
                                             sig->signing_key_digest);
        if (cert) {
          if (now < cert->expires)
            download_status_reset(&cl->dl_status);
          continue;
        }
        if (download_status_is_ready(&cl->dl_status, now,
                                     MAX_CERT_DL_FAILURES) &&
            !digestmap_get(pending, voter->identity_digest)) {
          log_info(LD_DIR, "We're missing a certificate from authority "
                   "with signing key %s: launching request.",
                   hex_str(sig->signing_key_digest, DIGEST_LEN));
          smartlist_add(missing_digests, sig->identity_digest);
        }
      } SMARTLIST_FOREACH_END(sig);
    } SMARTLIST_FOREACH_END(voter);
  }
  SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds) {
    int found = 0;
    if (!(ds->type & V3_DIRINFO))
      continue;
    if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
      continue;
    cl = get_cert_list(ds->v3_identity_digest);
    SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert, {
      if (now < cert->expires) {
        /* It's not expired, and we weren't looking for something to
         * verify a consensus with.  Call it done. */
        download_status_reset(&cl->dl_status);
        found = 1;
        break;
      }
    });
    if (!found &&
        download_status_is_ready(&cl->dl_status, now,MAX_CERT_DL_FAILURES) &&
        !digestmap_get(pending, ds->v3_identity_digest)) {
      log_info(LD_DIR, "No current certificate known for authority %s; "
               "launching request.", ds->nickname);
        smartlist_add(missing_digests, ds->v3_identity_digest);
    }
  } SMARTLIST_FOREACH_END(ds);

  if (!smartlist_len(missing_digests)) {
    goto done;
  } else {
    smartlist_t *fps = smartlist_new();
    smartlist_add(fps, tor_strdup("fp/"));
    SMARTLIST_FOREACH(missing_digests, const char *, d, {
        char *fp;
        if (digestmap_get(pending, d))
          continue;
        fp = tor_malloc(HEX_DIGEST_LEN+2);
        base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
        fp[HEX_DIGEST_LEN] = '+';
        fp[HEX_DIGEST_LEN+1] = '\0';
        smartlist_add(fps, fp);
      });
    if (smartlist_len(fps) == 1) {
      /* we didn't add any: they were all pending */
      SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
      smartlist_free(fps);
      goto done;
    }
    resource = smartlist_join_strings(fps, "", 0, NULL);
    resource[strlen(resource)-1] = '\0';
    SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
    smartlist_free(fps);
  }
  directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
                               resource, PDS_RETRY_IF_NO_SERVERS);

 done:
  tor_free(resource);
  smartlist_free(missing_digests);
  digestmap_free(pending, NULL);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void clear_trusted_dir_servers ( void  )

Remove all members from the list of trusted dir servers.

Definition at line 4189 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

We just fetched a new set of descriptors.

Compute how far through the "loading descriptors" bootstrapping phase we are, so we can inform the controller of our progress.

Definition at line 4970 of file routerlist.c.

{
  int num_present = 0, num_usable=0;
  time_t now = time(NULL);
  const networkstatus_t *consensus =
    networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
  double fraction;

  if (!consensus)
    return 0; /* can't count descriptors if we have no list of them */

  count_usable_descriptors(&num_present, &num_usable,
                           consensus, get_options(), now, NULL, 0);

  if (num_usable == 0)
    return 0; /* don't div by 0 */
  fraction = num_present / (num_usable/4.);
  if (fraction > 1.0)
    return 0; /* it's not the number of descriptors holding us back */
  return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
    (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
               BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
}

Here is the call graph for this function:

Here is the caller graph for this function:

void dump_routerlist_mem_usage ( int  severity)

Log information about how much memory is being used for routerlist, at log level severity.

Definition at line 2802 of file routerlist.c.

{
  uint64_t livedescs = 0;
  uint64_t olddescs = 0;
  if (!routerlist)
    return;
  SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
                    livedescs += r->cache_info.signed_descriptor_len);
  SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
                    olddescs += sd->signed_descriptor_len);

  log(severity, LD_DIR,
      "In %d live descriptors: "U64_FORMAT" bytes.  "
      "In %d old descriptors: "U64_FORMAT" bytes.",
      smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
      smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
}

Here is the caller graph for this function:

const char* esc_router_info ( const routerinfo_t router)

Allocate and return a new string representing the contact info and platform string for router, surrounded by quotes and using standard C escapes.

THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main thread. Also, each call invalidates the last-returned value, so don't try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));

If router is NULL, it just frees its internal memory and returns.

Definition at line 5381 of file routerlist.c.

{
  static char *info=NULL;
  char *esc_contact, *esc_platform;
  tor_free(info);

  if (!router)
    return NULL; /* we're exiting; just free the memory we use */

  esc_contact = esc_for_log(router->contact_info);
  esc_platform = esc_for_log(router->platform);

  tor_asprintf(&info, "Contact %s, Platform %s", esc_contact, esc_platform);
  tor_free(esc_contact);
  tor_free(esc_platform);

  return info;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void extrainfo_free ( extrainfo_t extrainfo)

Release all storage held by extrainfo

Definition at line 2727 of file routerlist.c.

{
  if (!extrainfo)
    return;
  tor_free(extrainfo->cache_info.signed_descriptor_body);
  tor_free(extrainfo->pending_sig);

  memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  tor_free(extrainfo);
}

Here is the caller graph for this function:

Return the signed descriptor for the extrainfo_t in our routerlist whose extra-info-digest is digest.

Return NULL if no such extra-info document is known.

Definition at line 2589 of file routerlist.c.

{
  extrainfo_t *ei;
  tor_assert(digest);
  if (!routerlist) return NULL;
  ei = eimap_get(routerlist->extra_info_map, digest);
  return ei ? &ei->cache_info : NULL;
}

Here is the caller graph for this function:

const char* get_dir_info_status_string ( void  )

Return a string describing what we're missing before we have enough directory info.

Definition at line 4920 of file routerlist.c.

{
  return dir_info_status;
}

Here is the caller graph for this function:

Return the number of directory authorities whose type matches some bit set in type

Definition at line 117 of file routerlist.c.

{
  int n = 0;
  if (!trusted_dir_servers)
    return 0;
  SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
                    if (ds->type & type)
                      ++n);
  return n;
}

Here is the caller graph for this function:

int hex_digest_nickname_decode ( const char *  hexdigest,
char *  digest_out,
char *  nickname_qualifier_char_out,
char *  nickname_out 
)

Helper: given an extended nickname in hexdigest try to decode it.

Return 0 on success, -1 on failure. Store the result into the DIGEST_LEN-byte buffer at digest_out, the single character at nickname_qualifier_char_out, and the MAXNICKNAME_LEN+1-byte buffer at nickname_out.

The recognized format is: HexName = Dollar? HexDigest NamePart? Dollar = '?' HexDigest = HexChar*20 HexChar = 'a'..'f' | 'A'..'F' | '0'..'9' NamePart = QualChar Name QualChar = '=' | '~' Name = NameChar*(1..MAX_NICKNAME_LEN) NameChar = Any ASCII alphanumeric character

Definition at line 2263 of file routerlist.c.

{
  size_t len;

  tor_assert(hexdigest);
  if (hexdigest[0] == '$')
    ++hexdigest;

  len = strlen(hexdigest);
  if (len < HEX_DIGEST_LEN) {
    return -1;
  } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
                                    hexdigest[HEX_DIGEST_LEN] == '~') &&
           len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
    *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
    strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
  } else if (len == HEX_DIGEST_LEN) {
    ;
  } else {
    return -1;
  }

  if (base16_decode(digest_out, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
    return -1;
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int hexdigest_to_digest ( const char *  hexdigest,
char *  digest 
)

If hexdigest is correctly formed, base16_decode it into digest, which must have DIGEST_LEN space in it.

Return 0 on success, -1 on failure.

Definition at line 2516 of file routerlist.c.

{
  if (hexdigest[0]=='$')
    ++hexdigest;
  if (strlen(hexdigest) < HEX_DIGEST_LEN ||
      base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
    return -1;
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return true if this node is currently acting as hidden service directory, false otherwise.

Definition at line 5912 of file routerlist.c.

{
  const routerinfo_t *me = router_get_my_routerinfo();
  if (!me)
    return 0;
  if (!get_options()->HidServDirectoryV2) {
    log_info(LD_REND, "We are not acting as hidden service directory, "
                      "because we have not been configured as such.");
    return 0;
  }
  return 1;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int hid_serv_get_responsible_directories ( smartlist_t responsible_dirs,
const char *  id 
)

Determine the routers that are responsible for id (binary) and add pointers to those routers' routerstatus_t to responsible_dirs.

Return -1 if we're returning an empty smartlist, else return 0.

Definition at line 5879 of file routerlist.c.

{
  int start, found, n_added = 0, i;
  networkstatus_t *c = networkstatus_get_latest_consensus();
  if (!c || !smartlist_len(c->routerstatus_list)) {
    log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
             "rendezvous operations.");
    return -1;
  }
  tor_assert(id);
  start = networkstatus_vote_find_entry_idx(c, id, &found);
  if (start == smartlist_len(c->routerstatus_list)) start = 0;
  i = start;
  do {
    routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
    if (r->is_hs_dir) {
      smartlist_add(responsible_dirs, r);
      if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
        return 0;
    }
    if (++i == smartlist_len(c->routerstatus_list))
      i = 0;
  } while (i != start);

  /* Even though we don't have the desired number of hidden service
   * directories, be happy if we got any. */
  return smartlist_len(responsible_dirs) ? 0 : -1;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int hid_serv_responsible_for_desc_id ( const char *  query)

Return true if this node is responsible for storing the descriptor ID in query and false otherwise.

Definition at line 5928 of file routerlist.c.

{
  const routerinfo_t *me;
  routerstatus_t *last_rs;
  const char *my_id, *last_id;
  int result;
  smartlist_t *responsible;
  if (!hid_serv_acting_as_directory())
    return 0;
  if (!(me = router_get_my_routerinfo()))
    return 0; /* This is redundant, but let's be paranoid. */
  my_id = me->cache_info.identity_digest;
  responsible = smartlist_new();
  if (hid_serv_get_responsible_directories(responsible, query) < 0) {
    smartlist_free(responsible);
    return 0;
  }
  last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
  last_id = last_rs->identity_digest;
  result = rend_id_is_in_interval(my_id, query, last_id);
  smartlist_free(responsible);
  return result;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void launch_descriptor_downloads ( int  purpose,
smartlist_t downloadable,
const routerstatus_t source,
time_t  now 
)

Given a purpose (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of router descriptor digests or microdescriptor digest256s in downloadable, decide whether to delay fetching until we have more.

If we don't want to delay, launch one or more requests to the appropriate directory authorities.

Definition at line 4391 of file routerlist.c.

{
  int should_delay = 0, n_downloadable;
  const or_options_t *options = get_options();
  const char *descname;

  tor_assert(purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
             purpose == DIR_PURPOSE_FETCH_MICRODESC);

  descname = (purpose == DIR_PURPOSE_FETCH_SERVERDESC) ?
    "routerdesc" : "microdesc";

  n_downloadable = smartlist_len(downloadable);
  if (!directory_fetches_dir_info_early(options)) {
    if (n_downloadable >= MAX_DL_TO_DELAY) {
      log_debug(LD_DIR,
                "There are enough downloadable %ss to launch requests.",
                descname);
      should_delay = 0;
    } else {
      should_delay = (last_descriptor_download_attempted +
                      MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
      if (!should_delay && n_downloadable) {
        if (last_descriptor_download_attempted) {
          log_info(LD_DIR,
                   "There are not many downloadable %ss, but we've "
                   "been waiting long enough (%d seconds). Downloading.",
                   descname,
                   (int)(now-last_descriptor_download_attempted));
        } else {
          log_info(LD_DIR,
                   "There are not many downloadable %ss, but we haven't "
                   "tried downloading descriptors recently. Downloading.",
                   descname);
        }
      }
    }
  }
  /* XXX should we consider having even the dir mirrors delay
   * a little bit, so we don't load the authorities as much? -RD
   * I don't think so.  If we do, clients that want those descriptors may
   * not actually find them if the caches haven't got them yet. -NM
   */

  if (! should_delay && n_downloadable) {
    int i, n_per_request;
    const char *req_plural = "", *rtr_plural = "";
    int pds_flags = PDS_RETRY_IF_NO_SERVERS;
    if (! authdir_mode_any_nonhidserv(options)) {
      /* If we wind up going to the authorities, we want to only open one
       * connection to each authority at a time, so that we don't overload
       * them.  We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
       * regardless of whether we're a cache or not; it gets ignored if we're
       * not calling router_pick_trusteddirserver.
       *
       * Setting this flag can make initiate_descriptor_downloads() ignore
       * requests.  We need to make sure that we do in fact call
       * update_router_descriptor_downloads() later on, once the connections
       * have succeeded or failed.
       */
      pds_flags |= (purpose == DIR_PURPOSE_FETCH_MICRODESC) ?
        PDS_NO_EXISTING_MICRODESC_FETCH :
        PDS_NO_EXISTING_SERVERDESC_FETCH;
    }

    n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
    if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
      if (n_per_request > MAX_MICRODESC_DL_PER_REQUEST)
        n_per_request = MAX_MICRODESC_DL_PER_REQUEST;
    } else {
      if (n_per_request > MAX_DL_PER_REQUEST)
        n_per_request = MAX_DL_PER_REQUEST;
    }
    if (n_per_request < MIN_DL_PER_REQUEST)
      n_per_request = MIN_DL_PER_REQUEST;

    if (n_downloadable > n_per_request)
      req_plural = rtr_plural = "s";
    else if (n_downloadable > 1)
      rtr_plural = "s";

    log_info(LD_DIR,
             "Launching %d request%s for %d router%s, %d at a time",
             CEIL_DIV(n_downloadable, n_per_request),
             req_plural, n_downloadable, rtr_plural, n_per_request);
    smartlist_sort_digests(downloadable);
    for (i=0; i < n_downloadable; i += n_per_request) {
      initiate_descriptor_downloads(source, purpose,
                                    downloadable, i, i+n_per_request,
                                    pds_flags);
    }
    last_descriptor_download_attempted = now;
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

void list_pending_microdesc_downloads ( digestmap_t *  result)

For every microdescriptor we are currently downloading by descriptor digest, set result[d] to (void*)1.

(Note that microdescriptor digests are 256-bit, and digestmap_t only holds 160-bit digests, so we're only getting the first 20 bytes of each digest here.)

XXXX Let there be a digestmap256_t, and use that instead.

Definition at line 4269 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int node_is_unreliable ( const node_t node,
int  need_uptime,
int  need_capacity,
int  need_guard 
)

Return 1 if router is not suitable for these parameters, else 0.

If need_uptime is non-zero, we require a minimum uptime. If need_capacity is non-zero, we require a minimum advertised bandwidth. If need_guard, we require that the router is a possible entry guard.

Definition at line 1619 of file routerlist.c.

{
  if (need_uptime && !node->is_stable)
    return 1;
  if (need_capacity && !node->is_fast)
    return 1;
  if (need_guard && !node->is_possible_guard)
    return 1;
  return 0;
}

Here is the caller graph for this function:

Choose a random element of status list sl, weighted by the advertised bandwidth of each node.

Definition at line 2150 of file routerlist.c.

{ /*XXXX MOVE */
  const node_t *ret;
  if ((ret = smartlist_choose_node_by_bandwidth_weights(sl, rule))) {
    return ret;
  } else {
    return smartlist_choose_node_by_bandwidth(sl, rule);
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

void refresh_all_country_info ( void  )

Called when we change a node set, or when we reload the geoip list: recompute all country info in all configuration node sets and in the routerlist.

Definition at line 5565 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

was_router_added_t router_add_extrainfo_to_routerlist ( extrainfo_t ei,
const char **  msg,
int  from_cache,
int  from_fetch 
)

Insert ei into the routerlist, or free it.

Other arguments are as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff we actually inserted it, ROUTER_BAD_EI otherwise.

Definition at line 3489 of file routerlist.c.

{
  int inserted;
  (void)from_fetch;
  if (msg) *msg = NULL;
  /*XXXX023 Do something with msg */

  inserted = extrainfo_insert(router_get_routerlist(), ei);

  if (inserted && !from_cache)
    signed_desc_append_to_journal(&ei->cache_info,
                                  &routerlist->extrainfo_store);

  if (inserted)
    return ROUTER_ADDED_SUCCESSFULLY;
  else
    return ROUTER_BAD_EI;
}

Here is the call graph for this function:

Here is the caller graph for this function:

was_router_added_t router_add_to_routerlist ( routerinfo_t router,
const char **  msg,
int  from_cache,
int  from_fetch 
)

Add router to the routerlist, if we don't already have it.

Replace older entries (if any) with the same key. Note: Callers should not hold their pointers to router if this function fails; router will either be inserted into the routerlist or freed. Similarly, even if this call succeeds, they should not hold their pointers to router after subsequent calls with other routerinfo's -- they might cause the original routerinfo to get freed.

Returns the status for the operation. Might set *msg if it wants the poster of the router to know something.

If from_cache, this descriptor came from our disk cache. If from_fetch, we received it in response to a request we made. (If both are false, that means it was uploaded to us as an auth dir server or via the controller.)

This function should be called after routers_update_status_from_consensus_networkstatus; subsequently, you should call router_rebuild_store and routerlist_descriptors_added.

Definition at line 3302 of file routerlist.c.

{
  const char *id_digest;
  const or_options_t *options = get_options();
  int authdir = authdir_mode_handles_descs(options, router->purpose);
  int authdir_believes_valid = 0;
  routerinfo_t *old_router;
  networkstatus_t *consensus =
    networkstatus_get_latest_consensus_by_flavor(FLAV_NS);
  const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  int in_consensus = 0;

  tor_assert(msg);

  if (!routerlist)
    router_get_routerlist();

  id_digest = router->cache_info.identity_digest;

  old_router = router_get_mutable_by_digest(id_digest);

  /* Make sure that we haven't already got this exact descriptor. */
  if (sdmap_get(routerlist->desc_digest_map,
                router->cache_info.signed_descriptor_digest)) {
    /* If we have this descriptor already and the new descriptor is a bridge
     * descriptor, replace it. If we had a bridge descriptor before and the
     * new one is not a bridge descriptor, don't replace it. */

    /* Only members of routerlist->identity_map can be bridges; we don't
     * put bridges in old_routers. */
    const int was_bridge = old_router &&
      old_router->purpose == ROUTER_PURPOSE_BRIDGE;

    if (routerinfo_is_a_configured_bridge(router) &&
        router->purpose == ROUTER_PURPOSE_BRIDGE &&
        !was_bridge) {
      log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
               "descriptor for router %s",
               router_describe(router));
    } else {
      log_info(LD_DIR,
               "Dropping descriptor that we already have for router %s",
               router_describe(router));
      *msg = "Router descriptor was not new.";
      routerinfo_free(router);
      return ROUTER_WAS_NOT_NEW;
    }
  }

  if (authdir) {
    if (authdir_wants_to_reject_router(router, msg,
                                       !from_cache && !from_fetch,
                                       &authdir_believes_valid)) {
      tor_assert(*msg);
      routerinfo_free(router);
      return ROUTER_AUTHDIR_REJECTS;
    }
  } else if (from_fetch) {
    /* Only check the descriptor digest against the network statuses when
     * we are receiving in response to a fetch. */

    if (!signed_desc_digest_is_recognized(&router->cache_info) &&
        !routerinfo_is_a_configured_bridge(router)) {
      /* We asked for it, so some networkstatus must have listed it when we
       * did.  Save it if we're a cache in case somebody else asks for it. */
      log_info(LD_DIR,
               "Received a no-longer-recognized descriptor for router %s",
               router_describe(router));
      *msg = "Router descriptor is not referenced by any network-status.";

      /* Only journal this desc if we'll be serving it. */
      if (!from_cache && should_cache_old_descriptors())
        signed_desc_append_to_journal(&router->cache_info,
                                      &routerlist->desc_store);
      routerlist_insert_old(routerlist, router);
      return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
    }
  }

  /* We no longer need a router with this descriptor digest. */
  SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  {
    routerstatus_t *rs =
      networkstatus_v2_find_mutable_entry(ns, id_digest);
    if (rs && tor_memeq(rs->descriptor_digest,
                      router->cache_info.signed_descriptor_digest,
                      DIGEST_LEN))
      rs->need_to_mirror = 0;
  });
  if (consensus) {
    routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
                                                     consensus, id_digest);
    if (rs && tor_memeq(rs->descriptor_digest,
                      router->cache_info.signed_descriptor_digest,
                      DIGEST_LEN)) {
      in_consensus = 1;
      rs->need_to_mirror = 0;
    }
  }

  if (router->purpose == ROUTER_PURPOSE_GENERAL &&
      consensus && !in_consensus && !authdir) {
    /* If it's a general router not listed in the consensus, then don't
     * consider replacing the latest router with it. */
    if (!from_cache && should_cache_old_descriptors())
      signed_desc_append_to_journal(&router->cache_info,
                                    &routerlist->desc_store);
    routerlist_insert_old(routerlist, router);
    *msg = "Skipping router descriptor: not in consensus.";
    return ROUTER_NOT_IN_CONSENSUS;
  }

  /* If we're reading a bridge descriptor from our cache, and we don't
   * recognize it as one of our currently configured bridges, drop the
   * descriptor. Otherwise we could end up using it as one of our entry
   * guards even if it isn't in our Bridge config lines. */
  if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
      !authdir_mode_bridge(options) &&
      !routerinfo_is_a_configured_bridge(router)) {
    log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
             "no bridge configured at that address.",
             safe_str_client(router_describe(router)));
    *msg = "Router descriptor was not a configured bridge.";
    routerinfo_free(router);
    return ROUTER_WAS_NOT_WANTED;
  }

  /* If we have a router with the same identity key, choose the newer one. */
  if (old_router) {
    if (!in_consensus && (router->cache_info.published_on <=
                          old_router->cache_info.published_on)) {
      /* Same key, but old.  This one is not listed in the consensus. */
      log_debug(LD_DIR, "Not-new descriptor for router %s",
                router_describe(router));
      /* Only journal this desc if we'll be serving it. */
      if (!from_cache && should_cache_old_descriptors())
        signed_desc_append_to_journal(&router->cache_info,
                                      &routerlist->desc_store);
      routerlist_insert_old(routerlist, router);
      *msg = "Router descriptor was not new.";
      return ROUTER_WAS_NOT_NEW;
    } else {
      /* Same key, and either new, or listed in the consensus. */
      log_debug(LD_DIR, "Replacing entry for router %s",
                router_describe(router));
      if (routers_have_same_or_addr(router, old_router)) {
        /* these carry over when the address and orport are unchanged. */
        router->last_reachable = old_router->last_reachable;
        router->testing_since = old_router->testing_since;
      }
      routerlist_replace(routerlist, old_router, router);
      if (!from_cache) {
        signed_desc_append_to_journal(&router->cache_info,
                                      &routerlist->desc_store);
      }
      directory_set_dirty();
      *msg = authdir_believes_valid ? "Valid server updated" :
        ("Invalid server updated. (This dirserver is marking your "
         "server as unapproved.)");
      return ROUTER_ADDED_SUCCESSFULLY;
    }
  }

  if (!in_consensus && from_cache &&
      router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
    *msg = "Router descriptor was really old.";
    routerinfo_free(router);
    return ROUTER_WAS_NOT_NEW;
  }

  /* We haven't seen a router with this identity before. Add it to the end of
   * the list. */
  routerlist_insert(routerlist, router);
  if (!from_cache) {
    signed_desc_append_to_journal(&router->cache_info,
                                  &routerlist->desc_store);
  }
  directory_set_dirty();
  return ROUTER_ADDED_SUCCESSFULLY;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int router_addr_is_trusted_dir ( uint32_t  addr)

Return true iff addr is the address of one of our trusted directory authorities.

Definition at line 2500 of file routerlist.c.

{
  if (!trusted_dir_servers)
    return 0;
  SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
    if (ent->addr == addr)
      return 1;
    );
  return 0;
}

Here is the caller graph for this function:

const node_t* router_choose_random_node ( smartlist_t excludedsmartlist,
routerset_t excludedset,
router_crn_flags_t  flags 
)

Return a random running node from the nodelist.

Never pick a node that is in excludedsmartlist, or which matches excludedset, even if they are the only nodes available. If CRN_NEED_UPTIME is set in flags and any router has more than a minimum uptime, return one of those. If CRN_NEED_CAPACITY is set in flags, weight your choice by the advertised capacity of each router. If CRN_ALLOW_INVALID is not set in flags, consider only Valid routers. If CRN_NEED_GUARD is set in flags, consider only Guard routers. If CRN_WEIGHT_AS_EXIT is set in flags, we weight bandwidths as if picking an exit node, otherwise we weight bandwidths for picking a relay node (that is, possibly discounting exit nodes). If CRN_NEED_DESC is set in flags, we only consider nodes that have a routerinfo or microdescriptor -- that is, enough info to be used to build a circuit.

Definition at line 2180 of file routerlist.c.

{ /* XXXX MOVE */
  const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
  const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
  const int need_guard = (flags & CRN_NEED_GUARD) != 0;
  const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
  const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
  const int need_desc = (flags & CRN_NEED_DESC) != 0;

  smartlist_t *sl=smartlist_new(),
    *excludednodes=smartlist_new();
  const node_t *choice = NULL;
  const routerinfo_t *r;
  bandwidth_weight_rule_t rule;

  tor_assert(!(weight_for_exit && need_guard));
  rule = weight_for_exit ? WEIGHT_FOR_EXIT :
    (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);

  /* Exclude relays that allow single hop exit circuits, if the user
   * wants to (such relays might be risky) */
  if (get_options()->ExcludeSingleHopRelays) {
    SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
      if (node_allows_single_hop_exits(node)) {
        smartlist_add(excludednodes, node);
      });
  }

  if ((r = routerlist_find_my_routerinfo()))
    routerlist_add_node_and_family(excludednodes, r);

  router_add_running_nodes_to_smartlist(sl, allow_invalid,
                                        need_uptime, need_capacity,
                                        need_guard, need_desc);
  smartlist_subtract(sl,excludednodes);
  if (excludedsmartlist)
    smartlist_subtract(sl,excludedsmartlist);
  if (excludedset)
    routerset_subtract_nodes(sl,excludedset);

  // Always weight by bandwidth
  choice = node_sl_choose_by_bandwidth(sl, rule);

  smartlist_free(sl);
  if (!choice && (need_uptime || need_capacity || need_guard)) {
    /* try once more -- recurse but with fewer restrictions. */
    log_info(LD_CIRC,
             "We couldn't find any live%s%s%s routers; falling back "
             "to list of all routers.",
             need_capacity?", fast":"",
             need_uptime?", stable":"",
             need_guard?", guard":"");
    flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
    choice = router_choose_random_node(
                     excludedsmartlist, excludedset, flags);
  }
  smartlist_free(excludednodes);
  if (!choice) {
    log_warn(LD_CIRC,
             "No available nodes when trying to choose node. Failing.");
  }
  return choice;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int router_differences_are_cosmetic ( const routerinfo_t r1,
const routerinfo_t r2 
)

Return true iff the only differences between r1 and r2 are such that would not cause a recent (post 0.1.1.6) dirserver to republish.

Definition at line 5136 of file routerlist.c.

{
  time_t r1pub, r2pub;
  long time_difference;
  tor_assert(r1 && r2);

  /* r1 should be the one that was published first. */
  if (r1->cache_info.published_on > r2->cache_info.published_on) {
    const routerinfo_t *ri_tmp = r2;
    r2 = r1;
    r1 = ri_tmp;
  }

  /* If any key fields differ, they're different. */
  if (strcasecmp(r1->address, r2->address) ||
      strcasecmp(r1->nickname, r2->nickname) ||
      r1->or_port != r2->or_port ||
      r1->dir_port != r2->dir_port ||
      r1->purpose != r2->purpose ||
      crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
      crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
      strcasecmp(r1->platform, r2->platform) ||
      (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
      (!r1->contact_info && r2->contact_info) ||
      (r1->contact_info && r2->contact_info &&
       strcasecmp(r1->contact_info, r2->contact_info)) ||
      r1->is_hibernating != r2->is_hibernating ||
      cmp_addr_policies(r1->exit_policy, r2->exit_policy))
    return 0;
  if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
    return 0;
  if (r1->declared_family && r2->declared_family) {
    int i, n;
    if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
      return 0;
    n = smartlist_len(r1->declared_family);
    for (i=0; i < n; ++i) {
      if (strcasecmp(smartlist_get(r1->declared_family, i),
                     smartlist_get(r2->declared_family, i)))
        return 0;
    }
  }

  /* Did bandwidth change a lot? */
  if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
      (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
    return 0;

  /* Did the bandwidthrate or bandwidthburst change? */
  if ((r1->bandwidthrate != r2->bandwidthrate) ||
      (r1->bandwidthburst != r2->bandwidthburst))
    return 0;

  /* Did more than 12 hours pass? */
  if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
      < r2->cache_info.published_on)
    return 0;

  /* Did uptime fail to increase by approximately the amount we would think,
   * give or take some slop? */
  r1pub = r1->cache_info.published_on;
  r2pub = r2->cache_info.published_on;
  time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
      time_difference > r1->uptime * .05 &&
      time_difference > r2->uptime * .05)
    return 0;

  /* Otherwise, the difference is cosmetic. */
  return 1;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int router_digest_is_trusted_dir_type ( const char *  digest,
dirinfo_type_t  type 
)

Return true iff digest is the digest of the identity key of a trusted directory matching at least one bit of type.

If type is zero, any authority is okay.

Definition at line 2484 of file routerlist.c.

{
  if (!trusted_dir_servers)
    return 0;
  if (authdir_mode(get_options()) && router_digest_is_me(digest))
    return 1;
  SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
    if (tor_memeq(digest, ent->digest, DIGEST_LEN)) {
      return (!type) || ((type & ent->type) != 0);
    });
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void router_dir_info_changed ( void  )

Called when our internal view of the directory has changed.

This can be when the authorities change, networkstatuses change, the list of routerdescs changes, or number of running routers changes.

Definition at line 4911 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int router_exit_policy_all_nodes_reject ( const tor_addr_t addr,
uint16_t  port,
int  need_uptime 
)

Return 1 if all running sufficiently-stable routers we can use will reject addr:port, return 0 if any might accept it.

Definition at line 4062 of file routerlist.c.

{ /* XXXX MOVE */
  addr_policy_result_t r;

  SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
    if (node->is_running &&
        !node_is_unreliable(node, need_uptime, 0, 0)) {

      r = compare_tor_addr_to_node_policy(addr, port, node);

      if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
        return 0; /* this one could be ok. good enough. */
    }
  } SMARTLIST_FOREACH_END(node);
  return 1; /* all will reject. */
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return true iff router does not permit exit streams.

Definition at line 4083 of file routerlist.c.

{
  return router->policy_is_reject_star;
}

Here is the caller graph for this function:

const node_t* router_find_exact_exit_enclave ( const char *  address,
uint16_t  port 
)

Find a router that's up, that has this IP address, and that allows exit to this address:port, or return NULL if there isn't a good one.

Don't exit enclave to excluded relays -- it wouldn't actually hurt anything, but this way there are fewer confused users.

Definition at line 1588 of file routerlist.c.

{/*XXXX MOVE*/
  uint32_t addr;
  struct in_addr in;
  tor_addr_t a;
  const or_options_t *options = get_options();

  if (!tor_inet_aton(address, &in))
    return NULL; /* it's not an IP already */
  addr = ntohl(in.s_addr);

  tor_addr_from_ipv4h(&a, addr);

  SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, {
    if (node_get_addr_ipv4h(node) == addr &&
        node->is_running &&
        compare_tor_addr_to_node_policy(&a, port, node) ==
          ADDR_POLICY_ACCEPTED &&
        !routerset_contains_node(options->_ExcludeExitNodesUnion, node))
      return node;
  });
  return NULL;
}

Here is the call graph for this function:

uint32_t router_get_advertised_bandwidth ( const routerinfo_t router)

Return the smaller of the router's configured BandwidthRate and its advertised capacity.

Definition at line 1634 of file routerlist.c.

{
  if (router->bandwidthcapacity < router->bandwidthrate)
    return router->bandwidthcapacity;
  return router->bandwidthrate;
}

Here is the caller graph for this function:

Return the smaller of the router's configured BandwidthRate and its advertised capacity, capped by max-believe-bw.

Definition at line 1648 of file routerlist.c.

{
  uint32_t result = router->bandwidthcapacity;
  if (result > router->bandwidthrate)
    result = router->bandwidthrate;
  if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
    result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
  return result;
}

Here is the caller graph for this function:

Return the router in our routerlist whose 20-byte descriptor is digest.

Return NULL if no such router is known.

Definition at line 2563 of file routerlist.c.

{
  tor_assert(digest);

  if (!routerlist) return NULL;

  return sdmap_get(routerlist->desc_digest_map, digest);
}

Here is the caller graph for this function:

Return the signed descriptor for the router in our routerlist whose 20-byte extra-info digest is digest.

Return NULL if no such router is known.

Definition at line 2576 of file routerlist.c.

{
  tor_assert(digest);

  if (!routerlist) return NULL;

  return sdmap_get(routerlist->desc_by_eid_map, digest);
}

Here is the caller graph for this function:

const routerinfo_t* router_get_by_hexdigest ( const char *  hexdigest)

Return the router in our routerlist whose hexadecimal key digest is hexdigest.

Return NULL if no such router is known.

Definition at line 2529 of file routerlist.c.

{
  if (is_legal_nickname(hexdigest))
    return NULL;

  /* It's not a legal nickname, so it must be a hexdigest or nothing. */
  return router_get_by_nickname(hexdigest, 1);
}

Here is the call graph for this function:

Here is the caller graph for this function:

const routerinfo_t* router_get_by_id_digest ( const char *  digest)

Return the router in our routerlist whose 20-byte key digest is digest.

Return NULL if no such router is known.

Definition at line 2555 of file routerlist.c.

{
  return router_get_mutable_by_digest(digest);
}

Here is the call graph for this function:

Here is the caller graph for this function:

const routerinfo_t* router_get_by_nickname ( const char *  nickname,
int  warn_if_unnamed 
)

Return the router in our routerlist whose (case-insensitive) nickname or (case-sensitive) hexadecimal key digest is nickname.

Return NULL if no such router is known.

Definition at line 2378 of file routerlist.c.

{
#if 1
  const node_t *node = node_get_by_nickname(nickname, warn_if_unnamed);
  if (node)
    return node->ri;
  else
    return NULL;
#else
  int maybedigest;
  char digest[DIGEST_LEN];
  routerinfo_t *best_match=NULL;
  int n_matches = 0;
  const char *named_digest = NULL;

  tor_assert(nickname);
  if (!routerlist)
    return NULL;
  if (nickname[0] == '$')
    return router_get_by_hexdigest(nickname);
  if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
    return NULL;

  maybedigest = (strlen(nickname) >= HEX_DIGEST_LEN) &&
    (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);

  if ((named_digest = networkstatus_get_router_digest_by_nickname(nickname))) {
    return rimap_get(routerlist->identity_map, named_digest);
  }
  if (networkstatus_nickname_is_unnamed(nickname))
    return NULL;

  /* If we reach this point, there's no canonical value for the nickname. */

  SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  {
    if (!strcasecmp(router->nickname, nickname)) {
      ++n_matches;
      if (n_matches <= 1 || router->is_running)
        best_match = router;
    } else if (maybedigest &&
               tor_memeq(digest, router->cache_info.identity_digest,
                         DIGEST_LEN)) {
      if (router_hex_digest_matches(router, nickname))
        return router;
      /* If we reach this point, we have a ID=name syntax that matches the
       * identity but not the name. That isn't an acceptable match. */
    }
  });

  if (best_match) {
    if (warn_if_unnamed && n_matches > 1) {
      smartlist_t *fps = smartlist_new();
      int any_unwarned = 0;
      SMARTLIST_FOREACH_BEGIN(routerlist->routers, routerinfo_t *, router) {
          routerstatus_t *rs;
          char fp[HEX_DIGEST_LEN+1];
          if (strcasecmp(router->nickname, nickname))
            continue;
          rs = router_get_mutable_consensus_status_by_id(
                                          router->cache_info.identity_digest);
          if (rs && !rs->name_lookup_warned) {
            rs->name_lookup_warned = 1;
            any_unwarned = 1;
          }
          base16_encode(fp, sizeof(fp),
                        router->cache_info.identity_digest, DIGEST_LEN);
          smartlist_add_asprintf(fps, "\"$%s\" for the one at %s:%d",
                       fp, router->address, router->or_port);
      } SMARTLIST_FOREACH_END(router);
      if (any_unwarned) {
        char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
        log_warn(LD_CONFIG,
                 "There are multiple matches for the nickname \"%s\","
                 " but none is listed as named by the directory authorities. "
                 "Choosing one arbitrarily. If you meant one in particular, "
                 "you should say %s.", nickname, alternatives);
        tor_free(alternatives);
      }
      SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
      smartlist_free(fps);
    } else if (warn_if_unnamed) {
      routerstatus_t *rs = router_get_mutable_consensus_status_by_id(
          best_match->cache_info.identity_digest);
      if (rs && !rs->name_lookup_warned) {
        char fp[HEX_DIGEST_LEN+1];
        base16_encode(fp, sizeof(fp),
                      best_match->cache_info.identity_digest, DIGEST_LEN);
        log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but this "
             "name is not registered, so it could be used by any server, "
             "not just the one you meant. "
             "To make sure you get the same server in the future, refer to "
             "it by key, as \"$%s\".", nickname, fp);
        rs->name_lookup_warned = 1;
      }
    }
    return best_match;
  }
  return NULL;
#endif
}

Here is the call graph for this function:

Here is the caller graph for this function:

routerinfo_t* router_get_mutable_by_digest ( const char *  digest)

As router_get_by_id_digest,but return a pointer that you're allowed to modify.

Definition at line 2541 of file routerlist.c.

{
  tor_assert(digest);

  if (!routerlist) return NULL;

  // routerlist_assert_ok(routerlist);

  return rimap_get(routerlist->identity_map, digest);
}

Here is the caller graph for this function:

int router_get_my_share_of_directory_requests ( double *  v2_share_out,
double *  v3_share_out 
)

Try to determine which fraction of v2 and v3 directory requests aimed at caches will be sent to us.

Set *v2_share_out and *v3_share_out to the fractions of v2 and v3 protocol shares we expect to see, respectively. Return 0 on success, negative on failure.

Definition at line 976 of file routerlist.c.

{
  const routerinfo_t *me = router_get_my_routerinfo();
  const routerstatus_t *rs;
  const int pds_flags = PDS_ALLOW_SELF|PDS_IGNORE_FASCISTFIREWALL;
  *v2_share_out = *v3_share_out = 0.0;
  if (!me)
    return -1;
  rs = router_get_consensus_status_by_id(me->cache_info.identity_digest);
  if (!rs)
    return -1;

  /* Calling for side effect */
  /* XXXX This is a bit of a kludge */
  if (rs->is_v2_dir) {
    sl_last_total_weighted_bw = 0;
    router_pick_directory_server(V2_DIRINFO, pds_flags);
    if (sl_last_total_weighted_bw != 0) {
      *v2_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
        U64_TO_DBL(sl_last_total_weighted_bw);
    }
  }

  if (rs->version_supports_v3_dir) {
    sl_last_total_weighted_bw = 0;
    router_pick_directory_server(V3_DIRINFO, pds_flags);
    if (sl_last_total_weighted_bw != 0) {
      *v3_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
        U64_TO_DBL(sl_last_total_weighted_bw);
    }
  }

  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return the current list of all known routers.

Definition at line 2674 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

Return a smartlist containing a list of trusted_dir_server_t * for all known trusted dirservers.

Callers must not modify the list or its contents.

Definition at line 924 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

Return the trusted_dir_server_t for the directory authority whose identity key hashes to digest, or NULL if no such authority is known.

Definition at line 1016 of file routerlist.c.

{
  if (!trusted_dir_servers)
    return NULL;

  SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
     {
       if (tor_memeq(ds->digest, digest, DIGEST_LEN))
         return ds;
     });

  return NULL;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return true iff we have enough networkstatus and router information to start building circuits.

Right now, this means "more than half the networkstatus documents, and at least 1/4 of expected routers."

Definition at line 4897 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int router_is_named ( const routerinfo_t router)

Return true iff router is listed as named in the current consensus.

Definition at line 2323 of file routerlist.c.

{
  const char *digest =
    networkstatus_get_router_digest_by_nickname(router->nickname);

  return (digest &&
          tor_memeq(digest, router->cache_info.identity_digest, DIGEST_LEN));
}

Here is the call graph for this function:

Here is the caller graph for this function:

void router_load_extrainfo_from_string ( const char *  s,
const char *  eos,
saved_location_t  saved_location,
smartlist_t requested_fingerprints,
int  descriptor_digests 
)

Parse one or more extrainfos from s (ending immediately before eos if eos is present).

Other arguments are as for router_load_routers_from_string().

Definition at line 3968 of file routerlist.c.

{
  smartlist_t *extrainfo_list = smartlist_new();
  const char *msg;
  int from_cache = (saved_location != SAVED_NOWHERE);

  router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
                                NULL);

  log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));

  SMARTLIST_FOREACH(extrainfo_list, extrainfo_t *, ei, {
      was_router_added_t added =
        router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
      if (WRA_WAS_ADDED(added) && requested_fingerprints) {
        char fp[HEX_DIGEST_LEN+1];
        base16_encode(fp, sizeof(fp), descriptor_digests ?
                        ei->cache_info.signed_descriptor_digest :
                        ei->cache_info.identity_digest,
                      DIGEST_LEN);
        smartlist_string_remove(requested_fingerprints, fp);
        /* We silently let people stuff us with extrainfos we didn't ask for,
         * so long as we would have wanted them anyway.  Since we always fetch
         * all the extrainfos we want, and we never actually act on them
         * inside Tor, this should be harmless. */
      }
    });

  routerlist_assert_ok(routerlist);
  router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);

  smartlist_free(extrainfo_list);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int router_load_routers_from_string ( const char *  s,
const char *  eos,
saved_location_t  saved_location,
smartlist_t requested_fingerprints,
int  descriptor_digests,
const char *  prepend_annotations 
)

Given a string s containing some routerdescs, parse it and put the routers into our directory.

If saved_location is SAVED_NOWHERE, the routers are in response to a query to the network: cache them by adding them to the journal.

Return the number of routers actually added.

If requested_fingerprints is provided, it must contain a list of uppercased fingerprints. Do not update any router whose fingerprint is not on the list; after updating a router, remove its fingerprint from the list.

If descriptor_digests is non-zero, then the requested_fingerprints are descriptor digests. Otherwise they are identity digests.

Definition at line 3892 of file routerlist.c.

{
  smartlist_t *routers = smartlist_new(), *changed = smartlist_new();
  char fp[HEX_DIGEST_LEN+1];
  const char *msg;
  int from_cache = (saved_location != SAVED_NOWHERE);
  int allow_annotations = (saved_location != SAVED_NOWHERE);
  int any_changed = 0;

  router_parse_list_from_string(&s, eos, routers, saved_location, 0,
                                allow_annotations, prepend_annotations);

  routers_update_status_from_consensus_networkstatus(routers, !from_cache);

  log_info(LD_DIR, "%d elements to add", smartlist_len(routers));

  SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
    was_router_added_t r;
    char d[DIGEST_LEN];
    if (requested_fingerprints) {
      base16_encode(fp, sizeof(fp), descriptor_digests ?
                      ri->cache_info.signed_descriptor_digest :
                      ri->cache_info.identity_digest,
                    DIGEST_LEN);
      if (smartlist_string_isin(requested_fingerprints, fp)) {
        smartlist_string_remove(requested_fingerprints, fp);
      } else {
        char *requested =
          smartlist_join_strings(requested_fingerprints," ",0,NULL);
        log_warn(LD_DIR,
                 "We received a router descriptor with a fingerprint (%s) "
                 "that we never requested. (We asked for: %s.) Dropping.",
                 fp, requested);
        tor_free(requested);
        routerinfo_free(ri);
        continue;
      }
    }

    memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
    r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
    if (WRA_WAS_ADDED(r)) {
      any_changed++;
      smartlist_add(changed, ri);
      routerlist_descriptors_added(changed, from_cache);
      smartlist_clear(changed);
    } else if (WRA_WAS_REJECTED(r)) {
      download_status_t *dl_status;
      dl_status = router_get_dl_status_by_descriptor_digest(d);
      if (dl_status) {
        log_info(LD_GENERAL, "Marking router %s as never downloadable",
                 hex_str(d, DIGEST_LEN));
        download_status_mark_impossible(dl_status);
      }
    }
  } SMARTLIST_FOREACH_END(ri);

  routerlist_assert_ok(routerlist);

  if (any_changed)
    router_rebuild_store(0, &routerlist->desc_store);

  smartlist_free(routers);
  smartlist_free(changed);

  return any_changed;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int router_load_single_router ( const char *  s,
uint8_t  purpose,
int  cache,
const char **  msg 
)

Code to parse a single router descriptor and insert it into the routerlist.

Return -1 if the descriptor was ill-formed; 0 if the descriptor was well-formed but could not be added; and 1 if the descriptor was added.

If we don't add it and msg is not NULL, then assign to *msg a static string describing the reason for refusing the descriptor.

This is used only by the controller.

Definition at line 3826 of file routerlist.c.

{
  routerinfo_t *ri;
  was_router_added_t r;
  smartlist_t *lst;
  char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  tor_assert(msg);
  *msg = NULL;

  tor_snprintf(annotation_buf, sizeof(annotation_buf),
               "@source controller\n"
               "@purpose %s\n", router_purpose_to_string(purpose));

  if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
    log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
    *msg = "Couldn't parse router descriptor.";
    return -1;
  }
  tor_assert(ri->purpose == purpose);
  if (router_is_me(ri)) {
    log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
    *msg = "Router's identity key matches mine.";
    routerinfo_free(ri);
    return 0;
  }

  if (!cache) /* obey the preference of the controller */
    ri->cache_info.do_not_cache = 1;

  lst = smartlist_new();
  smartlist_add(lst, ri);
  routers_update_status_from_consensus_networkstatus(lst, 0);

  r = router_add_to_routerlist(ri, msg, 0, 0);
  if (!WRA_WAS_ADDED(r)) {
    /* we've already assigned to *msg now, and ri is already freed */
    tor_assert(*msg);
    if (r == ROUTER_AUTHDIR_REJECTS)
      log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
    smartlist_free(lst);
    return 0;
  } else {
    routerlist_descriptors_added(lst, 0);
    smartlist_free(lst);
    log_debug(LD_DIR, "Added router to list");
    return 1;
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

int router_nickname_is_in_list ( const routerinfo_t router,
const char *  list 
)

Return 1 iff any member of the (possibly NULL) comma-separated list list is an acceptable nickname or hexdigest for router.

Else return 0.

Definition at line 1523 of file routerlist.c.

{
  smartlist_t *nickname_list;
  int v = 0;

  if (!list)
    return 0; /* definitely not */
  tor_assert(router);

  nickname_list = smartlist_new();
  smartlist_split_string(nickname_list, list, ",",
    SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  SMARTLIST_FOREACH(nickname_list, const char *, cp,
                    if (router_nickname_matches(router, cp)) {v=1;break;});
  SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  smartlist_free(nickname_list);
  return v;
}

Here is the call graph for this function:

Try to find a running dirserver that supports operations of type.

If there are no running dirservers in our routerlist and the PDS_RETRY_IF_NO_SERVERS flag is set, set all the authoritative ones as running again, and pick one.

If the PDS_IGNORE_FASCISTFIREWALL flag is set, then include dirservers that we can't reach.

If the PDS_ALLOW_SELF flag is not set, then don't include ourself (if we're a dirserver).

Don't pick an authority if any non-authority is viable; try to avoid using servers that have returned 503 recently.

Definition at line 948 of file routerlist.c.

{
  const routerstatus_t *choice;
  if (get_options()->PreferTunneledDirConns)
    flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;

  if (!routerlist)
    return NULL;

  choice = router_pick_directory_server_impl(type, flags);
  if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
    return choice;

  log_info(LD_DIR,
           "No reachable router entries for dirservers. "
           "Trying them all again.");
  /* mark all authdirservers as up again */
  mark_all_trusteddirservers_up();
  /* try again */
  choice = router_pick_directory_server_impl(type, flags);
  return choice;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Try to find a running trusted dirserver.

Flags are as for router_pick_directory_server.

Definition at line 1054 of file routerlist.c.

{
  const routerstatus_t *choice;
  int busy = 0;
  if (get_options()->PreferTunneledDirConns)
    flags |= _PDS_PREFER_TUNNELED_DIR_CONNS;

  choice = router_pick_trusteddirserver_impl(type, flags, &busy);
  if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
    return choice;
  if (busy) {
    /* If the reason that we got no server is that servers are "busy",
     * we must be excluding good servers because we already have serverdesc
     * fetches with them.  Do not mark down servers up because of this. */
    tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
                         PDS_NO_EXISTING_MICRODESC_FETCH)));
    return NULL;
  }

  log_info(LD_DIR,
           "No trusted dirservers are reachable. Trying them all again.");
  mark_all_trusteddirservers_up();
  return router_pick_trusteddirserver_impl(type, flags, NULL);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int router_reload_router_list ( void  )

Load all cached router descriptors and extra-info documents from the store.

Return 0 on success and -1 on failure.

Definition at line 909 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

Reset the descriptor download failure count on all routers, so that we can retry any long-failed routers immediately.

Definition at line 5109 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

Reset all internal variables used to count failed downloads of network status objects.

Definition at line 1357 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

void router_set_status ( const char *  digest,
int  up 
)

Mark the router with ID digest as running or non-running in our routerlist.

Definition at line 3257 of file routerlist.c.

{
  node_t *node;
  tor_assert(digest);

  SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
                    if (tor_memeq(d->digest, digest, DIGEST_LEN))
                      d->is_running = up);

  node = node_get_mutable_by_id(digest);
  if (node) {
#if 0
    log_debug(LD_DIR,"Marking router %s as %s.",
              node_describe(node), up ? "up" : "down");
#endif
    if (!up && node_is_me(node) && !net_is_disabled())
      log_warn(LD_NET, "We just marked ourself as down. Are your external "
               "addresses reachable?");
    node->is_running = up;
  }

  router_dir_info_changed();
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerinfo_free ( routerinfo_t router)

Free all storage held by router.

Definition at line 2700 of file routerlist.c.

{
  if (!router)
    return;

  tor_free(router->cache_info.signed_descriptor_body);
  tor_free(router->address);
  tor_free(router->nickname);
  tor_free(router->platform);
  tor_free(router->contact_info);
  if (router->onion_pkey)
    crypto_pk_free(router->onion_pkey);
  if (router->identity_pkey)
    crypto_pk_free(router->identity_pkey);
  if (router->declared_family) {
    SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
    smartlist_free(router->declared_family);
  }
  addr_policy_list_free(router->exit_policy);

  memset(router, 77, sizeof(routerinfo_t));

  tor_free(router);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int routerinfo_incompatible_with_extrainfo ( const routerinfo_t ri,
extrainfo_t ei,
signed_descriptor_t sd,
const char **  msg 
)

Check whether ri (a.k.a.

sd) is a router compatible with the extrainfo document ei. If no router is compatible with ei, ei should be dropped. Return 0 for "compatible", return 1 for "reject, and inform whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If msg is present, set *msg to a description of the incompatibility (if any).

Definition at line 5217 of file routerlist.c.

{
  int digest_matches, r=1;
  tor_assert(ri);
  tor_assert(ei);
  if (!sd)
    sd = (signed_descriptor_t*)&ri->cache_info;

  if (ei->bad_sig) {
    if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
    return 1;
  }

  digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
                           sd->extra_info_digest, DIGEST_LEN);

  /* The identity must match exactly to have been generated at the same time
   * by the same router. */
  if (tor_memneq(ri->cache_info.identity_digest,
                 ei->cache_info.identity_digest,
                 DIGEST_LEN)) {
    if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
    goto err; /* different servers */
  }

  if (ei->pending_sig) {
    char signed_digest[128];
    if (crypto_pk_public_checksig(ri->identity_pkey,
                       signed_digest, sizeof(signed_digest),
                       ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
        tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
               DIGEST_LEN)) {
      ei->bad_sig = 1;
      tor_free(ei->pending_sig);
      if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
      goto err; /* Bad signature, or no match. */
    }

    ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
    tor_free(ei->pending_sig);
  }

  if (ei->cache_info.published_on < sd->published_on) {
    if (msg) *msg = "Extrainfo published time did not match routerdesc";
    goto err;
  } else if (ei->cache_info.published_on > sd->published_on) {
    if (msg) *msg = "Extrainfo published time did not match routerdesc";
    r = -1;
    goto err;
  }

  if (!digest_matches) {
    if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
    goto err; /* Digest doesn't match declared value. */
  }

  return 0;
 err:
  if (digest_matches) {
    /* This signature was okay, and the digest was right: This is indeed the
     * corresponding extrainfo.  But insanely, it doesn't match the routerinfo
     * that lists it.  Don't try to fetch this one again. */
    sd->extrainfo_is_bogus = 1;
  }

  return r;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerlist_assert_ok ( const routerlist_t rl)

Assert that the internal representation of rl is self-consistent.

Definition at line 5291 of file routerlist.c.

{
  routerinfo_t *r2;
  signed_descriptor_t *sd2;
  if (!rl)
    return;
  SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  {
    r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
    tor_assert(r == r2);
    sd2 = sdmap_get(rl->desc_digest_map,
                    r->cache_info.signed_descriptor_digest);
    tor_assert(&(r->cache_info) == sd2);
    tor_assert(r->cache_info.routerlist_index == r_sl_idx);
    /* XXXX
     *
     *   Hoo boy.  We need to fix this one, and the fix is a bit tricky, so
     * commenting this out is just a band-aid.
     *
     *   The problem is that, although well-behaved router descriptors
     * should never have the same value for their extra_info_digest, it's
     * possible for ill-behaved routers to claim whatever they like there.
     *
     *   The real answer is to trash desc_by_eid_map and instead have
     * something that indicates for a given extra-info digest we want,
     * what its download status is.  We'll do that as a part of routerlist
     * refactoring once consensus directories are in.  For now,
     * this rep violation is probably harmless: an adversary can make us
     * reset our retry count for an extrainfo, but that's not the end
     * of the world.  Changing the representation in 0.2.0.x would just
     * destabilize the codebase.
    if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
      signed_descriptor_t *sd3 =
        sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
      tor_assert(sd3 == &(r->cache_info));
    }
    */
  });
  SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  {
    r2 = rimap_get(rl->identity_map, sd->identity_digest);
    tor_assert(sd != &(r2->cache_info));
    sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
    tor_assert(sd == sd2);
    tor_assert(sd->routerlist_index == sd_sl_idx);
    /* XXXX see above.
    if (!tor_digest_is_zero(sd->extra_info_digest)) {
      signed_descriptor_t *sd3 =
        sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
      tor_assert(sd3 == sd);
    }
    */
  });

  RIMAP_FOREACH(rl->identity_map, d, r) {
    tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
  } DIGESTMAP_FOREACH_END;
  SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
    tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
  } DIGESTMAP_FOREACH_END;
  SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
    tor_assert(!tor_digest_is_zero(d));
    tor_assert(sd);
    tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
  } DIGESTMAP_FOREACH_END;
  EIMAP_FOREACH(rl->extra_info_map, d, ei) {
    signed_descriptor_t *sd;
    tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
                       d, DIGEST_LEN));
    sd = sdmap_get(rl->desc_by_eid_map,
                   ei->cache_info.signed_descriptor_digest);
    // tor_assert(sd); // XXXX see above
    if (sd) {
      tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
                         sd->extra_info_digest, DIGEST_LEN));
    }
  } DIGESTMAP_FOREACH_END;
}

Here is the caller graph for this function:

void routerlist_descriptors_added ( smartlist_t sl,
int  from_cache 
)

We just added a new set of descriptors.

Take whatever extra steps we need.

Definition at line 3799 of file routerlist.c.

{
  tor_assert(sl);
  control_event_descriptors_changed(sl);
  SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
    if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
      learned_bridge_descriptor(ri, from_cache);
    if (ri->needs_retest_if_added) {
      ri->needs_retest_if_added = 0;
      dirserv_single_reachability_test(approx_time(), ri);
    }
  } SMARTLIST_FOREACH_END(ri);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Look through the routerlist until we find a router that has my key.

Return it.

Definition at line 1568 of file routerlist.c.

{
  if (!routerlist)
    return NULL;

  SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  {
    if (router_is_me(router))
      return router;
  });
  return NULL;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerlist_free ( routerlist_t rl)

Free all storage held by a routerlist rl.

Definition at line 2776 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

void routerlist_free_all ( void  )

Free all memory held by the routerlist module.

Definition at line 3214 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

void routerlist_remove ( routerlist_t rl,
routerinfo_t ri,
int  make_old,
time_t  now 
)

Remove an item ri from the routerlist rl, updating indices as needed.

If idx is nonnegative and smartlist_get(rl->routers, idx) == ri, we don't need to do a linear search over the list to decide which to remove. We fill the gap in rl->routers with a later element in the list, if any exists. ri is freed.

If make_old is true, instead of deleting the router, we try adding it to rl->old_routers.

Definition at line 2979 of file routerlist.c.

{
  routerinfo_t *ri_tmp;
  extrainfo_t *ei_tmp;
  int idx = ri->cache_info.routerlist_index;
  tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  tor_assert(smartlist_get(rl->routers, idx) == ri);

  nodelist_remove_routerinfo(ri);

  /* make sure the rephist module knows that it's not running */
  rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);

  ri->cache_info.routerlist_index = -1;
  smartlist_del(rl->routers, idx);
  if (idx < smartlist_len(rl->routers)) {
    routerinfo_t *r = smartlist_get(rl->routers, idx);
    r->cache_info.routerlist_index = idx;
  }

  ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  router_dir_info_changed();
  tor_assert(ri_tmp == ri);

  if (make_old && should_cache_old_descriptors() &&
      ri->purpose == ROUTER_PURPOSE_GENERAL) {
    signed_descriptor_t *sd;
    sd = signed_descriptor_from_routerinfo(ri);
    smartlist_add(rl->old_routers, sd);
    sd->routerlist_index = smartlist_len(rl->old_routers)-1;
    sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
    if (!tor_digest_is_zero(sd->extra_info_digest))
      sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  } else {
    signed_descriptor_t *sd_tmp;
    sd_tmp = sdmap_remove(rl->desc_digest_map,
                          ri->cache_info.signed_descriptor_digest);
    tor_assert(sd_tmp == &(ri->cache_info));
    rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
    ei_tmp = eimap_remove(rl->extra_info_map,
                          ri->cache_info.extra_info_digest);
    if (ei_tmp) {
      rl->extrainfo_store.bytes_dropped +=
        ei_tmp->cache_info.signed_descriptor_len;
      extrainfo_free(ei_tmp);
    }
    if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
      sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
    routerinfo_free(ri);
  }
#ifdef DEBUG_ROUTERLIST
  routerlist_assert_ok(rl);
#endif
}

Here is the call graph for this function:

Here is the caller graph for this function:

Deactivate any routers from the routerlist that are more than ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses; remove old routers from the list of cached routers if we have too many.

Definition at line 3634 of file routerlist.c.

{
  int i, hi=-1;
  const char *cur_id = NULL;
  time_t now = time(NULL);
  time_t cutoff;
  routerinfo_t *router;
  signed_descriptor_t *sd;
  digestset_t *retain;
  int caches = directory_caches_dir_info(get_options());
  const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  int have_enough_v2;
  const or_options_t *options = get_options();

  trusted_dirs_remove_old_certs();

  if (!routerlist || !consensus)
    return;

  // routerlist_assert_ok(routerlist);

  /* We need to guess how many router descriptors we will wind up wanting to
     retain, so that we can be sure to allocate a large enough Bloom filter
     to hold the digest set.  Overestimating is fine; underestimating is bad.
  */
  {
    /* We'll probably retain everything in the consensus. */
    int n_max_retain = smartlist_len(consensus->routerstatus_list);
    if (caches && networkstatus_v2_list) {
      /* If we care about v2 statuses, we'll retain at most as many as are
         listed any of the v2 statues.  This will be at least the length of
         the largest v2 networkstatus, and in the worst case, this set will be
         equal to the sum of the lengths of all v2 consensuses.  Take the
         worst case.
      */
      SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
                        n_max_retain += smartlist_len(ns->entries));
    }
    retain = digestset_new(n_max_retain);
  }

  cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  /* Build a list of all the descriptors that _anybody_ lists. */
  if (caches && networkstatus_v2_list) {
    SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
    {
      /* XXXX The inner loop here gets pretty expensive, and actually shows up
       * on some profiles.  It may be the reason digestmap_set shows up in
       * profiles too.  If instead we kept a per-descriptor digest count of
       * how many networkstatuses recommended each descriptor, and changed
       * that only when the networkstatuses changed, that would be a speed
       * improvement, possibly 1-4% if it also removes digestmap_set from the
       * profile.  Not worth it for 0.1.2.x, though.  The new directory
       * system will obsolete this whole thing in 0.2.0.x. */
      SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
        if (rs->published_on >= cutoff)
          digestset_add(retain, rs->descriptor_digest));
    });
  }

  /* Retain anything listed in the consensus. */
  if (consensus) {
    SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
        if (rs->published_on >= cutoff)
          digestset_add(retain, rs->descriptor_digest));
  }

  /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
   * we should consider pruning current routers that are too old and that
   * nobody recommends.  (If we don't have a consensus or enough v2
   * networkstatuses, then we should get more before we decide to kill
   * routers.) */
  /* we set this to true iff we don't care about v2 info, or we have enough. */
  have_enough_v2 = !caches ||
    !(authdir_mode_any_main(options) || options->FetchV2Networkstatus) ||
    (networkstatus_v2_list &&
     smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);

  if (have_enough_v2 && consensus) {
    cutoff = now - ROUTER_MAX_AGE;
    /* Remove too-old unrecommended members of routerlist->routers. */
    for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
      router = smartlist_get(routerlist->routers, i);
      if (router->cache_info.published_on <= cutoff &&
          router->cache_info.last_listed_as_valid_until < now &&
          !digestset_isin(retain,
                          router->cache_info.signed_descriptor_digest)) {
        /* Too old: remove it.  (If we're a cache, just move it into
         * old_routers.) */
        log_info(LD_DIR,
                 "Forgetting obsolete (too old) routerinfo for router %s",
                 router_describe(router));
        routerlist_remove(routerlist, router, 1, now);
        i--;
      }
    }
  }

  //routerlist_assert_ok(routerlist);

  /* Remove far-too-old members of routerlist->old_routers. */
  cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
    sd = smartlist_get(routerlist->old_routers, i);
    if (sd->published_on <= cutoff &&
        sd->last_listed_as_valid_until < now &&
        !digestset_isin(retain, sd->signed_descriptor_digest)) {
      /* Too old.  Remove it. */
      routerlist_remove_old(routerlist, sd, i--);
    }
  }

  //routerlist_assert_ok(routerlist);

  log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
           smartlist_len(routerlist->routers),
           smartlist_len(routerlist->old_routers));

  /* Now we might have to look at routerlist->old_routers for extraneous
   * members. (We'd keep all the members if we could, but we need to save
   * space.) First, check whether we have too many router descriptors, total.
   * We're okay with having too many for some given router, so long as the
   * total number doesn't approach max_descriptors_per_router()*len(router).
   */
  if (smartlist_len(routerlist->old_routers) <
      smartlist_len(routerlist->routers))
    goto done;

  /* Sort by identity, then fix indices. */
  smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
  /* Fix indices. */
  for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
    signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
    r->routerlist_index = i;
  }

  /* Iterate through the list from back to front, so when we remove descriptors
   * we don't mess up groups we haven't gotten to. */
  for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
    signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
    if (!cur_id) {
      cur_id = r->identity_digest;
      hi = i;
    }
    if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
      routerlist_remove_old_cached_routers_with_id(now,
                                                   cutoff, i+1, hi, retain);
      cur_id = r->identity_digest;
      hi = i;
    }
  }
  if (hi>=0)
    routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
  //routerlist_assert_ok(routerlist);

 done:
  digestset_free(retain);
  router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
  router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerlist_reset_warnings ( void  )

Forget that we have issued any router-related warnings, so that we'll warn again if we see the same errors.

Definition at line 3244 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

Clear all our timeouts for fetching v2 and v3 directory stuff, and then give it all a try again.

Definition at line 4049 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int routers_have_same_or_addr ( const routerinfo_t r1,
const routerinfo_t r2 
)

Return true iff r1 and r2 have the same address and OR port.

Definition at line 1349 of file routerlist.c.

{
  return r1->addr == r2->addr && r1->or_port == r2->or_port;
}

Here is the caller graph for this function:

Sort a list of routerinfo_t in ascending order of identity digest.

Definition at line 5413 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int routerset_contains_extendinfo ( const routerset_t set,
const extend_info_t ei 
)

Return true iff we can tell that ei is a member of set.

Definition at line 5655 of file routerlist.c.

{
  return routerset_contains(set,
                            &ei->addr,
                            ei->port,
                            ei->nickname,
                            ei->identity_digest,
                            -1 /*country*/);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int routerset_contains_node ( const routerset_t set,
const node_t node 
)

Return true iff node is in set.

Definition at line 5700 of file routerlist.c.

{
  if (node->rs)
    return routerset_contains_routerstatus(set, node->rs, node->country);
  else if (node->ri)
    return routerset_contains_router(set, node->ri, node->country);
  else
    return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int routerset_contains_router ( const routerset_t set,
const routerinfo_t ri,
country_t  country 
)

Return true iff ri is in set.

If country is -1, we look up the country.

Definition at line 5668 of file routerlist.c.

{
  tor_addr_t addr;
  tor_addr_from_ipv4h(&addr, ri->addr);
  return routerset_contains(set,
                            &addr,
                            ri->or_port,
                            ri->nickname,
                            ri->cache_info.identity_digest,
                            country);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int routerset_contains_routerstatus ( const routerset_t set,
const routerstatus_t rs,
country_t  country 
)

Return true iff rs is in set.

If country is -1, we look up the country.

Definition at line 5684 of file routerlist.c.

{
  tor_addr_t addr;
  tor_addr_from_ipv4h(&addr, rs->addr);
  return routerset_contains(set,
                            &addr,
                            rs->or_port,
                            rs->nickname,
                            rs->identity_digest,
                            country);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int routerset_equal ( const routerset_t old,
const routerset_t new 
)

Helper: return true iff old and new are both NULL, or both non-NULL equal routersets.

Definition at line 5807 of file routerlist.c.

{
  if (routerset_is_empty(old) && routerset_is_empty(new)) {
    /* Two empty sets are equal */
    return 1;
  } else if (routerset_is_empty(old) || routerset_is_empty(new)) {
    /* An empty set is equal to nothing else. */
    return 0;
  }
  tor_assert(old != NULL);
  tor_assert(new != NULL);

  if (smartlist_len(old->list) != smartlist_len(new->list))
    return 0;

  SMARTLIST_FOREACH(old->list, const char *, cp1, {
    const char *cp2 = smartlist_get(new->list, cp1_sl_idx);
    if (strcmp(cp1, cp2))
      return 0;
  });

  return 1;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerset_free ( routerset_t routerset)

Free all storage held in routerset.

Definition at line 5833 of file routerlist.c.

{
  if (!routerset)
    return;

  SMARTLIST_FOREACH(routerset->list, char *, cp, tor_free(cp));
  smartlist_free(routerset->list);
  SMARTLIST_FOREACH(routerset->policies, addr_policy_t *, p,
                    addr_policy_free(p));
  smartlist_free(routerset->policies);
  SMARTLIST_FOREACH(routerset->country_names, char *, cp, tor_free(cp));
  smartlist_free(routerset->country_names);

  strmap_free(routerset->names, NULL);
  digestmap_free(routerset->digests, NULL);
  bitarray_free(routerset->countries);
  tor_free(routerset);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerset_get_all_nodes ( smartlist_t out,
const routerset_t routerset,
const routerset_t excludeset,
int  running_only 
)

Add every known node_t that is a member of routerset to out, but never add any that are part of excludeset.

If running_only, only add the running ones.

Definition at line 5714 of file routerlist.c.

{ /* XXXX MOVE */
  tor_assert(out);
  if (!routerset || !routerset->list)
    return;

  if (routerset_is_list(routerset)) {
    /* No routers are specified by type; all are given by name or digest.
     * we can do a lookup in O(len(routerset)). */
    SMARTLIST_FOREACH(routerset->list, const char *, name, {
        const node_t *node = node_get_by_nickname(name, 1);
        if (node) {
          if (!running_only || node->is_running)
            if (!routerset_contains_node(excludeset, node))
              smartlist_add(out, (void*)node);
        }
    });
  } else {
    /* We need to iterate over the routerlist to get all the ones of the
     * right kind. */
    smartlist_t *nodes = nodelist_get_list();
    SMARTLIST_FOREACH(nodes, const node_t *, node, {
        if (running_only && !node->is_running)
          continue;
        if (routerset_contains_node(routerset, node) &&
            !routerset_contains_node(excludeset, node))
          smartlist_add(out, (void*)node);
    });
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

int routerset_is_empty ( const routerset_t set)

Return true iff there are no entries in set.

Definition at line 5615 of file routerlist.c.

{
  return !set || smartlist_len(set->list) == 0;
}

Here is the caller graph for this function:

int routerset_is_list ( const routerset_t set)

Return true iff set lists only nicknames and digests, and includes no IP ranges or countries.

Definition at line 5599 of file routerlist.c.

{
  return smartlist_len(set->country_names) == 0 &&
    smartlist_len(set->policies) == 0;
}

Here is the caller graph for this function:

int routerset_needs_geoip ( const routerset_t set)

Return true iff we need a GeoIP IP-to-country database to make sense of set.

Definition at line 5608 of file routerlist.c.

{
  return set && smartlist_len(set->country_names);
}

Here is the caller graph for this function:

Return a new empty routerset.

Definition at line 5453 of file routerlist.c.

{
  routerset_t *result = tor_malloc_zero(sizeof(routerset_t));
  result->list = smartlist_new();
  result->names = strmap_new();
  result->digests = digestmap_new();
  result->policies = smartlist_new();
  result->country_names = smartlist_new();
  return result;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int routerset_parse ( routerset_t target,
const char *  s,
const char *  description 
)

Parse the string s to create a set of routerset entries, and add them to target.

In log messages, refer to the string as description. Return 0 on success, -1 on failure.

Three kinds of elements are allowed in routersets: nicknames, IP address patterns, and fingerprints. They may be surrounded by optional space, and must be separated by commas.

Definition at line 5516 of file routerlist.c.

{
  int r = 0;
  int added_countries = 0;
  char *countryname;
  smartlist_t *list = smartlist_new();
  smartlist_split_string(list, s, ",",
                         SPLIT_SKIP_SPACE | SPLIT_IGNORE_BLANK, 0);
  SMARTLIST_FOREACH_BEGIN(list, char *, nick) {
      addr_policy_t *p;
      if (is_legal_hexdigest(nick)) {
        char d[DIGEST_LEN];
        if (*nick == '$')
          ++nick;
        log_debug(LD_CONFIG, "Adding identity %s to %s", nick, description);
        base16_decode(d, sizeof(d), nick, HEX_DIGEST_LEN);
        digestmap_set(target->digests, d, (void*)1);
      } else if (is_legal_nickname(nick)) {
        log_debug(LD_CONFIG, "Adding nickname %s to %s", nick, description);
        strmap_set_lc(target->names, nick, (void*)1);
      } else if ((countryname = routerset_get_countryname(nick)) != NULL) {
        log_debug(LD_CONFIG, "Adding country %s to %s", nick,
                  description);
        smartlist_add(target->country_names, countryname);
        added_countries = 1;
      } else if ((strchr(nick,'.') || strchr(nick, '*')) &&
                 (p = router_parse_addr_policy_item_from_string(
                                     nick, ADDR_POLICY_REJECT))) {
        log_debug(LD_CONFIG, "Adding address %s to %s", nick, description);
        smartlist_add(target->policies, p);
      } else {
        log_warn(LD_CONFIG, "Entry '%s' in %s is misformed.", nick,
                 description);
        r = -1;
        tor_free(nick);
        SMARTLIST_DEL_CURRENT(list, nick);
      }
  } SMARTLIST_FOREACH_END(nick);
  smartlist_add_all(target->list, list);
  smartlist_free(list);
  if (added_countries)
    routerset_refresh_countries(target);
  return r;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Update the routerset's countries bitarray_t.

Called whenever the GeoIP database is reloaded.

Definition at line 5483 of file routerlist.c.

{
  int cc;
  bitarray_free(target->countries);

  if (!geoip_is_loaded()) {
    target->countries = NULL;
    target->n_countries = 0;
    return;
  }
  target->n_countries = geoip_get_n_countries();
  target->countries = bitarray_init_zero(target->n_countries);
  SMARTLIST_FOREACH_BEGIN(target->country_names, const char *, country) {
    cc = geoip_get_country(country);
    if (cc >= 0) {
      tor_assert(cc < target->n_countries);
      bitarray_set(target->countries, cc);
    } else {
      log(LOG_WARN, LD_CONFIG, "Country code '%s' is not recognized.",
          country);
    }
  } SMARTLIST_FOREACH_END(country);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerset_subtract_nodes ( smartlist_t lst,
const routerset_t routerset 
)

Remove every node_t from lst that is in routerset.

Definition at line 5781 of file routerlist.c.

{ /*XXXX MOVE ? */
  tor_assert(lst);
  if (!routerset)
    return;
  SMARTLIST_FOREACH(lst, const node_t *, node, {
      if (routerset_contains_node(routerset, node)) {
        //log_debug(LD_DIR, "Subtracting %s",r->nickname);
        SMARTLIST_DEL_CURRENT(lst, node);
      }
    });
}

Here is the call graph for this function:

Here is the caller graph for this function:

char* routerset_to_string ( const routerset_t set)

Return a new string that when parsed by routerset_parse_string() will yield set.

Definition at line 5797 of file routerlist.c.

{
  if (!set || !set->list)
    return tor_strdup("");
  return smartlist_join_strings(set->list, ",", 0, NULL);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void routerset_union ( routerset_t target,
const routerset_t source 
)

Add all members of the set source to target.

Definition at line 5585 of file routerlist.c.

{
  char *s;
  tor_assert(target);
  if (!source || !source->list)
    return;
  s = routerset_to_string(source);
  routerset_parse(target, s, "other routerset");
  tor_free(s);
}

Here is the call graph for this function:

Here is the caller graph for this function:

As signed_descriptor_get_body(), but points to the beginning of the annotations section rather than the beginning of the descriptor.

Definition at line 2667 of file routerlist.c.

{
  return signed_descriptor_get_body_impl(desc, 1);
}

Here is the call graph for this function:

Here is the caller graph for this function:

const char* signed_descriptor_get_body ( const signed_descriptor_t desc)

Return a pointer to the signed textual representation of a descriptor.

The returned string is not guaranteed to be NUL-terminated: the string's length will be in desc->signed_descriptor_len.

The caller must not free the string returned.

Definition at line 2659 of file routerlist.c.

{
  return signed_descriptor_get_body_impl(desc, 0);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Save all v3 key certificates to the cached-certs file.

Definition at line 292 of file routerlist.c.

{
  char *filename;
  smartlist_t *chunks;

  if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
    return;

  chunks = smartlist_new();
  DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
    SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
          {
            sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
            c->bytes = cert->cache_info.signed_descriptor_body;
            c->len = cert->cache_info.signed_descriptor_len;
            smartlist_add(chunks, c);
          });
  } DIGESTMAP_FOREACH_END;

  filename = get_datadir_fname("cached-certs");
  if (write_chunks_to_file(filename, chunks, 0)) {
    log_warn(LD_FS, "Error writing certificates to disk.");
  }
  tor_free(filename);
  SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
  smartlist_free(chunks);

  trusted_dir_servers_certs_changed = 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int trusted_dirs_load_certs_from_string ( const char *  contents,
int  from_store,
int  flush 
)

Load a bunch of new key certificates from the string contents.

If from_store is true, the certificates are from the cache, and we don't need to flush them to disk. If flush is true, we need to flush any changed certificates to disk now. Return 0 on success, -1 if any certs fail to parse.

Definition at line 190 of file routerlist.c.

{
  trusted_dir_server_t *ds;
  const char *s, *eos;
  int failure_code = 0;

  for (s = contents; *s; s = eos) {
    authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
    cert_list_t *cl;
    if (!cert) {
      failure_code = -1;
      break;
    }
    ds = trusteddirserver_get_by_v3_auth_digest(
                                       cert->cache_info.identity_digest);
    log_debug(LD_DIR, "Parsed certificate for %s",
              ds ? ds->nickname : "unknown authority");

    if (already_have_cert(cert)) {
      /* we already have this one. continue. */
      log_info(LD_DIR, "Skipping %s certificate for %s that we "
               "already have.",
               from_store ? "cached" : "downloaded",
               ds ? ds->nickname : "an old or new authority");

      /* a duplicate on a download should be treated as a failure, since it
       * probably means we wanted a different secret key or we are trying to
       * replace an expired cert that has not in fact been updated. */
      if (!from_store) {
        if (authdir_mode(get_options())) {
          log_warn(LD_DIR,
                   "Got a certificate for %s, but we already have it. "
                   "Maybe they haven't updated it. Waiting for a while.",
                   ds ? ds->nickname : "an old or new authority");
        } else {
          log_info(LD_DIR,
                   "Got a certificate for %s, but we already have it. "
                   "Maybe they haven't updated it. Waiting for a while.",
                   ds ? ds->nickname : "an old or new authority");
        }

        authority_cert_dl_failed(cert->cache_info.identity_digest, 404);
      }

      authority_cert_free(cert);
      continue;
    }

    if (ds) {
      log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
               "signing key %s", from_store ? "cached" : "downloaded",
               ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
    } else {
      int adding = directory_caches_unknown_auth_certs(get_options());
      log_info(LD_DIR, "%s %s certificate for unrecognized directory "
               "authority with signing key %s",
               adding ? "Adding" : "Not adding",
               from_store ? "cached" : "downloaded",
               hex_str(cert->signing_key_digest,DIGEST_LEN));
      if (!adding) {
        authority_cert_free(cert);
        continue;
      }
    }

    cl = get_cert_list(cert->cache_info.identity_digest);
    smartlist_add(cl->certs, cert);
    if (ds && cert->cache_info.published_on > ds->addr_current_at) {
      /* Check to see whether we should update our view of the authority's
       * address. */
      if (cert->addr && cert->dir_port &&
          (ds->addr != cert->addr ||
           ds->dir_port != cert->dir_port)) {
        char *a = tor_dup_ip(cert->addr);
        log_notice(LD_DIR, "Updating address for directory authority %s "
                   "from %s:%d to %s:%d based on certificate.",
                   ds->nickname, ds->address, (int)ds->dir_port,
                   a, cert->dir_port);
        tor_free(a);
        ds->addr = cert->addr;
        ds->dir_port = cert->dir_port;
      }
      ds->addr_current_at = cert->cache_info.published_on;
    }

    if (!from_store)
      trusted_dir_servers_certs_changed = 1;
  }

  if (flush)
    trusted_dirs_flush_certs_to_disk();

  /* call this even if failure_code is <0, since some certs might have
   * succeeded. */
  networkstatus_note_certs_arrived();

  return failure_code;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int trusted_dirs_reload_certs ( void  )

Reload the cached v3 key certificates from the cached-certs file in the data directory.

Return 0 on success, -1 on failure.

Definition at line 151 of file routerlist.c.

{
  char *filename;
  char *contents;
  int r;

  filename = get_datadir_fname("cached-certs");
  contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  tor_free(filename);
  if (!contents)
    return 0;
  r = trusted_dirs_load_certs_from_string(contents, 1, 1);
  tor_free(contents);
  return r;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return the trusted_dir_server_t for the directory authority whose v3 identity key hashes to digest, or NULL if no such authority is known.

Definition at line 1035 of file routerlist.c.

{
  if (!trusted_dir_servers)
    return NULL;

  SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
     {
       if (tor_memeq(ds->v3_identity_digest, digest, DIGEST_LEN) &&
           (ds->type & V3_DIRINFO))
         return ds;
     });

  return NULL;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void update_all_descriptor_downloads ( time_t  now)

Update downloads for router descriptors and/or microdescriptors as appropriate.

Definition at line 4037 of file routerlist.c.

Here is the call graph for this function:

Here is the caller graph for this function:

void update_consensus_router_descriptor_downloads ( time_t  now,
int  is_vote,
networkstatus_t consensus 
)

For any descriptor that we want that's currently listed in consensus, download it as appropriate.

Definition at line 4639 of file routerlist.c.

{
  const or_options_t *options = get_options();
  digestmap_t *map = NULL;
  smartlist_t *no_longer_old = smartlist_new();
  smartlist_t *downloadable = smartlist_new();
  routerstatus_t *source = NULL;
  int authdir = authdir_mode(options);
  int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
    n_inprogress=0, n_in_oldrouters=0;

  if (directory_too_idle_to_fetch_descriptors(options, now))
    goto done;
  if (!consensus)
    goto done;

  if (is_vote) {
    /* where's it from, so we know whom to ask for descriptors */
    trusted_dir_server_t *ds;
    networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
    tor_assert(voter);
    ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
    if (ds)
      source = &(ds->fake_status);
    else
      log_warn(LD_DIR, "couldn't lookup source from vote?");
  }

  map = digestmap_new();
  list_pending_descriptor_downloads(map, 0);
  SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
      routerstatus_t *rs =
        is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
      signed_descriptor_t *sd;
      if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
        const routerinfo_t *ri;
        ++n_have;
        if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||