1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, 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 /* Note: our internal eventdns.c, plus Libevent 1.4, used a 1 return to
58 * signify failure to launch a resolve. Libevent 2.0 uses a -1 return to
59 * signify a failure on a resolve, though if we're on Libevent 2.0, we should
60 * have event2/dns.h and never hit these macros. Regardless, 0 is success. */
61 #define evdns_base_resolve_ipv4(base, addr, options, cb, ptr) \
62 ((evdns_resolve_ipv4((addr), (options), (cb), (ptr))!=0) \
64 #define evdns_base_resolve_reverse(base, addr, options, cb, ptr) \
65 ((evdns_resolve_reverse((addr), (options), (cb), (ptr))!=0) \
67 #define evdns_base_resolve_reverse_ipv6(base, addr, options, cb, ptr) \
68 ((evdns_resolve_reverse_ipv6((addr), (options), (cb), (ptr))!=0) \
71 #elif defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER < 0x02000303
72 #define evdns_base_set_option_(base, opt, val) \
73 evdns_base_set_option((base), (opt),(val),DNS_OPTIONS_ALL)
76 #define evdns_base_set_option_ evdns_base_set_option
80 /** Longest hostname we're willing to resolve. */
81 #define MAX_ADDRESSLEN 256
83 /** How long will we wait for an answer from the resolver before we decide
84 * that the resolver is wedged? */
85 #define RESOLVE_MAX_TIMEOUT 300
87 /** Possible outcomes from hostname lookup: permanent failure,
88 * transient (retryable) failure, and success. */
89 #define DNS_RESOLVE_FAILED_TRANSIENT 1
90 #define DNS_RESOLVE_FAILED_PERMANENT 2
91 #define DNS_RESOLVE_SUCCEEDED 3
93 /** Our evdns_base; this structure handles all our name lookups. */
94 static struct evdns_base
*the_evdns_base
= NULL
;
96 /** Have we currently configured nameservers with eventdns? */
97 static int nameservers_configured
= 0;
98 /** Did our most recent attempt to configure nameservers with eventdns fail? */
99 static int nameserver_config_failed
= 0;
100 /** What was the resolv_conf fname we last used when configuring the
101 * nameservers? Used to check whether we need to reconfigure. */
102 static char *resolv_conf_fname
= NULL
;
103 /** What was the mtime on the resolv.conf file we last used when configuring
104 * the nameservers? Used to check whether we need to reconfigure. */
105 static time_t resolv_conf_mtime
= 0;
107 /** Linked list of connections waiting for a DNS answer. */
108 typedef struct pending_connection_t
{
109 edge_connection_t
*conn
;
110 struct pending_connection_t
*next
;
111 } pending_connection_t
;
113 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
114 * pointers and memory stomping. */
115 #define CACHED_RESOLVE_MAGIC 0x1234F00D
117 /* Possible states for a cached resolve_t */
118 /** We are waiting for the resolver system to tell us an answer here.
119 * When we get one, or when we time out, the state of this cached_resolve_t
120 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
121 * entry. This cached_resolve_t will be in the hash table so that we will
122 * know not to launch more requests for this addr, but rather to add more
123 * connections to the pending list for the addr. */
124 #define CACHE_STATE_PENDING 0
125 /** This used to be a pending cached_resolve_t, and we got an answer for it.
126 * Now we're waiting for this cached_resolve_t to expire. This should
127 * have no pending connections, and should not appear in the hash table. */
128 #define CACHE_STATE_DONE 1
129 /** We are caching an answer for this address. This should have no pending
130 * connections, and should appear in the hash table. */
131 #define CACHE_STATE_CACHED_VALID 2
132 /** We are caching a failure for this address. This should have no pending
133 * connections, and should appear in the hash table */
134 #define CACHE_STATE_CACHED_FAILED 3
136 /** A DNS request: possibly completed, possibly pending; cached_resolve
137 * structs are stored at the OR side in a hash table, and as a linked
138 * list from oldest to newest.
140 typedef struct cached_resolve_t
{
141 HT_ENTRY(cached_resolve_t
) node
;
143 char address
[MAX_ADDRESSLEN
]; /**< The hostname to be resolved. */
146 struct in6_addr addr6
; /**< IPv6 addr for <b>address</b>. */
147 uint32_t addr
; /**< IPv4 addr for <b>address</b>. */
149 char *hostname
; /**< Hostname for <b>address</b> (if a reverse lookup) */
151 uint8_t state
; /**< Is this cached entry pending/done/valid/failed? */
152 uint8_t is_reverse
; /**< Is this a reverse (addr-to-hostname) lookup? */
153 time_t expire
; /**< Remove items from cache after this time. */
154 uint32_t ttl
; /**< What TTL did the nameserver tell us? */
155 /** Connections that want to know when we get an answer for this resolve. */
156 pending_connection_t
*pending_connections
;
157 /** Position of this element in the heap*/
161 static void purge_expired_resolves(time_t now
);
162 static void dns_found_answer(const char *address
, uint8_t is_reverse
,
163 uint32_t addr
, const char *hostname
, char outcome
,
165 static void send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
);
166 static int launch_resolve(edge_connection_t
*exitconn
);
167 static void add_wildcarded_test_address(const char *address
);
168 static int configure_nameservers(int force
);
169 static int answer_is_wildcarded(const char *ip
);
170 static int dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
171 or_circuit_t
*oncirc
, char **resolved_to_hostname
);
172 #ifdef DEBUG_DNS_CACHE
173 static void _assert_cache_ok(void);
174 #define assert_cache_ok() _assert_cache_ok()
176 #define assert_cache_ok() STMT_NIL
178 static void assert_resolve_ok(cached_resolve_t
*resolve
);
180 /** Hash table of cached_resolve objects. */
181 static HT_HEAD(cache_map
, cached_resolve_t
) cache_root
;
183 /** Function to compare hashed resolves on their addresses; used to
184 * implement hash tables. */
186 cached_resolves_eq(cached_resolve_t
*a
, cached_resolve_t
*b
)
188 /* make this smarter one day? */
189 assert_resolve_ok(a
); // Not b; b may be just a search.
190 return !strncmp(a
->address
, b
->address
, MAX_ADDRESSLEN
);
193 /** Hash function for cached_resolve objects */
194 static INLINE
unsigned int
195 cached_resolve_hash(cached_resolve_t
*a
)
197 return ht_string_hash(a
->address
);
200 HT_PROTOTYPE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
202 HT_GENERATE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
203 cached_resolves_eq
, 0.6, malloc
, realloc
, free
)
205 /** Initialize the DNS cache. */
209 HT_INIT(cache_map
, &cache_root
);
212 /** Helper: called by eventdns when eventdns wants to log something. */
214 evdns_log_cb(int warn
, const char *msg
)
217 static int all_down
= 0;
218 int severity
= warn
? LOG_WARN
: LOG_INFO
;
219 if (!strcmpstart(msg
, "Resolve requested for") &&
220 get_options()->SafeLogging
) {
221 log(LOG_INFO
, LD_EXIT
, "eventdns: Resolve requested.");
223 } else if (!strcmpstart(msg
, "Search: ")) {
226 if (!strcmpstart(msg
, "Nameserver ") && (cp
=strstr(msg
, " has failed: "))) {
227 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
228 const char *err
= strchr(cp
, ':')+2;
230 /* Don't warn about a single failed nameserver; we'll warn with 'all
231 * nameservers have failed' if we're completely out of nameservers;
232 * otherwise, the situation is tolerable. */
234 control_event_server_status(LOG_NOTICE
,
235 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
238 } else if (!strcmpstart(msg
, "Nameserver ") &&
239 (cp
=strstr(msg
, " is back up"))) {
240 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
241 severity
= (all_down
&& warn
) ? LOG_NOTICE
: LOG_INFO
;
243 control_event_server_status(LOG_NOTICE
,
244 "NAMESERVER_STATUS NS=%s STATUS=UP", ns
);
246 } else if (!strcmp(msg
, "All nameservers have failed")) {
247 control_event_server_status(LOG_WARN
, "NAMESERVER_ALL_DOWN");
250 log(severity
, LD_EXIT
, "eventdns: %s", msg
);
253 /** Helper: passed to eventdns.c as a callback so it can generate random
254 * numbers for transaction IDs and 0x20-hack coding. */
256 _dns_randfn(char *b
, size_t n
)
261 /** Initialize the DNS subsystem; called by the OR process. */
266 evdns_set_random_bytes_fn(_dns_randfn
);
267 if (server_mode(get_options())) {
268 int r
= configure_nameservers(1);
274 /** Called when DNS-related options change (or may have changed). Returns -1
275 * on failure, 0 on success. */
279 or_options_t
*options
= get_options();
280 if (! server_mode(options
)) {
282 if (!the_evdns_base
) {
283 if (!(the_evdns_base
= evdns_base_new(tor_libevent_get_base(), 0))) {
284 log_err(LD_BUG
, "Couldn't create an evdns_base");
289 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
290 evdns_base_search_clear(the_evdns_base
);
291 nameservers_configured
= 0;
292 tor_free(resolv_conf_fname
);
293 resolv_conf_mtime
= 0;
295 if (configure_nameservers(0) < 0) {
302 /** Return true iff the most recent attempt to initialize the DNS subsystem
305 has_dns_init_failed(void)
307 return nameserver_config_failed
;
310 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
311 * OP that asked us to resolve it. */
313 dns_clip_ttl(uint32_t ttl
)
315 if (ttl
< MIN_DNS_TTL
)
317 else if (ttl
> MAX_DNS_TTL
)
323 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
326 dns_get_expiry_ttl(uint32_t ttl
)
328 if (ttl
< MIN_DNS_TTL
)
330 else if (ttl
> MAX_DNS_ENTRY_AGE
)
331 return MAX_DNS_ENTRY_AGE
;
336 /** Helper: free storage held by an entry in the DNS cache. */
338 _free_cached_resolve(cached_resolve_t
*r
)
342 while (r
->pending_connections
) {
343 pending_connection_t
*victim
= r
->pending_connections
;
344 r
->pending_connections
= victim
->next
;
348 tor_free(r
->result
.hostname
);
349 r
->magic
= 0xFF00FF00;
353 /** Compare two cached_resolve_t pointers by expiry time, and return
354 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
355 * the priority queue implementation. */
357 _compare_cached_resolves_by_expiry(const void *_a
, const void *_b
)
359 const cached_resolve_t
*a
= _a
, *b
= _b
;
360 if (a
->expire
< b
->expire
)
362 else if (a
->expire
== b
->expire
)
368 /** Priority queue of cached_resolve_t objects to let us know when they
370 static smartlist_t
*cached_resolve_pqueue
= NULL
;
372 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
375 set_expiry(cached_resolve_t
*resolve
, time_t expires
)
377 tor_assert(resolve
&& resolve
->expire
== 0);
378 if (!cached_resolve_pqueue
)
379 cached_resolve_pqueue
= smartlist_create();
380 resolve
->expire
= expires
;
381 smartlist_pqueue_add(cached_resolve_pqueue
,
382 _compare_cached_resolves_by_expiry
,
383 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
),
387 /** Free all storage held in the DNS cache and related structures. */
391 cached_resolve_t
**ptr
, **next
, *item
;
393 if (cached_resolve_pqueue
) {
394 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
396 if (res
->state
== CACHE_STATE_DONE
)
397 _free_cached_resolve(res
);
400 for (ptr
= HT_START(cache_map
, &cache_root
); ptr
!= NULL
; ptr
= next
) {
402 next
= HT_NEXT_RMV(cache_map
, &cache_root
, ptr
);
403 _free_cached_resolve(item
);
405 HT_CLEAR(cache_map
, &cache_root
);
406 smartlist_free(cached_resolve_pqueue
);
407 cached_resolve_pqueue
= NULL
;
408 tor_free(resolv_conf_fname
);
411 /** Remove every cached_resolve whose <b>expire</b> time is before or
412 * equal to <b>now</b> from the cache. */
414 purge_expired_resolves(time_t now
)
416 cached_resolve_t
*resolve
, *removed
;
417 pending_connection_t
*pend
;
418 edge_connection_t
*pendconn
;
421 if (!cached_resolve_pqueue
)
424 while (smartlist_len(cached_resolve_pqueue
)) {
425 resolve
= smartlist_get(cached_resolve_pqueue
, 0);
426 if (resolve
->expire
> now
)
428 smartlist_pqueue_pop(cached_resolve_pqueue
,
429 _compare_cached_resolves_by_expiry
,
430 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
));
432 if (resolve
->state
== CACHE_STATE_PENDING
) {
434 "Expiring a dns resolve %s that's still pending. Forgot to "
435 "cull it? DNS resolve didn't tell us about the timeout?",
436 escaped_safe_str(resolve
->address
));
437 } else if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
438 resolve
->state
== CACHE_STATE_CACHED_FAILED
) {
440 "Forgetting old cached resolve (address %s, expires %lu)",
441 escaped_safe_str(resolve
->address
),
442 (unsigned long)resolve
->expire
);
443 tor_assert(!resolve
->pending_connections
);
445 tor_assert(resolve
->state
== CACHE_STATE_DONE
);
446 tor_assert(!resolve
->pending_connections
);
449 if (resolve
->pending_connections
) {
451 "Closing pending connections on timed-out DNS resolve!");
452 tor_fragile_assert();
453 while (resolve
->pending_connections
) {
454 pend
= resolve
->pending_connections
;
455 resolve
->pending_connections
= pend
->next
;
456 /* Connections should only be pending if they have no socket. */
457 tor_assert(pend
->conn
->_base
.s
== -1);
458 pendconn
= pend
->conn
;
459 connection_edge_end(pendconn
, END_STREAM_REASON_TIMEOUT
);
460 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
461 connection_free(TO_CONN(pendconn
));
466 if (resolve
->state
== CACHE_STATE_CACHED_VALID
||
467 resolve
->state
== CACHE_STATE_CACHED_FAILED
||
468 resolve
->state
== CACHE_STATE_PENDING
) {
469 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
470 if (removed
!= resolve
) {
471 log_err(LD_BUG
, "The expired resolve we purged didn't match any in"
472 " the cache. Tried to purge %s (%p); instead got %s (%p).",
473 resolve
->address
, (void*)resolve
,
474 removed
? removed
->address
: "NULL", (void*)removed
);
476 tor_assert(removed
== resolve
);
478 /* This should be in state DONE. Make sure it's not in the cache. */
479 cached_resolve_t
*tmp
= HT_FIND(cache_map
, &cache_root
, resolve
);
480 tor_assert(tmp
!= resolve
);
482 if (resolve
->is_reverse
)
483 tor_free(resolve
->result
.hostname
);
484 resolve
->magic
= 0xF0BBF0BB;
491 /** Send a response to the RESOLVE request of a connection.
492 * <b>answer_type</b> must be one of
493 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
495 * If <b>circ</b> is provided, and we have a cached answer, send the
496 * answer back along circ; otherwise, send the answer back along
497 * <b>conn</b>'s attached circuit.
500 send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
)
502 char buf
[RELAY_PAYLOAD_SIZE
];
506 buf
[0] = answer_type
;
507 ttl
= dns_clip_ttl(conn
->address_ttl
);
511 case RESOLVED_TYPE_IPV4
:
513 set_uint32(buf
+2, tor_addr_to_ipv4n(&conn
->_base
.addr
));
514 set_uint32(buf
+6, htonl(ttl
));
517 /*XXXX IP6 need ipv6 implementation */
518 case RESOLVED_TYPE_ERROR_TRANSIENT
:
519 case RESOLVED_TYPE_ERROR
:
521 const char *errmsg
= "Error resolving hostname";
522 size_t msglen
= strlen(errmsg
);
525 strlcpy(buf
+2, errmsg
, sizeof(buf
)-2);
526 set_uint32(buf
+2+msglen
, htonl(ttl
));
534 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
536 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
539 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
540 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
541 * The answer type will be RESOLVED_HOSTNAME.
543 * If <b>circ</b> is provided, and we have a cached answer, send the
544 * answer back along circ; otherwise, send the answer back along
545 * <b>conn</b>'s attached circuit.
548 send_resolved_hostname_cell(edge_connection_t
*conn
, const char *hostname
)
550 char buf
[RELAY_PAYLOAD_SIZE
];
553 size_t namelen
= strlen(hostname
);
554 tor_assert(hostname
);
556 tor_assert(namelen
< 256);
557 ttl
= dns_clip_ttl(conn
->address_ttl
);
559 buf
[0] = RESOLVED_TYPE_HOSTNAME
;
560 buf
[1] = (uint8_t)namelen
;
561 memcpy(buf
+2, hostname
, namelen
);
562 set_uint32(buf
+2+namelen
, htonl(ttl
));
563 buflen
= 2+namelen
+4;
565 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
566 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
567 // log_notice(LD_EXIT, "Sent");
570 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
571 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
572 * If resolve failed, free exitconn and return -1.
574 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
575 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
576 * need to send back an END cell, since connection_exit_begin_conn will
579 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
582 * Else, if seen before and pending, add conn to the pending list,
585 * Else, if not seen before, add conn to pending list, hand to
586 * dns farm, and return 0.
588 * Exitconn's on_circuit field must be set, but exitconn should not
589 * yet be linked onto the n_streams/resolving_streams list of that circuit.
590 * On success, link the connection to n_streams if it's an exit connection.
591 * On "pending", link the connection to resolving streams. Otherwise,
592 * clear its on_circuit field.
595 dns_resolve(edge_connection_t
*exitconn
)
597 or_circuit_t
*oncirc
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
599 char *hostname
= NULL
;
600 is_resolve
= exitconn
->_base
.purpose
== EXIT_PURPOSE_RESOLVE
;
602 r
= dns_resolve_impl(exitconn
, is_resolve
, oncirc
, &hostname
);
606 /* We got an answer without a lookup -- either the answer was
607 * cached, or it was obvious (like an IP address). */
609 /* Send the answer back right now, and detach. */
611 send_resolved_hostname_cell(exitconn
, hostname
);
613 send_resolved_cell(exitconn
, RESOLVED_TYPE_IPV4
);
614 exitconn
->on_circuit
= NULL
;
616 /* Add to the n_streams list; the calling function will send back a
618 exitconn
->next_stream
= oncirc
->n_streams
;
619 oncirc
->n_streams
= exitconn
;
623 /* The request is pending: add the connection into the linked list of
624 * resolving_streams on this circuit. */
625 exitconn
->_base
.state
= EXIT_CONN_STATE_RESOLVING
;
626 exitconn
->next_stream
= oncirc
->resolving_streams
;
627 oncirc
->resolving_streams
= exitconn
;
631 /* The request failed before it could start: cancel this connection,
632 * and stop everybody waiting for the same connection. */
634 send_resolved_cell(exitconn
,
635 (r
== -1) ? RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
638 exitconn
->on_circuit
= NULL
;
640 dns_cancel_pending_resolve(exitconn
->_base
.address
);
642 if (!exitconn
->_base
.marked_for_close
) {
643 connection_free(TO_CONN(exitconn
));
644 // XXX ... and we just leak exitconn otherwise? -RD
645 // If it's marked for close, it's on closeable_connection_lst in
646 // main.c. If it's on the closeable list, it will get freed from
648 // "<armadev> If that's true, there are other bugs around, where we
649 // don't check if it's marked, and will end up double-freeing."
650 // On the other hand, I don't know of any actual bugs here, so this
651 // shouldn't be holding up the rc. -RD
662 /** Helper function for dns_resolve: same functionality, but does not handle:
663 * - marking connections on error and clearing their on_circuit
664 * - linking connections to n_streams/resolving_streams,
665 * - sending resolved cells if we have an answer/error right away,
667 * Return -2 on a transient error. If it's a reverse resolve and it's
668 * successful, sets *<b>hostname_out</b> to a newly allocated string
669 * holding the cached reverse DNS value.
672 dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
673 or_circuit_t
*oncirc
, char **hostname_out
)
675 cached_resolve_t
*resolve
;
676 cached_resolve_t search
;
677 pending_connection_t
*pending_connection
;
680 time_t now
= time(NULL
);
681 uint8_t is_reverse
= 0;
683 assert_connection_ok(TO_CONN(exitconn
), 0);
684 tor_assert(exitconn
->_base
.s
== -1);
688 /* first check if exitconn->_base.address is an IP. If so, we already
689 * know the answer. */
690 if (tor_addr_from_str(&addr
, exitconn
->_base
.address
) >= 0) {
691 if (tor_addr_family(&addr
) == AF_INET
) {
692 tor_addr_copy(&exitconn
->_base
.addr
, &addr
);
693 exitconn
->address_ttl
= DEFAULT_DNS_TTL
;
701 /* If we're a non-exit, don't even do DNS lookups. */
702 if (!(me
= router_get_my_routerinfo()) ||
703 policy_is_reject_star(me
->exit_policy
)) {
706 if (address_is_invalid_destination(exitconn
->_base
.address
, 0)) {
707 log(LOG_PROTOCOL_WARN
, LD_EXIT
,
708 "Rejecting invalid destination address %s",
709 escaped_safe_str(exitconn
->_base
.address
));
713 /* then take this opportunity to see if there are any expired
714 * resolves in the hash table. */
715 purge_expired_resolves(now
);
717 /* lower-case exitconn->_base.address, so it's in canonical form */
718 tor_strlower(exitconn
->_base
.address
);
720 /* Check whether this is a reverse lookup. If it's malformed, or it's a
721 * .in-addr.arpa address but this isn't a resolve request, kill the
724 if ((r
= tor_addr_parse_reverse_lookup_name(&addr
, exitconn
->_base
.address
,
725 AF_UNSPEC
, 0)) != 0) {
728 if (tor_addr_is_internal(&addr
, 0)) /* internal address? */
732 if (!is_reverse
|| !is_resolve
) {
734 log_info(LD_EXIT
, "Bad .in-addr.arpa address \"%s\"; sending error.",
735 escaped_safe_str(exitconn
->_base
.address
));
736 else if (!is_resolve
)
738 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
740 escaped_safe_str(exitconn
->_base
.address
));
744 //log_notice(LD_EXIT, "Looks like an address %s",
745 //exitconn->_base.address);
748 /* now check the hash table to see if 'address' is already there. */
749 strlcpy(search
.address
, exitconn
->_base
.address
, sizeof(search
.address
));
750 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
751 if (resolve
&& resolve
->expire
> now
) { /* already there */
752 switch (resolve
->state
) {
753 case CACHE_STATE_PENDING
:
754 /* add us to the pending list */
755 pending_connection
= tor_malloc_zero(
756 sizeof(pending_connection_t
));
757 pending_connection
->conn
= exitconn
;
758 pending_connection
->next
= resolve
->pending_connections
;
759 resolve
->pending_connections
= pending_connection
;
760 log_debug(LD_EXIT
,"Connection (fd %d) waiting for pending DNS "
761 "resolve of %s", exitconn
->_base
.s
,
762 escaped_safe_str(exitconn
->_base
.address
));
764 case CACHE_STATE_CACHED_VALID
:
765 log_debug(LD_EXIT
,"Connection (fd %d) found cached answer for %s",
767 escaped_safe_str(resolve
->address
));
768 exitconn
->address_ttl
= resolve
->ttl
;
769 if (resolve
->is_reverse
) {
770 tor_assert(is_resolve
);
771 *hostname_out
= tor_strdup(resolve
->result
.hostname
);
773 tor_addr_from_ipv4h(&exitconn
->_base
.addr
, resolve
->result
.a
.addr
);
776 case CACHE_STATE_CACHED_FAILED
:
777 log_debug(LD_EXIT
,"Connection (fd %d) found cached error for %s",
779 escaped_safe_str(exitconn
->_base
.address
));
781 case CACHE_STATE_DONE
:
782 log_err(LD_BUG
, "Found a 'DONE' dns resolve still in the cache.");
783 tor_fragile_assert();
787 tor_assert(!resolve
);
788 /* not there, need to add it */
789 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
790 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
791 resolve
->state
= CACHE_STATE_PENDING
;
792 resolve
->minheap_idx
= -1;
793 resolve
->is_reverse
= is_reverse
;
794 strlcpy(resolve
->address
, exitconn
->_base
.address
, sizeof(resolve
->address
));
796 /* add this connection to the pending list */
797 pending_connection
= tor_malloc_zero(sizeof(pending_connection_t
));
798 pending_connection
->conn
= exitconn
;
799 resolve
->pending_connections
= pending_connection
;
801 /* Add this resolve to the cache and priority queue. */
802 HT_INSERT(cache_map
, &cache_root
, resolve
);
803 set_expiry(resolve
, now
+ RESOLVE_MAX_TIMEOUT
);
805 log_debug(LD_EXIT
,"Launching %s.",
806 escaped_safe_str(exitconn
->_base
.address
));
809 return launch_resolve(exitconn
);
812 /** Log an error and abort if conn is waiting for a DNS resolve.
815 assert_connection_edge_not_dns_pending(edge_connection_t
*conn
)
817 pending_connection_t
*pend
;
818 cached_resolve_t search
;
821 cached_resolve_t
*resolve
;
822 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
823 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
826 for (pend
= resolve
->pending_connections
; pend
; pend
= pend
->next
) {
827 tor_assert(pend
->conn
!= conn
);
830 cached_resolve_t
**resolve
;
831 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
832 for (pend
= (*resolve
)->pending_connections
; pend
; pend
= pend
->next
) {
833 tor_assert(pend
->conn
!= conn
);
839 /** Log an error and abort if any connection waiting for a DNS resolve is
842 assert_all_pending_dns_resolves_ok(void)
844 pending_connection_t
*pend
;
845 cached_resolve_t
**resolve
;
847 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
848 for (pend
= (*resolve
)->pending_connections
;
851 assert_connection_ok(TO_CONN(pend
->conn
), 0);
852 tor_assert(pend
->conn
->_base
.s
== -1);
853 tor_assert(!connection_in_array(TO_CONN(pend
->conn
)));
858 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
861 connection_dns_remove(edge_connection_t
*conn
)
863 pending_connection_t
*pend
, *victim
;
864 cached_resolve_t search
;
865 cached_resolve_t
*resolve
;
867 tor_assert(conn
->_base
.type
== CONN_TYPE_EXIT
);
868 tor_assert(conn
->_base
.state
== EXIT_CONN_STATE_RESOLVING
);
870 strlcpy(search
.address
, conn
->_base
.address
, sizeof(search
.address
));
872 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
874 log_notice(LD_BUG
, "Address %s is not pending. Dropping.",
875 escaped_safe_str(conn
->_base
.address
));
879 tor_assert(resolve
->pending_connections
);
880 assert_connection_ok(TO_CONN(conn
),0);
882 pend
= resolve
->pending_connections
;
884 if (pend
->conn
== conn
) {
885 resolve
->pending_connections
= pend
->next
;
887 log_debug(LD_EXIT
, "First connection (fd %d) no longer waiting "
890 escaped_safe_str(conn
->_base
.address
));
893 for ( ; pend
->next
; pend
= pend
->next
) {
894 if (pend
->next
->conn
== conn
) {
896 pend
->next
= victim
->next
;
899 "Connection (fd %d) no longer waiting for resolve of %s",
900 conn
->_base
.s
, escaped_safe_str(conn
->_base
.address
));
901 return; /* more are pending */
904 tor_assert(0); /* not reachable unless onlyconn not in pending list */
908 /** Mark all connections waiting for <b>address</b> for close. Then cancel
909 * the resolve for <b>address</b> itself, and remove any cached results for
910 * <b>address</b> from the cache.
913 dns_cancel_pending_resolve(const char *address
)
915 pending_connection_t
*pend
;
916 cached_resolve_t search
;
917 cached_resolve_t
*resolve
, *tmp
;
918 edge_connection_t
*pendconn
;
921 strlcpy(search
.address
, address
, sizeof(search
.address
));
923 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
927 if (resolve
->state
!= CACHE_STATE_PENDING
) {
928 /* We can get into this state if we never actually created the pending
929 * resolve, due to finding an earlier cached error or something. Just
931 if (resolve
->pending_connections
) {
933 "Address %s is not pending but has pending connections!",
934 escaped_safe_str(address
));
935 tor_fragile_assert();
940 if (!resolve
->pending_connections
) {
942 "Address %s is pending but has no pending connections!",
943 escaped_safe_str(address
));
944 tor_fragile_assert();
947 tor_assert(resolve
->pending_connections
);
949 /* mark all pending connections to fail */
951 "Failing all connections waiting on DNS resolve of %s",
952 escaped_safe_str(address
));
953 while (resolve
->pending_connections
) {
954 pend
= resolve
->pending_connections
;
955 pend
->conn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
956 pendconn
= pend
->conn
;
957 assert_connection_ok(TO_CONN(pendconn
), 0);
958 tor_assert(pendconn
->_base
.s
== -1);
959 if (!pendconn
->_base
.marked_for_close
) {
960 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
962 circ
= circuit_get_by_edge_conn(pendconn
);
964 circuit_detach_stream(circ
, pendconn
);
965 if (!pendconn
->_base
.marked_for_close
)
966 connection_free(TO_CONN(pendconn
));
967 resolve
->pending_connections
= pend
->next
;
971 tmp
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
972 if (tmp
!= resolve
) {
973 log_err(LD_BUG
, "The cancelled resolve we purged didn't match any in"
974 " the cache. Tried to purge %s (%p); instead got %s (%p).",
975 resolve
->address
, (void*)resolve
,
976 tmp
? tmp
->address
: "NULL", (void*)tmp
);
978 tor_assert(tmp
== resolve
);
980 resolve
->state
= CACHE_STATE_DONE
;
983 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
984 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
985 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
986 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
989 add_answer_to_cache(const char *address
, uint8_t is_reverse
, uint32_t addr
,
990 const char *hostname
, char outcome
, uint32_t ttl
)
992 cached_resolve_t
*resolve
;
993 if (outcome
== DNS_RESOLVE_FAILED_TRANSIENT
)
996 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
997 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
998 // hostname?hostname:"NULL",(int)outcome);
1000 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
1001 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
1002 resolve
->state
= (outcome
== DNS_RESOLVE_SUCCEEDED
) ?
1003 CACHE_STATE_CACHED_VALID
: CACHE_STATE_CACHED_FAILED
;
1004 strlcpy(resolve
->address
, address
, sizeof(resolve
->address
));
1005 resolve
->is_reverse
= is_reverse
;
1007 if (outcome
== DNS_RESOLVE_SUCCEEDED
) {
1008 tor_assert(hostname
);
1009 resolve
->result
.hostname
= tor_strdup(hostname
);
1011 tor_assert(! hostname
);
1012 resolve
->result
.hostname
= NULL
;
1015 tor_assert(!hostname
);
1016 resolve
->result
.a
.addr
= addr
;
1019 assert_resolve_ok(resolve
);
1020 HT_INSERT(cache_map
, &cache_root
, resolve
);
1021 set_expiry(resolve
, time(NULL
) + dns_get_expiry_ttl(ttl
));
1024 /** Return true iff <b>address</b> is one of the addresses we use to verify
1025 * that well-known sites aren't being hijacked by our DNS servers. */
1027 is_test_address(const char *address
)
1029 or_options_t
*options
= get_options();
1030 return options
->ServerDNSTestAddresses
&&
1031 smartlist_string_isin_case(options
->ServerDNSTestAddresses
, address
);
1034 /** Called on the OR side when a DNS worker or the eventdns library tells us
1035 * the outcome of a DNS resolve: tell all pending connections about the result
1036 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
1037 * string containing the address to look up; <b>addr</b> is an IPv4 address in
1038 * host order; <b>outcome</b> is one of
1039 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
1042 dns_found_answer(const char *address
, uint8_t is_reverse
, uint32_t addr
,
1043 const char *hostname
, char outcome
, uint32_t ttl
)
1045 pending_connection_t
*pend
;
1046 cached_resolve_t search
;
1047 cached_resolve_t
*resolve
, *removed
;
1048 edge_connection_t
*pendconn
;
1053 strlcpy(search
.address
, address
, sizeof(search
.address
));
1055 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
1057 int is_test_addr
= is_test_address(address
);
1059 log_info(LD_EXIT
,"Resolved unasked address %s; caching anyway.",
1060 escaped_safe_str(address
));
1061 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1064 assert_resolve_ok(resolve
);
1066 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1067 /* XXXX Maybe update addr? or check addr for consistency? Or let
1068 * VALID replace FAILED? */
1069 int is_test_addr
= is_test_address(address
);
1072 "Resolved %s which was already resolved; ignoring",
1073 escaped_safe_str(address
));
1074 tor_assert(resolve
->pending_connections
== NULL
);
1077 /* Removed this assertion: in fact, we'll sometimes get a double answer
1078 * to the same question. This can happen when we ask one worker to resolve
1079 * X.Y.Z., then we cancel the request, and then we ask another worker to
1081 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
1083 while (resolve
->pending_connections
) {
1084 pend
= resolve
->pending_connections
;
1085 pendconn
= pend
->conn
; /* don't pass complex things to the
1086 connection_mark_for_close macro */
1087 assert_connection_ok(TO_CONN(pendconn
),time(NULL
));
1088 tor_addr_from_ipv4h(&pendconn
->_base
.addr
, addr
);
1089 pendconn
->address_ttl
= ttl
;
1091 if (outcome
!= DNS_RESOLVE_SUCCEEDED
) {
1092 /* prevent double-remove. */
1093 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1094 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1095 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
1096 /* This detach must happen after we send the end cell. */
1097 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1099 send_resolved_cell(pendconn
, outcome
== DNS_RESOLVE_FAILED_PERMANENT
?
1100 RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
);
1101 /* This detach must happen after we send the resolved cell. */
1102 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1104 connection_free(TO_CONN(pendconn
));
1106 if (pendconn
->_base
.purpose
== EXIT_PURPOSE_CONNECT
) {
1107 tor_assert(!is_reverse
);
1108 /* prevent double-remove. */
1109 pend
->conn
->_base
.state
= EXIT_CONN_STATE_CONNECTING
;
1111 circ
= circuit_get_by_edge_conn(pend
->conn
);
1113 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1114 /* unlink pend->conn from resolving_streams, */
1115 circuit_detach_stream(circ
, pend
->conn
);
1116 /* and link it to n_streams */
1117 pend
->conn
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
1118 pend
->conn
->on_circuit
= circ
;
1119 TO_OR_CIRCUIT(circ
)->n_streams
= pend
->conn
;
1121 connection_exit_connect(pend
->conn
);
1123 /* prevent double-remove. This isn't really an accurate state,
1124 * but it does the right thing. */
1125 pendconn
->_base
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1127 send_resolved_hostname_cell(pendconn
, hostname
);
1129 send_resolved_cell(pendconn
, RESOLVED_TYPE_IPV4
);
1130 circ
= circuit_get_by_edge_conn(pendconn
);
1132 circuit_detach_stream(circ
, pendconn
);
1133 connection_free(TO_CONN(pendconn
));
1136 resolve
->pending_connections
= pend
->next
;
1140 resolve
->state
= CACHE_STATE_DONE
;
1141 removed
= HT_REMOVE(cache_map
, &cache_root
, &search
);
1142 if (removed
!= resolve
) {
1143 log_err(LD_BUG
, "The pending resolve we found wasn't removable from"
1144 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1145 resolve
->address
, (void*)resolve
,
1146 removed
? removed
->address
: "NULL", (void*)removed
);
1148 assert_resolve_ok(resolve
);
1151 add_answer_to_cache(address
, is_reverse
, addr
, hostname
, outcome
, ttl
);
1155 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1156 * a transient failure. */
1158 evdns_err_is_transient(int err
)
1162 case DNS_ERR_SERVERFAILED
:
1163 case DNS_ERR_TRUNCATED
:
1164 case DNS_ERR_TIMEOUT
:
1171 /** Configure eventdns nameservers if force is true, or if the configuration
1172 * has changed since the last time we called this function, or if we failed on
1173 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1174 * options->ServerDNSResolvConfFile; on Windows, this reads from
1175 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1178 configure_nameservers(int force
)
1180 or_options_t
*options
;
1181 const char *conf_fname
;
1184 options
= get_options();
1185 conf_fname
= options
->ServerDNSResolvConfFile
;
1188 conf_fname
= "/etc/resolv.conf";
1191 if (!the_evdns_base
) {
1192 if (!(the_evdns_base
= evdns_base_new(tor_libevent_get_base(), 0))) {
1193 log_err(LD_BUG
, "Couldn't create an evdns_base");
1198 #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
1199 if (options
->OutboundBindAddress
) {
1201 if (tor_addr_from_str(&addr
, options
->OutboundBindAddress
) < 0) {
1202 log_warn(LD_CONFIG
,"Outbound bind address '%s' didn't parse. Ignoring.",
1203 options
->OutboundBindAddress
);
1206 struct sockaddr_storage ss
;
1207 socklen
= tor_addr_to_sockaddr(&addr
, 0,
1208 (struct sockaddr
*)&ss
, sizeof(ss
));
1210 log_warn(LD_BUG
, "Couldn't convert outbound bind address to sockaddr."
1213 evdns_base_set_default_outgoing_bind_address(the_evdns_base
,
1214 (struct sockaddr
*)&ss
,
1221 evdns_set_log_fn(evdns_log_cb
);
1223 if (stat(conf_fname
, &st
)) {
1224 log_warn(LD_EXIT
, "Unable to stat resolver configuration in '%s': %s",
1225 conf_fname
, strerror(errno
));
1228 if (!force
&& resolv_conf_fname
&& !strcmp(conf_fname
,resolv_conf_fname
)
1229 && st
.st_mtime
== resolv_conf_mtime
) {
1230 log_info(LD_EXIT
, "No change to '%s'", conf_fname
);
1233 if (nameservers_configured
) {
1234 evdns_base_search_clear(the_evdns_base
);
1235 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
1237 log_info(LD_EXIT
, "Parsing resolver configuration in '%s'", conf_fname
);
1238 if ((r
= evdns_base_resolv_conf_parse(the_evdns_base
,
1239 DNS_OPTIONS_ALL
, conf_fname
))) {
1240 log_warn(LD_EXIT
, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1241 conf_fname
, conf_fname
, r
);
1244 if (evdns_base_count_nameservers(the_evdns_base
) == 0) {
1245 log_warn(LD_EXIT
, "Unable to find any nameservers in '%s'.", conf_fname
);
1248 tor_free(resolv_conf_fname
);
1249 resolv_conf_fname
= tor_strdup(conf_fname
);
1250 resolv_conf_mtime
= st
.st_mtime
;
1251 if (nameservers_configured
)
1252 evdns_base_resume(the_evdns_base
);
1256 if (nameservers_configured
) {
1257 evdns_base_search_clear(the_evdns_base
);
1258 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
1260 if (evdns_base_config_windows_nameservers(the_evdns_base
)) {
1261 log_warn(LD_EXIT
,"Could not config nameservers.");
1264 if (evdns_base_count_nameservers(the_evdns_base
) == 0) {
1265 log_warn(LD_EXIT
, "Unable to find any platform nameservers in "
1266 "your Windows configuration.");
1269 if (nameservers_configured
)
1270 evdns_base_resume(the_evdns_base
);
1271 tor_free(resolv_conf_fname
);
1272 resolv_conf_mtime
= 0;
1276 #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
1278 if (evdns_base_count_nameservers(the_evdns_base
) == 1) {
1279 SET("max-timeouts:", "16");
1280 SET("timeout:", "10");
1282 SET("max-timeouts:", "3");
1283 SET("timeout:", "5");
1286 if (options
->ServerDNSRandomizeCase
)
1287 SET("randomize-case:", "1");
1289 SET("randomize-case:", "0");
1293 dns_servers_relaunch_checks();
1295 nameservers_configured
= 1;
1296 if (nameserver_config_failed
) {
1297 nameserver_config_failed
= 0;
1298 mark_my_descriptor_dirty();
1302 nameservers_configured
= 0;
1303 if (! nameserver_config_failed
) {
1304 nameserver_config_failed
= 1;
1305 mark_my_descriptor_dirty();
1310 /** For eventdns: Called when we get an answer for a request we launched.
1311 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1314 evdns_callback(int result
, char type
, int count
, int ttl
, void *addresses
,
1317 char *string_address
= arg
;
1318 uint8_t is_reverse
= 0;
1319 int status
= DNS_RESOLVE_FAILED_PERMANENT
;
1321 const char *hostname
= NULL
;
1322 int was_wildcarded
= 0;
1324 if (result
== DNS_ERR_NONE
) {
1325 if (type
== DNS_IPv4_A
&& count
) {
1326 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1328 char *escaped_address
;
1329 uint32_t *addrs
= addresses
;
1330 in
.s_addr
= addrs
[0];
1331 addr
= ntohl(addrs
[0]);
1332 status
= DNS_RESOLVE_SUCCEEDED
;
1333 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1334 escaped_address
= esc_for_log(string_address
);
1336 if (answer_is_wildcarded(answer_buf
)) {
1337 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1338 "address %s; treating as a failure.",
1339 safe_str(escaped_address
),
1340 escaped_safe_str(answer_buf
));
1343 status
= DNS_RESOLVE_FAILED_PERMANENT
;
1345 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1346 safe_str(escaped_address
),
1347 escaped_safe_str(answer_buf
));
1349 tor_free(escaped_address
);
1350 } else if (type
== DNS_PTR
&& count
) {
1351 char *escaped_address
;
1353 hostname
= ((char**)addresses
)[0];
1354 status
= DNS_RESOLVE_SUCCEEDED
;
1355 escaped_address
= esc_for_log(string_address
);
1356 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1357 safe_str(escaped_address
),
1358 escaped_safe_str(hostname
));
1359 tor_free(escaped_address
);
1361 log_warn(LD_EXIT
, "eventdns returned only non-IPv4 answers for %s.",
1362 escaped_safe_str(string_address
));
1364 log_warn(LD_BUG
, "eventdns returned no addresses or error for %s!",
1365 escaped_safe_str(string_address
));
1368 if (evdns_err_is_transient(result
))
1369 status
= DNS_RESOLVE_FAILED_TRANSIENT
;
1371 if (was_wildcarded
) {
1372 if (is_test_address(string_address
)) {
1373 /* Ick. We're getting redirected on known-good addresses. Our DNS
1374 * server must really hate us. */
1375 add_wildcarded_test_address(string_address
);
1378 if (result
!= DNS_ERR_SHUTDOWN
)
1379 dns_found_answer(string_address
, is_reverse
, addr
, hostname
, status
, ttl
);
1380 tor_free(string_address
);
1383 /** For eventdns: start resolving as necessary to find the target for
1384 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1385 * 0 on "resolve launched." */
1387 launch_resolve(edge_connection_t
*exitconn
)
1389 char *addr
= tor_strdup(exitconn
->_base
.address
);
1390 struct evdns_request
*req
= NULL
;
1393 int options
= get_options()->ServerDNSSearchDomains
? 0
1394 : DNS_QUERY_NO_SEARCH
;
1395 /* What? Nameservers not configured? Sounds like a bug. */
1396 if (!nameservers_configured
) {
1397 log_warn(LD_EXIT
, "(Harmless.) Nameservers not configured, but resolve "
1398 "launched. Configuring.");
1399 if (configure_nameservers(1) < 0) {
1404 r
= tor_addr_parse_reverse_lookup_name(
1405 &a
, exitconn
->_base
.address
, AF_UNSPEC
, 0);
1407 tor_assert(the_evdns_base
);
1409 log_info(LD_EXIT
, "Launching eventdns request for %s",
1410 escaped_safe_str(exitconn
->_base
.address
));
1411 req
= evdns_base_resolve_ipv4(the_evdns_base
,
1412 exitconn
->_base
.address
, options
,
1413 evdns_callback
, addr
);
1414 } else if (r
== 1) {
1415 log_info(LD_EXIT
, "Launching eventdns reverse request for %s",
1416 escaped_safe_str(exitconn
->_base
.address
));
1417 if (tor_addr_family(&a
) == AF_INET
)
1418 req
= evdns_base_resolve_reverse(the_evdns_base
,
1419 tor_addr_to_in(&a
), DNS_QUERY_NO_SEARCH
,
1420 evdns_callback
, addr
);
1422 req
= evdns_base_resolve_reverse_ipv6(the_evdns_base
,
1423 tor_addr_to_in6(&a
), DNS_QUERY_NO_SEARCH
,
1424 evdns_callback
, addr
);
1425 } else if (r
== -1) {
1426 log_warn(LD_BUG
, "Somehow a malformed in-addr.arpa address reached here.");
1431 log_warn(LD_EXIT
, "eventdns rejected address %s.",
1432 escaped_safe_str(addr
));
1434 tor_free(addr
); /* There is no evdns request in progress; stop
1435 * addr from getting leaked. */
1440 /** How many requests for bogus addresses have we launched so far? */
1441 static int n_wildcard_requests
= 0;
1443 /** Map from dotted-quad IP address in response to an int holding how many
1444 * times we've seen it for a randomly generated (hopefully bogus) address. It
1445 * would be easier to use definitely-invalid addresses (as specified by
1446 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1447 static strmap_t
*dns_wildcard_response_count
= NULL
;
1449 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1450 * nameserver wants to return in response to requests for nonexistent domains.
1452 static smartlist_t
*dns_wildcard_list
= NULL
;
1453 /** True iff we've logged about a single address getting wildcarded.
1454 * Subsequent warnings will be less severe. */
1455 static int dns_wildcard_one_notice_given
= 0;
1456 /** True iff we've warned that our DNS server is wildcarding too many failures.
1458 static int dns_wildcard_notice_given
= 0;
1460 /** List of supposedly good addresses that are getting wildcarded to the
1461 * same addresses as nonexistent addresses. */
1462 static smartlist_t
*dns_wildcarded_test_address_list
= NULL
;
1463 /** True iff we've warned about a test address getting wildcarded */
1464 static int dns_wildcarded_test_address_notice_given
= 0;
1465 /** True iff all addresses seem to be getting wildcarded. */
1466 static int dns_is_completely_invalid
= 0;
1468 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1469 * a hopefully bogus address. */
1471 wildcard_increment_answer(const char *id
)
1474 if (!dns_wildcard_response_count
)
1475 dns_wildcard_response_count
= strmap_new();
1477 ip
= strmap_get(dns_wildcard_response_count
, id
); // may be null (0)
1479 ip
= tor_malloc_zero(sizeof(int));
1480 strmap_set(dns_wildcard_response_count
, id
, ip
);
1484 if (*ip
> 5 && n_wildcard_requests
> 10) {
1485 if (!dns_wildcard_list
) dns_wildcard_list
= smartlist_create();
1486 if (!smartlist_string_isin(dns_wildcard_list
, id
)) {
1487 log(dns_wildcard_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1488 "Your DNS provider has given \"%s\" as an answer for %d different "
1489 "invalid addresses. Apparently they are hijacking DNS failures. "
1490 "I'll try to correct for this by treating future occurrences of "
1491 "\"%s\" as 'not found'.", id
, *ip
, id
);
1492 smartlist_add(dns_wildcard_list
, tor_strdup(id
));
1494 if (!dns_wildcard_notice_given
)
1495 control_event_server_status(LOG_NOTICE
, "DNS_HIJACKED");
1496 dns_wildcard_notice_given
= 1;
1500 /** Note that a single test address (one believed to be good) seems to be
1501 * getting redirected to the same IP as failures are. */
1503 add_wildcarded_test_address(const char *address
)
1505 int n
, n_test_addrs
;
1506 if (!dns_wildcarded_test_address_list
)
1507 dns_wildcarded_test_address_list
= smartlist_create();
1509 if (smartlist_string_isin_case(dns_wildcarded_test_address_list
, address
))
1512 n_test_addrs
= get_options()->ServerDNSTestAddresses
?
1513 smartlist_len(get_options()->ServerDNSTestAddresses
) : 0;
1515 smartlist_add(dns_wildcarded_test_address_list
, tor_strdup(address
));
1516 n
= smartlist_len(dns_wildcarded_test_address_list
);
1517 if (n
> n_test_addrs
/2) {
1518 log(dns_wildcarded_test_address_notice_given
? LOG_INFO
: LOG_NOTICE
,
1519 LD_EXIT
, "Your DNS provider tried to redirect \"%s\" to a junk "
1520 "address. It has done this with %d test addresses so far. I'm "
1521 "going to stop being an exit node for now, since our DNS seems so "
1522 "broken.", address
, n
);
1523 if (!dns_is_completely_invalid
) {
1524 dns_is_completely_invalid
= 1;
1525 mark_my_descriptor_dirty();
1527 if (!dns_wildcarded_test_address_notice_given
)
1528 control_event_server_status(LOG_WARN
, "DNS_USELESS");
1529 dns_wildcarded_test_address_notice_given
= 1;
1533 /** Callback function when we get an answer (possibly failing) for a request
1534 * for a (hopefully) nonexistent domain. */
1536 evdns_wildcard_check_callback(int result
, char type
, int count
, int ttl
,
1537 void *addresses
, void *arg
)
1540 ++n_wildcard_requests
;
1541 if (result
== DNS_ERR_NONE
&& type
== DNS_IPv4_A
&& count
) {
1542 uint32_t *addrs
= addresses
;
1544 char *string_address
= arg
;
1545 for (i
= 0; i
< count
; ++i
) {
1546 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1548 in
.s_addr
= addrs
[i
];
1549 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1550 wildcard_increment_answer(answer_buf
);
1552 log(dns_wildcard_one_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1553 "Your DNS provider gave an answer for \"%s\", which "
1554 "is not supposed to exist. Apparently they are hijacking "
1555 "DNS failures. Trying to correct for this. We've noticed %d "
1556 "possibly bad address%s so far.",
1557 string_address
, strmap_size(dns_wildcard_response_count
),
1558 (strmap_size(dns_wildcard_response_count
) == 1) ? "" : "es");
1559 dns_wildcard_one_notice_given
= 1;
1564 /** Launch a single request for a nonexistent hostname consisting of between
1565 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1568 launch_wildcard_check(int min_len
, int max_len
, const char *suffix
)
1571 struct evdns_request
*req
;
1573 addr
= crypto_random_hostname(min_len
, max_len
, "", suffix
);
1574 log_info(LD_EXIT
, "Testing whether our DNS server is hijacking nonexistent "
1575 "domains with request for bogus hostname \"%s\"", addr
);
1577 tor_assert(the_evdns_base
);
1578 req
= evdns_base_resolve_ipv4(
1580 /* This "addr" tells us which address to resolve */
1582 DNS_QUERY_NO_SEARCH
, evdns_wildcard_check_callback
,
1583 /* This "addr" is an argument to the callback*/ addr
);
1585 /* There is no evdns request in progress; stop addr from getting leaked */
1590 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1591 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1593 launch_test_addresses(int fd
, short event
, void *args
)
1595 or_options_t
*options
= get_options();
1596 struct evdns_request
*req
;
1601 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like to "
1602 "hijack *everything*.");
1603 /* This situation is worse than the failure-hijacking situation. When this
1604 * happens, we're no good for DNS requests at all, and we shouldn't really
1605 * be an exit server.*/
1606 if (!options
->ServerDNSTestAddresses
)
1608 tor_assert(the_evdns_base
);
1609 SMARTLIST_FOREACH_BEGIN(options
->ServerDNSTestAddresses
,
1610 const char *, address
) {
1611 char *a
= tor_strdup(address
);
1612 req
= evdns_base_resolve_ipv4(the_evdns_base
,
1613 address
, DNS_QUERY_NO_SEARCH
, evdns_callback
, a
);
1616 log_info(LD_EXIT
, "eventdns rejected test address %s",
1617 escaped_safe_str(address
));
1620 } SMARTLIST_FOREACH_END(address
);
1623 #define N_WILDCARD_CHECKS 2
1625 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1626 * hostnames, and see if we can catch our nameserver trying to hijack them and
1627 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1628 * buy these lovely encyclopedias" page. */
1630 dns_launch_wildcard_checks(void)
1633 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like "
1634 "to hijack DNS failures.");
1635 for (i
= 0; i
< N_WILDCARD_CHECKS
; ++i
) {
1636 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1637 * to 'comply' with rfc2606, refrain from giving A records for these.
1638 * This is the standards-compliance equivalent of making sure that your
1639 * crackhouse's elevator inspection certificate is up to date.
1641 launch_wildcard_check(2, 16, ".invalid");
1642 launch_wildcard_check(2, 16, ".test");
1644 /* These will break specs if there are ever any number of
1645 * 8+-character top-level domains. */
1646 launch_wildcard_check(8, 16, "");
1648 /* Try some random .com/org/net domains. This will work fine so long as
1649 * not too many resolve to the same place. */
1650 launch_wildcard_check(8, 16, ".com");
1651 launch_wildcard_check(8, 16, ".org");
1652 launch_wildcard_check(8, 16, ".net");
1656 /** If appropriate, start testing whether our DNS servers tend to lie to
1659 dns_launch_correctness_checks(void)
1661 static struct event
*launch_event
= NULL
;
1662 struct timeval timeout
;
1663 if (!get_options()->ServerDNSDetectHijacking
)
1665 dns_launch_wildcard_checks();
1667 /* Wait a while before launching requests for test addresses, so we can
1668 * get the results from checking for wildcarding. */
1670 launch_event
= tor_evtimer_new(tor_libevent_get_base(),
1671 launch_test_addresses
, NULL
);
1672 timeout
.tv_sec
= 30;
1673 timeout
.tv_usec
= 0;
1674 if (evtimer_add(launch_event
, &timeout
)<0) {
1675 log_warn(LD_BUG
, "Couldn't add timer for checking for dns hijacking");
1679 /** Return true iff our DNS servers lie to us too much to be trusted. */
1681 dns_seems_to_be_broken(void)
1683 return dns_is_completely_invalid
;
1686 /** Forget what we've previously learned about our DNS servers' correctness. */
1688 dns_reset_correctness_checks(void)
1690 strmap_free(dns_wildcard_response_count
, _tor_free
);
1691 dns_wildcard_response_count
= NULL
;
1693 n_wildcard_requests
= 0;
1695 if (dns_wildcard_list
) {
1696 SMARTLIST_FOREACH(dns_wildcard_list
, char *, cp
, tor_free(cp
));
1697 smartlist_clear(dns_wildcard_list
);
1699 if (dns_wildcarded_test_address_list
) {
1700 SMARTLIST_FOREACH(dns_wildcarded_test_address_list
, char *, cp
,
1702 smartlist_clear(dns_wildcarded_test_address_list
);
1704 dns_wildcard_one_notice_given
= dns_wildcard_notice_given
=
1705 dns_wildcarded_test_address_notice_given
= dns_is_completely_invalid
= 0;
1708 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1709 * returned in response to requests for nonexistent hostnames. */
1711 answer_is_wildcarded(const char *ip
)
1713 return dns_wildcard_list
&& smartlist_string_isin(dns_wildcard_list
, ip
);
1716 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1718 assert_resolve_ok(cached_resolve_t
*resolve
)
1720 tor_assert(resolve
);
1721 tor_assert(resolve
->magic
== CACHED_RESOLVE_MAGIC
);
1722 tor_assert(strlen(resolve
->address
) < MAX_ADDRESSLEN
);
1723 tor_assert(tor_strisnonupper(resolve
->address
));
1724 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1725 tor_assert(!resolve
->pending_connections
);
1727 if (resolve
->state
== CACHE_STATE_PENDING
||
1728 resolve
->state
== CACHE_STATE_DONE
) {
1729 tor_assert(!resolve
->ttl
);
1730 if (resolve
->is_reverse
)
1731 tor_assert(!resolve
->result
.hostname
);
1733 tor_assert(!resolve
->result
.a
.addr
);
1737 /** Return the number of DNS cache entries as an int */
1739 dns_cache_entry_count(void)
1741 return HT_SIZE(&cache_root
);
1744 /** Log memory information about our internal DNS cache at level 'severity'. */
1746 dump_dns_mem_usage(int severity
)
1748 /* This should never be larger than INT_MAX. */
1749 int hash_count
= dns_cache_entry_count();
1750 size_t hash_mem
= sizeof(struct cached_resolve_t
) * hash_count
;
1751 hash_mem
+= HT_MEM_USAGE(&cache_root
);
1753 /* Print out the count and estimated size of our &cache_root. It undercounts
1754 hostnames in cached reverse resolves.
1756 log(severity
, LD_MM
, "Our DNS cache has %d entries.", hash_count
);
1757 log(severity
, LD_MM
, "Our DNS cache size is approximately %u bytes.",
1758 (unsigned)hash_mem
);
1761 #ifdef DEBUG_DNS_CACHE
1762 /** Exit with an assertion if the DNS cache is corrupt. */
1764 _assert_cache_ok(void)
1766 cached_resolve_t
**resolve
;
1767 int bad_rep
= _cache_map_HT_REP_IS_BAD(&cache_root
);
1769 log_err(LD_BUG
, "Bad rep type %d on dns cache hash table", bad_rep
);
1770 tor_assert(!bad_rep
);
1773 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1774 assert_resolve_ok(*resolve
);
1775 tor_assert((*resolve
)->state
!= CACHE_STATE_DONE
);
1777 if (!cached_resolve_pqueue
)
1780 smartlist_pqueue_assert_ok(cached_resolve_pqueue
,
1781 _compare_cached_resolves_by_expiry
,
1782 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
));
1784 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
1786 if (res
->state
== CACHE_STATE_DONE
) {
1787 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);
1788 tor_assert(!found
|| found
!= res
);
1790 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);