LCOV - code coverage report
Current view: top level - feature/client - entrynodes.c (source / functions) Hit Total Coverage
Test: lcov.info Lines: 1339 1581 84.7 %
Date: 2021-11-24 03:28:48 Functions: 111 129 86.0 %

          Line data    Source code
       1             : /* Copyright (c) 2001 Matej Pfajfar.
       2             :  * Copyright (c) 2001-2004, Roger Dingledine.
       3             :  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
       4             :  * Copyright (c) 2007-2021, The Tor Project, Inc. */
       5             : /* See LICENSE for licensing information */
       6             : 
       7             : /**
       8             :  * \file entrynodes.c
       9             :  * \brief Code to manage our fixed first nodes for various functions.
      10             :  *
      11             :  * Entry nodes can be guards (for general use) or bridges (for censorship
      12             :  * circumvention).
      13             :  *
      14             :  * In general, we use entry guards to prevent traffic-sampling attacks:
      15             :  * if we chose every circuit independently, an adversary controlling
      16             :  * some fraction of paths on the network would observe a sample of every
      17             :  * user's traffic. Using guards gives users a chance of not being
      18             :  * profiled.
      19             :  *
      20             :  * The current entry guard selection code is designed to try to avoid
      21             :  * _ever_ trying every guard on the network, to try to stick to guards
      22             :  * that we've used before, to handle hostile/broken networks, and
      23             :  * to behave sanely when the network goes up and down.
      24             :  *
      25             :  * Our algorithm works as follows: First, we maintain a SAMPLE of guards
      26             :  * we've seen in the networkstatus consensus.  We maintain this sample
      27             :  * over time, and store it persistently; it is chosen without reference
      28             :  * to our configuration or firewall rules.  Guards remain in the sample
      29             :  * as they enter and leave the consensus.  We expand this sample as
      30             :  * needed, up to a maximum size.
      31             :  *
      32             :  * As a subset of the sample, we maintain a FILTERED SET of the guards
      33             :  * that we would be willing to use if we could connect to them.  The
      34             :  * filter removes all the guards that we're excluding because they're
      35             :  * bridges (or not bridges), because we have restrictive firewall rules,
      36             :  * because of ExcludeNodes, because we of path bias restrictions,
      37             :  * because they're absent from the network at present, and so on.
      38             :  *
      39             :  * As a subset of the filtered set, we keep a REACHABLE FILTERED SET
      40             :  * (also called a "usable filtered set") of those guards that we call
      41             :  * "reachable" or "maybe reachable".  A guard is reachable if we've
      42             :  * connected to it more recently than we've failed.  A guard is "maybe
      43             :  * reachable" if we have never tried to connect to it, or if we
      44             :  * failed to connect to it so long ago that we no longer think our
      45             :  * failure means it's down.
      46             :  *
      47             :  * As a persistent ordered list whose elements are taken from the
      48             :  * sampled set, we track a CONFIRMED GUARDS LIST.  A guard becomes
      49             :  * confirmed when we successfully build a circuit through it, and decide
      50             :  * to use that circuit.
      51             :  *
      52             :  * And as a final group, we have an ordered list of PRIMARY GUARDS,
      53             :  * whose elements are taken from the filtered set. We prefer
      54             :  * confirmed guards to non-confirmed guards for this list, and place
      55             :  * other restrictions on it.  The primary guards are the ones that we
      56             :  * connect to "when nothing is wrong" -- circuits through them can be used
      57             :  * immediately.
      58             :  *
      59             :  * To build circuits, we take a primary guard if possible -- or a
      60             :  * reachable filtered confirmed guard if no primary guard is possible --
      61             :  * or the first (by sampled order) filtered guard otherwise.  If the guard is
      62             :  * primary, we can use the circuit immediately on success.  Otherwise,
      63             :  * the guard is now "pending" -- we won't use its circuit unless all
      64             :  * of the circuits we're trying to build through better guards have
      65             :  * definitely failed.
      66             :  *
      67             :  * While we're building circuits, we track a little "guard state" for
      68             :  * each circuit. We use this to keep track of whether the circuit is
      69             :  * one that we can use as soon as it's done, or whether it's one that
      70             :  * we should keep around to see if we can do better.  In the latter case,
      71             :  * a periodic call to entry_guards_upgrade_waiting_circuits() will
      72             :  * eventually upgrade it.
      73             :  **/
      74             : /* DOCDOC -- expand this.
      75             :  *
      76             :  * Information invariants:
      77             :  *
      78             :  * [x] whenever a guard becomes unreachable, clear its usable_filtered flag.
      79             :  *
      80             :  * [x] Whenever a guard becomes reachable or maybe-reachable, if its filtered
      81             :  * flag is set, set its usable_filtered flag.
      82             :  *
      83             :  * [x] Whenever we get a new consensus, call update_from_consensus(). (LATER.)
      84             :  *
      85             :  * [x] Whenever the configuration changes in a relevant way, update the
      86             :  * filtered/usable flags. (LATER.)
      87             :  *
      88             :  * [x] Whenever we add a guard to the sample, make sure its filtered/usable
      89             :  * flags are set as possible.
      90             :  *
      91             :  * [x] Whenever we remove a guard from the sample, remove it from the primary
      92             :  * and confirmed lists.
      93             :  *
      94             :  * [x] When we make a guard confirmed, update the primary list, and sort them
      95             :  * by sampled order.
      96             :  *
      97             :  * [x] When we make a guard filtered or unfiltered, update the primary list.
      98             :  *
      99             :  * [x] When we are about to pick a guard, make sure that the primary list is
     100             :  * full.
     101             :  *
     102             :  * [x] When we update the confirmed list, or when we re-build the primary list
     103             :  * and detect a change, we sort those lists by sampled_idx
     104             :  *
     105             :  * [x] Before calling first_reachable_filtered_entry_guard(), make sure
     106             :  * that the filtered, primary, and confirmed flags are up-to-date.
     107             :  *
     108             :  * [x] Call entry_guard_consider_retry every time we are about to check
     109             :  * is_usable_filtered or is_reachable, and every time we set
     110             :  * is_filtered to 1.
     111             :  *
     112             :  * [x] Call entry_guards_changed_for_guard_selection() whenever we update
     113             :  * a persistent field.
     114             :  */
     115             : 
     116             : #define ENTRYNODES_PRIVATE
     117             : 
     118             : #include "core/or/or.h"
     119             : #include "app/config/config.h"
     120             : #include "lib/confmgt/confmgt.h"
     121             : #include "app/config/statefile.h"
     122             : #include "core/mainloop/connection.h"
     123             : #include "core/mainloop/mainloop.h"
     124             : #include "core/or/channel.h"
     125             : #include "core/or/circuitbuild.h"
     126             : #include "core/or/circuitlist.h"
     127             : #include "core/or/circuitstats.h"
     128             : #include "core/or/circuituse.h"
     129             : #include "core/or/policies.h"
     130             : #include "feature/client/bridges.h"
     131             : #include "feature/client/circpathbias.h"
     132             : #include "feature/client/entrynodes.h"
     133             : #include "feature/client/transports.h"
     134             : #include "feature/control/control_events.h"
     135             : #include "feature/dircommon/directory.h"
     136             : #include "feature/nodelist/describe.h"
     137             : #include "feature/nodelist/microdesc.h"
     138             : #include "feature/nodelist/networkstatus.h"
     139             : #include "feature/nodelist/nickname.h"
     140             : #include "feature/nodelist/nodelist.h"
     141             : #include "feature/nodelist/node_select.h"
     142             : #include "feature/nodelist/routerset.h"
     143             : #include "feature/relay/router.h"
     144             : #include "lib/crypt_ops/crypto_rand.h"
     145             : #include "lib/crypt_ops/digestset.h"
     146             : #include "lib/encoding/confline.h"
     147             : #include "lib/math/fp.h"
     148             : 
     149             : #include "feature/nodelist/node_st.h"
     150             : #include "core/or/origin_circuit_st.h"
     151             : #include "app/config/or_state_st.h"
     152             : 
     153             : /** A list of existing guard selection contexts. */
     154             : static smartlist_t *guard_contexts = NULL;
     155             : /** The currently enabled guard selection context. */
     156             : static guard_selection_t *curr_guard_context = NULL;
     157             : 
     158             : /** A value of 1 means that at least one context has changed,
     159             :  * and those changes need to be flushed to disk. */
     160             : static int entry_guards_dirty = 0;
     161             : 
     162             : static void entry_guard_set_filtered_flags(const or_options_t *options,
     163             :                                            guard_selection_t *gs,
     164             :                                            entry_guard_t *guard);
     165             : static void pathbias_check_use_success_count(entry_guard_t *guard);
     166             : static void pathbias_check_close_success_count(entry_guard_t *guard);
     167             : static int node_is_possible_guard(const node_t *node);
     168             : static int node_passes_guard_filter(const or_options_t *options,
     169             :                                     const node_t *node);
     170             : static entry_guard_t *entry_guard_add_to_sample_impl(guard_selection_t *gs,
     171             :                                const uint8_t *rsa_id_digest,
     172             :                                const char *nickname,
     173             :                                const tor_addr_port_t *bridge_addrport);
     174             : static entry_guard_t *get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
     175             :                                               const tor_addr_port_t *addrport);
     176             : static int entry_guard_obeys_restriction(const entry_guard_t *guard,
     177             :                                          const entry_guard_restriction_t *rst);
     178             : static int compare_guards_by_sampled_idx(const void **a_, const void **b_);
     179             : 
     180             : /** Return 0 if we should apply guardfraction information found in the
     181             :  *  consensus. A specific consensus can be specified with the
     182             :  *  <b>ns</b> argument, if NULL the most recent one will be picked.*/
     183             : int
     184           9 : should_apply_guardfraction(const networkstatus_t *ns)
     185             : {
     186             :   /* We need to check the corresponding torrc option and the consensus
     187             :    * parameter if we need to. */
     188           9 :   const or_options_t *options = get_options();
     189             : 
     190             :   /* If UseGuardFraction is 'auto' then check the same-named consensus
     191             :    * parameter. If the consensus parameter is not present, default to
     192             :    * "off". */
     193           9 :   if (options->UseGuardFraction == -1) {
     194           3 :     return networkstatus_get_param(ns, "UseGuardFraction",
     195             :                                    0, /* default to "off" */
     196             :                                    0, 1);
     197             :   }
     198             : 
     199             :   return options->UseGuardFraction;
     200             : }
     201             : 
     202             : /** Return true iff we know a preferred descriptor for <b>guard</b> */
     203             : static int
     204        1512 : guard_has_descriptor(const entry_guard_t *guard)
     205             : {
     206        1512 :   const node_t *node = node_get_by_id(guard->identity);
     207        1512 :   if (!node)
     208             :     return 0;
     209        1509 :   return node_has_preferred_descriptor(node, 1);
     210             : }
     211             : 
     212             : /**
     213             :  * Try to determine the correct type for a selection named "name",
     214             :  * if <b>type</b> is GS_TYPE_INFER.
     215             :  */
     216             : STATIC guard_selection_type_t
     217         116 : guard_selection_infer_type(guard_selection_type_t type,
     218             :                            const char *name)
     219             : {
     220         116 :   if (type == GS_TYPE_INFER) {
     221           7 :     if (!strcmp(name, "bridges"))
     222             :       type = GS_TYPE_BRIDGE;
     223           5 :     else if (!strcmp(name, "restricted"))
     224             :       type = GS_TYPE_RESTRICTED;
     225             :     else
     226           5 :       type = GS_TYPE_NORMAL;
     227             :   }
     228         116 :   return type;
     229             : }
     230             : 
     231             : /**
     232             :  * Allocate and return a new guard_selection_t, with the name <b>name</b>.
     233             :  */
     234             : STATIC guard_selection_t *
     235         116 : guard_selection_new(const char *name,
     236             :                     guard_selection_type_t type)
     237             : {
     238         116 :   guard_selection_t *gs;
     239             : 
     240         116 :   type = guard_selection_infer_type(type, name);
     241             : 
     242         116 :   gs = tor_malloc_zero(sizeof(*gs));
     243         116 :   gs->name = tor_strdup(name);
     244         116 :   gs->type = type;
     245         116 :   gs->sampled_entry_guards = smartlist_new();
     246         116 :   gs->confirmed_entry_guards = smartlist_new();
     247         116 :   gs->primary_entry_guards = smartlist_new();
     248             : 
     249         116 :   return gs;
     250             : }
     251             : 
     252             : /**
     253             :  * Return the guard selection called <b>name</b>. If there is none, and
     254             :  * <b>create_if_absent</b> is true, then create and return it.  If there
     255             :  * is none, and <b>create_if_absent</b> is false, then return NULL.
     256             :  */
     257             : STATIC guard_selection_t *
     258          63 : get_guard_selection_by_name(const char *name,
     259             :                             guard_selection_type_t type,
     260             :                             int create_if_absent)
     261             : {
     262          63 :   if (!guard_contexts) {
     263           4 :     guard_contexts = smartlist_new();
     264             :   }
     265          87 :   SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
     266          50 :     if (!strcmp(gs->name, name))
     267          26 :       return gs;
     268          24 :   } SMARTLIST_FOREACH_END(gs);
     269             : 
     270          37 :   if (! create_if_absent)
     271             :     return NULL;
     272             : 
     273          32 :   log_debug(LD_GUARD, "Creating a guard selection called %s", name);
     274          32 :   guard_selection_t *new_selection = guard_selection_new(name, type);
     275          32 :   smartlist_add(guard_contexts, new_selection);
     276             : 
     277          32 :   return new_selection;
     278             : }
     279             : 
     280             : /**
     281             :  * Allocate the first guard context that we're planning to use,
     282             :  * and make it the current context.
     283             :  */
     284             : static void
     285          23 : create_initial_guard_context(void)
     286             : {
     287          23 :   tor_assert(! curr_guard_context);
     288          23 :   if (!guard_contexts) {
     289          16 :     guard_contexts = smartlist_new();
     290             :   }
     291          23 :   guard_selection_type_t type = GS_TYPE_INFER;
     292          23 :   const char *name = choose_guard_selection(
     293             :                              get_options(),
     294          23 :                              networkstatus_get_reasonably_live_consensus(
     295             :                                                     approx_time(),
     296             :                                                     usable_consensus_flavor()),
     297             :                              NULL,
     298             :                              &type);
     299          23 :   tor_assert(name); // "name" can only be NULL if we had an old name.
     300          23 :   tor_assert(type != GS_TYPE_INFER);
     301          23 :   log_notice(LD_GUARD, "Starting with guard context \"%s\"", name);
     302          23 :   curr_guard_context = get_guard_selection_by_name(name, type, 1);
     303          23 : }
     304             : 
     305             : /** Get current default guard_selection_t, creating it if necessary */
     306             : guard_selection_t *
     307         245 : get_guard_selection_info(void)
     308             : {
     309         245 :   if (!curr_guard_context) {
     310          22 :     create_initial_guard_context();
     311             :   }
     312             : 
     313         245 :   return curr_guard_context;
     314             : }
     315             : 
     316             : /** Return a statically allocated human-readable description of <b>guard</b>
     317             :  */
     318             : const char *
     319        3813 : entry_guard_describe(const entry_guard_t *guard)
     320             : {
     321        3813 :   static char buf[256];
     322        3813 :   tor_snprintf(buf, sizeof(buf),
     323             :                "%s ($%s)",
     324        3813 :                strlen(guard->nickname) ? guard->nickname : "[bridge]",
     325        3813 :                hex_str(guard->identity, DIGEST_LEN));
     326        3813 :   return buf;
     327             : }
     328             : 
     329             : /** Return <b>guard</b>'s 20-byte RSA identity digest */
     330             : const char *
     331           0 : entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
     332             : {
     333           0 :   return guard->identity;
     334             : }
     335             : 
     336             : /** Return the pathbias state associated with <b>guard</b>. */
     337             : guard_pathbias_t *
     338          29 : entry_guard_get_pathbias_state(entry_guard_t *guard)
     339             : {
     340          29 :   return &guard->pb;
     341             : }
     342             : 
     343        2702 : HANDLE_IMPL(entry_guard, entry_guard_t, ATTR_UNUSED STATIC)
     344             : 
     345             : /** Return an interval between 'now' and 'max_backdate' seconds in the past,
     346             :  * chosen uniformly at random.  We use this before recording persistent
     347             :  * dates, so that we aren't leaking exactly when we recorded it.
     348             :  */
     349        4841 : MOCK_IMPL(STATIC time_t,
     350             : randomize_time,(time_t now, time_t max_backdate))
     351             : {
     352        4841 :   tor_assert(max_backdate > 0);
     353             : 
     354        4841 :   time_t earliest = now - max_backdate;
     355        4841 :   time_t latest = now;
     356        4841 :   if (earliest <= 0)
     357             :     earliest = 1;
     358        4841 :   if (latest <= earliest)
     359        1000 :     latest = earliest + 1;
     360             : 
     361        4841 :   return crypto_rand_time_range(earliest, latest);
     362             : }
     363             : 
     364             : /**
     365             :  * @name parameters for networkstatus algorithm
     366             :  *
     367             :  * These parameters are taken from the consensus; some are overrideable in
     368             :  * the torrc.
     369             :  */
     370             : /**@{*/
     371             : /**
     372             :  * We never let our sampled guard set grow larger than this fraction
     373             :  * of the guards on the network.
     374             :  */
     375             : STATIC double
     376         155 : get_max_sample_threshold(void)
     377             : {
     378         155 :   int32_t pct =
     379         155 :     networkstatus_get_param(NULL, "guard-max-sample-threshold-percent",
     380             :                             DFLT_MAX_SAMPLE_THRESHOLD_PERCENT,
     381             :                             1, 100);
     382         155 :   return pct / 100.0;
     383             : }
     384             : /**
     385             :  * We never let our sampled guard set grow larger than this number.
     386             :  */
     387             : STATIC int
     388         193 : get_max_sample_size_absolute(void)
     389             : {
     390         193 :   return (int) networkstatus_get_param(NULL, "guard-max-sample-size",
     391             :                                        DFLT_MAX_SAMPLE_SIZE,
     392             :                                        1, INT32_MAX);
     393             : }
     394             : /**
     395             :  * We always try to make our sample contain at least this many guards.
     396             :  */
     397             : STATIC int
     398         604 : get_min_filtered_sample_size(void)
     399             : {
     400         604 :   return networkstatus_get_param(NULL, "guard-min-filtered-sample-size",
     401             :                                  DFLT_MIN_FILTERED_SAMPLE_SIZE,
     402             :                                  1, INT32_MAX);
     403             : }
     404             : /**
     405             :  * If a guard is unlisted for this many days in a row, we remove it.
     406             :  */
     407             : STATIC int
     408          39 : get_remove_unlisted_guards_after_days(void)
     409             : {
     410          39 :   return networkstatus_get_param(NULL,
     411             :                                  "guard-remove-unlisted-guards-after-days",
     412             :                                  DFLT_REMOVE_UNLISTED_GUARDS_AFTER_DAYS,
     413             :                                  1, 365*10);
     414             : }
     415             : 
     416             : /**
     417             :  * Return number of seconds that will make a guard no longer eligible
     418             :  * for selection if unlisted for this long.
     419             :  */
     420             : static time_t
     421          36 : get_remove_unlisted_guards_after_seconds(void)
     422             : {
     423          36 :   return get_remove_unlisted_guards_after_days() * 24 * 60 * 60;
     424             : }
     425             : 
     426             : /**
     427             :  * We remove unconfirmed guards from the sample after this many days,
     428             :  * regardless of whether they are listed or unlisted.
     429             :  */
     430             : STATIC int
     431        2114 : get_guard_lifetime(void)
     432             : {
     433        2114 :   if (get_options()->GuardLifetime >= 86400)
     434           0 :     return get_options()->GuardLifetime;
     435        2114 :   int32_t days;
     436        2114 :   days = networkstatus_get_param(NULL,
     437             :                                  "guard-lifetime-days",
     438             :                                  DFLT_GUARD_LIFETIME_DAYS, 1, 365*10);
     439        2114 :   return days * 86400;
     440             : }
     441             : /**
     442             :  * We remove confirmed guards from the sample if they were sampled
     443             :  * GUARD_LIFETIME_DAYS ago and confirmed this many days ago.
     444             :  */
     445             : STATIC int
     446          21 : get_guard_confirmed_min_lifetime(void)
     447             : {
     448          21 :   if (get_options()->GuardLifetime >= 86400)
     449           0 :     return get_options()->GuardLifetime;
     450          21 :   int32_t days;
     451          21 :   days = networkstatus_get_param(NULL, "guard-confirmed-min-lifetime-days",
     452             :                                  DFLT_GUARD_CONFIRMED_MIN_LIFETIME_DAYS,
     453             :                                  1, 365*10);
     454          21 :   return days * 86400;
     455             : }
     456             : /**
     457             :  * How many guards do we try to keep on our primary guard list?
     458             :  */
     459             : STATIC int
     460         291 : get_n_primary_guards(void)
     461             : {
     462             :   /* If the user has explicitly configured the number of primary guards, do
     463             :    * what the user wishes to do */
     464         291 :   const int configured_primaries = get_options()->NumPrimaryGuards;
     465         291 :   if (configured_primaries) {
     466             :     return configured_primaries;
     467             :   }
     468             : 
     469             :   /* otherwise check for consensus parameter and if that's not set either, just
     470             :    * use the default value. */
     471         290 :   return networkstatus_get_param(NULL,
     472             :                                  "guard-n-primary-guards",
     473             :                                  DFLT_N_PRIMARY_GUARDS, 1, INT32_MAX);
     474             : }
     475             : /**
     476             :  * Return the number of the live primary guards we should look at when
     477             :  * making a circuit.
     478             :  */
     479             : STATIC int
     480         262 : get_n_primary_guards_to_use(guard_usage_t usage)
     481             : {
     482         262 :   int configured;
     483         262 :   const char *param_name;
     484         262 :   int param_default;
     485             : 
     486             :   /* If the user has explicitly configured the amount of guards, use
     487             :      that. Otherwise, fall back to the default value. */
     488         262 :   if (usage == GUARD_USAGE_DIRGUARD) {
     489           4 :     configured = get_options()->NumDirectoryGuards;
     490           4 :     param_name = "guard-n-primary-dir-guards-to-use";
     491           4 :     param_default = DFLT_N_PRIMARY_DIR_GUARDS_TO_USE;
     492             :   } else {
     493         258 :     configured = get_options()->NumEntryGuards;
     494         258 :     param_name = "guard-n-primary-guards-to-use";
     495         258 :     param_default = DFLT_N_PRIMARY_GUARDS_TO_USE;
     496             :   }
     497         262 :   if (configured >= 1) {
     498             :     return configured;
     499             :   }
     500         262 :   return networkstatus_get_param(NULL,
     501             :                                  param_name, param_default, 1, INT32_MAX);
     502             : }
     503             : /**
     504             :  * If we haven't successfully built or used a circuit in this long, then
     505             :  * consider that the internet is probably down.
     506             :  */
     507             : STATIC int
     508          42 : get_internet_likely_down_interval(void)
     509             : {
     510          42 :   return networkstatus_get_param(NULL, "guard-internet-likely-down-interval",
     511             :                                  DFLT_INTERNET_LIKELY_DOWN_INTERVAL,
     512             :                                  1, INT32_MAX);
     513             : }
     514             : /**
     515             :  * If we're trying to connect to a nonprimary guard for at least this
     516             :  * many seconds, and we haven't gotten the connection to work, we will treat
     517             :  * lower-priority guards as usable.
     518             :  */
     519             : STATIC int
     520          24 : get_nonprimary_guard_connect_timeout(void)
     521             : {
     522          24 :   return networkstatus_get_param(NULL,
     523             :                                  "guard-nonprimary-guard-connect-timeout",
     524             :                                  DFLT_NONPRIMARY_GUARD_CONNECT_TIMEOUT,
     525             :                                  1, INT32_MAX);
     526             : }
     527             : /**
     528             :  * If a circuit has been sitting around in 'waiting for better guard' state
     529             :  * for at least this long, we'll expire it.
     530             :  */
     531             : STATIC int
     532           3 : get_nonprimary_guard_idle_timeout(void)
     533             : {
     534           3 :   return networkstatus_get_param(NULL,
     535             :                                  "guard-nonprimary-guard-idle-timeout",
     536             :                                  DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT,
     537             :                                  1, INT32_MAX);
     538             : }
     539             : /**
     540             :  * If our configuration retains fewer than this fraction of guards from the
     541             :  * torrc, we are in a restricted setting.
     542             :  */
     543             : STATIC double
     544          66 : get_meaningful_restriction_threshold(void)
     545             : {
     546          66 :   int32_t pct = networkstatus_get_param(NULL,
     547             :                                         "guard-meaningful-restriction-percent",
     548             :                                         DFLT_MEANINGFUL_RESTRICTION_PERCENT,
     549             :                                         1, INT32_MAX);
     550          66 :   return pct / 100.0;
     551             : }
     552             : /**
     553             :  * If our configuration retains fewer than this fraction of guards from the
     554             :  * torrc, we are in an extremely restricted setting, and should warn.
     555             :  */
     556             : STATIC double
     557          22 : get_extreme_restriction_threshold(void)
     558             : {
     559          22 :   int32_t pct = networkstatus_get_param(NULL,
     560             :                                         "guard-extreme-restriction-percent",
     561             :                                         DFLT_EXTREME_RESTRICTION_PERCENT,
     562             :                                         1, INT32_MAX);
     563          22 :   return pct / 100.0;
     564             : }
     565             : 
     566             : /* Mark <b>guard</b> as maybe reachable again. */
     567             : static void
     568         156 : mark_guard_maybe_reachable(entry_guard_t *guard)
     569             : {
     570         156 :   if (guard->is_reachable != GUARD_REACHABLE_NO) {
     571             :     return;
     572             :   }
     573             : 
     574             :   /* Note that we do not clear failing_since: this guard is now only
     575             :    * _maybe-reachable_. */
     576          36 :   guard->is_reachable = GUARD_REACHABLE_MAYBE;
     577          36 :   if (guard->is_filtered_guard)
     578          36 :     guard->is_usable_filtered_guard = 1;
     579             : }
     580             : 
     581             : /**
     582             :  * Called when the network comes up after having seemed to be down for
     583             :  * a while: Mark the primary guards as maybe-reachable so that we'll
     584             :  * try them again.
     585             :  */
     586             : STATIC void
     587           9 : mark_primary_guards_maybe_reachable(guard_selection_t *gs)
     588             : {
     589           9 :   tor_assert(gs);
     590             : 
     591           9 :   if (!gs->primary_guards_up_to_date)
     592           0 :     entry_guards_update_primary(gs);
     593             : 
     594          36 :   SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
     595          27 :     mark_guard_maybe_reachable(guard);
     596          27 :   } SMARTLIST_FOREACH_END(guard);
     597           9 : }
     598             : 
     599             : /* Called when we exhaust all guards in our sampled set: Marks all guards as
     600             :    maybe-reachable so that we 'll try them again. */
     601             : static void
     602           6 : mark_all_guards_maybe_reachable(guard_selection_t *gs)
     603             : {
     604           6 :   tor_assert(gs);
     605             : 
     606         135 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
     607         129 :     mark_guard_maybe_reachable(guard);
     608         129 :   } SMARTLIST_FOREACH_END(guard);
     609           6 : }
     610             : 
     611             : /**@}*/
     612             : 
     613             : /**
     614             :  * Given our options and our list of nodes, return the name of the
     615             :  * guard selection that we should use.  Return NULL for "use the
     616             :  * same selection you were using before.
     617             :  */
     618             : STATIC const char *
     619          33 : choose_guard_selection(const or_options_t *options,
     620             :                        const networkstatus_t *live_ns,
     621             :                        const guard_selection_t *old_selection,
     622             :                        guard_selection_type_t *type_out)
     623             : {
     624          33 :   tor_assert(options);
     625          33 :   tor_assert(type_out);
     626             : 
     627          33 :   if (options->UseBridges) {
     628           3 :     *type_out = GS_TYPE_BRIDGE;
     629           3 :     return "bridges";
     630             :   }
     631             : 
     632          30 :   if (! live_ns) {
     633             :     /* without a networkstatus, we can't tell any more than that. */
     634           8 :     *type_out = GS_TYPE_NORMAL;
     635           8 :     return "default";
     636             :   }
     637             : 
     638          22 :   const smartlist_t *nodes = nodelist_get_list();
     639          22 :   int n_guards = 0, n_passing_filter = 0;
     640        5717 :   SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
     641        5695 :     if (node_is_possible_guard(node)) {
     642        2858 :       ++n_guards;
     643        2858 :       if (node_passes_guard_filter(options, node)) {
     644        2449 :         ++n_passing_filter;
     645             :       }
     646             :     }
     647        5695 :   } SMARTLIST_FOREACH_END(node);
     648             : 
     649             :   /* We use separate 'high' and 'low' thresholds here to prevent flapping
     650             :    * back and forth */
     651          44 :   const int meaningful_threshold_high =
     652          22 :     (int)(n_guards * get_meaningful_restriction_threshold() * 1.05);
     653          44 :   const int meaningful_threshold_mid =
     654          22 :     (int)(n_guards * get_meaningful_restriction_threshold());
     655          44 :   const int meaningful_threshold_low =
     656          22 :     (int)(n_guards * get_meaningful_restriction_threshold() * .95);
     657          44 :   const int extreme_threshold =
     658          22 :     (int)(n_guards * get_extreme_restriction_threshold());
     659             : 
     660             :   /*
     661             :     If we have no previous selection, then we're "restricted" iff we are
     662             :     below the meaningful restriction threshold.  That's easy enough.
     663             : 
     664             :     But if we _do_ have a previous selection, we make it a little
     665             :     "sticky": we only move from "restricted" to "default" when we find
     666             :     that we're above the threshold plus 5%, and we only move from
     667             :     "default" to "restricted" when we're below the threshold minus 5%.
     668             :     That should prevent us from flapping back and forth if we happen to
     669             :     be hovering very close to the default.
     670             : 
     671             :     The extreme threshold is for warning only.
     672             :   */
     673             : 
     674          22 :   static int have_warned_extreme_threshold = 0;
     675          22 :   if (n_guards &&
     676          22 :       n_passing_filter < extreme_threshold &&
     677           3 :       ! have_warned_extreme_threshold) {
     678           3 :     have_warned_extreme_threshold = 1;
     679           3 :     const double exclude_frac =
     680           3 :       (n_guards - n_passing_filter) / (double)n_guards;
     681           3 :     log_warn(LD_GUARD, "Your configuration excludes %d%% of all possible "
     682             :              "guards. That's likely to make you stand out from the "
     683             :              "rest of the world.", (int)(exclude_frac * 100));
     684             :   }
     685             : 
     686             :   /* Easy case: no previous selection. Just check if we are in restricted or
     687             :      normal guard selection. */
     688          22 :   if (old_selection == NULL) {
     689          21 :     if (n_passing_filter >= meaningful_threshold_mid) {
     690          18 :       *type_out = GS_TYPE_NORMAL;
     691          18 :       return "default";
     692             :     } else {
     693           3 :       *type_out = GS_TYPE_RESTRICTED;
     694           3 :       return "restricted";
     695             :     }
     696             :   }
     697             : 
     698             :   /* Trickier case: we do have a previous guard selection context. */
     699           1 :   tor_assert(old_selection);
     700             : 
     701             :   /* Use high and low thresholds to decide guard selection, and if we fall in
     702             :      the middle then keep the current guard selection context. */
     703           1 :   if (n_passing_filter >= meaningful_threshold_high) {
     704           1 :     *type_out = GS_TYPE_NORMAL;
     705           1 :     return "default";
     706           0 :   } else if (n_passing_filter < meaningful_threshold_low) {
     707           0 :     *type_out = GS_TYPE_RESTRICTED;
     708           0 :     return "restricted";
     709             :   } else {
     710             :     /* we are in the middle: maintain previous guard selection */
     711           0 :     *type_out = old_selection->type;
     712           0 :     return old_selection->name;
     713             :   }
     714             : }
     715             : 
     716             : /**
     717             :  * Check whether we should switch from our current guard selection to a
     718             :  * different one.  If so, switch and return 1.  Return 0 otherwise.
     719             :  *
     720             :  * On a 1 return, the caller should mark all currently live circuits unusable
     721             :  * for new streams, by calling circuit_mark_all_unused_circs() and
     722             :  * circuit_mark_all_dirty_circs_as_unusable().
     723             :  */
     724             : int
     725           2 : update_guard_selection_choice(const or_options_t *options)
     726             : {
     727           2 :   if (!curr_guard_context) {
     728           1 :     create_initial_guard_context();
     729           1 :     return 1;
     730             :   }
     731             : 
     732           1 :   guard_selection_type_t type = GS_TYPE_INFER;
     733           1 :   const char *new_name = choose_guard_selection(
     734             :                              options,
     735           1 :                              networkstatus_get_reasonably_live_consensus(
     736             :                                                     approx_time(),
     737             :                                                     usable_consensus_flavor()),
     738             :                              curr_guard_context,
     739             :                              &type);
     740           1 :   tor_assert(new_name);
     741           1 :   tor_assert(type != GS_TYPE_INFER);
     742             : 
     743           1 :   const char *cur_name = curr_guard_context->name;
     744           1 :   if (! strcmp(cur_name, new_name)) {
     745           1 :     log_debug(LD_GUARD,
     746             :               "Staying with guard context \"%s\" (no change)", new_name);
     747           1 :     return 0; // No change
     748             :   }
     749             : 
     750           0 :   log_notice(LD_GUARD, "Switching to guard context \"%s\" (was using \"%s\")",
     751             :              new_name, cur_name);
     752           0 :   guard_selection_t *new_guard_context;
     753           0 :   new_guard_context = get_guard_selection_by_name(new_name, type, 1);
     754           0 :   tor_assert(new_guard_context);
     755           0 :   tor_assert(new_guard_context != curr_guard_context);
     756           0 :   curr_guard_context = new_guard_context;
     757             : 
     758           0 :   return 1;
     759             : }
     760             : 
     761             : /**
     762             :  * Return true iff <b>node</b> has all the flags needed for us to consider it
     763             :  * a possible guard when sampling guards.
     764             :  */
     765             : static int
     766       46695 : node_is_possible_guard(const node_t *node)
     767             : {
     768             :   /* The "GUARDS" set is all nodes in the nodelist for which this predicate
     769             :    * holds. */
     770             : 
     771       46695 :   tor_assert(node);
     772       46695 :   return (node->is_possible_guard &&
     773             :           node->is_stable &&
     774       46695 :           node->is_fast &&
     775       23133 :           node->is_valid &&
     776       69828 :           node_is_dir(node) &&
     777       23133 :           !router_digest_is_me(node->identity));
     778             : }
     779             : 
     780             : /**
     781             :  * Return the sampled guard with the RSA identity digest <b>rsa_id</b>, or
     782             :  * NULL if we don't have one. */
     783             : STATIC entry_guard_t *
     784        1895 : get_sampled_guard_with_id(guard_selection_t *gs,
     785             :                           const uint8_t *rsa_id)
     786             : {
     787        1895 :   tor_assert(gs);
     788        1895 :   tor_assert(rsa_id);
     789       21168 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
     790       19285 :     if (tor_memeq(guard->identity, rsa_id, DIGEST_LEN))
     791          12 :       return guard;
     792       19273 :   } SMARTLIST_FOREACH_END(guard);
     793             :   return NULL;
     794             : }
     795             : 
     796             : /** If <b>gs</b> contains a sampled entry guard matching <b>bridge</b>,
     797             :  * return that guard. Otherwise return NULL. */
     798             : static entry_guard_t *
     799           0 : get_sampled_guard_for_bridge(guard_selection_t *gs,
     800             :                              const bridge_info_t *bridge)
     801             : {
     802           0 :   const uint8_t *id = bridge_get_rsa_id_digest(bridge);
     803           0 :   const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
     804           0 :   entry_guard_t *guard;
     805           0 :   if (BUG(!addrport))
     806             :     return NULL; // LCOV_EXCL_LINE
     807           0 :   guard = get_sampled_guard_by_bridge_addr(gs, addrport);
     808           0 :   if (! guard || (id && tor_memneq(id, guard->identity, DIGEST_LEN)))
     809           0 :     return NULL;
     810             :   else
     811           0 :     return guard;
     812             : }
     813             : 
     814             : /** If we know a bridge_info_t matching <b>guard</b>, return that
     815             :  * bridge.  Otherwise return NULL. */
     816             : static bridge_info_t *
     817           4 : get_bridge_info_for_guard(const entry_guard_t *guard)
     818             : {
     819           4 :   const uint8_t *identity = NULL;
     820           4 :   if (! tor_digest_is_zero(guard->identity)) {
     821           4 :     identity = (const uint8_t *)guard->identity;
     822             :   }
     823           4 :   if (BUG(guard->bridge_addr == NULL))
     824           0 :     return NULL;
     825             : 
     826           4 :   return get_configured_bridge_by_exact_addr_port_digest(
     827           4 :                                                  &guard->bridge_addr->addr,
     828           4 :                                                  guard->bridge_addr->port,
     829             :                                                  (const char*)identity);
     830             : }
     831             : 
     832             : /**
     833             :  * Return true iff we have a sampled guard with the RSA identity digest
     834             :  * <b>rsa_id</b>. */
     835             : static inline int
     836        1871 : have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id)
     837             : {
     838        1871 :   return get_sampled_guard_with_id(gs, rsa_id) != NULL;
     839             : }
     840             : 
     841             : /**
     842             :  * Allocate a new entry_guard_t object for <b>node</b>, add it to the
     843             :  * sampled entry guards in <b>gs</b>, and return it. <b>node</b> must
     844             :  * not currently be a sampled guard in <b>gs</b>.
     845             :  */
     846             : STATIC entry_guard_t *
     847        1871 : entry_guard_add_to_sample(guard_selection_t *gs,
     848             :                           const node_t *node)
     849             : {
     850        1871 :   log_info(LD_GUARD, "Adding %s to the entry guard sample set.",
     851             :            node_describe(node));
     852             : 
     853             :   /* make sure that the guard is not already sampled. */
     854        1871 :   if (BUG(have_sampled_guard_with_id(gs, (const uint8_t*)node->identity)))
     855             :     return NULL; // LCOV_EXCL_LINE
     856             : 
     857        1871 :   return entry_guard_add_to_sample_impl(gs,
     858             :                                         (const uint8_t*)node->identity,
     859             :                                         node_get_nickname(node),
     860             :                                         NULL);
     861             : }
     862             : 
     863             : /**
     864             :  * Backend: adds a new sampled guard to <b>gs</b>, with given identity,
     865             :  * nickname, and ORPort.  rsa_id_digest and bridge_addrport are optional, but
     866             :  * we need one of them. nickname is optional. The caller is responsible for
     867             :  * maintaining the size limit of the SAMPLED_GUARDS set.
     868             :  */
     869             : static entry_guard_t *
     870        1871 : entry_guard_add_to_sample_impl(guard_selection_t *gs,
     871             :                                const uint8_t *rsa_id_digest,
     872             :                                const char *nickname,
     873             :                                const tor_addr_port_t *bridge_addrport)
     874             : {
     875        1871 :   const int GUARD_LIFETIME = get_guard_lifetime();
     876        1871 :   tor_assert(gs);
     877             : 
     878             :   // XXXX #20827 take ed25519 identity here too.
     879             : 
     880             :   /* Make sure we can actually identify the guard. */
     881        1871 :   if (BUG(!rsa_id_digest && !bridge_addrport))
     882             :     return NULL; // LCOV_EXCL_LINE
     883             : 
     884        1871 :   entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
     885             : 
     886             :   /* persistent fields */
     887        1871 :   guard->is_persistent = (rsa_id_digest != NULL);
     888        1871 :   guard->selection_name = tor_strdup(gs->name);
     889        1871 :   if (rsa_id_digest)
     890        1871 :     memcpy(guard->identity, rsa_id_digest, DIGEST_LEN);
     891        1871 :   if (nickname)
     892        1871 :     strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
     893        1871 :   guard->sampled_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
     894        1871 :   tor_free(guard->sampled_by_version);
     895        1871 :   guard->sampled_by_version = tor_strdup(VERSION);
     896        1871 :   guard->currently_listed = 1;
     897        1871 :   guard->sampled_idx = gs->next_sampled_idx++;
     898        1871 :   guard->confirmed_idx = -1;
     899             : 
     900             :   /* non-persistent fields */
     901        1871 :   guard->is_reachable = GUARD_REACHABLE_MAYBE;
     902        1871 :   if (bridge_addrport)
     903           0 :     guard->bridge_addr = tor_memdup(bridge_addrport, sizeof(*bridge_addrport));
     904             : 
     905        1871 :   smartlist_add(gs->sampled_entry_guards, guard);
     906        1871 :   guard->in_selection = gs;
     907        1871 :   entry_guard_set_filtered_flags(get_options(), gs, guard);
     908        1871 :   entry_guards_changed_for_guard_selection(gs);
     909             : 
     910             :   /* Just added this guard to the sampled set and hence it might be used as a
     911             :    * guard in the future: send GUARD NEW control event. */
     912        1871 :   control_event_guard(guard->nickname, guard->identity, "NEW");
     913             : 
     914        1871 :   return guard;
     915             : }
     916             : 
     917             : /**
     918             :  * Add an entry guard to the "bridges" guard selection sample, with
     919             :  * information taken from <b>bridge</b>. Return that entry guard.
     920             :  */
     921             : static entry_guard_t *
     922           0 : entry_guard_add_bridge_to_sample(guard_selection_t *gs,
     923             :                                  const bridge_info_t *bridge)
     924             : {
     925           0 :   const uint8_t *id_digest = bridge_get_rsa_id_digest(bridge);
     926           0 :   const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
     927             : 
     928           0 :   tor_assert(addrport);
     929             : 
     930             :   /* make sure that the guard is not already sampled. */
     931           0 :   if (BUG(get_sampled_guard_for_bridge(gs, bridge)))
     932             :     return NULL; // LCOV_EXCL_LINE
     933             : 
     934           0 :   return entry_guard_add_to_sample_impl(gs, id_digest, NULL, addrport);
     935             : }
     936             : 
     937             : /**
     938             :  * Return the entry_guard_t in <b>gs</b> whose address is <b>addrport</b>,
     939             :  * or NULL if none exists.
     940             : */
     941             : static entry_guard_t *
     942           0 : get_sampled_guard_by_bridge_addr(guard_selection_t *gs,
     943             :                                  const tor_addr_port_t *addrport)
     944             : {
     945           0 :   if (! gs)
     946             :     return NULL;
     947           0 :   if (BUG(!addrport))
     948           0 :     return NULL;
     949           0 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
     950           0 :     if (g->bridge_addr && tor_addr_port_eq(addrport, g->bridge_addr))
     951           0 :       return g;
     952           0 :   } SMARTLIST_FOREACH_END(g);
     953             :   return NULL;
     954             : }
     955             : 
     956             : /** Update the guard subsystem's knowledge of the identity of the bridge
     957             :  * at <b>addrport</b>.  Idempotent.
     958             :  */
     959             : void
     960           0 : entry_guard_learned_bridge_identity(const tor_addr_port_t *addrport,
     961             :                                     const uint8_t *rsa_id_digest)
     962             : {
     963           0 :   guard_selection_t *gs = get_guard_selection_by_name("bridges",
     964             :                                                       GS_TYPE_BRIDGE,
     965             :                                                       0);
     966           0 :   if (!gs)
     967             :     return;
     968             : 
     969           0 :   entry_guard_t *g = get_sampled_guard_by_bridge_addr(gs, addrport);
     970           0 :   if (!g)
     971             :     return;
     972             : 
     973           0 :   int make_persistent = 0;
     974             : 
     975           0 :   if (tor_digest_is_zero(g->identity)) {
     976           0 :     memcpy(g->identity, rsa_id_digest, DIGEST_LEN);
     977           0 :     make_persistent = 1;
     978           0 :   } else if (tor_memeq(g->identity, rsa_id_digest, DIGEST_LEN)) {
     979             :     /* Nothing to see here; we learned something we already knew. */
     980           0 :     if (BUG(! g->is_persistent))
     981           0 :       make_persistent = 1;
     982             :   } else {
     983           0 :     char old_id[HEX_DIGEST_LEN+1];
     984           0 :     base16_encode(old_id, sizeof(old_id), g->identity, sizeof(g->identity));
     985           0 :     log_warn(LD_BUG, "We 'learned' an identity %s for a bridge at %s:%d, but "
     986             :              "we already knew a different one (%s). Ignoring the new info as "
     987             :              "possibly bogus.",
     988             :              hex_str((const char *)rsa_id_digest, DIGEST_LEN),
     989             :              fmt_and_decorate_addr(&addrport->addr), addrport->port,
     990             :              old_id);
     991           0 :     return; // redundant, but let's be clear: we're not making this persistent.
     992             :   }
     993             : 
     994           0 :   if (make_persistent) {
     995           0 :     g->is_persistent = 1;
     996           0 :     entry_guards_changed_for_guard_selection(gs);
     997             :   }
     998             : }
     999             : 
    1000             : /**
    1001             :  * Return the number of sampled guards in <b>gs</b> that are "filtered"
    1002             :  * (that is, we're willing to connect to them) and that are "usable"
    1003             :  * (that is, either "reachable" or "maybe reachable").
    1004             :  *
    1005             :  * If a restriction is provided in <b>rst</b>, do not count any guards that
    1006             :  * violate it.
    1007             :  */
    1008             : STATIC int
    1009         514 : num_reachable_filtered_guards(const guard_selection_t *gs,
    1010             :                               const entry_guard_restriction_t *rst)
    1011             : {
    1012         514 :   int n_reachable_filtered_guards = 0;
    1013        7432 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    1014        6918 :     entry_guard_consider_retry(guard);
    1015        6918 :     if (! entry_guard_obeys_restriction(guard, rst))
    1016         138 :       continue;
    1017        6780 :     if (guard->is_usable_filtered_guard)
    1018        6060 :       ++n_reachable_filtered_guards;
    1019        6918 :   } SMARTLIST_FOREACH_END(guard);
    1020         514 :   return n_reachable_filtered_guards;
    1021             : }
    1022             : 
    1023             : /** Return the actual maximum size for the sample in <b>gs</b>,
    1024             :  * given that we know about <b>n_guards</b> total. */
    1025             : static int
    1026         157 : get_max_sample_size(guard_selection_t *gs,
    1027             :                     int n_guards)
    1028             : {
    1029         157 :   const int using_bridges = (gs->type == GS_TYPE_BRIDGE);
    1030         157 :   const int min_sample = get_min_filtered_sample_size();
    1031             : 
    1032             :   /* If we are in bridge mode, expand our sample set as needed without worrying
    1033             :    * about max size. We should respect the user's wishes to use many bridges if
    1034             :    * that's what they have specified in their configuration file. */
    1035         157 :   if (using_bridges)
    1036             :     return INT_MAX;
    1037             : 
    1038         155 :   const int max_sample_by_pct = (int)(n_guards * get_max_sample_threshold());
    1039         155 :   const int max_sample_absolute = get_max_sample_size_absolute();
    1040         155 :   const int max_sample = MIN(max_sample_by_pct, max_sample_absolute);
    1041         155 :   if (max_sample < min_sample)
    1042             :     return min_sample;
    1043             :   else
    1044         147 :     return max_sample;
    1045             : }
    1046             : 
    1047             : /**
    1048             :  * Return a smartlist of the all the guards that are not currently
    1049             :  * members of the sample (GUARDS - SAMPLED_GUARDS).  The elements of
    1050             :  * this list are node_t pointers in the non-bridge case, and
    1051             :  * bridge_info_t pointers in the bridge case.  Set *<b>n_guards_out</b>
    1052             :  * to the number of guards that we found in GUARDS, including those
    1053             :  * that were already sampled.
    1054             :  */
    1055             : static smartlist_t *
    1056         157 : get_eligible_guards(const or_options_t *options,
    1057             :                     guard_selection_t *gs,
    1058             :                     int *n_guards_out)
    1059             : {
    1060             :   /* Construct eligible_guards as GUARDS - SAMPLED_GUARDS */
    1061         157 :   smartlist_t *eligible_guards = smartlist_new();
    1062         157 :   int n_guards = 0; // total size of "GUARDS"
    1063             : 
    1064         157 :   if (gs->type == GS_TYPE_BRIDGE) {
    1065           2 :     const smartlist_t *bridges = bridge_list_get();
    1066           2 :     SMARTLIST_FOREACH_BEGIN(bridges, bridge_info_t *, bridge) {
    1067           0 :       ++n_guards;
    1068           0 :       if (NULL != get_sampled_guard_for_bridge(gs, bridge)) {
    1069           0 :         continue;
    1070             :       }
    1071           0 :       smartlist_add(eligible_guards, bridge);
    1072           0 :     } SMARTLIST_FOREACH_END(bridge);
    1073             :   } else {
    1074         155 :     const smartlist_t *nodes = nodelist_get_list();
    1075         155 :     const int n_sampled = smartlist_len(gs->sampled_entry_guards);
    1076             : 
    1077             :     /* Build a bloom filter of our current guards: let's keep this O(N). */
    1078         155 :     digestset_t *sampled_guard_ids = digestset_new(n_sampled);
    1079        1444 :     SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, const entry_guard_t *,
    1080             :                             guard) {
    1081        1289 :       digestset_add(sampled_guard_ids, guard->identity);
    1082        1289 :     } SMARTLIST_FOREACH_END(guard);
    1083             : 
    1084       40858 :     SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
    1085       40703 :       if (! node_is_possible_guard(node))
    1086       20683 :         continue;
    1087       20020 :       if (gs->type == GS_TYPE_RESTRICTED) {
    1088             :         /* In restricted mode, we apply the filter BEFORE sampling, so
    1089             :          * that we are sampling from the nodes that we might actually
    1090             :          * select. If we sampled first, we might wind up with a sample
    1091             :          * that didn't include any EntryNodes at all. */
    1092           0 :         if (! node_passes_guard_filter(options, node))
    1093           0 :           continue;
    1094             :       }
    1095       20020 :       ++n_guards;
    1096       20020 :       if (digestset_probably_contains(sampled_guard_ids, node->identity))
    1097        1296 :         continue;
    1098       18724 :       smartlist_add(eligible_guards, (node_t*)node);
    1099       40703 :     } SMARTLIST_FOREACH_END(node);
    1100             : 
    1101             :     /* Now we can free that bloom filter. */
    1102         155 :     digestset_free(sampled_guard_ids);
    1103             :   }
    1104             : 
    1105         157 :   *n_guards_out = n_guards;
    1106         157 :   return eligible_guards;
    1107             : }
    1108             : 
    1109             : /** Helper: given a smartlist of either bridge_info_t (if gs->type is
    1110             :  * GS_TYPE_BRIDGE) or node_t (otherwise), pick one that can be a guard,
    1111             :  * add it as a guard, remove it from the list, and return a new
    1112             :  * entry_guard_t.  Return NULL on failure. */
    1113             : static entry_guard_t *
    1114        1847 : select_and_add_guard_item_for_sample(guard_selection_t *gs,
    1115             :                                      smartlist_t *eligible_guards)
    1116             : {
    1117        1847 :   entry_guard_t *added_guard;
    1118        1847 :   if (gs->type == GS_TYPE_BRIDGE) {
    1119           0 :     const bridge_info_t *bridge = smartlist_choose(eligible_guards);
    1120           0 :     if (BUG(!bridge))
    1121             :       return NULL; // LCOV_EXCL_LINE
    1122           0 :     smartlist_remove(eligible_guards, bridge);
    1123           0 :     added_guard = entry_guard_add_bridge_to_sample(gs, bridge);
    1124             :   } else {
    1125        1847 :     const node_t *node =
    1126        1847 :       node_sl_choose_by_bandwidth(eligible_guards, WEIGHT_FOR_GUARD);
    1127        1847 :     if (BUG(!node))
    1128             :       return NULL; // LCOV_EXCL_LINE
    1129        1847 :     smartlist_remove(eligible_guards, node);
    1130        1847 :     added_guard = entry_guard_add_to_sample(gs, node);
    1131             :   }
    1132             : 
    1133             :   return added_guard;
    1134             : }
    1135             : 
    1136             : /**
    1137             :  * Return true iff we need a consensus to update our guards, but we don't
    1138             :  * have one. (We can return 0 here either if the consensus is _not_ missing,
    1139             :  * or if we don't need a consensus because we're using bridges.)
    1140             :  */
    1141             : static int
    1142         191 : reasonably_live_consensus_is_missing(const guard_selection_t *gs)
    1143             : {
    1144         191 :   tor_assert(gs);
    1145         191 :   if (gs->type == GS_TYPE_BRIDGE) {
    1146             :     /* We don't update bridges from the consensus; they aren't there. */
    1147             :     return 0;
    1148             :   }
    1149         187 :   return networkstatus_get_reasonably_live_consensus(
    1150             :                                             approx_time(),
    1151         187 :                                             usable_consensus_flavor()) == NULL;
    1152             : }
    1153             : 
    1154             : /**
    1155             :  * Add new guards to the sampled guards in <b>gs</b> until there are
    1156             :  * enough usable filtered guards, but never grow the sample beyond its
    1157             :  * maximum size.  Return the last guard added, or NULL if none were
    1158             :  * added.
    1159             :  */
    1160             : STATIC entry_guard_t *
    1161         164 : entry_guards_expand_sample(guard_selection_t *gs)
    1162             : {
    1163         164 :   tor_assert(gs);
    1164         164 :   const or_options_t *options = get_options();
    1165             : 
    1166         164 :   if (reasonably_live_consensus_is_missing(gs)) {
    1167           7 :     log_info(LD_GUARD, "Not expanding the sample guard set; we have "
    1168             :              "no reasonably live consensus.");
    1169           7 :     return NULL;
    1170             :   }
    1171             : 
    1172         157 :   int n_sampled = smartlist_len(gs->sampled_entry_guards);
    1173         157 :   entry_guard_t *added_guard = NULL;
    1174         157 :   int n_usable_filtered_guards = num_reachable_filtered_guards(gs, NULL);
    1175         157 :   int n_guards = 0;
    1176         157 :   smartlist_t *eligible_guards = get_eligible_guards(options, gs, &n_guards);
    1177             : 
    1178         157 :   const int max_sample = get_max_sample_size(gs, n_guards);
    1179         157 :   const int min_filtered_sample = get_min_filtered_sample_size();
    1180             : 
    1181         157 :   log_info(LD_GUARD, "Expanding the sample guard set. We have %d guards "
    1182             :            "in the sample, and %d eligible guards to extend it with.",
    1183             :            n_sampled, smartlist_len(eligible_guards));
    1184             : 
    1185        2004 :   while (n_usable_filtered_guards < min_filtered_sample) {
    1186             :     /* Has our sample grown too large to expand? */
    1187        1860 :     if (n_sampled >= max_sample) {
    1188           3 :       log_info(LD_GUARD, "Not expanding the guard sample any further; "
    1189             :                "just hit the maximum sample threshold of %d",
    1190             :                max_sample);
    1191           3 :       goto done;
    1192             :     }
    1193             : 
    1194             :     /* Did we run out of guards? */
    1195        1857 :     if (smartlist_len(eligible_guards) == 0) {
    1196             :       /* LCOV_EXCL_START
    1197             :          As long as MAX_SAMPLE_THRESHOLD makes can't be adjusted to
    1198             :          allow all guards to be sampled, this can't be reached.
    1199             :        */
    1200             :       log_info(LD_GUARD, "Not expanding the guard sample any further; "
    1201             :                "just ran out of eligible guards");
    1202             :       goto done;
    1203             :       /* LCOV_EXCL_STOP */
    1204             :     }
    1205             : 
    1206             :     /* Otherwise we can add at least one new guard. */
    1207        1847 :     added_guard = select_and_add_guard_item_for_sample(gs, eligible_guards);
    1208        1847 :     if (!added_guard)
    1209             :       goto done; // LCOV_EXCL_LINE -- only fails on BUG.
    1210             : 
    1211        1847 :     ++n_sampled;
    1212             : 
    1213        1847 :     if (added_guard->is_usable_filtered_guard)
    1214        1810 :       ++n_usable_filtered_guards;
    1215             :   }
    1216             : 
    1217         144 :  done:
    1218         157 :   smartlist_free(eligible_guards);
    1219         157 :   return added_guard;
    1220             : }
    1221             : 
    1222             : /**
    1223             :  * Helper: <b>guard</b> has just been removed from the sampled guards:
    1224             :  * also remove it from primary and confirmed. */
    1225             : static void
    1226           9 : remove_guard_from_confirmed_and_primary_lists(guard_selection_t *gs,
    1227             :                                               entry_guard_t *guard)
    1228             : {
    1229           9 :   if (guard->is_primary) {
    1230           3 :     guard->is_primary = 0;
    1231           3 :     smartlist_remove_keeporder(gs->primary_entry_guards, guard);
    1232             :   } else {
    1233           6 :     if (BUG(smartlist_contains(gs->primary_entry_guards, guard))) {
    1234           0 :       smartlist_remove_keeporder(gs->primary_entry_guards, guard);
    1235             :     }
    1236             :   }
    1237             : 
    1238           9 :   if (guard->confirmed_idx >= 0) {
    1239           3 :     smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
    1240           3 :     guard->confirmed_idx = -1;
    1241           3 :     guard->confirmed_on_date = 0;
    1242             :   } else {
    1243           6 :     if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard))) {
    1244             :       // LCOV_EXCL_START
    1245             :       smartlist_remove_keeporder(gs->confirmed_entry_guards, guard);
    1246             :       // LCOV_EXCL_STOP
    1247             :     }
    1248             :   }
    1249           9 : }
    1250             : 
    1251             : /** Return true iff <b>guard</b> is currently "listed" -- that is, it
    1252             :  * appears in the consensus, or as a configured bridge (as
    1253             :  * appropriate) */
    1254         300 : MOCK_IMPL(STATIC int,
    1255             : entry_guard_is_listed,(guard_selection_t *gs, const entry_guard_t *guard))
    1256             : {
    1257         300 :   if (gs->type == GS_TYPE_BRIDGE) {
    1258           0 :     return NULL != get_bridge_info_for_guard(guard);
    1259             :   } else {
    1260         300 :     const node_t *node = node_get_by_id(guard->identity);
    1261             : 
    1262         300 :     return node && node_is_possible_guard(node);
    1263             :   }
    1264             : }
    1265             : 
    1266             : /**
    1267             :  * Enumerate <b>sampled_entry_guards</b> smartlist in <b>gs</b>.
    1268             :  * For each <b>entry_guard_t</b> object in smartlist, do the following:
    1269             :  *  * Update <b>currently_listed</b> field to reflect if guard is listed
    1270             :  *    in guard selection <b>gs</b>.
    1271             :  *  * Set <b>unlisted_since_date</b> to approximate UNIX time of
    1272             :  *    unlisting if guard is unlisted (randomize within 20% of
    1273             :  *    get_remove_unlisted_guards_after_seconds()). Otherwise,
    1274             :  *    set it to 0.
    1275             :  *
    1276             :  * Require <b>gs</b> to be non-null pointer.
    1277             :  * Return a number of entries updated.
    1278             :  */
    1279             : static size_t
    1280          18 : sampled_guards_update_consensus_presence(guard_selection_t *gs)
    1281             : {
    1282          18 :   size_t n_changes = 0;
    1283             : 
    1284          18 :   tor_assert(gs);
    1285             : 
    1286          36 :   const time_t unlisted_since_slop =
    1287          18 :     get_remove_unlisted_guards_after_seconds() /  5;
    1288             : 
    1289         322 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    1290             :     /* XXXX #20827 check ed ID too */
    1291         304 :     const int is_listed = entry_guard_is_listed(gs, guard);
    1292             : 
    1293         304 :     if (is_listed && ! guard->currently_listed) {
    1294           3 :       ++n_changes;
    1295           3 :       guard->currently_listed = 1;
    1296           3 :       guard->unlisted_since_date = 0;
    1297           3 :       log_info(LD_GUARD, "Sampled guard %s is now listed again.",
    1298             :                entry_guard_describe(guard));
    1299         301 :     } else if (!is_listed && guard->currently_listed) {
    1300          18 :       ++n_changes;
    1301          18 :       guard->currently_listed = 0;
    1302          18 :       guard->unlisted_since_date = randomize_time(approx_time(),
    1303             :                                                   unlisted_since_slop);
    1304          18 :       log_info(LD_GUARD, "Sampled guard %s is now unlisted.",
    1305             :                entry_guard_describe(guard));
    1306         283 :     } else if (is_listed && guard->currently_listed) {
    1307         256 :       log_debug(LD_GUARD, "Sampled guard %s is still listed.",
    1308             :                entry_guard_describe(guard));
    1309             :     } else {
    1310          27 :       tor_assert(! is_listed && ! guard->currently_listed);
    1311          27 :       log_debug(LD_GUARD, "Sampled guard %s is still unlisted.",
    1312             :                 entry_guard_describe(guard));
    1313             :     }
    1314             : 
    1315             :     /* Clean up unlisted_since_date, just in case. */
    1316         304 :     if (guard->currently_listed && guard->unlisted_since_date) {
    1317           9 :       ++n_changes;
    1318           9 :       guard->unlisted_since_date = 0;
    1319           9 :       log_warn(LD_BUG, "Sampled guard %s was listed, but with "
    1320             :                "unlisted_since_date set. Fixing.",
    1321             :                entry_guard_describe(guard));
    1322         295 :     } else if (!guard->currently_listed && ! guard->unlisted_since_date) {
    1323           9 :       ++n_changes;
    1324           9 :       guard->unlisted_since_date = randomize_time(approx_time(),
    1325             :                                                   unlisted_since_slop);
    1326           9 :       log_warn(LD_BUG, "Sampled guard %s was unlisted, but with "
    1327             :                "unlisted_since_date unset. Fixing.",
    1328             :                entry_guard_describe(guard));
    1329             :     }
    1330         304 :   } SMARTLIST_FOREACH_END(guard);
    1331             : 
    1332          18 :   return n_changes;
    1333             : }
    1334             : 
    1335             : /**
    1336             :  * Enumerate <b>sampled_entry_guards</b> smartlist in <b>gs</b>.
    1337             :  * For each <b>entry_guard_t</b> object in smartlist, do the following:
    1338             :  * * If <b>currently_listed</b> is false and <b>unlisted_since_date</b>
    1339             :  *   is earlier than <b>remove_if_unlisted_since</b> - remove it.
    1340             :  * * Otherwise, check if <b>sampled_on_date</b> is earlier than
    1341             :  *   <b>maybe_remove_if_sampled_before</b>.
    1342             :  *   * When above condition is correct, remove the guard if:
    1343             :  *     * It was never confirmed.
    1344             :  *     * It was confirmed before <b>remove_if_confirmed_before</b>.
    1345             :  *
    1346             :  * Require <b>gs</b> to be non-null pointer.
    1347             :  * Return number of entries deleted.
    1348             :  */
    1349             : static size_t
    1350          18 : sampled_guards_prune_obsolete_entries(guard_selection_t *gs,
    1351             :                                   const time_t remove_if_unlisted_since,
    1352             :                                   const time_t maybe_remove_if_sampled_before,
    1353             :                                   const time_t remove_if_confirmed_before)
    1354             : {
    1355          18 :   size_t n_changes = 0;
    1356             : 
    1357          18 :   tor_assert(gs);
    1358             : 
    1359         322 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    1360         304 :     int rmv = 0;
    1361             : 
    1362         304 :     if (guard->currently_listed == 0 &&
    1363          45 :         guard->unlisted_since_date < remove_if_unlisted_since) {
    1364             :       /*
    1365             :         "We have a live consensus, and {IS_LISTED} is false, and
    1366             :          {FIRST_UNLISTED_AT} is over get_remove_unlisted_guards_after_days()
    1367             :          days in the past."
    1368             :       */
    1369           3 :       log_info(LD_GUARD, "Removing sampled guard %s: it has been unlisted "
    1370             :                "for over %d days", entry_guard_describe(guard),
    1371             :                get_remove_unlisted_guards_after_days());
    1372           3 :       rmv = 1;
    1373         301 :     } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {
    1374             :       /* We have a live consensus, and {ADDED_ON_DATE} is over
    1375             :         {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either
    1376             :         "never", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.
    1377             :       */
    1378           9 :       if (guard->confirmed_on_date == 0) {
    1379           3 :         rmv = 1;
    1380           3 :         log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
    1381             :                  "over %d days ago, but never confirmed.",
    1382             :                  entry_guard_describe(guard),
    1383             :                  get_guard_lifetime() / 86400);
    1384           6 :       } else if (guard->confirmed_on_date < remove_if_confirmed_before) {
    1385           3 :         rmv = 1;
    1386           3 :         log_info(LD_GUARD, "Removing sampled guard %s: it was sampled "
    1387             :                  "over %d days ago, and confirmed over %d days ago.",
    1388             :                  entry_guard_describe(guard),
    1389             :                  get_guard_lifetime() / 86400,
    1390             :                  get_guard_confirmed_min_lifetime() / 86400);
    1391             :       }
    1392             :     }
    1393             : 
    1394           9 :     if (rmv) {
    1395           9 :       ++n_changes;
    1396           9 :       SMARTLIST_DEL_CURRENT_KEEPORDER(gs->sampled_entry_guards, guard);
    1397           9 :       remove_guard_from_confirmed_and_primary_lists(gs, guard);
    1398           9 :       entry_guard_free(guard);
    1399             :     }
    1400         304 :   } SMARTLIST_FOREACH_END(guard);
    1401             : 
    1402          18 :   return n_changes;
    1403             : }
    1404             : 
    1405             : /**
    1406             :  * Update the status of all sampled guards based on the arrival of a
    1407             :  * new consensus networkstatus document.  This will include marking
    1408             :  * some guards as listed or unlisted, and removing expired guards. */
    1409             : STATIC void
    1410          27 : sampled_guards_update_from_consensus(guard_selection_t *gs)
    1411             : {
    1412          27 :   tor_assert(gs);
    1413             : 
    1414             :   // It's important to use a reasonably live consensus here; we want clients
    1415             :   // to bootstrap even if their clock is skewed by more than 2-3 hours.
    1416             :   // But we don't want to make changes based on anything that's really old.
    1417          27 :   if (reasonably_live_consensus_is_missing(gs)) {
    1418           9 :     log_info(LD_GUARD, "Not updating the sample guard set; we have "
    1419             :              "no reasonably live consensus.");
    1420           9 :     return;
    1421             :   }
    1422          18 :   log_info(LD_GUARD, "Updating sampled guard status based on received "
    1423             :            "consensus.");
    1424             : 
    1425             :   /* First: Update listed/unlisted. */
    1426          18 :   size_t n_changes = sampled_guards_update_consensus_presence(gs);
    1427             : 
    1428          36 :   const time_t remove_if_unlisted_since =
    1429          18 :     approx_time() - get_remove_unlisted_guards_after_seconds();
    1430          36 :   const time_t maybe_remove_if_sampled_before =
    1431          18 :     approx_time() - get_guard_lifetime();
    1432          36 :   const time_t remove_if_confirmed_before =
    1433          18 :     approx_time() - get_guard_confirmed_min_lifetime();
    1434             : 
    1435             :   /* Then: remove the ones that have been junk for too long */
    1436          36 :   n_changes +=
    1437          18 :     sampled_guards_prune_obsolete_entries(gs,
    1438             :                                           remove_if_unlisted_since,
    1439             :                                           maybe_remove_if_sampled_before,
    1440             :                                           remove_if_confirmed_before);
    1441             : 
    1442          18 :   if (n_changes) {
    1443          12 :     gs->primary_guards_up_to_date = 0;
    1444          12 :     entry_guards_update_filtered_sets(gs);
    1445             :     /* We don't need to rebuild the confirmed list right here -- we may have
    1446             :      * removed confirmed guards above, but we can't have added any new
    1447             :      * confirmed guards.
    1448             :      */
    1449          12 :     entry_guards_changed_for_guard_selection(gs);
    1450             :   }
    1451             : }
    1452             : 
    1453             : /**
    1454             :  * Return true iff <b>node</b> is a Tor relay that we are configured to
    1455             :  * be able to connect to. */
    1456             : static int
    1457        5080 : node_passes_guard_filter(const or_options_t *options,
    1458             :                          const node_t *node)
    1459             : {
    1460             :   /* NOTE: Make sure that this function stays in sync with
    1461             :    * options_transition_affects_entry_guards */
    1462        5080 :   if (routerset_contains_node(options->ExcludeNodes, node))
    1463             :     return 0;
    1464             : 
    1465        5410 :   if (options->EntryNodes &&
    1466         412 :       !routerset_contains_node(options->EntryNodes, node))
    1467             :     return 0;
    1468             : 
    1469        4588 :   if (!reachable_addr_allows_node(node, FIREWALL_OR_CONNECTION, 0))
    1470             :     return 0;
    1471             : 
    1472        4561 :   if (node_is_a_configured_bridge(node))
    1473           3 :     return 0;
    1474             : 
    1475             :   return 1;
    1476             : }
    1477             : 
    1478             : /** Helper: Return true iff <b>bridge</b> passes our configuration
    1479             :  * filter-- if it is a relay that we are configured to be able to
    1480             :  * connect to. */
    1481             : static int
    1482           0 : bridge_passes_guard_filter(const or_options_t *options,
    1483             :                            const bridge_info_t *bridge)
    1484             : {
    1485           0 :   tor_assert(bridge);
    1486           0 :   if (!bridge)
    1487             :     return 0;
    1488             : 
    1489           0 :   if (routerset_contains_bridge(options->ExcludeNodes, bridge))
    1490             :     return 0;
    1491             : 
    1492             :   /* Ignore entrynodes */
    1493           0 :   const tor_addr_port_t *addrport = bridge_get_addr_port(bridge);
    1494             : 
    1495           0 :   if (!reachable_addr_allows_addr(&addrport->addr,
    1496           0 :                                             addrport->port,
    1497             :                                             FIREWALL_OR_CONNECTION,
    1498             :                                             0, 0))
    1499           0 :     return 0;
    1500             : 
    1501             :   return 1;
    1502             : }
    1503             : 
    1504             : /**
    1505             :  * Return true iff <b>guard</b> is a Tor relay that we are configured to
    1506             :  * be able to connect to, and we haven't disabled it for omission from
    1507             :  * the consensus or path bias issues. */
    1508             : static int
    1509        2311 : entry_guard_passes_filter(const or_options_t *options, guard_selection_t *gs,
    1510             :                           entry_guard_t *guard)
    1511             : {
    1512        2311 :   if (guard->currently_listed == 0)
    1513             :     return 0;
    1514        2263 :   if (guard->pb.path_bias_disabled)
    1515             :     return 0;
    1516             : 
    1517        2254 :   if (gs->type == GS_TYPE_BRIDGE) {
    1518           4 :     const bridge_info_t *bridge = get_bridge_info_for_guard(guard);
    1519           4 :     if (bridge == NULL)
    1520             :       return 0;
    1521           0 :     return bridge_passes_guard_filter(options, bridge);
    1522             :   } else {
    1523        2250 :     const node_t *node = node_get_by_id(guard->identity);
    1524        2250 :     if (node == NULL) {
    1525             :       // This can happen when currently_listed is true, and we're not updating
    1526             :       // it because we don't have a live consensus.
    1527             :       return 0;
    1528             :     }
    1529             : 
    1530        2222 :     return node_passes_guard_filter(options, node);
    1531             :   }
    1532             : }
    1533             : 
    1534             : /** Return true iff <b>guard</b> is in the same family as <b>node</b>.
    1535             :  */
    1536             : static int
    1537         327 : guard_in_node_family(const entry_guard_t *guard, const node_t *node)
    1538             : {
    1539         327 :   const node_t *guard_node = node_get_by_id(guard->identity);
    1540         327 :   if (guard_node) {
    1541         327 :     return nodes_in_same_family(guard_node, node);
    1542             :   } else {
    1543             :     /* If we don't have a node_t for the guard node, we might have
    1544             :      * a bridge_info_t for it. So let's check to see whether the bridge
    1545             :      * address matches has any family issues.
    1546             :      *
    1547             :      * (Strictly speaking, I believe this check is unnecessary, since we only
    1548             :      * use it to avoid the exit's family when building circuits, and we don't
    1549             :      * build multihop circuits until we have a routerinfo_t for the
    1550             :      * bridge... at which point, we'll also have a node_t for the
    1551             :      * bridge. Nonetheless, it seems wise to include it, in case our
    1552             :      * assumptions change down the road.  -nickm.)
    1553             :      */
    1554           0 :     if (get_options()->EnforceDistinctSubnets && guard->bridge_addr) {
    1555           0 :       tor_addr_t node_addr;
    1556           0 :       node_get_addr(node, &node_addr);
    1557           0 :       if (router_addrs_in_same_network(&node_addr,
    1558           0 :                                        &guard->bridge_addr->addr)) {
    1559           0 :         return 1;
    1560             :       }
    1561             :     }
    1562           0 :     return 0;
    1563             :   }
    1564             : }
    1565             : 
    1566             : /* Allocate and return a new exit guard restriction (where <b>exit_id</b> is of
    1567             :  * size DIGEST_LEN) */
    1568             : STATIC entry_guard_restriction_t *
    1569          15 : guard_create_exit_restriction(const uint8_t *exit_id)
    1570             : {
    1571          15 :   entry_guard_restriction_t *rst = NULL;
    1572          15 :   rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
    1573          15 :   rst->type = RST_EXIT_NODE;
    1574          15 :   memcpy(rst->exclude_id, exit_id, DIGEST_LEN);
    1575          15 :   return rst;
    1576             : }
    1577             : 
    1578             : /** If we have fewer than this many possible usable guards, don't set
    1579             :  * MD-availability-based restrictions: we might denylist all of them. */
    1580             : #define MIN_GUARDS_FOR_MD_RESTRICTION 10
    1581             : 
    1582             : /** Return true if we should set md dirserver restrictions. We might not want
    1583             :  *  to set those if our guard options are too restricted, since we don't want
    1584             :  *  to denylist all of them. */
    1585             : static int
    1586           4 : should_set_md_dirserver_restriction(void)
    1587             : {
    1588           4 :   const guard_selection_t *gs = get_guard_selection_info();
    1589           4 :   int num_usable_guards = num_reachable_filtered_guards(gs, NULL);
    1590             : 
    1591             :   /* Don't set restriction if too few reachable filtered guards. */
    1592           4 :   if (num_usable_guards < MIN_GUARDS_FOR_MD_RESTRICTION) {
    1593           1 :     log_info(LD_GUARD, "Not setting md restriction: only %d"
    1594             :              " usable guards.", num_usable_guards);
    1595           1 :     return 0;
    1596             :   }
    1597             : 
    1598             :   /* We have enough usable guards: set MD restriction */
    1599             :   return 1;
    1600             : }
    1601             : 
    1602             : /** Allocate and return an outdated md guard restriction. Return NULL if no
    1603             :  *  such restriction is needed. */
    1604             : STATIC entry_guard_restriction_t *
    1605           4 : guard_create_dirserver_md_restriction(void)
    1606             : {
    1607           4 :   entry_guard_restriction_t *rst = NULL;
    1608             : 
    1609           4 :   if (!should_set_md_dirserver_restriction()) {
    1610           1 :     log_debug(LD_GUARD, "Not setting md restriction: too few "
    1611             :               "filtered guards.");
    1612           1 :     return NULL;
    1613             :   }
    1614             : 
    1615           3 :   rst = tor_malloc_zero(sizeof(entry_guard_restriction_t));
    1616           3 :   rst->type = RST_OUTDATED_MD_DIRSERVER;
    1617             : 
    1618           3 :   return rst;
    1619             : }
    1620             : 
    1621             : /* Return True if <b>guard</b> obeys the exit restriction <b>rst</b>. */
    1622             : static int
    1623         327 : guard_obeys_exit_restriction(const entry_guard_t *guard,
    1624             :                              const entry_guard_restriction_t *rst)
    1625             : {
    1626         327 :   tor_assert(rst->type == RST_EXIT_NODE);
    1627             : 
    1628             :   // Exclude the exit ID and all of its family.
    1629         327 :   const node_t *node = node_get_by_id((const char*)rst->exclude_id);
    1630         327 :   if (node && guard_in_node_family(guard, node))
    1631             :     return 0;
    1632             : 
    1633          24 :   return tor_memneq(guard->identity, rst->exclude_id, DIGEST_LEN);
    1634             : }
    1635             : 
    1636             : /** Return True if <b>guard</b> should be used as a dirserver for fetching
    1637             :  *  microdescriptors. */
    1638             : static int
    1639         129 : guard_obeys_md_dirserver_restriction(const entry_guard_t *guard)
    1640             : {
    1641             :   /* If this guard is an outdated dirserver, don't use it. */
    1642         129 :   if (microdesc_relay_is_outdated_dirserver(guard->identity)) {
    1643          27 :     log_info(LD_GENERAL, "Skipping %s dirserver: outdated",
    1644             :              hex_str(guard->identity, DIGEST_LEN));
    1645          27 :     return 0;
    1646             :   }
    1647             : 
    1648         102 :   log_debug(LD_GENERAL, "%s dirserver obeys md restrictions",
    1649             :             hex_str(guard->identity, DIGEST_LEN));
    1650             : 
    1651         102 :   return 1;
    1652             : }
    1653             : 
    1654             : /**
    1655             :  * Return true iff <b>guard</b> obeys the restrictions defined in <b>rst</b>.
    1656             :  * (If <b>rst</b> is NULL, there are no restrictions.)
    1657             :  */
    1658             : static int
    1659       13432 : entry_guard_obeys_restriction(const entry_guard_t *guard,
    1660             :                               const entry_guard_restriction_t *rst)
    1661             : {
    1662       13432 :   tor_assert(guard);
    1663       13432 :   if (! rst)
    1664             :     return 1; // No restriction?  No problem.
    1665             : 
    1666         456 :   if (rst->type == RST_EXIT_NODE) {
    1667         327 :     return guard_obeys_exit_restriction(guard, rst);
    1668         129 :   } else if (rst->type == RST_OUTDATED_MD_DIRSERVER) {
    1669         129 :     return guard_obeys_md_dirserver_restriction(guard);
    1670             :   }
    1671             : 
    1672           0 :   tor_assert_nonfatal_unreached();
    1673           0 :   return 0;
    1674             : }
    1675             : 
    1676             : /**
    1677             :  * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
    1678             :  * flags on <b>guard</b>. */
    1679             : void
    1680        2311 : entry_guard_set_filtered_flags(const or_options_t *options,
    1681             :                                guard_selection_t *gs,
    1682             :                                entry_guard_t *guard)
    1683             : {
    1684        2311 :   unsigned was_filtered = guard->is_filtered_guard;
    1685        2311 :   guard->is_filtered_guard = 0;
    1686        2311 :   guard->is_usable_filtered_guard = 0;
    1687             : 
    1688        2311 :   if (entry_guard_passes_filter(options, gs, guard)) {
    1689        2109 :     guard->is_filtered_guard = 1;
    1690             : 
    1691        2109 :     if (guard->is_reachable != GUARD_REACHABLE_NO)
    1692        2106 :       guard->is_usable_filtered_guard = 1;
    1693             : 
    1694        2109 :     entry_guard_consider_retry(guard);
    1695             :   }
    1696        2311 :   log_debug(LD_GUARD, "Updated sampled guard %s: filtered=%d; "
    1697             :             "reachable_filtered=%d.", entry_guard_describe(guard),
    1698             :             guard->is_filtered_guard, guard->is_usable_filtered_guard);
    1699             : 
    1700        2311 :   if (!bool_eq(was_filtered, guard->is_filtered_guard)) {
    1701             :     /* This guard might now be primary or nonprimary. */
    1702        1958 :     gs->primary_guards_up_to_date = 0;
    1703             :   }
    1704        2311 : }
    1705             : 
    1706             : /**
    1707             :  * Update the <b>is_filtered_guard</b> and <b>is_usable_filtered_guard</b>
    1708             :  * flag on every guard in <b>gs</b>. */
    1709             : STATIC void
    1710          36 : entry_guards_update_filtered_sets(guard_selection_t *gs)
    1711             : {
    1712          36 :   const or_options_t *options = get_options();
    1713             : 
    1714         476 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    1715         440 :     entry_guard_set_filtered_flags(options, gs, guard);
    1716         440 :   } SMARTLIST_FOREACH_END(guard);
    1717          36 : }
    1718             : 
    1719             : /**
    1720             :  * Return the first sampled guard from the reachable filtered sample guards
    1721             :  * in <b>gs</b>, subject to the exclusion rules listed in <b>flags</b>.
    1722             :  * Return NULL if no such guard can be found.
    1723             :  *
    1724             :  * Make sure that the sample is big enough, and that all the filter flags
    1725             :  * are set correctly, before calling this function.
    1726             :  *
    1727             :  * If a restriction is provided in <b>rst</b>, do not return any guards that
    1728             :  * violate it.
    1729             :  **/
    1730             : STATIC entry_guard_t *
    1731         290 : first_reachable_filtered_entry_guard(guard_selection_t *gs,
    1732             :                                        const entry_guard_restriction_t *rst,
    1733             :                                        unsigned flags)
    1734             : {
    1735         290 :   tor_assert(gs);
    1736         290 :   entry_guard_t *result = NULL;
    1737         290 :   const unsigned exclude_confirmed = flags & SAMPLE_EXCLUDE_CONFIRMED;
    1738         290 :   const unsigned exclude_primary = flags & SAMPLE_EXCLUDE_PRIMARY;
    1739         290 :   const unsigned exclude_pending = flags & SAMPLE_EXCLUDE_PENDING;
    1740         290 :   const unsigned no_update_primary = flags & SAMPLE_NO_UPDATE_PRIMARY;
    1741         290 :   const unsigned need_descriptor = flags & SAMPLE_EXCLUDE_NO_DESCRIPTOR;
    1742             : 
    1743        4728 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    1744        4438 :     entry_guard_consider_retry(guard);
    1745        4438 :   } SMARTLIST_FOREACH_END(guard);
    1746             : 
    1747         290 :   const int n_reachable_filtered = num_reachable_filtered_guards(gs, rst);
    1748             : 
    1749         290 :   log_info(LD_GUARD, "Trying to sample a reachable guard: We know of %d "
    1750             :            "in the USABLE_FILTERED set.", n_reachable_filtered);
    1751             : 
    1752         290 :   const int min_filtered_sample = get_min_filtered_sample_size();
    1753         290 :   if (n_reachable_filtered < min_filtered_sample) {
    1754         125 :     log_info(LD_GUARD, "  (That isn't enough. Trying to expand the sample.)");
    1755         125 :     entry_guards_expand_sample(gs);
    1756             :   }
    1757             : 
    1758         290 :   if (exclude_primary && !gs->primary_guards_up_to_date && !no_update_primary)
    1759          39 :     entry_guards_update_primary(gs);
    1760             : 
    1761             :   /* Build the set of reachable filtered guards. */
    1762         290 :   smartlist_t *reachable_filtered_sample = smartlist_new();
    1763        6050 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    1764        5760 :     entry_guard_consider_retry(guard);// redundant, but cheap.
    1765        5760 :     if (! entry_guard_obeys_restriction(guard, rst))
    1766         138 :       continue;
    1767        5622 :     if (! guard->is_usable_filtered_guard)
    1768         229 :       continue;
    1769        5393 :     if (exclude_confirmed && guard->confirmed_idx >= 0)
    1770          30 :       continue;
    1771        5363 :     if (exclude_primary && guard->is_primary)
    1772         196 :       continue;
    1773        5167 :     if (exclude_pending && guard->is_pending)
    1774          30 :       continue;
    1775        5137 :     if (need_descriptor && !guard_has_descriptor(guard))
    1776           0 :       continue;
    1777        5137 :     smartlist_add(reachable_filtered_sample, guard);
    1778        5760 :   } SMARTLIST_FOREACH_END(guard);
    1779             : 
    1780         290 :   log_info(LD_GUARD, "  (After filters [%x], we have %d guards to consider.)",
    1781             :            flags, smartlist_len(reachable_filtered_sample));
    1782             : 
    1783         290 :   if (smartlist_len(reachable_filtered_sample)) {
    1784             :     /**
    1785             :      * Get the first guard of the filtered set builds from
    1786             :      * sampled_entry_guards. Proposal 310 suggests this design to overcome
    1787             :      * performance and security issues linked to the previous selection
    1788             :      * method. The guard selected here should be filtered out if this function
    1789             :      * is called again in the same context. I.e., if we filter guards to add
    1790             :      * them into some list X, then the guards from list X will be filtered out
    1791             :      * when this function is called again. Hence it requires setting exclude
    1792             :      * flags in a appropriate way (depending of the context of the caller).
    1793             :      */
    1794         271 :     result = smartlist_get(reachable_filtered_sample, 0);
    1795         271 :     log_info(LD_GUARD, "  (Selected %s.)",
    1796             :              result ? entry_guard_describe(result) : "<null>");
    1797             :   }
    1798         290 :   smartlist_free(reachable_filtered_sample);
    1799             : 
    1800         290 :   return result;
    1801             : }
    1802             : 
    1803             : static int
    1804          17 : compare_guards_by_confirmed_idx(const void **a_, const void **b_)
    1805             : {
    1806          17 :   const entry_guard_t *a = *a_, *b = *b_;
    1807          17 :   if (a->confirmed_idx < b->confirmed_idx)
    1808             :     return -1;
    1809           9 :   else if (a->confirmed_idx > b->confirmed_idx)
    1810             :     return 1;
    1811             :   else
    1812           6 :     return 0;
    1813             : }
    1814             : /**
    1815             :  * Helper: compare two entry_guard_t by their sampled_idx values.
    1816             :  * Used to sort the sampled list
    1817             :  */
    1818             : static int
    1819         731 : compare_guards_by_sampled_idx(const void **a_, const void **b_)
    1820             : {
    1821         731 :   const entry_guard_t *a = *a_, *b = *b_;
    1822         731 :   if (a->sampled_idx < b->sampled_idx)
    1823             :     return -1;
    1824          42 :   else if (a->sampled_idx > b->sampled_idx)
    1825             :     return 1;
    1826             :   else
    1827           0 :     return 0;
    1828             : }
    1829             : 
    1830             : /**
    1831             :  * Find the confirmed guards from among the sampled guards in <b>gs</b>,
    1832             :  * and put them in confirmed_entry_guards in the correct
    1833             :  * order. Recalculate their indices.
    1834             :  */
    1835             : STATIC void
    1836          15 : entry_guards_update_confirmed(guard_selection_t *gs)
    1837             : {
    1838          15 :   smartlist_clear(gs->confirmed_entry_guards);
    1839         152 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    1840         137 :     if (guard->confirmed_idx >= 0)
    1841          24 :       smartlist_add(gs->confirmed_entry_guards, guard);
    1842         137 :   } SMARTLIST_FOREACH_END(guard);
    1843             : 
    1844          15 :   smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_confirmed_idx);
    1845             :   /** Needed to keep a dense array of confirmed_idx */
    1846          15 :   int any_changed = 0;
    1847          39 :   SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
    1848          24 :     if (guard->confirmed_idx != guard_sl_idx) {
    1849          17 :       any_changed = 1;
    1850          17 :       guard->confirmed_idx = guard_sl_idx;
    1851             :     }
    1852          24 :   } SMARTLIST_FOREACH_END(guard);
    1853             : 
    1854          15 :   gs->next_confirmed_idx = smartlist_len(gs->confirmed_entry_guards);
    1855             :   // We need the confirmed list to always be give guards in sampled order
    1856          15 :   smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_sampled_idx);
    1857             : 
    1858          15 :   if (any_changed) {
    1859           8 :     entry_guards_changed_for_guard_selection(gs);
    1860             :   }
    1861          15 : }
    1862             : 
    1863             : /**
    1864             :  * Mark <b>guard</b> as a confirmed guard -- that is, one that we have
    1865             :  * connected to, and intend to use again.
    1866             :  */
    1867             : STATIC void
    1868         219 : make_guard_confirmed(guard_selection_t *gs, entry_guard_t *guard)
    1869             : {
    1870         219 :   if (BUG(guard->confirmed_on_date && guard->confirmed_idx >= 0))
    1871             :     return; // LCOV_EXCL_LINE
    1872             : 
    1873         219 :   if (BUG(smartlist_contains(gs->confirmed_entry_guards, guard)))
    1874             :     return; // LCOV_EXCL_LINE
    1875             : 
    1876         219 :   const int GUARD_LIFETIME = get_guard_lifetime();
    1877         219 :   guard->confirmed_on_date = randomize_time(approx_time(), GUARD_LIFETIME/10);
    1878             : 
    1879         219 :   log_info(LD_GUARD, "Marking %s as a confirmed guard (index %d)",
    1880             :            entry_guard_describe(guard),
    1881             :            gs->next_confirmed_idx);
    1882             : 
    1883         219 :   guard->confirmed_idx = gs->next_confirmed_idx++;
    1884         219 :   smartlist_add(gs->confirmed_entry_guards, guard);
    1885             :   /** The confirmation ordering might not be the sample ording. We need to
    1886             :    * reorder */
    1887         219 :   smartlist_sort(gs->confirmed_entry_guards, compare_guards_by_sampled_idx);
    1888             : 
    1889             :   // This confirmed guard might kick something else out of the primary
    1890             :   // guards.
    1891         219 :   gs->primary_guards_up_to_date = 0;
    1892             : 
    1893         219 :   entry_guards_changed_for_guard_selection(gs);
    1894             : }
    1895             : 
    1896             : /**
    1897             :  * Recalculate the list of primary guards (the ones we'd prefer to use) from
    1898             :  * the filtered sample and the confirmed list.
    1899             :  */
    1900             : STATIC void
    1901         289 : entry_guards_update_primary(guard_selection_t *gs)
    1902             : {
    1903         289 :   tor_assert(gs);
    1904             : 
    1905             :   // prevent recursion. Recursion is potentially very bad here.
    1906         289 :   static int running = 0;
    1907         289 :   tor_assert(!running);
    1908         289 :   running = 1;
    1909             : 
    1910         289 :   const int N_PRIMARY_GUARDS = get_n_primary_guards();
    1911             : 
    1912         289 :   smartlist_t *new_primary_guards = smartlist_new();
    1913         289 :   smartlist_t *old_primary_guards = smartlist_new();
    1914         289 :   smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
    1915             : 
    1916             :   /* Set this flag now, to prevent the calls below from recursing. */
    1917         289 :   gs->primary_guards_up_to_date = 1;
    1918             : 
    1919             :   /* First, can we fill it up with confirmed guards? */
    1920         802 :   SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
    1921         567 :     if (smartlist_len(new_primary_guards) >= N_PRIMARY_GUARDS)
    1922             :       break;
    1923         513 :     if (! guard->is_filtered_guard)
    1924           6 :       continue;
    1925         507 :     guard->is_primary = 1;
    1926         507 :     smartlist_add(new_primary_guards, guard);
    1927         513 :   } SMARTLIST_FOREACH_END(guard);
    1928             : 
    1929         937 :   SMARTLIST_FOREACH_BEGIN(old_primary_guards, entry_guard_t *, guard) {
    1930             :     /* Can we keep any older primary guards? First remove all the ones
    1931             :      * that we already kept. */
    1932         648 :     if (smartlist_contains(new_primary_guards, guard)) {
    1933         498 :       SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
    1934         498 :       continue;
    1935             :     }
    1936             : 
    1937             :     /* Now add any that are still good. */
    1938         150 :     if (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS &&
    1939             :         guard->is_filtered_guard) {
    1940         144 :       guard->is_primary = 1;
    1941         144 :       smartlist_add(new_primary_guards, guard);
    1942         144 :       SMARTLIST_DEL_CURRENT_KEEPORDER(old_primary_guards, guard);
    1943             :     } else {
    1944             :       /* Mark the remaining previous primary guards as non-primary */
    1945           6 :       guard->is_primary = 0;
    1946             :     }
    1947         648 :   } SMARTLIST_FOREACH_END(guard);
    1948             : 
    1949             :   /* Finally, fill out the list with sampled guards. */
    1950         476 :   while (smartlist_len(new_primary_guards) < N_PRIMARY_GUARDS) {
    1951         197 :     entry_guard_t *guard = first_reachable_filtered_entry_guard(gs, NULL,
    1952             :                                             SAMPLE_EXCLUDE_CONFIRMED|
    1953             :                                             SAMPLE_EXCLUDE_PRIMARY|
    1954             :                                             SAMPLE_NO_UPDATE_PRIMARY);
    1955         197 :     if (!guard)
    1956             :       break;
    1957         187 :     guard->is_primary = 1;
    1958         187 :     smartlist_add(new_primary_guards, guard);
    1959             :   }
    1960             : 
    1961             : #if 1
    1962             :   /* Debugging. */
    1963        6158 :   SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, guard, {
    1964             :     tor_assert_nonfatal(
    1965             :                    bool_eq(guard->is_primary,
    1966             :                            smartlist_contains(new_primary_guards, guard)));
    1967             :   });
    1968             : #endif /* 1 */
    1969             : 
    1970         289 :   const int any_change = !smartlist_ptrs_eq(gs->primary_entry_guards,
    1971             :                                             new_primary_guards);
    1972         289 :   if (any_change) {
    1973          73 :     log_info(LD_GUARD, "Primary entry guards have changed. "
    1974             :              "New primary guard list is: ");
    1975          73 :     int n = smartlist_len(new_primary_guards);
    1976         290 :     SMARTLIST_FOREACH_BEGIN(new_primary_guards, entry_guard_t *, g) {
    1977         422 :       log_info(LD_GUARD, "  %d/%d: %s%s%s",
    1978             :                g_sl_idx+1, n, entry_guard_describe(g),
    1979             :                g->confirmed_idx >= 0 ? " (confirmed)" : "",
    1980             :                g->is_filtered_guard ? "" : " (excluded by filter)");
    1981         217 :     } SMARTLIST_FOREACH_END(g);
    1982          73 :     smartlist_sort(new_primary_guards, compare_guards_by_sampled_idx);
    1983             :   }
    1984             : 
    1985         289 :   smartlist_free(old_primary_guards);
    1986         289 :   smartlist_free(gs->primary_entry_guards);
    1987         289 :   gs->primary_entry_guards = new_primary_guards;
    1988         289 :   gs->primary_guards_up_to_date = 1;
    1989         289 :   running = 0;
    1990         289 : }
    1991             : 
    1992             : /**
    1993             :  * Return the number of seconds after the last attempt at which we should
    1994             :  * retry a guard that has been failing since <b>failing_since</b>.
    1995             :  */
    1996             : static int
    1997        1314 : get_retry_schedule(time_t failing_since, time_t now,
    1998             :                    int is_primary)
    1999             : {
    2000        1314 :   const unsigned SIX_HOURS = 6 * 3600;
    2001        1314 :   const unsigned FOUR_DAYS = 4 * 86400;
    2002        1314 :   const unsigned SEVEN_DAYS = 7 * 86400;
    2003             : 
    2004        1314 :   time_t tdiff;
    2005        1314 :   if (now > failing_since) {
    2006         900 :     tdiff = now - failing_since;
    2007             :   } else {
    2008             :     tdiff = 0;
    2009             :   }
    2010             : 
    2011        1314 :   const struct {
    2012             :     time_t maximum; int primary_delay; int nonprimary_delay;
    2013        1314 :   } delays[] = {
    2014             :     // clang-format off
    2015             :     { SIX_HOURS,    10*60,  1*60*60 },
    2016             :     { FOUR_DAYS,    90*60,  4*60*60 },
    2017             :     { SEVEN_DAYS, 4*60*60, 18*60*60 },
    2018             :     { TIME_MAX,   9*60*60, 36*60*60 }
    2019             :     // clang-format on
    2020             :   };
    2021             : 
    2022        1314 :   unsigned i;
    2023        1344 :   for (i = 0; i < ARRAY_LENGTH(delays); ++i) {
    2024        1344 :     if (tdiff <= delays[i].maximum) {
    2025        1314 :       return is_primary ? delays[i].primary_delay : delays[i].nonprimary_delay;
    2026             :     }
    2027             :   }
    2028             :   /* LCOV_EXCL_START -- can't reach, since delays ends with TIME_MAX. */
    2029             :   tor_assert_nonfatal_unreached();
    2030             :   return 36*60*60;
    2031             :   /* LCOV_EXCL_STOP */
    2032             : }
    2033             : 
    2034             : /**
    2035             :  * If <b>guard</b> is unreachable, consider whether enough time has passed
    2036             :  * to consider it maybe-reachable again.
    2037             :  */
    2038             : STATIC void
    2039       20051 : entry_guard_consider_retry(entry_guard_t *guard)
    2040             : {
    2041       20051 :   if (guard->is_reachable != GUARD_REACHABLE_NO)
    2042             :     return; /* No retry needed. */
    2043             : 
    2044        1314 :   const time_t now = approx_time();
    2045        1314 :   const int delay =
    2046        1314 :     get_retry_schedule(guard->failing_since, now, guard->is_primary);
    2047        1314 :   const time_t last_attempt = guard->last_tried_to_connect;
    2048             : 
    2049        1314 :   if (BUG(last_attempt == 0) ||
    2050        1314 :       now >= last_attempt + delay) {
    2051             :     /* We should mark this retriable. */
    2052          12 :     char tbuf[ISO_TIME_LEN+1];
    2053          12 :     format_local_iso_time(tbuf, last_attempt);
    2054          27 :     log_info(LD_GUARD, "Marked %s%sguard %s for possible retry, since we "
    2055             :              "haven't tried to use it since %s.",
    2056             :              guard->is_primary?"primary ":"",
    2057             :              guard->confirmed_idx>=0?"confirmed ":"",
    2058             :              entry_guard_describe(guard),
    2059             :              tbuf);
    2060             : 
    2061          12 :     guard->is_reachable = GUARD_REACHABLE_MAYBE;
    2062          12 :     if (guard->is_filtered_guard)
    2063          12 :       guard->is_usable_filtered_guard = 1;
    2064             :   }
    2065             : }
    2066             : 
    2067             : /** Tell the entry guards subsystem that we have confirmed that as of
    2068             :  * just now, we're on the internet. */
    2069             : void
    2070         255 : entry_guards_note_internet_connectivity(guard_selection_t *gs)
    2071             : {
    2072         255 :   gs->last_time_on_internet = approx_time();
    2073         255 : }
    2074             : 
    2075             : /**
    2076             :  * Pick a primary guard for use with a circuit, if available. Update the
    2077             :  * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
    2078             :  * guard as appropriate.  Set <b>state_out</b> to the new guard-state
    2079             :  * of the circuit.
    2080             :  */
    2081             : static entry_guard_t *
    2082         256 : select_primary_guard_for_circuit(guard_selection_t *gs,
    2083             :                                  guard_usage_t usage,
    2084             :                                  const entry_guard_restriction_t *rst,
    2085             :                                  unsigned *state_out)
    2086             : {
    2087         256 :   const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
    2088         256 :   entry_guard_t *chosen_guard = NULL;
    2089             : 
    2090         256 :   int num_entry_guards = get_n_primary_guards_to_use(usage);
    2091         256 :   smartlist_t *usable_primary_guards = smartlist_new();
    2092             : 
    2093         671 :   SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
    2094         571 :     entry_guard_consider_retry(guard);
    2095         571 :     if (!entry_guard_obeys_restriction(guard, rst)) {
    2096          27 :       log_info(LD_GUARD, "Entry guard %s doesn't obey restriction, we test the"
    2097             :           " next one", entry_guard_describe(guard));
    2098          27 :       continue;
    2099             :     }
    2100         544 :     if (guard->is_reachable != GUARD_REACHABLE_NO) {
    2101         157 :       if (need_descriptor && !guard_has_descriptor(guard)) {
    2102           0 :         log_info(LD_GUARD, "Guard %s does not have a descriptor",
    2103             :             entry_guard_describe(guard));
    2104           0 :         continue;
    2105             :       }
    2106         157 :       *state_out = GUARD_CIRC_STATE_USABLE_ON_COMPLETION;
    2107         157 :       guard->last_tried_to_connect = approx_time();
    2108         157 :       smartlist_add(usable_primary_guards, guard);
    2109         157 :       if (smartlist_len(usable_primary_guards) >= num_entry_guards)
    2110             :         break;
    2111             :     }
    2112         415 :   } SMARTLIST_FOREACH_END(guard);
    2113             : 
    2114         256 :   if (smartlist_len(usable_primary_guards)) {
    2115         157 :     chosen_guard = smartlist_choose(usable_primary_guards);
    2116         157 :     log_info(LD_GUARD,
    2117             :         "Selected primary guard %s for circuit from a list size of %d.",
    2118             :         entry_guard_describe(chosen_guard),
    2119             :         smartlist_len(usable_primary_guards));
    2120         157 :     smartlist_free(usable_primary_guards);
    2121             :   }
    2122             : 
    2123         256 :   smartlist_free(usable_primary_guards);
    2124         256 :   return chosen_guard;
    2125             : }
    2126             : 
    2127             : /**
    2128             :  * For use with a circuit, pick a non-pending running filtered confirmed guard,
    2129             :  * if one is available. Update the <b>last_tried_to_connect</b> time and the
    2130             :  * <b>is_pending</b> fields of the guard as appropriate. Set <b>state_out</b>
    2131             :  * to the new guard-state of the circuit.
    2132             :  */
    2133             : static entry_guard_t *
    2134          99 : select_confirmed_guard_for_circuit(guard_selection_t *gs,
    2135             :                                   guard_usage_t usage,
    2136             :                                   const entry_guard_restriction_t *rst,
    2137             :                                   unsigned *state_out)
    2138             : {
    2139          99 :   const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
    2140             : 
    2141         474 :   SMARTLIST_FOREACH_BEGIN(gs->confirmed_entry_guards, entry_guard_t *, guard) {
    2142         396 :     if (guard->is_primary)
    2143         270 :       continue; /* we already considered this one. */
    2144         126 :     if (! entry_guard_obeys_restriction(guard, rst))
    2145          24 :       continue;
    2146         102 :     entry_guard_consider_retry(guard);
    2147         102 :     if (guard->is_usable_filtered_guard && ! guard->is_pending) {
    2148          21 :       if (need_descriptor && !guard_has_descriptor(guard))
    2149           0 :         continue; /* not a bug */
    2150          21 :       guard->is_pending = 1;
    2151          21 :       guard->last_tried_to_connect = approx_time();
    2152          21 :       *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
    2153          21 :       log_info(LD_GUARD, "No primary guards available. Selected confirmed "
    2154             :                "guard %s for circuit. Will try other guards before using "
    2155             :                "this circuit.",
    2156             :                entry_guard_describe(guard));
    2157          21 :       return guard;
    2158             :     }
    2159         375 :   } SMARTLIST_FOREACH_END(guard);
    2160             : 
    2161             :   return NULL;
    2162             : }
    2163             : 
    2164             : /**
    2165             :  * For use with a circuit, pick a usable filtered guard. Update the
    2166             :  * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
    2167             :  * guard as appropriate. Set <b>state_out</b> to the new guard-state of the
    2168             :  * circuit.
    2169             :  */
    2170             : static entry_guard_t *
    2171          78 : select_filtered_guard_for_circuit(guard_selection_t *gs,
    2172             :                                   guard_usage_t usage,
    2173             :                                   const entry_guard_restriction_t *rst,
    2174             :                                   unsigned *state_out)
    2175             : {
    2176          78 :   const int need_descriptor = (usage == GUARD_USAGE_TRAFFIC);
    2177          78 :   entry_guard_t *chosen_guard = NULL;
    2178          78 :   unsigned flags = 0;
    2179          78 :   if (need_descriptor)
    2180          75 :     flags |= SAMPLE_EXCLUDE_NO_DESCRIPTOR;
    2181          78 :   chosen_guard = first_reachable_filtered_entry_guard(gs,
    2182             :                                                  rst,
    2183             :                                                  SAMPLE_EXCLUDE_CONFIRMED |
    2184             :                                                  SAMPLE_EXCLUDE_PRIMARY |
    2185             :                                                  SAMPLE_EXCLUDE_PENDING |
    2186             :                                                  flags);
    2187          78 :   if (!chosen_guard) {
    2188             :     return NULL;
    2189             :   }
    2190             : 
    2191          72 :   chosen_guard->is_pending = 1;
    2192          72 :   chosen_guard->last_tried_to_connect = approx_time();
    2193          72 :   *state_out = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
    2194          72 :   log_info(LD_GUARD, "No primary or confirmed guards available. Selected "
    2195             :            "guard %s for circuit. Will try other guards before "
    2196             :            "using this circuit.",
    2197             :            entry_guard_describe(chosen_guard));
    2198          72 :   return chosen_guard;
    2199             : }
    2200             : 
    2201             : /**
    2202             :  * Get a guard for use with a circuit.  Prefer to pick a running primary
    2203             :  * guard; then a non-pending running filtered confirmed guard; then a
    2204             :  * non-pending runnable filtered guard.  Update the
    2205             :  * <b>last_tried_to_connect</b> time and the <b>is_pending</b> fields of the
    2206             :  * guard as appropriate.  Set <b>state_out</b> to the new guard-state
    2207             :  * of the circuit.
    2208             :  */
    2209             : STATIC entry_guard_t *
    2210         256 : select_entry_guard_for_circuit(guard_selection_t *gs,
    2211             :                                guard_usage_t usage,
    2212             :                                const entry_guard_restriction_t *rst,
    2213             :                                unsigned *state_out)
    2214             : {
    2215         256 :   entry_guard_t *chosen_guard = NULL;
    2216         256 :   tor_assert(gs);
    2217         256 :   tor_assert(state_out);
    2218             : 
    2219         256 :   if (!gs->primary_guards_up_to_date)
    2220         144 :     entry_guards_update_primary(gs);
    2221             : 
    2222             :   /* "If any entry in PRIMARY_GUARDS has {is_reachable} status of
    2223             :       <maybe> or <yes>, return the first such guard." */
    2224         256 :   chosen_guard = select_primary_guard_for_circuit(gs, usage, rst, state_out);
    2225         256 :   if (chosen_guard)
    2226             :     return chosen_guard;
    2227             : 
    2228             :   /* "Otherwise, if the ordered intersection of {CONFIRMED_GUARDS}
    2229             :       and {USABLE_FILTERED_GUARDS} is nonempty, return the first
    2230             :       entry in that intersection that has {is_pending} set to
    2231             :       false." */
    2232          99 :   chosen_guard = select_confirmed_guard_for_circuit(gs, usage, rst, state_out);
    2233          99 :   if (chosen_guard)
    2234             :     return chosen_guard;
    2235             : 
    2236             :   /* "Otherwise, if there is no such entry, select a member
    2237             :    * {USABLE_FILTERED_GUARDS} following the sample ordering" */
    2238          78 :   chosen_guard = select_filtered_guard_for_circuit(gs, usage, rst, state_out);
    2239             : 
    2240          78 :   if (chosen_guard == NULL) {
    2241           6 :     log_info(LD_GUARD, "Absolutely no sampled guards were available. "
    2242             :              "Marking all guards for retry and starting from top again.");
    2243           6 :     mark_all_guards_maybe_reachable(gs);
    2244           6 :     return NULL;
    2245             :   }
    2246             : 
    2247             :   return chosen_guard;
    2248             : }
    2249             : 
    2250             : /**
    2251             :  * Note that we failed to connect to or build circuits through <b>guard</b>.
    2252             :  * Use with a guard returned by select_entry_guard_for_circuit().
    2253             :  */
    2254             : STATIC void
    2255         120 : entry_guards_note_guard_failure(guard_selection_t *gs,
    2256             :                                 entry_guard_t *guard)
    2257             : {
    2258         120 :   tor_assert(gs);
    2259             : 
    2260         120 :   guard->is_reachable = GUARD_REACHABLE_NO;
    2261         120 :   guard->is_usable_filtered_guard = 0;
    2262             : 
    2263         120 :   guard->is_pending = 0;
    2264         120 :   if (guard->failing_since == 0)
    2265         120 :     guard->failing_since = approx_time();
    2266             : 
    2267             :   /* This guard not reachable: send GUARD DOWN event */
    2268         120 :   control_event_guard(guard->nickname, guard->identity, "DOWN");
    2269             : 
    2270         129 :   log_info(LD_GUARD, "Recorded failure for %s%sguard %s",
    2271             :            guard->is_primary?"primary ":"",
    2272             :            guard->confirmed_idx>=0?"confirmed ":"",
    2273             :            entry_guard_describe(guard));
    2274         120 : }
    2275             : 
    2276             : /**
    2277             :  * Note that we successfully connected to, and built a circuit through
    2278             :  * <b>guard</b>. Given the old guard-state of the circuit in <b>old_state</b>,
    2279             :  * return the new guard-state of the circuit.
    2280             :  *
    2281             :  * Be aware: the circuit is only usable when its guard-state becomes
    2282             :  * GUARD_CIRC_STATE_COMPLETE.
    2283             :  **/
    2284             : STATIC unsigned
    2285          54 : entry_guards_note_guard_success(guard_selection_t *gs,
    2286             :                                 entry_guard_t *guard,
    2287             :                                 unsigned old_state)
    2288             : {
    2289          54 :   tor_assert(gs);
    2290             : 
    2291             :   /* Save this, since we're about to overwrite it. */
    2292          54 :   const time_t last_time_on_internet = gs->last_time_on_internet;
    2293          54 :   gs->last_time_on_internet = approx_time();
    2294             : 
    2295             :   /* If guard was not already marked as reachable, send a GUARD UP signal */
    2296          54 :   if (guard->is_reachable != GUARD_REACHABLE_YES) {
    2297          54 :     control_event_guard(guard->nickname, guard->identity, "UP");
    2298             :   }
    2299             : 
    2300          54 :   guard->is_reachable = GUARD_REACHABLE_YES;
    2301          54 :   guard->failing_since = 0;
    2302          54 :   guard->is_pending = 0;
    2303          54 :   if (guard->is_filtered_guard)
    2304          54 :     guard->is_usable_filtered_guard = 1;
    2305             : 
    2306          54 :   if (guard->confirmed_idx < 0) {
    2307          51 :     make_guard_confirmed(gs, guard);
    2308          51 :     if (!gs->primary_guards_up_to_date)
    2309          51 :       entry_guards_update_primary(gs);
    2310             :   }
    2311             : 
    2312          54 :   unsigned new_state;
    2313          54 :   switch (old_state) {
    2314             :     case GUARD_CIRC_STATE_COMPLETE:
    2315             :     case GUARD_CIRC_STATE_USABLE_ON_COMPLETION:
    2316             :       new_state = GUARD_CIRC_STATE_COMPLETE;
    2317             :       break;
    2318           0 :     default:
    2319           0 :       tor_assert_nonfatal_unreached();
    2320          45 :       FALLTHROUGH_UNLESS_ALL_BUGS_ARE_FATAL;
    2321          45 :     case GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD:
    2322          45 :       if (guard->is_primary) {
    2323             :         /* XXXX #20832 -- I don't actually like this logic. It seems to make
    2324             :          * us a little more susceptible to evil-ISP attacks.  The mitigations
    2325             :          * I'm thinking of, however, aren't local to this point, so I'll leave
    2326             :          * it alone. */
    2327             :         /* This guard may have become primary by virtue of being confirmed.
    2328             :          * If so, the circuit for it is now complete.
    2329             :          */
    2330             :         new_state = GUARD_CIRC_STATE_COMPLETE;
    2331             :       } else {
    2332          42 :         new_state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
    2333             :       }
    2334             :       break;
    2335             :   }
    2336             : 
    2337          54 :   if (! guard->is_primary) {
    2338          84 :     if (last_time_on_internet + get_internet_likely_down_interval()
    2339          42 :         < approx_time()) {
    2340           3 :       mark_primary_guards_maybe_reachable(gs);
    2341             :     }
    2342             :   }
    2343             : 
    2344          96 :   log_info(LD_GUARD, "Recorded success for %s%sguard %s",
    2345             :            guard->is_primary?"primary ":"",
    2346             :            guard->confirmed_idx>=0?"confirmed ":"",
    2347             :            entry_guard_describe(guard));
    2348             : 
    2349          54 :   return new_state;
    2350             : }
    2351             : 
    2352             : /**
    2353             :  * Helper: Return true iff <b>a</b> has higher priority than <b>b</b>.
    2354             :  */
    2355             : STATIC int
    2356          64 : entry_guard_has_higher_priority(entry_guard_t *a, entry_guard_t *b)
    2357             : {
    2358          64 :   tor_assert(a && b);
    2359          64 :   if (a == b)
    2360             :     return 0;
    2361             : 
    2362             :   /* Confirmed is always better than unconfirmed; lower index better
    2363             :      than higher */
    2364          42 :   if (a->confirmed_idx < 0) {
    2365          12 :     if (b->confirmed_idx >= 0)
    2366             :       return 0;
    2367             :   } else {
    2368          30 :     if (b->confirmed_idx < 0)
    2369             :       return 1;
    2370             : 
    2371             :     /* Lower confirmed_idx is better than higher. */
    2372          29 :     return (a->confirmed_idx < b->confirmed_idx);
    2373             :   }
    2374             : 
    2375             :   /* If we reach this point, both are unconfirmed. If one is pending, it
    2376             :    * has higher priority. */
    2377           8 :   if (a->is_pending) {
    2378           5 :     if (! b->is_pending)
    2379             :       return 1;
    2380             : 
    2381             :     /* Both are pending: earlier last_tried_connect wins. */
    2382           4 :     return a->last_tried_to_connect < b->last_tried_to_connect;
    2383             :   } else {
    2384           3 :     if (b->is_pending)
    2385             :       return 0;
    2386             : 
    2387             :     /* Neither is pending: priorities are equal. */
    2388             :     return 0;
    2389             :   }
    2390             : }
    2391             : 
    2392             : /** Release all storage held in <b>restriction</b> */
    2393             : STATIC void
    2394         202 : entry_guard_restriction_free_(entry_guard_restriction_t *rst)
    2395             : {
    2396         202 :   tor_free(rst);
    2397         202 : }
    2398             : 
    2399             : /**
    2400             :  * Release all storage held in <b>state</b>.
    2401             :  */
    2402             : void
    2403         320 : circuit_guard_state_free_(circuit_guard_state_t *state)
    2404             : {
    2405         320 :   if (!state)
    2406             :     return;
    2407         196 :   entry_guard_restriction_free(state->restrictions);
    2408         196 :   entry_guard_handle_free(state->guard);
    2409         196 :   tor_free(state);
    2410             : }
    2411             : 
    2412             : /** Allocate and return a new circuit_guard_state_t to track the result
    2413             :  * of using <b>guard</b> for a given operation. */
    2414         196 : MOCK_IMPL(STATIC circuit_guard_state_t *,
    2415             : circuit_guard_state_new,(entry_guard_t *guard, unsigned state,
    2416             :                          entry_guard_restriction_t *rst))
    2417             : {
    2418         196 :   circuit_guard_state_t *result;
    2419             : 
    2420         196 :   result = tor_malloc_zero(sizeof(circuit_guard_state_t));
    2421         196 :   result->guard = entry_guard_handle_new(guard);
    2422         196 :   result->state = state;
    2423         196 :   result->state_set_at = approx_time();
    2424         196 :   result->restrictions = rst;
    2425             : 
    2426         196 :   return result;
    2427             : }
    2428             : 
    2429             : /**
    2430             :  * Pick a suitable entry guard for a circuit in, and place that guard
    2431             :  * in *<b>chosen_node_out</b>. Set *<b>guard_state_out</b> to an opaque
    2432             :  * state object that will record whether the circuit is ready to be used
    2433             :  * or not. Return 0 on success; on failure, return -1.
    2434             :  *
    2435             :  * If a restriction is provided in <b>rst</b>, do not return any guards that
    2436             :  * violate it, and remember that restriction in <b>guard_state_out</b> for
    2437             :  * later use. (Takes ownership of the <b>rst</b> object.)
    2438             :  */
    2439             : int
    2440         196 : entry_guard_pick_for_circuit(guard_selection_t *gs,
    2441             :                              guard_usage_t usage,
    2442             :                              entry_guard_restriction_t *rst,
    2443             :                              const node_t **chosen_node_out,
    2444             :                              circuit_guard_state_t **guard_state_out)
    2445             : {
    2446         196 :   tor_assert(gs);
    2447         196 :   tor_assert(chosen_node_out);
    2448         196 :   tor_assert(guard_state_out);
    2449         196 :   *chosen_node_out = NULL;
    2450         196 :   *guard_state_out = NULL;
    2451             : 
    2452         196 :   unsigned state = 0;
    2453         196 :   entry_guard_t *guard =
    2454         196 :     select_entry_guard_for_circuit(gs, usage, rst, &state);
    2455         196 :   if (! guard)
    2456           0 :     goto fail;
    2457         196 :   if (BUG(state == 0))
    2458           0 :     goto fail;
    2459         196 :   const node_t *node = node_get_by_id(guard->identity);
    2460             :   // XXXX #20827 check Ed ID.
    2461         196 :   if (! node)
    2462           0 :     goto fail;
    2463         196 :   if (BUG(usage != GUARD_USAGE_DIRGUARD &&
    2464             :           !node_has_preferred_descriptor(node, 1)))
    2465           0 :     goto fail;
    2466             : 
    2467         196 :   *chosen_node_out = node;
    2468         196 :   *guard_state_out = circuit_guard_state_new(guard, state, rst);
    2469             : 
    2470         196 :   return 0;
    2471           0 :  fail:
    2472           0 :   entry_guard_restriction_free(rst);
    2473           0 :   return -1;
    2474             : }
    2475             : 
    2476             : /**
    2477             :  * Called by the circuit building module when a circuit has succeeded: informs
    2478             :  * the guards code that the guard in *<b>guard_state_p</b> is working, and
    2479             :  * advances the state of the guard module.  On a GUARD_USABLE_NEVER return
    2480             :  * value, the circuit is broken and should not be used.  On a GUARD_USABLE_NOW
    2481             :  * return value, the circuit is ready to use.  On a GUARD_MAYBE_USABLE_LATER
    2482             :  * return value, the circuit should not be used until we find out whether
    2483             :  * preferred guards will work for us.
    2484             :  */
    2485             : guard_usable_t
    2486          54 : entry_guard_succeeded(circuit_guard_state_t **guard_state_p)
    2487             : {
    2488          54 :   if (BUG(*guard_state_p == NULL))
    2489           0 :     return GUARD_USABLE_NEVER;
    2490             : 
    2491          54 :   entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
    2492          54 :   if (! guard || BUG(guard->in_selection == NULL))
    2493           0 :     return GUARD_USABLE_NEVER;
    2494             : 
    2495          54 :   unsigned newstate =
    2496         108 :     entry_guards_note_guard_success(guard->in_selection, guard,
    2497          54 :                                     (*guard_state_p)->state);
    2498             : 
    2499          54 :   (*guard_state_p)->state = newstate;
    2500          54 :   (*guard_state_p)->state_set_at = approx_time();
    2501             : 
    2502          54 :   if (newstate == GUARD_CIRC_STATE_COMPLETE) {
    2503             :     return GUARD_USABLE_NOW;
    2504             :   } else {
    2505          42 :     return GUARD_MAYBE_USABLE_LATER;
    2506             :   }
    2507             : }
    2508             : 
    2509             : /** Cancel the selection of *<b>guard_state_p</b> without declaring
    2510             :  * success or failure. It is safe to call this function if success or
    2511             :  * failure _has_ already been declared. */
    2512             : void
    2513          64 : entry_guard_cancel(circuit_guard_state_t **guard_state_p)
    2514             : {
    2515          64 :   if (BUG(*guard_state_p == NULL))
    2516           0 :     return;
    2517          64 :   entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
    2518          64 :   if (! guard)
    2519             :     return;
    2520             : 
    2521             :   /* XXXX prop271 -- last_tried_to_connect_at will be erroneous here, but this
    2522             :    * function will only get called in "bug" cases anyway. */
    2523          10 :   guard->is_pending = 0;
    2524          10 :   circuit_guard_state_free(*guard_state_p);
    2525          10 :   *guard_state_p = NULL;
    2526             : }
    2527             : 
    2528             : /**
    2529             :  * Called by the circuit building module when a circuit has failed:
    2530             :  * informs the guards code that the guard in *<b>guard_state_p</b> is
    2531             :  * not working, and advances the state of the guard module.
    2532             :  */
    2533             : void
    2534         111 : entry_guard_failed(circuit_guard_state_t **guard_state_p)
    2535             : {
    2536         111 :   if (BUG(*guard_state_p == NULL))
    2537           0 :     return;
    2538             : 
    2539         111 :   entry_guard_t *guard = entry_guard_handle_get((*guard_state_p)->guard);
    2540         111 :   if (! guard || BUG(guard->in_selection == NULL))
    2541           0 :     return;
    2542             : 
    2543         111 :   entry_guards_note_guard_failure(guard->in_selection, guard);
    2544             : 
    2545         111 :   (*guard_state_p)->state = GUARD_CIRC_STATE_DEAD;
    2546         111 :   (*guard_state_p)->state_set_at = approx_time();
    2547             : }
    2548             : 
    2549             : /**
    2550             :  * Run the entry_guard_failed() function on every circuit that is
    2551             :  * pending on <b>chan</b>.
    2552             :  */
    2553             : void
    2554           5 : entry_guard_chan_failed(channel_t *chan)
    2555             : {
    2556           5 :   if (!chan)
    2557           5 :     return;
    2558             : 
    2559           0 :   smartlist_t *pending = smartlist_new();
    2560           0 :   circuit_get_all_pending_on_channel(pending, chan);
    2561           0 :   SMARTLIST_FOREACH_BEGIN(pending, circuit_t *, circ) {
    2562           0 :     if (!CIRCUIT_IS_ORIGIN(circ))
    2563           0 :       continue;
    2564             : 
    2565           0 :     origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
    2566           0 :     if (origin_circ->guard_state) {
    2567             :       /* We might have no guard state if we didn't use a guard on this
    2568             :        * circuit (eg it's for a fallback directory). */
    2569           0 :       entry_guard_failed(&origin_circ->guard_state);
    2570             :     }
    2571           0 :   } SMARTLIST_FOREACH_END(circ);
    2572           0 :   smartlist_free(pending);
    2573             : }
    2574             : 
    2575             : /**
    2576             :  * Return true iff every primary guard in <b>gs</b> is believed to
    2577             :  * be unreachable.
    2578             :  */
    2579             : STATIC int
    2580          43 : entry_guards_all_primary_guards_are_down(guard_selection_t *gs)
    2581             : {
    2582          43 :   tor_assert(gs);
    2583          43 :   if (!gs->primary_guards_up_to_date)
    2584          10 :     entry_guards_update_primary(gs);
    2585         151 :   SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
    2586         114 :     entry_guard_consider_retry(guard);
    2587         114 :     if (guard->is_reachable != GUARD_REACHABLE_NO)
    2588             :       return 0;
    2589         108 :   } SMARTLIST_FOREACH_END(guard);
    2590             :   return 1;
    2591             : }
    2592             : 
    2593             : /** Wrapper for entry_guard_has_higher_priority that compares the
    2594             :  * guard-priorities of a pair of circuits. Return 1 if <b>a</b> has higher
    2595             :  * priority than <b>b</b>.
    2596             :  *
    2597             :  * If a restriction is provided in <b>rst</b>, then do not consider
    2598             :  * <b>a</b> to have higher priority if it violates the restriction.
    2599             :  */
    2600             : static int
    2601          57 : circ_state_has_higher_priority(origin_circuit_t *a,
    2602             :                                const entry_guard_restriction_t *rst,
    2603             :                                origin_circuit_t *b)
    2604             : {
    2605          57 :   circuit_guard_state_t *state_a = origin_circuit_get_guard_state(a);
    2606          57 :   circuit_guard_state_t *state_b = origin_circuit_get_guard_state(b);
    2607             : 
    2608          57 :   tor_assert(state_a);
    2609          57 :   tor_assert(state_b);
    2610             : 
    2611          57 :   entry_guard_t *guard_a = entry_guard_handle_get(state_a->guard);
    2612          57 :   entry_guard_t *guard_b = entry_guard_handle_get(state_b->guard);
    2613             : 
    2614          57 :   if (! guard_a) {
    2615             :     /* Unknown guard -- never higher priority. */
    2616             :     return 0;
    2617          57 :   } else if (! guard_b) {
    2618             :     /* Known guard -- higher priority than any unknown guard. */
    2619             :     return 1;
    2620          57 :   } else  if (! entry_guard_obeys_restriction(guard_a, rst)) {
    2621             :     /* Restriction violated; guard_a cannot have higher priority. */
    2622             :     return 0;
    2623             :   } else {
    2624             :     /* Both known -- compare.*/
    2625          51 :     return entry_guard_has_higher_priority(guard_a, guard_b);
    2626             :   }
    2627             : }
    2628             : 
    2629             : /**
    2630             :  * Look at all of the origin_circuit_t * objects in <b>all_circuits_in</b>,
    2631             :  * and see if any of them that were previously not ready to use for
    2632             :  * guard-related reasons are now ready to use. Place those circuits
    2633             :  * in <b>newly_complete_out</b>, and mark them COMPLETE.
    2634             :  *
    2635             :  * Return 1 if we upgraded any circuits, and 0 otherwise.
    2636             :  */
    2637             : int
    2638          34 : entry_guards_upgrade_waiting_circuits(guard_selection_t *gs,
    2639             :                                       const smartlist_t *all_circuits_in,
    2640             :                                       smartlist_t *newly_complete_out)
    2641             : {
    2642          34 :   tor_assert(gs);
    2643          34 :   tor_assert(all_circuits_in);
    2644          34 :   tor_assert(newly_complete_out);
    2645             : 
    2646          34 :   if (! entry_guards_all_primary_guards_are_down(gs)) {
    2647             :     /* We only upgrade a waiting circuit if the primary guards are all
    2648             :      * down. */
    2649           3 :     log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
    2650             :               "but not all primary guards were definitely down.");
    2651           3 :     return 0;
    2652             :   }
    2653             : 
    2654          31 :   int n_waiting = 0;
    2655          31 :   int n_complete = 0;
    2656          31 :   int n_complete_blocking = 0;
    2657          31 :   origin_circuit_t *best_waiting_circuit = NULL;
    2658          31 :   smartlist_t *all_circuits = smartlist_new();
    2659          92 :   SMARTLIST_FOREACH_BEGIN(all_circuits_in, origin_circuit_t *, circ) {
    2660             :     // We filter out circuits that aren't ours, or which we can't
    2661             :     // reason about.
    2662          61 :     circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    2663          61 :     if (state == NULL)
    2664           0 :       continue;
    2665          61 :     entry_guard_t *guard = entry_guard_handle_get(state->guard);
    2666          61 :     if (!guard || guard->in_selection != gs)
    2667           0 :       continue;
    2668          61 :     if (TO_CIRCUIT(circ)->marked_for_close) {
    2669             :       /* Don't consider any marked for close circuits. */
    2670           1 :       continue;
    2671             :     }
    2672             : 
    2673          60 :     smartlist_add(all_circuits, circ);
    2674          61 :   } SMARTLIST_FOREACH_END(circ);
    2675             : 
    2676          91 :   SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    2677          60 :     circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    2678          60 :     if (BUG(state == NULL))
    2679           0 :       continue;
    2680             : 
    2681          60 :     if (state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD) {
    2682          36 :       ++n_waiting;
    2683          45 :       if (! best_waiting_circuit ||
    2684           9 :           circ_state_has_higher_priority(circ, NULL, best_waiting_circuit)) {
    2685             :         best_waiting_circuit = circ;
    2686             :       }
    2687             :     }
    2688          60 :   } SMARTLIST_FOREACH_END(circ);
    2689             : 
    2690          31 :   if (! best_waiting_circuit) {
    2691           4 :     log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits, "
    2692             :               "but didn't find any.");
    2693           4 :     goto no_change;
    2694             :   }
    2695             : 
    2696             :   /* We'll need to keep track of what restrictions were used when picking this
    2697             :    * circuit, so that we don't allow any circuit without those restrictions to
    2698             :    * block it. */
    2699          54 :   const entry_guard_restriction_t *rst_on_best_waiting =
    2700          27 :     origin_circuit_get_guard_state(best_waiting_circuit)->restrictions;
    2701             : 
    2702             :   /* First look at the complete circuits: Do any block this circuit? */
    2703          81 :   SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    2704             :     /* "C2 "blocks" C1 if:
    2705             :         * C2 obeys all the restrictions that C1 had to obey, AND
    2706             :         * C2 has higher priority than C1, AND
    2707             :         * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
    2708             :           or C2 has been <usable_if_no_better_guard> for no more than
    2709             :           {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
    2710             :     */
    2711          54 :     circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    2712          54 :     if BUG((state == NULL))
    2713           0 :       continue;
    2714          54 :     if (state->state != GUARD_CIRC_STATE_COMPLETE)
    2715          45 :       continue;
    2716           9 :     ++n_complete;
    2717           9 :     if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
    2718             :                                        best_waiting_circuit))
    2719           3 :       ++n_complete_blocking;
    2720          54 :   } SMARTLIST_FOREACH_END(circ);
    2721             : 
    2722          27 :   if (n_complete_blocking) {
    2723           3 :     log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
    2724             :               "%d complete and %d guard-stalled. At least one complete "
    2725             :               "circuit had higher priority, so not upgrading.",
    2726             :               n_complete, n_waiting);
    2727           3 :     goto no_change;
    2728             :   }
    2729             : 
    2730             :   /* " * If any circuit C1 is <waiting_for_better_guard>, AND:
    2731             :           * All primary guards have reachable status of <no>.
    2732             :           * There is no circuit C2 that "blocks" C1.
    2733             :          Then, upgrade C1 to <complete>.""
    2734             :   */
    2735          24 :   int n_blockers_found = 0;
    2736          48 :   const time_t state_set_at_cutoff =
    2737          24 :     approx_time() - get_nonprimary_guard_connect_timeout();
    2738          72 :   SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    2739          48 :     circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    2740          48 :     if (BUG(state == NULL))
    2741           0 :       continue;
    2742          48 :     if (state->state != GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD)
    2743          39 :       continue;
    2744           9 :     if (state->state_set_at <= state_set_at_cutoff)
    2745           0 :       continue;
    2746           9 :     if (circ_state_has_higher_priority(circ, rst_on_best_waiting,
    2747             :                                        best_waiting_circuit))
    2748           3 :       ++n_blockers_found;
    2749          48 :   } SMARTLIST_FOREACH_END(circ);
    2750             : 
    2751          24 :   if (n_blockers_found) {
    2752           3 :     log_debug(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
    2753             :               "%d guard-stalled, but %d pending circuit(s) had higher "
    2754             :               "guard priority, so not upgrading.",
    2755             :               n_waiting, n_blockers_found);
    2756           3 :     goto no_change;
    2757             :   }
    2758             : 
    2759             :   /* Okay. We have a best waiting circuit, and we aren't waiting for
    2760             :      anything better.  Add all circuits with that priority to the
    2761             :      list, and call them COMPLETE. */
    2762          21 :   int n_succeeded = 0;
    2763          63 :   SMARTLIST_FOREACH_BEGIN(all_circuits, origin_circuit_t *, circ) {
    2764          42 :     circuit_guard_state_t *state = origin_circuit_get_guard_state(circ);
    2765          42 :     if (BUG(state == NULL))
    2766           0 :       continue;
    2767          42 :     if (circ != best_waiting_circuit && rst_on_best_waiting) {
    2768             :       /* Can't upgrade other circ with same priority as best; might
    2769             :          be blocked. */
    2770           6 :       continue;
    2771             :     }
    2772          36 :     if (state->state != GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD)
    2773           6 :       continue;
    2774          30 :     if (circ_state_has_higher_priority(best_waiting_circuit, NULL, circ))
    2775           9 :       continue;
    2776             : 
    2777          21 :     state->state = GUARD_CIRC_STATE_COMPLETE;
    2778          21 :     state->state_set_at = approx_time();
    2779          21 :     smartlist_add(newly_complete_out, circ);
    2780          21 :     ++n_succeeded;
    2781          42 :   } SMARTLIST_FOREACH_END(circ);
    2782             : 
    2783          21 :   log_info(LD_GUARD, "Considered upgrading guard-stalled circuits: found "
    2784             :            "%d guard-stalled, %d complete. %d of the guard-stalled "
    2785             :            "circuit(s) had high enough priority to upgrade.",
    2786             :            n_waiting, n_complete, n_succeeded);
    2787             : 
    2788          21 :   tor_assert_nonfatal(n_succeeded >= 1);
    2789          21 :   smartlist_free(all_circuits);
    2790          21 :   return 1;
    2791             : 
    2792          10 :  no_change:
    2793          10 :   smartlist_free(all_circuits);
    2794          10 :   return 0;
    2795             : }
    2796             : 
    2797             : /**
    2798             :  * Return true iff the circuit whose state is <b>guard_state</b> should
    2799             :  * expire.
    2800             :  */
    2801             : int
    2802           4 : entry_guard_state_should_expire(circuit_guard_state_t *guard_state)
    2803             : {
    2804           4 :   if (guard_state == NULL)
    2805             :     return 0;
    2806           6 :   const time_t expire_if_waiting_since =
    2807           3 :     approx_time() - get_nonprimary_guard_idle_timeout();
    2808           3 :   return (guard_state->state == GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD
    2809           3 :           && guard_state->state_set_at < expire_if_waiting_since);
    2810             : }
    2811             : 
    2812             : /**
    2813             :  * Update all derived pieces of the guard selection state in <b>gs</b>.
    2814             :  * Return true iff we should stop using all previously generated circuits.
    2815             :  */
    2816             : int
    2817           9 : entry_guards_update_all(guard_selection_t *gs)
    2818             : {
    2819           9 :   sampled_guards_update_from_consensus(gs);
    2820           9 :   entry_guards_update_filtered_sets(gs);
    2821           9 :   entry_guards_update_confirmed(gs);
    2822           9 :   entry_guards_update_primary(gs);
    2823           9 :   return 0;
    2824             : }
    2825             : 
    2826             : /**
    2827             :  * Return a newly allocated string for encoding the persistent parts of
    2828             :  * <b>guard</b> to the state file. <b>dense_sampled_idx</b> refers to the
    2829             :  * sampled_idx made dense for this <b>guard</b>. Encoding all guards should
    2830             :  * lead to a dense array of sampled_idx in the state file.
    2831             :  */
    2832             : STATIC char *
    2833           9 : entry_guard_encode_for_state(entry_guard_t *guard, int dense_sampled_idx)
    2834             : {
    2835             :   /*
    2836             :    * The meta-format we use is K=V K=V K=V... where K can be any
    2837             :    * characters excepts space and =, and V can be any characters except
    2838             :    * space.  The order of entries is not allowed to matter.
    2839             :    * Unrecognized K=V entries are persisted; recognized but erroneous
    2840             :    * entries are corrected.
    2841             :    */
    2842             : 
    2843           9 :   smartlist_t *result = smartlist_new();
    2844           9 :   char tbuf[ISO_TIME_LEN+1];
    2845             : 
    2846           9 :   tor_assert(guard);
    2847             : 
    2848           9 :   smartlist_add_asprintf(result, "in=%s", guard->selection_name);
    2849           9 :   smartlist_add_asprintf(result, "rsa_id=%s",
    2850           9 :                          hex_str(guard->identity, DIGEST_LEN));
    2851           9 :   if (guard->bridge_addr) {
    2852           3 :     smartlist_add_asprintf(result, "bridge_addr=%s:%d",
    2853           3 :                            fmt_and_decorate_addr(&guard->bridge_addr->addr),
    2854           3 :                            guard->bridge_addr->port);
    2855             :   }
    2856           9 :   if (strlen(guard->nickname) && is_legal_nickname(guard->nickname)) {
    2857           6 :     smartlist_add_asprintf(result, "nickname=%s", guard->nickname);
    2858             :   }
    2859             : 
    2860           9 :   format_iso_time_nospace(tbuf, guard->sampled_on_date);
    2861           9 :   smartlist_add_asprintf(result, "sampled_on=%s", tbuf);
    2862             :   // Replacing the sampled_idx by dense array
    2863           9 :   smartlist_add_asprintf(result, "sampled_idx=%d", dense_sampled_idx);
    2864           9 :   if (guard->sampled_by_version) {
    2865           8 :     smartlist_add_asprintf(result, "sampled_by=%s",
    2866             :                            guard->sampled_by_version);
    2867             :   }
    2868             : 
    2869           9 :   if (guard->unlisted_since_date > 0) {
    2870           1 :     format_iso_time_nospace(tbuf, guard->unlisted_since_date);
    2871           1 :     smartlist_add_asprintf(result, "unlisted_since=%s", tbuf);
    2872             :   }
    2873             : 
    2874           9 :   smartlist_add_asprintf(result, "listed=%d",
    2875           9 :                          (int)guard->currently_listed);
    2876             : 
    2877           9 :   if (guard->confirmed_idx >= 0) {
    2878           4 :     format_iso_time_nospace(tbuf, guard->confirmed_on_date);
    2879           4 :     smartlist_add_asprintf(result, "confirmed_on=%s", tbuf);
    2880             : 
    2881           4 :     smartlist_add_asprintf(result, "confirmed_idx=%d", guard->confirmed_idx);
    2882             :   }
    2883             : 
    2884           9 :   const double EPSILON = 1.0e-6;
    2885             : 
    2886             :   /* Make a copy of the pathbias object, since we will want to update
    2887             :      some of them */
    2888           9 :   guard_pathbias_t *pb = tor_memdup(&guard->pb, sizeof(*pb));
    2889           9 :   pb->use_successes = pathbias_get_use_success_count(guard);
    2890           9 :   pb->successful_circuits_closed = pathbias_get_close_success_count(guard);
    2891             : 
    2892             :   #define PB_FIELD(field) do {                                          \
    2893             :       if (pb->field >= EPSILON) {                                       \
    2894             :         smartlist_add_asprintf(result, "pb_" #field "=%f", pb->field);  \
    2895             :       }                                                                 \
    2896             :     } while (0)
    2897           9 :   PB_FIELD(use_attempts);
    2898           9 :   PB_FIELD(use_successes);
    2899           9 :   PB_FIELD(circ_attempts);
    2900           9 :   PB_FIELD(circ_successes);
    2901           9 :   PB_FIELD(successful_circuits_closed);
    2902           9 :   PB_FIELD(collapsed_circuits);
    2903           9 :   PB_FIELD(unusable_circuits);
    2904           9 :   PB_FIELD(timeouts);
    2905           9 :   tor_free(pb);
    2906             : #undef PB_FIELD
    2907             : 
    2908           9 :   if (guard->extra_state_fields)
    2909           1 :     smartlist_add_strdup(result, guard->extra_state_fields);
    2910             : 
    2911           9 :   char *joined = smartlist_join_strings(result, " ", 0, NULL);
    2912          90 :   SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
    2913           9 :   smartlist_free(result);
    2914             : 
    2915           9 :   return joined;
    2916             : }
    2917             : 
    2918             : /**
    2919             :  * Extract key=val from the state string <b>s</b> and duplicate the value to
    2920             :  * some string target declared in entry_guard_parse_from_state
    2921             :  */
    2922             : static void
    2923          38 : parse_from_state_set_vals(const char *s, smartlist_t *entries, smartlist_t
    2924             :     *extra, strmap_t *vals)
    2925             : {
    2926          38 :     smartlist_split_string(entries, s, " ",
    2927             :                            SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    2928             : 
    2929         356 :     SMARTLIST_FOREACH_BEGIN(entries, char *, entry) {
    2930         318 :       const char *eq = strchr(entry, '=');
    2931         318 :       if (!eq) {
    2932          18 :         smartlist_add(extra, entry);
    2933          18 :         continue;
    2934             :       }
    2935         300 :       char *key = tor_strndup(entry, eq-entry);
    2936         300 :       char **target = strmap_get(vals, key);
    2937         300 :       if (target == NULL || *target != NULL) {
    2938             :         /* unrecognized or already set */
    2939           2 :         smartlist_add(extra, entry);
    2940           2 :         tor_free(key);
    2941           2 :         continue;
    2942             :       }
    2943             : 
    2944         298 :       *target = tor_strdup(eq+1);
    2945         298 :       tor_free(key);
    2946         298 :       tor_free(entry);
    2947         318 :     } SMARTLIST_FOREACH_END(entry);
    2948          38 : }
    2949             : 
    2950             : /**
    2951             :  * Handle part of the parsing state file logic, focused on time related things
    2952             :  */
    2953             : static void
    2954          31 : parse_from_state_handle_time(entry_guard_t *guard, char *sampled_on, char
    2955             :     *unlisted_since, char *confirmed_on)
    2956             : {
    2957             : #define HANDLE_TIME(field) do {                                 \
    2958             :     if (field) {                                                \
    2959             :       int r = parse_iso_time_nospace(field, &field ## _time);   \
    2960             :       if (r < 0) {                                              \
    2961             :         log_warn(LD_CIRC, "Unable to parse %s %s from guard",   \
    2962             :                  #field, escaped(field));                       \
    2963             :         field##_time = -1;                                      \
    2964             :       }                                                         \
    2965             :     }                                                           \
    2966             :   } while (0)
    2967             : 
    2968          31 :   time_t sampled_on_time = 0;
    2969          31 :   time_t unlisted_since_time = 0;
    2970          31 :   time_t confirmed_on_time = 0;
    2971             : 
    2972          31 :   HANDLE_TIME(sampled_on);
    2973          31 :   HANDLE_TIME(unlisted_since);
    2974          31 :   HANDLE_TIME(confirmed_on);
    2975             : 
    2976          31 :   if (sampled_on_time <= 0)
    2977           2 :     sampled_on_time = approx_time();
    2978          31 :   if (unlisted_since_time < 0)
    2979           1 :     unlisted_since_time = 0;
    2980          31 :   if (confirmed_on_time < 0)
    2981           1 :     confirmed_on_time = 0;
    2982             : 
    2983             :   #undef HANDLE_TIME
    2984             : 
    2985          31 :   guard->sampled_on_date = sampled_on_time;
    2986          31 :   guard->unlisted_since_date = unlisted_since_time;
    2987          31 :   guard->confirmed_on_date = confirmed_on_time;
    2988          31 : }
    2989             : 
    2990             : /**
    2991             :  * Given a string generated by entry_guard_encode_for_state(), parse it
    2992             :  * (if possible) and return an entry_guard_t object for it.  Return NULL
    2993             :  * on complete failure.
    2994             :  */
    2995             : STATIC entry_guard_t *
    2996          38 : entry_guard_parse_from_state(const char *s)
    2997             : {
    2998             :   /* Unrecognized entries get put in here. */
    2999          38 :   smartlist_t *extra = smartlist_new();
    3000             : 
    3001             :   /* These fields get parsed from the string. */
    3002          38 :   char *in = NULL;
    3003          38 :   char *rsa_id = NULL;
    3004          38 :   char *nickname = NULL;
    3005          38 :   char *sampled_on = NULL;
    3006          38 :   char *sampled_idx = NULL;
    3007          38 :   char *sampled_by = NULL;
    3008          38 :   char *unlisted_since = NULL;
    3009          38 :   char *listed  = NULL;
    3010          38 :   char *confirmed_on = NULL;
    3011          38 :   char *confirmed_idx = NULL;
    3012          38 :   char *bridge_addr = NULL;
    3013             : 
    3014             :   // pathbias
    3015          38 :   char *pb_use_attempts = NULL;
    3016          38 :   char *pb_use_successes = NULL;
    3017          38 :   char *pb_circ_attempts = NULL;
    3018          38 :   char *pb_circ_successes = NULL;
    3019          38 :   char *pb_successful_circuits_closed = NULL;
    3020          38 :   char *pb_collapsed_circuits = NULL;
    3021          38 :   char *pb_unusable_circuits = NULL;
    3022          38 :   char *pb_timeouts = NULL;
    3023          38 :   int invalid_sampled_idx = get_max_sample_size_absolute();
    3024             : 
    3025             :   /* Split up the entries.  Put the ones we know about in strings and the
    3026             :    * rest in "extra". */
    3027             :   {
    3028          38 :     smartlist_t *entries = smartlist_new();
    3029             : 
    3030          38 :     strmap_t *vals = strmap_new(); // Maps keyword to location
    3031             : #define FIELD(f) \
    3032             :     strmap_set(vals, #f, &f);
    3033          38 :     FIELD(in);
    3034          38 :     FIELD(rsa_id);
    3035          38 :     FIELD(nickname);
    3036          38 :     FIELD(sampled_on);
    3037          38 :     FIELD(sampled_idx);
    3038          38 :     FIELD(sampled_by);
    3039          38 :     FIELD(unlisted_since);
    3040          38 :     FIELD(listed);
    3041          38 :     FIELD(confirmed_on);
    3042          38 :     FIELD(confirmed_idx);
    3043          38 :     FIELD(bridge_addr);
    3044          38 :     FIELD(pb_use_attempts);
    3045          38 :     FIELD(pb_use_successes);
    3046          38 :     FIELD(pb_circ_attempts);
    3047          38 :     FIELD(pb_circ_successes);
    3048          38 :     FIELD(pb_successful_circuits_closed);
    3049          38 :     FIELD(pb_collapsed_circuits);
    3050          38 :     FIELD(pb_unusable_circuits);
    3051          38 :     FIELD(pb_timeouts);
    3052             : #undef FIELD
    3053             :     /* Extract from s the key=val that we recognize, put the others in extra*/
    3054          38 :     parse_from_state_set_vals(s, entries, extra, vals);
    3055             : 
    3056          38 :     smartlist_free(entries);
    3057          38 :     strmap_free(vals, NULL);
    3058             :   }
    3059             : 
    3060          38 :   entry_guard_t *guard = tor_malloc_zero(sizeof(entry_guard_t));
    3061          38 :   guard->is_persistent = 1;
    3062             : 
    3063          38 :   if (in == NULL) {
    3064           3 :     log_warn(LD_CIRC, "Guard missing 'in' field");
    3065           3 :     goto err;
    3066             :   }
    3067             : 
    3068          35 :   guard->selection_name = in;
    3069          35 :   in = NULL;
    3070             : 
    3071          35 :   if (rsa_id == NULL) {
    3072           1 :     log_warn(LD_CIRC, "Guard missing RSA ID field");
    3073           1 :     goto err;
    3074             :   }
    3075             : 
    3076             :   /* Process the identity and nickname. */
    3077          34 :   if (base16_decode(guard->identity, sizeof(guard->identity),
    3078             :                     rsa_id, strlen(rsa_id)) != DIGEST_LEN) {
    3079           3 :     log_warn(LD_CIRC, "Unable to decode guard identity %s", escaped(rsa_id));
    3080           3 :     goto err;
    3081             :   }
    3082             : 
    3083          31 :   if (nickname) {
    3084          24 :     strlcpy(guard->nickname, nickname, sizeof(guard->nickname));
    3085             :   } else {
    3086           7 :     guard->nickname[0]='$';
    3087           7 :     base16_encode(guard->nickname+1, sizeof(guard->nickname)-1,
    3088             :                   guard->identity, DIGEST_LEN);
    3089             :   }
    3090             : 
    3091          31 :   if (bridge_addr) {
    3092           8 :     tor_addr_port_t res;
    3093           8 :     memset(&res, 0, sizeof(res));
    3094           8 :     int r = tor_addr_port_parse(LOG_WARN, bridge_addr,
    3095             :                                 &res.addr, &res.port, -1);
    3096           8 :     if (r == 0)
    3097           7 :       guard->bridge_addr = tor_memdup(&res, sizeof(res));
    3098             :     /* On error, we already warned. */
    3099             :   }
    3100             : 
    3101             :   /* Process the various time fields. */
    3102          31 :   parse_from_state_handle_time(guard, sampled_on, unlisted_since,
    3103             :       confirmed_on);
    3104             : 
    3105             :   /* Take sampled_by_version verbatim. */
    3106          31 :   guard->sampled_by_version = sampled_by;
    3107          31 :   sampled_by = NULL; /* prevent free */
    3108             :   /* Listed is a boolean */
    3109          31 :   if (listed && strcmp(listed, "0"))
    3110          29 :     guard->currently_listed = 1;
    3111             : 
    3112             :   /* The index is a nonnegative integer. */
    3113          31 :   guard->confirmed_idx = -1;
    3114          31 :   if (confirmed_idx) {
    3115          13 :     int ok=1;
    3116          13 :     long idx = tor_parse_long(confirmed_idx, 10, 0, INT_MAX, &ok, NULL);
    3117          13 :     if (! ok) {
    3118           1 :       log_warn(LD_GUARD, "Guard has invalid confirmed_idx %s",
    3119             :                escaped(confirmed_idx));
    3120             :     } else {
    3121          12 :       guard->confirmed_idx = (int)idx;
    3122             :     }
    3123             :   }
    3124             : 
    3125          31 :   if (sampled_idx) {
    3126          24 :     int ok = 1;
    3127          24 :     long idx = tor_parse_long(sampled_idx, 10, 0, INT_MAX, &ok, NULL);
    3128          24 :     if (!ok) {
    3129           0 :       log_warn(LD_GUARD, "Guard has invalid sampled_idx %s",
    3130             :           escaped(sampled_idx));
    3131             :       /* set it to a idx higher than the max sample size */
    3132           0 :       guard->sampled_idx = invalid_sampled_idx++;
    3133             :     } else {
    3134          24 :       guard->sampled_idx = (int)idx;
    3135             :     }
    3136           7 :   } else if (confirmed_idx) {
    3137             :     /* This state has been written by an older Tor version which did not have
    3138             :      * sample ordering  */
    3139             : 
    3140           4 :     guard->sampled_idx = guard->confirmed_idx;
    3141             :   } else {
    3142           3 :     log_info(LD_GUARD, "The state file seems to be into a status that could"
    3143             :              " yield to weird entry node selection: we're missing both a"
    3144             :              " sampled_idx and a confirmed_idx.");
    3145           3 :     guard->sampled_idx = invalid_sampled_idx++;
    3146             :   }
    3147             : 
    3148             :   /* Anything we didn't recognize gets crammed together */
    3149          31 :   if (smartlist_len(extra) > 0) {
    3150           2 :     guard->extra_state_fields = smartlist_join_strings(extra, " ", 0, NULL);
    3151             :   }
    3152             : 
    3153             :   /* initialize non-persistent fields */
    3154          31 :   guard->is_reachable = GUARD_REACHABLE_MAYBE;
    3155             : 
    3156             : #define PB_FIELD(field)                                                 \
    3157             :   do {                                                                  \
    3158             :     if (pb_ ## field) {                                                 \
    3159             :       int ok = 1;                                                       \
    3160             :       double r = tor_parse_double(pb_ ## field, 0.0, 1e9, &ok, NULL);   \
    3161             :       if (! ok) {                                                       \
    3162             :         log_warn(LD_CIRC, "Guard has invalid pb_%s %s",                 \
    3163             :                  #field, pb_ ## field);                                 \
    3164             :       } else {                                                          \
    3165             :         guard->pb.field = r;                                            \
    3166             :       }                                                                 \
    3167             :     }                                                                   \
    3168             :   } while (0)
    3169          31 :   PB_FIELD(use_attempts);
    3170          31 :   PB_FIELD(use_successes);
    3171          31 :   PB_FIELD(circ_attempts);
    3172          31 :   PB_FIELD(circ_successes);
    3173          31 :   PB_FIELD(successful_circuits_closed);
    3174          31 :   PB_FIELD(collapsed_circuits);
    3175          31 :   PB_FIELD(unusable_circuits);
    3176          31 :   PB_FIELD(timeouts);
    3177             : #undef PB_FIELD
    3178             : 
    3179          31 :   pathbias_check_use_success_count(guard);
    3180          31 :   pathbias_check_close_success_count(guard);
    3181             : 
    3182             :   /* We update everything on this guard later, after we've parsed
    3183             :    * everything.  */
    3184             : 
    3185          31 :   goto done;
    3186             : 
    3187           7 :  err:
    3188             :   // only consider it an error if the guard state was totally unparseable.
    3189           7 :   entry_guard_free(guard);
    3190           7 :   guard = NULL;
    3191             : 
    3192          38 :  done:
    3193          38 :   tor_free(in);
    3194          38 :   tor_free(rsa_id);
    3195          38 :   tor_free(nickname);
    3196          38 :   tor_free(sampled_on);
    3197          38 :   tor_free(sampled_by);
    3198          38 :   tor_free(unlisted_since);
    3199          38 :   tor_free(listed);
    3200          38 :   tor_free(confirmed_on);
    3201          38 :   tor_free(confirmed_idx);
    3202          38 :   tor_free(sampled_idx);
    3203          38 :   tor_free(bridge_addr);
    3204          38 :   tor_free(pb_use_attempts);
    3205          38 :   tor_free(pb_use_successes);
    3206          38 :   tor_free(pb_circ_attempts);
    3207          38 :   tor_free(pb_circ_successes);
    3208          38 :   tor_free(pb_successful_circuits_closed);
    3209          38 :   tor_free(pb_collapsed_circuits);
    3210          38 :   tor_free(pb_unusable_circuits);
    3211          38 :   tor_free(pb_timeouts);
    3212             : 
    3213          58 :   SMARTLIST_FOREACH(extra, char *, cp, tor_free(cp));
    3214          38 :   smartlist_free(extra);
    3215             : 
    3216          38 :   return guard;
    3217             : }
    3218             : 
    3219             : /**
    3220             :  * Replace the Guards entries in <b>state</b> with a list of all our sampled
    3221             :  * guards.
    3222             :  */
    3223             : static void
    3224           5 : entry_guards_update_guards_in_state(or_state_t *state)
    3225             : {
    3226           5 :   if (!guard_contexts)
    3227           0 :     return;
    3228           5 :   config_line_t *lines = NULL;
    3229           5 :   config_line_t **nextline = &lines;
    3230             : 
    3231           8 :   SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
    3232           3 :     int i = 0;
    3233          11 :     SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    3234           8 :       if (guard->is_persistent == 0)
    3235           1 :         continue;
    3236           7 :       *nextline = tor_malloc_zero(sizeof(config_line_t));
    3237           7 :       (*nextline)->key = tor_strdup("Guard");
    3238           7 :       (*nextline)->value = entry_guard_encode_for_state(guard, i);
    3239           7 :       nextline = &(*nextline)->next;
    3240           7 :       i++;
    3241           8 :     } SMARTLIST_FOREACH_END(guard);
    3242           3 :   } SMARTLIST_FOREACH_END(gs);
    3243             : 
    3244           5 :   config_free_lines(state->Guard);
    3245           5 :   state->Guard = lines;
    3246             : }
    3247             : 
    3248             : /**
    3249             :  * Replace our sampled guards from the Guards entries in <b>state</b>. Return 0
    3250             :  * on success, -1 on failure. (If <b>set</b> is true, replace nothing -- only
    3251             :  * check whether replacing would work.)
    3252             :  */
    3253             : static int
    3254          17 : entry_guards_load_guards_from_state(or_state_t *state, int set)
    3255             : {
    3256          17 :   const config_line_t *line = state->Guard;
    3257          17 :   int n_errors = 0;
    3258             : 
    3259          17 :   if (!guard_contexts)
    3260           6 :     guard_contexts = smartlist_new();
    3261             : 
    3262             :   /* Wipe all our existing guard info. (we shouldn't have any, but
    3263             :    * let's be safe.) */
    3264          17 :   if (set) {
    3265          10 :     SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
    3266           3 :       guard_selection_free(gs);
    3267           3 :       if (curr_guard_context == gs)
    3268           3 :         curr_guard_context = NULL;
    3269           3 :       SMARTLIST_DEL_CURRENT(guard_contexts, gs);
    3270           3 :     } SMARTLIST_FOREACH_END(gs);
    3271             :   }
    3272             : 
    3273          47 :   for ( ; line != NULL; line = line->next) {
    3274          30 :     entry_guard_t *guard = entry_guard_parse_from_state(line->value);
    3275          30 :     if (guard == NULL) {
    3276           2 :       ++n_errors;
    3277          30 :       continue;
    3278             :     }
    3279          28 :     tor_assert(guard->selection_name);
    3280          28 :     if (!strcmp(guard->selection_name, "legacy")) {
    3281           2 :       ++n_errors;
    3282           2 :       entry_guard_free(guard);
    3283           2 :       continue;
    3284             :     }
    3285             : 
    3286          26 :     if (set) {
    3287          17 :       guard_selection_t *gs;
    3288          17 :       gs = get_guard_selection_by_name(guard->selection_name,
    3289             :                                        GS_TYPE_INFER, 1);
    3290          17 :       tor_assert(gs);
    3291          17 :       smartlist_add(gs->sampled_entry_guards, guard);
    3292          17 :       guard->in_selection = gs;
    3293             :       /* Recompute the next_sampled_id from the state. We do not assume that
    3294             :        * sampled guards appear in the correct order within the file, and we
    3295             :        * need to know what would be the next sampled idx to give to any
    3296             :        * new sampled guard (i.e., max of guard->sampled_idx + 1)*/
    3297          17 :       if (gs->next_sampled_idx <= guard->sampled_idx) {
    3298          17 :         gs->next_sampled_idx = guard->sampled_idx + 1;
    3299             :       }
    3300             : 
    3301             :     } else {
    3302           9 :       entry_guard_free(guard);
    3303             :     }
    3304             :   }
    3305             : 
    3306          17 :   if (set) {
    3307          14 :     SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
    3308             :       /** Guards should be in sample order within the file, but it is maybe
    3309             :        * better NOT to assume that. Let's order them before updating lists
    3310             :        */
    3311           7 :       smartlist_sort(gs->sampled_entry_guards, compare_guards_by_sampled_idx);
    3312           7 :       entry_guards_update_all(gs);
    3313           7 :     } SMARTLIST_FOREACH_END(gs);
    3314             :   }
    3315          17 :   return n_errors ? -1 : 0;
    3316             : }
    3317             : 
    3318             : /** If <b>digest</b> matches the identity of any node in the
    3319             :  * entry_guards list for the provided guard selection state,
    3320             :  return that node. Else return NULL. */
    3321             : entry_guard_t *
    3322           0 : entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
    3323             :                                                  const char *digest)
    3324             : {
    3325           0 :   return get_sampled_guard_with_id(gs, (const uint8_t*)digest);
    3326             : }
    3327             : 
    3328             : /** Return the node_t associated with a single entry_guard_t. May
    3329             :  * return NULL if the guard is not currently in the consensus. */
    3330             : const node_t *
    3331           0 : entry_guard_find_node(const entry_guard_t *guard)
    3332             : {
    3333           0 :   tor_assert(guard);
    3334           0 :   return node_get_by_id(guard->identity);
    3335             : }
    3336             : 
    3337             : /** If <b>digest</b> matches the identity of any node in the
    3338             :  * entry_guards list for the default guard selection state,
    3339             :  return that node. Else return NULL. */
    3340             : entry_guard_t *
    3341           0 : entry_guard_get_by_id_digest(const char *digest)
    3342             : {
    3343           0 :   return entry_guard_get_by_id_digest_for_guard_selection(
    3344             :       get_guard_selection_info(), digest);
    3345             : }
    3346             : 
    3347             : /** We are about to connect to bridge with identity <b>digest</b> to fetch its
    3348             :  *  descriptor. Create a new guard state for this connection and return it. */
    3349             : circuit_guard_state_t *
    3350           0 : get_guard_state_for_bridge_desc_fetch(const char *digest)
    3351             : {
    3352           0 :   circuit_guard_state_t *guard_state = NULL;
    3353           0 :   entry_guard_t *guard = NULL;
    3354             : 
    3355           0 :   guard = entry_guard_get_by_id_digest_for_guard_selection(
    3356             :                                     get_guard_selection_info(), digest);
    3357           0 :   if (!guard) {
    3358             :     return NULL;
    3359             :   }
    3360             : 
    3361             :   /* Update the guard last_tried_to_connect time since it's checked by the
    3362             :    * guard subsystem. */
    3363           0 :   guard->last_tried_to_connect = approx_time();
    3364             : 
    3365             :   /* Create the guard state */
    3366           0 :   guard_state = circuit_guard_state_new(guard,
    3367             :                                         GUARD_CIRC_STATE_USABLE_ON_COMPLETION,
    3368             :                                         NULL);
    3369             : 
    3370           0 :   return guard_state;
    3371             : }
    3372             : 
    3373             : /** Release all storage held by <b>e</b>. */
    3374             : STATIC void
    3375        1724 : entry_guard_free_(entry_guard_t *e)
    3376             : {
    3377        1724 :   if (!e)
    3378             :     return;
    3379        1723 :   entry_guard_handles_clear(e);
    3380        1723 :   tor_free(e->sampled_by_version);
    3381        1723 :   tor_free(e->extra_state_fields);
    3382        1723 :   tor_free(e->selection_name);
    3383        1723 :   tor_free(e->bridge_addr);
    3384        1723 :   tor_free(e);
    3385             : }
    3386             : 
    3387             : /** Return 0 if we're fine adding arbitrary routers out of the
    3388             :  * directory to our entry guard list, or return 1 if we have a
    3389             :  * list already and we must stick to it.
    3390             :  */
    3391             : int
    3392           3 : entry_list_is_constrained(const or_options_t *options)
    3393             : {
    3394             :   // XXXX #21425 look at the current selection.
    3395           3 :   if (options->EntryNodes)
    3396             :     return 1;
    3397           3 :   if (options->UseBridges)
    3398           0 :     return 1;
    3399             :   return 0;
    3400             : }
    3401             : 
    3402             : /** Return the number of bridges that have descriptors that are marked with
    3403             :  * purpose 'bridge' and are running. If use_maybe_reachable is
    3404             :  * true, include bridges that might be reachable in the count.
    3405             :  * Otherwise, if it is false, only include bridges that have recently been
    3406             :  * found running in the count.
    3407             :  *
    3408             :  * We use this function to decide if we're ready to start building
    3409             :  * circuits through our bridges, or if we need to wait until the
    3410             :  * directory "server/authority" requests finish. */
    3411           0 : MOCK_IMPL(int,
    3412             : num_bridges_usable,(int use_maybe_reachable))
    3413             : {
    3414           0 :   int n_options = 0;
    3415             : 
    3416           0 :   if (BUG(!get_options()->UseBridges)) {
    3417           0 :     return 0;
    3418             :   }
    3419           0 :   guard_selection_t *gs  = get_guard_selection_info();
    3420           0 :   if (BUG(gs->type != GS_TYPE_BRIDGE)) {
    3421           0 :     return 0;
    3422             :   }
    3423             : 
    3424           0 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {
    3425             :     /* Not a bridge, or not one we are configured to be able to use. */
    3426           0 :     if (! guard->is_filtered_guard)
    3427           0 :       continue;
    3428             :     /* Definitely not usable */
    3429           0 :     if (guard->is_reachable == GUARD_REACHABLE_NO)
    3430           0 :       continue;
    3431             :     /* If we want to be really sure the bridges will work, skip maybes */
    3432           0 :     if (!use_maybe_reachable && guard->is_reachable == GUARD_REACHABLE_MAYBE)
    3433           0 :       continue;
    3434           0 :     if (tor_digest_is_zero(guard->identity))
    3435           0 :       continue;
    3436           0 :     const node_t *node = node_get_by_id(guard->identity);
    3437           0 :     if (node && node->ri)
    3438           0 :       ++n_options;
    3439           0 :   } SMARTLIST_FOREACH_END(guard);
    3440             : 
    3441             :   return n_options;
    3442             : }
    3443             : 
    3444             : /** Check the pathbias use success count of <b>node</b> and disable it if it
    3445             :  *  goes over our thresholds. */
    3446             : static void
    3447          31 : pathbias_check_use_success_count(entry_guard_t *node)
    3448             : {
    3449          31 :   const or_options_t *options = get_options();
    3450          31 :   const double EPSILON = 1.0e-9;
    3451             : 
    3452             :   /* Note: We rely on the < comparison here to allow us to set a 0
    3453             :    * rate and disable the feature entirely. If refactoring, don't
    3454             :    * change to <= */
    3455          31 :   if (node->pb.use_attempts > EPSILON &&
    3456           0 :       pathbias_get_use_success_count(node)/node->pb.use_attempts
    3457           0 :       < pathbias_get_extreme_use_rate(options) &&
    3458           0 :       pathbias_get_dropguards(options)) {
    3459           0 :     node->pb.path_bias_disabled = 1;
    3460           0 :     log_info(LD_GENERAL,
    3461             :              "Path use bias is too high (%f/%f); disabling node %s",
    3462             :              node->pb.circ_successes, node->pb.circ_attempts,
    3463             :              node->nickname);
    3464             :   }
    3465          31 : }
    3466             : 
    3467             : /** Check the pathbias close count of <b>node</b> and disable it if it goes
    3468             :  *  over our thresholds. */
    3469             : static void
    3470          31 : pathbias_check_close_success_count(entry_guard_t *node)
    3471             : {
    3472          31 :   const or_options_t *options = get_options();
    3473          31 :   const double EPSILON = 1.0e-9;
    3474             : 
    3475             :   /* Note: We rely on the < comparison here to allow us to set a 0
    3476             :    * rate and disable the feature entirely. If refactoring, don't
    3477             :    * change to <= */
    3478          42 :   if (node->pb.circ_attempts > EPSILON &&
    3479          11 :       pathbias_get_close_success_count(node)/node->pb.circ_attempts
    3480          11 :       < pathbias_get_extreme_rate(options) &&
    3481           0 :       pathbias_get_dropguards(options)) {
    3482           0 :     node->pb.path_bias_disabled = 1;
    3483           0 :     log_info(LD_GENERAL,
    3484             :              "Path bias is too high (%f/%f); disabling node %s",
    3485             :              node->pb.circ_successes, node->pb.circ_attempts,
    3486             :              node->nickname);
    3487             :   }
    3488          31 : }
    3489             : 
    3490             : /** Parse <b>state</b> and learn about the entry guards it describes.
    3491             :  * If <b>set</b> is true, and there are no errors, replace the guard
    3492             :  * list in the default guard selection context with what we find.
    3493             :  * On success, return 0. On failure, alloc into *<b>msg</b> a string
    3494             :  * describing the error, and return -1.
    3495             :  */
    3496             : int
    3497          17 : entry_guards_parse_state(or_state_t *state, int set, char **msg)
    3498             : {
    3499          17 :   entry_guards_dirty = 0;
    3500          17 :   int r1 = entry_guards_load_guards_from_state(state, set);
    3501          17 :   entry_guards_dirty = 0;
    3502             : 
    3503          17 :   if (r1 < 0) {
    3504           2 :     if (msg && *msg == NULL) {
    3505           2 :       *msg = tor_strdup("parsing error");
    3506             :     }
    3507           2 :     return -1;
    3508             :   }
    3509             :   return 0;
    3510             : }
    3511             : 
    3512             : /** How long will we let a change in our guard nodes stay un-saved
    3513             :  * when we are trying to avoid disk writes? */
    3514             : #define SLOW_GUARD_STATE_FLUSH_TIME 600
    3515             : /** How long will we let a change in our guard nodes stay un-saved
    3516             :  * when we are not trying to avoid disk writes? */
    3517             : #define FAST_GUARD_STATE_FLUSH_TIME 30
    3518             : 
    3519             : /** Our list of entry guards has changed for a particular guard selection
    3520             :  * context, or some element of one of our entry guards has changed for one.
    3521             :  * Write the changes to disk within the next few minutes.
    3522             :  */
    3523             : void
    3524        2113 : entry_guards_changed_for_guard_selection(guard_selection_t *gs)
    3525             : {
    3526        2113 :   time_t when;
    3527             : 
    3528        2113 :   tor_assert(gs != NULL);
    3529             : 
    3530        2113 :   entry_guards_dirty = 1;
    3531             : 
    3532        2113 :   if (get_options()->AvoidDiskWrites)
    3533           0 :     when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
    3534             :   else
    3535        2113 :     when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
    3536             : 
    3537             :   /* or_state_save() will call entry_guards_update_state() and
    3538             :      entry_guards_update_guards_in_state()
    3539             :   */
    3540        2113 :   or_state_mark_dirty(get_or_state(), when);
    3541        2113 : }
    3542             : 
    3543             : /** Our list of entry guards has changed for the default guard selection
    3544             :  * context, or some element of one of our entry guards has changed. Write
    3545             :  * the changes to disk within the next few minutes.
    3546             :  */
    3547             : void
    3548           0 : entry_guards_changed(void)
    3549             : {
    3550           0 :   entry_guards_changed_for_guard_selection(get_guard_selection_info());
    3551           0 : }
    3552             : 
    3553             : /** If the entry guard info has not changed, do nothing and return.
    3554             :  * Otherwise, free the EntryGuards piece of <b>state</b> and create
    3555             :  * a new one out of the global entry_guards list, and then mark
    3556             :  * <b>state</b> dirty so it will get saved to disk.
    3557             :  */
    3558             : void
    3559           5 : entry_guards_update_state(or_state_t *state)
    3560             : {
    3561           5 :   entry_guards_dirty = 0;
    3562             : 
    3563             :   // Handles all guard info.
    3564           5 :   entry_guards_update_guards_in_state(state);
    3565             : 
    3566           5 :   entry_guards_dirty = 0;
    3567             : 
    3568           5 :   if (!get_options()->AvoidDiskWrites)
    3569           5 :     or_state_mark_dirty(get_or_state(), 0);
    3570           5 :   entry_guards_dirty = 0;
    3571           5 : }
    3572             : 
    3573             : /** Return true iff the circuit's guard can succeed, that is, can be used. */
    3574             : int
    3575           0 : entry_guard_could_succeed(const circuit_guard_state_t *guard_state)
    3576             : {
    3577           0 :   if (get_options()->UseEntryGuards == 0) {
    3578             :     /* we're fine with this circuit's first hop, because we're not
    3579             :      * configured to use entry guards. */
    3580             :     return 1;
    3581             :   }
    3582             : 
    3583           0 :   if (!guard_state) {
    3584             :     return 0;
    3585             :   }
    3586             : 
    3587           0 :   entry_guard_t *guard = entry_guard_handle_get(guard_state->guard);
    3588           0 :   if (!guard || BUG(guard->in_selection == NULL)) {
    3589           0 :     return 0;
    3590             :   }
    3591             : 
    3592             :   return 1;
    3593             : }
    3594             : 
    3595             : /**
    3596             :  * Format a single entry guard in the format expected by the controller.
    3597             :  * Return a newly allocated string.
    3598             :  */
    3599             : STATIC char *
    3600           0 : getinfo_helper_format_single_entry_guard(const entry_guard_t *e)
    3601             : {
    3602           0 :   const char *status = NULL;
    3603           0 :   time_t when = 0;
    3604           0 :   const node_t *node;
    3605           0 :   char tbuf[ISO_TIME_LEN+1];
    3606           0 :   char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
    3607             : 
    3608             :   /* This is going to be a bit tricky, since the status
    3609             :    * codes weren't really intended for prop271 guards.
    3610             :    *
    3611             :    * XXXX use a more appropriate format for exporting this information
    3612             :    */
    3613           0 :   if (e->confirmed_idx < 0) {
    3614             :     status = "never-connected";
    3615           0 :   } else if (! e->currently_listed) {
    3616           0 :     when = e->unlisted_since_date;
    3617           0 :     status = "unusable";
    3618           0 :   } else if (! e->is_filtered_guard) {
    3619             :     status = "unusable";
    3620           0 :   } else if (e->is_reachable == GUARD_REACHABLE_NO) {
    3621           0 :     when = e->failing_since;
    3622           0 :     status = "down";
    3623             :   } else {
    3624             :     status = "up";
    3625             :   }
    3626             : 
    3627           0 :   node = entry_guard_find_node(e);
    3628           0 :   if (node) {
    3629           0 :     node_get_verbose_nickname(node, nbuf);
    3630             :   } else {
    3631           0 :     nbuf[0] = '$';
    3632           0 :     base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
    3633             :     /* e->nickname field is not very reliable if we don't know about
    3634             :      * this router any longer; don't include it. */
    3635             :   }
    3636             : 
    3637           0 :   char *result = NULL;
    3638           0 :   if (when) {
    3639           0 :     format_iso_time(tbuf, when);
    3640           0 :     tor_asprintf(&result, "%s %s %s\n", nbuf, status, tbuf);
    3641             :   } else {
    3642           0 :     tor_asprintf(&result, "%s %s\n", nbuf, status);
    3643             :   }
    3644           0 :   return result;
    3645             : }
    3646             : 
    3647             : /** If <b>question</b> is the string "entry-guards", then dump
    3648             :  * to *<b>answer</b> a newly allocated string describing all of
    3649             :  * the nodes in the global entry_guards list. See control-spec.txt
    3650             :  * for details.
    3651             :  * For backward compatibility, we also handle the string "helper-nodes".
    3652             :  *
    3653             :  * XXX this should be totally redesigned after prop 271 too, and that's
    3654             :  * going to take some control spec work.
    3655             :  * */
    3656             : int
    3657           0 : getinfo_helper_entry_guards(control_connection_t *conn,
    3658             :                             const char *question, char **answer,
    3659             :                             const char **errmsg)
    3660             : {
    3661           0 :   guard_selection_t *gs = get_guard_selection_info();
    3662             : 
    3663           0 :   tor_assert(gs != NULL);
    3664             : 
    3665           0 :   (void) conn;
    3666           0 :   (void) errmsg;
    3667             : 
    3668           0 :   if (!strcmp(question,"entry-guards") ||
    3669           0 :       !strcmp(question,"helper-nodes")) {
    3670           0 :     const smartlist_t *guards;
    3671           0 :     guards = gs->sampled_entry_guards;
    3672             : 
    3673           0 :     smartlist_t *sl = smartlist_new();
    3674             : 
    3675           0 :     SMARTLIST_FOREACH_BEGIN(guards, const entry_guard_t *, e) {
    3676           0 :       char *cp = getinfo_helper_format_single_entry_guard(e);
    3677           0 :       smartlist_add(sl, cp);
    3678           0 :     } SMARTLIST_FOREACH_END(e);
    3679           0 :     *answer = smartlist_join_strings(sl, "", 0, NULL);
    3680           0 :     SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
    3681           0 :     smartlist_free(sl);
    3682             :   }
    3683           0 :   return 0;
    3684             : }
    3685             : 
    3686             : /* Given the original bandwidth of a guard and its guardfraction,
    3687             :  * calculate how much bandwidth the guard should have as a guard and
    3688             :  * as a non-guard.
    3689             :  *
    3690             :  * Quoting from proposal236:
    3691             :  *
    3692             :  *   Let Wpf denote the weight from the 'bandwidth-weights' line a
    3693             :  *   client would apply to N for position p if it had the guard
    3694             :  *   flag, Wpn the weight if it did not have the guard flag, and B the
    3695             :  *   measured bandwidth of N in the consensus.  Then instead of choosing
    3696             :  *   N for position p proportionally to Wpf*B or Wpn*B, clients should
    3697             :  *   choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
    3698             :  *
    3699             :  * This function fills the <b>guardfraction_bw</b> structure. It sets
    3700             :  * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
    3701             :  */
    3702             : void
    3703         872 : guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
    3704             :                                   int orig_bandwidth,
    3705             :                                   uint32_t guardfraction_percentage)
    3706             : {
    3707         872 :   double guardfraction_fraction;
    3708             : 
    3709             :   /* Turn the percentage into a fraction. */
    3710         872 :   tor_assert(guardfraction_percentage <= 100);
    3711         872 :   guardfraction_fraction = guardfraction_percentage / 100.0;
    3712             : 
    3713         872 :   long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
    3714         872 :   tor_assert(guard_bw <= INT_MAX);
    3715             : 
    3716         872 :   guardfraction_bw->guard_bw = (int) guard_bw;
    3717             : 
    3718         872 :   guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
    3719         872 : }
    3720             : 
    3721             : /** Helper: Update the status of all entry guards, in whatever algorithm
    3722             :  * is used. Return true if we should stop using all previously generated
    3723             :  * circuits, by calling circuit_mark_all_unused_circs() and
    3724             :  * circuit_mark_all_dirty_circs_as_unusable().
    3725             :  */
    3726             : int
    3727           2 : guards_update_all(void)
    3728             : {
    3729           2 :   int mark_circuits = 0;
    3730           2 :   if (update_guard_selection_choice(get_options()))
    3731           1 :     mark_circuits = 1;
    3732             : 
    3733           2 :   tor_assert(curr_guard_context);
    3734             : 
    3735           2 :   if (entry_guards_update_all(curr_guard_context))
    3736           0 :     mark_circuits = 1;
    3737             : 
    3738           2 :   return mark_circuits;
    3739             : }
    3740             : 
    3741             : /** Helper: pick a guard for a circuit, with whatever algorithm is
    3742             :     used. */
    3743             : const node_t *
    3744           6 : guards_choose_guard(cpath_build_state_t *state,
    3745             :                     uint8_t purpose,
    3746             :                     circuit_guard_state_t **guard_state_out)
    3747             : {
    3748           6 :   const node_t *r = NULL;
    3749           6 :   const uint8_t *exit_id = NULL;
    3750           6 :   entry_guard_restriction_t *rst = NULL;
    3751             : 
    3752             :   /* Only apply restrictions if we have a specific exit node in mind, and only
    3753             :    * if we are not doing vanguard circuits: we don't want to apply guard
    3754             :    * restrictions to vanguard circuits. */
    3755           6 :   if (state && !circuit_should_use_vanguards(purpose) &&
    3756           3 :       (exit_id = build_state_get_exit_rsa_id(state))) {
    3757             :     /* We're building to a targeted exit node, so that node can't be
    3758             :      * chosen as our guard for this circuit.  Remember that fact in a
    3759             :      * restriction. */
    3760           3 :     rst = guard_create_exit_restriction(exit_id);
    3761           3 :     tor_assert(rst);
    3762             :   }
    3763           6 :   if (entry_guard_pick_for_circuit(get_guard_selection_info(),
    3764             :                                    GUARD_USAGE_TRAFFIC,
    3765             :                                    rst,
    3766             :                                    &r,
    3767             :                                    guard_state_out) < 0) {
    3768           0 :     tor_assert(r == NULL);
    3769             :   }
    3770           6 :   return r;
    3771             : }
    3772             : 
    3773             : /** Remove all currently listed entry guards for a given guard selection
    3774             :  * context.  This frees and replaces <b>gs</b>, so don't use <b>gs</b>
    3775             :  * after calling this function. */
    3776             : void
    3777           3 : remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
    3778             : {
    3779             :   // This function shouldn't exist. XXXX
    3780           3 :   tor_assert(gs != NULL);
    3781           3 :   char *old_name = tor_strdup(gs->name);
    3782           3 :   guard_selection_type_t old_type = gs->type;
    3783             : 
    3784          63 :   SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, entry, {
    3785             :     control_event_guard(entry->nickname, entry->identity, "DROPPED");
    3786             :   });
    3787             : 
    3788           3 :   if (gs == curr_guard_context) {
    3789           3 :     curr_guard_context = NULL;
    3790             :   }
    3791             : 
    3792           3 :   smartlist_remove(guard_contexts, gs);
    3793           3 :   guard_selection_free(gs);
    3794             : 
    3795           3 :   gs = get_guard_selection_by_name(old_name, old_type, 1);
    3796           3 :   entry_guards_changed_for_guard_selection(gs);
    3797           3 :   tor_free(old_name);
    3798           3 : }
    3799             : 
    3800             : /** Remove all currently listed entry guards, so new ones will be chosen.
    3801             :  *
    3802             :  * XXXX This function shouldn't exist -- it's meant to support the DROPGUARDS
    3803             :  * command, which is deprecated.
    3804             :  */
    3805             : void
    3806           0 : remove_all_entry_guards(void)
    3807             : {
    3808           0 :   remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
    3809           0 : }
    3810             : 
    3811             : /** Helper: pick a directory guard, with whatever algorithm is used. */
    3812             : const node_t *
    3813           4 : guards_choose_dirguard(uint8_t dir_purpose,
    3814             :                        circuit_guard_state_t **guard_state_out)
    3815             : {
    3816           4 :   const node_t *r = NULL;
    3817           4 :   entry_guard_restriction_t *rst = NULL;
    3818             : 
    3819             :   /* If we are fetching microdescs, don't query outdated dirservers. */
    3820           4 :   if (dir_purpose == DIR_PURPOSE_FETCH_MICRODESC) {
    3821           4 :     rst = guard_create_dirserver_md_restriction();
    3822             :   }
    3823             : 
    3824           4 :   if (entry_guard_pick_for_circuit(get_guard_selection_info(),
    3825             :                                    GUARD_USAGE_DIRGUARD,
    3826             :                                    rst,
    3827             :                                    &r,
    3828             :                                    guard_state_out) < 0) {
    3829           0 :     tor_assert(r == NULL);
    3830             :   }
    3831           4 :   return r;
    3832             : }
    3833             : 
    3834             : /**
    3835             :  * If we're running with a constrained guard set, then maybe mark our guards
    3836             :  * usable.  Return 1 if we do; 0 if we don't.
    3837             :  */
    3838             : int
    3839           0 : guards_retry_optimistic(const or_options_t *options)
    3840             : {
    3841           0 :   if (! entry_list_is_constrained(options))
    3842             :     return 0;
    3843             : 
    3844           0 :   mark_primary_guards_maybe_reachable(get_guard_selection_info());
    3845             : 
    3846           0 :   return 1;
    3847             : }
    3848             : 
    3849             : /**
    3850             :  * Check if we are missing any crucial dirinfo for the guard subsystem to
    3851             :  * work. Return NULL if everything went well, otherwise return a newly
    3852             :  * allocated string with an informative error message. In the latter case, use
    3853             :  * the general descriptor information <b>using_mds</b>, <b>num_present</b> and
    3854             :  * <b>num_usable</b> to improve the error message. */
    3855             : char *
    3856           6 : guard_selection_get_err_str_if_dir_info_missing(guard_selection_t *gs,
    3857             :                                         int using_mds,
    3858             :                                         int num_present, int num_usable)
    3859             : {
    3860           6 :   if (!gs->primary_guards_up_to_date)
    3861           0 :     entry_guards_update_primary(gs);
    3862             : 
    3863           6 :   char *ret_str = NULL;
    3864           6 :   int n_missing_descriptors = 0;
    3865           6 :   int n_considered = 0;
    3866           6 :   int num_primary_to_check;
    3867             : 
    3868             :   /* We want to check for the descriptor of at least the first two primary
    3869             :    * guards in our list, since these are the guards that we typically use for
    3870             :    * circuits. */
    3871           6 :   num_primary_to_check = get_n_primary_guards_to_use(GUARD_USAGE_TRAFFIC);
    3872           6 :   num_primary_to_check++;
    3873             : 
    3874          12 :   SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards, entry_guard_t *, guard) {
    3875          12 :     entry_guard_consider_retry(guard);
    3876          12 :     if (guard->is_reachable == GUARD_REACHABLE_NO)
    3877           0 :       continue;
    3878          12 :     n_considered++;
    3879          12 :     if (!guard_has_descriptor(guard))
    3880           3 :       n_missing_descriptors++;
    3881          12 :     if (n_considered >= num_primary_to_check)
    3882             :       break;
    3883           6 :   } SMARTLIST_FOREACH_END(guard);
    3884             : 
    3885             :   /* If we are not missing any descriptors, return NULL. */
    3886           6 :   if (!n_missing_descriptors) {
    3887             :     return NULL;
    3888             :   }
    3889             : 
    3890             :   /* otherwise return a helpful error string */
    3891           3 :   tor_asprintf(&ret_str, "We're missing descriptors for %d/%d of our "
    3892             :                "primary entry guards (total %sdescriptors: %d/%d). "
    3893             :                "That's ok. We will try to fetch missing descriptors soon.",
    3894             :                n_missing_descriptors, num_primary_to_check,
    3895             :                using_mds?"micro":"", num_present, num_usable);
    3896             : 
    3897           3 :   return ret_str;
    3898             : }
    3899             : 
    3900             : /** As guard_selection_have_enough_dir_info_to_build_circuits, but uses
    3901             :  * the default guard selection. */
    3902             : char *
    3903           0 : entry_guards_get_err_str_if_dir_info_missing(int using_mds,
    3904             :                                      int num_present, int num_usable)
    3905             : {
    3906           0 :   return guard_selection_get_err_str_if_dir_info_missing(
    3907             :                                                  get_guard_selection_info(),
    3908             :                                                  using_mds,
    3909             :                                                  num_present, num_usable);
    3910             : }
    3911             : 
    3912             : /** Free one guard selection context */
    3913             : STATIC void
    3914          97 : guard_selection_free_(guard_selection_t *gs)
    3915             : {
    3916          97 :   if (!gs) return;
    3917             : 
    3918          97 :   tor_free(gs->name);
    3919             : 
    3920          97 :   if (gs->sampled_entry_guards) {
    3921        1787 :     SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, e,
    3922             :                       entry_guard_free(e));
    3923          97 :     smartlist_free(gs->sampled_entry_guards);
    3924          97 :     gs->sampled_entry_guards = NULL;
    3925             :   }
    3926             : 
    3927          97 :   smartlist_free(gs->confirmed_entry_guards);
    3928          97 :   smartlist_free(gs->primary_entry_guards);
    3929             : 
    3930          97 :   tor_free(gs);
    3931             : }
    3932             : 
    3933             : /** Release all storage held by the list of entry guards and related
    3934             :  * memory structs. */
    3935             : void
    3936         240 : entry_guards_free_all(void)
    3937             : {
    3938             :   /* Null out the default */
    3939         240 :   curr_guard_context = NULL;
    3940             :   /* Free all the guard contexts */
    3941         240 :   if (guard_contexts != NULL) {
    3942          10 :     SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
    3943           4 :       guard_selection_free(gs);
    3944           4 :     } SMARTLIST_FOREACH_END(gs);
    3945           6 :     smartlist_free(guard_contexts);
    3946           6 :     guard_contexts = NULL;
    3947             :   }
    3948         240 :   circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
    3949         240 : }

Generated by: LCOV version 1.14