tor

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

dirvote.c (177663B)


      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 #define DIRVOTE_PRIVATE
      7 
      8 #include "core/or/or.h"
      9 #include "app/config/config.h"
     10 #include "app/config/resolve_addr.h"
     11 #include "core/or/policies.h"
     12 #include "core/or/protover.h"
     13 #include "core/or/tor_version_st.h"
     14 #include "core/or/versions.h"
     15 #include "feature/dirauth/bwauth.h"
     16 #include "feature/dirauth/dircollate.h"
     17 #include "feature/dirauth/dsigs_parse.h"
     18 #include "feature/dirauth/guardfraction.h"
     19 #include "feature/dirauth/recommend_pkg.h"
     20 #include "feature/dirauth/voteflags.h"
     21 #include "feature/dircache/dirserv.h"
     22 #include "feature/dirclient/dirclient.h"
     23 #include "feature/dircommon/directory.h"
     24 #include "feature/dirparse/microdesc_parse.h"
     25 #include "feature/dirparse/ns_parse.h"
     26 #include "feature/dirparse/parsecommon.h"
     27 #include "feature/dirparse/signing.h"
     28 #include "feature/nodelist/authcert.h"
     29 #include "feature/nodelist/dirlist.h"
     30 #include "feature/nodelist/fmt_routerstatus.h"
     31 #include "feature/nodelist/microdesc.h"
     32 #include "feature/nodelist/networkstatus.h"
     33 #include "feature/nodelist/nodefamily.h"
     34 #include "feature/nodelist/nodelist.h"
     35 #include "feature/nodelist/routerlist.h"
     36 #include "feature/relay/router.h"
     37 #include "feature/relay/routerkeys.h"
     38 #include "feature/stats/rephist.h"
     39 #include "feature/client/entrynodes.h" /* needed for guardfraction methods */
     40 #include "feature/nodelist/torcert.h"
     41 #include "feature/dirauth/voting_schedule.h"
     42 
     43 #include "feature/dirauth/dirvote.h"
     44 #include "feature/dirauth/authmode.h"
     45 #include "feature/dirauth/shared_random_state.h"
     46 #include "feature/dirauth/dirauth_sys.h"
     47 
     48 #include "feature/nodelist/authority_cert_st.h"
     49 #include "feature/dircache/cached_dir_st.h"
     50 #include "feature/dirclient/dir_server_st.h"
     51 #include "feature/dirauth/dirauth_options_st.h"
     52 #include "feature/nodelist/document_signature_st.h"
     53 #include "feature/nodelist/microdesc_st.h"
     54 #include "feature/nodelist/networkstatus_st.h"
     55 #include "feature/nodelist/networkstatus_voter_info_st.h"
     56 #include "feature/nodelist/node_st.h"
     57 #include "feature/dirauth/ns_detached_signatures_st.h"
     58 #include "feature/nodelist/routerinfo_st.h"
     59 #include "feature/nodelist/routerlist_st.h"
     60 #include "feature/dirauth/vote_microdesc_hash_st.h"
     61 #include "feature/nodelist/vote_routerstatus_st.h"
     62 #include "feature/dircommon/vote_timing_st.h"
     63 
     64 #include "lib/container/order.h"
     65 #include "lib/encoding/confline.h"
     66 #include "lib/crypt_ops/crypto_format.h"
     67 
     68 /* Algorithm to use for the bandwidth file digest. */
     69 #define DIGEST_ALG_BW_FILE DIGEST_SHA256
     70 
     71 /**
     72 * \file dirvote.c
     73 * \brief Functions to compute directory consensus, and schedule voting.
     74 *
     75 * This module is the center of the consensus-voting based directory
     76 * authority system.  With this system, a set of authorities first
     77 * publish vote based on their opinions of the network, and then compute
     78 * a consensus from those votes.  Each authority signs the consensus,
     79 * and clients trust the consensus if enough known authorities have
     80 * signed it.
     81 *
     82 * The code in this module is only invoked on directory authorities.  It's
     83 * responsible for:
     84 *
     85 * <ul>
     86 *   <li>Generating this authority's vote networkstatus, based on the
     87 *       authority's view of the network as represented in dirserv.c
     88 *   <li>Formatting the vote networkstatus objects.
     89 *   <li>Generating the microdescriptors that correspond to our own
     90 *       vote.
     91 *   <li>Sending votes to all the other authorities.
     92 *   <li>Trying to fetch missing votes from other authorities.
     93 *   <li>Computing the consensus from a set of votes, as well as
     94 *       a "detached signature" object for other authorities to fetch.
     95 *   <li>Collecting other authorities' signatures on the same consensus,
     96 *       until there are enough.
     97 *   <li>Publishing the consensus to the reset of the directory system.
     98 *   <li>Scheduling all of the above operations.
     99 * </ul>
    100 *
    101 * The main entry points are in dirvote_act(), which handles scheduled
    102 * actions; and dirvote_add_vote() and dirvote_add_signatures(), which
    103 * handle uploaded and downloaded votes and signatures.
    104 *
    105 * (See dir-spec.txt from torspec.git for a complete specification of
    106 * the directory protocol and voting algorithms.)
    107 **/
    108 
    109 /** A consensus that we have built and are appending signatures to.  Once it's
    110 * time to publish it, it will become an active consensus if it accumulates
    111 * enough signatures. */
    112 typedef struct pending_consensus_t {
    113  /** The body of the consensus that we're currently building.  Once we
    114   * have it built, it goes into dirserv.c */
    115  char *body;
    116  /** The parsed in-progress consensus document. */
    117  networkstatus_t *consensus;
    118  /** Have we reached the critical number of sigs on this consensus, and
    119   * exported it for the consensus transparency module? */
    120  bool have_exported_for_transparency;
    121 } pending_consensus_t;
    122 
    123 /* DOCDOC dirvote_add_signatures_to_all_pending_consensuses */
    124 static int dirvote_add_signatures_to_all_pending_consensuses(
    125                       const char *detached_signatures_body,
    126                       const char *source,
    127                       const char **msg_out);
    128 static int dirvote_add_signatures_to_pending_consensus(
    129                       pending_consensus_t *pc,
    130                       ns_detached_signatures_t *sigs,
    131                       const char *source,
    132                       int severity,
    133                       const char **msg_out);
    134 static char *list_v3_auth_ids(void);
    135 static void dirvote_fetch_missing_votes(void);
    136 static void dirvote_fetch_missing_signatures(void);
    137 static int dirvote_perform_vote(void);
    138 static void dirvote_clear_votes(int all_votes);
    139 static int dirvote_compute_consensuses(void);
    140 static int dirvote_publish_consensus(void);
    141 
    142 /* =====
    143 * Certificate functions
    144 * ===== */
    145 
    146 /** Allocate and return a new authority_cert_t with the same contents as
    147 * <b>cert</b>. */
    148 STATIC authority_cert_t *
    149 authority_cert_dup(authority_cert_t *cert)
    150 {
    151  authority_cert_t *out = tor_malloc(sizeof(authority_cert_t));
    152  tor_assert(cert);
    153 
    154  memcpy(out, cert, sizeof(authority_cert_t));
    155  /* Now copy pointed-to things. */
    156  out->cache_info.signed_descriptor_body =
    157    tor_strndup(cert->cache_info.signed_descriptor_body,
    158                cert->cache_info.signed_descriptor_len);
    159  out->cache_info.saved_location = SAVED_NOWHERE;
    160  out->identity_key = crypto_pk_dup_key(cert->identity_key);
    161  out->signing_key = crypto_pk_dup_key(cert->signing_key);
    162 
    163  return out;
    164 }
    165 
    166 /* =====
    167 * Voting
    168 * =====*/
    169 
    170 /* If <b>opt_value</b> is non-NULL, return "keyword opt_value\n" in a new
    171 * string. Otherwise return a new empty string. */
    172 static char *
    173 format_line_if_present(const char *keyword, const char *opt_value)
    174 {
    175  if (opt_value) {
    176    char *result = NULL;
    177    tor_asprintf(&result, "%s %s\n", keyword, opt_value);
    178    return result;
    179  } else {
    180    return tor_strdup("");
    181  }
    182 }
    183 
    184 /** Format the recommended/required-relay-client protocols lines for a vote in
    185 * a newly allocated string, and return that string. */
    186 static char *
    187 format_protocols_lines_for_vote(const networkstatus_t *v3_ns)
    188 {
    189  char *recommended_relay_protocols_line = NULL;
    190  char *recommended_client_protocols_line = NULL;
    191  char *required_relay_protocols_line = NULL;
    192  char *required_client_protocols_line = NULL;
    193 
    194  recommended_relay_protocols_line =
    195    format_line_if_present("recommended-relay-protocols",
    196                           v3_ns->recommended_relay_protocols);
    197  recommended_client_protocols_line =
    198    format_line_if_present("recommended-client-protocols",
    199                           v3_ns->recommended_client_protocols);
    200  required_relay_protocols_line =
    201    format_line_if_present("required-relay-protocols",
    202                           v3_ns->required_relay_protocols);
    203  required_client_protocols_line =
    204    format_line_if_present("required-client-protocols",
    205                           v3_ns->required_client_protocols);
    206 
    207  char *result = NULL;
    208  tor_asprintf(&result, "%s%s%s%s",
    209               recommended_relay_protocols_line,
    210               recommended_client_protocols_line,
    211               required_relay_protocols_line,
    212               required_client_protocols_line);
    213 
    214  tor_free(recommended_relay_protocols_line);
    215  tor_free(recommended_client_protocols_line);
    216  tor_free(required_relay_protocols_line);
    217  tor_free(required_client_protocols_line);
    218 
    219  return result;
    220 }
    221 
    222 /** Return a new string containing the string representation of the vote in
    223 * <b>v3_ns</b>, signed with our v3 signing key <b>private_signing_key</b>.
    224 * For v3 authorities. */
    225 STATIC char *
    226 format_networkstatus_vote(crypto_pk_t *private_signing_key,
    227                          networkstatus_t *v3_ns)
    228 {
    229  smartlist_t *chunks = smartlist_new();
    230  char fingerprint[FINGERPRINT_LEN+1];
    231  char digest[DIGEST_LEN];
    232  char *protocols_lines = NULL;
    233  char *client_versions_line = NULL, *server_versions_line = NULL;
    234  char *shared_random_vote_str = NULL;
    235  networkstatus_voter_info_t *voter;
    236  char *status = NULL;
    237 
    238  tor_assert(private_signing_key);
    239  tor_assert(v3_ns->type == NS_TYPE_VOTE || v3_ns->type == NS_TYPE_OPINION);
    240 
    241  voter = smartlist_get(v3_ns->voters, 0);
    242 
    243  base16_encode(fingerprint, sizeof(fingerprint),
    244                v3_ns->cert->cache_info.identity_digest, DIGEST_LEN);
    245 
    246  client_versions_line = format_line_if_present("client-versions",
    247                                                v3_ns->client_versions);
    248  server_versions_line = format_line_if_present("server-versions",
    249                                                v3_ns->server_versions);
    250  protocols_lines = format_protocols_lines_for_vote(v3_ns);
    251 
    252    /* Get shared random commitments/reveals line(s). */
    253  shared_random_vote_str = sr_get_string_for_vote();
    254 
    255  {
    256    char published[ISO_TIME_LEN+1];
    257    char va[ISO_TIME_LEN+1];
    258    char fu[ISO_TIME_LEN+1];
    259    char vu[ISO_TIME_LEN+1];
    260    char *flags = smartlist_join_strings(v3_ns->known_flags, " ", 0, NULL);
    261    /* XXXX Abstraction violation: should be pulling a field out of v3_ns.*/
    262    char *flag_thresholds = dirserv_get_flag_thresholds_line();
    263    char *params;
    264    char *bw_headers_line = NULL;
    265    char *bw_file_digest = NULL;
    266    authority_cert_t *cert = v3_ns->cert;
    267    char *methods =
    268      make_consensus_method_list(MIN_SUPPORTED_CONSENSUS_METHOD,
    269                                 MAX_SUPPORTED_CONSENSUS_METHOD, " ");
    270    format_iso_time(published, v3_ns->published);
    271    format_iso_time(va, v3_ns->valid_after);
    272    format_iso_time(fu, v3_ns->fresh_until);
    273    format_iso_time(vu, v3_ns->valid_until);
    274 
    275    if (v3_ns->net_params)
    276      params = smartlist_join_strings(v3_ns->net_params, " ", 0, NULL);
    277    else
    278      params = tor_strdup("");
    279    tor_assert(cert);
    280 
    281    /* v3_ns->bw_file_headers is only set when V3BandwidthsFile is
    282     * configured */
    283    if (v3_ns->bw_file_headers) {
    284      char *bw_file_headers = NULL;
    285      /* If there are too many headers, leave the header string NULL */
    286      if (! BUG(smartlist_len(v3_ns->bw_file_headers)
    287                > MAX_BW_FILE_HEADER_COUNT_IN_VOTE)) {
    288        bw_file_headers = smartlist_join_strings(v3_ns->bw_file_headers, " ",
    289                                                 0, NULL);
    290        if (BUG(strlen(bw_file_headers) > MAX_BW_FILE_HEADERS_LINE_LEN)) {
    291          /* Free and set to NULL, because the line was too long */
    292          tor_free(bw_file_headers);
    293        }
    294      }
    295      if (!bw_file_headers) {
    296          /* If parsing failed, add a bandwidth header line with no entries */
    297          bw_file_headers = tor_strdup("");
    298      }
    299      /* At this point, the line will always be present */
    300      bw_headers_line = format_line_if_present("bandwidth-file-headers",
    301                                               bw_file_headers);
    302      tor_free(bw_file_headers);
    303    }
    304 
    305    /* Create bandwidth-file-digest if applicable.
    306     * v3_ns->b64_digest_bw_file will contain the digest when V3BandwidthsFile
    307     * is configured and the bandwidth file could be read, even if it was not
    308     * parseable.
    309     */
    310    if (!tor_digest256_is_zero((const char *)v3_ns->bw_file_digest256)) {
    311      /* Encode the digest. */
    312      char b64_digest_bw_file[BASE64_DIGEST256_LEN+1] = {0};
    313      digest256_to_base64(b64_digest_bw_file,
    314                          (const char *)v3_ns->bw_file_digest256);
    315      /* "bandwidth-file-digest" 1*(SP algorithm "=" digest) NL */
    316      char *digest_algo_b64_digest_bw_file = NULL;
    317      tor_asprintf(&digest_algo_b64_digest_bw_file, "%s=%s",
    318                   crypto_digest_algorithm_get_name(DIGEST_ALG_BW_FILE),
    319                   b64_digest_bw_file);
    320      /* No need for tor_strdup(""), format_line_if_present does it. */
    321      bw_file_digest = format_line_if_present(
    322          "bandwidth-file-digest", digest_algo_b64_digest_bw_file);
    323      tor_free(digest_algo_b64_digest_bw_file);
    324    }
    325 
    326    const char *ip_str = fmt_addr(&voter->ipv4_addr);
    327 
    328    if (ip_str[0]) {
    329      smartlist_add_asprintf(chunks,
    330                   "network-status-version 3\n"
    331                   "vote-status %s\n"
    332                   "consensus-methods %s\n"
    333                   "published %s\n"
    334                   "valid-after %s\n"
    335                   "fresh-until %s\n"
    336                   "valid-until %s\n"
    337                   "voting-delay %d %d\n"
    338                   "%s%s" /* versions */
    339                   "%s" /* protocols */
    340                   "known-flags %s\n"
    341                   "flag-thresholds %s\n"
    342                   "params %s\n"
    343                   "%s" /* bandwidth file headers */
    344                   "%s" /* bandwidth file digest */
    345                   "dir-source %s %s %s %s %d %d\n"
    346                   "contact %s\n"
    347                   "%s" /* shared randomness information */
    348                   ,
    349                   v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion",
    350                   methods,
    351                   published, va, fu, vu,
    352                   v3_ns->vote_seconds, v3_ns->dist_seconds,
    353                   client_versions_line,
    354                   server_versions_line,
    355                   protocols_lines,
    356                   flags,
    357                   flag_thresholds,
    358                   params,
    359                   bw_headers_line ? bw_headers_line : "",
    360                   bw_file_digest ? bw_file_digest: "",
    361                   voter->nickname, fingerprint, voter->address,
    362                   ip_str, voter->ipv4_dirport, voter->ipv4_orport,
    363                   voter->contact,
    364                   shared_random_vote_str ?
    365                             shared_random_vote_str : "");
    366    }
    367 
    368    tor_free(params);
    369    tor_free(flags);
    370    tor_free(flag_thresholds);
    371    tor_free(methods);
    372    tor_free(shared_random_vote_str);
    373    tor_free(bw_headers_line);
    374    tor_free(bw_file_digest);
    375 
    376    if (ip_str[0] == '\0')
    377      goto err;
    378 
    379    if (!tor_digest_is_zero(voter->legacy_id_digest)) {
    380      char fpbuf[HEX_DIGEST_LEN+1];
    381      base16_encode(fpbuf, sizeof(fpbuf), voter->legacy_id_digest, DIGEST_LEN);
    382      smartlist_add_asprintf(chunks, "legacy-dir-key %s\n", fpbuf);
    383    }
    384 
    385    smartlist_add(chunks, tor_strndup(cert->cache_info.signed_descriptor_body,
    386                                      cert->cache_info.signed_descriptor_len));
    387  }
    388 
    389  SMARTLIST_FOREACH_BEGIN(v3_ns->routerstatus_list, vote_routerstatus_t *,
    390                          vrs) {
    391    char *rsf;
    392    vote_microdesc_hash_t *h;
    393    rsf = routerstatus_format_entry(&vrs->status,
    394                                    vrs->version, vrs->protocols,
    395                                    NS_V3_VOTE,
    396                                    vrs,
    397                                    -1);
    398    if (rsf)
    399      smartlist_add(chunks, rsf);
    400 
    401    for (h = vrs->microdesc; h; h = h->next) {
    402      smartlist_add_strdup(chunks, h->microdesc_hash_line);
    403    }
    404  } SMARTLIST_FOREACH_END(vrs);
    405 
    406  smartlist_add_strdup(chunks, "directory-footer\n");
    407 
    408  /* The digest includes everything up through the space after
    409   * directory-signature.  (Yuck.) */
    410  crypto_digest_smartlist(digest, DIGEST_LEN, chunks,
    411                          "directory-signature ", DIGEST_SHA1);
    412 
    413  {
    414    char signing_key_fingerprint[FINGERPRINT_LEN+1];
    415    if (crypto_pk_get_fingerprint(private_signing_key,
    416                                  signing_key_fingerprint, 0)<0) {
    417      log_warn(LD_BUG, "Unable to get fingerprint for signing key");
    418      goto err;
    419    }
    420 
    421    smartlist_add_asprintf(chunks, "directory-signature %s %s\n", fingerprint,
    422                           signing_key_fingerprint);
    423  }
    424 
    425  {
    426    char *sig = router_get_dirobj_signature(digest, DIGEST_LEN,
    427                                            private_signing_key);
    428    if (!sig) {
    429      log_warn(LD_BUG, "Unable to sign networkstatus vote.");
    430      goto err;
    431    }
    432    smartlist_add(chunks, sig);
    433  }
    434 
    435  status = smartlist_join_strings(chunks, "", 0, NULL);
    436 
    437  {
    438    networkstatus_t *v;
    439    if (!(v = networkstatus_parse_vote_from_string(status, strlen(status),
    440                                                   NULL,
    441                                                   v3_ns->type))) {
    442      log_err(LD_BUG,"Generated a networkstatus %s we couldn't parse: "
    443              "<<%s>>",
    444              v3_ns->type == NS_TYPE_VOTE ? "vote" : "opinion", status);
    445      goto err;
    446    }
    447    networkstatus_vote_free(v);
    448  }
    449 
    450  goto done;
    451 
    452 err:
    453  tor_free(status);
    454 done:
    455  tor_free(client_versions_line);
    456  tor_free(server_versions_line);
    457  tor_free(protocols_lines);
    458 
    459  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
    460  smartlist_free(chunks);
    461  return status;
    462 }
    463 
    464 /** Set *<b>timing_out</b> to the intervals at which we would like to vote.
    465 * Note that these aren't the intervals we'll use to vote; they're the ones
    466 * that we'll vote to use. */
    467 static void
    468 dirvote_get_preferred_voting_intervals(vote_timing_t *timing_out)
    469 {
    470  const or_options_t *options = get_options();
    471 
    472  tor_assert(timing_out);
    473 
    474  timing_out->vote_interval = options->V3AuthVotingInterval;
    475  timing_out->n_intervals_valid = options->V3AuthNIntervalsValid;
    476  timing_out->vote_delay = options->V3AuthVoteDelay;
    477  timing_out->dist_delay = options->V3AuthDistDelay;
    478 }
    479 
    480 /* =====
    481 * Consensus generation
    482 * ===== */
    483 
    484 /** If <b>vrs</b> has a hash made for the consensus method <b>method</b> with
    485 * the digest algorithm <b>alg</b>, decode it and copy it into
    486 * <b>digest256_out</b> and return 0.  Otherwise return -1. */
    487 static int
    488 vote_routerstatus_find_microdesc_hash(char *digest256_out,
    489                                      const vote_routerstatus_t *vrs,
    490                                      int method,
    491                                      digest_algorithm_t alg)
    492 {
    493  /* XXXX only returns the sha256 method. */
    494  const vote_microdesc_hash_t *h;
    495  char mstr[64];
    496  size_t mlen;
    497  char dstr[64];
    498 
    499  tor_snprintf(mstr, sizeof(mstr), "%d", method);
    500  mlen = strlen(mstr);
    501  tor_snprintf(dstr, sizeof(dstr), " %s=",
    502               crypto_digest_algorithm_get_name(alg));
    503 
    504  for (h = vrs->microdesc; h; h = h->next) {
    505    const char *cp = h->microdesc_hash_line;
    506    size_t num_len;
    507    /* cp looks like \d+(,\d+)* (digesttype=val )+ .  Let's hunt for mstr in
    508     * the first part. */
    509    while (1) {
    510      num_len = strspn(cp, "1234567890");
    511      if (num_len == mlen && fast_memeq(mstr, cp, mlen)) {
    512        /* This is the line. */
    513        char buf[BASE64_DIGEST256_LEN+1];
    514        /* XXXX ignores extraneous stuff if the digest is too long.  This
    515         * seems harmless enough, right? */
    516        cp = strstr(cp, dstr);
    517        if (!cp)
    518          return -1;
    519        cp += strlen(dstr);
    520        strlcpy(buf, cp, sizeof(buf));
    521        return digest256_from_base64(digest256_out, buf);
    522      }
    523      if (num_len == 0 || cp[num_len] != ',')
    524        break;
    525      cp += num_len + 1;
    526    }
    527  }
    528  return -1;
    529 }
    530 
    531 /** Given a vote <b>vote</b> (not a consensus!), return its associated
    532 * networkstatus_voter_info_t. */
    533 static networkstatus_voter_info_t *
    534 get_voter(const networkstatus_t *vote)
    535 {
    536  tor_assert(vote);
    537  tor_assert(vote->type == NS_TYPE_VOTE);
    538  tor_assert(vote->voters);
    539  tor_assert(smartlist_len(vote->voters) == 1);
    540  return smartlist_get(vote->voters, 0);
    541 }
    542 
    543 /** Temporary structure used in constructing a list of dir-source entries
    544 * for a consensus.  One of these is generated for every vote, and one more
    545 * for every legacy key in each vote. */
    546 typedef struct dir_src_ent_t {
    547  networkstatus_t *v;
    548  const char *digest;
    549  int is_legacy;
    550 } dir_src_ent_t;
    551 
    552 /** Helper for sorting networkstatus_t votes (not consensuses) by the
    553 * hash of their voters' identity digests. */
    554 static int
    555 compare_votes_by_authority_id_(const void **_a, const void **_b)
    556 {
    557  const networkstatus_t *a = *_a, *b = *_b;
    558  return fast_memcmp(get_voter(a)->identity_digest,
    559                get_voter(b)->identity_digest, DIGEST_LEN);
    560 }
    561 
    562 /** Helper: Compare the dir_src_ent_ts in *<b>_a</b> and *<b>_b</b> by
    563 * their identity digests, and return -1, 0, or 1 depending on their
    564 * ordering */
    565 static int
    566 compare_dir_src_ents_by_authority_id_(const void **_a, const void **_b)
    567 {
    568  const dir_src_ent_t *a = *_a, *b = *_b;
    569  const networkstatus_voter_info_t *a_v = get_voter(a->v),
    570    *b_v = get_voter(b->v);
    571  const char *a_id, *b_id;
    572  a_id = a->is_legacy ? a_v->legacy_id_digest : a_v->identity_digest;
    573  b_id = b->is_legacy ? b_v->legacy_id_digest : b_v->identity_digest;
    574 
    575  return fast_memcmp(a_id, b_id, DIGEST_LEN);
    576 }
    577 
    578 /** Given a sorted list of strings <b>in</b>, add every member to <b>out</b>
    579 * that occurs more than <b>min</b> times. */
    580 static void
    581 get_frequent_members(smartlist_t *out, smartlist_t *in, int min)
    582 {
    583  char *cur = NULL;
    584  int count = 0;
    585  SMARTLIST_FOREACH_BEGIN(in, char *, cp) {
    586    if (cur && !strcmp(cp, cur)) {
    587      ++count;
    588    } else {
    589      if (count > min)
    590        smartlist_add(out, cur);
    591      cur = cp;
    592      count = 1;
    593    }
    594  } SMARTLIST_FOREACH_END(cp);
    595  if (count > min)
    596    smartlist_add(out, cur);
    597 }
    598 
    599 /** Given a sorted list of strings <b>lst</b>, return the member that appears
    600 * most.  Break ties in favor of later-occurring members. */
    601 #define get_most_frequent_member(lst)           \
    602  smartlist_get_most_frequent_string(lst)
    603 
    604 /** Return 0 if and only if <b>a</b> and <b>b</b> are routerstatuses
    605 * that come from the same routerinfo, with the same derived elements.
    606 */
    607 static int
    608 compare_vote_rs(const vote_routerstatus_t *a, const vote_routerstatus_t *b)
    609 {
    610  int r;
    611  tor_assert(a);
    612  tor_assert(b);
    613 
    614  if ((r = fast_memcmp(a->status.identity_digest, b->status.identity_digest,
    615                  DIGEST_LEN)))
    616    return r;
    617  if ((r = fast_memcmp(a->status.descriptor_digest,
    618                       b->status.descriptor_digest,
    619                       DIGEST_LEN)))
    620    return r;
    621  /* If we actually reached this point, then the identities and
    622   * the descriptor digests matched, so somebody is making SHA1 collisions.
    623   */
    624 #define CMP_FIELD(utype, itype, field) do {                             \
    625    utype aval = (utype) (itype) a->field;                              \
    626    utype bval = (utype) (itype) b->field;                              \
    627    utype u = bval - aval;                                              \
    628    itype r2 = (itype) u;                                               \
    629    if (r2 < 0) {                                                       \
    630      return -1;                                                        \
    631    } else if (r2 > 0) {                                                \
    632      return 1;                                                         \
    633    }                                                                   \
    634  } while (0)
    635 
    636  CMP_FIELD(uint64_t, int64_t, published_on);
    637 
    638  if ((r = strcmp(b->status.nickname, a->status.nickname)))
    639    return r;
    640 
    641  if ((r = tor_addr_compare(&a->status.ipv4_addr, &b->status.ipv4_addr,
    642                            CMP_EXACT))) {
    643    return r;
    644  }
    645  CMP_FIELD(unsigned, int, status.ipv4_orport);
    646  CMP_FIELD(unsigned, int, status.ipv4_dirport);
    647 
    648  return 0;
    649 }
    650 
    651 /** Helper for sorting routerlists based on compare_vote_rs. */
    652 static int
    653 compare_vote_rs_(const void **_a, const void **_b)
    654 {
    655  const vote_routerstatus_t *a = *_a, *b = *_b;
    656  return compare_vote_rs(a,b);
    657 }
    658 
    659 /** Helper for sorting OR ports. */
    660 static int
    661 compare_orports_(const void **_a, const void **_b)
    662 {
    663  const tor_addr_port_t *a = *_a, *b = *_b;
    664  int r;
    665 
    666  if ((r = tor_addr_compare(&a->addr, &b->addr, CMP_EXACT)))
    667    return r;
    668  if ((r = (((int) b->port) - ((int) a->port))))
    669    return r;
    670 
    671  return 0;
    672 }
    673 
    674 /** Given a list of vote_routerstatus_t, all for the same router identity,
    675 * return whichever is most frequent, breaking ties in favor of more
    676 * recently published vote_routerstatus_t and in case of ties there,
    677 * in favor of smaller descriptor digest.
    678 */
    679 static vote_routerstatus_t *
    680 compute_routerstatus_consensus(smartlist_t *votes, int consensus_method,
    681                               char *microdesc_digest256_out,
    682                               tor_addr_port_t *best_alt_orport_out)
    683 {
    684  vote_routerstatus_t *most = NULL, *cur = NULL;
    685  int most_n = 0, cur_n = 0;
    686  time_t most_published = 0;
    687 
    688  /* compare_vote_rs_() sorts the items by identity digest (all the same),
    689   * then by SD digest.  That way, if we have a tie that the published_on
    690   * date cannot break, we use the descriptor with the smaller digest.
    691   */
    692  smartlist_sort(votes, compare_vote_rs_);
    693  SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
    694    if (cur && !compare_vote_rs(cur, rs)) {
    695      ++cur_n;
    696    } else {
    697      if (cur && (cur_n > most_n ||
    698                  (cur_n == most_n &&
    699                   cur->published_on > most_published))) {
    700        most = cur;
    701        most_n = cur_n;
    702        most_published = cur->published_on;
    703      }
    704      cur_n = 1;
    705      cur = rs;
    706    }
    707  } SMARTLIST_FOREACH_END(rs);
    708 
    709  if (cur_n > most_n ||
    710      (cur && cur_n == most_n && cur->published_on > most_published)) {
    711    most = cur;
    712    // most_n = cur_n; // unused after this point.
    713    // most_published = cur->status.published_on; // unused after this point.
    714  }
    715 
    716  tor_assert(most);
    717 
    718  /* Vote on potential alternative (sets of) OR port(s) in the winning
    719   * routerstatuses.
    720   *
    721   * XXX prop186 There's at most one alternative OR port (_the_ IPv6
    722   * port) for now. */
    723  if (best_alt_orport_out) {
    724    smartlist_t *alt_orports = smartlist_new();
    725    const tor_addr_port_t *most_alt_orport = NULL;
    726 
    727    SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
    728      tor_assert(rs);
    729      if (compare_vote_rs(most, rs) == 0 &&
    730          !tor_addr_is_null(&rs->status.ipv6_addr)
    731          && rs->status.ipv6_orport) {
    732        smartlist_add(alt_orports, tor_addr_port_new(&rs->status.ipv6_addr,
    733                                                     rs->status.ipv6_orport));
    734      }
    735    } SMARTLIST_FOREACH_END(rs);
    736 
    737    smartlist_sort(alt_orports, compare_orports_);
    738    most_alt_orport = smartlist_get_most_frequent(alt_orports,
    739                                                  compare_orports_);
    740    if (most_alt_orport) {
    741      memcpy(best_alt_orport_out, most_alt_orport, sizeof(tor_addr_port_t));
    742      log_debug(LD_DIR, "\"a\" line winner for %s is %s",
    743                most->status.nickname,
    744                fmt_addrport(&most_alt_orport->addr, most_alt_orport->port));
    745    }
    746 
    747    SMARTLIST_FOREACH(alt_orports, tor_addr_port_t *, ap, tor_free(ap));
    748    smartlist_free(alt_orports);
    749  }
    750 
    751  if (microdesc_digest256_out) {
    752    smartlist_t *digests = smartlist_new();
    753    const uint8_t *best_microdesc_digest;
    754    SMARTLIST_FOREACH_BEGIN(votes, vote_routerstatus_t *, rs) {
    755        char d[DIGEST256_LEN];
    756        if (compare_vote_rs(rs, most))
    757          continue;
    758        if (!vote_routerstatus_find_microdesc_hash(d, rs, consensus_method,
    759                                                   DIGEST_SHA256))
    760          smartlist_add(digests, tor_memdup(d, sizeof(d)));
    761    } SMARTLIST_FOREACH_END(rs);
    762    smartlist_sort_digests256(digests);
    763    best_microdesc_digest = smartlist_get_most_frequent_digest256(digests);
    764    if (best_microdesc_digest)
    765      memcpy(microdesc_digest256_out, best_microdesc_digest, DIGEST256_LEN);
    766    SMARTLIST_FOREACH(digests, char *, cp, tor_free(cp));
    767    smartlist_free(digests);
    768  }
    769 
    770  return most;
    771 }
    772 
    773 /** Sorting helper: compare two strings based on their values as base-ten
    774 * positive integers. (Non-integers are treated as prior to all integers, and
    775 * compared lexically.) */
    776 static int
    777 cmp_int_strings_(const void **_a, const void **_b)
    778 {
    779  const char *a = *_a, *b = *_b;
    780  int ai = (int)tor_parse_long(a, 10, 1, INT_MAX, NULL, NULL);
    781  int bi = (int)tor_parse_long(b, 10, 1, INT_MAX, NULL, NULL);
    782  if (ai<bi) {
    783    return -1;
    784  } else if (ai==bi) {
    785    if (ai == 0) /* Parsing failed. */
    786      return strcmp(a, b);
    787    return 0;
    788  } else {
    789    return 1;
    790  }
    791 }
    792 
    793 /** Given a list of networkstatus_t votes, determine and return the number of
    794 * the highest consensus method that is supported by more than 2/3 of the
    795 * voters. */
    796 static int
    797 compute_consensus_method(smartlist_t *votes)
    798 {
    799  smartlist_t *all_methods = smartlist_new();
    800  smartlist_t *acceptable_methods = smartlist_new();
    801  smartlist_t *tmp = smartlist_new();
    802  int min = (smartlist_len(votes) * 2) / 3;
    803  int n_ok;
    804  int result;
    805  SMARTLIST_FOREACH(votes, networkstatus_t *, vote,
    806  {
    807    tor_assert(vote->supported_methods);
    808    smartlist_add_all(tmp, vote->supported_methods);
    809    smartlist_sort(tmp, cmp_int_strings_);
    810    smartlist_uniq(tmp, cmp_int_strings_, NULL);
    811    smartlist_add_all(all_methods, tmp);
    812    smartlist_clear(tmp);
    813  });
    814 
    815  smartlist_sort(all_methods, cmp_int_strings_);
    816  /* find all the consensus methods supported by _more than_ min votes. */
    817  get_frequent_members(acceptable_methods, all_methods, min);
    818  n_ok = smartlist_len(acceptable_methods);
    819  if (n_ok) {
    820    const char *best = smartlist_get(acceptable_methods, n_ok-1);
    821    result = (int)tor_parse_long(best, 10, 1, INT_MAX, NULL, NULL);
    822  } else {
    823    result = 1;
    824  }
    825  smartlist_free(tmp);
    826  smartlist_free(all_methods);
    827  smartlist_free(acceptable_methods);
    828  return result;
    829 }
    830 
    831 /** Return true iff <b>method</b> is a consensus method that we support. */
    832 static int
    833 consensus_method_is_supported(int method)
    834 {
    835  return (method >= MIN_SUPPORTED_CONSENSUS_METHOD) &&
    836    (method <= MAX_SUPPORTED_CONSENSUS_METHOD);
    837 }
    838 
    839 /** Return a newly allocated string holding the numbers between low and high
    840 * (inclusive) that are supported consensus methods. */
    841 STATIC char *
    842 make_consensus_method_list(int low, int high, const char *separator)
    843 {
    844  char *list;
    845 
    846  int i;
    847  smartlist_t *lst;
    848  lst = smartlist_new();
    849  for (i = low; i <= high; ++i) {
    850    if (!consensus_method_is_supported(i))
    851      continue;
    852    smartlist_add_asprintf(lst, "%d", i);
    853  }
    854  list = smartlist_join_strings(lst, separator, 0, NULL);
    855  tor_assert(list);
    856  SMARTLIST_FOREACH(lst, char *, cp, tor_free(cp));
    857  smartlist_free(lst);
    858  return list;
    859 }
    860 
    861 /** Helper: given <b>lst</b>, a list of version strings such that every
    862 * version appears once for every versioning voter who recommends it, return a
    863 * newly allocated string holding the resulting client-versions or
    864 * server-versions list. May change contents of <b>lst</b>. */
    865 static char *
    866 compute_consensus_versions_list(smartlist_t *lst, int n_versioning)
    867 {
    868  int min = n_versioning / 2;
    869  smartlist_t *good = smartlist_new();
    870  char *result;
    871  SMARTLIST_FOREACH_BEGIN(lst, const char *, v) {
    872    if (strchr(v, ' ')) {
    873      log_warn(LD_DIR, "At least one authority has voted for a version %s "
    874               "that contains a space. This probably wasn't intentional, and "
    875               "is likely to cause trouble. Please tell them to stop it.",
    876               escaped(v));
    877    }
    878  } SMARTLIST_FOREACH_END(v);
    879  sort_version_list(lst, 0);
    880  /* collect the versions recommended in _more than_ min versioning votes */
    881  get_frequent_members(good, lst, min);
    882  result = smartlist_join_strings(good, ",", 0, NULL);
    883  smartlist_free(good);
    884  return result;
    885 }
    886 
    887 /** Given a list of K=V values, return the int32_t value corresponding to
    888 * KEYWORD=, or default_val if no such value exists, or if the value is
    889 * corrupt.
    890 */
    891 STATIC int32_t
    892 dirvote_get_intermediate_param_value(const smartlist_t *param_list,
    893                                     const char *keyword,
    894                                     int32_t default_val)
    895 {
    896  unsigned int n_found = 0;
    897  int32_t value = default_val;
    898 
    899  SMARTLIST_FOREACH_BEGIN(param_list, const char *, k_v_pair) {
    900    if (!strcmpstart(k_v_pair, keyword) && k_v_pair[strlen(keyword)] == '=') {
    901      const char *integer_str = &k_v_pair[strlen(keyword)+1];
    902      int ok;
    903      value = (int32_t)
    904        tor_parse_long(integer_str, 10, INT32_MIN, INT32_MAX, &ok, NULL);
    905      if (BUG(!ok))
    906        return default_val;
    907      ++n_found;
    908    }
    909  } SMARTLIST_FOREACH_END(k_v_pair);
    910 
    911  if (n_found == 1) {
    912    return value;
    913  } else {
    914    tor_assert_nonfatal(n_found == 0);
    915    return default_val;
    916  }
    917 }
    918 
    919 /** Minimum number of directory authorities voting for a parameter to
    920 * include it in the consensus, if consensus method 12 or later is to be
    921 * used. See proposal 178 for details. */
    922 #define MIN_VOTES_FOR_PARAM 3
    923 
    924 /** Helper: given a list of valid networkstatus_t, return a new smartlist
    925 * containing the contents of the consensus network parameter set.
    926 */
    927 STATIC smartlist_t *
    928 dirvote_compute_params(smartlist_t *votes, int method, int total_authorities)
    929 {
    930  int i;
    931  int32_t *vals;
    932 
    933  int cur_param_len;
    934  const char *cur_param;
    935  const char *eq;
    936 
    937  const int n_votes = smartlist_len(votes);
    938  smartlist_t *output;
    939  smartlist_t *param_list = smartlist_new();
    940  (void) method;
    941 
    942  /* We require that the parameter lists in the votes are well-formed: that
    943     is, that their keywords are unique and sorted, and that their values are
    944     between INT32_MIN and INT32_MAX inclusive.  This should be guaranteed by
    945     the parsing code. */
    946 
    947  vals = tor_calloc(n_votes, sizeof(int));
    948 
    949  SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
    950    if (!v->net_params)
    951      continue;
    952    smartlist_add_all(param_list, v->net_params);
    953  } SMARTLIST_FOREACH_END(v);
    954 
    955  if (smartlist_len(param_list) == 0) {
    956    tor_free(vals);
    957    return param_list;
    958  }
    959 
    960  smartlist_sort_strings(param_list);
    961  i = 0;
    962  cur_param = smartlist_get(param_list, 0);
    963  eq = strchr(cur_param, '=');
    964  tor_assert(eq);
    965  cur_param_len = (int)(eq+1 - cur_param);
    966 
    967  output = smartlist_new();
    968 
    969  SMARTLIST_FOREACH_BEGIN(param_list, const char *, param) {
    970    /* resolve spurious clang shallow analysis null pointer errors */
    971    tor_assert(param);
    972 
    973    const char *next_param;
    974    int ok=0;
    975    eq = strchr(param, '=');
    976    tor_assert(i<n_votes); /* Make sure we prevented vote-stuffing. */
    977    vals[i++] = (int32_t)
    978      tor_parse_long(eq+1, 10, INT32_MIN, INT32_MAX, &ok, NULL);
    979    tor_assert(ok); /* Already checked these when parsing. */
    980 
    981    if (param_sl_idx+1 == smartlist_len(param_list))
    982      next_param = NULL;
    983    else
    984      next_param = smartlist_get(param_list, param_sl_idx+1);
    985 
    986    if (!next_param || strncmp(next_param, param, cur_param_len)) {
    987      /* We've reached the end of a series. */
    988      /* Make sure enough authorities voted on this param, unless the
    989       * the consensus method we use is too old for that. */
    990      if (i > total_authorities/2 ||
    991          i >= MIN_VOTES_FOR_PARAM) {
    992        int32_t median = median_int32(vals, i);
    993        char *out_string = tor_malloc(64+cur_param_len);
    994        memcpy(out_string, param, cur_param_len);
    995        tor_snprintf(out_string+cur_param_len,64, "%ld", (long)median);
    996        smartlist_add(output, out_string);
    997      }
    998 
    999      i = 0;
   1000      if (next_param) {
   1001        eq = strchr(next_param, '=');
   1002        cur_param_len = (int)(eq+1 - next_param);
   1003      }
   1004    }
   1005  } SMARTLIST_FOREACH_END(param);
   1006 
   1007  smartlist_free(param_list);
   1008  tor_free(vals);
   1009  return output;
   1010 }
   1011 
   1012 #define RANGE_CHECK(a,b,c,d,e,f,g,mx) \
   1013       ((a) >= 0 && (a) <= (mx) && (b) >= 0 && (b) <= (mx) && \
   1014        (c) >= 0 && (c) <= (mx) && (d) >= 0 && (d) <= (mx) && \
   1015        (e) >= 0 && (e) <= (mx) && (f) >= 0 && (f) <= (mx) && \
   1016        (g) >= 0 && (g) <= (mx))
   1017 
   1018 #define CHECK_EQ(a, b, margin) \
   1019     ((a)-(b) >= 0 ? (a)-(b) <= (margin) : (b)-(a) <= (margin))
   1020 
   1021 typedef enum {
   1022 BW_WEIGHTS_NO_ERROR = 0,
   1023 BW_WEIGHTS_RANGE_ERROR = 1,
   1024 BW_WEIGHTS_SUMG_ERROR = 2,
   1025 BW_WEIGHTS_SUME_ERROR = 3,
   1026 BW_WEIGHTS_SUMD_ERROR = 4,
   1027 BW_WEIGHTS_BALANCE_MID_ERROR = 5,
   1028 BW_WEIGHTS_BALANCE_EG_ERROR = 6
   1029 } bw_weights_error_t;
   1030 
   1031 /**
   1032 * Verify that any weightings satisfy the balanced formulas.
   1033 */
   1034 static bw_weights_error_t
   1035 networkstatus_check_weights(int64_t Wgg, int64_t Wgd, int64_t Wmg,
   1036                            int64_t Wme, int64_t Wmd, int64_t Wee,
   1037                            int64_t Wed, int64_t scale, int64_t G,
   1038                            int64_t M, int64_t E, int64_t D, int64_t T,
   1039                            int64_t margin, int do_balance) {
   1040  bw_weights_error_t berr = BW_WEIGHTS_NO_ERROR;
   1041 
   1042  // Wed + Wmd + Wgd == 1
   1043  if (!CHECK_EQ(Wed + Wmd + Wgd, scale, margin)) {
   1044    berr = BW_WEIGHTS_SUMD_ERROR;
   1045    goto out;
   1046  }
   1047 
   1048  // Wmg + Wgg == 1
   1049  if (!CHECK_EQ(Wmg + Wgg, scale, margin)) {
   1050    berr = BW_WEIGHTS_SUMG_ERROR;
   1051    goto out;
   1052  }
   1053 
   1054  // Wme + Wee == 1
   1055  if (!CHECK_EQ(Wme + Wee, scale, margin)) {
   1056    berr = BW_WEIGHTS_SUME_ERROR;
   1057    goto out;
   1058  }
   1059 
   1060  // Verify weights within range 0->1
   1061  if (!RANGE_CHECK(Wgg, Wgd, Wmg, Wme, Wmd, Wed, Wee, scale)) {
   1062    berr = BW_WEIGHTS_RANGE_ERROR;
   1063    goto out;
   1064  }
   1065 
   1066  if (do_balance) {
   1067    // Wgg*G + Wgd*D == Wee*E + Wed*D, already scaled
   1068    if (!CHECK_EQ(Wgg*G + Wgd*D, Wee*E + Wed*D, (margin*T)/3)) {
   1069      berr = BW_WEIGHTS_BALANCE_EG_ERROR;
   1070      goto out;
   1071    }
   1072 
   1073    // Wgg*G + Wgd*D == M*scale + Wmd*D + Wme*E + Wmg*G, already scaled
   1074    if (!CHECK_EQ(Wgg*G + Wgd*D, M*scale + Wmd*D + Wme*E + Wmg*G,
   1075                (margin*T)/3)) {
   1076      berr = BW_WEIGHTS_BALANCE_MID_ERROR;
   1077      goto out;
   1078    }
   1079  }
   1080 
   1081 out:
   1082  if (berr) {
   1083    log_info(LD_DIR,
   1084             "Bw weight mismatch %d. G=%"PRId64" M=%"PRId64
   1085             " E=%"PRId64" D=%"PRId64" T=%"PRId64
   1086             " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
   1087             " Wgd=%d Wgg=%d Wme=%d Wmg=%d",
   1088             berr,
   1089             (G), (M), (E),
   1090             (D), (T),
   1091             (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
   1092             (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg);
   1093  }
   1094 
   1095  return berr;
   1096 }
   1097 
   1098 /**
   1099 * This function computes the bandwidth weights for consensus method 10.
   1100 *
   1101 * It returns true if weights could be computed, false otherwise.
   1102 */
   1103 int
   1104 networkstatus_compute_bw_weights_v10(smartlist_t *chunks, int64_t G,
   1105                                     int64_t M, int64_t E, int64_t D,
   1106                                     int64_t T, int64_t weight_scale)
   1107 {
   1108  bw_weights_error_t berr = 0;
   1109  int64_t Wgg = -1, Wgd = -1;
   1110  int64_t Wmg = -1, Wme = -1, Wmd = -1;
   1111  int64_t Wed = -1, Wee = -1;
   1112  const char *casename;
   1113 
   1114  if (G <= 0 || M <= 0 || E <= 0 || D <= 0) {
   1115    log_warn(LD_DIR, "Consensus with empty bandwidth: "
   1116                     "G=%"PRId64" M=%"PRId64" E=%"PRId64
   1117                     " D=%"PRId64" T=%"PRId64,
   1118             (G), (M), (E),
   1119             (D), (T));
   1120    return 0;
   1121  }
   1122 
   1123  /*
   1124   * Computed from cases in 3.8.3 of dir-spec.txt
   1125   *
   1126   * 1. Neither are scarce
   1127   * 2. Both Guard and Exit are scarce
   1128   *    a. R+D <= S
   1129   *    b. R+D > S
   1130   * 3. One of Guard or Exit is scarce
   1131   *    a. S+D < T/3
   1132   *    b. S+D >= T/3
   1133   */
   1134  if (3*E >= T && 3*G >= T) { // E >= T/3 && G >= T/3
   1135    /* Case 1: Neither are scarce.  */
   1136    casename = "Case 1 (Wgd=Wmd=Wed)";
   1137    Wgd = weight_scale/3;
   1138    Wed = weight_scale/3;
   1139    Wmd = weight_scale/3;
   1140    Wee = (weight_scale*(E+G+M))/(3*E);
   1141    Wme = weight_scale - Wee;
   1142    Wmg = (weight_scale*(2*G-E-M))/(3*G);
   1143    Wgg = weight_scale - Wmg;
   1144 
   1145    berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
   1146                                       weight_scale, G, M, E, D, T, 10, 1);
   1147 
   1148    if (berr) {
   1149      log_warn(LD_DIR,
   1150             "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
   1151             " E=%"PRId64" D=%"PRId64" T=%"PRId64
   1152             " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
   1153             " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
   1154             berr, casename,
   1155             (G), (M), (E),
   1156             (D), (T),
   1157             (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
   1158             (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
   1159      return 0;
   1160    }
   1161  } else if (3*E < T && 3*G < T) { // E < T/3 && G < T/3
   1162    int64_t R = MIN(E, G);
   1163    int64_t S = MAX(E, G);
   1164    /*
   1165     * Case 2: Both Guards and Exits are scarce
   1166     * Balance D between E and G, depending upon
   1167     * D capacity and scarcity.
   1168     */
   1169    if (R+D < S) { // Subcase a
   1170      Wgg = weight_scale;
   1171      Wee = weight_scale;
   1172      Wmg = 0;
   1173      Wme = 0;
   1174      Wmd = 0;
   1175      if (E < G) {
   1176        casename = "Case 2a (E scarce)";
   1177        Wed = weight_scale;
   1178        Wgd = 0;
   1179      } else { /* E >= G */
   1180        casename = "Case 2a (G scarce)";
   1181        Wed = 0;
   1182        Wgd = weight_scale;
   1183      }
   1184    } else { // Subcase b: R+D >= S
   1185      casename = "Case 2b1 (Wgg=weight_scale, Wmd=Wgd)";
   1186      Wee = (weight_scale*(E - G + M))/E;
   1187      Wed = (weight_scale*(D - 2*E + 4*G - 2*M))/(3*D);
   1188      Wme = (weight_scale*(G-M))/E;
   1189      Wmg = 0;
   1190      Wgg = weight_scale;
   1191      Wmd = (weight_scale - Wed)/2;
   1192      Wgd = (weight_scale - Wed)/2;
   1193 
   1194      berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee, Wed,
   1195                                       weight_scale, G, M, E, D, T, 10, 1);
   1196 
   1197      if (berr) {
   1198        casename = "Case 2b2 (Wgg=weight_scale, Wee=weight_scale)";
   1199        Wgg = weight_scale;
   1200        Wee = weight_scale;
   1201        Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
   1202        Wmd = (weight_scale*(D - 2*M + G + E))/(3*D);
   1203        Wme = 0;
   1204        Wmg = 0;
   1205 
   1206        if (Wmd < 0) { // Can happen if M > T/3
   1207          casename = "Case 2b3 (Wmd=0)";
   1208          Wmd = 0;
   1209          log_warn(LD_DIR,
   1210                   "Too much Middle bandwidth on the network to calculate "
   1211                   "balanced bandwidth-weights. Consider increasing the "
   1212                   "number of Guard nodes by lowering the requirements.");
   1213        }
   1214        Wgd = weight_scale - Wed - Wmd;
   1215        berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
   1216                  Wed, weight_scale, G, M, E, D, T, 10, 1);
   1217      }
   1218      if (berr != BW_WEIGHTS_NO_ERROR &&
   1219              berr != BW_WEIGHTS_BALANCE_MID_ERROR) {
   1220        log_warn(LD_DIR,
   1221             "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
   1222             " E=%"PRId64" D=%"PRId64" T=%"PRId64
   1223             " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
   1224             " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
   1225             berr, casename,
   1226             (G), (M), (E),
   1227             (D), (T),
   1228             (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
   1229             (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
   1230        return 0;
   1231      }
   1232    }
   1233  } else { // if (E < T/3 || G < T/3) {
   1234    int64_t S = MIN(E, G);
   1235    // Case 3: Exactly one of Guard or Exit is scarce
   1236    if (!(3*E < T || 3*G < T) || !(3*G >= T || 3*E >= T)) {
   1237      log_warn(LD_BUG,
   1238           "Bw-Weights Case 3 v10 but with G=%"PRId64" M="
   1239           "%"PRId64" E=%"PRId64" D=%"PRId64" T=%"PRId64,
   1240               (G), (M), (E),
   1241               (D), (T));
   1242    }
   1243 
   1244    if (3*(S+D) < T) { // Subcase a: S+D < T/3
   1245      if (G < E) {
   1246        casename = "Case 3a (G scarce)";
   1247        Wgg = Wgd = weight_scale;
   1248        Wmd = Wed = Wmg = 0;
   1249        // Minor subcase, if E is more scarce than M,
   1250        // keep its bandwidth in place.
   1251        if (E < M) Wme = 0;
   1252        else Wme = (weight_scale*(E-M))/(2*E);
   1253        Wee = weight_scale-Wme;
   1254      } else { // G >= E
   1255        casename = "Case 3a (E scarce)";
   1256        Wee = Wed = weight_scale;
   1257        Wmd = Wgd = Wme = 0;
   1258        // Minor subcase, if G is more scarce than M,
   1259        // keep its bandwidth in place.
   1260        if (G < M) Wmg = 0;
   1261        else Wmg = (weight_scale*(G-M))/(2*G);
   1262        Wgg = weight_scale-Wmg;
   1263      }
   1264    } else { // Subcase b: S+D >= T/3
   1265      // D != 0 because S+D >= T/3
   1266      if (G < E) {
   1267        casename = "Case 3bg (G scarce, Wgg=weight_scale, Wmd == Wed)";
   1268        Wgg = weight_scale;
   1269        Wgd = (weight_scale*(D - 2*G + E + M))/(3*D);
   1270        Wmg = 0;
   1271        Wee = (weight_scale*(E+M))/(2*E);
   1272        Wme = weight_scale - Wee;
   1273        Wmd = (weight_scale - Wgd)/2;
   1274        Wed = (weight_scale - Wgd)/2;
   1275 
   1276        berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
   1277                    Wed, weight_scale, G, M, E, D, T, 10, 1);
   1278      } else { // G >= E
   1279        casename = "Case 3be (E scarce, Wee=weight_scale, Wmd == Wgd)";
   1280        Wee = weight_scale;
   1281        Wed = (weight_scale*(D - 2*E + G + M))/(3*D);
   1282        Wme = 0;
   1283        Wgg = (weight_scale*(G+M))/(2*G);
   1284        Wmg = weight_scale - Wgg;
   1285        Wmd = (weight_scale - Wed)/2;
   1286        Wgd = (weight_scale - Wed)/2;
   1287 
   1288        berr = networkstatus_check_weights(Wgg, Wgd, Wmg, Wme, Wmd, Wee,
   1289                      Wed, weight_scale, G, M, E, D, T, 10, 1);
   1290      }
   1291      if (berr) {
   1292        log_warn(LD_DIR,
   1293             "Bw Weights error %d for %s v10. G=%"PRId64" M=%"PRId64
   1294             " E=%"PRId64" D=%"PRId64" T=%"PRId64
   1295             " Wmd=%d Wme=%d Wmg=%d Wed=%d Wee=%d"
   1296             " Wgd=%d Wgg=%d Wme=%d Wmg=%d weight_scale=%d",
   1297             berr, casename,
   1298             (G), (M), (E),
   1299             (D), (T),
   1300             (int)Wmd, (int)Wme, (int)Wmg, (int)Wed, (int)Wee,
   1301             (int)Wgd, (int)Wgg, (int)Wme, (int)Wmg, (int)weight_scale);
   1302        return 0;
   1303      }
   1304    }
   1305  }
   1306 
   1307  /* We cast down the weights to 32 bit ints on the assumption that
   1308   * weight_scale is ~= 10000. We need to ensure a rogue authority
   1309   * doesn't break this assumption to rig our weights */
   1310  tor_assert(0 < weight_scale && weight_scale <= INT32_MAX);
   1311 
   1312  /*
   1313   * Provide Wgm=Wgg, Wmm=weight_scale, Wem=Wee, Weg=Wed. May later determine
   1314   * that middle nodes need different bandwidth weights for dirport traffic,
   1315   * or that weird exit policies need special weight, or that bridges
   1316   * need special weight.
   1317   *
   1318   * NOTE: This list is sorted.
   1319   */
   1320  smartlist_add_asprintf(chunks,
   1321     "bandwidth-weights Wbd=%d Wbe=%d Wbg=%d Wbm=%d "
   1322     "Wdb=%d "
   1323     "Web=%d Wed=%d Wee=%d Weg=%d Wem=%d "
   1324     "Wgb=%d Wgd=%d Wgg=%d Wgm=%d "
   1325     "Wmb=%d Wmd=%d Wme=%d Wmg=%d Wmm=%d\n",
   1326     (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale,
   1327     (int)weight_scale,
   1328     (int)weight_scale, (int)Wed, (int)Wee, (int)Wed, (int)Wee,
   1329     (int)weight_scale, (int)Wgd, (int)Wgg, (int)Wgg,
   1330     (int)weight_scale, (int)Wmd, (int)Wme, (int)Wmg, (int)weight_scale);
   1331 
   1332  log_notice(LD_CIRC, "Computed bandwidth weights for %s with v10: "
   1333             "G=%"PRId64" M=%"PRId64" E=%"PRId64" D=%"PRId64
   1334             " T=%"PRId64,
   1335             casename,
   1336             (G), (M), (E),
   1337             (D), (T));
   1338  return 1;
   1339 }
   1340 
   1341 /** Update total bandwidth weights (G/M/E/D/T) with the bandwidth of
   1342 *  the router in <b>rs</b>. */
   1343 static void
   1344 update_total_bandwidth_weights(const routerstatus_t *rs,
   1345                               int is_exit, int is_guard,
   1346                               int64_t *G, int64_t *M, int64_t *E, int64_t *D,
   1347                               int64_t *T)
   1348 {
   1349  int default_bandwidth = rs->bandwidth_kb;
   1350  int guardfraction_bandwidth = 0;
   1351 
   1352  if (!rs->has_bandwidth) {
   1353    log_info(LD_BUG, "Missing consensus bandwidth for router %s",
   1354             rs->nickname);
   1355    return;
   1356  }
   1357 
   1358  /* If this routerstatus represents a guard that we have
   1359   * guardfraction information on, use it to calculate its actual
   1360   * bandwidth. From proposal236:
   1361   *
   1362   *    Similarly, when calculating the bandwidth-weights line as in
   1363   *    section 3.8.3 of dir-spec.txt, directory authorities should treat N
   1364   *    as if fraction F of its bandwidth has the guard flag and (1-F) does
   1365   *    not.  So when computing the totals G,M,E,D, each relay N with guard
   1366   *    visibility fraction F and bandwidth B should be added as follows:
   1367   *
   1368   *    G' = G + F*B, if N does not have the exit flag
   1369   *    M' = M + (1-F)*B, if N does not have the exit flag
   1370   *
   1371   *    or
   1372   *
   1373   *    D' = D + F*B, if N has the exit flag
   1374   *    E' = E + (1-F)*B, if N has the exit flag
   1375   *
   1376   * In this block of code, we prepare the bandwidth values by setting
   1377   * the default_bandwidth to F*B and guardfraction_bandwidth to (1-F)*B.
   1378   */
   1379  if (rs->has_guardfraction) {
   1380    guardfraction_bandwidth_t guardfraction_bw;
   1381 
   1382    tor_assert(is_guard);
   1383 
   1384    guard_get_guardfraction_bandwidth(&guardfraction_bw,
   1385                                      rs->bandwidth_kb,
   1386                                      rs->guardfraction_percentage);
   1387 
   1388    default_bandwidth = guardfraction_bw.guard_bw;
   1389    guardfraction_bandwidth = guardfraction_bw.non_guard_bw;
   1390  }
   1391 
   1392  /* Now calculate the total bandwidth weights with or without
   1393   * guardfraction. Depending on the flags of the relay, add its
   1394   * bandwidth to the appropriate weight pool. If it's a guard and
   1395   * guardfraction is enabled, add its bandwidth to both pools as
   1396   * indicated by the previous comment.
   1397   */
   1398  *T += default_bandwidth;
   1399  if (is_exit && is_guard) {
   1400 
   1401    *D += default_bandwidth;
   1402    if (rs->has_guardfraction) {
   1403      *E += guardfraction_bandwidth;
   1404    }
   1405 
   1406  } else if (is_exit) {
   1407 
   1408    *E += default_bandwidth;
   1409 
   1410  } else if (is_guard) {
   1411 
   1412    *G += default_bandwidth;
   1413    if (rs->has_guardfraction) {
   1414      *M += guardfraction_bandwidth;
   1415    }
   1416 
   1417  } else {
   1418 
   1419    *M += default_bandwidth;
   1420  }
   1421 }
   1422 
   1423 /** Considering the different recommended/required protocols sets as a
   1424 * 4-element array, return the element from <b>vote</b> for that protocol
   1425 * set.
   1426 */
   1427 static const char *
   1428 get_nth_protocol_set_vote(int n, const networkstatus_t *vote)
   1429 {
   1430  switch (n) {
   1431    case 0: return vote->recommended_client_protocols;
   1432    case 1: return vote->recommended_relay_protocols;
   1433    case 2: return vote->required_client_protocols;
   1434    case 3: return vote->required_relay_protocols;
   1435    default:
   1436      tor_assert_unreached();
   1437      return NULL;
   1438  }
   1439 }
   1440 
   1441 /** Considering the different recommended/required protocols sets as a
   1442 * 4-element array, return a newly allocated string for the consensus value
   1443 * for the n'th set.
   1444 */
   1445 static char *
   1446 compute_nth_protocol_set(int n, int n_voters, const smartlist_t *votes)
   1447 {
   1448  const char *keyword;
   1449  smartlist_t *proto_votes = smartlist_new();
   1450  int threshold;
   1451  switch (n) {
   1452    case 0:
   1453      keyword = "recommended-client-protocols";
   1454      threshold = CEIL_DIV(n_voters, 2);
   1455      break;
   1456    case 1:
   1457      keyword = "recommended-relay-protocols";
   1458      threshold = CEIL_DIV(n_voters, 2);
   1459      break;
   1460    case 2:
   1461      keyword = "required-client-protocols";
   1462      threshold = CEIL_DIV(n_voters * 2, 3);
   1463      break;
   1464    case 3:
   1465      keyword = "required-relay-protocols";
   1466      threshold = CEIL_DIV(n_voters * 2, 3);
   1467      break;
   1468    default:
   1469      tor_assert_unreached();
   1470      return NULL;
   1471  }
   1472 
   1473  SMARTLIST_FOREACH_BEGIN(votes, const networkstatus_t *, ns) {
   1474    const char *v = get_nth_protocol_set_vote(n, ns);
   1475    if (v)
   1476      smartlist_add(proto_votes, (void*)v);
   1477  } SMARTLIST_FOREACH_END(ns);
   1478 
   1479  char *protocols = protover_compute_vote(proto_votes, threshold);
   1480  smartlist_free(proto_votes);
   1481 
   1482  char *result = NULL;
   1483  tor_asprintf(&result, "%s %s\n", keyword, protocols);
   1484  tor_free(protocols);
   1485 
   1486  return result;
   1487 }
   1488 
   1489 /** Helper: Takes a smartlist of `const char *` flags, and a flag to remove.
   1490 *
   1491 * Removes that flag if it is present in the list.  Doesn't free it.
   1492 */
   1493 static void
   1494 remove_flag(smartlist_t *sl, const char *flag)
   1495 {
   1496  /* We can't use smartlist_string_remove() here, since that doesn't preserve
   1497   * order, and since it frees elements from the string. */
   1498 
   1499  int idx = smartlist_string_pos(sl, flag);
   1500  if (idx >= 0)
   1501    smartlist_del_keeporder(sl, idx);
   1502 }
   1503 
   1504 /** Given a list of vote networkstatus_t in <b>votes</b>, our public
   1505 * authority <b>identity_key</b>, our private authority <b>signing_key</b>,
   1506 * and the number of <b>total_authorities</b> that we believe exist in our
   1507 * voting quorum, generate the text of a new v3 consensus or microdescriptor
   1508 * consensus (depending on <b>flavor</b>), and return the value in a newly
   1509 * allocated string.
   1510 *
   1511 * Note: this function DOES NOT check whether the votes are from
   1512 * recognized authorities.   (dirvote_add_vote does that.)
   1513 *
   1514 * <strong>WATCH OUT</strong>: You need to think before you change the
   1515 * behavior of this function, or of the functions it calls! If some
   1516 * authorities compute the consensus with a different algorithm than
   1517 * others, they will not reach the same result, and they will not all
   1518 * sign the same thing!  If you really need to change the algorithm
   1519 * here, you should allocate a new "consensus_method" for the new
   1520 * behavior, and make the new behavior conditional on a new-enough
   1521 * consensus_method.
   1522 **/
   1523 STATIC char *
   1524 networkstatus_compute_consensus(smartlist_t *votes,
   1525                                int total_authorities,
   1526                                crypto_pk_t *identity_key,
   1527                                crypto_pk_t *signing_key,
   1528                                const char *legacy_id_key_digest,
   1529                                crypto_pk_t *legacy_signing_key,
   1530                                consensus_flavor_t flavor)
   1531 {
   1532  smartlist_t *chunks;
   1533  char *result = NULL;
   1534  int consensus_method;
   1535  time_t valid_after, fresh_until, valid_until;
   1536  int vote_seconds, dist_seconds;
   1537  char *client_versions = NULL, *server_versions = NULL;
   1538  smartlist_t *flags;
   1539  const char *flavor_name;
   1540  uint32_t max_unmeasured_bw_kb = DEFAULT_MAX_UNMEASURED_BW_KB;
   1541  int64_t G, M, E, D, T; /* For bandwidth weights */
   1542  const routerstatus_format_type_t rs_format =
   1543    flavor == FLAV_NS ? NS_V3_CONSENSUS : NS_V3_CONSENSUS_MICRODESC;
   1544  char *params = NULL;
   1545  char *packages = NULL;
   1546  int added_weights = 0;
   1547  dircollator_t *collator = NULL;
   1548  smartlist_t *param_list = NULL;
   1549 
   1550  tor_assert(flavor == FLAV_NS || flavor == FLAV_MICRODESC);
   1551  tor_assert(total_authorities >= smartlist_len(votes));
   1552  tor_assert(total_authorities > 0);
   1553 
   1554  flavor_name = networkstatus_get_flavor_name(flavor);
   1555 
   1556  if (!smartlist_len(votes)) {
   1557    log_warn(LD_DIR, "Can't compute a consensus from no votes.");
   1558    return NULL;
   1559  }
   1560  flags = smartlist_new();
   1561 
   1562  consensus_method = compute_consensus_method(votes);
   1563  if (consensus_method_is_supported(consensus_method)) {
   1564    log_info(LD_DIR, "Generating consensus using method %d.",
   1565             consensus_method);
   1566  } else {
   1567    log_warn(LD_DIR, "The other authorities will use consensus method %d, "
   1568             "which I don't support.  Maybe I should upgrade!",
   1569             consensus_method);
   1570    consensus_method = MAX_SUPPORTED_CONSENSUS_METHOD;
   1571  }
   1572 
   1573  {
   1574    /* It's smarter to initialize these weights to 1, so that later on,
   1575     * we can't accidentally divide by zero. */
   1576    G = M = E = D = 1;
   1577    T = 4;
   1578  }
   1579 
   1580  /* Compute medians of time-related things, and figure out how many
   1581   * routers we might need to talk about. */
   1582  {
   1583    int n_votes = smartlist_len(votes);
   1584    time_t *va_times = tor_calloc(n_votes, sizeof(time_t));
   1585    time_t *fu_times = tor_calloc(n_votes, sizeof(time_t));
   1586    time_t *vu_times = tor_calloc(n_votes, sizeof(time_t));
   1587    int *votesec_list = tor_calloc(n_votes, sizeof(int));
   1588    int *distsec_list = tor_calloc(n_votes, sizeof(int));
   1589    int n_versioning_clients = 0, n_versioning_servers = 0;
   1590    smartlist_t *combined_client_versions = smartlist_new();
   1591    smartlist_t *combined_server_versions = smartlist_new();
   1592 
   1593    SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
   1594      tor_assert(v->type == NS_TYPE_VOTE);
   1595      va_times[v_sl_idx] = v->valid_after;
   1596      fu_times[v_sl_idx] = v->fresh_until;
   1597      vu_times[v_sl_idx] = v->valid_until;
   1598      votesec_list[v_sl_idx] = v->vote_seconds;
   1599      distsec_list[v_sl_idx] = v->dist_seconds;
   1600      if (v->client_versions) {
   1601        smartlist_t *cv = smartlist_new();
   1602        ++n_versioning_clients;
   1603        smartlist_split_string(cv, v->client_versions, ",",
   1604                               SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
   1605        sort_version_list(cv, 1);
   1606        smartlist_add_all(combined_client_versions, cv);
   1607        smartlist_free(cv); /* elements get freed later. */
   1608      }
   1609      if (v->server_versions) {
   1610        smartlist_t *sv = smartlist_new();
   1611        ++n_versioning_servers;
   1612        smartlist_split_string(sv, v->server_versions, ",",
   1613                               SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
   1614        sort_version_list(sv, 1);
   1615        smartlist_add_all(combined_server_versions, sv);
   1616        smartlist_free(sv); /* elements get freed later. */
   1617      }
   1618      SMARTLIST_FOREACH(v->known_flags, const char *, cp,
   1619                        smartlist_add_strdup(flags, cp));
   1620    } SMARTLIST_FOREACH_END(v);
   1621    valid_after = median_time(va_times, n_votes);
   1622    fresh_until = median_time(fu_times, n_votes);
   1623    valid_until = median_time(vu_times, n_votes);
   1624    vote_seconds = median_int(votesec_list, n_votes);
   1625    dist_seconds = median_int(distsec_list, n_votes);
   1626 
   1627    tor_assert(valid_after +
   1628               (get_options()->TestingTorNetwork ?
   1629                MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) <= fresh_until);
   1630    tor_assert(fresh_until +
   1631               (get_options()->TestingTorNetwork ?
   1632                MIN_VOTE_INTERVAL_TESTING : MIN_VOTE_INTERVAL) <= valid_until);
   1633    tor_assert(vote_seconds >= MIN_VOTE_SECONDS);
   1634    tor_assert(dist_seconds >= MIN_DIST_SECONDS);
   1635 
   1636    server_versions = compute_consensus_versions_list(combined_server_versions,
   1637                                                      n_versioning_servers);
   1638    client_versions = compute_consensus_versions_list(combined_client_versions,
   1639                                                      n_versioning_clients);
   1640 
   1641    if (consensus_method < MIN_METHOD_TO_OMIT_PACKAGE_FINGERPRINTS)
   1642      packages = tor_strdup("");
   1643    else
   1644      packages = compute_consensus_package_lines(votes);
   1645 
   1646    SMARTLIST_FOREACH(combined_server_versions, char *, cp, tor_free(cp));
   1647    SMARTLIST_FOREACH(combined_client_versions, char *, cp, tor_free(cp));
   1648    smartlist_free(combined_server_versions);
   1649    smartlist_free(combined_client_versions);
   1650 
   1651    smartlist_add_strdup(flags, "NoEdConsensus");
   1652 
   1653    smartlist_sort_strings(flags);
   1654    smartlist_uniq_strings(flags);
   1655 
   1656    tor_free(va_times);
   1657    tor_free(fu_times);
   1658    tor_free(vu_times);
   1659    tor_free(votesec_list);
   1660    tor_free(distsec_list);
   1661  }
   1662  // True if anybody is voting on the BadExit flag.
   1663  const bool badexit_flag_is_listed =
   1664    smartlist_contains_string(flags, "BadExit");
   1665 
   1666  chunks = smartlist_new();
   1667 
   1668  {
   1669    char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
   1670      vu_buf[ISO_TIME_LEN+1];
   1671    char *flaglist;
   1672    format_iso_time(va_buf, valid_after);
   1673    format_iso_time(fu_buf, fresh_until);
   1674    format_iso_time(vu_buf, valid_until);
   1675    flaglist = smartlist_join_strings(flags, " ", 0, NULL);
   1676 
   1677    smartlist_add_asprintf(chunks, "network-status-version 3%s%s\n"
   1678                 "vote-status consensus\n",
   1679                 flavor == FLAV_NS ? "" : " ",
   1680                 flavor == FLAV_NS ? "" : flavor_name);
   1681 
   1682    smartlist_add_asprintf(chunks, "consensus-method %d\n",
   1683                           consensus_method);
   1684 
   1685    smartlist_add_asprintf(chunks,
   1686                 "valid-after %s\n"
   1687                 "fresh-until %s\n"
   1688                 "valid-until %s\n"
   1689                 "voting-delay %d %d\n"
   1690                 "client-versions %s\n"
   1691                 "server-versions %s\n"
   1692                 "%s" /* packages */
   1693                 "known-flags %s\n",
   1694                 va_buf, fu_buf, vu_buf,
   1695                 vote_seconds, dist_seconds,
   1696                 client_versions, server_versions,
   1697                 packages,
   1698                 flaglist);
   1699 
   1700    tor_free(flaglist);
   1701  }
   1702 
   1703  {
   1704    int num_dirauth = get_n_authorities(V3_DIRINFO);
   1705    int idx;
   1706    for (idx = 0; idx < 4; ++idx) {
   1707      char *proto_line = compute_nth_protocol_set(idx, num_dirauth, votes);
   1708      if (BUG(!proto_line))
   1709        continue;
   1710      smartlist_add(chunks, proto_line);
   1711    }
   1712  }
   1713 
   1714  param_list = dirvote_compute_params(votes, consensus_method,
   1715                                      total_authorities);
   1716  if (smartlist_len(param_list)) {
   1717    params = smartlist_join_strings(param_list, " ", 0, NULL);
   1718    smartlist_add_strdup(chunks, "params ");
   1719    smartlist_add(chunks, params);
   1720    smartlist_add_strdup(chunks, "\n");
   1721  }
   1722 
   1723  {
   1724    int num_dirauth = get_n_authorities(V3_DIRINFO);
   1725    /* Default value of this is 2/3 of the total number of authorities. For
   1726     * instance, if we have 9 dirauth, the default value is 6. The following
   1727     * calculation will round it down. */
   1728    int32_t num_srv_agreements =
   1729      dirvote_get_intermediate_param_value(param_list,
   1730                                           "AuthDirNumSRVAgreements",
   1731                                           (num_dirauth * 2) / 3);
   1732    /* Add the shared random value. */
   1733    char *srv_lines = sr_get_string_for_consensus(votes, num_srv_agreements);
   1734    if (srv_lines != NULL) {
   1735      smartlist_add(chunks, srv_lines);
   1736    }
   1737  }
   1738 
   1739  /* Sort the votes. */
   1740  smartlist_sort(votes, compare_votes_by_authority_id_);
   1741  /* Add the authority sections. */
   1742  {
   1743    smartlist_t *dir_sources = smartlist_new();
   1744    SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
   1745      dir_src_ent_t *e = tor_malloc_zero(sizeof(dir_src_ent_t));
   1746      e->v = v;
   1747      e->digest = get_voter(v)->identity_digest;
   1748      e->is_legacy = 0;
   1749      smartlist_add(dir_sources, e);
   1750      if (!tor_digest_is_zero(get_voter(v)->legacy_id_digest)) {
   1751        dir_src_ent_t *e_legacy = tor_malloc_zero(sizeof(dir_src_ent_t));
   1752        e_legacy->v = v;
   1753        e_legacy->digest = get_voter(v)->legacy_id_digest;
   1754        e_legacy->is_legacy = 1;
   1755        smartlist_add(dir_sources, e_legacy);
   1756      }
   1757    } SMARTLIST_FOREACH_END(v);
   1758    smartlist_sort(dir_sources, compare_dir_src_ents_by_authority_id_);
   1759 
   1760    SMARTLIST_FOREACH_BEGIN(dir_sources, const dir_src_ent_t *, e) {
   1761      char fingerprint[HEX_DIGEST_LEN+1];
   1762      char votedigest[HEX_DIGEST_LEN+1];
   1763      networkstatus_t *v = e->v;
   1764      networkstatus_voter_info_t *voter = get_voter(v);
   1765 
   1766      base16_encode(fingerprint, sizeof(fingerprint), e->digest, DIGEST_LEN);
   1767      base16_encode(votedigest, sizeof(votedigest), voter->vote_digest,
   1768                    DIGEST_LEN);
   1769 
   1770      smartlist_add_asprintf(chunks,
   1771                   "dir-source %s%s %s %s %s %d %d\n",
   1772                   voter->nickname, e->is_legacy ? "-legacy" : "",
   1773                   fingerprint, voter->address, fmt_addr(&voter->ipv4_addr),
   1774                   voter->ipv4_dirport,
   1775                   voter->ipv4_orport);
   1776      if (! e->is_legacy) {
   1777        smartlist_add_asprintf(chunks,
   1778                     "contact %s\n"
   1779                     "vote-digest %s\n",
   1780                     voter->contact,
   1781                     votedigest);
   1782      }
   1783    } SMARTLIST_FOREACH_END(e);
   1784    SMARTLIST_FOREACH(dir_sources, dir_src_ent_t *, e, tor_free(e));
   1785    smartlist_free(dir_sources);
   1786  }
   1787 
   1788  {
   1789    max_unmeasured_bw_kb = dirvote_get_intermediate_param_value(
   1790                param_list, "maxunmeasuredbw", DEFAULT_MAX_UNMEASURED_BW_KB);
   1791    if (max_unmeasured_bw_kb < 1)
   1792      max_unmeasured_bw_kb = 1;
   1793  }
   1794 
   1795  /* Add the actual router entries. */
   1796  {
   1797    int *size; /* size[j] is the number of routerstatuses in votes[j]. */
   1798    int *flag_counts; /* The number of voters that list flag[j] for the
   1799                       * currently considered router. */
   1800    int i;
   1801    smartlist_t *matching_descs = smartlist_new();
   1802    smartlist_t *chosen_flags = smartlist_new();
   1803    smartlist_t *versions = smartlist_new();
   1804    smartlist_t *protocols = smartlist_new();
   1805    smartlist_t *exitsummaries = smartlist_new();
   1806    uint32_t *bandwidths_kb = tor_calloc(smartlist_len(votes),
   1807                                         sizeof(uint32_t));
   1808    uint32_t *measured_bws_kb = tor_calloc(smartlist_len(votes),
   1809                                           sizeof(uint32_t));
   1810    uint32_t *measured_guardfraction = tor_calloc(smartlist_len(votes),
   1811                                                  sizeof(uint32_t));
   1812    int num_bandwidths;
   1813    int num_mbws;
   1814    int num_guardfraction_inputs;
   1815 
   1816    int *n_voter_flags; /* n_voter_flags[j] is the number of flags that
   1817                         * votes[j] knows about. */
   1818    int *n_flag_voters; /* n_flag_voters[f] is the number of votes that care
   1819                         * about flags[f]. */
   1820    int **flag_map; /* flag_map[j][b] is an index f such that flag_map[f]
   1821                     * is the same flag as votes[j]->known_flags[b]. */
   1822    int *named_flag; /* Index of the flag "Named" for votes[j] */
   1823    int *unnamed_flag; /* Index of the flag "Unnamed" for votes[j] */
   1824    int n_authorities_measuring_bandwidth;
   1825 
   1826    strmap_t *name_to_id_map = strmap_new();
   1827    char conflict[DIGEST_LEN];
   1828    char unknown[DIGEST_LEN];
   1829    memset(conflict, 0, sizeof(conflict));
   1830    memset(unknown, 0xff, sizeof(conflict));
   1831 
   1832    size = tor_calloc(smartlist_len(votes), sizeof(int));
   1833    n_voter_flags = tor_calloc(smartlist_len(votes), sizeof(int));
   1834    n_flag_voters = tor_calloc(smartlist_len(flags), sizeof(int));
   1835    flag_map = tor_calloc(smartlist_len(votes), sizeof(int *));
   1836    named_flag = tor_calloc(smartlist_len(votes), sizeof(int));
   1837    unnamed_flag = tor_calloc(smartlist_len(votes), sizeof(int));
   1838    for (i = 0; i < smartlist_len(votes); ++i)
   1839      unnamed_flag[i] = named_flag[i] = -1;
   1840 
   1841    /* Build the flag indexes. Note that no vote can have more than 64 members
   1842     * for known_flags, so no value will be greater than 63, so it's safe to
   1843     * do UINT64_C(1) << index on these values.  But note also that
   1844     * named_flag and unnamed_flag are initialized to -1, so we need to check
   1845     * that they're actually set before doing UINT64_C(1) << index with
   1846     * them.*/
   1847    SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
   1848      flag_map[v_sl_idx] = tor_calloc(smartlist_len(v->known_flags),
   1849                                      sizeof(int));
   1850      if (smartlist_len(v->known_flags) > MAX_KNOWN_FLAGS_IN_VOTE) {
   1851        log_warn(LD_BUG, "Somehow, a vote has %d entries in known_flags",
   1852                 smartlist_len(v->known_flags));
   1853      }
   1854      SMARTLIST_FOREACH_BEGIN(v->known_flags, const char *, fl) {
   1855        int p = smartlist_string_pos(flags, fl);
   1856        tor_assert(p >= 0);
   1857        flag_map[v_sl_idx][fl_sl_idx] = p;
   1858        ++n_flag_voters[p];
   1859        if (!strcmp(fl, "Named"))
   1860          named_flag[v_sl_idx] = fl_sl_idx;
   1861        if (!strcmp(fl, "Unnamed"))
   1862          unnamed_flag[v_sl_idx] = fl_sl_idx;
   1863      } SMARTLIST_FOREACH_END(fl);
   1864      n_voter_flags[v_sl_idx] = smartlist_len(v->known_flags);
   1865      size[v_sl_idx] = smartlist_len(v->routerstatus_list);
   1866    } SMARTLIST_FOREACH_END(v);
   1867 
   1868    /* Named and Unnamed get treated specially */
   1869    {
   1870      SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
   1871        uint64_t nf;
   1872        if (named_flag[v_sl_idx]<0)
   1873          continue;
   1874        nf = UINT64_C(1) << named_flag[v_sl_idx];
   1875        SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
   1876                                vote_routerstatus_t *, rs) {
   1877 
   1878          if ((rs->flags & nf) != 0) {
   1879            const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
   1880            if (!d) {
   1881              /* We have no name officially mapped to this digest. */
   1882              strmap_set_lc(name_to_id_map, rs->status.nickname,
   1883                            rs->status.identity_digest);
   1884            } else if (d != conflict &&
   1885                fast_memcmp(d, rs->status.identity_digest, DIGEST_LEN)) {
   1886              /* Authorities disagree about this nickname. */
   1887              strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
   1888            } else {
   1889              /* It's already a conflict, or it's already this ID. */
   1890            }
   1891          }
   1892        } SMARTLIST_FOREACH_END(rs);
   1893      } SMARTLIST_FOREACH_END(v);
   1894 
   1895      SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
   1896        uint64_t uf;
   1897        if (unnamed_flag[v_sl_idx]<0)
   1898          continue;
   1899        uf = UINT64_C(1) << unnamed_flag[v_sl_idx];
   1900        SMARTLIST_FOREACH_BEGIN(v->routerstatus_list,
   1901                                vote_routerstatus_t *, rs) {
   1902          if ((rs->flags & uf) != 0) {
   1903            const char *d = strmap_get_lc(name_to_id_map, rs->status.nickname);
   1904            if (d == conflict || d == unknown) {
   1905              /* Leave it alone; we know what it is. */
   1906            } else if (!d) {
   1907              /* We have no name officially mapped to this digest. */
   1908              strmap_set_lc(name_to_id_map, rs->status.nickname, unknown);
   1909            } else if (fast_memeq(d, rs->status.identity_digest, DIGEST_LEN)) {
   1910              /* Authorities disagree about this nickname. */
   1911              strmap_set_lc(name_to_id_map, rs->status.nickname, conflict);
   1912            } else {
   1913              /* It's mapped to a different name. */
   1914            }
   1915          }
   1916        } SMARTLIST_FOREACH_END(rs);
   1917      } SMARTLIST_FOREACH_END(v);
   1918    }
   1919 
   1920    /* We need to know how many votes measure bandwidth. */
   1921    n_authorities_measuring_bandwidth = 0;
   1922    SMARTLIST_FOREACH(votes, const networkstatus_t *, v,
   1923       if (v->has_measured_bws) {
   1924         ++n_authorities_measuring_bandwidth;
   1925       }
   1926    );
   1927 
   1928    /* Populate the collator */
   1929    collator = dircollator_new(smartlist_len(votes), total_authorities);
   1930    SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
   1931      dircollator_add_vote(collator, v);
   1932    } SMARTLIST_FOREACH_END(v);
   1933 
   1934    dircollator_collate(collator, consensus_method);
   1935 
   1936    /* Now go through all the votes */
   1937    flag_counts = tor_calloc(smartlist_len(flags), sizeof(int));
   1938    const int num_routers = dircollator_n_routers(collator);
   1939    for (i = 0; i < num_routers; ++i) {
   1940      vote_routerstatus_t **vrs_lst =
   1941        dircollator_get_votes_for_router(collator, i);
   1942 
   1943      vote_routerstatus_t *rs;
   1944      routerstatus_t rs_out;
   1945      const char *current_rsa_id = NULL;
   1946      const char *chosen_version;
   1947      const char *chosen_protocol_list;
   1948      const char *chosen_name = NULL;
   1949      int exitsummary_disagreement = 0;
   1950      int is_named = 0, is_unnamed = 0, is_running = 0, is_valid = 0;
   1951      int is_guard = 0, is_exit = 0, is_bad_exit = 0, is_middle_only = 0;
   1952      int naming_conflict = 0;
   1953      int n_listing = 0;
   1954      char microdesc_digest[DIGEST256_LEN];
   1955      tor_addr_port_t alt_orport = {TOR_ADDR_NULL, 0};
   1956 
   1957      memset(flag_counts, 0, sizeof(int)*smartlist_len(flags));
   1958      smartlist_clear(matching_descs);
   1959      smartlist_clear(chosen_flags);
   1960      smartlist_clear(versions);
   1961      smartlist_clear(protocols);
   1962      num_bandwidths = 0;
   1963      num_mbws = 0;
   1964      num_guardfraction_inputs = 0;
   1965      int ed_consensus = 0;
   1966      const uint8_t *ed_consensus_val = NULL;
   1967 
   1968      /* Okay, go through all the entries for this digest. */
   1969      for (int voter_idx = 0; voter_idx < smartlist_len(votes); ++voter_idx) {
   1970        if (vrs_lst[voter_idx] == NULL)
   1971          continue; /* This voter had nothing to say about this entry. */
   1972        rs = vrs_lst[voter_idx];
   1973        ++n_listing;
   1974 
   1975        current_rsa_id = rs->status.identity_digest;
   1976 
   1977        smartlist_add(matching_descs, rs);
   1978        if (rs->version && rs->version[0])
   1979          smartlist_add(versions, rs->version);
   1980 
   1981        if (rs->protocols) {
   1982          /* We include this one even if it's empty: voting for an
   1983           * empty protocol list actually is meaningful. */
   1984          smartlist_add(protocols, rs->protocols);
   1985        }
   1986 
   1987        /* Tally up all the flags. */
   1988        for (int flag = 0; flag < n_voter_flags[voter_idx]; ++flag) {
   1989          if (rs->flags & (UINT64_C(1) << flag))
   1990            ++flag_counts[flag_map[voter_idx][flag]];
   1991        }
   1992        if (named_flag[voter_idx] >= 0 &&
   1993            (rs->flags & (UINT64_C(1) << named_flag[voter_idx]))) {
   1994          if (chosen_name && strcmp(chosen_name, rs->status.nickname)) {
   1995            log_notice(LD_DIR, "Conflict on naming for router: %s vs %s",
   1996                       chosen_name, rs->status.nickname);
   1997            naming_conflict = 1;
   1998          }
   1999          chosen_name = rs->status.nickname;
   2000        }
   2001 
   2002        /* Count guardfraction votes and note down the values. */
   2003        if (rs->status.has_guardfraction) {
   2004          measured_guardfraction[num_guardfraction_inputs++] =
   2005            rs->status.guardfraction_percentage;
   2006        }
   2007 
   2008        /* count bandwidths */
   2009        if (rs->has_measured_bw)
   2010          measured_bws_kb[num_mbws++] = rs->measured_bw_kb;
   2011 
   2012        if (rs->status.has_bandwidth)
   2013          bandwidths_kb[num_bandwidths++] = rs->status.bandwidth_kb;
   2014 
   2015        /* Count number for which ed25519 is canonical. */
   2016        if (rs->ed25519_reflects_consensus) {
   2017          ++ed_consensus;
   2018          if (ed_consensus_val) {
   2019            tor_assert(fast_memeq(ed_consensus_val, rs->ed25519_id,
   2020                                  ED25519_PUBKEY_LEN));
   2021          } else {
   2022            ed_consensus_val = rs->ed25519_id;
   2023          }
   2024        }
   2025      }
   2026 
   2027      /* We don't include this router at all unless more than half of
   2028       * the authorities we believe in list it. */
   2029      if (n_listing <= total_authorities/2)
   2030        continue;
   2031 
   2032      if (ed_consensus > 0) {
   2033        if (ed_consensus <= total_authorities / 2) {
   2034          log_warn(LD_BUG, "Not enough entries had ed_consensus set; how "
   2035                   "can we have a consensus of %d?", ed_consensus);
   2036        }
   2037      }
   2038 
   2039      /* The clangalyzer can't figure out that this will never be NULL
   2040       * if n_listing is at least 1 */
   2041      tor_assert(current_rsa_id);
   2042 
   2043      /* Figure out the most popular opinion of what the most recent
   2044       * routerinfo and its contents are. */
   2045      memset(microdesc_digest, 0, sizeof(microdesc_digest));
   2046      rs = compute_routerstatus_consensus(matching_descs, consensus_method,
   2047                                          microdesc_digest, &alt_orport);
   2048      /* Copy bits of that into rs_out. */
   2049      memset(&rs_out, 0, sizeof(rs_out));
   2050      tor_assert(fast_memeq(current_rsa_id,
   2051                            rs->status.identity_digest,DIGEST_LEN));
   2052      memcpy(rs_out.identity_digest, current_rsa_id, DIGEST_LEN);
   2053      memcpy(rs_out.descriptor_digest, rs->status.descriptor_digest,
   2054             DIGEST_LEN);
   2055      tor_addr_copy(&rs_out.ipv4_addr, &rs->status.ipv4_addr);
   2056      rs_out.ipv4_dirport = rs->status.ipv4_dirport;
   2057      rs_out.ipv4_orport = rs->status.ipv4_orport;
   2058      tor_addr_copy(&rs_out.ipv6_addr, &alt_orport.addr);
   2059      rs_out.ipv6_orport = alt_orport.port;
   2060      rs_out.has_bandwidth = 0;
   2061      rs_out.has_exitsummary = 0;
   2062 
   2063      time_t published_on = rs->published_on;
   2064 
   2065      /* Starting with this consensus method, we no longer include a
   2066         meaningful published_on time for microdescriptor consensuses.  This
   2067         makes their diffs smaller and more compressible.
   2068 
   2069         We need to keep including a meaningful published_on time for NS
   2070         consensuses, however, until 035 relays are all obsolete. (They use
   2071         it for a purpose similar to the current StaleDesc flag.)
   2072      */
   2073      if (consensus_method >= MIN_METHOD_TO_SUPPRESS_MD_PUBLISHED &&
   2074          flavor == FLAV_MICRODESC) {
   2075        published_on = -1;
   2076      }
   2077 
   2078      if (chosen_name && !naming_conflict) {
   2079        strlcpy(rs_out.nickname, chosen_name, sizeof(rs_out.nickname));
   2080      } else {
   2081        strlcpy(rs_out.nickname, rs->status.nickname, sizeof(rs_out.nickname));
   2082      }
   2083 
   2084      {
   2085        const char *d = strmap_get_lc(name_to_id_map, rs_out.nickname);
   2086        if (!d) {
   2087          is_named = is_unnamed = 0;
   2088        } else if (fast_memeq(d, current_rsa_id, DIGEST_LEN)) {
   2089          is_named = 1; is_unnamed = 0;
   2090        } else {
   2091          is_named = 0; is_unnamed = 1;
   2092        }
   2093      }
   2094 
   2095      /* Set the flags. */
   2096      SMARTLIST_FOREACH_BEGIN(flags, const char *, fl) {
   2097        if (!strcmp(fl, "Named")) {
   2098          if (is_named)
   2099            smartlist_add(chosen_flags, (char*)fl);
   2100        } else if (!strcmp(fl, "Unnamed")) {
   2101          if (is_unnamed)
   2102            smartlist_add(chosen_flags, (char*)fl);
   2103        } else if (!strcmp(fl, "NoEdConsensus")) {
   2104          if (ed_consensus <= total_authorities/2)
   2105            smartlist_add(chosen_flags, (char*)fl);
   2106        } else {
   2107          if (flag_counts[fl_sl_idx] > n_flag_voters[fl_sl_idx]/2) {
   2108            smartlist_add(chosen_flags, (char*)fl);
   2109            if (!strcmp(fl, "Exit"))
   2110              is_exit = 1;
   2111            else if (!strcmp(fl, "Guard"))
   2112              is_guard = 1;
   2113            else if (!strcmp(fl, "Running"))
   2114              is_running = 1;
   2115            else if (!strcmp(fl, "BadExit"))
   2116              is_bad_exit = 1;
   2117            else if (!strcmp(fl, "MiddleOnly"))
   2118              is_middle_only = 1;
   2119            else if (!strcmp(fl, "Valid"))
   2120              is_valid = 1;
   2121          }
   2122        }
   2123      } SMARTLIST_FOREACH_END(fl);
   2124 
   2125      /* Starting with consensus method 4 we do not list servers
   2126       * that are not running in a consensus.  See Proposal 138 */
   2127      if (!is_running)
   2128        continue;
   2129 
   2130      /* Starting with consensus method 24, we don't list servers
   2131       * that are not valid in a consensus.  See Proposal 272 */
   2132      if (!is_valid)
   2133        continue;
   2134 
   2135      /* Starting with consensus method 32, we handle the middle-only
   2136       * flag specially: when it is present, we clear some flags, and
   2137       * set others. */
   2138      if (is_middle_only) {
   2139        remove_flag(chosen_flags, "Exit");
   2140        remove_flag(chosen_flags, "V2Dir");
   2141        remove_flag(chosen_flags, "Guard");
   2142        remove_flag(chosen_flags, "HSDir");
   2143        is_exit = is_guard = 0;
   2144        if (! is_bad_exit && badexit_flag_is_listed) {
   2145          is_bad_exit = 1;
   2146          smartlist_add(chosen_flags, (char *)"BadExit");
   2147          smartlist_sort_strings(chosen_flags); // restore order.
   2148        }
   2149      }
   2150 
   2151      /* Pick the version. */
   2152      if (smartlist_len(versions)) {
   2153        sort_version_list(versions, 0);
   2154        chosen_version = get_most_frequent_member(versions);
   2155      } else {
   2156        chosen_version = NULL;
   2157      }
   2158 
   2159      /* Pick the protocol list */
   2160      if (smartlist_len(protocols)) {
   2161        smartlist_sort_strings(protocols);
   2162        chosen_protocol_list = get_most_frequent_member(protocols);
   2163      } else {
   2164        chosen_protocol_list = NULL;
   2165      }
   2166 
   2167      /* If it's a guard and we have enough guardfraction votes,
   2168         calculate its consensus guardfraction value. */
   2169      if (is_guard && num_guardfraction_inputs > 2) {
   2170        rs_out.has_guardfraction = 1;
   2171        rs_out.guardfraction_percentage = median_uint32(measured_guardfraction,
   2172                                                     num_guardfraction_inputs);
   2173        /* final value should be an integer percentage! */
   2174        tor_assert(rs_out.guardfraction_percentage <= 100);
   2175      }
   2176 
   2177      /* Pick a bandwidth */
   2178      if (num_mbws > 2) {
   2179        rs_out.has_bandwidth = 1;
   2180        rs_out.bw_is_unmeasured = 0;
   2181        rs_out.bandwidth_kb = median_uint32(measured_bws_kb, num_mbws);
   2182      } else if (num_bandwidths > 0) {
   2183        rs_out.has_bandwidth = 1;
   2184        rs_out.bw_is_unmeasured = 1;
   2185        rs_out.bandwidth_kb = median_uint32(bandwidths_kb, num_bandwidths);
   2186        if (n_authorities_measuring_bandwidth > 2) {
   2187          /* Cap non-measured bandwidths. */
   2188          if (rs_out.bandwidth_kb > max_unmeasured_bw_kb) {
   2189            rs_out.bandwidth_kb = max_unmeasured_bw_kb;
   2190          }
   2191        }
   2192      }
   2193 
   2194      /* Fix bug 2203: Do not count BadExit nodes as Exits for bw weights */
   2195      is_exit = is_exit && !is_bad_exit;
   2196 
   2197      /* Update total bandwidth weights with the bandwidths of this router. */
   2198      {
   2199        update_total_bandwidth_weights(&rs_out,
   2200                                       is_exit, is_guard,
   2201                                       &G, &M, &E, &D, &T);
   2202      }
   2203 
   2204      /* Ok, we already picked a descriptor digest we want to list
   2205       * previously.  Now we want to use the exit policy summary from
   2206       * that descriptor.  If everybody plays nice all the voters who
   2207       * listed that descriptor will have the same summary.  If not then
   2208       * something is fishy and we'll use the most common one (breaking
   2209       * ties in favor of lexicographically larger one (only because it
   2210       * lets me reuse more existing code)).
   2211       *
   2212       * The other case that can happen is that no authority that voted
   2213       * for that descriptor has an exit policy summary.  That's
   2214       * probably quite unlikely but can happen.  In that case we use
   2215       * the policy that was most often listed in votes, again breaking
   2216       * ties like in the previous case.
   2217       */
   2218      {
   2219        /* Okay, go through all the votes for this router.  We prepared
   2220         * that list previously */
   2221        const char *chosen_exitsummary = NULL;
   2222        smartlist_clear(exitsummaries);
   2223        SMARTLIST_FOREACH_BEGIN(matching_descs, vote_routerstatus_t *, vsr) {
   2224          /* Check if the vote where this status comes from had the
   2225           * proper descriptor */
   2226          tor_assert(fast_memeq(rs_out.identity_digest,
   2227                             vsr->status.identity_digest,
   2228                             DIGEST_LEN));
   2229          if (vsr->status.has_exitsummary &&
   2230               fast_memeq(rs_out.descriptor_digest,
   2231                       vsr->status.descriptor_digest,
   2232                       DIGEST_LEN)) {
   2233            tor_assert(vsr->status.exitsummary);
   2234            smartlist_add(exitsummaries, vsr->status.exitsummary);
   2235            if (!chosen_exitsummary) {
   2236              chosen_exitsummary = vsr->status.exitsummary;
   2237            } else if (strcmp(chosen_exitsummary, vsr->status.exitsummary)) {
   2238              /* Great.  There's disagreement among the voters.  That
   2239               * really shouldn't be */
   2240              exitsummary_disagreement = 1;
   2241            }
   2242          }
   2243        } SMARTLIST_FOREACH_END(vsr);
   2244 
   2245        if (exitsummary_disagreement) {
   2246          char id[HEX_DIGEST_LEN+1];
   2247          char dd[HEX_DIGEST_LEN+1];
   2248          base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
   2249          base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
   2250          log_warn(LD_DIR, "The voters disagreed on the exit policy summary "
   2251                   " for router %s with descriptor %s.  This really shouldn't"
   2252                   " have happened.", id, dd);
   2253 
   2254          smartlist_sort_strings(exitsummaries);
   2255          chosen_exitsummary = get_most_frequent_member(exitsummaries);
   2256        } else if (!chosen_exitsummary) {
   2257          char id[HEX_DIGEST_LEN+1];
   2258          char dd[HEX_DIGEST_LEN+1];
   2259          base16_encode(id, sizeof(dd), rs_out.identity_digest, DIGEST_LEN);
   2260          base16_encode(dd, sizeof(dd), rs_out.descriptor_digest, DIGEST_LEN);
   2261          log_warn(LD_DIR, "Not one of the voters that made us select"
   2262                   "descriptor %s for router %s had an exit policy"
   2263                   "summary", dd, id);
   2264 
   2265          /* Ok, none of those voting for the digest we chose had an
   2266           * exit policy for us.  Well, that kinda sucks.
   2267           */
   2268          smartlist_clear(exitsummaries);
   2269          SMARTLIST_FOREACH(matching_descs, vote_routerstatus_t *, vsr, {
   2270            if (vsr->status.has_exitsummary)
   2271              smartlist_add(exitsummaries, vsr->status.exitsummary);
   2272          });
   2273          smartlist_sort_strings(exitsummaries);
   2274          chosen_exitsummary = get_most_frequent_member(exitsummaries);
   2275 
   2276          if (!chosen_exitsummary)
   2277            log_warn(LD_DIR, "Wow, not one of the voters had an exit "
   2278                     "policy summary for %s.  Wow.", id);
   2279        }
   2280 
   2281        if (chosen_exitsummary) {
   2282          rs_out.has_exitsummary = 1;
   2283          /* yea, discards the const */
   2284          rs_out.exitsummary = (char *)chosen_exitsummary;
   2285        }
   2286      }
   2287 
   2288      if (flavor == FLAV_MICRODESC &&
   2289          tor_digest256_is_zero(microdesc_digest)) {
   2290        /* With no microdescriptor digest, we omit the entry entirely. */
   2291        continue;
   2292      }
   2293 
   2294      {
   2295        char *buf;
   2296        /* Okay!! Now we can write the descriptor... */
   2297        /*     First line goes into "buf". */
   2298        buf = routerstatus_format_entry(&rs_out, NULL, NULL,
   2299                                        rs_format, NULL, published_on);
   2300        if (buf)
   2301          smartlist_add(chunks, buf);
   2302      }
   2303      /*     Now an m line, if applicable. */
   2304      if (flavor == FLAV_MICRODESC &&
   2305          !tor_digest256_is_zero(microdesc_digest)) {
   2306        char m[BASE64_DIGEST256_LEN+1];
   2307        digest256_to_base64(m, microdesc_digest);
   2308        smartlist_add_asprintf(chunks, "m %s\n", m);
   2309      }
   2310      /*     Next line is all flags.  The "\n" is missing. */
   2311      smartlist_add_asprintf(chunks, "s%s",
   2312                             smartlist_len(chosen_flags)?" ":"");
   2313      smartlist_add(chunks,
   2314                    smartlist_join_strings(chosen_flags, " ", 0, NULL));
   2315      /*     Now the version line. */
   2316      if (chosen_version) {
   2317        smartlist_add_strdup(chunks, "\nv ");
   2318        smartlist_add_strdup(chunks, chosen_version);
   2319      }
   2320      smartlist_add_strdup(chunks, "\n");
   2321      if (chosen_protocol_list) {
   2322        smartlist_add_asprintf(chunks, "pr %s\n", chosen_protocol_list);
   2323      }
   2324      /*     Now the weight line. */
   2325      if (rs_out.has_bandwidth) {
   2326        char *guardfraction_str = NULL;
   2327        int unmeasured = rs_out.bw_is_unmeasured;
   2328 
   2329        /* If we have guardfraction info, include it in the 'w' line. */
   2330        if (rs_out.has_guardfraction) {
   2331          tor_asprintf(&guardfraction_str,
   2332                       " GuardFraction=%u", rs_out.guardfraction_percentage);
   2333        }
   2334        smartlist_add_asprintf(chunks, "w Bandwidth=%d%s%s\n",
   2335                               rs_out.bandwidth_kb,
   2336                               unmeasured?" Unmeasured=1":"",
   2337                               guardfraction_str ? guardfraction_str : "");
   2338 
   2339        tor_free(guardfraction_str);
   2340      }
   2341 
   2342      /*     Now the exitpolicy summary line. */
   2343      if (rs_out.has_exitsummary && flavor == FLAV_NS) {
   2344        smartlist_add_asprintf(chunks, "p %s\n", rs_out.exitsummary);
   2345      }
   2346 
   2347      /* And the loop is over and we move on to the next router */
   2348    }
   2349 
   2350    tor_free(size);
   2351    tor_free(n_voter_flags);
   2352    tor_free(n_flag_voters);
   2353    for (i = 0; i < smartlist_len(votes); ++i)
   2354      tor_free(flag_map[i]);
   2355    tor_free(flag_map);
   2356    tor_free(flag_counts);
   2357    tor_free(named_flag);
   2358    tor_free(unnamed_flag);
   2359    strmap_free(name_to_id_map, NULL);
   2360    smartlist_free(matching_descs);
   2361    smartlist_free(chosen_flags);
   2362    smartlist_free(versions);
   2363    smartlist_free(protocols);
   2364    smartlist_free(exitsummaries);
   2365    tor_free(bandwidths_kb);
   2366    tor_free(measured_bws_kb);
   2367    tor_free(measured_guardfraction);
   2368  }
   2369 
   2370  /* Mark the directory footer region */
   2371  smartlist_add_strdup(chunks, "directory-footer\n");
   2372 
   2373  {
   2374    int64_t weight_scale;
   2375    weight_scale = dirvote_get_intermediate_param_value(
   2376                     param_list, "bwweightscale", BW_WEIGHT_SCALE);
   2377    if (weight_scale < 1)
   2378      weight_scale = 1;
   2379    added_weights = networkstatus_compute_bw_weights_v10(chunks, G, M, E, D,
   2380                                                         T, weight_scale);
   2381  }
   2382 
   2383  /* Write the unsigned proposed consensus text to disk, for dir auth
   2384   * debugging purposes, and also to put a sig-less consensus file in
   2385   * place for (with luck) later export to the consensus transparency
   2386   * module. */
   2387  {
   2388    char *unsigned_consensus = smartlist_join_strings(chunks, "", 0, NULL);
   2389    char *filename = NULL;
   2390    tor_asprintf(&filename, "my-consensus-%s", flavor_name);
   2391    char *fpath = get_datadir_fname(filename);
   2392    write_str_to_file(fpath, unsigned_consensus, 0);
   2393    tor_free(filename);
   2394    tor_free(fpath);
   2395    tor_free(unsigned_consensus);
   2396  }
   2397 
   2398  /* Add a signature. */
   2399  {
   2400    char digest[DIGEST256_LEN];
   2401    char fingerprint[HEX_DIGEST_LEN+1];
   2402    char signing_key_fingerprint[HEX_DIGEST_LEN+1];
   2403    digest_algorithm_t digest_alg =
   2404      flavor == FLAV_NS ? DIGEST_SHA1 : DIGEST_SHA256;
   2405    size_t digest_len =
   2406      flavor == FLAV_NS ? DIGEST_LEN : DIGEST256_LEN;
   2407    const char *algname = crypto_digest_algorithm_get_name(digest_alg);
   2408    char *signature;
   2409 
   2410    smartlist_add_strdup(chunks, "directory-signature ");
   2411 
   2412    /* Compute the hash of the chunks. */
   2413    crypto_digest_smartlist(digest, digest_len, chunks, "", digest_alg);
   2414 
   2415    /* Get the fingerprints */
   2416    crypto_pk_get_fingerprint(identity_key, fingerprint, 0);
   2417    crypto_pk_get_fingerprint(signing_key, signing_key_fingerprint, 0);
   2418 
   2419    /* add the junk that will go at the end of the line. */
   2420    if (flavor == FLAV_NS) {
   2421      smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
   2422                   signing_key_fingerprint);
   2423    } else {
   2424      smartlist_add_asprintf(chunks, "%s %s %s\n",
   2425                   algname, fingerprint,
   2426                   signing_key_fingerprint);
   2427    }
   2428    /* And the signature. */
   2429    if (!(signature = router_get_dirobj_signature(digest, digest_len,
   2430                                                  signing_key))) {
   2431      log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
   2432      goto done;
   2433    }
   2434    smartlist_add(chunks, signature);
   2435 
   2436    if (legacy_id_key_digest && legacy_signing_key) {
   2437      smartlist_add_strdup(chunks, "directory-signature ");
   2438      base16_encode(fingerprint, sizeof(fingerprint),
   2439                    legacy_id_key_digest, DIGEST_LEN);
   2440      crypto_pk_get_fingerprint(legacy_signing_key,
   2441                                signing_key_fingerprint, 0);
   2442      if (flavor == FLAV_NS) {
   2443        smartlist_add_asprintf(chunks, "%s %s\n", fingerprint,
   2444                     signing_key_fingerprint);
   2445      } else {
   2446        smartlist_add_asprintf(chunks, "%s %s %s\n",
   2447                     algname, fingerprint,
   2448                     signing_key_fingerprint);
   2449      }
   2450 
   2451      if (!(signature = router_get_dirobj_signature(digest, digest_len,
   2452                                                    legacy_signing_key))) {
   2453        log_warn(LD_BUG, "Couldn't sign consensus networkstatus.");
   2454        goto done;
   2455      }
   2456      smartlist_add(chunks, signature);
   2457    }
   2458  }
   2459 
   2460  result = smartlist_join_strings(chunks, "", 0, NULL);
   2461 
   2462  {
   2463    networkstatus_t *c;
   2464    if (!(c = networkstatus_parse_vote_from_string(result, strlen(result),
   2465                                                   NULL,
   2466                                                   NS_TYPE_CONSENSUS))) {
   2467      log_err(LD_BUG, "Generated a networkstatus consensus we couldn't "
   2468              "parse.");
   2469      tor_free(result);
   2470      goto done;
   2471    }
   2472    // Verify balancing parameters
   2473    if (added_weights) {
   2474      networkstatus_verify_bw_weights(c, consensus_method);
   2475    }
   2476    networkstatus_vote_free(c);
   2477  }
   2478 
   2479 done:
   2480 
   2481  dircollator_free(collator);
   2482  tor_free(client_versions);
   2483  tor_free(server_versions);
   2484  tor_free(packages);
   2485  SMARTLIST_FOREACH(flags, char *, cp, tor_free(cp));
   2486  smartlist_free(flags);
   2487  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   2488  smartlist_free(chunks);
   2489  SMARTLIST_FOREACH(param_list, char *, cp, tor_free(cp));
   2490  smartlist_free(param_list);
   2491 
   2492  return result;
   2493 }
   2494 
   2495 /** Given a list of networkstatus_t for each vote, return a newly allocated
   2496 * string containing the "package" lines for the vote. */
   2497 STATIC char *
   2498 compute_consensus_package_lines(smartlist_t *votes)
   2499 {
   2500  const int n_votes = smartlist_len(votes);
   2501 
   2502  /* This will be a map from "packagename version" strings to arrays
   2503   * of const char *, with the i'th member of the array corresponding to the
   2504   * package line from the i'th vote.
   2505   */
   2506  strmap_t *package_status = strmap_new();
   2507 
   2508  SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
   2509    if (! v->package_lines)
   2510      continue;
   2511    SMARTLIST_FOREACH_BEGIN(v->package_lines, const char *, line) {
   2512      if (! validate_recommended_package_line(line))
   2513        continue;
   2514 
   2515      /* Skip 'cp' to the second space in the line. */
   2516      const char *cp = strchr(line, ' ');
   2517      if (!cp) continue;
   2518      ++cp;
   2519      cp = strchr(cp, ' ');
   2520      if (!cp) continue;
   2521 
   2522      char *key = tor_strndup(line, cp - line);
   2523 
   2524      const char **status = strmap_get(package_status, key);
   2525      if (!status) {
   2526        status = tor_calloc(n_votes, sizeof(const char *));
   2527        strmap_set(package_status, key, status);
   2528      }
   2529      status[v_sl_idx] = line; /* overwrite old value */
   2530      tor_free(key);
   2531    } SMARTLIST_FOREACH_END(line);
   2532  } SMARTLIST_FOREACH_END(v);
   2533 
   2534  smartlist_t *entries = smartlist_new(); /* temporary */
   2535  smartlist_t *result_list = smartlist_new(); /* output */
   2536  STRMAP_FOREACH(package_status, key, const char **, values) {
   2537    int i, count=-1;
   2538    for (i = 0; i < n_votes; ++i) {
   2539      if (values[i])
   2540        smartlist_add(entries, (void*) values[i]);
   2541    }
   2542    smartlist_sort_strings(entries);
   2543    int n_voting_for_entry = smartlist_len(entries);
   2544    const char *most_frequent =
   2545      smartlist_get_most_frequent_string_(entries, &count);
   2546 
   2547    if (n_voting_for_entry >= 3 && count > n_voting_for_entry / 2) {
   2548      smartlist_add_asprintf(result_list, "package %s\n", most_frequent);
   2549    }
   2550 
   2551    smartlist_clear(entries);
   2552 
   2553  } STRMAP_FOREACH_END;
   2554 
   2555  smartlist_sort_strings(result_list);
   2556 
   2557  char *result = smartlist_join_strings(result_list, "", 0, NULL);
   2558 
   2559  SMARTLIST_FOREACH(result_list, char *, cp, tor_free(cp));
   2560  smartlist_free(result_list);
   2561  smartlist_free(entries);
   2562  strmap_free(package_status, tor_free_);
   2563 
   2564  return result;
   2565 }
   2566 
   2567 /** Given a consensus vote <b>target</b> and a set of detached signatures in
   2568 * <b>sigs</b> that correspond to the same consensus, check whether there are
   2569 * any new signatures in <b>src_voter_list</b> that should be added to
   2570 * <b>target</b>. (A signature should be added if we have no signature for that
   2571 * voter in <b>target</b> yet, or if we have no verifiable signature and the
   2572 * new signature is verifiable.)
   2573 *
   2574 * Return the number of signatures added or changed, or -1 if the document
   2575 * signatures are invalid. Sets *<b>msg_out</b> to a string constant
   2576 * describing the signature status.
   2577 */
   2578 STATIC int
   2579 networkstatus_add_detached_signatures(networkstatus_t *target,
   2580                                      ns_detached_signatures_t *sigs,
   2581                                      const char *source,
   2582                                      int severity,
   2583                                      const char **msg_out)
   2584 {
   2585  int r = 0;
   2586  const char *flavor;
   2587  smartlist_t *siglist;
   2588  tor_assert(sigs);
   2589  tor_assert(target);
   2590  tor_assert(target->type == NS_TYPE_CONSENSUS);
   2591 
   2592  flavor = networkstatus_get_flavor_name(target->flavor);
   2593 
   2594  /* Do the times seem right? */
   2595  if (target->valid_after != sigs->valid_after) {
   2596    *msg_out = "Valid-After times do not match "
   2597      "when adding detached signatures to consensus";
   2598    return -1;
   2599  }
   2600  if (target->fresh_until != sigs->fresh_until) {
   2601    *msg_out = "Fresh-until times do not match "
   2602      "when adding detached signatures to consensus";
   2603    return -1;
   2604  }
   2605  if (target->valid_until != sigs->valid_until) {
   2606    *msg_out = "Valid-until times do not match "
   2607      "when adding detached signatures to consensus";
   2608    return -1;
   2609  }
   2610  siglist = strmap_get(sigs->signatures, flavor);
   2611  if (!siglist) {
   2612    *msg_out = "No signatures for given consensus flavor";
   2613    return -1;
   2614  }
   2615 
   2616  /** Make sure all the digests we know match, and at least one matches. */
   2617  {
   2618    common_digests_t *digests = strmap_get(sigs->digests, flavor);
   2619    int n_matches = 0;
   2620    int alg;
   2621    if (!digests) {
   2622      *msg_out = "No digests for given consensus flavor";
   2623      return -1;
   2624    }
   2625    for (alg = DIGEST_SHA1; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
   2626      if (!fast_mem_is_zero(digests->d[alg], DIGEST256_LEN)) {
   2627        if (fast_memeq(target->digests.d[alg], digests->d[alg],
   2628                       DIGEST256_LEN)) {
   2629          ++n_matches;
   2630        } else {
   2631          *msg_out = "Mismatched digest.";
   2632          return -1;
   2633        }
   2634      }
   2635    }
   2636    if (!n_matches) {
   2637      *msg_out = "No recognized digests for given consensus flavor";
   2638    }
   2639  }
   2640 
   2641  /* For each voter in src... */
   2642  SMARTLIST_FOREACH_BEGIN(siglist, document_signature_t *, sig) {
   2643    char voter_identity[HEX_DIGEST_LEN+1];
   2644    networkstatus_voter_info_t *target_voter =
   2645      networkstatus_get_voter_by_id(target, sig->identity_digest);
   2646    authority_cert_t *cert = NULL;
   2647    const char *algorithm;
   2648    document_signature_t *old_sig = NULL;
   2649 
   2650    algorithm = crypto_digest_algorithm_get_name(sig->alg);
   2651 
   2652    base16_encode(voter_identity, sizeof(voter_identity),
   2653                  sig->identity_digest, DIGEST_LEN);
   2654    log_info(LD_DIR, "Looking at signature from %s using %s", voter_identity,
   2655             algorithm);
   2656    /* If the target doesn't know about this voter, then forget it. */
   2657    if (!target_voter) {
   2658      log_info(LD_DIR, "We do not know any voter with ID %s", voter_identity);
   2659      continue;
   2660    }
   2661 
   2662    old_sig = networkstatus_get_voter_sig_by_alg(target_voter, sig->alg);
   2663 
   2664    /* If the target already has a good signature from this voter, then skip
   2665     * this one. */
   2666    if (old_sig && old_sig->good_signature) {
   2667      log_info(LD_DIR, "We already have a good signature from %s using %s",
   2668               voter_identity, algorithm);
   2669      continue;
   2670    }
   2671 
   2672    /* Try checking the signature if we haven't already. */
   2673    if (!sig->good_signature && !sig->bad_signature) {
   2674      cert = authority_cert_get_by_digests(sig->identity_digest,
   2675                                           sig->signing_key_digest);
   2676      if (cert) {
   2677        /* Not checking the return value here, since we are going to look
   2678         * at the status of sig->good_signature in a moment. */
   2679        (void) networkstatus_check_document_signature(target, sig, cert);
   2680      }
   2681    }
   2682 
   2683    /* If this signature is good, or we don't have any signature yet,
   2684     * then maybe add it. */
   2685    if (sig->good_signature || !old_sig || old_sig->bad_signature) {
   2686      log_info(LD_DIR, "Adding signature from %s with %s", voter_identity,
   2687               algorithm);
   2688      tor_log(severity, LD_DIR, "Added a signature for %s from %s.",
   2689          target_voter->nickname, source);
   2690      ++r;
   2691      if (old_sig) {
   2692        smartlist_remove(target_voter->sigs, old_sig);
   2693        document_signature_free(old_sig);
   2694      }
   2695      smartlist_add(target_voter->sigs, document_signature_dup(sig));
   2696    } else {
   2697      log_info(LD_DIR, "Not adding signature from %s", voter_identity);
   2698    }
   2699  } SMARTLIST_FOREACH_END(sig);
   2700 
   2701  return r;
   2702 }
   2703 
   2704 /** Return a newly allocated string containing all the signatures on
   2705 * <b>consensus</b> by all voters. If <b>for_detached_signatures</b> is true,
   2706 * then the signatures will be put in a detached signatures document, so
   2707 * prefix any non-NS-flavored signatures with "additional-signature" rather
   2708 * than "directory-signature". */
   2709 static char *
   2710 networkstatus_format_signatures(networkstatus_t *consensus,
   2711                                int for_detached_signatures)
   2712 {
   2713  smartlist_t *elements;
   2714  char buf[4096];
   2715  char *result = NULL;
   2716  int n_sigs = 0;
   2717  const consensus_flavor_t flavor = consensus->flavor;
   2718  const char *flavor_name = networkstatus_get_flavor_name(flavor);
   2719  const char *keyword;
   2720 
   2721  if (for_detached_signatures && flavor != FLAV_NS)
   2722    keyword = "additional-signature";
   2723  else
   2724    keyword = "directory-signature";
   2725 
   2726  elements = smartlist_new();
   2727 
   2728  SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *, v) {
   2729    SMARTLIST_FOREACH_BEGIN(v->sigs, document_signature_t *, sig) {
   2730      char sk[HEX_DIGEST_LEN+1];
   2731      char id[HEX_DIGEST_LEN+1];
   2732      if (!sig->signature || sig->bad_signature)
   2733        continue;
   2734      ++n_sigs;
   2735      base16_encode(sk, sizeof(sk), sig->signing_key_digest, DIGEST_LEN);
   2736      base16_encode(id, sizeof(id), sig->identity_digest, DIGEST_LEN);
   2737      if (flavor == FLAV_NS) {
   2738        smartlist_add_asprintf(elements,
   2739                     "%s %s %s\n-----BEGIN SIGNATURE-----\n",
   2740                     keyword, id, sk);
   2741      } else {
   2742        const char *digest_name =
   2743          crypto_digest_algorithm_get_name(sig->alg);
   2744        smartlist_add_asprintf(elements,
   2745                     "%s%s%s %s %s %s\n-----BEGIN SIGNATURE-----\n",
   2746                     keyword,
   2747                     for_detached_signatures ? " " : "",
   2748                     for_detached_signatures ? flavor_name : "",
   2749                     digest_name, id, sk);
   2750      }
   2751      base64_encode(buf, sizeof(buf), sig->signature, sig->signature_len,
   2752                    BASE64_ENCODE_MULTILINE);
   2753      strlcat(buf, "-----END SIGNATURE-----\n", sizeof(buf));
   2754      smartlist_add_strdup(elements, buf);
   2755    } SMARTLIST_FOREACH_END(sig);
   2756  } SMARTLIST_FOREACH_END(v);
   2757 
   2758  result = smartlist_join_strings(elements, "", 0, NULL);
   2759  SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
   2760  smartlist_free(elements);
   2761  if (!n_sigs)
   2762    tor_free(result);
   2763  return result;
   2764 }
   2765 
   2766 /** Return a newly allocated string holding the detached-signatures document
   2767 * corresponding to the signatures on <b>consensuses</b>, which must contain
   2768 * exactly one FLAV_NS consensus, and no more than one consensus for each
   2769 * other flavor. */
   2770 STATIC char *
   2771 networkstatus_get_detached_signatures(smartlist_t *consensuses)
   2772 {
   2773  smartlist_t *elements;
   2774  char *result = NULL, *sigs = NULL;
   2775  networkstatus_t *consensus_ns = NULL;
   2776  tor_assert(consensuses);
   2777 
   2778  SMARTLIST_FOREACH(consensuses, networkstatus_t *, ns, {
   2779      tor_assert(ns);
   2780      tor_assert(ns->type == NS_TYPE_CONSENSUS);
   2781      if (ns && ns->flavor == FLAV_NS)
   2782        consensus_ns = ns;
   2783  });
   2784  if (!consensus_ns) {
   2785    log_warn(LD_BUG, "No NS consensus given.");
   2786    return NULL;
   2787  }
   2788 
   2789  elements = smartlist_new();
   2790 
   2791  {
   2792    char va_buf[ISO_TIME_LEN+1], fu_buf[ISO_TIME_LEN+1],
   2793      vu_buf[ISO_TIME_LEN+1];
   2794    char d[HEX_DIGEST_LEN+1];
   2795 
   2796    base16_encode(d, sizeof(d),
   2797                  consensus_ns->digests.d[DIGEST_SHA1], DIGEST_LEN);
   2798    format_iso_time(va_buf, consensus_ns->valid_after);
   2799    format_iso_time(fu_buf, consensus_ns->fresh_until);
   2800    format_iso_time(vu_buf, consensus_ns->valid_until);
   2801 
   2802    smartlist_add_asprintf(elements,
   2803                 "consensus-digest %s\n"
   2804                 "valid-after %s\n"
   2805                 "fresh-until %s\n"
   2806                 "valid-until %s\n", d, va_buf, fu_buf, vu_buf);
   2807  }
   2808 
   2809  /* Get all the digests for the non-FLAV_NS consensuses */
   2810  SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
   2811    const char *flavor_name = networkstatus_get_flavor_name(ns->flavor);
   2812    int alg;
   2813    if (ns->flavor == FLAV_NS)
   2814      continue;
   2815 
   2816    /* start with SHA256; we don't include SHA1 for anything but the basic
   2817     * consensus. */
   2818    for (alg = DIGEST_SHA256; alg < N_COMMON_DIGEST_ALGORITHMS; ++alg) {
   2819      char d[HEX_DIGEST256_LEN+1];
   2820      const char *alg_name =
   2821        crypto_digest_algorithm_get_name(alg);
   2822      if (fast_mem_is_zero(ns->digests.d[alg], DIGEST256_LEN))
   2823        continue;
   2824      base16_encode(d, sizeof(d), ns->digests.d[alg], DIGEST256_LEN);
   2825      smartlist_add_asprintf(elements, "additional-digest %s %s %s\n",
   2826                   flavor_name, alg_name, d);
   2827    }
   2828  } SMARTLIST_FOREACH_END(ns);
   2829 
   2830  /* Now get all the sigs for non-FLAV_NS consensuses */
   2831  SMARTLIST_FOREACH_BEGIN(consensuses, networkstatus_t *, ns) {
   2832    char *sigs_on_this_consensus;
   2833    if (ns->flavor == FLAV_NS)
   2834      continue;
   2835    sigs_on_this_consensus = networkstatus_format_signatures(ns, 1);
   2836    if (!sigs_on_this_consensus) {
   2837      log_warn(LD_DIR, "Couldn't format signatures");
   2838      goto err;
   2839    }
   2840    smartlist_add(elements, sigs_on_this_consensus);
   2841  } SMARTLIST_FOREACH_END(ns);
   2842 
   2843  /* Now add the FLAV_NS consensus signatrures. */
   2844  sigs = networkstatus_format_signatures(consensus_ns, 1);
   2845  if (!sigs)
   2846    goto err;
   2847  smartlist_add(elements, sigs);
   2848 
   2849  result = smartlist_join_strings(elements, "", 0, NULL);
   2850 err:
   2851  SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
   2852  smartlist_free(elements);
   2853  return result;
   2854 }
   2855 
   2856 /** Return a newly allocated string holding a detached-signatures document for
   2857 * all of the in-progress consensuses in the <b>n_flavors</b>-element array at
   2858 * <b>pending</b>. */
   2859 static char *
   2860 get_detached_signatures_from_pending_consensuses(pending_consensus_t *pending,
   2861                                                 int n_flavors)
   2862 {
   2863  int flav;
   2864  char *signatures;
   2865  smartlist_t *c = smartlist_new();
   2866  for (flav = 0; flav < n_flavors; ++flav) {
   2867    if (pending[flav].consensus)
   2868      smartlist_add(c, pending[flav].consensus);
   2869  }
   2870  signatures = networkstatus_get_detached_signatures(c);
   2871  smartlist_free(c);
   2872  return signatures;
   2873 }
   2874 
   2875 /**
   2876 * Entry point: Take whatever voting actions are pending as of <b>now</b>.
   2877 *
   2878 * Return the time at which the next action should be taken.
   2879 */
   2880 time_t
   2881 dirvote_act(const or_options_t *options, time_t now)
   2882 {
   2883  if (!authdir_mode_v3(options))
   2884    return TIME_MAX;
   2885  tor_assert_nonfatal(voting_schedule.voting_starts);
   2886  /* If we haven't initialized this object through this codeflow, we need to
   2887   * recalculate the timings to match our vote. The reason to do that is if we
   2888   * have a voting schedule initialized 1 minute ago, the voting timings might
   2889   * not be aligned to what we should expect with "now". This is especially
   2890   * true for TestingTorNetwork using smaller timings.  */
   2891  if (voting_schedule.created_on_demand) {
   2892    char *keys = list_v3_auth_ids();
   2893    authority_cert_t *c = get_my_v3_authority_cert();
   2894    log_notice(LD_DIR, "Scheduling voting.  Known authority IDs are %s. "
   2895               "Mine is %s.",
   2896               keys, hex_str(c->cache_info.identity_digest, DIGEST_LEN));
   2897    tor_free(keys);
   2898    dirauth_sched_recalculate_timing(options, now);
   2899  }
   2900 
   2901 #define IF_TIME_FOR_NEXT_ACTION(when_field, done_field) \
   2902  if (! voting_schedule.done_field) {                   \
   2903    if (voting_schedule.when_field > now) {             \
   2904      return voting_schedule.when_field;                \
   2905    } else {
   2906 #define ENDIF \
   2907    }           \
   2908  }
   2909 
   2910  IF_TIME_FOR_NEXT_ACTION(voting_starts, have_voted) {
   2911    log_notice(LD_DIR, "Time to vote.");
   2912    dirvote_perform_vote();
   2913    voting_schedule.have_voted = 1;
   2914  } ENDIF
   2915  IF_TIME_FOR_NEXT_ACTION(fetch_missing_votes, have_fetched_missing_votes) {
   2916    log_notice(LD_DIR, "Time to fetch any votes that we're missing.");
   2917    dirvote_fetch_missing_votes();
   2918    voting_schedule.have_fetched_missing_votes = 1;
   2919  } ENDIF
   2920  IF_TIME_FOR_NEXT_ACTION(voting_ends, have_built_consensus) {
   2921    log_notice(LD_DIR, "Time to compute a consensus.");
   2922    dirvote_compute_consensuses();
   2923    /* XXXX We will want to try again later if we haven't got enough
   2924     * votes yet.  Implement this if it turns out to ever happen. */
   2925    voting_schedule.have_built_consensus = 1;
   2926  } ENDIF
   2927  IF_TIME_FOR_NEXT_ACTION(fetch_missing_signatures,
   2928                          have_fetched_missing_signatures) {
   2929    log_notice(LD_DIR, "Time to fetch any signatures that we're missing.");
   2930    dirvote_fetch_missing_signatures();
   2931    voting_schedule.have_fetched_missing_signatures = 1;
   2932  } ENDIF
   2933  IF_TIME_FOR_NEXT_ACTION(interval_starts,
   2934                          have_published_consensus) {
   2935    log_notice(LD_DIR, "Time to publish the consensus and discard old votes");
   2936    dirvote_publish_consensus();
   2937    dirvote_clear_votes(0);
   2938    voting_schedule.have_published_consensus = 1;
   2939    /* Update our shared random state with the consensus just published. */
   2940    sr_act_post_consensus(
   2941                networkstatus_get_latest_consensus_by_flavor(FLAV_NS));
   2942    /* XXXX We will want to try again later if we haven't got enough
   2943     * signatures yet.  Implement this if it turns out to ever happen. */
   2944    dirauth_sched_recalculate_timing(options, now);
   2945    return voting_schedule.voting_starts;
   2946  } ENDIF
   2947 
   2948  tor_assert_nonfatal_unreached();
   2949  return now + 1;
   2950 
   2951 #undef ENDIF
   2952 #undef IF_TIME_FOR_NEXT_ACTION
   2953 }
   2954 
   2955 /** A vote networkstatus_t and its unparsed body: held around so we can
   2956 * use it to generate a consensus (at voting_ends) and so we can serve it to
   2957 * other authorities that might want it. */
   2958 typedef struct pending_vote_t {
   2959  cached_dir_t *vote_body;
   2960  networkstatus_t *vote;
   2961 } pending_vote_t;
   2962 
   2963 /** List of pending_vote_t for the current vote.  Before we've used them to
   2964 * build a consensus, the votes go here. */
   2965 static smartlist_t *pending_vote_list = NULL;
   2966 /** List of pending_vote_t for the previous vote.  After we've used them to
   2967 * build a consensus, the votes go here for the next period. */
   2968 static smartlist_t *previous_vote_list = NULL;
   2969 
   2970 /* DOCDOC pending_consensuses */
   2971 static pending_consensus_t pending_consensuses[N_CONSENSUS_FLAVORS];
   2972 
   2973 /** The detached signatures for the consensus that we're currently
   2974 * building. */
   2975 static char *pending_consensus_signatures = NULL;
   2976 
   2977 /** List of ns_detached_signatures_t: hold signatures that get posted to us
   2978 * before we have generated the consensus on our own. */
   2979 static smartlist_t *pending_consensus_signature_list = NULL;
   2980 
   2981 /** Generate a networkstatus vote and post it to all the v3 authorities.
   2982 * (V3 Authority only) */
   2983 static int
   2984 dirvote_perform_vote(void)
   2985 {
   2986  crypto_pk_t *key = get_my_v3_authority_signing_key();
   2987  authority_cert_t *cert = get_my_v3_authority_cert();
   2988  networkstatus_t *ns;
   2989  char *contents;
   2990  pending_vote_t *pending_vote;
   2991  time_t now = time(NULL);
   2992 
   2993  int status;
   2994  const char *msg = "";
   2995 
   2996  if (!cert || !key) {
   2997    log_warn(LD_NET, "Didn't find key/certificate to generate v3 vote");
   2998    return -1;
   2999  } else if (cert->expires < now) {
   3000    log_warn(LD_NET, "Can't generate v3 vote with expired certificate");
   3001    return -1;
   3002  }
   3003  if (!(ns = dirserv_generate_networkstatus_vote_obj(key, cert)))
   3004    return -1;
   3005 
   3006  contents = format_networkstatus_vote(key, ns);
   3007  networkstatus_vote_free(ns);
   3008  if (!contents)
   3009    return -1;
   3010 
   3011  pending_vote = dirvote_add_vote(contents, 0, "self", &msg, &status);
   3012  tor_free(contents);
   3013  if (!pending_vote) {
   3014    log_warn(LD_DIR, "Couldn't store my own vote! (I told myself, '%s'.)",
   3015             msg);
   3016    return -1;
   3017  }
   3018 
   3019  directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_VOTE,
   3020                               ROUTER_PURPOSE_GENERAL,
   3021                               V3_DIRINFO,
   3022                               pending_vote->vote_body->dir,
   3023                               pending_vote->vote_body->dir_len, 0);
   3024  log_notice(LD_DIR, "Vote posted.");
   3025  return 0;
   3026 }
   3027 
   3028 /** Send an HTTP request to every other v3 authority, for the votes of every
   3029 * authority for which we haven't received a vote yet in this period. (V3
   3030 * authority only) */
   3031 static void
   3032 dirvote_fetch_missing_votes(void)
   3033 {
   3034  smartlist_t *missing_fps = smartlist_new();
   3035  char *resource;
   3036 
   3037  SMARTLIST_FOREACH_BEGIN(router_get_trusted_dir_servers(),
   3038                          dir_server_t *, ds) {
   3039      if (!(ds->type & V3_DIRINFO))
   3040        continue;
   3041      if (!dirvote_get_vote(ds->v3_identity_digest,
   3042                            DGV_BY_ID|DGV_INCLUDE_PENDING)) {
   3043        char *cp = tor_malloc(HEX_DIGEST_LEN+1);
   3044        base16_encode(cp, HEX_DIGEST_LEN+1, ds->v3_identity_digest,
   3045                      DIGEST_LEN);
   3046        smartlist_add(missing_fps, cp);
   3047      }
   3048  } SMARTLIST_FOREACH_END(ds);
   3049 
   3050  if (!smartlist_len(missing_fps)) {
   3051    smartlist_free(missing_fps);
   3052    return;
   3053  }
   3054  {
   3055    char *tmp = smartlist_join_strings(missing_fps, " ", 0, NULL);
   3056    log_notice(LOG_NOTICE, "We're missing votes from %d authorities (%s). "
   3057               "Asking every other authority for a copy.",
   3058               smartlist_len(missing_fps), tmp);
   3059    tor_free(tmp);
   3060  }
   3061  resource = smartlist_join_strings(missing_fps, "+", 0, NULL);
   3062  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_STATUS_VOTE,
   3063                                     0, resource);
   3064  tor_free(resource);
   3065  SMARTLIST_FOREACH(missing_fps, char *, cp, tor_free(cp));
   3066  smartlist_free(missing_fps);
   3067 }
   3068 
   3069 /** Send a request to every other authority for its detached signatures,
   3070 * unless we have signatures from all other v3 authorities already. */
   3071 static void
   3072 dirvote_fetch_missing_signatures(void)
   3073 {
   3074  int need_any = 0;
   3075  int i;
   3076  for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
   3077    networkstatus_t *consensus = pending_consensuses[i].consensus;
   3078    if (!consensus ||
   3079        networkstatus_check_consensus_signature(consensus, -1) == 1) {
   3080      /* We have no consensus, or we have one that's signed by everybody. */
   3081      continue;
   3082    }
   3083    need_any = 1;
   3084  }
   3085  if (!need_any)
   3086    return;
   3087 
   3088  directory_get_from_all_authorities(DIR_PURPOSE_FETCH_DETACHED_SIGNATURES,
   3089                                     0, NULL);
   3090 }
   3091 
   3092 /** Release all storage held by pending consensuses (those waiting for
   3093 * signatures). */
   3094 static void
   3095 dirvote_clear_pending_consensuses(void)
   3096 {
   3097  int i;
   3098  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
   3099    pending_consensus_t *pc = &pending_consensuses[i];
   3100    tor_free(pc->body);
   3101 
   3102    networkstatus_vote_free(pc->consensus);
   3103    pc->consensus = NULL;
   3104  }
   3105 }
   3106 
   3107 /** Drop all currently pending votes, consensus, and detached signatures. */
   3108 static void
   3109 dirvote_clear_votes(int all_votes)
   3110 {
   3111  if (!previous_vote_list)
   3112    previous_vote_list = smartlist_new();
   3113  if (!pending_vote_list)
   3114    pending_vote_list = smartlist_new();
   3115 
   3116  /* All "previous" votes are now junk. */
   3117  SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, v, {
   3118      cached_dir_decref(v->vote_body);
   3119      v->vote_body = NULL;
   3120      networkstatus_vote_free(v->vote);
   3121      tor_free(v);
   3122    });
   3123  smartlist_clear(previous_vote_list);
   3124 
   3125  if (all_votes) {
   3126    /* If we're dumping all the votes, we delete the pending ones. */
   3127    SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
   3128        cached_dir_decref(v->vote_body);
   3129        v->vote_body = NULL;
   3130        networkstatus_vote_free(v->vote);
   3131        tor_free(v);
   3132      });
   3133  } else {
   3134    /* Otherwise, we move them into "previous". */
   3135    smartlist_add_all(previous_vote_list, pending_vote_list);
   3136  }
   3137  smartlist_clear(pending_vote_list);
   3138 
   3139  if (pending_consensus_signature_list) {
   3140    SMARTLIST_FOREACH(pending_consensus_signature_list, char *, cp,
   3141                      tor_free(cp));
   3142    smartlist_clear(pending_consensus_signature_list);
   3143  }
   3144  tor_free(pending_consensus_signatures);
   3145  dirvote_clear_pending_consensuses();
   3146 }
   3147 
   3148 /** Return a newly allocated string containing the hex-encoded v3 authority
   3149    identity digest of every recognized v3 authority. */
   3150 static char *
   3151 list_v3_auth_ids(void)
   3152 {
   3153  smartlist_t *known_v3_keys = smartlist_new();
   3154  char *keys;
   3155  SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
   3156                    dir_server_t *, ds,
   3157    if ((ds->type & V3_DIRINFO) &&
   3158        !tor_digest_is_zero(ds->v3_identity_digest))
   3159      smartlist_add(known_v3_keys,
   3160                    tor_strdup(hex_str(ds->v3_identity_digest, DIGEST_LEN))));
   3161  keys = smartlist_join_strings(known_v3_keys, ", ", 0, NULL);
   3162  SMARTLIST_FOREACH(known_v3_keys, char *, cp, tor_free(cp));
   3163  smartlist_free(known_v3_keys);
   3164  return keys;
   3165 }
   3166 
   3167 /* Check the voter information <b>vi</b>, and  assert that at least one
   3168 * signature is good. Asserts on failure. */
   3169 static void
   3170 assert_any_sig_good(const networkstatus_voter_info_t *vi)
   3171 {
   3172  int any_sig_good = 0;
   3173  SMARTLIST_FOREACH(vi->sigs, document_signature_t *, sig,
   3174                    if (sig->good_signature)
   3175                      any_sig_good = 1);
   3176  tor_assert(any_sig_good);
   3177 }
   3178 
   3179 /* Add <b>cert</b> to our list of known authority certificates. */
   3180 static void
   3181 add_new_cert_if_needed(const struct authority_cert_t *cert)
   3182 {
   3183  tor_assert(cert);
   3184  if (!authority_cert_get_by_digests(cert->cache_info.identity_digest,
   3185                                     cert->signing_key_digest)) {
   3186    /* Hey, it's a new cert! */
   3187    trusted_dirs_load_certs_from_string(
   3188                               cert->cache_info.signed_descriptor_body,
   3189                               TRUSTED_DIRS_CERTS_SRC_FROM_VOTE, 1 /*flush*/,
   3190                               NULL);
   3191    if (!authority_cert_get_by_digests(cert->cache_info.identity_digest,
   3192                                       cert->signing_key_digest)) {
   3193      log_warn(LD_BUG, "We added a cert, but still couldn't find it.");
   3194    }
   3195  }
   3196 }
   3197 
   3198 /** Called when we have received a networkstatus vote in <b>vote_body</b>.
   3199 * Parse and validate it, and on success store it as a pending vote (which we
   3200 * then return).  Return NULL on failure.  Sets *<b>msg_out</b> and
   3201 * *<b>status_out</b> to an HTTP response and status code.  (V3 authority
   3202 * only) */
   3203 pending_vote_t *
   3204 dirvote_add_vote(const char *vote_body, time_t time_posted,
   3205                 const char *where_from,
   3206                 const char **msg_out, int *status_out)
   3207 {
   3208  networkstatus_t *vote;
   3209  networkstatus_voter_info_t *vi;
   3210  dir_server_t *ds;
   3211  pending_vote_t *pending_vote = NULL;
   3212  const char *end_of_vote = NULL;
   3213  int any_failed = 0;
   3214  tor_assert(vote_body);
   3215  tor_assert(msg_out);
   3216  tor_assert(status_out);
   3217 
   3218  if (!pending_vote_list)
   3219    pending_vote_list = smartlist_new();
   3220  *status_out = 0;
   3221  *msg_out = NULL;
   3222 
   3223 again:
   3224  vote = networkstatus_parse_vote_from_string(vote_body, strlen(vote_body),
   3225                                              &end_of_vote,
   3226                                              NS_TYPE_VOTE);
   3227  if (!end_of_vote)
   3228    end_of_vote = vote_body + strlen(vote_body);
   3229  if (!vote) {
   3230    log_warn(LD_DIR, "Couldn't parse vote: length was %d",
   3231             (int)strlen(vote_body));
   3232    *msg_out = "Unable to parse vote";
   3233    goto err;
   3234  }
   3235  tor_assert(smartlist_len(vote->voters) == 1);
   3236  vi = get_voter(vote);
   3237  assert_any_sig_good(vi);
   3238  ds = trusteddirserver_get_by_v3_auth_digest(vi->identity_digest);
   3239  if (!ds) {
   3240    char *keys = list_v3_auth_ids();
   3241    log_warn(LD_DIR, "Got a vote from an authority (nickname %s, address %s) "
   3242             "with authority key ID %s. "
   3243             "This key ID is not recognized.  Known v3 key IDs are: %s",
   3244             vi->nickname, vi->address,
   3245             hex_str(vi->identity_digest, DIGEST_LEN), keys);
   3246    tor_free(keys);
   3247    *msg_out = "Vote not from a recognized v3 authority";
   3248    goto err;
   3249  }
   3250  add_new_cert_if_needed(vote->cert);
   3251 
   3252  /* Is it for the right period? */
   3253  if (vote->valid_after != voting_schedule.interval_starts) {
   3254    char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
   3255    format_iso_time(tbuf1, vote->valid_after);
   3256    format_iso_time(tbuf2, voting_schedule.interval_starts);
   3257    log_warn(LD_DIR, "Rejecting vote from %s with valid-after time of %s; "
   3258             "we were expecting %s", vi->address, tbuf1, tbuf2);
   3259    *msg_out = "Bad valid-after time";
   3260    goto err;
   3261  }
   3262 
   3263  if (time_posted) { /* they sent it to me via a POST */
   3264    log_notice(LD_DIR, "%s posted a vote to me from %s.",
   3265               vi->nickname, where_from);
   3266  } else { /* I imported this one myself */
   3267    log_notice(LD_DIR, "Retrieved %s's vote from %s.",
   3268               vi->nickname, where_from);
   3269  }
   3270 
   3271  /* Check if we received it, as a post, after the cutoff when we
   3272   * start asking other dir auths for it. If we do, the best plan
   3273   * is to discard it, because using it greatly increases the chances
   3274   * of a split vote for this round (some dir auths got it in time,
   3275   * some didn't). */
   3276  if (time_posted && time_posted > voting_schedule.fetch_missing_votes) {
   3277    char tbuf1[ISO_TIME_LEN+1], tbuf2[ISO_TIME_LEN+1];
   3278    format_iso_time(tbuf1, time_posted);
   3279    format_iso_time(tbuf2, voting_schedule.fetch_missing_votes);
   3280    log_warn(LD_DIR, "Rejecting %s's posted vote from %s received at %s; "
   3281             "our cutoff for received votes is %s. Check your clock, "
   3282             "CPU load, and network load. Also check the authority that "
   3283             "posted the vote.", vi->nickname, vi->address, tbuf1, tbuf2);
   3284    *msg_out = "Posted vote received too late, would be dangerous to count it";
   3285    goto err;
   3286  }
   3287 
   3288  /* Fetch any new router descriptors we just learned about */
   3289  update_consensus_router_descriptor_downloads(time(NULL), 1, vote);
   3290 
   3291  /* Now see whether we already have a vote from this authority. */
   3292  SMARTLIST_FOREACH_BEGIN(pending_vote_list, pending_vote_t *, v) {
   3293      if (fast_memeq(v->vote->cert->cache_info.identity_digest,
   3294                   vote->cert->cache_info.identity_digest,
   3295                   DIGEST_LEN)) {
   3296        networkstatus_voter_info_t *vi_old = get_voter(v->vote);
   3297        if (fast_memeq(vi_old->vote_digest, vi->vote_digest, DIGEST_LEN)) {
   3298          /* Ah, it's the same vote. Not a problem. */
   3299          log_notice(LD_DIR, "Discarding a vote we already have (from %s).",
   3300                     vi->address);
   3301          if (*status_out < 200)
   3302            *status_out = 200;
   3303          goto discard;
   3304        } else if (v->vote->published < vote->published) {
   3305          log_notice(LD_DIR, "Replacing an older pending vote from this "
   3306                     "directory (%s)", vi->address);
   3307          cached_dir_decref(v->vote_body);
   3308          networkstatus_vote_free(v->vote);
   3309          v->vote_body = new_cached_dir(tor_strndup(vote_body,
   3310                                                    end_of_vote-vote_body),
   3311                                        vote->published);
   3312          v->vote = vote;
   3313          if (end_of_vote &&
   3314              !strcmpstart(end_of_vote, "network-status-version"))
   3315            goto again;
   3316 
   3317          if (*status_out < 200)
   3318            *status_out = 200;
   3319          if (!*msg_out)
   3320            *msg_out = "OK";
   3321          return v;
   3322        } else {
   3323          log_notice(LD_DIR, "Discarding vote from %s because we have "
   3324                     "a newer one already.", vi->address);
   3325          *msg_out = "Already have a newer pending vote";
   3326          goto err;
   3327        }
   3328      }
   3329  } SMARTLIST_FOREACH_END(v);
   3330 
   3331  /* This a valid vote, update our shared random state. */
   3332  sr_handle_received_commits(vote->sr_info.commits,
   3333                             vote->cert->identity_key);
   3334 
   3335  pending_vote = tor_malloc_zero(sizeof(pending_vote_t));
   3336  pending_vote->vote_body = new_cached_dir(tor_strndup(vote_body,
   3337                                                       end_of_vote-vote_body),
   3338                                           vote->published);
   3339  pending_vote->vote = vote;
   3340  smartlist_add(pending_vote_list, pending_vote);
   3341 
   3342  if (!strcmpstart(end_of_vote, "network-status-version ")) {
   3343    vote_body = end_of_vote;
   3344    goto again;
   3345  }
   3346 
   3347  goto done;
   3348 
   3349 err:
   3350  any_failed = 1;
   3351  if (!*msg_out)
   3352    *msg_out = "Error adding vote";
   3353  if (*status_out < 400)
   3354    *status_out = 400;
   3355 
   3356 discard:
   3357  networkstatus_vote_free(vote);
   3358 
   3359  if (end_of_vote && !strcmpstart(end_of_vote, "network-status-version ")) {
   3360    vote_body = end_of_vote;
   3361    goto again;
   3362  }
   3363 
   3364 done:
   3365 
   3366  if (*status_out < 200)
   3367    *status_out = 200;
   3368  if (!*msg_out) {
   3369    if (!any_failed && !pending_vote) {
   3370      *msg_out = "Duplicate discarded";
   3371    } else {
   3372      *msg_out = "ok";
   3373    }
   3374  }
   3375 
   3376  return any_failed ? NULL : pending_vote;
   3377 }
   3378 
   3379 /* Write the votes in <b>pending_vote_list</b> to disk. */
   3380 static void
   3381 write_v3_votes_to_disk(const smartlist_t *pending_votes)
   3382 {
   3383  smartlist_t *votestrings = smartlist_new();
   3384  char *votefile = NULL;
   3385 
   3386  SMARTLIST_FOREACH(pending_votes, pending_vote_t *, v,
   3387    {
   3388      sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
   3389      c->bytes = v->vote_body->dir;
   3390      c->len = v->vote_body->dir_len;
   3391      smartlist_add(votestrings, c); /* collect strings to write to disk */
   3392    });
   3393 
   3394  votefile = get_datadir_fname("v3-status-votes");
   3395  write_chunks_to_file(votefile, votestrings, 0, 0);
   3396  log_debug(LD_DIR, "Wrote votes to disk (%s)!", votefile);
   3397 
   3398  tor_free(votefile);
   3399  SMARTLIST_FOREACH(votestrings, sized_chunk_t *, c, tor_free(c));
   3400  smartlist_free(votestrings);
   3401 }
   3402 
   3403 /** Try to compute a v3 networkstatus consensus from the currently pending
   3404 * votes.  Return 0 on success, -1 on failure.  Store the consensus in
   3405 * pending_consensus: it won't be ready to be published until we have
   3406 * everybody else's signatures collected too. (V3 Authority only) */
   3407 static int
   3408 dirvote_compute_consensuses(void)
   3409 {
   3410  /* Have we got enough votes to try? */
   3411  int n_votes, n_voters, n_vote_running = 0;
   3412  smartlist_t *votes = NULL;
   3413  char *consensus_body = NULL, *signatures = NULL;
   3414  networkstatus_t *consensus = NULL;
   3415  authority_cert_t *my_cert;
   3416  pending_consensus_t pending[N_CONSENSUS_FLAVORS];
   3417  int flav;
   3418 
   3419  memset(pending, 0, sizeof(pending));
   3420 
   3421  if (!pending_vote_list)
   3422    pending_vote_list = smartlist_new();
   3423 
   3424  /* Write votes to disk */
   3425  write_v3_votes_to_disk(pending_vote_list);
   3426 
   3427  /* Setup votes smartlist */
   3428  votes = smartlist_new();
   3429  SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v,
   3430    {
   3431      smartlist_add(votes, v->vote); /* collect votes to compute consensus */
   3432    });
   3433 
   3434  /* See if consensus managed to achieve majority */
   3435  n_voters = get_n_authorities(V3_DIRINFO);
   3436  n_votes = smartlist_len(pending_vote_list);
   3437  if (n_votes <= n_voters/2) {
   3438    log_warn(LD_DIR, "We don't have enough votes to generate a consensus: "
   3439             "%d of %d", n_votes, n_voters/2+1);
   3440    goto err;
   3441  }
   3442  tor_assert(pending_vote_list);
   3443  SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, v, {
   3444    if (smartlist_contains_string(v->vote->known_flags, "Running"))
   3445      n_vote_running++;
   3446  });
   3447  if (!n_vote_running) {
   3448    /* See task 1066. */
   3449    log_warn(LD_DIR, "Nobody has voted on the Running flag. Generating "
   3450                     "and publishing a consensus without Running nodes "
   3451                     "would make many clients stop working. Not "
   3452                     "generating a consensus!");
   3453    goto err;
   3454  }
   3455 
   3456  if (!(my_cert = get_my_v3_authority_cert())) {
   3457    log_warn(LD_DIR, "Can't generate consensus without a certificate.");
   3458    goto err;
   3459  }
   3460 
   3461  {
   3462    char legacy_dbuf[DIGEST_LEN];
   3463    crypto_pk_t *legacy_sign=NULL;
   3464    char *legacy_id_digest = NULL;
   3465    int n_generated = 0;
   3466    if (get_options()->V3AuthUseLegacyKey) {
   3467      authority_cert_t *cert = get_my_v3_legacy_cert();
   3468      legacy_sign = get_my_v3_legacy_signing_key();
   3469      if (cert) {
   3470        if (crypto_pk_get_digest(cert->identity_key, legacy_dbuf)) {
   3471          log_warn(LD_BUG,
   3472                   "Unable to compute digest of legacy v3 identity key");
   3473        } else {
   3474          legacy_id_digest = legacy_dbuf;
   3475        }
   3476      }
   3477    }
   3478 
   3479    for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
   3480      const char *flavor_name = networkstatus_get_flavor_name(flav);
   3481      consensus_body = networkstatus_compute_consensus(
   3482        votes, n_voters,
   3483        my_cert->identity_key,
   3484        get_my_v3_authority_signing_key(), legacy_id_digest, legacy_sign,
   3485        flav);
   3486 
   3487      if (!consensus_body) {
   3488        log_warn(LD_DIR, "Couldn't generate a %s consensus at all!",
   3489                 flavor_name);
   3490        continue;
   3491      }
   3492      consensus = networkstatus_parse_vote_from_string(consensus_body,
   3493                                                       strlen(consensus_body),
   3494                                                       NULL,
   3495                                                       NS_TYPE_CONSENSUS);
   3496      if (!consensus) {
   3497        log_warn(LD_DIR, "Couldn't parse %s consensus we generated!",
   3498                 flavor_name);
   3499        tor_free(consensus_body);
   3500        continue;
   3501      }
   3502 
   3503      /* 'Check' our own signature, to mark it valid. */
   3504      networkstatus_check_consensus_signature(consensus, -1);
   3505 
   3506      pending[flav].body = consensus_body;
   3507      pending[flav].consensus = consensus;
   3508      n_generated++;
   3509 
   3510      consensus_body = NULL;
   3511      consensus = NULL;
   3512    }
   3513    if (!n_generated) {
   3514      log_warn(LD_DIR, "Couldn't generate any consensus flavors at all.");
   3515      goto err;
   3516    }
   3517  }
   3518 
   3519  signatures = get_detached_signatures_from_pending_consensuses(
   3520       pending, N_CONSENSUS_FLAVORS);
   3521 
   3522  if (!signatures) {
   3523    log_warn(LD_DIR, "Couldn't extract signatures.");
   3524    goto err;
   3525  }
   3526 
   3527  dirvote_clear_pending_consensuses();
   3528  memcpy(pending_consensuses, pending, sizeof(pending));
   3529 
   3530  tor_free(pending_consensus_signatures);
   3531  pending_consensus_signatures = signatures;
   3532 
   3533  if (pending_consensus_signature_list) {
   3534    int n_sigs = 0;
   3535    /* we may have gotten signatures for this consensus before we built
   3536     * it ourself.  Add them now. */
   3537    SMARTLIST_FOREACH_BEGIN(pending_consensus_signature_list, char *, sig) {
   3538        const char *msg = NULL;
   3539        int r = dirvote_add_signatures_to_all_pending_consensuses(sig,
   3540                                                     "pending", &msg);
   3541        if (r >= 0)
   3542          n_sigs += r;
   3543        else
   3544          log_warn(LD_DIR,
   3545                   "Could not add queued signature to new consensus: %s",
   3546                   msg);
   3547        tor_free(sig);
   3548    } SMARTLIST_FOREACH_END(sig);
   3549    if (n_sigs)
   3550      log_notice(LD_DIR, "Added %d pending signatures while building "
   3551                 "consensus.", n_sigs);
   3552    smartlist_clear(pending_consensus_signature_list);
   3553  }
   3554 
   3555  log_notice(LD_DIR, "Consensus computed; uploading signature(s)");
   3556 
   3557  directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_SIGNATURES,
   3558                               ROUTER_PURPOSE_GENERAL,
   3559                               V3_DIRINFO,
   3560                               pending_consensus_signatures,
   3561                               strlen(pending_consensus_signatures), 0);
   3562  log_notice(LD_DIR, "Signature(s) posted.");
   3563 
   3564  smartlist_free(votes);
   3565  return 0;
   3566 err:
   3567  smartlist_free(votes);
   3568  tor_free(consensus_body);
   3569  tor_free(signatures);
   3570  networkstatus_vote_free(consensus);
   3571 
   3572  return -1;
   3573 }
   3574 
   3575 /** We just got enough sigs on the pending <b>flavor_name</b>-flavor
   3576 * consensus that it is time to export it to the consensus transparency
   3577 * module. We do this by writing a "consensus-transparency-%s" file which
   3578 * the module will detect and act on.
   3579 *
   3580 * The file needs to be just the bare consensus, with no signatures, so we
   3581 * are registering a hash that everybody can agree on. */
   3582 static void
   3583 export_consensus_for_transparency(const char *flavor_name)
   3584 {
   3585  char *filename = NULL;
   3586  tor_asprintf(&filename, "my-consensus-%s", flavor_name);
   3587  char *fpath_from = get_datadir_fname(filename);
   3588  tor_free(filename);
   3589  tor_asprintf(&filename, "consensus-transparency-%s", flavor_name);
   3590  char *fpath_to = get_datadir_fname(filename);
   3591  tor_free(filename);
   3592 
   3593  replace_file(fpath_from, fpath_to);
   3594 
   3595  log_notice(LD_DIR, "Exported consensus transparency file %s.",
   3596             fpath_to);
   3597 
   3598  tor_free(fpath_from);
   3599  tor_free(fpath_to);
   3600 }
   3601 
   3602 /** Helper: we just received <b>sigs</b> as
   3603 * signatures on the currently pending consensus. Add them to <b>pc</b>
   3604 * as appropriate. Return the number of signatures added, or -1 if error. */
   3605 static int
   3606 dirvote_add_signatures_to_pending_consensus(
   3607                       pending_consensus_t *pc,
   3608                       ns_detached_signatures_t *sigs,
   3609                       const char *source,
   3610                       int severity,
   3611                       const char **msg_out)
   3612 {
   3613  const char *flavor_name;
   3614  int r = -1;
   3615 
   3616  /* Only call if we have a pending consensus right now. */
   3617  tor_assert(pc->consensus);
   3618  tor_assert(pc->body);
   3619  tor_assert(pending_consensus_signatures);
   3620 
   3621  flavor_name = networkstatus_get_flavor_name(pc->consensus->flavor);
   3622  *msg_out = NULL;
   3623 
   3624  {
   3625    smartlist_t *sig_list = strmap_get(sigs->signatures, flavor_name);
   3626    log_info(LD_DIR, "Have %d signatures for adding to %s consensus.",
   3627             sig_list ? smartlist_len(sig_list) : 0, flavor_name);
   3628  }
   3629  r = networkstatus_add_detached_signatures(pc->consensus, sigs,
   3630                                            source, severity, msg_out);
   3631  if (r >= 0) {
   3632    log_info(LD_DIR,"Added %d signatures to consensus.", r);
   3633  } else {
   3634    log_fn(LOG_PROTOCOL_WARN, LD_DIR,
   3635           "Unable to add signatures to consensus: %s",
   3636           *msg_out ? *msg_out : "(unknown)");
   3637  }
   3638 
   3639  if (r >= 1) {
   3640    char *new_signatures =
   3641      networkstatus_format_signatures(pc->consensus, 0);
   3642    char *dst, *dst_end;
   3643    size_t new_consensus_len;
   3644    if (!new_signatures) {
   3645      *msg_out = "No signatures to add";
   3646      goto err;
   3647    }
   3648    new_consensus_len =
   3649      strlen(pc->body) + strlen(new_signatures) + 1;
   3650    pc->body = tor_realloc(pc->body, new_consensus_len);
   3651    dst_end = pc->body + new_consensus_len;
   3652    dst = (char *) find_str_at_start_of_line(pc->body, "directory-signature ");
   3653    tor_assert(dst);
   3654    strlcpy(dst, new_signatures, dst_end-dst);
   3655 
   3656    /* We remove this block once it has failed to crash for a while.  But
   3657     * unless it shows up in profiles, we're probably better leaving it in,
   3658     * just in case we break detached signature processing at some point. */
   3659    {
   3660      networkstatus_t *v = networkstatus_parse_vote_from_string(
   3661                                             pc->body, strlen(pc->body), NULL,
   3662                                             NS_TYPE_CONSENSUS);
   3663      tor_assert(v);
   3664      networkstatus_vote_free(v);
   3665    }
   3666    *msg_out = "Signatures added";
   3667    tor_free(new_signatures);
   3668 
   3669    /* Check if we now have enough sigs that we are confident this
   3670     * will be our consensus. */
   3671    if (!pc->have_exported_for_transparency &&
   3672        networkstatus_check_consensus_signature(pc->consensus, -1) >= 0) {
   3673      /* Yes! Send it to the consensus transparency module. */
   3674      export_consensus_for_transparency(flavor_name);
   3675      pc->have_exported_for_transparency = 1;
   3676    }
   3677 
   3678  } else if (r == 0) {
   3679    *msg_out = "Signatures ignored";
   3680  } else {
   3681    goto err;
   3682  }
   3683 
   3684  goto done;
   3685 err:
   3686  if (!*msg_out)
   3687    *msg_out = "Unrecognized error while adding detached signatures.";
   3688 done:
   3689  return r;
   3690 }
   3691 
   3692 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
   3693 * signatures on the currently pending consensus.  Add them to the pending
   3694 * consensus (if we have one).
   3695 *
   3696 * Set *<b>msg</b> to a string constant describing the status, regardless of
   3697 * success or failure.
   3698 *
   3699 * Return negative on failure, nonnegative on success. */
   3700 static int
   3701 dirvote_add_signatures_to_all_pending_consensuses(
   3702                       const char *detached_signatures_body,
   3703                       const char *source,
   3704                       const char **msg_out)
   3705 {
   3706  int r=0, i, n_added = 0, errors = 0;
   3707  ns_detached_signatures_t *sigs;
   3708  tor_assert(detached_signatures_body);
   3709  tor_assert(msg_out);
   3710  tor_assert(pending_consensus_signatures);
   3711 
   3712  if (!(sigs = networkstatus_parse_detached_signatures(
   3713                               detached_signatures_body, NULL))) {
   3714    *msg_out = "Couldn't parse detached signatures.";
   3715    goto err;
   3716  }
   3717 
   3718  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
   3719    int res;
   3720    int severity = i == FLAV_NS ? LOG_NOTICE : LOG_INFO;
   3721    pending_consensus_t *pc = &pending_consensuses[i];
   3722    if (!pc->consensus)
   3723      continue;
   3724    res = dirvote_add_signatures_to_pending_consensus(pc, sigs, source,
   3725                                                      severity, msg_out);
   3726    if (res < 0)
   3727      errors++;
   3728    else
   3729      n_added += res;
   3730  }
   3731 
   3732  if (errors && !n_added) {
   3733    r = -1;
   3734    goto err;
   3735  }
   3736 
   3737  if (n_added && pending_consensuses[FLAV_NS].consensus) {
   3738    char *new_detached =
   3739      get_detached_signatures_from_pending_consensuses(
   3740                      pending_consensuses, N_CONSENSUS_FLAVORS);
   3741    if (new_detached) {
   3742      tor_free(pending_consensus_signatures);
   3743      pending_consensus_signatures = new_detached;
   3744    }
   3745  }
   3746 
   3747  r = n_added;
   3748  goto done;
   3749 err:
   3750  if (!*msg_out)
   3751    *msg_out = "Unrecognized error while adding detached signatures.";
   3752 done:
   3753  ns_detached_signatures_free(sigs);
   3754  /* XXXX NM Check how return is used.  We can now have an error *and*
   3755     signatures added. */
   3756  return r;
   3757 }
   3758 
   3759 /** Helper: we just got the <b>detached_signatures_body</b> sent to us as
   3760 * signatures on the currently pending consensus.  Add them to the pending
   3761 * consensus (if we have one); otherwise queue them until we have a
   3762 * consensus.
   3763 *
   3764 * Set *<b>msg</b> to a string constant describing the status, regardless of
   3765 * success or failure.
   3766 *
   3767 * Return negative on failure, nonnegative on success. */
   3768 int
   3769 dirvote_add_signatures(const char *detached_signatures_body,
   3770                       const char *source,
   3771                       const char **msg)
   3772 {
   3773  if (pending_consensuses[FLAV_NS].consensus) {
   3774    log_notice(LD_DIR, "Got a signature from %s. "
   3775                       "Adding it to the pending consensus.", source);
   3776    return dirvote_add_signatures_to_all_pending_consensuses(
   3777                                     detached_signatures_body, source, msg);
   3778  } else {
   3779    log_notice(LD_DIR, "Got a signature from %s. "
   3780                       "Queuing it for the next consensus.", source);
   3781    if (!pending_consensus_signature_list)
   3782      pending_consensus_signature_list = smartlist_new();
   3783    smartlist_add_strdup(pending_consensus_signature_list,
   3784                  detached_signatures_body);
   3785    *msg = "Signature queued";
   3786    return 0;
   3787  }
   3788 }
   3789 
   3790 /** Replace the consensus that we're currently serving with the one that we've
   3791 * been building. (V3 Authority only) */
   3792 static int
   3793 dirvote_publish_consensus(void)
   3794 {
   3795  int i;
   3796 
   3797  /* Now remember all the other consensuses as if we were a directory cache. */
   3798  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
   3799    pending_consensus_t *pending = &pending_consensuses[i];
   3800    const char *name;
   3801    name = networkstatus_get_flavor_name(i);
   3802    tor_assert(name);
   3803    if (!pending->consensus ||
   3804      networkstatus_check_consensus_signature(pending->consensus, 1)<0) {
   3805      log_warn(LD_DIR, "Not enough info to publish pending %s consensus",name);
   3806      continue;
   3807    }
   3808 
   3809    if (networkstatus_set_current_consensus(pending->body,
   3810                                            strlen(pending->body),
   3811                                            name, 0, NULL))
   3812      log_warn(LD_DIR, "Error publishing %s consensus", name);
   3813    else
   3814      log_notice(LD_DIR, "Published %s consensus", name);
   3815  }
   3816 
   3817  return 0;
   3818 }
   3819 
   3820 /** Release all static storage held in dirvote.c */
   3821 void
   3822 dirvote_free_all(void)
   3823 {
   3824  dirvote_clear_votes(1);
   3825  /* now empty as a result of dirvote_clear_votes(). */
   3826  smartlist_free(pending_vote_list);
   3827  pending_vote_list = NULL;
   3828  smartlist_free(previous_vote_list);
   3829  previous_vote_list = NULL;
   3830 
   3831  dirvote_clear_pending_consensuses();
   3832  tor_free(pending_consensus_signatures);
   3833  if (pending_consensus_signature_list) {
   3834    /* now empty as a result of dirvote_clear_votes(). */
   3835    smartlist_free(pending_consensus_signature_list);
   3836    pending_consensus_signature_list = NULL;
   3837  }
   3838 }
   3839 
   3840 /* ====
   3841 * Access to pending items.
   3842 * ==== */
   3843 
   3844 /** Return the body of the consensus that we're currently trying to build. */
   3845 MOCK_IMPL(const char *,
   3846 dirvote_get_pending_consensus, (consensus_flavor_t flav))
   3847 {
   3848  tor_assert(((int)flav) >= 0 && (int)flav < N_CONSENSUS_FLAVORS);
   3849  return pending_consensuses[flav].body;
   3850 }
   3851 
   3852 /** Return the signatures that we know for the consensus that we're currently
   3853 * trying to build. */
   3854 MOCK_IMPL(const char *,
   3855 dirvote_get_pending_detached_signatures, (void))
   3856 {
   3857  return pending_consensus_signatures;
   3858 }
   3859 
   3860 /** Return a given vote specified by <b>fp</b>.  If <b>by_id</b>, return the
   3861 * vote for the authority with the v3 authority identity key digest <b>fp</b>;
   3862 * if <b>by_id</b> is false, return the vote whose digest is <b>fp</b>.  If
   3863 * <b>fp</b> is NULL, return our own vote.  If <b>include_previous</b> is
   3864 * false, do not consider any votes for a consensus that's already been built.
   3865 * If <b>include_pending</b> is false, do not consider any votes for the
   3866 * consensus that's in progress.  May return NULL if we have no vote for the
   3867 * authority in question. */
   3868 const cached_dir_t *
   3869 dirvote_get_vote(const char *fp, int flags)
   3870 {
   3871  int by_id = flags & DGV_BY_ID;
   3872  const int include_pending = flags & DGV_INCLUDE_PENDING;
   3873  const int include_previous = flags & DGV_INCLUDE_PREVIOUS;
   3874 
   3875  if (!pending_vote_list && !previous_vote_list)
   3876    return NULL;
   3877  if (fp == NULL) {
   3878    authority_cert_t *c = get_my_v3_authority_cert();
   3879    if (c) {
   3880      fp = c->cache_info.identity_digest;
   3881      by_id = 1;
   3882    } else
   3883      return NULL;
   3884  }
   3885  if (by_id) {
   3886    if (pending_vote_list && include_pending) {
   3887      SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
   3888        if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
   3889          return pv->vote_body);
   3890    }
   3891    if (previous_vote_list && include_previous) {
   3892      SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
   3893        if (fast_memeq(get_voter(pv->vote)->identity_digest, fp, DIGEST_LEN))
   3894          return pv->vote_body);
   3895    }
   3896  } else {
   3897    if (pending_vote_list && include_pending) {
   3898      SMARTLIST_FOREACH(pending_vote_list, pending_vote_t *, pv,
   3899        if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
   3900          return pv->vote_body);
   3901    }
   3902    if (previous_vote_list && include_previous) {
   3903      SMARTLIST_FOREACH(previous_vote_list, pending_vote_t *, pv,
   3904        if (fast_memeq(pv->vote->digests.d[DIGEST_SHA1], fp, DIGEST_LEN))
   3905          return pv->vote_body);
   3906    }
   3907  }
   3908  return NULL;
   3909 }
   3910 
   3911 /** Construct and return a new microdescriptor from a routerinfo <b>ri</b>
   3912 * according to <b>consensus_method</b>.
   3913 **/
   3914 STATIC microdesc_t *
   3915 dirvote_create_microdescriptor(const routerinfo_t *ri, int consensus_method)
   3916 {
   3917  (void) consensus_method; // Currently unneeded...
   3918  microdesc_t *result = NULL;
   3919  char *key = NULL, *summary = NULL, *family = NULL;
   3920  size_t keylen;
   3921  smartlist_t *chunks = smartlist_new();
   3922  char *output = NULL;
   3923  crypto_pk_t *rsa_pubkey = router_get_rsa_onion_pkey(ri->tap_onion_pkey,
   3924                                                      ri->tap_onion_pkey_len);
   3925  if (!rsa_pubkey) {
   3926    /* We do not yet support creating MDs for relays without TAP onion keys. */
   3927    goto done;
   3928  }
   3929 
   3930  if (crypto_pk_write_public_key_to_string(rsa_pubkey, &key, &keylen)<0)
   3931    goto done;
   3932  summary = policy_summarize(ri->exit_policy, AF_INET);
   3933  if (ri->declared_family)
   3934    family = smartlist_join_strings(ri->declared_family, " ", 0, NULL);
   3935 
   3936  smartlist_add_asprintf(chunks, "onion-key\n%s", key);
   3937 
   3938  if (ri->onion_curve25519_pkey) {
   3939    char kbuf[CURVE25519_BASE64_PADDED_LEN + 1];
   3940    curve25519_public_to_base64(kbuf, ri->onion_curve25519_pkey, false);
   3941    smartlist_add_asprintf(chunks, "ntor-onion-key %s\n", kbuf);
   3942  }
   3943 
   3944  if (family) {
   3945    const uint8_t *id = (const uint8_t *)ri->cache_info.identity_digest;
   3946    char *canonical_family = nodefamily_canonicalize(family, id, 0);
   3947    smartlist_add_asprintf(chunks, "family %s\n", canonical_family);
   3948    tor_free(canonical_family);
   3949  }
   3950 
   3951  if (consensus_method >= MIN_METHOD_FOR_FAMILY_IDS &&
   3952      ri->family_ids && smartlist_len(ri->family_ids)) {
   3953    char *family_ids = smartlist_join_strings(ri->family_ids, " ", 0, NULL);
   3954    smartlist_add_asprintf(chunks, "family-ids %s\n", family_ids);
   3955    tor_free(family_ids);
   3956  }
   3957 
   3958  if (summary && strcmp(summary, "reject 1-65535"))
   3959    smartlist_add_asprintf(chunks, "p %s\n", summary);
   3960 
   3961  if (ri->ipv6_exit_policy) {
   3962    /* XXXX+++ This doesn't match proposal 208, which says these should
   3963     * be taken unchanged from the routerinfo.  That's bogosity, IMO:
   3964     * the proposal should have said to do this instead.*/
   3965    char *p6 = write_short_policy(ri->ipv6_exit_policy);
   3966    if (p6 && strcmp(p6, "reject 1-65535"))
   3967      smartlist_add_asprintf(chunks, "p6 %s\n", p6);
   3968    tor_free(p6);
   3969  }
   3970 
   3971  {
   3972    char idbuf[ED25519_BASE64_LEN+1];
   3973    const char *keytype;
   3974    if (ri->cache_info.signing_key_cert &&
   3975        ri->cache_info.signing_key_cert->signing_key_included) {
   3976      keytype = "ed25519";
   3977      ed25519_public_to_base64(idbuf,
   3978                               &ri->cache_info.signing_key_cert->signing_key);
   3979    } else {
   3980      keytype = "rsa1024";
   3981      digest_to_base64(idbuf, ri->cache_info.identity_digest);
   3982    }
   3983    smartlist_add_asprintf(chunks, "id %s %s\n", keytype, idbuf);
   3984  }
   3985 
   3986  output = smartlist_join_strings(chunks, "", 0, NULL);
   3987 
   3988  {
   3989    smartlist_t *lst = microdescs_parse_from_string(output,
   3990                                                    output+strlen(output), 0,
   3991                                                    SAVED_NOWHERE, NULL);
   3992    if (smartlist_len(lst) != 1) {
   3993      log_warn(LD_DIR, "We generated a microdescriptor we couldn't parse.");
   3994      SMARTLIST_FOREACH(lst, microdesc_t *, md, microdesc_free(md));
   3995      smartlist_free(lst);
   3996      goto done;
   3997    }
   3998    result = smartlist_get(lst, 0);
   3999    smartlist_free(lst);
   4000  }
   4001 
   4002 done:
   4003  crypto_pk_free(rsa_pubkey);
   4004  tor_free(output);
   4005  tor_free(key);
   4006  tor_free(summary);
   4007  tor_free(family);
   4008  if (chunks) {
   4009    SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
   4010    smartlist_free(chunks);
   4011  }
   4012  return result;
   4013 }
   4014 
   4015 /** Format the appropriate vote line to describe the microdescriptor <b>md</b>
   4016 * in a consensus vote document.  Write it into the <b>out_len</b>-byte buffer
   4017 * in <b>out</b>.  Return -1 on failure and the number of characters written
   4018 * on success. */
   4019 static ssize_t
   4020 dirvote_format_microdesc_vote_line(char *out_buf, size_t out_buf_len,
   4021                                   const microdesc_t *md,
   4022                                   int consensus_method_low,
   4023                                   int consensus_method_high)
   4024 {
   4025  ssize_t ret = -1;
   4026  char d64[BASE64_DIGEST256_LEN+1];
   4027  char *microdesc_consensus_methods =
   4028    make_consensus_method_list(consensus_method_low,
   4029                               consensus_method_high,
   4030                               ",");
   4031  tor_assert(microdesc_consensus_methods);
   4032 
   4033  digest256_to_base64(d64, md->digest);
   4034 
   4035  if (tor_snprintf(out_buf, out_buf_len, "m %s sha256=%s\n",
   4036                   microdesc_consensus_methods, d64)<0)
   4037    goto out;
   4038 
   4039  ret = strlen(out_buf);
   4040 
   4041 out:
   4042  tor_free(microdesc_consensus_methods);
   4043  return ret;
   4044 }
   4045 
   4046 /** Array of start and end of consensus methods used for supported
   4047    microdescriptor formats. */
   4048 static const struct consensus_method_range_t {
   4049  int low;
   4050  int high;
   4051 } microdesc_consensus_methods[] = {
   4052  {MIN_SUPPORTED_CONSENSUS_METHOD,
   4053   MIN_METHOD_FOR_FAMILY_IDS - 1},
   4054  {MIN_METHOD_FOR_FAMILY_IDS,
   4055   MAX_SUPPORTED_CONSENSUS_METHOD},
   4056  {-1, -1}
   4057 };
   4058 
   4059 /** Helper type used when generating the microdescriptor lines in a directory
   4060 * vote. */
   4061 typedef struct microdesc_vote_line_t {
   4062  int low;
   4063  int high;
   4064  microdesc_t *md;
   4065  struct microdesc_vote_line_t *next;
   4066 } microdesc_vote_line_t;
   4067 
   4068 /** Generate and return a linked list of all the lines that should appear to
   4069 * describe a router's microdescriptor versions in a directory vote.
   4070 * Add the generated microdescriptors to <b>microdescriptors_out</b>. */
   4071 vote_microdesc_hash_t *
   4072 dirvote_format_all_microdesc_vote_lines(const routerinfo_t *ri, time_t now,
   4073                                        smartlist_t *microdescriptors_out)
   4074 {
   4075  const struct consensus_method_range_t *cmr;
   4076  microdesc_vote_line_t *entries = NULL, *ep;
   4077  vote_microdesc_hash_t *result = NULL;
   4078 
   4079  /* Generate the microdescriptors. */
   4080  for (cmr = microdesc_consensus_methods;
   4081       cmr->low != -1 && cmr->high != -1;
   4082       cmr++) {
   4083    microdesc_t *md = dirvote_create_microdescriptor(ri, cmr->low);
   4084    if (md) {
   4085      microdesc_vote_line_t *e =
   4086        tor_malloc_zero(sizeof(microdesc_vote_line_t));
   4087      e->md = md;
   4088      e->low = cmr->low;
   4089      e->high = cmr->high;
   4090      e->next = entries;
   4091      entries = e;
   4092    }
   4093  }
   4094 
   4095  /* Compress adjacent identical ones */
   4096  for (ep = entries; ep; ep = ep->next) {
   4097    while (ep->next &&
   4098           fast_memeq(ep->md->digest, ep->next->md->digest, DIGEST256_LEN) &&
   4099           ep->low == ep->next->high + 1) {
   4100      microdesc_vote_line_t *next = ep->next;
   4101      ep->low = next->low;
   4102      microdesc_free(next->md);
   4103      ep->next = next->next;
   4104      tor_free(next);
   4105    }
   4106  }
   4107 
   4108  /* Format them into vote_microdesc_hash_t, and add to microdescriptors_out.*/
   4109  while ((ep = entries)) {
   4110    char buf[128];
   4111    vote_microdesc_hash_t *h;
   4112    if (dirvote_format_microdesc_vote_line(buf, sizeof(buf), ep->md,
   4113                                           ep->low, ep->high) >= 0) {
   4114      h = tor_malloc_zero(sizeof(vote_microdesc_hash_t));
   4115      h->microdesc_hash_line = tor_strdup(buf);
   4116      h->next = result;
   4117      result = h;
   4118      ep->md->last_listed = now;
   4119      smartlist_add(microdescriptors_out, ep->md);
   4120    }
   4121    entries = ep->next;
   4122    tor_free(ep);
   4123  }
   4124 
   4125  return result;
   4126 }
   4127 
   4128 /** Parse and extract all SR commits from <b>tokens</b> and place them in
   4129 *  <b>ns</b>. */
   4130 static void
   4131 extract_shared_random_commits(networkstatus_t *ns, const smartlist_t *tokens)
   4132 {
   4133  smartlist_t *chunks = NULL;
   4134 
   4135  tor_assert(ns);
   4136  tor_assert(tokens);
   4137  /* Commits are only present in a vote. */
   4138  tor_assert(ns->type == NS_TYPE_VOTE);
   4139 
   4140  ns->sr_info.commits = smartlist_new();
   4141 
   4142  smartlist_t *commits = find_all_by_keyword(tokens, K_COMMIT);
   4143  /* It's normal that a vote might contain no commits even if it participates
   4144   * in the SR protocol. Don't treat it as an error. */
   4145  if (commits == NULL) {
   4146    goto end;
   4147  }
   4148 
   4149  /* Parse the commit. We do NO validation of number of arguments or ordering
   4150   * for forward compatibility, it's the parse commit job to inform us if it's
   4151   * supported or not. */
   4152  chunks = smartlist_new();
   4153  SMARTLIST_FOREACH_BEGIN(commits, directory_token_t *, tok) {
   4154    /* Extract all arguments and put them in the chunks list. */
   4155    for (int i = 0; i < tok->n_args; i++) {
   4156      smartlist_add(chunks, tok->args[i]);
   4157    }
   4158    sr_commit_t *commit = sr_parse_commit(chunks);
   4159    smartlist_clear(chunks);
   4160    if (commit == NULL) {
   4161      /* Get voter identity so we can warn that this dirauth vote contains
   4162       * commit we can't parse. */
   4163      networkstatus_voter_info_t *voter = smartlist_get(ns->voters, 0);
   4164      tor_assert(voter);
   4165      log_warn(LD_DIR, "SR: Unable to parse commit %s from vote of voter %s.",
   4166               escaped(tok->object_body),
   4167               hex_str(voter->identity_digest,
   4168                       sizeof(voter->identity_digest)));
   4169      /* Commitment couldn't be parsed. Continue onto the next commit because
   4170       * this one could be unsupported for instance. */
   4171      continue;
   4172    }
   4173    /* Add newly created commit object to the vote. */
   4174    smartlist_add(ns->sr_info.commits, commit);
   4175  } SMARTLIST_FOREACH_END(tok);
   4176 
   4177 end:
   4178  smartlist_free(chunks);
   4179  smartlist_free(commits);
   4180 }
   4181 
   4182 /* Using the given directory tokens in tokens, parse the shared random commits
   4183 * and put them in the given vote document ns.
   4184 *
   4185 * This also sets the SR participation flag if present in the vote. */
   4186 void
   4187 dirvote_parse_sr_commits(networkstatus_t *ns, const smartlist_t *tokens)
   4188 {
   4189  /* Does this authority participates in the SR protocol? */
   4190  directory_token_t *tok = find_opt_by_keyword(tokens, K_SR_FLAG);
   4191  if (tok) {
   4192    ns->sr_info.participate = 1;
   4193    /* Get the SR commitments and reveals from the vote. */
   4194    extract_shared_random_commits(ns, tokens);
   4195  }
   4196 }
   4197 
   4198 /* For the given vote, free the shared random commits if any. */
   4199 void
   4200 dirvote_clear_commits(networkstatus_t *ns)
   4201 {
   4202  tor_assert(ns->type == NS_TYPE_VOTE);
   4203 
   4204  if (ns->sr_info.commits) {
   4205    SMARTLIST_FOREACH(ns->sr_info.commits, sr_commit_t *, c,
   4206                      sr_commit_free(c));
   4207    smartlist_free(ns->sr_info.commits);
   4208  }
   4209 }
   4210 
   4211 /* The given url is the /tor/status-vote GET directory request. Populates the
   4212 * items list with strings that we can compress on the fly and dir_items with
   4213 * cached_dir_t objects that have a precompressed deflated version. */
   4214 void
   4215 dirvote_dirreq_get_status_vote(const char *url, smartlist_t *items,
   4216                               smartlist_t *dir_items)
   4217 {
   4218  int current;
   4219 
   4220  url += strlen("/tor/status-vote/");
   4221  current = !strcmpstart(url, "current/");
   4222  url = strchr(url, '/');
   4223  tor_assert(url);
   4224  ++url;
   4225  if (!strcmp(url, "consensus")) {
   4226    const char *item;
   4227    tor_assert(!current); /* we handle current consensus specially above,
   4228                           * since it wants to be spooled. */
   4229    if ((item = dirvote_get_pending_consensus(FLAV_NS)))
   4230      smartlist_add(items, (char*)item);
   4231  } else if (!current && !strcmp(url, "consensus-signatures")) {
   4232    /* XXXX the spec says that we should implement
   4233     * current/consensus-signatures too.  It doesn't seem to be needed,
   4234     * though. */
   4235    const char *item;
   4236    if ((item=dirvote_get_pending_detached_signatures()))
   4237      smartlist_add(items, (char*)item);
   4238  } else if (!strcmp(url, "authority")) {
   4239    const cached_dir_t *d;
   4240    int flags = DGV_BY_ID |
   4241      (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
   4242    if ((d=dirvote_get_vote(NULL, flags)))
   4243      smartlist_add(dir_items, (cached_dir_t*)d);
   4244  } else {
   4245    const cached_dir_t *d;
   4246    smartlist_t *fps = smartlist_new();
   4247    int flags;
   4248    if (!strcmpstart(url, "d/")) {
   4249      url += 2;
   4250      flags = DGV_INCLUDE_PENDING | DGV_INCLUDE_PREVIOUS;
   4251    } else {
   4252      flags = DGV_BY_ID |
   4253        (current ? DGV_INCLUDE_PREVIOUS : DGV_INCLUDE_PENDING);
   4254    }
   4255    dir_split_resource_into_fingerprints(url, fps, NULL,
   4256                                         DSR_HEX|DSR_SORT_UNIQ);
   4257    SMARTLIST_FOREACH(fps, char *, fp, {
   4258                      if ((d = dirvote_get_vote(fp, flags)))
   4259                      smartlist_add(dir_items, (cached_dir_t*)d);
   4260                      tor_free(fp);
   4261                      });
   4262    smartlist_free(fps);
   4263  }
   4264 }
   4265 
   4266 /** Get the best estimate of a router's bandwidth for dirauth purposes,
   4267 * preferring measured to advertised values if available. */
   4268 MOCK_IMPL(uint32_t,dirserv_get_bandwidth_for_router_kb,
   4269        (const routerinfo_t *ri))
   4270 {
   4271  uint32_t bw_kb = 0;
   4272  /*
   4273   * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
   4274   * signed) longs and the ones router_get_advertised_bandwidth() returns
   4275   * are uint32_t.
   4276   */
   4277  long mbw_kb = 0;
   4278 
   4279  if (ri) {
   4280    /*
   4281     * * First try to see if we have a measured bandwidth; don't bother with
   4282     * as_of_out here, on the theory that a stale measured bandwidth is still
   4283     * better to trust than an advertised one.
   4284     */
   4285    if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
   4286                                           &mbw_kb, NULL)) {
   4287      /* Got one! */
   4288      bw_kb = (uint32_t)mbw_kb;
   4289    } else {
   4290      /* If not, fall back to advertised */
   4291      bw_kb = router_get_advertised_bandwidth(ri) / 1000;
   4292    }
   4293  }
   4294 
   4295  return bw_kb;
   4296 }
   4297 
   4298 /**
   4299 * Helper: compare the address of family `family` in `a` with the address in
   4300 * `b`.  The family must be one of `AF_INET` and `AF_INET6`.
   4301 **/
   4302 static int
   4303 compare_routerinfo_addrs_by_family(const routerinfo_t *a,
   4304                                   const routerinfo_t *b,
   4305                                   int family)
   4306 {
   4307  const tor_addr_t *addr1 = (family==AF_INET) ? &a->ipv4_addr : &a->ipv6_addr;
   4308  const tor_addr_t *addr2 = (family==AF_INET) ? &b->ipv4_addr : &b->ipv6_addr;
   4309  return tor_addr_compare(addr1, addr2, CMP_EXACT);
   4310 }
   4311 
   4312 /** Helper for sorting: compares two ipv4 routerinfos first by ipv4 address,
   4313 * and then by descending order of "usefulness"
   4314 * (see compare_routerinfo_usefulness)
   4315 **/
   4316 STATIC int
   4317 compare_routerinfo_by_ipv4(const void **a, const void **b)
   4318 {
   4319  const routerinfo_t *first = *(const routerinfo_t **)a;
   4320  const routerinfo_t *second = *(const routerinfo_t **)b;
   4321  int comparison = compare_routerinfo_addrs_by_family(first, second, AF_INET);
   4322  if (comparison == 0) {
   4323    // If addresses are equal, use other comparison criteria
   4324    return compare_routerinfo_usefulness(first, second);
   4325  } else {
   4326    return comparison;
   4327  }
   4328 }
   4329 
   4330 /** Helper for sorting: compares two ipv6 routerinfos first by ipv6 address,
   4331 * and then by descending order of "usefulness"
   4332 * (see compare_routerinfo_usefulness)
   4333 **/
   4334 STATIC int
   4335 compare_routerinfo_by_ipv6(const void **a, const void **b)
   4336 {
   4337  const routerinfo_t *first = *(const routerinfo_t **)a;
   4338  const routerinfo_t *second = *(const routerinfo_t **)b;
   4339  int comparison = compare_routerinfo_addrs_by_family(first, second, AF_INET6);
   4340  // If addresses are equal, use other comparison criteria
   4341  if (comparison == 0)
   4342    return compare_routerinfo_usefulness(first, second);
   4343  else
   4344    return comparison;
   4345 }
   4346 
   4347 /**
   4348 * Compare routerinfos by descending order of "usefulness" :
   4349 * An authority is more useful than a non-authority; a running router is
   4350 * more useful than a non-running router; and a router with more bandwidth
   4351 * is more useful than one with less.
   4352 **/
   4353 STATIC int
   4354 compare_routerinfo_usefulness(const routerinfo_t *first,
   4355                              const routerinfo_t *second)
   4356 {
   4357  int first_is_auth, second_is_auth;
   4358  const node_t *node_first, *node_second;
   4359  int first_is_running, second_is_running;
   4360  uint32_t bw_kb_first, bw_kb_second;
   4361  /* Potentially, this next bit could cause k n lg n memeq calls.  But in
   4362   * reality, we will almost never get here, since addresses will usually be
   4363   * different. */
   4364  first_is_auth =
   4365    router_digest_is_trusted_dir(first->cache_info.identity_digest);
   4366  second_is_auth =
   4367    router_digest_is_trusted_dir(second->cache_info.identity_digest);
   4368 
   4369  if (first_is_auth && !second_is_auth)
   4370    return -1;
   4371  else if (!first_is_auth && second_is_auth)
   4372    return 1;
   4373 
   4374  node_first = node_get_by_id(first->cache_info.identity_digest);
   4375  node_second = node_get_by_id(second->cache_info.identity_digest);
   4376  first_is_running = node_first && node_first->is_running;
   4377  second_is_running = node_second && node_second->is_running;
   4378  if (first_is_running && !second_is_running)
   4379    return -1;
   4380  else if (!first_is_running && second_is_running)
   4381    return 1;
   4382 
   4383  bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
   4384  bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
   4385 
   4386  if (bw_kb_first > bw_kb_second)
   4387    return -1;
   4388  else if (bw_kb_first < bw_kb_second)
   4389    return 1;
   4390 
   4391  /* They're equal! Compare by identity digest, so there's a
   4392   * deterministic order and we avoid flapping. */
   4393  return fast_memcmp(first->cache_info.identity_digest,
   4394                     second->cache_info.identity_digest,
   4395                     DIGEST_LEN);
   4396 }
   4397 
   4398 /** Given a list of routerinfo_t in <b>routers</b> that all use the same
   4399 * IP version, specified in <b>family</b>, return a new digestmap_t whose keys
   4400 * are the identity digests of those routers that we're going to exclude for
   4401 * Sybil-like appearance.
   4402 */
   4403 STATIC digestmap_t *
   4404 get_sybil_list_by_ip_version(const smartlist_t *routers, sa_family_t family)
   4405 {
   4406  const dirauth_options_t *options = dirauth_get_options();
   4407  digestmap_t *omit_as_sybil = digestmap_new();
   4408  smartlist_t *routers_by_ip = smartlist_new();
   4409  int addr_count = 0;
   4410  routerinfo_t *last_ri = NULL;
   4411  /* Allow at most this number of Tor servers on a single IP address, ... */
   4412  int max_with_same_addr = options->AuthDirMaxServersPerAddr;
   4413  if (max_with_same_addr <= 0)
   4414    max_with_same_addr = INT_MAX;
   4415 
   4416  smartlist_add_all(routers_by_ip, routers);
   4417  if (family == AF_INET6)
   4418    smartlist_sort(routers_by_ip, compare_routerinfo_by_ipv6);
   4419  else
   4420    smartlist_sort(routers_by_ip, compare_routerinfo_by_ipv4);
   4421 
   4422  SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
   4423    bool addrs_equal;
   4424    if (last_ri)
   4425      addrs_equal = !compare_routerinfo_addrs_by_family(last_ri, ri, family);
   4426    else
   4427      addrs_equal = false;
   4428 
   4429    if (! addrs_equal) {
   4430      last_ri = ri;
   4431      addr_count = 1;
   4432    } else if (++addr_count > max_with_same_addr) {
   4433      digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
   4434    }
   4435  } SMARTLIST_FOREACH_END(ri);
   4436  smartlist_free(routers_by_ip);
   4437  return omit_as_sybil;
   4438 }
   4439 
   4440 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
   4441 * whose keys are the identity digests of those routers that we're going to
   4442 * exclude for Sybil-like appearance. */
   4443 STATIC digestmap_t *
   4444 get_all_possible_sybil(const smartlist_t *routers)
   4445 {
   4446  smartlist_t  *routers_ipv6, *routers_ipv4;
   4447  routers_ipv6 = smartlist_new();
   4448  routers_ipv4 = smartlist_new();
   4449  digestmap_t *omit_as_sybil_ipv4;
   4450  digestmap_t *omit_as_sybil_ipv6;
   4451  digestmap_t *omit_as_sybil = digestmap_new();
   4452  // Sort the routers in two lists depending on their IP version
   4453  SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
   4454    // If the router has an IPv6 address
   4455    if (tor_addr_family(&(ri->ipv6_addr)) == AF_INET6) {
   4456      smartlist_add(routers_ipv6, ri);
   4457    }
   4458    // If the router has an IPv4 address
   4459    if (tor_addr_family(&(ri->ipv4_addr)) == AF_INET) {
   4460      smartlist_add(routers_ipv4, ri);
   4461    }
   4462  } SMARTLIST_FOREACH_END(ri);
   4463  omit_as_sybil_ipv4 = get_sybil_list_by_ip_version(routers_ipv4, AF_INET);
   4464  omit_as_sybil_ipv6 = get_sybil_list_by_ip_version(routers_ipv6, AF_INET6);
   4465 
   4466  // Add all possible sybils to the common digestmap
   4467  DIGESTMAP_FOREACH (omit_as_sybil_ipv4, sybil_id, routerinfo_t *, ri) {
   4468    digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
   4469  } DIGESTMAP_FOREACH_END;
   4470  DIGESTMAP_FOREACH (omit_as_sybil_ipv6, sybil_id, routerinfo_t *, ri) {
   4471    digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
   4472  } DIGESTMAP_FOREACH_END;
   4473  // Clean the temp variables
   4474  smartlist_free(routers_ipv4);
   4475  smartlist_free(routers_ipv6);
   4476  digestmap_free(omit_as_sybil_ipv4, NULL);
   4477  digestmap_free(omit_as_sybil_ipv6, NULL);
   4478  // Return the digestmap: it now contains all the possible sybils
   4479  return omit_as_sybil;
   4480 }
   4481 
   4482 /** Given a platform string as in a routerinfo_t (possibly null), return a
   4483 * newly allocated version string for a networkstatus document, or NULL if the
   4484 * platform doesn't give a Tor version. */
   4485 static char *
   4486 version_from_platform(const char *platform)
   4487 {
   4488  if (platform && !strcmpstart(platform, "Tor ")) {
   4489    const char *eos = find_whitespace(platform+4);
   4490    if (eos && !strcmpstart(eos, " (r")) {
   4491      /* XXXX Unify this logic with the other version extraction
   4492       * logic in routerparse.c. */
   4493      eos = find_whitespace(eos+1);
   4494    }
   4495    if (eos) {
   4496      return tor_strndup(platform, eos-platform);
   4497    }
   4498  }
   4499  return NULL;
   4500 }
   4501 
   4502 /** Given a (possibly empty) list of config_line_t, each line of which contains
   4503 * a list of comma-separated version numbers surrounded by optional space,
   4504 * allocate and return a new string containing the version numbers, in order,
   4505 * separated by commas.  Used to generate Recommended(Client|Server)?Versions
   4506 */
   4507 char *
   4508 format_recommended_version_list(const config_line_t *ln, int warn)
   4509 {
   4510  smartlist_t *versions;
   4511  char *result;
   4512  versions = smartlist_new();
   4513  for ( ; ln; ln = ln->next) {
   4514    smartlist_split_string(versions, ln->value, ",",
   4515                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
   4516  }
   4517 
   4518  /* Handle the case where a dirauth operator has accidentally made some
   4519   * versions space-separated instead of comma-separated. */
   4520  smartlist_t *more_versions = smartlist_new();
   4521  SMARTLIST_FOREACH_BEGIN(versions, char *, v) {
   4522    if (strchr(v, ' ')) {
   4523      if (warn)
   4524        log_warn(LD_DIRSERV, "Unexpected space in versions list member %s. "
   4525                 "(These are supposed to be comma-separated; I'll pretend you "
   4526                 "used commas instead.)", escaped(v));
   4527      SMARTLIST_DEL_CURRENT(versions, v);
   4528      smartlist_split_string(more_versions, v, NULL,
   4529                             SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
   4530      tor_free(v);
   4531    }
   4532  } SMARTLIST_FOREACH_END(v);
   4533  smartlist_add_all(versions, more_versions);
   4534  smartlist_free(more_versions);
   4535 
   4536  /* Check to make sure everything looks like a version. */
   4537  if (warn) {
   4538    SMARTLIST_FOREACH_BEGIN(versions, const char *, v) {
   4539      tor_version_t ver;
   4540      if (tor_version_parse(v, &ver) < 0) {
   4541        log_warn(LD_DIRSERV, "Recommended version %s does not look valid. "
   4542                 " (I'll include it anyway, since you told me to.)",
   4543                 escaped(v));
   4544      }
   4545    } SMARTLIST_FOREACH_END(v);
   4546  }
   4547 
   4548  sort_version_list(versions, 1);
   4549  result = smartlist_join_strings(versions,",",0,NULL);
   4550  SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
   4551  smartlist_free(versions);
   4552  return result;
   4553 }
   4554 
   4555 /** If there are entries in <b>routers</b> with exactly the same ed25519 keys,
   4556 * remove the older one.  If they are exactly the same age, remove the one
   4557 * with the greater descriptor digest. May alter the order of the list. */
   4558 static void
   4559 routers_make_ed_keys_unique(smartlist_t *routers)
   4560 {
   4561  routerinfo_t *ri2;
   4562  digest256map_t *by_ed_key = digest256map_new();
   4563 
   4564  SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
   4565    ri->omit_from_vote = 0;
   4566    if (ri->cache_info.signing_key_cert == NULL)
   4567      continue; /* No ed key */
   4568    const uint8_t *pk = ri->cache_info.signing_key_cert->signing_key.pubkey;
   4569    if ((ri2 = digest256map_get(by_ed_key, pk))) {
   4570      /* Duplicate; must omit one.  Set the omit_from_vote flag in whichever
   4571       * one has the earlier published_on. */
   4572      const time_t ri_pub = ri->cache_info.published_on;
   4573      const time_t ri2_pub = ri2->cache_info.published_on;
   4574      if (ri2_pub < ri_pub ||
   4575          (ri2_pub == ri_pub &&
   4576           fast_memcmp(ri->cache_info.signed_descriptor_digest,
   4577                     ri2->cache_info.signed_descriptor_digest,DIGEST_LEN)<0)) {
   4578        digest256map_set(by_ed_key, pk, ri);
   4579        ri2->omit_from_vote = 1;
   4580      } else {
   4581        ri->omit_from_vote = 1;
   4582      }
   4583    } else {
   4584      /* Add to map */
   4585      digest256map_set(by_ed_key, pk, ri);
   4586    }
   4587  } SMARTLIST_FOREACH_END(ri);
   4588 
   4589  digest256map_free(by_ed_key, NULL);
   4590 
   4591  /* Now remove every router where the omit_from_vote flag got set. */
   4592  SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
   4593    if (ri->omit_from_vote) {
   4594      SMARTLIST_DEL_CURRENT(routers, ri);
   4595    }
   4596  } SMARTLIST_FOREACH_END(ri);
   4597 }
   4598 
   4599 /** Routerstatus <b>rs</b> is part of a group of routers that are on too
   4600 * narrow an IP-space. Clear out its flags since we don't want it be used
   4601 * because of its Sybil-like appearance.
   4602 *
   4603 * Leave its BadExit flag alone though, since if we think it's a bad exit,
   4604 * we want to vote that way in case all the other authorities are voting
   4605 * Running and Exit.
   4606 *
   4607 * Also set the Sybil flag in order to let a relay operator know that's
   4608 * why their relay hasn't been voted on.
   4609 */
   4610 static void
   4611 clear_status_flags_on_sybil(routerstatus_t *rs)
   4612 {
   4613  rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
   4614    rs->is_flagged_running = rs->is_named = rs->is_valid =
   4615    rs->is_hs_dir = rs->is_v2_dir = rs->is_possible_guard = 0;
   4616  rs->is_sybil = 1;
   4617  /* FFFF we might want some mechanism to check later on if we
   4618   * missed zeroing any flags: it's easy to add a new flag but
   4619   * forget to add it to this clause. */
   4620 }
   4621 
   4622 /** Space-separated list of all the flags that we will always vote on. */
   4623 const char DIRVOTE_UNIVERSAL_FLAGS[] =
   4624  "Authority "
   4625  "Exit "
   4626  "Fast "
   4627  "Guard "
   4628  "HSDir "
   4629  "Stable "
   4630  "StaleDesc "
   4631  "Sybil "
   4632  "V2Dir "
   4633  "Valid";
   4634 /** Space-separated list of all flags that we may or may not vote on,
   4635 * depending on our configuration. */
   4636 const char DIRVOTE_OPTIONAL_FLAGS[] =
   4637  "BadExit "
   4638  "MiddleOnly "
   4639  "Running";
   4640 
   4641 /** Return a new networkstatus_t* containing our current opinion. (For v3
   4642 * authorities) */
   4643 networkstatus_t *
   4644 dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
   4645                                        authority_cert_t *cert)
   4646 {
   4647  const or_options_t *options = get_options();
   4648  const dirauth_options_t *d_options = dirauth_get_options();
   4649  networkstatus_t *v3_out = NULL;
   4650  tor_addr_t addr;
   4651  char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
   4652  const char *contact;
   4653  smartlist_t *routers, *routerstatuses;
   4654  char identity_digest[DIGEST_LEN];
   4655  char signing_key_digest[DIGEST_LEN];
   4656  const int list_bad_exits = d_options->AuthDirListBadExits;
   4657  const int list_middle_only = d_options->AuthDirListMiddleOnly;
   4658  routerlist_t *rl = router_get_routerlist();
   4659  time_t now = time(NULL);
   4660  time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
   4661  networkstatus_voter_info_t *voter = NULL;
   4662  vote_timing_t timing;
   4663  const int vote_on_reachability = running_long_enough_to_decide_unreachable();
   4664  smartlist_t *microdescriptors = NULL;
   4665  smartlist_t *bw_file_headers = NULL;
   4666  uint8_t bw_file_digest256[DIGEST256_LEN] = {0};
   4667 
   4668  tor_assert(private_key);
   4669  tor_assert(cert);
   4670 
   4671  if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
   4672    log_err(LD_BUG, "Error computing signing key digest");
   4673    return NULL;
   4674  }
   4675  if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
   4676    log_err(LD_BUG, "Error computing identity key digest");
   4677    return NULL;
   4678  }
   4679  if (!find_my_address(options, AF_INET, LOG_WARN, &addr, NULL, &hostname)) {
   4680    log_warn(LD_NET, "Couldn't resolve my hostname");
   4681    return NULL;
   4682  }
   4683  if (!hostname || !strchr(hostname, '.')) {
   4684    tor_free(hostname);
   4685    hostname = tor_addr_to_str_dup(&addr);
   4686  }
   4687 
   4688  if (!hostname) {
   4689    log_err(LD_BUG, "Failed to determine hostname AND duplicate address");
   4690    return NULL;
   4691  }
   4692 
   4693  if (d_options->VersioningAuthoritativeDirectory) {
   4694    client_versions =
   4695      format_recommended_version_list(d_options->RecommendedClientVersions, 0);
   4696    server_versions =
   4697      format_recommended_version_list(d_options->RecommendedServerVersions, 0);
   4698  }
   4699 
   4700  contact = get_options()->ContactInfo;
   4701  if (!contact)
   4702    contact = "(none)";
   4703 
   4704  /*
   4705   * Do this so dirserv_compute_performance_thresholds() and
   4706   * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
   4707   */
   4708  if (options->V3BandwidthsFile) {
   4709    dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL, NULL,
   4710                                     NULL);
   4711  } else {
   4712    /*
   4713     * No bandwidths file; clear the measured bandwidth cache in case we had
   4714     * one last time around.
   4715     */
   4716    if (dirserv_get_measured_bw_cache_size() > 0) {
   4717      dirserv_clear_measured_bw_cache();
   4718    }
   4719  }
   4720 
   4721  /* precompute this part, since we need it to decide what "stable"
   4722   * means. */
   4723  SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
   4724                    dirserv_set_router_is_running(ri, now);
   4725                    });
   4726 
   4727  routers = smartlist_new();
   4728  smartlist_add_all(routers, rl->routers);
   4729  routers_make_ed_keys_unique(routers);
   4730  /* After this point, don't use rl->routers; use 'routers' instead. */
   4731  routers_sort_by_identity(routers);
   4732  /* Get a digestmap of possible sybil routers, IPv4 or IPv6 */
   4733  digestmap_t *omit_as_sybil = get_all_possible_sybil(routers);
   4734  DIGESTMAP_FOREACH (omit_as_sybil, sybil_id, void *, ignore) {
   4735    (void)ignore;
   4736    rep_hist_make_router_pessimal(sybil_id, now);
   4737  } DIGESTMAP_FOREACH_END
   4738  /* Count how many have measured bandwidths so we know how to assign flags;
   4739   * this must come before dirserv_compute_performance_thresholds() */
   4740  dirserv_count_measured_bws(routers);
   4741  dirserv_compute_performance_thresholds(omit_as_sybil);
   4742  routerstatuses = smartlist_new();
   4743  microdescriptors = smartlist_new();
   4744 
   4745  SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
   4746    /* If it has a protover list and contains a protocol name greater than
   4747     * MAX_PROTOCOL_NAME_LENGTH, skip it. */
   4748    if (ri->protocol_list &&
   4749        protover_list_is_invalid(ri->protocol_list)) {
   4750      continue;
   4751    }
   4752    if (ri->cache_info.published_on >= cutoff) {
   4753      routerstatus_t *rs;
   4754      vote_routerstatus_t *vrs;
   4755      node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
   4756      if (!node)
   4757        continue;
   4758 
   4759      vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
   4760      rs = &vrs->status;
   4761      dirauth_set_routerstatus_from_routerinfo(rs, node, ri, now,
   4762                                               list_bad_exits,
   4763                                               list_middle_only);
   4764      vrs->published_on = ri->cache_info.published_on;
   4765 
   4766      if (ri->cache_info.signing_key_cert) {
   4767        memcpy(vrs->ed25519_id,
   4768               ri->cache_info.signing_key_cert->signing_key.pubkey,
   4769               ED25519_PUBKEY_LEN);
   4770      }
   4771      if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
   4772        clear_status_flags_on_sybil(rs);
   4773 
   4774      if (!vote_on_reachability)
   4775        rs->is_flagged_running = 0;
   4776 
   4777      vrs->version = version_from_platform(ri->platform);
   4778      if (ri->protocol_list) {
   4779        vrs->protocols = tor_strdup(ri->protocol_list);
   4780      } else {
   4781        vrs->protocols = tor_strdup(
   4782                                protover_compute_for_old_tor(vrs->version));
   4783      }
   4784      vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
   4785                                                            microdescriptors);
   4786 
   4787      smartlist_add(routerstatuses, vrs);
   4788    }
   4789  } SMARTLIST_FOREACH_END(ri);
   4790 
   4791  {
   4792    smartlist_t *added =
   4793      microdescs_add_list_to_cache(get_microdesc_cache(),
   4794                                   microdescriptors, SAVED_NOWHERE, 0);
   4795    smartlist_free(added);
   4796    smartlist_free(microdescriptors);
   4797  }
   4798 
   4799  smartlist_free(routers);
   4800  digestmap_free(omit_as_sybil, NULL);
   4801 
   4802  /* Apply guardfraction information to routerstatuses. */
   4803  if (options->GuardfractionFile) {
   4804    dirserv_read_guardfraction_file(options->GuardfractionFile,
   4805                                    routerstatuses);
   4806  }
   4807 
   4808  /* This pass through applies the measured bw lines to the routerstatuses */
   4809  if (options->V3BandwidthsFile) {
   4810    /* Only set bw_file_headers when V3BandwidthsFile is configured */
   4811    bw_file_headers = smartlist_new();
   4812    dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
   4813                                     routerstatuses, bw_file_headers,
   4814                                     bw_file_digest256);
   4815  } else {
   4816    /*
   4817     * No bandwidths file; clear the measured bandwidth cache in case we had
   4818     * one last time around.
   4819     */
   4820    if (dirserv_get_measured_bw_cache_size() > 0) {
   4821      dirserv_clear_measured_bw_cache();
   4822    }
   4823  }
   4824 
   4825  v3_out = tor_malloc_zero(sizeof(networkstatus_t));
   4826 
   4827  v3_out->type = NS_TYPE_VOTE;
   4828  dirvote_get_preferred_voting_intervals(&timing);
   4829  v3_out->published = now;
   4830  {
   4831    char tbuf[ISO_TIME_LEN+1];
   4832    networkstatus_t *current_consensus =
   4833      networkstatus_get_live_consensus(now);
   4834    long last_consensus_interval; /* only used to pick a valid_after */
   4835    if (current_consensus)
   4836      last_consensus_interval = current_consensus->fresh_until -
   4837        current_consensus->valid_after;
   4838    else
   4839      last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
   4840    v3_out->valid_after =
   4841      voting_sched_get_start_of_interval_after(now,
   4842                                   (int)last_consensus_interval,
   4843                                   options->TestingV3AuthVotingStartOffset);
   4844    format_iso_time(tbuf, v3_out->valid_after);
   4845    log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
   4846               "consensus_set=%d, last_interval=%d",
   4847               tbuf, current_consensus?1:0, (int)last_consensus_interval);
   4848  }
   4849  v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
   4850  v3_out->valid_until = v3_out->valid_after +
   4851    (timing.vote_interval * timing.n_intervals_valid);
   4852  v3_out->vote_seconds = timing.vote_delay;
   4853  v3_out->dist_seconds = timing.dist_delay;
   4854  tor_assert(v3_out->vote_seconds > 0);
   4855  tor_assert(v3_out->dist_seconds > 0);
   4856  tor_assert(timing.n_intervals_valid > 0);
   4857 
   4858  v3_out->client_versions = client_versions;
   4859  v3_out->server_versions = server_versions;
   4860 
   4861  v3_out->recommended_relay_protocols =
   4862    tor_strdup(protover_get_recommended_relay_protocols());
   4863  v3_out->recommended_client_protocols =
   4864    tor_strdup(protover_get_recommended_client_protocols());
   4865  v3_out->required_client_protocols =
   4866    tor_strdup(protover_get_required_client_protocols());
   4867  v3_out->required_relay_protocols =
   4868    tor_strdup(protover_get_required_relay_protocols());
   4869 
   4870  /* We are not allowed to vote to require anything we don't have. */
   4871  tor_assert(protover_all_supported(v3_out->required_relay_protocols, NULL));
   4872  tor_assert(protover_all_supported(v3_out->required_client_protocols, NULL));
   4873 
   4874  /* We should not recommend anything we don't have. */
   4875  tor_assert_nonfatal(protover_all_supported(
   4876                               v3_out->recommended_relay_protocols, NULL));
   4877  tor_assert_nonfatal(protover_all_supported(
   4878                               v3_out->recommended_client_protocols, NULL));
   4879 
   4880  v3_out->known_flags = smartlist_new();
   4881  smartlist_split_string(v3_out->known_flags,
   4882                         DIRVOTE_UNIVERSAL_FLAGS,
   4883                         0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
   4884  if (vote_on_reachability)
   4885    smartlist_add_strdup(v3_out->known_flags, "Running");
   4886  if (list_bad_exits)
   4887    smartlist_add_strdup(v3_out->known_flags, "BadExit");
   4888  if (list_middle_only)
   4889    smartlist_add_strdup(v3_out->known_flags, "MiddleOnly");
   4890  smartlist_sort_strings(v3_out->known_flags);
   4891 
   4892  if (d_options->ConsensusParams) {
   4893    config_line_t *paramline = d_options->ConsensusParams;
   4894    v3_out->net_params = smartlist_new();
   4895    for ( ; paramline; paramline = paramline->next) {
   4896      smartlist_split_string(v3_out->net_params,
   4897                             paramline->value, NULL, 0, 0);
   4898    }
   4899 
   4900    /* for transparency and visibility, include our current value of
   4901     * AuthDirMaxServersPerAddr in our consensus params. Once enough dir
   4902     * auths do this, external tools should be able to use that value to
   4903     * help understand which relays are allowed into the consensus. */
   4904    smartlist_add_asprintf(v3_out->net_params, "AuthDirMaxServersPerAddr=%d",
   4905                           d_options->AuthDirMaxServersPerAddr);
   4906 
   4907    smartlist_sort_strings(v3_out->net_params);
   4908  }
   4909  v3_out->bw_file_headers = bw_file_headers;
   4910  memcpy(v3_out->bw_file_digest256, bw_file_digest256, DIGEST256_LEN);
   4911 
   4912  voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
   4913  voter->nickname = tor_strdup(options->Nickname);
   4914  memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
   4915  voter->sigs = smartlist_new();
   4916  voter->address = hostname;
   4917  tor_addr_copy(&voter->ipv4_addr, &addr);
   4918  voter->ipv4_dirport = routerconf_find_dir_port(options, 0);
   4919  voter->ipv4_orport = routerconf_find_or_port(options, AF_INET);
   4920  voter->contact = tor_strdup(contact);
   4921  if (options->V3AuthUseLegacyKey) {
   4922    authority_cert_t *c = get_my_v3_legacy_cert();
   4923    if (c) {
   4924      if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
   4925        log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
   4926        memset(voter->legacy_id_digest, 0, DIGEST_LEN);
   4927      }
   4928    }
   4929  }
   4930 
   4931  v3_out->voters = smartlist_new();
   4932  smartlist_add(v3_out->voters, voter);
   4933  v3_out->cert = authority_cert_dup(cert);
   4934  v3_out->routerstatus_list = routerstatuses;
   4935  /* Note: networkstatus_digest is unset; it won't get set until we actually
   4936   * format the vote. */
   4937 
   4938  return v3_out;
   4939 }