1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, 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 #include "../common/sandbox.h"
28 #ifdef HAVE_EVENT2_DNS_H
29 #include <event2/event.h>
30 #include <event2/dns.h>
34 #ifndef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
35 #define HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
39 #ifndef HAVE_EVENT2_DNS_H
42 #define evdns_base_new(x,y) tor_malloc(1)
43 #define evdns_base_clear_nameservers_and_suspend(base) \
44 evdns_clear_nameservers_and_suspend()
45 #define evdns_base_search_clear(base) evdns_search_clear()
46 #define evdns_base_set_default_outgoing_bind_address(base, a, len) \
47 evdns_set_default_outgoing_bind_address((a),(len))
48 #define evdns_base_resolv_conf_parse(base, options, fname) \
49 evdns_resolv_conf_parse((options), (fname))
50 #define evdns_base_count_nameservers(base) \
51 evdns_count_nameservers()
52 #define evdns_base_resume(base) \
54 #define evdns_base_config_windows_nameservers(base) \
55 evdns_config_windows_nameservers()
56 #define evdns_base_set_option_(base, opt, val) \
57 evdns_set_option((opt),(val),DNS_OPTIONS_ALL)
58 /* Note: our internal eventdns.c, plus Libevent 1.4, used a 1 return to
59 * signify failure to launch a resolve. Libevent 2.0 uses a -1 return to
60 * signify a failure on a resolve, though if we're on Libevent 2.0, we should
61 * have event2/dns.h and never hit these macros. Regardless, 0 is success. */
62 #define evdns_base_resolve_ipv4(base, addr, options, cb, ptr) \
63 ((evdns_resolve_ipv4((addr), (options), (cb), (ptr))!=0) \
65 #define evdns_base_resolve_ipv6(base, addr, options, cb, ptr) \
66 ((evdns_resolve_ipv6((addr), (options), (cb), (ptr))!=0) \
68 #define evdns_base_resolve_reverse(base, addr, options, cb, ptr) \
69 ((evdns_resolve_reverse((addr), (options), (cb), (ptr))!=0) \
71 #define evdns_base_resolve_reverse_ipv6(base, addr, options, cb, ptr) \
72 ((evdns_resolve_reverse_ipv6((addr), (options), (cb), (ptr))!=0) \
75 #elif defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER < 0x02000303
76 #define evdns_base_set_option_(base, opt, val) \
77 evdns_base_set_option((base), (opt),(val),DNS_OPTIONS_ALL)
80 #define evdns_base_set_option_ evdns_base_set_option
84 /** Longest hostname we're willing to resolve. */
85 #define MAX_ADDRESSLEN 256
87 /** How long will we wait for an answer from the resolver before we decide
88 * that the resolver is wedged? */
89 #define RESOLVE_MAX_TIMEOUT 300
91 /** Our evdns_base; this structure handles all our name lookups. */
92 static struct evdns_base
*the_evdns_base
= NULL
;
94 /** Have we currently configured nameservers with eventdns? */
95 static int nameservers_configured
= 0;
96 /** Did our most recent attempt to configure nameservers with eventdns fail? */
97 static int nameserver_config_failed
= 0;
98 /** What was the resolv_conf fname we last used when configuring the
99 * nameservers? Used to check whether we need to reconfigure. */
100 static char *resolv_conf_fname
= NULL
;
101 /** What was the mtime on the resolv.conf file we last used when configuring
102 * the nameservers? Used to check whether we need to reconfigure. */
103 static time_t resolv_conf_mtime
= 0;
105 /** Linked list of connections waiting for a DNS answer. */
106 typedef struct pending_connection_t
{
107 edge_connection_t
*conn
;
108 struct pending_connection_t
*next
;
109 } pending_connection_t
;
111 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
112 * pointers and memory stomping. */
113 #define CACHED_RESOLVE_MAGIC 0x1234F00D
115 /* Possible states for a cached resolve_t */
116 /** We are waiting for the resolver system to tell us an answer here.
117 * When we get one, or when we time out, the state of this cached_resolve_t
118 * will become "DONE" and we'll possibly add a CACHED
119 * entry. This cached_resolve_t will be in the hash table so that we will
120 * know not to launch more requests for this addr, but rather to add more
121 * connections to the pending list for the addr. */
122 #define CACHE_STATE_PENDING 0
123 /** This used to be a pending cached_resolve_t, and we got an answer for it.
124 * Now we're waiting for this cached_resolve_t to expire. This should
125 * have no pending connections, and should not appear in the hash table. */
126 #define CACHE_STATE_DONE 1
127 /** We are caching an answer for this address. This should have no pending
128 * connections, and should appear in the hash table. */
129 #define CACHE_STATE_CACHED 2
131 /** @name status values for a single DNS request.
134 /** The DNS request is in progress. */
135 #define RES_STATUS_INFLIGHT 1
136 /** The DNS request finished and gave an answer */
137 #define RES_STATUS_DONE_OK 2
138 /** The DNS request finished and gave an error */
139 #define RES_STATUS_DONE_ERR 3
142 /** A DNS request: possibly completed, possibly pending; cached_resolve
143 * structs are stored at the OR side in a hash table, and as a linked
144 * list from oldest to newest.
146 typedef struct cached_resolve_t
{
147 HT_ENTRY(cached_resolve_t
) node
;
148 uint32_t magic
; /**< Must be CACHED_RESOLVE_MAGIC */
149 char address
[MAX_ADDRESSLEN
]; /**< The hostname to be resolved. */
152 uint32_t addr_ipv4
; /**< IPv4 addr for <b>address</b>, if successful.
153 * (In host order.) */
154 int err_ipv4
; /**< One of DNS_ERR_*, if IPv4 lookup failed. */
155 } result_ipv4
; /**< Outcome of IPv4 lookup */
157 struct in6_addr addr_ipv6
; /**< IPv6 addr for <b>address</b>, if
159 int err_ipv6
; /**< One of DNS_ERR_*, if IPv6 lookup failed. */
160 } result_ipv6
; /**< Outcome of IPv6 lookup, if any */
162 char *hostname
; /** A hostname, if PTR lookup happened successfully*/
163 int err_hostname
; /** One of DNS_ERR_*, if PTR lookup failed. */
165 /** @name Status fields
167 * These take one of the RES_STATUS_* values, depending on the state
168 * of the corresponding lookup.
171 unsigned int res_status_ipv4
: 2;
172 unsigned int res_status_ipv6
: 2;
173 unsigned int res_status_hostname
: 2;
175 uint8_t state
; /**< Is this cached entry pending/done/informative? */
177 time_t expire
; /**< Remove items from cache after this time. */
178 uint32_t ttl_ipv4
; /**< What TTL did the nameserver tell us? */
179 uint32_t ttl_ipv6
; /**< What TTL did the nameserver tell us? */
180 uint32_t ttl_hostname
; /**< What TTL did the nameserver tell us? */
181 /** Connections that want to know when we get an answer for this resolve. */
182 pending_connection_t
*pending_connections
;
183 /** Position of this element in the heap*/
187 static void purge_expired_resolves(time_t now
);
188 static void dns_found_answer(const char *address
, uint8_t query_type
,
190 const tor_addr_t
*addr
,
191 const char *hostname
,
193 static void send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
,
194 const cached_resolve_t
*resolve
);
195 static int launch_resolve(cached_resolve_t
*resolve
);
196 static void add_wildcarded_test_address(const char *address
);
197 static int configure_nameservers(int force
);
198 static int answer_is_wildcarded(const char *ip
);
199 static int dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
200 or_circuit_t
*oncirc
, char **resolved_to_hostname
,
201 int *made_connection_pending_out
,
202 cached_resolve_t
**resolve_out
);
203 static int set_exitconn_info_from_resolve(edge_connection_t
*exitconn
,
204 const cached_resolve_t
*resolve
,
205 char **hostname_out
);
206 static int evdns_err_is_transient(int err
);
207 static void inform_pending_connections(cached_resolve_t
*resolve
);
208 static void make_pending_resolve_cached(cached_resolve_t
*cached
);
210 #ifdef DEBUG_DNS_CACHE
211 static void assert_cache_ok_(void);
212 #define assert_cache_ok() assert_cache_ok_()
214 #define assert_cache_ok() STMT_NIL
216 static void assert_resolve_ok(cached_resolve_t
*resolve
);
218 /** Hash table of cached_resolve objects. */
219 static HT_HEAD(cache_map
, cached_resolve_t
) cache_root
;
221 /** Global: how many IPv6 requests have we made in all? */
222 static uint64_t n_ipv6_requests_made
= 0;
223 /** Global: how many IPv6 requests have timed out? */
224 static uint64_t n_ipv6_timeouts
= 0;
225 /** Global: Do we think that IPv6 DNS is broken? */
226 static int dns_is_broken_for_ipv6
= 0;
228 /** Function to compare hashed resolves on their addresses; used to
229 * implement hash tables. */
231 cached_resolves_eq(cached_resolve_t
*a
, cached_resolve_t
*b
)
233 /* make this smarter one day? */
234 assert_resolve_ok(a
); // Not b; b may be just a search.
235 return !strncmp(a
->address
, b
->address
, MAX_ADDRESSLEN
);
238 /** Hash function for cached_resolve objects */
239 static INLINE
unsigned int
240 cached_resolve_hash(cached_resolve_t
*a
)
242 return (unsigned) siphash24g((const uint8_t*)a
->address
, strlen(a
->address
));
245 HT_PROTOTYPE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
247 HT_GENERATE(cache_map
, cached_resolve_t
, node
, cached_resolve_hash
,
248 cached_resolves_eq
, 0.6, malloc
, realloc
, free
)
250 /** Initialize the DNS cache. */
254 HT_INIT(cache_map
, &cache_root
);
257 /** Helper: called by eventdns when eventdns wants to log something. */
259 evdns_log_cb(int warn
, const char *msg
)
262 static int all_down
= 0;
263 int severity
= warn
? LOG_WARN
: LOG_INFO
;
264 if (!strcmpstart(msg
, "Resolve requested for") &&
265 get_options()->SafeLogging
) {
266 log_info(LD_EXIT
, "eventdns: Resolve requested.");
268 } else if (!strcmpstart(msg
, "Search: ")) {
271 if (!strcmpstart(msg
, "Nameserver ") && (cp
=strstr(msg
, " has failed: "))) {
272 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
273 const char *err
= strchr(cp
, ':')+2;
275 /* Don't warn about a single failed nameserver; we'll warn with 'all
276 * nameservers have failed' if we're completely out of nameservers;
277 * otherwise, the situation is tolerable. */
279 control_event_server_status(LOG_NOTICE
,
280 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
283 } else if (!strcmpstart(msg
, "Nameserver ") &&
284 (cp
=strstr(msg
, " is back up"))) {
285 char *ns
= tor_strndup(msg
+11, cp
-(msg
+11));
286 severity
= (all_down
&& warn
) ? LOG_NOTICE
: LOG_INFO
;
288 control_event_server_status(LOG_NOTICE
,
289 "NAMESERVER_STATUS NS=%s STATUS=UP", ns
);
291 } else if (!strcmp(msg
, "All nameservers have failed")) {
292 control_event_server_status(LOG_WARN
, "NAMESERVER_ALL_DOWN");
295 tor_log(severity
, LD_EXIT
, "eventdns: %s", msg
);
298 /** Helper: passed to eventdns.c as a callback so it can generate random
299 * numbers for transaction IDs and 0x20-hack coding. */
301 dns_randfn_(char *b
, size_t n
)
306 /** Initialize the DNS subsystem; called by the OR process. */
311 evdns_set_random_bytes_fn(dns_randfn_
);
312 if (server_mode(get_options())) {
313 int r
= configure_nameservers(1);
319 /** Called when DNS-related options change (or may have changed). Returns -1
320 * on failure, 0 on success. */
324 const or_options_t
*options
= get_options();
325 if (! server_mode(options
)) {
327 if (!the_evdns_base
) {
328 if (!(the_evdns_base
= evdns_base_new(tor_libevent_get_base(), 0))) {
329 log_err(LD_BUG
, "Couldn't create an evdns_base");
334 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
335 evdns_base_search_clear(the_evdns_base
);
336 nameservers_configured
= 0;
337 tor_free(resolv_conf_fname
);
338 resolv_conf_mtime
= 0;
340 if (configure_nameservers(0) < 0) {
347 /** Return true iff the most recent attempt to initialize the DNS subsystem
350 has_dns_init_failed(void)
352 return nameserver_config_failed
;
355 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
356 * OP that asked us to resolve it. */
358 dns_clip_ttl(uint32_t ttl
)
360 if (ttl
< MIN_DNS_TTL
)
362 else if (ttl
> MAX_DNS_TTL
)
368 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
371 dns_get_expiry_ttl(uint32_t ttl
)
373 if (ttl
< MIN_DNS_TTL
)
375 else if (ttl
> MAX_DNS_ENTRY_AGE
)
376 return MAX_DNS_ENTRY_AGE
;
381 /** Helper: free storage held by an entry in the DNS cache. */
383 free_cached_resolve_(cached_resolve_t
*r
)
387 while (r
->pending_connections
) {
388 pending_connection_t
*victim
= r
->pending_connections
;
389 r
->pending_connections
= victim
->next
;
392 if (r
->res_status_hostname
== RES_STATUS_DONE_OK
)
393 tor_free(r
->result_ptr
.hostname
);
394 r
->magic
= 0xFF00FF00;
398 /** Compare two cached_resolve_t pointers by expiry time, and return
399 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
400 * the priority queue implementation. */
402 compare_cached_resolves_by_expiry_(const void *_a
, const void *_b
)
404 const cached_resolve_t
*a
= _a
, *b
= _b
;
405 if (a
->expire
< b
->expire
)
407 else if (a
->expire
== b
->expire
)
413 /** Priority queue of cached_resolve_t objects to let us know when they
415 static smartlist_t
*cached_resolve_pqueue
= NULL
;
418 cached_resolve_add_answer(cached_resolve_t
*resolve
,
421 const tor_addr_t
*answer_addr
,
422 const char *answer_hostname
,
425 if (query_type
== DNS_PTR
) {
426 if (resolve
->res_status_hostname
!= RES_STATUS_INFLIGHT
)
429 if (dns_result
== DNS_ERR_NONE
&& answer_hostname
) {
430 resolve
->result_ptr
.hostname
= tor_strdup(answer_hostname
);
431 resolve
->res_status_hostname
= RES_STATUS_DONE_OK
;
433 resolve
->result_ptr
.err_hostname
= dns_result
;
434 resolve
->res_status_hostname
= RES_STATUS_DONE_ERR
;
436 resolve
->ttl_hostname
= ttl
;
437 } else if (query_type
== DNS_IPv4_A
) {
438 if (resolve
->res_status_ipv4
!= RES_STATUS_INFLIGHT
)
441 if (dns_result
== DNS_ERR_NONE
&& answer_addr
&&
442 tor_addr_family(answer_addr
) == AF_INET
) {
443 resolve
->result_ipv4
.addr_ipv4
= tor_addr_to_ipv4h(answer_addr
);
444 resolve
->res_status_ipv4
= RES_STATUS_DONE_OK
;
446 resolve
->result_ipv4
.err_ipv4
= dns_result
;
447 resolve
->res_status_ipv4
= RES_STATUS_DONE_ERR
;
450 } else if (query_type
== DNS_IPv6_AAAA
) {
451 if (resolve
->res_status_ipv6
!= RES_STATUS_INFLIGHT
)
454 if (dns_result
== DNS_ERR_NONE
&& answer_addr
&&
455 tor_addr_family(answer_addr
) == AF_INET6
) {
456 memcpy(&resolve
->result_ipv6
.addr_ipv6
,
457 tor_addr_to_in6(answer_addr
),
458 sizeof(struct in6_addr
));
459 resolve
->res_status_ipv6
= RES_STATUS_DONE_OK
;
461 resolve
->result_ipv6
.err_ipv6
= dns_result
;
462 resolve
->res_status_ipv6
= RES_STATUS_DONE_ERR
;
467 /** Return true iff there are no in-flight requests for <b>resolve</b>. */
469 cached_resolve_have_all_answers(const cached_resolve_t
*resolve
)
471 return (resolve
->res_status_ipv4
!= RES_STATUS_INFLIGHT
&&
472 resolve
->res_status_ipv6
!= RES_STATUS_INFLIGHT
&&
473 resolve
->res_status_hostname
!= RES_STATUS_INFLIGHT
);
476 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
479 set_expiry(cached_resolve_t
*resolve
, time_t expires
)
481 tor_assert(resolve
&& resolve
->expire
== 0);
482 if (!cached_resolve_pqueue
)
483 cached_resolve_pqueue
= smartlist_new();
484 resolve
->expire
= expires
;
485 smartlist_pqueue_add(cached_resolve_pqueue
,
486 compare_cached_resolves_by_expiry_
,
487 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
),
491 /** Free all storage held in the DNS cache and related structures. */
495 cached_resolve_t
**ptr
, **next
, *item
;
497 if (cached_resolve_pqueue
) {
498 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
500 if (res
->state
== CACHE_STATE_DONE
)
501 free_cached_resolve_(res
);
504 for (ptr
= HT_START(cache_map
, &cache_root
); ptr
!= NULL
; ptr
= next
) {
506 next
= HT_NEXT_RMV(cache_map
, &cache_root
, ptr
);
507 free_cached_resolve_(item
);
509 HT_CLEAR(cache_map
, &cache_root
);
510 smartlist_free(cached_resolve_pqueue
);
511 cached_resolve_pqueue
= NULL
;
512 tor_free(resolv_conf_fname
);
515 /** Remove every cached_resolve whose <b>expire</b> time is before or
516 * equal to <b>now</b> from the cache. */
518 purge_expired_resolves(time_t now
)
520 cached_resolve_t
*resolve
, *removed
;
521 pending_connection_t
*pend
;
522 edge_connection_t
*pendconn
;
525 if (!cached_resolve_pqueue
)
528 while (smartlist_len(cached_resolve_pqueue
)) {
529 resolve
= smartlist_get(cached_resolve_pqueue
, 0);
530 if (resolve
->expire
> now
)
532 smartlist_pqueue_pop(cached_resolve_pqueue
,
533 compare_cached_resolves_by_expiry_
,
534 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
));
536 if (resolve
->state
== CACHE_STATE_PENDING
) {
538 "Expiring a dns resolve %s that's still pending. Forgot to "
539 "cull it? DNS resolve didn't tell us about the timeout?",
540 escaped_safe_str(resolve
->address
));
541 } else if (resolve
->state
== CACHE_STATE_CACHED
) {
543 "Forgetting old cached resolve (address %s, expires %lu)",
544 escaped_safe_str(resolve
->address
),
545 (unsigned long)resolve
->expire
);
546 tor_assert(!resolve
->pending_connections
);
548 tor_assert(resolve
->state
== CACHE_STATE_DONE
);
549 tor_assert(!resolve
->pending_connections
);
552 if (resolve
->pending_connections
) {
554 "Closing pending connections on timed-out DNS resolve!");
555 while (resolve
->pending_connections
) {
556 pend
= resolve
->pending_connections
;
557 resolve
->pending_connections
= pend
->next
;
558 /* Connections should only be pending if they have no socket. */
559 tor_assert(!SOCKET_OK(pend
->conn
->base_
.s
));
560 pendconn
= pend
->conn
;
561 if (!pendconn
->base_
.marked_for_close
) {
562 connection_edge_end(pendconn
, END_STREAM_REASON_TIMEOUT
);
563 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
564 connection_free(TO_CONN(pendconn
));
570 if (resolve
->state
== CACHE_STATE_CACHED
||
571 resolve
->state
== CACHE_STATE_PENDING
) {
572 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
573 if (removed
!= resolve
) {
574 log_err(LD_BUG
, "The expired resolve we purged didn't match any in"
575 " the cache. Tried to purge %s (%p); instead got %s (%p).",
576 resolve
->address
, (void*)resolve
,
577 removed
? removed
->address
: "NULL", (void*)removed
);
579 tor_assert(removed
== resolve
);
581 /* This should be in state DONE. Make sure it's not in the cache. */
582 cached_resolve_t
*tmp
= HT_FIND(cache_map
, &cache_root
, resolve
);
583 tor_assert(tmp
!= resolve
);
585 if (resolve
->res_status_hostname
== RES_STATUS_DONE_OK
)
586 tor_free(resolve
->result_ptr
.hostname
);
587 resolve
->magic
= 0xF0BBF0BB;
594 /* argument for send_resolved_cell only, meaning "let the answer type be ipv4
595 * or ipv6 depending on the connection's address". */
596 #define RESOLVED_TYPE_AUTO 0xff
598 /** Send a response to the RESOLVE request of a connection.
599 * <b>answer_type</b> must be one of
600 * RESOLVED_TYPE_(AUTO|ERROR|ERROR_TRANSIENT|).
602 * If <b>circ</b> is provided, and we have a cached answer, send the
603 * answer back along circ; otherwise, send the answer back along
604 * <b>conn</b>'s attached circuit.
607 send_resolved_cell(edge_connection_t
*conn
, uint8_t answer_type
,
608 const cached_resolve_t
*resolved
)
610 char buf
[RELAY_PAYLOAD_SIZE
], *cp
= buf
;
614 buf
[0] = answer_type
;
615 ttl
= dns_clip_ttl(conn
->address_ttl
);
619 case RESOLVED_TYPE_AUTO
:
620 if (resolved
&& resolved
->res_status_ipv4
== RES_STATUS_DONE_OK
) {
621 cp
[0] = RESOLVED_TYPE_IPV4
;
623 set_uint32(cp
+2, htonl(resolved
->result_ipv4
.addr_ipv4
));
624 set_uint32(cp
+6, htonl(ttl
));
627 if (resolved
&& resolved
->res_status_ipv6
== RES_STATUS_DONE_OK
) {
628 const uint8_t *bytes
= resolved
->result_ipv6
.addr_ipv6
.s6_addr
;
629 cp
[0] = RESOLVED_TYPE_IPV6
;
631 memcpy(cp
+2, bytes
, 16);
632 set_uint32(cp
+18, htonl(ttl
));
639 answer_type
= RESOLVED_TYPE_ERROR
;
642 case RESOLVED_TYPE_ERROR_TRANSIENT
:
643 case RESOLVED_TYPE_ERROR
:
645 const char *errmsg
= "Error resolving hostname";
646 size_t msglen
= strlen(errmsg
);
648 buf
[0] = answer_type
;
650 strlcpy(buf
+2, errmsg
, sizeof(buf
)-2);
651 set_uint32(buf
+2+msglen
, htonl(ttl
));
659 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
661 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
664 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
665 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
666 * The answer type will be RESOLVED_HOSTNAME.
668 * If <b>circ</b> is provided, and we have a cached answer, send the
669 * answer back along circ; otherwise, send the answer back along
670 * <b>conn</b>'s attached circuit.
673 send_resolved_hostname_cell(edge_connection_t
*conn
, const char *hostname
)
675 char buf
[RELAY_PAYLOAD_SIZE
];
678 size_t namelen
= strlen(hostname
);
679 tor_assert(hostname
);
681 tor_assert(namelen
< 256);
682 ttl
= dns_clip_ttl(conn
->address_ttl
);
684 buf
[0] = RESOLVED_TYPE_HOSTNAME
;
685 buf
[1] = (uint8_t)namelen
;
686 memcpy(buf
+2, hostname
, namelen
);
687 set_uint32(buf
+2+namelen
, htonl(ttl
));
688 buflen
= 2+namelen
+4;
690 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
691 connection_edge_send_command(conn
, RELAY_COMMAND_RESOLVED
, buf
, buflen
);
692 // log_notice(LD_EXIT, "Sent");
695 /** See if we have a cache entry for <b>exitconn</b>-\>address. If so,
696 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
697 * If resolve failed, free exitconn and return -1.
699 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
700 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
701 * need to send back an END cell, since connection_exit_begin_conn will
704 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
707 * Else, if seen before and pending, add conn to the pending list,
710 * Else, if not seen before, add conn to pending list, hand to
711 * dns farm, and return 0.
713 * Exitconn's on_circuit field must be set, but exitconn should not
714 * yet be linked onto the n_streams/resolving_streams list of that circuit.
715 * On success, link the connection to n_streams if it's an exit connection.
716 * On "pending", link the connection to resolving streams. Otherwise,
717 * clear its on_circuit field.
720 dns_resolve(edge_connection_t
*exitconn
)
722 or_circuit_t
*oncirc
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
724 int made_connection_pending
= 0;
725 char *hostname
= NULL
;
726 cached_resolve_t
*resolve
= NULL
;
727 is_resolve
= exitconn
->base_
.purpose
== EXIT_PURPOSE_RESOLVE
;
729 r
= dns_resolve_impl(exitconn
, is_resolve
, oncirc
, &hostname
,
730 &made_connection_pending
, &resolve
);
734 /* We got an answer without a lookup -- either the answer was
735 * cached, or it was obvious (like an IP address). */
737 /* Send the answer back right now, and detach. */
739 send_resolved_hostname_cell(exitconn
, hostname
);
741 send_resolved_cell(exitconn
, RESOLVED_TYPE_AUTO
, resolve
);
742 exitconn
->on_circuit
= NULL
;
744 /* Add to the n_streams list; the calling function will send back a
746 exitconn
->next_stream
= oncirc
->n_streams
;
747 oncirc
->n_streams
= exitconn
;
751 /* The request is pending: add the connection into the linked list of
752 * resolving_streams on this circuit. */
753 exitconn
->base_
.state
= EXIT_CONN_STATE_RESOLVING
;
754 exitconn
->next_stream
= oncirc
->resolving_streams
;
755 oncirc
->resolving_streams
= exitconn
;
759 /* The request failed before it could start: cancel this connection,
760 * and stop everybody waiting for the same connection. */
762 send_resolved_cell(exitconn
,
763 (r
== -1) ? RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
,
767 exitconn
->on_circuit
= NULL
;
769 dns_cancel_pending_resolve(exitconn
->base_
.address
);
771 if (!made_connection_pending
&& !exitconn
->base_
.marked_for_close
) {
772 /* If we made the connection pending, then we freed it already in
773 * dns_cancel_pending_resolve(). If we marked it for close, it'll
774 * get freed from the main loop. Otherwise, can free it now. */
775 connection_free(TO_CONN(exitconn
));
786 /** Helper function for dns_resolve: same functionality, but does not handle:
787 * - marking connections on error and clearing their on_circuit
788 * - linking connections to n_streams/resolving_streams,
789 * - sending resolved cells if we have an answer/error right away,
791 * Return -2 on a transient error. If it's a reverse resolve and it's
792 * successful, sets *<b>hostname_out</b> to a newly allocated string
793 * holding the cached reverse DNS value.
795 * Set *<b>made_connection_pending_out</b> to true if we have placed
796 * <b>exitconn</b> on the list of pending connections for some resolve; set it
797 * to false otherwise.
799 * Set *<b>resolve_out</b> to a cached resolve, if we found one.
802 dns_resolve_impl(edge_connection_t
*exitconn
, int is_resolve
,
803 or_circuit_t
*oncirc
, char **hostname_out
,
804 int *made_connection_pending_out
,
805 cached_resolve_t
**resolve_out
)
807 cached_resolve_t
*resolve
;
808 cached_resolve_t search
;
809 pending_connection_t
*pending_connection
;
812 time_t now
= time(NULL
);
814 assert_connection_ok(TO_CONN(exitconn
), 0);
815 tor_assert(!SOCKET_OK(exitconn
->base_
.s
));
818 *made_connection_pending_out
= 0;
820 /* first check if exitconn->base_.address is an IP. If so, we already
821 * know the answer. */
822 if (tor_addr_parse(&addr
, exitconn
->base_
.address
) >= 0) {
823 if (tor_addr_family(&addr
) == AF_INET
||
824 tor_addr_family(&addr
) == AF_INET6
) {
825 tor_addr_copy(&exitconn
->base_
.addr
, &addr
);
826 exitconn
->address_ttl
= DEFAULT_DNS_TTL
;
829 /* XXXX unspec? Bogus? */
834 /* If we're a non-exit, don't even do DNS lookups. */
835 if (router_my_exit_policy_is_reject_star())
838 if (address_is_invalid_destination(exitconn
->base_
.address
, 0)) {
839 tor_log(LOG_PROTOCOL_WARN
, LD_EXIT
,
840 "Rejecting invalid destination address %s",
841 escaped_safe_str(exitconn
->base_
.address
));
845 /* then take this opportunity to see if there are any expired
846 * resolves in the hash table. */
847 purge_expired_resolves(now
);
849 /* lower-case exitconn->base_.address, so it's in canonical form */
850 tor_strlower(exitconn
->base_
.address
);
852 /* Check whether this is a reverse lookup. If it's malformed, or it's a
853 * .in-addr.arpa address but this isn't a resolve request, kill the
856 if ((r
= tor_addr_parse_PTR_name(&addr
, exitconn
->base_
.address
,
857 AF_UNSPEC
, 0)) != 0) {
860 if (tor_addr_is_internal(&addr
, 0)) /* internal address? */
864 if (!is_reverse
|| !is_resolve
) {
866 log_info(LD_EXIT
, "Bad .in-addr.arpa address \"%s\"; sending error.",
867 escaped_safe_str(exitconn
->base_
.address
));
868 else if (!is_resolve
)
870 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
872 escaped_safe_str(exitconn
->base_
.address
));
876 //log_notice(LD_EXIT, "Looks like an address %s",
877 //exitconn->base_.address);
879 exitconn
->is_reverse_dns_lookup
= is_reverse
;
881 /* now check the hash table to see if 'address' is already there. */
882 strlcpy(search
.address
, exitconn
->base_
.address
, sizeof(search
.address
));
883 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
884 if (resolve
&& resolve
->expire
> now
) { /* already there */
885 switch (resolve
->state
) {
886 case CACHE_STATE_PENDING
:
887 /* add us to the pending list */
888 pending_connection
= tor_malloc_zero(
889 sizeof(pending_connection_t
));
890 pending_connection
->conn
= exitconn
;
891 pending_connection
->next
= resolve
->pending_connections
;
892 resolve
->pending_connections
= pending_connection
;
893 *made_connection_pending_out
= 1;
894 log_debug(LD_EXIT
,"Connection (fd "TOR_SOCKET_T_FORMAT
") waiting "
895 "for pending DNS resolve of %s", exitconn
->base_
.s
,
896 escaped_safe_str(exitconn
->base_
.address
));
898 case CACHE_STATE_CACHED
:
899 log_debug(LD_EXIT
,"Connection (fd "TOR_SOCKET_T_FORMAT
") found "
900 "cached answer for %s",
902 escaped_safe_str(resolve
->address
));
904 *resolve_out
= resolve
;
906 return set_exitconn_info_from_resolve(exitconn
, resolve
, hostname_out
);
907 case CACHE_STATE_DONE
:
908 log_err(LD_BUG
, "Found a 'DONE' dns resolve still in the cache.");
909 tor_fragile_assert();
913 tor_assert(!resolve
);
914 /* not there, need to add it */
915 resolve
= tor_malloc_zero(sizeof(cached_resolve_t
));
916 resolve
->magic
= CACHED_RESOLVE_MAGIC
;
917 resolve
->state
= CACHE_STATE_PENDING
;
918 resolve
->minheap_idx
= -1;
919 strlcpy(resolve
->address
, exitconn
->base_
.address
, sizeof(resolve
->address
));
921 /* add this connection to the pending list */
922 pending_connection
= tor_malloc_zero(sizeof(pending_connection_t
));
923 pending_connection
->conn
= exitconn
;
924 resolve
->pending_connections
= pending_connection
;
925 *made_connection_pending_out
= 1;
927 /* Add this resolve to the cache and priority queue. */
928 HT_INSERT(cache_map
, &cache_root
, resolve
);
929 set_expiry(resolve
, now
+ RESOLVE_MAX_TIMEOUT
);
931 log_debug(LD_EXIT
,"Launching %s.",
932 escaped_safe_str(exitconn
->base_
.address
));
935 return launch_resolve(resolve
);
938 /** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
939 * <b>resolve</b> whose DNS lookups have all succeeded or failed, update the
940 * appropriate fields (address_ttl and addr) of <b>exitconn</b>.
942 * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
943 * copy of the name resulting hostname.
945 * Return -2 on a transient error, -1 on a permenent error, and 1 on
946 * a successful lookup.
949 set_exitconn_info_from_resolve(edge_connection_t
*exitconn
,
950 const cached_resolve_t
*resolve
,
953 int ipv4_ok
, ipv6_ok
, answer_with_ipv4
, r
;
954 uint32_t begincell_flags
;
955 const int is_resolve
= exitconn
->base_
.purpose
== EXIT_PURPOSE_RESOLVE
;
956 tor_assert(exitconn
);
959 if (exitconn
->is_reverse_dns_lookup
) {
960 exitconn
->address_ttl
= resolve
->ttl_hostname
;
961 if (resolve
->res_status_hostname
== RES_STATUS_DONE_OK
) {
962 *hostname_out
= tor_strdup(resolve
->result_ptr
.hostname
);
969 /* If we're here then the connection wants one or either of ipv4, ipv6, and
970 * we can give it one or both. */
972 begincell_flags
= BEGIN_FLAG_IPV6_OK
;
974 begincell_flags
= exitconn
->begincell_flags
;
977 ipv4_ok
= (resolve
->res_status_ipv4
== RES_STATUS_DONE_OK
) &&
978 ! (begincell_flags
& BEGIN_FLAG_IPV4_NOT_OK
);
979 ipv6_ok
= (resolve
->res_status_ipv6
== RES_STATUS_DONE_OK
) &&
980 (begincell_flags
& BEGIN_FLAG_IPV6_OK
) &&
981 get_options()->IPv6Exit
;
983 /* Now decide which one to actually give. */
984 if (ipv4_ok
&& ipv6_ok
&& is_resolve
) {
985 answer_with_ipv4
= 1;
986 } else if (ipv4_ok
&& ipv6_ok
) {
987 /* If we have both, see if our exit policy has an opinion. */
988 const uint16_t port
= exitconn
->base_
.port
;
989 int ipv4_allowed
, ipv6_allowed
;
991 tor_addr_from_ipv4h(&a4
, resolve
->result_ipv4
.addr_ipv4
);
992 tor_addr_from_in6(&a6
, &resolve
->result_ipv6
.addr_ipv6
);
993 ipv4_allowed
= !router_compare_to_my_exit_policy(&a4
, port
);
994 ipv6_allowed
= !router_compare_to_my_exit_policy(&a6
, port
);
995 if (ipv4_allowed
&& !ipv6_allowed
) {
996 answer_with_ipv4
= 1;
997 } else if (ipv6_allowed
&& !ipv4_allowed
) {
998 answer_with_ipv4
= 0;
1000 /* Our exit policy would permit both. Answer with whichever the user
1002 answer_with_ipv4
= !(begincell_flags
&
1003 BEGIN_FLAG_IPV6_PREFERRED
);
1006 /* Otherwise if one is okay, send it back. */
1008 answer_with_ipv4
= 1;
1009 } else if (ipv6_ok
) {
1010 answer_with_ipv4
= 0;
1012 /* Neither one was okay. Choose based on user preference. */
1013 answer_with_ipv4
= !(begincell_flags
&
1014 BEGIN_FLAG_IPV6_PREFERRED
);
1018 /* Finally, we write the answer back. */
1020 if (answer_with_ipv4
) {
1021 if (resolve
->res_status_ipv4
== RES_STATUS_DONE_OK
) {
1022 tor_addr_from_ipv4h(&exitconn
->base_
.addr
,
1023 resolve
->result_ipv4
.addr_ipv4
);
1025 r
= evdns_err_is_transient(resolve
->result_ipv4
.err_ipv4
) ? -2 : -1;
1028 exitconn
->address_ttl
= resolve
->ttl_ipv4
;
1030 if (resolve
->res_status_ipv6
== RES_STATUS_DONE_OK
) {
1031 tor_addr_from_in6(&exitconn
->base_
.addr
,
1032 &resolve
->result_ipv6
.addr_ipv6
);
1034 r
= evdns_err_is_transient(resolve
->result_ipv6
.err_ipv6
) ? -2 : -1;
1037 exitconn
->address_ttl
= resolve
->ttl_ipv6
;
1043 /** Log an error and abort if conn is waiting for a DNS resolve.
1046 assert_connection_edge_not_dns_pending(edge_connection_t
*conn
)
1048 pending_connection_t
*pend
;
1049 cached_resolve_t search
;
1052 cached_resolve_t
*resolve
;
1053 strlcpy(search
.address
, conn
->base_
.address
, sizeof(search
.address
));
1054 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
1057 for (pend
= resolve
->pending_connections
; pend
; pend
= pend
->next
) {
1058 tor_assert(pend
->conn
!= conn
);
1061 cached_resolve_t
**resolve
;
1062 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1063 for (pend
= (*resolve
)->pending_connections
; pend
; pend
= pend
->next
) {
1064 tor_assert(pend
->conn
!= conn
);
1070 /** Log an error and abort if any connection waiting for a DNS resolve is
1073 assert_all_pending_dns_resolves_ok(void)
1075 pending_connection_t
*pend
;
1076 cached_resolve_t
**resolve
;
1078 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
1079 for (pend
= (*resolve
)->pending_connections
;
1081 pend
= pend
->next
) {
1082 assert_connection_ok(TO_CONN(pend
->conn
), 0);
1083 tor_assert(!SOCKET_OK(pend
->conn
->base_
.s
));
1084 tor_assert(!connection_in_array(TO_CONN(pend
->conn
)));
1089 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
1092 connection_dns_remove(edge_connection_t
*conn
)
1094 pending_connection_t
*pend
, *victim
;
1095 cached_resolve_t search
;
1096 cached_resolve_t
*resolve
;
1098 tor_assert(conn
->base_
.type
== CONN_TYPE_EXIT
);
1099 tor_assert(conn
->base_
.state
== EXIT_CONN_STATE_RESOLVING
);
1101 strlcpy(search
.address
, conn
->base_
.address
, sizeof(search
.address
));
1103 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
1105 log_notice(LD_BUG
, "Address %s is not pending. Dropping.",
1106 escaped_safe_str(conn
->base_
.address
));
1110 tor_assert(resolve
->pending_connections
);
1111 assert_connection_ok(TO_CONN(conn
),0);
1113 pend
= resolve
->pending_connections
;
1115 if (pend
->conn
== conn
) {
1116 resolve
->pending_connections
= pend
->next
;
1118 log_debug(LD_EXIT
, "First connection (fd "TOR_SOCKET_T_FORMAT
") no "
1119 "longer waiting for resolve of %s",
1121 escaped_safe_str(conn
->base_
.address
));
1124 for ( ; pend
->next
; pend
= pend
->next
) {
1125 if (pend
->next
->conn
== conn
) {
1126 victim
= pend
->next
;
1127 pend
->next
= victim
->next
;
1130 "Connection (fd "TOR_SOCKET_T_FORMAT
") no longer waiting "
1131 "for resolve of %s",
1132 conn
->base_
.s
, escaped_safe_str(conn
->base_
.address
));
1133 return; /* more are pending */
1136 tor_assert(0); /* not reachable unless onlyconn not in pending list */
1140 /** Mark all connections waiting for <b>address</b> for close. Then cancel
1141 * the resolve for <b>address</b> itself, and remove any cached results for
1142 * <b>address</b> from the cache.
1145 dns_cancel_pending_resolve(const char *address
)
1147 pending_connection_t
*pend
;
1148 cached_resolve_t search
;
1149 cached_resolve_t
*resolve
, *tmp
;
1150 edge_connection_t
*pendconn
;
1153 strlcpy(search
.address
, address
, sizeof(search
.address
));
1155 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
1159 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1160 /* We can get into this state if we never actually created the pending
1161 * resolve, due to finding an earlier cached error or something. Just
1163 if (resolve
->pending_connections
) {
1165 "Address %s is not pending but has pending connections!",
1166 escaped_safe_str(address
));
1167 tor_fragile_assert();
1172 if (!resolve
->pending_connections
) {
1174 "Address %s is pending but has no pending connections!",
1175 escaped_safe_str(address
));
1176 tor_fragile_assert();
1179 tor_assert(resolve
->pending_connections
);
1181 /* mark all pending connections to fail */
1183 "Failing all connections waiting on DNS resolve of %s",
1184 escaped_safe_str(address
));
1185 while (resolve
->pending_connections
) {
1186 pend
= resolve
->pending_connections
;
1187 pend
->conn
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1188 pendconn
= pend
->conn
;
1189 assert_connection_ok(TO_CONN(pendconn
), 0);
1190 tor_assert(!SOCKET_OK(pendconn
->base_
.s
));
1191 if (!pendconn
->base_
.marked_for_close
) {
1192 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
1194 circ
= circuit_get_by_edge_conn(pendconn
);
1196 circuit_detach_stream(circ
, pendconn
);
1197 if (!pendconn
->base_
.marked_for_close
)
1198 connection_free(TO_CONN(pendconn
));
1199 resolve
->pending_connections
= pend
->next
;
1203 tmp
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
1204 if (tmp
!= resolve
) {
1205 log_err(LD_BUG
, "The cancelled resolve we purged didn't match any in"
1206 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1207 resolve
->address
, (void*)resolve
,
1208 tmp
? tmp
->address
: "NULL", (void*)tmp
);
1210 tor_assert(tmp
== resolve
);
1212 resolve
->state
= CACHE_STATE_DONE
;
1215 /** Return true iff <b>address</b> is one of the addresses we use to verify
1216 * that well-known sites aren't being hijacked by our DNS servers. */
1218 is_test_address(const char *address
)
1220 const or_options_t
*options
= get_options();
1221 return options
->ServerDNSTestAddresses
&&
1222 smartlist_contains_string_case(options
->ServerDNSTestAddresses
, address
);
1225 /** Called on the OR side when the eventdns library tells us the outcome of a
1226 * single DNS resolve: remember the answer, and tell all pending connections
1227 * about the result of the lookup if the lookup is now done. (<b>address</b>
1228 * is a NUL-terminated string containing the address to look up;
1229 * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
1230 * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
1231 * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
1232 * <b>ttl</b> is the time-to-live of this answer, in seconds.)
1235 dns_found_answer(const char *address
, uint8_t query_type
,
1237 const tor_addr_t
*addr
,
1238 const char *hostname
, uint32_t ttl
)
1240 cached_resolve_t search
;
1241 cached_resolve_t
*resolve
;
1245 strlcpy(search
.address
, address
, sizeof(search
.address
));
1247 resolve
= HT_FIND(cache_map
, &cache_root
, &search
);
1249 int is_test_addr
= is_test_address(address
);
1251 log_info(LD_EXIT
,"Resolved unasked address %s; ignoring.",
1252 escaped_safe_str(address
));
1255 assert_resolve_ok(resolve
);
1257 if (resolve
->state
!= CACHE_STATE_PENDING
) {
1258 /* XXXX Maybe update addr? or check addr for consistency? Or let
1259 * VALID replace FAILED? */
1260 int is_test_addr
= is_test_address(address
);
1263 "Resolved %s which was already resolved; ignoring",
1264 escaped_safe_str(address
));
1265 tor_assert(resolve
->pending_connections
== NULL
);
1269 cached_resolve_add_answer(resolve
, query_type
, dns_answer
,
1270 addr
, hostname
, ttl
);
1272 if (cached_resolve_have_all_answers(resolve
)) {
1273 inform_pending_connections(resolve
);
1275 make_pending_resolve_cached(resolve
);
1279 /** Given a pending cached_resolve_t that we just finished resolving,
1280 * inform every connection that was waiting for the outcome of that
1283 inform_pending_connections(cached_resolve_t
*resolve
)
1285 pending_connection_t
*pend
;
1286 edge_connection_t
*pendconn
;
1289 while (resolve
->pending_connections
) {
1290 char *hostname
= NULL
;
1291 pend
= resolve
->pending_connections
;
1292 pendconn
= pend
->conn
; /* don't pass complex things to the
1293 connection_mark_for_close macro */
1294 assert_connection_ok(TO_CONN(pendconn
),time(NULL
));
1296 if (pendconn
->base_
.marked_for_close
) {
1297 /* prevent double-remove. */
1298 pendconn
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1299 resolve
->pending_connections
= pend
->next
;
1304 r
= set_exitconn_info_from_resolve(pendconn
,
1309 /* prevent double-remove. */
1310 pendconn
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1311 if (pendconn
->base_
.purpose
== EXIT_PURPOSE_CONNECT
) {
1312 connection_edge_end(pendconn
, END_STREAM_REASON_RESOLVEFAILED
);
1313 /* This detach must happen after we send the end cell. */
1314 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1316 send_resolved_cell(pendconn
, r
== -1 ?
1317 RESOLVED_TYPE_ERROR
: RESOLVED_TYPE_ERROR_TRANSIENT
,
1319 /* This detach must happen after we send the resolved cell. */
1320 circuit_detach_stream(circuit_get_by_edge_conn(pendconn
), pendconn
);
1322 connection_free(TO_CONN(pendconn
));
1325 if (pendconn
->base_
.purpose
== EXIT_PURPOSE_CONNECT
) {
1326 /* prevent double-remove. */
1327 pend
->conn
->base_
.state
= EXIT_CONN_STATE_CONNECTING
;
1329 circ
= circuit_get_by_edge_conn(pend
->conn
);
1331 tor_assert(!CIRCUIT_IS_ORIGIN(circ
));
1332 /* unlink pend->conn from resolving_streams, */
1333 circuit_detach_stream(circ
, pend
->conn
);
1334 /* and link it to n_streams */
1335 pend
->conn
->next_stream
= TO_OR_CIRCUIT(circ
)->n_streams
;
1336 pend
->conn
->on_circuit
= circ
;
1337 TO_OR_CIRCUIT(circ
)->n_streams
= pend
->conn
;
1339 connection_exit_connect(pend
->conn
);
1341 /* prevent double-remove. This isn't really an accurate state,
1342 * but it does the right thing. */
1343 pendconn
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
1344 if (pendconn
->is_reverse_dns_lookup
)
1345 send_resolved_hostname_cell(pendconn
, hostname
);
1347 send_resolved_cell(pendconn
, RESOLVED_TYPE_AUTO
, resolve
);
1348 circ
= circuit_get_by_edge_conn(pendconn
);
1350 circuit_detach_stream(circ
, pendconn
);
1351 connection_free(TO_CONN(pendconn
));
1354 resolve
->pending_connections
= pend
->next
;
1360 /** Remove a pending cached_resolve_t from the hashtable, and add a
1361 * corresponding cached cached_resolve_t.
1363 * This function is only necessary because of the perversity of our
1364 * cache timeout code; see inline comment for ideas on eliminating it.
1367 make_pending_resolve_cached(cached_resolve_t
*resolve
)
1369 cached_resolve_t
*removed
;
1371 resolve
->state
= CACHE_STATE_DONE
;
1372 removed
= HT_REMOVE(cache_map
, &cache_root
, resolve
);
1373 if (removed
!= resolve
) {
1374 log_err(LD_BUG
, "The pending resolve we found wasn't removable from"
1375 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1376 resolve
->address
, (void*)resolve
,
1377 removed
? removed
->address
: "NULL", (void*)removed
);
1379 assert_resolve_ok(resolve
);
1381 /* The resolve will eventually just hit the time-out in the expiry queue and
1382 * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
1383 * way. XXXXX we could do better!*/
1386 cached_resolve_t
*new_resolve
= tor_memdup(resolve
,
1387 sizeof(cached_resolve_t
));
1388 uint32_t ttl
= UINT32_MAX
;
1389 new_resolve
->expire
= 0; /* So that set_expiry won't croak. */
1390 if (resolve
->res_status_hostname
== RES_STATUS_DONE_OK
)
1391 new_resolve
->result_ptr
.hostname
=
1392 tor_strdup(resolve
->result_ptr
.hostname
);
1394 new_resolve
->state
= CACHE_STATE_CACHED
;
1396 assert_resolve_ok(new_resolve
);
1397 HT_INSERT(cache_map
, &cache_root
, new_resolve
);
1399 if ((resolve
->res_status_ipv4
== RES_STATUS_DONE_OK
||
1400 resolve
->res_status_ipv4
== RES_STATUS_DONE_ERR
) &&
1401 resolve
->ttl_ipv4
< ttl
)
1402 ttl
= resolve
->ttl_ipv4
;
1404 if ((resolve
->res_status_ipv6
== RES_STATUS_DONE_OK
||
1405 resolve
->res_status_ipv6
== RES_STATUS_DONE_ERR
) &&
1406 resolve
->ttl_ipv6
< ttl
)
1407 ttl
= resolve
->ttl_ipv6
;
1409 if ((resolve
->res_status_hostname
== RES_STATUS_DONE_OK
||
1410 resolve
->res_status_hostname
== RES_STATUS_DONE_ERR
) &&
1411 resolve
->ttl_hostname
< ttl
)
1412 ttl
= resolve
->ttl_hostname
;
1414 set_expiry(new_resolve
, time(NULL
) + dns_get_expiry_ttl(ttl
));
1420 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1421 * a transient failure. */
1423 evdns_err_is_transient(int err
)
1427 case DNS_ERR_SERVERFAILED
:
1428 case DNS_ERR_TRUNCATED
:
1429 case DNS_ERR_TIMEOUT
:
1436 /** Configure eventdns nameservers if force is true, or if the configuration
1437 * has changed since the last time we called this function, or if we failed on
1438 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1439 * options->ServerDNSResolvConfFile; on Windows, this reads from
1440 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1443 configure_nameservers(int force
)
1445 const or_options_t
*options
;
1446 const char *conf_fname
;
1449 options
= get_options();
1450 conf_fname
= options
->ServerDNSResolvConfFile
;
1453 conf_fname
= "/etc/resolv.conf";
1455 flags
= DNS_OPTIONS_ALL
;
1457 if (!the_evdns_base
) {
1458 if (!(the_evdns_base
= evdns_base_new(tor_libevent_get_base(), 0))) {
1459 log_err(LD_BUG
, "Couldn't create an evdns_base");
1464 #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
1465 if (! tor_addr_is_null(&options
->OutboundBindAddressIPv4_
)) {
1467 struct sockaddr_storage ss
;
1468 socklen
= tor_addr_to_sockaddr(&options
->OutboundBindAddressIPv4_
, 0,
1469 (struct sockaddr
*)&ss
, sizeof(ss
));
1471 log_warn(LD_BUG
, "Couldn't convert outbound bind address to sockaddr."
1474 evdns_base_set_default_outgoing_bind_address(the_evdns_base
,
1475 (struct sockaddr
*)&ss
,
1481 evdns_set_log_fn(evdns_log_cb
);
1483 log_debug(LD_FS
, "stat()ing %s", conf_fname
);
1484 if (stat(sandbox_intern_string(conf_fname
), &st
)) {
1485 log_warn(LD_EXIT
, "Unable to stat resolver configuration in '%s': %s",
1486 conf_fname
, strerror(errno
));
1489 if (!force
&& resolv_conf_fname
&& !strcmp(conf_fname
,resolv_conf_fname
)
1490 && st
.st_mtime
== resolv_conf_mtime
) {
1491 log_info(LD_EXIT
, "No change to '%s'", conf_fname
);
1494 if (nameservers_configured
) {
1495 evdns_base_search_clear(the_evdns_base
);
1496 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
1498 #if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
1499 if (flags
& DNS_OPTION_HOSTSFILE
) {
1500 flags
^= DNS_OPTION_HOSTSFILE
;
1501 log_debug(LD_FS
, "Loading /etc/hosts");
1502 evdns_base_load_hosts(the_evdns_base
,
1503 sandbox_intern_string("/etc/hosts"));
1506 log_info(LD_EXIT
, "Parsing resolver configuration in '%s'", conf_fname
);
1507 if ((r
= evdns_base_resolv_conf_parse(the_evdns_base
, flags
,
1508 sandbox_intern_string(conf_fname
)))) {
1509 log_warn(LD_EXIT
, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1510 conf_fname
, conf_fname
, r
);
1513 if (evdns_base_count_nameservers(the_evdns_base
) == 0) {
1514 log_warn(LD_EXIT
, "Unable to find any nameservers in '%s'.", conf_fname
);
1517 tor_free(resolv_conf_fname
);
1518 resolv_conf_fname
= tor_strdup(conf_fname
);
1519 resolv_conf_mtime
= st
.st_mtime
;
1520 if (nameservers_configured
)
1521 evdns_base_resume(the_evdns_base
);
1525 if (nameservers_configured
) {
1526 evdns_base_search_clear(the_evdns_base
);
1527 evdns_base_clear_nameservers_and_suspend(the_evdns_base
);
1529 if (evdns_base_config_windows_nameservers(the_evdns_base
)) {
1530 log_warn(LD_EXIT
,"Could not config nameservers.");
1533 if (evdns_base_count_nameservers(the_evdns_base
) == 0) {
1534 log_warn(LD_EXIT
, "Unable to find any platform nameservers in "
1535 "your Windows configuration.");
1538 if (nameservers_configured
)
1539 evdns_base_resume(the_evdns_base
);
1540 tor_free(resolv_conf_fname
);
1541 resolv_conf_mtime
= 0;
1545 #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
1547 if (evdns_base_count_nameservers(the_evdns_base
) == 1) {
1548 SET("max-timeouts:", "16");
1549 SET("timeout:", "10");
1551 SET("max-timeouts:", "3");
1552 SET("timeout:", "5");
1555 if (options
->ServerDNSRandomizeCase
)
1556 SET("randomize-case:", "1");
1558 SET("randomize-case:", "0");
1562 dns_servers_relaunch_checks();
1564 nameservers_configured
= 1;
1565 if (nameserver_config_failed
) {
1566 nameserver_config_failed
= 0;
1567 /* XXX the three calls to republish the descriptor might be producing
1568 * descriptors that are only cosmetically different, especially on
1569 * non-exit relays! -RD */
1570 mark_my_descriptor_dirty("dns resolvers back");
1574 nameservers_configured
= 0;
1575 if (! nameserver_config_failed
) {
1576 nameserver_config_failed
= 1;
1577 mark_my_descriptor_dirty("dns resolvers failed");
1582 /** For eventdns: Called when we get an answer for a request we launched.
1583 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1586 evdns_callback(int result
, char type
, int count
, int ttl
, void *addresses
,
1590 uint8_t orig_query_type
= arg_
[0];
1591 char *string_address
= arg_
+ 1;
1593 const char *hostname
= NULL
;
1594 int was_wildcarded
= 0;
1596 tor_addr_make_unspec(&addr
);
1598 /* Keep track of whether IPv6 is working */
1599 if (type
== DNS_IPv6_AAAA
) {
1600 if (result
== DNS_ERR_TIMEOUT
) {
1604 if (n_ipv6_timeouts
> 10 &&
1605 n_ipv6_timeouts
> n_ipv6_requests_made
/ 2) {
1606 if (! dns_is_broken_for_ipv6
) {
1607 log_notice(LD_EXIT
, "More than half of our IPv6 requests seem to "
1608 "have timed out. I'm going to assume I can't get AAAA "
1610 dns_is_broken_for_ipv6
= 1;
1615 if (result
== DNS_ERR_NONE
) {
1616 if (type
== DNS_IPv4_A
&& count
) {
1617 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1618 char *escaped_address
;
1619 uint32_t *addrs
= addresses
;
1620 tor_addr_from_ipv4n(&addr
, addrs
[0]);
1622 tor_addr_to_str(answer_buf
, &addr
, sizeof(answer_buf
), 0);
1623 escaped_address
= esc_for_log(string_address
);
1625 if (answer_is_wildcarded(answer_buf
)) {
1626 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1627 "address %s; treating as a failure.",
1628 safe_str(escaped_address
),
1629 escaped_safe_str(answer_buf
));
1631 tor_addr_make_unspec(&addr
);
1632 result
= DNS_ERR_NOTEXIST
;
1634 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1635 safe_str(escaped_address
),
1636 escaped_safe_str(answer_buf
));
1638 tor_free(escaped_address
);
1639 } else if (type
== DNS_IPv6_AAAA
&& count
) {
1640 char answer_buf
[TOR_ADDR_BUF_LEN
];
1641 char *escaped_address
;
1642 struct in6_addr
*addrs
= addresses
;
1643 tor_addr_from_in6(&addr
, &addrs
[0]);
1644 tor_inet_ntop(AF_INET6
, &addrs
[0], answer_buf
, sizeof(answer_buf
));
1645 escaped_address
= esc_for_log(string_address
);
1647 if (answer_is_wildcarded(answer_buf
)) {
1648 log_debug(LD_EXIT
, "eventdns said that %s resolves to ISP-hijacked "
1649 "address %s; treating as a failure.",
1650 safe_str(escaped_address
),
1651 escaped_safe_str(answer_buf
));
1653 tor_addr_make_unspec(&addr
);
1654 result
= DNS_ERR_NOTEXIST
;
1656 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1657 safe_str(escaped_address
),
1658 escaped_safe_str(answer_buf
));
1660 tor_free(escaped_address
);
1661 } else if (type
== DNS_PTR
&& count
) {
1662 char *escaped_address
;
1663 hostname
= ((char**)addresses
)[0];
1664 escaped_address
= esc_for_log(string_address
);
1665 log_debug(LD_EXIT
, "eventdns said that %s resolves to %s",
1666 safe_str(escaped_address
),
1667 escaped_safe_str(hostname
));
1668 tor_free(escaped_address
);
1670 log_warn(LD_EXIT
, "eventdns returned only non-IPv4 answers for %s.",
1671 escaped_safe_str(string_address
));
1673 log_warn(LD_BUG
, "eventdns returned no addresses or error for %s!",
1674 escaped_safe_str(string_address
));
1677 if (was_wildcarded
) {
1678 if (is_test_address(string_address
)) {
1679 /* Ick. We're getting redirected on known-good addresses. Our DNS
1680 * server must really hate us. */
1681 add_wildcarded_test_address(string_address
);
1685 if (orig_query_type
&& type
&& orig_query_type
!= type
) {
1686 log_warn(LD_BUG
, "Weird; orig_query_type == %d but type == %d",
1687 (int)orig_query_type
, (int)type
);
1689 if (result
!= DNS_ERR_SHUTDOWN
)
1690 dns_found_answer(string_address
, orig_query_type
,
1691 result
, &addr
, hostname
, ttl
);
1696 /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
1697 * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
1698 * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
1700 launch_one_resolve(const char *address
, uint8_t query_type
,
1701 const tor_addr_t
*ptr_address
)
1703 const int options
= get_options()->ServerDNSSearchDomains
? 0
1704 : DNS_QUERY_NO_SEARCH
;
1705 const size_t addr_len
= strlen(address
);
1706 struct evdns_request
*req
= 0;
1707 char *addr
= tor_malloc(addr_len
+ 2);
1708 addr
[0] = (char) query_type
;
1709 memcpy(addr
+1, address
, addr_len
+ 1);
1711 switch (query_type
) {
1713 req
= evdns_base_resolve_ipv4(the_evdns_base
,
1714 address
, options
, evdns_callback
, addr
);
1717 req
= evdns_base_resolve_ipv6(the_evdns_base
,
1718 address
, options
, evdns_callback
, addr
);
1719 ++n_ipv6_requests_made
;
1722 if (tor_addr_family(ptr_address
) == AF_INET
)
1723 req
= evdns_base_resolve_reverse(the_evdns_base
,
1724 tor_addr_to_in(ptr_address
),
1725 DNS_QUERY_NO_SEARCH
,
1726 evdns_callback
, addr
);
1727 else if (tor_addr_family(ptr_address
) == AF_INET6
)
1728 req
= evdns_base_resolve_reverse_ipv6(the_evdns_base
,
1729 tor_addr_to_in6(ptr_address
),
1730 DNS_QUERY_NO_SEARCH
,
1731 evdns_callback
, addr
);
1733 log_warn(LD_BUG
, "Called with PTR query and unexpected address family");
1736 log_warn(LD_BUG
, "Called with unexpectd query type %d", (int)query_type
);
1748 /** For eventdns: start resolving as necessary to find the target for
1749 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1750 * 0 on "resolve launched." */
1752 launch_resolve(cached_resolve_t
*resolve
)
1757 if (get_options()->DisableNetwork
)
1760 /* What? Nameservers not configured? Sounds like a bug. */
1761 if (!nameservers_configured
) {
1762 log_warn(LD_EXIT
, "(Harmless.) Nameservers not configured, but resolve "
1763 "launched. Configuring.");
1764 if (configure_nameservers(1) < 0) {
1769 r
= tor_addr_parse_PTR_name(
1770 &a
, resolve
->address
, AF_UNSPEC
, 0);
1772 tor_assert(the_evdns_base
);
1774 log_info(LD_EXIT
, "Launching eventdns request for %s",
1775 escaped_safe_str(resolve
->address
));
1776 resolve
->res_status_ipv4
= RES_STATUS_INFLIGHT
;
1777 if (get_options()->IPv6Exit
)
1778 resolve
->res_status_ipv6
= RES_STATUS_INFLIGHT
;
1780 if (launch_one_resolve(resolve
->address
, DNS_IPv4_A
, NULL
) < 0) {
1781 resolve
->res_status_ipv4
= 0;
1785 if (r
==0 && get_options()->IPv6Exit
) {
1786 /* We ask for an IPv6 address for *everything*. */
1787 if (launch_one_resolve(resolve
->address
, DNS_IPv6_AAAA
, NULL
) < 0) {
1788 resolve
->res_status_ipv6
= 0;
1792 } else if (r
== 1) {
1794 log_info(LD_EXIT
, "Launching eventdns reverse request for %s",
1795 escaped_safe_str(resolve
->address
));
1796 resolve
->res_status_hostname
= RES_STATUS_INFLIGHT
;
1797 if (launch_one_resolve(resolve
->address
, DNS_PTR
, &a
) < 0) {
1798 resolve
->res_status_hostname
= 0;
1801 } else if (r
== -1) {
1802 log_warn(LD_BUG
, "Somehow a malformed in-addr.arpa address reached here.");
1806 log_fn(LOG_PROTOCOL_WARN
, LD_EXIT
, "eventdns rejected address %s.",
1807 escaped_safe_str(resolve
->address
));
1812 /** How many requests for bogus addresses have we launched so far? */
1813 static int n_wildcard_requests
= 0;
1815 /** Map from dotted-quad IP address in response to an int holding how many
1816 * times we've seen it for a randomly generated (hopefully bogus) address. It
1817 * would be easier to use definitely-invalid addresses (as specified by
1818 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1819 static strmap_t
*dns_wildcard_response_count
= NULL
;
1821 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1822 * nameserver wants to return in response to requests for nonexistent domains.
1824 static smartlist_t
*dns_wildcard_list
= NULL
;
1825 /** True iff we've logged about a single address getting wildcarded.
1826 * Subsequent warnings will be less severe. */
1827 static int dns_wildcard_one_notice_given
= 0;
1828 /** True iff we've warned that our DNS server is wildcarding too many failures.
1830 static int dns_wildcard_notice_given
= 0;
1832 /** List of supposedly good addresses that are getting wildcarded to the
1833 * same addresses as nonexistent addresses. */
1834 static smartlist_t
*dns_wildcarded_test_address_list
= NULL
;
1835 /** True iff we've warned about a test address getting wildcarded */
1836 static int dns_wildcarded_test_address_notice_given
= 0;
1837 /** True iff all addresses seem to be getting wildcarded. */
1838 static int dns_is_completely_invalid
= 0;
1840 /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
1841 * to a request for a hopefully bogus address. */
1843 wildcard_increment_answer(const char *id
)
1846 if (!dns_wildcard_response_count
)
1847 dns_wildcard_response_count
= strmap_new();
1849 ip
= strmap_get(dns_wildcard_response_count
, id
); // may be null (0)
1851 ip
= tor_malloc_zero(sizeof(int));
1852 strmap_set(dns_wildcard_response_count
, id
, ip
);
1856 if (*ip
> 5 && n_wildcard_requests
> 10) {
1857 if (!dns_wildcard_list
) dns_wildcard_list
= smartlist_new();
1858 if (!smartlist_contains_string(dns_wildcard_list
, id
)) {
1859 tor_log(dns_wildcard_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1860 "Your DNS provider has given \"%s\" as an answer for %d different "
1861 "invalid addresses. Apparently they are hijacking DNS failures. "
1862 "I'll try to correct for this by treating future occurrences of "
1863 "\"%s\" as 'not found'.", id
, *ip
, id
);
1864 smartlist_add(dns_wildcard_list
, tor_strdup(id
));
1866 if (!dns_wildcard_notice_given
)
1867 control_event_server_status(LOG_NOTICE
, "DNS_HIJACKED");
1868 dns_wildcard_notice_given
= 1;
1872 /** Note that a single test address (one believed to be good) seems to be
1873 * getting redirected to the same IP as failures are. */
1875 add_wildcarded_test_address(const char *address
)
1877 int n
, n_test_addrs
;
1878 if (!dns_wildcarded_test_address_list
)
1879 dns_wildcarded_test_address_list
= smartlist_new();
1881 if (smartlist_contains_string_case(dns_wildcarded_test_address_list
,
1885 n_test_addrs
= get_options()->ServerDNSTestAddresses
?
1886 smartlist_len(get_options()->ServerDNSTestAddresses
) : 0;
1888 smartlist_add(dns_wildcarded_test_address_list
, tor_strdup(address
));
1889 n
= smartlist_len(dns_wildcarded_test_address_list
);
1890 if (n
> n_test_addrs
/2) {
1891 tor_log(dns_wildcarded_test_address_notice_given
? LOG_INFO
: LOG_NOTICE
,
1892 LD_EXIT
, "Your DNS provider tried to redirect \"%s\" to a junk "
1893 "address. It has done this with %d test addresses so far. I'm "
1894 "going to stop being an exit node for now, since our DNS seems so "
1895 "broken.", address
, n
);
1896 if (!dns_is_completely_invalid
) {
1897 dns_is_completely_invalid
= 1;
1898 mark_my_descriptor_dirty("dns hijacking confirmed");
1900 if (!dns_wildcarded_test_address_notice_given
)
1901 control_event_server_status(LOG_WARN
, "DNS_USELESS");
1902 dns_wildcarded_test_address_notice_given
= 1;
1906 /** Callback function when we get an answer (possibly failing) for a request
1907 * for a (hopefully) nonexistent domain. */
1909 evdns_wildcard_check_callback(int result
, char type
, int count
, int ttl
,
1910 void *addresses
, void *arg
)
1913 ++n_wildcard_requests
;
1914 if (result
== DNS_ERR_NONE
&& count
) {
1915 char *string_address
= arg
;
1917 if (type
== DNS_IPv4_A
) {
1918 const uint32_t *addrs
= addresses
;
1919 for (i
= 0; i
< count
; ++i
) {
1920 char answer_buf
[INET_NTOA_BUF_LEN
+1];
1922 in
.s_addr
= addrs
[i
];
1923 tor_inet_ntoa(&in
, answer_buf
, sizeof(answer_buf
));
1924 wildcard_increment_answer(answer_buf
);
1926 } else if (type
== DNS_IPv6_AAAA
) {
1927 const struct in6_addr
*addrs
= addresses
;
1928 for (i
= 0; i
< count
; ++i
) {
1929 char answer_buf
[TOR_ADDR_BUF_LEN
+1];
1930 tor_inet_ntop(AF_INET6
, &addrs
[i
], answer_buf
, sizeof(answer_buf
));
1931 wildcard_increment_answer(answer_buf
);
1935 tor_log(dns_wildcard_one_notice_given
? LOG_INFO
: LOG_NOTICE
, LD_EXIT
,
1936 "Your DNS provider gave an answer for \"%s\", which "
1937 "is not supposed to exist. Apparently they are hijacking "
1938 "DNS failures. Trying to correct for this. We've noticed %d "
1939 "possibly bad address%s so far.",
1940 string_address
, strmap_size(dns_wildcard_response_count
),
1941 (strmap_size(dns_wildcard_response_count
) == 1) ? "" : "es");
1942 dns_wildcard_one_notice_given
= 1;
1947 /** Launch a single request for a nonexistent hostname consisting of between
1948 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1951 launch_wildcard_check(int min_len
, int max_len
, int is_ipv6
,
1955 struct evdns_request
*req
;
1957 addr
= crypto_random_hostname(min_len
, max_len
, "", suffix
);
1958 log_info(LD_EXIT
, "Testing whether our DNS server is hijacking nonexistent "
1959 "domains with request for bogus hostname \"%s\"", addr
);
1961 tor_assert(the_evdns_base
);
1963 req
= evdns_base_resolve_ipv6(
1965 /* This "addr" tells us which address to resolve */
1967 DNS_QUERY_NO_SEARCH
, evdns_wildcard_check_callback
,
1968 /* This "addr" is an argument to the callback*/ addr
);
1970 req
= evdns_base_resolve_ipv4(
1972 /* This "addr" tells us which address to resolve */
1974 DNS_QUERY_NO_SEARCH
, evdns_wildcard_check_callback
,
1975 /* This "addr" is an argument to the callback*/ addr
);
1977 /* There is no evdns request in progress; stop addr from getting leaked */
1982 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1983 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1985 launch_test_addresses(evutil_socket_t fd
, short event
, void *args
)
1987 const or_options_t
*options
= get_options();
1992 if (options
->DisableNetwork
)
1995 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like to "
1996 "hijack *everything*.");
1997 /* This situation is worse than the failure-hijacking situation. When this
1998 * happens, we're no good for DNS requests at all, and we shouldn't really
1999 * be an exit server.*/
2000 if (options
->ServerDNSTestAddresses
) {
2002 tor_assert(the_evdns_base
);
2003 SMARTLIST_FOREACH_BEGIN(options
->ServerDNSTestAddresses
,
2004 const char *, address
) {
2005 if (launch_one_resolve(address
, DNS_IPv4_A
, NULL
) < 0) {
2006 log_info(LD_EXIT
, "eventdns rejected test address %s",
2007 escaped_safe_str(address
));
2010 if (launch_one_resolve(address
, DNS_IPv6_AAAA
, NULL
) < 0) {
2011 log_info(LD_EXIT
, "eventdns rejected test address %s",
2012 escaped_safe_str(address
));
2014 } SMARTLIST_FOREACH_END(address
);
2018 #define N_WILDCARD_CHECKS 2
2020 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
2021 * hostnames, and see if we can catch our nameserver trying to hijack them and
2022 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
2023 * buy these lovely encyclopedias" page. */
2025 dns_launch_wildcard_checks(void)
2028 log_info(LD_EXIT
, "Launching checks to see whether our nameservers like "
2029 "to hijack DNS failures.");
2030 for (ipv6
= 0; ipv6
<= 1; ++ipv6
) {
2031 for (i
= 0; i
< N_WILDCARD_CHECKS
; ++i
) {
2032 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
2033 * attempt to 'comply' with rfc2606, refrain from giving A records for
2034 * these. This is the standards-compliance equivalent of making sure
2035 * that your crackhouse's elevator inspection certificate is up to date.
2037 launch_wildcard_check(2, 16, ipv6
, ".invalid");
2038 launch_wildcard_check(2, 16, ipv6
, ".test");
2040 /* These will break specs if there are ever any number of
2041 * 8+-character top-level domains. */
2042 launch_wildcard_check(8, 16, ipv6
, "");
2044 /* Try some random .com/org/net domains. This will work fine so long as
2045 * not too many resolve to the same place. */
2046 launch_wildcard_check(8, 16, ipv6
, ".com");
2047 launch_wildcard_check(8, 16, ipv6
, ".org");
2048 launch_wildcard_check(8, 16, ipv6
, ".net");
2053 /** If appropriate, start testing whether our DNS servers tend to lie to
2056 dns_launch_correctness_checks(void)
2058 static struct event
*launch_event
= NULL
;
2059 struct timeval timeout
;
2060 if (!get_options()->ServerDNSDetectHijacking
)
2062 dns_launch_wildcard_checks();
2064 /* Wait a while before launching requests for test addresses, so we can
2065 * get the results from checking for wildcarding. */
2067 launch_event
= tor_evtimer_new(tor_libevent_get_base(),
2068 launch_test_addresses
, NULL
);
2069 timeout
.tv_sec
= 30;
2070 timeout
.tv_usec
= 0;
2071 if (evtimer_add(launch_event
, &timeout
)<0) {
2072 log_warn(LD_BUG
, "Couldn't add timer for checking for dns hijacking");
2076 /** Return true iff our DNS servers lie to us too much to be trusted. */
2078 dns_seems_to_be_broken(void)
2080 return dns_is_completely_invalid
;
2083 /** Return true iff we think that IPv6 hostname lookup is broken */
2085 dns_seems_to_be_broken_for_ipv6(void)
2087 return dns_is_broken_for_ipv6
;
2090 /** Forget what we've previously learned about our DNS servers' correctness. */
2092 dns_reset_correctness_checks(void)
2094 strmap_free(dns_wildcard_response_count
, tor_free_
);
2095 dns_wildcard_response_count
= NULL
;
2097 n_wildcard_requests
= 0;
2099 n_ipv6_requests_made
= n_ipv6_timeouts
= 0;
2101 if (dns_wildcard_list
) {
2102 SMARTLIST_FOREACH(dns_wildcard_list
, char *, cp
, tor_free(cp
));
2103 smartlist_clear(dns_wildcard_list
);
2105 if (dns_wildcarded_test_address_list
) {
2106 SMARTLIST_FOREACH(dns_wildcarded_test_address_list
, char *, cp
,
2108 smartlist_clear(dns_wildcarded_test_address_list
);
2110 dns_wildcard_one_notice_given
= dns_wildcard_notice_given
=
2111 dns_wildcarded_test_address_notice_given
= dns_is_completely_invalid
=
2112 dns_is_broken_for_ipv6
= 0;
2115 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
2116 * returned in response to requests for nonexistent hostnames. */
2118 answer_is_wildcarded(const char *ip
)
2120 return dns_wildcard_list
&& smartlist_contains_string(dns_wildcard_list
, ip
);
2123 /** Exit with an assertion if <b>resolve</b> is corrupt. */
2125 assert_resolve_ok(cached_resolve_t
*resolve
)
2127 tor_assert(resolve
);
2128 tor_assert(resolve
->magic
== CACHED_RESOLVE_MAGIC
);
2129 tor_assert(strlen(resolve
->address
) < MAX_ADDRESSLEN
);
2130 tor_assert(tor_strisnonupper(resolve
->address
));
2131 if (resolve
->state
!= CACHE_STATE_PENDING
) {
2132 tor_assert(!resolve
->pending_connections
);
2134 if (resolve
->state
== CACHE_STATE_PENDING
||
2135 resolve
->state
== CACHE_STATE_DONE
) {
2137 tor_assert(!resolve
->ttl
);
2138 if (resolve
->is_reverse
)
2139 tor_assert(!resolve
->hostname
);
2141 tor_assert(!resolve
->result_ipv4
.addr_ipv4
);
2147 /** Return the number of DNS cache entries as an int */
2149 dns_cache_entry_count(void)
2151 return HT_SIZE(&cache_root
);
2154 /** Log memory information about our internal DNS cache at level 'severity'. */
2156 dump_dns_mem_usage(int severity
)
2158 /* This should never be larger than INT_MAX. */
2159 int hash_count
= dns_cache_entry_count();
2160 size_t hash_mem
= sizeof(struct cached_resolve_t
) * hash_count
;
2161 hash_mem
+= HT_MEM_USAGE(&cache_root
);
2163 /* Print out the count and estimated size of our &cache_root. It undercounts
2164 hostnames in cached reverse resolves.
2166 tor_log(severity
, LD_MM
, "Our DNS cache has %d entries.", hash_count
);
2167 tor_log(severity
, LD_MM
, "Our DNS cache size is approximately %u bytes.",
2168 (unsigned)hash_mem
);
2171 #ifdef DEBUG_DNS_CACHE
2172 /** Exit with an assertion if the DNS cache is corrupt. */
2174 assert_cache_ok_(void)
2176 cached_resolve_t
**resolve
;
2177 int bad_rep
= HT_REP_IS_BAD_(cache_map
, &cache_root
);
2179 log_err(LD_BUG
, "Bad rep type %d on dns cache hash table", bad_rep
);
2180 tor_assert(!bad_rep
);
2183 HT_FOREACH(resolve
, cache_map
, &cache_root
) {
2184 assert_resolve_ok(*resolve
);
2185 tor_assert((*resolve
)->state
!= CACHE_STATE_DONE
);
2187 if (!cached_resolve_pqueue
)
2190 smartlist_pqueue_assert_ok(cached_resolve_pqueue
,
2191 compare_cached_resolves_by_expiry_
,
2192 STRUCT_OFFSET(cached_resolve_t
, minheap_idx
));
2194 SMARTLIST_FOREACH(cached_resolve_pqueue
, cached_resolve_t
*, res
,
2196 if (res
->state
== CACHE_STATE_DONE
) {
2197 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);
2198 tor_assert(!found
|| found
!= res
);
2200 cached_resolve_t
*found
= HT_FIND(cache_map
, &cache_root
, res
);