1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Implements a local cache for DNS results for Tor servers.
9 * This is implemented as a wrapper around Adam Langley's eventdns.c code.
10 * (We can't just use gethostbyname() and friends because we really need to
16 #ifdef HAVE_EVENT2_DNS_H
17 #include <event2/event.h>
18 #include <event2/dns.h>
19 #include <event2/dns_compat.h>
23 #ifndef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
24 #define HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
28 /** Longest hostname we're willing to resolve. */
29 #define MAX_ADDRESSLEN 256
31 /** How long will we wait for an answer from the resolver before we decide
32 * that the resolver is wedged? */
33 #define RESOLVE_MAX_TIMEOUT 300
35 /** Possible outcomes from hostname lookup: permanent failure,
36 * transient (retryable) failure, and success. */
37 #define DNS_RESOLVE_FAILED_TRANSIENT 1
38 #define DNS_RESOLVE_FAILED_PERMANENT 2
39 #define DNS_RESOLVE_SUCCEEDED 3
41 /** Have we currently configured nameservers with eventdns? */
42 static int nameservers_configured
= 0;
43 /** Did our most recent attempt to configure nameservers with eventdns fail? */
44 static int nameserver_config_failed
= 0;
45 /** What was the resolv_conf fname we last used when configuring the
46 * nameservers? Used to check whether we need to reconfigure. */
47 static char *resolv_conf_fname
= NULL
;
48 /** What was the mtime on the resolv.conf file we last used when configuring
49 * the nameservers? Used to check whether we need to reconfigure. */
50 static time_t resolv_conf_mtime
= 0;
52 /** Linked list of connections waiting for a DNS answer. */
53 typedef struct pending_connection_t
{
54 edge_connection_t
*conn
;
55 struct pending_connection_t
*next
;
56 } pending_connection_t
;
58 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
59 * pointers and memory stomping. */
60 #define CACHED_RESOLVE_MAGIC 0x1234F00D
62 /* Possible states for a cached resolve_t */
63 /** We are waiting for the resolver system to tell us an answer here.
64 * When we get one, or when we time out, the state of this cached_resolve_t
65 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
66 * entry. This cached_resolve_t will be in the hash table so that we will
67 * know not to launch more requests for this addr, but rather to add more
68 * connections to the pending list for the addr. */
69 #define CACHE_STATE_PENDING 0
70 /** This used to be a pending cached_resolve_t, and we got an answer for it.
71 * Now we're waiting for this cached_resolve_t to expire. This should
72 * have no pending connections, and should not appear in the hash table. */
73 #define CACHE_STATE_DONE 1
74 /** We are caching an answer for this address. This should have no pending
75 * connections, and should appear in the hash table. */
76 #define CACHE_STATE_CACHED_VALID 2
77 /** We are caching a failure for this address. This should have no pending
78 * connections, and should appear in the hash table */
79 #define CACHE_STATE_CACHED_FAILED 3
81 /** A DNS request: possibly completed, possibly pending; cached_resolve
82 * structs are stored at the OR side in a hash table, and as a linked
83 * list from oldest to newest.
85 typedef struct cached_resolve_t
{
86 HT_ENTRY(cached_resolve_t
) node
;
88 char address
[MAX_ADDRESSLEN
]; /**< The hostname to be resolved. */
91 struct in6_addr addr6
; /**< IPv6 addr for <b>address</b>. */
92 uint32_t addr
; /**< IPv4 addr for <b>address</b>. */
94 char *hostname
; /**< Hostname for <b>address</b> (if a reverse lookup) */
96 uint8_t state
; /**< Is this cached entry pending/done/valid/failed? */
97 uint8_t is_reverse
; /**< Is this a reverse (addr-to-hostname) lookup? */
98 time_t expire
; /**< Remove items from cache after this time. */
99 uint32_t ttl
; /**< What TTL did the nameserver tell us? */
100 /** Connections that want to know when we get an answer for this resolve. */
101 pending_connection_t
*pending_connections
;
104 static void purge_expired_resolves(time_t now
);
105 static void dns_found_answer(const char *address
, uint8_t is_reverse
,
106 uint32_t addr
, const char *hostname
, char outcome
,
108 static void send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
);
109 static int launch_resolve(edge_connection_t
*exitconn
);
110 static void add_wildcarded_test_address(const char *address
);
111 static int configure_nameservers(int force
);
112 static int answer_is_wildcarded(const char *ip
);
113 static int dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
114 or_circuit_t
*oncirc
, char **resolved_to_hostname
);
115 #ifdef DEBUG_DNS_CACHE
116 static void _assert_cache_ok(void);
117 #define assert_cache_ok() _assert_cache_ok()
119 #define assert_cache_ok() STMT_NIL
121 static void assert_resolve_ok(cached_resolve_t
*resolve
);
123 /** Hash table of cached_resolve objects. */
124 static HT_HEAD(cache_map
, cached_resolve_t
) cache_root
;
126 /** Function to compare hashed resolves on their addresses; used to
127 * implement hash tables. */
129 cached_resolves_eq(cached_resolve_t
*a
, cached_resolve_t
*b
)
131 /* make this smarter one day? */
132 assert_resolve_ok(a
); // Not b; b may be just a search.
133 return !strncmp(a
->address
, b
->address
, MAX_ADDRESSLEN
);
136 /** Hash function for cached_resolve objects */
137 static INLINE
unsigned int
138 cached_resolve_hash(cached_resolve_t
*a
)
140 return ht_string_hash(a
->address
);
143 HT_PROTOTYPE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
145 HT_GENERATE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
146 cached_resolves_eq
, 0.6, malloc
, realloc
, free
)
148 /** Initialize the DNS cache. */
152 HT_INIT(cache_map
, &cache_root
);
155 /** Helper: called by eventdns when eventdns wants to log something. */
157 evdns_log_cb(int warn
, const char *msg
)
160 static int all_down
= 0;
161 int severity
= warn
? LOG_WARN
: LOG_INFO
;
162 if (!strcmpstart(msg
, "Resolve requested for") &&
163 get_options()->SafeLogging
) {
164 log(LOG_INFO
, LD_EXIT
, "eventdns: Resolve requested.");
166 } else if (!strcmpstart(msg
, "Search: ")) {
169 if (!strcmpstart(msg
, "Nameserver ") && (cp
=strstr(msg
, " has failed: "))) {
170 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
171 const char *err
= strchr(cp
, ':')+2;
173 /* Don't warn about a single failed nameserver; we'll warn with 'all
174 * nameservers have failed' if we're completely out of nameservers;
175 * otherwise, the situation is tolerable. */
177 control_event_server_status(LOG_NOTICE
,
178 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
181 } else if (!strcmpstart(msg
, "Nameserver ") &&
182 (cp
=strstr(msg
, " is back up"))) {
183 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
184 severity
= (all_down
&& warn
) ? LOG_NOTICE
: LOG_INFO
;
186 control_event_server_status(LOG_NOTICE
,
187 "NAMESERVER_STATUS NS=%s STATUS=UP", ns
);
189 } else if (!strcmp(msg
, "All nameservers have failed")) {
190 control_event_server_status(LOG_WARN
, "NAMESERVER_ALL_DOWN");
193 log(severity
, LD_EXIT
, "eventdns: %s", msg
);
196 /** Helper: passed to eventdns.c as a callback so it can generate random
197 * numbers for transaction IDs and 0x20-hack coding. */
199 _dns_randfn(char *b
, size_t n
)
204 /** Initialize the DNS subsystem; called by the OR process. */
209 evdns_set_random_bytes_fn(_dns_randfn
);
210 if (server_mode(get_options())) {
211 int r
= configure_nameservers(1);
217 /** Called when DNS-related options change (or may have changed). Returns -1
218 * on failure, 0 on success. */
222 or_options_t
*options
= get_options();
223 if (! server_mode(options
)) {
224 evdns_clear_nameservers_and_suspend();
225 evdns_search_clear();
226 nameservers_configured
= 0;
227 tor_free(resolv_conf_fname
);
228 resolv_conf_mtime
= 0;
230 if (configure_nameservers(0) < 0) {
237 /** Return true iff the most recent attempt to initialize the DNS subsystem
240 has_dns_init_failed(void)
242 return nameserver_config_failed
;
245 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
246 * OP that asked us to resolve it. */
248 dns_clip_ttl(uint32_t ttl
)
250 if (ttl
< MIN_DNS_TTL
)
252 else if (ttl
> MAX_DNS_TTL
)
258 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
261 dns_get_expiry_ttl(uint32_t ttl
)
263 if (ttl
< MIN_DNS_TTL
)
265 else if (ttl
> MAX_DNS_ENTRY_AGE
)
266 return MAX_DNS_ENTRY_AGE
;
271 /** Helper: free storage held by an entry in the DNS cache. */
273 _free_cached_resolve(cached_resolve_t
*r
)
275 while (r
->pending_connections
) {
276 pending_connection_t
*victim
= r
->pending_connections
;
277 r
->pending_connections
= victim
->next
;
281 tor_free(r
->result
.hostname
);
282 r
->magic
= 0xFF00FF00;
286 /** Compare two cached_resolve_t pointers by expiry time, and return
287 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
288 * the priority queue implementation. */
290 _compare_cached_resolves_by_expiry(const void *_a
, const void *_b
)
292 const cached_resolve_t
*a
= _a
, *b
= _b
;
293 if (a
->expire
< b
->expire
)
295 else if (a
->expire
== b
->expire
)
301 /** Priority queue of cached_resolve_t objects to let us know when they
303 static smartlist_t
*cached_resolve_pqueue
= NULL
;
305 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
308 set_expiry(cached_resolve_t
*resolve
, time_t expires
)
310 tor_assert(resolve
&& resolve
->expire
== 0);
311 if (!cached_resolve_pqueue
)
312 cached_resolve_pqueue
= smartlist_create();
313 resolve
->expire
= expires
;
314 smartlist_pqueue_add(cached_resolve_pqueue
,
315 _compare_cached_resolves_by_expiry
,
319 /** Free all storage held in the DNS cache and related structures. */
323 cached_resolve_t
**ptr
, **next
, *item
;
325 if (cached_resolve_pqueue
) {
326 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
328 if (res
->state
== CACHE_STATE_DONE
)
329 _free_cached_resolve(res
);
332 for (ptr
= HT_START(cache_map
, &cache_root
); ptr
!= NULL
; ptr
= next
) {
334 next
= HT_NEXT_RMV(cache_map
, &cache_root
, ptr
);
335 _free_cached_resolve(item
);
337 HT_CLEAR(cache_map
, &cache_root
);
338 if (cached_resolve_pqueue
)
339 smartlist_free(cached_resolve_pqueue
);
340 cached_resolve_pqueue
= NULL
;
341 tor_free(resolv_conf_fname
);
344 /** Remove every cached_resolve whose <b>expire</b> time is before or
345 * equal to <b>now</b> from the cache. */
347 purge_expired_resolves(time_t now
)
349 cached_resolve_t
*resolve
, *removed
;
350 pending_connection_t
*pend
;
351 edge_connection_t
*pendconn
;
354 if (!cached_resolve_pqueue
)
357 while (smartlist_len(cached_resolve_pqueue
)) {
358 resolve
= smartlist_get(cached_resolve_pqueue
, 0);
359 if (resolve
->expire
> now
)
361 smartlist_pqueue_pop(cached_resolve_pqueue
,
362 _compare_cached_resolves_by_expiry
);
364 if (resolve
->state
== CACHE_STATE_PENDING
) {
366 "Expiring a dns resolve %s that's still pending. Forgot to "
367 "cull it? DNS resolve didn't tell us about the timeout?",
368 escaped_safe_str(resolve
->address
));
369 } else if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
370 resolve
->state
== CACHE_STATE_CACHED_FAILED
) {
372 "Forgetting old cached resolve (address %s, expires %lu)",
373 escaped_safe_str(resolve
->address
),
374 (unsigned long)resolve
->expire
);
375 tor_assert(!resolve
->pending_connections
);
377 tor_assert(resolve
->state
== CACHE_STATE_DONE
);
378 tor_assert(!resolve
->pending_connections
);
381 if (resolve
->pending_connections
) {
383 "Closing pending connections on timed-out DNS resolve!");
384 tor_fragile_assert();
385 while (resolve
->pending_connections
) {
386 pend
= resolve
->pending_connections
;
387 resolve
->pending_connections
= pend
->next
;
388 /* Connections should only be pending if they have no socket. */
389 tor_assert(pend
->conn
->_base
.s
== -1);
390 pendconn
= pend
->conn
;
391 connection_edge_end(pendconn
, END_STREAM_REASON_TIMEOUT
);
392 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
393 connection_free(TO_CONN(pendconn
));
398 if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
399 resolve
->state
== CACHE_STATE_CACHED_FAILED
||
400 resolve
->state
== CACHE_STATE_PENDING
) {
401 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
402 if (removed
!= resolve
) {
403 log_err(LD_BUG
, "The expired resolve we purged didn't match any in"
404 " the cache. Tried to purge %s (%p); instead got %s (%p).",
405 resolve
->address
, (void*)resolve
,
406 removed
? removed
->address
: "NULL", (void*)remove
);
408 tor_assert(removed
== resolve
);
410 /* This should be in state DONE. Make sure it's not in the cache. */
411 cached_resolve_t
*tmp
= HT_FIND(cache_map
, &cache_root
, resolve
);
412 tor_assert(tmp
!= resolve
);
414 if (resolve
->is_reverse
)
415 tor_free(resolve
->result
.hostname
);
416 resolve
->magic
= 0xF0BBF0BB;
423 /** Send a response to the RESOLVE request of a connection.
424 * <b>answer_type</b> must be one of
425 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
427 * If <b>circ</b> is provided, and we have a cached answer, send the
428 * answer back along circ; otherwise, send the answer back along
429 * <b>conn</b>'s attached circuit.
432 send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
)
434 char buf
[RELAY_PAYLOAD_SIZE
];
438 buf
[0] = answer_type
;
439 ttl
= dns_clip_ttl(conn
->address_ttl
);
443 case RESOLVED_TYPE_IPV4
:
445 set_uint32(buf
+2, tor_addr_to_ipv4n(&conn
->_base
.addr
));
446 set_uint32(buf
+6, htonl(ttl
));
449 /*XXXX IP6 need ipv6 implementation */
450 case RESOLVED_TYPE_ERROR_TRANSIENT
:
451 case RESOLVED_TYPE_ERROR
:
453 const char *errmsg
= "Error resolving hostname";
454 size_t msglen
= strlen(errmsg
);
457 strlcpy(buf
+2, errmsg
, sizeof(buf
)-2);
458 set_uint32(buf
+2+msglen
, htonl(ttl
));
466 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
468 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
471 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
472 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
473 * The answer type will be RESOLVED_HOSTNAME.
475 * If <b>circ</b> is provided, and we have a cached answer, send the
476 * answer back along circ; otherwise, send the answer back along
477 * <b>conn</b>'s attached circuit.
480 send_resolved_hostname_cell(edge_connection_t
*conn
, const char *hostname
)
482 char buf
[RELAY_PAYLOAD_SIZE
];
485 size_t namelen
= strlen(hostname
);
486 tor_assert(hostname
);
488 tor_assert(namelen
< 256);
489 ttl
= dns_clip_ttl(conn
->address_ttl
);
491 buf
[0] = RESOLVED_TYPE_HOSTNAME
;
492 buf
[1] = (uint8_t)namelen
;
493 memcpy(buf
+2, hostname
, namelen
);
494 set_uint32(buf
+2+namelen
, htonl(ttl
));
495 buflen
= 2+namelen
+4;
497 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
498 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
499 // log_notice(LD_EXIT, "Sent");
502 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
503 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
504 * If resolve failed, free exitconn and return -1.
506 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
507 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
508 * need to send back an END cell, since connection_exit_begin_conn will
511 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
514 * Else, if seen before and pending, add conn to the pending list,
517 * Else, if not seen before, add conn to pending list, hand to
518 * dns farm, and return 0.
520 * Exitconn's on_circuit field must be set, but exitconn should not
521 * yet be linked onto the n_streams/resolving_streams list of that circuit.
522 * On success, link the connection to n_streams if it's an exit connection.
523 * On "pending", link the connection to resolving streams. Otherwise,
524 * clear its on_circuit field.
527 dns_resolve(edge_connection_t
*exitconn
)
529 or_circuit_t
*oncirc
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
531 char *hostname
= NULL
;
532 is_resolve
= exitconn
->_base
.purpose
== EXIT_PURPOSE_RESOLVE
;
534 r
= dns_resolve_impl(exitconn
, is_resolve
, oncirc
, &hostname
);
538 /* We got an answer without a lookup -- either the answer was
539 * cached, or it was obvious (like an IP address). */
541 /* Send the answer back right now, and detach. */
543 send_resolved_hostname_cell(exitconn
, hostname
);
545 send_resolved_cell(exitconn
, RESOLVED_TYPE_IPV4
);
546 exitconn
->on_circuit
= NULL
;
548 /* Add to the n_streams list; the calling function will send back a
550 exitconn
->next_stream
= oncirc
->n_streams
;
551 oncirc
->n_streams
= exitconn
;
555 /* The request is pending: add the connection into the linked list of
556 * resolving_streams on this circuit. */
557 exitconn
->_base
.state
= EXIT_CONN_STATE_RESOLVING
;
558 exitconn
->next_stream
= oncirc
->resolving_streams
;
559 oncirc
->resolving_streams
= exitconn
;
563 /* The request failed before it could start: cancel this connection,
564 * and stop everybody waiting for the same connection. */
566 send_resolved_cell(exitconn
,
567 (r
== -1) ? RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
570 exitconn
->on_circuit
= NULL
;
572 dns_cancel_pending_resolve(exitconn
->_base
.address
);
574 if (!exitconn
->_base
.marked_for_close
) {
575 connection_free(TO_CONN(exitconn
));
576 // XXX ... and we just leak exitconn otherwise? -RD
577 // If it's marked for close, it's on closeable_connection_lst in
578 // main.c. If it's on the closeable list, it will get freed from
580 // "<armadev> If that's true, there are other bugs around, where we
581 // don't check if it's marked, and will end up double-freeing."
582 // On the other hand, I don't know of any actual bugs here, so this
583 // shouldn't be holding up the rc. -RD
594 /** Helper function for dns_resolve: same functionality, but does not handle:
595 * - marking connections on error and clearing their on_circuit
596 * - linking connections to n_streams/resolving_streams,
597 * - sending resolved cells if we have an answer/error right away,
599 * Return -2 on a transient error. If it's a reverse resolve and it's
600 * successful, sets *<b>hostname_out</b> to a newly allocated string
601 * holding the cached reverse DNS value.
604 dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
605 or_circuit_t
*oncirc
, char **hostname_out
)
607 cached_resolve_t
*resolve
;
608 cached_resolve_t search
;
609 pending_connection_t
*pending_connection
;
612 time_t now
= time(NULL
);
613 uint8_t is_reverse
= 0;
615 assert_connection_ok(TO_CONN(exitconn
), 0);
616 tor_assert(exitconn
->_base
.s
== -1);
620 /* first check if exitconn->_base.address is an IP. If so, we already
621 * know the answer. */
622 if (tor_addr_from_str(&addr
, exitconn
->_base
.address
) >= 0) {
623 if (tor_addr_family(&addr
) == AF_INET
) {
624 tor_addr_assign(&exitconn
->_base
.addr
, &addr
);
625 exitconn
->address_ttl
= DEFAULT_DNS_TTL
;
633 /* If we're a non-exit, don't even do DNS lookups. */
634 if (!(me
= router_get_my_routerinfo()) ||
635 policy_is_reject_star(me
->exit_policy
)) {
638 if (address_is_invalid_destination(exitconn
->_base
.address
, 0)) {
639 log(LOG_PROTOCOL_WARN
, LD_EXIT
,
640 "Rejecting invalid destination address %s",
641 escaped_safe_str(exitconn
->_base
.address
));
645 /* then take this opportunity to see if there are any expired
646 * resolves in the hash table. */
647 purge_expired_resolves(now
);
649 /* lower-case exitconn->_base.address, so it's in canonical form */
650 tor_strlower(exitconn
->_base
.address
);
652 /* Check whether this is a reverse lookup. If it's malformed, or it's a
653 * .in-addr.arpa address but this isn't a resolve request, kill the
656 if ((r
= tor_addr_parse_reverse_lookup_name(&addr
, exitconn
->_base
.address
,
657 AF_UNSPEC
, 0)) != 0) {
660 if (tor_addr_is_internal(&addr
, 0)) /* internal address? */
664 if (!is_reverse
|| !is_resolve
) {
666 log_info(LD_EXIT
, "Bad .in-addr.arpa address \"%s\"; sending error.",
667 escaped_safe_str(exitconn
->_base
.address
));
668 else if (!is_resolve
)
670 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
672 escaped_safe_str(exitconn
->_base
.address
));
676 //log_notice(LD_EXIT, "Looks like an address %s",
677 //exitconn->_base.address);
680 /* now check the hash table to see if 'address' is already there. */
681 strlcpy(search
.address
, exitconn
->_base
.address
, sizeof(search
.address
));
682 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
683 if (resolve
&& resolve
->expire
> now
) { /* already there */
684 switch (resolve
->state
) {
685 case CACHE_STATE_PENDING
:
686 /* add us to the pending list */
687 pending_connection
= tor_malloc_zero(
688 sizeof(pending_connection_t
));
689 pending_connection
->conn
= exitconn
;
690 pending_connection
->next
= resolve
->pending_connections
;
691 resolve
->pending_connections
= pending_connection
;
692 log_debug(LD_EXIT
,"Connection (fd %d) waiting for pending DNS "
693 "resolve of %s", exitconn
->_base
.s
,
694 escaped_safe_str(exitconn
->_base
.address
));
696 case CACHE_STATE_CACHED_VALID
:
697 log_debug(LD_EXIT
,"Connection (fd %d) found cached answer for %s",
699 escaped_safe_str(resolve
->address
));
700 exitconn
->address_ttl
= resolve
->ttl
;
701 if (resolve
->is_reverse
) {
702 tor_assert(is_resolve
);
703 *hostname_out
= tor_strdup(resolve
->result
.hostname
);
705 tor_addr_from_ipv4h(&exitconn
->_base
.addr
, resolve
->result
.a
.addr
);
708 case CACHE_STATE_CACHED_FAILED
:
709 log_debug(LD_EXIT
,"Connection (fd %d) found cached error for %s",
711 escaped_safe_str(exitconn
->_base
.address
));
713 case CACHE_STATE_DONE
:
714 log_err(LD_BUG
, "Found a 'DONE' dns resolve still in the cache.");
715 tor_fragile_assert();
719 tor_assert(!resolve
);
720 /* not there, need to add it */
721 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
722 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
723 resolve
->state
= CACHE_STATE_PENDING
;
724 resolve
->is_reverse
= is_reverse
;
725 strlcpy(resolve
->address
, exitconn
->_base
.address
, sizeof(resolve
->address
));
727 /* add this connection to the pending list */
728 pending_connection
= tor_malloc_zero(sizeof(pending_connection_t
));
729 pending_connection
->conn
= exitconn
;
730 resolve
->pending_connections
= pending_connection
;
732 /* Add this resolve to the cache and priority queue. */
733 HT_INSERT(cache_map
, &cache_root
, resolve
);
734 set_expiry(resolve
, now
+ RESOLVE_MAX_TIMEOUT
);
736 log_debug(LD_EXIT
,"Launching %s.",
737 escaped_safe_str(exitconn
->_base
.address
));
740 return launch_resolve(exitconn
);
743 /** Log an error and abort if conn is waiting for a DNS resolve.
746 assert_connection_edge_not_dns_pending(edge_connection_t
*conn
)
748 pending_connection_t
*pend
;
749 cached_resolve_t search
;
752 cached_resolve_t
*resolve
;
753 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
754 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
757 for (pend
= resolve
->pending_connections
; pend
; pend
= pend
->next
) {
758 tor_assert(pend
->conn
!= conn
);
761 cached_resolve_t
**resolve
;
762 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
763 for (pend
= (*resolve
)->pending_connections
; pend
; pend
= pend
->next
) {
764 tor_assert(pend
->conn
!= conn
);
770 /** Log an error and abort if any connection waiting for a DNS resolve is
773 assert_all_pending_dns_resolves_ok(void)
775 pending_connection_t
*pend
;
776 cached_resolve_t
**resolve
;
778 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
779 for (pend
= (*resolve
)->pending_connections
;
782 assert_connection_ok(TO_CONN(pend
->conn
), 0);
783 tor_assert(pend
->conn
->_base
.s
== -1);
784 tor_assert(!connection_in_array(TO_CONN(pend
->conn
)));
789 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
792 connection_dns_remove(edge_connection_t
*conn
)
794 pending_connection_t
*pend
, *victim
;
795 cached_resolve_t search
;
796 cached_resolve_t
*resolve
;
798 tor_assert(conn
->_base
.type
== CONN_TYPE_EXIT
);
799 tor_assert(conn
->_base
.state
== EXIT_CONN_STATE_RESOLVING
);
801 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
803 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
805 log_notice(LD_BUG
, "Address %s is not pending. Dropping.",
806 escaped_safe_str(conn
->_base
.address
));
810 tor_assert(resolve
->pending_connections
);
811 assert_connection_ok(TO_CONN(conn
),0);
813 pend
= resolve
->pending_connections
;
815 if (pend
->conn
== conn
) {
816 resolve
->pending_connections
= pend
->next
;
818 log_debug(LD_EXIT
, "First connection (fd %d) no longer waiting "
820 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
823 for ( ; pend
->next
; pend
= pend
->next
) {
824 if (pend
->next
->conn
== conn
) {
826 pend
->next
= victim
->next
;
829 "Connection (fd %d) no longer waiting for resolve of %s",
830 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
831 return; /* more are pending */
834 tor_assert(0); /* not reachable unless onlyconn not in pending list */
838 /** Mark all connections waiting for <b>address</b> for close. Then cancel
839 * the resolve for <b>address</b> itself, and remove any cached results for
840 * <b>address</b> from the cache.
843 dns_cancel_pending_resolve(const char *address
)
845 pending_connection_t
*pend
;
846 cached_resolve_t search
;
847 cached_resolve_t
*resolve
, *tmp
;
848 edge_connection_t
*pendconn
;
851 strlcpy(search
.address
, address
, sizeof(search
.address
));
853 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
857 if (resolve
->state
!= CACHE_STATE_PENDING
) {
858 /* We can get into this state if we never actually created the pending
859 * resolve, due to finding an earlier cached error or something. Just
861 if (resolve
->pending_connections
) {
863 "Address %s is not pending but has pending connections!",
864 escaped_safe_str(address
));
865 tor_fragile_assert();
870 if (!resolve
->pending_connections
) {
872 "Address %s is pending but has no pending connections!",
873 escaped_safe_str(address
));
874 tor_fragile_assert();
877 tor_assert(resolve
->pending_connections
);
879 /* mark all pending connections to fail */
881 "Failing all connections waiting on DNS resolve of %s",
882 escaped_safe_str(address
));
883 while (resolve
->pending_connections
) {
884 pend
= resolve
->pending_connections
;
885 pend
->conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
886 pendconn
= pend
->conn
;
887 assert_connection_ok(TO_CONN(pendconn
), 0);
888 tor_assert(pendconn
->_base
.s
== -1);
889 if (!pendconn
->_base
.marked_for_close
) {
890 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
892 circ
= circuit_get_by_edge_conn(pendconn
);
894 circuit_detach_stream(circ
, pendconn
);
895 if (!pendconn
->_base
.marked_for_close
)
896 connection_free(TO_CONN(pendconn
));
897 resolve
->pending_connections
= pend
->next
;
901 tmp
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
902 if (tmp
!= resolve
) {
903 log_err(LD_BUG
, "The cancelled resolve we purged didn't match any in"
904 " the cache. Tried to purge %s (%p); instead got %s (%p).",
905 resolve
->address
, (void*)resolve
,
906 tmp
? tmp
->address
: "NULL", (void*)tmp
);
908 tor_assert(tmp
== resolve
);
910 resolve
->state
= CACHE_STATE_DONE
;
913 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
914 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
915 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
916 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
919 add_answer_to_cache(const char *address
, uint8_t is_reverse
, uint32_t addr
,
920 const char *hostname
, char outcome
, uint32_t ttl
)
922 cached_resolve_t
*resolve
;
923 if (outcome
== DNS_RESOLVE_FAILED_TRANSIENT
)
926 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
927 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
928 // hostname?hostname:"NULL",(int)outcome);
930 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
931 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
932 resolve
->state
= (outcome
== DNS_RESOLVE_SUCCEEDED
) ?
933 CACHE_STATE_CACHED_VALID
: CACHE_STATE_CACHED_FAILED
;
934 strlcpy(resolve
->address
, address
, sizeof(resolve
->address
));
935 resolve
->is_reverse
= is_reverse
;
937 if (outcome
== DNS_RESOLVE_SUCCEEDED
) {
938 tor_assert(hostname
);
939 resolve
->result
.hostname
= tor_strdup(hostname
);
941 tor_assert(! hostname
);
942 resolve
->result
.hostname
= NULL
;
945 tor_assert(!hostname
);
946 resolve
->result
.a
.addr
= addr
;
949 assert_resolve_ok(resolve
);
950 HT_INSERT(cache_map
, &cache_root
, resolve
);
951 set_expiry(resolve
, time(NULL
) + dns_get_expiry_ttl(ttl
));
954 /** Return true iff <b>address</b> is one of the addresses we use to verify
955 * that well-known sites aren't being hijacked by our DNS servers. */
957 is_test_address(const char *address
)
959 or_options_t
*options
= get_options();
960 return options
->ServerDNSTestAddresses
&&
961 smartlist_string_isin_case(options
->ServerDNSTestAddresses
, address
);
964 /** Called on the OR side when a DNS worker or the eventdns library tells us
965 * the outcome of a DNS resolve: tell all pending connections about the result
966 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
967 * string containing the address to look up; <b>addr</b> is an IPv4 address in
968 * host order; <b>outcome</b> is one of
969 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
972 dns_found_answer(const char *address
, uint8_t is_reverse
, uint32_t addr
,
973 const char *hostname
, char outcome
, uint32_t ttl
)
975 pending_connection_t
*pend
;
976 cached_resolve_t search
;
977 cached_resolve_t
*resolve
, *removed
;
978 edge_connection_t
*pendconn
;
983 strlcpy(search
.address
, address
, sizeof(search
.address
));
985 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
987 int is_test_addr
= is_test_address(address
);
989 log_info(LD_EXIT
,"Resolved unasked address %s; caching anyway.",
990 escaped_safe_str(address
));
991 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
994 assert_resolve_ok(resolve
);
996 if (resolve
->state
!= CACHE_STATE_PENDING
) {
997 /* XXXX Maybe update addr? or check addr for consistency? Or let
998 * VALID replace FAILED? */
999 int is_test_addr
= is_test_address(address
);
1002 "Resolved %s which was already resolved; ignoring",
1003 escaped_safe_str(address
));
1004 tor_assert(resolve
->pending_connections
== NULL
);
1007 /* Removed this assertion: in fact, we'll sometimes get a double answer
1008 * to the same question. This can happen when we ask one worker to resolve
1009 * X.Y.Z., then we cancel the request, and then we ask another worker to
1011 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
1013 while (resolve
->pending_connections
) {
1014 pend
= resolve
->pending_connections
;
1015 pendconn
= pend
->conn
; /* don't pass complex things to the
1016 connection_mark_for_close macro */
1017 assert_connection_ok(TO_CONN(pendconn
),time(NULL
));
1018 tor_addr_from_ipv4h(&pendconn
->_base
.addr
, addr
);
1019 pendconn
->address_ttl
= ttl
;
1021 if (outcome
!= DNS_RESOLVE_SUCCEEDED
) {
1022 /* prevent double-remove. */
1023 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1024 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1025 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
1026 /* This detach must happen after we send the end cell. */
1027 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1029 send_resolved_cell(pendconn
, outcome
== DNS_RESOLVE_FAILED_PERMANENT
?
1030 RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
1031 /* This detach must happen after we send the resolved cell. */
1032 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1034 connection_free(TO_CONN(pendconn
));
1036 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1037 tor_assert(!is_reverse
);
1038 /* prevent double-remove. */
1039 pend
->conn
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
1041 circ
= circuit_get_by_edge_conn(pend
->conn
);
1043 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1044 /* unlink pend->conn from resolving_streams, */
1045 circuit_detach_stream(circ
, pend
->conn
);
1046 /* and link it to n_streams */
1047 pend
->conn
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
1048 pend
->conn
->on_circuit
= circ
;
1049 TO_OR_CIRCUIT(circ
)->n_streams
= pend
->conn
;
1051 connection_exit_connect(pend
->conn
);
1053 /* prevent double-remove. This isn't really an accurate state,
1054 * but it does the right thing. */
1055 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1057 send_resolved_hostname_cell(pendconn
, hostname
);
1059 send_resolved_cell(pendconn
, RESOLVED_TYPE_IPV4
);
1060 circ
= circuit_get_by_edge_conn(pendconn
);
1062 circuit_detach_stream(circ
, pendconn
);
1063 connection_free(TO_CONN(pendconn
));
1066 resolve
->pending_connections
= pend
->next
;
1070 resolve
->state
= CACHE_STATE_DONE
;
1071 removed
= HT_REMOVE(cache_map
, &cache_root
, &search
);
1072 if (removed
!= resolve
) {
1073 log_err(LD_BUG
, "The pending resolve we found wasn't removable from"
1074 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1075 resolve
->address
, (void*)resolve
,
1076 removed
? removed
->address
: "NULL", (void*)removed
);
1078 assert_resolve_ok(resolve
);
1081 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1085 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1086 * a transient failure. */
1088 evdns_err_is_transient(int err
)
1092 case DNS_ERR_SERVERFAILED
:
1093 case DNS_ERR_TRUNCATED
:
1094 case DNS_ERR_TIMEOUT
:
1101 /** Configure eventdns nameservers if force is true, or if the configuration
1102 * has changed since the last time we called this function, or if we failed on
1103 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1104 * options->ServerDNSResolvConfFile; on Windows, this reads from
1105 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1108 configure_nameservers(int force
)
1110 or_options_t
*options
;
1111 const char *conf_fname
;
1114 options
= get_options();
1115 conf_fname
= options
->ServerDNSResolvConfFile
;
1118 conf_fname
= "/etc/resolv.conf";
1121 #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
1122 if (options
->OutboundBindAddress
) {
1124 if (tor_addr_from_str(&addr
, options
->OutboundBindAddress
) < 0) {
1125 log_warn(LD_CONFIG
,"Outbound bind address '%s' didn't parse. Ignoring.",
1126 options
->OutboundBindAddress
);
1129 struct sockaddr_storage ss
;
1130 socklen
= tor_addr_to_sockaddr(&addr
, 0,
1131 (struct sockaddr
*)&ss
, sizeof(ss
));
1133 log_warn(LD_BUG
, "Couldn't convert outbound bind address to sockaddr."
1136 evdns_set_default_outgoing_bind_address((struct sockaddr
*)&ss
,
1143 if (options
->ServerDNSRandomizeCase
)
1144 evdns_set_option("randomize-case:", "1", DNS_OPTIONS_ALL
);
1146 evdns_set_option("randomize-case:", "0", DNS_OPTIONS_ALL
);
1148 evdns_set_log_fn(evdns_log_cb
);
1150 if (stat(conf_fname
, &st
)) {
1151 log_warn(LD_EXIT
, "Unable to stat resolver configuration in '%s': %s",
1152 conf_fname
, strerror(errno
));
1155 if (!force
&& resolv_conf_fname
&& !strcmp(conf_fname
,resolv_conf_fname
)
1156 && st
.st_mtime
== resolv_conf_mtime
) {
1157 log_info(LD_EXIT
, "No change to '%s'", conf_fname
);
1160 if (nameservers_configured
) {
1161 evdns_search_clear();
1162 evdns_clear_nameservers_and_suspend();
1164 log_info(LD_EXIT
, "Parsing resolver configuration in '%s'", conf_fname
);
1165 if ((r
= evdns_resolv_conf_parse(DNS_OPTIONS_ALL
, conf_fname
))) {
1166 log_warn(LD_EXIT
, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1167 conf_fname
, conf_fname
, r
);
1170 if (evdns_count_nameservers() == 0) {
1171 log_warn(LD_EXIT
, "Unable to find any nameservers in '%s'.", conf_fname
);
1174 tor_free(resolv_conf_fname
);
1175 resolv_conf_fname
= tor_strdup(conf_fname
);
1176 resolv_conf_mtime
= st
.st_mtime
;
1177 if (nameservers_configured
)
1182 if (nameservers_configured
) {
1183 evdns_search_clear();
1184 evdns_clear_nameservers_and_suspend();
1186 if (evdns_config_windows_nameservers()) {
1187 log_warn(LD_EXIT
,"Could not config nameservers.");
1190 if (evdns_count_nameservers() == 0) {
1191 log_warn(LD_EXIT
, "Unable to find any platform nameservers in "
1192 "your Windows configuration.");
1195 if (nameservers_configured
)
1197 tor_free(resolv_conf_fname
);
1198 resolv_conf_mtime
= 0;
1202 if (evdns_count_nameservers() == 1) {
1203 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL
);
1204 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL
);
1206 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL
);
1207 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL
);
1210 dns_servers_relaunch_checks();
1212 nameservers_configured
= 1;
1213 if (nameserver_config_failed
) {
1214 nameserver_config_failed
= 0;
1215 mark_my_descriptor_dirty();
1219 nameservers_configured
= 0;
1220 if (! nameserver_config_failed
) {
1221 nameserver_config_failed
= 1;
1222 mark_my_descriptor_dirty();
1227 /** For eventdns: Called when we get an answer for a request we launched.
1228 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1231 evdns_callback(int result
, char type
, int count
, int ttl
, void *addresses
,
1234 char *string_address
= arg
;
1235 uint8_t is_reverse
= 0;
1236 int status
= DNS_RESOLVE_FAILED_PERMANENT
;
1238 const char *hostname
= NULL
;
1239 int was_wildcarded
= 0;
1241 if (result
== DNS_ERR_NONE
) {
1242 if (type
== DNS_IPv4_A
&& count
) {
1243 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1245 char *escaped_address
;
1246 uint32_t *addrs
= addresses
;
1247 in
.s_addr
= addrs
[0];
1248 addr
= ntohl(addrs
[0]);
1249 status
= DNS_RESOLVE_SUCCEEDED
;
1250 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1251 escaped_address
= esc_for_log(string_address
);
1253 if (answer_is_wildcarded(answer_buf
)) {
1254 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1255 "address %s; treating as a failure.",
1256 safe_str(escaped_address
),
1257 escaped_safe_str(answer_buf
));
1260 status
= DNS_RESOLVE_FAILED_PERMANENT
;
1262 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1263 safe_str(escaped_address
),
1264 escaped_safe_str(answer_buf
));
1266 tor_free(escaped_address
);
1267 } else if (type
== DNS_PTR
&& count
) {
1268 char *escaped_address
;
1270 hostname
= ((char**)addresses
)[0];
1271 status
= DNS_RESOLVE_SUCCEEDED
;
1272 escaped_address
= esc_for_log(string_address
);
1273 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1274 safe_str(escaped_address
),
1275 escaped_safe_str(hostname
));
1276 tor_free(escaped_address
);
1278 log_warn(LD_EXIT
, "eventdns returned only non-IPv4 answers for %s.",
1279 escaped_safe_str(string_address
));
1281 log_warn(LD_BUG
, "eventdns returned no addresses or error for %s!",
1282 escaped_safe_str(string_address
));
1285 if (evdns_err_is_transient(result
))
1286 status
= DNS_RESOLVE_FAILED_TRANSIENT
;
1288 if (was_wildcarded
) {
1289 if (is_test_address(string_address
)) {
1290 /* Ick. We're getting redirected on known-good addresses. Our DNS
1291 * server must really hate us. */
1292 add_wildcarded_test_address(string_address
);
1295 if (result
!= DNS_ERR_SHUTDOWN
)
1296 dns_found_answer(string_address
, is_reverse
, addr
, hostname
, status
, ttl
);
1297 tor_free(string_address
);
1300 /** For eventdns: start resolving as necessary to find the target for
1301 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1302 * 0 on "resolve launched." */
1304 launch_resolve(edge_connection_t
*exitconn
)
1306 char *addr
= tor_strdup(exitconn
->_base
.address
);
1309 int options
= get_options()->ServerDNSSearchDomains
? 0
1310 : DNS_QUERY_NO_SEARCH
;
1311 /* What? Nameservers not configured? Sounds like a bug. */
1312 if (!nameservers_configured
) {
1313 log_warn(LD_EXIT
, "(Harmless.) Nameservers not configured, but resolve "
1314 "launched. Configuring.");
1315 if (configure_nameservers(1) < 0) {
1320 r
= tor_addr_parse_reverse_lookup_name(
1321 &a
, exitconn
->_base
.address
, AF_UNSPEC
, 0);
1323 log_info(LD_EXIT
, "Launching eventdns request for %s",
1324 escaped_safe_str(exitconn
->_base
.address
));
1325 r
= evdns_resolve_ipv4(exitconn
->_base
.address
, options
,
1326 evdns_callback
, addr
);
1327 } else if (r
== 1) {
1328 log_info(LD_EXIT
, "Launching eventdns reverse request for %s",
1329 escaped_safe_str(exitconn
->_base
.address
));
1330 if (tor_addr_family(&a
) == AF_INET
)
1331 r
= evdns_resolve_reverse(tor_addr_to_in(&a
), DNS_QUERY_NO_SEARCH
,
1332 evdns_callback
, addr
);
1334 r
= evdns_resolve_reverse_ipv6(tor_addr_to_in6(&a
), DNS_QUERY_NO_SEARCH
,
1335 evdns_callback
, addr
);
1336 } else if (r
== -1) {
1337 log_warn(LD_BUG
, "Somehow a malformed in-addr.arpa address reached here.");
1341 log_warn(LD_EXIT
, "eventdns rejected address %s: error %d.",
1342 escaped_safe_str(addr
), r
);
1343 r
= evdns_err_is_transient(r
) ? -2 : -1;
1344 tor_free(addr
); /* There is no evdns request in progress; stop
1345 * addr from getting leaked. */
1350 /** How many requests for bogus addresses have we launched so far? */
1351 static int n_wildcard_requests
= 0;
1353 /** Map from dotted-quad IP address in response to an int holding how many
1354 * times we've seen it for a randomly generated (hopefully bogus) address. It
1355 * would be easier to use definitely-invalid addresses (as specified by
1356 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1357 static strmap_t
*dns_wildcard_response_count
= NULL
;
1359 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1360 * nameserver wants to return in response to requests for nonexistent domains.
1362 static smartlist_t
*dns_wildcard_list
= NULL
;
1363 /** True iff we've logged about a single address getting wildcarded.
1364 * Subsequent warnings will be less severe. */
1365 static int dns_wildcard_one_notice_given
= 0;
1366 /** True iff we've warned that our DNS server is wildcarding too many failures.
1368 static int dns_wildcard_notice_given
= 0;
1370 /** List of supposedly good addresses that are getting wildcarded to the
1371 * same addresses as nonexistent addresses. */
1372 static smartlist_t
*dns_wildcarded_test_address_list
= NULL
;
1373 /** True iff we've warned about a test address getting wildcarded */
1374 static int dns_wildcarded_test_address_notice_given
= 0;
1375 /** True iff all addresses seem to be getting wildcarded. */
1376 static int dns_is_completely_invalid
= 0;
1378 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1379 * a hopefully bogus address. */
1381 wildcard_increment_answer(const char *id
)
1384 if (!dns_wildcard_response_count
)
1385 dns_wildcard_response_count
= strmap_new();
1387 ip
= strmap_get(dns_wildcard_response_count
, id
); // may be null (0)
1389 ip
= tor_malloc_zero(sizeof(int));
1390 strmap_set(dns_wildcard_response_count
, id
, ip
);
1394 if (*ip
> 5 && n_wildcard_requests
> 10) {
1395 if (!dns_wildcard_list
) dns_wildcard_list
= smartlist_create();
1396 if (!smartlist_string_isin(dns_wildcard_list
, id
)) {
1397 log(dns_wildcard_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1398 "Your DNS provider has given \"%s\" as an answer for %d different "
1399 "invalid addresses. Apparently they are hijacking DNS failures. "
1400 "I'll try to correct for this by treating future occurrences of "
1401 "\"%s\" as 'not found'.", id
, *ip
, id
);
1402 smartlist_add(dns_wildcard_list
, tor_strdup(id
));
1404 if (!dns_wildcard_notice_given
)
1405 control_event_server_status(LOG_NOTICE
, "DNS_HIJACKED");
1406 dns_wildcard_notice_given
= 1;
1410 /** Note that a single test address (one believed to be good) seems to be
1411 * getting redirected to the same IP as failures are. */
1413 add_wildcarded_test_address(const char *address
)
1415 int n
, n_test_addrs
;
1416 if (!dns_wildcarded_test_address_list
)
1417 dns_wildcarded_test_address_list
= smartlist_create();
1419 if (smartlist_string_isin_case(dns_wildcarded_test_address_list
, address
))
1422 n_test_addrs
= get_options()->ServerDNSTestAddresses
?
1423 smartlist_len(get_options()->ServerDNSTestAddresses
) : 0;
1425 smartlist_add(dns_wildcarded_test_address_list
, tor_strdup(address
));
1426 n
= smartlist_len(dns_wildcarded_test_address_list
);
1427 if (n
> n_test_addrs
/2) {
1428 log(dns_wildcarded_test_address_notice_given
? LOG_INFO
: LOG_NOTICE
,
1429 LD_EXIT
, "Your DNS provider tried to redirect \"%s\" to a junk "
1430 "address. It has done this with %d test addresses so far. I'm "
1431 "going to stop being an exit node for now, since our DNS seems so "
1432 "broken.", address
, n
);
1433 if (!dns_is_completely_invalid
) {
1434 dns_is_completely_invalid
= 1;
1435 mark_my_descriptor_dirty();
1437 if (!dns_wildcarded_test_address_notice_given
)
1438 control_event_server_status(LOG_WARN
, "DNS_USELESS");
1439 dns_wildcarded_test_address_notice_given
= 1;
1443 /** Callback function when we get an answer (possibly failing) for a request
1444 * for a (hopefully) nonexistent domain. */
1446 evdns_wildcard_check_callback(int result
, char type
, int count
, int ttl
,
1447 void *addresses
, void *arg
)
1450 ++n_wildcard_requests
;
1451 if (result
== DNS_ERR_NONE
&& type
== DNS_IPv4_A
&& count
) {
1452 uint32_t *addrs
= addresses
;
1454 char *string_address
= arg
;
1455 for (i
= 0; i
< count
; ++i
) {
1456 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1458 in
.s_addr
= addrs
[i
];
1459 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1460 wildcard_increment_answer(answer_buf
);
1462 log(dns_wildcard_one_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1463 "Your DNS provider gave an answer for \"%s\", which "
1464 "is not supposed to exist. Apparently they are hijacking "
1465 "DNS failures. Trying to correct for this. We've noticed %d "
1466 "possibly bad address%s so far.",
1467 string_address
, strmap_size(dns_wildcard_response_count
),
1468 (strmap_size(dns_wildcard_response_count
) == 1) ? "" : "es");
1469 dns_wildcard_one_notice_given
= 1;
1474 /** Launch a single request for a nonexistent hostname consisting of between
1475 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1478 launch_wildcard_check(int min_len
, int max_len
, const char *suffix
)
1483 addr
= crypto_random_hostname(min_len
, max_len
, "", suffix
);
1484 log_info(LD_EXIT
, "Testing whether our DNS server is hijacking nonexistent "
1485 "domains with request for bogus hostname \"%s\"", addr
);
1487 r
= evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
1489 DNS_QUERY_NO_SEARCH
, evdns_wildcard_check_callback
,
1490 /* This "addr" is an argument to the callback*/ addr
);
1492 /* There is no evdns request in progress; stop addr from getting leaked */
1497 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1498 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1500 launch_test_addresses(int fd
, short event
, void *args
)
1502 or_options_t
*options
= get_options();
1507 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like to "
1508 "hijack *everything*.");
1509 /* This situation is worse than the failure-hijacking situation. When this
1510 * happens, we're no good for DNS requests at all, and we shouldn't really
1511 * be an exit server.*/
1512 if (!options
->ServerDNSTestAddresses
)
1514 SMARTLIST_FOREACH(options
->ServerDNSTestAddresses
, const char *, address
,
1516 int r
= evdns_resolve_ipv4(address
, DNS_QUERY_NO_SEARCH
, evdns_callback
,
1517 tor_strdup(address
));
1519 log_info(LD_EXIT
, "eventdns rejected test address %s: error %d",
1520 escaped_safe_str(address
), r
);
1524 #define N_WILDCARD_CHECKS 2
1526 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1527 * hostnames, and see if we can catch our nameserver trying to hijack them and
1528 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1529 * buy these lovely encyclopedias" page. */
1531 dns_launch_wildcard_checks(void)
1534 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like "
1535 "to hijack DNS failures.");
1536 for (i
= 0; i
< N_WILDCARD_CHECKS
; ++i
) {
1537 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1538 * to 'comply' with rfc2606, refrain from giving A records for these.
1539 * This is the standards-compliance equivalent of making sure that your
1540 * crackhouse's elevator inspection certificate is up to date.
1542 launch_wildcard_check(2, 16, ".invalid");
1543 launch_wildcard_check(2, 16, ".test");
1545 /* These will break specs if there are ever any number of
1546 * 8+-character top-level domains. */
1547 launch_wildcard_check(8, 16, "");
1549 /* Try some random .com/org/net domains. This will work fine so long as
1550 * not too many resolve to the same place. */
1551 launch_wildcard_check(8, 16, ".com");
1552 launch_wildcard_check(8, 16, ".org");
1553 launch_wildcard_check(8, 16, ".net");
1557 /** If appropriate, start testing whether our DNS servers tend to lie to
1560 dns_launch_correctness_checks(void)
1562 static struct event
*launch_event
= NULL
;
1563 struct timeval timeout
;
1564 if (!get_options()->ServerDNSDetectHijacking
)
1566 dns_launch_wildcard_checks();
1568 /* Wait a while before launching requests for test addresses, so we can
1569 * get the results from checking for wildcarding. */
1571 launch_event
= tor_evtimer_new(NULL
, launch_test_addresses
, NULL
);
1572 timeout
.tv_sec
= 30;
1573 timeout
.tv_usec
= 0;
1574 if (evtimer_add(launch_event
, &timeout
)<0) {
1575 log_warn(LD_BUG
, "Couldn't add timer for checking for dns hijacking");
1579 /** Return true iff our DNS servers lie to us too much to be trusted. */
1581 dns_seems_to_be_broken(void)
1583 return dns_is_completely_invalid
;
1586 /** Forget what we've previously learned about our DNS servers' correctness. */
1588 dns_reset_correctness_checks(void)
1590 if (dns_wildcard_response_count
) {
1591 strmap_free(dns_wildcard_response_count
, _tor_free
);
1592 dns_wildcard_response_count
= NULL
;
1594 n_wildcard_requests
= 0;
1596 if (dns_wildcard_list
) {
1597 SMARTLIST_FOREACH(dns_wildcard_list
, char *, cp
, tor_free(cp
));
1598 smartlist_clear(dns_wildcard_list
);
1600 if (dns_wildcarded_test_address_list
) {
1601 SMARTLIST_FOREACH(dns_wildcarded_test_address_list
, char *, cp
,
1603 smartlist_clear(dns_wildcarded_test_address_list
);
1605 dns_wildcard_one_notice_given
= dns_wildcard_notice_given
=
1606 dns_wildcarded_test_address_notice_given
= dns_is_completely_invalid
= 0;
1609 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1610 * returned in response to requests for nonexistent hostnames. */
1612 answer_is_wildcarded(const char *ip
)
1614 return dns_wildcard_list
&& smartlist_string_isin(dns_wildcard_list
, ip
);
1617 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1619 assert_resolve_ok(cached_resolve_t
*resolve
)
1621 tor_assert(resolve
);
1622 tor_assert(resolve
->magic
== CACHED_RESOLVE_MAGIC
);
1623 tor_assert(strlen(resolve
->address
) < MAX_ADDRESSLEN
);
1624 tor_assert(tor_strisnonupper(resolve
->address
));
1625 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1626 tor_assert(!resolve
->pending_connections
);
1628 if (resolve
->state
== CACHE_STATE_PENDING
||
1629 resolve
->state
== CACHE_STATE_DONE
) {
1630 tor_assert(!resolve
->ttl
);
1631 if (resolve
->is_reverse
)
1632 tor_assert(!resolve
->result
.hostname
);
1634 tor_assert(!resolve
->result
.a
.addr
);
1638 /** Return the number of DNS cache entries as an int */
1640 dns_cache_entry_count(void)
1642 return HT_SIZE(&cache_root
);
1645 /** Log memory information about our internal DNS cache at level 'severity'. */
1647 dump_dns_mem_usage(int severity
)
1649 /* This should never be larger than INT_MAX. */
1650 int hash_count
= dns_cache_entry_count();
1651 size_t hash_mem
= sizeof(struct cached_resolve_t
) * hash_count
;
1652 hash_mem
+= HT_MEM_USAGE(&cache_root
);
1654 /* Print out the count and estimated size of our &cache_root. It undercounts
1655 hostnames in cached reverse resolves.
1657 log(severity
, LD_MM
, "Our DNS cache has %d entries.", hash_count
);
1658 log(severity
, LD_MM
, "Our DNS cache size is approximately %u bytes.",
1659 (unsigned)hash_mem
);
1662 #ifdef DEBUG_DNS_CACHE
1663 /** Exit with an assertion if the DNS cache is corrupt. */
1665 _assert_cache_ok(void)
1667 cached_resolve_t
**resolve
;
1668 int bad_rep
= _cache_map_HT_REP_IS_BAD(&cache_root
);
1670 log_err(LD_BUG
, "Bad rep type %d on dns cache hash table", bad_rep
);
1671 tor_assert(!bad_rep
);
1674 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1675 assert_resolve_ok(*resolve
);
1676 tor_assert((*resolve
)->state
!= CACHE_STATE_DONE
);
1678 if (!cached_resolve_pqueue
)
1681 smartlist_pqueue_assert_ok(cached_resolve_pqueue
,
1682 _compare_cached_resolves_by_expiry
);
1684 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
1686 if (res
->state
== CACHE_STATE_DONE
) {
1687 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);
1688 tor_assert(!found
|| found
!= res
);
1690 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);