fix typo
[tor.git] / src / or / connection_edge.c
blob799baa2accd31d571d4874fe7038385a364194c6
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 /* XXXX 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 /* XXXX-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 uint8_t *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, (char *) cookie,
1707 auth_type);
1708 if (rend_data == NULL) {
1709 return -1;
1711 log_info(LD_REND,"Got a hidden service request for ID '%s'",
1712 safe_str_client(rend_data->onion_address));
1714 /* Lookup the given onion address. If invalid, stop right now else we
1715 * might have it in the cache or not, it will be tested later on. */
1716 unsigned int refetch_desc = 0;
1717 rend_cache_entry_t *entry = NULL;
1718 const int rend_cache_lookup_result =
1719 rend_cache_lookup_entry(rend_data->onion_address, -1, &entry);
1720 if (rend_cache_lookup_result < 0) {
1721 switch (-rend_cache_lookup_result) {
1722 case EINVAL:
1723 /* We should already have rejected this address! */
1724 log_warn(LD_BUG,"Invalid service name '%s'",
1725 safe_str_client(rend_data->onion_address));
1726 connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1727 return -1;
1728 case ENOENT:
1729 refetch_desc = 1;
1730 break;
1731 default:
1732 log_warn(LD_BUG, "Unknown cache lookup error %d",
1733 rend_cache_lookup_result);
1734 return -1;
1738 /* Help predict this next time. We're not sure if it will need
1739 * a stable circuit yet, but we know we'll need *something*. */
1740 rep_hist_note_used_internal(now, 0, 1);
1742 /* Now we have a descriptor but is it usable or not? If not, refetch.
1743 * Also, a fetch could have been requested if the onion address was not
1744 * found in the cache previously. */
1745 if (refetch_desc || !rend_client_any_intro_points_usable(entry)) {
1746 connection_ap_mark_as_non_pending_circuit(conn);
1747 base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1748 log_info(LD_REND, "Unknown descriptor %s. Fetching.",
1749 safe_str_client(rend_data->onion_address));
1750 rend_client_refetch_v2_renddesc(rend_data);
1751 return 0;
1754 /* We have the descriptor so launch a connection to the HS. */
1755 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1756 log_info(LD_REND, "Descriptor is here. Great.");
1757 connection_ap_mark_as_pending_circuit(conn);
1758 return 0;
1761 return 0; /* unreached but keeps the compiler happy */
1764 #ifdef TRANS_PF
1765 static int pf_socket = -1;
1767 get_pf_socket(void)
1769 int pf;
1770 /* This should be opened before dropping privileges. */
1771 if (pf_socket >= 0)
1772 return pf_socket;
1774 #ifdef OPENBSD
1775 /* only works on OpenBSD */
1776 pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
1777 #else
1778 /* works on NetBSD and FreeBSD */
1779 pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
1780 #endif
1782 if (pf < 0) {
1783 log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
1784 return -1;
1787 pf_socket = pf;
1788 return pf_socket;
1790 #endif
1792 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || defined(TRANS_TPROXY)
1793 /** Try fill in the address of <b>req</b> from the socket configured
1794 * with <b>conn</b>. */
1795 static int
1796 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
1798 struct sockaddr_storage orig_dst;
1799 socklen_t orig_dst_len = sizeof(orig_dst);
1800 tor_addr_t addr;
1802 #ifdef TRANS_TRPOXY
1803 if (options->TransProxyType_parsed == TPT_TPROXY) {
1804 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
1805 &orig_dst_len) < 0) {
1806 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1807 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
1808 return -1;
1810 goto done;
1812 #endif
1814 #ifdef TRANS_NETFILTER
1815 int rv = -1;
1816 switch (ENTRY_TO_CONN(conn)->socket_family) {
1817 #ifdef TRANS_NETFILTER_IPV4
1818 case AF_INET:
1819 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
1820 (struct sockaddr*)&orig_dst, &orig_dst_len);
1821 break;
1822 #endif
1823 #ifdef TRANS_NETFILTER_IPV6
1824 case AF_INET6:
1825 rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
1826 (struct sockaddr*)&orig_dst, &orig_dst_len);
1827 break;
1828 #endif
1829 default:
1830 log_warn(LD_BUG,
1831 "Received transparent data from an unsuported socket family %d",
1832 ENTRY_TO_CONN(conn)->socket_family);
1833 return -1;
1835 if (rv < 0) {
1836 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1837 log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
1838 return -1;
1840 goto done;
1841 #elif defined(TRANS_PF)
1842 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
1843 &orig_dst_len) < 0) {
1844 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1845 log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
1846 return -1;
1848 goto done;
1849 #else
1850 (void)conn;
1851 (void)req;
1852 log_warn(LD_BUG, "Unable to determine destination from socket.");
1853 return -1;
1854 #endif
1856 done:
1857 tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
1858 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
1860 return 0;
1862 #endif
1864 #ifdef TRANS_PF
1865 static int
1866 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
1868 struct sockaddr_storage proxy_addr;
1869 socklen_t proxy_addr_len = sizeof(proxy_addr);
1870 struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
1871 struct pfioc_natlook pnl;
1872 tor_addr_t addr;
1873 int pf = -1;
1875 if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
1876 &proxy_addr_len) < 0) {
1877 int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
1878 log_warn(LD_NET, "getsockname() to determine transocks destination "
1879 "failed: %s", tor_socket_strerror(e));
1880 return -1;
1883 #ifdef __FreeBSD__
1884 if (get_options()->TransProxyType_parsed == TPT_IPFW) {
1885 /* ipfw(8) is used and in this case getsockname returned the original
1886 destination */
1887 if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
1888 tor_fragile_assert();
1889 return -1;
1892 tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
1894 return 0;
1896 #endif
1898 memset(&pnl, 0, sizeof(pnl));
1899 pnl.proto = IPPROTO_TCP;
1900 pnl.direction = PF_OUT;
1901 if (proxy_sa->sa_family == AF_INET) {
1902 struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
1903 pnl.af = AF_INET;
1904 pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
1905 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
1906 pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
1907 pnl.dport = sin->sin_port;
1908 } else if (proxy_sa->sa_family == AF_INET6) {
1909 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
1910 pnl.af = AF_INET6;
1911 memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
1912 sizeof(struct in6_addr));
1913 pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
1914 memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
1915 pnl.dport = sin6->sin6_port;
1916 } else {
1917 log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
1918 (int)proxy_sa->sa_family);
1919 return -1;
1922 pf = get_pf_socket();
1923 if (pf<0)
1924 return -1;
1926 if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
1927 log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
1928 return -1;
1931 if (pnl.af == AF_INET) {
1932 tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
1933 } else if (pnl.af == AF_INET6) {
1934 tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
1935 } else {
1936 tor_fragile_assert();
1937 return -1;
1940 tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
1941 req->port = ntohs(pnl.rdport);
1943 return 0;
1945 #endif
1947 /** Fetch the original destination address and port from a
1948 * system-specific interface and put them into a
1949 * socks_request_t as if they came from a socks request.
1951 * Return -1 if an error prevents fetching the destination,
1952 * else return 0.
1954 static int
1955 connection_ap_get_original_destination(entry_connection_t *conn,
1956 socks_request_t *req)
1958 #ifdef TRANS_NETFILTER
1959 return destination_from_socket(conn, req);
1960 #elif defined(TRANS_PF)
1961 const or_options_t *options = get_options();
1963 if (options->TransProxyType_parsed == TPT_PF_DIVERT)
1964 return destination_from_socket(conn, req);
1966 if (options->TransProxyType_parsed == TPT_DEFAULT ||
1967 options->TransProxyType_parsed == TPT_IPFW)
1968 return destination_from_pf(conn, req);
1970 (void)conn;
1971 (void)req;
1972 log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
1973 options->TransProxyType);
1974 return -1;
1975 #else
1976 (void)conn;
1977 (void)req;
1978 log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
1979 "transparent proxy method was configured.");
1980 return -1;
1981 #endif
1984 /** connection_edge_process_inbuf() found a conn in state
1985 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1986 * the socks handshake.
1988 * If the handshake is complete, send it to
1989 * connection_ap_handshake_rewrite_and_attach().
1991 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1992 * else return 0.
1994 static int
1995 connection_ap_handshake_process_socks(entry_connection_t *conn)
1997 socks_request_t *socks;
1998 int sockshere;
1999 const or_options_t *options = get_options();
2000 int had_reply = 0;
2001 connection_t *base_conn = ENTRY_TO_CONN(conn);
2003 tor_assert(conn);
2004 tor_assert(base_conn->type == CONN_TYPE_AP);
2005 tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
2006 tor_assert(conn->socks_request);
2007 socks = conn->socks_request;
2009 log_debug(LD_APP,"entered.");
2011 IF_HAS_BUFFEREVENT(base_conn, {
2012 struct evbuffer *input = bufferevent_get_input(base_conn->bufev);
2013 sockshere = fetch_from_evbuffer_socks(input, socks,
2014 options->TestSocks, options->SafeSocks);
2015 }) ELSE_IF_NO_BUFFEREVENT {
2016 sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2017 options->TestSocks, options->SafeSocks);
2020 if (socks->replylen) {
2021 had_reply = 1;
2022 connection_write_to_buf((const char*)socks->reply, socks->replylen,
2023 base_conn);
2024 socks->replylen = 0;
2025 if (sockshere == -1) {
2026 /* An invalid request just got a reply, no additional
2027 * one is necessary. */
2028 socks->has_finished = 1;
2032 if (sockshere == 0) {
2033 log_debug(LD_APP,"socks handshake not all here yet.");
2034 return 0;
2035 } else if (sockshere == -1) {
2036 if (!had_reply) {
2037 log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2038 connection_ap_handshake_socks_reply(conn, NULL, 0,
2039 END_STREAM_REASON_SOCKSPROTOCOL);
2041 connection_mark_unattached_ap(conn,
2042 END_STREAM_REASON_SOCKSPROTOCOL |
2043 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED);
2044 return -1;
2045 } /* else socks handshake is done, continue processing */
2047 if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2048 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2049 else
2050 control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2052 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2055 /** connection_init_accepted_conn() found a new trans AP conn.
2056 * Get the original destination and send it to
2057 * connection_ap_handshake_rewrite_and_attach().
2059 * Return -1 if an unexpected error with conn (and it should be marked
2060 * for close), else return 0.
2063 connection_ap_process_transparent(entry_connection_t *conn)
2065 socks_request_t *socks;
2067 tor_assert(conn);
2068 tor_assert(conn->socks_request);
2069 socks = conn->socks_request;
2071 /* pretend that a socks handshake completed so we don't try to
2072 * send a socks reply down a transparent conn */
2073 socks->command = SOCKS_COMMAND_CONNECT;
2074 socks->has_finished = 1;
2076 log_debug(LD_APP,"entered.");
2078 if (connection_ap_get_original_destination(conn, socks) < 0) {
2079 log_warn(LD_APP,"Fetching original destination failed. Closing.");
2080 connection_mark_unattached_ap(conn,
2081 END_STREAM_REASON_CANT_FETCH_ORIG_DEST);
2082 return -1;
2084 /* we have the original destination */
2086 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2088 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2091 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2092 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2093 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2094 * form of the original destination.
2096 * If the original destination is complete, send it to
2097 * connection_ap_handshake_rewrite_and_attach().
2099 * Return -1 if an unexpected error with conn (and it should be marked
2100 * for close), else return 0.
2102 static int
2103 connection_ap_process_natd(entry_connection_t *conn)
2105 char tmp_buf[36], *tbuf, *daddr;
2106 size_t tlen = 30;
2107 int err, port_ok;
2108 socks_request_t *socks;
2110 tor_assert(conn);
2111 tor_assert(ENTRY_TO_CONN(conn)->state == AP_CONN_STATE_NATD_WAIT);
2112 tor_assert(conn->socks_request);
2113 socks = conn->socks_request;
2115 log_debug(LD_APP,"entered.");
2117 /* look for LF-terminated "[DEST ip_addr port]"
2118 * where ip_addr is a dotted-quad and port is in string form */
2119 err = connection_fetch_from_buf_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2120 if (err == 0)
2121 return 0;
2122 if (err < 0) {
2123 log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2124 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2125 return -1;
2128 if (strcmpstart(tmp_buf, "[DEST ")) {
2129 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2130 "said: %s",
2131 escaped(tmp_buf));
2132 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2133 return -1;
2136 daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2137 if (!(tbuf = strchr(tbuf, ' '))) {
2138 log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2139 "said: %s",
2140 escaped(tmp_buf));
2141 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2142 return -1;
2144 *tbuf++ = '\0';
2146 /* pretend that a socks handshake completed so we don't try to
2147 * send a socks reply down a natd conn */
2148 strlcpy(socks->address, daddr, sizeof(socks->address));
2149 socks->port = (uint16_t)
2150 tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2151 if (!port_ok) {
2152 log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2153 "of range.", escaped(tbuf));
2154 connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2155 return -1;
2158 socks->command = SOCKS_COMMAND_CONNECT;
2159 socks->has_finished = 1;
2161 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2163 ENTRY_TO_CONN(conn)->state = AP_CONN_STATE_CIRCUIT_WAIT;
2165 return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2168 /** Iterate over the two bytes of stream_id until we get one that is not
2169 * already in use; return it. Return 0 if can't get a unique stream_id.
2171 streamid_t
2172 get_unique_stream_id_by_circ(origin_circuit_t *circ)
2174 edge_connection_t *tmpconn;
2175 streamid_t test_stream_id;
2176 uint32_t attempts=0;
2178 again:
2179 test_stream_id = circ->next_stream_id++;
2180 if (++attempts > 1<<16) {
2181 /* Make sure we don't loop forever if all stream_id's are used. */
2182 log_warn(LD_APP,"No unused stream IDs. Failing.");
2183 return 0;
2185 if (test_stream_id == 0)
2186 goto again;
2187 for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2188 if (tmpconn->stream_id == test_stream_id)
2189 goto again;
2190 return test_stream_id;
2193 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
2194 * an exit that supports optimistic data. */
2195 static int
2196 connection_ap_supports_optimistic_data(const entry_connection_t *conn)
2198 const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2199 /* We can only send optimistic data if we're connected to an open
2200 general circuit. */
2201 if (edge_conn->on_circuit == NULL ||
2202 edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
2203 (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
2204 edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_REND_JOINED))
2205 return 0;
2207 return conn->may_use_optimistic_data;
2210 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
2211 * RELAY_BEGIN cell for <b>ap_conn</b>. */
2212 static uint32_t
2213 connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
2215 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2216 const node_t *exitnode = NULL;
2217 const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
2218 uint32_t flags = 0;
2220 /* No flags for begindir */
2221 if (ap_conn->use_begindir)
2222 return 0;
2224 /* No flags for hidden services. */
2225 if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
2226 return 0;
2228 /* If only IPv4 is supported, no flags */
2229 if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
2230 return 0;
2232 if (! cpath_layer ||
2233 ! cpath_layer->extend_info)
2234 return 0;
2236 if (!ap_conn->entry_cfg.ipv4_traffic)
2237 flags |= BEGIN_FLAG_IPV4_NOT_OK;
2239 exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
2241 if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
2242 tor_addr_t a;
2243 tor_addr_make_null(&a, AF_INET6);
2244 if (compare_tor_addr_to_node_policy(&a, ap_conn->socks_request->port,
2245 exitnode)
2246 != ADDR_POLICY_REJECTED) {
2247 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
2248 * no point. */
2249 flags |= BEGIN_FLAG_IPV6_OK;
2253 if (flags == BEGIN_FLAG_IPV6_OK) {
2254 /* When IPv4 and IPv6 are both allowed, consider whether to say we
2255 * prefer IPv6. Otherwise there's no point in declaring a preference */
2256 if (ap_conn->entry_cfg.prefer_ipv6)
2257 flags |= BEGIN_FLAG_IPV6_PREFERRED;
2260 if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
2261 log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
2262 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
2263 "not going to work. Did you perhaps ask for an IPv6 address "
2264 "on an IPv4Only port, or vice versa?");
2267 return flags;
2270 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2271 * socks_request field, and send it down circ.
2273 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2276 connection_ap_handshake_send_begin(entry_connection_t *ap_conn)
2278 char payload[CELL_PAYLOAD_SIZE];
2279 int payload_len;
2280 int begin_type;
2281 origin_circuit_t *circ;
2282 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2283 connection_t *base_conn = TO_CONN(edge_conn);
2284 tor_assert(edge_conn->on_circuit);
2285 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
2287 tor_assert(base_conn->type == CONN_TYPE_AP);
2288 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2289 tor_assert(ap_conn->socks_request);
2290 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
2292 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
2293 if (edge_conn->stream_id==0) {
2294 /* XXXX+ Instead of closing this stream, we should make it get
2295 * retried on another circuit. */
2296 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2298 /* Mark this circuit "unusable for new streams". */
2299 mark_circuit_unusable_for_new_conns(circ);
2300 return -1;
2303 /* Set up begin cell flags. */
2304 edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
2306 tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
2307 (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
2308 ap_conn->socks_request->address : "",
2309 ap_conn->socks_request->port);
2310 payload_len = (int)strlen(payload)+1;
2311 if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
2312 set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
2313 payload_len += 4;
2316 log_info(LD_APP,
2317 "Sending relay cell %d on circ %u to begin stream %d.",
2318 (int)ap_conn->use_begindir,
2319 (unsigned)circ->base_.n_circ_id,
2320 edge_conn->stream_id);
2322 begin_type = ap_conn->use_begindir ?
2323 RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
2324 if (begin_type == RELAY_COMMAND_BEGIN) {
2325 #ifndef NON_ANONYMOUS_MODE_ENABLED
2326 tor_assert(circ->build_state->onehop_tunnel == 0);
2327 #endif
2330 if (connection_edge_send_command(edge_conn, begin_type,
2331 begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
2332 begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
2333 return -1; /* circuit is closed, don't continue */
2335 edge_conn->package_window = STREAMWINDOW_START;
2336 edge_conn->deliver_window = STREAMWINDOW_START;
2337 base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
2338 log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
2339 ", n_circ_id %u",
2340 base_conn->s, (unsigned)circ->base_.n_circ_id);
2341 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
2343 /* If there's queued-up data, send it now */
2344 if ((connection_get_inbuf_len(base_conn) ||
2345 ap_conn->sending_optimistic_data) &&
2346 connection_ap_supports_optimistic_data(ap_conn)) {
2347 log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
2348 (long)connection_get_inbuf_len(base_conn),
2349 ap_conn->sending_optimistic_data ?
2350 (long)generic_buffer_len(ap_conn->sending_optimistic_data) : 0);
2351 if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
2352 connection_mark_for_close(base_conn);
2356 return 0;
2359 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2360 * socks_request field, and send it down circ.
2362 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2365 connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
2367 int payload_len, command;
2368 const char *string_addr;
2369 char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
2370 origin_circuit_t *circ;
2371 edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2372 connection_t *base_conn = TO_CONN(edge_conn);
2373 tor_assert(edge_conn->on_circuit);
2374 circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
2376 tor_assert(base_conn->type == CONN_TYPE_AP);
2377 tor_assert(base_conn->state == AP_CONN_STATE_CIRCUIT_WAIT);
2378 tor_assert(ap_conn->socks_request);
2379 tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL);
2381 command = ap_conn->socks_request->command;
2382 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
2384 edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
2385 if (edge_conn->stream_id==0) {
2386 /* XXXX+ Instead of closing this stream, we should make it get
2387 * retried on another circuit. */
2388 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2390 /* Mark this circuit "unusable for new streams". */
2391 mark_circuit_unusable_for_new_conns(circ);
2392 return -1;
2395 if (command == SOCKS_COMMAND_RESOLVE) {
2396 string_addr = ap_conn->socks_request->address;
2397 payload_len = (int)strlen(string_addr)+1;
2398 } else {
2399 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2400 const char *a = ap_conn->socks_request->address;
2401 tor_addr_t addr;
2402 int r;
2404 /* We're doing a reverse lookup. The input could be an IP address, or
2405 * could be an .in-addr.arpa or .ip6.arpa address */
2406 r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
2407 if (r <= 0) {
2408 log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
2409 safe_str_client(a));
2410 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2411 return -1;
2414 r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
2415 if (r < 0) {
2416 log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
2417 safe_str_client(a));
2418 connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
2419 return -1;
2422 string_addr = inaddr_buf;
2423 payload_len = (int)strlen(inaddr_buf)+1;
2424 tor_assert(payload_len <= (int)sizeof(inaddr_buf));
2427 log_debug(LD_APP,
2428 "Sending relay cell to begin stream %d.", edge_conn->stream_id);
2430 if (connection_edge_send_command(edge_conn,
2431 RELAY_COMMAND_RESOLVE,
2432 string_addr, payload_len) < 0)
2433 return -1; /* circuit is closed, don't continue */
2435 if (!base_conn->address) {
2436 /* This might be unnecessary. XXXX */
2437 base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
2439 base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
2440 log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
2441 ", n_circ_id %u",
2442 base_conn->s, (unsigned)circ->base_.n_circ_id);
2443 control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
2444 return 0;
2447 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
2448 * new linked connection pair, and attach one side to the conn, connection_add
2449 * it, initialize it to circuit_wait, and call
2450 * connection_ap_handshake_attach_circuit(conn) on it.
2452 * Return the newly created end of the linked connection pair, or -1 if error.
2454 entry_connection_t *
2455 connection_ap_make_link(connection_t *partner,
2456 char *address, uint16_t port,
2457 const char *digest,
2458 int session_group, int isolation_flags,
2459 int use_begindir, int want_onehop)
2461 entry_connection_t *conn;
2462 connection_t *base_conn;
2464 log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
2465 want_onehop ? "direct" : "anonymized",
2466 safe_str_client(address), port);
2468 conn = entry_connection_new(CONN_TYPE_AP, tor_addr_family(&partner->addr));
2469 base_conn = ENTRY_TO_CONN(conn);
2470 base_conn->linked = 1; /* so that we can add it safely below. */
2472 /* populate conn->socks_request */
2474 /* leave version at zero, so the socks_reply is empty */
2475 conn->socks_request->socks_version = 0;
2476 conn->socks_request->has_finished = 0; /* waiting for 'connected' */
2477 strlcpy(conn->socks_request->address, address,
2478 sizeof(conn->socks_request->address));
2479 conn->socks_request->port = port;
2480 conn->socks_request->command = SOCKS_COMMAND_CONNECT;
2481 conn->want_onehop = want_onehop;
2482 conn->use_begindir = use_begindir;
2483 if (use_begindir) {
2484 conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
2485 conn->chosen_exit_name[0] = '$';
2486 tor_assert(digest);
2487 base16_encode(conn->chosen_exit_name+1,HEX_DIGEST_LEN+1,
2488 digest, DIGEST_LEN);
2491 /* Populate isolation fields. */
2492 conn->socks_request->listener_type = CONN_TYPE_DIR_LISTENER;
2493 conn->original_dest_address = tor_strdup(address);
2494 conn->entry_cfg.session_group = session_group;
2495 conn->entry_cfg.isolation_flags = isolation_flags;
2497 base_conn->address = tor_strdup("(Tor_internal)");
2498 tor_addr_make_unspec(&base_conn->addr);
2499 base_conn->port = 0;
2501 connection_link_connections(partner, base_conn);
2503 if (connection_add(base_conn) < 0) { /* no space, forget it */
2504 connection_free(base_conn);
2505 return NULL;
2508 base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2510 control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2512 /* attaching to a dirty circuit is fine */
2513 connection_ap_mark_as_pending_circuit(conn);
2514 log_info(LD_APP,"... application connection created and linked.");
2515 return conn;
2518 /** Notify any interested controller connections about a new hostname resolve
2519 * or resolve error. Takes the same arguments as does
2520 * connection_ap_handshake_socks_resolved(). */
2521 static void
2522 tell_controller_about_resolved_result(entry_connection_t *conn,
2523 int answer_type,
2524 size_t answer_len,
2525 const char *answer,
2526 int ttl,
2527 time_t expires)
2529 expires = time(NULL) + ttl;
2530 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
2531 char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
2532 control_event_address_mapped(conn->socks_request->address,
2533 cp, expires, NULL, 0);
2534 tor_free(cp);
2535 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2536 char *cp = tor_strndup(answer, answer_len);
2537 control_event_address_mapped(conn->socks_request->address,
2538 cp, expires, NULL, 0);
2539 tor_free(cp);
2540 } else {
2541 control_event_address_mapped(conn->socks_request->address,
2542 "<error>", time(NULL)+ttl,
2543 "error=yes", 0);
2548 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
2549 * as the answer.
2551 void
2552 connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn,
2553 const tor_addr_t *answer,
2554 int ttl,
2555 time_t expires)
2557 if (tor_addr_family(answer) == AF_INET) {
2558 uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
2559 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
2560 (uint8_t*)&a,
2561 ttl, expires);
2562 } else if (tor_addr_family(answer) == AF_INET6) {
2563 const uint8_t *a = tor_addr_to_in6_addr8(answer);
2564 connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
2566 ttl, expires);
2567 } else {
2568 log_warn(LD_BUG, "Got called with address of unexpected family %d",
2569 tor_addr_family(answer));
2570 connection_ap_handshake_socks_resolved(conn,
2571 RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
2575 /** Send an answer to an AP connection that has requested a DNS lookup via
2576 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2577 * for unreachable; the answer should be in the format specified in the socks
2578 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2579 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2580 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2582 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
2583 * interface and those that use it less ugly. */
2584 MOCK_IMPL(void,
2585 connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
2586 int answer_type,
2587 size_t answer_len,
2588 const uint8_t *answer,
2589 int ttl,
2590 time_t expires))
2592 char buf[384];
2593 size_t replylen;
2595 if (ttl >= 0) {
2596 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2597 tor_addr_t a;
2598 tor_addr_from_ipv4n(&a, get_uint32(answer));
2599 if (! tor_addr_is_null(&a)) {
2600 client_dns_set_addressmap(conn,
2601 conn->socks_request->address, &a,
2602 conn->chosen_exit_name, ttl);
2604 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2605 tor_addr_t a;
2606 tor_addr_from_ipv6_bytes(&a, (char*)answer);
2607 if (! tor_addr_is_null(&a)) {
2608 client_dns_set_addressmap(conn,
2609 conn->socks_request->address, &a,
2610 conn->chosen_exit_name, ttl);
2612 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2613 char *cp = tor_strndup((char*)answer, answer_len);
2614 client_dns_set_reverse_addressmap(conn,
2615 conn->socks_request->address,
2617 conn->chosen_exit_name, ttl);
2618 tor_free(cp);
2622 if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
2623 if (conn->dns_server_request) {
2624 /* We had a request on our DNS port: answer it. */
2625 dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
2626 conn->socks_request->has_finished = 1;
2627 return;
2628 } else {
2629 /* This must be a request from the controller. Since answers to those
2630 * requests are not cached, they do not generate an ADDRMAP event on
2631 * their own. */
2632 tell_controller_about_resolved_result(conn, answer_type, answer_len,
2633 (char*)answer, ttl, expires);
2634 conn->socks_request->has_finished = 1;
2635 return;
2637 /* We shouldn't need to free conn here; it gets marked by the caller. */
2640 if (conn->socks_request->socks_version == 4) {
2641 buf[0] = 0x00; /* version */
2642 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2643 buf[1] = SOCKS4_GRANTED;
2644 set_uint16(buf+2, 0);
2645 memcpy(buf+4, answer, 4); /* address */
2646 replylen = SOCKS4_NETWORK_LEN;
2647 } else { /* "error" */
2648 buf[1] = SOCKS4_REJECT;
2649 memset(buf+2, 0, 6);
2650 replylen = SOCKS4_NETWORK_LEN;
2652 } else if (conn->socks_request->socks_version == 5) {
2653 /* SOCKS5 */
2654 buf[0] = 0x05; /* version */
2655 if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
2656 buf[1] = SOCKS5_SUCCEEDED;
2657 buf[2] = 0; /* reserved */
2658 buf[3] = 0x01; /* IPv4 address type */
2659 memcpy(buf+4, answer, 4); /* address */
2660 set_uint16(buf+8, 0); /* port == 0. */
2661 replylen = 10;
2662 } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
2663 buf[1] = SOCKS5_SUCCEEDED;
2664 buf[2] = 0; /* reserved */
2665 buf[3] = 0x04; /* IPv6 address type */
2666 memcpy(buf+4, answer, 16); /* address */
2667 set_uint16(buf+20, 0); /* port == 0. */
2668 replylen = 22;
2669 } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
2670 buf[1] = SOCKS5_SUCCEEDED;
2671 buf[2] = 0; /* reserved */
2672 buf[3] = 0x03; /* Domainname address type */
2673 buf[4] = (char)answer_len;
2674 memcpy(buf+5, answer, answer_len); /* address */
2675 set_uint16(buf+5+answer_len, 0); /* port == 0. */
2676 replylen = 5+answer_len+2;
2677 } else {
2678 buf[1] = SOCKS5_HOST_UNREACHABLE;
2679 memset(buf+2, 0, 8);
2680 replylen = 10;
2682 } else {
2683 /* no socks version info; don't send anything back */
2684 return;
2686 connection_ap_handshake_socks_reply(conn, buf, replylen,
2687 (answer_type == RESOLVED_TYPE_IPV4 ||
2688 answer_type == RESOLVED_TYPE_IPV6 ||
2689 answer_type == RESOLVED_TYPE_HOSTNAME) ?
2690 0 : END_STREAM_REASON_RESOLVEFAILED);
2693 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2694 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2695 * handshaking.
2697 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2698 * and return, else reply based on <b>endreason</b> (one of
2699 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2700 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2702 void
2703 connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply,
2704 size_t replylen, int endreason)
2706 char buf[256];
2707 socks5_reply_status_t status =
2708 stream_end_reason_to_socks5_response(endreason);
2710 tor_assert(conn->socks_request); /* make sure it's an AP stream */
2712 if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
2713 control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
2714 STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
2715 endreason);
2718 /* Flag this stream's circuit as having completed a stream successfully
2719 * (for path bias) */
2720 if (status == SOCKS5_SUCCEEDED ||
2721 endreason == END_STREAM_REASON_RESOLVEFAILED ||
2722 endreason == END_STREAM_REASON_CONNECTREFUSED ||
2723 endreason == END_STREAM_REASON_CONNRESET ||
2724 endreason == END_STREAM_REASON_NOROUTE ||
2725 endreason == END_STREAM_REASON_RESOURCELIMIT) {
2726 if (!conn->edge_.on_circuit ||
2727 !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
2728 if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
2729 log_info(LD_BUG,
2730 "No origin circuit for successful SOCKS stream "U64_FORMAT
2731 ". Reason: %d",
2732 U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
2733 endreason);
2736 * Else DNS remaps and failed hidden service lookups can send us
2737 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
2739 * Perhaps we could make the test more precise; we can tell hidden
2740 * services by conn->edge_.renddata != NULL; anything analogous for
2741 * the DNS remap case?
2743 } else {
2744 // XXX: Hrmm. It looks like optimistic data can't go through this
2745 // codepath, but someone should probably test it and make sure.
2746 // We don't want to mark optimistically opened streams as successful.
2747 pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn->edge_.on_circuit));
2751 if (conn->socks_request->has_finished) {
2752 log_warn(LD_BUG, "(Harmless.) duplicate calls to "
2753 "connection_ap_handshake_socks_reply.");
2754 return;
2756 if (replylen) { /* we already have a reply in mind */
2757 connection_write_to_buf(reply, replylen, ENTRY_TO_CONN(conn));
2758 conn->socks_request->has_finished = 1;
2759 return;
2761 if (conn->socks_request->socks_version == 4) {
2762 memset(buf,0,SOCKS4_NETWORK_LEN);
2763 buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
2764 /* leave version, destport, destip zero */
2765 connection_write_to_buf(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
2766 } else if (conn->socks_request->socks_version == 5) {
2767 size_t buf_len;
2768 memset(buf,0,sizeof(buf));
2769 if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
2770 buf[0] = 5; /* version 5 */
2771 buf[1] = (char)status;
2772 buf[2] = 0;
2773 buf[3] = 1; /* ipv4 addr */
2774 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
2775 buf_len = 10;
2776 } else { /* AF_INET6. */
2777 buf[0] = 5; /* version 5 */
2778 buf[1] = (char)status;
2779 buf[2] = 0;
2780 buf[3] = 4; /* ipv6 addr */
2781 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
2782 buf_len = 22;
2784 connection_write_to_buf(buf,buf_len,ENTRY_TO_CONN(conn));
2786 /* If socks_version isn't 4 or 5, don't send anything.
2787 * This can happen in the case of AP bridges. */
2788 conn->socks_request->has_finished = 1;
2789 return;
2792 /** Read a RELAY_BEGIN or RELAY_BEGINDIR cell from <b>cell</b>, decode it, and
2793 * place the result in <b>bcell</b>. On success return 0; on failure return
2794 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
2795 * the client.
2797 * Return -1 in the case where want to send a RELAY_END cell, and < -1 when
2798 * we don't.
2800 STATIC int
2801 begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
2802 uint8_t *end_reason_out)
2804 relay_header_t rh;
2805 const uint8_t *body, *nul;
2807 memset(bcell, 0, sizeof(*bcell));
2808 *end_reason_out = END_STREAM_REASON_MISC;
2810 relay_header_unpack(&rh, cell->payload);
2811 if (rh.length > RELAY_PAYLOAD_SIZE) {
2812 return -2; /*XXXX why not TORPROTOCOL? */
2815 bcell->stream_id = rh.stream_id;
2817 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2818 bcell->is_begindir = 1;
2819 return 0;
2820 } else if (rh.command != RELAY_COMMAND_BEGIN) {
2821 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2822 *end_reason_out = END_STREAM_REASON_INTERNAL;
2823 return -1;
2826 body = cell->payload + RELAY_HEADER_SIZE;
2827 nul = memchr(body, 0, rh.length);
2828 if (! nul) {
2829 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2830 "Relay begin cell has no \\0. Closing.");
2831 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
2832 return -1;
2835 if (tor_addr_port_split(LOG_PROTOCOL_WARN,
2836 (char*)(body),
2837 &bcell->address,&bcell->port)<0) {
2838 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2839 "Unable to parse addr:port in relay begin cell. Closing.");
2840 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
2841 return -1;
2843 if (bcell->port == 0) {
2844 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2845 "Missing port in relay begin cell. Closing.");
2846 tor_free(bcell->address);
2847 *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
2848 return -1;
2850 if (body + rh.length >= nul + 4)
2851 bcell->flags = ntohl(get_uint32(nul+1));
2853 return 0;
2856 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2857 * an exit hop for the circuit, or we are the origin and it is a
2858 * rendezvous begin.
2860 * Launch a new exit connection and initialize things appropriately.
2862 * If it's a rendezvous stream, call connection_exit_connect() on
2863 * it.
2865 * For general streams, call dns_resolve() on it first, and only call
2866 * connection_exit_connect() if the dns answer is already known.
2868 * Note that we don't call connection_add() on the new stream! We wait
2869 * for connection_exit_connect() to do that.
2871 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2872 * Else return 0.
2875 connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
2877 edge_connection_t *n_stream;
2878 relay_header_t rh;
2879 char *address = NULL;
2880 uint16_t port = 0;
2881 or_circuit_t *or_circ = NULL;
2882 const or_options_t *options = get_options();
2883 begin_cell_t bcell;
2884 int r;
2885 uint8_t end_reason=0;
2887 assert_circuit_ok(circ);
2888 if (!CIRCUIT_IS_ORIGIN(circ))
2889 or_circ = TO_OR_CIRCUIT(circ);
2891 relay_header_unpack(&rh, cell->payload);
2892 if (rh.length > RELAY_PAYLOAD_SIZE)
2893 return -END_CIRC_REASON_TORPROTOCOL;
2895 /* Note: we have to use relay_send_command_from_edge here, not
2896 * connection_edge_end or connection_edge_send_command, since those require
2897 * that we have a stream connected to a circuit, and we don't connect to a
2898 * circuit until we have a pending/successful resolve. */
2900 if (!server_mode(options) &&
2901 circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
2902 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2903 "Relay begin cell at non-server. Closing.");
2904 relay_send_end_cell_from_edge(rh.stream_id, circ,
2905 END_STREAM_REASON_EXITPOLICY, NULL);
2906 return 0;
2909 r = begin_cell_parse(cell, &bcell, &end_reason);
2910 if (r < -1) {
2911 return -END_CIRC_REASON_TORPROTOCOL;
2912 } else if (r == -1) {
2913 tor_free(bcell.address);
2914 relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, NULL);
2915 return 0;
2918 if (! bcell.is_begindir) {
2919 /* Steal reference */
2920 address = bcell.address;
2921 port = bcell.port;
2923 if (or_circ && or_circ->p_chan) {
2924 if (!options->AllowSingleHopExits &&
2925 (or_circ->is_first_hop ||
2926 (!connection_or_digest_is_known_relay(
2927 or_circ->p_chan->identity_digest) &&
2928 should_refuse_unknown_exits(options)))) {
2929 /* Don't let clients use us as a single-hop proxy, unless the user
2930 * has explicitly allowed that in the config. It attracts attackers
2931 * and users who'd be better off with, well, single-hop proxies.
2933 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
2934 "Attempt by %s to open a stream %s. Closing.",
2935 safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
2936 or_circ->is_first_hop ? "on first hop of circuit" :
2937 "from unknown relay");
2938 relay_send_end_cell_from_edge(rh.stream_id, circ,
2939 or_circ->is_first_hop ?
2940 END_STREAM_REASON_TORPROTOCOL :
2941 END_STREAM_REASON_MISC,
2942 NULL);
2943 tor_free(address);
2944 return 0;
2947 } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
2948 if (!directory_permits_begindir_requests(options) ||
2949 circ->purpose != CIRCUIT_PURPOSE_OR) {
2950 relay_send_end_cell_from_edge(rh.stream_id, circ,
2951 END_STREAM_REASON_NOTDIRECTORY, NULL);
2952 return 0;
2954 /* Make sure to get the 'real' address of the previous hop: the
2955 * caller might want to know whether the remote IP address has changed,
2956 * and we might already have corrected base_.addr[ess] for the relay's
2957 * canonical IP address. */
2958 if (or_circ && or_circ->p_chan)
2959 address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
2960 else
2961 address = tor_strdup("127.0.0.1");
2962 port = 1; /* XXXX This value is never actually used anywhere, and there
2963 * isn't "really" a connection here. But we
2964 * need to set it to something nonzero. */
2965 } else {
2966 log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
2967 relay_send_end_cell_from_edge(rh.stream_id, circ,
2968 END_STREAM_REASON_INTERNAL, NULL);
2969 return 0;
2972 if (! options->IPv6Exit) {
2973 /* I don't care if you prefer IPv6; I can't give you any. */
2974 bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
2975 /* If you don't want IPv4, I can't help. */
2976 if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
2977 tor_free(address);
2978 relay_send_end_cell_from_edge(rh.stream_id, circ,
2979 END_STREAM_REASON_EXITPOLICY, NULL);
2980 return 0;
2984 log_debug(LD_EXIT,"Creating new exit connection.");
2985 /* The 'AF_INET' here is temporary; we might need to change it later in
2986 * connection_exit_connect(). */
2987 n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
2989 /* Remember the tunneled request ID in the new edge connection, so that
2990 * we can measure download times. */
2991 n_stream->dirreq_id = circ->dirreq_id;
2993 n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
2994 n_stream->begincell_flags = bcell.flags;
2995 n_stream->stream_id = rh.stream_id;
2996 n_stream->base_.port = port;
2997 /* leave n_stream->s at -1, because it's not yet valid */
2998 n_stream->package_window = STREAMWINDOW_START;
2999 n_stream->deliver_window = STREAMWINDOW_START;
3001 if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
3002 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
3003 log_info(LD_REND,"begin is for rendezvous. configuring stream.");
3004 n_stream->base_.address = tor_strdup("(rendezvous)");
3005 n_stream->base_.state = EXIT_CONN_STATE_CONNECTING;
3006 n_stream->rend_data = rend_data_dup(origin_circ->rend_data);
3007 tor_assert(connection_edge_is_rendezvous_stream(n_stream));
3008 assert_circuit_ok(circ);
3010 const int r = rend_service_set_connection_addr_port(n_stream, origin_circ);
3011 if (r < 0) {
3012 log_info(LD_REND,"Didn't find rendezvous service (port %d)",
3013 n_stream->base_.port);
3014 /* Send back reason DONE because we want to make hidden service port
3015 * scanning harder thus instead of returning that the exit policy
3016 * didn't match, which makes it obvious that the port is closed,
3017 * return DONE and kill the circuit. That way, a user (malicious or
3018 * not) needs one circuit per bad port unless it matches the policy of
3019 * the hidden service. */
3020 relay_send_end_cell_from_edge(rh.stream_id, circ,
3021 END_STREAM_REASON_DONE,
3022 origin_circ->cpath->prev);
3023 connection_free(TO_CONN(n_stream));
3024 tor_free(address);
3026 /* Drop the circuit here since it might be someone deliberately
3027 * scanning the hidden service ports. Note that this mitigates port
3028 * scanning by adding more work on the attacker side to successfully
3029 * scan but does not fully solve it. */
3030 if (r < -1)
3031 return END_CIRC_AT_ORIGIN;
3032 else
3033 return 0;
3035 assert_circuit_ok(circ);
3036 log_debug(LD_REND,"Finished assigning addr/port");
3037 n_stream->cpath_layer = origin_circ->cpath->prev; /* link it */
3039 /* add it into the linked list of p_streams on this circuit */
3040 n_stream->next_stream = origin_circ->p_streams;
3041 n_stream->on_circuit = circ;
3042 origin_circ->p_streams = n_stream;
3043 assert_circuit_ok(circ);
3045 origin_circ->rend_data->nr_streams++;
3047 connection_exit_connect(n_stream);
3049 /* For path bias: This circuit was used successfully */
3050 pathbias_mark_use_success(origin_circ);
3052 tor_free(address);
3053 return 0;
3055 tor_strlower(address);
3056 n_stream->base_.address = address;
3057 n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3058 /* default to failed, change in dns_resolve if it turns out not to fail */
3060 if (we_are_hibernating()) {
3061 relay_send_end_cell_from_edge(rh.stream_id, circ,
3062 END_STREAM_REASON_HIBERNATING, NULL);
3063 connection_free(TO_CONN(n_stream));
3064 return 0;
3067 n_stream->on_circuit = circ;
3069 if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3070 tor_addr_t tmp_addr;
3071 tor_assert(or_circ);
3072 if (or_circ->p_chan &&
3073 channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
3074 tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
3076 return connection_exit_connect_dir(n_stream);
3079 log_debug(LD_EXIT,"about to start the dns_resolve().");
3081 /* send it off to the gethostbyname farm */
3082 switch (dns_resolve(n_stream)) {
3083 case 1: /* resolve worked; now n_stream is attached to circ. */
3084 assert_circuit_ok(circ);
3085 log_debug(LD_EXIT,"about to call connection_exit_connect().");
3086 connection_exit_connect(n_stream);
3087 return 0;
3088 case -1: /* resolve failed */
3089 relay_send_end_cell_from_edge(rh.stream_id, circ,
3090 END_STREAM_REASON_RESOLVEFAILED, NULL);
3091 /* n_stream got freed. don't touch it. */
3092 break;
3093 case 0: /* resolve added to pending list */
3094 assert_circuit_ok(circ);
3095 break;
3097 return 0;
3101 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
3102 * circuit <b>circ</b>;
3103 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
3106 connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
3108 edge_connection_t *dummy_conn;
3109 relay_header_t rh;
3111 assert_circuit_ok(TO_CIRCUIT(circ));
3112 relay_header_unpack(&rh, cell->payload);
3113 if (rh.length > RELAY_PAYLOAD_SIZE)
3114 return -1;
3116 /* This 'dummy_conn' only exists to remember the stream ID
3117 * associated with the resolve request; and to make the
3118 * implementation of dns.c more uniform. (We really only need to
3119 * remember the circuit, the stream ID, and the hostname to be
3120 * resolved; but if we didn't store them in a connection like this,
3121 * the housekeeping in dns.c would get way more complicated.)
3123 dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
3124 dummy_conn->stream_id = rh.stream_id;
3125 dummy_conn->base_.address = tor_strndup(
3126 (char*)cell->payload+RELAY_HEADER_SIZE,
3127 rh.length);
3128 dummy_conn->base_.port = 0;
3129 dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3130 dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
3132 dummy_conn->on_circuit = TO_CIRCUIT(circ);
3134 /* send it off to the gethostbyname farm */
3135 switch (dns_resolve(dummy_conn)) {
3136 case -1: /* Impossible to resolve; a resolved cell was sent. */
3137 /* Connection freed; don't touch it. */
3138 return 0;
3139 case 1: /* The result was cached; a resolved cell was sent. */
3140 if (!dummy_conn->base_.marked_for_close)
3141 connection_free(TO_CONN(dummy_conn));
3142 return 0;
3143 case 0: /* resolve added to pending list */
3144 assert_circuit_ok(TO_CIRCUIT(circ));
3145 break;
3147 return 0;
3150 /** Connect to conn's specified addr and port. If it worked, conn
3151 * has now been added to the connection_array.
3153 * Send back a connected cell. Include the resolved IP of the destination
3154 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
3155 * streams must not reveal what IP they connected to.)
3157 void
3158 connection_exit_connect(edge_connection_t *edge_conn)
3160 const tor_addr_t *addr;
3161 uint16_t port;
3162 connection_t *conn = TO_CONN(edge_conn);
3163 int socket_error = 0, result;
3165 if ( (!connection_edge_is_rendezvous_stream(edge_conn) &&
3166 router_compare_to_my_exit_policy(&edge_conn->base_.addr,
3167 edge_conn->base_.port)) ||
3168 (tor_addr_family(&conn->addr) == AF_INET6 &&
3169 ! get_options()->IPv6Exit)) {
3170 log_info(LD_EXIT,"%s:%d failed exit policy. Closing.",
3171 escaped_safe_str_client(conn->address), conn->port);
3172 connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
3173 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3174 connection_free(conn);
3175 return;
3178 #ifdef HAVE_SYS_UN_H
3179 if (conn->socket_family != AF_UNIX) {
3180 #else
3182 #endif /* defined(HAVE_SYS_UN_H) */
3183 addr = &conn->addr;
3184 port = conn->port;
3186 if (tor_addr_family(addr) == AF_INET6)
3187 conn->socket_family = AF_INET6;
3189 log_debug(LD_EXIT, "about to try connecting");
3190 result = connection_connect(conn, conn->address,
3191 addr, port, &socket_error);
3192 #ifdef HAVE_SYS_UN_H
3193 } else {
3195 * In the AF_UNIX case, we expect to have already had conn->port = 1,
3196 * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
3197 * case in connection_handle_listener_read()), and conn->address should
3198 * have the socket path to connect to.
3200 tor_assert(conn->address && strlen(conn->address) > 0);
3202 log_debug(LD_EXIT, "about to try connecting");
3203 result = connection_connect_unix(conn, conn->address, &socket_error);
3204 #endif /* defined(HAVE_SYS_UN_H) */
3207 switch (result) {
3208 case -1: {
3209 int reason = errno_to_stream_end_reason(socket_error);
3210 connection_edge_end(edge_conn, reason);
3211 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3212 connection_free(conn);
3213 return;
3215 case 0:
3216 conn->state = EXIT_CONN_STATE_CONNECTING;
3218 connection_watch_events(conn, READ_EVENT | WRITE_EVENT);
3219 /* writable indicates finish;
3220 * readable/error indicates broken link in windows-land. */
3221 return;
3222 /* case 1: fall through */
3225 conn->state = EXIT_CONN_STATE_OPEN;
3226 if (connection_get_outbuf_len(conn)) {
3227 /* in case there are any queued data cells, from e.g. optimistic data */
3228 IF_HAS_NO_BUFFEREVENT(conn)
3229 connection_watch_events(conn, READ_EVENT|WRITE_EVENT);
3230 } else {
3231 IF_HAS_NO_BUFFEREVENT(conn)
3232 connection_watch_events(conn, READ_EVENT);
3235 /* also, deliver a 'connected' cell back through the circuit. */
3236 if (connection_edge_is_rendezvous_stream(edge_conn)) {
3237 /* don't send an address back! */
3238 connection_edge_send_command(edge_conn,
3239 RELAY_COMMAND_CONNECTED,
3240 NULL, 0);
3241 } else { /* normal stream */
3242 uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
3243 int connected_payload_len =
3244 connected_cell_format_payload(connected_payload, &conn->addr,
3245 edge_conn->address_ttl);
3246 if (connected_payload_len < 0) {
3247 connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
3248 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
3249 connection_free(conn);
3250 return;
3253 connection_edge_send_command(edge_conn,
3254 RELAY_COMMAND_CONNECTED,
3255 (char*)connected_payload,
3256 connected_payload_len);
3260 /** Given an exit conn that should attach to us as a directory server, open a
3261 * bridge connection with a linked connection pair, create a new directory
3262 * conn, and join them together. Return 0 on success (or if there was an
3263 * error we could send back an end cell for). Return -(some circuit end
3264 * reason) if the circuit needs to be torn down. Either connects
3265 * <b>exitconn</b>, frees it, or marks it, as appropriate.
3267 static int
3268 connection_exit_connect_dir(edge_connection_t *exitconn)
3270 dir_connection_t *dirconn = NULL;
3271 or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
3273 log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
3275 exitconn->base_.state = EXIT_CONN_STATE_OPEN;
3277 dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
3279 tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
3280 dirconn->base_.port = 0;
3281 dirconn->base_.address = tor_strdup(exitconn->base_.address);
3282 dirconn->base_.type = CONN_TYPE_DIR;
3283 dirconn->base_.purpose = DIR_PURPOSE_SERVER;
3284 dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
3286 /* Note that the new dir conn belongs to the same tunneled request as
3287 * the edge conn, so that we can measure download times. */
3288 dirconn->dirreq_id = exitconn->dirreq_id;
3290 connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
3292 if (connection_add(TO_CONN(exitconn))<0) {
3293 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
3294 connection_free(TO_CONN(exitconn));
3295 connection_free(TO_CONN(dirconn));
3296 return 0;
3299 /* link exitconn to circ, now that we know we can use it. */
3300 exitconn->next_stream = circ->n_streams;
3301 circ->n_streams = exitconn;
3303 if (connection_add(TO_CONN(dirconn))<0) {
3304 connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
3305 connection_close_immediate(TO_CONN(exitconn));
3306 connection_mark_for_close(TO_CONN(exitconn));
3307 connection_free(TO_CONN(dirconn));
3308 return 0;
3311 connection_start_reading(TO_CONN(dirconn));
3312 connection_start_reading(TO_CONN(exitconn));
3314 if (connection_edge_send_command(exitconn,
3315 RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
3316 connection_mark_for_close(TO_CONN(exitconn));
3317 connection_mark_for_close(TO_CONN(dirconn));
3318 return 0;
3321 return 0;
3324 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
3325 * it is a general stream.
3328 connection_edge_is_rendezvous_stream(edge_connection_t *conn)
3330 tor_assert(conn);
3331 if (conn->rend_data)
3332 return 1;
3333 return 0;
3336 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
3337 * to exit from it, or 0 if it probably will not allow it.
3338 * (We might be uncertain if conn's destination address has not yet been
3339 * resolved.)
3342 connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit)
3344 const or_options_t *options = get_options();
3346 tor_assert(conn);
3347 tor_assert(conn->socks_request);
3348 tor_assert(exit);
3350 /* If a particular exit node has been requested for the new connection,
3351 * make sure the exit node of the existing circuit matches exactly.
3353 if (conn->chosen_exit_name) {
3354 const node_t *chosen_exit =
3355 node_get_by_nickname(conn->chosen_exit_name, 1);
3356 if (!chosen_exit || tor_memneq(chosen_exit->identity,
3357 exit->identity, DIGEST_LEN)) {
3358 /* doesn't match */
3359 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
3360 // conn->chosen_exit_name, exit->nickname);
3361 return 0;
3365 if (conn->use_begindir) {
3366 /* Internal directory fetches do not count as exiting. */
3367 return 1;
3370 if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
3371 tor_addr_t addr, *addrp = NULL;
3372 addr_policy_result_t r;
3373 if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
3374 addrp = &addr;
3375 } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
3376 tor_addr_make_null(&addr, AF_INET6);
3377 addrp = &addr;
3378 } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
3379 tor_addr_make_null(&addr, AF_INET);
3380 addrp = &addr;
3382 r = compare_tor_addr_to_node_policy(addrp, conn->socks_request->port,exit);
3383 if (r == ADDR_POLICY_REJECTED)
3384 return 0; /* We know the address, and the exit policy rejects it. */
3385 if (r == ADDR_POLICY_PROBABLY_REJECTED && !conn->chosen_exit_name)
3386 return 0; /* We don't know the addr, but the exit policy rejects most
3387 * addresses with this port. Since the user didn't ask for
3388 * this node, err on the side of caution. */
3389 } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3390 /* Don't send DNS requests to non-exit servers by default. */
3391 if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit))
3392 return 0;
3394 if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit)) {
3395 /* Not a suitable exit. Refuse it. */
3396 return 0;
3399 return 1;
3402 /** If address is of the form "y.onion" with a well-formed handle y:
3403 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
3405 * If address is of the form "x.y.onion" with a well-formed handle x:
3406 * Drop "x.", put a NUL after y, lower-case it, and return ONION_HOSTNAME.
3408 * If address is of the form "y.onion" with a badly-formed handle y:
3409 * Return BAD_HOSTNAME and log a message.
3411 * If address is of the form "y.exit":
3412 * Put a NUL after y and return EXIT_HOSTNAME.
3414 * Otherwise:
3415 * Return NORMAL_HOSTNAME and change nothing.
3417 hostname_type_t
3418 parse_extended_hostname(char *address)
3420 char *s;
3421 char *q;
3422 char query[REND_SERVICE_ID_LEN_BASE32+1];
3424 s = strrchr(address,'.');
3425 if (!s)
3426 return NORMAL_HOSTNAME; /* no dot, thus normal */
3427 if (!strcmp(s+1,"exit")) {
3428 *s = 0; /* NUL-terminate it */
3429 return EXIT_HOSTNAME; /* .exit */
3431 if (strcmp(s+1,"onion"))
3432 return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
3434 /* so it is .onion */
3435 *s = 0; /* NUL-terminate it */
3436 /* locate a 'sub-domain' component, in order to remove it */
3437 q = strrchr(address, '.');
3438 if (q == address) {
3439 goto failed; /* reject sub-domain, as DNS does */
3441 q = (NULL == q) ? address : q + 1;
3442 if (strlcpy(query, q, REND_SERVICE_ID_LEN_BASE32+1) >=
3443 REND_SERVICE_ID_LEN_BASE32+1)
3444 goto failed;
3445 if (q != address) {
3446 memmove(address, q, strlen(q) + 1 /* also get \0 */);
3448 if (rend_valid_service_id(query)) {
3449 return ONION_HOSTNAME; /* success */
3451 failed:
3452 /* otherwise, return to previous state and return 0 */
3453 *s = '.';
3454 log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
3455 safe_str_client(address));
3456 return BAD_HOSTNAME;
3459 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
3460 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
3461 * at <b>b</b>. */
3462 static int
3463 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
3465 if (a == NULL) {
3466 return (b == NULL);
3467 } else if (b == NULL) {
3468 return 0;
3469 } else if (alen != blen) {
3470 return 0;
3471 } else {
3472 return tor_memeq(a, b, alen);
3477 * Return true iff none of the isolation flags and fields in <b>conn</b>
3478 * should prevent it from being attached to <b>circ</b>.
3481 connection_edge_compatible_with_circuit(const entry_connection_t *conn,
3482 const origin_circuit_t *circ)
3484 const uint8_t iso = conn->entry_cfg.isolation_flags;
3485 const socks_request_t *sr = conn->socks_request;
3487 /* If circ has never been used for an isolated connection, we can
3488 * totally use it for this one. */
3489 if (!circ->isolation_values_set)
3490 return 1;
3492 /* If circ has been used for connections having more than one value
3493 * for some field f, it will have the corresponding bit set in
3494 * isolation_flags_mixed. If isolation_flags_mixed has any bits
3495 * in common with iso, then conn must be isolated from at least
3496 * one stream that has been attached to circ. */
3497 if ((iso & circ->isolation_flags_mixed) != 0) {
3498 /* For at least one field where conn is isolated, the circuit
3499 * already has mixed streams. */
3500 return 0;
3503 if (! conn->original_dest_address) {
3504 log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
3505 "having set conn->original_dest_address");
3506 ((entry_connection_t*)conn)->original_dest_address =
3507 tor_strdup(conn->socks_request->address);
3510 if ((iso & ISO_STREAM) &&
3511 (circ->associated_isolated_stream_global_id !=
3512 ENTRY_TO_CONN(conn)->global_identifier))
3513 return 0;
3515 if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
3516 return 0;
3517 if ((iso & ISO_DESTADDR) &&
3518 strcasecmp(conn->original_dest_address, circ->dest_address))
3519 return 0;
3520 if ((iso & ISO_SOCKSAUTH) &&
3521 (! memeq_opt(sr->username, sr->usernamelen,
3522 circ->socks_username, circ->socks_username_len) ||
3523 ! memeq_opt(sr->password, sr->passwordlen,
3524 circ->socks_password, circ->socks_password_len)))
3525 return 0;
3526 if ((iso & ISO_CLIENTPROTO) &&
3527 (conn->socks_request->listener_type != circ->client_proto_type ||
3528 conn->socks_request->socks_version != circ->client_proto_socksver))
3529 return 0;
3530 if ((iso & ISO_CLIENTADDR) &&
3531 !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
3532 return 0;
3533 if ((iso & ISO_SESSIONGRP) &&
3534 conn->entry_cfg.session_group != circ->session_group)
3535 return 0;
3536 if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
3537 return 0;
3539 return 1;
3543 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
3544 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
3545 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
3546 * a bitfield of isolation flags that we would have to set in
3547 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
3548 * <b>circ</b> has had no streams attached to it.
3551 connection_edge_update_circuit_isolation(const entry_connection_t *conn,
3552 origin_circuit_t *circ,
3553 int dry_run)
3555 const socks_request_t *sr = conn->socks_request;
3556 if (! conn->original_dest_address) {
3557 log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
3558 "having set conn->original_dest_address");
3559 ((entry_connection_t*)conn)->original_dest_address =
3560 tor_strdup(conn->socks_request->address);
3563 if (!circ->isolation_values_set) {
3564 if (dry_run)
3565 return -1;
3566 circ->associated_isolated_stream_global_id =
3567 ENTRY_TO_CONN(conn)->global_identifier;
3568 circ->dest_port = conn->socks_request->port;
3569 circ->dest_address = tor_strdup(conn->original_dest_address);
3570 circ->client_proto_type = conn->socks_request->listener_type;
3571 circ->client_proto_socksver = conn->socks_request->socks_version;
3572 tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
3573 circ->session_group = conn->entry_cfg.session_group;
3574 circ->nym_epoch = conn->nym_epoch;
3575 circ->socks_username = sr->username ?
3576 tor_memdup(sr->username, sr->usernamelen) : NULL;
3577 circ->socks_password = sr->password ?
3578 tor_memdup(sr->password, sr->passwordlen) : NULL;
3579 circ->socks_username_len = sr->usernamelen;
3580 circ->socks_password_len = sr->passwordlen;
3582 circ->isolation_values_set = 1;
3583 return 0;
3584 } else {
3585 uint8_t mixed = 0;
3586 if (conn->socks_request->port != circ->dest_port)
3587 mixed |= ISO_DESTPORT;
3588 if (strcasecmp(conn->original_dest_address, circ->dest_address))
3589 mixed |= ISO_DESTADDR;
3590 if (!memeq_opt(sr->username, sr->usernamelen,
3591 circ->socks_username, circ->socks_username_len) ||
3592 !memeq_opt(sr->password, sr->passwordlen,
3593 circ->socks_password, circ->socks_password_len))
3594 mixed |= ISO_SOCKSAUTH;
3595 if ((conn->socks_request->listener_type != circ->client_proto_type ||
3596 conn->socks_request->socks_version != circ->client_proto_socksver))
3597 mixed |= ISO_CLIENTPROTO;
3598 if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
3599 mixed |= ISO_CLIENTADDR;
3600 if (conn->entry_cfg.session_group != circ->session_group)
3601 mixed |= ISO_SESSIONGRP;
3602 if (conn->nym_epoch != circ->nym_epoch)
3603 mixed |= ISO_NYM_EPOCH;
3605 if (dry_run)
3606 return mixed;
3608 if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
3609 log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
3610 "isolation flags.");
3612 circ->isolation_flags_mixed |= mixed;
3613 return 0;
3618 * Clear the isolation settings on <b>circ</b>.
3620 * This only works on an open circuit that has never had a stream attached to
3621 * it, and whose isolation settings are hypothetical. (We set hypothetical
3622 * isolation settings on circuits as we're launching them, so that we
3623 * know whether they can handle more streams or whether we need to launch
3624 * even more circuits. Once the circuit is open, if it turns out that
3625 * we no longer have any streams to attach to it, we clear the isolation flags
3626 * and data so that other streams can have a chance.)
3628 void
3629 circuit_clear_isolation(origin_circuit_t *circ)
3631 if (circ->isolation_any_streams_attached) {
3632 log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
3633 return;
3635 if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
3636 log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
3637 "circuit");
3638 return;
3641 circ->isolation_values_set = 0;
3642 circ->isolation_flags_mixed = 0;
3643 circ->associated_isolated_stream_global_id = 0;
3644 circ->client_proto_type = 0;
3645 circ->client_proto_socksver = 0;
3646 circ->dest_port = 0;
3647 tor_addr_make_unspec(&circ->client_addr);
3648 tor_free(circ->dest_address);
3649 circ->session_group = -1;
3650 circ->nym_epoch = 0;
3651 if (circ->socks_username) {
3652 memwipe(circ->socks_username, 0x11, circ->socks_username_len);
3653 tor_free(circ->socks_username);
3655 if (circ->socks_password) {
3656 memwipe(circ->socks_password, 0x05, circ->socks_password_len);
3657 tor_free(circ->socks_password);
3659 circ->socks_username_len = circ->socks_password_len = 0;
3662 /** Free all storage held in module-scoped variables for connection_edge.c */
3663 void
3664 connection_edge_free_all(void)
3666 untried_pending_connections = 0;
3667 smartlist_free(pending_entry_connections);
3668 pending_entry_connections = NULL;