tor

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

circuitbuild.c (97286B)


      1 /* Copyright (c) 2001 Matej Pfajfar.
      2 * Copyright (c) 2001-2004, Roger Dingledine.
      3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      5 /* See LICENSE for licensing information */
      6 
      7 /**
      8 * \file circuitbuild.c
      9 *
     10 * \brief Implements the details of building circuits (by choosing paths,
     11 * constructing/sending create/extend cells, and so on).
     12 *
     13 * On the client side, this module handles launching circuits. Circuit
     14 * launches are started from circuit_establish_circuit(), called from
     15 * circuit_launch_by_extend_info()).  To choose the path the circuit will
     16 * take, onion_extend_cpath() calls into a maze of node selection functions.
     17 *
     18 * Once the circuit is ready to be launched, the first hop is treated as a
     19 * special case with circuit_handle_first_hop(), since it might need to open a
     20 * channel.  As the channel opens, and later as CREATED and RELAY_EXTENDED
     21 * cells arrive, the client will invoke circuit_send_next_onion_skin() to send
     22 * CREATE or RELAY_EXTEND cells.
     23 *
     24 * The server side is handled in feature/relay/circuitbuild_relay.c.
     25 **/
     26 
     27 #define CIRCUITBUILD_PRIVATE
     28 #define OCIRC_EVENT_PRIVATE
     29 
     30 #include "core/or/or.h"
     31 #include "app/config/config.h"
     32 #include "lib/confmgt/confmgt.h"
     33 #include "core/crypto/hs_ntor.h"
     34 #include "core/crypto/onion_crypto.h"
     35 #include "core/crypto/onion_fast.h"
     36 #include "core/mainloop/connection.h"
     37 #include "core/mainloop/mainloop.h"
     38 #include "core/or/channel.h"
     39 #include "core/or/circuitbuild.h"
     40 #include "core/or/circuitlist.h"
     41 #include "core/or/circuitstats.h"
     42 #include "core/or/circuituse.h"
     43 #include "core/or/circuitpadding.h"
     44 #include "core/or/command.h"
     45 #include "core/or/connection_edge.h"
     46 #include "core/or/connection_or.h"
     47 #include "core/or/conflux_pool.h"
     48 #include "core/or/extendinfo.h"
     49 #include "core/or/onion.h"
     50 #include "core/or/ocirc_event.h"
     51 #include "core/or/policies.h"
     52 #include "core/or/relay.h"
     53 #include "core/or/trace_probes_circuit.h"
     54 #include "core/or/crypt_path.h"
     55 #include "core/or/protover.h"
     56 #include "feature/client/bridges.h"
     57 #include "feature/client/circpathbias.h"
     58 #include "feature/client/entrynodes.h"
     59 #include "feature/client/transports.h"
     60 #include "feature/control/control_events.h"
     61 #include "feature/dircommon/directory.h"
     62 #include "feature/nodelist/describe.h"
     63 #include "feature/nodelist/microdesc.h"
     64 #include "feature/nodelist/networkstatus.h"
     65 #include "feature/nodelist/nickname.h"
     66 #include "feature/nodelist/node_select.h"
     67 #include "feature/nodelist/nodelist.h"
     68 #include "feature/nodelist/routerlist.h"
     69 #include "feature/nodelist/routerset.h"
     70 #include "feature/relay/router.h"
     71 #include "feature/relay/routermode.h"
     72 #include "feature/relay/selftest.h"
     73 #include "feature/stats/predict_ports.h"
     74 #include "lib/crypt_ops/crypto_rand.h"
     75 #include "lib/trace/events.h"
     76 #include "core/or/congestion_control_common.h"
     77 
     78 #include "core/or/cell_st.h"
     79 #include "core/or/cpath_build_state_st.h"
     80 #include "core/or/entry_connection_st.h"
     81 #include "core/or/extend_info_st.h"
     82 #include "feature/nodelist/node_st.h"
     83 #include "core/or/or_circuit_st.h"
     84 #include "core/or/origin_circuit_st.h"
     85 
     86 #include "trunnel/extension.h"
     87 #include "trunnel/congestion_control.h"
     88 #include "trunnel/subproto_request.h"
     89 
     90 static int circuit_send_first_onion_skin(origin_circuit_t *circ);
     91 static int circuit_build_no_more_hops(origin_circuit_t *circ);
     92 static int circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
     93                                                crypt_path_t *hop);
     94 static const node_t *choose_good_middle_server(const origin_circuit_t *,
     95                          uint8_t purpose,
     96                          cpath_build_state_t *state,
     97                          crypt_path_t *head,
     98                          int cur_len);
     99 
    100 /** This function tries to get a channel to the specified endpoint,
    101 * and then calls command_setup_channel() to give it the right
    102 * callbacks.
    103 */
    104 MOCK_IMPL(channel_t *,
    105 channel_connect_for_circuit,(const extend_info_t *ei))
    106 {
    107  channel_t *chan;
    108 
    109  const tor_addr_port_t *orport = extend_info_pick_orport(ei);
    110  if (!orport)
    111    return NULL;
    112  const char *id_digest = ei->identity_digest;
    113  const ed25519_public_key_t *ed_id = &ei->ed_identity;
    114 
    115  chan = channel_connect(&orport->addr, orport->port, id_digest, ed_id);
    116  if (chan) command_setup_channel(chan);
    117 
    118  return chan;
    119 }
    120 
    121 /** Search for a value for circ_id that we can use on <b>chan</b> for an
    122 * outbound circuit, until we get a circ_id that is not in use by any other
    123 * circuit on that conn.
    124 *
    125 * Return it, or 0 if can't get a unique circ_id.
    126 */
    127 STATIC circid_t
    128 get_unique_circ_id_by_chan(channel_t *chan)
    129 {
    130 /* This number is chosen somewhat arbitrarily; see comment below for more
    131 * info.  When the space is 80% full, it gives a one-in-a-million failure
    132 * chance; when the space is 90% full, it gives a one-in-850 chance; and when
    133 * the space is 95% full, it gives a one-in-26 failure chance.  That seems
    134 * okay, though you could make a case IMO for anything between N=32 and
    135 * N=256. */
    136 #define MAX_CIRCID_ATTEMPTS 64
    137  int in_use;
    138  unsigned n_with_circ = 0, n_pending_destroy = 0, n_weird_pending_destroy = 0;
    139  circid_t test_circ_id;
    140  circid_t attempts=0;
    141  circid_t high_bit, max_range, mask;
    142  int64_t pending_destroy_time_total = 0;
    143  int64_t pending_destroy_time_max = 0;
    144 
    145  tor_assert(chan);
    146 
    147  if (chan->circ_id_type == CIRC_ID_TYPE_NEITHER) {
    148    log_warn(LD_BUG,
    149             "Trying to pick a circuit ID for a connection from "
    150             "a client with no identity.");
    151    return 0;
    152  }
    153  max_range = (chan->wide_circ_ids) ? (1u<<31) : (1u<<15);
    154  mask = max_range - 1;
    155  high_bit = (chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ? max_range : 0;
    156  do {
    157    if (++attempts > MAX_CIRCID_ATTEMPTS) {
    158      /* Make sure we don't loop forever because all circuit IDs are used.
    159       *
    160       * Once, we would try until we had tried every possible circuit ID.  But
    161       * that's quite expensive.  Instead, we try MAX_CIRCID_ATTEMPTS random
    162       * circuit IDs, and then give up.
    163       *
    164       * This potentially causes us to give up early if our circuit ID space
    165       * is nearly full.  If we have N circuit IDs in use, then we will reject
    166       * a new circuit with probability (N / max_range) ^ MAX_CIRCID_ATTEMPTS.
    167       * This means that in practice, a few percent of our circuit ID capacity
    168       * will go unused.
    169       *
    170       * The alternative here, though, is to do a linear search over the
    171       * whole circuit ID space every time we extend a circuit, which is
    172       * not so great either.
    173       */
    174      int64_t queued_destroys;
    175      char *m = rate_limit_log(&chan->last_warned_circ_ids_exhausted,
    176                               approx_time());
    177      if (m == NULL)
    178        return 0; /* This message has been rate-limited away. */
    179      if (n_pending_destroy)
    180        pending_destroy_time_total /= n_pending_destroy;
    181      log_warn(LD_CIRC,"No unused circIDs found on channel %s wide "
    182                 "circID support, with %u inbound and %u outbound circuits. "
    183                 "Found %u circuit IDs in use by circuits, and %u with "
    184                 "pending destroy cells. (%u of those were marked bogusly.) "
    185                 "The ones with pending destroy cells "
    186                 "have been marked unusable for an average of %ld seconds "
    187                 "and a maximum of %ld seconds. This channel is %ld seconds "
    188                 "old. Failing a circuit.%s",
    189                 chan->wide_circ_ids ? "with" : "without",
    190                 chan->num_p_circuits, chan->num_n_circuits,
    191                 n_with_circ, n_pending_destroy, n_weird_pending_destroy,
    192                 (long)pending_destroy_time_total,
    193                 (long)pending_destroy_time_max,
    194                 (long)(approx_time() - chan->timestamp_created),
    195                 m);
    196      tor_free(m);
    197 
    198      if (!chan->cmux) {
    199        /* This warning should be impossible. */
    200        log_warn(LD_BUG, "  This channel somehow has no cmux on it!");
    201        return 0;
    202      }
    203 
    204      /* analysis so far on 12184 suggests that we're running out of circuit
    205         IDs because it looks like we have too many pending destroy
    206         cells. Let's see how many we really have pending.
    207      */
    208      queued_destroys = circuitmux_count_queued_destroy_cells(chan,
    209                                                              chan->cmux);
    210 
    211      log_warn(LD_CIRC, "  Circuitmux on this channel has %u circuits, "
    212               "of which %u are active. It says it has %"PRId64
    213               " destroy cells queued.",
    214               circuitmux_num_circuits(chan->cmux),
    215               circuitmux_num_active_circuits(chan->cmux),
    216               (queued_destroys));
    217 
    218      /* Change this into "if (1)" in order to get more information about
    219       * possible failure modes here.  You'll need to know how to use gdb with
    220       * Tor: this will make Tor exit with an assertion failure if the cmux is
    221       * corrupt. */
    222      if (0)
    223        circuitmux_assert_okay(chan->cmux);
    224 
    225      channel_dump_statistics(chan, LOG_WARN);
    226 
    227      return 0;
    228    }
    229 
    230    do {
    231      crypto_rand((char*) &test_circ_id, sizeof(test_circ_id));
    232      test_circ_id &= mask;
    233    } while (test_circ_id == 0);
    234 
    235    test_circ_id |= high_bit;
    236 
    237    in_use = circuit_id_in_use_on_channel(test_circ_id, chan);
    238    if (in_use == 1)
    239      ++n_with_circ;
    240    else if (in_use == 2) {
    241      time_t since_when;
    242      ++n_pending_destroy;
    243      since_when =
    244        circuit_id_when_marked_unusable_on_channel(test_circ_id, chan);
    245      if (since_when) {
    246        time_t waiting = approx_time() - since_when;
    247        pending_destroy_time_total += waiting;
    248        if (waiting > pending_destroy_time_max)
    249          pending_destroy_time_max = waiting;
    250      } else {
    251        ++n_weird_pending_destroy;
    252      }
    253    }
    254  } while (in_use);
    255  return test_circ_id;
    256 }
    257 
    258 /** If <b>verbose</b> is false, allocate and return a comma-separated list of
    259 * the currently built elements of <b>circ</b>. If <b>verbose</b> is true, also
    260 * list information about link status in a more verbose format using spaces.
    261 * If <b>verbose_names</b> is false, give hex digests; if <b>verbose_names</b>
    262 * is true, use $DIGEST=Name style names.
    263 */
    264 static char *
    265 circuit_list_path_impl(origin_circuit_t *circ, int verbose, int verbose_names)
    266 {
    267  crypt_path_t *hop;
    268  smartlist_t *elements;
    269  const char *states[] = {"closed", "waiting for keys", "open"};
    270  char *s;
    271 
    272  elements = smartlist_new();
    273 
    274  if (verbose) {
    275    const char *nickname = build_state_get_exit_nickname(circ->build_state);
    276    smartlist_add_asprintf(elements, "%s%s circ (length %d%s%s):",
    277                 circ->build_state->is_internal ? "internal" : "exit",
    278                 circ->build_state->need_uptime ? " (high-uptime)" : "",
    279                 circ->build_state->desired_path_len,
    280                 circ->base_.state == CIRCUIT_STATE_OPEN ? "" : ", last hop ",
    281                 circ->base_.state == CIRCUIT_STATE_OPEN ? "" :
    282                 (nickname?nickname:"*unnamed*"));
    283  }
    284 
    285  hop = circ->cpath;
    286  do {
    287    char *elt;
    288    const char *id;
    289    const node_t *node;
    290    if (!hop)
    291      break;
    292    if (!verbose && hop->state != CPATH_STATE_OPEN)
    293      break;
    294    if (!hop->extend_info)
    295      break;
    296    id = hop->extend_info->identity_digest;
    297    if (verbose_names) {
    298      elt = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
    299      if ((node = node_get_by_id(id))) {
    300        node_get_verbose_nickname(node, elt);
    301      } else if (is_legal_nickname(hop->extend_info->nickname)) {
    302        elt[0] = '$';
    303        base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
    304        elt[HEX_DIGEST_LEN+1]= '~';
    305        strlcpy(elt+HEX_DIGEST_LEN+2,
    306                hop->extend_info->nickname, MAX_NICKNAME_LEN+1);
    307      } else {
    308        elt[0] = '$';
    309        base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
    310      }
    311    } else { /* ! verbose_names */
    312      elt = tor_malloc(HEX_DIGEST_LEN+2);
    313      elt[0] = '$';
    314      base16_encode(elt+1, HEX_DIGEST_LEN+1, id, DIGEST_LEN);
    315    }
    316    tor_assert(elt);
    317    if (verbose) {
    318      tor_assert(hop->state <= 2);
    319      smartlist_add_asprintf(elements,"%s(%s)",elt,states[hop->state]);
    320      tor_free(elt);
    321    } else {
    322      smartlist_add(elements, elt);
    323    }
    324    hop = hop->next;
    325  } while (hop != circ->cpath);
    326 
    327  s = smartlist_join_strings(elements, verbose?" ":",", 0, NULL);
    328  SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
    329  smartlist_free(elements);
    330  return s;
    331 }
    332 
    333 /** If <b>verbose</b> is false, allocate and return a comma-separated
    334 * list of the currently built elements of <b>circ</b>.  If
    335 * <b>verbose</b> is true, also list information about link status in
    336 * a more verbose format using spaces.
    337 */
    338 char *
    339 circuit_list_path(origin_circuit_t *circ, int verbose)
    340 {
    341  return circuit_list_path_impl(circ, verbose, 0);
    342 }
    343 
    344 /** Allocate and return a comma-separated list of the currently built elements
    345 * of <b>circ</b>, giving each as a verbose nickname.
    346 */
    347 char *
    348 circuit_list_path_for_controller(origin_circuit_t *circ)
    349 {
    350  return circuit_list_path_impl(circ, 0, 1);
    351 }
    352 
    353 /** Log, at severity <b>severity</b>, the nicknames of each router in
    354 * <b>circ</b>'s cpath. Also log the length of the cpath, and the intended
    355 * exit point.
    356 */
    357 void
    358 circuit_log_path(int severity, unsigned int domain, origin_circuit_t *circ)
    359 {
    360  char *s = circuit_list_path(circ,1);
    361  tor_log(severity,domain,"%s",s);
    362  tor_free(s);
    363 }
    364 
    365 /** Return 1 iff every node in circ's cpath definitely supports ntor. */
    366 static int
    367 circuit_cpath_supports_ntor(const origin_circuit_t *circ)
    368 {
    369  crypt_path_t *head, *cpath;
    370 
    371  cpath = head = circ->cpath;
    372  do {
    373    /* if the extend_info is missing, we can't tell if it supports ntor */
    374    if (!cpath->extend_info) {
    375      return 0;
    376    }
    377 
    378    /* if the key is blank, it definitely doesn't support ntor */
    379    if (!extend_info_supports_ntor(cpath->extend_info)) {
    380      return 0;
    381    }
    382    cpath = cpath->next;
    383  } while (cpath != head);
    384 
    385  return 1;
    386 }
    387 
    388 /** Pick all the entries in our cpath. Stop and return 0 when we're
    389 * happy, or return -1 if an error occurs. */
    390 static int
    391 onion_populate_cpath(origin_circuit_t *circ)
    392 {
    393  int r = 0;
    394 
    395  /* onion_extend_cpath assumes these are non-NULL */
    396  tor_assert(circ);
    397  tor_assert(circ->build_state);
    398 
    399  while (r == 0) {
    400    r = onion_extend_cpath(circ);
    401    if (r < 0) {
    402      log_info(LD_CIRC,"Generating cpath hop failed.");
    403      return -1;
    404    }
    405  }
    406 
    407  /* The path is complete */
    408  tor_assert(r == 1);
    409 
    410  /* Does every node in this path support ntor? */
    411  int path_supports_ntor = circuit_cpath_supports_ntor(circ);
    412 
    413  /* We would like every path to support ntor, but we have to allow for some
    414   * edge cases. */
    415  tor_assert(circuit_get_cpath_len(circ));
    416 
    417  if (circuit_get_cpath_len(circ) == 1) {
    418    /* Allow for bootstrapping: when we're fetching directly from a fallback,
    419     * authority, or bridge, we have no way of knowing its ntor onion key
    420     * before we connect to it. So instead, we try connecting, and end up using
    421     * CREATE_FAST. */
    422    tor_assert(circ->cpath);
    423    tor_assert(circ->cpath->extend_info);
    424    const node_t *node = node_get_by_id(
    425                                    circ->cpath->extend_info->identity_digest);
    426    /* If we don't know the node and its descriptor, we must be bootstrapping.
    427     */
    428    if (!node || !node_has_preferred_descriptor(node, 1)) {
    429      return 0;
    430    }
    431  }
    432 
    433  if (BUG(!path_supports_ntor)) {
    434    /* If we're building a multi-hop path, and it's not one of the HS or
    435     * bootstrapping exceptions, and it doesn't support ntor, something has
    436     * gone wrong. */
    437    return -1;
    438  }
    439 
    440  return 0;
    441 }
    442 
    443 /** Create and return a new origin circuit. Initialize its purpose and
    444 * build-state based on our arguments.  The <b>flags</b> argument is a
    445 * bitfield of CIRCLAUNCH_* flags, see circuit_launch_by_extend_info() for
    446 * more details. */
    447 origin_circuit_t *
    448 origin_circuit_init(uint8_t purpose, int flags)
    449 {
    450  /* sets circ->p_circ_id and circ->p_chan */
    451  origin_circuit_t *circ = origin_circuit_new();
    452  circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_CHAN_WAIT);
    453  circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
    454  circ->build_state->onehop_tunnel =
    455    ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
    456  circ->build_state->need_uptime =
    457    ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
    458  circ->build_state->need_capacity =
    459    ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
    460  circ->build_state->is_internal =
    461    ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
    462  circ->build_state->is_ipv6_selftest =
    463    ((flags & CIRCLAUNCH_IS_IPV6_SELFTEST) ? 1 : 0);
    464  circ->build_state->need_conflux =
    465    ((flags & CIRCLAUNCH_NEED_CONFLUX) ? 1 : 0);
    466  circ->base_.purpose = purpose;
    467  return circ;
    468 }
    469 
    470 /** Build a new circuit for <b>purpose</b>. If <b>exit</b> is defined, then use
    471 * that as your exit router, else choose a suitable exit node. The <b>flags</b>
    472 * argument is a bitfield of CIRCLAUNCH_* flags, see
    473 * circuit_launch_by_extend_info() for more details.
    474 *
    475 * Also launch a connection to the first OR in the chosen path, if
    476 * it's not open already.
    477 */
    478 origin_circuit_t *
    479 circuit_establish_circuit(uint8_t purpose, extend_info_t *exit_ei, int flags)
    480 {
    481  origin_circuit_t *circ;
    482  int err_reason = 0;
    483 
    484  circ = origin_circuit_init(purpose, flags);
    485 
    486  if (onion_pick_cpath_exit(circ, exit_ei) < 0 ||
    487      onion_populate_cpath(circ) < 0) {
    488    circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
    489    return NULL;
    490  }
    491 
    492  circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
    493 
    494  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
    495    circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
    496    return NULL;
    497  }
    498 
    499  tor_trace(TR_SUBSYS(circuit), TR_EV(establish), circ);
    500  return circ;
    501 }
    502 
    503 /**
    504 * Build a new conflux circuit for <b>purpose</b>. If <b>exit</b> is defined,
    505 * then use that as your exit router, else choose a suitable exit node.
    506 * The <b>flags</b> argument is a bitfield of CIRCLAUNCH_* flags, see
    507 * circuit_launch_by_extend_info() for more details.
    508 *
    509 * Also launch a connection to the first OR in the chosen path, if
    510 * it's not open already.
    511 */
    512 MOCK_IMPL(origin_circuit_t *,
    513 circuit_establish_circuit_conflux,(const uint8_t *conflux_nonce,
    514                                   uint8_t purpose, extend_info_t *exit_ei,
    515                                   int flags))
    516 {
    517  origin_circuit_t *circ;
    518  int err_reason = 0;
    519 
    520  /* Right now, only conflux client circuits use this function */
    521  tor_assert(purpose == CIRCUIT_PURPOSE_CONFLUX_UNLINKED);
    522 
    523  circ = origin_circuit_init(purpose, flags);
    524  TO_CIRCUIT(circ)->conflux_pending_nonce =
    525    tor_memdup(conflux_nonce, DIGEST256_LEN);
    526 
    527  if (onion_pick_cpath_exit(circ, exit_ei) < 0 ||
    528      onion_populate_cpath(circ) < 0) {
    529    circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
    530    return NULL;
    531  }
    532 
    533  circuit_event_status(circ, CIRC_EVENT_LAUNCHED, 0);
    534 
    535  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
    536    circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
    537    return NULL;
    538  }
    539 
    540  /* This can happen if the above triggered the OOM handler which in turn
    541   * closed that very circuit. */
    542  if (TO_CIRCUIT(circ)->marked_for_close) {
    543    return NULL;
    544  }
    545 
    546  tor_trace(TR_SUBSYS(circuit), TR_EV(establish), circ);
    547  return circ;
    548 }
    549 
    550 /** Return the guard state associated with <b>circ</b>, which may be NULL. */
    551 circuit_guard_state_t *
    552 origin_circuit_get_guard_state(origin_circuit_t *circ)
    553 {
    554  return circ->guard_state;
    555 }
    556 
    557 /**
    558 * Helper function to publish a channel association message
    559 *
    560 * circuit_handle_first_hop() calls this to notify subscribers about a
    561 * channel launch event, which associates a circuit with a channel.
    562 * This doesn't always correspond to an assignment of the circuit's
    563 * n_chan field, because that seems to be only for fully-open
    564 * channels.
    565 **/
    566 static void
    567 circuit_chan_publish(const origin_circuit_t *circ, const channel_t *chan)
    568 {
    569  ocirc_chan_msg_t *msg = tor_malloc(sizeof(*msg));
    570 
    571  msg->gid = circ->global_identifier;
    572  msg->chan = chan->global_identifier;
    573  msg->onehop = circ->build_state->onehop_tunnel;
    574 
    575  ocirc_chan_publish(msg);
    576 }
    577 
    578 /** Start establishing the first hop of our circuit. Figure out what
    579 * OR we should connect to, and if necessary start the connection to
    580 * it. If we're already connected, then send the 'create' cell.
    581 * Return 0 for ok, -reason if circ should be marked-for-close. */
    582 int
    583 circuit_handle_first_hop(origin_circuit_t *circ)
    584 {
    585  crypt_path_t *firsthop;
    586  channel_t *n_chan;
    587  int err_reason = 0;
    588  const char *msg = NULL;
    589  int should_launch = 0;
    590  const or_options_t *options = get_options();
    591 
    592  firsthop = cpath_get_next_non_open_hop(circ->cpath);
    593  tor_assert(firsthop);
    594  tor_assert(firsthop->extend_info);
    595 
    596  /* Some bridges are on private addresses. Others pass a dummy private
    597   * address to the pluggable transport, which ignores it.
    598   * Deny the connection if:
    599   * - the address is internal, and
    600   * - we're not connecting to a configured bridge, and
    601   * - we're not configured to allow extends to private addresses. */
    602  if (extend_info_any_orport_addr_is_internal(firsthop->extend_info) &&
    603      !extend_info_is_a_configured_bridge(firsthop->extend_info) &&
    604      !options->ExtendAllowPrivateAddresses) {
    605    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
    606           "Client asked me to connect directly to a private address");
    607    return -END_CIRC_REASON_TORPROTOCOL;
    608  }
    609 
    610  /* now see if we're already connected to the first OR in 'route' */
    611  const tor_addr_port_t *orport4 =
    612    extend_info_get_orport(firsthop->extend_info, AF_INET);
    613  const tor_addr_port_t *orport6 =
    614    extend_info_get_orport(firsthop->extend_info, AF_INET6);
    615  n_chan = channel_get_for_extend(
    616                          firsthop->extend_info->identity_digest,
    617                          &firsthop->extend_info->ed_identity,
    618                          orport4 ? &orport4->addr : NULL,
    619                          orport6 ? &orport6->addr : NULL,
    620                          true,
    621                          &msg,
    622                          &should_launch);
    623 
    624  if (!n_chan) {
    625    /* not currently connected in a useful way. */
    626    log_info(LD_CIRC, "Next router is %s: %s",
    627             safe_str_client(extend_info_describe(firsthop->extend_info)),
    628             msg?msg:"???");
    629    circ->base_.n_hop = extend_info_dup(firsthop->extend_info);
    630 
    631    if (should_launch) {
    632      n_chan = channel_connect_for_circuit(firsthop->extend_info);
    633      if (!n_chan) { /* connect failed, forget the whole thing */
    634        log_info(LD_CIRC,"connect to firsthop failed. Closing.");
    635        return -END_CIRC_REASON_CONNECTFAILED;
    636      }
    637      /* We didn't find a channel, but we're launching one for an origin
    638       * circuit.  (If we decided not to launch a channel, then we found at
    639       * least one once good in-progress channel use for this circuit, and
    640       * marked it in channel_get_for_extend().) */
    641      channel_mark_as_used_for_origin_circuit(n_chan);
    642      circuit_chan_publish(circ, n_chan);
    643    }
    644 
    645    log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
    646    /* return success. The onion/circuit/etc will be taken care of
    647     * automatically (may already have been) whenever n_chan reaches
    648     * OR_CONN_STATE_OPEN.
    649     */
    650    return 0;
    651  } else { /* it's already open. use it. */
    652    tor_assert(!circ->base_.n_hop);
    653    circ->base_.n_chan = n_chan;
    654    /* We found a channel, and we're using it for an origin circuit. */
    655    channel_mark_as_used_for_origin_circuit(n_chan);
    656    circuit_chan_publish(circ, n_chan);
    657    log_debug(LD_CIRC,"Conn open for %s. Delivering first onion skin.",
    658              safe_str_client(extend_info_describe(firsthop->extend_info)));
    659    if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
    660      log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
    661      circ->base_.n_chan = NULL;
    662      return err_reason;
    663    }
    664  }
    665  return 0;
    666 }
    667 
    668 /** Find any circuits that are waiting on <b>chan</b> to become
    669 * open and get them to send their create cells forward.
    670 *
    671 * Status is 1 if connect succeeded, or 0 if connect failed.
    672 */
    673 void
    674 circuit_n_chan_done(channel_t *chan, int status)
    675 {
    676  smartlist_t *pending_circs;
    677  int err_reason = 0;
    678 
    679  tor_assert(chan);
    680 
    681  log_debug(LD_CIRC,"chan to %s, status=%d",
    682            channel_describe_peer(chan), status);
    683 
    684  pending_circs = smartlist_new();
    685  circuit_get_all_pending_on_channel(pending_circs, chan);
    686 
    687  SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
    688    {
    689      /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
    690       * leaving them in in case it's possible for the status of a circuit to
    691       * change as we're going down the list. */
    692      if (circ->marked_for_close || circ->n_chan || !circ->n_hop ||
    693          circ->state != CIRCUIT_STATE_CHAN_WAIT)
    694        continue;
    695 
    696      const char *rsa_ident = NULL;
    697      const ed25519_public_key_t *ed_ident = NULL;
    698      if (! tor_digest_is_zero(circ->n_hop->identity_digest)) {
    699        rsa_ident = circ->n_hop->identity_digest;
    700      }
    701      if (! ed25519_public_key_is_zero(&circ->n_hop->ed_identity)) {
    702        ed_ident = &circ->n_hop->ed_identity;
    703      }
    704 
    705      if (rsa_ident == NULL && ed_ident == NULL) {
    706        /* Look at addr/port. This is an unkeyed connection. */
    707        if (!channel_matches_extend_info(chan, circ->n_hop))
    708          continue;
    709      } else {
    710        /* We expected a key or keys. See if they matched. */
    711        if (!channel_remote_identity_matches(chan, rsa_ident, ed_ident))
    712          continue;
    713 
    714        /* If the channel is canonical, great.  If not, it needs to match
    715         * the requested address exactly. */
    716        if (! chan->is_canonical &&
    717            ! channel_matches_extend_info(chan, circ->n_hop)) {
    718          continue;
    719        }
    720      }
    721      if (!status) { /* chan failed; close circ */
    722        log_info(LD_CIRC,"Channel failed; closing circ.");
    723        circuit_mark_for_close(circ, END_CIRC_REASON_CHANNEL_CLOSED);
    724        continue;
    725      }
    726 
    727      log_debug(LD_CIRC, "Found circ, sending create cell.");
    728      /* circuit_deliver_create_cell will set n_circ_id and add us to
    729       * chan_circuid_circuit_map, so we don't need to call
    730       * set_circid_chan here. */
    731      circ->n_chan = chan;
    732      extend_info_free(circ->n_hop);
    733      circ->n_hop = NULL;
    734 
    735      if (CIRCUIT_IS_ORIGIN(circ)) {
    736        if ((err_reason =
    737             circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
    738          log_info(LD_CIRC,
    739                   "send_next_onion_skin failed; circuit marked for closing.");
    740          circuit_mark_for_close(circ, -err_reason);
    741          continue;
    742          /* XXX could this be bad, eg if next_onion_skin failed because conn
    743           *     died? */
    744        }
    745      } else {
    746        /* pull the create cell out of circ->n_chan_create_cell, and send it */
    747        tor_assert(circ->n_chan_create_cell);
    748        if (circuit_deliver_create_cell(circ, circ->n_chan_create_cell, 1)<0) {
    749          circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
    750          continue;
    751        }
    752        tor_free(circ->n_chan_create_cell);
    753        circuit_set_state(circ, CIRCUIT_STATE_OPEN);
    754      }
    755    }
    756  SMARTLIST_FOREACH_END(circ);
    757 
    758  smartlist_free(pending_circs);
    759 }
    760 
    761 /** Find a new circid that isn't currently in use on the circ->n_chan
    762 * for the outgoing
    763 * circuit <b>circ</b>, and deliver the cell <b>create_cell</b> to this
    764 * circuit.  If <b>relayed</b> is true, this is a create cell somebody
    765 * gave us via an EXTEND cell, so we shouldn't worry if we don't understand
    766 * it. Return -1 if we failed to find a suitable circid, else return 0.
    767 */
    768 MOCK_IMPL(int,
    769 circuit_deliver_create_cell,(circuit_t *circ,
    770                             const struct create_cell_t *create_cell,
    771                             int relayed))
    772 {
    773  cell_t cell;
    774  circid_t id;
    775  int r;
    776 
    777  tor_assert(circ);
    778  tor_assert(circ->n_chan);
    779  tor_assert(create_cell);
    780  tor_assert(create_cell->cell_type == CELL_CREATE ||
    781             create_cell->cell_type == CELL_CREATE_FAST ||
    782             create_cell->cell_type == CELL_CREATE2);
    783 
    784  id = get_unique_circ_id_by_chan(circ->n_chan);
    785  if (!id) {
    786    static ratelim_t circid_warning_limit = RATELIM_INIT(9600);
    787    log_fn_ratelim(&circid_warning_limit, LOG_WARN, LD_CIRC,
    788                   "failed to get unique circID.");
    789    goto error;
    790  }
    791 
    792  tor_assert_nonfatal_once(circ->n_chan->is_canonical);
    793 
    794  memset(&cell, 0, sizeof(cell_t));
    795  r = relayed ? create_cell_format_relayed(&cell, create_cell)
    796              : create_cell_format(&cell, create_cell);
    797  if (r < 0) {
    798    log_warn(LD_CIRC,"Couldn't format create cell");
    799    goto error;
    800  }
    801  log_debug(LD_CIRC,"Chosen circID %u.", (unsigned)id);
    802  circuit_set_n_circid_chan(circ, id, circ->n_chan);
    803  cell.circ_id = circ->n_circ_id;
    804 
    805  if (append_cell_to_circuit_queue(circ, circ->n_chan, &cell,
    806                                   CELL_DIRECTION_OUT, 0) < 0) {
    807    return -1;
    808  }
    809 
    810  if (CIRCUIT_IS_ORIGIN(circ)) {
    811    /* Update began timestamp for circuits starting their first hop */
    812    if (TO_ORIGIN_CIRCUIT(circ)->cpath->state == CPATH_STATE_CLOSED) {
    813      if (!CHANNEL_IS_OPEN(circ->n_chan)) {
    814        log_warn(LD_CIRC,
    815                 "Got first hop for a circuit without an opened channel. "
    816                 "State: %s.", channel_state_to_string(circ->n_chan->state));
    817        tor_fragile_assert();
    818      }
    819 
    820      tor_gettimeofday(&circ->timestamp_began);
    821    }
    822 
    823    /* mark it so it gets better rate limiting treatment. */
    824    channel_timestamp_client(circ->n_chan);
    825  }
    826 
    827  return 0;
    828 error:
    829  circ->n_chan = NULL;
    830  return -1;
    831 }
    832 
    833 /** Return true iff we should send a create_fast cell to start building a
    834 * given circuit */
    835 static inline bool
    836 should_use_create_fast_for_circuit(origin_circuit_t *circ)
    837 {
    838  tor_assert(circ->cpath);
    839  tor_assert(circ->cpath->extend_info);
    840 
    841  return ! circuit_has_usable_onion_key(circ);
    842 }
    843 
    844 /**
    845 * Return true if <b>circ</b> is the type of circuit we want to count
    846 * timeouts from.
    847 *
    848 * In particular, we want to consider any circuit that plans to build
    849 * at least 3 hops (but maybe more), but has 3 or fewer hops built
    850 * so far.
    851 *
    852 * We still want to consider circuits before 3 hops, because we need
    853 * to decide if we should convert them to a measurement circuit in
    854 * circuit_build_times_handle_completed_hop(), rather than letting
    855 * slow circuits get killed right away.
    856 */
    857 int
    858 circuit_timeout_want_to_count_circ(const origin_circuit_t *circ)
    859 {
    860  return !circ->has_opened
    861          && circ->build_state->desired_path_len >= DEFAULT_ROUTE_LEN
    862          && circuit_get_cpath_opened_len(circ) <= DEFAULT_ROUTE_LEN;
    863 }
    864 
    865 /** Decide whether to use a TAP or ntor handshake for connecting to <b>ei</b>
    866 * directly, and set *<b>cell_type_out</b> and *<b>handshake_type_out</b>
    867 * accordingly.
    868 * Note that TAP handshakes in CREATE cells are only used for direct
    869 * connections:
    870 *  - from Single Onions to rend points not in the service's consensus.
    871 * This is checked in onion_populate_cpath. */
    872 static void
    873 circuit_pick_create_handshake(uint8_t *cell_type_out,
    874                              uint16_t *handshake_type_out,
    875                              const extend_info_t *ei)
    876 {
    877  /* torspec says: In general, clients SHOULD use CREATE whenever they are
    878   * using the TAP handshake, and CREATE2 otherwise. */
    879  *cell_type_out = CELL_CREATE2;
    880  /* Only use ntor v3 with exits that support congestion control,
    881   * and only when it is enabled. */
    882  if (ei->exit_supports_congestion_control &&
    883      congestion_control_enabled())
    884    *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR_V3;
    885  else if (ei->enable_cgo)
    886    *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR_V3;
    887  else
    888    *handshake_type_out = ONION_HANDSHAKE_TYPE_NTOR;
    889 }
    890 
    891 /** Decide whether to use a TAP or ntor handshake for extending to <b>ei</b>
    892 * and set *<b>handshake_type_out</b> accordingly. Decide whether we should
    893 * use an EXTEND2 or an EXTEND cell to do so, and set *<b>cell_type_out</b>
    894 * and *<b>create_cell_type_out</b> accordingly.
    895 * Note that TAP handshakes in EXTEND cells are only used:
    896 *  - from clients to intro points, and
    897 *  - from hidden services to rend points.
    898 * This is checked in onion_populate_cpath.
    899 */
    900 static void
    901 circuit_pick_extend_handshake(uint8_t *cell_type_out,
    902                              uint8_t *create_cell_type_out,
    903                              uint16_t *handshake_type_out,
    904                              const extend_info_t *ei)
    905 {
    906  uint8_t t;
    907  circuit_pick_create_handshake(&t, handshake_type_out, ei);
    908 
    909  *cell_type_out = RELAY_COMMAND_EXTEND2;
    910  *create_cell_type_out = CELL_CREATE2;
    911 }
    912 
    913 /**
    914 * Return true iff <b>circ</b> is allowed
    915 * to have no guard configured, even if the circuit is multihop
    916 * and guards are enabled.
    917 */
    918 static int
    919 circuit_may_omit_guard(const origin_circuit_t *circ)
    920 {
    921  if (BUG(!circ))
    922    return 0;
    923 
    924  if (circ->first_hop_from_controller) {
    925    /* The controller picked the first hop: that bypasses the guard system. */
    926    return 1;
    927  }
    928 
    929  switch (circ->base_.purpose) {
    930    case CIRCUIT_PURPOSE_TESTING:
    931    case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
    932      /* Testing circuits may omit guards because they're measuring
    933       * liveness or performance, and don't want guards to interfere. */
    934      return 1;
    935    default:
    936      /* All other multihop circuits should use guards if guards are
    937       * enabled. */
    938      return 0;
    939  }
    940 }
    941 
    942 /** This is the backbone function for building circuits.
    943 *
    944 * If circ's first hop is closed, then we need to build a create
    945 * cell and send it forward.
    946 *
    947 * Otherwise, if circ's cpath still has any non-open hops, we need to
    948 * build a relay extend cell and send it forward to the next non-open hop.
    949 *
    950 * If all hops on the cpath are open, we're done building the circuit
    951 * and we should do housekeeping for the newly opened circuit.
    952 *
    953 * Return -reason if we want to tear down circ, else return 0.
    954 */
    955 int
    956 circuit_send_next_onion_skin(origin_circuit_t *circ)
    957 {
    958  tor_assert(circ);
    959 
    960  if (circ->cpath->state == CPATH_STATE_CLOSED) {
    961    /* Case one: we're on the first hop. */
    962    return circuit_send_first_onion_skin(circ);
    963  }
    964 
    965  tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
    966  tor_assert(circ->base_.state == CIRCUIT_STATE_BUILDING);
    967 
    968  crypt_path_t *hop = cpath_get_next_non_open_hop(circ->cpath);
    969  circuit_build_times_handle_completed_hop(circ);
    970 
    971  circpad_machine_event_circ_added_hop(circ);
    972 
    973  if (hop) {
    974    /* Case two: we're on a hop after the first. */
    975    return circuit_send_intermediate_onion_skin(circ, hop);
    976  }
    977 
    978  /* Case three: the circuit is finished. Do housekeeping tasks on it. */
    979  circpad_machine_event_circ_built(circ);
    980  return circuit_build_no_more_hops(circ);
    981 }
    982 
    983 /**
    984 * Called from circuit_send_next_onion_skin() when we find ourselves connected
    985 * to the first hop in <b>circ</b>: Send a CREATE or CREATE2 or CREATE_FAST
    986 * cell to that hop.  Return 0 on success; -reason on failure (if the circuit
    987 * should be torn down).
    988 */
    989 static int
    990 circuit_send_first_onion_skin(origin_circuit_t *circ)
    991 {
    992  int fast;
    993  int len;
    994  const node_t *node;
    995  create_cell_t cc;
    996  memset(&cc, 0, sizeof(cc));
    997 
    998  log_debug(LD_CIRC,"First skin; sending create cell.");
    999 
   1000  if (circ->build_state->onehop_tunnel) {
   1001    control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
   1002  } else {
   1003    control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);
   1004 
   1005    /* If this is not a one-hop tunnel, the channel is being used
   1006     * for traffic that wants anonymity and protection from traffic
   1007     * analysis (such as netflow record retention). That means we want
   1008     * to pad it.
   1009     */
   1010    if (circ->base_.n_chan->channel_usage < CHANNEL_USED_FOR_FULL_CIRCS)
   1011      circ->base_.n_chan->channel_usage = CHANNEL_USED_FOR_FULL_CIRCS;
   1012  }
   1013 
   1014  node = node_get_by_id(circ->base_.n_chan->identity_digest);
   1015  fast = should_use_create_fast_for_circuit(circ);
   1016  if (!fast) {
   1017    /* We know the right onion key: we should send a create cell. */
   1018    circuit_pick_create_handshake(&cc.cell_type, &cc.handshake_type,
   1019                                  circ->cpath->extend_info);
   1020  } else {
   1021    /* We don't know an onion key, so we need to fall back to CREATE_FAST. */
   1022    cc.cell_type = CELL_CREATE_FAST;
   1023    cc.handshake_type = ONION_HANDSHAKE_TYPE_FAST;
   1024  }
   1025 
   1026  len = onion_skin_create(cc.handshake_type,
   1027                          circ->cpath->extend_info,
   1028                          &circ->cpath->handshake_state,
   1029                          cc.onionskin,
   1030                          sizeof(cc.onionskin));
   1031  if (len < 0) {
   1032    log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
   1033    return - END_CIRC_REASON_INTERNAL;
   1034  }
   1035  cc.handshake_len = len;
   1036 
   1037  if (circuit_deliver_create_cell(TO_CIRCUIT(circ), &cc, 0) < 0)
   1038    return - END_CIRC_REASON_RESOURCELIMIT;
   1039  tor_trace(TR_SUBSYS(circuit), TR_EV(first_onion_skin), circ, circ->cpath);
   1040 
   1041  circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
   1042  circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
   1043  log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
   1044           fast ? "CREATE_FAST" : "CREATE",
   1045           node ? node_describe(node) : "<unnamed>");
   1046  return 0;
   1047 }
   1048 
   1049 /**
   1050 * Called from circuit_send_next_onion_skin() when we find that we have no
   1051 * more hops: mark the circuit as finished, and perform the necessary
   1052 * bookkeeping.  Return 0 on success; -reason on failure (if the circuit
   1053 * should be torn down).
   1054 */
   1055 static int
   1056 circuit_build_no_more_hops(origin_circuit_t *circ)
   1057 {
   1058  guard_usable_t r;
   1059  if (! circ->guard_state) {
   1060    if (circuit_get_cpath_len(circ) != 1 &&
   1061        ! circuit_may_omit_guard(circ) &&
   1062        get_options()->UseEntryGuards) {
   1063      log_warn(LD_BUG, "%d-hop circuit %p with purpose %d has no "
   1064               "guard state",
   1065               circuit_get_cpath_len(circ), circ, circ->base_.purpose);
   1066    }
   1067    r = GUARD_USABLE_NOW;
   1068  } else {
   1069    r = entry_guard_succeeded(&circ->guard_state);
   1070  }
   1071  const int is_usable_for_streams = (r == GUARD_USABLE_NOW);
   1072  if (r == GUARD_USABLE_NOW) {
   1073    circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
   1074  } else if (r == GUARD_MAYBE_USABLE_LATER) {
   1075    // Wait till either a better guard succeeds, or till
   1076    // all better guards fail.
   1077    circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_GUARD_WAIT);
   1078  } else {
   1079    tor_assert_nonfatal(r == GUARD_USABLE_NEVER);
   1080    return - END_CIRC_REASON_INTERNAL;
   1081  }
   1082 
   1083  /* XXXX #21422 -- the rest of this branch needs careful thought!
   1084   * Some of the things here need to happen when a circuit becomes
   1085   * mechanically open; some need to happen when it is actually usable.
   1086   * I think I got them right, but more checking would be wise. -NM
   1087   */
   1088 
   1089  log_info(LD_CIRC,"circuit built!");
   1090  circuit_reset_failure_count(0);
   1091 
   1092  if (circ->build_state->onehop_tunnel || circ->has_opened) {
   1093    control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
   1094  }
   1095 
   1096  pathbias_count_build_success(circ);
   1097  if (is_usable_for_streams)
   1098    circuit_has_opened(circ); /* do other actions as necessary */
   1099 
   1100  if (!have_completed_a_circuit() && !circ->build_state->onehop_tunnel) {
   1101    const or_options_t *options = get_options();
   1102    note_that_we_completed_a_circuit();
   1103    /* FFFF Log a count of known routers here */
   1104    log_info(LD_GENERAL,
   1105             "Tor has successfully opened a circuit. "
   1106             "Looks like client functionality is working.");
   1107    control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
   1108    control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
   1109    clear_broken_connection_map(1);
   1110    if (server_mode(options) &&
   1111        !router_all_orports_seem_reachable(options)) {
   1112      router_do_reachability_checks();
   1113    }
   1114  }
   1115 
   1116  /* We're done with measurement circuits here. Just close them */
   1117  if (circ->base_.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
   1118    circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
   1119  }
   1120  return 0;
   1121 }
   1122 
   1123 /**
   1124 * Called from circuit_send_next_onion_skin() when we find that we have a hop
   1125 * other than the first that we need to extend to: use <b>hop</b>'s
   1126 * information to extend the circuit another step. Return 0 on success;
   1127 * -reason on failure (if the circuit should be torn down).
   1128 */
   1129 static int
   1130 circuit_send_intermediate_onion_skin(origin_circuit_t *circ,
   1131                                     crypt_path_t *hop)
   1132 {
   1133  int len;
   1134  extend_cell_t ec;
   1135  /* Relays and bridges can send IPv6 extends. But for clients, it's an
   1136   * obvious version distinguisher. */
   1137  const bool include_ipv6 = server_mode(get_options());
   1138  memset(&ec, 0, sizeof(ec));
   1139  tor_addr_make_unspec(&ec.orport_ipv4.addr);
   1140  tor_addr_make_unspec(&ec.orport_ipv6.addr);
   1141 
   1142  log_debug(LD_CIRC,"starting to send subsequent skin.");
   1143 
   1144  circuit_pick_extend_handshake(&ec.cell_type,
   1145                                &ec.create_cell.cell_type,
   1146                                &ec.create_cell.handshake_type,
   1147                                hop->extend_info);
   1148 
   1149  const tor_addr_port_t *orport4 =
   1150    extend_info_get_orport(hop->extend_info, AF_INET);
   1151  const tor_addr_port_t *orport6 =
   1152    extend_info_get_orport(hop->extend_info, AF_INET6);
   1153  int n_addrs_set = 0;
   1154  if (orport4) {
   1155    tor_addr_copy(&ec.orport_ipv4.addr, &orport4->addr);
   1156    ec.orport_ipv4.port = orport4->port;
   1157    ++n_addrs_set;
   1158  }
   1159  if (orport6 && include_ipv6) {
   1160    tor_addr_copy(&ec.orport_ipv6.addr, &orport6->addr);
   1161    ec.orport_ipv6.port = orport6->port;
   1162    ++n_addrs_set;
   1163  }
   1164 
   1165  if (n_addrs_set == 0) {
   1166    log_warn(LD_BUG, "No supported address family found in extend_info.");
   1167    return - END_CIRC_REASON_INTERNAL;
   1168  }
   1169  memcpy(ec.node_id, hop->extend_info->identity_digest, DIGEST_LEN);
   1170  /* Set the ED25519 identity too -- it will only get included
   1171   * in the extend2 cell if we're configured to use it, though. */
   1172  ed25519_pubkey_copy(&ec.ed_pubkey, &hop->extend_info->ed_identity);
   1173 
   1174  len = onion_skin_create(ec.create_cell.handshake_type,
   1175                          hop->extend_info,
   1176                          &hop->handshake_state,
   1177                          ec.create_cell.onionskin,
   1178                          sizeof(ec.create_cell.onionskin));
   1179  if (len < 0) {
   1180    log_warn(LD_CIRC,"onion_skin_create failed.");
   1181    return - END_CIRC_REASON_INTERNAL;
   1182  }
   1183  ec.create_cell.handshake_len = len;
   1184 
   1185  log_info(LD_CIRC,"Sending extend relay cell.");
   1186  {
   1187    uint8_t command = 0;
   1188    uint16_t payload_len=0;
   1189    uint8_t payload[RELAY_PAYLOAD_SIZE_MAX];
   1190    if (extend_cell_format(&command, &payload_len, payload, &ec)<0) {
   1191      log_warn(LD_CIRC,"Couldn't format extend cell");
   1192      return -END_CIRC_REASON_INTERNAL;
   1193    }
   1194 
   1195    if (payload_len > circuit_max_relay_payload(
   1196                             TO_CIRCUIT(circ), hop->prev, command)) {
   1197      log_warn(LD_BUG, "Generated a too-long extend cell");
   1198      return -END_CIRC_REASON_INTERNAL;
   1199    }
   1200 
   1201    /* send it to hop->prev, because that relay will transfer
   1202     * it to a create cell and then send to hop */
   1203    if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
   1204                                     command,
   1205                                     (char*)payload, payload_len,
   1206                                     hop->prev) < 0)
   1207      return 0; /* circuit is closed */
   1208  }
   1209  hop->state = CPATH_STATE_AWAITING_KEYS;
   1210  tor_trace(TR_SUBSYS(circuit), TR_EV(intermediate_onion_skin), circ, hop);
   1211  return 0;
   1212 }
   1213 
   1214 /** Our clock just jumped by <b>seconds_elapsed</b>. If <b>was_idle</b> is
   1215 * true, then the monotonic time matches; otherwise it doesn't. Assume
   1216 * something has also gone wrong with our network: notify the user, and
   1217 * abandon all not-yet-used circuits. */
   1218 void
   1219 circuit_note_clock_jumped(int64_t seconds_elapsed, bool was_idle)
   1220 {
   1221  int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
   1222  if (was_idle) {
   1223    tor_log(severity, LD_GENERAL, "Tor has been idle for %"PRId64
   1224            " seconds; assuming established circuits no longer work.",
   1225            (seconds_elapsed));
   1226  } else {
   1227    tor_log(severity, LD_GENERAL,
   1228            "Your system clock just jumped %"PRId64" seconds %s; "
   1229            "assuming established circuits no longer work.",
   1230            (
   1231                 seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed),
   1232            seconds_elapsed >=0 ? "forward" : "backward");
   1233  }
   1234  control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%"PRId64
   1235                               " IDLE=%d",
   1236                               (seconds_elapsed), was_idle?1:0);
   1237  /* so we log when it works again */
   1238  note_that_we_maybe_cant_complete_circuits();
   1239  control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
   1240                              "CLOCK_JUMPED");
   1241  circuit_mark_all_unused_circs();
   1242  circuit_mark_all_dirty_circs_as_unusable();
   1243  if (seconds_elapsed < 0) {
   1244    /* Restart all the timers in case we jumped a long way into the past. */
   1245    reset_all_main_loop_timers();
   1246  }
   1247 }
   1248 
   1249 /** A "created" cell <b>reply</b> came back to us on circuit <b>circ</b>.
   1250 * (The body of <b>reply</b> varies depending on what sort of handshake
   1251 * this is.)
   1252 *
   1253 * Calculate the appropriate keys and digests, make sure KH is
   1254 * correct, and initialize this hop of the cpath.
   1255 *
   1256 * Return - reason if we want to mark circ for close, else return 0.
   1257 */
   1258 int
   1259 circuit_finish_handshake(origin_circuit_t *circ,
   1260                         const created_cell_t *reply)
   1261 {
   1262  char keys[MAX_RELAY_KEY_MATERIAL_LEN];
   1263  crypt_path_t *hop;
   1264  int rv;
   1265 
   1266  if ((rv = pathbias_count_build_attempt(circ)) < 0) {
   1267    log_warn(LD_CIRC, "pathbias_count_build_attempt failed: %d", rv);
   1268    return rv;
   1269  }
   1270 
   1271  if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
   1272    hop = circ->cpath;
   1273  } else {
   1274    hop = cpath_get_next_non_open_hop(circ->cpath);
   1275    if (!hop) { /* got an extended when we're all done? */
   1276      log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
   1277      return - END_CIRC_REASON_TORPROTOCOL;
   1278    }
   1279  }
   1280  tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);
   1281 
   1282  circuit_params_t params;
   1283  size_t keylen = sizeof(keys);
   1284  {
   1285    const char *msg = NULL;
   1286 
   1287    if (onion_skin_client_handshake(hop->handshake_state.tag,
   1288                                    &hop->handshake_state,
   1289                                    reply->reply, reply->handshake_len,
   1290                                    (uint8_t*)keys, &keylen,
   1291                                    (uint8_t*)hop->rend_circ_nonce,
   1292                                    &params,
   1293                                    &msg) < 0) {
   1294      if (msg)
   1295        log_warn(LD_CIRC,"onion_skin_client_handshake failed: %s", msg);
   1296      return -END_CIRC_REASON_TORPROTOCOL;
   1297    }
   1298  }
   1299 
   1300  onion_handshake_state_release(&hop->handshake_state);
   1301  if (cpath_init_circuit_crypto(params.crypto_alg,
   1302                                hop, keys, keylen)<0) {
   1303    return -END_CIRC_REASON_TORPROTOCOL;
   1304  }
   1305  hop->relay_cell_format = params.cell_fmt;
   1306 
   1307  if (params.cc_enabled) {
   1308    int circ_len = circuit_get_cpath_len(circ);
   1309 
   1310    if (circ_len == DEFAULT_ROUTE_LEN &&
   1311        circuit_get_cpath_hop(circ, DEFAULT_ROUTE_LEN) == hop) {
   1312      hop->ccontrol = congestion_control_new(&params, CC_PATH_EXIT);
   1313    } else if (circ_len == SBWS_ROUTE_LEN &&
   1314               circuit_get_cpath_hop(circ, SBWS_ROUTE_LEN) == hop) {
   1315      hop->ccontrol = congestion_control_new(&params, CC_PATH_SBWS);
   1316    } else {
   1317      if (circ_len > DEFAULT_ROUTE_LEN) {
   1318        /* This can happen for unknown reasons; cannibalization codepaths
   1319         * don't seem able to do it, so there is some magic way that hops can
   1320         * still get added. Perhaps some cases of circuit pre-build that change
   1321         * purpose? */
   1322        log_info(LD_CIRC,
   1323                   "Unexpected path length %d for exit circuit %d, purpose %d",
   1324                    circ_len, circ->global_identifier,
   1325                    TO_CIRCUIT(circ)->purpose);
   1326        hop->ccontrol = congestion_control_new(&params, CC_PATH_EXIT);
   1327      } else {
   1328        /* This is likely directory requests, which should block on orconn
   1329         * before congestion control, but let's give them the lower sbws
   1330         * param set anyway just in case. */
   1331        log_info(LD_CIRC,
   1332                 "Unexpected path length %d for exit circuit %d, purpose %d",
   1333                 circ_len, circ->global_identifier,
   1334                 TO_CIRCUIT(circ)->purpose);
   1335 
   1336        hop->ccontrol = congestion_control_new(&params, CC_PATH_SBWS);
   1337      }
   1338    }
   1339  }
   1340 
   1341  hop->state = CPATH_STATE_OPEN;
   1342  log_info(LD_CIRC,"Finished building circuit hop:");
   1343  circuit_log_path(LOG_INFO,LD_CIRC,circ);
   1344  circuit_event_status(circ, CIRC_EVENT_EXTENDED, 0);
   1345 
   1346  return 0;
   1347 }
   1348 
   1349 /** We received a relay truncated cell on circ.
   1350 *
   1351 * Since we don't send truncates currently, getting a truncated
   1352 * means that a connection broke or an extend failed. For now,
   1353 * just give up: force circ to close, and return 0.
   1354 */
   1355 int
   1356 circuit_truncated(origin_circuit_t *circ, int reason)
   1357 {
   1358 //  crypt_path_t *victim;
   1359 //  connection_t *stream;
   1360 
   1361  tor_assert(circ);
   1362 
   1363  /* XXX Since we don't send truncates currently, getting a truncated
   1364   *     means that a connection broke or an extend failed. For now,
   1365   *     just give up.
   1366   */
   1367  circuit_mark_for_close(TO_CIRCUIT(circ),
   1368          END_CIRC_REASON_FLAG_REMOTE|reason);
   1369  return 0;
   1370 
   1371 #if 0
   1372  while (layer->next != circ->cpath) {
   1373    /* we need to clear out layer->next */
   1374    victim = layer->next;
   1375    log_debug(LD_CIRC, "Killing a layer of the cpath.");
   1376 
   1377    for (stream = circ->p_streams; stream; stream=stream->next_stream) {
   1378      if (stream->cpath_layer == victim) {
   1379        log_info(LD_APP, "Marking stream %d for close because of truncate.",
   1380                 stream->stream_id);
   1381        /* no need to send 'end' relay cells,
   1382         * because the other side's already dead
   1383         */
   1384        connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
   1385      }
   1386    }
   1387 
   1388    layer->next = victim->next;
   1389    cpath_free(victim);
   1390  }
   1391 
   1392  log_info(LD_CIRC, "finished");
   1393  return 0;
   1394 #endif /* 0 */
   1395 }
   1396 
   1397 /** Helper for new_route_len().  Choose a circuit length for purpose
   1398 * <b>purpose</b>: DEFAULT_ROUTE_LEN (+ 1 if someone else chose the
   1399 * exit).  If someone else chose the exit, they could be colluding
   1400 * with the exit, so add a randomly selected node to preserve
   1401 * anonymity.
   1402 *
   1403 * Here, "exit node" sometimes means an OR acting as an internal
   1404 * endpoint, rather than as a relay to an external endpoint.  This
   1405 * means there need to be at least DEFAULT_ROUTE_LEN routers between
   1406 * us and the internal endpoint to preserve the same anonymity
   1407 * properties that we would get when connecting to an external
   1408 * endpoint.  These internal endpoints can include:
   1409 *
   1410 *   - Connections to a directory of hidden services
   1411 *     (CIRCUIT_PURPOSE_C_GENERAL)
   1412 *
   1413 *   - A client connecting to an introduction point, which the hidden
   1414 *     service picked (CIRCUIT_PURPOSE_C_INTRODUCING, via
   1415 *     circuit_get_open_circ_or_launch() which rewrites it from
   1416 *     CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
   1417 *
   1418 *   - A hidden service connecting to a rendezvous point, which the
   1419 *     client picked (CIRCUIT_PURPOSE_S_CONNECT_REND.
   1420 *
   1421 * There are currently two situations where we picked the exit node
   1422 * ourselves, making DEFAULT_ROUTE_LEN a safe circuit length:
   1423 *
   1424 *   - We are a hidden service connecting to an introduction point
   1425 *     (CIRCUIT_PURPOSE_S_ESTABLISH_INTRO).
   1426 *
   1427 *   - We are a router testing its own reachabiity
   1428 *     (CIRCUIT_PURPOSE_TESTING, via router_do_reachability_checks())
   1429 *
   1430 * onion_pick_cpath_exit() bypasses us (by not calling
   1431 * new_route_len()) in the one-hop tunnel case, so we don't need to
   1432 * handle that.
   1433 */
   1434 int
   1435 route_len_for_purpose(uint8_t purpose, extend_info_t *exit_ei)
   1436 {
   1437  int routelen = DEFAULT_ROUTE_LEN;
   1438  int known_purpose = 0;
   1439 
   1440  /* If we're using L3 vanguards, we need longer paths for onion services */
   1441  if (circuit_purpose_is_hidden_service(purpose) &&
   1442      get_options()->HSLayer3Nodes) {
   1443    /* Clients want an extra hop for rends to avoid linkability.
   1444     * Services want it for intro points to avoid publishing their
   1445     * layer3 guards. They want it for hsdir posts to use
   1446     * their full layer3 guard set for those connections.
   1447     * Ex: C - G - L2 - L3 - R
   1448     *     S - G - L2 - L3 - HSDIR
   1449     *     S - G - L2 - L3 - I
   1450     */
   1451    if (purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND ||
   1452        purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
   1453        purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
   1454        purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
   1455      return routelen+1;
   1456 
   1457    /* For connections to hsdirs, clients want two extra hops
   1458     * when using layer3 guards, to avoid linkability.
   1459     * Same goes for intro points. Note that the route len
   1460     * includes the intro point or hsdir, hence the +2.
   1461     * Ex: C - G - L2 - L3 - M - I
   1462     *     C - G - L2 - L3 - M - HSDIR
   1463     *     S - G - L2 - L3 - M - R
   1464     */
   1465    if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
   1466        purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
   1467        purpose == CIRCUIT_PURPOSE_C_INTRODUCING)
   1468      return routelen+2;
   1469  }
   1470 
   1471  if (!exit_ei)
   1472    return routelen;
   1473 
   1474  switch (purpose) {
   1475    /* These purposes connect to a router that we chose, so DEFAULT_ROUTE_LEN
   1476     * is safe: */
   1477  case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
   1478  case CIRCUIT_PURPOSE_TESTING:
   1479    /* router reachability testing */
   1480    known_purpose = 1;
   1481    break;
   1482 
   1483    /* These purposes connect to a router that someone else
   1484     * might have chosen, so add an extra hop to protect anonymity. */
   1485  case CIRCUIT_PURPOSE_C_GENERAL:
   1486  case CIRCUIT_PURPOSE_C_HSDIR_GET:
   1487  case CIRCUIT_PURPOSE_S_HSDIR_POST:
   1488    /* connecting to hidden service directory */
   1489  case CIRCUIT_PURPOSE_C_INTRODUCING:
   1490    /* client connecting to introduction point */
   1491  case CIRCUIT_PURPOSE_S_CONNECT_REND:
   1492    /* hidden service connecting to rendezvous point */
   1493  case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
   1494    /* hidden service connecting to intro point. In this case we want an extra
   1495       hop to avoid linkability attacks by the introduction point. */
   1496    known_purpose = 1;
   1497    routelen++;
   1498    break;
   1499 
   1500  default:
   1501    /* Got a purpose not listed above along with a chosen exit.
   1502     * Increase the circuit length by one anyway for safety. */
   1503    routelen++;
   1504    break;
   1505  }
   1506 
   1507  if (BUG(exit_ei && !known_purpose)) {
   1508    log_warn(LD_BUG, "Unhandled purpose %d with a chosen exit; "
   1509             "assuming routelen %d.", purpose, routelen);
   1510  }
   1511  return routelen;
   1512 }
   1513 
   1514 /** Choose a length for a circuit of purpose <b>purpose</b> and check
   1515 * if enough routers are available.
   1516 *
   1517 * If the routerlist <b>nodes</b> doesn't have enough routers
   1518 * to handle the desired path length, return -1.
   1519 */
   1520 STATIC int
   1521 new_route_len(uint8_t purpose, extend_info_t *exit_ei,
   1522              const smartlist_t *nodes)
   1523 {
   1524  int routelen;
   1525 
   1526  tor_assert(nodes);
   1527 
   1528  routelen = route_len_for_purpose(purpose, exit_ei);
   1529 
   1530  int num_acceptable_direct = count_acceptable_nodes(nodes, 1);
   1531  int num_acceptable_indirect = count_acceptable_nodes(nodes, 0);
   1532 
   1533  log_debug(LD_CIRC,"Chosen route length %d (%d direct and %d indirect "
   1534             "routers suitable).", routelen, num_acceptable_direct,
   1535             num_acceptable_indirect);
   1536 
   1537  if (num_acceptable_direct < 1 || num_acceptable_indirect < routelen - 1) {
   1538    log_info(LD_CIRC,
   1539             "Not enough acceptable routers (%d/%d direct and %d/%d "
   1540             "indirect routers suitable). Discarding this circuit.",
   1541             num_acceptable_direct, routelen,
   1542             num_acceptable_indirect, routelen);
   1543    return -1;
   1544  }
   1545 
   1546  return routelen;
   1547 }
   1548 
   1549 /** Return a newly allocated list of uint16_t * for each predicted port not
   1550 * handled by a current circuit. */
   1551 static smartlist_t *
   1552 circuit_get_unhandled_ports(time_t now)
   1553 {
   1554  smartlist_t *dest = rep_hist_get_predicted_ports(now);
   1555  circuit_remove_handled_ports(dest);
   1556  return dest;
   1557 }
   1558 
   1559 /** Return 1 if we already have circuits present or on the way for
   1560 * all anticipated ports. Return 0 if we should make more.
   1561 *
   1562 * If we're returning 0, set need_uptime and need_capacity to
   1563 * indicate any requirements that the unhandled ports have.
   1564 */
   1565 MOCK_IMPL(int,
   1566 circuit_all_predicted_ports_handled, (time_t now, int *need_uptime,
   1567                                      int *need_capacity))
   1568 {
   1569  int i, enough;
   1570  uint16_t *port;
   1571  smartlist_t *sl = circuit_get_unhandled_ports(now);
   1572  smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
   1573  tor_assert(need_uptime);
   1574  tor_assert(need_capacity);
   1575  // Always predict need_capacity
   1576  *need_capacity = 1;
   1577  enough = (smartlist_len(sl) == 0);
   1578  for (i = 0; i < smartlist_len(sl); ++i) {
   1579    port = smartlist_get(sl, i);
   1580    if (smartlist_contains_int_as_string(LongLivedServices, *port))
   1581      *need_uptime = 1;
   1582    tor_free(port);
   1583  }
   1584  smartlist_free(sl);
   1585  return enough;
   1586 }
   1587 
   1588 /** Return 1 if <b>node</b> can handle one or more of the ports in
   1589 * <b>needed_ports</b>, else return 0.
   1590 */
   1591 static int
   1592 node_handles_some_port(const node_t *node, smartlist_t *needed_ports)
   1593 { /* XXXX MOVE */
   1594  int i;
   1595  uint16_t port;
   1596 
   1597  for (i = 0; i < smartlist_len(needed_ports); ++i) {
   1598    addr_policy_result_t r;
   1599    /* alignment issues aren't a worry for this dereference, since
   1600       needed_ports is explicitly a smartlist of uint16_t's */
   1601    port = *(uint16_t *)smartlist_get(needed_ports, i);
   1602    tor_assert(port);
   1603    if (node)
   1604      r = compare_tor_addr_to_node_policy(NULL, port, node);
   1605    else
   1606      continue;
   1607    if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
   1608      return 1;
   1609  }
   1610  return 0;
   1611 }
   1612 
   1613 /** Return true iff <b>conn</b> needs another general circuit to be
   1614 * built. */
   1615 static int
   1616 ap_stream_wants_exit_attention(connection_t *conn)
   1617 {
   1618  entry_connection_t *entry;
   1619  if (conn->type != CONN_TYPE_AP)
   1620    return 0;
   1621  entry = TO_ENTRY_CONN(conn);
   1622 
   1623  if (conn->state == AP_CONN_STATE_CIRCUIT_WAIT &&
   1624      !conn->marked_for_close &&
   1625      !(entry->want_onehop) && /* ignore one-hop streams */
   1626      !(entry->use_begindir) && /* ignore targeted dir fetches */
   1627      !(entry->chosen_exit_name) && /* ignore defined streams */
   1628      !connection_edge_is_rendezvous_stream(TO_EDGE_CONN(conn)) &&
   1629      !circuit_stream_is_being_handled(TO_ENTRY_CONN(conn), 0,
   1630                                       MIN_CIRCUITS_HANDLING_STREAM))
   1631    return 1;
   1632  return 0;
   1633 }
   1634 
   1635 /** Return a pointer to a suitable router to be the exit node for the
   1636 * general-purpose circuit we're about to build.
   1637 *
   1638 * Look through the connection array, and choose a router that maximizes
   1639 * the number of pending streams that can exit from this router.
   1640 *
   1641 * Return NULL if we can't find any suitable routers.
   1642 */
   1643 static const node_t *
   1644 choose_good_exit_server_general(router_crn_flags_t flags)
   1645 {
   1646  int *n_supported;
   1647  int n_pending_connections = 0;
   1648  smartlist_t *connections;
   1649  int best_support = -1;
   1650  int n_best_support=0;
   1651  const or_options_t *options = get_options();
   1652  const smartlist_t *the_nodes;
   1653  const node_t *selected_node=NULL;
   1654  const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
   1655  const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
   1656 
   1657  /* We should not require guard flags on exits. */
   1658  IF_BUG_ONCE(flags & CRN_NEED_GUARD)
   1659    return NULL;
   1660 
   1661  /* We reject single-hop exits for all node positions. */
   1662  IF_BUG_ONCE(flags & CRN_DIRECT_CONN)
   1663    return NULL;
   1664 
   1665  /* We only want exits to extend if we cannibalize the circuit.
   1666   * But we don't require IPv6 extends yet. */
   1667  IF_BUG_ONCE(flags & CRN_INITIATE_IPV6_EXTEND)
   1668    return NULL;
   1669 
   1670  connections = get_connection_array();
   1671 
   1672  /* Count how many connections are waiting for a circuit to be built.
   1673   * We use this for log messages now, but in the future we may depend on it.
   1674   */
   1675  SMARTLIST_FOREACH(connections, connection_t *, conn,
   1676  {
   1677    if (ap_stream_wants_exit_attention(conn))
   1678      ++n_pending_connections;
   1679  });
   1680 //  log_fn(LOG_DEBUG, "Choosing exit node; %d connections are pending",
   1681 //         n_pending_connections);
   1682  /* Now we count, for each of the routers in the directory, how many
   1683   * of the pending connections could possibly exit from that
   1684   * router (n_supported[i]). (We can't be sure about cases where we
   1685   * don't know the IP address of the pending connection.)
   1686   *
   1687   * -1 means "Don't use this router at all."
   1688   */
   1689  the_nodes = nodelist_get_list();
   1690  n_supported = tor_calloc(smartlist_len(the_nodes), sizeof(int));
   1691  SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
   1692    const int i = node_sl_idx;
   1693    if (router_digest_is_me(node->identity)) {
   1694      n_supported[i] = -1;
   1695 //      log_fn(LOG_DEBUG,"Skipping node %s -- it's me.", router->nickname);
   1696      /* XXX there's probably a reverse predecessor attack here, but
   1697       * it's slow. should we take this out? -RD
   1698       */
   1699      continue;
   1700    }
   1701    if (!router_can_choose_node(node, flags)) {
   1702      n_supported[i] = -1;
   1703      continue;
   1704    }
   1705    if (node->is_bad_exit) {
   1706      n_supported[i] = -1;
   1707      continue; /* skip routers that are known to be down or bad exits */
   1708    }
   1709    if (routerset_contains_node(options->ExcludeExitNodesUnion_, node)) {
   1710      n_supported[i] = -1;
   1711      continue; /* user asked us not to use it, no matter what */
   1712    }
   1713    if (options->ExitNodes &&
   1714        !routerset_contains_node(options->ExitNodes, node)) {
   1715      n_supported[i] = -1;
   1716      continue; /* not one of our chosen exit nodes */
   1717    }
   1718    if (node_exit_policy_rejects_all(node)) {
   1719      n_supported[i] = -1;
   1720 //      log_fn(LOG_DEBUG,"Skipping node %s (index %d) -- it rejects all.",
   1721 //             router->nickname, i);
   1722      continue; /* skip routers that reject all */
   1723    }
   1724    n_supported[i] = 0;
   1725    /* iterate over connections */
   1726    SMARTLIST_FOREACH_BEGIN(connections, connection_t *, conn) {
   1727      if (!ap_stream_wants_exit_attention(conn))
   1728        continue; /* Skip everything but APs in CIRCUIT_WAIT */
   1729      if (connection_ap_can_use_exit(TO_ENTRY_CONN(conn), node)) {
   1730        ++n_supported[i];
   1731 //        log_fn(LOG_DEBUG,"%s is supported. n_supported[%d] now %d.",
   1732 //               router->nickname, i, n_supported[i]);
   1733      } else {
   1734 //        log_fn(LOG_DEBUG,"%s (index %d) would reject this stream.",
   1735 //               router->nickname, i);
   1736      }
   1737    } SMARTLIST_FOREACH_END(conn);
   1738    if (n_pending_connections > 0 && n_supported[i] == 0) {
   1739      /* Leave best_support at -1 if that's where it is, so we can
   1740       * distinguish it later. */
   1741      continue;
   1742    }
   1743    if (n_supported[i] > best_support) {
   1744      /* If this router is better than previous ones, remember its index
   1745       * and goodness, and start counting how many routers are this good. */
   1746      best_support = n_supported[i]; n_best_support=1;
   1747 //      log_fn(LOG_DEBUG,"%s is new best supported option so far.",
   1748 //             router->nickname);
   1749    } else if (n_supported[i] == best_support) {
   1750      /* If this router is _as good_ as the best one, just increment the
   1751       * count of equally good routers.*/
   1752      ++n_best_support;
   1753    }
   1754  } SMARTLIST_FOREACH_END(node);
   1755  log_info(LD_CIRC,
   1756           "Found %d servers that might support %d/%d pending connections.",
   1757           n_best_support, best_support >= 0 ? best_support : 0,
   1758           n_pending_connections);
   1759 
   1760  /* If any routers definitely support any pending connections, choose one
   1761   * at random. */
   1762  if (best_support > 0) {
   1763    smartlist_t *supporting = smartlist_new();
   1764 
   1765    SMARTLIST_FOREACH(the_nodes, const node_t *, node, {
   1766      if (n_supported[node_sl_idx] == best_support)
   1767        smartlist_add(supporting, (void*)node);
   1768    });
   1769 
   1770    selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
   1771    smartlist_free(supporting);
   1772  } else {
   1773    /* Either there are no pending connections, or no routers even seem to
   1774     * possibly support any of them.  Choose a router at random that satisfies
   1775     * at least one predicted exit port. */
   1776 
   1777    int attempt;
   1778    smartlist_t *needed_ports, *supporting;
   1779 
   1780    if (best_support == -1) {
   1781      if (need_uptime || need_capacity) {
   1782        log_info(LD_CIRC,
   1783                 "We couldn't find any live%s%s routers; falling back "
   1784                 "to list of all routers.",
   1785                 need_capacity?", fast":"",
   1786                 need_uptime?", stable":"");
   1787        tor_free(n_supported);
   1788        flags &= ~(CRN_NEED_UPTIME|CRN_NEED_CAPACITY);
   1789        return choose_good_exit_server_general(flags);
   1790      }
   1791      log_notice(LD_CIRC, "All routers are down or won't exit%s -- "
   1792                 "choosing a doomed exit at random.",
   1793                 options->ExcludeExitNodesUnion_ ? " or are Excluded" : "");
   1794    }
   1795    supporting = smartlist_new();
   1796    needed_ports = circuit_get_unhandled_ports(time(NULL));
   1797    for (attempt = 0; attempt < 2; attempt++) {
   1798      /* try once to pick only from routers that satisfy a needed port,
   1799       * then if there are none, pick from any that support exiting. */
   1800      SMARTLIST_FOREACH_BEGIN(the_nodes, const node_t *, node) {
   1801        if (n_supported[node_sl_idx] != -1 &&
   1802            (attempt || node_handles_some_port(node, needed_ports))) {
   1803 //          log_fn(LOG_DEBUG,"Try %d: '%s' is a possibility.",
   1804 //                 try, router->nickname);
   1805          smartlist_add(supporting, (void*)node);
   1806        }
   1807      } SMARTLIST_FOREACH_END(node);
   1808 
   1809      selected_node = node_sl_choose_by_bandwidth(supporting, WEIGHT_FOR_EXIT);
   1810      if (selected_node)
   1811        break;
   1812      smartlist_clear(supporting);
   1813      /* If we reach this point, we can't actually support any unhandled
   1814       * predicted ports, so clear all the remaining ones. */
   1815      if (smartlist_len(needed_ports))
   1816        rep_hist_remove_predicted_ports(needed_ports);
   1817    }
   1818    SMARTLIST_FOREACH(needed_ports, uint16_t *, cp, tor_free(cp));
   1819    smartlist_free(needed_ports);
   1820    smartlist_free(supporting);
   1821  }
   1822 
   1823  tor_free(n_supported);
   1824  if (selected_node) {
   1825    log_info(LD_CIRC, "Chose exit server '%s'", node_describe(selected_node));
   1826    return selected_node;
   1827  }
   1828  if (options->ExitNodes) {
   1829    log_warn(LD_CIRC,
   1830             "No exits in ExitNodes%s seem to be running: "
   1831             "can't choose an exit.",
   1832             options->ExcludeExitNodesUnion_ ?
   1833             ", except possibly those excluded by your configuration, " : "");
   1834  }
   1835  return NULL;
   1836 }
   1837 
   1838 /*
   1839 * Helper function to pick a configured restricted middle node
   1840 * (either HSLayer2Nodes or HSLayer3Nodes).
   1841 *
   1842 * Make sure that the node we chose is alive, and not excluded,
   1843 * and return it.
   1844 *
   1845 * The exclude_set is a routerset of nodes that the selected node
   1846 * must not match, and the exclude_list is a simple list of nodes
   1847 * that the selected node must not be in. Either or both may be
   1848 * NULL.
   1849 *
   1850 * Return NULL if no usable nodes could be found. */
   1851 static const node_t *
   1852 pick_restricted_middle_node(router_crn_flags_t flags,
   1853                            const routerset_t *pick_from,
   1854                            const routerset_t *exclude_set,
   1855                            const smartlist_t *exclude_list,
   1856                            int position_hint)
   1857 {
   1858  const node_t *middle_node = NULL;
   1859 
   1860  smartlist_t *allowlisted_live_middles = smartlist_new();
   1861  smartlist_t *all_live_nodes = smartlist_new();
   1862 
   1863  tor_assert(pick_from);
   1864 
   1865  /* Add all running nodes to all_live_nodes */
   1866  router_add_running_nodes_to_smartlist(all_live_nodes, flags);
   1867 
   1868  /* Filter all_live_nodes to only add live *and* allowlisted middles
   1869   * to the list allowlisted_live_middles. */
   1870  SMARTLIST_FOREACH_BEGIN(all_live_nodes, node_t *, live_node) {
   1871    if (routerset_contains_node(pick_from, live_node)) {
   1872      smartlist_add(allowlisted_live_middles, live_node);
   1873    }
   1874  } SMARTLIST_FOREACH_END(live_node);
   1875 
   1876  /* Honor ExcludeNodes */
   1877  if (exclude_set) {
   1878    routerset_subtract_nodes(allowlisted_live_middles, exclude_set);
   1879  }
   1880 
   1881  if (exclude_list) {
   1882    smartlist_subtract(allowlisted_live_middles, exclude_list);
   1883  }
   1884 
   1885  /**
   1886   * Max number of restricted nodes before we alert the user and try
   1887   * to load balance for them.
   1888   *
   1889   * The most aggressive vanguard design had 16 nodes at layer3.
   1890   * Let's give a small ceiling above that. */
   1891 #define MAX_SANE_RESTRICTED_NODES 20
   1892  /* If the user (or associated tor controller) selected only a few nodes,
   1893   * assume they took load balancing into account and don't do it for them.
   1894   *
   1895   * If there are a lot of nodes in here, assume they did not load balance
   1896   * and do it for them, but also warn them that they may be Doing It Wrong.
   1897   */
   1898  if (smartlist_len(allowlisted_live_middles) <=
   1899          MAX_SANE_RESTRICTED_NODES) {
   1900    middle_node = smartlist_choose(allowlisted_live_middles);
   1901  } else {
   1902    static ratelim_t pinned_notice_limit = RATELIM_INIT(24*3600);
   1903    log_fn_ratelim(&pinned_notice_limit, LOG_NOTICE, LD_CIRC,
   1904            "Your _HSLayer%dNodes setting has resulted "
   1905            "in %d total nodes. This is a lot of nodes. "
   1906            "You may want to consider using a Tor controller "
   1907            "to select and update a smaller set of nodes instead.",
   1908            position_hint, smartlist_len(allowlisted_live_middles));
   1909 
   1910    /* NO_WEIGHTING here just means don't take node flags into account
   1911     * (ie: use consensus measurement only). This is done so that
   1912     * we don't further surprise the user by not using Exits that they
   1913     * specified at all */
   1914    middle_node = node_sl_choose_by_bandwidth(allowlisted_live_middles,
   1915                                              NO_WEIGHTING);
   1916  }
   1917 
   1918  smartlist_free(allowlisted_live_middles);
   1919  smartlist_free(all_live_nodes);
   1920 
   1921  return middle_node;
   1922 }
   1923 
   1924 /** Return a pointer to a suitable router to be the exit node for the
   1925 * circuit of purpose <b>purpose</b> that we're about to build (or NULL
   1926 * if no router is suitable).
   1927 *
   1928 * For general-purpose circuits, pass it off to
   1929 * choose_good_exit_server_general()
   1930 *
   1931 * For client-side rendezvous circuits, choose a random node, weighted
   1932 * toward the preferences in 'options'.
   1933 */
   1934 static const node_t *
   1935 choose_good_exit_server(origin_circuit_t *circ,
   1936                        router_crn_flags_t flags, int is_internal)
   1937 {
   1938  const or_options_t *options = get_options();
   1939  flags |= CRN_NEED_DESC;
   1940 
   1941  switch (TO_CIRCUIT(circ)->purpose) {
   1942    case CIRCUIT_PURPOSE_C_HSDIR_GET:
   1943    case CIRCUIT_PURPOSE_S_HSDIR_POST:
   1944    case CIRCUIT_PURPOSE_HS_VANGUARDS:
   1945    case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
   1946      /* For these three, we want to pick the exit like a middle hop,
   1947       * since it should be random. */
   1948      tor_assert_nonfatal(is_internal);
   1949      /* We want to avoid picking certain nodes for HS purposes. */
   1950      flags |= CRN_FOR_HS;
   1951      FALLTHROUGH;
   1952    case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
   1953    case CIRCUIT_PURPOSE_C_GENERAL:
   1954      if (is_internal) /* pick it like a middle hop */
   1955        return router_choose_random_node(NULL, options->ExcludeNodes, flags);
   1956      else
   1957        return choose_good_exit_server_general(flags);
   1958  }
   1959  log_warn(LD_BUG,"Unhandled purpose %d", TO_CIRCUIT(circ)->purpose);
   1960  tor_fragile_assert();
   1961  return NULL;
   1962 }
   1963 
   1964 /** Log a warning if the user specified an exit for the circuit that
   1965 * has been excluded from use by ExcludeNodes or ExcludeExitNodes. */
   1966 static void
   1967 warn_if_last_router_excluded(origin_circuit_t *circ,
   1968                             const extend_info_t *exit_ei)
   1969 {
   1970  const or_options_t *options = get_options();
   1971  routerset_t *rs = options->ExcludeNodes;
   1972  const char *description;
   1973  uint8_t purpose = circ->base_.purpose;
   1974 
   1975  if (circ->build_state->onehop_tunnel)
   1976    return;
   1977 
   1978  switch (purpose)
   1979    {
   1980    default:
   1981    case CIRCUIT_PURPOSE_OR:
   1982    case CIRCUIT_PURPOSE_INTRO_POINT:
   1983    case CIRCUIT_PURPOSE_REND_POINT_WAITING:
   1984    case CIRCUIT_PURPOSE_REND_ESTABLISHED:
   1985      log_warn(LD_BUG, "Called on non-origin circuit (purpose %d, %s)",
   1986               (int)purpose,
   1987               circuit_purpose_to_string(purpose));
   1988      return;
   1989    case CIRCUIT_PURPOSE_S_HSDIR_POST:
   1990    case CIRCUIT_PURPOSE_C_HSDIR_GET:
   1991    case CIRCUIT_PURPOSE_C_GENERAL:
   1992    case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
   1993    case CIRCUIT_PURPOSE_CONFLUX_LINKED:
   1994      if (circ->build_state->is_internal)
   1995        return;
   1996      description = "requested exit node";
   1997      rs = options->ExcludeExitNodesUnion_;
   1998      break;
   1999    case CIRCUIT_PURPOSE_C_INTRODUCING:
   2000    case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
   2001    case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
   2002    case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
   2003    case CIRCUIT_PURPOSE_S_CONNECT_REND:
   2004    case CIRCUIT_PURPOSE_S_REND_JOINED:
   2005    case CIRCUIT_PURPOSE_TESTING:
   2006      return;
   2007    case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
   2008    case CIRCUIT_PURPOSE_C_REND_READY:
   2009    case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
   2010    case CIRCUIT_PURPOSE_C_REND_JOINED:
   2011      description = "chosen rendezvous point";
   2012      break;
   2013    case CIRCUIT_PURPOSE_CONTROLLER:
   2014      rs = options->ExcludeExitNodesUnion_;
   2015      description = "controller-selected circuit target";
   2016      break;
   2017    }
   2018 
   2019  if (routerset_contains_extendinfo(rs, exit_ei)) {
   2020    /* We should never get here if StrictNodes is set to 1. */
   2021    if (options->StrictNodes) {
   2022      log_warn(LD_BUG, "Using %s '%s' which is listed in ExcludeNodes%s, "
   2023               "even though StrictNodes is set. Please report. "
   2024               "(Circuit purpose: %s)",
   2025               description, extend_info_describe(exit_ei),
   2026               rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
   2027               circuit_purpose_to_string(purpose));
   2028    } else {
   2029      log_warn(LD_CIRC, "Using %s '%s' which is listed in "
   2030               "ExcludeNodes%s, because no better options were available. To "
   2031               "prevent this (and possibly break your Tor functionality), "
   2032               "set the StrictNodes configuration option. "
   2033               "(Circuit purpose: %s)",
   2034               description, extend_info_describe(exit_ei),
   2035               rs==options->ExcludeNodes?"":" or ExcludeExitNodes",
   2036               circuit_purpose_to_string(purpose));
   2037    }
   2038    circuit_log_path(LOG_WARN, LD_CIRC, circ);
   2039  }
   2040 
   2041  return;
   2042 }
   2043 
   2044 /* Return a set of generic CRN_* flags based on <b>state</b>.
   2045 *
   2046 * Called for every position in the circuit. */
   2047 STATIC int
   2048 cpath_build_state_to_crn_flags(const cpath_build_state_t *state)
   2049 {
   2050  router_crn_flags_t flags = 0;
   2051  /* These flags apply to entry, middle, and exit nodes.
   2052   * If a flag only applies to a specific position, it should be checked in
   2053   * that function. */
   2054  if (state->need_uptime)
   2055    flags |= CRN_NEED_UPTIME;
   2056  if (state->need_capacity)
   2057    flags |= CRN_NEED_CAPACITY;
   2058  return flags;
   2059 }
   2060 
   2061 /* Return the CRN_INITIATE_IPV6_EXTEND flag, based on <b>state</b> and
   2062 * <b>cur_len</b>.
   2063 *
   2064 * Only called for middle nodes (for now). Must not be called on single-hop
   2065 * circuits. */
   2066 STATIC int
   2067 cpath_build_state_to_crn_ipv6_extend_flag(const cpath_build_state_t *state,
   2068                                          int cur_len)
   2069 {
   2070  IF_BUG_ONCE(state->desired_path_len < 2)
   2071    return 0;
   2072 
   2073  /* The last node is the relay doing the self-test. So we want to extend over
   2074   * IPv6 from the second-last node. */
   2075  if (state->is_ipv6_selftest && cur_len == state->desired_path_len - 2)
   2076    return CRN_INITIATE_IPV6_EXTEND;
   2077  else
   2078    return 0;
   2079 }
   2080 
   2081 /** Decide a suitable length for circ's cpath, and pick an exit
   2082 * router (or use <b>exit_ei</b> if provided). Store these in the
   2083 * cpath.
   2084 *
   2085 * If <b>is_hs_v3_rp_circuit</b> is set, then this exit should be suitable to
   2086 * be used as an HS v3 rendezvous point.
   2087 *
   2088 * Return 0 if ok, -1 if circuit should be closed. */
   2089 STATIC int
   2090 onion_pick_cpath_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
   2091 {
   2092  cpath_build_state_t *state = circ->build_state;
   2093 
   2094  if (state->onehop_tunnel) {
   2095    log_debug(LD_CIRC, "Launching a one-hop circuit for dir tunnel%s.",
   2096              (hs_service_allow_non_anonymous_connection(get_options()) ?
   2097               ", or intro or rendezvous connection" : ""));
   2098    state->desired_path_len = 1;
   2099  } else {
   2100    int r = new_route_len(circ->base_.purpose, exit_ei, nodelist_get_list());
   2101    if (r < 1) /* must be at least 1 */
   2102      return -1;
   2103    state->desired_path_len = r;
   2104  }
   2105 
   2106  if (exit_ei) { /* the circuit-builder pre-requested one */
   2107    warn_if_last_router_excluded(circ, exit_ei);
   2108    log_info(LD_CIRC,"Using requested exit node '%s'",
   2109             extend_info_describe(exit_ei));
   2110    exit_ei = extend_info_dup(exit_ei);
   2111  } else { /* we have to decide one */
   2112    router_crn_flags_t flags = CRN_NEED_DESC;
   2113    flags |= cpath_build_state_to_crn_flags(state);
   2114    /* Some internal exits are one hop, for example directory connections.
   2115     * (Guards are always direct, middles are never direct.) */
   2116    if (state->onehop_tunnel)
   2117      flags |= CRN_DIRECT_CONN;
   2118    if (state->need_conflux)
   2119      flags |= CRN_CONFLUX;
   2120    const node_t *node =
   2121      choose_good_exit_server(circ, flags, state->is_internal);
   2122    if (!node) {
   2123      log_warn(LD_CIRC,"Failed to choose an exit server");
   2124      return -1;
   2125    }
   2126    exit_ei = extend_info_from_node(node, state->onehop_tunnel,
   2127                /* for_exit_use */
   2128                !state->is_internal && (
   2129                  TO_CIRCUIT(circ)->purpose ==
   2130                  CIRCUIT_PURPOSE_C_GENERAL ||
   2131                  TO_CIRCUIT(circ)->purpose ==
   2132                  CIRCUIT_PURPOSE_CONFLUX_UNLINKED));
   2133    if (BUG(exit_ei == NULL))
   2134      return -1;
   2135  }
   2136  state->chosen_exit = exit_ei;
   2137  return 0;
   2138 }
   2139 
   2140 /** Give <b>circ</b> a new exit destination to <b>exit_ei</b>, and add a
   2141 * hop to the cpath reflecting this. Don't send the next extend cell --
   2142 * the caller will do this if it wants to.
   2143 */
   2144 int
   2145 circuit_append_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
   2146 {
   2147  cpath_build_state_t *state;
   2148  tor_assert(exit_ei);
   2149  tor_assert(circ);
   2150 
   2151  state = circ->build_state;
   2152  tor_assert(state);
   2153  extend_info_free(state->chosen_exit);
   2154  state->chosen_exit = extend_info_dup(exit_ei);
   2155 
   2156  ++circ->build_state->desired_path_len;
   2157  cpath_append_hop(&circ->cpath, exit_ei);
   2158  return 0;
   2159 }
   2160 
   2161 /** Take an open <b>circ</b>, and add a new hop at the end, based on
   2162 * <b>info</b>. Set its state back to CIRCUIT_STATE_BUILDING, and then
   2163 * send the next extend cell to begin connecting to that hop.
   2164 */
   2165 int
   2166 circuit_extend_to_new_exit(origin_circuit_t *circ, extend_info_t *exit_ei)
   2167 {
   2168  int err_reason = 0;
   2169  warn_if_last_router_excluded(circ, exit_ei);
   2170 
   2171  tor_gettimeofday(&circ->base_.timestamp_began);
   2172 
   2173  circuit_append_new_exit(circ, exit_ei);
   2174  circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
   2175  if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
   2176    log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
   2177             extend_info_describe(exit_ei));
   2178    circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
   2179    return -1;
   2180  }
   2181 
   2182  return 0;
   2183 }
   2184 
   2185 /** Return the number of routers in <b>nodes</b> that are currently up and
   2186 * available for building circuits through.
   2187 *
   2188 * If <b>direct</b> is true, only count nodes that are suitable for direct
   2189 * connections. Counts nodes regardless of whether their addresses are
   2190 * preferred.
   2191 */
   2192 MOCK_IMPL(STATIC int,
   2193 count_acceptable_nodes, (const smartlist_t *nodes, int direct))
   2194 {
   2195  int num=0;
   2196  int flags = CRN_NEED_DESC;
   2197 
   2198  if (direct)
   2199    flags |= CRN_DIRECT_CONN;
   2200 
   2201  SMARTLIST_FOREACH_BEGIN(nodes, const node_t *, node) {
   2202    //    log_debug(LD_CIRC,
   2203    //              "Contemplating whether router %d (%s) is a new option.",
   2204    //              i, r->nickname);
   2205    if (!router_can_choose_node(node, flags))
   2206      continue;
   2207    ++num;
   2208  } SMARTLIST_FOREACH_END(node);
   2209 
   2210 //    log_debug(LD_CIRC,"I like %d. num_acceptable_routers now %d.",i, num);
   2211 
   2212  return num;
   2213 }
   2214 
   2215 /**
   2216 * Build the exclude list for vanguard circuits.
   2217 *
   2218 * For vanguard circuits we exclude all the already chosen nodes (including the
   2219 * exit) from being middle hops to prevent the creation of A - B - A subpaths.
   2220 * We also allow the 4th hop to be the same as the guard node so as to not leak
   2221 * guard information to RP/IP/HSDirs.
   2222 *
   2223 * For vanguard circuits, we don't apply any subnet or family restrictions.
   2224 * This is to avoid impossible-to-build circuit paths, or just situations where
   2225 * our earlier guards prevent us from using most of our later ones.
   2226 *
   2227 * The alternative is building the circuit in reverse. Reverse calls to
   2228 * onion_extend_cpath() (ie: select outer hops first) would then have the
   2229 * property that you don't gain information about inner hops by observing
   2230 * outer ones. See https://bugs.torproject.org/tpo/core/tor/24487
   2231 * for this.
   2232 *
   2233 * (Note further that we still exclude the exit to prevent A - B - A
   2234 * at the end of the path. */
   2235 static smartlist_t *
   2236 build_vanguard_middle_exclude_list(uint8_t purpose,
   2237                                   cpath_build_state_t *state,
   2238                                   crypt_path_t *head,
   2239                                   int cur_len)
   2240 {
   2241  smartlist_t *excluded;
   2242  const node_t *r;
   2243  crypt_path_t *cpath;
   2244  int i;
   2245 
   2246  (void) purpose;
   2247 
   2248  excluded = smartlist_new();
   2249 
   2250  /* Add the exit to the exclude list (note that the exit/last hop is always
   2251   * chosen first in circuit_establish_circuit()). */
   2252  if ((r = build_state_get_exit_node(state))) {
   2253    smartlist_add(excluded, (node_t*)r);
   2254  }
   2255 
   2256  /* If we are picking the 4th hop, allow that node to be the guard too.
   2257   * This prevents us from avoiding the Guard for those hops, which
   2258   * gives the adversary information about our guard if they control
   2259   * the RP, IP, or HSDIR. We don't do this check based on purpose
   2260   * because we also want to allow HS_VANGUARDS pre-build circuits
   2261   * to use the guard for that last hop.
   2262   */
   2263  if (cur_len == DEFAULT_ROUTE_LEN+1) {
   2264    /* Skip the first hop for the exclude list below */
   2265    head = head->next;
   2266    cur_len--;
   2267  }
   2268 
   2269  for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
   2270    if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
   2271      smartlist_add(excluded, (node_t*)r);
   2272    }
   2273  }
   2274 
   2275  return excluded;
   2276 }
   2277 
   2278 /**
   2279 * Build a list of nodes to exclude from the choice of this middle
   2280 * hop, based on already chosen nodes.
   2281 */
   2282 static smartlist_t *
   2283 build_middle_exclude_list(const origin_circuit_t *circ,
   2284                          uint8_t purpose,
   2285                          cpath_build_state_t *state,
   2286                          crypt_path_t *head,
   2287                          int cur_len)
   2288 {
   2289  smartlist_t *excluded;
   2290  const node_t *r;
   2291  crypt_path_t *cpath;
   2292  int i;
   2293 
   2294  /** Vanguard circuits have their own path selection rules */
   2295  if (circuit_should_use_vanguards(purpose)) {
   2296    return build_vanguard_middle_exclude_list(purpose, state, head, cur_len);
   2297  }
   2298 
   2299  excluded = smartlist_new();
   2300 
   2301  // Exclude other middles on pending and built conflux circs
   2302  conflux_add_middles_to_exclude_list(circ, excluded);
   2303 
   2304  /* For non-vanguard circuits, add the exit and its family to the exclude list
   2305   * (note that the exit/last hop is always chosen first in
   2306   * circuit_establish_circuit()). */
   2307  if ((r = build_state_get_exit_node(state))) {
   2308    nodelist_add_node_and_family(excluded, r);
   2309  }
   2310 
   2311  /* also exclude all other already chosen nodes and their family */
   2312  for (i = 0, cpath = head; cpath && i < cur_len; ++i, cpath=cpath->next) {
   2313    if ((r = node_get_by_id(cpath->extend_info->identity_digest))) {
   2314      nodelist_add_node_and_family(excluded, r);
   2315    }
   2316  }
   2317 
   2318  return excluded;
   2319 }
   2320 
   2321 /** Return true if we MUST use vanguards for picking this middle node. */
   2322 static int
   2323 middle_node_must_be_vanguard(const or_options_t *options,
   2324                             uint8_t purpose, int cur_len)
   2325 {
   2326  /* If this is not a hidden service circuit, don't use vanguards */
   2327  if (!circuit_purpose_is_hidden_service(purpose)) {
   2328    return 0;
   2329  }
   2330 
   2331  /* Don't even bother if the feature is disabled */
   2332  if (!vanguards_lite_is_enabled()) {
   2333    return 0;
   2334  }
   2335 
   2336  /* If we are a hidden service circuit, always use either vanguards-lite
   2337   * or HSLayer2Nodes for 2nd hop. */
   2338  if (cur_len == 1) {
   2339    return 1;
   2340  }
   2341 
   2342  /* If we have sticky L3 nodes, and this is an L3 pick, use vanguards */
   2343  if (options->HSLayer3Nodes && cur_len == 2) {
   2344    return 1;
   2345  }
   2346 
   2347  return 0;
   2348 }
   2349 
   2350 /** Pick a sticky vanguard middle node or return NULL if not found.
   2351 *  See doc of pick_restricted_middle_node() for argument details. */
   2352 static const node_t *
   2353 pick_vanguard_middle_node(const or_options_t *options,
   2354                          router_crn_flags_t flags, int cur_len,
   2355                          const smartlist_t *excluded)
   2356 {
   2357  const routerset_t *vanguard_routerset = NULL;
   2358  const node_t *node = NULL;
   2359 
   2360  /* Pick the right routerset based on the current hop */
   2361  if (cur_len == 1) {
   2362    vanguard_routerset = options->HSLayer2Nodes ?
   2363      options->HSLayer2Nodes : get_layer2_guards();
   2364  } else if (cur_len == 2) {
   2365    vanguard_routerset = options->HSLayer3Nodes;
   2366  } else {
   2367    /* guaranteed by middle_node_should_be_vanguard() */
   2368    tor_assert_nonfatal_unreached();
   2369    return NULL;
   2370  }
   2371 
   2372  if (BUG(!vanguard_routerset)) {
   2373    return NULL;
   2374  }
   2375 
   2376  node = pick_restricted_middle_node(flags, vanguard_routerset,
   2377                                     options->ExcludeNodes, excluded,
   2378                                     cur_len+1);
   2379 
   2380  if (!node) {
   2381    static ratelim_t pinned_warning_limit = RATELIM_INIT(300);
   2382    log_fn_ratelim(&pinned_warning_limit, LOG_WARN, LD_CIRC,
   2383            "Could not find a node that matches the configured "
   2384            "_HSLayer%dNodes set", cur_len+1);
   2385  }
   2386 
   2387  return node;
   2388 }
   2389 
   2390 /** A helper function used by onion_extend_cpath(). Use <b>purpose</b>
   2391 * and <b>state</b> and the cpath <b>head</b> (currently populated only
   2392 * to length <b>cur_len</b> to decide a suitable middle hop for a
   2393 * circuit. In particular, make sure we don't pick the exit node or its
   2394 * family, and make sure we don't duplicate any previous nodes or their
   2395 * families. */
   2396 static const node_t *
   2397 choose_good_middle_server(const origin_circuit_t * circ,
   2398                          uint8_t purpose,
   2399                          cpath_build_state_t *state,
   2400                          crypt_path_t *head,
   2401                          int cur_len)
   2402 {
   2403  const node_t *choice;
   2404  smartlist_t *excluded;
   2405  const or_options_t *options = get_options();
   2406  router_crn_flags_t flags = CRN_NEED_DESC;
   2407  tor_assert(CIRCUIT_PURPOSE_MIN_ <= purpose &&
   2408             purpose <= CIRCUIT_PURPOSE_MAX_);
   2409 
   2410  log_debug(LD_CIRC, "Contemplating intermediate hop #%d: random choice.",
   2411            cur_len+1);
   2412 
   2413  excluded = build_middle_exclude_list(circ, purpose, state, head, cur_len);
   2414 
   2415  flags |= cpath_build_state_to_crn_flags(state);
   2416  flags |= cpath_build_state_to_crn_ipv6_extend_flag(state, cur_len);
   2417 
   2418  /** If a hidden service circuit wants a specific middle node, pin it. */
   2419  if (middle_node_must_be_vanguard(options, purpose, cur_len)) {
   2420    log_debug(LD_GENERAL, "Picking a sticky node (cur_len = %d)", cur_len);
   2421    choice = pick_vanguard_middle_node(options, flags, cur_len, excluded);
   2422    smartlist_free(excluded);
   2423    return choice;
   2424  }
   2425 
   2426  if (options->MiddleNodes) {
   2427    smartlist_t *sl = smartlist_new();
   2428    routerset_get_all_nodes(sl, options->MiddleNodes,
   2429                            options->ExcludeNodes, 1);
   2430 
   2431    smartlist_subtract(sl, excluded);
   2432 
   2433    choice = node_sl_choose_by_bandwidth(sl, WEIGHT_FOR_MID);
   2434    smartlist_free(sl);
   2435    if (choice) {
   2436      log_fn(LOG_INFO, LD_CIRC, "Chose fixed middle node: %s",
   2437          hex_str(choice->identity, DIGEST_LEN));
   2438    } else {
   2439      log_fn(LOG_NOTICE, LD_CIRC, "Restricted middle not available");
   2440    }
   2441  } else {
   2442    choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
   2443  }
   2444  smartlist_free(excluded);
   2445  return choice;
   2446 }
   2447 
   2448 /** Pick a good entry server for the circuit to be built according to
   2449 * <b>state</b>.  Don't reuse a chosen exit (if any), don't use this
   2450 * router (if we're an OR), and respect firewall settings; if we're
   2451 * configured to use entry guards, return one.
   2452 *
   2453 * Set *<b>guard_state_out</b> to information about the guard that
   2454 * we're selecting, which we'll use later to remember whether the
   2455 * guard worked or not.
   2456 */
   2457 const node_t *
   2458 choose_good_entry_server(const origin_circuit_t *circ,
   2459                         uint8_t purpose, cpath_build_state_t *state,
   2460                         circuit_guard_state_t **guard_state_out)
   2461 {
   2462  const node_t *choice;
   2463  smartlist_t *excluded;
   2464  const or_options_t *options = get_options();
   2465  /* If possible, choose an entry server with a preferred address,
   2466   * otherwise, choose one with an allowed address */
   2467  router_crn_flags_t flags = (CRN_NEED_GUARD|CRN_NEED_DESC|CRN_PREF_ADDR|
   2468                              CRN_DIRECT_CONN);
   2469  const node_t *node;
   2470 
   2471  /* Once we used this function to select a node to be a guard.  We had
   2472   * 'state == NULL' be the signal for that.  But we don't do that any more.
   2473   */
   2474  tor_assert_nonfatal(state);
   2475 
   2476  if (state && options->UseEntryGuards &&
   2477      (purpose != CIRCUIT_PURPOSE_TESTING || options->BridgeRelay)) {
   2478    /* This request is for an entry server to use for a regular circuit,
   2479     * and we use entry guard nodes.  Just return one of the guard nodes.  */
   2480    tor_assert(guard_state_out);
   2481    return guards_choose_guard(circ, state, purpose, guard_state_out);
   2482  }
   2483 
   2484  excluded = smartlist_new();
   2485 
   2486  if (state && (node = build_state_get_exit_node(state))) {
   2487    /* Exclude the exit node from the state, if we have one.  Also exclude its
   2488     * family. */
   2489    nodelist_add_node_and_family(excluded, node);
   2490  }
   2491 
   2492  if (state) {
   2493    flags |= cpath_build_state_to_crn_flags(state);
   2494  }
   2495 
   2496  choice = router_choose_random_node(excluded, options->ExcludeNodes, flags);
   2497  smartlist_free(excluded);
   2498  return choice;
   2499 }
   2500 
   2501 /** Choose a suitable next hop for the circuit <b>circ</b>.
   2502 * Append the hop info to circ->cpath.
   2503 *
   2504 * Return 1 if the path is complete, 0 if we successfully added a hop,
   2505 * and -1 on error.
   2506 */
   2507 STATIC int
   2508 onion_extend_cpath(origin_circuit_t *circ)
   2509 {
   2510  uint8_t purpose = circ->base_.purpose;
   2511  cpath_build_state_t *state = circ->build_state;
   2512  int cur_len = circuit_get_cpath_len(circ);
   2513  extend_info_t *info = NULL;
   2514 
   2515  if (cur_len >= state->desired_path_len) {
   2516    log_debug(LD_CIRC, "Path is complete: %d steps long",
   2517              state->desired_path_len);
   2518    return 1;
   2519  }
   2520 
   2521  log_debug(LD_CIRC, "Path is %d long; we want %d", cur_len,
   2522            state->desired_path_len);
   2523 
   2524  if (cur_len == state->desired_path_len - 1) { /* Picking last node */
   2525    info = extend_info_dup(state->chosen_exit);
   2526  } else if (cur_len == 0) { /* picking first node */
   2527    const node_t *r = choose_good_entry_server(circ, purpose, state,
   2528                                               &circ->guard_state);
   2529    if (r) {
   2530      /* If we're a client, use the preferred address rather than the
   2531         primary address, for potentially connecting to an IPv6 OR
   2532         port. Servers always want the primary (IPv4) address. */
   2533      int client = (server_mode(get_options()) == 0);
   2534      info = extend_info_from_node(r, client, false);
   2535      /* Clients can fail to find an allowed address */
   2536      tor_assert_nonfatal(info || client);
   2537    }
   2538  } else {
   2539    const node_t *r =
   2540      choose_good_middle_server(circ, purpose, state, circ->cpath, cur_len);
   2541    if (r) {
   2542      info = extend_info_from_node(r, 0, false);
   2543    }
   2544  }
   2545 
   2546  if (!info) {
   2547    /* This can happen on first startup, possibly due to insufficient relays
   2548     * downloaded to pick vanguards-lite layer2 nodes, or other ephemeral
   2549     * reasons. It only happens briefly, is hard to reproduce, and then goes
   2550     * away for ever. :/ */
   2551    if (!router_have_minimum_dir_info()) {
   2552       log_info(LD_CIRC,
   2553                "Failed to find node for hop #%d of our path. Discarding "
   2554                "this circuit.", cur_len+1);
   2555    } else {
   2556       log_notice(LD_CIRC,
   2557                 "Failed to find node for hop #%d of our path. Discarding "
   2558                 "this circuit.", cur_len+1);
   2559    }
   2560    return -1;
   2561  }
   2562 
   2563  log_debug(LD_CIRC,"Chose router %s for hop #%d (exit is %s)",
   2564            extend_info_describe(info),
   2565            cur_len+1, build_state_get_exit_nickname(state));
   2566 
   2567  cpath_append_hop(&circ->cpath, info);
   2568  extend_info_free(info);
   2569  return 0;
   2570 }
   2571 
   2572 /** Return the node_t for the chosen exit router in <b>state</b>.
   2573 * If there is no chosen exit, or if we don't know the node_t for
   2574 * the chosen exit, return NULL.
   2575 */
   2576 MOCK_IMPL(const node_t *,
   2577 build_state_get_exit_node,(cpath_build_state_t *state))
   2578 {
   2579  if (!state || !state->chosen_exit)
   2580    return NULL;
   2581  return node_get_by_id(state->chosen_exit->identity_digest);
   2582 }
   2583 
   2584 /** Return the RSA ID digest for the chosen exit router in <b>state</b>.
   2585 * If there is no chosen exit, return NULL.
   2586 */
   2587 const uint8_t *
   2588 build_state_get_exit_rsa_id(cpath_build_state_t *state)
   2589 {
   2590  if (!state || !state->chosen_exit)
   2591    return NULL;
   2592  return (const uint8_t *) state->chosen_exit->identity_digest;
   2593 }
   2594 
   2595 /** Return the nickname for the chosen exit router in <b>state</b>. If
   2596 * there is no chosen exit, or if we don't know the routerinfo_t for the
   2597 * chosen exit, return NULL.
   2598 */
   2599 const char *
   2600 build_state_get_exit_nickname(cpath_build_state_t *state)
   2601 {
   2602  if (!state || !state->chosen_exit)
   2603    return NULL;
   2604  return state->chosen_exit->nickname;
   2605 }
   2606 
   2607 /* Does circ have an onion key which it's allowed to use? */
   2608 int
   2609 circuit_has_usable_onion_key(const origin_circuit_t *circ)
   2610 {
   2611  tor_assert(circ);
   2612  tor_assert(circ->cpath);
   2613  tor_assert(circ->cpath->extend_info);
   2614  return extend_info_supports_ntor(circ->cpath->extend_info);
   2615 }
   2616 
   2617 /** Find the circuits that are waiting to find out whether their guards are
   2618 * usable, and if any are ready to become usable, mark them open and try
   2619 * attaching streams as appropriate. */
   2620 void
   2621 circuit_upgrade_circuits_from_guard_wait(void)
   2622 {
   2623  smartlist_t *to_upgrade =
   2624    circuit_find_circuits_to_upgrade_from_guard_wait();
   2625 
   2626  if (to_upgrade == NULL)
   2627    return;
   2628 
   2629  log_info(LD_GUARD, "Upgrading %d circuits from 'waiting for better guard' "
   2630           "to 'open'.", smartlist_len(to_upgrade));
   2631 
   2632  SMARTLIST_FOREACH_BEGIN(to_upgrade, origin_circuit_t *, circ) {
   2633    circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
   2634    circuit_has_opened(circ);
   2635  } SMARTLIST_FOREACH_END(circ);
   2636 
   2637  smartlist_free(to_upgrade);
   2638 }
   2639 
   2640 // TODO: Find a better place to declare this; it's duplicated in
   2641 // onion_crypto.c
   2642 #define EXT_TYPE_SUBPROTO 3
   2643 
   2644 /** Add a request for the CGO subprotocol capability to ext.
   2645 *
   2646 * NOTE: If we need to support other subprotocol extensions,
   2647 * do not add separate functions! Instead rename this function
   2648 * and adapt it as appropriate.
   2649 */
   2650 static int
   2651 build_cgo_subproto_request(trn_extension_t *ext)
   2652 {
   2653  trn_extension_field_t *fld = NULL;
   2654  trn_subproto_request_t *req = NULL;
   2655  trn_subproto_request_ext_t *req_ext = NULL;
   2656  int r = 0;
   2657 
   2658  fld = trn_extension_field_new();
   2659  req_ext = trn_subproto_request_ext_new();
   2660 
   2661  req = trn_subproto_request_new();
   2662  req->protocol_id = PRT_RELAY;
   2663  req->proto_cap_number = PROTOVER_RELAY_CRYPT_CGO;
   2664  trn_subproto_request_ext_add_reqs(req_ext, req);
   2665  req = NULL; // prevent double-free
   2666 
   2667  // TODO: If we add other capabilities here, we need to make
   2668  // sure they are correctly sorted.
   2669 
   2670  ssize_t len = trn_subproto_request_ext_encoded_len(req_ext);
   2671  if (BUG(len<0))
   2672    goto err;
   2673  if (BUG(len > UINT8_MAX))
   2674    goto err;
   2675 
   2676  trn_extension_field_setlen_field(fld, len);
   2677  trn_extension_field_set_field_type(fld, EXT_TYPE_SUBPROTO);
   2678  trn_extension_field_set_field_len(fld, len);
   2679  uint8_t *out = trn_extension_field_getarray_field(fld);
   2680  ssize_t len2 = trn_subproto_request_ext_encode(out, len, req_ext);
   2681  if (BUG(len != len2))
   2682    goto err;
   2683 
   2684  trn_extension_add_fields(ext, fld);
   2685  fld = NULL; // prevent double-free
   2686 
   2687  // We succeeded!
   2688  r = 0;
   2689 
   2690 err:
   2691  trn_subproto_request_ext_free(req_ext);
   2692  trn_subproto_request_free(req);
   2693  trn_extension_field_free(fld);
   2694 
   2695  return r;
   2696 }
   2697 
   2698 /** Helper: Comparison function to sort extensions. */
   2699 static int
   2700 ext_cmp(const void *a, const void *b)
   2701 {
   2702  const trn_extension_field_t *fa = *(trn_extension_field_t **)a;
   2703  const trn_extension_field_t *fb = *(trn_extension_field_t **)b;
   2704  uint8_t ta = trn_extension_field_get_field_type(fa);
   2705  uint8_t tb = trn_extension_field_get_field_type(fb);
   2706  if (ta < tb)
   2707    return -1;
   2708  else if (ta == tb)
   2709    return 0;
   2710  else
   2711    return 1;
   2712 }
   2713 
   2714 /**
   2715 * Try to generate a circuit-negotiation message for communication with a
   2716 * given relay.  Assumes we are using ntor v3, or some later version that
   2717 * supports parameter negotiatoin.
   2718 *
   2719 * On success, return 0 and pass back a message in the `out` parameters.
   2720 * Otherwise, return -1.
   2721 **/
   2722 int
   2723 client_circ_negotiation_message(const extend_info_t *ei,
   2724                                uint8_t **msg_out,
   2725                                size_t *msg_len_out,
   2726                                circuit_params_t *params_out)
   2727 {
   2728  tor_assert(ei && msg_out && msg_len_out && params_out);
   2729  bool cc_enabled = false;
   2730 
   2731  *msg_out = NULL;
   2732 
   2733  trn_extension_t *ext = trn_extension_new();
   2734 
   2735  if (ei->exit_supports_congestion_control &&
   2736      congestion_control_enabled()) {
   2737    if (congestion_control_build_ext_request(ext) < 0) {
   2738      goto err;
   2739    }
   2740    cc_enabled = true;
   2741  }
   2742 
   2743  if (cc_enabled && ei->enable_cgo) {
   2744    if (build_cgo_subproto_request(ext) < 0) {
   2745      goto err;
   2746    }
   2747    params_out->cell_fmt = RELAY_CELL_FORMAT_V1;
   2748    params_out->crypto_alg = RELAY_CRYPTO_ALG_CGO_CLIENT;
   2749  }
   2750 
   2751  size_t n_fields = trn_extension_getlen_fields(ext);
   2752  qsort(trn_extension_getarray_fields(ext),
   2753        n_fields, sizeof(trn_extension_field_t *),
   2754        ext_cmp);
   2755 
   2756  trn_extension_set_num(ext, n_fields);
   2757 
   2758  ssize_t total_len = trn_extension_encoded_len(ext);
   2759  if (BUG(total_len < 0))
   2760    goto err;
   2761 
   2762  *msg_out = tor_malloc_zero(total_len);
   2763  *msg_len_out = total_len;
   2764  if (BUG(trn_extension_encode(*msg_out, total_len, ext) < 0)) {
   2765    goto err;
   2766  }
   2767  trn_extension_free(ext);
   2768 
   2769  return 0;
   2770 err:
   2771  trn_extension_free(ext);
   2772  tor_free(*msg_out);
   2773  return -1;
   2774 }