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