tor

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

connection_edge.c (184038B)


      1 /* Copyright (c) 2001 Matej Pfajfar.
      2 * Copyright (c) 2001-2004, Roger Dingledine.
      3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      5 /* See LICENSE for licensing information */
      6 
      7 /**
      8 * \file connection_edge.c
      9 * \brief Handle edge streams.
     10 *
     11 * An edge_connection_t is a subtype of a connection_t, and represents two
     12 * critical concepts in Tor: a stream, and an edge connection.  From the Tor
     13 * protocol's point of view, a stream is a bi-directional channel that is
     14 * multiplexed on a single circuit.  Each stream on a circuit is identified
     15 * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
     16 * Streams are created in response to client requests.
     17 *
     18 * An edge connection is one thing that can implement a stream: it is either a
     19 * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
     20 * exit connection.
     21 *
     22 * Not every instance of edge_connection_t truly represents an edge connection,
     23 * however. (Sorry!) We also create edge_connection_t objects for streams that
     24 * we will not be handling with TCP.  The types of these streams are:
     25 *   <ul>
     26 *   <li>DNS lookup streams, created on the client side in response to
     27 *     a UDP DNS request received on a DNSPort, or a RESOLVE command
     28 *     on a controller.
     29 *   <li>DNS lookup streams, created on the exit side in response to
     30 *     a RELAY_RESOLVE cell from a client.
     31 *   <li>Tunneled directory streams, created on the directory cache side
     32 *     in response to a RELAY_BEGIN_DIR cell.  These streams attach directly
     33 *     to a dir_connection_t object without ever using TCP.
     34 *   </ul>
     35 *
     36 * This module handles general-purpose functionality having to do with
     37 * edge_connection_t.  On the client side, it accepts various types of
     38 * application requests on SocksPorts, TransPorts, and NATDPorts, and
     39 * creates streams appropriately.
     40 *
     41 * This module is also responsible for implementing stream isolation:
     42 * ensuring that streams that should not be linkable to one another are
     43 * kept to different circuits.
     44 *
     45 * On the exit side, this module handles the various stream-creating
     46 * type of RELAY cells by launching appropriate outgoing connections,
     47 * DNS requests, or directory connection objects.
     48 *
     49 * And for all edge connections, this module is responsible for handling
     50 * incoming and outdoing data as it arrives or leaves in the relay.c
     51 * module.  (Outgoing data will be packaged in
     52 * connection_edge_process_inbuf() as it calls
     53 * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
     54 * cells is applied in connection_edge_process_relay_cell().)
     55 **/
     56 #define CONNECTION_EDGE_PRIVATE
     57 
     58 #include "core/or/or.h"
     59 
     60 #include "lib/err/backtrace.h"
     61 
     62 #include "app/config/config.h"
     63 #include "core/mainloop/connection.h"
     64 #include "core/mainloop/mainloop.h"
     65 #include "core/mainloop/netstatus.h"
     66 #include "core/or/channel.h"
     67 #include "core/or/circuitbuild.h"
     68 #include "core/or/circuitlist.h"
     69 #include "core/or/circuituse.h"
     70 #include "core/or/circuitpadding.h"
     71 #include "core/or/connection_edge.h"
     72 #include "core/or/congestion_control_flow.h"
     73 #include "core/or/conflux_util.h"
     74 #include "core/or/circuitstats.h"
     75 #include "core/or/connection_or.h"
     76 #include "core/or/dos.h"
     77 #include "core/or/extendinfo.h"
     78 #include "core/or/policies.h"
     79 #include "core/or/reasons.h"
     80 #include "core/or/relay.h"
     81 #include "core/or/sendme.h"
     82 #include "core/proto/proto_http.h"
     83 #include "core/proto/proto_socks.h"
     84 #include "feature/client/addressmap.h"
     85 #include "feature/client/circpathbias.h"
     86 #include "feature/client/dnsserv.h"
     87 #include "feature/control/control_events.h"
     88 #include "feature/dircache/dirserv.h"
     89 #include "feature/dircommon/directory.h"
     90 #include "feature/hibernate/hibernate.h"
     91 #include "feature/hs/hs_cache.h"
     92 #include "feature/hs/hs_circuit.h"
     93 #include "feature/hs/hs_client.h"
     94 #include "feature/hs/hs_common.h"
     95 #include "feature/nodelist/describe.h"
     96 #include "feature/nodelist/networkstatus.h"
     97 #include "feature/nodelist/nodelist.h"
     98 #include "feature/nodelist/routerlist.h"
     99 #include "feature/nodelist/routerset.h"
    100 #include "feature/relay/dns.h"
    101 #include "feature/relay/router.h"
    102 #include "feature/relay/routermode.h"
    103 #include "feature/rend/rendcommon.h"
    104 #include "feature/stats/predict_ports.h"
    105 #include "feature/stats/rephist.h"
    106 #include "lib/buf/buffers.h"
    107 #include "lib/crypt_ops/crypto_rand.h"
    108 #include "lib/crypt_ops/crypto_util.h"
    109 #include "lib/encoding/confline.h"
    110 
    111 #include "core/or/cell_st.h"
    112 #include "core/or/cpath_build_state_st.h"
    113 #include "feature/dircommon/dir_connection_st.h"
    114 #include "core/or/entry_connection_st.h"
    115 #include "core/or/extend_info_st.h"
    116 #include "feature/nodelist/node_st.h"
    117 #include "core/or/or_circuit_st.h"
    118 #include "core/or/origin_circuit_st.h"
    119 #include "core/or/half_edge_st.h"
    120 #include "core/or/socks_request_st.h"
    121 #include "lib/evloop/compat_libevent.h"
    122 
    123 #ifdef HAVE_LINUX_TYPES_H
    124 #include <linux/types.h>
    125 #endif
    126 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
    127 #include <linux/netfilter_ipv4.h>
    128 #define TRANS_NETFILTER
    129 #define TRANS_NETFILTER_IPV4
    130 #endif
    131 
    132 #ifdef HAVE_LINUX_IF_H
    133 #include <linux/if.h>
    134 #endif
    135 
    136 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
    137 #include <linux/netfilter_ipv6/ip6_tables.h>
    138 #if defined(IP6T_SO_ORIGINAL_DST)
    139 #define TRANS_NETFILTER
    140 #define TRANS_NETFILTER_IPV6
    141 #endif
    142 #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
    143 
    144 #ifdef HAVE_FCNTL_H
    145 #include <fcntl.h>
    146 #endif
    147 #ifdef HAVE_SYS_IOCTL_H
    148 #include <sys/ioctl.h>
    149 #endif
    150 #ifdef HAVE_SYS_PARAM_H
    151 #include <sys/param.h>
    152 #endif
    153 
    154 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
    155 #include <net/if.h>
    156 #include <net/pfvar.h>
    157 #define TRANS_PF
    158 #endif
    159 
    160 #ifdef IP_TRANSPARENT
    161 #define TRANS_TPROXY
    162 #endif
    163 
    164 #define SOCKS4_GRANTED          90
    165 #define SOCKS4_REJECT           91
    166 
    167 static int connection_ap_handshake_process_socks(entry_connection_t *conn);
    168 static int connection_ap_process_natd(entry_connection_t *conn);
    169 static int connection_exit_connect_dir(edge_connection_t *exitconn);
    170 static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
    171 static int connection_ap_supports_optimistic_data(const entry_connection_t *);
    172 static bool network_reentry_is_allowed(void);
    173 
    174 /**
    175 * Cast a `connection_t *` to an `edge_connection_t *`.
    176 *
    177 * Exit with an assertion failure if the input is not an
    178 * `edge_connection_t`.
    179 **/
    180 edge_connection_t *
    181 TO_EDGE_CONN(connection_t *c)
    182 {
    183  tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
    184             c->magic == ENTRY_CONNECTION_MAGIC);
    185  return DOWNCAST(edge_connection_t, c);
    186 }
    187 
    188 /**
    189 * Cast a `const connection_t *` to a `const edge_connection_t *`.
    190 *
    191 * Exit with an assertion failure if the input is not an
    192 * `edge_connection_t`.
    193 **/
    194 const edge_connection_t *
    195 CONST_TO_EDGE_CONN(const connection_t *c)
    196 {
    197  return TO_EDGE_CONN((connection_t *)c);
    198 }
    199 
    200 /**
    201 * Cast a `connection_t *` to an `entry_connection_t *`.
    202 *
    203 * Exit with an assertion failure if the input is not an
    204 * `entry_connection_t`.
    205 **/
    206 entry_connection_t *
    207 TO_ENTRY_CONN(connection_t *c)
    208 {
    209  tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
    210  return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
    211 }
    212 
    213 /**
    214 * Cast a `const connection_t *` to a `const entry_connection_t *`.
    215 *
    216 * Exit with an assertion failure if the input is not an
    217 * `entry_connection_t`.
    218 **/
    219 const entry_connection_t *
    220 CONST_TO_ENTRY_CONN(const connection_t *c)
    221 {
    222  return TO_ENTRY_CONN((connection_t*) c);
    223 }
    224 
    225 /**
    226 * Cast an `edge_connection_t *` to an `entry_connection_t *`.
    227 *
    228 * Exit with an assertion failure if the input is not an
    229 * `entry_connection_t`.
    230 **/
    231 entry_connection_t *
    232 EDGE_TO_ENTRY_CONN(edge_connection_t *c)
    233 {
    234  tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
    235  return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
    236 }
    237 
    238 /**
    239 * Cast a `const edge_connection_t *` to a `const entry_connection_t *`.
    240 *
    241 * Exit with an assertion failure if the input is not an
    242 * `entry_connection_t`.
    243 **/
    244 const entry_connection_t *
    245 CONST_EDGE_TO_ENTRY_CONN(const edge_connection_t *c)
    246 {
    247  return EDGE_TO_ENTRY_CONN((edge_connection_t*)c);
    248 }
    249 
    250 /** An AP stream has failed/finished. If it hasn't already sent back
    251 * a socks reply, send one now (based on endreason). Also set
    252 * has_sent_end to 1, and mark the conn.
    253 */
    254 MOCK_IMPL(void,
    255 connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
    256                                int line, const char *file))
    257 {
    258  connection_t *base_conn = ENTRY_TO_CONN(conn);
    259  tor_assert(base_conn->type == CONN_TYPE_AP);
    260  ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
    261 
    262  if (base_conn->marked_for_close) {
    263    /* This call will warn as appropriate. */
    264    connection_mark_for_close_(base_conn, line, file);
    265    return;
    266  }
    267 
    268  if (!conn->socks_request->has_finished) {
    269    if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
    270      log_warn(LD_BUG,
    271               "stream (marked at %s:%d) sending two socks replies?",
    272               file, line);
    273 
    274    if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
    275      connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
    276    else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
    277      connection_ap_handshake_socks_resolved(conn,
    278                                             RESOLVED_TYPE_ERROR_TRANSIENT,
    279                                             0, NULL, -1, -1);
    280    else /* unknown or no handshake at all. send no response. */
    281      conn->socks_request->has_finished = 1;
    282  }
    283 
    284  connection_mark_and_flush_(base_conn, line, file);
    285 
    286  ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
    287 }
    288 
    289 /** There was an EOF. Send an end and mark the connection for close.
    290 */
    291 int
    292 connection_edge_reached_eof(edge_connection_t *conn)
    293 {
    294  if (connection_get_inbuf_len(TO_CONN(conn)) &&
    295      connection_state_is_open(TO_CONN(conn))) {
    296    /* it still has stuff to process. don't let it die yet. */
    297    return 0;
    298  }
    299  log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
    300           conn->base_.s);
    301  if (!conn->base_.marked_for_close) {
    302    /* only mark it if not already marked. it's possible to
    303     * get the 'end' right around when the client hangs up on us. */
    304    connection_edge_end(conn, END_STREAM_REASON_DONE);
    305    if (conn->base_.type == CONN_TYPE_AP) {
    306      /* eof, so don't send a socks reply back */
    307      if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
    308        EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
    309    }
    310    connection_mark_for_close(TO_CONN(conn));
    311  }
    312  return 0;
    313 }
    314 
    315 /** Handle new bytes on conn->inbuf based on state:
    316 *   - If it's waiting for socks info, try to read another step of the
    317 *     socks handshake out of conn->inbuf.
    318 *   - If it's waiting for the original destination, fetch it.
    319 *   - If it's open, then package more relay cells from the stream.
    320 *   - Else, leave the bytes on inbuf alone for now.
    321 *
    322 * Mark and return -1 if there was an unexpected error with the conn,
    323 * else return 0.
    324 */
    325 int
    326 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
    327 {
    328  tor_assert(conn);
    329 
    330  switch (conn->base_.state) {
    331    case AP_CONN_STATE_SOCKS_WAIT:
    332      if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
    333        /* already marked */
    334        return -1;
    335      }
    336      return 0;
    337    case AP_CONN_STATE_NATD_WAIT:
    338      if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
    339        /* already marked */
    340        return -1;
    341      }
    342      return 0;
    343    case AP_CONN_STATE_HTTP_CONNECT_WAIT:
    344      if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn)) < 0) {
    345        return -1;
    346      }
    347      return 0;
    348    case AP_CONN_STATE_OPEN:
    349      if (! conn->base_.linked) {
    350        note_user_activity(approx_time());
    351      }
    352 
    353      FALLTHROUGH;
    354    case EXIT_CONN_STATE_OPEN:
    355      if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
    356        /* (We already sent an end cell if possible) */
    357        connection_mark_for_close(TO_CONN(conn));
    358        return -1;
    359      }
    360      return 0;
    361    case AP_CONN_STATE_CONNECT_WAIT:
    362      if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
    363        log_info(LD_EDGE,
    364                 "data from edge while in '%s' state. Sending it anyway. "
    365                 "package_partial=%d, buflen=%ld",
    366                 conn_state_to_string(conn->base_.type, conn->base_.state),
    367                 package_partial,
    368                 (long)connection_get_inbuf_len(TO_CONN(conn)));
    369        if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
    370          /* (We already sent an end cell if possible) */
    371          connection_mark_for_close(TO_CONN(conn));
    372          return -1;
    373        }
    374        return 0;
    375      }
    376      /* Fall through if the connection is on a circuit without optimistic
    377       * data support. */
    378      FALLTHROUGH;
    379    case EXIT_CONN_STATE_CONNECTING:
    380    case AP_CONN_STATE_RENDDESC_WAIT:
    381    case AP_CONN_STATE_CIRCUIT_WAIT:
    382    case AP_CONN_STATE_RESOLVE_WAIT:
    383    case AP_CONN_STATE_CONTROLLER_WAIT:
    384      log_info(LD_EDGE,
    385               "data from edge while in '%s' state. Leaving it on buffer.",
    386               conn_state_to_string(conn->base_.type, conn->base_.state));
    387      return 0;
    388  }
    389  log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
    390  tor_fragile_assert();
    391  connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
    392  connection_mark_for_close(TO_CONN(conn));
    393  return -1;
    394 }
    395 
    396 /** This edge needs to be closed, because its circuit has closed.
    397 * Mark it for close and return 0.
    398 */
    399 int
    400 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
    401 {
    402  if (!conn->base_.marked_for_close) {
    403    log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
    404             (unsigned) circ_id);
    405    if (conn->base_.type == CONN_TYPE_AP) {
    406      entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
    407      connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
    408      control_event_stream_bandwidth(conn);
    409      control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
    410                                  END_STREAM_REASON_DESTROY);
    411      conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
    412    } else {
    413      /* closing the circuit, nothing to send an END to */
    414      conn->edge_has_sent_end = 1;
    415      conn->end_reason = END_STREAM_REASON_DESTROY;
    416      conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
    417      connection_mark_and_flush(TO_CONN(conn));
    418    }
    419  }
    420  conn->cpath_layer = NULL;
    421  conn->on_circuit = NULL;
    422  return 0;
    423 }
    424 
    425 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
    426 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
    427 * is not a client connection, set the relay end cell's reason for closing
    428 * as <b>reason</b> */
    429 static int
    430 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
    431                              uint8_t reason, crypt_path_t *cpath_layer)
    432 {
    433  char payload[1];
    434 
    435  if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
    436    /* Never send the server an informative reason code; it doesn't need to
    437     * know why the client stream is failing. */
    438    reason = END_STREAM_REASON_MISC;
    439  }
    440 
    441  payload[0] = (char) reason;
    442 
    443  /* Note: we have to use relay_send_command_from_edge here, not
    444   * connection_edge_end or connection_edge_send_command, since those require
    445   * that we have a stream connected to a circuit, and we don't connect to a
    446   * circuit until we have a pending/successful resolve. */
    447  return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
    448                                      payload, 1, cpath_layer);
    449 }
    450 
    451 /* If the connection <b>conn</b> is attempting to connect to an external
    452 * destination that is an hidden service and the reason is a connection
    453 * refused or timeout, log it so the operator can take appropriate actions.
    454 * The log statement is a rate limited warning. */
    455 static void
    456 warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
    457 {
    458  tor_assert(conn);
    459 
    460  if (conn->base_.type == CONN_TYPE_EXIT &&
    461      connection_edge_is_rendezvous_stream(conn) &&
    462      (reason == END_STREAM_REASON_CONNECTREFUSED ||
    463       reason == END_STREAM_REASON_TIMEOUT)) {
    464 #define WARN_FAILED_HS_CONNECTION 300
    465    static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
    466    char *m;
    467    if ((m = rate_limit_log(&warn_limit, approx_time()))) {
    468      log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
    469               connection_describe_peer(TO_CONN(conn)),
    470               stream_end_reason_to_string(reason));
    471      tor_free(m);
    472    }
    473  }
    474 }
    475 
    476 /** Given a TTL (in seconds) from a DNS response or from a relay, determine
    477 * what TTL clients and relays should actually use for caching it. */
    478 uint32_t
    479 clip_dns_ttl(uint32_t ttl)
    480 {
    481  /* This logic is a defense against "DefectTor" DNS-based traffic
    482   * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
    483   * We only give two values: a "low" value and a "high" value.
    484   */
    485  if (ttl < MIN_DNS_TTL)
    486    return MIN_DNS_TTL;
    487  else
    488    return MAX_DNS_TTL;
    489 }
    490 
    491 /** Given a TTL (in seconds), determine what TTL an exit relay should use by
    492 * first clipping as usual and then adding some randomness which is sampled
    493 * uniformly at random from [-FUZZY_DNS_TTL, FUZZY_DNS_TTL].  This facilitates
    494 * fuzzy TTLs, which makes it harder to infer when a website was visited via
    495 * side-channels like DNS (see "Website Fingerprinting with Website Oracles").
    496 *
    497 * Note that this can't underflow because FUZZY_DNS_TTL < MIN_DNS_TTL.
    498 */
    499 uint32_t
    500 clip_dns_fuzzy_ttl(uint32_t ttl)
    501 {
    502  return clip_dns_ttl(ttl) +
    503    crypto_rand_uint(1 + 2*FUZZY_DNS_TTL) - FUZZY_DNS_TTL;
    504 }
    505 
    506 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
    507 * remember that we've done so.  If this is not a client connection, set the
    508 * relay end cell's reason for closing as <b>reason</b>.
    509 *
    510 * Return -1 if this function has already been called on this conn,
    511 * else return 0.
    512 */
    513 int
    514 connection_edge_end(edge_connection_t *conn, uint8_t reason)
    515 {
    516  char payload[RELAY_PAYLOAD_SIZE_MAX];
    517  size_t payload_len=1;
    518  circuit_t *circ;
    519  uint8_t control_reason = reason;
    520 
    521  if (conn->edge_has_sent_end) {
    522    log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
    523             "on an already ended stream?", reason);
    524    tor_fragile_assert();
    525    return -1;
    526  }
    527 
    528  if (conn->base_.marked_for_close) {
    529    log_warn(LD_BUG,
    530             "called on conn that's already marked for close at %s:%d.",
    531             conn->base_.marked_for_close_file, conn->base_.marked_for_close);
    532    return 0;
    533  }
    534 
    535  circ = circuit_get_by_edge_conn(conn);
    536  if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
    537    /* If this is a client circuit, don't send the server an informative
    538     * reason code; it doesn't need to know why the client stream is
    539     * failing. */
    540    reason = END_STREAM_REASON_MISC;
    541  }
    542 
    543  payload[0] = (char)reason;
    544  if (reason == END_STREAM_REASON_EXITPOLICY &&
    545      !connection_edge_is_rendezvous_stream(conn)) {
    546    int addrlen;
    547    if (tor_addr_family(&conn->base_.addr) == AF_INET) {
    548      set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
    549      addrlen = 4;
    550    } else {
    551      memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
    552      addrlen = 16;
    553    }
    554    set_uint32(payload+1+addrlen, htonl(conn->address_ttl));
    555    payload_len += 4+addrlen;
    556  }
    557 
    558  if (circ && !circ->marked_for_close) {
    559    log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
    560              conn->base_.s);
    561 
    562    if (CIRCUIT_IS_ORIGIN(circ)) {
    563      origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
    564      connection_half_edge_add(conn, origin_circ);
    565    }
    566 
    567    connection_edge_send_command(conn, RELAY_COMMAND_END,
    568                                 payload, payload_len);
    569    /* We'll log warn if the connection was an hidden service and couldn't be
    570     * made because the service wasn't available. */
    571    warn_if_hs_unreachable(conn, control_reason);
    572  } else {
    573    log_debug(LD_EDGE,"No circ to send end on conn "
    574              "(fd "TOR_SOCKET_T_FORMAT").",
    575              conn->base_.s);
    576  }
    577 
    578  conn->edge_has_sent_end = 1;
    579  conn->end_reason = control_reason;
    580  return 0;
    581 }
    582 
    583 /**
    584 * Helper function for bsearch.
    585 *
    586 * As per smartlist_bsearch, return < 0 if key precedes member,
    587 * > 0 if member precedes key, and 0 if they are equal.
    588 *
    589 * This is equivalent to subtraction of the values of key - member
    590 * (why does no one ever say that explicitly?).
    591 */
    592 static int
    593 connection_half_edge_compare_bsearch(const void *key, const void **member)
    594 {
    595  const half_edge_t *e2;
    596  tor_assert(key);
    597  tor_assert(member && *(half_edge_t**)member);
    598  e2 = *(const half_edge_t **)member;
    599 
    600  return *(const streamid_t*)key - e2->stream_id;
    601 }
    602 
    603 /** Total number of half_edge_t objects allocated */
    604 static size_t n_half_conns_allocated = 0;
    605 
    606 /**
    607 * Add a half-closed connection to the list, to watch for activity.
    608 *
    609 * These connections are removed from the list upon receiving an end
    610 * cell.
    611 */
    612 STATIC void
    613 connection_half_edge_add(const edge_connection_t *conn,
    614                         origin_circuit_t *circ)
    615 {
    616  half_edge_t *half_conn = NULL;
    617  int insert_at = 0;
    618  int ignored;
    619 
    620  /* Double-check for re-insertion. This should not happen,
    621   * but this check is cheap compared to the sort anyway */
    622  if (connection_half_edge_find_stream_id(circ->half_streams,
    623                                          conn->stream_id)) {
    624    log_warn(LD_BUG, "Duplicate stream close for stream %d on circuit %d",
    625             conn->stream_id, circ->global_identifier);
    626    return;
    627  }
    628 
    629  half_conn = tor_malloc_zero(sizeof(half_edge_t));
    630  ++n_half_conns_allocated;
    631 
    632  if (!circ->half_streams) {
    633    circ->half_streams = smartlist_new();
    634    conflux_update_half_streams(circ, circ->half_streams);
    635  }
    636 
    637  half_conn->stream_id = conn->stream_id;
    638 
    639   // Is there a connected cell pending?
    640  half_conn->connected_pending = conn->base_.state ==
    641      AP_CONN_STATE_CONNECT_WAIT;
    642 
    643  if (edge_uses_flow_control(conn)) {
    644    /* If the edge uses the new congestion control flow control, we must use
    645     * time-based limits on half-edge activity. */
    646    uint64_t timeout_usec = (uint64_t)(get_circuit_build_timeout_ms()*1000);
    647    half_conn->used_ccontrol = 1;
    648 
    649    /* If this is an onion service circuit, double the CBT as an approximate
    650     * value for the other half of the circuit */
    651    if (conn->hs_ident) {
    652      timeout_usec *= 2;
    653    }
    654 
    655    /* The stream should stop seeing any use after the larger of the circuit
    656     * RTT and the overall circuit build timeout */
    657    half_conn->end_ack_expected_usec = MAX(timeout_usec,
    658                                           edge_get_max_rtt(conn)) +
    659                                        monotime_absolute_usec();
    660  } else {
    661    // How many sendme's should I expect?
    662    half_conn->sendmes_pending =
    663     (STREAMWINDOW_START-conn->package_window)/STREAMWINDOW_INCREMENT;
    664 
    665    /* Data should only arrive if we're not waiting on a resolved cell.
    666     * It can arrive after waiting on connected, because of optimistic
    667     * data. */
    668    if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
    669      // How many more data cells can arrive on this id?
    670      half_conn->data_pending = conn->deliver_window;
    671    }
    672  }
    673 
    674  insert_at = smartlist_bsearch_idx(circ->half_streams, &half_conn->stream_id,
    675                                    connection_half_edge_compare_bsearch,
    676                                    &ignored);
    677  smartlist_insert(circ->half_streams, insert_at, half_conn);
    678 }
    679 
    680 /**
    681 * Return true if the circuit has any half-closed connections
    682 * that are still within the end_ack_expected_usec timestamp
    683 * from now.
    684 */
    685 bool
    686 connection_half_edges_waiting(const origin_circuit_t *circ)
    687 {
    688  if (!circ->half_streams)
    689    return false;
    690 
    691  SMARTLIST_FOREACH_BEGIN(circ->half_streams, const half_edge_t *, half_conn) {
    692    if (half_conn->end_ack_expected_usec > monotime_absolute_usec())
    693      return true;
    694  } SMARTLIST_FOREACH_END(half_conn);
    695 
    696  return false;
    697 }
    698 
    699 /** Release space held by <b>he</b> */
    700 void
    701 half_edge_free_(half_edge_t *he)
    702 {
    703  if (!he)
    704    return;
    705  --n_half_conns_allocated;
    706  tor_free(he);
    707 }
    708 
    709 /** Return the number of bytes devoted to storing info on half-open streams. */
    710 size_t
    711 half_streams_get_total_allocation(void)
    712 {
    713  return n_half_conns_allocated * sizeof(half_edge_t);
    714 }
    715 
    716 /**
    717 * Find a stream_id_t in the list in O(lg(n)).
    718 *
    719 * Returns NULL if the list is empty or element is not found.
    720 * Returns a pointer to the element if found.
    721 */
    722 STATIC half_edge_t *
    723 connection_half_edge_find_stream_id(const smartlist_t *half_conns,
    724                                    streamid_t stream_id)
    725 {
    726  if (!half_conns)
    727    return NULL;
    728 
    729  return smartlist_bsearch(half_conns, &stream_id,
    730                           connection_half_edge_compare_bsearch);
    731 }
    732 
    733 /**
    734 * Check if this stream_id is in a half-closed state. If so,
    735 * check if it still has data cells pending, and decrement that
    736 * window if so.
    737 *
    738 * Return 1 if the data window was not empty.
    739 * Return 0 otherwise.
    740 */
    741 int
    742 connection_half_edge_is_valid_data(const smartlist_t *half_conns,
    743                                   streamid_t stream_id)
    744 {
    745  half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
    746                                                          stream_id);
    747 
    748  if (!half)
    749    return 0;
    750 
    751  if (half->used_ccontrol) {
    752    if (monotime_absolute_usec() > half->end_ack_expected_usec)
    753      return 0;
    754    return 1;
    755  }
    756 
    757  if (half->data_pending > 0) {
    758    half->data_pending--;
    759    return 1;
    760  }
    761 
    762  return 0;
    763 }
    764 
    765 /**
    766 * Check if this stream_id is in a half-closed state. If so,
    767 * check if it still has a connected cell pending, and decrement
    768 * that window if so.
    769 *
    770 * Return 1 if the connected window was not empty.
    771 * Return 0 otherwise.
    772 */
    773 int
    774 connection_half_edge_is_valid_connected(const smartlist_t *half_conns,
    775                                        streamid_t stream_id)
    776 {
    777  half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
    778                                                          stream_id);
    779 
    780  if (!half)
    781    return 0;
    782 
    783  if (half->connected_pending) {
    784    half->connected_pending = 0;
    785    return 1;
    786  }
    787 
    788  return 0;
    789 }
    790 
    791 /**
    792 * Check if this stream_id is in a half-closed state. If so,
    793 * check if it still has sendme cells pending, and decrement that
    794 * window if so.
    795 *
    796 * Return 1 if the sendme window was not empty.
    797 * Return 0 otherwise.
    798 */
    799 int
    800 connection_half_edge_is_valid_sendme(const smartlist_t *half_conns,
    801                                     streamid_t stream_id)
    802 {
    803  half_edge_t *half = connection_half_edge_find_stream_id(half_conns,
    804                                                          stream_id);
    805 
    806  if (!half)
    807    return 0;
    808 
    809  /* congestion control edges don't use sendmes */
    810  if (half->used_ccontrol)
    811    return 0;
    812 
    813  if (half->sendmes_pending > 0) {
    814    half->sendmes_pending--;
    815    return 1;
    816  }
    817 
    818  return 0;
    819 }
    820 
    821 /**
    822 * Check if this stream_id is in a half-closed state. If so, remove
    823 * it from the list. No other data should come after the END cell.
    824 *
    825 * Return 1 if stream_id was in half-closed state.
    826 * Return 0 otherwise.
    827 */
    828 int
    829 connection_half_edge_is_valid_end(smartlist_t *half_conns,
    830                                  streamid_t stream_id)
    831 {
    832  half_edge_t *half;
    833  int found, remove_idx;
    834 
    835  if (!half_conns)
    836    return 0;
    837 
    838  remove_idx = smartlist_bsearch_idx(half_conns, &stream_id,
    839                                    connection_half_edge_compare_bsearch,
    840                                    &found);
    841  if (!found)
    842    return 0;
    843 
    844  half = smartlist_get(half_conns, remove_idx);
    845  smartlist_del_keeporder(half_conns, remove_idx);
    846  half_edge_free(half);
    847  return 1;
    848 }
    849 
    850 /**
    851 * Streams that were used to send a RESOLVE cell are closed
    852 * when they get the RESOLVED, without an end. So treat
    853 * a RESOLVED just like an end, and remove from the list.
    854 */
    855 int
    856 connection_half_edge_is_valid_resolved(smartlist_t *half_conns,
    857                                       streamid_t stream_id)
    858 {
    859  return connection_half_edge_is_valid_end(half_conns, stream_id);
    860 }
    861 
    862 /** An error has just occurred on an operation on an edge connection
    863 * <b>conn</b>.  Extract the errno; convert it to an end reason, and send an
    864 * appropriate relay end cell to the other end of the connection's circuit.
    865 **/
    866 int
    867 connection_edge_end_errno(edge_connection_t *conn)
    868 {
    869  uint8_t reason;
    870  tor_assert(conn);
    871  reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
    872  return connection_edge_end(conn, reason);
    873 }
    874 
    875 /** We just wrote some data to <b>conn</b>; act appropriately.
    876 *
    877 * (That is, if it's open, consider sending a stream-level sendme cell if we
    878 * have just flushed enough.)
    879 */
    880 int
    881 connection_edge_flushed_some(edge_connection_t *conn)
    882 {
    883  switch (conn->base_.state) {
    884    case AP_CONN_STATE_OPEN:
    885      if (! conn->base_.linked) {
    886        note_user_activity(approx_time());
    887      }
    888 
    889      FALLTHROUGH;
    890    case EXIT_CONN_STATE_OPEN:
    891      sendme_connection_edge_consider_sending(conn);
    892      break;
    893  }
    894  return 0;
    895 }
    896 
    897 /** Connection <b>conn</b> has finished writing and has no bytes left on
    898 * its outbuf.
    899 *
    900 * If it's in state 'open', stop writing, consider responding with a
    901 * sendme, and return.
    902 * Otherwise, stop writing and return.
    903 *
    904 * If <b>conn</b> is broken, mark it for close and return -1, else
    905 * return 0.
    906 */
    907 int
    908 connection_edge_finished_flushing(edge_connection_t *conn)
    909 {
    910  tor_assert(conn);
    911 
    912  switch (conn->base_.state) {
    913    case AP_CONN_STATE_OPEN:
    914    case EXIT_CONN_STATE_OPEN:
    915      sendme_connection_edge_consider_sending(conn);
    916      return 0;
    917    case AP_CONN_STATE_SOCKS_WAIT:
    918    case AP_CONN_STATE_NATD_WAIT:
    919    case AP_CONN_STATE_RENDDESC_WAIT:
    920    case AP_CONN_STATE_CIRCUIT_WAIT:
    921    case AP_CONN_STATE_CONNECT_WAIT:
    922    case AP_CONN_STATE_CONTROLLER_WAIT:
    923    case AP_CONN_STATE_RESOLVE_WAIT:
    924    case AP_CONN_STATE_HTTP_CONNECT_WAIT:
    925      return 0;
    926    default:
    927      log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
    928      tor_fragile_assert();
    929      return -1;
    930  }
    931  return 0;
    932 }
    933 
    934 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
    935 * able to generate. */
    936 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
    937 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
    938 
    939 /** Set the buffer at <b>payload_out</b> -- which must have at least
    940 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
    941 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
    942 * that the name resolution that led us to <b>addr</b> will be valid for
    943 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
    944 * success. */
    945 STATIC int
    946 connected_cell_format_payload(uint8_t *payload_out,
    947                              const tor_addr_t *addr,
    948                              uint32_t ttl)
    949 {
    950  const sa_family_t family = tor_addr_family(addr);
    951  int connected_payload_len;
    952 
    953  /* should be needless */
    954  memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
    955 
    956  if (family == AF_INET) {
    957    set_uint32(payload_out, tor_addr_to_ipv4n(addr));
    958    connected_payload_len = 4;
    959  } else if (family == AF_INET6) {
    960    set_uint32(payload_out, 0);
    961    set_uint8(payload_out + 4, 6);
    962    memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
    963    connected_payload_len = 21;
    964  } else {
    965    return -1;
    966  }
    967 
    968  set_uint32(payload_out + connected_payload_len, htonl(ttl));
    969  connected_payload_len += 4;
    970 
    971  tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
    972 
    973  return connected_payload_len;
    974 }
    975 
    976 /* This is an onion service client connection: Export the client circuit ID
    977 * according to the HAProxy proxy protocol. */
    978 STATIC void
    979 export_hs_client_circuit_id(edge_connection_t *edge_conn,
    980                            hs_circuit_id_protocol_t protocol)
    981 {
    982  /* We only support HAProxy right now. */
    983  if (protocol != HS_CIRCUIT_ID_PROTOCOL_HAPROXY)
    984    return;
    985 
    986  char *buf = NULL;
    987  const char dst_ipv6[] = "::1";
    988  /* See RFC4193 regarding fc00::/7 */
    989  const char src_ipv6_prefix[] = "fc00:dead:beef:4dad:";
    990  uint16_t dst_port = 0;
    991  uint16_t src_port = 1; /* default value */
    992  uint32_t gid = 0; /* default value */
    993 
    994  /* Generate a GID and source port for this client */
    995  if (edge_conn->on_circuit != NULL) {
    996    gid = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit)->global_identifier;
    997    src_port = gid & 0x0000ffff;
    998  }
    999 
   1000  /* Grab the original dest port from the hs ident */
   1001  if (edge_conn->hs_ident) {
   1002    dst_port = edge_conn->hs_ident->orig_virtual_port;
   1003  }
   1004 
   1005  /* Build the string */
   1006  tor_asprintf(&buf, "PROXY TCP6 %s:%x:%x %s %d %d\r\n",
   1007               src_ipv6_prefix,
   1008               gid >> 16, gid & 0x0000ffff,
   1009               dst_ipv6, src_port, dst_port);
   1010 
   1011  connection_buf_add(buf, strlen(buf), TO_CONN(edge_conn));
   1012 
   1013  tor_free(buf);
   1014 }
   1015 
   1016 /** Connected handler for exit connections: start writing pending
   1017 * data, deliver 'CONNECTED' relay cells as appropriate, and check
   1018 * any pending data that may have been received. */
   1019 int
   1020 connection_edge_finished_connecting(edge_connection_t *edge_conn)
   1021 {
   1022  connection_t *conn;
   1023 
   1024  tor_assert(edge_conn);
   1025  tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
   1026  conn = TO_CONN(edge_conn);
   1027  tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
   1028 
   1029  log_info(LD_EXIT,"%s established.",
   1030           connection_describe(conn));
   1031 
   1032  rep_hist_note_exit_stream_opened(conn->port);
   1033 
   1034  conn->state = EXIT_CONN_STATE_OPEN;
   1035 
   1036  connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
   1037  if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
   1038                                        * cells */
   1039    connection_start_writing(conn);
   1040  /* deliver a 'connected' relay cell back through the circuit. */
   1041  if (connection_edge_is_rendezvous_stream(edge_conn)) {
   1042    if (connection_edge_send_command(edge_conn,
   1043                                     RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
   1044      return 0; /* circuit is closed, don't continue */
   1045  } else {
   1046    uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
   1047    int connected_payload_len =
   1048      connected_cell_format_payload(connected_payload, &conn->addr,
   1049                                    edge_conn->address_ttl);
   1050    if (connected_payload_len < 0)
   1051      return -1;
   1052 
   1053    if (connection_edge_send_command(edge_conn,
   1054                        RELAY_COMMAND_CONNECTED,
   1055                        (char*)connected_payload, connected_payload_len) < 0)
   1056      return 0; /* circuit is closed, don't continue */
   1057  }
   1058  tor_assert(edge_conn->package_window > 0);
   1059  /* in case the server has written anything */
   1060  return connection_edge_process_inbuf(edge_conn, 1);
   1061 }
   1062 
   1063 /** A list of all the entry_connection_t * objects that are not marked
   1064 * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
   1065 *
   1066 * (Right now, we check in several places to make sure that this list is
   1067 * correct.  When it's incorrect, we'll fix it, and log a BUG message.)
   1068 */
   1069 static smartlist_t *pending_entry_connections = NULL;
   1070 
   1071 static int untried_pending_connections = 0;
   1072 
   1073 /**
   1074 * Mainloop event to tell us to scan for pending connections that can
   1075 * be attached.
   1076 */
   1077 static mainloop_event_t *attach_pending_entry_connections_ev = NULL;
   1078 
   1079 /** Common code to connection_(ap|exit)_about_to_close. */
   1080 static void
   1081 connection_edge_about_to_close(edge_connection_t *edge_conn)
   1082 {
   1083  /* Under memory pressure, the OOM handler can close connections without
   1084   * sending END cell. If we are NOT in that scenario, log loudly. */
   1085  if (!edge_conn->edge_has_sent_end && !have_been_under_memory_pressure()) {
   1086    connection_t *conn = TO_CONN(edge_conn);
   1087    log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
   1088             "hasn't sent end yet?",
   1089             conn->marked_for_close_file, conn->marked_for_close);
   1090    tor_fragile_assert();
   1091  }
   1092 }
   1093 
   1094 /** Called when we're about to finally unlink and free an AP (client)
   1095 * connection: perform necessary accounting and cleanup */
   1096 void
   1097 connection_ap_about_to_close(entry_connection_t *entry_conn)
   1098 {
   1099  circuit_t *circ;
   1100  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
   1101  connection_t *conn = ENTRY_TO_CONN(entry_conn);
   1102 
   1103  connection_edge_about_to_close(edge_conn);
   1104 
   1105  if (entry_conn->socks_request->has_finished == 0) {
   1106    /* since conn gets removed right after this function finishes,
   1107     * there's no point trying to send back a reply at this point. */
   1108    log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
   1109             " back a socks reply.",
   1110             conn->marked_for_close_file, conn->marked_for_close);
   1111  }
   1112  if (!edge_conn->end_reason) {
   1113    log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
   1114             " set end_reason.",
   1115             conn->marked_for_close_file, conn->marked_for_close);
   1116  }
   1117  if (entry_conn->dns_server_request) {
   1118    log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
   1119             " replied to DNS request.",
   1120             conn->marked_for_close_file, conn->marked_for_close);
   1121    dnsserv_reject_request(entry_conn);
   1122  }
   1123 
   1124  if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
   1125    smartlist_remove(pending_entry_connections, entry_conn);
   1126  }
   1127 
   1128 #if 1
   1129  /* Check to make sure that this isn't in pending_entry_connections if it
   1130   * didn't actually belong there. */
   1131  if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
   1132    connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
   1133                                                  "about_to_close");
   1134  }
   1135 #endif /* 1 */
   1136 
   1137  control_event_stream_bandwidth(edge_conn);
   1138  control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
   1139                              edge_conn->end_reason);
   1140  circ = circuit_get_by_edge_conn(edge_conn);
   1141  if (circ)
   1142    circuit_detach_stream(circ, edge_conn);
   1143 }
   1144 
   1145 /** Called when we're about to finally unlink and free an exit
   1146 * connection: perform necessary accounting and cleanup */
   1147 void
   1148 connection_exit_about_to_close(edge_connection_t *edge_conn)
   1149 {
   1150  circuit_t *circ;
   1151  connection_t *conn = TO_CONN(edge_conn);
   1152 
   1153  connection_edge_about_to_close(edge_conn);
   1154 
   1155  circ = circuit_get_by_edge_conn(edge_conn);
   1156  if (circ)
   1157    circuit_detach_stream(circ, edge_conn);
   1158  if (conn->state == EXIT_CONN_STATE_RESOLVING) {
   1159    connection_dns_remove(edge_conn);
   1160  }
   1161 }
   1162 
   1163 /** Define a schedule for how long to wait between retrying
   1164 * application connections. Rather than waiting a fixed amount of
   1165 * time between each retry, we wait 10 seconds each for the first
   1166 * two tries, and 15 seconds for each retry after
   1167 * that. Hopefully this will improve the expected user experience. */
   1168 static int
   1169 compute_retry_timeout(entry_connection_t *conn)
   1170 {
   1171  int timeout = get_options()->CircuitStreamTimeout;
   1172  if (timeout) /* if our config options override the default, use them */
   1173    return timeout;
   1174  if (conn->num_socks_retries < 2) /* try 0 and try 1 */
   1175    return 10;
   1176  return 15;
   1177 }
   1178 
   1179 /** Find all general-purpose AP streams waiting for a response that sent their
   1180 * begin/resolve cell too long ago. Detach from their current circuit, and
   1181 * mark their current circuit as unsuitable for new streams. Then call
   1182 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
   1183 * available) or launch a new one.
   1184 *
   1185 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
   1186 * retry attempt).
   1187 */
   1188 void
   1189 connection_ap_expire_beginning(void)
   1190 {
   1191  edge_connection_t *conn;
   1192  entry_connection_t *entry_conn;
   1193  circuit_t *circ;
   1194  time_t now = time(NULL);
   1195  const or_options_t *options = get_options();
   1196  int severity;
   1197  int cutoff;
   1198  int seconds_idle, seconds_since_born;
   1199  smartlist_t *conns = get_connection_array();
   1200 
   1201  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
   1202    if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
   1203      continue;
   1204    entry_conn = TO_ENTRY_CONN(base_conn);
   1205    conn = ENTRY_TO_EDGE_CONN(entry_conn);
   1206    /* if it's an internal linked connection, don't yell its status. */
   1207    severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
   1208      ? LOG_INFO : LOG_NOTICE;
   1209    seconds_idle = (int)( now - base_conn->timestamp_last_read_allowed );
   1210    seconds_since_born = (int)( now - base_conn->timestamp_created );
   1211 
   1212    if (base_conn->state == AP_CONN_STATE_OPEN)
   1213      continue;
   1214 
   1215    /* We already consider SocksTimeout in
   1216     * connection_ap_handshake_attach_circuit(), but we need to consider
   1217     * it here too because controllers that put streams in controller_wait
   1218     * state never ask Tor to attach the circuit. */
   1219    if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
   1220      /* If this is a connection to an HS with PoW defenses enabled, we need to
   1221       * wait longer than the usual Socks timeout. */
   1222      if (seconds_since_born >= options->SocksTimeout &&
   1223          !entry_conn->hs_with_pow_conn) {
   1224        log_fn(severity, LD_APP,
   1225            "Tried for %d seconds to get a connection to %s:%d. "
   1226            "Giving up. (%s)",
   1227            seconds_since_born,
   1228            safe_str_client(entry_conn->socks_request->address),
   1229            entry_conn->socks_request->port,
   1230            conn_state_to_string(CONN_TYPE_AP, base_conn->state));
   1231        connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
   1232      }
   1233      continue;
   1234    }
   1235 
   1236    /* We're in state connect_wait or resolve_wait now -- waiting for a
   1237     * reply to our relay cell. See if we want to retry/give up. */
   1238 
   1239    cutoff = compute_retry_timeout(entry_conn);
   1240    if (seconds_idle < cutoff)
   1241      continue;
   1242    circ = circuit_get_by_edge_conn(conn);
   1243    if (!circ) { /* it's vanished? */
   1244      log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
   1245               safe_str_client(entry_conn->socks_request->address));
   1246      connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
   1247      continue;
   1248    }
   1249    if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
   1250      if (seconds_idle >= options->SocksTimeout) {
   1251        log_fn(severity, LD_REND,
   1252               "Rend stream is %d seconds late. Giving up on address"
   1253               " '%s.onion'.",
   1254               seconds_idle,
   1255               safe_str_client(entry_conn->socks_request->address));
   1256        /* Roll back path bias use state so that we probe the circuit
   1257         * if nothing else succeeds on it */
   1258        pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
   1259 
   1260        connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
   1261        connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
   1262      }
   1263      continue;
   1264    }
   1265 
   1266    if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
   1267        circ->purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED &&
   1268        circ->purpose != CIRCUIT_PURPOSE_CONTROLLER &&
   1269        circ->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
   1270        circ->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
   1271        circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
   1272        circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
   1273      log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
   1274               "The purpose on the circuit was %s; it was in state %s, "
   1275               "path_state %s.",
   1276               circuit_purpose_to_string(circ->purpose),
   1277               circuit_state_to_string(circ->state),
   1278               CIRCUIT_IS_ORIGIN(circ) ?
   1279                pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
   1280                "none");
   1281    }
   1282    log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
   1283           "We tried for %d seconds to connect to '%s' using exit %s."
   1284           " Retrying on a new circuit.",
   1285           seconds_idle,
   1286           safe_str_client(entry_conn->socks_request->address),
   1287           conn->cpath_layer ?
   1288             extend_info_describe(conn->cpath_layer->extend_info):
   1289             "*unnamed*");
   1290    /* send an end down the circuit */
   1291    connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
   1292    /* un-mark it as ending, since we're going to reuse it */
   1293    conn->edge_has_sent_end = 0;
   1294    conn->end_reason = 0;
   1295    /* make us not try this circuit again, but allow
   1296     * current streams on it to survive if they can */
   1297    mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
   1298 
   1299    /* give our stream another 'cutoff' seconds to try */
   1300    conn->base_.timestamp_last_read_allowed += cutoff;
   1301    if (entry_conn->num_socks_retries < 250) /* avoid overflow */
   1302      entry_conn->num_socks_retries++;
   1303    /* move it back into 'pending' state, and try to attach. */
   1304    if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
   1305                                       END_STREAM_REASON_TIMEOUT)<0) {
   1306      if (!base_conn->marked_for_close)
   1307        connection_mark_unattached_ap(entry_conn,
   1308                                      END_STREAM_REASON_CANT_ATTACH);
   1309    }
   1310  } SMARTLIST_FOREACH_END(base_conn);
   1311 }
   1312 
   1313 /**
   1314 * As connection_ap_attach_pending, but first scans the entire connection
   1315 * array to see if any elements are missing.
   1316 */
   1317 void
   1318 connection_ap_rescan_and_attach_pending(void)
   1319 {
   1320  entry_connection_t *entry_conn;
   1321  smartlist_t *conns = get_connection_array();
   1322 
   1323  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
   1324    pending_entry_connections = smartlist_new();
   1325 
   1326  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
   1327    if (conn->marked_for_close ||
   1328        conn->type != CONN_TYPE_AP ||
   1329        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
   1330      continue;
   1331 
   1332    entry_conn = TO_ENTRY_CONN(conn);
   1333    tor_assert(entry_conn);
   1334    if (! smartlist_contains(pending_entry_connections, entry_conn)) {
   1335      log_warn(LD_BUG, "Found a connection %p that was supposed to be "
   1336               "in pending_entry_connections, but wasn't. No worries; "
   1337               "adding it.",
   1338               pending_entry_connections);
   1339      untried_pending_connections = 1;
   1340      connection_ap_mark_as_pending_circuit(entry_conn);
   1341    }
   1342 
   1343  } SMARTLIST_FOREACH_END(conn);
   1344 
   1345  connection_ap_attach_pending(1);
   1346 }
   1347 
   1348 /** Tell any AP streams that are listed as waiting for a new circuit to try
   1349 * again.  If there is an available circuit for a stream, attach it. Otherwise,
   1350 * launch a new circuit.
   1351 *
   1352 * If <b>retry</b> is false, only check the list if it contains at least one
   1353 * streams that we have not yet tried to attach to a circuit.
   1354 */
   1355 void
   1356 connection_ap_attach_pending(int retry)
   1357 {
   1358  if (PREDICT_UNLIKELY(!pending_entry_connections)) {
   1359    return;
   1360  }
   1361 
   1362  if (untried_pending_connections == 0 && !retry)
   1363    return;
   1364 
   1365  /* Don't allow any modifications to list while we are iterating over
   1366   * it.  We'll put streams back on this list if we can't attach them
   1367   * immediately. */
   1368  smartlist_t *pending = pending_entry_connections;
   1369  pending_entry_connections = smartlist_new();
   1370 
   1371  SMARTLIST_FOREACH_BEGIN(pending,
   1372                          entry_connection_t *, entry_conn) {
   1373    connection_t *conn = ENTRY_TO_CONN(entry_conn);
   1374    tor_assert(conn && entry_conn);
   1375    if (conn->marked_for_close) {
   1376      continue;
   1377    }
   1378    if (conn->magic != ENTRY_CONNECTION_MAGIC) {
   1379      log_warn(LD_BUG, "%p has impossible magic value %u.",
   1380               entry_conn, (unsigned)conn->magic);
   1381      continue;
   1382    }
   1383    if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
   1384      /* The connection_ap_handshake_attach_circuit() call, for onion service,
   1385       * can lead to more than one connections in the "pending" list to change
   1386       * state and so it is OK to get here. Ignore it because this connection
   1387       * won't be in pending_entry_connections list after this point. */
   1388      continue;
   1389    }
   1390 
   1391    /* Okay, we're through the sanity checks. Try to handle this stream. */
   1392    if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
   1393      if (!conn->marked_for_close)
   1394        connection_mark_unattached_ap(entry_conn,
   1395                                      END_STREAM_REASON_CANT_ATTACH);
   1396    }
   1397 
   1398    if (! conn->marked_for_close &&
   1399        conn->type == CONN_TYPE_AP &&
   1400        conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
   1401      /* Is it still waiting for a circuit? If so, we didn't attach it,
   1402       * so it's still pending.  Put it back on the list.
   1403       */
   1404      if (!smartlist_contains(pending_entry_connections, entry_conn)) {
   1405        smartlist_add(pending_entry_connections, entry_conn);
   1406        continue;
   1407      }
   1408    }
   1409 
   1410    /* If we got here, then we either closed the connection, or
   1411     * we attached it. */
   1412  } SMARTLIST_FOREACH_END(entry_conn);
   1413 
   1414  smartlist_free(pending);
   1415  untried_pending_connections = 0;
   1416 }
   1417 
   1418 static void
   1419 attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
   1420 {
   1421  (void)ev;
   1422  (void)arg;
   1423  connection_ap_attach_pending(0);
   1424 }
   1425 
   1426 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
   1427 *
   1428 * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
   1429 * should not already be pending a circuit.  The circuit will get
   1430 * launched or the connection will get attached the next time we
   1431 * call connection_ap_attach_pending().
   1432 */
   1433 void
   1434 connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn,
   1435                                       const char *fname, int lineno)
   1436 {
   1437  connection_t *conn = ENTRY_TO_CONN(entry_conn);
   1438  tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
   1439  tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
   1440  if (conn->marked_for_close)
   1441    return;
   1442 
   1443  if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
   1444    pending_entry_connections = smartlist_new();
   1445  }
   1446  if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
   1447    attach_pending_entry_connections_ev = mainloop_event_postloop_new(
   1448                                  attach_pending_entry_connections_cb, NULL);
   1449  }
   1450  if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
   1451                                          entry_conn))) {
   1452    log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
   1453             "(Called from %s:%d.)",
   1454             entry_conn, fname, lineno);
   1455 #ifdef DEBUGGING_17659
   1456    const char *f2 = entry_conn->marked_pending_circ_file;
   1457    log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
   1458             f2 ? f2 : "<NULL>",
   1459             entry_conn->marked_pending_circ_line);
   1460 #endif /* defined(DEBUGGING_17659) */
   1461    log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
   1462    return;
   1463  }
   1464 
   1465 #ifdef DEBUGGING_17659
   1466  entry_conn->marked_pending_circ_line = (uint16_t) lineno;
   1467  entry_conn->marked_pending_circ_file = fname;
   1468 #endif
   1469 
   1470  untried_pending_connections = 1;
   1471  smartlist_add(pending_entry_connections, entry_conn);
   1472 
   1473  mainloop_event_activate(attach_pending_entry_connections_ev);
   1474 }
   1475 
   1476 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
   1477 void
   1478 connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
   1479 {
   1480  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
   1481    return;
   1482  smartlist_remove(pending_entry_connections, entry_conn);
   1483 }
   1484 
   1485 /** Mark <b>entry_conn</b> as waiting for a rendezvous descriptor. This
   1486 * function will remove the entry connection from the waiting for a circuit
   1487 * list (pending_entry_connections).
   1488 *
   1489 * This pattern is used across the code base because a connection in state
   1490 * AP_CONN_STATE_RENDDESC_WAIT must not be in the pending list. */
   1491 void
   1492 connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
   1493 {
   1494  tor_assert(entry_conn);
   1495 
   1496  connection_ap_mark_as_non_pending_circuit(entry_conn);
   1497  ENTRY_TO_CONN(entry_conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
   1498 }
   1499 
   1500 /* DOCDOC */
   1501 void
   1502 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
   1503                                              const char *where)
   1504 {
   1505  if (pending_entry_connections &&
   1506      smartlist_contains(pending_entry_connections, entry_conn)) {
   1507    log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
   1508             entry_conn, where);
   1509    connection_ap_mark_as_non_pending_circuit(entry_conn);
   1510  }
   1511 }
   1512 
   1513 /** Tell any AP streams that are waiting for a one-hop tunnel to
   1514 * <b>failed_digest</b> that they are going to fail. */
   1515 /* XXXX We should get rid of this function, and instead attach
   1516 * one-hop streams to circ->p_streams so they get marked in
   1517 * circuit_mark_for_close like normal p_streams. */
   1518 void
   1519 connection_ap_fail_onehop(const char *failed_digest,
   1520                          cpath_build_state_t *build_state)
   1521 {
   1522  entry_connection_t *entry_conn;
   1523  char digest[DIGEST_LEN];
   1524  smartlist_t *conns = get_connection_array();
   1525  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
   1526    if (conn->marked_for_close ||
   1527        conn->type != CONN_TYPE_AP ||
   1528        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
   1529      continue;
   1530    entry_conn = TO_ENTRY_CONN(conn);
   1531    if (!entry_conn->want_onehop)
   1532      continue;
   1533    if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
   1534        tor_memneq(digest, failed_digest, DIGEST_LEN))
   1535      continue;
   1536    if (tor_digest_is_zero(digest)) {
   1537      /* we don't know the digest; have to compare addr:port */
   1538      tor_addr_t addr;
   1539      if (!build_state || !build_state->chosen_exit ||
   1540          !entry_conn->socks_request) {
   1541        continue;
   1542      }
   1543      if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
   1544          !extend_info_has_orport(build_state->chosen_exit, &addr,
   1545                                  entry_conn->socks_request->port))
   1546        continue;
   1547    }
   1548    log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
   1549                     "just failed.", entry_conn->chosen_exit_name,
   1550                     entry_conn->socks_request->address);
   1551    connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
   1552  } SMARTLIST_FOREACH_END(conn);
   1553 }
   1554 
   1555 /** A circuit failed to finish on its last hop <b>info</b>. If there
   1556 * are any streams waiting with this exit node in mind, but they
   1557 * don't absolutely require it, make them give up on it.
   1558 */
   1559 void
   1560 circuit_discard_optional_exit_enclaves(extend_info_t *info)
   1561 {
   1562  entry_connection_t *entry_conn;
   1563  const node_t *r1, *r2;
   1564 
   1565  smartlist_t *conns = get_connection_array();
   1566  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
   1567    if (conn->marked_for_close ||
   1568        conn->type != CONN_TYPE_AP ||
   1569        conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
   1570      continue;
   1571    entry_conn = TO_ENTRY_CONN(conn);
   1572    if (!entry_conn->chosen_exit_optional &&
   1573        !entry_conn->chosen_exit_retries)
   1574      continue;
   1575    r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
   1576                              NNF_NO_WARN_UNNAMED);
   1577    r2 = node_get_by_id(info->identity_digest);
   1578    if (!r1 || !r2 || r1 != r2)
   1579      continue;
   1580    tor_assert(entry_conn->socks_request);
   1581    if (entry_conn->chosen_exit_optional) {
   1582      log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
   1583               safe_str_client(entry_conn->chosen_exit_name),
   1584               escaped_safe_str_client(entry_conn->socks_request->address));
   1585      entry_conn->chosen_exit_optional = 0;
   1586      tor_free(entry_conn->chosen_exit_name); /* clears it */
   1587      /* if this port is dangerous, warn or reject it now that we don't
   1588       * think it'll be using an enclave. */
   1589      consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
   1590    }
   1591    if (entry_conn->chosen_exit_retries) {
   1592      if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
   1593        clear_trackexithost_mappings(entry_conn->chosen_exit_name);
   1594        tor_free(entry_conn->chosen_exit_name); /* clears it */
   1595        /* if this port is dangerous, warn or reject it now that we don't
   1596         * think it'll be using an enclave. */
   1597        consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
   1598      }
   1599    }
   1600  } SMARTLIST_FOREACH_END(conn);
   1601 }
   1602 
   1603 /** Set the connection state to CONTROLLER_WAIT and send an control port event.
   1604 */
   1605 void
   1606 connection_entry_set_controller_wait(entry_connection_t *conn)
   1607 {
   1608  CONNECTION_AP_EXPECT_NONPENDING(conn);
   1609  ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
   1610  control_event_stream_status(conn, STREAM_EVENT_CONTROLLER_WAIT, 0);
   1611 }
   1612 
   1613 /** The AP connection <b>conn</b> has just failed while attaching or
   1614 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
   1615 * might work. Detach the circuit, and either reattach it, launch a
   1616 * new circuit, tell the controller, or give up as appropriate.
   1617 *
   1618 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
   1619 */
   1620 int
   1621 connection_ap_detach_retriable(entry_connection_t *conn,
   1622                               origin_circuit_t *circ,
   1623                               int reason)
   1624 {
   1625  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
   1626  ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
   1627 
   1628  /* Roll back path bias use state so that we probe the circuit
   1629   * if nothing else succeeds on it */
   1630  pathbias_mark_use_rollback(circ);
   1631 
   1632  if (conn->pending_optimistic_data) {
   1633    buf_set_to_copy(&conn->sending_optimistic_data,
   1634                    conn->pending_optimistic_data);
   1635  }
   1636 
   1637  if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
   1638    /* If we're attaching streams ourself, or if this connection is
   1639     * a tunneled directory connection, then just attach it. */
   1640    ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
   1641    circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
   1642    connection_ap_mark_as_pending_circuit(conn);
   1643  } else {
   1644    connection_entry_set_controller_wait(conn);
   1645    circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
   1646  }
   1647  return 0;
   1648 }
   1649 
   1650 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
   1651 * reject depending on our config options. */
   1652 static int
   1653 consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
   1654 {
   1655  const or_options_t *options = get_options();
   1656  int reject = smartlist_contains_int_as_string(
   1657                                     options->RejectPlaintextPorts, port);
   1658 
   1659  if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
   1660    log_warn(LD_APP, "Application request to port %d: this port is "
   1661             "commonly used for unencrypted protocols. Please make sure "
   1662             "you don't send anything you would mind the rest of the "
   1663             "Internet reading!%s", port, reject ? " Closing." : "");
   1664    control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
   1665                                port, reject ? "REJECT" : "WARN");
   1666  }
   1667 
   1668  if (reject) {
   1669    log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
   1670    connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   1671    return -1;
   1672  }
   1673 
   1674  return 0;
   1675 }
   1676 
   1677 /** Parse the given hostname in address. Returns true if the parsing was
   1678 * successful and type_out contains the type of the hostname. Else, false is
   1679 * returned which means it was not recognized and type_out is set to
   1680 * BAD_HOSTNAME.
   1681 *
   1682 * The possible recognized forms are (where true is returned):
   1683 *
   1684 *  If address is of the form "y.onion" with a well-formed handle y:
   1685 *     Put a NUL after y, lower-case it, and return ONION_V3_HOSTNAME
   1686 *     depending on the HS version.
   1687 *
   1688 *  If address is of the form "x.y.onion" with a well-formed handle x:
   1689 *     Drop "x.", put a NUL after y, lower-case it, and return
   1690 *     ONION_V3_HOSTNAME depending on the HS version.
   1691 *
   1692 * If address is of the form "y.onion" with a badly-formed handle y:
   1693 *     Return BAD_HOSTNAME and log a message.
   1694 *
   1695 * If address is of the form "y.exit":
   1696 *     Put a NUL after y and return EXIT_HOSTNAME.
   1697 *
   1698 * Otherwise:
   1699 *     Return NORMAL_HOSTNAME and change nothing.
   1700 */
   1701 STATIC bool
   1702 parse_extended_hostname(char *address, hostname_type_t *type_out)
   1703 {
   1704  char *s;
   1705  char *q;
   1706  char query[HS_SERVICE_ADDR_LEN_BASE32+1];
   1707 
   1708  s = strrchr(address,'.');
   1709  if (!s) {
   1710    *type_out = NORMAL_HOSTNAME; /* no dot, thus normal */
   1711    goto success;
   1712  }
   1713  if (!strcmp(s+1,"exit")) {
   1714    *s = 0; /* NUL-terminate it */
   1715    *type_out = EXIT_HOSTNAME; /* .exit */
   1716    goto success;
   1717  }
   1718  if (strcmp(s+1,"onion")) {
   1719    *type_out = NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
   1720    goto success;
   1721  }
   1722 
   1723  /* so it is .onion */
   1724  *s = 0; /* NUL-terminate it */
   1725  /* locate a 'sub-domain' component, in order to remove it */
   1726  q = strrchr(address, '.');
   1727  if (q == address) {
   1728    *type_out = BAD_HOSTNAME;
   1729    goto failed; /* reject sub-domain, as DNS does */
   1730  }
   1731  q = (NULL == q) ? address : q + 1;
   1732  if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
   1733      HS_SERVICE_ADDR_LEN_BASE32+1) {
   1734    *type_out = BAD_HOSTNAME;
   1735    goto failed;
   1736  }
   1737  if (q != address) {
   1738    memmove(address, q, strlen(q) + 1 /* also get \0 */);
   1739  }
   1740 
   1741  /* v3 onion address check. */
   1742  if (strlen(query) == HS_SERVICE_ADDR_LEN_BASE32) {
   1743    *type_out = ONION_V3_HOSTNAME;
   1744    if (hs_address_is_valid(query)) {
   1745      goto success;
   1746    }
   1747    goto failed;
   1748  }
   1749 
   1750  /* Reaching this point, nothing was recognized. */
   1751  *type_out = BAD_HOSTNAME;
   1752  goto failed;
   1753 
   1754 success:
   1755  return true;
   1756 failed:
   1757  /* otherwise, return to previous state and return 0 */
   1758  *s = '.';
   1759  const bool is_onion = (*type_out == ONION_V3_HOSTNAME);
   1760  log_warn(LD_APP, "Invalid %shostname %s; rejecting",
   1761           is_onion ? "onion " : "",
   1762           safe_str_client(address));
   1763  if (*type_out == ONION_V3_HOSTNAME) {
   1764      *type_out = BAD_HOSTNAME;
   1765  }
   1766  return false;
   1767 }
   1768 
   1769 /** How many times do we try connecting with an exit configured via
   1770 * TrackHostExits before concluding that it won't work any more and trying a
   1771 * different one? */
   1772 #define TRACKHOSTEXITS_RETRIES 5
   1773 
   1774 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
   1775 *  asked us to leave streams unattached. Return 0 in that case.
   1776 *
   1777 *  See connection_ap_handshake_rewrite_and_attach()'s
   1778 *  documentation for arguments and return value.
   1779 */
   1780 MOCK_IMPL(int,
   1781 connection_ap_rewrite_and_attach_if_allowed,(entry_connection_t *conn,
   1782                                             origin_circuit_t *circ,
   1783                                             crypt_path_t *cpath))
   1784 {
   1785  const or_options_t *options = get_options();
   1786 
   1787  if (options->LeaveStreamsUnattached) {
   1788    connection_entry_set_controller_wait(conn);
   1789    return 0;
   1790  }
   1791  return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
   1792 }
   1793 
   1794 /* Try to perform any map-based rewriting of the target address in
   1795 * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
   1796 * conn->socks_request.address as appropriate.
   1797 */
   1798 STATIC void
   1799 connection_ap_handshake_rewrite(entry_connection_t *conn,
   1800                                rewrite_result_t *out)
   1801 {
   1802  socks_request_t *socks = conn->socks_request;
   1803  const or_options_t *options = get_options();
   1804  tor_addr_t addr_tmp;
   1805 
   1806  /* Initialize all the fields of 'out' to reasonable defaults */
   1807  out->automap = 0;
   1808  out->exit_source = ADDRMAPSRC_NONE;
   1809  out->map_expires = TIME_MAX;
   1810  out->end_reason = 0;
   1811  out->should_close = 0;
   1812  out->orig_address[0] = 0;
   1813 
   1814  /* We convert all incoming addresses to lowercase. */
   1815  tor_strlower(socks->address);
   1816  /* Remember the original address. */
   1817  strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
   1818  log_debug(LD_APP,"Client asked for %s:%d",
   1819            safe_str_client(socks->address),
   1820            socks->port);
   1821 
   1822  /* Check for whether this is a .exit address.  By default, those are
   1823   * disallowed when they're coming straight from the client, but you're
   1824   * allowed to have them in MapAddress commands and so forth. */
   1825  if (!strcmpend(socks->address, ".exit")) {
   1826    static ratelim_t exit_warning_limit = RATELIM_INIT(60*15);
   1827    log_fn_ratelim(&exit_warning_limit, LOG_WARN, LD_APP,
   1828                   "The  \".exit\" notation is disabled in Tor due to "
   1829                   "security risks.");
   1830    control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
   1831                                escaped(socks->address));
   1832    out->end_reason = END_STREAM_REASON_TORPROTOCOL;
   1833    out->should_close = 1;
   1834    return;
   1835  }
   1836 
   1837  /* Remember the original address so we can tell the user about what
   1838   * they actually said, not just what it turned into. */
   1839  /* XXX yes, this is the same as out->orig_address above. One is
   1840   * in the output, and one is in the connection. */
   1841  if (! conn->original_dest_address) {
   1842    /* Is the 'if' necessary here? XXXX */
   1843    conn->original_dest_address = tor_strdup(conn->socks_request->address);
   1844  }
   1845 
   1846  /* First, apply MapAddress and MAPADDRESS mappings. We need to do
   1847   * these only for non-reverse lookups, since they don't exist for those.
   1848   * We also need to do this before we consider automapping, since we might
   1849   * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
   1850   * we'd need to automap it. */
   1851  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
   1852    const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
   1853    if (addressmap_rewrite(socks->address, sizeof(socks->address),
   1854                       rewrite_flags, &out->map_expires, &out->exit_source)) {
   1855      control_event_stream_status(conn, STREAM_EVENT_REMAP,
   1856                                  REMAP_STREAM_SOURCE_CACHE);
   1857    }
   1858  }
   1859 
   1860  /* Now see if we need to create or return an existing Hostname->IP
   1861   * automapping.  Automapping happens when we're asked to resolve a
   1862   * hostname, and AutomapHostsOnResolve is set, and the hostname has a
   1863   * suffix listed in AutomapHostsSuffixes.  It's a handy feature
   1864   * that lets you have Tor assign e.g. IPv6 addresses for .onion
   1865   * names, and return them safely from DNSPort.
   1866   */
   1867  if (socks->command == SOCKS_COMMAND_RESOLVE &&
   1868      tor_addr_parse(&addr_tmp, socks->address)<0 &&
   1869      options->AutomapHostsOnResolve) {
   1870    /* Check the suffix... */
   1871    out->automap = addressmap_address_should_automap(socks->address, options);
   1872    if (out->automap) {
   1873      /* If we get here, then we should apply an automapping for this. */
   1874      const char *new_addr;
   1875      /* We return an IPv4 address by default, or an IPv6 address if we
   1876       * are allowed to do so. */
   1877      int addr_type = RESOLVED_TYPE_IPV4;
   1878      if (conn->socks_request->socks_version != 4) {
   1879        if (!conn->entry_cfg.ipv4_traffic ||
   1880            (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
   1881            conn->entry_cfg.prefer_ipv6_virtaddr)
   1882          addr_type = RESOLVED_TYPE_IPV6;
   1883      }
   1884      /* Okay, register the target address as automapped, and find the new
   1885       * address we're supposed to give as a resolve answer.  (Return a cached
   1886       * value if we've looked up this address before.
   1887       */
   1888      new_addr = addressmap_register_virtual_address(
   1889                                    addr_type, tor_strdup(socks->address));
   1890      if (! new_addr) {
   1891        log_warn(LD_APP, "Unable to automap address %s",
   1892                 escaped_safe_str(socks->address));
   1893        out->end_reason = END_STREAM_REASON_INTERNAL;
   1894        out->should_close = 1;
   1895        return;
   1896      }
   1897      log_info(LD_APP, "Automapping %s to %s",
   1898               escaped_safe_str_client(socks->address),
   1899               safe_str_client(new_addr));
   1900      strlcpy(socks->address, new_addr, sizeof(socks->address));
   1901    }
   1902  }
   1903 
   1904  /* Now handle reverse lookups, if they're in the cache.  This doesn't
   1905   * happen too often, since client-side DNS caching is off by default,
   1906   * and very deprecated. */
   1907  if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
   1908    unsigned rewrite_flags = 0;
   1909    if (conn->entry_cfg.use_cached_ipv4_answers)
   1910      rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
   1911    if (conn->entry_cfg.use_cached_ipv6_answers)
   1912      rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
   1913 
   1914    if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
   1915                                   rewrite_flags, &out->map_expires)) {
   1916      char *result = tor_strdup(socks->address);
   1917      /* remember _what_ is supposed to have been resolved. */
   1918      tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
   1919                   out->orig_address);
   1920      connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
   1921                                             strlen(result), (uint8_t*)result,
   1922                                             -1,
   1923                                             out->map_expires);
   1924      tor_free(result);
   1925      out->end_reason = END_STREAM_REASON_DONE |
   1926                        END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
   1927      out->should_close = 1;
   1928      return;
   1929    }
   1930 
   1931    /* Hang on, did we find an answer saying that this is a reverse lookup for
   1932     * an internal address?  If so, we should reject it if we're configured to
   1933     * do so. */
   1934    if (options->ClientDNSRejectInternalAddresses) {
   1935      /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
   1936      tor_addr_t addr;
   1937      int ok;
   1938      ok = tor_addr_parse_PTR_name(
   1939                               &addr, socks->address, AF_UNSPEC, 1);
   1940      if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
   1941        connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
   1942                                               0, NULL, -1, TIME_MAX);
   1943        out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
   1944                          END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
   1945        out->should_close = 1;
   1946        return;
   1947      }
   1948    }
   1949  }
   1950 
   1951  /* If we didn't automap it before, then this is still the address that
   1952   * came straight from the user, mapped according to any
   1953   * MapAddress/MAPADDRESS commands.  Now apply other mappings,
   1954   * including previously registered Automap entries (IP back to
   1955   * hostname), TrackHostExits entries, and client-side DNS cache
   1956   * entries (if they're turned on).
   1957   */
   1958  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
   1959      !out->automap) {
   1960    unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
   1961    addressmap_entry_source_t exit_source2;
   1962    if (conn->entry_cfg.use_cached_ipv4_answers)
   1963      rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
   1964    if (conn->entry_cfg.use_cached_ipv6_answers)
   1965      rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
   1966    if (addressmap_rewrite(socks->address, sizeof(socks->address),
   1967                        rewrite_flags, &out->map_expires, &exit_source2)) {
   1968      control_event_stream_status(conn, STREAM_EVENT_REMAP,
   1969                                  REMAP_STREAM_SOURCE_CACHE);
   1970    }
   1971    if (out->exit_source == ADDRMAPSRC_NONE) {
   1972      /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
   1973       * the original source of a .exit. */
   1974      out->exit_source = exit_source2;
   1975    }
   1976  }
   1977 
   1978  /* Check to see whether we're about to use an address in the virtual
   1979   * range without actually having gotten it from an Automap. */
   1980  if (!out->automap && address_is_in_virtual_range(socks->address)) {
   1981    /* This address was probably handed out by
   1982     * client_dns_get_unmapped_address, but the mapping was discarded for some
   1983     * reason.  Or the user typed in a virtual address range manually.  We
   1984     * *don't* want to send the address through Tor; that's likely to fail,
   1985     * and may leak information.
   1986     */
   1987    log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
   1988             safe_str_client(socks->address));
   1989    out->end_reason = END_STREAM_REASON_INTERNAL;
   1990    out->should_close = 1;
   1991    return;
   1992  }
   1993 }
   1994 
   1995 /** We just received a SOCKS request in <b>conn</b> to a v3 onion. Start
   1996 *  connecting to the onion service. */
   1997 static int
   1998 connection_ap_handle_onion(entry_connection_t *conn,
   1999                           socks_request_t *socks,
   2000                           origin_circuit_t *circ)
   2001 {
   2002  int retval;
   2003  time_t now = approx_time();
   2004  connection_t *base_conn = ENTRY_TO_CONN(conn);
   2005 
   2006  /* If .onion address requests are disabled, refuse the request */
   2007  if (!conn->entry_cfg.onion_traffic) {
   2008    log_warn(LD_APP, "Onion address %s requested from a port with .onion "
   2009             "disabled", safe_str_client(socks->address));
   2010    connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2011    return -1;
   2012  }
   2013 
   2014  /* Check whether it's RESOLVE or RESOLVE_PTR.  We don't handle those
   2015   * for hidden service addresses. */
   2016  if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
   2017    /* if it's a resolve request, fail it right now, rather than
   2018     * building all the circuits and then realizing it won't work. */
   2019    log_warn(LD_APP,
   2020             "Resolve requests to hidden services not allowed. Failing.");
   2021    connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
   2022                                           0,NULL,-1,TIME_MAX);
   2023    connection_mark_unattached_ap(conn,
   2024                               END_STREAM_REASON_SOCKSPROTOCOL |
   2025                               END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
   2026    return -1;
   2027  }
   2028 
   2029  /* If we were passed a circuit, then we need to fail.  .onion addresses
   2030   * only work when we launch our own circuits for now. */
   2031  if (circ) {
   2032    log_warn(LD_CONTROL, "Attachstream to a circuit is not "
   2033             "supported for .onion addresses currently. Failing.");
   2034    connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2035    return -1;
   2036  }
   2037 
   2038  int descriptor_is_usable = 0;
   2039 
   2040  /* Create HS conn identifier with HS pubkey */
   2041  hs_ident_edge_conn_t *hs_conn_ident =
   2042    tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
   2043 
   2044  retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
   2045                            NULL, NULL);
   2046  if (retval < 0) {
   2047    log_warn(LD_GENERAL, "failed to parse hs address");
   2048    tor_free(hs_conn_ident);
   2049    return -1;
   2050  }
   2051  ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
   2052 
   2053  /* Check the v3 desc cache */
   2054  const hs_descriptor_t *cached_desc = NULL;
   2055  unsigned int refetch_desc = 0;
   2056  cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
   2057  if (cached_desc) {
   2058    descriptor_is_usable =
   2059      hs_client_any_intro_points_usable(&hs_conn_ident->identity_pk,
   2060                                        cached_desc);
   2061    /* Check if PoW parameters have expired. If yes, the descriptor is
   2062     * unusable. */
   2063    if (cached_desc->encrypted_data.pow_params) {
   2064      if (cached_desc->encrypted_data.pow_params->expiration_time <
   2065          approx_time()) {
   2066        log_info(LD_REND, "Descriptor PoW parameters have expired.");
   2067        descriptor_is_usable = 0;
   2068      } else {
   2069        /* Mark that the connection is to an HS with PoW defenses on. */
   2070        conn->hs_with_pow_conn = 1;
   2071      }
   2072    }
   2073 
   2074    log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
   2075             (descriptor_is_usable) ? "usable" : "unusable",
   2076             safe_str_client(socks->address),
   2077             (descriptor_is_usable) ? "Not fetching." : "Refetching.");
   2078  } else {
   2079    /* We couldn't find this descriptor; we should look it up. */
   2080    log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
   2081             safe_str_client(socks->address));
   2082    refetch_desc = 1;
   2083  }
   2084 
   2085  /* Help predict that we'll want to do hidden service circuits in the
   2086   * future. We're not sure if it will need a stable circuit yet, but
   2087   * we know we'll need *something*. */
   2088  rep_hist_note_used_internal(now, 0, 1);
   2089 
   2090  /* Now we have a descriptor but is it usable or not? If not, refetch.
   2091   * Also, a fetch could have been requested if the onion address was not
   2092   * found in the cache previously. */
   2093  if (refetch_desc || !descriptor_is_usable) {
   2094    edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
   2095    connection_ap_mark_as_non_pending_circuit(conn);
   2096    base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
   2097    tor_assert(edge_conn->hs_ident);
   2098    /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
   2099     * went and act accordingly. */
   2100    int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
   2101    switch (ret) {
   2102    case HS_CLIENT_FETCH_MISSING_INFO:
   2103      /* Keeping the connection in descriptor wait state is fine because
   2104       * once we get enough dirinfo or a new live consensus, the HS client
   2105       * subsystem is notified and every connection in that state will
   2106       * trigger a fetch for the service key. */
   2107    case HS_CLIENT_FETCH_LAUNCHED:
   2108    case HS_CLIENT_FETCH_PENDING:
   2109    case HS_CLIENT_FETCH_HAVE_DESC:
   2110      return 0;
   2111    case HS_CLIENT_FETCH_ERROR:
   2112    case HS_CLIENT_FETCH_NO_HSDIRS:
   2113    case HS_CLIENT_FETCH_NOT_ALLOWED:
   2114      /* Can't proceed further and better close the SOCKS request. */
   2115      return -1;
   2116    }
   2117  }
   2118 
   2119  /* We have the descriptor!  So launch a connection to the HS. */
   2120  log_info(LD_REND, "Descriptor is here. Great.");
   2121 
   2122  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
   2123  /* We'll try to attach it at the next event loop, or whenever
   2124   * we call connection_ap_attach_pending() */
   2125  connection_ap_mark_as_pending_circuit(conn);
   2126  return 0;
   2127 }
   2128 
   2129 /** Connection <b>conn</b> just finished its socks handshake, or the
   2130 * controller asked us to take care of it. If <b>circ</b> is defined,
   2131 * then that's where we'll want to attach it. Otherwise we have to
   2132 * figure it out ourselves.
   2133 *
   2134 * First, parse whether it's a .exit address, remap it, and so on. Then
   2135 * if it's for a general circuit, try to attach it to a circuit (or launch
   2136 * one as needed), else if it's for a rendezvous circuit, fetch a
   2137 * rendezvous descriptor first (or attach/launch a circuit if the
   2138 * rendezvous descriptor is already here and fresh enough).
   2139 *
   2140 * The stream will exit from the hop
   2141 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
   2142 * <b>cpath</b> is NULL.
   2143 */
   2144 int
   2145 connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
   2146                                           origin_circuit_t *circ,
   2147                                           crypt_path_t *cpath)
   2148 {
   2149  socks_request_t *socks = conn->socks_request;
   2150  const or_options_t *options = get_options();
   2151  connection_t *base_conn = ENTRY_TO_CONN(conn);
   2152  time_t now = time(NULL);
   2153  rewrite_result_t rr;
   2154 
   2155  /* First we'll do the rewrite part.  Let's see if we get a reasonable
   2156   * answer.
   2157   */
   2158  memset(&rr, 0, sizeof(rr));
   2159  connection_ap_handshake_rewrite(conn,&rr);
   2160 
   2161  if (rr.should_close) {
   2162    /* connection_ap_handshake_rewrite told us to close the connection:
   2163     * either because it sent back an answer, or because it sent back an
   2164     * error */
   2165    connection_mark_unattached_ap(conn, rr.end_reason);
   2166    if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
   2167      return 0;
   2168    else
   2169      return -1;
   2170  }
   2171 
   2172  const time_t map_expires = rr.map_expires;
   2173  const int automap = rr.automap;
   2174  const addressmap_entry_source_t exit_source = rr.exit_source;
   2175 
   2176  /* Now see whether the hostname is bogus.  This could happen because of an
   2177   * onion hostname whose format we don't recognize. */
   2178  hostname_type_t addresstype;
   2179  if (!parse_extended_hostname(socks->address, &addresstype)) {
   2180    control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
   2181                                escaped(socks->address));
   2182    if (addresstype == BAD_HOSTNAME) {
   2183      conn->socks_request->socks_extended_error_code = SOCKS5_HS_BAD_ADDRESS;
   2184    }
   2185    connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2186    return -1;
   2187  }
   2188 
   2189  /* If this is a .exit hostname, strip off the .name.exit part, and
   2190   * see whether we're willing to connect there, and otherwise handle the
   2191   * .exit address.
   2192   *
   2193   * We'll set chosen_exit_name and/or close the connection as appropriate.
   2194   */
   2195  if (addresstype == EXIT_HOSTNAME) {
   2196    /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
   2197     * not ExcludeExitNodes. */
   2198    routerset_t *excludeset = options->StrictNodes ?
   2199      options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
   2200    const node_t *node = NULL;
   2201 
   2202    /* If this .exit was added by an AUTOMAP, then it came straight from
   2203     * a user.  That's not safe. */
   2204    if (exit_source == ADDRMAPSRC_AUTOMAP) {
   2205      /* Whoops; this one is stale.  It must have gotten added earlier?
   2206       * (Probably this is not possible, since AllowDotExit no longer
   2207       * exists.) */
   2208      log_warn(LD_APP,"Stale automapped address for '%s.$fp.exit'. Refusing.",
   2209               safe_str_client(socks->address));
   2210      control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
   2211                                  escaped(socks->address));
   2212      connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2213      tor_assert_nonfatal_unreached();
   2214      return -1;
   2215    }
   2216 
   2217    /* Double-check to make sure there are no .exits coming from
   2218     * impossible/weird sources. */
   2219    if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
   2220      /* It shouldn't be possible to get a .exit address from any of these
   2221       * sources. */
   2222      log_warn(LD_BUG,"Address '%s.$fp.exit', with impossible source for the "
   2223               ".exit part. Refusing.",
   2224               safe_str_client(socks->address));
   2225      control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
   2226                                  escaped(socks->address));
   2227      connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2228      return -1;
   2229    }
   2230 
   2231    tor_assert(!automap);
   2232 
   2233    /* Now, find the character before the .(name) part.
   2234     * (The ".exit" part got stripped off by "parse_extended_hostname").
   2235     *
   2236     * We're going to put the exit name into conn->chosen_exit_name, and
   2237     * look up a node correspondingly. */
   2238    char *s = strrchr(socks->address,'.');
   2239    if (s) {
   2240      /* The address was of the form "(stuff).(name).exit */
   2241      if (s[1] != '\0') {
   2242        /* Looks like a real .exit one. */
   2243        conn->chosen_exit_name = tor_strdup(s+1);
   2244        node = node_get_by_nickname(conn->chosen_exit_name, 0);
   2245 
   2246        if (exit_source == ADDRMAPSRC_TRACKEXIT) {
   2247          /* We 5 tries before it expires the addressmap */
   2248          conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
   2249        }
   2250        *s = 0;
   2251      } else {
   2252        /* Oops, the address was (stuff)..exit.  That's not okay. */
   2253        log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
   2254                 safe_str_client(socks->address));
   2255        control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
   2256                                    escaped(socks->address));
   2257        connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2258        return -1;
   2259      }
   2260    } else {
   2261      /* It looks like they just asked for "foo.exit".  That's a special
   2262       * form that means (foo's address).foo.exit. */
   2263 
   2264      conn->chosen_exit_name = tor_strdup(socks->address);
   2265      node = node_get_by_nickname(conn->chosen_exit_name, 0);
   2266      if (node) {
   2267        *socks->address = 0;
   2268        node_get_address_string(node, socks->address, sizeof(socks->address));
   2269      }
   2270    }
   2271 
   2272    /* Now make sure that the chosen exit exists... */
   2273    if (!node) {
   2274      log_warn(LD_APP,
   2275               "Unrecognized relay in exit address '%s.$fp.exit'. Refusing.",
   2276               safe_str_client(socks->address));
   2277      connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2278      return -1;
   2279    }
   2280    /* ...and make sure that it isn't excluded. */
   2281    if (routerset_contains_node(excludeset, node)) {
   2282      log_warn(LD_APP,
   2283               "Excluded relay in exit address '%s.$fp.exit'. Refusing.",
   2284               safe_str_client(socks->address));
   2285      connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2286      return -1;
   2287    }
   2288    /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
   2289       Bar is not listed in it?  I say yes, but our revised manpage branch
   2290       implies no. */
   2291  }
   2292 
   2293  /* Now, we handle everything that isn't a .onion address. */
   2294  if (addresstype != ONION_V3_HOSTNAME) {
   2295    /* Not a hidden-service request.  It's either a hostname or an IP,
   2296     * possibly with a .exit that we stripped off.  We're going to check
   2297     * if we're allowed to connect/resolve there, and then launch the
   2298     * appropriate request. */
   2299 
   2300    /* Check for funny characters in the address. */
   2301    if (address_is_invalid_destination(socks->address, 1)) {
   2302      control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
   2303                                  escaped(socks->address));
   2304      log_warn(LD_APP,
   2305               "Destination '%s' seems to be an invalid hostname. Failing.",
   2306               safe_str_client(socks->address));
   2307      connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2308      return -1;
   2309    }
   2310 
   2311    /* socks->address is a non-onion hostname or IP address.
   2312     * If we can't do any non-onion requests, refuse the connection.
   2313     * If we have a hostname but can't do DNS, refuse the connection.
   2314     * If we have an IP address, but we can't use that address family,
   2315     * refuse the connection.
   2316     *
   2317     * If we can do DNS requests, and we can use at least one address family,
   2318     * then we have to resolve the address first. Then we'll know if it
   2319     * resolves to a usable address family. */
   2320 
   2321    /* First, check if all non-onion traffic is disabled */
   2322    if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
   2323        && !conn->entry_cfg.ipv6_traffic) {
   2324        log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
   2325                 "or IP address %s because Port has OnionTrafficOnly set (or "
   2326                 "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
   2327                 safe_str_client(socks->address));
   2328        connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2329        return -1;
   2330    }
   2331 
   2332    /* Then check if we have a hostname or IP address, and whether DNS or
   2333     * the IP address family are permitted.  Reject if not. */
   2334    tor_addr_t dummy_addr;
   2335    int socks_family = tor_addr_parse(&dummy_addr, socks->address);
   2336    /* family will be -1 for a non-onion hostname that's not an IP */
   2337    if (socks_family == -1) {
   2338      if (!conn->entry_cfg.dns_request) {
   2339        log_warn(LD_APP, "Refusing to connect to hostname %s "
   2340                 "because Port has NoDNSRequest set.",
   2341                 safe_str_client(socks->address));
   2342        connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2343        return -1;
   2344      }
   2345    } else if (socks_family == AF_INET) {
   2346      if (!conn->entry_cfg.ipv4_traffic) {
   2347        log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
   2348                 "Port has NoIPv4Traffic set.",
   2349                 safe_str_client(socks->address));
   2350        connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2351        return -1;
   2352      }
   2353    } else if (socks_family == AF_INET6) {
   2354      if (!conn->entry_cfg.ipv6_traffic) {
   2355        log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
   2356                 "Port has NoIPv6Traffic set.",
   2357                 safe_str_client(socks->address));
   2358        connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2359        return -1;
   2360      }
   2361    } else {
   2362      tor_assert_nonfatal_unreached_once();
   2363    }
   2364 
   2365    /* See if this is a hostname lookup that we can answer immediately.
   2366     * (For example, an attempt to look up the IP address for an IP address.)
   2367     */
   2368    if (socks->command == SOCKS_COMMAND_RESOLVE) {
   2369      tor_addr_t answer;
   2370      /* Reply to resolves immediately if we can. */
   2371      if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
   2372        /* remember _what_ is supposed to have been resolved. */
   2373        strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
   2374        connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
   2375                                                    map_expires);
   2376        connection_mark_unattached_ap(conn,
   2377                                END_STREAM_REASON_DONE |
   2378                                END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
   2379        return 0;
   2380      }
   2381      tor_assert(!automap);
   2382      rep_hist_note_used_resolve(now); /* help predict this next time */
   2383    } else if (socks->command == SOCKS_COMMAND_CONNECT) {
   2384      /* Now see if this is a connect request that we can reject immediately */
   2385 
   2386      tor_assert(!automap);
   2387      /* Don't allow connections to port 0. */
   2388      if (socks->port == 0) {
   2389        log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
   2390        connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2391        return -1;
   2392      }
   2393      /* You can't make connections to internal addresses, by default.
   2394       * Exceptions are begindir requests (where the address is meaningless),
   2395       * or cases where you've hand-configured a particular exit, thereby
   2396       * making the local address meaningful. */
   2397      if (options->ClientRejectInternalAddresses &&
   2398          !conn->use_begindir && !conn->chosen_exit_name && !circ) {
   2399        /* If we reach this point then we don't want to allow internal
   2400         * addresses.  Check if we got one. */
   2401        tor_addr_t addr;
   2402        if (tor_addr_hostname_is_local(socks->address) ||
   2403            (tor_addr_parse(&addr, socks->address) >= 0 &&
   2404             tor_addr_is_internal(&addr, 0))) {
   2405          /* If this is an explicit private address with no chosen exit node,
   2406           * then we really don't want to try to connect to it.  That's
   2407           * probably an error. */
   2408          if (conn->is_transparent_ap) {
   2409 #define WARN_INTRVL_LOOP 300
   2410            static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
   2411            char *m;
   2412            if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
   2413              log_warn(LD_NET,
   2414                       "Rejecting request for anonymous connection to private "
   2415                       "address %s on a TransPort or NATDPort.  Possible loop "
   2416                       "in your NAT rules?%s", safe_str_client(socks->address),
   2417                       m);
   2418              tor_free(m);
   2419            }
   2420          } else {
   2421 #define WARN_INTRVL_PRIV 300
   2422            static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
   2423            char *m;
   2424            if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
   2425              log_warn(LD_NET,
   2426                       "Rejecting SOCKS request for anonymous connection to "
   2427                       "private address %s.%s",
   2428                       safe_str_client(socks->address),m);
   2429              tor_free(m);
   2430            }
   2431          }
   2432          connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
   2433          return -1;
   2434        }
   2435      } /* end "if we should check for internal addresses" */
   2436 
   2437      /* Okay.  We're still doing a CONNECT, and it wasn't a private
   2438       * address.  Here we do special handling for literal IP addresses,
   2439       * to see if we should reject this preemptively, and to set up
   2440       * fields in conn->entry_cfg to tell the exit what AF we want. */
   2441      {
   2442        tor_addr_t addr;
   2443        /* XXX Duplicate call to tor_addr_parse. */
   2444        if (tor_addr_parse(&addr, socks->address) >= 0) {
   2445          /* If we reach this point, it's an IPv4 or an IPv6 address. */
   2446          sa_family_t family = tor_addr_family(&addr);
   2447 
   2448          if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
   2449              (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
   2450            /* You can't do an IPv4 address on a v6-only socks listener,
   2451             * or vice versa. */
   2452            log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
   2453                     "family that this listener does not support.");
   2454            connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2455            return -1;
   2456          } else if (family == AF_INET6 && socks->socks_version == 4) {
   2457            /* You can't make a socks4 request to an IPv6 address. Socks4
   2458             * doesn't support that. */
   2459            log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
   2460            connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2461            return -1;
   2462          } else if (socks->socks_version == 4 &&
   2463                     !conn->entry_cfg.ipv4_traffic) {
   2464            /* You can't do any kind of Socks4 request when IPv4 is forbidden.
   2465             *
   2466             * XXX raise this check outside the enclosing block? */
   2467            log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
   2468                     "no IPv4 traffic supported.");
   2469            connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
   2470            return -1;
   2471          } else if (family == AF_INET6) {
   2472            /* Tell the exit: we won't accept any ipv4 connection to an IPv6
   2473             * address. */
   2474            conn->entry_cfg.ipv4_traffic = 0;
   2475          } else if (family == AF_INET) {
   2476            /* Tell the exit: we won't accept any ipv6 connection to an IPv4
   2477             * address. */
   2478            conn->entry_cfg.ipv6_traffic = 0;
   2479          }
   2480 
   2481          /* Next, yet another check: we know it's a direct IP address. Is it
   2482           * the IP address of a known relay and its ORPort, or of a directory
   2483           * authority and its OR or Dir Port? If so, and if a consensus param
   2484           * says to, then exit relays will refuse this request (see ticket
   2485           * 2667 for details). Let's just refuse it locally right now, to
   2486           * save time and network load but also to give the user a more
   2487           * useful log message. */
   2488          if (!network_reentry_is_allowed() &&
   2489              nodelist_reentry_contains(&addr, socks->port)) {
   2490            log_warn(LD_APP, "Not attempting connection to %s:%d because "
   2491                     "the network would reject it. Are you trying to send "
   2492                     "Tor traffic over Tor? This traffic can be harmful to "
   2493                     "the Tor network. If you really need it, try using "
   2494                     "a bridge as a workaround.",
   2495                     safe_str_client(socks->address), socks->port);
   2496            connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
   2497            return -1;
   2498          }
   2499        }
   2500      }
   2501 
   2502      /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
   2503      if (socks->socks_version == 4)
   2504        conn->entry_cfg.ipv6_traffic = 0;
   2505 
   2506      /* Still handling CONNECT. Now, check for exit enclaves.  (Which we
   2507       * don't do on BEGIN_DIR, or when there is a chosen exit.)
   2508       *
   2509       * TODO: Should we remove this?  Exit enclaves are nutty and don't
   2510       * work very well
   2511       */
   2512      if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
   2513        /* see if we can find a suitable enclave exit */
   2514        const node_t *r =
   2515          router_find_exact_exit_enclave(socks->address, socks->port);
   2516        if (r) {
   2517          log_info(LD_APP,
   2518                   "Redirecting address %s to exit at enclave router %s",
   2519                   safe_str_client(socks->address), node_describe(r));
   2520          /* use the hex digest, not nickname, in case there are two
   2521             routers with this nickname */
   2522          conn->chosen_exit_name =
   2523            tor_strdup(hex_str(r->identity, DIGEST_LEN));
   2524          conn->chosen_exit_optional = 1;
   2525        }
   2526      }
   2527 
   2528      /* Still handling CONNECT: warn or reject if it's using a dangerous
   2529       * port. */
   2530      if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
   2531        if (consider_plaintext_ports(conn, socks->port) < 0)
   2532          return -1;
   2533 
   2534      /* Remember the port so that we will predict that more requests
   2535         there will happen in the future. */
   2536      if (!conn->use_begindir) {
   2537        /* help predict this next time */
   2538        rep_hist_note_used_port(now, socks->port);
   2539      }
   2540    } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
   2541      rep_hist_note_used_resolve(now); /* help predict this next time */
   2542      /* no extra processing needed */
   2543    } else {
   2544      /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
   2545      tor_fragile_assert();
   2546    }
   2547 
   2548    /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
   2549     * address, and decided not to reject it for any number of reasons. Now
   2550     * mark the connection as waiting for a circuit, and try to attach it!
   2551     */
   2552    base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
   2553 
   2554    /* If we were given a circuit to attach to, try to attach. Otherwise,
   2555     * try to find a good one and attach to that. */
   2556    int rv;
   2557    if (circ) {
   2558      rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
   2559    } else {
   2560      /* We'll try to attach it at the next event loop, or whenever
   2561       * we call connection_ap_attach_pending() */
   2562      connection_ap_mark_as_pending_circuit(conn);
   2563      rv = 0;
   2564    }
   2565 
   2566    /* If the above function returned 0 then we're waiting for a circuit.
   2567     * if it returned 1, we're attached.  Both are okay.  But if it returned
   2568     * -1, there was an error, so make sure the connection is marked, and
   2569     * return -1. */
   2570    if (rv < 0) {
   2571      if (!base_conn->marked_for_close)
   2572        connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
   2573      return -1;
   2574    }
   2575 
   2576    return 0;
   2577  } else {
   2578    /* If we get here, it's a request for a .onion address! */
   2579    tor_assert(addresstype == ONION_V3_HOSTNAME);
   2580    tor_assert(!automap);
   2581    return connection_ap_handle_onion(conn, socks, circ);
   2582  }
   2583 
   2584  return 0; /* unreached but keeps the compiler happy */
   2585 }
   2586 
   2587 #ifdef TRANS_PF
   2588 static int pf_socket = -1;
   2589 int
   2590 get_pf_socket(void)
   2591 {
   2592  int pf;
   2593  /*  This should be opened before dropping privileges. */
   2594  if (pf_socket >= 0)
   2595    return pf_socket;
   2596 
   2597 #if defined(OpenBSD)
   2598  /* only works on OpenBSD */
   2599  pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
   2600 #else
   2601  /* works on NetBSD and FreeBSD */
   2602  pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
   2603 #endif /* defined(OpenBSD) */
   2604 
   2605  if (pf < 0) {
   2606    log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
   2607    return -1;
   2608  }
   2609 
   2610  pf_socket = pf;
   2611  return pf_socket;
   2612 }
   2613 #endif /* defined(TRANS_PF) */
   2614 
   2615 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
   2616  defined(TRANS_TPROXY)
   2617 /** Try fill in the address of <b>req</b> from the socket configured
   2618 * with <b>conn</b>. */
   2619 static int
   2620 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
   2621 {
   2622  struct sockaddr_storage orig_dst;
   2623  socklen_t orig_dst_len = sizeof(orig_dst);
   2624  tor_addr_t addr;
   2625 
   2626 #ifdef TRANS_TPROXY
   2627  if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
   2628    if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
   2629                    &orig_dst_len) < 0) {
   2630      int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
   2631      log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
   2632      return -1;
   2633    }
   2634    goto done;
   2635  }
   2636 #endif /* defined(TRANS_TPROXY) */
   2637 
   2638 #ifdef TRANS_NETFILTER
   2639  int rv = -1;
   2640  switch (ENTRY_TO_CONN(conn)->socket_family) {
   2641 #ifdef TRANS_NETFILTER_IPV4
   2642    case AF_INET:
   2643      rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
   2644                  (struct sockaddr*)&orig_dst, &orig_dst_len);
   2645      break;
   2646 #endif /* defined(TRANS_NETFILTER_IPV4) */
   2647 #ifdef TRANS_NETFILTER_IPV6
   2648    case AF_INET6:
   2649      rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
   2650                  (struct sockaddr*)&orig_dst, &orig_dst_len);
   2651      break;
   2652 #endif /* defined(TRANS_NETFILTER_IPV6) */
   2653    default:
   2654      log_warn(LD_BUG, "Received transparent data from an unsupported "
   2655                       "socket family %d",
   2656               ENTRY_TO_CONN(conn)->socket_family);
   2657      return -1;
   2658  }
   2659  if (rv < 0) {
   2660    int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
   2661    log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
   2662    return -1;
   2663  }
   2664  goto done;
   2665 #elif defined(TRANS_PF)
   2666  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
   2667                  &orig_dst_len) < 0) {
   2668    int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
   2669    log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
   2670    return -1;
   2671  }
   2672  goto done;
   2673 #else
   2674  (void)conn;
   2675  (void)req;
   2676  log_warn(LD_BUG, "Unable to determine destination from socket.");
   2677  return -1;
   2678 #endif /* defined(TRANS_NETFILTER) || ... */
   2679 
   2680 done:
   2681  tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
   2682  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
   2683 
   2684  return 0;
   2685 }
   2686 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
   2687 
   2688 #ifdef TRANS_PF
   2689 static int
   2690 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
   2691 {
   2692  struct sockaddr_storage proxy_addr;
   2693  socklen_t proxy_addr_len = sizeof(proxy_addr);
   2694  struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
   2695  struct pfioc_natlook pnl;
   2696  tor_addr_t addr;
   2697  int pf = -1;
   2698 
   2699  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
   2700                  &proxy_addr_len) < 0) {
   2701    int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
   2702    log_warn(LD_NET, "getsockname() to determine transocks destination "
   2703             "failed: %s", tor_socket_strerror(e));
   2704    return -1;
   2705  }
   2706 
   2707 #ifdef __FreeBSD__
   2708  if (get_options()->TransProxyType_parsed == TPT_IPFW) {
   2709    /* ipfw(8) is used and in this case getsockname returned the original
   2710       destination */
   2711    if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
   2712      tor_fragile_assert();
   2713      return -1;
   2714    }
   2715 
   2716    tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
   2717 
   2718    return 0;
   2719  }
   2720 #endif /* defined(__FreeBSD__) */
   2721 
   2722  memset(&pnl, 0, sizeof(pnl));
   2723  pnl.proto           = IPPROTO_TCP;
   2724  pnl.direction       = PF_OUT;
   2725  if (proxy_sa->sa_family == AF_INET) {
   2726    struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
   2727    pnl.af              = AF_INET;
   2728    pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
   2729    pnl.sport           = htons(ENTRY_TO_CONN(conn)->port);
   2730    pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
   2731    pnl.dport           = sin->sin_port;
   2732  } else if (proxy_sa->sa_family == AF_INET6) {
   2733    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
   2734    pnl.af = AF_INET6;
   2735    const struct in6_addr *dest_in6 =
   2736      tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr);
   2737    if (BUG(!dest_in6))
   2738      return -1;
   2739    memcpy(&pnl.saddr.v6, dest_in6, sizeof(struct in6_addr));
   2740    pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
   2741    memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
   2742    pnl.dport = sin6->sin6_port;
   2743  } else {
   2744    log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
   2745             (int)proxy_sa->sa_family);
   2746    return -1;
   2747  }
   2748 
   2749  pf = get_pf_socket();
   2750  if (pf<0)
   2751    return -1;
   2752 
   2753  if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
   2754    log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
   2755    return -1;
   2756  }
   2757 
   2758  if (pnl.af == AF_INET) {
   2759    tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
   2760  } else if (pnl.af == AF_INET6) {
   2761    tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
   2762  } else {
   2763    tor_fragile_assert();
   2764    return -1;
   2765  }
   2766 
   2767  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
   2768  req->port = ntohs(pnl.rdport);
   2769 
   2770  return 0;
   2771 }
   2772 #endif /* defined(TRANS_PF) */
   2773 
   2774 /** Fetch the original destination address and port from a
   2775 * system-specific interface and put them into a
   2776 * socks_request_t as if they came from a socks request.
   2777 *
   2778 * Return -1 if an error prevents fetching the destination,
   2779 * else return 0.
   2780 */
   2781 static int
   2782 connection_ap_get_original_destination(entry_connection_t *conn,
   2783                                       socks_request_t *req)
   2784 {
   2785 #ifdef TRANS_NETFILTER
   2786  return destination_from_socket(conn, req);
   2787 #elif defined(TRANS_PF)
   2788  const or_options_t *options = get_options();
   2789 
   2790  if (options->TransProxyType_parsed == TPT_PF_DIVERT)
   2791    return destination_from_socket(conn, req);
   2792 
   2793  if (options->TransProxyType_parsed == TPT_DEFAULT ||
   2794      options->TransProxyType_parsed == TPT_IPFW)
   2795    return destination_from_pf(conn, req);
   2796 
   2797  (void)conn;
   2798  (void)req;
   2799  log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
   2800           options->TransProxyType);
   2801  return -1;
   2802 #else
   2803  (void)conn;
   2804  (void)req;
   2805  log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
   2806           "transparent proxy method was configured.");
   2807  return -1;
   2808 #endif /* defined(TRANS_NETFILTER) || ... */
   2809 }
   2810 
   2811 /** connection_edge_process_inbuf() found a conn in state
   2812 * socks_wait. See if conn->inbuf has the right bytes to proceed with
   2813 * the socks handshake.
   2814 *
   2815 * If the handshake is complete, send it to
   2816 * connection_ap_handshake_rewrite_and_attach().
   2817 *
   2818 * Return -1 if an unexpected error with conn occurs (and mark it for close),
   2819 * else return 0.
   2820 */
   2821 static int
   2822 connection_ap_handshake_process_socks(entry_connection_t *conn)
   2823 {
   2824  socks_request_t *socks;
   2825  int sockshere;
   2826  const or_options_t *options = get_options();
   2827  int had_reply = 0;
   2828  connection_t *base_conn = ENTRY_TO_CONN(conn);
   2829 
   2830  tor_assert(conn);
   2831  tor_assert(base_conn->type == CONN_TYPE_AP);
   2832  tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
   2833  tor_assert(conn->socks_request);
   2834  socks = conn->socks_request;
   2835 
   2836  log_debug(LD_APP,"entered.");
   2837 
   2838  sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
   2839                                   options->TestSocks, options->SafeSocks);
   2840 
   2841  if (socks->replylen) {
   2842    had_reply = 1;
   2843    connection_buf_add((const char*)socks->reply, socks->replylen,
   2844                            base_conn);
   2845    socks->replylen = 0;
   2846    if (sockshere == -1) {
   2847      /* An invalid request just got a reply, no additional
   2848       * one is necessary. */
   2849      socks->has_finished = 1;
   2850    }
   2851  }
   2852 
   2853  if (sockshere == 0) {
   2854    log_debug(LD_APP,"socks handshake not all here yet.");
   2855    return 0;
   2856  } else if (sockshere == -1) {
   2857    if (!had_reply) {
   2858      log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
   2859      connection_ap_handshake_socks_reply(conn, NULL, 0,
   2860                                          END_STREAM_REASON_SOCKSPROTOCOL);
   2861    }
   2862    connection_mark_unattached_ap(conn,
   2863                              END_STREAM_REASON_SOCKSPROTOCOL |
   2864                              END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
   2865    return -1;
   2866  } /* else socks handshake is done, continue processing */
   2867 
   2868  if (SOCKS_COMMAND_IS_CONNECT(socks->command))
   2869    control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
   2870  else
   2871    control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
   2872 
   2873  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
   2874 }
   2875 
   2876 /** connection_init_accepted_conn() found a new trans AP conn.
   2877 * Get the original destination and send it to
   2878 * connection_ap_handshake_rewrite_and_attach().
   2879 *
   2880 * Return -1 if an unexpected error with conn (and it should be marked
   2881 * for close), else return 0.
   2882 */
   2883 int
   2884 connection_ap_process_transparent(entry_connection_t *conn)
   2885 {
   2886  socks_request_t *socks;
   2887 
   2888  tor_assert(conn);
   2889  tor_assert(conn->socks_request);
   2890  socks = conn->socks_request;
   2891 
   2892  /* pretend that a socks handshake completed so we don't try to
   2893   * send a socks reply down a transparent conn */
   2894  socks->command = SOCKS_COMMAND_CONNECT;
   2895  socks->has_finished = 1;
   2896 
   2897  log_debug(LD_APP,"entered.");
   2898 
   2899  if (connection_ap_get_original_destination(conn, socks) < 0) {
   2900    log_warn(LD_APP,"Fetching original destination failed. Closing.");
   2901    connection_mark_unattached_ap(conn,
   2902                               END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
   2903    return -1;
   2904  }
   2905  /* we have the original destination */
   2906 
   2907  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
   2908 
   2909  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
   2910 }
   2911 
   2912 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
   2913 * conn-\>inbuf has the right bytes to proceed.  See FreeBSD's libalias(3) and
   2914 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
   2915 * form of the original destination.
   2916 *
   2917 * If the original destination is complete, send it to
   2918 * connection_ap_handshake_rewrite_and_attach().
   2919 *
   2920 * Return -1 if an unexpected error with conn (and it should be marked
   2921 * for close), else return 0.
   2922 */
   2923 static int
   2924 connection_ap_process_natd(entry_connection_t *conn)
   2925 {
   2926  char tmp_buf[36], *tbuf, *daddr;
   2927  size_t tlen = 30;
   2928  int err, port_ok;
   2929  socks_request_t *socks;
   2930 
   2931  tor_assert(conn);
   2932  tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
   2933  tor_assert(conn->socks_request);
   2934  socks = conn->socks_request;
   2935 
   2936  log_debug(LD_APP,"entered.");
   2937 
   2938  /* look for LF-terminated "[DEST ip_addr port]"
   2939   * where ip_addr is a dotted-quad and port is in string form */
   2940  err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
   2941  if (err == 0)
   2942    return 0;
   2943  if (err < 0) {
   2944    log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
   2945    connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
   2946    return -1;
   2947  }
   2948 
   2949  if (strcmpstart(tmp_buf, "[DEST ")) {
   2950    log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
   2951             "said: %s",
   2952             escaped(tmp_buf));
   2953    connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
   2954    return -1;
   2955  }
   2956 
   2957  daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
   2958  if (!(tbuf = strchr(tbuf, ' '))) {
   2959    log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
   2960             "said: %s",
   2961             escaped(tmp_buf));
   2962    connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
   2963    return -1;
   2964  }
   2965  *tbuf++ = '\0';
   2966 
   2967  /* pretend that a socks handshake completed so we don't try to
   2968   * send a socks reply down a natd conn */
   2969  strlcpy(socks->address, daddr, sizeof(socks->address));
   2970  socks->port = (uint16_t)
   2971    tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
   2972  if (!port_ok) {
   2973    log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
   2974             "of range.", escaped(tbuf));
   2975    connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
   2976    return -1;
   2977  }
   2978 
   2979  socks->command = SOCKS_COMMAND_CONNECT;
   2980  socks->has_finished = 1;
   2981 
   2982  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
   2983 
   2984  ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
   2985 
   2986  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
   2987 }
   2988 
   2989 #define TOR_CAPABILITIES_HEADER \
   2990  "Tor-Capabilities: \r\n"
   2991 
   2992 #define HTTP_CONNECT_FIXED_HEADERS \
   2993  TOR_CAPABILITIES_HEADER \
   2994  "Via: tor/1.0 tor-network (tor "VERSION")\r\n"
   2995 
   2996 #define HTTP_OTHER_FIXED_HEADERS \
   2997  TOR_CAPABILITIES_HEADER \
   2998  "Server: tor/1.0 (tor "VERSION")\r\n"
   2999 
   3000 static const char HTTP_OPTIONS_REPLY[] =
   3001  "HTTP/1.0 200 OK\r\n"
   3002  "Allow: OPTIONS, CONNECT\r\n"
   3003  HTTP_OTHER_FIXED_HEADERS
   3004  "\r\n";
   3005 
   3006 static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
   3007  "HTTP/1.0 405 Method Not Allowed\r\n"
   3008  "Content-Type: text/html; charset=iso-8859-1\r\n"
   3009  HTTP_OTHER_FIXED_HEADERS
   3010  "\r\n"
   3011  "<html>\n"
   3012  "<head>\n"
   3013  "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
   3014  "</head>\n"
   3015  "<body>\n"
   3016  "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
   3017  "<p>\n"
   3018  "It appears you have configured your web browser to use this Tor port as\n"
   3019  "an HTTP proxy.\n"
   3020  "</p><p>\n"
   3021  "This is not correct: This port is configured as a CONNECT tunnel, not\n"
   3022  "an HTTP proxy. Please configure your client accordingly.  You can also\n"
   3023  "use HTTPS; then the client should automatically use HTTP CONNECT."
   3024  "</p>\n"
   3025  "<p>\n"
   3026  "See <a href=\"https://www.torproject.org/documentation.html\">"
   3027  "https://www.torproject.org/documentation.html</a> for more "
   3028  "information.\n"
   3029  "</p>\n"
   3030  "</body>\n"
   3031  "</html>\n";
   3032 
   3033 /** Return true iff `host` is a valid host header value indicating localhost.
   3034 */
   3035 static bool
   3036 host_header_is_localhost(const char *host_value)
   3037 {
   3038  char *host = NULL;
   3039  uint16_t port = 0;
   3040  tor_addr_t addr;
   3041  bool result;
   3042 
   3043  // Note that this does not _require_ that a port was set,
   3044  // which is what we want.
   3045  if (tor_addr_port_split(LOG_DEBUG, host_value, &host, &port) < 0) {
   3046    return false;
   3047  }
   3048  tor_assert(host);
   3049 
   3050  if (tor_addr_parse(&addr, host) == 0) {
   3051    result = tor_addr_is_loopback(&addr);
   3052  } else {
   3053    result = ! strcasecmp(host, "localhost");
   3054  }
   3055 
   3056  tor_free(host);
   3057  return result;
   3058 }
   3059 
   3060 /** Return true if the Proxy-Authorization header present in <b>auth</b>
   3061 * isn't using the "modern" format introduced by proposal 365,
   3062 * with "basic" auth and username "tor". */
   3063 STATIC bool
   3064 using_old_proxy_auth(const char *auth)
   3065 {
   3066  auth = eat_whitespace(auth);
   3067  if (strcasecmpstart(auth, "Basic ")) {
   3068    // Not Basic.
   3069    return true;
   3070  }
   3071  auth += strlen("Basic ");
   3072  auth = eat_whitespace(auth);
   3073 
   3074  ssize_t clen = base64_decode_maxsize(strlen(auth)) + 1;
   3075  char *credential = tor_malloc_zero(clen);
   3076  ssize_t n = base64_decode(credential, clen, auth, strlen(auth));
   3077  if (n < 0 || BUG(n >= clen)) {
   3078    // not base64, or somehow too long.
   3079    tor_free(credential);
   3080    return true;
   3081  }
   3082  // nul-terminate.
   3083  credential[n] = 0;
   3084 
   3085  bool username_is_modern = ! strcmpstart(credential, "tor:");
   3086  tor_free(credential);
   3087 
   3088  return ! username_is_modern;
   3089 }
   3090 
   3091 /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
   3092 * but we have not yet received a full HTTP CONNECT request.  Try to parse an
   3093 * HTTP CONNECT request from the connection's inbuf.  On success, set up the
   3094 * connection's socks_request field and try to attach the connection.  On
   3095 * failure, send an HTTP reply, and mark the connection.
   3096 */
   3097 STATIC int
   3098 connection_ap_process_http_connect(entry_connection_t *conn)
   3099 {
   3100  if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
   3101    return -1;
   3102 
   3103  char *headers = NULL, *body = NULL;
   3104  char *command = NULL, *addrport = NULL;
   3105  char *addr = NULL;
   3106  size_t bodylen = 0;
   3107  const char *fixed_reply_headers = HTTP_OTHER_FIXED_HEADERS;
   3108 
   3109  const char *errmsg = NULL;
   3110  bool close_without_message = false;
   3111  int rv = 0;
   3112  bool host_is_localhost = false;
   3113 
   3114  // If true, we already have a full reply, so we shouldn't add
   3115  // fixed headers and CRLF.
   3116  bool errmsg_is_complete = false;
   3117  // If true, we're sending a fixed reply as an errmsg,
   3118  // but technically this isn't an error so we shouldn't log.
   3119  bool skip_error_log = false;
   3120 
   3121  const int http_status =
   3122    fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
   3123                        &body, &bodylen, 1024, 0);
   3124  if (http_status < 0) {
   3125    /* Unparseable http message.  Don't send a reply. */
   3126    close_without_message = true;
   3127    goto err;
   3128  } else if (http_status == 0) {
   3129    /* no HTTP request yet. */
   3130    goto done;
   3131  }
   3132 
   3133  const int cmd_status = parse_http_command(headers, &command, &addrport);
   3134  if (cmd_status < 0) {
   3135    /* Unparseable command. Don't reply. */
   3136    close_without_message = true;
   3137    goto err;
   3138  }
   3139  tor_assert(command);
   3140  tor_assert(addrport);
   3141  {
   3142    // Find out whether the host is localhost.  If it isn't,
   3143    // then either this is a connect request (which is okay)
   3144    // or a webpage is using DNS rebinding to try to bypass
   3145    // browser security (which isn't).
   3146    char *host = http_get_header(headers, "Host: ");
   3147    if (host) {
   3148      host_is_localhost = host_header_is_localhost(host);
   3149    }
   3150    tor_free(host);
   3151  }
   3152  if (!strcasecmp(command, "options") && host_is_localhost) {
   3153    errmsg = HTTP_OPTIONS_REPLY;
   3154    errmsg_is_complete = true;
   3155 
   3156    // TODO: We could in theory make sure that the target
   3157    // is a host or is *.
   3158    // TODO: We could in theory make sure that the body is empty.
   3159    // (And we would have to, if we ever support HTTP/1.1.)
   3160 
   3161    // This is not actually an error, but the error handling
   3162    // does the right operations here (send the reply,
   3163    // mark the connection).
   3164    skip_error_log = true;
   3165 
   3166    goto err;
   3167  }
   3168  if (strcasecmp(command, "connect")) {
   3169    if (host_is_localhost) {
   3170      errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
   3171      errmsg_is_complete = true;
   3172    } else {
   3173      close_without_message = true;
   3174    }
   3175    goto err;
   3176  }
   3177 
   3178  fixed_reply_headers = HTTP_CONNECT_FIXED_HEADERS;
   3179 
   3180  tor_assert(conn->socks_request);
   3181  socks_request_t *socks = conn->socks_request;
   3182  uint16_t port;
   3183  if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
   3184    errmsg = "HTTP/1.0 400 Bad Request\r\n";
   3185    goto err;
   3186  }
   3187  if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
   3188    errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n";
   3189    goto err;
   3190  }
   3191 
   3192  /* Reject the request if it's trying to interact with Arti RPC. */
   3193  char *rpc_hdr = http_get_header(headers, "Tor-RPC-Target: ");
   3194  if (rpc_hdr) {
   3195    tor_free(rpc_hdr);
   3196    errmsg = "HTTP/1.0 501 Not implemented (No RPC Support)\r\n";
   3197    goto err;
   3198  }
   3199 
   3200  /* Abuse the 'username' and 'password' fields here. They are already an
   3201  * abuse. */
   3202  {
   3203    char *authorization = http_get_header(headers, "Proxy-Authorization: ");
   3204    if (authorization) {
   3205      if (using_old_proxy_auth(authorization)) {
   3206        log_warn(LD_GENERAL, "Proxy-Authorization header in legacy format. "
   3207                 "With modern Tor, use Basic auth with username=tor.");
   3208      }
   3209      socks->username = authorization; // steal reference
   3210      socks->usernamelen = strlen(authorization);
   3211    }
   3212    char *isolation = http_get_header(headers, "Tor-Stream-Isolation: ");
   3213    char *x_isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
   3214    if (isolation || x_isolation) {
   3215      // We need to cram both of these headers into a single
   3216      // password field.  Using a delimiter like this is a bit ugly,
   3217      // but the only ones who can confuse it are the applications,
   3218      // whom we are trusting to get their own isolation right.
   3219      const char DELIM[] = "\x01\xff\x01\xff";
   3220      tor_asprintf(&socks->password,
   3221                   "%s%s%s",
   3222                   isolation?isolation:"",
   3223                   DELIM,
   3224                   x_isolation?x_isolation:"");
   3225      tor_free(isolation);
   3226      tor_free(x_isolation);
   3227 
   3228      socks->passwordlen = strlen(socks->password);
   3229    }
   3230  }
   3231 
   3232  socks->command = SOCKS_COMMAND_CONNECT;
   3233  socks->listener_type = CONN_TYPE_AP_HTTP_CONNECT_LISTENER;
   3234  strlcpy(socks->address, addr, sizeof(socks->address));
   3235  socks->port = port;
   3236 
   3237  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
   3238 
   3239  rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
   3240 
   3241  // XXXX send a "100 Continue" message?
   3242 
   3243  goto done;
   3244 
   3245 err:
   3246  if (! close_without_message && BUG(errmsg == NULL))
   3247    errmsg = "HTTP/1.0 400 Bad Request\r\n";
   3248  if (errmsg) {
   3249    if (!skip_error_log)
   3250      log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
   3251    connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
   3252    if (!errmsg_is_complete) {
   3253      connection_buf_add(fixed_reply_headers, strlen(fixed_reply_headers),
   3254                         ENTRY_TO_CONN(conn));
   3255      connection_buf_add("\r\n", 2, ENTRY_TO_CONN(conn));
   3256    }
   3257  } else {
   3258    if (!skip_error_log)
   3259      log_info(LD_EDGE, "HTTP tunnel error: closing silently");
   3260  }
   3261  /* Mark it as "has_finished" so that we don't try to send an extra socks
   3262   * reply. */
   3263  conn->socks_request->has_finished = 1;
   3264  connection_mark_unattached_ap(conn,
   3265                                END_STREAM_REASON_HTTPPROTOCOL|
   3266                                END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
   3267 
   3268 done:
   3269  tor_free(headers);
   3270  tor_free(body);
   3271  tor_free(command);
   3272  tor_free(addrport);
   3273  tor_free(addr);
   3274  return rv;
   3275 }
   3276 
   3277 /** Iterate over the two bytes of stream_id until we get one that is not
   3278 * already in use; return it. Return 0 if can't get a unique stream_id.
   3279 */
   3280 streamid_t
   3281 get_unique_stream_id_by_circ(origin_circuit_t *circ)
   3282 {
   3283  edge_connection_t *tmpconn;
   3284  streamid_t test_stream_id;
   3285  uint32_t attempts=0;
   3286 
   3287 again:
   3288  test_stream_id = circ->next_stream_id++;
   3289  if (++attempts > 1<<16) {
   3290    /* Make sure we don't loop forever if all stream_id's are used. */
   3291    log_warn(LD_APP,"No unused stream IDs. Failing.");
   3292    return 0;
   3293  }
   3294  if (test_stream_id == 0)
   3295    goto again;
   3296  for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
   3297    if (tmpconn->stream_id == test_stream_id)
   3298      goto again;
   3299 
   3300  if (connection_half_edge_find_stream_id(circ->half_streams,
   3301                                           test_stream_id))
   3302    goto again;
   3303 
   3304  if (TO_CIRCUIT(circ)->conflux) {
   3305    conflux_sync_circ_fields(TO_CIRCUIT(circ)->conflux, circ);
   3306  }
   3307 
   3308  return test_stream_id;
   3309 }
   3310 
   3311 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
   3312 * an exit that supports optimistic data. */
   3313 static int
   3314 connection_ap_supports_optimistic_data(const entry_connection_t *conn)
   3315 {
   3316  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
   3317  /* We can only send optimistic data if we're connected to an open
   3318     general circuit. */
   3319  // TODO-329-PURPOSE: Can conflux circuits use optimistic data?
   3320  // Does anything use optimistic data?
   3321  if (edge_conn->on_circuit == NULL ||
   3322      edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
   3323      (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
   3324       edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_HSDIR_GET &&
   3325       edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_S_HSDIR_POST &&
   3326       edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
   3327    return 0;
   3328 
   3329  return conn->may_use_optimistic_data;
   3330 }
   3331 
   3332 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
   3333 * RELAY_BEGIN cell for <b>ap_conn</b>. */
   3334 static uint32_t
   3335 connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
   3336 {
   3337  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
   3338  const node_t *exitnode = NULL;
   3339  const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
   3340  uint32_t flags = 0;
   3341 
   3342  /* No flags for begindir */
   3343  if (ap_conn->use_begindir)
   3344    return 0;
   3345 
   3346  /* No flags for hidden services. */
   3347  if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
   3348      edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_CONFLUX_LINKED)
   3349    return 0;
   3350 
   3351  /* If only IPv4 is supported, no flags */
   3352  if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
   3353    return 0;
   3354 
   3355  if (! cpath_layer ||
   3356      ! cpath_layer->extend_info)
   3357    return 0;
   3358 
   3359  if (!ap_conn->entry_cfg.ipv4_traffic)
   3360    flags |= BEGIN_FLAG_IPV4_NOT_OK;
   3361 
   3362  exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
   3363 
   3364  if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
   3365    tor_addr_t a;
   3366    tor_addr_make_null(&a, AF_INET6);
   3367    if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
   3368                                        exitnode)
   3369        != ADDR_POLICY_REJECTED) {
   3370      /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
   3371       * no point. */
   3372      flags |= BEGIN_FLAG_IPV6_OK;
   3373    }
   3374  }
   3375 
   3376  if (flags == BEGIN_FLAG_IPV6_OK) {
   3377    /* When IPv4 and IPv6 are both allowed, consider whether to say we
   3378     * prefer IPv6.  Otherwise there's no point in declaring a preference */
   3379    if (ap_conn->entry_cfg.prefer_ipv6)
   3380      flags |= BEGIN_FLAG_IPV6_PREFERRED;
   3381  }
   3382 
   3383  if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
   3384    log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
   3385             "am telling it to fulfil with neither IPv4 nor IPv6. That's "
   3386             "not going to work. Did you perhaps ask for an IPv6 address "
   3387             "on an IPv4Only port, or vice versa?");
   3388  }
   3389 
   3390  return flags;
   3391 }
   3392 
   3393 /** Write a relay begin cell, using destaddr and destport from ap_conn's
   3394 * socks_request field, and send it down circ.
   3395 *
   3396 * If ap_conn is broken, mark it for close and return -1. Else return 0.
   3397 */
   3398 MOCK_IMPL(int,
   3399 connection_ap_handshake_send_begin,(entry_connection_t *ap_conn))
   3400 {
   3401  char payload[RELAY_PAYLOAD_SIZE_MAX];
   3402  size_t payload_len;
   3403  int begin_type;
   3404  const or_options_t *options = get_options();
   3405  origin_circuit_t *circ;
   3406  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
   3407  connection_t *base_conn = TO_CONN(edge_conn);
   3408  tor_assert(edge_conn->on_circuit);
   3409  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
   3410 
   3411  tor_assert(base_conn->type == CONN_TYPE_AP);
   3412  tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
   3413  tor_assert(ap_conn->socks_request);
   3414  tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
   3415 
   3416  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
   3417  if (edge_conn->stream_id==0) {
   3418    /* XXXX+ Instead of closing this stream, we should make it get
   3419     * retried on another circuit. */
   3420    connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
   3421 
   3422    /* Mark this circuit "unusable for new streams". */
   3423    mark_circuit_unusable_for_new_conns(circ);
   3424    return -1;
   3425  }
   3426 
   3427  size_t payload_max = circuit_max_relay_payload(
   3428                edge_conn->on_circuit, edge_conn->cpath_layer,
   3429                RELAY_COMMAND_BEGIN);
   3430  /* Set up begin cell flags. */
   3431  edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
   3432 
   3433  tor_snprintf(payload,payload_max, "%s:%d",
   3434               (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   3435                circ->base_.purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED ||
   3436                circ->base_.purpose == CIRCUIT_PURPOSE_CONTROLLER) ?
   3437                 ap_conn->socks_request->address : "",
   3438               ap_conn->socks_request->port);
   3439  payload_len = strlen(payload)+1;
   3440  if (payload_len <= payload_max - 4 && edge_conn->begincell_flags) {
   3441    set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
   3442    payload_len += 4;
   3443  }
   3444 
   3445  log_info(LD_APP,
   3446           "Sending relay cell %d on circ %u to begin stream %d.",
   3447           (int)ap_conn->use_begindir,
   3448           (unsigned)circ->base_.n_circ_id,
   3449           edge_conn->stream_id);
   3450 
   3451  begin_type = ap_conn->use_begindir ?
   3452                 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
   3453 
   3454  /* Check that circuits are anonymised, based on their type. */
   3455  if (begin_type == RELAY_COMMAND_BEGIN) {
   3456    /* This connection is a standard OR connection.
   3457     * Make sure its path length is anonymous, or that we're in a
   3458     * non-anonymous mode. */
   3459    assert_circ_anonymity_ok(circ, options);
   3460  } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
   3461    /* This connection is a begindir directory connection.
   3462     * Look at the linked directory connection to access the directory purpose.
   3463     * If a BEGINDIR connection is ever not linked, that's a bug. */
   3464    if (BUG(!base_conn->linked)) {
   3465      return -1;
   3466    }
   3467    connection_t *linked_dir_conn_base = base_conn->linked_conn;
   3468    /* If the linked connection has been unlinked by other code, we can't send
   3469     * a begin cell on it. */
   3470    if (!linked_dir_conn_base) {
   3471      return -1;
   3472    }
   3473    /* Sensitive directory connections must have an anonymous path length.
   3474     * Otherwise, directory connections are typically one-hop.
   3475     * This matches the earlier check for directory connection path anonymity
   3476     * in directory_initiate_request(). */
   3477    if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
   3478                    TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
   3479                    TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
   3480      assert_circ_anonymity_ok(circ, options);
   3481    }
   3482  } else {
   3483    /* This code was written for the two connection types BEGIN and BEGIN_DIR
   3484     */
   3485    tor_assert_unreached();
   3486  }
   3487 
   3488  if (connection_edge_send_command(edge_conn, begin_type,
   3489                  begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
   3490                  begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
   3491    return -1; /* circuit is closed, don't continue */
   3492 
   3493  edge_conn->package_window = STREAMWINDOW_START;
   3494  edge_conn->deliver_window = STREAMWINDOW_START;
   3495  base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
   3496  log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
   3497           ", n_circ_id %u",
   3498           base_conn->s, (unsigned)circ->base_.n_circ_id);
   3499  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
   3500 
   3501  /* If there's queued-up data, send it now */
   3502  if ((connection_get_inbuf_len(base_conn) ||
   3503       ap_conn->sending_optimistic_data) &&
   3504      connection_ap_supports_optimistic_data(ap_conn)) {
   3505    log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
   3506             (long)connection_get_inbuf_len(base_conn),
   3507             ap_conn->sending_optimistic_data ?
   3508             (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
   3509    if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
   3510      connection_mark_for_close(base_conn);
   3511    }
   3512  }
   3513 
   3514  return 0;
   3515 }
   3516 
   3517 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
   3518 * socks_request field, and send it down circ.
   3519 *
   3520 * If ap_conn is broken, mark it for close and return -1. Else return 0.
   3521 */
   3522 int
   3523 connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
   3524 {
   3525  int payload_len, command;
   3526  const char *string_addr;
   3527  char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
   3528  origin_circuit_t *circ;
   3529  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
   3530  connection_t *base_conn = TO_CONN(edge_conn);
   3531  tor_assert(edge_conn->on_circuit);
   3532  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
   3533 
   3534  tor_assert(base_conn->type == CONN_TYPE_AP);
   3535  tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
   3536  tor_assert(ap_conn->socks_request);
   3537  tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL ||
   3538             circ->base_.purpose == CIRCUIT_PURPOSE_CONFLUX_LINKED);
   3539 
   3540  command = ap_conn->socks_request->command;
   3541  tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
   3542 
   3543  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
   3544  if (edge_conn->stream_id==0) {
   3545    /* XXXX+ Instead of closing this stream, we should make it get
   3546     * retried on another circuit. */
   3547    connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
   3548 
   3549    /* Mark this circuit "unusable for new streams". */
   3550    mark_circuit_unusable_for_new_conns(circ);
   3551    return -1;
   3552  }
   3553 
   3554  if (command == SOCKS_COMMAND_RESOLVE) {
   3555    string_addr = ap_conn->socks_request->address;
   3556    payload_len = (int)strlen(string_addr)+1;
   3557  } else {
   3558    /* command == SOCKS_COMMAND_RESOLVE_PTR */
   3559    const char *a = ap_conn->socks_request->address;
   3560    tor_addr_t addr;
   3561    int r;
   3562 
   3563    /* We're doing a reverse lookup.  The input could be an IP address, or
   3564     * could be an .in-addr.arpa or .ip6.arpa address */
   3565    r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
   3566    if (r <= 0) {
   3567      log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
   3568               safe_str_client(a));
   3569      connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
   3570      return -1;
   3571    }
   3572 
   3573    r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
   3574    if (r < 0) {
   3575      log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
   3576               safe_str_client(a));
   3577      connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
   3578      return -1;
   3579    }
   3580 
   3581    string_addr = inaddr_buf;
   3582    payload_len = (int)strlen(inaddr_buf)+1;
   3583    tor_assert(payload_len <= (int)sizeof(inaddr_buf));
   3584  }
   3585 
   3586  log_debug(LD_APP,
   3587            "Sending relay cell to begin stream %d.", edge_conn->stream_id);
   3588 
   3589  if (connection_edge_send_command(edge_conn,
   3590                           RELAY_COMMAND_RESOLVE,
   3591                           string_addr, payload_len) < 0)
   3592    return -1; /* circuit is closed, don't continue */
   3593 
   3594  if (!base_conn->address) {
   3595    /* This might be unnecessary. XXXX */
   3596    base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
   3597  }
   3598  base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
   3599  log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
   3600           ", n_circ_id %u",
   3601           base_conn->s, (unsigned)circ->base_.n_circ_id);
   3602  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
   3603  return 0;
   3604 }
   3605 
   3606 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
   3607 * new linked connection pair, and attach one side to the conn, connection_add
   3608 * it, initialize it to circuit_wait, and call
   3609 * connection_ap_handshake_attach_circuit(conn) on it.
   3610 *
   3611 * Return the newly created end of the linked connection pair, or -1 if error.
   3612 */
   3613 entry_connection_t *
   3614 connection_ap_make_link(connection_t *partner,
   3615                        char *address, uint16_t port,
   3616                        const char *digest,
   3617                        int session_group, int isolation_flags,
   3618                        int use_begindir, int want_onehop)
   3619 {
   3620  entry_connection_t *conn;
   3621  connection_t *base_conn;
   3622 
   3623  log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
   3624           want_onehop ? "direct" : "anonymized",
   3625           safe_str_client(address), port);
   3626 
   3627  conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
   3628  base_conn = ENTRY_TO_CONN(conn);
   3629  base_conn->linked = 1; /* so that we can add it safely below. */
   3630 
   3631  /* populate conn->socks_request */
   3632 
   3633  /* leave version at zero, so the socks_reply is empty */
   3634  conn->socks_request->socks_version = 0;
   3635  conn->socks_request->has_finished = 0; /* waiting for 'connected' */
   3636  strlcpy(conn->socks_request->address, address,
   3637          sizeof(conn->socks_request->address));
   3638  conn->socks_request->port = port;
   3639  conn->socks_request->command = SOCKS_COMMAND_CONNECT;
   3640  conn->want_onehop = want_onehop;
   3641  conn->use_begindir = use_begindir;
   3642  if (use_begindir) {
   3643    conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
   3644    conn->chosen_exit_name[0] = '$';
   3645    tor_assert(digest);
   3646    base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
   3647                  digest, DIGEST_LEN);
   3648  }
   3649 
   3650  /* Populate isolation fields. */
   3651  conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
   3652  conn->original_dest_address = tor_strdup(address);
   3653  conn->entry_cfg.session_group = session_group;
   3654  conn->entry_cfg.isolation_flags = isolation_flags;
   3655 
   3656  base_conn->address = tor_strdup("(Tor_internal)");
   3657  tor_addr_make_unspec(&base_conn->addr);
   3658  base_conn->port = 0;
   3659 
   3660  connection_link_connections(partner, base_conn);
   3661 
   3662  if (connection_add(base_conn) < 0) { /* no space, forget it */
   3663    connection_free(base_conn);
   3664    return NULL;
   3665  }
   3666 
   3667  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
   3668 
   3669  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
   3670 
   3671  /* attaching to a dirty circuit is fine */
   3672  connection_ap_mark_as_pending_circuit(conn);
   3673  log_info(LD_APP,"... application connection created and linked.");
   3674  return conn;
   3675 }
   3676 
   3677 /** Notify any interested controller connections about a new hostname resolve
   3678 * or resolve error.  Takes the same arguments as does
   3679 * connection_ap_handshake_socks_resolved(). */
   3680 static void
   3681 tell_controller_about_resolved_result(entry_connection_t *conn,
   3682                                      int answer_type,
   3683                                      size_t answer_len,
   3684                                      const char *answer,
   3685                                      int ttl,
   3686                                      time_t expires)
   3687 {
   3688  uint64_t stream_id = 0;
   3689 
   3690  if (BUG(!conn)) {
   3691    return;
   3692  }
   3693 
   3694  stream_id = ENTRY_TO_CONN(conn)->global_identifier;
   3695 
   3696  expires = time(NULL) + ttl;
   3697  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
   3698    char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
   3699    if (cp)
   3700      control_event_address_mapped(conn->socks_request->address,
   3701                                   cp, expires, NULL, 0, stream_id);
   3702    tor_free(cp);
   3703  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
   3704    char *cp = tor_strndup(answer, answer_len);
   3705    control_event_address_mapped(conn->socks_request->address,
   3706                                 cp, expires, NULL, 0, stream_id);
   3707    tor_free(cp);
   3708  } else {
   3709    control_event_address_mapped(conn->socks_request->address,
   3710                                 "<error>", time(NULL)+ttl,
   3711                                 "error=yes", 0, stream_id);
   3712  }
   3713 }
   3714 
   3715 /**
   3716 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
   3717 * as the answer.
   3718 */
   3719 void
   3720 connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
   3721                                            const tor_addr_t *answer,
   3722                                            int ttl,
   3723                                            time_t expires)
   3724 {
   3725  if (tor_addr_family(answer) == AF_INET) {
   3726    uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
   3727    connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
   3728                                           (uint8_t*)&a,
   3729                                           ttl, expires);
   3730  } else if (tor_addr_family(answer) == AF_INET6) {
   3731    const uint8_t *a = tor_addr_to_in6_addr8(answer);
   3732    connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
   3733                                           a,
   3734                                           ttl, expires);
   3735  } else {
   3736    log_warn(LD_BUG, "Got called with address of unexpected family %d",
   3737             tor_addr_family(answer));
   3738    connection_ap_handshake_socks_resolved(conn,
   3739                                           RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
   3740  }
   3741 }
   3742 
   3743 /** Send an answer to an AP connection that has requested a DNS lookup via
   3744 * SOCKS.  The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
   3745 * for unreachable; the answer should be in the format specified in the socks
   3746 * extensions document.  <b>ttl</b> is the ttl for the answer, or -1 on
   3747 * certain errors or for values that didn't come via DNS.  <b>expires</b> is
   3748 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
   3749 **/
   3750 /* XXXX the use of the ttl and expires fields is nutty.  Let's make this
   3751 * interface and those that use it less ugly. */
   3752 MOCK_IMPL(void,
   3753 connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
   3754                                       int answer_type,
   3755                                       size_t answer_len,
   3756                                       const uint8_t *answer,
   3757                                       int ttl,
   3758                                       time_t expires))
   3759 {
   3760  char buf[384];
   3761  size_t replylen;
   3762 
   3763  if (ttl >= 0) {
   3764    if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
   3765      tor_addr_t a;
   3766      tor_addr_from_ipv4n(&a, get_uint32(answer));
   3767      if (! tor_addr_is_null(&a)) {
   3768        client_dns_set_addressmap(conn,
   3769                                  conn->socks_request->address, &a,
   3770                                  conn->chosen_exit_name, ttl);
   3771      }
   3772    } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
   3773      tor_addr_t a;
   3774      tor_addr_from_ipv6_bytes(&a, answer);
   3775      if (! tor_addr_is_null(&a)) {
   3776        client_dns_set_addressmap(conn,
   3777                                  conn->socks_request->address, &a,
   3778                                  conn->chosen_exit_name, ttl);
   3779      }
   3780    } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
   3781      char *cp = tor_strndup((char*)answer, answer_len);
   3782      client_dns_set_reverse_addressmap(conn,
   3783                                        conn->socks_request->address,
   3784                                        cp,
   3785                                        conn->chosen_exit_name, ttl);
   3786      tor_free(cp);
   3787    }
   3788  }
   3789 
   3790  if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
   3791    if (conn->dns_server_request) {
   3792      /* We had a request on our DNS port: answer it. */
   3793      dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
   3794      conn->socks_request->has_finished = 1;
   3795      return;
   3796    } else {
   3797      /* This must be a request from the controller. Since answers to those
   3798       * requests are not cached, they do not generate an ADDRMAP event on
   3799       * their own. */
   3800      tell_controller_about_resolved_result(conn, answer_type, answer_len,
   3801                                            (char*)answer, ttl, expires);
   3802      conn->socks_request->has_finished = 1;
   3803      return;
   3804    }
   3805    /* We shouldn't need to free conn here; it gets marked by the caller. */
   3806  }
   3807 
   3808  if (conn->socks_request->socks_version == 4) {
   3809    buf[0] = 0x00; /* version */
   3810    if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
   3811      buf[1] = SOCKS4_GRANTED;
   3812      set_uint16(buf+2, 0);
   3813      memcpy(buf+4, answer, 4); /* address */
   3814      replylen = SOCKS4_NETWORK_LEN;
   3815    } else { /* "error" */
   3816      buf[1] = SOCKS4_REJECT;
   3817      memset(buf+2, 0, 6);
   3818      replylen = SOCKS4_NETWORK_LEN;
   3819    }
   3820  } else if (conn->socks_request->socks_version == 5) {
   3821    /* SOCKS5 */
   3822    buf[0] = 0x05; /* version */
   3823    if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
   3824      buf[1] = SOCKS5_SUCCEEDED;
   3825      buf[2] = 0; /* reserved */
   3826      buf[3] = 0x01; /* IPv4 address type */
   3827      memcpy(buf+4, answer, 4); /* address */
   3828      set_uint16(buf+8, 0); /* port == 0. */
   3829      replylen = 10;
   3830    } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
   3831      buf[1] = SOCKS5_SUCCEEDED;
   3832      buf[2] = 0; /* reserved */
   3833      buf[3] = 0x04; /* IPv6 address type */
   3834      memcpy(buf+4, answer, 16); /* address */
   3835      set_uint16(buf+20, 0); /* port == 0. */
   3836      replylen = 22;
   3837    } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
   3838      buf[1] = SOCKS5_SUCCEEDED;
   3839      buf[2] = 0; /* reserved */
   3840      buf[3] = 0x03; /* Domainname address type */
   3841      buf[4] = (char)answer_len;
   3842      memcpy(buf+5, answer, answer_len); /* address */
   3843      set_uint16(buf+5+answer_len, 0); /* port == 0. */
   3844      replylen = 5+answer_len+2;
   3845    } else {
   3846      buf[1] = SOCKS5_HOST_UNREACHABLE;
   3847      memset(buf+2, 0, 8);
   3848      replylen = 10;
   3849    }
   3850  } else {
   3851    /* no socks version info; don't send anything back */
   3852    return;
   3853  }
   3854  connection_ap_handshake_socks_reply(conn, buf, replylen,
   3855          (answer_type == RESOLVED_TYPE_IPV4 ||
   3856           answer_type == RESOLVED_TYPE_IPV6 ||
   3857           answer_type == RESOLVED_TYPE_HOSTNAME) ?
   3858                                      0 : END_STREAM_REASON_RESOLVEFAILED);
   3859 }
   3860 
   3861 /** Send a socks reply to stream <b>conn</b>, using the appropriate
   3862 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
   3863 * handshaking.
   3864 *
   3865 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
   3866 * and return, else reply based on <b>endreason</b> (one of
   3867 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
   3868 * be 0 or REASON_DONE.  Send endreason to the controller, if appropriate.
   3869 */
   3870 void
   3871 connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
   3872                                    size_t replylen, int endreason)
   3873 {
   3874  char buf[256];
   3875  socks5_reply_status_t status;
   3876 
   3877  tor_assert(conn->socks_request); /* make sure it's an AP stream */
   3878 
   3879  if (conn->socks_request->socks_use_extended_errors &&
   3880      conn->socks_request->socks_extended_error_code != 0) {
   3881    status = conn->socks_request->socks_extended_error_code;
   3882  } else {
   3883    status = stream_end_reason_to_socks5_response(endreason);
   3884  }
   3885 
   3886  if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
   3887    control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
   3888                                STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
   3889                                endreason);
   3890  }
   3891 
   3892  /* Flag this stream's circuit as having completed a stream successfully
   3893   * (for path bias) */
   3894  if (status == SOCKS5_SUCCEEDED ||
   3895      endreason == END_STREAM_REASON_RESOLVEFAILED ||
   3896      endreason == END_STREAM_REASON_CONNECTREFUSED ||
   3897      endreason == END_STREAM_REASON_CONNRESET ||
   3898      endreason == END_STREAM_REASON_NOROUTE ||
   3899      endreason == END_STREAM_REASON_RESOURCELIMIT) {
   3900    if (!conn->edge_.on_circuit ||
   3901       !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
   3902      if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
   3903        log_info(LD_BUG,
   3904                 "No origin circuit for successful SOCKS stream %"PRIu64
   3905                 ". Reason: %d",
   3906                 (ENTRY_TO_CONN(conn)->global_identifier),
   3907                 endreason);
   3908      }
   3909      /*
   3910       * Else DNS remaps and failed hidden service lookups can send us
   3911       * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
   3912       *
   3913       * Perhaps we could make the test more precise; we can tell hidden
   3914       * services by conn->edge_.renddata != NULL; anything analogous for
   3915       * the DNS remap case?
   3916       */
   3917    } else {
   3918      // XXX: Hrmm. It looks like optimistic data can't go through this
   3919      // codepath, but someone should probably test it and make sure.
   3920      // We don't want to mark optimistically opened streams as successful.
   3921      pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
   3922    }
   3923  }
   3924 
   3925  if (conn->socks_request->has_finished) {
   3926    log_warn(LD_BUG, "(Harmless.) duplicate calls to "
   3927             "connection_ap_handshake_socks_reply.");
   3928    return;
   3929  }
   3930  if (replylen) { /* we already have a reply in mind */
   3931    connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
   3932    conn->socks_request->has_finished = 1;
   3933    return;
   3934  }
   3935  if (conn->socks_request->listener_type ==
   3936       CONN_TYPE_AP_HTTP_CONNECT_LISTENER) {
   3937    const char *response = end_reason_to_http_connect_response_line(endreason);
   3938    if (!response) {
   3939      response = "HTTP/1.0 400 Bad Request\r\n";
   3940    }
   3941    connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
   3942    connection_buf_add(HTTP_CONNECT_FIXED_HEADERS,
   3943                       strlen(HTTP_CONNECT_FIXED_HEADERS),
   3944                       ENTRY_TO_CONN(conn));
   3945    if (endreason) {
   3946      bool reason_is_remote = (endreason & END_STREAM_REASON_MASK) < 256;
   3947      const char *reason = stream_end_reason_to_control_string(endreason);
   3948      if (reason) {
   3949        const char *prefix = reason_is_remote ? "end" : "c-tor";
   3950        tor_snprintf(buf, sizeof(buf),
   3951                     "Tor-Request-Failed: %s/%s\r\n",
   3952                     prefix, reason);
   3953        connection_buf_add(buf, strlen(buf), ENTRY_TO_CONN(conn));
   3954      }
   3955    }
   3956    connection_buf_add("\r\n", 2, ENTRY_TO_CONN(conn));
   3957  } else if (conn->socks_request->socks_version == 4) {
   3958    memset(buf,0,SOCKS4_NETWORK_LEN);
   3959    buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
   3960    /* leave version, destport, destip zero */
   3961    connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
   3962  } else if (conn->socks_request->socks_version == 5) {
   3963    size_t buf_len;
   3964    memset(buf,0,sizeof(buf));
   3965    if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
   3966      buf[0] = 5; /* version 5 */
   3967      buf[1] = (char)status;
   3968      buf[2] = 0;
   3969      buf[3] = 1; /* ipv4 addr */
   3970      /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
   3971      buf_len = 10;
   3972    } else { /* AF_INET6. */
   3973      buf[0] = 5; /* version 5 */
   3974      buf[1] = (char)status;
   3975      buf[2] = 0;
   3976      buf[3] = 4; /* ipv6 addr */
   3977      /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
   3978      buf_len = 22;
   3979    }
   3980    connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
   3981  }
   3982  /* If socks_version isn't 4 or 5, don't send anything.
   3983   * This can happen in the case of AP bridges. */
   3984  conn->socks_request->has_finished = 1;
   3985  return;
   3986 }
   3987 
   3988 /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
   3989 * place the result in <b>bcell</b>.  On success return 0; on failure return
   3990 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
   3991 * the client.
   3992 *
   3993 * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
   3994 * we don't.
   3995 **/
   3996 STATIC int
   3997 begin_cell_parse(const relay_msg_t *msg, begin_cell_t *bcell,
   3998                 uint8_t *end_reason_out)
   3999 {
   4000  const uint8_t *body, *nul;
   4001 
   4002  memset(bcell, 0, sizeof(*bcell));
   4003  *end_reason_out = END_STREAM_REASON_MISC;
   4004 
   4005  bcell->stream_id = msg->stream_id;
   4006 
   4007  if (msg->command == RELAY_COMMAND_BEGIN_DIR) {
   4008    bcell->is_begindir = 1;
   4009    return 0;
   4010  } else if (msg->command != RELAY_COMMAND_BEGIN) {
   4011    log_warn(LD_BUG, "Got an unexpected command %u", msg->command);
   4012    *end_reason_out = END_STREAM_REASON_INTERNAL;
   4013    return -1;
   4014  }
   4015 
   4016  body = msg->body;
   4017  nul = memchr(body, 0, msg->length);
   4018  if (! nul) {
   4019    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
   4020           "Relay begin cell has no \\0. Closing.");
   4021    *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
   4022    return -1;
   4023  }
   4024 
   4025  if (tor_addr_port_split(LOG_PROTOCOL_WARN,
   4026                          (char*)(body),
   4027                          &bcell->address,&bcell->port)<0) {
   4028    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
   4029           "Unable to parse addr:port in relay begin cell. Closing.");
   4030    *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
   4031    return -1;
   4032  }
   4033  if (bcell->port == 0) {
   4034    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
   4035           "Missing port in relay begin cell. Closing.");
   4036    tor_free(bcell->address);
   4037    *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
   4038    return -1;
   4039  }
   4040  if (body + msg->length >= nul + 4)
   4041    bcell->flags = ntohl(get_uint32(nul+1));
   4042 
   4043  return 0;
   4044 }
   4045 
   4046 /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
   4047 * connection, attach it to the circ and connect it. Return 0 on success
   4048 * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
   4049 * where the caller should close the circuit. */
   4050 static int
   4051 handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
   4052 {
   4053  int ret;
   4054  origin_circuit_t *origin_circ;
   4055 
   4056  assert_circuit_ok(circ);
   4057  tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
   4058  tor_assert(conn);
   4059 
   4060  log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
   4061                     "to the service destination.");
   4062 
   4063  origin_circ = TO_ORIGIN_CIRCUIT(circ);
   4064  conn->base_.address = tor_strdup("(rendezvous)");
   4065  conn->base_.state = EXIT_CONN_STATE_CONNECTING;
   4066 
   4067  if (origin_circ->hs_ident) {
   4068    /* Setup the identifier to be the one for the circuit service. */
   4069    conn->hs_ident =
   4070      hs_ident_edge_conn_new(&origin_circ->hs_ident->identity_pk);
   4071    tor_assert(connection_edge_is_rendezvous_stream(conn));
   4072    ret = hs_service_set_conn_addr_port(origin_circ, conn);
   4073  } else {
   4074    /* We should never get here if the circuit's purpose is rendezvous. */
   4075    tor_assert_nonfatal_unreached();
   4076    return -1;
   4077  }
   4078  if (ret < 0) {
   4079    log_info(LD_REND, "Didn't find rendezvous service at %s",
   4080             connection_describe_peer(TO_CONN(conn)));
   4081    /* Send back reason DONE because we want to make hidden service port
   4082     * scanning harder thus instead of returning that the exit policy
   4083     * didn't match, which makes it obvious that the port is closed,
   4084     * return DONE and kill the circuit. That way, a user (malicious or
   4085     * not) needs one circuit per bad port unless it matches the policy of
   4086     * the hidden service. */
   4087    relay_send_end_cell_from_edge(conn->stream_id, circ,
   4088                                  END_STREAM_REASON_DONE,
   4089                                  origin_circ->cpath->prev);
   4090    connection_free_(TO_CONN(conn));
   4091 
   4092    /* Drop the circuit here since it might be someone deliberately
   4093     * scanning the hidden service ports. Note that this mitigates port
   4094     * scanning by adding more work on the attacker side to successfully
   4095     * scan but does not fully solve it. */
   4096    if (ret < -1) {
   4097      return END_CIRC_AT_ORIGIN;
   4098    } else {
   4099      return 0;
   4100    }
   4101  }
   4102 
   4103  /* Link the circuit and the connection crypt path. */
   4104  conn->cpath_layer = origin_circ->cpath->prev;
   4105 
   4106  /* If this is the first stream on this circuit, tell circpad */
   4107  if (!origin_circ->p_streams)
   4108    circpad_machine_event_circ_has_streams(origin_circ);
   4109 
   4110  /* Add it into the linked list of p_streams on this circuit */
   4111  conn->next_stream = origin_circ->p_streams;
   4112  origin_circ->p_streams = conn;
   4113  conn->on_circuit = circ;
   4114  assert_circuit_ok(circ);
   4115 
   4116  hs_inc_rdv_stream_counter(origin_circ);
   4117 
   4118  /* If it's an onion service connection, we might want to include the proxy
   4119   * protocol header: */
   4120  if (conn->hs_ident) {
   4121    hs_circuit_id_protocol_t circuit_id_protocol =
   4122      hs_service_exports_circuit_id(&conn->hs_ident->identity_pk);
   4123    export_hs_client_circuit_id(conn, circuit_id_protocol);
   4124  }
   4125 
   4126  /* Connect tor to the hidden service destination. */
   4127  connection_exit_connect(conn);
   4128 
   4129  /* For path bias: This circuit was used successfully */
   4130  pathbias_mark_use_success(origin_circ);
   4131  return 0;
   4132 }
   4133 
   4134 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
   4135 * an exit hop for the circuit, or we are the origin and it is a
   4136 * rendezvous begin.
   4137 *
   4138 * Launch a new exit connection and initialize things appropriately.
   4139 *
   4140 * If it's a rendezvous stream, call connection_exit_connect() on
   4141 * it.
   4142 *
   4143 * For general streams, call dns_resolve() on it first, and only call
   4144 * connection_exit_connect() if the dns answer is already known.
   4145 *
   4146 * Note that we don't call connection_add() on the new stream! We wait
   4147 * for connection_exit_connect() to do that.
   4148 *
   4149 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
   4150 * Else return 0.
   4151 */
   4152 int
   4153 connection_exit_begin_conn(const relay_msg_t *msg, circuit_t *circ)
   4154 {
   4155  edge_connection_t *n_stream;
   4156  char *address = NULL;
   4157  uint16_t port = 0;
   4158  or_circuit_t *or_circ = NULL;
   4159  origin_circuit_t *origin_circ = NULL;
   4160  crypt_path_t *layer_hint = NULL;
   4161  const or_options_t *options = get_options();
   4162  begin_cell_t bcell;
   4163  int rv;
   4164  uint8_t end_reason=0;
   4165  dos_stream_defense_type_t dos_defense_type;
   4166 
   4167  assert_circuit_ok(circ);
   4168  if (!CIRCUIT_IS_ORIGIN(circ)) {
   4169    or_circ = TO_OR_CIRCUIT(circ);
   4170  } else {
   4171    tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
   4172    origin_circ = TO_ORIGIN_CIRCUIT(circ);
   4173    layer_hint = origin_circ->cpath->prev;
   4174  }
   4175 
   4176  if (!server_mode(options) &&
   4177      circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
   4178    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
   4179           "Relay begin cell at non-server. Closing.");
   4180    relay_send_end_cell_from_edge(msg->stream_id, circ,
   4181                                  END_STREAM_REASON_EXITPOLICY, NULL);
   4182    return 0;
   4183  }
   4184 
   4185  rv = begin_cell_parse(msg, &bcell, &end_reason);
   4186  if (rv < -1) {
   4187    return -END_CIRC_REASON_TORPROTOCOL;
   4188  } else if (rv == -1) {
   4189    tor_free(bcell.address);
   4190    relay_send_end_cell_from_edge(msg->stream_id, circ, end_reason,
   4191                                  layer_hint);
   4192    return 0;
   4193  }
   4194 
   4195  if (! bcell.is_begindir) {
   4196    /* Steal reference */
   4197    tor_assert(bcell.address);
   4198    address = bcell.address;
   4199    port = bcell.port;
   4200 
   4201    if (or_circ && or_circ->p_chan) {
   4202      const int client_chan = channel_is_client(or_circ->p_chan);
   4203      if ((client_chan ||
   4204           (!connection_or_digest_is_known_relay(
   4205                or_circ->p_chan->identity_digest) &&
   4206          should_refuse_unknown_exits(options)))) {
   4207        /* Don't let clients use us as a single-hop proxy. It attracts
   4208         * attackers and users who'd be better off with, well, single-hop
   4209         * proxies. */
   4210        log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
   4211               "Attempt by %s to open a stream %s. Closing.",
   4212               safe_str(channel_describe_peer(or_circ->p_chan)),
   4213               client_chan ? "on first hop of circuit" :
   4214                             "from unknown relay");
   4215        relay_send_end_cell_from_edge(msg->stream_id, circ,
   4216                                      client_chan ?
   4217                                        END_STREAM_REASON_TORPROTOCOL :
   4218                                        END_STREAM_REASON_MISC,
   4219                                      NULL);
   4220        tor_free(address);
   4221        return 0;
   4222      }
   4223    }
   4224  } else if (msg->command == RELAY_COMMAND_BEGIN_DIR) {
   4225    if (!directory_permits_begindir_requests(options) ||
   4226        circ->purpose != CIRCUIT_PURPOSE_OR) {
   4227      relay_send_end_cell_from_edge(msg->stream_id, circ,
   4228                                    END_STREAM_REASON_NOTDIRECTORY,
   4229                                    layer_hint);
   4230      return 0;
   4231    }
   4232    /* Make sure to get the 'real' address of the previous hop: the
   4233     * caller might want to know whether the remote IP address has changed,
   4234     * and we might already have corrected base_.addr[ess] for the relay's
   4235     * canonical IP address. */
   4236    tor_addr_t chan_addr;
   4237    if (or_circ && or_circ->p_chan &&
   4238        channel_get_addr_if_possible(or_circ->p_chan, &chan_addr)) {
   4239      address = tor_addr_to_str_dup(&chan_addr);
   4240    } else {
   4241      address = tor_strdup("127.0.0.1");
   4242    }
   4243    port = 1; /* XXXX This value is never actually used anywhere, and there
   4244               * isn't "really" a connection here.  But we
   4245               * need to set it to something nonzero. */
   4246  } else {
   4247    log_warn(LD_BUG, "Got an unexpected command %u", msg->command);
   4248    relay_send_end_cell_from_edge(msg->stream_id, circ,
   4249                                  END_STREAM_REASON_INTERNAL, layer_hint);
   4250    return 0;
   4251  }
   4252 
   4253  if (! options->IPv6Exit) {
   4254    /* I don't care if you prefer IPv6; I can't give you any. */
   4255    bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
   4256    /* If you don't want IPv4, I can't help. */
   4257    if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
   4258      tor_free(address);
   4259      relay_send_end_cell_from_edge(msg->stream_id, circ,
   4260                                    END_STREAM_REASON_EXITPOLICY, layer_hint);
   4261      return 0;
   4262    }
   4263  }
   4264 
   4265  log_debug(LD_EXIT,"Creating new exit connection.");
   4266  /* The 'AF_INET' here is temporary; we might need to change it later in
   4267   * connection_exit_connect(). */
   4268  n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
   4269 
   4270  /* Remember the tunneled request ID in the new edge connection, so that
   4271   * we can measure download times. */
   4272  n_stream->dirreq_id = circ->dirreq_id;
   4273 
   4274  n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
   4275  n_stream->begincell_flags = bcell.flags;
   4276  n_stream->stream_id = msg->stream_id;
   4277  n_stream->base_.port = port;
   4278  /* leave n_stream->s at -1, because it's not yet valid */
   4279  n_stream->package_window = STREAMWINDOW_START;
   4280  n_stream->deliver_window = STREAMWINDOW_START;
   4281 
   4282  if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
   4283    int ret;
   4284    tor_free(address);
   4285    /* We handle this circuit and stream in this function for all supported
   4286     * hidden service version. */
   4287    ret = handle_hs_exit_conn(circ, n_stream);
   4288 
   4289    if (ret == 0) {
   4290      /* This was a valid cell. Count it as delivered + overhead. */
   4291      circuit_read_valid_data(origin_circ, msg->length);
   4292    }
   4293    return ret;
   4294  }
   4295  tor_strlower(address);
   4296  n_stream->base_.address = address;
   4297  n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
   4298  /* default to failed, change in dns_resolve if it turns out not to fail */
   4299 
   4300  /* If we're hibernating or shutting down, we refuse to open new streams. */
   4301  if (we_are_hibernating()) {
   4302    relay_send_end_cell_from_edge(msg->stream_id, circ,
   4303                                  END_STREAM_REASON_HIBERNATING, NULL);
   4304    connection_free_(TO_CONN(n_stream));
   4305    return 0;
   4306  }
   4307 
   4308  n_stream->on_circuit = circ;
   4309 
   4310  if (msg->command == RELAY_COMMAND_BEGIN_DIR) {
   4311    tor_addr_t tmp_addr;
   4312    tor_assert(or_circ);
   4313    if (or_circ->p_chan &&
   4314        channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
   4315      tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
   4316    }
   4317    return connection_exit_connect_dir(n_stream);
   4318  }
   4319 
   4320  log_debug(LD_EXIT,"about to start the dns_resolve().");
   4321 
   4322  // in the future we may want to have a similar defense for BEGIN_DIR and
   4323  // BEGIN sent to OS.
   4324  dos_defense_type = dos_stream_new_begin_or_resolve_cell(or_circ);
   4325  switch (dos_defense_type) {
   4326    case DOS_STREAM_DEFENSE_NONE:
   4327      break;
   4328    case DOS_STREAM_DEFENSE_REFUSE_STREAM:
   4329      // we don't use END_STREAM_REASON_RESOURCELIMIT because it would make a
   4330      // client mark us as non-functional until they get a new consensus.
   4331      relay_send_end_cell_from_edge(msg->stream_id, circ,
   4332                                    END_STREAM_REASON_MISC, layer_hint);
   4333      connection_free_(TO_CONN(n_stream));
   4334      return 0;
   4335    case DOS_STREAM_DEFENSE_CLOSE_CIRCUIT:
   4336      connection_free_(TO_CONN(n_stream));
   4337      return -END_CIRC_REASON_RESOURCELIMIT;
   4338  }
   4339 
   4340  /* send it off to the gethostbyname farm */
   4341  switch (dns_resolve(n_stream)) {
   4342    case 1: /* resolve worked; now n_stream is attached to circ. */
   4343      assert_circuit_ok(circ);
   4344      log_debug(LD_EXIT,"about to call connection_exit_connect().");
   4345      connection_exit_connect(n_stream);
   4346      return 0;
   4347    case -1: /* resolve failed */
   4348      relay_send_end_cell_from_edge(msg->stream_id, circ,
   4349                                    END_STREAM_REASON_RESOLVEFAILED, NULL);
   4350      /* n_stream got freed. don't touch it. */
   4351      break;
   4352    case 0: /* resolve added to pending list */
   4353      assert_circuit_ok(circ);
   4354      break;
   4355  }
   4356  return 0;
   4357 }
   4358 
   4359 /**
   4360 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
   4361 * circuit <b>circ</b>;
   4362 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
   4363 *
   4364 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
   4365 * Else return 0.
   4366 */
   4367 int
   4368 connection_exit_begin_resolve(const relay_msg_t *msg, or_circuit_t *circ)
   4369 {
   4370  edge_connection_t *dummy_conn;
   4371  dos_stream_defense_type_t dos_defense_type;
   4372 
   4373  assert_circuit_ok(TO_CIRCUIT(circ));
   4374 
   4375  /* Note the RESOLVE stream as seen. */
   4376  rep_hist_note_exit_stream(RELAY_COMMAND_RESOLVE);
   4377 
   4378  /* This 'dummy_conn' only exists to remember the stream ID
   4379   * associated with the resolve request; and to make the
   4380   * implementation of dns.c more uniform.  (We really only need to
   4381   * remember the circuit, the stream ID, and the hostname to be
   4382   * resolved; but if we didn't store them in a connection like this,
   4383   * the housekeeping in dns.c would get way more complicated.)
   4384   */
   4385  dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
   4386  dummy_conn->stream_id = msg->stream_id;
   4387  dummy_conn->base_.address = tor_strndup((char *) msg->body, msg->length);
   4388  dummy_conn->base_.port = 0;
   4389  dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
   4390  dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
   4391 
   4392  dummy_conn->on_circuit = TO_CIRCUIT(circ);
   4393 
   4394  dos_defense_type = dos_stream_new_begin_or_resolve_cell(circ);
   4395  switch (dos_defense_type) {
   4396    case DOS_STREAM_DEFENSE_NONE:
   4397      break;
   4398    case DOS_STREAM_DEFENSE_REFUSE_STREAM:
   4399      dns_send_resolved_error_cell(dummy_conn, RESOLVED_TYPE_ERROR_TRANSIENT);
   4400      connection_free_(TO_CONN(dummy_conn));
   4401      return 0;
   4402    case DOS_STREAM_DEFENSE_CLOSE_CIRCUIT:
   4403      connection_free_(TO_CONN(dummy_conn));
   4404      return -END_CIRC_REASON_RESOURCELIMIT;
   4405  }
   4406 
   4407  /* send it off to the gethostbyname farm */
   4408  switch (dns_resolve(dummy_conn)) {
   4409    case -1: /* Impossible to resolve; a resolved cell was sent. */
   4410      /* Connection freed; don't touch it. */
   4411      return 0;
   4412    case 1: /* The result was cached; a resolved cell was sent. */
   4413      if (!dummy_conn->base_.marked_for_close)
   4414        connection_free_(TO_CONN(dummy_conn));
   4415      return 0;
   4416    case 0: /* resolve added to pending list */
   4417      assert_circuit_ok(TO_CIRCUIT(circ));
   4418      break;
   4419  }
   4420  return 0;
   4421 }
   4422 
   4423 /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
   4424 * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
   4425 */
   4426 static int
   4427 my_exit_policy_rejects(const tor_addr_t *addr,
   4428                       uint16_t port,
   4429                       const char **why_rejected)
   4430 {
   4431  if (router_compare_to_my_exit_policy(addr, port)) {
   4432    *why_rejected = "";
   4433    return 1;
   4434  } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
   4435    *why_rejected = " (IPv6 address without IPv6Exit configured)";
   4436    return 1;
   4437  }
   4438  return 0;
   4439 }
   4440 
   4441 /* Reapply exit policy to existing connections, possibly terminating
   4442 * connections
   4443 * no longer allowed by the policy.
   4444 */
   4445 void
   4446 connection_reapply_exit_policy(config_line_t *changes)
   4447 {
   4448  int marked_for_close = 0;
   4449  smartlist_t *conn_list = NULL;
   4450  smartlist_t *policy = NULL;
   4451  int config_change_relevant = 0;
   4452 
   4453  if (get_options()->ReevaluateExitPolicy == 0) {
   4454    return;
   4455  }
   4456 
   4457  for (const config_line_t *line = changes;
   4458       line && !config_change_relevant;
   4459       line = line->next) {
   4460    const char* exit_policy_options[] = {
   4461      "ExitRelay",
   4462      "ExitPolicy",
   4463      "ReducedExitPolicy",
   4464      "ReevaluateExitPolicy",
   4465      "IPv6Exit",
   4466      NULL
   4467    };
   4468    for (unsigned int i = 0; exit_policy_options[i] != NULL; ++i) {
   4469      if (strcmp(line->key, exit_policy_options[i]) == 0) {
   4470        config_change_relevant = 1;
   4471        break;
   4472      }
   4473    }
   4474  }
   4475 
   4476  if (!config_change_relevant) {
   4477    /* Policy did not change: no need to iterate over connections */
   4478    return;
   4479  }
   4480 
   4481  // we can't use router_compare_to_my_exit_policy as it depend on the
   4482  // descriptor, which is regenerated asynchronously, so we have to parse the
   4483  // policy ourselves.
   4484  // We don't verify for our own IP, it's not part of the configuration.
   4485  if (BUG(policies_parse_exit_policy_from_options(get_options(), NULL, NULL,
   4486                                                  &policy) != 0)) {
   4487    return;
   4488  }
   4489 
   4490  conn_list = connection_list_by_type_purpose(CONN_TYPE_EXIT,
   4491                                              EXIT_PURPOSE_CONNECT);
   4492 
   4493  SMARTLIST_FOREACH_BEGIN(conn_list, connection_t *, conn) {
   4494    addr_policy_result_t verdict = compare_tor_addr_to_addr_policy(&conn->addr,
   4495                                                                   conn->port,
   4496                                                                   policy);
   4497    if (verdict != ADDR_POLICY_ACCEPTED) {
   4498      connection_edge_end(TO_EDGE_CONN(conn), END_STREAM_REASON_EXITPOLICY);
   4499      connection_mark_for_close(conn);
   4500      ++marked_for_close;
   4501    }
   4502  } SMARTLIST_FOREACH_END(conn);
   4503 
   4504  smartlist_free(conn_list);
   4505  smartlist_free(policy);
   4506 
   4507  log_info(LD_GENERAL, "Marked %d connections to be closed as no longer "
   4508           "allowed per ExitPolicy", marked_for_close);
   4509 }
   4510 
   4511 /** Return true iff the consensus allows network reentry. The default value is
   4512 * false if the parameter is not found. */
   4513 static bool
   4514 network_reentry_is_allowed(void)
   4515 {
   4516  /* Default is false, re-entry is not allowed. */
   4517  return !!networkstatus_get_param(NULL, "allow-network-reentry", 0, 0, 1);
   4518 }
   4519 
   4520 /** Connect to conn's specified addr and port. If it worked, conn
   4521 * has now been added to the connection_array.
   4522 *
   4523 * Send back a connected cell. Include the resolved IP of the destination
   4524 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
   4525 * streams must not reveal what IP they connected to.)
   4526 */
   4527 void
   4528 connection_exit_connect(edge_connection_t *edge_conn)
   4529 {
   4530  const tor_addr_t *addr;
   4531  uint16_t port;
   4532  connection_t *conn = TO_CONN(edge_conn);
   4533  int socket_error = 0, result;
   4534  const char *why_failed_exit_policy = NULL;
   4535 
   4536  /* Apply exit policy to non-rendezvous connections. */
   4537  if (! connection_edge_is_rendezvous_stream(edge_conn) &&
   4538      my_exit_policy_rejects(&edge_conn->base_.addr,
   4539                             edge_conn->base_.port,
   4540                             &why_failed_exit_policy)) {
   4541    if (BUG(!why_failed_exit_policy))
   4542      why_failed_exit_policy = "";
   4543    log_info(LD_EXIT,"%s failed exit policy%s. Closing.",
   4544             connection_describe(conn),
   4545             why_failed_exit_policy);
   4546    rep_hist_note_conn_rejected(conn->type, conn->socket_family);
   4547    connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
   4548    circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
   4549    connection_free(conn);
   4550    return;
   4551  }
   4552 
   4553  /* Next, check for attempts to connect back into the Tor network. We don't
   4554   * want to allow these for the same reason we don't want to allow
   4555   * infinite-length circuits (see "A Practical Congestion Attack on Tor Using
   4556   * Long Paths", Usenix Security 2009). See also ticket 2667.
   4557   *
   4558   * Skip this if the network reentry is allowed (known from the consensus).
   4559   *
   4560   * The TORPROTOCOL reason is used instead of EXITPOLICY so client do NOT
   4561   * attempt to retry connecting onto another circuit that will also fail
   4562   * bringing considerable more load on the network if so.
   4563   *
   4564   * Since the address+port set here is a bloomfilter, in very rare cases, the
   4565   * check will create a false positive meaning that the destination could
   4566   * actually be legit and thus being denied exit. However, sending back a
   4567   * reason that makes the client retry results in much worst consequences in
   4568   * case of an attack so this is a small price to pay. */
   4569  if (!connection_edge_is_rendezvous_stream(edge_conn) &&
   4570      !network_reentry_is_allowed() &&
   4571      nodelist_reentry_contains(&conn->addr, conn->port)) {
   4572    log_info(LD_EXIT, "%s tried to connect back to a known relay address. "
   4573                      "Closing.", connection_describe(conn));
   4574    rep_hist_note_conn_rejected(conn->type, conn->socket_family);
   4575    connection_edge_end(edge_conn, END_STREAM_REASON_CONNECTREFUSED);
   4576    circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
   4577    connection_free(conn);
   4578    return;
   4579  }
   4580 
   4581  /* Note the BEGIN stream as seen. We do this after the Exit policy check in
   4582   * order to only account for valid streams. */
   4583  rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN);
   4584 
   4585 #ifdef HAVE_SYS_UN_H
   4586  if (conn->socket_family != AF_UNIX) {
   4587 #else
   4588  {
   4589 #endif /* defined(HAVE_SYS_UN_H) */
   4590    addr = &conn->addr;
   4591    port = conn->port;
   4592 
   4593    if (tor_addr_family(addr) == AF_INET6)
   4594      conn->socket_family = AF_INET6;
   4595 
   4596    log_debug(LD_EXIT, "about to try connecting");
   4597    result = connection_connect(conn, conn->address,
   4598                                addr, port, &socket_error);
   4599 #ifdef HAVE_SYS_UN_H
   4600  } else {
   4601    /*
   4602     * In the AF_UNIX case, we expect to have already had conn->port = 1,
   4603     * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
   4604     * case in connection_handle_listener_read()), and conn->address should
   4605     * have the socket path to connect to.
   4606     */
   4607    tor_assert(conn->address && strlen(conn->address) > 0);
   4608 
   4609    log_debug(LD_EXIT, "about to try connecting");
   4610    result = connection_connect_unix(conn, conn->address, &socket_error);
   4611 #endif /* defined(HAVE_SYS_UN_H) */
   4612  }
   4613 
   4614  switch (result) {
   4615    case -1: {
   4616      int reason = errno_to_stream_end_reason(socket_error);
   4617      connection_edge_end(edge_conn, reason);
   4618      circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
   4619      connection_free(conn);
   4620      return;
   4621    }
   4622    case 0:
   4623      conn->state = EXIT_CONN_STATE_CONNECTING;
   4624 
   4625      connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
   4626      /* writable indicates finish;
   4627       * readable/error indicates broken link in windows-land. */
   4628      return;
   4629    /* case 1: fall through */
   4630  }
   4631 
   4632  conn->state = EXIT_CONN_STATE_OPEN;
   4633  if (connection_get_outbuf_len(conn)) {
   4634    /* in case there are any queued data cells, from e.g. optimistic data */
   4635    connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
   4636  } else {
   4637    connection_watch_events(conn, READ_EVENT);
   4638  }
   4639 
   4640  /* also, deliver a 'connected' cell back through the circuit. */
   4641  if (connection_edge_is_rendezvous_stream(edge_conn)) {
   4642    /* don't send an address back! */
   4643    connection_edge_send_command(edge_conn,
   4644                                 RELAY_COMMAND_CONNECTED,
   4645                                 NULL, 0);
   4646  } else { /* normal stream */
   4647    uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
   4648    int connected_payload_len =
   4649      connected_cell_format_payload(connected_payload, &conn->addr,
   4650                                    edge_conn->address_ttl);
   4651    if (connected_payload_len < 0) {
   4652      connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
   4653      circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
   4654      connection_free(conn);
   4655      return;
   4656    }
   4657 
   4658    connection_edge_send_command(edge_conn,
   4659                                 RELAY_COMMAND_CONNECTED,
   4660                                 (char*)connected_payload,
   4661                                 connected_payload_len);
   4662  }
   4663 }
   4664 
   4665 /** Given an exit conn that should attach to us as a directory server, open a
   4666 * bridge connection with a linked connection pair, create a new directory
   4667 * conn, and join them together.  Return 0 on success (or if there was an
   4668 * error we could send back an end cell for).  Return -(some circuit end
   4669 * reason) if the circuit needs to be torn down.  Either connects
   4670 * <b>exitconn</b>, frees it, or marks it, as appropriate.
   4671 */
   4672 static int
   4673 connection_exit_connect_dir(edge_connection_t *exitconn)
   4674 {
   4675  dir_connection_t *dirconn = NULL;
   4676  or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
   4677 
   4678  log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
   4679 
   4680  /* Note the BEGIN_DIR stream as seen. */
   4681  rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN_DIR);
   4682 
   4683  exitconn->base_.state = EXIT_CONN_STATE_OPEN;
   4684 
   4685  dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
   4686 
   4687  tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
   4688  dirconn->base_.port = 0;
   4689  dirconn->base_.address = tor_strdup(exitconn->base_.address);
   4690  dirconn->base_.type = CONN_TYPE_DIR;
   4691  dirconn->base_.purpose = DIR_PURPOSE_SERVER;
   4692  dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
   4693 
   4694  /* Note that the new dir conn belongs to the same tunneled request as
   4695   * the edge conn, so that we can measure download times. */
   4696  dirconn->dirreq_id = exitconn->dirreq_id;
   4697 
   4698  connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
   4699 
   4700  if (connection_add(TO_CONN(exitconn))<0) {
   4701    connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
   4702    connection_free_(TO_CONN(exitconn));
   4703    connection_free_(TO_CONN(dirconn));
   4704    return 0;
   4705  }
   4706 
   4707  /* link exitconn to circ, now that we know we can use it. */
   4708  exitconn->next_stream = circ->n_streams;
   4709  circ->n_streams = exitconn;
   4710 
   4711  if (connection_add(TO_CONN(dirconn))<0) {
   4712    connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
   4713    connection_close_immediate(TO_CONN(exitconn));
   4714    connection_mark_for_close(TO_CONN(exitconn));
   4715    connection_free_(TO_CONN(dirconn));
   4716    return 0;
   4717  }
   4718 
   4719  connection_start_reading(TO_CONN(dirconn));
   4720  connection_start_reading(TO_CONN(exitconn));
   4721 
   4722  if (connection_edge_send_command(exitconn,
   4723                                   RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
   4724    connection_mark_for_close(TO_CONN(exitconn));
   4725    connection_mark_for_close(TO_CONN(dirconn));
   4726    return 0;
   4727  }
   4728 
   4729  return 0;
   4730 }
   4731 
   4732 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
   4733 * it is a general stream.
   4734 */
   4735 int
   4736 connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
   4737 {
   4738  tor_assert(conn);
   4739 
   4740  if (conn->hs_ident) {
   4741    return 1;
   4742  }
   4743  return 0;
   4744 }
   4745 
   4746 /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
   4747 * to exit from it, or 0 if it probably will not allow it.
   4748 * (We might be uncertain if conn's destination address has not yet been
   4749 * resolved.)
   4750 */
   4751 int
   4752 connection_ap_can_use_exit(const entry_connection_t *conn,
   4753                           const node_t *exit_node)
   4754 {
   4755  const or_options_t *options = get_options();
   4756 
   4757  tor_assert(conn);
   4758  tor_assert(conn->socks_request);
   4759  tor_assert(exit_node);
   4760 
   4761  /* If a particular exit node has been requested for the new connection,
   4762   * make sure the exit node of the existing circuit matches exactly.
   4763   */
   4764  if (conn->chosen_exit_name) {
   4765    const node_t *chosen_exit =
   4766      node_get_by_nickname(conn->chosen_exit_name, 0);
   4767    if (!chosen_exit || tor_memneq(chosen_exit->identity,
   4768                               exit_node->identity, DIGEST_LEN)) {
   4769      /* doesn't match */
   4770 //      log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
   4771 //                conn->chosen_exit_name, exit->nickname);
   4772      return 0;
   4773    }
   4774  }
   4775 
   4776  if (conn->use_begindir) {
   4777    /* Internal directory fetches do not count as exiting. */
   4778    return 1;
   4779  }
   4780 
   4781  if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
   4782    tor_addr_t addr, *addrp = NULL;
   4783    addr_policy_result_t r;
   4784    if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
   4785      addrp = &addr;
   4786    } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
   4787      tor_addr_make_null(&addr, AF_INET6);
   4788      addrp = &addr;
   4789    } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
   4790      tor_addr_make_null(&addr, AF_INET);
   4791      addrp = &addr;
   4792    }
   4793    r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,
   4794                                        exit_node);
   4795    if (r == ADDR_POLICY_REJECTED)
   4796      return 0; /* We know the address, and the exit policy rejects it. */
   4797    if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
   4798      return 0; /* We don't know the addr, but the exit policy rejects most
   4799                 * addresses with this port. Since the user didn't ask for
   4800                 * this node, err on the side of caution. */
   4801  } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
   4802    /* Don't send DNS requests to non-exit servers by default. */
   4803    if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
   4804      return 0;
   4805  }
   4806  if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
   4807    /* Not a suitable exit. Refuse it. */
   4808    return 0;
   4809  }
   4810 
   4811  return 1;
   4812 }
   4813 
   4814 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
   4815 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
   4816 * at <b>b</b>. */
   4817 static int
   4818 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
   4819 {
   4820  if (a == NULL) {
   4821    return (b == NULL);
   4822  } else if (b == NULL) {
   4823    return 0;
   4824  } else if (alen != blen) {
   4825    return 0;
   4826  } else {
   4827    return tor_memeq(a, b, alen);
   4828  }
   4829 }
   4830 
   4831 /**
   4832 * Return true iff none of the isolation flags and fields in <b>conn</b>
   4833 * should prevent it from being attached to <b>circ</b>.
   4834 */
   4835 int
   4836 connection_edge_compatible_with_circuit(const entry_connection_t *conn,
   4837                                        const origin_circuit_t *circ)
   4838 {
   4839  const uint8_t iso = conn->entry_cfg.isolation_flags;
   4840  const socks_request_t *sr = conn->socks_request;
   4841 
   4842  /* If circ has never been used for an isolated connection, we can
   4843   * totally use it for this one. */
   4844  if (!circ->isolation_values_set)
   4845    return 1;
   4846 
   4847  /* If circ has been used for connections having more than one value
   4848   * for some field f, it will have the corresponding bit set in
   4849   * isolation_flags_mixed.  If isolation_flags_mixed has any bits
   4850   * in common with iso, then conn must be isolated from at least
   4851   * one stream that has been attached to circ. */
   4852  if ((iso & circ->isolation_flags_mixed) != 0) {
   4853    /* For at least one field where conn is isolated, the circuit
   4854     * already has mixed streams. */
   4855    return 0;
   4856  }
   4857 
   4858  if (! conn->original_dest_address) {
   4859    log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
   4860             "having set conn->original_dest_address");
   4861    ((entry_connection_t*)conn)->original_dest_address =
   4862      tor_strdup(conn->socks_request->address);
   4863  }
   4864 
   4865  if ((iso & ISO_STREAM) &&
   4866      (circ->associated_isolated_stream_global_id !=
   4867       ENTRY_TO_CONN(conn)->global_identifier))
   4868    return 0;
   4869 
   4870  if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
   4871    return 0;
   4872  if ((iso & ISO_DESTADDR) &&
   4873      strcasecmp(conn->original_dest_address, circ->dest_address))
   4874    return 0;
   4875  if ((iso & ISO_SOCKSAUTH) &&
   4876      (! memeq_opt(sr->username, sr->usernamelen,
   4877                   circ->socks_username, circ->socks_username_len) ||
   4878       ! memeq_opt(sr->password, sr->passwordlen,
   4879                   circ->socks_password, circ->socks_password_len)))
   4880    return 0;
   4881  if ((iso & ISO_CLIENTPROTO) &&
   4882      (conn->socks_request->listener_type != circ->client_proto_type ||
   4883       conn->socks_request->socks_version != circ->client_proto_socksver))
   4884    return 0;
   4885  if ((iso & ISO_CLIENTADDR) &&
   4886      !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
   4887    return 0;
   4888  if ((iso & ISO_SESSIONGRP) &&
   4889      conn->entry_cfg.session_group != circ->session_group)
   4890    return 0;
   4891  if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
   4892    return 0;
   4893 
   4894  return 1;
   4895 }
   4896 
   4897 /**
   4898 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
   4899 * to reflect having had <b>conn</b> attached to it, and return 0.  Otherwise,
   4900 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
   4901 * a bitfield of isolation flags that we would have to set in
   4902 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
   4903 * <b>circ</b> has had no streams attached to it.
   4904 */
   4905 int
   4906 connection_edge_update_circuit_isolation(const entry_connection_t *conn,
   4907                                         origin_circuit_t *circ,
   4908                                         int dry_run)
   4909 {
   4910  const socks_request_t *sr = conn->socks_request;
   4911  if (! conn->original_dest_address) {
   4912    log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
   4913             "having set conn->original_dest_address");
   4914    ((entry_connection_t*)conn)->original_dest_address =
   4915      tor_strdup(conn->socks_request->address);
   4916  }
   4917 
   4918  if (!circ->isolation_values_set) {
   4919    if (dry_run)
   4920      return -1;
   4921    circ->associated_isolated_stream_global_id =
   4922      ENTRY_TO_CONN(conn)->global_identifier;
   4923    circ->dest_port = conn->socks_request->port;
   4924    circ->dest_address = tor_strdup(conn->original_dest_address);
   4925    circ->client_proto_type = conn->socks_request->listener_type;
   4926    circ->client_proto_socksver = conn->socks_request->socks_version;
   4927    tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
   4928    circ->session_group = conn->entry_cfg.session_group;
   4929    circ->nym_epoch = conn->nym_epoch;
   4930    circ->socks_username = sr->username ?
   4931      tor_memdup(sr->username, sr->usernamelen) : NULL;
   4932    circ->socks_password = sr->password ?
   4933      tor_memdup(sr->password, sr->passwordlen) : NULL;
   4934    circ->socks_username_len = sr->usernamelen;
   4935    circ->socks_password_len = sr->passwordlen;
   4936 
   4937    circ->isolation_values_set = 1;
   4938    return 0;
   4939  } else {
   4940    uint8_t mixed = 0;
   4941    if (conn->socks_request->port != circ->dest_port)
   4942      mixed |= ISO_DESTPORT;
   4943    if (strcasecmp(conn->original_dest_address, circ->dest_address))
   4944      mixed |= ISO_DESTADDR;
   4945    if (!memeq_opt(sr->username, sr->usernamelen,
   4946                   circ->socks_username, circ->socks_username_len) ||
   4947        !memeq_opt(sr->password, sr->passwordlen,
   4948                   circ->socks_password, circ->socks_password_len))
   4949      mixed |= ISO_SOCKSAUTH;
   4950    if ((conn->socks_request->listener_type != circ->client_proto_type ||
   4951         conn->socks_request->socks_version != circ->client_proto_socksver))
   4952      mixed |= ISO_CLIENTPROTO;
   4953    if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
   4954      mixed |= ISO_CLIENTADDR;
   4955    if (conn->entry_cfg.session_group != circ->session_group)
   4956      mixed |= ISO_SESSIONGRP;
   4957    if (conn->nym_epoch != circ->nym_epoch)
   4958      mixed |= ISO_NYM_EPOCH;
   4959 
   4960    if (dry_run)
   4961      return mixed;
   4962 
   4963    if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
   4964      log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
   4965               "isolation flags.");
   4966    }
   4967    circ->isolation_flags_mixed |= mixed;
   4968    return 0;
   4969  }
   4970 }
   4971 
   4972 /**
   4973 * Clear the isolation settings on <b>circ</b>.
   4974 *
   4975 * This only works on an open circuit that has never had a stream attached to
   4976 * it, and whose isolation settings are hypothetical.  (We set hypothetical
   4977 * isolation settings on circuits as we're launching them, so that we
   4978 * know whether they can handle more streams or whether we need to launch
   4979 * even more circuits.  Once the circuit is open, if it turns out that
   4980 * we no longer have any streams to attach to it, we clear the isolation flags
   4981 * and data so that other streams can have a chance.)
   4982 */
   4983 void
   4984 circuit_clear_isolation(origin_circuit_t *circ)
   4985 {
   4986  if (circ->isolation_any_streams_attached) {
   4987    log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
   4988    return;
   4989  }
   4990  if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
   4991    log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
   4992             "circuit");
   4993    return;
   4994  }
   4995 
   4996  circ->isolation_values_set = 0;
   4997  circ->isolation_flags_mixed = 0;
   4998  circ->associated_isolated_stream_global_id = 0;
   4999  circ->client_proto_type = 0;
   5000  circ->client_proto_socksver = 0;
   5001  circ->dest_port = 0;
   5002  tor_addr_make_unspec(&circ->client_addr);
   5003  tor_free(circ->dest_address);
   5004  circ->session_group = -1;
   5005  circ->nym_epoch = 0;
   5006  if (circ->socks_username) {
   5007    memwipe(circ->socks_username, 0x11, circ->socks_username_len);
   5008    tor_free(circ->socks_username);
   5009  }
   5010  if (circ->socks_password) {
   5011    memwipe(circ->socks_password, 0x05, circ->socks_password_len);
   5012    tor_free(circ->socks_password);
   5013  }
   5014  circ->socks_username_len = circ->socks_password_len = 0;
   5015 }
   5016 
   5017 /** Send an END and mark for close the given edge connection conn using the
   5018 * given reason that has to be a stream reason.
   5019 *
   5020 * Note: We don't unattached the AP connection (if applicable) because we
   5021 * don't want to flush the remaining data. This function aims at ending
   5022 * everything quickly regardless of the connection state.
   5023 *
   5024 * This function can't fail and does nothing if conn is NULL. */
   5025 void
   5026 connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
   5027 {
   5028  if (!conn) {
   5029    return;
   5030  }
   5031 
   5032  connection_edge_end(conn, reason);
   5033  connection_mark_for_close(TO_CONN(conn));
   5034 }
   5035 
   5036 /** Free all storage held in module-scoped variables for connection_edge.c */
   5037 void
   5038 connection_edge_free_all(void)
   5039 {
   5040  untried_pending_connections = 0;
   5041  smartlist_free(pending_entry_connections);
   5042  pending_entry_connections = NULL;
   5043  mainloop_event_free(attach_pending_entry_connections_ev);
   5044 }