tor

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

circuituse.c (124417B)


      1 /* Copyright (c) 2001 Matej Pfajfar.
      2 * Copyright (c) 2001-2004, Roger Dingledine.
      3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      5 /* See LICENSE for licensing information */
      6 
      7 /**
      8 * \file circuituse.c
      9 * \brief Launch the right sort of circuits and attach the right streams to
     10 * them.
     11 *
     12 * As distinct from circuitlist.c, which manages lookups to find circuits, and
     13 * circuitbuild.c, which handles the logistics of circuit construction, this
     14 * module keeps track of which streams can be attached to which circuits (in
     15 * circuit_get_best()), and attaches streams to circuits (with
     16 * circuit_try_attaching_streams(), connection_ap_handshake_attach_circuit(),
     17 * and connection_ap_handshake_attach_chosen_circuit() ).
     18 *
     19 * This module also makes sure that we are building circuits for all of the
     20 * predicted ports, using circuit_remove_handled_ports(),
     21 * circuit_stream_is_being_handled(), and circuit_build_needed_cirs().  It
     22 * handles launching circuits for specific targets using
     23 * circuit_launch_by_extend_info().
     24 *
     25 * This is also where we handle expiring circuits that have been around for
     26 * too long without actually completing, along with the circuit_build_timeout
     27 * logic in circuitstats.c.
     28 **/
     29 
     30 #include "core/or/or.h"
     31 #include "app/config/config.h"
     32 #include "core/mainloop/connection.h"
     33 #include "core/or/channel.h"
     34 #include "core/or/circuitbuild.h"
     35 #include "core/or/circuitlist.h"
     36 #include "core/or/circuitstats.h"
     37 #include "core/or/circuituse.h"
     38 #include "core/or/circuitpadding.h"
     39 #include "core/or/conflux_pool.h"
     40 #include "core/or/connection_edge.h"
     41 #include "core/or/extendinfo.h"
     42 #include "core/or/policies.h"
     43 #include "core/or/trace_probes_circuit.h"
     44 #include "feature/client/addressmap.h"
     45 #include "feature/client/bridges.h"
     46 #include "feature/client/circpathbias.h"
     47 #include "feature/client/entrynodes.h"
     48 #include "feature/client/proxymode.h"
     49 #include "feature/control/control_events.h"
     50 #include "feature/dircommon/directory.h"
     51 #include "feature/hs/hs_circuit.h"
     52 #include "feature/hs/hs_client.h"
     53 #include "feature/hs/hs_common.h"
     54 #include "feature/hs/hs_ident.h"
     55 #include "feature/hs/hs_metrics.h"
     56 #include "feature/hs/hs_stats.h"
     57 #include "feature/nodelist/describe.h"
     58 #include "feature/nodelist/networkstatus.h"
     59 #include "feature/nodelist/nodelist.h"
     60 #include "feature/nodelist/routerlist.h"
     61 #include "feature/relay/routermode.h"
     62 #include "feature/relay/selftest.h"
     63 #include "feature/stats/predict_ports.h"
     64 #include "lib/math/fp.h"
     65 #include "lib/time/tvdiff.h"
     66 #include "lib/trace/events.h"
     67 #include "src/core/mainloop/mainloop.h"
     68 #include "core/or/conflux.h"
     69 
     70 #include "core/or/cpath_build_state_st.h"
     71 #include "feature/dircommon/dir_connection_st.h"
     72 #include "core/or/entry_connection_st.h"
     73 #include "core/or/extend_info_st.h"
     74 #include "core/or/or_circuit_st.h"
     75 #include "core/or/origin_circuit_st.h"
     76 #include "core/or/socks_request_st.h"
     77 
     78 #include "core/or/conflux_util.h"
     79 
     80 STATIC void circuit_expire_old_circuits_clientside(void);
     81 static void circuit_increment_failure_count(void);
     82 static bool connection_ap_socks_iso_keepalive_enabled(
     83    const entry_connection_t *);
     84 
     85 /** Check whether the hidden service destination of the stream at
     86 *  <b>edge_conn</b> is the same as the destination of the circuit at
     87 *  <b>origin_circ</b>. */
     88 static int
     89 circuit_matches_with_rend_stream(const edge_connection_t *edge_conn,
     90                                 const origin_circuit_t *origin_circ)
     91 {
     92  /* Check if this is a v3 rendezvous circ/stream */
     93  if ((edge_conn->hs_ident && !origin_circ->hs_ident) ||
     94      (!edge_conn->hs_ident && origin_circ->hs_ident) ||
     95      (edge_conn->hs_ident && origin_circ->hs_ident &&
     96       !ed25519_pubkey_eq(&edge_conn->hs_ident->identity_pk,
     97                          &origin_circ->hs_ident->identity_pk))) {
     98    /* this circ is not for this conn */
     99    return 0;
    100  }
    101 
    102  return 1;
    103 }
    104 
    105 /** Return 1 if <b>circ</b> could be returned by circuit_get_best().
    106 * Else return 0.
    107 */
    108 int
    109 circuit_is_acceptable(const origin_circuit_t *origin_circ,
    110                      const entry_connection_t *conn,
    111                      int must_be_open, uint8_t purpose,
    112                      int need_uptime, int need_internal,
    113                      time_t now)
    114 {
    115  const circuit_t *circ = TO_CIRCUIT(origin_circ);
    116  const node_t *exitnode;
    117  cpath_build_state_t *build_state;
    118  tor_assert(circ);
    119  tor_assert(conn);
    120  tor_assert(conn->socks_request);
    121 
    122  if (must_be_open && (circ->state != CIRCUIT_STATE_OPEN || !circ->n_chan))
    123    return 0; /* ignore non-open circs */
    124  if (circ->marked_for_close)
    125    return 0;
    126 
    127  /* if this circ isn't our purpose, skip. */
    128  if (purpose == CIRCUIT_PURPOSE_C_REND_JOINED && !must_be_open) {
    129    if (circ->purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
    130        circ->purpose != CIRCUIT_PURPOSE_C_REND_READY &&
    131        circ->purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED &&
    132        circ->purpose != CIRCUIT_PURPOSE_C_REND_JOINED)
    133      return 0;
    134  } else if (purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT &&
    135             !must_be_open) {
    136    if (circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCING &&
    137        circ->purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
    138      return 0;
    139  } else {
    140    if (purpose != circ->purpose)
    141      return 0;
    142  }
    143 
    144  if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
    145      purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
    146      purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
    147      purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
    148      purpose == CIRCUIT_PURPOSE_C_REND_JOINED ||
    149      purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED) {
    150    if (circ->timestamp_dirty &&
    151       circ->timestamp_dirty+get_options()->MaxCircuitDirtiness <= now)
    152      return 0;
    153  }
    154 
    155  if (origin_circ->unusable_for_new_conns)
    156    return 0;
    157 
    158  /* decide if this circ is suitable for this conn */
    159 
    160  /* for rend circs, circ->cpath->prev is not the last router in the
    161   * circuit, it's the magical extra service hop. so just check the nickname
    162   * of the one we meant to finish at.
    163   */
    164  build_state = origin_circ->build_state;
    165  exitnode = build_state_get_exit_node(build_state);
    166 
    167  if (need_uptime && !build_state->need_uptime)
    168    return 0;
    169  if (need_internal != build_state->is_internal)
    170    return 0;
    171 
    172  if (purpose == CIRCUIT_PURPOSE_C_GENERAL ||
    173      purpose == CIRCUIT_PURPOSE_CONFLUX_UNLINKED ||
    174      purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED ||
    175      purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
    176      purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
    177    tor_addr_t addr;
    178    if (!exitnode && !build_state->onehop_tunnel) {
    179      log_debug(LD_CIRC,"Not considering circuit with unknown router.");
    180      return 0; /* this circuit is screwed and doesn't know it yet,
    181                 * or is a rendezvous circuit. */
    182    }
    183    if (build_state->onehop_tunnel) {
    184      if (!conn->want_onehop) {
    185        log_debug(LD_CIRC,"Skipping one-hop circuit.");
    186        return 0;
    187      }
    188      tor_assert(conn->chosen_exit_name);
    189      if (build_state->chosen_exit) {
    190        char digest[DIGEST_LEN];
    191        if (hexdigest_to_digest(conn->chosen_exit_name, digest) < 0)
    192          return 0; /* broken digest, we don't want it */
    193        if (tor_memneq(digest, build_state->chosen_exit->identity_digest,
    194                          DIGEST_LEN))
    195          return 0; /* this is a circuit to somewhere else */
    196        if (tor_digest_is_zero(digest)) {
    197          /* we don't know the digest; have to compare addr:port */
    198          const int family = tor_addr_parse(&addr,
    199                                            conn->socks_request->address);
    200          if (family < 0 ||
    201              !extend_info_has_orport(build_state->chosen_exit, &addr,
    202                                      conn->socks_request->port))
    203            return 0;
    204        }
    205      }
    206    } else {
    207      if (conn->want_onehop) {
    208        /* don't use three-hop circuits -- that could hurt our anonymity. */
    209        return 0;
    210      }
    211    }
    212    if (origin_circ->prepend_policy) {
    213      if (tor_addr_parse(&addr, conn->socks_request->address) != -1) {
    214        int r = compare_tor_addr_to_addr_policy(&addr,
    215                                                conn->socks_request->port,
    216                                                origin_circ->prepend_policy);
    217        if (r == ADDR_POLICY_REJECTED)
    218          return 0;
    219      }
    220    }
    221    if (exitnode && !connection_ap_can_use_exit(conn, exitnode)) {
    222      /* can't exit from this router */
    223      return 0;
    224    }
    225  } else { /* not general: this might be a rend circuit */
    226    const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
    227    if (!circuit_matches_with_rend_stream(edge_conn, origin_circ)) {
    228      return 0;
    229    }
    230  }
    231 
    232  if (!connection_edge_compatible_with_circuit(conn, origin_circ)) {
    233    /* conn needs to be isolated from other conns that have already used
    234     * origin_circ */
    235    return 0;
    236  }
    237 
    238  return 1;
    239 }
    240 
    241 /** Return 1 if circuit <b>a</b> is better than circuit <b>b</b> for
    242 * <b>conn</b>, and return 0 otherwise. Used by circuit_get_best.
    243 */
    244 static int
    245 circuit_is_better(const origin_circuit_t *oa, const origin_circuit_t *ob,
    246                  const entry_connection_t *conn)
    247 {
    248  const circuit_t *a = TO_CIRCUIT(oa);
    249  const circuit_t *b = TO_CIRCUIT(ob);
    250  const uint8_t purpose = ENTRY_TO_CONN(conn)->purpose;
    251  int a_bits, b_bits;
    252 
    253  /* If one of the circuits was allowed to live due to relaxing its timeout,
    254   * it is definitely worse (it's probably a much slower path). */
    255  if (oa->relaxed_timeout && !ob->relaxed_timeout)
    256    return 0; /* ob is better. It's not relaxed. */
    257  if (!oa->relaxed_timeout && ob->relaxed_timeout)
    258    return 1; /* oa is better. It's not relaxed. */
    259 
    260  switch (purpose) {
    261    case CIRCUIT_PURPOSE_S_HSDIR_POST:
    262    case CIRCUIT_PURPOSE_C_HSDIR_GET:
    263    case CIRCUIT_PURPOSE_C_GENERAL:
    264      /* if it's used but less dirty it's best;
    265       * else if it's more recently created it's best
    266       */
    267      if (b->timestamp_dirty) {
    268        if (a->timestamp_dirty &&
    269            a->timestamp_dirty > b->timestamp_dirty)
    270          return 1;
    271      } else {
    272        if (a->timestamp_dirty ||
    273            timercmp(&a->timestamp_began, &b->timestamp_began, OP_GT))
    274          return 1;
    275        if (ob->build_state->is_internal)
    276          /* XXXX++ what the heck is this internal thing doing here. I
    277           * think we can get rid of it. circuit_is_acceptable() already
    278           * makes sure that is_internal is exactly what we need it to
    279           * be. -RD */
    280          return 1;
    281      }
    282      break;
    283    case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
    284      /* the closer it is to ack_wait the better it is */
    285      if (a->purpose > b->purpose)
    286        return 1;
    287      break;
    288    case CIRCUIT_PURPOSE_C_REND_JOINED:
    289      /* the closer it is to rend_joined the better it is */
    290      if (a->purpose > b->purpose)
    291        return 1;
    292      break;
    293  }
    294 
    295  /* XXXX Maybe this check should get a higher priority to avoid
    296   *   using up circuits too rapidly. */
    297 
    298  a_bits = connection_edge_update_circuit_isolation(conn,
    299                                                    (origin_circuit_t*)oa, 1);
    300  b_bits = connection_edge_update_circuit_isolation(conn,
    301                                                    (origin_circuit_t*)ob, 1);
    302  /* if x_bits < 0, then we have not used x for anything; better not to dirty
    303   * a connection if we can help it. */
    304  if (a_bits < 0) {
    305    return 0;
    306  } else if (b_bits < 0) {
    307    return 1;
    308  }
    309  a_bits &= ~ oa->isolation_flags_mixed;
    310  a_bits &= ~ ob->isolation_flags_mixed;
    311  if (n_bits_set_u8(a_bits) < n_bits_set_u8(b_bits)) {
    312    /* The fewer new restrictions we need to make on a circuit for stream
    313     * isolation, the better. */
    314    return 1;
    315  }
    316 
    317  return 0;
    318 }
    319 
    320 /** Find the best circ that conn can use, preferably one which is
    321 * dirty. Circ must not be too old.
    322 *
    323 * Conn must be defined.
    324 *
    325 * If must_be_open, ignore circs not in CIRCUIT_STATE_OPEN.
    326 *
    327 * circ_purpose specifies what sort of circuit we must have.
    328 * It can be C_GENERAL, C_INTRODUCE_ACK_WAIT, or C_REND_JOINED.
    329 *
    330 * If it's REND_JOINED and must_be_open==0, then return the closest
    331 * rendezvous-purposed circuit that you can find.
    332 *
    333 * If it's INTRODUCE_ACK_WAIT and must_be_open==0, then return the
    334 * closest introduce-purposed circuit that you can find.
    335 */
    336 static origin_circuit_t *
    337 circuit_get_best(const entry_connection_t *conn,
    338                 int must_be_open, uint8_t purpose,
    339                 int need_uptime, int need_internal)
    340 {
    341  origin_circuit_t *best=NULL;
    342  struct timeval now;
    343  time_t now_sec;
    344 
    345  tor_assert(conn);
    346 
    347  tor_assert(purpose == CIRCUIT_PURPOSE_C_GENERAL ||
    348             purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
    349             purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
    350             purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
    351             purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT ||
    352             purpose == CIRCUIT_PURPOSE_C_REND_JOINED);
    353 
    354  tor_gettimeofday(&now);
    355  now_sec = now.tv_sec;
    356 
    357  // Prefer pre-built conflux circuits here, if available but only for general
    358  // purposes. We don't have onion service conflux support at the moment.
    359  if (purpose == CIRCUIT_PURPOSE_C_GENERAL &&
    360      (best = conflux_get_circ_for_conn(conn, now_sec))) {
    361    return best;
    362  }
    363 
    364  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
    365    origin_circuit_t *origin_circ;
    366    if (!CIRCUIT_IS_ORIGIN(circ))
    367      continue;
    368    origin_circ = TO_ORIGIN_CIRCUIT(circ);
    369 
    370    if (!circuit_is_acceptable(origin_circ,conn,must_be_open,purpose,
    371                               need_uptime,need_internal, now_sec))
    372      continue;
    373 
    374    /* now this is an acceptable circ to hand back. but that doesn't
    375     * mean it's the *best* circ to hand back. try to decide.
    376     */
    377    if (!best || circuit_is_better(origin_circ,best,conn))
    378      best = origin_circ;
    379  }
    380  SMARTLIST_FOREACH_END(circ);
    381 
    382  return best;
    383 }
    384 
    385 /** Return the number of not-yet-open general-purpose origin circuits. */
    386 static int
    387 count_pending_general_client_circuits(void)
    388 {
    389  int count = 0;
    390 
    391  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
    392    if (circ->marked_for_close ||
    393        circ->state == CIRCUIT_STATE_OPEN ||
    394        !CIRCUIT_PURPOSE_COUNTS_TOWARDS_MAXPENDING(circ->purpose) ||
    395        !CIRCUIT_IS_ORIGIN(circ))
    396      continue;
    397 
    398    ++count;
    399  }
    400  SMARTLIST_FOREACH_END(circ);
    401 
    402  return count;
    403 }
    404 
    405 #if 0
    406 /** Check whether, according to the policies in <b>options</b>, the
    407 * circuit <b>circ</b> makes sense. */
    408 /* XXXX currently only checks Exclude{Exit}Nodes; it should check more.
    409 * Also, it doesn't have the right definition of an exit circuit. Also,
    410 * it's never called. */
    411 int
    412 circuit_conforms_to_options(const origin_circuit_t *circ,
    413                            const or_options_t *options)
    414 {
    415  const crypt_path_t *cpath, *cpath_next = NULL;
    416 
    417  /* first check if it includes any excluded nodes */
    418  for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
    419    cpath_next = cpath->next;
    420    if (routerset_contains_extendinfo(options->ExcludeNodes,
    421                                      cpath->extend_info))
    422      return 0;
    423  }
    424 
    425  /* then consider the final hop */
    426  if (routerset_contains_extendinfo(options->ExcludeExitNodes,
    427                                    circ->cpath->prev->extend_info))
    428    return 0;
    429 
    430  return 1;
    431 }
    432 #endif /* 0 */
    433 
    434 /**
    435 * Close all circuits that start at us, aren't open, and were born
    436 * at least CircuitBuildTimeout seconds ago.
    437 *
    438 * TODO: This function is now partially redundant to
    439 * circuit_build_times_handle_completed_hop(), but that function only
    440 * covers circuits up to and including 3 hops that are still actually
    441 * completing hops. However, circuit_expire_building() also handles longer
    442 * circuits, as well as circuits that are completely stalled.
    443 * In the future (after prop247/other path selection revamping), we probably
    444 * want to eliminate this rats nest in favor of a simpler approach.
    445 */
    446 void
    447 circuit_expire_building(void)
    448 {
    449  /* circ_times.timeout_ms and circ_times.close_ms are from
    450   * circuit_build_times_get_initial_timeout() if we haven't computed
    451   * custom timeouts yet */
    452  struct timeval general_cutoff, begindir_cutoff, fourhop_cutoff,
    453    close_cutoff, extremely_old_cutoff,
    454    cannibalized_cutoff, c_intro_cutoff, s_intro_cutoff, stream_cutoff,
    455    c_rend_ready_cutoff;
    456  const or_options_t *options = get_options();
    457  struct timeval now;
    458  cpath_build_state_t *build_state;
    459  int any_opened_circs = 0;
    460 
    461  tor_gettimeofday(&now);
    462 
    463  /* Check to see if we have any opened circuits. If we don't,
    464   * we want to be more lenient with timeouts, in case the
    465   * user has relocated and/or changed network connections.
    466   * See bug #3443. */
    467  any_opened_circs = circuit_any_opened_circuits();
    468 
    469 #define SET_CUTOFF(target, msec) do {                       \
    470    long ms = tor_lround(msec);                             \
    471    struct timeval diff;                                    \
    472    diff.tv_sec = ms / 1000;                                \
    473    diff.tv_usec = (int)((ms % 1000) * 1000);               \
    474    timersub(&now, &diff, &target);                         \
    475  } while (0)
    476 
    477  /**
    478   * Because circuit build timeout is calculated only based on 3 hop
    479   * general purpose circuit construction, we need to scale the timeout
    480   * to make it properly apply to longer circuits, and circuits of
    481   * certain usage types. The following diagram illustrates how we
    482   * derive the scaling below. In short, we calculate the number
    483   * of times our telescoping-based circuit construction causes cells
    484   * to traverse each link for the circuit purpose types in question,
    485   * and then assume each link is equivalent.
    486   *
    487   * OP --a--> A --b--> B --c--> C
    488   * OP --a--> A --b--> B --c--> C --d--> D
    489   *
    490   * Let h = a = b = c = d
    491   *
    492   * Three hops (general_cutoff)
    493   *   RTTs = 3a + 2b + c
    494   *   RTTs = 6h
    495   * Cannibalized:
    496   *   RTTs = a+b+c+d
    497   *   RTTs = 4h
    498   * Four hops:
    499   *   RTTs = 4a + 3b + 2c + d
    500   *   RTTs = 10h
    501   * Client INTRODUCE1+ACK: // XXX: correct?
    502   *   RTTs = 5a + 4b + 3c + 2d
    503   *   RTTs = 14h
    504   * Server intro:
    505   *   RTTs = 4a + 3b + 2c
    506   *   RTTs = 9h
    507   */
    508  SET_CUTOFF(general_cutoff, get_circuit_build_timeout_ms());
    509  SET_CUTOFF(begindir_cutoff, get_circuit_build_timeout_ms());
    510 
    511  // TODO: We should probably use route_len_for_purpose() here instead,
    512  // except that does not count the extra round trip for things like server
    513  // intros and rends.
    514 
    515  /* > 3hop circs seem to have a 1.0 second delay on their cannibalized
    516   * 4th hop. */
    517  SET_CUTOFF(fourhop_cutoff, get_circuit_build_timeout_ms() * (10/6.0) + 1000);
    518 
    519  /* CIRCUIT_PURPOSE_C_ESTABLISH_REND behaves more like a RELAY cell.
    520   * Use the stream cutoff (more or less). */
    521  SET_CUTOFF(stream_cutoff, MAX(options->CircuitStreamTimeout,15)*1000 + 1000);
    522 
    523  /* Be lenient with cannibalized circs. They already survived the official
    524   * CBT, and they're usually not performance-critical. */
    525  SET_CUTOFF(cannibalized_cutoff,
    526             MAX(get_circuit_build_close_time_ms()*(4/6.0),
    527                 options->CircuitStreamTimeout * 1000) + 1000);
    528 
    529  /* Intro circs have an extra round trip (and are also 4 hops long) */
    530  SET_CUTOFF(c_intro_cutoff, get_circuit_build_timeout_ms() * (14/6.0) + 1000);
    531 
    532  /* Server intro circs have an extra round trip */
    533  SET_CUTOFF(s_intro_cutoff, get_circuit_build_timeout_ms() * (9/6.0) + 1000);
    534 
    535  /* For circuit purpose set to: CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED.
    536   *
    537   * The cutoff of such circuit is very high because we end up in this state if
    538   * once the INTRODUCE_ACK is received which could be before the service
    539   * receives the INTRODUCE2 cell. The worst case is a full 3-hop latency
    540   * (intro -> service), 4-hop circuit creation latency (service -> RP), and
    541   * finally a 7-hop latency for the RENDEZVOUS2 cell to arrive (service ->
    542   * client). */
    543  SET_CUTOFF(c_rend_ready_cutoff, get_circuit_build_timeout_ms() * 3 + 1000);
    544 
    545  SET_CUTOFF(close_cutoff, get_circuit_build_close_time_ms());
    546  SET_CUTOFF(extremely_old_cutoff, get_circuit_build_close_time_ms()*2 + 1000);
    547 
    548  bool fixed_time = circuit_build_times_disabled(get_options());
    549 
    550  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *,victim) {
    551    struct timeval cutoff;
    552 
    553    if (!CIRCUIT_IS_ORIGIN(victim) || /* didn't originate here */
    554        victim->marked_for_close)     /* don't mess with marked circs */
    555      continue;
    556 
    557    /* If we haven't yet started the first hop, it means we don't have
    558     * any orconns available, and thus have not started counting time yet
    559     * for this circuit. See circuit_deliver_create_cell() and uses of
    560     * timestamp_began.
    561     *
    562     * Continue to wait in this case. The ORConn should timeout
    563     * independently and kill us then.
    564     */
    565    if (TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_CLOSED) {
    566      continue;
    567    }
    568 
    569    build_state = TO_ORIGIN_CIRCUIT(victim)->build_state;
    570    if (build_state && build_state->onehop_tunnel)
    571      cutoff = begindir_cutoff;
    572    else if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
    573      cutoff = close_cutoff;
    574    else if (victim->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
    575      cutoff = c_intro_cutoff;
    576    else if (victim->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO)
    577      cutoff = s_intro_cutoff;
    578    else if (victim->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
    579      /* Service connecting to a rendezvous point is a four hop circuit. We set
    580       * it explicitly here because this function is a clusterf***. */
    581      cutoff = fourhop_cutoff;
    582    } else if (victim->purpose == CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
    583      cutoff = c_rend_ready_cutoff;
    584    else if (victim->purpose == CIRCUIT_PURPOSE_PATH_BIAS_TESTING)
    585      cutoff = close_cutoff;
    586    else if (TO_ORIGIN_CIRCUIT(victim)->has_opened &&
    587             victim->state != CIRCUIT_STATE_OPEN)
    588      cutoff = cannibalized_cutoff;
    589    else if (build_state && build_state->desired_path_len >= 4)
    590      cutoff = fourhop_cutoff;
    591    else
    592      cutoff = general_cutoff;
    593 
    594    if (timercmp(&victim->timestamp_began, &cutoff, OP_GT))
    595      continue; /* it's still young, leave it alone */
    596 
    597    /* We need to double-check the opened state here because
    598     * we don't want to consider opened 1-hop dircon circuits for
    599     * deciding when to relax the timeout, but we *do* want to relax
    600     * those circuits too if nothing else is opened *and* they still
    601     * aren't either. */
    602    if (!any_opened_circs && victim->state != CIRCUIT_STATE_OPEN) {
    603      /* It's still young enough that we wouldn't close it, right? */
    604      if (timercmp(&victim->timestamp_began, &close_cutoff, OP_GT)) {
    605        if (!TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout) {
    606          int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath->state
    607                                      == CPATH_STATE_OPEN;
    608          if (!fixed_time) {
    609            log_info(LD_CIRC,
    610                "No circuits are opened. Relaxing timeout for circuit %d "
    611                "(a %s %d-hop circuit in state %s with channel state %s).",
    612                TO_ORIGIN_CIRCUIT(victim)->global_identifier,
    613                circuit_purpose_to_string(victim->purpose),
    614                TO_ORIGIN_CIRCUIT(victim)->build_state ?
    615                  TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
    616                  -1,
    617                circuit_state_to_string(victim->state),
    618                victim->n_chan ?
    619                   channel_state_to_string(victim->n_chan->state) : "none");
    620          }
    621 
    622          /* We count the timeout here for CBT, because technically this
    623           * was a timeout, and the timeout value needs to reset if we
    624           * see enough of them. Note this means we also need to avoid
    625           * double-counting below, too. */
    626          circuit_build_times_count_timeout(get_circuit_build_times_mutable(),
    627              first_hop_succeeded);
    628          TO_ORIGIN_CIRCUIT(victim)->relaxed_timeout = 1;
    629        }
    630        continue;
    631      } else {
    632        static ratelim_t relax_timeout_limit = RATELIM_INIT(3600);
    633        const double build_close_ms = get_circuit_build_close_time_ms();
    634        if (!fixed_time) {
    635          log_fn_ratelim(&relax_timeout_limit, LOG_NOTICE, LD_CIRC,
    636                 "No circuits are opened. Relaxed timeout for circuit %d "
    637                 "(a %s %d-hop circuit in state %s with channel state %s) to "
    638                 "%ldms. However, it appears the circuit has timed out "
    639                 "anyway.",
    640                 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
    641                 circuit_purpose_to_string(victim->purpose),
    642                 TO_ORIGIN_CIRCUIT(victim)->build_state ?
    643                   TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
    644                   -1,
    645                 circuit_state_to_string(victim->state),
    646                 victim->n_chan ?
    647                    channel_state_to_string(victim->n_chan->state) : "none",
    648                 (long)build_close_ms);
    649        }
    650      }
    651    }
    652 
    653 #if 0
    654    /* some debug logs, to help track bugs */
    655    if (victim->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
    656        victim->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) {
    657      if (!victim->timestamp_dirty)
    658        log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d)."
    659               "(clean).",
    660               victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
    661               victim->purpose, victim->build_state->chosen_exit_name,
    662               victim->n_circ_id);
    663      else
    664        log_fn(LOG_DEBUG,"Considering %sopen purpose %d to %s (circid %d). "
    665               "%d secs since dirty.",
    666               victim->state == CIRCUIT_STATE_OPEN ? "" : "non",
    667               victim->purpose, victim->build_state->chosen_exit_name,
    668               victim->n_circ_id,
    669               (int)(now - victim->timestamp_dirty));
    670    }
    671 #endif /* 0 */
    672 
    673    /* if circ is !open, or if it's open but purpose is a non-finished
    674     * intro or rend, then mark it for close */
    675    if (victim->state == CIRCUIT_STATE_OPEN) {
    676      switch (victim->purpose) {
    677        default: /* most open circuits can be left alone. */
    678          continue; /* yes, continue inside a switch refers to the nearest
    679                     * enclosing loop. C is smart. */
    680        case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
    681          break; /* too old, need to die */
    682        case CIRCUIT_PURPOSE_C_REND_READY:
    683          /* it's a rend_ready circ -- has it already picked a query? */
    684          /* c_rend_ready circs measure age since timestamp_dirty,
    685           * because that's set when they switch purposes
    686           */
    687          if (TO_ORIGIN_CIRCUIT(victim)->hs_ident ||
    688              victim->timestamp_dirty > cutoff.tv_sec)
    689            continue;
    690          break;
    691        case CIRCUIT_PURPOSE_PATH_BIAS_TESTING:
    692          /* Open path bias testing circuits are given a long
    693           * time to complete the test, but not forever */
    694          TO_ORIGIN_CIRCUIT(victim)->path_state = PATH_STATE_USE_FAILED;
    695          break;
    696        case CIRCUIT_PURPOSE_C_INTRODUCING:
    697          /* That purpose means that the intro point circuit has been opened
    698           * successfully but the INTRODUCE1 cell hasn't been sent yet because
    699           * the client is waiting for the rendezvous point circuit to open.
    700           * Keep this circuit open while waiting for the rendezvous circuit.
    701           * We let the circuit idle timeout take care of cleaning this
    702           * circuit if it never used. */
    703          continue;
    704        case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
    705        case CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED:
    706        case CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT:
    707          /* rend and intro circs become dirty each time they
    708           * make an introduction attempt. so timestamp_dirty
    709           * will reflect the time since the last attempt.
    710           */
    711          if (victim->timestamp_dirty > cutoff.tv_sec)
    712            continue;
    713          break;
    714      }
    715    } else { /* circuit not open, consider recording failure as timeout */
    716      int first_hop_succeeded = TO_ORIGIN_CIRCUIT(victim)->cpath &&
    717            TO_ORIGIN_CIRCUIT(victim)->cpath->state == CPATH_STATE_OPEN;
    718      if (TO_ORIGIN_CIRCUIT(victim)->p_streams != NULL) {
    719        log_warn(LD_BUG, "Circuit %d (purpose %d, %s) has timed out, "
    720                 "yet has attached streams!",
    721                 TO_ORIGIN_CIRCUIT(victim)->global_identifier,
    722                 victim->purpose,
    723                 circuit_purpose_to_string(victim->purpose));
    724        tor_fragile_assert();
    725        continue;
    726      }
    727 
    728      if (circuit_timeout_want_to_count_circ(TO_ORIGIN_CIRCUIT(victim)) &&
    729          circuit_build_times_enough_to_compute(get_circuit_build_times())) {
    730 
    731        log_info(LD_CIRC,
    732                 "Deciding to count the timeout for circuit %"PRIu32,
    733                 TO_ORIGIN_CIRCUIT(victim)->global_identifier);
    734 
    735        /* Circuits are allowed to last longer for measurement.
    736         * Switch their purpose and wait. */
    737        if (victim->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
    738          circuit_build_times_mark_circ_as_measurement_only(TO_ORIGIN_CIRCUIT(
    739                                                            victim));
    740          continue;
    741        }
    742 
    743        /*
    744         * If the circuit build time is much greater than we would have cut
    745         * it off at, we probably had a suspend event along this codepath,
    746         * and we should discard the value.
    747         */
    748        if (timercmp(&victim->timestamp_began, &extremely_old_cutoff, OP_LT)) {
    749          log_notice(LD_CIRC,
    750                     "Extremely large value for circuit build timeout: %lds. "
    751                     "Assuming clock jump. Purpose %d (%s)",
    752                     (long)(now.tv_sec - victim->timestamp_began.tv_sec),
    753                     victim->purpose,
    754                     circuit_purpose_to_string(victim->purpose));
    755        } else if (circuit_build_times_count_close(
    756            get_circuit_build_times_mutable(),
    757            first_hop_succeeded,
    758            (time_t)victim->timestamp_created.tv_sec)) {
    759          circuit_build_times_set_timeout(get_circuit_build_times_mutable());
    760        }
    761      }
    762    }
    763 
    764    /* Special checks for onion service circuits. */
    765    switch (victim->purpose) {
    766    case CIRCUIT_PURPOSE_C_REND_READY:
    767      /* We only want to spare a rend circ iff it has been specified in an
    768       * INTRODUCE1 cell sent to a hidden service. */
    769      if (hs_circ_is_rend_sent_in_intro1(CONST_TO_ORIGIN_CIRCUIT(victim))) {
    770        continue;
    771      }
    772      break;
    773    case CIRCUIT_PURPOSE_S_CONNECT_REND:
    774      /* The connection to the rendezvous point has timed out, close it and
    775       * retry if possible. */
    776      log_info(LD_CIRC,"Rendezvous circ %u (state %d:%s, purpose %d) "
    777               "as timed-out, closing it. Relaunching rendezvous attempt.",
    778               (unsigned)victim->n_circ_id,
    779               victim->state, circuit_state_to_string(victim->state),
    780               victim->purpose);
    781      /* We'll close as a timeout the victim circuit. The rendezvous point
    782       * won't keep both circuits, it only keeps the newest (for the same
    783       * cookie). */
    784      break;
    785    default:
    786      break;
    787    }
    788 
    789    if (victim->n_chan)
    790      log_info(LD_CIRC,
    791               "Abandoning circ %u %s:%u (state %d,%d:%s, purpose %d, "
    792               "len %d)", TO_ORIGIN_CIRCUIT(victim)->global_identifier,
    793               channel_describe_peer(victim->n_chan),
    794               (unsigned)victim->n_circ_id,
    795               TO_ORIGIN_CIRCUIT(victim)->has_opened,
    796               victim->state, circuit_state_to_string(victim->state),
    797               victim->purpose,
    798               TO_ORIGIN_CIRCUIT(victim)->build_state ?
    799                 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
    800                 -1);
    801    else
    802      log_info(LD_CIRC,
    803               "Abandoning circ %u %u (state %d,%d:%s, purpose %d, len %d)",
    804               TO_ORIGIN_CIRCUIT(victim)->global_identifier,
    805               (unsigned)victim->n_circ_id,
    806               TO_ORIGIN_CIRCUIT(victim)->has_opened,
    807               victim->state,
    808               circuit_state_to_string(victim->state), victim->purpose,
    809               TO_ORIGIN_CIRCUIT(victim)->build_state ?
    810                 TO_ORIGIN_CIRCUIT(victim)->build_state->desired_path_len :
    811                 -1);
    812 
    813    circuit_log_path(LOG_INFO,LD_CIRC,TO_ORIGIN_CIRCUIT(victim));
    814    tor_trace(TR_SUBSYS(circuit), TR_EV(timeout), TO_ORIGIN_CIRCUIT(victim));
    815    if (victim->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
    816      circuit_mark_for_close(victim, END_CIRC_REASON_MEASUREMENT_EXPIRED);
    817    else
    818      circuit_mark_for_close(victim, END_CIRC_REASON_TIMEOUT);
    819 
    820    pathbias_count_timeout(TO_ORIGIN_CIRCUIT(victim));
    821  } SMARTLIST_FOREACH_END(victim);
    822 }
    823 
    824 /**
    825 * Mark for close all circuits that start here, that were built through a
    826 * guard we weren't sure if we wanted to use, and that have been waiting
    827 * around for way too long.
    828 */
    829 void
    830 circuit_expire_waiting_for_better_guard(void)
    831 {
    832  SMARTLIST_FOREACH_BEGIN(circuit_get_global_origin_circuit_list(),
    833                          origin_circuit_t *, circ) {
    834    if (TO_CIRCUIT(circ)->marked_for_close)
    835      continue;
    836    if (circ->guard_state == NULL)
    837      continue;
    838    if (entry_guard_state_should_expire(circ->guard_state))
    839      circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NONE);
    840  } SMARTLIST_FOREACH_END(circ);
    841 }
    842 
    843 /** For debugging #8387: track when we last called
    844 * circuit_expire_old_circuits_clientside. */
    845 static time_t last_expired_clientside_circuits = 0;
    846 
    847 /**
    848 * As a diagnostic for bug 8387, log information about how many one-hop
    849 * circuits we have around that have been there for at least <b>age</b>
    850 * seconds. Log a few of them. Ignores Single Onion Service intro, it is
    851 * expected to be long-term one-hop circuits.
    852 */
    853 void
    854 circuit_log_ancient_one_hop_circuits(int age)
    855 {
    856 #define MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG 10
    857  time_t now = time(NULL);
    858  time_t cutoff = now - age;
    859  int n_found = 0;
    860  smartlist_t *log_these = smartlist_new();
    861  const or_options_t *options = get_options();
    862 
    863  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
    864    const origin_circuit_t *ocirc;
    865    if (! CIRCUIT_IS_ORIGIN(circ))
    866      continue;
    867    if (circ->timestamp_created.tv_sec >= cutoff)
    868      continue;
    869    /* Single Onion Services deliberately make long term one-hop intro
    870     * and rendezvous connections. Don't log the established ones. */
    871    if (hs_service_allow_non_anonymous_connection(options) &&
    872        (circ->purpose == CIRCUIT_PURPOSE_S_INTRO ||
    873         circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED))
    874      continue;
    875    ocirc = CONST_TO_ORIGIN_CIRCUIT(circ);
    876 
    877    if (ocirc->build_state && ocirc->build_state->onehop_tunnel) {
    878      ++n_found;
    879 
    880      if (smartlist_len(log_these) < MAX_ANCIENT_ONEHOP_CIRCUITS_TO_LOG)
    881        smartlist_add(log_these, (origin_circuit_t*) ocirc);
    882    }
    883  }
    884  SMARTLIST_FOREACH_END(circ);
    885 
    886  if (n_found == 0)
    887    goto done;
    888 
    889  log_notice(LD_HEARTBEAT,
    890             "Diagnostic for issue 8387: Found %d one-hop circuits more "
    891             "than %d seconds old! Logging %d...",
    892             n_found, age, smartlist_len(log_these));
    893 
    894  SMARTLIST_FOREACH_BEGIN(log_these, const origin_circuit_t *, ocirc) {
    895    char created[ISO_TIME_LEN+1];
    896    int stream_num;
    897    const edge_connection_t *conn;
    898    char *dirty = NULL;
    899    const circuit_t *circ = TO_CIRCUIT(ocirc);
    900 
    901    format_local_iso_time(created,
    902                          (time_t)circ->timestamp_created.tv_sec);
    903 
    904    if (circ->timestamp_dirty) {
    905      char dirty_since[ISO_TIME_LEN+1];
    906      format_local_iso_time(dirty_since, circ->timestamp_dirty);
    907 
    908      tor_asprintf(&dirty, "Dirty since %s (%ld seconds vs %ld-second cutoff)",
    909                   dirty_since, (long)(now - circ->timestamp_dirty),
    910                   (long) options->MaxCircuitDirtiness);
    911    } else {
    912      dirty = tor_strdup("Not marked dirty");
    913    }
    914 
    915    log_notice(LD_HEARTBEAT, "  #%d created at %s. %s, %s. %s for close. "
    916               "Package window: %d. "
    917               "%s for new conns. %s.",
    918               ocirc_sl_idx,
    919               created,
    920               circuit_state_to_string(circ->state),
    921               circuit_purpose_to_string(circ->purpose),
    922               circ->marked_for_close ? "Marked" : "Not marked",
    923               circ->package_window,
    924               ocirc->unusable_for_new_conns ? "Not usable" : "usable",
    925               dirty);
    926    tor_free(dirty);
    927 
    928    stream_num = 0;
    929    for (conn = ocirc->p_streams; conn; conn = conn->next_stream) {
    930      const connection_t *c = TO_CONN(conn);
    931      char stream_created[ISO_TIME_LEN+1];
    932      if (++stream_num >= 5)
    933        break;
    934 
    935      format_local_iso_time(stream_created, c->timestamp_created);
    936 
    937      log_notice(LD_HEARTBEAT, "     Stream#%d created at %s. "
    938                 "%s conn in state %s. "
    939                 "It is %slinked and %sreading from a linked connection %p. "
    940                 "Package window %d. "
    941                 "%s for close (%s:%d). Hold-open is %sset. "
    942                 "Has %ssent RELAY_END. %s on circuit.",
    943                 stream_num,
    944                 stream_created,
    945                 conn_type_to_string(c->type),
    946                 conn_state_to_string(c->type, c->state),
    947                 c->linked ? "" : "not ",
    948                 c->reading_from_linked_conn ? "": "not",
    949                 c->linked_conn,
    950                 conn->package_window,
    951                 c->marked_for_close ? "Marked" : "Not marked",
    952                 c->marked_for_close_file ? c->marked_for_close_file : "--",
    953                 c->marked_for_close,
    954                 c->hold_open_until_flushed ? "" : "not ",
    955                 conn->edge_has_sent_end ? "" : "not ",
    956                 connection_is_reading(c) ? "Not blocked" : "Blocked");
    957      if (! c->linked_conn)
    958        continue;
    959 
    960      c = c->linked_conn;
    961 
    962      log_notice(LD_HEARTBEAT, "        Linked to %s connection in state %s "
    963                 "(Purpose %d). %s for close (%s:%d). Hold-open is %sset. ",
    964                 conn_type_to_string(c->type),
    965                 conn_state_to_string(c->type, c->state),
    966                 c->purpose,
    967                 c->marked_for_close ? "Marked" : "Not marked",
    968                 c->marked_for_close_file ? c->marked_for_close_file : "--",
    969                 c->marked_for_close,
    970                 c->hold_open_until_flushed ? "" : "not ");
    971    }
    972  } SMARTLIST_FOREACH_END(ocirc);
    973 
    974  log_notice(LD_HEARTBEAT, "It has been %ld seconds since I last called "
    975             "circuit_expire_old_circuits_clientside().",
    976             (long)(now - last_expired_clientside_circuits));
    977 
    978 done:
    979  smartlist_free(log_these);
    980 }
    981 
    982 /** Remove any elements in <b>needed_ports</b> that are handled by an
    983 * open or in-progress circuit.
    984 */
    985 void
    986 circuit_remove_handled_ports(smartlist_t *needed_ports)
    987 {
    988  int i;
    989  uint16_t *port;
    990 
    991  for (i = 0; i < smartlist_len(needed_ports); ++i) {
    992    port = smartlist_get(needed_ports, i);
    993    tor_assert(*port);
    994    if (circuit_stream_is_being_handled(NULL, *port,
    995                                        MIN_CIRCUITS_HANDLING_STREAM)) {
    996      log_debug(LD_CIRC,"Port %d is already being handled; removing.", *port);
    997      smartlist_del(needed_ports, i--);
    998      tor_free(port);
    999    } else {
   1000      log_debug(LD_CIRC,"Port %d is not handled.", *port);
   1001    }
   1002  }
   1003 }
   1004 
   1005 /** Return 1 if at least <b>min</b> general-purpose non-internal circuits
   1006 * will have an acceptable exit node for exit stream <b>conn</b> if it
   1007 * is defined, else for "*:port".
   1008 * Else return 0.
   1009 */
   1010 int
   1011 circuit_stream_is_being_handled(entry_connection_t *conn,
   1012                                uint16_t port, int min)
   1013 {
   1014  const node_t *exitnode;
   1015  int num=0;
   1016  time_t now = time(NULL);
   1017  int need_uptime = smartlist_contains_int_as_string(
   1018                                   get_options()->LongLivedPorts,
   1019                                   conn ? conn->socks_request->port : port);
   1020 
   1021  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1022    if (CIRCUIT_IS_ORIGIN(circ) &&
   1023        !circ->marked_for_close &&
   1024        (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   1025         circ->purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED) &&
   1026        (!circ->timestamp_dirty ||
   1027         circ->timestamp_dirty + get_options()->MaxCircuitDirtiness > now)) {
   1028      origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
   1029      cpath_build_state_t *build_state = origin_circ->build_state;
   1030      if (build_state->is_internal || build_state->onehop_tunnel)
   1031        continue;
   1032      if (origin_circ->unusable_for_new_conns)
   1033        continue;
   1034      if (origin_circ->isolation_values_set &&
   1035          (conn == NULL ||
   1036           !connection_edge_compatible_with_circuit(conn, origin_circ)))
   1037        continue;
   1038 
   1039      exitnode = build_state_get_exit_node(build_state);
   1040      if (exitnode && (!need_uptime || build_state->need_uptime)) {
   1041        int ok;
   1042        if (conn) {
   1043          ok = connection_ap_can_use_exit(conn, exitnode);
   1044        } else {
   1045          addr_policy_result_t r;
   1046          r = compare_tor_addr_to_node_policy(NULL, port, exitnode);
   1047          ok = r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED;
   1048        }
   1049        if (ok) {
   1050          if (++num >= min)
   1051            return 1;
   1052        }
   1053      }
   1054    }
   1055  }
   1056  SMARTLIST_FOREACH_END(circ);
   1057  return 0;
   1058 }
   1059 
   1060 /** Don't keep more than this many unused open circuits around. */
   1061 #define MAX_UNUSED_OPEN_CIRCUITS 14
   1062 
   1063 /* Return true if a circuit is available for use, meaning that it is open,
   1064 * clean, usable for new multi-hop connections, and a general purpose origin
   1065 * circuit.
   1066 * Accept any kind of circuit, return false if the above conditions are not
   1067 * met. */
   1068 STATIC int
   1069 circuit_is_available_for_use(const circuit_t *circ)
   1070 {
   1071  const origin_circuit_t *origin_circ;
   1072  cpath_build_state_t *build_state;
   1073 
   1074  if (!CIRCUIT_IS_ORIGIN(circ))
   1075    return 0; /* We first filter out only origin circuits before doing the
   1076                 following checks. */
   1077  if (circ->marked_for_close)
   1078    return 0; /* Don't mess with marked circs */
   1079  if (circ->timestamp_dirty)
   1080    return 0; /* Only count clean circs */
   1081  if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
   1082      circ->purpose != CIRCUIT_PURPOSE_HS_VANGUARDS)
   1083    return 0; /* We only pay attention to general purpose circuits.
   1084                 General purpose circuits are always origin circuits. */
   1085 
   1086  origin_circ = CONST_TO_ORIGIN_CIRCUIT(circ);
   1087  if (origin_circ->unusable_for_new_conns)
   1088    return 0;
   1089 
   1090  build_state = origin_circ->build_state;
   1091  if (build_state->onehop_tunnel)
   1092    return 0;
   1093 
   1094  return 1;
   1095 }
   1096 
   1097 /* Return true if we need any more exit circuits.
   1098 * needs_uptime and needs_capacity are set only if we need more exit circuits.
   1099 * Check if we know of a port that's been requested recently and no circuit
   1100 * is currently available that can handle it. */
   1101 STATIC int
   1102 needs_exit_circuits(time_t now, int *needs_uptime, int *needs_capacity)
   1103 {
   1104  return (!circuit_all_predicted_ports_handled(now, needs_uptime,
   1105                                               needs_capacity) &&
   1106          router_have_consensus_path() == CONSENSUS_PATH_EXIT);
   1107 }
   1108 
   1109 /* Hidden services need at least this many internal circuits */
   1110 #define SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS 3
   1111 
   1112 /* Return true if we need any more hidden service server circuits.
   1113 * HS servers only need an internal circuit. */
   1114 STATIC int
   1115 needs_hs_server_circuits(time_t now, int num_uptime_internal)
   1116 {
   1117  if (!hs_service_get_num_services()) {
   1118    /* No services, we don't need anything. */
   1119    goto no_need;
   1120  }
   1121 
   1122  if (num_uptime_internal >= SUFFICIENT_UPTIME_INTERNAL_HS_SERVERS) {
   1123    /* We have sufficient amount of internal circuit. */
   1124    goto no_need;
   1125  }
   1126 
   1127  if (router_have_consensus_path() == CONSENSUS_PATH_UNKNOWN) {
   1128    /* Consensus hasn't been checked or might be invalid so requesting
   1129     * internal circuits is not wise. */
   1130    goto no_need;
   1131  }
   1132 
   1133  /* At this point, we need a certain amount of circuits and we will most
   1134   * likely use them for rendezvous so we note down the use of internal
   1135   * circuit for our prediction for circuit needing uptime and capacity. */
   1136  rep_hist_note_used_internal(now, 1, 1);
   1137 
   1138  return 1;
   1139 no_need:
   1140  return 0;
   1141 }
   1142 
   1143 /* We need at least this many internal circuits for hidden service clients */
   1144 #define SUFFICIENT_INTERNAL_HS_CLIENTS 3
   1145 
   1146 /* We need at least this much uptime for internal circuits for hidden service
   1147 * clients */
   1148 #define SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS 2
   1149 
   1150 /* Return true if we need any more hidden service client circuits.
   1151 * HS clients only need an internal circuit. */
   1152 STATIC int
   1153 needs_hs_client_circuits(time_t now, int *needs_uptime, int *needs_capacity,
   1154    int num_internal, int num_uptime_internal)
   1155 {
   1156  int used_internal_recently = rep_hist_get_predicted_internal(now,
   1157                                                               needs_uptime,
   1158                                                               needs_capacity);
   1159  int requires_uptime = num_uptime_internal <
   1160                        SUFFICIENT_UPTIME_INTERNAL_HS_CLIENTS &&
   1161                        needs_uptime;
   1162 
   1163  return (used_internal_recently &&
   1164         (requires_uptime || num_internal < SUFFICIENT_INTERNAL_HS_CLIENTS) &&
   1165          router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN);
   1166 }
   1167 
   1168 /* This is how many circuits can be opened concurrently during the cbt learning
   1169 * phase. This number cannot exceed the tor-wide MAX_UNUSED_OPEN_CIRCUITS. */
   1170 #define DFLT_CBT_UNUSED_OPEN_CIRCS (10)
   1171 #define MIN_CBT_UNUSED_OPEN_CIRCS 0
   1172 #define MAX_CBT_UNUSED_OPEN_CIRCS MAX_UNUSED_OPEN_CIRCUITS
   1173 
   1174 /* Return true if we need more circuits for a good build timeout.
   1175 * XXXX make the assumption that build timeout streams should be
   1176 * created whenever we can build internal circuits. */
   1177 STATIC int
   1178 needs_circuits_for_build(int num)
   1179 {
   1180  if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN) {
   1181    if (num < networkstatus_get_param(NULL, "cbtmaxopencircs",
   1182                              DFLT_CBT_UNUSED_OPEN_CIRCS,
   1183                              MIN_CBT_UNUSED_OPEN_CIRCS,
   1184                              MAX_CBT_UNUSED_OPEN_CIRCS) &&
   1185        !circuit_build_times_disabled(get_options()) &&
   1186        circuit_build_times_needs_circuits_now(get_circuit_build_times())) {
   1187      return 1;
   1188    }
   1189  }
   1190  return 0;
   1191 }
   1192 
   1193 /** Determine how many circuits we have open that are clean,
   1194 * Make sure it's enough for all the upcoming behaviors we predict we'll have.
   1195 * But put an upper bound on the total number of circuits.
   1196 */
   1197 static void
   1198 circuit_predict_and_launch_new(void)
   1199 {
   1200  int num=0, num_internal=0, num_uptime_internal=0;
   1201  int hidserv_needs_uptime=0, hidserv_needs_capacity=1;
   1202  int port_needs_uptime=0, port_needs_capacity=1;
   1203  time_t now = time(NULL);
   1204  int flags = 0;
   1205 
   1206  /* Attempt to launch predicted conflux circuits. This is outside the HS or
   1207   * Exit preemptive circuit set.
   1208   * As with the other types of preemptive circuits, we only want to
   1209   * launch them if we have predicted ports. (If we haven't needed a
   1210   * circuit for a while, maybe we won't need one soon either.) */
   1211  if (predicted_ports_prediction_time_remaining(now)) {
   1212    conflux_predict_new(now);
   1213  }
   1214 
   1215  /* Count how many of each type of circuit we currently have. */
   1216  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1217    if (!circuit_is_available_for_use(circ))
   1218      continue;
   1219 
   1220    num++;
   1221 
   1222    cpath_build_state_t *build_state = TO_ORIGIN_CIRCUIT(circ)->build_state;
   1223    if (build_state->is_internal)
   1224      num_internal++;
   1225    if (build_state->need_uptime && build_state->is_internal)
   1226      num_uptime_internal++;
   1227  }
   1228  SMARTLIST_FOREACH_END(circ);
   1229 
   1230  /* If that's enough, then stop now. */
   1231  if (num >= MAX_UNUSED_OPEN_CIRCUITS)
   1232    return;
   1233 
   1234  if (needs_exit_circuits(now, &port_needs_uptime, &port_needs_capacity)) {
   1235    if (port_needs_uptime)
   1236      flags |= CIRCLAUNCH_NEED_UPTIME;
   1237    if (port_needs_capacity)
   1238      flags |= CIRCLAUNCH_NEED_CAPACITY;
   1239 
   1240    log_info(LD_CIRC,
   1241             "Have %d clean circs (%d internal), need another exit circ.",
   1242             num, num_internal);
   1243 
   1244    circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
   1245    return;
   1246  }
   1247 
   1248  if (needs_hs_server_circuits(now, num_uptime_internal)) {
   1249    flags = (CIRCLAUNCH_NEED_CAPACITY | CIRCLAUNCH_NEED_UPTIME |
   1250             CIRCLAUNCH_IS_INTERNAL);
   1251 
   1252    log_info(LD_CIRC,
   1253             "Have %d clean circs (%d internal), need another internal "
   1254             "circ for my hidden service.",
   1255             num, num_internal);
   1256    circuit_launch(CIRCUIT_PURPOSE_HS_VANGUARDS, flags);
   1257    return;
   1258  }
   1259 
   1260  if (needs_hs_client_circuits(now, &hidserv_needs_uptime,
   1261                               &hidserv_needs_capacity,
   1262                               num_internal, num_uptime_internal))
   1263  {
   1264    if (hidserv_needs_uptime)
   1265      flags |= CIRCLAUNCH_NEED_UPTIME;
   1266    if (hidserv_needs_capacity)
   1267      flags |= CIRCLAUNCH_NEED_CAPACITY;
   1268    flags |= CIRCLAUNCH_IS_INTERNAL;
   1269 
   1270    log_info(LD_CIRC,
   1271             "Have %d clean circs (%d uptime-internal, %d internal), need"
   1272             " another hidden service circ.",
   1273             num, num_uptime_internal, num_internal);
   1274 
   1275    /* Always launch vanguards purpose circuits for HS clients,
   1276     * for vanguards-lite. This prevents us from cannibalizing
   1277     * to build these circuits (and thus not use vanguards). */
   1278    circuit_launch(CIRCUIT_PURPOSE_HS_VANGUARDS, flags);
   1279    return;
   1280  }
   1281 
   1282  if (needs_circuits_for_build(num)) {
   1283    flags = CIRCLAUNCH_NEED_CAPACITY;
   1284    /* if there are no exits in the consensus, make timeout
   1285     * circuits internal */
   1286    if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL)
   1287      flags |= CIRCLAUNCH_IS_INTERNAL;
   1288 
   1289    log_info(LD_CIRC,
   1290             "Have %d clean circs need another buildtime test circ.", num);
   1291    circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, flags);
   1292    return;
   1293  }
   1294 }
   1295 
   1296 /** Build a new test circuit every 5 minutes */
   1297 #define TESTING_CIRCUIT_INTERVAL 300
   1298 
   1299 /** This function is called once a second, if router_have_minimum_dir_info()
   1300 * is true. Its job is to make sure all services we offer have enough circuits
   1301 * available. Some services just want enough circuits for current tasks,
   1302 * whereas others want a minimum set of idle circuits hanging around.
   1303 */
   1304 void
   1305 circuit_build_needed_circs(time_t now)
   1306 {
   1307  const or_options_t *options = get_options();
   1308 
   1309  /* launch a new circ for any pending streams that need one
   1310   * XXXX make the assumption that (some) AP streams (i.e. HS clients)
   1311   * don't require an exit circuit, review in #13814.
   1312   * This allows HSs to function in a consensus without exits. */
   1313  if (router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN)
   1314    connection_ap_rescan_and_attach_pending();
   1315 
   1316  circuit_expire_old_circs_as_needed(now);
   1317 
   1318  if (!options->DisablePredictedCircuits)
   1319    circuit_predict_and_launch_new();
   1320 }
   1321 
   1322 /**
   1323 * Called once a second either directly or from
   1324 * circuit_build_needed_circs(). As appropriate (once per NewCircuitPeriod)
   1325 * resets failure counts and expires old circuits.
   1326 */
   1327 void
   1328 circuit_expire_old_circs_as_needed(time_t now)
   1329 {
   1330  static time_t time_to_expire_and_reset = 0;
   1331 
   1332  if (time_to_expire_and_reset < now) {
   1333    circuit_reset_failure_count(1);
   1334    time_to_expire_and_reset = now + get_options()->NewCircuitPeriod;
   1335    if (proxy_mode(get_options()))
   1336      addressmap_clean(now);
   1337    circuit_expire_old_circuits_clientside();
   1338 
   1339 #if 0 /* disable for now, until predict-and-launch-new can cull leftovers */
   1340 
   1341    /* If we ever re-enable, this has to move into
   1342     * circuit_build_needed_circs */
   1343 
   1344    circ = circuit_get_youngest_clean_open(CIRCUIT_PURPOSE_C_GENERAL);
   1345    if (get_options()->RunTesting &&
   1346        circ &&
   1347        circ->timestamp_began.tv_sec + TESTING_CIRCUIT_INTERVAL < now) {
   1348      log_fn(LOG_INFO,"Creating a new testing circuit.");
   1349      circuit_launch(CIRCUIT_PURPOSE_C_GENERAL, 0);
   1350    }
   1351 #endif /* 0 */
   1352  }
   1353 }
   1354 
   1355 /** If the stream <b>conn</b> is a member of any of the linked
   1356 * lists of <b>circ</b>, then remove it from the list.
   1357 */
   1358 void
   1359 circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
   1360 {
   1361  edge_connection_t *prevconn;
   1362  bool update_dirty = false;
   1363 
   1364  tor_assert(circ);
   1365  tor_assert(conn);
   1366 
   1367  if (conn->base_.type == CONN_TYPE_AP) {
   1368    entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
   1369    entry_conn->may_use_optimistic_data = 0;
   1370    // When KeepAliveIsolateSOCKSAuth is in effect, we update the dirty
   1371    // time on close as well as on open.
   1372    update_dirty = connection_ap_socks_iso_keepalive_enabled(entry_conn);
   1373  }
   1374  conn->cpath_layer = NULL; /* don't keep a stale pointer */
   1375  conn->on_circuit = NULL;
   1376 
   1377  if (CIRCUIT_IS_ORIGIN(circ)) {
   1378    origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
   1379    int removed = 0;
   1380    if (conn == origin_circ->p_streams) {
   1381      origin_circ->p_streams = conn->next_stream;
   1382      conflux_update_p_streams(origin_circ, conn->next_stream);
   1383      removed = 1;
   1384    } else {
   1385      for (prevconn = origin_circ->p_streams;
   1386           prevconn && prevconn->next_stream && prevconn->next_stream != conn;
   1387           prevconn = prevconn->next_stream)
   1388        ;
   1389      if (prevconn && prevconn->next_stream) {
   1390        prevconn->next_stream = conn->next_stream;
   1391        removed = 1;
   1392      }
   1393    }
   1394    if (removed) {
   1395      log_debug(LD_APP, "Removing stream %d from circ %u",
   1396                conn->stream_id, (unsigned)circ->n_circ_id);
   1397 
   1398      if (update_dirty) {
   1399        circ->timestamp_dirty = approx_time();
   1400      }
   1401 
   1402      /* If the stream was removed, and it was a rend stream, decrement the
   1403       * number of streams on the circuit associated with the rend service.
   1404       */
   1405      if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
   1406        hs_dec_rdv_stream_counter(origin_circ);
   1407      }
   1408 
   1409      /* If there are no more streams on this circ, tell circpad */
   1410      if (!origin_circ->p_streams)
   1411        circpad_machine_event_circ_has_no_streams(origin_circ);
   1412 
   1413      return;
   1414    }
   1415  } else {
   1416    or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
   1417    if (conn == or_circ->n_streams) {
   1418      or_circ->n_streams = conn->next_stream;
   1419      conflux_update_n_streams(or_circ, conn->next_stream);
   1420      return;
   1421    }
   1422    if (conn == or_circ->resolving_streams) {
   1423      or_circ->resolving_streams = conn->next_stream;
   1424      conflux_update_resolving_streams(or_circ, conn->next_stream);
   1425      return;
   1426    }
   1427 
   1428    for (prevconn = or_circ->n_streams;
   1429         prevconn && prevconn->next_stream && prevconn->next_stream != conn;
   1430         prevconn = prevconn->next_stream)
   1431      ;
   1432    if (prevconn && prevconn->next_stream) {
   1433      prevconn->next_stream = conn->next_stream;
   1434      return;
   1435    }
   1436 
   1437    for (prevconn = or_circ->resolving_streams;
   1438         prevconn && prevconn->next_stream && prevconn->next_stream != conn;
   1439         prevconn = prevconn->next_stream)
   1440      ;
   1441    if (prevconn && prevconn->next_stream) {
   1442      prevconn->next_stream = conn->next_stream;
   1443      return;
   1444    }
   1445  }
   1446 
   1447  log_warn(LD_BUG,"Edge connection not in circuit's list.");
   1448  /* Don't give an error here; it's harmless. */
   1449  tor_fragile_assert();
   1450 }
   1451 
   1452 /** Find each circuit that has been unused for too long, or dirty
   1453 * for too long and has no streams on it: mark it for close.
   1454 */
   1455 STATIC void
   1456 circuit_expire_old_circuits_clientside(void)
   1457 {
   1458  struct timeval cutoff, now;
   1459 
   1460  tor_gettimeofday(&now);
   1461  last_expired_clientside_circuits = now.tv_sec;
   1462 
   1463  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1464    if (circ->marked_for_close || !CIRCUIT_IS_ORIGIN(circ))
   1465      continue;
   1466 
   1467    cutoff = now;
   1468    cutoff.tv_sec -= TO_ORIGIN_CIRCUIT(circ)->circuit_idle_timeout;
   1469 
   1470    /* If the circuit has been dirty for too long, and there are no streams
   1471     * on it, mark it for close.
   1472     */
   1473    if (circ->timestamp_dirty &&
   1474        circ->timestamp_dirty + get_options()->MaxCircuitDirtiness <
   1475          now.tv_sec &&
   1476        !connection_half_edges_waiting(TO_ORIGIN_CIRCUIT(circ)) &&
   1477        !TO_ORIGIN_CIRCUIT(circ)->p_streams /* nothing attached */ ) {
   1478      log_debug(LD_CIRC, "Closing n_circ_id %u (dirty %ld sec ago, "
   1479                "purpose %d)",
   1480                (unsigned)circ->n_circ_id,
   1481                (long)(now.tv_sec - circ->timestamp_dirty),
   1482                circ->purpose);
   1483      /* Don't do this magic for testing circuits. Their death is governed
   1484       * by circuit_expire_building */
   1485      if (circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
   1486        tor_trace(TR_SUBSYS(circuit), TR_EV(idle_timeout),
   1487                  TO_ORIGIN_CIRCUIT(circ));
   1488        circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
   1489      }
   1490    } else if (!circ->timestamp_dirty && circ->state == CIRCUIT_STATE_OPEN) {
   1491      if (timercmp(&circ->timestamp_began, &cutoff, OP_LT)) {
   1492        if (circ->purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   1493                circ->purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
   1494                circ->purpose == CIRCUIT_PURPOSE_CONFLUX_UNLINKED ||
   1495                circ->purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED ||
   1496                circ->purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
   1497                circ->purpose == CIRCUIT_PURPOSE_HS_VANGUARDS ||
   1498                circ->purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT ||
   1499                circ->purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO ||
   1500                circ->purpose == CIRCUIT_PURPOSE_TESTING ||
   1501                circ->purpose == CIRCUIT_PURPOSE_C_CIRCUIT_PADDING ||
   1502                (circ->purpose >= CIRCUIT_PURPOSE_C_INTRODUCING &&
   1503                circ->purpose <= CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED) ||
   1504                circ->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
   1505          log_info(LD_CIRC,
   1506                    "Closing circuit %"PRIu32
   1507                    " that has been unused for %ld msec.",
   1508                   TO_ORIGIN_CIRCUIT(circ)->global_identifier,
   1509                   tv_mdiff(&circ->timestamp_began, &now));
   1510          tor_trace(TR_SUBSYS(circuit), TR_EV(idle_timeout),
   1511                    TO_ORIGIN_CIRCUIT(circ));
   1512          circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
   1513        } else if (!TO_ORIGIN_CIRCUIT(circ)->is_ancient) {
   1514          /* Server-side rend joined circuits can end up really old, because
   1515           * they are reused by clients for longer than normal. The client
   1516           * controls their lifespan. (They never become dirty, because
   1517           * connection_exit_begin_conn() never marks anything as dirty.)
   1518           * Similarly, server-side intro circuits last a long time. */
   1519          if (circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED &&
   1520              circ->purpose != CIRCUIT_PURPOSE_S_INTRO) {
   1521            log_notice(LD_CIRC,
   1522                       "Ancient non-dirty circuit %d is still around after "
   1523                       "%ld milliseconds. Purpose: %d (%s)",
   1524                       TO_ORIGIN_CIRCUIT(circ)->global_identifier,
   1525                       tv_mdiff(&circ->timestamp_began, &now),
   1526                       circ->purpose,
   1527                       circuit_purpose_to_string(circ->purpose));
   1528            TO_ORIGIN_CIRCUIT(circ)->is_ancient = 1;
   1529          }
   1530        }
   1531      }
   1532    }
   1533  } SMARTLIST_FOREACH_END(circ);
   1534 }
   1535 
   1536 /** How long do we wait before killing circuits with the properties
   1537 * described below?
   1538 *
   1539 * Probably we could choose a number here as low as 5 to 10 seconds,
   1540 * since these circs are used for begindir, and a) generally you either
   1541 * ask another begindir question right after or you don't for a long time,
   1542 * b) clients at least through 0.2.1.x choose from the whole set of
   1543 * directory mirrors at each choice, and c) re-establishing a one-hop
   1544 * circuit via create-fast is a light operation assuming the TLS conn is
   1545 * still there.
   1546 *
   1547 * I expect "b" to go away one day when we move to using directory
   1548 * guards, but I think "a" and "c" are good enough reasons that a low
   1549 * number is safe even then.
   1550 */
   1551 #define IDLE_ONE_HOP_CIRC_TIMEOUT 60
   1552 
   1553 /** Find each non-origin circuit that has been unused for too long,
   1554 * has no streams on it, came from a client, and ends here: mark it
   1555 * for close.
   1556 */
   1557 void
   1558 circuit_expire_old_circuits_serverside(time_t now)
   1559 {
   1560  or_circuit_t *or_circ;
   1561  time_t cutoff = now - IDLE_ONE_HOP_CIRC_TIMEOUT;
   1562 
   1563  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1564    if (circ->marked_for_close || CIRCUIT_IS_ORIGIN(circ))
   1565      continue;
   1566    or_circ = TO_OR_CIRCUIT(circ);
   1567    /* If the circuit has been idle for too long, and there are no streams
   1568     * on it, and it ends here, and it used a create_fast, mark it for close.
   1569     *
   1570     * Also if there is a rend_splice on it, it's a single onion service
   1571     * circuit and we should not close it.
   1572     */
   1573    if (or_circ->p_chan && channel_is_client(or_circ->p_chan) &&
   1574        !circ->n_chan &&
   1575        !or_circ->n_streams && !or_circ->resolving_streams &&
   1576        !or_circ->rend_splice &&
   1577        channel_when_last_xmit(or_circ->p_chan) <= cutoff) {
   1578      log_info(LD_CIRC, "Closing circ_id %u (empty %d secs ago)",
   1579               (unsigned)or_circ->p_circ_id,
   1580               (int)(now - channel_when_last_xmit(or_circ->p_chan)));
   1581      circuit_mark_for_close(circ, END_CIRC_REASON_FINISHED);
   1582    }
   1583  }
   1584  SMARTLIST_FOREACH_END(circ);
   1585 }
   1586 
   1587 /** Number of testing circuits we want open before testing our bandwidth. */
   1588 #define NUM_PARALLEL_TESTING_CIRCS 4
   1589 
   1590 /** True iff we've ever had enough testing circuits open to test our
   1591 * bandwidth. */
   1592 static int have_performed_bandwidth_test = 0;
   1593 
   1594 /** Reset have_performed_bandwidth_test, so we'll start building
   1595 * testing circuits again so we can exercise our bandwidth. */
   1596 void
   1597 reset_bandwidth_test(void)
   1598 {
   1599  have_performed_bandwidth_test = 0;
   1600 }
   1601 
   1602 /** Return 1 if we've already exercised our bandwidth, or if we
   1603 * have fewer than NUM_PARALLEL_TESTING_CIRCS testing circuits
   1604 * established or on the way. Else return 0.
   1605 */
   1606 int
   1607 circuit_enough_testing_circs(void)
   1608 {
   1609  int num = 0;
   1610 
   1611  if (have_performed_bandwidth_test)
   1612    return 1;
   1613 
   1614  SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
   1615    if (!circ->marked_for_close && CIRCUIT_IS_ORIGIN(circ) &&
   1616        circ->purpose == CIRCUIT_PURPOSE_TESTING &&
   1617        circ->state == CIRCUIT_STATE_OPEN)
   1618      num++;
   1619  }
   1620  SMARTLIST_FOREACH_END(circ);
   1621  return num >= NUM_PARALLEL_TESTING_CIRCS;
   1622 }
   1623 
   1624 /** A testing circuit has completed. Take whatever stats we want.
   1625 * Noticing reachability is taken care of in onionskin_answer(),
   1626 * so there's no need to record anything here. But if we still want
   1627 * to do the bandwidth test, and we now have enough testing circuits
   1628 * open, do it.
   1629 */
   1630 static void
   1631 circuit_testing_opened(origin_circuit_t *circ)
   1632 {
   1633  if (have_performed_bandwidth_test ||
   1634      !router_orport_seems_reachable(get_options(), AF_INET)) {
   1635    /* either we've already done everything we want with testing circuits,
   1636     * OR this IPv4 testing circuit became open due to a fluke, e.g. we picked
   1637     * a last hop where we already had the connection open due to a
   1638     * outgoing local circuit, OR this is an IPv6 self-test circuit, not
   1639     * a bandwidth test circuit. */
   1640    circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_AT_ORIGIN);
   1641  } else if (circuit_enough_testing_circs()) {
   1642    router_perform_bandwidth_test(NUM_PARALLEL_TESTING_CIRCS, time(NULL));
   1643    have_performed_bandwidth_test = 1;
   1644  } else {
   1645    router_do_reachability_checks();
   1646  }
   1647 }
   1648 
   1649 /** A testing circuit has failed to build. Take whatever stats we want. */
   1650 static void
   1651 circuit_testing_failed(origin_circuit_t *circ, int at_last_hop)
   1652 {
   1653  const or_options_t *options = get_options();
   1654  if (server_mode(options) &&
   1655      router_all_orports_seem_reachable(options))
   1656    return;
   1657 
   1658  log_info(LD_GENERAL,
   1659           "Our testing circuit (to see if your ORPort is reachable) "
   1660           "has failed. I'll try again later.");
   1661 
   1662  /* These aren't used yet. */
   1663  (void)circ;
   1664  (void)at_last_hop;
   1665 }
   1666 
   1667 /** The circuit <b>circ</b> has just become open. Take the next
   1668 * step: for rendezvous circuits, we pass circ to the appropriate
   1669 * function in rendclient or rendservice. For general circuits, we
   1670 * call connection_ap_attach_pending, which looks for pending streams
   1671 * that could use circ.
   1672 */
   1673 void
   1674 circuit_has_opened(origin_circuit_t *circ)
   1675 {
   1676  tor_trace(TR_SUBSYS(circuit), TR_EV(opened), circ);
   1677  circuit_event_status(circ, CIRC_EVENT_BUILT, 0);
   1678 
   1679  /* Remember that this circuit has finished building. Now if we start
   1680   * it building again later (e.g. by extending it), we will know not
   1681   * to consider its build time. */
   1682  circ->has_opened = 1;
   1683 
   1684  switch (TO_CIRCUIT(circ)->purpose) {
   1685    case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
   1686      hs_client_circuit_has_opened(circ);
   1687      /* Start building an intro circ if we don't have one yet. */
   1688      connection_ap_attach_pending(1);
   1689      /* This isn't a call to circuit_try_attaching_streams because a
   1690       * circuit in _C_ESTABLISH_REND state isn't connected to its
   1691       * hidden service yet, thus we can't attach streams to it yet,
   1692       * thus circuit_try_attaching_streams would always clear the
   1693       * circuit's isolation state.  circuit_try_attaching_streams is
   1694       * called later, when the rend circ enters _C_REND_JOINED
   1695       * state. */
   1696      break;
   1697    case CIRCUIT_PURPOSE_C_INTRODUCING:
   1698      hs_client_circuit_has_opened(circ);
   1699      break;
   1700    case CIRCUIT_PURPOSE_CONFLUX_UNLINKED:
   1701      conflux_circuit_has_opened(circ);
   1702      break;
   1703    case CIRCUIT_PURPOSE_C_GENERAL:
   1704      circuit_try_attaching_streams(circ);
   1705      break;
   1706    case CIRCUIT_PURPOSE_C_HSDIR_GET:
   1707    case CIRCUIT_PURPOSE_S_HSDIR_POST:
   1708      /* Tell any AP connections that have been waiting for a new
   1709       * circuit that one is ready. */
   1710      circuit_try_attaching_streams(circ);
   1711      break;
   1712    case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
   1713      /* at the service, waiting for introductions */
   1714      hs_service_circuit_has_opened(circ);
   1715      break;
   1716    case CIRCUIT_PURPOSE_S_CONNECT_REND:
   1717      /* at the service, connecting to rend point */
   1718      hs_service_circuit_has_opened(circ);
   1719      break;
   1720    case CIRCUIT_PURPOSE_TESTING:
   1721      circuit_testing_opened(circ);
   1722      break;
   1723    /* default:
   1724     * This won't happen in normal operation, but might happen if the
   1725     * controller did it. Just let it slide. */
   1726  }
   1727 }
   1728 
   1729 /** If the stream-isolation state of <b>circ</b> can be cleared, clear
   1730 * it.  Return non-zero iff <b>circ</b>'s isolation state was cleared. */
   1731 static int
   1732 circuit_try_clearing_isolation_state(origin_circuit_t *circ)
   1733 {
   1734  if (/* The circuit may have become non-open if it was cannibalized.*/
   1735      circ->base_.state == CIRCUIT_STATE_OPEN &&
   1736      /* If !isolation_values_set, there is nothing to clear. */
   1737      circ->isolation_values_set &&
   1738      /* It's not legal to clear a circuit's isolation info if it's ever had
   1739       * streams attached */
   1740      !circ->isolation_any_streams_attached) {
   1741    /* If we have any isolation information set on this circuit, and
   1742     * we didn't manage to attach any streams to it, then we can
   1743     * and should clear it and try again. */
   1744    circuit_clear_isolation(circ);
   1745    return 1;
   1746  } else {
   1747    return 0;
   1748  }
   1749 }
   1750 
   1751 /** Called when a circuit becomes ready for streams to be attached to
   1752 * it. */
   1753 void
   1754 circuit_try_attaching_streams(origin_circuit_t *circ)
   1755 {
   1756  /* Attach streams to this circuit if we can. */
   1757  connection_ap_attach_pending(1);
   1758 
   1759  /* The call to circuit_try_clearing_isolation_state here will do
   1760   * nothing and return 0 if we didn't attach any streams to circ
   1761   * above. */
   1762  if (circuit_try_clearing_isolation_state(circ)) {
   1763    /* Maybe *now* we can attach some streams to this circuit. */
   1764    connection_ap_attach_pending(1);
   1765  }
   1766 }
   1767 
   1768 /** Called whenever a circuit could not be successfully built.
   1769 */
   1770 void
   1771 circuit_build_failed(origin_circuit_t *circ)
   1772 {
   1773  channel_t *n_chan = NULL;
   1774  /* we should examine circ and see if it failed because of
   1775   * the last hop or an earlier hop. then use this info below.
   1776   */
   1777  int failed_at_last_hop = 0;
   1778 
   1779  /* First, check to see if this was a path failure, rather than build
   1780   * failure.
   1781   *
   1782   * Note that we deliberately use circuit_get_cpath_len() (and not
   1783   * circuit_get_cpath_opened_len()) because we only want to ensure
   1784   * that a full path is *chosen*. This is different than a full path
   1785   * being *built*. We only want to count *build* failures below.
   1786   *
   1787   * Path selection failures can happen spuriously for a number
   1788   * of reasons (such as aggressive/invalid user-specified path
   1789   * restrictions in the torrc, insufficient microdescriptors, and
   1790   * non-user reasons like exitpolicy issues), and so should not be
   1791   * counted as failures below.
   1792   */
   1793  if (circuit_get_cpath_len(circ) < circ->build_state->desired_path_len) {
   1794    static ratelim_t pathfail_limit = RATELIM_INIT(3600);
   1795    log_fn_ratelim(&pathfail_limit, LOG_NOTICE, LD_CIRC,
   1796             "Our circuit %u (id: %" PRIu32 ") died due to an invalid "
   1797             "selected path, purpose %s. This may be a torrc "
   1798             "configuration issue, or a bug.",
   1799              TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
   1800              circuit_purpose_to_string(TO_CIRCUIT(circ)->purpose));
   1801 
   1802    /* If the path failed on an RP, retry it. */
   1803    if (TO_CIRCUIT(circ)->purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
   1804      hs_metrics_failed_rdv(&circ->hs_ident->identity_pk,
   1805                            HS_METRICS_ERR_RDV_PATH);
   1806      hs_circ_retry_service_rendezvous_point(circ);
   1807    }
   1808 
   1809    /* In all other cases, just bail. The rest is just failure accounting
   1810     * that we don't want to do */
   1811    return;
   1812  }
   1813 
   1814  /* If the last hop isn't open, and the second-to-last is, we failed
   1815   * at the last hop. */
   1816  if (circ->cpath &&
   1817      circ->cpath->prev->state != CPATH_STATE_OPEN &&
   1818      circ->cpath->prev->prev->state == CPATH_STATE_OPEN) {
   1819    failed_at_last_hop = 1;
   1820  }
   1821 
   1822  /* Check if we failed at first hop */
   1823  if (circ->cpath &&
   1824      circ->cpath->state != CPATH_STATE_OPEN &&
   1825      ! circ->base_.received_destroy) {
   1826    /* We failed at the first hop for some reason other than a DESTROY cell.
   1827     * If there's an OR connection to blame, blame it. Also, avoid this relay
   1828     * for a while, and fail any one-hop directory fetches destined for it. */
   1829    const char *n_chan_ident = circ->cpath->extend_info->identity_digest;
   1830    tor_assert(n_chan_ident);
   1831    int already_marked = 0;
   1832    if (circ->base_.n_chan) {
   1833      n_chan = circ->base_.n_chan;
   1834 
   1835      if (n_chan->is_bad_for_new_circs) {
   1836        /* We only want to blame this router when a fresh healthy
   1837         * connection fails. So don't mark this router as newly failed,
   1838         * since maybe this was just an old circuit attempt that's
   1839         * finally timing out now. Also, there's no need to blow away
   1840         * circuits/streams/etc, since the failure of an unhealthy conn
   1841         * doesn't tell us much about whether a healthy conn would
   1842         * succeed. */
   1843        already_marked = 1;
   1844      }
   1845      log_info(LD_OR,
   1846               "Our circuit %u (id: %" PRIu32 ") failed to get a response "
   1847               "from the first hop (%s). I'm going to try to rotate to a "
   1848               "better connection.",
   1849               TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier,
   1850               channel_describe_peer(n_chan));
   1851      n_chan->is_bad_for_new_circs = 1;
   1852    } else {
   1853      log_info(LD_OR,
   1854               "Our circuit %u (id: %" PRIu32 ") died before the first hop "
   1855               "with no connection",
   1856               TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier);
   1857    }
   1858    if (!already_marked) {
   1859      /*
   1860       * If we have guard state (new guard API) and our path selection
   1861       * code actually chose a full path, then blame the failure of this
   1862       * circuit on the guard.
   1863       */
   1864      if (circ->guard_state)
   1865        entry_guard_failed(&circ->guard_state);
   1866      /* if there are any one-hop streams waiting on this circuit, fail
   1867       * them now so they can retry elsewhere. */
   1868      connection_ap_fail_onehop(n_chan_ident, circ->build_state);
   1869    }
   1870  }
   1871 
   1872  switch (circ->base_.purpose) {
   1873    case CIRCUIT_PURPOSE_C_HSDIR_GET:
   1874    case CIRCUIT_PURPOSE_S_HSDIR_POST:
   1875    case CIRCUIT_PURPOSE_C_GENERAL:
   1876      /* If we never built the circuit, note it as a failure. */
   1877      circuit_increment_failure_count();
   1878      if (failed_at_last_hop) {
   1879        /* Make sure any streams that demand our last hop as their exit
   1880         * know that it's unlikely to happen. */
   1881        circuit_discard_optional_exit_enclaves(circ->cpath->prev->extend_info);
   1882      }
   1883      break;
   1884    case CIRCUIT_PURPOSE_TESTING:
   1885      circuit_testing_failed(circ, failed_at_last_hop);
   1886      break;
   1887    case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
   1888      /* at the service, waiting for introductions */
   1889      if (circ->base_.state != CIRCUIT_STATE_OPEN) {
   1890        circuit_increment_failure_count();
   1891      }
   1892      /* no need to care here, because the service will rebuild intro
   1893       * points periodically. */
   1894      break;
   1895    case CIRCUIT_PURPOSE_C_INTRODUCING:
   1896      /* at the client, connecting to intro point */
   1897      /* Don't increment failure count, since the service may have picked
   1898       * the introduction point maliciously */
   1899      /* The client will pick a new intro point when this one dies, if
   1900       * the stream in question still cares. No need to act here. */
   1901      break;
   1902    case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
   1903      /* at the client, waiting for the service */
   1904      circuit_increment_failure_count();
   1905      /* the client will pick a new rend point when this one dies, if
   1906       * the stream in question still cares. No need to act here. */
   1907      break;
   1908    case CIRCUIT_PURPOSE_S_CONNECT_REND:
   1909      /* at the service, connecting to rend point */
   1910      /* Don't increment failure count, since the client may have picked
   1911       * the rendezvous point maliciously */
   1912      log_info(LD_REND,
   1913               "Couldn't connect to the client's chosen rend point %s "
   1914               "(%s hop failed).",
   1915               escaped(build_state_get_exit_nickname(circ->build_state)),
   1916               failed_at_last_hop?"last":"non-last");
   1917 
   1918      hs_metrics_failed_rdv(&circ->hs_ident->identity_pk,
   1919                            HS_METRICS_ERR_RDV_RP_CONN_FAILURE);
   1920      hs_circ_retry_service_rendezvous_point(circ);
   1921      break;
   1922    /* default:
   1923     * This won't happen in normal operation, but might happen if the
   1924     * controller did it. Just let it slide. */
   1925  }
   1926 }
   1927 
   1928 /** Number of consecutive failures so far; should only be touched by
   1929 * circuit_launch_new and circuit_*_failure_count.
   1930 */
   1931 static int n_circuit_failures = 0;
   1932 /** Before the last time we called circuit_reset_failure_count(), were
   1933 * there a lot of failures? */
   1934 static int did_circs_fail_last_period = 0;
   1935 
   1936 /** Don't retry launching a new circuit if we try this many times with no
   1937 * success. */
   1938 #define MAX_CIRCUIT_FAILURES 5
   1939 
   1940 /** Launch a new circuit; see circuit_launch_by_extend_info() for
   1941 * details on arguments. */
   1942 origin_circuit_t *
   1943 circuit_launch(uint8_t purpose, int flags)
   1944 {
   1945  return circuit_launch_by_extend_info(purpose, NULL, flags);
   1946 }
   1947 
   1948 /* Do we have enough descriptors to build paths?
   1949 * If need_exit is true, return 1 if we can build exit paths.
   1950 * (We need at least one Exit in the consensus to build exit paths.)
   1951 * If need_exit is false, return 1 if we can build internal paths.
   1952 */
   1953 static int
   1954 have_enough_path_info(int need_exit)
   1955 {
   1956  if (need_exit)
   1957    return router_have_consensus_path() == CONSENSUS_PATH_EXIT;
   1958  else
   1959    return router_have_consensus_path() != CONSENSUS_PATH_UNKNOWN;
   1960 }
   1961 
   1962 /**
   1963 * Tell us if a circuit is a hidden service circuit.
   1964 */
   1965 int
   1966 circuit_purpose_is_hidden_service(uint8_t purpose)
   1967 {
   1968  /* HS Vanguard purpose. */
   1969  if (circuit_purpose_is_hs_vanguards(purpose)) {
   1970    return 1;
   1971  }
   1972 
   1973  /* Client-side purpose */
   1974  if (circuit_purpose_is_hs_client(purpose)) {
   1975    return 1;
   1976  }
   1977 
   1978  /* Service-side purpose */
   1979  if (circuit_purpose_is_hs_service(purpose)) {
   1980    return 1;
   1981  }
   1982 
   1983  return 0;
   1984 }
   1985 
   1986 /** Return true iff the given circuit is an HS client circuit. */
   1987 bool
   1988 circuit_purpose_is_hs_client(const uint8_t purpose)
   1989 {
   1990  return (purpose >= CIRCUIT_PURPOSE_C_HS_MIN_ &&
   1991          purpose <= CIRCUIT_PURPOSE_C_HS_MAX_);
   1992 }
   1993 
   1994 /** Return true iff the given circuit is an HS service circuit. */
   1995 bool
   1996 circuit_purpose_is_hs_service(const uint8_t purpose)
   1997 {
   1998  return (purpose >= CIRCUIT_PURPOSE_S_HS_MIN_ &&
   1999          purpose <= CIRCUIT_PURPOSE_S_HS_MAX_);
   2000 }
   2001 
   2002 /** Return true iff the given circuit is an HS Vanguards circuit. */
   2003 bool
   2004 circuit_purpose_is_hs_vanguards(const uint8_t purpose)
   2005 {
   2006  return (purpose == CIRCUIT_PURPOSE_HS_VANGUARDS);
   2007 }
   2008 
   2009 /** Return true iff the given circuit is an HS v3 circuit. */
   2010 bool
   2011 circuit_is_hs_v3(const circuit_t *circ)
   2012 {
   2013  return (CIRCUIT_IS_ORIGIN(circ) &&
   2014          (CONST_TO_ORIGIN_CIRCUIT(circ)->hs_ident != NULL));
   2015 }
   2016 
   2017 /**
   2018 * Return true if this circuit purpose should use vanguards
   2019 * or pinned Layer2 or Layer3 guards.
   2020 *
   2021 * This function takes both the circuit purpose and the
   2022 * torrc options for pinned middles/vanguards into account
   2023 * (ie: the circuit must be a hidden service circuit and
   2024 * vanguards/pinned middles must be enabled for it to return
   2025 * true).
   2026 */
   2027 int
   2028 circuit_should_use_vanguards(uint8_t purpose)
   2029 {
   2030  /* All hidden service circuits use either vanguards or
   2031   * vanguards-lite. */
   2032  if (circuit_purpose_is_hidden_service(purpose))
   2033    return 1;
   2034 
   2035  /* Everything else is a normal circuit */
   2036  return 0;
   2037 }
   2038 
   2039 /**
   2040 * Return true for the set of conditions for which it is OK to use
   2041 * a cannibalized circuit.
   2042 *
   2043 * Don't cannibalize for onehops, or certain purposes.
   2044 */
   2045 static int
   2046 circuit_should_cannibalize_to_build(uint8_t purpose_to_build,
   2047                                    int has_extend_info,
   2048                                    int onehop_tunnel)
   2049 {
   2050 
   2051  /* Do not try to cannibalize if this is a one hop circuit. */
   2052  if (onehop_tunnel) {
   2053    return 0;
   2054  }
   2055 
   2056  /* Don't try to cannibalize for general purpose circuits that do not
   2057   * specify a custom exit. */
   2058  if (purpose_to_build == CIRCUIT_PURPOSE_C_GENERAL && !has_extend_info) {
   2059    return 0;
   2060  }
   2061 
   2062  /* Don't cannibalize for testing circuits. We want to see if they
   2063   * complete normally. Also don't cannibalize for vanguard-purpose
   2064   * circuits, since those are specially pre-built for later
   2065   * cannibalization by the actual specific circuit types that need
   2066   * vanguards.
   2067   */
   2068  if (purpose_to_build == CIRCUIT_PURPOSE_TESTING ||
   2069      purpose_to_build == CIRCUIT_PURPOSE_HS_VANGUARDS) {
   2070    return 0;
   2071  }
   2072 
   2073  /* The server-side intro circ is not cannibalized because it only
   2074   * needs a 3 hop circuit. It is also long-lived, so it is more
   2075   * important that it have lower latency than get built fast.
   2076   */
   2077  if (purpose_to_build == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO) {
   2078    return 0;
   2079  }
   2080 
   2081  /* Do not cannibalize for conflux circuits */
   2082  if (purpose_to_build == CIRCUIT_PURPOSE_CONFLUX_UNLINKED) {
   2083    return 0;
   2084  }
   2085 
   2086  return 1;
   2087 }
   2088 
   2089 /** Launch a new circuit with purpose <b>purpose</b> and exit node
   2090 * <b>extend_info</b> (or NULL to select a random exit node).
   2091 *
   2092 * If flags contains:
   2093 *  - CIRCLAUNCH_ONEHOP_TUNNEL: the circuit will have only one hop;
   2094 *  - CIRCLAUNCH_NEED_UPTIME: choose routers with high uptime;
   2095 *  - CIRCLAUNCH_NEED_CAPACITY: choose routers with high bandwidth;
   2096 *  - CIRCLAUNCH_IS_IPV6_SELFTEST: the second-last hop must support IPv6
   2097 *                                 extends;
   2098 *  - CIRCLAUNCH_IS_INTERNAL: the last hop need not be an exit node;
   2099 *  - CIRCLAUNCH_IS_V3_RP: the last hop must support v3 onion service
   2100 *                         rendezvous.
   2101 *
   2102 * Return the newly allocated circuit on success, or NULL on failure. */
   2103 origin_circuit_t *
   2104 circuit_launch_by_extend_info(uint8_t purpose,
   2105                              extend_info_t *extend_info,
   2106                              int flags)
   2107 {
   2108  origin_circuit_t *circ;
   2109  int onehop_tunnel = (flags & CIRCLAUNCH_ONEHOP_TUNNEL) != 0;
   2110  int have_path = have_enough_path_info(! (flags & CIRCLAUNCH_IS_INTERNAL) );
   2111 
   2112  /* Keep some stats about our attempts to launch HS rendezvous circuits */
   2113  if (purpose == CIRCUIT_PURPOSE_S_CONNECT_REND) {
   2114    hs_stats_note_service_rendezvous_launch();
   2115  }
   2116 
   2117  if (!onehop_tunnel && (!router_have_minimum_dir_info() || !have_path)) {
   2118    log_debug(LD_CIRC,"Haven't %s yet; canceling "
   2119              "circuit launch.",
   2120              !router_have_minimum_dir_info() ?
   2121              "fetched enough directory info" :
   2122              "received a consensus with exits");
   2123    return NULL;
   2124  }
   2125 
   2126  /* If we can/should cannibalize another circuit to build this one,
   2127   * then do so. */
   2128  if (circuit_should_cannibalize_to_build(purpose,
   2129                                          extend_info != NULL,
   2130                                          onehop_tunnel)) {
   2131    /* see if there are appropriate circs available to cannibalize. */
   2132    /* XXX if we're planning to add a hop, perhaps we want to look for
   2133     * internal circs rather than exit circs? -RD */
   2134    circ = circuit_find_to_cannibalize(purpose, extend_info, flags);
   2135    if (circ) {
   2136      uint8_t old_purpose = circ->base_.purpose;
   2137      struct timeval old_timestamp_began = circ->base_.timestamp_began;
   2138 
   2139      log_info(LD_CIRC, "Cannibalizing circ %u (id: %" PRIu32 ") for "
   2140                        "purpose %d (%s)",
   2141               TO_CIRCUIT(circ)->n_circ_id, circ->global_identifier, purpose,
   2142               circuit_purpose_to_string(purpose));
   2143 
   2144      if ((purpose == CIRCUIT_PURPOSE_S_CONNECT_REND ||
   2145           purpose == CIRCUIT_PURPOSE_C_INTRODUCING) &&
   2146          circ->path_state == PATH_STATE_BUILD_SUCCEEDED) {
   2147        /* Path bias: Cannibalized rends pre-emptively count as a
   2148         * successfully built but unused closed circuit. We don't
   2149         * wait until the extend (or the close) because the rend
   2150         * point could be malicious.
   2151         *
   2152         * Same deal goes for client side introductions. Clients
   2153         * can be manipulated to connect repeatedly to them
   2154         * (especially web clients).
   2155         *
   2156         * If we decide to probe the initial portion of these circs,
   2157         * (up to the adversary's final hop), we need to remove this,
   2158         * or somehow mark the circuit with a special path state.
   2159         */
   2160 
   2161        /* This must be called before the purpose change */
   2162        pathbias_check_close(circ, END_CIRC_REASON_FINISHED);
   2163      }
   2164 
   2165      circuit_change_purpose(TO_CIRCUIT(circ), purpose);
   2166      /* Reset the start date of this circ, else expire_building
   2167       * will see it and think it's been trying to build since it
   2168       * began.
   2169       *
   2170       * Technically, the code should reset this when the
   2171       * create cell is finally sent, but we're close enough
   2172       * here. */
   2173      tor_gettimeofday(&circ->base_.timestamp_began);
   2174 
   2175      control_event_circuit_cannibalized(circ, old_purpose,
   2176                                         &old_timestamp_began);
   2177 
   2178      switch (purpose) {
   2179        case CIRCUIT_PURPOSE_C_ESTABLISH_REND:
   2180          /* it's ready right now */
   2181          break;
   2182        case CIRCUIT_PURPOSE_C_INTRODUCING:
   2183        case CIRCUIT_PURPOSE_S_CONNECT_REND:
   2184        case CIRCUIT_PURPOSE_C_GENERAL:
   2185        case CIRCUIT_PURPOSE_S_HSDIR_POST:
   2186        case CIRCUIT_PURPOSE_C_HSDIR_GET:
   2187        case CIRCUIT_PURPOSE_S_ESTABLISH_INTRO:
   2188          /* need to add a new hop */
   2189          tor_assert(extend_info);
   2190          if (circuit_extend_to_new_exit(circ, extend_info) < 0)
   2191            return NULL;
   2192          break;
   2193        default:
   2194          log_warn(LD_BUG,
   2195                   "unexpected purpose %d when cannibalizing a circ.",
   2196                   purpose);
   2197          tor_fragile_assert();
   2198          return NULL;
   2199      }
   2200 
   2201      tor_trace(TR_SUBSYS(circuit), TR_EV(cannibalized), circ);
   2202      return circ;
   2203    }
   2204  }
   2205 
   2206  if (did_circs_fail_last_period &&
   2207      n_circuit_failures > MAX_CIRCUIT_FAILURES) {
   2208    /* too many failed circs in a row. don't try. */
   2209 //    log_fn(LOG_INFO,"%d failures so far, not trying.",n_circuit_failures);
   2210    return NULL;
   2211  }
   2212 
   2213  /* try a circ. if it fails, circuit_mark_for_close will increment
   2214   * n_circuit_failures */
   2215  return circuit_establish_circuit(purpose, extend_info, flags);
   2216 }
   2217 
   2218 /** Record another failure at opening a general circuit. When we have
   2219 * too many, we'll stop trying for the remainder of this minute.
   2220 */
   2221 static void
   2222 circuit_increment_failure_count(void)
   2223 {
   2224  ++n_circuit_failures;
   2225  log_debug(LD_CIRC,"n_circuit_failures now %d.",n_circuit_failures);
   2226 }
   2227 
   2228 /** Reset the failure count for opening general circuits. This means
   2229 * we will try MAX_CIRCUIT_FAILURES times more (if necessary) before
   2230 * stopping again.
   2231 */
   2232 void
   2233 circuit_reset_failure_count(int timeout)
   2234 {
   2235  if (timeout && n_circuit_failures > MAX_CIRCUIT_FAILURES)
   2236    did_circs_fail_last_period = 1;
   2237  else
   2238    did_circs_fail_last_period = 0;
   2239  n_circuit_failures = 0;
   2240 }
   2241 
   2242 /** Find an open circ that we're happy to use for <b>conn</b> and return 1. If
   2243 * there isn't one, and there isn't one on the way, launch one and return
   2244 * 0. If it will never work, return -1.
   2245 *
   2246 * Write the found or in-progress or launched circ into *circp.
   2247 */
   2248 static int
   2249 circuit_get_open_circ_or_launch(entry_connection_t *conn,
   2250                                uint8_t desired_circuit_purpose,
   2251                                origin_circuit_t **circp)
   2252 {
   2253  origin_circuit_t *circ;
   2254  int check_exit_policy;
   2255  int need_uptime, need_internal;
   2256  int want_onehop;
   2257  const or_options_t *options = get_options();
   2258 
   2259  tor_assert(conn);
   2260  tor_assert(circp);
   2261  if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
   2262    connection_t *c = ENTRY_TO_CONN(conn);
   2263    log_err(LD_BUG, "Connection state mismatch: wanted "
   2264            "AP_CONN_STATE_CIRCUIT_WAIT, but got %d (%s)",
   2265            c->state, conn_state_to_string(c->type, c->state));
   2266  }
   2267  tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_CIRCUIT_WAIT);
   2268 
   2269  /* Will the exit policy of the exit node apply to this stream? */
   2270  check_exit_policy =
   2271      conn->socks_request->command == SOCKS_COMMAND_CONNECT &&
   2272      !conn->use_begindir &&
   2273      !connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn));
   2274 
   2275  /* Does this connection want a one-hop circuit? */
   2276  want_onehop = conn->want_onehop;
   2277 
   2278  /* Do we need a high-uptime circuit? */
   2279  need_uptime = !conn->want_onehop && !conn->use_begindir &&
   2280                smartlist_contains_int_as_string(options->LongLivedPorts,
   2281                                          conn->socks_request->port);
   2282 
   2283  /* Do we need an "internal" circuit? */
   2284  if (desired_circuit_purpose != CIRCUIT_PURPOSE_C_GENERAL)
   2285    need_internal = 1;
   2286  else if (conn->use_begindir || conn->want_onehop)
   2287    need_internal = 1;
   2288  else
   2289    need_internal = 0;
   2290 
   2291  /* We now know what kind of circuit we need.  See if there is an
   2292   * open circuit that we can use for this stream */
   2293  circ = circuit_get_best(conn, 1 /* Insist on open circuits */,
   2294                          desired_circuit_purpose,
   2295                          need_uptime, need_internal);
   2296 
   2297  if (circ) {
   2298    /* We got a circuit that will work for this stream!  We can return it. */
   2299    *circp = circ;
   2300    return 1; /* we're happy */
   2301  }
   2302 
   2303  /* Okay, there's no circuit open that will work for this stream. Let's
   2304   * see if there's an in-progress circuit or if we have to launch one */
   2305 
   2306  /* Do we know enough directory info to build circuits at all? */
   2307  int have_path = have_enough_path_info(!need_internal);
   2308 
   2309  if (!want_onehop && (!router_have_minimum_dir_info() || !have_path)) {
   2310    /* If we don't have enough directory information, we can't build
   2311     * multihop circuits.
   2312     */
   2313    if (!connection_get_by_type(CONN_TYPE_DIR)) {
   2314      int severity = LOG_NOTICE;
   2315      /* Retry some stuff that might help the connection work. */
   2316      /* If we are configured with EntryNodes or UseBridges */
   2317      if (entry_list_is_constrained(options)) {
   2318        /* Retry all our guards / bridges.
   2319         * guards_retry_optimistic() always returns true here. */
   2320        int rv = guards_retry_optimistic(options);
   2321        tor_assert_nonfatal_once(rv);
   2322        log_fn(severity, LD_APP|LD_DIR,
   2323               "Application request when we haven't %s. "
   2324               "Optimistically trying known %s again.",
   2325               !router_have_minimum_dir_info() ?
   2326               "used client functionality lately" :
   2327               "received a consensus with exits",
   2328               options->UseBridges ? "bridges" : "entrynodes");
   2329      } else {
   2330        /* Getting directory documents doesn't help much if we have a limited
   2331         * number of guards */
   2332        tor_assert_nonfatal(!options->UseBridges);
   2333        tor_assert_nonfatal(!options->EntryNodes);
   2334        /* Retry our directory fetches, so we have a fresh set of guard info */
   2335        log_fn(severity, LD_APP|LD_DIR,
   2336               "Application request when we haven't %s. "
   2337               "Optimistically trying directory fetches again.",
   2338               !router_have_minimum_dir_info() ?
   2339               "used client functionality lately" :
   2340               "received a consensus with exits");
   2341        routerlist_retry_directory_downloads(time(NULL));
   2342      }
   2343    }
   2344    /* Since we didn't have enough directory info, we can't attach now.  The
   2345     * stream will be dealt with when router_have_minimum_dir_info becomes 1,
   2346     * or when all directory attempts fail and directory_all_unreachable()
   2347     * kills it.
   2348     */
   2349    return 0;
   2350  }
   2351 
   2352  /* Check whether the exit policy of the chosen exit, or the exit policies
   2353   * of _all_ nodes, would forbid this node. */
   2354  if (check_exit_policy) {
   2355    if (!conn->chosen_exit_name) {
   2356      struct in_addr in;
   2357      tor_addr_t addr, *addrp=NULL;
   2358      if (tor_inet_aton(conn->socks_request->address, &in)) {
   2359        tor_addr_from_in(&addr, &in);
   2360        addrp = &addr;
   2361      }
   2362      if (router_exit_policy_all_nodes_reject(addrp,
   2363                                              conn->socks_request->port,
   2364                                              need_uptime)) {
   2365        log_notice(LD_APP,
   2366                   "No Tor server allows exit to %s:%d. Rejecting.",
   2367                   safe_str_client(conn->socks_request->address),
   2368                   conn->socks_request->port);
   2369        return -1;
   2370      }
   2371    } else {
   2372      /* XXXX Duplicates checks in connection_ap_handshake_attach_circuit:
   2373       * refactor into a single function. */
   2374      const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
   2375      int opt = conn->chosen_exit_optional;
   2376      if (node && !connection_ap_can_use_exit(conn, node)) {
   2377        log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
   2378               "Requested exit point '%s' is excluded or "
   2379               "would refuse request. %s.",
   2380               conn->chosen_exit_name, opt ? "Trying others" : "Closing");
   2381        if (opt) {
   2382          conn->chosen_exit_optional = 0;
   2383          tor_free(conn->chosen_exit_name);
   2384          /* Try again. */
   2385          return circuit_get_open_circ_or_launch(conn,
   2386                                                 desired_circuit_purpose,
   2387                                                 circp);
   2388        }
   2389        return -1;
   2390      }
   2391    }
   2392  }
   2393 
   2394  /* Now, check whether there already a circuit on the way that could handle
   2395   * this stream. This check matches the one above, but this time we
   2396   * do not require that the circuit will work. */
   2397  circ = circuit_get_best(conn, 0 /* don't insist on open circuits */,
   2398                          desired_circuit_purpose,
   2399                          need_uptime, need_internal);
   2400  if (circ)
   2401    log_debug(LD_CIRC, "one on the way!");
   2402 
   2403  if (!circ) {
   2404    /* No open or in-progress circuit could handle this stream!  We
   2405     * will have to launch one!
   2406     */
   2407 
   2408    /* The chosen exit node, if there is one. */
   2409    extend_info_t *extend_info=NULL;
   2410    const int n_pending = count_pending_general_client_circuits();
   2411 
   2412    /* Do we have too many pending circuits? */
   2413    if (n_pending >= options->MaxClientCircuitsPending) {
   2414      static ratelim_t delay_limit = RATELIM_INIT(10*60);
   2415      char *m;
   2416      if ((m = rate_limit_log(&delay_limit, approx_time()))) {
   2417        log_notice(LD_APP, "We'd like to launch a circuit to handle a "
   2418                   "connection, but we already have %d general-purpose client "
   2419                   "circuits pending. Waiting until some finish.%s",
   2420                   n_pending, m);
   2421        tor_free(m);
   2422      }
   2423      return 0;
   2424    }
   2425 
   2426    /* If this is a hidden service trying to start an introduction point,
   2427     * handle that case. */
   2428    if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
   2429      const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
   2430      /* need to pick an intro point */
   2431      extend_info = hs_client_get_random_intro_from_edge(edge_conn);
   2432      if (!extend_info) {
   2433        log_info(LD_REND, "No intro points: re-fetching service descriptor.");
   2434        hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
   2435        connection_ap_mark_as_waiting_for_renddesc(conn);
   2436        return 0;
   2437      }
   2438      log_info(LD_REND,"Chose %s as intro point for service",
   2439               extend_info_describe(extend_info));
   2440    }
   2441 
   2442    /* If we have specified a particular exit node for our
   2443     * connection, then be sure to open a circuit to that exit node.
   2444     */
   2445    if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   2446        desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
   2447        desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET) {
   2448      if (conn->chosen_exit_name) {
   2449        const node_t *r;
   2450        int opt = conn->chosen_exit_optional;
   2451        r = node_get_by_nickname(conn->chosen_exit_name, 0);
   2452        if (r && node_has_preferred_descriptor(r, conn->want_onehop ? 1 : 0)) {
   2453          /* We might want to connect to an IPv6 bridge for loading
   2454             descriptors so we use the preferred address rather than
   2455             the primary. */
   2456          extend_info = extend_info_from_node(r, conn->want_onehop ? 1 : 0,
   2457                         desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL);
   2458          if (!extend_info) {
   2459            log_warn(LD_CIRC,"Could not make a one-hop connection to %s. "
   2460                     "Discarding this circuit.", conn->chosen_exit_name);
   2461            return -1;
   2462          }
   2463        } else  { /* ! (r && node_has_preferred_descriptor(...)) */
   2464          log_debug(LD_DIR, "considering %d, %s",
   2465                    want_onehop, conn->chosen_exit_name);
   2466          if (want_onehop && conn->chosen_exit_name[0] == '$') {
   2467            /* We're asking for a one-hop circuit to a router that
   2468             * we don't have a routerinfo about. Make up an extend_info. */
   2469            /* XXX prop220: we need to make chosen_exit_name able to
   2470             * encode both key formats. This is not absolutely critical
   2471             * since this is just for one-hop circuits, but we should
   2472             * still get it done */
   2473            char digest[DIGEST_LEN];
   2474            char *hexdigest = conn->chosen_exit_name+1;
   2475            tor_addr_t addr;
   2476            if (strlen(hexdigest) < HEX_DIGEST_LEN ||
   2477                base16_decode(digest,DIGEST_LEN,
   2478                              hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN) {
   2479              log_info(LD_DIR, "Broken exit digest on tunnel conn. Closing.");
   2480              return -1;
   2481            }
   2482            if (tor_addr_parse(&addr, conn->socks_request->address) < 0) {
   2483              log_info(LD_DIR, "Broken address %s on tunnel conn. Closing.",
   2484                       escaped_safe_str_client(conn->socks_request->address));
   2485              return -1;
   2486            }
   2487            /* XXXX prop220 add a workaround for ed25519 ID below*/
   2488            extend_info = extend_info_new(conn->chosen_exit_name+1,
   2489                                          digest,
   2490                                          NULL, /* Ed25519 ID */
   2491                                          NULL, /* onion keys */
   2492                                          &addr, conn->socks_request->port,
   2493                                          NULL,
   2494                                          false);
   2495          } else { /* ! (want_onehop && conn->chosen_exit_name[0] == '$') */
   2496            /* We will need an onion key for the router, and we
   2497             * don't have one. Refuse or relax requirements. */
   2498            log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
   2499                   "Requested exit point '%s' is not known. %s.",
   2500                   conn->chosen_exit_name, opt ? "Trying others" : "Closing");
   2501            if (opt) {
   2502              conn->chosen_exit_optional = 0;
   2503              tor_free(conn->chosen_exit_name);
   2504              /* Try again with no requested exit */
   2505              return circuit_get_open_circ_or_launch(conn,
   2506                                                     desired_circuit_purpose,
   2507                                                     circp);
   2508            }
   2509            return -1;
   2510          }
   2511        }
   2512      }
   2513    } /* Done checking for general circutis with chosen exits. */
   2514 
   2515    /* What purpose do we need to launch this circuit with? */
   2516    uint8_t new_circ_purpose;
   2517    if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
   2518      new_circ_purpose = CIRCUIT_PURPOSE_C_ESTABLISH_REND;
   2519    else if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT)
   2520      new_circ_purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
   2521    else
   2522      new_circ_purpose = desired_circuit_purpose;
   2523 
   2524    /* Determine what kind of a circuit to launch, and actually launch it. */
   2525    {
   2526      int flags = CIRCLAUNCH_NEED_CAPACITY;
   2527      if (want_onehop) flags |= CIRCLAUNCH_ONEHOP_TUNNEL;
   2528      if (need_uptime) flags |= CIRCLAUNCH_NEED_UPTIME;
   2529      if (need_internal) flags |= CIRCLAUNCH_IS_INTERNAL;
   2530 
   2531      /* If we are about to pick a v3 RP right now, make sure we pick a
   2532       * rendezvous point that supports the v3 protocol! */
   2533      if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_REND_JOINED &&
   2534          new_circ_purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
   2535          ENTRY_TO_EDGE_CONN(conn)->hs_ident) {
   2536        log_info(LD_GENERAL, "Getting rendezvous circuit to v3 service!");
   2537      }
   2538 
   2539      circ = circuit_launch_by_extend_info(new_circ_purpose, extend_info,
   2540                                           flags);
   2541    }
   2542 
   2543    extend_info_free(extend_info);
   2544 
   2545    /* Now trigger things that need to happen when we launch circuits */
   2546 
   2547    if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   2548        desired_circuit_purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
   2549        desired_circuit_purpose == CIRCUIT_PURPOSE_S_HSDIR_POST) {
   2550      /* We just caused a circuit to get built because of this stream.
   2551       * If this stream has caused a _lot_ of circuits to be built, that's
   2552       * a bad sign: we should tell the user. */
   2553      if (conn->num_circuits_launched < NUM_CIRCUITS_LAUNCHED_THRESHOLD &&
   2554          ++conn->num_circuits_launched == NUM_CIRCUITS_LAUNCHED_THRESHOLD)
   2555        log_info(LD_CIRC, "The application request to %s:%d has launched "
   2556                 "%d circuits without finding one it likes.",
   2557                 escaped_safe_str_client(conn->socks_request->address),
   2558                 conn->socks_request->port,
   2559                 conn->num_circuits_launched);
   2560    } else {
   2561      /* help predict this next time */
   2562      rep_hist_note_used_internal(time(NULL), need_uptime, 1);
   2563      if (circ) {
   2564        const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
   2565        if (edge_conn->hs_ident) {
   2566          circ->hs_ident =
   2567            hs_ident_circuit_new(&edge_conn->hs_ident->identity_pk);
   2568        }
   2569        if (desired_circuit_purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
   2570          if (hs_client_setup_intro_circ_auth_key(circ) < 0) {
   2571            return 0;
   2572          }
   2573        }
   2574        if (circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND &&
   2575            circ->base_.state == CIRCUIT_STATE_OPEN)
   2576          circuit_has_opened(circ);
   2577      }
   2578    }
   2579  } /* endif (!circ) */
   2580 
   2581  /* We either found a good circuit, or launched a new circuit, or failed to
   2582   * do so. Report success, and delay. */
   2583 
   2584  if (circ) {
   2585    /* Mark the circuit with the isolation fields for this connection.
   2586     * When the circuit arrives, we'll clear these flags: this is
   2587     * just some internal bookkeeping to make sure that we have
   2588     * launched enough circuits.
   2589     */
   2590    connection_edge_update_circuit_isolation(conn, circ, 0);
   2591  } else {
   2592    log_info(LD_APP,
   2593             "No safe circuit (purpose %d) ready for edge "
   2594             "connection; delaying.",
   2595             desired_circuit_purpose);
   2596  }
   2597  *circp = circ;
   2598  return 0;
   2599 }
   2600 
   2601 /** Return true iff <b>crypt_path</b> is one of the crypt_paths for
   2602 * <b>circ</b>.
   2603 *
   2604 * WARNING: This function only validates that the cpath is on the *current*
   2605 * circuit, for internal consistency checking. For codepaths involving streams,
   2606 * or cpaths or layer_hints that could be from a different circuit due to
   2607 * conflux, use edge_uses_cpath() or conflux_validate_source_hop() instead.
   2608 */
   2609 static int
   2610 cpath_is_on_circuit(origin_circuit_t *circ, crypt_path_t *crypt_path)
   2611 {
   2612  crypt_path_t *cpath, *cpath_next = NULL;
   2613  for (cpath = circ->cpath; cpath_next != circ->cpath; cpath = cpath_next) {
   2614    cpath_next = cpath->next;
   2615    if (crypt_path == cpath)
   2616      return 1;
   2617  }
   2618  return 0;
   2619 }
   2620 
   2621 /** Attach the AP stream <b>apconn</b> to circ's linked list of
   2622 * p_streams. Also set apconn's cpath_layer to <b>cpath</b>, or to the last
   2623 * hop in circ's cpath if <b>cpath</b> is NULL.
   2624 */
   2625 static void
   2626 link_apconn_to_circ(entry_connection_t *apconn, origin_circuit_t *circ,
   2627                    crypt_path_t *cpath)
   2628 {
   2629  const node_t *exitnode = NULL;
   2630 
   2631  /* add it into the linked list of streams on this circuit */
   2632  log_debug(LD_APP|LD_CIRC, "attaching new conn to circ. n_circ_id %u.",
   2633            (unsigned)circ->base_.n_circ_id);
   2634 
   2635  /* If this is the first stream on this circuit, tell circpad
   2636   * that streams are attached */
   2637  if (!circ->p_streams)
   2638    circpad_machine_event_circ_has_streams(circ);
   2639 
   2640  /* reset it, so we can measure circ timeouts */
   2641  ENTRY_TO_CONN(apconn)->timestamp_last_read_allowed = time(NULL);
   2642  ENTRY_TO_EDGE_CONN(apconn)->next_stream = circ->p_streams;
   2643  ENTRY_TO_EDGE_CONN(apconn)->on_circuit = TO_CIRCUIT(circ);
   2644  /* assert_connection_ok(conn, time(NULL)); */
   2645  circ->p_streams = ENTRY_TO_EDGE_CONN(apconn);
   2646  conflux_update_p_streams(circ, ENTRY_TO_EDGE_CONN(apconn));
   2647 
   2648  if (connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(apconn))) {
   2649    /* We are attaching a stream to a rendezvous circuit.  That means
   2650     * that an attempt to connect to a hidden service just
   2651     * succeeded.  Tell rendclient.c. */
   2652    hs_client_note_connection_attempt_succeeded(ENTRY_TO_EDGE_CONN(apconn));
   2653  }
   2654 
   2655  if (cpath) { /* we were given one; use it */
   2656    tor_assert(cpath_is_on_circuit(circ, cpath));
   2657  } else {
   2658    /* use the last hop in the circuit */
   2659    tor_assert(circ->cpath);
   2660    tor_assert(circ->cpath->prev);
   2661    tor_assert(circ->cpath->prev->state == CPATH_STATE_OPEN);
   2662    cpath = circ->cpath->prev;
   2663  }
   2664  ENTRY_TO_EDGE_CONN(apconn)->cpath_layer = cpath;
   2665 
   2666  circ->isolation_any_streams_attached = 1;
   2667  connection_edge_update_circuit_isolation(apconn, circ, 0);
   2668 
   2669  /* Compute the exitnode if possible, for logging below */
   2670  if (cpath->extend_info)
   2671    exitnode = node_get_by_id(cpath->extend_info->identity_digest);
   2672 
   2673  /* See if we can use optimistic data on this circuit */
   2674  // TODO-329-PURPOSE: Can conflux use optimistic data? Does
   2675  // anything use optimistic data? Does anything use this?
   2676  if (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   2677      circ->base_.purpose == CIRCUIT_PURPOSE_C_HSDIR_GET ||
   2678      circ->base_.purpose == CIRCUIT_PURPOSE_S_HSDIR_POST ||
   2679      circ->base_.purpose == CIRCUIT_PURPOSE_C_REND_JOINED)
   2680    apconn->may_use_optimistic_data = 1;
   2681  else
   2682    apconn->may_use_optimistic_data = 0;
   2683  log_info(LD_APP, "Looks like completed circuit to %s %s allow "
   2684           "optimistic data for connection to %s",
   2685           (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   2686            circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) ?
   2687             /* node_describe() does the right thing if exitnode is NULL */
   2688             safe_str_client(node_describe(exitnode)) :
   2689             "hidden service",
   2690           apconn->may_use_optimistic_data ? "does" : "doesn't",
   2691           safe_str_client(apconn->socks_request->address));
   2692 }
   2693 
   2694 /** Return true iff <b>address</b> is matched by one of the entries in
   2695 * TrackHostExits. */
   2696 int
   2697 hostname_in_track_host_exits(const or_options_t *options, const char *address)
   2698 {
   2699  if (!options->TrackHostExits)
   2700    return 0;
   2701  SMARTLIST_FOREACH_BEGIN(options->TrackHostExits, const char *, cp) {
   2702    if (cp[0] == '.') { /* match end */
   2703      if (cp[1] == '\0' ||
   2704          !strcasecmpend(address, cp) ||
   2705          !strcasecmp(address, &cp[1]))
   2706        return 1;
   2707    } else if (strcasecmp(cp, address) == 0) {
   2708      return 1;
   2709    }
   2710  } SMARTLIST_FOREACH_END(cp);
   2711  return 0;
   2712 }
   2713 
   2714 /** If an exit wasn't explicitly specified for <b>conn</b>, consider saving
   2715 * the exit that we *did* choose for use by future connections to
   2716 * <b>conn</b>'s destination.
   2717 */
   2718 static void
   2719 consider_recording_trackhost(const entry_connection_t *conn,
   2720                             const origin_circuit_t *circ)
   2721 {
   2722  const or_options_t *options = get_options();
   2723  char *new_address = NULL;
   2724  char fp[HEX_DIGEST_LEN+1];
   2725  uint64_t stream_id = 0;
   2726 
   2727  if (BUG(!conn)) {
   2728    return;
   2729  }
   2730 
   2731  stream_id = ENTRY_TO_CONN(conn)->global_identifier;
   2732 
   2733  /* Search the addressmap for this conn's destination. */
   2734  /* If they're not in the address map.. */
   2735  if (!options->TrackHostExits ||
   2736      addressmap_have_mapping(conn->socks_request->address,
   2737                              options->TrackHostExitsExpire))
   2738    return; /* nothing to track, or already mapped */
   2739 
   2740  if (!hostname_in_track_host_exits(options, conn->socks_request->address) ||
   2741      !circ->build_state->chosen_exit)
   2742    return;
   2743 
   2744  /* write down the fingerprint of the chosen exit, not the nickname,
   2745   * because the chosen exit might not be named. */
   2746  base16_encode(fp, sizeof(fp),
   2747                circ->build_state->chosen_exit->identity_digest, DIGEST_LEN);
   2748 
   2749  /* Add this exit/hostname pair to the addressmap. */
   2750  tor_asprintf(&new_address, "%s.%s.exit",
   2751               conn->socks_request->address, fp);
   2752 
   2753  addressmap_register(conn->socks_request->address, new_address,
   2754                      time(NULL) + options->TrackHostExitsExpire,
   2755                      ADDRMAPSRC_TRACKEXIT, 0, 0, stream_id);
   2756 }
   2757 
   2758 /**
   2759 * Return true if <b>conn</b> is configured with KeepaliveIsolateSOCKSAuth,
   2760 * and it has its socks isolation set.
   2761 */
   2762 static bool
   2763 connection_ap_socks_iso_keepalive_enabled(const entry_connection_t *conn)
   2764 {
   2765  return conn &&
   2766    conn->socks_request &&
   2767    (conn->entry_cfg.isolation_flags & ISO_SOCKSAUTH) &&
   2768    (conn->entry_cfg.socks_iso_keep_alive) &&
   2769    (conn->socks_request->usernamelen || conn->socks_request->passwordlen);
   2770 }
   2771 
   2772 /** Attempt to attach the connection <b>conn</b> to <b>circ</b>, and send a
   2773 * begin or resolve cell as appropriate.  Return values are as for
   2774 * connection_ap_handshake_attach_circuit.  The stream will exit from the hop
   2775 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
   2776 * <b>cpath</b> is NULL. */
   2777 int
   2778 connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn,
   2779                                              origin_circuit_t *circ,
   2780                                              crypt_path_t *cpath)
   2781 {
   2782  connection_t *base_conn = ENTRY_TO_CONN(conn);
   2783  tor_assert(conn);
   2784  tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT ||
   2785             base_conn->state == AP_CONN_STATE_CONTROLLER_WAIT);
   2786  tor_assert(conn->socks_request);
   2787  tor_assert(circ);
   2788  tor_assert(circ->base_.state == CIRCUIT_STATE_OPEN);
   2789 
   2790  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
   2791 
   2792  if (!circ->base_.timestamp_dirty ||
   2793      connection_ap_socks_iso_keepalive_enabled(conn)) {
   2794    /* When stream isolation is in use and controlled by an application
   2795     * we are willing to keep using the stream. */
   2796    circ->base_.timestamp_dirty = approx_time();
   2797    if (TO_CIRCUIT(circ)->conflux) {
   2798      conflux_sync_circ_fields(TO_CIRCUIT(circ)->conflux, circ);
   2799    }
   2800  }
   2801 
   2802  pathbias_count_use_attempt(circ);
   2803 
   2804  /* Now, actually link the connection. */
   2805  link_apconn_to_circ(conn, circ, cpath);
   2806 
   2807  tor_assert(conn->socks_request);
   2808  if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
   2809    if (!conn->use_begindir) {
   2810      consider_recording_trackhost(conn, circ);
   2811    }
   2812    if (connection_ap_handshake_send_begin(conn) < 0)
   2813      return -1;
   2814  } else {
   2815    if (connection_ap_handshake_send_resolve(conn) < 0)
   2816      return -1;
   2817  }
   2818 
   2819  return 1;
   2820 }
   2821 
   2822 /**
   2823 * Return an appropriate circuit purpose for non-rend streams.
   2824 * We don't handle rends here because a rend stream triggers two
   2825 * circuit builds with different purposes, so it is handled elsewhere.
   2826 *
   2827 * This function just figures out what type of hsdir activity this is,
   2828 * and tells us. Everything else is general.
   2829 */
   2830 static int
   2831 connection_ap_get_nonrend_circ_purpose(const entry_connection_t *conn)
   2832 {
   2833  const connection_t *base_conn = ENTRY_TO_CONN(conn);
   2834  tor_assert_nonfatal(!connection_edge_is_rendezvous_stream(
   2835                      ENTRY_TO_EDGE_CONN(conn)));
   2836 
   2837  if (base_conn->linked_conn &&
   2838      base_conn->linked_conn->type == CONN_TYPE_DIR) {
   2839    /* Set a custom purpose for hsdir activity */
   2840    if (base_conn->linked_conn->purpose == DIR_PURPOSE_UPLOAD_HSDESC) {
   2841      return CIRCUIT_PURPOSE_S_HSDIR_POST;
   2842    } else if (base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_HSDESC) {
   2843      return CIRCUIT_PURPOSE_C_HSDIR_GET;
   2844    }
   2845  }
   2846 
   2847  /* All other purposes are general for now */
   2848  return CIRCUIT_PURPOSE_C_GENERAL;
   2849 }
   2850 
   2851 /** Try to find a safe live circuit for stream <b>conn</b>.  If we find one,
   2852 * attach the stream, send appropriate cells, and return 1.  Otherwise,
   2853 * try to launch new circuit(s) for the stream.  If we can launch
   2854 * circuits, return 0.  Otherwise, if we simply can't proceed with
   2855 * this stream, return -1. (conn needs to die, and is maybe already marked).
   2856 */
   2857 /* XXXX this function should mark for close whenever it returns -1;
   2858 * its callers shouldn't have to worry about that. */
   2859 int
   2860 connection_ap_handshake_attach_circuit(entry_connection_t *conn)
   2861 {
   2862  connection_t *base_conn = ENTRY_TO_CONN(conn);
   2863  int retval;
   2864  int conn_age;
   2865  int want_onehop;
   2866 
   2867  tor_assert(conn);
   2868  tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
   2869  tor_assert(conn->socks_request);
   2870  want_onehop = conn->want_onehop;
   2871 
   2872  conn_age = (int)(time(NULL) - base_conn->timestamp_created);
   2873 
   2874  /* Is this connection so old that we should give up on it? Don't timeout if
   2875   * this is a connection to an HS with PoW enabled because it can take an
   2876   * arbitrary amount of time. */
   2877  if (conn_age >= get_options()->SocksTimeout && !conn->hs_with_pow_conn) {
   2878    int severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port) ?
   2879      LOG_INFO : LOG_NOTICE;
   2880    log_fn(severity, LD_APP,
   2881           "Tried for %d seconds to get a connection to %s:%d. Giving up.",
   2882           conn_age, safe_str_client(conn->socks_request->address),
   2883           conn->socks_request->port);
   2884    return -1;
   2885  }
   2886 
   2887  /* We handle "general" (non-onion) connections much more straightforwardly.
   2888   */
   2889  if (!connection_edge_is_rendezvous_stream(ENTRY_TO_EDGE_CONN(conn))) {
   2890    /* we're a general conn */
   2891    origin_circuit_t *circ=NULL;
   2892 
   2893    /* Are we linked to a dir conn that aims to fetch a consensus?
   2894     * We check here because the conn might no longer be needed. */
   2895    if (base_conn->linked_conn &&
   2896        base_conn->linked_conn->type == CONN_TYPE_DIR &&
   2897        base_conn->linked_conn->purpose == DIR_PURPOSE_FETCH_CONSENSUS) {
   2898 
   2899      /* Yes we are. Is there a consensus fetch farther along than us? */
   2900      if (networkstatus_consensus_is_already_downloading(
   2901            TO_DIR_CONN(base_conn->linked_conn)->requested_resource)) {
   2902        /* We're doing the "multiple consensus fetch attempts" game from
   2903         * proposal 210, and we're late to the party. Just close this conn.
   2904         * The circuit and TLS conn that we made will time out after a while
   2905         * if nothing else wants to use them. */
   2906        log_info(LD_DIR, "Closing extra consensus fetch (to %s) since one "
   2907                 "is already downloading.", base_conn->linked_conn->address);
   2908        return -1;
   2909      }
   2910    }
   2911 
   2912    /* If we have a chosen exit, we need to use a circuit that's
   2913     * open to that exit. See what exit we meant, and whether we can use it.
   2914     */
   2915    if (conn->chosen_exit_name) {
   2916      const node_t *node = node_get_by_nickname(conn->chosen_exit_name, 0);
   2917      int opt = conn->chosen_exit_optional;
   2918      if (!node && !want_onehop) {
   2919        /* We ran into this warning when trying to extend a circuit to a
   2920         * hidden service directory for which we didn't have a router
   2921         * descriptor. See flyspray task 767 for more details. We should
   2922         * keep this in mind when deciding to use BEGIN_DIR cells for other
   2923         * directory requests as well. -KL*/
   2924        log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
   2925               "Requested exit point '%s' is not known. %s.",
   2926               conn->chosen_exit_name, opt ? "Trying others" : "Closing");
   2927        if (opt) {
   2928          /* If we are allowed to ignore the .exit request, do so */
   2929          conn->chosen_exit_optional = 0;
   2930          tor_free(conn->chosen_exit_name);
   2931          return 0;
   2932        }
   2933        return -1;
   2934      }
   2935      if (node && !connection_ap_can_use_exit(conn, node)) {
   2936        log_fn(opt ? LOG_INFO : LOG_WARN, LD_APP,
   2937               "Requested exit point '%s' is excluded or "
   2938               "would refuse request. %s.",
   2939               conn->chosen_exit_name, opt ? "Trying others" : "Closing");
   2940        if (opt) {
   2941          /* If we are allowed to ignore the .exit request, do so */
   2942          conn->chosen_exit_optional = 0;
   2943          tor_free(conn->chosen_exit_name);
   2944          return 0;
   2945        }
   2946        return -1;
   2947      }
   2948    }
   2949 
   2950    /* Find the circuit that we should use, if there is one. Otherwise
   2951     * launch it
   2952     */
   2953    retval = circuit_get_open_circ_or_launch(conn,
   2954            connection_ap_get_nonrend_circ_purpose(conn),
   2955            &circ);
   2956 
   2957    if (retval < 1) {
   2958      /* We were either told "-1" (complete failure) or 0 (circuit in
   2959       * progress); we can't attach this stream yet. */
   2960      return retval;
   2961    }
   2962 
   2963    log_debug(LD_APP|LD_CIRC,
   2964              "Attaching apconn to circ %u (stream %d sec old).",
   2965              (unsigned)circ->base_.n_circ_id, conn_age);
   2966    /* print the circ's path, so clients can figure out which circs are
   2967     * sucking. */
   2968    circuit_log_path(LOG_INFO,LD_APP|LD_CIRC,circ);
   2969 
   2970    /* We have found a suitable circuit for our conn. Hurray.  Do
   2971     * the attachment. */
   2972    return connection_ap_handshake_attach_chosen_circuit(conn, circ, NULL);
   2973 
   2974  } else { /* we're a rendezvous conn */
   2975    origin_circuit_t *rendcirc=NULL, *introcirc=NULL;
   2976 
   2977    tor_assert(!ENTRY_TO_EDGE_CONN(conn)->cpath_layer);
   2978 
   2979    /* start by finding a rendezvous circuit for us */
   2980 
   2981    retval = circuit_get_open_circ_or_launch(
   2982       conn, CIRCUIT_PURPOSE_C_REND_JOINED, &rendcirc);
   2983    if (retval < 0) return -1; /* failed */
   2984 
   2985    if (retval > 0) {
   2986      tor_assert(rendcirc);
   2987      /* one is already established, attach */
   2988      log_info(LD_REND,
   2989               "rend joined circ %u (id: %" PRIu32 ") already here. "
   2990               "Attaching. (stream %d sec old)",
   2991               (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
   2992               rendcirc->global_identifier, conn_age);
   2993      /* Mark rendezvous circuits as 'newly dirty' every time you use
   2994       * them, since the process of rebuilding a rendezvous circ is so
   2995       * expensive. There is a tradeoff between linkability and
   2996       * feasibility, at this point.
   2997       */
   2998      rendcirc->base_.timestamp_dirty = time(NULL);
   2999 
   3000      /* We've also attempted to use them. If they fail, we need to
   3001       * probe them for path bias */
   3002      pathbias_count_use_attempt(rendcirc);
   3003 
   3004      link_apconn_to_circ(conn, rendcirc, NULL);
   3005      if (connection_ap_handshake_send_begin(conn) < 0)
   3006        return 0; /* already marked, let them fade away */
   3007      return 1;
   3008    }
   3009 
   3010    /* At this point we need to re-check the state, since it's possible that
   3011     * our call to circuit_get_open_circ_or_launch() changed the connection's
   3012     * state from "CIRCUIT_WAIT" to "RENDDESC_WAIT" because we decided to
   3013     * re-fetch the descriptor.
   3014     */
   3015    if (ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_CIRCUIT_WAIT) {
   3016      log_info(LD_REND, "This connection is no longer ready to attach; its "
   3017               "state changed."
   3018               "(We probably have to re-fetch its descriptor.)");
   3019      return 0;
   3020    }
   3021 
   3022    if (rendcirc && (rendcirc->base_.purpose ==
   3023                     CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)) {
   3024      log_info(LD_REND,
   3025               "pending-join circ %u (id: %" PRIu32 ") already here, with "
   3026               "intro ack. Stalling. (stream %d sec old)",
   3027               (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
   3028               rendcirc->global_identifier, conn_age);
   3029      return 0;
   3030    }
   3031 
   3032    /* it's on its way. find an intro circ. */
   3033    retval = circuit_get_open_circ_or_launch(
   3034      conn, CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT, &introcirc);
   3035    if (retval < 0) return -1; /* failed */
   3036 
   3037    if (rendcirc && introcirc) {
   3038      /* Let's fill out the hs_ident fully as soon as possible, so that
   3039       * unreachability counts can be updated properly even if circuits close
   3040       * early. */
   3041      tor_assert_nonfatal(!ed25519_public_key_is_zero(
   3042                             &introcirc->hs_ident->intro_auth_pk));
   3043      ed25519_pubkey_copy(&rendcirc->hs_ident->intro_auth_pk,
   3044                          &introcirc->hs_ident->intro_auth_pk);
   3045    }
   3046 
   3047    if (retval > 0) {
   3048      /* one has already sent the intro. keep waiting. */
   3049      tor_assert(introcirc);
   3050      log_info(LD_REND, "Intro circ %u (id: %" PRIu32 ") present and "
   3051                        "awaiting ACK. Rend circuit %u (id: %" PRIu32 "). "
   3052                        "Stalling. (stream %d sec old)",
   3053               (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
   3054               introcirc->global_identifier,
   3055               rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
   3056               rendcirc ? rendcirc->global_identifier : 0,
   3057               conn_age);
   3058      return 0;
   3059    }
   3060 
   3061    /* now rendcirc and introcirc are each either undefined or not finished */
   3062 
   3063    if (rendcirc && introcirc &&
   3064        rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY) {
   3065      log_info(LD_REND,
   3066               "ready rend circ %u (id: %" PRIu32 ") already here. No"
   3067               "intro-ack yet on intro %u (id: %" PRIu32 "). "
   3068               "(stream %d sec old)",
   3069               (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
   3070               rendcirc->global_identifier,
   3071               (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
   3072               introcirc->global_identifier, conn_age);
   3073 
   3074      tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
   3075      if (introcirc->base_.state == CIRCUIT_STATE_OPEN) {
   3076        int ret;
   3077        log_info(LD_REND, "Found open intro circ %u (id: %" PRIu32 "). "
   3078                          "Rend circuit %u (id: %" PRIu32 "); Considering "
   3079                          "sending introduction. (stream %d sec old)",
   3080                 (unsigned) TO_CIRCUIT(introcirc)->n_circ_id,
   3081                 introcirc->global_identifier,
   3082                 (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id,
   3083                 rendcirc->global_identifier, conn_age);
   3084        ret = hs_client_send_introduce1(introcirc, rendcirc);
   3085        switch (ret) {
   3086        case 0: /* success */
   3087          rendcirc->base_.timestamp_dirty = time(NULL);
   3088          introcirc->base_.timestamp_dirty = time(NULL);
   3089 
   3090          pathbias_count_use_attempt(introcirc);
   3091          pathbias_count_use_attempt(rendcirc);
   3092 
   3093          assert_circuit_ok(TO_CIRCUIT(rendcirc));
   3094          assert_circuit_ok(TO_CIRCUIT(introcirc));
   3095          return 0;
   3096        case -1: /* transient error */
   3097          return 0;
   3098        case -2: /* permanent error */
   3099          return -1;
   3100        default: /* oops */
   3101          tor_fragile_assert();
   3102          return -1;
   3103        }
   3104      }
   3105    }
   3106 
   3107    log_info(LD_REND, "Intro %u (id: %" PRIu32 ") and rend circuit %u "
   3108                      "(id: %" PRIu32 ") circuits are not both ready. "
   3109                      "Stalling conn. (%d sec old)",
   3110             introcirc ? (unsigned) TO_CIRCUIT(introcirc)->n_circ_id : 0,
   3111             introcirc ? introcirc->global_identifier : 0,
   3112             rendcirc ? (unsigned) TO_CIRCUIT(rendcirc)->n_circ_id : 0,
   3113             rendcirc ? rendcirc->global_identifier : 0, conn_age);
   3114    return 0;
   3115  }
   3116 }
   3117 
   3118 /** Change <b>circ</b>'s purpose to <b>new_purpose</b>. */
   3119 void
   3120 circuit_change_purpose(circuit_t *circ, uint8_t new_purpose)
   3121 {
   3122  uint8_t old_purpose;
   3123  /* Don't allow an OR circ to become an origin circ or vice versa. */
   3124  tor_assert(!!(CIRCUIT_IS_ORIGIN(circ)) ==
   3125             !!(CIRCUIT_PURPOSE_IS_ORIGIN(new_purpose)));
   3126 
   3127  if (circ->purpose == new_purpose) return;
   3128 
   3129  /* If this is a conflux circuit, a purpose change means we have closed */
   3130  if (CIRCUIT_IS_CONFLUX(circ)) {
   3131    /* If we're not transitioning to the linked purpose, we're closed. */
   3132    if (new_purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED)
   3133      conflux_circuit_has_closed(circ);
   3134  }
   3135 
   3136  if (CIRCUIT_IS_ORIGIN(circ)) {
   3137    char old_purpose_desc[80] = "";
   3138 
   3139    strncpy(old_purpose_desc, circuit_purpose_to_string(circ->purpose), 80-1);
   3140    old_purpose_desc[80-1] = '\0';
   3141 
   3142    log_debug(LD_CIRC,
   3143              "changing purpose of origin circ %d "
   3144              "from \"%s\" (%d) to \"%s\" (%d)",
   3145              TO_ORIGIN_CIRCUIT(circ)->global_identifier,
   3146              old_purpose_desc,
   3147              circ->purpose,
   3148              circuit_purpose_to_string(new_purpose),
   3149              new_purpose);
   3150 
   3151    /* Take specific actions if we are repurposing a hidden service circuit. */
   3152    if (circuit_purpose_is_hidden_service(circ->purpose) &&
   3153        !circuit_purpose_is_hidden_service(new_purpose)) {
   3154      hs_circ_cleanup_on_repurpose(circ);
   3155    }
   3156  }
   3157 
   3158  old_purpose = circ->purpose;
   3159  circ->purpose = new_purpose;
   3160  tor_trace(TR_SUBSYS(circuit), TR_EV(change_purpose), circ, old_purpose,
   3161            new_purpose);
   3162 
   3163  if (CIRCUIT_IS_ORIGIN(circ)) {
   3164    control_event_circuit_purpose_changed(TO_ORIGIN_CIRCUIT(circ),
   3165                                          old_purpose);
   3166 
   3167    circpad_machine_event_circ_purpose_changed(TO_ORIGIN_CIRCUIT(circ));
   3168  }
   3169 }
   3170 
   3171 /** Mark <b>circ</b> so that no more connections can be attached to it. */
   3172 void
   3173 mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
   3174 {
   3175  const or_options_t *options = get_options();
   3176  tor_assert(circ);
   3177 
   3178  /* XXXX This is a kludge; we're only keeping it around in case there's
   3179   * something that doesn't check unusable_for_new_conns, and to avoid
   3180   * deeper refactoring of our expiration logic. */
   3181  if (! circ->base_.timestamp_dirty)
   3182    circ->base_.timestamp_dirty = approx_time();
   3183  if (options->MaxCircuitDirtiness >= circ->base_.timestamp_dirty)
   3184    circ->base_.timestamp_dirty = 1; /* prevent underflow */
   3185  else
   3186    circ->base_.timestamp_dirty -= options->MaxCircuitDirtiness;
   3187 
   3188  circ->unusable_for_new_conns = 1;
   3189 
   3190  if (TO_CIRCUIT(circ)->conflux) {
   3191    conflux_sync_circ_fields(TO_CIRCUIT(circ)->conflux, circ);
   3192  }
   3193 }
   3194 
   3195 /**
   3196 * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
   3197 * the valid delivered written fields and the overhead field,
   3198 * respectively.
   3199 */
   3200 void
   3201 circuit_sent_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
   3202 {
   3203  if (!circ) return;
   3204 
   3205  tor_assertf_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE_MAX,
   3206                       "Wrong relay_body_len: %d (should be at most %d)",
   3207                       relay_body_len, RELAY_PAYLOAD_SIZE_MAX);
   3208 
   3209  circ->n_delivered_written_circ_bw =
   3210      tor_add_u32_nowrap(circ->n_delivered_written_circ_bw, relay_body_len);
   3211  // TODO CGO: I think this may now be somewhat incorrect.
   3212  circ->n_overhead_written_circ_bw =
   3213      tor_add_u32_nowrap(circ->n_overhead_written_circ_bw,
   3214                         RELAY_PAYLOAD_SIZE_MAX-relay_body_len);
   3215 }
   3216 
   3217 /**
   3218 * Add relay_body_len and RELAY_PAYLOAD_SIZE-relay_body_len to
   3219 * the valid delivered read field and the overhead field,
   3220 * respectively.
   3221 */
   3222 void
   3223 circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
   3224 {
   3225  if (!circ) return;
   3226 
   3227  tor_assert_nonfatal(relay_body_len <= RELAY_PAYLOAD_SIZE_MAX);
   3228 
   3229  circ->n_delivered_read_circ_bw =
   3230      tor_add_u32_nowrap(circ->n_delivered_read_circ_bw, relay_body_len);
   3231  // TODO CGO: I think this may now be somewhat incorrect.
   3232  circ->n_overhead_read_circ_bw =
   3233      tor_add_u32_nowrap(circ->n_overhead_read_circ_bw,
   3234                         RELAY_PAYLOAD_SIZE_MAX-relay_body_len);
   3235 }