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-2011, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
8 * \file connection_edge.c
9 * \brief Handle edge streams.
14 #include "circuitlist.h"
15 #include "circuituse.h"
17 #include "connection.h"
18 #include "connection_edge.h"
19 #include "connection_or.h"
24 #include "hibernate.h"
30 #include "rendclient.h"
31 #include "rendcommon.h"
32 #include "rendservice.h"
35 #include "routerlist.h"
37 #ifdef HAVE_LINUX_TYPES_H
38 #include <linux/types.h>
40 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
41 #include <linux/netfilter_ipv4.h>
42 #define TRANS_NETFILTER
45 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
47 #include <net/pfvar.h>
51 #define SOCKS4_GRANTED 90
52 #define SOCKS4_REJECT 91
54 static int connection_ap_handshake_process_socks(entry_connection_t
*conn
);
55 static int connection_ap_process_natd(entry_connection_t
*conn
);
56 static int connection_exit_connect_dir(edge_connection_t
*exitconn
);
57 static int address_is_in_virtual_range(const char *addr
);
58 static int consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
);
59 static void clear_trackexithost_mappings(const char *exitname
);
60 static int connection_ap_supports_optimistic_data(const entry_connection_t
*);
62 /** An AP stream has failed/finished. If it hasn't already sent back
63 * a socks reply, send one now (based on endreason). Also set
64 * has_sent_end to 1, and mark the conn.
67 _connection_mark_unattached_ap(entry_connection_t
*conn
, int endreason
,
68 int line
, const char *file
)
70 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
71 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
72 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
73 ENTRY_TO_EDGE_CONN(conn
)->edge_has_sent_end
= 1; /* no circ yet */
75 /* If this is a rendezvous stream and it is failing without ever
76 * being attached to a circuit, assume that an attempt to connect to
77 * the destination hidden service has just ended.
79 * XXX023 This condition doesn't limit to only streams failing
80 * without ever being attached. That sloppiness should be harmless,
81 * but we should fix it someday anyway. */
82 if ((edge_conn
->on_circuit
!= NULL
|| edge_conn
->edge_has_sent_end
) &&
83 connection_edge_is_rendezvous_stream(edge_conn
)) {
84 rend_client_note_connection_attempt_ended(
85 edge_conn
->rend_data
->onion_address
);
88 if (base_conn
->marked_for_close
) {
89 /* This call will warn as appropriate. */
90 _connection_mark_for_close(base_conn
, line
, file
);
94 if (!conn
->socks_request
->has_finished
) {
95 if (endreason
& END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
)
97 "stream (marked at %s:%d) sending two socks replies?",
100 if (SOCKS_COMMAND_IS_CONNECT(conn
->socks_request
->command
))
101 connection_ap_handshake_socks_reply(conn
, NULL
, 0, endreason
);
102 else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
103 connection_ap_handshake_socks_resolved(conn
,
104 RESOLVED_TYPE_ERROR_TRANSIENT
,
106 else /* unknown or no handshake at all. send no response. */
107 conn
->socks_request
->has_finished
= 1;
110 _connection_mark_and_flush(base_conn
, line
, file
);
112 ENTRY_TO_EDGE_CONN(conn
)->end_reason
= endreason
;
115 /** There was an EOF. Send an end and mark the connection for close.
118 connection_edge_reached_eof(edge_connection_t
*conn
)
120 if (connection_get_inbuf_len(TO_CONN(conn
)) &&
121 connection_state_is_open(TO_CONN(conn
))) {
122 /* it still has stuff to process. don't let it die yet. */
125 log_info(LD_EDGE
,"conn (fd %d) reached eof. Closing.", conn
->_base
.s
);
126 if (!conn
->_base
.marked_for_close
) {
127 /* only mark it if not already marked. it's possible to
128 * get the 'end' right around when the client hangs up on us. */
129 connection_edge_end(conn
, END_STREAM_REASON_DONE
);
130 if (conn
->_base
.type
== CONN_TYPE_AP
) {
131 /* eof, so don't send a socks reply back */
132 if (EDGE_TO_ENTRY_CONN(conn
)->socks_request
)
133 EDGE_TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
135 connection_mark_for_close(TO_CONN(conn
));
140 /** Handle new bytes on conn->inbuf based on state:
141 * - If it's waiting for socks info, try to read another step of the
142 * socks handshake out of conn->inbuf.
143 * - If it's waiting for the original destination, fetch it.
144 * - If it's open, then package more relay cells from the stream.
145 * - Else, leave the bytes on inbuf alone for now.
147 * Mark and return -1 if there was an unexpected error with the conn,
151 connection_edge_process_inbuf(edge_connection_t
*conn
, int package_partial
)
155 switch (conn
->_base
.state
) {
156 case AP_CONN_STATE_SOCKS_WAIT
:
157 if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn
)) <0) {
162 case AP_CONN_STATE_NATD_WAIT
:
163 if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn
)) < 0) {
168 case AP_CONN_STATE_OPEN
:
169 case EXIT_CONN_STATE_OPEN
:
170 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
) < 0) {
171 /* (We already sent an end cell if possible) */
172 connection_mark_for_close(TO_CONN(conn
));
176 case AP_CONN_STATE_CONNECT_WAIT
:
177 if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn
))) {
179 "data from edge while in '%s' state. Sending it anyway. "
180 "package_partial=%d, buflen=%ld",
181 conn_state_to_string(conn
->_base
.type
, conn
->_base
.state
),
183 (long)connection_get_inbuf_len(TO_CONN(conn
)));
184 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
)<0) {
185 /* (We already sent an end cell if possible) */
186 connection_mark_for_close(TO_CONN(conn
));
191 /* Fall through if the connection is on a circuit without optimistic
193 case EXIT_CONN_STATE_CONNECTING
:
194 case AP_CONN_STATE_RENDDESC_WAIT
:
195 case AP_CONN_STATE_CIRCUIT_WAIT
:
196 case AP_CONN_STATE_RESOLVE_WAIT
:
197 case AP_CONN_STATE_CONTROLLER_WAIT
:
199 "data from edge while in '%s' state. Leaving it on buffer.",
200 conn_state_to_string(conn
->_base
.type
, conn
->_base
.state
));
203 log_warn(LD_BUG
,"Got unexpected state %d. Closing.",conn
->_base
.state
);
204 tor_fragile_assert();
205 connection_edge_end(conn
, END_STREAM_REASON_INTERNAL
);
206 connection_mark_for_close(TO_CONN(conn
));
210 /** This edge needs to be closed, because its circuit has closed.
211 * Mark it for close and return 0.
214 connection_edge_destroy(circid_t circ_id
, edge_connection_t
*conn
)
216 if (!conn
->_base
.marked_for_close
) {
218 "CircID %d: At an edge. Marking connection for close.", circ_id
);
219 if (conn
->_base
.type
== CONN_TYPE_AP
) {
220 entry_connection_t
*entry_conn
= EDGE_TO_ENTRY_CONN(conn
);
221 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_DESTROY
);
222 control_event_stream_bandwidth(conn
);
223 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
224 END_STREAM_REASON_DESTROY
);
225 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
227 /* closing the circuit, nothing to send an END to */
228 conn
->edge_has_sent_end
= 1;
229 conn
->end_reason
= END_STREAM_REASON_DESTROY
;
230 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
231 connection_mark_and_flush(TO_CONN(conn
));
234 conn
->cpath_layer
= NULL
;
235 conn
->on_circuit
= NULL
;
239 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
240 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
241 * is not a client connection, set the relay end cell's reason for closing
242 * as <b>reason</b> */
244 relay_send_end_cell_from_edge(streamid_t stream_id
, circuit_t
*circ
,
245 uint8_t reason
, crypt_path_t
*cpath_layer
)
249 if (CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
250 /* Never send the server an informative reason code; it doesn't need to
251 * know why the client stream is failing. */
252 reason
= END_STREAM_REASON_MISC
;
255 payload
[0] = (char) reason
;
257 return relay_send_command_from_edge(stream_id
, circ
, RELAY_COMMAND_END
,
258 payload
, 1, cpath_layer
);
261 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
262 * remember that we've done so. If this is not a client connection, set the
263 * relay end cell's reason for closing as <b>reason</b>.
265 * Return -1 if this function has already been called on this conn,
269 connection_edge_end(edge_connection_t
*conn
, uint8_t reason
)
271 char payload
[RELAY_PAYLOAD_SIZE
];
272 size_t payload_len
=1;
274 uint8_t control_reason
= reason
;
276 if (conn
->edge_has_sent_end
) {
277 log_warn(LD_BUG
,"(Harmless.) Calling connection_edge_end (reason %d) "
278 "on an already ended stream?", reason
);
279 tor_fragile_assert();
283 if (conn
->_base
.marked_for_close
) {
285 "called on conn that's already marked for close at %s:%d.",
286 conn
->_base
.marked_for_close_file
, conn
->_base
.marked_for_close
);
290 circ
= circuit_get_by_edge_conn(conn
);
291 if (circ
&& CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
292 /* If this is a client circuit, don't send the server an informative
293 * reason code; it doesn't need to know why the client stream is
295 reason
= END_STREAM_REASON_MISC
;
298 payload
[0] = (char)reason
;
299 if (reason
== END_STREAM_REASON_EXITPOLICY
&&
300 !connection_edge_is_rendezvous_stream(conn
)) {
302 if (tor_addr_family(&conn
->_base
.addr
) == AF_INET
) {
303 set_uint32(payload
+1, tor_addr_to_ipv4n(&conn
->_base
.addr
));
306 memcpy(payload
+1, tor_addr_to_in6_addr8(&conn
->_base
.addr
), 16);
309 set_uint32(payload
+1+addrlen
, htonl(dns_clip_ttl(conn
->address_ttl
)));
310 payload_len
+= 4+addrlen
;
313 if (circ
&& !circ
->marked_for_close
) {
314 log_debug(LD_EDGE
,"Sending end on conn (fd %d).",conn
->_base
.s
);
315 connection_edge_send_command(conn
, RELAY_COMMAND_END
,
316 payload
, payload_len
);
318 log_debug(LD_EDGE
,"No circ to send end on conn (fd %d).",
322 conn
->edge_has_sent_end
= 1;
323 conn
->end_reason
= control_reason
;
327 /** An error has just occurred on an operation on an edge connection
328 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
329 * appropriate relay end cell to the other end of the connection's circuit.
332 connection_edge_end_errno(edge_connection_t
*conn
)
336 reason
= errno_to_stream_end_reason(tor_socket_errno(conn
->_base
.s
));
337 return connection_edge_end(conn
, reason
);
340 /** We just wrote some data to <b>conn</b>; act appropriately.
342 * (That is, if it's open, consider sending a stream-level sendme cell if we
343 * have just flushed enough.)
346 connection_edge_flushed_some(edge_connection_t
*conn
)
348 switch (conn
->_base
.state
) {
349 case AP_CONN_STATE_OPEN
:
350 case EXIT_CONN_STATE_OPEN
:
351 connection_edge_consider_sending_sendme(conn
);
357 /** Connection <b>conn</b> has finished writing and has no bytes left on
360 * If it's in state 'open', stop writing, consider responding with a
361 * sendme, and return.
362 * Otherwise, stop writing and return.
364 * If <b>conn</b> is broken, mark it for close and return -1, else
368 connection_edge_finished_flushing(edge_connection_t
*conn
)
372 switch (conn
->_base
.state
) {
373 case AP_CONN_STATE_OPEN
:
374 case EXIT_CONN_STATE_OPEN
:
375 connection_edge_consider_sending_sendme(conn
);
377 case AP_CONN_STATE_SOCKS_WAIT
:
378 case AP_CONN_STATE_NATD_WAIT
:
379 case AP_CONN_STATE_RENDDESC_WAIT
:
380 case AP_CONN_STATE_CIRCUIT_WAIT
:
381 case AP_CONN_STATE_CONNECT_WAIT
:
382 case AP_CONN_STATE_CONTROLLER_WAIT
:
383 case AP_CONN_STATE_RESOLVE_WAIT
:
386 log_warn(LD_BUG
, "Called in unexpected state %d.",conn
->_base
.state
);
387 tor_fragile_assert();
393 /** Connected handler for exit connections: start writing pending
394 * data, deliver 'CONNECTED' relay cells as appropriate, and check
395 * any pending data that may have been received. */
397 connection_edge_finished_connecting(edge_connection_t
*edge_conn
)
401 tor_assert(edge_conn
);
402 tor_assert(edge_conn
->_base
.type
== CONN_TYPE_EXIT
);
403 conn
= TO_CONN(edge_conn
);
404 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
406 log_info(LD_EXIT
,"Exit connection to %s:%u (%s) established.",
407 escaped_safe_str(conn
->address
), conn
->port
,
408 safe_str(fmt_addr(&conn
->addr
)));
410 rep_hist_note_exit_stream_opened(conn
->port
);
412 conn
->state
= EXIT_CONN_STATE_OPEN
;
413 IF_HAS_NO_BUFFEREVENT(conn
)
414 connection_watch_events(conn
, READ_EVENT
); /* stop writing, keep reading */
415 if (connection_get_outbuf_len(conn
)) /* in case there are any queued relay
417 connection_start_writing(conn
);
418 /* deliver a 'connected' relay cell back through the circuit. */
419 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
420 if (connection_edge_send_command(edge_conn
,
421 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0)
422 return 0; /* circuit is closed, don't continue */
424 char connected_payload
[20];
425 int connected_payload_len
;
426 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
427 set_uint32(connected_payload
, tor_addr_to_ipv4n(&conn
->addr
));
428 set_uint32(connected_payload
+4,
429 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
430 connected_payload_len
= 8;
432 memcpy(connected_payload
, tor_addr_to_in6_addr8(&conn
->addr
), 16);
433 set_uint32(connected_payload
+16,
434 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
435 connected_payload_len
= 20;
437 if (connection_edge_send_command(edge_conn
,
438 RELAY_COMMAND_CONNECTED
,
439 connected_payload
, connected_payload_len
) < 0)
440 return 0; /* circuit is closed, don't continue */
442 tor_assert(edge_conn
->package_window
> 0);
443 /* in case the server has written anything */
444 return connection_edge_process_inbuf(edge_conn
, 1);
447 /** Common code to connection_(ap|exit)_about_to_close. */
449 connection_edge_about_to_close(edge_connection_t
*edge_conn
)
451 if (!edge_conn
->edge_has_sent_end
) {
452 connection_t
*conn
= TO_CONN(edge_conn
);
453 log_warn(LD_BUG
, "(Harmless.) Edge connection (marked at %s:%d) "
454 "hasn't sent end yet?",
455 conn
->marked_for_close_file
, conn
->marked_for_close
);
456 tor_fragile_assert();
460 /* Called when we're about to finally unlink and free an AP (client)
461 * connection: perform necessary accounting and cleanup */
463 connection_ap_about_to_close(entry_connection_t
*entry_conn
)
466 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
467 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
469 if (entry_conn
->socks_request
->has_finished
== 0) {
470 /* since conn gets removed right after this function finishes,
471 * there's no point trying to send back a reply at this point. */
472 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without sending"
473 " back a socks reply.",
474 conn
->marked_for_close_file
, conn
->marked_for_close
);
476 if (!edge_conn
->end_reason
) {
477 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
479 conn
->marked_for_close_file
, conn
->marked_for_close
);
481 if (entry_conn
->dns_server_request
) {
482 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
483 " replied to DNS request.",
484 conn
->marked_for_close_file
, conn
->marked_for_close
);
485 dnsserv_reject_request(entry_conn
);
487 control_event_stream_bandwidth(edge_conn
);
488 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
489 edge_conn
->end_reason
);
490 circ
= circuit_get_by_edge_conn(edge_conn
);
492 circuit_detach_stream(circ
, edge_conn
);
495 /* Called when we're about to finally unlink and free an exit
496 * connection: perform necessary accounting and cleanup */
498 connection_exit_about_to_close(edge_connection_t
*edge_conn
)
501 connection_t
*conn
= TO_CONN(edge_conn
);
503 connection_edge_about_to_close(edge_conn
);
505 circ
= circuit_get_by_edge_conn(edge_conn
);
507 circuit_detach_stream(circ
, edge_conn
);
508 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
509 connection_dns_remove(edge_conn
);
513 /** Define a schedule for how long to wait between retrying
514 * application connections. Rather than waiting a fixed amount of
515 * time between each retry, we wait 10 seconds each for the first
516 * two tries, and 15 seconds for each retry after
517 * that. Hopefully this will improve the expected user experience. */
519 compute_retry_timeout(entry_connection_t
*conn
)
521 int timeout
= get_options()->CircuitStreamTimeout
;
522 if (timeout
) /* if our config options override the default, use them */
524 if (conn
->num_socks_retries
< 2) /* try 0 and try 1 */
529 /** Find all general-purpose AP streams waiting for a response that sent their
530 * begin/resolve cell too long ago. Detach from their current circuit, and
531 * mark their current circuit as unsuitable for new streams. Then call
532 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
533 * available) or launch a new one.
535 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
539 connection_ap_expire_beginning(void)
541 edge_connection_t
*conn
;
542 entry_connection_t
*entry_conn
;
544 time_t now
= time(NULL
);
545 const or_options_t
*options
= get_options();
548 int seconds_idle
, seconds_since_born
;
549 smartlist_t
*conns
= get_connection_array();
551 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
552 if (base_conn
->type
!= CONN_TYPE_AP
|| base_conn
->marked_for_close
)
554 entry_conn
= TO_ENTRY_CONN(base_conn
);
555 conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
556 /* if it's an internal linked connection, don't yell its status. */
557 severity
= (tor_addr_is_null(&base_conn
->addr
) && !base_conn
->port
)
558 ? LOG_INFO
: LOG_NOTICE
;
559 seconds_idle
= (int)( now
- base_conn
->timestamp_lastread
);
560 seconds_since_born
= (int)( now
- base_conn
->timestamp_created
);
562 if (base_conn
->state
== AP_CONN_STATE_OPEN
)
565 /* We already consider SocksTimeout in
566 * connection_ap_handshake_attach_circuit(), but we need to consider
567 * it here too because controllers that put streams in controller_wait
568 * state never ask Tor to attach the circuit. */
569 if (AP_CONN_STATE_IS_UNATTACHED(base_conn
->state
)) {
570 if (seconds_since_born
>= options
->SocksTimeout
) {
571 log_fn(severity
, LD_APP
,
572 "Tried for %d seconds to get a connection to %s:%d. "
575 safe_str_client(entry_conn
->socks_request
->address
),
576 entry_conn
->socks_request
->port
,
577 conn_state_to_string(CONN_TYPE_AP
, base_conn
->state
));
578 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
583 /* We're in state connect_wait or resolve_wait now -- waiting for a
584 * reply to our relay cell. See if we want to retry/give up. */
586 cutoff
= compute_retry_timeout(entry_conn
);
587 if (seconds_idle
< cutoff
)
589 circ
= circuit_get_by_edge_conn(conn
);
590 if (!circ
) { /* it's vanished? */
591 log_info(LD_APP
,"Conn is waiting (address %s), but lost its circ.",
592 safe_str_client(entry_conn
->socks_request
->address
));
593 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
596 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
597 if (seconds_idle
>= options
->SocksTimeout
) {
598 log_fn(severity
, LD_REND
,
599 "Rend stream is %d seconds late. Giving up on address"
602 safe_str_client(entry_conn
->socks_request
->address
));
603 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
604 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
608 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
609 log_fn(cutoff
< 15 ? LOG_INFO
: severity
, LD_APP
,
610 "We tried for %d seconds to connect to '%s' using exit %s."
611 " Retrying on a new circuit.",
613 safe_str_client(entry_conn
->socks_request
->address
),
615 extend_info_describe(conn
->cpath_layer
->extend_info
):
617 /* send an end down the circuit */
618 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
619 /* un-mark it as ending, since we're going to reuse it */
620 conn
->edge_has_sent_end
= 0;
621 conn
->end_reason
= 0;
622 /* kludge to make us not try this circuit again, yet to allow
623 * current streams on it to survive if they can: make it
624 * unattractive to use for new streams */
625 /* XXXX023 this is a kludgy way to do this. */
626 tor_assert(circ
->timestamp_dirty
);
627 circ
->timestamp_dirty
-= options
->MaxCircuitDirtiness
;
628 /* give our stream another 'cutoff' seconds to try */
629 conn
->_base
.timestamp_lastread
+= cutoff
;
630 if (entry_conn
->num_socks_retries
< 250) /* avoid overflow */
631 entry_conn
->num_socks_retries
++;
632 /* move it back into 'pending' state, and try to attach. */
633 if (connection_ap_detach_retriable(entry_conn
, TO_ORIGIN_CIRCUIT(circ
),
634 END_STREAM_REASON_TIMEOUT
)<0) {
635 if (!base_conn
->marked_for_close
)
636 connection_mark_unattached_ap(entry_conn
,
637 END_STREAM_REASON_CANT_ATTACH
);
639 } SMARTLIST_FOREACH_END(base_conn
);
642 /** Tell any AP streams that are waiting for a new circuit to try again,
643 * either attaching to an available circ or launching a new one.
646 connection_ap_attach_pending(void)
648 entry_connection_t
*entry_conn
;
649 smartlist_t
*conns
= get_connection_array();
650 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
652 if (conn
->marked_for_close
||
653 conn
->type
!= CONN_TYPE_AP
||
654 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
656 entry_conn
= TO_ENTRY_CONN(conn
);
657 if (connection_ap_handshake_attach_circuit(entry_conn
) < 0) {
658 if (!conn
->marked_for_close
)
659 connection_mark_unattached_ap(entry_conn
,
660 END_STREAM_REASON_CANT_ATTACH
);
665 /** Tell any AP streams that are waiting for a one-hop tunnel to
666 * <b>failed_digest</b> that they are going to fail. */
667 /* XXX023 We should get rid of this function, and instead attach
668 * one-hop streams to circ->p_streams so they get marked in
669 * circuit_mark_for_close like normal p_streams. */
671 connection_ap_fail_onehop(const char *failed_digest
,
672 cpath_build_state_t
*build_state
)
674 entry_connection_t
*entry_conn
;
675 char digest
[DIGEST_LEN
];
676 smartlist_t
*conns
= get_connection_array();
677 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
678 if (conn
->marked_for_close
||
679 conn
->type
!= CONN_TYPE_AP
||
680 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
682 entry_conn
= TO_ENTRY_CONN(conn
);
683 if (!entry_conn
->want_onehop
)
685 if (hexdigest_to_digest(entry_conn
->chosen_exit_name
, digest
) < 0 ||
686 tor_memneq(digest
, failed_digest
, DIGEST_LEN
))
688 if (tor_digest_is_zero(digest
)) {
689 /* we don't know the digest; have to compare addr:port */
691 if (!build_state
|| !build_state
->chosen_exit
||
692 !entry_conn
->socks_request
|| !entry_conn
->socks_request
->address
)
694 if (tor_addr_parse(&addr
, entry_conn
->socks_request
->address
)<0 ||
695 !tor_addr_eq(&build_state
->chosen_exit
->addr
, &addr
) ||
696 build_state
->chosen_exit
->port
!= entry_conn
->socks_request
->port
)
699 log_info(LD_APP
, "Closing one-hop stream to '%s/%s' because the OR conn "
700 "just failed.", entry_conn
->chosen_exit_name
,
701 entry_conn
->socks_request
->address
);
702 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
703 } SMARTLIST_FOREACH_END(conn
);
706 /** A circuit failed to finish on its last hop <b>info</b>. If there
707 * are any streams waiting with this exit node in mind, but they
708 * don't absolutely require it, make them give up on it.
711 circuit_discard_optional_exit_enclaves(extend_info_t
*info
)
713 entry_connection_t
*entry_conn
;
714 const node_t
*r1
, *r2
;
716 smartlist_t
*conns
= get_connection_array();
717 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
718 if (conn
->marked_for_close
||
719 conn
->type
!= CONN_TYPE_AP
||
720 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
722 entry_conn
= TO_ENTRY_CONN(conn
);
723 if (!entry_conn
->chosen_exit_optional
&&
724 !entry_conn
->chosen_exit_retries
)
726 r1
= node_get_by_nickname(entry_conn
->chosen_exit_name
, 0);
727 r2
= node_get_by_id(info
->identity_digest
);
728 if (!r1
|| !r2
|| r1
!= r2
)
730 tor_assert(entry_conn
->socks_request
);
731 if (entry_conn
->chosen_exit_optional
) {
732 log_info(LD_APP
, "Giving up on enclave exit '%s' for destination %s.",
733 safe_str_client(entry_conn
->chosen_exit_name
),
734 escaped_safe_str_client(entry_conn
->socks_request
->address
));
735 entry_conn
->chosen_exit_optional
= 0;
736 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
737 /* if this port is dangerous, warn or reject it now that we don't
738 * think it'll be using an enclave. */
739 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
741 if (entry_conn
->chosen_exit_retries
) {
742 if (--entry_conn
->chosen_exit_retries
== 0) { /* give up! */
743 clear_trackexithost_mappings(entry_conn
->chosen_exit_name
);
744 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
745 /* if this port is dangerous, warn or reject it now that we don't
746 * think it'll be using an enclave. */
747 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
750 } SMARTLIST_FOREACH_END(conn
);
753 /** The AP connection <b>conn</b> has just failed while attaching or
754 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
755 * might work. Detach the circuit, and either reattach it, launch a
756 * new circuit, tell the controller, or give up as a appropriate.
758 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
761 connection_ap_detach_retriable(entry_connection_t
*conn
,
762 origin_circuit_t
*circ
,
765 control_event_stream_status(conn
, STREAM_EVENT_FAILED_RETRIABLE
, reason
);
766 ENTRY_TO_CONN(conn
)->timestamp_lastread
= time(NULL
);
768 if (conn
->pending_optimistic_data
) {
769 generic_buffer_set_to_copy(&conn
->sending_optimistic_data
,
770 conn
->pending_optimistic_data
);
773 if (!get_options()->LeaveStreamsUnattached
|| conn
->use_begindir
) {
774 /* If we're attaching streams ourself, or if this connection is
775 * a tunneled directory connection, then just attach it. */
776 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
777 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
778 return connection_ap_handshake_attach_circuit(conn
);
780 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
781 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
786 /** A client-side struct to remember requests to rewrite addresses
787 * to new addresses. These structs are stored in the hash table
788 * "addressmap" below.
790 * There are 5 ways to set an address mapping:
791 * - A MapAddress command from the controller [permanent]
792 * - An AddressMap directive in the torrc [permanent]
793 * - When a TrackHostExits torrc directive is triggered [temporary]
794 * - When a DNS resolve succeeds [temporary]
795 * - When a DNS resolve fails [temporary]
797 * When an addressmap request is made but one is already registered,
798 * the new one is replaced only if the currently registered one has
799 * no "new_address" (that is, it's in the process of DNS resolve),
800 * or if the new one is permanent (expires==0 or 1).
802 * (We overload the 'expires' field, using "0" for mappings set via
803 * the configuration file, "1" for mappings set from the control
804 * interface, and other values for DNS and TrackHostExit mappings that can
807 * A mapping may be 'wildcarded'. If "src_wildcard" is true, then
808 * any address that ends with a . followed by the key for this entry will
809 * get remapped by it. If "dst_wildcard" is also true, then only the
810 * matching suffix of such addresses will get replaced by new_address.
815 addressmap_entry_source_t source
:3;
816 unsigned src_wildcard
:1;
817 unsigned dst_wildcard
:1;
818 short num_resolve_failures
;
819 } addressmap_entry_t
;
821 /** Entry for mapping addresses to which virtual address we mapped them to. */
824 char *hostname_address
;
825 } virtaddress_entry_t
;
827 /** A hash table to store client-side address rewrite instructions. */
828 static strmap_t
*addressmap
=NULL
;
830 * Table mapping addresses to which virtual address, if any, we
833 * We maintain the following invariant: if [A,B] is in
834 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
835 * must be in addressmap. We do not require that the converse hold:
836 * if it fails, then we could end up mapping two virtual addresses to
837 * the same address, which is no disaster.
839 static strmap_t
*virtaddress_reversemap
=NULL
;
841 /** Initialize addressmap. */
843 addressmap_init(void)
845 addressmap
= strmap_new();
846 virtaddress_reversemap
= strmap_new();
849 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
851 addressmap_ent_free(void *_ent
)
853 addressmap_entry_t
*ent
;
858 tor_free(ent
->new_address
);
862 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
864 addressmap_virtaddress_ent_free(void *_ent
)
866 virtaddress_entry_t
*ent
;
871 tor_free(ent
->ipv4_address
);
872 tor_free(ent
->hostname_address
);
876 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
878 addressmap_virtaddress_remove(const char *address
, addressmap_entry_t
*ent
)
880 if (ent
&& ent
->new_address
&&
881 address_is_in_virtual_range(ent
->new_address
)) {
882 virtaddress_entry_t
*ve
=
883 strmap_get(virtaddress_reversemap
, ent
->new_address
);
884 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
886 if (!strcmp(address
, ve
->ipv4_address
))
887 tor_free(ve
->ipv4_address
);
888 if (!strcmp(address
, ve
->hostname_address
))
889 tor_free(ve
->hostname_address
);
890 if (!ve
->ipv4_address
&& !ve
->hostname_address
) {
892 strmap_remove(virtaddress_reversemap
, ent
->new_address
);
898 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
899 * client address maps. */
901 addressmap_ent_remove(const char *address
, addressmap_entry_t
*ent
)
903 addressmap_virtaddress_remove(address
, ent
);
904 addressmap_ent_free(ent
);
907 /** Unregister all TrackHostExits mappings from any address to
908 * *.exitname.exit. */
910 clear_trackexithost_mappings(const char *exitname
)
914 if (!addressmap
|| !exitname
)
916 suffix_len
= strlen(exitname
) + 16;
917 suffix
= tor_malloc(suffix_len
);
918 tor_snprintf(suffix
, suffix_len
, ".%s.exit", exitname
);
919 tor_strlower(suffix
);
921 STRMAP_FOREACH_MODIFY(addressmap
, address
, addressmap_entry_t
*, ent
) {
922 if (ent
->source
== ADDRMAPSRC_TRACKEXIT
&&
923 !strcmpend(ent
->new_address
, suffix
)) {
924 addressmap_ent_remove(address
, ent
);
925 MAP_DEL_CURRENT(address
);
927 } STRMAP_FOREACH_END
;
932 /** Remove all TRACKEXIT mappings from the addressmap for which the target
933 * host is unknown or no longer allowed, or for which the source address
934 * is no longer in trackexithosts. */
936 addressmap_clear_excluded_trackexithosts(const or_options_t
*options
)
938 const routerset_t
*allow_nodes
= options
->ExitNodes
;
939 const routerset_t
*exclude_nodes
= options
->_ExcludeExitNodesUnion
;
943 if (routerset_is_empty(allow_nodes
))
945 if (allow_nodes
== NULL
&& routerset_is_empty(exclude_nodes
))
948 STRMAP_FOREACH_MODIFY(addressmap
, address
, addressmap_entry_t
*, ent
) {
950 const char *target
= ent
->new_address
, *dot
;
955 /* DNS resolving in progress */
957 } else if (strcmpend(target
, ".exit")) {
958 /* Not a .exit mapping */
960 } else if (ent
->source
!= ADDRMAPSRC_TRACKEXIT
) {
961 /* Not a trackexit mapping. */
964 len
= strlen(target
);
966 continue; /* malformed. */
967 dot
= target
+ len
- 6; /* dot now points to just before .exit */
968 while (dot
> target
&& *dot
!= '.')
970 if (*dot
== '.') dot
++;
971 nodename
= tor_strndup(dot
, len
-5-(dot
-target
));;
972 node
= node_get_by_nickname(nodename
, 0);
975 (allow_nodes
&& !routerset_contains_node(allow_nodes
, node
)) ||
976 routerset_contains_node(exclude_nodes
, node
) ||
977 !hostname_in_track_host_exits(options
, address
)) {
978 /* We don't know this one, or we want to be rid of it. */
979 addressmap_ent_remove(address
, ent
);
980 MAP_DEL_CURRENT(address
);
982 } STRMAP_FOREACH_END
;
985 /** Remove all AUTOMAP mappings from the addressmap for which the
986 * source address no longer matches AutomapHostsSuffixes, which is
987 * no longer allowed by AutomapHostsOnResolve, or for which the
988 * target address is no longer in the virtual network. */
990 addressmap_clear_invalid_automaps(const or_options_t
*options
)
992 int clear_all
= !options
->AutomapHostsOnResolve
;
993 const smartlist_t
*suffixes
= options
->AutomapHostsSuffixes
;
999 clear_all
= 1; /* This should be impossible, but let's be sure. */
1001 STRMAP_FOREACH_MODIFY(addressmap
, src_address
, addressmap_entry_t
*, ent
) {
1002 int remove
= clear_all
;
1003 if (ent
->source
!= ADDRMAPSRC_AUTOMAP
)
1004 continue; /* not an automap mapping. */
1007 int suffix_found
= 0;
1008 SMARTLIST_FOREACH(suffixes
, const char *, suffix
, {
1009 if (!strcasecmpend(src_address
, suffix
)) {
1018 if (!remove
&& ! address_is_in_virtual_range(ent
->new_address
))
1022 addressmap_ent_remove(src_address
, ent
);
1023 MAP_DEL_CURRENT(src_address
);
1025 } STRMAP_FOREACH_END
;
1028 /** Remove all entries from the addressmap that were set via the
1029 * configuration file or the command line. */
1031 addressmap_clear_configured(void)
1033 addressmap_get_mappings(NULL
, 0, 0, 0);
1036 /** Remove all entries from the addressmap that are set to expire, ever. */
1038 addressmap_clear_transient(void)
1040 addressmap_get_mappings(NULL
, 2, TIME_MAX
, 0);
1043 /** Clean out entries from the addressmap cache that were
1044 * added long enough ago that they are no longer valid.
1047 addressmap_clean(time_t now
)
1049 addressmap_get_mappings(NULL
, 2, now
, 0);
1052 /** Free all the elements in the addressmap, and free the addressmap
1055 addressmap_free_all(void)
1057 strmap_free(addressmap
, addressmap_ent_free
);
1060 strmap_free(virtaddress_reversemap
, addressmap_virtaddress_ent_free
);
1061 virtaddress_reversemap
= NULL
;
1064 /** Try to find a match for AddressMap expressions that use
1065 * wildcard notation such as '*.c.d *.e.f' (so 'a.c.d' will map to 'a.e.f') or
1066 * '*.c.d a.b.c' (so 'a.c.d' will map to a.b.c).
1067 * Return the matching entry in AddressMap or NULL if no match is found.
1068 * For expressions such as '*.c.d *.e.f', truncate <b>address</b> 'a.c.d'
1069 * to 'a' before we return the matching AddressMap entry.
1071 * This function does not handle the case where a pattern of the form "*.c.d"
1072 * matches the address c.d -- that's done by the main addressmap_rewrite
1075 static addressmap_entry_t
*
1076 addressmap_match_superdomains(char *address
)
1078 addressmap_entry_t
*val
;
1082 while ((cp
= strchr(cp
, '.'))) {
1083 /* cp now points to a suffix of address that begins with a . */
1084 val
= strmap_get_lc(addressmap
, cp
+1);
1085 if (val
&& val
->src_wildcard
) {
1086 if (val
->dst_wildcard
)
1095 /** Look at address, and rewrite it until it doesn't want any
1096 * more rewrites; but don't get into an infinite loop.
1097 * Don't write more than maxlen chars into address. Return true if the
1098 * address changed; false otherwise. Set *<b>expires_out</b> to the
1099 * expiry time of the result, or to <b>time_max</b> if the result does
1103 addressmap_rewrite(char *address
, size_t maxlen
, time_t *expires_out
)
1105 addressmap_entry_t
*ent
;
1107 time_t expires
= TIME_MAX
;
1109 for (rewrites
= 0; rewrites
< 16; rewrites
++) {
1110 int exact_match
= 0;
1111 char *addr_orig
= tor_strdup(escaped_safe_str_client(address
));
1113 ent
= strmap_get(addressmap
, address
);
1115 if (!ent
|| !ent
->new_address
) {
1116 ent
= addressmap_match_superdomains(address
);
1118 if (ent
->src_wildcard
&& !ent
->dst_wildcard
&&
1119 !strcasecmp(address
, ent
->new_address
)) {
1120 /* This is a rule like *.example.com example.com, and we just got
1122 tor_free(addr_orig
);
1124 *expires_out
= expires
;
1125 return rewrites
> 0;
1131 if (!ent
|| !ent
->new_address
) {
1132 tor_free(addr_orig
);
1134 *expires_out
= expires
;
1135 return (rewrites
> 0); /* done, no rewrite needed */
1138 if (ent
->dst_wildcard
&& !exact_match
) {
1139 strlcat(address
, ".", maxlen
);
1140 strlcat(address
, ent
->new_address
, maxlen
);
1142 strlcpy(address
, ent
->new_address
, maxlen
);
1145 log_info(LD_APP
, "Addressmap: rewriting %s to %s",
1146 addr_orig
, escaped_safe_str_client(address
));
1147 if (ent
->expires
> 1 && ent
->expires
< expires
)
1148 expires
= ent
->expires
;
1149 tor_free(addr_orig
);
1152 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
1153 escaped_safe_str_client(address
));
1154 /* it's fine to rewrite a rewrite, but don't loop forever */
1156 *expires_out
= TIME_MAX
;
1160 /** If we have a cached reverse DNS entry for the address stored in the
1161 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
1162 * rewrite to the cached value and return 1. Otherwise return 0. Set
1163 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
1164 * if the result does not expire. */
1166 addressmap_rewrite_reverse(char *address
, size_t maxlen
, time_t *expires_out
)
1169 addressmap_entry_t
*ent
;
1171 tor_asprintf(&s
, "REVERSE[%s]", address
);
1172 ent
= strmap_get(addressmap
, s
);
1174 cp
= tor_strdup(escaped_safe_str_client(ent
->new_address
));
1175 log_info(LD_APP
, "Rewrote reverse lookup %s -> %s",
1176 escaped_safe_str_client(s
), cp
);
1178 strlcpy(address
, ent
->new_address
, maxlen
);
1183 *expires_out
= (ent
&& ent
->expires
> 1) ? ent
->expires
: TIME_MAX
;
1189 /** Return 1 if <b>address</b> is already registered, else return 0. If address
1190 * is already registered, and <b>update_expires</b> is non-zero, then update
1191 * the expiry time on the mapping with update_expires if it is a
1192 * mapping created by TrackHostExits. */
1194 addressmap_have_mapping(const char *address
, int update_expiry
)
1196 addressmap_entry_t
*ent
;
1197 if (!(ent
=strmap_get_lc(addressmap
, address
)))
1199 if (update_expiry
&& ent
->source
==ADDRMAPSRC_TRACKEXIT
)
1200 ent
->expires
=time(NULL
) + update_expiry
;
1204 /** Register a request to map <b>address</b> to <b>new_address</b>,
1205 * which will expire on <b>expires</b> (or 0 if never expires from
1206 * config file, 1 if never expires from controller, 2 if never expires
1207 * (virtual address mapping) from the controller.)
1209 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
1210 * free as appropriate. We will leave address alone.
1212 * If <b>wildcard_addr</b> is true, then the mapping will match any address
1213 * equal to <b>address</b>, or any address ending with a period followed by
1214 * <b>address</b>. If <b>wildcard_addr</b> and <b>wildcard_new_addr</b> are
1215 * both true, the mapping will rewrite addresses that end with
1216 * ".<b>address</b>" into ones that end with ".<b>new_address</b>."
1218 * If <b>new_address</b> is NULL, or <b>new_address</b> is equal to
1219 * <b>address</b> and <b>wildcard_addr</b> is equal to
1220 * <b>wildcard_new_addr</b>, remove any mappings that exist from
1224 * It is an error to set <b>wildcard_new_addr</b> if <b>wildcard_addr</b> is
1227 addressmap_register(const char *address
, char *new_address
, time_t expires
,
1228 addressmap_entry_source_t source
,
1229 const int wildcard_addr
,
1230 const int wildcard_new_addr
)
1232 addressmap_entry_t
*ent
;
1234 if (wildcard_new_addr
)
1235 tor_assert(wildcard_addr
);
1237 ent
= strmap_get(addressmap
, address
);
1238 if (!new_address
|| (!strcasecmp(address
,new_address
) &&
1239 wildcard_addr
== wildcard_new_addr
)) {
1240 /* Remove the mapping, if any. */
1241 tor_free(new_address
);
1243 addressmap_ent_remove(address
,ent
);
1244 strmap_remove(addressmap
, address
);
1248 if (!ent
) { /* make a new one and register it */
1249 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
1250 strmap_set(addressmap
, address
, ent
);
1251 } else if (ent
->new_address
) { /* we need to clean up the old mapping. */
1253 log_info(LD_APP
,"Temporary addressmap ('%s' to '%s') not performed, "
1254 "since it's already mapped to '%s'",
1255 safe_str_client(address
),
1256 safe_str_client(new_address
),
1257 safe_str_client(ent
->new_address
));
1258 tor_free(new_address
);
1261 if (address_is_in_virtual_range(ent
->new_address
) &&
1263 /* XXX This isn't the perfect test; we want to avoid removing
1264 * mappings set from the control interface _as virtual mapping */
1265 addressmap_virtaddress_remove(address
, ent
);
1267 tor_free(ent
->new_address
);
1268 } /* else { we have an in-progress resolve with no mapping. } */
1270 ent
->new_address
= new_address
;
1271 ent
->expires
= expires
==2 ? 1 : expires
;
1272 ent
->num_resolve_failures
= 0;
1273 ent
->source
= source
;
1274 ent
->src_wildcard
= wildcard_addr
? 1 : 0;
1275 ent
->dst_wildcard
= wildcard_new_addr
? 1 : 0;
1277 log_info(LD_CONFIG
, "Addressmap: (re)mapped '%s' to '%s'",
1278 safe_str_client(address
),
1279 safe_str_client(ent
->new_address
));
1280 control_event_address_mapped(address
, ent
->new_address
, expires
, NULL
);
1283 /** An attempt to resolve <b>address</b> failed at some OR.
1284 * Increment the number of resolve failures we have on record
1285 * for it, and then return that number.
1288 client_dns_incr_failures(const char *address
)
1290 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
1292 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
1293 ent
->expires
= time(NULL
) + MAX_DNS_ENTRY_AGE
;
1294 strmap_set(addressmap
,address
,ent
);
1296 if (ent
->num_resolve_failures
< SHORT_MAX
)
1297 ++ent
->num_resolve_failures
; /* don't overflow */
1298 log_info(LD_APP
, "Address %s now has %d resolve failures.",
1299 safe_str_client(address
),
1300 ent
->num_resolve_failures
);
1301 return ent
->num_resolve_failures
;
1304 /** If <b>address</b> is in the client DNS addressmap, reset
1305 * the number of resolve failures we have on record for it.
1306 * This is used when we fail a stream because it won't resolve:
1307 * otherwise future attempts on that address will only try once.
1310 client_dns_clear_failures(const char *address
)
1312 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
1314 ent
->num_resolve_failures
= 0;
1317 /** Record the fact that <b>address</b> resolved to <b>name</b>.
1318 * We can now use this in subsequent streams via addressmap_rewrite()
1319 * so we can more correctly choose an exit that will allow <b>address</b>.
1321 * If <b>exitname</b> is defined, then append the addresses with
1322 * ".exitname.exit" before registering the mapping.
1324 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1325 * <b>ttl</b>seconds; otherwise, we use the default.
1328 client_dns_set_addressmap_impl(const char *address
, const char *name
,
1329 const char *exitname
,
1332 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
1333 char extendedaddress
[MAX_SOCKS_ADDR_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
1334 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
1335 char extendedval
[INET_NTOA_BUF_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
1337 tor_assert(address
);
1341 ttl
= DEFAULT_DNS_TTL
;
1343 ttl
= dns_clip_ttl(ttl
);
1346 /* XXXX fails to ever get attempts to get an exit address of
1347 * google.com.digest[=~]nickname.exit; we need a syntax for this that
1348 * won't make strict RFC952-compliant applications (like us) barf. */
1349 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
1350 "%s.%s.exit", address
, exitname
);
1351 tor_snprintf(extendedval
, sizeof(extendedval
),
1352 "%s.%s.exit", name
, exitname
);
1354 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
1356 tor_snprintf(extendedval
, sizeof(extendedval
),
1359 addressmap_register(extendedaddress
, tor_strdup(extendedval
),
1360 time(NULL
) + ttl
, ADDRMAPSRC_DNS
, 0, 0);
1363 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1364 * We can now use this in subsequent streams via addressmap_rewrite()
1365 * so we can more correctly choose an exit that will allow <b>address</b>.
1367 * If <b>exitname</b> is defined, then append the addresses with
1368 * ".exitname.exit" before registering the mapping.
1370 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1371 * <b>ttl</b>seconds; otherwise, we use the default.
1374 client_dns_set_addressmap(const char *address
, uint32_t val
,
1375 const char *exitname
,
1379 char valbuf
[INET_NTOA_BUF_LEN
];
1381 tor_assert(address
);
1383 if (tor_inet_aton(address
, &in
))
1384 return; /* If address was an IP address already, don't add a mapping. */
1385 in
.s_addr
= htonl(val
);
1386 tor_inet_ntoa(&in
,valbuf
,sizeof(valbuf
));
1388 client_dns_set_addressmap_impl(address
, valbuf
, exitname
, ttl
);
1391 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1392 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1394 * If <b>exitname</b> is defined, then append the addresses with
1395 * ".exitname.exit" before registering the mapping.
1397 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1398 * <b>ttl</b>seconds; otherwise, we use the default.
1401 client_dns_set_reverse_addressmap(const char *address
, const char *v
,
1402 const char *exitname
,
1405 size_t len
= strlen(address
) + 16;
1406 char *s
= tor_malloc(len
);
1407 tor_snprintf(s
, len
, "REVERSE[%s]", address
);
1408 client_dns_set_addressmap_impl(s
, v
, exitname
, ttl
);
1412 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1413 * These addresses should map to localhost, so even if the
1414 * application accidentally tried to connect to them directly (not
1415 * via Tor), it wouldn't get too far astray.
1417 * These options are configured by parse_virtual_addr_network().
1419 /** Which network should we use for virtual IPv4 addresses? Only the first
1420 * bits of this value are fixed. */
1421 static uint32_t virtual_addr_network
= 0x7fc00000u
;
1422 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1423 static maskbits_t virtual_addr_netmask_bits
= 10;
1424 /** What's the next virtual address we will hand out? */
1425 static uint32_t next_virtual_addr
= 0x7fc00000u
;
1427 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1428 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1429 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1430 * string and return -1 on failure. If validate_only is false, sets the
1431 * actual virtual address range to the parsed value. */
1433 parse_virtual_addr_network(const char *val
, int validate_only
,
1437 uint16_t port_min
, port_max
;
1440 if (parse_addr_and_port_range(val
, &addr
, &bits
, &port_min
, &port_max
)) {
1441 if (msg
) *msg
= tor_strdup("Error parsing VirtualAddressNetwork");
1445 if (port_min
!= 1 || port_max
!= 65535) {
1446 if (msg
) *msg
= tor_strdup("Can't specify ports on VirtualAddressNetwork");
1451 if (msg
) *msg
= tor_strdup("VirtualAddressNetwork expects a /16 "
1452 "network or larger");
1459 virtual_addr_network
= (uint32_t)( addr
& (0xfffffffful
<< (32-bits
)) );
1460 virtual_addr_netmask_bits
= bits
;
1462 if (addr_mask_cmp_bits(next_virtual_addr
, addr
, bits
))
1463 next_virtual_addr
= addr
;
1469 * Return true iff <b>addr</b> is likely to have been returned by
1470 * client_dns_get_unused_address.
1473 address_is_in_virtual_range(const char *address
)
1476 tor_assert(address
);
1477 if (!strcasecmpend(address
, ".virtual")) {
1479 } else if (tor_inet_aton(address
, &in
)) {
1480 uint32_t addr
= ntohl(in
.s_addr
);
1481 if (!addr_mask_cmp_bits(addr
, virtual_addr_network
,
1482 virtual_addr_netmask_bits
))
1488 /** Increment the value of next_virtual_addr; reset it to the start of the
1489 * virtual address range if it wraps around.
1492 increment_virtual_addr(void)
1494 ++next_virtual_addr
;
1495 if (addr_mask_cmp_bits(next_virtual_addr
, virtual_addr_network
,
1496 virtual_addr_netmask_bits
))
1497 next_virtual_addr
= virtual_addr_network
;
1500 /** Return a newly allocated string holding an address of <b>type</b>
1501 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1502 * and that is very unlikely to be the address of any real host.
1504 * May return NULL if we have run out of virtual addresses.
1507 addressmap_get_virtual_address(int type
)
1510 tor_assert(addressmap
);
1512 if (type
== RESOLVED_TYPE_HOSTNAME
) {
1515 crypto_rand(rand
, sizeof(rand
));
1516 base32_encode(buf
,sizeof(buf
),rand
,sizeof(rand
));
1517 strlcat(buf
, ".virtual", sizeof(buf
));
1518 } while (strmap_get(addressmap
, buf
));
1519 return tor_strdup(buf
);
1520 } else if (type
== RESOLVED_TYPE_IPV4
) {
1521 // This is an imperfect estimate of how many addresses are available, but
1524 uint32_t available
= 1u << (32-virtual_addr_netmask_bits
);
1526 /* Don't hand out any .0 or .255 address. */
1527 while ((next_virtual_addr
& 0xff) == 0 ||
1528 (next_virtual_addr
& 0xff) == 0xff) {
1529 increment_virtual_addr();
1530 if (! --available
) {
1531 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
1535 in
.s_addr
= htonl(next_virtual_addr
);
1536 tor_inet_ntoa(&in
, buf
, sizeof(buf
));
1537 if (!strmap_get(addressmap
, buf
)) {
1538 increment_virtual_addr();
1542 increment_virtual_addr();
1544 // log_info(LD_CONFIG, "%d addrs available", (int)available);
1546 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
1550 return tor_strdup(buf
);
1552 log_warn(LD_BUG
, "Called with unsupported address type (%d)", type
);
1557 /** A controller has requested that we map some address of type
1558 * <b>type</b> to the address <b>new_address</b>. Choose an address
1559 * that is unlikely to be used, and map it, and return it in a newly
1560 * allocated string. If another address of the same type is already
1561 * mapped to <b>new_address</b>, try to return a copy of that address.
1563 * The string in <b>new_address</b> may be freed or inserted into a map
1564 * as appropriate. May return NULL if are out of virtual addresses.
1567 addressmap_register_virtual_address(int type
, char *new_address
)
1570 virtaddress_entry_t
*vent
;
1571 int vent_needs_to_be_added
= 0;
1573 tor_assert(new_address
);
1574 tor_assert(addressmap
);
1575 tor_assert(virtaddress_reversemap
);
1577 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1579 vent
= tor_malloc_zero(sizeof(virtaddress_entry_t
));
1580 vent_needs_to_be_added
= 1;
1583 addrp
= (type
== RESOLVED_TYPE_IPV4
) ?
1584 &vent
->ipv4_address
: &vent
->hostname_address
;
1586 addressmap_entry_t
*ent
= strmap_get(addressmap
, *addrp
);
1587 if (ent
&& ent
->new_address
&&
1588 !strcasecmp(new_address
, ent
->new_address
)) {
1589 tor_free(new_address
);
1590 tor_assert(!vent_needs_to_be_added
);
1591 return tor_strdup(*addrp
);
1594 "Internal confusion: I thought that '%s' was mapped to by "
1595 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1596 safe_str_client(new_address
),
1597 safe_str_client(*addrp
),
1598 safe_str_client(*addrp
),
1599 ent
?safe_str_client(ent
->new_address
):"(nothing)");
1603 *addrp
= addressmap_get_virtual_address(type
);
1606 tor_free(new_address
);
1609 log_info(LD_APP
, "Registering map from %s to %s", *addrp
, new_address
);
1610 if (vent_needs_to_be_added
)
1611 strmap_set(virtaddress_reversemap
, new_address
, vent
);
1612 addressmap_register(*addrp
, new_address
, 2, ADDRMAPSRC_AUTOMAP
, 0, 0);
1616 /* Try to catch possible bugs */
1617 addressmap_entry_t
*ent
;
1618 ent
= strmap_get(addressmap
, *addrp
);
1620 tor_assert(!strcasecmp(ent
->new_address
,new_address
));
1621 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1623 tor_assert(!strcasecmp(*addrp
,
1624 (type
== RESOLVED_TYPE_IPV4
) ?
1625 vent
->ipv4_address
: vent
->hostname_address
));
1626 log_info(LD_APP
, "Map from %s to %s okay.",
1627 safe_str_client(*addrp
),
1628 safe_str_client(new_address
));
1635 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1636 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1637 * should be true if we're using this address as a client; false if we're
1638 * using it as a server.
1641 address_is_invalid_destination(const char *address
, int client
)
1644 if (get_options()->AllowNonRFC953Hostnames
)
1647 if (get_options()->ServerDNSAllowNonRFC953Hostnames
)
1652 if (TOR_ISALNUM(*address
) ||
1655 *address
== '_') /* Underscore is not allowed, but Windows does it
1656 * sometimes, just to thumb its nose at the IETF. */
1664 /** Iterate over all address mappings which have expiry times between
1665 * min_expires and max_expires, inclusive. If sl is provided, add an
1666 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1667 * the expiry time if want_expiry is false. If sl is NULL, remove the
1671 addressmap_get_mappings(smartlist_t
*sl
, time_t min_expires
,
1672 time_t max_expires
, int want_expiry
)
1674 strmap_iter_t
*iter
;
1677 addressmap_entry_t
*val
;
1682 for (iter
= strmap_iter_init(addressmap
); !strmap_iter_done(iter
); ) {
1683 strmap_iter_get(iter
, &key
, &_val
);
1685 if (val
->expires
>= min_expires
&& val
->expires
<= max_expires
) {
1687 iter
= strmap_iter_next_rmv(addressmap
,iter
);
1688 addressmap_ent_remove(key
, val
);
1690 } else if (val
->new_address
) {
1691 size_t len
= strlen(key
)+strlen(val
->new_address
)+ISO_TIME_LEN
+5;
1692 char *line
= tor_malloc(len
);
1694 if (val
->expires
< 3 || val
->expires
== TIME_MAX
)
1695 tor_snprintf(line
, len
, "%s %s NEVER", key
, val
->new_address
);
1697 char time
[ISO_TIME_LEN
+1];
1698 format_iso_time(time
, val
->expires
);
1699 tor_snprintf(line
, len
, "%s %s \"%s\"", key
, val
->new_address
,
1703 tor_snprintf(line
, len
, "%s %s", key
, val
->new_address
);
1705 smartlist_add(sl
, line
);
1708 iter
= strmap_iter_next(addressmap
,iter
);
1712 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1713 * reject depending on our config options. */
1715 consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
)
1717 const or_options_t
*options
= get_options();
1718 int reject
= smartlist_string_num_isin(options
->RejectPlaintextPorts
, port
);
1720 if (smartlist_string_num_isin(options
->WarnPlaintextPorts
, port
)) {
1721 log_warn(LD_APP
, "Application request to port %d: this port is "
1722 "commonly used for unencrypted protocols. Please make sure "
1723 "you don't send anything you would mind the rest of the "
1724 "Internet reading!%s", port
, reject
? " Closing." : "");
1725 control_event_client_status(LOG_WARN
, "DANGEROUS_PORT PORT=%d RESULT=%s",
1726 port
, reject
? "REJECT" : "WARN");
1730 log_info(LD_APP
, "Port %d listed in RejectPlaintextPorts. Closing.", port
);
1731 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1738 /** How many times do we try connecting with an exit configured via
1739 * TrackHostExits before concluding that it won't work any more and trying a
1741 #define TRACKHOSTEXITS_RETRIES 5
1743 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1744 * asked us to leave streams unattached. Return 0 in that case.
1746 * See connection_ap_handshake_rewrite_and_attach()'s
1747 * documentation for arguments and return value.
1750 connection_ap_rewrite_and_attach_if_allowed(entry_connection_t
*conn
,
1751 origin_circuit_t
*circ
,
1752 crypt_path_t
*cpath
)
1754 const or_options_t
*options
= get_options();
1756 if (options
->LeaveStreamsUnattached
) {
1757 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1760 return connection_ap_handshake_rewrite_and_attach(conn
, circ
, cpath
);
1763 /** Connection <b>conn</b> just finished its socks handshake, or the
1764 * controller asked us to take care of it. If <b>circ</b> is defined,
1765 * then that's where we'll want to attach it. Otherwise we have to
1766 * figure it out ourselves.
1768 * First, parse whether it's a .exit address, remap it, and so on. Then
1769 * if it's for a general circuit, try to attach it to a circuit (or launch
1770 * one as needed), else if it's for a rendezvous circuit, fetch a
1771 * rendezvous descriptor first (or attach/launch a circuit if the
1772 * rendezvous descriptor is already here and fresh enough).
1774 * The stream will exit from the hop
1775 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1776 * <b>cpath</b> is NULL.
1779 connection_ap_handshake_rewrite_and_attach(entry_connection_t
*conn
,
1780 origin_circuit_t
*circ
,
1781 crypt_path_t
*cpath
)
1783 socks_request_t
*socks
= conn
->socks_request
;
1784 hostname_type_t addresstype
;
1785 const or_options_t
*options
= get_options();
1786 struct in_addr addr_tmp
;
1787 /* We set this to true if this is an address we should automatically
1788 * remap to a local address in VirtualAddrNetwork */
1790 char orig_address
[MAX_SOCKS_ADDR_LEN
];
1791 time_t map_expires
= TIME_MAX
;
1792 /* This will be set to true iff the address starts out as a non-.exit
1793 address, and we remap it to one because of an entry in the addressmap. */
1794 int remapped_to_exit
= 0;
1795 time_t now
= time(NULL
);
1796 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
1798 tor_strlower(socks
->address
); /* normalize it */
1799 strlcpy(orig_address
, socks
->address
, sizeof(orig_address
));
1800 log_debug(LD_APP
,"Client asked for %s:%d",
1801 safe_str_client(socks
->address
),
1804 if (! conn
->original_dest_address
)
1805 conn
->original_dest_address
= tor_strdup(conn
->socks_request
->address
);
1807 if (socks
->command
== SOCKS_COMMAND_RESOLVE
&&
1808 !tor_inet_aton(socks
->address
, &addr_tmp
) &&
1809 options
->AutomapHostsOnResolve
&& options
->AutomapHostsSuffixes
) {
1810 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, const char *, cp
,
1811 if (!strcasecmpend(socks
->address
, cp
)) {
1816 const char *new_addr
;
1817 new_addr
= addressmap_register_virtual_address(
1818 RESOLVED_TYPE_IPV4
, tor_strdup(socks
->address
));
1820 log_warn(LD_APP
, "Unable to automap address %s",
1821 escaped_safe_str(socks
->address
));
1822 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
1825 log_info(LD_APP
, "Automapping %s to %s",
1826 escaped_safe_str_client(socks
->address
),
1827 safe_str_client(new_addr
));
1828 strlcpy(socks
->address
, new_addr
, sizeof(socks
->address
));
1832 if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1833 if (addressmap_rewrite_reverse(socks
->address
, sizeof(socks
->address
),
1835 char *result
= tor_strdup(socks
->address
);
1836 /* remember _what_ is supposed to have been resolved. */
1837 tor_snprintf(socks
->address
, sizeof(socks
->address
), "REVERSE[%s]",
1839 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_HOSTNAME
,
1840 strlen(result
), (uint8_t*)result
,
1843 connection_mark_unattached_ap(conn
,
1844 END_STREAM_REASON_DONE
|
1845 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1848 if (options
->ClientDNSRejectInternalAddresses
) {
1849 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1852 ok
= tor_addr_parse_PTR_name(
1853 &addr
, socks
->address
, AF_UNSPEC
, 1);
1854 if (ok
== 1 && tor_addr_is_internal(&addr
, 0)) {
1855 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_ERROR
,
1856 0, NULL
, -1, TIME_MAX
);
1857 connection_mark_unattached_ap(conn
,
1858 END_STREAM_REASON_SOCKSPROTOCOL
|
1859 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1863 } else if (!automap
) {
1864 int started_without_chosen_exit
= strcasecmpend(socks
->address
, ".exit");
1865 /* For address map controls, remap the address. */
1866 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
),
1868 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1869 REMAP_STREAM_SOURCE_CACHE
);
1870 if (started_without_chosen_exit
&&
1871 !strcasecmpend(socks
->address
, ".exit") &&
1872 map_expires
< TIME_MAX
)
1873 remapped_to_exit
= 1;
1877 if (!automap
&& address_is_in_virtual_range(socks
->address
)) {
1878 /* This address was probably handed out by client_dns_get_unmapped_address,
1879 * but the mapping was discarded for some reason. We *don't* want to send
1880 * the address through Tor; that's likely to fail, and may leak
1883 log_warn(LD_APP
,"Missing mapping for virtual address '%s'. Refusing.",
1884 safe_str_client(socks
->address
));
1885 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
1889 /* Parse the address provided by SOCKS. Modify it in-place if it
1890 * specifies a hidden-service (.onion) or particular exit node (.exit).
1892 addresstype
= parse_extended_hostname(socks
->address
,
1893 remapped_to_exit
|| options
->AllowDotExit
);
1895 if (addresstype
== BAD_HOSTNAME
) {
1896 log_warn(LD_APP
, "Invalid onion hostname %s; rejecting",
1897 safe_str_client(socks
->address
));
1898 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1899 escaped(socks
->address
));
1900 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1904 if (addresstype
== EXIT_HOSTNAME
) {
1905 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1906 * node, and conn->address to hold only the address portion. */
1907 char *s
= strrchr(socks
->address
,'.');
1909 /* If StrictNodes is not set, then .exit overrides ExcludeNodes. */
1910 routerset_t
*excludeset
= options
->StrictNodes
?
1911 options
->_ExcludeExitNodesUnion
: options
->ExcludeExitNodes
;
1914 tor_assert(!automap
);
1916 /* The address was of the form "(stuff).(name).exit */
1918 conn
->chosen_exit_name
= tor_strdup(s
+1);
1919 node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1920 if (remapped_to_exit
) /* 5 tries before it expires the addressmap */
1921 conn
->chosen_exit_retries
= TRACKHOSTEXITS_RETRIES
;
1924 /* Oops, the address was (stuff)..exit. That's not okay. */
1925 log_warn(LD_APP
,"Malformed exit address '%s.exit'. Refusing.",
1926 safe_str_client(socks
->address
));
1927 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1928 escaped(socks
->address
));
1929 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1933 /* It looks like they just asked for "foo.exit". */
1935 conn
->chosen_exit_name
= tor_strdup(socks
->address
);
1936 node
= node_get_by_nickname(conn
->chosen_exit_name
, 1);
1938 *socks
->address
= 0;
1939 node_get_address_string(node
, socks
->address
, sizeof(socks
->address
));
1942 /* Now make sure that the chosen exit exists... */
1945 "Unrecognized relay in exit address '%s.exit'. Refusing.",
1946 safe_str_client(socks
->address
));
1947 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1950 /* ...and make sure that it isn't excluded. */
1951 if (routerset_contains_node(excludeset
, node
)) {
1953 "Excluded relay in exit address '%s.exit'. Refusing.",
1954 safe_str_client(socks
->address
));
1955 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1958 /* XXXX022-1090 Should we also allow foo.bar.exit if ExitNodes is set and
1959 Bar is not listed in it? I say yes, but our revised manpage branch
1963 if (addresstype
!= ONION_HOSTNAME
) {
1964 /* not a hidden-service request (i.e. normal or .exit) */
1965 if (address_is_invalid_destination(socks
->address
, 1)) {
1966 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1967 escaped(socks
->address
));
1969 "Destination '%s' seems to be an invalid hostname. Failing.",
1970 safe_str_client(socks
->address
));
1971 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1975 if (options
->Tor2webMode
) {
1976 log_warn(LD_APP
, "Refusing to connect to non-hidden-service hostname %s "
1977 "because tor2web mode is enabled.",
1978 safe_str_client(socks
->address
));
1979 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1983 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
1986 /* Reply to resolves immediately if we can. */
1987 if (tor_inet_aton(socks
->address
, &in
)) { /* see if it's an IP already */
1988 /* leave it in network order */
1990 /* remember _what_ is supposed to have been resolved. */
1991 strlcpy(socks
->address
, orig_address
, sizeof(socks
->address
));
1992 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
1995 connection_mark_unattached_ap(conn
,
1996 END_STREAM_REASON_DONE
|
1997 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2000 tor_assert(!automap
);
2001 rep_hist_note_used_resolve(now
); /* help predict this next time */
2002 } else if (socks
->command
== SOCKS_COMMAND_CONNECT
) {
2003 tor_assert(!automap
);
2004 if (socks
->port
== 0) {
2005 log_notice(LD_APP
,"Application asked to connect to port 0. Refusing.");
2006 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2009 if (options
->ClientRejectInternalAddresses
&&
2010 !conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
2012 if (tor_addr_parse(&addr
, socks
->address
) >= 0 &&
2013 tor_addr_is_internal(&addr
, 0)) {
2014 /* If this is an explicit private address with no chosen exit node,
2015 * then we really don't want to try to connect to it. That's
2016 * probably an error. */
2017 if (conn
->is_transparent_ap
) {
2019 "Rejecting request for anonymous connection to private "
2020 "address %s on a TransPort or NATDPort. Possible loop "
2021 "in your NAT rules?", safe_str_client(socks
->address
));
2024 "Rejecting SOCKS request for anonymous connection to "
2025 "private address %s", safe_str_client(socks
->address
));
2027 connection_mark_unattached_ap(conn
, END_STREAM_REASON_PRIVATE_ADDR
);
2032 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
2033 /* see if we can find a suitable enclave exit */
2035 router_find_exact_exit_enclave(socks
->address
, socks
->port
);
2038 "Redirecting address %s to exit at enclave router %s",
2039 safe_str_client(socks
->address
), node_describe(r
));
2040 /* use the hex digest, not nickname, in case there are two
2041 routers with this nickname */
2042 conn
->chosen_exit_name
=
2043 tor_strdup(hex_str(r
->identity
, DIGEST_LEN
));
2044 conn
->chosen_exit_optional
= 1;
2048 /* warn or reject if it's using a dangerous port */
2049 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
)
2050 if (consider_plaintext_ports(conn
, socks
->port
) < 0)
2053 if (!conn
->use_begindir
) {
2054 /* help predict this next time */
2055 rep_hist_note_used_port(now
, socks
->port
);
2057 } else if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
2058 rep_hist_note_used_resolve(now
); /* help predict this next time */
2059 /* no extra processing needed */
2061 tor_fragile_assert();
2063 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2064 if ((circ
&& connection_ap_handshake_attach_chosen_circuit(
2065 conn
, circ
, cpath
) < 0) ||
2067 connection_ap_handshake_attach_circuit(conn
) < 0)) {
2068 if (!base_conn
->marked_for_close
)
2069 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
2074 /* it's a hidden-service request */
2075 rend_cache_entry_t
*entry
;
2077 rend_service_authorization_t
*client_auth
;
2078 rend_data_t
*rend_data
;
2079 tor_assert(!automap
);
2080 if (SOCKS_COMMAND_IS_RESOLVE(socks
->command
)) {
2081 /* if it's a resolve request, fail it right now, rather than
2082 * building all the circuits and then realizing it won't work. */
2084 "Resolve requests to hidden services not allowed. Failing.");
2085 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
2086 0,NULL
,-1,TIME_MAX
);
2087 connection_mark_unattached_ap(conn
,
2088 END_STREAM_REASON_SOCKSPROTOCOL
|
2089 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2094 log_warn(LD_CONTROL
, "Attachstream to a circuit is not "
2095 "supported for .onion addresses currently. Failing.");
2096 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2100 ENTRY_TO_EDGE_CONN(conn
)->rend_data
= rend_data
=
2101 tor_malloc_zero(sizeof(rend_data_t
));
2102 strlcpy(rend_data
->onion_address
, socks
->address
,
2103 sizeof(rend_data
->onion_address
));
2104 log_info(LD_REND
,"Got a hidden service request for ID '%s'",
2105 safe_str_client(rend_data
->onion_address
));
2106 /* see if we already have it cached */
2107 r
= rend_cache_lookup_entry(rend_data
->onion_address
, -1, &entry
);
2109 log_warn(LD_BUG
,"Invalid service name '%s'",
2110 safe_str_client(rend_data
->onion_address
));
2111 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2115 /* Help predict this next time. We're not sure if it will need
2116 * a stable circuit yet, but we know we'll need *something*. */
2117 rep_hist_note_used_internal(now
, 0, 1);
2119 /* Look up if we have client authorization for it. */
2120 client_auth
= rend_client_lookup_service_authorization(
2121 rend_data
->onion_address
);
2123 log_info(LD_REND
, "Using previously configured client authorization "
2124 "for hidden service request.");
2125 memcpy(rend_data
->descriptor_cookie
,
2126 client_auth
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
2127 rend_data
->auth_type
= client_auth
->auth_type
;
2130 base_conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
2131 log_info(LD_REND
, "Unknown descriptor %s. Fetching.",
2132 safe_str_client(rend_data
->onion_address
));
2133 rend_client_refetch_v2_renddesc(rend_data
);
2134 } else { /* r > 0 */
2135 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2136 log_info(LD_REND
, "Descriptor is here. Great.");
2137 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
2138 if (!base_conn
->marked_for_close
)
2139 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
2145 return 0; /* unreached but keeps the compiler happy */
2149 static int pf_socket
= -1;
2154 /* This should be opened before dropping privileges. */
2159 /* only works on OpenBSD */
2160 pf
= tor_open_cloexec("/dev/pf", O_RDONLY
, 0);
2162 /* works on NetBSD and FreeBSD */
2163 pf
= tor_open_cloexec("/dev/pf", O_RDWR
, 0);
2167 log_warn(LD_NET
, "open(\"/dev/pf\") failed: %s", strerror(errno
));
2176 /** Fetch the original destination address and port from a
2177 * system-specific interface and put them into a
2178 * socks_request_t as if they came from a socks request.
2180 * Return -1 if an error prevents fetching the destination,
2184 connection_ap_get_original_destination(entry_connection_t
*conn
,
2185 socks_request_t
*req
)
2187 #ifdef TRANS_NETFILTER
2189 struct sockaddr_storage orig_dst
;
2190 socklen_t orig_dst_len
= sizeof(orig_dst
);
2193 if (getsockopt(ENTRY_TO_CONN(conn
)->s
, SOL_IP
, SO_ORIGINAL_DST
,
2194 (struct sockaddr
*)&orig_dst
, &orig_dst_len
) < 0) {
2195 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2196 log_warn(LD_NET
, "getsockopt() failed: %s", tor_socket_strerror(e
));
2200 tor_addr_from_sockaddr(&addr
, (struct sockaddr
*)&orig_dst
, &req
->port
);
2201 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 0);
2204 #elif defined(TRANS_PF)
2205 struct sockaddr_storage proxy_addr
;
2206 socklen_t proxy_addr_len
= sizeof(proxy_addr
);
2207 struct sockaddr
*proxy_sa
= (struct sockaddr
*) &proxy_addr
;
2208 struct pfioc_natlook pnl
;
2212 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&proxy_addr
,
2213 &proxy_addr_len
) < 0) {
2214 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2215 log_warn(LD_NET
, "getsockname() to determine transocks destination "
2216 "failed: %s", tor_socket_strerror(e
));
2220 memset(&pnl
, 0, sizeof(pnl
));
2221 pnl
.proto
= IPPROTO_TCP
;
2222 pnl
.direction
= PF_OUT
;
2223 if (proxy_sa
->sa_family
== AF_INET
) {
2224 struct sockaddr_in
*sin
= (struct sockaddr_in
*)proxy_sa
;
2226 pnl
.saddr
.v4
.s_addr
= tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn
)->addr
);
2227 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
2228 pnl
.daddr
.v4
.s_addr
= sin
->sin_addr
.s_addr
;
2229 pnl
.dport
= sin
->sin_port
;
2230 } else if (proxy_sa
->sa_family
== AF_INET6
) {
2231 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)proxy_sa
;
2233 memcpy(&pnl
.saddr
.v6
, tor_addr_to_in6(&ENTRY_TO_CONN(conn
)->addr
),
2234 sizeof(struct in6_addr
));
2235 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
2236 memcpy(&pnl
.daddr
.v6
, &sin6
->sin6_addr
, sizeof(struct in6_addr
));
2237 pnl
.dport
= sin6
->sin6_port
;
2239 log_warn(LD_NET
, "getsockname() gave an unexpected address family (%d)",
2240 (int)proxy_sa
->sa_family
);
2244 pf
= get_pf_socket();
2248 if (ioctl(pf
, DIOCNATLOOK
, &pnl
) < 0) {
2249 log_warn(LD_NET
, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno
));
2253 if (pnl
.af
== AF_INET
) {
2254 tor_addr_from_ipv4n(&addr
, pnl
.rdaddr
.v4
.s_addr
);
2255 } else if (pnl
.af
== AF_INET6
) {
2256 tor_addr_from_in6(&addr
, &pnl
.rdaddr
.v6
);
2258 tor_fragile_assert();
2262 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 0);
2263 req
->port
= ntohs(pnl
.rdport
);
2269 log_warn(LD_BUG
, "Called connection_ap_get_original_destination, but no "
2270 "transparent proxy method was configured.");
2275 /** connection_edge_process_inbuf() found a conn in state
2276 * socks_wait. See if conn->inbuf has the right bytes to proceed with
2277 * the socks handshake.
2279 * If the handshake is complete, send it to
2280 * connection_ap_handshake_rewrite_and_attach().
2282 * Return -1 if an unexpected error with conn occurs (and mark it for close),
2286 connection_ap_handshake_process_socks(entry_connection_t
*conn
)
2288 socks_request_t
*socks
;
2290 const or_options_t
*options
= get_options();
2292 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
2295 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
2296 tor_assert(base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
);
2297 tor_assert(conn
->socks_request
);
2298 socks
= conn
->socks_request
;
2300 log_debug(LD_APP
,"entered.");
2302 IF_HAS_BUFFEREVENT(base_conn
, {
2303 struct evbuffer
*input
= bufferevent_get_input(base_conn
->bufev
);
2304 sockshere
= fetch_from_evbuffer_socks(input
, socks
,
2305 options
->TestSocks
, options
->SafeSocks
);
2306 }) ELSE_IF_NO_BUFFEREVENT
{
2307 sockshere
= fetch_from_buf_socks(base_conn
->inbuf
, socks
,
2308 options
->TestSocks
, options
->SafeSocks
);
2311 if (socks
->replylen
) {
2313 connection_write_to_buf((const char*)socks
->reply
, socks
->replylen
,
2315 socks
->replylen
= 0;
2318 if (sockshere
== 0) {
2319 log_debug(LD_APP
,"socks handshake not all here yet.");
2321 } else if (sockshere
== -1) {
2323 log_warn(LD_APP
,"Fetching socks handshake failed. Closing.");
2324 connection_ap_handshake_socks_reply(conn
, NULL
, 0,
2325 END_STREAM_REASON_SOCKSPROTOCOL
);
2327 connection_mark_unattached_ap(conn
,
2328 END_STREAM_REASON_SOCKSPROTOCOL
|
2329 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2331 } /* else socks handshake is done, continue processing */
2333 if (SOCKS_COMMAND_IS_CONNECT(socks
->command
))
2334 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2336 control_event_stream_status(conn
, STREAM_EVENT_NEW_RESOLVE
, 0);
2338 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2341 /** connection_init_accepted_conn() found a new trans AP conn.
2342 * Get the original destination and send it to
2343 * connection_ap_handshake_rewrite_and_attach().
2345 * Return -1 if an unexpected error with conn (and it should be marked
2346 * for close), else return 0.
2349 connection_ap_process_transparent(entry_connection_t
*conn
)
2351 socks_request_t
*socks
;
2354 tor_assert(conn
->socks_request
);
2355 socks
= conn
->socks_request
;
2357 /* pretend that a socks handshake completed so we don't try to
2358 * send a socks reply down a transparent conn */
2359 socks
->command
= SOCKS_COMMAND_CONNECT
;
2360 socks
->has_finished
= 1;
2362 log_debug(LD_APP
,"entered.");
2364 if (connection_ap_get_original_destination(conn
, socks
) < 0) {
2365 log_warn(LD_APP
,"Fetching original destination failed. Closing.");
2366 connection_mark_unattached_ap(conn
,
2367 END_STREAM_REASON_CANT_FETCH_ORIG_DEST
);
2370 /* we have the original destination */
2372 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2374 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2377 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2378 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2379 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2380 * form of the original destination.
2382 * If the original destination is complete, send it to
2383 * connection_ap_handshake_rewrite_and_attach().
2385 * Return -1 if an unexpected error with conn (and it should be marked
2386 * for close), else return 0.
2389 connection_ap_process_natd(entry_connection_t
*conn
)
2391 char tmp_buf
[36], *tbuf
, *daddr
;
2394 socks_request_t
*socks
;
2397 tor_assert(ENTRY_TO_CONN(conn
)->state
== AP_CONN_STATE_NATD_WAIT
);
2398 tor_assert(conn
->socks_request
);
2399 socks
= conn
->socks_request
;
2401 log_debug(LD_APP
,"entered.");
2403 /* look for LF-terminated "[DEST ip_addr port]"
2404 * where ip_addr is a dotted-quad and port is in string form */
2405 err
= connection_fetch_from_buf_line(ENTRY_TO_CONN(conn
), tmp_buf
, &tlen
);
2409 log_warn(LD_APP
,"NATD handshake failed (DEST too long). Closing");
2410 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2414 if (strcmpstart(tmp_buf
, "[DEST ")) {
2415 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2418 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2422 daddr
= tbuf
= &tmp_buf
[0] + 6; /* after end of "[DEST " */
2423 if (!(tbuf
= strchr(tbuf
, ' '))) {
2424 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2427 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2432 /* pretend that a socks handshake completed so we don't try to
2433 * send a socks reply down a natd conn */
2434 strlcpy(socks
->address
, daddr
, sizeof(socks
->address
));
2435 socks
->port
= (uint16_t)
2436 tor_parse_long(tbuf
, 10, 1, 65535, &port_ok
, &daddr
);
2438 log_warn(LD_APP
,"NATD handshake failed; port %s is ill-formed or out "
2439 "of range.", escaped(tbuf
));
2440 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2444 socks
->command
= SOCKS_COMMAND_CONNECT
;
2445 socks
->has_finished
= 1;
2447 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2449 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2451 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2454 /** Iterate over the two bytes of stream_id until we get one that is not
2455 * already in use; return it. Return 0 if can't get a unique stream_id.
2458 get_unique_stream_id_by_circ(origin_circuit_t
*circ
)
2460 edge_connection_t
*tmpconn
;
2461 streamid_t test_stream_id
;
2462 uint32_t attempts
=0;
2465 test_stream_id
= circ
->next_stream_id
++;
2466 if (++attempts
> 1<<16) {
2467 /* Make sure we don't loop forever if all stream_id's are used. */
2468 log_warn(LD_APP
,"No unused stream IDs. Failing.");
2471 if (test_stream_id
== 0)
2473 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
2474 if (tmpconn
->stream_id
== test_stream_id
)
2476 return test_stream_id
;
2479 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
2480 * an exit that supports optimistic data. */
2482 connection_ap_supports_optimistic_data(const entry_connection_t
*conn
)
2484 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
2485 /* We can only send optimistic data if we're connected to an open
2487 if (edge_conn
->on_circuit
== NULL
||
2488 edge_conn
->on_circuit
->state
!= CIRCUIT_STATE_OPEN
||
2489 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
2492 return conn
->may_use_optimistic_data
;
2495 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2496 * socks_request field, and send it down circ.
2498 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2501 connection_ap_handshake_send_begin(entry_connection_t
*ap_conn
)
2503 char payload
[CELL_PAYLOAD_SIZE
];
2506 origin_circuit_t
*circ
;
2507 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
2508 connection_t
*base_conn
= TO_CONN(edge_conn
);
2509 tor_assert(edge_conn
->on_circuit
);
2510 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
2512 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
2513 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
2514 tor_assert(ap_conn
->socks_request
);
2515 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn
->socks_request
->command
));
2517 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
2518 if (edge_conn
->stream_id
==0) {
2519 /* XXXX023 Instead of closing this stream, we should make it get
2520 * retried on another circuit. */
2521 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2523 /* Mark this circuit "unusable for new streams". */
2524 /* XXXX023 this is a kludgy way to do this. */
2525 tor_assert(circ
->_base
.timestamp_dirty
);
2526 circ
->_base
.timestamp_dirty
-= get_options()->MaxCircuitDirtiness
;
2530 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:%d",
2531 (circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
) ?
2532 ap_conn
->socks_request
->address
: "",
2533 ap_conn
->socks_request
->port
);
2534 payload_len
= (int)strlen(payload
)+1;
2537 "Sending relay cell %d to begin stream %d.",
2538 (int)ap_conn
->use_begindir
,
2539 edge_conn
->stream_id
);
2541 begin_type
= ap_conn
->use_begindir
?
2542 RELAY_COMMAND_BEGIN_DIR
: RELAY_COMMAND_BEGIN
;
2543 if (begin_type
== RELAY_COMMAND_BEGIN
) {
2544 #ifndef NON_ANONYMOUS_MODE_ENABLED
2545 tor_assert(circ
->build_state
->onehop_tunnel
== 0);
2549 if (connection_edge_send_command(edge_conn
, begin_type
,
2550 begin_type
== RELAY_COMMAND_BEGIN
? payload
: NULL
,
2551 begin_type
== RELAY_COMMAND_BEGIN
? payload_len
: 0) < 0)
2552 return -1; /* circuit is closed, don't continue */
2554 edge_conn
->package_window
= STREAMWINDOW_START
;
2555 edge_conn
->deliver_window
= STREAMWINDOW_START
;
2556 base_conn
->state
= AP_CONN_STATE_CONNECT_WAIT
;
2557 log_info(LD_APP
,"Address/port sent, ap socket %d, n_circ_id %d",
2558 base_conn
->s
, circ
->_base
.n_circ_id
);
2559 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
, 0);
2561 /* If there's queued-up data, send it now */
2562 if ((connection_get_inbuf_len(base_conn
) ||
2563 ap_conn
->sending_optimistic_data
) &&
2564 connection_ap_supports_optimistic_data(ap_conn
)) {
2565 log_info(LD_APP
, "Sending up to %ld + %ld bytes of queued-up data",
2566 (long)connection_get_inbuf_len(base_conn
),
2567 ap_conn
->sending_optimistic_data
?
2568 (long)generic_buffer_len(ap_conn
->sending_optimistic_data
) : 0);
2569 if (connection_edge_package_raw_inbuf(edge_conn
, 1, NULL
) < 0) {
2570 connection_mark_for_close(base_conn
);
2577 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2578 * socks_request field, and send it down circ.
2580 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2583 connection_ap_handshake_send_resolve(entry_connection_t
*ap_conn
)
2585 int payload_len
, command
;
2586 const char *string_addr
;
2587 char inaddr_buf
[REVERSE_LOOKUP_NAME_BUF_LEN
];
2588 origin_circuit_t
*circ
;
2589 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
2590 connection_t
*base_conn
= TO_CONN(edge_conn
);
2591 tor_assert(edge_conn
->on_circuit
);
2592 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
2594 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
2595 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
2596 tor_assert(ap_conn
->socks_request
);
2597 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
2599 command
= ap_conn
->socks_request
->command
;
2600 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command
));
2602 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
2603 if (edge_conn
->stream_id
==0) {
2604 /* XXXX023 Instead of closing this stream, we should make it get
2605 * retried on another circuit. */
2606 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2608 /* Mark this circuit "unusable for new streams". */
2609 /* XXXX023 this is a kludgy way to do this. */
2610 tor_assert(circ
->_base
.timestamp_dirty
);
2611 circ
->_base
.timestamp_dirty
-= get_options()->MaxCircuitDirtiness
;
2615 if (command
== SOCKS_COMMAND_RESOLVE
) {
2616 string_addr
= ap_conn
->socks_request
->address
;
2617 payload_len
= (int)strlen(string_addr
)+1;
2619 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2620 const char *a
= ap_conn
->socks_request
->address
;
2624 /* We're doing a reverse lookup. The input could be an IP address, or
2625 * could be an .in-addr.arpa or .ip6.arpa address */
2626 r
= tor_addr_parse_PTR_name(&addr
, a
, AF_INET
, 1);
2628 log_warn(LD_APP
, "Rejecting ill-formed reverse lookup of %s",
2629 safe_str_client(a
));
2630 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2634 r
= tor_addr_to_PTR_name(inaddr_buf
, sizeof(inaddr_buf
), &addr
);
2636 log_warn(LD_BUG
, "Couldn't generate reverse lookup hostname of %s",
2637 safe_str_client(a
));
2638 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2642 string_addr
= inaddr_buf
;
2643 payload_len
= (int)strlen(inaddr_buf
)+1;
2644 tor_assert(payload_len
<= (int)sizeof(inaddr_buf
));
2648 "Sending relay cell to begin stream %d.", edge_conn
->stream_id
);
2650 if (connection_edge_send_command(edge_conn
,
2651 RELAY_COMMAND_RESOLVE
,
2652 string_addr
, payload_len
) < 0)
2653 return -1; /* circuit is closed, don't continue */
2655 tor_free(base_conn
->address
); /* Maybe already set by dnsserv. */
2656 base_conn
->address
= tor_strdup("(Tor_internal)");
2657 base_conn
->state
= AP_CONN_STATE_RESOLVE_WAIT
;
2658 log_info(LD_APP
,"Address sent for resolve, ap socket %d, n_circ_id %d",
2659 base_conn
->s
, circ
->_base
.n_circ_id
);
2660 control_event_stream_status(ap_conn
, STREAM_EVENT_NEW
, 0);
2661 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
, 0);
2665 /** Make an AP connection_t, make a new linked connection pair, and attach
2666 * one side to the conn, connection_add it, initialize it to circuit_wait,
2667 * and call connection_ap_handshake_attach_circuit(conn) on it.
2669 * Return the other end of the linked connection pair, or -1 if error.
2672 entry_connection_t
*
2673 connection_ap_make_link(connection_t
*partner
,
2674 char *address
, uint16_t port
,
2676 int session_group
, int isolation_flags
,
2677 int use_begindir
, int want_onehop
)
2679 entry_connection_t
*conn
;
2680 connection_t
*base_conn
;
2682 log_info(LD_APP
,"Making internal %s tunnel to %s:%d ...",
2683 want_onehop
? "direct" : "anonymized",
2684 safe_str_client(address
), port
);
2686 conn
= entry_connection_new(CONN_TYPE_AP
, tor_addr_family(&partner
->addr
));
2687 base_conn
= ENTRY_TO_CONN(conn
);
2688 base_conn
->linked
= 1; /* so that we can add it safely below. */
2690 /* populate conn->socks_request */
2692 /* leave version at zero, so the socks_reply is empty */
2693 conn
->socks_request
->socks_version
= 0;
2694 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
2695 strlcpy(conn
->socks_request
->address
, address
,
2696 sizeof(conn
->socks_request
->address
));
2697 conn
->socks_request
->port
= port
;
2698 conn
->socks_request
->command
= SOCKS_COMMAND_CONNECT
;
2699 conn
->want_onehop
= want_onehop
;
2700 conn
->use_begindir
= use_begindir
;
2702 conn
->chosen_exit_name
= tor_malloc(HEX_DIGEST_LEN
+2);
2703 conn
->chosen_exit_name
[0] = '$';
2705 base16_encode(conn
->chosen_exit_name
+1,HEX_DIGEST_LEN
+1,
2706 digest
, DIGEST_LEN
);
2709 /* Populate isolation fields. */
2710 conn
->socks_request
->listener_type
= CONN_TYPE_DIR_LISTENER
;
2711 conn
->original_dest_address
= tor_strdup(address
);
2712 conn
->session_group
= session_group
;
2713 conn
->isolation_flags
= isolation_flags
;
2715 base_conn
->address
= tor_strdup("(Tor_internal)");
2716 tor_addr_make_unspec(&base_conn
->addr
);
2717 base_conn
->port
= 0;
2719 connection_link_connections(partner
, base_conn
);
2721 if (connection_add(base_conn
) < 0) { /* no space, forget it */
2722 connection_free(base_conn
);
2726 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2728 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2730 /* attaching to a dirty circuit is fine */
2731 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
2732 if (!base_conn
->marked_for_close
)
2733 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
2737 log_info(LD_APP
,"... application connection created and linked.");
2741 /** Notify any interested controller connections about a new hostname resolve
2742 * or resolve error. Takes the same arguments as does
2743 * connection_ap_handshake_socks_resolved(). */
2745 tell_controller_about_resolved_result(entry_connection_t
*conn
,
2753 if (ttl
>= 0 && (answer_type
== RESOLVED_TYPE_IPV4
||
2754 answer_type
== RESOLVED_TYPE_HOSTNAME
)) {
2755 return; /* we already told the controller. */
2756 } else if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
>= 4) {
2757 char *cp
= tor_dup_ip(get_uint32(answer
));
2758 control_event_address_mapped(conn
->socks_request
->address
,
2761 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2762 char *cp
= tor_strndup(answer
, answer_len
);
2763 control_event_address_mapped(conn
->socks_request
->address
,
2767 control_event_address_mapped(conn
->socks_request
->address
,
2774 /** Send an answer to an AP connection that has requested a DNS lookup via
2775 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2776 * for unreachable; the answer should be in the format specified in the socks
2777 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2778 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2779 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2781 /* XXXX023 the use of the ttl and expires fields is nutty. Let's make this
2782 * interface and those that use it less ugly. */
2784 connection_ap_handshake_socks_resolved(entry_connection_t
*conn
,
2787 const uint8_t *answer
,
2795 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2796 uint32_t a
= ntohl(get_uint32(answer
));
2798 client_dns_set_addressmap(conn
->socks_request
->address
, a
,
2799 conn
->chosen_exit_name
, ttl
);
2800 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2801 char *cp
= tor_strndup((char*)answer
, answer_len
);
2802 client_dns_set_reverse_addressmap(conn
->socks_request
->address
,
2804 conn
->chosen_exit_name
, ttl
);
2809 if (ENTRY_TO_EDGE_CONN(conn
)->is_dns_request
) {
2810 if (conn
->dns_server_request
) {
2811 /* We had a request on our DNS port: answer it. */
2812 dnsserv_resolved(conn
, answer_type
, answer_len
, (char*)answer
, ttl
);
2813 conn
->socks_request
->has_finished
= 1;
2816 /* This must be a request from the controller. We already sent
2817 * a mapaddress if there's a ttl. */
2818 tell_controller_about_resolved_result(conn
, answer_type
, answer_len
,
2819 (char*)answer
, ttl
, expires
);
2820 conn
->socks_request
->has_finished
= 1;
2823 /* We shouldn't need to free conn here; it gets marked by the caller. */
2826 if (conn
->socks_request
->socks_version
== 4) {
2827 buf
[0] = 0x00; /* version */
2828 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2829 buf
[1] = SOCKS4_GRANTED
;
2830 set_uint16(buf
+2, 0);
2831 memcpy(buf
+4, answer
, 4); /* address */
2832 replylen
= SOCKS4_NETWORK_LEN
;
2833 } else { /* "error" */
2834 buf
[1] = SOCKS4_REJECT
;
2835 memset(buf
+2, 0, 6);
2836 replylen
= SOCKS4_NETWORK_LEN
;
2838 } else if (conn
->socks_request
->socks_version
== 5) {
2840 buf
[0] = 0x05; /* version */
2841 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2842 buf
[1] = SOCKS5_SUCCEEDED
;
2843 buf
[2] = 0; /* reserved */
2844 buf
[3] = 0x01; /* IPv4 address type */
2845 memcpy(buf
+4, answer
, 4); /* address */
2846 set_uint16(buf
+8, 0); /* port == 0. */
2848 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
2849 buf
[1] = SOCKS5_SUCCEEDED
;
2850 buf
[2] = 0; /* reserved */
2851 buf
[3] = 0x04; /* IPv6 address type */
2852 memcpy(buf
+4, answer
, 16); /* address */
2853 set_uint16(buf
+20, 0); /* port == 0. */
2855 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2856 buf
[1] = SOCKS5_SUCCEEDED
;
2857 buf
[2] = 0; /* reserved */
2858 buf
[3] = 0x03; /* Domainname address type */
2859 buf
[4] = (char)answer_len
;
2860 memcpy(buf
+5, answer
, answer_len
); /* address */
2861 set_uint16(buf
+5+answer_len
, 0); /* port == 0. */
2862 replylen
= 5+answer_len
+2;
2864 buf
[1] = SOCKS5_HOST_UNREACHABLE
;
2865 memset(buf
+2, 0, 8);
2869 /* no socks version info; don't send anything back */
2872 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
2873 (answer_type
== RESOLVED_TYPE_IPV4
||
2874 answer_type
== RESOLVED_TYPE_IPV6
||
2875 answer_type
== RESOLVED_TYPE_HOSTNAME
) ?
2876 0 : END_STREAM_REASON_RESOLVEFAILED
);
2879 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2880 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2883 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2884 * and return, else reply based on <b>endreason</b> (one of
2885 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2886 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2889 connection_ap_handshake_socks_reply(entry_connection_t
*conn
, char *reply
,
2890 size_t replylen
, int endreason
)
2893 socks5_reply_status_t status
=
2894 stream_end_reason_to_socks5_response(endreason
);
2896 tor_assert(conn
->socks_request
); /* make sure it's an AP stream */
2898 control_event_stream_status(conn
,
2899 status
==SOCKS5_SUCCEEDED
? STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
,
2902 if (conn
->socks_request
->has_finished
) {
2903 log_warn(LD_BUG
, "(Harmless.) duplicate calls to "
2904 "connection_ap_handshake_socks_reply.");
2907 if (replylen
) { /* we already have a reply in mind */
2908 connection_write_to_buf(reply
, replylen
, ENTRY_TO_CONN(conn
));
2909 conn
->socks_request
->has_finished
= 1;
2912 if (conn
->socks_request
->socks_version
== 4) {
2913 memset(buf
,0,SOCKS4_NETWORK_LEN
);
2914 buf
[1] = (status
==SOCKS5_SUCCEEDED
? SOCKS4_GRANTED
: SOCKS4_REJECT
);
2915 /* leave version, destport, destip zero */
2916 connection_write_to_buf(buf
, SOCKS4_NETWORK_LEN
, ENTRY_TO_CONN(conn
));
2917 } else if (conn
->socks_request
->socks_version
== 5) {
2918 buf
[0] = 5; /* version 5 */
2919 buf
[1] = (char)status
;
2921 buf
[3] = 1; /* ipv4 addr */
2922 memset(buf
+4,0,6); /* Set external addr/port to 0.
2923 The spec doesn't seem to say what to do here. -RD */
2924 connection_write_to_buf(buf
,10,ENTRY_TO_CONN(conn
));
2926 /* If socks_version isn't 4 or 5, don't send anything.
2927 * This can happen in the case of AP bridges. */
2928 conn
->socks_request
->has_finished
= 1;
2932 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2933 * an exit hop for the circuit, or we are the origin and it is a
2936 * Launch a new exit connection and initialize things appropriately.
2938 * If it's a rendezvous stream, call connection_exit_connect() on
2941 * For general streams, call dns_resolve() on it first, and only call
2942 * connection_exit_connect() if the dns answer is already known.
2944 * Note that we don't call connection_add() on the new stream! We wait
2945 * for connection_exit_connect() to do that.
2947 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2951 connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
)
2953 edge_connection_t
*n_stream
;
2957 or_circuit_t
*or_circ
= NULL
;
2958 const or_options_t
*options
= get_options();
2960 assert_circuit_ok(circ
);
2961 if (!CIRCUIT_IS_ORIGIN(circ
))
2962 or_circ
= TO_OR_CIRCUIT(circ
);
2964 relay_header_unpack(&rh
, cell
->payload
);
2965 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
2968 /* Note: we have to use relay_send_command_from_edge here, not
2969 * connection_edge_end or connection_edge_send_command, since those require
2970 * that we have a stream connected to a circuit, and we don't connect to a
2971 * circuit until we have a pending/successful resolve. */
2973 if (!server_mode(options
) &&
2974 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
2975 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2976 "Relay begin cell at non-server. Closing.");
2977 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2978 END_STREAM_REASON_EXITPOLICY
, NULL
);
2982 if (rh
.command
== RELAY_COMMAND_BEGIN
) {
2983 if (!memchr(cell
->payload
+RELAY_HEADER_SIZE
, 0, rh
.length
)) {
2984 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2985 "Relay begin cell has no \\0. Closing.");
2986 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2987 END_STREAM_REASON_TORPROTOCOL
, NULL
);
2990 if (tor_addr_port_split(LOG_PROTOCOL_WARN
,
2991 (char*)(cell
->payload
+RELAY_HEADER_SIZE
),
2992 &address
,&port
)<0) {
2993 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2994 "Unable to parse addr:port in relay begin cell. Closing.");
2995 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2996 END_STREAM_REASON_TORPROTOCOL
, NULL
);
3000 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3001 "Missing port in relay begin cell. Closing.");
3002 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3003 END_STREAM_REASON_TORPROTOCOL
, NULL
);
3007 if (or_circ
&& or_circ
->p_conn
&& !options
->AllowSingleHopExits
&&
3008 (or_circ
->is_first_hop
||
3009 (!connection_or_digest_is_known_relay(
3010 or_circ
->p_conn
->identity_digest
) &&
3011 should_refuse_unknown_exits(options
)))) {
3012 /* Don't let clients use us as a single-hop proxy, unless the user
3013 * has explicitly allowed that in the config. It attracts attackers
3014 * and users who'd be better off with, well, single-hop proxies.
3016 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3017 "Attempt by %s to open a stream %s. Closing.",
3018 safe_str(or_circ
->p_conn
->_base
.address
),
3019 or_circ
->is_first_hop
? "on first hop of circuit" :
3020 "from unknown relay");
3021 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3022 or_circ
->is_first_hop
?
3023 END_STREAM_REASON_TORPROTOCOL
:
3024 END_STREAM_REASON_MISC
,
3029 } else if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
3030 if (!directory_permits_begindir_requests(options
) ||
3031 circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
3032 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3033 END_STREAM_REASON_NOTDIRECTORY
, NULL
);
3036 /* Make sure to get the 'real' address of the previous hop: the
3037 * caller might want to know whether his IP address has changed, and
3038 * we might already have corrected _base.addr[ess] for the relay's
3039 * canonical IP address. */
3040 if (or_circ
&& or_circ
->p_conn
)
3041 address
= tor_dup_addr(&or_circ
->p_conn
->real_addr
);
3043 address
= tor_strdup("127.0.0.1");
3044 port
= 1; /* XXXX This value is never actually used anywhere, and there
3045 * isn't "really" a connection here. But we
3046 * need to set it to something nonzero. */
3048 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
3049 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3050 END_STREAM_REASON_INTERNAL
, NULL
);
3054 log_debug(LD_EXIT
,"Creating new exit connection.");
3055 n_stream
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
3057 /* Remember the tunneled request ID in the new edge connection, so that
3058 * we can measure download times. */
3059 TO_CONN(n_stream
)->dirreq_id
= circ
->dirreq_id
;
3061 n_stream
->_base
.purpose
= EXIT_PURPOSE_CONNECT
;
3063 n_stream
->stream_id
= rh
.stream_id
;
3064 n_stream
->_base
.port
= port
;
3065 /* leave n_stream->s at -1, because it's not yet valid */
3066 n_stream
->package_window
= STREAMWINDOW_START
;
3067 n_stream
->deliver_window
= STREAMWINDOW_START
;
3069 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
3070 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3071 log_info(LD_REND
,"begin is for rendezvous. configuring stream.");
3072 n_stream
->_base
.address
= tor_strdup("(rendezvous)");
3073 n_stream
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
3074 n_stream
->rend_data
= rend_data_dup(origin_circ
->rend_data
);
3075 tor_assert(connection_edge_is_rendezvous_stream(n_stream
));
3076 assert_circuit_ok(circ
);
3077 if (rend_service_set_connection_addr_port(n_stream
, origin_circ
) < 0) {
3078 log_info(LD_REND
,"Didn't find rendezvous service (port %d)",
3079 n_stream
->_base
.port
);
3080 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3081 END_STREAM_REASON_EXITPOLICY
,
3082 origin_circ
->cpath
->prev
);
3083 connection_free(TO_CONN(n_stream
));
3087 assert_circuit_ok(circ
);
3088 log_debug(LD_REND
,"Finished assigning addr/port");
3089 n_stream
->cpath_layer
= origin_circ
->cpath
->prev
; /* link it */
3091 /* add it into the linked list of p_streams on this circuit */
3092 n_stream
->next_stream
= origin_circ
->p_streams
;
3093 n_stream
->on_circuit
= circ
;
3094 origin_circ
->p_streams
= n_stream
;
3095 assert_circuit_ok(circ
);
3097 connection_exit_connect(n_stream
);
3101 tor_strlower(address
);
3102 n_stream
->_base
.address
= address
;
3103 n_stream
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
3104 /* default to failed, change in dns_resolve if it turns out not to fail */
3106 if (we_are_hibernating()) {
3107 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3108 END_STREAM_REASON_HIBERNATING
, NULL
);
3109 connection_free(TO_CONN(n_stream
));
3113 n_stream
->on_circuit
= circ
;
3115 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
3116 tor_assert(or_circ
);
3117 if (or_circ
->p_conn
&& !tor_addr_is_null(&or_circ
->p_conn
->real_addr
))
3118 tor_addr_copy(&n_stream
->_base
.addr
, &or_circ
->p_conn
->real_addr
);
3119 return connection_exit_connect_dir(n_stream
);
3122 log_debug(LD_EXIT
,"about to start the dns_resolve().");
3124 /* send it off to the gethostbyname farm */
3125 switch (dns_resolve(n_stream
)) {
3126 case 1: /* resolve worked; now n_stream is attached to circ. */
3127 assert_circuit_ok(circ
);
3128 log_debug(LD_EXIT
,"about to call connection_exit_connect().");
3129 connection_exit_connect(n_stream
);
3131 case -1: /* resolve failed */
3132 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3133 END_STREAM_REASON_RESOLVEFAILED
, NULL
);
3134 /* n_stream got freed. don't touch it. */
3136 case 0: /* resolve added to pending list */
3137 assert_circuit_ok(circ
);
3144 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
3145 * circuit <b>circ</b>;
3146 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
3149 connection_exit_begin_resolve(cell_t
*cell
, or_circuit_t
*circ
)
3151 edge_connection_t
*dummy_conn
;
3154 assert_circuit_ok(TO_CIRCUIT(circ
));
3155 relay_header_unpack(&rh
, cell
->payload
);
3156 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
3159 /* This 'dummy_conn' only exists to remember the stream ID
3160 * associated with the resolve request; and to make the
3161 * implementation of dns.c more uniform. (We really only need to
3162 * remember the circuit, the stream ID, and the hostname to be
3163 * resolved; but if we didn't store them in a connection like this,
3164 * the housekeeping in dns.c would get way more complicated.)
3166 dummy_conn
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
3167 dummy_conn
->stream_id
= rh
.stream_id
;
3168 dummy_conn
->_base
.address
= tor_strndup(
3169 (char*)cell
->payload
+RELAY_HEADER_SIZE
,
3171 dummy_conn
->_base
.port
= 0;
3172 dummy_conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
3173 dummy_conn
->_base
.purpose
= EXIT_PURPOSE_RESOLVE
;
3175 dummy_conn
->on_circuit
= TO_CIRCUIT(circ
);
3177 /* send it off to the gethostbyname farm */
3178 switch (dns_resolve(dummy_conn
)) {
3179 case -1: /* Impossible to resolve; a resolved cell was sent. */
3180 /* Connection freed; don't touch it. */
3182 case 1: /* The result was cached; a resolved cell was sent. */
3183 if (!dummy_conn
->_base
.marked_for_close
)
3184 connection_free(TO_CONN(dummy_conn
));
3186 case 0: /* resolve added to pending list */
3187 assert_circuit_ok(TO_CIRCUIT(circ
));
3193 /** Connect to conn's specified addr and port. If it worked, conn
3194 * has now been added to the connection_array.
3196 * Send back a connected cell. Include the resolved IP of the destination
3197 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
3198 * streams must not reveal what IP they connected to.)
3201 connection_exit_connect(edge_connection_t
*edge_conn
)
3203 const tor_addr_t
*addr
;
3205 connection_t
*conn
= TO_CONN(edge_conn
);
3206 int socket_error
= 0;
3208 if (!connection_edge_is_rendezvous_stream(edge_conn
) &&
3209 router_compare_to_my_exit_policy(edge_conn
)) {
3210 log_info(LD_EXIT
,"%s:%d failed exit policy. Closing.",
3211 escaped_safe_str_client(conn
->address
), conn
->port
);
3212 connection_edge_end(edge_conn
, END_STREAM_REASON_EXITPOLICY
);
3213 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
3214 connection_free(conn
);
3221 log_debug(LD_EXIT
,"about to try connecting");
3222 switch (connection_connect(conn
, conn
->address
, addr
, port
, &socket_error
)) {
3224 int reason
= errno_to_stream_end_reason(socket_error
);
3225 connection_edge_end(edge_conn
, reason
);
3226 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
3227 connection_free(conn
);
3231 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
3233 connection_watch_events(conn
, READ_EVENT
| WRITE_EVENT
);
3234 /* writable indicates finish;
3235 * readable/error indicates broken link in windows-land. */
3237 /* case 1: fall through */
3240 conn
->state
= EXIT_CONN_STATE_OPEN
;
3241 if (connection_get_outbuf_len(conn
)) {
3242 /* in case there are any queued data cells */
3243 log_warn(LD_BUG
,"newly connected conn had data waiting!");
3244 // connection_start_writing(conn);
3246 IF_HAS_NO_BUFFEREVENT(conn
)
3247 connection_watch_events(conn
, READ_EVENT
);
3249 /* also, deliver a 'connected' cell back through the circuit. */
3250 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
3251 /* rendezvous stream */
3252 /* don't send an address back! */
3253 connection_edge_send_command(edge_conn
,
3254 RELAY_COMMAND_CONNECTED
,
3256 } else { /* normal stream */
3257 char connected_payload
[20];
3258 int connected_payload_len
;
3259 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
3260 set_uint32(connected_payload
, tor_addr_to_ipv4n(&conn
->addr
));
3261 connected_payload_len
= 4;
3263 memcpy(connected_payload
, tor_addr_to_in6_addr8(&conn
->addr
), 16);
3264 connected_payload_len
= 16;
3266 set_uint32(connected_payload
+connected_payload_len
,
3267 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
3268 connected_payload_len
+= 4;
3269 connection_edge_send_command(edge_conn
,
3270 RELAY_COMMAND_CONNECTED
,
3271 connected_payload
, connected_payload_len
);
3275 /** Given an exit conn that should attach to us as a directory server, open a
3276 * bridge connection with a linked connection pair, create a new directory
3277 * conn, and join them together. Return 0 on success (or if there was an
3278 * error we could send back an end cell for). Return -(some circuit end
3279 * reason) if the circuit needs to be torn down. Either connects
3280 * <b>exitconn</b>, frees it, or marks it, as appropriate.
3283 connection_exit_connect_dir(edge_connection_t
*exitconn
)
3285 dir_connection_t
*dirconn
= NULL
;
3286 or_circuit_t
*circ
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
3288 log_info(LD_EXIT
, "Opening local connection for anonymized directory exit");
3290 exitconn
->_base
.state
= EXIT_CONN_STATE_OPEN
;
3292 dirconn
= dir_connection_new(tor_addr_family(&exitconn
->_base
.addr
));
3294 tor_addr_copy(&dirconn
->_base
.addr
, &exitconn
->_base
.addr
);
3295 dirconn
->_base
.port
= 0;
3296 dirconn
->_base
.address
= tor_strdup(exitconn
->_base
.address
);
3297 dirconn
->_base
.type
= CONN_TYPE_DIR
;
3298 dirconn
->_base
.purpose
= DIR_PURPOSE_SERVER
;
3299 dirconn
->_base
.state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
3301 /* Note that the new dir conn belongs to the same tunneled request as
3302 * the edge conn, so that we can measure download times. */
3303 TO_CONN(dirconn
)->dirreq_id
= TO_CONN(exitconn
)->dirreq_id
;
3305 connection_link_connections(TO_CONN(dirconn
), TO_CONN(exitconn
));
3307 if (connection_add(TO_CONN(exitconn
))<0) {
3308 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
3309 connection_free(TO_CONN(exitconn
));
3310 connection_free(TO_CONN(dirconn
));
3314 /* link exitconn to circ, now that we know we can use it. */
3315 exitconn
->next_stream
= circ
->n_streams
;
3316 circ
->n_streams
= exitconn
;
3318 if (connection_add(TO_CONN(dirconn
))<0) {
3319 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
3320 connection_close_immediate(TO_CONN(exitconn
));
3321 connection_mark_for_close(TO_CONN(exitconn
));
3322 connection_free(TO_CONN(dirconn
));
3326 connection_start_reading(TO_CONN(dirconn
));
3327 connection_start_reading(TO_CONN(exitconn
));
3329 if (connection_edge_send_command(exitconn
,
3330 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0) {
3331 connection_mark_for_close(TO_CONN(exitconn
));
3332 connection_mark_for_close(TO_CONN(dirconn
));
3339 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
3340 * it is a general stream.
3343 connection_edge_is_rendezvous_stream(edge_connection_t
*conn
)
3346 if (conn
->rend_data
)
3351 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
3352 * to exit from it, or 0 if it probably will not allow it.
3353 * (We might be uncertain if conn's destination address has not yet been
3357 connection_ap_can_use_exit(const entry_connection_t
*conn
, const node_t
*exit
)
3359 const or_options_t
*options
= get_options();
3362 tor_assert(conn
->socks_request
);
3365 /* If a particular exit node has been requested for the new connection,
3366 * make sure the exit node of the existing circuit matches exactly.
3368 if (conn
->chosen_exit_name
) {
3369 const node_t
*chosen_exit
=
3370 node_get_by_nickname(conn
->chosen_exit_name
, 1);
3371 if (!chosen_exit
|| tor_memneq(chosen_exit
->identity
,
3372 exit
->identity
, DIGEST_LEN
)) {
3374 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
3375 // conn->chosen_exit_name, exit->nickname);
3380 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
&&
3381 !conn
->use_begindir
) {
3383 tor_addr_t addr
, *addrp
= NULL
;
3384 addr_policy_result_t r
;
3385 if (tor_inet_aton(conn
->socks_request
->address
, &in
)) {
3386 tor_addr_from_in(&addr
, &in
);
3389 r
= compare_tor_addr_to_node_policy(addrp
, conn
->socks_request
->port
,exit
);
3390 if (r
== ADDR_POLICY_REJECTED
)
3391 return 0; /* We know the address, and the exit policy rejects it. */
3392 if (r
== ADDR_POLICY_PROBABLY_REJECTED
&& !conn
->chosen_exit_name
)
3393 return 0; /* We don't know the addr, but the exit policy rejects most
3394 * addresses with this port. Since the user didn't ask for
3395 * this node, err on the side of caution. */
3396 } else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
3397 /* Don't send DNS requests to non-exit servers by default. */
3398 if (!conn
->chosen_exit_name
&& node_exit_policy_rejects_all(exit
))
3401 if (routerset_contains_node(options
->_ExcludeExitNodesUnion
, exit
)) {
3402 /* Not a suitable exit. Refuse it. */
3409 /** If address is of the form "y.onion" with a well-formed handle y:
3410 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
3412 * If address is of the form "y.exit" and <b>allowdotexit</b> is true:
3413 * Put a NUL after y and return EXIT_HOSTNAME.
3416 * Return NORMAL_HOSTNAME and change nothing.
3419 parse_extended_hostname(char *address
, int allowdotexit
)
3422 char query
[REND_SERVICE_ID_LEN_BASE32
+1];
3424 s
= strrchr(address
,'.');
3426 return NORMAL_HOSTNAME
; /* no dot, thus normal */
3427 if (!strcmp(s
+1,"exit")) {
3429 *s
= 0; /* NUL-terminate it */
3430 return EXIT_HOSTNAME
; /* .exit */
3432 log_warn(LD_APP
, "The \".exit\" notation is disabled in Tor due to "
3433 "security risks. Set AllowDotExit in your torrc to enable "
3435 /* FFFF send a controller event too to notify Vidalia users */
3436 return BAD_HOSTNAME
;
3439 if (strcmp(s
+1,"onion"))
3440 return NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
3442 /* so it is .onion */
3443 *s
= 0; /* NUL-terminate it */
3444 if (strlcpy(query
, address
, REND_SERVICE_ID_LEN_BASE32
+1) >=
3445 REND_SERVICE_ID_LEN_BASE32
+1)
3447 if (rend_valid_service_id(query
)) {
3448 return ONION_HOSTNAME
; /* success */
3451 /* otherwise, return to previous state and return 0 */
3453 return BAD_HOSTNAME
;
3456 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
3457 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
3460 memeq_opt(const char *a
, size_t alen
, const char *b
, size_t blen
)
3464 } else if (b
== NULL
) {
3466 } else if (alen
!= blen
) {
3469 return tor_memeq(a
, b
, alen
);
3474 * Return true iff none of the isolation flags and fields in <b>conn</b>
3475 * should prevent it from being attached to <b>circ</b>.
3478 connection_edge_compatible_with_circuit(const entry_connection_t
*conn
,
3479 const origin_circuit_t
*circ
)
3481 const uint8_t iso
= conn
->isolation_flags
;
3482 const socks_request_t
*sr
= conn
->socks_request
;
3484 /* If circ has never been used for an isolated connection, we can
3485 * totally use it for this one. */
3486 if (!circ
->isolation_values_set
)
3489 /* If circ has been used for connections having more than one value
3490 * for some field f, it will have the corresponding bit set in
3491 * isolation_flags_mixed. If isolation_flags_mixed has any bits
3492 * in common with iso, then conn must be isolated from at least
3493 * one stream that has been attached to circ. */
3494 if ((iso
& circ
->isolation_flags_mixed
) != 0) {
3495 /* For at least one field where conn is isolated, the circuit
3496 * already has mixed streams. */
3500 if (! conn
->original_dest_address
) {
3501 log_warn(LD_BUG
, "Reached connection_edge_compatible_with_circuit without "
3502 "having set conn->original_dest_address");
3503 ((entry_connection_t
*)conn
)->original_dest_address
=
3504 tor_strdup(conn
->socks_request
->address
);
3507 if ((iso
& ISO_STREAM
) &&
3508 (circ
->associated_isolated_stream_global_id
!=
3509 ENTRY_TO_CONN(conn
)->global_identifier
))
3512 if ((iso
& ISO_DESTPORT
) && conn
->socks_request
->port
!= circ
->dest_port
)
3514 if ((iso
& ISO_DESTADDR
) &&
3515 strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
3517 if ((iso
& ISO_SOCKSAUTH
) &&
3518 (! memeq_opt(sr
->username
, sr
->usernamelen
,
3519 circ
->socks_username
, circ
->socks_username_len
) ||
3520 ! memeq_opt(sr
->password
, sr
->passwordlen
,
3521 circ
->socks_password
, circ
->socks_password_len
)))
3523 if ((iso
& ISO_CLIENTPROTO
) &&
3524 (conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
3525 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
3527 if ((iso
& ISO_CLIENTADDR
) &&
3528 !tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
3530 if ((iso
& ISO_SESSIONGRP
) && conn
->session_group
!= circ
->session_group
)
3532 if ((iso
& ISO_NYM_EPOCH
) && conn
->nym_epoch
!= circ
->nym_epoch
)
3539 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
3540 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
3541 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
3542 * a bitfield of isolation flags that we would have to set in
3543 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
3544 * <b>circ</b> has had no streams attached to it.
3547 connection_edge_update_circuit_isolation(const entry_connection_t
*conn
,
3548 origin_circuit_t
*circ
,
3551 const socks_request_t
*sr
= conn
->socks_request
;
3552 if (! conn
->original_dest_address
) {
3553 log_warn(LD_BUG
, "Reached connection_update_circuit_isolation without "
3554 "having set conn->original_dest_address");
3555 ((entry_connection_t
*)conn
)->original_dest_address
=
3556 tor_strdup(conn
->socks_request
->address
);
3559 if (!circ
->isolation_values_set
) {
3562 circ
->associated_isolated_stream_global_id
=
3563 ENTRY_TO_CONN(conn
)->global_identifier
;
3564 circ
->dest_port
= conn
->socks_request
->port
;
3565 circ
->dest_address
= tor_strdup(conn
->original_dest_address
);
3566 circ
->client_proto_type
= conn
->socks_request
->listener_type
;
3567 circ
->client_proto_socksver
= conn
->socks_request
->socks_version
;
3568 tor_addr_copy(&circ
->client_addr
, &ENTRY_TO_CONN(conn
)->addr
);
3569 circ
->session_group
= conn
->session_group
;
3570 circ
->nym_epoch
= conn
->nym_epoch
;
3571 circ
->socks_username
= sr
->username
?
3572 tor_memdup(sr
->username
, sr
->usernamelen
) : NULL
;
3573 circ
->socks_password
= sr
->password
?
3574 tor_memdup(sr
->password
, sr
->passwordlen
) : NULL
;
3575 circ
->socks_username_len
= sr
->usernamelen
;
3576 circ
->socks_password_len
= sr
->passwordlen
;
3578 circ
->isolation_values_set
= 1;
3582 if (conn
->socks_request
->port
!= circ
->dest_port
)
3583 mixed
|= ISO_DESTPORT
;
3584 if (strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
3585 mixed
|= ISO_DESTADDR
;
3586 if (!memeq_opt(sr
->username
, sr
->usernamelen
,
3587 circ
->socks_username
, circ
->socks_username_len
) ||
3588 !memeq_opt(sr
->password
, sr
->passwordlen
,
3589 circ
->socks_password
, circ
->socks_password_len
))
3590 mixed
|= ISO_SOCKSAUTH
;
3591 if ((conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
3592 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
3593 mixed
|= ISO_CLIENTPROTO
;
3594 if (!tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
3595 mixed
|= ISO_CLIENTADDR
;
3596 if (conn
->session_group
!= circ
->session_group
)
3597 mixed
|= ISO_SESSIONGRP
;
3598 if (conn
->nym_epoch
!= circ
->nym_epoch
)
3599 mixed
|= ISO_NYM_EPOCH
;
3604 if ((mixed
& conn
->isolation_flags
) != 0) {
3605 log_warn(LD_BUG
, "Updating a circuit with seemingly incompatible "
3606 "isolation flags.");
3608 circ
->isolation_flags_mixed
|= mixed
;
3614 * Clear the isolation settings on <b>circ</b>.
3616 * This only works on an open circuit that has never had a stream attached to
3617 * it, and whose isolation settings are hypothetical. (We set hypothetical
3618 * isolation settings on circuits as we're launching them, so that we
3619 * know whether they can handle more streams or whether we need to launch
3620 * even more circuits. Once the circuit is open, if it turns out that
3621 * we no longer have any streams to attach to it, we clear the isolation flags
3622 * and data so that other streams can have a chance.)
3625 circuit_clear_isolation(origin_circuit_t
*circ
)
3627 if (circ
->isolation_any_streams_attached
) {
3628 log_warn(LD_BUG
, "Tried to clear the isolation status of a dirty circuit");
3631 if (TO_CIRCUIT(circ
)->state
!= CIRCUIT_STATE_OPEN
) {
3632 log_warn(LD_BUG
, "Tried to clear the isolation status of a non-open "
3637 circ
->isolation_values_set
= 0;
3638 circ
->isolation_flags_mixed
= 0;
3639 circ
->associated_isolated_stream_global_id
= 0;
3640 circ
->client_proto_type
= 0;
3641 circ
->client_proto_socksver
= 0;
3642 circ
->dest_port
= 0;
3643 tor_addr_make_unspec(&circ
->client_addr
);
3644 tor_free(circ
->dest_address
);
3645 circ
->session_group
= -1;
3646 circ
->nym_epoch
= 0;
3647 if (circ
->socks_username
) {
3648 memset(circ
->socks_username
, 0x11, circ
->socks_username_len
);
3649 tor_free(circ
->socks_username
);
3651 if (circ
->socks_password
) {
3652 memset(circ
->socks_password
, 0x05, circ
->socks_password_len
);
3653 tor_free(circ
->socks_password
);
3655 circ
->socks_username_len
= circ
->socks_password_len
= 0;