tor

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

circuitlist.c (95137B)


      1 /* Copyright 2001 Matej Pfajfar.
      2 * Copyright (c) 2001-2004, Roger Dingledine.
      3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      5 /* See LICENSE for licensing information */
      6 
      7 /**
      8 * \file circuitlist.c
      9 *
     10 * \brief Manage global structures that list and index circuits, and
     11 *   look up circuits within them.
     12 *
     13 * One of the most frequent operations in Tor occurs every time that
     14 * a relay cell arrives on a channel.  When that happens, we need to
     15 * find which circuit it is associated with, based on the channel and the
     16 * circuit ID in the relay cell.
     17 *
     18 * To handle that, we maintain a global list of circuits, and a hashtable
     19 * mapping [channel,circID] pairs to circuits.  Circuits are added to and
     20 * removed from this mapping using circuit_set_p_circid_chan() and
     21 * circuit_set_n_circid_chan().  To look up a circuit from this map, most
     22 * callers should use circuit_get_by_circid_channel(), though
     23 * circuit_get_by_circid_channel_even_if_marked() is appropriate under some
     24 * circumstances.
     25 *
     26 * We also need to allow for the possibility that we have blocked use of a
     27 * circuit ID (because we are waiting to send a DESTROY cell), but the
     28 * circuit is not there any more.  For that case, we allow placeholder
     29 * entries in the table, using channel_mark_circid_unusable().
     30 *
     31 * To efficiently handle a channel that has just opened, we also maintain a
     32 * list of the circuits waiting for channels, so we can attach them as
     33 * needed without iterating through the whole list of circuits, using
     34 * circuit_get_all_pending_on_channel().
     35 *
     36 * In this module, we also handle the list of circuits that have been
     37 * marked for close elsewhere, and close them as needed.  (We use this
     38 * "mark now, close later" pattern here and elsewhere to avoid
     39 * unpredictable recursion if we closed every circuit immediately upon
     40 * realizing it needed to close.)  See circuit_mark_for_close() for the
     41 * mark function, and circuit_close_all_marked() for the close function.
     42 *
     43 * For hidden services, we need to be able to look up introduction point
     44 * circuits and rendezvous circuits by cookie, key, etc.  These are
     45 * currently handled with linear searches in
     46 * circuit_get_next_by_pk_and_purpose(), and with hash lookups in
     47 * circuit_get_rendezvous() and circuit_get_intro_point().
     48 *
     49 * This module is also the entry point for our out-of-memory handler
     50 * logic, which was originally circuit-focused.
     51 **/
     52 #define CIRCUITLIST_PRIVATE
     53 #define OCIRC_EVENT_PRIVATE
     54 #include "lib/cc/torint.h"  /* TOR_PRIuSZ */
     55 
     56 #include "core/or/or.h"
     57 #include "core/or/channel.h"
     58 #include "core/or/channeltls.h"
     59 #include "feature/client/circpathbias.h"
     60 #include "core/or/circuitbuild.h"
     61 #include "core/or/circuitlist.h"
     62 #include "core/or/circuituse.h"
     63 #include "core/or/circuitstats.h"
     64 #include "core/or/circuitpadding.h"
     65 #include "core/or/conflux.h"
     66 #include "core/or/conflux_pool.h"
     67 #include "core/or/crypt_path.h"
     68 #include "core/or/dos.h"
     69 #include "core/or/extendinfo.h"
     70 #include "core/or/status.h"
     71 #include "core/or/trace_probes_circuit.h"
     72 #include "core/mainloop/connection.h"
     73 #include "app/config/config.h"
     74 #include "core/or/connection_edge.h"
     75 #include "core/or/connection_or.h"
     76 #include "feature/control/control_events.h"
     77 #include "lib/crypt_ops/crypto_rand.h"
     78 #include "lib/crypt_ops/crypto_util.h"
     79 #include "lib/crypt_ops/crypto_dh.h"
     80 #include "feature/dircommon/directory.h"
     81 #include "feature/client/entrynodes.h"
     82 #include "core/mainloop/mainloop.h"
     83 #include "feature/hs/hs_cache.h"
     84 #include "feature/hs/hs_circuit.h"
     85 #include "feature/hs/hs_circuitmap.h"
     86 #include "feature/hs/hs_ident.h"
     87 #include "feature/nodelist/networkstatus.h"
     88 #include "feature/nodelist/nodelist.h"
     89 #include "feature/relay/onion_queue.h"
     90 #include "core/crypto/onion_crypto.h"
     91 #include "core/crypto/onion_fast.h"
     92 #include "core/or/policies.h"
     93 #include "core/or/relay.h"
     94 #include "core/crypto/relay_crypto.h"
     95 #include "feature/rend/rendcommon.h"
     96 #include "feature/stats/predict_ports.h"
     97 #include "feature/stats/bwhist.h"
     98 #include "feature/stats/rephist.h"
     99 #include "feature/nodelist/routerlist.h"
    100 #include "feature/nodelist/routerset.h"
    101 #include "core/or/channelpadding.h"
    102 #include "lib/compress/compress.h"
    103 #include "lib/compress/compress_lzma.h"
    104 #include "lib/compress/compress_zlib.h"
    105 #include "lib/compress/compress_zstd.h"
    106 #include "lib/buf/buffers.h"
    107 #include "core/or/congestion_control_common.h"
    108 #include "core/or/congestion_control_st.h"
    109 #include "lib/math/stats.h"
    110 
    111 #include "core/or/ocirc_event.h"
    112 
    113 #include "ht.h"
    114 
    115 #include "core/or/cpath_build_state_st.h"
    116 #include "core/or/crypt_path_reference_st.h"
    117 #include "feature/dircommon/dir_connection_st.h"
    118 #include "core/or/edge_connection_st.h"
    119 #include "core/or/half_edge_st.h"
    120 #include "core/or/extend_info_st.h"
    121 #include "core/or/or_circuit_st.h"
    122 #include "core/or/origin_circuit_st.h"
    123 
    124 #include "core/or/conflux_util.h"
    125 /********* START VARIABLES **********/
    126 
    127 /** A global list of all circuits at this hop. */
    128 static smartlist_t *global_circuitlist = NULL;
    129 
    130 /** A global list of all origin circuits. Every element of this is also
    131 * an element of global_circuitlist. */
    132 static smartlist_t *global_origin_circuit_list = NULL;
    133 
    134 /** A list of all the circuits in CIRCUIT_STATE_CHAN_WAIT. */
    135 static smartlist_t *circuits_pending_chans = NULL;
    136 
    137 /** List of all the (origin) circuits whose state is
    138 * CIRCUIT_STATE_GUARD_WAIT. */
    139 static smartlist_t *circuits_pending_other_guards = NULL;
    140 
    141 /** A list of all the circuits that have been marked with
    142 * circuit_mark_for_close and which are waiting for circuit_about_to_free. */
    143 static smartlist_t *circuits_pending_close = NULL;
    144 
    145 static void circuit_about_to_free_atexit(circuit_t *circ);
    146 static void circuit_about_to_free(circuit_t *circ);
    147 
    148 /**
    149 * A cached value of the current state of the origin circuit list.  Has the
    150 * value 1 if we saw any opened circuits recently (since the last call to
    151 * circuit_any_opened_circuits(), which gets called around once a second by
    152 * circuit_expire_building). 0 otherwise.
    153 */
    154 static int any_opened_circs_cached_val = 0;
    155 
    156 /** Moving average of the cc->cwnd from each closed circuit. */
    157 double cc_stats_circ_close_cwnd_ma = 0;
    158 /** Moving average of the cc->cwnd from each closed slow-start circuit. */
    159 double cc_stats_circ_close_ss_cwnd_ma = 0;
    160 
    161 uint64_t cc_stats_circs_closed = 0;
    162 
    163 /** Total number of circuit protocol violation. This is incremented when the
    164 * END_CIRC_REASON_TORPROTOCOL is used to close a circuit. */
    165 uint64_t circ_n_proto_violation = 0;
    166 
    167 /********* END VARIABLES ************/
    168 
    169 /* Implement circuit handle helpers. */
    170 HANDLE_IMPL(circuit, circuit_t,)
    171 
    172 or_circuit_t *
    173 TO_OR_CIRCUIT(circuit_t *x)
    174 {
    175  tor_assert(x->magic == OR_CIRCUIT_MAGIC);
    176  return DOWNCAST(or_circuit_t, x);
    177 }
    178 const or_circuit_t *
    179 CONST_TO_OR_CIRCUIT(const circuit_t *x)
    180 {
    181  tor_assert(x->magic == OR_CIRCUIT_MAGIC);
    182  return DOWNCAST(or_circuit_t, x);
    183 }
    184 origin_circuit_t *
    185 TO_ORIGIN_CIRCUIT(circuit_t *x)
    186 {
    187  tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
    188  return DOWNCAST(origin_circuit_t, x);
    189 }
    190 const origin_circuit_t *
    191 CONST_TO_ORIGIN_CIRCUIT(const circuit_t *x)
    192 {
    193  tor_assert(x->magic == ORIGIN_CIRCUIT_MAGIC);
    194  return DOWNCAST(origin_circuit_t, x);
    195 }
    196 
    197 /** A map from channel and circuit ID to circuit.  (Lookup performance is
    198 * very important here, since we need to do it every time a cell arrives.) */
    199 typedef struct chan_circid_circuit_map_t {
    200  HT_ENTRY(chan_circid_circuit_map_t) node;
    201  channel_t *chan;
    202  circid_t circ_id;
    203  circuit_t *circuit;
    204  /* For debugging 12184: when was this placeholder item added? */
    205  time_t made_placeholder_at;
    206 } chan_circid_circuit_map_t;
    207 
    208 /** Helper for hash tables: compare the channel and circuit ID for a and
    209 * b, and return less than, equal to, or greater than zero appropriately.
    210 */
    211 static inline int
    212 chan_circid_entries_eq_(chan_circid_circuit_map_t *a,
    213                        chan_circid_circuit_map_t *b)
    214 {
    215  return a->chan == b->chan && a->circ_id == b->circ_id;
    216 }
    217 
    218 /** Helper: return a hash based on circuit ID and the pointer value of
    219 * chan in <b>a</b>. */
    220 static inline unsigned int
    221 chan_circid_entry_hash_(chan_circid_circuit_map_t *a)
    222 {
    223  /* Try to squeze the siphash input into 8 bytes to save any extra siphash
    224   * rounds.  This hash function is in the critical path. */
    225  uintptr_t chan = (uintptr_t) (void*) a->chan;
    226  uint32_t array[2];
    227  array[0] = a->circ_id;
    228  /* The low bits of the channel pointer are uninteresting, since the channel
    229   * is a pretty big structure. */
    230  array[1] = (uint32_t) (chan >> 6);
    231  return (unsigned) siphash24g(array, sizeof(array));
    232 }
    233 
    234 /** Map from [chan,circid] to circuit. */
    235 static HT_HEAD(chan_circid_map, chan_circid_circuit_map_t)
    236     chan_circid_map = HT_INITIALIZER();
    237 HT_PROTOTYPE(chan_circid_map, chan_circid_circuit_map_t, node,
    238             chan_circid_entry_hash_, chan_circid_entries_eq_);
    239 HT_GENERATE2(chan_circid_map, chan_circid_circuit_map_t, node,
    240             chan_circid_entry_hash_, chan_circid_entries_eq_, 0.6,
    241             tor_reallocarray_, tor_free_);
    242 
    243 /** The most recently returned entry from circuit_get_by_circid_chan;
    244 * used to improve performance when many cells arrive in a row from the
    245 * same circuit.
    246 */
    247 static chan_circid_circuit_map_t *_last_circid_chan_ent = NULL;
    248 
    249 /** Implementation helper for circuit_set_{p,n}_circid_channel: A circuit ID
    250 * and/or channel for circ has just changed from <b>old_chan, old_id</b>
    251 * to <b>chan, id</b>.  Adjust the chan,circid map as appropriate, removing
    252 * the old entry (if any) and adding a new one. */
    253 static void
    254 circuit_set_circid_chan_helper(circuit_t *circ, int direction,
    255                               circid_t id,
    256                               channel_t *chan)
    257 {
    258  chan_circid_circuit_map_t search;
    259  chan_circid_circuit_map_t *found;
    260  channel_t *old_chan, **chan_ptr;
    261  circid_t old_id, *circid_ptr;
    262  int make_active, attached = 0;
    263 
    264  if (direction == CELL_DIRECTION_OUT) {
    265    chan_ptr = &circ->n_chan;
    266    circid_ptr = &circ->n_circ_id;
    267    make_active = circ->n_chan_cells.n > 0;
    268  } else {
    269    or_circuit_t *c = TO_OR_CIRCUIT(circ);
    270    chan_ptr = &c->p_chan;
    271    circid_ptr = &c->p_circ_id;
    272    make_active = c->p_chan_cells.n > 0;
    273  }
    274  old_chan = *chan_ptr;
    275  old_id = *circid_ptr;
    276 
    277  if (id == old_id && chan == old_chan)
    278    return;
    279 
    280  if (_last_circid_chan_ent &&
    281      ((old_id == _last_circid_chan_ent->circ_id &&
    282        old_chan == _last_circid_chan_ent->chan) ||
    283       (id == _last_circid_chan_ent->circ_id &&
    284        chan == _last_circid_chan_ent->chan))) {
    285    _last_circid_chan_ent = NULL;
    286  }
    287 
    288  if (old_chan) {
    289    /*
    290     * If we're changing channels or ID and had an old channel and a non
    291     * zero old ID and weren't marked for close (i.e., we should have been
    292     * attached), detach the circuit. ID changes require this because
    293     * circuitmux hashes on (channel_id, circuit_id).
    294     */
    295    if (old_id != 0 && (old_chan != chan || old_id != id) &&
    296        !(circ->marked_for_close)) {
    297      tor_assert(old_chan->cmux);
    298      circuitmux_detach_circuit(old_chan->cmux, circ);
    299    }
    300 
    301    /* we may need to remove it from the conn-circid map */
    302    search.circ_id = old_id;
    303    search.chan = old_chan;
    304    found = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
    305    if (found) {
    306      tor_free(found);
    307      if (direction == CELL_DIRECTION_OUT) {
    308        /* One fewer circuits use old_chan as n_chan */
    309        --(old_chan->num_n_circuits);
    310      } else {
    311        /* One fewer circuits use old_chan as p_chan */
    312        --(old_chan->num_p_circuits);
    313      }
    314    }
    315  }
    316 
    317  /* Change the values only after we have possibly made the circuit inactive
    318   * on the previous chan. */
    319  *chan_ptr = chan;
    320  *circid_ptr = id;
    321 
    322  if (chan == NULL)
    323    return;
    324 
    325  /* now add the new one to the conn-circid map */
    326  search.circ_id = id;
    327  search.chan = chan;
    328  found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
    329  if (found) {
    330    found->circuit = circ;
    331    found->made_placeholder_at = 0;
    332  } else {
    333    found = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
    334    found->circ_id = id;
    335    found->chan = chan;
    336    found->circuit = circ;
    337    HT_INSERT(chan_circid_map, &chan_circid_map, found);
    338  }
    339 
    340  /*
    341   * Attach to the circuitmux if we're changing channels or IDs and
    342   * have a new channel and ID to use and the circuit is not marked for
    343   * close.
    344   */
    345  if (chan && id != 0 && (old_chan != chan || old_id != id) &&
    346      !(circ->marked_for_close)) {
    347    tor_assert(chan->cmux);
    348    circuitmux_attach_circuit(chan->cmux, circ, direction);
    349    attached = 1;
    350  }
    351 
    352  /*
    353   * This is a no-op if we have no cells, but if we do it marks us active to
    354   * the circuitmux
    355   */
    356  if (make_active && attached)
    357    update_circuit_on_cmux(circ, direction);
    358 
    359  /* Adjust circuit counts on new channel */
    360  if (direction == CELL_DIRECTION_OUT) {
    361    ++chan->num_n_circuits;
    362  } else {
    363    ++chan->num_p_circuits;
    364  }
    365 }
    366 
    367 /** Mark that circuit id <b>id</b> shouldn't be used on channel <b>chan</b>,
    368 * even if there is no circuit on the channel. We use this to keep the
    369 * circuit id from getting re-used while we have queued but not yet sent
    370 * a destroy cell. */
    371 void
    372 channel_mark_circid_unusable(channel_t *chan, circid_t id)
    373 {
    374  chan_circid_circuit_map_t search;
    375  chan_circid_circuit_map_t *ent;
    376 
    377  /* See if there's an entry there. That wouldn't be good. */
    378  memset(&search, 0, sizeof(search));
    379  search.chan = chan;
    380  search.circ_id = id;
    381  ent = HT_FIND(chan_circid_map, &chan_circid_map, &search);
    382 
    383  if (ent && ent->circuit) {
    384    /* we have a problem. */
    385    log_warn(LD_BUG, "Tried to mark %u unusable on %p, but there was already "
    386             "a circuit there.", (unsigned)id, chan);
    387  } else if (ent) {
    388    /* It's already marked. */
    389    if (!ent->made_placeholder_at)
    390      ent->made_placeholder_at = approx_time();
    391  } else {
    392    ent = tor_malloc_zero(sizeof(chan_circid_circuit_map_t));
    393    ent->chan = chan;
    394    ent->circ_id = id;
    395    /* leave circuit at NULL. */
    396    ent->made_placeholder_at = approx_time();
    397    HT_INSERT(chan_circid_map, &chan_circid_map, ent);
    398  }
    399 }
    400 
    401 /** Mark that a circuit id <b>id</b> can be used again on <b>chan</b>.
    402 * We use this to re-enable the circuit ID after we've sent a destroy cell.
    403 */
    404 void
    405 channel_mark_circid_usable(channel_t *chan, circid_t id)
    406 {
    407  chan_circid_circuit_map_t search;
    408  chan_circid_circuit_map_t *ent;
    409 
    410  /* See if there's an entry there. That wouldn't be good. */
    411  memset(&search, 0, sizeof(search));
    412  search.chan = chan;
    413  search.circ_id = id;
    414  ent = HT_REMOVE(chan_circid_map, &chan_circid_map, &search);
    415  if (ent && ent->circuit) {
    416    log_warn(LD_BUG, "Tried to mark %u usable on %p, but there was already "
    417             "a circuit there.", (unsigned)id, chan);
    418    return;
    419  }
    420  if (_last_circid_chan_ent == ent)
    421    _last_circid_chan_ent = NULL;
    422  tor_free(ent);
    423 }
    424 
    425 /** Called to indicate that a DESTROY is pending on <b>chan</b> with
    426 * circuit ID <b>id</b>, but hasn't been sent yet. */
    427 void
    428 channel_note_destroy_pending(channel_t *chan, circid_t id)
    429 {
    430  circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
    431  if (circ) {
    432    if (circ->n_chan == chan && circ->n_circ_id == id) {
    433      circ->n_delete_pending = 1;
    434    } else {
    435      or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
    436      if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
    437        circ->p_delete_pending = 1;
    438      }
    439    }
    440    return;
    441  }
    442  channel_mark_circid_unusable(chan, id);
    443 }
    444 
    445 /** Called to indicate that a DESTROY is no longer pending on <b>chan</b> with
    446 * circuit ID <b>id</b> -- typically, because it has been sent. */
    447 MOCK_IMPL(void,
    448 channel_note_destroy_not_pending,(channel_t *chan, circid_t id))
    449 {
    450  circuit_t *circ = circuit_get_by_circid_channel_even_if_marked(id,chan);
    451  if (circ) {
    452    if (circ->n_chan == chan && circ->n_circ_id == id) {
    453      circ->n_delete_pending = 0;
    454    } else {
    455      or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
    456      if (orcirc->p_chan == chan && orcirc->p_circ_id == id) {
    457        circ->p_delete_pending = 0;
    458      }
    459    }
    460    /* XXXX this shouldn't happen; log a bug here. */
    461    return;
    462  }
    463  channel_mark_circid_usable(chan, id);
    464 }
    465 
    466 /** Set the p_conn field of a circuit <b>circ</b>, along
    467 * with the corresponding circuit ID, and add the circuit as appropriate
    468 * to the (chan,id)-\>circuit map. */
    469 void
    470 circuit_set_p_circid_chan(or_circuit_t *or_circ, circid_t id,
    471                          channel_t *chan)
    472 {
    473  circuit_t *circ = TO_CIRCUIT(or_circ);
    474  channel_t *old_chan = or_circ->p_chan;
    475  circid_t old_id = or_circ->p_circ_id;
    476 
    477  circuit_set_circid_chan_helper(circ, CELL_DIRECTION_IN, id, chan);
    478 
    479  if (chan) {
    480    chan->timestamp_last_had_circuits = approx_time();
    481  }
    482 
    483  if (circ->p_delete_pending && old_chan) {
    484    channel_mark_circid_unusable(old_chan, old_id);
    485    circ->p_delete_pending = 0;
    486  }
    487 }
    488 
    489 /** Set the n_conn field of a circuit <b>circ</b>, along
    490 * with the corresponding circuit ID, and add the circuit as appropriate
    491 * to the (chan,id)-\>circuit map. */
    492 void
    493 circuit_set_n_circid_chan(circuit_t *circ, circid_t id,
    494                          channel_t *chan)
    495 {
    496  channel_t *old_chan = circ->n_chan;
    497  circid_t old_id = circ->n_circ_id;
    498 
    499  circuit_set_circid_chan_helper(circ, CELL_DIRECTION_OUT, id, chan);
    500 
    501  if (chan) {
    502    chan->timestamp_last_had_circuits = approx_time();
    503  }
    504 
    505  if (circ->n_delete_pending && old_chan) {
    506    channel_mark_circid_unusable(old_chan, old_id);
    507    circ->n_delete_pending = 0;
    508  }
    509 }
    510 
    511 /**
    512 * Helper function to publish a message about events on an origin circuit
    513 *
    514 * Publishes a message to subscribers of origin circuit events, and
    515 * sends the control event.
    516 **/
    517 int
    518 circuit_event_status(origin_circuit_t *circ, circuit_status_event_t tp,
    519                     int reason_code)
    520 {
    521  ocirc_cevent_msg_t *msg = tor_malloc(sizeof(*msg));
    522 
    523  tor_assert(circ);
    524 
    525  msg->gid = circ->global_identifier;
    526  msg->evtype = tp;
    527  msg->reason = reason_code;
    528  msg->onehop = circ->build_state->onehop_tunnel;
    529 
    530  ocirc_cevent_publish(msg);
    531  return control_event_circuit_status(circ, tp, reason_code);
    532 }
    533 
    534 /**
    535 * Helper function to publish a state change message
    536 *
    537 * circuit_set_state() calls this to notify subscribers about a change
    538 * of the state of an origin circuit.  @a circ must be an origin
    539 * circuit.
    540 **/
    541 static void
    542 circuit_state_publish(const circuit_t *circ)
    543 {
    544  ocirc_state_msg_t *msg = tor_malloc(sizeof(*msg));
    545  const origin_circuit_t *ocirc;
    546 
    547  tor_assert(CIRCUIT_IS_ORIGIN(circ));
    548  ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
    549  /* Only inbound OR circuits can be in this state, not origin circuits. */
    550  tor_assert(circ->state != CIRCUIT_STATE_ONIONSKIN_PENDING);
    551 
    552  msg->gid = ocirc->global_identifier;
    553  msg->state = circ->state;
    554  msg->onehop = ocirc->build_state->onehop_tunnel;
    555 
    556  ocirc_state_publish(msg);
    557 }
    558 
    559 /** Change the state of <b>circ</b> to <b>state</b>, adding it to or removing
    560 * it from lists as appropriate. */
    561 void
    562 circuit_set_state(circuit_t *circ, uint8_t state)
    563 {
    564  tor_assert(circ);
    565  if (state == circ->state)
    566    return;
    567  if (PREDICT_UNLIKELY(!circuits_pending_chans))
    568    circuits_pending_chans = smartlist_new();
    569  if (PREDICT_UNLIKELY(!circuits_pending_other_guards))
    570    circuits_pending_other_guards = smartlist_new();
    571  if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
    572    /* remove from waiting-circuit list. */
    573    smartlist_remove(circuits_pending_chans, circ);
    574  }
    575  if (state == CIRCUIT_STATE_CHAN_WAIT) {
    576    /* add to waiting-circuit list. */
    577    smartlist_add(circuits_pending_chans, circ);
    578  }
    579  if (circ->state == CIRCUIT_STATE_GUARD_WAIT) {
    580    smartlist_remove(circuits_pending_other_guards, circ);
    581  }
    582  if (state == CIRCUIT_STATE_GUARD_WAIT) {
    583    smartlist_add(circuits_pending_other_guards, circ);
    584  }
    585  if (state == CIRCUIT_STATE_GUARD_WAIT || state == CIRCUIT_STATE_OPEN)
    586    tor_assert(!circ->n_chan_create_cell);
    587 
    588  tor_trace(TR_SUBSYS(circuit), TR_EV(change_state), circ, circ->state, state);
    589  circ->state = state;
    590  if (CIRCUIT_IS_ORIGIN(circ))
    591    circuit_state_publish(circ);
    592 }
    593 
    594 /** Append to <b>out</b> all circuits in state CHAN_WAIT waiting for
    595 * the given connection. */
    596 void
    597 circuit_get_all_pending_on_channel(smartlist_t *out, channel_t *chan)
    598 {
    599  tor_assert(out);
    600  tor_assert(chan);
    601 
    602  if (!circuits_pending_chans)
    603    return;
    604 
    605  SMARTLIST_FOREACH_BEGIN(circuits_pending_chans, circuit_t *, circ) {
    606    if (circ->marked_for_close)
    607      continue;
    608    if (!circ->n_hop)
    609      continue;
    610    tor_assert(circ->state == CIRCUIT_STATE_CHAN_WAIT);
    611    if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
    612      /* Look at addr/port. This is an unkeyed connection. */
    613      if (!channel_matches_extend_info(chan, circ->n_hop))
    614        continue;
    615    } else {
    616      /* We expected a key. See if it's the right one. */
    617      if (tor_memneq(chan->identity_digest,
    618                     circ->n_hop->identity_digest, DIGEST_LEN))
    619        continue;
    620    }
    621    smartlist_add(out, circ);
    622  } SMARTLIST_FOREACH_END(circ);
    623 }
    624 
    625 /** Return the number of circuits in state CHAN_WAIT, waiting for the given
    626 * channel. */
    627 int
    628 circuit_count_pending_on_channel(channel_t *chan)
    629 {
    630  int cnt;
    631  smartlist_t *sl = smartlist_new();
    632 
    633  tor_assert(chan);
    634 
    635  circuit_get_all_pending_on_channel(sl, chan);
    636  cnt = smartlist_len(sl);
    637  smartlist_free(sl);
    638  log_debug(LD_CIRC,"or_conn to %s, %d pending circs",
    639            channel_describe_peer(chan),
    640            cnt);
    641  return cnt;
    642 }
    643 
    644 /** Remove <b>origin_circ</b> from the global list of origin circuits.
    645 * Called when we are freeing a circuit.
    646 */
    647 static void
    648 circuit_remove_from_origin_circuit_list(origin_circuit_t *origin_circ)
    649 {
    650  int origin_idx = origin_circ->global_origin_circuit_list_idx;
    651  if (origin_idx < 0)
    652    return;
    653  origin_circuit_t *c2;
    654  tor_assert(origin_idx <= smartlist_len(global_origin_circuit_list));
    655  c2 = smartlist_get(global_origin_circuit_list, origin_idx);
    656  tor_assert(origin_circ == c2);
    657  smartlist_del(global_origin_circuit_list, origin_idx);
    658  if (origin_idx < smartlist_len(global_origin_circuit_list)) {
    659    origin_circuit_t *replacement =
    660      smartlist_get(global_origin_circuit_list, origin_idx);
    661    replacement->global_origin_circuit_list_idx = origin_idx;
    662  }
    663  origin_circ->global_origin_circuit_list_idx = -1;
    664 }
    665 
    666 /** Add <b>origin_circ</b> to the global list of origin circuits. Called
    667 * when creating the circuit. */
    668 static void
    669 circuit_add_to_origin_circuit_list(origin_circuit_t *origin_circ)
    670 {
    671  tor_assert(origin_circ->global_origin_circuit_list_idx == -1);
    672  smartlist_t *lst = circuit_get_global_origin_circuit_list();
    673  smartlist_add(lst, origin_circ);
    674  origin_circ->global_origin_circuit_list_idx = smartlist_len(lst) - 1;
    675 }
    676 
    677 /** Detach from the global circuit list, and deallocate, all
    678 * circuits that have been marked for close.
    679 */
    680 void
    681 circuit_close_all_marked(void)
    682 {
    683  if (circuits_pending_close == NULL)
    684    return;
    685 
    686  smartlist_t *lst = circuit_get_global_list();
    687  SMARTLIST_FOREACH_BEGIN(circuits_pending_close, circuit_t *, circ) {
    688    tor_assert(circ->marked_for_close);
    689 
    690    /* Remove it from the circuit list. */
    691    int idx = circ->global_circuitlist_idx;
    692    smartlist_del(lst, idx);
    693    if (idx < smartlist_len(lst)) {
    694      circuit_t *replacement = smartlist_get(lst, idx);
    695      replacement->global_circuitlist_idx = idx;
    696    }
    697    circ->global_circuitlist_idx = -1;
    698 
    699    /* Remove it from the origin circuit list, if appropriate. */
    700    if (CIRCUIT_IS_ORIGIN(circ)) {
    701      circuit_remove_from_origin_circuit_list(TO_ORIGIN_CIRCUIT(circ));
    702    }
    703 
    704    circuit_about_to_free(circ);
    705    circuit_free(circ);
    706  } SMARTLIST_FOREACH_END(circ);
    707 
    708  smartlist_clear(circuits_pending_close);
    709 }
    710 
    711 /** Return a pointer to the global list of circuits. */
    712 MOCK_IMPL(smartlist_t *,
    713 circuit_get_global_list,(void))
    714 {
    715  if (NULL == global_circuitlist)
    716    global_circuitlist = smartlist_new();
    717  return global_circuitlist;
    718 }
    719 
    720 /** Return a pointer to the global list of origin circuits. */
    721 smartlist_t *
    722 circuit_get_global_origin_circuit_list(void)
    723 {
    724  if (NULL == global_origin_circuit_list)
    725    global_origin_circuit_list = smartlist_new();
    726  return global_origin_circuit_list;
    727 }
    728 
    729 /**
    730 * Return true if we have any opened general-purpose 3 hop
    731 * origin circuits.
    732 *
    733 * The result from this function is cached for use by
    734 * circuit_any_opened_circuits_cached().
    735 */
    736 int
    737 circuit_any_opened_circuits(void)
    738 {
    739  SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
    740          const origin_circuit_t *, next_circ) {
    741    if (!TO_CIRCUIT(next_circ)->marked_for_close &&
    742        next_circ->has_opened &&
    743        TO_CIRCUIT(next_circ)->state == CIRCUIT_STATE_OPEN &&
    744        TO_CIRCUIT(next_circ)->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
    745        next_circ->build_state &&
    746        next_circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN) {
    747      circuit_cache_opened_circuit_state(1);
    748      return 1;
    749    }
    750  } SMARTLIST_FOREACH_END(next_circ);
    751 
    752  circuit_cache_opened_circuit_state(0);
    753  return 0;
    754 }
    755 
    756 /**
    757 * Cache the "any circuits opened" state, as specified in param
    758 * circuits_are_opened. This is a helper function to update
    759 * the circuit opened status whenever we happen to look at the
    760 * circuit list.
    761 */
    762 void
    763 circuit_cache_opened_circuit_state(int circuits_are_opened)
    764 {
    765  any_opened_circs_cached_val = circuits_are_opened;
    766 }
    767 
    768 /**
    769 * Return true if there were any opened circuits since the last call to
    770 * circuit_any_opened_circuits(), or since circuit_expire_building() last
    771 * ran (it runs roughly once per second).
    772 */
    773 int
    774 circuit_any_opened_circuits_cached(void)
    775 {
    776  return any_opened_circs_cached_val;
    777 }
    778 
    779 /** Function to make circ-\>state human-readable */
    780 const char *
    781 circuit_state_to_string(int state)
    782 {
    783  static char buf[64];
    784  switch (state) {
    785    case CIRCUIT_STATE_BUILDING: return "doing handshakes";
    786    case CIRCUIT_STATE_ONIONSKIN_PENDING: return "processing the onion";
    787    case CIRCUIT_STATE_CHAN_WAIT: return "connecting to server";
    788    case CIRCUIT_STATE_GUARD_WAIT: return "waiting to see how other "
    789      "guards perform";
    790    case CIRCUIT_STATE_OPEN: return "open";
    791    default:
    792      log_warn(LD_BUG, "Unknown circuit state %d", state);
    793      tor_snprintf(buf, sizeof(buf), "unknown state [%d]", state);
    794      return buf;
    795  }
    796 }
    797 
    798 /** Map a circuit purpose to a string suitable to be displayed to a
    799 * controller. */
    800 const char *
    801 circuit_purpose_to_controller_string(uint8_t purpose)
    802 {
    803  static char buf[32];
    804  switch (purpose) {
    805    case CIRCUIT_PURPOSE_OR:
    806    case CIRCUIT_PURPOSE_INTRO_POINT:
    807    case CIRCUIT_PURPOSE_REND_POINT_WAITING:
    808    case CIRCUIT_PURPOSE_REND_ESTABLISHED:
    809      return "SERVER"; /* A controller should never see these, actually. */
    810 
    811    case CIRCUIT_PURPOSE_C_GENERAL:
    812      return "GENERAL";
    813 
    814    case CIRCUIT_PURPOSE_C_HSDIR_GET:
    815      return "HS_CLIENT_HSDIR";
    816 
    817    case CIRCUIT_PURPOSE_C_INTRODUCING:
    818    case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
    819    case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
    820      return "HS_CLIENT_INTRO";
    821 
    822    case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
    823    case CIRCUIT_PURPOSE_C_REND_READY:
    824    case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
    825    case CIRCUIT_PURPOSE_C_REND_JOINED:
    826      return "HS_CLIENT_REND";
    827 
    828    case CIRCUIT_PURPOSE_S_HSDIR_POST:
    829      return "HS_SERVICE_HSDIR";
    830 
    831    case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
    832    case CIRCUIT_PURPOSE_S_INTRO:
    833      return "HS_SERVICE_INTRO";
    834 
    835    case CIRCUIT_PURPOSE_S_CONNECT_REND:
    836    case CIRCUIT_PURPOSE_S_REND_JOINED:
    837      return "HS_SERVICE_REND";
    838 
    839    case CIRCUIT_PURPOSE_TESTING:
    840      return "TESTING";
    841    case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
    842      return "MEASURE_TIMEOUT";
    843    case CIRCUIT_PURPOSE_CONTROLLER:
    844      return "CONTROLLER";
    845    case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
    846      return "PATH_BIAS_TESTING";
    847    case CIRCUIT_PURPOSE_HS_VANGUARDS:
    848      return "HS_VANGUARDS";
    849    case CIRCUIT_PURPOSE_C_CIRCUIT_PADDING:
    850      return "CIRCUIT_PADDING";
    851 
    852    case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
    853      return "CONFLUX_UNLINKED";
    854    case CIRCUIT_PURPOSE_CONFLUX_LINKED:
    855      return "CONFLUX_LINKED";
    856 
    857    default:
    858      tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
    859      return buf;
    860  }
    861 }
    862 
    863 /** Return a string specifying the state of the hidden-service circuit
    864 * purpose <b>purpose</b>, or NULL if <b>purpose</b> is not a
    865 * hidden-service-related circuit purpose. */
    866 const char *
    867 circuit_purpose_to_controller_hs_state_string(uint8_t purpose)
    868 {
    869  switch (purpose)
    870    {
    871    default:
    872      log_fn(LOG_WARN, LD_BUG,
    873             "Unrecognized circuit purpose: %d",
    874             (int)purpose);
    875      tor_fragile_assert();
    876      FALLTHROUGH_UNLESS_ALL_BUGS_ARE_FATAL;
    877 
    878    case CIRCUIT_PURPOSE_OR:
    879    case CIRCUIT_PURPOSE_C_GENERAL:
    880    case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
    881    case CIRCUIT_PURPOSE_TESTING:
    882    case CIRCUIT_PURPOSE_CONTROLLER:
    883    case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
    884    case CIRCUIT_PURPOSE_HS_VANGUARDS:
    885    case CIRCUIT_PURPOSE_C_CIRCUIT_PADDING:
    886    case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
    887    case CIRCUIT_PURPOSE_CONFLUX_LINKED:
    888      return NULL;
    889 
    890    case CIRCUIT_PURPOSE_INTRO_POINT:
    891      return "OR_HSSI_ESTABLISHED";
    892    case CIRCUIT_PURPOSE_REND_POINT_WAITING:
    893      return "OR_HSCR_ESTABLISHED";
    894    case CIRCUIT_PURPOSE_REND_ESTABLISHED:
    895      return "OR_HS_R_JOINED";
    896 
    897    case CIRCUIT_PURPOSE_C_HSDIR_GET:
    898    case CIRCUIT_PURPOSE_C_INTRODUCING:
    899      return "HSCI_CONNECTING";
    900    case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
    901      return "HSCI_INTRO_SENT";
    902    case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
    903      return "HSCI_DONE";
    904 
    905    case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
    906      return "HSCR_CONNECTING";
    907    case CIRCUIT_PURPOSE_C_REND_READY:
    908      return "HSCR_ESTABLISHED_IDLE";
    909    case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
    910      return "HSCR_ESTABLISHED_WAITING";
    911    case CIRCUIT_PURPOSE_C_REND_JOINED:
    912      return "HSCR_JOINED";
    913 
    914    case CIRCUIT_PURPOSE_S_HSDIR_POST:
    915    case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
    916      return "HSSI_CONNECTING";
    917    case CIRCUIT_PURPOSE_S_INTRO:
    918      return "HSSI_ESTABLISHED";
    919 
    920    case CIRCUIT_PURPOSE_S_CONNECT_REND:
    921      return "HSSR_CONNECTING";
    922    case CIRCUIT_PURPOSE_S_REND_JOINED:
    923      return "HSSR_JOINED";
    924    }
    925 }
    926 
    927 /** Return a human-readable string for the circuit purpose <b>purpose</b>. */
    928 const char *
    929 circuit_purpose_to_string(uint8_t purpose)
    930 {
    931  static char buf[32];
    932 
    933  switch (purpose)
    934    {
    935    case CIRCUIT_PURPOSE_OR:
    936      return "Circuit at relay";
    937    case CIRCUIT_PURPOSE_INTRO_POINT:
    938      return "Acting as intro point";
    939    case CIRCUIT_PURPOSE_REND_POINT_WAITING:
    940      return "Acting as rendezvous (pending)";
    941    case CIRCUIT_PURPOSE_REND_ESTABLISHED:
    942      return "Acting as rendezvous (established)";
    943    case CIRCUIT_PURPOSE_C_GENERAL:
    944      return "General-purpose client";
    945    case CIRCUIT_PURPOSE_C_INTRODUCING:
    946      return "Hidden service client: Connecting to intro point";
    947    case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
    948      return "Hidden service client: Waiting for ack from intro point";
    949    case CIRCUIT_PURPOSE_C_INTRODUCE_ACKED:
    950      return "Hidden service client: Received ack from intro point";
    951    case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
    952      return "Hidden service client: Establishing rendezvous point";
    953    case CIRCUIT_PURPOSE_C_REND_READY:
    954      return "Hidden service client: Pending rendezvous point";
    955    case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
    956      return "Hidden service client: Pending rendezvous point (ack received)";
    957    case CIRCUIT_PURPOSE_C_REND_JOINED:
    958      return "Hidden service client: Active rendezvous point";
    959    case CIRCUIT_PURPOSE_C_HSDIR_GET:
    960      return "Hidden service client: Fetching HS descriptor";
    961 
    962    case CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT:
    963      return "Measuring circuit timeout";
    964 
    965    case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
    966      return "Hidden service: Establishing introduction point";
    967    case CIRCUIT_PURPOSE_S_INTRO:
    968      return "Hidden service: Introduction point";
    969    case CIRCUIT_PURPOSE_S_CONNECT_REND:
    970      return "Hidden service: Connecting to rendezvous point";
    971    case CIRCUIT_PURPOSE_S_REND_JOINED:
    972      return "Hidden service: Active rendezvous point";
    973    case CIRCUIT_PURPOSE_S_HSDIR_POST:
    974      return "Hidden service: Uploading HS descriptor";
    975 
    976    case CIRCUIT_PURPOSE_TESTING:
    977      return "Testing circuit";
    978 
    979    case CIRCUIT_PURPOSE_CONTROLLER:
    980      return "Circuit made by controller";
    981 
    982    case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
    983      return "Path-bias testing circuit";
    984 
    985    case CIRCUIT_PURPOSE_HS_VANGUARDS:
    986      return "Hidden service: Pre-built vanguard circuit";
    987 
    988    case CIRCUIT_PURPOSE_C_CIRCUIT_PADDING:
    989      return "Circuit kept open for padding";
    990 
    991    case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
    992      return "Unlinked conflux circuit";
    993 
    994    case CIRCUIT_PURPOSE_CONFLUX_LINKED:
    995      return "Linked conflux circuit";
    996 
    997    default:
    998      tor_snprintf(buf, sizeof(buf), "UNKNOWN_%d", (int)purpose);
    999      return buf;
   1000  }
   1001 }
   1002 
   1003 /** Pick a reasonable package_window to start out for our circuits.
   1004 * Originally this was hard-coded at 1000, but now the consensus votes
   1005 * on the answer. See proposal 168. */
   1006 int32_t
   1007 circuit_initial_package_window(void)
   1008 {
   1009  int32_t num = networkstatus_get_param(NULL, "circwindow", CIRCWINDOW_START,
   1010                                        CIRCWINDOW_START_MIN,
   1011                                        CIRCWINDOW_START_MAX);
   1012  /* If the consensus tells us a negative number, we'd assert. */
   1013  if (num < 0)
   1014    num = CIRCWINDOW_START;
   1015  return num;
   1016 }
   1017 
   1018 /** Initialize the common elements in a circuit_t, and add it to the global
   1019 * list. */
   1020 static void
   1021 init_circuit_base(circuit_t *circ)
   1022 {
   1023  tor_gettimeofday(&circ->timestamp_created);
   1024 
   1025  // Gets reset when we send CREATE_FAST.
   1026  // circuit_expire_building() expects these to be equal
   1027  // until the orconn is built.
   1028  circ->timestamp_began = circ->timestamp_created;
   1029 
   1030  circ->package_window = circuit_initial_package_window();
   1031  circ->deliver_window = CIRCWINDOW_START;
   1032  circuit_reset_sendme_randomness(circ);
   1033  cell_queue_init(&circ->n_chan_cells);
   1034 
   1035  smartlist_add(circuit_get_global_list(), circ);
   1036  circ->global_circuitlist_idx = smartlist_len(circuit_get_global_list()) - 1;
   1037 }
   1038 
   1039 /** If we haven't yet decided on a good timeout value for circuit
   1040 * building, we close idle circuits aggressively so we can get more
   1041 * data points. These are the default, min, and max consensus values */
   1042 #define DFLT_IDLE_TIMEOUT_WHILE_LEARNING (3*60)
   1043 #define MIN_IDLE_TIMEOUT_WHILE_LEARNING (10)
   1044 #define MAX_IDLE_TIMEOUT_WHILE_LEARNING (1000*60)
   1045 
   1046 /** Allocate space for a new circuit, initializing with <b>p_circ_id</b>
   1047 * and <b>p_conn</b>. Add it to the global circuit list.
   1048 */
   1049 origin_circuit_t *
   1050 origin_circuit_new(void)
   1051 {
   1052  origin_circuit_t *circ;
   1053  /* never zero, since a global ID of 0 is treated specially by the
   1054   * controller */
   1055  static uint32_t n_circuits_allocated = 1;
   1056 
   1057  circ = tor_malloc_zero(sizeof(origin_circuit_t));
   1058  circ->base_.magic = ORIGIN_CIRCUIT_MAGIC;
   1059 
   1060  circ->next_stream_id = crypto_rand_int(1<<16);
   1061  circ->global_identifier = n_circuits_allocated++;
   1062  circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
   1063  circ->remaining_relay_early_cells -= crypto_rand_int(2);
   1064 
   1065  init_circuit_base(TO_CIRCUIT(circ));
   1066 
   1067  /* Add to origin-list. */
   1068  circ->global_origin_circuit_list_idx = -1;
   1069  circuit_add_to_origin_circuit_list(circ);
   1070 
   1071  circuit_build_times_update_last_circ(get_circuit_build_times_mutable());
   1072 
   1073  if (! circuit_build_times_disabled(get_options()) &&
   1074      circuit_build_times_needs_circuits(get_circuit_build_times())) {
   1075    /* Circuits should be shorter lived if we need more of them
   1076     * for learning a good build timeout */
   1077    circ->circuit_idle_timeout =
   1078      networkstatus_get_param(NULL, "cbtlearntimeout",
   1079                              DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
   1080                              MIN_IDLE_TIMEOUT_WHILE_LEARNING,
   1081                              MAX_IDLE_TIMEOUT_WHILE_LEARNING);
   1082  } else {
   1083    // This should always be larger than the current port prediction time
   1084    // remaining, or else we'll end up with the case where a circuit times out
   1085    // and another one is built, effectively doubling the timeout window.
   1086    //
   1087    // We also randomize it by up to 5% more (ie 5% of 0 to 3600 seconds,
   1088    // depending on how much circuit prediction time is remaining) so that
   1089    // we don't close a bunch of unused circuits all at the same time.
   1090    int prediction_time_remaining =
   1091      predicted_ports_prediction_time_remaining(time(NULL));
   1092    circ->circuit_idle_timeout = prediction_time_remaining+1+
   1093        crypto_rand_int(1+prediction_time_remaining/20);
   1094 
   1095    if (circ->circuit_idle_timeout <= 0) {
   1096      log_warn(LD_BUG,
   1097               "Circuit chose a negative idle timeout of %d based on "
   1098               "%d seconds of predictive building remaining.",
   1099               circ->circuit_idle_timeout,
   1100               prediction_time_remaining);
   1101      circ->circuit_idle_timeout =
   1102          networkstatus_get_param(NULL, "cbtlearntimeout",
   1103                  DFLT_IDLE_TIMEOUT_WHILE_LEARNING,
   1104                  MIN_IDLE_TIMEOUT_WHILE_LEARNING,
   1105                  MAX_IDLE_TIMEOUT_WHILE_LEARNING);
   1106    }
   1107 
   1108    log_info(LD_CIRC,
   1109              "Circuit %"PRIu32" chose an idle timeout of %d based on "
   1110              "%d seconds of predictive building remaining.",
   1111              (circ->global_identifier),
   1112              circ->circuit_idle_timeout,
   1113              prediction_time_remaining);
   1114  }
   1115 
   1116  tor_trace(TR_SUBSYS(circuit), TR_EV(new_origin), circ);
   1117  return circ;
   1118 }
   1119 
   1120 /** Allocate a new or_circuit_t, connected to <b>p_chan</b> as
   1121 * <b>p_circ_id</b>.  If <b>p_chan</b> is NULL, the circuit is unattached. */
   1122 or_circuit_t *
   1123 or_circuit_new(circid_t p_circ_id, channel_t *p_chan)
   1124 {
   1125  /* CircIDs */
   1126  or_circuit_t *circ;
   1127 
   1128  circ = tor_malloc_zero(sizeof(or_circuit_t));
   1129  circ->base_.magic = OR_CIRCUIT_MAGIC;
   1130 
   1131  if (p_chan)
   1132    circuit_set_p_circid_chan(circ, p_circ_id, p_chan);
   1133 
   1134  circ->remaining_relay_early_cells = MAX_RELAY_EARLY_CELLS_PER_CIRCUIT;
   1135  cell_queue_init(&circ->p_chan_cells);
   1136 
   1137  init_circuit_base(TO_CIRCUIT(circ));
   1138  dos_stream_init_circ_tbf(circ);
   1139 
   1140  tor_trace(TR_SUBSYS(circuit), TR_EV(new_or), circ);
   1141  return circ;
   1142 }
   1143 
   1144 /** Free all storage held in circ->testing_cell_stats */
   1145 void
   1146 circuit_clear_testing_cell_stats(circuit_t *circ)
   1147 {
   1148  if (!circ || !circ->testing_cell_stats)
   1149    return;
   1150  SMARTLIST_FOREACH(circ->testing_cell_stats, testing_cell_stats_entry_t *,
   1151                    ent, tor_free(ent));
   1152  smartlist_free(circ->testing_cell_stats);
   1153  circ->testing_cell_stats = NULL;
   1154 }
   1155 
   1156 /** Deallocate space associated with circ.
   1157 */
   1158 STATIC void
   1159 circuit_free_(circuit_t *circ)
   1160 {
   1161  circid_t n_circ_id = 0;
   1162  void *mem;
   1163  size_t memlen;
   1164  int should_free = 1;
   1165  if (!circ)
   1166    return;
   1167 
   1168  /* We keep a copy of this so we can log its value before it gets unset. */
   1169  n_circ_id = circ->n_circ_id;
   1170 
   1171  circuit_clear_testing_cell_stats(circ);
   1172 
   1173  /* Cleanup circuit from anything HS v3 related. We also do this when the
   1174   * circuit is closed. This is to avoid any code path that free registered
   1175   * circuits without closing them before. This needs to be done before the
   1176   * hs identifier is freed. */
   1177  hs_circ_cleanup_on_free(circ);
   1178 
   1179  congestion_control_free(circ->ccontrol);
   1180 
   1181  if (CIRCUIT_IS_ORIGIN(circ)) {
   1182    origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
   1183    mem = ocirc;
   1184    memlen = sizeof(origin_circuit_t);
   1185    tor_assert(circ->magic == ORIGIN_CIRCUIT_MAGIC);
   1186 
   1187    circuit_remove_from_origin_circuit_list(ocirc);
   1188 
   1189    if (ocirc->half_streams) {
   1190      SMARTLIST_FOREACH_BEGIN(ocirc->half_streams, half_edge_t *,
   1191                              half_conn) {
   1192        half_edge_free(half_conn);
   1193      } SMARTLIST_FOREACH_END(half_conn);
   1194      smartlist_free(ocirc->half_streams);
   1195    }
   1196 
   1197    if (ocirc->build_state) {
   1198        extend_info_free(ocirc->build_state->chosen_exit);
   1199    }
   1200    tor_free(ocirc->build_state);
   1201 
   1202    /* Cancel before freeing, if we haven't already succeeded or failed. */
   1203    if (ocirc->guard_state) {
   1204      entry_guard_cancel(&ocirc->guard_state);
   1205    }
   1206    circuit_guard_state_free(ocirc->guard_state);
   1207 
   1208    circuit_clear_cpath(ocirc);
   1209 
   1210    crypto_pk_free(ocirc->intro_key);
   1211 
   1212    /* Finally, free the identifier of the circuit and nullify it so multiple
   1213     * cleanup will work. */
   1214    hs_ident_circuit_free(ocirc->hs_ident);
   1215    ocirc->hs_ident = NULL;
   1216 
   1217    tor_free(ocirc->dest_address);
   1218    if (ocirc->socks_username) {
   1219      memwipe(ocirc->socks_username, 0x12, ocirc->socks_username_len);
   1220      tor_free(ocirc->socks_username);
   1221    }
   1222    if (ocirc->socks_password) {
   1223      memwipe(ocirc->socks_password, 0x06, ocirc->socks_password_len);
   1224      tor_free(ocirc->socks_password);
   1225    }
   1226    addr_policy_list_free(ocirc->prepend_policy);
   1227  } else {
   1228    or_circuit_t *ocirc = TO_OR_CIRCUIT(circ);
   1229    /* Remember cell statistics for this circuit before deallocating. */
   1230    if (get_options()->CellStatistics)
   1231      rep_hist_buffer_stats_add_circ(circ, time(NULL));
   1232    mem = ocirc;
   1233    memlen = sizeof(or_circuit_t);
   1234    tor_assert(circ->magic == OR_CIRCUIT_MAGIC);
   1235 
   1236    should_free = (ocirc->workqueue_entry == NULL);
   1237 
   1238    relay_crypto_clear(&ocirc->crypto);
   1239 
   1240    if (ocirc->rend_splice) {
   1241      or_circuit_t *other = ocirc->rend_splice;
   1242      tor_assert(other->base_.magic == OR_CIRCUIT_MAGIC);
   1243      other->rend_splice = NULL;
   1244    }
   1245 
   1246    /* remove from map. */
   1247    circuit_set_p_circid_chan(ocirc, 0, NULL);
   1248 
   1249    /* Clear cell queue _after_ removing it from the map.  Otherwise our
   1250     * "active" checks will be violated. */
   1251    cell_queue_clear(&ocirc->p_chan_cells);
   1252  }
   1253 
   1254  extend_info_free(circ->n_hop);
   1255  tor_free(circ->n_chan_create_cell);
   1256 
   1257  if (circ->global_circuitlist_idx != -1) {
   1258    int idx = circ->global_circuitlist_idx;
   1259    circuit_t *c2 = smartlist_get(global_circuitlist, idx);
   1260    tor_assert(c2 == circ);
   1261    smartlist_del(global_circuitlist, idx);
   1262    if (idx < smartlist_len(global_circuitlist)) {
   1263      c2 = smartlist_get(global_circuitlist, idx);
   1264      c2->global_circuitlist_idx = idx;
   1265    }
   1266  }
   1267 
   1268  /* Remove from map. */
   1269  circuit_set_n_circid_chan(circ, 0, NULL);
   1270 
   1271  /* Clear cell queue _after_ removing it from the map.  Otherwise our
   1272   * "active" checks will be violated. */
   1273  cell_queue_clear(&circ->n_chan_cells);
   1274 
   1275  /* Cleanup possible SENDME state. */
   1276  if (circ->sendme_last_digests) {
   1277    SMARTLIST_FOREACH(circ->sendme_last_digests, uint8_t *, d, tor_free(d));
   1278    smartlist_free(circ->sendme_last_digests);
   1279  }
   1280 
   1281  log_info(LD_CIRC, "Circuit %u (id: %" PRIu32 ") has been freed.",
   1282           n_circ_id,
   1283           CIRCUIT_IS_ORIGIN(circ) ?
   1284              TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0);
   1285 
   1286  /* Free any circuit padding structures */
   1287  circpad_circuit_free_all_machineinfos(circ);
   1288 
   1289  /* Clear all dangling handle references. */
   1290  circuit_handles_clear(circ);
   1291 
   1292  /* Tracepoint. Data within the circuit object is recorded so do this before
   1293   * the actual memory free. */
   1294  tor_trace(TR_SUBSYS(circuit), TR_EV(free), circ);
   1295 
   1296  if (should_free) {
   1297    memwipe(mem, 0xAA, memlen); /* poison memory */
   1298    tor_free(mem);
   1299  } else {
   1300    /* If we made it here, this is an or_circuit_t that still has a pending
   1301     * cpuworker request which we weren't able to cancel.  Instead, set up
   1302     * the magic value so that when the reply comes back, we'll know to discard
   1303     * the reply and free this structure.
   1304     */
   1305    memwipe(mem, 0xAA, memlen);
   1306    circ->magic = DEAD_CIRCUIT_MAGIC;
   1307  }
   1308 }
   1309 
   1310 /** Deallocate the linked list circ-><b>cpath</b>, and remove the cpath from
   1311 * <b>circ</b>. */
   1312 void
   1313 circuit_clear_cpath(origin_circuit_t *circ)
   1314 {
   1315  crypt_path_t *victim, *head, *cpath;
   1316 
   1317  head = cpath = circ->cpath;
   1318 
   1319  if (!cpath)
   1320    return;
   1321 
   1322  /* it's a circular list, so we have to notice when we've
   1323   * gone through it once. */
   1324  while (cpath->next && cpath->next != head) {
   1325    victim = cpath;
   1326    cpath = victim->next;
   1327    cpath_free(victim);
   1328  }
   1329 
   1330  cpath_free(cpath);
   1331 
   1332  circ->cpath = NULL;
   1333 }
   1334 
   1335 /** Release all storage held by circuits. */
   1336 void
   1337 circuit_free_all(void)
   1338 {
   1339  smartlist_t *lst = circuit_get_global_list();
   1340 
   1341  SMARTLIST_FOREACH_BEGIN(lst, circuit_t *, tmp) {
   1342    if (! CIRCUIT_IS_ORIGIN(tmp)) {
   1343      or_circuit_t *or_circ = TO_OR_CIRCUIT(tmp);
   1344      while (or_circ->resolving_streams) {
   1345        edge_connection_t *next_conn;
   1346        next_conn = or_circ->resolving_streams->next_stream;
   1347        connection_free_(TO_CONN(or_circ->resolving_streams));
   1348        or_circ->resolving_streams = next_conn;
   1349      }
   1350    }
   1351    tmp->global_circuitlist_idx = -1;
   1352    circuit_about_to_free_atexit(tmp);
   1353    circuit_free(tmp);
   1354    SMARTLIST_DEL_CURRENT(lst, tmp);
   1355  } SMARTLIST_FOREACH_END(tmp);
   1356 
   1357  smartlist_free(lst);
   1358  global_circuitlist = NULL;
   1359 
   1360  smartlist_free(global_origin_circuit_list);
   1361  global_origin_circuit_list = NULL;
   1362 
   1363  smartlist_free(circuits_pending_chans);
   1364  circuits_pending_chans = NULL;
   1365 
   1366  smartlist_free(circuits_pending_close);
   1367  circuits_pending_close = NULL;
   1368 
   1369  smartlist_free(circuits_pending_other_guards);
   1370  circuits_pending_other_guards = NULL;
   1371 
   1372  {
   1373    chan_circid_circuit_map_t **elt, **next, *c;
   1374    for (elt = HT_START(chan_circid_map, &chan_circid_map);
   1375         elt;
   1376         elt = next) {
   1377      c = *elt;
   1378      next = HT_NEXT_RMV(chan_circid_map, &chan_circid_map, elt);
   1379 
   1380      tor_assert(c->circuit == NULL);
   1381      tor_free(c);
   1382    }
   1383  }
   1384  HT_CLEAR(chan_circid_map, &chan_circid_map);
   1385 }
   1386 
   1387 /** A helper function for circuit_dump_by_conn() below. Log a bunch
   1388 * of information about circuit <b>circ</b>.
   1389 */
   1390 static void
   1391 circuit_dump_conn_details(int severity,
   1392                          circuit_t *circ,
   1393                          int conn_array_index,
   1394                          const char *type,
   1395                          circid_t this_circid,
   1396                          circid_t other_circid)
   1397 {
   1398  tor_log(severity, LD_CIRC, "Conn %d has %s circuit: circID %u "
   1399      "(other side %u), state %d (%s), born %ld:",
   1400      conn_array_index, type, (unsigned)this_circid, (unsigned)other_circid,
   1401      circ->state, circuit_state_to_string(circ->state),
   1402      (long)circ->timestamp_began.tv_sec);
   1403  if (CIRCUIT_IS_ORIGIN(circ)) { /* circ starts at this node */
   1404    circuit_log_path(severity, LD_CIRC, TO_ORIGIN_CIRCUIT(circ));
   1405  }
   1406 }
   1407 
   1408 /** Log, at severity <b>severity</b>, information about each circuit
   1409 * that is connected to <b>conn</b>.
   1410 */
   1411 void
   1412 circuit_dump_by_conn(connection_t *conn, int severity)
   1413 {
   1414  edge_connection_t *tmpconn;
   1415 
   1416  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1417    circid_t n_circ_id = circ->n_circ_id, p_circ_id = 0;
   1418 
   1419    if (circ->marked_for_close) {
   1420      continue;
   1421    }
   1422 
   1423    if (!CIRCUIT_IS_ORIGIN(circ)) {
   1424      p_circ_id = TO_OR_CIRCUIT(circ)->p_circ_id;
   1425    }
   1426 
   1427    if (CIRCUIT_IS_ORIGIN(circ)) {
   1428      for (tmpconn=TO_ORIGIN_CIRCUIT(circ)->p_streams; tmpconn;
   1429           tmpconn=tmpconn->next_stream) {
   1430        if (TO_CONN(tmpconn) == conn) {
   1431          circuit_dump_conn_details(severity, circ, conn->conn_array_index,
   1432                                    "App-ward", p_circ_id, n_circ_id);
   1433        }
   1434      }
   1435    }
   1436 
   1437    if (! CIRCUIT_IS_ORIGIN(circ)) {
   1438      for (tmpconn=TO_OR_CIRCUIT(circ)->n_streams; tmpconn;
   1439           tmpconn=tmpconn->next_stream) {
   1440        if (TO_CONN(tmpconn) == conn) {
   1441          circuit_dump_conn_details(severity, circ, conn->conn_array_index,
   1442                                    "Exit-ward", n_circ_id, p_circ_id);
   1443        }
   1444      }
   1445    }
   1446  }
   1447  SMARTLIST_FOREACH_END(circ);
   1448 }
   1449 
   1450 /** Return the circuit whose global ID is <b>id</b>, or NULL if no
   1451 * such circuit exists. */
   1452 origin_circuit_t *
   1453 circuit_get_by_global_id(uint32_t id)
   1454 {
   1455  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1456    if (CIRCUIT_IS_ORIGIN(circ) &&
   1457        TO_ORIGIN_CIRCUIT(circ)->global_identifier == id) {
   1458      if (circ->marked_for_close)
   1459        return NULL;
   1460      else
   1461        return TO_ORIGIN_CIRCUIT(circ);
   1462    }
   1463  }
   1464  SMARTLIST_FOREACH_END(circ);
   1465  return NULL;
   1466 }
   1467 
   1468 /** Return a circ such that:
   1469 *  - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
   1470 *  - circ is attached to <b>chan</b>, either as p_chan or n_chan.
   1471 * Return NULL if no such circuit exists.
   1472 *
   1473 * If <b>found_entry_out</b> is provided, set it to true if we have a
   1474 * placeholder entry for circid/chan, and leave it unset otherwise.
   1475 */
   1476 static inline circuit_t *
   1477 circuit_get_by_circid_channel_impl(circid_t circ_id, channel_t *chan,
   1478                                   int *found_entry_out)
   1479 {
   1480  chan_circid_circuit_map_t search;
   1481  chan_circid_circuit_map_t *found;
   1482 
   1483  if (_last_circid_chan_ent &&
   1484      circ_id == _last_circid_chan_ent->circ_id &&
   1485      chan == _last_circid_chan_ent->chan) {
   1486    found = _last_circid_chan_ent;
   1487  } else {
   1488    search.circ_id = circ_id;
   1489    search.chan = chan;
   1490    found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
   1491    _last_circid_chan_ent = found;
   1492  }
   1493  if (found && found->circuit) {
   1494    log_debug(LD_CIRC,
   1495              "circuit_get_by_circid_channel_impl() returning circuit %p for"
   1496              " circ_id %u, channel ID %"PRIu64 " (%p)",
   1497              found->circuit, (unsigned)circ_id,
   1498              (chan->global_identifier), chan);
   1499    if (found_entry_out)
   1500      *found_entry_out = 1;
   1501    return found->circuit;
   1502  }
   1503 
   1504  log_debug(LD_CIRC,
   1505            "circuit_get_by_circid_channel_impl() found %s for"
   1506            " circ_id %u, channel ID %"PRIu64 " (%p)",
   1507            found ? "placeholder" : "nothing",
   1508            (unsigned)circ_id,
   1509            (chan->global_identifier), chan);
   1510 
   1511  if (found_entry_out)
   1512    *found_entry_out = found ? 1 : 0;
   1513 
   1514  return NULL;
   1515  /* The rest of this checks for bugs. Disabled by default. */
   1516  /* We comment it out because coverity complains otherwise.
   1517  {
   1518    circuit_t *circ;
   1519    TOR_LIST_FOREACH(circ, &global_circuitlist, head) {
   1520      if (! CIRCUIT_IS_ORIGIN(circ)) {
   1521        or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
   1522        if (or_circ->p_chan == chan && or_circ->p_circ_id == circ_id) {
   1523          log_warn(LD_BUG,
   1524                   "circuit matches p_chan, but not in hash table (Bug!)");
   1525          return circ;
   1526        }
   1527      }
   1528      if (circ->n_chan == chan && circ->n_circ_id == circ_id) {
   1529        log_warn(LD_BUG,
   1530                 "circuit matches n_chan, but not in hash table (Bug!)");
   1531        return circ;
   1532      }
   1533    }
   1534    return NULL;
   1535  } */
   1536 }
   1537 
   1538 /** Return a circ such that:
   1539 *  - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
   1540 *  - circ is attached to <b>chan</b>, either as p_chan or n_chan.
   1541 *  - circ is not marked for close.
   1542 * Return NULL if no such circuit exists.
   1543 */
   1544 circuit_t *
   1545 circuit_get_by_circid_channel(circid_t circ_id, channel_t *chan)
   1546 {
   1547  circuit_t *circ = circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
   1548  if (!circ || circ->marked_for_close)
   1549    return NULL;
   1550  else
   1551    return circ;
   1552 }
   1553 
   1554 /** Return a circ such that:
   1555 *  - circ-\>n_circ_id or circ-\>p_circ_id is equal to <b>circ_id</b>, and
   1556 *  - circ is attached to <b>chan</b>, either as p_chan or n_chan.
   1557 * Return NULL if no such circuit exists.
   1558 */
   1559 circuit_t *
   1560 circuit_get_by_circid_channel_even_if_marked(circid_t circ_id,
   1561                                             channel_t *chan)
   1562 {
   1563  return circuit_get_by_circid_channel_impl(circ_id, chan, NULL);
   1564 }
   1565 
   1566 /** Return true iff the circuit ID <b>circ_id</b> is currently used by a
   1567 * circuit, marked or not, on <b>chan</b>, or if the circ ID is reserved until
   1568 * a queued destroy cell can be sent.
   1569 *
   1570 * (Return 1 if the circuit is present, marked or not; Return 2
   1571 * if the circuit ID is pending a destroy.)
   1572 **/
   1573 int
   1574 circuit_id_in_use_on_channel(circid_t circ_id, channel_t *chan)
   1575 {
   1576  int found = 0;
   1577  if (circuit_get_by_circid_channel_impl(circ_id, chan, &found) != NULL)
   1578    return 1;
   1579  if (found)
   1580    return 2;
   1581  return 0;
   1582 }
   1583 
   1584 /** Helper for debugging 12184.  Returns the time since which 'circ_id' has
   1585 * been marked unusable on 'chan'. */
   1586 time_t
   1587 circuit_id_when_marked_unusable_on_channel(circid_t circ_id, channel_t *chan)
   1588 {
   1589  chan_circid_circuit_map_t search;
   1590  chan_circid_circuit_map_t *found;
   1591 
   1592  memset(&search, 0, sizeof(search));
   1593  search.circ_id = circ_id;
   1594  search.chan = chan;
   1595 
   1596  found = HT_FIND(chan_circid_map, &chan_circid_map, &search);
   1597 
   1598  if (! found || found->circuit)
   1599    return 0;
   1600 
   1601  return found->made_placeholder_at;
   1602 }
   1603 
   1604 /** Return the circuit that a given edge connection is using. */
   1605 circuit_t *
   1606 circuit_get_by_edge_conn(edge_connection_t *conn)
   1607 {
   1608  circuit_t *circ;
   1609 
   1610  circ = conn->on_circuit;
   1611  tor_assert(!circ ||
   1612             (CIRCUIT_IS_ORIGIN(circ) ? circ->magic == ORIGIN_CIRCUIT_MAGIC
   1613                                      : circ->magic == OR_CIRCUIT_MAGIC));
   1614 
   1615  return circ;
   1616 }
   1617 
   1618 /** For each circuit that has <b>chan</b> as n_chan or p_chan, unlink the
   1619 * circuit from the chan,circid map, and mark it for close if it hasn't
   1620 * been marked already.
   1621 */
   1622 void
   1623 circuit_unlink_all_from_channel(channel_t *chan, int reason)
   1624 {
   1625  smartlist_t *detached = smartlist_new();
   1626 
   1627 /* #define DEBUG_CIRCUIT_UNLINK_ALL */
   1628 
   1629  channel_unlink_all_circuits(chan, detached);
   1630 
   1631 #ifdef DEBUG_CIRCUIT_UNLINK_ALL
   1632  {
   1633    smartlist_t *detached_2 = smartlist_new();
   1634    int mismatch = 0, badlen = 0;
   1635 
   1636    SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1637      if (circ->n_chan == chan ||
   1638          (!CIRCUIT_IS_ORIGIN(circ) &&
   1639           TO_OR_CIRCUIT(circ)->p_chan == chan)) {
   1640        smartlist_add(detached_2, circ);
   1641      }
   1642    }
   1643    SMARTLIST_FOREACH_END(circ);
   1644 
   1645    if (smartlist_len(detached) != smartlist_len(detached_2)) {
   1646       log_warn(LD_BUG, "List of detached circuits had the wrong length! "
   1647                "(got %d, should have gotten %d)",
   1648                (int)smartlist_len(detached),
   1649                (int)smartlist_len(detached_2));
   1650       badlen = 1;
   1651    }
   1652    smartlist_sort_pointers(detached);
   1653    smartlist_sort_pointers(detached_2);
   1654 
   1655    SMARTLIST_FOREACH(detached, circuit_t *, c,
   1656        if (c != smartlist_get(detached_2, c_sl_idx))
   1657          mismatch = 1;
   1658    );
   1659 
   1660    if (mismatch)
   1661      log_warn(LD_BUG, "Mismatch in list of detached circuits.");
   1662 
   1663    if (badlen || mismatch) {
   1664      smartlist_free(detached);
   1665      detached = detached_2;
   1666    } else {
   1667      log_notice(LD_CIRC, "List of %d circuits was as expected.",
   1668                (int)smartlist_len(detached));
   1669      smartlist_free(detached_2);
   1670    }
   1671  }
   1672 #endif /* defined(DEBUG_CIRCUIT_UNLINK_ALL) */
   1673 
   1674  SMARTLIST_FOREACH_BEGIN(detached, circuit_t *, circ) {
   1675    int mark = 0;
   1676    if (circ->n_chan == chan) {
   1677 
   1678      circuit_set_n_circid_chan(circ, 0, NULL);
   1679      mark = 1;
   1680 
   1681      /* If we didn't request this closure, pass the remote
   1682       * bit to mark_for_close. */
   1683      if (chan->reason_for_closing != CHANNEL_CLOSE_REQUESTED)
   1684        reason |= END_CIRC_REASON_FLAG_REMOTE;
   1685    }
   1686    if (! CIRCUIT_IS_ORIGIN(circ)) {
   1687      or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
   1688      if (or_circ->p_chan == chan) {
   1689        circuit_set_p_circid_chan(or_circ, 0, NULL);
   1690        mark = 1;
   1691      }
   1692    }
   1693    if (!mark) {
   1694      log_warn(LD_BUG, "Circuit on detached list which I had no reason "
   1695          "to mark");
   1696      continue;
   1697    }
   1698    if (!circ->marked_for_close)
   1699      circuit_mark_for_close(circ, reason);
   1700  } SMARTLIST_FOREACH_END(circ);
   1701 
   1702  smartlist_free(detached);
   1703 }
   1704 
   1705 /** Return the first introduction circuit originating from the global circuit
   1706 * list after <b>start</b> or at the start of the list if <b>start</b> is
   1707 * NULL. Return NULL if no circuit is found.
   1708 *
   1709 * If <b>want_client_circ</b> is true, then we are looking for client-side
   1710 * introduction circuits: A client introduction point circuit has a purpose of
   1711 * either CIRCUIT_PURPOSE_C_INTRODUCING, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT
   1712 * or CIRCUIT_PURPOSE_C_INTRODUCE_ACKED. This does not return a circuit marked
   1713 * for close, but it returns circuits regardless of their circuit state.
   1714 *
   1715 * If <b>want_client_circ</b> is false, then we are looking for service-side
   1716 * introduction circuits: A service introduction point circuit has a purpose of
   1717 * either CIRCUIT_PURPOSE_S_ESTABLISH_INTRO or CIRCUIT_PURPOSE_S_INTRO. This
   1718 * does not return circuits marked for close, or in any state other than open.
   1719 */
   1720 origin_circuit_t *
   1721 circuit_get_next_intro_circ(const origin_circuit_t *start,
   1722                            bool want_client_circ)
   1723 {
   1724  int idx = 0;
   1725  smartlist_t *lst = circuit_get_global_list();
   1726 
   1727  if (start) {
   1728    idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
   1729  }
   1730 
   1731  for ( ; idx < smartlist_len(lst); ++idx) {
   1732    circuit_t *circ = smartlist_get(lst, idx);
   1733 
   1734    /* Ignore a marked for close circuit or if the state is not open. */
   1735    if (circ->marked_for_close) {
   1736      continue;
   1737    }
   1738 
   1739    /* Depending on whether we are looking for client or service circs, skip
   1740     * circuits with other purposes. */
   1741    if (want_client_circ) {
   1742      if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
   1743          circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
   1744          circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACKED) {
   1745        continue;
   1746      }
   1747    } else { /* we are looking for service-side circs */
   1748      if (circ->state != CIRCUIT_STATE_OPEN) {
   1749        continue;
   1750      }
   1751      if (circ->purpose != CIRCUIT_PURPOSE_S_ESTABLISH_INTRO &&
   1752          circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
   1753        continue;
   1754      }
   1755    }
   1756 
   1757    /* The purposes we are looking for are only for origin circuits so the
   1758     * following is valid. */
   1759    return TO_ORIGIN_CIRCUIT(circ);
   1760  }
   1761  /* Not found. */
   1762  return NULL;
   1763 }
   1764 
   1765 /** Return the first service rendezvous circuit originating from the global
   1766 * circuit list after <b>start</b> or at the start of the list if <b>start</b>
   1767 * is NULL. Return NULL if no circuit is found.
   1768 *
   1769 * A service rendezvous point circuit has a purpose of either
   1770 * CIRCUIT_PURPOSE_S_CONNECT_REND or CIRCUIT_PURPOSE_S_REND_JOINED. This does
   1771 * not return a circuit marked for close and its state must be open. */
   1772 origin_circuit_t *
   1773 circuit_get_next_service_rp_circ(origin_circuit_t *start)
   1774 {
   1775  int idx = 0;
   1776  smartlist_t *lst = circuit_get_global_list();
   1777 
   1778  if (start) {
   1779    idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
   1780  }
   1781 
   1782  for ( ; idx < smartlist_len(lst); ++idx) {
   1783    circuit_t *circ = smartlist_get(lst, idx);
   1784 
   1785    /* Ignore a marked for close circuit or purpose not matching a service
   1786     * intro point or if the state is not open. */
   1787    if (circ->marked_for_close || circ->state != CIRCUIT_STATE_OPEN ||
   1788        (circ->purpose != CIRCUIT_PURPOSE_S_CONNECT_REND &&
   1789         circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED)) {
   1790      continue;
   1791    }
   1792    /* The purposes we are looking for are only for origin circuits so the
   1793     * following is valid. */
   1794    return TO_ORIGIN_CIRCUIT(circ);
   1795  }
   1796  /* Not found. */
   1797  return NULL;
   1798 }
   1799 
   1800 /** Return the first circuit originating here in global_circuitlist after
   1801 * <b>start</b> whose purpose is <b>purpose</b>. Return NULL if no circuit is
   1802 * found. If <b>start</b> is NULL, begin at the start of the list. */
   1803 origin_circuit_t *
   1804 circuit_get_next_by_purpose(origin_circuit_t *start, uint8_t purpose)
   1805 {
   1806  int idx;
   1807  smartlist_t *lst = circuit_get_global_list();
   1808  tor_assert(CIRCUIT_PURPOSE_IS_ORIGIN(purpose));
   1809  if (start == NULL)
   1810    idx = 0;
   1811  else
   1812    idx = TO_CIRCUIT(start)->global_circuitlist_idx + 1;
   1813 
   1814  for ( ; idx < smartlist_len(lst); ++idx) {
   1815    circuit_t *circ = smartlist_get(lst, idx);
   1816 
   1817    if (circ->marked_for_close)
   1818      continue;
   1819    if (circ->purpose != purpose)
   1820      continue;
   1821    /* At this point we should be able to get a valid origin circuit because
   1822     * the origin purpose we are looking for matches this circuit. */
   1823    if (BUG(!CIRCUIT_PURPOSE_IS_ORIGIN(circ->purpose))) {
   1824      break;
   1825    }
   1826    return TO_ORIGIN_CIRCUIT(circ);
   1827  }
   1828  return NULL;
   1829 }
   1830 
   1831 /** We are trying to create a circuit of purpose <b>purpose</b> and we are
   1832 *  looking for cannibalizable circuits. Return the circuit purpose we would be
   1833 *  willing to cannibalize. */
   1834 static uint8_t
   1835 get_circuit_purpose_needed_to_cannibalize(uint8_t purpose)
   1836 {
   1837  if (circuit_should_use_vanguards(purpose)) {
   1838    /* If we are using vanguards, then we should only cannibalize vanguard
   1839     * circuits so that we get the same path construction logic. */
   1840    return CIRCUIT_PURPOSE_HS_VANGUARDS;
   1841  } else {
   1842    /* Conflux purposes should never get here */
   1843    tor_assert_nonfatal(purpose != CIRCUIT_PURPOSE_CONFLUX_UNLINKED &&
   1844                        purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED);
   1845    /* If no vanguards are used just get a general circuit! */
   1846    return CIRCUIT_PURPOSE_C_GENERAL;
   1847  }
   1848 }
   1849 
   1850 /** Return a circuit that is open, is CIRCUIT_PURPOSE_C_GENERAL,
   1851 * has a timestamp_dirty value of 0, has flags matching the CIRCLAUNCH_*
   1852 * flags in <b>flags</b>, and if info is defined, does not already use info
   1853 * as any of its hops; or NULL if no circuit fits this description.
   1854 *
   1855 * The <b>purpose</b> argument refers to the purpose of the circuit we want to
   1856 * create, not the purpose of the circuit we want to cannibalize.
   1857 *
   1858 * If !CIRCLAUNCH_NEED_UPTIME, prefer returning non-uptime circuits.
   1859 *
   1860 * To "cannibalize" a circuit means to extend it an extra hop, and use it
   1861 * for some other purpose than we had originally intended.  We do this when
   1862 * we want to perform some low-bandwidth task at a specific relay, and we
   1863 * would like the circuit to complete as soon as possible.  (If we were going
   1864 * to use a lot of bandwidth, we wouldn't want a circuit with an extra hop.
   1865 * If we didn't care about circuit completion latency, we would just build
   1866 * a new circuit.)
   1867 */
   1868 origin_circuit_t *
   1869 circuit_find_to_cannibalize(uint8_t purpose_to_produce, extend_info_t *info,
   1870                            int flags)
   1871 {
   1872  origin_circuit_t *best=NULL;
   1873  int need_uptime = (flags & CIRCLAUNCH_NEED_UPTIME) != 0;
   1874  int need_capacity = (flags & CIRCLAUNCH_NEED_CAPACITY) != 0;
   1875  int internal = (flags & CIRCLAUNCH_IS_INTERNAL) != 0;
   1876  const or_options_t *options = get_options();
   1877  /* We want the circuit we are trying to cannibalize to have this purpose */
   1878  int purpose_to_search_for;
   1879 
   1880  /* Make sure we're not trying to create a onehop circ by
   1881   * cannibalization. */
   1882  tor_assert(!(flags & CIRCLAUNCH_ONEHOP_TUNNEL));
   1883 
   1884  purpose_to_search_for = get_circuit_purpose_needed_to_cannibalize(
   1885                                                  purpose_to_produce);
   1886 
   1887  tor_assert_nonfatal(purpose_to_search_for == CIRCUIT_PURPOSE_C_GENERAL ||
   1888                      purpose_to_search_for == CIRCUIT_PURPOSE_HS_VANGUARDS);
   1889 
   1890  tor_assert_nonfatal(purpose_to_search_for !=
   1891                      CIRCUIT_PURPOSE_CONFLUX_UNLINKED);
   1892  tor_assert_nonfatal(purpose_to_produce != CIRCUIT_PURPOSE_CONFLUX_UNLINKED);
   1893 
   1894  log_debug(LD_CIRC,
   1895            "Hunting for a circ to cannibalize: purpose %d, uptime %d, "
   1896            "capacity %d, internal %d",
   1897            purpose_to_produce, need_uptime, need_capacity, internal);
   1898 
   1899  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
   1900    if (CIRCUIT_IS_ORIGIN(circ_) &&
   1901        circ_->state == CIRCUIT_STATE_OPEN &&
   1902        !circ_->marked_for_close &&
   1903        circ_->purpose == purpose_to_search_for &&
   1904        !circ_->timestamp_dirty) {
   1905      origin_circuit_t *circ = TO_ORIGIN_CIRCUIT(circ_);
   1906 
   1907      /* Only cannibalize from reasonable length circuits. If we
   1908       * want C_GENERAL, then only choose 3 hop circs. If we want
   1909       * HS_VANGUARDS, only choose 4 hop circs.
   1910       */
   1911      if (circ->build_state->desired_path_len !=
   1912          route_len_for_purpose(purpose_to_search_for, NULL)) {
   1913        goto next;
   1914      }
   1915 
   1916      /* Ignore any circuits for which we can't use the Guard. It is possible
   1917       * that the Guard was removed from the sampled set after the circuit
   1918       * was created, so avoid using it. */
   1919      if (!entry_guard_could_succeed(circ->guard_state)) {
   1920        goto next;
   1921      }
   1922 
   1923      if ((!need_uptime || circ->build_state->need_uptime) &&
   1924          (!need_capacity || circ->build_state->need_capacity) &&
   1925          (internal == circ->build_state->is_internal) &&
   1926          !circ->unusable_for_new_conns &&
   1927          circ->remaining_relay_early_cells &&
   1928          !circ->build_state->onehop_tunnel &&
   1929          !circ->isolation_values_set) {
   1930        if (info) {
   1931          /* need to make sure we don't duplicate hops */
   1932          crypt_path_t *hop = circ->cpath;
   1933          const node_t *ri1 = node_get_by_id(info->identity_digest);
   1934          do {
   1935            const node_t *ri2;
   1936            if (tor_memeq(hop->extend_info->identity_digest,
   1937                          info->identity_digest, DIGEST_LEN))
   1938              goto next;
   1939            if (ri1 &&
   1940                (ri2 = node_get_by_id(hop->extend_info->identity_digest))
   1941                && nodes_in_same_family(ri1, ri2))
   1942              goto next;
   1943            hop=hop->next;
   1944          } while (hop!=circ->cpath);
   1945        }
   1946        if (options->ExcludeNodes) {
   1947          /* Make sure no existing nodes in the circuit are excluded for
   1948           * general use.  (This may be possible if StrictNodes is 0, and we
   1949           * thought we needed to use an otherwise excluded node for, say, a
   1950           * directory operation.) */
   1951          crypt_path_t *hop = circ->cpath;
   1952          do {
   1953            if (routerset_contains_extendinfo(options->ExcludeNodes,
   1954                                              hop->extend_info))
   1955              goto next;
   1956            hop = hop->next;
   1957          } while (hop != circ->cpath);
   1958        }
   1959 
   1960        if (!best || (best->build_state->need_uptime && !need_uptime))
   1961          best = circ;
   1962      next: ;
   1963      }
   1964    }
   1965  }
   1966  SMARTLIST_FOREACH_END(circ_);
   1967  return best;
   1968 }
   1969 
   1970 /**
   1971 * Check whether any of the origin circuits that are waiting to see if
   1972 * their guard is good enough to use can be upgraded to "ready". If so,
   1973 * return a new smartlist containing them. Otherwise return NULL.
   1974 */
   1975 smartlist_t *
   1976 circuit_find_circuits_to_upgrade_from_guard_wait(void)
   1977 {
   1978  /* Only if some circuit is actually waiting on an upgrade should we
   1979   * run the algorithm. */
   1980  if (! circuits_pending_other_guards ||
   1981      smartlist_len(circuits_pending_other_guards)==0)
   1982    return NULL;
   1983  /* Only if we have some origin circuits should we run the algorithm. */
   1984  if (!global_origin_circuit_list)
   1985    return NULL;
   1986 
   1987  /* Okay; we can pass our circuit list to entrynodes.c.*/
   1988  smartlist_t *result = smartlist_new();
   1989  int circuits_upgraded  = entry_guards_upgrade_waiting_circuits(
   1990                                                 get_guard_selection_info(),
   1991                                                 global_origin_circuit_list,
   1992                                                 result);
   1993  if (circuits_upgraded && smartlist_len(result)) {
   1994    return result;
   1995  } else {
   1996    smartlist_free(result);
   1997    return NULL;
   1998  }
   1999 }
   2000 
   2001 /** Return the number of hops in circuit's path. If circ has no entries,
   2002 * or is NULL, returns 0. */
   2003 int
   2004 circuit_get_cpath_len(origin_circuit_t *circ)
   2005 {
   2006  int n = 0;
   2007  if (circ && circ->cpath) {
   2008    crypt_path_t *cpath, *cpath_next = NULL;
   2009    for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
   2010      cpath_next = cpath->next;
   2011      ++n;
   2012    }
   2013  }
   2014  return n;
   2015 }
   2016 
   2017 /** Return the number of opened hops in circuit's path.
   2018 * If circ has no entries, or is NULL, returns 0. */
   2019 int
   2020 circuit_get_cpath_opened_len(const origin_circuit_t *circ)
   2021 {
   2022  int n = 0;
   2023  if (circ && circ->cpath) {
   2024    crypt_path_t *cpath, *cpath_next = NULL;
   2025    for (cpath = circ->cpath;
   2026         cpath->state == CPATH_STATE_OPEN
   2027           && cpath_next != circ->cpath;
   2028         cpath = cpath_next) {
   2029      cpath_next = cpath->next;
   2030      ++n;
   2031    }
   2032  }
   2033  return n;
   2034 }
   2035 
   2036 /** Return the <b>hopnum</b>th hop in <b>circ</b>->cpath, or NULL if there
   2037 * aren't that many hops in the list. <b>hopnum</b> starts at 1.
   2038 * Returns NULL if <b>hopnum</b> is 0 or negative. */
   2039 crypt_path_t *
   2040 circuit_get_cpath_hop(origin_circuit_t *circ, int hopnum)
   2041 {
   2042  if (circ && circ->cpath && hopnum > 0) {
   2043    crypt_path_t *cpath, *cpath_next = NULL;
   2044    for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
   2045      cpath_next = cpath->next;
   2046      if (--hopnum <= 0)
   2047        return cpath;
   2048    }
   2049  }
   2050  return NULL;
   2051 }
   2052 
   2053 /** Go through the circuitlist; mark-for-close each circuit that starts
   2054 *  at us but has not yet been used. */
   2055 void
   2056 circuit_mark_all_unused_circs(void)
   2057 {
   2058  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   2059    if (CIRCUIT_IS_ORIGIN(circ) &&
   2060        !circ->marked_for_close &&
   2061        !circ->timestamp_dirty)
   2062      circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
   2063  }
   2064  SMARTLIST_FOREACH_END(circ);
   2065 }
   2066 
   2067 /** Go through the circuitlist; for each circuit that starts at us
   2068 * and is dirty, frob its timestamp_dirty so we won't use it for any
   2069 * new streams.
   2070 *
   2071 * This is useful for letting the user change pseudonyms, so new
   2072 * streams will not be linkable to old streams.
   2073 */
   2074 void
   2075 circuit_mark_all_dirty_circs_as_unusable(void)
   2076 {
   2077  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   2078    if (CIRCUIT_IS_ORIGIN(circ) &&
   2079        !circ->marked_for_close &&
   2080        circ->timestamp_dirty) {
   2081      mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
   2082    }
   2083  }
   2084  SMARTLIST_FOREACH_END(circ);
   2085 }
   2086 
   2087 /**
   2088 * Report any queued cells on or_circuits as written in our bandwidth
   2089 * totals, for the specified channel direction.
   2090 *
   2091 * When we close a circuit or clear its cell queues, we've read
   2092 * data and recorded those bytes in our read statistics, but we're
   2093 * not going to write it. This discrepancy can be used by an adversary
   2094 * to infer information from our public relay statistics and perform
   2095 * attacks such as guard discovery.
   2096 *
   2097 * This function is in the critical path of circuit_mark_for_close().
   2098 * It must be (and is) O(1)!
   2099 *
   2100 * See https://bugs.torproject.org/tpo/core/tor/23512
   2101 */
   2102 void
   2103 circuit_synchronize_written_or_bandwidth(const circuit_t *c,
   2104                                         circuit_channel_direction_t dir)
   2105 {
   2106  uint64_t cells;
   2107  uint64_t cell_size;
   2108  uint64_t written_sync;
   2109  const channel_t *chan = NULL;
   2110  const or_circuit_t *or_circ;
   2111 
   2112  if (!CIRCUIT_IS_ORCIRC(c))
   2113    return;
   2114 
   2115  or_circ = CONST_TO_OR_CIRCUIT(c);
   2116 
   2117  if (dir == CIRCUIT_N_CHAN) {
   2118    chan = c->n_chan;
   2119    cells = c->n_chan_cells.n;
   2120  } else {
   2121    chan = or_circ->p_chan;
   2122    cells = or_circ->p_chan_cells.n;
   2123  }
   2124 
   2125  /* If we still know the chan, determine real cell size. Otherwise,
   2126   * assume it's a wide circid channel */
   2127  if (chan)
   2128    cell_size = get_cell_network_size(chan->wide_circ_ids);
   2129  else
   2130    cell_size = CELL_MAX_NETWORK_SIZE;
   2131 
   2132  /* If we know the channel, find out if it's IPv6. */
   2133  tor_addr_t remote_addr;
   2134  bool is_ipv6 = chan &&
   2135    channel_get_addr_if_possible(chan, &remote_addr) &&
   2136    tor_addr_family(&remote_addr) == AF_INET6;
   2137 
   2138  /* The missing written bytes are the cell counts times their cell
   2139   * size plus TLS per cell overhead */
   2140  written_sync = cells*(cell_size+TLS_PER_CELL_OVERHEAD);
   2141 
   2142  /* Report the missing bytes as written, to avoid asymmetry.
   2143   * We must use time() for consistency with rephist, even though on
   2144   * some very old rare platforms, approx_time() may be faster. */
   2145  bwhist_note_bytes_written(written_sync, time(NULL), is_ipv6);
   2146 }
   2147 
   2148 /** Mark <b>circ</b> to be closed next time we call
   2149 * circuit_close_all_marked(). Do any cleanup needed:
   2150 *   - If state is onionskin_pending, remove circ from the onion_pending
   2151 *     list.
   2152 *   - If circ isn't open yet: call circuit_build_failed() if we're
   2153 *     the origin.
   2154 *   - If purpose is C_INTRODUCE_ACK_WAIT, report the intro point
   2155 *     failure we just had to the hidden service client module.
   2156 *   - If purpose is C_INTRODUCING and <b>reason</b> isn't TIMEOUT,
   2157 *     report to the hidden service client module that the intro point
   2158 *     we just tried may be unreachable.
   2159 *   - Send appropriate destroys and edge_destroys for conns and
   2160 *     streams attached to circ.
   2161 *   - If circ->rend_splice is set (we are the midpoint of a joined
   2162 *     rendezvous stream), then mark the other circuit to close as well.
   2163 */
   2164 MOCK_IMPL(void,
   2165 circuit_mark_for_close_, (circuit_t *circ, int reason, int line,
   2166                          const char *file))
   2167 {
   2168  int orig_reason = reason; /* Passed to the controller */
   2169  assert_circuit_ok(circ);
   2170  tor_assert(line);
   2171  tor_assert(file);
   2172 
   2173  if (reason == END_CIRC_REASON_TORPROTOCOL) {
   2174    circ_n_proto_violation++;
   2175  }
   2176 
   2177  /* Check whether the circuitpadding subsystem wants to block this close */
   2178  if (circpad_marked_circuit_for_padding(circ, reason)) {
   2179    return;
   2180  }
   2181 
   2182  if (circ->marked_for_close) {
   2183    log_warn(LD_BUG,
   2184        "Duplicate call to circuit_mark_for_close at %s:%d"
   2185        " (first at %s:%d)", file, line,
   2186        circ->marked_for_close_file, circ->marked_for_close);
   2187    return;
   2188  }
   2189  if (reason == END_CIRC_AT_ORIGIN) {
   2190    if (!CIRCUIT_IS_ORIGIN(circ)) {
   2191      log_warn(LD_BUG, "Specified 'at-origin' non-reason for ending circuit, "
   2192               "but circuit was not at origin. (called %s:%d, purpose=%d)",
   2193               file, line, circ->purpose);
   2194    }
   2195    reason = END_CIRC_REASON_NONE;
   2196  }
   2197 
   2198  if (CIRCUIT_IS_ORIGIN(circ)) {
   2199    if (pathbias_check_close(TO_ORIGIN_CIRCUIT(circ), reason) == -1) {
   2200      /* Don't close it yet, we need to test it first */
   2201      return;
   2202    }
   2203 
   2204    /* We don't send reasons when closing circuits at the origin. */
   2205    reason = END_CIRC_REASON_NONE;
   2206  }
   2207 
   2208  circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_N_CHAN);
   2209  circuit_synchronize_written_or_bandwidth(circ, CIRCUIT_P_CHAN);
   2210 
   2211  if (reason & END_CIRC_REASON_FLAG_REMOTE)
   2212    reason &= ~END_CIRC_REASON_FLAG_REMOTE;
   2213 
   2214  if (reason < END_CIRC_REASON_MIN_ || reason > END_CIRC_REASON_MAX_) {
   2215    if (!(orig_reason & END_CIRC_REASON_FLAG_REMOTE))
   2216      log_warn(LD_BUG, "Reason %d out of range at %s:%d", reason, file, line);
   2217    reason = END_CIRC_REASON_NONE;
   2218  }
   2219 
   2220  circ->marked_for_close = line;
   2221  circ->marked_for_close_file = file;
   2222  circ->marked_for_close_reason = reason;
   2223  circ->marked_for_close_orig_reason = orig_reason;
   2224 
   2225  if (!CIRCUIT_IS_ORIGIN(circ)) {
   2226    or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
   2227    if (or_circ->rend_splice) {
   2228      if (!or_circ->rend_splice->base_.marked_for_close) {
   2229        /* do this after marking this circuit, to avoid infinite recursion. */
   2230        circuit_mark_for_close(TO_CIRCUIT(or_circ->rend_splice), reason);
   2231      }
   2232      or_circ->rend_splice = NULL;
   2233    }
   2234  }
   2235 
   2236  /* Notify the HS subsystem that this circuit is closing. */
   2237  hs_circ_cleanup_on_close(circ);
   2238 
   2239  /* Specific actions if this is a conflux related circuit. */
   2240  if (CIRCUIT_IS_CONFLUX(circ)) {
   2241    conflux_circuit_has_closed(circ);
   2242  }
   2243 
   2244  /* Update stats. */
   2245  if (circ->ccontrol) {
   2246    if (circ->ccontrol->in_slow_start) {
   2247      /* If we are in slow start, only count the ss cwnd if we've sent
   2248       * enough data to get RTT measurements such that we have a min
   2249       * and a max RTT, and they are not the same. This prevents us from
   2250       * averaging and reporting unused and low-use circuits here */
   2251      if (circ->ccontrol->max_rtt_usec != circ->ccontrol->min_rtt_usec) {
   2252        cc_stats_circ_close_ss_cwnd_ma =
   2253          stats_update_running_avg(cc_stats_circ_close_ss_cwnd_ma,
   2254                                   circ->ccontrol->cwnd);
   2255      }
   2256    } else {
   2257      cc_stats_circ_close_cwnd_ma =
   2258        stats_update_running_avg(cc_stats_circ_close_cwnd_ma,
   2259                                 circ->ccontrol->cwnd);
   2260    }
   2261    cc_stats_circs_closed++;
   2262  }
   2263 
   2264  if (circuits_pending_close == NULL)
   2265    circuits_pending_close = smartlist_new();
   2266 
   2267  smartlist_add(circuits_pending_close, circ);
   2268  mainloop_schedule_postloop_cleanup();
   2269 
   2270  log_info(LD_GENERAL, "Circuit %u (id: %" PRIu32 ") marked for close at "
   2271                       "%s:%d (orig reason: %d, new reason: %d)",
   2272           circ->n_circ_id,
   2273           CIRCUIT_IS_ORIGIN(circ) ?
   2274              TO_ORIGIN_CIRCUIT(circ)->global_identifier : 0,
   2275           file, line, orig_reason, reason);
   2276  tor_trace(TR_SUBSYS(circuit), TR_EV(mark_for_close), circ);
   2277 }
   2278 
   2279 /** Called immediately before freeing a marked circuit <b>circ</b> from
   2280 * circuit_free_all() while shutting down Tor; this is a safe-at-shutdown
   2281 * version of circuit_about_to_free().  It's important that it at least
   2282 * do circuitmux_detach_circuit() when appropriate.
   2283 */
   2284 static void
   2285 circuit_about_to_free_atexit(circuit_t *circ)
   2286 {
   2287  /* Cleanup conflux specifics. */
   2288  conflux_circuit_about_to_free(circ);
   2289 
   2290  if (circ->n_chan) {
   2291    circuit_clear_cell_queue(circ, circ->n_chan);
   2292    circuitmux_detach_circuit(circ->n_chan->cmux, circ);
   2293    circuit_set_n_circid_chan(circ, 0, NULL);
   2294  }
   2295 
   2296  if (! CIRCUIT_IS_ORIGIN(circ)) {
   2297    or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
   2298 
   2299    if (or_circ->p_chan) {
   2300      circuit_clear_cell_queue(circ, or_circ->p_chan);
   2301      circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
   2302      circuit_set_p_circid_chan(or_circ, 0, NULL);
   2303    }
   2304  }
   2305 }
   2306 
   2307 /** Called immediately before freeing a marked circuit <b>circ</b>.
   2308 * Disconnects the circuit from other data structures, launches events
   2309 * as appropriate, and performs other housekeeping.
   2310 */
   2311 static void
   2312 circuit_about_to_free(circuit_t *circ)
   2313 {
   2314 
   2315  int reason = circ->marked_for_close_reason;
   2316  int orig_reason = circ->marked_for_close_orig_reason;
   2317 
   2318  /* Cleanup conflux specifics. */
   2319  conflux_circuit_about_to_free(circ);
   2320 
   2321  if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
   2322    onion_pending_remove(TO_OR_CIRCUIT(circ));
   2323  }
   2324  /* If the circuit ever became OPEN, we sent it to the reputation history
   2325   * module then.  If it isn't OPEN, we send it there now to remember which
   2326   * links worked and which didn't.
   2327   */
   2328  if (circ->state != CIRCUIT_STATE_OPEN &&
   2329      circ->state != CIRCUIT_STATE_GUARD_WAIT) {
   2330    if (CIRCUIT_IS_ORIGIN(circ)) {
   2331      origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
   2332      circuit_build_failed(ocirc); /* take actions if necessary */
   2333    }
   2334  }
   2335  if (circ->state == CIRCUIT_STATE_CHAN_WAIT) {
   2336    if (circuits_pending_chans)
   2337      smartlist_remove(circuits_pending_chans, circ);
   2338  }
   2339  if (circuits_pending_other_guards) {
   2340    smartlist_remove(circuits_pending_other_guards, circ);
   2341  }
   2342  if (CIRCUIT_IS_ORIGIN(circ)) {
   2343    circuit_event_status(TO_ORIGIN_CIRCUIT(circ),
   2344     (circ->state == CIRCUIT_STATE_OPEN ||
   2345      circ->state == CIRCUIT_STATE_GUARD_WAIT) ?
   2346                                 CIRC_EVENT_CLOSED:CIRC_EVENT_FAILED,
   2347     orig_reason);
   2348  }
   2349 
   2350  if (circ->n_chan) {
   2351    circuit_clear_cell_queue(circ, circ->n_chan);
   2352    /* Only send destroy if the channel isn't closing anyway */
   2353    if (!CHANNEL_CONDEMNED(circ->n_chan)) {
   2354      channel_send_destroy(circ->n_circ_id, circ->n_chan, reason);
   2355    }
   2356    circuitmux_detach_circuit(circ->n_chan->cmux, circ);
   2357    circuit_set_n_circid_chan(circ, 0, NULL);
   2358  }
   2359 
   2360  if (! CIRCUIT_IS_ORIGIN(circ)) {
   2361    or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
   2362    edge_connection_t *conn;
   2363 
   2364    for (conn=or_circ->n_streams; conn; conn=conn->next_stream)
   2365      connection_edge_destroy(or_circ->p_circ_id, conn);
   2366    or_circ->n_streams = NULL;
   2367 
   2368    while (or_circ->resolving_streams) {
   2369      conn = or_circ->resolving_streams;
   2370      or_circ->resolving_streams = conn->next_stream;
   2371      if (!conn->base_.marked_for_close) {
   2372        /* The client will see a DESTROY, and infer that the connections
   2373         * are closing because the circuit is getting torn down.  No need
   2374         * to send an end cell. */
   2375        conn->edge_has_sent_end = 1;
   2376        conn->end_reason = END_STREAM_REASON_DESTROY;
   2377        conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
   2378        connection_mark_for_close(TO_CONN(conn));
   2379      }
   2380      conn->on_circuit = NULL;
   2381    }
   2382 
   2383    if (or_circ->p_chan) {
   2384      circuit_clear_cell_queue(circ, or_circ->p_chan);
   2385      /* Only send destroy if the channel isn't closing anyway */
   2386      if (!CHANNEL_CONDEMNED(or_circ->p_chan)) {
   2387        channel_send_destroy(or_circ->p_circ_id, or_circ->p_chan, reason);
   2388      }
   2389      circuitmux_detach_circuit(or_circ->p_chan->cmux, circ);
   2390      circuit_set_p_circid_chan(or_circ, 0, NULL);
   2391    }
   2392 
   2393    if (or_circ->n_cells_discarded_at_end) {
   2394      time_t age = approx_time() - circ->timestamp_created.tv_sec;
   2395      note_circ_closed_for_unrecognized_cells(
   2396                      age, or_circ->n_cells_discarded_at_end);
   2397    }
   2398  } else {
   2399    origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
   2400    edge_connection_t *conn;
   2401    for (conn=ocirc->p_streams; conn; conn=conn->next_stream)
   2402      connection_edge_destroy(circ->n_circ_id, conn);
   2403    ocirc->p_streams = NULL;
   2404  }
   2405 }
   2406 
   2407 /** Given a marked circuit <b>circ</b>, aggressively free its cell queues to
   2408 * recover memory. */
   2409 static void
   2410 marked_circuit_free_cells(circuit_t *circ)
   2411 {
   2412  if (!circ->marked_for_close) {
   2413    log_warn(LD_BUG, "Called on non-marked circuit");
   2414    return;
   2415  }
   2416  cell_queue_clear(&circ->n_chan_cells);
   2417  if (! CIRCUIT_IS_ORIGIN(circ)) {
   2418    or_circuit_t *orcirc = TO_OR_CIRCUIT(circ);
   2419    cell_queue_clear(&orcirc->p_chan_cells);
   2420  }
   2421 }
   2422 
   2423 static size_t
   2424 single_conn_free_bytes(connection_t *conn)
   2425 {
   2426  size_t result = 0;
   2427  if (conn->inbuf) {
   2428    result += buf_allocation(conn->inbuf);
   2429    buf_clear(conn->inbuf);
   2430  }
   2431  if (conn->outbuf) {
   2432    result += buf_allocation(conn->outbuf);
   2433    buf_clear(conn->outbuf);
   2434  }
   2435  if (conn->type == CONN_TYPE_DIR) {
   2436    dir_connection_t *dir_conn = TO_DIR_CONN(conn);
   2437    if (dir_conn->compress_state) {
   2438      result += tor_compress_state_size(dir_conn->compress_state);
   2439      tor_compress_free(dir_conn->compress_state);
   2440      dir_conn->compress_state = NULL;
   2441    }
   2442  }
   2443  return result;
   2444 }
   2445 
   2446 /** Aggressively free buffer contents on all the buffers of all streams in the
   2447 * list starting at <b>stream</b>. Return the number of bytes recovered. */
   2448 static size_t
   2449 marked_circuit_streams_free_bytes(edge_connection_t *stream)
   2450 {
   2451  size_t result = 0;
   2452  for ( ; stream; stream = stream->next_stream) {
   2453    connection_t *conn = TO_CONN(stream);
   2454    result += single_conn_free_bytes(conn);
   2455    if (conn->linked_conn) {
   2456      result += single_conn_free_bytes(conn->linked_conn);
   2457    }
   2458  }
   2459  return result;
   2460 }
   2461 
   2462 /** Aggressively free buffer contents on all the buffers of all streams on
   2463 * circuit <b>c</b>. Return the number of bytes recovered. */
   2464 static size_t
   2465 marked_circuit_free_stream_bytes(circuit_t *c)
   2466 {
   2467  if (CIRCUIT_IS_ORIGIN(c)) {
   2468    return marked_circuit_streams_free_bytes(TO_ORIGIN_CIRCUIT(c)->p_streams);
   2469  } else {
   2470    return marked_circuit_streams_free_bytes(TO_OR_CIRCUIT(c)->n_streams);
   2471  }
   2472 }
   2473 
   2474 /** Return the number of cells used by the circuit <b>c</b>'s cell queues. */
   2475 STATIC size_t
   2476 n_cells_in_circ_queues(const circuit_t *c)
   2477 {
   2478  size_t n = c->n_chan_cells.n;
   2479  if (! CIRCUIT_IS_ORIGIN(c)) {
   2480    circuit_t *cc = (circuit_t *) c;
   2481    n += TO_OR_CIRCUIT(cc)->p_chan_cells.n;
   2482  }
   2483  return n;
   2484 }
   2485 
   2486 /** Return the number of bytes allocated for <b>c</b>'s half-open streams. */
   2487 static size_t
   2488 circuit_alloc_in_half_streams(const circuit_t *c)
   2489 {
   2490  if (! CIRCUIT_IS_ORIGIN(c)) {
   2491    return 0;
   2492  }
   2493  const origin_circuit_t *ocirc = CONST_TO_ORIGIN_CIRCUIT(c);
   2494  if (ocirc->half_streams)
   2495    return smartlist_len(ocirc->half_streams) * sizeof(half_edge_t);
   2496  else
   2497    return 0;
   2498 }
   2499 
   2500 /**
   2501 * Return the age of the oldest cell queued on <b>c</b>, in timestamp units.
   2502 * Return 0 if there are no cells queued on c.  Requires that <b>now</b> be
   2503 * the current coarse timestamp.
   2504 *
   2505 * This function will return incorrect results if the oldest cell queued on
   2506 * the circuit is older than about 2**32 msec (about 49 days) old.
   2507 */
   2508 STATIC uint32_t
   2509 circuit_max_queued_cell_age(const circuit_t *c, uint32_t now)
   2510 {
   2511  uint32_t age = 0;
   2512  packed_cell_t *cell;
   2513 
   2514  if (NULL != (cell = TOR_SIMPLEQ_FIRST(&c->n_chan_cells.head)))
   2515    age = now - cell->inserted_timestamp;
   2516 
   2517  if (! CIRCUIT_IS_ORIGIN(c)) {
   2518    const or_circuit_t *orcirc = CONST_TO_OR_CIRCUIT(c);
   2519    if (NULL != (cell = TOR_SIMPLEQ_FIRST(&orcirc->p_chan_cells.head))) {
   2520      uint32_t age2 = now - cell->inserted_timestamp;
   2521      if (age2 > age)
   2522        return age2;
   2523    }
   2524  }
   2525  return age;
   2526 }
   2527 
   2528 /** Return the age of the oldest buffer chunk on <b>conn</b>, where age is
   2529 * taken in timestamp units before the time <b>now</b>.  If the connection has
   2530 * no data, treat it as having age zero.
   2531 **/
   2532 static uint32_t
   2533 conn_get_buffer_age(const connection_t *conn, uint32_t now_ts)
   2534 {
   2535  uint32_t age = 0, age2;
   2536  if (conn->outbuf) {
   2537    age2 = buf_get_oldest_chunk_timestamp(conn->outbuf, now_ts);
   2538    if (age2 > age)
   2539      age = age2;
   2540  }
   2541  if (conn->inbuf) {
   2542    age2 = buf_get_oldest_chunk_timestamp(conn->inbuf, now_ts);
   2543    if (age2 > age)
   2544      age = age2;
   2545  }
   2546  return age;
   2547 }
   2548 
   2549 /** Return the age in timestamp units of the oldest buffer chunk on any stream
   2550 * in the linked list <b>stream</b>, where age is taken in timestamp units
   2551 * before the timestamp <b>now</b>. */
   2552 static uint32_t
   2553 circuit_get_streams_max_data_age(const edge_connection_t *stream, uint32_t now)
   2554 {
   2555  uint32_t age = 0, age2;
   2556  for (; stream; stream = stream->next_stream) {
   2557    const connection_t *conn = TO_CONN(stream);
   2558    age2 = conn_get_buffer_age(conn, now);
   2559    if (age2 > age)
   2560      age = age2;
   2561    if (conn->linked_conn) {
   2562      age2 = conn_get_buffer_age(conn->linked_conn, now);
   2563      if (age2 > age)
   2564        age = age2;
   2565    }
   2566  }
   2567  return age;
   2568 }
   2569 
   2570 /** Return the age in timestamp units of the oldest buffer chunk on any stream
   2571 * attached to the circuit <b>c</b>, where age is taken before the timestamp
   2572 * <b>now</b>. */
   2573 STATIC uint32_t
   2574 circuit_max_queued_data_age(const circuit_t *c, uint32_t now)
   2575 {
   2576  if (CIRCUIT_IS_ORIGIN(c)) {
   2577    return circuit_get_streams_max_data_age(
   2578        CONST_TO_ORIGIN_CIRCUIT(c)->p_streams, now);
   2579  } else {
   2580    return circuit_get_streams_max_data_age(
   2581        CONST_TO_OR_CIRCUIT(c)->n_streams, now);
   2582  }
   2583 }
   2584 
   2585 /** Return the age of the oldest cell or stream buffer chunk on the circuit
   2586 * <b>c</b>, where age is taken in timestamp units before the timestamp
   2587 * <b>now</b> */
   2588 STATIC uint32_t
   2589 circuit_max_queued_item_age(const circuit_t *c, uint32_t now)
   2590 {
   2591  uint32_t cell_age = circuit_max_queued_cell_age(c, now);
   2592  uint32_t data_age = circuit_max_queued_data_age(c, now);
   2593  if (cell_age > data_age)
   2594    return cell_age;
   2595  else
   2596    return data_age;
   2597 }
   2598 
   2599 /** Helper to sort a list of circuit_t by age of oldest item, in descending
   2600 * order. */
   2601 static int
   2602 circuits_compare_by_oldest_queued_item_(const void **a_, const void **b_)
   2603 {
   2604  const circuit_t *a = *a_;
   2605  const circuit_t *b = *b_;
   2606  uint32_t age_a = a->age_tmp;
   2607  uint32_t age_b = b->age_tmp;
   2608 
   2609  if (age_a < age_b)
   2610    return 1;
   2611  else if (age_a == age_b)
   2612    return 0;
   2613  else
   2614    return -1;
   2615 }
   2616 
   2617 static uint32_t now_ts_for_buf_cmp;
   2618 
   2619 /** Helper to sort a list of circuit_t by age of oldest item, in descending
   2620 * order. */
   2621 static int
   2622 conns_compare_by_buffer_age_(const void **a_, const void **b_)
   2623 {
   2624  const connection_t *a = *a_;
   2625  const connection_t *b = *b_;
   2626  time_t age_a = conn_get_buffer_age(a, now_ts_for_buf_cmp);
   2627  time_t age_b = conn_get_buffer_age(b, now_ts_for_buf_cmp);
   2628 
   2629  if (age_a < age_b)
   2630    return 1;
   2631  else if (age_a == age_b)
   2632    return 0;
   2633  else
   2634    return -1;
   2635 }
   2636 
   2637 #define FRACTION_OF_DATA_TO_RETAIN_ON_OOM 0.90
   2638 
   2639 /** We're out of memory for cells, having allocated <b>current_allocation</b>
   2640 * bytes' worth.  Kill the 'worst' circuits until we're under
   2641 * FRACTION_OF_DATA_TO_RETAIN_ON_OOM of our maximum usage.
   2642 *
   2643 * Return the number of bytes removed. */
   2644 size_t
   2645 circuits_handle_oom(size_t current_allocation)
   2646 {
   2647  smartlist_t *circlist;
   2648  smartlist_t *connection_array = get_connection_array();
   2649  int conn_idx;
   2650  size_t mem_to_recover;
   2651  size_t mem_recovered=0;
   2652  int n_circuits_killed=0;
   2653  int n_dirconns_killed=0;
   2654  int n_edgeconns_killed = 0;
   2655  uint32_t now_ts;
   2656  log_notice(LD_GENERAL, "We're low on memory (cell queues total alloc:"
   2657             " %"TOR_PRIuSZ" buffer total alloc: %" TOR_PRIuSZ ","
   2658             " tor compress total alloc: %" TOR_PRIuSZ
   2659             " (zlib: %" TOR_PRIuSZ ", zstd: %" TOR_PRIuSZ ","
   2660             " lzma: %" TOR_PRIuSZ "),"
   2661             " rendezvous cache total alloc: %" TOR_PRIuSZ "). Killing"
   2662             " circuits withover-long queues. (This behavior is controlled by"
   2663             " MaxMemInQueues.)",
   2664             cell_queues_get_total_allocation(),
   2665             buf_get_total_allocation(),
   2666             tor_compress_get_total_allocation(),
   2667             tor_zlib_get_total_allocation(),
   2668             tor_zstd_get_total_allocation(),
   2669             tor_lzma_get_total_allocation(),
   2670             hs_cache_get_total_allocation());
   2671  {
   2672    size_t mem_target = (size_t)(get_options()->MaxMemInQueues *
   2673                                 FRACTION_OF_DATA_TO_RETAIN_ON_OOM);
   2674    if (current_allocation <= mem_target)
   2675      return 0;
   2676    mem_to_recover = current_allocation - mem_target;
   2677  }
   2678 
   2679  now_ts = monotime_coarse_get_stamp();
   2680 
   2681  circlist = circuit_get_global_list();
   2682  SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
   2683    circ->age_tmp = circuit_max_queued_item_age(circ, now_ts);
   2684  } SMARTLIST_FOREACH_END(circ);
   2685 
   2686  /* This is O(n log n); there are faster algorithms we could use instead.
   2687   * Let's hope this doesn't happen enough to be in the critical path. */
   2688  smartlist_sort(circlist, circuits_compare_by_oldest_queued_item_);
   2689 
   2690  /* Fix up the indices before we run into trouble */
   2691  SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
   2692    circ->global_circuitlist_idx = circ_sl_idx;
   2693  } SMARTLIST_FOREACH_END(circ);
   2694 
   2695  /* Now sort the connection array ... */
   2696  now_ts_for_buf_cmp = now_ts;
   2697  smartlist_sort(connection_array, conns_compare_by_buffer_age_);
   2698  now_ts_for_buf_cmp = 0;
   2699 
   2700  /* Fix up the connection array to its new order. */
   2701  SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
   2702    conn->conn_array_index = conn_sl_idx;
   2703  } SMARTLIST_FOREACH_END(conn);
   2704 
   2705  /* Okay, now the worst circuits and connections are at the front of their
   2706   * respective lists. Let's mark them, and reclaim their storage
   2707   * aggressively. */
   2708  conn_idx = 0;
   2709  SMARTLIST_FOREACH_BEGIN(circlist, circuit_t *, circ) {
   2710    size_t n;
   2711    size_t freed;
   2712 
   2713    /* Free storage in any non-linked directory connections that have buffered
   2714     * data older than this circuit. */
   2715    while (conn_idx < smartlist_len(connection_array)) {
   2716      connection_t *conn = smartlist_get(connection_array, conn_idx);
   2717      uint32_t conn_age = conn_get_buffer_age(conn, now_ts);
   2718      if (conn_age < circ->age_tmp) {
   2719        break;
   2720      }
   2721      /* Also consider edge connections so we don't accumulate bytes on the
   2722       * outbuf due to a malicious destination holding off the read on us. */
   2723      if ((conn->type == CONN_TYPE_DIR && conn->linked_conn == NULL) ||
   2724          CONN_IS_EDGE(conn)) {
   2725        if (!conn->marked_for_close) {
   2726          if (CONN_IS_EDGE(conn)) {
   2727            TO_EDGE_CONN(conn)->end_reason = END_STREAM_REASON_RESOURCELIMIT;
   2728          }
   2729          connection_mark_for_close(conn);
   2730        }
   2731        mem_recovered += single_conn_free_bytes(conn);
   2732 
   2733        if (conn->type == CONN_TYPE_DIR) {
   2734          ++n_dirconns_killed;
   2735        } else {
   2736          ++n_edgeconns_killed;
   2737        }
   2738 
   2739        if (mem_recovered >= mem_to_recover)
   2740          goto done_recovering_mem;
   2741      }
   2742      ++conn_idx;
   2743    }
   2744 
   2745    /* Now, kill the circuit. */
   2746    n = n_cells_in_circ_queues(circ);
   2747    const size_t half_stream_alloc = circuit_alloc_in_half_streams(circ);
   2748    if (! circ->marked_for_close) {
   2749      circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
   2750    }
   2751    marked_circuit_free_cells(circ);
   2752    freed = marked_circuit_free_stream_bytes(circ);
   2753 
   2754    ++n_circuits_killed;
   2755 
   2756    mem_recovered += n * packed_cell_mem_cost();
   2757    mem_recovered += half_stream_alloc;
   2758    mem_recovered += freed;
   2759    mem_recovered += conflux_get_circ_bytes_allocation(circ);
   2760 
   2761    if (mem_recovered >= mem_to_recover)
   2762      goto done_recovering_mem;
   2763  } SMARTLIST_FOREACH_END(circ);
   2764 
   2765 done_recovering_mem:
   2766  log_notice(LD_GENERAL, "Removed %"TOR_PRIuSZ" bytes by killing %d circuits; "
   2767             "%d circuits remain alive. Also killed %d non-linked directory "
   2768             "connections. Killed %d edge connections",
   2769             mem_recovered,
   2770             n_circuits_killed,
   2771             smartlist_len(circlist) - n_circuits_killed,
   2772             n_dirconns_killed,
   2773             n_edgeconns_killed);
   2774 
   2775  return mem_recovered;
   2776 }
   2777 
   2778 /** Verify that circuit <b>c</b> has all of its invariants
   2779 * correct. Trigger an assert if anything is invalid.
   2780 */
   2781 MOCK_IMPL(void,
   2782 assert_circuit_ok,(const circuit_t *c))
   2783 {
   2784  edge_connection_t *conn;
   2785  const or_circuit_t *or_circ = NULL;
   2786  const origin_circuit_t *origin_circ = NULL;
   2787 
   2788  tor_assert(c);
   2789  tor_assert(c->magic == ORIGIN_CIRCUIT_MAGIC || c->magic == OR_CIRCUIT_MAGIC);
   2790  tor_assert(c->purpose >= CIRCUIT_PURPOSE_MIN_ &&
   2791             c->purpose <= CIRCUIT_PURPOSE_MAX_);
   2792 
   2793  if (CIRCUIT_IS_ORIGIN(c))
   2794    origin_circ = CONST_TO_ORIGIN_CIRCUIT(c);
   2795  else
   2796    or_circ = CONST_TO_OR_CIRCUIT(c);
   2797 
   2798  if (c->n_chan) {
   2799    tor_assert(!c->n_hop);
   2800 
   2801    if (c->n_circ_id) {
   2802      /* We use the _impl variant here to make sure we don't fail on marked
   2803       * circuits, which would not be returned by the regular function. */
   2804      circuit_t *c2 = circuit_get_by_circid_channel_impl(c->n_circ_id,
   2805                                                         c->n_chan, NULL);
   2806      tor_assert(c == c2);
   2807    }
   2808  }
   2809  if (or_circ && or_circ->p_chan) {
   2810    if (or_circ->p_circ_id) {
   2811      /* ibid */
   2812      circuit_t *c2 =
   2813        circuit_get_by_circid_channel_impl(or_circ->p_circ_id,
   2814                                           or_circ->p_chan, NULL);
   2815      tor_assert(c == c2);
   2816    }
   2817  }
   2818  if (or_circ)
   2819    for (conn = or_circ->n_streams; conn; conn = conn->next_stream)
   2820      tor_assert(conn->base_.type == CONN_TYPE_EXIT);
   2821 
   2822  tor_assert(c->deliver_window >= 0);
   2823  tor_assert(c->package_window >= 0);
   2824  if (c->state == CIRCUIT_STATE_OPEN ||
   2825      c->state == CIRCUIT_STATE_GUARD_WAIT) {
   2826    tor_assert(!c->n_chan_create_cell);
   2827    if (or_circ) {
   2828      relay_crypto_assert_ok(&or_circ->crypto);
   2829    }
   2830  }
   2831  if (c->state == CIRCUIT_STATE_CHAN_WAIT && !c->marked_for_close) {
   2832    tor_assert(circuits_pending_chans &&
   2833               smartlist_contains(circuits_pending_chans, c));
   2834  } else {
   2835    tor_assert(!circuits_pending_chans ||
   2836               !smartlist_contains(circuits_pending_chans, c));
   2837  }
   2838  if (origin_circ && origin_circ->cpath) {
   2839    cpath_assert_ok(origin_circ->cpath);
   2840  }
   2841  if (c->purpose == CIRCUIT_PURPOSE_REND_ESTABLISHED) {
   2842    tor_assert(or_circ);
   2843    if (!c->marked_for_close) {
   2844      tor_assert(or_circ->rend_splice);
   2845      tor_assert(or_circ->rend_splice->rend_splice == or_circ);
   2846    }
   2847    tor_assert(or_circ->rend_splice != or_circ);
   2848  } else {
   2849    tor_assert(!or_circ || !or_circ->rend_splice);
   2850  }
   2851 }
   2852 
   2853 /** Return true iff the circuit queue for the given direction is full that is
   2854 * above the high watermark. */
   2855 bool
   2856 circuit_is_queue_full(const circuit_t *circ, cell_direction_t direction)
   2857 {
   2858  int queue_size;
   2859 
   2860  tor_assert(circ);
   2861 
   2862  /* Gather objects we need based on cell direction. */
   2863  if (direction == CELL_DIRECTION_OUT) {
   2864    /* Outbound. */
   2865    queue_size = circ->n_chan_cells.n;
   2866  } else {
   2867    /* Inbound. */
   2868    queue_size = CONST_TO_OR_CIRCUIT(circ)->p_chan_cells.n;
   2869  }
   2870 
   2871  /* Then check if our cell queue has reached its high watermark as in its
   2872   * upper limit. This is so we avoid too much memory pressure by queuing a
   2873   * large amount of cells. */
   2874  return queue_size >= cell_queue_highwatermark();
   2875 }