LCOV - code coverage report
Current view: top level - test - test_entrynodes.c (source / functions) Hit Total Coverage
Test: lcov.info Lines: 1748 1748 100.0 %
Date: 2021-11-24 03:28:48 Functions: 64 64 100.0 %

          Line data    Source code
       1             : /* Copyright (c) 2014-2021, The Tor Project, Inc. */
       2             : /* See LICENSE for licensing information */
       3             : 
       4             : #include "orconfig.h"
       5             : 
       6             : #define CIRCUITLIST_PRIVATE
       7             : #define CIRCUITBUILD_PRIVATE
       8             : #define CONFIG_PRIVATE
       9             : #define STATEFILE_PRIVATE
      10             : #define ENTRYNODES_PRIVATE
      11             : #define ROUTERLIST_PRIVATE
      12             : #define DIRCLIENT_PRIVATE
      13             : 
      14             : #include "core/or/or.h"
      15             : #include "test/test.h"
      16             : 
      17             : #include "feature/client/bridges.h"
      18             : #include "core/or/circuitlist.h"
      19             : #include "core/or/circuitbuild.h"
      20             : #include "app/config/config.h"
      21             : #include "lib/confmgt/confmgt.h"
      22             : #include "lib/crypt_ops/crypto_rand.h"
      23             : #include "feature/dircommon/directory.h"
      24             : #include "feature/dirclient/dirclient.h"
      25             : #include "feature/client/entrynodes.h"
      26             : #include "feature/nodelist/nodelist.h"
      27             : #include "feature/nodelist/networkstatus.h"
      28             : #include "core/or/policies.h"
      29             : #include "feature/nodelist/routerlist.h"
      30             : #include "feature/nodelist/routerset.h"
      31             : #include "app/config/statefile.h"
      32             : 
      33             : #include "core/or/cpath_build_state_st.h"
      34             : #include "core/or/crypt_path_st.h"
      35             : #include "feature/dircommon/dir_connection_st.h"
      36             : #include "feature/nodelist/microdesc_st.h"
      37             : #include "feature/nodelist/networkstatus_st.h"
      38             : #include "feature/nodelist/node_st.h"
      39             : #include "core/or/origin_circuit_st.h"
      40             : #include "app/config/or_state_st.h"
      41             : #include "feature/nodelist/routerinfo_st.h"
      42             : #include "feature/nodelist/routerstatus_st.h"
      43             : 
      44             : #include "test/test_helpers.h"
      45             : #include "test/log_test_helpers.h"
      46             : 
      47             : #include "lib/container/bloomfilt.h"
      48             : #include "lib/encoding/confline.h"
      49             : 
      50             : /* TODO:
      51             :  * choose_random_entry() test with state set.
      52             :  *
      53             :  * parse_state() tests with more than one guards.
      54             :  *
      55             :  * More tests for set_from_config(): Multiple nodes, use fingerprints,
      56             :  *                                   use country codes.
      57             :  */
      58             : 
      59             : /** Dummy Tor state used in unittests. */
      60             : static or_state_t *dummy_state = NULL;
      61             : static or_state_t *
      62        2112 : get_or_state_replacement(void)
      63             : {
      64        2112 :   return dummy_state;
      65             : }
      66             : 
      67             : static networkstatus_t *dummy_consensus = NULL;
      68             : 
      69             : static smartlist_t *big_fake_net_nodes = NULL;
      70             : 
      71             : static const smartlist_t *
      72        3459 : bfn_mock_nodelist_get_list(void)
      73             : {
      74        3459 :   return big_fake_net_nodes;
      75             : }
      76             : 
      77             : static networkstatus_t *
      78         195 : bfn_mock_networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
      79             : {
      80         195 :   (void)now;
      81         195 :   (void)flavor;
      82         195 :   return dummy_consensus;
      83             : }
      84             : 
      85             : static const node_t *
      86        5019 : bfn_mock_node_get_by_id(const char *id)
      87             : {
      88      662538 :   SMARTLIST_FOREACH(big_fake_net_nodes, node_t *, n,
      89             :                     if (fast_memeq(n->identity, id, 20))
      90             :                       return n);
      91             : 
      92             :   return NULL;
      93             : }
      94             : 
      95             : /* Helper function to free a test node. */
      96             : static void
      97       26829 : test_node_free(node_t *n)
      98             : {
      99       26829 :   tor_free(n->rs);
     100       26829 :   tor_free(n->md->onion_curve25519_pkey);
     101       26829 :   short_policy_free(n->md->exit_policy);
     102       26829 :   tor_free(n->md);
     103       26829 :   tor_free(n);
     104       26829 : }
     105             : 
     106             : /* Unittest cleanup function: Cleanup the fake network. */
     107             : static int
     108          99 : big_fake_network_cleanup(const struct testcase_t *testcase, void *ptr)
     109             : {
     110          99 :   (void) testcase;
     111          99 :   (void) ptr;
     112             : 
     113          99 :   if (big_fake_net_nodes) {
     114       26157 :     SMARTLIST_FOREACH(big_fake_net_nodes, node_t *, n, {
     115             :       test_node_free(n);
     116             :     });
     117          99 :     smartlist_free(big_fake_net_nodes);
     118             :   }
     119             : 
     120          99 :   UNMOCK(nodelist_get_list);
     121          99 :   UNMOCK(node_get_by_id);
     122          99 :   UNMOCK(get_or_state);
     123          99 :   UNMOCK(networkstatus_get_reasonably_live_consensus);
     124          99 :   or_state_free(dummy_state);
     125          99 :   dummy_state = NULL;
     126          99 :   tor_free(dummy_consensus);
     127             : 
     128          99 :   return 1; /* NOP */
     129             : }
     130             : 
     131             : #define REASONABLY_FUTURE " reasonably-future"
     132             : #define REASONABLY_PAST " reasonably-past"
     133             : 
     134             : /* Unittest setup function: Setup a fake network. */
     135             : static void *
     136          99 : big_fake_network_setup(const struct testcase_t *testcase)
     137             : {
     138          99 :   int i;
     139             : 
     140             :   /* These are minimal node_t objects that only contain the aspects of node_t
     141             :    * that we need for entrynodes.c. */
     142          99 :   const int N_NODES = 271;
     143             : 
     144          99 :   const char *argument = testcase->setup_data;
     145          99 :   int reasonably_future_consensus = 0, reasonably_past_consensus = 0;
     146          99 :   if (argument) {
     147          75 :     reasonably_future_consensus = strstr(argument, REASONABLY_FUTURE) != NULL;
     148          75 :     reasonably_past_consensus = strstr(argument, REASONABLY_PAST) != NULL;
     149             :   }
     150             : 
     151          99 :   big_fake_net_nodes = smartlist_new();
     152       26928 :   for (i = 0; i < N_NODES; ++i) {
     153       26829 :     curve25519_secret_key_t curve25519_secret_key;
     154             : 
     155       26829 :     node_t *n = tor_malloc_zero(sizeof(node_t));
     156       26829 :     n->md = tor_malloc_zero(sizeof(microdesc_t));
     157             : 
     158             :     /* Generate curve25519 key for this node */
     159       53658 :     n->md->onion_curve25519_pkey =
     160       26829 :       tor_malloc_zero(sizeof(curve25519_public_key_t));
     161       26829 :     curve25519_secret_key_generate(&curve25519_secret_key, 0);
     162       26829 :     curve25519_public_key_generate(n->md->onion_curve25519_pkey,
     163             :                                    &curve25519_secret_key);
     164             : 
     165       26829 :     crypto_rand(n->identity, sizeof(n->identity));
     166       26829 :     n->rs = tor_malloc_zero(sizeof(routerstatus_t));
     167             : 
     168       26829 :     memcpy(n->rs->identity_digest, n->identity, DIGEST_LEN);
     169             : 
     170       26829 :     n->is_running = n->is_valid = n->is_fast = n->is_stable = 1;
     171             : 
     172             :     /* Note: all these guards have the same address, so you'll need to
     173             :      * disable EnforceDistinctSubnets when a restriction is applied. */
     174       26829 :     tor_addr_from_ipv4h(&n->rs->ipv4_addr, 0x04020202);
     175       26829 :     n->rs->ipv4_orport = 1234;
     176       26829 :     n->rs->is_v2_dir = 1;
     177       26829 :     n->rs->has_bandwidth = 1;
     178       26829 :     n->rs->bandwidth_kb = 30;
     179             : 
     180             :     /* Make a random nickname for each node */
     181             :     {
     182       26829 :       char nickname_binary[8];
     183       26829 :       crypto_rand(nickname_binary, sizeof(nickname_binary));
     184       26829 :       base32_encode(n->rs->nickname, sizeof(n->rs->nickname),
     185             :                     nickname_binary, sizeof(nickname_binary));
     186             :     }
     187             : 
     188             :     /* Call half of the nodes a possible guard. */
     189       26829 :     if (i % 2 == 0) {
     190       13464 :       n->is_possible_guard = 1;
     191       13464 :       n->rs->guardfraction_percentage = 100;
     192       13464 :       n->rs->has_guardfraction = 1;
     193       13464 :       n->rs->is_possible_guard = 1;
     194             :     }
     195             : 
     196             :     /* Make some of these nodes a possible exit */
     197       26829 :     if (i % 7 == 0) {
     198        3861 :       n->md->exit_policy = parse_short_policy("accept 443");
     199             :     }
     200             : 
     201       26829 :     n->nodelist_idx = smartlist_len(big_fake_net_nodes);
     202       26829 :     smartlist_add(big_fake_net_nodes, n);
     203             :   }
     204             : 
     205          99 :   dummy_state = or_state_new();
     206          99 :   dummy_consensus = tor_malloc_zero(sizeof(networkstatus_t));
     207          99 :   if (reasonably_future_consensus) {
     208             :     /* Make the dummy consensus valid in 6 hours, and expiring in 7 hours. */
     209          33 :     dummy_consensus->valid_after = approx_time() + 6*3600;
     210          33 :     dummy_consensus->valid_until = approx_time() + 7*3600;
     211          66 :   } else if (reasonably_past_consensus) {
     212             :     /* Make the dummy consensus valid from 16 hours ago, but expired 12 hours
     213             :      * ago. */
     214          33 :     dummy_consensus->valid_after = approx_time() - 16*3600;
     215          33 :     dummy_consensus->valid_until = approx_time() - 12*3600;
     216             :   } else {
     217             :     /* Make the dummy consensus valid for an hour either side of now. */
     218          33 :     dummy_consensus->valid_after = approx_time() - 3600;
     219          33 :     dummy_consensus->valid_until = approx_time() + 3600;
     220             :   }
     221             : 
     222          99 :   MOCK(nodelist_get_list, bfn_mock_nodelist_get_list);
     223          99 :   MOCK(node_get_by_id, bfn_mock_node_get_by_id);
     224          99 :   MOCK(get_or_state,
     225             :        get_or_state_replacement);
     226          99 :   MOCK(networkstatus_get_reasonably_live_consensus,
     227             :        bfn_mock_networkstatus_get_reasonably_live_consensus);
     228             :   /* Return anything but NULL (it's interpreted as test fail) */
     229          99 :   return (void*)testcase;
     230             : }
     231             : 
     232             : static time_t
     233         276 : mock_randomize_time_no_randomization(time_t a, time_t b)
     234             : {
     235         276 :   (void) b;
     236         276 :   return a;
     237             : }
     238             : 
     239             : static or_options_t *mocked_options;
     240             : 
     241             : static const or_options_t *
     242           6 : mock_get_options(void)
     243             : {
     244           6 :   return mocked_options;
     245             : }
     246             : 
     247             : #define TEST_IPV4_ADDR "123.45.67.89"
     248             : #define TEST_IPV6_ADDR "[1234:5678:90ab:cdef::]"
     249             : 
     250             : static void
     251           1 : test_node_preferred_orport(void *arg)
     252             : {
     253           1 :   (void)arg;
     254           1 :   tor_addr_t ipv4_addr;
     255           1 :   const uint16_t ipv4_port = 4444;
     256           1 :   tor_addr_t ipv6_addr;
     257           1 :   const uint16_t ipv6_port = 6666;
     258           1 :   routerinfo_t node_ri;
     259           1 :   node_t node;
     260           1 :   tor_addr_port_t ap;
     261             : 
     262             :   /* Setup options */
     263           1 :   mocked_options = options_new();
     264             :   /* We don't test ClientPreferIPv6ORPort here, because it's used in
     265             :    * nodelist_set_consensus to setup node.ipv6_preferred, which we set
     266             :    * directly. */
     267           1 :   MOCK(get_options, mock_get_options);
     268             : 
     269             :   /* Setup IP addresses */
     270           1 :   tor_addr_parse(&ipv4_addr, TEST_IPV4_ADDR);
     271           1 :   tor_addr_parse(&ipv6_addr, TEST_IPV6_ADDR);
     272             : 
     273             :   /* Setup node_ri */
     274           1 :   memset(&node_ri, 0, sizeof(node_ri));
     275           1 :   tor_addr_copy(&node_ri.ipv4_addr, &ipv4_addr);
     276           1 :   node_ri.ipv4_orport = ipv4_port;
     277           1 :   tor_addr_copy(&node_ri.ipv6_addr, &ipv6_addr);
     278           1 :   node_ri.ipv6_orport = ipv6_port;
     279             : 
     280             :   /* Setup node */
     281           1 :   memset(&node, 0, sizeof(node));
     282           1 :   node.ri = &node_ri;
     283             : 
     284             :   /* Check the preferred address is IPv4 if we're only using IPv4, regardless
     285             :    * of whether we prefer it or not */
     286           1 :   mocked_options->ClientUseIPv4 = 1;
     287           1 :   mocked_options->ClientUseIPv6 = 0;
     288           1 :   node.ipv6_preferred = 0;
     289           1 :   node_get_pref_orport(&node, &ap);
     290           1 :   tt_assert(tor_addr_eq(&ap.addr, &ipv4_addr));
     291           1 :   tt_assert(ap.port == ipv4_port);
     292             : 
     293           1 :   node.ipv6_preferred = 1;
     294           1 :   node_get_pref_orport(&node, &ap);
     295           1 :   tt_assert(tor_addr_eq(&ap.addr, &ipv4_addr));
     296           1 :   tt_assert(ap.port == ipv4_port);
     297             : 
     298             :   /* Check the preferred address is IPv4 if we're using IPv4 and IPv6, but
     299             :    * don't prefer the IPv6 address */
     300           1 :   mocked_options->ClientUseIPv4 = 1;
     301           1 :   mocked_options->ClientUseIPv6 = 1;
     302           1 :   node.ipv6_preferred = 0;
     303           1 :   node_get_pref_orport(&node, &ap);
     304           1 :   tt_assert(tor_addr_eq(&ap.addr, &ipv4_addr));
     305           1 :   tt_assert(ap.port == ipv4_port);
     306             : 
     307             :   /* Check the preferred address is IPv6 if we prefer it and
     308             :    * ClientUseIPv6 is 1, regardless of ClientUseIPv4 */
     309           1 :   mocked_options->ClientUseIPv4 = 1;
     310           1 :   mocked_options->ClientUseIPv6 = 1;
     311           1 :   node.ipv6_preferred = 1;
     312           1 :   node_get_pref_orport(&node, &ap);
     313           1 :   tt_assert(tor_addr_eq(&ap.addr, &ipv6_addr));
     314           1 :   tt_assert(ap.port == ipv6_port);
     315             : 
     316           1 :   mocked_options->ClientUseIPv4 = 0;
     317           1 :   node_get_pref_orport(&node, &ap);
     318           1 :   tt_assert(tor_addr_eq(&ap.addr, &ipv6_addr));
     319           1 :   tt_assert(ap.port == ipv6_port);
     320             : 
     321             :   /* Check the preferred address is IPv6 if we don't prefer it, but
     322             :    * ClientUseIPv4 is 0 */
     323           1 :   mocked_options->ClientUseIPv4 = 0;
     324           1 :   mocked_options->ClientUseIPv6 = 1;
     325           1 :   node.ipv6_preferred = reachable_addr_prefer_ipv6_orport(mocked_options);
     326           1 :   node_get_pref_orport(&node, &ap);
     327           1 :   tt_assert(tor_addr_eq(&ap.addr, &ipv6_addr));
     328           1 :   tt_assert(ap.port == ipv6_port);
     329             : 
     330           1 :  done:
     331           1 :   or_options_free(mocked_options);
     332           1 :   UNMOCK(get_options);
     333           1 : }
     334             : 
     335             : static void
     336           1 : test_entry_guard_describe(void *arg)
     337             : {
     338           1 :   (void)arg;
     339           1 :   entry_guard_t g;
     340           1 :   memset(&g, 0, sizeof(g));
     341           1 :   strlcpy(g.nickname, "okefenokee", sizeof(g.nickname));
     342           1 :   memcpy(g.identity, "theforestprimeval---", DIGEST_LEN);
     343             : 
     344           1 :   tt_str_op(entry_guard_describe(&g), OP_EQ,
     345             :             "okefenokee ($746865666F726573747072696D6576616C2D2D2D)");
     346             : 
     347           1 :  done:
     348           1 :   ;
     349           1 : }
     350             : 
     351             : static void
     352           1 : test_entry_guard_randomize_time(void *arg)
     353             : {
     354           1 :   const time_t now = 1479153573;
     355           1 :   const int delay = 86400;
     356           1 :   const int N = 1000;
     357           1 :   (void)arg;
     358             : 
     359           1 :   time_t t;
     360           1 :   int i;
     361        1001 :   for (i = 0; i < N; ++i) {
     362        1000 :     t = randomize_time(now, delay);
     363        1000 :     tt_int_op(t, OP_LE, now);
     364        1000 :     tt_int_op(t, OP_GE, now-delay);
     365             :   }
     366             : 
     367             :   /* now try the corner cases */
     368        1001 :   for (i = 0; i < N; ++i) {
     369        1000 :     t = randomize_time(100, delay);
     370        1000 :     tt_int_op(t, OP_GE, 1);
     371        1000 :     tt_int_op(t, OP_LE, 100);
     372             : 
     373        1000 :     t = randomize_time(0, delay);
     374        1000 :     tt_int_op(t, OP_EQ, 1);
     375             :   }
     376             : 
     377           1 :  done:
     378           1 :   ;
     379           1 : }
     380             : 
     381             : static void
     382           1 : test_entry_guard_encode_for_state_minimal(void *arg)
     383             : {
     384           1 :   (void) arg;
     385           1 :   entry_guard_t *eg = tor_malloc_zero(sizeof(entry_guard_t));
     386             : 
     387           1 :   eg->selection_name = tor_strdup("wubwub");
     388           1 :   memcpy(eg->identity, "plurpyflurpyslurpydo", DIGEST_LEN);
     389           1 :   eg->sampled_on_date = 1479081600;
     390           1 :   eg->confirmed_idx = -1;
     391             : 
     392           1 :   char *s = NULL;
     393           1 :   s = entry_guard_encode_for_state(eg, 0);
     394             : 
     395           1 :   tt_str_op(s, OP_EQ,
     396             :             "in=wubwub "
     397             :             "rsa_id=706C75727079666C75727079736C75727079646F "
     398             :             "sampled_on=2016-11-14T00:00:00 "
     399             :             "sampled_idx=0 "
     400             :             "listed=0");
     401             : 
     402           1 :  done:
     403           1 :   entry_guard_free(eg);
     404           1 :   tor_free(s);
     405           1 : }
     406             : 
     407             : static void
     408           1 : test_entry_guard_encode_for_state_maximal(void *arg)
     409             : {
     410           1 :   (void) arg;
     411           1 :   entry_guard_t *eg = tor_malloc_zero(sizeof(entry_guard_t));
     412             : 
     413           1 :   strlcpy(eg->nickname, "Fred", sizeof(eg->nickname));
     414           1 :   eg->selection_name = tor_strdup("default");
     415           1 :   memcpy(eg->identity, "plurpyflurpyslurpydo", DIGEST_LEN);
     416           1 :   eg->bridge_addr = tor_malloc_zero(sizeof(tor_addr_port_t));
     417           1 :   tor_addr_from_ipv4h(&eg->bridge_addr->addr, 0x08080404);
     418           1 :   eg->bridge_addr->port = 9999;
     419           1 :   eg->sampled_on_date = 1479081600;
     420           1 :   eg->sampled_by_version = tor_strdup("1.2.3");
     421           1 :   eg->unlisted_since_date = 1479081645;
     422           1 :   eg->currently_listed = 1;
     423           1 :   eg->confirmed_on_date = 1479081690;
     424           1 :   eg->confirmed_idx = 333;
     425           1 :   eg->sampled_idx = 42;
     426           1 :   eg->extra_state_fields = tor_strdup("and the green grass grew all around");
     427             : 
     428           1 :   char *s = NULL;
     429           1 :   s = entry_guard_encode_for_state(eg, 0);
     430             : 
     431           1 :   tt_str_op(s, OP_EQ,
     432             :             "in=default "
     433             :             "rsa_id=706C75727079666C75727079736C75727079646F "
     434             :             "bridge_addr=8.8.4.4:9999 "
     435             :             "nickname=Fred "
     436             :             "sampled_on=2016-11-14T00:00:00 "
     437             :             "sampled_idx=0 "
     438             :             "sampled_by=1.2.3 "
     439             :             "unlisted_since=2016-11-14T00:00:45 "
     440             :             "listed=1 "
     441             :             "confirmed_on=2016-11-14T00:01:30 "
     442             :             "confirmed_idx=333 "
     443             :             "and the green grass grew all around");
     444             : 
     445           1 :  done:
     446           1 :   entry_guard_free(eg);
     447           1 :   tor_free(s);
     448           1 : }
     449             : 
     450             : static void
     451           1 : test_entry_guard_parse_from_state_minimal(void *arg)
     452             : {
     453           1 :   (void)arg;
     454           1 :   char *mem_op_hex_tmp = NULL;
     455           1 :   entry_guard_t *eg = NULL;
     456           1 :   time_t t = approx_time();
     457             : 
     458           1 :   eg = entry_guard_parse_from_state(
     459             :                  "in=default_plus "
     460             :                  "rsa_id=596f75206d6179206e656564206120686f626279");
     461           1 :   tt_assert(eg);
     462             : 
     463           1 :   tt_str_op(eg->selection_name, OP_EQ, "default_plus");
     464           1 :   test_mem_op_hex(eg->identity, OP_EQ,
     465             :                   "596f75206d6179206e656564206120686f626279");
     466           1 :   tt_str_op(eg->nickname, OP_EQ, "$596F75206D6179206E656564206120686F626279");
     467           1 :   tt_ptr_op(eg->bridge_addr, OP_EQ, NULL);
     468           1 :   tt_i64_op(eg->sampled_on_date, OP_GE, t);
     469           1 :   tt_i64_op(eg->sampled_on_date, OP_LE, t+86400);
     470           1 :   tt_i64_op(eg->unlisted_since_date, OP_EQ, 0);
     471           1 :   tt_ptr_op(eg->sampled_by_version, OP_EQ, NULL);
     472           1 :   tt_int_op(eg->currently_listed, OP_EQ, 0);
     473           1 :   tt_i64_op(eg->confirmed_on_date, OP_EQ, 0);
     474           1 :   tt_int_op(eg->confirmed_idx, OP_EQ, -1);
     475             : 
     476           1 :   tt_int_op(eg->last_tried_to_connect, OP_EQ, 0);
     477           1 :   tt_int_op(eg->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
     478             : 
     479           1 :  done:
     480           1 :   entry_guard_free(eg);
     481           1 :   tor_free(mem_op_hex_tmp);
     482           1 : }
     483             : 
     484             : static void
     485           1 : test_entry_guard_parse_from_state_maximal(void *arg)
     486             : {
     487           1 :   (void)arg;
     488           1 :   char *mem_op_hex_tmp = NULL;
     489           1 :   entry_guard_t *eg = NULL;
     490             : 
     491           1 :   eg = entry_guard_parse_from_state(
     492             :             "in=fred "
     493             :             "rsa_id=706C75727079666C75727079736C75727079646F "
     494             :             "bridge_addr=[1::3]:9999 "
     495             :             "nickname=Fred "
     496             :             "sampled_on=2016-11-14T00:00:00 "
     497             :             "sampled_by=1.2.3 "
     498             :             "unlisted_since=2016-11-14T00:00:45 "
     499             :             "listed=1 "
     500             :             "confirmed_on=2016-11-14T00:01:30 "
     501             :             "confirmed_idx=333 "
     502             :             "and the green grass grew all around "
     503             :             "rsa_id=all,around");
     504           1 :   tt_assert(eg);
     505             : 
     506           1 :   test_mem_op_hex(eg->identity, OP_EQ,
     507             :                   "706C75727079666C75727079736C75727079646F");
     508           1 :   tt_str_op(fmt_addr(&eg->bridge_addr->addr), OP_EQ, "1::3");
     509           1 :   tt_int_op(eg->bridge_addr->port, OP_EQ, 9999);
     510           1 :   tt_str_op(eg->nickname, OP_EQ, "Fred");
     511           1 :   tt_i64_op(eg->sampled_on_date, OP_EQ, 1479081600);
     512           1 :   tt_i64_op(eg->unlisted_since_date, OP_EQ, 1479081645);
     513           1 :   tt_str_op(eg->sampled_by_version, OP_EQ, "1.2.3");
     514           1 :   tt_int_op(eg->currently_listed, OP_EQ, 1);
     515           1 :   tt_i64_op(eg->confirmed_on_date, OP_EQ, 1479081690);
     516           1 :   tt_int_op(eg->confirmed_idx, OP_EQ, 333);
     517           1 :   tt_str_op(eg->extra_state_fields, OP_EQ,
     518             :             "and the green grass grew all around rsa_id=all,around");
     519             : 
     520           1 :   tt_int_op(eg->last_tried_to_connect, OP_EQ, 0);
     521           1 :   tt_int_op(eg->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
     522             : 
     523           1 :  done:
     524           1 :   entry_guard_free(eg);
     525           1 :   tor_free(mem_op_hex_tmp);
     526           1 : }
     527             : 
     528             : static void
     529           1 : test_entry_guard_parse_from_state_failure(void *arg)
     530             : {
     531           1 :   (void)arg;
     532           1 :   entry_guard_t *eg = NULL;
     533             : 
     534             :   /* no selection */
     535           1 :   eg = entry_guard_parse_from_state(
     536             :                  "rsa_id=596f75206d6179206e656564206120686f626270");
     537           1 :   tt_ptr_op(eg, OP_EQ, NULL);
     538             : 
     539             :   /* no RSA ID. */
     540           1 :   eg = entry_guard_parse_from_state("in=default nickname=Fred");
     541           1 :   tt_ptr_op(eg, OP_EQ, NULL);
     542             : 
     543             :   /* Bad RSA ID: bad character. */
     544           1 :   eg = entry_guard_parse_from_state(
     545             :                  "in=default "
     546             :                  "rsa_id=596f75206d6179206e656564206120686f62627q");
     547           1 :   tt_ptr_op(eg, OP_EQ, NULL);
     548             : 
     549             :   /* Bad RSA ID: too long.*/
     550           1 :   eg = entry_guard_parse_from_state(
     551             :                  "in=default "
     552             :                  "rsa_id=596f75206d6179206e656564206120686f6262703");
     553           1 :   tt_ptr_op(eg, OP_EQ, NULL);
     554             : 
     555             :   /* Bad RSA ID: too short.*/
     556           1 :   eg = entry_guard_parse_from_state(
     557             :                  "in=default "
     558             :                  "rsa_id=596f75206d6179206e65656420612");
     559           1 :   tt_ptr_op(eg, OP_EQ, NULL);
     560             : 
     561           1 :  done:
     562           1 :   entry_guard_free(eg);
     563           1 : }
     564             : 
     565             : static void
     566           1 : test_entry_guard_parse_from_state_partial_failure(void *arg)
     567             : {
     568           1 :   (void)arg;
     569           1 :   char *mem_op_hex_tmp = NULL;
     570           1 :   entry_guard_t *eg = NULL;
     571           1 :   time_t t = approx_time();
     572             : 
     573           1 :   eg = entry_guard_parse_from_state(
     574             :             "in=default "
     575             :             "rsa_id=706C75727079666C75727079736C75727079646F "
     576             :             "bridge_addr=1.2.3.3.4:5 "
     577             :             "nickname=FredIsANodeWithAStrangeNicknameThatIsTooLong "
     578             :             "sampled_on=2016-11-14T00:00:99 "
     579             :             "sampled_by=1.2.3 stuff in the middle "
     580             :             "unlisted_since=2016-xx-14T00:00:45 "
     581             :             "listed=0 "
     582             :             "confirmed_on=2016-11-14T00:01:30zz "
     583             :             "confirmed_idx=idx "
     584             :             "and the green grass grew all around "
     585             :             "rsa_id=all,around");
     586           1 :   tt_assert(eg);
     587             : 
     588           1 :   test_mem_op_hex(eg->identity, OP_EQ,
     589             :                   "706C75727079666C75727079736C75727079646F");
     590           1 :   tt_str_op(eg->nickname, OP_EQ, "FredIsANodeWithAStrangeNicknameThatIsTooL");
     591           1 :   tt_ptr_op(eg->bridge_addr, OP_EQ, NULL);
     592           1 :   tt_i64_op(eg->sampled_on_date, OP_EQ, t);
     593           1 :   tt_i64_op(eg->unlisted_since_date, OP_EQ, 0);
     594           1 :   tt_str_op(eg->sampled_by_version, OP_EQ, "1.2.3");
     595           1 :   tt_int_op(eg->currently_listed, OP_EQ, 0);
     596           1 :   tt_i64_op(eg->confirmed_on_date, OP_EQ, 0);
     597           1 :   tt_int_op(eg->confirmed_idx, OP_EQ, -1);
     598           1 :   tt_str_op(eg->extra_state_fields, OP_EQ,
     599             :             "stuff in the middle and the green grass grew all around "
     600             :             "rsa_id=all,around");
     601             : 
     602           1 :   tt_int_op(eg->last_tried_to_connect, OP_EQ, 0);
     603           1 :   tt_int_op(eg->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
     604             : 
     605           1 :  done:
     606           1 :   entry_guard_free(eg);
     607           1 :   tor_free(mem_op_hex_tmp);
     608           1 : }
     609             : 
     610             : static int
     611           4 : mock_entry_guard_is_listed(guard_selection_t *gs, const entry_guard_t *guard)
     612             : {
     613           4 :   (void)gs;
     614           4 :   (void)guard;
     615           4 :   return 1;
     616             : }
     617             : 
     618             : static void
     619           1 : test_entry_guard_parse_from_state_full(void *arg)
     620             : {
     621           1 :   (void)arg;
     622             :   /* Here's a state I made while testing.  The identities and locations for
     623             :    * the bridges are redacted. */
     624           1 :   const char STATE[] =
     625             :   "Guard in=default rsa_id=214F44BD5B638E8C817D47FF7C97397790BF0345 "
     626             :     "nickname=TotallyNinja sampled_on=2016-11-12T19:32:49 "
     627             :     "sampled_idx=0 "
     628             :     "sampled_by=0.3.0.0-alpha-dev "
     629             :     "listed=1\n"
     630             :   "Guard in=default rsa_id=052900AB0EA3ED54BAB84AE8A99E74E8693CE2B2 "
     631             :     "nickname=5OfNovember sampled_on=2016-11-20T04:32:05 "
     632             :     "sampled_idx=1 "
     633             :     "sampled_by=0.3.0.0-alpha-dev "
     634             :     "listed=1 confirmed_on=2016-11-22T08:13:28 confirmed_idx=0 "
     635             :     "pb_circ_attempts=4.000000 pb_circ_successes=2.000000 "
     636             :     "pb_successful_circuits_closed=2.000000\n"
     637             :   "Guard in=default rsa_id=7B700C0C207EBD0002E00F499BE265519AC3C25A "
     638             :     "nickname=dc6jgk11 sampled_on=2016-11-28T11:50:13 "
     639             :     "sampled_idx=2 "
     640             :     "sampled_by=0.3.0.0-alpha-dev "
     641             :     "listed=1 confirmed_on=2016-11-24T08:45:30 confirmed_idx=4 "
     642             :     "pb_circ_attempts=5.000000 pb_circ_successes=5.000000 "
     643             :     "pb_successful_circuits_closed=5.000000\n"
     644             :   "Guard in=wobblesome rsa_id=7B700C0C207EBD0002E00F499BE265519AC3C25A "
     645             :     "nickname=dc6jgk11 sampled_on=2016-11-28T11:50:13 "
     646             :     "sampled_idx=0 "
     647             :     "sampled_by=0.3.0.0-alpha-dev "
     648             :     "listed=1\n"
     649             :   "Guard in=default rsa_id=E9025AD60D86875D5F11548D536CC6AF60F0EF5E "
     650             :     "nickname=maibrunn sampled_on=2016-11-25T22:36:38 "
     651             :     "sampled_idx=3 "
     652             :     "sampled_by=0.3.0.0-alpha-dev listed=1\n"
     653             :   "Guard in=default rsa_id=DCD30B90BA3A792DA75DC54A327EF353FB84C38E "
     654             :     "nickname=Unnamed sampled_on=2016-11-25T14:34:00 "
     655             :     "sampled_idx=10 "
     656             :     "sampled_by=0.3.0.0-alpha-dev listed=1\n"
     657             :   "Guard in=bridges rsa_id=8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2E "
     658             :     "bridge_addr=24.1.1.1:443 sampled_on=2016-11-25T06:44:14 "
     659             :     "sampled_idx=0 "
     660             :     "sampled_by=0.3.0.0-alpha-dev listed=1 "
     661             :     "confirmed_on=2016-11-29T10:36:06 confirmed_idx=0 "
     662             :     "pb_circ_attempts=8.000000 pb_circ_successes=8.000000 "
     663             :     "pb_successful_circuits_closed=13.000000\n"
     664             :   "Guard in=bridges rsa_id=5800000000000000000000000000000000000000 "
     665             :     "bridge_addr=37.218.246.143:28366 "
     666             :     "sampled_on=2016-11-18T15:07:34 sampled_idx=1 "
     667             :     "sampled_by=0.3.0.0-alpha-dev listed=1\n";
     668             : 
     669           1 :   config_line_t *lines = NULL;
     670           1 :   or_state_t *state = tor_malloc_zero(sizeof(or_state_t));
     671           1 :   int r = config_get_lines(STATE, &lines, 0);
     672           1 :   char *msg = NULL;
     673           1 :   smartlist_t *text = smartlist_new();
     674           1 :   char *joined = NULL;
     675             : 
     676             :   // So nodes aren't expired. This is Tue, 13 Dec 2016 09:37:14 GMT
     677           1 :   update_approx_time(1481621834);
     678             : 
     679           1 :   MOCK(entry_guard_is_listed, mock_entry_guard_is_listed);
     680             : 
     681           1 :   dummy_state = state;
     682           1 :   MOCK(get_or_state,
     683             :        get_or_state_replacement);
     684             : 
     685           1 :   tt_int_op(r, OP_EQ, 0);
     686           1 :   tt_assert(lines);
     687             : 
     688           1 :   state->Guard = lines;
     689             : 
     690             :   /* Try it first without setting the result. */
     691           1 :   r = entry_guards_parse_state(state, 0, &msg);
     692           1 :   tt_int_op(r, OP_EQ, 0);
     693           1 :   guard_selection_t *gs_br =
     694           1 :     get_guard_selection_by_name("bridges", GS_TYPE_BRIDGE, 0);
     695           1 :   tt_ptr_op(gs_br, OP_EQ, NULL);
     696             : 
     697           1 :   r = entry_guards_parse_state(state, 1, &msg);
     698           1 :   tt_int_op(r, OP_EQ, 0);
     699           1 :   gs_br = get_guard_selection_by_name("bridges", GS_TYPE_BRIDGE, 0);
     700           1 :   guard_selection_t *gs_df =
     701           1 :     get_guard_selection_by_name("default", GS_TYPE_NORMAL, 0);
     702           1 :   guard_selection_t *gs_wb =
     703           1 :     get_guard_selection_by_name("wobblesome", GS_TYPE_NORMAL, 0);
     704             : 
     705           1 :   tt_assert(gs_br);
     706           1 :   tt_assert(gs_df);
     707           1 :   tt_assert(gs_wb);
     708             : 
     709           1 :   tt_int_op(smartlist_len(gs_df->sampled_entry_guards), OP_EQ, 5);
     710           1 :   tt_int_op(smartlist_len(gs_br->sampled_entry_guards), OP_EQ, 2);
     711           1 :   tt_int_op(smartlist_len(gs_wb->sampled_entry_guards), OP_EQ, 1);
     712             : 
     713             :   /* Try again; make sure it doesn't double-add the guards. */
     714           1 :   r = entry_guards_parse_state(state, 1, &msg);
     715           1 :   tt_int_op(r, OP_EQ, 0);
     716           1 :   gs_br = get_guard_selection_by_name("bridges", GS_TYPE_BRIDGE, 0);
     717           1 :   gs_df = get_guard_selection_by_name("default", GS_TYPE_NORMAL, 0);
     718           1 :   tt_assert(gs_br);
     719           1 :   tt_assert(gs_df);
     720           1 :   tt_int_op(smartlist_len(gs_df->sampled_entry_guards), OP_EQ, 5);
     721           1 :   tt_int_op(smartlist_len(gs_br->sampled_entry_guards), OP_EQ, 2);
     722             : 
     723             :   /* Re-encode; it should be the same... almost. */
     724             :   {
     725             :     /* (Make a guard nonpersistent first) */
     726           1 :     entry_guard_t *g = smartlist_get(gs_df->sampled_entry_guards, 0);
     727           1 :     g->is_persistent = 0;
     728             :   }
     729           1 :   config_free_lines(lines);
     730           1 :   lines = state->Guard = NULL; // to prevent double-free.
     731           1 :   entry_guards_update_state(state);
     732           1 :   tt_assert(state->Guard);
     733           1 :   lines = state->Guard;
     734             : 
     735           1 :   config_line_t *ln;
     736           8 :   for (ln = lines; ln; ln = ln->next) {
     737           7 :     smartlist_add_asprintf(text, "%s %s\n",ln->key, ln->value);
     738             :   }
     739           1 :   joined = smartlist_join_strings(text, "", 0, NULL);
     740           1 :   tt_str_op(joined, OP_EQ,
     741             :   "Guard in=default rsa_id=052900AB0EA3ED54BAB84AE8A99E74E8693CE2B2 "
     742             :     "nickname=5OfNovember sampled_on=2016-11-20T04:32:05 "
     743             :     "sampled_idx=0 "
     744             :     "sampled_by=0.3.0.0-alpha-dev "
     745             :     "listed=1 confirmed_on=2016-11-22T08:13:28 confirmed_idx=0 "
     746             :     "pb_circ_attempts=4.000000 pb_circ_successes=2.000000 "
     747             :     "pb_successful_circuits_closed=2.000000\n"
     748             :   "Guard in=default rsa_id=7B700C0C207EBD0002E00F499BE265519AC3C25A "
     749             :     "nickname=dc6jgk11 sampled_on=2016-11-28T11:50:13 "
     750             :     "sampled_idx=1 "
     751             :     "sampled_by=0.3.0.0-alpha-dev "
     752             :     "listed=1 confirmed_on=2016-11-24T08:45:30 confirmed_idx=1 "
     753             :     "pb_circ_attempts=5.000000 pb_circ_successes=5.000000 "
     754             :     "pb_successful_circuits_closed=5.000000\n"
     755             :   "Guard in=default rsa_id=E9025AD60D86875D5F11548D536CC6AF60F0EF5E "
     756             :     "nickname=maibrunn sampled_on=2016-11-25T22:36:38 "
     757             :     "sampled_idx=2 "
     758             :     "sampled_by=0.3.0.0-alpha-dev listed=1\n"
     759             :   "Guard in=default rsa_id=DCD30B90BA3A792DA75DC54A327EF353FB84C38E "
     760             :     "nickname=Unnamed sampled_on=2016-11-25T14:34:00 "
     761             :     "sampled_idx=3 "
     762             :     "sampled_by=0.3.0.0-alpha-dev listed=1\n"
     763             :   "Guard in=wobblesome rsa_id=7B700C0C207EBD0002E00F499BE265519AC3C25A "
     764             :     "nickname=dc6jgk11 sampled_on=2016-11-28T11:50:13 "
     765             :     "sampled_idx=0 "
     766             :     "sampled_by=0.3.0.0-alpha-dev "
     767             :     "listed=1\n"
     768             :   "Guard in=bridges rsa_id=8FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF2E "
     769             :     "bridge_addr=24.1.1.1:443 sampled_on=2016-11-25T06:44:14 "
     770             :     "sampled_idx=0 "
     771             :     "sampled_by=0.3.0.0-alpha-dev listed=1 "
     772             :     "confirmed_on=2016-11-29T10:36:06 confirmed_idx=0 "
     773             :     "pb_circ_attempts=8.000000 pb_circ_successes=8.000000 "
     774             :     "pb_successful_circuits_closed=13.000000\n"
     775             :   "Guard in=bridges rsa_id=5800000000000000000000000000000000000000 "
     776             :     "bridge_addr=37.218.246.143:28366 "
     777             :     "sampled_on=2016-11-18T15:07:34 sampled_idx=1 "
     778             :     "sampled_by=0.3.0.0-alpha-dev listed=1\n");
     779             : 
     780           1 :  done:
     781           1 :   config_free_lines(lines);
     782           1 :   tor_free(state);
     783           1 :   tor_free(msg);
     784           1 :   UNMOCK(get_or_state);
     785           1 :   UNMOCK(entry_guard_is_listed);
     786           8 :   SMARTLIST_FOREACH(text, char *, cp, tor_free(cp));
     787           1 :   smartlist_free(text);
     788           1 :   tor_free(joined);
     789           1 : }
     790             : 
     791             : static void
     792           1 : test_entry_guard_parse_from_state_broken(void *arg)
     793             : {
     794           1 :   (void)arg;
     795             :   /* Here's a variation on the previous state. Every line but the first is
     796             :    * busted somehow. */
     797           1 :   const char STATE[] =
     798             :   /* Okay. */
     799             :   "Guard in=default rsa_id=214F44BD5B638E8C817D47FF7C97397790BF0345 "
     800             :     "nickname=TotallyNinja sampled_on=2016-11-12T19:32:49 "
     801             :     "sampled_by=0.3.0.0-alpha-dev "
     802             :     "listed=1\n"
     803             :   /* No selection listed. */
     804             :   "Guard rsa_id=052900AB0EA3ED54BAB84AE8A99E74E8693CE2B2 "
     805             :     "nickname=5OfNovember sampled_on=2016-11-20T04:32:05 "
     806             :     "sampled_by=0.3.0.0-alpha-dev "
     807             :     "listed=1 confirmed_on=2016-11-22T08:13:28 confirmed_idx=0 "
     808             :     "pb_circ_attempts=4.000000 pb_circ_successes=2.000000 "
     809             :     "pb_successful_circuits_closed=2.000000\n"
     810             :   /* Selection is "legacy"!! */
     811             :   "Guard in=legacy rsa_id=7B700C0C207EBD0002E00F499BE265519AC3C25A "
     812             :     "nickname=dc6jgk11 sampled_on=2016-11-28T11:50:13 "
     813             :     "sampled_by=0.3.0.0-alpha-dev "
     814             :     "listed=1 confirmed_on=2016-11-24T08:45:30 confirmed_idx=4 "
     815             :     "pb_circ_attempts=5.000000 pb_circ_successes=5.000000 "
     816             :     "pb_successful_circuits_closed=5.000000\n";
     817             : 
     818           1 :   config_line_t *lines = NULL;
     819           1 :   or_state_t *state = tor_malloc_zero(sizeof(or_state_t));
     820           1 :   int r = config_get_lines(STATE, &lines, 0);
     821           1 :   char *msg = NULL;
     822             : 
     823           1 :   dummy_state = state;
     824           1 :   MOCK(get_or_state,
     825             :        get_or_state_replacement);
     826             : 
     827           1 :   tt_int_op(r, OP_EQ, 0);
     828           1 :   tt_assert(lines);
     829             : 
     830           1 :   state->Guard = lines;
     831             : 
     832             :   /* First, no-set case. we should get an error. */
     833           1 :   r = entry_guards_parse_state(state, 0, &msg);
     834           1 :   tt_int_op(r, OP_LT, 0);
     835           1 :   tt_ptr_op(msg, OP_NE, NULL);
     836             :   /* And we shouldn't have made anything. */
     837           1 :   guard_selection_t *gs_df =
     838           1 :     get_guard_selection_by_name("default", GS_TYPE_NORMAL, 0);
     839           1 :   tt_ptr_op(gs_df, OP_EQ, NULL);
     840           1 :   tor_free(msg);
     841             : 
     842             :   /* Now see about the set case (which shouldn't happen IRL) */
     843           1 :   r = entry_guards_parse_state(state, 1, &msg);
     844           1 :   tt_int_op(r, OP_LT, 0);
     845           1 :   tt_ptr_op(msg, OP_NE, NULL);
     846           1 :   gs_df = get_guard_selection_by_name("default", GS_TYPE_NORMAL, 0);
     847           1 :   tt_ptr_op(gs_df, OP_NE, NULL);
     848           1 :   tt_int_op(smartlist_len(gs_df->sampled_entry_guards), OP_EQ, 1);
     849             : 
     850           1 :  done:
     851           1 :   config_free_lines(lines);
     852           1 :   tor_free(state);
     853           1 :   tor_free(msg);
     854           1 :   UNMOCK(get_or_state);
     855           1 : }
     856             : 
     857             : static void
     858           1 : test_entry_guard_get_guard_selection_by_name(void *arg)
     859             : {
     860           1 :   (void)arg;
     861           1 :   guard_selection_t *gs1, *gs2, *gs3;
     862             : 
     863           1 :   gs1 = get_guard_selection_by_name("unlikely", GS_TYPE_NORMAL, 0);
     864           1 :   tt_ptr_op(gs1, OP_EQ, NULL);
     865           1 :   gs1 = get_guard_selection_by_name("unlikely", GS_TYPE_NORMAL, 1);
     866           1 :   tt_ptr_op(gs1, OP_NE, NULL);
     867           1 :   gs2 = get_guard_selection_by_name("unlikely", GS_TYPE_NORMAL, 1);
     868           1 :   tt_assert(gs2 == gs1);
     869           1 :   gs2 = get_guard_selection_by_name("unlikely", GS_TYPE_NORMAL, 0);
     870           1 :   tt_assert(gs2 == gs1);
     871             : 
     872           1 :   gs2 = get_guard_selection_by_name("implausible", GS_TYPE_NORMAL, 0);
     873           1 :   tt_ptr_op(gs2, OP_EQ, NULL);
     874           1 :   gs2 = get_guard_selection_by_name("implausible", GS_TYPE_NORMAL, 1);
     875           1 :   tt_ptr_op(gs2, OP_NE, NULL);
     876           1 :   tt_assert(gs2 != gs1);
     877           1 :   gs3 = get_guard_selection_by_name("implausible", GS_TYPE_NORMAL, 0);
     878           1 :   tt_assert(gs3 == gs2);
     879             : 
     880           1 :   gs3 = get_guard_selection_by_name("default", GS_TYPE_NORMAL, 0);
     881           1 :   tt_ptr_op(gs3, OP_EQ, NULL);
     882           1 :   gs3 = get_guard_selection_by_name("default", GS_TYPE_NORMAL, 1);
     883           1 :   tt_ptr_op(gs3, OP_NE, NULL);
     884           1 :   tt_assert(gs3 != gs2);
     885           1 :   tt_assert(gs3 != gs1);
     886           1 :   tt_assert(gs3 == get_guard_selection_info());
     887             : 
     888           1 :  done:
     889           1 :   entry_guards_free_all();
     890           1 : }
     891             : 
     892             : static void
     893           3 : test_entry_guard_choose_selection_initial(void *arg)
     894             : {
     895             :   /* Tests for picking our initial guard selection (based on having had
     896             :    * no previous selection */
     897           3 :   (void)arg;
     898           3 :   guard_selection_type_t type = GS_TYPE_INFER;
     899           3 :   const char *name = choose_guard_selection(get_options(),
     900             :                                             dummy_consensus, NULL, &type);
     901           3 :   tt_str_op(name, OP_EQ, "default");
     902           3 :   tt_int_op(type, OP_EQ, GS_TYPE_NORMAL);
     903             : 
     904             :   /* If we're using bridges, we get the bridge selection. */
     905           3 :   get_options_mutable()->UseBridges = 1;
     906           3 :   name = choose_guard_selection(get_options(),
     907             :                                 dummy_consensus, NULL, &type);
     908           3 :   tt_str_op(name, OP_EQ, "bridges");
     909           3 :   tt_int_op(type, OP_EQ, GS_TYPE_BRIDGE);
     910           3 :   get_options_mutable()->UseBridges = 0;
     911             : 
     912             :   /* If we discard >99% of our guards, though, we should be in the restricted
     913             :    * set. */
     914           3 :   tt_assert(get_options_mutable()->EntryNodes == NULL);
     915           3 :   get_options_mutable()->EntryNodes = routerset_new();
     916           3 :   routerset_parse(get_options_mutable()->EntryNodes, "1.0.0.0/8", "foo");
     917           3 :   name = choose_guard_selection(get_options(),
     918             :                                 dummy_consensus, NULL, &type);
     919           3 :   tt_str_op(name, OP_EQ, "restricted");
     920           3 :   tt_int_op(type, OP_EQ, GS_TYPE_RESTRICTED);
     921             : 
     922           3 :  done:
     923           3 :   ;
     924           3 : }
     925             : 
     926             : static void
     927           3 : test_entry_guard_add_single_guard(void *arg)
     928             : {
     929           3 :   (void)arg;
     930           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
     931             : 
     932             :   /* 1: Add a single guard to the sample. */
     933           3 :   node_t *n1 = smartlist_get(big_fake_net_nodes, 0);
     934           3 :   time_t now = approx_time();
     935           3 :   tt_assert(n1->is_possible_guard == 1);
     936           3 :   entry_guard_t *g1 = entry_guard_add_to_sample(gs, n1);
     937           3 :   tt_assert(g1);
     938             : 
     939             :   /* Make sure its fields look right. */
     940           3 :   tt_mem_op(n1->identity, OP_EQ, g1->identity, DIGEST_LEN);
     941           3 :   tt_i64_op(g1->sampled_on_date, OP_GE, now - 12*86400);
     942           3 :   tt_i64_op(g1->sampled_on_date, OP_LE, now);
     943           3 :   tt_str_op(g1->sampled_by_version, OP_EQ, VERSION);
     944           3 :   tt_uint_op(g1->currently_listed, OP_EQ, 1);
     945           3 :   tt_i64_op(g1->confirmed_on_date, OP_EQ, 0);
     946           3 :   tt_int_op(g1->confirmed_idx, OP_EQ, -1);
     947           3 :   tt_int_op(g1->last_tried_to_connect, OP_EQ, 0);
     948           3 :   tt_uint_op(g1->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
     949           3 :   tt_i64_op(g1->failing_since, OP_EQ, 0);
     950           3 :   tt_uint_op(g1->is_filtered_guard, OP_EQ, 1);
     951           3 :   tt_uint_op(g1->is_usable_filtered_guard, OP_EQ, 1);
     952           3 :   tt_uint_op(g1->is_primary, OP_EQ, 0);
     953           3 :   tt_ptr_op(g1->extra_state_fields, OP_EQ, NULL);
     954             : 
     955             :   /* Make sure it got added. */
     956           3 :   tt_int_op(1, OP_EQ, smartlist_len(gs->sampled_entry_guards));
     957           3 :   tt_ptr_op(g1, OP_EQ, smartlist_get(gs->sampled_entry_guards, 0));
     958           3 :   tt_ptr_op(g1, OP_EQ, get_sampled_guard_with_id(gs, (uint8_t*)n1->identity));
     959           3 :   const uint8_t bad_id[20] = {0};
     960           3 :   tt_ptr_op(NULL, OP_EQ, get_sampled_guard_with_id(gs, bad_id));
     961             : 
     962           3 :  done:
     963           3 :   guard_selection_free(gs);
     964           3 : }
     965             : 
     966             : static void
     967           3 : test_entry_guard_node_filter(void *arg)
     968             : {
     969           3 :   (void)arg;
     970           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
     971           3 :   bridge_line_t *bl = NULL;
     972             : 
     973             :   /* Initialize a bunch of node objects that are all guards. */
     974             : #define NUM 7
     975           3 :   node_t *n[NUM];
     976           3 :   entry_guard_t *g[NUM];
     977           3 :   int i;
     978          27 :   for (i=0; i < NUM; ++i) {
     979          21 :     n[i] = smartlist_get(big_fake_net_nodes, i*2); // even ones are guards.
     980          21 :     g[i] = entry_guard_add_to_sample(gs, n[i]);
     981             : 
     982             :     // everything starts out filtered-in
     983          21 :     tt_uint_op(g[i]->is_filtered_guard, OP_EQ, 1);
     984          21 :     tt_uint_op(g[i]->is_usable_filtered_guard, OP_EQ, 1);
     985             :   }
     986           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, NUM);
     987             : 
     988             :   /* Make sure refiltering doesn't hurt */
     989           3 :   entry_guards_update_filtered_sets(gs);
     990          27 :   for (i = 0; i < NUM; ++i) {
     991          21 :     tt_uint_op(g[i]->is_filtered_guard, OP_EQ, 1);
     992          21 :     tt_uint_op(g[i]->is_usable_filtered_guard, OP_EQ, 1);
     993             :   }
     994           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, NUM);
     995             : 
     996             :   /* Now start doing things to make the guards get filtered out, 1 by 1. */
     997             : 
     998             :   /* 0: Not listed. */
     999           3 :   g[0]->currently_listed = 0;
    1000             : 
    1001             :   /* 1: path bias says this guard is maybe eeeevil. */
    1002           3 :   g[1]->pb.path_bias_disabled = 1;
    1003             : 
    1004             :   /* 2: Unreachable address. */
    1005           3 :   tor_addr_make_unspec(&n[2]->rs->ipv4_addr);
    1006             : 
    1007             :   /* 3: ExcludeNodes */
    1008           3 :   tor_addr_from_ipv4h(&n[3]->rs->ipv4_addr, 0x90902020);
    1009           3 :   routerset_free(get_options_mutable()->ExcludeNodes);
    1010           3 :   get_options_mutable()->ExcludeNodes = routerset_new();
    1011           3 :   routerset_parse(get_options_mutable()->ExcludeNodes, "144.144.0.0/16", "");
    1012             : 
    1013             :   /* 4: Bridge. */
    1014           3 :   get_options_mutable()->UseBridges = 1;
    1015           3 :   sweep_bridge_list();
    1016           3 :   bl = tor_malloc_zero(sizeof(bridge_line_t));
    1017           3 :   tor_addr_copy(&bl->addr, &n[4]->rs->ipv4_addr);
    1018           3 :   bl->port = n[4]->rs->ipv4_orport;
    1019           3 :   memcpy(bl->digest, n[4]->identity, 20);
    1020           3 :   bridge_add_from_config(bl);
    1021           3 :   bl = NULL; // prevent free.
    1022           3 :   get_options_mutable()->UseBridges = 0;
    1023             : 
    1024             :   /* 5: Unreachable. This stays in the filter, but isn't in usable-filtered */
    1025           3 :   g[5]->last_tried_to_connect = approx_time(); // prevent retry.
    1026           3 :   g[5]->is_reachable = GUARD_REACHABLE_NO;
    1027             : 
    1028             :   /* 6: no change. */
    1029             : 
    1030             :   /* Now refilter and inspect. */
    1031           3 :   entry_guards_update_filtered_sets(gs);
    1032          27 :   for (i = 0; i < NUM; ++i) {
    1033          21 :     tt_assert(g[i]->is_filtered_guard == (i == 5 || i == 6));
    1034          21 :     tt_assert(g[i]->is_usable_filtered_guard == (i == 6));
    1035             :   }
    1036           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, 1);
    1037             : 
    1038             :   /* Now make sure we have no live consensus, and no nodes.  Nothing should
    1039             :    * pass the filter any more. */
    1040           3 :   tor_free(dummy_consensus);
    1041           3 :   dummy_consensus = NULL;
    1042         816 :   SMARTLIST_FOREACH(big_fake_net_nodes, node_t *, node, {
    1043             :     memset(node->identity, 0xff, 20);
    1044             :   });
    1045           3 :   entry_guards_update_filtered_sets(gs);
    1046          27 :   for (i = 0; i < NUM; ++i) {
    1047          21 :     tt_uint_op(g[i]->is_filtered_guard, OP_EQ, 0);
    1048          21 :     tt_uint_op(g[i]->is_usable_filtered_guard, OP_EQ, 0);
    1049             :   }
    1050           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, 0);
    1051             : 
    1052           3 :  done:
    1053           3 :   guard_selection_free(gs);
    1054           3 :   tor_free(bl);
    1055             : #undef NUM
    1056           3 : }
    1057             : 
    1058             : static void
    1059           3 : test_entry_guard_expand_sample(void *arg)
    1060             : {
    1061           3 :   (void)arg;
    1062           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1063           3 :   digestmap_t *node_by_id = digestmap_new();
    1064             : 
    1065           3 :   entry_guard_t *guard = entry_guards_expand_sample(gs);
    1066           3 :   tt_assert(guard); // the last guard returned.
    1067             : 
    1068             :   // Every sampled guard here should be filtered and reachable for now.
    1069           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ,
    1070             :             num_reachable_filtered_guards(gs, NULL));
    1071             : 
    1072             :   /* Make sure we got the right number. */
    1073           3 :   tt_int_op(DFLT_MIN_FILTERED_SAMPLE_SIZE, OP_EQ,
    1074             :             num_reachable_filtered_guards(gs, NULL));
    1075             : 
    1076             :   // Make sure everything we got was from our fake node list, and everything
    1077             :   // was unique.
    1078          63 :   SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, g) {
    1079          60 :     const node_t *n = bfn_mock_node_get_by_id(g->identity);
    1080          60 :     tt_assert(n);
    1081          60 :     tt_ptr_op(NULL, OP_EQ, digestmap_get(node_by_id, g->identity));
    1082          60 :     digestmap_set(node_by_id, g->identity, (void*) n);
    1083          60 :     int idx = smartlist_pos(big_fake_net_nodes, n);
    1084             :     // The even ones are the guards; make sure we got guards.
    1085          60 :     tt_int_op(idx & 1, OP_EQ, 0);
    1086          60 :   } SMARTLIST_FOREACH_END(g);
    1087             : 
    1088             :   // Nothing became unusable/unfiltered, so a subsequent expand should
    1089             :   // make no changes.
    1090           3 :   guard = entry_guards_expand_sample(gs);
    1091           3 :   tt_ptr_op(guard, OP_EQ, NULL); // no guard was added.
    1092           3 :   tt_int_op(DFLT_MIN_FILTERED_SAMPLE_SIZE, OP_EQ,
    1093             :             num_reachable_filtered_guards(gs, NULL));
    1094             : 
    1095             :   // Make a few guards unreachable.
    1096           3 :   guard = smartlist_get(gs->sampled_entry_guards, 0);
    1097           3 :   guard->is_usable_filtered_guard = 0;
    1098           3 :   guard = smartlist_get(gs->sampled_entry_guards, 1);
    1099           3 :   guard->is_usable_filtered_guard = 0;
    1100           3 :   guard = smartlist_get(gs->sampled_entry_guards, 2);
    1101           3 :   guard->is_usable_filtered_guard = 0;
    1102           3 :   tt_int_op(DFLT_MIN_FILTERED_SAMPLE_SIZE - 3, OP_EQ,
    1103             :             num_reachable_filtered_guards(gs, NULL));
    1104             : 
    1105             :   // This time, expanding the sample will add some more guards.
    1106           3 :   guard = entry_guards_expand_sample(gs);
    1107           3 :   tt_assert(guard); // no guard was added.
    1108           3 :   tt_int_op(DFLT_MIN_FILTERED_SAMPLE_SIZE, OP_EQ,
    1109             :             num_reachable_filtered_guards(gs, NULL));
    1110           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ,
    1111             :             num_reachable_filtered_guards(gs, NULL)+3);
    1112             : 
    1113             :   // Still idempotent.
    1114           3 :   guard = entry_guards_expand_sample(gs);
    1115           3 :   tt_ptr_op(guard, OP_EQ, NULL); // no guard was added.
    1116           3 :   tt_int_op(DFLT_MIN_FILTERED_SAMPLE_SIZE, OP_EQ,
    1117             :             num_reachable_filtered_guards(gs, NULL));
    1118             : 
    1119             :   // Now, do a nasty trick: tell the filter to exclude 31/32 of the guards.
    1120             :   // This will cause the sample size to get reeeeally huge, while the
    1121             :   // filtered sample size grows only slowly.
    1122           3 :   routerset_free(get_options_mutable()->ExcludeNodes);
    1123           3 :   get_options_mutable()->ExcludeNodes = routerset_new();
    1124           3 :   routerset_parse(get_options_mutable()->ExcludeNodes, "144.144.0.0/16", "");
    1125         816 :   SMARTLIST_FOREACH(big_fake_net_nodes, node_t *, n, {
    1126             :     if (n_sl_idx % 64 != 0) {
    1127             :       tor_addr_from_ipv4h(&n->rs->ipv4_addr, 0x90903030);
    1128             :     }
    1129             :   });
    1130           3 :   entry_guards_update_filtered_sets(gs);
    1131             : 
    1132             :   // Surely (p ~ 1-2**-60), one of our guards has been excluded.
    1133           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_LT,
    1134             :             DFLT_MIN_FILTERED_SAMPLE_SIZE);
    1135             : 
    1136             :   // Try to regenerate the guards.
    1137           3 :   guard = entry_guards_expand_sample(gs);
    1138           3 :   tt_assert(guard); // no guard was added.
    1139             : 
    1140             :   /* this time, it's possible that we didn't add enough sampled guards. */
    1141           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_LE,
    1142             :             DFLT_MIN_FILTERED_SAMPLE_SIZE);
    1143             :   /* but we definitely didn't exceed the sample maximum. */
    1144           3 :   const int n_guards = 271 / 2;
    1145           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_LE,
    1146             :             (int)(n_guards * .3));
    1147             : 
    1148           3 :  done:
    1149           3 :   guard_selection_free(gs);
    1150           3 :   digestmap_free(node_by_id, NULL);
    1151           3 : }
    1152             : 
    1153             : static void
    1154           3 : test_entry_guard_expand_sample_small_net(void *arg)
    1155             : {
    1156           3 :   (void)arg;
    1157           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1158             : 
    1159             :   /* Fun corner case: not enough guards to make up our whole sample size. */
    1160         816 :   SMARTLIST_FOREACH(big_fake_net_nodes, node_t *, n, {
    1161             :     if (n_sl_idx >= 15) {
    1162             :       test_node_free(n);
    1163             :       SMARTLIST_DEL_CURRENT(big_fake_net_nodes, n);
    1164             :     } else {
    1165             :       tor_addr_make_unspec(&n->rs->ipv4_addr); // make the filter reject this.
    1166             :     }
    1167             :   });
    1168             : 
    1169           3 :   entry_guard_t *guard = entry_guards_expand_sample(gs);
    1170           3 :   tt_assert(guard); // the last guard returned -- some guard was added.
    1171             :   // half the nodes are guards, so we have 8 guards left.  The set
    1172             :   // is small, so we sampled everything.
    1173           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, 8);
    1174           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, 0);
    1175           3 :  done:
    1176           3 :   guard_selection_free(gs);
    1177           3 : }
    1178             : 
    1179             : static void
    1180           3 : test_entry_guard_update_from_consensus_status(void *arg)
    1181             : {
    1182             :   /* Here we're going to have some nodes become un-guardy, and say we got a
    1183             :    * new consensus. This should cause those nodes to get detected as
    1184             :    * unreachable. */
    1185             : 
    1186           3 :   (void)arg;
    1187           3 :   int i;
    1188           3 :   time_t start = approx_time();
    1189           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1190           3 :   networkstatus_t *ns_tmp = NULL;
    1191             : 
    1192             :   /* Don't randomly backdate stuff; it will make correctness harder to check.*/
    1193           3 :   MOCK(randomize_time, mock_randomize_time_no_randomization);
    1194             : 
    1195             :   /* First, sample some guards. */
    1196           3 :   entry_guards_expand_sample(gs);
    1197           3 :   int n_sampled_pre = smartlist_len(gs->sampled_entry_guards);
    1198           3 :   int n_filtered_pre = num_reachable_filtered_guards(gs, NULL);
    1199           3 :   tt_i64_op(n_sampled_pre, OP_EQ, n_filtered_pre);
    1200           3 :   tt_i64_op(n_sampled_pre, OP_GT, 10);
    1201             : 
    1202             :   /* At this point, it should be a no-op to do this: */
    1203           3 :   sampled_guards_update_from_consensus(gs);
    1204             : 
    1205             :   /* Now let's make some of our guards become unlisted.  The easiest way to
    1206             :    * do that would be to take away their guard flag. */
    1207          21 :   for (i = 0; i < 5; ++i) {
    1208          15 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1209          15 :     node_t *n = (node_t*) bfn_mock_node_get_by_id(g->identity);
    1210          15 :     tt_assert(n);
    1211          15 :     n->is_possible_guard = 0;
    1212             :   }
    1213             : 
    1214           3 :   update_approx_time(start + 30);
    1215             :   {
    1216             :     /* try this with no live networkstatus. Nothing should happen! */
    1217           3 :     ns_tmp = dummy_consensus;
    1218           3 :     dummy_consensus = NULL;
    1219           3 :     sampled_guards_update_from_consensus(gs);
    1220           3 :     tt_i64_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, n_sampled_pre);
    1221           3 :     tt_i64_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, n_filtered_pre);
    1222             :     /* put the networkstatus back. */
    1223           3 :     dummy_consensus = ns_tmp;
    1224           3 :     ns_tmp = NULL;
    1225             :   }
    1226             : 
    1227             :   /* Now those guards should become unlisted, and drop off the filter, but
    1228             :    * stay in the sample. */
    1229           3 :   update_approx_time(start + 60);
    1230           3 :   sampled_guards_update_from_consensus(gs);
    1231             : 
    1232           3 :   tt_i64_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, n_sampled_pre);
    1233           3 :   tt_i64_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, n_filtered_pre-5);
    1234          18 :   for (i = 0; i < 5; ++i) {
    1235          15 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1236          15 :     tt_assert(! g->currently_listed);
    1237          15 :     tt_i64_op(g->unlisted_since_date, OP_EQ, start+60);
    1238             :   }
    1239          48 :   for (i = 5; i < n_sampled_pre; ++i) {
    1240          45 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1241          45 :     tt_assert(g->currently_listed);
    1242          45 :     tt_i64_op(g->unlisted_since_date, OP_EQ, 0);
    1243             :   }
    1244             : 
    1245             :   /* Now re-list one, and remove one completely. */
    1246             :   {
    1247           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 0);
    1248           3 :     node_t *n = (node_t*) bfn_mock_node_get_by_id(g->identity);
    1249           3 :     tt_assert(n);
    1250           3 :     n->is_possible_guard = 1;
    1251             :   }
    1252             :   {
    1253             :     /* try removing the node, to make sure we don't crash on an absent node
    1254             :      */
    1255           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 5);
    1256           3 :     node_t *n = (node_t*) bfn_mock_node_get_by_id(g->identity);
    1257           3 :     tt_assert(n);
    1258           3 :     smartlist_remove(big_fake_net_nodes, n);
    1259           3 :     test_node_free(n);
    1260             :   }
    1261           3 :   update_approx_time(start + 300);
    1262           3 :   sampled_guards_update_from_consensus(gs);
    1263             : 
    1264             :   /* guards 1..5 are now unlisted; 0,6,7.. are listed. */
    1265           3 :   tt_i64_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, n_sampled_pre);
    1266          18 :   for (i = 1; i < 6; ++i) {
    1267          15 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1268          15 :     tt_assert(! g->currently_listed);
    1269          15 :     if (i == 5)
    1270           3 :       tt_i64_op(g->unlisted_since_date, OP_EQ, start+300);
    1271             :     else
    1272          15 :       tt_i64_op(g->unlisted_since_date, OP_EQ, start+60);
    1273             :   }
    1274          90 :   for (i = 0; i < n_sampled_pre; i = (!i) ? 6 : i+1) { /* 0,6,7,8, ... */
    1275          45 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1276          45 :     tt_assert(g->currently_listed);
    1277          45 :     tt_i64_op(g->unlisted_since_date, OP_EQ, 0);
    1278             :   }
    1279             : 
    1280           3 :  done:
    1281           3 :   tor_free(ns_tmp); /* in case we couldn't put it back */
    1282           3 :   guard_selection_free(gs);
    1283           3 :   UNMOCK(randomize_time);
    1284           3 : }
    1285             : 
    1286             : static void
    1287           3 : test_entry_guard_update_from_consensus_repair(void *arg)
    1288             : {
    1289             :   /* Here we'll make sure that our code to repair the unlisted-since
    1290             :    * times is correct. */
    1291             : 
    1292           3 :   (void)arg;
    1293           3 :   int i;
    1294           3 :   time_t start = approx_time();
    1295           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1296             : 
    1297             :   /* Don't randomly backdate stuff; it will make correctness harder to check.*/
    1298           3 :   MOCK(randomize_time, mock_randomize_time_no_randomization);
    1299             : 
    1300             :   /* First, sample some guards. */
    1301           3 :   entry_guards_expand_sample(gs);
    1302           3 :   int n_sampled_pre = smartlist_len(gs->sampled_entry_guards);
    1303           3 :   int n_filtered_pre = num_reachable_filtered_guards(gs, NULL);
    1304           3 :   tt_i64_op(n_sampled_pre, OP_EQ, n_filtered_pre);
    1305           3 :   tt_i64_op(n_sampled_pre, OP_GT, 10);
    1306             : 
    1307             :   /* Now corrupt the list a bit.  Call some unlisted-since-never, and some
    1308             :    * listed-and-unlisted-since-a-time. */
    1309           3 :   update_approx_time(start + 300);
    1310          15 :   for (i = 0; i < 3; ++i) {
    1311             :     /* these will get a date. */
    1312           9 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1313           9 :     node_t *n = (node_t*) bfn_mock_node_get_by_id(g->identity);
    1314           9 :     tt_assert(n);
    1315           9 :     n->is_possible_guard = 0;
    1316           9 :     g->currently_listed = 0;
    1317             :   }
    1318          12 :   for (i = 3; i < 6; ++i) {
    1319             :     /* these will become listed. */
    1320           9 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1321           9 :     g->unlisted_since_date = start+100;
    1322             :   }
    1323           3 :   setup_full_capture_of_logs(LOG_WARN);
    1324           3 :   sampled_guards_update_from_consensus(gs);
    1325           3 :   expect_log_msg_containing(
    1326           3 :              "was listed, but with unlisted_since_date set");
    1327           3 :   expect_log_msg_containing(
    1328           3 :              "was unlisted, but with unlisted_since_date unset");
    1329           3 :   teardown_capture_of_logs();
    1330             : 
    1331           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, n_sampled_pre);
    1332           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, n_filtered_pre-3);
    1333          54 :   for (i = 3; i < n_sampled_pre; ++i) {
    1334             :     /* these will become listed. */
    1335          51 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, i);
    1336          51 :     if (i < 3) {
    1337             :       tt_assert(! g->currently_listed);
    1338             :       tt_i64_op(g->unlisted_since_date, OP_EQ, start+300);
    1339             :     } else {
    1340          51 :       tt_assert(g->currently_listed);
    1341          51 :       tt_i64_op(g->unlisted_since_date, OP_EQ, 0);
    1342             :     }
    1343             :   }
    1344             : 
    1345           3 :  done:
    1346           3 :   teardown_capture_of_logs();
    1347           3 :   guard_selection_free(gs);
    1348           3 :   UNMOCK(randomize_time);
    1349           3 : }
    1350             : 
    1351             : static void
    1352           3 : test_entry_guard_update_from_consensus_remove(void *arg)
    1353             : {
    1354             :   /* Now let's check the logic responsible for removing guards from the
    1355             :    * sample entirely. */
    1356             : 
    1357           3 :   (void)arg;
    1358             :   //int i;
    1359           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1360           3 :   smartlist_t *keep_ids = smartlist_new();
    1361           3 :   smartlist_t *remove_ids = smartlist_new();
    1362             : 
    1363             :   /* Don't randomly backdate stuff; it will make correctness harder to check.*/
    1364           3 :   MOCK(randomize_time, mock_randomize_time_no_randomization);
    1365             : 
    1366             :   /* First, sample some guards. */
    1367           3 :   entry_guards_expand_sample(gs);
    1368           3 :   int n_sampled_pre = smartlist_len(gs->sampled_entry_guards);
    1369           3 :   int n_filtered_pre = num_reachable_filtered_guards(gs, NULL);
    1370           3 :   tt_i64_op(n_sampled_pre, OP_EQ, n_filtered_pre);
    1371           3 :   tt_i64_op(n_sampled_pre, OP_GT, 10);
    1372             : 
    1373           3 :   const time_t one_day_ago = approx_time() - 1*24*60*60;
    1374           3 :   const time_t one_year_ago = approx_time() - 365*24*60*60;
    1375           3 :   const time_t two_years_ago = approx_time() - 2*365*24*60*60;
    1376             :   /* 0: unlisted for a day. (keep this) */
    1377             :   {
    1378           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 0);
    1379           3 :     node_t *n = (node_t*) bfn_mock_node_get_by_id(g->identity);
    1380           3 :     tt_assert(n);
    1381           3 :     n->is_possible_guard = 0;
    1382           3 :     g->currently_listed = 0;
    1383           3 :     g->unlisted_since_date = one_day_ago;
    1384           3 :     smartlist_add(keep_ids, tor_memdup(g->identity, 20));
    1385             :   }
    1386             :   /* 1: unlisted for a year. (remove this) */
    1387             :   {
    1388           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 1);
    1389           3 :     node_t *n = (node_t*) bfn_mock_node_get_by_id(g->identity);
    1390           3 :     tt_assert(n);
    1391           3 :     n->is_possible_guard = 0;
    1392           3 :     g->currently_listed = 0;
    1393           3 :     g->unlisted_since_date = one_year_ago;
    1394           3 :     smartlist_add(remove_ids, tor_memdup(g->identity, 20));
    1395             :   }
    1396             :   /* 2: added a day ago, never confirmed. (keep this) */
    1397             :   {
    1398           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 2);
    1399           3 :     g->sampled_on_date = one_day_ago;
    1400           3 :     smartlist_add(keep_ids, tor_memdup(g->identity, 20));
    1401             :   }
    1402             :   /* 3: added a year ago, never confirmed. (remove this) */
    1403             :   {
    1404           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 3);
    1405           3 :     g->sampled_on_date = one_year_ago;
    1406           3 :     smartlist_add(remove_ids, tor_memdup(g->identity, 20));
    1407             :   }
    1408             :   /* 4: added two year ago, confirmed yesterday, primary. (keep this.) */
    1409             :   {
    1410           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 4);
    1411           3 :     g->sampled_on_date = one_year_ago;
    1412           3 :     g->confirmed_on_date = one_day_ago;
    1413           3 :     g->confirmed_idx = 0;
    1414           3 :     g->is_primary = 1;
    1415           3 :     smartlist_add(gs->confirmed_entry_guards, g);
    1416           3 :     smartlist_add(gs->primary_entry_guards, g);
    1417           3 :     smartlist_add(keep_ids, tor_memdup(g->identity, 20));
    1418             :   }
    1419             :   /* 5: added two years ago, confirmed a year ago, primary. (remove this) */
    1420             :   {
    1421           3 :     entry_guard_t *g = smartlist_get(gs->sampled_entry_guards, 5);
    1422           3 :     g->sampled_on_date = two_years_ago;
    1423           3 :     g->confirmed_on_date = one_year_ago;
    1424           3 :     g->confirmed_idx = 1;
    1425           3 :     g->is_primary = 1;
    1426           3 :     smartlist_add(gs->confirmed_entry_guards, g);
    1427           3 :     smartlist_add(gs->primary_entry_guards, g);
    1428           3 :     smartlist_add(remove_ids, tor_memdup(g->identity, 20));
    1429             :   }
    1430             : 
    1431           3 :   sampled_guards_update_from_consensus(gs);
    1432             : 
    1433             :   /* Did we remove the right ones? */
    1434          12 :   SMARTLIST_FOREACH(keep_ids, uint8_t *, id, {
    1435             :       tt_assert(get_sampled_guard_with_id(gs, id) != NULL);
    1436             :   });
    1437          12 :   SMARTLIST_FOREACH(remove_ids, uint8_t *, id, {
    1438             :     tt_want(get_sampled_guard_with_id(gs, id) == NULL);
    1439             :   });
    1440             : 
    1441             :   /* Did we remove the right number? */
    1442           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, n_sampled_pre - 3);
    1443             : 
    1444           3 :  done:
    1445           3 :   guard_selection_free(gs);
    1446           3 :   UNMOCK(randomize_time);
    1447          12 :   SMARTLIST_FOREACH(keep_ids, char *, cp, tor_free(cp));
    1448          12 :   SMARTLIST_FOREACH(remove_ids, char *, cp, tor_free(cp));
    1449           3 :   smartlist_free(keep_ids);
    1450           3 :   smartlist_free(remove_ids);
    1451           3 : }
    1452             : 
    1453             : static void
    1454           3 : test_entry_guard_confirming_guards(void *arg)
    1455             : {
    1456           3 :   (void)arg;
    1457             :   /* Now let's check the logic responsible for manipulating the list
    1458             :    * of confirmed guards */
    1459           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1460           3 :   MOCK(randomize_time, mock_randomize_time_no_randomization);
    1461             : 
    1462             :   /* Create the sample. */
    1463           3 :   entry_guards_expand_sample(gs);
    1464             : 
    1465             :   /* Confirm a few  guards. */
    1466           3 :   time_t start = approx_time();
    1467           3 :   entry_guard_t *g1 = smartlist_get(gs->sampled_entry_guards, 0);
    1468           3 :   entry_guard_t *g2 = smartlist_get(gs->sampled_entry_guards, 1);
    1469           3 :   entry_guard_t *g3 = smartlist_get(gs->sampled_entry_guards, 8);
    1470           3 :   make_guard_confirmed(gs, g2);
    1471           3 :   update_approx_time(start + 10);
    1472           3 :   make_guard_confirmed(gs, g1);
    1473           3 :   make_guard_confirmed(gs, g3);
    1474             : 
    1475             :   /* Were the correct dates and indices fed in? */
    1476           3 :   tt_int_op(g1->confirmed_idx, OP_EQ, 1);
    1477           3 :   tt_int_op(g2->confirmed_idx, OP_EQ, 0);
    1478           3 :   tt_int_op(g3->confirmed_idx, OP_EQ, 2);
    1479           3 :   tt_i64_op(g1->confirmed_on_date, OP_EQ, start+10);
    1480           3 :   tt_i64_op(g2->confirmed_on_date, OP_EQ, start);
    1481           3 :   tt_i64_op(g3->confirmed_on_date, OP_EQ, start+10);
    1482           3 :   tt_ptr_op(smartlist_get(gs->confirmed_entry_guards, 0), OP_EQ, g1);
    1483           3 :   tt_ptr_op(smartlist_get(gs->confirmed_entry_guards, 1), OP_EQ, g2);
    1484           3 :   tt_ptr_op(smartlist_get(gs->confirmed_entry_guards, 2), OP_EQ, g3);
    1485             : 
    1486             :   /* Now make sure we can regenerate the confirmed_entry_guards list. */
    1487           3 :   smartlist_clear(gs->confirmed_entry_guards);
    1488           3 :   g2->confirmed_idx = 0;
    1489           3 :   g1->confirmed_idx = 10;
    1490           3 :   g3->confirmed_idx = 100;
    1491           3 :   entry_guards_update_confirmed(gs);
    1492           3 :   tt_int_op(g1->confirmed_idx, OP_EQ, 1);
    1493           3 :   tt_int_op(g2->confirmed_idx, OP_EQ, 0);
    1494           3 :   tt_int_op(g3->confirmed_idx, OP_EQ, 2);
    1495           3 :   tt_ptr_op(smartlist_get(gs->confirmed_entry_guards, 0), OP_EQ, g1);
    1496           3 :   tt_ptr_op(smartlist_get(gs->confirmed_entry_guards, 1), OP_EQ, g2);
    1497           3 :   tt_ptr_op(smartlist_get(gs->confirmed_entry_guards, 2), OP_EQ, g3);
    1498             : 
    1499             :   /* Now make sure we can regenerate the confirmed_entry_guards list if
    1500             :    * the indices are messed up. */
    1501           3 :   g1->confirmed_idx = g2->confirmed_idx = g3->confirmed_idx = 999;
    1502           3 :   smartlist_clear(gs->confirmed_entry_guards);
    1503           3 :   entry_guards_update_confirmed(gs);
    1504           3 :   tt_int_op(g1->confirmed_idx, OP_GE, 0);
    1505           3 :   tt_int_op(g2->confirmed_idx, OP_GE, 0);
    1506           3 :   tt_int_op(g3->confirmed_idx, OP_GE, 0);
    1507           3 :   tt_int_op(g1->confirmed_idx, OP_LE, 2);
    1508           3 :   tt_int_op(g2->confirmed_idx, OP_LE, 2);
    1509           3 :   tt_int_op(g3->confirmed_idx, OP_LE, 2);
    1510           3 :   g1 = smartlist_get(gs->confirmed_entry_guards, 0);
    1511           3 :   g2 = smartlist_get(gs->confirmed_entry_guards, 1);
    1512           3 :   g3 = smartlist_get(gs->confirmed_entry_guards, 2);
    1513           3 :   tt_int_op(g1->sampled_idx, OP_EQ, 0);
    1514           3 :   tt_int_op(g2->sampled_idx, OP_EQ, 1);
    1515           3 :   tt_int_op(g3->sampled_idx, OP_EQ, 8);
    1516           3 :   tt_assert(g1 != g2);
    1517           3 :   tt_assert(g1 != g3);
    1518           3 :   tt_assert(g2 != g3);
    1519             : 
    1520           3 :  done:
    1521           3 :   UNMOCK(randomize_time);
    1522           3 :   guard_selection_free(gs);
    1523           3 : }
    1524             : 
    1525             : static void
    1526           3 : test_entry_guard_sample_reachable_filtered(void *arg)
    1527             : {
    1528           3 :   (void)arg;
    1529           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1530           3 :   entry_guards_expand_sample(gs);
    1531             : 
    1532             :   /* We've got a sampled list now; let's make one non-usable-filtered; some
    1533             :    * confirmed, some primary, some pending.
    1534             :    */
    1535           3 :   int n_guards = smartlist_len(gs->sampled_entry_guards);
    1536           3 :   tt_int_op(n_guards, OP_GT, 10);
    1537           3 :   entry_guard_t *g;
    1538           3 :   g = smartlist_get(gs->sampled_entry_guards, 0);
    1539           3 :   g->is_pending = 1;
    1540           3 :   g = smartlist_get(gs->sampled_entry_guards, 1);
    1541           3 :   make_guard_confirmed(gs, g);
    1542           3 :   g = smartlist_get(gs->sampled_entry_guards, 2);
    1543           3 :   g->is_primary = 1;
    1544           3 :   g = smartlist_get(gs->sampled_entry_guards, 3);
    1545           3 :   g->pb.path_bias_disabled = 1;
    1546             : 
    1547           3 :   entry_guards_update_filtered_sets(gs);
    1548           3 :   gs->primary_guards_up_to_date = 1;
    1549           3 :   tt_int_op(num_reachable_filtered_guards(gs, NULL), OP_EQ, n_guards - 1);
    1550           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, n_guards);
    1551             : 
    1552             :   // +1 since the one we made disabled will make  another one get added.
    1553           3 :   ++n_guards;
    1554             : 
    1555             :   /* Try a bunch of selections. */
    1556           3 :   const struct {
    1557             :     int flag; int idx;
    1558           3 :   } tests[] = {
    1559             :     { 0, -1 },
    1560             :     { SAMPLE_EXCLUDE_CONFIRMED, 1 },
    1561             :     { SAMPLE_EXCLUDE_PRIMARY|SAMPLE_NO_UPDATE_PRIMARY, 2 },
    1562             :     { SAMPLE_EXCLUDE_PENDING, 0 },
    1563             :     { -1, -1},
    1564             :   };
    1565           3 :   int j;
    1566          15 :   for (j = 0; tests[j].flag >= 0; ++j) {
    1567          12 :     const int excluded_flags = tests[j].flag;
    1568          12 :     const int excluded_idx = tests[j].idx;
    1569          12 :     g = first_reachable_filtered_entry_guard(gs, NULL, excluded_flags);
    1570          12 :     tor_assert(g);
    1571          12 :     int pos = smartlist_pos(gs->sampled_entry_guards, g);
    1572          12 :     tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, n_guards);
    1573          12 :     const int should_be_set = (pos != excluded_idx &&
    1574          12 :                                  pos != 3); // filtered out.
    1575          12 :     tt_int_op(1, OP_EQ, should_be_set);
    1576             :   }
    1577             : 
    1578           3 :  done:
    1579           3 :   guard_selection_free(gs);
    1580           3 : }
    1581             : 
    1582             : static void
    1583           3 : test_entry_guard_sample_reachable_filtered_empty(void *arg)
    1584             : {
    1585           3 :   (void)arg;
    1586           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1587             :   /* What if we try to sample from a set of 0? */
    1588         816 :   SMARTLIST_FOREACH(big_fake_net_nodes, node_t *, n,
    1589             :                     n->is_possible_guard = 0);
    1590             : 
    1591           3 :   entry_guard_t *g = first_reachable_filtered_entry_guard(gs, NULL, 0);
    1592           3 :   tt_ptr_op(g, OP_EQ, NULL);
    1593             : 
    1594           3 :  done:
    1595           3 :   guard_selection_free(gs);
    1596           3 : }
    1597             : 
    1598             : static void
    1599           3 : test_entry_guard_retry_unreachable(void *arg)
    1600             : {
    1601           3 :   (void)arg;
    1602           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1603             : 
    1604           3 :   entry_guards_expand_sample(gs);
    1605             :   /* Let's say that we have two guards, and they're down.
    1606             :    */
    1607           3 :   time_t start = approx_time();
    1608           3 :   entry_guard_t *g1 = smartlist_get(gs->sampled_entry_guards, 0);
    1609           3 :   entry_guard_t *g2 = smartlist_get(gs->sampled_entry_guards, 1);
    1610           3 :   entry_guard_t *g3 = smartlist_get(gs->sampled_entry_guards, 2);
    1611           3 :   g1->is_reachable = GUARD_REACHABLE_NO;
    1612           3 :   g2->is_reachable = GUARD_REACHABLE_NO;
    1613           3 :   g1->is_primary = 1;
    1614           3 :   g1->failing_since = g2->failing_since = start;
    1615           3 :   g1->last_tried_to_connect = g2->last_tried_to_connect = start;
    1616             : 
    1617             :   /* Wait 5 minutes.  Nothing will get retried. */
    1618           3 :   update_approx_time(start + 5 * 60);
    1619           3 :   entry_guard_consider_retry(g1);
    1620           3 :   entry_guard_consider_retry(g2);
    1621           3 :   entry_guard_consider_retry(g3); // just to make sure this doesn't crash.
    1622           3 :   tt_int_op(g1->is_reachable, OP_EQ, GUARD_REACHABLE_NO);
    1623           3 :   tt_int_op(g2->is_reachable, OP_EQ, GUARD_REACHABLE_NO);
    1624           3 :   tt_int_op(g3->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    1625             : 
    1626             :   /* After 30 min, the primary one gets retried */
    1627           3 :   update_approx_time(start + 35 * 60);
    1628           3 :   entry_guard_consider_retry(g1);
    1629           3 :   entry_guard_consider_retry(g2);
    1630           3 :   tt_int_op(g1->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    1631           3 :   tt_int_op(g2->is_reachable, OP_EQ, GUARD_REACHABLE_NO);
    1632             : 
    1633           3 :   g1->is_reachable = GUARD_REACHABLE_NO;
    1634           3 :   g1->last_tried_to_connect = start + 55*60;
    1635             : 
    1636             :   /* After 1 hour, we'll retry the nonprimary one. */
    1637           3 :   update_approx_time(start + 61 * 60);
    1638           3 :   entry_guard_consider_retry(g1);
    1639           3 :   entry_guard_consider_retry(g2);
    1640           3 :   tt_int_op(g1->is_reachable, OP_EQ, GUARD_REACHABLE_NO);
    1641           3 :   tt_int_op(g2->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    1642             : 
    1643           3 :   g2->is_reachable = GUARD_REACHABLE_NO;
    1644           3 :   g2->last_tried_to_connect = start + 61*60;
    1645             : 
    1646             :   /* And then the primary one again. */
    1647           3 :   update_approx_time(start + 66 * 60);
    1648           3 :   entry_guard_consider_retry(g1);
    1649           3 :   entry_guard_consider_retry(g2);
    1650           3 :   tt_int_op(g1->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    1651           3 :   tt_int_op(g2->is_reachable, OP_EQ, GUARD_REACHABLE_NO);
    1652             : 
    1653           3 :  done:
    1654           3 :   guard_selection_free(gs);
    1655           3 : }
    1656             : 
    1657             : static void
    1658           3 : test_entry_guard_manage_primary(void *arg)
    1659             : {
    1660           3 :   (void)arg;
    1661           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1662           3 :   smartlist_t *prev_guards = smartlist_new();
    1663             : 
    1664             :   /* If no guards are confirmed, we should pick a few reachable guards and
    1665             :    * call them all primary. But not confirmed.*/
    1666           3 :   entry_guards_update_primary(gs);
    1667           3 :   int n_primary = smartlist_len(gs->primary_entry_guards);
    1668           3 :   tt_int_op(n_primary, OP_GE, 1);
    1669          12 :   SMARTLIST_FOREACH(gs->primary_entry_guards, entry_guard_t *, g, {
    1670             :     tt_assert(g->is_primary);
    1671             :     tt_assert(g->confirmed_idx == -1);
    1672             :   });
    1673             : 
    1674             :   /* Calling it a second time should leave the guards unchanged. */
    1675           3 :   smartlist_add_all(prev_guards, gs->primary_entry_guards);
    1676           3 :   entry_guards_update_primary(gs);
    1677           3 :   tt_int_op(smartlist_len(gs->primary_entry_guards), OP_EQ, n_primary);
    1678          12 :   SMARTLIST_FOREACH(gs->primary_entry_guards, entry_guard_t *, g, {
    1679             :     tt_ptr_op(g, OP_EQ, smartlist_get(prev_guards, g_sl_idx));
    1680             :   });
    1681             : 
    1682             :   /**
    1683             :    * If we have one confirmed guard, that guards becomes the first primary
    1684             :    * only if its sampled_idx is smaller
    1685             :    * */
    1686             : 
    1687             :   /* find a non-primary guard... it should have a sampled_idx higher than
    1688             :    * existing primary guards */
    1689           3 :   entry_guard_t *confirmed = NULL;
    1690          12 :   SMARTLIST_FOREACH(gs->sampled_entry_guards, entry_guard_t *, g, {
    1691             :     if (! g->is_primary) {
    1692             :       confirmed = g;
    1693             :       break;
    1694             :     }
    1695             :   });
    1696           3 :   tt_assert(confirmed);
    1697             :   /* make it confirmed. */
    1698           3 :   make_guard_confirmed(gs, confirmed);
    1699             :   /* update the list... */
    1700           3 :   smartlist_clear(prev_guards);
    1701           3 :   smartlist_add_all(prev_guards, gs->primary_entry_guards);
    1702           3 :   entry_guards_update_primary(gs);
    1703             : 
    1704             :   /* the confirmed guard should be at the end of the primary list! Hopefully,
    1705             :    * one of the primary guards with a lower sampled_idx will confirm soon :)
    1706             :    * Doing this won't make the client switches between primaries depending on
    1707             :    * the order of confirming events */
    1708           3 :   tt_int_op(smartlist_len(gs->primary_entry_guards), OP_EQ, n_primary);
    1709           3 :   tt_ptr_op(smartlist_get(gs->primary_entry_guards,
    1710             :         smartlist_len(gs->primary_entry_guards)-1), OP_EQ, confirmed);
    1711             :   {
    1712           3 :     entry_guard_t *prev_last_guard = smartlist_get(prev_guards, n_primary-1);
    1713           3 :     tt_assert(! prev_last_guard->is_primary);
    1714             :   }
    1715             : 
    1716             :   /* Calling it a fourth time should leave the guards unchanged. */
    1717           3 :   smartlist_clear(prev_guards);
    1718           3 :   smartlist_add_all(prev_guards, gs->primary_entry_guards);
    1719           3 :   entry_guards_update_primary(gs);
    1720           3 :   tt_int_op(smartlist_len(gs->primary_entry_guards), OP_EQ, n_primary);
    1721          12 :   SMARTLIST_FOREACH(gs->primary_entry_guards, entry_guard_t *, g, {
    1722             :     tt_ptr_op(g, OP_EQ, smartlist_get(prev_guards, g_sl_idx));
    1723             :   });
    1724             : 
    1725             :   /* Do some dirinfo checks */
    1726             :   {
    1727             :     /* Check that we have all required dirinfo for the primaries (that's done
    1728             :      * in big_fake_network_setup()) */
    1729           6 :     char *dir_info_str =
    1730           3 :       guard_selection_get_err_str_if_dir_info_missing(gs, 0, 0, 0);
    1731           3 :     tt_assert(!dir_info_str);
    1732             : 
    1733             :     /* Now artificially remove the first primary's descriptor and re-check */
    1734           3 :     entry_guard_t *first_primary;
    1735           3 :     first_primary = smartlist_get(gs->primary_entry_guards, 0);
    1736             :     /* Change the first primary's identity digest so that the mocked functions
    1737             :      * can't find its descriptor */
    1738           3 :     memset(first_primary->identity, 9, sizeof(first_primary->identity));
    1739           3 :     dir_info_str =guard_selection_get_err_str_if_dir_info_missing(gs, 1, 2, 3);
    1740           3 :     tt_str_op(dir_info_str, OP_EQ,
    1741             :               "We're missing descriptors for 1/2 of our primary entry guards "
    1742             :               "(total microdescriptors: 2/3). That's ok. We will try to fetch "
    1743             :               "missing descriptors soon.");
    1744           3 :     tor_free(dir_info_str);
    1745             :   }
    1746             : 
    1747           3 :  done:
    1748           3 :   guard_selection_free(gs);
    1749           3 :   smartlist_free(prev_guards);
    1750           3 : }
    1751             : 
    1752             : static void
    1753           1 : test_entry_guard_guard_preferred(void *arg)
    1754             : {
    1755           1 :   (void) arg;
    1756           1 :   entry_guard_t *g1 = tor_malloc_zero(sizeof(entry_guard_t));
    1757           1 :   entry_guard_t *g2 = tor_malloc_zero(sizeof(entry_guard_t));
    1758             : 
    1759           1 :   g1->confirmed_idx = g2->confirmed_idx = -1;
    1760           1 :   g1->last_tried_to_connect = approx_time();
    1761           1 :   g2->last_tried_to_connect = approx_time();
    1762             : 
    1763           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g1, g1));
    1764             : 
    1765             :   /* Neither is pending; priorities equal. */
    1766           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g2, g1));
    1767           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g1, g2));
    1768             : 
    1769             :   /* If one is pending, the pending one has higher priority */
    1770           1 :   g1->is_pending = 1;
    1771           1 :   tt_int_op(1, OP_EQ, entry_guard_has_higher_priority(g1, g2));
    1772           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g2, g1));
    1773             : 
    1774             :   /* If both are pending, and last_tried_to_connect is equal:
    1775             :      priorities equal */
    1776           1 :   g2->is_pending = 1;
    1777           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g2, g1));
    1778           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g1, g2));
    1779             : 
    1780             :   /* One had a connection that startied earlier: it has higher priority. */
    1781           1 :   g2->last_tried_to_connect -= 10;
    1782           1 :   tt_int_op(1, OP_EQ, entry_guard_has_higher_priority(g2, g1));
    1783           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g1, g2));
    1784             : 
    1785             :   /* Now, say that g1 is confirmed. It will get higher priority. */
    1786           1 :   g1->confirmed_idx = 5;
    1787           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g2, g1));
    1788           1 :   tt_int_op(1, OP_EQ, entry_guard_has_higher_priority(g1, g2));
    1789             : 
    1790             :   /* But if g2 was confirmed first, it will get priority */
    1791           1 :   g2->confirmed_idx = 2;
    1792           1 :   tt_int_op(1, OP_EQ, entry_guard_has_higher_priority(g2, g1));
    1793           1 :   tt_int_op(0, OP_EQ, entry_guard_has_higher_priority(g1, g2));
    1794             : 
    1795           1 :  done:
    1796           1 :   tor_free(g1);
    1797           1 :   tor_free(g2);
    1798           1 : }
    1799             : 
    1800             : static void
    1801           3 : test_entry_guard_correct_cascading_order(void *arg)
    1802             : {
    1803           3 :   (void)arg;
    1804           3 :   smartlist_t *old_primary_guards = smartlist_new();
    1805           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1806           3 :   entry_guards_expand_sample(gs);
    1807             :   /** First, a test in which the primary guards need be pulled from different
    1808             :    * lists to fill up the primary list -- this may happen, if for example, not
    1809             :    * enough guards have confirmed yet */
    1810           3 :   entry_guard_t *g;
    1811             :   /** just one confirmed */
    1812           3 :   g = smartlist_get(gs->sampled_entry_guards, 2);
    1813           3 :   make_guard_confirmed(gs, g);
    1814           3 :   entry_guards_update_primary(gs);
    1815           3 :   g = smartlist_get(gs->primary_entry_guards, 0);
    1816           3 :   tt_int_op(g->sampled_idx, OP_EQ, 0);
    1817           3 :   g = smartlist_get(gs->primary_entry_guards, 1);
    1818           3 :   tt_int_op(g->sampled_idx, OP_EQ, 1);
    1819           3 :   g = smartlist_get(gs->primary_entry_guards, 2);
    1820           3 :   tt_int_op(g->sampled_idx, OP_EQ, 2);
    1821             : 
    1822             :   /** Now the primaries get all confirmed, and the primary list should not
    1823             :    * change */
    1824           3 :   make_guard_confirmed(gs, smartlist_get(gs->primary_entry_guards, 0));
    1825           3 :   make_guard_confirmed(gs, smartlist_get(gs->primary_entry_guards, 1));
    1826           3 :   smartlist_add_all(old_primary_guards, gs->primary_entry_guards);
    1827           3 :   entry_guards_update_primary(gs);
    1828           3 :   smartlist_ptrs_eq(gs->primary_entry_guards, old_primary_guards);
    1829             :   /** the confirmed guards should also have the same set of guards, in the same
    1830             :    * order :-) */
    1831           3 :   smartlist_ptrs_eq(gs->confirmed_entry_guards, gs->primary_entry_guards);
    1832             :   /** Now select a guard for a circuit, and make sure it is the first primary
    1833             :    * guard */
    1834           3 :   unsigned state = 9999;
    1835           3 :   g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1836           3 :   tt_ptr_op(g, OP_EQ, smartlist_get(gs->primary_entry_guards, 0));
    1837             :   /** Now, let's mark this guard as unreachable and let's update the lists */
    1838           3 :   g->is_reachable = GUARD_REACHABLE_NO;
    1839           3 :   g->failing_since = approx_time() - 10;
    1840           3 :   g->last_tried_to_connect = approx_time() - 10;
    1841           3 :   state = 9999;
    1842           3 :   entry_guards_update_primary(gs);
    1843           3 :   g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1844             :   /** we should have switched to the next one is sampled order */
    1845           3 :   tt_int_op(g->sampled_idx, OP_EQ, 1);
    1846           3 :  done:
    1847           3 :   smartlist_free(old_primary_guards);
    1848           3 :   guard_selection_free(gs);
    1849           3 : }
    1850             : 
    1851             : static void
    1852           3 : test_entry_guard_select_for_circuit_no_confirmed(void *arg)
    1853             : {
    1854             :   /* Simpler cases: no gaurds are confirmed yet. */
    1855           3 :   (void)arg;
    1856           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1857           3 :   entry_guard_restriction_t *rst = NULL;
    1858             : 
    1859             :   /* simple starting configuration */
    1860           3 :   entry_guards_update_primary(gs);
    1861           3 :   unsigned state = 9999;
    1862             : 
    1863           3 :   entry_guard_t *g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC,
    1864             :                                                     NULL, &state);
    1865             : 
    1866           3 :   tt_assert(g);
    1867           3 :   tt_assert(g->is_primary);
    1868           3 :   tt_int_op(g->confirmed_idx, OP_EQ, -1);
    1869           3 :   tt_uint_op(g->is_pending, OP_EQ, 0); // primary implies non-pending.
    1870           3 :   tt_uint_op(state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    1871           3 :   tt_i64_op(g->last_tried_to_connect, OP_EQ, approx_time());
    1872             : 
    1873             :   // If we do that again, we should get the same guard.
    1874           3 :   entry_guard_t *g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC,
    1875             :                                                      NULL, &state);
    1876           3 :   tt_ptr_op(g2, OP_EQ, g);
    1877             : 
    1878             :   // if we mark that guard down, we should get a different primary guard.
    1879             :   // auto-retry it.
    1880           3 :   g->is_reachable = GUARD_REACHABLE_NO;
    1881           3 :   g->failing_since = approx_time() - 10;
    1882           3 :   g->last_tried_to_connect = approx_time() - 10;
    1883           3 :   state = 9999;
    1884           3 :   g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1885           3 :   tt_ptr_op(g2, OP_NE, g);
    1886           3 :   tt_assert(g2);
    1887           3 :   tt_assert(g2->is_primary);
    1888           3 :   tt_int_op(g2->confirmed_idx, OP_EQ, -1);
    1889           3 :   tt_uint_op(g2->is_pending, OP_EQ, 0); // primary implies non-pending.
    1890           3 :   tt_uint_op(state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    1891           3 :   tt_i64_op(g2->last_tried_to_connect, OP_EQ, approx_time());
    1892             : 
    1893             :   // If we say that the first primary guard was last tried a long time ago, we
    1894             :   // should get an automatic retry on it.
    1895           3 :   g->failing_since = approx_time() - 72*60*60;
    1896           3 :   g->last_tried_to_connect = approx_time() - 72*60*60;
    1897           3 :   state = 9999;
    1898           3 :   g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1899           3 :   tt_ptr_op(g2, OP_EQ, g);
    1900           3 :   tt_assert(g2);
    1901           3 :   tt_uint_op(state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    1902           3 :   tt_i64_op(g2->last_tried_to_connect, OP_EQ, approx_time());
    1903           3 :   tt_int_op(g2->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    1904             : 
    1905             :   // And if we mark ALL the primary guards down, we should get another guard
    1906             :   // at random.
    1907          12 :   SMARTLIST_FOREACH(gs->primary_entry_guards, entry_guard_t *, guard, {
    1908             :     guard->is_reachable = GUARD_REACHABLE_NO;
    1909             :     guard->last_tried_to_connect = approx_time() - 5;
    1910             :     guard->failing_since = approx_time() - 30;
    1911             :   });
    1912           3 :   state = 9999;
    1913           3 :   g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1914           3 :   tt_assert(g2);
    1915           3 :   tt_assert(!g2->is_primary);
    1916           3 :   tt_int_op(g2->confirmed_idx, OP_EQ, -1);
    1917           3 :   tt_uint_op(g2->is_pending, OP_EQ, 1);
    1918           3 :   tt_uint_op(state, OP_EQ, GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    1919           3 :   tt_i64_op(g2->last_tried_to_connect, OP_EQ, approx_time());
    1920           3 :   tt_int_op(g2->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    1921             : 
    1922             :   // As a bonus, maybe we should be retrying the primary guards. Let's say so.
    1923           3 :   mark_primary_guards_maybe_reachable(gs);
    1924          12 :   SMARTLIST_FOREACH(gs->primary_entry_guards, entry_guard_t *, guard, {
    1925             :     tt_int_op(guard->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    1926             :     tt_assert(guard->is_usable_filtered_guard == 1);
    1927             :     // no change to these fields.
    1928             :     tt_i64_op(guard->last_tried_to_connect, OP_EQ, approx_time() - 5);
    1929             :     tt_i64_op(guard->failing_since, OP_EQ, approx_time() - 30);
    1930             :   });
    1931             : 
    1932             :   /* Let's try again and we should get the first primary guard again */
    1933           3 :   g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1934           3 :   tt_ptr_op(g, OP_EQ, smartlist_get(gs->primary_entry_guards, 0));
    1935           3 :   g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1936           3 :   tt_ptr_op(g2, OP_EQ, g);
    1937             : 
    1938             :   /* But if we impose a restriction, we don't get the same guard */
    1939           3 :   rst = guard_create_exit_restriction((uint8_t*)g->identity);
    1940           3 :   g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, rst, &state);
    1941           3 :   tt_ptr_op(g2, OP_NE, g);
    1942             : 
    1943           3 :  done:
    1944           3 :   guard_selection_free(gs);
    1945           3 :   entry_guard_restriction_free(rst);
    1946           3 : }
    1947             : 
    1948             : static void
    1949           3 : test_entry_guard_select_for_circuit_confirmed(void *arg)
    1950             : {
    1951             :   /* Case 2: if all the primary guards are down, and there are more confirmed
    1952             :      guards, we use a confirmed guard. */
    1953           3 :   (void)arg;
    1954           3 :   int i;
    1955           3 :   entry_guard_restriction_t *rst = NULL;
    1956           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    1957           3 :   const int N_CONFIRMED = 10;
    1958             : 
    1959             :   /* slightly more complicated simple starting configuration */
    1960           3 :   entry_guards_update_primary(gs);
    1961          36 :   for (i = 0; i < N_CONFIRMED; ++i) {
    1962          30 :     entry_guard_t *guard = smartlist_get(gs->sampled_entry_guards, i);
    1963          30 :     make_guard_confirmed(gs, guard);
    1964             :   }
    1965           3 :   entry_guards_update_primary(gs); // rebuild the primary list.
    1966             : 
    1967           3 :   unsigned state = 9999;
    1968             : 
    1969             :   // As above, this gives us a primary guard.
    1970           3 :   entry_guard_t *g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC,
    1971             :                                                     NULL, &state);
    1972           3 :   tt_assert(g);
    1973           3 :   tt_assert(g->is_primary);
    1974           3 :   tt_int_op(g->confirmed_idx, OP_EQ, 0);
    1975           3 :   tt_uint_op(g->is_pending, OP_EQ, 0); // primary implies non-pending.
    1976           3 :   tt_uint_op(state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    1977           3 :   tt_i64_op(g->last_tried_to_connect, OP_EQ, approx_time());
    1978           3 :   tt_ptr_op(g, OP_EQ, smartlist_get(gs->primary_entry_guards, 0));
    1979             : 
    1980             :   // But if we mark all the primary guards down...
    1981          12 :   SMARTLIST_FOREACH(gs->primary_entry_guards, entry_guard_t *, guard, {
    1982             :     guard->last_tried_to_connect = approx_time();
    1983             :     entry_guards_note_guard_failure(gs, guard);
    1984             :   });
    1985             : 
    1986             :   // ... we should get a confirmed guard.
    1987           3 :   state = 9999;
    1988           3 :   g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    1989           3 :   tt_assert(g);
    1990           3 :   tt_assert(! g->is_primary);
    1991           3 :   tt_int_op(g->confirmed_idx, OP_EQ, smartlist_len(gs->primary_entry_guards));
    1992           3 :   tt_assert(g->is_pending);
    1993           3 :   tt_uint_op(state, OP_EQ, GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    1994           3 :   tt_i64_op(g->last_tried_to_connect, OP_EQ, approx_time());
    1995             : 
    1996             :   // And if we try again, we should get a different confirmed guard, since
    1997             :   // that one is pending.
    1998           3 :   state = 9999;
    1999           3 :   entry_guard_t *g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC,
    2000             :                                                      NULL, &state);
    2001           3 :   tt_assert(g2);
    2002           3 :   tt_assert(! g2->is_primary);
    2003           3 :   tt_ptr_op(g2, OP_NE, g);
    2004           3 :   tt_int_op(g2->confirmed_idx, OP_EQ,
    2005             :             smartlist_len(gs->primary_entry_guards)+1);
    2006           3 :   tt_assert(g2->is_pending);
    2007           3 :   tt_uint_op(state, OP_EQ, GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    2008           3 :   tt_i64_op(g2->last_tried_to_connect, OP_EQ, approx_time());
    2009             : 
    2010             :   // If we say that the next confirmed guard in order is excluded, and
    2011             :   // we disable EnforceDistinctSubnets, we get the guard AFTER the
    2012             :   // one we excluded.
    2013           3 :   get_options_mutable()->EnforceDistinctSubnets = 0;
    2014           3 :   g = smartlist_get(gs->confirmed_entry_guards,
    2015             :                      smartlist_len(gs->primary_entry_guards)+2);
    2016           3 :   rst = guard_create_exit_restriction((uint8_t*)g->identity);
    2017           3 :   g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, rst, &state);
    2018           3 :   tt_ptr_op(g2, OP_NE, NULL);
    2019           3 :   tt_ptr_op(g2, OP_NE, g);
    2020           3 :   tt_int_op(g2->confirmed_idx, OP_EQ,
    2021             :             smartlist_len(gs->primary_entry_guards)+3);
    2022             : 
    2023             :   // If we make every confirmed guard become pending then we start poking
    2024             :   // other guards.
    2025           3 :   const int n_remaining_confirmed =
    2026           3 :     N_CONFIRMED - 3 - smartlist_len(gs->primary_entry_guards);
    2027          15 :   for (i = 0; i < n_remaining_confirmed; ++i) {
    2028          12 :     g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    2029          12 :     tt_int_op(g->confirmed_idx, OP_GE, 0);
    2030          12 :     tt_assert(g);
    2031             :   }
    2032           3 :   state = 9999;
    2033           3 :   g = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &state);
    2034           3 :   tt_assert(g);
    2035           3 :   tt_assert(g->is_pending);
    2036           3 :   tt_int_op(g->confirmed_idx, OP_EQ, -1);
    2037             : 
    2038             :   // If we EnforceDistinctSubnets and apply a restriction, we get
    2039             :   // nothing, since we put all of the nodes in the same /16.
    2040             :   // Regression test for bug 22753/TROVE-2017-006.
    2041           3 :   get_options_mutable()->EnforceDistinctSubnets = 1;
    2042           3 :   g = smartlist_get(gs->confirmed_entry_guards, 0);
    2043           3 :   memcpy(rst->exclude_id, g->identity, DIGEST_LEN);
    2044           3 :   g2 = select_entry_guard_for_circuit(gs, GUARD_USAGE_TRAFFIC, rst, &state);
    2045           3 :   tt_ptr_op(g2, OP_EQ, NULL);
    2046             : 
    2047           3 :  done:
    2048           3 :   guard_selection_free(gs);
    2049           3 :   entry_guard_restriction_free(rst);
    2050           3 : }
    2051             : 
    2052             : static void
    2053           3 : test_entry_guard_select_for_circuit_highlevel_primary(void *arg)
    2054             : {
    2055             :   /* Play around with selecting primary guards for circuits and markign
    2056             :    * them up and down */
    2057           3 :   (void)arg;
    2058           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    2059             : 
    2060           3 :   time_t start = approx_time();
    2061             : 
    2062           3 :   const node_t *node = NULL;
    2063           3 :   circuit_guard_state_t *guard = NULL;
    2064           3 :   entry_guard_t *g;
    2065           3 :   guard_usable_t u;
    2066             :   /*
    2067             :    * Make sure that the pick-for-circuit API basically works.  We'll get
    2068             :    * a primary guard, so it'll be usable on completion.
    2069             :    */
    2070           3 :   int r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2071             :                                        &node, &guard);
    2072             : 
    2073           3 :   tt_int_op(r, OP_EQ, 0);
    2074           3 :   tt_assert(node);
    2075           3 :   tt_assert(guard);
    2076           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    2077           3 :   g = entry_guard_handle_get(guard->guard);
    2078           3 :   tt_assert(g);
    2079           3 :   tt_mem_op(g->identity, OP_EQ, node->identity, DIGEST_LEN);
    2080           3 :   tt_int_op(g->is_primary, OP_EQ, 1);
    2081           3 :   tt_i64_op(g->last_tried_to_connect, OP_EQ, start);
    2082           3 :   tt_int_op(g->confirmed_idx, OP_EQ, -1);
    2083             : 
    2084             :   /* Call that circuit successful. */
    2085           3 :   update_approx_time(start+15);
    2086           3 :   u = entry_guard_succeeded(&guard);
    2087           3 :   tt_int_op(u, OP_EQ, GUARD_USABLE_NOW); /* We can use it now. */
    2088           3 :   tt_assert(guard);
    2089           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_COMPLETE);
    2090           3 :   g = entry_guard_handle_get(guard->guard);
    2091           3 :   tt_assert(g);
    2092           3 :   tt_int_op(g->is_reachable, OP_EQ, GUARD_REACHABLE_YES);
    2093           3 :   tt_int_op(g->confirmed_idx, OP_EQ, 0);
    2094             : 
    2095           3 :   circuit_guard_state_free(guard);
    2096           3 :   guard = NULL;
    2097           3 :   node = NULL;
    2098           3 :   g = NULL;
    2099             : 
    2100             :   /* Try again. We'll also get a primary guard this time. (The same one,
    2101             :      in fact.)  But this time, we'll say the connection has failed. */
    2102           3 :   update_approx_time(start+35);
    2103           3 :   r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2104             :                                    &node, &guard);
    2105           3 :   tt_int_op(r, OP_EQ, 0);
    2106           3 :   tt_assert(node);
    2107           3 :   tt_assert(guard);
    2108           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    2109           3 :   tt_i64_op(guard->state_set_at, OP_EQ, start+35);
    2110           3 :   g = entry_guard_handle_get(guard->guard);
    2111           3 :   tt_assert(g);
    2112           3 :   tt_mem_op(g->identity, OP_EQ, node->identity, DIGEST_LEN);
    2113           3 :   tt_int_op(g->is_primary, OP_EQ, 1);
    2114           3 :   tt_i64_op(g->last_tried_to_connect, OP_EQ, start+35);
    2115           3 :   tt_int_op(g->confirmed_idx, OP_EQ, 0); // same one.
    2116             : 
    2117             :   /* It's failed!  What will happen to our poor guard? */
    2118           3 :   update_approx_time(start+45);
    2119           3 :   entry_guard_failed(&guard);
    2120           3 :   tt_assert(guard);
    2121           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_DEAD);
    2122           3 :   tt_i64_op(guard->state_set_at, OP_EQ, start+45);
    2123           3 :   g = entry_guard_handle_get(guard->guard);
    2124           3 :   tt_assert(g);
    2125           3 :   tt_int_op(g->is_reachable, OP_EQ, GUARD_REACHABLE_NO);
    2126           3 :   tt_i64_op(g->failing_since, OP_EQ, start+45);
    2127           3 :   tt_int_op(g->confirmed_idx, OP_EQ, 0); // still confirmed.
    2128             : 
    2129           3 :   circuit_guard_state_free(guard);
    2130           3 :   guard = NULL;
    2131           3 :   node = NULL;
    2132           3 :   entry_guard_t *g_prev = g;
    2133           3 :   g = NULL;
    2134             : 
    2135             :   /* Now try a third time. Since the other one is down, we'll get a different
    2136             :    * (still primary) guard.
    2137             :    */
    2138           3 :   update_approx_time(start+60);
    2139           3 :   r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2140             :                                    &node, &guard);
    2141           3 :   tt_int_op(r, OP_EQ, 0);
    2142           3 :   tt_assert(node);
    2143           3 :   tt_assert(guard);
    2144           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    2145           3 :   g = entry_guard_handle_get(guard->guard);
    2146           3 :   tt_assert(g);
    2147           3 :   tt_ptr_op(g, OP_NE, g_prev);
    2148           3 :   tt_mem_op(g->identity, OP_EQ, node->identity, DIGEST_LEN);
    2149           3 :   tt_mem_op(g->identity, OP_NE, g_prev->identity, DIGEST_LEN);
    2150           3 :   tt_int_op(g->is_primary, OP_EQ, 1);
    2151           3 :   tt_i64_op(g->last_tried_to_connect, OP_EQ, start+60);
    2152           3 :   tt_int_op(g->confirmed_idx, OP_EQ, -1); // not confirmed now.
    2153             : 
    2154             :   /* Call this one up; watch it get confirmed. */
    2155           3 :   update_approx_time(start+90);
    2156           3 :   u = entry_guard_succeeded(&guard);
    2157           3 :   tt_int_op(u, OP_EQ, GUARD_USABLE_NOW);
    2158           3 :   tt_assert(guard);
    2159           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_COMPLETE);
    2160           3 :   g = entry_guard_handle_get(guard->guard);
    2161           3 :   tt_assert(g);
    2162           3 :   tt_int_op(g->is_reachable, OP_EQ, GUARD_REACHABLE_YES);
    2163           3 :   tt_int_op(g->confirmed_idx, OP_EQ, 1);
    2164             : 
    2165           3 :  done:
    2166           3 :   guard_selection_free(gs);
    2167           3 :   circuit_guard_state_free(guard);
    2168           3 : }
    2169             : 
    2170             : static void
    2171           3 : test_entry_guard_select_for_circuit_highlevel_confirm_other(void *arg)
    2172             : {
    2173           3 :   (void) arg;
    2174           3 :   const int N_PRIMARY = DFLT_N_PRIMARY_GUARDS;
    2175             : 
    2176             :   /* At the start, we have no confirmed guards.  We'll mark the primary guards
    2177             :    * down, then confirm something else.  As soon as we do, it should become
    2178             :    * primary, and we should get it next time. */
    2179             : 
    2180           3 :   time_t start = approx_time();
    2181           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    2182           3 :   circuit_guard_state_t *guard = NULL;
    2183           3 :   int i, r;
    2184           3 :   const node_t *node = NULL;
    2185           3 :   guard_usable_t u;
    2186             : 
    2187             :   /* Declare that we're on the internet. */
    2188           3 :   entry_guards_note_internet_connectivity(gs);
    2189             : 
    2190             :   /* Primary guards are down! */
    2191          15 :   for (i = 0; i < N_PRIMARY; ++i) {
    2192           9 :     r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2193             :                                      &node, &guard);
    2194           9 :     tt_assert(node);
    2195           9 :     tt_assert(guard);
    2196           9 :     tt_int_op(r, OP_EQ, 0);
    2197           9 :     tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    2198           9 :     entry_guard_failed(&guard);
    2199           9 :     circuit_guard_state_free(guard);
    2200           9 :     guard = NULL;
    2201           9 :     node = NULL;
    2202             :   }
    2203             : 
    2204             :   /* Next guard should be non-primary. */
    2205           3 :   node = NULL;
    2206           3 :   r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2207             :                                    &node, &guard);
    2208           3 :   tt_assert(node);
    2209           3 :   tt_assert(guard);
    2210           3 :   tt_int_op(r, OP_EQ, 0);
    2211           3 :   entry_guard_t *g = entry_guard_handle_get(guard->guard);
    2212           3 :   tt_assert(g);
    2213           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    2214           3 :   tt_int_op(g->confirmed_idx, OP_EQ, -1);
    2215           3 :   tt_int_op(g->is_primary, OP_EQ, 0);
    2216           3 :   tt_int_op(g->is_pending, OP_EQ, 1);
    2217           3 :   (void)start;
    2218             : 
    2219           3 :   u = entry_guard_succeeded(&guard);
    2220             :   /* We're on the internet (by fiat), so this guard will get called "confirmed"
    2221             :    * and should immediately become primary.
    2222             :    */
    2223           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_COMPLETE);
    2224           3 :   tt_assert(u == GUARD_USABLE_NOW);
    2225           3 :   tt_int_op(g->confirmed_idx, OP_EQ, 0);
    2226           3 :   tt_int_op(g->is_primary, OP_EQ, 1);
    2227           3 :   tt_int_op(g->is_pending, OP_EQ, 0);
    2228             : 
    2229           3 :  done:
    2230           3 :   guard_selection_free(gs);
    2231           3 :   circuit_guard_state_free(guard);
    2232           3 : }
    2233             : 
    2234             : static void
    2235           3 : test_entry_guard_select_for_circuit_highlevel_primary_retry(void *arg)
    2236             : {
    2237           3 :   (void) arg;
    2238           3 :   const int N_PRIMARY = DFLT_N_PRIMARY_GUARDS;
    2239             : 
    2240             :   /* At the start, we have no confirmed guards.  We'll mark the primary guards
    2241             :    * down, then confirm something else.  As soon as we do, it should become
    2242             :    * primary, and we should get it next time. */
    2243             : 
    2244           3 :   time_t start = approx_time();
    2245           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    2246           3 :   circuit_guard_state_t *guard = NULL, *guard2 = NULL;
    2247           3 :   int i, r;
    2248           3 :   const node_t *node = NULL;
    2249           3 :   entry_guard_t *g;
    2250           3 :   guard_usable_t u;
    2251             : 
    2252             :   /* Declare that we're on the internet. */
    2253           3 :   entry_guards_note_internet_connectivity(gs);
    2254             : 
    2255             :   /* Make primary guards confirmed (so they won't be superseded by a later
    2256             :    * guard), then mark them down. */
    2257          15 :   for (i = 0; i < N_PRIMARY; ++i) {
    2258           9 :     r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2259             :                                      &node, &guard);
    2260           9 :     tt_assert(node);
    2261           9 :     tt_assert(guard);
    2262           9 :     tt_int_op(r, OP_EQ, 0);
    2263           9 :     tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    2264           9 :     g = entry_guard_handle_get(guard->guard);
    2265           9 :     make_guard_confirmed(gs, g);
    2266           9 :     tt_int_op(g->is_primary, OP_EQ, 1);
    2267           9 :     entry_guard_failed(&guard);
    2268           9 :     circuit_guard_state_free(guard);
    2269           9 :     tt_int_op(g->is_reachable, OP_EQ, GUARD_REACHABLE_NO);
    2270           9 :     guard = NULL;
    2271           9 :     node = NULL;
    2272             :   }
    2273             : 
    2274             :   /* Get another guard that we might try. */
    2275           3 :   r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2276             :                                    &node, &guard);
    2277           3 :   tt_assert(node);
    2278           3 :   tt_assert(guard);
    2279           3 :   tt_int_op(r, OP_EQ, 0);
    2280           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    2281           3 :   g = entry_guard_handle_get(guard->guard);
    2282           3 :   tt_int_op(g->is_primary, OP_EQ, 0);
    2283             : 
    2284           3 :   tt_assert(entry_guards_all_primary_guards_are_down(gs));
    2285             : 
    2286             :   /* And an hour has passed ... */
    2287           3 :   update_approx_time(start + 3600);
    2288             : 
    2289             :   /* Say that guard has succeeded! */
    2290           3 :   u = entry_guard_succeeded(&guard);
    2291           3 :   tt_int_op(u, OP_EQ, GUARD_MAYBE_USABLE_LATER);
    2292           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD);
    2293           3 :   g = entry_guard_handle_get(guard->guard);
    2294             : 
    2295             :   /* The primary guards should have been marked up! */
    2296          12 :   SMARTLIST_FOREACH(gs->primary_entry_guards, entry_guard_t *, pg, {
    2297             :     tt_int_op(pg->is_primary, OP_EQ, 1);
    2298             :     tt_ptr_op(g, OP_NE, pg);
    2299             :     tt_int_op(pg->is_reachable, OP_EQ, GUARD_REACHABLE_MAYBE);
    2300             :   });
    2301             : 
    2302             :   /* Have a circuit to a primary guard succeed. */
    2303           3 :   r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2304             :                                    &node, &guard2);
    2305           3 :   tt_int_op(r, OP_EQ, 0);
    2306           3 :   tt_int_op(guard2->state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    2307           3 :   u = entry_guard_succeeded(&guard2);
    2308           3 :   tt_assert(u == GUARD_USABLE_NOW);
    2309           3 :   tt_int_op(guard2->state, OP_EQ, GUARD_CIRC_STATE_COMPLETE);
    2310             : 
    2311           3 :   tt_assert(! entry_guards_all_primary_guards_are_down(gs));
    2312             : 
    2313           3 :  done:
    2314           3 :   guard_selection_free(gs);
    2315           3 :   circuit_guard_state_free(guard);
    2316           3 :   circuit_guard_state_free(guard2);
    2317           3 : }
    2318             : 
    2319             : static void
    2320           3 : test_entry_guard_select_and_cancel(void *arg)
    2321             : {
    2322           3 :   (void) arg;
    2323           3 :   const int N_PRIMARY = DFLT_N_PRIMARY_GUARDS;
    2324           3 :   int i,r;
    2325           3 :   const node_t *node = NULL;
    2326           3 :   circuit_guard_state_t *guard;
    2327           3 :   guard_selection_t *gs = guard_selection_new("default", GS_TYPE_NORMAL);
    2328           3 :   entry_guard_t *g;
    2329             : 
    2330             :   /* Once more, we mark all the primary guards down. */
    2331           3 :   entry_guards_note_internet_connectivity(gs);
    2332          15 :   for (i = 0; i < N_PRIMARY; ++i) {
    2333           9 :     r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2334             :                                      &node, &guard);
    2335           9 :     tt_int_op(r, OP_EQ, 0);
    2336           9 :     tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_ON_COMPLETION);
    2337           9 :     g = entry_guard_handle_get(guard->guard);
    2338           9 :     tt_int_op(g->is_primary, OP_EQ, 1);
    2339           9 :     tt_int_op(g->is_pending, OP_EQ, 0);
    2340           9 :     make_guard_confirmed(gs, g);
    2341           9 :     entry_guard_failed(&guard);
    2342           9 :     circuit_guard_state_free(guard);
    2343           9 :     guard = NULL;
    2344           9 :     node = NULL;
    2345             :   }
    2346             : 
    2347           3 :   tt_assert(entry_guards_all_primary_guards_are_down(gs));
    2348             : 
    2349             :   /* Now get another guard we could try... */
    2350           3 :   r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2351             :                                    &node, &guard);
    2352           3 :   tt_assert(node);
    2353           3 :   tt_assert(guard);
    2354           3 :   tt_int_op(r, OP_EQ, 0);
    2355           3 :   tt_int_op(guard->state, OP_EQ, GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    2356           3 :   g = entry_guard_handle_get(guard->guard);
    2357           3 :   tt_int_op(g->is_primary, OP_EQ, 0);
    2358           3 :   tt_int_op(g->is_pending, OP_EQ, 1);
    2359             : 
    2360             :   /* Whoops! We should never have asked for this guard. Cancel the request! */
    2361           3 :   entry_guard_cancel(&guard);
    2362           3 :   tt_ptr_op(guard, OP_EQ, NULL);
    2363           3 :   tt_int_op(g->is_primary, OP_EQ, 0);
    2364           3 :   tt_int_op(g->is_pending, OP_EQ, 0);
    2365             : 
    2366           3 :  done:
    2367           3 :   guard_selection_free(gs);
    2368           3 :   circuit_guard_state_free(guard);
    2369           3 : }
    2370             : 
    2371             : static void
    2372           3 : test_entry_guard_drop_guards(void *arg)
    2373             : {
    2374           3 :   (void) arg;
    2375           3 :   int r;
    2376           3 :   const node_t *node = NULL;
    2377           3 :   circuit_guard_state_t *guard;
    2378           3 :   guard_selection_t *gs = get_guard_selection_info();
    2379             : 
    2380             :   // Pick a guard, to get things set up.
    2381           3 :   r = entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2382             :                                    &node, &guard);
    2383           3 :   tt_int_op(r, OP_EQ, 0);
    2384           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_GE,
    2385             :             DFLT_MIN_FILTERED_SAMPLE_SIZE);
    2386           3 :   tt_ptr_op(gs, OP_EQ, get_guard_selection_info());
    2387             : 
    2388             :   // Drop all the guards!  (This is a bad idea....)
    2389           3 :   remove_all_entry_guards_for_guard_selection(gs);
    2390           3 :   gs = get_guard_selection_info();
    2391           3 :   tt_int_op(smartlist_len(gs->sampled_entry_guards), OP_EQ, 0);
    2392           3 :   tt_int_op(smartlist_len(gs->primary_entry_guards), OP_EQ, 0);
    2393           3 :   tt_int_op(smartlist_len(gs->confirmed_entry_guards), OP_EQ, 0);
    2394             : 
    2395           3 :  done:
    2396           3 :   circuit_guard_state_free(guard);
    2397           3 :   guard_selection_free(gs);
    2398           3 : }
    2399             : 
    2400             : /* Unit test setup function: Create a fake network, and set everything up
    2401             :  * for testing the upgrade-a-waiting-circuit code. */
    2402             : typedef struct {
    2403             :   guard_selection_t *gs;
    2404             :   time_t start;
    2405             :   circuit_guard_state_t *guard1_state;
    2406             :   circuit_guard_state_t *guard2_state;
    2407             :   entry_guard_t *guard1;
    2408             :   entry_guard_t *guard2;
    2409             :   origin_circuit_t *circ1;
    2410             :   origin_circuit_t *circ2;
    2411             :   smartlist_t *all_origin_circuits;
    2412             : } upgrade_circuits_data_t;
    2413             : static void *
    2414          27 : upgrade_circuits_setup(const struct testcase_t *testcase)
    2415             : {
    2416          27 :   upgrade_circuits_data_t *data = tor_malloc_zero(sizeof(*data));
    2417          54 :   guard_selection_t *gs = data->gs =
    2418          27 :     guard_selection_new("default", GS_TYPE_NORMAL);
    2419          27 :   circuit_guard_state_t *guard;
    2420          27 :   const node_t *node;
    2421          27 :   entry_guard_t *g;
    2422          27 :   int i;
    2423          27 :   const int N_PRIMARY = DFLT_N_PRIMARY_GUARDS;
    2424          27 :   const char *argument = testcase->setup_data;
    2425          27 :   const int make_circ1_succeed = strstr(argument, "c1-done") != NULL;
    2426          27 :   const int make_circ2_succeed = strstr(argument, "c2-done") != NULL;
    2427             : 
    2428          27 :   big_fake_network_setup(testcase);
    2429             : 
    2430             :   /* We're going to set things up in a state where a circuit will be ready to
    2431             :    * be upgraded.  Each test can make a single change (or not) that should
    2432             :    * block the upgrade.
    2433             :    */
    2434             : 
    2435             :   /* First, make all the primary guards confirmed, and down. */
    2436          27 :   data->start = approx_time();
    2437          27 :   entry_guards_note_internet_connectivity(gs);
    2438         135 :   for (i = 0; i < N_PRIMARY; ++i) {
    2439          81 :     entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL, &node, &guard);
    2440          81 :     g = entry_guard_handle_get(guard->guard);
    2441          81 :     make_guard_confirmed(gs, g);
    2442          81 :     entry_guard_failed(&guard);
    2443          81 :     circuit_guard_state_free(guard);
    2444             :   }
    2445             : 
    2446             :   /* Grab another couple of guards */
    2447          27 :   data->all_origin_circuits = smartlist_new();
    2448             : 
    2449          27 :   update_approx_time(data->start + 27);
    2450          27 :   entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2451             :                                &node, &data->guard1_state);
    2452          27 :   origin_circuit_t *circ;
    2453          27 :   data->circ1 = circ = origin_circuit_new();
    2454          27 :   circ->base_.purpose = CIRCUIT_PURPOSE_C_GENERAL;
    2455          27 :   circ->guard_state = data->guard1_state;
    2456          27 :   smartlist_add(data->all_origin_circuits, circ);
    2457             : 
    2458          27 :   update_approx_time(data->start + 30);
    2459          27 :   entry_guard_pick_for_circuit(gs, GUARD_USAGE_TRAFFIC, NULL,
    2460             :                                &node, &data->guard2_state);
    2461          27 :   data->circ2 = circ = origin_circuit_new();
    2462          27 :   circ->base_.purpose = CIRCUIT_PURPOSE_C_GENERAL;
    2463          27 :   circ->guard_state = data->guard2_state;
    2464          27 :   smartlist_add(data->all_origin_circuits, circ);
    2465             : 
    2466          27 :   data->guard1 = entry_guard_handle_get(data->guard1_state->guard);
    2467          27 :   data->guard2 = entry_guard_handle_get(data->guard2_state->guard);
    2468          27 :   tor_assert(data->guard1 != data->guard2);
    2469          27 :   tor_assert(data->guard1_state->state ==
    2470             :              GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    2471          27 :   tor_assert(data->guard2_state->state ==
    2472             :              GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD);
    2473             : 
    2474          27 :   guard_usable_t r;
    2475          27 :   update_approx_time(data->start + 32);
    2476          27 :   if (make_circ1_succeed) {
    2477          18 :     r = entry_guard_succeeded(&data->guard1_state);
    2478          18 :     tor_assert(r == GUARD_MAYBE_USABLE_LATER);
    2479          18 :     tor_assert(data->guard1_state->state ==
    2480             :                GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD);
    2481             :   }
    2482          27 :   update_approx_time(data->start + 33);
    2483          27 :   if (make_circ2_succeed) {
    2484          21 :     r = entry_guard_succeeded(&data->guard2_state);
    2485          21 :     tor_assert(r == GUARD_MAYBE_USABLE_LATER);
    2486          21 :     tor_assert(data->guard2_state->state ==
    2487             :                GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD);
    2488             :   }
    2489             : 
    2490          27 :   return data;
    2491             : }
    2492             : static int
    2493          27 : upgrade_circuits_cleanup(const struct testcase_t *testcase, void *ptr)
    2494             : {
    2495          27 :   upgrade_circuits_data_t *data = ptr;
    2496             :   // circuit_guard_state_free(data->guard1_state); // held in circ1
    2497             :   // circuit_guard_state_free(data->guard2_state); // held in circ2
    2498          27 :   guard_selection_free(data->gs);
    2499          27 :   smartlist_free(data->all_origin_circuits);
    2500          27 :   circuit_free_(TO_CIRCUIT(data->circ1));
    2501          27 :   circuit_free_(TO_CIRCUIT(data->circ2));
    2502          27 :   tor_free(data);
    2503          27 :   return big_fake_network_cleanup(testcase, NULL);
    2504             : }
    2505             : 
    2506             : static void
    2507           3 : test_entry_guard_upgrade_a_circuit(void *arg)
    2508             : {
    2509           3 :   upgrade_circuits_data_t *data = arg;
    2510             : 
    2511             :   /* This is the easy case: we have no COMPLETED circuits, all the
    2512             :    * primary guards are down, we have two WAITING circuits: one will
    2513             :    * get upgraded to COMPLETED!  (The one that started first.)
    2514             :    */
    2515             : 
    2516           3 :   smartlist_t *result = smartlist_new();
    2517           3 :   int r;
    2518           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2519           3 :                                             data->all_origin_circuits,
    2520             :                                             result);
    2521           3 :   tt_int_op(r, OP_EQ, 1);
    2522           3 :   tt_int_op(smartlist_len(result), OP_EQ, 1);
    2523           3 :   origin_circuit_t *oc = smartlist_get(result, 0);
    2524             : 
    2525             :   /* circ1 was started first, so we'll get told to ugrade it... */
    2526           3 :   tt_ptr_op(oc, OP_EQ, data->circ1);
    2527             : 
    2528             :   /* And the guard state should be complete */
    2529           3 :   tt_ptr_op(data->guard1_state, OP_NE, NULL);
    2530           3 :   tt_int_op(data->guard1_state->state, OP_EQ, GUARD_CIRC_STATE_COMPLETE);
    2531             : 
    2532           3 :  done:
    2533           3 :   smartlist_free(result);
    2534           3 : }
    2535             : 
    2536             : static void
    2537           3 : test_entry_guard_upgrade_blocked_by_live_primary_guards(void *arg)
    2538             : {
    2539           3 :   upgrade_circuits_data_t *data = arg;
    2540             : 
    2541             :   /* If any primary guards might be up, we can't upgrade any waiting
    2542             :    * circuits.
    2543             :    */
    2544           3 :   mark_primary_guards_maybe_reachable(data->gs);
    2545             : 
    2546           3 :   smartlist_t *result = smartlist_new();
    2547           3 :   int r;
    2548           3 :   setup_capture_of_logs(LOG_DEBUG);
    2549           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2550           3 :                                             data->all_origin_circuits,
    2551             :                                             result);
    2552           3 :   tt_int_op(r, OP_EQ, 0);
    2553           3 :   tt_int_op(smartlist_len(result), OP_EQ, 0);
    2554           3 :   expect_log_msg_containing("not all primary guards were definitely down.");
    2555             : 
    2556           3 :  done:
    2557           3 :   teardown_capture_of_logs();
    2558           3 :   smartlist_free(result);
    2559           3 : }
    2560             : 
    2561             : static void
    2562           3 : test_entry_guard_upgrade_blocked_by_lack_of_waiting_circuits(void *arg)
    2563             : {
    2564           3 :   upgrade_circuits_data_t *data = arg;
    2565             : 
    2566             :   /* If no circuits are waiting, we can't upgrade anything.  (The test
    2567             :    * setup in this case was told not to make any of the circuits "waiting".)
    2568             :    */
    2569           3 :   smartlist_t *result = smartlist_new();
    2570           3 :   int r;
    2571           3 :   setup_capture_of_logs(LOG_DEBUG);
    2572           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2573           3 :                                             data->all_origin_circuits,
    2574             :                                             result);
    2575           3 :   tt_int_op(r, OP_EQ, 0);
    2576           3 :   tt_int_op(smartlist_len(result), OP_EQ, 0);
    2577           3 :   expect_log_msg_containing("Considered upgrading guard-stalled circuits, "
    2578           3 :                             "but didn't find any.");
    2579             : 
    2580           3 :  done:
    2581           3 :   teardown_capture_of_logs();
    2582           3 :   smartlist_free(result);
    2583           3 : }
    2584             : 
    2585             : static void
    2586           3 : test_entry_guard_upgrade_blocked_by_better_circ_complete(void *arg)
    2587             : {
    2588           3 :   upgrade_circuits_data_t *data = arg;
    2589             : 
    2590             :   /* We'll run through the logic of upgrade_a_circuit below...
    2591             :    * and then try again to make sure that circ2 isn't also upgraded.
    2592             :    */
    2593             : 
    2594           3 :   smartlist_t *result = smartlist_new();
    2595           3 :   int r;
    2596           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2597           3 :                                             data->all_origin_circuits,
    2598             :                                             result);
    2599           3 :   tt_int_op(r, OP_EQ, 1);
    2600           3 :   tt_int_op(smartlist_len(result), OP_EQ, 1);
    2601           3 :   origin_circuit_t *oc = smartlist_get(result, 0);
    2602           3 :   tt_ptr_op(oc, OP_EQ, data->circ1);
    2603           3 :   tt_ptr_op(data->guard1_state, OP_NE, NULL);
    2604           3 :   tt_int_op(data->guard1_state->state, OP_EQ, GUARD_CIRC_STATE_COMPLETE);
    2605             : 
    2606             :   /* Now, try again. Make sure that circ2 isn't upgraded. */
    2607           3 :   smartlist_clear(result);
    2608           3 :   setup_capture_of_logs(LOG_DEBUG);
    2609           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2610           3 :                                             data->all_origin_circuits,
    2611             :                                             result);
    2612           3 :   tt_int_op(r, OP_EQ, 0);
    2613           3 :   tt_int_op(smartlist_len(result), OP_EQ, 0);
    2614           3 :   expect_log_msg_containing("At least one complete circuit had higher "
    2615           3 :                             "priority, so not upgrading.");
    2616             : 
    2617           3 :  done:
    2618           3 :   teardown_capture_of_logs();
    2619           3 :   smartlist_free(result);
    2620           3 : }
    2621             : 
    2622             : static void
    2623           3 : test_entry_guard_upgrade_not_blocked_by_restricted_circ_complete(void *arg)
    2624             : {
    2625           3 :   upgrade_circuits_data_t *data = arg;
    2626             : 
    2627             :   /* Once more, let circ1 become complete. But this time, we'll claim
    2628             :    * that circ2 was restricted to not use the same guard as circ1. */
    2629           6 :   data->guard2_state->restrictions =
    2630           3 :     guard_create_exit_restriction((uint8_t*)data->guard1->identity);
    2631             : 
    2632           3 :   smartlist_t *result = smartlist_new();
    2633           3 :   int r;
    2634           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2635           3 :                                             data->all_origin_circuits,
    2636             :                                             result);
    2637           3 :   tt_int_op(r, OP_EQ, 1);
    2638           3 :   tt_int_op(smartlist_len(result), OP_EQ, 1);
    2639           3 :   origin_circuit_t *oc = smartlist_get(result, 0);
    2640           3 :   tt_ptr_op(oc, OP_EQ, data->circ1);
    2641           3 :   tt_ptr_op(data->guard1_state, OP_NE, NULL);
    2642           3 :   tt_int_op(data->guard1_state->state, OP_EQ, GUARD_CIRC_STATE_COMPLETE);
    2643             : 
    2644             :   /* Now, we try again. Since circ2 has a restriction that circ1 doesn't obey,
    2645             :    * circ2 _is_ eligible for upgrade. */
    2646           3 :   smartlist_clear(result);
    2647           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2648           3 :                                             data->all_origin_circuits,
    2649             :                                             result);
    2650           3 :   tt_int_op(r, OP_EQ, 1);
    2651           3 :   tt_int_op(smartlist_len(result), OP_EQ, 1);
    2652           3 :   origin_circuit_t *oc2 = smartlist_get(result, 0);
    2653           3 :   tt_ptr_op(oc2, OP_EQ, data->circ2);
    2654             : 
    2655           3 :  done:
    2656           3 :   smartlist_free(result);
    2657           3 : }
    2658             : 
    2659             : static void
    2660           3 : test_entry_guard_upgrade_not_blocked_by_worse_circ_complete(void *arg)
    2661             : {
    2662           3 :   upgrade_circuits_data_t *data = arg;
    2663           3 :   smartlist_t *result = smartlist_new();
    2664             :   /* here we manually make circ2 COMPLETE, and make sure that circ1
    2665             :    * gets made complete anyway, since guard1 has higher priority
    2666             :    */
    2667           3 :   update_approx_time(data->start + 300);
    2668           3 :   data->guard2_state->state = GUARD_CIRC_STATE_COMPLETE;
    2669           3 :   data->guard2_state->state_set_at = approx_time();
    2670           3 :   update_approx_time(data->start + 301);
    2671             : 
    2672             :   /* Now, try again. Make sure that circ1 is approved. */
    2673           3 :   int r;
    2674           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2675           3 :                                             data->all_origin_circuits,
    2676             :                                             result);
    2677           3 :   tt_int_op(r, OP_EQ, 1);
    2678           3 :   tt_int_op(smartlist_len(result), OP_EQ, 1);
    2679           3 :   origin_circuit_t *oc = smartlist_get(result, 0);
    2680           3 :   tt_ptr_op(oc, OP_EQ, data->circ1);
    2681             : 
    2682           3 :  done:
    2683           3 :   smartlist_free(result);
    2684           3 : }
    2685             : 
    2686             : static void
    2687           3 : test_entry_guard_upgrade_blocked_by_better_circ_pending(void *arg)
    2688             : {
    2689           3 :   upgrade_circuits_data_t *data = arg;
    2690             : 
    2691             :   /* circ2 is done, but circ1 is still pending. Since circ1 is better,
    2692             :    * we won't upgrade circ2. */
    2693             : 
    2694             :   /* XXXX Prop271 -- this is a kludge.  I'm making sure circ1 _is_ better,
    2695             :    * by messing with the guards' confirmed_idx */
    2696           3 :   make_guard_confirmed(data->gs, data->guard1);
    2697             :   {
    2698           3 :     int tmp;
    2699           3 :     tmp = data->guard1->confirmed_idx;
    2700           3 :     data->guard1->confirmed_idx = data->guard2->confirmed_idx;
    2701           3 :     data->guard2->confirmed_idx = tmp;
    2702             :   }
    2703             : 
    2704           3 :   smartlist_t *result = smartlist_new();
    2705           3 :   setup_capture_of_logs(LOG_DEBUG);
    2706           3 :   int r;
    2707           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2708           3 :                                             data->all_origin_circuits,
    2709             :                                             result);
    2710           3 :   tt_int_op(r, OP_EQ, 0);
    2711           3 :   tt_int_op(smartlist_len(result), OP_EQ, 0);
    2712           3 :   expect_log_msg_containing("but 1 pending circuit(s) had higher guard "
    2713           3 :                             "priority, so not upgrading.");
    2714             : 
    2715           3 :  done:
    2716           3 :   teardown_capture_of_logs();
    2717           3 :   smartlist_free(result);
    2718           3 : }
    2719             : 
    2720             : static void
    2721           3 : test_entry_guard_upgrade_not_blocked_by_restricted_circ_pending(void *arg)
    2722             : {
    2723           3 :   upgrade_circuits_data_t *data = arg;
    2724             :   /* circ2 is done, but circ1 is still pending. But when there is a
    2725             :      restriction on circ2 that circ1 can't satisfy, circ1 can't block
    2726             :      circ2. */
    2727             : 
    2728             :   /* XXXX Prop271 -- this is a kludge.  I'm making sure circ1 _is_ better,
    2729             :    * by messing with the guards' confirmed_idx */
    2730           3 :   make_guard_confirmed(data->gs, data->guard1);
    2731             :   {
    2732           3 :     int tmp;
    2733           3 :     tmp = data->guard1->confirmed_idx;
    2734           3 :     data->guard1->confirmed_idx = data->guard2->confirmed_idx;
    2735           3 :     data->guard2->confirmed_idx = tmp;
    2736             :   }
    2737             : 
    2738           6 :   data->guard2_state->restrictions =
    2739           3 :     guard_create_exit_restriction((uint8_t*)data->guard1->identity);
    2740             : 
    2741           3 :   smartlist_t *result = smartlist_new();
    2742           3 :   int r;
    2743           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2744           3 :                                             data->all_origin_circuits,
    2745             :                                             result);
    2746           3 :   tt_int_op(r, OP_EQ, 1);
    2747           3 :   tt_int_op(smartlist_len(result), OP_EQ, 1);
    2748           3 :   origin_circuit_t *oc = smartlist_get(result, 0);
    2749           3 :   tt_ptr_op(oc, OP_EQ, data->circ2);
    2750             : 
    2751           3 :  done:
    2752           3 :   smartlist_free(result);
    2753           3 : }
    2754             : 
    2755             : static void
    2756           3 : test_entry_guard_upgrade_not_blocked_by_worse_circ_pending(void *arg)
    2757             : {
    2758           3 :   upgrade_circuits_data_t *data = arg;
    2759             : 
    2760             :   /* circ1 is done, but circ2 is still pending. Since circ1 is better,
    2761             :    * we will upgrade it. */
    2762           3 :   smartlist_t *result = smartlist_new();
    2763           3 :   int r;
    2764           6 :   r = entry_guards_upgrade_waiting_circuits(data->gs,
    2765           3 :                                             data->all_origin_circuits,
    2766             :                                             result);
    2767           3 :   tt_int_op(r, OP_EQ, 1);
    2768           3 :   tt_int_op(smartlist_len(result), OP_EQ, 1);
    2769           3 :   origin_circuit_t *oc = smartlist_get(result, 0);
    2770           3 :   tt_ptr_op(oc, OP_EQ, data->circ1);
    2771             : 
    2772           3 :  done:
    2773           3 :   smartlist_free(result);
    2774           3 : }
    2775             : 
    2776             : static void
    2777           1 : test_entry_guard_should_expire_waiting(void *arg)
    2778             : {
    2779           1 :   (void)arg;
    2780           1 :   circuit_guard_state_t *fake_state = tor_malloc_zero(sizeof(*fake_state));
    2781             :   /* We'll leave "guard" unset -- it won't matter here. */
    2782             : 
    2783             :   /* No state? Can't expire. */
    2784           1 :   tt_assert(! entry_guard_state_should_expire(NULL));
    2785             : 
    2786             :   /* Let's try one that expires. */
    2787           1 :   fake_state->state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
    2788           2 :   fake_state->state_set_at =
    2789           1 :     approx_time() - DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT - 1;
    2790             : 
    2791           1 :   tt_assert(entry_guard_state_should_expire(fake_state));
    2792             : 
    2793             :   /* But it wouldn't expire if we changed the state. */
    2794           1 :   fake_state->state = GUARD_CIRC_STATE_USABLE_IF_NO_BETTER_GUARD;
    2795           1 :   tt_assert(! entry_guard_state_should_expire(fake_state));
    2796             : 
    2797             :   /* And it wouldn't have expired a few seconds ago. */
    2798           1 :   fake_state->state = GUARD_CIRC_STATE_WAITING_FOR_BETTER_GUARD;
    2799           2 :   fake_state->state_set_at =
    2800           1 :     approx_time() - DFLT_NONPRIMARY_GUARD_IDLE_TIMEOUT + 5;
    2801           1 :   tt_assert(! entry_guard_state_should_expire(fake_state));
    2802             : 
    2803           1 :  done:
    2804           1 :   tor_free(fake_state);
    2805           1 : }
    2806             : 
    2807             : /** Test that the number of primary guards can be controlled using torrc */
    2808             : static void
    2809           1 : test_entry_guard_number_of_primaries(void *arg)
    2810             : {
    2811           1 :   (void) arg;
    2812             : 
    2813             :   /* Get default value */
    2814           1 :   tt_int_op(get_n_primary_guards(), OP_EQ, DFLT_N_PRIMARY_GUARDS);
    2815             : 
    2816             :   /* Set number of primaries using torrc */
    2817           1 :   get_options_mutable()->NumPrimaryGuards = 42;
    2818           1 :   tt_int_op(get_n_primary_guards(), OP_EQ, 42);
    2819             : 
    2820           1 :  done:
    2821           1 :   ;
    2822           1 : }
    2823             : 
    2824             : static void
    2825           3 : mock_directory_initiate_request(directory_request_t *req)
    2826             : {
    2827           3 :   if (req->guard_state) {
    2828           3 :     circuit_guard_state_free(req->guard_state);
    2829             :   }
    2830           3 : }
    2831             : 
    2832             : static networkstatus_t *mock_ns_val = NULL;
    2833             : static networkstatus_t *
    2834           9 : mock_ns_get_by_flavor(consensus_flavor_t f)
    2835             : {
    2836           9 :   (void)f;
    2837           9 :   return mock_ns_val;
    2838             : }
    2839             : 
    2840             : /** Test that when we fetch microdescriptors we skip guards that have
    2841             :  *  previously failed to serve us needed microdescriptors. */
    2842             : static void
    2843           3 : test_entry_guard_outdated_dirserver_exclusion(void *arg)
    2844             : {
    2845           3 :   int retval;
    2846           3 :   response_handler_args_t *args = NULL;
    2847           3 :   dir_connection_t *conn = NULL;
    2848           3 :   (void) arg;
    2849             : 
    2850             :   /* Test prep: Make a new guard selection */
    2851           3 :   guard_selection_t *gs = get_guard_selection_by_name("default",
    2852             :                                                       GS_TYPE_NORMAL, 1);
    2853             : 
    2854             :   /* ... we want to use entry guards */
    2855           3 :   or_options_t *options = get_options_mutable();
    2856           3 :   options->UseEntryGuards = 1;
    2857           3 :   options->UseBridges = 0;
    2858             : 
    2859             :   /* ... prepare some md digests we want to download in the future */
    2860           3 :   smartlist_t *digests = smartlist_new();
    2861           3 :   const char *prose = "unhurried and wise, we perceive.";
    2862          63 :   for (int i = 0; i < 20; i++) {
    2863          60 :     smartlist_add(digests, (char*)prose);
    2864             :   }
    2865             : 
    2866           3 :   tt_int_op(smartlist_len(digests), OP_EQ, 20);
    2867             : 
    2868             :   /* ... now mock some functions */
    2869           3 :   mock_ns_val = tor_malloc_zero(sizeof(networkstatus_t));
    2870           3 :   MOCK(networkstatus_get_latest_consensus_by_flavor, mock_ns_get_by_flavor);
    2871           3 :   MOCK(directory_initiate_request, mock_directory_initiate_request);
    2872             : 
    2873             :   /* Test logic:
    2874             :    *  0. Create a proper guard set and primary guard list.
    2875             :    *  1. Pretend to fail microdescriptor fetches from all the primary guards.
    2876             :    *  2. Order another microdescriptor fetch and make sure that primary guards
    2877             :    *     get skipped since they failed previous fetches.
    2878             :    */
    2879             : 
    2880             :   { /* Setup primary guard list */
    2881           3 :     int i;
    2882           3 :     entry_guards_update_primary(gs);
    2883          15 :     for (i = 0; i < DFLT_N_PRIMARY_GUARDS; ++i) {
    2884           9 :       entry_guard_t *guard = smartlist_get(gs->sampled_entry_guards, i);
    2885           9 :       make_guard_confirmed(gs, guard);
    2886             :     }
    2887           3 :     entry_guards_update_primary(gs);
    2888             :   }
    2889             : 
    2890             :   {
    2891             :     /* Fail microdesc fetches with all the primary guards */
    2892           3 :     args = tor_malloc_zero(sizeof(response_handler_args_t));
    2893           3 :     args->status_code = 404;
    2894           3 :     args->reason = NULL;
    2895           3 :     args->body = NULL;
    2896           3 :     args->body_len = 0;
    2897             : 
    2898           3 :     conn = tor_malloc_zero(sizeof(dir_connection_t));
    2899           3 :     conn->requested_resource = tor_strdup("d/jlinblackorigami");
    2900           3 :     conn->base_.purpose = DIR_PURPOSE_FETCH_MICRODESC;
    2901             : 
    2902             :     /* Pretend to fail fetches with all primary guards */
    2903          12 :     SMARTLIST_FOREACH_BEGIN(gs->primary_entry_guards,const entry_guard_t *,g) {
    2904           9 :       memcpy(conn->identity_digest, g->identity, DIGEST_LEN);
    2905             : 
    2906           9 :       retval = handle_response_fetch_microdesc(conn, args);
    2907           9 :       tt_int_op(retval, OP_EQ, 0);
    2908           9 :     } SMARTLIST_FOREACH_END(g);
    2909             :   }
    2910             : 
    2911             :   {
    2912             :     /* Now order the final md download */
    2913           3 :     setup_full_capture_of_logs(LOG_INFO);
    2914           3 :     initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_MICRODESC,
    2915             :                                   digests, 3, 7, 0);
    2916             : 
    2917             :     /* ... and check that because we failed to fetch microdescs from all our
    2918             :      * primaries, we didn't end up selecting a primary for fetching dir info */
    2919           3 :     expect_log_msg_containing("No primary or confirmed guards available.");
    2920           3 :     teardown_capture_of_logs();
    2921             :   }
    2922             : 
    2923           3 :  done:
    2924           3 :   UNMOCK(networkstatus_get_latest_consensus_by_flavor);
    2925           3 :   UNMOCK(directory_initiate_request);
    2926           3 :   smartlist_free(digests);
    2927           3 :   tor_free(mock_ns_val);
    2928           3 :   tor_free(args);
    2929           3 :   if (conn) {
    2930           3 :     tor_free(conn->requested_resource);
    2931           3 :     tor_free(conn);
    2932             :   }
    2933           3 : }
    2934             : 
    2935             : /** Test helper to extend the <b>oc</b> circuit path <b>n</b> times and then
    2936             :  *  ensure that the circuit is now complete. */
    2937             : static void
    2938           6 : helper_extend_circuit_path_n_times(origin_circuit_t *oc, int n)
    2939             : {
    2940           6 :   int retval;
    2941           6 :   int i;
    2942             : 
    2943             :   /* Extend path n times */
    2944          27 :   for (i = 0 ; i < n ; i++) {
    2945          21 :     retval = onion_extend_cpath(oc);
    2946          21 :     tt_int_op(retval, OP_EQ, 0);
    2947          21 :     tt_int_op(circuit_get_cpath_len(oc), OP_EQ, i+1);
    2948             :   }
    2949             : 
    2950             :   /* Now do it one last time and see that circ is complete */
    2951           6 :   retval = onion_extend_cpath(oc);
    2952           6 :   tt_int_op(retval, OP_EQ, 1);
    2953             : 
    2954           6 :  done:
    2955           6 :   ;
    2956           6 : }
    2957             : 
    2958             : /** Test for basic Tor path selection. Makes sure we build 3-hop circuits. */
    2959             : static void
    2960           3 : test_entry_guard_basic_path_selection(void *arg)
    2961             : {
    2962           3 :   (void) arg;
    2963             : 
    2964           3 :   int retval;
    2965             : 
    2966             :   /* Enable entry guards */
    2967           3 :   or_options_t *options = get_options_mutable();
    2968           3 :   options->UseEntryGuards = 1;
    2969             : 
    2970             :   /* disables /16 check since all nodes have the same addr... */
    2971           3 :   options->EnforceDistinctSubnets = 0;
    2972             : 
    2973             :   /* Create our circuit */
    2974           3 :   circuit_t *circ = dummy_origin_circuit_new(30);
    2975           3 :   origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
    2976           3 :   oc->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
    2977             : 
    2978             :   /* First pick the exit and pin it on the build_state */
    2979           3 :   retval = onion_pick_cpath_exit(oc, NULL, 0);
    2980           3 :   tt_int_op(retval, OP_EQ, 0);
    2981             : 
    2982             :   /* Extend path 3 times. First we pick guard, then middle, then exit. */
    2983           3 :   helper_extend_circuit_path_n_times(oc, 3);
    2984             : 
    2985           3 :  done:
    2986           3 :   circuit_free_(circ);
    2987           3 : }
    2988             : 
    2989             : /** Test helper to build an L2 and L3 vanguard list. The vanguard lists
    2990             :  *  produced should be completely disjoint. */
    2991             : static void
    2992           3 : helper_setup_vanguard_list(or_options_t *options)
    2993             : {
    2994           3 :   int i = 0;
    2995             : 
    2996             :   /* Add some nodes to the vanguard L2 list */
    2997           3 :   options->HSLayer2Nodes = routerset_new();
    2998          18 :   for (i = 0; i < 10 ; i += 2) {
    2999          15 :     node_t *vanguard_node = smartlist_get(big_fake_net_nodes, i);
    3000          15 :     tt_assert(vanguard_node->is_possible_guard);
    3001          15 :     routerset_parse(options->HSLayer2Nodes, vanguard_node->rs->nickname, "l2");
    3002             :   }
    3003             :   /* also add some nodes to vanguard L3 list
    3004             :    * (L2 list and L3 list should be disjoint for this test to work) */
    3005           3 :   options->HSLayer3Nodes = routerset_new();
    3006          18 :   for (i = 10; i < 20 ; i += 2) {
    3007          15 :     node_t *vanguard_node = smartlist_get(big_fake_net_nodes, i);
    3008          15 :     tt_assert(vanguard_node->is_possible_guard);
    3009          15 :     routerset_parse(options->HSLayer3Nodes, vanguard_node->rs->nickname, "l3");
    3010             :   }
    3011             : 
    3012           3 :  done:
    3013           3 :   ;
    3014           3 : }
    3015             : 
    3016             : /** Test to ensure that vanguard path selection works properly.  Ensures that
    3017             :  *  default vanguard circuits are 4 hops, and that path selection works
    3018             :  *  correctly given the vanguard settings. */
    3019             : static void
    3020           3 : test_entry_guard_vanguard_path_selection(void *arg)
    3021             : {
    3022           3 :   (void) arg;
    3023             : 
    3024           3 :   int retval;
    3025             : 
    3026             :   /* Enable entry guards */
    3027           3 :   or_options_t *options = get_options_mutable();
    3028           3 :   options->UseEntryGuards = 1;
    3029             : 
    3030             :   /* XXX disables /16 check */
    3031           3 :   options->EnforceDistinctSubnets = 0;
    3032             : 
    3033             :   /* Setup our vanguard list */
    3034           3 :   helper_setup_vanguard_list(options);
    3035             : 
    3036             :   /* Create our circuit */
    3037           3 :   circuit_t *circ = dummy_origin_circuit_new(30);
    3038           3 :   origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(circ);
    3039           3 :   oc->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
    3040           3 :   oc->build_state->is_internal = 1;
    3041             : 
    3042             :   /* Switch circuit purpose to vanguards */
    3043           3 :   circ->purpose = CIRCUIT_PURPOSE_HS_VANGUARDS;
    3044             : 
    3045             :   /* First pick the exit and pin it on the build_state */
    3046           3 :   tt_int_op(oc->build_state->desired_path_len, OP_EQ, 0);
    3047           3 :   retval = onion_pick_cpath_exit(oc, NULL, 0);
    3048           3 :   tt_int_op(retval, OP_EQ, 0);
    3049             : 
    3050             :   /* Ensure that vanguards make 4-hop circuits by default */
    3051           3 :   tt_int_op(oc->build_state->desired_path_len, OP_EQ, 4);
    3052             : 
    3053             :   /* Extend path as many times as needed to have complete circ. */
    3054           3 :   helper_extend_circuit_path_n_times(oc, oc->build_state->desired_path_len);
    3055             : 
    3056             :   /* Test that the cpath linked list is set correctly. */
    3057           3 :   crypt_path_t *l1_node = oc->cpath;
    3058           3 :   crypt_path_t *l2_node = l1_node->next;
    3059           3 :   crypt_path_t *l3_node = l2_node->next;
    3060           3 :   crypt_path_t *l4_node = l3_node->next;
    3061           3 :   crypt_path_t *l1_node_again = l4_node->next;
    3062           3 :   tt_ptr_op(l1_node, OP_EQ, l1_node_again);
    3063             : 
    3064             :   /* Test that L2 is indeed HSLayer2Node */
    3065           6 :   retval = routerset_contains_extendinfo(options->HSLayer2Nodes,
    3066           3 :                                          l2_node->extend_info);
    3067           3 :   tt_int_op(retval, OP_EQ, 4);
    3068             :   /* test that L3 node is _not_ contained in HSLayer2Node */
    3069           6 :   retval = routerset_contains_extendinfo(options->HSLayer2Nodes,
    3070           3 :                                          l3_node->extend_info);
    3071           3 :   tt_int_op(retval, OP_LT, 4);
    3072             : 
    3073             :   /* Test that L3 is indeed HSLayer3Node */
    3074           6 :   retval = routerset_contains_extendinfo(options->HSLayer3Nodes,
    3075           3 :                                          l3_node->extend_info);
    3076           3 :   tt_int_op(retval, OP_EQ, 4);
    3077             :   /* test that L2 node is _not_ contained in HSLayer3Node */
    3078           6 :   retval = routerset_contains_extendinfo(options->HSLayer3Nodes,
    3079           3 :                                          l2_node->extend_info);
    3080           3 :   tt_int_op(retval, OP_LT, 4);
    3081             : 
    3082             :   /* TODO: Test that L1 can be the same as exit. To test this we need start
    3083             :      enforcing EnforceDistinctSubnets again, which means that we need to give
    3084             :      each test node a different address which currently breaks some tests. */
    3085             : 
    3086           3 :  done:
    3087           3 :   circuit_free_(circ);
    3088           3 : }
    3089             : 
    3090             : static const struct testcase_setup_t big_fake_network = {
    3091             :   big_fake_network_setup, big_fake_network_cleanup
    3092             : };
    3093             : 
    3094             : static const struct testcase_setup_t upgrade_circuits = {
    3095             :   upgrade_circuits_setup, upgrade_circuits_cleanup
    3096             : };
    3097             : 
    3098             : #ifndef COCCI
    3099             : #define NO_PREFIX_TEST(name) \
    3100             :   { #name, test_ ## name, 0, NULL, NULL }
    3101             : 
    3102             : #define EN_TEST_BASE(name, fork, setup, arg) \
    3103             :   { #name, test_entry_guard_ ## name, fork, setup, (void*)(arg) }
    3104             : 
    3105             : #define EN_TEST(name)      EN_TEST_BASE(name, 0,       NULL, NULL)
    3106             : #define EN_TEST_FORK(name) EN_TEST_BASE(name, TT_FORK, NULL, NULL)
    3107             : 
    3108             : #define BFN_TEST(name) \
    3109             :   EN_TEST_BASE(name, TT_FORK, &big_fake_network, NULL), \
    3110             :   { #name "_reasonably_future", test_entry_guard_ ## name, TT_FORK, \
    3111             :     &big_fake_network, (void*)(REASONABLY_FUTURE) }, \
    3112             :   { #name "_reasonably_past", test_entry_guard_ ## name, TT_FORK, \
    3113             :     &big_fake_network, (void*)(REASONABLY_PAST) }
    3114             : 
    3115             : #define UPGRADE_TEST(name, arg) \
    3116             :   EN_TEST_BASE(name, TT_FORK, &upgrade_circuits, arg), \
    3117             :   { #name "_reasonably_future", test_entry_guard_ ## name, TT_FORK, \
    3118             :     &upgrade_circuits, (void*)(arg REASONABLY_FUTURE) }, \
    3119             :   { #name "_reasonably_past", test_entry_guard_ ## name, TT_FORK, \
    3120             :     &upgrade_circuits, (void*)(arg REASONABLY_PAST) }
    3121             : #endif /* !defined(COCCI) */
    3122             : 
    3123             : struct testcase_t entrynodes_tests[] = {
    3124             :   NO_PREFIX_TEST(node_preferred_orport),
    3125             :   NO_PREFIX_TEST(entry_guard_describe),
    3126             : 
    3127             :   EN_TEST(randomize_time),
    3128             :   EN_TEST(encode_for_state_minimal),
    3129             :   EN_TEST(encode_for_state_maximal),
    3130             :   EN_TEST(parse_from_state_minimal),
    3131             :   EN_TEST(parse_from_state_maximal),
    3132             :   EN_TEST(parse_from_state_failure),
    3133             :   EN_TEST(parse_from_state_partial_failure),
    3134             : 
    3135             :   EN_TEST_FORK(parse_from_state_full),
    3136             :   EN_TEST_FORK(parse_from_state_broken),
    3137             :   EN_TEST_FORK(get_guard_selection_by_name),
    3138             :   EN_TEST_FORK(number_of_primaries),
    3139             : 
    3140             :   BFN_TEST(choose_selection_initial),
    3141             :   BFN_TEST(add_single_guard),
    3142             :   BFN_TEST(node_filter),
    3143             :   BFN_TEST(expand_sample),
    3144             :   BFN_TEST(expand_sample_small_net),
    3145             :   BFN_TEST(update_from_consensus_status),
    3146             :   BFN_TEST(update_from_consensus_repair),
    3147             :   BFN_TEST(update_from_consensus_remove),
    3148             :   BFN_TEST(confirming_guards),
    3149             :   BFN_TEST(sample_reachable_filtered),
    3150             :   BFN_TEST(sample_reachable_filtered_empty),
    3151             :   BFN_TEST(retry_unreachable),
    3152             :   BFN_TEST(manage_primary),
    3153             :   BFN_TEST(correct_cascading_order),
    3154             : 
    3155             :   EN_TEST_FORK(guard_preferred),
    3156             : 
    3157             :   BFN_TEST(select_for_circuit_no_confirmed),
    3158             :   BFN_TEST(select_for_circuit_confirmed),
    3159             :   BFN_TEST(select_for_circuit_highlevel_primary),
    3160             :   BFN_TEST(select_for_circuit_highlevel_confirm_other),
    3161             :   BFN_TEST(select_for_circuit_highlevel_primary_retry),
    3162             :   BFN_TEST(select_and_cancel),
    3163             :   BFN_TEST(drop_guards),
    3164             :   BFN_TEST(outdated_dirserver_exclusion),
    3165             :   BFN_TEST(basic_path_selection),
    3166             :   BFN_TEST(vanguard_path_selection),
    3167             : 
    3168             :   UPGRADE_TEST(upgrade_a_circuit, "c1-done c2-done"),
    3169             :   UPGRADE_TEST(upgrade_blocked_by_live_primary_guards, "c1-done c2-done"),
    3170             :   UPGRADE_TEST(upgrade_blocked_by_lack_of_waiting_circuits, ""),
    3171             :   UPGRADE_TEST(upgrade_blocked_by_better_circ_complete, "c1-done c2-done"),
    3172             :   UPGRADE_TEST(upgrade_not_blocked_by_restricted_circ_complete,
    3173             :                "c1-done c2-done"),
    3174             :   UPGRADE_TEST(upgrade_not_blocked_by_worse_circ_complete, "c1-done c2-done"),
    3175             :   UPGRADE_TEST(upgrade_blocked_by_better_circ_pending, "c2-done"),
    3176             :   UPGRADE_TEST(upgrade_not_blocked_by_restricted_circ_pending,
    3177             :                "c2-done"),
    3178             :   UPGRADE_TEST(upgrade_not_blocked_by_worse_circ_pending, "c1-done"),
    3179             : 
    3180             :   EN_TEST_FORK(should_expire_waiting),
    3181             : 
    3182             :   END_OF_TESTCASES
    3183             : };

Generated by: LCOV version 1.14