Enhance pqueue so we can remove items from the middle.
[tor.git] / src / or / dns.c
blob9ecdf426e40c4daa75460321c1a59de43c838d4c
1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, 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 "ht.h"
16 #ifdef HAVE_EVENT2_DNS_H
17 #include <event2/event.h>
18 #include <event2/dns.h>
19 #else
20 #include <event.h>
21 #include "eventdns.h"
22 #ifndef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
23 #define HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
24 #endif
25 #endif
27 #ifndef HAVE_EVENT2_DNS_H
28 struct evdns_base;
29 struct evdns_request;
30 #define evdns_base_new(x,y) tor_malloc(1)
31 #define evdns_base_clear_nameservers_and_suspend(base) \
32 evdns_clear_nameservers_and_suspend()
33 #define evdns_base_search_clear(base) evdns_search_clear()
34 #define evdns_base_set_default_outgoing_bind_address(base, a, len) \
35 evdns_set_default_outgoing_bind_address((a),(len))
36 #define evdns_base_resolv_conf_parse(base, options, fname) \
37 evdns_resolv_conf_parse((options), (fname))
38 #define evdns_base_count_nameservers(base) \
39 evdns_count_nameservers()
40 #define evdns_base_resume(base) \
41 evdns_resume()
42 #define evdns_base_config_windows_nameservers(base) \
43 evdns_config_windows_nameservers()
44 #define evdns_base_set_option(base, opt, val, flags) \
45 evdns_set_option((opt),(val),(flags))
46 #define evdns_base_resolve_ipv4(base, addr, options, cb, ptr) \
47 ((evdns_resolve_ipv4(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
48 #define evdns_base_resolve_reverse(base, addr, options, cb, ptr) \
49 ((evdns_resolve_reverse(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
50 #define evdns_base_resolve_reverse_ipv6(base, addr, options, cb, ptr) \
51 ((evdns_resolve_reverse_ipv6(addr, options, cb, ptr)<0) ? NULL : ((void*)1))
52 #endif
54 /** Longest hostname we're willing to resolve. */
55 #define MAX_ADDRESSLEN 256
57 /** How long will we wait for an answer from the resolver before we decide
58 * that the resolver is wedged? */
59 #define RESOLVE_MAX_TIMEOUT 300
61 /** Possible outcomes from hostname lookup: permanent failure,
62 * transient (retryable) failure, and success. */
63 #define DNS_RESOLVE_FAILED_TRANSIENT 1
64 #define DNS_RESOLVE_FAILED_PERMANENT 2
65 #define DNS_RESOLVE_SUCCEEDED 3
67 /** Our evdns_base; this structure handles all our name lookups. */
68 static struct evdns_base *the_evdns_base = NULL;
70 /** Have we currently configured nameservers with eventdns? */
71 static int nameservers_configured = 0;
72 /** Did our most recent attempt to configure nameservers with eventdns fail? */
73 static int nameserver_config_failed = 0;
74 /** What was the resolv_conf fname we last used when configuring the
75 * nameservers? Used to check whether we need to reconfigure. */
76 static char *resolv_conf_fname = NULL;
77 /** What was the mtime on the resolv.conf file we last used when configuring
78 * the nameservers? Used to check whether we need to reconfigure. */
79 static time_t resolv_conf_mtime = 0;
81 /** Linked list of connections waiting for a DNS answer. */
82 typedef struct pending_connection_t {
83 edge_connection_t *conn;
84 struct pending_connection_t *next;
85 } pending_connection_t;
87 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
88 * pointers and memory stomping. */
89 #define CACHED_RESOLVE_MAGIC 0x1234F00D
91 /* Possible states for a cached resolve_t */
92 /** We are waiting for the resolver system to tell us an answer here.
93 * When we get one, or when we time out, the state of this cached_resolve_t
94 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
95 * entry. This cached_resolve_t will be in the hash table so that we will
96 * know not to launch more requests for this addr, but rather to add more
97 * connections to the pending list for the addr. */
98 #define CACHE_STATE_PENDING 0
99 /** This used to be a pending cached_resolve_t, and we got an answer for it.
100 * Now we're waiting for this cached_resolve_t to expire. This should
101 * have no pending connections, and should not appear in the hash table. */
102 #define CACHE_STATE_DONE 1
103 /** We are caching an answer for this address. This should have no pending
104 * connections, and should appear in the hash table. */
105 #define CACHE_STATE_CACHED_VALID 2
106 /** We are caching a failure for this address. This should have no pending
107 * connections, and should appear in the hash table */
108 #define CACHE_STATE_CACHED_FAILED 3
110 /** A DNS request: possibly completed, possibly pending; cached_resolve
111 * structs are stored at the OR side in a hash table, and as a linked
112 * list from oldest to newest.
114 typedef struct cached_resolve_t {
115 HT_ENTRY(cached_resolve_t) node;
116 uint32_t magic;
117 char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
118 union {
119 struct {
120 struct in6_addr addr6; /**< IPv6 addr for <b>address</b>. */
121 uint32_t addr; /**< IPv4 addr for <b>address</b>. */
122 } a;
123 char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
124 } result;
125 uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
126 uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
127 time_t expire; /**< Remove items from cache after this time. */
128 uint32_t ttl; /**< What TTL did the nameserver tell us? */
129 /** Connections that want to know when we get an answer for this resolve. */
130 pending_connection_t *pending_connections;
131 /** Position of this element in the heap*/
132 int minheap_idx;
133 } cached_resolve_t;
135 static void purge_expired_resolves(time_t now);
136 static void dns_found_answer(const char *address, uint8_t is_reverse,
137 uint32_t addr, const char *hostname, char outcome,
138 uint32_t ttl);
139 static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
140 static int launch_resolve(edge_connection_t *exitconn);
141 static void add_wildcarded_test_address(const char *address);
142 static int configure_nameservers(int force);
143 static int answer_is_wildcarded(const char *ip);
144 static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
145 or_circuit_t *oncirc, char **resolved_to_hostname);
146 #ifdef DEBUG_DNS_CACHE
147 static void _assert_cache_ok(void);
148 #define assert_cache_ok() _assert_cache_ok()
149 #else
150 #define assert_cache_ok() STMT_NIL
151 #endif
152 static void assert_resolve_ok(cached_resolve_t *resolve);
154 /** Hash table of cached_resolve objects. */
155 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
157 /** Function to compare hashed resolves on their addresses; used to
158 * implement hash tables. */
159 static INLINE int
160 cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
162 /* make this smarter one day? */
163 assert_resolve_ok(a); // Not b; b may be just a search.
164 return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
167 /** Hash function for cached_resolve objects */
168 static INLINE unsigned int
169 cached_resolve_hash(cached_resolve_t *a)
171 return ht_string_hash(a->address);
174 HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
175 cached_resolves_eq)
176 HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
177 cached_resolves_eq, 0.6, malloc, realloc, free)
179 /** Initialize the DNS cache. */
180 static void
181 init_cache_map(void)
183 HT_INIT(cache_map, &cache_root);
186 /** Helper: called by eventdns when eventdns wants to log something. */
187 static void
188 evdns_log_cb(int warn, const char *msg)
190 const char *cp;
191 static int all_down = 0;
192 int severity = warn ? LOG_WARN : LOG_INFO;
193 if (!strcmpstart(msg, "Resolve requested for") &&
194 get_options()->SafeLogging) {
195 log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
196 return;
197 } else if (!strcmpstart(msg, "Search: ")) {
198 return;
200 if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
201 char *ns = tor_strndup(msg+11, cp-(msg+11));
202 const char *err = strchr(cp, ':')+2;
203 tor_assert(err);
204 /* Don't warn about a single failed nameserver; we'll warn with 'all
205 * nameservers have failed' if we're completely out of nameservers;
206 * otherwise, the situation is tolerable. */
207 severity = LOG_INFO;
208 control_event_server_status(LOG_NOTICE,
209 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
210 ns, escaped(err));
211 tor_free(ns);
212 } else if (!strcmpstart(msg, "Nameserver ") &&
213 (cp=strstr(msg, " is back up"))) {
214 char *ns = tor_strndup(msg+11, cp-(msg+11));
215 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
216 all_down = 0;
217 control_event_server_status(LOG_NOTICE,
218 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
219 tor_free(ns);
220 } else if (!strcmp(msg, "All nameservers have failed")) {
221 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
222 all_down = 1;
224 log(severity, LD_EXIT, "eventdns: %s", msg);
227 /** Helper: passed to eventdns.c as a callback so it can generate random
228 * numbers for transaction IDs and 0x20-hack coding. */
229 static void
230 _dns_randfn(char *b, size_t n)
232 crypto_rand(b,n);
235 /** Initialize the DNS subsystem; called by the OR process. */
237 dns_init(void)
239 init_cache_map();
240 evdns_set_random_bytes_fn(_dns_randfn);
241 if (server_mode(get_options())) {
242 int r = configure_nameservers(1);
243 return r;
245 return 0;
248 /** Called when DNS-related options change (or may have changed). Returns -1
249 * on failure, 0 on success. */
251 dns_reset(void)
253 or_options_t *options = get_options();
254 if (! server_mode(options)) {
255 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
256 evdns_base_search_clear(the_evdns_base);
257 nameservers_configured = 0;
258 tor_free(resolv_conf_fname);
259 resolv_conf_mtime = 0;
260 } else {
261 if (configure_nameservers(0) < 0) {
262 return -1;
265 return 0;
268 /** Return true iff the most recent attempt to initialize the DNS subsystem
269 * failed. */
271 has_dns_init_failed(void)
273 return nameserver_config_failed;
276 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
277 * OP that asked us to resolve it. */
278 uint32_t
279 dns_clip_ttl(uint32_t ttl)
281 if (ttl < MIN_DNS_TTL)
282 return MIN_DNS_TTL;
283 else if (ttl > MAX_DNS_TTL)
284 return MAX_DNS_TTL;
285 else
286 return ttl;
289 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
290 * our cache. */
291 static uint32_t
292 dns_get_expiry_ttl(uint32_t ttl)
294 if (ttl < MIN_DNS_TTL)
295 return MIN_DNS_TTL;
296 else if (ttl > MAX_DNS_ENTRY_AGE)
297 return MAX_DNS_ENTRY_AGE;
298 else
299 return ttl;
302 /** Helper: free storage held by an entry in the DNS cache. */
303 static void
304 _free_cached_resolve(cached_resolve_t *r)
306 if (!r)
307 return;
308 while (r->pending_connections) {
309 pending_connection_t *victim = r->pending_connections;
310 r->pending_connections = victim->next;
311 tor_free(victim);
313 if (r->is_reverse)
314 tor_free(r->result.hostname);
315 r->magic = 0xFF00FF00;
316 tor_free(r);
319 /** Compare two cached_resolve_t pointers by expiry time, and return
320 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
321 * the priority queue implementation. */
322 static int
323 _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
325 const cached_resolve_t *a = _a, *b = _b;
326 if (a->expire < b->expire)
327 return -1;
328 else if (a->expire == b->expire)
329 return 0;
330 else
331 return 1;
334 /** Priority queue of cached_resolve_t objects to let us know when they
335 * will expire. */
336 static smartlist_t *cached_resolve_pqueue = NULL;
338 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
339 * priority queue */
340 static void
341 set_expiry(cached_resolve_t *resolve, time_t expires)
343 tor_assert(resolve && resolve->expire == 0);
344 if (!cached_resolve_pqueue)
345 cached_resolve_pqueue = smartlist_create();
346 resolve->expire = expires;
347 smartlist_pqueue_add(cached_resolve_pqueue,
348 _compare_cached_resolves_by_expiry,
349 STRUCT_OFFSET(cached_resolve_t, minheap_idx),
350 resolve);
353 /** Free all storage held in the DNS cache and related structures. */
354 void
355 dns_free_all(void)
357 cached_resolve_t **ptr, **next, *item;
358 assert_cache_ok();
359 if (cached_resolve_pqueue) {
360 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
362 if (res->state == CACHE_STATE_DONE)
363 _free_cached_resolve(res);
366 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
367 item = *ptr;
368 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
369 _free_cached_resolve(item);
371 HT_CLEAR(cache_map, &cache_root);
372 smartlist_free(cached_resolve_pqueue);
373 cached_resolve_pqueue = NULL;
374 tor_free(resolv_conf_fname);
377 /** Remove every cached_resolve whose <b>expire</b> time is before or
378 * equal to <b>now</b> from the cache. */
379 static void
380 purge_expired_resolves(time_t now)
382 cached_resolve_t *resolve, *removed;
383 pending_connection_t *pend;
384 edge_connection_t *pendconn;
386 assert_cache_ok();
387 if (!cached_resolve_pqueue)
388 return;
390 while (smartlist_len(cached_resolve_pqueue)) {
391 resolve = smartlist_get(cached_resolve_pqueue, 0);
392 if (resolve->expire > now)
393 break;
394 smartlist_pqueue_pop(cached_resolve_pqueue,
395 _compare_cached_resolves_by_expiry,
396 STRUCT_OFFSET(cached_resolve_t, minheap_idx));
398 if (resolve->state == CACHE_STATE_PENDING) {
399 log_debug(LD_EXIT,
400 "Expiring a dns resolve %s that's still pending. Forgot to "
401 "cull it? DNS resolve didn't tell us about the timeout?",
402 escaped_safe_str(resolve->address));
403 } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
404 resolve->state == CACHE_STATE_CACHED_FAILED) {
405 log_debug(LD_EXIT,
406 "Forgetting old cached resolve (address %s, expires %lu)",
407 escaped_safe_str(resolve->address),
408 (unsigned long)resolve->expire);
409 tor_assert(!resolve->pending_connections);
410 } else {
411 tor_assert(resolve->state == CACHE_STATE_DONE);
412 tor_assert(!resolve->pending_connections);
415 if (resolve->pending_connections) {
416 log_debug(LD_EXIT,
417 "Closing pending connections on timed-out DNS resolve!");
418 tor_fragile_assert();
419 while (resolve->pending_connections) {
420 pend = resolve->pending_connections;
421 resolve->pending_connections = pend->next;
422 /* Connections should only be pending if they have no socket. */
423 tor_assert(pend->conn->_base.s == -1);
424 pendconn = pend->conn;
425 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
426 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
427 connection_free(TO_CONN(pendconn));
428 tor_free(pend);
432 if (resolve->state == CACHE_STATE_CACHED_VALID ||
433 resolve->state == CACHE_STATE_CACHED_FAILED ||
434 resolve->state == CACHE_STATE_PENDING) {
435 removed = HT_REMOVE(cache_map, &cache_root, resolve);
436 if (removed != resolve) {
437 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
438 " the cache. Tried to purge %s (%p); instead got %s (%p).",
439 resolve->address, (void*)resolve,
440 removed ? removed->address : "NULL", (void*)remove);
442 tor_assert(removed == resolve);
443 } else {
444 /* This should be in state DONE. Make sure it's not in the cache. */
445 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
446 tor_assert(tmp != resolve);
448 if (resolve->is_reverse)
449 tor_free(resolve->result.hostname);
450 resolve->magic = 0xF0BBF0BB;
451 tor_free(resolve);
454 assert_cache_ok();
457 /** Send a response to the RESOLVE request of a connection.
458 * <b>answer_type</b> must be one of
459 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
461 * If <b>circ</b> is provided, and we have a cached answer, send the
462 * answer back along circ; otherwise, send the answer back along
463 * <b>conn</b>'s attached circuit.
465 static void
466 send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
468 char buf[RELAY_PAYLOAD_SIZE];
469 size_t buflen;
470 uint32_t ttl;
472 buf[0] = answer_type;
473 ttl = dns_clip_ttl(conn->address_ttl);
475 switch (answer_type)
477 case RESOLVED_TYPE_IPV4:
478 buf[1] = 4;
479 set_uint32(buf+2, tor_addr_to_ipv4n(&conn->_base.addr));
480 set_uint32(buf+6, htonl(ttl));
481 buflen = 10;
482 break;
483 /*XXXX IP6 need ipv6 implementation */
484 case RESOLVED_TYPE_ERROR_TRANSIENT:
485 case RESOLVED_TYPE_ERROR:
487 const char *errmsg = "Error resolving hostname";
488 size_t msglen = strlen(errmsg);
490 buf[1] = msglen;
491 strlcpy(buf+2, errmsg, sizeof(buf)-2);
492 set_uint32(buf+2+msglen, htonl(ttl));
493 buflen = 6+msglen;
494 break;
496 default:
497 tor_assert(0);
498 return;
500 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
502 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
505 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
506 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
507 * The answer type will be RESOLVED_HOSTNAME.
509 * If <b>circ</b> is provided, and we have a cached answer, send the
510 * answer back along circ; otherwise, send the answer back along
511 * <b>conn</b>'s attached circuit.
513 static void
514 send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
516 char buf[RELAY_PAYLOAD_SIZE];
517 size_t buflen;
518 uint32_t ttl;
519 size_t namelen = strlen(hostname);
520 tor_assert(hostname);
522 tor_assert(namelen < 256);
523 ttl = dns_clip_ttl(conn->address_ttl);
525 buf[0] = RESOLVED_TYPE_HOSTNAME;
526 buf[1] = (uint8_t)namelen;
527 memcpy(buf+2, hostname, namelen);
528 set_uint32(buf+2+namelen, htonl(ttl));
529 buflen = 2+namelen+4;
531 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
532 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
533 // log_notice(LD_EXIT, "Sent");
536 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
537 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
538 * If resolve failed, free exitconn and return -1.
540 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
541 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
542 * need to send back an END cell, since connection_exit_begin_conn will
543 * do that for us.)
545 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
546 * circuit.
548 * Else, if seen before and pending, add conn to the pending list,
549 * and return 0.
551 * Else, if not seen before, add conn to pending list, hand to
552 * dns farm, and return 0.
554 * Exitconn's on_circuit field must be set, but exitconn should not
555 * yet be linked onto the n_streams/resolving_streams list of that circuit.
556 * On success, link the connection to n_streams if it's an exit connection.
557 * On "pending", link the connection to resolving streams. Otherwise,
558 * clear its on_circuit field.
561 dns_resolve(edge_connection_t *exitconn)
563 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
564 int is_resolve, r;
565 char *hostname = NULL;
566 is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
568 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
570 switch (r) {
571 case 1:
572 /* We got an answer without a lookup -- either the answer was
573 * cached, or it was obvious (like an IP address). */
574 if (is_resolve) {
575 /* Send the answer back right now, and detach. */
576 if (hostname)
577 send_resolved_hostname_cell(exitconn, hostname);
578 else
579 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
580 exitconn->on_circuit = NULL;
581 } else {
582 /* Add to the n_streams list; the calling function will send back a
583 * connected cell. */
584 exitconn->next_stream = oncirc->n_streams;
585 oncirc->n_streams = exitconn;
587 break;
588 case 0:
589 /* The request is pending: add the connection into the linked list of
590 * resolving_streams on this circuit. */
591 exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
592 exitconn->next_stream = oncirc->resolving_streams;
593 oncirc->resolving_streams = exitconn;
594 break;
595 case -2:
596 case -1:
597 /* The request failed before it could start: cancel this connection,
598 * and stop everybody waiting for the same connection. */
599 if (is_resolve) {
600 send_resolved_cell(exitconn,
601 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
604 exitconn->on_circuit = NULL;
606 dns_cancel_pending_resolve(exitconn->_base.address);
608 if (!exitconn->_base.marked_for_close) {
609 connection_free(TO_CONN(exitconn));
610 // XXX ... and we just leak exitconn otherwise? -RD
611 // If it's marked for close, it's on closeable_connection_lst in
612 // main.c. If it's on the closeable list, it will get freed from
613 // main.c. -NM
614 // "<armadev> If that's true, there are other bugs around, where we
615 // don't check if it's marked, and will end up double-freeing."
616 // On the other hand, I don't know of any actual bugs here, so this
617 // shouldn't be holding up the rc. -RD
619 break;
620 default:
621 tor_assert(0);
624 tor_free(hostname);
625 return r;
628 /** Helper function for dns_resolve: same functionality, but does not handle:
629 * - marking connections on error and clearing their on_circuit
630 * - linking connections to n_streams/resolving_streams,
631 * - sending resolved cells if we have an answer/error right away,
633 * Return -2 on a transient error. If it's a reverse resolve and it's
634 * successful, sets *<b>hostname_out</b> to a newly allocated string
635 * holding the cached reverse DNS value.
637 static int
638 dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
639 or_circuit_t *oncirc, char **hostname_out)
641 cached_resolve_t *resolve;
642 cached_resolve_t search;
643 pending_connection_t *pending_connection;
644 routerinfo_t *me;
645 tor_addr_t addr;
646 time_t now = time(NULL);
647 uint8_t is_reverse = 0;
648 int r;
649 assert_connection_ok(TO_CONN(exitconn), 0);
650 tor_assert(exitconn->_base.s == -1);
651 assert_cache_ok();
652 tor_assert(oncirc);
654 /* first check if exitconn->_base.address is an IP. If so, we already
655 * know the answer. */
656 if (tor_addr_from_str(&addr, exitconn->_base.address) >= 0) {
657 if (tor_addr_family(&addr) == AF_INET) {
658 tor_addr_assign(&exitconn->_base.addr, &addr);
659 exitconn->address_ttl = DEFAULT_DNS_TTL;
660 return 1;
661 } else {
662 /* XXXX IPv6 */
663 return -1;
667 /* If we're a non-exit, don't even do DNS lookups. */
668 if (!(me = router_get_my_routerinfo()) ||
669 policy_is_reject_star(me->exit_policy)) {
670 return -1;
672 if (address_is_invalid_destination(exitconn->_base.address, 0)) {
673 log(LOG_PROTOCOL_WARN, LD_EXIT,
674 "Rejecting invalid destination address %s",
675 escaped_safe_str(exitconn->_base.address));
676 return -1;
679 /* then take this opportunity to see if there are any expired
680 * resolves in the hash table. */
681 purge_expired_resolves(now);
683 /* lower-case exitconn->_base.address, so it's in canonical form */
684 tor_strlower(exitconn->_base.address);
686 /* Check whether this is a reverse lookup. If it's malformed, or it's a
687 * .in-addr.arpa address but this isn't a resolve request, kill the
688 * connection.
690 if ((r = tor_addr_parse_reverse_lookup_name(&addr, exitconn->_base.address,
691 AF_UNSPEC, 0)) != 0) {
692 if (r == 1) {
693 is_reverse = 1;
694 if (tor_addr_is_internal(&addr, 0)) /* internal address? */
695 return -1;
698 if (!is_reverse || !is_resolve) {
699 if (!is_reverse)
700 log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
701 escaped_safe_str(exitconn->_base.address));
702 else if (!is_resolve)
703 log_info(LD_EXIT,
704 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
705 "sending error.",
706 escaped_safe_str(exitconn->_base.address));
708 return -1;
710 //log_notice(LD_EXIT, "Looks like an address %s",
711 //exitconn->_base.address);
714 /* now check the hash table to see if 'address' is already there. */
715 strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
716 resolve = HT_FIND(cache_map, &cache_root, &search);
717 if (resolve && resolve->expire > now) { /* already there */
718 switch (resolve->state) {
719 case CACHE_STATE_PENDING:
720 /* add us to the pending list */
721 pending_connection = tor_malloc_zero(
722 sizeof(pending_connection_t));
723 pending_connection->conn = exitconn;
724 pending_connection->next = resolve->pending_connections;
725 resolve->pending_connections = pending_connection;
726 log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
727 "resolve of %s", exitconn->_base.s,
728 escaped_safe_str(exitconn->_base.address));
729 return 0;
730 case CACHE_STATE_CACHED_VALID:
731 log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
732 exitconn->_base.s,
733 escaped_safe_str(resolve->address));
734 exitconn->address_ttl = resolve->ttl;
735 if (resolve->is_reverse) {
736 tor_assert(is_resolve);
737 *hostname_out = tor_strdup(resolve->result.hostname);
738 } else {
739 tor_addr_from_ipv4h(&exitconn->_base.addr, resolve->result.a.addr);
741 return 1;
742 case CACHE_STATE_CACHED_FAILED:
743 log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
744 exitconn->_base.s,
745 escaped_safe_str(exitconn->_base.address));
746 return -1;
747 case CACHE_STATE_DONE:
748 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
749 tor_fragile_assert();
751 tor_assert(0);
753 tor_assert(!resolve);
754 /* not there, need to add it */
755 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
756 resolve->magic = CACHED_RESOLVE_MAGIC;
757 resolve->state = CACHE_STATE_PENDING;
758 resolve->minheap_idx = -1;
759 resolve->is_reverse = is_reverse;
760 strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
762 /* add this connection to the pending list */
763 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
764 pending_connection->conn = exitconn;
765 resolve->pending_connections = pending_connection;
767 /* Add this resolve to the cache and priority queue. */
768 HT_INSERT(cache_map, &cache_root, resolve);
769 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
771 log_debug(LD_EXIT,"Launching %s.",
772 escaped_safe_str(exitconn->_base.address));
773 assert_cache_ok();
775 return launch_resolve(exitconn);
778 /** Log an error and abort if conn is waiting for a DNS resolve.
780 void
781 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
783 pending_connection_t *pend;
784 cached_resolve_t search;
786 #if 1
787 cached_resolve_t *resolve;
788 strlcpy(search.address, conn->_base.address, sizeof(search.address));
789 resolve = HT_FIND(cache_map, &cache_root, &search);
790 if (!resolve)
791 return;
792 for (pend = resolve->pending_connections; pend; pend = pend->next) {
793 tor_assert(pend->conn != conn);
795 #else
796 cached_resolve_t **resolve;
797 HT_FOREACH(resolve, cache_map, &cache_root) {
798 for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
799 tor_assert(pend->conn != conn);
802 #endif
805 /** Log an error and abort if any connection waiting for a DNS resolve is
806 * corrupted. */
807 void
808 assert_all_pending_dns_resolves_ok(void)
810 pending_connection_t *pend;
811 cached_resolve_t **resolve;
813 HT_FOREACH(resolve, cache_map, &cache_root) {
814 for (pend = (*resolve)->pending_connections;
815 pend;
816 pend = pend->next) {
817 assert_connection_ok(TO_CONN(pend->conn), 0);
818 tor_assert(pend->conn->_base.s == -1);
819 tor_assert(!connection_in_array(TO_CONN(pend->conn)));
824 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
826 void
827 connection_dns_remove(edge_connection_t *conn)
829 pending_connection_t *pend, *victim;
830 cached_resolve_t search;
831 cached_resolve_t *resolve;
833 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
834 tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
836 strlcpy(search.address, conn->_base.address, sizeof(search.address));
838 resolve = HT_FIND(cache_map, &cache_root, &search);
839 if (!resolve) {
840 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
841 escaped_safe_str(conn->_base.address));
842 return;
845 tor_assert(resolve->pending_connections);
846 assert_connection_ok(TO_CONN(conn),0);
848 pend = resolve->pending_connections;
850 if (pend->conn == conn) {
851 resolve->pending_connections = pend->next;
852 tor_free(pend);
853 log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
854 "for resolve of %s",
855 conn->_base.s, escaped_safe_str(conn->_base.address));
856 return;
857 } else {
858 for ( ; pend->next; pend = pend->next) {
859 if (pend->next->conn == conn) {
860 victim = pend->next;
861 pend->next = victim->next;
862 tor_free(victim);
863 log_debug(LD_EXIT,
864 "Connection (fd %d) no longer waiting for resolve of %s",
865 conn->_base.s, escaped_safe_str(conn->_base.address));
866 return; /* more are pending */
869 tor_assert(0); /* not reachable unless onlyconn not in pending list */
873 /** Mark all connections waiting for <b>address</b> for close. Then cancel
874 * the resolve for <b>address</b> itself, and remove any cached results for
875 * <b>address</b> from the cache.
877 void
878 dns_cancel_pending_resolve(const char *address)
880 pending_connection_t *pend;
881 cached_resolve_t search;
882 cached_resolve_t *resolve, *tmp;
883 edge_connection_t *pendconn;
884 circuit_t *circ;
886 strlcpy(search.address, address, sizeof(search.address));
888 resolve = HT_FIND(cache_map, &cache_root, &search);
889 if (!resolve)
890 return;
892 if (resolve->state != CACHE_STATE_PENDING) {
893 /* We can get into this state if we never actually created the pending
894 * resolve, due to finding an earlier cached error or something. Just
895 * ignore it. */
896 if (resolve->pending_connections) {
897 log_warn(LD_BUG,
898 "Address %s is not pending but has pending connections!",
899 escaped_safe_str(address));
900 tor_fragile_assert();
902 return;
905 if (!resolve->pending_connections) {
906 log_warn(LD_BUG,
907 "Address %s is pending but has no pending connections!",
908 escaped_safe_str(address));
909 tor_fragile_assert();
910 return;
912 tor_assert(resolve->pending_connections);
914 /* mark all pending connections to fail */
915 log_debug(LD_EXIT,
916 "Failing all connections waiting on DNS resolve of %s",
917 escaped_safe_str(address));
918 while (resolve->pending_connections) {
919 pend = resolve->pending_connections;
920 pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
921 pendconn = pend->conn;
922 assert_connection_ok(TO_CONN(pendconn), 0);
923 tor_assert(pendconn->_base.s == -1);
924 if (!pendconn->_base.marked_for_close) {
925 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
927 circ = circuit_get_by_edge_conn(pendconn);
928 if (circ)
929 circuit_detach_stream(circ, pendconn);
930 if (!pendconn->_base.marked_for_close)
931 connection_free(TO_CONN(pendconn));
932 resolve->pending_connections = pend->next;
933 tor_free(pend);
936 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
937 if (tmp != resolve) {
938 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
939 " the cache. Tried to purge %s (%p); instead got %s (%p).",
940 resolve->address, (void*)resolve,
941 tmp ? tmp->address : "NULL", (void*)tmp);
943 tor_assert(tmp == resolve);
945 resolve->state = CACHE_STATE_DONE;
948 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
949 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
950 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
951 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
953 static void
954 add_answer_to_cache(const char *address, uint8_t is_reverse, uint32_t addr,
955 const char *hostname, char outcome, uint32_t ttl)
957 cached_resolve_t *resolve;
958 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
959 return;
961 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
962 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
963 // hostname?hostname:"NULL",(int)outcome);
965 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
966 resolve->magic = CACHED_RESOLVE_MAGIC;
967 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
968 CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
969 strlcpy(resolve->address, address, sizeof(resolve->address));
970 resolve->is_reverse = is_reverse;
971 if (is_reverse) {
972 if (outcome == DNS_RESOLVE_SUCCEEDED) {
973 tor_assert(hostname);
974 resolve->result.hostname = tor_strdup(hostname);
975 } else {
976 tor_assert(! hostname);
977 resolve->result.hostname = NULL;
979 } else {
980 tor_assert(!hostname);
981 resolve->result.a.addr = addr;
983 resolve->ttl = ttl;
984 assert_resolve_ok(resolve);
985 HT_INSERT(cache_map, &cache_root, resolve);
986 set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
989 /** Return true iff <b>address</b> is one of the addresses we use to verify
990 * that well-known sites aren't being hijacked by our DNS servers. */
991 static INLINE int
992 is_test_address(const char *address)
994 or_options_t *options = get_options();
995 return options->ServerDNSTestAddresses &&
996 smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
999 /** Called on the OR side when a DNS worker or the eventdns library tells us
1000 * the outcome of a DNS resolve: tell all pending connections about the result
1001 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
1002 * string containing the address to look up; <b>addr</b> is an IPv4 address in
1003 * host order; <b>outcome</b> is one of
1004 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
1006 static void
1007 dns_found_answer(const char *address, uint8_t is_reverse, uint32_t addr,
1008 const char *hostname, char outcome, uint32_t ttl)
1010 pending_connection_t *pend;
1011 cached_resolve_t search;
1012 cached_resolve_t *resolve, *removed;
1013 edge_connection_t *pendconn;
1014 circuit_t *circ;
1016 assert_cache_ok();
1018 strlcpy(search.address, address, sizeof(search.address));
1020 resolve = HT_FIND(cache_map, &cache_root, &search);
1021 if (!resolve) {
1022 int is_test_addr = is_test_address(address);
1023 if (!is_test_addr)
1024 log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
1025 escaped_safe_str(address));
1026 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
1027 return;
1029 assert_resolve_ok(resolve);
1031 if (resolve->state != CACHE_STATE_PENDING) {
1032 /* XXXX Maybe update addr? or check addr for consistency? Or let
1033 * VALID replace FAILED? */
1034 int is_test_addr = is_test_address(address);
1035 if (!is_test_addr)
1036 log_notice(LD_EXIT,
1037 "Resolved %s which was already resolved; ignoring",
1038 escaped_safe_str(address));
1039 tor_assert(resolve->pending_connections == NULL);
1040 return;
1042 /* Removed this assertion: in fact, we'll sometimes get a double answer
1043 * to the same question. This can happen when we ask one worker to resolve
1044 * X.Y.Z., then we cancel the request, and then we ask another worker to
1045 * resolve X.Y.Z. */
1046 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
1048 while (resolve->pending_connections) {
1049 pend = resolve->pending_connections;
1050 pendconn = pend->conn; /* don't pass complex things to the
1051 connection_mark_for_close macro */
1052 assert_connection_ok(TO_CONN(pendconn),time(NULL));
1053 tor_addr_from_ipv4h(&pendconn->_base.addr, addr);
1054 pendconn->address_ttl = ttl;
1056 if (outcome != DNS_RESOLVE_SUCCEEDED) {
1057 /* prevent double-remove. */
1058 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1059 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1060 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1061 /* This detach must happen after we send the end cell. */
1062 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1063 } else {
1064 send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
1065 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
1066 /* This detach must happen after we send the resolved cell. */
1067 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1069 connection_free(TO_CONN(pendconn));
1070 } else {
1071 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1072 tor_assert(!is_reverse);
1073 /* prevent double-remove. */
1074 pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
1076 circ = circuit_get_by_edge_conn(pend->conn);
1077 tor_assert(circ);
1078 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1079 /* unlink pend->conn from resolving_streams, */
1080 circuit_detach_stream(circ, pend->conn);
1081 /* and link it to n_streams */
1082 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1083 pend->conn->on_circuit = circ;
1084 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1086 connection_exit_connect(pend->conn);
1087 } else {
1088 /* prevent double-remove. This isn't really an accurate state,
1089 * but it does the right thing. */
1090 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1091 if (is_reverse)
1092 send_resolved_hostname_cell(pendconn, hostname);
1093 else
1094 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
1095 circ = circuit_get_by_edge_conn(pendconn);
1096 tor_assert(circ);
1097 circuit_detach_stream(circ, pendconn);
1098 connection_free(TO_CONN(pendconn));
1101 resolve->pending_connections = pend->next;
1102 tor_free(pend);
1105 resolve->state = CACHE_STATE_DONE;
1106 removed = HT_REMOVE(cache_map, &cache_root, &search);
1107 if (removed != resolve) {
1108 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1109 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1110 resolve->address, (void*)resolve,
1111 removed ? removed->address : "NULL", (void*)removed);
1113 assert_resolve_ok(resolve);
1114 assert_cache_ok();
1116 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
1117 assert_cache_ok();
1120 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1121 * a transient failure. */
1122 static int
1123 evdns_err_is_transient(int err)
1125 switch (err)
1127 case DNS_ERR_SERVERFAILED:
1128 case DNS_ERR_TRUNCATED:
1129 case DNS_ERR_TIMEOUT:
1130 return 1;
1131 default:
1132 return 0;
1136 /** Configure eventdns nameservers if force is true, or if the configuration
1137 * has changed since the last time we called this function, or if we failed on
1138 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1139 * options->ServerDNSResolvConfFile; on Windows, this reads from
1140 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1141 * -1 on failure. */
1142 static int
1143 configure_nameservers(int force)
1145 or_options_t *options;
1146 const char *conf_fname;
1147 struct stat st;
1148 int r;
1149 options = get_options();
1150 conf_fname = options->ServerDNSResolvConfFile;
1151 #ifndef MS_WINDOWS
1152 if (!conf_fname)
1153 conf_fname = "/etc/resolv.conf";
1154 #endif
1156 if (!the_evdns_base) {
1157 if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
1158 log_err(LD_BUG, "Couldn't create an evdns_base");
1159 return -1;
1163 #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
1164 if (options->OutboundBindAddress) {
1165 tor_addr_t addr;
1166 if (tor_addr_from_str(&addr, options->OutboundBindAddress) < 0) {
1167 log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
1168 options->OutboundBindAddress);
1169 } else {
1170 int socklen;
1171 struct sockaddr_storage ss;
1172 socklen = tor_addr_to_sockaddr(&addr, 0,
1173 (struct sockaddr *)&ss, sizeof(ss));
1174 if (socklen < 0) {
1175 log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
1176 " Ignoring.");
1177 } else {
1178 evdns_base_set_default_outgoing_bind_address(the_evdns_base,
1179 (struct sockaddr *)&ss,
1180 socklen);
1184 #endif
1186 evdns_set_log_fn(evdns_log_cb);
1187 if (conf_fname) {
1188 if (stat(conf_fname, &st)) {
1189 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1190 conf_fname, strerror(errno));
1191 goto err;
1193 if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
1194 && st.st_mtime == resolv_conf_mtime) {
1195 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1196 return 0;
1198 if (nameservers_configured) {
1199 evdns_base_search_clear(the_evdns_base);
1200 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1202 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1203 if ((r = evdns_base_resolv_conf_parse(the_evdns_base,
1204 DNS_OPTIONS_ALL, conf_fname))) {
1205 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1206 conf_fname, conf_fname, r);
1207 goto err;
1209 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1210 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
1211 goto err;
1213 tor_free(resolv_conf_fname);
1214 resolv_conf_fname = tor_strdup(conf_fname);
1215 resolv_conf_mtime = st.st_mtime;
1216 if (nameservers_configured)
1217 evdns_base_resume(the_evdns_base);
1219 #ifdef MS_WINDOWS
1220 else {
1221 if (nameservers_configured) {
1222 evdns_base_search_clear(the_evdns_base);
1223 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1225 if (evdns_base_config_windows_nameservers(the_evdns_base)) {
1226 log_warn(LD_EXIT,"Could not config nameservers.");
1227 goto err;
1229 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1230 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1231 "your Windows configuration.");
1232 goto err;
1234 if (nameservers_configured)
1235 evdns_base_resume(the_evdns_base);
1236 tor_free(resolv_conf_fname);
1237 resolv_conf_mtime = 0;
1239 #endif
1241 #define SET(k,v) \
1242 evdns_base_set_option(the_evdns_base, (k), (v), DNS_OPTIONS_ALL)
1244 if (evdns_base_count_nameservers(the_evdns_base) == 1) {
1245 SET("max-timeouts:", "16");
1246 SET("timeout:", "10");
1247 } else {
1248 SET("max-timeouts:", "3");
1249 SET("timeout:", "5");
1252 if (options->ServerDNSRandomizeCase)
1253 SET("randomize-case:", "1");
1254 else
1255 SET("randomize-case:", "0");
1257 #undef SET
1259 dns_servers_relaunch_checks();
1261 nameservers_configured = 1;
1262 if (nameserver_config_failed) {
1263 nameserver_config_failed = 0;
1264 mark_my_descriptor_dirty();
1266 return 0;
1267 err:
1268 nameservers_configured = 0;
1269 if (! nameserver_config_failed) {
1270 nameserver_config_failed = 1;
1271 mark_my_descriptor_dirty();
1273 return -1;
1276 /** For eventdns: Called when we get an answer for a request we launched.
1277 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1279 static void
1280 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1281 void *arg)
1283 char *string_address = arg;
1284 uint8_t is_reverse = 0;
1285 int status = DNS_RESOLVE_FAILED_PERMANENT;
1286 uint32_t addr = 0;
1287 const char *hostname = NULL;
1288 int was_wildcarded = 0;
1290 if (result == DNS_ERR_NONE) {
1291 if (type == DNS_IPv4_A && count) {
1292 char answer_buf[INET_NTOA_BUF_LEN+1];
1293 struct in_addr in;
1294 char *escaped_address;
1295 uint32_t *addrs = addresses;
1296 in.s_addr = addrs[0];
1297 addr = ntohl(addrs[0]);
1298 status = DNS_RESOLVE_SUCCEEDED;
1299 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1300 escaped_address = esc_for_log(string_address);
1302 if (answer_is_wildcarded(answer_buf)) {
1303 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1304 "address %s; treating as a failure.",
1305 safe_str(escaped_address),
1306 escaped_safe_str(answer_buf));
1307 was_wildcarded = 1;
1308 addr = 0;
1309 status = DNS_RESOLVE_FAILED_PERMANENT;
1310 } else {
1311 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1312 safe_str(escaped_address),
1313 escaped_safe_str(answer_buf));
1315 tor_free(escaped_address);
1316 } else if (type == DNS_PTR && count) {
1317 char *escaped_address;
1318 is_reverse = 1;
1319 hostname = ((char**)addresses)[0];
1320 status = DNS_RESOLVE_SUCCEEDED;
1321 escaped_address = esc_for_log(string_address);
1322 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1323 safe_str(escaped_address),
1324 escaped_safe_str(hostname));
1325 tor_free(escaped_address);
1326 } else if (count) {
1327 log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
1328 escaped_safe_str(string_address));
1329 } else {
1330 log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
1331 escaped_safe_str(string_address));
1333 } else {
1334 if (evdns_err_is_transient(result))
1335 status = DNS_RESOLVE_FAILED_TRANSIENT;
1337 if (was_wildcarded) {
1338 if (is_test_address(string_address)) {
1339 /* Ick. We're getting redirected on known-good addresses. Our DNS
1340 * server must really hate us. */
1341 add_wildcarded_test_address(string_address);
1344 if (result != DNS_ERR_SHUTDOWN)
1345 dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
1346 tor_free(string_address);
1349 /** For eventdns: start resolving as necessary to find the target for
1350 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1351 * 0 on "resolve launched." */
1352 static int
1353 launch_resolve(edge_connection_t *exitconn)
1355 char *addr = tor_strdup(exitconn->_base.address);
1356 struct evdns_request *req = NULL;
1357 tor_addr_t a;
1358 int r;
1359 int options = get_options()->ServerDNSSearchDomains ? 0
1360 : DNS_QUERY_NO_SEARCH;
1361 /* What? Nameservers not configured? Sounds like a bug. */
1362 if (!nameservers_configured) {
1363 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1364 "launched. Configuring.");
1365 if (configure_nameservers(1) < 0) {
1366 return -1;
1370 r = tor_addr_parse_reverse_lookup_name(
1371 &a, exitconn->_base.address, AF_UNSPEC, 0);
1372 if (r == 0) {
1373 log_info(LD_EXIT, "Launching eventdns request for %s",
1374 escaped_safe_str(exitconn->_base.address));
1375 req = evdns_base_resolve_ipv4(the_evdns_base,
1376 exitconn->_base.address, options,
1377 evdns_callback, addr);
1378 } else if (r == 1) {
1379 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1380 escaped_safe_str(exitconn->_base.address));
1381 if (tor_addr_family(&a) == AF_INET)
1382 req = evdns_base_resolve_reverse(the_evdns_base,
1383 tor_addr_to_in(&a), DNS_QUERY_NO_SEARCH,
1384 evdns_callback, addr);
1385 else
1386 req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
1387 tor_addr_to_in6(&a), DNS_QUERY_NO_SEARCH,
1388 evdns_callback, addr);
1389 } else if (r == -1) {
1390 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1393 r = 0;
1394 if (!req) {
1395 log_warn(LD_EXIT, "eventdns rejected address %s.", escaped_safe_str(addr));
1396 r = -1;
1397 tor_free(addr); /* There is no evdns request in progress; stop
1398 * addr from getting leaked. */
1400 return r;
1403 /** How many requests for bogus addresses have we launched so far? */
1404 static int n_wildcard_requests = 0;
1406 /** Map from dotted-quad IP address in response to an int holding how many
1407 * times we've seen it for a randomly generated (hopefully bogus) address. It
1408 * would be easier to use definitely-invalid addresses (as specified by
1409 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1410 static strmap_t *dns_wildcard_response_count = NULL;
1412 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1413 * nameserver wants to return in response to requests for nonexistent domains.
1415 static smartlist_t *dns_wildcard_list = NULL;
1416 /** True iff we've logged about a single address getting wildcarded.
1417 * Subsequent warnings will be less severe. */
1418 static int dns_wildcard_one_notice_given = 0;
1419 /** True iff we've warned that our DNS server is wildcarding too many failures.
1421 static int dns_wildcard_notice_given = 0;
1423 /** List of supposedly good addresses that are getting wildcarded to the
1424 * same addresses as nonexistent addresses. */
1425 static smartlist_t *dns_wildcarded_test_address_list = NULL;
1426 /** True iff we've warned about a test address getting wildcarded */
1427 static int dns_wildcarded_test_address_notice_given = 0;
1428 /** True iff all addresses seem to be getting wildcarded. */
1429 static int dns_is_completely_invalid = 0;
1431 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1432 * a hopefully bogus address. */
1433 static void
1434 wildcard_increment_answer(const char *id)
1436 int *ip;
1437 if (!dns_wildcard_response_count)
1438 dns_wildcard_response_count = strmap_new();
1440 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1441 if (!ip) {
1442 ip = tor_malloc_zero(sizeof(int));
1443 strmap_set(dns_wildcard_response_count, id, ip);
1445 ++*ip;
1447 if (*ip > 5 && n_wildcard_requests > 10) {
1448 if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
1449 if (!smartlist_string_isin(dns_wildcard_list, id)) {
1450 log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1451 "Your DNS provider has given \"%s\" as an answer for %d different "
1452 "invalid addresses. Apparently they are hijacking DNS failures. "
1453 "I'll try to correct for this by treating future occurrences of "
1454 "\"%s\" as 'not found'.", id, *ip, id);
1455 smartlist_add(dns_wildcard_list, tor_strdup(id));
1457 if (!dns_wildcard_notice_given)
1458 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1459 dns_wildcard_notice_given = 1;
1463 /** Note that a single test address (one believed to be good) seems to be
1464 * getting redirected to the same IP as failures are. */
1465 static void
1466 add_wildcarded_test_address(const char *address)
1468 int n, n_test_addrs;
1469 if (!dns_wildcarded_test_address_list)
1470 dns_wildcarded_test_address_list = smartlist_create();
1472 if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
1473 return;
1475 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1476 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1478 smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
1479 n = smartlist_len(dns_wildcarded_test_address_list);
1480 if (n > n_test_addrs/2) {
1481 log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
1482 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1483 "address. It has done this with %d test addresses so far. I'm "
1484 "going to stop being an exit node for now, since our DNS seems so "
1485 "broken.", address, n);
1486 if (!dns_is_completely_invalid) {
1487 dns_is_completely_invalid = 1;
1488 mark_my_descriptor_dirty();
1490 if (!dns_wildcarded_test_address_notice_given)
1491 control_event_server_status(LOG_WARN, "DNS_USELESS");
1492 dns_wildcarded_test_address_notice_given = 1;
1496 /** Callback function when we get an answer (possibly failing) for a request
1497 * for a (hopefully) nonexistent domain. */
1498 static void
1499 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1500 void *addresses, void *arg)
1502 (void)ttl;
1503 ++n_wildcard_requests;
1504 if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
1505 uint32_t *addrs = addresses;
1506 int i;
1507 char *string_address = arg;
1508 for (i = 0; i < count; ++i) {
1509 char answer_buf[INET_NTOA_BUF_LEN+1];
1510 struct in_addr in;
1511 in.s_addr = addrs[i];
1512 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1513 wildcard_increment_answer(answer_buf);
1515 log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1516 "Your DNS provider gave an answer for \"%s\", which "
1517 "is not supposed to exist. Apparently they are hijacking "
1518 "DNS failures. Trying to correct for this. We've noticed %d "
1519 "possibly bad address%s so far.",
1520 string_address, strmap_size(dns_wildcard_response_count),
1521 (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
1522 dns_wildcard_one_notice_given = 1;
1524 tor_free(arg);
1527 /** Launch a single request for a nonexistent hostname consisting of between
1528 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1529 * <b>suffix</b> */
1530 static void
1531 launch_wildcard_check(int min_len, int max_len, const char *suffix)
1533 char *addr;
1534 struct evdns_request *req;
1536 addr = crypto_random_hostname(min_len, max_len, "", suffix);
1537 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1538 "domains with request for bogus hostname \"%s\"", addr);
1540 req = evdns_base_resolve_ipv4(
1541 the_evdns_base,
1542 /* This "addr" tells us which address to resolve */
1543 addr,
1544 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1545 /* This "addr" is an argument to the callback*/ addr);
1546 if (!req) {
1547 /* There is no evdns request in progress; stop addr from getting leaked */
1548 tor_free(addr);
1552 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1553 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1554 static void
1555 launch_test_addresses(int fd, short event, void *args)
1557 or_options_t *options = get_options();
1558 struct evdns_request *req;
1559 (void)fd;
1560 (void)event;
1561 (void)args;
1563 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1564 "hijack *everything*.");
1565 /* This situation is worse than the failure-hijacking situation. When this
1566 * happens, we're no good for DNS requests at all, and we shouldn't really
1567 * be an exit server.*/
1568 if (!options->ServerDNSTestAddresses)
1569 return;
1570 SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
1571 const char *, address) {
1572 char *a = tor_strdup(address);
1573 req = evdns_base_resolve_ipv4(the_evdns_base,
1574 address, DNS_QUERY_NO_SEARCH, evdns_callback, a);
1576 if (!req) {
1577 log_info(LD_EXIT, "eventdns rejected test address %s",
1578 escaped_safe_str(address));
1579 tor_free(a);
1581 } SMARTLIST_FOREACH_END(address);
1584 #define N_WILDCARD_CHECKS 2
1586 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1587 * hostnames, and see if we can catch our nameserver trying to hijack them and
1588 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1589 * buy these lovely encyclopedias" page. */
1590 static void
1591 dns_launch_wildcard_checks(void)
1593 int i;
1594 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
1595 "to hijack DNS failures.");
1596 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
1597 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1598 * to 'comply' with rfc2606, refrain from giving A records for these.
1599 * This is the standards-compliance equivalent of making sure that your
1600 * crackhouse's elevator inspection certificate is up to date.
1602 launch_wildcard_check(2, 16, ".invalid");
1603 launch_wildcard_check(2, 16, ".test");
1605 /* These will break specs if there are ever any number of
1606 * 8+-character top-level domains. */
1607 launch_wildcard_check(8, 16, "");
1609 /* Try some random .com/org/net domains. This will work fine so long as
1610 * not too many resolve to the same place. */
1611 launch_wildcard_check(8, 16, ".com");
1612 launch_wildcard_check(8, 16, ".org");
1613 launch_wildcard_check(8, 16, ".net");
1617 /** If appropriate, start testing whether our DNS servers tend to lie to
1618 * us. */
1619 void
1620 dns_launch_correctness_checks(void)
1622 static struct event *launch_event = NULL;
1623 struct timeval timeout;
1624 if (!get_options()->ServerDNSDetectHijacking)
1625 return;
1626 dns_launch_wildcard_checks();
1628 /* Wait a while before launching requests for test addresses, so we can
1629 * get the results from checking for wildcarding. */
1630 if (! launch_event)
1631 launch_event = tor_evtimer_new(tor_libevent_get_base(),
1632 launch_test_addresses, NULL);
1633 timeout.tv_sec = 30;
1634 timeout.tv_usec = 0;
1635 if (evtimer_add(launch_event, &timeout)<0) {
1636 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
1640 /** Return true iff our DNS servers lie to us too much to be trusted. */
1642 dns_seems_to_be_broken(void)
1644 return dns_is_completely_invalid;
1647 /** Forget what we've previously learned about our DNS servers' correctness. */
1648 void
1649 dns_reset_correctness_checks(void)
1651 strmap_free(dns_wildcard_response_count, _tor_free);
1652 dns_wildcard_response_count = NULL;
1654 n_wildcard_requests = 0;
1656 if (dns_wildcard_list) {
1657 SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
1658 smartlist_clear(dns_wildcard_list);
1660 if (dns_wildcarded_test_address_list) {
1661 SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
1662 tor_free(cp));
1663 smartlist_clear(dns_wildcarded_test_address_list);
1665 dns_wildcard_one_notice_given = dns_wildcard_notice_given =
1666 dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
1669 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1670 * returned in response to requests for nonexistent hostnames. */
1671 static int
1672 answer_is_wildcarded(const char *ip)
1674 return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
1677 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1678 static void
1679 assert_resolve_ok(cached_resolve_t *resolve)
1681 tor_assert(resolve);
1682 tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
1683 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
1684 tor_assert(tor_strisnonupper(resolve->address));
1685 if (resolve->state != CACHE_STATE_PENDING) {
1686 tor_assert(!resolve->pending_connections);
1688 if (resolve->state == CACHE_STATE_PENDING ||
1689 resolve->state == CACHE_STATE_DONE) {
1690 tor_assert(!resolve->ttl);
1691 if (resolve->is_reverse)
1692 tor_assert(!resolve->result.hostname);
1693 else
1694 tor_assert(!resolve->result.a.addr);
1698 /** Return the number of DNS cache entries as an int */
1699 static int
1700 dns_cache_entry_count(void)
1702 return HT_SIZE(&cache_root);
1705 /** Log memory information about our internal DNS cache at level 'severity'. */
1706 void
1707 dump_dns_mem_usage(int severity)
1709 /* This should never be larger than INT_MAX. */
1710 int hash_count = dns_cache_entry_count();
1711 size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
1712 hash_mem += HT_MEM_USAGE(&cache_root);
1714 /* Print out the count and estimated size of our &cache_root. It undercounts
1715 hostnames in cached reverse resolves.
1717 log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
1718 log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
1719 (unsigned)hash_mem);
1722 #ifdef DEBUG_DNS_CACHE
1723 /** Exit with an assertion if the DNS cache is corrupt. */
1724 static void
1725 _assert_cache_ok(void)
1727 cached_resolve_t **resolve;
1728 int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
1729 if (bad_rep) {
1730 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
1731 tor_assert(!bad_rep);
1734 HT_FOREACH(resolve, cache_map, &cache_root) {
1735 assert_resolve_ok(*resolve);
1736 tor_assert((*resolve)->state != CACHE_STATE_DONE);
1738 if (!cached_resolve_pqueue)
1739 return;
1741 smartlist_pqueue_assert_ok(cached_resolve_pqueue,
1742 _compare_cached_resolves_by_expiry,
1743 STRUCT_OFFSET(cached_resolve_t, minheap_idx));
1745 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
1747 if (res->state == CACHE_STATE_DONE) {
1748 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1749 tor_assert(!found || found != res);
1750 } else {
1751 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1752 tor_assert(found);
1756 #endif