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"
29 #include "rendclient.h"
30 #include "rendcommon.h"
31 #include "rendservice.h"
34 #include "routerlist.h"
36 #ifdef HAVE_LINUX_TYPES_H
37 #include <linux/types.h>
39 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
40 #include <linux/netfilter_ipv4.h>
41 #define TRANS_NETFILTER
44 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
46 #include <net/pfvar.h>
50 #define SOCKS4_GRANTED 90
51 #define SOCKS4_REJECT 91
53 static int connection_ap_handshake_process_socks(edge_connection_t
*conn
);
54 static int connection_ap_process_natd(edge_connection_t
*conn
);
55 static int connection_exit_connect_dir(edge_connection_t
*exitconn
);
56 static int address_is_in_virtual_range(const char *addr
);
57 static int consider_plaintext_ports(edge_connection_t
*conn
, uint16_t port
);
58 static void clear_trackexithost_mappings(const char *exitname
);
60 /** An AP stream has failed/finished. If it hasn't already sent back
61 * a socks reply, send one now (based on endreason). Also set
62 * has_sent_end to 1, and mark the conn.
65 _connection_mark_unattached_ap(edge_connection_t
*conn
, int endreason
,
66 int line
, const char *file
)
68 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
69 conn
->edge_has_sent_end
= 1; /* no circ yet */
71 if (conn
->_base
.marked_for_close
) {
72 /* This call will warn as appropriate. */
73 _connection_mark_for_close(TO_CONN(conn
), line
, file
);
77 if (!conn
->socks_request
->has_finished
) {
78 if (endreason
& END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
)
80 "stream (marked at %s:%d) sending two socks replies?",
83 if (SOCKS_COMMAND_IS_CONNECT(conn
->socks_request
->command
))
84 connection_ap_handshake_socks_reply(conn
, NULL
, 0, endreason
);
85 else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
86 connection_ap_handshake_socks_resolved(conn
,
87 RESOLVED_TYPE_ERROR_TRANSIENT
,
89 else /* unknown or no handshake at all. send no response. */
90 conn
->socks_request
->has_finished
= 1;
93 _connection_mark_for_close(TO_CONN(conn
), line
, file
);
94 conn
->_base
.hold_open_until_flushed
= 1;
95 conn
->end_reason
= endreason
;
98 /** There was an EOF. Send an end and mark the connection for close.
101 connection_edge_reached_eof(edge_connection_t
*conn
)
103 if (buf_datalen(conn
->_base
.inbuf
) &&
104 connection_state_is_open(TO_CONN(conn
))) {
105 /* it still has stuff to process. don't let it die yet. */
108 log_info(LD_EDGE
,"conn (fd %d) reached eof. Closing.", conn
->_base
.s
);
109 if (!conn
->_base
.marked_for_close
) {
110 /* only mark it if not already marked. it's possible to
111 * get the 'end' right around when the client hangs up on us. */
112 connection_edge_end(conn
, END_STREAM_REASON_DONE
);
113 if (conn
->socks_request
) /* eof, so don't send a socks reply back */
114 conn
->socks_request
->has_finished
= 1;
115 connection_mark_for_close(TO_CONN(conn
));
120 /** Handle new bytes on conn->inbuf based on state:
121 * - If it's waiting for socks info, try to read another step of the
122 * socks handshake out of conn->inbuf.
123 * - If it's waiting for the original destination, fetch it.
124 * - If it's open, then package more relay cells from the stream.
125 * - Else, leave the bytes on inbuf alone for now.
127 * Mark and return -1 if there was an unexpected error with the conn,
131 connection_edge_process_inbuf(edge_connection_t
*conn
, int package_partial
)
135 switch (conn
->_base
.state
) {
136 case AP_CONN_STATE_SOCKS_WAIT
:
137 if (connection_ap_handshake_process_socks(conn
) < 0) {
142 case AP_CONN_STATE_NATD_WAIT
:
143 if (connection_ap_process_natd(conn
) < 0) {
148 case AP_CONN_STATE_OPEN
:
149 case EXIT_CONN_STATE_OPEN
:
150 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
) < 0) {
151 /* (We already sent an end cell if possible) */
152 connection_mark_for_close(TO_CONN(conn
));
156 case EXIT_CONN_STATE_CONNECTING
:
157 case AP_CONN_STATE_RENDDESC_WAIT
:
158 case AP_CONN_STATE_CIRCUIT_WAIT
:
159 case AP_CONN_STATE_CONNECT_WAIT
:
160 case AP_CONN_STATE_RESOLVE_WAIT
:
161 case AP_CONN_STATE_CONTROLLER_WAIT
:
163 "data from edge while in '%s' state. Leaving it on buffer.",
164 conn_state_to_string(conn
->_base
.type
, conn
->_base
.state
));
167 log_warn(LD_BUG
,"Got unexpected state %d. Closing.",conn
->_base
.state
);
168 tor_fragile_assert();
169 connection_edge_end(conn
, END_STREAM_REASON_INTERNAL
);
170 connection_mark_for_close(TO_CONN(conn
));
174 /** This edge needs to be closed, because its circuit has closed.
175 * Mark it for close and return 0.
178 connection_edge_destroy(circid_t circ_id
, edge_connection_t
*conn
)
180 if (!conn
->_base
.marked_for_close
) {
182 "CircID %d: At an edge. Marking connection for close.", circ_id
);
183 if (conn
->_base
.type
== CONN_TYPE_AP
) {
184 connection_mark_unattached_ap(conn
, END_STREAM_REASON_DESTROY
);
185 control_event_stream_bandwidth(conn
);
186 control_event_stream_status(conn
, STREAM_EVENT_CLOSED
,
187 END_STREAM_REASON_DESTROY
);
188 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
190 /* closing the circuit, nothing to send an END to */
191 conn
->edge_has_sent_end
= 1;
192 conn
->end_reason
= END_STREAM_REASON_DESTROY
;
193 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
194 connection_mark_for_close(TO_CONN(conn
));
195 conn
->_base
.hold_open_until_flushed
= 1;
198 conn
->cpath_layer
= NULL
;
199 conn
->on_circuit
= NULL
;
203 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
204 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
205 * is not a client connection, set the relay end cell's reason for closing
206 * as <b>reason</b> */
208 relay_send_end_cell_from_edge(streamid_t stream_id
, circuit_t
*circ
,
209 uint8_t reason
, crypt_path_t
*cpath_layer
)
213 if (CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
214 /* Never send the server an informative reason code; it doesn't need to
215 * know why the client stream is failing. */
216 reason
= END_STREAM_REASON_MISC
;
219 payload
[0] = (char) reason
;
221 return relay_send_command_from_edge(stream_id
, circ
, RELAY_COMMAND_END
,
222 payload
, 1, cpath_layer
);
225 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
226 * remember that we've done so. If this is not a client connection, set the
227 * relay end cell's reason for closing as <b>reason</b>.
229 * Return -1 if this function has already been called on this conn,
233 connection_edge_end(edge_connection_t
*conn
, uint8_t reason
)
235 char payload
[RELAY_PAYLOAD_SIZE
];
236 size_t payload_len
=1;
238 uint8_t control_reason
= reason
;
240 if (conn
->edge_has_sent_end
) {
241 log_warn(LD_BUG
,"(Harmless.) Calling connection_edge_end (reason %d) "
242 "on an already ended stream?", reason
);
243 tor_fragile_assert();
247 if (conn
->_base
.marked_for_close
) {
249 "called on conn that's already marked for close at %s:%d.",
250 conn
->_base
.marked_for_close_file
, conn
->_base
.marked_for_close
);
254 circ
= circuit_get_by_edge_conn(conn
);
255 if (circ
&& CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
256 /* If this is a client circuit, don't send the server an informative
257 * reason code; it doesn't need to know why the client stream is
259 reason
= END_STREAM_REASON_MISC
;
262 payload
[0] = (char)reason
;
263 if (reason
== END_STREAM_REASON_EXITPOLICY
&&
264 !connection_edge_is_rendezvous_stream(conn
)) {
266 if (tor_addr_family(&conn
->_base
.addr
) == AF_INET
) {
267 set_uint32(payload
+1, tor_addr_to_ipv4n(&conn
->_base
.addr
));
270 memcpy(payload
+1, tor_addr_to_in6_addr8(&conn
->_base
.addr
), 16);
273 set_uint32(payload
+1+addrlen
, htonl(dns_clip_ttl(conn
->address_ttl
)));
274 payload_len
+= 4+addrlen
;
277 if (circ
&& !circ
->marked_for_close
) {
278 log_debug(LD_EDGE
,"Sending end on conn (fd %d).",conn
->_base
.s
);
279 connection_edge_send_command(conn
, RELAY_COMMAND_END
,
280 payload
, payload_len
);
282 log_debug(LD_EDGE
,"No circ to send end on conn (fd %d).",
286 conn
->edge_has_sent_end
= 1;
287 conn
->end_reason
= control_reason
;
291 /** An error has just occurred on an operation on an edge connection
292 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
293 * appropriate relay end cell to the other end of the connection's circuit.
296 connection_edge_end_errno(edge_connection_t
*conn
)
300 reason
= errno_to_stream_end_reason(tor_socket_errno(conn
->_base
.s
));
301 return connection_edge_end(conn
, reason
);
304 /** Connection <b>conn</b> has finished writing and has no bytes left on
307 * If it's in state 'open', stop writing, consider responding with a
308 * sendme, and return.
309 * Otherwise, stop writing and return.
311 * If <b>conn</b> is broken, mark it for close and return -1, else
315 connection_edge_finished_flushing(edge_connection_t
*conn
)
319 switch (conn
->_base
.state
) {
320 case AP_CONN_STATE_OPEN
:
321 case EXIT_CONN_STATE_OPEN
:
322 connection_stop_writing(TO_CONN(conn
));
323 connection_edge_consider_sending_sendme(conn
);
325 case AP_CONN_STATE_SOCKS_WAIT
:
326 case AP_CONN_STATE_NATD_WAIT
:
327 case AP_CONN_STATE_RENDDESC_WAIT
:
328 case AP_CONN_STATE_CIRCUIT_WAIT
:
329 case AP_CONN_STATE_CONNECT_WAIT
:
330 case AP_CONN_STATE_CONTROLLER_WAIT
:
331 connection_stop_writing(TO_CONN(conn
));
334 log_warn(LD_BUG
, "Called in unexpected state %d.",conn
->_base
.state
);
335 tor_fragile_assert();
341 /** Connected handler for exit connections: start writing pending
342 * data, deliver 'CONNECTED' relay cells as appropriate, and check
343 * any pending data that may have been received. */
345 connection_edge_finished_connecting(edge_connection_t
*edge_conn
)
349 tor_assert(edge_conn
);
350 tor_assert(edge_conn
->_base
.type
== CONN_TYPE_EXIT
);
351 conn
= TO_CONN(edge_conn
);
352 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
354 log_info(LD_EXIT
,"Exit connection to %s:%u (%s) established.",
355 escaped_safe_str(conn
->address
), conn
->port
,
356 safe_str(fmt_addr(&conn
->addr
)));
358 rep_hist_note_exit_stream_opened(conn
->port
);
360 conn
->state
= EXIT_CONN_STATE_OPEN
;
361 connection_watch_events(conn
, READ_EVENT
); /* stop writing, keep reading */
362 if (connection_wants_to_flush(conn
)) /* in case there are any queued relay
364 connection_start_writing(conn
);
365 /* deliver a 'connected' relay cell back through the circuit. */
366 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
367 if (connection_edge_send_command(edge_conn
,
368 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0)
369 return 0; /* circuit is closed, don't continue */
371 char connected_payload
[20];
372 int connected_payload_len
;
373 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
374 set_uint32(connected_payload
, tor_addr_to_ipv4n(&conn
->addr
));
375 set_uint32(connected_payload
+4,
376 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
377 connected_payload_len
= 8;
379 memcpy(connected_payload
, tor_addr_to_in6_addr8(&conn
->addr
), 16);
380 set_uint32(connected_payload
+16,
381 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
382 connected_payload_len
= 20;
384 if (connection_edge_send_command(edge_conn
,
385 RELAY_COMMAND_CONNECTED
,
386 connected_payload
, connected_payload_len
) < 0)
387 return 0; /* circuit is closed, don't continue */
389 tor_assert(edge_conn
->package_window
> 0);
390 /* in case the server has written anything */
391 return connection_edge_process_inbuf(edge_conn
, 1);
394 /** Define a schedule for how long to wait between retrying
395 * application connections. Rather than waiting a fixed amount of
396 * time between each retry, we wait 10 seconds each for the first
397 * two tries, and 15 seconds for each retry after
398 * that. Hopefully this will improve the expected user experience. */
400 compute_retry_timeout(edge_connection_t
*conn
)
402 int timeout
= get_options()->CircuitStreamTimeout
;
403 if (timeout
) /* if our config options override the default, use them */
405 if (conn
->num_socks_retries
< 2) /* try 0 and try 1 */
410 /** Find all general-purpose AP streams waiting for a response that sent their
411 * begin/resolve cell too long ago. Detach from their current circuit, and
412 * mark their current circuit as unsuitable for new streams. Then call
413 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
414 * available) or launch a new one.
416 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
420 connection_ap_expire_beginning(void)
422 edge_connection_t
*conn
;
424 time_t now
= time(NULL
);
425 or_options_t
*options
= get_options();
428 int seconds_idle
, seconds_since_born
;
429 smartlist_t
*conns
= get_connection_array();
431 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, c
) {
432 if (c
->type
!= CONN_TYPE_AP
|| c
->marked_for_close
)
434 conn
= TO_EDGE_CONN(c
);
435 /* if it's an internal linked connection, don't yell its status. */
436 severity
= (tor_addr_is_null(&conn
->_base
.addr
) && !conn
->_base
.port
)
437 ? LOG_INFO
: LOG_NOTICE
;
438 seconds_idle
= (int)( now
- conn
->_base
.timestamp_lastread
);
439 seconds_since_born
= (int)( now
- conn
->_base
.timestamp_created
);
441 if (conn
->_base
.state
== AP_CONN_STATE_OPEN
)
444 /* We already consider SocksTimeout in
445 * connection_ap_handshake_attach_circuit(), but we need to consider
446 * it here too because controllers that put streams in controller_wait
447 * state never ask Tor to attach the circuit. */
448 if (AP_CONN_STATE_IS_UNATTACHED(conn
->_base
.state
)) {
449 if (seconds_since_born
>= options
->SocksTimeout
) {
450 log_fn(severity
, LD_APP
,
451 "Tried for %d seconds to get a connection to %s:%d. "
454 safe_str_client(conn
->socks_request
->address
),
455 conn
->socks_request
->port
,
456 conn_state_to_string(CONN_TYPE_AP
, conn
->_base
.state
));
457 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
462 /* We're in state connect_wait or resolve_wait now -- waiting for a
463 * reply to our relay cell. See if we want to retry/give up. */
465 cutoff
= compute_retry_timeout(conn
);
466 if (seconds_idle
< cutoff
)
468 circ
= circuit_get_by_edge_conn(conn
);
469 if (!circ
) { /* it's vanished? */
470 log_info(LD_APP
,"Conn is waiting (address %s), but lost its circ.",
471 safe_str_client(conn
->socks_request
->address
));
472 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
475 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
476 if (seconds_idle
>= options
->SocksTimeout
) {
477 log_fn(severity
, LD_REND
,
478 "Rend stream is %d seconds late. Giving up on address"
481 safe_str_client(conn
->socks_request
->address
));
482 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
483 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
487 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
488 log_fn(cutoff
< 15 ? LOG_INFO
: severity
, LD_APP
,
489 "We tried for %d seconds to connect to '%s' using exit '%s'."
490 " Retrying on a new circuit.",
492 safe_str_client(conn
->socks_request
->address
),
494 conn
->cpath_layer
->extend_info
->nickname
: "*unnamed*");
495 /* send an end down the circuit */
496 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
497 /* un-mark it as ending, since we're going to reuse it */
498 conn
->edge_has_sent_end
= 0;
499 conn
->end_reason
= 0;
500 /* kludge to make us not try this circuit again, yet to allow
501 * current streams on it to survive if they can: make it
502 * unattractive to use for new streams */
503 tor_assert(circ
->timestamp_dirty
);
504 circ
->timestamp_dirty
-= options
->MaxCircuitDirtiness
;
505 /* give our stream another 'cutoff' seconds to try */
506 conn
->_base
.timestamp_lastread
+= cutoff
;
507 if (conn
->num_socks_retries
< 250) /* avoid overflow */
508 conn
->num_socks_retries
++;
509 /* move it back into 'pending' state, and try to attach. */
510 if (connection_ap_detach_retriable(conn
, TO_ORIGIN_CIRCUIT(circ
),
511 END_STREAM_REASON_TIMEOUT
)<0) {
512 if (!conn
->_base
.marked_for_close
)
513 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
515 } SMARTLIST_FOREACH_END(conn
);
518 /** Tell any AP streams that are waiting for a new circuit to try again,
519 * either attaching to an available circ or launching a new one.
522 connection_ap_attach_pending(void)
524 edge_connection_t
*edge_conn
;
525 smartlist_t
*conns
= get_connection_array();
526 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
528 if (conn
->marked_for_close
||
529 conn
->type
!= CONN_TYPE_AP
||
530 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
532 edge_conn
= TO_EDGE_CONN(conn
);
533 if (connection_ap_handshake_attach_circuit(edge_conn
) < 0) {
534 if (!edge_conn
->_base
.marked_for_close
)
535 connection_mark_unattached_ap(edge_conn
,
536 END_STREAM_REASON_CANT_ATTACH
);
541 /** Tell any AP streams that are waiting for a one-hop tunnel to
542 * <b>failed_digest</b> that they are going to fail. */
543 /* XXX022 We should get rid of this function, and instead attach
544 * one-hop streams to circ->p_streams so they get marked in
545 * circuit_mark_for_close like normal p_streams. */
547 connection_ap_fail_onehop(const char *failed_digest
,
548 cpath_build_state_t
*build_state
)
550 edge_connection_t
*edge_conn
;
551 char digest
[DIGEST_LEN
];
552 smartlist_t
*conns
= get_connection_array();
553 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
554 if (conn
->marked_for_close
||
555 conn
->type
!= CONN_TYPE_AP
||
556 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
558 edge_conn
= TO_EDGE_CONN(conn
);
559 if (!edge_conn
->want_onehop
)
561 if (hexdigest_to_digest(edge_conn
->chosen_exit_name
, digest
) < 0 ||
562 memcmp(digest
, failed_digest
, DIGEST_LEN
))
564 if (tor_digest_is_zero(digest
)) {
565 /* we don't know the digest; have to compare addr:port */
567 if (!build_state
|| !build_state
->chosen_exit
||
568 !edge_conn
->socks_request
|| !edge_conn
->socks_request
->address
)
570 if (tor_addr_from_str(&addr
, edge_conn
->socks_request
->address
)<0 ||
571 !tor_addr_eq(&build_state
->chosen_exit
->addr
, &addr
) ||
572 build_state
->chosen_exit
->port
!= edge_conn
->socks_request
->port
)
575 log_info(LD_APP
, "Closing one-hop stream to '%s/%s' because the OR conn "
576 "just failed.", edge_conn
->chosen_exit_name
,
577 edge_conn
->socks_request
->address
);
578 connection_mark_unattached_ap(edge_conn
, END_STREAM_REASON_TIMEOUT
);
579 } SMARTLIST_FOREACH_END(conn
);
582 /** A circuit failed to finish on its last hop <b>info</b>. If there
583 * are any streams waiting with this exit node in mind, but they
584 * don't absolutely require it, make them give up on it.
587 circuit_discard_optional_exit_enclaves(extend_info_t
*info
)
589 edge_connection_t
*edge_conn
;
590 routerinfo_t
*r1
, *r2
;
592 smartlist_t
*conns
= get_connection_array();
593 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
594 if (conn
->marked_for_close
||
595 conn
->type
!= CONN_TYPE_AP
||
596 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
598 edge_conn
= TO_EDGE_CONN(conn
);
599 if (!edge_conn
->chosen_exit_optional
&&
600 !edge_conn
->chosen_exit_retries
)
602 r1
= router_get_by_nickname(edge_conn
->chosen_exit_name
, 0);
603 r2
= router_get_by_digest(info
->identity_digest
);
604 if (!r1
|| !r2
|| r1
!= r2
)
606 tor_assert(edge_conn
->socks_request
);
607 if (edge_conn
->chosen_exit_optional
) {
608 log_info(LD_APP
, "Giving up on enclave exit '%s' for destination %s.",
609 safe_str_client(edge_conn
->chosen_exit_name
),
610 escaped_safe_str_client(edge_conn
->socks_request
->address
));
611 edge_conn
->chosen_exit_optional
= 0;
612 tor_free(edge_conn
->chosen_exit_name
); /* clears it */
613 /* if this port is dangerous, warn or reject it now that we don't
614 * think it'll be using an enclave. */
615 consider_plaintext_ports(edge_conn
, edge_conn
->socks_request
->port
);
617 if (edge_conn
->chosen_exit_retries
) {
618 if (--edge_conn
->chosen_exit_retries
== 0) { /* give up! */
619 clear_trackexithost_mappings(edge_conn
->chosen_exit_name
);
620 tor_free(edge_conn
->chosen_exit_name
); /* clears it */
621 /* if this port is dangerous, warn or reject it now that we don't
622 * think it'll be using an enclave. */
623 consider_plaintext_ports(edge_conn
, edge_conn
->socks_request
->port
);
626 } SMARTLIST_FOREACH_END(conn
);
629 /** The AP connection <b>conn</b> has just failed while attaching or
630 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
631 * might work. Detach the circuit, and either reattach it, launch a
632 * new circuit, tell the controller, or give up as a appropriate.
634 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
637 connection_ap_detach_retriable(edge_connection_t
*conn
, origin_circuit_t
*circ
,
640 control_event_stream_status(conn
, STREAM_EVENT_FAILED_RETRIABLE
, reason
);
641 conn
->_base
.timestamp_lastread
= time(NULL
);
642 if (!get_options()->LeaveStreamsUnattached
|| conn
->use_begindir
) {
643 /* If we're attaching streams ourself, or if this connection is
644 * a tunneled directory connection, then just attach it. */
645 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
646 circuit_detach_stream(TO_CIRCUIT(circ
),conn
);
647 return connection_ap_handshake_attach_circuit(conn
);
649 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
650 circuit_detach_stream(TO_CIRCUIT(circ
),conn
);
655 /** A client-side struct to remember requests to rewrite addresses
656 * to new addresses. These structs are stored in the hash table
657 * "addressmap" below.
659 * There are 5 ways to set an address mapping:
660 * - A MapAddress command from the controller [permanent]
661 * - An AddressMap directive in the torrc [permanent]
662 * - When a TrackHostExits torrc directive is triggered [temporary]
663 * - When a DNS resolve succeeds [temporary]
664 * - When a DNS resolve fails [temporary]
666 * When an addressmap request is made but one is already registered,
667 * the new one is replaced only if the currently registered one has
668 * no "new_address" (that is, it's in the process of DNS resolve),
669 * or if the new one is permanent (expires==0 or 1).
671 * (We overload the 'expires' field, using "0" for mappings set via
672 * the configuration file, "1" for mappings set from the control
673 * interface, and other values for DNS and TrackHostExit mappings that can
679 addressmap_entry_source_t source
:3;
680 short num_resolve_failures
;
681 } addressmap_entry_t
;
683 /** Entry for mapping addresses to which virtual address we mapped them to. */
686 char *hostname_address
;
687 } virtaddress_entry_t
;
689 /** A hash table to store client-side address rewrite instructions. */
690 static strmap_t
*addressmap
=NULL
;
692 * Table mapping addresses to which virtual address, if any, we
695 * We maintain the following invariant: if [A,B] is in
696 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
697 * must be in addressmap. We do not require that the converse hold:
698 * if it fails, then we could end up mapping two virtual addresses to
699 * the same address, which is no disaster.
701 static strmap_t
*virtaddress_reversemap
=NULL
;
703 /** Initialize addressmap. */
705 addressmap_init(void)
707 addressmap
= strmap_new();
708 virtaddress_reversemap
= strmap_new();
711 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
713 addressmap_ent_free(void *_ent
)
715 addressmap_entry_t
*ent
;
720 tor_free(ent
->new_address
);
724 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
726 addressmap_virtaddress_ent_free(void *_ent
)
728 virtaddress_entry_t
*ent
;
733 tor_free(ent
->ipv4_address
);
734 tor_free(ent
->hostname_address
);
738 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
740 addressmap_virtaddress_remove(const char *address
, addressmap_entry_t
*ent
)
742 if (ent
&& ent
->new_address
&&
743 address_is_in_virtual_range(ent
->new_address
)) {
744 virtaddress_entry_t
*ve
=
745 strmap_get(virtaddress_reversemap
, ent
->new_address
);
746 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
748 if (!strcmp(address
, ve
->ipv4_address
))
749 tor_free(ve
->ipv4_address
);
750 if (!strcmp(address
, ve
->hostname_address
))
751 tor_free(ve
->hostname_address
);
752 if (!ve
->ipv4_address
&& !ve
->hostname_address
) {
754 strmap_remove(virtaddress_reversemap
, ent
->new_address
);
760 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
761 * client address maps. */
763 addressmap_ent_remove(const char *address
, addressmap_entry_t
*ent
)
765 addressmap_virtaddress_remove(address
, ent
);
766 addressmap_ent_free(ent
);
769 /** Unregister all TrackHostExits mappings from any address to
770 * *.exitname.exit. */
772 clear_trackexithost_mappings(const char *exitname
)
776 if (!addressmap
|| !exitname
)
778 suffix_len
= strlen(exitname
) + 16;
779 suffix
= tor_malloc(suffix_len
);
780 tor_snprintf(suffix
, suffix_len
, ".%s.exit", exitname
);
781 tor_strlower(suffix
);
783 STRMAP_FOREACH_MODIFY(addressmap
, address
, addressmap_entry_t
*, ent
) {
784 if (ent
->source
== ADDRMAPSRC_TRACKEXIT
&& !strcmpend(address
, suffix
)) {
785 addressmap_ent_remove(address
, ent
);
786 MAP_DEL_CURRENT(address
);
788 } STRMAP_FOREACH_END
;
793 /** Remove all entries from the addressmap that were set via the
794 * configuration file or the command line. */
796 addressmap_clear_configured(void)
798 addressmap_get_mappings(NULL
, 0, 0, 0);
801 /** Remove all entries from the addressmap that are set to expire, ever. */
803 addressmap_clear_transient(void)
805 addressmap_get_mappings(NULL
, 2, TIME_MAX
, 0);
808 /** Clean out entries from the addressmap cache that were
809 * added long enough ago that they are no longer valid.
812 addressmap_clean(time_t now
)
814 addressmap_get_mappings(NULL
, 2, now
, 0);
817 /** Free all the elements in the addressmap, and free the addressmap
820 addressmap_free_all(void)
822 strmap_free(addressmap
, addressmap_ent_free
);
825 strmap_free(virtaddress_reversemap
, addressmap_virtaddress_ent_free
);
826 virtaddress_reversemap
= NULL
;
829 /** Look at address, and rewrite it until it doesn't want any
830 * more rewrites; but don't get into an infinite loop.
831 * Don't write more than maxlen chars into address. Return true if the
832 * address changed; false otherwise. Set *<b>expires_out</b> to the
833 * expiry time of the result, or to <b>time_max</b> if the result does
837 addressmap_rewrite(char *address
, size_t maxlen
, time_t *expires_out
)
839 addressmap_entry_t
*ent
;
842 time_t expires
= TIME_MAX
;
844 for (rewrites
= 0; rewrites
< 16; rewrites
++) {
845 ent
= strmap_get(addressmap
, address
);
847 if (!ent
|| !ent
->new_address
) {
849 *expires_out
= expires
;
850 return (rewrites
> 0); /* done, no rewrite needed */
853 cp
= tor_strdup(escaped_safe_str_client(ent
->new_address
));
854 log_info(LD_APP
, "Addressmap: rewriting %s to %s",
855 escaped_safe_str_client(address
), cp
);
856 if (ent
->expires
> 1 && ent
->expires
< expires
)
857 expires
= ent
->expires
;
859 strlcpy(address
, ent
->new_address
, maxlen
);
862 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
863 escaped_safe_str_client(address
));
864 /* it's fine to rewrite a rewrite, but don't loop forever */
866 *expires_out
= TIME_MAX
;
870 /** If we have a cached reverse DNS entry for the address stored in the
871 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
872 * rewrite to the cached value and return 1. Otherwise return 0. Set
873 * *<b>expires_out</b> to the expiry time of the result, or to <b>time_max</b>
874 * if the result does not expire. */
876 addressmap_rewrite_reverse(char *address
, size_t maxlen
, time_t *expires_out
)
878 size_t len
= maxlen
+ 16;
879 char *s
= tor_malloc(len
), *cp
;
880 addressmap_entry_t
*ent
;
882 tor_snprintf(s
, len
, "REVERSE[%s]", address
);
883 ent
= strmap_get(addressmap
, s
);
885 cp
= tor_strdup(escaped_safe_str_client(ent
->new_address
));
886 log_info(LD_APP
, "Rewrote reverse lookup %s -> %s",
887 escaped_safe_str_client(s
), cp
);
889 strlcpy(address
, ent
->new_address
, maxlen
);
894 *expires_out
= (ent
&& ent
->expires
> 1) ? ent
->expires
: TIME_MAX
;
900 /** Return 1 if <b>address</b> is already registered, else return 0. If address
901 * is already registered, and <b>update_expires</b> is non-zero, then update
902 * the expiry time on the mapping with update_expires if it is a
903 * mapping created by TrackHostExits. */
905 addressmap_have_mapping(const char *address
, int update_expiry
)
907 addressmap_entry_t
*ent
;
908 if (!(ent
=strmap_get_lc(addressmap
, address
)))
910 if (update_expiry
&& ent
->source
==ADDRMAPSRC_TRACKEXIT
)
911 ent
->expires
=time(NULL
) + update_expiry
;
915 /** Register a request to map <b>address</b> to <b>new_address</b>,
916 * which will expire on <b>expires</b> (or 0 if never expires from
917 * config file, 1 if never expires from controller, 2 if never expires
918 * (virtual address mapping) from the controller.)
920 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
921 * free as appropriate. We will leave address alone.
923 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
924 * any mappings that exist from <b>address</b>.
927 addressmap_register(const char *address
, char *new_address
, time_t expires
,
928 addressmap_entry_source_t source
)
930 addressmap_entry_t
*ent
;
932 ent
= strmap_get(addressmap
, address
);
933 if (!new_address
|| !strcasecmp(address
,new_address
)) {
934 /* Remove the mapping, if any. */
935 tor_free(new_address
);
937 addressmap_ent_remove(address
,ent
);
938 strmap_remove(addressmap
, address
);
942 if (!ent
) { /* make a new one and register it */
943 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
944 strmap_set(addressmap
, address
, ent
);
945 } else if (ent
->new_address
) { /* we need to clean up the old mapping. */
947 log_info(LD_APP
,"Temporary addressmap ('%s' to '%s') not performed, "
948 "since it's already mapped to '%s'",
949 safe_str_client(address
),
950 safe_str_client(new_address
),
951 safe_str_client(ent
->new_address
));
952 tor_free(new_address
);
955 if (address_is_in_virtual_range(ent
->new_address
) &&
957 /* XXX This isn't the perfect test; we want to avoid removing
958 * mappings set from the control interface _as virtual mapping */
959 addressmap_virtaddress_remove(address
, ent
);
961 tor_free(ent
->new_address
);
962 } /* else { we have an in-progress resolve with no mapping. } */
964 ent
->new_address
= new_address
;
965 ent
->expires
= expires
==2 ? 1 : expires
;
966 ent
->num_resolve_failures
= 0;
967 ent
->source
= source
;
969 log_info(LD_CONFIG
, "Addressmap: (re)mapped '%s' to '%s'",
970 safe_str_client(address
),
971 safe_str_client(ent
->new_address
));
972 control_event_address_mapped(address
, ent
->new_address
, expires
, NULL
);
975 /** An attempt to resolve <b>address</b> failed at some OR.
976 * Increment the number of resolve failures we have on record
977 * for it, and then return that number.
980 client_dns_incr_failures(const char *address
)
982 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
984 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
985 ent
->expires
= time(NULL
) + MAX_DNS_ENTRY_AGE
;
986 strmap_set(addressmap
,address
,ent
);
988 if (ent
->num_resolve_failures
< SHORT_MAX
)
989 ++ent
->num_resolve_failures
; /* don't overflow */
990 log_info(LD_APP
, "Address %s now has %d resolve failures.",
991 safe_str_client(address
),
992 ent
->num_resolve_failures
);
993 return ent
->num_resolve_failures
;
996 /** If <b>address</b> is in the client DNS addressmap, reset
997 * the number of resolve failures we have on record for it.
998 * This is used when we fail a stream because it won't resolve:
999 * otherwise future attempts on that address will only try once.
1002 client_dns_clear_failures(const char *address
)
1004 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
1006 ent
->num_resolve_failures
= 0;
1009 /** Record the fact that <b>address</b> resolved to <b>name</b>.
1010 * We can now use this in subsequent streams via addressmap_rewrite()
1011 * so we can more correctly choose an exit that will allow <b>address</b>.
1013 * If <b>exitname</b> is defined, then append the addresses with
1014 * ".exitname.exit" before registering the mapping.
1016 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1017 * <b>ttl</b>seconds; otherwise, we use the default.
1020 client_dns_set_addressmap_impl(const char *address
, const char *name
,
1021 const char *exitname
,
1024 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
1025 char extendedaddress
[MAX_SOCKS_ADDR_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
1026 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
1027 char extendedval
[INET_NTOA_BUF_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
1029 tor_assert(address
);
1033 ttl
= DEFAULT_DNS_TTL
;
1035 ttl
= dns_clip_ttl(ttl
);
1038 /* XXXX fails to ever get attempts to get an exit address of
1039 * google.com.digest[=~]nickname.exit; we need a syntax for this that
1040 * won't make strict RFC952-compliant applications (like us) barf. */
1041 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
1042 "%s.%s.exit", address
, exitname
);
1043 tor_snprintf(extendedval
, sizeof(extendedval
),
1044 "%s.%s.exit", name
, exitname
);
1046 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
1048 tor_snprintf(extendedval
, sizeof(extendedval
),
1051 addressmap_register(extendedaddress
, tor_strdup(extendedval
),
1052 time(NULL
) + ttl
, ADDRMAPSRC_DNS
);
1055 /** Record the fact that <b>address</b> resolved to <b>val</b>.
1056 * We can now use this in subsequent streams via addressmap_rewrite()
1057 * so we can more correctly choose an exit that will allow <b>address</b>.
1059 * If <b>exitname</b> is defined, then append the addresses with
1060 * ".exitname.exit" before registering the mapping.
1062 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1063 * <b>ttl</b>seconds; otherwise, we use the default.
1066 client_dns_set_addressmap(const char *address
, uint32_t val
,
1067 const char *exitname
,
1071 char valbuf
[INET_NTOA_BUF_LEN
];
1073 tor_assert(address
);
1075 if (tor_inet_aton(address
, &in
))
1076 return; /* If address was an IP address already, don't add a mapping. */
1077 in
.s_addr
= htonl(val
);
1078 tor_inet_ntoa(&in
,valbuf
,sizeof(valbuf
));
1080 client_dns_set_addressmap_impl(address
, valbuf
, exitname
, ttl
);
1083 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
1084 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
1086 * If <b>exitname</b> is defined, then append the addresses with
1087 * ".exitname.exit" before registering the mapping.
1089 * If <b>ttl</b> is nonnegative, the mapping will be valid for
1090 * <b>ttl</b>seconds; otherwise, we use the default.
1093 client_dns_set_reverse_addressmap(const char *address
, const char *v
,
1094 const char *exitname
,
1097 size_t len
= strlen(address
) + 16;
1098 char *s
= tor_malloc(len
);
1099 tor_snprintf(s
, len
, "REVERSE[%s]", address
);
1100 client_dns_set_addressmap_impl(s
, v
, exitname
, ttl
);
1104 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
1105 * These addresses should map to localhost, so even if the
1106 * application accidentally tried to connect to them directly (not
1107 * via Tor), it wouldn't get too far astray.
1109 * These options are configured by parse_virtual_addr_network().
1111 /** Which network should we use for virtual IPv4 addresses? Only the first
1112 * bits of this value are fixed. */
1113 static uint32_t virtual_addr_network
= 0x7fc00000u
;
1114 /** How many bits of <b>virtual_addr_network</b> are fixed? */
1115 static maskbits_t virtual_addr_netmask_bits
= 10;
1116 /** What's the next virtual address we will hand out? */
1117 static uint32_t next_virtual_addr
= 0x7fc00000u
;
1119 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
1120 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
1121 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
1122 * string and return -1 on failure. If validate_only is false, sets the
1123 * actual virtual address range to the parsed value. */
1125 parse_virtual_addr_network(const char *val
, int validate_only
,
1129 uint16_t port_min
, port_max
;
1132 if (parse_addr_and_port_range(val
, &addr
, &bits
, &port_min
, &port_max
)) {
1133 if (msg
) *msg
= tor_strdup("Error parsing VirtualAddressNetwork");
1137 if (port_min
!= 1 || port_max
!= 65535) {
1138 if (msg
) *msg
= tor_strdup("Can't specify ports on VirtualAddressNetwork");
1143 if (msg
) *msg
= tor_strdup("VirtualAddressNetwork expects a /16 "
1144 "network or larger");
1151 virtual_addr_network
= (uint32_t)( addr
& (0xfffffffful
<< (32-bits
)) );
1152 virtual_addr_netmask_bits
= bits
;
1154 if (addr_mask_cmp_bits(next_virtual_addr
, addr
, bits
))
1155 next_virtual_addr
= addr
;
1161 * Return true iff <b>addr</b> is likely to have been returned by
1162 * client_dns_get_unused_address.
1165 address_is_in_virtual_range(const char *address
)
1168 tor_assert(address
);
1169 if (!strcasecmpend(address
, ".virtual")) {
1171 } else if (tor_inet_aton(address
, &in
)) {
1172 uint32_t addr
= ntohl(in
.s_addr
);
1173 if (!addr_mask_cmp_bits(addr
, virtual_addr_network
,
1174 virtual_addr_netmask_bits
))
1180 /** Increment the value of next_virtual_addr; reset it to the start of the
1181 * virtual address range if it wraps around.
1184 increment_virtual_addr(void)
1186 ++next_virtual_addr
;
1187 if (addr_mask_cmp_bits(next_virtual_addr
, virtual_addr_network
,
1188 virtual_addr_netmask_bits
))
1189 next_virtual_addr
= virtual_addr_network
;
1192 /** Return a newly allocated string holding an address of <b>type</b>
1193 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
1194 * and that is very unlikely to be the address of any real host.
1196 * May return NULL if we have run out of virtual addresses.
1199 addressmap_get_virtual_address(int type
)
1203 tor_assert(addressmap
);
1205 if (type
== RESOLVED_TYPE_HOSTNAME
) {
1208 crypto_rand(rand
, sizeof(rand
));
1209 base32_encode(buf
,sizeof(buf
),rand
,sizeof(rand
));
1210 strlcat(buf
, ".virtual", sizeof(buf
));
1211 } while (strmap_get(addressmap
, buf
));
1212 return tor_strdup(buf
);
1213 } else if (type
== RESOLVED_TYPE_IPV4
) {
1214 // This is an imperfect estimate of how many addresses are available, but
1216 uint32_t available
= 1u << (32-virtual_addr_netmask_bits
);
1218 /* Don't hand out any .0 or .255 address. */
1219 while ((next_virtual_addr
& 0xff) == 0 ||
1220 (next_virtual_addr
& 0xff) == 0xff) {
1221 increment_virtual_addr();
1222 if (! --available
) {
1223 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
1227 in
.s_addr
= htonl(next_virtual_addr
);
1228 tor_inet_ntoa(&in
, buf
, sizeof(buf
));
1229 if (!strmap_get(addressmap
, buf
)) {
1230 increment_virtual_addr();
1234 increment_virtual_addr();
1236 // log_info(LD_CONFIG, "%d addrs available", (int)available);
1238 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
1242 return tor_strdup(buf
);
1244 log_warn(LD_BUG
, "Called with unsupported address type (%d)", type
);
1249 /** A controller has requested that we map some address of type
1250 * <b>type</b> to the address <b>new_address</b>. Choose an address
1251 * that is unlikely to be used, and map it, and return it in a newly
1252 * allocated string. If another address of the same type is already
1253 * mapped to <b>new_address</b>, try to return a copy of that address.
1255 * The string in <b>new_address</b> may be freed or inserted into a map
1256 * as appropriate. May return NULL if are out of virtual addresses.
1259 addressmap_register_virtual_address(int type
, char *new_address
)
1262 virtaddress_entry_t
*vent
;
1263 int vent_needs_to_be_added
= 0;
1265 tor_assert(new_address
);
1266 tor_assert(addressmap
);
1267 tor_assert(virtaddress_reversemap
);
1269 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1271 vent
= tor_malloc_zero(sizeof(virtaddress_entry_t
));
1272 vent_needs_to_be_added
= 1;
1275 addrp
= (type
== RESOLVED_TYPE_IPV4
) ?
1276 &vent
->ipv4_address
: &vent
->hostname_address
;
1278 addressmap_entry_t
*ent
= strmap_get(addressmap
, *addrp
);
1279 if (ent
&& ent
->new_address
&&
1280 !strcasecmp(new_address
, ent
->new_address
)) {
1281 tor_free(new_address
);
1282 tor_assert(!vent_needs_to_be_added
);
1283 return tor_strdup(*addrp
);
1286 "Internal confusion: I thought that '%s' was mapped to by "
1287 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1288 safe_str_client(new_address
),
1289 safe_str_client(*addrp
),
1290 safe_str_client(*addrp
),
1291 ent
?safe_str_client(ent
->new_address
):"(nothing)");
1295 *addrp
= addressmap_get_virtual_address(type
);
1298 tor_free(new_address
);
1301 log_info(LD_APP
, "Registering map from %s to %s", *addrp
, new_address
);
1302 if (vent_needs_to_be_added
)
1303 strmap_set(virtaddress_reversemap
, new_address
, vent
);
1304 addressmap_register(*addrp
, new_address
, 2, ADDRMAPSRC_CONTROLLER
);
1308 /* Try to catch possible bugs */
1309 addressmap_entry_t
*ent
;
1310 ent
= strmap_get(addressmap
, *addrp
);
1312 tor_assert(!strcasecmp(ent
->new_address
,new_address
));
1313 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1315 tor_assert(!strcasecmp(*addrp
,
1316 (type
== RESOLVED_TYPE_IPV4
) ?
1317 vent
->ipv4_address
: vent
->hostname_address
));
1318 log_info(LD_APP
, "Map from %s to %s okay.",
1319 safe_str_client(*addrp
),
1320 safe_str_client(new_address
));
1327 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1328 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1329 * should be true if we're using this address as a client; false if we're
1330 * using it as a server.
1333 address_is_invalid_destination(const char *address
, int client
)
1336 if (get_options()->AllowNonRFC953Hostnames
)
1339 if (get_options()->ServerDNSAllowNonRFC953Hostnames
)
1344 if (TOR_ISALNUM(*address
) ||
1347 *address
== '_') /* Underscore is not allowed, but Windows does it
1348 * sometimes, just to thumb its nose at the IETF. */
1356 /** Iterate over all address mappings which have expiry times between
1357 * min_expires and max_expires, inclusive. If sl is provided, add an
1358 * "old-addr new-addr expiry" string to sl for each mapping, omitting
1359 * the expiry time if want_expiry is false. If sl is NULL, remove the
1363 addressmap_get_mappings(smartlist_t
*sl
, time_t min_expires
,
1364 time_t max_expires
, int want_expiry
)
1366 strmap_iter_t
*iter
;
1369 addressmap_entry_t
*val
;
1374 for (iter
= strmap_iter_init(addressmap
); !strmap_iter_done(iter
); ) {
1375 strmap_iter_get(iter
, &key
, &_val
);
1377 if (val
->expires
>= min_expires
&& val
->expires
<= max_expires
) {
1379 iter
= strmap_iter_next_rmv(addressmap
,iter
);
1380 addressmap_ent_remove(key
, val
);
1382 } else if (val
->new_address
) {
1383 size_t len
= strlen(key
)+strlen(val
->new_address
)+ISO_TIME_LEN
+5;
1384 char *line
= tor_malloc(len
);
1386 if (val
->expires
< 3 || val
->expires
== TIME_MAX
)
1387 tor_snprintf(line
, len
, "%s %s NEVER", key
, val
->new_address
);
1389 char time
[ISO_TIME_LEN
+1];
1390 format_iso_time(time
, val
->expires
);
1391 tor_snprintf(line
, len
, "%s %s \"%s\"", key
, val
->new_address
,
1395 tor_snprintf(line
, len
, "%s %s", key
, val
->new_address
);
1397 smartlist_add(sl
, line
);
1400 iter
= strmap_iter_next(addressmap
,iter
);
1404 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1405 * reject depending on our config options. */
1407 consider_plaintext_ports(edge_connection_t
*conn
, uint16_t port
)
1409 or_options_t
*options
= get_options();
1410 int reject
= smartlist_string_num_isin(options
->RejectPlaintextPorts
, port
);
1412 if (smartlist_string_num_isin(options
->WarnPlaintextPorts
, port
)) {
1413 log_warn(LD_APP
, "Application request to port %d: this port is "
1414 "commonly used for unencrypted protocols. Please make sure "
1415 "you don't send anything you would mind the rest of the "
1416 "Internet reading!%s", port
, reject
? " Closing." : "");
1417 control_event_client_status(LOG_WARN
, "DANGEROUS_PORT PORT=%d RESULT=%s",
1418 port
, reject
? "REJECT" : "WARN");
1422 log_info(LD_APP
, "Port %d listed in RejectPlaintextPorts. Closing.", port
);
1423 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1430 /** How many times do we try connecting with an exit configured via
1431 * TrackHostExits before concluding that it won't work any more and trying a
1433 #define TRACKHOSTEXITS_RETRIES 5
1435 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1436 * asked us to leave streams unattached. Return 0 in that case.
1438 * See connection_ap_handshake_rewrite_and_attach()'s
1439 * documentation for arguments and return value.
1442 connection_ap_rewrite_and_attach_if_allowed(edge_connection_t
*conn
,
1443 origin_circuit_t
*circ
,
1444 crypt_path_t
*cpath
)
1446 or_options_t
*options
= get_options();
1448 if (options
->LeaveStreamsUnattached
) {
1449 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1452 return connection_ap_handshake_rewrite_and_attach(conn
, circ
, cpath
);
1455 /** Connection <b>conn</b> just finished its socks handshake, or the
1456 * controller asked us to take care of it. If <b>circ</b> is defined,
1457 * then that's where we'll want to attach it. Otherwise we have to
1458 * figure it out ourselves.
1460 * First, parse whether it's a .exit address, remap it, and so on. Then
1461 * if it's for a general circuit, try to attach it to a circuit (or launch
1462 * one as needed), else if it's for a rendezvous circuit, fetch a
1463 * rendezvous descriptor first (or attach/launch a circuit if the
1464 * rendezvous descriptor is already here and fresh enough).
1466 * The stream will exit from the hop
1467 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1468 * <b>cpath</b> is NULL.
1471 connection_ap_handshake_rewrite_and_attach(edge_connection_t
*conn
,
1472 origin_circuit_t
*circ
,
1473 crypt_path_t
*cpath
)
1475 socks_request_t
*socks
= conn
->socks_request
;
1476 hostname_type_t addresstype
;
1477 or_options_t
*options
= get_options();
1478 struct in_addr addr_tmp
;
1480 char orig_address
[MAX_SOCKS_ADDR_LEN
];
1481 time_t map_expires
= TIME_MAX
;
1482 int remapped_to_exit
= 0;
1483 time_t now
= time(NULL
);
1485 tor_strlower(socks
->address
); /* normalize it */
1486 strlcpy(orig_address
, socks
->address
, sizeof(orig_address
));
1487 log_debug(LD_APP
,"Client asked for %s:%d",
1488 safe_str_client(socks
->address
),
1491 if (socks
->command
== SOCKS_COMMAND_RESOLVE
&&
1492 !tor_inet_aton(socks
->address
, &addr_tmp
) &&
1493 options
->AutomapHostsOnResolve
&& options
->AutomapHostsSuffixes
) {
1494 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, const char *, cp
,
1495 if (!strcasecmpend(socks
->address
, cp
)) {
1500 const char *new_addr
;
1501 new_addr
= addressmap_register_virtual_address(
1502 RESOLVED_TYPE_IPV4
, tor_strdup(socks
->address
));
1504 log_warn(LD_APP
, "Unable to automap address %s",
1505 escaped_safe_str(socks
->address
));
1506 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
1509 log_info(LD_APP
, "Automapping %s to %s",
1510 escaped_safe_str_client(socks
->address
),
1511 safe_str_client(new_addr
));
1512 strlcpy(socks
->address
, new_addr
, sizeof(socks
->address
));
1516 if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1517 if (addressmap_rewrite_reverse(socks
->address
, sizeof(socks
->address
),
1519 char *result
= tor_strdup(socks
->address
);
1520 /* remember _what_ is supposed to have been resolved. */
1521 tor_snprintf(socks
->address
, sizeof(socks
->address
), "REVERSE[%s]",
1523 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_HOSTNAME
,
1524 strlen(result
), (uint8_t*)result
,
1527 connection_mark_unattached_ap(conn
,
1528 END_STREAM_REASON_DONE
|
1529 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1532 if (options
->ClientDNSRejectInternalAddresses
) {
1533 /* Don't let people try to do a reverse lookup on 10.0.0.1. */
1536 ok
= tor_addr_parse_reverse_lookup_name(
1537 &addr
, socks
->address
, AF_UNSPEC
, 1);
1538 if (ok
== 1 && tor_addr_is_internal(&addr
, 0)) {
1539 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_ERROR
,
1540 0, NULL
, -1, TIME_MAX
);
1541 connection_mark_unattached_ap(conn
,
1542 END_STREAM_REASON_SOCKSPROTOCOL
|
1543 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1547 } else if (!automap
) {
1548 int started_without_chosen_exit
= strcasecmpend(socks
->address
, ".exit");
1549 /* For address map controls, remap the address. */
1550 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
),
1552 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1553 REMAP_STREAM_SOURCE_CACHE
);
1554 if (started_without_chosen_exit
&&
1555 !strcasecmpend(socks
->address
, ".exit") &&
1556 map_expires
< TIME_MAX
)
1557 remapped_to_exit
= 1;
1561 if (!automap
&& address_is_in_virtual_range(socks
->address
)) {
1562 /* This address was probably handed out by client_dns_get_unmapped_address,
1563 * but the mapping was discarded for some reason. We *don't* want to send
1564 * the address through Tor; that's likely to fail, and may leak
1567 log_warn(LD_APP
,"Missing mapping for virtual address '%s'. Refusing.",
1568 safe_str_client(socks
->address
));
1569 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
1573 /* Parse the address provided by SOCKS. Modify it in-place if it
1574 * specifies a hidden-service (.onion) or particular exit node (.exit).
1576 addresstype
= parse_extended_hostname(socks
->address
,
1577 remapped_to_exit
|| options
->AllowDotExit
);
1579 if (addresstype
== BAD_HOSTNAME
) {
1580 log_warn(LD_APP
, "Invalid onion hostname %s; rejecting",
1581 safe_str_client(socks
->address
));
1582 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1583 escaped(socks
->address
));
1584 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1588 if (addresstype
== EXIT_HOSTNAME
) {
1589 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1590 * node, and conn->address to hold only the address portion. */
1591 char *s
= strrchr(socks
->address
,'.');
1592 tor_assert(!automap
);
1595 conn
->chosen_exit_name
= tor_strdup(s
+1);
1596 if (remapped_to_exit
) /* 5 tries before it expires the addressmap */
1597 conn
->chosen_exit_retries
= TRACKHOSTEXITS_RETRIES
;
1600 log_warn(LD_APP
,"Malformed exit address '%s.exit'. Refusing.",
1601 safe_str_client(socks
->address
));
1602 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1603 escaped(socks
->address
));
1604 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1609 conn
->chosen_exit_name
= tor_strdup(socks
->address
);
1610 r
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1611 *socks
->address
= 0;
1613 strlcpy(socks
->address
, r
->address
, sizeof(socks
->address
));
1616 "Unrecognized server in exit address '%s.exit'. Refusing.",
1617 safe_str_client(socks
->address
));
1618 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1624 if (addresstype
!= ONION_HOSTNAME
) {
1625 /* not a hidden-service request (i.e. normal or .exit) */
1626 if (address_is_invalid_destination(socks
->address
, 1)) {
1627 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1628 escaped(socks
->address
));
1630 "Destination '%s' seems to be an invalid hostname. Failing.",
1631 safe_str_client(socks
->address
));
1632 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1636 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
1639 /* Reply to resolves immediately if we can. */
1640 if (tor_inet_aton(socks
->address
, &in
)) { /* see if it's an IP already */
1641 /* leave it in network order */
1643 /* remember _what_ is supposed to have been resolved. */
1644 strlcpy(socks
->address
, orig_address
, sizeof(socks
->address
));
1645 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
1648 connection_mark_unattached_ap(conn
,
1649 END_STREAM_REASON_DONE
|
1650 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1653 tor_assert(!automap
);
1654 rep_hist_note_used_resolve(now
); /* help predict this next time */
1655 } else if (socks
->command
== SOCKS_COMMAND_CONNECT
) {
1656 tor_assert(!automap
);
1657 if (socks
->port
== 0) {
1658 log_notice(LD_APP
,"Application asked to connect to port 0. Refusing.");
1659 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1662 if (options
->ClientRejectInternalAddresses
&&
1663 !conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
1665 if (tor_addr_from_str(&addr
, socks
->address
) >= 0 &&
1666 tor_addr_is_internal(&addr
, 0)) {
1667 /* If this is an explicit private address with no chosen exit node,
1668 * then we really don't want to try to connect to it. That's
1669 * probably an error. */
1670 if (conn
->is_transparent_ap
) {
1672 "Rejecting request for anonymous connection to private "
1673 "address %s on a TransPort or NATDPort. Possible loop "
1674 "in your NAT rules?", safe_str_client(socks
->address
));
1677 "Rejecting SOCKS request for anonymous connection to "
1678 "private address %s", safe_str_client(socks
->address
));
1680 connection_mark_unattached_ap(conn
, END_STREAM_REASON_PRIVATE_ADDR
);
1685 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
1686 /* see if we can find a suitable enclave exit */
1688 router_find_exact_exit_enclave(socks
->address
, socks
->port
);
1691 "Redirecting address %s to exit at enclave router %s",
1692 safe_str_client(socks
->address
), r
->nickname
);
1693 /* use the hex digest, not nickname, in case there are two
1694 routers with this nickname */
1695 conn
->chosen_exit_name
=
1696 tor_strdup(hex_str(r
->cache_info
.identity_digest
, DIGEST_LEN
));
1697 conn
->chosen_exit_optional
= 1;
1701 /* warn or reject if it's using a dangerous port */
1702 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
)
1703 if (consider_plaintext_ports(conn
, socks
->port
) < 0)
1706 if (!conn
->use_begindir
) {
1707 /* help predict this next time */
1708 rep_hist_note_used_port(now
, socks
->port
);
1710 } else if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1711 rep_hist_note_used_resolve(now
); /* help predict this next time */
1712 /* no extra processing needed */
1714 tor_fragile_assert();
1716 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1717 if ((circ
&& connection_ap_handshake_attach_chosen_circuit(
1718 conn
, circ
, cpath
) < 0) ||
1720 connection_ap_handshake_attach_circuit(conn
) < 0)) {
1721 if (!conn
->_base
.marked_for_close
)
1722 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1727 /* it's a hidden-service request */
1728 rend_cache_entry_t
*entry
;
1730 rend_service_authorization_t
*client_auth
;
1731 tor_assert(!automap
);
1732 if (SOCKS_COMMAND_IS_RESOLVE(socks
->command
)) {
1733 /* if it's a resolve request, fail it right now, rather than
1734 * building all the circuits and then realizing it won't work. */
1736 "Resolve requests to hidden services not allowed. Failing.");
1737 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
1738 0,NULL
,-1,TIME_MAX
);
1739 connection_mark_unattached_ap(conn
,
1740 END_STREAM_REASON_SOCKSPROTOCOL
|
1741 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1746 log_warn(LD_CONTROL
, "Attachstream to a circuit is not "
1747 "supported for .onion addresses currently. Failing.");
1748 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1752 conn
->rend_data
= tor_malloc_zero(sizeof(rend_data_t
));
1753 strlcpy(conn
->rend_data
->onion_address
, socks
->address
,
1754 sizeof(conn
->rend_data
->onion_address
));
1755 log_info(LD_REND
,"Got a hidden service request for ID '%s'",
1756 safe_str_client(conn
->rend_data
->onion_address
));
1757 /* see if we already have it cached */
1758 r
= rend_cache_lookup_entry(conn
->rend_data
->onion_address
, -1, &entry
);
1760 log_warn(LD_BUG
,"Invalid service name '%s'",
1761 safe_str_client(conn
->rend_data
->onion_address
));
1762 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1766 /* Help predict this next time. We're not sure if it will need
1767 * a stable circuit yet, but we know we'll need *something*. */
1768 rep_hist_note_used_internal(now
, 0, 1);
1770 /* Look up if we have client authorization for it. */
1771 client_auth
= rend_client_lookup_service_authorization(
1772 conn
->rend_data
->onion_address
);
1774 log_info(LD_REND
, "Using previously configured client authorization "
1775 "for hidden service request.");
1776 memcpy(conn
->rend_data
->descriptor_cookie
,
1777 client_auth
->descriptor_cookie
, REND_DESC_COOKIE_LEN
);
1778 conn
->rend_data
->auth_type
= client_auth
->auth_type
;
1781 conn
->_base
.state
= AP_CONN_STATE_RENDDESC_WAIT
;
1782 log_info(LD_REND
, "Unknown descriptor %s. Fetching.",
1783 safe_str_client(conn
->rend_data
->onion_address
));
1784 rend_client_refetch_v2_renddesc(conn
->rend_data
);
1785 } else { /* r > 0 */
1786 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1787 log_info(LD_REND
, "Descriptor is here. Great.");
1788 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
1789 if (!conn
->_base
.marked_for_close
)
1790 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1796 return 0; /* unreached but keeps the compiler happy */
1800 static int pf_socket
= -1;
1805 /* This should be opened before dropping privileges. */
1810 /* only works on OpenBSD */
1811 pf
= open("/dev/pf", O_RDONLY
);
1813 /* works on NetBSD and FreeBSD */
1814 pf
= open("/dev/pf", O_RDWR
);
1818 log_warn(LD_NET
, "open(\"/dev/pf\") failed: %s", strerror(errno
));
1827 /** Fetch the original destination address and port from a
1828 * system-specific interface and put them into a
1829 * socks_request_t as if they came from a socks request.
1831 * Return -1 if an error prevents fetching the destination,
1835 connection_ap_get_original_destination(edge_connection_t
*conn
,
1836 socks_request_t
*req
)
1838 #ifdef TRANS_NETFILTER
1840 struct sockaddr_storage orig_dst
;
1841 socklen_t orig_dst_len
= sizeof(orig_dst
);
1844 if (getsockopt(conn
->_base
.s
, SOL_IP
, SO_ORIGINAL_DST
,
1845 (struct sockaddr
*)&orig_dst
, &orig_dst_len
) < 0) {
1846 int e
= tor_socket_errno(conn
->_base
.s
);
1847 log_warn(LD_NET
, "getsockopt() failed: %s", tor_socket_strerror(e
));
1851 tor_addr_from_sockaddr(&addr
, (struct sockaddr
*)&orig_dst
, &req
->port
);
1852 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 0);
1855 #elif defined(TRANS_PF)
1856 struct sockaddr_storage proxy_addr
;
1857 socklen_t proxy_addr_len
= sizeof(proxy_addr
);
1858 struct sockaddr
*proxy_sa
= (struct sockaddr
*) &proxy_addr
;
1859 struct pfioc_natlook pnl
;
1863 if (getsockname(conn
->_base
.s
, (struct sockaddr
*)&proxy_addr
,
1864 &proxy_addr_len
) < 0) {
1865 int e
= tor_socket_errno(conn
->_base
.s
);
1866 log_warn(LD_NET
, "getsockname() to determine transocks destination "
1867 "failed: %s", tor_socket_strerror(e
));
1871 memset(&pnl
, 0, sizeof(pnl
));
1872 pnl
.proto
= IPPROTO_TCP
;
1873 pnl
.direction
= PF_OUT
;
1874 if (proxy_sa
->sa_family
== AF_INET
) {
1875 struct sockaddr_in
*sin
= (struct sockaddr_in
*)proxy_sa
;
1877 pnl
.saddr
.v4
.s_addr
= tor_addr_to_ipv4n(&conn
->_base
.addr
);
1878 pnl
.sport
= htons(conn
->_base
.port
);
1879 pnl
.daddr
.v4
.s_addr
= sin
->sin_addr
.s_addr
;
1880 pnl
.dport
= sin
->sin_port
;
1881 } else if (proxy_sa
->sa_family
== AF_INET6
) {
1882 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)proxy_sa
;
1884 memcpy(&pnl
.saddr
.v6
, tor_addr_to_in6(&conn
->_base
.addr
),
1885 sizeof(struct in6_addr
));
1886 pnl
.sport
= htons(conn
->_base
.port
);
1887 memcpy(&pnl
.daddr
.v6
, &sin6
->sin6_addr
, sizeof(struct in6_addr
));
1888 pnl
.dport
= sin6
->sin6_port
;
1890 log_warn(LD_NET
, "getsockname() gave an unexpected address family (%d)",
1891 (int)proxy_sa
->sa_family
);
1895 pf
= get_pf_socket();
1899 if (ioctl(pf
, DIOCNATLOOK
, &pnl
) < 0) {
1900 log_warn(LD_NET
, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno
));
1904 if (pnl
.af
== AF_INET
) {
1905 tor_addr_from_ipv4n(&addr
, pnl
.rdaddr
.v4
.s_addr
);
1906 } else if (pnl
.af
== AF_INET6
) {
1907 tor_addr_from_in6(&addr
, &pnl
.rdaddr
.v6
);
1909 tor_fragile_assert();
1913 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 0);
1914 req
->port
= ntohs(pnl
.rdport
);
1920 log_warn(LD_BUG
, "Called connection_ap_get_original_destination, but no "
1921 "transparent proxy method was configured.");
1926 /** connection_edge_process_inbuf() found a conn in state
1927 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1928 * the socks handshake.
1930 * If the handshake is complete, send it to
1931 * connection_ap_handshake_rewrite_and_attach().
1933 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1937 connection_ap_handshake_process_socks(edge_connection_t
*conn
)
1939 socks_request_t
*socks
;
1941 or_options_t
*options
= get_options();
1944 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
1945 tor_assert(conn
->_base
.state
== AP_CONN_STATE_SOCKS_WAIT
);
1946 tor_assert(conn
->socks_request
);
1947 socks
= conn
->socks_request
;
1949 log_debug(LD_APP
,"entered.");
1951 sockshere
= fetch_from_buf_socks(conn
->_base
.inbuf
, socks
,
1952 options
->TestSocks
, options
->SafeSocks
);
1953 if (sockshere
== 0) {
1954 if (socks
->replylen
) {
1955 connection_write_to_buf(socks
->reply
, socks
->replylen
, TO_CONN(conn
));
1956 /* zero it out so we can do another round of negotiation */
1957 socks
->replylen
= 0;
1959 log_debug(LD_APP
,"socks handshake not all here yet.");
1962 } else if (sockshere
== -1) {
1963 if (socks
->replylen
) { /* we should send reply back */
1964 log_debug(LD_APP
,"reply is already set for us. Using it.");
1965 connection_ap_handshake_socks_reply(conn
, socks
->reply
, socks
->replylen
,
1966 END_STREAM_REASON_SOCKSPROTOCOL
);
1969 log_warn(LD_APP
,"Fetching socks handshake failed. Closing.");
1970 connection_ap_handshake_socks_reply(conn
, NULL
, 0,
1971 END_STREAM_REASON_SOCKSPROTOCOL
);
1973 connection_mark_unattached_ap(conn
,
1974 END_STREAM_REASON_SOCKSPROTOCOL
|
1975 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1977 } /* else socks handshake is done, continue processing */
1979 if (SOCKS_COMMAND_IS_CONNECT(socks
->command
))
1980 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1982 control_event_stream_status(conn
, STREAM_EVENT_NEW_RESOLVE
, 0);
1984 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
1987 /** connection_init_accepted_conn() found a new trans AP conn.
1988 * Get the original destination and send it to
1989 * connection_ap_handshake_rewrite_and_attach().
1991 * Return -1 if an unexpected error with conn (and it should be marked
1992 * for close), else return 0.
1995 connection_ap_process_transparent(edge_connection_t
*conn
)
1997 socks_request_t
*socks
;
2000 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
2001 tor_assert(conn
->socks_request
);
2002 socks
= conn
->socks_request
;
2004 /* pretend that a socks handshake completed so we don't try to
2005 * send a socks reply down a transparent conn */
2006 socks
->command
= SOCKS_COMMAND_CONNECT
;
2007 socks
->has_finished
= 1;
2009 log_debug(LD_APP
,"entered.");
2011 if (connection_ap_get_original_destination(conn
, socks
) < 0) {
2012 log_warn(LD_APP
,"Fetching original destination failed. Closing.");
2013 connection_mark_unattached_ap(conn
,
2014 END_STREAM_REASON_CANT_FETCH_ORIG_DEST
);
2017 /* we have the original destination */
2019 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2021 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2024 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2025 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2026 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2027 * form of the original destination.
2029 * If the original destination is complete, send it to
2030 * connection_ap_handshake_rewrite_and_attach().
2032 * Return -1 if an unexpected error with conn (and it should be marked
2033 * for close), else return 0.
2036 connection_ap_process_natd(edge_connection_t
*conn
)
2038 char tmp_buf
[36], *tbuf
, *daddr
;
2041 socks_request_t
*socks
;
2044 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
2045 tor_assert(conn
->_base
.state
== AP_CONN_STATE_NATD_WAIT
);
2046 tor_assert(conn
->socks_request
);
2047 socks
= conn
->socks_request
;
2049 log_debug(LD_APP
,"entered.");
2051 /* look for LF-terminated "[DEST ip_addr port]"
2052 * where ip_addr is a dotted-quad and port is in string form */
2053 err
= fetch_from_buf_line(conn
->_base
.inbuf
, tmp_buf
, &tlen
);
2057 log_warn(LD_APP
,"NATD handshake failed (DEST too long). Closing");
2058 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2062 if (strcmpstart(tmp_buf
, "[DEST ")) {
2063 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2066 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2070 daddr
= tbuf
= &tmp_buf
[0] + 6; /* after end of "[DEST " */
2071 if (!(tbuf
= strchr(tbuf
, ' '))) {
2072 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2075 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2080 /* pretend that a socks handshake completed so we don't try to
2081 * send a socks reply down a natd conn */
2082 strlcpy(socks
->address
, daddr
, sizeof(socks
->address
));
2083 socks
->port
= (uint16_t)
2084 tor_parse_long(tbuf
, 10, 1, 65535, &port_ok
, &daddr
);
2086 log_warn(LD_APP
,"NATD handshake failed; port %s is ill-formed or out "
2087 "of range.", escaped(tbuf
));
2088 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2092 socks
->command
= SOCKS_COMMAND_CONNECT
;
2093 socks
->has_finished
= 1;
2095 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2097 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2099 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2102 /** Iterate over the two bytes of stream_id until we get one that is not
2103 * already in use; return it. Return 0 if can't get a unique stream_id.
2106 get_unique_stream_id_by_circ(origin_circuit_t
*circ
)
2108 edge_connection_t
*tmpconn
;
2109 streamid_t test_stream_id
;
2110 uint32_t attempts
=0;
2113 test_stream_id
= circ
->next_stream_id
++;
2114 if (++attempts
> 1<<16) {
2115 /* Make sure we don't loop forever if all stream_id's are used. */
2116 log_warn(LD_APP
,"No unused stream IDs. Failing.");
2119 if (test_stream_id
== 0)
2121 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
2122 if (tmpconn
->stream_id
== test_stream_id
)
2124 return test_stream_id
;
2127 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2128 * socks_request field, and send it down circ.
2130 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2133 connection_ap_handshake_send_begin(edge_connection_t
*ap_conn
)
2135 char payload
[CELL_PAYLOAD_SIZE
];
2138 origin_circuit_t
*circ
;
2139 tor_assert(ap_conn
->on_circuit
);
2140 circ
= TO_ORIGIN_CIRCUIT(ap_conn
->on_circuit
);
2142 tor_assert(ap_conn
->_base
.type
== CONN_TYPE_AP
);
2143 tor_assert(ap_conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
2144 tor_assert(ap_conn
->socks_request
);
2145 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn
->socks_request
->command
));
2147 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
2148 if (ap_conn
->stream_id
==0) {
2149 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2150 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_RESOURCELIMIT
);
2154 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:%d",
2155 (circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
) ?
2156 ap_conn
->socks_request
->address
: "",
2157 ap_conn
->socks_request
->port
);
2158 payload_len
= (int)strlen(payload
)+1;
2161 "Sending relay cell to begin stream %d.", ap_conn
->stream_id
);
2163 begin_type
= ap_conn
->use_begindir
?
2164 RELAY_COMMAND_BEGIN_DIR
: RELAY_COMMAND_BEGIN
;
2165 if (begin_type
== RELAY_COMMAND_BEGIN
) {
2166 tor_assert(circ
->build_state
->onehop_tunnel
== 0);
2169 if (connection_edge_send_command(ap_conn
, begin_type
,
2170 begin_type
== RELAY_COMMAND_BEGIN
? payload
: NULL
,
2171 begin_type
== RELAY_COMMAND_BEGIN
? payload_len
: 0) < 0)
2172 return -1; /* circuit is closed, don't continue */
2174 ap_conn
->package_window
= STREAMWINDOW_START
;
2175 ap_conn
->deliver_window
= STREAMWINDOW_START
;
2176 ap_conn
->_base
.state
= AP_CONN_STATE_CONNECT_WAIT
;
2177 log_info(LD_APP
,"Address/port sent, ap socket %d, n_circ_id %d",
2178 ap_conn
->_base
.s
, circ
->_base
.n_circ_id
);
2179 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
, 0);
2183 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2184 * socks_request field, and send it down circ.
2186 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2189 connection_ap_handshake_send_resolve(edge_connection_t
*ap_conn
)
2191 int payload_len
, command
;
2192 const char *string_addr
;
2193 char inaddr_buf
[REVERSE_LOOKUP_NAME_BUF_LEN
];
2194 origin_circuit_t
*circ
;
2195 tor_assert(ap_conn
->on_circuit
);
2196 circ
= TO_ORIGIN_CIRCUIT(ap_conn
->on_circuit
);
2198 tor_assert(ap_conn
->_base
.type
== CONN_TYPE_AP
);
2199 tor_assert(ap_conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
2200 tor_assert(ap_conn
->socks_request
);
2201 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
2203 command
= ap_conn
->socks_request
->command
;
2204 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command
));
2206 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
2207 if (ap_conn
->stream_id
==0) {
2208 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2209 /*XXXX022 _close_ the circuit because it's full? That sounds dumb. */
2210 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_RESOURCELIMIT
);
2214 if (command
== SOCKS_COMMAND_RESOLVE
) {
2215 string_addr
= ap_conn
->socks_request
->address
;
2216 payload_len
= (int)strlen(string_addr
)+1;
2218 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2219 const char *a
= ap_conn
->socks_request
->address
;
2223 /* We're doing a reverse lookup. The input could be an IP address, or
2224 * could be an .in-addr.arpa or .ip6.arpa address */
2225 r
= tor_addr_parse_reverse_lookup_name(&addr
, a
, AF_INET
, 1);
2227 log_warn(LD_APP
, "Rejecting ill-formed reverse lookup of %s",
2228 safe_str_client(a
));
2229 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2233 r
= tor_addr_to_reverse_lookup_name(inaddr_buf
, sizeof(inaddr_buf
), &addr
);
2235 log_warn(LD_BUG
, "Couldn't generate reverse lookup hostname of %s",
2236 safe_str_client(a
));
2237 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2241 string_addr
= inaddr_buf
;
2242 payload_len
= (int)strlen(inaddr_buf
)+1;
2243 tor_assert(payload_len
<= (int)sizeof(inaddr_buf
));
2247 "Sending relay cell to begin stream %d.", ap_conn
->stream_id
);
2249 if (connection_edge_send_command(ap_conn
,
2250 RELAY_COMMAND_RESOLVE
,
2251 string_addr
, payload_len
) < 0)
2252 return -1; /* circuit is closed, don't continue */
2254 tor_free(ap_conn
->_base
.address
); /* Maybe already set by dnsserv. */
2255 ap_conn
->_base
.address
= tor_strdup("(Tor_internal)");
2256 ap_conn
->_base
.state
= AP_CONN_STATE_RESOLVE_WAIT
;
2257 log_info(LD_APP
,"Address sent for resolve, ap socket %d, n_circ_id %d",
2258 ap_conn
->_base
.s
, circ
->_base
.n_circ_id
);
2259 control_event_stream_status(ap_conn
, STREAM_EVENT_NEW
, 0);
2260 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
, 0);
2264 /** Make an AP connection_t, make a new linked connection pair, and attach
2265 * one side to the conn, connection_add it, initialize it to circuit_wait,
2266 * and call connection_ap_handshake_attach_circuit(conn) on it.
2268 * Return the other end of the linked connection pair, or -1 if error.
2271 connection_ap_make_link(char *address
, uint16_t port
,
2272 const char *digest
, int use_begindir
, int want_onehop
)
2274 edge_connection_t
*conn
;
2276 log_info(LD_APP
,"Making internal %s tunnel to %s:%d ...",
2277 want_onehop
? "direct" : "anonymized",
2278 safe_str_client(address
), port
);
2280 conn
= edge_connection_new(CONN_TYPE_AP
, AF_INET
);
2281 conn
->_base
.linked
= 1; /* so that we can add it safely below. */
2283 /* populate conn->socks_request */
2285 /* leave version at zero, so the socks_reply is empty */
2286 conn
->socks_request
->socks_version
= 0;
2287 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
2288 strlcpy(conn
->socks_request
->address
, address
,
2289 sizeof(conn
->socks_request
->address
));
2290 conn
->socks_request
->port
= port
;
2291 conn
->socks_request
->command
= SOCKS_COMMAND_CONNECT
;
2292 conn
->want_onehop
= want_onehop
;
2293 conn
->use_begindir
= use_begindir
;
2295 conn
->chosen_exit_name
= tor_malloc(HEX_DIGEST_LEN
+2);
2296 conn
->chosen_exit_name
[0] = '$';
2298 base16_encode(conn
->chosen_exit_name
+1,HEX_DIGEST_LEN
+1,
2299 digest
, DIGEST_LEN
);
2302 conn
->_base
.address
= tor_strdup("(Tor_internal)");
2303 tor_addr_make_unspec(&conn
->_base
.addr
);
2304 conn
->_base
.port
= 0;
2306 if (connection_add(TO_CONN(conn
)) < 0) { /* no space, forget it */
2307 connection_free(TO_CONN(conn
));
2311 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2313 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2315 /* attaching to a dirty circuit is fine */
2316 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
2317 if (!conn
->_base
.marked_for_close
)
2318 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
2322 log_info(LD_APP
,"... application connection created and linked.");
2326 /** Notify any interested controller connections about a new hostname resolve
2327 * or resolve error. Takes the same arguments as does
2328 * connection_ap_handshake_socks_resolved(). */
2330 tell_controller_about_resolved_result(edge_connection_t
*conn
,
2338 if (ttl
>= 0 && (answer_type
== RESOLVED_TYPE_IPV4
||
2339 answer_type
== RESOLVED_TYPE_HOSTNAME
)) {
2340 return; /* we already told the controller. */
2341 } else if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
>= 4) {
2343 char buf
[INET_NTOA_BUF_LEN
];
2344 in
.s_addr
= get_uint32(answer
);
2345 tor_inet_ntoa(&in
, buf
, sizeof(buf
));
2346 control_event_address_mapped(conn
->socks_request
->address
,
2347 buf
, expires
, NULL
);
2348 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
<256) {
2349 char *cp
= tor_strndup(answer
, answer_len
);
2350 control_event_address_mapped(conn
->socks_request
->address
,
2354 control_event_address_mapped(conn
->socks_request
->address
,
2361 /** Send an answer to an AP connection that has requested a DNS lookup via
2362 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
2363 * for unreachable; the answer should be in the format specified in the socks
2364 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
2365 * certain errors or for values that didn't come via DNS. <b>expires</b> is
2366 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
2368 /* XXXX022 the use of the ttl and expires fields is nutty. Let's make this
2369 * interface and those that use it less ugly. */
2371 connection_ap_handshake_socks_resolved(edge_connection_t
*conn
,
2374 const uint8_t *answer
,
2382 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2383 uint32_t a
= ntohl(get_uint32(answer
));
2385 client_dns_set_addressmap(conn
->socks_request
->address
, a
,
2386 conn
->chosen_exit_name
, ttl
);
2387 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2388 char *cp
= tor_strndup((char*)answer
, answer_len
);
2389 client_dns_set_reverse_addressmap(conn
->socks_request
->address
,
2391 conn
->chosen_exit_name
, ttl
);
2396 if (conn
->is_dns_request
) {
2397 if (conn
->dns_server_request
) {
2398 /* We had a request on our DNS port: answer it. */
2399 dnsserv_resolved(conn
, answer_type
, answer_len
, (char*)answer
, ttl
);
2400 conn
->socks_request
->has_finished
= 1;
2403 /* This must be a request from the controller. We already sent
2404 * a mapaddress if there's a ttl. */
2405 tell_controller_about_resolved_result(conn
, answer_type
, answer_len
,
2406 (char*)answer
, ttl
, expires
);
2407 conn
->socks_request
->has_finished
= 1;
2410 /* We shouldn't need to free conn here; it gets marked by the caller. */
2413 if (conn
->socks_request
->socks_version
== 4) {
2414 buf
[0] = 0x00; /* version */
2415 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2416 buf
[1] = SOCKS4_GRANTED
;
2417 set_uint16(buf
+2, 0);
2418 memcpy(buf
+4, answer
, 4); /* address */
2419 replylen
= SOCKS4_NETWORK_LEN
;
2420 } else { /* "error" */
2421 buf
[1] = SOCKS4_REJECT
;
2422 memset(buf
+2, 0, 6);
2423 replylen
= SOCKS4_NETWORK_LEN
;
2425 } else if (conn
->socks_request
->socks_version
== 5) {
2427 buf
[0] = 0x05; /* version */
2428 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2429 buf
[1] = SOCKS5_SUCCEEDED
;
2430 buf
[2] = 0; /* reserved */
2431 buf
[3] = 0x01; /* IPv4 address type */
2432 memcpy(buf
+4, answer
, 4); /* address */
2433 set_uint16(buf
+8, 0); /* port == 0. */
2435 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
2436 buf
[1] = SOCKS5_SUCCEEDED
;
2437 buf
[2] = 0; /* reserved */
2438 buf
[3] = 0x04; /* IPv6 address type */
2439 memcpy(buf
+4, answer
, 16); /* address */
2440 set_uint16(buf
+20, 0); /* port == 0. */
2442 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2443 buf
[1] = SOCKS5_SUCCEEDED
;
2444 buf
[2] = 0; /* reserved */
2445 buf
[3] = 0x03; /* Domainname address type */
2446 buf
[4] = (char)answer_len
;
2447 memcpy(buf
+5, answer
, answer_len
); /* address */
2448 set_uint16(buf
+5+answer_len
, 0); /* port == 0. */
2449 replylen
= 5+answer_len
+2;
2451 buf
[1] = SOCKS5_HOST_UNREACHABLE
;
2452 memset(buf
+2, 0, 8);
2456 /* no socks version info; don't send anything back */
2459 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
2460 (answer_type
== RESOLVED_TYPE_IPV4
||
2461 answer_type
== RESOLVED_TYPE_IPV6
) ?
2462 0 : END_STREAM_REASON_RESOLVEFAILED
);
2465 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2466 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2469 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2470 * and return, else reply based on <b>endreason</b> (one of
2471 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2472 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2475 connection_ap_handshake_socks_reply(edge_connection_t
*conn
, char *reply
,
2476 size_t replylen
, int endreason
)
2479 socks5_reply_status_t status
=
2480 stream_end_reason_to_socks5_response(endreason
);
2482 tor_assert(conn
->socks_request
); /* make sure it's an AP stream */
2484 control_event_stream_status(conn
,
2485 status
==SOCKS5_SUCCEEDED
? STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
,
2488 if (conn
->socks_request
->has_finished
) {
2489 log_warn(LD_BUG
, "(Harmless.) duplicate calls to "
2490 "connection_ap_handshake_socks_reply.");
2493 if (replylen
) { /* we already have a reply in mind */
2494 connection_write_to_buf(reply
, replylen
, TO_CONN(conn
));
2495 conn
->socks_request
->has_finished
= 1;
2498 if (conn
->socks_request
->socks_version
== 4) {
2499 memset(buf
,0,SOCKS4_NETWORK_LEN
);
2500 buf
[1] = (status
==SOCKS5_SUCCEEDED
? SOCKS4_GRANTED
: SOCKS4_REJECT
);
2501 /* leave version, destport, destip zero */
2502 connection_write_to_buf(buf
, SOCKS4_NETWORK_LEN
, TO_CONN(conn
));
2503 } else if (conn
->socks_request
->socks_version
== 5) {
2504 buf
[0] = 5; /* version 5 */
2505 buf
[1] = (char)status
;
2507 buf
[3] = 1; /* ipv4 addr */
2508 memset(buf
+4,0,6); /* Set external addr/port to 0.
2509 The spec doesn't seem to say what to do here. -RD */
2510 connection_write_to_buf(buf
,10,TO_CONN(conn
));
2512 /* If socks_version isn't 4 or 5, don't send anything.
2513 * This can happen in the case of AP bridges. */
2514 conn
->socks_request
->has_finished
= 1;
2518 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2519 * an exit hop for the circuit, or we are the origin and it is a
2522 * Launch a new exit connection and initialize things appropriately.
2524 * If it's a rendezvous stream, call connection_exit_connect() on
2527 * For general streams, call dns_resolve() on it first, and only call
2528 * connection_exit_connect() if the dns answer is already known.
2530 * Note that we don't call connection_add() on the new stream! We wait
2531 * for connection_exit_connect() to do that.
2533 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2537 connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
)
2539 edge_connection_t
*n_stream
;
2543 or_circuit_t
*or_circ
= NULL
;
2544 or_options_t
*options
= get_options();
2546 assert_circuit_ok(circ
);
2547 if (!CIRCUIT_IS_ORIGIN(circ
))
2548 or_circ
= TO_OR_CIRCUIT(circ
);
2550 relay_header_unpack(&rh
, cell
->payload
);
2551 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
2554 /* Note: we have to use relay_send_command_from_edge here, not
2555 * connection_edge_end or connection_edge_send_command, since those require
2556 * that we have a stream connected to a circuit, and we don't connect to a
2557 * circuit until we have a pending/successful resolve. */
2559 if (!server_mode(options
) &&
2560 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
2561 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2562 "Relay begin cell at non-server. Closing.");
2563 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2564 END_STREAM_REASON_EXITPOLICY
, NULL
);
2568 if (rh
.command
== RELAY_COMMAND_BEGIN
) {
2569 if (!memchr(cell
->payload
+RELAY_HEADER_SIZE
, 0, rh
.length
)) {
2570 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2571 "Relay begin cell has no \\0. Closing.");
2572 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2573 END_STREAM_REASON_TORPROTOCOL
, NULL
);
2576 if (parse_addr_port(LOG_PROTOCOL_WARN
,
2577 (char*)(cell
->payload
+RELAY_HEADER_SIZE
),
2578 &address
,NULL
,&port
)<0) {
2579 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2580 "Unable to parse addr:port in relay begin cell. Closing.");
2581 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2582 END_STREAM_REASON_TORPROTOCOL
, NULL
);
2586 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2587 "Missing port in relay begin cell. Closing.");
2588 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2589 END_STREAM_REASON_TORPROTOCOL
, NULL
);
2593 if (or_circ
&& or_circ
->p_conn
&& !options
->AllowSingleHopExits
&&
2594 (or_circ
->is_first_hop
||
2595 (!connection_or_digest_is_known_relay(
2596 or_circ
->p_conn
->identity_digest
) &&
2597 should_refuse_unknown_exits(options
)))) {
2598 /* Don't let clients use us as a single-hop proxy, unless the user
2599 * has explicitly allowed that in the config. It attracts attackers
2600 * and users who'd be better off with, well, single-hop proxies.
2602 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2603 "Attempt by %s to open a stream %s. Closing.",
2604 safe_str(or_circ
->p_conn
->_base
.address
),
2605 or_circ
->is_first_hop
? "on first hop of circuit" :
2606 "from unknown relay");
2607 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2608 or_circ
->is_first_hop
?
2609 END_STREAM_REASON_TORPROTOCOL
:
2610 END_STREAM_REASON_MISC
,
2615 } else if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2616 if (!directory_permits_begindir_requests(options
) ||
2617 circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
2618 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2619 END_STREAM_REASON_NOTDIRECTORY
, NULL
);
2622 /* Make sure to get the 'real' address of the previous hop: the
2623 * caller might want to know whether his IP address has changed, and
2624 * we might already have corrected _base.addr[ess] for the relay's
2625 * canonical IP address. */
2626 if (or_circ
&& or_circ
->p_conn
)
2627 address
= tor_dup_addr(&or_circ
->p_conn
->real_addr
);
2629 address
= tor_strdup("127.0.0.1");
2630 port
= 1; /* XXXX This value is never actually used anywhere, and there
2631 * isn't "really" a connection here. But we
2632 * need to set it to something nonzero. */
2634 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
2635 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2636 END_STREAM_REASON_INTERNAL
, NULL
);
2640 log_debug(LD_EXIT
,"Creating new exit connection.");
2641 n_stream
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
2643 /* Remember the tunneled request ID in the new edge connection, so that
2644 * we can measure download times. */
2645 TO_CONN(n_stream
)->dirreq_id
= circ
->dirreq_id
;
2647 n_stream
->_base
.purpose
= EXIT_PURPOSE_CONNECT
;
2649 n_stream
->stream_id
= rh
.stream_id
;
2650 n_stream
->_base
.port
= port
;
2651 /* leave n_stream->s at -1, because it's not yet valid */
2652 n_stream
->package_window
= STREAMWINDOW_START
;
2653 n_stream
->deliver_window
= STREAMWINDOW_START
;
2655 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
2656 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2657 log_info(LD_REND
,"begin is for rendezvous. configuring stream.");
2658 n_stream
->_base
.address
= tor_strdup("(rendezvous)");
2659 n_stream
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
2660 n_stream
->rend_data
= rend_data_dup(origin_circ
->rend_data
);
2661 tor_assert(connection_edge_is_rendezvous_stream(n_stream
));
2662 assert_circuit_ok(circ
);
2663 if (rend_service_set_connection_addr_port(n_stream
, origin_circ
) < 0) {
2664 log_info(LD_REND
,"Didn't find rendezvous service (port %d)",
2665 n_stream
->_base
.port
);
2666 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2667 END_STREAM_REASON_EXITPOLICY
,
2668 origin_circ
->cpath
->prev
);
2669 connection_free(TO_CONN(n_stream
));
2673 assert_circuit_ok(circ
);
2674 log_debug(LD_REND
,"Finished assigning addr/port");
2675 n_stream
->cpath_layer
= origin_circ
->cpath
->prev
; /* link it */
2677 /* add it into the linked list of p_streams on this circuit */
2678 n_stream
->next_stream
= origin_circ
->p_streams
;
2679 n_stream
->on_circuit
= circ
;
2680 origin_circ
->p_streams
= n_stream
;
2681 assert_circuit_ok(circ
);
2683 connection_exit_connect(n_stream
);
2687 tor_strlower(address
);
2688 n_stream
->_base
.address
= address
;
2689 n_stream
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2690 /* default to failed, change in dns_resolve if it turns out not to fail */
2692 if (we_are_hibernating()) {
2693 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2694 END_STREAM_REASON_HIBERNATING
, NULL
);
2695 connection_free(TO_CONN(n_stream
));
2699 n_stream
->on_circuit
= circ
;
2701 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2702 tor_assert(or_circ
);
2703 if (or_circ
->p_conn
&& !tor_addr_is_null(&or_circ
->p_conn
->real_addr
))
2704 tor_addr_copy(&n_stream
->_base
.addr
, &or_circ
->p_conn
->real_addr
);
2705 return connection_exit_connect_dir(n_stream
);
2708 log_debug(LD_EXIT
,"about to start the dns_resolve().");
2710 /* send it off to the gethostbyname farm */
2711 switch (dns_resolve(n_stream
)) {
2712 case 1: /* resolve worked; now n_stream is attached to circ. */
2713 assert_circuit_ok(circ
);
2714 log_debug(LD_EXIT
,"about to call connection_exit_connect().");
2715 connection_exit_connect(n_stream
);
2717 case -1: /* resolve failed */
2718 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
2719 END_STREAM_REASON_RESOLVEFAILED
, NULL
);
2720 /* n_stream got freed. don't touch it. */
2722 case 0: /* resolve added to pending list */
2723 assert_circuit_ok(circ
);
2730 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
2731 * circuit <b>circ</b>;
2732 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2735 connection_exit_begin_resolve(cell_t
*cell
, or_circuit_t
*circ
)
2737 edge_connection_t
*dummy_conn
;
2740 assert_circuit_ok(TO_CIRCUIT(circ
));
2741 relay_header_unpack(&rh
, cell
->payload
);
2742 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
2745 /* This 'dummy_conn' only exists to remember the stream ID
2746 * associated with the resolve request; and to make the
2747 * implementation of dns.c more uniform. (We really only need to
2748 * remember the circuit, the stream ID, and the hostname to be
2749 * resolved; but if we didn't store them in a connection like this,
2750 * the housekeeping in dns.c would get way more complicated.)
2752 dummy_conn
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
2753 dummy_conn
->stream_id
= rh
.stream_id
;
2754 dummy_conn
->_base
.address
= tor_strndup(
2755 (char*)cell
->payload
+RELAY_HEADER_SIZE
,
2757 dummy_conn
->_base
.port
= 0;
2758 dummy_conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2759 dummy_conn
->_base
.purpose
= EXIT_PURPOSE_RESOLVE
;
2761 dummy_conn
->on_circuit
= TO_CIRCUIT(circ
);
2763 /* send it off to the gethostbyname farm */
2764 switch (dns_resolve(dummy_conn
)) {
2765 case -1: /* Impossible to resolve; a resolved cell was sent. */
2766 /* Connection freed; don't touch it. */
2768 case 1: /* The result was cached; a resolved cell was sent. */
2769 if (!dummy_conn
->_base
.marked_for_close
)
2770 connection_free(TO_CONN(dummy_conn
));
2772 case 0: /* resolve added to pending list */
2773 assert_circuit_ok(TO_CIRCUIT(circ
));
2779 /** Connect to conn's specified addr and port. If it worked, conn
2780 * has now been added to the connection_array.
2782 * Send back a connected cell. Include the resolved IP of the destination
2783 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2784 * streams must not reveal what IP they connected to.)
2787 connection_exit_connect(edge_connection_t
*edge_conn
)
2789 const tor_addr_t
*addr
;
2791 connection_t
*conn
= TO_CONN(edge_conn
);
2792 int socket_error
= 0;
2794 if (!connection_edge_is_rendezvous_stream(edge_conn
) &&
2795 router_compare_to_my_exit_policy(edge_conn
)) {
2796 log_info(LD_EXIT
,"%s:%d failed exit policy. Closing.",
2797 escaped_safe_str_client(conn
->address
), conn
->port
);
2798 connection_edge_end(edge_conn
, END_STREAM_REASON_EXITPOLICY
);
2799 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2800 connection_free(conn
);
2807 log_debug(LD_EXIT
,"about to try connecting");
2808 switch (connection_connect(conn
, conn
->address
, addr
, port
, &socket_error
)) {
2810 /* XXX021 use socket_error below rather than trying to piece things
2811 * together from the current errno, which may have been clobbered. */
2812 connection_edge_end_errno(edge_conn
);
2813 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2814 connection_free(conn
);
2817 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
2819 connection_watch_events(conn
, READ_EVENT
| WRITE_EVENT
);
2820 /* writable indicates finish;
2821 * readable/error indicates broken link in windows-land. */
2823 /* case 1: fall through */
2826 conn
->state
= EXIT_CONN_STATE_OPEN
;
2827 if (connection_wants_to_flush(conn
)) {
2828 /* in case there are any queued data cells */
2829 log_warn(LD_BUG
,"newly connected conn had data waiting!");
2830 // connection_start_writing(conn);
2832 connection_watch_events(conn
, READ_EVENT
);
2834 /* also, deliver a 'connected' cell back through the circuit. */
2835 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
2836 /* rendezvous stream */
2837 /* don't send an address back! */
2838 connection_edge_send_command(edge_conn
,
2839 RELAY_COMMAND_CONNECTED
,
2841 } else { /* normal stream */
2842 char connected_payload
[20];
2843 int connected_payload_len
;
2844 if (tor_addr_family(&conn
->addr
) == AF_INET
) {
2845 set_uint32(connected_payload
, tor_addr_to_ipv4n(&conn
->addr
));
2846 connected_payload_len
= 4;
2848 memcpy(connected_payload
, tor_addr_to_in6_addr8(&conn
->addr
), 16);
2849 connected_payload_len
= 16;
2851 set_uint32(connected_payload
+connected_payload_len
,
2852 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
2853 connected_payload_len
+= 4;
2854 connection_edge_send_command(edge_conn
,
2855 RELAY_COMMAND_CONNECTED
,
2856 connected_payload
, connected_payload_len
);
2860 /** Given an exit conn that should attach to us as a directory server, open a
2861 * bridge connection with a linked connection pair, create a new directory
2862 * conn, and join them together. Return 0 on success (or if there was an
2863 * error we could send back an end cell for). Return -(some circuit end
2864 * reason) if the circuit needs to be torn down. Either connects
2865 * <b>exitconn</b>, frees it, or marks it, as appropriate.
2868 connection_exit_connect_dir(edge_connection_t
*exitconn
)
2870 dir_connection_t
*dirconn
= NULL
;
2871 or_circuit_t
*circ
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
2873 log_info(LD_EXIT
, "Opening local connection for anonymized directory exit");
2875 exitconn
->_base
.state
= EXIT_CONN_STATE_OPEN
;
2877 dirconn
= dir_connection_new(AF_INET
);
2879 tor_addr_copy(&dirconn
->_base
.addr
, &exitconn
->_base
.addr
);
2880 dirconn
->_base
.port
= 0;
2881 dirconn
->_base
.address
= tor_strdup(exitconn
->_base
.address
);
2882 dirconn
->_base
.type
= CONN_TYPE_DIR
;
2883 dirconn
->_base
.purpose
= DIR_PURPOSE_SERVER
;
2884 dirconn
->_base
.state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
2886 /* Note that the new dir conn belongs to the same tunneled request as
2887 * the edge conn, so that we can measure download times. */
2888 TO_CONN(dirconn
)->dirreq_id
= TO_CONN(exitconn
)->dirreq_id
;
2890 connection_link_connections(TO_CONN(dirconn
), TO_CONN(exitconn
));
2892 if (connection_add(TO_CONN(exitconn
))<0) {
2893 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
2894 connection_free(TO_CONN(exitconn
));
2895 connection_free(TO_CONN(dirconn
));
2899 /* link exitconn to circ, now that we know we can use it. */
2900 exitconn
->next_stream
= circ
->n_streams
;
2901 circ
->n_streams
= exitconn
;
2903 if (connection_add(TO_CONN(dirconn
))<0) {
2904 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
2905 connection_close_immediate(TO_CONN(exitconn
));
2906 connection_mark_for_close(TO_CONN(exitconn
));
2907 connection_free(TO_CONN(dirconn
));
2911 connection_start_reading(TO_CONN(dirconn
));
2912 connection_start_reading(TO_CONN(exitconn
));
2914 if (connection_edge_send_command(exitconn
,
2915 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0) {
2916 connection_mark_for_close(TO_CONN(exitconn
));
2917 connection_mark_for_close(TO_CONN(dirconn
));
2924 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2925 * it is a general stream.
2928 connection_edge_is_rendezvous_stream(edge_connection_t
*conn
)
2931 if (conn
->rend_data
)
2936 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2937 * to exit from it, or 0 if it probably will not allow it.
2938 * (We might be uncertain if conn's destination address has not yet been
2941 * If <b>excluded_means_no</b> is 1 and Exclude*Nodes is set and excludes
2942 * this relay, return 0.
2945 connection_ap_can_use_exit(edge_connection_t
*conn
, routerinfo_t
*exit
,
2946 int excluded_means_no
)
2948 or_options_t
*options
= get_options();
2951 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
2952 tor_assert(conn
->socks_request
);
2955 /* If a particular exit node has been requested for the new connection,
2956 * make sure the exit node of the existing circuit matches exactly.
2958 if (conn
->chosen_exit_name
) {
2959 routerinfo_t
*chosen_exit
=
2960 router_get_by_nickname(conn
->chosen_exit_name
, 1);
2961 if (!chosen_exit
|| memcmp(chosen_exit
->cache_info
.identity_digest
,
2962 exit
->cache_info
.identity_digest
, DIGEST_LEN
)) {
2964 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2965 // conn->chosen_exit_name, exit->nickname);
2970 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
&&
2971 !conn
->use_begindir
) {
2974 addr_policy_result_t r
;
2975 if (tor_inet_aton(conn
->socks_request
->address
, &in
))
2976 addr
= ntohl(in
.s_addr
);
2977 r
= compare_addr_to_addr_policy(addr
, conn
->socks_request
->port
,
2979 if (r
== ADDR_POLICY_REJECTED
)
2980 return 0; /* We know the address, and the exit policy rejects it. */
2981 if (r
== ADDR_POLICY_PROBABLY_REJECTED
&& !conn
->chosen_exit_name
)
2982 return 0; /* We don't know the addr, but the exit policy rejects most
2983 * addresses with this port. Since the user didn't ask for
2984 * this node, err on the side of caution. */
2985 } else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
2986 /* Can't support reverse lookups without eventdns. */
2987 if (conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE_PTR
&&
2988 exit
->has_old_dnsworkers
)
2991 /* Don't send DNS requests to non-exit servers by default. */
2992 if (!conn
->chosen_exit_name
&& policy_is_reject_star(exit
->exit_policy
))
2995 if (options
->_ExcludeExitNodesUnion
&&
2996 (options
->StrictNodes
|| excluded_means_no
) &&
2997 routerset_contains_router(options
->_ExcludeExitNodesUnion
, exit
)) {
2998 /* If we are trying to avoid this node as exit, and we have StrictNodes
2999 * set, then this is not a suitable exit. Refuse it.
3001 * If we don't have StrictNodes set, then this function gets called in
3002 * two contexts. First, we've got a circuit open and we want to know
3003 * whether we can use it. In that case, we somehow built this circuit
3004 * despite having the last hop in ExcludeExitNodes, so we should be
3005 * willing to use it. Second, we are evaluating whether this is an
3006 * acceptable exit for a new circuit. In that case, skip it. */
3013 /** If address is of the form "y.onion" with a well-formed handle y:
3014 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
3016 * If address is of the form "y.exit" and <b>allowdotexit</b> is true:
3017 * Put a NUL after y and return EXIT_HOSTNAME.
3020 * Return NORMAL_HOSTNAME and change nothing.
3023 parse_extended_hostname(char *address
, int allowdotexit
)
3026 char query
[REND_SERVICE_ID_LEN_BASE32
+1];
3028 s
= strrchr(address
,'.');
3030 return NORMAL_HOSTNAME
; /* no dot, thus normal */
3031 if (!strcmp(s
+1,"exit")) {
3033 *s
= 0; /* NUL-terminate it */
3034 return EXIT_HOSTNAME
; /* .exit */
3036 log_warn(LD_APP
, "The \".exit\" notation is disabled in Tor due to "
3037 "security risks. Set AllowDotExit in your torrc to enable "
3039 /* FFFF send a controller event too to notify Vidalia users */
3040 return BAD_HOSTNAME
;
3043 if (strcmp(s
+1,"onion"))
3044 return NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
3046 /* so it is .onion */
3047 *s
= 0; /* NUL-terminate it */
3048 if (strlcpy(query
, address
, REND_SERVICE_ID_LEN_BASE32
+1) >=
3049 REND_SERVICE_ID_LEN_BASE32
+1)
3051 if (rend_valid_service_id(query
)) {
3052 return ONION_HOSTNAME
; /* success */
3055 /* otherwise, return to previous state and return 0 */
3057 return BAD_HOSTNAME
;