Move in-addr.arpa parsing and generation into address.c, and simplify the code that...
[tor/rransom.git] / src / or / dns.c
blob191fd068c10b15bc3ecc5ee8f4666861f3997314
1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char dns_c_id[] =
7 "$Id$";
9 /**
10 * \file dns.c
11 * \brief Implements a local cache for DNS results for Tor servers.
12 * This is implemented as a wrapper around Adam Langley's eventdns.c code.
13 * (We can't just use gethostbyname() and friends because we really need to
14 * be nonblocking.)
15 **/
17 #include "or.h"
18 #include "ht.h"
19 #include "eventdns.h"
21 /** Longest hostname we're willing to resolve. */
22 #define MAX_ADDRESSLEN 256
24 /** How long will we wait for an answer from the resolver before we decide
25 * that the resolver is wedged? */
26 #define RESOLVE_MAX_TIMEOUT 300
28 /** Possible outcomes from hostname lookup: permanent failure,
29 * transient (retryable) failure, and success. */
30 #define DNS_RESOLVE_FAILED_TRANSIENT 1
31 #define DNS_RESOLVE_FAILED_PERMANENT 2
32 #define DNS_RESOLVE_SUCCEEDED 3
34 /** Have we currently configured nameservers with eventdns? */
35 static int nameservers_configured = 0;
36 /** Did our most recent attempt to configure nameservers with eventdns fail? */
37 static int nameserver_config_failed = 0;
38 /** What was the resolv_conf fname we last used when configuring the
39 * nameservers? Used to check whether we need to reconfigure. */
40 static char *resolv_conf_fname = NULL;
41 /** What was the mtime on the resolv.conf file we last used when configuring
42 * the nameservers? Used to check whether we need to reconfigure. */
43 static time_t resolv_conf_mtime = 0;
45 /** Linked list of connections waiting for a DNS answer. */
46 typedef struct pending_connection_t {
47 edge_connection_t *conn;
48 struct pending_connection_t *next;
49 } pending_connection_t;
51 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
52 * pointers and memory stomping. */
53 #define CACHED_RESOLVE_MAGIC 0x1234F00D
55 /* Possible states for a cached resolve_t */
56 /** We are waiting for the resolver system to tell us an answer here.
57 * When we get one, or when we time out, the state of this cached_resolve_t
58 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
59 * entry. This cached_resolve_t will be in the hash table so that we will
60 * know not to launch more requests for this addr, but rather to add more
61 * connections to the pending list for the addr. */
62 #define CACHE_STATE_PENDING 0
63 /** This used to be a pending cached_resolve_t, and we got an answer for it.
64 * Now we're waiting for this cached_resolve_t to expire. This should
65 * have no pending connections, and should not appear in the hash table. */
66 #define CACHE_STATE_DONE 1
67 /** We are caching an answer for this address. This should have no pending
68 * connections, and should appear in the hash table. */
69 #define CACHE_STATE_CACHED_VALID 2
70 /** We are caching a failure for this address. This should have no pending
71 * connections, and should appear in the hash table */
72 #define CACHE_STATE_CACHED_FAILED 3
74 /** A DNS request: possibly completed, possibly pending; cached_resolve
75 * structs are stored at the OR side in a hash table, and as a linked
76 * list from oldest to newest.
78 typedef struct cached_resolve_t {
79 HT_ENTRY(cached_resolve_t) node;
80 uint32_t magic;
81 char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
82 union {
83 struct {
84 struct in6_addr addr6; /**< IPv6 addr for <b>address</b>. */
85 uint32_t addr; /**< IPv4 addr for <b>address</b>. */
86 } a;
87 char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
88 } result;
89 uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
90 uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
91 time_t expire; /**< Remove items from cache after this time. */
92 uint32_t ttl; /**< What TTL did the nameserver tell us? */
93 /** Connections that want to know when we get an answer for this resolve. */
94 pending_connection_t *pending_connections;
95 } cached_resolve_t;
97 static void purge_expired_resolves(time_t now);
98 static void dns_found_answer(const char *address, uint8_t is_reverse,
99 uint32_t addr, const char *hostname, char outcome,
100 uint32_t ttl);
101 static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
102 static int launch_resolve(edge_connection_t *exitconn);
103 static void add_wildcarded_test_address(const char *address);
104 static int configure_nameservers(int force);
105 static int answer_is_wildcarded(const char *ip);
106 static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
107 or_circuit_t *oncirc, char **resolved_to_hostname);
108 #ifdef DEBUG_DNS_CACHE
109 static void _assert_cache_ok(void);
110 #define assert_cache_ok() _assert_cache_ok()
111 #else
112 #define assert_cache_ok() STMT_NIL
113 #endif
114 static void assert_resolve_ok(cached_resolve_t *resolve);
116 /** Hash table of cached_resolve objects. */
117 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
119 /** Function to compare hashed resolves on their addresses; used to
120 * implement hash tables. */
121 static INLINE int
122 cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
124 /* make this smarter one day? */
125 assert_resolve_ok(a); // Not b; b may be just a search.
126 return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
129 /** Hash function for cached_resolve objects */
130 static INLINE unsigned int
131 cached_resolve_hash(cached_resolve_t *a)
133 return ht_string_hash(a->address);
136 HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
137 cached_resolves_eq)
138 HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
139 cached_resolves_eq, 0.6, malloc, realloc, free)
141 /** Initialize the DNS cache. */
142 static void
143 init_cache_map(void)
145 HT_INIT(cache_map, &cache_root);
148 /** Helper: called by eventdns when eventdns wants to log something. */
149 static void
150 evdns_log_cb(int warn, const char *msg)
152 const char *cp;
153 static int all_down = 0;
154 int severity = warn ? LOG_WARN : LOG_INFO;
155 if (!strcmpstart(msg, "Resolve requested for") &&
156 get_options()->SafeLogging) {
157 log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
158 return;
159 } else if (!strcmpstart(msg, "Search: ")) {
160 return;
162 if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
163 char *ns = tor_strndup(msg+11, cp-(msg+11));
164 const char *err = strchr(cp, ':')+2;
165 tor_assert(err);
166 /* Don't warn about a single failed nameserver; we'll warn with 'all
167 * nameservers have failed' if we're completely out of nameservers;
168 * otherwise, the situation is tolerable. */
169 severity = LOG_INFO;
170 control_event_server_status(LOG_NOTICE,
171 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
172 ns, escaped(err));
173 tor_free(ns);
174 } else if (!strcmpstart(msg, "Nameserver ") &&
175 (cp=strstr(msg, " is back up"))) {
176 char *ns = tor_strndup(msg+11, cp-(msg+11));
177 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
178 all_down = 0;
179 control_event_server_status(LOG_NOTICE,
180 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
181 tor_free(ns);
182 } else if (!strcmp(msg, "All nameservers have failed")) {
183 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
184 all_down = 1;
186 log(severity, LD_EXIT, "eventdns: %s", msg);
189 static void
190 randfn(char *b, size_t n)
192 crypto_rand(b,n);
195 /** Initialize the DNS subsystem; called by the OR process. */
197 dns_init(void)
199 init_cache_map();
200 evdns_set_random_bytes_fn(randfn);
201 if (get_options()->ServerDNSRandomizeCase)
202 evdns_set_option("randomize-case", "1", DNS_OPTIONS_ALL);
203 else
204 evdns_set_option("randomize-case", "0", DNS_OPTIONS_ALL);
205 if (server_mode(get_options())) {
206 int r = configure_nameservers(1);
207 return r;
209 return 0;
212 /** Called when DNS-related options change (or may have changed). Returns -1
213 * on failure, 0 on success. */
215 dns_reset(void)
217 or_options_t *options = get_options();
218 if (! server_mode(options)) {
219 evdns_clear_nameservers_and_suspend();
220 evdns_search_clear();
221 nameservers_configured = 0;
222 tor_free(resolv_conf_fname);
223 resolv_conf_mtime = 0;
224 } else {
225 if (configure_nameservers(0) < 0) {
226 return -1;
229 return 0;
232 /** Return true iff the most recent attempt to initialize the DNS subsystem
233 * failed. */
235 has_dns_init_failed(void)
237 return nameserver_config_failed;
240 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
241 * OP that asked us to resolve it. */
242 uint32_t
243 dns_clip_ttl(uint32_t ttl)
245 if (ttl < MIN_DNS_TTL)
246 return MIN_DNS_TTL;
247 else if (ttl > MAX_DNS_TTL)
248 return MAX_DNS_TTL;
249 else
250 return ttl;
253 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
254 * our cache. */
255 static uint32_t
256 dns_get_expiry_ttl(uint32_t ttl)
258 if (ttl < MIN_DNS_TTL)
259 return MIN_DNS_TTL;
260 else if (ttl > MAX_DNS_ENTRY_AGE)
261 return MAX_DNS_ENTRY_AGE;
262 else
263 return ttl;
266 /** Helper: free storage held by an entry in the DNS cache. */
267 static void
268 _free_cached_resolve(cached_resolve_t *r)
270 while (r->pending_connections) {
271 pending_connection_t *victim = r->pending_connections;
272 r->pending_connections = victim->next;
273 tor_free(victim);
275 if (r->is_reverse)
276 tor_free(r->result.hostname);
277 r->magic = 0xFF00FF00;
278 tor_free(r);
281 /** Compare two cached_resolve_t pointers by expiry time, and return
282 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
283 * the priority queue implementation. */
284 static int
285 _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
287 const cached_resolve_t *a = _a, *b = _b;
288 if (a->expire < b->expire)
289 return -1;
290 else if (a->expire == b->expire)
291 return 0;
292 else
293 return 1;
296 /** Priority queue of cached_resolve_t objects to let us know when they
297 * will expire. */
298 static smartlist_t *cached_resolve_pqueue = NULL;
300 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
301 * priority queue */
302 static void
303 set_expiry(cached_resolve_t *resolve, time_t expires)
305 tor_assert(resolve && resolve->expire == 0);
306 if (!cached_resolve_pqueue)
307 cached_resolve_pqueue = smartlist_create();
308 resolve->expire = expires;
309 smartlist_pqueue_add(cached_resolve_pqueue,
310 _compare_cached_resolves_by_expiry,
311 resolve);
314 /** Free all storage held in the DNS cache and related structures. */
315 void
316 dns_free_all(void)
318 cached_resolve_t **ptr, **next, *item;
319 assert_cache_ok();
320 if (cached_resolve_pqueue) {
321 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
323 if (res->state == CACHE_STATE_DONE)
324 _free_cached_resolve(res);
327 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
328 item = *ptr;
329 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
330 _free_cached_resolve(item);
332 HT_CLEAR(cache_map, &cache_root);
333 if (cached_resolve_pqueue)
334 smartlist_free(cached_resolve_pqueue);
335 cached_resolve_pqueue = NULL;
336 tor_free(resolv_conf_fname);
339 /** Remove every cached_resolve whose <b>expire</b> time is before or
340 * equal to <b>now</b> from the cache. */
341 static void
342 purge_expired_resolves(time_t now)
344 cached_resolve_t *resolve, *removed;
345 pending_connection_t *pend;
346 edge_connection_t *pendconn;
348 assert_cache_ok();
349 if (!cached_resolve_pqueue)
350 return;
352 while (smartlist_len(cached_resolve_pqueue)) {
353 resolve = smartlist_get(cached_resolve_pqueue, 0);
354 if (resolve->expire > now)
355 break;
356 smartlist_pqueue_pop(cached_resolve_pqueue,
357 _compare_cached_resolves_by_expiry);
359 if (resolve->state == CACHE_STATE_PENDING) {
360 log_debug(LD_EXIT,
361 "Expiring a dns resolve %s that's still pending. Forgot to "
362 "cull it? DNS resolve didn't tell us about the timeout?",
363 escaped_safe_str(resolve->address));
364 } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
365 resolve->state == CACHE_STATE_CACHED_FAILED) {
366 log_debug(LD_EXIT,
367 "Forgetting old cached resolve (address %s, expires %lu)",
368 escaped_safe_str(resolve->address),
369 (unsigned long)resolve->expire);
370 tor_assert(!resolve->pending_connections);
371 } else {
372 tor_assert(resolve->state == CACHE_STATE_DONE);
373 tor_assert(!resolve->pending_connections);
376 if (resolve->pending_connections) {
377 log_debug(LD_EXIT,
378 "Closing pending connections on timed-out DNS resolve!");
379 tor_fragile_assert();
380 while (resolve->pending_connections) {
381 pend = resolve->pending_connections;
382 resolve->pending_connections = pend->next;
383 /* Connections should only be pending if they have no socket. */
384 tor_assert(pend->conn->_base.s == -1);
385 pendconn = pend->conn;
386 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
387 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
388 connection_free(TO_CONN(pendconn));
389 tor_free(pend);
393 if (resolve->state == CACHE_STATE_CACHED_VALID ||
394 resolve->state == CACHE_STATE_CACHED_FAILED ||
395 resolve->state == CACHE_STATE_PENDING) {
396 removed = HT_REMOVE(cache_map, &cache_root, resolve);
397 if (removed != resolve) {
398 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
399 " the cache. Tried to purge %s (%p); instead got %s (%p).",
400 resolve->address, (void*)resolve,
401 removed ? removed->address : "NULL", (void*)remove);
403 tor_assert(removed == resolve);
404 } else {
405 /* This should be in state DONE. Make sure it's not in the cache. */
406 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
407 tor_assert(tmp != resolve);
409 if (resolve->is_reverse)
410 tor_free(resolve->result.hostname);
411 resolve->magic = 0xF0BBF0BB;
412 tor_free(resolve);
415 assert_cache_ok();
418 /** Send a response to the RESOLVE request of a connection.
419 * <b>answer_type</b> must be one of
420 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
422 * If <b>circ</b> is provided, and we have a cached answer, send the
423 * answer back along circ; otherwise, send the answer back along
424 * <b>conn</b>'s attached circuit.
426 static void
427 send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
429 char buf[RELAY_PAYLOAD_SIZE];
430 size_t buflen;
431 uint32_t ttl;
433 buf[0] = answer_type;
434 ttl = dns_clip_ttl(conn->address_ttl);
436 switch (answer_type)
438 case RESOLVED_TYPE_IPV4:
439 buf[1] = 4;
440 set_uint32(buf+2, tor_addr_to_ipv4n(&conn->_base.addr));
441 set_uint32(buf+6, htonl(ttl));
442 buflen = 10;
443 break;
444 /*XXXX IP6 need ipv6 implementation */
445 case RESOLVED_TYPE_ERROR_TRANSIENT:
446 case RESOLVED_TYPE_ERROR:
448 const char *errmsg = "Error resolving hostname";
449 size_t msglen = strlen(errmsg);
451 buf[1] = msglen;
452 strlcpy(buf+2, errmsg, sizeof(buf)-2);
453 set_uint32(buf+2+msglen, htonl(ttl));
454 buflen = 6+msglen;
455 break;
457 default:
458 tor_assert(0);
459 return;
461 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
463 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
466 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
467 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
468 * The answer type will be RESOLVED_HOSTNAME.
470 * If <b>circ</b> is provided, and we have a cached answer, send the
471 * answer back along circ; otherwise, send the answer back along
472 * <b>conn</b>'s attached circuit.
474 static void
475 send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
477 char buf[RELAY_PAYLOAD_SIZE];
478 size_t buflen;
479 uint32_t ttl;
480 size_t namelen = strlen(hostname);
481 tor_assert(hostname);
483 tor_assert(namelen < 256);
484 ttl = dns_clip_ttl(conn->address_ttl);
486 buf[0] = RESOLVED_TYPE_HOSTNAME;
487 buf[1] = (uint8_t)namelen;
488 memcpy(buf+2, hostname, namelen);
489 set_uint32(buf+2+namelen, htonl(ttl));
490 buflen = 2+namelen+4;
492 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
493 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
494 // log_notice(LD_EXIT, "Sent");
497 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
498 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
499 * If resolve failed, free exitconn and return -1.
501 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
502 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
503 * need to send back an END cell, since connection_exit_begin_conn will
504 * do that for us.)
506 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
507 * circuit.
509 * Else, if seen before and pending, add conn to the pending list,
510 * and return 0.
512 * Else, if not seen before, add conn to pending list, hand to
513 * dns farm, and return 0.
515 * Exitconn's on_circuit field must be set, but exitconn should not
516 * yet be linked onto the n_streams/resolving_streams list of that circuit.
517 * On success, link the connection to n_streams if it's an exit connection.
518 * On "pending", link the connection to resolving streams. Otherwise,
519 * clear its on_circuit field.
522 dns_resolve(edge_connection_t *exitconn)
524 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
525 int is_resolve, r;
526 char *hostname = NULL;
527 is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
529 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
531 switch (r) {
532 case 1:
533 /* We got an answer without a lookup -- either the answer was
534 * cached, or it was obvious (like an IP address). */
535 if (is_resolve) {
536 /* Send the answer back right now, and detach. */
537 if (hostname)
538 send_resolved_hostname_cell(exitconn, hostname);
539 else
540 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
541 exitconn->on_circuit = NULL;
542 } else {
543 /* Add to the n_streams list; the calling function will send back a
544 * connected cell. */
545 exitconn->next_stream = oncirc->n_streams;
546 oncirc->n_streams = exitconn;
548 break;
549 case 0:
550 /* The request is pending: add the connection into the linked list of
551 * resolving_streams on this circuit. */
552 exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
553 exitconn->next_stream = oncirc->resolving_streams;
554 oncirc->resolving_streams = exitconn;
555 break;
556 case -2:
557 case -1:
558 /* The request failed before it could start: cancel this connection,
559 * and stop everybody waiting for the same connection. */
560 if (is_resolve) {
561 send_resolved_cell(exitconn,
562 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
565 exitconn->on_circuit = NULL;
567 dns_cancel_pending_resolve(exitconn->_base.address);
569 if (!exitconn->_base.marked_for_close) {
570 connection_free(TO_CONN(exitconn));
571 // XXX ... and we just leak exitconn otherwise? -RD
572 // If it's marked for close, it's on closeable_connection_lst in
573 // main.c. If it's on the closeable list, it will get freed from
574 // main.c. -NM
575 // "<armadev> If that's true, there are other bugs around, where we
576 // don't check if it's marked, and will end up double-freeing."
577 // On the other hand, I don't know of any actual bugs here, so this
578 // shouldn't be holding up the rc. -RD
580 break;
581 default:
582 tor_assert(0);
585 tor_free(hostname);
586 return r;
589 /** Helper function for dns_resolve: same functionality, but does not handle:
590 * - marking connections on error and clearing their on_circuit
591 * - linking connections to n_streams/resolving_streams,
592 * - sending resolved cells if we have an answer/error right away,
594 * Return -2 on a transient error. If it's a reverse resolve and it's
595 * successful, sets *<b>hostname_out</b> to a newly allocated string
596 * holding the cached reverse DNS value.
598 static int
599 dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
600 or_circuit_t *oncirc, char **hostname_out)
602 cached_resolve_t *resolve;
603 cached_resolve_t search;
604 pending_connection_t *pending_connection;
605 routerinfo_t *me;
606 tor_addr_t addr;
607 time_t now = time(NULL);
608 uint8_t is_reverse = 0;
609 int r;
610 assert_connection_ok(TO_CONN(exitconn), 0);
611 tor_assert(exitconn->_base.s == -1);
612 assert_cache_ok();
613 tor_assert(oncirc);
615 /* first check if exitconn->_base.address is an IP. If so, we already
616 * know the answer. */
617 if (tor_addr_from_str(&addr, exitconn->_base.address)<0) {
618 tor_addr_assign(&exitconn->_base.addr, &addr);
619 exitconn->address_ttl = DEFAULT_DNS_TTL;
620 return 1;
622 /* If we're a non-exit, don't even do DNS lookups. */
623 if (!(me = router_get_my_routerinfo()) ||
624 policy_is_reject_star(me->exit_policy)) {
625 return -1;
627 if (address_is_invalid_destination(exitconn->_base.address, 0)) {
628 log(LOG_PROTOCOL_WARN, LD_EXIT,
629 "Rejecting invalid destination address %s",
630 escaped_safe_str(exitconn->_base.address));
631 return -1;
634 /* then take this opportunity to see if there are any expired
635 * resolves in the hash table. */
636 purge_expired_resolves(now);
638 /* lower-case exitconn->_base.address, so it's in canonical form */
639 tor_strlower(exitconn->_base.address);
641 /* Check whether this is a reverse lookup. If it's malformed, or it's a
642 * .in-addr.arpa address but this isn't a resolve request, kill the
643 * connection.
645 if ((r = tor_addr_parse_reverse_lookup_name(&addr, exitconn->_base.address,
646 AF_UNSPEC, 0)) != 0) {
647 if (r == 1) {
648 is_reverse = 1;
649 if (tor_addr_is_internal(&addr, 0)) /* internal address? */
650 return -1;
653 if (!is_reverse || !is_resolve) {
654 if (!is_reverse)
655 log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
656 escaped_safe_str(exitconn->_base.address));
657 else if (!is_resolve)
658 log_info(LD_EXIT,
659 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
660 "sending error.",
661 escaped_safe_str(exitconn->_base.address));
663 return -1;
665 //log_notice(LD_EXIT, "Looks like an address %s",
666 //exitconn->_base.address);
669 /* now check the hash table to see if 'address' is already there. */
670 strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
671 resolve = HT_FIND(cache_map, &cache_root, &search);
672 if (resolve && resolve->expire > now) { /* already there */
673 switch (resolve->state) {
674 case CACHE_STATE_PENDING:
675 /* add us to the pending list */
676 pending_connection = tor_malloc_zero(
677 sizeof(pending_connection_t));
678 pending_connection->conn = exitconn;
679 pending_connection->next = resolve->pending_connections;
680 resolve->pending_connections = pending_connection;
681 log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
682 "resolve of %s", exitconn->_base.s,
683 escaped_safe_str(exitconn->_base.address));
684 return 0;
685 case CACHE_STATE_CACHED_VALID:
686 log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
687 exitconn->_base.s,
688 escaped_safe_str(resolve->address));
689 exitconn->address_ttl = resolve->ttl;
690 if (resolve->is_reverse) {
691 tor_assert(is_resolve);
692 *hostname_out = tor_strdup(resolve->result.hostname);
693 } else {
694 tor_addr_from_ipv4h(&exitconn->_base.addr, resolve->result.a.addr);
696 return 1;
697 case CACHE_STATE_CACHED_FAILED:
698 log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
699 exitconn->_base.s,
700 escaped_safe_str(exitconn->_base.address));
701 return -1;
702 case CACHE_STATE_DONE:
703 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
704 tor_fragile_assert();
706 tor_assert(0);
708 tor_assert(!resolve);
709 /* not there, need to add it */
710 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
711 resolve->magic = CACHED_RESOLVE_MAGIC;
712 resolve->state = CACHE_STATE_PENDING;
713 resolve->is_reverse = is_reverse;
714 strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
716 /* add this connection to the pending list */
717 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
718 pending_connection->conn = exitconn;
719 resolve->pending_connections = pending_connection;
721 /* Add this resolve to the cache and priority queue. */
722 HT_INSERT(cache_map, &cache_root, resolve);
723 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
725 log_debug(LD_EXIT,"Launching %s.",
726 escaped_safe_str(exitconn->_base.address));
727 assert_cache_ok();
729 return launch_resolve(exitconn);
732 /** Log an error and abort if conn is waiting for a DNS resolve.
734 void
735 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
737 pending_connection_t *pend;
738 cached_resolve_t **resolve;
740 HT_FOREACH(resolve, cache_map, &cache_root) {
741 for (pend = (*resolve)->pending_connections;
742 pend;
743 pend = pend->next) {
744 tor_assert(pend->conn != conn);
749 /** Log an error and abort if any connection waiting for a DNS resolve is
750 * corrupted. */
751 void
752 assert_all_pending_dns_resolves_ok(void)
754 pending_connection_t *pend;
755 cached_resolve_t **resolve;
757 HT_FOREACH(resolve, cache_map, &cache_root) {
758 for (pend = (*resolve)->pending_connections;
759 pend;
760 pend = pend->next) {
761 assert_connection_ok(TO_CONN(pend->conn), 0);
762 tor_assert(pend->conn->_base.s == -1);
763 tor_assert(!connection_in_array(TO_CONN(pend->conn)));
768 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
770 void
771 connection_dns_remove(edge_connection_t *conn)
773 pending_connection_t *pend, *victim;
774 cached_resolve_t search;
775 cached_resolve_t *resolve;
777 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
778 tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
780 strlcpy(search.address, conn->_base.address, sizeof(search.address));
782 resolve = HT_FIND(cache_map, &cache_root, &search);
783 if (!resolve) {
784 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
785 escaped_safe_str(conn->_base.address));
786 return;
789 tor_assert(resolve->pending_connections);
790 assert_connection_ok(TO_CONN(conn),0);
792 pend = resolve->pending_connections;
794 if (pend->conn == conn) {
795 resolve->pending_connections = pend->next;
796 tor_free(pend);
797 log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
798 "for resolve of %s",
799 conn->_base.s, escaped_safe_str(conn->_base.address));
800 return;
801 } else {
802 for ( ; pend->next; pend = pend->next) {
803 if (pend->next->conn == conn) {
804 victim = pend->next;
805 pend->next = victim->next;
806 tor_free(victim);
807 log_debug(LD_EXIT,
808 "Connection (fd %d) no longer waiting for resolve of %s",
809 conn->_base.s, escaped_safe_str(conn->_base.address));
810 return; /* more are pending */
813 tor_assert(0); /* not reachable unless onlyconn not in pending list */
817 /** Mark all connections waiting for <b>address</b> for close. Then cancel
818 * the resolve for <b>address</b> itself, and remove any cached results for
819 * <b>address</b> from the cache.
821 void
822 dns_cancel_pending_resolve(const char *address)
824 pending_connection_t *pend;
825 cached_resolve_t search;
826 cached_resolve_t *resolve, *tmp;
827 edge_connection_t *pendconn;
828 circuit_t *circ;
830 strlcpy(search.address, address, sizeof(search.address));
832 resolve = HT_FIND(cache_map, &cache_root, &search);
833 if (!resolve)
834 return;
836 if (resolve->state != CACHE_STATE_PENDING) {
837 /* We can get into this state if we never actually created the pending
838 * resolve, due to finding an earlier cached error or something. Just
839 * ignore it. */
840 if (resolve->pending_connections) {
841 log_warn(LD_BUG,
842 "Address %s is not pending but has pending connections!",
843 escaped_safe_str(address));
844 tor_fragile_assert();
846 return;
849 if (!resolve->pending_connections) {
850 log_warn(LD_BUG,
851 "Address %s is pending but has no pending connections!",
852 escaped_safe_str(address));
853 tor_fragile_assert();
854 return;
856 tor_assert(resolve->pending_connections);
858 /* mark all pending connections to fail */
859 log_debug(LD_EXIT,
860 "Failing all connections waiting on DNS resolve of %s",
861 escaped_safe_str(address));
862 while (resolve->pending_connections) {
863 pend = resolve->pending_connections;
864 pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
865 pendconn = pend->conn;
866 assert_connection_ok(TO_CONN(pendconn), 0);
867 tor_assert(pendconn->_base.s == -1);
868 if (!pendconn->_base.marked_for_close) {
869 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
871 circ = circuit_get_by_edge_conn(pendconn);
872 if (circ)
873 circuit_detach_stream(circ, pendconn);
874 if (!pendconn->_base.marked_for_close)
875 connection_free(TO_CONN(pendconn));
876 resolve->pending_connections = pend->next;
877 tor_free(pend);
880 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
881 if (tmp != resolve) {
882 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
883 " the cache. Tried to purge %s (%p); instead got %s (%p).",
884 resolve->address, (void*)resolve,
885 tmp ? tmp->address : "NULL", (void*)tmp);
887 tor_assert(tmp == resolve);
889 resolve->state = CACHE_STATE_DONE;
892 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
893 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
894 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
895 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
897 static void
898 add_answer_to_cache(const char *address, uint8_t is_reverse, uint32_t addr,
899 const char *hostname, char outcome, uint32_t ttl)
901 cached_resolve_t *resolve;
902 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
903 return;
905 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
906 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
907 // hostname?hostname:"NULL",(int)outcome);
909 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
910 resolve->magic = CACHED_RESOLVE_MAGIC;
911 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
912 CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
913 strlcpy(resolve->address, address, sizeof(resolve->address));
914 resolve->is_reverse = is_reverse;
915 if (is_reverse) {
916 if (outcome == DNS_RESOLVE_SUCCEEDED) {
917 tor_assert(hostname);
918 resolve->result.hostname = tor_strdup(hostname);
919 } else {
920 tor_assert(! hostname);
921 resolve->result.hostname = NULL;
923 } else {
924 tor_assert(!hostname);
925 resolve->result.a.addr = addr;
927 resolve->ttl = ttl;
928 assert_resolve_ok(resolve);
929 HT_INSERT(cache_map, &cache_root, resolve);
930 set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
933 /** Return true iff <b>address</b> is one of the addresses we use to verify
934 * that well-known sites aren't being hijacked by our DNS servers. */
935 static INLINE int
936 is_test_address(const char *address)
938 or_options_t *options = get_options();
939 return options->ServerDNSTestAddresses &&
940 smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
943 /** Called on the OR side when a DNS worker or the eventdns library tells us
944 * the outcome of a DNS resolve: tell all pending connections about the result
945 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
946 * string containing the address to look up; <b>addr</b> is an IPv4 address in
947 * host order; <b>outcome</b> is one of
948 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
950 static void
951 dns_found_answer(const char *address, uint8_t is_reverse, uint32_t addr,
952 const char *hostname, char outcome, uint32_t ttl)
954 pending_connection_t *pend;
955 cached_resolve_t search;
956 cached_resolve_t *resolve, *removed;
957 edge_connection_t *pendconn;
958 circuit_t *circ;
960 assert_cache_ok();
962 strlcpy(search.address, address, sizeof(search.address));
964 resolve = HT_FIND(cache_map, &cache_root, &search);
965 if (!resolve) {
966 int is_test_addr = is_test_address(address);
967 if (!is_test_addr)
968 log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
969 escaped_safe_str(address));
970 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
971 return;
973 assert_resolve_ok(resolve);
975 if (resolve->state != CACHE_STATE_PENDING) {
976 /* XXXX Maybe update addr? or check addr for consistency? Or let
977 * VALID replace FAILED? */
978 int is_test_addr = is_test_address(address);
979 if (!is_test_addr)
980 log_notice(LD_EXIT,
981 "Resolved %s which was already resolved; ignoring",
982 escaped_safe_str(address));
983 tor_assert(resolve->pending_connections == NULL);
984 return;
986 /* Removed this assertion: in fact, we'll sometimes get a double answer
987 * to the same question. This can happen when we ask one worker to resolve
988 * X.Y.Z., then we cancel the request, and then we ask another worker to
989 * resolve X.Y.Z. */
990 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
992 while (resolve->pending_connections) {
993 pend = resolve->pending_connections;
994 pendconn = pend->conn; /* don't pass complex things to the
995 connection_mark_for_close macro */
996 assert_connection_ok(TO_CONN(pendconn),time(NULL));
997 tor_addr_from_ipv4h(&pendconn->_base.addr, addr);
998 pendconn->address_ttl = ttl;
1000 if (outcome != DNS_RESOLVE_SUCCEEDED) {
1001 /* prevent double-remove. */
1002 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1003 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1004 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1005 /* This detach must happen after we send the end cell. */
1006 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1007 } else {
1008 send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
1009 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
1010 /* This detach must happen after we send the resolved cell. */
1011 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1013 connection_free(TO_CONN(pendconn));
1014 } else {
1015 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1016 tor_assert(!is_reverse);
1017 /* prevent double-remove. */
1018 pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
1020 circ = circuit_get_by_edge_conn(pend->conn);
1021 tor_assert(circ);
1022 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1023 /* unlink pend->conn from resolving_streams, */
1024 circuit_detach_stream(circ, pend->conn);
1025 /* and link it to n_streams */
1026 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1027 pend->conn->on_circuit = circ;
1028 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1030 connection_exit_connect(pend->conn);
1031 } else {
1032 /* prevent double-remove. This isn't really an accurate state,
1033 * but it does the right thing. */
1034 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1035 if (is_reverse)
1036 send_resolved_hostname_cell(pendconn, hostname);
1037 else
1038 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
1039 circ = circuit_get_by_edge_conn(pendconn);
1040 tor_assert(circ);
1041 circuit_detach_stream(circ, pendconn);
1042 connection_free(TO_CONN(pendconn));
1045 resolve->pending_connections = pend->next;
1046 tor_free(pend);
1049 resolve->state = CACHE_STATE_DONE;
1050 removed = HT_REMOVE(cache_map, &cache_root, &search);
1051 if (removed != resolve) {
1052 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1053 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1054 resolve->address, (void*)resolve,
1055 removed ? removed->address : "NULL", (void*)removed);
1057 assert_resolve_ok(resolve);
1058 assert_cache_ok();
1060 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
1061 assert_cache_ok();
1064 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1065 * a transient failure. */
1066 static int
1067 evdns_err_is_transient(int err)
1069 switch (err)
1071 case DNS_ERR_SERVERFAILED:
1072 case DNS_ERR_TRUNCATED:
1073 case DNS_ERR_TIMEOUT:
1074 return 1;
1075 default:
1076 return 0;
1080 /** Configure eventdns nameservers if force is true, or if the configuration
1081 * has changed since the last time we called this function, or if we failed on
1082 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1083 * options->ServerDNSResolvConfFile; on Windows, this reads from
1084 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1085 * -1 on failure. */
1086 static int
1087 configure_nameservers(int force)
1089 or_options_t *options;
1090 const char *conf_fname;
1091 struct stat st;
1092 int r;
1093 options = get_options();
1094 conf_fname = options->ServerDNSResolvConfFile;
1095 #ifndef MS_WINDOWS
1096 if (!conf_fname)
1097 conf_fname = "/etc/resolv.conf";
1098 #endif
1100 evdns_set_log_fn(evdns_log_cb);
1101 if (conf_fname) {
1102 if (stat(conf_fname, &st)) {
1103 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1104 conf_fname, strerror(errno));
1105 goto err;
1107 if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
1108 && st.st_mtime == resolv_conf_mtime) {
1109 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1110 return 0;
1112 if (nameservers_configured) {
1113 evdns_search_clear();
1114 evdns_clear_nameservers_and_suspend();
1116 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1117 if ((r = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname))) {
1118 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1119 conf_fname, conf_fname, r);
1120 goto err;
1122 if (evdns_count_nameservers() == 0) {
1123 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
1124 goto err;
1126 tor_free(resolv_conf_fname);
1127 resolv_conf_fname = tor_strdup(conf_fname);
1128 resolv_conf_mtime = st.st_mtime;
1129 if (nameservers_configured)
1130 evdns_resume();
1132 #ifdef MS_WINDOWS
1133 else {
1134 if (nameservers_configured) {
1135 evdns_search_clear();
1136 evdns_clear_nameservers_and_suspend();
1138 if (evdns_config_windows_nameservers()) {
1139 log_warn(LD_EXIT,"Could not config nameservers.");
1140 goto err;
1142 if (evdns_count_nameservers() == 0) {
1143 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1144 "your Windows configuration.");
1145 goto err;
1147 if (nameservers_configured)
1148 evdns_resume();
1149 tor_free(resolv_conf_fname);
1150 resolv_conf_mtime = 0;
1152 #endif
1154 if (evdns_count_nameservers() == 1) {
1155 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
1156 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
1157 } else {
1158 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
1159 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
1162 dns_servers_relaunch_checks();
1164 nameservers_configured = 1;
1165 if (nameserver_config_failed) {
1166 nameserver_config_failed = 0;
1167 mark_my_descriptor_dirty();
1169 return 0;
1170 err:
1171 nameservers_configured = 0;
1172 if (! nameserver_config_failed) {
1173 nameserver_config_failed = 1;
1174 mark_my_descriptor_dirty();
1176 return -1;
1179 /** For eventdns: Called when we get an answer for a request we launched.
1180 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1182 static void
1183 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1184 void *arg)
1186 char *string_address = arg;
1187 uint8_t is_reverse = 0;
1188 int status = DNS_RESOLVE_FAILED_PERMANENT;
1189 uint32_t addr = 0;
1190 const char *hostname = NULL;
1191 int was_wildcarded = 0;
1193 if (result == DNS_ERR_NONE) {
1194 if (type == DNS_IPv4_A && count) {
1195 char answer_buf[INET_NTOA_BUF_LEN+1];
1196 struct in_addr in;
1197 char *escaped_address;
1198 uint32_t *addrs = addresses;
1199 in.s_addr = addrs[0];
1200 addr = ntohl(addrs[0]);
1201 status = DNS_RESOLVE_SUCCEEDED;
1202 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1203 escaped_address = esc_for_log(string_address);
1205 if (answer_is_wildcarded(answer_buf)) {
1206 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1207 "address %s; treating as a failure.",
1208 safe_str(escaped_address),
1209 escaped_safe_str(answer_buf));
1210 was_wildcarded = 1;
1211 addr = 0;
1212 status = DNS_RESOLVE_FAILED_PERMANENT;
1213 } else {
1214 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1215 safe_str(escaped_address),
1216 escaped_safe_str(answer_buf));
1218 tor_free(escaped_address);
1219 } else if (type == DNS_PTR && count) {
1220 char *escaped_address;
1221 is_reverse = 1;
1222 hostname = ((char**)addresses)[0];
1223 status = DNS_RESOLVE_SUCCEEDED;
1224 escaped_address = esc_for_log(string_address);
1225 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1226 safe_str(escaped_address),
1227 escaped_safe_str(hostname));
1228 tor_free(escaped_address);
1229 } else if (count) {
1230 log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
1231 escaped_safe_str(string_address));
1232 } else {
1233 log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
1234 escaped_safe_str(string_address));
1236 } else {
1237 if (evdns_err_is_transient(result))
1238 status = DNS_RESOLVE_FAILED_TRANSIENT;
1240 if (was_wildcarded) {
1241 if (is_test_address(string_address)) {
1242 /* Ick. We're getting redirected on known-good addresses. Our DNS
1243 * server must really hate us. */
1244 add_wildcarded_test_address(string_address);
1247 if (result != DNS_ERR_SHUTDOWN)
1248 dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
1249 tor_free(string_address);
1252 /** For eventdns: start resolving as necessary to find the target for
1253 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1254 * 0 on "resolve launched." */
1255 static int
1256 launch_resolve(edge_connection_t *exitconn)
1258 char *addr = tor_strdup(exitconn->_base.address);
1259 tor_addr_t a;
1260 int r;
1261 int options = get_options()->ServerDNSSearchDomains ? 0
1262 : DNS_QUERY_NO_SEARCH;
1263 /* What? Nameservers not configured? Sounds like a bug. */
1264 if (!nameservers_configured) {
1265 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1266 "launched. Configuring.");
1267 if (configure_nameservers(1) < 0) {
1268 return -1;
1272 r = tor_addr_parse_reverse_lookup_name(
1273 &a, exitconn->_base.address, AF_UNSPEC, 0);
1274 if (r == 0) {
1275 log_info(LD_EXIT, "Launching eventdns request for %s",
1276 escaped_safe_str(exitconn->_base.address));
1277 r = evdns_resolve_ipv4(exitconn->_base.address, options,
1278 evdns_callback, addr);
1279 } else if (r == 1) {
1280 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1281 escaped_safe_str(exitconn->_base.address));
1282 if (tor_addr_family(&a) == AF_INET)
1283 r = evdns_resolve_reverse(tor_addr_to_in(&a), DNS_QUERY_NO_SEARCH,
1284 evdns_callback, addr);
1285 else
1286 r = evdns_resolve_reverse_ipv6(tor_addr_to_in6(&a), DNS_QUERY_NO_SEARCH,
1287 evdns_callback, addr);
1288 } else if (r == -1) {
1289 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1292 if (r) {
1293 log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
1294 escaped_safe_str(addr), r);
1295 r = evdns_err_is_transient(r) ? -2 : -1;
1296 tor_free(addr); /* There is no evdns request in progress; stop
1297 * addr from getting leaked. */
1299 return r;
1302 /** How many requests for bogus addresses have we launched so far? */
1303 static int n_wildcard_requests = 0;
1305 /** Map from dotted-quad IP address in response to an int holding how many
1306 * times we've seen it for a randomly generated (hopefully bogus) address. It
1307 * would be easier to use definitely-invalid addresses (as specified by
1308 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1309 static strmap_t *dns_wildcard_response_count = NULL;
1311 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1312 * nameserver wants to return in response to requests for nonexistent domains.
1314 static smartlist_t *dns_wildcard_list = NULL;
1315 /** True iff we've logged about a single address getting wildcarded.
1316 * Subsequent warnings will be less severe. */
1317 static int dns_wildcard_one_notice_given = 0;
1318 /** True iff we've warned that our DNS server is wildcarding too many failures.
1320 static int dns_wildcard_notice_given = 0;
1322 /** List of supposedly good addresses that are getting wildcarded to the
1323 * same addresses as nonexistent addresses. */
1324 static smartlist_t *dns_wildcarded_test_address_list = NULL;
1325 /** True iff we've warned about a test address getting wildcarded */
1326 static int dns_wildcarded_test_address_notice_given = 0;
1327 /** True iff all addresses seem to be getting wildcarded. */
1328 static int dns_is_completely_invalid = 0;
1330 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1331 * a hopefully bogus address. */
1332 static void
1333 wildcard_increment_answer(const char *id)
1335 int *ip;
1336 if (!dns_wildcard_response_count)
1337 dns_wildcard_response_count = strmap_new();
1339 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1340 if (!ip) {
1341 ip = tor_malloc_zero(sizeof(int));
1342 strmap_set(dns_wildcard_response_count, id, ip);
1344 ++*ip;
1346 if (*ip > 5 && n_wildcard_requests > 10) {
1347 if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
1348 if (!smartlist_string_isin(dns_wildcard_list, id)) {
1349 log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1350 "Your DNS provider has given \"%s\" as an answer for %d different "
1351 "invalid addresses. Apparently they are hijacking DNS failures. "
1352 "I'll try to correct for this by treating future occurrences of "
1353 "\"%s\" as 'not found'.", id, *ip, id);
1354 smartlist_add(dns_wildcard_list, tor_strdup(id));
1356 if (!dns_wildcard_notice_given)
1357 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1358 dns_wildcard_notice_given = 1;
1362 /** Note that a single test address (one believed to be good) seems to be
1363 * getting redirected to the same IP as failures are. */
1364 static void
1365 add_wildcarded_test_address(const char *address)
1367 int n, n_test_addrs;
1368 if (!dns_wildcarded_test_address_list)
1369 dns_wildcarded_test_address_list = smartlist_create();
1371 if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
1372 return;
1374 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1375 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1377 smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
1378 n = smartlist_len(dns_wildcarded_test_address_list);
1379 if (n > n_test_addrs/2) {
1380 log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
1381 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1382 "address. It has done this with %d test addresses so far. I'm "
1383 "going to stop being an exit node for now, since our DNS seems so "
1384 "broken.", address, n);
1385 if (!dns_is_completely_invalid) {
1386 dns_is_completely_invalid = 1;
1387 mark_my_descriptor_dirty();
1389 if (!dns_wildcarded_test_address_notice_given)
1390 control_event_server_status(LOG_WARN, "DNS_USELESS");
1391 dns_wildcarded_test_address_notice_given = 1;
1395 /** Callback function when we get an answer (possibly failing) for a request
1396 * for a (hopefully) nonexistent domain. */
1397 static void
1398 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1399 void *addresses, void *arg)
1401 (void)ttl;
1402 ++n_wildcard_requests;
1403 if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
1404 uint32_t *addrs = addresses;
1405 int i;
1406 char *string_address = arg;
1407 for (i = 0; i < count; ++i) {
1408 char answer_buf[INET_NTOA_BUF_LEN+1];
1409 struct in_addr in;
1410 in.s_addr = addrs[i];
1411 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1412 wildcard_increment_answer(answer_buf);
1414 log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1415 "Your DNS provider gave an answer for \"%s\", which "
1416 "is not supposed to exist. Apparently they are hijacking "
1417 "DNS failures. Trying to correct for this. We've noticed %d "
1418 "possibly bad address%s so far.",
1419 string_address, strmap_size(dns_wildcard_response_count),
1420 (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
1421 dns_wildcard_one_notice_given = 1;
1423 tor_free(arg);
1426 /** Launch a single request for a nonexistent hostname consisting of between
1427 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1428 * <b>suffix</b> */
1429 static void
1430 launch_wildcard_check(int min_len, int max_len, const char *suffix)
1432 char *addr;
1433 int r;
1435 addr = crypto_random_hostname(min_len, max_len, "", suffix);
1436 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1437 "domains with request for bogus hostname \"%s\"", addr);
1439 r = evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
1440 addr,
1441 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1442 /* This "addr" is an argument to the callback*/ addr);
1443 if (r) {
1444 /* There is no evdns request in progress; stop addr from getting leaked */
1445 tor_free(addr);
1449 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1450 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1451 static void
1452 launch_test_addresses(int fd, short event, void *args)
1454 or_options_t *options = get_options();
1455 (void)fd;
1456 (void)event;
1457 (void)args;
1459 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1460 "hijack *everything*.");
1461 /* This situation is worse than the failure-hijacking situation. When this
1462 * happens, we're no good for DNS requests at all, and we shouldn't really
1463 * be an exit server.*/
1464 if (!options->ServerDNSTestAddresses)
1465 return;
1466 SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
1468 int r = evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
1469 tor_strdup(address));
1470 if (r)
1471 log_info(LD_EXIT, "eventdns rejected test address %s: error %d",
1472 escaped_safe_str(address), r);
1476 #define N_WILDCARD_CHECKS 2
1478 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1479 * hostnames, and see if we can catch our nameserver trying to hijack them and
1480 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1481 * buy these lovely encyclopedias" page. */
1482 static void
1483 dns_launch_wildcard_checks(void)
1485 int i;
1486 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
1487 "to hijack DNS failures.");
1488 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
1489 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1490 * to 'comply' with rfc2606, refrain from giving A records for these.
1491 * This is the standards-compliance equivalent of making sure that your
1492 * crackhouse's elevator inspection certificate is up to date.
1494 launch_wildcard_check(2, 16, ".invalid");
1495 launch_wildcard_check(2, 16, ".test");
1497 /* These will break specs if there are ever any number of
1498 * 8+-character top-level domains. */
1499 launch_wildcard_check(8, 16, "");
1501 /* Try some random .com/org/net domains. This will work fine so long as
1502 * not too many resolve to the same place. */
1503 launch_wildcard_check(8, 16, ".com");
1504 launch_wildcard_check(8, 16, ".org");
1505 launch_wildcard_check(8, 16, ".net");
1509 /** If appropriate, start testing whether our DNS servers tend to lie to
1510 * us. */
1511 void
1512 dns_launch_correctness_checks(void)
1514 static struct event launch_event;
1515 struct timeval timeout;
1516 if (!get_options()->ServerDNSDetectHijacking)
1517 return;
1518 dns_launch_wildcard_checks();
1520 /* Wait a while before launching requests for test addresses, so we can
1521 * get the results from checking for wildcarding. */
1522 evtimer_set(&launch_event, launch_test_addresses, NULL);
1523 timeout.tv_sec = 30;
1524 timeout.tv_usec = 0;
1525 if (evtimer_add(&launch_event, &timeout)<0) {
1526 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
1530 /** Return true iff our DNS servers lie to us too much to be trustd. */
1532 dns_seems_to_be_broken(void)
1534 return dns_is_completely_invalid;
1537 /** Forget what we've previously learned about our DNS servers' correctness. */
1538 void
1539 dns_reset_correctness_checks(void)
1541 if (dns_wildcard_response_count) {
1542 strmap_free(dns_wildcard_response_count, _tor_free);
1543 dns_wildcard_response_count = NULL;
1545 n_wildcard_requests = 0;
1547 if (dns_wildcard_list) {
1548 SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
1549 smartlist_clear(dns_wildcard_list);
1551 if (dns_wildcarded_test_address_list) {
1552 SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
1553 tor_free(cp));
1554 smartlist_clear(dns_wildcarded_test_address_list);
1556 dns_wildcard_one_notice_given = dns_wildcard_notice_given =
1557 dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
1560 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1561 * returned in response to requests for nonexistent hostnames. */
1562 static int
1563 answer_is_wildcarded(const char *ip)
1565 return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
1568 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1569 static void
1570 assert_resolve_ok(cached_resolve_t *resolve)
1572 tor_assert(resolve);
1573 tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
1574 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
1575 tor_assert(tor_strisnonupper(resolve->address));
1576 if (resolve->state != CACHE_STATE_PENDING) {
1577 tor_assert(!resolve->pending_connections);
1579 if (resolve->state == CACHE_STATE_PENDING ||
1580 resolve->state == CACHE_STATE_DONE) {
1581 tor_assert(!resolve->ttl);
1582 if (resolve->is_reverse)
1583 tor_assert(!resolve->result.hostname);
1584 else
1585 tor_assert(!resolve->result.a.addr);
1589 #ifdef DEBUG_DNS_CACHE
1590 /** Exit with an assertion if the DNS cache is corrupt. */
1591 static void
1592 _assert_cache_ok(void)
1594 cached_resolve_t **resolve;
1595 int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
1596 if (bad_rep) {
1597 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
1598 tor_assert(!bad_rep);
1601 HT_FOREACH(resolve, cache_map, &cache_root) {
1602 assert_resolve_ok(*resolve);
1603 tor_assert((*resolve)->state != CACHE_STATE_DONE);
1605 if (!cached_resolve_pqueue)
1606 return;
1608 smartlist_pqueue_assert_ok(cached_resolve_pqueue,
1609 _compare_cached_resolves_by_expiry);
1611 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
1613 if (res->state == CACHE_STATE_DONE) {
1614 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1615 tor_assert(!found || found != res);
1616 } else {
1617 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1618 tor_assert(found);
1622 #endif