1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char connection_edge_c_id
[] =
10 * \file connection_edge.c
11 * \brief Handle edge streams.
16 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
17 #include <linux/netfilter_ipv4.h>
18 #define TRANS_NETFILTER
21 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
23 #include <net/pfvar.h>
27 /** List of exit_redirect_t for every configured RedirectExit. */
28 static smartlist_t
*redirect_exit_list
= NULL
;
30 static int connection_ap_handshake_process_socks(edge_connection_t
*conn
);
31 static int connection_ap_process_natd(edge_connection_t
*conn
);
32 static int connection_exit_connect_dir(edge_connection_t
*exitconn
);
34 /** An AP stream has failed/finished. If it hasn't already sent back
35 * a socks reply, send one now (based on endreason). Also set
36 * has_sent_end to 1, and mark the conn.
39 _connection_mark_unattached_ap(edge_connection_t
*conn
, int endreason
,
40 int line
, const char *file
)
42 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
43 conn
->_base
.edge_has_sent_end
= 1; /* no circ yet */
45 if (conn
->_base
.marked_for_close
) {
46 /* This call will warn as appropriate. */
47 _connection_mark_for_close(TO_CONN(conn
), line
, file
);
51 if (!conn
->socks_request
->has_finished
) {
52 if (endreason
& END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
)
54 "stream (marked at %s:%d) sending two socks replies?",
57 if (SOCKS_COMMAND_IS_CONNECT(conn
->socks_request
->command
))
58 connection_ap_handshake_socks_reply(conn
, NULL
, 0, endreason
);
59 else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
60 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_ERROR
,
62 else /* unknown or no handshake at all. send no response. */
63 conn
->socks_request
->has_finished
= 1;
66 _connection_mark_for_close(TO_CONN(conn
), line
, file
);
67 conn
->_base
.hold_open_until_flushed
= 1;
68 conn
->end_reason
= endreason
;
71 /** There was an EOF. Send an end and mark the connection for close.
74 connection_edge_reached_eof(edge_connection_t
*conn
)
76 if (buf_datalen(conn
->_base
.inbuf
) &&
77 connection_state_is_open(TO_CONN(conn
))) {
78 /* it still has stuff to process. don't let it die yet. */
81 log_info(LD_EDGE
,"conn (fd %d) reached eof. Closing.", conn
->_base
.s
);
82 if (!conn
->_base
.marked_for_close
) {
83 /* only mark it if not already marked. it's possible to
84 * get the 'end' right around when the client hangs up on us. */
85 connection_edge_end(conn
, END_STREAM_REASON_DONE
);
86 if (conn
->socks_request
) /* eof, so don't send a socks reply back */
87 conn
->socks_request
->has_finished
= 1;
88 connection_mark_for_close(TO_CONN(conn
));
93 /** Handle new bytes on conn->inbuf based on state:
94 * - If it's waiting for socks info, try to read another step of the
95 * socks handshake out of conn->inbuf.
96 * - If it's waiting for the original destination, fetch it.
97 * - If it's open, then package more relay cells from the stream.
98 * - Else, leave the bytes on inbuf alone for now.
100 * Mark and return -1 if there was an unexpected error with the conn,
104 connection_edge_process_inbuf(edge_connection_t
*conn
, int package_partial
)
108 switch (conn
->_base
.state
) {
109 case AP_CONN_STATE_SOCKS_WAIT
:
110 if (connection_ap_handshake_process_socks(conn
) < 0) {
115 case AP_CONN_STATE_NATD_WAIT
:
116 if (connection_ap_process_natd(conn
) < 0) {
121 case AP_CONN_STATE_OPEN
:
122 case EXIT_CONN_STATE_OPEN
:
123 if (connection_edge_package_raw_inbuf(conn
, package_partial
) < 0) {
124 /* (We already sent an end cell if possible) */
125 connection_mark_for_close(TO_CONN(conn
));
129 case EXIT_CONN_STATE_CONNECTING
:
130 case AP_CONN_STATE_RENDDESC_WAIT
:
131 case AP_CONN_STATE_CIRCUIT_WAIT
:
132 case AP_CONN_STATE_CONNECT_WAIT
:
133 case AP_CONN_STATE_RESOLVE_WAIT
:
134 case AP_CONN_STATE_CONTROLLER_WAIT
:
136 "data from edge while in '%s' state. Leaving it on buffer.",
137 conn_state_to_string(conn
->_base
.type
, conn
->_base
.state
));
140 log_warn(LD_BUG
,"Got unexpected state %d. Closing.",conn
->_base
.state
);
141 tor_fragile_assert();
142 connection_edge_end(conn
, END_STREAM_REASON_INTERNAL
);
143 connection_mark_for_close(TO_CONN(conn
));
147 /** This edge needs to be closed, because its circuit has closed.
148 * Mark it for close and return 0.
151 connection_edge_destroy(uint16_t circ_id
, edge_connection_t
*conn
)
153 if (!conn
->_base
.marked_for_close
) {
155 "CircID %d: At an edge. Marking connection for close.", circ_id
);
156 if (conn
->_base
.type
== CONN_TYPE_AP
) {
157 connection_mark_unattached_ap(conn
, END_STREAM_REASON_DESTROY
);
159 /* closing the circuit, nothing to send an END to */
160 conn
->_base
.edge_has_sent_end
= 1;
161 conn
->end_reason
= END_STREAM_REASON_DESTROY
;
162 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
163 if (conn
->_base
.type
== CONN_TYPE_AP
)
164 control_event_stream_status(conn
, STREAM_EVENT_CLOSED
,
165 END_STREAM_REASON_DESTROY
);
166 connection_mark_for_close(TO_CONN(conn
));
167 conn
->_base
.hold_open_until_flushed
= 1;
170 conn
->cpath_layer
= NULL
;
171 conn
->on_circuit
= NULL
;
175 /** Send a relay end cell from stream <b>conn</b> down conn's circuit. Set
176 * the relay end cell's reason for closing as <b>reason</b>.
178 * Return -1 if this function has already been called on this conn,
182 connection_edge_end(edge_connection_t
*conn
, char reason
)
184 char payload
[RELAY_PAYLOAD_SIZE
];
185 size_t payload_len
=1;
188 if (conn
->_base
.edge_has_sent_end
) {
189 log_warn(LD_BUG
,"(Harmless.) Calling connection_edge_end (reason %d) "
190 "on an already ended stream?", reason
);
191 tor_fragile_assert();
195 if (conn
->_base
.marked_for_close
) {
197 "called on conn that's already marked for close at %s:%d.",
198 conn
->_base
.marked_for_close_file
, conn
->_base
.marked_for_close
);
203 if (reason
== END_STREAM_REASON_EXITPOLICY
&&
204 !connection_edge_is_rendezvous_stream(conn
)) {
205 set_uint32(payload
+1, htonl(conn
->_base
.addr
));
206 set_uint32(payload
+5, htonl(dns_clip_ttl(conn
->address_ttl
)));
210 circ
= circuit_get_by_edge_conn(conn
);
211 if (circ
&& !circ
->marked_for_close
) {
212 log_debug(LD_EDGE
,"Sending end on conn (fd %d).",conn
->_base
.s
);
213 connection_edge_send_command(conn
, RELAY_COMMAND_END
,
214 payload
, payload_len
);
216 log_debug(LD_EDGE
,"No circ to send end on conn (fd %d).",
220 conn
->_base
.edge_has_sent_end
= 1;
221 conn
->end_reason
= reason
;
225 /** An error has just occured on an operation on an edge connection
226 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
227 * appropriate relay end cell to the other end of the connection's circuit.
230 connection_edge_end_errno(edge_connection_t
*conn
)
234 reason
= (uint8_t)errno_to_end_reason(tor_socket_errno(conn
->_base
.s
));
235 return connection_edge_end(conn
, reason
);
238 /** Connection <b>conn</b> has finished writing and has no bytes left on
241 * If it's in state 'open', stop writing, consider responding with a
242 * sendme, and return.
243 * Otherwise, stop writing and return.
245 * If <b>conn</b> is broken, mark it for close and return -1, else
249 connection_edge_finished_flushing(edge_connection_t
*conn
)
253 switch (conn
->_base
.state
) {
254 case AP_CONN_STATE_OPEN
:
255 case EXIT_CONN_STATE_OPEN
:
256 connection_stop_writing(TO_CONN(conn
));
257 connection_edge_consider_sending_sendme(conn
);
259 case AP_CONN_STATE_SOCKS_WAIT
:
260 case AP_CONN_STATE_NATD_WAIT
:
261 case AP_CONN_STATE_RENDDESC_WAIT
:
262 case AP_CONN_STATE_CIRCUIT_WAIT
:
263 case AP_CONN_STATE_CONNECT_WAIT
:
264 case AP_CONN_STATE_CONTROLLER_WAIT
:
265 connection_stop_writing(TO_CONN(conn
));
268 log_warn(LD_BUG
, "Called in unexpected state %d.",conn
->_base
.state
);
269 tor_fragile_assert();
275 /** Connected handler for exit connections: start writing pending
276 * data, deliver 'CONNECTED' relay cells as appropriate, and check
277 * any pending data that may have been received. */
279 connection_edge_finished_connecting(edge_connection_t
*edge_conn
)
281 char valbuf
[INET_NTOA_BUF_LEN
];
285 tor_assert(edge_conn
);
286 tor_assert(edge_conn
->_base
.type
== CONN_TYPE_EXIT
);
287 conn
= TO_CONN(edge_conn
);
288 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
290 in
.s_addr
= htonl(conn
->addr
);
291 tor_inet_ntoa(&in
,valbuf
,sizeof(valbuf
));
292 log_info(LD_EXIT
,"Exit connection to %s:%u (%s) established.",
293 escaped_safe_str(conn
->address
),conn
->port
,safe_str(valbuf
));
295 conn
->state
= EXIT_CONN_STATE_OPEN
;
296 connection_watch_events(conn
, EV_READ
); /* stop writing, continue reading */
297 if (connection_wants_to_flush(conn
)) /* in case there are any queued relay
299 connection_start_writing(conn
);
300 /* deliver a 'connected' relay cell back through the circuit. */
301 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
302 if (connection_edge_send_command(edge_conn
,
303 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0)
304 return 0; /* circuit is closed, don't continue */
306 char connected_payload
[8];
307 set_uint32(connected_payload
, htonl(conn
->addr
));
308 set_uint32(connected_payload
+4,
309 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
310 if (connection_edge_send_command(edge_conn
,
311 RELAY_COMMAND_CONNECTED
,
312 connected_payload
, 8) < 0)
313 return 0; /* circuit is closed, don't continue */
315 tor_assert(edge_conn
->package_window
> 0);
316 /* in case the server has written anything */
317 return connection_edge_process_inbuf(edge_conn
, 1);
320 /** Define a schedule for how long to wait between retrying
321 * application connections. Rather than waiting a fixed amount of
322 * time between each retry, we wait 10 seconds each for the first
323 * two tries, and 15 seconds for each retry after
324 * that. Hopefully this will improve the expected user experience. */
326 compute_retry_timeout(edge_connection_t
*conn
)
328 if (conn
->num_socks_retries
< 2) /* try 0 and try 1 */
333 /** Find all general-purpose AP streams waiting for a response that sent their
334 * begin/resolve cell >=15 seconds ago. Detach from their current circuit, and
335 * mark their current circuit as unsuitable for new streams. Then call
336 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
337 * available) or launch a new one.
339 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
343 connection_ap_expire_beginning(void)
345 edge_connection_t
*conn
;
347 time_t now
= time(NULL
);
348 or_options_t
*options
= get_options();
352 smartlist_t
*conns
= get_connection_array();
354 SMARTLIST_FOREACH(conns
, connection_t
*, c
,
356 if (c
->type
!= CONN_TYPE_AP
)
358 conn
= TO_EDGE_CONN(c
);
359 /* if it's an internal bridge connection, don't yell its status. */
360 severity
= (!conn
->_base
.addr
&& !conn
->_base
.port
)
361 ? LOG_INFO
: LOG_NOTICE
;
362 seconds_idle
= now
- conn
->_base
.timestamp_lastread
;
364 if (AP_CONN_STATE_IS_UNATTACHED(conn
->_base
.state
)) {
365 if (seconds_idle
>= options
->SocksTimeout
) {
366 log_fn(severity
, LD_APP
,
367 "Tried for %d seconds to get a connection to %s:%d. "
369 seconds_idle
, safe_str(conn
->socks_request
->address
),
370 conn
->socks_request
->port
,
371 conn_state_to_string(CONN_TYPE_AP
, conn
->_base
.state
));
372 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
377 if (conn
->_base
.state
== AP_CONN_STATE_OPEN
)
380 /* We're in state connect_wait or resolve_wait now -- waiting for a
381 * reply to our relay cell. See if we want to retry/give up. */
383 cutoff
= compute_retry_timeout(conn
);
384 if (seconds_idle
< cutoff
)
386 circ
= circuit_get_by_edge_conn(conn
);
387 if (!circ
) { /* it's vanished? */
388 log_info(LD_APP
,"Conn is waiting (address %s), but lost its circ.",
389 safe_str(conn
->socks_request
->address
));
390 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
393 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
394 if (seconds_idle
>= options
->SocksTimeout
) {
395 log_fn(severity
, LD_REND
,
396 "Rend stream is %d seconds late. Giving up on address"
399 safe_str(conn
->socks_request
->address
));
400 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
401 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TIMEOUT
);
405 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
406 log_fn(cutoff
< 15 ? LOG_INFO
: severity
, LD_APP
,
407 "We tried for %d seconds to connect to '%s' using exit '%s'."
408 " Retrying on a new circuit.",
409 seconds_idle
, safe_str(conn
->socks_request
->address
),
411 conn
->cpath_layer
->extend_info
->nickname
: "*unnamed*");
412 /* send an end down the circuit */
413 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
414 /* un-mark it as ending, since we're going to reuse it */
415 conn
->_base
.edge_has_sent_end
= 0;
416 conn
->end_reason
= 0;
417 /* kludge to make us not try this circuit again, yet to allow
418 * current streams on it to survive if they can: make it
419 * unattractive to use for new streams */
420 tor_assert(circ
->timestamp_dirty
);
421 circ
->timestamp_dirty
-= options
->MaxCircuitDirtiness
;
422 /* give our stream another 'cutoff' seconds to try */
423 conn
->_base
.timestamp_lastread
+= cutoff
;
424 if (conn
->num_socks_retries
< 250) /* avoid overflow */
425 conn
->num_socks_retries
++;
426 /* move it back into 'pending' state, and try to attach. */
427 if (connection_ap_detach_retriable(conn
, TO_ORIGIN_CIRCUIT(circ
),
428 END_STREAM_REASON_TIMEOUT
)<0) {
429 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
431 }); /* end foreach */
434 /** Tell any AP streams that are waiting for a new circuit to try again,
435 * either attaching to an available circ or launching a new one.
438 connection_ap_attach_pending(void)
440 edge_connection_t
*edge_conn
;
441 smartlist_t
*conns
= get_connection_array();
442 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
444 if (conn
->marked_for_close
||
445 conn
->type
!= CONN_TYPE_AP
||
446 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
448 edge_conn
= TO_EDGE_CONN(conn
);
449 if (connection_ap_handshake_attach_circuit(edge_conn
) < 0) {
450 connection_mark_unattached_ap(edge_conn
, END_STREAM_REASON_CANT_ATTACH
);
455 /** A circuit failed to finish on its last hop <b>info</b>. If there
456 * are any streams waiting with this exit node in mind, but they
457 * don't absolutely require it, make them give up on it.
460 circuit_discard_optional_exit_enclaves(extend_info_t
*info
)
462 edge_connection_t
*edge_conn
;
463 routerinfo_t
*r1
, *r2
;
465 smartlist_t
*conns
= get_connection_array();
466 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
468 if (conn
->marked_for_close
||
469 conn
->type
!= CONN_TYPE_AP
||
470 !conn
->chosen_exit_optional
)
472 edge_conn
= TO_EDGE_CONN(conn
);
473 r1
= router_get_by_nickname(edge_conn
->chosen_exit_name
, 0);
474 r2
= router_get_by_nickname(info
->nickname
, 0);
475 if (r1
&& r2
&& r1
==r2
) {
476 tor_assert(edge_conn
->socks_request
);
477 log_info(LD_APP
, "Giving up on enclave exit '%s' for destination %s.",
478 safe_str(edge_conn
->chosen_exit_name
),
479 escaped_safe_str(edge_conn
->socks_request
->address
));
480 conn
->chosen_exit_optional
= 0;
481 tor_free(edge_conn
->chosen_exit_name
); /* clears it */
486 /** The AP connection <b>conn</b> has just failed while attaching or
487 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
488 * might work. Detach the circuit, and either reattach it, launch a
489 * new circuit, tell the controller, or give up as a appropriate.
491 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
494 connection_ap_detach_retriable(edge_connection_t
*conn
, origin_circuit_t
*circ
,
497 control_event_stream_status(conn
, STREAM_EVENT_FAILED_RETRIABLE
, reason
);
498 conn
->_base
.timestamp_lastread
= time(NULL
);
499 if (! get_options()->LeaveStreamsUnattached
) {
500 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
501 circuit_detach_stream(TO_CIRCUIT(circ
),conn
);
502 return connection_ap_handshake_attach_circuit(conn
);
504 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
505 circuit_detach_stream(TO_CIRCUIT(circ
),conn
);
510 /** A client-side struct to remember requests to rewrite addresses
511 * to new addresses. These structs are stored in the hash table
512 * "addressmap" below.
514 * There are 5 ways to set an address mapping:
515 * - A MapAddress command from the controller [permanent]
516 * - An AddressMap directive in the torrc [permanent]
517 * - When a TrackHostExits torrc directive is triggered [temporary]
518 * - When a dns resolve succeeds [temporary]
519 * - When a dns resolve fails [temporary]
521 * When an addressmap request is made but one is already registered,
522 * the new one is replaced only if the currently registered one has
523 * no "new_address" (that is, it's in the process of dns resolve),
524 * or if the new one is permanent (expires==0 or 1).
526 * (We overload the 'expires' field, using "0" for mappings set via
527 * the configuration file, "1" for mappings set from the control
528 * interface, and other values for DNS mappings that can expire.)
533 int num_resolve_failures
;
534 } addressmap_entry_t
;
536 /** Entry for mapping addresses to which virtual address we mapped them to. */
539 char *hostname_address
;
540 } virtaddress_entry_t
;
542 /** A hash table to store client-side address rewrite instructions. */
543 static strmap_t
*addressmap
=NULL
;
545 * Table mapping addresses to which virtual address, if any, we
548 * We maintain the following invariant: if [A,B] is in
549 * virtaddress_reversemap, then B must be a virtual address, and [A,B]
550 * must be in addressmap. We do not require that the converse hold:
551 * if it fails, then we could end up mapping two virtual addresses to
552 * the same address, which is no disaster.
554 static strmap_t
*virtaddress_reversemap
=NULL
;
556 /** Initialize addressmap. */
558 addressmap_init(void)
560 addressmap
= strmap_new();
561 virtaddress_reversemap
= strmap_new();
564 /** Free the memory associated with the addressmap entry <b>_ent</b>. */
566 addressmap_ent_free(void *_ent
)
568 addressmap_entry_t
*ent
= _ent
;
569 tor_free(ent
->new_address
);
573 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
575 addressmap_virtaddress_ent_free(void *_ent
)
577 virtaddress_entry_t
*ent
= _ent
;
578 tor_free(ent
->ipv4_address
);
579 tor_free(ent
->hostname_address
);
583 /** Free storage held by a virtaddress_entry_t* entry in <b>ent</b>. */
585 addressmap_virtaddress_remove(const char *address
, addressmap_entry_t
*ent
)
587 if (ent
&& ent
->new_address
&&
588 address_is_in_virtual_range(ent
->new_address
)) {
589 virtaddress_entry_t
*ve
=
590 strmap_get(virtaddress_reversemap
, ent
->new_address
);
591 /*log_fn(LOG_NOTICE,"remove reverse mapping for %s",ent->new_address);*/
593 if (!strcmp(address
, ve
->ipv4_address
))
594 tor_free(ve
->ipv4_address
);
595 if (!strcmp(address
, ve
->hostname_address
))
596 tor_free(ve
->hostname_address
);
597 if (!ve
->ipv4_address
&& !ve
->hostname_address
) {
599 strmap_remove(virtaddress_reversemap
, ent
->new_address
);
605 /** Remove <b>ent</b> (which must be mapped to by <b>address</b>) from the
606 * client address maps. */
608 addressmap_ent_remove(const char *address
, addressmap_entry_t
*ent
)
610 addressmap_virtaddress_remove(address
, ent
);
611 addressmap_ent_free(ent
);
614 /** Remove all entries from the addressmap that were set via the
615 * configuration file or the command line. */
617 addressmap_clear_configured(void)
619 addressmap_get_mappings(NULL
, 0, 0);
622 /** Remove all entries from the addressmap that are set to expire, ever. */
624 addressmap_clear_transient(void)
626 addressmap_get_mappings(NULL
, 2, TIME_MAX
);
629 /** Clean out entries from the addressmap cache that were
630 * added long enough ago that they are no longer valid.
633 addressmap_clean(time_t now
)
635 addressmap_get_mappings(NULL
, 2, now
);
638 /** Free all the elements in the addressmap, and free the addressmap
641 addressmap_free_all(void)
644 strmap_free(addressmap
, addressmap_ent_free
);
647 if (virtaddress_reversemap
) {
648 strmap_free(virtaddress_reversemap
, addressmap_virtaddress_ent_free
);
649 virtaddress_reversemap
= NULL
;
653 /** Look at address, and rewrite it until it doesn't want any
654 * more rewrites; but don't get into an infinite loop.
655 * Don't write more than maxlen chars into address. Return true if the
656 * address changed; false otherwise.
659 addressmap_rewrite(char *address
, size_t maxlen
)
661 addressmap_entry_t
*ent
;
665 for (rewrites
= 0; rewrites
< 16; rewrites
++) {
666 ent
= strmap_get(addressmap
, address
);
668 if (!ent
|| !ent
->new_address
)
669 return (rewrites
> 0); /* done, no rewrite needed */
671 cp
= tor_strdup(escaped_safe_str(ent
->new_address
));
672 log_info(LD_APP
, "Addressmap: rewriting %s to %s",
673 escaped_safe_str(address
), cp
);
675 strlcpy(address
, ent
->new_address
, maxlen
);
678 "Loop detected: we've rewritten %s 16 times! Using it as-is.",
679 escaped_safe_str(address
));
680 /* it's fine to rewrite a rewrite, but don't loop forever */
684 /** If we have a cached reverse DNS entry for the address stored in the
685 * <b>maxlen</b>-byte buffer <b>address</b> (typically, a dotted quad) then
686 * rewrite to the cached value and return 1. Otherwise return 0. */
688 addressmap_rewrite_reverse(char *address
, size_t maxlen
)
690 size_t len
= maxlen
+ 16;
691 char *s
= tor_malloc(len
), *cp
;
692 addressmap_entry_t
*ent
;
694 tor_snprintf(s
, len
, "REVERSE[%s]", address
);
695 ent
= strmap_get(addressmap
, s
);
697 cp
= tor_strdup(escaped_safe_str(ent
->new_address
));
698 log_info(LD_APP
, "Rewrote reverse lookup %s -> %s",
699 escaped_safe_str(s
), cp
);
701 strlcpy(address
, ent
->new_address
, maxlen
);
708 /** Return 1 if <b>address</b> is already registered, else return 0 */
710 addressmap_have_mapping(const char *address
)
712 return strmap_get_lc(addressmap
, address
) ? 1 : 0;
715 /** Register a request to map <b>address</b> to <b>new_address</b>,
716 * which will expire on <b>expires</b> (or 0 if never expires from
717 * config file, 1 if never expires from controller, 2 if never expires
718 * (virtual address mapping) from the controller.)
720 * <b>new_address</b> should be a newly dup'ed string, which we'll use or
721 * free as appropriate. We will leave address alone.
723 * If <b>new_address</b> is NULL, or equal to <b>address</b>, remove
724 * any mappings that exist from <b>address</b>.
727 addressmap_register(const char *address
, char *new_address
, time_t expires
)
729 addressmap_entry_t
*ent
;
731 ent
= strmap_get(addressmap
, address
);
732 if (!new_address
|| !strcasecmp(address
,new_address
)) {
733 /* Remove the mapping, if any. */
734 tor_free(new_address
);
736 addressmap_ent_remove(address
,ent
);
737 strmap_remove(addressmap
, address
);
741 if (!ent
) { /* make a new one and register it */
742 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
743 strmap_set(addressmap
, address
, ent
);
744 } else if (ent
->new_address
) { /* we need to clean up the old mapping. */
746 log_info(LD_APP
,"Temporary addressmap ('%s' to '%s') not performed, "
747 "since it's already mapped to '%s'",
748 safe_str(address
), safe_str(new_address
), safe_str(ent
->new_address
));
749 tor_free(new_address
);
752 if (address_is_in_virtual_range(ent
->new_address
) &&
754 /* XXX This isn't the perfect test; we want to avoid removing
755 * mappings set from the control interface _as virtual mapping */
756 addressmap_virtaddress_remove(address
, ent
);
758 tor_free(ent
->new_address
);
759 } /* else { we have an in-progress resolve with no mapping. } */
761 ent
->new_address
= new_address
;
762 ent
->expires
= expires
==2 ? 1 : expires
;
763 ent
->num_resolve_failures
= 0;
765 log_info(LD_CONFIG
, "Addressmap: (re)mapped '%s' to '%s'",
766 safe_str(address
), safe_str(ent
->new_address
));
767 control_event_address_mapped(address
, ent
->new_address
, expires
);
770 /** An attempt to resolve <b>address</b> failed at some OR.
771 * Increment the number of resolve failures we have on record
772 * for it, and then return that number.
775 client_dns_incr_failures(const char *address
)
777 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
779 ent
= tor_malloc_zero(sizeof(addressmap_entry_t
));
780 ent
->expires
= time(NULL
) + MAX_DNS_ENTRY_AGE
;
781 strmap_set(addressmap
,address
,ent
);
783 ++ent
->num_resolve_failures
;
784 log_info(LD_APP
, "Address %s now has %d resolve failures.",
785 safe_str(address
), ent
->num_resolve_failures
);
786 return ent
->num_resolve_failures
;
789 /** If <b>address</b> is in the client dns addressmap, reset
790 * the number of resolve failures we have on record for it.
791 * This is used when we fail a stream because it won't resolve:
792 * otherwise future attempts on that address will only try once.
795 client_dns_clear_failures(const char *address
)
797 addressmap_entry_t
*ent
= strmap_get(addressmap
, address
);
799 ent
->num_resolve_failures
= 0;
802 /** Record the fact that <b>address</b> resolved to <b>name</b>.
803 * We can now use this in subsequent streams via addressmap_rewrite()
804 * so we can more correctly choose an exit that will allow <b>address</b>.
806 * If <b>exitname</b> is defined, then append the addresses with
807 * ".exitname.exit" before registering the mapping.
809 * If <b>ttl</b> is nonnegative, the mapping will be valid for
810 * <b>ttl</b>seconds; otherwise, we use the default.
813 client_dns_set_addressmap_impl(const char *address
, const char *name
,
814 const char *exitname
,
817 /* <address>.<hex or nickname>.exit\0 or just <address>\0 */
818 char extendedaddress
[MAX_SOCKS_ADDR_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
819 /* 123.123.123.123.<hex or nickname>.exit\0 or just 123.123.123.123\0 */
820 char extendedval
[INET_NTOA_BUF_LEN
+MAX_VERBOSE_NICKNAME_LEN
+10];
826 ttl
= DEFAULT_DNS_TTL
;
828 ttl
= dns_clip_ttl(ttl
);
831 /* XXXX fails to ever get attempts to get an exit address of
832 * google.com.digest[=~]nickname.exit; we need a syntax for this that
833 * won't make strict RFC952-compliant applications (like us) barf. */
834 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
835 "%s.%s.exit", address
, exitname
);
836 tor_snprintf(extendedval
, sizeof(extendedval
),
837 "%s.%s.exit", name
, exitname
);
839 tor_snprintf(extendedaddress
, sizeof(extendedaddress
),
841 tor_snprintf(extendedval
, sizeof(extendedval
),
844 addressmap_register(extendedaddress
, tor_strdup(extendedval
),
848 /** Record the fact that <b>address</b> resolved to <b>val</b>.
849 * We can now use this in subsequent streams via addressmap_rewrite()
850 * so we can more correctly choose an exit that will allow <b>address</b>.
852 * If <b>exitname</b> is defined, then append the addresses with
853 * ".exitname.exit" before registering the mapping.
855 * If <b>ttl</b> is nonnegative, the mapping will be valid for
856 * <b>ttl</b>seconds; otherwise, we use the default.
859 client_dns_set_addressmap(const char *address
, uint32_t val
,
860 const char *exitname
,
864 char valbuf
[INET_NTOA_BUF_LEN
];
868 if (tor_inet_aton(address
, &in
))
869 return; /* If address was an IP address already, don't add a mapping. */
870 in
.s_addr
= htonl(val
);
871 tor_inet_ntoa(&in
,valbuf
,sizeof(valbuf
));
873 client_dns_set_addressmap_impl(address
, valbuf
, exitname
, ttl
);
876 /** Add a cache entry noting that <b>address</b> (ordinarily a dotted quad)
877 * resolved via a RESOLVE_PTR request to the hostname <b>v</b>.
879 * If <b>exitname</b> is defined, then append the addresses with
880 * ".exitname.exit" before registering the mapping.
882 * If <b>ttl</b> is nonnegative, the mapping will be valid for
883 * <b>ttl</b>seconds; otherwise, we use the default.
886 client_dns_set_reverse_addressmap(const char *address
, const char *v
,
887 const char *exitname
,
890 size_t len
= strlen(address
) + 16;
891 char *s
= tor_malloc(len
);
892 tor_snprintf(s
, len
, "REVERSE[%s]", address
);
893 client_dns_set_addressmap_impl(s
, v
, exitname
, ttl
);
897 /* By default, we hand out 127.192.0.1 through 127.254.254.254.
898 * These addresses should map to localhost, so even if the
899 * application accidentally tried to connect to them directly (not
900 * via Tor), it wouldn't get too far astray.
902 * These options are configured by parse_virtual_addr_network().
904 static uint32_t virtual_addr_network
= 0x7fc00000u
;
905 static uint32_t virtual_addr_netmask
= 0xffc00000u
;
906 static int virtual_addr_netmask_bits
= 10;
907 static uint32_t next_virtual_addr
= 0x7fc00000u
;
909 /** Read a netmask of the form 127.192.0.0/10 from "val", and check whether
910 * it's a valid set of virtual addresses to hand out in response to MAPADDRESS
911 * requests. Return 0 on success; set *msg (if provided) to a newly allocated
912 * string and return -1 on failure. If validate_only is false, sets the
913 * actual virtual address range to the parsed value. */
915 parse_virtual_addr_network(const char *val
, int validate_only
,
919 uint16_t port_min
, port_max
;
922 if (parse_addr_and_port_range(val
, &addr
, &mask
, &port_min
, &port_max
)) {
923 if (msg
) *msg
= tor_strdup("Error parsing VirtualAddressNetwork");
927 if (port_min
!= 1 || port_max
!= 65535) {
928 if (msg
) *msg
= tor_strdup("Can't specify ports on VirtualAddressNetwork");
932 bits
= addr_mask_get_bits(mask
);
934 if (msg
) *msg
= tor_strdup("VirtualAddressNetwork must have a mask that "
935 "can be expressed as a prefix");
940 if (msg
) *msg
= tor_strdup("VirtualAddressNetwork expects a /16 "
941 "network or larger");
948 virtual_addr_network
= addr
& mask
;
949 virtual_addr_netmask
= mask
;
950 virtual_addr_netmask_bits
= bits
;
952 if ((next_virtual_addr
& mask
) != addr
)
953 next_virtual_addr
= addr
;
959 * Return true iff <b>addr</b> is likely to have been returned by
960 * client_dns_get_unused_address.
963 address_is_in_virtual_range(const char *address
)
967 if (!strcasecmpend(address
, ".virtual")) {
969 } else if (tor_inet_aton(address
, &in
)) {
970 uint32_t addr
= ntohl(in
.s_addr
);
971 if ((addr
& virtual_addr_netmask
) == virtual_addr_network
)
977 /** Return a newly allocated string holding an address of <b>type</b>
978 * (one of RESOLVED_TYPE_{IPV4|HOSTNAME}) that has not yet been mapped,
979 * and that is very unlikely to be the address of any real host.
982 addressmap_get_virtual_address(int type
)
987 if (type
== RESOLVED_TYPE_HOSTNAME
) {
990 crypto_rand(rand
, sizeof(rand
));
991 base32_encode(buf
,sizeof(buf
),rand
,sizeof(rand
));
992 strlcat(buf
, ".virtual", sizeof(buf
));
993 } while (strmap_get(addressmap
, buf
));
994 return tor_strdup(buf
);
995 } else if (type
== RESOLVED_TYPE_IPV4
) {
996 // This is an imperfect estimate of how many addresses are available, but
998 uint32_t available
= 1u << (32-virtual_addr_netmask_bits
);
1000 /* Don't hand out any .0 or .255 address. */
1001 while ((next_virtual_addr
& 0xff) == 0 ||
1002 (next_virtual_addr
& 0xff) == 0xff) {
1003 ++next_virtual_addr
;
1005 in
.s_addr
= htonl(next_virtual_addr
);
1006 tor_inet_ntoa(&in
, buf
, sizeof(buf
));
1007 if (!strmap_get(addressmap
, buf
))
1010 ++next_virtual_addr
;
1012 log_info(LD_CONFIG
, "%d addrs available", (int)available
);
1013 if (! --available
) {
1014 log_warn(LD_CONFIG
, "Ran out of virtual addresses!");
1017 if ((next_virtual_addr
& virtual_addr_netmask
) != virtual_addr_network
)
1018 next_virtual_addr
= virtual_addr_network
;
1020 return tor_strdup(buf
);
1022 log_warn(LD_BUG
, "Called with unsupported address type (%d)", type
);
1027 /** A controller has requested that we map some address of type
1028 * <b>type</b> to the address <b>new_address</b>. Choose an address
1029 * that is unlikely to be used, and map it, and return it in a newly
1030 * allocated string. If another address of the same type is already
1031 * mapped to <b>new_address</b>, try to return a copy of that address.
1033 * The string in <b>new_address</b> may be freed, or inserted into a map
1037 addressmap_register_virtual_address(int type
, char *new_address
)
1040 virtaddress_entry_t
*vent
;
1042 tor_assert(new_address
);
1043 tor_assert(addressmap
);
1044 tor_assert(virtaddress_reversemap
);
1046 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1048 vent
= tor_malloc_zero(sizeof(virtaddress_entry_t
));
1049 strmap_set(virtaddress_reversemap
, new_address
, vent
);
1052 addrp
= (type
== RESOLVED_TYPE_IPV4
) ?
1053 &vent
->ipv4_address
: &vent
->hostname_address
;
1055 addressmap_entry_t
*ent
= strmap_get(addressmap
, *addrp
);
1056 if (ent
&& ent
->new_address
&&
1057 !strcasecmp(new_address
, ent
->new_address
)) {
1058 tor_free(new_address
);
1059 return tor_strdup(*addrp
);
1062 "Internal confusion: I thought that '%s' was mapped to by "
1063 "'%s', but '%s' really maps to '%s'. This is a harmless bug.",
1064 safe_str(new_address
), safe_str(*addrp
), safe_str(*addrp
),
1065 ent
?safe_str(ent
->new_address
):"(nothing)");
1069 *addrp
= addressmap_get_virtual_address(type
);
1070 log_info(LD_APP
, "Registering map from %s to %s", *addrp
, new_address
);
1071 addressmap_register(*addrp
, new_address
, 2);
1075 /* Try to catch possible bugs */
1076 addressmap_entry_t
*ent
;
1077 ent
= strmap_get(addressmap
, *addrp
);
1079 tor_assert(!strcasecmp(ent
->new_address
,new_address
));
1080 vent
= strmap_get(virtaddress_reversemap
, new_address
);
1082 tor_assert(!strcasecmp(*addrp
,
1083 (type
== RESOLVED_TYPE_IPV4
) ?
1084 vent
->ipv4_address
: vent
->hostname_address
));
1085 log_info(LD_APP
, "Map from %s to %s okay.",
1086 safe_str(*addrp
),safe_str(new_address
));
1093 /** Return 1 if <b>address</b> has funny characters in it like colons. Return
1094 * 0 if it's fine, or if we're configured to allow it anyway. <b>client</b>
1095 * should be true if we're using this address as a client; false if we're
1096 * using it as a server.
1099 address_is_invalid_destination(const char *address
, int client
)
1102 if (get_options()->AllowNonRFC953Hostnames
)
1105 if (get_options()->ServerDNSAllowNonRFC953Hostnames
)
1110 if (TOR_ISALNUM(*address
) ||
1113 *address
== '_') /* Underscore is not allowed, but Windows does it
1114 * sometimes, just to thumb its nose at the IETF. */
1122 /** Iterate over all address mappings which have expiry times between
1123 * min_expires and max_expires, inclusive. If sl is provided, add an
1124 * "old-addr new-addr" string to sl for each mapping. If sl is NULL,
1125 * remove the mappings.
1128 addressmap_get_mappings(smartlist_t
*sl
, time_t min_expires
,
1131 strmap_iter_t
*iter
;
1134 addressmap_entry_t
*val
;
1139 for (iter
= strmap_iter_init(addressmap
); !strmap_iter_done(iter
); ) {
1140 strmap_iter_get(iter
, &key
, &_val
);
1142 if (val
->expires
>= min_expires
&& val
->expires
<= max_expires
) {
1144 iter
= strmap_iter_next_rmv(addressmap
,iter
);
1145 addressmap_ent_remove(key
, val
);
1147 } else if (val
->new_address
) {
1148 size_t len
= strlen(key
)+strlen(val
->new_address
)+2;
1149 char *line
= tor_malloc(len
);
1150 tor_snprintf(line
, len
, "%s %s", key
, val
->new_address
);
1151 smartlist_add(sl
, line
);
1154 iter
= strmap_iter_next(addressmap
,iter
);
1158 /** Connection <b>conn</b> just finished its socks handshake, or the
1159 * controller asked us to take care of it. If <b>circ</b> is defined,
1160 * then that's where we'll want to attach it. Otherwise we have to
1161 * figure it out ourselves.
1163 * First, parse whether it's a .exit address, remap it, and so on. Then
1164 * if it's for a general circuit, try to attach it to a circuit (or launch
1165 * one as needed), else if it's for a rendezvous circuit, fetch a
1166 * rendezvous descriptor first (or attach/launch a circuit if the
1167 * rendezvous descriptor is already here and fresh enough).
1169 * The stream will exit from the hop
1170 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1171 * <b>cpath</b> is NULL.
1174 connection_ap_handshake_rewrite_and_attach(edge_connection_t
*conn
,
1175 origin_circuit_t
*circ
,
1176 crypt_path_t
*cpath
)
1178 socks_request_t
*socks
= conn
->socks_request
;
1179 hostname_type_t addresstype
;
1180 or_options_t
*options
= get_options();
1181 struct in_addr addr_tmp
;
1183 char orig_address
[MAX_SOCKS_ADDR_LEN
];
1185 tor_strlower(socks
->address
); /* normalize it */
1186 strlcpy(orig_address
, socks
->address
, sizeof(orig_address
));
1187 log_debug(LD_APP
,"Client asked for %s:%d",
1188 safe_str(socks
->address
),
1191 if (socks
->command
== SOCKS_COMMAND_RESOLVE
&&
1192 !tor_inet_aton(socks
->address
, &addr_tmp
) &&
1193 options
->AutomapHostsOnResolve
&& options
->AutomapHostsSuffixes
) {
1194 SMARTLIST_FOREACH(options
->AutomapHostsSuffixes
, const char *, cp
,
1195 if (!strcasecmpend(socks
->address
, cp
)) {
1200 const char *new_addr
;
1201 new_addr
= addressmap_register_virtual_address(
1202 RESOLVED_TYPE_IPV4
, tor_strdup(socks
->address
));
1203 tor_assert(new_addr
);
1204 log_info(LD_APP
, "Automapping %s to %s",
1205 escaped_safe_str(socks
->address
), safe_str(new_addr
));
1206 strlcpy(socks
->address
, new_addr
, sizeof(socks
->address
));
1210 if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1211 if (addressmap_rewrite_reverse(socks
->address
, sizeof(socks
->address
))) {
1212 char *result
= tor_strdup(socks
->address
);
1213 /* remember _what_ is supposed to have been resolved. */
1214 strlcpy(socks
->address
, orig_address
, sizeof(socks
->address
));
1215 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_HOSTNAME
,
1216 strlen(result
), result
, -1);
1217 connection_mark_unattached_ap(conn
,
1218 END_STREAM_REASON_DONE
|
1219 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1222 } else if (!automap
) {
1223 /* For address map controls, remap the address. */
1224 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
))) {
1225 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1226 REMAP_STREAM_SOURCE_CACHE
);
1230 if (!automap
&& address_is_in_virtual_range(socks
->address
)) {
1231 /* This address was probably handed out by client_dns_get_unmapped_address,
1232 * but the mapping was discarded for some reason. We *don't* want to send
1233 * the address through Tor; that's likely to fail, and may leak
1236 log_warn(LD_APP
,"Missing mapping for virtual address '%s'. Refusing.",
1237 socks
->address
); /* don't safe_str() this yet. */
1238 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INTERNAL
);
1242 /* Parse the address provided by SOCKS. Modify it in-place if it
1243 * specifies a hidden-service (.onion) or particular exit node (.exit).
1245 addresstype
= parse_extended_hostname(socks
->address
);
1247 if (addresstype
== BAD_HOSTNAME
) {
1248 log_warn(LD_APP
, "Invalid hostname %s; rejecting", socks
->address
);
1249 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1250 escaped(socks
->address
));
1251 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1255 if (addresstype
== EXIT_HOSTNAME
) {
1256 /* foo.exit -- modify conn->chosen_exit_node to specify the exit
1257 * node, and conn->address to hold only the address portion.*/
1258 char *s
= strrchr(socks
->address
,'.');
1259 tor_assert(!automap
);
1262 conn
->chosen_exit_name
= tor_strdup(s
+1);
1265 log_warn(LD_APP
,"Malformed exit address '%s.exit'. Refusing.",
1266 safe_str(socks
->address
));
1267 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1268 escaped(socks
->address
));
1269 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1274 conn
->chosen_exit_name
= tor_strdup(socks
->address
);
1275 r
= router_get_by_nickname(conn
->chosen_exit_name
, 1);
1276 *socks
->address
= 0;
1278 strlcpy(socks
->address
, r
->address
, sizeof(socks
->address
));
1281 "Unrecognized server in exit address '%s.exit'. Refusing.",
1282 safe_str(socks
->address
));
1283 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1289 if (addresstype
!= ONION_HOSTNAME
) {
1290 /* not a hidden-service request (i.e. normal or .exit) */
1291 if (address_is_invalid_destination(socks
->address
, 1)) {
1292 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1293 escaped(socks
->address
));
1295 "Destination '%s' seems to be an invalid hostname. Failing.",
1296 safe_str(socks
->address
));
1297 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1301 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
1304 /* Reply to resolves immediately if we can. */
1305 if (strlen(socks
->address
) > RELAY_PAYLOAD_SIZE
) {
1306 log_warn(LD_APP
,"Address to be resolved is too large. Failing.");
1307 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1308 escaped(socks
->address
));
1309 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
1311 connection_mark_unattached_ap(conn
,
1312 END_STREAM_REASON_SOCKSPROTOCOL
|
1313 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1316 if (tor_inet_aton(socks
->address
, &in
)) { /* see if it's an IP already */
1317 /* leave it in network order */
1319 /* remember _what_ is supposed to have been resolved. */
1320 strlcpy(socks
->address
, orig_address
, sizeof(socks
->address
));
1321 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
1323 connection_mark_unattached_ap(conn
,
1324 END_STREAM_REASON_DONE
|
1325 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1328 tor_assert(!automap
);
1329 rep_hist_note_used_resolve(time(NULL
)); /* help predict this next time */
1330 } else if (socks
->command
== SOCKS_COMMAND_CONNECT
) {
1331 tor_assert(!automap
);
1332 if (socks
->port
== 0) {
1333 log_notice(LD_APP
,"Application asked to connect to port 0. Refusing.");
1334 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1338 if (!conn
->chosen_exit_name
&& !circ
) {
1339 /* see if we can find a suitable enclave exit */
1341 router_find_exact_exit_enclave(socks
->address
, socks
->port
);
1344 "Redirecting address %s to exit at enclave router %s",
1345 safe_str(socks
->address
), r
->nickname
);
1346 /* use the hex digest, not nickname, in case there are two
1347 routers with this nickname */
1348 conn
->chosen_exit_name
=
1349 tor_strdup(hex_str(r
->cache_info
.identity_digest
, DIGEST_LEN
));
1350 conn
->_base
.chosen_exit_optional
= 1;
1354 /* help predict this next time */
1355 rep_hist_note_used_port(socks
->port
, time(NULL
));
1356 } else if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1357 rep_hist_note_used_resolve(time(NULL
)); /* help predict this next time */
1358 } else if (socks
->command
== SOCKS_COMMAND_CONNECT_DIR
) {
1361 tor_fragile_assert();
1363 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1364 if ((circ
&& connection_ap_handshake_attach_chosen_circuit(
1365 conn
, circ
, cpath
) < 0) ||
1367 connection_ap_handshake_attach_circuit(conn
) < 0)) {
1368 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);//xxxdup
1373 /* it's a hidden-service request */
1374 rend_cache_entry_t
*entry
;
1376 tor_assert(!automap
);
1377 if (SOCKS_COMMAND_IS_RESOLVE(socks
->command
)) {
1378 /* if it's a resolve request, fail it right now, rather than
1379 * building all the circuits and then realizing it won't work. */
1381 "Resolve requests to hidden services not allowed. Failing.");
1382 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
1384 connection_mark_unattached_ap(conn
,
1385 END_STREAM_REASON_SOCKSPROTOCOL
|
1386 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1391 log_warn(LD_CONTROL
, "Attachstream to a circuit is not "
1392 "supported for .onion addresses currently. Failing.");
1393 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1397 strlcpy(conn
->rend_query
, socks
->address
, sizeof(conn
->rend_query
));
1398 log_info(LD_REND
,"Got a hidden service request for ID '%s'",
1399 safe_str(conn
->rend_query
));
1400 /* see if we already have it cached */
1401 r
= rend_cache_lookup_entry(conn
->rend_query
, -1, &entry
);
1403 log_warn(LD_BUG
,"Invalid service name '%s'",
1404 safe_str(conn
->rend_query
));
1405 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1409 conn
->_base
.state
= AP_CONN_STATE_RENDDESC_WAIT
;
1410 log_info(LD_REND
, "Unknown descriptor %s. Fetching.",
1411 safe_str(conn
->rend_query
));
1412 rend_client_refetch_renddesc(conn
->rend_query
);
1413 } else { /* r > 0 */
1414 /** How long after we receive a hidden service descriptor do we consider
1416 #define NUM_SECONDS_BEFORE_HS_REFETCH (60*15)
1417 if (time(NULL
) - entry
->received
< NUM_SECONDS_BEFORE_HS_REFETCH
) {
1418 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1419 log_info(LD_REND
, "Descriptor is here and fresh enough. Great.");
1420 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
1421 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1425 conn
->_base
.state
= AP_CONN_STATE_RENDDESC_WAIT
;
1426 log_info(LD_REND
, "Stale descriptor %s. Refetching.",
1427 safe_str(conn
->rend_query
));
1428 rend_client_refetch_renddesc(conn
->rend_query
);
1433 return 0; /* unreached but keeps the compiler happy */
1437 static int pf_socket
= -1;
1442 /* Ideally, this should be opened before dropping privs. */
1447 /* only works on OpenBSD */
1448 pf
= open("/dev/pf", O_RDONLY
);
1450 /* works on NetBSD and FreeBSD */
1451 pf
= open("/dev/pf", O_RDWR
);
1455 log_warn(LD_NET
, "open(\"/dev/pf\") failed: %s", strerror(errno
));
1464 /** Fetch the original destination address and port from a
1465 * system-specific interface and put them into a
1466 * socks_request_t as if they came from a socks request.
1468 * Return -1 if an error prevents fetching the destination,
1472 connection_ap_get_original_destination(edge_connection_t
*conn
,
1473 socks_request_t
*req
)
1475 #ifdef TRANS_NETFILTER
1477 struct sockaddr_in orig_dst
;
1478 socklen_t orig_dst_len
= sizeof(orig_dst
);
1479 char tmpbuf
[INET_NTOA_BUF_LEN
];
1481 if (getsockopt(conn
->_base
.s
, SOL_IP
, SO_ORIGINAL_DST
,
1482 (struct sockaddr
*)&orig_dst
, &orig_dst_len
) < 0) {
1483 int e
= tor_socket_errno(conn
->_base
.s
);
1484 log_warn(LD_NET
, "getsockopt() failed: %s", tor_socket_strerror(e
));
1488 tor_inet_ntoa(&orig_dst
.sin_addr
, tmpbuf
, sizeof(tmpbuf
));
1489 strlcpy(req
->address
, tmpbuf
, sizeof(req
->address
));
1490 req
->port
= ntohs(orig_dst
.sin_port
);
1493 #elif defined(TRANS_PF)
1494 struct sockaddr_in proxy_addr
;
1495 socklen_t proxy_addr_len
= sizeof(proxy_addr
);
1496 char tmpbuf
[INET_NTOA_BUF_LEN
];
1497 struct pfioc_natlook pnl
;
1500 if (getsockname(conn
->_base
.s
, (struct sockaddr
*)&proxy_addr
,
1501 &proxy_addr_len
) < 0) {
1502 int e
= tor_socket_errno(conn
->_base
.s
);
1503 log_warn(LD_NET
, "getsockname() to determine transocks destination "
1504 "failed: %s", tor_socket_strerror(e
));
1508 memset(&pnl
, 0, sizeof(pnl
));
1510 pnl
.proto
= IPPROTO_TCP
;
1511 pnl
.direction
= PF_OUT
;
1512 pnl
.saddr
.v4
.s_addr
= htonl(conn
->_base
.addr
);
1513 pnl
.sport
= htons(conn
->_base
.port
);
1514 pnl
.daddr
.v4
.s_addr
= proxy_addr
.sin_addr
.s_addr
;
1515 pnl
.dport
= proxy_addr
.sin_port
;
1517 pf
= get_pf_socket();
1521 if (ioctl(pf
, DIOCNATLOOK
, &pnl
) < 0) {
1522 log_warn(LD_NET
, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno
));
1526 tor_inet_ntoa(&pnl
.rdaddr
.v4
, tmpbuf
, sizeof(tmpbuf
));
1527 strlcpy(req
->address
, tmpbuf
, sizeof(req
->address
));
1528 req
->port
= ntohs(pnl
.rdport
);
1534 log_warn(LD_BUG
, "Called connection_ap_get_original_destination, but no "
1535 "transparent proxy method was configured.");
1540 /** connection_edge_process_inbuf() found a conn in state
1541 * socks_wait. See if conn->inbuf has the right bytes to proceed with
1542 * the socks handshake.
1544 * If the handshake is complete, send it to
1545 * connection_ap_handshake_rewrite_and_attach().
1547 * Return -1 if an unexpected error with conn occurs (and mark it for close),
1551 connection_ap_handshake_process_socks(edge_connection_t
*conn
)
1553 socks_request_t
*socks
;
1555 or_options_t
*options
= get_options();
1558 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
1559 tor_assert(conn
->_base
.state
== AP_CONN_STATE_SOCKS_WAIT
);
1560 tor_assert(conn
->socks_request
);
1561 socks
= conn
->socks_request
;
1563 log_debug(LD_APP
,"entered.");
1565 sockshere
= fetch_from_buf_socks(conn
->_base
.inbuf
, socks
,
1566 options
->TestSocks
, options
->SafeSocks
);
1567 if (sockshere
== 0) {
1568 if (socks
->replylen
) {
1569 connection_write_to_buf(socks
->reply
, socks
->replylen
, TO_CONN(conn
));
1570 /* zero it out so we can do another round of negotiation */
1571 socks
->replylen
= 0;
1573 log_debug(LD_APP
,"socks handshake not all here yet.");
1576 } else if (sockshere
== -1) {
1577 if (socks
->replylen
) { /* we should send reply back */
1578 log_debug(LD_APP
,"reply is already set for us. Using it.");
1579 connection_ap_handshake_socks_reply(conn
, socks
->reply
, socks
->replylen
,
1580 END_STREAM_REASON_SOCKSPROTOCOL
);
1583 log_warn(LD_APP
,"Fetching socks handshake failed. Closing.");
1584 connection_ap_handshake_socks_reply(conn
, NULL
, 0,
1585 END_STREAM_REASON_SOCKSPROTOCOL
);
1587 connection_mark_unattached_ap(conn
,
1588 END_STREAM_REASON_SOCKSPROTOCOL
|
1589 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1591 } /* else socks handshake is done, continue processing */
1593 if (hostname_is_noconnect_address(socks
->address
))
1595 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1596 control_event_stream_status(conn
, STREAM_EVENT_CLOSED
, 0);
1597 connection_mark_unattached_ap(conn
, END_STREAM_REASON_DONE
);
1601 if (SOCKS_COMMAND_IS_CONNECT(socks
->command
))
1602 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1604 control_event_stream_status(conn
, STREAM_EVENT_NEW_RESOLVE
, 0);
1606 if (options
->LeaveStreamsUnattached
) {
1607 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1610 return connection_ap_handshake_rewrite_and_attach(conn
, NULL
, NULL
);
1613 /** connection_init_accepted_conn() found a new trans AP conn.
1614 * Get the original destination and send it to
1615 * connection_ap_handshake_rewrite_and_attach().
1617 * Return -1 if an unexpected error with conn (and it should be marked
1618 * for close), else return 0.
1621 connection_ap_process_transparent(edge_connection_t
*conn
)
1623 socks_request_t
*socks
;
1624 or_options_t
*options
= get_options();
1627 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
1628 tor_assert(conn
->socks_request
);
1629 socks
= conn
->socks_request
;
1631 /* pretend that a socks handshake completed so we don't try to
1632 * send a socks reply down a transparent conn */
1633 socks
->command
= SOCKS_COMMAND_CONNECT
;
1634 socks
->has_finished
= 1;
1636 log_debug(LD_APP
,"entered.");
1638 if (connection_ap_get_original_destination(conn
, socks
) < 0) {
1639 log_warn(LD_APP
,"Fetching original destination failed. Closing.");
1640 connection_mark_unattached_ap(conn
,
1641 END_STREAM_REASON_CANT_FETCH_ORIG_DEST
);
1644 /* we have the original destination */
1646 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1648 if (options
->LeaveStreamsUnattached
) {
1649 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1652 return connection_ap_handshake_rewrite_and_attach(conn
, NULL
, NULL
);
1655 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
1656 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
1657 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
1658 * form of the original destination.
1660 * If the original destination is complete, send it to
1661 * connection_ap_handshake_rewrite_and_attach().
1663 * Return -1 if an unexpected error with conn (and it should be marked
1664 * for close), else return 0.
1667 connection_ap_process_natd(edge_connection_t
*conn
)
1669 char tmp_buf
[36], *tbuf
, *daddr
;
1672 socks_request_t
*socks
;
1673 or_options_t
*options
= get_options();
1676 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
1677 tor_assert(conn
->_base
.state
== AP_CONN_STATE_NATD_WAIT
);
1678 tor_assert(conn
->socks_request
);
1679 socks
= conn
->socks_request
;
1681 log_debug(LD_APP
,"entered.");
1683 /* look for LF-terminated "[DEST ip_addr port]"
1684 * where ip_addr is a dotted-quad and port is in string form */
1685 err
= fetch_from_buf_line_lf(conn
->_base
.inbuf
, tmp_buf
, &tlen
);
1689 log_warn(LD_APP
,"Natd handshake failed (DEST too long). Closing");
1690 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1694 if (strcmpstart(tmp_buf
, "[DEST ")) {
1695 log_warn(LD_APP
,"Natd handshake was ill-formed; closing. The client "
1698 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1702 daddr
= tbuf
= &tmp_buf
[0] + 6; /* after end of "[DEST " */
1703 while (*tbuf
!= '\0' && *tbuf
!= ' ')
1708 /* pretend that a socks handshake completed so we don't try to
1709 * send a socks reply down a natd conn */
1710 strlcpy(socks
->address
, daddr
, sizeof(socks
->address
));
1711 socks
->port
= (uint16_t)
1712 tor_parse_long(tbuf
, 10, 1, 65535, &port_ok
, &daddr
);
1714 log_warn(LD_APP
,"Natd handshake failed; port %s is ill-formed or out "
1715 "of range.", escaped(tbuf
));
1716 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
1720 socks
->command
= SOCKS_COMMAND_CONNECT
;
1721 socks
->has_finished
= 1;
1723 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
1725 if (options
->LeaveStreamsUnattached
) {
1726 conn
->_base
.state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1729 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1731 return connection_ap_handshake_rewrite_and_attach(conn
, NULL
, NULL
);
1734 /** Iterate over the two bytes of stream_id until we get one that is not
1735 * already in use; return it. Return 0 if can't get a unique stream_id.
1738 get_unique_stream_id_by_circ(origin_circuit_t
*circ
)
1740 edge_connection_t
*tmpconn
;
1741 uint16_t test_stream_id
;
1742 uint32_t attempts
=0;
1745 test_stream_id
= circ
->next_stream_id
++;
1746 if (++attempts
> 1<<16) {
1747 /* Make sure we don't loop forever if all stream_id's are used. */
1748 log_warn(LD_APP
,"No unused stream IDs. Failing.");
1751 if (test_stream_id
== 0)
1753 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
1754 if (tmpconn
->stream_id
== test_stream_id
)
1756 return test_stream_id
;
1759 /** Write a relay begin cell, using destaddr and destport from ap_conn's
1760 * socks_request field, and send it down circ.
1762 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1765 connection_ap_handshake_send_begin(edge_connection_t
*ap_conn
)
1767 char payload
[CELL_PAYLOAD_SIZE
];
1770 origin_circuit_t
*circ
;
1771 tor_assert(ap_conn
->on_circuit
);
1772 circ
= TO_ORIGIN_CIRCUIT(ap_conn
->on_circuit
);
1774 tor_assert(ap_conn
->_base
.type
== CONN_TYPE_AP
);
1775 tor_assert(ap_conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1776 tor_assert(ap_conn
->socks_request
);
1777 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn
->socks_request
->command
));
1779 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
1780 if (ap_conn
->stream_id
==0) {
1781 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1782 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_RESOURCELIMIT
);
1786 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:%d",
1787 (circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
) ?
1788 ap_conn
->socks_request
->address
: "",
1789 ap_conn
->socks_request
->port
);
1790 payload_len
= strlen(payload
)+1;
1793 "Sending relay cell to begin stream %d.", ap_conn
->stream_id
);
1795 begin_type
= ap_conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
?
1796 RELAY_COMMAND_BEGIN
: RELAY_COMMAND_BEGIN_DIR
;
1797 if (begin_type
== RELAY_COMMAND_BEGIN
) {
1798 tor_assert(circ
->build_state
->onehop_tunnel
== 0);
1801 if (connection_edge_send_command(ap_conn
, begin_type
,
1802 begin_type
== RELAY_COMMAND_BEGIN
? payload
: NULL
,
1803 begin_type
== RELAY_COMMAND_BEGIN
? payload_len
: 0) < 0)
1804 return -1; /* circuit is closed, don't continue */
1806 ap_conn
->package_window
= STREAMWINDOW_START
;
1807 ap_conn
->deliver_window
= STREAMWINDOW_START
;
1808 ap_conn
->_base
.state
= AP_CONN_STATE_CONNECT_WAIT
;
1809 log_info(LD_APP
,"Address/port sent, ap socket %d, n_circ_id %d",
1810 ap_conn
->_base
.s
, circ
->_base
.n_circ_id
);
1811 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
, 0);
1815 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
1816 * socks_request field, and send it down circ.
1818 * If ap_conn is broken, mark it for close and return -1. Else return 0.
1821 connection_ap_handshake_send_resolve(edge_connection_t
*ap_conn
)
1823 int payload_len
, command
;
1824 const char *string_addr
;
1825 char inaddr_buf
[32];
1826 origin_circuit_t
*circ
;
1827 tor_assert(ap_conn
->on_circuit
);
1828 circ
= TO_ORIGIN_CIRCUIT(ap_conn
->on_circuit
);
1830 tor_assert(ap_conn
->_base
.type
== CONN_TYPE_AP
);
1831 tor_assert(ap_conn
->_base
.state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1832 tor_assert(ap_conn
->socks_request
);
1833 tor_assert(circ
->_base
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
1835 command
= ap_conn
->socks_request
->command
;
1836 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command
));
1838 ap_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
1839 if (ap_conn
->stream_id
==0) {
1840 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1841 circuit_mark_for_close(TO_CIRCUIT(circ
), END_CIRC_REASON_RESOURCELIMIT
);
1845 if (command
== SOCKS_COMMAND_RESOLVE
) {
1846 string_addr
= ap_conn
->socks_request
->address
;
1847 payload_len
= strlen(string_addr
)+1;
1848 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
);
1852 size_t len
= strlen(ap_conn
->socks_request
->address
);
1854 if (!strcasecmpend(ap_conn
->socks_request
->address
, ".in-addr.arpa")) {
1855 c
= ap_conn
->socks_request
->address
[len
-13];
1856 ap_conn
->socks_request
->address
[len
-13] = '\0';
1858 if (tor_inet_aton(ap_conn
->socks_request
->address
, &in
) == 0) {
1859 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
1864 /* this path happens on DNS. Can we unify? XXXX020 */
1865 ap_conn
->socks_request
->address
[len
-13] = c
;
1866 strlcpy(inaddr_buf
, ap_conn
->socks_request
->address
, sizeof(inaddr_buf
));
1868 /* this path happens on tor-resolve. Can we unify? XXXX020 */
1869 a
= ntohl(in
.s_addr
);
1870 tor_snprintf(inaddr_buf
, sizeof(inaddr_buf
), "%d.%d.%d.%d.in-addr.arpa",
1871 (int)(uint8_t)((a
)&0xff),
1872 (int)(uint8_t)((a
>>8 )&0xff),
1873 (int)(uint8_t)((a
>>16)&0xff),
1874 (int)(uint8_t)((a
>>24)&0xff));
1876 string_addr
= inaddr_buf
;
1877 payload_len
= strlen(inaddr_buf
)+1;
1878 tor_assert(payload_len
<= RELAY_PAYLOAD_SIZE
);
1882 "Sending relay cell to begin stream %d.", ap_conn
->stream_id
);
1884 if (connection_edge_send_command(ap_conn
,
1885 RELAY_COMMAND_RESOLVE
,
1886 string_addr
, payload_len
) < 0)
1887 return -1; /* circuit is closed, don't continue */
1889 ap_conn
->_base
.state
= AP_CONN_STATE_RESOLVE_WAIT
;
1890 log_info(LD_APP
,"Address sent for resolve, ap socket %d, n_circ_id %d",
1891 ap_conn
->_base
.s
, circ
->_base
.n_circ_id
);
1892 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
, 0);
1896 /** Make an AP connection_t, do a socketpair and attach one side
1897 * to the conn, connection_add it, initialize it to circuit_wait,
1898 * and call connection_ap_handshake_attach_circuit(conn) on it.
1900 * Return the other end of the socketpair, or -1 if error.
1902 * DOCDOC The above is now wrong; we use links.
1903 * DOCDOC start_reading
1906 connection_ap_make_bridge(char *address
, uint16_t port
,
1907 const char *digest
, int command
)
1909 edge_connection_t
*conn
;
1911 log_notice(LD_APP
,"Making internal anonymized tunnel to %s:%d ...",
1912 safe_str(address
),port
); /* XXXX020 Downgrade back to info. */
1914 conn
= TO_EDGE_CONN(connection_new(CONN_TYPE_AP
));
1915 conn
->_base
.linked
= 1; /* so that we can add it safely below. */
1917 /* populate conn->socks_request */
1919 /* leave version at zero, so the socks_reply is empty */
1920 conn
->socks_request
->socks_version
= 0;
1921 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
1922 strlcpy(conn
->socks_request
->address
, address
,
1923 sizeof(conn
->socks_request
->address
));
1924 conn
->socks_request
->port
= port
;
1925 conn
->socks_request
->command
= command
;
1926 if (command
== SOCKS_COMMAND_CONNECT_DIR
) {
1927 conn
->chosen_exit_name
= tor_malloc(HEX_DIGEST_LEN
+2);
1928 conn
->chosen_exit_name
[0] = '$';
1929 base16_encode(conn
->chosen_exit_name
+1,HEX_DIGEST_LEN
+1,
1930 digest
, DIGEST_LEN
);
1933 conn
->_base
.address
= tor_strdup("(local link)");
1934 conn
->_base
.addr
= 0;
1935 conn
->_base
.port
= 0;
1937 if (connection_add(TO_CONN(conn
)) < 0) { /* no space, forget it */
1938 connection_free(TO_CONN(conn
));
1942 conn
->_base
.state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1944 /* attaching to a dirty circuit is fine */
1945 if (connection_ap_handshake_attach_circuit(conn
) < 0) {
1946 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
1950 log_info(LD_APP
,"... AP bridge created and connected.");
1954 /** Send an answer to an AP connection that has requested a DNS lookup
1955 * via SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or
1956 * -1 for unreachable; the answer should be in the format specified
1957 * in the socks extensions document.
1960 connection_ap_handshake_socks_resolved(edge_connection_t
*conn
,
1970 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
1971 uint32_t a
= ntohl(get_uint32(answer
));
1973 client_dns_set_addressmap(conn
->socks_request
->address
, a
,
1974 conn
->chosen_exit_name
, ttl
);
1975 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
1976 char *cp
= tor_strndup(answer
, answer_len
);
1977 client_dns_set_reverse_addressmap(conn
->socks_request
->address
,
1979 conn
->chosen_exit_name
, ttl
);
1984 if (conn
->dns_server_request
) {
1985 dnsserv_resolved(conn
, answer_type
, answer_len
, answer
, ttl
);
1986 conn
->socks_request
->has_finished
= 1; /* DOCDOC */
1990 if (conn
->socks_request
->socks_version
== 4) {
1991 buf
[0] = 0x00; /* version */
1992 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
1993 buf
[1] = 90; /* "Granted" */
1994 set_uint16(buf
+2, 0);
1995 memcpy(buf
+4, answer
, 4); /* address */
1996 replylen
= SOCKS4_NETWORK_LEN
;
1998 buf
[1] = 91; /* "error" */
1999 memset(buf
+2, 0, 6);
2000 replylen
= SOCKS4_NETWORK_LEN
;
2002 } else if (conn
->socks_request
->socks_version
== 5) {
2004 buf
[0] = 0x05; /* version */
2005 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
2006 buf
[1] = SOCKS5_SUCCEEDED
;
2007 buf
[2] = 0; /* reserved */
2008 buf
[3] = 0x01; /* IPv4 address type */
2009 memcpy(buf
+4, answer
, 4); /* address */
2010 set_uint16(buf
+8, 0); /* port == 0. */
2012 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
2013 buf
[1] = SOCKS5_SUCCEEDED
;
2014 buf
[2] = 0; /* reserved */
2015 buf
[3] = 0x04; /* IPv6 address type */
2016 memcpy(buf
+4, answer
, 16); /* address */
2017 set_uint16(buf
+20, 0); /* port == 0. */
2019 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2020 buf
[1] = SOCKS5_SUCCEEDED
;
2021 buf
[2] = 0; /* reserved */
2022 buf
[3] = 0x03; /* Domainname address type */
2023 buf
[4] = (char)answer_len
;
2024 memcpy(buf
+5, answer
, answer_len
); /* address */
2025 set_uint16(buf
+5+answer_len
, 0); /* port == 0. */
2026 replylen
= 5+answer_len
+2;
2028 buf
[1] = SOCKS5_HOST_UNREACHABLE
;
2029 memset(buf
+2, 0, 8);
2033 /* no socks version info; don't send anything back */
2036 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
2037 (answer_type
== RESOLVED_TYPE_IPV4
||
2038 answer_type
== RESOLVED_TYPE_IPV6
) ?
2039 0 : END_STREAM_REASON_RESOLVEFAILED
);
2042 /** Send a socks reply to stream <b>conn</b>, using the appropriate
2043 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
2046 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
2047 * and return, else reply based on <b>endreason</b> (one of
2048 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
2049 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
2052 connection_ap_handshake_socks_reply(edge_connection_t
*conn
, char *reply
,
2053 size_t replylen
, int endreason
)
2056 socks5_reply_status_t status
=
2057 connection_edge_end_reason_socks5_response(endreason
);
2059 tor_assert(conn
->socks_request
); /* make sure it's an AP stream */
2061 control_event_stream_status(conn
,
2062 status
==SOCKS5_SUCCEEDED
? STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
,
2065 if (conn
->socks_request
->has_finished
) {
2066 log_warn(LD_BUG
, "(Harmless.) duplicate calls to "
2067 "connection_ap_handshake_socks_reply.");
2070 if (replylen
) { /* we already have a reply in mind */
2071 connection_write_to_buf(reply
, replylen
, TO_CONN(conn
));
2072 conn
->socks_request
->has_finished
= 1;
2075 if (conn
->socks_request
->socks_version
== 4) {
2076 memset(buf
,0,SOCKS4_NETWORK_LEN
);
2077 #define SOCKS4_GRANTED 90
2078 #define SOCKS4_REJECT 91
2079 buf
[1] = (status
==SOCKS5_SUCCEEDED
? SOCKS4_GRANTED
: SOCKS4_REJECT
);
2080 /* leave version, destport, destip zero */
2081 connection_write_to_buf(buf
, SOCKS4_NETWORK_LEN
, TO_CONN(conn
));
2082 } else if (conn
->socks_request
->socks_version
== 5) {
2083 buf
[0] = 5; /* version 5 */
2084 buf
[1] = (char)status
;
2086 buf
[3] = 1; /* ipv4 addr */
2087 memset(buf
+4,0,6); /* Set external addr/port to 0.
2088 The spec doesn't seem to say what to do here. -RD */
2089 connection_write_to_buf(buf
,10,TO_CONN(conn
));
2091 /* If socks_version isn't 4 or 5, don't send anything.
2092 * This can happen in the case of AP bridges. */
2093 conn
->socks_request
->has_finished
= 1;
2097 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
2098 * an exit hop for the circuit, or we are the origin and it is a
2101 * Launch a new exit connection and initialize things appropriately.
2103 * If it's a rendezvous stream, call connection_exit_connect() on
2106 * For general streams, call dns_resolve() on it first, and only call
2107 * connection_exit_connect() if the dns answer is already known.
2109 * Note that we don't call connection_add() on the new stream! We wait
2110 * for connection_exit_connect() to do that.
2112 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
2116 connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
)
2118 edge_connection_t
*n_stream
;
2122 char end_payload
[1];
2123 or_circuit_t
*or_circ
= NULL
;
2125 assert_circuit_ok(circ
);
2126 if (!CIRCUIT_IS_ORIGIN(circ
))
2127 or_circ
= TO_OR_CIRCUIT(circ
);
2129 relay_header_unpack(&rh
, cell
->payload
);
2131 /* Note: we have to use relay_send_command_from_edge here, not
2132 * connection_edge_end or connection_edge_send_command, since those require
2133 * that we have a stream connected to a circuit, and we don't connect to a
2134 * circuit until we have a pending/successful resolve. */
2136 if (!server_mode(get_options()) &&
2137 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
2138 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2139 "Relay begin cell at non-server. Closing.");
2140 end_payload
[0] = END_STREAM_REASON_EXITPOLICY
;
2141 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2142 end_payload
, 1, NULL
);
2146 if (rh
.command
== RELAY_COMMAND_BEGIN
) {
2147 if (!memchr(cell
->payload
+RELAY_HEADER_SIZE
, 0, rh
.length
)) {
2148 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2149 "Relay begin cell has no \\0. Closing.");
2150 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2151 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2152 end_payload
, 1, NULL
);
2155 if (parse_addr_port(LOG_PROTOCOL_WARN
, cell
->payload
+RELAY_HEADER_SIZE
,
2156 &address
,NULL
,&port
)<0) {
2157 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2158 "Unable to parse addr:port in relay begin cell. Closing.");
2159 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2160 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2161 end_payload
, 1, NULL
);
2165 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2166 "Missing port in relay begin cell. Closing.");
2167 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2168 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2169 end_payload
, 1, NULL
);
2173 if (or_circ
&& or_circ
->is_first_hop
) {
2174 /* Don't let clients use us as a single-hop proxy; it attracts attackers
2175 * and users who'd be better off with, well, single-hop proxies.
2177 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
2178 "Attempt to open a stream on first hop of circuit. Closing.");
2179 end_payload
[0] = END_STREAM_REASON_TORPROTOCOL
;
2180 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2181 end_payload
, 1, NULL
);
2185 } else if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2186 or_options_t
*options
= get_options();
2187 port
= options
->DirPort
; /* not actually used to open a connection */
2188 if (!port
|| circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
2189 end_payload
[0] = END_STREAM_REASON_NOTDIRECTORY
;
2190 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2191 end_payload
, 1, NULL
);
2194 if (or_circ
&& or_circ
->p_conn
&& or_circ
->p_conn
->_base
.address
)
2195 address
= tor_strdup(or_circ
->p_conn
->_base
.address
);
2197 address
= tor_strdup("127.0.0.1");
2199 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
2200 end_payload
[0] = END_STREAM_REASON_INTERNAL
;
2201 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2202 end_payload
, 1, NULL
);
2206 log_debug(LD_EXIT
,"Creating new exit connection.");
2207 n_stream
= TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT
));
2208 n_stream
->_base
.purpose
= EXIT_PURPOSE_CONNECT
;
2210 n_stream
->stream_id
= rh
.stream_id
;
2211 n_stream
->_base
.port
= port
;
2212 /* leave n_stream->s at -1, because it's not yet valid */
2213 n_stream
->package_window
= STREAMWINDOW_START
;
2214 n_stream
->deliver_window
= STREAMWINDOW_START
;
2216 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
2217 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
2218 log_debug(LD_REND
,"begin is for rendezvous. configuring stream.");
2219 n_stream
->_base
.address
= tor_strdup("(rendezvous)");
2220 n_stream
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
2221 strlcpy(n_stream
->rend_query
, origin_circ
->rend_query
,
2222 sizeof(n_stream
->rend_query
));
2223 tor_assert(connection_edge_is_rendezvous_stream(n_stream
));
2224 assert_circuit_ok(circ
);
2225 if (rend_service_set_connection_addr_port(n_stream
, origin_circ
) < 0) {
2226 log_info(LD_REND
,"Didn't find rendezvous service (port %d)",
2227 n_stream
->_base
.port
);
2228 end_payload
[0] = END_STREAM_REASON_EXITPOLICY
;
2229 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2230 end_payload
, 1, NULL
);
2231 connection_free(TO_CONN(n_stream
));
2232 /* knock the whole thing down, somebody screwed up */
2233 circuit_mark_for_close(circ
, END_CIRC_REASON_CONNECTFAILED
);
2237 assert_circuit_ok(circ
);
2238 log_debug(LD_REND
,"Finished assigning addr/port");
2239 n_stream
->cpath_layer
= origin_circ
->cpath
->prev
; /* link it */
2241 /* add it into the linked list of n_streams on this circuit */
2242 n_stream
->next_stream
= origin_circ
->p_streams
;
2243 n_stream
->on_circuit
= circ
;
2244 origin_circ
->p_streams
= n_stream
;
2245 assert_circuit_ok(circ
);
2247 connection_exit_connect(n_stream
);
2251 tor_strlower(address
);
2252 n_stream
->_base
.address
= address
;
2253 n_stream
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2254 /* default to failed, change in dns_resolve if it turns out not to fail */
2256 if (we_are_hibernating()) {
2257 end_payload
[0] = END_STREAM_REASON_HIBERNATING
;
2258 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2259 end_payload
, 1, NULL
);
2260 connection_free(TO_CONN(n_stream
));
2264 n_stream
->on_circuit
= circ
;
2266 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
2267 tor_assert(or_circ
);
2268 if (or_circ
->p_conn
&& or_circ
->p_conn
->_base
.addr
)
2269 n_stream
->_base
.addr
= or_circ
->p_conn
->_base
.addr
;
2270 return connection_exit_connect_dir(n_stream
);
2273 log_debug(LD_EXIT
,"about to start the dns_resolve().");
2275 /* send it off to the gethostbyname farm */
2276 switch (dns_resolve(n_stream
)) {
2277 case 1: /* resolve worked; now n_stream is attached to circ. */
2278 assert_circuit_ok(circ
);
2279 log_debug(LD_EXIT
,"about to call connection_exit_connect().");
2280 connection_exit_connect(n_stream
);
2282 case -1: /* resolve failed */
2283 end_payload
[0] = END_STREAM_REASON_RESOLVEFAILED
;
2284 relay_send_command_from_edge(rh
.stream_id
, circ
, RELAY_COMMAND_END
,
2285 end_payload
, 1, NULL
);
2286 /* n_stream got freed. don't touch it. */
2288 case 0: /* resolve added to pending list */
2289 assert_circuit_ok(circ
);
2296 * Called when we receive a RELAY_RESOLVE cell 'cell' along the circuit 'circ';
2297 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
2300 connection_exit_begin_resolve(cell_t
*cell
, or_circuit_t
*circ
)
2302 edge_connection_t
*dummy_conn
;
2305 assert_circuit_ok(TO_CIRCUIT(circ
));
2306 relay_header_unpack(&rh
, cell
->payload
);
2308 /* This 'dummy_conn' only exists to remember the stream ID
2309 * associated with the resolve request; and to make the
2310 * implementation of dns.c more uniform. (We really only need to
2311 * remember the circuit, the stream ID, and the hostname to be
2312 * resolved; but if we didn't store them in a connection like this,
2313 * the housekeeping in dns.c would get way more complicated.)
2315 dummy_conn
= TO_EDGE_CONN(connection_new(CONN_TYPE_EXIT
));
2316 dummy_conn
->stream_id
= rh
.stream_id
;
2317 dummy_conn
->_base
.address
= tor_strndup(cell
->payload
+RELAY_HEADER_SIZE
,
2319 dummy_conn
->_base
.port
= 0;
2320 dummy_conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
2321 dummy_conn
->_base
.purpose
= EXIT_PURPOSE_RESOLVE
;
2323 dummy_conn
->on_circuit
= TO_CIRCUIT(circ
);
2325 /* send it off to the gethostbyname farm */
2326 switch (dns_resolve(dummy_conn
)) {
2327 case -1: /* Impossible to resolve; a resolved cell was sent. */
2328 /* Connection freed; don't touch it. */
2330 case 1: /* The result was cached; a resolved cell was sent. */
2331 if (!dummy_conn
->_base
.marked_for_close
)
2332 connection_free(TO_CONN(dummy_conn
));
2334 case 0: /* resolve added to pending list */
2335 assert_circuit_ok(TO_CIRCUIT(circ
));
2341 /** Connect to conn's specified addr and port. If it worked, conn
2342 * has now been added to the connection_array.
2344 * Send back a connected cell. Include the resolved IP of the destination
2345 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
2346 * streams must not reveal what IP they connected to.)
2349 connection_exit_connect(edge_connection_t
*edge_conn
)
2353 connection_t
*conn
= TO_CONN(edge_conn
);
2355 if (!connection_edge_is_rendezvous_stream(edge_conn
) &&
2356 router_compare_to_my_exit_policy(edge_conn
)) {
2357 log_info(LD_EXIT
,"%s:%d failed exit policy. Closing.",
2358 escaped_safe_str(conn
->address
), conn
->port
);
2359 connection_edge_end(edge_conn
, END_STREAM_REASON_EXITPOLICY
);
2360 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2361 connection_free(conn
);
2367 if (redirect_exit_list
) {
2368 SMARTLIST_FOREACH(redirect_exit_list
, exit_redirect_t
*, r
,
2370 if ((addr
&r
->mask
)==(r
->addr
&r
->mask
) &&
2371 (r
->port_min
<= port
) && (port
<= r
->port_max
)) {
2373 if (r
->is_redirect
) {
2374 char tmpbuf
[INET_NTOA_BUF_LEN
];
2375 addr
= r
->addr_dest
;
2376 port
= r
->port_dest
;
2377 in
.s_addr
= htonl(addr
);
2378 tor_inet_ntoa(&in
, tmpbuf
, sizeof(tmpbuf
));
2379 log_debug(LD_EXIT
, "Redirecting connection from %s:%d to %s:%d",
2380 escaped_safe_str(conn
->address
), conn
->port
,
2381 safe_str(tmpbuf
), port
);
2388 log_debug(LD_EXIT
,"about to try connecting");
2389 switch (connection_connect(conn
, conn
->address
, addr
, port
)) {
2391 connection_edge_end_errno(edge_conn
);
2392 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
2393 connection_free(conn
);
2396 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
2398 connection_watch_events(conn
, EV_WRITE
| EV_READ
);
2399 /* writable indicates finish;
2400 * readable/error indicates broken link in windowsland. */
2402 /* case 1: fall through */
2405 conn
->state
= EXIT_CONN_STATE_OPEN
;
2406 if (connection_wants_to_flush(conn
)) {
2407 /* in case there are any queued data cells */
2408 log_warn(LD_BUG
,"newly connected conn had data waiting!");
2409 // connection_start_writing(conn);
2411 connection_watch_events(conn
, EV_READ
);
2413 /* also, deliver a 'connected' cell back through the circuit. */
2414 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
2415 /* rendezvous stream */
2416 /* don't send an address back! */
2417 connection_edge_send_command(edge_conn
,
2418 RELAY_COMMAND_CONNECTED
,
2420 } else { /* normal stream */
2421 /* This must be the original address, not the redirected address. */
2422 char connected_payload
[8];
2423 set_uint32(connected_payload
, htonl(conn
->addr
));
2424 set_uint32(connected_payload
+4,
2425 htonl(dns_clip_ttl(edge_conn
->address_ttl
)));
2426 connection_edge_send_command(edge_conn
,
2427 RELAY_COMMAND_CONNECTED
,
2428 connected_payload
, 8);
2432 /** Given an exit conn that should attach to us as a directory server, open a
2433 * bridge connection with a socketpair, create a new directory conn, and join
2434 * them together. Return 0 on success (or if there was an error we could send
2435 * back an end cell for). Return -(some circuit end reason) if the circuit
2436 * needs to be torn down. Either connects <b>exitconn<b/>, frees it,
2437 * or marks it, as appropriate.
2439 * DOCDOC no longer uses socketpair
2442 connection_exit_connect_dir(edge_connection_t
*exitconn
)
2444 dir_connection_t
*dirconn
= NULL
;
2445 or_circuit_t
*circ
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
2447 log_info(LD_EXIT
, "Opening local connection for anonymized directory exit");
2449 exitconn
->_base
.state
= EXIT_CONN_STATE_OPEN
;
2451 dirconn
= TO_DIR_CONN(connection_new(CONN_TYPE_DIR
));
2453 dirconn
->_base
.addr
= 0x7f000001;
2454 dirconn
->_base
.port
= 0;
2455 dirconn
->_base
.address
= tor_strdup("Tor network");
2456 dirconn
->_base
.type
= CONN_TYPE_DIR
;
2457 dirconn
->_base
.purpose
= DIR_PURPOSE_SERVER
;
2458 dirconn
->_base
.state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
2460 connection_link_connections(TO_CONN(dirconn
), TO_CONN(exitconn
));
2462 if (connection_add(TO_CONN(exitconn
))<0) {
2463 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
2464 connection_free(TO_CONN(exitconn
));
2465 connection_free(TO_CONN(dirconn
));
2469 /* link exitconn to circ, now that we know we can use it. */
2470 exitconn
->next_stream
= circ
->n_streams
;
2471 circ
->n_streams
= exitconn
;
2473 if (connection_add(TO_CONN(dirconn
))<0) {
2474 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
2475 connection_close_immediate(TO_CONN(exitconn
));
2476 connection_mark_for_close(TO_CONN(exitconn
));
2477 connection_free(TO_CONN(dirconn
));
2481 connection_start_reading(TO_CONN(dirconn
));
2482 connection_start_reading(TO_CONN(exitconn
));
2484 if (connection_edge_send_command(exitconn
,
2485 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0) {
2486 connection_mark_for_close(TO_CONN(exitconn
));
2487 connection_mark_for_close(TO_CONN(dirconn
));
2494 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
2495 * it is a general stream.
2498 connection_edge_is_rendezvous_stream(edge_connection_t
*conn
)
2501 if (*conn
->rend_query
) /* XXX */ /* XXXX Why is this XXX? -NM */
2506 /** Return 1 if router <b>exit</b> is likely to allow stream <b>conn</b>
2507 * to exit from it, or 0 if it probably will not allow it.
2508 * (We might be uncertain if conn's destination address has not yet been
2512 connection_ap_can_use_exit(edge_connection_t
*conn
, routerinfo_t
*exit
)
2515 tor_assert(conn
->_base
.type
== CONN_TYPE_AP
);
2516 tor_assert(conn
->socks_request
);
2519 /* If a particular exit node has been requested for the new connection,
2520 * make sure the exit node of the existing circuit matches exactly.
2522 if (conn
->chosen_exit_name
) {
2523 if (router_get_by_nickname(conn
->chosen_exit_name
, 1) != exit
) {
2525 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
2526 // conn->chosen_exit_name, exit->nickname);
2531 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
2534 addr_policy_result_t r
;
2535 if (tor_inet_aton(conn
->socks_request
->address
, &in
))
2536 addr
= ntohl(in
.s_addr
);
2537 r
= compare_addr_to_addr_policy(addr
, conn
->socks_request
->port
,
2539 if (r
== ADDR_POLICY_REJECTED
|| r
== ADDR_POLICY_PROBABLY_REJECTED
)
2541 } else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
2542 /* Can't support reverse lookups without eventdns. */
2543 if (conn
->socks_request
->command
== SOCKS_COMMAND_RESOLVE_PTR
&&
2544 exit
->has_old_dnsworkers
)
2547 /* Don't send DNS requests to non-exit servers by default. */
2548 if (!conn
->chosen_exit_name
&& policy_is_reject_star(exit
->exit_policy
))
2554 /** Make connection redirection follow the provided list of
2555 * exit_redirect_t */
2557 set_exit_redirects(smartlist_t
*lst
)
2559 if (redirect_exit_list
) {
2560 SMARTLIST_FOREACH(redirect_exit_list
, exit_redirect_t
*, p
, tor_free(p
));
2561 smartlist_free(redirect_exit_list
);
2563 redirect_exit_list
= lst
;
2566 /** If address is of the form "y.onion" with a well-formed handle y:
2567 * Put a NUL after y, lower-case it, and return ONION_HOSTNAME.
2569 * If address is of the form "y.exit":
2570 * Put a NUL after y and return EXIT_HOSTNAME.
2573 * Return NORMAL_HOSTNAME and change nothing.
2576 parse_extended_hostname(char *address
)
2579 char query
[REND_SERVICE_ID_LEN
+1];
2581 s
= strrchr(address
,'.');
2583 return NORMAL_HOSTNAME
; /* no dot, thus normal */
2584 if (!strcmp(s
+1,"exit")) {
2585 *s
= 0; /* nul-terminate it */
2586 return EXIT_HOSTNAME
; /* .exit */
2588 if (strcmp(s
+1,"onion"))
2589 return NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
2591 /* so it is .onion */
2592 *s
= 0; /* nul-terminate it */
2593 if (strlcpy(query
, address
, REND_SERVICE_ID_LEN
+1) >=
2594 REND_SERVICE_ID_LEN
+1)
2596 if (rend_valid_service_id(query
)) {
2597 return ONION_HOSTNAME
; /* success */
2600 /* otherwise, return to previous state and return 0 */
2602 return BAD_HOSTNAME
;
2605 /** Check if the address is of the form "y.noconnect"
2608 hostname_is_noconnect_address(const char *address
)
2610 return ! strcasecmpend(address
, ".noconnect");