tor

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

connection_or.c (82748B)


      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 connection_or.c
      9 * \brief Functions to handle OR connections, TLS handshaking, and
     10 * cells on the network.
     11 *
     12 * An or_connection_t is a subtype of connection_t (as implemented in
     13 * connection.c) that uses a TLS connection to send and receive cells on the
     14 * Tor network. (By sending and receiving cells connection_or.c, it cooperates
     15 * with channeltls.c to implement a the channel interface of channel.c.)
     16 *
     17 * Every OR connection has an underlying tortls_t object (as implemented in
     18 * tortls.c) which it uses as its TLS stream.  It is responsible for
     19 * sending and receiving cells over that TLS.
     20 *
     21 * This module also implements the client side of the v3 (and greater) Tor
     22 * link handshake.
     23 **/
     24 #include "core/or/or.h"
     25 #include "feature/client/bridges.h"
     26 #include "lib/buf/buffers.h"
     27 /*
     28 * Define this so we get channel internal functions, since we're implementing
     29 * part of a subclass (channel_tls_t).
     30 */
     31 #define CHANNEL_OBJECT_PRIVATE
     32 #define CONNECTION_OR_PRIVATE
     33 #define ORCONN_EVENT_PRIVATE
     34 #include "core/or/channel.h"
     35 #include "core/or/channeltls.h"
     36 #include "core/or/circuitbuild.h"
     37 #include "core/or/circuitlist.h"
     38 #include "core/or/circuitstats.h"
     39 #include "core/or/command.h"
     40 #include "app/config/config.h"
     41 #include "core/mainloop/connection.h"
     42 #include "core/or/connection_or.h"
     43 #include "feature/relay/relay_handshake.h"
     44 #include "feature/control/control_events.h"
     45 #include "lib/crypt_ops/crypto_util.h"
     46 #include "feature/dirauth/reachability.h"
     47 #include "feature/client/entrynodes.h"
     48 #include "lib/geoip/geoip.h"
     49 #include "core/mainloop/mainloop.h"
     50 #include "trunnel/netinfo.h"
     51 #include "feature/nodelist/microdesc.h"
     52 #include "feature/nodelist/networkstatus.h"
     53 #include "feature/nodelist/nodelist.h"
     54 #include "core/proto/proto_cell.h"
     55 #include "core/or/reasons.h"
     56 #include "core/or/relay.h"
     57 #include "feature/rend/rendcommon.h"
     58 #include "feature/stats/rephist.h"
     59 #include "feature/relay/router.h"
     60 #include "feature/relay/routerkeys.h"
     61 #include "feature/relay/routermode.h"
     62 #include "feature/nodelist/dirlist.h"
     63 #include "feature/nodelist/routerlist.h"
     64 #include "feature/relay/ext_orport.h"
     65 #include "core/or/scheduler.h"
     66 #include "feature/nodelist/torcert.h"
     67 #include "core/or/channelpadding.h"
     68 #include "core/or/congestion_control_common.h"
     69 #include "feature/dirauth/authmode.h"
     70 #include "feature/hs/hs_service.h"
     71 
     72 #include "core/or/cell_st.h"
     73 #include "core/or/cell_queue_st.h"
     74 #include "core/or/or_connection_st.h"
     75 #include "core/or/or_handshake_certs_st.h"
     76 #include "core/or/or_handshake_state_st.h"
     77 #include "app/config/or_state_st.h"
     78 #include "feature/nodelist/routerinfo_st.h"
     79 #include "core/or/var_cell_st.h"
     80 #include "lib/crypt_ops/crypto_format.h"
     81 
     82 #include "lib/tls/tortls.h"
     83 
     84 #include "core/or/orconn_event.h"
     85 
     86 static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
     87 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
     88 
     89 static unsigned int
     90 connection_or_is_bad_for_new_circs(or_connection_t *or_conn);
     91 static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
     92 
     93 static void connection_or_check_canonicity(or_connection_t *conn,
     94                                           int started_here);
     95 
     96 /**************************************************************/
     97 
     98 /**
     99 * Cast a `connection_t *` to an `or_connection_t *`.
    100 *
    101 * Exit with an assertion failure if the input is not an `or_connection_t`.
    102 **/
    103 or_connection_t *
    104 TO_OR_CONN(connection_t *c)
    105 {
    106  tor_assert(c->magic == OR_CONNECTION_MAGIC);
    107  return DOWNCAST(or_connection_t, c);
    108 }
    109 
    110 /**
    111 * Cast a `const connection_t *` to a `const or_connection_t *`.
    112 *
    113 * Exit with an assertion failure if the input is not an `or_connection_t`.
    114 **/
    115 const or_connection_t *
    116 CONST_TO_OR_CONN(const connection_t *c)
    117 {
    118  return TO_OR_CONN((connection_t *)c);
    119 }
    120 
    121 /** Clear clear conn->identity_digest and update other data
    122 * structures as appropriate.*/
    123 void
    124 connection_or_clear_identity(or_connection_t *conn)
    125 {
    126  tor_assert(conn);
    127  memset(conn->identity_digest, 0, DIGEST_LEN);
    128 }
    129 
    130 /** Clear all identities in OR conns.*/
    131 void
    132 connection_or_clear_identity_map(void)
    133 {
    134  smartlist_t *conns = get_connection_array();
    135  SMARTLIST_FOREACH(conns, connection_t *, conn,
    136  {
    137    if (conn->type == CONN_TYPE_OR) {
    138      connection_or_clear_identity(TO_OR_CONN(conn));
    139    }
    140  });
    141 }
    142 
    143 /** Change conn->identity_digest to digest, and add conn into
    144 * the appropriate digest maps.
    145 *
    146 * NOTE that this function only allows two kinds of transitions: from
    147 * unset identity to set identity, and from idempotent re-settings
    148 * of the same identity.  It's not allowed to clear an identity or to
    149 * change an identity.  Return 0 on success, and -1 if the transition
    150 * is not allowed.
    151 **/
    152 static void
    153 connection_or_set_identity_digest(or_connection_t *conn,
    154                                  const char *rsa_digest,
    155                                  const ed25519_public_key_t *ed_id)
    156 {
    157  channel_t *chan = NULL;
    158  tor_assert(conn);
    159  tor_assert(rsa_digest);
    160 
    161  if (conn->chan)
    162    chan = TLS_CHAN_TO_BASE(conn->chan);
    163 
    164  log_info(LD_HANDSHAKE, "Set identity digest for %s at %p: %s %s.",
    165           connection_describe(TO_CONN(conn)),
    166           conn,
    167           hex_str(rsa_digest, DIGEST_LEN),
    168           ed25519_fmt(ed_id));
    169  log_info(LD_HANDSHAKE, "   (Previously: %s %s)",
    170           hex_str(conn->identity_digest, DIGEST_LEN),
    171           chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
    172 
    173  const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
    174  const int ed_id_was_set =
    175    chan && !ed25519_public_key_is_zero(&chan->ed25519_identity);
    176  const int new_ed_id_is_set =
    177    (ed_id && !ed25519_public_key_is_zero(ed_id));
    178  const int rsa_changed =
    179    tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
    180  const int ed_changed = bool_neq(ed_id_was_set, new_ed_id_is_set) ||
    181    (ed_id_was_set && new_ed_id_is_set && chan &&
    182     !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
    183 
    184  if (BUG(rsa_changed && rsa_id_was_set))
    185    return;
    186  if (BUG(ed_changed && ed_id_was_set))
    187    return;
    188 
    189  if (!rsa_changed && !ed_changed)
    190    return;
    191 
    192  /* If the identity was set previously, remove the old mapping. */
    193  if (rsa_id_was_set) {
    194    connection_or_clear_identity(conn);
    195    if (chan)
    196      channel_clear_identity_digest(chan);
    197  }
    198 
    199  memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
    200 
    201  /* If we're initializing the IDs to zero, don't add a mapping yet. */
    202  if (tor_digest_is_zero(rsa_digest) && !new_ed_id_is_set)
    203    return;
    204 
    205  /* Deal with channels */
    206  if (chan)
    207    channel_set_identity_digest(chan, rsa_digest, ed_id);
    208 }
    209 
    210 /**
    211 * Return the Ed25519 identity of the peer for this connection (if any).
    212 *
    213 * Note that this ID may not be the _actual_ identity for the peer if
    214 * authentication is not complete.
    215 **/
    216 const struct ed25519_public_key_t *
    217 connection_or_get_alleged_ed25519_id(const or_connection_t *conn)
    218 {
    219  if (conn && conn->chan) {
    220    const channel_t *chan = NULL;
    221    chan = TLS_CHAN_TO_BASE(conn->chan);
    222    if (!ed25519_public_key_is_zero(&chan->ed25519_identity)) {
    223      return &chan->ed25519_identity;
    224    }
    225  }
    226 
    227  return NULL;
    228 }
    229 
    230 /**************************************************************/
    231 
    232 /** Map from a string describing what a non-open OR connection was doing when
    233 * failed, to an intptr_t describing the count of connections that failed that
    234 * way.  Note that the count is stored _as_ the pointer.
    235 */
    236 static strmap_t *broken_connection_counts;
    237 
    238 /** If true, do not record information in <b>broken_connection_counts</b>. */
    239 static int disable_broken_connection_counts = 0;
    240 
    241 /** Record that an OR connection failed in <b>state</b>. */
    242 static void
    243 note_broken_connection(const char *state)
    244 {
    245  void *ptr;
    246  intptr_t val;
    247  if (disable_broken_connection_counts)
    248    return;
    249 
    250  if (!broken_connection_counts)
    251    broken_connection_counts = strmap_new();
    252 
    253  ptr = strmap_get(broken_connection_counts, state);
    254  val = (intptr_t)ptr;
    255  val++;
    256  ptr = (void*)val;
    257  strmap_set(broken_connection_counts, state, ptr);
    258 }
    259 
    260 /** Forget all recorded states for failed connections.  If
    261 * <b>stop_recording</b> is true, don't record any more. */
    262 void
    263 clear_broken_connection_map(int stop_recording)
    264 {
    265  if (broken_connection_counts)
    266    strmap_free(broken_connection_counts, NULL);
    267  broken_connection_counts = NULL;
    268  if (stop_recording)
    269    disable_broken_connection_counts = 1;
    270 }
    271 
    272 /** Write a detailed description the state of <b>orconn</b> into the
    273 * <b>buflen</b>-byte buffer at <b>buf</b>.  This description includes not
    274 * only the OR-conn level state but also the TLS state.  It's useful for
    275 * diagnosing broken handshakes. */
    276 static void
    277 connection_or_get_state_description(or_connection_t *orconn,
    278                                    char *buf, size_t buflen)
    279 {
    280  connection_t *conn = TO_CONN(orconn);
    281  const char *conn_state;
    282  char tls_state[256];
    283 
    284  tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
    285 
    286  conn_state = conn_state_to_string(conn->type, conn->state);
    287  tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
    288 
    289  tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
    290 }
    291 
    292 /** Record the current state of <b>orconn</b> as the state of a broken
    293 * connection. */
    294 static void
    295 connection_or_note_state_when_broken(or_connection_t *orconn)
    296 {
    297  char buf[256];
    298  if (disable_broken_connection_counts)
    299    return;
    300  connection_or_get_state_description(orconn, buf, sizeof(buf));
    301  log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
    302  note_broken_connection(buf);
    303 }
    304 
    305 /** Helper type used to sort connection states and find the most frequent. */
    306 typedef struct broken_state_count_t {
    307  intptr_t count;
    308  const char *state;
    309 } broken_state_count_t;
    310 
    311 /** Helper function used to sort broken_state_count_t by frequency. */
    312 static int
    313 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
    314 {
    315  const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
    316  if (b->count < a->count)
    317    return -1;
    318  else if (b->count == a->count)
    319    return 0;
    320  else
    321    return 1;
    322 }
    323 
    324 /** Upper limit on the number of different states to report for connection
    325 * failure. */
    326 #define MAX_REASONS_TO_REPORT 10
    327 
    328 /** Report a list of the top states for failed OR connections at log level
    329 * <b>severity</b>, in log domain <b>domain</b>. */
    330 void
    331 connection_or_report_broken_states(int severity, int domain)
    332 {
    333  int total = 0;
    334  smartlist_t *items;
    335 
    336  if (!broken_connection_counts || disable_broken_connection_counts)
    337    return;
    338 
    339  items = smartlist_new();
    340  STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
    341    broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
    342    c->count = (intptr_t)countptr;
    343    total += (int)c->count;
    344    c->state = state;
    345    smartlist_add(items, c);
    346  } STRMAP_FOREACH_END;
    347 
    348  smartlist_sort(items, broken_state_count_compare);
    349 
    350  tor_log(severity, domain, "%d connections have failed%s", total,
    351      smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
    352 
    353  SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
    354    if (c_sl_idx > MAX_REASONS_TO_REPORT)
    355      break;
    356    tor_log(severity, domain,
    357        " %d connections died in state %s", (int)c->count, c->state);
    358  } SMARTLIST_FOREACH_END(c);
    359 
    360  SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
    361  smartlist_free(items);
    362 }
    363 
    364 /**
    365 * Helper function to publish an OR connection status event
    366 *
    367 * Publishes a messages to subscribers of ORCONN messages, and sends
    368 * the control event.
    369 **/
    370 void
    371 connection_or_event_status(or_connection_t *conn, or_conn_status_event_t tp,
    372                           int reason)
    373 {
    374  orconn_status_msg_t *msg = tor_malloc(sizeof(*msg));
    375 
    376  msg->gid = conn->base_.global_identifier;
    377  msg->status = tp;
    378  msg->reason = reason;
    379  orconn_status_publish(msg);
    380  control_event_or_conn_status(conn, tp, reason);
    381 }
    382 
    383 /**
    384 * Helper function to publish a state change message
    385 *
    386 * connection_or_change_state() calls this to notify subscribers about
    387 * a change of an OR connection state.
    388 **/
    389 static void
    390 connection_or_state_publish(const or_connection_t *conn, uint8_t state)
    391 {
    392  orconn_state_msg_t *msg = tor_malloc(sizeof(*msg));
    393 
    394  msg->gid = conn->base_.global_identifier;
    395  if (conn->is_pt) {
    396    /* Do extra decoding because conn->proxy_type indicates the proxy
    397     * protocol that tor uses to talk with the transport plugin,
    398     * instead of PROXY_PLUGGABLE. */
    399    tor_assert_nonfatal(conn->proxy_type != PROXY_NONE);
    400    msg->proxy_type = PROXY_PLUGGABLE;
    401  } else {
    402    msg->proxy_type = conn->proxy_type;
    403  }
    404  msg->state = state;
    405  if (conn->chan) {
    406    msg->chan = TLS_CHAN_TO_BASE(conn->chan)->global_identifier;
    407  } else {
    408    msg->chan = 0;
    409  }
    410  orconn_state_publish(msg);
    411 }
    412 
    413 /** Call this to change or_connection_t states, so the owning channel_tls_t can
    414 * be notified.
    415 */
    416 MOCK_IMPL(void,
    417 connection_or_change_state,(or_connection_t *conn, uint8_t state))
    418 {
    419  tor_assert(conn);
    420 
    421  conn->base_.state = state;
    422 
    423  connection_or_state_publish(conn, state);
    424  if (conn->chan)
    425    channel_tls_handle_state_change_on_orconn(conn->chan, conn, state);
    426 }
    427 
    428 /** Return the number of circuits using an or_connection_t; this used to
    429 * be an or_connection_t field, but it got moved to channel_t and we
    430 * shouldn't maintain two copies. */
    431 MOCK_IMPL(int,
    432 connection_or_get_num_circuits, (or_connection_t *conn))
    433 {
    434  tor_assert(conn);
    435 
    436  if (conn->chan) {
    437    return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
    438  } else return 0;
    439 }
    440 
    441 /**************************************************************/
    442 
    443 /** Pack the cell_t host-order structure <b>src</b> into network-order
    444 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
    445 * wire format.
    446 *
    447 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
    448 * should set it or clear it as appropriate.
    449 */
    450 void
    451 cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
    452 {
    453  char *dest = dst->body;
    454  if (wide_circ_ids) {
    455    set_uint32(dest, htonl(src->circ_id));
    456    dest += 4;
    457  } else {
    458    /* Clear the last two bytes of dest, in case we can accidentally
    459     * send them to the network somehow. */
    460    memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
    461    set_uint16(dest, htons(src->circ_id));
    462    dest += 2;
    463  }
    464  set_uint8(dest, src->command);
    465  memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
    466 }
    467 
    468 /** Unpack the network-order buffer <b>src</b> into a host-order
    469 * cell_t structure <b>dest</b>.
    470 */
    471 static void
    472 cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
    473 {
    474  if (wide_circ_ids) {
    475    dest->circ_id = ntohl(get_uint32(src));
    476    src += 4;
    477  } else {
    478    dest->circ_id = ntohs(get_uint16(src));
    479    src += 2;
    480  }
    481  dest->command = get_uint8(src);
    482  memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
    483 }
    484 
    485 /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
    486 * bytes of <b>hdr_out</b>. Returns number of bytes used. */
    487 int
    488 var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
    489 {
    490  int r;
    491  if (wide_circ_ids) {
    492    set_uint32(hdr_out, htonl(cell->circ_id));
    493    hdr_out += 4;
    494    r = VAR_CELL_MAX_HEADER_SIZE;
    495  } else {
    496    set_uint16(hdr_out, htons(cell->circ_id));
    497    hdr_out += 2;
    498    r = VAR_CELL_MAX_HEADER_SIZE - 2;
    499  }
    500  set_uint8(hdr_out, cell->command);
    501  set_uint16(hdr_out+1, htons(cell->payload_len));
    502  return r;
    503 }
    504 
    505 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
    506 * payload space. */
    507 var_cell_t *
    508 var_cell_new(uint16_t payload_len)
    509 {
    510  size_t size = offsetof(var_cell_t, payload) + payload_len;
    511  var_cell_t *cell = tor_malloc_zero(size);
    512  cell->payload_len = payload_len;
    513  cell->command = 0;
    514  cell->circ_id = 0;
    515  return cell;
    516 }
    517 
    518 /**
    519 * Copy a var_cell_t
    520 */
    521 var_cell_t *
    522 var_cell_copy(const var_cell_t *src)
    523 {
    524  var_cell_t *copy = NULL;
    525  size_t size = 0;
    526 
    527  if (src != NULL) {
    528    size = offsetof(var_cell_t, payload) + src->payload_len;
    529    copy = tor_malloc_zero(size);
    530    copy->payload_len = src->payload_len;
    531    copy->command = src->command;
    532    copy->circ_id = src->circ_id;
    533    memcpy(copy->payload, src->payload, copy->payload_len);
    534  }
    535 
    536  return copy;
    537 }
    538 
    539 /** Release all space held by <b>cell</b>. */
    540 void
    541 var_cell_free_(var_cell_t *cell)
    542 {
    543  tor_free(cell);
    544 }
    545 
    546 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
    547 int
    548 connection_or_reached_eof(or_connection_t *conn)
    549 {
    550  tor_assert(conn);
    551 
    552  log_info(LD_OR,"OR connection reached EOF. Closing.");
    553  connection_or_close_normally(conn, 1);
    554 
    555  return 0;
    556 }
    557 
    558 /** Handle any new bytes that have come in on connection <b>conn</b>.
    559 * If conn is in 'open' state, hand it to
    560 * connection_or_process_cells_from_inbuf()
    561 * (else do nothing).
    562 */
    563 int
    564 connection_or_process_inbuf(or_connection_t *conn)
    565 {
    566  int ret = 0;
    567  tor_assert(conn);
    568 
    569  switch (conn->base_.state) {
    570    case OR_CONN_STATE_PROXY_HANDSHAKING:
    571      ret = connection_read_proxy_handshake(TO_CONN(conn));
    572 
    573      /* start TLS after handshake completion, or deal with error */
    574      if (ret == 1) {
    575        tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
    576        if (buf_datalen(conn->base_.inbuf) != 0) {
    577          log_fn(LOG_PROTOCOL_WARN, LD_NET, "Found leftover (%d bytes) "
    578                 "when transitioning from PROXY_HANDSHAKING state on %s: "
    579                 "closing.",
    580                 (int)buf_datalen(conn->base_.inbuf),
    581                 connection_describe(TO_CONN(conn)));
    582          connection_or_close_for_error(conn, 0);
    583          return -1;
    584        }
    585        if (connection_tls_start_handshake(conn, 0) < 0)
    586          ret = -1;
    587        /* Touch the channel's active timestamp if there is one */
    588        if (conn->chan)
    589          channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
    590      }
    591      if (ret < 0) {
    592        connection_or_close_for_error(conn, 0);
    593      }
    594 
    595      return ret;
    596    case OR_CONN_STATE_OPEN:
    597    case OR_CONN_STATE_SERVER_VERSIONS_WAIT:
    598    case OR_CONN_STATE_OR_HANDSHAKING_V3:
    599      return connection_or_process_cells_from_inbuf(conn);
    600    default:
    601      break; /* don't do anything */
    602  }
    603 
    604  /* This check makes sure that we don't have any data on the inbuf if we're
    605   * doing our TLS handshake: if we did, they were probably put there by a
    606   * SOCKS proxy trying to trick us into accepting unauthenticated data.
    607   */
    608  if (buf_datalen(conn->base_.inbuf) != 0) {
    609    log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated data (%d bytes) "
    610           "on non-open %s; closing.",
    611           (int)buf_datalen(conn->base_.inbuf),
    612           connection_describe(TO_CONN(conn)));
    613    connection_or_close_for_error(conn, 0);
    614    ret = -1;
    615  }
    616 
    617  return ret;
    618 }
    619 
    620 /** Called whenever we have flushed some data on an or_conn: add more data
    621 * from active circuits. */
    622 int
    623 connection_or_flushed_some(or_connection_t *conn)
    624 {
    625  size_t datalen;
    626 
    627  /* Update the channel's active timestamp if there is one */
    628  if (conn->chan)
    629    channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
    630 
    631  /* If we're under the low water mark, add cells until we're just over the
    632   * high water mark. */
    633  datalen = connection_get_outbuf_len(TO_CONN(conn));
    634  if (datalen < or_conn_lowwatermark()) {
    635    /* Let the scheduler know */
    636    scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
    637  }
    638 
    639  return 0;
    640 }
    641 
    642 /** This is for channeltls.c to ask how many cells we could accept if
    643 * they were available. */
    644 ssize_t
    645 connection_or_num_cells_writeable(or_connection_t *conn)
    646 {
    647  size_t datalen, cell_network_size;
    648  ssize_t n = 0;
    649 
    650  tor_assert(conn);
    651 
    652  /*
    653   * If we're under the high water mark, we're potentially
    654   * writeable; note this is different from the calculation above
    655   * used to trigger when to start writing after we've stopped.
    656   */
    657  datalen = connection_get_outbuf_len(TO_CONN(conn));
    658  if (datalen < or_conn_highwatermark()) {
    659    cell_network_size = get_cell_network_size(conn->wide_circ_ids);
    660    n = CEIL_DIV(or_conn_highwatermark() - datalen, cell_network_size);
    661  }
    662 
    663  return n;
    664 }
    665 
    666 /** Connection <b>conn</b> has finished writing and has no bytes left on
    667 * its outbuf.
    668 *
    669 * Otherwise it's in state "open": stop writing and return.
    670 *
    671 * If <b>conn</b> is broken, mark it for close and return -1, else
    672 * return 0.
    673 */
    674 int
    675 connection_or_finished_flushing(or_connection_t *conn)
    676 {
    677  tor_assert(conn);
    678  assert_connection_ok(TO_CONN(conn),0);
    679 
    680  switch (conn->base_.state) {
    681    case OR_CONN_STATE_PROXY_HANDSHAKING:
    682      /* PROXY_HAPROXY gets connected by receiving an ack. */
    683      if (conn->proxy_type == PROXY_HAPROXY) {
    684        tor_assert(TO_CONN(conn)->proxy_state == PROXY_HAPROXY_WAIT_FOR_FLUSH);
    685        IF_BUG_ONCE(buf_datalen(TO_CONN(conn)->inbuf) != 0) {
    686          /* This should be impossible; we're not even reading. */
    687          connection_or_close_for_error(conn, 0);
    688          return -1;
    689        }
    690        TO_CONN(conn)->proxy_state = PROXY_CONNECTED;
    691 
    692        if (connection_tls_start_handshake(conn, 0) < 0) {
    693          /* TLS handshaking error of some kind. */
    694          connection_or_close_for_error(conn, 0);
    695          return -1;
    696        }
    697        break;
    698      }
    699      break;
    700    case OR_CONN_STATE_OPEN:
    701    case OR_CONN_STATE_OR_HANDSHAKING_V3:
    702      break;
    703    default:
    704      log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
    705      tor_fragile_assert();
    706      return -1;
    707  }
    708 
    709  /* Update the channel's active timestamp if there is one */
    710  if (conn->chan)
    711    channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
    712 
    713  return 0;
    714 }
    715 
    716 /** Connected handler for OR connections: begin the TLS handshake.
    717 */
    718 int
    719 connection_or_finished_connecting(or_connection_t *or_conn)
    720 {
    721  const int proxy_type = or_conn->proxy_type;
    722  connection_t *conn;
    723 
    724  tor_assert(or_conn);
    725  conn = TO_CONN(or_conn);
    726  tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
    727 
    728  log_debug(LD_HANDSHAKE,"connect finished for %s",
    729            connection_describe(conn));
    730 
    731  if (proxy_type != PROXY_NONE) {
    732    /* start proxy handshake */
    733    if (connection_proxy_connect(conn, proxy_type) < 0) {
    734      connection_or_close_for_error(or_conn, 0);
    735      return -1;
    736    }
    737 
    738    connection_or_change_state(or_conn, OR_CONN_STATE_PROXY_HANDSHAKING);
    739    connection_start_reading(conn);
    740 
    741    return 0;
    742  }
    743 
    744  if (connection_tls_start_handshake(or_conn, 0) < 0) {
    745    /* TLS handshaking error of some kind. */
    746    connection_or_close_for_error(or_conn, 0);
    747    return -1;
    748  }
    749  return 0;
    750 }
    751 
    752 /** Called when we're about to finally unlink and free an OR connection:
    753 * perform necessary accounting and cleanup */
    754 void
    755 connection_or_about_to_close(or_connection_t *or_conn)
    756 {
    757  connection_t *conn = TO_CONN(or_conn);
    758 
    759  /* Tell the controlling channel we're closed */
    760  if (or_conn->chan) {
    761    channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
    762    /*
    763     * NULL this out because the channel might hang around a little
    764     * longer before channel_run_cleanup() gets it.
    765     */
    766    or_conn->chan->conn = NULL;
    767    or_conn->chan = NULL;
    768  }
    769 
    770  /* Remember why we're closing this connection. */
    771  if (conn->state != OR_CONN_STATE_OPEN) {
    772    /* now mark things down as needed */
    773    if (connection_or_nonopen_was_started_here(or_conn)) {
    774      const or_options_t *options = get_options();
    775      connection_or_note_state_when_broken(or_conn);
    776      /* Tell the new guard API about the channel failure */
    777      entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
    778      if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
    779        int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
    780        connection_or_event_status(or_conn, OR_CONN_EVENT_FAILED,
    781                                   reason);
    782        if (!authdir_mode_tests_reachability(options)) {
    783          const char *warning = NULL;
    784          if (reason == END_OR_CONN_REASON_TLS_ERROR && or_conn->tls) {
    785            warning = tor_tls_get_last_error_msg(or_conn->tls);
    786          }
    787          if (warning == NULL) {
    788            warning = orconn_end_reason_to_control_string(reason);
    789          }
    790          control_event_bootstrap_prob_or(warning, reason, or_conn);
    791        }
    792      }
    793    }
    794  } else if (conn->hold_open_until_flushed) {
    795    /* We only set hold_open_until_flushed when we're intentionally
    796     * closing a connection. */
    797    connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
    798                tls_error_to_orconn_end_reason(or_conn->tls_error));
    799  } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
    800    connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
    801                tls_error_to_orconn_end_reason(or_conn->tls_error));
    802  } else {
    803    /* Normal close, we notify of a done connection. */
    804    connection_or_event_status(or_conn, OR_CONN_EVENT_CLOSED,
    805                               END_OR_CONN_REASON_DONE);
    806  }
    807 }
    808 
    809 /** Return 1 if identity digest <b>id_digest</b> is known to be a
    810 * currently or recently running relay. Otherwise return 0. */
    811 int
    812 connection_or_digest_is_known_relay(const char *id_digest)
    813 {
    814  if (router_get_consensus_status_by_id(id_digest))
    815    return 1; /* It's in the consensus: "yes" */
    816  if (router_get_by_id_digest(id_digest))
    817    return 1; /* Not in the consensus, but we have a descriptor for
    818               * it. Probably it was in a recent consensus. "Yes". */
    819  return 0;
    820 }
    821 
    822 /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
    823 * relay, we will rely on the global read and write buckets, so give it
    824 * per-conn limits that are big enough they'll never matter. But if it's
    825 * not a known relay, first check if we set PerConnBwRate/Burst, then
    826 * check if the consensus sets them, else default to 'big enough'.
    827 *
    828 * If <b>reset</b> is true, set the bucket to be full.  Otherwise, just
    829 * clip the bucket if it happens to be <em>too</em> full.
    830 */
    831 static void
    832 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
    833                                          const or_options_t *options)
    834 {
    835  int rate, burst; /* per-connection rate limiting params */
    836  if (connection_or_digest_is_known_relay(conn->identity_digest)) {
    837    /* It's in the consensus, or we have a descriptor for it meaning it
    838     * was probably in a recent consensus. It's a recognized relay:
    839     * give it full bandwidth. */
    840    rate = (int)options->BandwidthRate;
    841    burst = (int)options->BandwidthBurst;
    842  } else {
    843    /* Not a recognized relay. Squeeze it down based on the suggested
    844     * bandwidth parameters in the consensus, but allow local config
    845     * options to override. */
    846    rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
    847        networkstatus_get_param(NULL, "perconnbwrate",
    848                                (int)options->BandwidthRate, 1, INT32_MAX);
    849    burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
    850        networkstatus_get_param(NULL, "perconnbwburst",
    851                                (int)options->BandwidthBurst, 1, INT32_MAX);
    852  }
    853 
    854  token_bucket_rw_adjust(&conn->bucket, rate, burst);
    855  if (reset) {
    856    token_bucket_rw_reset(&conn->bucket, monotime_coarse_get_stamp());
    857  }
    858 }
    859 
    860 /** Either our set of relays or our per-conn rate limits have changed.
    861 * Go through all the OR connections and update their token buckets to make
    862 * sure they don't exceed their maximum values. */
    863 void
    864 connection_or_update_token_buckets(smartlist_t *conns,
    865                                   const or_options_t *options)
    866 {
    867  SMARTLIST_FOREACH(conns, connection_t *, conn,
    868  {
    869    if (connection_speaks_cells(conn))
    870      connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
    871  });
    872 }
    873 
    874 /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
    875 * non-canonical otherwise. Adjust idle_timeout accordingly.
    876 */
    877 void
    878 connection_or_set_canonical(or_connection_t *or_conn,
    879                            int is_canonical)
    880 {
    881  if (bool_eq(is_canonical, or_conn->is_canonical) &&
    882      or_conn->idle_timeout != 0) {
    883    /* Don't recalculate an existing idle_timeout unless the canonical
    884     * status changed. */
    885    return;
    886  }
    887 
    888  or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
    889  or_conn->idle_timeout = channelpadding_get_channel_idle_timeout(
    890          TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
    891 
    892  log_info(LD_CIRC,
    893          "Channel %"PRIu64 " chose an idle timeout of %d.",
    894          or_conn->chan ?
    895          (TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
    896          or_conn->idle_timeout);
    897 }
    898 
    899 /** If we don't necessarily know the router we're connecting to, but we
    900 * have an addr/port/id_digest, then fill in as much as we can. Start
    901 * by checking to see if this describes a router we know.
    902 * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
    903 * 0 if it's an incoming connection.  */
    904 void
    905 connection_or_init_conn_from_address(or_connection_t *conn,
    906                                     const tor_addr_t *addr, uint16_t port,
    907                                     const char *id_digest,
    908                                     const ed25519_public_key_t *ed_id,
    909                                     int started_here)
    910 {
    911  log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
    912            fmt_addr(addr),
    913            hex_str((const char*)id_digest, DIGEST_LEN),
    914            ed25519_fmt(ed_id),
    915            started_here);
    916 
    917  connection_or_set_identity_digest(conn, id_digest, ed_id);
    918  connection_or_update_token_buckets_helper(conn, 1, get_options());
    919 
    920  conn->base_.port = port;
    921  tor_addr_copy(&conn->base_.addr, addr);
    922  if (! conn->base_.address) {
    923    conn->base_.address = tor_strdup(fmt_addr(addr));
    924  }
    925 
    926  connection_or_check_canonicity(conn, started_here);
    927 }
    928 
    929 /** Check whether the identity of <b>conn</b> matches a known node.  If it
    930 * does, check whether the address of conn matches the expected address, and
    931 * update the connection's is_canonical flag, nickname, and address fields as
    932 * appropriate. */
    933 static void
    934 connection_or_check_canonicity(or_connection_t *conn, int started_here)
    935 {
    936  (void) started_here;
    937 
    938  const char *id_digest = conn->identity_digest;
    939  const ed25519_public_key_t *ed_id = NULL;
    940  if (conn->chan)
    941    ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
    942 
    943  const node_t *r = node_get_by_id(id_digest);
    944  if (r &&
    945      node_supports_ed25519_link_authentication(r, 1) &&
    946      ! node_ed25519_id_matches(r, ed_id)) {
    947    /* If this node is capable of proving an ed25519 ID,
    948     * we can't call this a canonical connection unless both IDs match. */
    949     r = NULL;
    950  }
    951 
    952  if (r) {
    953    tor_addr_port_t node_ipv4_ap;
    954    tor_addr_port_t node_ipv6_ap;
    955    node_get_prim_orport(r, &node_ipv4_ap);
    956    node_get_pref_ipv6_orport(r, &node_ipv6_ap);
    957    if (tor_addr_eq(&conn->base_.addr, &node_ipv4_ap.addr) ||
    958        tor_addr_eq(&conn->base_.addr, &node_ipv6_ap.addr)) {
    959      connection_or_set_canonical(conn, 1);
    960    }
    961    /* Choose the correct canonical address and port. */
    962    tor_addr_port_t *node_ap;
    963    if (tor_addr_family(&conn->base_.addr) == AF_INET) {
    964      node_ap = &node_ipv4_ap;
    965    } else {
    966      node_ap = &node_ipv6_ap;
    967    }
    968    /* Remember the canonical addr/port so our log messages will make
    969       sense. */
    970    tor_addr_port_copy(&conn->canonical_orport, node_ap);
    971    tor_free(conn->nickname);
    972    conn->nickname = tor_strdup(node_get_nickname(r));
    973  } else {
    974    tor_free(conn->nickname);
    975    conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
    976    conn->nickname[0] = '$';
    977    base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
    978                  conn->identity_digest, DIGEST_LEN);
    979  }
    980 
    981  /*
    982   * We have to tell channeltls.c to update the channel marks (local, in
    983   * particular), since we may have changed the address.
    984   */
    985 
    986  if (conn->chan) {
    987    channel_tls_update_marks(conn);
    988  }
    989 }
    990 
    991 /** These just pass all the is_bad_for_new_circs manipulation on to
    992 * channel_t */
    993 
    994 static unsigned int
    995 connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
    996 {
    997  tor_assert(or_conn);
    998 
    999  if (or_conn->chan)
   1000    return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
   1001  else return 0;
   1002 }
   1003 
   1004 static void
   1005 connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
   1006 {
   1007  tor_assert(or_conn);
   1008 
   1009  if (or_conn->chan)
   1010    channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
   1011 }
   1012 
   1013 /** How old do we let a connection to an OR get before deciding it's
   1014 * too old for new circuits? */
   1015 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
   1016 
   1017 /** Expire an or_connection if it is too old. Helper for
   1018 * connection_or_group_set_badness_ and fast path for
   1019 * channel_rsa_id_group_set_badness.
   1020 *
   1021 * Returns 1 if the connection was already expired, else 0.
   1022 */
   1023 int
   1024 connection_or_single_set_badness_(time_t now,
   1025                                  or_connection_t *or_conn,
   1026                                  int force)
   1027 {
   1028  /* XXXX this function should also be about channels? */
   1029  if (or_conn->base_.marked_for_close ||
   1030      connection_or_is_bad_for_new_circs(or_conn))
   1031    return 1;
   1032 
   1033  if (force ||
   1034      or_conn->base_.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
   1035        < now) {
   1036    log_info(LD_OR,
   1037             "Marking %s as too old for new circuits "
   1038             "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
   1039             connection_describe(TO_CONN(or_conn)),
   1040             or_conn->base_.s,
   1041             (int)(now - or_conn->base_.timestamp_created));
   1042    connection_or_mark_bad_for_new_circs(or_conn);
   1043  }
   1044 
   1045  return 0;
   1046 }
   1047 
   1048 /** Given a list of all the or_connections with a given
   1049 * identity, set elements of that list as is_bad_for_new_circs as
   1050 * appropriate. Helper for connection_or_set_bad_connections().
   1051 *
   1052 * Specifically, we set the is_bad_for_new_circs flag on:
   1053 *    - all connections if <b>force</b> is true.
   1054 *    - all connections that are too old.
   1055 *    - all open non-canonical connections for which a canonical connection
   1056 *      exists to the same router.
   1057 *    - all open canonical connections for which a 'better' canonical
   1058 *      connection exists to the same router.
   1059 *    - all open non-canonical connections for which a 'better' non-canonical
   1060 *      connection exists to the same router at the same address.
   1061 *
   1062 * See channel_is_better() in channel.c for our idea of what makes one OR
   1063 * connection better than another.
   1064 */
   1065 void
   1066 connection_or_group_set_badness_(smartlist_t *group, int force)
   1067 {
   1068  /* XXXX this function should be entirely about channels, not OR
   1069   * XXXX connections. */
   1070 
   1071  or_connection_t *best = NULL;
   1072  int n_canonical = 0;
   1073  time_t now = time(NULL);
   1074 
   1075  /* Pass 1: expire everything that's old, and see what the status of
   1076   * everything else is. */
   1077  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
   1078    if (connection_or_single_set_badness_(now, or_conn, force))
   1079      continue;
   1080 
   1081    if (or_conn->is_canonical) {
   1082      ++n_canonical;
   1083    }
   1084  } SMARTLIST_FOREACH_END(or_conn);
   1085 
   1086  /* Pass 2: We know how about how good the best connection is.
   1087   * expire everything that's worse, and find the very best if we can. */
   1088  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
   1089    if (or_conn->base_.marked_for_close ||
   1090        connection_or_is_bad_for_new_circs(or_conn))
   1091      continue; /* This one doesn't need to be marked bad. */
   1092    if (or_conn->base_.state != OR_CONN_STATE_OPEN)
   1093      continue; /* Don't mark anything bad until we have seen what happens
   1094                 * when the connection finishes. */
   1095    if (n_canonical && !or_conn->is_canonical) {
   1096      /* We have at least one open canonical connection to this router,
   1097       * and this one is open but not canonical.  Mark it bad. */
   1098      log_info(LD_OR,
   1099               "Marking %s unsuitable for new circuits: "
   1100               "(fd "TOR_SOCKET_T_FORMAT", %d secs old).  It is not "
   1101               "canonical, and we have another connection to that OR that is.",
   1102               connection_describe(TO_CONN(or_conn)),
   1103               or_conn->base_.s,
   1104               (int)(now - or_conn->base_.timestamp_created));
   1105      connection_or_mark_bad_for_new_circs(or_conn);
   1106      continue;
   1107    }
   1108 
   1109    if (!best ||
   1110        channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
   1111                          TLS_CHAN_TO_BASE(best->chan))) {
   1112      best = or_conn;
   1113    }
   1114  } SMARTLIST_FOREACH_END(or_conn);
   1115 
   1116  if (!best)
   1117    return;
   1118 
   1119  /* Pass 3: One connection to OR is best.  If it's canonical, mark as bad
   1120   * every other open connection.  If it's non-canonical, mark as bad
   1121   * every other open connection to the same address.
   1122   *
   1123   * XXXX This isn't optimal; if we have connections to an OR at multiple
   1124   *   addresses, we'd like to pick the best _for each address_, and mark as
   1125   *   bad every open connection that isn't best for its address.  But this
   1126   *   can only occur in cases where the other OR is old (so we have no
   1127   *   canonical connection to it), or where all the connections to the OR are
   1128   *   at noncanonical addresses and we have no good direct connection (which
   1129   *   means we aren't at risk of attaching circuits to it anyway).  As
   1130   *   0.1.2.x dies out, the first case will go away, and the second one is
   1131   *   "mostly harmless", so a fix can wait until somebody is bored.
   1132   */
   1133  SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
   1134    if (or_conn->base_.marked_for_close ||
   1135        connection_or_is_bad_for_new_circs(or_conn) ||
   1136        or_conn->base_.state != OR_CONN_STATE_OPEN)
   1137      continue;
   1138    if (or_conn != best &&
   1139        channel_is_better(TLS_CHAN_TO_BASE(best->chan),
   1140                          TLS_CHAN_TO_BASE(or_conn->chan))) {
   1141      /* This isn't the best conn, _and_ the best conn is better than it */
   1142      if (best->is_canonical) {
   1143        log_info(LD_OR,
   1144                 "Marking %s as unsuitable for new circuits: "
   1145                 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
   1146                 "We have a better canonical one "
   1147                 "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
   1148                 connection_describe(TO_CONN(or_conn)),
   1149                 or_conn->base_.s,
   1150                 (int)(now - or_conn->base_.timestamp_created),
   1151                 best->base_.s, (int)(now - best->base_.timestamp_created));
   1152        connection_or_mark_bad_for_new_circs(or_conn);
   1153      } else if (tor_addr_eq(&TO_CONN(or_conn)->addr,
   1154                             &TO_CONN(best)->addr)) {
   1155        log_info(LD_OR,
   1156                 "Marking %s unsuitable for new circuits: "
   1157                 "(fd "TOR_SOCKET_T_FORMAT", %d secs old).  We have a better "
   1158                 "one with the "
   1159                 "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
   1160                 connection_describe(TO_CONN(or_conn)),
   1161                 or_conn->base_.s,
   1162                 (int)(now - or_conn->base_.timestamp_created),
   1163                 best->base_.s, (int)(now - best->base_.timestamp_created));
   1164        connection_or_mark_bad_for_new_circs(or_conn);
   1165      }
   1166    }
   1167  } SMARTLIST_FOREACH_END(or_conn);
   1168 }
   1169 
   1170 /* Lifetime of a connection failure. After that, we'll retry. This is in
   1171 * seconds. */
   1172 #define OR_CONNECT_FAILURE_LIFETIME 60
   1173 /* The interval to use with when to clean up the failure cache. */
   1174 #define OR_CONNECT_FAILURE_CLEANUP_INTERVAL 60
   1175 
   1176 /* When is the next time we have to cleanup the failure map. We keep this
   1177 * because we clean it opportunistically. */
   1178 static time_t or_connect_failure_map_next_cleanup_ts = 0;
   1179 
   1180 /* OR connection failure entry data structure. It is kept in the connection
   1181 * failure map defined below and indexed by OR identity digest, address and
   1182 * port.
   1183 *
   1184 * We need to identify a connection failure with these three values because we
   1185 * want to avoid to wrongfully block a relay if someone is trying to
   1186 * extend to a known identity digest but with the wrong IP/port. For instance,
   1187 * it can happen if a relay changed its port but the client still has an old
   1188 * descriptor with the old port. We want to stop connecting to that
   1189 * IP/port/identity all together, not only the relay identity. */
   1190 typedef struct or_connect_failure_entry_t {
   1191  HT_ENTRY(or_connect_failure_entry_t) node;
   1192  /* Identity digest of the connection where it is connecting to. */
   1193  uint8_t identity_digest[DIGEST_LEN];
   1194  /* This is the connection address from the base connection_t. After the
   1195   * connection is checked for canonicity, the base address should represent
   1196   * what we know instead of where we are connecting to. This is what we need
   1197   * so we can correlate known relays within the consensus. */
   1198  tor_addr_t addr;
   1199  uint16_t port;
   1200  /* Last time we were unable to connect. */
   1201  time_t last_failed_connect_ts;
   1202 } or_connect_failure_entry_t;
   1203 
   1204 /* Map where we keep connection failure entries. They are indexed by addr,
   1205 * port and identity digest. */
   1206 static HT_HEAD(or_connect_failure_ht, or_connect_failure_entry_t)
   1207       or_connect_failures_map = HT_INITIALIZER();
   1208 
   1209 /* Helper: Hashtable equal function. Return 1 if equal else 0. */
   1210 static int
   1211 or_connect_failure_ht_eq(const or_connect_failure_entry_t *a,
   1212                         const or_connect_failure_entry_t *b)
   1213 {
   1214  return fast_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN) &&
   1215         tor_addr_eq(&a->addr, &b->addr) &&
   1216         a->port == b->port;
   1217 }
   1218 
   1219 /* Helper: Return the hash for the hashtable of the given entry. For this
   1220 * table, it is a combination of address, port and identity digest. */
   1221 static unsigned int
   1222 or_connect_failure_ht_hash(const or_connect_failure_entry_t *entry)
   1223 {
   1224  size_t offset = 0, addr_size;
   1225  const void *addr_ptr;
   1226  /* Largest size is IPv6 and IPv4 is smaller so it is fine. */
   1227  uint8_t data[16 + sizeof(uint16_t) + DIGEST_LEN];
   1228 
   1229  /* Get the right address bytes depending on the family. */
   1230  switch (tor_addr_family(&entry->addr)) {
   1231  case AF_INET:
   1232    addr_size = 4;
   1233    addr_ptr = &entry->addr.addr.in_addr.s_addr;
   1234    break;
   1235  case AF_INET6:
   1236    addr_size = 16;
   1237    addr_ptr = &entry->addr.addr.in6_addr.s6_addr;
   1238    break;
   1239  default:
   1240    tor_assert_nonfatal_unreached();
   1241    return 0;
   1242  }
   1243 
   1244  memcpy(data, addr_ptr, addr_size);
   1245  offset += addr_size;
   1246  memcpy(data + offset, entry->identity_digest, DIGEST_LEN);
   1247  offset += DIGEST_LEN;
   1248  set_uint16(data + offset, entry->port);
   1249  offset += sizeof(uint16_t);
   1250 
   1251  return (unsigned int) siphash24g(data, offset);
   1252 }
   1253 
   1254 HT_PROTOTYPE(or_connect_failure_ht, or_connect_failure_entry_t, node,
   1255             or_connect_failure_ht_hash, or_connect_failure_ht_eq);
   1256 
   1257 HT_GENERATE2(or_connect_failure_ht, or_connect_failure_entry_t, node,
   1258             or_connect_failure_ht_hash, or_connect_failure_ht_eq,
   1259             0.6, tor_reallocarray_, tor_free_);
   1260 
   1261 /* Initialize a given connect failure entry with the given identity_digest,
   1262 * addr and port. All field are optional except ocf. */
   1263 static void
   1264 or_connect_failure_init(const char *identity_digest, const tor_addr_t *addr,
   1265                        uint16_t port, or_connect_failure_entry_t *ocf)
   1266 {
   1267  tor_assert(ocf);
   1268  if (identity_digest) {
   1269    memcpy(ocf->identity_digest, identity_digest,
   1270           sizeof(ocf->identity_digest));
   1271  }
   1272  if (addr) {
   1273    tor_addr_copy(&ocf->addr, addr);
   1274  }
   1275  ocf->port = port;
   1276 }
   1277 
   1278 /* Return a newly allocated connection failure entry. It is initialized with
   1279 * the given or_conn data. This can't fail. */
   1280 static or_connect_failure_entry_t *
   1281 or_connect_failure_new(const or_connection_t *or_conn)
   1282 {
   1283  or_connect_failure_entry_t *ocf = tor_malloc_zero(sizeof(*ocf));
   1284  or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
   1285                          TO_CONN(or_conn)->port, ocf);
   1286  return ocf;
   1287 }
   1288 
   1289 /* Return a connection failure entry matching the given or_conn. NULL is
   1290 * returned if not found. */
   1291 static or_connect_failure_entry_t *
   1292 or_connect_failure_find(const or_connection_t *or_conn)
   1293 {
   1294  or_connect_failure_entry_t lookup;
   1295  tor_assert(or_conn);
   1296  or_connect_failure_init(or_conn->identity_digest, &TO_CONN(or_conn)->addr,
   1297                          TO_CONN(or_conn)->port, &lookup);
   1298  return HT_FIND(or_connect_failure_ht, &or_connect_failures_map, &lookup);
   1299 }
   1300 
   1301 /* Note down in the connection failure cache that a failure occurred on the
   1302 * given or_conn. */
   1303 STATIC void
   1304 note_or_connect_failed(const or_connection_t *or_conn)
   1305 {
   1306  or_connect_failure_entry_t *ocf = NULL;
   1307 
   1308  tor_assert(or_conn);
   1309 
   1310  if (or_conn->potentially_used_for_bootstrapping) {
   1311    /* Don't cache connection failures for connections we initiated ourself.
   1312     * If these direct connections fail, we're supposed to recognize that
   1313     * the destination is down and stop trying. See ticket 40499. */
   1314    return;
   1315  }
   1316 
   1317  ocf = or_connect_failure_find(or_conn);
   1318  if (ocf == NULL) {
   1319    ocf = or_connect_failure_new(or_conn);
   1320    HT_INSERT(or_connect_failure_ht, &or_connect_failures_map, ocf);
   1321  }
   1322  ocf->last_failed_connect_ts = approx_time();
   1323 }
   1324 
   1325 /* Cleanup the connection failure cache and remove all entries below the
   1326 * given cutoff. */
   1327 static void
   1328 or_connect_failure_map_cleanup(time_t cutoff)
   1329 {
   1330  or_connect_failure_entry_t **ptr, **next, *entry;
   1331 
   1332  for (ptr = HT_START(or_connect_failure_ht, &or_connect_failures_map);
   1333       ptr != NULL; ptr = next) {
   1334    entry = *ptr;
   1335    if (entry->last_failed_connect_ts <= cutoff) {
   1336      next = HT_NEXT_RMV(or_connect_failure_ht, &or_connect_failures_map, ptr);
   1337      tor_free(entry);
   1338    } else {
   1339      next = HT_NEXT(or_connect_failure_ht, &or_connect_failures_map, ptr);
   1340    }
   1341  }
   1342 }
   1343 
   1344 /* Return true iff the given OR connection can connect to its destination that
   1345 * is the triplet identity_digest, address and port.
   1346 *
   1347 * The or_conn MUST have gone through connection_or_check_canonicity() so the
   1348 * base address is properly set to what we know or doesn't know. */
   1349 STATIC int
   1350 should_connect_to_relay(const or_connection_t *or_conn)
   1351 {
   1352  time_t now, cutoff;
   1353  time_t connect_failed_since_ts = 0;
   1354  or_connect_failure_entry_t *ocf;
   1355 
   1356  tor_assert(or_conn);
   1357 
   1358  now = approx_time();
   1359  cutoff = now - OR_CONNECT_FAILURE_LIFETIME;
   1360 
   1361  /* Opportunistically try to cleanup the failure cache. We do that at regular
   1362   * interval so it doesn't grow too big. */
   1363  if (or_connect_failure_map_next_cleanup_ts <= now) {
   1364    or_connect_failure_map_cleanup(cutoff);
   1365    or_connect_failure_map_next_cleanup_ts =
   1366      now + OR_CONNECT_FAILURE_CLEANUP_INTERVAL;
   1367  }
   1368 
   1369  /* Look if we have failed previously to the same destination as this
   1370   * OR connection. */
   1371  ocf = or_connect_failure_find(or_conn);
   1372  if (ocf) {
   1373    connect_failed_since_ts = ocf->last_failed_connect_ts;
   1374  }
   1375  /* If we do have an unable to connect timestamp and it is below cutoff, we
   1376   * can connect. Or we have never failed before so let it connect. */
   1377  if (connect_failed_since_ts > cutoff) {
   1378    goto no_connect;
   1379  }
   1380 
   1381  /* Ok we can connect! */
   1382  return 1;
   1383 no_connect:
   1384  return 0;
   1385 }
   1386 
   1387 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
   1388 * a TCP connection. Send notifications appropriately.
   1389 *
   1390 * <b>reason</b> specifies the or_conn_end_reason for the failure;
   1391 * <b>msg</b> specifies the strerror-style error message.
   1392 */
   1393 void
   1394 connection_or_connect_failed(or_connection_t *conn,
   1395                             int reason, const char *msg)
   1396 {
   1397  connection_or_event_status(conn, OR_CONN_EVENT_FAILED, reason);
   1398  if (!authdir_mode_tests_reachability(get_options()))
   1399    control_event_bootstrap_prob_or(msg, reason, conn);
   1400  note_or_connect_failed(conn);
   1401 }
   1402 
   1403 /** <b>conn</b> got an error in connection_handle_read_impl() or
   1404 * connection_handle_write_impl() and is going to die soon.
   1405 *
   1406 * <b>reason</b> specifies the or_conn_end_reason for the failure;
   1407 * <b>msg</b> specifies the strerror-style error message.
   1408 */
   1409 void
   1410 connection_or_notify_error(or_connection_t *conn,
   1411                           int reason, const char *msg)
   1412 {
   1413  channel_t *chan;
   1414 
   1415  tor_assert(conn);
   1416 
   1417  /* If we're connecting, call connect_failed() too */
   1418  if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
   1419    connection_or_connect_failed(conn, reason, msg);
   1420 
   1421  /* Tell the controlling channel if we have one */
   1422  if (conn->chan) {
   1423    chan = TLS_CHAN_TO_BASE(conn->chan);
   1424    /* Don't transition if we're already in closing, closed or error */
   1425    if (!CHANNEL_CONDEMNED(chan)) {
   1426      channel_close_for_error(chan);
   1427    }
   1428  }
   1429 
   1430  /* No need to mark for error because connection.c is about to do that */
   1431 }
   1432 
   1433 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
   1434 * handshake with an OR with identity digest <b>id_digest</b>.  Optionally,
   1435 * pass in a pointer to a channel using this connection.
   1436 *
   1437 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
   1438 * return that connection. If the connect() is in progress, set the
   1439 * new conn's state to 'connecting' and return it. If connect() succeeds,
   1440 * call connection_tls_start_handshake() on it.
   1441 *
   1442 * This function is called from router_retry_connections(), for
   1443 * ORs connecting to ORs, and circuit_establish_circuit(), for
   1444 * OPs connecting to ORs.
   1445 *
   1446 * Return the launched conn, or NULL if it failed.
   1447 */
   1448 MOCK_IMPL(or_connection_t *,
   1449 connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
   1450                        const char *id_digest,
   1451                        const ed25519_public_key_t *ed_id,
   1452                        channel_tls_t *chan))
   1453 {
   1454  or_connection_t *conn;
   1455  const or_options_t *options = get_options();
   1456  int socket_error = 0;
   1457  tor_addr_t addr;
   1458 
   1459  int r;
   1460  tor_addr_t proxy_addr;
   1461  uint16_t proxy_port;
   1462  int proxy_type, is_pt = 0;
   1463 
   1464  tor_assert(_addr);
   1465  tor_assert(id_digest);
   1466  tor_addr_copy(&addr, _addr);
   1467 
   1468  if (server_mode(options) && router_digest_is_me(id_digest)) {
   1469    log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
   1470    return NULL;
   1471  }
   1472  if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
   1473    log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
   1474             "identity. Refusing.");
   1475    return NULL;
   1476  }
   1477 
   1478  conn = or_connection_new(CONN_TYPE_OR, tor_addr_family(&addr));
   1479 
   1480  /*
   1481   * Set up conn so it's got all the data we need to remember for channels
   1482   *
   1483   * This stuff needs to happen before connection_or_init_conn_from_address()
   1484   * so connection_or_set_identity_digest() and such know where to look to
   1485   * keep the channel up to date.
   1486   */
   1487  conn->chan = chan;
   1488  chan->conn = conn;
   1489  connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
   1490 
   1491  /* We have a proper OR connection setup, now check if we can connect to it
   1492   * that is we haven't had a failure earlier. This is to avoid to try to
   1493   * constantly connect to relays that we think are not reachable. */
   1494  if (!should_connect_to_relay(conn)) {
   1495    log_info(LD_GENERAL, "Can't connect to %s because we "
   1496                         "failed earlier. Refusing.",
   1497             connection_describe_peer(TO_CONN(conn)));
   1498    connection_free_(TO_CONN(conn));
   1499    return NULL;
   1500  }
   1501 
   1502  conn->is_outgoing = 1;
   1503 
   1504  /* If we are using a proxy server, find it and use it. */
   1505  r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, &is_pt,
   1506                         TO_CONN(conn));
   1507  if (r == 0) {
   1508    conn->proxy_type = proxy_type;
   1509    if (proxy_type != PROXY_NONE) {
   1510      tor_addr_copy(&addr, &proxy_addr);
   1511      port = proxy_port;
   1512      conn->base_.proxy_state = PROXY_INFANT;
   1513      conn->is_pt = is_pt;
   1514    }
   1515    connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
   1516    connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
   1517  } else {
   1518    /* This duplication of state change calls is necessary in case we
   1519     * run into an error condition below */
   1520    connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
   1521    connection_or_event_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
   1522 
   1523    /* get_proxy_addrport() might fail if we have a Bridge line that
   1524       references a transport, but no ClientTransportPlugin lines
   1525       defining its transport proxy. If this is the case, let's try to
   1526       output a useful log message to the user. */
   1527    const char *transport_name =
   1528      find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
   1529                                             TO_CONN(conn)->port);
   1530 
   1531    if (transport_name) {
   1532      log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
   1533               "using pluggable transport '%s', but we can't find a pluggable "
   1534               "transport proxy supporting '%s'. This can happen if you "
   1535               "haven't provided a ClientTransportPlugin line, or if "
   1536               "your pluggable transport proxy stopped running.",
   1537               connection_describe_peer(TO_CONN(conn)),
   1538               transport_name, transport_name);
   1539 
   1540      control_event_bootstrap_prob_or(
   1541                                "Can't connect to bridge",
   1542                                END_OR_CONN_REASON_PT_MISSING,
   1543                                conn);
   1544 
   1545    } else {
   1546      log_warn(LD_GENERAL, "Tried to connect to %s through a proxy, but "
   1547               "the proxy address could not be found.",
   1548               connection_describe_peer(TO_CONN(conn)));
   1549    }
   1550 
   1551    connection_free_(TO_CONN(conn));
   1552    return NULL;
   1553  }
   1554 
   1555  switch (connection_connect(TO_CONN(conn), conn->base_.address,
   1556                             &addr, port, &socket_error)) {
   1557    case -1:
   1558      /* We failed to establish a connection probably because of a local
   1559       * error. No need to blame the guard in this case. Notify the networking
   1560       * system of this failure. */
   1561      connection_or_connect_failed(conn,
   1562                                   errno_to_orconn_end_reason(socket_error),
   1563                                   tor_socket_strerror(socket_error));
   1564      connection_free_(TO_CONN(conn));
   1565      return NULL;
   1566    case 0:
   1567      connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
   1568      /* writable indicates finish, readable indicates broken link,
   1569         error indicates broken link on windows */
   1570      return conn;
   1571    /* case 1: fall through */
   1572  }
   1573 
   1574  if (connection_or_finished_connecting(conn) < 0) {
   1575    /* already marked for close */
   1576    return NULL;
   1577  }
   1578  return conn;
   1579 }
   1580 
   1581 /** Mark orconn for close and transition the associated channel, if any, to
   1582 * the closing state.
   1583 *
   1584 * It's safe to call this and connection_or_close_for_error() any time, and
   1585 * channel layer will treat it as a connection closing for reasons outside
   1586 * its control, like the remote end closing it.  It can also be a local
   1587 * reason that's specific to connection_t/or_connection_t rather than
   1588 * the channel mechanism, such as expiration of old connections in
   1589 * run_connection_housekeeping().  If you want to close a channel_t
   1590 * from somewhere that logically works in terms of generic channels
   1591 * rather than connections, use channel_mark_for_close(); see also
   1592 * the comment on that function in channel.c.
   1593 */
   1594 void
   1595 connection_or_close_normally(or_connection_t *orconn, int flush)
   1596 {
   1597  channel_t *chan = NULL;
   1598 
   1599  tor_assert(orconn);
   1600  if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
   1601  else connection_mark_for_close_internal(TO_CONN(orconn));
   1602  if (orconn->chan) {
   1603    chan = TLS_CHAN_TO_BASE(orconn->chan);
   1604    /* Don't transition if we're already in closing, closed or error */
   1605    if (!CHANNEL_CONDEMNED(chan)) {
   1606      channel_close_from_lower_layer(chan);
   1607    }
   1608  }
   1609 }
   1610 
   1611 /** Mark orconn for close and transition the associated channel, if any, to
   1612 * the error state.
   1613 */
   1614 MOCK_IMPL(void,
   1615 connection_or_close_for_error,(or_connection_t *orconn, int flush))
   1616 {
   1617  channel_t *chan = NULL;
   1618 
   1619  tor_assert(orconn);
   1620  if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
   1621  else connection_mark_for_close_internal(TO_CONN(orconn));
   1622  if (orconn->chan) {
   1623    chan = TLS_CHAN_TO_BASE(orconn->chan);
   1624    /* Don't transition if we're already in closing, closed or error */
   1625    if (!CHANNEL_CONDEMNED(chan)) {
   1626      channel_close_for_error(chan);
   1627    }
   1628  }
   1629 }
   1630 
   1631 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
   1632 * we initiated the connection, else it's 1.
   1633 *
   1634 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
   1635 * pass <b>conn</b> to connection_tls_continue_handshake().
   1636 *
   1637 * Return -1 if <b>conn</b> is broken, else return 0.
   1638 */
   1639 MOCK_IMPL(int,
   1640 connection_tls_start_handshake,(or_connection_t *conn, int receiving))
   1641 {
   1642  channel_listener_t *chan_listener;
   1643  channel_t *chan;
   1644 
   1645  /* Incoming connections will need a new channel passed to the
   1646   * channel_tls_listener */
   1647  if (receiving) {
   1648    /* It shouldn't already be set */
   1649    tor_assert(!(conn->chan));
   1650    chan_listener = channel_tls_get_listener();
   1651    if (!chan_listener) {
   1652      chan_listener = channel_tls_start_listener();
   1653      command_setup_listener(chan_listener);
   1654    }
   1655    chan = channel_tls_handle_incoming(conn);
   1656    channel_listener_queue_incoming(chan_listener, chan);
   1657  }
   1658 
   1659  connection_or_change_state(conn, OR_CONN_STATE_TLS_HANDSHAKING);
   1660  tor_assert(!conn->tls);
   1661  conn->tls = tor_tls_new(conn->base_.s, receiving);
   1662  if (!conn->tls) {
   1663    log_warn(LD_BUG,"tor_tls_new failed. Closing.");
   1664    return -1;
   1665  }
   1666  tor_tls_set_logged_address(conn->tls,
   1667                             connection_describe_peer(TO_CONN(conn)));
   1668 
   1669  connection_start_reading(TO_CONN(conn));
   1670  log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
   1671            conn->base_.s);
   1672 
   1673  if (connection_tls_continue_handshake(conn) < 0)
   1674    return -1;
   1675 
   1676  return 0;
   1677 }
   1678 
   1679 /** Move forward with the tls handshake. If it finishes, hand
   1680 * <b>conn</b> to connection_tls_finish_handshake().
   1681 *
   1682 * Return -1 if <b>conn</b> is broken, else return 0.
   1683 */
   1684 int
   1685 connection_tls_continue_handshake(or_connection_t *conn)
   1686 {
   1687  int result;
   1688  check_no_tls_errors();
   1689 
   1690  tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
   1691  // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
   1692  result = tor_tls_handshake(conn->tls);
   1693  // log_notice(LD_OR, "Result: %d", result);
   1694 
   1695  switch (result) {
   1696    CASE_TOR_TLS_ERROR_ANY:
   1697      conn->tls_error = result;
   1698      log_info(LD_OR,"tls error [%s]. breaking connection.",
   1699             tor_tls_err_to_string(result));
   1700      return -1;
   1701    case TOR_TLS_DONE:
   1702      {
   1703        if (!tor_tls_is_server(conn->tls)) {
   1704          tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
   1705          return connection_or_launch_v3_or_handshake(conn);
   1706        } else {
   1707          /* v3+ handshake, but we are not a client. */
   1708          log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
   1709                           "Expecting VERSIONS cell");
   1710          /* Note: We could instead just send a VERSIONS cell now,
   1711           * since the V2 handshake is no longer a thing.
   1712           * But that would require re-plumbing this state machine. */
   1713          connection_or_change_state(conn,
   1714                                     OR_CONN_STATE_SERVER_VERSIONS_WAIT);
   1715          connection_stop_writing(TO_CONN(conn));
   1716          connection_start_reading(TO_CONN(conn));
   1717          return 0;
   1718        }
   1719      }
   1720    case TOR_TLS_WANTWRITE:
   1721      connection_start_writing(TO_CONN(conn));
   1722      log_debug(LD_OR,"wanted write");
   1723      return 0;
   1724    case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
   1725      log_debug(LD_OR,"wanted read");
   1726      return 0;
   1727    case TOR_TLS_CLOSE:
   1728      conn->tls_error = result;
   1729      log_info(LD_OR,"tls closed. breaking connection.");
   1730      return -1;
   1731  }
   1732  return 0;
   1733 }
   1734 
   1735 /** Return 1 if we initiated this connection, or 0 if it started
   1736 * out as an incoming connection.
   1737 */
   1738 int
   1739 connection_or_nonopen_was_started_here(or_connection_t *conn)
   1740 {
   1741  tor_assert(conn->base_.type == CONN_TYPE_OR ||
   1742             conn->base_.type == CONN_TYPE_EXT_OR);
   1743  if (!conn->tls)
   1744    return 1; /* it's still in proxy states or something */
   1745  if (conn->handshake_state)
   1746    return conn->handshake_state->started_here;
   1747  return !tor_tls_is_server(conn->tls);
   1748 }
   1749 
   1750 /** Called when we (as a connection initiator) have definitively,
   1751 * authenticatedly, learned that ID of the Tor instance on the other
   1752 * side of <b>conn</b> is <b>rsa_peer_id</b> and optionally <b>ed_peer_id</b>.
   1753 * For v1 and v2 handshakes,
   1754 * this is right after we get a certificate chain in a TLS handshake
   1755 * or renegotiation.  For v3+ handshakes, this is right after we get a
   1756 * certificate chain in a CERTS cell.
   1757 *
   1758 * If we did not know the ID before, record the one we got.
   1759 *
   1760 * If we wanted an ID, but we didn't get the one we expected, log a message
   1761 * and return -1.
   1762 * On relays:
   1763 *  - log a protocol warning whenever the fingerprints don't match;
   1764 * On clients:
   1765 *  - if a relay's fingerprint doesn't match, log a warning;
   1766 *  - if we don't have updated relay fingerprints from a recent consensus, and
   1767 *    a fallback directory mirror's hard-coded fingerprint has changed, log an
   1768 *    info explaining that we will try another fallback.
   1769 *
   1770 * If we're testing reachability, remember what we learned.
   1771 *
   1772 * Return 0 on success, -1 on failure.
   1773 */
   1774 int
   1775 connection_or_client_learned_peer_id(or_connection_t *conn,
   1776                                     const uint8_t *rsa_peer_id,
   1777                                     const ed25519_public_key_t *ed_peer_id)
   1778 {
   1779  const or_options_t *options = get_options();
   1780  channel_tls_t *chan_tls = conn->chan;
   1781  channel_t *chan = channel_tls_to_base(chan_tls);
   1782  int changed_identity = 0;
   1783  tor_assert(chan);
   1784 
   1785  const int expected_rsa_key =
   1786    ! tor_digest_is_zero(conn->identity_digest);
   1787  const int expected_ed_key =
   1788    ! ed25519_public_key_is_zero(&chan->ed25519_identity);
   1789 
   1790  log_info(LD_HANDSHAKE, "learned peer id for %s at %p: %s, %s",
   1791           connection_describe(TO_CONN(conn)),
   1792           conn,
   1793           hex_str((const char*)rsa_peer_id, DIGEST_LEN),
   1794           ed25519_fmt(ed_peer_id));
   1795 
   1796  if (! expected_rsa_key && ! expected_ed_key) {
   1797    log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
   1798             "connection.");
   1799    connection_or_set_identity_digest(conn,
   1800                                      (const char*)rsa_peer_id, ed_peer_id);
   1801    tor_free(conn->nickname);
   1802    conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
   1803    conn->nickname[0] = '$';
   1804    base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
   1805                  conn->identity_digest, DIGEST_LEN);
   1806    log_info(LD_HANDSHAKE, "Connected to router at %s without knowing "
   1807             "its key. Hoping for the best.",
   1808             connection_describe_peer(TO_CONN(conn)));
   1809    /* if it's a bridge and we didn't know its identity fingerprint, now
   1810     * we do -- remember it for future attempts. */
   1811    learned_router_identity(&conn->base_.addr, conn->base_.port,
   1812                            (const char*)rsa_peer_id, ed_peer_id);
   1813    changed_identity = 1;
   1814  }
   1815 
   1816  const int rsa_mismatch = expected_rsa_key &&
   1817    tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
   1818  /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
   1819   * and didn't get it. It's okay if we get one that we didn't ask for. */
   1820  const int ed25519_mismatch =
   1821    expected_ed_key &&
   1822    (ed_peer_id == NULL ||
   1823     ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
   1824 
   1825  if (rsa_mismatch || ed25519_mismatch) {
   1826    /* I was aiming for a particular digest. I didn't get it! */
   1827    char seen_rsa[HEX_DIGEST_LEN+1];
   1828    char expected_rsa[HEX_DIGEST_LEN+1];
   1829    char seen_ed[ED25519_BASE64_LEN+1];
   1830    char expected_ed[ED25519_BASE64_LEN+1];
   1831    base16_encode(seen_rsa, sizeof(seen_rsa),
   1832                  (const char*)rsa_peer_id, DIGEST_LEN);
   1833    base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
   1834                  DIGEST_LEN);
   1835    if (ed_peer_id) {
   1836      ed25519_public_to_base64(seen_ed, ed_peer_id);
   1837    } else {
   1838      strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
   1839    }
   1840    if (! ed25519_public_key_is_zero(&chan->ed25519_identity)) {
   1841      ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
   1842    } else {
   1843      strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
   1844    }
   1845    const int using_hardcoded_fingerprints =
   1846      !networkstatus_get_reasonably_live_consensus(time(NULL),
   1847                                                   usable_consensus_flavor());
   1848    const int is_fallback_fingerprint = router_digest_is_fallback_dir(
   1849                                                   conn->identity_digest);
   1850    const int is_authority_fingerprint = router_digest_is_trusted_dir(
   1851                                                   conn->identity_digest);
   1852    const int non_anonymous_mode =
   1853      hs_service_non_anonymous_mode_enabled(options);
   1854    int severity;
   1855    const char *extra_log = "";
   1856 
   1857    /* Relays and Single Onion Services make direct connections using
   1858     * untrusted authentication keys. */
   1859    if (server_mode(options) || non_anonymous_mode) {
   1860      severity = LOG_PROTOCOL_WARN;
   1861    } else {
   1862      if (using_hardcoded_fingerprints) {
   1863        /* We need to do the checks in this order, because the list of
   1864         * fallbacks includes the list of authorities */
   1865        if (is_authority_fingerprint) {
   1866          severity = LOG_WARN;
   1867        } else if (is_fallback_fingerprint) {
   1868          /* we expect a small number of fallbacks to change from their
   1869           * hard-coded fingerprints over the life of a release */
   1870          severity = LOG_INFO;
   1871          extra_log = " Tor will try a different fallback.";
   1872        } else {
   1873          /* it's a bridge, it's either a misconfiguration, or unexpected */
   1874          severity = LOG_WARN;
   1875        }
   1876      } else {
   1877        /* a relay has changed its fingerprint from the one in the consensus */
   1878        severity = LOG_WARN;
   1879      }
   1880    }
   1881 
   1882    log_fn(severity, LD_HANDSHAKE,
   1883           "Tried connecting to router at %s, but RSA + ed25519 identity "
   1884           "keys were not as expected: wanted %s + %s but got %s + %s.%s",
   1885           connection_describe_peer(TO_CONN(conn)),
   1886           expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
   1887 
   1888    /* Tell the new guard API about the channel failure */
   1889    entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
   1890    connection_or_event_status(conn, OR_CONN_EVENT_FAILED,
   1891                               END_OR_CONN_REASON_OR_IDENTITY);
   1892    if (!authdir_mode_tests_reachability(options))
   1893      control_event_bootstrap_prob_or(
   1894                                "Unexpected identity in router certificate",
   1895                                END_OR_CONN_REASON_OR_IDENTITY,
   1896                                conn);
   1897    return -1;
   1898  }
   1899 
   1900  if (!expected_ed_key && ed_peer_id) {
   1901    log_info(LD_HANDSHAKE, "(We had no Ed25519 ID in mind when we made this "
   1902             "connection.)");
   1903    connection_or_set_identity_digest(conn,
   1904                                      (const char*)rsa_peer_id, ed_peer_id);
   1905    changed_identity = 1;
   1906  }
   1907 
   1908  if (changed_identity) {
   1909    /* If we learned an identity for this connection, then we might have
   1910     * just discovered it to be canonical. */
   1911    connection_or_check_canonicity(conn, conn->handshake_state->started_here);
   1912    if (conn->tls)
   1913      tor_tls_set_logged_address(conn->tls,
   1914                                 connection_describe_peer(TO_CONN(conn)));
   1915  }
   1916 
   1917  if (authdir_mode_tests_reachability(options)) {
   1918    // We don't want to use canonical_orport here -- we want the address
   1919    // that we really used.
   1920    dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
   1921                            (const char*)rsa_peer_id, ed_peer_id);
   1922  }
   1923 
   1924  return 0;
   1925 }
   1926 
   1927 /** Return when we last used this channel for client activity (origin
   1928 * circuits). This is called from connection.c, since client_used is now one
   1929 * of the timestamps in channel_t */
   1930 time_t
   1931 connection_or_client_used(or_connection_t *conn)
   1932 {
   1933  tor_assert(conn);
   1934 
   1935  if (conn->chan) {
   1936    return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
   1937  } else return 0;
   1938 }
   1939 
   1940 /**
   1941 * Called as client when initial TLS handshake is done, and we notice
   1942 * that we got a v3-handshake signalling certificate from the server.
   1943 * Set up structures, do bookkeeping, and send the versions cell.
   1944 * Return 0 on success and -1 on failure.
   1945 */
   1946 static int
   1947 connection_or_launch_v3_or_handshake(or_connection_t *conn)
   1948 {
   1949  tor_assert(connection_or_nonopen_was_started_here(conn));
   1950 
   1951  circuit_build_times_network_is_live(get_circuit_build_times_mutable());
   1952 
   1953  connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
   1954  if (connection_init_or_handshake_state(conn, 1) < 0)
   1955    return -1;
   1956 
   1957  return connection_or_send_versions(conn, 1);
   1958 }
   1959 
   1960 /** Allocate a new connection handshake state for the connection
   1961 * <b>conn</b>.  Return 0 on success, -1 on failure. */
   1962 int
   1963 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
   1964 {
   1965  or_handshake_state_t *s;
   1966  if (conn->handshake_state) {
   1967    log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
   1968    return 0;
   1969  }
   1970  s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
   1971  s->started_here = started_here ? 1 : 0;
   1972  s->digest_sent_data = 1;
   1973  s->digest_received_data = 1;
   1974  if (! started_here && get_current_link_cert_cert()) {
   1975    s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
   1976  }
   1977  s->certs = or_handshake_certs_new();
   1978  s->certs->started_here = s->started_here;
   1979  return 0;
   1980 }
   1981 
   1982 /** Free all storage held by <b>state</b>. */
   1983 void
   1984 or_handshake_state_free_(or_handshake_state_t *state)
   1985 {
   1986  if (!state)
   1987    return;
   1988  crypto_digest_free(state->digest_sent);
   1989  crypto_digest_free(state->digest_received);
   1990  or_handshake_certs_free(state->certs);
   1991  tor_cert_free(state->own_link_cert);
   1992  memwipe(state, 0xBE, sizeof(or_handshake_state_t));
   1993  tor_free(state);
   1994 }
   1995 
   1996 /**
   1997 * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
   1998 * false) or received (if <b>incoming</b> is true) during a V3 handshake using
   1999 * <b>state</b>.
   2000 *
   2001 * (We don't record the cell, but we keep a digest of everything sent or
   2002 * received during the v3 handshake, and the client signs it in an
   2003 * authenticate cell.)
   2004 */
   2005 void
   2006 or_handshake_state_record_cell(or_connection_t *conn,
   2007                               or_handshake_state_t *state,
   2008                               const cell_t *cell,
   2009                               int incoming)
   2010 {
   2011  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
   2012  crypto_digest_t *d, **dptr;
   2013  packed_cell_t packed;
   2014  if (incoming) {
   2015    if (!state->digest_received_data)
   2016      return;
   2017  } else {
   2018    if (!state->digest_sent_data)
   2019      return;
   2020  }
   2021  if (!incoming) {
   2022    log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
   2023             "while making a handshake digest.  But we think we are sending "
   2024             "one with type %d.", (int)cell->command);
   2025  }
   2026  dptr = incoming ? &state->digest_received : &state->digest_sent;
   2027  if (! *dptr)
   2028    *dptr = crypto_digest256_new(DIGEST_SHA256);
   2029 
   2030  d = *dptr;
   2031  /* Re-packing like this is a little inefficient, but we don't have to do
   2032     this very often at all. */
   2033  cell_pack(&packed, cell, conn->wide_circ_ids);
   2034  crypto_digest_add_bytes(d, packed.body, cell_network_size);
   2035  memwipe(&packed, 0, sizeof(packed));
   2036 }
   2037 
   2038 /** Remember that a variable-length <b>cell</b> has been transmitted (if
   2039 * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
   2040 * V3 handshake using <b>state</b>.
   2041 *
   2042 * (We don't record the cell, but we keep a digest of everything sent or
   2043 * received during the v3 handshake, and the client signs it in an
   2044 * authenticate cell.)
   2045 */
   2046 void
   2047 or_handshake_state_record_var_cell(or_connection_t *conn,
   2048                                   or_handshake_state_t *state,
   2049                                   const var_cell_t *cell,
   2050                                   int incoming)
   2051 {
   2052  crypto_digest_t *d, **dptr;
   2053  int n;
   2054  char buf[VAR_CELL_MAX_HEADER_SIZE];
   2055  if (incoming) {
   2056    if (!state->digest_received_data)
   2057      return;
   2058  } else {
   2059    if (!state->digest_sent_data)
   2060      return;
   2061  }
   2062  dptr = incoming ? &state->digest_received : &state->digest_sent;
   2063  if (! *dptr)
   2064    *dptr = crypto_digest256_new(DIGEST_SHA256);
   2065 
   2066  d = *dptr;
   2067 
   2068  n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
   2069  crypto_digest_add_bytes(d, buf, n);
   2070  crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
   2071 
   2072  memwipe(buf, 0, sizeof(buf));
   2073 }
   2074 
   2075 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
   2076 * as appropriate.  Called when we are done with all TLS and OR handshaking.
   2077 */
   2078 int
   2079 connection_or_set_state_open(or_connection_t *conn)
   2080 {
   2081  connection_or_change_state(conn, OR_CONN_STATE_OPEN);
   2082  connection_or_event_status(conn, OR_CONN_EVENT_CONNECTED, 0);
   2083 
   2084  /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
   2085   * that uses an earlier link protocol should not be treated as a relay. */
   2086  if (conn->link_proto < 3) {
   2087    channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
   2088  }
   2089 
   2090  or_handshake_state_free(conn->handshake_state);
   2091  conn->handshake_state = NULL;
   2092  connection_start_reading(TO_CONN(conn));
   2093 
   2094  return 0;
   2095 }
   2096 
   2097 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
   2098 * For cells that use or affect a circuit, this should only be called by
   2099 * connection_or_flush_from_first_active_circuit().
   2100 */
   2101 void
   2102 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
   2103 {
   2104  packed_cell_t networkcell;
   2105  size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
   2106 
   2107  tor_assert(cell);
   2108  tor_assert(conn);
   2109 
   2110  cell_pack(&networkcell, cell, conn->wide_circ_ids);
   2111 
   2112  /* We need to count padding cells from this non-packed code path
   2113   * since they are sent via chan->write_cell() (which is not packed) */
   2114  rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
   2115  if (cell->command == CELL_PADDING)
   2116    rep_hist_padding_count_write(PADDING_TYPE_CELL);
   2117 
   2118  connection_buf_add(networkcell.body, cell_network_size, TO_CONN(conn));
   2119 
   2120  /* Touch the channel's active timestamp if there is one */
   2121  if (conn->chan) {
   2122    channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
   2123 
   2124    if (TLS_CHAN_TO_BASE(conn->chan)->padding_enabled) {
   2125      rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL);
   2126      if (cell->command == CELL_PADDING)
   2127        rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL);
   2128    }
   2129  }
   2130 
   2131  if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
   2132    or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
   2133 }
   2134 
   2135 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
   2136 * <b>conn</b>'s outbuf.  Right now, this <em>DOES NOT</em> support cells that
   2137 * affect a circuit.
   2138 */
   2139 MOCK_IMPL(void,
   2140 connection_or_write_var_cell_to_buf,(const var_cell_t *cell,
   2141                                     or_connection_t *conn))
   2142 {
   2143  int n;
   2144  char hdr[VAR_CELL_MAX_HEADER_SIZE];
   2145  tor_assert(cell);
   2146  tor_assert(conn);
   2147  n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
   2148  connection_buf_add(hdr, n, TO_CONN(conn));
   2149  connection_buf_add((char*)cell->payload,
   2150                          cell->payload_len, TO_CONN(conn));
   2151  if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
   2152    or_handshake_state_record_var_cell(conn, conn->handshake_state, cell, 0);
   2153 
   2154  rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
   2155  /* Touch the channel's active timestamp if there is one */
   2156  if (conn->chan)
   2157    channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
   2158 }
   2159 
   2160 /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
   2161 * inbuf.  Return values as for fetch_var_cell_from_buf(). */
   2162 static int
   2163 connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
   2164 {
   2165  connection_t *conn = TO_CONN(or_conn);
   2166  return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
   2167 }
   2168 
   2169 /** Process cells from <b>conn</b>'s inbuf.
   2170 *
   2171 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
   2172 * and hand it to command_process_cell().
   2173 *
   2174 * Always return 0.
   2175 */
   2176 static int
   2177 connection_or_process_cells_from_inbuf(or_connection_t *conn)
   2178 {
   2179  var_cell_t *var_cell;
   2180 
   2181  /*
   2182   * Note on memory management for incoming cells: below the channel layer,
   2183   * we shouldn't need to consider its internal queueing/copying logic.  It
   2184   * is safe to pass cells to it on the stack or on the heap, but in the
   2185   * latter case we must be sure we free them later.
   2186   *
   2187   * The incoming cell queue code in channel.c will (in the common case)
   2188   * decide it can pass them to the upper layer immediately, in which case
   2189   * those functions may run directly on the cell pointers we pass here, or
   2190   * it may decide to queue them, in which case it will allocate its own
   2191   * buffer and copy the cell.
   2192   */
   2193 
   2194  while (1) {
   2195    log_debug(LD_OR,
   2196              TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
   2197              "(%d pending in tls object).",
   2198              conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
   2199              tor_tls_get_pending_bytes(conn->tls));
   2200    if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
   2201      if (!var_cell)
   2202        return 0; /* not yet. */
   2203 
   2204      /* Touch the channel's active timestamp if there is one */
   2205      if (conn->chan)
   2206        channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
   2207 
   2208      circuit_build_times_network_is_live(get_circuit_build_times_mutable());
   2209      channel_tls_handle_var_cell(var_cell, conn);
   2210      var_cell_free(var_cell);
   2211    } else {
   2212      const int wide_circ_ids = conn->wide_circ_ids;
   2213      size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
   2214      char buf[CELL_MAX_NETWORK_SIZE];
   2215      cell_t cell;
   2216      if (connection_get_inbuf_len(TO_CONN(conn))
   2217          < cell_network_size) /* whole response available? */
   2218        return 0; /* not yet */
   2219 
   2220      /* Touch the channel's active timestamp if there is one */
   2221      if (conn->chan)
   2222        channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
   2223 
   2224      circuit_build_times_network_is_live(get_circuit_build_times_mutable());
   2225      connection_buf_get_bytes(buf, cell_network_size, TO_CONN(conn));
   2226 
   2227      /* retrieve cell info from buf (create the host-order struct from the
   2228       * network-order string) */
   2229      cell_unpack(&cell, buf, wide_circ_ids);
   2230 
   2231      channel_tls_handle_cell(&cell, conn);
   2232    }
   2233  }
   2234 }
   2235 
   2236 /** Array of supported link protocol versions. */
   2237 static const uint16_t or_protocol_versions[] = { 3, 4, 5 };
   2238 /** Number of versions in <b>or_protocol_versions</b>. */
   2239 static const int n_or_protocol_versions =
   2240  (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
   2241 
   2242 /** Return true iff <b>v</b> is a link protocol version that this Tor
   2243 * implementation believes it can support. */
   2244 int
   2245 is_or_protocol_version_known(uint16_t v)
   2246 {
   2247  int i;
   2248  for (i = 0; i < n_or_protocol_versions; ++i) {
   2249    if (or_protocol_versions[i] == v)
   2250      return 1;
   2251  }
   2252  return 0;
   2253 }
   2254 
   2255 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
   2256 * link protocol versions that this Tor can support.
   2257 *
   2258 * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
   2259 * allow protocol version v3 or later.  If not <b>v3_plus</b>, this is
   2260 * not part of a v3 protocol handshake, so don't allow protocol v3 or
   2261 * later.
   2262 **/
   2263 int
   2264 connection_or_send_versions(or_connection_t *conn, int v3_plus)
   2265 {
   2266  var_cell_t *cell;
   2267  int i;
   2268  int n_versions = 0;
   2269  const int min_version = v3_plus ? 3 : 0;
   2270  const int max_version = v3_plus ? UINT16_MAX : 2;
   2271  tor_assert(conn->handshake_state &&
   2272             !conn->handshake_state->sent_versions_at);
   2273  cell = var_cell_new(n_or_protocol_versions * 2);
   2274  cell->command = CELL_VERSIONS;
   2275  for (i = 0; i < n_or_protocol_versions; ++i) {
   2276    uint16_t v = or_protocol_versions[i];
   2277    if (v < min_version || v > max_version)
   2278      continue;
   2279    set_uint16(cell->payload+(2*n_versions), htons(v));
   2280    ++n_versions;
   2281  }
   2282  cell->payload_len = n_versions * 2;
   2283 
   2284  connection_or_write_var_cell_to_buf(cell, conn);
   2285  conn->handshake_state->sent_versions_at = time(NULL);
   2286 
   2287  var_cell_free(cell);
   2288  return 0;
   2289 }
   2290 
   2291 static netinfo_addr_t *
   2292 netinfo_addr_from_tor_addr(const tor_addr_t *tor_addr)
   2293 {
   2294  sa_family_t addr_family = tor_addr_family(tor_addr);
   2295 
   2296  if (BUG(addr_family != AF_INET && addr_family != AF_INET6))
   2297    return NULL;
   2298 
   2299  netinfo_addr_t *netinfo_addr = netinfo_addr_new();
   2300 
   2301  if (addr_family == AF_INET) {
   2302    netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV4);
   2303    netinfo_addr_set_len(netinfo_addr, 4);
   2304    netinfo_addr_set_addr_ipv4(netinfo_addr, tor_addr_to_ipv4h(tor_addr));
   2305  } else if (addr_family == AF_INET6) {
   2306    netinfo_addr_set_addr_type(netinfo_addr, NETINFO_ADDR_TYPE_IPV6);
   2307    netinfo_addr_set_len(netinfo_addr, 16);
   2308    uint8_t *ipv6_buf = netinfo_addr_getarray_addr_ipv6(netinfo_addr);
   2309    const uint8_t *in6_addr = tor_addr_to_in6_addr8(tor_addr);
   2310    memcpy(ipv6_buf, in6_addr, 16);
   2311  }
   2312 
   2313  return netinfo_addr;
   2314 }
   2315 
   2316 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
   2317 * about their address, our address, and the current time. */
   2318 MOCK_IMPL(int,
   2319 connection_or_send_netinfo,(or_connection_t *conn))
   2320 {
   2321  cell_t cell;
   2322  time_t now = time(NULL);
   2323  const routerinfo_t *me;
   2324  int r = -1;
   2325 
   2326  tor_assert(conn->handshake_state);
   2327 
   2328  if (conn->handshake_state->sent_netinfo) {
   2329    log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
   2330             "where we already sent one.");
   2331    return 0;
   2332  }
   2333 
   2334  memset(&cell, 0, sizeof(cell_t));
   2335  cell.command = CELL_NETINFO;
   2336 
   2337  netinfo_cell_t *netinfo_cell = netinfo_cell_new();
   2338 
   2339  /* Timestamp, if we're a relay. */
   2340  if (public_server_mode(get_options()) || ! conn->is_outgoing)
   2341    netinfo_cell_set_timestamp(netinfo_cell, (uint32_t)now);
   2342 
   2343  /* Their address. */
   2344  const tor_addr_t *remote_tor_addr = &TO_CONN(conn)->addr;
   2345  /* We can safely use TO_CONN(conn)->addr here, since we no longer replace
   2346   * it with a canonical address. */
   2347  netinfo_addr_t *their_addr = netinfo_addr_from_tor_addr(remote_tor_addr);
   2348 
   2349  netinfo_cell_set_other_addr(netinfo_cell, their_addr);
   2350 
   2351  /* My address -- only include it if I'm a public relay, or if I'm a
   2352   * bridge and this is an incoming connection. If I'm a bridge and this
   2353   * is an outgoing connection, act like a normal client and omit it. */
   2354  if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
   2355      (me = router_get_my_routerinfo())) {
   2356    uint8_t n_my_addrs = 1 + !tor_addr_is_null(&me->ipv6_addr);
   2357    netinfo_cell_set_n_my_addrs(netinfo_cell, n_my_addrs);
   2358 
   2359    netinfo_cell_add_my_addrs(netinfo_cell,
   2360                              netinfo_addr_from_tor_addr(&me->ipv4_addr));
   2361 
   2362    if (!tor_addr_is_null(&me->ipv6_addr)) {
   2363      netinfo_cell_add_my_addrs(netinfo_cell,
   2364                                netinfo_addr_from_tor_addr(&me->ipv6_addr));
   2365    }
   2366  }
   2367 
   2368  const char *errmsg = NULL;
   2369  if ((errmsg = netinfo_cell_check(netinfo_cell))) {
   2370    log_warn(LD_OR, "Failed to validate NETINFO cell with error: %s",
   2371                    errmsg);
   2372    goto cleanup;
   2373  }
   2374 
   2375  if (netinfo_cell_encode(cell.payload, CELL_PAYLOAD_SIZE,
   2376                          netinfo_cell) < 0) {
   2377    log_warn(LD_OR, "Failed generating NETINFO cell");
   2378    goto cleanup;
   2379  }
   2380 
   2381  conn->handshake_state->digest_sent_data = 0;
   2382  conn->handshake_state->sent_netinfo = 1;
   2383  connection_or_write_cell_to_buf(&cell, conn);
   2384 
   2385  r = 0;
   2386 cleanup:
   2387  netinfo_cell_free(netinfo_cell);
   2388 
   2389  return r;
   2390 }