tor

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

channel.c (103495B)


      1 /* * Copyright (c) 2012-2021, The Tor Project, Inc. */
      2 /* See LICENSE for licensing information */
      3 
      4 /**
      5 * \file channel.c
      6 *
      7 * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
      8 * transfer cells from Tor instance to Tor instance. Currently, there is only
      9 * one implementation of the channel abstraction: in channeltls.c.
     10 *
     11 * Channels are a higher-level abstraction than or_connection_t: In general,
     12 * any means that two Tor relays use to exchange cells, or any means that a
     13 * relay and a client use to exchange cells, is a channel.
     14 *
     15 * Channels differ from pluggable transports in that they do not wrap an
     16 * underlying protocol over which cells are transmitted: they <em>are</em> the
     17 * underlying protocol.
     18 *
     19 * This module defines the generic parts of the channel_t interface, and
     20 * provides the machinery necessary for specialized implementations to be
     21 * created.  At present, there is one specialized implementation in
     22 * channeltls.c, which uses connection_or.c to send cells over a TLS
     23 * connection.
     24 *
     25 * Every channel implementation is responsible for being able to transmit
     26 * cells that are passed to it
     27 *
     28 * For *inbound* cells, the entry point is: channel_process_cell(). It takes a
     29 * cell and will pass it to the cell handler set by
     30 * channel_set_cell_handlers(). Currently, this is passed back to the command
     31 * subsystem which is command_process_cell().
     32 *
     33 * NOTE: For now, the separation between channels and specialized channels
     34 * (like channeltls) is not that well defined. So the channeltls layer calls
     35 * channel_process_cell() which originally comes from the connection subsystem.
     36 * This should be hopefully be fixed with #23993.
     37 *
     38 * For *outbound* cells, the entry point is: channel_write_packed_cell().
     39 * Only packed cells are dequeued from the circuit queue by the scheduler
     40 * which uses channel_flush_from_first_active_circuit() to decide which cells
     41 * to flush from which circuit on the channel. They are then passed down to
     42 * the channel subsystem. This calls the low layer with the function pointer
     43 * .write_packed_cell().
     44 *
     45 * Each specialized channel (currently only channeltls_t) MUST implement a
     46 * series of function found in channel_t. See channel.h for more
     47 * documentation.
     48 **/
     49 
     50 /*
     51 * Define this so channel.h gives us things only channel_t subclasses
     52 * should touch.
     53 */
     54 #define CHANNEL_OBJECT_PRIVATE
     55 
     56 /* This one's for stuff only channel.c and the test suite should see */
     57 #define CHANNEL_FILE_PRIVATE
     58 
     59 #include "core/or/or.h"
     60 #include "app/config/config.h"
     61 #include "core/mainloop/mainloop.h"
     62 #include "core/or/channel.h"
     63 #include "core/or/channelpadding.h"
     64 #include "core/or/channeltls.h"
     65 #include "core/or/circuitbuild.h"
     66 #include "core/or/circuitlist.h"
     67 #include "core/or/circuitmux.h"
     68 #include "core/or/circuitstats.h"
     69 #include "core/or/connection_or.h" /* For var_cell_free() */
     70 #include "core/or/dos.h"
     71 #include "core/or/relay.h"
     72 #include "core/or/scheduler.h"
     73 #include "feature/client/entrynodes.h"
     74 #include "feature/hs/hs_service.h"
     75 #include "feature/nodelist/dirlist.h"
     76 #include "feature/nodelist/networkstatus.h"
     77 #include "feature/nodelist/nodelist.h"
     78 #include "feature/nodelist/routerlist.h"
     79 #include "feature/relay/router.h"
     80 #include "feature/stats/geoip_stats.h"
     81 #include "feature/stats/rephist.h"
     82 #include "lib/evloop/timers.h"
     83 #include "lib/time/compat_time.h"
     84 
     85 #include "core/or/cell_queue_st.h"
     86 #include "core/or/or_connection_st.h"
     87 
     88 /* Global lists of channels */
     89 
     90 /* All channel_t instances */
     91 static smartlist_t *all_channels = NULL;
     92 
     93 /* All channel_t instances not in ERROR or CLOSED states */
     94 static smartlist_t *active_channels = NULL;
     95 
     96 /* All channel_t instances in ERROR or CLOSED states */
     97 static smartlist_t *finished_channels = NULL;
     98 
     99 /* All channel_listener_t instances */
    100 static smartlist_t *all_listeners = NULL;
    101 
    102 /* All channel_listener_t instances in LISTENING state */
    103 static smartlist_t *active_listeners = NULL;
    104 
    105 /* All channel_listener_t instances in LISTENING state */
    106 static smartlist_t *finished_listeners = NULL;
    107 
    108 /** Map from channel->global_identifier to channel.  Contains the same
    109 * elements as all_channels. */
    110 static HT_HEAD(channel_gid_map, channel_t) channel_gid_map = HT_INITIALIZER();
    111 
    112 static unsigned
    113 channel_id_hash(const channel_t *chan)
    114 {
    115  return (unsigned) chan->global_identifier;
    116 }
    117 static int
    118 channel_id_eq(const channel_t *a, const channel_t *b)
    119 {
    120  return a->global_identifier == b->global_identifier;
    121 }
    122 HT_PROTOTYPE(channel_gid_map, channel_t, gidmap_node,
    123             channel_id_hash, channel_id_eq);
    124 HT_GENERATE2(channel_gid_map, channel_t, gidmap_node,
    125             channel_id_hash, channel_id_eq,
    126             0.6, tor_reallocarray_, tor_free_);
    127 
    128 HANDLE_IMPL(channel, channel_t,)
    129 
    130 /* Counter for ID numbers */
    131 static uint64_t n_channels_allocated = 0;
    132 
    133 /* Digest->channel map
    134 *
    135 * Similar to the one used in connection_or.c, this maps from the identity
    136 * digest of a remote endpoint to a channel_t to that endpoint.  Channels
    137 * should be placed here when registered and removed when they close or error.
    138 * If more than one channel exists, follow the next_with_same_id pointer
    139 * as a linked list.
    140 */
    141 static HT_HEAD(channel_idmap, channel_idmap_entry_t) channel_identity_map =
    142  HT_INITIALIZER();
    143 
    144 typedef struct channel_idmap_entry_t {
    145  HT_ENTRY(channel_idmap_entry_t) node;
    146  uint8_t digest[DIGEST_LEN];
    147  TOR_LIST_HEAD(channel_list_t, channel_t) channel_list;
    148 } channel_idmap_entry_t;
    149 
    150 static inline unsigned
    151 channel_idmap_hash(const channel_idmap_entry_t *ent)
    152 {
    153  return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
    154 }
    155 
    156 static inline int
    157 channel_idmap_eq(const channel_idmap_entry_t *a,
    158                  const channel_idmap_entry_t *b)
    159 {
    160  return tor_memeq(a->digest, b->digest, DIGEST_LEN);
    161 }
    162 
    163 HT_PROTOTYPE(channel_idmap, channel_idmap_entry_t, node, channel_idmap_hash,
    164             channel_idmap_eq);
    165 HT_GENERATE2(channel_idmap, channel_idmap_entry_t, node, channel_idmap_hash,
    166             channel_idmap_eq, 0.5,  tor_reallocarray_, tor_free_);
    167 
    168 /* Functions to maintain the digest map */
    169 static void channel_remove_from_digest_map(channel_t *chan);
    170 
    171 static void channel_force_xfree(channel_t *chan);
    172 static void channel_free_list(smartlist_t *channels,
    173                               int mark_for_close);
    174 static void channel_listener_free_list(smartlist_t *channels,
    175                                        int mark_for_close);
    176 static void channel_listener_force_xfree(channel_listener_t *chan_l);
    177 
    178 /***********************************
    179 * Channel state utility functions *
    180 **********************************/
    181 
    182 /**
    183 * Indicate whether a given channel state is valid.
    184 */
    185 int
    186 channel_state_is_valid(channel_state_t state)
    187 {
    188  int is_valid;
    189 
    190  switch (state) {
    191    case CHANNEL_STATE_CLOSED:
    192    case CHANNEL_STATE_CLOSING:
    193    case CHANNEL_STATE_ERROR:
    194    case CHANNEL_STATE_MAINT:
    195    case CHANNEL_STATE_OPENING:
    196    case CHANNEL_STATE_OPEN:
    197      is_valid = 1;
    198      break;
    199    case CHANNEL_STATE_LAST:
    200    default:
    201      is_valid = 0;
    202  }
    203 
    204  return is_valid;
    205 }
    206 
    207 /**
    208 * Indicate whether a given channel listener state is valid.
    209 */
    210 int
    211 channel_listener_state_is_valid(channel_listener_state_t state)
    212 {
    213  int is_valid;
    214 
    215  switch (state) {
    216    case CHANNEL_LISTENER_STATE_CLOSED:
    217    case CHANNEL_LISTENER_STATE_LISTENING:
    218    case CHANNEL_LISTENER_STATE_CLOSING:
    219    case CHANNEL_LISTENER_STATE_ERROR:
    220      is_valid = 1;
    221      break;
    222    case CHANNEL_LISTENER_STATE_LAST:
    223    default:
    224      is_valid = 0;
    225  }
    226 
    227  return is_valid;
    228 }
    229 
    230 /**
    231 * Indicate whether a channel state transition is valid.
    232 *
    233 * This function takes two channel states and indicates whether a
    234 * transition between them is permitted (see the state definitions and
    235 * transition table in or.h at the channel_state_t typedef).
    236 */
    237 int
    238 channel_state_can_transition(channel_state_t from, channel_state_t to)
    239 {
    240  int is_valid;
    241 
    242  switch (from) {
    243    case CHANNEL_STATE_CLOSED:
    244      is_valid = (to == CHANNEL_STATE_OPENING);
    245      break;
    246    case CHANNEL_STATE_CLOSING:
    247      is_valid = (to == CHANNEL_STATE_CLOSED ||
    248                  to == CHANNEL_STATE_ERROR);
    249      break;
    250    case CHANNEL_STATE_ERROR:
    251      is_valid = 0;
    252      break;
    253    case CHANNEL_STATE_MAINT:
    254      is_valid = (to == CHANNEL_STATE_CLOSING ||
    255                  to == CHANNEL_STATE_ERROR ||
    256                  to == CHANNEL_STATE_OPEN);
    257      break;
    258    case CHANNEL_STATE_OPENING:
    259      is_valid = (to == CHANNEL_STATE_CLOSING ||
    260                  to == CHANNEL_STATE_ERROR ||
    261                  to == CHANNEL_STATE_OPEN);
    262      break;
    263    case CHANNEL_STATE_OPEN:
    264      is_valid = (to == CHANNEL_STATE_CLOSING ||
    265                  to == CHANNEL_STATE_ERROR ||
    266                  to == CHANNEL_STATE_MAINT);
    267      break;
    268    case CHANNEL_STATE_LAST:
    269    default:
    270      is_valid = 0;
    271  }
    272 
    273  return is_valid;
    274 }
    275 
    276 /**
    277 * Indicate whether a channel listener state transition is valid.
    278 *
    279 * This function takes two channel listener states and indicates whether a
    280 * transition between them is permitted (see the state definitions and
    281 * transition table in or.h at the channel_listener_state_t typedef).
    282 */
    283 int
    284 channel_listener_state_can_transition(channel_listener_state_t from,
    285                                      channel_listener_state_t to)
    286 {
    287  int is_valid;
    288 
    289  switch (from) {
    290    case CHANNEL_LISTENER_STATE_CLOSED:
    291      is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
    292      break;
    293    case CHANNEL_LISTENER_STATE_CLOSING:
    294      is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
    295                  to == CHANNEL_LISTENER_STATE_ERROR);
    296      break;
    297    case CHANNEL_LISTENER_STATE_ERROR:
    298      is_valid = 0;
    299      break;
    300    case CHANNEL_LISTENER_STATE_LISTENING:
    301      is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
    302                  to == CHANNEL_LISTENER_STATE_ERROR);
    303      break;
    304    case CHANNEL_LISTENER_STATE_LAST:
    305    default:
    306      is_valid = 0;
    307  }
    308 
    309  return is_valid;
    310 }
    311 
    312 /**
    313 * Return a human-readable description for a channel state.
    314 */
    315 const char *
    316 channel_state_to_string(channel_state_t state)
    317 {
    318  const char *descr;
    319 
    320  switch (state) {
    321    case CHANNEL_STATE_CLOSED:
    322      descr = "closed";
    323      break;
    324    case CHANNEL_STATE_CLOSING:
    325      descr = "closing";
    326      break;
    327    case CHANNEL_STATE_ERROR:
    328      descr = "channel error";
    329      break;
    330    case CHANNEL_STATE_MAINT:
    331      descr = "temporarily suspended for maintenance";
    332      break;
    333    case CHANNEL_STATE_OPENING:
    334      descr = "opening";
    335      break;
    336    case CHANNEL_STATE_OPEN:
    337      descr = "open";
    338      break;
    339    case CHANNEL_STATE_LAST:
    340    default:
    341      descr = "unknown or invalid channel state";
    342  }
    343 
    344  return descr;
    345 }
    346 
    347 /**
    348 * Return a human-readable description for a channel listener state.
    349 */
    350 const char *
    351 channel_listener_state_to_string(channel_listener_state_t state)
    352 {
    353  const char *descr;
    354 
    355  switch (state) {
    356    case CHANNEL_LISTENER_STATE_CLOSED:
    357      descr = "closed";
    358      break;
    359    case CHANNEL_LISTENER_STATE_CLOSING:
    360      descr = "closing";
    361      break;
    362    case CHANNEL_LISTENER_STATE_ERROR:
    363      descr = "channel listener error";
    364      break;
    365    case CHANNEL_LISTENER_STATE_LISTENING:
    366      descr = "listening";
    367      break;
    368    case CHANNEL_LISTENER_STATE_LAST:
    369    default:
    370      descr = "unknown or invalid channel listener state";
    371  }
    372 
    373  return descr;
    374 }
    375 
    376 /***************************************
    377 * Channel registration/unregistration *
    378 ***************************************/
    379 
    380 /**
    381 * Register a channel.
    382 *
    383 * This function registers a newly created channel in the global lists/maps
    384 * of active channels.
    385 */
    386 void
    387 channel_register(channel_t *chan)
    388 {
    389  tor_assert(chan);
    390  tor_assert(chan->global_identifier);
    391 
    392  /* No-op if already registered */
    393  if (chan->registered) return;
    394 
    395  log_debug(LD_CHANNEL,
    396            "Registering channel %p (ID %"PRIu64 ") "
    397            "in state %s (%d) with digest %s",
    398            chan, (chan->global_identifier),
    399            channel_state_to_string(chan->state), chan->state,
    400            hex_str(chan->identity_digest, DIGEST_LEN));
    401 
    402  /* Make sure we have all_channels, then add it */
    403  if (!all_channels) all_channels = smartlist_new();
    404  smartlist_add(all_channels, chan);
    405  channel_t *oldval = HT_REPLACE(channel_gid_map, &channel_gid_map, chan);
    406  tor_assert(! oldval);
    407 
    408  /* Is it finished? */
    409  if (CHANNEL_FINISHED(chan)) {
    410    /* Put it in the finished list, creating it if necessary */
    411    if (!finished_channels) finished_channels = smartlist_new();
    412    smartlist_add(finished_channels, chan);
    413    mainloop_schedule_postloop_cleanup();
    414  } else {
    415    /* Put it in the active list, creating it if necessary */
    416    if (!active_channels) active_channels = smartlist_new();
    417    smartlist_add(active_channels, chan);
    418 
    419    if (!CHANNEL_IS_CLOSING(chan)) {
    420      /* It should have a digest set */
    421      if (!tor_digest_is_zero(chan->identity_digest)) {
    422        /* Yeah, we're good, add it to the map */
    423        channel_add_to_digest_map(chan);
    424      } else {
    425        log_info(LD_CHANNEL,
    426                "Channel %p (global ID %"PRIu64 ") "
    427                "in state %s (%d) registered with no identity digest",
    428                chan, (chan->global_identifier),
    429                channel_state_to_string(chan->state), chan->state);
    430      }
    431    }
    432  }
    433 
    434  /* Mark it as registered */
    435  chan->registered = 1;
    436 }
    437 
    438 /**
    439 * Unregister a channel.
    440 *
    441 * This function removes a channel from the global lists and maps and is used
    442 * when freeing a closed/errored channel.
    443 */
    444 void
    445 channel_unregister(channel_t *chan)
    446 {
    447  tor_assert(chan);
    448 
    449  /* No-op if not registered */
    450  if (!(chan->registered)) return;
    451 
    452  /* Is it finished? */
    453  if (CHANNEL_FINISHED(chan)) {
    454    /* Get it out of the finished list */
    455    if (finished_channels) smartlist_remove(finished_channels, chan);
    456  } else {
    457    /* Get it out of the active list */
    458    if (active_channels) smartlist_remove(active_channels, chan);
    459  }
    460 
    461  /* Get it out of all_channels */
    462  if (all_channels) smartlist_remove(all_channels, chan);
    463  channel_t *oldval = HT_REMOVE(channel_gid_map, &channel_gid_map, chan);
    464  tor_assert(oldval == NULL || oldval == chan);
    465 
    466  /* Mark it as unregistered */
    467  chan->registered = 0;
    468 
    469  /* Should it be in the digest map? */
    470  if (!tor_digest_is_zero(chan->identity_digest) &&
    471      !(CHANNEL_CONDEMNED(chan))) {
    472    /* Remove it */
    473    channel_remove_from_digest_map(chan);
    474  }
    475 }
    476 
    477 /**
    478 * Register a channel listener.
    479 *
    480 * This function registers a newly created channel listener in the global
    481 * lists/maps of active channel listeners.
    482 */
    483 void
    484 channel_listener_register(channel_listener_t *chan_l)
    485 {
    486  tor_assert(chan_l);
    487 
    488  /* No-op if already registered */
    489  if (chan_l->registered) return;
    490 
    491  log_debug(LD_CHANNEL,
    492            "Registering channel listener %p (ID %"PRIu64 ") "
    493            "in state %s (%d)",
    494            chan_l, (chan_l->global_identifier),
    495            channel_listener_state_to_string(chan_l->state),
    496            chan_l->state);
    497 
    498  /* Make sure we have all_listeners, then add it */
    499  if (!all_listeners) all_listeners = smartlist_new();
    500  smartlist_add(all_listeners, chan_l);
    501 
    502  /* Is it finished? */
    503  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
    504      chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
    505    /* Put it in the finished list, creating it if necessary */
    506    if (!finished_listeners) finished_listeners = smartlist_new();
    507    smartlist_add(finished_listeners, chan_l);
    508  } else {
    509    /* Put it in the active list, creating it if necessary */
    510    if (!active_listeners) active_listeners = smartlist_new();
    511    smartlist_add(active_listeners, chan_l);
    512  }
    513 
    514  /* Mark it as registered */
    515  chan_l->registered = 1;
    516 }
    517 
    518 /**
    519 * Unregister a channel listener.
    520 *
    521 * This function removes a channel listener from the global lists and maps
    522 * and is used when freeing a closed/errored channel listener.
    523 */
    524 void
    525 channel_listener_unregister(channel_listener_t *chan_l)
    526 {
    527  tor_assert(chan_l);
    528 
    529  /* No-op if not registered */
    530  if (!(chan_l->registered)) return;
    531 
    532  /* Is it finished? */
    533  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
    534      chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
    535    /* Get it out of the finished list */
    536    if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
    537  } else {
    538    /* Get it out of the active list */
    539    if (active_listeners) smartlist_remove(active_listeners, chan_l);
    540  }
    541 
    542  /* Get it out of all_listeners */
    543 if (all_listeners) smartlist_remove(all_listeners, chan_l);
    544 
    545  /* Mark it as unregistered */
    546  chan_l->registered = 0;
    547 }
    548 
    549 /*********************************
    550 * Channel digest map maintenance
    551 *********************************/
    552 
    553 /**
    554 * Add a channel to the digest map.
    555 *
    556 * This function adds a channel to the digest map and inserts it into the
    557 * correct linked list if channels with that remote endpoint identity digest
    558 * already exist.
    559 */
    560 STATIC void
    561 channel_add_to_digest_map(channel_t *chan)
    562 {
    563  channel_idmap_entry_t *ent, search;
    564 
    565  tor_assert(chan);
    566 
    567  /* Assert that the state makes sense */
    568  tor_assert(!CHANNEL_CONDEMNED(chan));
    569 
    570  /* Assert that there is a digest */
    571  tor_assert(!tor_digest_is_zero(chan->identity_digest));
    572 
    573  memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
    574  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
    575  if (! ent) {
    576    ent = tor_malloc(sizeof(channel_idmap_entry_t));
    577    memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
    578    TOR_LIST_INIT(&ent->channel_list);
    579    HT_INSERT(channel_idmap, &channel_identity_map, ent);
    580  }
    581  TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
    582 
    583  log_debug(LD_CHANNEL,
    584            "Added channel %p (global ID %"PRIu64 ") "
    585            "to identity map in state %s (%d) with digest %s",
    586            chan, (chan->global_identifier),
    587            channel_state_to_string(chan->state), chan->state,
    588            hex_str(chan->identity_digest, DIGEST_LEN));
    589 }
    590 
    591 /**
    592 * Remove a channel from the digest map.
    593 *
    594 * This function removes a channel from the digest map and the linked list of
    595 * channels for that digest if more than one exists.
    596 */
    597 static void
    598 channel_remove_from_digest_map(channel_t *chan)
    599 {
    600  channel_idmap_entry_t *ent, search;
    601 
    602  tor_assert(chan);
    603 
    604  /* Assert that there is a digest */
    605  tor_assert(!tor_digest_is_zero(chan->identity_digest));
    606 
    607  /* Pull it out of its list, wherever that list is */
    608  TOR_LIST_REMOVE(chan, next_with_same_id);
    609 
    610  memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
    611  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
    612 
    613  /* Look for it in the map */
    614  if (ent) {
    615    /* Okay, it's here */
    616 
    617    if (TOR_LIST_EMPTY(&ent->channel_list)) {
    618      HT_REMOVE(channel_idmap, &channel_identity_map, ent);
    619      tor_free(ent);
    620    }
    621 
    622    log_debug(LD_CHANNEL,
    623              "Removed channel %p (global ID %"PRIu64 ") from "
    624              "identity map in state %s (%d) with digest %s",
    625              chan, (chan->global_identifier),
    626              channel_state_to_string(chan->state), chan->state,
    627              hex_str(chan->identity_digest, DIGEST_LEN));
    628  } else {
    629    /* Shouldn't happen */
    630    log_warn(LD_BUG,
    631             "Trying to remove channel %p (global ID %"PRIu64 ") with "
    632             "digest %s from identity map, but couldn't find any with "
    633             "that digest",
    634             chan, (chan->global_identifier),
    635             hex_str(chan->identity_digest, DIGEST_LEN));
    636  }
    637 }
    638 
    639 /****************************
    640 * Channel lookup functions *
    641 ***************************/
    642 
    643 /**
    644 * Find channel by global ID.
    645 *
    646 * This function searches for a channel by the global_identifier assigned
    647 * at initialization time.  This identifier is unique for the lifetime of the
    648 * Tor process.
    649 */
    650 channel_t *
    651 channel_find_by_global_id(uint64_t global_identifier)
    652 {
    653  channel_t lookup;
    654  channel_t *rv = NULL;
    655 
    656  lookup.global_identifier = global_identifier;
    657  rv = HT_FIND(channel_gid_map, &channel_gid_map, &lookup);
    658  if (rv) {
    659    tor_assert(rv->global_identifier == global_identifier);
    660  }
    661 
    662  return rv;
    663 }
    664 
    665 /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
    666 * as its identity keys.  If either is NULL, do not check for a match. */
    667 int
    668 channel_remote_identity_matches(const channel_t *chan,
    669                                const char *rsa_id_digest,
    670                                const ed25519_public_key_t *ed_id)
    671 {
    672  if (BUG(!chan))
    673    return 0;
    674  if (rsa_id_digest) {
    675    if (tor_memneq(rsa_id_digest, chan->identity_digest, DIGEST_LEN))
    676      return 0;
    677  }
    678  if (ed_id) {
    679    if (tor_memneq(ed_id->pubkey, chan->ed25519_identity.pubkey,
    680                   ED25519_PUBKEY_LEN))
    681      return 0;
    682  }
    683  return 1;
    684 }
    685 
    686 /**
    687 * Find channel by RSA/Ed25519 identity of of the remote endpoint.
    688 *
    689 * This function looks up a channel by the digest of its remote endpoint's RSA
    690 * identity key.  If <b>ed_id</b> is provided and nonzero, only a channel
    691 * matching the <b>ed_id</b> will be returned.
    692 *
    693 * It's possible that more than one channel to a given endpoint exists.  Use
    694 * channel_next_with_rsa_identity() to walk the list of channels; make sure
    695 * to test for Ed25519 identity match too (as appropriate)
    696 */
    697 channel_t *
    698 channel_find_by_remote_identity(const char *rsa_id_digest,
    699                                const ed25519_public_key_t *ed_id)
    700 {
    701  channel_t *rv = NULL;
    702  channel_idmap_entry_t *ent, search;
    703 
    704  tor_assert(rsa_id_digest); /* For now, we require that every channel have
    705                              * an RSA identity, and that every lookup
    706                              * contain an RSA identity */
    707  if (ed_id && ed25519_public_key_is_zero(ed_id)) {
    708    /* Treat zero as meaning "We don't care about the presence or absence of
    709     * an Ed key", not "There must be no Ed key". */
    710    ed_id = NULL;
    711  }
    712 
    713  memcpy(search.digest, rsa_id_digest, DIGEST_LEN);
    714  ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
    715  if (ent) {
    716    rv = TOR_LIST_FIRST(&ent->channel_list);
    717  }
    718  while (rv && ! channel_remote_identity_matches(rv, rsa_id_digest, ed_id)) {
    719    rv = channel_next_with_rsa_identity(rv);
    720  }
    721 
    722  return rv;
    723 }
    724 
    725 /**
    726 * Get next channel with digest.
    727 *
    728 * This function takes a channel and finds the next channel in the list
    729 * with the same digest.
    730 */
    731 channel_t *
    732 channel_next_with_rsa_identity(channel_t *chan)
    733 {
    734  tor_assert(chan);
    735 
    736  return TOR_LIST_NEXT(chan, next_with_same_id);
    737 }
    738 
    739 /**
    740 * Relays run this once an hour to look over our list of channels to other
    741 * relays. It prints out some statistics if there are multiple connections
    742 * to many relays.
    743 *
    744 * This function is similar to connection_or_set_bad_connections(),
    745 * and probably could be adapted to replace it, if it was modified to actually
    746 * take action on any of these connections.
    747 */
    748 void
    749 channel_check_for_duplicates(void)
    750 {
    751  channel_idmap_entry_t **iter;
    752  channel_t *chan;
    753  int total_dirauth_connections = 0, total_dirauths = 0;
    754  int total_relay_connections = 0, total_relays = 0, total_canonical = 0;
    755  int total_half_canonical = 0;
    756  int total_gt_one_connection = 0, total_gt_two_connections = 0;
    757  int total_gt_four_connections = 0;
    758 
    759  HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
    760    int connections_to_relay = 0;
    761    const char *id_digest = (char *) (*iter)->digest;
    762 
    763    /* Only consider relay connections */
    764    if (!connection_or_digest_is_known_relay(id_digest))
    765      continue;
    766 
    767    total_relays++;
    768 
    769    const bool is_dirauth = router_digest_is_trusted_dir(id_digest);
    770    if (is_dirauth)
    771      total_dirauths++;
    772 
    773    for (chan = TOR_LIST_FIRST(&(*iter)->channel_list); chan;
    774        chan = channel_next_with_rsa_identity(chan)) {
    775 
    776      if (CHANNEL_CONDEMNED(chan) || !CHANNEL_IS_OPEN(chan))
    777        continue;
    778 
    779      connections_to_relay++;
    780      total_relay_connections++;
    781      if (is_dirauth)
    782        total_dirauth_connections++;
    783 
    784      if (chan->is_canonical(chan)) total_canonical++;
    785 
    786      if (!chan->is_canonical_to_peer && chan->is_canonical(chan)) {
    787        total_half_canonical++;
    788      }
    789    }
    790 
    791    if (connections_to_relay > 1) total_gt_one_connection++;
    792    if (connections_to_relay > 2) total_gt_two_connections++;
    793    if (connections_to_relay > 4) total_gt_four_connections++;
    794  }
    795 
    796  /* Don't bother warning about excessive connections unless we have
    797   * at least this many connections, total.
    798   */
    799 #define MIN_RELAY_CONNECTIONS_TO_WARN 25
    800  /* If the average number of connections for a regular relay is more than
    801   * this, that's too high.
    802   */
    803 #define MAX_AVG_RELAY_CONNECTIONS 1.5
    804  /* If the average number of connections for a dirauth is more than
    805   * this, that's too high.
    806   */
    807 #define MAX_AVG_DIRAUTH_CONNECTIONS 4
    808 
    809  /* How many connections total would be okay, given the number of
    810   * relays and dirauths that we have connections to? */
    811  const int max_tolerable_connections = (int)(
    812    (total_relays-total_dirauths) * MAX_AVG_RELAY_CONNECTIONS +
    813    total_dirauths * MAX_AVG_DIRAUTH_CONNECTIONS);
    814 
    815  /* If we average 1.5 or more connections per relay, something is wrong */
    816  if (total_relays > MIN_RELAY_CONNECTIONS_TO_WARN &&
    817      total_relay_connections > max_tolerable_connections) {
    818    log_notice(LD_OR,
    819        "Your relay has a very large number of connections to other relays. "
    820        "Is your outbound address the same as your relay address? "
    821        "Found %d connections to authorities, %d connections to %d relays. "
    822        "Found %d current canonical connections, "
    823        "in %d of which we were a non-canonical peer. "
    824        "%d relays had more than 1 connection, %d had more than 2, and "
    825        "%d had more than 4 connections.",
    826        total_dirauth_connections, total_relay_connections,
    827        total_relays, total_canonical, total_half_canonical,
    828        total_gt_one_connection, total_gt_two_connections,
    829        total_gt_four_connections);
    830  } else {
    831    log_info(LD_OR, "Performed connection pruning. "
    832        "Found %d connections to authorities, %d connections to %d relays. "
    833        "Found %d current canonical connections, "
    834        "in %d of which we were a non-canonical peer. "
    835        "%d relays had more than 1 connection, %d had more than 2, and "
    836        "%d had more than 4 connections.",
    837        total_dirauth_connections, total_relay_connections,
    838        total_relays, total_canonical, total_half_canonical,
    839        total_gt_one_connection, total_gt_two_connections,
    840        total_gt_four_connections);
    841  }
    842 }
    843 
    844 /**
    845 * Initialize a channel.
    846 *
    847 * This function should be called by subclasses to set up some per-channel
    848 * variables.  I.e., this is the superclass constructor.  Before this, the
    849 * channel should be allocated with tor_malloc_zero().
    850 */
    851 void
    852 channel_init(channel_t *chan)
    853 {
    854  tor_assert(chan);
    855 
    856  /* Assign an ID and bump the counter */
    857  chan->global_identifier = ++n_channels_allocated;
    858 
    859  /* Init timestamp */
    860  chan->timestamp_last_had_circuits = time(NULL);
    861 
    862  /* Warn about exhausted circuit IDs no more than hourly. */
    863  chan->last_warned_circ_ids_exhausted.rate = 3600;
    864 
    865  /* Initialize list entries. */
    866  memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
    867 
    868  /* Timestamp it */
    869  channel_timestamp_created(chan);
    870 
    871  /* It hasn't been open yet. */
    872  chan->has_been_open = 0;
    873 
    874  /* Scheduler state is idle */
    875  chan->scheduler_state = SCHED_CHAN_IDLE;
    876 
    877  /* Channel is not in the scheduler heap. */
    878  chan->sched_heap_idx = -1;
    879 
    880  tor_addr_make_unspec(&chan->addr_according_to_peer);
    881 }
    882 
    883 /**
    884 * Initialize a channel listener.
    885 *
    886 * This function should be called by subclasses to set up some per-channel
    887 * variables.  I.e., this is the superclass constructor.  Before this, the
    888 * channel listener should be allocated with tor_malloc_zero().
    889 */
    890 void
    891 channel_init_listener(channel_listener_t *chan_l)
    892 {
    893  tor_assert(chan_l);
    894 
    895  /* Assign an ID and bump the counter */
    896  chan_l->global_identifier = ++n_channels_allocated;
    897 
    898  /* Timestamp it */
    899  channel_listener_timestamp_created(chan_l);
    900 }
    901 
    902 /**
    903 * Free a channel; nothing outside of channel.c and subclasses should call
    904 * this - it frees channels after they have closed and been unregistered.
    905 */
    906 void
    907 channel_free_(channel_t *chan)
    908 {
    909  if (!chan) return;
    910 
    911  /* It must be closed or errored */
    912  tor_assert(CHANNEL_FINISHED(chan));
    913 
    914  /* It must be deregistered */
    915  tor_assert(!(chan->registered));
    916 
    917  log_debug(LD_CHANNEL,
    918            "Freeing channel %"PRIu64 " at %p",
    919            (chan->global_identifier), chan);
    920 
    921  /* Get this one out of the scheduler */
    922  scheduler_release_channel(chan);
    923 
    924  /*
    925   * Get rid of cmux policy before we do anything, so cmux policies don't
    926   * see channels in weird half-freed states.
    927   */
    928  if (chan->cmux) {
    929    circuitmux_set_policy(chan->cmux, NULL);
    930  }
    931 
    932  /* Remove all timers and associated handle entries now */
    933  timer_free(chan->padding_timer);
    934  channel_handle_free(chan->timer_handle);
    935  channel_handles_clear(chan);
    936 
    937  /* Call a free method if there is one */
    938  if (chan->free_fn) chan->free_fn(chan);
    939 
    940  channel_clear_remote_end(chan);
    941 
    942  /* Get rid of cmux */
    943  if (chan->cmux) {
    944    circuitmux_detach_all_circuits(chan->cmux, NULL);
    945    circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
    946    circuitmux_free(chan->cmux);
    947    chan->cmux = NULL;
    948  }
    949 
    950  tor_free(chan);
    951 }
    952 
    953 /**
    954 * Free a channel listener; nothing outside of channel.c and subclasses
    955 * should call this - it frees channel listeners after they have closed and
    956 * been unregistered.
    957 */
    958 void
    959 channel_listener_free_(channel_listener_t *chan_l)
    960 {
    961  if (!chan_l) return;
    962 
    963  log_debug(LD_CHANNEL,
    964            "Freeing channel_listener_t %"PRIu64 " at %p",
    965            (chan_l->global_identifier),
    966            chan_l);
    967 
    968  /* It must be closed or errored */
    969  tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
    970             chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
    971  /* It must be deregistered */
    972  tor_assert(!(chan_l->registered));
    973 
    974  /* Call a free method if there is one */
    975  if (chan_l->free_fn) chan_l->free_fn(chan_l);
    976 
    977  tor_free(chan_l);
    978 }
    979 
    980 /**
    981 * Free a channel and skip the state/registration asserts; this internal-
    982 * use-only function should be called only from channel_free_all() when
    983 * shutting down the Tor process.
    984 */
    985 static void
    986 channel_force_xfree(channel_t *chan)
    987 {
    988  tor_assert(chan);
    989 
    990  log_debug(LD_CHANNEL,
    991            "Force-freeing channel %"PRIu64 " at %p",
    992            (chan->global_identifier), chan);
    993 
    994  /* Get this one out of the scheduler */
    995  scheduler_release_channel(chan);
    996 
    997  /*
    998   * Get rid of cmux policy before we do anything, so cmux policies don't
    999   * see channels in weird half-freed states.
   1000   */
   1001  if (chan->cmux) {
   1002    circuitmux_set_policy(chan->cmux, NULL);
   1003  }
   1004 
   1005  /* Remove all timers and associated handle entries now */
   1006  timer_free(chan->padding_timer);
   1007  channel_handle_free(chan->timer_handle);
   1008  channel_handles_clear(chan);
   1009 
   1010  /* Call a free method if there is one */
   1011  if (chan->free_fn) chan->free_fn(chan);
   1012 
   1013  channel_clear_remote_end(chan);
   1014 
   1015  /* Get rid of cmux */
   1016  if (chan->cmux) {
   1017    circuitmux_free(chan->cmux);
   1018    chan->cmux = NULL;
   1019  }
   1020 
   1021  tor_free(chan);
   1022 }
   1023 
   1024 /**
   1025 * Free a channel listener and skip the state/registration asserts; this
   1026 * internal-use-only function should be called only from channel_free_all()
   1027 * when shutting down the Tor process.
   1028 */
   1029 static void
   1030 channel_listener_force_xfree(channel_listener_t *chan_l)
   1031 {
   1032  tor_assert(chan_l);
   1033 
   1034  log_debug(LD_CHANNEL,
   1035            "Force-freeing channel_listener_t %"PRIu64 " at %p",
   1036            (chan_l->global_identifier),
   1037            chan_l);
   1038 
   1039  /* Call a free method if there is one */
   1040  if (chan_l->free_fn) chan_l->free_fn(chan_l);
   1041 
   1042  /*
   1043   * The incoming list just gets emptied and freed; we request close on
   1044   * any channels we find there, but since we got called while shutting
   1045   * down they will get deregistered and freed elsewhere anyway.
   1046   */
   1047  if (chan_l->incoming_list) {
   1048    SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
   1049                            channel_t *, qchan) {
   1050      channel_mark_for_close(qchan);
   1051    } SMARTLIST_FOREACH_END(qchan);
   1052 
   1053    smartlist_free(chan_l->incoming_list);
   1054    chan_l->incoming_list = NULL;
   1055  }
   1056 
   1057  tor_free(chan_l);
   1058 }
   1059 
   1060 /**
   1061 * Set the listener for a channel listener.
   1062 *
   1063 * This function sets the handler for new incoming channels on a channel
   1064 * listener.
   1065 */
   1066 void
   1067 channel_listener_set_listener_fn(channel_listener_t *chan_l,
   1068                                channel_listener_fn_ptr listener)
   1069 {
   1070  tor_assert(chan_l);
   1071  tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
   1072 
   1073  log_debug(LD_CHANNEL,
   1074           "Setting listener callback for channel listener %p "
   1075           "(global ID %"PRIu64 ") to %p",
   1076           chan_l, (chan_l->global_identifier),
   1077           listener);
   1078 
   1079  chan_l->listener = listener;
   1080  if (chan_l->listener) channel_listener_process_incoming(chan_l);
   1081 }
   1082 
   1083 /**
   1084 * Return the fixed-length cell handler for a channel.
   1085 *
   1086 * This function gets the handler for incoming fixed-length cells installed
   1087 * on a channel.
   1088 */
   1089 channel_cell_handler_fn_ptr
   1090 channel_get_cell_handler(channel_t *chan)
   1091 {
   1092  tor_assert(chan);
   1093 
   1094  if (CHANNEL_CAN_HANDLE_CELLS(chan))
   1095    return chan->cell_handler;
   1096 
   1097  return NULL;
   1098 }
   1099 
   1100 /**
   1101 * Set both cell handlers for a channel.
   1102 *
   1103 * This function sets both the fixed-length and variable length cell handlers
   1104 * for a channel.
   1105 */
   1106 void
   1107 channel_set_cell_handlers(channel_t *chan,
   1108                          channel_cell_handler_fn_ptr cell_handler)
   1109 {
   1110  tor_assert(chan);
   1111  tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
   1112 
   1113  log_debug(LD_CHANNEL,
   1114           "Setting cell_handler callback for channel %p to %p",
   1115           chan, cell_handler);
   1116 
   1117  /* Change them */
   1118  chan->cell_handler = cell_handler;
   1119 }
   1120 
   1121 /*
   1122 * On closing channels
   1123 *
   1124 * There are three functions that close channels, for use in
   1125 * different circumstances:
   1126 *
   1127 *  - Use channel_mark_for_close() for most cases
   1128 *  - Use channel_close_from_lower_layer() if you are connection_or.c
   1129 *    and the other end closes the underlying connection.
   1130 *  - Use channel_close_for_error() if you are connection_or.c and
   1131 *    some sort of error has occurred.
   1132 */
   1133 
   1134 /**
   1135 * Mark a channel for closure.
   1136 *
   1137 * This function tries to close a channel_t; it will go into the CLOSING
   1138 * state, and eventually the lower layer should put it into the CLOSED or
   1139 * ERROR state.  Then, channel_run_cleanup() will eventually free it.
   1140 */
   1141 void
   1142 channel_mark_for_close(channel_t *chan)
   1143 {
   1144  tor_assert(chan != NULL);
   1145  tor_assert(chan->close != NULL);
   1146 
   1147  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
   1148  if (CHANNEL_CONDEMNED(chan))
   1149    return;
   1150 
   1151  log_debug(LD_CHANNEL,
   1152            "Closing channel %p (global ID %"PRIu64 ") "
   1153            "by request",
   1154            chan, (chan->global_identifier));
   1155 
   1156  /* Note closing by request from above */
   1157  chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
   1158 
   1159  /* Change state to CLOSING */
   1160  channel_change_state(chan, CHANNEL_STATE_CLOSING);
   1161 
   1162  /* Tell the lower layer */
   1163  chan->close(chan);
   1164 
   1165  /*
   1166   * It's up to the lower layer to change state to CLOSED or ERROR when we're
   1167   * ready; we'll try to free channels that are in the finished list from
   1168   * channel_run_cleanup().  The lower layer should do this by calling
   1169   * channel_closed().
   1170   */
   1171 }
   1172 
   1173 /**
   1174 * Mark a channel listener for closure.
   1175 *
   1176 * This function tries to close a channel_listener_t; it will go into the
   1177 * CLOSING state, and eventually the lower layer should put it into the CLOSED
   1178 * or ERROR state.  Then, channel_run_cleanup() will eventually free it.
   1179 */
   1180 void
   1181 channel_listener_mark_for_close(channel_listener_t *chan_l)
   1182 {
   1183  tor_assert(chan_l != NULL);
   1184  tor_assert(chan_l->close != NULL);
   1185 
   1186  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
   1187  if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
   1188      chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
   1189      chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
   1190 
   1191  log_debug(LD_CHANNEL,
   1192            "Closing channel listener %p (global ID %"PRIu64 ") "
   1193            "by request",
   1194            chan_l, (chan_l->global_identifier));
   1195 
   1196  /* Note closing by request from above */
   1197  chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
   1198 
   1199  /* Change state to CLOSING */
   1200  channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
   1201 
   1202  /* Tell the lower layer */
   1203  chan_l->close(chan_l);
   1204 
   1205  /*
   1206   * It's up to the lower layer to change state to CLOSED or ERROR when we're
   1207   * ready; we'll try to free channels that are in the finished list from
   1208   * channel_run_cleanup().  The lower layer should do this by calling
   1209   * channel_listener_closed().
   1210   */
   1211 }
   1212 
   1213 /**
   1214 * Close a channel from the lower layer.
   1215 *
   1216 * Notify the channel code that the channel is being closed due to a non-error
   1217 * condition in the lower layer.  This does not call the close() method, since
   1218 * the lower layer already knows.
   1219 */
   1220 void
   1221 channel_close_from_lower_layer(channel_t *chan)
   1222 {
   1223  tor_assert(chan != NULL);
   1224 
   1225  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
   1226  if (CHANNEL_CONDEMNED(chan))
   1227    return;
   1228 
   1229  log_debug(LD_CHANNEL,
   1230            "Closing channel %p (global ID %"PRIu64 ") "
   1231            "due to lower-layer event",
   1232            chan, (chan->global_identifier));
   1233 
   1234  /* Note closing by event from below */
   1235  chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
   1236 
   1237  /* Change state to CLOSING */
   1238  channel_change_state(chan, CHANNEL_STATE_CLOSING);
   1239 }
   1240 
   1241 /**
   1242 * Notify that the channel is being closed due to an error condition.
   1243 *
   1244 * This function is called by the lower layer implementing the transport
   1245 * when a channel must be closed due to an error condition.  This does not
   1246 * call the channel's close method, since the lower layer already knows.
   1247 */
   1248 void
   1249 channel_close_for_error(channel_t *chan)
   1250 {
   1251  tor_assert(chan != NULL);
   1252 
   1253  /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
   1254  if (CHANNEL_CONDEMNED(chan))
   1255    return;
   1256 
   1257  log_debug(LD_CHANNEL,
   1258            "Closing channel %p due to lower-layer error",
   1259            chan);
   1260 
   1261  /* Note closing by event from below */
   1262  chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
   1263 
   1264  /* Change state to CLOSING */
   1265  channel_change_state(chan, CHANNEL_STATE_CLOSING);
   1266 }
   1267 
   1268 /**
   1269 * Notify that the lower layer is finished closing the channel.
   1270 *
   1271 * This function should be called by the lower layer when a channel
   1272 * is finished closing and it should be regarded as inactive and
   1273 * freed by the channel code.
   1274 */
   1275 void
   1276 channel_closed(channel_t *chan)
   1277 {
   1278  tor_assert(chan);
   1279  tor_assert(CHANNEL_CONDEMNED(chan));
   1280 
   1281  /* No-op if already inactive */
   1282  if (CHANNEL_FINISHED(chan))
   1283    return;
   1284 
   1285  /* Inform any pending (not attached) circs that they should
   1286   * give up. */
   1287  if (! chan->has_been_open)
   1288    circuit_n_chan_done(chan, 0);
   1289 
   1290  /* Now close all the attached circuits on it. */
   1291  circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
   1292 
   1293  if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
   1294    channel_change_state(chan, CHANNEL_STATE_CLOSED);
   1295  } else {
   1296    channel_change_state(chan, CHANNEL_STATE_ERROR);
   1297  }
   1298 }
   1299 
   1300 /**
   1301 * Clear the identity_digest of a channel.
   1302 *
   1303 * This function clears the identity digest of the remote endpoint for a
   1304 * channel; this is intended for use by the lower layer.
   1305 */
   1306 void
   1307 channel_clear_identity_digest(channel_t *chan)
   1308 {
   1309  int state_not_in_map;
   1310 
   1311  tor_assert(chan);
   1312 
   1313  log_debug(LD_CHANNEL,
   1314            "Clearing remote endpoint digest on channel %p with "
   1315            "global ID %"PRIu64,
   1316            chan, (chan->global_identifier));
   1317 
   1318  state_not_in_map = CHANNEL_CONDEMNED(chan);
   1319 
   1320  if (!state_not_in_map && chan->registered &&
   1321      !tor_digest_is_zero(chan->identity_digest))
   1322    /* if it's registered get it out of the digest map */
   1323    channel_remove_from_digest_map(chan);
   1324 
   1325  memset(chan->identity_digest, 0,
   1326         sizeof(chan->identity_digest));
   1327 }
   1328 
   1329 /**
   1330 * Set the identity_digest of a channel.
   1331 *
   1332 * This function sets the identity digest of the remote endpoint for a
   1333 * channel; this is intended for use by the lower layer.
   1334 */
   1335 void
   1336 channel_set_identity_digest(channel_t *chan,
   1337                            const char *identity_digest,
   1338                            const ed25519_public_key_t *ed_identity)
   1339 {
   1340  int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
   1341 
   1342  tor_assert(chan);
   1343 
   1344  log_debug(LD_CHANNEL,
   1345            "Setting remote endpoint digest on channel %p with "
   1346            "global ID %"PRIu64 " to digest %s",
   1347            chan, (chan->global_identifier),
   1348            identity_digest ?
   1349              hex_str(identity_digest, DIGEST_LEN) : "(null)");
   1350 
   1351  state_not_in_map = CHANNEL_CONDEMNED(chan);
   1352 
   1353  was_in_digest_map =
   1354    !state_not_in_map &&
   1355    chan->registered &&
   1356    !tor_digest_is_zero(chan->identity_digest);
   1357  should_be_in_digest_map =
   1358    !state_not_in_map &&
   1359    chan->registered &&
   1360    (identity_digest &&
   1361     !tor_digest_is_zero(identity_digest));
   1362 
   1363  if (was_in_digest_map)
   1364    /* We should always remove it; we'll add it back if we're writing
   1365     * in a new digest.
   1366     */
   1367    channel_remove_from_digest_map(chan);
   1368 
   1369  if (identity_digest) {
   1370    memcpy(chan->identity_digest,
   1371           identity_digest,
   1372           sizeof(chan->identity_digest));
   1373  } else {
   1374    memset(chan->identity_digest, 0,
   1375           sizeof(chan->identity_digest));
   1376  }
   1377  if (ed_identity) {
   1378    memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
   1379  } else {
   1380    memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
   1381  }
   1382 
   1383  /* Put it in the digest map if we should */
   1384  if (should_be_in_digest_map)
   1385    channel_add_to_digest_map(chan);
   1386 }
   1387 
   1388 /**
   1389 * Clear the remote end metadata (identity_digest) of a channel.
   1390 *
   1391 * This function clears all the remote end info from a channel; this is
   1392 * intended for use by the lower layer.
   1393 */
   1394 void
   1395 channel_clear_remote_end(channel_t *chan)
   1396 {
   1397  int state_not_in_map;
   1398 
   1399  tor_assert(chan);
   1400 
   1401  log_debug(LD_CHANNEL,
   1402            "Clearing remote endpoint identity on channel %p with "
   1403            "global ID %"PRIu64,
   1404            chan, (chan->global_identifier));
   1405 
   1406  state_not_in_map = CHANNEL_CONDEMNED(chan);
   1407 
   1408  if (!state_not_in_map && chan->registered &&
   1409      !tor_digest_is_zero(chan->identity_digest))
   1410    /* if it's registered get it out of the digest map */
   1411    channel_remove_from_digest_map(chan);
   1412 
   1413  memset(chan->identity_digest, 0,
   1414         sizeof(chan->identity_digest));
   1415 }
   1416 
   1417 /**
   1418 * Write to a channel the given packed cell.
   1419 *
   1420 * Two possible errors can happen. Either the channel is not opened or the
   1421 * lower layer (specialized channel) failed to write it. In both cases, it is
   1422 * the caller responsibility to free the cell.
   1423 */
   1424 static int
   1425 write_packed_cell(channel_t *chan, packed_cell_t *cell)
   1426 {
   1427  int ret = -1;
   1428  size_t cell_bytes;
   1429  uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
   1430 
   1431  tor_assert(chan);
   1432  tor_assert(cell);
   1433 
   1434  /* Assert that the state makes sense for a cell write */
   1435  tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
   1436 
   1437  {
   1438    circid_t circ_id;
   1439    if (packed_cell_is_destroy(chan, cell, &circ_id)) {
   1440      channel_note_destroy_not_pending(chan, circ_id);
   1441    }
   1442  }
   1443 
   1444  /* For statistical purposes, figure out how big this cell is */
   1445  cell_bytes = get_cell_network_size(chan->wide_circ_ids);
   1446 
   1447  /* Can we send it right out?  If so, try */
   1448  if (!CHANNEL_IS_OPEN(chan)) {
   1449    goto done;
   1450  }
   1451 
   1452  /* Write the cell on the connection's outbuf. */
   1453  if (chan->write_packed_cell(chan, cell) < 0) {
   1454    goto done;
   1455  }
   1456  /* Timestamp for transmission */
   1457  channel_timestamp_xmit(chan);
   1458  /* Update the counter */
   1459  ++(chan->n_cells_xmitted);
   1460  chan->n_bytes_xmitted += cell_bytes;
   1461  /* Successfully sent the cell. */
   1462  ret = 0;
   1463 
   1464  /* Update padding statistics for the packed codepath.. */
   1465  rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
   1466  if (command == CELL_PADDING)
   1467    rep_hist_padding_count_write(PADDING_TYPE_CELL);
   1468  if (chan->padding_enabled) {
   1469    rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL);
   1470    if (command == CELL_PADDING)
   1471      rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL);
   1472  }
   1473 
   1474 done:
   1475  return ret;
   1476 }
   1477 
   1478 /**
   1479 * Write a packed cell to a channel.
   1480 *
   1481 * Write a packed cell to a channel using the write_cell() method.  This is
   1482 * called by the transport-independent code to deliver a packed cell to a
   1483 * channel for transmission.
   1484 *
   1485 * Return 0 on success else a negative value. In both cases, the caller should
   1486 * not access the cell anymore, it is freed both on success and error.
   1487 */
   1488 int
   1489 channel_write_packed_cell(channel_t *chan, packed_cell_t *cell)
   1490 {
   1491  int ret = -1;
   1492 
   1493  tor_assert(chan);
   1494  tor_assert(cell);
   1495 
   1496  if (CHANNEL_IS_CLOSING(chan)) {
   1497    log_debug(LD_CHANNEL, "Discarding %p on closing channel %p with "
   1498              "global ID %"PRIu64, cell, chan,
   1499              (chan->global_identifier));
   1500    goto end;
   1501  }
   1502  log_debug(LD_CHANNEL,
   1503            "Writing %p to channel %p with global ID "
   1504            "%"PRIu64, cell, chan, (chan->global_identifier));
   1505 
   1506  ret = write_packed_cell(chan, cell);
   1507 
   1508 end:
   1509  /* Whatever happens, we free the cell. Either an error occurred or the cell
   1510   * was put on the connection outbuf, both cases we have ownership of the
   1511   * cell and we free it. */
   1512  packed_cell_free(cell);
   1513  return ret;
   1514 }
   1515 
   1516 /**
   1517 * Change channel state.
   1518 *
   1519 * This internal and subclass use only function is used to change channel
   1520 * state, performing all transition validity checks and whatever actions
   1521 * are appropriate to the state transition in question.
   1522 */
   1523 static void
   1524 channel_change_state_(channel_t *chan, channel_state_t to_state)
   1525 {
   1526  channel_state_t from_state;
   1527  unsigned char was_active, is_active;
   1528  unsigned char was_in_id_map, is_in_id_map;
   1529 
   1530  tor_assert(chan);
   1531  from_state = chan->state;
   1532 
   1533  tor_assert(channel_state_is_valid(from_state));
   1534  tor_assert(channel_state_is_valid(to_state));
   1535  tor_assert(channel_state_can_transition(chan->state, to_state));
   1536 
   1537  /* Check for no-op transitions */
   1538  if (from_state == to_state) {
   1539    log_debug(LD_CHANNEL,
   1540              "Got no-op transition from \"%s\" to itself on channel %p"
   1541              "(global ID %"PRIu64 ")",
   1542              channel_state_to_string(to_state),
   1543              chan, (chan->global_identifier));
   1544    return;
   1545  }
   1546 
   1547  /* If we're going to a closing or closed state, we must have a reason set */
   1548  if (to_state == CHANNEL_STATE_CLOSING ||
   1549      to_state == CHANNEL_STATE_CLOSED ||
   1550      to_state == CHANNEL_STATE_ERROR) {
   1551    tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
   1552  }
   1553 
   1554  log_debug(LD_CHANNEL,
   1555            "Changing state of channel %p (global ID %"PRIu64
   1556            ") from \"%s\" to \"%s\"",
   1557            chan,
   1558            (chan->global_identifier),
   1559            channel_state_to_string(chan->state),
   1560            channel_state_to_string(to_state));
   1561 
   1562  chan->state = to_state;
   1563 
   1564  /* Need to add to the right lists if the channel is registered */
   1565  if (chan->registered) {
   1566    was_active = !(from_state == CHANNEL_STATE_CLOSED ||
   1567                   from_state == CHANNEL_STATE_ERROR);
   1568    is_active = !(to_state == CHANNEL_STATE_CLOSED ||
   1569                  to_state == CHANNEL_STATE_ERROR);
   1570 
   1571    /* Need to take off active list and put on finished list? */
   1572    if (was_active && !is_active) {
   1573      if (active_channels) smartlist_remove(active_channels, chan);
   1574      if (!finished_channels) finished_channels = smartlist_new();
   1575      smartlist_add(finished_channels, chan);
   1576      mainloop_schedule_postloop_cleanup();
   1577    }
   1578    /* Need to put on active list? */
   1579    else if (!was_active && is_active) {
   1580      if (finished_channels) smartlist_remove(finished_channels, chan);
   1581      if (!active_channels) active_channels = smartlist_new();
   1582      smartlist_add(active_channels, chan);
   1583    }
   1584 
   1585    if (!tor_digest_is_zero(chan->identity_digest)) {
   1586      /* Now we need to handle the identity map */
   1587      was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
   1588                        from_state == CHANNEL_STATE_CLOSED ||
   1589                        from_state == CHANNEL_STATE_ERROR);
   1590      is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
   1591                       to_state == CHANNEL_STATE_CLOSED ||
   1592                       to_state == CHANNEL_STATE_ERROR);
   1593 
   1594      if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
   1595      else if (was_in_id_map && !is_in_id_map)
   1596        channel_remove_from_digest_map(chan);
   1597    }
   1598  }
   1599 
   1600  /*
   1601   * If we're going to a closed/closing state, we don't need scheduling any
   1602   * more; in CHANNEL_STATE_MAINT we can't accept writes.
   1603   */
   1604  if (to_state == CHANNEL_STATE_CLOSING ||
   1605      to_state == CHANNEL_STATE_CLOSED ||
   1606      to_state == CHANNEL_STATE_ERROR) {
   1607    scheduler_release_channel(chan);
   1608  } else if (to_state == CHANNEL_STATE_MAINT) {
   1609    scheduler_channel_doesnt_want_writes(chan);
   1610  }
   1611 }
   1612 
   1613 /**
   1614 * As channel_change_state_, but change the state to any state but open.
   1615 */
   1616 void
   1617 channel_change_state(channel_t *chan, channel_state_t to_state)
   1618 {
   1619  tor_assert(to_state != CHANNEL_STATE_OPEN);
   1620  channel_change_state_(chan, to_state);
   1621 }
   1622 
   1623 /**
   1624 * As channel_change_state, but change the state to open.
   1625 */
   1626 void
   1627 channel_change_state_open(channel_t *chan)
   1628 {
   1629  channel_change_state_(chan, CHANNEL_STATE_OPEN);
   1630 
   1631  /* Tell circuits if we opened and stuff */
   1632  channel_do_open_actions(chan);
   1633  chan->has_been_open = 1;
   1634 }
   1635 
   1636 /**
   1637 * Change channel listener state.
   1638 *
   1639 * This internal and subclass use only function is used to change channel
   1640 * listener state, performing all transition validity checks and whatever
   1641 * actions are appropriate to the state transition in question.
   1642 */
   1643 void
   1644 channel_listener_change_state(channel_listener_t *chan_l,
   1645                              channel_listener_state_t to_state)
   1646 {
   1647  channel_listener_state_t from_state;
   1648  unsigned char was_active, is_active;
   1649 
   1650  tor_assert(chan_l);
   1651  from_state = chan_l->state;
   1652 
   1653  tor_assert(channel_listener_state_is_valid(from_state));
   1654  tor_assert(channel_listener_state_is_valid(to_state));
   1655  tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
   1656 
   1657  /* Check for no-op transitions */
   1658  if (from_state == to_state) {
   1659    log_debug(LD_CHANNEL,
   1660              "Got no-op transition from \"%s\" to itself on channel "
   1661              "listener %p (global ID %"PRIu64 ")",
   1662              channel_listener_state_to_string(to_state),
   1663              chan_l, (chan_l->global_identifier));
   1664    return;
   1665  }
   1666 
   1667  /* If we're going to a closing or closed state, we must have a reason set */
   1668  if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
   1669      to_state == CHANNEL_LISTENER_STATE_CLOSED ||
   1670      to_state == CHANNEL_LISTENER_STATE_ERROR) {
   1671    tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
   1672  }
   1673 
   1674  log_debug(LD_CHANNEL,
   1675            "Changing state of channel listener %p (global ID %"PRIu64
   1676            "from \"%s\" to \"%s\"",
   1677            chan_l, (chan_l->global_identifier),
   1678            channel_listener_state_to_string(chan_l->state),
   1679            channel_listener_state_to_string(to_state));
   1680 
   1681  chan_l->state = to_state;
   1682 
   1683  /* Need to add to the right lists if the channel listener is registered */
   1684  if (chan_l->registered) {
   1685    was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
   1686                   from_state == CHANNEL_LISTENER_STATE_ERROR);
   1687    is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
   1688                  to_state == CHANNEL_LISTENER_STATE_ERROR);
   1689 
   1690    /* Need to take off active list and put on finished list? */
   1691    if (was_active && !is_active) {
   1692      if (active_listeners) smartlist_remove(active_listeners, chan_l);
   1693      if (!finished_listeners) finished_listeners = smartlist_new();
   1694      smartlist_add(finished_listeners, chan_l);
   1695      mainloop_schedule_postloop_cleanup();
   1696    }
   1697    /* Need to put on active list? */
   1698    else if (!was_active && is_active) {
   1699      if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
   1700      if (!active_listeners) active_listeners = smartlist_new();
   1701      smartlist_add(active_listeners, chan_l);
   1702    }
   1703  }
   1704 
   1705  if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
   1706      to_state == CHANNEL_LISTENER_STATE_ERROR) {
   1707    tor_assert(!(chan_l->incoming_list) ||
   1708                smartlist_len(chan_l->incoming_list) == 0);
   1709  }
   1710 }
   1711 
   1712 /* Maximum number of cells that is allowed to flush at once within
   1713 * channel_flush_some_cells(). */
   1714 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
   1715 
   1716 /**
   1717 * Try to flush cells of the given channel chan up to a maximum of num_cells.
   1718 *
   1719 * This is called by the scheduler when it wants to flush cells from the
   1720 * channel's circuit queue(s) to the connection outbuf (not yet on the wire).
   1721 *
   1722 * If the channel is not in state CHANNEL_STATE_OPEN, this does nothing and
   1723 * will return 0 meaning no cells were flushed.
   1724 *
   1725 * If num_cells is -1, we'll try to flush up to the maximum cells allowed
   1726 * defined in MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED.
   1727 *
   1728 * On success, the number of flushed cells are returned and it can never be
   1729 * above num_cells. If 0 is returned, no cells were flushed either because the
   1730 * channel was not opened or we had no cells on the channel. A negative number
   1731 * can NOT be sent back.
   1732 *
   1733 * This function is part of the fast path. */
   1734 MOCK_IMPL(ssize_t,
   1735 channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
   1736 {
   1737  unsigned int unlimited = 0;
   1738  ssize_t flushed = 0;
   1739  int clamped_num_cells;
   1740 
   1741  tor_assert(chan);
   1742 
   1743  if (num_cells < 0) unlimited = 1;
   1744  if (!unlimited && num_cells <= flushed) goto done;
   1745 
   1746  /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
   1747  if (CHANNEL_IS_OPEN(chan)) {
   1748    if (circuitmux_num_cells(chan->cmux) > 0) {
   1749      /* Calculate number of cells, including clamp */
   1750      if (unlimited) {
   1751        clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
   1752      } else {
   1753        if (num_cells - flushed >
   1754            MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
   1755          clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
   1756        } else {
   1757          clamped_num_cells = (int)(num_cells - flushed);
   1758        }
   1759      }
   1760 
   1761      /* Try to get more cells from any active circuits */
   1762      flushed = channel_flush_from_first_active_circuit(
   1763          chan, clamped_num_cells);
   1764    }
   1765  }
   1766 
   1767 done:
   1768  return flushed;
   1769 }
   1770 
   1771 /**
   1772 * Check if any cells are available.
   1773 *
   1774 * This is used by the scheduler to know if the channel has more to flush
   1775 * after a scheduling round.
   1776 */
   1777 MOCK_IMPL(int,
   1778 channel_more_to_flush, (channel_t *chan))
   1779 {
   1780  tor_assert(chan);
   1781 
   1782  if (circuitmux_num_cells(chan->cmux) > 0) return 1;
   1783 
   1784  /* Else no */
   1785  return 0;
   1786 }
   1787 
   1788 /**
   1789 * Notify the channel we're done flushing the output in the lower layer.
   1790 *
   1791 * Connection.c will call this when we've flushed the output; there's some
   1792 * dirreq-related maintenance to do.
   1793 */
   1794 void
   1795 channel_notify_flushed(channel_t *chan)
   1796 {
   1797  tor_assert(chan);
   1798 
   1799  if (chan->dirreq_id != 0)
   1800    geoip_change_dirreq_state(chan->dirreq_id,
   1801                              DIRREQ_TUNNELED,
   1802                              DIRREQ_CHANNEL_BUFFER_FLUSHED);
   1803 }
   1804 
   1805 /**
   1806 * Process the queue of incoming channels on a listener.
   1807 *
   1808 * Use a listener's registered callback to process as many entries in the
   1809 * queue of incoming channels as possible.
   1810 */
   1811 void
   1812 channel_listener_process_incoming(channel_listener_t *listener)
   1813 {
   1814  tor_assert(listener);
   1815 
   1816  /*
   1817   * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
   1818   * while closing a listener.
   1819   */
   1820  tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
   1821             listener->state == CHANNEL_LISTENER_STATE_CLOSING);
   1822  tor_assert(listener->listener);
   1823 
   1824  log_debug(LD_CHANNEL,
   1825            "Processing queue of incoming connections for channel "
   1826            "listener %p (global ID %"PRIu64 ")",
   1827            listener, (listener->global_identifier));
   1828 
   1829  if (!(listener->incoming_list)) return;
   1830 
   1831  SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
   1832                          channel_t *, chan) {
   1833    tor_assert(chan);
   1834 
   1835    log_debug(LD_CHANNEL,
   1836              "Handling incoming channel %p (%"PRIu64 ") "
   1837              "for listener %p (%"PRIu64 ")",
   1838              chan,
   1839              (chan->global_identifier),
   1840              listener,
   1841              (listener->global_identifier));
   1842    /* Make sure this is set correctly */
   1843    channel_mark_incoming(chan);
   1844    listener->listener(listener, chan);
   1845  } SMARTLIST_FOREACH_END(chan);
   1846 
   1847  smartlist_free(listener->incoming_list);
   1848  listener->incoming_list = NULL;
   1849 }
   1850 
   1851 /**
   1852 * Take actions required when a channel becomes open.
   1853 *
   1854 * Handle actions we should do when we know a channel is open; a lot of
   1855 * this comes from the old connection_or_set_state_open() of connection_or.c.
   1856 *
   1857 * Because of this mechanism, future channel_t subclasses should take care
   1858 * not to change a channel from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
   1859 * until there is positive confirmation that the network is operational.
   1860 * In particular, anything UDP-based should not make this transition until a
   1861 * packet is received from the other side.
   1862 */
   1863 void
   1864 channel_do_open_actions(channel_t *chan)
   1865 {
   1866  tor_addr_t remote_addr;
   1867  int started_here;
   1868 
   1869  tor_assert(chan);
   1870 
   1871  started_here = channel_is_outgoing(chan);
   1872 
   1873  if (started_here) {
   1874    circuit_build_times_network_is_live(get_circuit_build_times_mutable());
   1875    router_set_status(chan->identity_digest, 1);
   1876  } else {
   1877    /* only report it to the geoip module if it's a client and it hasn't
   1878     * already been set up for tracking earlier. (Incoming TLS connections
   1879     * are tracked before the handshake.) */
   1880    if (channel_is_client(chan)) {
   1881      if (channel_get_addr_if_possible(chan, &remote_addr)) {
   1882        channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
   1883        if (!tlschan->conn->tracked_for_dos_mitigation) {
   1884          char *transport_name = NULL;
   1885          if (chan->get_transport_name(chan, &transport_name) < 0) {
   1886            transport_name = NULL;
   1887          }
   1888          geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
   1889                                 &remote_addr, transport_name,
   1890                                 time(NULL));
   1891          if (tlschan && tlschan->conn) {
   1892            dos_new_client_conn(tlschan->conn, transport_name);
   1893          }
   1894          tor_free(transport_name);
   1895        }
   1896      }
   1897      /* Otherwise the underlying transport can't tell us this, so skip it */
   1898    }
   1899  }
   1900 
   1901  /* Disable or reduce padding according to user prefs. */
   1902  if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
   1903    if (!get_options()->ConnectionPadding) {
   1904      /* Disable if torrc disabled */
   1905      channelpadding_disable_padding_on_channel(chan);
   1906    } else if (hs_service_allow_non_anonymous_connection(get_options()) &&
   1907               !networkstatus_get_param(NULL,
   1908                                        CHANNELPADDING_SOS_PARAM,
   1909                                        CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
   1910      /* Disable if we're using RSOS and the consensus disabled padding
   1911       * for RSOS */
   1912      channelpadding_disable_padding_on_channel(chan);
   1913    } else if (get_options()->ReducedConnectionPadding) {
   1914      /* Padding can be forced and/or reduced by clients, regardless of if
   1915       * the channel supports it */
   1916      channelpadding_reduce_padding_on_channel(chan);
   1917    }
   1918  }
   1919 
   1920  circuit_n_chan_done(chan, 1);
   1921 }
   1922 
   1923 /**
   1924 * Queue an incoming channel on a listener.
   1925 *
   1926 * Internal and subclass use only function to queue an incoming channel from
   1927 * a listener.  A subclass of channel_listener_t should call this when a new
   1928 * incoming channel is created.
   1929 */
   1930 void
   1931 channel_listener_queue_incoming(channel_listener_t *listener,
   1932                                channel_t *incoming)
   1933 {
   1934  int need_to_queue = 0;
   1935 
   1936  tor_assert(listener);
   1937  tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
   1938  tor_assert(incoming);
   1939 
   1940  log_debug(LD_CHANNEL,
   1941            "Queueing incoming channel %p (global ID %"PRIu64 ") on "
   1942            "channel listener %p (global ID %"PRIu64 ")",
   1943            incoming, (incoming->global_identifier),
   1944            listener, (listener->global_identifier));
   1945 
   1946  /* Do we need to queue it, or can we just call the listener right away? */
   1947  if (!(listener->listener)) need_to_queue = 1;
   1948  if (listener->incoming_list &&
   1949      (smartlist_len(listener->incoming_list) > 0))
   1950    need_to_queue = 1;
   1951 
   1952  /* If we need to queue and have no queue, create one */
   1953  if (need_to_queue && !(listener->incoming_list)) {
   1954    listener->incoming_list = smartlist_new();
   1955  }
   1956 
   1957  /* Bump the counter and timestamp it */
   1958  channel_listener_timestamp_active(listener);
   1959  channel_listener_timestamp_accepted(listener);
   1960  ++(listener->n_accepted);
   1961 
   1962  /* If we don't need to queue, process it right away */
   1963  if (!need_to_queue) {
   1964    tor_assert(listener->listener);
   1965    listener->listener(listener, incoming);
   1966  }
   1967  /*
   1968   * Otherwise, we need to queue; queue and then process the queue if
   1969   * we can.
   1970   */
   1971  else {
   1972    tor_assert(listener->incoming_list);
   1973    smartlist_add(listener->incoming_list, incoming);
   1974    if (listener->listener) channel_listener_process_incoming(listener);
   1975  }
   1976 }
   1977 
   1978 /**
   1979 * Process a cell from the given channel.
   1980 */
   1981 void
   1982 channel_process_cell(channel_t *chan, cell_t *cell)
   1983 {
   1984  tor_assert(chan);
   1985  tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
   1986             CHANNEL_IS_OPEN(chan));
   1987  tor_assert(cell);
   1988 
   1989  /* Nothing we can do if we have no registered cell handlers */
   1990  if (!chan->cell_handler)
   1991    return;
   1992 
   1993  /* Timestamp for receiving */
   1994  channel_timestamp_recv(chan);
   1995  /* Update received counter. */
   1996  ++(chan->n_cells_recved);
   1997  chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
   1998 
   1999  log_debug(LD_CHANNEL,
   2000            "Processing incoming cell_t %p for channel %p (global ID "
   2001            "%"PRIu64 ")", cell, chan,
   2002            (chan->global_identifier));
   2003  chan->cell_handler(chan, cell);
   2004 }
   2005 
   2006 /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
   2007 * *<b>circid_out</b> to its circuit ID, and return true.  Otherwise, return
   2008 * false. */
   2009 /* XXXX Move this function. */
   2010 int
   2011 packed_cell_is_destroy(channel_t *chan,
   2012                       const packed_cell_t *packed_cell,
   2013                       circid_t *circid_out)
   2014 {
   2015  if (chan->wide_circ_ids) {
   2016    if (packed_cell->body[4] == CELL_DESTROY) {
   2017      *circid_out = ntohl(get_uint32(packed_cell->body));
   2018      return 1;
   2019    }
   2020  } else {
   2021    if (packed_cell->body[2] == CELL_DESTROY) {
   2022      *circid_out = ntohs(get_uint16(packed_cell->body));
   2023      return 1;
   2024    }
   2025  }
   2026  return 0;
   2027 }
   2028 
   2029 /**
   2030 * Send destroy cell on a channel.
   2031 *
   2032 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
   2033 * onto channel <b>chan</b>.  Don't perform range-checking on reason:
   2034 * we may want to propagate reasons from other cells.
   2035 */
   2036 int
   2037 channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
   2038 {
   2039  tor_assert(chan);
   2040  if (circ_id == 0) {
   2041    log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
   2042             "on a channel %"PRIu64 " at %p in state %s (%d)",
   2043             (chan->global_identifier),
   2044             chan, channel_state_to_string(chan->state),
   2045             chan->state);
   2046    return 0;
   2047  }
   2048 
   2049  /* Check to make sure we can send on this channel first */
   2050  if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
   2051    channel_note_destroy_pending(chan, circ_id);
   2052    circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
   2053    log_debug(LD_OR,
   2054              "Sending destroy (circID %u) on channel %p "
   2055              "(global ID %"PRIu64 ")",
   2056              (unsigned)circ_id, chan,
   2057              (chan->global_identifier));
   2058  } else {
   2059    log_warn(LD_BUG,
   2060             "Someone called channel_send_destroy() for circID %u "
   2061             "on a channel %"PRIu64 " at %p in state %s (%d)",
   2062             (unsigned)circ_id, (chan->global_identifier),
   2063             chan, channel_state_to_string(chan->state),
   2064             chan->state);
   2065  }
   2066 
   2067  return 0;
   2068 }
   2069 
   2070 /**
   2071 * Dump channel statistics to the log.
   2072 *
   2073 * This is called from dumpstats() in main.c and spams the log with
   2074 * statistics on channels.
   2075 */
   2076 void
   2077 channel_dumpstats(int severity)
   2078 {
   2079  if (all_channels && smartlist_len(all_channels) > 0) {
   2080    tor_log(severity, LD_GENERAL,
   2081        "Dumping statistics about %d channels:",
   2082        smartlist_len(all_channels));
   2083    tor_log(severity, LD_GENERAL,
   2084        "%d are active, and %d are done and waiting for cleanup",
   2085        (active_channels != NULL) ?
   2086          smartlist_len(active_channels) : 0,
   2087        (finished_channels != NULL) ?
   2088          smartlist_len(finished_channels) : 0);
   2089 
   2090    SMARTLIST_FOREACH(all_channels, channel_t *, chan,
   2091                      channel_dump_statistics(chan, severity));
   2092 
   2093    tor_log(severity, LD_GENERAL,
   2094        "Done spamming about channels now");
   2095  } else {
   2096    tor_log(severity, LD_GENERAL,
   2097        "No channels to dump");
   2098  }
   2099 }
   2100 
   2101 /**
   2102 * Dump channel listener statistics to the log.
   2103 *
   2104 * This is called from dumpstats() in main.c and spams the log with
   2105 * statistics on channel listeners.
   2106 */
   2107 void
   2108 channel_listener_dumpstats(int severity)
   2109 {
   2110  if (all_listeners && smartlist_len(all_listeners) > 0) {
   2111    tor_log(severity, LD_GENERAL,
   2112        "Dumping statistics about %d channel listeners:",
   2113        smartlist_len(all_listeners));
   2114    tor_log(severity, LD_GENERAL,
   2115        "%d are active and %d are done and waiting for cleanup",
   2116        (active_listeners != NULL) ?
   2117          smartlist_len(active_listeners) : 0,
   2118        (finished_listeners != NULL) ?
   2119          smartlist_len(finished_listeners) : 0);
   2120 
   2121    SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
   2122                      channel_listener_dump_statistics(chan_l, severity));
   2123 
   2124    tor_log(severity, LD_GENERAL,
   2125        "Done spamming about channel listeners now");
   2126  } else {
   2127    tor_log(severity, LD_GENERAL,
   2128        "No channel listeners to dump");
   2129  }
   2130 }
   2131 
   2132 /**
   2133 * Clean up channels.
   2134 *
   2135 * This gets called periodically from run_scheduled_events() in main.c;
   2136 * it cleans up after closed channels.
   2137 */
   2138 void
   2139 channel_run_cleanup(void)
   2140 {
   2141  channel_t *tmp = NULL;
   2142 
   2143  /* Check if we need to do anything */
   2144  if (!finished_channels || smartlist_len(finished_channels) == 0) return;
   2145 
   2146  /* Iterate through finished_channels and get rid of them */
   2147  SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
   2148    tmp = curr;
   2149    /* Remove it from the list */
   2150    SMARTLIST_DEL_CURRENT(finished_channels, curr);
   2151    /* Also unregister it */
   2152    channel_unregister(tmp);
   2153    /* ... and free it */
   2154    channel_free(tmp);
   2155  } SMARTLIST_FOREACH_END(curr);
   2156 }
   2157 
   2158 /**
   2159 * Clean up channel listeners.
   2160 *
   2161 * This gets called periodically from run_scheduled_events() in main.c;
   2162 * it cleans up after closed channel listeners.
   2163 */
   2164 void
   2165 channel_listener_run_cleanup(void)
   2166 {
   2167  channel_listener_t *tmp = NULL;
   2168 
   2169  /* Check if we need to do anything */
   2170  if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
   2171 
   2172  /* Iterate through finished_channels and get rid of them */
   2173  SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
   2174    tmp = curr;
   2175    /* Remove it from the list */
   2176    SMARTLIST_DEL_CURRENT(finished_listeners, curr);
   2177    /* Also unregister it */
   2178    channel_listener_unregister(tmp);
   2179    /* ... and free it */
   2180    channel_listener_free(tmp);
   2181  } SMARTLIST_FOREACH_END(curr);
   2182 }
   2183 
   2184 /**
   2185 * Free a list of channels for channel_free_all().
   2186 */
   2187 static void
   2188 channel_free_list(smartlist_t *channels, int mark_for_close)
   2189 {
   2190  if (!channels) return;
   2191 
   2192  SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
   2193    /* Deregister and free it */
   2194    tor_assert(curr);
   2195    log_debug(LD_CHANNEL,
   2196              "Cleaning up channel %p (global ID %"PRIu64 ") "
   2197              "in state %s (%d)",
   2198              curr, (curr->global_identifier),
   2199              channel_state_to_string(curr->state), curr->state);
   2200    /* Detach circuits early so they can find the channel */
   2201    if (curr->cmux) {
   2202      circuitmux_detach_all_circuits(curr->cmux, NULL);
   2203    }
   2204    SMARTLIST_DEL_CURRENT(channels, curr);
   2205    channel_unregister(curr);
   2206    if (mark_for_close) {
   2207      if (!CHANNEL_CONDEMNED(curr)) {
   2208        channel_mark_for_close(curr);
   2209      }
   2210      channel_force_xfree(curr);
   2211    } else channel_free(curr);
   2212  } SMARTLIST_FOREACH_END(curr);
   2213 }
   2214 
   2215 /**
   2216 * Free a list of channel listeners for channel_free_all().
   2217 */
   2218 static void
   2219 channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
   2220 {
   2221  if (!listeners) return;
   2222 
   2223  SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
   2224    /* Deregister and free it */
   2225    tor_assert(curr);
   2226    log_debug(LD_CHANNEL,
   2227              "Cleaning up channel listener %p (global ID %"PRIu64 ") "
   2228              "in state %s (%d)",
   2229              curr, (curr->global_identifier),
   2230              channel_listener_state_to_string(curr->state), curr->state);
   2231    channel_listener_unregister(curr);
   2232    if (mark_for_close) {
   2233      if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
   2234            curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
   2235            curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
   2236        channel_listener_mark_for_close(curr);
   2237      }
   2238      channel_listener_force_xfree(curr);
   2239    } else channel_listener_free(curr);
   2240  } SMARTLIST_FOREACH_END(curr);
   2241 }
   2242 
   2243 /**
   2244 * Close all channels and free everything.
   2245 *
   2246 * This gets called from tor_free_all() in main.c to clean up on exit.
   2247 * It will close all registered channels and free associated storage,
   2248 * then free the all_channels, active_channels, listening_channels and
   2249 * finished_channels lists and also channel_identity_map.
   2250 */
   2251 void
   2252 channel_free_all(void)
   2253 {
   2254  log_debug(LD_CHANNEL,
   2255            "Shutting down channels...");
   2256 
   2257  /* First, let's go for finished channels */
   2258  if (finished_channels) {
   2259    channel_free_list(finished_channels, 0);
   2260    smartlist_free(finished_channels);
   2261    finished_channels = NULL;
   2262  }
   2263 
   2264  /* Now the finished listeners */
   2265  if (finished_listeners) {
   2266    channel_listener_free_list(finished_listeners, 0);
   2267    smartlist_free(finished_listeners);
   2268    finished_listeners = NULL;
   2269  }
   2270 
   2271  /* Now all active channels */
   2272  if (active_channels) {
   2273    channel_free_list(active_channels, 1);
   2274    smartlist_free(active_channels);
   2275    active_channels = NULL;
   2276  }
   2277 
   2278  /* Now all active listeners */
   2279  if (active_listeners) {
   2280    channel_listener_free_list(active_listeners, 1);
   2281    smartlist_free(active_listeners);
   2282    active_listeners = NULL;
   2283  }
   2284 
   2285  /* Now all channels, in case any are left over */
   2286  if (all_channels) {
   2287    channel_free_list(all_channels, 1);
   2288    smartlist_free(all_channels);
   2289    all_channels = NULL;
   2290  }
   2291 
   2292  /* Now all listeners, in case any are left over */
   2293  if (all_listeners) {
   2294    channel_listener_free_list(all_listeners, 1);
   2295    smartlist_free(all_listeners);
   2296    all_listeners = NULL;
   2297  }
   2298 
   2299  /* Now free channel_identity_map */
   2300  log_debug(LD_CHANNEL,
   2301            "Freeing channel_identity_map");
   2302  /* Geez, anything still left over just won't die ... let it leak then */
   2303  HT_CLEAR(channel_idmap, &channel_identity_map);
   2304 
   2305  /* Same with channel_gid_map */
   2306  log_debug(LD_CHANNEL,
   2307            "Freeing channel_gid_map");
   2308  HT_CLEAR(channel_gid_map, &channel_gid_map);
   2309 
   2310  log_debug(LD_CHANNEL,
   2311            "Done cleaning up after channels");
   2312 }
   2313 
   2314 /**
   2315 * Connect to a given addr/port/digest.
   2316 *
   2317 * This sets up a new outgoing channel; in the future if multiple
   2318 * channel_t subclasses are available, this is where the selection policy
   2319 * should go.  It may also be desirable to fold port into tor_addr_t
   2320 * or make a new type including a tor_addr_t and port, so we have a
   2321 * single abstract object encapsulating all the protocol details of
   2322 * how to contact an OR.
   2323 */
   2324 channel_t *
   2325 channel_connect(const tor_addr_t *addr, uint16_t port,
   2326                const char *id_digest,
   2327                const ed25519_public_key_t *ed_id)
   2328 {
   2329  return channel_tls_connect(addr, port, id_digest, ed_id);
   2330 }
   2331 
   2332 /**
   2333 * Decide which of two channels to prefer for extending a circuit.
   2334 *
   2335 * This function is called while extending a circuit and returns true iff
   2336 * a is 'better' than b.  The most important criterion here is that a
   2337 * canonical channel is always better than a non-canonical one, but the
   2338 * number of circuits and the age are used as tie-breakers.
   2339 *
   2340 * This is based on the former connection_or_is_better() of connection_or.c
   2341 */
   2342 int
   2343 channel_is_better(channel_t *a, channel_t *b)
   2344 {
   2345  int a_is_canonical, b_is_canonical;
   2346 
   2347  tor_assert(a);
   2348  tor_assert(b);
   2349 
   2350  /* If one channel is bad for new circuits, and the other isn't,
   2351   * use the one that is still good. */
   2352  if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
   2353    return 1;
   2354  if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
   2355    return 0;
   2356 
   2357  /* Check if one is canonical and the other isn't first */
   2358  a_is_canonical = channel_is_canonical(a);
   2359  b_is_canonical = channel_is_canonical(b);
   2360 
   2361  if (a_is_canonical && !b_is_canonical) return 1;
   2362  if (!a_is_canonical && b_is_canonical) return 0;
   2363 
   2364  /* Check if we suspect that one of the channels will be preferred
   2365   * by the peer */
   2366  if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
   2367  if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
   2368 
   2369  /*
   2370   * Okay, if we're here they tied on canonicity. Prefer the older
   2371   * connection, so that the adversary can't create a new connection
   2372   * and try to switch us over to it (which will leak information
   2373   * about long-lived circuits). Additionally, switching connections
   2374   * too often makes us more vulnerable to attacks like Torscan and
   2375   * passive netflow-based equivalents.
   2376   *
   2377   * Connections will still only live for at most a week, due to
   2378   * the check in connection_or_group_set_badness() against
   2379   * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
   2380   * unusable for new circuits after 1 week. That check sets
   2381   * is_bad_for_new_circs, which is checked in channel_get_for_extend().
   2382   *
   2383   * We check channel_is_bad_for_new_circs() above here anyway, for safety.
   2384   */
   2385  if (channel_when_created(a) < channel_when_created(b)) return 1;
   2386  else if (channel_when_created(a) > channel_when_created(b)) return 0;
   2387 
   2388  if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
   2389  else return 0;
   2390 }
   2391 
   2392 /**
   2393 * Get a channel to extend a circuit.
   2394 *
   2395 * Given the desired relay identity, pick a suitable channel to extend a
   2396 * circuit to the target IPv4 or IPv6 address requested by the client. Search
   2397 * for an existing channel for the requested endpoint. Make sure the channel
   2398 * is usable for new circuits, and matches one of the target addresses.
   2399 *
   2400 * Try to return the best channel. But if there is no good channel, set
   2401 * *msg_out to a message describing the channel's state and our next action,
   2402 * and set *launch_out to a boolean indicated whether the caller should try to
   2403 * launch a new channel with channel_connect().
   2404 *
   2405 * If `for_origin_circ` is set, mark the channel as interesting for origin
   2406 * circuits, and therefore interesting for our bootstrapping reports.
   2407 */
   2408 MOCK_IMPL(channel_t *,
   2409 channel_get_for_extend,(const char *rsa_id_digest,
   2410                        const ed25519_public_key_t *ed_id,
   2411                        const tor_addr_t *target_ipv4_addr,
   2412                        const tor_addr_t *target_ipv6_addr,
   2413                        bool for_origin_circ,
   2414                        const char **msg_out,
   2415                        int *launch_out))
   2416 {
   2417  channel_t *chan, *best = NULL;
   2418  int n_inprogress_goodaddr = 0, n_old = 0;
   2419  int n_noncanonical = 0;
   2420 
   2421  tor_assert(msg_out);
   2422  tor_assert(launch_out);
   2423 
   2424  chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
   2425 
   2426  /* Walk the list of channels */
   2427  for (; chan; chan = channel_next_with_rsa_identity(chan)) {
   2428    tor_assert(tor_memeq(chan->identity_digest,
   2429                         rsa_id_digest, DIGEST_LEN));
   2430 
   2431   if (CHANNEL_CONDEMNED(chan))
   2432      continue;
   2433 
   2434    /* Never return a channel on which the other end appears to be
   2435     * a client. */
   2436    if (channel_is_client(chan)) {
   2437      continue;
   2438    }
   2439 
   2440    /* The Ed25519 key has to match too */
   2441    if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
   2442      continue;
   2443    }
   2444 
   2445    const bool matches_target =
   2446      channel_matches_target_addr_for_extend(chan,
   2447                                             target_ipv4_addr,
   2448                                             target_ipv6_addr);
   2449    /* Never return a non-open connection. */
   2450    if (!CHANNEL_IS_OPEN(chan)) {
   2451      /* If the address matches, don't launch a new connection for this
   2452       * circuit. */
   2453      if (matches_target) {
   2454        ++n_inprogress_goodaddr;
   2455        if (for_origin_circ) {
   2456          /* We were looking for a connection for an origin circuit; this one
   2457           * matches, so we'll note that we decided to use it for an origin
   2458           * circuit. */
   2459          channel_mark_as_used_for_origin_circuit(chan);
   2460        }
   2461      }
   2462      continue;
   2463    }
   2464 
   2465    /* Never return a connection that shouldn't be used for circs. */
   2466    if (channel_is_bad_for_new_circs(chan)) {
   2467      ++n_old;
   2468      continue;
   2469    }
   2470 
   2471    /* Only return canonical connections or connections where the address
   2472     * is the address we wanted. */
   2473    if (!channel_is_canonical(chan) && !matches_target) {
   2474      ++n_noncanonical;
   2475      continue;
   2476    }
   2477 
   2478    if (!best) {
   2479      best = chan; /* If we have no 'best' so far, this one is good enough. */
   2480      continue;
   2481    }
   2482 
   2483    if (channel_is_better(chan, best))
   2484      best = chan;
   2485  }
   2486 
   2487  if (best) {
   2488    *msg_out = "Connection is fine; using it.";
   2489    *launch_out = 0;
   2490    return best;
   2491  } else if (n_inprogress_goodaddr) {
   2492    *msg_out = "Connection in progress; waiting.";
   2493    *launch_out = 0;
   2494    return NULL;
   2495  } else if (n_old || n_noncanonical) {
   2496    *msg_out = "Connections all too old, or too non-canonical. "
   2497               " Launching a new one.";
   2498    *launch_out = 1;
   2499    return NULL;
   2500  } else {
   2501    *msg_out = "Not connected. Connecting.";
   2502    *launch_out = 1;
   2503    return NULL;
   2504  }
   2505 }
   2506 
   2507 /**
   2508 * Describe the transport subclass for a channel.
   2509 *
   2510 * Invoke a method to get a string description of the lower-layer
   2511 * transport for this channel.
   2512 */
   2513 const char *
   2514 channel_describe_transport(channel_t *chan)
   2515 {
   2516  tor_assert(chan);
   2517  tor_assert(chan->describe_transport);
   2518 
   2519  return chan->describe_transport(chan);
   2520 }
   2521 
   2522 /**
   2523 * Describe the transport subclass for a channel listener.
   2524 *
   2525 * Invoke a method to get a string description of the lower-layer
   2526 * transport for this channel listener.
   2527 */
   2528 const char *
   2529 channel_listener_describe_transport(channel_listener_t *chan_l)
   2530 {
   2531  tor_assert(chan_l);
   2532  tor_assert(chan_l->describe_transport);
   2533 
   2534  return chan_l->describe_transport(chan_l);
   2535 }
   2536 
   2537 /**
   2538 * Dump channel statistics.
   2539 *
   2540 * Dump statistics for one channel to the log.
   2541 */
   2542 MOCK_IMPL(void,
   2543 channel_dump_statistics, (channel_t *chan, int severity))
   2544 {
   2545  double avg, interval, age;
   2546  time_t now = time(NULL);
   2547  tor_addr_t remote_addr;
   2548  int have_remote_addr;
   2549  char *remote_addr_str;
   2550 
   2551  tor_assert(chan);
   2552 
   2553  age = (double)(now - chan->timestamp_created);
   2554 
   2555  tor_log(severity, LD_GENERAL,
   2556      "Channel %"PRIu64 " (at %p) with transport %s is in state "
   2557      "%s (%d)",
   2558      (chan->global_identifier), chan,
   2559      channel_describe_transport(chan),
   2560      channel_state_to_string(chan->state), chan->state);
   2561  tor_log(severity, LD_GENERAL,
   2562      " * Channel %"PRIu64 " was created at %"PRIu64
   2563      " (%"PRIu64 " seconds ago) "
   2564      "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
   2565      (chan->global_identifier),
   2566      (uint64_t)(chan->timestamp_created),
   2567      (uint64_t)(now - chan->timestamp_created),
   2568      (uint64_t)(chan->timestamp_active),
   2569      (uint64_t)(now - chan->timestamp_active));
   2570 
   2571  /* Handle digest. */
   2572  if (!tor_digest_is_zero(chan->identity_digest)) {
   2573    tor_log(severity, LD_GENERAL,
   2574        " * Channel %"PRIu64 " says it is connected "
   2575        "to an OR with digest %s",
   2576        (chan->global_identifier),
   2577        hex_str(chan->identity_digest, DIGEST_LEN));
   2578  } else {
   2579    tor_log(severity, LD_GENERAL,
   2580        " * Channel %"PRIu64 " does not know the digest"
   2581        " of the OR it is connected to",
   2582        (chan->global_identifier));
   2583  }
   2584 
   2585  /* Handle remote address and descriptions */
   2586  have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
   2587  if (have_remote_addr) {
   2588    char *actual = tor_strdup(channel_describe_peer(chan));
   2589    remote_addr_str = tor_addr_to_str_dup(&remote_addr);
   2590    tor_log(severity, LD_GENERAL,
   2591        " * Channel %"PRIu64 " says its remote address"
   2592        " is %s, and gives a canonical description of \"%s\" and an "
   2593        "actual description of \"%s\"",
   2594        (chan->global_identifier),
   2595        safe_str(remote_addr_str),
   2596        safe_str(channel_describe_peer(chan)),
   2597        safe_str(actual));
   2598    tor_free(remote_addr_str);
   2599    tor_free(actual);
   2600  } else {
   2601    char *actual = tor_strdup(channel_describe_peer(chan));
   2602    tor_log(severity, LD_GENERAL,
   2603        " * Channel %"PRIu64 " does not know its remote "
   2604        "address, but gives a canonical description of \"%s\" and an "
   2605        "actual description of \"%s\"",
   2606        (chan->global_identifier),
   2607        channel_describe_peer(chan),
   2608        actual);
   2609    tor_free(actual);
   2610  }
   2611 
   2612  /* Handle marks */
   2613  tor_log(severity, LD_GENERAL,
   2614      " * Channel %"PRIu64 " has these marks: %s %s %s %s %s",
   2615      (chan->global_identifier),
   2616      channel_is_bad_for_new_circs(chan) ?
   2617        "bad_for_new_circs" : "!bad_for_new_circs",
   2618      channel_is_canonical(chan) ?
   2619        "canonical" : "!canonical",
   2620      channel_is_client(chan) ?
   2621        "client" : "!client",
   2622      channel_is_local(chan) ?
   2623        "local" : "!local",
   2624      channel_is_incoming(chan) ?
   2625        "incoming" : "outgoing");
   2626 
   2627  /* Describe circuits */
   2628  tor_log(severity, LD_GENERAL,
   2629      " * Channel %"PRIu64 " has %d active circuits out of"
   2630      " %d in total",
   2631      (chan->global_identifier),
   2632      (chan->cmux != NULL) ?
   2633         circuitmux_num_active_circuits(chan->cmux) : 0,
   2634      (chan->cmux != NULL) ?
   2635         circuitmux_num_circuits(chan->cmux) : 0);
   2636 
   2637  /* Describe timestamps */
   2638  if (chan->timestamp_client == 0) {
   2639      tor_log(severity, LD_GENERAL,
   2640              " * Channel %"PRIu64 " was never used by a "
   2641             "client", (chan->global_identifier));
   2642  } else {
   2643      tor_log(severity, LD_GENERAL,
   2644              " * Channel %"PRIu64 " was last used by a "
   2645              "client at %"PRIu64 " (%"PRIu64 " seconds ago)",
   2646              (chan->global_identifier),
   2647              (uint64_t)(chan->timestamp_client),
   2648              (uint64_t)(now - chan->timestamp_client));
   2649  }
   2650  if (chan->timestamp_recv == 0) {
   2651      tor_log(severity, LD_GENERAL,
   2652              " * Channel %"PRIu64 " never received a cell",
   2653              (chan->global_identifier));
   2654  } else {
   2655      tor_log(severity, LD_GENERAL,
   2656              " * Channel %"PRIu64 " last received a cell "
   2657              "at %"PRIu64 " (%"PRIu64 " seconds ago)",
   2658              (chan->global_identifier),
   2659              (uint64_t)(chan->timestamp_recv),
   2660              (uint64_t)(now - chan->timestamp_recv));
   2661  }
   2662  if (chan->timestamp_xmit == 0) {
   2663      tor_log(severity, LD_GENERAL,
   2664              " * Channel %"PRIu64 " never transmitted a cell",
   2665              (chan->global_identifier));
   2666  } else {
   2667      tor_log(severity, LD_GENERAL,
   2668              " * Channel %"PRIu64 " last transmitted a cell "
   2669              "at %"PRIu64 " (%"PRIu64 " seconds ago)",
   2670              (chan->global_identifier),
   2671              (uint64_t)(chan->timestamp_xmit),
   2672              (uint64_t)(now - chan->timestamp_xmit));
   2673  }
   2674 
   2675  /* Describe counters and rates */
   2676  tor_log(severity, LD_GENERAL,
   2677      " * Channel %"PRIu64 " has received "
   2678      "%"PRIu64 " bytes in %"PRIu64 " cells and transmitted "
   2679      "%"PRIu64 " bytes in %"PRIu64 " cells",
   2680      (chan->global_identifier),
   2681      (chan->n_bytes_recved),
   2682      (chan->n_cells_recved),
   2683      (chan->n_bytes_xmitted),
   2684      (chan->n_cells_xmitted));
   2685  if (now > chan->timestamp_created &&
   2686      chan->timestamp_created > 0) {
   2687    if (chan->n_bytes_recved > 0) {
   2688      avg = (double)(chan->n_bytes_recved) / age;
   2689      tor_log(severity, LD_GENERAL,
   2690          " * Channel %"PRIu64 " has averaged %f "
   2691          "bytes received per second",
   2692          (chan->global_identifier), avg);
   2693    }
   2694    if (chan->n_cells_recved > 0) {
   2695      avg = (double)(chan->n_cells_recved) / age;
   2696      if (avg >= 1.0) {
   2697        tor_log(severity, LD_GENERAL,
   2698            " * Channel %"PRIu64 " has averaged %f "
   2699            "cells received per second",
   2700            (chan->global_identifier), avg);
   2701      } else if (avg >= 0.0) {
   2702        interval = 1.0 / avg;
   2703        tor_log(severity, LD_GENERAL,
   2704            " * Channel %"PRIu64 " has averaged %f "
   2705            "seconds between received cells",
   2706            (chan->global_identifier), interval);
   2707      }
   2708    }
   2709    if (chan->n_bytes_xmitted > 0) {
   2710      avg = (double)(chan->n_bytes_xmitted) / age;
   2711      tor_log(severity, LD_GENERAL,
   2712          " * Channel %"PRIu64 " has averaged %f "
   2713          "bytes transmitted per second",
   2714          (chan->global_identifier), avg);
   2715    }
   2716    if (chan->n_cells_xmitted > 0) {
   2717      avg = (double)(chan->n_cells_xmitted) / age;
   2718      if (avg >= 1.0) {
   2719        tor_log(severity, LD_GENERAL,
   2720            " * Channel %"PRIu64 " has averaged %f "
   2721            "cells transmitted per second",
   2722            (chan->global_identifier), avg);
   2723      } else if (avg >= 0.0) {
   2724        interval = 1.0 / avg;
   2725        tor_log(severity, LD_GENERAL,
   2726            " * Channel %"PRIu64 " has averaged %f "
   2727            "seconds between transmitted cells",
   2728            (chan->global_identifier), interval);
   2729      }
   2730    }
   2731  }
   2732 
   2733  /* Dump anything the lower layer has to say */
   2734  channel_dump_transport_statistics(chan, severity);
   2735 }
   2736 
   2737 /**
   2738 * Dump channel listener statistics.
   2739 *
   2740 * Dump statistics for one channel listener to the log.
   2741 */
   2742 void
   2743 channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
   2744 {
   2745  double avg, interval, age;
   2746  time_t now = time(NULL);
   2747 
   2748  tor_assert(chan_l);
   2749 
   2750  age = (double)(now - chan_l->timestamp_created);
   2751 
   2752  tor_log(severity, LD_GENERAL,
   2753      "Channel listener %"PRIu64 " (at %p) with transport %s is in "
   2754      "state %s (%d)",
   2755      (chan_l->global_identifier), chan_l,
   2756      channel_listener_describe_transport(chan_l),
   2757      channel_listener_state_to_string(chan_l->state), chan_l->state);
   2758  tor_log(severity, LD_GENERAL,
   2759      " * Channel listener %"PRIu64 " was created at %"PRIu64
   2760      " (%"PRIu64 " seconds ago) "
   2761      "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
   2762      (chan_l->global_identifier),
   2763      (uint64_t)(chan_l->timestamp_created),
   2764      (uint64_t)(now - chan_l->timestamp_created),
   2765      (uint64_t)(chan_l->timestamp_active),
   2766      (uint64_t)(now - chan_l->timestamp_active));
   2767 
   2768  tor_log(severity, LD_GENERAL,
   2769      " * Channel listener %"PRIu64 " last accepted an incoming "
   2770        "channel at %"PRIu64 " (%"PRIu64 " seconds ago) "
   2771        "and has accepted %"PRIu64 " channels in total",
   2772        (chan_l->global_identifier),
   2773        (uint64_t)(chan_l->timestamp_accepted),
   2774        (uint64_t)(now - chan_l->timestamp_accepted),
   2775        (uint64_t)(chan_l->n_accepted));
   2776 
   2777  /*
   2778   * If it's sensible to do so, get the rate of incoming channels on this
   2779   * listener
   2780   */
   2781  if (now > chan_l->timestamp_created &&
   2782      chan_l->timestamp_created > 0 &&
   2783      chan_l->n_accepted > 0) {
   2784    avg = (double)(chan_l->n_accepted) / age;
   2785    if (avg >= 1.0) {
   2786      tor_log(severity, LD_GENERAL,
   2787          " * Channel listener %"PRIu64 " has averaged %f incoming "
   2788          "channels per second",
   2789          (chan_l->global_identifier), avg);
   2790    } else if (avg >= 0.0) {
   2791      interval = 1.0 / avg;
   2792      tor_log(severity, LD_GENERAL,
   2793          " * Channel listener %"PRIu64 " has averaged %f seconds "
   2794          "between incoming channels",
   2795          (chan_l->global_identifier), interval);
   2796    }
   2797  }
   2798 
   2799  /* Dump anything the lower layer has to say */
   2800  channel_listener_dump_transport_statistics(chan_l, severity);
   2801 }
   2802 
   2803 /**
   2804 * Invoke transport-specific stats dump for channel.
   2805 *
   2806 * If there is a lower-layer statistics dump method, invoke it.
   2807 */
   2808 void
   2809 channel_dump_transport_statistics(channel_t *chan, int severity)
   2810 {
   2811  tor_assert(chan);
   2812 
   2813  if (chan->dumpstats) chan->dumpstats(chan, severity);
   2814 }
   2815 
   2816 /**
   2817 * Invoke transport-specific stats dump for channel listener.
   2818 *
   2819 * If there is a lower-layer statistics dump method, invoke it.
   2820 */
   2821 void
   2822 channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
   2823                                           int severity)
   2824 {
   2825  tor_assert(chan_l);
   2826 
   2827  if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
   2828 }
   2829 
   2830 /**
   2831 * Return text description of the remote endpoint canonical address.
   2832 *
   2833 * This function returns a human-readable string for logging; nothing
   2834 * should parse it or rely on a particular format.
   2835 *
   2836 * Subsequent calls to this function may invalidate its return value.
   2837 */
   2838 MOCK_IMPL(const char *,
   2839 channel_describe_peer,(channel_t *chan))
   2840 {
   2841  tor_assert(chan);
   2842  tor_assert(chan->describe_peer);
   2843 
   2844  return chan->describe_peer(chan);
   2845 }
   2846 
   2847 /**
   2848 * Get the remote address for this channel, if possible.
   2849 *
   2850 * Write the remote address out to a tor_addr_t if the underlying transport
   2851 * supports this operation, and return 1.  Return 0 if the underlying transport
   2852 * doesn't let us do this.
   2853 *
   2854 * Always returns the "real" address of the peer -- the one we're connected to
   2855 * on the internet.
   2856 */
   2857 MOCK_IMPL(int,
   2858 channel_get_addr_if_possible,(const channel_t *chan,
   2859                              tor_addr_t *addr_out))
   2860 {
   2861  tor_assert(chan);
   2862  tor_assert(addr_out);
   2863  tor_assert(chan->get_remote_addr);
   2864 
   2865  return chan->get_remote_addr(chan, addr_out);
   2866 }
   2867 
   2868 /**
   2869 * Return true iff the channel has any cells on the connection outbuf waiting
   2870 * to be sent onto the network.
   2871 */
   2872 int
   2873 channel_has_queued_writes(channel_t *chan)
   2874 {
   2875  tor_assert(chan);
   2876  tor_assert(chan->has_queued_writes);
   2877 
   2878  /* Check with the lower layer */
   2879  return chan->has_queued_writes(chan);
   2880 }
   2881 
   2882 /**
   2883 * Check the is_bad_for_new_circs flag.
   2884 *
   2885 * This function returns the is_bad_for_new_circs flag of the specified
   2886 * channel.
   2887 */
   2888 int
   2889 channel_is_bad_for_new_circs(channel_t *chan)
   2890 {
   2891  tor_assert(chan);
   2892 
   2893  return chan->is_bad_for_new_circs;
   2894 }
   2895 
   2896 /**
   2897 * Mark a channel as bad for new circuits.
   2898 *
   2899 * Set the is_bad_for_new_circs_flag on chan.
   2900 */
   2901 void
   2902 channel_mark_bad_for_new_circs(channel_t *chan)
   2903 {
   2904  tor_assert(chan);
   2905 
   2906  chan->is_bad_for_new_circs = 1;
   2907 }
   2908 
   2909 /**
   2910 * Get the client flag.
   2911 *
   2912 * This returns the client flag of a channel, which will be set if
   2913 * command_process_create_cell() in command.c thinks this is a connection
   2914 * from a client.
   2915 */
   2916 int
   2917 channel_is_client(const channel_t *chan)
   2918 {
   2919  tor_assert(chan);
   2920 
   2921  return chan->is_client;
   2922 }
   2923 
   2924 /**
   2925 * Set the client flag.
   2926 *
   2927 * Mark a channel as being from a client.
   2928 */
   2929 void
   2930 channel_mark_client(channel_t *chan)
   2931 {
   2932  tor_assert(chan);
   2933 
   2934  chan->is_client = 1;
   2935 }
   2936 
   2937 /**
   2938 * Clear the client flag.
   2939 *
   2940 * Mark a channel as being _not_ from a client.
   2941 */
   2942 void
   2943 channel_clear_client(channel_t *chan)
   2944 {
   2945  tor_assert(chan);
   2946 
   2947  chan->is_client = 0;
   2948 }
   2949 
   2950 /**
   2951 * Get the canonical flag for a channel.
   2952 *
   2953 * This returns the is_canonical for a channel; this flag is determined by
   2954 * the lower layer and can't be set in a transport-independent way.
   2955 */
   2956 int
   2957 channel_is_canonical(channel_t *chan)
   2958 {
   2959  tor_assert(chan);
   2960  tor_assert(chan->is_canonical);
   2961 
   2962  return chan->is_canonical(chan);
   2963 }
   2964 
   2965 /**
   2966 * Test incoming flag.
   2967 *
   2968 * This function gets the incoming flag; this is set when a listener spawns
   2969 * a channel.  If this returns true the channel was remotely initiated.
   2970 */
   2971 int
   2972 channel_is_incoming(channel_t *chan)
   2973 {
   2974  tor_assert(chan);
   2975 
   2976  return chan->is_incoming;
   2977 }
   2978 
   2979 /**
   2980 * Set the incoming flag.
   2981 *
   2982 * This function is called when a channel arrives on a listening channel
   2983 * to mark it as incoming.
   2984 */
   2985 void
   2986 channel_mark_incoming(channel_t *chan)
   2987 {
   2988  tor_assert(chan);
   2989 
   2990  chan->is_incoming = 1;
   2991 }
   2992 
   2993 /**
   2994 * Test local flag.
   2995 *
   2996 * This function gets the local flag; the lower layer should set this when
   2997 * setting up the channel if is_local_addr() is true for all of the
   2998 * destinations it will communicate with on behalf of this channel.  It's
   2999 * used to decide whether to declare the network reachable when seeing incoming
   3000 * traffic on the channel.
   3001 */
   3002 int
   3003 channel_is_local(channel_t *chan)
   3004 {
   3005  tor_assert(chan);
   3006 
   3007  return chan->is_local;
   3008 }
   3009 
   3010 /**
   3011 * Set the local flag.
   3012 *
   3013 * This internal-only function should be called by the lower layer if the
   3014 * channel is to a local address.  See channel_is_local() above or the
   3015 * description of the is_local bit in channel.h.
   3016 */
   3017 void
   3018 channel_mark_local(channel_t *chan)
   3019 {
   3020  tor_assert(chan);
   3021 
   3022  chan->is_local = 1;
   3023 }
   3024 
   3025 /**
   3026 * Mark a channel as remote.
   3027 *
   3028 * This internal-only function should be called by the lower layer if the
   3029 * channel is not to a local address but has previously been marked local.
   3030 * See channel_is_local() above or the description of the is_local bit in
   3031 * channel.h
   3032 */
   3033 void
   3034 channel_mark_remote(channel_t *chan)
   3035 {
   3036  tor_assert(chan);
   3037 
   3038  chan->is_local = 0;
   3039 }
   3040 
   3041 /**
   3042 * Test outgoing flag.
   3043 *
   3044 * This function gets the outgoing flag; this is the inverse of the incoming
   3045 * bit set when a listener spawns a channel.  If this returns true the channel
   3046 * was locally initiated.
   3047 */
   3048 int
   3049 channel_is_outgoing(channel_t *chan)
   3050 {
   3051  tor_assert(chan);
   3052 
   3053  return !(chan->is_incoming);
   3054 }
   3055 
   3056 /**
   3057 * Mark a channel as outgoing.
   3058 *
   3059 * This function clears the incoming flag and thus marks a channel as
   3060 * outgoing.
   3061 */
   3062 void
   3063 channel_mark_outgoing(channel_t *chan)
   3064 {
   3065  tor_assert(chan);
   3066 
   3067  chan->is_incoming = 0;
   3068 }
   3069 
   3070 /************************
   3071 * Flow control queries *
   3072 ***********************/
   3073 
   3074 /**
   3075 * Estimate the number of writeable cells.
   3076 *
   3077 * Ask the lower layer for an estimate of how many cells it can accept.
   3078 */
   3079 int
   3080 channel_num_cells_writeable(channel_t *chan)
   3081 {
   3082  int result;
   3083 
   3084  tor_assert(chan);
   3085  tor_assert(chan->num_cells_writeable);
   3086 
   3087  if (chan->state == CHANNEL_STATE_OPEN) {
   3088    /* Query lower layer */
   3089    result = chan->num_cells_writeable(chan);
   3090    if (result < 0) result = 0;
   3091  } else {
   3092    /* No cells are writeable in any other state */
   3093    result = 0;
   3094  }
   3095 
   3096  return result;
   3097 }
   3098 
   3099 /*********************
   3100 * Timestamp updates *
   3101 ********************/
   3102 
   3103 /**
   3104 * Update the created timestamp for a channel.
   3105 *
   3106 * This updates the channel's created timestamp and should only be called
   3107 * from channel_init().
   3108 */
   3109 void
   3110 channel_timestamp_created(channel_t *chan)
   3111 {
   3112  time_t now = time(NULL);
   3113 
   3114  tor_assert(chan);
   3115 
   3116  chan->timestamp_created = now;
   3117 }
   3118 
   3119 /**
   3120 * Update the created timestamp for a channel listener.
   3121 *
   3122 * This updates the channel listener's created timestamp and should only be
   3123 * called from channel_init_listener().
   3124 */
   3125 void
   3126 channel_listener_timestamp_created(channel_listener_t *chan_l)
   3127 {
   3128  time_t now = time(NULL);
   3129 
   3130  tor_assert(chan_l);
   3131 
   3132  chan_l->timestamp_created = now;
   3133 }
   3134 
   3135 /**
   3136 * Update the last active timestamp for a channel.
   3137 *
   3138 * This function updates the channel's last active timestamp; it should be
   3139 * called by the lower layer whenever there is activity on the channel which
   3140 * does not lead to a cell being transmitted or received; the active timestamp
   3141 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
   3142 * but it should be updated for things like the v3 handshake and stuff that
   3143 * produce activity only visible to the lower layer.
   3144 */
   3145 void
   3146 channel_timestamp_active(channel_t *chan)
   3147 {
   3148  time_t now = time(NULL);
   3149 
   3150  tor_assert(chan);
   3151  monotime_coarse_get(&chan->timestamp_xfer);
   3152 
   3153  chan->timestamp_active = now;
   3154 
   3155  /* Clear any potential netflow padding timer. We're active */
   3156  monotime_coarse_zero(&chan->next_padding_time);
   3157 }
   3158 
   3159 /**
   3160 * Update the last active timestamp for a channel listener.
   3161 */
   3162 void
   3163 channel_listener_timestamp_active(channel_listener_t *chan_l)
   3164 {
   3165  time_t now = time(NULL);
   3166 
   3167  tor_assert(chan_l);
   3168 
   3169  chan_l->timestamp_active = now;
   3170 }
   3171 
   3172 /**
   3173 * Update the last accepted timestamp.
   3174 *
   3175 * This function updates the channel listener's last accepted timestamp; it
   3176 * should be called whenever a new incoming channel is accepted on a
   3177 * listener.
   3178 */
   3179 void
   3180 channel_listener_timestamp_accepted(channel_listener_t *chan_l)
   3181 {
   3182  time_t now = time(NULL);
   3183 
   3184  tor_assert(chan_l);
   3185 
   3186  chan_l->timestamp_active = now;
   3187  chan_l->timestamp_accepted = now;
   3188 }
   3189 
   3190 /**
   3191 * Update client timestamp.
   3192 *
   3193 * This function is called by relay.c to timestamp a channel that appears to
   3194 * be used as a client.
   3195 */
   3196 void
   3197 channel_timestamp_client(channel_t *chan)
   3198 {
   3199  time_t now = time(NULL);
   3200 
   3201  tor_assert(chan);
   3202 
   3203  chan->timestamp_client = now;
   3204 }
   3205 
   3206 /**
   3207 * Update the recv timestamp.
   3208 *
   3209 * This is called whenever we get an incoming cell from the lower layer.
   3210 * This also updates the active timestamp.
   3211 */
   3212 void
   3213 channel_timestamp_recv(channel_t *chan)
   3214 {
   3215  time_t now = time(NULL);
   3216  tor_assert(chan);
   3217  monotime_coarse_get(&chan->timestamp_xfer);
   3218 
   3219  chan->timestamp_active = now;
   3220  chan->timestamp_recv = now;
   3221 
   3222  /* Clear any potential netflow padding timer. We're active */
   3223  monotime_coarse_zero(&chan->next_padding_time);
   3224 }
   3225 
   3226 /**
   3227 * Update the xmit timestamp.
   3228 *
   3229 * This is called whenever we pass an outgoing cell to the lower layer.  This
   3230 * also updates the active timestamp.
   3231 */
   3232 void
   3233 channel_timestamp_xmit(channel_t *chan)
   3234 {
   3235  time_t now = time(NULL);
   3236  tor_assert(chan);
   3237 
   3238  monotime_coarse_get(&chan->timestamp_xfer);
   3239 
   3240  chan->timestamp_active = now;
   3241  chan->timestamp_xmit = now;
   3242 
   3243  /* Clear any potential netflow padding timer. We're active */
   3244  monotime_coarse_zero(&chan->next_padding_time);
   3245 }
   3246 
   3247 /***************************************************************
   3248 * Timestamp queries - see above for definitions of timestamps *
   3249 **************************************************************/
   3250 
   3251 /**
   3252 * Query created timestamp for a channel.
   3253 */
   3254 time_t
   3255 channel_when_created(channel_t *chan)
   3256 {
   3257  tor_assert(chan);
   3258 
   3259  return chan->timestamp_created;
   3260 }
   3261 
   3262 /**
   3263 * Query client timestamp.
   3264 */
   3265 time_t
   3266 channel_when_last_client(channel_t *chan)
   3267 {
   3268  tor_assert(chan);
   3269 
   3270  return chan->timestamp_client;
   3271 }
   3272 
   3273 /**
   3274 * Query xmit timestamp.
   3275 */
   3276 time_t
   3277 channel_when_last_xmit(channel_t *chan)
   3278 {
   3279  tor_assert(chan);
   3280 
   3281  return chan->timestamp_xmit;
   3282 }
   3283 
   3284 /**
   3285 * Check if a channel matches an extend_info_t.
   3286 *
   3287 * This function calls the lower layer and asks if this channel matches a
   3288 * given extend_info_t.
   3289 *
   3290 * NOTE that this function only checks for an address/port match, and should
   3291 * be used only when no identity is available.
   3292 */
   3293 int
   3294 channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
   3295 {
   3296  tor_assert(chan);
   3297  tor_assert(chan->matches_extend_info);
   3298  tor_assert(extend_info);
   3299 
   3300  return chan->matches_extend_info(chan, extend_info);
   3301 }
   3302 
   3303 /**
   3304 * Check if a channel matches the given target IPv4 or IPv6 addresses.
   3305 * If either address matches, return true. If neither address matches,
   3306 * return false.
   3307 *
   3308 * Both addresses can't be NULL.
   3309 *
   3310 * This function calls into the lower layer and asks if this channel thinks
   3311 * it matches the target addresses for circuit extension purposes.
   3312 */
   3313 STATIC bool
   3314 channel_matches_target_addr_for_extend(channel_t *chan,
   3315                                       const tor_addr_t *target_ipv4_addr,
   3316                                       const tor_addr_t *target_ipv6_addr)
   3317 {
   3318  tor_assert(chan);
   3319  tor_assert(chan->matches_target);
   3320 
   3321  IF_BUG_ONCE(!target_ipv4_addr && !target_ipv6_addr)
   3322    return false;
   3323 
   3324  if (target_ipv4_addr && chan->matches_target(chan, target_ipv4_addr))
   3325    return true;
   3326 
   3327  if (target_ipv6_addr && chan->matches_target(chan, target_ipv6_addr))
   3328    return true;
   3329 
   3330  return false;
   3331 }
   3332 
   3333 /**
   3334 * Return the total number of circuits used by a channel.
   3335 *
   3336 * @param chan Channel to query
   3337 * @return Number of circuits using this as n_chan or p_chan
   3338 */
   3339 unsigned int
   3340 channel_num_circuits(channel_t *chan)
   3341 {
   3342  tor_assert(chan);
   3343 
   3344  return chan->num_n_circuits +
   3345         chan->num_p_circuits;
   3346 }
   3347 
   3348 /**
   3349 * Set up circuit ID generation.
   3350 *
   3351 * This is called when setting up a channel and replaces the old
   3352 * connection_or_set_circid_type().
   3353 */
   3354 MOCK_IMPL(void,
   3355 channel_set_circid_type,(channel_t *chan,
   3356                         crypto_pk_t *identity_rcvd,
   3357                         int consider_identity))
   3358 {
   3359  int started_here;
   3360  crypto_pk_t *our_identity;
   3361 
   3362  tor_assert(chan);
   3363 
   3364  started_here = channel_is_outgoing(chan);
   3365 
   3366  if (! consider_identity) {
   3367    if (started_here)
   3368      chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
   3369    else
   3370      chan->circ_id_type = CIRC_ID_TYPE_LOWER;
   3371    return;
   3372  }
   3373 
   3374  our_identity = started_here ?
   3375    get_tlsclient_identity_key() : get_server_identity_key();
   3376 
   3377  if (identity_rcvd) {
   3378    if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
   3379      chan->circ_id_type = CIRC_ID_TYPE_LOWER;
   3380    } else {
   3381      chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
   3382    }
   3383  } else {
   3384    chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
   3385  }
   3386 }
   3387 
   3388 static int
   3389 channel_sort_by_ed25519_identity(const void **a_, const void **b_)
   3390 {
   3391  const channel_t *a = *a_,
   3392                  *b = *b_;
   3393  return fast_memcmp(&a->ed25519_identity.pubkey,
   3394                     &b->ed25519_identity.pubkey,
   3395                     sizeof(a->ed25519_identity.pubkey));
   3396 }
   3397 
   3398 /** Helper for channel_update_bad_for_new_circs(): Perform the
   3399 * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
   3400 * all of which MUST have the same RSA ID.  (They MAY have different
   3401 * Ed25519 IDs.) */
   3402 static void
   3403 channel_rsa_id_group_set_badness(struct channel_list_t *lst, int force)
   3404 {
   3405  /*XXXX This function should really be about channels. 15056 */
   3406  channel_t *chan = TOR_LIST_FIRST(lst);
   3407 
   3408  if (!chan)
   3409    return;
   3410 
   3411  /* if there is only one channel, don't bother looping */
   3412  if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan, next_with_same_id))) {
   3413    connection_or_single_set_badness_(
   3414            time(NULL), BASE_CHAN_TO_TLS(chan)->conn, force);
   3415    return;
   3416  }
   3417 
   3418  smartlist_t *channels = smartlist_new();
   3419 
   3420  TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
   3421    if (BASE_CHAN_TO_TLS(chan)->conn) {
   3422      smartlist_add(channels, chan);
   3423    }
   3424  }
   3425 
   3426  smartlist_sort(channels, channel_sort_by_ed25519_identity);
   3427 
   3428  const ed25519_public_key_t *common_ed25519_identity = NULL;
   3429  /* it would be more efficient to do a slice, but this case is rare */
   3430  smartlist_t *or_conns = smartlist_new();
   3431  SMARTLIST_FOREACH_BEGIN(channels, channel_t *, channel) {
   3432    tor_assert(channel); // Suppresses some compiler warnings.
   3433 
   3434    if (!common_ed25519_identity)
   3435      common_ed25519_identity = &channel->ed25519_identity;
   3436 
   3437    if (! ed25519_pubkey_eq(&channel->ed25519_identity,
   3438                            common_ed25519_identity)) {
   3439        connection_or_group_set_badness_(or_conns, force);
   3440        smartlist_clear(or_conns);
   3441        common_ed25519_identity = &channel->ed25519_identity;
   3442    }
   3443 
   3444    smartlist_add(or_conns, BASE_CHAN_TO_TLS(channel)->conn);
   3445  } SMARTLIST_FOREACH_END(channel);
   3446 
   3447  connection_or_group_set_badness_(or_conns, force);
   3448 
   3449  /* XXXX 15056 we may want to do something special with connections that have
   3450   * no set Ed25519 identity! */
   3451 
   3452  smartlist_free(or_conns);
   3453  smartlist_free(channels);
   3454 }
   3455 
   3456 /** Go through all the channels (or if <b>digest</b> is non-NULL, just
   3457 * the OR connections with that digest), and set the is_bad_for_new_circs
   3458 * flag based on the rules in connection_or_group_set_badness() (or just
   3459 * always set it if <b>force</b> is true).
   3460 */
   3461 void
   3462 channel_update_bad_for_new_circs(const char *digest, int force)
   3463 {
   3464  if (digest) {
   3465    channel_idmap_entry_t *ent;
   3466    channel_idmap_entry_t search;
   3467    memset(&search, 0, sizeof(search));
   3468    memcpy(search.digest, digest, DIGEST_LEN);
   3469    ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
   3470    if (ent) {
   3471      channel_rsa_id_group_set_badness(&ent->channel_list, force);
   3472    }
   3473    return;
   3474  }
   3475 
   3476  /* no digest; just look at everything. */
   3477  channel_idmap_entry_t **iter;
   3478  HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
   3479    channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
   3480  }
   3481 }