tor

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

test_dir.c (263327B)


      1 /* Copyright (c) 2001-2004, Roger Dingledine.
      2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      4 /* See LICENSE for licensing information */
      5 
      6 #include "orconfig.h"
      7 #include <math.h>
      8 
      9 #define BWAUTH_PRIVATE
     10 #define CONFIG_PRIVATE
     11 #define CONTROL_GETINFO_PRIVATE
     12 #define DIRAUTH_SYS_PRIVATE
     13 #define DIRCACHE_PRIVATE
     14 #define DIRCLIENT_PRIVATE
     15 #define DIRVOTE_PRIVATE
     16 #define DLSTATUS_PRIVATE
     17 #define HIBERNATE_PRIVATE
     18 #define NETWORKSTATUS_PRIVATE
     19 #define NS_PARSE_PRIVATE
     20 #define NODE_SELECT_PRIVATE
     21 #define RELAY_PRIVATE
     22 #define ROUTERLIST_PRIVATE
     23 #define ROUTER_PRIVATE
     24 #define ROUTERKEYS_PRIVATE
     25 #define ROUTERPARSE_PRIVATE
     26 #define UNPARSEABLE_PRIVATE
     27 #define VOTEFLAGS_PRIVATE
     28 
     29 #include "core/or/or.h"
     30 #include "app/config/config.h"
     31 #include "lib/confmgt/confmgt.h"
     32 #include "core/mainloop/connection.h"
     33 #include "core/or/relay.h"
     34 #include "core/or/protover.h"
     35 #include "core/or/versions.h"
     36 #include "feature/client/bridges.h"
     37 #include "feature/client/entrynodes.h"
     38 #include "feature/control/control_getinfo.h"
     39 #include "feature/dirauth/bwauth.h"
     40 #include "feature/dirauth/dirauth_sys.h"
     41 #include "feature/dirauth/dirvote.h"
     42 #include "feature/dirauth/dsigs_parse.h"
     43 #include "feature/dirauth/process_descs.h"
     44 #include "feature/dirauth/recommend_pkg.h"
     45 #include "feature/dirauth/shared_random_state.h"
     46 #include "feature/dirauth/voteflags.h"
     47 #include "feature/dircache/dircache.h"
     48 #include "feature/dircache/dirserv.h"
     49 #include "feature/dirclient/dirclient.h"
     50 #include "feature/dirclient/dlstatus.h"
     51 #include "feature/dircommon/directory.h"
     52 #include "feature/dircommon/fp_pair.h"
     53 #include "feature/dirauth/voting_schedule.h"
     54 #include "feature/hibernate/hibernate.h"
     55 #include "feature/nodelist/authcert.h"
     56 #include "feature/nodelist/dirlist.h"
     57 #include "feature/nodelist/microdesc.h"
     58 #include "feature/nodelist/networkstatus.h"
     59 #include "feature/nodelist/nickname.h"
     60 #include "feature/nodelist/node_select.h"
     61 #include "feature/nodelist/routerlist.h"
     62 #include "feature/dirparse/authcert_parse.h"
     63 #include "feature/dirparse/ns_parse.h"
     64 #include "feature/dirparse/routerparse.h"
     65 #include "feature/dirparse/unparseable.h"
     66 #include "feature/nodelist/routerset.h"
     67 #include "feature/nodelist/torcert.h"
     68 #include "feature/relay/router.h"
     69 #include "feature/relay/routerkeys.h"
     70 #include "feature/relay/routermode.h"
     71 #include "lib/compress/compress.h"
     72 #include "lib/crypt_ops/crypto_ed25519.h"
     73 #include "lib/crypt_ops/crypto_format.h"
     74 #include "lib/crypt_ops/crypto_rand.h"
     75 #include "lib/encoding/confline.h"
     76 #include "lib/memarea/memarea.h"
     77 #include "lib/osinfo/uname.h"
     78 #include "test/log_test_helpers.h"
     79 #include "test/opts_test_helpers.h"
     80 #include "test/test.h"
     81 #include "test/test_dir_common.h"
     82 
     83 #include "core/or/addr_policy_st.h"
     84 #include "feature/dirauth/dirauth_options_st.h"
     85 #include "feature/nodelist/authority_cert_st.h"
     86 #include "feature/nodelist/document_signature_st.h"
     87 #include "feature/nodelist/extrainfo_st.h"
     88 #include "feature/nodelist/microdesc_st.h"
     89 #include "feature/nodelist/networkstatus_st.h"
     90 #include "feature/nodelist/networkstatus_voter_info_st.h"
     91 #include "feature/dirauth/ns_detached_signatures_st.h"
     92 #include "core/or/port_cfg_st.h"
     93 #include "feature/nodelist/routerinfo_st.h"
     94 #include "feature/nodelist/routerlist_st.h"
     95 #include "core/or/tor_version_st.h"
     96 #include "feature/dirauth/vote_microdesc_hash_st.h"
     97 #include "feature/nodelist/vote_routerstatus_st.h"
     98 
     99 #ifdef HAVE_SYS_STAT_H
    100 #include <sys/stat.h>
    101 #endif
    102 #ifdef HAVE_UNISTD_H
    103 #include <unistd.h>
    104 #endif
    105 
    106 static void setup_ei_digests(void);
    107 static uint8_t digest_ei_minimal[20];
    108 static uint8_t digest_ei_bad_nickname[20];
    109 static uint8_t digest_ei_maximal[20];
    110 static uint8_t digest_ei_bad_tokens[20];
    111 static uint8_t digest_ei_bad_sig2[20];
    112 static uint8_t digest_ei_bad_published[20];
    113 
    114 static networkstatus_t *
    115 networkstatus_parse_vote_from_string_(const char *s,
    116                                      const char **eos_out,
    117                                      enum networkstatus_type_t ns_type)
    118 {
    119  size_t len = strlen(s);
    120  // memdup so that it won't be nul-terminated.
    121  char *tmp = tor_memdup(s, len);
    122  networkstatus_t *result =
    123    networkstatus_parse_vote_from_string(tmp, len, eos_out, ns_type);
    124  if (eos_out && *eos_out) {
    125    *eos_out = s + (*eos_out - tmp);
    126  }
    127  tor_free(tmp);
    128  return result;
    129 }
    130 
    131 static void
    132 test_dir_nicknames(void *arg)
    133 {
    134  (void)arg;
    135  tt_assert( is_legal_nickname("a"));
    136  tt_assert(!is_legal_nickname(""));
    137  tt_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
    138  tt_assert(!is_legal_nickname("hyphen-")); /* bad char */
    139  tt_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
    140  tt_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
    141  /* valid */
    142  tt_assert( is_legal_nickname_or_hexdigest(
    143                                 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
    144  tt_assert( is_legal_nickname_or_hexdigest(
    145                         "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
    146  tt_assert( is_legal_nickname_or_hexdigest(
    147                         "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
    148  /* too short */
    149  tt_assert(!is_legal_nickname_or_hexdigest(
    150                                 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
    151  /* illegal char */
    152  tt_assert(!is_legal_nickname_or_hexdigest(
    153                                 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
    154  /* hex part too long */
    155  tt_assert(!is_legal_nickname_or_hexdigest(
    156                         "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
    157  tt_assert(!is_legal_nickname_or_hexdigest(
    158                         "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
    159  /* Bad nickname */
    160  tt_assert(!is_legal_nickname_or_hexdigest(
    161                         "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
    162  tt_assert(!is_legal_nickname_or_hexdigest(
    163                         "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
    164  tt_assert(!is_legal_nickname_or_hexdigest(
    165                       "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
    166  tt_assert(!is_legal_nickname_or_hexdigest(
    167                       "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
    168                       "abcdefghijklmnoppqrst"));
    169  /* Bad extra char. */
    170  tt_assert(!is_legal_nickname_or_hexdigest(
    171                         "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
    172  tt_assert(is_legal_nickname_or_hexdigest("xyzzy"));
    173  tt_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
    174  tt_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
    175 done:
    176  ;
    177 }
    178 
    179 /* Allocate and return a new routerinfo, with the fields set from the
    180 * arguments to this function.
    181 *
    182 * Also sets:
    183 *  - random RSA identity and onion keys,
    184 *  - the platform field using get_platform_str(), and
    185 *  - supports_tunnelled_dir_requests to 1.
    186 *
    187 * If rsa_onion_keypair_out is not NULL, it is set to the onion keypair.
    188 * The caller must free this keypair.
    189 */
    190 static routerinfo_t *
    191 basic_routerinfo_new(const char *nickname, uint32_t ipv4_addr,
    192                     uint16_t or_port, uint16_t dir_port,
    193                     uint32_t bandwidthrate, uint32_t bandwidthburst,
    194                     uint32_t bandwidthcapacity,
    195                     time_t published_on,
    196                     crypto_pk_t **rsa_onion_keypair_out)
    197 {
    198  char platform[256];
    199 
    200  tor_assert(nickname);
    201 
    202  crypto_pk_t *pk1 = NULL, *pk2 = NULL;
    203  /* These keys are random: idx is ignored. */
    204  pk1 = pk_generate(0);
    205  pk2 = pk_generate(1);
    206 
    207  tor_assert(pk1);
    208  tor_assert(pk2);
    209 
    210  get_platform_str(platform, sizeof(platform));
    211 
    212  routerinfo_t *r1 = tor_malloc_zero(sizeof(routerinfo_t));
    213 
    214  r1->nickname = tor_strdup(nickname);
    215  r1->platform = tor_strdup(platform);
    216 
    217  tor_addr_from_ipv4h(&r1->ipv4_addr, ipv4_addr);
    218  r1->ipv4_orport = or_port;
    219  r1->ipv4_dirport = dir_port;
    220  r1->supports_tunnelled_dir_requests = 1;
    221 
    222  router_set_rsa_onion_pkey(pk1, &r1->tap_onion_pkey, &r1->tap_onion_pkey_len);
    223  r1->identity_pkey = pk2;
    224 
    225  r1->bandwidthrate = bandwidthrate;
    226  r1->bandwidthburst = bandwidthburst;
    227  r1->bandwidthcapacity = bandwidthcapacity;
    228 
    229  r1->cache_info.published_on = published_on;
    230  r1->protocol_list = tor_strdup(protover_get_supported_protocols());
    231 
    232  if (rsa_onion_keypair_out) {
    233    *rsa_onion_keypair_out = pk1;
    234  } else {
    235    crypto_pk_free(pk1);
    236  }
    237 
    238  return r1;
    239 }
    240 
    241 /* Allocate and return a new string containing a "router" line for r1. */
    242 static char *
    243 get_new_router_line(const routerinfo_t *r1)
    244 {
    245  char *line = NULL;
    246 
    247  tor_assert(r1);
    248 
    249  tor_asprintf(&line,
    250               "router %s %s %d 0 %d\n",
    251               r1->nickname, fmt_addr(&r1->ipv4_addr),
    252               r1->ipv4_orport, r1->ipv4_dirport);
    253  tor_assert(line);
    254 
    255  return line;
    256 }
    257 
    258 /* Allocate and return a new string containing a "platform" line for the
    259 * current Tor version and OS. */
    260 static char *
    261 get_new_platform_line(void)
    262 {
    263  char *line = NULL;
    264 
    265  tor_asprintf(&line,
    266               "platform Tor %s on %s\n",
    267               VERSION, get_uname());
    268  tor_assert(line);
    269 
    270  return line;
    271 }
    272 
    273 /* Allocate and return a new string containing a "published" line for r1.
    274 * r1->cache_info.published_on must be between 0 and 59 seconds. */
    275 static char *
    276 get_new_published_line(const routerinfo_t *r1)
    277 {
    278  char *line = NULL;
    279 
    280  tor_assert(r1);
    281 
    282  tor_assert(r1->cache_info.published_on >= 0);
    283  tor_assert(r1->cache_info.published_on <= 59);
    284 
    285  tor_asprintf(&line,
    286               "published 1970-01-01 00:00:%02u\n",
    287               (unsigned)r1->cache_info.published_on);
    288  tor_assert(line);
    289 
    290  return line;
    291 }
    292 
    293 /* Allocate and return a new string containing a "fingerprint" line for r1. */
    294 static char *
    295 get_new_fingerprint_line(const routerinfo_t *r1)
    296 {
    297  char *line = NULL;
    298  char fingerprint[FINGERPRINT_LEN+1];
    299 
    300  tor_assert(r1);
    301 
    302  tor_assert(!crypto_pk_get_fingerprint(r1->identity_pkey, fingerprint, 1));
    303  tor_assert(strlen(fingerprint) > 0);
    304 
    305  tor_asprintf(&line,
    306               "fingerprint %s\n",
    307               fingerprint);
    308  tor_assert(line);
    309 
    310  return line;
    311 }
    312 
    313 /* Allocate and return a new string containing an "uptime" line with uptime t.
    314 *
    315 * You should pass a hard-coded value to this function, because even if we made
    316 * it reflect uptime, that still wouldn't make it right, because the two
    317 * descriptors might be made on different seconds.
    318 */
    319 static char *
    320 get_new_uptime_line(time_t t)
    321 {
    322  char *line = NULL;
    323 
    324  tor_asprintf(&line,
    325               "uptime %u\n",
    326               (unsigned)t);
    327  tor_assert(line);
    328 
    329  return line;
    330 }
    331 
    332 /* Allocate and return a new string containing an "bandwidth" line for r1.
    333 */
    334 static char *
    335 get_new_bandwidth_line(const routerinfo_t *r1)
    336 {
    337  char *line = NULL;
    338 
    339  tor_assert(r1);
    340 
    341  tor_asprintf(&line,
    342               "bandwidth %u %u %u\n",
    343               r1->bandwidthrate,
    344               r1->bandwidthburst,
    345               r1->bandwidthcapacity);
    346  tor_assert(line);
    347 
    348  return line;
    349 }
    350 
    351 /* Allocate and return a new string containing a key_name block for the
    352 * RSA key pk1.
    353 */
    354 static char *
    355 get_new_rsa_key_block(const char *key_name, crypto_pk_t *pk1)
    356 {
    357  char *block = NULL;
    358  char *pk1_str = NULL;
    359  size_t pk1_str_len = 0;
    360 
    361  tor_assert(key_name);
    362  tor_assert(pk1);
    363 
    364  tor_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
    365                                                   &pk1_str_len));
    366  tor_assert(pk1_str);
    367  tor_assert(pk1_str_len);
    368 
    369  tor_asprintf(&block,
    370               "%s\n%s",
    371               key_name,
    372               pk1_str);
    373  tor_free(pk1_str);
    374 
    375  tor_assert(block);
    376  return block;
    377 }
    378 
    379 /* Allocate and return a new string containing an "onion-key" block for the
    380 * router r1.
    381 */
    382 static char *
    383 get_new_onion_key_block(const routerinfo_t *r1)
    384 {
    385  char *block = NULL;
    386  tor_assert(r1);
    387  crypto_pk_t *pk_tmp = router_get_rsa_onion_pkey(r1->tap_onion_pkey,
    388                                                  r1->tap_onion_pkey_len);
    389  block = get_new_rsa_key_block("onion-key", pk_tmp);
    390  crypto_pk_free(pk_tmp);
    391  return block;
    392 }
    393 
    394 /* Allocate and return a new string containing an "signing-key" block for the
    395 * router r1.
    396 */
    397 static char *
    398 get_new_signing_key_block(const routerinfo_t *r1)
    399 {
    400  tor_assert(r1);
    401  return get_new_rsa_key_block("signing-key", r1->identity_pkey);
    402 }
    403 
    404 /* Allocate and return a new string containing an "ntor-onion-key" line for
    405 * the curve25519 public key ntor_onion_pubkey.
    406 */
    407 static char *
    408 get_new_ntor_onion_key_line(const curve25519_public_key_t *ntor_onion_pubkey)
    409 {
    410  char *line = NULL;
    411  char cert_buf[256];
    412 
    413  tor_assert(ntor_onion_pubkey);
    414 
    415  curve25519_public_to_base64(cert_buf, ntor_onion_pubkey, false);
    416  tor_assert(strlen(cert_buf) > 0);
    417 
    418  tor_asprintf(&line,
    419               "ntor-onion-key %s\n",
    420               cert_buf);
    421  tor_assert(line);
    422 
    423  return line;
    424 }
    425 
    426 /* Allocate and return a new string containing a "bridge-distribution-request"
    427 * line for options.
    428 */
    429 static char *
    430 get_new_bridge_distribution_request_line(const or_options_t *options)
    431 {
    432  if (options->BridgeRelay) {
    433    return tor_strdup("bridge-distribution-request any\n");
    434  } else {
    435    return tor_strdup("");
    436  }
    437 }
    438 
    439 static smartlist_t *mocked_configured_ports = NULL;
    440 
    441 /** Returns mocked_configured_ports */
    442 static const smartlist_t *
    443 mock_get_configured_ports(void)
    444 {
    445  return mocked_configured_ports;
    446 }
    447 
    448 static crypto_pk_t *mocked_server_identitykey = NULL;
    449 
    450 /* Returns mocked_server_identitykey with no checks. */
    451 static crypto_pk_t *
    452 mock_get_server_identity_key(void)
    453 {
    454  return mocked_server_identitykey;
    455 }
    456 
    457 static crypto_pk_t *mocked_onionkey = NULL;
    458 
    459 /* Returns mocked_onionkey with no checks. */
    460 static crypto_pk_t *
    461 mock_get_onion_key(void)
    462 {
    463  return mocked_onionkey;
    464 }
    465 
    466 static routerinfo_t *mocked_routerinfo = NULL;
    467 
    468 /* Returns 0 and sets ri_out to mocked_routerinfo.
    469 * ri_out must not be NULL. There are no other checks. */
    470 static int
    471 mock_router_build_fresh_unsigned_routerinfo(routerinfo_t **ri_out)
    472 {
    473  tor_assert(ri_out);
    474  *ri_out = mocked_routerinfo;
    475  return 0;
    476 }
    477 
    478 static ed25519_keypair_t *mocked_master_signing_key = NULL;
    479 
    480 /* Returns mocked_master_signing_key with no checks. */
    481 static const ed25519_keypair_t *
    482 mock_get_master_signing_keypair(void)
    483 {
    484  return mocked_master_signing_key;
    485 }
    486 
    487 static struct tor_cert_st *mocked_signing_key_cert = NULL;
    488 
    489 /* Returns mocked_signing_key_cert with no checks. */
    490 static const struct tor_cert_st *
    491 mock_get_master_signing_key_cert(void)
    492 {
    493  return mocked_signing_key_cert;
    494 }
    495 
    496 static curve25519_keypair_t *mocked_curve25519_onion_key = NULL;
    497 
    498 /* Returns mocked_curve25519_onion_key with no checks. */
    499 static const curve25519_keypair_t *
    500 mock_get_current_curve25519_keypair(void)
    501 {
    502  return mocked_curve25519_onion_key;
    503 }
    504 
    505 /* Unmock get_configured_ports() and free mocked_configured_ports. */
    506 static void
    507 cleanup_mock_configured_ports(void)
    508 {
    509  UNMOCK(get_configured_ports);
    510 
    511  if (mocked_configured_ports) {
    512    SMARTLIST_FOREACH(mocked_configured_ports, port_cfg_t *, p, tor_free(p));
    513    smartlist_free(mocked_configured_ports);
    514  }
    515 }
    516 
    517 /* Mock get_configured_ports() with a list containing or_port and dir_port.
    518 * If a port is 0, don't set it.
    519 * Only sets the minimal data required for the tests to pass. */
    520 static void
    521 setup_mock_configured_ports(uint16_t or_port, uint16_t dir_port)
    522 {
    523  cleanup_mock_configured_ports();
    524 
    525  /* Fake just enough of an ORPort and DirPort to get by */
    526  MOCK(get_configured_ports, mock_get_configured_ports);
    527  mocked_configured_ports = smartlist_new();
    528 
    529  if (or_port) {
    530    port_cfg_t *or_port_cfg = tor_malloc_zero(sizeof(*or_port_cfg));
    531    or_port_cfg->type = CONN_TYPE_OR_LISTENER;
    532    or_port_cfg->addr.family = AF_INET;
    533    or_port_cfg->port = or_port;
    534    smartlist_add(mocked_configured_ports, or_port_cfg);
    535  }
    536 
    537  if (dir_port) {
    538    port_cfg_t *dir_port_cfg = tor_malloc_zero(sizeof(*dir_port_cfg));
    539    dir_port_cfg->type = CONN_TYPE_DIR_LISTENER;
    540    dir_port_cfg->addr.family = AF_INET;
    541    dir_port_cfg->port = dir_port;
    542    smartlist_add(mocked_configured_ports, dir_port_cfg);
    543  }
    544 }
    545 
    546 /* Clean up the data structures and unmock the functions needed for generating
    547 * a fresh descriptor. */
    548 static void
    549 cleanup_mocks_for_fresh_descriptor(void)
    550 {
    551  tor_free(get_options_mutable()->Nickname);
    552 
    553  mocked_server_identitykey = NULL;
    554  UNMOCK(get_server_identity_key);
    555 
    556  crypto_pk_free(mocked_onionkey);
    557  UNMOCK(get_onion_key);
    558 }
    559 
    560 /* Mock the data structures and functions needed for generating a fresh
    561 * descriptor.
    562 *
    563 * Sets options->Nickname from r1->nickname.
    564 * Mocks get_server_identity_key() with r1->identity_pkey.
    565 *
    566 * If rsa_onion_keypair is not NULL, it is used to mock get_onion_key().
    567 * Otherwise, the public key in r1->onion_pkey is used to mock get_onion_key().
    568 */
    569 static void
    570 setup_mocks_for_fresh_descriptor(const routerinfo_t *r1,
    571                                 crypto_pk_t *rsa_onion_keypair)
    572 {
    573  cleanup_mocks_for_fresh_descriptor();
    574 
    575  tor_assert(r1);
    576 
    577  /* router_build_fresh_signed_extrainfo() requires options->Nickname */
    578  get_options_mutable()->Nickname = tor_strdup(r1->nickname);
    579 
    580  /* router_build_fresh_signed_extrainfo() requires get_server_identity_key().
    581   * Use the same one as the call to router_dump_router_to_string() above.
    582   */
    583  mocked_server_identitykey = r1->identity_pkey;
    584  MOCK(get_server_identity_key, mock_get_server_identity_key);
    585 
    586  /* router_dump_and_sign_routerinfo_descriptor_body() requires
    587   * get_onion_key(). Use the same one as r1.
    588   */
    589  if (rsa_onion_keypair) {
    590    mocked_onionkey = crypto_pk_dup_key(rsa_onion_keypair);
    591  } else {
    592    mocked_onionkey = router_get_rsa_onion_pkey(r1->tap_onion_pkey,
    593                                                r1->tap_onion_pkey_len);
    594  }
    595  MOCK(get_onion_key, mock_get_onion_key);
    596 }
    597 
    598 /* Set options based on arg.
    599 *
    600 * b: BridgeRelay 1
    601 * e: ExtraInfoStatistics 1
    602 * s: sets all the individual statistics options to 1
    603 *
    604 * Always sets AssumeReachable to 1.
    605 *
    606 * Does not set ServerTransportPlugin, because it's parsed before use.
    607 *
    608 * Does not set BridgeRecordUsageByCountry, because the tests don't have access
    609 * to a GeoIPFile or GeoIPv6File. */
    610 static void
    611 setup_dir_formats_options(const char *arg, or_options_t *options)
    612 {
    613  /* Skip reachability checks for DirPort, ORPort, and tunnelled-dir-server */
    614  options->AssumeReachable = 1;
    615 
    616  if (strchr(arg, 'b')) {
    617    options->BridgeRelay = 1;
    618  }
    619 
    620  if (strchr(arg, 'e')) {
    621    options->ExtraInfoStatistics = 1;
    622  }
    623 
    624  if (strchr(arg, 's')) {
    625    options->DirReqStatistics = 1;
    626    options->HiddenServiceStatistics = 1;
    627    options->EntryStatistics = 1;
    628    options->CellStatistics = 1;
    629    options->ExitPortStatistics = 1;
    630    options->ConnDirectionStatistics = 1;
    631    options->PaddingStatistics = 1;
    632  }
    633 }
    634 
    635 /* Check that routerinfos r1 and rp1 are consistent.
    636 * Only performs some basic checks.
    637 */
    638 #define CHECK_ROUTERINFO_CONSISTENCY(r1, rp1) \
    639 STMT_BEGIN \
    640  tt_assert(r1); \
    641  tt_assert(rp1); \
    642  tt_assert(tor_addr_eq(&rp1->ipv4_addr, &r1->ipv4_addr)); \
    643  tt_int_op(rp1->ipv4_orport,OP_EQ, r1->ipv4_orport); \
    644  tt_int_op(rp1->ipv4_dirport,OP_EQ, r1->ipv4_dirport); \
    645  tt_int_op(rp1->bandwidthrate,OP_EQ, r1->bandwidthrate); \
    646  tt_int_op(rp1->bandwidthburst,OP_EQ, r1->bandwidthburst); \
    647  tt_int_op(rp1->bandwidthcapacity,OP_EQ, r1->bandwidthcapacity); \
    648  crypto_pk_t *rp1_onion_pkey = router_get_rsa_onion_pkey( \
    649                                                    rp1->tap_onion_pkey, \
    650                                                    rp1->tap_onion_pkey_len); \
    651  crypto_pk_t *r1_onion_pkey = router_get_rsa_onion_pkey( \
    652                                                    r1->tap_onion_pkey, \
    653                                                    r1->tap_onion_pkey_len); \
    654  tt_int_op(crypto_pk_cmp_keys(rp1_onion_pkey, r1_onion_pkey), OP_EQ, 0); \
    655  crypto_pk_free(rp1_onion_pkey); \
    656  crypto_pk_free(r1_onion_pkey); \
    657  tt_int_op(crypto_pk_cmp_keys(rp1->identity_pkey, r1->identity_pkey), \
    658            OP_EQ, 0); \
    659  tt_int_op(rp1->supports_tunnelled_dir_requests, OP_EQ, \
    660            r1->supports_tunnelled_dir_requests); \
    661 STMT_END
    662 
    663 /* Check that routerinfo r1 and extrainfo e1 are consistent.
    664 * Only performs some basic checks.
    665 */
    666 #define CHECK_EXTRAINFO_CONSISTENCY(r1, e1) \
    667 STMT_BEGIN \
    668  tt_assert(r1); \
    669  tt_assert(e1); \
    670 \
    671  tt_str_op(e1->nickname, OP_EQ, r1->nickname); \
    672 STMT_END
    673 
    674 /* Check that the exit policy in rp2 is as expected. */
    675 #define CHECK_PARSED_EXIT_POLICY(rp2) \
    676 STMT_BEGIN \
    677  tt_int_op(smartlist_len(rp2->exit_policy),OP_EQ, 2); \
    678 \
    679  p = smartlist_get(rp2->exit_policy, 0); \
    680  tt_int_op(p->policy_type,OP_EQ, ADDR_POLICY_ACCEPT); \
    681  tt_assert(tor_addr_is_null(&p->addr)); \
    682  tt_int_op(p->maskbits,OP_EQ, 0); \
    683  tt_int_op(p->prt_min,OP_EQ, 80); \
    684  tt_int_op(p->prt_max,OP_EQ, 80); \
    685 \
    686  p = smartlist_get(rp2->exit_policy, 1); \
    687  tt_int_op(p->policy_type,OP_EQ, ADDR_POLICY_REJECT); \
    688  tt_assert(tor_addr_eq(&p->addr, &ex2->addr)); \
    689  tt_int_op(p->maskbits,OP_EQ, 8); \
    690  tt_int_op(p->prt_min,OP_EQ, 24); \
    691  tt_int_op(p->prt_max,OP_EQ, 24); \
    692 STMT_END
    693 
    694 /** Run unit tests for router descriptor generation logic for a RSA + ed25519
    695 * router.
    696 */
    697 static void
    698 test_dir_formats_rsa_ed25519(void *arg)
    699 {
    700  char *buf = NULL;
    701  char *buf2 = NULL;
    702  char *cp = NULL;
    703 
    704  crypto_pk_t *r2_onion_pkey = NULL;
    705  char cert_buf[256];
    706  uint8_t *rsa_cc = NULL;
    707  time_t now = time(NULL);
    708 
    709  routerinfo_t *r2 = NULL;
    710  extrainfo_t *e2 = NULL;
    711  routerinfo_t *r2_out = NULL;
    712  routerinfo_t *rp2 = NULL;
    713  extrainfo_t *ep2 = NULL;
    714  addr_policy_t *ex1, *ex2;
    715  const addr_policy_t *p;
    716 
    717  smartlist_t *chunks = NULL;
    718  int rv = -1;
    719 
    720  or_options_t *options = get_options_mutable();
    721  setup_dir_formats_options((const char *)arg, options);
    722 
    723  hibernate_set_state_for_testing_(HIBERNATE_STATE_LIVE);
    724 
    725  /* r2 is a RSA + ed25519 descriptor, with an exit policy, but no DirPort or
    726   * IPv6 */
    727  r2 = basic_routerinfo_new("Fred", 0x0a030201u /* 10.3.2.1 */,
    728                            9005, 0,
    729                            3000, 3000, 3000,
    730                            5,
    731                            &r2_onion_pkey);
    732 
    733  /* Fake just enough of an ntor key to get by */
    734  curve25519_keypair_t r2_onion_keypair;
    735  curve25519_keypair_generate(&r2_onion_keypair, 0);
    736  r2->onion_curve25519_pkey = tor_memdup(&r2_onion_keypair.pubkey,
    737                                         sizeof(curve25519_public_key_t));
    738 
    739  /* Now add relay ed25519 keys
    740   * We can't use init_mock_ed_keys() here, because the keys are seeded */
    741  ed25519_keypair_t kp1, kp2;
    742  ed25519_secret_key_from_seed(&kp1.seckey,
    743                          (const uint8_t*)"YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY");
    744  ed25519_public_key_generate(&kp1.pubkey, &kp1.seckey);
    745  ed25519_secret_key_from_seed(&kp2.seckey,
    746                          (const uint8_t*)"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    747  ed25519_public_key_generate(&kp2.pubkey, &kp2.seckey);
    748  r2->cache_info.signing_key_cert = tor_cert_create_ed25519(&kp1,
    749                                         CERT_TYPE_ID_SIGNING,
    750                                         &kp2.pubkey,
    751                                         now, 86400,
    752                                         CERT_FLAG_INCLUDE_SIGNING_KEY);
    753 
    754  /* Now add an exit policy */
    755  ex1 = tor_malloc_zero(sizeof(addr_policy_t));
    756  ex2 = tor_malloc_zero(sizeof(addr_policy_t));
    757  ex1->policy_type = ADDR_POLICY_ACCEPT;
    758  tor_addr_from_ipv4h(&ex1->addr, 0);
    759  ex1->maskbits = 0;
    760  ex1->prt_min = ex1->prt_max = 80;
    761  ex2->policy_type = ADDR_POLICY_REJECT;
    762  tor_addr_from_ipv4h(&ex2->addr, 18<<24);
    763  ex2->maskbits = 8;
    764  ex2->prt_min = ex2->prt_max = 24;
    765 
    766  r2->exit_policy = smartlist_new();
    767  smartlist_add(r2->exit_policy, ex1);
    768  smartlist_add(r2->exit_policy, ex2);
    769 
    770  /* Fake just enough of an ORPort to get by */
    771  setup_mock_configured_ports(r2->ipv4_orport, 0);
    772 
    773  buf = router_dump_router_to_string(r2,
    774                                     r2->identity_pkey, r2_onion_pkey,
    775                                     &r2_onion_keypair, &kp2);
    776  tt_assert(buf);
    777 
    778  cleanup_mock_configured_ports();
    779 
    780  chunks = smartlist_new();
    781 
    782  /* Synthesise a router descriptor, without the signatures */
    783  smartlist_add(chunks, get_new_router_line(r2));
    784 
    785  smartlist_add_strdup(chunks,
    786                       "identity-ed25519\n"
    787                       "-----BEGIN ED25519 CERT-----\n");
    788  base64_encode(cert_buf, sizeof(cert_buf),
    789                (const char*)r2->cache_info.signing_key_cert->encoded,
    790                r2->cache_info.signing_key_cert->encoded_len,
    791                BASE64_ENCODE_MULTILINE);
    792  smartlist_add_strdup(chunks, cert_buf);
    793  smartlist_add_strdup(chunks, "-----END ED25519 CERT-----\n");
    794 
    795  smartlist_add_strdup(chunks, "master-key-ed25519 ");
    796  {
    797    char k[ED25519_BASE64_LEN+1];
    798    ed25519_public_to_base64(k, &r2->cache_info.signing_key_cert->signing_key);
    799    smartlist_add_strdup(chunks, k);
    800    smartlist_add_strdup(chunks, "\n");
    801  }
    802 
    803  smartlist_add(chunks, get_new_platform_line());
    804  smartlist_add_asprintf(chunks,
    805                         "proto %s\n", protover_get_supported_protocols());
    806  smartlist_add(chunks, get_new_published_line(r2));
    807  smartlist_add(chunks, get_new_fingerprint_line(r2));
    808 
    809  smartlist_add(chunks, get_new_uptime_line(0));
    810  smartlist_add(chunks, get_new_bandwidth_line(r2));
    811 
    812  smartlist_add(chunks, get_new_onion_key_block(r2));
    813  smartlist_add(chunks, get_new_signing_key_block(r2));
    814 
    815  int rsa_cc_len;
    816  rsa_cc = make_tap_onion_key_crosscert(r2_onion_pkey,
    817                                        &kp1.pubkey,
    818                                        r2->identity_pkey,
    819                                        &rsa_cc_len);
    820  tt_assert(rsa_cc);
    821  base64_encode(cert_buf, sizeof(cert_buf), (char*)rsa_cc, rsa_cc_len,
    822                BASE64_ENCODE_MULTILINE);
    823  smartlist_add_strdup(chunks, "onion-key-crosscert\n"
    824                       "-----BEGIN CROSSCERT-----\n");
    825  smartlist_add_strdup(chunks, cert_buf);
    826  smartlist_add_strdup(chunks, "-----END CROSSCERT-----\n");
    827  int ntor_cc_sign;
    828  {
    829    tor_cert_t *ntor_cc = NULL;
    830    ntor_cc = make_ntor_onion_key_crosscert(&r2_onion_keypair,
    831                                          &kp1.pubkey,
    832                                          r2->cache_info.published_on,
    833                                          get_onion_key_lifetime(),
    834                                          &ntor_cc_sign);
    835    tt_assert(ntor_cc);
    836    base64_encode(cert_buf, sizeof(cert_buf),
    837                (char*)ntor_cc->encoded, ntor_cc->encoded_len,
    838                BASE64_ENCODE_MULTILINE);
    839    tor_cert_free(ntor_cc);
    840  }
    841  smartlist_add_asprintf(chunks,
    842               "ntor-onion-key-crosscert %d\n"
    843               "-----BEGIN ED25519 CERT-----\n"
    844               "%s"
    845               "-----END ED25519 CERT-----\n", ntor_cc_sign, cert_buf);
    846 
    847  smartlist_add_strdup(chunks, "hidden-service-dir\n");
    848 
    849  smartlist_add(chunks, get_new_bridge_distribution_request_line(options));
    850  smartlist_add(chunks, get_new_ntor_onion_key_line(&r2_onion_keypair.pubkey));
    851  smartlist_add_strdup(chunks, "accept *:80\nreject 18.0.0.0/8:24\n");
    852  smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
    853 
    854  smartlist_add_strdup(chunks, "router-sig-ed25519 ");
    855 
    856  size_t len_out = 0;
    857  buf2 = smartlist_join_strings(chunks, "", 0, &len_out);
    858  SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
    859  smartlist_free(chunks);
    860 
    861  tt_assert(len_out > 0);
    862 
    863  buf[strlen(buf2)] = '\0'; /* Don't compare either sig; they're never the same
    864                             * twice */
    865 
    866  tt_str_op(buf, OP_EQ, buf2);
    867  tor_free(buf);
    868 
    869  /* We make a couple of changes now before we make the desc that we're going
    870   * to parse and check the signature on. */
    871  setup_mock_configured_ports(r2->ipv4_orport, 0);
    872 
    873  ed25519_keypair_t family_1;
    874  ed25519_keypair_t family_2;
    875  ed25519_keypair_generate(&family_1, 0);
    876  ed25519_keypair_generate(&family_2, 0);
    877  {
    878    smartlist_t *family_keys = smartlist_new();
    879    smartlist_add(family_keys, tor_memdup(&family_1, sizeof(family_1)));
    880    smartlist_add(family_keys, tor_memdup(&family_2, sizeof(family_2)));
    881    set_family_id_keys(family_keys); // takes ownership.
    882  }
    883 
    884  buf = router_dump_router_to_string(r2, r2->identity_pkey,
    885                                     r2_onion_pkey,
    886                                     &r2_onion_keypair, &kp2);
    887  tt_assert(buf);
    888 
    889  cleanup_mock_configured_ports();
    890 
    891  /* Now, try to parse buf */
    892  cp = buf;
    893  rp2 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
    894 
    895  CHECK_ROUTERINFO_CONSISTENCY(r2, rp2);
    896 
    897  tt_mem_op(rp2->onion_curve25519_pkey->public_key,OP_EQ,
    898             r2->onion_curve25519_pkey->public_key,
    899             CURVE25519_PUBKEY_LEN);
    900 
    901  // Check family ids.
    902  tt_assert(rp2->family_ids != NULL);
    903  tt_int_op(smartlist_len(rp2->family_ids), OP_EQ, 2);
    904 {
    905    char k[ED25519_BASE64_LEN+1];
    906    char b[sizeof(k)+16];
    907    ed25519_public_to_base64(k, &family_1.pubkey);
    908    tor_snprintf(b, sizeof(b), "ed25519:%s", k);
    909    tt_assert(smartlist_contains_string(rp2->family_ids, b));
    910    ed25519_public_to_base64(k, &family_2.pubkey);
    911    tor_snprintf(b, sizeof(b), "ed25519:%s", k);
    912    tt_assert(smartlist_contains_string(rp2->family_ids, b));
    913  }
    914 
    915  CHECK_PARSED_EXIT_POLICY(rp2);
    916 
    917  tor_free(buf);
    918  routerinfo_free(rp2);
    919 
    920  /* Test extrainfo creation. */
    921 
    922  /* Set up standard mocks and data */
    923  setup_mocks_for_fresh_descriptor(r2, r2_onion_pkey);
    924 
    925  /* router_build_fresh_descriptor() requires
    926   * router_build_fresh_unsigned_routerinfo(), but the implementation is
    927   * too complex. Instead, we re-use r2.
    928   */
    929  mocked_routerinfo = r2;
    930  MOCK(router_build_fresh_unsigned_routerinfo,
    931       mock_router_build_fresh_unsigned_routerinfo);
    932 
    933  /* r2 uses ed25519, so we need to mock the ed key functions */
    934  mocked_master_signing_key = &kp2;
    935  MOCK(get_master_signing_keypair, mock_get_master_signing_keypair);
    936 
    937  mocked_signing_key_cert = r2->cache_info.signing_key_cert;
    938  MOCK(get_master_signing_key_cert, mock_get_master_signing_key_cert);
    939 
    940  mocked_curve25519_onion_key = &r2_onion_keypair;
    941  MOCK(get_current_curve25519_keypair, mock_get_current_curve25519_keypair);
    942 
    943  /* Fake just enough of an ORPort to get by */
    944  setup_mock_configured_ports(r2->ipv4_orport, 0);
    945 
    946  /* Test the high-level interface. */
    947  rv = router_build_fresh_descriptor(&r2_out, &e2);
    948  if (rv < 0) {
    949    /* router_build_fresh_descriptor() frees r2 on failure. */
    950    r2 = NULL;
    951    /* Get rid of an alias to rp2 */
    952    r2_out = NULL;
    953  }
    954  tt_assert(rv == 0);
    955  tt_assert(r2_out);
    956  tt_assert(e2);
    957  /* Guaranteed by mock_router_build_fresh_unsigned_routerinfo() */
    958  tt_ptr_op(r2_out, OP_EQ, r2);
    959  /* Get rid of an alias to r2 */
    960  r2_out = NULL;
    961 
    962  /* Now cleanup */
    963  cleanup_mocks_for_fresh_descriptor();
    964 
    965  mocked_routerinfo = NULL;
    966  UNMOCK(router_build_fresh_unsigned_routerinfo);
    967  mocked_master_signing_key = NULL;
    968  UNMOCK(get_master_signing_keypair);
    969  mocked_signing_key_cert = NULL;
    970  UNMOCK(get_master_signing_key_cert);
    971  mocked_curve25519_onion_key = NULL;
    972  UNMOCK(get_current_curve25519_keypair);
    973 
    974  cleanup_mock_configured_ports();
    975 
    976  CHECK_EXTRAINFO_CONSISTENCY(r2, e2);
    977 
    978  /* Test that the signed ri is parseable */
    979  tt_assert(r2->cache_info.signed_descriptor_body);
    980  cp = r2->cache_info.signed_descriptor_body;
    981  rp2 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL,NULL);
    982 
    983  CHECK_ROUTERINFO_CONSISTENCY(r2, rp2);
    984 
    985  tt_mem_op(rp2->onion_curve25519_pkey->public_key,OP_EQ,
    986            r2->onion_curve25519_pkey->public_key,
    987            CURVE25519_PUBKEY_LEN);
    988 
    989  CHECK_PARSED_EXIT_POLICY(rp2);
    990 
    991  routerinfo_free(rp2);
    992 
    993  /* Test that the signed ei is parseable */
    994  tt_assert(e2->cache_info.signed_descriptor_body);
    995  cp = e2->cache_info.signed_descriptor_body;
    996  ep2 = extrainfo_parse_entry_from_string((const char*)cp,NULL,1,NULL,NULL);
    997 
    998  CHECK_EXTRAINFO_CONSISTENCY(r2, ep2);
    999 
   1000  /* In future tests, we could check the actual extrainfo statistics. */
   1001 
   1002  extrainfo_free(ep2);
   1003 
   1004 done:
   1005  dirserv_free_fingerprint_list();
   1006 
   1007  tor_free(options->Nickname);
   1008 
   1009  cleanup_mock_configured_ports();
   1010  cleanup_mocks_for_fresh_descriptor();
   1011 
   1012  if (chunks) {
   1013    SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
   1014    smartlist_free(chunks);
   1015  }
   1016 
   1017  routerinfo_free(r2);
   1018  routerinfo_free(r2_out);
   1019  routerinfo_free(rp2);
   1020 
   1021  extrainfo_free(e2);
   1022  extrainfo_free(ep2);
   1023 
   1024  tor_free(rsa_cc);
   1025  crypto_pk_free(r2_onion_pkey);
   1026 
   1027  tor_free(buf);
   1028  tor_free(buf2);
   1029 }
   1030 
   1031 #include "failing_routerdescs.inc"
   1032 
   1033 static void
   1034 test_dir_routerinfo_parsing(void *arg)
   1035 {
   1036  (void) arg;
   1037 
   1038  int again;
   1039  routerinfo_t *ri = NULL;
   1040 
   1041 #define CHECK_OK(s)                                                     \
   1042  do {                                                                  \
   1043    routerinfo_free(ri);                                                \
   1044    ri = router_parse_entry_from_string((s), NULL, 0, 0, NULL, NULL);   \
   1045    tt_assert(ri);                                                      \
   1046  } while (0)
   1047 #define CHECK_FAIL(s, againval)                                         \
   1048  do {                                                                  \
   1049    routerinfo_free(ri);                                                \
   1050    again = 999;                                                        \
   1051    ri = router_parse_entry_from_string((s), NULL, 0, 0, NULL, &again); \
   1052    tt_assert(ri == NULL);                                              \
   1053    tt_int_op(again, OP_EQ, (againval));                                \
   1054  } while (0)
   1055 
   1056  CHECK_OK(EX_RI_MINIMAL);
   1057  CHECK_OK(EX_RI_MAXIMAL);
   1058 
   1059  /* good annotations prepended */
   1060  routerinfo_free(ri);
   1061  ri = router_parse_entry_from_string(EX_RI_MINIMAL, NULL, 0, 0,
   1062                                      "@purpose bridge\n", NULL);
   1063  tt_ptr_op(ri, OP_NE, NULL);
   1064  tt_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
   1065  routerinfo_free(ri);
   1066 
   1067  /* bad annotations prepended. */
   1068  ri = router_parse_entry_from_string(EX_RI_MINIMAL,
   1069                                      NULL, 0, 0, "@purpose\n", NULL);
   1070  tt_ptr_op(ri, OP_EQ, NULL);
   1071 
   1072  /* bad annotations on router. */
   1073  ri = router_parse_entry_from_string("@purpose\nrouter x\n", NULL, 0, 1,
   1074                                      NULL, NULL);
   1075  tt_ptr_op(ri, OP_EQ, NULL);
   1076 
   1077  /* unwanted annotations on router. */
   1078  ri = router_parse_entry_from_string("@purpose foo\nrouter x\n", NULL, 0, 0,
   1079                                      NULL, NULL);
   1080  tt_ptr_op(ri, OP_EQ, NULL);
   1081 
   1082  /* No signature. */
   1083  ri = router_parse_entry_from_string("router x\n", NULL, 0, 0,
   1084                                      NULL, NULL);
   1085  tt_ptr_op(ri, OP_EQ, NULL);
   1086 
   1087  /* Not a router */
   1088  routerinfo_free(ri);
   1089  ri = router_parse_entry_from_string("hello\n", NULL, 0, 0, NULL, NULL);
   1090  tt_ptr_op(ri, OP_EQ, NULL);
   1091 
   1092  CHECK_FAIL(EX_RI_BAD_SIG1, 1);
   1093  CHECK_FAIL(EX_RI_BAD_TOKENS, 0);
   1094  CHECK_FAIL(EX_RI_BAD_PUBLISHED, 0);
   1095  CHECK_FAIL(EX_RI_NEG_BANDWIDTH, 0);
   1096  CHECK_FAIL(EX_RI_BAD_BANDWIDTH, 0);
   1097  CHECK_FAIL(EX_RI_BAD_BANDWIDTH2, 0);
   1098  CHECK_FAIL(EX_RI_BAD_BANDWIDTH3, 0);
   1099  CHECK_FAIL(EX_RI_BAD_ONIONKEY, 0);
   1100  CHECK_FAIL(EX_RI_BAD_PORTS, 0);
   1101  CHECK_FAIL(EX_RI_BAD_IP, 0);
   1102  CHECK_FAIL(EX_RI_BAD_DIRPORT, 0);
   1103  CHECK_FAIL(EX_RI_BAD_NAME2, 0);
   1104  CHECK_FAIL(EX_RI_BAD_UPTIME, 0);
   1105 
   1106  CHECK_FAIL(EX_RI_BAD_BANDWIDTH3, 0);
   1107  CHECK_FAIL(EX_RI_BAD_NTOR_KEY, 0);
   1108  CHECK_FAIL(EX_RI_BAD_FINGERPRINT, 0);
   1109  CHECK_FAIL(EX_RI_MISMATCHED_FINGERPRINT, 0);
   1110  CHECK_FAIL(EX_RI_BAD_HAS_ACCEPT6, 0);
   1111  CHECK_FAIL(EX_RI_BAD_NO_EXIT_POLICY, 0);
   1112  CHECK_FAIL(EX_RI_BAD_IPV6_EXIT_POLICY, 0);
   1113  CHECK_FAIL(EX_RI_BAD_FAMILY, 0);
   1114  CHECK_FAIL(EX_RI_ZERO_ORPORT, 0);
   1115 
   1116  CHECK_FAIL(EX_RI_ED_MISSING_CROSSCERT, 0);
   1117  CHECK_FAIL(EX_RI_ED_MISSING_CROSSCERT2, 0);
   1118  CHECK_FAIL(EX_RI_ED_MISSING_CROSSCERT_SIGN, 0);
   1119  CHECK_FAIL(EX_RI_ED_BAD_SIG1, 0);
   1120  CHECK_FAIL(EX_RI_ED_BAD_SIG2, 0);
   1121  CHECK_FAIL(EX_RI_ED_BAD_SIG3, 0);
   1122  CHECK_FAIL(EX_RI_ED_BAD_CROSSCERT1, 0);
   1123  CHECK_FAIL(EX_RI_ED_MISPLACED1, 0);
   1124  CHECK_FAIL(EX_RI_ED_MISPLACED2, 0);
   1125  CHECK_FAIL(EX_RI_ED_BAD_CERT1, 0);
   1126 
   1127 #undef CHECK_FAIL
   1128 #undef CHECK_OK
   1129 done:
   1130  routerinfo_free(ri);
   1131 }
   1132 
   1133 #include "example_extrainfo.inc"
   1134 
   1135 static void
   1136 routerinfo_free_wrapper_(void *arg)
   1137 {
   1138  routerinfo_free_(arg);
   1139 }
   1140 
   1141 static void
   1142 test_dir_extrainfo_parsing(void *arg)
   1143 {
   1144  (void) arg;
   1145 
   1146 #define CHECK_OK(s)                                                     \
   1147  do {                                                                  \
   1148    extrainfo_free(ei);                                                 \
   1149    ei = extrainfo_parse_entry_from_string((s), NULL, 0, map, NULL);    \
   1150    tt_assert(ei);                                                      \
   1151  } while (0)
   1152 #define CHECK_FAIL(s, againval)                                         \
   1153  do {                                                                  \
   1154    extrainfo_free(ei);                                                 \
   1155    again = 999;                                                        \
   1156    ei = extrainfo_parse_entry_from_string((s), NULL, 0, map, &again);  \
   1157    tt_assert(ei == NULL);                                              \
   1158    tt_int_op(again, OP_EQ, (againval));                                   \
   1159  } while (0)
   1160 #define ADD(name)                                                       \
   1161  do {                                                                  \
   1162    ri = tor_malloc_zero(sizeof(routerinfo_t));                         \
   1163    crypto_pk_t *pk = ri->identity_pkey = crypto_pk_new();              \
   1164    tt_assert(! crypto_pk_read_public_key_from_string(pk,               \
   1165                                      name##_KEY, strlen(name##_KEY))); \
   1166    tt_int_op(20,OP_EQ,base16_decode(d, 20, name##_FP, strlen(name##_FP))); \
   1167    digestmap_set((digestmap_t*)map, d, ri);                            \
   1168    ri = NULL;                                                          \
   1169  } while (0)
   1170 
   1171  routerinfo_t *ri = NULL;
   1172  char d[20];
   1173  struct digest_ri_map_t *map = NULL;
   1174  extrainfo_t *ei = NULL;
   1175  int again;
   1176 
   1177  CHECK_OK(EX_EI_MINIMAL);
   1178  tt_assert(ei->pending_sig);
   1179  CHECK_OK(EX_EI_MAXIMAL);
   1180  tt_assert(ei->pending_sig);
   1181 
   1182  map = (struct digest_ri_map_t *)digestmap_new();
   1183  ADD(EX_EI_MINIMAL);
   1184  ADD(EX_EI_MAXIMAL);
   1185  ADD(EX_EI_BAD_NICKNAME);
   1186  ADD(EX_EI_BAD_TOKENS);
   1187  ADD(EX_EI_BAD_START);
   1188  ADD(EX_EI_BAD_PUBLISHED);
   1189 
   1190  ADD(EX_EI_ED_MISSING_SIG);
   1191  ADD(EX_EI_ED_MISSING_CERT);
   1192  ADD(EX_EI_ED_BAD_CERT1);
   1193  ADD(EX_EI_ED_BAD_CERT2);
   1194  ADD(EX_EI_ED_MISPLACED_CERT);
   1195  ADD(EX_EI_ED_MISPLACED_SIG);
   1196 
   1197  CHECK_OK(EX_EI_MINIMAL);
   1198  tt_ptr_op(ei->pending_sig, OP_EQ, NULL);
   1199  CHECK_OK(EX_EI_MAXIMAL);
   1200  tt_ptr_op(ei->pending_sig, OP_EQ, NULL);
   1201 
   1202  CHECK_FAIL(EX_EI_BAD_SIG1,1);
   1203  CHECK_FAIL(EX_EI_BAD_SIG2,0);
   1204  CHECK_FAIL(EX_EI_BAD_NICKNAME,0);
   1205  CHECK_FAIL(EX_EI_BAD_TOKENS,0);
   1206  CHECK_FAIL(EX_EI_BAD_START,0);
   1207  CHECK_FAIL(EX_EI_BAD_PUBLISHED,0);
   1208 
   1209  CHECK_FAIL(EX_EI_ED_MISSING_SIG,0);
   1210  CHECK_FAIL(EX_EI_ED_MISSING_CERT,0);
   1211  CHECK_FAIL(EX_EI_ED_BAD_CERT1,0);
   1212  CHECK_FAIL(EX_EI_ED_BAD_CERT2,0);
   1213  CHECK_FAIL(EX_EI_ED_MISPLACED_CERT,0);
   1214  CHECK_FAIL(EX_EI_ED_MISPLACED_SIG,0);
   1215 
   1216 #undef CHECK_OK
   1217 #undef CHECK_FAIL
   1218 
   1219 done:
   1220  escaped(NULL);
   1221  extrainfo_free(ei);
   1222  routerinfo_free(ri);
   1223  digestmap_free_((digestmap_t*)map, routerinfo_free_wrapper_);
   1224 }
   1225 
   1226 static void
   1227 test_dir_parse_router_list(void *arg)
   1228 {
   1229  (void) arg;
   1230  smartlist_t *invalid = smartlist_new();
   1231  smartlist_t *dest = smartlist_new();
   1232  smartlist_t *chunks = smartlist_new();
   1233  int dest_has_ri = 1;
   1234  char *list = NULL;
   1235  const char *cp;
   1236  digestmap_t *map = NULL;
   1237  char *mem_op_hex_tmp = NULL;
   1238  routerinfo_t *ri = NULL;
   1239  char d[DIGEST_LEN];
   1240 
   1241  smartlist_add_strdup(chunks, EX_RI_MINIMAL);     // ri 0
   1242  smartlist_add_strdup(chunks, EX_RI_BAD_PORTS);   // bad ri 0
   1243  smartlist_add_strdup(chunks, EX_EI_MAXIMAL);     // ei 0
   1244  smartlist_add_strdup(chunks, EX_EI_BAD_SIG2);    // bad ei --
   1245  smartlist_add_strdup(chunks, EX_EI_BAD_NICKNAME);// bad ei 0
   1246  smartlist_add_strdup(chunks, EX_RI_BAD_SIG1);    // bad ri --
   1247  smartlist_add_strdup(chunks, EX_EI_BAD_PUBLISHED);  // bad ei 1
   1248  smartlist_add_strdup(chunks, EX_RI_MAXIMAL);     // ri 1
   1249  smartlist_add_strdup(chunks, EX_RI_BAD_FAMILY);  // bad ri 1
   1250  smartlist_add_strdup(chunks, EX_EI_MINIMAL);     // ei 1
   1251 
   1252  list = smartlist_join_strings(chunks, "", 0, NULL);
   1253 
   1254  /* First, parse the routers. */
   1255  cp = list;
   1256  tt_int_op(0,OP_EQ,
   1257            router_parse_list_from_string(&cp, NULL, dest, SAVED_NOWHERE,
   1258                                          0, 0, NULL, invalid));
   1259  tt_int_op(2, OP_EQ, smartlist_len(dest));
   1260  tt_ptr_op(cp, OP_EQ, list + strlen(list));
   1261 
   1262  routerinfo_t *r = smartlist_get(dest, 0);
   1263  tt_mem_op(r->cache_info.signed_descriptor_body, OP_EQ,
   1264            EX_RI_MINIMAL, strlen(EX_RI_MINIMAL));
   1265  r = smartlist_get(dest, 1);
   1266  tt_mem_op(r->cache_info.signed_descriptor_body, OP_EQ,
   1267            EX_RI_MAXIMAL, strlen(EX_RI_MAXIMAL));
   1268 
   1269  setup_ei_digests();
   1270 
   1271  tt_int_op(2, OP_EQ, smartlist_len(invalid));
   1272 
   1273  test_memeq_hex(smartlist_get(invalid, 0),
   1274                 "10F951AF93AED0D3BC7FA5FFA232EB8C17747ACE");
   1275  test_memeq_hex(smartlist_get(invalid, 1),
   1276                 "41D8723CDD4B1AADCCE538C28CDE7F69828C73D0");
   1277 
   1278  /* Now tidy up */
   1279  SMARTLIST_FOREACH(dest, routerinfo_t *, rinfo, routerinfo_free(rinfo));
   1280  SMARTLIST_FOREACH(invalid, uint8_t *, dig, tor_free(dig));
   1281  smartlist_clear(dest);
   1282  smartlist_clear(invalid);
   1283 
   1284  /* And check extrainfos. */
   1285  dest_has_ri = 0;
   1286  map = (digestmap_t*)router_get_routerlist()->identity_map;
   1287  ADD(EX_EI_MINIMAL);
   1288  ADD(EX_EI_MAXIMAL);
   1289  ADD(EX_EI_BAD_NICKNAME);
   1290  ADD(EX_EI_BAD_PUBLISHED);
   1291  ADD(EX_EI_BAD_SIG2);
   1292  cp = list;
   1293  tt_int_op(0,OP_EQ,
   1294            router_parse_list_from_string(&cp, NULL, dest, SAVED_NOWHERE,
   1295                                          1, 0, NULL, invalid));
   1296  tt_int_op(2, OP_EQ, smartlist_len(dest));
   1297  extrainfo_t *e = smartlist_get(dest, 0);
   1298  tt_mem_op(e->cache_info.signed_descriptor_body, OP_EQ,
   1299            EX_EI_MAXIMAL, strlen(EX_EI_MAXIMAL));
   1300  e = smartlist_get(dest, 1);
   1301  tt_mem_op(e->cache_info.signed_descriptor_body, OP_EQ,
   1302            EX_EI_MINIMAL, strlen(EX_EI_MINIMAL));
   1303 
   1304  tt_int_op(3, OP_EQ, smartlist_len(invalid));
   1305  tt_mem_op(smartlist_get(invalid, 0),
   1306            OP_EQ,
   1307            digest_ei_bad_sig2, DIGEST_LEN);
   1308  tt_mem_op(smartlist_get(invalid, 1),
   1309            OP_EQ,
   1310            digest_ei_bad_nickname, DIGEST_LEN);
   1311  tt_mem_op(smartlist_get(invalid, 2),
   1312            OP_EQ,
   1313            digest_ei_bad_published, DIGEST_LEN);
   1314 
   1315 done:
   1316  tor_free(list);
   1317  if (dest_has_ri)
   1318    SMARTLIST_FOREACH(dest, routerinfo_t *, rt, routerinfo_free(rt));
   1319  else
   1320    SMARTLIST_FOREACH(dest, extrainfo_t *, ei, extrainfo_free(ei));
   1321  smartlist_free(dest);
   1322  SMARTLIST_FOREACH(invalid, uint8_t *, dig, tor_free(dig));
   1323  smartlist_free(invalid);
   1324  SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
   1325  smartlist_free(chunks);
   1326  routerinfo_free(ri);
   1327  if (map) {
   1328    digestmap_free_((digestmap_t*)map, routerinfo_free_wrapper_);
   1329    router_get_routerlist()->identity_map =
   1330      (struct digest_ri_map_t*)digestmap_new();
   1331  }
   1332  tor_free(mem_op_hex_tmp);
   1333 
   1334 #undef ADD
   1335 }
   1336 
   1337 /* Made with chutney and a patched tor: Has no onion-key or
   1338 * onion-key-crosscert */
   1339 static const char ROUTERDESC_NO_ONION_KEY[] =
   1340 "router test001a 127.0.0.1 5001 0 7001\n"
   1341 "identity-ed25519\n"
   1342 "-----BEGIN ED25519 CERT-----\n"
   1343 "AQQAB0xWARbCJfDrX0OTtpM0fDxU9cLweMnZeUq/KBfAN1wwWHtMAQAgBADBQJ1o\n"
   1344 "ClrXUenWC90FYEUQDpMSdxdxKlrR83rYy+keGe61WQHYP0ebowJC19UvPnYryLeA\n"
   1345 "Gnhko2WwmbUDGicdnY4j2VSFU15oxBjln65IznZJyiZM4zGE1GkNZzKGmQY=\n"
   1346 "-----END ED25519 CERT-----\n"
   1347 "master-key-ed25519 wUCdaApa11Hp1gvdBWBFEA6TEncXcSpa0fN62MvpHhk\n"
   1348 "or-address [::]:5001\n"
   1349 "platform Tor 0.4.9.0-alpha-dev on Linux\n"
   1350 "proto Conflux=1 Cons=1-2 Desc=1-2 DirCache=2 FlowCtrl=1-2 HSDir=2 "
   1351  "HSIntro=4-5 HSRend=1-2 Link=1-5 LinkAuth=1,3 Microdesc=1-2 Padding=2 "
   1352  "Relay=1-4\n"
   1353 "published 2024-06-24 21:34:22\n"
   1354 "fingerprint FD3A 6FA4 E716 C379 3CBA FEC3 39EA 01C8 B49D 7189\n"
   1355 "uptime 0\n"
   1356 "bandwidth 1073741824 1073741824 0\n"
   1357 "extra-info-digest 9946CAC41485EDFFDD83F7DAF1A088C30563126C "
   1358  "lpAMRlRTy9QR2xVCu1nnnxOHA2I05TTKvCSPPcr1geo\n"
   1359 "caches-extra-info\n"
   1360 "signing-key\n"
   1361 "-----BEGIN RSA PUBLIC KEY-----\n"
   1362 "MIGJAoGBALcIIij7gNpvSZPvaCLDDNyyQZq7fR0aXiHgmiIc5hYVcBl+zF5sTX6a\n"
   1363 "jQF+GQdbSHcRzA1IMWPXnA7+nGOxSNayrQwExuf7ESsBaQHU81/dmV+rgTwtcd3K\n"
   1364 "9lobTQUm+idLvGjVF5P1XJkduPvURIgpIfXT1ZHJUQhwxWSw8MmnAgMBAAE=\n"
   1365 "-----END RSA PUBLIC KEY-----\n"
   1366 "ntor-onion-key-crosscert 1\n"
   1367 "-----BEGIN ED25519 CERT-----\n"
   1368 "AQoAB0wmAcFAnWgKWtdR6dYL3QVgRRAOkxJ3F3EqWtHzetjL6R4ZAFPSCMLyQ82v\n"
   1369 "dvcpZDa7C/qp8TsJn2Z8v77RjRc2QD1KYDzGfg5euwlB1lu8+IR38l3mmC1PXXhe\n"
   1370 "ZB84q4aUdAA=\n"
   1371 "-----END ED25519 CERT-----\n"
   1372 "hidden-service-dir\n"
   1373 "contact auth1@test.test\n"
   1374 "ntor-onion-key m0dedSB2vjtvz08bNu+LCdIApVuspRlzXbsphXZ62zQ\n"
   1375 "reject *:*\n"
   1376 "tunnelled-dir-server\n"
   1377 "router-sig-ed25519 VMwmiN9KhWWFSFSuVZxG1g46mb2QhMhv0UlatvPKyAV+1jPl"
   1378  "EbDFaO1Qur0335Rn0ToysC6UqB1p78pefX67Aw\n"
   1379 "router-signature\n"
   1380 "-----BEGIN SIGNATURE-----\n"
   1381 "q9Hxy4FJVIK2ks/ByBv8P1p7Pc68ie/TTlDN+tce9opPlijy9+ze9/Gd2SKonRm1\n"
   1382 "J+WBj/kKYKw+YoUExIT0qMfa6QTCOe/ecp1sNmgeW0YfloP4Nv8goi3S0k4yrPk/\n"
   1383 "qw6TIXGYJpvrdR1Qe7+MEl2K1Okqsy5amtOU400lYRA=\n"
   1384 "-----END SIGNATURE-----\n"
   1385  ;
   1386 
   1387 static void
   1388 test_dir_parse_no_onion_keyrouter_list(void *arg)
   1389 {
   1390  (void) arg;
   1391 
   1392  routerinfo_t *ri =
   1393    router_parse_entry_from_string(ROUTERDESC_NO_ONION_KEY, NULL,
   1394                                   0, 1, 0, NULL);
   1395 
   1396  tt_assert(ri);
   1397  tt_assert(ri->tap_onion_pkey == NULL);
   1398 
   1399 done:
   1400  routerinfo_free(ri);
   1401 }
   1402 
   1403 static download_status_t dls_minimal;
   1404 static download_status_t dls_maximal;
   1405 static download_status_t dls_bad_fingerprint;
   1406 static download_status_t dls_bad_sig1;
   1407 static download_status_t dls_bad_ports;
   1408 static download_status_t dls_bad_tokens;
   1409 
   1410 static uint8_t digest_minimal[20];
   1411 static uint8_t digest_maximal[20];
   1412 static uint8_t digest_bad_fingerprint[20];
   1413 static uint8_t digest_bad_sig1[20];
   1414 static uint8_t digest_bad_ports[20];
   1415 static uint8_t digest_bad_tokens[20];
   1416 
   1417 static void
   1418 setup_dls_digests(void)
   1419 {
   1420 #define SETUP(string, name)                                             \
   1421  do {                                                                  \
   1422    router_get_router_hash(string, strlen(string), (char*)digest_##name); \
   1423  } while (0)
   1424 
   1425  SETUP(EX_RI_MINIMAL, minimal);
   1426  SETUP(EX_RI_MAXIMAL, maximal);
   1427  SETUP(EX_RI_BAD_FINGERPRINT, bad_fingerprint);
   1428  SETUP(EX_RI_BAD_SIG1, bad_sig1);
   1429  SETUP(EX_RI_BAD_PORTS, bad_ports);
   1430  SETUP(EX_RI_BAD_TOKENS, bad_tokens);
   1431 #undef SETUP
   1432 }
   1433 
   1434 static int mock_router_get_dl_status_unrecognized = 0;
   1435 static int mock_router_get_dl_status_calls = 0;
   1436 
   1437 static download_status_t *
   1438 mock_router_get_dl_status(const char *d)
   1439 {
   1440  ++mock_router_get_dl_status_calls;
   1441 #define CHECK(name)                                         \
   1442  do {                                                      \
   1443    if (fast_memeq(d, digest_##name, DIGEST_LEN))           \
   1444      return &dls_##name;                                   \
   1445  } while (0)
   1446 
   1447  CHECK(minimal);
   1448  CHECK(maximal);
   1449  CHECK(bad_fingerprint);
   1450  CHECK(bad_sig1);
   1451  CHECK(bad_ports);
   1452  CHECK(bad_tokens);
   1453 
   1454  ++mock_router_get_dl_status_unrecognized;
   1455  return NULL;
   1456 #undef CHECK
   1457 }
   1458 
   1459 static void
   1460 test_dir_load_routers(void *arg)
   1461 {
   1462  (void) arg;
   1463  smartlist_t *chunks = smartlist_new();
   1464  smartlist_t *wanted = smartlist_new();
   1465  char buf[DIGEST_LEN];
   1466  char *mem_op_hex_tmp = NULL;
   1467  char *list = NULL;
   1468 
   1469 #define ADD(str)                                                        \
   1470  do {                                                                  \
   1471    tt_int_op(0,OP_EQ,router_get_router_hash(str, strlen(str), buf));      \
   1472    smartlist_add_strdup(wanted, hex_str(buf, DIGEST_LEN));        \
   1473  } while (0)
   1474 
   1475  setup_dls_digests();
   1476 
   1477  MOCK(router_get_dl_status_by_descriptor_digest, mock_router_get_dl_status);
   1478 
   1479  update_approx_time(1412510400);
   1480 
   1481  smartlist_add_strdup(chunks, EX_RI_MINIMAL);
   1482  smartlist_add_strdup(chunks, EX_RI_BAD_FINGERPRINT);
   1483  smartlist_add_strdup(chunks, EX_RI_BAD_SIG1);
   1484  smartlist_add_strdup(chunks, EX_RI_MAXIMAL);
   1485  smartlist_add_strdup(chunks, EX_RI_BAD_PORTS);
   1486  smartlist_add_strdup(chunks, EX_RI_BAD_TOKENS);
   1487 
   1488  /* not ADDing MINIMAL */
   1489  ADD(EX_RI_MAXIMAL);
   1490  ADD(EX_RI_BAD_FINGERPRINT);
   1491  ADD(EX_RI_BAD_SIG1);
   1492  /* Not ADDing BAD_PORTS */
   1493  ADD(EX_RI_BAD_TOKENS);
   1494 
   1495  list = smartlist_join_strings(chunks, "", 0, NULL);
   1496  tt_int_op(1, OP_EQ,
   1497            router_load_routers_from_string(list, NULL, SAVED_IN_JOURNAL,
   1498                                            wanted, 1, NULL));
   1499 
   1500  /* The "maximal" router was added. */
   1501  /* "minimal" was not. */
   1502  tt_int_op(smartlist_len(router_get_routerlist()->routers),OP_EQ,1);
   1503  routerinfo_t *r = smartlist_get(router_get_routerlist()->routers, 0);
   1504  test_memeq_hex(r->cache_info.signed_descriptor_digest,
   1505                 "1F437798ACD1FC9CBD1C3C04DBF80F7E9F819C3F");
   1506  tt_int_op(dls_minimal.n_download_failures, OP_EQ, 0);
   1507  tt_int_op(dls_maximal.n_download_failures, OP_EQ, 0);
   1508 
   1509  /* "Bad fingerprint" and "Bad tokens" should have gotten marked
   1510   * non-retriable. */
   1511  tt_want_int_op(mock_router_get_dl_status_calls, OP_EQ, 2);
   1512  tt_want_int_op(mock_router_get_dl_status_unrecognized, OP_EQ, 0);
   1513  tt_int_op(dls_bad_fingerprint.n_download_failures, OP_EQ, 255);
   1514  tt_int_op(dls_bad_tokens.n_download_failures, OP_EQ, 255);
   1515 
   1516  /* bad_sig2 and bad ports" are retriable -- one since only the signature
   1517   * was bad, and one because we didn't ask for it. */
   1518  tt_int_op(dls_bad_sig1.n_download_failures, OP_EQ, 0);
   1519  tt_int_op(dls_bad_ports.n_download_failures, OP_EQ, 0);
   1520 
   1521  tt_int_op(smartlist_len(wanted), OP_EQ, 1);
   1522  tt_str_op(smartlist_get(wanted, 0), OP_EQ,
   1523            "3BB7D03C1C4DBC1DDE840096FF3C330914757B77");
   1524 
   1525 #undef ADD
   1526 
   1527 done:
   1528  tor_free(mem_op_hex_tmp);
   1529  UNMOCK(router_get_dl_status_by_descriptor_digest);
   1530  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   1531  smartlist_free(chunks);
   1532  SMARTLIST_FOREACH(wanted, char *, cp, tor_free(cp));
   1533  smartlist_free(wanted);
   1534  tor_free(list);
   1535 }
   1536 
   1537 static int mock_get_by_ei_dd_calls = 0;
   1538 static int mock_get_by_ei_dd_unrecognized = 0;
   1539 
   1540 static signed_descriptor_t sd_ei_minimal;
   1541 static signed_descriptor_t sd_ei_bad_nickname;
   1542 static signed_descriptor_t sd_ei_maximal;
   1543 static signed_descriptor_t sd_ei_bad_tokens;
   1544 static signed_descriptor_t sd_ei_bad_sig2;
   1545 
   1546 static void
   1547 setup_ei_digests(void)
   1548 {
   1549 #define SETUP(string, name)                                             \
   1550  do {                                                                  \
   1551    router_get_extrainfo_hash(string, strlen(string),                   \
   1552                              (char*)digest_ei_##name);                 \
   1553  } while (0)
   1554 
   1555  SETUP(EX_EI_MINIMAL, minimal);
   1556  SETUP(EX_EI_MAXIMAL, maximal);
   1557  SETUP(EX_EI_BAD_NICKNAME, bad_nickname);
   1558  SETUP(EX_EI_BAD_TOKENS, bad_tokens);
   1559  SETUP(EX_EI_BAD_SIG2, bad_sig2);
   1560  SETUP(EX_EI_BAD_PUBLISHED, bad_published);
   1561 
   1562 #undef SETUP
   1563 }
   1564 
   1565 static signed_descriptor_t *
   1566 mock_get_by_ei_desc_digest(const char *d)
   1567 {
   1568  ++mock_get_by_ei_dd_calls;
   1569 #define CHECK(name)                                         \
   1570  do {                                                      \
   1571    if (fast_memeq(d, digest_ei_##name, DIGEST_LEN))        \
   1572      return &sd_ei_##name;                                 \
   1573  } while (0)
   1574 
   1575  CHECK(minimal);
   1576  CHECK(maximal);
   1577  CHECK(bad_nickname);
   1578  CHECK(bad_sig2);
   1579  CHECK(bad_tokens);
   1580  ++mock_get_by_ei_dd_unrecognized;
   1581  return NULL;
   1582 #undef CHECK
   1583 }
   1584 
   1585 static signed_descriptor_t *
   1586 mock_ei_get_by_ei_digest(const char *d)
   1587 {
   1588  signed_descriptor_t *sd = &sd_ei_minimal;
   1589 
   1590  if (fast_memeq(d, digest_ei_minimal, DIGEST_LEN)) {
   1591    sd->signed_descriptor_body = (char *)EX_EI_MINIMAL;
   1592    sd->signed_descriptor_len = sizeof(EX_EI_MINIMAL);
   1593    sd->annotations_len = 0;
   1594    sd->saved_location = SAVED_NOWHERE;
   1595    return sd;
   1596  }
   1597  return NULL;
   1598 }
   1599 
   1600 static smartlist_t *mock_ei_insert_list = NULL;
   1601 static was_router_added_t
   1602 mock_ei_insert(routerlist_t *rl, extrainfo_t *ei, int warn_if_incompatible)
   1603 {
   1604  (void) rl;
   1605  (void) warn_if_incompatible;
   1606  smartlist_add(mock_ei_insert_list, ei);
   1607  return ROUTER_ADDED_SUCCESSFULLY;
   1608 }
   1609 
   1610 static void
   1611 test_dir_load_extrainfo(void *arg)
   1612 {
   1613  (void) arg;
   1614  smartlist_t *chunks = smartlist_new();
   1615  smartlist_t *wanted = smartlist_new();
   1616  char buf[DIGEST_LEN];
   1617  char *mem_op_hex_tmp = NULL;
   1618  char *list = NULL;
   1619 
   1620 #define ADD(str)                                                        \
   1621  do {                                                                  \
   1622    tt_int_op(0,OP_EQ,router_get_extrainfo_hash(str, strlen(str), buf));   \
   1623    smartlist_add_strdup(wanted, hex_str(buf, DIGEST_LEN));        \
   1624  } while (0)
   1625 
   1626  setup_ei_digests();
   1627  mock_ei_insert_list = smartlist_new();
   1628  MOCK(router_get_by_extrainfo_digest, mock_get_by_ei_desc_digest);
   1629  MOCK(extrainfo_insert, mock_ei_insert);
   1630 
   1631  smartlist_add_strdup(chunks, EX_EI_MINIMAL);
   1632  smartlist_add_strdup(chunks, EX_EI_BAD_NICKNAME);
   1633  smartlist_add_strdup(chunks, EX_EI_MAXIMAL);
   1634  smartlist_add_strdup(chunks, EX_EI_BAD_PUBLISHED);
   1635  smartlist_add_strdup(chunks, EX_EI_BAD_TOKENS);
   1636 
   1637  /* not ADDing MINIMAL */
   1638  ADD(EX_EI_MAXIMAL);
   1639  ADD(EX_EI_BAD_NICKNAME);
   1640  /* Not ADDing BAD_PUBLISHED */
   1641  ADD(EX_EI_BAD_TOKENS);
   1642  ADD(EX_EI_BAD_SIG2);
   1643 
   1644  list = smartlist_join_strings(chunks, "", 0, NULL);
   1645  router_load_extrainfo_from_string(list, NULL, SAVED_IN_JOURNAL, wanted, 1);
   1646 
   1647  /* The "maximal" router was added. */
   1648  /* "minimal" was also added, even though we didn't ask for it, since
   1649   * that's what we do with extrainfos. */
   1650  tt_int_op(smartlist_len(mock_ei_insert_list),OP_EQ,2);
   1651 
   1652  extrainfo_t *e = smartlist_get(mock_ei_insert_list, 0);
   1653  tt_mem_op(e->cache_info.signed_descriptor_digest, OP_EQ,
   1654            digest_ei_minimal, DIGEST_LEN);
   1655 
   1656  e = smartlist_get(mock_ei_insert_list, 1);
   1657  tt_mem_op(e->cache_info.signed_descriptor_digest, OP_EQ,
   1658            digest_ei_maximal, DIGEST_LEN);
   1659  tt_int_op(dls_minimal.n_download_failures, OP_EQ, 0);
   1660  tt_int_op(dls_maximal.n_download_failures, OP_EQ, 0);
   1661 
   1662  /* "Bad nickname" and "Bad tokens" should have gotten marked
   1663   * non-retriable. */
   1664  tt_want_int_op(mock_get_by_ei_dd_calls, OP_EQ, 2);
   1665  tt_want_int_op(mock_get_by_ei_dd_unrecognized, OP_EQ, 0);
   1666  tt_int_op(sd_ei_bad_nickname.ei_dl_status.n_download_failures, OP_EQ, 255);
   1667  tt_int_op(sd_ei_bad_tokens.ei_dl_status.n_download_failures, OP_EQ, 255);
   1668 
   1669  /* bad_ports is retriable -- because we didn't ask for it. */
   1670  tt_int_op(dls_bad_ports.n_download_failures, OP_EQ, 0);
   1671 
   1672  /* Wanted still contains "BAD_SIG2" */
   1673  tt_int_op(smartlist_len(wanted), OP_EQ, 1);
   1674  const char *got_wanted =smartlist_get(wanted, 0);
   1675  tt_int_op(strlen(got_wanted), OP_EQ, HEX_DIGEST_LEN);
   1676  char d[DIGEST_LEN];
   1677  base16_decode(d, DIGEST_LEN, got_wanted, strlen(got_wanted));
   1678  tt_mem_op(d, OP_EQ, digest_ei_bad_sig2, DIGEST_LEN);
   1679 
   1680 #undef ADD
   1681 
   1682 done:
   1683  tor_free(mem_op_hex_tmp);
   1684  UNMOCK(router_get_by_extrainfo_digest);
   1685  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   1686  smartlist_free(chunks);
   1687  SMARTLIST_FOREACH(wanted, char *, cp, tor_free(cp));
   1688  smartlist_free(wanted);
   1689  tor_free(list);
   1690 }
   1691 
   1692 static void
   1693 test_dir_getinfo_extra(void *arg)
   1694 {
   1695  int r;
   1696  char *answer = NULL;
   1697  const char *errmsg = NULL;
   1698  char buf[128];
   1699  char hexdigest[HEX_DIGEST_LEN+1];
   1700  (void)arg;
   1701 
   1702  setup_ei_digests();
   1703  base16_encode(hexdigest, sizeof(hexdigest),
   1704                (const char*)digest_ei_minimal, DIGEST_LEN);
   1705  tor_snprintf(buf, sizeof(buf), "extra-info/digest/%s", hexdigest);
   1706 
   1707  MOCK(extrainfo_get_by_descriptor_digest, mock_ei_get_by_ei_digest);
   1708  r = getinfo_helper_dir(NULL, buf, &answer, &errmsg);
   1709  tt_int_op(0, OP_EQ, r);
   1710  tt_ptr_op(NULL, OP_EQ, errmsg);
   1711  tt_str_op(answer, OP_EQ, EX_EI_MINIMAL);
   1712  tor_free(answer);
   1713 
   1714  answer = NULL;
   1715  r = getinfo_helper_dir(NULL, "extra-info/digest/"
   1716                         "NOTAVALIDHEXSTRINGNOTAVALIDHEXSTRINGNOTA", &answer,
   1717                         &errmsg);
   1718  tt_int_op(0, OP_EQ, r);
   1719  /* getinfo_helper_dir() should maybe return an error here but doesn't */
   1720  tt_ptr_op(NULL, OP_EQ, errmsg);
   1721  /* In any case, there should be no answer for an invalid hex string. */
   1722  tt_ptr_op(NULL, OP_EQ, answer);
   1723 
   1724 done:
   1725  UNMOCK(extrainfo_get_by_descriptor_digest);
   1726 }
   1727 
   1728 static void
   1729 test_dir_versions(void *arg)
   1730 {
   1731  tor_version_t ver1;
   1732 
   1733  /* Try out version parsing functionality */
   1734  (void)arg;
   1735  tt_int_op(0,OP_EQ, tor_version_parse("0.3.4pre2-cvs", &ver1));
   1736  tt_int_op(0,OP_EQ, ver1.major);
   1737  tt_int_op(3,OP_EQ, ver1.minor);
   1738  tt_int_op(4,OP_EQ, ver1.micro);
   1739  tt_int_op(VER_PRE,OP_EQ, ver1.status);
   1740  tt_int_op(2,OP_EQ, ver1.patchlevel);
   1741  tt_int_op(0,OP_EQ, tor_version_parse("0.3.4rc1", &ver1));
   1742  tt_int_op(0,OP_EQ, ver1.major);
   1743  tt_int_op(3,OP_EQ, ver1.minor);
   1744  tt_int_op(4,OP_EQ, ver1.micro);
   1745  tt_int_op(VER_RC,OP_EQ, ver1.status);
   1746  tt_int_op(1,OP_EQ, ver1.patchlevel);
   1747  tt_int_op(0,OP_EQ, tor_version_parse("1.3.4", &ver1));
   1748  tt_int_op(1,OP_EQ, ver1.major);
   1749  tt_int_op(3,OP_EQ, ver1.minor);
   1750  tt_int_op(4,OP_EQ, ver1.micro);
   1751  tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
   1752  tt_int_op(0,OP_EQ, ver1.patchlevel);
   1753  tt_int_op(0,OP_EQ, tor_version_parse("1.3.4.999", &ver1));
   1754  tt_int_op(1,OP_EQ, ver1.major);
   1755  tt_int_op(3,OP_EQ, ver1.minor);
   1756  tt_int_op(4,OP_EQ, ver1.micro);
   1757  tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
   1758  tt_int_op(999,OP_EQ, ver1.patchlevel);
   1759  tt_int_op(0,OP_EQ, tor_version_parse("0.1.2.4-alpha", &ver1));
   1760  tt_int_op(0,OP_EQ, ver1.major);
   1761  tt_int_op(1,OP_EQ, ver1.minor);
   1762  tt_int_op(2,OP_EQ, ver1.micro);
   1763  tt_int_op(4,OP_EQ, ver1.patchlevel);
   1764  tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
   1765  tt_str_op("alpha",OP_EQ, ver1.status_tag);
   1766  tt_int_op(0,OP_EQ, tor_version_parse("0.1.2.4", &ver1));
   1767  tt_int_op(0,OP_EQ, ver1.major);
   1768  tt_int_op(1,OP_EQ, ver1.minor);
   1769  tt_int_op(2,OP_EQ, ver1.micro);
   1770  tt_int_op(4,OP_EQ, ver1.patchlevel);
   1771  tt_int_op(VER_RELEASE,OP_EQ, ver1.status);
   1772  tt_str_op("",OP_EQ, ver1.status_tag);
   1773 
   1774  tt_int_op(0, OP_EQ, tor_version_parse("10.1", &ver1));
   1775  tt_int_op(10, OP_EQ, ver1.major);
   1776  tt_int_op(1, OP_EQ, ver1.minor);
   1777  tt_int_op(0, OP_EQ, ver1.micro);
   1778  tt_int_op(0, OP_EQ, ver1.patchlevel);
   1779  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1780  tt_str_op("", OP_EQ, ver1.status_tag);
   1781  tt_int_op(0, OP_EQ, tor_version_parse("5.99.999", &ver1));
   1782  tt_int_op(5, OP_EQ, ver1.major);
   1783  tt_int_op(99, OP_EQ, ver1.minor);
   1784  tt_int_op(999, OP_EQ, ver1.micro);
   1785  tt_int_op(0, OP_EQ, ver1.patchlevel);
   1786  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1787  tt_str_op("", OP_EQ, ver1.status_tag);
   1788  tt_int_op(0, OP_EQ, tor_version_parse("10.1-alpha", &ver1));
   1789  tt_int_op(10, OP_EQ, ver1.major);
   1790  tt_int_op(1, OP_EQ, ver1.minor);
   1791  tt_int_op(0, OP_EQ, ver1.micro);
   1792  tt_int_op(0, OP_EQ, ver1.patchlevel);
   1793  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1794  tt_str_op("alpha", OP_EQ, ver1.status_tag);
   1795  /* Go through the full set of status tags */
   1796  tt_int_op(0, OP_EQ, tor_version_parse("2.1.700-alpha", &ver1));
   1797  tt_int_op(2, OP_EQ, ver1.major);
   1798  tt_int_op(1, OP_EQ, ver1.minor);
   1799  tt_int_op(700, OP_EQ, ver1.micro);
   1800  tt_int_op(0, OP_EQ, ver1.patchlevel);
   1801  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1802  tt_str_op("alpha", OP_EQ, ver1.status_tag);
   1803  tt_int_op(0, OP_EQ, tor_version_parse("1.6.8-alpha-dev", &ver1));
   1804  tt_int_op(1, OP_EQ, ver1.major);
   1805  tt_int_op(6, OP_EQ, ver1.minor);
   1806  tt_int_op(8, OP_EQ, ver1.micro);
   1807  tt_int_op(0, OP_EQ, ver1.patchlevel);
   1808  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1809  tt_str_op("alpha-dev", OP_EQ, ver1.status_tag);
   1810  tt_int_op(0, OP_EQ, tor_version_parse("0.2.9.5-rc", &ver1));
   1811  tt_int_op(0, OP_EQ, ver1.major);
   1812  tt_int_op(2, OP_EQ, ver1.minor);
   1813  tt_int_op(9, OP_EQ, ver1.micro);
   1814  tt_int_op(5, OP_EQ, ver1.patchlevel);
   1815  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1816  tt_str_op("rc", OP_EQ, ver1.status_tag);
   1817  tt_int_op(0, OP_EQ, tor_version_parse("0.2.9.6-rc-dev", &ver1));
   1818  tt_int_op(0, OP_EQ, ver1.major);
   1819  tt_int_op(2, OP_EQ, ver1.minor);
   1820  tt_int_op(9, OP_EQ, ver1.micro);
   1821  tt_int_op(6, OP_EQ, ver1.patchlevel);
   1822  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1823  tt_str_op("rc-dev", OP_EQ, ver1.status_tag);
   1824  tt_int_op(0, OP_EQ, tor_version_parse("0.2.9.8", &ver1));
   1825  tt_int_op(0, OP_EQ, ver1.major);
   1826  tt_int_op(2, OP_EQ, ver1.minor);
   1827  tt_int_op(9, OP_EQ, ver1.micro);
   1828  tt_int_op(8, OP_EQ, ver1.patchlevel);
   1829  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1830  tt_str_op("", OP_EQ, ver1.status_tag);
   1831  tt_int_op(0, OP_EQ, tor_version_parse("0.2.9.9-dev", &ver1));
   1832  tt_int_op(0, OP_EQ, ver1.major);
   1833  tt_int_op(2, OP_EQ, ver1.minor);
   1834  tt_int_op(9, OP_EQ, ver1.micro);
   1835  tt_int_op(9, OP_EQ, ver1.patchlevel);
   1836  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1837  tt_str_op("dev", OP_EQ, ver1.status_tag);
   1838  /* In #21450, we fixed an inconsistency in parsing versions > INT32_MAX
   1839   * between i386 and x86_64, as we used tor_parse_long, and then cast to int
   1840   */
   1841  tt_int_op(0, OP_EQ, tor_version_parse("0.2147483647.0", &ver1));
   1842  tt_int_op(0, OP_EQ, ver1.major);
   1843  tt_int_op(2147483647, OP_EQ, ver1.minor);
   1844  tt_int_op(0, OP_EQ, ver1.micro);
   1845  tt_int_op(0, OP_EQ, ver1.patchlevel);
   1846  tt_int_op(VER_RELEASE, OP_EQ, ver1.status);
   1847  tt_str_op("", OP_EQ, ver1.status_tag);
   1848  tt_int_op(-1, OP_EQ, tor_version_parse("0.2147483648.0", &ver1));
   1849  tt_int_op(-1, OP_EQ, tor_version_parse("0.4294967295.0", &ver1));
   1850  /* In #21278, we reject negative version components */
   1851  tt_int_op(-1, OP_EQ, tor_version_parse("0.-1.0", &ver1));
   1852  tt_int_op(-1, OP_EQ, tor_version_parse("0.-2147483648.0", &ver1));
   1853  tt_int_op(-1, OP_EQ, tor_version_parse("0.-4294967295.0", &ver1));
   1854  /* In #21507, we reject version components with non-numeric prefixes */
   1855  tt_int_op(-1, OP_EQ, tor_version_parse("0.-0.0", &ver1));
   1856  tt_int_op(-1, OP_EQ, tor_version_parse("+1.0.0", &ver1));
   1857  /* use the list in isspace() */
   1858  tt_int_op(-1, OP_EQ, tor_version_parse("0.\t0.0", &ver1));
   1859  tt_int_op(-1, OP_EQ, tor_version_parse("0.\n0.0", &ver1));
   1860  tt_int_op(-1, OP_EQ, tor_version_parse("0.\v0.0", &ver1));
   1861  tt_int_op(-1, OP_EQ, tor_version_parse("0.\f0.0", &ver1));
   1862  tt_int_op(-1, OP_EQ, tor_version_parse("0.\r0.0", &ver1));
   1863  tt_int_op(-1, OP_EQ, tor_version_parse("0. 0.0", &ver1));
   1864 
   1865 #define tt_versionstatus_op(vs1, op, vs2)                               \
   1866  tt_assert_test_type(vs1,vs2,#vs1" "#op" "#vs2,version_status_t,       \
   1867                      (val1_ op val2_),"%d",TT_EXIT_TEST_FUNCTION)
   1868 #define test_v_i_o(val, ver, lst)                                       \
   1869  tt_versionstatus_op(val, OP_EQ, tor_version_is_obsolete(ver, lst))
   1870 
   1871  /* make sure tor_version_is_obsolete() works */
   1872  test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
   1873  test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
   1874  test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
   1875  test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
   1876  test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
   1877  test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
   1878  test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
   1879  test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
   1880  test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
   1881  test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
   1882  test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
   1883  test_v_i_o(VS_NEW, "0.2.9.9-dev", "0.2.9.9");
   1884  /* Not on list, but newer than any in same series. */
   1885  test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
   1886             "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
   1887  /* Series newer than any on list. */
   1888  test_v_i_o(VS_NEW, "0.1.2.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
   1889  /* Series older than any on list. */
   1890  test_v_i_o(VS_OLD, "0.0.1.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
   1891  /* Not on list, not newer than any on same series. */
   1892  test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
   1893             "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
   1894  /* On list, not newer than any on same series. */
   1895  test_v_i_o(VS_UNRECOMMENDED,
   1896             "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
   1897  tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
   1898  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1899          "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
   1900          "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
   1901          "0.0.8rc2"));
   1902  tt_int_op(0,OP_EQ, tor_version_as_new_as(
   1903          "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
   1904          "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
   1905 
   1906  /* Now try svn revisions. */
   1907  tt_int_op(1,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
   1908                                   "Tor 0.2.1.0-dev (r99)"));
   1909  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1910                                   "Tor 0.2.1.0-dev (r100) on Banana Jr",
   1911                                   "Tor 0.2.1.0-dev (r99) on Hal 9000"));
   1912  tt_int_op(1,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
   1913                                   "Tor 0.2.1.0-dev on Colossus"));
   1914  tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
   1915                                   "Tor 0.2.1.0-dev (r100)"));
   1916  tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
   1917                                   "Tor 0.2.1.0-dev (r100) on AM"));
   1918  tt_int_op(0,OP_EQ, tor_version_as_new_as("Tor 0.2.1.0-dev",
   1919                                   "Tor 0.2.1.0-dev (r99)"));
   1920  tt_int_op(1,OP_EQ, tor_version_as_new_as("Tor 0.2.1.1",
   1921                                   "Tor 0.2.1.0-dev (r99)"));
   1922  /* And git revisions */
   1923  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1924                                        "Tor 0.2.9.9 (git-56788a2489127072)",
   1925                                        "Tor 0.2.9.9 (git-56788a2489127072)"));
   1926  /* a git revision is newer than no git revision */
   1927  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1928                                        "Tor 0.2.9.9 (git-56788a2489127072)",
   1929                                        "Tor 0.2.9.9"));
   1930  /* a longer git revision is newer than a shorter git revision
   1931   * this should be true if they prefix-match, but if they don't, they are
   1932   * incomparable, because hashes aren't ordered (but we compare their bytes
   1933   * anyway) */
   1934  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1935                  "Tor 0.2.9.9 (git-56788a2489127072d513cf4baf35a8ff475f3c7b)",
   1936                  "Tor 0.2.9.9 (git-56788a2489127072)"));
   1937  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1938                                        "Tor 0.2.9.9 (git-0102)",
   1939                                        "Tor 0.2.9.9 (git-03)"));
   1940  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1941                                        "Tor 0.2.9.9 (git-0102)",
   1942                                        "Tor 0.2.9.9 (git-00)"));
   1943  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1944                                           "Tor 0.2.9.9 (git-01)",
   1945                                           "Tor 0.2.9.9 (git-00)"));
   1946  tt_int_op(0,OP_EQ, tor_version_as_new_as(
   1947                                           "Tor 0.2.9.9 (git-00)",
   1948                                           "Tor 0.2.9.9 (git-01)"));
   1949  /* In #21278, we compare without integer overflows.
   1950   * But since #21450 limits version components to [0, INT32_MAX], it is no
   1951   * longer possible to cause an integer overflow in tor_version_compare() */
   1952  tt_int_op(0,OP_EQ, tor_version_as_new_as(
   1953                                           "Tor 0.0.0.0",
   1954                                           "Tor 2147483647.0.0.0"));
   1955  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1956                                           "Tor 2147483647.0.0.0",
   1957                                           "Tor 0.0.0.0"));
   1958  /* These versions used to cause an overflow, now they don't parse
   1959   * (and authorities reject their descriptors), and log a BUG message */
   1960  setup_full_capture_of_logs(LOG_WARN);
   1961  tt_int_op(0,OP_EQ, tor_version_as_new_as(
   1962                                           "Tor 0.0.0.0",
   1963                                           "Tor 0.-2147483648.0.0"));
   1964  expect_single_log_msg_containing("unparseable");
   1965  mock_clean_saved_logs();
   1966  tt_int_op(0,OP_EQ, tor_version_as_new_as(
   1967                                           "Tor 0.2147483647.0.0",
   1968                                           "Tor 0.-1.0.0"));
   1969  expect_single_log_msg_containing("unparseable");
   1970  mock_clean_saved_logs();
   1971  tt_int_op(0,OP_EQ, tor_version_as_new_as(
   1972                                           "Tor 0.2147483647.0.0",
   1973                                           "Tor 0.-2147483648.0.0"));
   1974  expect_single_log_msg_containing("unparseable");
   1975  mock_clean_saved_logs();
   1976  tt_int_op(1,OP_EQ, tor_version_as_new_as(
   1977                                           "Tor 4294967295.0.0.0",
   1978                                           "Tor 0.0.0.0"));
   1979  expect_no_log_entry();
   1980  tt_int_op(0,OP_EQ, tor_version_as_new_as(
   1981                                           "Tor 0.4294967295.0.0",
   1982                                           "Tor 0.-4294967295.0.0"));
   1983  expect_single_log_msg_containing("unparseable");
   1984  mock_clean_saved_logs();
   1985  teardown_capture_of_logs();
   1986 
   1987  /* Now try git revisions */
   1988  tt_int_op(0,OP_EQ, tor_version_parse("0.5.6.7 (git-ff00ff)", &ver1));
   1989  tt_int_op(0,OP_EQ, ver1.major);
   1990  tt_int_op(5,OP_EQ, ver1.minor);
   1991  tt_int_op(6,OP_EQ, ver1.micro);
   1992  tt_int_op(7,OP_EQ, ver1.patchlevel);
   1993  tt_int_op(3,OP_EQ, ver1.git_tag_len);
   1994  tt_mem_op(ver1.git_tag,OP_EQ, "\xff\x00\xff", 3);
   1995  /* reject bad hex digits */
   1996  tt_int_op(-1,OP_EQ, tor_version_parse("0.5.6.7 (git-ff00xx)", &ver1));
   1997  /* reject odd hex digit count */
   1998  tt_int_op(-1,OP_EQ, tor_version_parse("0.5.6.7 (git-ff00fff)", &ver1));
   1999  /* ignore "git " */
   2000  tt_int_op(0,OP_EQ, tor_version_parse("0.5.6.7 (git ff00fff)", &ver1));
   2001  /* standard length is 16 hex digits */
   2002  tt_int_op(0,OP_EQ, tor_version_parse("0.5.6.7 (git-0010203040506070)",
   2003                                       &ver1));
   2004  /* length limit is 40 hex digits */
   2005  tt_int_op(0,OP_EQ, tor_version_parse(
   2006                     "0.5.6.7 (git-000102030405060708090a0b0c0d0e0f10111213)",
   2007                     &ver1));
   2008  tt_int_op(-1,OP_EQ, tor_version_parse(
   2009                    "0.5.6.7 (git-000102030405060708090a0b0c0d0e0f1011121314)",
   2010                    &ver1));
   2011 done:
   2012  teardown_capture_of_logs();
   2013 }
   2014 
   2015 /** Run unit tests for directory fp_pair functions. */
   2016 static void
   2017 test_dir_fp_pairs(void *arg)
   2018 {
   2019  smartlist_t *sl = smartlist_new();
   2020  fp_pair_t *pair;
   2021 
   2022  (void)arg;
   2023  dir_split_resource_into_fingerprint_pairs(
   2024       /* Two pairs, out of order, with one duplicate. */
   2025       "73656372657420646174612E0000000000FFFFFF-"
   2026       "557365204145532d32353620696e73746561642e+"
   2027       "73656372657420646174612E0000000000FFFFFF-"
   2028       "557365204145532d32353620696e73746561642e+"
   2029       "48657861646563696d616c2069736e277420736f-"
   2030       "676f6f6420666f7220686964696e6720796f7572.z", sl);
   2031 
   2032  tt_int_op(smartlist_len(sl),OP_EQ, 2);
   2033  pair = smartlist_get(sl, 0);
   2034  tt_mem_op(pair->first,OP_EQ,  "Hexadecimal isn't so", DIGEST_LEN);
   2035  tt_mem_op(pair->second,OP_EQ, "good for hiding your", DIGEST_LEN);
   2036  pair = smartlist_get(sl, 1);
   2037  tt_mem_op(pair->first,OP_EQ,  "secret data.\0\0\0\0\0\xff\xff\xff",
   2038            DIGEST_LEN);
   2039  tt_mem_op(pair->second,OP_EQ, "Use AES-256 instead.", DIGEST_LEN);
   2040 
   2041 done:
   2042  SMARTLIST_FOREACH(sl, fp_pair_t *, pair_to_free, tor_free(pair_to_free));
   2043  smartlist_free(sl);
   2044 }
   2045 
   2046 static void
   2047 test_dir_split_fps(void *testdata)
   2048 {
   2049  smartlist_t *sl = smartlist_new();
   2050  char *mem_op_hex_tmp = NULL;
   2051  (void)testdata;
   2052 
   2053  /* Some example hex fingerprints and their base64 equivalents */
   2054 #define HEX1 "Fe0daff89127389bc67558691231234551193EEE"
   2055 #define HEX2 "Deadbeef99999991111119999911111111f00ba4"
   2056 #define HEX3 "b33ff00db33ff00db33ff00db33ff00db33ff00d"
   2057 #define HEX256_1 \
   2058    "f3f3f3f3fbbbbf3f3f3f3fbbbf3f3f3f3fbbbbf3f3f3f3fbbbf3f3f3f3fbbbbf"
   2059 #define HEX256_2 \
   2060    "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccCCc"
   2061 #define HEX256_3 \
   2062    "0123456789ABCdef0123456789ABCdef0123456789ABCdef0123456789ABCdef"
   2063 #define B64_1 "/g2v+JEnOJvGdVhpEjEjRVEZPu4"
   2064 #define B64_2 "3q2+75mZmZERERmZmRERERHwC6Q"
   2065 #define B64_256_1 "8/Pz8/u7vz8/Pz+7vz8/Pz+7u/Pz8/P7u/Pz8/P7u78"
   2066 #define B64_256_2 "zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMw"
   2067 
   2068  /* no flags set */
   2069  dir_split_resource_into_fingerprints("A+C+B", sl, NULL, 0);
   2070  tt_int_op(smartlist_len(sl), OP_EQ, 3);
   2071  tt_str_op(smartlist_get(sl, 0), OP_EQ, "A");
   2072  tt_str_op(smartlist_get(sl, 1), OP_EQ, "C");
   2073  tt_str_op(smartlist_get(sl, 2), OP_EQ, "B");
   2074  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2075  smartlist_clear(sl);
   2076 
   2077  /* uniq strings. */
   2078  dir_split_resource_into_fingerprints("A+C+B+A+B+B", sl, NULL, DSR_SORT_UNIQ);
   2079  tt_int_op(smartlist_len(sl), OP_EQ, 3);
   2080  tt_str_op(smartlist_get(sl, 0), OP_EQ, "A");
   2081  tt_str_op(smartlist_get(sl, 1), OP_EQ, "B");
   2082  tt_str_op(smartlist_get(sl, 2), OP_EQ, "C");
   2083  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2084  smartlist_clear(sl);
   2085 
   2086  /* Decode hex. */
   2087  dir_split_resource_into_fingerprints(HEX1"+"HEX2, sl, NULL, DSR_HEX);
   2088  tt_int_op(smartlist_len(sl), OP_EQ, 2);
   2089  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX1);
   2090  test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
   2091  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2092  smartlist_clear(sl);
   2093 
   2094  /* decode hex and drop weirdness. */
   2095  dir_split_resource_into_fingerprints(HEX1"+bogus+"HEX2"+"HEX256_1,
   2096                                       sl, NULL, DSR_HEX);
   2097  tt_int_op(smartlist_len(sl), OP_EQ, 2);
   2098  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX1);
   2099  test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
   2100  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2101  smartlist_clear(sl);
   2102 
   2103  /* Decode long hex */
   2104  dir_split_resource_into_fingerprints(HEX256_1"+"HEX256_2"+"HEX2"+"HEX256_3,
   2105                                       sl, NULL, DSR_HEX|DSR_DIGEST256);
   2106  tt_int_op(smartlist_len(sl), OP_EQ, 3);
   2107  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_1);
   2108  test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX256_2);
   2109  test_mem_op_hex(smartlist_get(sl, 2), OP_EQ, HEX256_3);
   2110  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2111  smartlist_clear(sl);
   2112 
   2113  /* Decode hex and sort. */
   2114  dir_split_resource_into_fingerprints(HEX1"+"HEX2"+"HEX3"+"HEX2,
   2115                                       sl, NULL, DSR_HEX|DSR_SORT_UNIQ);
   2116  tt_int_op(smartlist_len(sl), OP_EQ, 3);
   2117  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX3);
   2118  test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
   2119  test_mem_op_hex(smartlist_get(sl, 2), OP_EQ, HEX1);
   2120  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2121  smartlist_clear(sl);
   2122 
   2123  /* Decode long hex and sort */
   2124  dir_split_resource_into_fingerprints(HEX256_1"+"HEX256_2"+"HEX256_3
   2125                                       "+"HEX256_1,
   2126                                       sl, NULL,
   2127                                       DSR_HEX|DSR_DIGEST256|DSR_SORT_UNIQ);
   2128  tt_int_op(smartlist_len(sl), OP_EQ, 3);
   2129  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_3);
   2130  test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX256_2);
   2131  test_mem_op_hex(smartlist_get(sl, 2), OP_EQ, HEX256_1);
   2132  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2133  smartlist_clear(sl);
   2134 
   2135  /* Decode base64 */
   2136  dir_split_resource_into_fingerprints(B64_1"-"B64_2, sl, NULL, DSR_BASE64);
   2137  tt_int_op(smartlist_len(sl), OP_EQ, 2);
   2138  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX1);
   2139  test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX2);
   2140  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2141  smartlist_clear(sl);
   2142 
   2143  /* Decode long base64 */
   2144  dir_split_resource_into_fingerprints(B64_256_1"-"B64_256_2,
   2145                                       sl, NULL, DSR_BASE64|DSR_DIGEST256);
   2146  tt_int_op(smartlist_len(sl), OP_EQ, 2);
   2147  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_1);
   2148  test_mem_op_hex(smartlist_get(sl, 1), OP_EQ, HEX256_2);
   2149  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2150  smartlist_clear(sl);
   2151 
   2152  dir_split_resource_into_fingerprints(B64_256_1,
   2153                                       sl, NULL, DSR_BASE64|DSR_DIGEST256);
   2154  tt_int_op(smartlist_len(sl), OP_EQ, 1);
   2155  test_mem_op_hex(smartlist_get(sl, 0), OP_EQ, HEX256_1);
   2156  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2157  smartlist_clear(sl);
   2158 
   2159 done:
   2160  SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
   2161  smartlist_free(sl);
   2162  tor_free(mem_op_hex_tmp);
   2163 }
   2164 
   2165 static void
   2166 test_dir_measured_bw_kb(void *arg)
   2167 {
   2168  measured_bw_line_t mbwl;
   2169  int i;
   2170  const char *lines_pass[] = {
   2171    "node_id=$557365204145532d32353620696e73746561642e bw=1024\n",
   2172    /* check whether node_id does not need the dollar sign at the start */
   2173    "node_id=557365204145532d32353620696e73746561642e bw=1024\n",
   2174    "node_id=$557365204145532d32353620696e73746561642e\t  bw=1024 \n",
   2175    " node_id=$557365204145532d32353620696e73746561642e  bw=1024\n",
   2176    "\tnoise\tnode_id=$557365204145532d32353620696e73746561642e  "
   2177                "bw=1024 junk=007\n",
   2178    "misc=junk node_id=$557365204145532d32353620696e73746561642e  "
   2179                "bw=1024 junk=007\n",
   2180    /* check whether node_id can be at the end */
   2181    "bw=1024 node_id=$557365204145532d32353620696e73746561642e\n",
   2182    /* check whether node_id can be at the end and bw has something in front*/
   2183    "foo=bar bw=1024 node_id=$557365204145532d32353620696e73746561642e\n",
   2184    /* check whether node_id can be at the end and something in the
   2185     * in the middle of bw and node_id */
   2186    "bw=1024 foo=bar node_id=$557365204145532d32353620696e73746561642e\n",
   2187 
   2188    /* Test that a line with vote=1 will pass. */
   2189    "node_id=$557365204145532d32353620696e73746561642e bw=1024 vote=1\n",
   2190    /* Test that a line with unmeasured=1 will pass. */
   2191    "node_id=$557365204145532d32353620696e73746561642e bw=1024 unmeasured=1\n",
   2192    /* Test that a line with vote=1 and unmeasured=1 will pass. */
   2193    "node_id=$557365204145532d32353620696e73746561642e bw=1024 vote=1"
   2194    "unmeasured=1\n",
   2195    /* Test that a line with unmeasured=0 will pass. */
   2196    "node_id=$557365204145532d32353620696e73746561642e bw=1024 unmeasured=0\n",
   2197    /* Test that a line with vote=1 and unmeasured=0 will pass. */
   2198    "node_id=$557365204145532d32353620696e73746561642e bw=1024 vote=1"
   2199    "unmeasured=0\n",
   2200    "end"
   2201  };
   2202  const char *lines_fail[] = {
   2203    /* Test possible python stupidity on input */
   2204    "node_id=None bw=1024\n",
   2205    "node_id=$None bw=1024\n",
   2206    "node_id=$557365204145532d32353620696e73746561642e bw=None\n",
   2207    "node_id=$557365204145532d32353620696e73746561642e bw=1024.0\n",
   2208    "node_id=$557365204145532d32353620696e73746561642e bw=.1024\n",
   2209    "node_id=$557365204145532d32353620696e73746561642e bw=1.024\n",
   2210    "node_id=$557365204145532d32353620696e73746561642e bw=1024 bw=0\n",
   2211    "node_id=$557365204145532d32353620696e73746561642e bw=1024 bw=None\n",
   2212    "node_id=$557365204145532d32353620696e73746561642e bw=-1024\n",
   2213    /* Test incomplete writes due to race conditions, partial copies, etc */
   2214    "node_i",
   2215    "node_i\n",
   2216    "node_id=",
   2217    "node_id=\n",
   2218    "node_id=$557365204145532d32353620696e73746561642e bw=",
   2219    "node_id=$557365204145532d32353620696e73746561642e bw=1024",
   2220    "node_id=$557365204145532d32353620696e73746561642e bw=\n",
   2221    "node_id=$557365204145532d32353620696e7374",
   2222    "node_id=$557365204145532d32353620696e7374\n",
   2223    "",
   2224    "\n",
   2225    " \n ",
   2226    " \n\n",
   2227    /* Test assorted noise */
   2228    " node_id= ",
   2229    "node_id==$557365204145532d32353620696e73746561642e bw==1024\n",
   2230    "node_id=$55736520414552d32353620696e73746561642e bw=1024\n",
   2231    "node_id= $557365204145532d32353620696e73746561642e bw=0.23\n",
   2232 
   2233    /* Test that a line with vote=0 will fail too, so that it is ignored. */
   2234    "node_id=$557365204145532d32353620696e73746561642e bw=1024 vote=0\n",
   2235    /* Test that a line with vote=0 will fail even if unmeasured=0. */
   2236    ("node_id=$557365204145532d32353620696e73746561642e bw=1024 vote=0 "
   2237     "unmeasured=0\n"),
   2238    "end"
   2239  };
   2240 
   2241  (void)arg;
   2242  for (i = 0; strcmp(lines_fail[i], "end"); i++) {
   2243    //fprintf(stderr, "Testing: %s\n", lines_fail[i]);
   2244    /* Testing only with line_is_after_headers = 1. Tests with
   2245     * line_is_after_headers = 0 in
   2246     * test_dir_measured_bw_kb_line_is_after_headers */
   2247    tt_assert(measured_bw_line_parse(&mbwl, lines_fail[i], 1) == -1);
   2248  }
   2249 
   2250  for (i = 0; strcmp(lines_pass[i], "end"); i++) {
   2251    //fprintf(stderr, "Testing: %s %d\n", lines_pass[i], TOR_ISSPACE('\n'));
   2252    /* Testing only with line_is_after_headers = 1. Tests with
   2253     * line_is_after_headers = 0 in
   2254     * test_dir_measured_bw_kb_line_is_after_headers */
   2255    tt_assert(measured_bw_line_parse(&mbwl, lines_pass[i], 1) == 0);
   2256    tt_assert(mbwl.bw_kb == 1024);
   2257    tt_assert(strcmp(mbwl.node_hex,
   2258                "557365204145532d32353620696e73746561642e") == 0);
   2259  }
   2260 
   2261 done:
   2262  return;
   2263 }
   2264 
   2265 /* Unit tests for measured_bw_line_parse using line_is_after_headers flag.
   2266 * When the end of the header is detected (a first complete bw line is parsed),
   2267 * incomplete lines fail and give warnings, but do not give warnings if
   2268 * the header is not ended, allowing to ignore additional header lines. */
   2269 static void
   2270 test_dir_measured_bw_kb_line_is_after_headers(void *arg)
   2271 {
   2272  (void)arg;
   2273  measured_bw_line_t mbwl;
   2274  const char *line_pass = \
   2275    "node_id=$557365204145532d32353620696e73746561642e bw=1024\n";
   2276  int i;
   2277  const char *lines_fail[] = {
   2278    "node_id=$557365204145532d32353620696e73746561642e \n",
   2279    "bw=1024\n",
   2280    "rtt=300\n",
   2281    "end"
   2282  };
   2283 
   2284  setup_capture_of_logs(LOG_DEBUG);
   2285 
   2286  /* Test bw lines when header has ended */
   2287  for (i = 0; strcmp(lines_fail[i], "end"); i++) {
   2288    tt_assert(measured_bw_line_parse(&mbwl, lines_fail[i], 1) == -1);
   2289    expect_log_msg_containing("Incomplete line in bandwidth file:");
   2290    mock_clean_saved_logs();
   2291  }
   2292 
   2293  tt_assert(measured_bw_line_parse(&mbwl, line_pass, 1) == 0);
   2294 
   2295  /* Test bw lines when header has not ended */
   2296  for (i = 0; strcmp(lines_fail[i], "end"); i++) {
   2297    tt_assert(measured_bw_line_parse(&mbwl, lines_fail[i], 0) == -1);
   2298    expect_log_msg_containing("Missing bw or node_id in bandwidth file line:");
   2299    mock_clean_saved_logs();
   2300  }
   2301 
   2302  tt_assert(measured_bw_line_parse(&mbwl, line_pass, 0) == 0);
   2303 
   2304 done:
   2305  teardown_capture_of_logs();
   2306 }
   2307 
   2308 /* Test dirserv_read_measured_bandwidths with headers and complete files. */
   2309 static void
   2310 test_dir_dirserv_read_measured_bandwidths(void *arg)
   2311 {
   2312  (void)arg;
   2313  char *content = NULL;
   2314  time_t timestamp = time(NULL);
   2315  char *fname = tor_strdup(get_fname("V3BandwidthsFile"));
   2316  smartlist_t *bw_file_headers = smartlist_new();
   2317  /* bw file strings in vote */
   2318  char *bw_file_headers_str = NULL;
   2319  char *bw_file_headers_str_v100 = NULL;
   2320  char *bw_file_headers_str_v110 = NULL;
   2321  char *bw_file_headers_str_bad = NULL;
   2322  char *bw_file_headers_str_extra = NULL;
   2323  char bw_file_headers_str_long[MAX_BW_FILE_HEADER_COUNT_IN_VOTE * 8 + 1] = "";
   2324  /* string header lines in bw file */
   2325  char *header_lines_v100 = NULL;
   2326  char *header_lines_v110_no_terminator = NULL;
   2327  char *header_lines_v110 = NULL;
   2328  char header_lines_long[MAX_BW_FILE_HEADER_COUNT_IN_VOTE * 8 + 1] = "";
   2329  int i;
   2330  const char *header_lines_v110_no_terminator_no_timestamp =
   2331    "version=1.1.0\n"
   2332    "software=sbws\n"
   2333    "software_version=0.1.0\n"
   2334    "earliest_bandwidth=2018-05-08T16:13:26\n"
   2335    "file_created=2018-04-16T21:49:18\n"
   2336    "generator_started=2018-05-08T16:13:25\n"
   2337    "latest_bandwidth=2018-04-16T20:49:18\n";
   2338  const char *bw_file_headers_str_v110_no_timestamp =
   2339    "version=1.1.0 software=sbws "
   2340    "software_version=0.1.0 "
   2341    "earliest_bandwidth=2018-05-08T16:13:26 "
   2342    "file_created=2018-04-16T21:49:18 "
   2343    "generator_started=2018-05-08T16:13:25 "
   2344    "latest_bandwidth=2018-04-16T20:49:18";
   2345  const char *relay_lines_v100 =
   2346    "node_id=$557365204145532d32353620696e73746561642e bw=1024 "
   2347    "nick=Test measured_at=1523911725 updated_at=1523911725 "
   2348    "pid_error=4.11374090719 pid_error_sum=4.11374090719 "
   2349    "pid_bw=57136645 pid_delta=2.12168374577 circ_fail=0.2 "
   2350    "scanner=/filepath\n";
   2351  const char *relay_lines_v110 =
   2352    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 "
   2353    "master_key_ed25519=YaqV4vbvPYKucElk297eVdNArDz9HtIwUoIeo0+cVIpQ "
   2354    "bw=760 nick=Test rtt=380 time=2018-05-08T16:13:26\n";
   2355  const char *relay_lines_bad =
   2356    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A\n";
   2357 
   2358  tor_asprintf(&header_lines_v100, "%ld\n", (long)timestamp);
   2359  tor_asprintf(&header_lines_v110_no_terminator, "%ld\n%s", (long)timestamp,
   2360               header_lines_v110_no_terminator_no_timestamp);
   2361  tor_asprintf(&header_lines_v110, "%s%s",
   2362               header_lines_v110_no_terminator, BW_FILE_HEADERS_TERMINATOR);
   2363 
   2364  tor_asprintf(&bw_file_headers_str_v100, "timestamp=%ld",(long)timestamp);
   2365  tor_asprintf(&bw_file_headers_str_v110, "timestamp=%ld %s",
   2366               (long)timestamp, bw_file_headers_str_v110_no_timestamp);
   2367  tor_asprintf(&bw_file_headers_str_bad, "%s "
   2368               "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A",
   2369               bw_file_headers_str_v110);
   2370 
   2371  for (i=0; i<MAX_BW_FILE_HEADER_COUNT_IN_VOTE; i++) {
   2372    strlcat(header_lines_long, "foo=bar\n",
   2373            sizeof(header_lines_long));
   2374  }
   2375  /* 8 is the number of v110 lines in header_lines_v110 */
   2376  for (i=0; i<MAX_BW_FILE_HEADER_COUNT_IN_VOTE - 8 - 1; i++) {
   2377    strlcat(bw_file_headers_str_long, "foo=bar ",
   2378            sizeof(bw_file_headers_str_long));
   2379  }
   2380  strlcat(bw_file_headers_str_long, "foo=bar",
   2381          sizeof(bw_file_headers_str_long));
   2382  tor_asprintf(&bw_file_headers_str_extra,
   2383               "%s %s",
   2384               bw_file_headers_str_v110,
   2385               bw_file_headers_str_long);
   2386 
   2387  /* Test an empty bandwidth file. bw_file_headers will be empty string */
   2388  write_str_to_file(fname, "", 0);
   2389  setup_capture_of_logs(LOG_WARN);
   2390  tt_int_op(-1, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2391                                                        bw_file_headers,
   2392                                                        NULL));
   2393  expect_log_msg("Empty bandwidth file\n");
   2394  teardown_capture_of_logs();
   2395  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2396  tt_str_op("", OP_EQ, bw_file_headers_str);
   2397  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2398  smartlist_free(bw_file_headers);
   2399  tor_free(bw_file_headers_str);
   2400 
   2401  /* Test bandwidth file with only timestamp.
   2402   * bw_file_headers will be empty string */
   2403  bw_file_headers = smartlist_new();
   2404  tor_asprintf(&content, "%ld", (long)timestamp);
   2405  write_str_to_file(fname, content, 0);
   2406  tor_free(content);
   2407  tt_int_op(-1, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2408                                                        bw_file_headers,
   2409                                                        NULL));
   2410 
   2411  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2412  tt_str_op("", OP_EQ, bw_file_headers_str);
   2413  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2414  smartlist_free(bw_file_headers);
   2415  tor_free(bw_file_headers_str);
   2416 
   2417  /* Test v1.0.0 bandwidth file headers */
   2418  write_str_to_file(fname, header_lines_v100, 0);
   2419  bw_file_headers = smartlist_new();
   2420  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2421                                                       bw_file_headers,
   2422                                                       NULL));
   2423 
   2424  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2425  tt_str_op(bw_file_headers_str_v100, OP_EQ, bw_file_headers_str);
   2426  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2427  smartlist_free(bw_file_headers);
   2428  tor_free(bw_file_headers_str);
   2429 
   2430  /* Test v1.0.0 complete bandwidth file */
   2431  bw_file_headers = smartlist_new();
   2432  tor_asprintf(&content, "%s%s", header_lines_v100, relay_lines_v100);
   2433  write_str_to_file(fname, content, 0);
   2434  tor_free(content);
   2435  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2436                                                       bw_file_headers,
   2437                                                       NULL));
   2438 
   2439  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2440  tt_str_op(bw_file_headers_str_v100, OP_EQ, bw_file_headers_str);
   2441  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2442  smartlist_free(bw_file_headers);
   2443  tor_free(bw_file_headers_str);
   2444 
   2445  /* Test v1.0.0 complete bandwidth file with NULL bw_file_headers. */
   2446  tor_asprintf(&content, "%s%s", header_lines_v100, relay_lines_v100);
   2447  write_str_to_file(fname, content, 0);
   2448  tor_free(content);
   2449  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL, NULL,
   2450                                                       NULL));
   2451 
   2452  /* Test bandwidth file including v1.1.0 bandwidth headers and
   2453   * v1.0.0 relay lines. bw_file_headers will contain the v1.1.0 headers. */
   2454  bw_file_headers = smartlist_new();
   2455  tor_asprintf(&content, "%s%s%s", header_lines_v100, header_lines_v110,
   2456               relay_lines_v100);
   2457  write_str_to_file(fname, content, 0);
   2458  tor_free(content);
   2459  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2460                                                       bw_file_headers,
   2461                                                       NULL));
   2462 
   2463  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2464  tt_str_op(bw_file_headers_str_v110, OP_EQ, bw_file_headers_str);
   2465  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2466  smartlist_free(bw_file_headers);
   2467  tor_free(bw_file_headers_str);
   2468 
   2469  /* Test v1.0.0 complete bandwidth file with v1.1.0 headers at the end.
   2470   * bw_file_headers will contain only v1.0.0 headers and the additional
   2471   * headers will be interpreted as malformed relay lines. */
   2472  bw_file_headers = smartlist_new();
   2473  tor_asprintf(&content, "%s%s%s", header_lines_v100, relay_lines_v100,
   2474               header_lines_v110);
   2475  write_str_to_file(fname, content, 0);
   2476  tor_free(content);
   2477  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2478                                                       bw_file_headers,
   2479                                                       NULL));
   2480 
   2481  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2482  tt_str_op(bw_file_headers_str_v100, OP_EQ, bw_file_headers_str);
   2483  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2484  smartlist_free(bw_file_headers);
   2485  tor_free(bw_file_headers_str);
   2486 
   2487  /* Test v1.0.0 complete bandwidth file, the v1.1.0 headers and more relay
   2488   * lines. bw_file_headers will contain only v1.0.0 headers, the additional
   2489   * headers will be interpreted as malformed relay lines and the last relay
   2490   * lines will be correctly interpreted as relay lines. */
   2491  bw_file_headers = smartlist_new();
   2492  tor_asprintf(&content, "%s%s%s%s", header_lines_v100, relay_lines_v100,
   2493               header_lines_v110, relay_lines_v100);
   2494  write_str_to_file(fname, content, 0);
   2495  tor_free(content);
   2496  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2497                                                       bw_file_headers,
   2498                                                       NULL));
   2499 
   2500  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2501  tt_str_op(bw_file_headers_str_v100, OP_EQ, bw_file_headers_str);
   2502  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2503  smartlist_free(bw_file_headers);
   2504  tor_free(bw_file_headers_str);
   2505 
   2506  /* Test v1.1.0 bandwidth headers without terminator */
   2507  bw_file_headers = smartlist_new();
   2508  write_str_to_file(fname, header_lines_v110_no_terminator, 0);
   2509  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2510                                                       bw_file_headers,
   2511                                                       NULL));
   2512 
   2513  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2514  tt_str_op(bw_file_headers_str_v110, OP_EQ, bw_file_headers_str);
   2515  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2516  smartlist_free(bw_file_headers);
   2517  tor_free(bw_file_headers_str);
   2518 
   2519  /* Test v1.1.0 bandwidth headers with terminator */
   2520  bw_file_headers = smartlist_new();
   2521  write_str_to_file(fname, header_lines_v110, 0);
   2522  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2523                                                       bw_file_headers,
   2524                                                       NULL));
   2525 
   2526  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2527  tt_str_op(bw_file_headers_str_v110, OP_EQ, bw_file_headers_str);
   2528  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2529  smartlist_free(bw_file_headers);
   2530  tor_free(bw_file_headers_str);
   2531 
   2532  /* Test v1.1.0 bandwidth file without terminator, then relay lines.
   2533   * bw_file_headers will contain the v1.1.0 headers. */
   2534  bw_file_headers = smartlist_new();
   2535  tor_asprintf(&content, "%s%s",
   2536               header_lines_v110_no_terminator, relay_lines_v110);
   2537  write_str_to_file(fname, content, 0);
   2538  tor_free(content);
   2539  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2540                                                       bw_file_headers,
   2541                                                       NULL));
   2542 
   2543  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2544  tt_str_op(bw_file_headers_str_v110, OP_EQ, bw_file_headers_str);
   2545  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2546  smartlist_free(bw_file_headers);
   2547  tor_free(bw_file_headers_str);
   2548 
   2549  /* Test v1.1.0 bandwidth headers with terminator, then relay lines
   2550   * bw_file_headers will contain the v1.1.0 headers. */
   2551  bw_file_headers = smartlist_new();
   2552  tor_asprintf(&content, "%s%s",
   2553               header_lines_v110, relay_lines_v110);
   2554  write_str_to_file(fname, content, 0);
   2555  tor_free(content);
   2556  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2557                                                       bw_file_headers,
   2558                                                       NULL));
   2559 
   2560  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2561  tt_str_op(bw_file_headers_str_v110, OP_EQ, bw_file_headers_str);
   2562  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2563  smartlist_free(bw_file_headers);
   2564  tor_free(bw_file_headers_str);
   2565 
   2566  /* Test v1.1.0 bandwidth headers with terminator, then bad relay lines,
   2567   * then terminator, then relay_lines_bad.
   2568   * bw_file_headers will contain the v1.1.0 headers. */
   2569  bw_file_headers = smartlist_new();
   2570  tor_asprintf(&content, "%s%s%s%s", header_lines_v110, relay_lines_bad,
   2571               BW_FILE_HEADERS_TERMINATOR, relay_lines_bad);
   2572  write_str_to_file(fname, content, 0);
   2573  tor_free(content);
   2574  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2575                                                       bw_file_headers,
   2576                                                       NULL));
   2577 
   2578  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2579  tt_str_op(bw_file_headers_str_v110, OP_EQ, bw_file_headers_str);
   2580  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2581  smartlist_free(bw_file_headers);
   2582  tor_free(bw_file_headers_str);
   2583 
   2584  /* Test v1.1.0 bandwidth headers without terminator, then bad relay lines,
   2585   * then relay lines. bw_file_headers will contain the v1.1.0 headers and
   2586   * the bad relay lines. */
   2587  bw_file_headers = smartlist_new();
   2588  tor_asprintf(&content, "%s%s%s",
   2589               header_lines_v110_no_terminator, relay_lines_bad,
   2590               relay_lines_v110);
   2591  write_str_to_file(fname, content, 0);
   2592  tor_free(content);
   2593  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2594                                                       bw_file_headers,
   2595                                                       NULL));
   2596 
   2597  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2598  tt_str_op(bw_file_headers_str_bad, OP_EQ, bw_file_headers_str);
   2599  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2600  smartlist_free(bw_file_headers);
   2601  tor_free(bw_file_headers_str);
   2602 
   2603  /* Test v1.1.0 bandwidth headers without terminator,
   2604   * then many bad relay lines, then relay lines.
   2605   * bw_file_headers will contain the v1.1.0 headers and the bad relay lines
   2606   * to a maximum of MAX_BW_FILE_HEADER_COUNT_IN_VOTE header lines. */
   2607  bw_file_headers = smartlist_new();
   2608  tor_asprintf(&content, "%s%s%s",
   2609               header_lines_v110_no_terminator, header_lines_long,
   2610               relay_lines_v110);
   2611  write_str_to_file(fname, content, 0);
   2612  tor_free(content);
   2613  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2614                                                       bw_file_headers,
   2615                                                       NULL));
   2616 
   2617  tt_int_op(MAX_BW_FILE_HEADER_COUNT_IN_VOTE, OP_EQ,
   2618            smartlist_len(bw_file_headers));
   2619  bw_file_headers_str = smartlist_join_strings(bw_file_headers, " ", 0, NULL);
   2620  tt_str_op(bw_file_headers_str_extra, OP_EQ, bw_file_headers_str);
   2621  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2622  smartlist_free(bw_file_headers);
   2623  tor_free(bw_file_headers_str);
   2624 
   2625  /* Test v1.1.0 bandwidth headers without terminator,
   2626   * then many bad relay lines, then relay lines.
   2627   * bw_file_headers will contain the v1.1.0 headers and the bad relay lines.
   2628   * Force bw_file_headers to have more than MAX_BW_FILE_HEADER_COUNT_IN_VOTE
   2629   * This test is needed while there is not dirvote test. */
   2630  bw_file_headers = smartlist_new();
   2631  tor_asprintf(&content, "%s%s%s",
   2632               header_lines_v110_no_terminator, header_lines_long,
   2633               relay_lines_v110);
   2634  write_str_to_file(fname, content, 0);
   2635  tor_free(content);
   2636  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL,
   2637                                                       bw_file_headers,
   2638                                                       NULL));
   2639 
   2640  tt_int_op(MAX_BW_FILE_HEADER_COUNT_IN_VOTE, OP_EQ,
   2641            smartlist_len(bw_file_headers));
   2642  /* force bw_file_headers to be bigger than
   2643   * MAX_BW_FILE_HEADER_COUNT_IN_VOTE */
   2644  NONSTRING char line[8] = "foo=bar\0";
   2645  smartlist_add_strdup(bw_file_headers, line);
   2646  tt_int_op(MAX_BW_FILE_HEADER_COUNT_IN_VOTE, OP_LT,
   2647            smartlist_len(bw_file_headers));
   2648  SMARTLIST_FOREACH(bw_file_headers, char *, c, tor_free(c));
   2649  smartlist_free(bw_file_headers);
   2650  tor_free(bw_file_headers_str);
   2651 
   2652  /* Test v1.x.x bandwidth line with vote=0.
   2653   * It will be ignored it and logged it at debug level. */
   2654  const char *relay_lines_ignore =
   2655    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 bw=1024 vote=0\n"
   2656    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 bw=1024 vote=0"
   2657    "unmeasured=1\n"
   2658    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 bw=1024 vote=0"
   2659    "unmeasured=0\n";
   2660 
   2661  /* Create the bandwidth file */
   2662  tor_asprintf(&content, "%ld\n%s", (long)timestamp, relay_lines_ignore);
   2663  write_str_to_file(fname, content, 0);
   2664  tor_free(content);
   2665 
   2666  /* Read the bandwidth file */
   2667  setup_full_capture_of_logs(LOG_DEBUG);
   2668  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL, NULL,
   2669                                                       NULL));
   2670  expect_log_msg_containing("Ignoring bandwidth file line");
   2671  teardown_capture_of_logs();
   2672 
   2673  /* Test v1.x.x bandwidth line with "vote=1" or "unmeasured=1" or
   2674   * "unmeasured=0".
   2675   * They will not be ignored. */
   2676  /* Create the bandwidth file */
   2677  const char *relay_lines_vote =
   2678    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 bw=1024 vote=1\n"
   2679    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 bw=1024 unmeasured=0\n"
   2680    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 bw=1024 unmeasured=1\n";
   2681  tor_asprintf(&content, "%ld\n%s", (long)timestamp, relay_lines_vote);
   2682  write_str_to_file(fname, content, 0);
   2683  tor_free(content);
   2684 
   2685  /* Read the bandwidth file */
   2686  setup_full_capture_of_logs(LOG_DEBUG);
   2687  tt_int_op(0, OP_EQ, dirserv_read_measured_bandwidths(fname, NULL, NULL,
   2688                                                       NULL));
   2689  expect_log_msg_not_containing("Ignoring bandwidth file line");
   2690  teardown_capture_of_logs();
   2691 
   2692 done:
   2693  unlink(fname);
   2694  tor_free(fname);
   2695  tor_free(header_lines_v100);
   2696  tor_free(header_lines_v110_no_terminator);
   2697  tor_free(header_lines_v110);
   2698  tor_free(bw_file_headers_str_v100);
   2699  tor_free(bw_file_headers_str_v110);
   2700  tor_free(bw_file_headers_str_bad);
   2701  tor_free(bw_file_headers_str_extra);
   2702 }
   2703 
   2704 #define MBWC_INIT_TIME 1000
   2705 
   2706 /** Do the measured bandwidth cache unit test */
   2707 static void
   2708 test_dir_measured_bw_kb_cache(void *arg)
   2709 {
   2710  /* Initial fake time_t for testing */
   2711  time_t curr = MBWC_INIT_TIME;
   2712  /* Some measured_bw_line_ts */
   2713  measured_bw_line_t mbwl[3];
   2714  /* For receiving output on cache queries */
   2715  long bw;
   2716  time_t as_of;
   2717 
   2718  /* First, clear the cache and assert that it's empty */
   2719  (void)arg;
   2720  dirserv_clear_measured_bw_cache();
   2721  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 0);
   2722  /*
   2723   * Set up test mbwls; none of the dirserv_cache_*() functions care about
   2724   * the node_hex field.
   2725   */
   2726  memset(mbwl[0].node_id, 0x01, DIGEST_LEN);
   2727  mbwl[0].bw_kb = 20;
   2728  memset(mbwl[1].node_id, 0x02, DIGEST_LEN);
   2729  mbwl[1].bw_kb = 40;
   2730  memset(mbwl[2].node_id, 0x03, DIGEST_LEN);
   2731  mbwl[2].bw_kb = 80;
   2732  /* Try caching something */
   2733  dirserv_cache_measured_bw(&(mbwl[0]), curr);
   2734  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 1);
   2735  /* Okay, let's see if we can retrieve it */
   2736  tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,&bw, &as_of));
   2737  tt_int_op(bw,OP_EQ, 20);
   2738  tt_int_op(as_of,OP_EQ, MBWC_INIT_TIME);
   2739  /* Try retrieving it without some outputs */
   2740  tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,NULL, NULL));
   2741  tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,&bw, NULL));
   2742  tt_int_op(bw,OP_EQ, 20);
   2743  tt_assert(dirserv_query_measured_bw_cache_kb(mbwl[0].node_id,NULL,&as_of));
   2744  tt_int_op(as_of,OP_EQ, MBWC_INIT_TIME);
   2745  /* Now expire it */
   2746  curr += MAX_MEASUREMENT_AGE + 1;
   2747  dirserv_expire_measured_bw_cache(curr);
   2748  /* Check that the cache is empty */
   2749  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 0);
   2750  /* Check that we can't retrieve it */
   2751  tt_assert(!dirserv_query_measured_bw_cache_kb(mbwl[0].node_id, NULL,NULL));
   2752  /* Try caching a few things now */
   2753  dirserv_cache_measured_bw(&(mbwl[0]), curr);
   2754  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 1);
   2755  curr += MAX_MEASUREMENT_AGE / 4;
   2756  dirserv_cache_measured_bw(&(mbwl[1]), curr);
   2757  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 2);
   2758  curr += MAX_MEASUREMENT_AGE / 4;
   2759  dirserv_cache_measured_bw(&(mbwl[2]), curr);
   2760  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 3);
   2761  curr += MAX_MEASUREMENT_AGE / 4 + 1;
   2762  /* Do an expire that's too soon to get any of them */
   2763  dirserv_expire_measured_bw_cache(curr);
   2764  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 3);
   2765  /* Push the oldest one off the cliff */
   2766  curr += MAX_MEASUREMENT_AGE / 4;
   2767  dirserv_expire_measured_bw_cache(curr);
   2768  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 2);
   2769  /* And another... */
   2770  curr += MAX_MEASUREMENT_AGE / 4;
   2771  dirserv_expire_measured_bw_cache(curr);
   2772  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 1);
   2773  /* This should empty it out again */
   2774  curr += MAX_MEASUREMENT_AGE / 4;
   2775  dirserv_expire_measured_bw_cache(curr);
   2776  tt_int_op(dirserv_get_measured_bw_cache_size(),OP_EQ, 0);
   2777 
   2778 done:
   2779  return;
   2780 }
   2781 
   2782 static char *
   2783 my_dirvote_compute_params(smartlist_t *votes, int method,
   2784                          int total_authorities)
   2785 {
   2786  smartlist_t *s = dirvote_compute_params(votes, method, total_authorities);
   2787  tor_assert(s);
   2788  char *res = smartlist_join_strings(s, " ", 0, NULL);
   2789  SMARTLIST_FOREACH(s, char *, cp, tor_free(cp));
   2790  smartlist_free(s);
   2791  return res;
   2792 }
   2793 
   2794 #define dirvote_compute_params my_dirvote_compute_params
   2795 
   2796 static void
   2797 test_dir_param_voting(void *arg)
   2798 {
   2799  networkstatus_t vote1, vote2, vote3, vote4;
   2800  smartlist_t *votes = smartlist_new();
   2801  char *res = NULL;
   2802 
   2803  /* dirvote_compute_params only looks at the net_params field of the votes,
   2804     so that's all we need to set.
   2805   */
   2806  (void)arg;
   2807  memset(&vote1, 0, sizeof(vote1));
   2808  memset(&vote2, 0, sizeof(vote2));
   2809  memset(&vote3, 0, sizeof(vote3));
   2810  memset(&vote4, 0, sizeof(vote4));
   2811  vote1.net_params = smartlist_new();
   2812  vote2.net_params = smartlist_new();
   2813  vote3.net_params = smartlist_new();
   2814  vote4.net_params = smartlist_new();
   2815  smartlist_split_string(vote1.net_params,
   2816                         "ab=90 abcd=20 cw=50 x-yz=-99", NULL, 0, 0);
   2817  smartlist_split_string(vote2.net_params,
   2818                         "ab=27 cw=5 x-yz=88", NULL, 0, 0);
   2819  smartlist_split_string(vote3.net_params,
   2820                         "abcd=20 c=60 cw=500 x-yz=-9 zzzzz=101", NULL, 0, 0);
   2821  smartlist_split_string(vote4.net_params,
   2822                         "ab=900 abcd=200 c=1 cw=51 x-yz=100", NULL, 0, 0);
   2823  tt_int_op(100,OP_EQ, networkstatus_get_param(&vote4, "x-yz", 50, 0, 300));
   2824  tt_int_op(222,OP_EQ, networkstatus_get_param(&vote4, "foobar", 222, 0, 300));
   2825  tt_int_op(80,OP_EQ, networkstatus_get_param(&vote4, "ab", 12, 0, 80));
   2826  tt_int_op(-8,OP_EQ, networkstatus_get_param(&vote4, "ab", -12, -100, -8));
   2827  tt_int_op(0,OP_EQ, networkstatus_get_param(&vote4, "foobar", 0, -100, 8));
   2828 
   2829  tt_int_op(100,OP_EQ, networkstatus_get_overridable_param(
   2830                                        &vote4, -1, "x-yz", 50, 0, 300));
   2831  tt_int_op(30,OP_EQ, networkstatus_get_overridable_param(
   2832                                        &vote4, 30, "x-yz", 50, 0, 300));
   2833  tt_int_op(0,OP_EQ, networkstatus_get_overridable_param(
   2834                                        &vote4, -101, "foobar", 0, -100, 8));
   2835  tt_int_op(-99,OP_EQ, networkstatus_get_overridable_param(
   2836                                        &vote4, -99, "foobar", 0, -100, 8));
   2837 
   2838  smartlist_add(votes, &vote1);
   2839 
   2840  /* Do the first tests without adding all the other votes, for
   2841   * networks without many dirauths. */
   2842 
   2843  res = dirvote_compute_params(votes, 12, 2);
   2844  tt_str_op(res,OP_EQ, "");
   2845  tor_free(res);
   2846 
   2847  res = dirvote_compute_params(votes, 12, 1);
   2848  tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-99");
   2849  tor_free(res);
   2850 
   2851  smartlist_add(votes, &vote2);
   2852 
   2853  res = dirvote_compute_params(votes, 12, 2);
   2854  tt_str_op(res,OP_EQ, "ab=27 cw=5 x-yz=-99");
   2855  tor_free(res);
   2856 
   2857  res = dirvote_compute_params(votes, 12, 3);
   2858  tt_str_op(res,OP_EQ, "ab=27 cw=5 x-yz=-99");
   2859  tor_free(res);
   2860 
   2861  res = dirvote_compute_params(votes, 12, 6);
   2862  tt_str_op(res,OP_EQ, "");
   2863  tor_free(res);
   2864 
   2865  smartlist_add(votes, &vote3);
   2866 
   2867  res = dirvote_compute_params(votes, 12, 3);
   2868  tt_str_op(res,OP_EQ, "ab=27 abcd=20 cw=50 x-yz=-9");
   2869  tor_free(res);
   2870 
   2871  res = dirvote_compute_params(votes, 12, 5);
   2872  tt_str_op(res,OP_EQ, "cw=50 x-yz=-9");
   2873  tor_free(res);
   2874 
   2875  res = dirvote_compute_params(votes, 12, 9);
   2876  tt_str_op(res,OP_EQ, "cw=50 x-yz=-9");
   2877  tor_free(res);
   2878 
   2879  smartlist_add(votes, &vote4);
   2880 
   2881  res = dirvote_compute_params(votes, 12, 4);
   2882  tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
   2883  tor_free(res);
   2884 
   2885  res = dirvote_compute_params(votes, 12, 5);
   2886  tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
   2887  tor_free(res);
   2888 
   2889  /* Test that the special-cased "at least three dirauths voted for
   2890   * this param" logic works as expected. */
   2891  res = dirvote_compute_params(votes, 12, 6);
   2892  tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
   2893  tor_free(res);
   2894 
   2895  res = dirvote_compute_params(votes, 12, 10);
   2896  tt_str_op(res,OP_EQ, "ab=90 abcd=20 cw=50 x-yz=-9");
   2897  tor_free(res);
   2898 
   2899 done:
   2900  tor_free(res);
   2901  SMARTLIST_FOREACH(vote1.net_params, char *, cp, tor_free(cp));
   2902  SMARTLIST_FOREACH(vote2.net_params, char *, cp, tor_free(cp));
   2903  SMARTLIST_FOREACH(vote3.net_params, char *, cp, tor_free(cp));
   2904  SMARTLIST_FOREACH(vote4.net_params, char *, cp, tor_free(cp));
   2905  smartlist_free(vote1.net_params);
   2906  smartlist_free(vote2.net_params);
   2907  smartlist_free(vote3.net_params);
   2908  smartlist_free(vote4.net_params);
   2909  smartlist_free(votes);
   2910 
   2911  return;
   2912 }
   2913 
   2914 static void
   2915 test_dir_param_voting_lookup(void *arg)
   2916 {
   2917  (void)arg;
   2918  smartlist_t *lst = smartlist_new();
   2919 
   2920  smartlist_split_string(lst,
   2921                         "moomin=9 moomin=10 moomintroll=5 fred "
   2922                         "jack= electricity=sdk opa=6z abc=9 abcd=99",
   2923                         NULL, 0, 0);
   2924 
   2925  tt_int_op(1000,
   2926            OP_EQ, dirvote_get_intermediate_param_value(lst, "ab", 1000));
   2927  tt_int_op(9, OP_EQ, dirvote_get_intermediate_param_value(lst, "abc", 1000));
   2928  tt_int_op(99, OP_EQ,
   2929            dirvote_get_intermediate_param_value(lst, "abcd", 1000));
   2930 
   2931 #ifndef ALL_BUGS_ARE_FATAL
   2932  /* moomin appears twice. That's a bug. */
   2933  tor_capture_bugs_(1);
   2934  tt_int_op(-100, OP_EQ,
   2935            dirvote_get_intermediate_param_value(lst, "moomin", -100));
   2936  tt_int_op(smartlist_len(tor_get_captured_bug_log_()), OP_EQ, 1);
   2937  tt_str_op(smartlist_get(tor_get_captured_bug_log_(), 0), OP_EQ,
   2938            "n_found == 0");
   2939  tor_end_capture_bugs_();
   2940  /* There is no 'fred=', so that is treated as not existing. */
   2941  tt_int_op(-100, OP_EQ,
   2942            dirvote_get_intermediate_param_value(lst, "fred", -100));
   2943  /* jack is truncated */
   2944  tor_capture_bugs_(1);
   2945  tt_int_op(-100, OP_EQ,
   2946            dirvote_get_intermediate_param_value(lst, "jack", -100));
   2947  tt_int_op(smartlist_len(tor_get_captured_bug_log_()), OP_EQ, 1);
   2948  tt_str_op(smartlist_get(tor_get_captured_bug_log_(), 0), OP_EQ,
   2949            "!(!ok)");
   2950  tor_end_capture_bugs_();
   2951  /* electricity and opa aren't integers. */
   2952  tor_capture_bugs_(1);
   2953  tt_int_op(-100, OP_EQ,
   2954            dirvote_get_intermediate_param_value(lst, "electricity", -100));
   2955  tt_int_op(smartlist_len(tor_get_captured_bug_log_()), OP_EQ, 1);
   2956  tt_str_op(smartlist_get(tor_get_captured_bug_log_(), 0), OP_EQ,
   2957            "!(!ok)");
   2958  tor_end_capture_bugs_();
   2959 
   2960  tor_capture_bugs_(1);
   2961  tt_int_op(-100, OP_EQ,
   2962            dirvote_get_intermediate_param_value(lst, "opa", -100));
   2963  tt_int_op(smartlist_len(tor_get_captured_bug_log_()), OP_EQ, 1);
   2964  tt_str_op(smartlist_get(tor_get_captured_bug_log_(), 0), OP_EQ,
   2965            "!(!ok)");
   2966  tor_end_capture_bugs_();
   2967 #endif /* !defined(ALL_BUGS_ARE_FATAL) */
   2968 
   2969 done:
   2970  SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
   2971  smartlist_free(lst);
   2972  tor_end_capture_bugs_();
   2973 }
   2974 
   2975 #undef dirvote_compute_params
   2976 
   2977 /** Helper: Test that two networkstatus_voter_info_t do in fact represent the
   2978 * same voting authority, and that they do in fact have all the same
   2979 * information. */
   2980 static void
   2981 test_same_voter(networkstatus_voter_info_t *v1,
   2982                networkstatus_voter_info_t *v2)
   2983 {
   2984  tt_str_op(v1->nickname,OP_EQ, v2->nickname);
   2985  tt_mem_op(v1->identity_digest,OP_EQ, v2->identity_digest, DIGEST_LEN);
   2986  tt_str_op(v1->address,OP_EQ, v2->address);
   2987  tt_assert(tor_addr_eq(&v1->ipv4_addr, &v2->ipv4_addr));
   2988  tt_int_op(v1->ipv4_dirport,OP_EQ, v2->ipv4_dirport);
   2989  tt_int_op(v1->ipv4_orport,OP_EQ, v2->ipv4_orport);
   2990  tt_str_op(v1->contact,OP_EQ, v2->contact);
   2991  tt_mem_op(v1->vote_digest,OP_EQ, v2->vote_digest, DIGEST_LEN);
   2992 done:
   2993  ;
   2994 }
   2995 
   2996 /** Helper: get a detached signatures document for one or two
   2997 * consensuses. */
   2998 static char *
   2999 get_detached_sigs(networkstatus_t *ns, networkstatus_t *ns2)
   3000 {
   3001  char *r;
   3002  smartlist_t *sl;
   3003  tor_assert(ns && ns->flavor == FLAV_NS);
   3004  sl = smartlist_new();
   3005  smartlist_add(sl,ns);
   3006  if (ns2)
   3007    smartlist_add(sl,ns2);
   3008  r = networkstatus_get_detached_signatures(sl);
   3009  smartlist_free(sl);
   3010  return r;
   3011 }
   3012 
   3013 /** Apply tweaks to the vote list for each voter */
   3014 static int
   3015 vote_tweaks_for_v3ns(networkstatus_t *v, int voter, time_t now)
   3016 {
   3017  vote_routerstatus_t *vrs;
   3018  const char *msg = NULL;
   3019 
   3020  tt_assert(v);
   3021  (void)now;
   3022 
   3023  if (voter == 1) {
   3024    measured_bw_line_t mbw;
   3025    memset(mbw.node_id, 33, sizeof(mbw.node_id));
   3026    mbw.bw_kb = 1024;
   3027    tt_int_op(measured_bw_line_apply(&mbw, v->routerstatus_list), OP_EQ, 1);
   3028  } else if (voter == 2 || voter == 3) {
   3029    /* Monkey around with the list a bit */
   3030    vrs = smartlist_get(v->routerstatus_list, 2);
   3031    smartlist_del_keeporder(v->routerstatus_list, 2);
   3032    vote_routerstatus_free(vrs);
   3033    vrs = smartlist_get(v->routerstatus_list, 0);
   3034    vrs->status.is_fast = 1;
   3035 
   3036    if (voter == 3) {
   3037      vrs = smartlist_get(v->routerstatus_list, 0);
   3038      smartlist_del_keeporder(v->routerstatus_list, 0);
   3039      vote_routerstatus_free(vrs);
   3040      vrs = smartlist_get(v->routerstatus_list, 0);
   3041      memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
   3042      tt_assert(router_add_to_routerlist(
   3043                  dir_common_generate_ri_from_rs(vrs), &msg,0,0) >= 0);
   3044    }
   3045  }
   3046 
   3047 done:
   3048  return 0;
   3049 }
   3050 
   3051 /**
   3052 * Test a parsed vote_routerstatus_t for v3_networkstatus test
   3053 */
   3054 static void
   3055 test_vrs_for_v3ns(vote_routerstatus_t *vrs, int voter, time_t now)
   3056 {
   3057  routerstatus_t *rs;
   3058  tor_addr_t addr_ipv6;
   3059 
   3060  tt_assert(vrs);
   3061  rs = &(vrs->status);
   3062  tt_assert(rs);
   3063 
   3064  /* Split out by digests to test */
   3065  if (tor_memeq(rs->identity_digest,
   3066                "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
   3067                "\x3\x3\x3\x3",
   3068                DIGEST_LEN) &&
   3069                (voter == 1)) {
   3070    /* Check the first routerstatus. */
   3071    tt_str_op(vrs->version,OP_EQ, "0.1.2.14");
   3072    tt_int_op(vrs->published_on,OP_EQ, now-1500);
   3073    tt_str_op(rs->nickname,OP_EQ, "router2");
   3074    tt_mem_op(rs->identity_digest,OP_EQ,
   3075               "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
   3076               "\x3\x3\x3\x3",
   3077               DIGEST_LEN);
   3078    tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
   3079    tt_assert(tor_addr_eq_ipv4h(&rs->ipv4_addr, 0x99008801));
   3080    tt_int_op(rs->ipv4_orport,OP_EQ, 443);
   3081    tt_int_op(rs->ipv4_dirport,OP_EQ, 8000);
   3082    /* no flags except "running" (16) and "v2dir" (64) and "valid" (128) */
   3083    tt_u64_op(vrs->flags, OP_EQ, UINT64_C(0xd0));
   3084  } else if (tor_memeq(rs->identity_digest,
   3085                       "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
   3086                       "\x5\x5\x5\x5",
   3087                       DIGEST_LEN) &&
   3088                       (voter == 1 || voter == 2)) {
   3089    tt_mem_op(rs->identity_digest,OP_EQ,
   3090               "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
   3091               "\x5\x5\x5\x5",
   3092               DIGEST_LEN);
   3093 
   3094    if (voter == 1) {
   3095      /* Check the second routerstatus. */
   3096      tt_str_op(vrs->version,OP_EQ, "0.2.0.5");
   3097      tt_int_op(vrs->published_on,OP_EQ, now-1000);
   3098      tt_str_op(rs->nickname,OP_EQ, "router1");
   3099    }
   3100    tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
   3101    tt_assert(tor_addr_eq_ipv4h(&rs->ipv4_addr, 0x99009901));
   3102    tt_int_op(rs->ipv4_orport,OP_EQ, 443);
   3103    tt_int_op(rs->ipv4_dirport,OP_EQ, 0);
   3104    tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
   3105    tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
   3106    tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
   3107    if (voter == 1) {
   3108      /* all except "authority" (1) */
   3109      tt_u64_op(vrs->flags, OP_EQ, UINT64_C(254));
   3110    } else {
   3111      /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
   3112      tt_u64_op(vrs->flags, OP_EQ, UINT64_C(974));
   3113    }
   3114  } else if (tor_memeq(rs->identity_digest,
   3115                       "\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33"
   3116                       "\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33",
   3117                       DIGEST_LEN) &&
   3118                       (voter == 1 || voter == 2)) {
   3119    /* Check the measured bandwidth bits */
   3120    tt_assert(vrs->has_measured_bw &&
   3121                vrs->measured_bw_kb == 1024);
   3122  } else {
   3123    /*
   3124     * Didn't expect this, but the old unit test only checked some of them,
   3125     * so don't assert.
   3126     */
   3127    /* tt_assert(0); */
   3128  }
   3129 
   3130 done:
   3131  return;
   3132 }
   3133 
   3134 /**
   3135 * Test a consensus for v3_networkstatus_test
   3136 */
   3137 static void
   3138 test_consensus_for_v3ns(networkstatus_t *con, time_t now)
   3139 {
   3140  (void)now;
   3141 
   3142  tt_assert(con);
   3143  tt_ptr_op(con->cert, OP_EQ, NULL);
   3144  tt_int_op(2,OP_EQ, smartlist_len(con->routerstatus_list));
   3145  /* There should be two listed routers: one with identity 3, one with
   3146   * identity 5. */
   3147 
   3148 done:
   3149  return;
   3150 }
   3151 
   3152 /**
   3153 * Test a router list entry for v3_networkstatus test
   3154 */
   3155 static void
   3156 test_routerstatus_for_v3ns(routerstatus_t *rs, time_t now)
   3157 {
   3158  (void)now;
   3159  tor_addr_t addr_ipv6;
   3160 
   3161  tt_assert(rs);
   3162 
   3163  /* There should be two listed routers: one with identity 3, one with
   3164   * identity 5. */
   3165  /* This one showed up in 2 digests. */
   3166  if (tor_memeq(rs->identity_digest,
   3167                "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
   3168                "\x3\x3",
   3169                DIGEST_LEN)) {
   3170    tt_mem_op(rs->identity_digest,OP_EQ,
   3171               "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
   3172               DIGEST_LEN);
   3173    tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
   3174    tt_assert(!rs->is_authority);
   3175    tt_assert(!rs->is_exit);
   3176    tt_assert(!rs->is_fast);
   3177    tt_assert(!rs->is_possible_guard);
   3178    tt_assert(!rs->is_stable);
   3179    /* (If it wasn't running it wouldn't be here) */
   3180    tt_assert(rs->is_flagged_running);
   3181    tt_assert(rs->is_valid);
   3182    tt_assert(!rs->is_named);
   3183    tt_assert(rs->is_v2_dir);
   3184    /* XXXX check version */
   3185  } else if (tor_memeq(rs->identity_digest,
   3186                       "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
   3187                       "\x5\x5\x5\x5",
   3188                       DIGEST_LEN)) {
   3189    /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'.  */
   3190    tt_mem_op(rs->identity_digest,OP_EQ,
   3191               "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
   3192               DIGEST_LEN);
   3193    tt_str_op(rs->nickname,OP_EQ, "router1");
   3194    tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
   3195    tt_assert(tor_addr_eq_ipv4h(&rs->ipv4_addr, 0x99009901));
   3196    tt_int_op(rs->ipv4_orport,OP_EQ, 443);
   3197    tt_int_op(rs->ipv4_dirport,OP_EQ, 0);
   3198    tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
   3199    tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
   3200    tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
   3201    tt_assert(!rs->is_authority);
   3202    tt_assert(rs->is_exit);
   3203    tt_assert(rs->is_fast);
   3204    tt_assert(rs->is_possible_guard);
   3205    tt_assert(rs->is_stable);
   3206    tt_assert(rs->is_flagged_running);
   3207    tt_assert(rs->is_valid);
   3208    tt_assert(rs->is_v2_dir);
   3209    tt_assert(!rs->is_named);
   3210    /* XXXX check version */
   3211  } else {
   3212    /* Weren't expecting this... */
   3213    tt_abort();
   3214  }
   3215 
   3216 done:
   3217  return;
   3218 }
   3219 
   3220 static void
   3221 test_dir_networkstatus_compute_bw_weights_v10(void *arg)
   3222 {
   3223  (void) arg;
   3224  smartlist_t *chunks = smartlist_new();
   3225  int64_t G, M, E, D, T, weight_scale;
   3226  int ret;
   3227  weight_scale = 10000;
   3228 
   3229  /* no case. one or more of the values is 0 */
   3230  G = M = E = D = 0;
   3231  T = G + M + E + D;
   3232  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3233                                             weight_scale);
   3234  tt_int_op(ret, OP_EQ, 0);
   3235  tt_int_op(smartlist_len(chunks), OP_EQ, 0);
   3236 
   3237  /* case 1 */
   3238  /* XXX dir-spec not followed? See #20272. If it isn't closed, then this is
   3239   * testing current behavior, not spec. */
   3240  G = E = 10;
   3241  M = D = 1;
   3242  T = G + M + E + D;
   3243  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3244                                             weight_scale);
   3245  tt_int_op(ret, OP_EQ, 1);
   3246  tt_int_op(smartlist_len(chunks), OP_EQ, 1);
   3247  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=3333 "
   3248    "Wbe=3000 Wbg=3000 Wbm=10000 Wdb=10000 Web=10000 Wed=3333 Wee=7000 "
   3249    "Weg=3333 Wem=7000 Wgb=10000 Wgd=3333 Wgg=7000 Wgm=7000 Wmb=10000 "
   3250    "Wmd=3333 Wme=3000 Wmg=3000 Wmm=10000\n");
   3251  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3252  smartlist_clear(chunks);
   3253 
   3254  /* case 2a E scarce */
   3255  M = 100;
   3256  G = 20;
   3257  E = D = 5;
   3258  T = G + M + E + D;
   3259  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3260                                             weight_scale);
   3261  tt_int_op(ret, OP_EQ, 1);
   3262  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=0 Wbe=0 "
   3263    "Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=10000 Wee=10000 Weg=10000 "
   3264    "Wem=10000 Wgb=10000 Wgd=0 Wgg=10000 Wgm=10000 Wmb=10000 Wmd=0 Wme=0 "
   3265    "Wmg=0 Wmm=10000\n");
   3266  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3267  smartlist_clear(chunks);
   3268 
   3269  /* case 2a G scarce */
   3270  M = 100;
   3271  E = 20;
   3272  G = D = 5;
   3273  T = G + M + E + D;
   3274  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3275                                             weight_scale);
   3276  tt_int_op(ret, OP_EQ, 1);
   3277  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=0 Wbe=0 "
   3278    "Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=0 Wee=10000 Weg=0 Wem=10000 "
   3279    "Wgb=10000 Wgd=10000 Wgg=10000 Wgm=10000 Wmb=10000 Wmd=0 Wme=0 Wmg=0 "
   3280    "Wmm=10000\n");
   3281  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3282  smartlist_clear(chunks);
   3283 
   3284  /* case 2b1 (Wgg=1, Wmd=Wgd) */
   3285  M = 10;
   3286  E = 30;
   3287  G = 10;
   3288  D = 100;
   3289  T = G + M + E + D;
   3290  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3291                                             weight_scale);
   3292  tt_int_op(ret, OP_EQ, 1);
   3293  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=4000 "
   3294    "Wbe=0 Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=2000 Wee=10000 Weg=2000 "
   3295    "Wem=10000 Wgb=10000 Wgd=4000 Wgg=10000 Wgm=10000 Wmb=10000 Wmd=4000 "
   3296    "Wme=0 Wmg=0 Wmm=10000\n");
   3297  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3298  smartlist_clear(chunks);
   3299 
   3300  /* case 2b2 */
   3301  M = 60;
   3302  E = 30;
   3303  G = 10;
   3304  D = 100;
   3305  T = G + M + E + D;
   3306  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3307                                             weight_scale);
   3308  tt_int_op(ret, OP_EQ, 1);
   3309  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=666 Wbe=0 "
   3310    "Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=3666 Wee=10000 Weg=3666 "
   3311    "Wem=10000 Wgb=10000 Wgd=5668 Wgg=10000 Wgm=10000 Wmb=10000 Wmd=666 "
   3312    "Wme=0 Wmg=0 Wmm=10000\n");
   3313  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3314  smartlist_clear(chunks);
   3315 
   3316  /* case 2b3 */
   3317  /* XXX I can't get a combination of values that hits this case without error,
   3318   * so this just tests that it fails. See #20285. Also see #20284 as 2b3 does
   3319   * not follow dir-spec. */
   3320  /* (E < T/3 && G < T/3) && (E+D>=G || G+D>=E) && (M > T/3) */
   3321  M = 80;
   3322  E = 30;
   3323  G = 30;
   3324  D = 30;
   3325  T = G + M + E + D;
   3326  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3327                                             weight_scale);
   3328  tt_int_op(ret, OP_EQ, 0);
   3329  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3330  smartlist_clear(chunks);
   3331 
   3332  /* case 3a G scarce */
   3333  M = 10;
   3334  E = 30;
   3335  G = 10;
   3336  D = 5;
   3337  T = G + M + E + D;
   3338  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3339                                             weight_scale);
   3340  tt_int_op(ret, OP_EQ, 1);
   3341  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=0 "
   3342    "Wbe=3333 Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=0 Wee=6667 Weg=0 "
   3343    "Wem=6667 Wgb=10000 Wgd=10000 Wgg=10000 Wgm=10000 Wmb=10000 Wmd=0 "
   3344    "Wme=3333 Wmg=0 Wmm=10000\n");
   3345  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3346  smartlist_clear(chunks);
   3347 
   3348  /* case 3a E scarce */
   3349  M = 10;
   3350  E = 10;
   3351  G = 30;
   3352  D = 5;
   3353  T = G + M + E + D;
   3354  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3355                                             weight_scale);
   3356  tt_int_op(ret, OP_EQ, 1);
   3357  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=0 Wbe=0 "
   3358    "Wbg=3333 Wbm=10000 Wdb=10000 Web=10000 Wed=10000 Wee=10000 Weg=10000 "
   3359    "Wem=10000 Wgb=10000 Wgd=0 Wgg=6667 Wgm=6667 Wmb=10000 Wmd=0 Wme=0 "
   3360    "Wmg=3333 Wmm=10000\n");
   3361  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3362  smartlist_clear(chunks);
   3363 
   3364  /* case 3bg */
   3365  M = 10;
   3366  E = 30;
   3367  G = 10;
   3368  D = 10;
   3369  T = G + M + E + D;
   3370  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3371                                             weight_scale);
   3372  tt_int_op(ret, OP_EQ, 1);
   3373  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=0 "
   3374    "Wbe=3334 Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=0 Wee=6666 Weg=0 "
   3375    "Wem=6666 Wgb=10000 Wgd=10000 Wgg=10000 Wgm=10000 Wmb=10000 Wmd=0 "
   3376    "Wme=3334 Wmg=0 Wmm=10000\n");
   3377  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3378  smartlist_clear(chunks);
   3379 
   3380  /* case 3be */
   3381  M = 10;
   3382  E = 10;
   3383  G = 30;
   3384  D = 10;
   3385  T = G + M + E + D;
   3386  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3387                                             weight_scale);
   3388  tt_int_op(ret, OP_EQ, 1);
   3389  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=0 Wbe=0 "
   3390    "Wbg=3334 Wbm=10000 Wdb=10000 Web=10000 Wed=10000 Wee=10000 Weg=10000 "
   3391    "Wem=10000 Wgb=10000 Wgd=0 Wgg=6666 Wgm=6666 Wmb=10000 Wmd=0 Wme=0 "
   3392    "Wmg=3334 Wmm=10000\n");
   3393  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3394  smartlist_clear(chunks);
   3395 
   3396  /* case from 21 Jul 2013 (3be) */
   3397  G = 5483409;
   3398  M = 1455379;
   3399  E = 980834;
   3400  D = 3385803;
   3401  T = 11305425;
   3402  tt_i64_op(G+M+E+D, OP_EQ, T);
   3403  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3404                                             weight_scale);
   3405  tt_assert(ret);
   3406  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=883 Wbe=0 "
   3407    "Wbg=3673 Wbm=10000 Wdb=10000 Web=10000 Wed=8233 Wee=10000 Weg=8233 "
   3408    "Wem=10000 Wgb=10000 Wgd=883 Wgg=6327 Wgm=6327 Wmb=10000 Wmd=883 Wme=0 "
   3409    "Wmg=3673 Wmm=10000\n");
   3410  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3411  smartlist_clear(chunks);
   3412 
   3413  /* case from 04 Oct 2016 (3a E scarce) */
   3414  G=29322240;
   3415  M=4721546;
   3416  E=1522058;
   3417  D=9273571;
   3418  T=44839415;
   3419  tt_i64_op(G+M+E+D, OP_EQ, T);
   3420  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3421                                             weight_scale);
   3422  tt_assert(ret);
   3423  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=0 Wbe=0 "
   3424    "Wbg=4194 Wbm=10000 Wdb=10000 Web=10000 Wed=10000 Wee=10000 Weg=10000 "
   3425    "Wem=10000 Wgb=10000 Wgd=0 Wgg=5806 Wgm=5806 Wmb=10000 Wmd=0 Wme=0 "
   3426    "Wmg=4194 Wmm=10000\n");
   3427  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3428  smartlist_clear(chunks);
   3429 
   3430  /* case from 04 Sep 2013 (2b1) */
   3431  G=3091352;
   3432  M=1838837;
   3433  E=2109300;
   3434  D=2469369;
   3435  T=9508858;
   3436  tt_i64_op(G+M+E+D, OP_EQ, T);
   3437  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3438                                             weight_scale);
   3439  tt_assert(ret);
   3440  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=317 "
   3441    "Wbe=5938 Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=9366 Wee=4061 "
   3442    "Weg=9366 Wem=4061 Wgb=10000 Wgd=317 Wgg=10000 Wgm=10000 Wmb=10000 "
   3443    "Wmd=317 Wme=5938 Wmg=0 Wmm=10000\n");
   3444  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3445  smartlist_clear(chunks);
   3446 
   3447  /* explicitly test initializing weights to 1*/
   3448  G=1;
   3449  M=1;
   3450  E=1;
   3451  D=1;
   3452  T=4;
   3453  tt_i64_op(G+M+E+D, OP_EQ, T);
   3454  ret = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D, T,
   3455                                             weight_scale);
   3456  tt_str_op(smartlist_get(chunks, 0), OP_EQ, "bandwidth-weights Wbd=3333 "
   3457    "Wbe=0 Wbg=0 Wbm=10000 Wdb=10000 Web=10000 Wed=3333 Wee=10000 Weg=3333 "
   3458    "Wem=10000 Wgb=10000 Wgd=3333 Wgg=10000 Wgm=10000 Wmb=10000 Wmd=3333 "
   3459    "Wme=0 Wmg=0 Wmm=10000\n");
   3460  tt_assert(ret);
   3461 
   3462 done:
   3463  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   3464  smartlist_free(chunks);
   3465 }
   3466 
   3467 static authority_cert_t *mock_cert;
   3468 
   3469 static authority_cert_t *
   3470 get_my_v3_authority_cert_m(void)
   3471 {
   3472  tor_assert(mock_cert);
   3473  return mock_cert;
   3474 }
   3475 
   3476 /** Run a unit tests for generating and parsing networkstatuses, with
   3477 * the supply test fns. */
   3478 static void
   3479 test_a_networkstatus(
   3480    vote_routerstatus_t * (*vrs_gen)(int idx, time_t now),
   3481    int (*vote_tweaks)(networkstatus_t *v, int voter, time_t now),
   3482    void (*vrs_test)(vote_routerstatus_t *vrs, int voter, time_t now),
   3483    void (*consensus_test)(networkstatus_t *con, time_t now),
   3484    void (*rs_test)(routerstatus_t *rs, time_t now))
   3485 {
   3486  authority_cert_t *cert1=NULL, *cert2=NULL, *cert3=NULL;
   3487  crypto_pk_t *sign_skey_1=NULL, *sign_skey_2=NULL, *sign_skey_3=NULL;
   3488  crypto_pk_t *sign_skey_leg1=NULL;
   3489  /*
   3490   * Sum the non-zero returns from vote_tweaks() we've seen; if vote_tweaks()
   3491   * returns non-zero, it changed net_params and we should skip the tests for
   3492   * that later as they will fail.
   3493   */
   3494  int params_tweaked = 0;
   3495 
   3496  time_t now = time(NULL);
   3497  networkstatus_voter_info_t *voter;
   3498  document_signature_t *sig;
   3499  networkstatus_t *vote=NULL, *v1=NULL, *v2=NULL, *v3=NULL, *con=NULL,
   3500    *con_md=NULL;
   3501  vote_routerstatus_t *vrs;
   3502  routerstatus_t *rs;
   3503  int idx, n_rs, n_vrs;
   3504  char *consensus_text=NULL, *cp=NULL;
   3505  smartlist_t *votes = smartlist_new();
   3506 
   3507  /* For generating the two other consensuses. */
   3508  char *detached_text1=NULL, *detached_text2=NULL;
   3509  char *consensus_text2=NULL, *consensus_text3=NULL;
   3510  char *consensus_text_md2=NULL, *consensus_text_md3=NULL;
   3511  char *consensus_text_md=NULL;
   3512  networkstatus_t *con2=NULL, *con_md2=NULL, *con3=NULL, *con_md3=NULL;
   3513  ns_detached_signatures_t *dsig1=NULL, *dsig2=NULL;
   3514 
   3515  tt_assert(vrs_gen);
   3516  tt_assert(rs_test);
   3517  tt_assert(vrs_test);
   3518 
   3519  MOCK(get_my_v3_authority_cert, get_my_v3_authority_cert_m);
   3520 
   3521  /* Parse certificates and keys. */
   3522  cert1 = mock_cert = authority_cert_parse_from_string(AUTHORITY_CERT_1,
   3523                                                 strlen(AUTHORITY_CERT_1),
   3524                                                 NULL);
   3525  tt_assert(cert1);
   3526  cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2,
   3527                                           strlen(AUTHORITY_CERT_2),
   3528                                           NULL);
   3529  tt_assert(cert2);
   3530  cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3,
   3531                                           strlen(AUTHORITY_CERT_3),
   3532                                           NULL);
   3533  tt_assert(cert3);
   3534  sign_skey_1 = crypto_pk_new();
   3535  sign_skey_2 = crypto_pk_new();
   3536  sign_skey_3 = crypto_pk_new();
   3537  sign_skey_leg1 = pk_generate(4);
   3538  dirauth_sched_recalculate_timing(get_options(), now);
   3539  sr_state_init(0, 0);
   3540 
   3541  tt_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
   3542                                                   AUTHORITY_SIGNKEY_1, -1));
   3543  tt_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
   3544                                                   AUTHORITY_SIGNKEY_2, -1));
   3545  tt_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
   3546                                                   AUTHORITY_SIGNKEY_3, -1));
   3547 
   3548  tt_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
   3549  tt_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
   3550 
   3551  tt_assert(!dir_common_construct_vote_1(&vote, cert1, sign_skey_1, vrs_gen,
   3552                                         &v1, &n_vrs, now, 1));
   3553  tt_assert(v1);
   3554 
   3555  /* Make sure the parsed thing was right. */
   3556  tt_int_op(v1->type,OP_EQ, NS_TYPE_VOTE);
   3557  tt_int_op(v1->published,OP_EQ, vote->published);
   3558  tt_int_op(v1->valid_after,OP_EQ, vote->valid_after);
   3559  tt_int_op(v1->fresh_until,OP_EQ, vote->fresh_until);
   3560  tt_int_op(v1->valid_until,OP_EQ, vote->valid_until);
   3561  tt_int_op(v1->vote_seconds,OP_EQ, vote->vote_seconds);
   3562  tt_int_op(v1->dist_seconds,OP_EQ, vote->dist_seconds);
   3563  tt_str_op(v1->client_versions,OP_EQ, vote->client_versions);
   3564  tt_str_op(v1->server_versions,OP_EQ, vote->server_versions);
   3565  tt_assert(v1->voters && smartlist_len(v1->voters));
   3566  voter = smartlist_get(v1->voters, 0);
   3567  tt_str_op(voter->nickname,OP_EQ, "Voter1");
   3568  tt_str_op(voter->address,OP_EQ, "1.2.3.4");
   3569  tt_assert(tor_addr_eq_ipv4h(&voter->ipv4_addr, 0x01020304));
   3570  tt_int_op(voter->ipv4_dirport,OP_EQ, 80);
   3571  tt_int_op(voter->ipv4_orport,OP_EQ, 9000);
   3572  tt_str_op(voter->contact,OP_EQ, "voter@example.com");
   3573  tt_assert(v1->cert);
   3574  tt_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
   3575  cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
   3576  tt_str_op(cp,OP_EQ, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
   3577  tor_free(cp);
   3578  tt_int_op(smartlist_len(v1->routerstatus_list),OP_EQ, n_vrs);
   3579  networkstatus_vote_free(vote);
   3580  vote = NULL;
   3581 
   3582  if (vote_tweaks) params_tweaked += vote_tweaks(v1, 1, now);
   3583 
   3584  /* Check the routerstatuses. */
   3585  for (idx = 0; idx < n_vrs; ++idx) {
   3586    vrs = smartlist_get(v1->routerstatus_list, idx);
   3587    tt_assert(vrs);
   3588    vrs_test(vrs, 1, now);
   3589  }
   3590 
   3591  /* Generate second vote. It disagrees on some of the times,
   3592   * and doesn't list versions, and knows some crazy flags.
   3593   * Generate and parse v2. */
   3594  tt_assert(!dir_common_construct_vote_2(&vote, cert2, sign_skey_2, vrs_gen,
   3595                                         &v2, &n_vrs, now, 1));
   3596  tt_assert(v2);
   3597 
   3598  if (vote_tweaks) params_tweaked += vote_tweaks(v2, 2, now);
   3599 
   3600  /* Check that flags come out right.*/
   3601  cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
   3602  tt_str_op(cp,OP_EQ, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
   3603             "Running:Stable:V2Dir:Valid");
   3604  tor_free(cp);
   3605 
   3606  /* Check the routerstatuses. */
   3607  n_vrs = smartlist_len(v2->routerstatus_list);
   3608  for (idx = 0; idx < n_vrs; ++idx) {
   3609    vrs = smartlist_get(v2->routerstatus_list, idx);
   3610    tt_assert(vrs);
   3611    vrs_test(vrs, 2, now);
   3612  }
   3613  networkstatus_vote_free(vote);
   3614  vote = NULL;
   3615 
   3616  /* Generate the third vote with a legacy id. */
   3617  tt_assert(!dir_common_construct_vote_3(&vote, cert3, sign_skey_3, vrs_gen,
   3618                                         &v3, &n_vrs, now, 1));
   3619  tt_assert(v3);
   3620 
   3621  if (vote_tweaks) params_tweaked += vote_tweaks(v3, 3, now);
   3622 
   3623  /* Compute a consensus as voter 3. */
   3624  smartlist_add(votes, v3);
   3625  smartlist_add(votes, v1);
   3626  smartlist_add(votes, v2);
   3627  consensus_text = networkstatus_compute_consensus(votes, 3,
   3628                                                   cert3->identity_key,
   3629                                                   sign_skey_3,
   3630                                                   "AAAAAAAAAAAAAAAAAAAA",
   3631                                                   sign_skey_leg1,
   3632                                                   FLAV_NS);
   3633  tt_assert(consensus_text);
   3634  con = networkstatus_parse_vote_from_string_(consensus_text, NULL,
   3635                                             NS_TYPE_CONSENSUS);
   3636  tt_assert(con);
   3637  //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
   3638  //           v1_text, v2_text, v3_text);
   3639  consensus_text_md = networkstatus_compute_consensus(votes, 3,
   3640                                                   cert3->identity_key,
   3641                                                   sign_skey_3,
   3642                                                   "AAAAAAAAAAAAAAAAAAAA",
   3643                                                   sign_skey_leg1,
   3644                                                   FLAV_MICRODESC);
   3645  tt_assert(consensus_text_md);
   3646  con_md = networkstatus_parse_vote_from_string_(consensus_text_md, NULL,
   3647                                                NS_TYPE_CONSENSUS);
   3648  tt_assert(con_md);
   3649  tt_int_op(con_md->flavor,OP_EQ, FLAV_MICRODESC);
   3650 
   3651  /* Check consensus contents. */
   3652  tt_assert(con->type == NS_TYPE_CONSENSUS);
   3653  tt_int_op(con->published,OP_EQ, 0); /* this field only appears in votes. */
   3654  tt_int_op(con->valid_after,OP_EQ, now+1000);
   3655  tt_int_op(con->fresh_until,OP_EQ, now+2003); /* median */
   3656  tt_int_op(con->valid_until,OP_EQ, now+3000);
   3657  tt_int_op(con->vote_seconds,OP_EQ, 100);
   3658  tt_int_op(con->dist_seconds,OP_EQ, 250); /* median */
   3659  tt_str_op(con->client_versions,OP_EQ, "0.1.2.14");
   3660  tt_str_op(con->server_versions,OP_EQ, "0.1.2.15,0.1.2.16");
   3661  cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
   3662  tt_str_op(cp,OP_EQ, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
   3663             "Running:Stable:V2Dir:Valid");
   3664  tor_free(cp);
   3665  if (!params_tweaked) {
   3666    /* Skip this one if vote_tweaks() messed with the param lists */
   3667    cp = smartlist_join_strings(con->net_params, ":", 0, NULL);
   3668    tt_str_op(cp,OP_EQ, "circuitwindow=80:foo=660");
   3669    tor_free(cp);
   3670  }
   3671 
   3672  tt_int_op(4,OP_EQ, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
   3673  /* The voter id digests should be in this order. */
   3674  tt_assert(fast_memcmp(cert2->cache_info.identity_digest,
   3675                     cert1->cache_info.identity_digest,DIGEST_LEN)<0);
   3676  tt_assert(fast_memcmp(cert1->cache_info.identity_digest,
   3677                     cert3->cache_info.identity_digest,DIGEST_LEN)<0);
   3678  test_same_voter(smartlist_get(con->voters, 1),
   3679                  smartlist_get(v2->voters, 0));
   3680  test_same_voter(smartlist_get(con->voters, 2),
   3681                  smartlist_get(v1->voters, 0));
   3682  test_same_voter(smartlist_get(con->voters, 3),
   3683                  smartlist_get(v3->voters, 0));
   3684 
   3685  consensus_test(con, now);
   3686 
   3687  /* Check the routerstatuses. */
   3688  n_rs = smartlist_len(con->routerstatus_list);
   3689  tt_assert(n_rs);
   3690  for (idx = 0; idx < n_rs; ++idx) {
   3691    rs = smartlist_get(con->routerstatus_list, idx);
   3692    tt_assert(rs);
   3693    rs_test(rs, now);
   3694  }
   3695 
   3696  n_rs = smartlist_len(con_md->routerstatus_list);
   3697  tt_assert(n_rs);
   3698  for (idx = 0; idx < n_rs; ++idx) {
   3699    rs = smartlist_get(con_md->routerstatus_list, idx);
   3700    tt_assert(rs);
   3701  }
   3702 
   3703  /* Check signatures.  the first voter is a pseudo-entry with a legacy key.
   3704   * The second one hasn't signed.  The fourth one has signed: validate it. */
   3705  voter = smartlist_get(con->voters, 1);
   3706  tt_int_op(smartlist_len(voter->sigs),OP_EQ, 0);
   3707 
   3708  voter = smartlist_get(con->voters, 3);
   3709  tt_int_op(smartlist_len(voter->sigs),OP_EQ, 1);
   3710  sig = smartlist_get(voter->sigs, 0);
   3711  tt_assert(sig->signature);
   3712  tt_assert(!sig->good_signature);
   3713  tt_assert(!sig->bad_signature);
   3714 
   3715  tt_assert(!networkstatus_check_document_signature(con, sig, cert3));
   3716  tt_assert(sig->signature);
   3717  tt_assert(sig->good_signature);
   3718  tt_assert(!sig->bad_signature);
   3719 
   3720  {
   3721    const char *msg=NULL;
   3722    /* Compute the other two signed consensuses. */
   3723    smartlist_shuffle(votes);
   3724    consensus_text2 = networkstatus_compute_consensus(votes, 3,
   3725                                                      cert2->identity_key,
   3726                                                      sign_skey_2, NULL,NULL,
   3727                                                      FLAV_NS);
   3728    consensus_text_md2 = networkstatus_compute_consensus(votes, 3,
   3729                                                      cert2->identity_key,
   3730                                                      sign_skey_2, NULL,NULL,
   3731                                                      FLAV_MICRODESC);
   3732    smartlist_shuffle(votes);
   3733    consensus_text3 = networkstatus_compute_consensus(votes, 3,
   3734                                                      cert1->identity_key,
   3735                                                      sign_skey_1, NULL,NULL,
   3736                                                      FLAV_NS);
   3737    consensus_text_md3 = networkstatus_compute_consensus(votes, 3,
   3738                                                      cert1->identity_key,
   3739                                                      sign_skey_1, NULL,NULL,
   3740                                                      FLAV_MICRODESC);
   3741    tt_assert(consensus_text2);
   3742    tt_assert(consensus_text3);
   3743    tt_assert(consensus_text_md2);
   3744    tt_assert(consensus_text_md3);
   3745    con2 = networkstatus_parse_vote_from_string_(consensus_text2, NULL,
   3746                                                NS_TYPE_CONSENSUS);
   3747    con3 = networkstatus_parse_vote_from_string_(consensus_text3, NULL,
   3748                                                NS_TYPE_CONSENSUS);
   3749    con_md2 = networkstatus_parse_vote_from_string_(consensus_text_md2, NULL,
   3750                                                NS_TYPE_CONSENSUS);
   3751    con_md3 = networkstatus_parse_vote_from_string_(consensus_text_md3, NULL,
   3752                                                NS_TYPE_CONSENSUS);
   3753    tt_assert(con2);
   3754    tt_assert(con3);
   3755    tt_assert(con_md2);
   3756    tt_assert(con_md3);
   3757 
   3758    /* All three should have the same digest. */
   3759    tt_mem_op(&con->digests,OP_EQ, &con2->digests, sizeof(common_digests_t));
   3760    tt_mem_op(&con->digests,OP_EQ, &con3->digests, sizeof(common_digests_t));
   3761 
   3762    tt_mem_op(&con_md->digests,OP_EQ, &con_md2->digests,
   3763              sizeof(common_digests_t));
   3764    tt_mem_op(&con_md->digests,OP_EQ, &con_md3->digests,
   3765              sizeof(common_digests_t));
   3766 
   3767    /* Extract a detached signature from con3. */
   3768    detached_text1 = get_detached_sigs(con3, con_md3);
   3769    tt_assert(detached_text1);
   3770    /* Try to parse it. */
   3771    dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
   3772    tt_assert(dsig1);
   3773 
   3774    /* Are parsed values as expected? */
   3775    tt_int_op(dsig1->valid_after,OP_EQ, con3->valid_after);
   3776    tt_int_op(dsig1->fresh_until,OP_EQ, con3->fresh_until);
   3777    tt_int_op(dsig1->valid_until,OP_EQ, con3->valid_until);
   3778    {
   3779      common_digests_t *dsig_digests = strmap_get(dsig1->digests, "ns");
   3780      tt_assert(dsig_digests);
   3781      tt_mem_op(dsig_digests->d[DIGEST_SHA1], OP_EQ,
   3782                con3->digests.d[DIGEST_SHA1], DIGEST_LEN);
   3783      dsig_digests = strmap_get(dsig1->digests, "microdesc");
   3784      tt_assert(dsig_digests);
   3785      tt_mem_op(dsig_digests->d[DIGEST_SHA256],OP_EQ,
   3786                 con_md3->digests.d[DIGEST_SHA256],
   3787                 DIGEST256_LEN);
   3788    }
   3789    {
   3790      smartlist_t *dsig_signatures = strmap_get(dsig1->signatures, "ns");
   3791      tt_assert(dsig_signatures);
   3792      tt_int_op(1,OP_EQ, smartlist_len(dsig_signatures));
   3793      sig = smartlist_get(dsig_signatures, 0);
   3794      tt_mem_op(sig->identity_digest,OP_EQ, cert1->cache_info.identity_digest,
   3795                 DIGEST_LEN);
   3796      tt_int_op(sig->alg,OP_EQ, DIGEST_SHA1);
   3797 
   3798      dsig_signatures = strmap_get(dsig1->signatures, "microdesc");
   3799      tt_assert(dsig_signatures);
   3800      tt_int_op(1,OP_EQ, smartlist_len(dsig_signatures));
   3801      sig = smartlist_get(dsig_signatures, 0);
   3802      tt_mem_op(sig->identity_digest,OP_EQ, cert1->cache_info.identity_digest,
   3803                 DIGEST_LEN);
   3804      tt_int_op(sig->alg,OP_EQ, DIGEST_SHA256);
   3805    }
   3806 
   3807    /* Try adding it to con2. */
   3808    detached_text2 = get_detached_sigs(con2,con_md2);
   3809    tt_int_op(1,OP_EQ, networkstatus_add_detached_signatures(con2, dsig1,
   3810                                                   "test", LOG_INFO, &msg));
   3811    tor_free(detached_text2);
   3812    tt_int_op(1,OP_EQ,
   3813              networkstatus_add_detached_signatures(con_md2, dsig1, "test",
   3814                                                     LOG_INFO, &msg));
   3815    tor_free(detached_text2);
   3816    detached_text2 = get_detached_sigs(con2,con_md2);
   3817    //printf("\n<%s>\n", detached_text2);
   3818    dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
   3819    tt_assert(dsig2);
   3820    /*
   3821    printf("\n");
   3822    SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
   3823        char hd[64];
   3824        base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
   3825        printf("%s\n", hd);
   3826      });
   3827    */
   3828    tt_int_op(2,OP_EQ,
   3829            smartlist_len((smartlist_t*)strmap_get(dsig2->signatures, "ns")));
   3830    tt_int_op(2,OP_EQ,
   3831            smartlist_len((smartlist_t*)strmap_get(dsig2->signatures,
   3832                                                   "microdesc")));
   3833 
   3834    /* Try adding to con2 twice; verify that nothing changes. */
   3835    tt_int_op(0,OP_EQ, networkstatus_add_detached_signatures(con2, dsig1,
   3836                                               "test", LOG_INFO, &msg));
   3837 
   3838    /* Add to con. */
   3839    tt_int_op(2,OP_EQ, networkstatus_add_detached_signatures(con, dsig2,
   3840                                               "test", LOG_INFO, &msg));
   3841    /* Check signatures */
   3842    voter = smartlist_get(con->voters, 1);
   3843    sig = smartlist_get(voter->sigs, 0);
   3844    tt_assert(sig);
   3845    tt_assert(!networkstatus_check_document_signature(con, sig, cert2));
   3846    voter = smartlist_get(con->voters, 2);
   3847    sig = smartlist_get(voter->sigs, 0);
   3848    tt_assert(sig);
   3849    tt_assert(!networkstatus_check_document_signature(con, sig, cert1));
   3850  }
   3851 
   3852 done:
   3853  tor_free(cp);
   3854  smartlist_free(votes);
   3855  tor_free(consensus_text);
   3856  tor_free(consensus_text_md);
   3857 
   3858  networkstatus_vote_free(vote);
   3859  networkstatus_vote_free(v1);
   3860  networkstatus_vote_free(v2);
   3861  networkstatus_vote_free(v3);
   3862  networkstatus_vote_free(con);
   3863  networkstatus_vote_free(con_md);
   3864  crypto_pk_free(sign_skey_1);
   3865  crypto_pk_free(sign_skey_2);
   3866  crypto_pk_free(sign_skey_3);
   3867  crypto_pk_free(sign_skey_leg1);
   3868  authority_cert_free(cert1);
   3869  authority_cert_free(cert2);
   3870  authority_cert_free(cert3);
   3871 
   3872  tor_free(consensus_text2);
   3873  tor_free(consensus_text3);
   3874  tor_free(consensus_text_md2);
   3875  tor_free(consensus_text_md3);
   3876  tor_free(detached_text1);
   3877  tor_free(detached_text2);
   3878 
   3879  networkstatus_vote_free(con2);
   3880  networkstatus_vote_free(con3);
   3881  networkstatus_vote_free(con_md2);
   3882  networkstatus_vote_free(con_md3);
   3883  ns_detached_signatures_free(dsig1);
   3884  ns_detached_signatures_free(dsig2);
   3885 }
   3886 
   3887 /** Run unit tests for generating and parsing V3 consensus networkstatus
   3888 * documents. */
   3889 static void
   3890 test_dir_v3_networkstatus(void *arg)
   3891 {
   3892  (void)arg;
   3893  test_a_networkstatus(dir_common_gen_routerstatus_for_v3ns,
   3894                       vote_tweaks_for_v3ns,
   3895                       test_vrs_for_v3ns,
   3896                       test_consensus_for_v3ns,
   3897                       test_routerstatus_for_v3ns);
   3898 }
   3899 
   3900 static void
   3901 test_dir_scale_bw(void *testdata)
   3902 {
   3903  double v[8] = { 2.0/3,
   3904                  7.0,
   3905                  1.0,
   3906                  3.0,
   3907                  1.0/5,
   3908                  1.0/7,
   3909                  12.0,
   3910                  24.0 };
   3911  double vals_dbl[8];
   3912  uint64_t vals_u64[8];
   3913  uint64_t total;
   3914  int i;
   3915 
   3916  (void) testdata;
   3917 
   3918  for (i=0; i<8; ++i)
   3919    vals_dbl[i] = v[i];
   3920 
   3921  scale_array_elements_to_u64(vals_u64, vals_dbl, 8, &total);
   3922 
   3923  tt_int_op((int)total, OP_EQ, 48);
   3924  total = 0;
   3925  for (i=0; i<8; ++i) {
   3926    total += vals_u64[i];
   3927  }
   3928  tt_assert(total >= (UINT64_C(1)<<60));
   3929  tt_assert(total <= (UINT64_C(1)<<62));
   3930 
   3931  for (i=0; i<8; ++i) {
   3932    /* vals[2].u64 is the scaled value of 1.0 */
   3933    double ratio = ((double)vals_u64[i]) / vals_u64[2];
   3934    tt_double_op(fabs(ratio - v[i]), OP_LT, .00001);
   3935  }
   3936 
   3937  /* test handling of no entries */
   3938  total = 1;
   3939  scale_array_elements_to_u64(vals_u64, vals_dbl, 0, &total);
   3940  tt_assert(total == 0);
   3941 
   3942  /* make sure we don't read the array when we have no entries
   3943   * may require compiler flags to catch NULL dereferences */
   3944  total = 1;
   3945  scale_array_elements_to_u64(NULL, NULL, 0, &total);
   3946  tt_assert(total == 0);
   3947 
   3948  scale_array_elements_to_u64(NULL, NULL, 0, NULL);
   3949 
   3950  /* test handling of zero totals */
   3951  total = 1;
   3952  vals_dbl[0] = 0.0;
   3953  scale_array_elements_to_u64(vals_u64, vals_dbl, 1, &total);
   3954  tt_assert(total == 0);
   3955  tt_assert(vals_u64[0] == 0);
   3956 
   3957  vals_dbl[0] = 0.0;
   3958  vals_dbl[1] = 0.0;
   3959  scale_array_elements_to_u64(vals_u64, vals_dbl, 2, NULL);
   3960  tt_assert(vals_u64[0] == 0);
   3961  tt_assert(vals_u64[1] == 0);
   3962 
   3963 done:
   3964  ;
   3965 }
   3966 
   3967 static void
   3968 test_dir_random_weighted(void *testdata)
   3969 {
   3970  int histogram[10];
   3971  uint64_t vals[10] = {3,1,2,4,6,0,7,5,8,9}, total=0;
   3972  uint64_t inp_u64[10];
   3973  int i, choice;
   3974  const int n = 50000;
   3975  double max_sq_error;
   3976  (void) testdata;
   3977 
   3978  /* Try a ten-element array with values from 0 through 10. The values are
   3979   * in a scrambled order to make sure we don't depend on order. */
   3980  memset(histogram,0,sizeof(histogram));
   3981  for (i=0; i<10; ++i) {
   3982    inp_u64[i] = vals[i];
   3983    total += vals[i];
   3984  }
   3985  tt_u64_op(total, OP_EQ, 45);
   3986  for (i=0; i<n; ++i) {
   3987    choice = choose_array_element_by_weight(inp_u64, 10);
   3988    tt_int_op(choice, OP_GE, 0);
   3989    tt_int_op(choice, OP_LT, 10);
   3990    histogram[choice]++;
   3991  }
   3992 
   3993  /* Now see if we chose things about frequently enough. */
   3994  max_sq_error = 0;
   3995  for (i=0; i<10; ++i) {
   3996    int expected = (int)(n*vals[i]/total);
   3997    double frac_diff = 0, sq;
   3998    TT_BLATHER(("  %d : %5d vs %5d\n", (int)vals[i], histogram[i], expected));
   3999    if (expected)
   4000      frac_diff = (histogram[i] - expected) / ((double)expected);
   4001    else
   4002      tt_int_op(histogram[i], OP_EQ, 0);
   4003 
   4004    sq = frac_diff * frac_diff;
   4005    if (sq > max_sq_error)
   4006      max_sq_error = sq;
   4007  }
   4008  /* It should almost always be much much less than this.  If you want to
   4009   * figure out the odds, please feel free. */
   4010  tt_double_op(max_sq_error, OP_LT, .05);
   4011 
   4012  /* Now try a singleton; do we choose it? */
   4013  for (i = 0; i < 100; ++i) {
   4014    choice = choose_array_element_by_weight(inp_u64, 1);
   4015    tt_int_op(choice, OP_EQ, 0);
   4016  }
   4017 
   4018  /* Now try an array of zeros.  We should choose randomly. */
   4019  memset(histogram,0,sizeof(histogram));
   4020  for (i = 0; i < 5; ++i)
   4021    inp_u64[i] = 0;
   4022  for (i = 0; i < n; ++i) {
   4023    choice = choose_array_element_by_weight(inp_u64, 5);
   4024    tt_int_op(choice, OP_GE, 0);
   4025    tt_int_op(choice, OP_LT, 5);
   4026    histogram[choice]++;
   4027  }
   4028  /* Now see if we chose things about frequently enough. */
   4029  max_sq_error = 0;
   4030  for (i=0; i<5; ++i) {
   4031    int expected = n/5;
   4032    double frac_diff = 0, sq;
   4033    TT_BLATHER(("  %d : %5d vs %5d\n", (int)vals[i], histogram[i], expected));
   4034    frac_diff = (histogram[i] - expected) / ((double)expected);
   4035    sq = frac_diff * frac_diff;
   4036    if (sq > max_sq_error)
   4037      max_sq_error = sq;
   4038  }
   4039  /* It should almost always be much much less than this.  If you want to
   4040   * figure out the odds, please feel free. */
   4041  tt_double_op(max_sq_error, OP_LT, .05);
   4042 done:
   4043  ;
   4044 }
   4045 
   4046 /* Function pointers for test_dir_clip_unmeasured_bw_kb() */
   4047 
   4048 static uint32_t alternate_clip_bw = 0;
   4049 
   4050 /**
   4051 * Generate a routerstatus for clip_unmeasured_bw_kb test; based on the
   4052 * v3_networkstatus ones.
   4053 */
   4054 static vote_routerstatus_t *
   4055 gen_routerstatus_for_umbw(int idx, time_t now)
   4056 {
   4057  vote_routerstatus_t *vrs = NULL;
   4058  routerstatus_t *rs;
   4059  tor_addr_t addr_ipv6;
   4060  uint32_t max_unmeasured_bw_kb = (alternate_clip_bw > 0) ?
   4061    alternate_clip_bw : DEFAULT_MAX_UNMEASURED_BW_KB;
   4062 
   4063  switch (idx) {
   4064    case 0:
   4065      /* Generate the first routerstatus. */
   4066      vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
   4067      rs = &vrs->status;
   4068      vrs->version = tor_strdup("0.1.2.14");
   4069      vrs->published_on = now-1500;
   4070      strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
   4071      memset(rs->identity_digest, 3, DIGEST_LEN);
   4072      memset(rs->descriptor_digest, 78, DIGEST_LEN);
   4073      tor_addr_from_ipv4h(&rs->ipv4_addr, 0x99008801);
   4074      rs->ipv4_orport = 443;
   4075      rs->ipv4_dirport = 8000;
   4076      /* all flags but running and valid cleared */
   4077      rs->is_flagged_running = 1;
   4078      rs->is_valid = 1;
   4079      /*
   4080       * This one has measured bandwidth below the clip cutoff, and
   4081       * so shouldn't be clipped; we'll have to test that it isn't
   4082       * later.
   4083       */
   4084      vrs->has_measured_bw = 1;
   4085      rs->has_bandwidth = 1;
   4086      vrs->measured_bw_kb = rs->bandwidth_kb = max_unmeasured_bw_kb / 2;
   4087      vrs->protocols = tor_strdup("Link=2 Wombat=40");
   4088      break;
   4089    case 1:
   4090      /* Generate the second routerstatus. */
   4091      vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
   4092      rs = &vrs->status;
   4093      vrs->version = tor_strdup("0.2.0.5");
   4094      vrs->published_on = now-1000;
   4095      strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
   4096      memset(rs->identity_digest, 5, DIGEST_LEN);
   4097      memset(rs->descriptor_digest, 77, DIGEST_LEN);
   4098      tor_addr_from_ipv4h(&rs->ipv4_addr, 0x99009901);
   4099      rs->ipv4_orport = 443;
   4100      rs->ipv4_dirport = 0;
   4101      tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
   4102      tor_addr_copy(&rs->ipv6_addr, &addr_ipv6);
   4103      rs->ipv6_orport = 4711;
   4104      rs->is_exit = rs->is_stable = rs->is_fast = rs->is_flagged_running =
   4105        rs->is_valid = rs->is_possible_guard = 1;
   4106      /*
   4107       * This one has measured bandwidth above the clip cutoff, and
   4108       * so shouldn't be clipped; we'll have to test that it isn't
   4109       * later.
   4110       */
   4111      vrs->has_measured_bw = 1;
   4112      rs->has_bandwidth = 1;
   4113      vrs->measured_bw_kb = rs->bandwidth_kb = 2 * max_unmeasured_bw_kb;
   4114      vrs->protocols = tor_strdup("Link=2 Wombat=40");
   4115      break;
   4116    case 2:
   4117      /* Generate the third routerstatus. */
   4118      vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
   4119      rs = &vrs->status;
   4120      vrs->version = tor_strdup("0.1.0.3");
   4121      vrs->published_on = now-1000;
   4122      strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
   4123      memset(rs->identity_digest, 0x33, DIGEST_LEN);
   4124      memset(rs->descriptor_digest, 79, DIGEST_LEN);
   4125      tor_addr_from_ipv4h(&rs->ipv4_addr, 0xAA009901);
   4126      rs->ipv4_orport = 400;
   4127      rs->ipv4_dirport = 9999;
   4128      rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
   4129        rs->is_flagged_running = rs->is_valid =
   4130        rs->is_possible_guard = 1;
   4131      /*
   4132       * This one has unmeasured bandwidth above the clip cutoff, and
   4133       * so should be clipped; we'll have to test that it isn't
   4134       * later.
   4135       */
   4136      vrs->has_measured_bw = 0;
   4137      rs->has_bandwidth = 1;
   4138      vrs->measured_bw_kb = 0;
   4139      rs->bandwidth_kb = 2 * max_unmeasured_bw_kb;
   4140      vrs->protocols = tor_strdup("Link=2 Wombat=40");
   4141      break;
   4142    case 3:
   4143      /* Generate a fourth routerstatus that is not running. */
   4144      vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
   4145      rs = &vrs->status;
   4146      vrs->version = tor_strdup("0.1.6.3");
   4147      vrs->published_on = now-1000;
   4148      strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
   4149      memset(rs->identity_digest, 0x34, DIGEST_LEN);
   4150      memset(rs->descriptor_digest, 47, DIGEST_LEN);
   4151      tor_addr_from_ipv4h(&rs->ipv4_addr, 0xC0000203);
   4152      rs->ipv4_orport = 500;
   4153      rs->ipv4_dirport = 1999;
   4154      /* all flags but running and valid cleared */
   4155      rs->is_flagged_running = 1;
   4156      rs->is_valid = 1;
   4157      /*
   4158       * This one has unmeasured bandwidth below the clip cutoff, and
   4159       * so shouldn't be clipped; we'll have to test that it isn't
   4160       * later.
   4161       */
   4162      vrs->has_measured_bw = 0;
   4163      rs->has_bandwidth = 1;
   4164      vrs->measured_bw_kb = 0;
   4165      rs->bandwidth_kb = max_unmeasured_bw_kb / 2;
   4166      vrs->protocols = tor_strdup("Link=2 Wombat=40");
   4167      break;
   4168    case 4:
   4169      /* No more for this test; return NULL */
   4170      vrs = NULL;
   4171      break;
   4172    default:
   4173      /* Shouldn't happen */
   4174      tt_abort();
   4175  }
   4176  if (vrs) {
   4177    vrs->microdesc = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
   4178    tor_asprintf(&vrs->microdesc->microdesc_hash_line,
   4179                 "m 32,33 "
   4180                 "sha256=xyzajkldsdsajdadlsdjaslsdksdjlsdjsdaskdaaa%d\n",
   4181                 idx);
   4182  }
   4183 
   4184 done:
   4185  return vrs;
   4186 }
   4187 
   4188 /** Apply tweaks to the vote list for each voter; for the umbw test this is
   4189 * just adding the right consensus methods to let clipping happen */
   4190 static int
   4191 vote_tweaks_for_umbw(networkstatus_t *v, int voter, time_t now)
   4192 {
   4193  char *maxbw_param = NULL;
   4194  int rv = 0;
   4195 
   4196  tt_assert(v);
   4197  (void)voter;
   4198  (void)now;
   4199 
   4200  tt_assert(v->supported_methods);
   4201  SMARTLIST_FOREACH(v->supported_methods, char *, c, tor_free(c));
   4202  smartlist_clear(v->supported_methods);
   4203  smartlist_split_string(v->supported_methods,
   4204                         "32 33",
   4205                         NULL, 0, -1);
   4206  /* If we're using a non-default clip bandwidth, add it to net_params */
   4207  if (alternate_clip_bw > 0) {
   4208    tor_asprintf(&maxbw_param, "maxunmeasuredbw=%u", alternate_clip_bw);
   4209    tt_assert(maxbw_param);
   4210    if (maxbw_param) {
   4211      smartlist_add(v->net_params, maxbw_param);
   4212      rv = 1;
   4213    }
   4214  }
   4215 
   4216 done:
   4217  return rv;
   4218 }
   4219 
   4220 /**
   4221 * Test a parsed vote_routerstatus_t for umbw test.
   4222 */
   4223 static void
   4224 test_vrs_for_umbw(vote_routerstatus_t *vrs, int voter, time_t now)
   4225 {
   4226  routerstatus_t *rs;
   4227  tor_addr_t addr_ipv6;
   4228  uint32_t max_unmeasured_bw_kb = (alternate_clip_bw > 0) ?
   4229    alternate_clip_bw : DEFAULT_MAX_UNMEASURED_BW_KB;
   4230 
   4231  (void)voter;
   4232  tt_assert(vrs);
   4233  rs = &(vrs->status);
   4234  tt_assert(rs);
   4235 
   4236  /* Split out by digests to test */
   4237  if (tor_memeq(rs->identity_digest,
   4238                "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
   4239                "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
   4240                DIGEST_LEN)) {
   4241    /*
   4242     * Check the first routerstatus - measured bandwidth below the clip
   4243     * cutoff.
   4244     */
   4245    tt_str_op(vrs->version,OP_EQ, "0.1.2.14");
   4246    tt_int_op(vrs->published_on,OP_EQ, now-1500);
   4247    tt_str_op(rs->nickname,OP_EQ, "router2");
   4248    tt_mem_op(rs->identity_digest,OP_EQ,
   4249               "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
   4250               "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
   4251               DIGEST_LEN);
   4252    tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
   4253    tt_assert(tor_addr_eq_ipv4h(&rs->ipv4_addr, 0x99008801));
   4254    tt_int_op(rs->ipv4_orport,OP_EQ, 443);
   4255    tt_int_op(rs->ipv4_dirport,OP_EQ, 8000);
   4256    tt_assert(rs->has_bandwidth);
   4257    tt_assert(vrs->has_measured_bw);
   4258    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
   4259    tt_int_op(vrs->measured_bw_kb,OP_EQ, max_unmeasured_bw_kb / 2);
   4260  } else if (tor_memeq(rs->identity_digest,
   4261                       "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
   4262                       "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
   4263                       DIGEST_LEN)) {
   4264 
   4265    /*
   4266     * Check the second routerstatus - measured bandwidth above the clip
   4267     * cutoff.
   4268     */
   4269    tt_str_op(vrs->version,OP_EQ, "0.2.0.5");
   4270    tt_int_op(vrs->published_on,OP_EQ, now-1000);
   4271    tt_str_op(rs->nickname,OP_EQ, "router1");
   4272    tt_mem_op(rs->identity_digest,OP_EQ,
   4273               "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
   4274               "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
   4275               DIGEST_LEN);
   4276    tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
   4277    tt_assert(tor_addr_eq_ipv4h(&rs->ipv4_addr, 0x99009901));
   4278    tt_int_op(rs->ipv4_orport,OP_EQ, 443);
   4279    tt_int_op(rs->ipv4_dirport,OP_EQ, 0);
   4280    tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
   4281    tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
   4282    tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
   4283    tt_assert(rs->has_bandwidth);
   4284    tt_assert(vrs->has_measured_bw);
   4285    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb * 2);
   4286    tt_int_op(vrs->measured_bw_kb,OP_EQ, max_unmeasured_bw_kb * 2);
   4287  } else if (tor_memeq(rs->identity_digest,
   4288                       "\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33"
   4289                       "\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33",
   4290                       DIGEST_LEN)) {
   4291    /*
   4292     * Check the third routerstatus - unmeasured bandwidth above the clip
   4293     * cutoff; this one should be clipped later on in the consensus, but
   4294     * appears unclipped in the vote.
   4295     */
   4296    tt_assert(rs->has_bandwidth);
   4297    tt_assert(!(vrs->has_measured_bw));
   4298    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb * 2);
   4299    tt_int_op(vrs->measured_bw_kb,OP_EQ, 0);
   4300  } else if (tor_memeq(rs->identity_digest,
   4301                       "\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34"
   4302                       "\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34",
   4303                       DIGEST_LEN)) {
   4304    /*
   4305     * Check the fourth routerstatus - unmeasured bandwidth below the clip
   4306     * cutoff; this one should not be clipped.
   4307     */
   4308    tt_assert(rs->has_bandwidth);
   4309    tt_assert(!(vrs->has_measured_bw));
   4310    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
   4311    tt_int_op(vrs->measured_bw_kb,OP_EQ, 0);
   4312  } else {
   4313    tt_abort();
   4314  }
   4315 
   4316 done:
   4317  return;
   4318 }
   4319 
   4320 /**
   4321 * Test a consensus for v3_networkstatus_test
   4322 */
   4323 static void
   4324 test_consensus_for_umbw(networkstatus_t *con, time_t now)
   4325 {
   4326  (void)now;
   4327 
   4328  tt_assert(con);
   4329  tt_ptr_op(con->cert, OP_EQ, NULL);
   4330  // tt_assert(con->consensus_method >= MIN_METHOD_TO_CLIP_UNMEASURED_BW_KB);
   4331  tt_int_op(con->consensus_method, OP_GE, 16);
   4332  tt_int_op(4,OP_EQ, smartlist_len(con->routerstatus_list));
   4333  /* There should be four listed routers; all voters saw the same in this */
   4334 
   4335 done:
   4336  return;
   4337 }
   4338 
   4339 /**
   4340 * Test a router list entry for umbw test
   4341 */
   4342 static void
   4343 test_routerstatus_for_umbw(routerstatus_t *rs, time_t now)
   4344 {
   4345  (void)now;
   4346  tor_addr_t addr_ipv6;
   4347  uint32_t max_unmeasured_bw_kb = (alternate_clip_bw > 0) ?
   4348    alternate_clip_bw : DEFAULT_MAX_UNMEASURED_BW_KB;
   4349 
   4350  tt_assert(rs);
   4351 
   4352  /* There should be four listed routers, as constructed above */
   4353  if (tor_memeq(rs->identity_digest,
   4354                "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
   4355                "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
   4356                DIGEST_LEN)) {
   4357    tt_mem_op(rs->identity_digest,OP_EQ,
   4358               "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3"
   4359               "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
   4360               DIGEST_LEN);
   4361    tt_mem_op(rs->descriptor_digest,OP_EQ, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
   4362    tt_assert(!rs->is_authority);
   4363    tt_assert(!rs->is_exit);
   4364    tt_assert(!rs->is_fast);
   4365    tt_assert(!rs->is_possible_guard);
   4366    tt_assert(!rs->is_stable);
   4367    /* (If it wasn't running and valid it wouldn't be here) */
   4368    tt_assert(rs->is_flagged_running);
   4369    tt_assert(rs->is_valid);
   4370    tt_assert(!rs->is_named);
   4371    /* This one should have measured bandwidth below the clip cutoff */
   4372    tt_assert(rs->has_bandwidth);
   4373    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
   4374    tt_assert(!(rs->bw_is_unmeasured));
   4375  } else if (tor_memeq(rs->identity_digest,
   4376                       "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
   4377                       "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
   4378                       DIGEST_LEN)) {
   4379    /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'.  */
   4380    tt_mem_op(rs->identity_digest,OP_EQ,
   4381               "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5"
   4382               "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
   4383               DIGEST_LEN);
   4384    tt_str_op(rs->nickname,OP_EQ, "router1");
   4385    tt_mem_op(rs->descriptor_digest,OP_EQ, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
   4386    tt_assert(tor_addr_eq_ipv4h(&rs->ipv4_addr, 0x99009901));
   4387    tt_int_op(rs->ipv4_orport,OP_EQ, 443);
   4388    tt_int_op(rs->ipv4_dirport,OP_EQ, 0);
   4389    tor_addr_parse(&addr_ipv6, "[1:2:3::4]");
   4390    tt_assert(tor_addr_eq(&rs->ipv6_addr, &addr_ipv6));
   4391    tt_int_op(rs->ipv6_orport,OP_EQ, 4711);
   4392    tt_assert(!rs->is_authority);
   4393    tt_assert(rs->is_exit);
   4394    tt_assert(rs->is_fast);
   4395    tt_assert(rs->is_possible_guard);
   4396    tt_assert(rs->is_stable);
   4397    tt_assert(rs->is_flagged_running);
   4398    tt_assert(rs->is_valid);
   4399    tt_assert(!rs->is_named);
   4400    /* This one should have measured bandwidth above the clip cutoff */
   4401    tt_assert(rs->has_bandwidth);
   4402    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb * 2);
   4403    tt_assert(!(rs->bw_is_unmeasured));
   4404  } else if (tor_memeq(rs->identity_digest,
   4405                "\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33"
   4406                "\x33\x33\x33\x33\x33\x33\x33\x33\x33\x33",
   4407                DIGEST_LEN)) {
   4408    /*
   4409     * This one should have unmeasured bandwidth above the clip cutoff,
   4410     * and so should be clipped
   4411     */
   4412    tt_assert(rs->has_bandwidth);
   4413    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb);
   4414    tt_assert(rs->bw_is_unmeasured);
   4415  } else if (tor_memeq(rs->identity_digest,
   4416                "\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34"
   4417                "\x34\x34\x34\x34\x34\x34\x34\x34\x34\x34",
   4418                DIGEST_LEN)) {
   4419    /*
   4420     * This one should have unmeasured bandwidth below the clip cutoff,
   4421     * and so should not be clipped
   4422     */
   4423    tt_assert(rs->has_bandwidth);
   4424    tt_int_op(rs->bandwidth_kb,OP_EQ, max_unmeasured_bw_kb / 2);
   4425    tt_assert(rs->bw_is_unmeasured);
   4426  } else {
   4427    /* Weren't expecting this... */
   4428    tt_abort();
   4429  }
   4430 
   4431 done:
   4432  return;
   4433 }
   4434 
   4435 /**
   4436 * Compute a consensus involving clipping unmeasured bandwidth with consensus
   4437 * method 17; this uses the same test_a_networkstatus() function that the
   4438 * v3_networkstatus test uses.
   4439 */
   4440 
   4441 static void
   4442 test_dir_clip_unmeasured_bw_kb(void *arg)
   4443 {
   4444  /* Run the test with the default clip bandwidth */
   4445  (void)arg;
   4446  alternate_clip_bw = 0;
   4447  test_a_networkstatus(gen_routerstatus_for_umbw,
   4448                       vote_tweaks_for_umbw,
   4449                       test_vrs_for_umbw,
   4450                       test_consensus_for_umbw,
   4451                       test_routerstatus_for_umbw);
   4452 }
   4453 
   4454 /**
   4455 * This version of test_dir_clip_unmeasured_bw_kb() uses a non-default choice
   4456 * of clip bandwidth.
   4457 */
   4458 
   4459 static void
   4460 test_dir_clip_unmeasured_bw_kb_alt(void *arg)
   4461 {
   4462  /*
   4463   * Try a different one; this value is chosen so that the below-the-cutoff
   4464   * unmeasured nodes the test uses, at alternate_clip_bw / 2, will be above
   4465   * DEFAULT_MAX_UNMEASURED_BW_KB and if the consensus incorrectly uses that
   4466   * cutoff it will fail the test.
   4467   */
   4468  (void)arg;
   4469  alternate_clip_bw = 3 * DEFAULT_MAX_UNMEASURED_BW_KB;
   4470  test_a_networkstatus(gen_routerstatus_for_umbw,
   4471                       vote_tweaks_for_umbw,
   4472                       test_vrs_for_umbw,
   4473                       test_consensus_for_umbw,
   4474                       test_routerstatus_for_umbw);
   4475 }
   4476 
   4477 static void
   4478 test_dir_fmt_control_ns(void *arg)
   4479 {
   4480  char *s = NULL;
   4481  routerstatus_t rs;
   4482  (void)arg;
   4483 
   4484  memset(&rs, 0, sizeof(rs));
   4485  strlcpy(rs.nickname, "TetsuoMilk", sizeof(rs.nickname));
   4486  memcpy(rs.identity_digest, "Stately, plump Buck ", DIGEST_LEN);
   4487  memcpy(rs.descriptor_digest, "Mulligan came up fro", DIGEST_LEN);
   4488  tor_addr_from_ipv4h(&rs.ipv4_addr, 0x20304050);
   4489  rs.ipv4_orport = 9001;
   4490  rs.ipv4_dirport = 9002;
   4491  rs.is_exit = 1;
   4492  rs.is_fast = 1;
   4493  rs.is_flagged_running = 1;
   4494  rs.has_bandwidth = 1;
   4495  rs.is_v2_dir = 1;
   4496  rs.bandwidth_kb = 1000;
   4497 
   4498  s = networkstatus_getinfo_helper_single(&rs);
   4499  tt_assert(s);
   4500  tt_str_op(s, OP_EQ,
   4501            "r TetsuoMilk U3RhdGVseSwgcGx1bXAgQnVjayA "
   4502               "TXVsbGlnYW4gY2FtZSB1cCBmcm8 2038-01-01 00:00:00 "
   4503               "32.48.64.80 9001 9002\n"
   4504            "s Exit Fast Running V2Dir\n"
   4505            "w Bandwidth=1000\n");
   4506 
   4507 done:
   4508  tor_free(s);
   4509 }
   4510 
   4511 static int mock_get_options_calls = 0;
   4512 static or_options_t *mock_options = NULL;
   4513 
   4514 static void
   4515 reset_options(or_options_t *options, int *get_options_calls)
   4516 {
   4517  memset(options, 0, sizeof(or_options_t));
   4518  options->TestingTorNetwork = 1;
   4519 
   4520  *get_options_calls = 0;
   4521 }
   4522 
   4523 static const or_options_t *
   4524 mock_get_options(void)
   4525 {
   4526  ++mock_get_options_calls;
   4527  tor_assert(mock_options);
   4528  return mock_options;
   4529 }
   4530 
   4531 /**
   4532 * Test dirauth_get_b64_digest_bw_file.
   4533 * This function should be near the other bwauth functions, but it needs
   4534 * mock_get_options, that is only defined here.
   4535 */
   4536 
   4537 static void
   4538 test_dir_bwauth_bw_file_digest256(void *arg)
   4539 {
   4540  (void)arg;
   4541  const char *content =
   4542    "1541171221\n"
   4543    "node_id=$68A483E05A2ABDCA6DA5A3EF8DB5177638A27F80 "
   4544    "master_key_ed25519=YaqV4vbvPYKucElk297eVdNArDz9HtIwUoIeo0+cVIpQ "
   4545    "bw=760 nick=Test time=2018-05-08T16:13:26\n";
   4546 
   4547  char *fname = tor_strdup(get_fname("V3BandwidthsFile"));
   4548  /* Initialize to a wrong digest. */
   4549  NONSTRING
   4550    uint8_t digest[DIGEST256_LEN] = "01234567890123456789abcdefghijkl";
   4551 
   4552  /* Digest of an empty string. Initialize to a wrong digest. */
   4553  NONSTRING
   4554    char digest_empty_str[DIGEST256_LEN] = "01234567890123456789abcdefghijkl";
   4555  crypto_digest256(digest_empty_str, "", 0, DIGEST_SHA256);
   4556 
   4557  /* Digest of the content. Initialize to a wrong digest. */
   4558  NONSTRING
   4559    char digest_expected[DIGEST256_LEN] = "01234567890123456789abcdefghijkl";
   4560  crypto_digest256(digest_expected, content, strlen(content), DIGEST_SHA256);
   4561 
   4562  /* When the bandwidth file can not be found. */
   4563  tt_int_op(-1, OP_EQ,
   4564            dirserv_read_measured_bandwidths(fname,
   4565                                             NULL, NULL, digest));
   4566  tt_mem_op(digest, OP_EQ, digest_empty_str, DIGEST256_LEN);
   4567 
   4568  /* When there is a timestamp but it is too old. */
   4569  write_str_to_file(fname, content, 0);
   4570  tt_int_op(-1, OP_EQ,
   4571            dirserv_read_measured_bandwidths(fname,
   4572                                             NULL, NULL, digest));
   4573  /* The digest will be correct. */
   4574  tt_mem_op(digest, OP_EQ, digest_expected, DIGEST256_LEN);
   4575 
   4576  update_approx_time(1541171221);
   4577 
   4578  /* When there is a bandwidth file and it can be read. */
   4579  tt_int_op(0, OP_EQ,
   4580            dirserv_read_measured_bandwidths(fname,
   4581                                             NULL, NULL, digest));
   4582  tt_mem_op(digest, OP_EQ, digest_expected, DIGEST256_LEN);
   4583 
   4584 done:
   4585  unlink(fname);
   4586  tor_free(fname);
   4587  update_approx_time(time(NULL));
   4588 }
   4589 
   4590 static void
   4591 reset_routerstatus(routerstatus_t *rs,
   4592                   const char *hex_identity_digest,
   4593                   uint32_t ipv4_addr)
   4594 {
   4595  memset(rs, 0, sizeof(routerstatus_t));
   4596  base16_decode(rs->identity_digest, sizeof(rs->identity_digest),
   4597                hex_identity_digest, HEX_DIGEST_LEN);
   4598  /* A zero address matches everything, so the address needs to be set.
   4599   * But the specific value is irrelevant. */
   4600  tor_addr_from_ipv4h(&rs->ipv4_addr, ipv4_addr);
   4601 }
   4602 
   4603 #define ROUTER_A_ID_STR    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
   4604 #define ROUTER_A_IPV4      0xAA008801
   4605 #define ROUTER_B_ID_STR    "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
   4606 #define ROUTER_B_IPV4      0xBB008801
   4607 
   4608 #define ROUTERSET_ALL_STR  "*"
   4609 #define ROUTERSET_A_STR    ROUTER_A_ID_STR
   4610 #define ROUTERSET_NONE_STR ""
   4611 
   4612 /*
   4613 * Test that dirserv_set_routerstatus_testing sets router flags correctly
   4614 * Using "*"  sets flags on A and B
   4615 * Using "A"  sets flags on A
   4616 * Using ""   sets flags on Neither
   4617 * If the router is not included:
   4618 *   - if *Strict is set, the flag is set to 0,
   4619 *   - otherwise, the flag is not modified. */
   4620 static void
   4621 test_dir_dirserv_set_routerstatus_testing(void *arg)
   4622 {
   4623  (void)arg;
   4624 
   4625  /* Init options */
   4626  dirauth_options_t *dirauth_options =
   4627    tor_malloc_zero(sizeof(dirauth_options_t));
   4628 
   4629  mock_options = tor_malloc(sizeof(or_options_t));
   4630  reset_options(mock_options, &mock_get_options_calls);
   4631  MOCK(get_options, mock_get_options);
   4632  dirauth_set_options(dirauth_options);
   4633 
   4634  /* Init routersets */
   4635  routerset_t *routerset_all  = routerset_new();
   4636  routerset_parse(routerset_all,  ROUTERSET_ALL_STR,  "All routers");
   4637 
   4638  routerset_t *routerset_a    = routerset_new();
   4639  routerset_parse(routerset_a,    ROUTERSET_A_STR,    "Router A only");
   4640 
   4641  routerset_t *routerset_none = routerset_new();
   4642  /* Routersets are empty when provided by routerset_new(),
   4643   * so this is not strictly necessary */
   4644  routerset_parse(routerset_none, ROUTERSET_NONE_STR, "No routers");
   4645 
   4646  /* Init routerstatuses */
   4647  routerstatus_t *rs_a = tor_malloc(sizeof(routerstatus_t));
   4648  reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
   4649 
   4650  routerstatus_t *rs_b = tor_malloc(sizeof(routerstatus_t));
   4651  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4652 
   4653  /* Sanity check that routersets correspond to routerstatuses.
   4654   * Return values are {2, 3, 4} */
   4655 
   4656  /* We want 3 ("*" means match all addresses) */
   4657  tt_int_op(routerset_contains_routerstatus(routerset_all, rs_a, 0), OP_EQ, 3);
   4658  tt_int_op(routerset_contains_routerstatus(routerset_all, rs_b, 0), OP_EQ, 3);
   4659 
   4660  /* We want 4 (match id_digest [or nickname]) */
   4661  tt_int_op(routerset_contains_routerstatus(routerset_a, rs_a, 0), OP_EQ, 4);
   4662  tt_int_op(routerset_contains_routerstatus(routerset_a, rs_b, 0), OP_EQ, 0);
   4663 
   4664  tt_int_op(routerset_contains_routerstatus(routerset_none, rs_a, 0), OP_EQ,
   4665            0);
   4666  tt_int_op(routerset_contains_routerstatus(routerset_none, rs_b, 0), OP_EQ,
   4667            0);
   4668 
   4669  /* Check that "*" sets flags on all routers: Exit
   4670   * Check the flags aren't being confused with each other */
   4671  reset_options(mock_options, &mock_get_options_calls);
   4672  memset(dirauth_options, 0, sizeof(*dirauth_options));
   4673  reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
   4674  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4675 
   4676  dirauth_options->TestingDirAuthVoteExit = routerset_all;
   4677  dirauth_options->TestingDirAuthVoteExitIsStrict = 0;
   4678 
   4679  dirserv_set_routerstatus_testing(rs_a);
   4680  dirserv_set_routerstatus_testing(rs_b);
   4681 
   4682  tt_uint_op(rs_a->is_exit, OP_EQ, 1);
   4683  tt_uint_op(rs_b->is_exit, OP_EQ, 1);
   4684  /* Be paranoid - check no other flags are set */
   4685  tt_uint_op(rs_a->is_possible_guard, OP_EQ, 0);
   4686  tt_uint_op(rs_b->is_possible_guard, OP_EQ, 0);
   4687  tt_uint_op(rs_a->is_hs_dir, OP_EQ, 0);
   4688  tt_uint_op(rs_b->is_hs_dir, OP_EQ, 0);
   4689 
   4690  /* Check that "*" sets flags on all routers: Guard & HSDir
   4691   * Cover the remaining flags in one test */
   4692  reset_options(mock_options, &mock_get_options_calls);
   4693  memset(dirauth_options, 0, sizeof(*dirauth_options));
   4694  reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
   4695  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4696 
   4697  dirauth_options->TestingDirAuthVoteGuard = routerset_all;
   4698  dirauth_options->TestingDirAuthVoteGuardIsStrict = 0;
   4699  dirauth_options->TestingDirAuthVoteHSDir = routerset_all;
   4700  dirauth_options->TestingDirAuthVoteHSDirIsStrict = 0;
   4701 
   4702  dirserv_set_routerstatus_testing(rs_a);
   4703  dirserv_set_routerstatus_testing(rs_b);
   4704 
   4705  tt_uint_op(rs_a->is_possible_guard, OP_EQ, 1);
   4706  tt_uint_op(rs_b->is_possible_guard, OP_EQ, 1);
   4707  tt_uint_op(rs_a->is_hs_dir, OP_EQ, 1);
   4708  tt_uint_op(rs_b->is_hs_dir, OP_EQ, 1);
   4709  /* Be paranoid - check exit isn't set */
   4710  tt_uint_op(rs_a->is_exit, OP_EQ, 0);
   4711  tt_uint_op(rs_b->is_exit, OP_EQ, 0);
   4712 
   4713  /* Check routerset A sets all flags on router A,
   4714   * but leaves router B unmodified */
   4715  reset_options(mock_options, &mock_get_options_calls);
   4716  memset(dirauth_options, 0, sizeof(*dirauth_options));
   4717  reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
   4718  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4719 
   4720  dirauth_options->TestingDirAuthVoteExit = routerset_a;
   4721  dirauth_options->TestingDirAuthVoteExitIsStrict = 0;
   4722  dirauth_options->TestingDirAuthVoteGuard = routerset_a;
   4723  dirauth_options->TestingDirAuthVoteGuardIsStrict = 0;
   4724  dirauth_options->TestingDirAuthVoteHSDir = routerset_a;
   4725  dirauth_options->TestingDirAuthVoteHSDirIsStrict = 0;
   4726 
   4727  dirserv_set_routerstatus_testing(rs_a);
   4728  dirserv_set_routerstatus_testing(rs_b);
   4729 
   4730  tt_uint_op(rs_a->is_exit, OP_EQ, 1);
   4731  tt_uint_op(rs_b->is_exit, OP_EQ, 0);
   4732  tt_uint_op(rs_a->is_possible_guard, OP_EQ, 1);
   4733  tt_uint_op(rs_b->is_possible_guard, OP_EQ, 0);
   4734  tt_uint_op(rs_a->is_hs_dir, OP_EQ, 1);
   4735  tt_uint_op(rs_b->is_hs_dir, OP_EQ, 0);
   4736 
   4737  /* Check routerset A unsets all flags on router B when Strict is set */
   4738  reset_options(mock_options, &mock_get_options_calls);
   4739  memset(dirauth_options, 0, sizeof(*dirauth_options));
   4740  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4741 
   4742  dirauth_options->TestingDirAuthVoteExit = routerset_a;
   4743  dirauth_options->TestingDirAuthVoteExitIsStrict = 1;
   4744  dirauth_options->TestingDirAuthVoteGuard = routerset_a;
   4745  dirauth_options->TestingDirAuthVoteGuardIsStrict = 1;
   4746  dirauth_options->TestingDirAuthVoteHSDir = routerset_a;
   4747  dirauth_options->TestingDirAuthVoteHSDirIsStrict = 1;
   4748 
   4749  rs_b->is_exit = 1;
   4750  rs_b->is_possible_guard = 1;
   4751  rs_b->is_hs_dir = 1;
   4752 
   4753  dirserv_set_routerstatus_testing(rs_b);
   4754 
   4755  tt_uint_op(rs_b->is_exit, OP_EQ, 0);
   4756  tt_uint_op(rs_b->is_possible_guard, OP_EQ, 0);
   4757  tt_uint_op(rs_b->is_hs_dir, OP_EQ, 0);
   4758 
   4759  /* Check routerset A doesn't modify flags on router B without Strict set */
   4760  reset_options(mock_options, &mock_get_options_calls);
   4761  memset(dirauth_options, 0, sizeof(*dirauth_options));
   4762  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4763 
   4764  dirauth_options->TestingDirAuthVoteExit = routerset_a;
   4765  dirauth_options->TestingDirAuthVoteExitIsStrict = 0;
   4766  dirauth_options->TestingDirAuthVoteGuard = routerset_a;
   4767  dirauth_options->TestingDirAuthVoteGuardIsStrict = 0;
   4768  dirauth_options->TestingDirAuthVoteHSDir = routerset_a;
   4769  dirauth_options->TestingDirAuthVoteHSDirIsStrict = 0;
   4770 
   4771  rs_b->is_exit = 1;
   4772  rs_b->is_possible_guard = 1;
   4773  rs_b->is_hs_dir = 1;
   4774 
   4775  dirserv_set_routerstatus_testing(rs_b);
   4776 
   4777  tt_uint_op(rs_b->is_exit, OP_EQ, 1);
   4778  tt_uint_op(rs_b->is_possible_guard, OP_EQ, 1);
   4779  tt_uint_op(rs_b->is_hs_dir, OP_EQ, 1);
   4780 
   4781  /* Check the empty routerset zeroes all flags
   4782   * on routers A & B with Strict set */
   4783  reset_options(mock_options, &mock_get_options_calls);
   4784  memset(dirauth_options, 0, sizeof(*dirauth_options));
   4785  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4786 
   4787  dirauth_options->TestingDirAuthVoteExit = routerset_none;
   4788  dirauth_options->TestingDirAuthVoteExitIsStrict = 1;
   4789  dirauth_options->TestingDirAuthVoteGuard = routerset_none;
   4790  dirauth_options->TestingDirAuthVoteGuardIsStrict = 1;
   4791  dirauth_options->TestingDirAuthVoteHSDir = routerset_none;
   4792  dirauth_options->TestingDirAuthVoteHSDirIsStrict = 1;
   4793 
   4794  rs_b->is_exit = 1;
   4795  rs_b->is_possible_guard = 1;
   4796  rs_b->is_hs_dir = 1;
   4797 
   4798  dirserv_set_routerstatus_testing(rs_b);
   4799 
   4800  tt_uint_op(rs_b->is_exit, OP_EQ, 0);
   4801  tt_uint_op(rs_b->is_possible_guard, OP_EQ, 0);
   4802  tt_uint_op(rs_b->is_hs_dir, OP_EQ, 0);
   4803 
   4804  /* Check the empty routerset doesn't modify any flags
   4805   * on A or B without Strict set */
   4806  reset_options(mock_options, &mock_get_options_calls);
   4807  memset(dirauth_options, 0, sizeof(*dirauth_options));
   4808  reset_routerstatus(rs_a, ROUTER_A_ID_STR, ROUTER_A_IPV4);
   4809  reset_routerstatus(rs_b, ROUTER_B_ID_STR, ROUTER_B_IPV4);
   4810 
   4811  dirauth_options->TestingDirAuthVoteExit = routerset_none;
   4812  dirauth_options->TestingDirAuthVoteExitIsStrict = 0;
   4813  dirauth_options->TestingDirAuthVoteGuard = routerset_none;
   4814  dirauth_options->TestingDirAuthVoteGuardIsStrict = 0;
   4815  dirauth_options->TestingDirAuthVoteHSDir = routerset_none;
   4816  dirauth_options->TestingDirAuthVoteHSDirIsStrict = 0;
   4817 
   4818  rs_b->is_exit = 1;
   4819  rs_b->is_possible_guard = 1;
   4820  rs_b->is_hs_dir = 1;
   4821 
   4822  dirserv_set_routerstatus_testing(rs_a);
   4823  dirserv_set_routerstatus_testing(rs_b);
   4824 
   4825  tt_uint_op(rs_a->is_exit, OP_EQ, 0);
   4826  tt_uint_op(rs_a->is_possible_guard, OP_EQ, 0);
   4827  tt_uint_op(rs_a->is_hs_dir, OP_EQ, 0);
   4828  tt_uint_op(rs_b->is_exit, OP_EQ, 1);
   4829  tt_uint_op(rs_b->is_possible_guard, OP_EQ, 1);
   4830  tt_uint_op(rs_b->is_hs_dir, OP_EQ, 1);
   4831 
   4832 done:
   4833  tor_free(mock_options);
   4834  tor_free(dirauth_options);
   4835  mock_options = NULL;
   4836 
   4837  UNMOCK(get_options);
   4838 
   4839  routerset_free(routerset_all);
   4840  routerset_free(routerset_a);
   4841  routerset_free(routerset_none);
   4842 
   4843  tor_free(rs_a);
   4844  tor_free(rs_b);
   4845 }
   4846 
   4847 static void
   4848 test_dir_http_handling(void *args)
   4849 {
   4850  char *url = NULL;
   4851  (void)args;
   4852 
   4853  /* Parse http url tests: */
   4854  /* Good headers */
   4855  tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1\r\n"
   4856                           "Host: example.com\r\n"
   4857                           "User-Agent: Mozilla/5.0 (Windows;"
   4858                           " U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
   4859                           &url),OP_EQ, 0);
   4860  tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
   4861  tor_free(url);
   4862 
   4863  tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.0\r\n", &url),OP_EQ, 0);
   4864  tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
   4865  tor_free(url);
   4866 
   4867  tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.600\r\n", &url),
   4868            OP_EQ, 0);
   4869  tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
   4870  tor_free(url);
   4871 
   4872  /* Should prepend '/tor/' to url if required */
   4873  tt_int_op(parse_http_url("GET /a/b/c.txt HTTP/1.1\r\n"
   4874                           "Host: example.com\r\n"
   4875                           "User-Agent: Mozilla/5.0 (Windows;"
   4876                           " U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
   4877                           &url),OP_EQ, 0);
   4878  tt_str_op(url,OP_EQ, "/tor/a/b/c.txt");
   4879  tor_free(url);
   4880 
   4881  /* Bad headers -- no HTTP/1.x*/
   4882  tt_int_op(parse_http_url("GET /a/b/c.txt\r\n"
   4883                           "Host: example.com\r\n"
   4884                           "User-Agent: Mozilla/5.0 (Windows;"
   4885                           " U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
   4886                           &url),OP_EQ, -1);
   4887  tt_ptr_op(url, OP_EQ, NULL);
   4888 
   4889  /* Bad headers */
   4890  tt_int_op(parse_http_url("GET /a/b/c.txt\r\n"
   4891                           "Host: example.com\r\n"
   4892                           "User-Agent: Mozilla/5.0 (Windows;"
   4893                           " U; Windows NT 6.1; en-US; rv:1.9.1.5)\r\n",
   4894                           &url),OP_EQ, -1);
   4895  tt_ptr_op(url, OP_EQ, NULL);
   4896 
   4897  tt_int_op(parse_http_url("GET /tor/a/b/c.txt", &url),OP_EQ, -1);
   4898  tt_ptr_op(url, OP_EQ, NULL);
   4899 
   4900  tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1", &url),OP_EQ, -1);
   4901  tt_ptr_op(url, OP_EQ, NULL);
   4902 
   4903  tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.1x\r\n", &url),
   4904            OP_EQ, -1);
   4905  tt_ptr_op(url, OP_EQ, NULL);
   4906 
   4907  tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.", &url),OP_EQ, -1);
   4908  tt_ptr_op(url, OP_EQ, NULL);
   4909 
   4910  tt_int_op(parse_http_url("GET /tor/a/b/c.txt HTTP/1.\r", &url),OP_EQ, -1);
   4911  tt_ptr_op(url, OP_EQ, NULL);
   4912 
   4913 done:
   4914  tor_free(url);
   4915 }
   4916 
   4917 static void
   4918 test_dir_purpose_needs_anonymity_returns_true_by_default(void *arg)
   4919 {
   4920  (void)arg;
   4921 
   4922 #ifdef ALL_BUGS_ARE_FATAL
   4923  /* Coverity (and maybe clang analyser) complain that the code following
   4924   * tt_skip() is unconditionally unreachable. */
   4925 #if !defined(__COVERITY__) && !defined(__clang_analyzer__)
   4926  tt_skip();
   4927 #endif
   4928 #endif /* defined(ALL_BUGS_ARE_FATAL) */
   4929 
   4930  tor_capture_bugs_(1);
   4931  setup_full_capture_of_logs(LOG_WARN);
   4932  tt_int_op(1, OP_EQ, purpose_needs_anonymity(0, 0, NULL));
   4933  tt_int_op(1, OP_EQ, smartlist_len(tor_get_captured_bug_log_()));
   4934  expect_single_log_msg_containing("Called with dir_purpose=0");
   4935 
   4936  tor_end_capture_bugs_();
   4937 done:
   4938  tor_end_capture_bugs_();
   4939  teardown_capture_of_logs();
   4940 }
   4941 
   4942 static void
   4943 test_dir_purpose_needs_anonymity_returns_true_for_bridges(void *arg)
   4944 {
   4945  (void)arg;
   4946 
   4947  tt_int_op(1, OP_EQ, purpose_needs_anonymity(0, ROUTER_PURPOSE_BRIDGE, NULL));
   4948  tt_int_op(1, OP_EQ, purpose_needs_anonymity(0, ROUTER_PURPOSE_BRIDGE,
   4949                                           "foobar"));
   4950 done: ;
   4951 }
   4952 
   4953 static void
   4954 test_dir_purpose_needs_anonymity_returns_false_for_own_bridge_desc(void *arg)
   4955 {
   4956  (void)arg;
   4957  tt_int_op(0, OP_EQ, purpose_needs_anonymity(DIR_PURPOSE_FETCH_SERVERDESC,
   4958                                           ROUTER_PURPOSE_BRIDGE,
   4959                                           "authority.z"));
   4960 done: ;
   4961 }
   4962 
   4963 static void
   4964 test_dir_purpose_needs_anonymity_ret_false_for_non_sensitive_conn(void *arg)
   4965 {
   4966  (void)arg;
   4967 
   4968  tt_int_op(0, OP_EQ, purpose_needs_anonymity(DIR_PURPOSE_UPLOAD_DIR,
   4969                                           ROUTER_PURPOSE_GENERAL, NULL));
   4970  tt_int_op(0, OP_EQ,
   4971            purpose_needs_anonymity(DIR_PURPOSE_UPLOAD_VOTE, 0, NULL));
   4972  tt_int_op(0, OP_EQ,
   4973            purpose_needs_anonymity(DIR_PURPOSE_UPLOAD_SIGNATURES, 0, NULL));
   4974  tt_int_op(0, OP_EQ,
   4975            purpose_needs_anonymity(DIR_PURPOSE_FETCH_STATUS_VOTE, 0, NULL));
   4976  tt_int_op(0, OP_EQ, purpose_needs_anonymity(
   4977                    DIR_PURPOSE_FETCH_DETACHED_SIGNATURES, 0, NULL));
   4978  tt_int_op(0, OP_EQ,
   4979            purpose_needs_anonymity(DIR_PURPOSE_FETCH_CONSENSUS, 0, NULL));
   4980  tt_int_op(0, OP_EQ,
   4981            purpose_needs_anonymity(DIR_PURPOSE_FETCH_CERTIFICATE, 0, NULL));
   4982  tt_int_op(0, OP_EQ,
   4983            purpose_needs_anonymity(DIR_PURPOSE_FETCH_SERVERDESC, 0, NULL));
   4984  tt_int_op(0, OP_EQ,
   4985            purpose_needs_anonymity(DIR_PURPOSE_FETCH_EXTRAINFO, 0, NULL));
   4986  tt_int_op(0, OP_EQ,
   4987            purpose_needs_anonymity(DIR_PURPOSE_FETCH_MICRODESC, 0, NULL));
   4988  done: ;
   4989 }
   4990 
   4991 static void
   4992 test_dir_fetch_type(void *arg)
   4993 {
   4994  (void)arg;
   4995 
   4996  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_EXTRAINFO, ROUTER_PURPOSE_BRIDGE,
   4997                           NULL), OP_EQ, EXTRAINFO_DIRINFO | BRIDGE_DIRINFO);
   4998  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_EXTRAINFO, ROUTER_PURPOSE_GENERAL,
   4999                           NULL), OP_EQ, EXTRAINFO_DIRINFO | V3_DIRINFO);
   5000 
   5001  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_SERVERDESC, ROUTER_PURPOSE_BRIDGE,
   5002                           NULL), OP_EQ, BRIDGE_DIRINFO);
   5003  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_SERVERDESC,
   5004                           ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
   5005 
   5006  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_STATUS_VOTE,
   5007                           ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
   5008  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
   5009                           ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
   5010  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_CERTIFICATE,
   5011                           ROUTER_PURPOSE_GENERAL, NULL), OP_EQ, V3_DIRINFO);
   5012 
   5013  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_CONSENSUS, ROUTER_PURPOSE_GENERAL,
   5014                           "microdesc"), OP_EQ, V3_DIRINFO|MICRODESC_DIRINFO);
   5015  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_CONSENSUS, ROUTER_PURPOSE_GENERAL,
   5016                           NULL), OP_EQ, V3_DIRINFO);
   5017 
   5018  tt_int_op(dir_fetch_type(DIR_PURPOSE_FETCH_MICRODESC, ROUTER_PURPOSE_GENERAL,
   5019                           NULL), OP_EQ, MICRODESC_DIRINFO);
   5020 
   5021 done:
   5022  teardown_capture_of_logs();
   5023 }
   5024 
   5025 static void
   5026 test_dir_packages(void *arg)
   5027 {
   5028  smartlist_t *votes = smartlist_new();
   5029  char *res = NULL;
   5030  (void)arg;
   5031 
   5032 #define BAD(s) \
   5033  tt_int_op(0, OP_EQ, validate_recommended_package_line(s));
   5034 #define GOOD(s) \
   5035  tt_int_op(1, OP_EQ, validate_recommended_package_line(s));
   5036  GOOD("tor 0.2.6.3-alpha "
   5037       "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
   5038       "sha256=sssdlkfjdsklfjdskfljasdklfj");
   5039  GOOD("tor 0.2.6.3-alpha "
   5040       "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
   5041       "sha256=sssdlkfjdsklfjdskfljasdklfj blake2b=fred");
   5042  BAD("tor 0.2.6.3-alpha "
   5043       "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
   5044       "sha256=sssdlkfjdsklfjdskfljasdklfj=");
   5045  BAD("tor 0.2.6.3-alpha "
   5046       "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz "
   5047       "sha256=sssdlkfjdsklfjdskfljasdklfj blake2b");
   5048  BAD("tor 0.2.6.3-alpha "
   5049       "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz ");
   5050  BAD("tor 0.2.6.3-alpha "
   5051       "http://torproject.example.com/dist/tor-0.2.6.3-alpha.tar.gz");
   5052  BAD("tor 0.2.6.3-alpha ");
   5053  BAD("tor 0.2.6.3-alpha");
   5054  BAD("tor ");
   5055  BAD("tor");
   5056  BAD("");
   5057  BAD("=foobar sha256="
   5058      "3c179f46ca77069a6a0bac70212a9b3b838b2f66129cb52d568837fc79d8fcc7");
   5059  BAD("= = sha256="
   5060      "3c179f46ca77069a6a0bac70212a9b3b838b2f66129cb52d568837fc79d8fcc7");
   5061 
   5062  BAD("sha512= sha256="
   5063      "3c179f46ca77069a6a0bac70212a9b3b838b2f66129cb52d568837fc79d8fcc7");
   5064 
   5065  smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
   5066  smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
   5067  smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
   5068  smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
   5069  smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
   5070  smartlist_add(votes, tor_malloc_zero(sizeof(networkstatus_t)));
   5071  SMARTLIST_FOREACH(votes, networkstatus_t *, ns,
   5072                    ns->package_lines = smartlist_new());
   5073 
   5074 #define ADD(i, s)                                                       \
   5075  smartlist_add(((networkstatus_t*)smartlist_get(votes, (i)))->package_lines, \
   5076                (void*)(s));
   5077 
   5078  /* Only one vote for this one. */
   5079  ADD(4, "cisco 99z http://foobar.example.com/ sha256=blahblah");
   5080 
   5081  /* Only two matching entries for this one, but 3 voters */
   5082  ADD(1, "mystic 99y http://barfoo.example.com/ sha256=blahblah");
   5083  ADD(3, "mystic 99y http://foobar.example.com/ sha256=blahblah");
   5084  ADD(4, "mystic 99y http://foobar.example.com/ sha256=blahblah");
   5085 
   5086  /* Only two matching entries for this one, but at least 4 voters */
   5087  ADD(1, "mystic 99p http://barfoo.example.com/ sha256=ggggggg");
   5088  ADD(3, "mystic 99p http://foobar.example.com/ sha256=blahblah");
   5089  ADD(4, "mystic 99p http://foobar.example.com/ sha256=blahblah");
   5090  ADD(5, "mystic 99p http://foobar.example.com/ sha256=ggggggg");
   5091 
   5092  /* This one has only invalid votes. */
   5093  ADD(0, "haffenreffer 1.2 http://foobar.example.com/ sha256");
   5094  ADD(1, "haffenreffer 1.2 http://foobar.example.com/ ");
   5095  ADD(2, "haffenreffer 1.2 ");
   5096  ADD(3, "haffenreffer ");
   5097  ADD(4, "haffenreffer");
   5098 
   5099  /* Three matching votes for this; it should actually go in! */
   5100  ADD(2, "element 0.66.1 http://quux.example.com/ sha256=abcdef");
   5101  ADD(3, "element 0.66.1 http://quux.example.com/ sha256=abcdef");
   5102  ADD(4, "element 0.66.1 http://quux.example.com/ sha256=abcdef");
   5103  ADD(1, "element 0.66.1 http://quum.example.com/ sha256=abcdef");
   5104  ADD(0, "element 0.66.1 http://quux.example.com/ sha256=abcde");
   5105 
   5106  /* Three votes for A, three votes for B */
   5107  ADD(0, "clownshoes 22alpha1 http://quumble.example.com/ blake2=foob");
   5108  ADD(1, "clownshoes 22alpha1 http://quumble.example.com/ blake2=foob");
   5109  ADD(2, "clownshoes 22alpha1 http://quumble.example.com/ blake2=foob");
   5110  ADD(3, "clownshoes 22alpha1 http://quumble.example.com/ blake2=fooz");
   5111  ADD(4, "clownshoes 22alpha1 http://quumble.example.com/ blake2=fooz");
   5112  ADD(5, "clownshoes 22alpha1 http://quumble.example.com/ blake2=fooz");
   5113 
   5114  /* Three votes for A, two votes for B */
   5115  ADD(1, "clownshoes 22alpha3 http://quumble.example.com/ blake2=foob");
   5116  ADD(2, "clownshoes 22alpha3 http://quumble.example.com/ blake2=foob");
   5117  ADD(3, "clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz");
   5118  ADD(4, "clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz");
   5119  ADD(5, "clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz");
   5120 
   5121  /* Four votes for A, two for B. */
   5122  ADD(0, "clownshoes 22alpha4 http://quumble.example.com/ blake2=foob");
   5123  ADD(1, "clownshoes 22alpha4 http://quumble.example.com/ blake2=foob");
   5124  ADD(2, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
   5125  ADD(3, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
   5126  ADD(4, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
   5127  ADD(5, "clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa");
   5128 
   5129  /* Five votes for A ... all from the same authority.  Three for B. */
   5130  ADD(0, "cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m");
   5131  ADD(1, "cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m");
   5132  ADD(3, "cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m");
   5133  ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
   5134  ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
   5135  ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
   5136  ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
   5137  ADD(2, "cbc 99.1.11.1.1 http://example.com/ cubehash=ahooy");
   5138 
   5139  /* As above but new replaces old: no two match. */
   5140  ADD(0, "cbc 99.1.11.1.2 http://example.com/cbc/ cubehash=ahooy sha512=m");
   5141  ADD(1, "cbc 99.1.11.1.2 http://example.com/cbc/ cubehash=ahooy sha512=m");
   5142  ADD(1, "cbc 99.1.11.1.2 http://example.com/cbc/x cubehash=ahooy sha512=m");
   5143  ADD(2, "cbc 99.1.11.1.2 http://example.com/cbc/ cubehash=ahooy sha512=m");
   5144  ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
   5145  ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
   5146  ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
   5147  ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
   5148  ADD(2, "cbc 99.1.11.1.2 http://example.com/ cubehash=ahooy");
   5149 
   5150  res = compute_consensus_package_lines(votes);
   5151  tt_assert(res);
   5152  tt_str_op(res, OP_EQ,
   5153    "package cbc 99.1.11.1.1 http://example.com/cbc/ cubehash=ahooy sha512=m\n"
   5154    "package clownshoes 22alpha3 http://quumble.example.com/ blake2=fooz\n"
   5155    "package clownshoes 22alpha4 http://quumble.example.cam/ blake2=fooa\n"
   5156    "package element 0.66.1 http://quux.example.com/ sha256=abcdef\n"
   5157    "package mystic 99y http://foobar.example.com/ sha256=blahblah\n"
   5158            );
   5159 
   5160 #undef ADD
   5161 #undef BAD
   5162 #undef GOOD
   5163 done:
   5164  SMARTLIST_FOREACH(votes, networkstatus_t *, ns,
   5165                    { smartlist_free(ns->package_lines); tor_free(ns); });
   5166  smartlist_free(votes);
   5167  tor_free(res);
   5168 }
   5169 
   5170 static void
   5171 download_status_random_backoff_helper(int min_delay)
   5172 {
   5173  download_status_t dls_random =
   5174    { 0, 0, 0, DL_SCHED_GENERIC, DL_WANT_AUTHORITY,
   5175               DL_SCHED_INCREMENT_FAILURE, 0, 0 };
   5176  int increment = -1;
   5177  int old_increment = -1;
   5178  time_t current_time = time(NULL);
   5179 
   5180  /* Check the random backoff cases */
   5181  int n_attempts = 0;
   5182  do {
   5183    increment = download_status_schedule_get_delay(&dls_random,
   5184                                                   min_delay,
   5185                                                   current_time);
   5186 
   5187    log_debug(LD_DIR, "Min: %d, Inc: %d, Old Inc: %d",
   5188              min_delay, increment, old_increment);
   5189 
   5190    /* Regression test for 20534 and friends
   5191     * increment must always increase after the first */
   5192    if (dls_random.last_backoff_position > 0) {
   5193      /* Always increment the exponential backoff */
   5194      tt_int_op(increment, OP_GE, 1);
   5195    }
   5196 
   5197    /* Test */
   5198    tt_int_op(increment, OP_GE, min_delay);
   5199 
   5200    /* Advance */
   5201    if (dls_random.n_download_attempts < IMPOSSIBLE_TO_DOWNLOAD - 1) {
   5202      ++(dls_random.n_download_attempts);
   5203      ++(dls_random.n_download_failures);
   5204    }
   5205 
   5206    /* Try another maybe */
   5207    old_increment = increment;
   5208  } while (++n_attempts < 1000);
   5209 
   5210 done:
   5211  return;
   5212 }
   5213 
   5214 static void
   5215 test_dir_download_status_random_backoff(void *arg)
   5216 {
   5217  (void)arg;
   5218 
   5219  /* Do a standard test */
   5220  download_status_random_backoff_helper(0);
   5221  /* regression tests for 17750: initial delay */
   5222  download_status_random_backoff_helper(10);
   5223  download_status_random_backoff_helper(20);
   5224 
   5225  /* Pathological cases */
   5226  download_status_random_backoff_helper(INT_MAX/2);
   5227 }
   5228 
   5229 static void
   5230 test_dir_download_status_random_backoff_ranges(void *arg)
   5231 {
   5232  (void)arg;
   5233  int lo, hi;
   5234  next_random_exponential_delay_range(&lo, &hi, 0, 10);
   5235  tt_int_op(lo, OP_EQ, 10);
   5236  tt_int_op(hi, OP_EQ, 11);
   5237 
   5238  next_random_exponential_delay_range(&lo, &hi, 6, 10);
   5239  tt_int_op(lo, OP_EQ, 10);
   5240  tt_int_op(hi, OP_EQ, 6*3);
   5241 
   5242  next_random_exponential_delay_range(&lo, &hi, 13, 10);
   5243  tt_int_op(lo, OP_EQ, 10);
   5244  tt_int_op(hi, OP_EQ, 13 * 3);
   5245 
   5246  next_random_exponential_delay_range(&lo, &hi, 37, 10);
   5247  tt_int_op(lo, OP_EQ, 10);
   5248  tt_int_op(hi, OP_EQ, 111);
   5249 
   5250  next_random_exponential_delay_range(&lo, &hi, 123, 10);
   5251  tt_int_op(lo, OP_EQ, 10);
   5252  tt_int_op(hi, OP_EQ, 369);
   5253 
   5254  next_random_exponential_delay_range(&lo, &hi, INT_MAX-5, 10);
   5255  tt_int_op(lo, OP_EQ, 10);
   5256  tt_int_op(hi, OP_EQ, INT_MAX);
   5257 done:
   5258  ;
   5259 }
   5260 
   5261 static void
   5262 test_dir_download_status_increment(void *arg)
   5263 {
   5264  (void)arg;
   5265  download_status_t dls_exp = { 0, 0, 0, DL_SCHED_GENERIC,
   5266    DL_WANT_ANY_DIRSERVER,
   5267    DL_SCHED_INCREMENT_ATTEMPT,
   5268    0, 0 };
   5269  or_options_t test_options;
   5270  time_t current_time = time(NULL);
   5271 
   5272  const int delay0 = 10;
   5273  const int no_delay = 0;
   5274  const int schedule = 10;
   5275  const int schedule_no_initial_delay = 0;
   5276 
   5277  /* Put it in the options */
   5278  mock_options = &test_options;
   5279  reset_options(mock_options, &mock_get_options_calls);
   5280  mock_options->TestingBridgeBootstrapDownloadInitialDelay = schedule;
   5281  mock_options->TestingClientDownloadInitialDelay = schedule;
   5282 
   5283  MOCK(get_options, mock_get_options);
   5284 
   5285  /* Check that the initial value of the schedule is the first value used,
   5286   * whether or not it was reset before being used */
   5287 
   5288  /* regression test for 17750: no initial delay */
   5289  mock_options->TestingClientDownloadInitialDelay = schedule_no_initial_delay;
   5290  mock_get_options_calls = 0;
   5291  /* we really want to test that it's equal to time(NULL) + delay0, but that's
   5292   * an unrealiable test, because time(NULL) might change. */
   5293 
   5294  /* regression test for 17750: exponential, no initial delay */
   5295  mock_options->TestingClientDownloadInitialDelay = schedule_no_initial_delay;
   5296  mock_get_options_calls = 0;
   5297  /* we really want to test that it's equal to time(NULL) + delay0, but that's
   5298   * an unrealiable test, because time(NULL) might change. */
   5299  tt_assert(download_status_get_next_attempt_at(&dls_exp)
   5300            >= current_time + no_delay);
   5301  tt_assert(download_status_get_next_attempt_at(&dls_exp)
   5302            != TIME_MAX);
   5303  tt_int_op(download_status_get_n_failures(&dls_exp), OP_EQ, 0);
   5304  tt_int_op(download_status_get_n_attempts(&dls_exp), OP_EQ, 0);
   5305  tt_int_op(mock_get_options_calls, OP_GE, 1);
   5306 
   5307  /* regression test for 17750: exponential, initial delay */
   5308  mock_options->TestingClientDownloadInitialDelay = schedule;
   5309  mock_get_options_calls = 0;
   5310  /* we really want to test that it's equal to time(NULL) + delay0, but that's
   5311   * an unrealiable test, because time(NULL) might change. */
   5312  tt_assert(download_status_get_next_attempt_at(&dls_exp)
   5313            >= current_time + delay0);
   5314  tt_assert(download_status_get_next_attempt_at(&dls_exp)
   5315            != TIME_MAX);
   5316  tt_int_op(download_status_get_n_failures(&dls_exp), OP_EQ, 0);
   5317  tt_int_op(download_status_get_n_attempts(&dls_exp), OP_EQ, 0);
   5318  tt_int_op(mock_get_options_calls, OP_GE, 1);
   5319 
   5320 done:
   5321  UNMOCK(get_options);
   5322  mock_options = NULL;
   5323  mock_get_options_calls = 0;
   5324  teardown_capture_of_logs();
   5325 }
   5326 
   5327 static void
   5328 test_dir_authdir_type_to_string(void *data)
   5329 {
   5330  (void)data;
   5331  char *res;
   5332 
   5333  tt_str_op(res = authdir_type_to_string(NO_DIRINFO), OP_EQ,
   5334            "[Not an authority]");
   5335  tor_free(res);
   5336 
   5337  tt_str_op(res = authdir_type_to_string(EXTRAINFO_DIRINFO), OP_EQ,
   5338            "[Not an authority]");
   5339  tor_free(res);
   5340 
   5341  tt_str_op(res = authdir_type_to_string(MICRODESC_DIRINFO), OP_EQ,
   5342            "[Not an authority]");
   5343  tor_free(res);
   5344 
   5345  tt_str_op(res = authdir_type_to_string(V3_DIRINFO), OP_EQ, "V3");
   5346  tor_free(res);
   5347 
   5348  tt_str_op(res = authdir_type_to_string(BRIDGE_DIRINFO), OP_EQ, "Bridge");
   5349  tor_free(res);
   5350 
   5351  tt_str_op(res = authdir_type_to_string(
   5352            V3_DIRINFO | BRIDGE_DIRINFO | EXTRAINFO_DIRINFO), OP_EQ,
   5353            "V3, Bridge");
   5354  done:
   5355  tor_free(res);
   5356 }
   5357 
   5358 static void
   5359 test_dir_conn_purpose_to_string(void *data)
   5360 {
   5361  (void)data;
   5362 
   5363 #define EXPECT_CONN_PURPOSE(purpose, expected) \
   5364  tt_str_op(dir_conn_purpose_to_string(purpose), OP_EQ, expected);
   5365 
   5366  EXPECT_CONN_PURPOSE(DIR_PURPOSE_UPLOAD_DIR, "server descriptor upload");
   5367  EXPECT_CONN_PURPOSE(DIR_PURPOSE_UPLOAD_VOTE, "consensus vote upload");
   5368  EXPECT_CONN_PURPOSE(DIR_PURPOSE_UPLOAD_SIGNATURES,
   5369                      "consensus signature upload");
   5370  EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_SERVERDESC, "server descriptor fetch");
   5371  EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_EXTRAINFO, "extra-info fetch");
   5372  EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_CONSENSUS,
   5373                      "consensus network-status fetch");
   5374  EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_CERTIFICATE, "authority cert fetch");
   5375  EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_STATUS_VOTE, "status vote fetch");
   5376  EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
   5377                      "consensus signature fetch");
   5378  EXPECT_CONN_PURPOSE(DIR_PURPOSE_FETCH_MICRODESC, "microdescriptor fetch");
   5379 
   5380  /* This will give a warning, because there is no purpose 1024. */
   5381  setup_full_capture_of_logs(LOG_WARN);
   5382  EXPECT_CONN_PURPOSE(1024, "(unknown)");
   5383  expect_single_log_msg_containing("Called with unknown purpose 1024");
   5384 
   5385 done:
   5386  teardown_capture_of_logs();
   5387 }
   5388 
   5389 static int dir_tests_public_server_mode(const or_options_t *options);
   5390 ATTR_UNUSED static int dir_tests_public_server_mode_called = 0;
   5391 
   5392 static int
   5393 dir_tests_public_server_mode(const or_options_t *options)
   5394 {
   5395  (void)options;
   5396 
   5397  if (dir_tests_public_server_mode_called++ == 0) {
   5398    return 1;
   5399  }
   5400 
   5401  return 0;
   5402 }
   5403 
   5404 static void
   5405 test_dir_should_use_directory_guards(void *data)
   5406 {
   5407  or_options_t *options;
   5408  char *errmsg = NULL;
   5409  (void)data;
   5410 
   5411  MOCK(public_server_mode,
   5412       dir_tests_public_server_mode);
   5413 
   5414  options = options_new();
   5415  options_init(options);
   5416 
   5417  tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
   5418  tt_int_op(dir_tests_public_server_mode_called, OP_EQ, 1);
   5419 
   5420  options->UseEntryGuards = 1;
   5421  options->DownloadExtraInfo = 0;
   5422  options->FetchDirInfoEarly = 0;
   5423  options->FetchDirInfoExtraEarly = 0;
   5424  options->FetchUselessDescriptors = 0;
   5425  tt_int_op(should_use_directory_guards(options), OP_EQ, 1);
   5426  tt_int_op(dir_tests_public_server_mode_called, OP_EQ, 2);
   5427 
   5428  options->UseEntryGuards = 0;
   5429  tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
   5430  tt_int_op(dir_tests_public_server_mode_called, OP_EQ, 3);
   5431  options->UseEntryGuards = 1;
   5432 
   5433  options->DownloadExtraInfo = 1;
   5434  tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
   5435  tt_int_op(dir_tests_public_server_mode_called, OP_EQ, 4);
   5436  options->DownloadExtraInfo = 0;
   5437 
   5438  options->FetchDirInfoEarly = 1;
   5439  tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
   5440  tt_int_op(dir_tests_public_server_mode_called, OP_EQ, 5);
   5441  options->FetchDirInfoEarly = 0;
   5442 
   5443  options->FetchDirInfoExtraEarly = 1;
   5444  tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
   5445  tt_int_op(dir_tests_public_server_mode_called, OP_EQ, 6);
   5446  options->FetchDirInfoExtraEarly = 0;
   5447 
   5448  options->FetchUselessDescriptors = 1;
   5449  tt_int_op(should_use_directory_guards(options), OP_EQ, 0);
   5450  tt_int_op(dir_tests_public_server_mode_called, OP_EQ, 7);
   5451  options->FetchUselessDescriptors = 0;
   5452 
   5453  done:
   5454    UNMOCK(public_server_mode);
   5455    or_options_free(options);
   5456    tor_free(errmsg);
   5457 }
   5458 
   5459 static void dir_tests_directory_initiate_request(directory_request_t *req);
   5460 ATTR_UNUSED static int dir_tests_directory_initiate_request_called = 0;
   5461 
   5462 static void
   5463 test_dir_should_not_init_request_to_ourselves(void *data)
   5464 {
   5465  char digest[DIGEST_LEN];
   5466  dir_server_t *ourself = NULL;
   5467  crypto_pk_t *key = pk_generate(2);
   5468  (void) data;
   5469 
   5470  MOCK(directory_initiate_request,
   5471       dir_tests_directory_initiate_request);
   5472 
   5473  clear_dir_servers();
   5474  routerlist_free_all();
   5475 
   5476  set_server_identity_key(key);
   5477  crypto_pk_get_digest(key, (char*) &digest);
   5478  ourself = trusted_dir_server_new("ourself", "127.0.0.1", 9059, 9060,
   5479                                   NULL, digest,
   5480                                   NULL, V3_DIRINFO, 1.0);
   5481 
   5482  tt_assert(ourself);
   5483  dir_server_add(ourself);
   5484 
   5485  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE, 0, NULL);
   5486  tt_int_op(dir_tests_directory_initiate_request_called, OP_EQ, 0);
   5487 
   5488  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES, 0,
   5489                                     NULL);
   5490 
   5491  tt_int_op(dir_tests_directory_initiate_request_called, OP_EQ, 0);
   5492 
   5493  done:
   5494    UNMOCK(directory_initiate_request);
   5495    clear_dir_servers();
   5496    routerlist_free_all();
   5497    crypto_pk_free(key);
   5498 }
   5499 
   5500 static void
   5501 test_dir_should_not_init_request_to_dir_auths_without_v3_info(void *data)
   5502 {
   5503  dir_server_t *ds = NULL;
   5504  dirinfo_type_t dirinfo_type = BRIDGE_DIRINFO | EXTRAINFO_DIRINFO \
   5505                                | MICRODESC_DIRINFO;
   5506  (void) data;
   5507 
   5508  MOCK(directory_initiate_request,
   5509       dir_tests_directory_initiate_request);
   5510 
   5511  clear_dir_servers();
   5512  routerlist_free_all();
   5513 
   5514  ds = trusted_dir_server_new("ds", "10.0.0.1", 9059, 9060, NULL,
   5515                              "12345678901234567890", NULL, dirinfo_type, 1.0);
   5516  tt_assert(ds);
   5517  dir_server_add(ds);
   5518 
   5519  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE, 0, NULL);
   5520  tt_int_op(dir_tests_directory_initiate_request_called, OP_EQ, 0);
   5521 
   5522  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES, 0,
   5523                                     NULL);
   5524  tt_int_op(dir_tests_directory_initiate_request_called, OP_EQ, 0);
   5525 
   5526  done:
   5527    UNMOCK(directory_initiate_request);
   5528    clear_dir_servers();
   5529    routerlist_free_all();
   5530 }
   5531 
   5532 static void
   5533 test_dir_should_init_request_to_dir_auths(void *data)
   5534 {
   5535  dir_server_t *ds = NULL;
   5536  (void) data;
   5537 
   5538  MOCK(directory_initiate_request,
   5539       dir_tests_directory_initiate_request);
   5540 
   5541  clear_dir_servers();
   5542  routerlist_free_all();
   5543 
   5544  ds = trusted_dir_server_new("ds", "10.0.0.1", 9059, 9060, NULL,
   5545                              "12345678901234567890", NULL, V3_DIRINFO, 1.0);
   5546  tt_assert(ds);
   5547  dir_server_add(ds);
   5548 
   5549  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE, 0, NULL);
   5550  tt_int_op(dir_tests_directory_initiate_request_called, OP_EQ, 1);
   5551 
   5552  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES, 0,
   5553                                     NULL);
   5554  tt_int_op(dir_tests_directory_initiate_request_called, OP_EQ, 2);
   5555 
   5556  done:
   5557    UNMOCK(directory_initiate_request);
   5558    clear_dir_servers();
   5559    routerlist_free_all();
   5560 }
   5561 
   5562 void
   5563 dir_tests_directory_initiate_request(directory_request_t *req)
   5564 {
   5565  (void)req;
   5566  dir_tests_directory_initiate_request_called++;
   5567 }
   5568 
   5569 /*
   5570 * Mock check_private_dir(), and always succeed - no need to actually
   5571 * look at or create anything on the filesystem.
   5572 */
   5573 
   5574 static int
   5575 mock_check_private_dir(const char *dirname, cpd_check_t check,
   5576                       const char *effective_user)
   5577 {
   5578  (void)dirname;
   5579  (void)check;
   5580  (void)effective_user;
   5581 
   5582  return 0;
   5583 }
   5584 
   5585 /*
   5586 * This really mocks options_get_datadir_fname2_suffix(), but for testing
   5587 * dump_desc(), we only care about get_datadir_fname(sub1), which is defined
   5588 * in config.h as:
   5589 *
   5590 * options_get_datadir_fname2_suffix(get_options(), sub1, NULL, NULL)
   5591 */
   5592 
   5593 static char *
   5594 mock_get_datadir_fname(const or_options_t *options,
   5595                       directory_root_t roottype,
   5596                       const char *sub1, const char *sub2,
   5597                       const char *suffix)
   5598 {
   5599  (void) roottype;
   5600  char *rv = NULL;
   5601 
   5602  /*
   5603   * Assert we were called like get_datadir_fname2() or get_datadir_fname(),
   5604   * since that's all we implement here.
   5605   */
   5606  tt_ptr_op(options, OP_NE, NULL);
   5607  tt_ptr_op(sub1, OP_NE, NULL);
   5608  /*
   5609   * No particular assertions about sub2, since we could be in the
   5610   * get_datadir_fname() or get_datadir_fname2() case.
   5611   */
   5612  tt_ptr_op(suffix, OP_EQ, NULL);
   5613 
   5614  /* Just duplicate the basename and return it for this mock */
   5615  if (sub2) {
   5616    /* If we have sub2, it's the basename, otherwise sub1 */
   5617    rv = tor_strdup(sub2);
   5618  } else {
   5619    rv = tor_strdup(sub1);
   5620  }
   5621 
   5622 done:
   5623  return rv;
   5624 }
   5625 
   5626 static char *last_unlinked_path = NULL;
   5627 static int unlinked_count = 0;
   5628 
   5629 static void
   5630 mock_unlink_reset(void)
   5631 {
   5632  tor_free(last_unlinked_path);
   5633  unlinked_count = 0;
   5634 }
   5635 
   5636 static int
   5637 mock_unlink(const char *path)
   5638 {
   5639  tt_ptr_op(path, OP_NE, NULL);
   5640 
   5641  tor_free(last_unlinked_path);
   5642  last_unlinked_path = tor_strdup(path);
   5643  ++unlinked_count;
   5644 
   5645 done:
   5646  return 0;
   5647 }
   5648 
   5649 static char *last_write_str_path = NULL;
   5650 static uint8_t last_write_str_hash[DIGEST256_LEN];
   5651 static int write_str_count = 0;
   5652 
   5653 static void
   5654 mock_write_str_to_file_reset(void)
   5655 {
   5656  tor_free(last_write_str_path);
   5657  write_str_count = 0;
   5658 }
   5659 
   5660 static int
   5661 mock_write_str_to_file(const char *path, const char *str, int bin)
   5662 {
   5663  size_t len;
   5664  uint8_t hash[DIGEST256_LEN];
   5665 
   5666  (void)bin;
   5667 
   5668  tt_ptr_op(path, OP_NE, NULL);
   5669  tt_ptr_op(str, OP_NE, NULL);
   5670 
   5671  len = strlen(str);
   5672  crypto_digest256((char *)hash, str, len, DIGEST_SHA256);
   5673 
   5674  tor_free(last_write_str_path);
   5675  last_write_str_path = tor_strdup(path);
   5676  memcpy(last_write_str_hash, hash, sizeof(last_write_str_hash));
   5677  ++write_str_count;
   5678 
   5679 done:
   5680  return 0;
   5681 }
   5682 
   5683 static void
   5684 test_dir_dump_unparseable_descriptors(void *data)
   5685 {
   5686  /*
   5687   * These bogus descriptors look nothing at all like real bogus descriptors
   5688   * we might see, but we're only testing dump_desc() here, not the parser.
   5689   */
   5690  const char *test_desc_type = "squamous";
   5691  /* strlen(test_desc_1) = 583 bytes */
   5692  const char *test_desc_1 =
   5693    "The most merciful thing in the world, I think, is the inability of the "
   5694    "human mind to correlate all its contents. We live on a placid island of"
   5695    " ignorance in the midst of black seas of infinity, and it was not meant"
   5696    " that we should voyage far. The sciences, each straining in its own dir"
   5697    "ection, have hitherto harmed us little; but some day the piecing togeth"
   5698    "er of dissociated knowledge will open up such terrifying vistas of real"
   5699    "ity, and of our frightful position therein, that we shall either go mad"
   5700    "from the revelation or flee from the light into the peace and safety of"
   5701    "a new dark age.";
   5702  uint8_t test_desc_1_hash[DIGEST256_LEN];
   5703  char test_desc_1_hash_str[HEX_DIGEST256_LEN+1];
   5704  /* strlen(test_desc_2) = 650 bytes */
   5705  const char *test_desc_2 =
   5706    "I think their predominant colour was a greyish-green, though they had w"
   5707    "hite bellies. They were mostly shiny and slippery, but the ridges of th"
   5708    "eir backs were scaly. Their forms vaguely suggested the anthropoid, whi"
   5709    "le their heads were the heads of fish, with prodigious bulging eyes tha"
   5710    "t never closed. At the sides of their necks were palpitating gills, and"
   5711    "their long paws were webbed. They hopped irregularly, sometimes on two "
   5712    "legs and sometimes on four. I was somehow glad that they had no more th"
   5713    "an four limbs. Their croaking, baying voices, clearly wed tar articulat"
   5714    "e speech, held all the dark shades of expression which their staring fa"
   5715    "ces lacked.";
   5716  uint8_t test_desc_2_hash[DIGEST256_LEN];
   5717  char test_desc_2_hash_str[HEX_DIGEST256_LEN+1];
   5718  /* strlen(test_desc_3) = 700 bytes */
   5719  const char *test_desc_3 =
   5720    "Without knowing what futurism is like, Johansen achieved something very"
   5721    "close to it when he spoke of the city; for instead of describing any de"
   5722    "finite structure or building, he dwells only on broad impressions of va"
   5723    "st angles and stone surfaces - surfaces too great to belong to anything"
   5724    "right or proper for this earth, and impious with horrible images and hi"
   5725    "eroglyphs. I mention his talk about angles because it suggests somethin"
   5726    "g Wilcox had told me of his awful dreams. He said that the geometry of "
   5727    "the dream-place he saw was abnormal, non-Euclidean, and loathsomely red"
   5728    "olent of spheres and dimensions apart from ours. Now an unlettered seam"
   5729    "an felt the same thing whilst gazing at the terrible reality.";
   5730  uint8_t test_desc_3_hash[DIGEST256_LEN];
   5731  char test_desc_3_hash_str[HEX_DIGEST256_LEN+1];
   5732  /* strlen(test_desc_3) = 604 bytes */
   5733  const char *test_desc_4 =
   5734    "So we glanced back simultaneously, it would appear; though no doubt the"
   5735    "incipient motion of one prompted the imitation of the other. As we did "
   5736    "so we flashed both torches full strength at the momentarily thinned mis"
   5737    "t; either from sheer primitive anxiety to see all we could, or in a les"
   5738    "s primitive but equally unconscious effort to dazzle the entity before "
   5739    "we dimmed our light and dodged among the penguins of the labyrinth cent"
   5740    "er ahead. Unhappy act! Not Orpheus himself, or Lot's wife, paid much mo"
   5741    "re dearly for a backward glance. And again came that shocking, wide-ran"
   5742    "ged piping - \"Tekeli-li! Tekeli-li!\"";
   5743  uint8_t test_desc_4_hash[DIGEST256_LEN];
   5744  char test_desc_4_hash_str[HEX_DIGEST256_LEN+1];
   5745  (void)data;
   5746 
   5747  /*
   5748   * Set up options mock so we can force a tiny FIFO size and generate
   5749   * cleanups.
   5750   */
   5751  mock_options = tor_malloc(sizeof(or_options_t));
   5752  reset_options(mock_options, &mock_get_options_calls);
   5753  mock_options->MaxUnparseableDescSizeToLog = 1536;
   5754  MOCK(get_options, mock_get_options);
   5755  MOCK(check_private_dir, mock_check_private_dir);
   5756  MOCK(options_get_dir_fname2_suffix,
   5757       mock_get_datadir_fname);
   5758 
   5759  /*
   5760   * Set up unlink and write mocks
   5761   */
   5762  MOCK(tor_unlink, mock_unlink);
   5763  mock_unlink_reset();
   5764  MOCK(write_str_to_file, mock_write_str_to_file);
   5765  mock_write_str_to_file_reset();
   5766 
   5767  /*
   5768   * Compute hashes we'll need to recognize which descriptor is which
   5769   */
   5770  crypto_digest256((char *)test_desc_1_hash, test_desc_1,
   5771                   strlen(test_desc_1), DIGEST_SHA256);
   5772  base16_encode(test_desc_1_hash_str, sizeof(test_desc_1_hash_str),
   5773                (const char *)test_desc_1_hash,
   5774                sizeof(test_desc_1_hash));
   5775  crypto_digest256((char *)test_desc_2_hash, test_desc_2,
   5776                   strlen(test_desc_2), DIGEST_SHA256);
   5777  base16_encode(test_desc_2_hash_str, sizeof(test_desc_2_hash_str),
   5778                (const char *)test_desc_2_hash,
   5779                sizeof(test_desc_2_hash));
   5780  crypto_digest256((char *)test_desc_3_hash, test_desc_3,
   5781                   strlen(test_desc_3), DIGEST_SHA256);
   5782  base16_encode(test_desc_3_hash_str, sizeof(test_desc_3_hash_str),
   5783                (const char *)test_desc_3_hash,
   5784                sizeof(test_desc_3_hash));
   5785  crypto_digest256((char *)test_desc_4_hash, test_desc_4,
   5786                   strlen(test_desc_4), DIGEST_SHA256);
   5787  base16_encode(test_desc_4_hash_str, sizeof(test_desc_4_hash_str),
   5788                (const char *)test_desc_4_hash,
   5789                sizeof(test_desc_4_hash));
   5790 
   5791  /*
   5792   * Reset the FIFO and check its state
   5793   */
   5794  dump_desc_fifo_cleanup();
   5795  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   5796  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   5797 
   5798  /*
   5799   * (1) Fire off dump_desc() once; these descriptors should all be safely
   5800   * smaller than configured FIFO size.
   5801   */
   5802 
   5803  dump_desc(test_desc_1, test_desc_type);
   5804 
   5805  /*
   5806   * Assert things about the FIFO state
   5807   */
   5808  tt_u64_op(len_descs_dumped, OP_EQ, strlen(test_desc_1));
   5809  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 1);
   5810 
   5811  /*
   5812   * Assert things about the mocks
   5813   */
   5814  tt_int_op(unlinked_count, OP_EQ, 0);
   5815  tt_int_op(write_str_count, OP_EQ, 1);
   5816  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_1_hash, DIGEST_SHA256);
   5817 
   5818  /*
   5819   * Reset the FIFO and check its state
   5820   */
   5821  dump_desc_fifo_cleanup();
   5822  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   5823  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   5824 
   5825  /*
   5826   * Reset the mocks and check their state
   5827   */
   5828  mock_unlink_reset();
   5829  mock_write_str_to_file_reset();
   5830  tt_int_op(unlinked_count, OP_EQ, 0);
   5831  tt_int_op(write_str_count, OP_EQ, 0);
   5832 
   5833  /*
   5834   * (2) Fire off dump_desc() twice; this still should trigger no cleanup.
   5835   */
   5836 
   5837  /* First time */
   5838  dump_desc(test_desc_2, test_desc_type);
   5839 
   5840  /*
   5841   * Assert things about the FIFO state
   5842   */
   5843  tt_u64_op(len_descs_dumped, OP_EQ, strlen(test_desc_2));
   5844  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 1);
   5845 
   5846  /*
   5847   * Assert things about the mocks
   5848   */
   5849  tt_int_op(unlinked_count, OP_EQ, 0);
   5850  tt_int_op(write_str_count, OP_EQ, 1);
   5851  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_2_hash, DIGEST_SHA256);
   5852 
   5853  /* Second time */
   5854  dump_desc(test_desc_3, test_desc_type);
   5855 
   5856  /*
   5857   * Assert things about the FIFO state
   5858   */
   5859  tt_u64_op(len_descs_dumped, OP_EQ,
   5860            strlen(test_desc_2) + strlen(test_desc_3));
   5861  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   5862 
   5863  /*
   5864   * Assert things about the mocks
   5865   */
   5866  tt_int_op(unlinked_count, OP_EQ, 0);
   5867  tt_int_op(write_str_count, OP_EQ, 2);
   5868  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_3_hash, DIGEST_SHA256);
   5869 
   5870  /*
   5871   * Reset the FIFO and check its state
   5872   */
   5873  dump_desc_fifo_cleanup();
   5874  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   5875  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   5876 
   5877  /*
   5878   * Reset the mocks and check their state
   5879   */
   5880  mock_unlink_reset();
   5881  mock_write_str_to_file_reset();
   5882  tt_int_op(unlinked_count, OP_EQ, 0);
   5883  tt_int_op(write_str_count, OP_EQ, 0);
   5884 
   5885  /*
   5886   * (3) Three calls to dump_desc cause a FIFO cleanup
   5887   */
   5888 
   5889  /* First time */
   5890  dump_desc(test_desc_4, test_desc_type);
   5891 
   5892  /*
   5893   * Assert things about the FIFO state
   5894   */
   5895  tt_u64_op(len_descs_dumped, OP_EQ, strlen(test_desc_4));
   5896  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 1);
   5897 
   5898  /*
   5899   * Assert things about the mocks
   5900   */
   5901  tt_int_op(unlinked_count, OP_EQ, 0);
   5902  tt_int_op(write_str_count, OP_EQ, 1);
   5903  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_4_hash, DIGEST_SHA256);
   5904 
   5905  /* Second time */
   5906  dump_desc(test_desc_1, test_desc_type);
   5907 
   5908  /*
   5909   * Assert things about the FIFO state
   5910   */
   5911  tt_u64_op(len_descs_dumped, OP_EQ,
   5912            strlen(test_desc_4) + strlen(test_desc_1));
   5913  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   5914 
   5915  /*
   5916   * Assert things about the mocks
   5917   */
   5918  tt_int_op(unlinked_count, OP_EQ, 0);
   5919  tt_int_op(write_str_count, OP_EQ, 2);
   5920  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_1_hash, DIGEST_SHA256);
   5921 
   5922  /* Third time - we should unlink the dump of test_desc_4 here */
   5923  dump_desc(test_desc_2, test_desc_type);
   5924 
   5925  /*
   5926   * Assert things about the FIFO state
   5927   */
   5928  tt_u64_op(len_descs_dumped, OP_EQ,
   5929            strlen(test_desc_1) + strlen(test_desc_2));
   5930  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   5931 
   5932  /*
   5933   * Assert things about the mocks
   5934   */
   5935  tt_int_op(unlinked_count, OP_EQ, 1);
   5936  tt_int_op(write_str_count, OP_EQ, 3);
   5937  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_2_hash, DIGEST_SHA256);
   5938 
   5939  /*
   5940   * Reset the FIFO and check its state
   5941   */
   5942  dump_desc_fifo_cleanup();
   5943  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   5944  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   5945 
   5946  /*
   5947   * Reset the mocks and check their state
   5948   */
   5949  mock_unlink_reset();
   5950  mock_write_str_to_file_reset();
   5951  tt_int_op(unlinked_count, OP_EQ, 0);
   5952  tt_int_op(write_str_count, OP_EQ, 0);
   5953 
   5954  /*
   5955   * (4) But repeating one (A B B) doesn't overflow and cleanup
   5956   */
   5957 
   5958  /* First time */
   5959  dump_desc(test_desc_3, test_desc_type);
   5960 
   5961  /*
   5962   * Assert things about the FIFO state
   5963   */
   5964  tt_u64_op(len_descs_dumped, OP_EQ, strlen(test_desc_3));
   5965  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 1);
   5966 
   5967  /*
   5968   * Assert things about the mocks
   5969   */
   5970  tt_int_op(unlinked_count, OP_EQ, 0);
   5971  tt_int_op(write_str_count, OP_EQ, 1);
   5972  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_3_hash, DIGEST_SHA256);
   5973 
   5974  /* Second time */
   5975  dump_desc(test_desc_4, test_desc_type);
   5976 
   5977  /*
   5978   * Assert things about the FIFO state
   5979   */
   5980  tt_u64_op(len_descs_dumped, OP_EQ,
   5981            strlen(test_desc_3) + strlen(test_desc_4));
   5982  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   5983 
   5984  /*
   5985   * Assert things about the mocks
   5986   */
   5987  tt_int_op(unlinked_count, OP_EQ, 0);
   5988  tt_int_op(write_str_count, OP_EQ, 2);
   5989  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_4_hash, DIGEST_SHA256);
   5990 
   5991  /* Third time */
   5992  dump_desc(test_desc_4, test_desc_type);
   5993 
   5994  /*
   5995   * Assert things about the FIFO state
   5996   */
   5997  tt_u64_op(len_descs_dumped, OP_EQ,
   5998            strlen(test_desc_3) + strlen(test_desc_4));
   5999  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6000 
   6001  /*
   6002   * Assert things about the mocks
   6003   */
   6004  tt_int_op(unlinked_count, OP_EQ, 0);
   6005  tt_int_op(write_str_count, OP_EQ, 2);
   6006  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_4_hash, DIGEST_SHA256);
   6007 
   6008  /*
   6009   * Reset the FIFO and check its state
   6010   */
   6011  dump_desc_fifo_cleanup();
   6012  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   6013  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   6014 
   6015  /*
   6016   * Reset the mocks and check their state
   6017   */
   6018  mock_unlink_reset();
   6019  mock_write_str_to_file_reset();
   6020  tt_int_op(unlinked_count, OP_EQ, 0);
   6021  tt_int_op(write_str_count, OP_EQ, 0);
   6022 
   6023  /*
   6024   * (5) Same for the (A B A) repetition
   6025   */
   6026 
   6027  /* First time */
   6028  dump_desc(test_desc_1, test_desc_type);
   6029 
   6030  /*
   6031   * Assert things about the FIFO state
   6032   */
   6033  tt_u64_op(len_descs_dumped, OP_EQ, strlen(test_desc_1));
   6034  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 1);
   6035 
   6036  /*
   6037   * Assert things about the mocks
   6038   */
   6039  tt_int_op(unlinked_count, OP_EQ, 0);
   6040  tt_int_op(write_str_count, OP_EQ, 1);
   6041  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_1_hash, DIGEST_SHA256);
   6042 
   6043  /* Second time */
   6044  dump_desc(test_desc_2, test_desc_type);
   6045 
   6046  /*
   6047   * Assert things about the FIFO state
   6048   */
   6049  tt_u64_op(len_descs_dumped, OP_EQ,
   6050            strlen(test_desc_1) + strlen(test_desc_2));
   6051  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6052 
   6053  /*
   6054   * Assert things about the mocks
   6055   */
   6056  tt_int_op(unlinked_count, OP_EQ, 0);
   6057  tt_int_op(write_str_count, OP_EQ, 2);
   6058  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_2_hash, DIGEST_SHA256);
   6059 
   6060  /* Third time */
   6061  dump_desc(test_desc_1, test_desc_type);
   6062 
   6063  /*
   6064   * Assert things about the FIFO state
   6065   */
   6066  tt_u64_op(len_descs_dumped, OP_EQ,
   6067            strlen(test_desc_1) + strlen(test_desc_2));
   6068  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6069 
   6070  /*
   6071   * Assert things about the mocks
   6072   */
   6073  tt_int_op(unlinked_count, OP_EQ, 0);
   6074  tt_int_op(write_str_count, OP_EQ, 2);
   6075  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_2_hash, DIGEST_SHA256);
   6076 
   6077  /*
   6078   * Reset the FIFO and check its state
   6079   */
   6080  dump_desc_fifo_cleanup();
   6081  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   6082  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   6083 
   6084  /*
   6085   * Reset the mocks and check their state
   6086   */
   6087  mock_unlink_reset();
   6088  mock_write_str_to_file_reset();
   6089  tt_int_op(unlinked_count, OP_EQ, 0);
   6090  tt_int_op(write_str_count, OP_EQ, 0);
   6091 
   6092  /*
   6093   * (6) (A B B C) triggering overflow on C causes A, not B to be unlinked
   6094   */
   6095 
   6096  /* First time */
   6097  dump_desc(test_desc_3, test_desc_type);
   6098 
   6099  /*
   6100   * Assert things about the FIFO state
   6101   */
   6102  tt_u64_op(len_descs_dumped, OP_EQ, strlen(test_desc_3));
   6103  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 1);
   6104 
   6105  /*
   6106   * Assert things about the mocks
   6107   */
   6108  tt_int_op(unlinked_count, OP_EQ, 0);
   6109  tt_int_op(write_str_count, OP_EQ, 1);
   6110  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_3_hash, DIGEST_SHA256);
   6111 
   6112  /* Second time */
   6113  dump_desc(test_desc_4, test_desc_type);
   6114 
   6115  /*
   6116   * Assert things about the FIFO state
   6117   */
   6118  tt_u64_op(len_descs_dumped, OP_EQ,
   6119            strlen(test_desc_3) + strlen(test_desc_4));
   6120  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6121 
   6122  /*
   6123   * Assert things about the mocks
   6124   */
   6125  tt_int_op(unlinked_count, OP_EQ, 0);
   6126  tt_int_op(write_str_count, OP_EQ, 2);
   6127  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_4_hash, DIGEST_SHA256);
   6128 
   6129  /* Third time */
   6130  dump_desc(test_desc_4, test_desc_type);
   6131 
   6132  /*
   6133   * Assert things about the FIFO state
   6134   */
   6135  tt_u64_op(len_descs_dumped, OP_EQ,
   6136            strlen(test_desc_3) + strlen(test_desc_4));
   6137  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6138 
   6139  /*
   6140   * Assert things about the mocks
   6141   */
   6142  tt_int_op(unlinked_count, OP_EQ, 0);
   6143  tt_int_op(write_str_count, OP_EQ, 2);
   6144  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_4_hash, DIGEST_SHA256);
   6145 
   6146  /* Fourth time - we should unlink the dump of test_desc_3 here */
   6147  dump_desc(test_desc_1, test_desc_type);
   6148 
   6149  /*
   6150   * Assert things about the FIFO state
   6151   */
   6152  tt_u64_op(len_descs_dumped, OP_EQ,
   6153            strlen(test_desc_4) + strlen(test_desc_1));
   6154  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6155 
   6156  /*
   6157   * Assert things about the mocks
   6158   */
   6159  tt_int_op(unlinked_count, OP_EQ, 1);
   6160  tt_int_op(write_str_count, OP_EQ, 3);
   6161  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_1_hash, DIGEST_SHA256);
   6162 
   6163  /*
   6164   * Reset the FIFO and check its state
   6165   */
   6166  dump_desc_fifo_cleanup();
   6167  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   6168  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   6169 
   6170  /*
   6171   * Reset the mocks and check their state
   6172   */
   6173  mock_unlink_reset();
   6174  mock_write_str_to_file_reset();
   6175  tt_int_op(unlinked_count, OP_EQ, 0);
   6176  tt_int_op(write_str_count, OP_EQ, 0);
   6177 
   6178  /*
   6179   * (7) (A B A C) triggering overflow on C causes B, not A to be unlinked
   6180   */
   6181 
   6182  /* First time */
   6183  dump_desc(test_desc_2, test_desc_type);
   6184 
   6185  /*
   6186   * Assert things about the FIFO state
   6187   */
   6188  tt_u64_op(len_descs_dumped, OP_EQ, strlen(test_desc_2));
   6189  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 1);
   6190 
   6191  /*
   6192   * Assert things about the mocks
   6193   */
   6194  tt_int_op(unlinked_count, OP_EQ, 0);
   6195  tt_int_op(write_str_count, OP_EQ, 1);
   6196  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_2_hash, DIGEST_SHA256);
   6197 
   6198  /* Second time */
   6199  dump_desc(test_desc_3, test_desc_type);
   6200 
   6201  /*
   6202   * Assert things about the FIFO state
   6203   */
   6204  tt_u64_op(len_descs_dumped, OP_EQ,
   6205            strlen(test_desc_2) + strlen(test_desc_3));
   6206  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6207 
   6208  /*
   6209   * Assert things about the mocks
   6210   */
   6211  tt_int_op(unlinked_count, OP_EQ, 0);
   6212  tt_int_op(write_str_count, OP_EQ, 2);
   6213  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_3_hash, DIGEST_SHA256);
   6214 
   6215  /* Third time */
   6216  dump_desc(test_desc_2, test_desc_type);
   6217 
   6218  /*
   6219   * Assert things about the FIFO state
   6220   */
   6221  tt_u64_op(len_descs_dumped, OP_EQ,
   6222            strlen(test_desc_2) + strlen(test_desc_3));
   6223  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6224 
   6225  /*
   6226   * Assert things about the mocks
   6227   */
   6228  tt_int_op(unlinked_count, OP_EQ, 0);
   6229  tt_int_op(write_str_count, OP_EQ, 2);
   6230  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_3_hash, DIGEST_SHA256);
   6231 
   6232  /* Fourth time - we should unlink the dump of test_desc_3 here */
   6233  dump_desc(test_desc_4, test_desc_type);
   6234 
   6235  /*
   6236   * Assert things about the FIFO state
   6237   */
   6238  tt_u64_op(len_descs_dumped, OP_EQ,
   6239            strlen(test_desc_2) + strlen(test_desc_4));
   6240  tt_assert(descs_dumped != NULL && smartlist_len(descs_dumped) == 2);
   6241 
   6242  /*
   6243   * Assert things about the mocks
   6244   */
   6245  tt_int_op(unlinked_count, OP_EQ, 1);
   6246  tt_int_op(write_str_count, OP_EQ, 3);
   6247  tt_mem_op(last_write_str_hash, OP_EQ, test_desc_4_hash, DIGEST_SHA256);
   6248 
   6249  /*
   6250   * Reset the FIFO and check its state
   6251   */
   6252  dump_desc_fifo_cleanup();
   6253  tt_u64_op(len_descs_dumped, OP_EQ, 0);
   6254  tt_assert(descs_dumped == NULL || smartlist_len(descs_dumped) == 0);
   6255 
   6256  /*
   6257   * Reset the mocks and check their state
   6258   */
   6259  mock_unlink_reset();
   6260  mock_write_str_to_file_reset();
   6261  tt_int_op(unlinked_count, OP_EQ, 0);
   6262  tt_int_op(write_str_count, OP_EQ, 0);
   6263 
   6264 done:
   6265 
   6266  /* Clean up the fifo */
   6267  dump_desc_fifo_cleanup();
   6268 
   6269  /* Remove mocks */
   6270  UNMOCK(tor_unlink);
   6271  mock_unlink_reset();
   6272  UNMOCK(write_str_to_file);
   6273  mock_write_str_to_file_reset();
   6274  UNMOCK(options_get_dir_fname2_suffix);
   6275  UNMOCK(check_private_dir);
   6276  UNMOCK(get_options);
   6277  tor_free(mock_options);
   6278  mock_options = NULL;
   6279 
   6280  return;
   6281 }
   6282 
   6283 /* Variables for reset_read_file_to_str_mock() */
   6284 
   6285 static int enforce_expected_filename = 0;
   6286 static char *expected_filename = NULL;
   6287 static char *file_content = NULL;
   6288 static size_t file_content_len = 0;
   6289 static struct stat file_stat;
   6290 static int read_count = 0, read_call_count = 0;
   6291 
   6292 static void
   6293 reset_read_file_to_str_mock(void)
   6294 {
   6295  tor_free(expected_filename);
   6296  tor_free(file_content);
   6297  file_content_len = 0;
   6298  memset(&file_stat, 0, sizeof(file_stat));
   6299  read_count = 0;
   6300  read_call_count = 0;
   6301 }
   6302 
   6303 static char *
   6304 read_file_to_str_mock(const char *filename, int flags,
   6305                      struct stat *stat_out) {
   6306  char *result = NULL;
   6307 
   6308  /* Insist we got a filename */
   6309  tt_ptr_op(filename, OP_NE, NULL);
   6310 
   6311  /* We ignore flags */
   6312  (void)flags;
   6313 
   6314  /* Bump the call count */
   6315  ++read_call_count;
   6316 
   6317  if (enforce_expected_filename) {
   6318    tt_assert(expected_filename);
   6319    tt_str_op(filename, OP_EQ, expected_filename);
   6320  }
   6321 
   6322  if (expected_filename != NULL &&
   6323      file_content != NULL &&
   6324      strcmp(filename, expected_filename) == 0) {
   6325    /* You asked for it, you got it */
   6326 
   6327    /*
   6328     * This is the same behavior as the real read_file_to_str();
   6329     * if there's a NUL, the real size ends up in stat_out.
   6330     */
   6331    result = tor_malloc(file_content_len + 1);
   6332    if (file_content_len > 0) {
   6333      memcpy(result, file_content, file_content_len);
   6334    }
   6335    result[file_content_len] = '\0';
   6336 
   6337    /* Do we need to set up stat_out? */
   6338    if (stat_out != NULL) {
   6339      memcpy(stat_out, &file_stat, sizeof(file_stat));
   6340      /* We always return the correct length here */
   6341      stat_out->st_size = file_content_len;
   6342    }
   6343 
   6344    /* Wooo, we have a return value - bump the counter */
   6345    ++read_count;
   6346  }
   6347  /* else no match, return NULL */
   6348 
   6349 done:
   6350  return result;
   6351 }
   6352 
   6353 /* This one tests dump_desc_populate_one_file() */
   6354 static void
   6355 test_dir_populate_dump_desc_fifo(void *data)
   6356 {
   6357  const char *dirname = "foo";
   6358  const char *fname = NULL;
   6359  dumped_desc_t *ent;
   6360 
   6361  (void)data;
   6362 
   6363  /*
   6364   * Set up unlink and read_file_to_str mocks
   6365   */
   6366  MOCK(tor_unlink, mock_unlink);
   6367  mock_unlink_reset();
   6368  MOCK(read_file_to_str, read_file_to_str_mock);
   6369  reset_read_file_to_str_mock();
   6370 
   6371  /* Check state of unlink mock */
   6372  tt_int_op(unlinked_count, OP_EQ, 0);
   6373 
   6374  /* Some cases that should fail before trying to read the file */
   6375  ent = dump_desc_populate_one_file(dirname, "bar");
   6376  tt_ptr_op(ent, OP_EQ, NULL);
   6377  tt_int_op(unlinked_count, OP_EQ, 1);
   6378  tt_int_op(read_count, OP_EQ, 0);
   6379  tt_int_op(read_call_count, OP_EQ, 0);
   6380 
   6381  ent = dump_desc_populate_one_file(dirname, "unparseable-desc");
   6382  tt_ptr_op(ent, OP_EQ, NULL);
   6383  tt_int_op(unlinked_count, OP_EQ, 2);
   6384  tt_int_op(read_count, OP_EQ, 0);
   6385  tt_int_op(read_call_count, OP_EQ, 0);
   6386 
   6387  ent = dump_desc_populate_one_file(dirname, "unparseable-desc.baz");
   6388  tt_ptr_op(ent, OP_EQ, NULL);
   6389  tt_int_op(unlinked_count, OP_EQ, 3);
   6390  tt_int_op(read_count, OP_EQ, 0);
   6391  tt_int_op(read_call_count, OP_EQ, 0);
   6392 
   6393  ent = dump_desc_populate_one_file(
   6394      dirname,
   6395      "unparseable-desc.08AE85E90461F59E");
   6396  tt_ptr_op(ent, OP_EQ, NULL);
   6397  tt_int_op(unlinked_count, OP_EQ, 4);
   6398  tt_int_op(read_count, OP_EQ, 0);
   6399  tt_int_op(read_call_count, OP_EQ, 0);
   6400 
   6401  ent = dump_desc_populate_one_file(
   6402      dirname,
   6403      "unparseable-desc.08AE85E90461F59EDF0981323F3A70D02B55AB54B44B04F"
   6404      "287D72F7B72F242E85C8CB0EDA8854A99");
   6405  tt_ptr_op(ent, OP_EQ, NULL);
   6406  tt_int_op(unlinked_count, OP_EQ, 5);
   6407  tt_int_op(read_count, OP_EQ, 0);
   6408  tt_int_op(read_call_count, OP_EQ, 0);
   6409 
   6410  /* This is a correct-length digest but base16_decode() will fail */
   6411  ent = dump_desc_populate_one_file(
   6412      dirname,
   6413      "unparseable-desc.68219B8BGE64B705A6FFC728C069DC596216D60A7D7520C"
   6414      "D5ECE250D912E686B");
   6415  tt_ptr_op(ent, OP_EQ, NULL);
   6416  tt_int_op(unlinked_count, OP_EQ, 6);
   6417  tt_int_op(read_count, OP_EQ, 0);
   6418  tt_int_op(read_call_count, OP_EQ, 0);
   6419 
   6420  /* This one has a correctly formed filename and should try reading */
   6421 
   6422  /* Read fails */
   6423  ent = dump_desc_populate_one_file(
   6424      dirname,
   6425      "unparseable-desc.DF0981323F3A70D02B55AB54B44B04F287D72F7B72F242E"
   6426      "85C8CB0EDA8854A99");
   6427  tt_ptr_op(ent, OP_EQ, NULL);
   6428  tt_int_op(unlinked_count, OP_EQ, 7);
   6429  tt_int_op(read_count, OP_EQ, 0);
   6430  tt_int_op(read_call_count, OP_EQ, 1);
   6431 
   6432  /* This read will succeed but the digest won't match the file content */
   6433  fname =
   6434    "unparseable-desc."
   6435    "DF0981323F3A70D02B55AB54B44B04F287D72F7B72F242E85C8CB0EDA8854A99";
   6436  enforce_expected_filename = 1;
   6437  tor_asprintf(&expected_filename, "%s%s%s", dirname, PATH_SEPARATOR, fname);
   6438  file_content = tor_strdup("hanc culpam maiorem an illam dicam?");
   6439  file_content_len = strlen(file_content);
   6440  file_stat.st_mtime = 123456;
   6441  ent = dump_desc_populate_one_file(dirname, fname);
   6442  enforce_expected_filename = 0;
   6443  tt_ptr_op(ent, OP_EQ, NULL);
   6444  tt_int_op(unlinked_count, OP_EQ, 8);
   6445  tt_int_op(read_count, OP_EQ, 1);
   6446  tt_int_op(read_call_count, OP_EQ, 2);
   6447  tor_free(expected_filename);
   6448  tor_free(file_content);
   6449 
   6450  /* This one will match */
   6451  fname =
   6452    "unparseable-desc."
   6453    "0786C7173447B7FB033FFCA2FC47C3CF71C30DD47CA8236D3FC7FF35853271C6";
   6454  tor_asprintf(&expected_filename, "%s%s%s", dirname, PATH_SEPARATOR, fname);
   6455  file_content = tor_strdup("hanc culpam maiorem an illam dicam?");
   6456  file_content_len = strlen(file_content);
   6457  file_stat.st_mtime = 789012;
   6458  ent = dump_desc_populate_one_file(dirname, fname);
   6459  tt_ptr_op(ent, OP_NE, NULL);
   6460  tt_int_op(unlinked_count, OP_EQ, 8);
   6461  tt_int_op(read_count, OP_EQ, 2);
   6462  tt_int_op(read_call_count, OP_EQ, 3);
   6463  tt_str_op(ent->filename, OP_EQ, expected_filename);
   6464  tt_int_op(ent->len, OP_EQ, file_content_len);
   6465  tt_int_op(ent->when, OP_EQ, file_stat.st_mtime);
   6466  tor_free(ent->filename);
   6467  tor_free(ent);
   6468  tor_free(expected_filename);
   6469 
   6470  /*
   6471   * Reset the mocks and check their state
   6472   */
   6473  mock_unlink_reset();
   6474  tt_int_op(unlinked_count, OP_EQ, 0);
   6475  reset_read_file_to_str_mock();
   6476  tt_int_op(read_count, OP_EQ, 0);
   6477 
   6478 done:
   6479 
   6480  UNMOCK(tor_unlink);
   6481  mock_unlink_reset();
   6482  UNMOCK(read_file_to_str);
   6483  reset_read_file_to_str_mock();
   6484 
   6485  tor_free(file_content);
   6486 
   6487  return;
   6488 }
   6489 
   6490 static smartlist_t *
   6491 listdir_mock(const char *dname)
   6492 {
   6493  smartlist_t *l;
   6494 
   6495  /* Ignore the name, always return this list */
   6496  (void)dname;
   6497 
   6498  l = smartlist_new();
   6499  smartlist_add_strdup(l, "foo");
   6500  smartlist_add_strdup(l, "bar");
   6501  smartlist_add_strdup(l, "baz");
   6502 
   6503  return l;
   6504 }
   6505 
   6506 static dumped_desc_t *
   6507 pop_one_mock(const char *dirname, const char *f)
   6508 {
   6509  dumped_desc_t *ent = NULL;
   6510 
   6511  if (dirname != NULL && strcmp(dirname, "d") == 0) {
   6512    if (f != NULL && strcmp(f, "foo") == 0) {
   6513      ent = tor_malloc_zero(sizeof(*ent));
   6514      ent->filename = tor_strdup("d/foo");
   6515      ent->len = 123;
   6516      ent->digest_sha256[0] = 1;
   6517      ent->when = 1024;
   6518    } else if (f != NULL && strcmp(f, "bar") == 0) {
   6519      ent = tor_malloc_zero(sizeof(*ent));
   6520      ent->filename = tor_strdup("d/bar");
   6521      ent->len = 456;
   6522      ent->digest_sha256[0] = 2;
   6523      /*
   6524       * Note that the timestamps are in a different order than
   6525       * listdir_mock() returns; we're testing the sort order.
   6526       */
   6527      ent->when = 512;
   6528    } else if (f != NULL && strcmp(f, "baz") == 0) {
   6529      ent = tor_malloc_zero(sizeof(*ent));
   6530      ent->filename = tor_strdup("d/baz");
   6531      ent->len = 789;
   6532      ent->digest_sha256[0] = 3;
   6533      ent->when = 768;
   6534    }
   6535  }
   6536 
   6537  return ent;
   6538 }
   6539 
   6540 /* This one tests dump_desc_populate_fifo_from_directory() */
   6541 static void
   6542 test_dir_populate_dump_desc_fifo_2(void *data)
   6543 {
   6544  dumped_desc_t *ent = NULL;
   6545 
   6546  (void)data;
   6547 
   6548  /* Set up the mocks */
   6549  MOCK(tor_listdir, listdir_mock);
   6550  MOCK(dump_desc_populate_one_file, pop_one_mock);
   6551 
   6552  /* Run dump_desc_populate_fifo_from_directory() */
   6553  descs_dumped = NULL;
   6554  len_descs_dumped = 0;
   6555  dump_desc_populate_fifo_from_directory("d");
   6556  tt_assert(descs_dumped != NULL);
   6557  tt_int_op(smartlist_len(descs_dumped), OP_EQ, 3);
   6558  tt_u64_op(len_descs_dumped, OP_EQ, 1368);
   6559  ent = smartlist_get(descs_dumped, 0);
   6560  tt_str_op(ent->filename, OP_EQ, "d/bar");
   6561  tt_int_op(ent->len, OP_EQ, 456);
   6562  tt_int_op(ent->when, OP_EQ, 512);
   6563  ent = smartlist_get(descs_dumped, 1);
   6564  tt_str_op(ent->filename, OP_EQ, "d/baz");
   6565  tt_int_op(ent->len, OP_EQ, 789);
   6566  tt_int_op(ent->when, OP_EQ, 768);
   6567  ent = smartlist_get(descs_dumped, 2);
   6568  tt_str_op(ent->filename, OP_EQ, "d/foo");
   6569  tt_int_op(ent->len, OP_EQ, 123);
   6570  tt_int_op(ent->when, OP_EQ, 1024);
   6571 
   6572 done:
   6573  dump_desc_fifo_cleanup();
   6574 
   6575  UNMOCK(dump_desc_populate_one_file);
   6576  UNMOCK(tor_listdir);
   6577 
   6578  return;
   6579 }
   6580 
   6581 static int mock_networkstatus_consensus_is_bootstrapping_value = 0;
   6582 static int
   6583 mock_networkstatus_consensus_is_bootstrapping(time_t now)
   6584 {
   6585  (void)now;
   6586  return mock_networkstatus_consensus_is_bootstrapping_value;
   6587 }
   6588 
   6589 static int mock_networkstatus_consensus_can_use_extra_fallbacks_value = 0;
   6590 static int
   6591 mock_networkstatus_consensus_can_use_extra_fallbacks(
   6592                                                  const or_options_t *options)
   6593 {
   6594  (void)options;
   6595  return mock_networkstatus_consensus_can_use_extra_fallbacks_value;
   6596 }
   6597 
   6598 static int mock_num_bridges_usable_value = 0;
   6599 static int
   6600 mock_num_bridges_usable(int use_maybe_reachable)
   6601 {
   6602  (void)use_maybe_reachable;
   6603  return mock_num_bridges_usable_value;
   6604 }
   6605 
   6606 /* data is a 3 character nul-terminated string.
   6607 * If data[0] is 'b', set bootstrapping, anything else means not bootstrapping
   6608 * If data[1] is 'f', set extra fallbacks, anything else means no extra
   6609 * If data[2] is 'f', set running bridges, anything else means no extra
   6610 * fallbacks.
   6611 */
   6612 static void
   6613 test_dir_find_dl_min_delay(void* data)
   6614 {
   6615  const char *str = (const char *)data;
   6616 
   6617  tt_assert(strlen(data) == 3);
   6618 
   6619  if (str[0] == 'b') {
   6620    mock_networkstatus_consensus_is_bootstrapping_value = 1;
   6621  } else {
   6622    mock_networkstatus_consensus_is_bootstrapping_value = 0;
   6623  }
   6624 
   6625  if (str[1] == 'f') {
   6626    mock_networkstatus_consensus_can_use_extra_fallbacks_value = 1;
   6627  } else {
   6628    mock_networkstatus_consensus_can_use_extra_fallbacks_value = 0;
   6629  }
   6630 
   6631  if (str[2] == 'r') {
   6632    /* Any positive, non-zero value should work */
   6633    mock_num_bridges_usable_value = 2;
   6634  } else {
   6635    mock_num_bridges_usable_value = 0;
   6636  }
   6637 
   6638  MOCK(networkstatus_consensus_is_bootstrapping,
   6639       mock_networkstatus_consensus_is_bootstrapping);
   6640  MOCK(networkstatus_consensus_can_use_extra_fallbacks,
   6641       mock_networkstatus_consensus_can_use_extra_fallbacks);
   6642  MOCK(num_bridges_usable,
   6643       mock_num_bridges_usable);
   6644 
   6645  download_status_t dls;
   6646 
   6647  const int server=10, client=20, server_cons=30, client_cons=40;
   6648  const int client_boot_auth_only_cons=50, client_boot_auth_cons=60;
   6649  const int client_boot_fallback_cons=70, bridge=80, bridge_bootstrap=90;
   6650 
   6651  mock_options = tor_malloc(sizeof(or_options_t));
   6652  reset_options(mock_options, &mock_get_options_calls);
   6653  MOCK(get_options, mock_get_options);
   6654 
   6655  mock_options->TestingServerDownloadInitialDelay = server;
   6656  mock_options->TestingClientDownloadInitialDelay = client;
   6657  mock_options->TestingServerConsensusDownloadInitialDelay = server_cons;
   6658  mock_options->TestingClientConsensusDownloadInitialDelay = client_cons;
   6659  mock_options->ClientBootstrapConsensusAuthorityOnlyDownloadInitialDelay =
   6660    client_boot_auth_only_cons;
   6661  mock_options->ClientBootstrapConsensusAuthorityDownloadInitialDelay =
   6662    client_boot_auth_cons;
   6663  mock_options->ClientBootstrapConsensusFallbackDownloadInitialDelay =
   6664    client_boot_fallback_cons;
   6665  mock_options->TestingBridgeDownloadInitialDelay = bridge;
   6666  mock_options->TestingBridgeBootstrapDownloadInitialDelay = bridge_bootstrap;
   6667 
   6668  dls.schedule = DL_SCHED_GENERIC;
   6669  /* client */
   6670  mock_options->ClientOnly = 1;
   6671  tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ, client);
   6672  mock_options->ClientOnly = 0;
   6673 
   6674  /* dir mode */
   6675  mock_options->DirPort_set = 1;
   6676  mock_options->DirCache = 1;
   6677  tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ, server);
   6678  mock_options->DirPort_set = 0;
   6679  mock_options->DirCache = 0;
   6680 
   6681  dls.schedule = DL_SCHED_CONSENSUS;
   6682  /* public server mode */
   6683  mock_options->ORPort_set = 1;
   6684  tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ, server_cons);
   6685  mock_options->ORPort_set = 0;
   6686 
   6687  /* client and bridge modes */
   6688  if (networkstatus_consensus_is_bootstrapping(time(NULL))) {
   6689    if (networkstatus_consensus_can_use_extra_fallbacks(mock_options)) {
   6690      dls.want_authority = 1;
   6691      /* client */
   6692      mock_options->ClientOnly = 1;
   6693      tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6694                client_boot_auth_cons);
   6695      mock_options->ClientOnly = 0;
   6696 
   6697      /* bridge relay */
   6698      mock_options->ORPort_set = 1;
   6699      mock_options->BridgeRelay = 1;
   6700      tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6701                client_boot_auth_cons);
   6702      mock_options->ORPort_set = 0;
   6703      mock_options->BridgeRelay = 0;
   6704 
   6705      dls.want_authority = 0;
   6706      /* client */
   6707      mock_options->ClientOnly = 1;
   6708      tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6709                client_boot_fallback_cons);
   6710      mock_options->ClientOnly = 0;
   6711 
   6712      /* bridge relay */
   6713      mock_options->ORPort_set = 1;
   6714      mock_options->BridgeRelay = 1;
   6715      tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6716                client_boot_fallback_cons);
   6717      mock_options->ORPort_set = 0;
   6718      mock_options->BridgeRelay = 0;
   6719 
   6720    } else {
   6721      /* dls.want_authority is ignored */
   6722      /* client */
   6723      mock_options->ClientOnly = 1;
   6724      tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6725                client_boot_auth_only_cons);
   6726      mock_options->ClientOnly = 0;
   6727 
   6728      /* bridge relay */
   6729      mock_options->ORPort_set = 1;
   6730      mock_options->BridgeRelay = 1;
   6731      tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6732                client_boot_auth_only_cons);
   6733      mock_options->ORPort_set = 0;
   6734      mock_options->BridgeRelay = 0;
   6735    }
   6736  } else {
   6737    /* client */
   6738    mock_options->ClientOnly = 1;
   6739    tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6740              client_cons);
   6741    mock_options->ClientOnly = 0;
   6742 
   6743    /* bridge relay */
   6744    mock_options->ORPort_set = 1;
   6745    mock_options->BridgeRelay = 1;
   6746    tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ,
   6747              client_cons);
   6748    mock_options->ORPort_set = 0;
   6749    mock_options->BridgeRelay = 0;
   6750  }
   6751 
   6752  dls.schedule = DL_SCHED_BRIDGE;
   6753  /* client */
   6754  tt_int_op(find_dl_min_delay(&dls, mock_options), OP_EQ, bridge_bootstrap);
   6755 
   6756 done:
   6757  UNMOCK(networkstatus_consensus_is_bootstrapping);
   6758  UNMOCK(networkstatus_consensus_can_use_extra_fallbacks);
   6759  UNMOCK(num_bridges_usable);
   6760  UNMOCK(get_options);
   6761  tor_free(mock_options);
   6762  mock_options = NULL;
   6763 }
   6764 
   6765 static void
   6766 test_dir_matching_flags(void *arg)
   6767 {
   6768  (void) arg;
   6769  routerstatus_t *rs_noflags = NULL;
   6770  routerstatus_t *rs = NULL;
   6771  char *s = NULL;
   6772 
   6773  smartlist_t *tokens = smartlist_new();
   6774  memarea_t *area = memarea_new();
   6775 
   6776  int expected_val_when_unused = 0;
   6777 
   6778  const char *ex_noflags =
   6779    "r example hereiswhereyouridentitygoes 2015-08-30 12:00:00 "
   6780       "192.168.0.1 9001 0\n"
   6781    "m thisoneislongerbecauseitisa256bitmddigest33\n"
   6782    "s\n"
   6783    "pr Link=4\n";
   6784  const char *cp = ex_noflags;
   6785  rs_noflags = routerstatus_parse_entry_from_string(
   6786         area, &cp,
   6787         cp + strlen(cp),
   6788         tokens, NULL, NULL,
   6789         MAX_SUPPORTED_CONSENSUS_METHOD, FLAV_MICRODESC);
   6790  tt_assert(rs_noflags);
   6791 
   6792 #define FLAG(string, field) STMT_BEGIN {        \
   6793    tor_asprintf(&s,\
   6794                 "r example hereiswhereyouridentitygoes 2015-08-30 12:00:00 " \
   6795                 "192.168.0.1 9001 0\n"                                 \
   6796                 "m thisoneislongerbecauseitisa256bitmddigest33\n"      \
   6797                 "pr Link=4\n"                                          \
   6798                 "s %s\n", string);                                     \
   6799    cp = s;                                                             \
   6800    rs =  routerstatus_parse_entry_from_string(                         \
   6801      area, &cp,                                                        \
   6802      cp + strlen(cp),                                                  \
   6803      tokens, NULL, NULL,                                               \
   6804      MAX_SUPPORTED_CONSENSUS_METHOD, FLAV_MICRODESC);                  \
   6805    /* the field should usually be 0 when no flags are listed */        \
   6806    tt_int_op(rs_noflags->field, OP_EQ, expected_val_when_unused);      \
   6807    /* the field should be 1 when this flags islisted */                \
   6808    tt_int_op(rs->field, OP_EQ, 1);                                     \
   6809    tor_free(s);                                                        \
   6810    routerstatus_free(rs);                                              \
   6811 } STMT_END
   6812 
   6813  FLAG("Authority", is_authority);
   6814  FLAG("BadExit", is_bad_exit);
   6815  FLAG("Exit", is_exit);
   6816  FLAG("Fast", is_fast);
   6817  FLAG("Guard", is_possible_guard);
   6818  FLAG("HSDir", is_hs_dir);
   6819  FLAG("Stable", is_stable);
   6820  FLAG("StaleDesc", is_staledesc);
   6821  FLAG("V2Dir", is_v2_dir);
   6822 
   6823  // These flags are assumed to be set whether they're declared or not.
   6824  expected_val_when_unused = 1;
   6825  FLAG("Running", is_flagged_running);
   6826  FLAG("Valid", is_valid);
   6827  expected_val_when_unused = 0;
   6828 
   6829  // These flags are no longer used, but still parsed.
   6830  FLAG("Named", is_named);
   6831  FLAG("Unnamed", is_unnamed);
   6832 
   6833 done:
   6834  tor_free(s);
   6835  routerstatus_free(rs);
   6836  routerstatus_free(rs_noflags);
   6837  memarea_drop_all(area);
   6838  smartlist_free(tokens);
   6839 }
   6840 
   6841 static void
   6842 test_dir_assumed_flags(void *arg)
   6843 {
   6844  (void)arg;
   6845  smartlist_t *tokens = smartlist_new();
   6846  memarea_t *area = memarea_new();
   6847  routerstatus_t *rs = NULL;
   6848 
   6849  /* We can assume that consensus method is higher than 24, so Running and
   6850   * Valid are always implicitly set */
   6851  const char *str1 =
   6852    "r example hereiswhereyouridentitygoes 2015-08-30 12:00:00 "
   6853       "192.168.0.1 9001 0\n"
   6854    "m thisoneislongerbecauseitisa256bitmddigest33\n"
   6855    "s Fast Guard Stable\n"
   6856    "pr Link=4\n";
   6857  const char *eos = str1 + strlen(str1);
   6858 
   6859  const char *cp = str1;
   6860  rs = routerstatus_parse_entry_from_string(area, &cp, eos, tokens, NULL, NULL,
   6861                                            24, FLAV_MICRODESC);
   6862  tt_assert(rs);
   6863  tt_assert(rs->is_flagged_running);
   6864  tt_assert(rs->is_valid);
   6865  tt_assert(! rs->is_exit);
   6866  tt_assert(rs->is_fast);
   6867 
   6868 done:
   6869  smartlist_free(tokens);
   6870  memarea_drop_all(area);
   6871  routerstatus_free(rs);
   6872 }
   6873 
   6874 static void
   6875 test_dir_post_parsing(void *arg)
   6876 {
   6877  (void) arg;
   6878 
   6879  /* Test the version parsing from an HS descriptor publish request. */
   6880  {
   6881    const char *end;
   6882    const char *prefix = "/tor/hs/";
   6883    int version = parse_hs_version_from_post("/tor/hs//publish", prefix, &end);
   6884    tt_int_op(version, OP_EQ, -1);
   6885    tt_ptr_op(end, OP_EQ, NULL);
   6886    version = parse_hs_version_from_post("/tor/hs/a/publish", prefix, &end);
   6887    tt_int_op(version, OP_EQ, -1);
   6888    tt_ptr_op(end, OP_EQ, NULL);
   6889    version = parse_hs_version_from_post("/tor/hs/3/publish", prefix, &end);
   6890    tt_int_op(version, OP_EQ, 3);
   6891    tt_str_op(end, OP_EQ, "/publish");
   6892    version = parse_hs_version_from_post("/tor/hs/42/publish", prefix, &end);
   6893    tt_int_op(version, OP_EQ, 42);
   6894    tt_str_op(end, OP_EQ, "/publish");
   6895    version = parse_hs_version_from_post("/tor/hs/18163/publish",prefix, &end);
   6896    tt_int_op(version, OP_EQ, 18163);
   6897    tt_str_op(end, OP_EQ, "/publish");
   6898    version = parse_hs_version_from_post("JUNKJUNKJUNK", prefix, &end);
   6899    tt_int_op(version, OP_EQ, -1);
   6900    tt_ptr_op(end, OP_EQ, NULL);
   6901    version = parse_hs_version_from_post("/tor/hs/3/publish", "blah", &end);
   6902    tt_int_op(version, OP_EQ, -1);
   6903    tt_ptr_op(end, OP_EQ, NULL);
   6904    /* Missing the '/' at the end of the prefix. */
   6905    version = parse_hs_version_from_post("/tor/hs/3/publish", "/tor/hs", &end);
   6906    tt_int_op(version, OP_EQ, -1);
   6907    tt_ptr_op(end, OP_EQ, NULL);
   6908    version = parse_hs_version_from_post("/random/blah/tor/hs/3/publish",
   6909                                         prefix, &end);
   6910    tt_int_op(version, OP_EQ, -1);
   6911    tt_ptr_op(end, OP_EQ, NULL);
   6912    version = parse_hs_version_from_post("/tor/hs/3/publish/random/junk",
   6913                                         prefix, &end);
   6914    tt_int_op(version, OP_EQ, 3);
   6915    tt_str_op(end, OP_EQ, "/publish/random/junk");
   6916    version = parse_hs_version_from_post("/tor/hs/-1/publish", prefix, &end);
   6917    tt_int_op(version, OP_EQ, -1);
   6918    tt_ptr_op(end, OP_EQ, NULL);
   6919    /* INT_MAX */
   6920    version = parse_hs_version_from_post("/tor/hs/2147483647/publish",
   6921                                         prefix, &end);
   6922    tt_int_op(version, OP_EQ, INT_MAX);
   6923    tt_str_op(end, OP_EQ, "/publish");
   6924    /* INT_MAX + 1*/
   6925    version = parse_hs_version_from_post("/tor/hs/2147483648/publish",
   6926                                         prefix, &end);
   6927    tt_int_op(version, OP_EQ, -1);
   6928    tt_ptr_op(end, OP_EQ, NULL);
   6929  }
   6930 
   6931 done:
   6932  ;
   6933 }
   6934 
   6935 static void
   6936 test_dir_platform_str(void *arg)
   6937 {
   6938  char platform[256];
   6939  (void)arg;
   6940  platform[0] = 0;
   6941  get_platform_str(platform, sizeof(platform));
   6942  tt_int_op((int)strlen(platform), OP_GT, 0);
   6943  tt_assert(!strcmpstart(platform, "Tor "));
   6944 
   6945  tor_version_t ver;
   6946  // make sure this is a tor version, a real actual tor version.
   6947  tt_int_op(tor_version_parse_platform(platform, &ver, 1), OP_EQ, 1);
   6948 
   6949  TT_BLATHER(("%d.%d.%d.%d", ver.major, ver.minor, ver.micro, ver.patchlevel));
   6950 
   6951  // Handle an example version.
   6952  tt_int_op(tor_version_parse_platform(
   6953        "Tor 0.3.3.3 (foo) (git-xyzzy) on a potato", &ver, 1), OP_EQ, 1);
   6954 done:
   6955  ;
   6956 }
   6957 
   6958 static void
   6959 test_dir_format_versions_list(void *arg)
   6960 {
   6961  (void)arg;
   6962  char *s = NULL;
   6963  config_line_t *lines = NULL;
   6964 
   6965  setup_capture_of_logs(LOG_WARN);
   6966  s = format_recommended_version_list(lines, 1);
   6967  tt_str_op(s, OP_EQ, "");
   6968 
   6969  tor_free(s);
   6970  config_line_append(&lines, "ignored", "0.3.4.1, 0.2.9.111-alpha, 4.4.4-rc");
   6971  s = format_recommended_version_list(lines, 1);
   6972  tt_str_op(s, OP_EQ,  "0.2.9.111-alpha,0.3.4.1,4.4.4-rc");
   6973 
   6974  tor_free(s);
   6975  config_line_append(&lines, "ignored", "0.1.2.3,0.2.9.10   ");
   6976  s = format_recommended_version_list(lines, 1);
   6977  tt_str_op(s, OP_EQ,  "0.1.2.3,0.2.9.10,0.2.9.111-alpha,0.3.4.1,4.4.4-rc");
   6978 
   6979  /* There should be no warnings so far. */
   6980  expect_no_log_entry();
   6981 
   6982  /* Now try a line with a space in it. */
   6983  tor_free(s);
   6984  config_line_append(&lines, "ignored", "1.3.3.8 1.3.3.7");
   6985  s = format_recommended_version_list(lines, 1);
   6986  tt_str_op(s, OP_EQ,  "0.1.2.3,0.2.9.10,0.2.9.111-alpha,0.3.4.1,"
   6987            "1.3.3.7,1.3.3.8,4.4.4-rc");
   6988 
   6989  expect_single_log_msg_containing(
   6990          "Unexpected space in versions list member \"1.3.3.8 1.3.3.7\"." );
   6991 
   6992  /* Start over, with a line containing a bogus version */
   6993  config_free_lines(lines);
   6994  lines = NULL;
   6995  tor_free(s);
   6996  mock_clean_saved_logs();
   6997  config_line_append(&lines, "ignored", "0.1.2.3, alpha-complex, 0.1.1.8-rc");
   6998  s = format_recommended_version_list(lines,1);
   6999  tt_str_op(s, OP_EQ, "0.1.1.8-rc,0.1.2.3,alpha-complex");
   7000  expect_single_log_msg_containing(
   7001        "Recommended version \"alpha-complex\" does not look valid.");
   7002 
   7003 done:
   7004  tor_free(s);
   7005  config_free_lines(lines);
   7006  teardown_capture_of_logs();
   7007 }
   7008 
   7009 static void
   7010 test_dir_add_fingerprint(void *arg)
   7011 {
   7012  (void)arg;
   7013  authdir_config_t *list;
   7014  int ret;
   7015  ed25519_secret_key_t seckey;
   7016  ed25519_public_key_t pubkey_good, pubkey_bad;
   7017 
   7018  authdir_init_fingerprint_list();
   7019  list = authdir_return_fingerprint_list();
   7020 
   7021  setup_capture_of_logs(LOG_WARN);
   7022 
   7023  /* RSA test - successful */
   7024  ret = add_rsa_fingerprint_to_dir("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
   7025                                   list, 0);
   7026  tt_int_op(ret, OP_EQ, 0);
   7027 
   7028  /* RSA test - failure */
   7029  ret = add_rsa_fingerprint_to_dir("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
   7030                                   list, 0);
   7031  tt_int_op(ret, OP_EQ, -1);
   7032 
   7033  /* ed25519 test - successful */
   7034  ed25519_secret_key_generate(&seckey, 0);
   7035  ed25519_public_key_generate(&pubkey_good, &seckey);
   7036 
   7037  ret = add_ed25519_to_dir(&pubkey_good, list, 0);
   7038  tt_int_op(ret, OP_EQ, 0);
   7039 
   7040  /* ed25519 test - failure */
   7041  digest256_from_base64((char *) pubkey_bad.pubkey, "gibberish");
   7042 
   7043  ret = add_ed25519_to_dir(&pubkey_bad, list, 0);
   7044  tt_int_op(ret, OP_EQ, -1);
   7045 
   7046 done:
   7047  teardown_capture_of_logs();
   7048  dirserv_free_fingerprint_list();
   7049 }
   7050 
   7051 static void
   7052 test_dir_dirserv_load_fingerprint_file(void *arg)
   7053 {
   7054  (void)arg;
   7055  char *fname = tor_strdup(get_fname("approved-routers"));
   7056 
   7057  // Neither RSA nor ed25519
   7058  const char *router_lines_invalid =
   7059    "!badexit notafingerprint";
   7060  const char *router_lines_too_long =
   7061    "!badexit thisisareallylongstringthatislongerthanafingerprint\n";
   7062  const char *router_lines_bad_fmt_str =
   7063    "!badexit ABCDEFGH|%1$p|%2$p|%3$p|%4$p|%5$p|%6$p\n";
   7064  const char *router_lines_valid_rsa =
   7065    "!badexit AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n";
   7066  const char *router_lines_invalid_rsa =
   7067    "!badexit ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ\n";
   7068  const char *router_lines_valid_ed25519 =
   7069    "!badexit wqfLzgfCtRfYNg88LsL1QpzxS0itapJ1aj6TbnByx/Q\n";
   7070  const char *router_lines_invalid_ed25519 =
   7071    "!badexit --fLzgfCtRfYNg88LsL1QpzxS0itapJ1aj6TbnByx--\n";
   7072 
   7073  // Test: Invalid Fingerprint (not RSA or ed25519)
   7074  setup_capture_of_logs(LOG_NOTICE);
   7075  write_str_to_file(fname, router_lines_invalid, 0);
   7076  tt_int_op(dirserv_load_fingerprint_file(), OP_EQ, 0);
   7077  expect_log_msg_containing("Invalid fingerprint");
   7078  teardown_capture_of_logs();
   7079 
   7080  // Test: Very long string (longer than RSA or ed25519 key)
   7081  setup_capture_of_logs(LOG_NOTICE);
   7082  write_str_to_file(fname, router_lines_too_long, 0);
   7083  tt_int_op(dirserv_load_fingerprint_file(), OP_EQ, 0);
   7084  expect_log_msg_containing("Invalid fingerprint");
   7085  teardown_capture_of_logs();
   7086 
   7087  // Test: Format string exploit
   7088  setup_capture_of_logs(LOG_NOTICE);
   7089  write_str_to_file(fname, router_lines_bad_fmt_str, 0);
   7090  tt_int_op(dirserv_load_fingerprint_file(), OP_EQ, 0);
   7091  expect_log_msg_containing("Invalid fingerprint");
   7092  teardown_capture_of_logs();
   7093 
   7094  // Test: Valid RSA
   7095  setup_capture_of_logs(LOG_NOTICE);
   7096  write_str_to_file(fname, router_lines_valid_rsa, 0);
   7097  tt_int_op(dirserv_load_fingerprint_file(), OP_EQ, 0);
   7098  teardown_capture_of_logs();
   7099 
   7100  // Test: Invalid RSA
   7101  setup_capture_of_logs(LOG_NOTICE);
   7102  write_str_to_file(fname, router_lines_invalid_rsa, 0);
   7103  tt_int_op(dirserv_load_fingerprint_file(), OP_EQ, 0);
   7104  expect_log_msg_containing("Invalid fingerprint");
   7105  teardown_capture_of_logs();
   7106 
   7107  // Test: Valid ed25519
   7108  setup_capture_of_logs(LOG_NOTICE);
   7109  write_str_to_file(fname, router_lines_valid_ed25519, 0);
   7110  tt_int_op(dirserv_load_fingerprint_file(), OP_EQ, 0);
   7111  teardown_capture_of_logs();
   7112 
   7113  // Test: Invalid ed25519
   7114  setup_capture_of_logs(LOG_NOTICE);
   7115  write_str_to_file(fname, router_lines_invalid_ed25519, 0);
   7116  tt_int_op(dirserv_load_fingerprint_file(), OP_EQ, 0);
   7117  expect_log_msg_containing("Invalid fingerprint");
   7118  teardown_capture_of_logs();
   7119 
   7120 done:
   7121  tor_free(fname);
   7122  dirserv_free_fingerprint_list();
   7123 }
   7124 
   7125 #define RESET_FP_LIST(list) STMT_BEGIN \
   7126    dirserv_free_fingerprint_list(); \
   7127    authdir_init_fingerprint_list(); \
   7128    list = authdir_return_fingerprint_list(); \
   7129  STMT_END
   7130 
   7131 static void
   7132 test_dir_dirserv_router_get_status(void *arg)
   7133 {
   7134  authdir_config_t *list;
   7135  routerinfo_t *ri = NULL;
   7136  ed25519_keypair_t kp1, kp2;
   7137  char d[DIGEST_LEN];
   7138  char fp[HEX_DIGEST_LEN+1];
   7139  int ret;
   7140  const char *msg;
   7141  time_t now = time(NULL);
   7142 
   7143  (void)arg;
   7144 
   7145  crypto_pk_t *pk = pk_generate(0);
   7146 
   7147  authdir_init_fingerprint_list();
   7148  list = authdir_return_fingerprint_list();
   7149 
   7150  /* Set up the routerinfo */
   7151  ri = tor_malloc_zero(sizeof(routerinfo_t));
   7152  tor_addr_from_ipv4h(&ri->ipv4_addr, 0xc0a80001u);
   7153  ri->ipv4_orport = 9001;
   7154  ri->platform = tor_strdup("0.4.0.1-alpha");
   7155  ri->nickname = tor_strdup("Jessica");
   7156  ri->identity_pkey = crypto_pk_dup_key(pk);
   7157 
   7158  curve25519_keypair_t ri_onion_keypair;
   7159  curve25519_keypair_generate(&ri_onion_keypair, 0);
   7160  ri->onion_curve25519_pkey = tor_memdup(&ri_onion_keypair.pubkey,
   7161                                         sizeof(curve25519_public_key_t));
   7162 
   7163  ed25519_secret_key_from_seed(&kp1.seckey,
   7164                          (const uint8_t*)"YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY");
   7165  ed25519_public_key_generate(&kp1.pubkey, &kp1.seckey);
   7166  ed25519_secret_key_from_seed(&kp2.seckey,
   7167                          (const uint8_t*)"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
   7168  ed25519_public_key_generate(&kp2.pubkey, &kp2.seckey);
   7169  ri->cache_info.signing_key_cert = tor_cert_create_ed25519(&kp1,
   7170                                         CERT_TYPE_ID_SIGNING,
   7171                                         &kp2.pubkey,
   7172                                         now, 86400,
   7173                                         CERT_FLAG_INCLUDE_SIGNING_KEY);
   7174 
   7175  crypto_pk_get_digest(ri->identity_pkey, d);
   7176  base16_encode(fp, HEX_DIGEST_LEN + 1, d, DIGEST_LEN);
   7177 
   7178  /* Try on an empty fingerprint list */
   7179  ret = dirserv_router_get_status(ri, &msg, LOG_INFO);
   7180  tt_int_op(ret, OP_EQ, 0);
   7181  RESET_FP_LIST(list);
   7182 
   7183  ret = dirserv_router_get_status(ri, &msg, LOG_INFO);
   7184  tt_int_op(ret, OP_EQ, 0);
   7185  RESET_FP_LIST(list);
   7186 
   7187  /* Try an accepted router */
   7188  add_rsa_fingerprint_to_dir(fp, list, 0);
   7189  ret = dirserv_router_get_status(ri, &msg, LOG_INFO);
   7190  tt_int_op(ret, OP_EQ, 0);
   7191  RESET_FP_LIST(list);
   7192 
   7193  add_ed25519_to_dir(&kp1.pubkey, list, 0);
   7194  ret = dirserv_router_get_status(ri, &msg, LOG_INFO);
   7195  tt_int_op(ret, OP_EQ, 0);
   7196  RESET_FP_LIST(list);
   7197 
   7198  /* Try a rejected router */
   7199  add_rsa_fingerprint_to_dir(fp, list, RTR_REJECT);
   7200  ret = dirserv_router_get_status(ri, &msg, LOG_INFO);
   7201  tt_int_op(ret, OP_EQ, RTR_REJECT);
   7202  RESET_FP_LIST(list);
   7203 
   7204  add_ed25519_to_dir(&kp1.pubkey, list, RTR_REJECT);
   7205  ret = dirserv_router_get_status(ri, &msg, LOG_INFO);
   7206  tt_int_op(ret, OP_EQ, RTR_REJECT);
   7207  RESET_FP_LIST(list);
   7208 
   7209 done:
   7210  dirserv_free_fingerprint_list();
   7211  routerinfo_free(ri);
   7212  crypto_pk_free(pk);
   7213 }
   7214 
   7215 static void
   7216 test_dir_dirserv_would_reject_router(void *arg)
   7217 {
   7218  authdir_config_t *list;
   7219  routerstatus_t rs;
   7220  vote_routerstatus_t vrs;
   7221  ed25519_keypair_t kp;
   7222  char fp[HEX_DIGEST_LEN+1];
   7223 
   7224  (void)arg;
   7225 
   7226  authdir_init_fingerprint_list();
   7227  list = authdir_return_fingerprint_list();
   7228 
   7229  /* Set up the routerstatus */
   7230  memset(&rs, 0, sizeof(rs));
   7231  tor_addr_from_ipv4h(&rs.ipv4_addr, 0xc0a80001u);
   7232  rs.ipv4_orport = 9001;
   7233  strlcpy(rs.nickname, "Nicole", sizeof(rs.nickname));
   7234  memcpy(rs.identity_digest, "Cloud nine is great ", DIGEST_LEN);
   7235 
   7236  ed25519_secret_key_from_seed(&kp.seckey,
   7237                          (const uint8_t*)"YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY");
   7238  ed25519_public_key_generate(&kp.pubkey, &kp.seckey);
   7239 
   7240  base16_encode(fp, HEX_DIGEST_LEN + 1, rs.identity_digest, DIGEST_LEN);
   7241 
   7242  /* Setup the vote_routerstatus_t. */
   7243  memcpy(vrs.ed25519_id, &kp.pubkey, ED25519_PUBKEY_LEN);
   7244 
   7245  /* Try an empty fingerprint list */
   7246  tt_assert(!dirserv_would_reject_router(&rs, &vrs));
   7247  RESET_FP_LIST(list);
   7248 
   7249  tt_assert(!dirserv_would_reject_router(&rs, &vrs));
   7250  RESET_FP_LIST(list);
   7251 
   7252  /* Try an accepted router */
   7253  add_rsa_fingerprint_to_dir(fp, list, 0);
   7254  tt_assert(!dirserv_would_reject_router(&rs, &vrs));
   7255  RESET_FP_LIST(list);
   7256 
   7257  add_ed25519_to_dir(&kp.pubkey, list, 0);
   7258  tt_assert(!dirserv_would_reject_router(&rs, &vrs));
   7259  RESET_FP_LIST(list);
   7260 
   7261  /* Try a rejected router */
   7262  add_rsa_fingerprint_to_dir(fp, list, RTR_REJECT);
   7263  tt_assert(dirserv_would_reject_router(&rs, &vrs));
   7264  RESET_FP_LIST(list);
   7265 
   7266  add_ed25519_to_dir(&kp.pubkey, list, RTR_REJECT);
   7267  tt_assert(dirserv_would_reject_router(&rs, &vrs));
   7268  RESET_FP_LIST(list);
   7269 
   7270 done:
   7271  dirserv_free_fingerprint_list();
   7272 }
   7273 
   7274 static void
   7275 test_dir_dirserv_add_own_fingerprint(void *arg)
   7276 {
   7277  authdir_config_t *list;
   7278  char digest[DIGEST_LEN];
   7279  crypto_pk_t *pk = pk_generate(0);
   7280 
   7281  (void)arg;
   7282 
   7283  init_mock_ed_keys(pk);
   7284  authdir_init_fingerprint_list();
   7285  list = authdir_return_fingerprint_list();
   7286  dirserv_add_own_fingerprint(pk, get_master_identity_key());
   7287 
   7288  /* Check if we have a RSA key. */
   7289  crypto_pk_get_digest(pk, digest);
   7290  tt_assert(digestmap_get(list->status_by_digest, digest));
   7291 
   7292  /* Check if we have a ed25519 key. */
   7293  tt_assert(digest256map_get(list->status_by_digest256,
   7294                             get_master_identity_key()->pubkey));
   7295 
   7296  RESET_FP_LIST(list);
   7297 
   7298 done:
   7299  dirserv_free_fingerprint_list();
   7300  crypto_pk_free(pk);
   7301 }
   7302 
   7303 static void
   7304 test_dir_parse_family_cert(void *arg)
   7305 {
   7306  (void)arg;
   7307  ed25519_keypair_t kp_family;
   7308  ed25519_keypair_t kp_id;
   7309  char family_b64[ED25519_BASE64_LEN+1];
   7310  tor_cert_t *cert = NULL;
   7311  int r;
   7312 
   7313  time_t now = 1739288377;
   7314  time_t lifetime = 86400;
   7315  time_t got_expiration = -1;
   7316  char *got_family_id = NULL;
   7317  char *expect_family_id = NULL;
   7318 
   7319  setup_capture_of_logs(LOG_WARN);
   7320 
   7321  ed25519_keypair_generate(&kp_family, 0);
   7322  ed25519_keypair_generate(&kp_id, 0);
   7323  ed25519_public_to_base64(family_b64, &kp_family.pubkey);
   7324  tor_asprintf(&expect_family_id, "ed25519:%s", family_b64);
   7325 
   7326  // Wrong type.
   7327  cert = tor_cert_create_ed25519(&kp_family,
   7328                                 CERT_TYPE_ID_SIGNING,
   7329                                 &kp_id.pubkey,
   7330                                 now, lifetime,
   7331                                 CERT_FLAG_INCLUDE_SIGNING_KEY);
   7332  tt_assert(cert);
   7333  r = check_one_family_cert(cert->encoded, cert->encoded_len,
   7334                            &kp_id.pubkey,
   7335                            &got_family_id,
   7336                            &got_expiration);
   7337  tt_ptr_op(got_family_id, OP_EQ, NULL);
   7338  tt_int_op(r, OP_EQ, -1);
   7339  expect_single_log_msg_containing("Wrong cert type");
   7340  mock_clean_saved_logs();
   7341  tor_cert_free(cert);
   7342 
   7343  // Family key not included.
   7344  cert = tor_cert_create_ed25519(&kp_family,
   7345                                 CERT_TYPE_FAMILY_V_IDENTITY,
   7346                                 &kp_id.pubkey,
   7347                                 now, lifetime,
   7348                                 0);
   7349  tt_assert(cert);
   7350  r = check_one_family_cert(cert->encoded, cert->encoded_len,
   7351                            &kp_id.pubkey,
   7352                            &got_family_id,
   7353                            &got_expiration);
   7354  tt_ptr_op(got_family_id, OP_EQ, NULL);
   7355  tt_int_op(r, OP_EQ, -1);
   7356  expect_single_log_msg_containing("Missing family key");
   7357  mock_clean_saved_logs();
   7358  tor_cert_free(cert);
   7359 
   7360  // Certified key isn't correct
   7361  cert = tor_cert_create_ed25519(&kp_family,
   7362                                 CERT_TYPE_FAMILY_V_IDENTITY,
   7363                                 &kp_family.pubkey,
   7364                                 now, lifetime,
   7365                                 CERT_FLAG_INCLUDE_SIGNING_KEY);
   7366  tt_assert(cert);
   7367  r = check_one_family_cert(cert->encoded, cert->encoded_len,
   7368                            &kp_id.pubkey,
   7369                            &got_family_id,
   7370                            &got_expiration);
   7371  tt_ptr_op(got_family_id, OP_EQ, NULL);
   7372  tt_int_op(r, OP_EQ, -1);
   7373  expect_single_log_msg_containing("Key mismatch");
   7374  mock_clean_saved_logs();
   7375  tor_cert_free(cert);
   7376 
   7377  // Signature is bogus.
   7378  cert = tor_cert_create_ed25519(&kp_family,
   7379                                 CERT_TYPE_FAMILY_V_IDENTITY,
   7380                                 &kp_id.pubkey,
   7381                                 now, lifetime,
   7382                                 CERT_FLAG_INCLUDE_SIGNING_KEY);
   7383  tt_assert(cert);
   7384  cert->encoded[cert->encoded_len-1] ^= 0x77; // corrupt the signature
   7385  r = check_one_family_cert(cert->encoded, cert->encoded_len,
   7386                            &kp_id.pubkey,
   7387                            &got_family_id,
   7388                            &got_expiration);
   7389  tt_ptr_op(got_family_id, OP_EQ, NULL);
   7390  tt_int_op(r, OP_EQ, -1);
   7391  expect_single_log_msg_containing("Invalid signature");
   7392  mock_clean_saved_logs();
   7393  tor_cert_free(cert);
   7394 
   7395  // Everything is okay!
   7396  cert = tor_cert_create_ed25519(&kp_family,
   7397                                 CERT_TYPE_FAMILY_V_IDENTITY,
   7398                                 &kp_id.pubkey,
   7399                                 now, lifetime,
   7400                                 CERT_FLAG_INCLUDE_SIGNING_KEY);
   7401  tt_assert(cert);
   7402  got_expiration = -1;
   7403  r = check_one_family_cert(cert->encoded, cert->encoded_len,
   7404                            &kp_id.pubkey,
   7405                            &got_family_id,
   7406                            &got_expiration);
   7407  expect_no_log_entry();
   7408  tt_int_op(r, OP_EQ, 0);
   7409  tt_int_op(got_expiration, OP_NE, -1);
   7410  // Cert expirations have 1-hour granularity
   7411  tt_int_op(got_expiration, OP_GE, now + lifetime);
   7412  tt_int_op(got_expiration, OP_LT, now + lifetime + 3601);
   7413  tt_str_op(got_family_id, OP_EQ, expect_family_id);
   7414  tt_assert(!strchr(got_family_id, '=')); // not family
   7415 
   7416 done:
   7417  tor_cert_free(cert);
   7418  tor_free(got_family_id);
   7419  tor_free(expect_family_id);
   7420  teardown_capture_of_logs();
   7421 }
   7422 
   7423 #ifndef COCCI
   7424 #define DIR_LEGACY(name)                             \
   7425  { #name, test_dir_ ## name , TT_FORK, NULL, NULL }
   7426 
   7427 #define DIR(name,flags)                              \
   7428  { #name, test_dir_##name, (flags), NULL, NULL }
   7429 
   7430 /* where arg is a string constant */
   7431 #define DIR_ARG(name,flags,arg)                      \
   7432  { #name "_" arg, test_dir_##name, (flags), &passthrough_setup, (void*) arg }
   7433 #endif /* !defined(COCCI) */
   7434 
   7435 struct testcase_t dir_tests[] = {
   7436  DIR_LEGACY(nicknames),
   7437  /* extrainfo without any stats */
   7438  DIR_ARG(formats_rsa_ed25519, TT_FORK, ""),
   7439  /* on a bridge */
   7440  DIR_ARG(formats_rsa_ed25519, TT_FORK, "b"),
   7441  /* extrainfo with basic stats */
   7442  DIR_ARG(formats_rsa_ed25519, TT_FORK, "e"),
   7443  DIR_ARG(formats_rsa_ed25519, TT_FORK, "be"),
   7444  /* extrainfo with all stats */
   7445  DIR_ARG(formats_rsa_ed25519, TT_FORK, "es"),
   7446  DIR_ARG(formats_rsa_ed25519, TT_FORK, "bes"),
   7447  DIR(routerinfo_parsing, 0),
   7448  DIR(extrainfo_parsing, 0),
   7449  DIR(parse_router_list, TT_FORK),
   7450  DIR(parse_no_onion_keyrouter_list, TT_FORK),
   7451  DIR(load_routers, TT_FORK),
   7452  DIR(load_extrainfo, TT_FORK),
   7453  DIR(getinfo_extra, 0),
   7454  DIR_LEGACY(versions),
   7455  DIR_LEGACY(fp_pairs),
   7456  DIR(split_fps, 0),
   7457  DIR_LEGACY(measured_bw_kb),
   7458  DIR_LEGACY(measured_bw_kb_line_is_after_headers),
   7459  DIR_LEGACY(measured_bw_kb_cache),
   7460  DIR_LEGACY(dirserv_read_measured_bandwidths),
   7461  DIR(bwauth_bw_file_digest256, 0),
   7462  DIR_LEGACY(param_voting),
   7463  DIR(param_voting_lookup, 0),
   7464  DIR_LEGACY(v3_networkstatus),
   7465  DIR(random_weighted, 0),
   7466  DIR(scale_bw, 0),
   7467  DIR_LEGACY(clip_unmeasured_bw_kb),
   7468  DIR_LEGACY(clip_unmeasured_bw_kb_alt),
   7469  DIR(fmt_control_ns, 0),
   7470  DIR(dirserv_set_routerstatus_testing, TT_FORK),
   7471  DIR(http_handling, 0),
   7472  DIR(purpose_needs_anonymity_returns_true_for_bridges, 0),
   7473  DIR(purpose_needs_anonymity_returns_false_for_own_bridge_desc, 0),
   7474  DIR(purpose_needs_anonymity_returns_true_by_default, 0),
   7475  DIR(purpose_needs_anonymity_ret_false_for_non_sensitive_conn, 0),
   7476  DIR(post_parsing, 0),
   7477  DIR(fetch_type, 0),
   7478  DIR(packages, 0),
   7479  DIR(download_status_random_backoff, 0),
   7480  DIR(download_status_random_backoff_ranges, 0),
   7481  DIR(download_status_increment, TT_FORK),
   7482  DIR(authdir_type_to_string, 0),
   7483  DIR(conn_purpose_to_string, 0),
   7484  DIR(should_use_directory_guards, 0),
   7485  DIR(should_not_init_request_to_ourselves, TT_FORK),
   7486  DIR(should_not_init_request_to_dir_auths_without_v3_info, 0),
   7487  DIR(should_init_request_to_dir_auths, 0),
   7488  DIR(dump_unparseable_descriptors, 0),
   7489  DIR(populate_dump_desc_fifo, 0),
   7490  DIR(populate_dump_desc_fifo_2, 0),
   7491  DIR_ARG(find_dl_min_delay, TT_FORK, "bfd"),
   7492  DIR_ARG(find_dl_min_delay, TT_FORK, "bad"),
   7493  DIR_ARG(find_dl_min_delay, TT_FORK, "cfd"),
   7494  DIR_ARG(find_dl_min_delay, TT_FORK, "cad"),
   7495  DIR_ARG(find_dl_min_delay, TT_FORK, "bfr"),
   7496  DIR_ARG(find_dl_min_delay, TT_FORK, "bar"),
   7497  DIR_ARG(find_dl_min_delay, TT_FORK, "cfr"),
   7498  DIR_ARG(find_dl_min_delay, TT_FORK, "car"),
   7499  DIR(assumed_flags, 0),
   7500  DIR(matching_flags, 0),
   7501  DIR(networkstatus_compute_bw_weights_v10, 0),
   7502  DIR(platform_str, 0),
   7503  DIR(format_versions_list, TT_FORK),
   7504  DIR(add_fingerprint, TT_FORK),
   7505  DIR(dirserv_load_fingerprint_file, TT_FORK),
   7506  DIR(dirserv_router_get_status, TT_FORK),
   7507  DIR(dirserv_would_reject_router, TT_FORK),
   7508  DIR(dirserv_add_own_fingerprint, TT_FORK),
   7509  DIR(parse_family_cert, TT_FORK),
   7510  END_OF_TESTCASES
   7511 };