Merge remote-tracking branch 'karsten/task-18460-2' into maint-0.2.8
[tor.git] / src / or / connection_edge.c
blob754e9762ea169ded2a4e84c72a024a414dc35505
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-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_edge.c
9 * \brief Handle edge streams.
10 **/
11 #define CONNECTION_EDGE_PRIVATE
13 #include "or.h"
15 #include "backtrace.h"
17 #include "addressmap.h"
18 #include "buffers.h"
19 #include "channel.h"
20 #include "circpathbias.h"
21 #include "circuitlist.h"
22 #include "circuituse.h"
23 #include "config.h"
24 #include "connection.h"
25 #include "connection_edge.h"
26 #include "connection_or.h"
27 #include "control.h"
28 #include "dns.h"
29 #include "dnsserv.h"
30 #include "dirserv.h"
31 #include "hibernate.h"
32 #include "main.h"
33 #include "nodelist.h"
34 #include "policies.h"
35 #include "reasons.h"
36 #include "relay.h"
37 #include "rendclient.h"
38 #include "rendcommon.h"
39 #include "rendservice.h"
40 #include "rephist.h"
41 #include "router.h"
42 #include "routerlist.h"
43 #include "routerset.h"
44 #include "circuitbuild.h"
46 #ifdef HAVE_LINUX_TYPES_H
47 #include <linux/types.h>
48 #endif
49 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
50 #include <linux/netfilter_ipv4.h>
51 #define TRANS_NETFILTER
52 #define TRANS_NETFILTER_IPV4
53 #endif
55 #ifdef HAVE_LINUX_IF_H
56 #include <linux/if.h>
57 #endif
59 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
60 #include <linux/netfilter_ipv6/ip6_tables.h>
61 #if defined(IP6T_SO_ORIGINAL_DST)
62 #define TRANS_NETFILTER
63 #define TRANS_NETFILTER_IPV6
64 #endif
65 #endif
67 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
68 #include <net/if.h>
69 #include <net/pfvar.h>
70 #define TRANS_PF
71 #endif
73 #ifdef IP_TRANSPARENT
74 #define TRANS_TPROXY
75 #endif
77 #define SOCKS4_GRANTED 90
78 #define SOCKS4_REJECT 91
80 static int connection_ap_handshake_process_socks(entry_connection_t *conn);
81 static int connection_ap_process_natd(entry_connection_t *conn);
82 static int connection_exit_connect_dir(edge_connection_t *exitconn);
83 static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
84 static int connection_ap_supports_optimistic_data(const entry_connection_t *);
86 /** An AP stream has failed/finished. If it hasn't already sent back
87 * a socks reply, send one now (based on endreason). Also set
88 * has_sent_end to 1, and mark the conn.
90 MOCK_IMPL(void,
91 connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
92 int line, const char *file))
94 connection_t *base_conn = ENTRY_TO_CONN(conn);
95 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
96 tor_assert(base_conn->type == CONN_TYPE_AP);
97 ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
99 /* If this is a rendezvous stream and it is failing without ever
100 * being attached to a circuit, assume that an attempt to connect to
101 * the destination hidden service has just ended.
103 * XXXX This condition doesn't limit to only streams failing
104 * without ever being attached. That sloppiness should be harmless,
105 * but we should fix it someday anyway. */
106 if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
107 connection_edge_is_rendezvous_stream(edge_conn)) {
108 rend_client_note_connection_attempt_ended(edge_conn->rend_data);
111 if (base_conn->marked_for_close) {
112 /* This call will warn as appropriate. */
113 connection_mark_for_close_(base_conn, line, file);
114 return;
117 if (!conn->socks_request->has_finished) {
118 if (endreason & END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED)
119 log_warn(LD_BUG,
120 "stream (marked at %s:%d) sending two socks replies?",
121 file, line);
123 if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
124 connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
125 else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
126 connection_ap_handshake_socks_resolved(conn,
127 RESOLVED_TYPE_ERROR_TRANSIENT,
128 0, NULL, -1, -1);
129 else /* unknown or no handshake at all. send no response. */
130 conn->socks_request->has_finished = 1;
133 connection_mark_and_flush_(base_conn, line, file);
135 ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
138 /** There was an EOF. Send an end and mark the connection for close.
141 connection_edge_reached_eof(edge_connection_t *conn)
143 if (connection_get_inbuf_len(TO_CONN(conn)) &&
144 connection_state_is_open(TO_CONN(conn))) {
145 /* it still has stuff to process. don't let it die yet. */
146 return 0;
148 log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
149 conn->base_.s);
150 if (!conn->base_.marked_for_close) {
151 /* only mark it if not already marked. it's possible to
152 * get the 'end' right around when the client hangs up on us. */
153 connection_edge_end(conn, END_STREAM_REASON_DONE);
154 if (conn->base_.type == CONN_TYPE_AP) {
155 /* eof, so don't send a socks reply back */
156 if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
157 EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
159 connection_mark_for_close(TO_CONN(conn));
161 return 0;
164 /** Handle new bytes on conn->inbuf based on state:
165 * - If it's waiting for socks info, try to read another step of the
166 * socks handshake out of conn->inbuf.
167 * - If it's waiting for the original destination, fetch it.
168 * - If it's open, then package more relay cells from the stream.
169 * - Else, leave the bytes on inbuf alone for now.
171 * Mark and return -1 if there was an unexpected error with the conn,
172 * else return 0.
175 connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
177 tor_assert(conn);
179 switch (conn->base_.state) {
180 case AP_CONN_STATE_SOCKS_WAIT:
181 if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
182 /* already marked */
183 return -1;
185 return 0;
186 case AP_CONN_STATE_NATD_WAIT:
187 if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
188 /* already marked */
189 return -1;
191 return 0;
192 case AP_CONN_STATE_OPEN:
193 case EXIT_CONN_STATE_OPEN:
194 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
195 /* (We already sent an end cell if possible) */
196 connection_mark_for_close(TO_CONN(conn));
197 return -1;
199 return 0;
200 case AP_CONN_STATE_CONNECT_WAIT:
201 if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
202 log_info(LD_EDGE,
203 "data from edge while in '%s' state. Sending it anyway. "
204 "package_partial=%d, buflen=%ld",
205 conn_state_to_string(conn->base_.type, conn->base_.state),
206 package_partial,
207 (long)connection_get_inbuf_len(TO_CONN(conn)));
208 if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
209 /* (We already sent an end cell if possible) */
210 connection_mark_for_close(TO_CONN(conn));
211 return -1;
213 return 0;
215 /* Fall through if the connection is on a circuit without optimistic
216 * data support. */
217 case EXIT_CONN_STATE_CONNECTING:
218 case AP_CONN_STATE_RENDDESC_WAIT:
219 case AP_CONN_STATE_CIRCUIT_WAIT:
220 case AP_CONN_STATE_RESOLVE_WAIT:
221 case AP_CONN_STATE_CONTROLLER_WAIT:
222 log_info(LD_EDGE,
223 "data from edge while in '%s' state. Leaving it on buffer.",
224 conn_state_to_string(conn->base_.type, conn->base_.state));
225 return 0;
227 log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
228 tor_fragile_assert();
229 connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
230 connection_mark_for_close(TO_CONN(conn));
231 return -1;
234 /** This edge needs to be closed, because its circuit has closed.
235 * Mark it for close and return 0.
238 connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
240 if (!conn->base_.marked_for_close) {
241 log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
242 (unsigned) circ_id);
243 if (conn->base_.type == CONN_TYPE_AP) {
244 entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
245 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
246 control_event_stream_bandwidth(conn);
247 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
248 END_STREAM_REASON_DESTROY);
249 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
250 } else {
251 /* closing the circuit, nothing to send an END to */
252 conn->edge_has_sent_end = 1;
253 conn->end_reason = END_STREAM_REASON_DESTROY;
254 conn->end_reason |= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED;
255 connection_mark_and_flush(TO_CONN(conn));
258 conn->cpath_layer = NULL;
259 conn->on_circuit = NULL;
260 return 0;
263 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
264 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
265 * is not a client connection, set the relay end cell's reason for closing
266 * as <b>reason</b> */
267 static int
268 relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ,
269 uint8_t reason, crypt_path_t *cpath_layer)
271 char payload[1];
273 if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
274 /* Never send the server an informative reason code; it doesn't need to
275 * know why the client stream is failing. */
276 reason = END_STREAM_REASON_MISC;
279 payload[0] = (char) reason;
281 return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
282 payload, 1, cpath_layer);
285 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
286 * remember that we've done so. If this is not a client connection, set the
287 * relay end cell's reason for closing as <b>reason</b>.
289 * Return -1 if this function has already been called on this conn,
290 * else return 0.
293 connection_edge_end(edge_connection_t *conn, uint8_t reason)
295 char payload[RELAY_PAYLOAD_SIZE];
296 size_t payload_len=1;
297 circuit_t *circ;
298 uint8_t control_reason = reason;
300 if (conn->edge_has_sent_end) {
301 log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
302 "on an already ended stream?", reason);
303 tor_fragile_assert();
304 return -1;
307 if (conn->base_.marked_for_close) {
308 log_warn(LD_BUG,
309 "called on conn that's already marked for close at %s:%d.",
310 conn->base_.marked_for_close_file, conn->base_.marked_for_close);
311 return 0;
314 circ = circuit_get_by_edge_conn(conn);
315 if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
316 /* If this is a client circuit, don't send the server an informative
317 * reason code; it doesn't need to know why the client stream is
318 * failing. */
319 reason = END_STREAM_REASON_MISC;
322 payload[0] = (char)reason;
323 if (reason == END_STREAM_REASON_EXITPOLICY &&
324 !connection_edge_is_rendezvous_stream(conn)) {
325 int addrlen;
326 if (tor_addr_family(&conn->base_.addr) == AF_INET) {
327 set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
328 addrlen = 4;
329 } else {
330 memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
331 addrlen = 16;
333 set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
334 payload_len += 4+addrlen;
337 if (circ && !circ->marked_for_close) {
338 log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
339 conn->base_.s);
340 connection_edge_send_command(conn, RELAY_COMMAND_END,
341 payload, payload_len);
342 } else {
343 log_debug(LD_EDGE,"No circ to send end on conn "
344 "(fd "TOR_SOCKET_T_FORMAT").",
345 conn->base_.s);
348 conn->edge_has_sent_end = 1;
349 conn->end_reason = control_reason;
350 return 0;
353 /** An error has just occurred on an operation on an edge connection
354 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
355 * appropriate relay end cell to the other end of the connection's circuit.
358 connection_edge_end_errno(edge_connection_t *conn)
360 uint8_t reason;
361 tor_assert(conn);
362 reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
363 return connection_edge_end(conn, reason);
366 /** We just wrote some data to <b>conn</b>; act appropriately.
368 * (That is, if it's open, consider sending a stream-level sendme cell if we
369 * have just flushed enough.)
372 connection_edge_flushed_some(edge_connection_t *conn)
374 switch (conn->base_.state) {
375 case AP_CONN_STATE_OPEN:
376 case EXIT_CONN_STATE_OPEN:
377 connection_edge_consider_sending_sendme(conn);
378 break;
380 return 0;
383 /** Connection <b>conn</b> has finished writing and has no bytes left on
384 * its outbuf.
386 * If it's in state 'open', stop writing, consider responding with a
387 * sendme, and return.
388 * Otherwise, stop writing and return.
390 * If <b>conn</b> is broken, mark it for close and return -1, else
391 * return 0.
394 connection_edge_finished_flushing(edge_connection_t *conn)
396 tor_assert(conn);
398 switch (conn->base_.state) {
399 case AP_CONN_STATE_OPEN:
400 case EXIT_CONN_STATE_OPEN:
401 connection_edge_consider_sending_sendme(conn);
402 return 0;
403 case AP_CONN_STATE_SOCKS_WAIT:
404 case AP_CONN_STATE_NATD_WAIT:
405 case AP_CONN_STATE_RENDDESC_WAIT:
406 case AP_CONN_STATE_CIRCUIT_WAIT:
407 case AP_CONN_STATE_CONNECT_WAIT:
408 case AP_CONN_STATE_CONTROLLER_WAIT:
409 case AP_CONN_STATE_RESOLVE_WAIT:
410 return 0;
411 default:
412 log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
413 tor_fragile_assert();
414 return -1;
416 return 0;
419 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
420 * able to generate. */
421 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
422 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
424 /** Set the buffer at <b>payload_out</b> -- which must have at least
425 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
426 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
427 * that the name resolution that led us to <b>addr</b> will be valid for
428 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
429 * success. */
430 STATIC int
431 connected_cell_format_payload(uint8_t *payload_out,
432 const tor_addr_t *addr,
433 uint32_t ttl)
435 const sa_family_t family = tor_addr_family(addr);
436 int connected_payload_len;
438 /* should be needless */
439 memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
441 if (family == AF_INET) {
442 set_uint32(payload_out, tor_addr_to_ipv4n(addr));
443 connected_payload_len = 4;
444 } else if (family == AF_INET6) {
445 set_uint32(payload_out, 0);
446 set_uint8(payload_out + 4, 6);
447 memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
448 connected_payload_len = 21;
449 } else {
450 return -1;
453 set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
454 connected_payload_len += 4;
456 tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
458 return connected_payload_len;
461 /** Connected handler for exit connections: start writing pending
462 * data, deliver 'CONNECTED' relay cells as appropriate, and check
463 * any pending data that may have been received. */
465 connection_edge_finished_connecting(edge_connection_t *edge_conn)
467 connection_t *conn;
469 tor_assert(edge_conn);
470 tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
471 conn = TO_CONN(edge_conn);
472 tor_assert(conn->state == EXIT_CONN_STATE_CONNECTING);
474 log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
475 escaped_safe_str(conn->address), conn->port,
476 safe_str(fmt_and_decorate_addr(&conn->addr)));
478 rep_hist_note_exit_stream_opened(conn->port);
480 conn->state = EXIT_CONN_STATE_OPEN;
481 IF_HAS_NO_BUFFEREVENT(conn)
482 connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
483 if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
484 * cells */
485 connection_start_writing(conn);
486 /* deliver a 'connected' relay cell back through the circuit. */
487 if (connection_edge_is_rendezvous_stream(edge_conn)) {
488 if (connection_edge_send_command(edge_conn,
489 RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
490 return 0; /* circuit is closed, don't continue */
491 } else {
492 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
493 int connected_payload_len =
494 connected_cell_format_payload(connected_payload, &conn->addr,
495 edge_conn->address_ttl);
496 if (connected_payload_len < 0)
497 return -1;
499 if (connection_edge_send_command(edge_conn,
500 RELAY_COMMAND_CONNECTED,
501 (char*)connected_payload, connected_payload_len) < 0)
502 return 0; /* circuit is closed, don't continue */
504 tor_assert(edge_conn->package_window > 0);
505 /* in case the server has written anything */
506 return connection_edge_process_inbuf(edge_conn, 1);
509 /** A list of all the entry_connection_t * objects that are not marked
510 * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
512 * (Right now, we check in several places to make sure that this list is
513 * correct. When it's incorrect, we'll fix it, and log a BUG message.)
515 static smartlist_t *pending_entry_connections = NULL;
517 static int untried_pending_connections = 0;
519 /** Common code to connection_(ap|exit)_about_to_close. */
520 static void
521 connection_edge_about_to_close(edge_connection_t *edge_conn)
523 if (!edge_conn->edge_has_sent_end) {
524 connection_t *conn = TO_CONN(edge_conn);
525 log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
526 "hasn't sent end yet?",
527 conn->marked_for_close_file, conn->marked_for_close);
528 tor_fragile_assert();
532 /** Called when we're about to finally unlink and free an AP (client)
533 * connection: perform necessary accounting and cleanup */
534 void
535 connection_ap_about_to_close(entry_connection_t *entry_conn)
537 circuit_t *circ;
538 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
539 connection_t *conn = ENTRY_TO_CONN(entry_conn);
541 connection_edge_about_to_close(edge_conn);
543 if (entry_conn->socks_request->has_finished == 0) {
544 /* since conn gets removed right after this function finishes,
545 * there's no point trying to send back a reply at this point. */
546 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
547 " back a socks reply.",
548 conn->marked_for_close_file, conn->marked_for_close);
550 if (!edge_conn->end_reason) {
551 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
552 " set end_reason.",
553 conn->marked_for_close_file, conn->marked_for_close);
555 if (entry_conn->dns_server_request) {
556 log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
557 " replied to DNS request.",
558 conn->marked_for_close_file, conn->marked_for_close);
559 dnsserv_reject_request(entry_conn);
562 if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
563 smartlist_remove(pending_entry_connections, entry_conn);
566 #if 1
567 /* Check to make sure that this isn't in pending_entry_connections if it
568 * didn't actually belong there. */
569 if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
570 connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
571 "about_to_close");
573 #endif
575 control_event_stream_bandwidth(edge_conn);
576 control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
577 edge_conn->end_reason);
578 circ = circuit_get_by_edge_conn(edge_conn);
579 if (circ)
580 circuit_detach_stream(circ, edge_conn);
583 /** Called when we're about to finally unlink and free an exit
584 * connection: perform necessary accounting and cleanup */
585 void
586 connection_exit_about_to_close(edge_connection_t *edge_conn)
588 circuit_t *circ;
589 connection_t *conn = TO_CONN(edge_conn);
591 connection_edge_about_to_close(edge_conn);
593 circ = circuit_get_by_edge_conn(edge_conn);
594 if (circ)
595 circuit_detach_stream(circ, edge_conn);
596 if (conn->state == EXIT_CONN_STATE_RESOLVING) {
597 connection_dns_remove(edge_conn);
601 /** Define a schedule for how long to wait between retrying
602 * application connections. Rather than waiting a fixed amount of
603 * time between each retry, we wait 10 seconds each for the first
604 * two tries, and 15 seconds for each retry after
605 * that. Hopefully this will improve the expected user experience. */
606 static int
607 compute_retry_timeout(entry_connection_t *conn)
609 int timeout = get_options()->CircuitStreamTimeout;
610 if (timeout) /* if our config options override the default, use them */
611 return timeout;
612 if (conn->num_socks_retries < 2) /* try 0 and try 1 */
613 return 10;
614 return 15;
617 /** Find all general-purpose AP streams waiting for a response that sent their
618 * begin/resolve cell too long ago. Detach from their current circuit, and
619 * mark their current circuit as unsuitable for new streams. Then call
620 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
621 * available) or launch a new one.
623 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
624 * retry attempt).
626 void
627 connection_ap_expire_beginning(void)
629 edge_connection_t *conn;
630 entry_connection_t *entry_conn;
631 circuit_t *circ;
632 time_t now = time(NULL);
633 const or_options_t *options = get_options();
634 int severity;
635 int cutoff;
636 int seconds_idle, seconds_since_born;
637 smartlist_t *conns = get_connection_array();
639 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
640 if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
641 continue;
642 entry_conn = TO_ENTRY_CONN(base_conn);
643 conn = ENTRY_TO_EDGE_CONN(entry_conn);
644 /* if it's an internal linked connection, don't yell its status. */
645 severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
646 ? LOG_INFO : LOG_NOTICE;
647 seconds_idle = (int)( now - base_conn->timestamp_lastread );
648 seconds_since_born = (int)( now - base_conn->timestamp_created );
650 if (base_conn->state == AP_CONN_STATE_OPEN)
651 continue;
653 /* We already consider SocksTimeout in
654 * connection_ap_handshake_attach_circuit(), but we need to consider
655 * it here too because controllers that put streams in controller_wait
656 * state never ask Tor to attach the circuit. */
657 if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
658 if (seconds_since_born >= options->SocksTimeout) {
659 log_fn(severity, LD_APP,
660 "Tried for %d seconds to get a connection to %s:%d. "
661 "Giving up. (%s)",
662 seconds_since_born,
663 safe_str_client(entry_conn->socks_request->address),
664 entry_conn->socks_request->port,
665 conn_state_to_string(CONN_TYPE_AP, base_conn->state));
666 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
668 continue;
671 /* We're in state connect_wait or resolve_wait now -- waiting for a
672 * reply to our relay cell. See if we want to retry/give up. */
674 cutoff = compute_retry_timeout(entry_conn);
675 if (seconds_idle < cutoff)
676 continue;
677 circ = circuit_get_by_edge_conn(conn);
678 if (!circ) { /* it's vanished? */
679 log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
680 safe_str_client(entry_conn->socks_request->address));
681 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
682 continue;
684 if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
685 if (seconds_idle >= options->SocksTimeout) {
686 log_fn(severity, LD_REND,
687 "Rend stream is %d seconds late. Giving up on address"
688 " '%s.onion'.",
689 seconds_idle,
690 safe_str_client(entry_conn->socks_request->address));
691 /* Roll back path bias use state so that we probe the circuit
692 * if nothing else succeeds on it */
693 pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ));
695 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
696 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
698 continue;
700 if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
701 circ->purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT &&
702 circ->purpose != CIRCUIT_PURPOSE_PATH_BIAS_TESTING) {
703 log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
704 "The purpose on the circuit was %s; it was in state %s, "
705 "path_state %s.",
706 circuit_purpose_to_string(circ->purpose),
707 circuit_state_to_string(circ->state),
708 CIRCUIT_IS_ORIGIN(circ) ?
709 pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
710 "none");
712 log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
713 "We tried for %d seconds to connect to '%s' using exit %s."
714 " Retrying on a new circuit.",
715 seconds_idle,
716 safe_str_client(entry_conn->socks_request->address),
717 conn->cpath_layer ?
718 extend_info_describe(conn->cpath_layer->extend_info):
719 "*unnamed*");
720 /* send an end down the circuit */
721 connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
722 /* un-mark it as ending, since we're going to reuse it */
723 conn->edge_has_sent_end = 0;
724 conn->end_reason = 0;
725 /* make us not try this circuit again, but allow
726 * current streams on it to survive if they can */
727 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ));
729 /* give our stream another 'cutoff' seconds to try */
730 conn->base_.timestamp_lastread += cutoff;
731 if (entry_conn->num_socks_retries < 250) /* avoid overflow */
732 entry_conn->num_socks_retries++;
733 /* move it back into 'pending' state, and try to attach. */
734 if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
735 END_STREAM_REASON_TIMEOUT)<0) {
736 if (!base_conn->marked_for_close)
737 connection_mark_unattached_ap(entry_conn,
738 END_STREAM_REASON_CANT_ATTACH);
740 } SMARTLIST_FOREACH_END(base_conn);
744 * As connection_ap_attach_pending, but first scans the entire connection
745 * array to see if any elements are missing.
747 void
748 connection_ap_rescan_and_attach_pending(void)
750 entry_connection_t *entry_conn;
751 smartlist_t *conns = get_connection_array();
753 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
754 pending_entry_connections = smartlist_new();
756 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
757 if (conn->marked_for_close ||
758 conn->type != CONN_TYPE_AP ||
759 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
760 continue;
762 entry_conn = TO_ENTRY_CONN(conn);
763 tor_assert(entry_conn);
764 if (! smartlist_contains(pending_entry_connections, entry_conn)) {
765 log_warn(LD_BUG, "Found a connection %p that was supposed to be "
766 "in pending_entry_connections, but wasn't. No worries; "
767 "adding it.",
768 pending_entry_connections);
769 untried_pending_connections = 1;
770 connection_ap_mark_as_pending_circuit(entry_conn);
773 } SMARTLIST_FOREACH_END(conn);
775 connection_ap_attach_pending(1);
778 #ifdef DEBUGGING_17659
779 #define UNMARK() do { \
780 entry_conn->marked_pending_circ_line = 0; \
781 entry_conn->marked_pending_circ_file = 0; \
782 } while (0)
783 #else
784 #define UNMARK() do { } while (0)
785 #endif
787 /** Tell any AP streams that are listed as waiting for a new circuit to try
788 * again, either attaching to an available circ or launching a new one.
790 * If <b>retry</b> is false, only check the list if it contains at least one
791 * streams that we have not yet tried to attach to a circuit.
793 void
794 connection_ap_attach_pending(int retry)
796 if (PREDICT_UNLIKELY(!pending_entry_connections)) {
797 return;
800 if (untried_pending_connections == 0 && !retry)
801 return;
803 /* Don't allow modifications to pending_entry_connections while we are
804 * iterating over it. */
805 smartlist_t *pending = pending_entry_connections;
806 pending_entry_connections = smartlist_new();
808 SMARTLIST_FOREACH_BEGIN(pending,
809 entry_connection_t *, entry_conn) {
810 connection_t *conn = ENTRY_TO_CONN(entry_conn);
811 tor_assert(conn && entry_conn);
812 if (conn->marked_for_close) {
813 UNMARK();
814 continue;
816 if (conn->magic != ENTRY_CONNECTION_MAGIC) {
817 log_warn(LD_BUG, "%p has impossible magic value %u.",
818 entry_conn, (unsigned)conn->magic);
819 UNMARK();
820 continue;
822 if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
823 log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
824 "is %s. Why is it on pending_entry_connections?",
825 entry_conn,
826 conn_state_to_string(conn->type, conn->state));
827 UNMARK();
828 continue;
831 if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
832 if (!conn->marked_for_close)
833 connection_mark_unattached_ap(entry_conn,
834 END_STREAM_REASON_CANT_ATTACH);
837 if (! conn->marked_for_close &&
838 conn->type == CONN_TYPE_AP &&
839 conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
840 if (!smartlist_contains(pending_entry_connections, entry_conn)) {
841 smartlist_add(pending_entry_connections, entry_conn);
842 continue;
846 UNMARK();
847 } SMARTLIST_FOREACH_END(entry_conn);
849 smartlist_free(pending);
850 untried_pending_connections = 0;
853 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
855 * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
856 * should not already be pending a circuit. The circuit will get
857 * launched or the connection will get attached the next time we
858 * call connection_ap_attach_pending().
860 void
861 connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn,
862 const char *fname, int lineno)
864 connection_t *conn = ENTRY_TO_CONN(entry_conn);
865 tor_assert(conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
866 tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
867 if (conn->marked_for_close)
868 return;
870 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
871 pending_entry_connections = smartlist_new();
873 if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
874 entry_conn))) {
875 log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
876 "(Called from %s:%d.)",
877 entry_conn, fname, lineno);
878 #ifdef DEBUGGING_17659
879 const char *f2 = entry_conn->marked_pending_circ_file;
880 log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
881 f2 ? f2 : "<NULL>",
882 entry_conn->marked_pending_circ_line);
883 #endif
884 log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
885 return;
888 #ifdef DEBUGGING_17659
889 entry_conn->marked_pending_circ_line = (uint16_t) lineno;
890 entry_conn->marked_pending_circ_file = fname;
891 #endif
893 untried_pending_connections = 1;
894 smartlist_add(pending_entry_connections, entry_conn);
897 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
898 void
899 connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
901 if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
902 return;
903 UNMARK();
904 smartlist_remove(pending_entry_connections, entry_conn);
907 /* DOCDOC */
908 void
909 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
910 const char *where)
912 if (pending_entry_connections &&
913 smartlist_contains(pending_entry_connections, entry_conn)) {
914 log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
915 entry_conn, where);
916 connection_ap_mark_as_non_pending_circuit(entry_conn);
920 /** Tell any AP streams that are waiting for a one-hop tunnel to
921 * <b>failed_digest</b> that they are going to fail. */
922 /* XXX024 We should get rid of this function, and instead attach
923 * one-hop streams to circ->p_streams so they get marked in
924 * circuit_mark_for_close like normal p_streams. */
925 void
926 connection_ap_fail_onehop(const char *failed_digest,
927 cpath_build_state_t *build_state)
929 entry_connection_t *entry_conn;
930 char digest[DIGEST_LEN];
931 smartlist_t *conns = get_connection_array();
932 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
933 if (conn->marked_for_close ||
934 conn->type != CONN_TYPE_AP ||
935 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
936 continue;
937 entry_conn = TO_ENTRY_CONN(conn);
938 if (!entry_conn->want_onehop)
939 continue;
940 if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
941 tor_memneq(digest, failed_digest, DIGEST_LEN))
942 continue;
943 if (tor_digest_is_zero(digest)) {
944 /* we don't know the digest; have to compare addr:port */
945 tor_addr_t addr;
946 if (!build_state || !build_state->chosen_exit ||
947 !entry_conn->socks_request) {
948 continue;
950 if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
951 !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
952 build_state->chosen_exit->port != entry_conn->socks_request->port)
953 continue;
955 log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
956 "just failed.", entry_conn->chosen_exit_name,
957 entry_conn->socks_request->address);
958 connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
959 } SMARTLIST_FOREACH_END(conn);
962 /** A circuit failed to finish on its last hop <b>info</b>. If there
963 * are any streams waiting with this exit node in mind, but they
964 * don't absolutely require it, make them give up on it.
966 void
967 circuit_discard_optional_exit_enclaves(extend_info_t *info)
969 entry_connection_t *entry_conn;
970 const node_t *r1, *r2;
972 smartlist_t *conns = get_connection_array();
973 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
974 if (conn->marked_for_close ||
975 conn->type != CONN_TYPE_AP ||
976 conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
977 continue;
978 entry_conn = TO_ENTRY_CONN(conn);
979 if (!entry_conn->chosen_exit_optional &&
980 !entry_conn->chosen_exit_retries)
981 continue;
982 r1 = node_get_by_nickname(entry_conn->chosen_exit_name, 0);
983 r2 = node_get_by_id(info->identity_digest);
984 if (!r1 || !r2 || r1 != r2)
985 continue;
986 tor_assert(entry_conn->socks_request);
987 if (entry_conn->chosen_exit_optional) {
988 log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
989 safe_str_client(entry_conn->chosen_exit_name),
990 escaped_safe_str_client(entry_conn->socks_request->address));
991 entry_conn->chosen_exit_optional = 0;
992 tor_free(entry_conn->chosen_exit_name); /* clears it */
993 /* if this port is dangerous, warn or reject it now that we don't
994 * think it'll be using an enclave. */
995 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
997 if (entry_conn->chosen_exit_retries) {
998 if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
999 clear_trackexithost_mappings(entry_conn->chosen_exit_name);
1000 tor_free(entry_conn->chosen_exit_name); /* clears it */
1001 /* if this port is dangerous, warn or reject it now that we don't
1002 * think it'll be using an enclave. */
1003 consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1006 } SMARTLIST_FOREACH_END(conn);
1009 /** The AP connection <b>conn</b> has just failed while attaching or
1010 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1011 * might work. Detach the circuit, and either reattach it, launch a
1012 * new circuit, tell the controller, or give up as appropriate.
1014 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1017 connection_ap_detach_retriable(entry_connection_t *conn,
1018 origin_circuit_t *circ,
1019 int reason)
1021 control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
1022 ENTRY_TO_CONN(conn)->timestamp_lastread = time(NULL);
1024 /* Roll back path bias use state so that we probe the circuit
1025 * if nothing else succeeds on it */
1026 pathbias_mark_use_rollback(circ);
1028 if (conn->pending_optimistic_data) {
1029 generic_buffer_set_to_copy(&conn->sending_optimistic_data,
1030 conn->pending_optimistic_data);
1033 if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
1034 /* If we're attaching streams ourself, or if this connection is
1035 * a tunneled directory connection, then just attach it. */
1036 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
1037 circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1038 connection_ap_mark_as_pending_circuit(conn);
1039 } else {
1040 CONNECTION_AP_EXPECT_NONPENDING(conn);
1041 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
1042 circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1044 return 0;
1047 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1048 * reject depending on our config options. */
1049 static int
1050 consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
1052 const or_options_t *options = get_options();
1053 int reject = smartlist_contains_int_as_string(
1054 options->RejectPlaintextPorts, port);
1056 if (smartlist_contains_int_as_string(options->WarnPlaintextPorts, port)) {
1057 log_warn(LD_APP, "Application request to port %d: this port is "
1058 "commonly used for unencrypted protocols. Please make sure "
1059 "you don't send anything you would mind the rest of the "
1060 "Internet reading!%s", port, reject ? " Closing." : "");
1061 control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1062 port, reject ? "REJECT" : "WARN");
1065 if (reject) {
1066 log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1067 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1068 return -1;
1071 return 0;
1074 /** How many times do we try connecting with an exit configured via
1075 * TrackHostExits before concluding that it won't work any more and trying a
1076 * different one? */
1077 #define TRACKHOSTEXITS_RETRIES 5
1079 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1080 * asked us to leave streams unattached. Return 0 in that case.
1082 * See connection_ap_handshake_rewrite_and_attach()'s
1083 * documentation for arguments and return value.
1086 connection_ap_rewrite_and_attach_if_allowed(entry_connection_t *conn,
1087 origin_circuit_t *circ,
1088 crypt_path_t *cpath)
1090 const or_options_t *options = get_options();
1092 if (options->LeaveStreamsUnattached) {
1093 CONNECTION_AP_EXPECT_NONPENDING(conn);
1094 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
1095 return 0;
1097 return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1100 /* Try to perform any map-based rewriting of the target address in
1101 * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1102 * conn->socks_request.address as appropriate.
1104 STATIC void
1105 connection_ap_handshake_rewrite(entry_connection_t *conn,
1106 rewrite_result_t *out)
1108 socks_request_t *socks = conn->socks_request;
1109 const or_options_t *options = get_options();
1110 tor_addr_t addr_tmp;
1112 /* Initialize all the fields of 'out' to reasonable defaults */
1113 out->automap = 0;
1114 out->exit_source = ADDRMAPSRC_NONE;
1115 out->map_expires = TIME_MAX;
1116 out->end_reason = 0;
1117 out->should_close = 0;
1118 out->orig_address[0] = 0;
1120 /* We convert all incoming addresses to lowercase. */
1121 tor_strlower(socks->address);
1122 /* Remember the original address. */
1123 strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
1124 log_debug(LD_APP,"Client asked for %s:%d",
1125 safe_str_client(socks->address),
1126 socks->port);
1128 /* Check for whether this is a .exit address. By default, those are
1129 * disallowed when they're coming straight from the client, but you're
1130 * allowed to have them in MapAddress commands and so forth. */
1131 if (!strcmpend(socks->address, ".exit") && !options->AllowDotExit) {
1132 log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
1133 "security risks. Set AllowDotExit in your torrc to enable "
1134 "it (at your own risk).");
1135 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1136 escaped(socks->address));
1137 out->end_reason = END_STREAM_REASON_TORPROTOCOL;
1138 out->should_close = 1;
1139 return;
1142 /* Remember the original address so we can tell the user about what
1143 * they actually said, not just what it turned into. */
1144 if (! conn->original_dest_address) {
1145 /* Is the 'if' necessary here? XXXX */
1146 conn->original_dest_address = tor_strdup(conn->socks_request->address);
1149 /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1150 * these only for non-reverse lookups, since they don't exist for those.
1151 * We need to do this before we consider automapping, since we might
1152 * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1153 * we'd need to automap it. */
1154 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
1155 const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
1156 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1157 rewrite_flags, &out->map_expires, &out->exit_source)) {
1158 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1159 REMAP_STREAM_SOURCE_CACHE);
1163 /* Now, handle automapping. Automapping happens when we're asked to
1164 * resolve a hostname, and AutomapHostsOnResolve is set, and
1165 * the hostname has a suffix listed in AutomapHostsSuffixes.
1167 if (socks->command == SOCKS_COMMAND_RESOLVE &&
1168 tor_addr_parse(&addr_tmp, socks->address)<0 &&
1169 options->AutomapHostsOnResolve) {
1170 /* Check the suffix... */
1171 out->automap = addressmap_address_should_automap(socks->address, options);
1172 if (out->automap) {
1173 /* If we get here, then we should apply an automapping for this. */
1174 const char *new_addr;
1175 /* We return an IPv4 address by default, or an IPv6 address if we
1176 * are allowed to do so. */
1177 int addr_type = RESOLVED_TYPE_IPV4;
1178 if (conn->socks_request->socks_version != 4) {
1179 if (!conn->entry_cfg.ipv4_traffic ||
1180 (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
1181 conn->entry_cfg.prefer_ipv6_virtaddr)
1182 addr_type = RESOLVED_TYPE_IPV6;
1184 /* Okay, register the target address as automapped, and find the new
1185 * address we're supposed to give as a resolve answer. (Return a cached
1186 * value if we've looked up this address before.
1188 new_addr = addressmap_register_virtual_address(
1189 addr_type, tor_strdup(socks->address));
1190 if (! new_addr) {
1191 log_warn(LD_APP, "Unable to automap address %s",
1192 escaped_safe_str(socks->address));
1193 out->end_reason = END_STREAM_REASON_INTERNAL;
1194 out->should_close = 1;
1195 return;
1197 log_info(LD_APP, "Automapping %s to %s",
1198 escaped_safe_str_client(socks->address),
1199 safe_str_client(new_addr));
1200 strlcpy(socks->address, new_addr, sizeof(socks->address));
1204 /* Now handle reverse lookups, if they're in the cache. This doesn't
1205 * happen too often, since client-side DNS caching is off by default. */
1206 if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1207 unsigned rewrite_flags = 0;
1208 if (conn->entry_cfg.use_cached_ipv4_answers)
1209 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1210 if (conn->entry_cfg.use_cached_ipv6_answers)
1211 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1213 if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1214 rewrite_flags, &out->map_expires)) {
1215 char *result = tor_strdup(socks->address);
1216 /* remember _what_ is supposed to have been resolved. */
1217 tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1218 out->orig_address);
1219 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1220 strlen(result), (uint8_t*)result,
1222 out->map_expires);
1223 tor_free(result);
1224 out->end_reason = END_STREAM_REASON_DONE |
1225 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
1226 out->should_close = 1;
1227 return;
1230 /* Hang on, did we find an answer saying that this is a reverse lookup for
1231 * an internal address? If so, we should reject it if we're condigured to
1232 * do so. */
1233 if (options->ClientDNSRejectInternalAddresses) {
1234 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1235 tor_addr_t addr;
1236 int ok;
1237 ok = tor_addr_parse_PTR_name(
1238 &addr, socks->address, AF_UNSPEC, 1);
1239 if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1240 connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1241 0, NULL, -1, TIME_MAX);
1242 out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
1243 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED;
1244 out->should_close = 1;
1245 return;
1250 /* If we didn't automap it before, then this is still the address
1251 * that came straight from the user, mapped according to any
1252 * MapAddress/MAPADDRESS commands. Now other mappings, including
1253 * previously registered Automap entries, TrackHostExits entries,
1254 * and client-side DNS cache entries (not recommended).
1256 if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
1257 !out->automap) {
1258 unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
1259 addressmap_entry_source_t exit_source2;
1260 if (conn->entry_cfg.use_cached_ipv4_answers)
1261 rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1262 if (conn->entry_cfg.use_cached_ipv6_answers)
1263 rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1264 if (addressmap_rewrite(socks->address, sizeof(socks->address),
1265 rewrite_flags, &out->map_expires, &exit_source2)) {
1266 control_event_stream_status(conn, STREAM_EVENT_REMAP,
1267 REMAP_STREAM_SOURCE_CACHE);
1269 if (out->exit_source == ADDRMAPSRC_NONE) {
1270 /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1271 * the original source of a .exit. */
1272 out->exit_source = exit_source2;
1276 /* Check to see whether we're about to use an address in the virtual
1277 * range without actually having gotten it from an Automap. */
1278 if (!out->automap && address_is_in_virtual_range(socks->address)) {
1279 /* This address was probably handed out by
1280 * client_dns_get_unmapped_address, but the mapping was discarded for some
1281 * reason. Or the user typed in a virtual address range manually. We
1282 * *don't* want to send the address through Tor; that's likely to fail,
1283 * and may leak information.
1285 log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1286 safe_str_client(socks->address));
1287 out->end_reason = END_STREAM_REASON_INTERNAL;
1288 out->should_close = 1;
1289 return;
1293 /** Connection <b>conn</b> just finished its socks handshake, or the
1294 * controller asked us to take care of it. If <b>circ</b> is defined,
1295 * then that's where we'll want to attach it. Otherwise we have to
1296 * figure it out ourselves.
1298 * First, parse whether it's a .exit address, remap it, and so on. Then
1299 * if it's for a general circuit, try to attach it to a circuit (or launch
1300 * one as needed), else if it's for a rendezvous circuit, fetch a
1301 * rendezvous descriptor first (or attach/launch a circuit if the
1302 * rendezvous descriptor is already here and fresh enough).
1304 * The stream will exit from the hop
1305 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1306 * <b>cpath</b> is NULL.
1309 connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn,
1310 origin_circuit_t *circ,
1311 crypt_path_t *cpath)
1313 socks_request_t *socks = conn->socks_request;
1314 const or_options_t *options = get_options();
1315 connection_t *base_conn = ENTRY_TO_CONN(conn);
1316 time_t now = time(NULL);
1317 rewrite_result_t rr;
1319 memset(&rr, 0, sizeof(rr));
1320 connection_ap_handshake_rewrite(conn,&rr);
1322 if (rr.should_close) {
1323 /* connection_ap_handshake_rewrite told us to close the connection,
1324 * either because it sent back an answer, or because it sent back an
1325 * error */
1326 connection_mark_unattached_ap(conn, rr.end_reason);
1327 if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
1328 return 0;
1329 else
1330 return -1;
1333 const time_t map_expires = rr.map_expires;
1334 const int automap = rr.automap;
1335 const addressmap_entry_source_t exit_source = rr.exit_source;
1337 /* Parse the address provided by SOCKS. Modify it in-place if it
1338 * specifies a hidden-service (.onion) or particular exit node (.exit).
1340 const hostname_type_t addresstype = parse_extended_hostname(socks->address);
1342 /* Now see whether the hostname is bogus. This could happen because of an
1343 * onion hostname whose format we don't recognize. */
1344 if (addresstype == BAD_HOSTNAME) {
1345 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1346 escaped(socks->address));
1347 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1348 return -1;
1351 /* If this is a .exit hostname, strip off the .name.exit part, and
1352 * see whether we're going to connect there, and otherwise handle it.
1353 * (The ".exit" part got stripped off by "parse_extended_hostname").
1355 * We'll set chosen_exit_name and/or close the connection as appropriate.
1357 if (addresstype == EXIT_HOSTNAME) {
1358 /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
1359 * not ExcludeExitNodes. */
1360 routerset_t *excludeset = options->StrictNodes ?
1361 options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
1362 const node_t *node = NULL;
1364 /* If this .exit was added by an AUTOMAP, then it came straight from
1365 * a user. Make sure that options->AllowDotExit permits that. */
1366 if (exit_source == ADDRMAPSRC_AUTOMAP && !options->AllowDotExit) {
1367 /* Whoops; this one is stale. It must have gotten added earlier,
1368 * when AllowDotExit was on. */
1369 log_warn(LD_APP,"Stale automapped address for '%s.exit', with "
1370 "AllowDotExit disabled. Refusing.",
1371 safe_str_client(socks->address));
1372 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1373 escaped(socks->address));
1374 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1375 return -1;
1378 /* Double-check to make sure there are no .exits coming from
1379 * impossible/weird sources. */
1380 if (exit_source == ADDRMAPSRC_DNS ||
1381 (exit_source == ADDRMAPSRC_NONE && !options->AllowDotExit)) {
1382 /* It shouldn't be possible to get a .exit address from any of these
1383 * sources. */
1384 log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
1385 ".exit part. Refusing.",
1386 safe_str_client(socks->address));
1387 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1388 escaped(socks->address));
1389 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1390 return -1;
1393 tor_assert(!automap);
1394 /* Now, find the character before the .(name) part. */
1395 char *s = strrchr(socks->address,'.');
1396 if (s) {
1397 /* The address was of the form "(stuff).(name).exit */
1398 if (s[1] != '\0') {
1399 /* Looks like a real .exit one. */
1400 conn->chosen_exit_name = tor_strdup(s+1);
1401 node = node_get_by_nickname(conn->chosen_exit_name, 1);
1403 if (exit_source == ADDRMAPSRC_TRACKEXIT) {
1404 /* We 5 tries before it expires the addressmap */
1405 conn->chosen_exit_retries = TRACKHOSTEXITS_RETRIES;
1407 *s = 0;
1408 } else {
1409 /* Oops, the address was (stuff)..exit. That's not okay. */
1410 log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
1411 safe_str_client(socks->address));
1412 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1413 escaped(socks->address));
1414 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1415 return -1;
1417 } else {
1418 /* It looks like they just asked for "foo.exit". That's a special
1419 * form that means (foo's address).foo.exit. */
1421 conn->chosen_exit_name = tor_strdup(socks->address);
1422 node = node_get_by_nickname(conn->chosen_exit_name, 1);
1423 if (node) {
1424 *socks->address = 0;
1425 node_get_address_string(node, socks->address, sizeof(socks->address));
1429 /* Now make sure that the chosen exit exists... */
1430 if (!node) {
1431 log_warn(LD_APP,
1432 "Unrecognized relay in exit address '%s.exit'. Refusing.",
1433 safe_str_client(socks->address));
1434 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1435 return -1;
1437 /* ...and make sure that it isn't excluded. */
1438 if (routerset_contains_node(excludeset, node)) {
1439 log_warn(LD_APP,
1440 "Excluded relay in exit address '%s.exit'. Refusing.",
1441 safe_str_client(socks->address));
1442 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1443 return -1;
1445 /* XXXX024-1090 Should we also allow foo.bar.exit if ExitNodes is set and
1446 Bar is not listed in it? I say yes, but our revised manpage branch
1447 implies no. */
1450 /* Now, handle everything that isn't a .onion address. */
1451 if (addresstype != ONION_HOSTNAME) {
1452 /* Not a hidden-service request. It's either a hostname or an IP,
1453 * possibly with a .exit that we stripped off. */
1455 /* Check for funny characters in the address. */
1456 if (address_is_invalid_destination(socks->address, 1)) {
1457 control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1458 escaped(socks->address));
1459 log_warn(LD_APP,
1460 "Destination '%s' seems to be an invalid hostname. Failing.",
1461 safe_str_client(socks->address));
1462 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1463 return -1;
1466 #ifdef ENABLE_TOR2WEB_MODE
1467 /* If we're running in Tor2webMode, we don't allow anything BUT .onion
1468 * addresses. */
1469 if (options->Tor2webMode) {
1470 log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname %s "
1471 "because tor2web mode is enabled.",
1472 safe_str_client(socks->address));
1473 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1474 return -1;
1476 #endif
1478 /* See if this is a hostname lookup that we can answer immediately.
1479 * (For example, an attempt to look up the IP address for an IP address.)
1481 if (socks->command == SOCKS_COMMAND_RESOLVE) {
1482 tor_addr_t answer;
1483 /* Reply to resolves immediately if we can. */
1484 if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
1485 /* remember _what_ is supposed to have been resolved. */
1486 strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
1487 connection_ap_handshake_socks_resolved_addr(conn, &answer, -1,
1488 map_expires);
1489 connection_mark_unattached_ap(conn,
1490 END_STREAM_REASON_DONE |
1491 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1492 return 0;
1494 tor_assert(!automap);
1495 rep_hist_note_used_resolve(now); /* help predict this next time */
1496 } else if (socks->command == SOCKS_COMMAND_CONNECT) {
1497 /* Special handling for attempts to connect */
1498 tor_assert(!automap);
1499 /* Don't allow connections to port 0. */
1500 if (socks->port == 0) {
1501 log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
1502 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1503 return -1;
1505 /* You can't make connections to internal addresses, by default.
1506 * Exceptions are begindir requests (where the address is meaningless,
1507 * or cases where you've hand-configured a particular exit, thereby
1508 * making the local address meaningful. */
1509 if (options->ClientRejectInternalAddresses &&
1510 !conn->use_begindir && !conn->chosen_exit_name && !circ) {
1511 /* If we reach this point then we don't want to allow internal
1512 * addresses. Check if we got one. */
1513 tor_addr_t addr;
1514 if (tor_addr_hostname_is_local(socks->address) ||
1515 (tor_addr_parse(&addr, socks->address) >= 0 &&
1516 tor_addr_is_internal(&addr, 0))) {
1517 /* If this is an explicit private address with no chosen exit node,
1518 * then we really don't want to try to connect to it. That's
1519 * probably an error. */
1520 if (conn->is_transparent_ap) {
1521 #define WARN_INTRVL_LOOP 300
1522 static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
1523 char *m;
1524 if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
1525 log_warn(LD_NET,
1526 "Rejecting request for anonymous connection to private "
1527 "address %s on a TransPort or NATDPort. Possible loop "
1528 "in your NAT rules?%s", safe_str_client(socks->address),
1530 tor_free(m);
1532 } else {
1533 #define WARN_INTRVL_PRIV 300
1534 static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
1535 char *m;
1536 if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
1537 log_warn(LD_NET,
1538 "Rejecting SOCKS request for anonymous connection to "
1539 "private address %s.%s",
1540 safe_str_client(socks->address),m);
1541 tor_free(m);
1544 connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
1545 return -1;
1547 } /* end "if we should check for internal addresses" */
1549 /* Okay. We're still doing a CONNECT, and it wasn't a private
1550 * address. Do special handling for literal IP addresses */
1552 tor_addr_t addr;
1553 /* XXX Duplicate call to tor_addr_parse. */
1554 if (tor_addr_parse(&addr, socks->address) >= 0) {
1555 /* If we reach this point, it's an IPv4 or an IPv6 address. */
1556 sa_family_t family = tor_addr_family(&addr);
1558 if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
1559 (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
1560 /* You can't do an IPv4 address on a v6-only socks listener,
1561 * or vice versa. */
1562 log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
1563 "family that this listener does not support.");
1564 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1565 return -1;
1566 } else if (family == AF_INET6 && socks->socks_version == 4) {
1567 /* You can't make a socks4 request to an IPv6 address. Socks4
1568 * doesn't support that. */
1569 log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
1570 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1571 return -1;
1572 } else if (socks->socks_version == 4 &&
1573 !conn->entry_cfg.ipv4_traffic) {
1574 /* You can't do any kind of Socks4 request when IPv4 is forbidden.
1576 * XXX raise this check outside the enclosing block? */
1577 log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
1578 "no IPv4 traffic supported.");
1579 connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1580 return -1;
1581 } else if (family == AF_INET6) {
1582 /* Tell the exit: we won't accept any ipv4 connection to an IPv6
1583 * address. */
1584 conn->entry_cfg.ipv4_traffic = 0;
1585 } else if (family == AF_INET) {
1586 /* Tell the exit: we won't accept any ipv6 connection to an IPv4
1587 * address. */
1588 conn->entry_cfg.ipv6_traffic = 0;
1593 if (socks->socks_version == 4)
1594 conn->entry_cfg.ipv6_traffic = 0;
1596 /* Still handling CONNECT. Now, check for exit enclaves. (Which we
1597 * don't do on BEGINDIR, or there is a chosen exit.)
1599 if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
1600 /* see if we can find a suitable enclave exit */
1601 const node_t *r =
1602 router_find_exact_exit_enclave(socks->address, socks->port);
1603 if (r) {
1604 log_info(LD_APP,
1605 "Redirecting address %s to exit at enclave router %s",
1606 safe_str_client(socks->address), node_describe(r));
1607 /* use the hex digest, not nickname, in case there are two
1608 routers with this nickname */
1609 conn->chosen_exit_name =
1610 tor_strdup(hex_str(r->identity, DIGEST_LEN));
1611 conn->chosen_exit_optional = 1;
1615 /* Still handling CONNECT: warn or reject if it's using a dangerous
1616 * port. */
1617 if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
1618 if (consider_plaintext_ports(conn, socks->port) < 0)
1619 return -1;
1621 /* Remember the port so that we do predicted requests there. */
1622 if (!conn->use_begindir) {
1623 /* help predict this next time */
1624 rep_hist_note_used_port(now, socks->port);
1626 } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1627 rep_hist_note_used_resolve(now); /* help predict this next time */
1628 /* no extra processing needed */
1629 } else {
1630 /* We should only be doing CONNECT or RESOLVE! */
1631 tor_fragile_assert();
1634 /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
1635 * address, and decided not to reject it for any number of reasons. Now
1636 * mark the connection as waiting for a circuit, and try to attach it!
1638 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1640 /* If we were given a circuit to attach to, try to attach. Otherwise,
1641 * try to find a good one and attach to that. */
1642 int rv;
1643 if (circ) {
1644 rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
1645 } else {
1646 connection_ap_mark_as_pending_circuit(conn);
1647 rv = 0;
1650 /* If the above function returned 0 then we're waiting for a circuit.
1651 * if it returned 1, we're attached. Both are okay. But if it returned
1652 * -1, there was an error, so make sure the connection is marked, and
1653 * return -1. */
1654 if (rv < 0) {
1655 if (!base_conn->marked_for_close)
1656 connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
1657 return -1;
1660 return 0;
1661 } else {
1662 /* If we get here, it's a request for a .onion address! */
1663 tor_assert(!automap);
1665 /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
1666 * for hidden service addresses. */
1667 if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1668 /* if it's a resolve request, fail it right now, rather than
1669 * building all the circuits and then realizing it won't work. */
1670 log_warn(LD_APP,
1671 "Resolve requests to hidden services not allowed. Failing.");
1672 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1673 0,NULL,-1,TIME_MAX);
1674 connection_mark_unattached_ap(conn,
1675 END_STREAM_REASON_SOCKSPROTOCOL |
1676 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
1677 return -1;
1680 /* If we were passed a circuit, then we need to fail. .onion addresses
1681 * only work when we launch our own circuits for now. */
1682 if (circ) {
1683 log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1684 "supported for .onion addresses currently. Failing.");
1685 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1686 return -1;
1689 /* Look up if we have client authorization configured for this hidden
1690 * service. If we do, associate it with the rend_data. */
1691 rend_service_authorization_t *client_auth =
1692 rend_client_lookup_service_authorization(socks->address);
1694 const char *cookie = NULL;
1695 rend_auth_type_t auth_type = REND_NO_AUTH;
1696 if (client_auth) {
1697 log_info(LD_REND, "Using previously configured client authorization "
1698 "for hidden service request.");
1699 auth_type = client_auth->auth_type;
1700 cookie = client_auth->descriptor_cookie;
1703 /* Fill in the rend_data field so we can start doing a connection to
1704 * a hidden service. */
1705 rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
1706 rend_data_client_create(socks->address, NULL, cookie, auth_type);
1707 if (rend_data == NULL) {
1708 return -1;
1710 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1711 safe_str_client(rend_data->onion_address));
1713 /* Lookup the given onion address. If invalid, stop right now else we
1714 * might have it in the cache or not, it will be tested later on. */
1715 unsigned int refetch_desc = 0;
1716 rend_cache_entry_t *entry = NULL;
1717 const int rend_cache_lookup_result =
1718 rend_cache_lookup_entry(rend_data->onion_address, -1, &entry);
1719 if (rend_cache_lookup_result < 0) {
1720 switch (-rend_cache_lookup_result) {
1721 case EINVAL:
1722 /* We should already have rejected this address! */
1723 log_warn(LD_BUG,"Invalid service name '%s'",
1724 safe_str_client(rend_data->onion_address));
1725 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1726 return -1;
1727 case ENOENT:
1728 refetch_desc = 1;
1729 break;
1730 default:
1731 log_warn(LD_BUG, "Unknown cache lookup error %d",
1732 rend_cache_lookup_result);
1733 return -1;
1737 /* Help predict this next time. We're not sure if it will need
1738 * a stable circuit yet, but we know we'll need *something*. */
1739 rep_hist_note_used_internal(now, 0, 1);
1741 /* Now we have a descriptor but is it usable or not? If not, refetch.
1742 * Also, a fetch could have been requested if the onion address was not
1743 * found in the cache previously. */
1744 if (refetch_desc || !rend_client_any_intro_points_usable(entry)) {
1745 connection_ap_mark_as_non_pending_circuit(conn);
1746 base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1747 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1748 safe_str_client(rend_data->onion_address));
1749 rend_client_refetch_v2_renddesc(rend_data);
1750 return 0;
1753 /* We have the descriptor so launch a connection to the HS. */
1754 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1755 log_info(LD_REND, "Descriptor is here. Great.");
1756 connection_ap_mark_as_pending_circuit(conn);
1757 return 0;
1760 return 0; /* unreached but keeps the compiler happy */
1763 #ifdef TRANS_PF
1764 static int pf_socket = -1;
1766 get_pf_socket(void)
1768 int pf;
1769 /* This should be opened before dropping privileges. */
1770 if (pf_socket >= 0)
1771 return pf_socket;
1773 #ifdef OPENBSD
1774 /* only works on OpenBSD */
1775 pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
1776 #else
1777 /* works on NetBSD and FreeBSD */
1778 pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
1779 #endif
1781 if (pf < 0) {
1782 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1783 return -1;
1786 pf_socket = pf;
1787 return pf_socket;
1789 #endif
1791 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || defined(TRANS_TPROXY)
1792 /** Try fill in the address of <b>req</b> from the socket configured
1793 * with <b>conn</b>. */
1794 static int
1795 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
1797 struct sockaddr_storage orig_dst;
1798 socklen_t orig_dst_len = sizeof(orig_dst);
1799 tor_addr_t addr;
1801 #ifdef TRANS_TRPOXY
1802 if (options->TransProxyType_parsed == TPT_TPROXY) {
1803 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
1804 &orig_dst_len) < 0) {
1805 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1806 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
1807 return -1;
1809 goto done;
1811 #endif
1813 #ifdef TRANS_NETFILTER
1814 int rv = -1;
1815 switch (ENTRY_TO_CONN(conn)->socket_family) {
1816 #ifdef TRANS_NETFILTER_IPV4
1817 case AF_INET:
1818 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
1819 (struct sockaddr*)&orig_dst, &orig_dst_len);
1820 break;
1821 #endif
1822 #ifdef TRANS_NETFILTER_IPV6
1823 case AF_INET6:
1824 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
1825 (struct sockaddr*)&orig_dst, &orig_dst_len);
1826 break;
1827 #endif
1828 default:
1829 log_warn(LD_BUG,
1830 "Received transparent data from an unsuported socket family %d",
1831 ENTRY_TO_CONN(conn)->socket_family);
1832 return -1;
1834 if (rv < 0) {
1835 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1836 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1837 return -1;
1839 goto done;
1840 #elif defined(TRANS_PF)
1841 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
1842 &orig_dst_len) < 0) {
1843 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1844 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
1845 return -1;
1847 goto done;
1848 #else
1849 (void)conn;
1850 (void)req;
1851 log_warn(LD_BUG, "Unable to determine destination from socket.");
1852 return -1;
1853 #endif
1855 done:
1856 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1857 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
1859 return 0;
1861 #endif
1863 #ifdef TRANS_PF
1864 static int
1865 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
1867 struct sockaddr_storage proxy_addr;
1868 socklen_t proxy_addr_len = sizeof(proxy_addr);
1869 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1870 struct pfioc_natlook pnl;
1871 tor_addr_t addr;
1872 int pf = -1;
1874 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
1875 &proxy_addr_len) < 0) {
1876 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1877 log_warn(LD_NET, "getsockname() to determine transocks destination "
1878 "failed: %s", tor_socket_strerror(e));
1879 return -1;
1882 #ifdef __FreeBSD__
1883 if (get_options()->TransProxyType_parsed == TPT_IPFW) {
1884 /* ipfw(8) is used and in this case getsockname returned the original
1885 destination */
1886 if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
1887 tor_fragile_assert();
1888 return -1;
1891 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1893 return 0;
1895 #endif
1897 memset(&pnl, 0, sizeof(pnl));
1898 pnl.proto = IPPROTO_TCP;
1899 pnl.direction = PF_OUT;
1900 if (proxy_sa->sa_family == AF_INET) {
1901 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1902 pnl.af = AF_INET;
1903 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
1904 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
1905 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1906 pnl.dport = sin->sin_port;
1907 } else if (proxy_sa->sa_family == AF_INET6) {
1908 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1909 pnl.af = AF_INET6;
1910 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
1911 sizeof(struct in6_addr));
1912 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
1913 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1914 pnl.dport = sin6->sin6_port;
1915 } else {
1916 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1917 (int)proxy_sa->sa_family);
1918 return -1;
1921 pf = get_pf_socket();
1922 if (pf<0)
1923 return -1;
1925 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1926 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1927 return -1;
1930 if (pnl.af == AF_INET) {
1931 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1932 } else if (pnl.af == AF_INET6) {
1933 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1934 } else {
1935 tor_fragile_assert();
1936 return -1;
1939 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
1940 req->port = ntohs(pnl.rdport);
1942 return 0;
1944 #endif
1946 /** Fetch the original destination address and port from a
1947 * system-specific interface and put them into a
1948 * socks_request_t as if they came from a socks request.
1950 * Return -1 if an error prevents fetching the destination,
1951 * else return 0.
1953 static int
1954 connection_ap_get_original_destination(entry_connection_t *conn,
1955 socks_request_t *req)
1957 #ifdef TRANS_NETFILTER
1958 return destination_from_socket(conn, req);
1959 #elif defined(TRANS_PF)
1960 const or_options_t *options = get_options();
1962 if (options->TransProxyType_parsed == TPT_PF_DIVERT)
1963 return destination_from_socket(conn, req);
1965 if (options->TransProxyType_parsed == TPT_DEFAULT ||
1966 options->TransProxyType_parsed == TPT_IPFW)
1967 return destination_from_pf(conn, req);
1969 (void)conn;
1970 (void)req;
1971 log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
1972 options->TransProxyType);
1973 return -1;
1974 #else
1975 (void)conn;
1976 (void)req;
1977 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1978 "transparent proxy method was configured.");
1979 return -1;
1980 #endif
1983 /** connection_edge_process_inbuf() found a conn in state
1984 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1985 * the socks handshake.
1987 * If the handshake is complete, send it to
1988 * connection_ap_handshake_rewrite_and_attach().
1990 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1991 * else return 0.
1993 static int
1994 connection_ap_handshake_process_socks(entry_connection_t *conn)
1996 socks_request_t *socks;
1997 int sockshere;
1998 const or_options_t *options = get_options();
1999 int had_reply = 0;
2000 connection_t *base_conn = ENTRY_TO_CONN(conn);
2002 tor_assert(conn);
2003 tor_assert(base_conn->type == CONN_TYPE_AP);
2004 tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
2005 tor_assert(conn->socks_request);
2006 socks = conn->socks_request;
2008 log_debug(LD_APP,"entered.");
2010 IF_HAS_BUFFEREVENT(base_conn, {
2011 struct evbuffer *input = bufferevent_get_input(base_conn->bufev);
2012 sockshere = fetch_from_evbuffer_socks(input, socks,
2013 options->TestSocks, options->SafeSocks);
2014 }) ELSE_IF_NO_BUFFEREVENT {
2015 sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2016 options->TestSocks, options->SafeSocks);
2019 if (socks->replylen) {
2020 had_reply = 1;
2021 connection_write_to_buf((const char*)socks->reply, socks->replylen,
2022 base_conn);
2023 socks->replylen = 0;
2024 if (sockshere == -1) {
2025 /* An invalid request just got a reply, no additional
2026 * one is necessary. */
2027 socks->has_finished = 1;
2031 if (sockshere == 0) {
2032 log_debug(LD_APP,"socks handshake not all here yet.");
2033 return 0;
2034 } else if (sockshere == -1) {
2035 if (!had_reply) {
2036 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2037 connection_ap_handshake_socks_reply(conn, NULL, 0,
2038 END_STREAM_REASON_SOCKSPROTOCOL);
2040 connection_mark_unattached_ap(conn,
2041 END_STREAM_REASON_SOCKSPROTOCOL |
2042 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
2043 return -1;
2044 } /* else socks handshake is done, continue processing */
2046 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2047 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2048 else
2049 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2051 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2054 /** connection_init_accepted_conn() found a new trans AP conn.
2055 * Get the original destination and send it to
2056 * connection_ap_handshake_rewrite_and_attach().
2058 * Return -1 if an unexpected error with conn (and it should be marked
2059 * for close), else return 0.
2062 connection_ap_process_transparent(entry_connection_t *conn)
2064 socks_request_t *socks;
2066 tor_assert(conn);
2067 tor_assert(conn->socks_request);
2068 socks = conn->socks_request;
2070 /* pretend that a socks handshake completed so we don't try to
2071 * send a socks reply down a transparent conn */
2072 socks->command = SOCKS_COMMAND_CONNECT;
2073 socks->has_finished = 1;
2075 log_debug(LD_APP,"entered.");
2077 if (connection_ap_get_original_destination(conn, socks) < 0) {
2078 log_warn(LD_APP,"Fetching original destination failed. Closing.");
2079 connection_mark_unattached_ap(conn,
2080 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
2081 return -1;
2083 /* we have the original destination */
2085 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2087 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2090 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2091 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2092 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2093 * form of the original destination.
2095 * If the original destination is complete, send it to
2096 * connection_ap_handshake_rewrite_and_attach().
2098 * Return -1 if an unexpected error with conn (and it should be marked
2099 * for close), else return 0.
2101 static int
2102 connection_ap_process_natd(entry_connection_t *conn)
2104 char tmp_buf[36], *tbuf, *daddr;
2105 size_t tlen = 30;
2106 int err, port_ok;
2107 socks_request_t *socks;
2109 tor_assert(conn);
2110 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
2111 tor_assert(conn->socks_request);
2112 socks = conn->socks_request;
2114 log_debug(LD_APP,"entered.");
2116 /* look for LF-terminated "[DEST ip_addr port]"
2117 * where ip_addr is a dotted-quad and port is in string form */
2118 err = connection_fetch_from_buf_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2119 if (err == 0)
2120 return 0;
2121 if (err < 0) {
2122 log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2123 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2124 return -1;
2127 if (strcmpstart(tmp_buf, "[DEST ")) {
2128 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2129 "said: %s",
2130 escaped(tmp_buf));
2131 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2132 return -1;
2135 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2136 if (!(tbuf = strchr(tbuf, ' '))) {
2137 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2138 "said: %s",
2139 escaped(tmp_buf));
2140 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2141 return -1;
2143 *tbuf++ = '\0';
2145 /* pretend that a socks handshake completed so we don't try to
2146 * send a socks reply down a natd conn */
2147 strlcpy(socks->address, daddr, sizeof(socks->address));
2148 socks->port = (uint16_t)
2149 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2150 if (!port_ok) {
2151 log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2152 "of range.", escaped(tbuf));
2153 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2154 return -1;
2157 socks->command = SOCKS_COMMAND_CONNECT;
2158 socks->has_finished = 1;
2160 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2162 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
2164 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2167 /** Iterate over the two bytes of stream_id until we get one that is not
2168 * already in use; return it. Return 0 if can't get a unique stream_id.
2170 streamid_t
2171 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2173 edge_connection_t *tmpconn;
2174 streamid_t test_stream_id;
2175 uint32_t attempts=0;
2177 again:
2178 test_stream_id = circ->next_stream_id++;
2179 if (++attempts > 1<<16) {
2180 /* Make sure we don't loop forever if all stream_id's are used. */
2181 log_warn(LD_APP,"No unused stream IDs. Failing.");
2182 return 0;
2184 if (test_stream_id == 0)
2185 goto again;
2186 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2187 if (tmpconn->stream_id == test_stream_id)
2188 goto again;
2189 return test_stream_id;
2192 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
2193 * an exit that supports optimistic data. */
2194 static int
2195 connection_ap_supports_optimistic_data(const entry_connection_t *conn)
2197 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2198 /* We can only send optimistic data if we're connected to an open
2199 general circuit. */
2200 if (edge_conn->on_circuit == NULL ||
2201 edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
2202 (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
2203 edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
2204 return 0;
2206 return conn->may_use_optimistic_data;
2209 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
2210 * RELAY_BEGIN cell for <b>ap_conn</b>. */
2211 static uint32_t
2212 connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
2214 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2215 const node_t *exitnode = NULL;
2216 const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
2217 uint32_t flags = 0;
2219 /* No flags for begindir */
2220 if (ap_conn->use_begindir)
2221 return 0;
2223 /* No flags for hidden services. */
2224 if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
2225 return 0;
2227 /* If only IPv4 is supported, no flags */
2228 if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
2229 return 0;
2231 if (! cpath_layer ||
2232 ! cpath_layer->extend_info)
2233 return 0;
2235 if (!ap_conn->entry_cfg.ipv4_traffic)
2236 flags |= BEGIN_FLAG_IPV4_NOT_OK;
2238 exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
2240 if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
2241 tor_addr_t a;
2242 tor_addr_make_null(&a, AF_INET6);
2243 if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
2244 exitnode)
2245 != ADDR_POLICY_REJECTED) {
2246 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
2247 * no point. */
2248 flags |= BEGIN_FLAG_IPV6_OK;
2252 if (flags == BEGIN_FLAG_IPV6_OK) {
2253 /* When IPv4 and IPv6 are both allowed, consider whether to say we
2254 * prefer IPv6. Otherwise there's no point in declaring a preference */
2255 if (ap_conn->entry_cfg.prefer_ipv6)
2256 flags |= BEGIN_FLAG_IPV6_PREFERRED;
2259 if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
2260 log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
2261 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
2262 "not going to work. Did you perhaps ask for an IPv6 address "
2263 "on an IPv4Only port, or vice versa?");
2266 return flags;
2269 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2270 * socks_request field, and send it down circ.
2272 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2275 connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
2277 char payload[CELL_PAYLOAD_SIZE];
2278 int payload_len;
2279 int begin_type;
2280 origin_circuit_t *circ;
2281 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2282 connection_t *base_conn = TO_CONN(edge_conn);
2283 tor_assert(edge_conn->on_circuit);
2284 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
2286 tor_assert(base_conn->type == CONN_TYPE_AP);
2287 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2288 tor_assert(ap_conn->socks_request);
2289 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2291 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
2292 if (edge_conn->stream_id==0) {
2293 /* XXXX024 Instead of closing this stream, we should make it get
2294 * retried on another circuit. */
2295 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2297 /* Mark this circuit "unusable for new streams". */
2298 mark_circuit_unusable_for_new_conns(circ);
2299 return -1;
2302 /* Set up begin cell flags. */
2303 edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
2305 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2306 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2307 ap_conn->socks_request->address : "",
2308 ap_conn->socks_request->port);
2309 payload_len = (int)strlen(payload)+1;
2310 if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
2311 set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
2312 payload_len += 4;
2315 log_info(LD_APP,
2316 "Sending relay cell %d on circ %u to begin stream %d.",
2317 (int)ap_conn->use_begindir,
2318 (unsigned)circ->base_.n_circ_id,
2319 edge_conn->stream_id);
2321 begin_type = ap_conn->use_begindir ?
2322 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2323 if (begin_type == RELAY_COMMAND_BEGIN) {
2324 #ifndef NON_ANONYMOUS_MODE_ENABLED
2325 tor_assert(circ->build_state->onehop_tunnel == 0);
2326 #endif
2329 if (connection_edge_send_command(edge_conn, begin_type,
2330 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2331 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2332 return -1; /* circuit is closed, don't continue */
2334 edge_conn->package_window = STREAMWINDOW_START;
2335 edge_conn->deliver_window = STREAMWINDOW_START;
2336 base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
2337 log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
2338 ", n_circ_id %u",
2339 base_conn->s, (unsigned)circ->base_.n_circ_id);
2340 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2342 /* If there's queued-up data, send it now */
2343 if ((connection_get_inbuf_len(base_conn) ||
2344 ap_conn->sending_optimistic_data) &&
2345 connection_ap_supports_optimistic_data(ap_conn)) {
2346 log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
2347 (long)connection_get_inbuf_len(base_conn),
2348 ap_conn->sending_optimistic_data ?
2349 (long)generic_buffer_len(ap_conn->sending_optimistic_data) : 0);
2350 if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
2351 connection_mark_for_close(base_conn);
2355 return 0;
2358 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2359 * socks_request field, and send it down circ.
2361 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2364 connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
2366 int payload_len, command;
2367 const char *string_addr;
2368 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2369 origin_circuit_t *circ;
2370 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2371 connection_t *base_conn = TO_CONN(edge_conn);
2372 tor_assert(edge_conn->on_circuit);
2373 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
2375 tor_assert(base_conn->type == CONN_TYPE_AP);
2376 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2377 tor_assert(ap_conn->socks_request);
2378 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2380 command = ap_conn->socks_request->command;
2381 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2383 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
2384 if (edge_conn->stream_id==0) {
2385 /* XXXX024 Instead of closing this stream, we should make it get
2386 * retried on another circuit. */
2387 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2389 /* Mark this circuit "unusable for new streams". */
2390 mark_circuit_unusable_for_new_conns(circ);
2391 return -1;
2394 if (command == SOCKS_COMMAND_RESOLVE) {
2395 string_addr = ap_conn->socks_request->address;
2396 payload_len = (int)strlen(string_addr)+1;
2397 } else {
2398 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2399 const char *a = ap_conn->socks_request->address;
2400 tor_addr_t addr;
2401 int r;
2403 /* We're doing a reverse lookup. The input could be an IP address, or
2404 * could be an .in-addr.arpa or .ip6.arpa address */
2405 r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
2406 if (r <= 0) {
2407 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2408 safe_str_client(a));
2409 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2410 return -1;
2413 r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2414 if (r < 0) {
2415 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2416 safe_str_client(a));
2417 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2418 return -1;
2421 string_addr = inaddr_buf;
2422 payload_len = (int)strlen(inaddr_buf)+1;
2423 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
2426 log_debug(LD_APP,
2427 "Sending relay cell to begin stream %d.", edge_conn->stream_id);
2429 if (connection_edge_send_command(edge_conn,
2430 RELAY_COMMAND_RESOLVE,
2431 string_addr, payload_len) < 0)
2432 return -1; /* circuit is closed, don't continue */
2434 if (!base_conn->address) {
2435 /* This might be unnecessary. XXXX */
2436 base_conn->address = tor_dup_addr(&base_conn->addr);
2438 base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
2439 log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
2440 ", n_circ_id %u",
2441 base_conn->s, (unsigned)circ->base_.n_circ_id);
2442 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2443 return 0;
2446 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
2447 * new linked connection pair, and attach one side to the conn, connection_add
2448 * it, initialize it to circuit_wait, and call
2449 * connection_ap_handshake_attach_circuit(conn) on it.
2451 * Return the newly created end of the linked connection pair, or -1 if error.
2453 entry_connection_t *
2454 connection_ap_make_link(connection_t *partner,
2455 char *address, uint16_t port,
2456 const char *digest,
2457 int session_group, int isolation_flags,
2458 int use_begindir, int want_onehop)
2460 entry_connection_t *conn;
2461 connection_t *base_conn;
2463 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2464 want_onehop ? "direct" : "anonymized",
2465 safe_str_client(address), port);
2467 conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
2468 base_conn = ENTRY_TO_CONN(conn);
2469 base_conn->linked = 1; /* so that we can add it safely below. */
2471 /* populate conn->socks_request */
2473 /* leave version at zero, so the socks_reply is empty */
2474 conn->socks_request->socks_version = 0;
2475 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2476 strlcpy(conn->socks_request->address, address,
2477 sizeof(conn->socks_request->address));
2478 conn->socks_request->port = port;
2479 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2480 conn->want_onehop = want_onehop;
2481 conn->use_begindir = use_begindir;
2482 if (use_begindir) {
2483 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2484 conn->chosen_exit_name[0] = '$';
2485 tor_assert(digest);
2486 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2487 digest, DIGEST_LEN);
2490 /* Populate isolation fields. */
2491 conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
2492 conn->original_dest_address = tor_strdup(address);
2493 conn->entry_cfg.session_group = session_group;
2494 conn->entry_cfg.isolation_flags = isolation_flags;
2496 base_conn->address = tor_strdup("(Tor_internal)");
2497 tor_addr_make_unspec(&base_conn->addr);
2498 base_conn->port = 0;
2500 connection_link_connections(partner, base_conn);
2502 if (connection_add(base_conn) < 0) { /* no space, forget it */
2503 connection_free(base_conn);
2504 return NULL;
2507 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2509 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2511 /* attaching to a dirty circuit is fine */
2512 connection_ap_mark_as_pending_circuit(conn);
2513 log_info(LD_APP,"... application connection created and linked.");
2514 return conn;
2517 /** Notify any interested controller connections about a new hostname resolve
2518 * or resolve error. Takes the same arguments as does
2519 * connection_ap_handshake_socks_resolved(). */
2520 static void
2521 tell_controller_about_resolved_result(entry_connection_t *conn,
2522 int answer_type,
2523 size_t answer_len,
2524 const char *answer,
2525 int ttl,
2526 time_t expires)
2528 expires = time(NULL) + ttl;
2529 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2530 char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
2531 control_event_address_mapped(conn->socks_request->address,
2532 cp, expires, NULL, 0);
2533 tor_free(cp);
2534 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2535 char *cp = tor_strndup(answer, answer_len);
2536 control_event_address_mapped(conn->socks_request->address,
2537 cp, expires, NULL, 0);
2538 tor_free(cp);
2539 } else {
2540 control_event_address_mapped(conn->socks_request->address,
2541 "<error>", time(NULL)+ttl,
2542 "error=yes", 0);
2547 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
2548 * as the answer.
2550 void
2551 connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
2552 const tor_addr_t *answer,
2553 int ttl,
2554 time_t expires)
2556 if (tor_addr_family(answer) == AF_INET) {
2557 uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
2558 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
2559 (uint8_t*)&a,
2560 ttl, expires);
2561 } else if (tor_addr_family(answer) == AF_INET6) {
2562 const uint8_t *a = tor_addr_to_in6_addr8(answer);
2563 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
2565 ttl, expires);
2566 } else {
2567 log_warn(LD_BUG, "Got called with address of unexpected family %d",
2568 tor_addr_family(answer));
2569 connection_ap_handshake_socks_resolved(conn,
2570 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
2574 /** Send an answer to an AP connection that has requested a DNS lookup via
2575 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2576 * for unreachable; the answer should be in the format specified in the socks
2577 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2578 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2579 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2581 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
2582 * interface and those that use it less ugly. */
2583 MOCK_IMPL(void,
2584 connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
2585 int answer_type,
2586 size_t answer_len,
2587 const uint8_t *answer,
2588 int ttl,
2589 time_t expires))
2591 char buf[384];
2592 size_t replylen;
2594 if (ttl >= 0) {
2595 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2596 tor_addr_t a;
2597 tor_addr_from_ipv4n(&a, get_uint32(answer));
2598 if (! tor_addr_is_null(&a)) {
2599 client_dns_set_addressmap(conn,
2600 conn->socks_request->address, &a,
2601 conn->chosen_exit_name, ttl);
2603 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2604 tor_addr_t a;
2605 tor_addr_from_ipv6_bytes(&a, (char*)answer);
2606 if (! tor_addr_is_null(&a)) {
2607 client_dns_set_addressmap(conn,
2608 conn->socks_request->address, &a,
2609 conn->chosen_exit_name, ttl);
2611 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2612 char *cp = tor_strndup((char*)answer, answer_len);
2613 client_dns_set_reverse_addressmap(conn,
2614 conn->socks_request->address,
2616 conn->chosen_exit_name, ttl);
2617 tor_free(cp);
2621 if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
2622 if (conn->dns_server_request) {
2623 /* We had a request on our DNS port: answer it. */
2624 dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
2625 conn->socks_request->has_finished = 1;
2626 return;
2627 } else {
2628 /* This must be a request from the controller. Since answers to those
2629 * requests are not cached, they do not generate an ADDRMAP event on
2630 * their own. */
2631 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2632 (char*)answer, ttl, expires);
2633 conn->socks_request->has_finished = 1;
2634 return;
2636 /* We shouldn't need to free conn here; it gets marked by the caller. */
2639 if (conn->socks_request->socks_version == 4) {
2640 buf[0] = 0x00; /* version */
2641 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2642 buf[1] = SOCKS4_GRANTED;
2643 set_uint16(buf+2, 0);
2644 memcpy(buf+4, answer, 4); /* address */
2645 replylen = SOCKS4_NETWORK_LEN;
2646 } else { /* "error" */
2647 buf[1] = SOCKS4_REJECT;
2648 memset(buf+2, 0, 6);
2649 replylen = SOCKS4_NETWORK_LEN;
2651 } else if (conn->socks_request->socks_version == 5) {
2652 /* SOCKS5 */
2653 buf[0] = 0x05; /* version */
2654 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2655 buf[1] = SOCKS5_SUCCEEDED;
2656 buf[2] = 0; /* reserved */
2657 buf[3] = 0x01; /* IPv4 address type */
2658 memcpy(buf+4, answer, 4); /* address */
2659 set_uint16(buf+8, 0); /* port == 0. */
2660 replylen = 10;
2661 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2662 buf[1] = SOCKS5_SUCCEEDED;
2663 buf[2] = 0; /* reserved */
2664 buf[3] = 0x04; /* IPv6 address type */
2665 memcpy(buf+4, answer, 16); /* address */
2666 set_uint16(buf+20, 0); /* port == 0. */
2667 replylen = 22;
2668 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2669 buf[1] = SOCKS5_SUCCEEDED;
2670 buf[2] = 0; /* reserved */
2671 buf[3] = 0x03; /* Domainname address type */
2672 buf[4] = (char)answer_len;
2673 memcpy(buf+5, answer, answer_len); /* address */
2674 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2675 replylen = 5+answer_len+2;
2676 } else {
2677 buf[1] = SOCKS5_HOST_UNREACHABLE;
2678 memset(buf+2, 0, 8);
2679 replylen = 10;
2681 } else {
2682 /* no socks version info; don't send anything back */
2683 return;
2685 connection_ap_handshake_socks_reply(conn, buf, replylen,
2686 (answer_type == RESOLVED_TYPE_IPV4 ||
2687 answer_type == RESOLVED_TYPE_IPV6 ||
2688 answer_type == RESOLVED_TYPE_HOSTNAME) ?
2689 0 : END_STREAM_REASON_RESOLVEFAILED);
2692 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2693 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2694 * handshaking.
2696 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2697 * and return, else reply based on <b>endreason</b> (one of
2698 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2699 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2701 void
2702 connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
2703 size_t replylen, int endreason)
2705 char buf[256];
2706 socks5_reply_status_t status =
2707 stream_end_reason_to_socks5_response(endreason);
2709 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2711 if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2712 control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
2713 STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2714 endreason);
2717 /* Flag this stream's circuit as having completed a stream successfully
2718 * (for path bias) */
2719 if (status == SOCKS5_SUCCEEDED ||
2720 endreason == END_STREAM_REASON_RESOLVEFAILED ||
2721 endreason == END_STREAM_REASON_CONNECTREFUSED ||
2722 endreason == END_STREAM_REASON_CONNRESET ||
2723 endreason == END_STREAM_REASON_NOROUTE ||
2724 endreason == END_STREAM_REASON_RESOURCELIMIT) {
2725 if (!conn->edge_.on_circuit ||
2726 !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
2727 if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
2728 log_info(LD_BUG,
2729 "No origin circuit for successful SOCKS stream "U64_FORMAT
2730 ". Reason: %d",
2731 U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
2732 endreason);
2735 * Else DNS remaps and failed hidden service lookups can send us
2736 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
2738 * Perhaps we could make the test more precise; we can tell hidden
2739 * services by conn->edge_.renddata != NULL; anything analogous for
2740 * the DNS remap case?
2742 } else {
2743 // XXX: Hrmm. It looks like optimistic data can't go through this
2744 // codepath, but someone should probably test it and make sure.
2745 // We don't want to mark optimistically opened streams as successful.
2746 pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
2750 if (conn->socks_request->has_finished) {
2751 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2752 "connection_ap_handshake_socks_reply.");
2753 return;
2755 if (replylen) { /* we already have a reply in mind */
2756 connection_write_to_buf(reply, replylen, ENTRY_TO_CONN(conn));
2757 conn->socks_request->has_finished = 1;
2758 return;
2760 if (conn->socks_request->socks_version == 4) {
2761 memset(buf,0,SOCKS4_NETWORK_LEN);
2762 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2763 /* leave version, destport, destip zero */
2764 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
2765 } else if (conn->socks_request->socks_version == 5) {
2766 size_t buf_len;
2767 memset(buf,0,sizeof(buf));
2768 if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
2769 buf[0] = 5; /* version 5 */
2770 buf[1] = (char)status;
2771 buf[2] = 0;
2772 buf[3] = 1; /* ipv4 addr */
2773 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
2774 buf_len = 10;
2775 } else { /* AF_INET6. */
2776 buf[0] = 5; /* version 5 */
2777 buf[1] = (char)status;
2778 buf[2] = 0;
2779 buf[3] = 4; /* ipv6 addr */
2780 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
2781 buf_len = 22;
2783 connection_write_to_buf(buf,buf_len,ENTRY_TO_CONN(conn));
2785 /* If socks_version isn't 4 or 5, don't send anything.
2786 * This can happen in the case of AP bridges. */
2787 conn->socks_request->has_finished = 1;
2788 return;
2791 /** Read a RELAY_BEGIN or RELAY_BEGINDIR cell from <b>cell</b>, decode it, and
2792 * place the result in <b>bcell</b>. On success return 0; on failure return
2793 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
2794 * the client.
2796 * Return -1 in the case where want to send a RELAY_END cell, and < -1 when
2797 * we don't.
2799 STATIC int
2800 begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
2801 uint8_t *end_reason_out)
2803 relay_header_t rh;
2804 const uint8_t *body, *nul;
2806 memset(bcell, 0, sizeof(*bcell));
2807 *end_reason_out = END_STREAM_REASON_MISC;
2809 relay_header_unpack(&rh, cell->payload);
2810 if (rh.length > RELAY_PAYLOAD_SIZE) {
2811 return -2; /*XXXX why not TORPROTOCOL? */
2814 bcell->stream_id = rh.stream_id;
2816 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2817 bcell->is_begindir = 1;
2818 return 0;
2819 } else if (rh.command != RELAY_COMMAND_BEGIN) {
2820 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2821 *end_reason_out = END_STREAM_REASON_INTERNAL;
2822 return -1;
2825 body = cell->payload + RELAY_HEADER_SIZE;
2826 nul = memchr(body, 0, rh.length);
2827 if (! nul) {
2828 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2829 "Relay begin cell has no \\0. Closing.");
2830 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
2831 return -1;
2834 if (tor_addr_port_split(LOG_PROTOCOL_WARN,
2835 (char*)(body),
2836 &bcell->address,&bcell->port)<0) {
2837 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2838 "Unable to parse addr:port in relay begin cell. Closing.");
2839 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
2840 return -1;
2842 if (bcell->port == 0) {
2843 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2844 "Missing port in relay begin cell. Closing.");
2845 tor_free(bcell->address);
2846 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
2847 return -1;
2849 if (body + rh.length >= nul + 4)
2850 bcell->flags = ntohl(get_uint32(nul+1));
2852 return 0;
2855 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2856 * an exit hop for the circuit, or we are the origin and it is a
2857 * rendezvous begin.
2859 * Launch a new exit connection and initialize things appropriately.
2861 * If it's a rendezvous stream, call connection_exit_connect() on
2862 * it.
2864 * For general streams, call dns_resolve() on it first, and only call
2865 * connection_exit_connect() if the dns answer is already known.
2867 * Note that we don't call connection_add() on the new stream! We wait
2868 * for connection_exit_connect() to do that.
2870 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2871 * Else return 0.
2874 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2876 edge_connection_t *n_stream;
2877 relay_header_t rh;
2878 char *address = NULL;
2879 uint16_t port = 0;
2880 or_circuit_t *or_circ = NULL;
2881 const or_options_t *options = get_options();
2882 begin_cell_t bcell;
2883 int r;
2884 uint8_t end_reason=0;
2886 assert_circuit_ok(circ);
2887 if (!CIRCUIT_IS_ORIGIN(circ))
2888 or_circ = TO_OR_CIRCUIT(circ);
2890 relay_header_unpack(&rh, cell->payload);
2891 if (rh.length > RELAY_PAYLOAD_SIZE)
2892 return -END_CIRC_REASON_TORPROTOCOL;
2894 /* Note: we have to use relay_send_command_from_edge here, not
2895 * connection_edge_end or connection_edge_send_command, since those require
2896 * that we have a stream connected to a circuit, and we don't connect to a
2897 * circuit until we have a pending/successful resolve. */
2899 if (!server_mode(options) &&
2900 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2901 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2902 "Relay begin cell at non-server. Closing.");
2903 relay_send_end_cell_from_edge(rh.stream_id, circ,
2904 END_STREAM_REASON_EXITPOLICY, NULL);
2905 return 0;
2908 r = begin_cell_parse(cell, &bcell, &end_reason);
2909 if (r < -1) {
2910 return -END_CIRC_REASON_TORPROTOCOL;
2911 } else if (r == -1) {
2912 tor_free(bcell.address);
2913 relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL);
2914 return 0;
2917 if (! bcell.is_begindir) {
2918 /* Steal reference */
2919 address = bcell.address;
2920 port = bcell.port;
2922 if (or_circ && or_circ->p_chan) {
2923 if (!options->AllowSingleHopExits &&
2924 (or_circ->is_first_hop ||
2925 (!connection_or_digest_is_known_relay(
2926 or_circ->p_chan->identity_digest) &&
2927 should_refuse_unknown_exits(options)))) {
2928 /* Don't let clients use us as a single-hop proxy, unless the user
2929 * has explicitly allowed that in the config. It attracts attackers
2930 * and users who'd be better off with, well, single-hop proxies.
2932 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2933 "Attempt by %s to open a stream %s. Closing.",
2934 safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
2935 or_circ->is_first_hop ? "on first hop of circuit" :
2936 "from unknown relay");
2937 relay_send_end_cell_from_edge(rh.stream_id, circ,
2938 or_circ->is_first_hop ?
2939 END_STREAM_REASON_TORPROTOCOL :
2940 END_STREAM_REASON_MISC,
2941 NULL);
2942 tor_free(address);
2943 return 0;
2946 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2947 if (!directory_permits_begindir_requests(options) ||
2948 circ->purpose != CIRCUIT_PURPOSE_OR) {
2949 relay_send_end_cell_from_edge(rh.stream_id, circ,
2950 END_STREAM_REASON_NOTDIRECTORY, NULL);
2951 return 0;
2953 /* Make sure to get the 'real' address of the previous hop: the
2954 * caller might want to know whether the remote IP address has changed,
2955 * and we might already have corrected base_.addr[ess] for the relay's
2956 * canonical IP address. */
2957 if (or_circ && or_circ->p_chan)
2958 address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
2959 else
2960 address = tor_strdup("127.0.0.1");
2961 port = 1; /* XXXX This value is never actually used anywhere, and there
2962 * isn't "really" a connection here. But we
2963 * need to set it to something nonzero. */
2964 } else {
2965 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2966 relay_send_end_cell_from_edge(rh.stream_id, circ,
2967 END_STREAM_REASON_INTERNAL, NULL);
2968 return 0;
2971 if (! options->IPv6Exit) {
2972 /* I don't care if you prefer IPv6; I can't give you any. */
2973 bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
2974 /* If you don't want IPv4, I can't help. */
2975 if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
2976 tor_free(address);
2977 relay_send_end_cell_from_edge(rh.stream_id, circ,
2978 END_STREAM_REASON_EXITPOLICY, NULL);
2979 return 0;
2983 log_debug(LD_EXIT,"Creating new exit connection.");
2984 /* The 'AF_INET' here is temporary; we might need to change it later in
2985 * connection_exit_connect(). */
2986 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2988 /* Remember the tunneled request ID in the new edge connection, so that
2989 * we can measure download times. */
2990 n_stream->dirreq_id = circ->dirreq_id;
2992 n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
2993 n_stream->begincell_flags = bcell.flags;
2994 n_stream->stream_id = rh.stream_id;
2995 n_stream->base_.port = port;
2996 /* leave n_stream->s at -1, because it's not yet valid */
2997 n_stream->package_window = STREAMWINDOW_START;
2998 n_stream->deliver_window = STREAMWINDOW_START;
3000 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
3001 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
3002 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
3003 n_stream->base_.address = tor_strdup("(rendezvous)");
3004 n_stream->base_.state = EXIT_CONN_STATE_CONNECTING;
3005 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
3006 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
3007 assert_circuit_ok(circ);
3009 const int r = rend_service_set_connection_addr_port(n_stream, origin_circ);
3010 if (r < 0) {
3011 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
3012 n_stream->base_.port);
3013 /* Send back reason DONE because we want to make hidden service port
3014 * scanning harder thus instead of returning that the exit policy
3015 * didn't match, which makes it obvious that the port is closed,
3016 * return DONE and kill the circuit. That way, a user (malicious or
3017 * not) needs one circuit per bad port unless it matches the policy of
3018 * the hidden service. */
3019 relay_send_end_cell_from_edge(rh.stream_id, circ,
3020 END_STREAM_REASON_DONE,
3021 origin_circ->cpath->prev);
3022 connection_free(TO_CONN(n_stream));
3023 tor_free(address);
3025 /* Drop the circuit here since it might be someone deliberately
3026 * scanning the hidden service ports. Note that this mitigates port
3027 * scanning by adding more work on the attacker side to successfully
3028 * scan but does not fully solve it. */
3029 if (r < -1)
3030 return END_CIRC_AT_ORIGIN;
3031 else
3032 return 0;
3034 assert_circuit_ok(circ);
3035 log_debug(LD_REND,"Finished assigning addr/port");
3036 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
3038 /* add it into the linked list of p_streams on this circuit */
3039 n_stream->next_stream = origin_circ->p_streams;
3040 n_stream->on_circuit = circ;
3041 origin_circ->p_streams = n_stream;
3042 assert_circuit_ok(circ);
3044 origin_circ->rend_data->nr_streams++;
3046 connection_exit_connect(n_stream);
3048 /* For path bias: This circuit was used successfully */
3049 pathbias_mark_use_success(origin_circ);
3051 tor_free(address);
3052 return 0;
3054 tor_strlower(address);
3055 n_stream->base_.address = address;
3056 n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3057 /* default to failed, change in dns_resolve if it turns out not to fail */
3059 if (we_are_hibernating()) {
3060 relay_send_end_cell_from_edge(rh.stream_id, circ,
3061 END_STREAM_REASON_HIBERNATING, NULL);
3062 connection_free(TO_CONN(n_stream));
3063 return 0;
3066 n_stream->on_circuit = circ;
3068 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3069 tor_addr_t tmp_addr;
3070 tor_assert(or_circ);
3071 if (or_circ->p_chan &&
3072 channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
3073 tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
3075 return connection_exit_connect_dir(n_stream);
3078 log_debug(LD_EXIT,"about to start the dns_resolve().");
3080 /* send it off to the gethostbyname farm */
3081 switch (dns_resolve(n_stream)) {
3082 case 1: /* resolve worked; now n_stream is attached to circ. */
3083 assert_circuit_ok(circ);
3084 log_debug(LD_EXIT,"about to call connection_exit_connect().");
3085 connection_exit_connect(n_stream);
3086 return 0;
3087 case -1: /* resolve failed */
3088 relay_send_end_cell_from_edge(rh.stream_id, circ,
3089 END_STREAM_REASON_RESOLVEFAILED, NULL);
3090 /* n_stream got freed. don't touch it. */
3091 break;
3092 case 0: /* resolve added to pending list */
3093 assert_circuit_ok(circ);
3094 break;
3096 return 0;
3100 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
3101 * circuit <b>circ</b>;
3102 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
3105 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
3107 edge_connection_t *dummy_conn;
3108 relay_header_t rh;
3110 assert_circuit_ok(TO_CIRCUIT(circ));
3111 relay_header_unpack(&rh, cell->payload);
3112 if (rh.length > RELAY_PAYLOAD_SIZE)
3113 return -1;
3115 /* This 'dummy_conn' only exists to remember the stream ID
3116 * associated with the resolve request; and to make the
3117 * implementation of dns.c more uniform. (We really only need to
3118 * remember the circuit, the stream ID, and the hostname to be
3119 * resolved; but if we didn't store them in a connection like this,
3120 * the housekeeping in dns.c would get way more complicated.)
3122 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
3123 dummy_conn->stream_id = rh.stream_id;
3124 dummy_conn->base_.address = tor_strndup(
3125 (char*)cell->payload+RELAY_HEADER_SIZE,
3126 rh.length);
3127 dummy_conn->base_.port = 0;
3128 dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3129 dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
3131 dummy_conn->on_circuit = TO_CIRCUIT(circ);
3133 /* send it off to the gethostbyname farm */
3134 switch (dns_resolve(dummy_conn)) {
3135 case -1: /* Impossible to resolve; a resolved cell was sent. */
3136 /* Connection freed; don't touch it. */
3137 return 0;
3138 case 1: /* The result was cached; a resolved cell was sent. */
3139 if (!dummy_conn->base_.marked_for_close)
3140 connection_free(TO_CONN(dummy_conn));
3141 return 0;
3142 case 0: /* resolve added to pending list */
3143 assert_circuit_ok(TO_CIRCUIT(circ));
3144 break;
3146 return 0;
3149 /** Connect to conn's specified addr and port. If it worked, conn
3150 * has now been added to the connection_array.
3152 * Send back a connected cell. Include the resolved IP of the destination
3153 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
3154 * streams must not reveal what IP they connected to.)
3156 void
3157 connection_exit_connect(edge_connection_t *edge_conn)
3159 const tor_addr_t *addr;
3160 uint16_t port;
3161 connection_t *conn = TO_CONN(edge_conn);
3162 int socket_error = 0, result;
3164 if ( (!connection_edge_is_rendezvous_stream(edge_conn) &&
3165 router_compare_to_my_exit_policy(&edge_conn->base_.addr,
3166 edge_conn->base_.port)) ||
3167 (tor_addr_family(&conn->addr) == AF_INET6 &&
3168 ! get_options()->IPv6Exit)) {
3169 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
3170 escaped_safe_str_client(conn->address), conn->port);
3171 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
3172 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3173 connection_free(conn);
3174 return;
3177 #ifdef HAVE_SYS_UN_H
3178 if (conn->socket_family != AF_UNIX) {
3179 #else
3181 #endif /* defined(HAVE_SYS_UN_H) */
3182 addr = &conn->addr;
3183 port = conn->port;
3185 if (tor_addr_family(addr) == AF_INET6)
3186 conn->socket_family = AF_INET6;
3188 log_debug(LD_EXIT, "about to try connecting");
3189 result = connection_connect(conn, conn->address,
3190 addr, port, &socket_error);
3191 #ifdef HAVE_SYS_UN_H
3192 } else {
3194 * In the AF_UNIX case, we expect to have already had conn->port = 1,
3195 * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
3196 * case in connection_handle_listener_read()), and conn->address should
3197 * have the socket path to connect to.
3199 tor_assert(conn->address && strlen(conn->address) > 0);
3201 log_debug(LD_EXIT, "about to try connecting");
3202 result = connection_connect_unix(conn, conn->address, &socket_error);
3203 #endif /* defined(HAVE_SYS_UN_H) */
3206 switch (result) {
3207 case -1: {
3208 int reason = errno_to_stream_end_reason(socket_error);
3209 connection_edge_end(edge_conn, reason);
3210 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3211 connection_free(conn);
3212 return;
3214 case 0:
3215 conn->state = EXIT_CONN_STATE_CONNECTING;
3217 connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
3218 /* writable indicates finish;
3219 * readable/error indicates broken link in windows-land. */
3220 return;
3221 /* case 1: fall through */
3224 conn->state = EXIT_CONN_STATE_OPEN;
3225 if (connection_get_outbuf_len(conn)) {
3226 /* in case there are any queued data cells, from e.g. optimistic data */
3227 IF_HAS_NO_BUFFEREVENT(conn)
3228 connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
3229 } else {
3230 IF_HAS_NO_BUFFEREVENT(conn)
3231 connection_watch_events(conn, READ_EVENT);
3234 /* also, deliver a 'connected' cell back through the circuit. */
3235 if (connection_edge_is_rendezvous_stream(edge_conn)) {
3236 /* don't send an address back! */
3237 connection_edge_send_command(edge_conn,
3238 RELAY_COMMAND_CONNECTED,
3239 NULL, 0);
3240 } else { /* normal stream */
3241 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
3242 int connected_payload_len =
3243 connected_cell_format_payload(connected_payload, &conn->addr,
3244 edge_conn->address_ttl);
3245 if (connected_payload_len < 0) {
3246 connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
3247 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3248 connection_free(conn);
3249 return;
3252 connection_edge_send_command(edge_conn,
3253 RELAY_COMMAND_CONNECTED,
3254 (char*)connected_payload,
3255 connected_payload_len);
3259 /** Given an exit conn that should attach to us as a directory server, open a
3260 * bridge connection with a linked connection pair, create a new directory
3261 * conn, and join them together. Return 0 on success (or if there was an
3262 * error we could send back an end cell for). Return -(some circuit end
3263 * reason) if the circuit needs to be torn down. Either connects
3264 * <b>exitconn</b>, frees it, or marks it, as appropriate.
3266 static int
3267 connection_exit_connect_dir(edge_connection_t *exitconn)
3269 dir_connection_t *dirconn = NULL;
3270 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
3272 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
3274 exitconn->base_.state = EXIT_CONN_STATE_OPEN;
3276 dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
3278 tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
3279 dirconn->base_.port = 0;
3280 dirconn->base_.address = tor_strdup(exitconn->base_.address);
3281 dirconn->base_.type = CONN_TYPE_DIR;
3282 dirconn->base_.purpose = DIR_PURPOSE_SERVER;
3283 dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
3285 /* Note that the new dir conn belongs to the same tunneled request as
3286 * the edge conn, so that we can measure download times. */
3287 dirconn->dirreq_id = exitconn->dirreq_id;
3289 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
3291 if (connection_add(TO_CONN(exitconn))<0) {
3292 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
3293 connection_free(TO_CONN(exitconn));
3294 connection_free(TO_CONN(dirconn));
3295 return 0;
3298 /* link exitconn to circ, now that we know we can use it. */
3299 exitconn->next_stream = circ->n_streams;
3300 circ->n_streams = exitconn;
3302 if (connection_add(TO_CONN(dirconn))<0) {
3303 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
3304 connection_close_immediate(TO_CONN(exitconn));
3305 connection_mark_for_close(TO_CONN(exitconn));
3306 connection_free(TO_CONN(dirconn));
3307 return 0;
3310 connection_start_reading(TO_CONN(dirconn));
3311 connection_start_reading(TO_CONN(exitconn));
3313 if (connection_edge_send_command(exitconn,
3314 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
3315 connection_mark_for_close(TO_CONN(exitconn));
3316 connection_mark_for_close(TO_CONN(dirconn));
3317 return 0;
3320 return 0;
3323 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
3324 * it is a general stream.
3327 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
3329 tor_assert(conn);
3330 if (conn->rend_data)
3331 return 1;
3332 return 0;
3335 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
3336 * to exit from it, or 0 if it probably will not allow it.
3337 * (We might be uncertain if conn's destination address has not yet been
3338 * resolved.)
3341 connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit)
3343 const or_options_t *options = get_options();
3345 tor_assert(conn);
3346 tor_assert(conn->socks_request);
3347 tor_assert(exit);
3349 /* If a particular exit node has been requested for the new connection,
3350 * make sure the exit node of the existing circuit matches exactly.
3352 if (conn->chosen_exit_name) {
3353 const node_t *chosen_exit =
3354 node_get_by_nickname(conn->chosen_exit_name, 1);
3355 if (!chosen_exit || tor_memneq(chosen_exit->identity,
3356 exit->identity, DIGEST_LEN)) {
3357 /* doesn't match */
3358 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
3359 // conn->chosen_exit_name, exit->nickname);
3360 return 0;
3364 if (conn->use_begindir) {
3365 /* Internal directory fetches do not count as exiting. */
3366 return 1;
3369 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
3370 tor_addr_t addr, *addrp = NULL;
3371 addr_policy_result_t r;
3372 if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
3373 addrp = &addr;
3374 } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
3375 tor_addr_make_null(&addr, AF_INET6);
3376 addrp = &addr;
3377 } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
3378 tor_addr_make_null(&addr, AF_INET);
3379 addrp = &addr;
3381 r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,exit);
3382 if (r == ADDR_POLICY_REJECTED)
3383 return 0; /* We know the address, and the exit policy rejects it. */
3384 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
3385 return 0; /* We don't know the addr, but the exit policy rejects most
3386 * addresses with this port. Since the user didn't ask for
3387 * this node, err on the side of caution. */
3388 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3389 /* Don't send DNS requests to non-exit servers by default. */
3390 if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit))
3391 return 0;
3393 if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit)) {
3394 /* Not a suitable exit. Refuse it. */
3395 return 0;
3398 return 1;
3401 /** If address is of the form "y.onion" with a well-formed handle y:
3402 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
3404 * If address is of the form "x.y.onion" with a well-formed handle x:
3405 * Drop "x.", put a NUL after y, lower-case it, and return ONION_HOSTNAME.
3407 * If address is of the form "y.onion" with a badly-formed handle y:
3408 * Return BAD_HOSTNAME and log a message.
3410 * If address is of the form "y.exit":
3411 * Put a NUL after y and return EXIT_HOSTNAME.
3413 * Otherwise:
3414 * Return NORMAL_HOSTNAME and change nothing.
3416 hostname_type_t
3417 parse_extended_hostname(char *address)
3419 char *s;
3420 char *q;
3421 char query[REND_SERVICE_ID_LEN_BASE32+1];
3423 s = strrchr(address,'.');
3424 if (!s)
3425 return NORMAL_HOSTNAME; /* no dot, thus normal */
3426 if (!strcmp(s+1,"exit")) {
3427 *s = 0; /* NUL-terminate it */
3428 return EXIT_HOSTNAME; /* .exit */
3430 if (strcmp(s+1,"onion"))
3431 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
3433 /* so it is .onion */
3434 *s = 0; /* NUL-terminate it */
3435 /* locate a 'sub-domain' component, in order to remove it */
3436 q = strrchr(address, '.');
3437 if (q == address) {
3438 goto failed; /* reject sub-domain, as DNS does */
3440 q = (NULL == q) ? address : q + 1;
3441 if (strlcpy(query, q, REND_SERVICE_ID_LEN_BASE32+1) >=
3442 REND_SERVICE_ID_LEN_BASE32+1)
3443 goto failed;
3444 if (q != address) {
3445 memmove(address, q, strlen(q) + 1 /* also get \0 */);
3447 if (rend_valid_service_id(query)) {
3448 return ONION_HOSTNAME; /* success */
3450 failed:
3451 /* otherwise, return to previous state and return 0 */
3452 *s = '.';
3453 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
3454 safe_str_client(address));
3455 return BAD_HOSTNAME;
3458 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
3459 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
3460 * at <b>b</b>. */
3461 static int
3462 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
3464 if (a == NULL) {
3465 return (b == NULL);
3466 } else if (b == NULL) {
3467 return 0;
3468 } else if (alen != blen) {
3469 return 0;
3470 } else {
3471 return tor_memeq(a, b, alen);
3476 * Return true iff none of the isolation flags and fields in <b>conn</b>
3477 * should prevent it from being attached to <b>circ</b>.
3480 connection_edge_compatible_with_circuit(const entry_connection_t *conn,
3481 const origin_circuit_t *circ)
3483 const uint8_t iso = conn->entry_cfg.isolation_flags;
3484 const socks_request_t *sr = conn->socks_request;
3486 /* If circ has never been used for an isolated connection, we can
3487 * totally use it for this one. */
3488 if (!circ->isolation_values_set)
3489 return 1;
3491 /* If circ has been used for connections having more than one value
3492 * for some field f, it will have the corresponding bit set in
3493 * isolation_flags_mixed. If isolation_flags_mixed has any bits
3494 * in common with iso, then conn must be isolated from at least
3495 * one stream that has been attached to circ. */
3496 if ((iso & circ->isolation_flags_mixed) != 0) {
3497 /* For at least one field where conn is isolated, the circuit
3498 * already has mixed streams. */
3499 return 0;
3502 if (! conn->original_dest_address) {
3503 log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
3504 "having set conn->original_dest_address");
3505 ((entry_connection_t*)conn)->original_dest_address =
3506 tor_strdup(conn->socks_request->address);
3509 if ((iso & ISO_STREAM) &&
3510 (circ->associated_isolated_stream_global_id !=
3511 ENTRY_TO_CONN(conn)->global_identifier))
3512 return 0;
3514 if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
3515 return 0;
3516 if ((iso & ISO_DESTADDR) &&
3517 strcasecmp(conn->original_dest_address, circ->dest_address))
3518 return 0;
3519 if ((iso & ISO_SOCKSAUTH) &&
3520 (! memeq_opt(sr->username, sr->usernamelen,
3521 circ->socks_username, circ->socks_username_len) ||
3522 ! memeq_opt(sr->password, sr->passwordlen,
3523 circ->socks_password, circ->socks_password_len)))
3524 return 0;
3525 if ((iso & ISO_CLIENTPROTO) &&
3526 (conn->socks_request->listener_type != circ->client_proto_type ||
3527 conn->socks_request->socks_version != circ->client_proto_socksver))
3528 return 0;
3529 if ((iso & ISO_CLIENTADDR) &&
3530 !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
3531 return 0;
3532 if ((iso & ISO_SESSIONGRP) &&
3533 conn->entry_cfg.session_group != circ->session_group)
3534 return 0;
3535 if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
3536 return 0;
3538 return 1;
3542 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
3543 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
3544 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
3545 * a bitfield of isolation flags that we would have to set in
3546 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
3547 * <b>circ</b> has had no streams attached to it.
3550 connection_edge_update_circuit_isolation(const entry_connection_t *conn,
3551 origin_circuit_t *circ,
3552 int dry_run)
3554 const socks_request_t *sr = conn->socks_request;
3555 if (! conn->original_dest_address) {
3556 log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
3557 "having set conn->original_dest_address");
3558 ((entry_connection_t*)conn)->original_dest_address =
3559 tor_strdup(conn->socks_request->address);
3562 if (!circ->isolation_values_set) {
3563 if (dry_run)
3564 return -1;
3565 circ->associated_isolated_stream_global_id =
3566 ENTRY_TO_CONN(conn)->global_identifier;
3567 circ->dest_port = conn->socks_request->port;
3568 circ->dest_address = tor_strdup(conn->original_dest_address);
3569 circ->client_proto_type = conn->socks_request->listener_type;
3570 circ->client_proto_socksver = conn->socks_request->socks_version;
3571 tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
3572 circ->session_group = conn->entry_cfg.session_group;
3573 circ->nym_epoch = conn->nym_epoch;
3574 circ->socks_username = sr->username ?
3575 tor_memdup(sr->username, sr->usernamelen) : NULL;
3576 circ->socks_password = sr->password ?
3577 tor_memdup(sr->password, sr->passwordlen) : NULL;
3578 circ->socks_username_len = sr->usernamelen;
3579 circ->socks_password_len = sr->passwordlen;
3581 circ->isolation_values_set = 1;
3582 return 0;
3583 } else {
3584 uint8_t mixed = 0;
3585 if (conn->socks_request->port != circ->dest_port)
3586 mixed |= ISO_DESTPORT;
3587 if (strcasecmp(conn->original_dest_address, circ->dest_address))
3588 mixed |= ISO_DESTADDR;
3589 if (!memeq_opt(sr->username, sr->usernamelen,
3590 circ->socks_username, circ->socks_username_len) ||
3591 !memeq_opt(sr->password, sr->passwordlen,
3592 circ->socks_password, circ->socks_password_len))
3593 mixed |= ISO_SOCKSAUTH;
3594 if ((conn->socks_request->listener_type != circ->client_proto_type ||
3595 conn->socks_request->socks_version != circ->client_proto_socksver))
3596 mixed |= ISO_CLIENTPROTO;
3597 if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
3598 mixed |= ISO_CLIENTADDR;
3599 if (conn->entry_cfg.session_group != circ->session_group)
3600 mixed |= ISO_SESSIONGRP;
3601 if (conn->nym_epoch != circ->nym_epoch)
3602 mixed |= ISO_NYM_EPOCH;
3604 if (dry_run)
3605 return mixed;
3607 if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
3608 log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
3609 "isolation flags.");
3611 circ->isolation_flags_mixed |= mixed;
3612 return 0;
3617 * Clear the isolation settings on <b>circ</b>.
3619 * This only works on an open circuit that has never had a stream attached to
3620 * it, and whose isolation settings are hypothetical. (We set hypothetical
3621 * isolation settings on circuits as we're launching them, so that we
3622 * know whether they can handle more streams or whether we need to launch
3623 * even more circuits. Once the circuit is open, if it turns out that
3624 * we no longer have any streams to attach to it, we clear the isolation flags
3625 * and data so that other streams can have a chance.)
3627 void
3628 circuit_clear_isolation(origin_circuit_t *circ)
3630 if (circ->isolation_any_streams_attached) {
3631 log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
3632 return;
3634 if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
3635 log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
3636 "circuit");
3637 return;
3640 circ->isolation_values_set = 0;
3641 circ->isolation_flags_mixed = 0;
3642 circ->associated_isolated_stream_global_id = 0;
3643 circ->client_proto_type = 0;
3644 circ->client_proto_socksver = 0;
3645 circ->dest_port = 0;
3646 tor_addr_make_unspec(&circ->client_addr);
3647 tor_free(circ->dest_address);
3648 circ->session_group = -1;
3649 circ->nym_epoch = 0;
3650 if (circ->socks_username) {
3651 memwipe(circ->socks_username, 0x11, circ->socks_username_len);
3652 tor_free(circ->socks_username);
3654 if (circ->socks_password) {
3655 memwipe(circ->socks_password, 0x05, circ->socks_password_len);
3656 tor_free(circ->socks_password);
3658 circ->socks_username_len = circ->socks_password_len = 0;
3661 /** Free all storage held in module-scoped variables for connection_edge.c */
3662 void
3663 connection_edge_free_all(void)
3665 untried_pending_connections = 0;
3666 smartlist_free(pending_entry_connections);
3667 pending_entry_connections = NULL;