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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
8 * \file connection_edge.c
9 * \brief Handle edge streams.
11 #define CONNECTION_EDGE_PRIVATE
14 #include "addressmap.h"
17 #include "circpathbias.h"
18 #include "circuitlist.h"
19 #include "circuituse.h"
21 #include "connection.h"
22 #include "connection_edge.h"
23 #include "connection_or.h"
28 #include "hibernate.h"
34 #include "rendclient.h"
35 #include "rendcommon.h"
36 #include "rendservice.h"
39 #include "routerlist.h"
40 #include "routerset.h"
41 #include "circuitbuild.h"
43 #ifdef HAVE_LINUX_TYPES_H
44 #include <linux/types.h>
46 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
47 #include <linux/netfilter_ipv4.h>
48 #define TRANS_NETFILTER
51 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
53 #include <net/pfvar.h>
57 #define SOCKS4_GRANTED 90
58 #define SOCKS4_REJECT 91
60 static int connection_ap_handshake_process_socks(entry_connection_t
*conn
);
61 static int connection_ap_process_natd(entry_connection_t
*conn
);
62 static int connection_exit_connect_dir(edge_connection_t
*exitconn
);
63 static int consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
);
64 static int connection_ap_supports_optimistic_data(const entry_connection_t
*);
66 /** An AP stream has failed/finished. If it hasn't already sent back
67 * a socks reply, send one now (based on endreason). Also set
68 * has_sent_end to 1, and mark the conn.
71 connection_mark_unattached_ap_
,(entry_connection_t
*conn
, int endreason
,
72 int line
, const char *file
))
74 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
75 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
76 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
77 ENTRY_TO_EDGE_CONN(conn
)->edge_has_sent_end
= 1; /* no circ yet */
79 /* If this is a rendezvous stream and it is failing without ever
80 * being attached to a circuit, assume that an attempt to connect to
81 * the destination hidden service has just ended.
83 * XXXX This condition doesn't limit to only streams failing
84 * without ever being attached. That sloppiness should be harmless,
85 * but we should fix it someday anyway. */
86 if ((edge_conn
->on_circuit
!= NULL
|| edge_conn
->edge_has_sent_end
) &&
87 connection_edge_is_rendezvous_stream(edge_conn
)) {
88 rend_client_note_connection_attempt_ended(
89 edge_conn
->rend_data
->onion_address
);
92 if (base_conn
->marked_for_close
) {
93 /* This call will warn as appropriate. */
94 connection_mark_for_close_(base_conn
, line
, file
);
98 if (!conn
->socks_request
->has_finished
) {
99 if (endreason
& END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
)
101 "stream (marked at %s:%d) sending two socks replies?",
104 if (SOCKS_COMMAND_IS_CONNECT(conn
->socks_request
->command
))
105 connection_ap_handshake_socks_reply(conn
, NULL
, 0, endreason
);
106 else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
107 connection_ap_handshake_socks_resolved(conn
,
108 RESOLVED_TYPE_ERROR_TRANSIENT
,
110 else /* unknown or no handshake at all. send no response. */
111 conn
->socks_request
->has_finished
= 1;
114 connection_mark_and_flush_(base_conn
, line
, file
);
116 ENTRY_TO_EDGE_CONN(conn
)->end_reason
= endreason
;
119 /** There was an EOF. Send an end and mark the connection for close.
122 connection_edge_reached_eof(edge_connection_t
*conn
)
124 if (connection_get_inbuf_len(TO_CONN(conn
)) &&
125 connection_state_is_open(TO_CONN(conn
))) {
126 /* it still has stuff to process. don't let it die yet. */
129 log_info(LD_EDGE
,"conn (fd "TOR_SOCKET_T_FORMAT
") reached eof. Closing.",
131 if (!conn
->base_
.marked_for_close
) {
132 /* only mark it if not already marked. it's possible to
133 * get the 'end' right around when the client hangs up on us. */
134 connection_edge_end(conn
, END_STREAM_REASON_DONE
);
135 if (conn
->base_
.type
== CONN_TYPE_AP
) {
136 /* eof, so don't send a socks reply back */
137 if (EDGE_TO_ENTRY_CONN(conn
)->socks_request
)
138 EDGE_TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
140 connection_mark_for_close(TO_CONN(conn
));
145 /** Handle new bytes on conn->inbuf based on state:
146 * - If it's waiting for socks info, try to read another step of the
147 * socks handshake out of conn->inbuf.
148 * - If it's waiting for the original destination, fetch it.
149 * - If it's open, then package more relay cells from the stream.
150 * - Else, leave the bytes on inbuf alone for now.
152 * Mark and return -1 if there was an unexpected error with the conn,
156 connection_edge_process_inbuf(edge_connection_t
*conn
, int package_partial
)
160 switch (conn
->base_
.state
) {
161 case AP_CONN_STATE_SOCKS_WAIT
:
162 if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn
)) <0) {
167 case AP_CONN_STATE_NATD_WAIT
:
168 if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn
)) < 0) {
173 case AP_CONN_STATE_OPEN
:
174 case EXIT_CONN_STATE_OPEN
:
175 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
) < 0) {
176 /* (We already sent an end cell if possible) */
177 connection_mark_for_close(TO_CONN(conn
));
181 case AP_CONN_STATE_CONNECT_WAIT
:
182 if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn
))) {
184 "data from edge while in '%s' state. Sending it anyway. "
185 "package_partial=%d, buflen=%ld",
186 conn_state_to_string(conn
->base_
.type
, conn
->base_
.state
),
188 (long)connection_get_inbuf_len(TO_CONN(conn
)));
189 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
)<0) {
190 /* (We already sent an end cell if possible) */
191 connection_mark_for_close(TO_CONN(conn
));
196 /* Fall through if the connection is on a circuit without optimistic
198 case EXIT_CONN_STATE_CONNECTING
:
199 case AP_CONN_STATE_RENDDESC_WAIT
:
200 case AP_CONN_STATE_CIRCUIT_WAIT
:
201 case AP_CONN_STATE_RESOLVE_WAIT
:
202 case AP_CONN_STATE_CONTROLLER_WAIT
:
204 "data from edge while in '%s' state. Leaving it on buffer.",
205 conn_state_to_string(conn
->base_
.type
, conn
->base_
.state
));
208 log_warn(LD_BUG
,"Got unexpected state %d. Closing.",conn
->base_
.state
);
209 tor_fragile_assert();
210 connection_edge_end(conn
, END_STREAM_REASON_INTERNAL
);
211 connection_mark_for_close(TO_CONN(conn
));
215 /** This edge needs to be closed, because its circuit has closed.
216 * Mark it for close and return 0.
219 connection_edge_destroy(circid_t circ_id
, edge_connection_t
*conn
)
221 if (!conn
->base_
.marked_for_close
) {
222 log_info(LD_EDGE
, "CircID %u: At an edge. Marking connection for close.",
224 if (conn
->base_
.type
== CONN_TYPE_AP
) {
225 entry_connection_t
*entry_conn
= EDGE_TO_ENTRY_CONN(conn
);
226 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_DESTROY
);
227 control_event_stream_bandwidth(conn
);
228 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
229 END_STREAM_REASON_DESTROY
);
230 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
232 /* closing the circuit, nothing to send an END to */
233 conn
->edge_has_sent_end
= 1;
234 conn
->end_reason
= END_STREAM_REASON_DESTROY
;
235 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
236 connection_mark_and_flush(TO_CONN(conn
));
239 conn
->cpath_layer
= NULL
;
240 conn
->on_circuit
= NULL
;
244 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
245 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
246 * is not a client connection, set the relay end cell's reason for closing
247 * as <b>reason</b> */
249 relay_send_end_cell_from_edge(streamid_t stream_id
, circuit_t
*circ
,
250 uint8_t reason
, crypt_path_t
*cpath_layer
)
254 if (CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
255 /* Never send the server an informative reason code; it doesn't need to
256 * know why the client stream is failing. */
257 reason
= END_STREAM_REASON_MISC
;
260 payload
[0] = (char) reason
;
262 return relay_send_command_from_edge(stream_id
, circ
, RELAY_COMMAND_END
,
263 payload
, 1, cpath_layer
);
266 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
267 * remember that we've done so. If this is not a client connection, set the
268 * relay end cell's reason for closing as <b>reason</b>.
270 * Return -1 if this function has already been called on this conn,
274 connection_edge_end(edge_connection_t
*conn
, uint8_t reason
)
276 char payload
[RELAY_PAYLOAD_SIZE
];
277 size_t payload_len
=1;
279 uint8_t control_reason
= reason
;
281 if (conn
->edge_has_sent_end
) {
282 log_warn(LD_BUG
,"(Harmless.) Calling connection_edge_end (reason %d) "
283 "on an already ended stream?", reason
);
284 tor_fragile_assert();
288 if (conn
->base_
.marked_for_close
) {
290 "called on conn that's already marked for close at %s:%d.",
291 conn
->base_
.marked_for_close_file
, conn
->base_
.marked_for_close
);
295 circ
= circuit_get_by_edge_conn(conn
);
296 if (circ
&& CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
297 /* If this is a client circuit, don't send the server an informative
298 * reason code; it doesn't need to know why the client stream is
300 reason
= END_STREAM_REASON_MISC
;
303 payload
[0] = (char)reason
;
304 if (reason
== END_STREAM_REASON_EXITPOLICY
&&
305 !connection_edge_is_rendezvous_stream(conn
)) {
307 if (tor_addr_family(&conn
->base_
.addr
) == AF_INET
) {
308 set_uint32(payload
+1, tor_addr_to_ipv4n(&conn
->base_
.addr
));
311 memcpy(payload
+1, tor_addr_to_in6_addr8(&conn
->base_
.addr
), 16);
314 set_uint32(payload
+1+addrlen
, htonl(dns_clip_ttl(conn
->address_ttl
)));
315 payload_len
+= 4+addrlen
;
318 if (circ
&& !circ
->marked_for_close
) {
319 log_debug(LD_EDGE
,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT
").",
321 connection_edge_send_command(conn
, RELAY_COMMAND_END
,
322 payload
, payload_len
);
324 log_debug(LD_EDGE
,"No circ to send end on conn "
325 "(fd "TOR_SOCKET_T_FORMAT
").",
329 conn
->edge_has_sent_end
= 1;
330 conn
->end_reason
= control_reason
;
334 /** An error has just occurred on an operation on an edge connection
335 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
336 * appropriate relay end cell to the other end of the connection's circuit.
339 connection_edge_end_errno(edge_connection_t
*conn
)
343 reason
= errno_to_stream_end_reason(tor_socket_errno(conn
->base_
.s
));
344 return connection_edge_end(conn
, reason
);
347 /** We just wrote some data to <b>conn</b>; act appropriately.
349 * (That is, if it's open, consider sending a stream-level sendme cell if we
350 * have just flushed enough.)
353 connection_edge_flushed_some(edge_connection_t
*conn
)
355 switch (conn
->base_
.state
) {
356 case AP_CONN_STATE_OPEN
:
357 case EXIT_CONN_STATE_OPEN
:
358 connection_edge_consider_sending_sendme(conn
);
364 /** Connection <b>conn</b> has finished writing and has no bytes left on
367 * If it's in state 'open', stop writing, consider responding with a
368 * sendme, and return.
369 * Otherwise, stop writing and return.
371 * If <b>conn</b> is broken, mark it for close and return -1, else
375 connection_edge_finished_flushing(edge_connection_t
*conn
)
379 switch (conn
->base_
.state
) {
380 case AP_CONN_STATE_OPEN
:
381 case EXIT_CONN_STATE_OPEN
:
382 connection_edge_consider_sending_sendme(conn
);
384 case AP_CONN_STATE_SOCKS_WAIT
:
385 case AP_CONN_STATE_NATD_WAIT
:
386 case AP_CONN_STATE_RENDDESC_WAIT
:
387 case AP_CONN_STATE_CIRCUIT_WAIT
:
388 case AP_CONN_STATE_CONNECT_WAIT
:
389 case AP_CONN_STATE_CONTROLLER_WAIT
:
390 case AP_CONN_STATE_RESOLVE_WAIT
:
393 log_warn(LD_BUG
, "Called in unexpected state %d.",conn
->base_
.state
);
394 tor_fragile_assert();
400 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
401 * able to generate. */
402 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
403 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
405 /** Set the buffer at <b>payload_out</b> -- which must have at least
406 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
407 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
408 * that the name resolution that led us to <b>addr</b> will be valid for
409 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
412 connected_cell_format_payload(uint8_t *payload_out
,
413 const tor_addr_t
*addr
,
416 const sa_family_t family
= tor_addr_family(addr
);
417 int connected_payload_len
;
419 /* should be needless */
420 memset(payload_out
, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN
);
422 if (family
== AF_INET
) {
423 set_uint32(payload_out
, tor_addr_to_ipv4n(addr
));
424 connected_payload_len
= 4;
425 } else if (family
== AF_INET6
) {
426 set_uint32(payload_out
, 0);
427 set_uint8(payload_out
+ 4, 6);
428 memcpy(payload_out
+ 5, tor_addr_to_in6_addr8(addr
), 16);
429 connected_payload_len
= 21;
434 set_uint32(payload_out
+ connected_payload_len
, htonl(dns_clip_ttl(ttl
)));
435 connected_payload_len
+= 4;
437 tor_assert(connected_payload_len
<= MAX_CONNECTED_CELL_PAYLOAD_LEN
);
439 return connected_payload_len
;
442 /** Connected handler for exit connections: start writing pending
443 * data, deliver 'CONNECTED' relay cells as appropriate, and check
444 * any pending data that may have been received. */
446 connection_edge_finished_connecting(edge_connection_t
*edge_conn
)
450 tor_assert(edge_conn
);
451 tor_assert(edge_conn
->base_
.type
== CONN_TYPE_EXIT
);
452 conn
= TO_CONN(edge_conn
);
453 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
455 log_info(LD_EXIT
,"Exit connection to %s:%u (%s) established.",
456 escaped_safe_str(conn
->address
), conn
->port
,
457 safe_str(fmt_and_decorate_addr(&conn
->addr
)));
459 rep_hist_note_exit_stream_opened(conn
->port
);
461 conn
->state
= EXIT_CONN_STATE_OPEN
;
462 IF_HAS_NO_BUFFEREVENT(conn
)
463 connection_watch_events(conn
, READ_EVENT
); /* stop writing, keep reading */
464 if (connection_get_outbuf_len(conn
)) /* in case there are any queued relay
466 connection_start_writing(conn
);
467 /* deliver a 'connected' relay cell back through the circuit. */
468 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
469 if (connection_edge_send_command(edge_conn
,
470 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0)
471 return 0; /* circuit is closed, don't continue */
473 uint8_t connected_payload
[MAX_CONNECTED_CELL_PAYLOAD_LEN
];
474 int connected_payload_len
=
475 connected_cell_format_payload(connected_payload
, &conn
->addr
,
476 edge_conn
->address_ttl
);
477 if (connected_payload_len
< 0)
480 if (connection_edge_send_command(edge_conn
,
481 RELAY_COMMAND_CONNECTED
,
482 (char*)connected_payload
, connected_payload_len
) < 0)
483 return 0; /* circuit is closed, don't continue */
485 tor_assert(edge_conn
->package_window
> 0);
486 /* in case the server has written anything */
487 return connection_edge_process_inbuf(edge_conn
, 1);
490 /** Common code to connection_(ap|exit)_about_to_close. */
492 connection_edge_about_to_close(edge_connection_t
*edge_conn
)
494 if (!edge_conn
->edge_has_sent_end
) {
495 connection_t
*conn
= TO_CONN(edge_conn
);
496 log_warn(LD_BUG
, "(Harmless.) Edge connection (marked at %s:%d) "
497 "hasn't sent end yet?",
498 conn
->marked_for_close_file
, conn
->marked_for_close
);
499 tor_fragile_assert();
503 /** Called when we're about to finally unlink and free an AP (client)
504 * connection: perform necessary accounting and cleanup */
506 connection_ap_about_to_close(entry_connection_t
*entry_conn
)
509 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
510 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
512 if (entry_conn
->socks_request
->has_finished
== 0) {
513 /* since conn gets removed right after this function finishes,
514 * there's no point trying to send back a reply at this point. */
515 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without sending"
516 " back a socks reply.",
517 conn
->marked_for_close_file
, conn
->marked_for_close
);
519 if (!edge_conn
->end_reason
) {
520 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
522 conn
->marked_for_close_file
, conn
->marked_for_close
);
524 if (entry_conn
->dns_server_request
) {
525 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
526 " replied to DNS request.",
527 conn
->marked_for_close_file
, conn
->marked_for_close
);
528 dnsserv_reject_request(entry_conn
);
530 control_event_stream_bandwidth(edge_conn
);
531 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
532 edge_conn
->end_reason
);
533 circ
= circuit_get_by_edge_conn(edge_conn
);
535 circuit_detach_stream(circ
, edge_conn
);
538 /** Called when we're about to finally unlink and free an exit
539 * connection: perform necessary accounting and cleanup */
541 connection_exit_about_to_close(edge_connection_t
*edge_conn
)
544 connection_t
*conn
= TO_CONN(edge_conn
);
546 connection_edge_about_to_close(edge_conn
);
548 circ
= circuit_get_by_edge_conn(edge_conn
);
550 circuit_detach_stream(circ
, edge_conn
);
551 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
552 connection_dns_remove(edge_conn
);
556 /** Define a schedule for how long to wait between retrying
557 * application connections. Rather than waiting a fixed amount of
558 * time between each retry, we wait 10 seconds each for the first
559 * two tries, and 15 seconds for each retry after
560 * that. Hopefully this will improve the expected user experience. */
562 compute_retry_timeout(entry_connection_t
*conn
)
564 int timeout
= get_options()->CircuitStreamTimeout
;
565 if (timeout
) /* if our config options override the default, use them */
567 if (conn
->num_socks_retries
< 2) /* try 0 and try 1 */
572 /** Find all general-purpose AP streams waiting for a response that sent their
573 * begin/resolve cell too long ago. Detach from their current circuit, and
574 * mark their current circuit as unsuitable for new streams. Then call
575 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
576 * available) or launch a new one.
578 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
582 connection_ap_expire_beginning(void)
584 edge_connection_t
*conn
;
585 entry_connection_t
*entry_conn
;
587 time_t now
= time(NULL
);
588 const or_options_t
*options
= get_options();
591 int seconds_idle
, seconds_since_born
;
592 smartlist_t
*conns
= get_connection_array();
594 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
595 if (base_conn
->type
!= CONN_TYPE_AP
|| base_conn
->marked_for_close
)
597 entry_conn
= TO_ENTRY_CONN(base_conn
);
598 conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
599 /* if it's an internal linked connection, don't yell its status. */
600 severity
= (tor_addr_is_null(&base_conn
->addr
) && !base_conn
->port
)
601 ? LOG_INFO
: LOG_NOTICE
;
602 seconds_idle
= (int)( now
- base_conn
->timestamp_lastread
);
603 seconds_since_born
= (int)( now
- base_conn
->timestamp_created
);
605 if (base_conn
->state
== AP_CONN_STATE_OPEN
)
608 /* We already consider SocksTimeout in
609 * connection_ap_handshake_attach_circuit(), but we need to consider
610 * it here too because controllers that put streams in controller_wait
611 * state never ask Tor to attach the circuit. */
612 if (AP_CONN_STATE_IS_UNATTACHED(base_conn
->state
)) {
613 if (seconds_since_born
>= options
->SocksTimeout
) {
614 log_fn(severity
, LD_APP
,
615 "Tried for %d seconds to get a connection to %s:%d. "
618 safe_str_client(entry_conn
->socks_request
->address
),
619 entry_conn
->socks_request
->port
,
620 conn_state_to_string(CONN_TYPE_AP
, base_conn
->state
));
621 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
626 /* We're in state connect_wait or resolve_wait now -- waiting for a
627 * reply to our relay cell. See if we want to retry/give up. */
629 cutoff
= compute_retry_timeout(entry_conn
);
630 if (seconds_idle
< cutoff
)
632 circ
= circuit_get_by_edge_conn(conn
);
633 if (!circ
) { /* it's vanished? */
634 log_info(LD_APP
,"Conn is waiting (address %s), but lost its circ.",
635 safe_str_client(entry_conn
->socks_request
->address
));
636 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
639 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
640 if (seconds_idle
>= options
->SocksTimeout
) {
641 log_fn(severity
, LD_REND
,
642 "Rend stream is %d seconds late. Giving up on address"
645 safe_str_client(entry_conn
->socks_request
->address
));
646 /* Roll back path bias use state so that we probe the circuit
647 * if nothing else succeeds on it */
648 pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ
));
650 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
651 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
655 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
&&
656 circ
->purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
&&
657 circ
->purpose
!= CIRCUIT_PURPOSE_PATH_BIAS_TESTING
) {
658 log_warn(LD_BUG
, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
659 "The purpose on the circuit was %s; it was in state %s, "
661 circuit_purpose_to_string(circ
->purpose
),
662 circuit_state_to_string(circ
->state
),
663 CIRCUIT_IS_ORIGIN(circ
) ?
664 pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ
)->path_state
) :
667 log_fn(cutoff
< 15 ? LOG_INFO
: severity
, LD_APP
,
668 "We tried for %d seconds to connect to '%s' using exit %s."
669 " Retrying on a new circuit.",
671 safe_str_client(entry_conn
->socks_request
->address
),
673 extend_info_describe(conn
->cpath_layer
->extend_info
):
675 /* send an end down the circuit */
676 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
677 /* un-mark it as ending, since we're going to reuse it */
678 conn
->edge_has_sent_end
= 0;
679 conn
->end_reason
= 0;
680 /* make us not try this circuit again, but allow
681 * current streams on it to survive if they can */
682 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ
));
684 /* give our stream another 'cutoff' seconds to try */
685 conn
->base_
.timestamp_lastread
+= cutoff
;
686 if (entry_conn
->num_socks_retries
< 250) /* avoid overflow */
687 entry_conn
->num_socks_retries
++;
688 /* move it back into 'pending' state, and try to attach. */
689 if (connection_ap_detach_retriable(entry_conn
, TO_ORIGIN_CIRCUIT(circ
),
690 END_STREAM_REASON_TIMEOUT
)<0) {
691 if (!base_conn
->marked_for_close
)
692 connection_mark_unattached_ap(entry_conn
,
693 END_STREAM_REASON_CANT_ATTACH
);
695 } SMARTLIST_FOREACH_END(base_conn
);
698 /** Tell any AP streams that are waiting for a new circuit to try again,
699 * either attaching to an available circ or launching a new one.
702 connection_ap_attach_pending(void)
704 entry_connection_t
*entry_conn
;
705 smartlist_t
*conns
= get_connection_array();
706 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
707 if (conn
->marked_for_close
||
708 conn
->type
!= CONN_TYPE_AP
||
709 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
711 entry_conn
= TO_ENTRY_CONN(conn
);
712 if (connection_ap_handshake_attach_circuit(entry_conn
) < 0) {
713 if (!conn
->marked_for_close
)
714 connection_mark_unattached_ap(entry_conn
,
715 END_STREAM_REASON_CANT_ATTACH
);
717 } SMARTLIST_FOREACH_END(conn
);
720 /** Tell any AP streams that are waiting for a one-hop tunnel to
721 * <b>failed_digest</b> that they are going to fail. */
722 /* XXX024 We should get rid of this function, and instead attach
723 * one-hop streams to circ->p_streams so they get marked in
724 * circuit_mark_for_close like normal p_streams. */
726 connection_ap_fail_onehop(const char *failed_digest
,
727 cpath_build_state_t
*build_state
)
729 entry_connection_t
*entry_conn
;
730 char digest
[DIGEST_LEN
];
731 smartlist_t
*conns
= get_connection_array();
732 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
733 if (conn
->marked_for_close
||
734 conn
->type
!= CONN_TYPE_AP
||
735 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
737 entry_conn
= TO_ENTRY_CONN(conn
);
738 if (!entry_conn
->want_onehop
)
740 if (hexdigest_to_digest(entry_conn
->chosen_exit_name
, digest
) < 0 ||
741 tor_memneq(digest
, failed_digest
, DIGEST_LEN
))
743 if (tor_digest_is_zero(digest
)) {
744 /* we don't know the digest; have to compare addr:port */
746 if (!build_state
|| !build_state
->chosen_exit
||
747 !entry_conn
->socks_request
|| !entry_conn
->socks_request
->address
)
749 if (tor_addr_parse(&addr
, entry_conn
->socks_request
->address
)<0 ||
750 !tor_addr_eq(&build_state
->chosen_exit
->addr
, &addr
) ||
751 build_state
->chosen_exit
->port
!= entry_conn
->socks_request
->port
)
754 log_info(LD_APP
, "Closing one-hop stream to '%s/%s' because the OR conn "
755 "just failed.", entry_conn
->chosen_exit_name
,
756 entry_conn
->socks_request
->address
);
757 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
758 } SMARTLIST_FOREACH_END(conn
);
761 /** A circuit failed to finish on its last hop <b>info</b>. If there
762 * are any streams waiting with this exit node in mind, but they
763 * don't absolutely require it, make them give up on it.
766 circuit_discard_optional_exit_enclaves(extend_info_t
*info
)
768 entry_connection_t
*entry_conn
;
769 const node_t
*r1
, *r2
;
771 smartlist_t
*conns
= get_connection_array();
772 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
773 if (conn
->marked_for_close
||
774 conn
->type
!= CONN_TYPE_AP
||
775 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
777 entry_conn
= TO_ENTRY_CONN(conn
);
778 if (!entry_conn
->chosen_exit_optional
&&
779 !entry_conn
->chosen_exit_retries
)
781 r1
= node_get_by_nickname(entry_conn
->chosen_exit_name
, 0);
782 r2
= node_get_by_id(info
->identity_digest
);
783 if (!r1
|| !r2
|| r1
!= r2
)
785 tor_assert(entry_conn
->socks_request
);
786 if (entry_conn
->chosen_exit_optional
) {
787 log_info(LD_APP
, "Giving up on enclave exit '%s' for destination %s.",
788 safe_str_client(entry_conn
->chosen_exit_name
),
789 escaped_safe_str_client(entry_conn
->socks_request
->address
));
790 entry_conn
->chosen_exit_optional
= 0;
791 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
792 /* if this port is dangerous, warn or reject it now that we don't
793 * think it'll be using an enclave. */
794 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
796 if (entry_conn
->chosen_exit_retries
) {
797 if (--entry_conn
->chosen_exit_retries
== 0) { /* give up! */
798 clear_trackexithost_mappings(entry_conn
->chosen_exit_name
);
799 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
800 /* if this port is dangerous, warn or reject it now that we don't
801 * think it'll be using an enclave. */
802 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
805 } SMARTLIST_FOREACH_END(conn
);
808 /** The AP connection <b>conn</b> has just failed while attaching or
809 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
810 * might work. Detach the circuit, and either reattach it, launch a
811 * new circuit, tell the controller, or give up as appropriate.
813 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
816 connection_ap_detach_retriable(entry_connection_t
*conn
,
817 origin_circuit_t
*circ
,
820 control_event_stream_status(conn
, STREAM_EVENT_FAILED_RETRIABLE
, reason
);
821 ENTRY_TO_CONN(conn
)->timestamp_lastread
= time(NULL
);
823 /* Roll back path bias use state so that we probe the circuit
824 * if nothing else succeeds on it */
825 pathbias_mark_use_rollback(circ
);
827 if (conn
->pending_optimistic_data
) {
828 generic_buffer_set_to_copy(&conn
->sending_optimistic_data
,
829 conn
->pending_optimistic_data
);
832 if (!get_options()->LeaveStreamsUnattached
|| conn
->use_begindir
) {
833 /* If we're attaching streams ourself, or if this connection is
834 * a tunneled directory connection, then just attach it. */
835 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
836 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
837 return connection_ap_handshake_attach_circuit(conn
);
839 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
840 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
845 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
846 * reject depending on our config options. */
848 consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
)
850 const or_options_t
*options
= get_options();
851 int reject
= smartlist_contains_int_as_string(
852 options
->RejectPlaintextPorts
, port
);
854 if (smartlist_contains_int_as_string(options
->WarnPlaintextPorts
, port
)) {
855 log_warn(LD_APP
, "Application request to port %d: this port is "
856 "commonly used for unencrypted protocols. Please make sure "
857 "you don't send anything you would mind the rest of the "
858 "Internet reading!%s", port
, reject
? " Closing." : "");
859 control_event_client_status(LOG_WARN
, "DANGEROUS_PORT PORT=%d RESULT=%s",
860 port
, reject
? "REJECT" : "WARN");
864 log_info(LD_APP
, "Port %d listed in RejectPlaintextPorts. Closing.", port
);
865 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
872 /** How many times do we try connecting with an exit configured via
873 * TrackHostExits before concluding that it won't work any more and trying a
875 #define TRACKHOSTEXITS_RETRIES 5
877 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
878 * asked us to leave streams unattached. Return 0 in that case.
880 * See connection_ap_handshake_rewrite_and_attach()'s
881 * documentation for arguments and return value.
884 connection_ap_rewrite_and_attach_if_allowed(entry_connection_t
*conn
,
885 origin_circuit_t
*circ
,
888 const or_options_t
*options
= get_options();
890 if (options
->LeaveStreamsUnattached
) {
891 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
894 return connection_ap_handshake_rewrite_and_attach(conn
, circ
, cpath
);
897 /** Connection <b>conn</b> just finished its socks handshake, or the
898 * controller asked us to take care of it. If <b>circ</b> is defined,
899 * then that's where we'll want to attach it. Otherwise we have to
900 * figure it out ourselves.
902 * First, parse whether it's a .exit address, remap it, and so on. Then
903 * if it's for a general circuit, try to attach it to a circuit (or launch
904 * one as needed), else if it's for a rendezvous circuit, fetch a
905 * rendezvous descriptor first (or attach/launch a circuit if the
906 * rendezvous descriptor is already here and fresh enough).
908 * The stream will exit from the hop
909 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
910 * <b>cpath</b> is NULL.
913 connection_ap_handshake_rewrite_and_attach(entry_connection_t
*conn
,
914 origin_circuit_t
*circ
,
917 socks_request_t
*socks
= conn
->socks_request
;
918 hostname_type_t addresstype
;
919 const or_options_t
*options
= get_options();
921 /* We set this to true if this is an address we should automatically
922 * remap to a local address in VirtualAddrNetwork */
924 char orig_address
[MAX_SOCKS_ADDR_LEN
];
925 time_t map_expires
= TIME_MAX
;
926 time_t now
= time(NULL
);
927 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
928 addressmap_entry_source_t exit_source
= ADDRMAPSRC_NONE
;
930 tor_strlower(socks
->address
); /* normalize it */
931 strlcpy(orig_address
, socks
->address
, sizeof(orig_address
));
932 log_debug(LD_APP
,"Client asked for %s:%d",
933 safe_str_client(socks
->address
),
936 if (!strcmpend(socks
->address
, ".exit") && !options
->AllowDotExit
) {
937 log_warn(LD_APP
, "The \".exit\" notation is disabled in Tor due to "
938 "security risks. Set AllowDotExit in your torrc to enable "
939 "it (at your own risk).");
940 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
941 escaped(socks
->address
));
942 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
946 if (! conn
->original_dest_address
)
947 conn
->original_dest_address
= tor_strdup(conn
->socks_request
->address
);
949 if (socks
->command
== SOCKS_COMMAND_RESOLVE
&&
950 tor_addr_parse(&addr_tmp
, socks
->address
)<0 &&
951 options
->AutomapHostsOnResolve
) {
952 automap
= addressmap_address_should_automap(socks
->address
, options
);
954 const char *new_addr
;
955 int addr_type
= RESOLVED_TYPE_IPV4
;
956 if (conn
->socks_request
->socks_version
!= 4) {
957 if (!conn
->ipv4_traffic_ok
||
958 (conn
->ipv6_traffic_ok
&& conn
->prefer_ipv6_traffic
) ||
959 conn
->prefer_ipv6_virtaddr
)
960 addr_type
= RESOLVED_TYPE_IPV6
;
962 new_addr
= addressmap_register_virtual_address(
963 addr_type
, tor_strdup(socks
->address
));
965 log_warn(LD_APP
, "Unable to automap address %s",
966 escaped_safe_str(socks
->address
));
967 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
970 log_info(LD_APP
, "Automapping %s to %s",
971 escaped_safe_str_client(socks
->address
),
972 safe_str_client(new_addr
));
973 strlcpy(socks
->address
, new_addr
, sizeof(socks
->address
));
977 if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
978 unsigned rewrite_flags
= 0;
979 if (conn
->use_cached_ipv4_answers
)
980 rewrite_flags
|= AMR_FLAG_USE_IPV4_DNS
;
981 if (conn
->use_cached_ipv6_answers
)
982 rewrite_flags
|= AMR_FLAG_USE_IPV6_DNS
;
984 if (addressmap_rewrite_reverse(socks
->address
, sizeof(socks
->address
),
985 rewrite_flags
, &map_expires
)) {
986 char *result
= tor_strdup(socks
->address
);
987 /* remember _what_ is supposed to have been resolved. */
988 tor_snprintf(socks
->address
, sizeof(socks
->address
), "REVERSE[%s]",
990 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_HOSTNAME
,
991 strlen(result
), (uint8_t*)result
,
994 connection_mark_unattached_ap(conn
,
995 END_STREAM_REASON_DONE
|
996 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
999 if (options
->ClientDNSRejectInternalAddresses
) {
1000 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1003 ok
= tor_addr_parse_PTR_name(
1004 &addr
, socks
->address
, AF_UNSPEC
, 1);
1005 if (ok
== 1 && tor_addr_is_internal(&addr
, 0)) {
1006 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_ERROR
,
1007 0, NULL
, -1, TIME_MAX
);
1008 connection_mark_unattached_ap(conn
,
1009 END_STREAM_REASON_SOCKSPROTOCOL
|
1010 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1014 } else if (!automap
) {
1015 /* For address map controls, remap the address. */
1016 unsigned rewrite_flags
= 0;
1017 if (conn
->use_cached_ipv4_answers
)
1018 rewrite_flags
|= AMR_FLAG_USE_IPV4_DNS
;
1019 if (conn
->use_cached_ipv6_answers
)
1020 rewrite_flags
|= AMR_FLAG_USE_IPV6_DNS
;
1021 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
),
1022 rewrite_flags
, &map_expires
, &exit_source
)) {
1023 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1024 REMAP_STREAM_SOURCE_CACHE
);
1028 if (!automap
&& address_is_in_virtual_range(socks
->address
)) {
1029 /* This address was probably handed out by client_dns_get_unmapped_address,
1030 * but the mapping was discarded for some reason. We *don't* want to send
1031 * the address through Tor; that's likely to fail, and may leak
1034 log_warn(LD_APP
,"Missing mapping for virtual address '%s'. Refusing.",
1035 safe_str_client(socks
->address
));
1036 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
1040 /* Parse the address provided by SOCKS. Modify it in-place if it
1041 * specifies a hidden-service (.onion) or particular exit node (.exit).
1043 addresstype
= parse_extended_hostname(socks
->address
);
1045 if (addresstype
== BAD_HOSTNAME
) {
1046 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1047 escaped(socks
->address
));
1048 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1052 if (addresstype
== EXIT_HOSTNAME
) {
1053 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1054 * node, and conn->address to hold only the address portion. */
1055 char *s
= strrchr(socks
->address
,'.');
1057 /* If StrictNodes is not set, then .exit overrides ExcludeNodes. */
1058 routerset_t
*excludeset
= options
->StrictNodes
?
1059 options
->ExcludeExitNodesUnion_
: options
->ExcludeExitNodes
;
1062 if (exit_source
== ADDRMAPSRC_AUTOMAP
&& !options
->AllowDotExit
) {
1063 /* Whoops; this one is stale. It must have gotten added earlier,
1064 * when AllowDotExit was on. */
1065 log_warn(LD_APP
,"Stale automapped address for '%s.exit', with "
1066 "AllowDotExit disabled. Refusing.",
1067 safe_str_client(socks
->address
));
1068 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1069 escaped(socks
->address
));
1070 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1074 if (exit_source
== ADDRMAPSRC_DNS
||
1075 (exit_source
== ADDRMAPSRC_NONE
&& !options
->AllowDotExit
)) {
1076 /* It shouldn't be possible to get a .exit address from any of these
1078 log_warn(LD_BUG
,"Address '%s.exit', with impossible source for the "
1079 ".exit part. Refusing.",
1080 safe_str_client(socks
->address
));
1081 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1082 escaped(socks
->address
));
1083 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1087 tor_assert(!automap
);
1089 /* The address was of the form "(stuff).(name).exit */
1091 conn
->chosen_exit_name
= tor_strdup(s
+1);
1092 node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1094 if (exit_source
== ADDRMAPSRC_TRACKEXIT
) {
1095 /* We 5 tries before it expires the addressmap */
1096 conn
->chosen_exit_retries
= TRACKHOSTEXITS_RETRIES
;
1100 /* Oops, the address was (stuff)..exit. That's not okay. */
1101 log_warn(LD_APP
,"Malformed exit address '%s.exit'. Refusing.",
1102 safe_str_client(socks
->address
));
1103 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1104 escaped(socks
->address
));
1105 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1109 /* It looks like they just asked for "foo.exit". */
1111 conn
->chosen_exit_name
= tor_strdup(socks
->address
);
1112 node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1114 *socks
->address
= 0;
1115 node_get_address_string(node
, socks
->address
, sizeof(socks
->address
));
1118 /* Now make sure that the chosen exit exists... */
1121 "Unrecognized relay in exit address '%s.exit'. Refusing.",
1122 safe_str_client(socks
->address
));
1123 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1126 /* ...and make sure that it isn't excluded. */
1127 if (routerset_contains_node(excludeset
, node
)) {
1129 "Excluded relay in exit address '%s.exit'. Refusing.",
1130 safe_str_client(socks
->address
));
1131 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1134 /* XXXX024-1090 Should we also allow foo.bar.exit if ExitNodes is set and
1135 Bar is not listed in it? I say yes, but our revised manpage branch
1139 if (addresstype
!= ONION_HOSTNAME
) {
1140 /* not a hidden-service request (i.e. normal or .exit) */
1141 if (address_is_invalid_destination(socks
->address
, 1)) {
1142 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1143 escaped(socks
->address
));
1145 "Destination '%s' seems to be an invalid hostname. Failing.",
1146 safe_str_client(socks
->address
));
1147 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1151 if (options
->Tor2webMode
) {
1152 log_warn(LD_APP
, "Refusing to connect to non-hidden-service hostname %s "
1153 "because tor2web mode is enabled.",
1154 safe_str_client(socks
->address
));
1155 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1159 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
1161 /* Reply to resolves immediately if we can. */
1162 if (tor_addr_parse(&answer
, socks
->address
) >= 0) {/* is it an IP? */
1163 /* remember _what_ is supposed to have been resolved. */
1164 strlcpy(socks
->address
, orig_address
, sizeof(socks
->address
));
1165 connection_ap_handshake_socks_resolved_addr(conn
, &answer
, -1,
1167 connection_mark_unattached_ap(conn
,
1168 END_STREAM_REASON_DONE
|
1169 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1172 tor_assert(!automap
);
1173 rep_hist_note_used_resolve(now
); /* help predict this next time */
1174 } else if (socks
->command
== SOCKS_COMMAND_CONNECT
) {
1175 tor_assert(!automap
);
1176 if (socks
->port
== 0) {
1177 log_notice(LD_APP
,"Application asked to connect to port 0. Refusing.");
1178 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1181 if (options
->ClientRejectInternalAddresses
&&
1182 !conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
1184 if (tor_addr_hostname_is_local(socks
->address
) ||
1185 (tor_addr_parse(&addr
, socks
->address
) >= 0 &&
1186 tor_addr_is_internal(&addr
, 0))) {
1187 /* If this is an explicit private address with no chosen exit node,
1188 * then we really don't want to try to connect to it. That's
1189 * probably an error. */
1190 if (conn
->is_transparent_ap
) {
1191 #define WARN_INTRVL_LOOP 300
1192 static ratelim_t loop_warn_limit
= RATELIM_INIT(WARN_INTRVL_LOOP
);
1194 if ((m
= rate_limit_log(&loop_warn_limit
, approx_time()))) {
1196 "Rejecting request for anonymous connection to private "
1197 "address %s on a TransPort or NATDPort. Possible loop "
1198 "in your NAT rules?%s", safe_str_client(socks
->address
),
1203 #define WARN_INTRVL_PRIV 300
1204 static ratelim_t priv_warn_limit
= RATELIM_INIT(WARN_INTRVL_PRIV
);
1206 if ((m
= rate_limit_log(&priv_warn_limit
, approx_time()))) {
1208 "Rejecting SOCKS request for anonymous connection to "
1209 "private address %s.%s",
1210 safe_str_client(socks
->address
),m
);
1214 connection_mark_unattached_ap(conn
, END_STREAM_REASON_PRIVATE_ADDR
);
1221 /* XXX Duplicate call to tor_addr_parse. */
1222 if (tor_addr_parse(&addr
, socks
->address
) >= 0) {
1223 sa_family_t family
= tor_addr_family(&addr
);
1224 if ((family
== AF_INET
&& ! conn
->ipv4_traffic_ok
) ||
1225 (family
== AF_INET6
&& ! conn
->ipv4_traffic_ok
)) {
1226 log_warn(LD_NET
, "Rejecting SOCKS request for an IP address "
1227 "family that this listener does not support.");
1228 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1230 } else if (family
== AF_INET6
&& socks
->socks_version
== 4) {
1231 log_warn(LD_NET
, "Rejecting SOCKS4 request for an IPv6 address.");
1232 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1234 } else if (socks
->socks_version
== 4 && !conn
->ipv4_traffic_ok
) {
1235 log_warn(LD_NET
, "Rejecting SOCKS4 request on a listener with "
1236 "no IPv4 traffic supported.");
1237 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1239 } else if (family
== AF_INET6
) {
1240 conn
->ipv4_traffic_ok
= 0;
1241 } else if (family
== AF_INET
) {
1242 conn
->ipv6_traffic_ok
= 0;
1247 if (socks
->socks_version
== 4)
1248 conn
->ipv6_traffic_ok
= 0;
1250 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
1251 /* see if we can find a suitable enclave exit */
1253 router_find_exact_exit_enclave(socks
->address
, socks
->port
);
1256 "Redirecting address %s to exit at enclave router %s",
1257 safe_str_client(socks
->address
), node_describe(r
));
1258 /* use the hex digest, not nickname, in case there are two
1259 routers with this nickname */
1260 conn
->chosen_exit_name
=
1261 tor_strdup(hex_str(r
->identity
, DIGEST_LEN
));
1262 conn
->chosen_exit_optional
= 1;
1266 /* warn or reject if it's using a dangerous port */
1267 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
)
1268 if (consider_plaintext_ports(conn
, socks
->port
) < 0)
1271 if (!conn
->use_begindir
) {
1272 /* help predict this next time */
1273 rep_hist_note_used_port(now
, socks
->port
);
1275 } else if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1276 rep_hist_note_used_resolve(now
); /* help predict this next time */
1277 /* no extra processing needed */
1279 tor_fragile_assert();
1281 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1282 if ((circ
&& connection_ap_handshake_attach_chosen_circuit(
1283 conn
, circ
, cpath
) < 0) ||
1285 connection_ap_handshake_attach_circuit(conn
) < 0)) {
1286 if (!base_conn
->marked_for_close
)
1287 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1292 /* it's a hidden-service request */
1293 rend_cache_entry_t
*entry
;
1295 rend_service_authorization_t
*client_auth
;
1296 rend_data_t
*rend_data
;
1297 tor_assert(!automap
);
1298 if (SOCKS_COMMAND_IS_RESOLVE(socks
->command
)) {
1299 /* if it's a resolve request, fail it right now, rather than
1300 * building all the circuits and then realizing it won't work. */
1302 "Resolve requests to hidden services not allowed. Failing.");
1303 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
1304 0,NULL
,-1,TIME_MAX
);
1305 connection_mark_unattached_ap(conn
,
1306 END_STREAM_REASON_SOCKSPROTOCOL
|
1307 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1312 log_warn(LD_CONTROL
, "Attachstream to a circuit is not "
1313 "supported for .onion addresses currently. Failing.");
1314 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1318 ENTRY_TO_EDGE_CONN(conn
)->rend_data
= rend_data
=
1319 tor_malloc_zero(sizeof(rend_data_t
));
1320 strlcpy(rend_data
->onion_address
, socks
->address
,
1321 sizeof(rend_data
->onion_address
));
1322 log_info(LD_REND
,"Got a hidden service request for ID '%s'",
1323 safe_str_client(rend_data
->onion_address
));
1324 /* see if we already have it cached */
1325 r
= rend_cache_lookup_entry(rend_data
->onion_address
, -1, &entry
);
1327 log_warn(LD_BUG
,"Invalid service name '%s'",
1328 safe_str_client(rend_data
->onion_address
));
1329 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1333 /* Help predict this next time. We're not sure if it will need
1334 * a stable circuit yet, but we know we'll need *something*. */
1335 rep_hist_note_used_internal(now
, 0, 1);
1337 /* Look up if we have client authorization for it. */
1338 client_auth
= rend_client_lookup_service_authorization(
1339 rend_data
->onion_address
);
1341 log_info(LD_REND
, "Using previously configured client authorization "
1342 "for hidden service request.");
1343 memcpy(rend_data
->descriptor_cookie
,
1344 client_auth
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
1345 rend_data
->auth_type
= client_auth
->auth_type
;
1348 base_conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
1349 log_info(LD_REND
, "Unknown descriptor %s. Fetching.",
1350 safe_str_client(rend_data
->onion_address
));
1351 rend_client_refetch_v2_renddesc(rend_data
);
1352 } else { /* r > 0 */
1353 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1354 log_info(LD_REND
, "Descriptor is here. Great.");
1355 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
1356 if (!base_conn
->marked_for_close
)
1357 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1363 return 0; /* unreached but keeps the compiler happy */
1367 static int pf_socket
= -1;
1372 /* This should be opened before dropping privileges. */
1377 /* only works on OpenBSD */
1378 pf
= tor_open_cloexec("/dev/pf", O_RDONLY
, 0);
1380 /* works on NetBSD and FreeBSD */
1381 pf
= tor_open_cloexec("/dev/pf", O_RDWR
, 0);
1385 log_warn(LD_NET
, "open(\"/dev/pf\") failed: %s", strerror(errno
));
1394 #if defined(TRANS_NETFILTER) || defined(TRANS_PF)
1395 /** Try fill in the address of <b>req</b> from the socket configured
1396 * with <b>conn</b>. */
1398 destination_from_socket(entry_connection_t
*conn
, socks_request_t
*req
)
1400 struct sockaddr_storage orig_dst
;
1401 socklen_t orig_dst_len
= sizeof(orig_dst
);
1404 #ifdef TRANS_NETFILTER
1405 if (getsockopt(ENTRY_TO_CONN(conn
)->s
, SOL_IP
, SO_ORIGINAL_DST
,
1406 (struct sockaddr
*)&orig_dst
, &orig_dst_len
) < 0) {
1407 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
1408 log_warn(LD_NET
, "getsockopt() failed: %s", tor_socket_strerror(e
));
1411 #elif defined(TRANS_PF)
1412 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&orig_dst
,
1413 &orig_dst_len
) < 0) {
1414 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
1415 log_warn(LD_NET
, "getsockname() failed: %s", tor_socket_strerror(e
));
1421 log_warn(LD_BUG
, "Unable to determine destination from socket.");
1425 tor_addr_from_sockaddr(&addr
, (struct sockaddr
*)&orig_dst
, &req
->port
);
1426 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 1);
1434 destination_from_pf(entry_connection_t
*conn
, socks_request_t
*req
)
1436 struct sockaddr_storage proxy_addr
;
1437 socklen_t proxy_addr_len
= sizeof(proxy_addr
);
1438 struct sockaddr
*proxy_sa
= (struct sockaddr
*) &proxy_addr
;
1439 struct pfioc_natlook pnl
;
1443 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&proxy_addr
,
1444 &proxy_addr_len
) < 0) {
1445 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
1446 log_warn(LD_NET
, "getsockname() to determine transocks destination "
1447 "failed: %s", tor_socket_strerror(e
));
1452 if (get_options()->TransProxyType_parsed
== TPT_IPFW
) {
1453 /* ipfw(8) is used and in this case getsockname returned the original
1455 if (tor_addr_from_sockaddr(&addr
, proxy_sa
, &req
->port
) < 0) {
1456 tor_fragile_assert();
1460 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 0);
1466 memset(&pnl
, 0, sizeof(pnl
));
1467 pnl
.proto
= IPPROTO_TCP
;
1468 pnl
.direction
= PF_OUT
;
1469 if (proxy_sa
->sa_family
== AF_INET
) {
1470 struct sockaddr_in
*sin
= (struct sockaddr_in
*)proxy_sa
;
1472 pnl
.saddr
.v4
.s_addr
= tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn
)->addr
);
1473 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
1474 pnl
.daddr
.v4
.s_addr
= sin
->sin_addr
.s_addr
;
1475 pnl
.dport
= sin
->sin_port
;
1476 } else if (proxy_sa
->sa_family
== AF_INET6
) {
1477 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)proxy_sa
;
1479 memcpy(&pnl
.saddr
.v6
, tor_addr_to_in6(&ENTRY_TO_CONN(conn
)->addr
),
1480 sizeof(struct in6_addr
));
1481 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
1482 memcpy(&pnl
.daddr
.v6
, &sin6
->sin6_addr
, sizeof(struct in6_addr
));
1483 pnl
.dport
= sin6
->sin6_port
;
1485 log_warn(LD_NET
, "getsockname() gave an unexpected address family (%d)",
1486 (int)proxy_sa
->sa_family
);
1490 pf
= get_pf_socket();
1494 if (ioctl(pf
, DIOCNATLOOK
, &pnl
) < 0) {
1495 log_warn(LD_NET
, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno
));
1499 if (pnl
.af
== AF_INET
) {
1500 tor_addr_from_ipv4n(&addr
, pnl
.rdaddr
.v4
.s_addr
);
1501 } else if (pnl
.af
== AF_INET6
) {
1502 tor_addr_from_in6(&addr
, &pnl
.rdaddr
.v6
);
1504 tor_fragile_assert();
1508 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 1);
1509 req
->port
= ntohs(pnl
.rdport
);
1515 /** Fetch the original destination address and port from a
1516 * system-specific interface and put them into a
1517 * socks_request_t as if they came from a socks request.
1519 * Return -1 if an error prevents fetching the destination,
1523 connection_ap_get_original_destination(entry_connection_t
*conn
,
1524 socks_request_t
*req
)
1526 #ifdef TRANS_NETFILTER
1527 return destination_from_socket(conn
, req
);
1528 #elif defined(TRANS_PF)
1529 const or_options_t
*options
= get_options();
1531 if (options
->TransProxyType_parsed
== TPT_PF_DIVERT
)
1532 return destination_from_socket(conn
, req
);
1534 if (options
->TransProxyType_parsed
== TPT_DEFAULT
)
1535 return destination_from_pf(conn
, req
);
1539 log_warn(LD_BUG
, "Proxy destination determination mechanism %s unknown.",
1540 options
->TransProxyType
);
1545 log_warn(LD_BUG
, "Called connection_ap_get_original_destination, but no "
1546 "transparent proxy method was configured.");
1551 /** connection_edge_process_inbuf() found a conn in state
1552 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1553 * the socks handshake.
1555 * If the handshake is complete, send it to
1556 * connection_ap_handshake_rewrite_and_attach().
1558 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1562 connection_ap_handshake_process_socks(entry_connection_t
*conn
)
1564 socks_request_t
*socks
;
1566 const or_options_t
*options
= get_options();
1568 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
1571 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
1572 tor_assert(base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
);
1573 tor_assert(conn
->socks_request
);
1574 socks
= conn
->socks_request
;
1576 log_debug(LD_APP
,"entered.");
1578 IF_HAS_BUFFEREVENT(base_conn
, {
1579 struct evbuffer
*input
= bufferevent_get_input(base_conn
->bufev
);
1580 sockshere
= fetch_from_evbuffer_socks(input
, socks
,
1581 options
->TestSocks
, options
->SafeSocks
);
1582 }) ELSE_IF_NO_BUFFEREVENT
{
1583 sockshere
= fetch_from_buf_socks(base_conn
->inbuf
, socks
,
1584 options
->TestSocks
, options
->SafeSocks
);
1587 if (socks
->replylen
) {
1589 connection_write_to_buf((const char*)socks
->reply
, socks
->replylen
,
1591 socks
->replylen
= 0;
1592 if (sockshere
== -1) {
1593 /* An invalid request just got a reply, no additional
1594 * one is necessary. */
1595 socks
->has_finished
= 1;
1599 if (sockshere
== 0) {
1600 log_debug(LD_APP
,"socks handshake not all here yet.");
1602 } else if (sockshere
== -1) {
1604 log_warn(LD_APP
,"Fetching socks handshake failed. Closing.");
1605 connection_ap_handshake_socks_reply(conn
, NULL
, 0,
1606 END_STREAM_REASON_SOCKSPROTOCOL
);
1608 connection_mark_unattached_ap(conn
,
1609 END_STREAM_REASON_SOCKSPROTOCOL
|
1610 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1612 } /* else socks handshake is done, continue processing */
1614 if (SOCKS_COMMAND_IS_CONNECT(socks
->command
))
1615 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1617 control_event_stream_status(conn
, STREAM_EVENT_NEW_RESOLVE
, 0);
1619 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
1622 /** connection_init_accepted_conn() found a new trans AP conn.
1623 * Get the original destination and send it to
1624 * connection_ap_handshake_rewrite_and_attach().
1626 * Return -1 if an unexpected error with conn (and it should be marked
1627 * for close), else return 0.
1630 connection_ap_process_transparent(entry_connection_t
*conn
)
1632 socks_request_t
*socks
;
1635 tor_assert(conn
->socks_request
);
1636 socks
= conn
->socks_request
;
1638 /* pretend that a socks handshake completed so we don't try to
1639 * send a socks reply down a transparent conn */
1640 socks
->command
= SOCKS_COMMAND_CONNECT
;
1641 socks
->has_finished
= 1;
1643 log_debug(LD_APP
,"entered.");
1645 if (connection_ap_get_original_destination(conn
, socks
) < 0) {
1646 log_warn(LD_APP
,"Fetching original destination failed. Closing.");
1647 connection_mark_unattached_ap(conn
,
1648 END_STREAM_REASON_CANT_FETCH_ORIG_DEST
);
1651 /* we have the original destination */
1653 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1655 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
1658 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1659 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1660 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1661 * form of the original destination.
1663 * If the original destination is complete, send it to
1664 * connection_ap_handshake_rewrite_and_attach().
1666 * Return -1 if an unexpected error with conn (and it should be marked
1667 * for close), else return 0.
1670 connection_ap_process_natd(entry_connection_t
*conn
)
1672 char tmp_buf
[36], *tbuf
, *daddr
;
1675 socks_request_t
*socks
;
1678 tor_assert(ENTRY_TO_CONN(conn
)->state
== AP_CONN_STATE_NATD_WAIT
);
1679 tor_assert(conn
->socks_request
);
1680 socks
= conn
->socks_request
;
1682 log_debug(LD_APP
,"entered.");
1684 /* look for LF-terminated "[DEST ip_addr port]"
1685 * where ip_addr is a dotted-quad and port is in string form */
1686 err
= connection_fetch_from_buf_line(ENTRY_TO_CONN(conn
), tmp_buf
, &tlen
);
1690 log_warn(LD_APP
,"NATD handshake failed (DEST too long). Closing");
1691 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1695 if (strcmpstart(tmp_buf
, "[DEST ")) {
1696 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
1699 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1703 daddr
= tbuf
= &tmp_buf
[0] + 6; /* after end of "[DEST " */
1704 if (!(tbuf
= strchr(tbuf
, ' '))) {
1705 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
1708 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1713 /* pretend that a socks handshake completed so we don't try to
1714 * send a socks reply down a natd conn */
1715 strlcpy(socks
->address
, daddr
, sizeof(socks
->address
));
1716 socks
->port
= (uint16_t)
1717 tor_parse_long(tbuf
, 10, 1, 65535, &port_ok
, &daddr
);
1719 log_warn(LD_APP
,"NATD handshake failed; port %s is ill-formed or out "
1720 "of range.", escaped(tbuf
));
1721 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1725 socks
->command
= SOCKS_COMMAND_CONNECT
;
1726 socks
->has_finished
= 1;
1728 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1730 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1732 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
1735 /** Iterate over the two bytes of stream_id until we get one that is not
1736 * already in use; return it. Return 0 if can't get a unique stream_id.
1739 get_unique_stream_id_by_circ(origin_circuit_t
*circ
)
1741 edge_connection_t
*tmpconn
;
1742 streamid_t test_stream_id
;
1743 uint32_t attempts
=0;
1746 test_stream_id
= circ
->next_stream_id
++;
1747 if (++attempts
> 1<<16) {
1748 /* Make sure we don't loop forever if all stream_id's are used. */
1749 log_warn(LD_APP
,"No unused stream IDs. Failing.");
1752 if (test_stream_id
== 0)
1754 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
1755 if (tmpconn
->stream_id
== test_stream_id
)
1757 return test_stream_id
;
1760 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
1761 * an exit that supports optimistic data. */
1763 connection_ap_supports_optimistic_data(const entry_connection_t
*conn
)
1765 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
1766 /* We can only send optimistic data if we're connected to an open
1768 if (edge_conn
->on_circuit
== NULL
||
1769 edge_conn
->on_circuit
->state
!= CIRCUIT_STATE_OPEN
||
1770 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
1773 return conn
->may_use_optimistic_data
;
1776 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
1777 * RELAY_BEGIN cell for <b>ap_conn</b>. */
1779 connection_ap_get_begincell_flags(entry_connection_t
*ap_conn
)
1781 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
1782 const node_t
*exitnode
= NULL
;
1783 const crypt_path_t
*cpath_layer
= edge_conn
->cpath_layer
;
1786 /* No flags for begindir */
1787 if (ap_conn
->use_begindir
)
1790 /* No flags for hidden services. */
1791 if (edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
1794 /* If only IPv4 is supported, no flags */
1795 if (ap_conn
->ipv4_traffic_ok
&& !ap_conn
->ipv6_traffic_ok
)
1798 if (! cpath_layer
||
1799 ! cpath_layer
->extend_info
)
1802 if (!ap_conn
->ipv4_traffic_ok
)
1803 flags
|= BEGIN_FLAG_IPV4_NOT_OK
;
1805 exitnode
= node_get_by_id(cpath_layer
->extend_info
->identity_digest
);
1807 if (ap_conn
->ipv6_traffic_ok
&& exitnode
) {
1809 tor_addr_make_null(&a
, AF_INET6
);
1810 if (compare_tor_addr_to_node_policy(&a
, ap_conn
->socks_request
->port
,
1812 != ADDR_POLICY_REJECTED
) {
1813 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
1815 flags
|= BEGIN_FLAG_IPV6_OK
;
1819 if (flags
== BEGIN_FLAG_IPV6_OK
) {
1820 /* When IPv4 and IPv6 are both allowed, consider whether to say we
1821 * prefer IPv6. Otherwise there's no point in declaring a preference */
1822 if (ap_conn
->prefer_ipv6_traffic
)
1823 flags
|= BEGIN_FLAG_IPV6_PREFERRED
;
1826 if (flags
== BEGIN_FLAG_IPV4_NOT_OK
) {
1827 log_warn(LD_EDGE
, "I'm about to ask a node for a connection that I "
1828 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
1829 "not going to work. Did you perhaps ask for an IPv6 address "
1830 "on an IPv4Only port, or vice versa?");
1836 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1837 * socks_request field, and send it down circ.
1839 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1842 connection_ap_handshake_send_begin(entry_connection_t
*ap_conn
)
1844 char payload
[CELL_PAYLOAD_SIZE
];
1847 origin_circuit_t
*circ
;
1848 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
1849 connection_t
*base_conn
= TO_CONN(edge_conn
);
1850 tor_assert(edge_conn
->on_circuit
);
1851 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
1853 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
1854 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1855 tor_assert(ap_conn
->socks_request
);
1856 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn
->socks_request
->command
));
1858 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
1859 if (edge_conn
->stream_id
==0) {
1860 /* XXXX024 Instead of closing this stream, we should make it get
1861 * retried on another circuit. */
1862 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1864 /* Mark this circuit "unusable for new streams". */
1865 mark_circuit_unusable_for_new_conns(circ
);
1869 /* Set up begin cell flags. */
1870 edge_conn
->begincell_flags
= connection_ap_get_begincell_flags(ap_conn
);
1872 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:%d",
1873 (circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
) ?
1874 ap_conn
->socks_request
->address
: "",
1875 ap_conn
->socks_request
->port
);
1876 payload_len
= (int)strlen(payload
)+1;
1877 if (payload_len
<= RELAY_PAYLOAD_SIZE
- 4 && edge_conn
->begincell_flags
) {
1878 set_uint32(payload
+ payload_len
, htonl(edge_conn
->begincell_flags
));
1883 "Sending relay cell %d to begin stream %d.",
1884 (int)ap_conn
->use_begindir
,
1885 edge_conn
->stream_id
);
1887 begin_type
= ap_conn
->use_begindir
?
1888 RELAY_COMMAND_BEGIN_DIR
: RELAY_COMMAND_BEGIN
;
1889 if (begin_type
== RELAY_COMMAND_BEGIN
) {
1890 #ifndef NON_ANONYMOUS_MODE_ENABLED
1891 tor_assert(circ
->build_state
->onehop_tunnel
== 0);
1895 if (connection_edge_send_command(edge_conn
, begin_type
,
1896 begin_type
== RELAY_COMMAND_BEGIN
? payload
: NULL
,
1897 begin_type
== RELAY_COMMAND_BEGIN
? payload_len
: 0) < 0)
1898 return -1; /* circuit is closed, don't continue */
1900 edge_conn
->package_window
= STREAMWINDOW_START
;
1901 edge_conn
->deliver_window
= STREAMWINDOW_START
;
1902 base_conn
->state
= AP_CONN_STATE_CONNECT_WAIT
;
1903 log_info(LD_APP
,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
1905 base_conn
->s
, (unsigned)circ
->base_
.n_circ_id
);
1906 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
, 0);
1908 /* If there's queued-up data, send it now */
1909 if ((connection_get_inbuf_len(base_conn
) ||
1910 ap_conn
->sending_optimistic_data
) &&
1911 connection_ap_supports_optimistic_data(ap_conn
)) {
1912 log_info(LD_APP
, "Sending up to %ld + %ld bytes of queued-up data",
1913 (long)connection_get_inbuf_len(base_conn
),
1914 ap_conn
->sending_optimistic_data
?
1915 (long)generic_buffer_len(ap_conn
->sending_optimistic_data
) : 0);
1916 if (connection_edge_package_raw_inbuf(edge_conn
, 1, NULL
) < 0) {
1917 connection_mark_for_close(base_conn
);
1924 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1925 * socks_request field, and send it down circ.
1927 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1930 connection_ap_handshake_send_resolve(entry_connection_t
*ap_conn
)
1932 int payload_len
, command
;
1933 const char *string_addr
;
1934 char inaddr_buf
[REVERSE_LOOKUP_NAME_BUF_LEN
];
1935 origin_circuit_t
*circ
;
1936 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
1937 connection_t
*base_conn
= TO_CONN(edge_conn
);
1938 tor_assert(edge_conn
->on_circuit
);
1939 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
1941 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
1942 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1943 tor_assert(ap_conn
->socks_request
);
1944 tor_assert(circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
1946 command
= ap_conn
->socks_request
->command
;
1947 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command
));
1949 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
1950 if (edge_conn
->stream_id
==0) {
1951 /* XXXX024 Instead of closing this stream, we should make it get
1952 * retried on another circuit. */
1953 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1955 /* Mark this circuit "unusable for new streams". */
1956 mark_circuit_unusable_for_new_conns(circ
);
1960 if (command
== SOCKS_COMMAND_RESOLVE
) {
1961 string_addr
= ap_conn
->socks_request
->address
;
1962 payload_len
= (int)strlen(string_addr
)+1;
1964 /* command == SOCKS_COMMAND_RESOLVE_PTR */
1965 const char *a
= ap_conn
->socks_request
->address
;
1969 /* We're doing a reverse lookup. The input could be an IP address, or
1970 * could be an .in-addr.arpa or .ip6.arpa address */
1971 r
= tor_addr_parse_PTR_name(&addr
, a
, AF_UNSPEC
, 1);
1973 log_warn(LD_APP
, "Rejecting ill-formed reverse lookup of %s",
1974 safe_str_client(a
));
1975 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1979 r
= tor_addr_to_PTR_name(inaddr_buf
, sizeof(inaddr_buf
), &addr
);
1981 log_warn(LD_BUG
, "Couldn't generate reverse lookup hostname of %s",
1982 safe_str_client(a
));
1983 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1987 string_addr
= inaddr_buf
;
1988 payload_len
= (int)strlen(inaddr_buf
)+1;
1989 tor_assert(payload_len
<= (int)sizeof(inaddr_buf
));
1993 "Sending relay cell to begin stream %d.", edge_conn
->stream_id
);
1995 if (connection_edge_send_command(edge_conn
,
1996 RELAY_COMMAND_RESOLVE
,
1997 string_addr
, payload_len
) < 0)
1998 return -1; /* circuit is closed, don't continue */
2000 if (!base_conn
->address
) {
2001 /* This might be unnecessary. XXXX */
2002 base_conn
->address
= tor_dup_addr(&base_conn
->addr
);
2004 base_conn
->state
= AP_CONN_STATE_RESOLVE_WAIT
;
2005 log_info(LD_APP
,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
2007 base_conn
->s
, (unsigned)circ
->base_
.n_circ_id
);
2008 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
, 0);
2012 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
2013 * new linked connection pair, and attach one side to the conn, connection_add
2014 * it, initialize it to circuit_wait, and call
2015 * connection_ap_handshake_attach_circuit(conn) on it.
2017 * Return the newly created end of the linked connection pair, or -1 if error.
2019 entry_connection_t
*
2020 connection_ap_make_link(connection_t
*partner
,
2021 char *address
, uint16_t port
,
2023 int session_group
, int isolation_flags
,
2024 int use_begindir
, int want_onehop
)
2026 entry_connection_t
*conn
;
2027 connection_t
*base_conn
;
2029 log_info(LD_APP
,"Making internal %s tunnel to %s:%d ...",
2030 want_onehop
? "direct" : "anonymized",
2031 safe_str_client(address
), port
);
2033 conn
= entry_connection_new(CONN_TYPE_AP
, tor_addr_family(&partner
->addr
));
2034 base_conn
= ENTRY_TO_CONN(conn
);
2035 base_conn
->linked
= 1; /* so that we can add it safely below. */
2037 /* populate conn->socks_request */
2039 /* leave version at zero, so the socks_reply is empty */
2040 conn
->socks_request
->socks_version
= 0;
2041 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
2042 strlcpy(conn
->socks_request
->address
, address
,
2043 sizeof(conn
->socks_request
->address
));
2044 conn
->socks_request
->port
= port
;
2045 conn
->socks_request
->command
= SOCKS_COMMAND_CONNECT
;
2046 conn
->want_onehop
= want_onehop
;
2047 conn
->use_begindir
= use_begindir
;
2049 conn
->chosen_exit_name
= tor_malloc(HEX_DIGEST_LEN
+2);
2050 conn
->chosen_exit_name
[0] = '$';
2052 base16_encode(conn
->chosen_exit_name
+1,HEX_DIGEST_LEN
+1,
2053 digest
, DIGEST_LEN
);
2056 /* Populate isolation fields. */
2057 conn
->socks_request
->listener_type
= CONN_TYPE_DIR_LISTENER
;
2058 conn
->original_dest_address
= tor_strdup(address
);
2059 conn
->session_group
= session_group
;
2060 conn
->isolation_flags
= isolation_flags
;
2062 base_conn
->address
= tor_strdup("(Tor_internal)");
2063 tor_addr_make_unspec(&base_conn
->addr
);
2064 base_conn
->port
= 0;
2066 connection_link_connections(partner
, base_conn
);
2068 if (connection_add(base_conn
) < 0) { /* no space, forget it */
2069 connection_free(base_conn
);
2073 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2075 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2077 /* attaching to a dirty circuit is fine */
2078 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
2079 if (!base_conn
->marked_for_close
)
2080 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
2084 log_info(LD_APP
,"... application connection created and linked.");
2088 /** Notify any interested controller connections about a new hostname resolve
2089 * or resolve error. Takes the same arguments as does
2090 * connection_ap_handshake_socks_resolved(). */
2092 tell_controller_about_resolved_result(entry_connection_t
*conn
,
2099 expires
= time(NULL
) + ttl
;
2100 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
>= 4) {
2101 char *cp
= tor_dup_ip(ntohl(get_uint32(answer
)));
2102 control_event_address_mapped(conn
->socks_request
->address
,
2103 cp
, expires
, NULL
, 0);
2105 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2106 char *cp
= tor_strndup(answer
, answer_len
);
2107 control_event_address_mapped(conn
->socks_request
->address
,
2108 cp
, expires
, NULL
, 0);
2111 control_event_address_mapped(conn
->socks_request
->address
,
2112 "<error>", time(NULL
)+ttl
,
2118 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
2122 connection_ap_handshake_socks_resolved_addr(entry_connection_t
*conn
,
2123 const tor_addr_t
*answer
,
2127 if (tor_addr_family(answer
) == AF_INET
) {
2128 uint32_t a
= tor_addr_to_ipv4n(answer
); /* network order */
2129 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
2132 } else if (tor_addr_family(answer
) == AF_INET6
) {
2133 const uint8_t *a
= tor_addr_to_in6_addr8(answer
);
2134 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV6
,16,
2138 log_warn(LD_BUG
, "Got called with address of unexpected family %d",
2139 tor_addr_family(answer
));
2140 connection_ap_handshake_socks_resolved(conn
,
2141 RESOLVED_TYPE_ERROR
,0,NULL
,-1,-1);
2145 /** Send an answer to an AP connection that has requested a DNS lookup via
2146 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2147 * for unreachable; the answer should be in the format specified in the socks
2148 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2149 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2150 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2152 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
2153 * interface and those that use it less ugly. */
2155 connection_ap_handshake_socks_resolved
,(entry_connection_t
*conn
,
2158 const uint8_t *answer
,
2166 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2168 tor_addr_from_ipv4n(&a
, get_uint32(answer
));
2169 if (! tor_addr_is_null(&a
)) {
2170 client_dns_set_addressmap(conn
,
2171 conn
->socks_request
->address
, &a
,
2172 conn
->chosen_exit_name
, ttl
);
2174 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
2176 tor_addr_from_ipv6_bytes(&a
, (char*)answer
);
2177 if (! tor_addr_is_null(&a
)) {
2178 client_dns_set_addressmap(conn
,
2179 conn
->socks_request
->address
, &a
,
2180 conn
->chosen_exit_name
, ttl
);
2182 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2183 char *cp
= tor_strndup((char*)answer
, answer_len
);
2184 client_dns_set_reverse_addressmap(conn
,
2185 conn
->socks_request
->address
,
2187 conn
->chosen_exit_name
, ttl
);
2192 if (ENTRY_TO_EDGE_CONN(conn
)->is_dns_request
) {
2193 if (conn
->dns_server_request
) {
2194 /* We had a request on our DNS port: answer it. */
2195 dnsserv_resolved(conn
, answer_type
, answer_len
, (char*)answer
, ttl
);
2196 conn
->socks_request
->has_finished
= 1;
2199 /* This must be a request from the controller. Since answers to those
2200 * requests are not cached, they do not generate an ADDRMAP event on
2202 tell_controller_about_resolved_result(conn
, answer_type
, answer_len
,
2203 (char*)answer
, ttl
, expires
);
2204 conn
->socks_request
->has_finished
= 1;
2207 /* We shouldn't need to free conn here; it gets marked by the caller. */
2210 if (conn
->socks_request
->socks_version
== 4) {
2211 buf
[0] = 0x00; /* version */
2212 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2213 buf
[1] = SOCKS4_GRANTED
;
2214 set_uint16(buf
+2, 0);
2215 memcpy(buf
+4, answer
, 4); /* address */
2216 replylen
= SOCKS4_NETWORK_LEN
;
2217 } else { /* "error" */
2218 buf
[1] = SOCKS4_REJECT
;
2219 memset(buf
+2, 0, 6);
2220 replylen
= SOCKS4_NETWORK_LEN
;
2222 } else if (conn
->socks_request
->socks_version
== 5) {
2224 buf
[0] = 0x05; /* version */
2225 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2226 buf
[1] = SOCKS5_SUCCEEDED
;
2227 buf
[2] = 0; /* reserved */
2228 buf
[3] = 0x01; /* IPv4 address type */
2229 memcpy(buf
+4, answer
, 4); /* address */
2230 set_uint16(buf
+8, 0); /* port == 0. */
2232 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
2233 buf
[1] = SOCKS5_SUCCEEDED
;
2234 buf
[2] = 0; /* reserved */
2235 buf
[3] = 0x04; /* IPv6 address type */
2236 memcpy(buf
+4, answer
, 16); /* address */
2237 set_uint16(buf
+20, 0); /* port == 0. */
2239 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2240 buf
[1] = SOCKS5_SUCCEEDED
;
2241 buf
[2] = 0; /* reserved */
2242 buf
[3] = 0x03; /* Domainname address type */
2243 buf
[4] = (char)answer_len
;
2244 memcpy(buf
+5, answer
, answer_len
); /* address */
2245 set_uint16(buf
+5+answer_len
, 0); /* port == 0. */
2246 replylen
= 5+answer_len
+2;
2248 buf
[1] = SOCKS5_HOST_UNREACHABLE
;
2249 memset(buf
+2, 0, 8);
2253 /* no socks version info; don't send anything back */
2256 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
2257 (answer_type
== RESOLVED_TYPE_IPV4
||
2258 answer_type
== RESOLVED_TYPE_IPV6
||
2259 answer_type
== RESOLVED_TYPE_HOSTNAME
) ?
2260 0 : END_STREAM_REASON_RESOLVEFAILED
);
2263 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2264 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2267 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2268 * and return, else reply based on <b>endreason</b> (one of
2269 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2270 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2273 connection_ap_handshake_socks_reply(entry_connection_t
*conn
, char *reply
,
2274 size_t replylen
, int endreason
)
2277 socks5_reply_status_t status
=
2278 stream_end_reason_to_socks5_response(endreason
);
2280 tor_assert(conn
->socks_request
); /* make sure it's an AP stream */
2282 if (!SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
2283 control_event_stream_status(conn
, status
==SOCKS5_SUCCEEDED
?
2284 STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
,
2288 /* Flag this stream's circuit as having completed a stream successfully
2289 * (for path bias) */
2290 if (status
== SOCKS5_SUCCEEDED
||
2291 endreason
== END_STREAM_REASON_RESOLVEFAILED
||
2292 endreason
== END_STREAM_REASON_CONNECTREFUSED
||
2293 endreason
== END_STREAM_REASON_CONNRESET
||
2294 endreason
== END_STREAM_REASON_NOROUTE
||
2295 endreason
== END_STREAM_REASON_RESOURCELIMIT
) {
2296 if (!conn
->edge_
.on_circuit
||
2297 !CIRCUIT_IS_ORIGIN(conn
->edge_
.on_circuit
)) {
2298 if (endreason
!= END_STREAM_REASON_RESOLVEFAILED
) {
2300 "No origin circuit for successful SOCKS stream "U64_FORMAT
2302 U64_PRINTF_ARG(ENTRY_TO_CONN(conn
)->global_identifier
),
2306 * Else DNS remaps and failed hidden service lookups can send us
2307 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
2309 * Perhaps we could make the test more precise; we can tell hidden
2310 * services by conn->edge_.renddata != NULL; anything analogous for
2311 * the DNS remap case?
2314 // XXX: Hrmm. It looks like optimistic data can't go through this
2315 // codepath, but someone should probably test it and make sure.
2316 // We don't want to mark optimistically opened streams as successful.
2317 pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn
->edge_
.on_circuit
));
2321 if (conn
->socks_request
->has_finished
) {
2322 log_warn(LD_BUG
, "(Harmless.) duplicate calls to "
2323 "connection_ap_handshake_socks_reply.");
2326 if (replylen
) { /* we already have a reply in mind */
2327 connection_write_to_buf(reply
, replylen
, ENTRY_TO_CONN(conn
));
2328 conn
->socks_request
->has_finished
= 1;
2331 if (conn
->socks_request
->socks_version
== 4) {
2332 memset(buf
,0,SOCKS4_NETWORK_LEN
);
2333 buf
[1] = (status
==SOCKS5_SUCCEEDED
? SOCKS4_GRANTED
: SOCKS4_REJECT
);
2334 /* leave version, destport, destip zero */
2335 connection_write_to_buf(buf
, SOCKS4_NETWORK_LEN
, ENTRY_TO_CONN(conn
));
2336 } else if (conn
->socks_request
->socks_version
== 5) {
2338 memset(buf
,0,sizeof(buf
));
2339 if (tor_addr_family(&conn
->edge_
.base_
.addr
) == AF_INET
) {
2340 buf
[0] = 5; /* version 5 */
2341 buf
[1] = (char)status
;
2343 buf
[3] = 1; /* ipv4 addr */
2344 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
2346 } else { /* AF_INET6. */
2347 buf
[0] = 5; /* version 5 */
2348 buf
[1] = (char)status
;
2350 buf
[3] = 4; /* ipv6 addr */
2351 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
2354 connection_write_to_buf(buf
,buf_len
,ENTRY_TO_CONN(conn
));
2356 /* If socks_version isn't 4 or 5, don't send anything.
2357 * This can happen in the case of AP bridges. */
2358 conn
->socks_request
->has_finished
= 1;
2362 /** Read a RELAY_BEGIN or RELAY_BEGINDIR cell from <b>cell</b>, decode it, and
2363 * place the result in <b>bcell</b>. On success return 0; on failure return
2364 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
2367 * Return -1 in the case where want to send a RELAY_END cell, and < -1 when
2371 begin_cell_parse(const cell_t
*cell
, begin_cell_t
*bcell
,
2372 uint8_t *end_reason_out
)
2375 const uint8_t *body
, *nul
;
2377 memset(bcell
, 0, sizeof(*bcell
));
2378 *end_reason_out
= END_STREAM_REASON_MISC
;
2380 relay_header_unpack(&rh
, cell
->payload
);
2381 if (rh
.length
> RELAY_PAYLOAD_SIZE
) {
2382 return -2; /*XXXX why not TORPROTOCOL? */
2385 bcell
->stream_id
= rh
.stream_id
;
2387 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2388 bcell
->is_begindir
= 1;
2390 } else if (rh
.command
!= RELAY_COMMAND_BEGIN
) {
2391 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
2392 *end_reason_out
= END_STREAM_REASON_INTERNAL
;
2396 body
= cell
->payload
+ RELAY_HEADER_SIZE
;
2397 nul
= memchr(body
, 0, rh
.length
);
2399 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2400 "Relay begin cell has no \\0. Closing.");
2401 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
2405 if (tor_addr_port_split(LOG_PROTOCOL_WARN
,
2407 &bcell
->address
,&bcell
->port
)<0) {
2408 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2409 "Unable to parse addr:port in relay begin cell. Closing.");
2410 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
2413 if (bcell
->port
== 0) {
2414 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2415 "Missing port in relay begin cell. Closing.");
2416 tor_free(bcell
->address
);
2417 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
2420 if (body
+ rh
.length
>= nul
+ 4)
2421 bcell
->flags
= ntohl(get_uint32(nul
+1));
2426 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2427 * an exit hop for the circuit, or we are the origin and it is a
2430 * Launch a new exit connection and initialize things appropriately.
2432 * If it's a rendezvous stream, call connection_exit_connect() on
2435 * For general streams, call dns_resolve() on it first, and only call
2436 * connection_exit_connect() if the dns answer is already known.
2438 * Note that we don't call connection_add() on the new stream! We wait
2439 * for connection_exit_connect() to do that.
2441 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2445 connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
)
2447 edge_connection_t
*n_stream
;
2449 char *address
= NULL
;
2451 or_circuit_t
*or_circ
= NULL
;
2452 const or_options_t
*options
= get_options();
2455 uint8_t end_reason
=0;
2457 assert_circuit_ok(circ
);
2458 if (!CIRCUIT_IS_ORIGIN(circ
))
2459 or_circ
= TO_OR_CIRCUIT(circ
);
2461 relay_header_unpack(&rh
, cell
->payload
);
2462 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
2465 /* Note: we have to use relay_send_command_from_edge here, not
2466 * connection_edge_end or connection_edge_send_command, since those require
2467 * that we have a stream connected to a circuit, and we don't connect to a
2468 * circuit until we have a pending/successful resolve. */
2470 if (!server_mode(options
) &&
2471 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
2472 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2473 "Relay begin cell at non-server. Closing.");
2474 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2475 END_STREAM_REASON_EXITPOLICY
, NULL
);
2479 r
= begin_cell_parse(cell
, &bcell
, &end_reason
);
2482 } else if (r
== -1) {
2483 tor_free(bcell
.address
);
2484 relay_send_end_cell_from_edge(rh
.stream_id
, circ
, end_reason
, NULL
);
2488 if (! bcell
.is_begindir
) {
2489 /* Steal reference */
2490 address
= bcell
.address
;
2493 if (or_circ
&& or_circ
->p_chan
) {
2494 if (!options
->AllowSingleHopExits
&&
2495 (or_circ
->is_first_hop
||
2496 (!connection_or_digest_is_known_relay(
2497 or_circ
->p_chan
->identity_digest
) &&
2498 should_refuse_unknown_exits(options
)))) {
2499 /* Don't let clients use us as a single-hop proxy, unless the user
2500 * has explicitly allowed that in the config. It attracts attackers
2501 * and users who'd be better off with, well, single-hop proxies.
2503 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2504 "Attempt by %s to open a stream %s. Closing.",
2505 safe_str(channel_get_canonical_remote_descr(or_circ
->p_chan
)),
2506 or_circ
->is_first_hop
? "on first hop of circuit" :
2507 "from unknown relay");
2508 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2509 or_circ
->is_first_hop
?
2510 END_STREAM_REASON_TORPROTOCOL
:
2511 END_STREAM_REASON_MISC
,
2517 } else if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2518 if (!directory_permits_begindir_requests(options
) ||
2519 circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
2520 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2521 END_STREAM_REASON_NOTDIRECTORY
, NULL
);
2524 /* Make sure to get the 'real' address of the previous hop: the
2525 * caller might want to know whether his IP address has changed, and
2526 * we might already have corrected base_.addr[ess] for the relay's
2527 * canonical IP address. */
2528 if (or_circ
&& or_circ
->p_chan
)
2529 address
= tor_strdup(channel_get_actual_remote_address(or_circ
->p_chan
));
2531 address
= tor_strdup("127.0.0.1");
2532 port
= 1; /* XXXX This value is never actually used anywhere, and there
2533 * isn't "really" a connection here. But we
2534 * need to set it to something nonzero. */
2536 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
2537 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2538 END_STREAM_REASON_INTERNAL
, NULL
);
2542 if (! options
->IPv6Exit
) {
2543 /* I don't care if you prefer IPv6; I can't give you any. */
2544 bcell
.flags
&= ~BEGIN_FLAG_IPV6_PREFERRED
;
2545 /* If you don't want IPv4, I can't help. */
2546 if (bcell
.flags
& BEGIN_FLAG_IPV4_NOT_OK
) {
2548 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2549 END_STREAM_REASON_EXITPOLICY
, NULL
);
2554 log_debug(LD_EXIT
,"Creating new exit connection.");
2555 /* The 'AF_INET' here is temporary; we might need to change it later in
2556 * connection_exit_connect(). */
2557 n_stream
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
2559 /* Remember the tunneled request ID in the new edge connection, so that
2560 * we can measure download times. */
2561 n_stream
->dirreq_id
= circ
->dirreq_id
;
2563 n_stream
->base_
.purpose
= EXIT_PURPOSE_CONNECT
;
2564 n_stream
->begincell_flags
= bcell
.flags
;
2565 n_stream
->stream_id
= rh
.stream_id
;
2566 n_stream
->base_
.port
= port
;
2567 /* leave n_stream->s at -1, because it's not yet valid */
2568 n_stream
->package_window
= STREAMWINDOW_START
;
2569 n_stream
->deliver_window
= STREAMWINDOW_START
;
2571 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
2572 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2573 log_info(LD_REND
,"begin is for rendezvous. configuring stream.");
2574 n_stream
->base_
.address
= tor_strdup("(rendezvous)");
2575 n_stream
->base_
.state
= EXIT_CONN_STATE_CONNECTING
;
2576 n_stream
->rend_data
= rend_data_dup(origin_circ
->rend_data
);
2577 tor_assert(connection_edge_is_rendezvous_stream(n_stream
));
2578 assert_circuit_ok(circ
);
2579 if (rend_service_set_connection_addr_port(n_stream
, origin_circ
) < 0) {
2580 log_info(LD_REND
,"Didn't find rendezvous service (port %d)",
2581 n_stream
->base_
.port
);
2582 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2583 END_STREAM_REASON_EXITPOLICY
,
2584 origin_circ
->cpath
->prev
);
2585 connection_free(TO_CONN(n_stream
));
2589 assert_circuit_ok(circ
);
2590 log_debug(LD_REND
,"Finished assigning addr/port");
2591 n_stream
->cpath_layer
= origin_circ
->cpath
->prev
; /* link it */
2593 /* add it into the linked list of p_streams on this circuit */
2594 n_stream
->next_stream
= origin_circ
->p_streams
;
2595 n_stream
->on_circuit
= circ
;
2596 origin_circ
->p_streams
= n_stream
;
2597 assert_circuit_ok(circ
);
2599 connection_exit_connect(n_stream
);
2601 /* For path bias: This circuit was used successfully */
2602 pathbias_mark_use_success(origin_circ
);
2607 tor_strlower(address
);
2608 n_stream
->base_
.address
= address
;
2609 n_stream
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2610 /* default to failed, change in dns_resolve if it turns out not to fail */
2612 if (we_are_hibernating()) {
2613 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2614 END_STREAM_REASON_HIBERNATING
, NULL
);
2615 connection_free(TO_CONN(n_stream
));
2619 n_stream
->on_circuit
= circ
;
2621 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2622 tor_addr_t tmp_addr
;
2623 tor_assert(or_circ
);
2624 if (or_circ
->p_chan
&&
2625 channel_get_addr_if_possible(or_circ
->p_chan
, &tmp_addr
)) {
2626 tor_addr_copy(&n_stream
->base_
.addr
, &tmp_addr
);
2628 return connection_exit_connect_dir(n_stream
);
2631 log_debug(LD_EXIT
,"about to start the dns_resolve().");
2633 /* send it off to the gethostbyname farm */
2634 switch (dns_resolve(n_stream
)) {
2635 case 1: /* resolve worked; now n_stream is attached to circ. */
2636 assert_circuit_ok(circ
);
2637 log_debug(LD_EXIT
,"about to call connection_exit_connect().");
2638 connection_exit_connect(n_stream
);
2640 case -1: /* resolve failed */
2641 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2642 END_STREAM_REASON_RESOLVEFAILED
, NULL
);
2643 /* n_stream got freed. don't touch it. */
2645 case 0: /* resolve added to pending list */
2646 assert_circuit_ok(circ
);
2653 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2654 * circuit <b>circ</b>;
2655 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2658 connection_exit_begin_resolve(cell_t
*cell
, or_circuit_t
*circ
)
2660 edge_connection_t
*dummy_conn
;
2663 assert_circuit_ok(TO_CIRCUIT(circ
));
2664 relay_header_unpack(&rh
, cell
->payload
);
2665 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
2668 /* This 'dummy_conn' only exists to remember the stream ID
2669 * associated with the resolve request; and to make the
2670 * implementation of dns.c more uniform. (We really only need to
2671 * remember the circuit, the stream ID, and the hostname to be
2672 * resolved; but if we didn't store them in a connection like this,
2673 * the housekeeping in dns.c would get way more complicated.)
2675 dummy_conn
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
2676 dummy_conn
->stream_id
= rh
.stream_id
;
2677 dummy_conn
->base_
.address
= tor_strndup(
2678 (char*)cell
->payload
+RELAY_HEADER_SIZE
,
2680 dummy_conn
->base_
.port
= 0;
2681 dummy_conn
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2682 dummy_conn
->base_
.purpose
= EXIT_PURPOSE_RESOLVE
;
2684 dummy_conn
->on_circuit
= TO_CIRCUIT(circ
);
2686 /* send it off to the gethostbyname farm */
2687 switch (dns_resolve(dummy_conn
)) {
2688 case -1: /* Impossible to resolve; a resolved cell was sent. */
2689 /* Connection freed; don't touch it. */
2691 case 1: /* The result was cached; a resolved cell was sent. */
2692 if (!dummy_conn
->base_
.marked_for_close
)
2693 connection_free(TO_CONN(dummy_conn
));
2695 case 0: /* resolve added to pending list */
2696 assert_circuit_ok(TO_CIRCUIT(circ
));
2702 /** Connect to conn's specified addr and port. If it worked, conn
2703 * has now been added to the connection_array.
2705 * Send back a connected cell. Include the resolved IP of the destination
2706 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2707 * streams must not reveal what IP they connected to.)
2710 connection_exit_connect(edge_connection_t
*edge_conn
)
2712 const tor_addr_t
*addr
;
2714 connection_t
*conn
= TO_CONN(edge_conn
);
2715 int socket_error
= 0;
2717 if ( (!connection_edge_is_rendezvous_stream(edge_conn
) &&
2718 router_compare_to_my_exit_policy(&edge_conn
->base_
.addr
,
2719 edge_conn
->base_
.port
)) ||
2720 (tor_addr_family(&conn
->addr
) == AF_INET6
&&
2721 ! get_options()->IPv6Exit
)) {
2722 log_info(LD_EXIT
,"%s:%d failed exit policy. Closing.",
2723 escaped_safe_str_client(conn
->address
), conn
->port
);
2724 connection_edge_end(edge_conn
, END_STREAM_REASON_EXITPOLICY
);
2725 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2726 connection_free(conn
);
2733 if (tor_addr_family(addr
) == AF_INET6
)
2734 conn
->socket_family
= AF_INET6
;
2736 log_debug(LD_EXIT
,"about to try connecting");
2737 switch (connection_connect(conn
, conn
->address
, addr
, port
, &socket_error
)) {
2739 int reason
= errno_to_stream_end_reason(socket_error
);
2740 connection_edge_end(edge_conn
, reason
);
2741 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2742 connection_free(conn
);
2746 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
2748 connection_watch_events(conn
, READ_EVENT
| WRITE_EVENT
);
2749 /* writable indicates finish;
2750 * readable/error indicates broken link in windows-land. */
2752 /* case 1: fall through */
2755 conn
->state
= EXIT_CONN_STATE_OPEN
;
2756 if (connection_get_outbuf_len(conn
)) {
2757 /* in case there are any queued data cells, from e.g. optimistic data */
2758 IF_HAS_NO_BUFFEREVENT(conn
)
2759 connection_watch_events(conn
, READ_EVENT
|WRITE_EVENT
);
2761 IF_HAS_NO_BUFFEREVENT(conn
)
2762 connection_watch_events(conn
, READ_EVENT
);
2765 /* also, deliver a 'connected' cell back through the circuit. */
2766 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
2767 /* rendezvous stream */
2768 /* don't send an address back! */
2769 connection_edge_send_command(edge_conn
,
2770 RELAY_COMMAND_CONNECTED
,
2772 } else { /* normal stream */
2773 uint8_t connected_payload
[MAX_CONNECTED_CELL_PAYLOAD_LEN
];
2774 int connected_payload_len
=
2775 connected_cell_format_payload(connected_payload
, &conn
->addr
,
2776 edge_conn
->address_ttl
);
2777 if (connected_payload_len
< 0) {
2778 connection_edge_end(edge_conn
, END_STREAM_REASON_INTERNAL
);
2779 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2780 connection_free(conn
);
2784 connection_edge_send_command(edge_conn
,
2785 RELAY_COMMAND_CONNECTED
,
2786 (char*)connected_payload
,
2787 connected_payload_len
);
2791 /** Given an exit conn that should attach to us as a directory server, open a
2792 * bridge connection with a linked connection pair, create a new directory
2793 * conn, and join them together. Return 0 on success (or if there was an
2794 * error we could send back an end cell for). Return -(some circuit end
2795 * reason) if the circuit needs to be torn down. Either connects
2796 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2799 connection_exit_connect_dir(edge_connection_t
*exitconn
)
2801 dir_connection_t
*dirconn
= NULL
;
2802 or_circuit_t
*circ
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
2804 log_info(LD_EXIT
, "Opening local connection for anonymized directory exit");
2806 exitconn
->base_
.state
= EXIT_CONN_STATE_OPEN
;
2808 dirconn
= dir_connection_new(tor_addr_family(&exitconn
->base_
.addr
));
2810 tor_addr_copy(&dirconn
->base_
.addr
, &exitconn
->base_
.addr
);
2811 dirconn
->base_
.port
= 0;
2812 dirconn
->base_
.address
= tor_strdup(exitconn
->base_
.address
);
2813 dirconn
->base_
.type
= CONN_TYPE_DIR
;
2814 dirconn
->base_
.purpose
= DIR_PURPOSE_SERVER
;
2815 dirconn
->base_
.state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
2817 /* Note that the new dir conn belongs to the same tunneled request as
2818 * the edge conn, so that we can measure download times. */
2819 dirconn
->dirreq_id
= exitconn
->dirreq_id
;
2821 connection_link_connections(TO_CONN(dirconn
), TO_CONN(exitconn
));
2823 if (connection_add(TO_CONN(exitconn
))<0) {
2824 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
2825 connection_free(TO_CONN(exitconn
));
2826 connection_free(TO_CONN(dirconn
));
2830 /* link exitconn to circ, now that we know we can use it. */
2831 exitconn
->next_stream
= circ
->n_streams
;
2832 circ
->n_streams
= exitconn
;
2834 if (connection_add(TO_CONN(dirconn
))<0) {
2835 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
2836 connection_close_immediate(TO_CONN(exitconn
));
2837 connection_mark_for_close(TO_CONN(exitconn
));
2838 connection_free(TO_CONN(dirconn
));
2842 connection_start_reading(TO_CONN(dirconn
));
2843 connection_start_reading(TO_CONN(exitconn
));
2845 if (connection_edge_send_command(exitconn
,
2846 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0) {
2847 connection_mark_for_close(TO_CONN(exitconn
));
2848 connection_mark_for_close(TO_CONN(dirconn
));
2855 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2856 * it is a general stream.
2859 connection_edge_is_rendezvous_stream(edge_connection_t
*conn
)
2862 if (conn
->rend_data
)
2867 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2868 * to exit from it, or 0 if it probably will not allow it.
2869 * (We might be uncertain if conn's destination address has not yet been
2873 connection_ap_can_use_exit(const entry_connection_t
*conn
, const node_t
*exit
)
2875 const or_options_t
*options
= get_options();
2878 tor_assert(conn
->socks_request
);
2881 /* If a particular exit node has been requested for the new connection,
2882 * make sure the exit node of the existing circuit matches exactly.
2884 if (conn
->chosen_exit_name
) {
2885 const node_t
*chosen_exit
=
2886 node_get_by_nickname(conn
->chosen_exit_name
, 1);
2887 if (!chosen_exit
|| tor_memneq(chosen_exit
->identity
,
2888 exit
->identity
, DIGEST_LEN
)) {
2890 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2891 // conn->chosen_exit_name, exit->nickname);
2896 if (conn
->use_begindir
) {
2897 /* Internal directory fetches do not count as exiting. */
2901 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
2902 tor_addr_t addr
, *addrp
= NULL
;
2903 addr_policy_result_t r
;
2904 if (0 == tor_addr_parse(&addr
, conn
->socks_request
->address
)) {
2906 } else if (!conn
->ipv4_traffic_ok
&& conn
->ipv6_traffic_ok
) {
2907 tor_addr_make_null(&addr
, AF_INET6
);
2909 } else if (conn
->ipv4_traffic_ok
&& !conn
->ipv6_traffic_ok
) {
2910 tor_addr_make_null(&addr
, AF_INET
);
2913 r
= compare_tor_addr_to_node_policy(addrp
, conn
->socks_request
->port
,exit
);
2914 if (r
== ADDR_POLICY_REJECTED
)
2915 return 0; /* We know the address, and the exit policy rejects it. */
2916 if (r
== ADDR_POLICY_PROBABLY_REJECTED
&& !conn
->chosen_exit_name
)
2917 return 0; /* We don't know the addr, but the exit policy rejects most
2918 * addresses with this port. Since the user didn't ask for
2919 * this node, err on the side of caution. */
2920 } else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
2921 /* Don't send DNS requests to non-exit servers by default. */
2922 if (!conn
->chosen_exit_name
&& node_exit_policy_rejects_all(exit
))
2925 if (routerset_contains_node(options
->ExcludeExitNodesUnion_
, exit
)) {
2926 /* Not a suitable exit. Refuse it. */
2933 /** If address is of the form "y.onion" with a well-formed handle y:
2934 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2936 * If address is of the form "x.y.onion" with a well-formed handle x:
2937 * Drop "x.", put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2939 * If address is of the form "y.onion" with a badly-formed handle y:
2940 * Return BAD_HOSTNAME and log a message.
2942 * If address is of the form "y.exit":
2943 * Put a NUL after y and return EXIT_HOSTNAME.
2946 * Return NORMAL_HOSTNAME and change nothing.
2949 parse_extended_hostname(char *address
)
2953 char query
[REND_SERVICE_ID_LEN_BASE32
+1];
2955 s
= strrchr(address
,'.');
2957 return NORMAL_HOSTNAME
; /* no dot, thus normal */
2958 if (!strcmp(s
+1,"exit")) {
2959 *s
= 0; /* NUL-terminate it */
2960 return EXIT_HOSTNAME
; /* .exit */
2962 if (strcmp(s
+1,"onion"))
2963 return NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
2965 /* so it is .onion */
2966 *s
= 0; /* NUL-terminate it */
2967 /* locate a 'sub-domain' component, in order to remove it */
2968 q
= strrchr(address
, '.');
2970 goto failed
; /* reject sub-domain, as DNS does */
2972 q
= (NULL
== q
) ? address
: q
+ 1;
2973 if (strlcpy(query
, q
, REND_SERVICE_ID_LEN_BASE32
+1) >=
2974 REND_SERVICE_ID_LEN_BASE32
+1)
2977 memmove(address
, q
, strlen(q
) + 1 /* also get \0 */);
2979 if (rend_valid_service_id(query
)) {
2980 return ONION_HOSTNAME
; /* success */
2983 /* otherwise, return to previous state and return 0 */
2985 log_warn(LD_APP
, "Invalid onion hostname %s; rejecting",
2986 safe_str_client(address
));
2987 return BAD_HOSTNAME
;
2990 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
2991 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
2994 memeq_opt(const char *a
, size_t alen
, const char *b
, size_t blen
)
2998 } else if (b
== NULL
) {
3000 } else if (alen
!= blen
) {
3003 return tor_memeq(a
, b
, alen
);
3008 * Return true iff none of the isolation flags and fields in <b>conn</b>
3009 * should prevent it from being attached to <b>circ</b>.
3012 connection_edge_compatible_with_circuit(const entry_connection_t
*conn
,
3013 const origin_circuit_t
*circ
)
3015 const uint8_t iso
= conn
->isolation_flags
;
3016 const socks_request_t
*sr
= conn
->socks_request
;
3018 /* If circ has never been used for an isolated connection, we can
3019 * totally use it for this one. */
3020 if (!circ
->isolation_values_set
)
3023 /* If circ has been used for connections having more than one value
3024 * for some field f, it will have the corresponding bit set in
3025 * isolation_flags_mixed. If isolation_flags_mixed has any bits
3026 * in common with iso, then conn must be isolated from at least
3027 * one stream that has been attached to circ. */
3028 if ((iso
& circ
->isolation_flags_mixed
) != 0) {
3029 /* For at least one field where conn is isolated, the circuit
3030 * already has mixed streams. */
3034 if (! conn
->original_dest_address
) {
3035 log_warn(LD_BUG
, "Reached connection_edge_compatible_with_circuit without "
3036 "having set conn->original_dest_address");
3037 ((entry_connection_t
*)conn
)->original_dest_address
=
3038 tor_strdup(conn
->socks_request
->address
);
3041 if ((iso
& ISO_STREAM
) &&
3042 (circ
->associated_isolated_stream_global_id
!=
3043 ENTRY_TO_CONN(conn
)->global_identifier
))
3046 if ((iso
& ISO_DESTPORT
) && conn
->socks_request
->port
!= circ
->dest_port
)
3048 if ((iso
& ISO_DESTADDR
) &&
3049 strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
3051 if ((iso
& ISO_SOCKSAUTH
) &&
3052 (! memeq_opt(sr
->username
, sr
->usernamelen
,
3053 circ
->socks_username
, circ
->socks_username_len
) ||
3054 ! memeq_opt(sr
->password
, sr
->passwordlen
,
3055 circ
->socks_password
, circ
->socks_password_len
)))
3057 if ((iso
& ISO_CLIENTPROTO
) &&
3058 (conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
3059 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
3061 if ((iso
& ISO_CLIENTADDR
) &&
3062 !tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
3064 if ((iso
& ISO_SESSIONGRP
) && conn
->session_group
!= circ
->session_group
)
3066 if ((iso
& ISO_NYM_EPOCH
) && conn
->nym_epoch
!= circ
->nym_epoch
)
3073 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
3074 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
3075 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
3076 * a bitfield of isolation flags that we would have to set in
3077 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
3078 * <b>circ</b> has had no streams attached to it.
3081 connection_edge_update_circuit_isolation(const entry_connection_t
*conn
,
3082 origin_circuit_t
*circ
,
3085 const socks_request_t
*sr
= conn
->socks_request
;
3086 if (! conn
->original_dest_address
) {
3087 log_warn(LD_BUG
, "Reached connection_update_circuit_isolation without "
3088 "having set conn->original_dest_address");
3089 ((entry_connection_t
*)conn
)->original_dest_address
=
3090 tor_strdup(conn
->socks_request
->address
);
3093 if (!circ
->isolation_values_set
) {
3096 circ
->associated_isolated_stream_global_id
=
3097 ENTRY_TO_CONN(conn
)->global_identifier
;
3098 circ
->dest_port
= conn
->socks_request
->port
;
3099 circ
->dest_address
= tor_strdup(conn
->original_dest_address
);
3100 circ
->client_proto_type
= conn
->socks_request
->listener_type
;
3101 circ
->client_proto_socksver
= conn
->socks_request
->socks_version
;
3102 tor_addr_copy(&circ
->client_addr
, &ENTRY_TO_CONN(conn
)->addr
);
3103 circ
->session_group
= conn
->session_group
;
3104 circ
->nym_epoch
= conn
->nym_epoch
;
3105 circ
->socks_username
= sr
->username
?
3106 tor_memdup(sr
->username
, sr
->usernamelen
) : NULL
;
3107 circ
->socks_password
= sr
->password
?
3108 tor_memdup(sr
->password
, sr
->passwordlen
) : NULL
;
3109 circ
->socks_username_len
= sr
->usernamelen
;
3110 circ
->socks_password_len
= sr
->passwordlen
;
3112 circ
->isolation_values_set
= 1;
3116 if (conn
->socks_request
->port
!= circ
->dest_port
)
3117 mixed
|= ISO_DESTPORT
;
3118 if (strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
3119 mixed
|= ISO_DESTADDR
;
3120 if (!memeq_opt(sr
->username
, sr
->usernamelen
,
3121 circ
->socks_username
, circ
->socks_username_len
) ||
3122 !memeq_opt(sr
->password
, sr
->passwordlen
,
3123 circ
->socks_password
, circ
->socks_password_len
))
3124 mixed
|= ISO_SOCKSAUTH
;
3125 if ((conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
3126 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
3127 mixed
|= ISO_CLIENTPROTO
;
3128 if (!tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
3129 mixed
|= ISO_CLIENTADDR
;
3130 if (conn
->session_group
!= circ
->session_group
)
3131 mixed
|= ISO_SESSIONGRP
;
3132 if (conn
->nym_epoch
!= circ
->nym_epoch
)
3133 mixed
|= ISO_NYM_EPOCH
;
3138 if ((mixed
& conn
->isolation_flags
) != 0) {
3139 log_warn(LD_BUG
, "Updating a circuit with seemingly incompatible "
3140 "isolation flags.");
3142 circ
->isolation_flags_mixed
|= mixed
;
3148 * Clear the isolation settings on <b>circ</b>.
3150 * This only works on an open circuit that has never had a stream attached to
3151 * it, and whose isolation settings are hypothetical. (We set hypothetical
3152 * isolation settings on circuits as we're launching them, so that we
3153 * know whether they can handle more streams or whether we need to launch
3154 * even more circuits. Once the circuit is open, if it turns out that
3155 * we no longer have any streams to attach to it, we clear the isolation flags
3156 * and data so that other streams can have a chance.)
3159 circuit_clear_isolation(origin_circuit_t
*circ
)
3161 if (circ
->isolation_any_streams_attached
) {
3162 log_warn(LD_BUG
, "Tried to clear the isolation status of a dirty circuit");
3165 if (TO_CIRCUIT(circ
)->state
!= CIRCUIT_STATE_OPEN
) {
3166 log_warn(LD_BUG
, "Tried to clear the isolation status of a non-open "
3171 circ
->isolation_values_set
= 0;
3172 circ
->isolation_flags_mixed
= 0;
3173 circ
->associated_isolated_stream_global_id
= 0;
3174 circ
->client_proto_type
= 0;
3175 circ
->client_proto_socksver
= 0;
3176 circ
->dest_port
= 0;
3177 tor_addr_make_unspec(&circ
->client_addr
);
3178 tor_free(circ
->dest_address
);
3179 circ
->session_group
= -1;
3180 circ
->nym_epoch
= 0;
3181 if (circ
->socks_username
) {
3182 memwipe(circ
->socks_username
, 0x11, circ
->socks_username_len
);
3183 tor_free(circ
->socks_username
);
3185 if (circ
->socks_password
) {
3186 memwipe(circ
->socks_password
, 0x05, circ
->socks_password_len
);
3187 tor_free(circ
->socks_password
);
3189 circ
->socks_username_len
= circ
->socks_password_len
= 0;