1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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
15 #include "circuitlist.h"
16 #include "circuituse.h"
18 #include "connection.h"
19 #include "connection_edge.h"
27 #ifdef HAVE_EVENT2_DNS_H
28 #include <event2/event.h>
29 #include <event2/dns.h>
33 #ifndef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
34 #define HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
38 #ifndef HAVE_EVENT2_DNS_H
41 #define evdns_base_new(x,y) tor_malloc(1)
42 #define evdns_base_clear_nameservers_and_suspend(base) \
43 evdns_clear_nameservers_and_suspend()
44 #define evdns_base_search_clear(base) evdns_search_clear()
45 #define evdns_base_set_default_outgoing_bind_address(base, a, len) \
46 evdns_set_default_outgoing_bind_address((a),(len))
47 #define evdns_base_resolv_conf_parse(base, options, fname) \
48 evdns_resolv_conf_parse((options), (fname))
49 #define evdns_base_count_nameservers(base) \
50 evdns_count_nameservers()
51 #define evdns_base_resume(base) \
53 #define evdns_base_config_windows_nameservers(base) \
54 evdns_config_windows_nameservers()
55 #define evdns_base_set_option_(base, opt, val) \
56 evdns_set_option((opt),(val),DNS_OPTIONS_ALL)
57 #define evdns_base_resolve_ipv4(base, addr, options, cb, ptr) \
58 ((evdns_resolve_ipv4(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
59 #define evdns_base_resolve_reverse(base, addr, options, cb, ptr) \
60 ((evdns_resolve_reverse(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
61 #define evdns_base_resolve_reverse_ipv6(base, addr, options, cb, ptr) \
62 ((evdns_resolve_reverse_ipv6(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
64 #elif defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER < 0x02000303
65 #define evdns_base_set_option_(base, opt, val) \
66 evdns_base_set_option((base), (opt),(val),DNS_OPTIONS_ALL)
69 #define evdns_base_set_option_ evdns_base_set_option
73 /** Longest hostname we're willing to resolve. */
74 #define MAX_ADDRESSLEN 256
76 /** How long will we wait for an answer from the resolver before we decide
77 * that the resolver is wedged? */
78 #define RESOLVE_MAX_TIMEOUT 300
80 /** Possible outcomes from hostname lookup: permanent failure,
81 * transient (retryable) failure, and success. */
82 #define DNS_RESOLVE_FAILED_TRANSIENT 1
83 #define DNS_RESOLVE_FAILED_PERMANENT 2
84 #define DNS_RESOLVE_SUCCEEDED 3
86 /** Our evdns_base; this structure handles all our name lookups. */
87 static struct evdns_base
*the_evdns_base
= NULL
;
89 /** Have we currently configured nameservers with eventdns? */
90 static int nameservers_configured
= 0;
91 /** Did our most recent attempt to configure nameservers with eventdns fail? */
92 static int nameserver_config_failed
= 0;
93 /** What was the resolv_conf fname we last used when configuring the
94 * nameservers? Used to check whether we need to reconfigure. */
95 static char *resolv_conf_fname
= NULL
;
96 /** What was the mtime on the resolv.conf file we last used when configuring
97 * the nameservers? Used to check whether we need to reconfigure. */
98 static time_t resolv_conf_mtime
= 0;
100 /** Linked list of connections waiting for a DNS answer. */
101 typedef struct pending_connection_t
{
102 edge_connection_t
*conn
;
103 struct pending_connection_t
*next
;
104 } pending_connection_t
;
106 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
107 * pointers and memory stomping. */
108 #define CACHED_RESOLVE_MAGIC 0x1234F00D
110 /* Possible states for a cached resolve_t */
111 /** We are waiting for the resolver system to tell us an answer here.
112 * When we get one, or when we time out, the state of this cached_resolve_t
113 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
114 * entry. This cached_resolve_t will be in the hash table so that we will
115 * know not to launch more requests for this addr, but rather to add more
116 * connections to the pending list for the addr. */
117 #define CACHE_STATE_PENDING 0
118 /** This used to be a pending cached_resolve_t, and we got an answer for it.
119 * Now we're waiting for this cached_resolve_t to expire. This should
120 * have no pending connections, and should not appear in the hash table. */
121 #define CACHE_STATE_DONE 1
122 /** We are caching an answer for this address. This should have no pending
123 * connections, and should appear in the hash table. */
124 #define CACHE_STATE_CACHED_VALID 2
125 /** We are caching a failure for this address. This should have no pending
126 * connections, and should appear in the hash table */
127 #define CACHE_STATE_CACHED_FAILED 3
129 /** A DNS request: possibly completed, possibly pending; cached_resolve
130 * structs are stored at the OR side in a hash table, and as a linked
131 * list from oldest to newest.
133 typedef struct cached_resolve_t
{
134 HT_ENTRY(cached_resolve_t
) node
;
136 char address
[MAX_ADDRESSLEN
]; /**< The hostname to be resolved. */
139 struct in6_addr addr6
; /**< IPv6 addr for <b>address</b>. */
140 uint32_t addr
; /**< IPv4 addr for <b>address</b>. */
142 char *hostname
; /**< Hostname for <b>address</b> (if a reverse lookup) */
144 uint8_t state
; /**< Is this cached entry pending/done/valid/failed? */
145 uint8_t is_reverse
; /**< Is this a reverse (addr-to-hostname) lookup? */
146 time_t expire
; /**< Remove items from cache after this time. */
147 uint32_t ttl
; /**< What TTL did the nameserver tell us? */
148 /** Connections that want to know when we get an answer for this resolve. */
149 pending_connection_t
*pending_connections
;
150 /** Position of this element in the heap*/
154 static void purge_expired_resolves(time_t now
);
155 static void dns_found_answer(const char *address
, uint8_t is_reverse
,
156 uint32_t addr
, const char *hostname
, char outcome
,
158 static void send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
);
159 static int launch_resolve(edge_connection_t
*exitconn
);
160 static void add_wildcarded_test_address(const char *address
);
161 static int configure_nameservers(int force
);
162 static int answer_is_wildcarded(const char *ip
);
163 static int dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
164 or_circuit_t
*oncirc
, char **resolved_to_hostname
);
165 #ifdef DEBUG_DNS_CACHE
166 static void _assert_cache_ok(void);
167 #define assert_cache_ok() _assert_cache_ok()
169 #define assert_cache_ok() STMT_NIL
171 static void assert_resolve_ok(cached_resolve_t
*resolve
);
173 /** Hash table of cached_resolve objects. */
174 static HT_HEAD(cache_map
, cached_resolve_t
) cache_root
;
176 /** Function to compare hashed resolves on their addresses; used to
177 * implement hash tables. */
179 cached_resolves_eq(cached_resolve_t
*a
, cached_resolve_t
*b
)
181 /* make this smarter one day? */
182 assert_resolve_ok(a
); // Not b; b may be just a search.
183 return !strncmp(a
->address
, b
->address
, MAX_ADDRESSLEN
);
186 /** Hash function for cached_resolve objects */
187 static INLINE
unsigned int
188 cached_resolve_hash(cached_resolve_t
*a
)
190 return ht_string_hash(a
->address
);
193 HT_PROTOTYPE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
195 HT_GENERATE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
196 cached_resolves_eq
, 0.6, malloc
, realloc
, free
)
198 /** Initialize the DNS cache. */
202 HT_INIT(cache_map
, &cache_root
);
205 /** Helper: called by eventdns when eventdns wants to log something. */
207 evdns_log_cb(int warn
, const char *msg
)
210 static int all_down
= 0;
211 int severity
= warn
? LOG_WARN
: LOG_INFO
;
212 if (!strcmpstart(msg
, "Resolve requested for") &&
213 get_options()->SafeLogging
) {
214 log(LOG_INFO
, LD_EXIT
, "eventdns: Resolve requested.");
216 } else if (!strcmpstart(msg
, "Search: ")) {
219 if (!strcmpstart(msg
, "Nameserver ") && (cp
=strstr(msg
, " has failed: "))) {
220 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
221 const char *err
= strchr(cp
, ':')+2;
223 /* Don't warn about a single failed nameserver; we'll warn with 'all
224 * nameservers have failed' if we're completely out of nameservers;
225 * otherwise, the situation is tolerable. */
227 control_event_server_status(LOG_NOTICE
,
228 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
231 } else if (!strcmpstart(msg
, "Nameserver ") &&
232 (cp
=strstr(msg
, " is back up"))) {
233 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
234 severity
= (all_down
&& warn
) ? LOG_NOTICE
: LOG_INFO
;
236 control_event_server_status(LOG_NOTICE
,
237 "NAMESERVER_STATUS NS=%s STATUS=UP", ns
);
239 } else if (!strcmp(msg
, "All nameservers have failed")) {
240 control_event_server_status(LOG_WARN
, "NAMESERVER_ALL_DOWN");
243 log(severity
, LD_EXIT
, "eventdns: %s", msg
);
246 /** Helper: passed to eventdns.c as a callback so it can generate random
247 * numbers for transaction IDs and 0x20-hack coding. */
249 _dns_randfn(char *b
, size_t n
)
254 /** Initialize the DNS subsystem; called by the OR process. */
259 evdns_set_random_bytes_fn(_dns_randfn
);
260 if (server_mode(get_options())) {
261 int r
= configure_nameservers(1);
267 /** Called when DNS-related options change (or may have changed). Returns -1
268 * on failure, 0 on success. */
272 or_options_t
*options
= get_options();
273 if (! server_mode(options
)) {
275 if (!the_evdns_base
) {
276 if (!(the_evdns_base
= evdns_base_new(tor_libevent_get_base(), 0))) {
277 log_err(LD_BUG
, "Couldn't create an evdns_base");
282 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
283 evdns_base_search_clear(the_evdns_base
);
284 nameservers_configured
= 0;
285 tor_free(resolv_conf_fname
);
286 resolv_conf_mtime
= 0;
288 if (configure_nameservers(0) < 0) {
295 /** Return true iff the most recent attempt to initialize the DNS subsystem
298 has_dns_init_failed(void)
300 return nameserver_config_failed
;
303 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
304 * OP that asked us to resolve it. */
306 dns_clip_ttl(uint32_t ttl
)
308 if (ttl
< MIN_DNS_TTL
)
310 else if (ttl
> MAX_DNS_TTL
)
316 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
319 dns_get_expiry_ttl(uint32_t ttl
)
321 if (ttl
< MIN_DNS_TTL
)
323 else if (ttl
> MAX_DNS_ENTRY_AGE
)
324 return MAX_DNS_ENTRY_AGE
;
329 /** Helper: free storage held by an entry in the DNS cache. */
331 _free_cached_resolve(cached_resolve_t
*r
)
335 while (r
->pending_connections
) {
336 pending_connection_t
*victim
= r
->pending_connections
;
337 r
->pending_connections
= victim
->next
;
341 tor_free(r
->result
.hostname
);
342 r
->magic
= 0xFF00FF00;
346 /** Compare two cached_resolve_t pointers by expiry time, and return
347 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
348 * the priority queue implementation. */
350 _compare_cached_resolves_by_expiry(const void *_a
, const void *_b
)
352 const cached_resolve_t
*a
= _a
, *b
= _b
;
353 if (a
->expire
< b
->expire
)
355 else if (a
->expire
== b
->expire
)
361 /** Priority queue of cached_resolve_t objects to let us know when they
363 static smartlist_t
*cached_resolve_pqueue
= NULL
;
365 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
368 set_expiry(cached_resolve_t
*resolve
, time_t expires
)
370 tor_assert(resolve
&& resolve
->expire
== 0);
371 if (!cached_resolve_pqueue
)
372 cached_resolve_pqueue
= smartlist_create();
373 resolve
->expire
= expires
;
374 smartlist_pqueue_add(cached_resolve_pqueue
,
375 _compare_cached_resolves_by_expiry
,
376 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
),
380 /** Free all storage held in the DNS cache and related structures. */
384 cached_resolve_t
**ptr
, **next
, *item
;
386 if (cached_resolve_pqueue
) {
387 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
389 if (res
->state
== CACHE_STATE_DONE
)
390 _free_cached_resolve(res
);
393 for (ptr
= HT_START(cache_map
, &cache_root
); ptr
!= NULL
; ptr
= next
) {
395 next
= HT_NEXT_RMV(cache_map
, &cache_root
, ptr
);
396 _free_cached_resolve(item
);
398 HT_CLEAR(cache_map
, &cache_root
);
399 smartlist_free(cached_resolve_pqueue
);
400 cached_resolve_pqueue
= NULL
;
401 tor_free(resolv_conf_fname
);
404 /** Remove every cached_resolve whose <b>expire</b> time is before or
405 * equal to <b>now</b> from the cache. */
407 purge_expired_resolves(time_t now
)
409 cached_resolve_t
*resolve
, *removed
;
410 pending_connection_t
*pend
;
411 edge_connection_t
*pendconn
;
414 if (!cached_resolve_pqueue
)
417 while (smartlist_len(cached_resolve_pqueue
)) {
418 resolve
= smartlist_get(cached_resolve_pqueue
, 0);
419 if (resolve
->expire
> now
)
421 smartlist_pqueue_pop(cached_resolve_pqueue
,
422 _compare_cached_resolves_by_expiry
,
423 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
));
425 if (resolve
->state
== CACHE_STATE_PENDING
) {
427 "Expiring a dns resolve %s that's still pending. Forgot to "
428 "cull it? DNS resolve didn't tell us about the timeout?",
429 escaped_safe_str(resolve
->address
));
430 } else if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
431 resolve
->state
== CACHE_STATE_CACHED_FAILED
) {
433 "Forgetting old cached resolve (address %s, expires %lu)",
434 escaped_safe_str(resolve
->address
),
435 (unsigned long)resolve
->expire
);
436 tor_assert(!resolve
->pending_connections
);
438 tor_assert(resolve
->state
== CACHE_STATE_DONE
);
439 tor_assert(!resolve
->pending_connections
);
442 if (resolve
->pending_connections
) {
444 "Closing pending connections on timed-out DNS resolve!");
445 tor_fragile_assert();
446 while (resolve
->pending_connections
) {
447 pend
= resolve
->pending_connections
;
448 resolve
->pending_connections
= pend
->next
;
449 /* Connections should only be pending if they have no socket. */
450 tor_assert(pend
->conn
->_base
.s
== -1);
451 pendconn
= pend
->conn
;
452 connection_edge_end(pendconn
, END_STREAM_REASON_TIMEOUT
);
453 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
454 connection_free(TO_CONN(pendconn
));
459 if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
460 resolve
->state
== CACHE_STATE_CACHED_FAILED
||
461 resolve
->state
== CACHE_STATE_PENDING
) {
462 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
463 if (removed
!= resolve
) {
464 log_err(LD_BUG
, "The expired resolve we purged didn't match any in"
465 " the cache. Tried to purge %s (%p); instead got %s (%p).",
466 resolve
->address
, (void*)resolve
,
467 removed
? removed
->address
: "NULL", (void*)removed
);
469 tor_assert(removed
== resolve
);
471 /* This should be in state DONE. Make sure it's not in the cache. */
472 cached_resolve_t
*tmp
= HT_FIND(cache_map
, &cache_root
, resolve
);
473 tor_assert(tmp
!= resolve
);
475 if (resolve
->is_reverse
)
476 tor_free(resolve
->result
.hostname
);
477 resolve
->magic
= 0xF0BBF0BB;
484 /** Send a response to the RESOLVE request of a connection.
485 * <b>answer_type</b> must be one of
486 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
488 * If <b>circ</b> is provided, and we have a cached answer, send the
489 * answer back along circ; otherwise, send the answer back along
490 * <b>conn</b>'s attached circuit.
493 send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
)
495 char buf
[RELAY_PAYLOAD_SIZE
];
499 buf
[0] = answer_type
;
500 ttl
= dns_clip_ttl(conn
->address_ttl
);
504 case RESOLVED_TYPE_IPV4
:
506 set_uint32(buf
+2, tor_addr_to_ipv4n(&conn
->_base
.addr
));
507 set_uint32(buf
+6, htonl(ttl
));
510 /*XXXX IP6 need ipv6 implementation */
511 case RESOLVED_TYPE_ERROR_TRANSIENT
:
512 case RESOLVED_TYPE_ERROR
:
514 const char *errmsg
= "Error resolving hostname";
515 size_t msglen
= strlen(errmsg
);
518 strlcpy(buf
+2, errmsg
, sizeof(buf
)-2);
519 set_uint32(buf
+2+msglen
, htonl(ttl
));
527 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
529 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
532 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
533 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
534 * The answer type will be RESOLVED_HOSTNAME.
536 * If <b>circ</b> is provided, and we have a cached answer, send the
537 * answer back along circ; otherwise, send the answer back along
538 * <b>conn</b>'s attached circuit.
541 send_resolved_hostname_cell(edge_connection_t
*conn
, const char *hostname
)
543 char buf
[RELAY_PAYLOAD_SIZE
];
546 size_t namelen
= strlen(hostname
);
547 tor_assert(hostname
);
549 tor_assert(namelen
< 256);
550 ttl
= dns_clip_ttl(conn
->address_ttl
);
552 buf
[0] = RESOLVED_TYPE_HOSTNAME
;
553 buf
[1] = (uint8_t)namelen
;
554 memcpy(buf
+2, hostname
, namelen
);
555 set_uint32(buf
+2+namelen
, htonl(ttl
));
556 buflen
= 2+namelen
+4;
558 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
559 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
560 // log_notice(LD_EXIT, "Sent");
563 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
564 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
565 * If resolve failed, free exitconn and return -1.
567 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
568 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
569 * need to send back an END cell, since connection_exit_begin_conn will
572 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
575 * Else, if seen before and pending, add conn to the pending list,
578 * Else, if not seen before, add conn to pending list, hand to
579 * dns farm, and return 0.
581 * Exitconn's on_circuit field must be set, but exitconn should not
582 * yet be linked onto the n_streams/resolving_streams list of that circuit.
583 * On success, link the connection to n_streams if it's an exit connection.
584 * On "pending", link the connection to resolving streams. Otherwise,
585 * clear its on_circuit field.
588 dns_resolve(edge_connection_t
*exitconn
)
590 or_circuit_t
*oncirc
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
592 char *hostname
= NULL
;
593 is_resolve
= exitconn
->_base
.purpose
== EXIT_PURPOSE_RESOLVE
;
595 r
= dns_resolve_impl(exitconn
, is_resolve
, oncirc
, &hostname
);
599 /* We got an answer without a lookup -- either the answer was
600 * cached, or it was obvious (like an IP address). */
602 /* Send the answer back right now, and detach. */
604 send_resolved_hostname_cell(exitconn
, hostname
);
606 send_resolved_cell(exitconn
, RESOLVED_TYPE_IPV4
);
607 exitconn
->on_circuit
= NULL
;
609 /* Add to the n_streams list; the calling function will send back a
611 exitconn
->next_stream
= oncirc
->n_streams
;
612 oncirc
->n_streams
= exitconn
;
616 /* The request is pending: add the connection into the linked list of
617 * resolving_streams on this circuit. */
618 exitconn
->_base
.state
= EXIT_CONN_STATE_RESOLVING
;
619 exitconn
->next_stream
= oncirc
->resolving_streams
;
620 oncirc
->resolving_streams
= exitconn
;
624 /* The request failed before it could start: cancel this connection,
625 * and stop everybody waiting for the same connection. */
627 send_resolved_cell(exitconn
,
628 (r
== -1) ? RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
631 exitconn
->on_circuit
= NULL
;
633 dns_cancel_pending_resolve(exitconn
->_base
.address
);
635 if (!exitconn
->_base
.marked_for_close
) {
636 connection_free(TO_CONN(exitconn
));
637 // XXX ... and we just leak exitconn otherwise? -RD
638 // If it's marked for close, it's on closeable_connection_lst in
639 // main.c. If it's on the closeable list, it will get freed from
641 // "<armadev> If that's true, there are other bugs around, where we
642 // don't check if it's marked, and will end up double-freeing."
643 // On the other hand, I don't know of any actual bugs here, so this
644 // shouldn't be holding up the rc. -RD
655 /** Helper function for dns_resolve: same functionality, but does not handle:
656 * - marking connections on error and clearing their on_circuit
657 * - linking connections to n_streams/resolving_streams,
658 * - sending resolved cells if we have an answer/error right away,
660 * Return -2 on a transient error. If it's a reverse resolve and it's
661 * successful, sets *<b>hostname_out</b> to a newly allocated string
662 * holding the cached reverse DNS value.
665 dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
666 or_circuit_t
*oncirc
, char **hostname_out
)
668 cached_resolve_t
*resolve
;
669 cached_resolve_t search
;
670 pending_connection_t
*pending_connection
;
673 time_t now
= time(NULL
);
674 uint8_t is_reverse
= 0;
676 assert_connection_ok(TO_CONN(exitconn
), 0);
677 tor_assert(exitconn
->_base
.s
== -1);
681 /* first check if exitconn->_base.address is an IP. If so, we already
682 * know the answer. */
683 if (tor_addr_from_str(&addr
, exitconn
->_base
.address
) >= 0) {
684 if (tor_addr_family(&addr
) == AF_INET
) {
685 tor_addr_copy(&exitconn
->_base
.addr
, &addr
);
686 exitconn
->address_ttl
= DEFAULT_DNS_TTL
;
694 /* If we're a non-exit, don't even do DNS lookups. */
695 if (!(me
= router_get_my_routerinfo()) ||
696 policy_is_reject_star(me
->exit_policy
)) {
699 if (address_is_invalid_destination(exitconn
->_base
.address
, 0)) {
700 log(LOG_PROTOCOL_WARN
, LD_EXIT
,
701 "Rejecting invalid destination address %s",
702 escaped_safe_str(exitconn
->_base
.address
));
706 /* then take this opportunity to see if there are any expired
707 * resolves in the hash table. */
708 purge_expired_resolves(now
);
710 /* lower-case exitconn->_base.address, so it's in canonical form */
711 tor_strlower(exitconn
->_base
.address
);
713 /* Check whether this is a reverse lookup. If it's malformed, or it's a
714 * .in-addr.arpa address but this isn't a resolve request, kill the
717 if ((r
= tor_addr_parse_reverse_lookup_name(&addr
, exitconn
->_base
.address
,
718 AF_UNSPEC
, 0)) != 0) {
721 if (tor_addr_is_internal(&addr
, 0)) /* internal address? */
725 if (!is_reverse
|| !is_resolve
) {
727 log_info(LD_EXIT
, "Bad .in-addr.arpa address \"%s\"; sending error.",
728 escaped_safe_str(exitconn
->_base
.address
));
729 else if (!is_resolve
)
731 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
733 escaped_safe_str(exitconn
->_base
.address
));
737 //log_notice(LD_EXIT, "Looks like an address %s",
738 //exitconn->_base.address);
741 /* now check the hash table to see if 'address' is already there. */
742 strlcpy(search
.address
, exitconn
->_base
.address
, sizeof(search
.address
));
743 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
744 if (resolve
&& resolve
->expire
> now
) { /* already there */
745 switch (resolve
->state
) {
746 case CACHE_STATE_PENDING
:
747 /* add us to the pending list */
748 pending_connection
= tor_malloc_zero(
749 sizeof(pending_connection_t
));
750 pending_connection
->conn
= exitconn
;
751 pending_connection
->next
= resolve
->pending_connections
;
752 resolve
->pending_connections
= pending_connection
;
753 log_debug(LD_EXIT
,"Connection (fd %d) waiting for pending DNS "
754 "resolve of %s", exitconn
->_base
.s
,
755 escaped_safe_str(exitconn
->_base
.address
));
757 case CACHE_STATE_CACHED_VALID
:
758 log_debug(LD_EXIT
,"Connection (fd %d) found cached answer for %s",
760 escaped_safe_str(resolve
->address
));
761 exitconn
->address_ttl
= resolve
->ttl
;
762 if (resolve
->is_reverse
) {
763 tor_assert(is_resolve
);
764 *hostname_out
= tor_strdup(resolve
->result
.hostname
);
766 tor_addr_from_ipv4h(&exitconn
->_base
.addr
, resolve
->result
.a
.addr
);
769 case CACHE_STATE_CACHED_FAILED
:
770 log_debug(LD_EXIT
,"Connection (fd %d) found cached error for %s",
772 escaped_safe_str(exitconn
->_base
.address
));
774 case CACHE_STATE_DONE
:
775 log_err(LD_BUG
, "Found a 'DONE' dns resolve still in the cache.");
776 tor_fragile_assert();
780 tor_assert(!resolve
);
781 /* not there, need to add it */
782 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
783 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
784 resolve
->state
= CACHE_STATE_PENDING
;
785 resolve
->minheap_idx
= -1;
786 resolve
->is_reverse
= is_reverse
;
787 strlcpy(resolve
->address
, exitconn
->_base
.address
, sizeof(resolve
->address
));
789 /* add this connection to the pending list */
790 pending_connection
= tor_malloc_zero(sizeof(pending_connection_t
));
791 pending_connection
->conn
= exitconn
;
792 resolve
->pending_connections
= pending_connection
;
794 /* Add this resolve to the cache and priority queue. */
795 HT_INSERT(cache_map
, &cache_root
, resolve
);
796 set_expiry(resolve
, now
+ RESOLVE_MAX_TIMEOUT
);
798 log_debug(LD_EXIT
,"Launching %s.",
799 escaped_safe_str(exitconn
->_base
.address
));
802 return launch_resolve(exitconn
);
805 /** Log an error and abort if conn is waiting for a DNS resolve.
808 assert_connection_edge_not_dns_pending(edge_connection_t
*conn
)
810 pending_connection_t
*pend
;
811 cached_resolve_t search
;
814 cached_resolve_t
*resolve
;
815 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
816 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
819 for (pend
= resolve
->pending_connections
; pend
; pend
= pend
->next
) {
820 tor_assert(pend
->conn
!= conn
);
823 cached_resolve_t
**resolve
;
824 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
825 for (pend
= (*resolve
)->pending_connections
; pend
; pend
= pend
->next
) {
826 tor_assert(pend
->conn
!= conn
);
832 /** Log an error and abort if any connection waiting for a DNS resolve is
835 assert_all_pending_dns_resolves_ok(void)
837 pending_connection_t
*pend
;
838 cached_resolve_t
**resolve
;
840 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
841 for (pend
= (*resolve
)->pending_connections
;
844 assert_connection_ok(TO_CONN(pend
->conn
), 0);
845 tor_assert(pend
->conn
->_base
.s
== -1);
846 tor_assert(!connection_in_array(TO_CONN(pend
->conn
)));
851 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
854 connection_dns_remove(edge_connection_t
*conn
)
856 pending_connection_t
*pend
, *victim
;
857 cached_resolve_t search
;
858 cached_resolve_t
*resolve
;
860 tor_assert(conn
->_base
.type
== CONN_TYPE_EXIT
);
861 tor_assert(conn
->_base
.state
== EXIT_CONN_STATE_RESOLVING
);
863 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
865 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
867 log_notice(LD_BUG
, "Address %s is not pending. Dropping.",
868 escaped_safe_str(conn
->_base
.address
));
872 tor_assert(resolve
->pending_connections
);
873 assert_connection_ok(TO_CONN(conn
),0);
875 pend
= resolve
->pending_connections
;
877 if (pend
->conn
== conn
) {
878 resolve
->pending_connections
= pend
->next
;
880 log_debug(LD_EXIT
, "First connection (fd %d) no longer waiting "
883 escaped_safe_str(conn
->_base
.address
));
886 for ( ; pend
->next
; pend
= pend
->next
) {
887 if (pend
->next
->conn
== conn
) {
889 pend
->next
= victim
->next
;
892 "Connection (fd %d) no longer waiting for resolve of %s",
893 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
894 return; /* more are pending */
897 tor_assert(0); /* not reachable unless onlyconn not in pending list */
901 /** Mark all connections waiting for <b>address</b> for close. Then cancel
902 * the resolve for <b>address</b> itself, and remove any cached results for
903 * <b>address</b> from the cache.
906 dns_cancel_pending_resolve(const char *address
)
908 pending_connection_t
*pend
;
909 cached_resolve_t search
;
910 cached_resolve_t
*resolve
, *tmp
;
911 edge_connection_t
*pendconn
;
914 strlcpy(search
.address
, address
, sizeof(search
.address
));
916 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
920 if (resolve
->state
!= CACHE_STATE_PENDING
) {
921 /* We can get into this state if we never actually created the pending
922 * resolve, due to finding an earlier cached error or something. Just
924 if (resolve
->pending_connections
) {
926 "Address %s is not pending but has pending connections!",
927 escaped_safe_str(address
));
928 tor_fragile_assert();
933 if (!resolve
->pending_connections
) {
935 "Address %s is pending but has no pending connections!",
936 escaped_safe_str(address
));
937 tor_fragile_assert();
940 tor_assert(resolve
->pending_connections
);
942 /* mark all pending connections to fail */
944 "Failing all connections waiting on DNS resolve of %s",
945 escaped_safe_str(address
));
946 while (resolve
->pending_connections
) {
947 pend
= resolve
->pending_connections
;
948 pend
->conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
949 pendconn
= pend
->conn
;
950 assert_connection_ok(TO_CONN(pendconn
), 0);
951 tor_assert(pendconn
->_base
.s
== -1);
952 if (!pendconn
->_base
.marked_for_close
) {
953 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
955 circ
= circuit_get_by_edge_conn(pendconn
);
957 circuit_detach_stream(circ
, pendconn
);
958 if (!pendconn
->_base
.marked_for_close
)
959 connection_free(TO_CONN(pendconn
));
960 resolve
->pending_connections
= pend
->next
;
964 tmp
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
965 if (tmp
!= resolve
) {
966 log_err(LD_BUG
, "The cancelled resolve we purged didn't match any in"
967 " the cache. Tried to purge %s (%p); instead got %s (%p).",
968 resolve
->address
, (void*)resolve
,
969 tmp
? tmp
->address
: "NULL", (void*)tmp
);
971 tor_assert(tmp
== resolve
);
973 resolve
->state
= CACHE_STATE_DONE
;
976 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
977 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
978 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
979 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
982 add_answer_to_cache(const char *address
, uint8_t is_reverse
, uint32_t addr
,
983 const char *hostname
, char outcome
, uint32_t ttl
)
985 cached_resolve_t
*resolve
;
986 if (outcome
== DNS_RESOLVE_FAILED_TRANSIENT
)
989 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
990 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
991 // hostname?hostname:"NULL",(int)outcome);
993 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
994 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
995 resolve
->state
= (outcome
== DNS_RESOLVE_SUCCEEDED
) ?
996 CACHE_STATE_CACHED_VALID
: CACHE_STATE_CACHED_FAILED
;
997 strlcpy(resolve
->address
, address
, sizeof(resolve
->address
));
998 resolve
->is_reverse
= is_reverse
;
1000 if (outcome
== DNS_RESOLVE_SUCCEEDED
) {
1001 tor_assert(hostname
);
1002 resolve
->result
.hostname
= tor_strdup(hostname
);
1004 tor_assert(! hostname
);
1005 resolve
->result
.hostname
= NULL
;
1008 tor_assert(!hostname
);
1009 resolve
->result
.a
.addr
= addr
;
1012 assert_resolve_ok(resolve
);
1013 HT_INSERT(cache_map
, &cache_root
, resolve
);
1014 set_expiry(resolve
, time(NULL
) + dns_get_expiry_ttl(ttl
));
1017 /** Return true iff <b>address</b> is one of the addresses we use to verify
1018 * that well-known sites aren't being hijacked by our DNS servers. */
1020 is_test_address(const char *address
)
1022 or_options_t
*options
= get_options();
1023 return options
->ServerDNSTestAddresses
&&
1024 smartlist_string_isin_case(options
->ServerDNSTestAddresses
, address
);
1027 /** Called on the OR side when a DNS worker or the eventdns library tells us
1028 * the outcome of a DNS resolve: tell all pending connections about the result
1029 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
1030 * string containing the address to look up; <b>addr</b> is an IPv4 address in
1031 * host order; <b>outcome</b> is one of
1032 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
1035 dns_found_answer(const char *address
, uint8_t is_reverse
, uint32_t addr
,
1036 const char *hostname
, char outcome
, uint32_t ttl
)
1038 pending_connection_t
*pend
;
1039 cached_resolve_t search
;
1040 cached_resolve_t
*resolve
, *removed
;
1041 edge_connection_t
*pendconn
;
1046 strlcpy(search
.address
, address
, sizeof(search
.address
));
1048 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
1050 int is_test_addr
= is_test_address(address
);
1052 log_info(LD_EXIT
,"Resolved unasked address %s; caching anyway.",
1053 escaped_safe_str(address
));
1054 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1057 assert_resolve_ok(resolve
);
1059 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1060 /* XXXX Maybe update addr? or check addr for consistency? Or let
1061 * VALID replace FAILED? */
1062 int is_test_addr
= is_test_address(address
);
1065 "Resolved %s which was already resolved; ignoring",
1066 escaped_safe_str(address
));
1067 tor_assert(resolve
->pending_connections
== NULL
);
1070 /* Removed this assertion: in fact, we'll sometimes get a double answer
1071 * to the same question. This can happen when we ask one worker to resolve
1072 * X.Y.Z., then we cancel the request, and then we ask another worker to
1074 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
1076 while (resolve
->pending_connections
) {
1077 pend
= resolve
->pending_connections
;
1078 pendconn
= pend
->conn
; /* don't pass complex things to the
1079 connection_mark_for_close macro */
1080 assert_connection_ok(TO_CONN(pendconn
),time(NULL
));
1081 tor_addr_from_ipv4h(&pendconn
->_base
.addr
, addr
);
1082 pendconn
->address_ttl
= ttl
;
1084 if (outcome
!= DNS_RESOLVE_SUCCEEDED
) {
1085 /* prevent double-remove. */
1086 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1087 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1088 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
1089 /* This detach must happen after we send the end cell. */
1090 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1092 send_resolved_cell(pendconn
, outcome
== DNS_RESOLVE_FAILED_PERMANENT
?
1093 RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
1094 /* This detach must happen after we send the resolved cell. */
1095 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1097 connection_free(TO_CONN(pendconn
));
1099 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1100 tor_assert(!is_reverse
);
1101 /* prevent double-remove. */
1102 pend
->conn
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
1104 circ
= circuit_get_by_edge_conn(pend
->conn
);
1106 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1107 /* unlink pend->conn from resolving_streams, */
1108 circuit_detach_stream(circ
, pend
->conn
);
1109 /* and link it to n_streams */
1110 pend
->conn
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
1111 pend
->conn
->on_circuit
= circ
;
1112 TO_OR_CIRCUIT(circ
)->n_streams
= pend
->conn
;
1114 connection_exit_connect(pend
->conn
);
1116 /* prevent double-remove. This isn't really an accurate state,
1117 * but it does the right thing. */
1118 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1120 send_resolved_hostname_cell(pendconn
, hostname
);
1122 send_resolved_cell(pendconn
, RESOLVED_TYPE_IPV4
);
1123 circ
= circuit_get_by_edge_conn(pendconn
);
1125 circuit_detach_stream(circ
, pendconn
);
1126 connection_free(TO_CONN(pendconn
));
1129 resolve
->pending_connections
= pend
->next
;
1133 resolve
->state
= CACHE_STATE_DONE
;
1134 removed
= HT_REMOVE(cache_map
, &cache_root
, &search
);
1135 if (removed
!= resolve
) {
1136 log_err(LD_BUG
, "The pending resolve we found wasn't removable from"
1137 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1138 resolve
->address
, (void*)resolve
,
1139 removed
? removed
->address
: "NULL", (void*)removed
);
1141 assert_resolve_ok(resolve
);
1144 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1148 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1149 * a transient failure. */
1151 evdns_err_is_transient(int err
)
1155 case DNS_ERR_SERVERFAILED
:
1156 case DNS_ERR_TRUNCATED
:
1157 case DNS_ERR_TIMEOUT
:
1164 /** Configure eventdns nameservers if force is true, or if the configuration
1165 * has changed since the last time we called this function, or if we failed on
1166 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1167 * options->ServerDNSResolvConfFile; on Windows, this reads from
1168 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1171 configure_nameservers(int force
)
1173 or_options_t
*options
;
1174 const char *conf_fname
;
1177 options
= get_options();
1178 conf_fname
= options
->ServerDNSResolvConfFile
;
1181 conf_fname
= "/etc/resolv.conf";
1184 if (!the_evdns_base
) {
1185 if (!(the_evdns_base
= evdns_base_new(tor_libevent_get_base(), 0))) {
1186 log_err(LD_BUG
, "Couldn't create an evdns_base");
1191 #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
1192 if (options
->OutboundBindAddress
) {
1194 if (tor_addr_from_str(&addr
, options
->OutboundBindAddress
) < 0) {
1195 log_warn(LD_CONFIG
,"Outbound bind address '%s' didn't parse. Ignoring.",
1196 options
->OutboundBindAddress
);
1199 struct sockaddr_storage ss
;
1200 socklen
= tor_addr_to_sockaddr(&addr
, 0,
1201 (struct sockaddr
*)&ss
, sizeof(ss
));
1203 log_warn(LD_BUG
, "Couldn't convert outbound bind address to sockaddr."
1206 evdns_base_set_default_outgoing_bind_address(the_evdns_base
,
1207 (struct sockaddr
*)&ss
,
1214 evdns_set_log_fn(evdns_log_cb
);
1216 if (stat(conf_fname
, &st
)) {
1217 log_warn(LD_EXIT
, "Unable to stat resolver configuration in '%s': %s",
1218 conf_fname
, strerror(errno
));
1221 if (!force
&& resolv_conf_fname
&& !strcmp(conf_fname
,resolv_conf_fname
)
1222 && st
.st_mtime
== resolv_conf_mtime
) {
1223 log_info(LD_EXIT
, "No change to '%s'", conf_fname
);
1226 if (nameservers_configured
) {
1227 evdns_base_search_clear(the_evdns_base
);
1228 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
1230 log_info(LD_EXIT
, "Parsing resolver configuration in '%s'", conf_fname
);
1231 if ((r
= evdns_base_resolv_conf_parse(the_evdns_base
,
1232 DNS_OPTIONS_ALL
, conf_fname
))) {
1233 log_warn(LD_EXIT
, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1234 conf_fname
, conf_fname
, r
);
1237 if (evdns_base_count_nameservers(the_evdns_base
) == 0) {
1238 log_warn(LD_EXIT
, "Unable to find any nameservers in '%s'.", conf_fname
);
1241 tor_free(resolv_conf_fname
);
1242 resolv_conf_fname
= tor_strdup(conf_fname
);
1243 resolv_conf_mtime
= st
.st_mtime
;
1244 if (nameservers_configured
)
1245 evdns_base_resume(the_evdns_base
);
1249 if (nameservers_configured
) {
1250 evdns_base_search_clear(the_evdns_base
);
1251 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
1253 if (evdns_base_config_windows_nameservers(the_evdns_base
)) {
1254 log_warn(LD_EXIT
,"Could not config nameservers.");
1257 if (evdns_base_count_nameservers(the_evdns_base
) == 0) {
1258 log_warn(LD_EXIT
, "Unable to find any platform nameservers in "
1259 "your Windows configuration.");
1262 if (nameservers_configured
)
1263 evdns_base_resume(the_evdns_base
);
1264 tor_free(resolv_conf_fname
);
1265 resolv_conf_mtime
= 0;
1269 #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
1271 if (evdns_base_count_nameservers(the_evdns_base
) == 1) {
1272 SET("max-timeouts:", "16");
1273 SET("timeout:", "10");
1275 SET("max-timeouts:", "3");
1276 SET("timeout:", "5");
1279 if (options
->ServerDNSRandomizeCase
)
1280 SET("randomize-case:", "1");
1282 SET("randomize-case:", "0");
1286 dns_servers_relaunch_checks();
1288 nameservers_configured
= 1;
1289 if (nameserver_config_failed
) {
1290 nameserver_config_failed
= 0;
1291 mark_my_descriptor_dirty();
1295 nameservers_configured
= 0;
1296 if (! nameserver_config_failed
) {
1297 nameserver_config_failed
= 1;
1298 mark_my_descriptor_dirty();
1303 /** For eventdns: Called when we get an answer for a request we launched.
1304 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1307 evdns_callback(int result
, char type
, int count
, int ttl
, void *addresses
,
1310 char *string_address
= arg
;
1311 uint8_t is_reverse
= 0;
1312 int status
= DNS_RESOLVE_FAILED_PERMANENT
;
1314 const char *hostname
= NULL
;
1315 int was_wildcarded
= 0;
1317 if (result
== DNS_ERR_NONE
) {
1318 if (type
== DNS_IPv4_A
&& count
) {
1319 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1321 char *escaped_address
;
1322 uint32_t *addrs
= addresses
;
1323 in
.s_addr
= addrs
[0];
1324 addr
= ntohl(addrs
[0]);
1325 status
= DNS_RESOLVE_SUCCEEDED
;
1326 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1327 escaped_address
= esc_for_log(string_address
);
1329 if (answer_is_wildcarded(answer_buf
)) {
1330 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1331 "address %s; treating as a failure.",
1332 safe_str(escaped_address
),
1333 escaped_safe_str(answer_buf
));
1336 status
= DNS_RESOLVE_FAILED_PERMANENT
;
1338 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1339 safe_str(escaped_address
),
1340 escaped_safe_str(answer_buf
));
1342 tor_free(escaped_address
);
1343 } else if (type
== DNS_PTR
&& count
) {
1344 char *escaped_address
;
1346 hostname
= ((char**)addresses
)[0];
1347 status
= DNS_RESOLVE_SUCCEEDED
;
1348 escaped_address
= esc_for_log(string_address
);
1349 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1350 safe_str(escaped_address
),
1351 escaped_safe_str(hostname
));
1352 tor_free(escaped_address
);
1354 log_warn(LD_EXIT
, "eventdns returned only non-IPv4 answers for %s.",
1355 escaped_safe_str(string_address
));
1357 log_warn(LD_BUG
, "eventdns returned no addresses or error for %s!",
1358 escaped_safe_str(string_address
));
1361 if (evdns_err_is_transient(result
))
1362 status
= DNS_RESOLVE_FAILED_TRANSIENT
;
1364 if (was_wildcarded
) {
1365 if (is_test_address(string_address
)) {
1366 /* Ick. We're getting redirected on known-good addresses. Our DNS
1367 * server must really hate us. */
1368 add_wildcarded_test_address(string_address
);
1371 if (result
!= DNS_ERR_SHUTDOWN
)
1372 dns_found_answer(string_address
, is_reverse
, addr
, hostname
, status
, ttl
);
1373 tor_free(string_address
);
1376 /** For eventdns: start resolving as necessary to find the target for
1377 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1378 * 0 on "resolve launched." */
1380 launch_resolve(edge_connection_t
*exitconn
)
1382 char *addr
= tor_strdup(exitconn
->_base
.address
);
1383 struct evdns_request
*req
= NULL
;
1386 int options
= get_options()->ServerDNSSearchDomains
? 0
1387 : DNS_QUERY_NO_SEARCH
;
1388 /* What? Nameservers not configured? Sounds like a bug. */
1389 if (!nameservers_configured
) {
1390 log_warn(LD_EXIT
, "(Harmless.) Nameservers not configured, but resolve "
1391 "launched. Configuring.");
1392 if (configure_nameservers(1) < 0) {
1397 r
= tor_addr_parse_reverse_lookup_name(
1398 &a
, exitconn
->_base
.address
, AF_UNSPEC
, 0);
1400 tor_assert(the_evdns_base
);
1402 log_info(LD_EXIT
, "Launching eventdns request for %s",
1403 escaped_safe_str(exitconn
->_base
.address
));
1404 req
= evdns_base_resolve_ipv4(the_evdns_base
,
1405 exitconn
->_base
.address
, options
,
1406 evdns_callback
, addr
);
1407 } else if (r
== 1) {
1408 log_info(LD_EXIT
, "Launching eventdns reverse request for %s",
1409 escaped_safe_str(exitconn
->_base
.address
));
1410 if (tor_addr_family(&a
) == AF_INET
)
1411 req
= evdns_base_resolve_reverse(the_evdns_base
,
1412 tor_addr_to_in(&a
), DNS_QUERY_NO_SEARCH
,
1413 evdns_callback
, addr
);
1415 req
= evdns_base_resolve_reverse_ipv6(the_evdns_base
,
1416 tor_addr_to_in6(&a
), DNS_QUERY_NO_SEARCH
,
1417 evdns_callback
, addr
);
1418 } else if (r
== -1) {
1419 log_warn(LD_BUG
, "Somehow a malformed in-addr.arpa address reached here.");
1424 log_warn(LD_EXIT
, "eventdns rejected address %s.",
1425 escaped_safe_str(addr
));
1427 tor_free(addr
); /* There is no evdns request in progress; stop
1428 * addr from getting leaked. */
1433 /** How many requests for bogus addresses have we launched so far? */
1434 static int n_wildcard_requests
= 0;
1436 /** Map from dotted-quad IP address in response to an int holding how many
1437 * times we've seen it for a randomly generated (hopefully bogus) address. It
1438 * would be easier to use definitely-invalid addresses (as specified by
1439 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1440 static strmap_t
*dns_wildcard_response_count
= NULL
;
1442 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1443 * nameserver wants to return in response to requests for nonexistent domains.
1445 static smartlist_t
*dns_wildcard_list
= NULL
;
1446 /** True iff we've logged about a single address getting wildcarded.
1447 * Subsequent warnings will be less severe. */
1448 static int dns_wildcard_one_notice_given
= 0;
1449 /** True iff we've warned that our DNS server is wildcarding too many failures.
1451 static int dns_wildcard_notice_given
= 0;
1453 /** List of supposedly good addresses that are getting wildcarded to the
1454 * same addresses as nonexistent addresses. */
1455 static smartlist_t
*dns_wildcarded_test_address_list
= NULL
;
1456 /** True iff we've warned about a test address getting wildcarded */
1457 static int dns_wildcarded_test_address_notice_given
= 0;
1458 /** True iff all addresses seem to be getting wildcarded. */
1459 static int dns_is_completely_invalid
= 0;
1461 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1462 * a hopefully bogus address. */
1464 wildcard_increment_answer(const char *id
)
1467 if (!dns_wildcard_response_count
)
1468 dns_wildcard_response_count
= strmap_new();
1470 ip
= strmap_get(dns_wildcard_response_count
, id
); // may be null (0)
1472 ip
= tor_malloc_zero(sizeof(int));
1473 strmap_set(dns_wildcard_response_count
, id
, ip
);
1477 if (*ip
> 5 && n_wildcard_requests
> 10) {
1478 if (!dns_wildcard_list
) dns_wildcard_list
= smartlist_create();
1479 if (!smartlist_string_isin(dns_wildcard_list
, id
)) {
1480 log(dns_wildcard_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1481 "Your DNS provider has given \"%s\" as an answer for %d different "
1482 "invalid addresses. Apparently they are hijacking DNS failures. "
1483 "I'll try to correct for this by treating future occurrences of "
1484 "\"%s\" as 'not found'.", id
, *ip
, id
);
1485 smartlist_add(dns_wildcard_list
, tor_strdup(id
));
1487 if (!dns_wildcard_notice_given
)
1488 control_event_server_status(LOG_NOTICE
, "DNS_HIJACKED");
1489 dns_wildcard_notice_given
= 1;
1493 /** Note that a single test address (one believed to be good) seems to be
1494 * getting redirected to the same IP as failures are. */
1496 add_wildcarded_test_address(const char *address
)
1498 int n
, n_test_addrs
;
1499 if (!dns_wildcarded_test_address_list
)
1500 dns_wildcarded_test_address_list
= smartlist_create();
1502 if (smartlist_string_isin_case(dns_wildcarded_test_address_list
, address
))
1505 n_test_addrs
= get_options()->ServerDNSTestAddresses
?
1506 smartlist_len(get_options()->ServerDNSTestAddresses
) : 0;
1508 smartlist_add(dns_wildcarded_test_address_list
, tor_strdup(address
));
1509 n
= smartlist_len(dns_wildcarded_test_address_list
);
1510 if (n
> n_test_addrs
/2) {
1511 log(dns_wildcarded_test_address_notice_given
? LOG_INFO
: LOG_NOTICE
,
1512 LD_EXIT
, "Your DNS provider tried to redirect \"%s\" to a junk "
1513 "address. It has done this with %d test addresses so far. I'm "
1514 "going to stop being an exit node for now, since our DNS seems so "
1515 "broken.", address
, n
);
1516 if (!dns_is_completely_invalid
) {
1517 dns_is_completely_invalid
= 1;
1518 mark_my_descriptor_dirty();
1520 if (!dns_wildcarded_test_address_notice_given
)
1521 control_event_server_status(LOG_WARN
, "DNS_USELESS");
1522 dns_wildcarded_test_address_notice_given
= 1;
1526 /** Callback function when we get an answer (possibly failing) for a request
1527 * for a (hopefully) nonexistent domain. */
1529 evdns_wildcard_check_callback(int result
, char type
, int count
, int ttl
,
1530 void *addresses
, void *arg
)
1533 ++n_wildcard_requests
;
1534 if (result
== DNS_ERR_NONE
&& type
== DNS_IPv4_A
&& count
) {
1535 uint32_t *addrs
= addresses
;
1537 char *string_address
= arg
;
1538 for (i
= 0; i
< count
; ++i
) {
1539 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1541 in
.s_addr
= addrs
[i
];
1542 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1543 wildcard_increment_answer(answer_buf
);
1545 log(dns_wildcard_one_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1546 "Your DNS provider gave an answer for \"%s\", which "
1547 "is not supposed to exist. Apparently they are hijacking "
1548 "DNS failures. Trying to correct for this. We've noticed %d "
1549 "possibly bad address%s so far.",
1550 string_address
, strmap_size(dns_wildcard_response_count
),
1551 (strmap_size(dns_wildcard_response_count
) == 1) ? "" : "es");
1552 dns_wildcard_one_notice_given
= 1;
1557 /** Launch a single request for a nonexistent hostname consisting of between
1558 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1561 launch_wildcard_check(int min_len
, int max_len
, const char *suffix
)
1564 struct evdns_request
*req
;
1566 addr
= crypto_random_hostname(min_len
, max_len
, "", suffix
);
1567 log_info(LD_EXIT
, "Testing whether our DNS server is hijacking nonexistent "
1568 "domains with request for bogus hostname \"%s\"", addr
);
1570 tor_assert(the_evdns_base
);
1571 req
= evdns_base_resolve_ipv4(
1573 /* This "addr" tells us which address to resolve */
1575 DNS_QUERY_NO_SEARCH
, evdns_wildcard_check_callback
,
1576 /* This "addr" is an argument to the callback*/ addr
);
1578 /* There is no evdns request in progress; stop addr from getting leaked */
1583 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1584 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1586 launch_test_addresses(int fd
, short event
, void *args
)
1588 or_options_t
*options
= get_options();
1589 struct evdns_request
*req
;
1594 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like to "
1595 "hijack *everything*.");
1596 /* This situation is worse than the failure-hijacking situation. When this
1597 * happens, we're no good for DNS requests at all, and we shouldn't really
1598 * be an exit server.*/
1599 if (!options
->ServerDNSTestAddresses
)
1601 tor_assert(the_evdns_base
);
1602 SMARTLIST_FOREACH_BEGIN(options
->ServerDNSTestAddresses
,
1603 const char *, address
) {
1604 char *a
= tor_strdup(address
);
1605 req
= evdns_base_resolve_ipv4(the_evdns_base
,
1606 address
, DNS_QUERY_NO_SEARCH
, evdns_callback
, a
);
1609 log_info(LD_EXIT
, "eventdns rejected test address %s",
1610 escaped_safe_str(address
));
1613 } SMARTLIST_FOREACH_END(address
);
1616 #define N_WILDCARD_CHECKS 2
1618 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1619 * hostnames, and see if we can catch our nameserver trying to hijack them and
1620 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1621 * buy these lovely encyclopedias" page. */
1623 dns_launch_wildcard_checks(void)
1626 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like "
1627 "to hijack DNS failures.");
1628 for (i
= 0; i
< N_WILDCARD_CHECKS
; ++i
) {
1629 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1630 * to 'comply' with rfc2606, refrain from giving A records for these.
1631 * This is the standards-compliance equivalent of making sure that your
1632 * crackhouse's elevator inspection certificate is up to date.
1634 launch_wildcard_check(2, 16, ".invalid");
1635 launch_wildcard_check(2, 16, ".test");
1637 /* These will break specs if there are ever any number of
1638 * 8+-character top-level domains. */
1639 launch_wildcard_check(8, 16, "");
1641 /* Try some random .com/org/net domains. This will work fine so long as
1642 * not too many resolve to the same place. */
1643 launch_wildcard_check(8, 16, ".com");
1644 launch_wildcard_check(8, 16, ".org");
1645 launch_wildcard_check(8, 16, ".net");
1649 /** If appropriate, start testing whether our DNS servers tend to lie to
1652 dns_launch_correctness_checks(void)
1654 static struct event
*launch_event
= NULL
;
1655 struct timeval timeout
;
1656 if (!get_options()->ServerDNSDetectHijacking
)
1658 dns_launch_wildcard_checks();
1660 /* Wait a while before launching requests for test addresses, so we can
1661 * get the results from checking for wildcarding. */
1663 launch_event
= tor_evtimer_new(tor_libevent_get_base(),
1664 launch_test_addresses
, NULL
);
1665 timeout
.tv_sec
= 30;
1666 timeout
.tv_usec
= 0;
1667 if (evtimer_add(launch_event
, &timeout
)<0) {
1668 log_warn(LD_BUG
, "Couldn't add timer for checking for dns hijacking");
1672 /** Return true iff our DNS servers lie to us too much to be trusted. */
1674 dns_seems_to_be_broken(void)
1676 return dns_is_completely_invalid
;
1679 /** Forget what we've previously learned about our DNS servers' correctness. */
1681 dns_reset_correctness_checks(void)
1683 strmap_free(dns_wildcard_response_count
, _tor_free
);
1684 dns_wildcard_response_count
= NULL
;
1686 n_wildcard_requests
= 0;
1688 if (dns_wildcard_list
) {
1689 SMARTLIST_FOREACH(dns_wildcard_list
, char *, cp
, tor_free(cp
));
1690 smartlist_clear(dns_wildcard_list
);
1692 if (dns_wildcarded_test_address_list
) {
1693 SMARTLIST_FOREACH(dns_wildcarded_test_address_list
, char *, cp
,
1695 smartlist_clear(dns_wildcarded_test_address_list
);
1697 dns_wildcard_one_notice_given
= dns_wildcard_notice_given
=
1698 dns_wildcarded_test_address_notice_given
= dns_is_completely_invalid
= 0;
1701 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1702 * returned in response to requests for nonexistent hostnames. */
1704 answer_is_wildcarded(const char *ip
)
1706 return dns_wildcard_list
&& smartlist_string_isin(dns_wildcard_list
, ip
);
1709 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1711 assert_resolve_ok(cached_resolve_t
*resolve
)
1713 tor_assert(resolve
);
1714 tor_assert(resolve
->magic
== CACHED_RESOLVE_MAGIC
);
1715 tor_assert(strlen(resolve
->address
) < MAX_ADDRESSLEN
);
1716 tor_assert(tor_strisnonupper(resolve
->address
));
1717 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1718 tor_assert(!resolve
->pending_connections
);
1720 if (resolve
->state
== CACHE_STATE_PENDING
||
1721 resolve
->state
== CACHE_STATE_DONE
) {
1722 tor_assert(!resolve
->ttl
);
1723 if (resolve
->is_reverse
)
1724 tor_assert(!resolve
->result
.hostname
);
1726 tor_assert(!resolve
->result
.a
.addr
);
1730 /** Return the number of DNS cache entries as an int */
1732 dns_cache_entry_count(void)
1734 return HT_SIZE(&cache_root
);
1737 /** Log memory information about our internal DNS cache at level 'severity'. */
1739 dump_dns_mem_usage(int severity
)
1741 /* This should never be larger than INT_MAX. */
1742 int hash_count
= dns_cache_entry_count();
1743 size_t hash_mem
= sizeof(struct cached_resolve_t
) * hash_count
;
1744 hash_mem
+= HT_MEM_USAGE(&cache_root
);
1746 /* Print out the count and estimated size of our &cache_root. It undercounts
1747 hostnames in cached reverse resolves.
1749 log(severity
, LD_MM
, "Our DNS cache has %d entries.", hash_count
);
1750 log(severity
, LD_MM
, "Our DNS cache size is approximately %u bytes.",
1751 (unsigned)hash_mem
);
1754 #ifdef DEBUG_DNS_CACHE
1755 /** Exit with an assertion if the DNS cache is corrupt. */
1757 _assert_cache_ok(void)
1759 cached_resolve_t
**resolve
;
1760 int bad_rep
= _cache_map_HT_REP_IS_BAD(&cache_root
);
1762 log_err(LD_BUG
, "Bad rep type %d on dns cache hash table", bad_rep
);
1763 tor_assert(!bad_rep
);
1766 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1767 assert_resolve_ok(*resolve
);
1768 tor_assert((*resolve
)->state
!= CACHE_STATE_DONE
);
1770 if (!cached_resolve_pqueue
)
1773 smartlist_pqueue_assert_ok(cached_resolve_pqueue
,
1774 _compare_cached_resolves_by_expiry
,
1775 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
));
1777 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
1779 if (res
->state
== CACHE_STATE_DONE
) {
1780 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);
1781 tor_assert(!found
|| found
!= res
);
1783 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);