Avoid crashing if we call num_usable_bridges() when bridges are not enabled
[tor/appveyor.git] / src / or / connection_edge.c
blobf178917f0bfe21725100b8f4eb6d6b934cd4d3d4
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-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_edge.c
9 * \brief Handle edge streams.
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.
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.
22 * Not every instance of edge_connection_t truly represents an edge connction,
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>
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.
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.
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.
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
58 #include "or.h"
60 #include "backtrace.h"
62 #include "addressmap.h"
63 #include "buffers.h"
64 #include "channel.h"
65 #include "circpathbias.h"
66 #include "circuitlist.h"
67 #include "circuituse.h"
68 #include "config.h"
69 #include "connection.h"
70 #include "connection_edge.h"
71 #include "connection_or.h"
72 #include "control.h"
73 #include "dns.h"
74 #include "dnsserv.h"
75 #include "directory.h"
76 #include "dirserv.h"
77 #include "hibernate.h"
78 #include "hs_common.h"
79 #include "hs_cache.h"
80 #include "hs_client.h"
81 #include "hs_circuit.h"
82 #include "main.h"
83 #include "networkstatus.h"
84 #include "nodelist.h"
85 #include "policies.h"
86 #include "proto_http.h"
87 #include "proto_socks.h"
88 #include "reasons.h"
89 #include "relay.h"
90 #include "rendclient.h"
91 #include "rendcommon.h"
92 #include "rendservice.h"
93 #include "rephist.h"
94 #include "router.h"
95 #include "routerlist.h"
96 #include "routerset.h"
97 #include "circuitbuild.h"
99 #ifdef HAVE_LINUX_TYPES_H
100 #include <linux/types.h>
101 #endif
102 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
103 #include <linux/netfilter_ipv4.h>
104 #define TRANS_NETFILTER
105 #define TRANS_NETFILTER_IPV4
106 #endif
108 #ifdef HAVE_LINUX_IF_H
109 #include <linux/if.h>
110 #endif
112 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
113 #include <linux/netfilter_ipv6/ip6_tables.h>
114 #if defined(IP6T_SO_ORIGINAL_DST)
115 #define TRANS_NETFILTER
116 #define TRANS_NETFILTER_IPV6
117 #endif
118 #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
120 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
121 #include <net/if.h>
122 #include <net/pfvar.h>
123 #define TRANS_PF
124 #endif
126 #ifdef IP_TRANSPARENT
127 #define TRANS_TPROXY
128 #endif
130 #define SOCKS4_GRANTED 90
131 #define SOCKS4_REJECT 91
133 static int connection_ap_handshake_process_socks(entry_connection_t *conn);
134 static int connection_ap_process_natd(entry_connection_t *conn);
135 static int connection_exit_connect_dir(edge_connection_t *exitconn);
136 static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
137 static int connection_ap_supports_optimistic_data(const entry_connection_t *);
139 /** An AP stream has failed/finished. If it hasn't already sent back
140 * a socks reply, send one now (based on endreason). Also set
141 * has_sent_end to 1, and mark the conn.
143 MOCK_IMPL(void,
144 connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
145 int line, const char *file))
147 connection_t *base_conn = ENTRY_TO_CONN(conn);
148 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
149 tor_assert(base_conn->type == CONN_TYPE_AP);
150 ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
152 /* If this is a rendezvous stream and it is failing without ever
153 * being attached to a circuit, assume that an attempt to connect to
154 * the destination hidden service has just ended.
156 * XXXX This condition doesn't limit to only streams failing
157 * without ever being attached. That sloppiness should be harmless,
158 * but we should fix it someday anyway. */
159 if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
160 connection_edge_is_rendezvous_stream(edge_conn)) {
161 if (edge_conn->rend_data) {
162 rend_client_note_connection_attempt_ended(edge_conn->rend_data);
166 if (base_conn->marked_for_close) {
167 /* This call will warn as appropriate. */
168 connection_mark_for_close_(base_conn, line, file);
169 return;
172 if (!conn->socks_request->has_finished) {
173 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
174 log_warn(LD_BUG,
175 "stream (marked at %s:%d) sending two socks replies?",
176 file, line);
178 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
179 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
180 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
181 connection_ap_handshake_socks_resolved(conn,
182 RESOLVED_TYPE_ERROR_TRANSIENT,
183 0, NULL, -1, -1);
184 else /* unknown or no handshake at all. send no response. */
185 conn->socks_request->has_finished = 1;
188 connection_mark_and_flush_(base_conn, line, file);
190 ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
193 /** There was an EOF. Send an end and mark the connection for close.
196 connection_edge_reached_eof(edge_connection_t *conn)
198 if (connection_get_inbuf_len(TO_CONN(conn)) &&
199 connection_state_is_open(TO_CONN(conn))) {
200 /* it still has stuff to process. don't let it die yet. */
201 return 0;
203 log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
204 conn->base_.s);
205 if (!conn->base_.marked_for_close) {
206 /* only mark it if not already marked. it's possible to
207 * get the 'end' right around when the client hangs up on us. */
208 connection_edge_end(conn, END_STREAM_REASON_DONE);
209 if (conn->base_.type == CONN_TYPE_AP) {
210 /* eof, so don't send a socks reply back */
211 if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
212 EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
214 connection_mark_for_close(TO_CONN(conn));
216 return 0;
219 /** Handle new bytes on conn->inbuf based on state:
220 * - If it's waiting for socks info, try to read another step of the
221 * socks handshake out of conn->inbuf.
222 * - If it's waiting for the original destination, fetch it.
223 * - If it's open, then package more relay cells from the stream.
224 * - Else, leave the bytes on inbuf alone for now.
226 * Mark and return -1 if there was an unexpected error with the conn,
227 * else return 0.
230 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
232 tor_assert(conn);
234 switch (conn->base_.state) {
235 case AP_CONN_STATE_SOCKS_WAIT:
236 if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
237 /* already marked */
238 return -1;
240 return 0;
241 case AP_CONN_STATE_NATD_WAIT:
242 if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
243 /* already marked */
244 return -1;
246 return 0;
247 case AP_CONN_STATE_HTTP_CONNECT_WAIT:
248 if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn)) < 0) {
249 return -1;
251 return 0;
252 case AP_CONN_STATE_OPEN:
253 case EXIT_CONN_STATE_OPEN:
254 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
255 /* (We already sent an end cell if possible) */
256 connection_mark_for_close(TO_CONN(conn));
257 return -1;
259 return 0;
260 case AP_CONN_STATE_CONNECT_WAIT:
261 if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
262 log_info(LD_EDGE,
263 "data from edge while in '%s' state. Sending it anyway. "
264 "package_partial=%d, buflen=%ld",
265 conn_state_to_string(conn->base_.type, conn->base_.state),
266 package_partial,
267 (long)connection_get_inbuf_len(TO_CONN(conn)));
268 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
269 /* (We already sent an end cell if possible) */
270 connection_mark_for_close(TO_CONN(conn));
271 return -1;
273 return 0;
275 /* Fall through if the connection is on a circuit without optimistic
276 * data support. */
277 /* Falls through. */
278 case EXIT_CONN_STATE_CONNECTING:
279 case AP_CONN_STATE_RENDDESC_WAIT:
280 case AP_CONN_STATE_CIRCUIT_WAIT:
281 case AP_CONN_STATE_RESOLVE_WAIT:
282 case AP_CONN_STATE_CONTROLLER_WAIT:
283 log_info(LD_EDGE,
284 "data from edge while in '%s' state. Leaving it on buffer.",
285 conn_state_to_string(conn->base_.type, conn->base_.state));
286 return 0;
288 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
289 tor_fragile_assert();
290 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
291 connection_mark_for_close(TO_CONN(conn));
292 return -1;
295 /** This edge needs to be closed, because its circuit has closed.
296 * Mark it for close and return 0.
299 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
301 if (!conn->base_.marked_for_close) {
302 log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
303 (unsigned) circ_id);
304 if (conn->base_.type == CONN_TYPE_AP) {
305 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
306 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
307 control_event_stream_bandwidth(conn);
308 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
309 END_STREAM_REASON_DESTROY);
310 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
311 } else {
312 /* closing the circuit, nothing to send an END to */
313 conn->edge_has_sent_end = 1;
314 conn->end_reason = END_STREAM_REASON_DESTROY;
315 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
316 connection_mark_and_flush(TO_CONN(conn));
319 conn->cpath_layer = NULL;
320 conn->on_circuit = NULL;
321 return 0;
324 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
325 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
326 * is not a client connection, set the relay end cell's reason for closing
327 * as <b>reason</b> */
328 static int
329 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
330 uint8_t reason, crypt_path_t *cpath_layer)
332 char payload[1];
334 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
335 /* Never send the server an informative reason code; it doesn't need to
336 * know why the client stream is failing. */
337 reason = END_STREAM_REASON_MISC;
340 payload[0] = (char) reason;
342 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
343 payload, 1, cpath_layer);
346 /* If the connection <b>conn</b> is attempting to connect to an external
347 * destination that is an hidden service and the reason is a connection
348 * refused or timeout, log it so the operator can take appropriate actions.
349 * The log statement is a rate limited warning. */
350 static void
351 warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
353 tor_assert(conn);
355 if (conn->base_.type == CONN_TYPE_EXIT &&
356 connection_edge_is_rendezvous_stream(conn) &&
357 (reason == END_STREAM_REASON_CONNECTREFUSED ||
358 reason == END_STREAM_REASON_TIMEOUT)) {
359 #define WARN_FAILED_HS_CONNECTION 300
360 static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
361 char *m;
362 if ((m = rate_limit_log(&warn_limit, approx_time()))) {
363 log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
364 (conn->base_.socket_family == AF_UNIX) ?
365 safe_str(conn->base_.address) :
366 safe_str(fmt_addrport(&conn->base_.addr, conn->base_.port)),
367 stream_end_reason_to_string(reason));
368 tor_free(m);
373 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
374 * remember that we've done so. If this is not a client connection, set the
375 * relay end cell's reason for closing as <b>reason</b>.
377 * Return -1 if this function has already been called on this conn,
378 * else return 0.
381 connection_edge_end(edge_connection_t *conn, uint8_t reason)
383 char payload[RELAY_PAYLOAD_SIZE];
384 size_t payload_len=1;
385 circuit_t *circ;
386 uint8_t control_reason = reason;
388 if (conn->edge_has_sent_end) {
389 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
390 "on an already ended stream?", reason);
391 tor_fragile_assert();
392 return -1;
395 if (conn->base_.marked_for_close) {
396 log_warn(LD_BUG,
397 "called on conn that's already marked for close at %s:%d.",
398 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
399 return 0;
402 circ = circuit_get_by_edge_conn(conn);
403 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
404 /* If this is a client circuit, don't send the server an informative
405 * reason code; it doesn't need to know why the client stream is
406 * failing. */
407 reason = END_STREAM_REASON_MISC;
410 payload[0] = (char)reason;
411 if (reason == END_STREAM_REASON_EXITPOLICY &&
412 !connection_edge_is_rendezvous_stream(conn)) {
413 int addrlen;
414 if (tor_addr_family(&conn->base_.addr) == AF_INET) {
415 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
416 addrlen = 4;
417 } else {
418 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
419 addrlen = 16;
421 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
422 payload_len += 4+addrlen;
425 if (circ && !circ->marked_for_close) {
426 log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
427 conn->base_.s);
428 connection_edge_send_command(conn, RELAY_COMMAND_END,
429 payload, payload_len);
430 /* We'll log warn if the connection was an hidden service and couldn't be
431 * made because the service wasn't available. */
432 warn_if_hs_unreachable(conn, control_reason);
433 } else {
434 log_debug(LD_EDGE,"No circ to send end on conn "
435 "(fd "TOR_SOCKET_T_FORMAT").",
436 conn->base_.s);
439 conn->edge_has_sent_end = 1;
440 conn->end_reason = control_reason;
441 return 0;
444 /** An error has just occurred on an operation on an edge connection
445 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
446 * appropriate relay end cell to the other end of the connection's circuit.
449 connection_edge_end_errno(edge_connection_t *conn)
451 uint8_t reason;
452 tor_assert(conn);
453 reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
454 return connection_edge_end(conn, reason);
457 /** We just wrote some data to <b>conn</b>; act appropriately.
459 * (That is, if it's open, consider sending a stream-level sendme cell if we
460 * have just flushed enough.)
463 connection_edge_flushed_some(edge_connection_t *conn)
465 switch (conn->base_.state) {
466 case AP_CONN_STATE_OPEN:
467 case EXIT_CONN_STATE_OPEN:
468 connection_edge_consider_sending_sendme(conn);
469 break;
471 return 0;
474 /** Connection <b>conn</b> has finished writing and has no bytes left on
475 * its outbuf.
477 * If it's in state 'open', stop writing, consider responding with a
478 * sendme, and return.
479 * Otherwise, stop writing and return.
481 * If <b>conn</b> is broken, mark it for close and return -1, else
482 * return 0.
485 connection_edge_finished_flushing(edge_connection_t *conn)
487 tor_assert(conn);
489 switch (conn->base_.state) {
490 case AP_CONN_STATE_OPEN:
491 case EXIT_CONN_STATE_OPEN:
492 connection_edge_consider_sending_sendme(conn);
493 return 0;
494 case AP_CONN_STATE_SOCKS_WAIT:
495 case AP_CONN_STATE_NATD_WAIT:
496 case AP_CONN_STATE_RENDDESC_WAIT:
497 case AP_CONN_STATE_CIRCUIT_WAIT:
498 case AP_CONN_STATE_CONNECT_WAIT:
499 case AP_CONN_STATE_CONTROLLER_WAIT:
500 case AP_CONN_STATE_RESOLVE_WAIT:
501 case AP_CONN_STATE_HTTP_CONNECT_WAIT:
502 return 0;
503 default:
504 log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
505 tor_fragile_assert();
506 return -1;
508 return 0;
511 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
512 * able to generate. */
513 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
514 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
516 /** Set the buffer at <b>payload_out</b> -- which must have at least
517 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
518 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
519 * that the name resolution that led us to <b>addr</b> will be valid for
520 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
521 * success. */
522 STATIC int
523 connected_cell_format_payload(uint8_t *payload_out,
524 const tor_addr_t *addr,
525 uint32_t ttl)
527 const sa_family_t family = tor_addr_family(addr);
528 int connected_payload_len;
530 /* should be needless */
531 memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
533 if (family == AF_INET) {
534 set_uint32(payload_out, tor_addr_to_ipv4n(addr));
535 connected_payload_len = 4;
536 } else if (family == AF_INET6) {
537 set_uint32(payload_out, 0);
538 set_uint8(payload_out + 4, 6);
539 memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
540 connected_payload_len = 21;
541 } else {
542 return -1;
545 set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
546 connected_payload_len += 4;
548 tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
550 return connected_payload_len;
553 /** Connected handler for exit connections: start writing pending
554 * data, deliver 'CONNECTED' relay cells as appropriate, and check
555 * any pending data that may have been received. */
557 connection_edge_finished_connecting(edge_connection_t *edge_conn)
559 connection_t *conn;
561 tor_assert(edge_conn);
562 tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
563 conn = TO_CONN(edge_conn);
564 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
566 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
567 escaped_safe_str(conn->address), conn->port,
568 safe_str(fmt_and_decorate_addr(&conn->addr)));
570 rep_hist_note_exit_stream_opened(conn->port);
572 conn->state = EXIT_CONN_STATE_OPEN;
573 connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
574 if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
575 * cells */
576 connection_start_writing(conn);
577 /* deliver a 'connected' relay cell back through the circuit. */
578 if (connection_edge_is_rendezvous_stream(edge_conn)) {
579 if (connection_edge_send_command(edge_conn,
580 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
581 return 0; /* circuit is closed, don't continue */
582 } else {
583 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
584 int connected_payload_len =
585 connected_cell_format_payload(connected_payload, &conn->addr,
586 edge_conn->address_ttl);
587 if (connected_payload_len < 0)
588 return -1;
590 if (connection_edge_send_command(edge_conn,
591 RELAY_COMMAND_CONNECTED,
592 (char*)connected_payload, connected_payload_len) < 0)
593 return 0; /* circuit is closed, don't continue */
595 tor_assert(edge_conn->package_window > 0);
596 /* in case the server has written anything */
597 return connection_edge_process_inbuf(edge_conn, 1);
600 /** A list of all the entry_connection_t * objects that are not marked
601 * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
603 * (Right now, we check in several places to make sure that this list is
604 * correct. When it's incorrect, we'll fix it, and log a BUG message.)
606 static smartlist_t *pending_entry_connections = NULL;
608 static int untried_pending_connections = 0;
610 /** Common code to connection_(ap|exit)_about_to_close. */
611 static void
612 connection_edge_about_to_close(edge_connection_t *edge_conn)
614 if (!edge_conn->edge_has_sent_end) {
615 connection_t *conn = TO_CONN(edge_conn);
616 log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
617 "hasn't sent end yet?",
618 conn->marked_for_close_file, conn->marked_for_close);
619 tor_fragile_assert();
623 /** Called when we're about to finally unlink and free an AP (client)
624 * connection: perform necessary accounting and cleanup */
625 void
626 connection_ap_about_to_close(entry_connection_t *entry_conn)
628 circuit_t *circ;
629 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
630 connection_t *conn = ENTRY_TO_CONN(entry_conn);
632 connection_edge_about_to_close(edge_conn);
634 if (entry_conn->socks_request->has_finished == 0) {
635 /* since conn gets removed right after this function finishes,
636 * there's no point trying to send back a reply at this point. */
637 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
638 " back a socks reply.",
639 conn->marked_for_close_file, conn->marked_for_close);
641 if (!edge_conn->end_reason) {
642 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
643 " set end_reason.",
644 conn->marked_for_close_file, conn->marked_for_close);
646 if (entry_conn->dns_server_request) {
647 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
648 " replied to DNS request.",
649 conn->marked_for_close_file, conn->marked_for_close);
650 dnsserv_reject_request(entry_conn);
653 if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
654 smartlist_remove(pending_entry_connections, entry_conn);
657 #if 1
658 /* Check to make sure that this isn't in pending_entry_connections if it
659 * didn't actually belong there. */
660 if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
661 connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
662 "about_to_close");
664 #endif /* 1 */
666 control_event_stream_bandwidth(edge_conn);
667 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
668 edge_conn->end_reason);
669 circ = circuit_get_by_edge_conn(edge_conn);
670 if (circ)
671 circuit_detach_stream(circ, edge_conn);
674 /** Called when we're about to finally unlink and free an exit
675 * connection: perform necessary accounting and cleanup */
676 void
677 connection_exit_about_to_close(edge_connection_t *edge_conn)
679 circuit_t *circ;
680 connection_t *conn = TO_CONN(edge_conn);
682 connection_edge_about_to_close(edge_conn);
684 circ = circuit_get_by_edge_conn(edge_conn);
685 if (circ)
686 circuit_detach_stream(circ, edge_conn);
687 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
688 connection_dns_remove(edge_conn);
692 /** Define a schedule for how long to wait between retrying
693 * application connections. Rather than waiting a fixed amount of
694 * time between each retry, we wait 10 seconds each for the first
695 * two tries, and 15 seconds for each retry after
696 * that. Hopefully this will improve the expected user experience. */
697 static int
698 compute_retry_timeout(entry_connection_t *conn)
700 int timeout = get_options()->CircuitStreamTimeout;
701 if (timeout) /* if our config options override the default, use them */
702 return timeout;
703 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
704 return 10;
705 return 15;
708 /** Find all general-purpose AP streams waiting for a response that sent their
709 * begin/resolve cell too long ago. Detach from their current circuit, and
710 * mark their current circuit as unsuitable for new streams. Then call
711 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
712 * available) or launch a new one.
714 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
715 * retry attempt).
717 void
718 connection_ap_expire_beginning(void)
720 edge_connection_t *conn;
721 entry_connection_t *entry_conn;
722 circuit_t *circ;
723 time_t now = time(NULL);
724 const or_options_t *options = get_options();
725 int severity;
726 int cutoff;
727 int seconds_idle, seconds_since_born;
728 smartlist_t *conns = get_connection_array();
730 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
731 if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
732 continue;
733 entry_conn = TO_ENTRY_CONN(base_conn);
734 conn = ENTRY_TO_EDGE_CONN(entry_conn);
735 /* if it's an internal linked connection, don't yell its status. */
736 severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
737 ? LOG_INFO : LOG_NOTICE;
738 seconds_idle = (int)( now - base_conn->timestamp_lastread );
739 seconds_since_born = (int)( now - base_conn->timestamp_created );
741 if (base_conn->state == AP_CONN_STATE_OPEN)
742 continue;
744 /* We already consider SocksTimeout in
745 * connection_ap_handshake_attach_circuit(), but we need to consider
746 * it here too because controllers that put streams in controller_wait
747 * state never ask Tor to attach the circuit. */
748 if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
749 if (seconds_since_born >= options->SocksTimeout) {
750 log_fn(severity, LD_APP,
751 "Tried for %d seconds to get a connection to %s:%d. "
752 "Giving up. (%s)",
753 seconds_since_born,
754 safe_str_client(entry_conn->socks_request->address),
755 entry_conn->socks_request->port,
756 conn_state_to_string(CONN_TYPE_AP, base_conn->state));
757 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
759 continue;
762 /* We're in state connect_wait or resolve_wait now -- waiting for a
763 * reply to our relay cell. See if we want to retry/give up. */
765 cutoff = compute_retry_timeout(entry_conn);
766 if (seconds_idle < cutoff)
767 continue;
768 circ = circuit_get_by_edge_conn(conn);
769 if (!circ) { /* it's vanished? */
770 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
771 safe_str_client(entry_conn->socks_request->address));
772 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
773 continue;
775 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
776 if (seconds_idle >= options->SocksTimeout) {
777 log_fn(severity, LD_REND,
778 "Rend stream is %d seconds late. Giving up on address"
779 " '%s.onion'.",
780 seconds_idle,
781 safe_str_client(entry_conn->socks_request->address));
782 /* Roll back path bias use state so that we probe the circuit
783 * if nothing else succeeds on it */
784 pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
786 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
787 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
789 continue;
791 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
792 circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
793 circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
794 log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
795 "The purpose on the circuit was %s; it was in state %s, "
796 "path_state %s.",
797 circuit_purpose_to_string(circ->purpose),
798 circuit_state_to_string(circ->state),
799 CIRCUIT_IS_ORIGIN(circ) ?
800 pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
801 "none");
803 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
804 "We tried for %d seconds to connect to '%s' using exit %s."
805 " Retrying on a new circuit.",
806 seconds_idle,
807 safe_str_client(entry_conn->socks_request->address),
808 conn->cpath_layer ?
809 extend_info_describe(conn->cpath_layer->extend_info):
810 "*unnamed*");
811 /* send an end down the circuit */
812 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
813 /* un-mark it as ending, since we're going to reuse it */
814 conn->edge_has_sent_end = 0;
815 conn->end_reason = 0;
816 /* make us not try this circuit again, but allow
817 * current streams on it to survive if they can */
818 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
820 /* give our stream another 'cutoff' seconds to try */
821 conn->base_.timestamp_lastread += cutoff;
822 if (entry_conn->num_socks_retries < 250) /* avoid overflow */
823 entry_conn->num_socks_retries++;
824 /* move it back into 'pending' state, and try to attach. */
825 if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
826 END_STREAM_REASON_TIMEOUT)<0) {
827 if (!base_conn->marked_for_close)
828 connection_mark_unattached_ap(entry_conn,
829 END_STREAM_REASON_CANT_ATTACH);
831 } SMARTLIST_FOREACH_END(base_conn);
835 * As connection_ap_attach_pending, but first scans the entire connection
836 * array to see if any elements are missing.
838 void
839 connection_ap_rescan_and_attach_pending(void)
841 entry_connection_t *entry_conn;
842 smartlist_t *conns = get_connection_array();
844 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
845 pending_entry_connections = smartlist_new();
847 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
848 if (conn->marked_for_close ||
849 conn->type != CONN_TYPE_AP ||
850 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
851 continue;
853 entry_conn = TO_ENTRY_CONN(conn);
854 tor_assert(entry_conn);
855 if (! smartlist_contains(pending_entry_connections, entry_conn)) {
856 log_warn(LD_BUG, "Found a connection %p that was supposed to be "
857 "in pending_entry_connections, but wasn't. No worries; "
858 "adding it.",
859 pending_entry_connections);
860 untried_pending_connections = 1;
861 connection_ap_mark_as_pending_circuit(entry_conn);
864 } SMARTLIST_FOREACH_END(conn);
866 connection_ap_attach_pending(1);
869 #ifdef DEBUGGING_17659
870 #define UNMARK() do { \
871 entry_conn->marked_pending_circ_line = 0; \
872 entry_conn->marked_pending_circ_file = 0; \
873 } while (0)
874 #else /* !(defined(DEBUGGING_17659)) */
875 #define UNMARK() do { } while (0)
876 #endif /* defined(DEBUGGING_17659) */
878 /** Tell any AP streams that are listed as waiting for a new circuit to try
879 * again. If there is an available circuit for a stream, attach it. Otherwise,
880 * launch a new circuit.
882 * If <b>retry</b> is false, only check the list if it contains at least one
883 * streams that we have not yet tried to attach to a circuit.
885 void
886 connection_ap_attach_pending(int retry)
888 if (PREDICT_UNLIKELY(!pending_entry_connections)) {
889 return;
892 if (untried_pending_connections == 0 && !retry)
893 return;
895 /* Don't allow any modifications to list while we are iterating over
896 * it. We'll put streams back on this list if we can't attach them
897 * immediately. */
898 smartlist_t *pending = pending_entry_connections;
899 pending_entry_connections = smartlist_new();
901 SMARTLIST_FOREACH_BEGIN(pending,
902 entry_connection_t *, entry_conn) {
903 connection_t *conn = ENTRY_TO_CONN(entry_conn);
904 tor_assert(conn && entry_conn);
905 if (conn->marked_for_close) {
906 UNMARK();
907 continue;
909 if (conn->magic != ENTRY_CONNECTION_MAGIC) {
910 log_warn(LD_BUG, "%p has impossible magic value %u.",
911 entry_conn, (unsigned)conn->magic);
912 UNMARK();
913 continue;
915 if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
916 log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
917 "is %s. Why is it on pending_entry_connections?",
918 entry_conn,
919 conn_state_to_string(conn->type, conn->state));
920 UNMARK();
921 continue;
924 /* Okay, we're through the sanity checks. Try to handle this stream. */
925 if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
926 if (!conn->marked_for_close)
927 connection_mark_unattached_ap(entry_conn,
928 END_STREAM_REASON_CANT_ATTACH);
931 if (! conn->marked_for_close &&
932 conn->type == CONN_TYPE_AP &&
933 conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
934 /* Is it still waiting for a circuit? If so, we didn't attach it,
935 * so it's still pending. Put it back on the list.
937 if (!smartlist_contains(pending_entry_connections, entry_conn)) {
938 smartlist_add(pending_entry_connections, entry_conn);
939 continue;
943 /* If we got here, then we either closed the connection, or
944 * we attached it. */
945 UNMARK();
946 } SMARTLIST_FOREACH_END(entry_conn);
948 smartlist_free(pending);
949 untried_pending_connections = 0;
952 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
954 * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
955 * should not already be pending a circuit. The circuit will get
956 * launched or the connection will get attached the next time we
957 * call connection_ap_attach_pending().
959 void
960 connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn,
961 const char *fname, int lineno)
963 connection_t *conn = ENTRY_TO_CONN(entry_conn);
964 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
965 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
966 if (conn->marked_for_close)
967 return;
969 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
970 pending_entry_connections = smartlist_new();
972 if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
973 entry_conn))) {
974 log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
975 "(Called from %s:%d.)",
976 entry_conn, fname, lineno);
977 #ifdef DEBUGGING_17659
978 const char *f2 = entry_conn->marked_pending_circ_file;
979 log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
980 f2 ? f2 : "<NULL>",
981 entry_conn->marked_pending_circ_line);
982 #endif /* defined(DEBUGGING_17659) */
983 log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
984 return;
987 #ifdef DEBUGGING_17659
988 entry_conn->marked_pending_circ_line = (uint16_t) lineno;
989 entry_conn->marked_pending_circ_file = fname;
990 #endif
992 untried_pending_connections = 1;
993 smartlist_add(pending_entry_connections, entry_conn);
995 /* Work-around for bug 19969: we handle pending_entry_connections at
996 * the end of run_main_loop_once(), but in many cases that function will
997 * take a very long time, if ever, to finish its call to event_base_loop().
999 * So the fix is to tell it right now that it ought to finish its loop at
1000 * its next available opportunity.
1002 tell_event_loop_to_finish();
1005 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
1006 void
1007 connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
1009 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1010 return;
1011 UNMARK();
1012 smartlist_remove(pending_entry_connections, entry_conn);
1015 /* DOCDOC */
1016 void
1017 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
1018 const char *where)
1020 if (pending_entry_connections &&
1021 smartlist_contains(pending_entry_connections, entry_conn)) {
1022 log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
1023 entry_conn, where);
1024 connection_ap_mark_as_non_pending_circuit(entry_conn);
1028 /** Tell any AP streams that are waiting for a one-hop tunnel to
1029 * <b>failed_digest</b> that they are going to fail. */
1030 /* XXXX We should get rid of this function, and instead attach
1031 * one-hop streams to circ->p_streams so they get marked in
1032 * circuit_mark_for_close like normal p_streams. */
1033 void
1034 connection_ap_fail_onehop(const char *failed_digest,
1035 cpath_build_state_t *build_state)
1037 entry_connection_t *entry_conn;
1038 char digest[DIGEST_LEN];
1039 smartlist_t *conns = get_connection_array();
1040 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1041 if (conn->marked_for_close ||
1042 conn->type != CONN_TYPE_AP ||
1043 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1044 continue;
1045 entry_conn = TO_ENTRY_CONN(conn);
1046 if (!entry_conn->want_onehop)
1047 continue;
1048 if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
1049 tor_memneq(digest, failed_digest, DIGEST_LEN))
1050 continue;
1051 if (tor_digest_is_zero(digest)) {
1052 /* we don't know the digest; have to compare addr:port */
1053 tor_addr_t addr;
1054 if (!build_state || !build_state->chosen_exit ||
1055 !entry_conn->socks_request) {
1056 continue;
1058 if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
1059 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
1060 build_state->chosen_exit->port != entry_conn->socks_request->port)
1061 continue;
1063 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
1064 "just failed.", entry_conn->chosen_exit_name,
1065 entry_conn->socks_request->address);
1066 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1067 } SMARTLIST_FOREACH_END(conn);
1070 /** A circuit failed to finish on its last hop <b>info</b>. If there
1071 * are any streams waiting with this exit node in mind, but they
1072 * don't absolutely require it, make them give up on it.
1074 void
1075 circuit_discard_optional_exit_enclaves(extend_info_t *info)
1077 entry_connection_t *entry_conn;
1078 const node_t *r1, *r2;
1080 smartlist_t *conns = get_connection_array();
1081 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1082 if (conn->marked_for_close ||
1083 conn->type != CONN_TYPE_AP ||
1084 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1085 continue;
1086 entry_conn = TO_ENTRY_CONN(conn);
1087 if (!entry_conn->chosen_exit_optional &&
1088 !entry_conn->chosen_exit_retries)
1089 continue;
1090 r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
1091 NNF_NO_WARN_UNNAMED);
1092 r2 = node_get_by_id(info->identity_digest);
1093 if (!r1 || !r2 || r1 != r2)
1094 continue;
1095 tor_assert(entry_conn->socks_request);
1096 if (entry_conn->chosen_exit_optional) {
1097 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
1098 safe_str_client(entry_conn->chosen_exit_name),
1099 escaped_safe_str_client(entry_conn->socks_request->address));
1100 entry_conn->chosen_exit_optional = 0;
1101 tor_free(entry_conn->chosen_exit_name); /* clears it */
1102 /* if this port is dangerous, warn or reject it now that we don't
1103 * think it'll be using an enclave. */
1104 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1106 if (entry_conn->chosen_exit_retries) {
1107 if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
1108 clear_trackexithost_mappings(entry_conn->chosen_exit_name);
1109 tor_free(entry_conn->chosen_exit_name); /* clears it */
1110 /* if this port is dangerous, warn or reject it now that we don't
1111 * think it'll be using an enclave. */
1112 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1115 } SMARTLIST_FOREACH_END(conn);
1118 /** The AP connection <b>conn</b> has just failed while attaching or
1119 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1120 * might work. Detach the circuit, and either reattach it, launch a
1121 * new circuit, tell the controller, or give up as appropriate.
1123 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1126 connection_ap_detach_retriable(entry_connection_t *conn,
1127 origin_circuit_t *circ,
1128 int reason)
1130 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
1131 ENTRY_TO_CONN(conn)->timestamp_lastread = time(NULL);
1133 /* Roll back path bias use state so that we probe the circuit
1134 * if nothing else succeeds on it */
1135 pathbias_mark_use_rollback(circ);
1137 if (conn->pending_optimistic_data) {
1138 buf_set_to_copy(&conn->sending_optimistic_data,
1139 conn->pending_optimistic_data);
1142 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
1143 /* If we're attaching streams ourself, or if this connection is
1144 * a tunneled directory connection, then just attach it. */
1145 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
1146 circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1147 connection_ap_mark_as_pending_circuit(conn);
1148 } else {
1149 CONNECTION_AP_EXPECT_NONPENDING(conn);
1150 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
1151 circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1153 return 0;
1156 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1157 * reject depending on our config options. */
1158 static int
1159 consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
1161 const or_options_t *options = get_options();
1162 int reject = smartlist_contains_int_as_string(
1163 options->RejectPlaintextPorts, port);
1165 if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
1166 log_warn(LD_APP, "Application request to port %d: this port is "
1167 "commonly used for unencrypted protocols. Please make sure "
1168 "you don't send anything you would mind the rest of the "
1169 "Internet reading!%s", port, reject ? " Closing." : "");
1170 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1171 port, reject ? "REJECT" : "WARN");
1174 if (reject) {
1175 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1176 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1177 return -1;
1180 return 0;
1183 /** How many times do we try connecting with an exit configured via
1184 * TrackHostExits before concluding that it won't work any more and trying a
1185 * different one? */
1186 #define TRACKHOSTEXITS_RETRIES 5
1188 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1189 * asked us to leave streams unattached. Return 0 in that case.
1191 * See connection_ap_handshake_rewrite_and_attach()'s
1192 * documentation for arguments and return value.
1194 MOCK_IMPL(int,
1195 connection_ap_rewrite_and_attach_if_allowed,(entry_connection_t *conn,
1196 origin_circuit_t *circ,
1197 crypt_path_t *cpath))
1199 const or_options_t *options = get_options();
1201 if (options->LeaveStreamsUnattached) {
1202 CONNECTION_AP_EXPECT_NONPENDING(conn);
1203 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
1204 return 0;
1206 return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1209 /* Try to perform any map-based rewriting of the target address in
1210 * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1211 * conn->socks_request.address as appropriate.
1213 STATIC void
1214 connection_ap_handshake_rewrite(entry_connection_t *conn,
1215 rewrite_result_t *out)
1217 socks_request_t *socks = conn->socks_request;
1218 const or_options_t *options = get_options();
1219 tor_addr_t addr_tmp;
1221 /* Initialize all the fields of 'out' to reasonable defaults */
1222 out->automap = 0;
1223 out->exit_source = ADDRMAPSRC_NONE;
1224 out->map_expires = TIME_MAX;
1225 out->end_reason = 0;
1226 out->should_close = 0;
1227 out->orig_address[0] = 0;
1229 /* We convert all incoming addresses to lowercase. */
1230 tor_strlower(socks->address);
1231 /* Remember the original address. */
1232 strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
1233 log_debug(LD_APP,"Client asked for %s:%d",
1234 safe_str_client(socks->address),
1235 socks->port);
1237 /* Check for whether this is a .exit address. By default, those are
1238 * disallowed when they're coming straight from the client, but you're
1239 * allowed to have them in MapAddress commands and so forth. */
1240 if (!strcmpend(socks->address, ".exit")) {
1241 log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
1242 "security risks.");
1243 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1244 escaped(socks->address));
1245 out->end_reason = END_STREAM_REASON_TORPROTOCOL;
1246 out->should_close = 1;
1247 return;
1250 /* Remember the original address so we can tell the user about what
1251 * they actually said, not just what it turned into. */
1252 /* XXX yes, this is the same as out->orig_address above. One is
1253 * in the output, and one is in the connection. */
1254 if (! conn->original_dest_address) {
1255 /* Is the 'if' necessary here? XXXX */
1256 conn->original_dest_address = tor_strdup(conn->socks_request->address);
1259 /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1260 * these only for non-reverse lookups, since they don't exist for those.
1261 * We also need to do this before we consider automapping, since we might
1262 * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1263 * we'd need to automap it. */
1264 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
1265 const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
1266 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1267 rewrite_flags, &out->map_expires, &out->exit_source)) {
1268 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1269 REMAP_STREAM_SOURCE_CACHE);
1273 /* Now see if we need to create or return an existing Hostname->IP
1274 * automapping. Automapping happens when we're asked to resolve a
1275 * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1276 * suffix listed in AutomapHostsSuffixes. It's a handy feature
1277 * that lets you have Tor assign e.g. IPv6 addresses for .onion
1278 * names, and return them safely from DNSPort.
1280 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1281 tor_addr_parse(&addr_tmp, socks->address)<0 &&
1282 options->AutomapHostsOnResolve) {
1283 /* Check the suffix... */
1284 out->automap = addressmap_address_should_automap(socks->address, options);
1285 if (out->automap) {
1286 /* If we get here, then we should apply an automapping for this. */
1287 const char *new_addr;
1288 /* We return an IPv4 address by default, or an IPv6 address if we
1289 * are allowed to do so. */
1290 int addr_type = RESOLVED_TYPE_IPV4;
1291 if (conn->socks_request->socks_version != 4) {
1292 if (!conn->entry_cfg.ipv4_traffic ||
1293 (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
1294 conn->entry_cfg.prefer_ipv6_virtaddr)
1295 addr_type = RESOLVED_TYPE_IPV6;
1297 /* Okay, register the target address as automapped, and find the new
1298 * address we're supposed to give as a resolve answer. (Return a cached
1299 * value if we've looked up this address before.
1301 new_addr = addressmap_register_virtual_address(
1302 addr_type, tor_strdup(socks->address));
1303 if (! new_addr) {
1304 log_warn(LD_APP, "Unable to automap address %s",
1305 escaped_safe_str(socks->address));
1306 out->end_reason = END_STREAM_REASON_INTERNAL;
1307 out->should_close = 1;
1308 return;
1310 log_info(LD_APP, "Automapping %s to %s",
1311 escaped_safe_str_client(socks->address),
1312 safe_str_client(new_addr));
1313 strlcpy(socks->address, new_addr, sizeof(socks->address));
1317 /* Now handle reverse lookups, if they're in the cache. This doesn't
1318 * happen too often, since client-side DNS caching is off by default,
1319 * and very deprecated. */
1320 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1321 unsigned rewrite_flags = 0;
1322 if (conn->entry_cfg.use_cached_ipv4_answers)
1323 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1324 if (conn->entry_cfg.use_cached_ipv6_answers)
1325 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1327 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1328 rewrite_flags, &out->map_expires)) {
1329 char *result = tor_strdup(socks->address);
1330 /* remember _what_ is supposed to have been resolved. */
1331 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1332 out->orig_address);
1333 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1334 strlen(result), (uint8_t*)result,
1336 out->map_expires);
1337 tor_free(result);
1338 out->end_reason = END_STREAM_REASON_DONE |
1339 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
1340 out->should_close = 1;
1341 return;
1344 /* Hang on, did we find an answer saying that this is a reverse lookup for
1345 * an internal address? If so, we should reject it if we're configured to
1346 * do so. */
1347 if (options->ClientDNSRejectInternalAddresses) {
1348 /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1349 tor_addr_t addr;
1350 int ok;
1351 ok = tor_addr_parse_PTR_name(
1352 &addr, socks->address, AF_UNSPEC, 1);
1353 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1354 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1355 0, NULL, -1, TIME_MAX);
1356 out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
1357 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
1358 out->should_close = 1;
1359 return;
1364 /* If we didn't automap it before, then this is still the address that
1365 * came straight from the user, mapped according to any
1366 * MapAddress/MAPADDRESS commands. Now apply other mappings,
1367 * including previously registered Automap entries (IP back to
1368 * hostname), TrackHostExits entries, and client-side DNS cache
1369 * entries (if they're turned on).
1371 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
1372 !out->automap) {
1373 unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
1374 addressmap_entry_source_t exit_source2;
1375 if (conn->entry_cfg.use_cached_ipv4_answers)
1376 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1377 if (conn->entry_cfg.use_cached_ipv6_answers)
1378 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1379 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1380 rewrite_flags, &out->map_expires, &exit_source2)) {
1381 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1382 REMAP_STREAM_SOURCE_CACHE);
1384 if (out->exit_source == ADDRMAPSRC_NONE) {
1385 /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1386 * the original source of a .exit. */
1387 out->exit_source = exit_source2;
1391 /* Check to see whether we're about to use an address in the virtual
1392 * range without actually having gotten it from an Automap. */
1393 if (!out->automap && address_is_in_virtual_range(socks->address)) {
1394 /* This address was probably handed out by
1395 * client_dns_get_unmapped_address, but the mapping was discarded for some
1396 * reason. Or the user typed in a virtual address range manually. We
1397 * *don't* want to send the address through Tor; that's likely to fail,
1398 * and may leak information.
1400 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1401 safe_str_client(socks->address));
1402 out->end_reason = END_STREAM_REASON_INTERNAL;
1403 out->should_close = 1;
1404 return;
1408 /** We just received a SOCKS request in <b>conn</b> to an onion address of type
1409 * <b>addresstype</b>. Start connecting to the onion service. */
1410 static int
1411 connection_ap_handle_onion(entry_connection_t *conn,
1412 socks_request_t *socks,
1413 origin_circuit_t *circ,
1414 hostname_type_t addresstype)
1416 time_t now = approx_time();
1417 connection_t *base_conn = ENTRY_TO_CONN(conn);
1419 /* If .onion address requests are disabled, refuse the request */
1420 if (!conn->entry_cfg.onion_traffic) {
1421 log_warn(LD_APP, "Onion address %s requested from a port with .onion "
1422 "disabled", safe_str_client(socks->address));
1423 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1424 return -1;
1427 /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
1428 * for hidden service addresses. */
1429 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1430 /* if it's a resolve request, fail it right now, rather than
1431 * building all the circuits and then realizing it won't work. */
1432 log_warn(LD_APP,
1433 "Resolve requests to hidden services not allowed. Failing.");
1434 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1435 0,NULL,-1,TIME_MAX);
1436 connection_mark_unattached_ap(conn,
1437 END_STREAM_REASON_SOCKSPROTOCOL |
1438 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1439 return -1;
1442 /* If we were passed a circuit, then we need to fail. .onion addresses
1443 * only work when we launch our own circuits for now. */
1444 if (circ) {
1445 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1446 "supported for .onion addresses currently. Failing.");
1447 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1448 return -1;
1451 /* Interface: Regardless of HS version after the block below we should have
1452 set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
1453 const char *onion_address = NULL;
1454 int rend_cache_lookup_result = -ENOENT;
1455 int descriptor_is_usable = 0;
1457 if (addresstype == ONION_V2_HOSTNAME) { /* it's a v2 hidden service */
1458 rend_cache_entry_t *entry = NULL;
1459 /* Look up if we have client authorization configured for this hidden
1460 * service. If we do, associate it with the rend_data. */
1461 rend_service_authorization_t *client_auth =
1462 rend_client_lookup_service_authorization(socks->address);
1464 const uint8_t *cookie = NULL;
1465 rend_auth_type_t auth_type = REND_NO_AUTH;
1466 if (client_auth) {
1467 log_info(LD_REND, "Using previously configured client authorization "
1468 "for hidden service request.");
1469 auth_type = client_auth->auth_type;
1470 cookie = client_auth->descriptor_cookie;
1473 /* Fill in the rend_data field so we can start doing a connection to
1474 * a hidden service. */
1475 rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
1476 rend_data_client_create(socks->address, NULL, (char *) cookie,
1477 auth_type);
1478 if (rend_data == NULL) {
1479 return -1;
1481 onion_address = rend_data_get_address(rend_data);
1482 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1483 safe_str_client(onion_address));
1485 rend_cache_lookup_result = rend_cache_lookup_entry(onion_address,-1,
1486 &entry);
1487 if (!rend_cache_lookup_result && entry) {
1488 descriptor_is_usable = rend_client_any_intro_points_usable(entry);
1490 } else { /* it's a v3 hidden service */
1491 tor_assert(addresstype == ONION_V3_HOSTNAME);
1492 const hs_descriptor_t *cached_desc = NULL;
1493 int retval;
1494 /* Create HS conn identifier with HS pubkey */
1495 hs_ident_edge_conn_t *hs_conn_ident =
1496 tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
1498 retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
1499 NULL, NULL);
1500 if (retval < 0) {
1501 log_warn(LD_GENERAL, "failed to parse hs address");
1502 tor_free(hs_conn_ident);
1503 return -1;
1505 ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
1507 onion_address = socks->address;
1509 /* Check the v3 desc cache */
1510 cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
1511 if (cached_desc) {
1512 rend_cache_lookup_result = 0;
1513 descriptor_is_usable =
1514 hs_client_any_intro_points_usable(&hs_conn_ident->identity_pk,
1515 cached_desc);
1516 log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
1517 (descriptor_is_usable) ? "usable" : "unusable",
1518 safe_str_client(onion_address),
1519 (descriptor_is_usable) ? "Not fetching." : "Refecting.");
1520 } else {
1521 rend_cache_lookup_result = -ENOENT;
1525 /* Lookup the given onion address. If invalid, stop right now.
1526 * Otherwise, we might have it in the cache or not. */
1527 unsigned int refetch_desc = 0;
1528 if (rend_cache_lookup_result < 0) {
1529 switch (-rend_cache_lookup_result) {
1530 case EINVAL:
1531 /* We should already have rejected this address! */
1532 log_warn(LD_BUG,"Invalid service name '%s'",
1533 safe_str_client(onion_address));
1534 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1535 return -1;
1536 case ENOENT:
1537 /* We didn't have this; we should look it up. */
1538 log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
1539 safe_str_client(onion_address));
1540 refetch_desc = 1;
1541 break;
1542 default:
1543 log_warn(LD_BUG, "Unknown cache lookup error %d",
1544 rend_cache_lookup_result);
1545 return -1;
1549 /* Help predict that we'll want to do hidden service circuits in the
1550 * future. We're not sure if it will need a stable circuit yet, but
1551 * we know we'll need *something*. */
1552 rep_hist_note_used_internal(now, 0, 1);
1554 /* Now we have a descriptor but is it usable or not? If not, refetch.
1555 * Also, a fetch could have been requested if the onion address was not
1556 * found in the cache previously. */
1557 if (refetch_desc || !descriptor_is_usable) {
1558 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
1559 connection_ap_mark_as_non_pending_circuit(conn);
1560 base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1561 if (addresstype == ONION_V2_HOSTNAME) {
1562 tor_assert(edge_conn->rend_data);
1563 rend_client_refetch_v2_renddesc(edge_conn->rend_data);
1564 /* Whatever the result of the refetch, we don't go further. */
1565 return 0;
1566 } else {
1567 tor_assert(addresstype == ONION_V3_HOSTNAME);
1568 tor_assert(edge_conn->hs_ident);
1569 /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
1570 * went and act accordingly. */
1571 int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
1572 switch (ret) {
1573 case HS_CLIENT_FETCH_MISSING_INFO:
1574 /* Keeping the connection in descriptor wait state is fine because
1575 * once we get enough dirinfo or a new live consensus, the HS client
1576 * subsystem is notified and every connection in that state will
1577 * trigger a fetch for the service key. */
1578 case HS_CLIENT_FETCH_LAUNCHED:
1579 case HS_CLIENT_FETCH_PENDING:
1580 case HS_CLIENT_FETCH_HAVE_DESC:
1581 return 0;
1582 case HS_CLIENT_FETCH_ERROR:
1583 case HS_CLIENT_FETCH_NO_HSDIRS:
1584 case HS_CLIENT_FETCH_NOT_ALLOWED:
1585 /* Can't proceed further and better close the SOCKS request. */
1586 return -1;
1591 /* We have the descriptor! So launch a connection to the HS. */
1592 log_info(LD_REND, "Descriptor is here. Great.");
1594 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1595 /* We'll try to attach it at the next event loop, or whenever
1596 * we call connection_ap_attach_pending() */
1597 connection_ap_mark_as_pending_circuit(conn);
1598 return 0;
1601 /** Connection <b>conn</b> just finished its socks handshake, or the
1602 * controller asked us to take care of it. If <b>circ</b> is defined,
1603 * then that's where we'll want to attach it. Otherwise we have to
1604 * figure it out ourselves.
1606 * First, parse whether it's a .exit address, remap it, and so on. Then
1607 * if it's for a general circuit, try to attach it to a circuit (or launch
1608 * one as needed), else if it's for a rendezvous circuit, fetch a
1609 * rendezvous descriptor first (or attach/launch a circuit if the
1610 * rendezvous descriptor is already here and fresh enough).
1612 * The stream will exit from the hop
1613 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1614 * <b>cpath</b> is NULL.
1617 connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
1618 origin_circuit_t *circ,
1619 crypt_path_t *cpath)
1621 socks_request_t *socks = conn->socks_request;
1622 const or_options_t *options = get_options();
1623 connection_t *base_conn = ENTRY_TO_CONN(conn);
1624 time_t now = time(NULL);
1625 rewrite_result_t rr;
1627 /* First we'll do the rewrite part. Let's see if we get a reasonable
1628 * answer.
1630 memset(&rr, 0, sizeof(rr));
1631 connection_ap_handshake_rewrite(conn,&rr);
1633 if (rr.should_close) {
1634 /* connection_ap_handshake_rewrite told us to close the connection:
1635 * either because it sent back an answer, or because it sent back an
1636 * error */
1637 connection_mark_unattached_ap(conn, rr.end_reason);
1638 if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
1639 return 0;
1640 else
1641 return -1;
1644 const time_t map_expires = rr.map_expires;
1645 const int automap = rr.automap;
1646 const addressmap_entry_source_t exit_source = rr.exit_source;
1648 /* Now, we parse the address to see if it's an .onion or .exit or
1649 * other special address.
1651 const hostname_type_t addresstype = parse_extended_hostname(socks->address);
1653 /* Now see whether the hostname is bogus. This could happen because of an
1654 * onion hostname whose format we don't recognize. */
1655 if (addresstype == BAD_HOSTNAME) {
1656 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1657 escaped(socks->address));
1658 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1659 return -1;
1662 /* If this is a .exit hostname, strip off the .name.exit part, and
1663 * see whether we're willing to connect there, and and otherwise handle the
1664 * .exit address.
1666 * We'll set chosen_exit_name and/or close the connection as appropriate.
1668 if (addresstype == EXIT_HOSTNAME) {
1669 /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
1670 * not ExcludeExitNodes. */
1671 routerset_t *excludeset = options->StrictNodes ?
1672 options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
1673 const node_t *node = NULL;
1675 /* If this .exit was added by an AUTOMAP, then it came straight from
1676 * a user. That's not safe. */
1677 if (exit_source == ADDRMAPSRC_AUTOMAP) {
1678 /* Whoops; this one is stale. It must have gotten added earlier?
1679 * (Probably this is not possible, since AllowDotExit no longer
1680 * exists.) */
1681 log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
1682 safe_str_client(socks->address));
1683 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1684 escaped(socks->address));
1685 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1686 tor_assert_nonfatal_unreached();
1687 return -1;
1690 /* Double-check to make sure there are no .exits coming from
1691 * impossible/weird sources. */
1692 if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
1693 /* It shouldn't be possible to get a .exit address from any of these
1694 * sources. */
1695 log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
1696 ".exit part. Refusing.",
1697 safe_str_client(socks->address));
1698 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1699 escaped(socks->address));
1700 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1701 return -1;
1704 tor_assert(!automap);
1706 /* Now, find the character before the .(name) part.
1707 * (The ".exit" part got stripped off by "parse_extended_hostname").
1709 * We're going to put the exit name into conn->chosen_exit_name, and
1710 * look up a node correspondingly. */
1711 char *s = strrchr(socks->address,'.');
1712 if (s) {
1713 /* The address was of the form "(stuff).(name).exit */
1714 if (s[1] != '\0') {
1715 /* Looks like a real .exit one. */
1716 conn->chosen_exit_name = tor_strdup(s+1);
1717 node = node_get_by_nickname(conn->chosen_exit_name, 0);
1719 if (exit_source == ADDRMAPSRC_TRACKEXIT) {
1720 /* We 5 tries before it expires the addressmap */
1721 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1723 *s = 0;
1724 } else {
1725 /* Oops, the address was (stuff)..exit. That's not okay. */
1726 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1727 safe_str_client(socks->address));
1728 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1729 escaped(socks->address));
1730 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1731 return -1;
1733 } else {
1734 /* It looks like they just asked for "foo.exit". That's a special
1735 * form that means (foo's address).foo.exit. */
1737 conn->chosen_exit_name = tor_strdup(socks->address);
1738 node = node_get_by_nickname(conn->chosen_exit_name, 0);
1739 if (node) {
1740 *socks->address = 0;
1741 node_get_address_string(node, socks->address, sizeof(socks->address));
1745 /* Now make sure that the chosen exit exists... */
1746 if (!node) {
1747 log_warn(LD_APP,
1748 "Unrecognized relay in exit address '%s.exit'. Refusing.",
1749 safe_str_client(socks->address));
1750 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1751 return -1;
1753 /* ...and make sure that it isn't excluded. */
1754 if (routerset_contains_node(excludeset, node)) {
1755 log_warn(LD_APP,
1756 "Excluded relay in exit address '%s.exit'. Refusing.",
1757 safe_str_client(socks->address));
1758 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1759 return -1;
1761 /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
1762 Bar is not listed in it? I say yes, but our revised manpage branch
1763 implies no. */
1766 /* Now, we handle everything that isn't a .onion address. */
1767 if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {
1768 /* Not a hidden-service request. It's either a hostname or an IP,
1769 * possibly with a .exit that we stripped off. We're going to check
1770 * if we're allowed to connect/resolve there, and then launch the
1771 * appropriate request. */
1773 /* Check for funny characters in the address. */
1774 if (address_is_invalid_destination(socks->address, 1)) {
1775 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1776 escaped(socks->address));
1777 log_warn(LD_APP,
1778 "Destination '%s' seems to be an invalid hostname. Failing.",
1779 safe_str_client(socks->address));
1780 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1781 return -1;
1784 #ifdef ENABLE_TOR2WEB_MODE
1785 /* If we're running in Tor2webMode, we don't allow anything BUT .onion
1786 * addresses. */
1787 if (options->Tor2webMode) {
1788 log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
1789 "or IP address %s because tor2web mode is enabled.",
1790 safe_str_client(socks->address));
1791 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1792 return -1;
1794 #endif /* defined(ENABLE_TOR2WEB_MODE) */
1796 /* socks->address is a non-onion hostname or IP address.
1797 * If we can't do any non-onion requests, refuse the connection.
1798 * If we have a hostname but can't do DNS, refuse the connection.
1799 * If we have an IP address, but we can't use that address family,
1800 * refuse the connection.
1802 * If we can do DNS requests, and we can use at least one address family,
1803 * then we have to resolve the address first. Then we'll know if it
1804 * resolves to a usable address family. */
1806 /* First, check if all non-onion traffic is disabled */
1807 if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
1808 && !conn->entry_cfg.ipv6_traffic) {
1809 log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
1810 "or IP address %s because Port has OnionTrafficOnly set (or "
1811 "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
1812 safe_str_client(socks->address));
1813 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1814 return -1;
1817 /* Then check if we have a hostname or IP address, and whether DNS or
1818 * the IP address family are permitted. Reject if not. */
1819 tor_addr_t dummy_addr;
1820 int socks_family = tor_addr_parse(&dummy_addr, socks->address);
1821 /* family will be -1 for a non-onion hostname that's not an IP */
1822 if (socks_family == -1) {
1823 if (!conn->entry_cfg.dns_request) {
1824 log_warn(LD_APP, "Refusing to connect to hostname %s "
1825 "because Port has NoDNSRequest set.",
1826 safe_str_client(socks->address));
1827 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1828 return -1;
1830 } else if (socks_family == AF_INET) {
1831 if (!conn->entry_cfg.ipv4_traffic) {
1832 log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
1833 "Port has NoIPv4Traffic set.",
1834 safe_str_client(socks->address));
1835 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1836 return -1;
1838 } else if (socks_family == AF_INET6) {
1839 if (!conn->entry_cfg.ipv6_traffic) {
1840 log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
1841 "Port has NoIPv6Traffic set.",
1842 safe_str_client(socks->address));
1843 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1844 return -1;
1846 } else {
1847 tor_assert_nonfatal_unreached_once();
1850 /* See if this is a hostname lookup that we can answer immediately.
1851 * (For example, an attempt to look up the IP address for an IP address.)
1853 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1854 tor_addr_t answer;
1855 /* Reply to resolves immediately if we can. */
1856 if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
1857 /* remember _what_ is supposed to have been resolved. */
1858 strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
1859 connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
1860 map_expires);
1861 connection_mark_unattached_ap(conn,
1862 END_STREAM_REASON_DONE |
1863 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1864 return 0;
1866 tor_assert(!automap);
1867 rep_hist_note_used_resolve(now); /* help predict this next time */
1868 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1869 /* Now see if this is a connect request that we can reject immediately */
1871 tor_assert(!automap);
1872 /* Don't allow connections to port 0. */
1873 if (socks->port == 0) {
1874 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1875 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1876 return -1;
1878 /* You can't make connections to internal addresses, by default.
1879 * Exceptions are begindir requests (where the address is meaningless),
1880 * or cases where you've hand-configured a particular exit, thereby
1881 * making the local address meaningful. */
1882 if (options->ClientRejectInternalAddresses &&
1883 !conn->use_begindir && !conn->chosen_exit_name && !circ) {
1884 /* If we reach this point then we don't want to allow internal
1885 * addresses. Check if we got one. */
1886 tor_addr_t addr;
1887 if (tor_addr_hostname_is_local(socks->address) ||
1888 (tor_addr_parse(&addr, socks->address) >= 0 &&
1889 tor_addr_is_internal(&addr, 0))) {
1890 /* If this is an explicit private address with no chosen exit node,
1891 * then we really don't want to try to connect to it. That's
1892 * probably an error. */
1893 if (conn->is_transparent_ap) {
1894 #define WARN_INTRVL_LOOP 300
1895 static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
1896 char *m;
1897 if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
1898 log_warn(LD_NET,
1899 "Rejecting request for anonymous connection to private "
1900 "address %s on a TransPort or NATDPort. Possible loop "
1901 "in your NAT rules?%s", safe_str_client(socks->address),
1903 tor_free(m);
1905 } else {
1906 #define WARN_INTRVL_PRIV 300
1907 static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
1908 char *m;
1909 if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
1910 log_warn(LD_NET,
1911 "Rejecting SOCKS request for anonymous connection to "
1912 "private address %s.%s",
1913 safe_str_client(socks->address),m);
1914 tor_free(m);
1917 connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
1918 return -1;
1920 } /* end "if we should check for internal addresses" */
1922 /* Okay. We're still doing a CONNECT, and it wasn't a private
1923 * address. Here we do special handling for literal IP addresses,
1924 * to see if we should reject this preemptively, and to set up
1925 * fields in conn->entry_cfg to tell the exit what AF we want. */
1927 tor_addr_t addr;
1928 /* XXX Duplicate call to tor_addr_parse. */
1929 if (tor_addr_parse(&addr, socks->address) >= 0) {
1930 /* If we reach this point, it's an IPv4 or an IPv6 address. */
1931 sa_family_t family = tor_addr_family(&addr);
1933 if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
1934 (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
1935 /* You can't do an IPv4 address on a v6-only socks listener,
1936 * or vice versa. */
1937 log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
1938 "family that this listener does not support.");
1939 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1940 return -1;
1941 } else if (family == AF_INET6 && socks->socks_version == 4) {
1942 /* You can't make a socks4 request to an IPv6 address. Socks4
1943 * doesn't support that. */
1944 log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
1945 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1946 return -1;
1947 } else if (socks->socks_version == 4 &&
1948 !conn->entry_cfg.ipv4_traffic) {
1949 /* You can't do any kind of Socks4 request when IPv4 is forbidden.
1951 * XXX raise this check outside the enclosing block? */
1952 log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
1953 "no IPv4 traffic supported.");
1954 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1955 return -1;
1956 } else if (family == AF_INET6) {
1957 /* Tell the exit: we won't accept any ipv4 connection to an IPv6
1958 * address. */
1959 conn->entry_cfg.ipv4_traffic = 0;
1960 } else if (family == AF_INET) {
1961 /* Tell the exit: we won't accept any ipv6 connection to an IPv4
1962 * address. */
1963 conn->entry_cfg.ipv6_traffic = 0;
1968 /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
1969 if (socks->socks_version == 4)
1970 conn->entry_cfg.ipv6_traffic = 0;
1972 /* Still handling CONNECT. Now, check for exit enclaves. (Which we
1973 * don't do on BEGIN_DIR, or when there is a chosen exit.)
1975 * TODO: Should we remove this? Exit enclaves are nutty and don't
1976 * work very well
1978 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1979 /* see if we can find a suitable enclave exit */
1980 const node_t *r =
1981 router_find_exact_exit_enclave(socks->address, socks->port);
1982 if (r) {
1983 log_info(LD_APP,
1984 "Redirecting address %s to exit at enclave router %s",
1985 safe_str_client(socks->address), node_describe(r));
1986 /* use the hex digest, not nickname, in case there are two
1987 routers with this nickname */
1988 conn->chosen_exit_name =
1989 tor_strdup(hex_str(r->identity, DIGEST_LEN));
1990 conn->chosen_exit_optional = 1;
1994 /* Still handling CONNECT: warn or reject if it's using a dangerous
1995 * port. */
1996 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1997 if (consider_plaintext_ports(conn, socks->port) < 0)
1998 return -1;
2000 /* Remember the port so that we will predict that more requests
2001 there will happen in the future. */
2002 if (!conn->use_begindir) {
2003 /* help predict this next time */
2004 rep_hist_note_used_port(now, socks->port);
2006 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
2007 rep_hist_note_used_resolve(now); /* help predict this next time */
2008 /* no extra processing needed */
2009 } else {
2010 /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2011 tor_fragile_assert();
2014 /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2015 * address, and decided not to reject it for any number of reasons. Now
2016 * mark the connection as waiting for a circuit, and try to attach it!
2018 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2020 /* If we were given a circuit to attach to, try to attach. Otherwise,
2021 * try to find a good one and attach to that. */
2022 int rv;
2023 if (circ) {
2024 rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
2025 } else {
2026 /* We'll try to attach it at the next event loop, or whenever
2027 * we call connection_ap_attach_pending() */
2028 connection_ap_mark_as_pending_circuit(conn);
2029 rv = 0;
2032 /* If the above function returned 0 then we're waiting for a circuit.
2033 * if it returned 1, we're attached. Both are okay. But if it returned
2034 * -1, there was an error, so make sure the connection is marked, and
2035 * return -1. */
2036 if (rv < 0) {
2037 if (!base_conn->marked_for_close)
2038 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2039 return -1;
2042 return 0;
2043 } else {
2044 /* If we get here, it's a request for a .onion address! */
2045 tor_assert(addresstype == ONION_V2_HOSTNAME ||
2046 addresstype == ONION_V3_HOSTNAME);
2047 tor_assert(!automap);
2048 return connection_ap_handle_onion(conn, socks, circ, addresstype);
2051 return 0; /* unreached but keeps the compiler happy */
2054 #ifdef TRANS_PF
2055 static int pf_socket = -1;
2057 get_pf_socket(void)
2059 int pf;
2060 /* This should be opened before dropping privileges. */
2061 if (pf_socket >= 0)
2062 return pf_socket;
2064 #if defined(OpenBSD)
2065 /* only works on OpenBSD */
2066 pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
2067 #else
2068 /* works on NetBSD and FreeBSD */
2069 pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
2070 #endif /* defined(OpenBSD) */
2072 if (pf < 0) {
2073 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
2074 return -1;
2077 pf_socket = pf;
2078 return pf_socket;
2080 #endif /* defined(TRANS_PF) */
2082 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2083 defined(TRANS_TPROXY)
2084 /** Try fill in the address of <b>req</b> from the socket configured
2085 * with <b>conn</b>. */
2086 static int
2087 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
2089 struct sockaddr_storage orig_dst;
2090 socklen_t orig_dst_len = sizeof(orig_dst);
2091 tor_addr_t addr;
2093 #ifdef TRANS_TPROXY
2094 if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
2095 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2096 &orig_dst_len) < 0) {
2097 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2098 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2099 return -1;
2101 goto done;
2103 #endif /* defined(TRANS_TPROXY) */
2105 #ifdef TRANS_NETFILTER
2106 int rv = -1;
2107 switch (ENTRY_TO_CONN(conn)->socket_family) {
2108 #ifdef TRANS_NETFILTER_IPV4
2109 case AF_INET:
2110 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
2111 (struct sockaddr*)&orig_dst, &orig_dst_len);
2112 break;
2113 #endif /* defined(TRANS_NETFILTER_IPV4) */
2114 #ifdef TRANS_NETFILTER_IPV6
2115 case AF_INET6:
2116 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
2117 (struct sockaddr*)&orig_dst, &orig_dst_len);
2118 break;
2119 #endif /* defined(TRANS_NETFILTER_IPV6) */
2120 default:
2121 log_warn(LD_BUG,
2122 "Received transparent data from an unsuported socket family %d",
2123 ENTRY_TO_CONN(conn)->socket_family);
2124 return -1;
2126 if (rv < 0) {
2127 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2128 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
2129 return -1;
2131 goto done;
2132 #elif defined(TRANS_PF)
2133 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2134 &orig_dst_len) < 0) {
2135 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2136 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2137 return -1;
2139 goto done;
2140 #else
2141 (void)conn;
2142 (void)req;
2143 log_warn(LD_BUG, "Unable to determine destination from socket.");
2144 return -1;
2145 #endif /* defined(TRANS_NETFILTER) || ... */
2147 done:
2148 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
2149 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2151 return 0;
2153 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2155 #ifdef TRANS_PF
2156 static int
2157 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
2159 struct sockaddr_storage proxy_addr;
2160 socklen_t proxy_addr_len = sizeof(proxy_addr);
2161 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
2162 struct pfioc_natlook pnl;
2163 tor_addr_t addr;
2164 int pf = -1;
2166 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
2167 &proxy_addr_len) < 0) {
2168 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2169 log_warn(LD_NET, "getsockname() to determine transocks destination "
2170 "failed: %s", tor_socket_strerror(e));
2171 return -1;
2174 #ifdef __FreeBSD__
2175 if (get_options()->TransProxyType_parsed == TPT_IPFW) {
2176 /* ipfw(8) is used and in this case getsockname returned the original
2177 destination */
2178 if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
2179 tor_fragile_assert();
2180 return -1;
2183 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
2185 return 0;
2187 #endif /* defined(__FreeBSD__) */
2189 memset(&pnl, 0, sizeof(pnl));
2190 pnl.proto = IPPROTO_TCP;
2191 pnl.direction = PF_OUT;
2192 if (proxy_sa->sa_family == AF_INET) {
2193 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
2194 pnl.af = AF_INET;
2195 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
2196 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2197 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
2198 pnl.dport = sin->sin_port;
2199 } else if (proxy_sa->sa_family == AF_INET6) {
2200 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
2201 pnl.af = AF_INET6;
2202 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
2203 sizeof(struct in6_addr));
2204 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2205 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
2206 pnl.dport = sin6->sin6_port;
2207 } else {
2208 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
2209 (int)proxy_sa->sa_family);
2210 return -1;
2213 pf = get_pf_socket();
2214 if (pf<0)
2215 return -1;
2217 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
2218 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
2219 return -1;
2222 if (pnl.af == AF_INET) {
2223 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
2224 } else if (pnl.af == AF_INET6) {
2225 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
2226 } else {
2227 tor_fragile_assert();
2228 return -1;
2231 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2232 req->port = ntohs(pnl.rdport);
2234 return 0;
2236 #endif /* defined(TRANS_PF) */
2238 /** Fetch the original destination address and port from a
2239 * system-specific interface and put them into a
2240 * socks_request_t as if they came from a socks request.
2242 * Return -1 if an error prevents fetching the destination,
2243 * else return 0.
2245 static int
2246 connection_ap_get_original_destination(entry_connection_t *conn,
2247 socks_request_t *req)
2249 #ifdef TRANS_NETFILTER
2250 return destination_from_socket(conn, req);
2251 #elif defined(TRANS_PF)
2252 const or_options_t *options = get_options();
2254 if (options->TransProxyType_parsed == TPT_PF_DIVERT)
2255 return destination_from_socket(conn, req);
2257 if (options->TransProxyType_parsed == TPT_DEFAULT ||
2258 options->TransProxyType_parsed == TPT_IPFW)
2259 return destination_from_pf(conn, req);
2261 (void)conn;
2262 (void)req;
2263 log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
2264 options->TransProxyType);
2265 return -1;
2266 #else
2267 (void)conn;
2268 (void)req;
2269 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
2270 "transparent proxy method was configured.");
2271 return -1;
2272 #endif /* defined(TRANS_NETFILTER) || ... */
2275 /** connection_edge_process_inbuf() found a conn in state
2276 * socks_wait. See if conn->inbuf has the right bytes to proceed with
2277 * the socks handshake.
2279 * If the handshake is complete, send it to
2280 * connection_ap_handshake_rewrite_and_attach().
2282 * Return -1 if an unexpected error with conn occurs (and mark it for close),
2283 * else return 0.
2285 static int
2286 connection_ap_handshake_process_socks(entry_connection_t *conn)
2288 socks_request_t *socks;
2289 int sockshere;
2290 const or_options_t *options = get_options();
2291 int had_reply = 0;
2292 connection_t *base_conn = ENTRY_TO_CONN(conn);
2294 tor_assert(conn);
2295 tor_assert(base_conn->type == CONN_TYPE_AP);
2296 tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
2297 tor_assert(conn->socks_request);
2298 socks = conn->socks_request;
2300 log_debug(LD_APP,"entered.");
2302 sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2303 options->TestSocks, options->SafeSocks);
2305 if (socks->replylen) {
2306 had_reply = 1;
2307 connection_buf_add((const char*)socks->reply, socks->replylen,
2308 base_conn);
2309 socks->replylen = 0;
2310 if (sockshere == -1) {
2311 /* An invalid request just got a reply, no additional
2312 * one is necessary. */
2313 socks->has_finished = 1;
2317 if (sockshere == 0) {
2318 log_debug(LD_APP,"socks handshake not all here yet.");
2319 return 0;
2320 } else if (sockshere == -1) {
2321 if (!had_reply) {
2322 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2323 connection_ap_handshake_socks_reply(conn, NULL, 0,
2324 END_STREAM_REASON_SOCKSPROTOCOL);
2326 connection_mark_unattached_ap(conn,
2327 END_STREAM_REASON_SOCKSPROTOCOL |
2328 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
2329 return -1;
2330 } /* else socks handshake is done, continue processing */
2332 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2333 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2334 else
2335 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2337 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2340 /** connection_init_accepted_conn() found a new trans AP conn.
2341 * Get the original destination and send it to
2342 * connection_ap_handshake_rewrite_and_attach().
2344 * Return -1 if an unexpected error with conn (and it should be marked
2345 * for close), else return 0.
2348 connection_ap_process_transparent(entry_connection_t *conn)
2350 socks_request_t *socks;
2352 tor_assert(conn);
2353 tor_assert(conn->socks_request);
2354 socks = conn->socks_request;
2356 /* pretend that a socks handshake completed so we don't try to
2357 * send a socks reply down a transparent conn */
2358 socks->command = SOCKS_COMMAND_CONNECT;
2359 socks->has_finished = 1;
2361 log_debug(LD_APP,"entered.");
2363 if (connection_ap_get_original_destination(conn, socks) < 0) {
2364 log_warn(LD_APP,"Fetching original destination failed. Closing.");
2365 connection_mark_unattached_ap(conn,
2366 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
2367 return -1;
2369 /* we have the original destination */
2371 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2373 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2376 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2377 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2378 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2379 * form of the original destination.
2381 * If the original destination is complete, send it to
2382 * connection_ap_handshake_rewrite_and_attach().
2384 * Return -1 if an unexpected error with conn (and it should be marked
2385 * for close), else return 0.
2387 static int
2388 connection_ap_process_natd(entry_connection_t *conn)
2390 char tmp_buf[36], *tbuf, *daddr;
2391 size_t tlen = 30;
2392 int err, port_ok;
2393 socks_request_t *socks;
2395 tor_assert(conn);
2396 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
2397 tor_assert(conn->socks_request);
2398 socks = conn->socks_request;
2400 log_debug(LD_APP,"entered.");
2402 /* look for LF-terminated "[DEST ip_addr port]"
2403 * where ip_addr is a dotted-quad and port is in string form */
2404 err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2405 if (err == 0)
2406 return 0;
2407 if (err < 0) {
2408 log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2409 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2410 return -1;
2413 if (strcmpstart(tmp_buf, "[DEST ")) {
2414 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2415 "said: %s",
2416 escaped(tmp_buf));
2417 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2418 return -1;
2421 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2422 if (!(tbuf = strchr(tbuf, ' '))) {
2423 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2424 "said: %s",
2425 escaped(tmp_buf));
2426 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2427 return -1;
2429 *tbuf++ = '\0';
2431 /* pretend that a socks handshake completed so we don't try to
2432 * send a socks reply down a natd conn */
2433 strlcpy(socks->address, daddr, sizeof(socks->address));
2434 socks->port = (uint16_t)
2435 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2436 if (!port_ok) {
2437 log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2438 "of range.", escaped(tbuf));
2439 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2440 return -1;
2443 socks->command = SOCKS_COMMAND_CONNECT;
2444 socks->has_finished = 1;
2446 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2448 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
2450 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2453 /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
2454 * but we have not yet received a full HTTP CONNECT request. Try to parse an
2455 * HTTP CONNECT request from the connection's inbuf. On success, set up the
2456 * connection's socks_request field and try to attach the connection. On
2457 * failure, send an HTTP reply, and mark the connection.
2459 STATIC int
2460 connection_ap_process_http_connect(entry_connection_t *conn)
2462 if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
2463 return -1;
2465 char *headers = NULL, *body = NULL;
2466 char *command = NULL, *addrport = NULL;
2467 char *addr = NULL;
2468 size_t bodylen = 0;
2470 const char *errmsg = NULL;
2471 int rv = 0;
2473 const int http_status =
2474 fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
2475 &body, &bodylen, 1024, 0);
2476 if (http_status < 0) {
2477 /* Bad http status */
2478 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2479 goto err;
2480 } else if (http_status == 0) {
2481 /* no HTTP request yet. */
2482 goto done;
2485 const int cmd_status = parse_http_command(headers, &command, &addrport);
2486 if (cmd_status < 0) {
2487 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2488 goto err;
2490 tor_assert(command);
2491 tor_assert(addrport);
2492 if (strcasecmp(command, "connect")) {
2493 errmsg = "HTTP/1.0 405 Method Not Allowed\r\n\r\n";
2494 goto err;
2497 tor_assert(conn->socks_request);
2498 socks_request_t *socks = conn->socks_request;
2499 uint16_t port;
2500 if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
2501 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2502 goto err;
2504 if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
2505 errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
2506 goto err;
2509 /* Abuse the 'username' and 'password' fields here. They are already an
2510 * abuse. */
2512 char *authorization = http_get_header(headers, "Proxy-Authorization: ");
2513 if (authorization) {
2514 socks->username = authorization; // steal reference
2515 socks->usernamelen = strlen(authorization);
2517 char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
2518 if (isolation) {
2519 socks->password = isolation; // steal reference
2520 socks->passwordlen = strlen(isolation);
2524 socks->command = SOCKS_COMMAND_CONNECT;
2525 socks->listener_type = CONN_TYPE_AP_HTTP_CONNECT_LISTENER;
2526 strlcpy(socks->address, addr, sizeof(socks->address));
2527 socks->port = port;
2529 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2531 rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2533 // XXXX send a "100 Continue" message?
2535 goto done;
2537 err:
2538 if (BUG(errmsg == NULL))
2539 errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2540 log_warn(LD_EDGE, "Saying %s", escaped(errmsg));
2541 connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
2542 connection_mark_unattached_ap(conn,
2543 END_STREAM_REASON_HTTPPROTOCOL|
2544 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
2546 done:
2547 tor_free(headers);
2548 tor_free(body);
2549 tor_free(command);
2550 tor_free(addrport);
2551 tor_free(addr);
2552 return rv;
2555 /** Iterate over the two bytes of stream_id until we get one that is not
2556 * already in use; return it. Return 0 if can't get a unique stream_id.
2558 streamid_t
2559 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2561 edge_connection_t *tmpconn;
2562 streamid_t test_stream_id;
2563 uint32_t attempts=0;
2565 again:
2566 test_stream_id = circ->next_stream_id++;
2567 if (++attempts > 1<<16) {
2568 /* Make sure we don't loop forever if all stream_id's are used. */
2569 log_warn(LD_APP,"No unused stream IDs. Failing.");
2570 return 0;
2572 if (test_stream_id == 0)
2573 goto again;
2574 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2575 if (tmpconn->stream_id == test_stream_id)
2576 goto again;
2577 return test_stream_id;
2580 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
2581 * an exit that supports optimistic data. */
2582 static int
2583 connection_ap_supports_optimistic_data(const entry_connection_t *conn)
2585 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2586 /* We can only send optimistic data if we're connected to an open
2587 general circuit. */
2588 if (edge_conn->on_circuit == NULL ||
2589 edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
2590 (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
2591 edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
2592 return 0;
2594 return conn->may_use_optimistic_data;
2597 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
2598 * RELAY_BEGIN cell for <b>ap_conn</b>. */
2599 static uint32_t
2600 connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
2602 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2603 const node_t *exitnode = NULL;
2604 const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
2605 uint32_t flags = 0;
2607 /* No flags for begindir */
2608 if (ap_conn->use_begindir)
2609 return 0;
2611 /* No flags for hidden services. */
2612 if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
2613 return 0;
2615 /* If only IPv4 is supported, no flags */
2616 if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
2617 return 0;
2619 if (! cpath_layer ||
2620 ! cpath_layer->extend_info)
2621 return 0;
2623 if (!ap_conn->entry_cfg.ipv4_traffic)
2624 flags |= BEGIN_FLAG_IPV4_NOT_OK;
2626 exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
2628 if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
2629 tor_addr_t a;
2630 tor_addr_make_null(&a, AF_INET6);
2631 if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
2632 exitnode)
2633 != ADDR_POLICY_REJECTED) {
2634 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
2635 * no point. */
2636 flags |= BEGIN_FLAG_IPV6_OK;
2640 if (flags == BEGIN_FLAG_IPV6_OK) {
2641 /* When IPv4 and IPv6 are both allowed, consider whether to say we
2642 * prefer IPv6. Otherwise there's no point in declaring a preference */
2643 if (ap_conn->entry_cfg.prefer_ipv6)
2644 flags |= BEGIN_FLAG_IPV6_PREFERRED;
2647 if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
2648 log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
2649 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
2650 "not going to work. Did you perhaps ask for an IPv6 address "
2651 "on an IPv4Only port, or vice versa?");
2654 return flags;
2657 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2658 * socks_request field, and send it down circ.
2660 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2662 MOCK_IMPL(int,
2663 connection_ap_handshake_send_begin,(entry_connection_t *ap_conn))
2665 char payload[CELL_PAYLOAD_SIZE];
2666 int payload_len;
2667 int begin_type;
2668 const or_options_t *options = get_options();
2669 origin_circuit_t *circ;
2670 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2671 connection_t *base_conn = TO_CONN(edge_conn);
2672 tor_assert(edge_conn->on_circuit);
2673 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
2675 tor_assert(base_conn->type == CONN_TYPE_AP);
2676 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2677 tor_assert(ap_conn->socks_request);
2678 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2680 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
2681 if (edge_conn->stream_id==0) {
2682 /* XXXX+ Instead of closing this stream, we should make it get
2683 * retried on another circuit. */
2684 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2686 /* Mark this circuit "unusable for new streams". */
2687 mark_circuit_unusable_for_new_conns(circ);
2688 return -1;
2691 /* Set up begin cell flags. */
2692 edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
2694 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2695 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2696 ap_conn->socks_request->address : "",
2697 ap_conn->socks_request->port);
2698 payload_len = (int)strlen(payload)+1;
2699 if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
2700 set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
2701 payload_len += 4;
2704 log_info(LD_APP,
2705 "Sending relay cell %d on circ %u to begin stream %d.",
2706 (int)ap_conn->use_begindir,
2707 (unsigned)circ->base_.n_circ_id,
2708 edge_conn->stream_id);
2710 begin_type = ap_conn->use_begindir ?
2711 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2713 /* Check that circuits are anonymised, based on their type. */
2714 if (begin_type == RELAY_COMMAND_BEGIN) {
2715 /* This connection is a standard OR connection.
2716 * Make sure its path length is anonymous, or that we're in a
2717 * non-anonymous mode. */
2718 assert_circ_anonymity_ok(circ, options);
2719 } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
2720 /* This connection is a begindir directory connection.
2721 * Look at the linked directory connection to access the directory purpose.
2722 * If a BEGINDIR connection is ever not linked, that's a bug. */
2723 if (BUG(!base_conn->linked)) {
2724 return -1;
2726 connection_t *linked_dir_conn_base = base_conn->linked_conn;
2727 /* If the linked connection has been unlinked by other code, we can't send
2728 * a begin cell on it. */
2729 if (!linked_dir_conn_base) {
2730 return -1;
2732 /* Sensitive directory connections must have an anonymous path length.
2733 * Otherwise, directory connections are typically one-hop.
2734 * This matches the earlier check for directory connection path anonymity
2735 * in directory_initiate_request(). */
2736 if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
2737 TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
2738 TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
2739 assert_circ_anonymity_ok(circ, options);
2741 } else {
2742 /* This code was written for the two connection types BEGIN and BEGIN_DIR
2744 tor_assert_unreached();
2747 if (connection_edge_send_command(edge_conn, begin_type,
2748 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2749 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2750 return -1; /* circuit is closed, don't continue */
2752 edge_conn->package_window = STREAMWINDOW_START;
2753 edge_conn->deliver_window = STREAMWINDOW_START;
2754 base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
2755 log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
2756 ", n_circ_id %u",
2757 base_conn->s, (unsigned)circ->base_.n_circ_id);
2758 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2760 /* If there's queued-up data, send it now */
2761 if ((connection_get_inbuf_len(base_conn) ||
2762 ap_conn->sending_optimistic_data) &&
2763 connection_ap_supports_optimistic_data(ap_conn)) {
2764 log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
2765 (long)connection_get_inbuf_len(base_conn),
2766 ap_conn->sending_optimistic_data ?
2767 (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
2768 if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
2769 connection_mark_for_close(base_conn);
2773 return 0;
2776 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2777 * socks_request field, and send it down circ.
2779 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2782 connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
2784 int payload_len, command;
2785 const char *string_addr;
2786 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2787 origin_circuit_t *circ;
2788 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2789 connection_t *base_conn = TO_CONN(edge_conn);
2790 tor_assert(edge_conn->on_circuit);
2791 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
2793 tor_assert(base_conn->type == CONN_TYPE_AP);
2794 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2795 tor_assert(ap_conn->socks_request);
2796 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2798 command = ap_conn->socks_request->command;
2799 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2801 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
2802 if (edge_conn->stream_id==0) {
2803 /* XXXX+ Instead of closing this stream, we should make it get
2804 * retried on another circuit. */
2805 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2807 /* Mark this circuit "unusable for new streams". */
2808 mark_circuit_unusable_for_new_conns(circ);
2809 return -1;
2812 if (command == SOCKS_COMMAND_RESOLVE) {
2813 string_addr = ap_conn->socks_request->address;
2814 payload_len = (int)strlen(string_addr)+1;
2815 } else {
2816 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2817 const char *a = ap_conn->socks_request->address;
2818 tor_addr_t addr;
2819 int r;
2821 /* We're doing a reverse lookup. The input could be an IP address, or
2822 * could be an .in-addr.arpa or .ip6.arpa address */
2823 r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
2824 if (r <= 0) {
2825 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2826 safe_str_client(a));
2827 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2828 return -1;
2831 r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2832 if (r < 0) {
2833 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2834 safe_str_client(a));
2835 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2836 return -1;
2839 string_addr = inaddr_buf;
2840 payload_len = (int)strlen(inaddr_buf)+1;
2841 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
2844 log_debug(LD_APP,
2845 "Sending relay cell to begin stream %d.", edge_conn->stream_id);
2847 if (connection_edge_send_command(edge_conn,
2848 RELAY_COMMAND_RESOLVE,
2849 string_addr, payload_len) < 0)
2850 return -1; /* circuit is closed, don't continue */
2852 if (!base_conn->address) {
2853 /* This might be unnecessary. XXXX */
2854 base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
2856 base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
2857 log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
2858 ", n_circ_id %u",
2859 base_conn->s, (unsigned)circ->base_.n_circ_id);
2860 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2861 return 0;
2864 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
2865 * new linked connection pair, and attach one side to the conn, connection_add
2866 * it, initialize it to circuit_wait, and call
2867 * connection_ap_handshake_attach_circuit(conn) on it.
2869 * Return the newly created end of the linked connection pair, or -1 if error.
2871 entry_connection_t *
2872 connection_ap_make_link(connection_t *partner,
2873 char *address, uint16_t port,
2874 const char *digest,
2875 int session_group, int isolation_flags,
2876 int use_begindir, int want_onehop)
2878 entry_connection_t *conn;
2879 connection_t *base_conn;
2881 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2882 want_onehop ? "direct" : "anonymized",
2883 safe_str_client(address), port);
2885 conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
2886 base_conn = ENTRY_TO_CONN(conn);
2887 base_conn->linked = 1; /* so that we can add it safely below. */
2889 /* populate conn->socks_request */
2891 /* leave version at zero, so the socks_reply is empty */
2892 conn->socks_request->socks_version = 0;
2893 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2894 strlcpy(conn->socks_request->address, address,
2895 sizeof(conn->socks_request->address));
2896 conn->socks_request->port = port;
2897 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2898 conn->want_onehop = want_onehop;
2899 conn->use_begindir = use_begindir;
2900 if (use_begindir) {
2901 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2902 conn->chosen_exit_name[0] = '$';
2903 tor_assert(digest);
2904 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2905 digest, DIGEST_LEN);
2908 /* Populate isolation fields. */
2909 conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
2910 conn->original_dest_address = tor_strdup(address);
2911 conn->entry_cfg.session_group = session_group;
2912 conn->entry_cfg.isolation_flags = isolation_flags;
2914 base_conn->address = tor_strdup("(Tor_internal)");
2915 tor_addr_make_unspec(&base_conn->addr);
2916 base_conn->port = 0;
2918 connection_link_connections(partner, base_conn);
2920 if (connection_add(base_conn) < 0) { /* no space, forget it */
2921 connection_free(base_conn);
2922 return NULL;
2925 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2927 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2929 /* attaching to a dirty circuit is fine */
2930 connection_ap_mark_as_pending_circuit(conn);
2931 log_info(LD_APP,"... application connection created and linked.");
2932 return conn;
2935 /** Notify any interested controller connections about a new hostname resolve
2936 * or resolve error. Takes the same arguments as does
2937 * connection_ap_handshake_socks_resolved(). */
2938 static void
2939 tell_controller_about_resolved_result(entry_connection_t *conn,
2940 int answer_type,
2941 size_t answer_len,
2942 const char *answer,
2943 int ttl,
2944 time_t expires)
2946 expires = time(NULL) + ttl;
2947 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2948 char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
2949 control_event_address_mapped(conn->socks_request->address,
2950 cp, expires, NULL, 0);
2951 tor_free(cp);
2952 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2953 char *cp = tor_strndup(answer, answer_len);
2954 control_event_address_mapped(conn->socks_request->address,
2955 cp, expires, NULL, 0);
2956 tor_free(cp);
2957 } else {
2958 control_event_address_mapped(conn->socks_request->address,
2959 "<error>", time(NULL)+ttl,
2960 "error=yes", 0);
2965 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
2966 * as the answer.
2968 void
2969 connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
2970 const tor_addr_t *answer,
2971 int ttl,
2972 time_t expires)
2974 if (tor_addr_family(answer) == AF_INET) {
2975 uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
2976 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
2977 (uint8_t*)&a,
2978 ttl, expires);
2979 } else if (tor_addr_family(answer) == AF_INET6) {
2980 const uint8_t *a = tor_addr_to_in6_addr8(answer);
2981 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
2983 ttl, expires);
2984 } else {
2985 log_warn(LD_BUG, "Got called with address of unexpected family %d",
2986 tor_addr_family(answer));
2987 connection_ap_handshake_socks_resolved(conn,
2988 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
2992 /** Send an answer to an AP connection that has requested a DNS lookup via
2993 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2994 * for unreachable; the answer should be in the format specified in the socks
2995 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2996 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2997 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2999 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
3000 * interface and those that use it less ugly. */
3001 MOCK_IMPL(void,
3002 connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
3003 int answer_type,
3004 size_t answer_len,
3005 const uint8_t *answer,
3006 int ttl,
3007 time_t expires))
3009 char buf[384];
3010 size_t replylen;
3012 if (ttl >= 0) {
3013 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3014 tor_addr_t a;
3015 tor_addr_from_ipv4n(&a, get_uint32(answer));
3016 if (! tor_addr_is_null(&a)) {
3017 client_dns_set_addressmap(conn,
3018 conn->socks_request->address, &a,
3019 conn->chosen_exit_name, ttl);
3021 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3022 tor_addr_t a;
3023 tor_addr_from_ipv6_bytes(&a, (char*)answer);
3024 if (! tor_addr_is_null(&a)) {
3025 client_dns_set_addressmap(conn,
3026 conn->socks_request->address, &a,
3027 conn->chosen_exit_name, ttl);
3029 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3030 char *cp = tor_strndup((char*)answer, answer_len);
3031 client_dns_set_reverse_addressmap(conn,
3032 conn->socks_request->address,
3034 conn->chosen_exit_name, ttl);
3035 tor_free(cp);
3039 if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
3040 if (conn->dns_server_request) {
3041 /* We had a request on our DNS port: answer it. */
3042 dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
3043 conn->socks_request->has_finished = 1;
3044 return;
3045 } else {
3046 /* This must be a request from the controller. Since answers to those
3047 * requests are not cached, they do not generate an ADDRMAP event on
3048 * their own. */
3049 tell_controller_about_resolved_result(conn, answer_type, answer_len,
3050 (char*)answer, ttl, expires);
3051 conn->socks_request->has_finished = 1;
3052 return;
3054 /* We shouldn't need to free conn here; it gets marked by the caller. */
3057 if (conn->socks_request->socks_version == 4) {
3058 buf[0] = 0x00; /* version */
3059 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3060 buf[1] = SOCKS4_GRANTED;
3061 set_uint16(buf+2, 0);
3062 memcpy(buf+4, answer, 4); /* address */
3063 replylen = SOCKS4_NETWORK_LEN;
3064 } else { /* "error" */
3065 buf[1] = SOCKS4_REJECT;
3066 memset(buf+2, 0, 6);
3067 replylen = SOCKS4_NETWORK_LEN;
3069 } else if (conn->socks_request->socks_version == 5) {
3070 /* SOCKS5 */
3071 buf[0] = 0x05; /* version */
3072 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3073 buf[1] = SOCKS5_SUCCEEDED;
3074 buf[2] = 0; /* reserved */
3075 buf[3] = 0x01; /* IPv4 address type */
3076 memcpy(buf+4, answer, 4); /* address */
3077 set_uint16(buf+8, 0); /* port == 0. */
3078 replylen = 10;
3079 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3080 buf[1] = SOCKS5_SUCCEEDED;
3081 buf[2] = 0; /* reserved */
3082 buf[3] = 0x04; /* IPv6 address type */
3083 memcpy(buf+4, answer, 16); /* address */
3084 set_uint16(buf+20, 0); /* port == 0. */
3085 replylen = 22;
3086 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3087 buf[1] = SOCKS5_SUCCEEDED;
3088 buf[2] = 0; /* reserved */
3089 buf[3] = 0x03; /* Domainname address type */
3090 buf[4] = (char)answer_len;
3091 memcpy(buf+5, answer, answer_len); /* address */
3092 set_uint16(buf+5+answer_len, 0); /* port == 0. */
3093 replylen = 5+answer_len+2;
3094 } else {
3095 buf[1] = SOCKS5_HOST_UNREACHABLE;
3096 memset(buf+2, 0, 8);
3097 replylen = 10;
3099 } else {
3100 /* no socks version info; don't send anything back */
3101 return;
3103 connection_ap_handshake_socks_reply(conn, buf, replylen,
3104 (answer_type == RESOLVED_TYPE_IPV4 ||
3105 answer_type == RESOLVED_TYPE_IPV6 ||
3106 answer_type == RESOLVED_TYPE_HOSTNAME) ?
3107 0 : END_STREAM_REASON_RESOLVEFAILED);
3110 /** Send a socks reply to stream <b>conn</b>, using the appropriate
3111 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
3112 * handshaking.
3114 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
3115 * and return, else reply based on <b>endreason</b> (one of
3116 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
3117 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
3119 void
3120 connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
3121 size_t replylen, int endreason)
3123 char buf[256];
3124 socks5_reply_status_t status =
3125 stream_end_reason_to_socks5_response(endreason);
3127 tor_assert(conn->socks_request); /* make sure it's an AP stream */
3129 if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3130 control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
3131 STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
3132 endreason);
3135 /* Flag this stream's circuit as having completed a stream successfully
3136 * (for path bias) */
3137 if (status == SOCKS5_SUCCEEDED ||
3138 endreason == END_STREAM_REASON_RESOLVEFAILED ||
3139 endreason == END_STREAM_REASON_CONNECTREFUSED ||
3140 endreason == END_STREAM_REASON_CONNRESET ||
3141 endreason == END_STREAM_REASON_NOROUTE ||
3142 endreason == END_STREAM_REASON_RESOURCELIMIT) {
3143 if (!conn->edge_.on_circuit ||
3144 !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
3145 if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
3146 log_info(LD_BUG,
3147 "No origin circuit for successful SOCKS stream "U64_FORMAT
3148 ". Reason: %d",
3149 U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
3150 endreason);
3153 * Else DNS remaps and failed hidden service lookups can send us
3154 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3156 * Perhaps we could make the test more precise; we can tell hidden
3157 * services by conn->edge_.renddata != NULL; anything analogous for
3158 * the DNS remap case?
3160 } else {
3161 // XXX: Hrmm. It looks like optimistic data can't go through this
3162 // codepath, but someone should probably test it and make sure.
3163 // We don't want to mark optimistically opened streams as successful.
3164 pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
3168 if (conn->socks_request->has_finished) {
3169 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
3170 "connection_ap_handshake_socks_reply.");
3171 return;
3173 if (replylen) { /* we already have a reply in mind */
3174 connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
3175 conn->socks_request->has_finished = 1;
3176 return;
3178 if (conn->socks_request->listener_type ==
3179 CONN_TYPE_AP_HTTP_CONNECT_LISTENER) {
3180 const char *response = end_reason_to_http_connect_response_line(endreason);
3181 if (!response) {
3182 response = "HTTP/1.0 400 Bad Request\r\n\r\n";
3184 connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
3185 } else if (conn->socks_request->socks_version == 4) {
3186 memset(buf,0,SOCKS4_NETWORK_LEN);
3187 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
3188 /* leave version, destport, destip zero */
3189 connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
3190 } else if (conn->socks_request->socks_version == 5) {
3191 size_t buf_len;
3192 memset(buf,0,sizeof(buf));
3193 if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
3194 buf[0] = 5; /* version 5 */
3195 buf[1] = (char)status;
3196 buf[2] = 0;
3197 buf[3] = 1; /* ipv4 addr */
3198 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3199 buf_len = 10;
3200 } else { /* AF_INET6. */
3201 buf[0] = 5; /* version 5 */
3202 buf[1] = (char)status;
3203 buf[2] = 0;
3204 buf[3] = 4; /* ipv6 addr */
3205 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3206 buf_len = 22;
3208 connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
3210 /* If socks_version isn't 4 or 5, don't send anything.
3211 * This can happen in the case of AP bridges. */
3212 conn->socks_request->has_finished = 1;
3213 return;
3216 /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
3217 * place the result in <b>bcell</b>. On success return 0; on failure return
3218 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
3219 * the client.
3221 * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
3222 * we don't.
3224 STATIC int
3225 begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
3226 uint8_t *end_reason_out)
3228 relay_header_t rh;
3229 const uint8_t *body, *nul;
3231 memset(bcell, 0, sizeof(*bcell));
3232 *end_reason_out = END_STREAM_REASON_MISC;
3234 relay_header_unpack(&rh, cell->payload);
3235 if (rh.length > RELAY_PAYLOAD_SIZE) {
3236 return -2; /*XXXX why not TORPROTOCOL? */
3239 bcell->stream_id = rh.stream_id;
3241 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3242 bcell->is_begindir = 1;
3243 return 0;
3244 } else if (rh.command != RELAY_COMMAND_BEGIN) {
3245 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3246 *end_reason_out = END_STREAM_REASON_INTERNAL;
3247 return -1;
3250 body = cell->payload + RELAY_HEADER_SIZE;
3251 nul = memchr(body, 0, rh.length);
3252 if (! nul) {
3253 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3254 "Relay begin cell has no \\0. Closing.");
3255 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3256 return -1;
3259 if (tor_addr_port_split(LOG_PROTOCOL_WARN,
3260 (char*)(body),
3261 &bcell->address,&bcell->port)<0) {
3262 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3263 "Unable to parse addr:port in relay begin cell. Closing.");
3264 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3265 return -1;
3267 if (bcell->port == 0) {
3268 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3269 "Missing port in relay begin cell. Closing.");
3270 tor_free(bcell->address);
3271 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3272 return -1;
3274 if (body + rh.length >= nul + 4)
3275 bcell->flags = ntohl(get_uint32(nul+1));
3277 return 0;
3280 /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
3281 * connection, attach it to the circ and connect it. Return 0 on success
3282 * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
3283 * where the caller should close the circuit. */
3284 static int
3285 handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
3287 int ret;
3288 origin_circuit_t *origin_circ;
3290 assert_circuit_ok(circ);
3291 tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
3292 tor_assert(conn);
3294 log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
3295 "to the service destination.");
3297 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3298 conn->base_.address = tor_strdup("(rendezvous)");
3299 conn->base_.state = EXIT_CONN_STATE_CONNECTING;
3301 /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
3302 * service. */
3303 if (origin_circ->rend_data) {
3304 conn->rend_data = rend_data_dup(origin_circ->rend_data);
3305 tor_assert(connection_edge_is_rendezvous_stream(conn));
3306 ret = rend_service_set_connection_addr_port(conn, origin_circ);
3307 } else if (origin_circ->hs_ident) {
3308 /* Setup the identifier to be the one for the circuit service. */
3309 conn->hs_ident =
3310 hs_ident_edge_conn_new(&origin_circ->hs_ident->identity_pk);
3311 tor_assert(connection_edge_is_rendezvous_stream(conn));
3312 ret = hs_service_set_conn_addr_port(origin_circ, conn);
3313 } else {
3314 /* We should never get here if the circuit's purpose is rendezvous. */
3315 tor_assert_nonfatal_unreached();
3316 return -1;
3318 if (ret < 0) {
3319 log_info(LD_REND, "Didn't find rendezvous service (addr%s, port %d)",
3320 fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port);
3321 /* Send back reason DONE because we want to make hidden service port
3322 * scanning harder thus instead of returning that the exit policy
3323 * didn't match, which makes it obvious that the port is closed,
3324 * return DONE and kill the circuit. That way, a user (malicious or
3325 * not) needs one circuit per bad port unless it matches the policy of
3326 * the hidden service. */
3327 relay_send_end_cell_from_edge(conn->stream_id, circ,
3328 END_STREAM_REASON_DONE,
3329 origin_circ->cpath->prev);
3330 connection_free(TO_CONN(conn));
3332 /* Drop the circuit here since it might be someone deliberately
3333 * scanning the hidden service ports. Note that this mitigates port
3334 * scanning by adding more work on the attacker side to successfully
3335 * scan but does not fully solve it. */
3336 if (ret < -1) {
3337 return END_CIRC_AT_ORIGIN;
3338 } else {
3339 return 0;
3343 /* Link the circuit and the connection crypt path. */
3344 conn->cpath_layer = origin_circ->cpath->prev;
3346 /* Add it into the linked list of p_streams on this circuit */
3347 conn->next_stream = origin_circ->p_streams;
3348 origin_circ->p_streams = conn;
3349 conn->on_circuit = circ;
3350 assert_circuit_ok(circ);
3352 hs_inc_rdv_stream_counter(origin_circ);
3354 /* Connect tor to the hidden service destination. */
3355 connection_exit_connect(conn);
3357 /* For path bias: This circuit was used successfully */
3358 pathbias_mark_use_success(origin_circ);
3359 return 0;
3362 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
3363 * an exit hop for the circuit, or we are the origin and it is a
3364 * rendezvous begin.
3366 * Launch a new exit connection and initialize things appropriately.
3368 * If it's a rendezvous stream, call connection_exit_connect() on
3369 * it.
3371 * For general streams, call dns_resolve() on it first, and only call
3372 * connection_exit_connect() if the dns answer is already known.
3374 * Note that we don't call connection_add() on the new stream! We wait
3375 * for connection_exit_connect() to do that.
3377 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
3378 * Else return 0.
3381 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
3383 edge_connection_t *n_stream;
3384 relay_header_t rh;
3385 char *address = NULL;
3386 uint16_t port = 0;
3387 or_circuit_t *or_circ = NULL;
3388 origin_circuit_t *origin_circ = NULL;
3389 crypt_path_t *layer_hint = NULL;
3390 const or_options_t *options = get_options();
3391 begin_cell_t bcell;
3392 int rv;
3393 uint8_t end_reason=0;
3395 assert_circuit_ok(circ);
3396 if (!CIRCUIT_IS_ORIGIN(circ)) {
3397 or_circ = TO_OR_CIRCUIT(circ);
3398 } else {
3399 tor_assert(circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED);
3400 origin_circ = TO_ORIGIN_CIRCUIT(circ);
3401 layer_hint = origin_circ->cpath->prev;
3404 relay_header_unpack(&rh, cell->payload);
3405 if (rh.length > RELAY_PAYLOAD_SIZE)
3406 return -END_CIRC_REASON_TORPROTOCOL;
3408 /* Note: we have to use relay_send_command_from_edge here, not
3409 * connection_edge_end or connection_edge_send_command, since those require
3410 * that we have a stream connected to a circuit, and we don't connect to a
3411 * circuit until we have a pending/successful resolve. */
3413 if (!server_mode(options) &&
3414 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
3415 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3416 "Relay begin cell at non-server. Closing.");
3417 relay_send_end_cell_from_edge(rh.stream_id, circ,
3418 END_STREAM_REASON_EXITPOLICY, NULL);
3419 return 0;
3422 rv = begin_cell_parse(cell, &bcell, &end_reason);
3423 if (rv < -1) {
3424 return -END_CIRC_REASON_TORPROTOCOL;
3425 } else if (rv == -1) {
3426 tor_free(bcell.address);
3427 relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
3428 return 0;
3431 if (! bcell.is_begindir) {
3432 /* Steal reference */
3433 address = bcell.address;
3434 port = bcell.port;
3436 if (or_circ && or_circ->p_chan) {
3437 const int client_chan = channel_is_client(or_circ->p_chan);
3438 if ((client_chan ||
3439 (!connection_or_digest_is_known_relay(
3440 or_circ->p_chan->identity_digest) &&
3441 should_refuse_unknown_exits(options)))) {
3442 /* Don't let clients use us as a single-hop proxy. It attracts
3443 * attackers and users who'd be better off with, well, single-hop
3444 * proxies. */
3445 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3446 "Attempt by %s to open a stream %s. Closing.",
3447 safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
3448 client_chan ? "on first hop of circuit" :
3449 "from unknown relay");
3450 relay_send_end_cell_from_edge(rh.stream_id, circ,
3451 client_chan ?
3452 END_STREAM_REASON_TORPROTOCOL :
3453 END_STREAM_REASON_MISC,
3454 NULL);
3455 tor_free(address);
3456 return 0;
3459 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3460 if (!directory_permits_begindir_requests(options) ||
3461 circ->purpose != CIRCUIT_PURPOSE_OR) {
3462 relay_send_end_cell_from_edge(rh.stream_id, circ,
3463 END_STREAM_REASON_NOTDIRECTORY, layer_hint);
3464 return 0;
3466 /* Make sure to get the 'real' address of the previous hop: the
3467 * caller might want to know whether the remote IP address has changed,
3468 * and we might already have corrected base_.addr[ess] for the relay's
3469 * canonical IP address. */
3470 if (or_circ && or_circ->p_chan)
3471 address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
3472 else
3473 address = tor_strdup("127.0.0.1");
3474 port = 1; /* XXXX This value is never actually used anywhere, and there
3475 * isn't "really" a connection here. But we
3476 * need to set it to something nonzero. */
3477 } else {
3478 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3479 relay_send_end_cell_from_edge(rh.stream_id, circ,
3480 END_STREAM_REASON_INTERNAL, layer_hint);
3481 return 0;
3484 if (! options->IPv6Exit) {
3485 /* I don't care if you prefer IPv6; I can't give you any. */
3486 bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
3487 /* If you don't want IPv4, I can't help. */
3488 if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
3489 tor_free(address);
3490 relay_send_end_cell_from_edge(rh.stream_id, circ,
3491 END_STREAM_REASON_EXITPOLICY, layer_hint);
3492 return 0;
3496 log_debug(LD_EXIT,"Creating new exit connection.");
3497 /* The 'AF_INET' here is temporary; we might need to change it later in
3498 * connection_exit_connect(). */
3499 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
3501 /* Remember the tunneled request ID in the new edge connection, so that
3502 * we can measure download times. */
3503 n_stream->dirreq_id = circ->dirreq_id;
3505 n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
3506 n_stream->begincell_flags = bcell.flags;
3507 n_stream->stream_id = rh.stream_id;
3508 n_stream->base_.port = port;
3509 /* leave n_stream->s at -1, because it's not yet valid */
3510 n_stream->package_window = STREAMWINDOW_START;
3511 n_stream->deliver_window = STREAMWINDOW_START;
3513 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
3514 tor_free(address);
3515 /* We handle this circuit and stream in this function for all supported
3516 * hidden service version. */
3517 return handle_hs_exit_conn(circ, n_stream);
3519 tor_strlower(address);
3520 n_stream->base_.address = address;
3521 n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3522 /* default to failed, change in dns_resolve if it turns out not to fail */
3524 if (we_are_hibernating()) {
3525 relay_send_end_cell_from_edge(rh.stream_id, circ,
3526 END_STREAM_REASON_HIBERNATING, NULL);
3527 connection_free(TO_CONN(n_stream));
3528 return 0;
3531 n_stream->on_circuit = circ;
3533 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3534 tor_addr_t tmp_addr;
3535 tor_assert(or_circ);
3536 if (or_circ->p_chan &&
3537 channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
3538 tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
3540 return connection_exit_connect_dir(n_stream);
3543 log_debug(LD_EXIT,"about to start the dns_resolve().");
3545 /* send it off to the gethostbyname farm */
3546 switch (dns_resolve(n_stream)) {
3547 case 1: /* resolve worked; now n_stream is attached to circ. */
3548 assert_circuit_ok(circ);
3549 log_debug(LD_EXIT,"about to call connection_exit_connect().");
3550 connection_exit_connect(n_stream);
3551 return 0;
3552 case -1: /* resolve failed */
3553 relay_send_end_cell_from_edge(rh.stream_id, circ,
3554 END_STREAM_REASON_RESOLVEFAILED, NULL);
3555 /* n_stream got freed. don't touch it. */
3556 break;
3557 case 0: /* resolve added to pending list */
3558 assert_circuit_ok(circ);
3559 break;
3561 return 0;
3565 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
3566 * circuit <b>circ</b>;
3567 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
3570 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
3572 edge_connection_t *dummy_conn;
3573 relay_header_t rh;
3575 assert_circuit_ok(TO_CIRCUIT(circ));
3576 relay_header_unpack(&rh, cell->payload);
3577 if (rh.length > RELAY_PAYLOAD_SIZE)
3578 return -1;
3580 /* This 'dummy_conn' only exists to remember the stream ID
3581 * associated with the resolve request; and to make the
3582 * implementation of dns.c more uniform. (We really only need to
3583 * remember the circuit, the stream ID, and the hostname to be
3584 * resolved; but if we didn't store them in a connection like this,
3585 * the housekeeping in dns.c would get way more complicated.)
3587 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
3588 dummy_conn->stream_id = rh.stream_id;
3589 dummy_conn->base_.address = tor_strndup(
3590 (char*)cell->payload+RELAY_HEADER_SIZE,
3591 rh.length);
3592 dummy_conn->base_.port = 0;
3593 dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3594 dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
3596 dummy_conn->on_circuit = TO_CIRCUIT(circ);
3598 /* send it off to the gethostbyname farm */
3599 switch (dns_resolve(dummy_conn)) {
3600 case -1: /* Impossible to resolve; a resolved cell was sent. */
3601 /* Connection freed; don't touch it. */
3602 return 0;
3603 case 1: /* The result was cached; a resolved cell was sent. */
3604 if (!dummy_conn->base_.marked_for_close)
3605 connection_free(TO_CONN(dummy_conn));
3606 return 0;
3607 case 0: /* resolve added to pending list */
3608 assert_circuit_ok(TO_CIRCUIT(circ));
3609 break;
3611 return 0;
3614 /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
3615 * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
3617 static int
3618 my_exit_policy_rejects(const tor_addr_t *addr,
3619 uint16_t port,
3620 const char **why_rejected)
3622 if (router_compare_to_my_exit_policy(addr, port)) {
3623 *why_rejected = "";
3624 return 1;
3625 } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
3626 *why_rejected = " (IPv6 address without IPv6Exit configured)";
3627 return 1;
3629 return 0;
3632 /** Connect to conn's specified addr and port. If it worked, conn
3633 * has now been added to the connection_array.
3635 * Send back a connected cell. Include the resolved IP of the destination
3636 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
3637 * streams must not reveal what IP they connected to.)
3639 void
3640 connection_exit_connect(edge_connection_t *edge_conn)
3642 const tor_addr_t *addr;
3643 uint16_t port;
3644 connection_t *conn = TO_CONN(edge_conn);
3645 int socket_error = 0, result;
3646 const char *why_failed_exit_policy = NULL;
3648 /* Apply exit policy to non-rendezvous connections. */
3649 if (! connection_edge_is_rendezvous_stream(edge_conn) &&
3650 my_exit_policy_rejects(&edge_conn->base_.addr,
3651 edge_conn->base_.port,
3652 &why_failed_exit_policy)) {
3653 if (BUG(!why_failed_exit_policy))
3654 why_failed_exit_policy = "";
3655 log_info(LD_EXIT,"%s:%d failed exit policy%s. Closing.",
3656 escaped_safe_str_client(conn->address), conn->port,
3657 why_failed_exit_policy);
3658 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
3659 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3660 connection_free(conn);
3661 return;
3664 #ifdef HAVE_SYS_UN_H
3665 if (conn->socket_family != AF_UNIX) {
3666 #else
3668 #endif /* defined(HAVE_SYS_UN_H) */
3669 addr = &conn->addr;
3670 port = conn->port;
3672 if (tor_addr_family(addr) == AF_INET6)
3673 conn->socket_family = AF_INET6;
3675 log_debug(LD_EXIT, "about to try connecting");
3676 result = connection_connect(conn, conn->address,
3677 addr, port, &socket_error);
3678 #ifdef HAVE_SYS_UN_H
3679 } else {
3681 * In the AF_UNIX case, we expect to have already had conn->port = 1,
3682 * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
3683 * case in connection_handle_listener_read()), and conn->address should
3684 * have the socket path to connect to.
3686 tor_assert(conn->address && strlen(conn->address) > 0);
3688 log_debug(LD_EXIT, "about to try connecting");
3689 result = connection_connect_unix(conn, conn->address, &socket_error);
3690 #endif /* defined(HAVE_SYS_UN_H) */
3693 switch (result) {
3694 case -1: {
3695 int reason = errno_to_stream_end_reason(socket_error);
3696 connection_edge_end(edge_conn, reason);
3697 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3698 connection_free(conn);
3699 return;
3701 case 0:
3702 conn->state = EXIT_CONN_STATE_CONNECTING;
3704 connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
3705 /* writable indicates finish;
3706 * readable/error indicates broken link in windows-land. */
3707 return;
3708 /* case 1: fall through */
3711 conn->state = EXIT_CONN_STATE_OPEN;
3712 if (connection_get_outbuf_len(conn)) {
3713 /* in case there are any queued data cells, from e.g. optimistic data */
3714 connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
3715 } else {
3716 connection_watch_events(conn, READ_EVENT);
3719 /* also, deliver a 'connected' cell back through the circuit. */
3720 if (connection_edge_is_rendezvous_stream(edge_conn)) {
3721 /* don't send an address back! */
3722 connection_edge_send_command(edge_conn,
3723 RELAY_COMMAND_CONNECTED,
3724 NULL, 0);
3725 } else { /* normal stream */
3726 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
3727 int connected_payload_len =
3728 connected_cell_format_payload(connected_payload, &conn->addr,
3729 edge_conn->address_ttl);
3730 if (connected_payload_len < 0) {
3731 connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
3732 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3733 connection_free(conn);
3734 return;
3737 connection_edge_send_command(edge_conn,
3738 RELAY_COMMAND_CONNECTED,
3739 (char*)connected_payload,
3740 connected_payload_len);
3744 /** Given an exit conn that should attach to us as a directory server, open a
3745 * bridge connection with a linked connection pair, create a new directory
3746 * conn, and join them together. Return 0 on success (or if there was an
3747 * error we could send back an end cell for). Return -(some circuit end
3748 * reason) if the circuit needs to be torn down. Either connects
3749 * <b>exitconn</b>, frees it, or marks it, as appropriate.
3751 static int
3752 connection_exit_connect_dir(edge_connection_t *exitconn)
3754 dir_connection_t *dirconn = NULL;
3755 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
3757 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
3759 exitconn->base_.state = EXIT_CONN_STATE_OPEN;
3761 dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
3763 tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
3764 dirconn->base_.port = 0;
3765 dirconn->base_.address = tor_strdup(exitconn->base_.address);
3766 dirconn->base_.type = CONN_TYPE_DIR;
3767 dirconn->base_.purpose = DIR_PURPOSE_SERVER;
3768 dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
3770 /* Note that the new dir conn belongs to the same tunneled request as
3771 * the edge conn, so that we can measure download times. */
3772 dirconn->dirreq_id = exitconn->dirreq_id;
3774 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
3776 if (connection_add(TO_CONN(exitconn))<0) {
3777 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
3778 connection_free(TO_CONN(exitconn));
3779 connection_free(TO_CONN(dirconn));
3780 return 0;
3783 /* link exitconn to circ, now that we know we can use it. */
3784 exitconn->next_stream = circ->n_streams;
3785 circ->n_streams = exitconn;
3787 if (connection_add(TO_CONN(dirconn))<0) {
3788 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
3789 connection_close_immediate(TO_CONN(exitconn));
3790 connection_mark_for_close(TO_CONN(exitconn));
3791 connection_free(TO_CONN(dirconn));
3792 return 0;
3795 connection_start_reading(TO_CONN(dirconn));
3796 connection_start_reading(TO_CONN(exitconn));
3798 if (connection_edge_send_command(exitconn,
3799 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
3800 connection_mark_for_close(TO_CONN(exitconn));
3801 connection_mark_for_close(TO_CONN(dirconn));
3802 return 0;
3805 return 0;
3808 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
3809 * it is a general stream.
3812 connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
3814 tor_assert(conn);
3815 /* It should not be possible to set both of these structs */
3816 tor_assert_nonfatal(!(conn->rend_data && conn->hs_ident));
3818 if (conn->rend_data || conn->hs_ident) {
3819 return 1;
3821 return 0;
3824 /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
3825 * to exit from it, or 0 if it probably will not allow it.
3826 * (We might be uncertain if conn's destination address has not yet been
3827 * resolved.)
3830 connection_ap_can_use_exit(const entry_connection_t *conn,
3831 const node_t *exit_node)
3833 const or_options_t *options = get_options();
3835 tor_assert(conn);
3836 tor_assert(conn->socks_request);
3837 tor_assert(exit_node);
3839 /* If a particular exit node has been requested for the new connection,
3840 * make sure the exit node of the existing circuit matches exactly.
3842 if (conn->chosen_exit_name) {
3843 const node_t *chosen_exit =
3844 node_get_by_nickname(conn->chosen_exit_name, 0);
3845 if (!chosen_exit || tor_memneq(chosen_exit->identity,
3846 exit_node->identity, DIGEST_LEN)) {
3847 /* doesn't match */
3848 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
3849 // conn->chosen_exit_name, exit->nickname);
3850 return 0;
3854 if (conn->use_begindir) {
3855 /* Internal directory fetches do not count as exiting. */
3856 return 1;
3859 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
3860 tor_addr_t addr, *addrp = NULL;
3861 addr_policy_result_t r;
3862 if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
3863 addrp = &addr;
3864 } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
3865 tor_addr_make_null(&addr, AF_INET6);
3866 addrp = &addr;
3867 } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
3868 tor_addr_make_null(&addr, AF_INET);
3869 addrp = &addr;
3871 r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,
3872 exit_node);
3873 if (r == ADDR_POLICY_REJECTED)
3874 return 0; /* We know the address, and the exit policy rejects it. */
3875 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
3876 return 0; /* We don't know the addr, but the exit policy rejects most
3877 * addresses with this port. Since the user didn't ask for
3878 * this node, err on the side of caution. */
3879 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3880 /* Don't send DNS requests to non-exit servers by default. */
3881 if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
3882 return 0;
3884 if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
3885 /* Not a suitable exit. Refuse it. */
3886 return 0;
3889 return 1;
3892 /** If address is of the form "y.onion" with a well-formed handle y:
3893 * Put a NUL after y, lower-case it, and return ONION_V2_HOSTNAME or
3894 * ONION_V3_HOSTNAME depending on the HS version.
3896 * If address is of the form "x.y.onion" with a well-formed handle x:
3897 * Drop "x.", put a NUL after y, lower-case it, and return
3898 * ONION_V2_HOSTNAME or ONION_V3_HOSTNAME depending on the HS version.
3900 * If address is of the form "y.onion" with a badly-formed handle y:
3901 * Return BAD_HOSTNAME and log a message.
3903 * If address is of the form "y.exit":
3904 * Put a NUL after y and return EXIT_HOSTNAME.
3906 * Otherwise:
3907 * Return NORMAL_HOSTNAME and change nothing.
3909 hostname_type_t
3910 parse_extended_hostname(char *address)
3912 char *s;
3913 char *q;
3914 char query[HS_SERVICE_ADDR_LEN_BASE32+1];
3916 s = strrchr(address,'.');
3917 if (!s)
3918 return NORMAL_HOSTNAME; /* no dot, thus normal */
3919 if (!strcmp(s+1,"exit")) {
3920 *s = 0; /* NUL-terminate it */
3921 return EXIT_HOSTNAME; /* .exit */
3923 if (strcmp(s+1,"onion"))
3924 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
3926 /* so it is .onion */
3927 *s = 0; /* NUL-terminate it */
3928 /* locate a 'sub-domain' component, in order to remove it */
3929 q = strrchr(address, '.');
3930 if (q == address) {
3931 goto failed; /* reject sub-domain, as DNS does */
3933 q = (NULL == q) ? address : q + 1;
3934 if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
3935 HS_SERVICE_ADDR_LEN_BASE32+1)
3936 goto failed;
3937 if (q != address) {
3938 memmove(address, q, strlen(q) + 1 /* also get \0 */);
3940 if (rend_valid_v2_service_id(query)) {
3941 return ONION_V2_HOSTNAME; /* success */
3943 if (hs_address_is_valid(query)) {
3944 return ONION_V3_HOSTNAME;
3946 failed:
3947 /* otherwise, return to previous state and return 0 */
3948 *s = '.';
3949 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
3950 safe_str_client(address));
3951 return BAD_HOSTNAME;
3954 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
3955 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
3956 * at <b>b</b>. */
3957 static int
3958 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
3960 if (a == NULL) {
3961 return (b == NULL);
3962 } else if (b == NULL) {
3963 return 0;
3964 } else if (alen != blen) {
3965 return 0;
3966 } else {
3967 return tor_memeq(a, b, alen);
3972 * Return true iff none of the isolation flags and fields in <b>conn</b>
3973 * should prevent it from being attached to <b>circ</b>.
3976 connection_edge_compatible_with_circuit(const entry_connection_t *conn,
3977 const origin_circuit_t *circ)
3979 const uint8_t iso = conn->entry_cfg.isolation_flags;
3980 const socks_request_t *sr = conn->socks_request;
3982 /* If circ has never been used for an isolated connection, we can
3983 * totally use it for this one. */
3984 if (!circ->isolation_values_set)
3985 return 1;
3987 /* If circ has been used for connections having more than one value
3988 * for some field f, it will have the corresponding bit set in
3989 * isolation_flags_mixed. If isolation_flags_mixed has any bits
3990 * in common with iso, then conn must be isolated from at least
3991 * one stream that has been attached to circ. */
3992 if ((iso & circ->isolation_flags_mixed) != 0) {
3993 /* For at least one field where conn is isolated, the circuit
3994 * already has mixed streams. */
3995 return 0;
3998 if (! conn->original_dest_address) {
3999 log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
4000 "having set conn->original_dest_address");
4001 ((entry_connection_t*)conn)->original_dest_address =
4002 tor_strdup(conn->socks_request->address);
4005 if ((iso & ISO_STREAM) &&
4006 (circ->associated_isolated_stream_global_id !=
4007 ENTRY_TO_CONN(conn)->global_identifier))
4008 return 0;
4010 if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
4011 return 0;
4012 if ((iso & ISO_DESTADDR) &&
4013 strcasecmp(conn->original_dest_address, circ->dest_address))
4014 return 0;
4015 if ((iso & ISO_SOCKSAUTH) &&
4016 (! memeq_opt(sr->username, sr->usernamelen,
4017 circ->socks_username, circ->socks_username_len) ||
4018 ! memeq_opt(sr->password, sr->passwordlen,
4019 circ->socks_password, circ->socks_password_len)))
4020 return 0;
4021 if ((iso & ISO_CLIENTPROTO) &&
4022 (conn->socks_request->listener_type != circ->client_proto_type ||
4023 conn->socks_request->socks_version != circ->client_proto_socksver))
4024 return 0;
4025 if ((iso & ISO_CLIENTADDR) &&
4026 !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4027 return 0;
4028 if ((iso & ISO_SESSIONGRP) &&
4029 conn->entry_cfg.session_group != circ->session_group)
4030 return 0;
4031 if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
4032 return 0;
4034 return 1;
4038 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
4039 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
4040 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
4041 * a bitfield of isolation flags that we would have to set in
4042 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
4043 * <b>circ</b> has had no streams attached to it.
4046 connection_edge_update_circuit_isolation(const entry_connection_t *conn,
4047 origin_circuit_t *circ,
4048 int dry_run)
4050 const socks_request_t *sr = conn->socks_request;
4051 if (! conn->original_dest_address) {
4052 log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
4053 "having set conn->original_dest_address");
4054 ((entry_connection_t*)conn)->original_dest_address =
4055 tor_strdup(conn->socks_request->address);
4058 if (!circ->isolation_values_set) {
4059 if (dry_run)
4060 return -1;
4061 circ->associated_isolated_stream_global_id =
4062 ENTRY_TO_CONN(conn)->global_identifier;
4063 circ->dest_port = conn->socks_request->port;
4064 circ->dest_address = tor_strdup(conn->original_dest_address);
4065 circ->client_proto_type = conn->socks_request->listener_type;
4066 circ->client_proto_socksver = conn->socks_request->socks_version;
4067 tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
4068 circ->session_group = conn->entry_cfg.session_group;
4069 circ->nym_epoch = conn->nym_epoch;
4070 circ->socks_username = sr->username ?
4071 tor_memdup(sr->username, sr->usernamelen) : NULL;
4072 circ->socks_password = sr->password ?
4073 tor_memdup(sr->password, sr->passwordlen) : NULL;
4074 circ->socks_username_len = sr->usernamelen;
4075 circ->socks_password_len = sr->passwordlen;
4077 circ->isolation_values_set = 1;
4078 return 0;
4079 } else {
4080 uint8_t mixed = 0;
4081 if (conn->socks_request->port != circ->dest_port)
4082 mixed |= ISO_DESTPORT;
4083 if (strcasecmp(conn->original_dest_address, circ->dest_address))
4084 mixed |= ISO_DESTADDR;
4085 if (!memeq_opt(sr->username, sr->usernamelen,
4086 circ->socks_username, circ->socks_username_len) ||
4087 !memeq_opt(sr->password, sr->passwordlen,
4088 circ->socks_password, circ->socks_password_len))
4089 mixed |= ISO_SOCKSAUTH;
4090 if ((conn->socks_request->listener_type != circ->client_proto_type ||
4091 conn->socks_request->socks_version != circ->client_proto_socksver))
4092 mixed |= ISO_CLIENTPROTO;
4093 if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4094 mixed |= ISO_CLIENTADDR;
4095 if (conn->entry_cfg.session_group != circ->session_group)
4096 mixed |= ISO_SESSIONGRP;
4097 if (conn->nym_epoch != circ->nym_epoch)
4098 mixed |= ISO_NYM_EPOCH;
4100 if (dry_run)
4101 return mixed;
4103 if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
4104 log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
4105 "isolation flags.");
4107 circ->isolation_flags_mixed |= mixed;
4108 return 0;
4113 * Clear the isolation settings on <b>circ</b>.
4115 * This only works on an open circuit that has never had a stream attached to
4116 * it, and whose isolation settings are hypothetical. (We set hypothetical
4117 * isolation settings on circuits as we're launching them, so that we
4118 * know whether they can handle more streams or whether we need to launch
4119 * even more circuits. Once the circuit is open, if it turns out that
4120 * we no longer have any streams to attach to it, we clear the isolation flags
4121 * and data so that other streams can have a chance.)
4123 void
4124 circuit_clear_isolation(origin_circuit_t *circ)
4126 if (circ->isolation_any_streams_attached) {
4127 log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
4128 return;
4130 if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
4131 log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
4132 "circuit");
4133 return;
4136 circ->isolation_values_set = 0;
4137 circ->isolation_flags_mixed = 0;
4138 circ->associated_isolated_stream_global_id = 0;
4139 circ->client_proto_type = 0;
4140 circ->client_proto_socksver = 0;
4141 circ->dest_port = 0;
4142 tor_addr_make_unspec(&circ->client_addr);
4143 tor_free(circ->dest_address);
4144 circ->session_group = -1;
4145 circ->nym_epoch = 0;
4146 if (circ->socks_username) {
4147 memwipe(circ->socks_username, 0x11, circ->socks_username_len);
4148 tor_free(circ->socks_username);
4150 if (circ->socks_password) {
4151 memwipe(circ->socks_password, 0x05, circ->socks_password_len);
4152 tor_free(circ->socks_password);
4154 circ->socks_username_len = circ->socks_password_len = 0;
4157 /** Free all storage held in module-scoped variables for connection_edge.c */
4158 void
4159 connection_edge_free_all(void)
4161 untried_pending_connections = 0;
4162 smartlist_free(pending_entry_connections);
4163 pending_entry_connections = NULL;