fix some irix compile complaints; make "kbytes" work as a memory unit
[tor.git] / src / or / dns.c
blobb4b86502fb1a936ee0cca99e834cf8699092e80b
1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007, 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 /** What was the resolv_conf fname we last used when configuring the
37 * nameservers? Used to check whether we need to reconfigure. */
38 static char *resolv_conf_fname = NULL;
39 /** What was the mtime on the resolv.conf file we last used when configuring
40 * the nameservers? Used to check whether we need to reconfigure. */
41 static time_t resolv_conf_mtime = 0;
43 /** Linked list of connections waiting for a DNS answer. */
44 typedef struct pending_connection_t {
45 edge_connection_t *conn;
46 struct pending_connection_t *next;
47 } pending_connection_t;
49 /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
50 * pointers and memory stomping. */
51 #define CACHED_RESOLVE_MAGIC 0x1234F00D
53 /* Possible states for a cached resolve_t */
54 /** We are waiting for the resolver system to tell us an answer here.
55 * When we get one, or when we time out, the state of this cached_resolve_t
56 * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
57 * entry. This cached_resolve_t will be in the hash table so that we will
58 * know not to launch more requests for this addr, but rather to add more
59 * connections to the pending list for the addr. */
60 #define CACHE_STATE_PENDING 0
61 /** This used to be a pending cached_resolve_t, and we got an answer for it.
62 * Now we're waiting for this cached_resolve_t to expire. This should
63 * have no pending connections, and should not appear in the hash table. */
64 #define CACHE_STATE_DONE 1
65 /** We are caching an answer for this address. This should have no pending
66 * connections, and should appear in the hash table. */
67 #define CACHE_STATE_CACHED_VALID 2
68 /** We are caching a failure for this address. This should have no pending
69 * connections, and should appear in the hash table */
70 #define CACHE_STATE_CACHED_FAILED 3
72 /** A DNS request: possibly completed, possibly pending; cached_resolve
73 * structs are stored at the OR side in a hash table, and as a linked
74 * list from oldest to newest.
76 typedef struct cached_resolve_t {
77 HT_ENTRY(cached_resolve_t) node;
78 uint32_t magic;
79 char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
80 union {
81 uint32_t addr; /**< IPv4 addr for <b>address</b>. */
82 char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
83 } result;
84 uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
85 uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
86 time_t expire; /**< Remove items from cache after this time. */
87 uint32_t ttl; /**< What TTL did the nameserver tell us? */
88 /** Connections that want to know when we get an answer for this resolve. */
89 pending_connection_t *pending_connections;
90 } cached_resolve_t;
92 static void purge_expired_resolves(time_t now);
93 static void dns_found_answer(const char *address, int is_reverse,
94 uint32_t addr, const char *hostname, char outcome,
95 uint32_t ttl);
96 static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
97 static int launch_resolve(edge_connection_t *exitconn);
98 static void add_wildcarded_test_address(const char *address);
99 static int configure_nameservers(int force);
100 static int answer_is_wildcarded(const char *ip);
101 static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
102 or_circuit_t *oncirc, char **resolved_to_hostname);
103 #ifdef DEBUG_DNS_CACHE
104 static void _assert_cache_ok(void);
105 #define assert_cache_ok() _assert_cache_ok()
106 #else
107 #define assert_cache_ok() STMT_NIL
108 #endif
109 static void assert_resolve_ok(cached_resolve_t *resolve);
111 /** Hash table of cached_resolve objects. */
112 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
114 /** Function to compare hashed resolves on their addresses; used to
115 * implement hash tables. */
116 static INLINE int
117 cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
119 /* make this smarter one day? */
120 assert_resolve_ok(a); // Not b; b may be just a search.
121 return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
124 /** Hash function for cached_resolve objects */
125 static INLINE unsigned int
126 cached_resolve_hash(cached_resolve_t *a)
128 return ht_string_hash(a->address);
131 HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
132 cached_resolves_eq)
133 HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
134 cached_resolves_eq, 0.6, malloc, realloc, free)
136 /** Initialize the DNS cache. */
137 static void
138 init_cache_map(void)
140 HT_INIT(cache_map, &cache_root);
143 /** Helper: called by eventdns when eventdns wants to log something. */
144 static void
145 evdns_log_cb(int warn, const char *msg)
147 const char *cp;
148 static int all_down = 0;
149 int severity = warn ? LOG_WARN : LOG_INFO;
150 if (!strcmpstart(msg, "Resolve requested for") &&
151 get_options()->SafeLogging) {
152 log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
153 return;
154 } else if (!strcmpstart(msg, "Search: ")) {
155 return;
157 if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
158 char *ns = tor_strndup(msg+11, cp-(msg+11));
159 const char *err = strchr(cp, ':'+2);
160 /* Don't warn about a single failed nameserver; we'll warn with 'all
161 * nameservers have failed' if we're completely out of nameservers;
162 * otherwise, the situation is tolerable. */
163 severity = LOG_INFO;
164 control_event_server_status(LOG_NOTICE,
165 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
166 ns, escaped(err));
167 tor_free(ns);
168 } else if (!strcmpstart(msg, "Nameserver ") &&
169 (cp=strstr(msg, " is back up"))) {
170 char *ns = tor_strndup(msg+11, cp-(msg+11));
171 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
172 all_down = 0;
173 control_event_server_status(LOG_NOTICE,
174 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
175 tor_free(ns);
176 } else if (!strcmp(msg, "All nameservers have failed")) {
177 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
178 all_down = 1;
180 log(severity, LD_EXIT, "eventdns: %s", msg);
183 /** Helper: generate a good random transaction ID. */
184 static uint16_t
185 dns_get_transaction_id(void)
187 uint16_t result;
188 crypto_rand((void*)&result, sizeof(result));
189 return result;
192 /** Initialize the DNS subsystem; called by the OR process. */
194 dns_init(void)
196 init_cache_map();
197 evdns_set_transaction_id_fn(dns_get_transaction_id);
198 if (server_mode(get_options()))
199 return configure_nameservers(1);
200 return 0;
203 /** Called when DNS-related options change (or may have changed). Returns -1
204 * on failure, 0 on success. */
206 dns_reset(void)
208 or_options_t *options = get_options();
209 if (! server_mode(options)) {
210 evdns_clear_nameservers_and_suspend();
211 evdns_search_clear();
212 nameservers_configured = 0;
213 tor_free(resolv_conf_fname);
214 resolv_conf_mtime = 0;
215 } else {
216 if (configure_nameservers(0) < 0)
217 return -1;
219 return 0;
222 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
223 * OP that asked us to resolve it. */
224 uint32_t
225 dns_clip_ttl(uint32_t ttl)
227 if (ttl < MIN_DNS_TTL)
228 return MIN_DNS_TTL;
229 else if (ttl > MAX_DNS_TTL)
230 return MAX_DNS_TTL;
231 else
232 return ttl;
235 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
236 * our cache. */
237 static uint32_t
238 dns_get_expiry_ttl(uint32_t ttl)
240 if (ttl < MIN_DNS_TTL)
241 return MIN_DNS_TTL;
242 else if (ttl > MAX_DNS_ENTRY_AGE)
243 return MAX_DNS_ENTRY_AGE;
244 else
245 return ttl;
248 /** Helper: free storage held by an entry in the DNS cache. */
249 static void
250 _free_cached_resolve(cached_resolve_t *r)
252 while (r->pending_connections) {
253 pending_connection_t *victim = r->pending_connections;
254 r->pending_connections = victim->next;
255 tor_free(victim);
257 if (r->is_reverse)
258 tor_free(r->result.hostname);
259 r->magic = 0xFF00FF00;
260 tor_free(r);
263 /** Compare two cached_resolve_t pointers by expiry time, and return
264 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
265 * the priority queue implementation. */
266 static int
267 _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
269 const cached_resolve_t *a = _a, *b = _b;
270 return a->expire - b->expire;
273 /** Priority queue of cached_resolve_t objects to let us know when they
274 * will expire. */
275 static smartlist_t *cached_resolve_pqueue = NULL;
277 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
278 * priority queue */
279 static void
280 set_expiry(cached_resolve_t *resolve, time_t expires)
282 tor_assert(resolve && resolve->expire == 0);
283 if (!cached_resolve_pqueue)
284 cached_resolve_pqueue = smartlist_create();
285 resolve->expire = expires;
286 smartlist_pqueue_add(cached_resolve_pqueue,
287 _compare_cached_resolves_by_expiry,
288 resolve);
291 /** Free all storage held in the DNS cache and related structures. */
292 void
293 dns_free_all(void)
295 cached_resolve_t **ptr, **next, *item;
296 assert_cache_ok();
297 if (cached_resolve_pqueue) {
298 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
300 if (res->state == CACHE_STATE_DONE)
301 _free_cached_resolve(res);
304 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
305 item = *ptr;
306 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
307 _free_cached_resolve(item);
309 HT_CLEAR(cache_map, &cache_root);
310 if (cached_resolve_pqueue)
311 smartlist_free(cached_resolve_pqueue);
312 cached_resolve_pqueue = NULL;
313 tor_free(resolv_conf_fname);
316 /** Remove every cached_resolve whose <b>expire</b> time is before or
317 * equal to <b>now</b> from the cache. */
318 static void
319 purge_expired_resolves(time_t now)
321 cached_resolve_t *resolve, *removed;
322 pending_connection_t *pend;
323 edge_connection_t *pendconn;
325 assert_cache_ok();
326 if (!cached_resolve_pqueue)
327 return;
329 while (smartlist_len(cached_resolve_pqueue)) {
330 resolve = smartlist_get(cached_resolve_pqueue, 0);
331 if (resolve->expire > now)
332 break;
333 smartlist_pqueue_pop(cached_resolve_pqueue,
334 _compare_cached_resolves_by_expiry);
336 if (resolve->state == CACHE_STATE_PENDING) {
337 log_debug(LD_EXIT,
338 "Expiring a dns resolve %s that's still pending. Forgot to "
339 "cull it? DNS resolve didn't tell us about the timeout?",
340 escaped_safe_str(resolve->address));
341 } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
342 resolve->state == CACHE_STATE_CACHED_FAILED) {
343 log_debug(LD_EXIT,
344 "Forgetting old cached resolve (address %s, expires %lu)",
345 escaped_safe_str(resolve->address),
346 (unsigned long)resolve->expire);
347 tor_assert(!resolve->pending_connections);
348 } else {
349 tor_assert(resolve->state == CACHE_STATE_DONE);
350 tor_assert(!resolve->pending_connections);
353 if (resolve->pending_connections) {
354 log_debug(LD_EXIT,
355 "Closing pending connections on timed-out DNS resolve!");
356 tor_fragile_assert();
357 while (resolve->pending_connections) {
358 pend = resolve->pending_connections;
359 resolve->pending_connections = pend->next;
360 /* Connections should only be pending if they have no socket. */
361 tor_assert(pend->conn->_base.s == -1);
362 pendconn = pend->conn;
363 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
364 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
365 connection_free(TO_CONN(pendconn));
366 tor_free(pend);
370 if (resolve->state == CACHE_STATE_CACHED_VALID ||
371 resolve->state == CACHE_STATE_CACHED_FAILED ||
372 resolve->state == CACHE_STATE_PENDING) {
373 removed = HT_REMOVE(cache_map, &cache_root, resolve);
374 if (removed != resolve) {
375 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
376 " the cache. Tried to purge %s (%p); instead got %s (%p).",
377 resolve->address, (void*)resolve,
378 removed ? removed->address : "NULL", (void*)remove);
380 tor_assert(removed == resolve);
381 } else {
382 /* This should be in state DONE. Make sure it's not in the cache. */
383 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
384 tor_assert(tmp != resolve);
386 if (resolve->is_reverse)
387 tor_free(resolve->result.hostname);
388 resolve->magic = 0xF0BBF0BB;
389 tor_free(resolve);
392 assert_cache_ok();
395 /** Send a response to the RESOLVE request of a connection.
396 * <b>answer_type</b> must be one of
397 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
399 * If <b>circ</b> is provided, and we have a cached answer, send the
400 * answer back along circ; otherwise, send the answer back along
401 * <b>conn</b>'s attached circuit.
403 static void
404 send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
406 char buf[RELAY_PAYLOAD_SIZE];
407 size_t buflen;
408 uint32_t ttl;
410 buf[0] = answer_type;
411 ttl = dns_clip_ttl(conn->address_ttl);
413 switch (answer_type)
415 case RESOLVED_TYPE_IPV4:
416 buf[1] = 4;
417 set_uint32(buf+2, htonl(conn->_base.addr));
418 set_uint32(buf+6, htonl(ttl));
419 buflen = 10;
420 break;
421 case RESOLVED_TYPE_ERROR_TRANSIENT:
422 case RESOLVED_TYPE_ERROR:
424 const char *errmsg = "Error resolving hostname";
425 int msglen = strlen(errmsg);
427 buf[1] = msglen;
428 strlcpy(buf+2, errmsg, sizeof(buf)-2);
429 set_uint32(buf+2+msglen, htonl(ttl));
430 buflen = 6+msglen;
431 break;
433 default:
434 tor_assert(0);
435 return;
437 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
439 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
442 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
443 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
444 * The answer type will be RESOLVED_HOSTNAME.
446 * If <b>circ</b> is provided, and we have a cached answer, send the
447 * answer back along circ; otherwise, send the answer back along
448 * <b>conn</b>'s attached circuit.
450 static void
451 send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
453 char buf[RELAY_PAYLOAD_SIZE];
454 size_t buflen;
455 uint32_t ttl;
456 size_t namelen = strlen(hostname);
457 tor_assert(hostname);
459 tor_assert(namelen < 256);
460 ttl = dns_clip_ttl(conn->address_ttl);
462 buf[0] = RESOLVED_TYPE_HOSTNAME;
463 buf[1] = (uint8_t)namelen;
464 memcpy(buf+2, hostname, namelen);
465 set_uint32(buf+2+namelen, htonl(ttl));
466 buflen = 2+namelen+4;
468 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
469 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
470 // log_notice(LD_EXIT, "Sent");
473 /** Given a lower-case <b>address</b>, check to see whether it's a
474 * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
475 * parse it and place the address in <b>in</b> if present. Return 1 on success;
476 * 0 if the address is not in in-addr.arpa format, and -1 if the address is
477 * malformed. */
478 static int
479 parse_inaddr_arpa_address(const char *address, struct in_addr *in)
481 char buf[INET_NTOA_BUF_LEN];
482 char *cp;
483 size_t len;
484 struct in_addr inaddr;
486 cp = strstr(address, ".in-addr.arpa");
487 if (!cp || *(cp+strlen(".in-addr.arpa")))
488 return 0; /* not an .in-addr.arpa address */
490 len = cp - address;
492 if (len >= INET_NTOA_BUF_LEN)
493 return -1; /* Too long. */
495 memcpy(buf, address, len);
496 buf[len] = '\0';
497 if (tor_inet_aton(buf, &inaddr) == 0)
498 return -1; /* malformed. */
500 if (in) {
501 uint32_t a;
502 /* reverse the bytes */
503 a = ( ((inaddr.s_addr & 0x000000fful) << 24)
504 |((inaddr.s_addr & 0x0000ff00ul) << 8)
505 |((inaddr.s_addr & 0x00ff0000ul) >> 8)
506 |((inaddr.s_addr & 0xff000000ul) >> 24));
507 inaddr.s_addr = a;
509 memcpy(in, &inaddr, sizeof(inaddr));
512 return 1;
515 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
516 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
517 * If resolve failed, free exitconn and return -1.
519 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
520 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
521 * need to send back an END cell, since connection_exit_begin_conn will
522 * do that for us.)
524 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
525 * circuit.
527 * Else, if seen before and pending, add conn to the pending list,
528 * and return 0.
530 * Else, if not seen before, add conn to pending list, hand to
531 * dns farm, and return 0.
533 * Exitconn's on_circuit field must be set, but exitconn should not
534 * yet be linked onto the n_streams/resolving_streams list of that circuit.
535 * On success, link the connection to n_streams if it's an exit connection.
536 * On "pending", link the connection to resolving streams. Otherwise,
537 * clear its on_circuit field.
540 dns_resolve(edge_connection_t *exitconn)
542 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
543 int is_resolve, r;
544 char *hostname = NULL;
545 is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
547 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
548 switch (r) {
549 case 1:
550 /* We got an answer without a lookup -- either the answer was
551 * cached, or it was obvious (like an IP address). */
552 if (is_resolve) {
553 /* Send the answer back right now, and detach. */
554 if (hostname)
555 send_resolved_hostname_cell(exitconn, hostname);
556 else
557 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
558 exitconn->on_circuit = NULL;
559 } else {
560 /* Add to the n_streams list; the calling function will send back a
561 * connected cell. */
562 exitconn->next_stream = oncirc->n_streams;
563 oncirc->n_streams = exitconn;
565 break;
566 case 0:
567 /* The request is pending: add the connection into the linked list of
568 * resolving_streams on this circuit. */
569 exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
570 exitconn->next_stream = oncirc->resolving_streams;
571 oncirc->resolving_streams = exitconn;
572 break;
573 case -2:
574 case -1:
575 /* The request failed before it could start: cancel this connection,
576 * and stop everybody waiting for the same connection. */
577 if (is_resolve) {
578 send_resolved_cell(exitconn,
579 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
582 exitconn->on_circuit = NULL;
584 dns_cancel_pending_resolve(exitconn->_base.address);
586 if (!exitconn->_base.marked_for_close) {
587 connection_free(TO_CONN(exitconn));
588 //XXX020 ... and we just leak exitconn otherwise? -RD
589 // If it's marked for close, it's on closeable_connection_lst in
590 // main.c. If it's on the closeable list, it will get freed from
591 // main.c. -NM
592 // "<armadev> If that's true, there are other bugs around, where we
593 // don't check if it's marked, and will end up double-freeing."
595 break;
596 default:
597 tor_assert(0);
600 tor_free(hostname);
601 return r;
604 /** Helper function for dns_resolve: same functionality, but does not handle:
605 * - marking connections on error and clearing their on_circuit
606 * - linking connections to n_streams/resolving_streams,
607 * - sending resolved cells if we have an answer/error right away,
609 * Return -2 on a transient error. If it's a reverse resolve and it's
610 * successful, sets *<b>hostname_out</b> to a newly allocated string
611 * holding the cached reverse DNS value.
613 static int
614 dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
615 or_circuit_t *oncirc, char **hostname_out)
617 cached_resolve_t *resolve;
618 cached_resolve_t search;
619 pending_connection_t *pending_connection;
620 struct in_addr in;
621 time_t now = time(NULL);
622 int is_reverse = 0, r;
623 assert_connection_ok(TO_CONN(exitconn), 0);
624 tor_assert(exitconn->_base.s == -1);
625 assert_cache_ok();
626 tor_assert(oncirc);
628 /* first check if exitconn->_base.address is an IP. If so, we already
629 * know the answer. */
630 if (tor_inet_aton(exitconn->_base.address, &in) != 0) {
631 exitconn->_base.addr = ntohl(in.s_addr);
632 exitconn->address_ttl = DEFAULT_DNS_TTL;
633 return 1;
635 if (address_is_invalid_destination(exitconn->_base.address, 0)) {
636 log(LOG_PROTOCOL_WARN, LD_EXIT,
637 "Rejecting invalid destination address %s",
638 escaped_safe_str(exitconn->_base.address));
639 return -1;
642 /* then take this opportunity to see if there are any expired
643 * resolves in the hash table. */
644 purge_expired_resolves(now);
646 /* lower-case exitconn->_base.address, so it's in canonical form */
647 tor_strlower(exitconn->_base.address);
649 /* Check whether this is a reverse lookup. If it's malformed, or it's a
650 * .in-addr.arpa address but this isn't a resolve request, kill the
651 * connection.
653 if ((r = parse_inaddr_arpa_address(exitconn->_base.address, NULL)) != 0) {
654 if (r == 1)
655 is_reverse = 1;
657 if (!is_reverse || !is_resolve) {
658 if (!is_reverse)
659 log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
660 escaped_safe_str(exitconn->_base.address));
661 else if (!is_resolve)
662 log_info(LD_EXIT,
663 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
664 "sending error.",
665 escaped_safe_str(exitconn->_base.address));
667 return -1;
669 //log_notice(LD_EXIT, "Looks like an address %s",
670 //exitconn->_base.address);
673 /* now check the hash table to see if 'address' is already there. */
674 strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
675 resolve = HT_FIND(cache_map, &cache_root, &search);
676 if (resolve && resolve->expire > now) { /* already there */
677 switch (resolve->state) {
678 case CACHE_STATE_PENDING:
679 /* add us to the pending list */
680 pending_connection = tor_malloc_zero(
681 sizeof(pending_connection_t));
682 pending_connection->conn = exitconn;
683 pending_connection->next = resolve->pending_connections;
684 resolve->pending_connections = pending_connection;
685 log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
686 "resolve of %s", exitconn->_base.s,
687 escaped_safe_str(exitconn->_base.address));
688 return 0;
689 case CACHE_STATE_CACHED_VALID:
690 log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
691 exitconn->_base.s,
692 escaped_safe_str(resolve->address));
693 exitconn->address_ttl = resolve->ttl;
694 if (resolve->is_reverse) {
695 tor_assert(is_resolve);
696 *hostname_out = tor_strdup(resolve->result.hostname);
697 } else {
698 exitconn->_base.addr = resolve->result.addr;
700 return 1;
701 case CACHE_STATE_CACHED_FAILED:
702 log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
703 exitconn->_base.s,
704 escaped_safe_str(exitconn->_base.address));
705 return -1;
706 case CACHE_STATE_DONE:
707 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
708 tor_fragile_assert();
710 tor_assert(0);
712 tor_assert(!resolve);
713 /* not there, need to add it */
714 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
715 resolve->magic = CACHED_RESOLVE_MAGIC;
716 resolve->state = CACHE_STATE_PENDING;
717 resolve->is_reverse = is_reverse;
718 strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
720 /* add this connection to the pending list */
721 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
722 pending_connection->conn = exitconn;
723 resolve->pending_connections = pending_connection;
725 /* Add this resolve to the cache and priority queue. */
726 HT_INSERT(cache_map, &cache_root, resolve);
727 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
729 log_debug(LD_EXIT,"Launching %s.",
730 escaped_safe_str(exitconn->_base.address));
731 assert_cache_ok();
733 return launch_resolve(exitconn);
736 /** Log an error and abort if conn is waiting for a DNS resolve.
738 void
739 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
741 pending_connection_t *pend;
742 cached_resolve_t **resolve;
744 HT_FOREACH(resolve, cache_map, &cache_root) {
745 for (pend = (*resolve)->pending_connections;
746 pend;
747 pend = pend->next) {
748 tor_assert(pend->conn != conn);
753 /** Log an error and abort if any connection waiting for a DNS resolve is
754 * corrupted. */
755 void
756 assert_all_pending_dns_resolves_ok(void)
758 pending_connection_t *pend;
759 cached_resolve_t **resolve;
761 HT_FOREACH(resolve, cache_map, &cache_root) {
762 for (pend = (*resolve)->pending_connections;
763 pend;
764 pend = pend->next) {
765 assert_connection_ok(TO_CONN(pend->conn), 0);
766 tor_assert(pend->conn->_base.s == -1);
767 tor_assert(!connection_in_array(TO_CONN(pend->conn)));
772 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
774 void
775 connection_dns_remove(edge_connection_t *conn)
777 pending_connection_t *pend, *victim;
778 cached_resolve_t search;
779 cached_resolve_t *resolve;
781 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
782 tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
784 strlcpy(search.address, conn->_base.address, sizeof(search.address));
786 resolve = HT_FIND(cache_map, &cache_root, &search);
787 if (!resolve) {
788 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
789 escaped_safe_str(conn->_base.address));
790 return;
793 tor_assert(resolve->pending_connections);
794 assert_connection_ok(TO_CONN(conn),0);
796 pend = resolve->pending_connections;
798 if (pend->conn == conn) {
799 resolve->pending_connections = pend->next;
800 tor_free(pend);
801 log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
802 "for resolve of %s",
803 conn->_base.s, escaped_safe_str(conn->_base.address));
804 return;
805 } else {
806 for ( ; pend->next; pend = pend->next) {
807 if (pend->next->conn == conn) {
808 victim = pend->next;
809 pend->next = victim->next;
810 tor_free(victim);
811 log_debug(LD_EXIT,
812 "Connection (fd %d) no longer waiting for resolve of %s",
813 conn->_base.s, escaped_safe_str(conn->_base.address));
814 return; /* more are pending */
817 tor_assert(0); /* not reachable unless onlyconn not in pending list */
821 /** Mark all connections waiting for <b>address</b> for close. Then cancel
822 * the resolve for <b>address</b> itself, and remove any cached results for
823 * <b>address</b> from the cache.
825 void
826 dns_cancel_pending_resolve(const char *address)
828 pending_connection_t *pend;
829 cached_resolve_t search;
830 cached_resolve_t *resolve, *tmp;
831 edge_connection_t *pendconn;
832 circuit_t *circ;
834 strlcpy(search.address, address, sizeof(search.address));
836 resolve = HT_FIND(cache_map, &cache_root, &search);
837 if (!resolve)
838 return;
840 if (resolve->state != CACHE_STATE_PENDING) {
841 /* We can get into this state if we never actually created the pending
842 * resolve, due to finding an earlier cached error or something. Just
843 * ignore it. */
844 if (resolve->pending_connections) {
845 log_warn(LD_BUG,
846 "Address %s is not pending but has pending connections!",
847 escaped_safe_str(address));
848 tor_fragile_assert();
850 return;
853 if (!resolve->pending_connections) {
854 /* XXX this should never trigger, but sometimes it does */
855 /* XXXX020 is the above still true? -NM */
856 log_warn(LD_BUG,
857 "Address %s is pending but has no pending connections!",
858 escaped_safe_str(address));
859 tor_fragile_assert();
860 return;
862 tor_assert(resolve->pending_connections);
864 /* mark all pending connections to fail */
865 log_debug(LD_EXIT,
866 "Failing all connections waiting on DNS resolve of %s",
867 escaped_safe_str(address));
868 while (resolve->pending_connections) {
869 pend = resolve->pending_connections;
870 pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
871 pendconn = pend->conn;
872 assert_connection_ok(TO_CONN(pendconn), 0);
873 tor_assert(pendconn->_base.s == -1);
874 if (!pendconn->_base.marked_for_close) {
875 /* XXXX020 RESOURCELIMIT? Not RESOLVEFAILED??? */
876 connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT);
878 circ = circuit_get_by_edge_conn(pendconn);
879 if (circ)
880 circuit_detach_stream(circ, pendconn);
881 if (!pendconn->_base.marked_for_close)
882 connection_free(TO_CONN(pendconn));
883 resolve->pending_connections = pend->next;
884 tor_free(pend);
887 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
888 if (tmp != resolve) {
889 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
890 " the cache. Tried to purge %s (%p); instead got %s (%p).",
891 resolve->address, (void*)resolve,
892 tmp ? tmp->address : "NULL", (void*)tmp);
894 tor_assert(tmp == resolve);
896 resolve->state = CACHE_STATE_DONE;
899 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
900 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
901 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
902 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
904 static void
905 add_answer_to_cache(const char *address, int is_reverse, uint32_t addr,
906 const char *hostname, char outcome, uint32_t ttl)
908 cached_resolve_t *resolve;
909 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
910 return;
912 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
913 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
914 // hostname?hostname:"NULL",(int)outcome);
916 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
917 resolve->magic = CACHED_RESOLVE_MAGIC;
918 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
919 CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
920 strlcpy(resolve->address, address, sizeof(resolve->address));
921 resolve->is_reverse = is_reverse;
922 if (is_reverse) {
923 if (outcome == DNS_RESOLVE_SUCCEEDED) {
924 tor_assert(hostname);
925 resolve->result.hostname = tor_strdup(hostname);
926 } else {
927 tor_assert(! hostname);
928 resolve->result.hostname = NULL;
930 } else {
931 tor_assert(!hostname);
932 resolve->result.addr = addr;
934 resolve->ttl = ttl;
935 assert_resolve_ok(resolve);
936 HT_INSERT(cache_map, &cache_root, resolve);
937 set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
940 /** Return true iff <b>address</b> is one of the addresses we use to verify
941 * that well-known sites aren't being hijacked by our DNS servers. */
942 static INLINE int
943 is_test_address(const char *address)
945 or_options_t *options = get_options();
946 return options->ServerDNSTestAddresses &&
947 smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
950 /** Called on the OR side when a DNS worker or the eventdns library tells us
951 * the outcome of a DNS resolve: tell all pending connections about the result
952 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
953 * string containing the address to look up; <b>addr</b> is an IPv4 address in
954 * host order; <b>outcome</b> is one of
955 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
957 static void
958 dns_found_answer(const char *address, int is_reverse, uint32_t addr,
959 const char *hostname, char outcome, uint32_t ttl)
961 pending_connection_t *pend;
962 cached_resolve_t search;
963 cached_resolve_t *resolve, *removed;
964 edge_connection_t *pendconn;
965 circuit_t *circ;
967 assert_cache_ok();
969 strlcpy(search.address, address, sizeof(search.address));
971 resolve = HT_FIND(cache_map, &cache_root, &search);
972 if (!resolve) {
973 int is_test_addr = is_test_address(address);
974 if (!is_test_addr)
975 log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
976 escaped_safe_str(address));
977 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
978 return;
980 assert_resolve_ok(resolve);
982 if (resolve->state != CACHE_STATE_PENDING) {
983 /* XXXX020 Maybe update addr? or check addr for consistency? Or let
984 * VALID replace FAILED? */
985 int is_test_addr = is_test_address(address);
986 if (!is_test_addr)
987 log_notice(LD_EXIT,
988 "Resolved %s which was already resolved; ignoring",
989 escaped_safe_str(address));
990 tor_assert(resolve->pending_connections == NULL);
991 return;
993 /* Removed this assertion: in fact, we'll sometimes get a double answer
994 * to the same question. This can happen when we ask one worker to resolve
995 * X.Y.Z., then we cancel the request, and then we ask another worker to
996 * resolve X.Y.Z. */
997 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
999 while (resolve->pending_connections) {
1000 pend = resolve->pending_connections;
1001 pendconn = pend->conn; /* don't pass complex things to the
1002 connection_mark_for_close macro */
1003 assert_connection_ok(TO_CONN(pendconn),time(NULL));
1004 pendconn->_base.addr = addr;
1005 pendconn->address_ttl = ttl;
1007 if (outcome != DNS_RESOLVE_SUCCEEDED) {
1008 /* prevent double-remove. */
1009 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1010 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1011 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1012 /* This detach must happen after we send the end cell. */
1013 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1014 } else {
1015 send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
1016 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
1017 /* This detach must happen after we send the resolved cell. */
1018 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1020 connection_free(TO_CONN(pendconn));
1021 } else {
1022 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1023 tor_assert(!is_reverse);
1024 /* prevent double-remove. */
1025 pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
1027 circ = circuit_get_by_edge_conn(pend->conn);
1028 tor_assert(circ);
1029 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1030 /* unlink pend->conn from resolving_streams, */
1031 circuit_detach_stream(circ, pend->conn);
1032 /* and link it to n_streams */
1033 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1034 pend->conn->on_circuit = circ;
1035 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1037 connection_exit_connect(pend->conn);
1038 } else {
1039 /* prevent double-remove. This isn't really an accurate state,
1040 * but it does the right thing. */
1041 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1042 if (is_reverse)
1043 send_resolved_hostname_cell(pendconn, hostname);
1044 else
1045 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
1046 circ = circuit_get_by_edge_conn(pendconn);
1047 tor_assert(circ);
1048 circuit_detach_stream(circ, pendconn);
1049 connection_free(TO_CONN(pendconn));
1052 resolve->pending_connections = pend->next;
1053 tor_free(pend);
1056 resolve->state = CACHE_STATE_DONE;
1057 removed = HT_REMOVE(cache_map, &cache_root, &search);
1058 if (removed != resolve) {
1059 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1060 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1061 resolve->address, (void*)resolve,
1062 removed ? removed->address : "NULL", (void*)removed);
1064 assert_resolve_ok(resolve);
1065 assert_cache_ok();
1067 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
1068 assert_cache_ok();
1071 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1072 * a transient failure. */
1073 static int
1074 evdns_err_is_transient(int err)
1076 switch (err)
1078 case DNS_ERR_SERVERFAILED:
1079 case DNS_ERR_TRUNCATED:
1080 case DNS_ERR_TIMEOUT:
1081 return 1;
1082 default:
1083 return 0;
1087 /** Configure eventdns nameservers if force is true, or if the configuration
1088 * has changed since the last time we called this function. On Unix, this
1089 * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
1090 * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
1091 * Return 0 on success or -1 on failure. */
1092 static int
1093 configure_nameservers(int force)
1095 or_options_t *options;
1096 const char *conf_fname;
1097 struct stat st;
1098 int r;
1099 options = get_options();
1100 conf_fname = options->ServerDNSResolvConfFile;
1101 #ifndef MS_WINDOWS
1102 if (!conf_fname)
1103 conf_fname = "/etc/resolv.conf";
1104 #endif
1106 evdns_set_log_fn(evdns_log_cb);
1107 if (conf_fname) {
1108 if (stat(conf_fname, &st)) {
1109 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1110 conf_fname, strerror(errno));
1111 return -1;
1113 if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
1114 && st.st_mtime == resolv_conf_mtime) {
1115 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1116 return 0;
1118 if (nameservers_configured) {
1119 evdns_search_clear();
1120 evdns_clear_nameservers_and_suspend();
1122 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1123 if ((r = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname))) {
1124 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1125 conf_fname, conf_fname, r);
1126 return -1;
1128 if (evdns_count_nameservers() == 0) {
1129 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
1130 return -1;
1132 tor_free(resolv_conf_fname);
1133 resolv_conf_fname = tor_strdup(conf_fname);
1134 resolv_conf_mtime = st.st_mtime;
1135 if (nameservers_configured)
1136 evdns_resume();
1138 #ifdef MS_WINDOWS
1139 else {
1140 if (nameservers_configured) {
1141 evdns_search_clear();
1142 evdns_clear_nameservers_and_suspend();
1144 if (evdns_config_windows_nameservers()) {
1145 log_warn(LD_EXIT,"Could not config nameservers.");
1146 return -1;
1148 if (evdns_count_nameservers() == 0) {
1149 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1150 "your Windows configuration. Perhaps you should list a "
1151 "ServerDNSResolvConfFile file in your torrc?");
1152 return -1;
1154 if (nameservers_configured)
1155 evdns_resume();
1156 tor_free(resolv_conf_fname);
1157 resolv_conf_mtime = 0;
1159 #endif
1161 if (evdns_count_nameservers() == 1) {
1162 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
1163 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
1164 } else {
1165 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
1166 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
1169 dns_servers_relaunch_checks();
1171 nameservers_configured = 1;
1172 return 0;
1175 /** For eventdns: Called when we get an answer for a request we launched.
1176 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1178 static void
1179 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1180 void *arg)
1182 char *string_address = arg;
1183 int is_reverse = 0;
1184 int status = DNS_RESOLVE_FAILED_PERMANENT;
1185 uint32_t addr = 0;
1186 const char *hostname = NULL;
1187 int was_wildcarded = 0;
1189 if (result == DNS_ERR_NONE) {
1190 if (type == DNS_IPv4_A && count) {
1191 char answer_buf[INET_NTOA_BUF_LEN+1];
1192 struct in_addr in;
1193 char *escaped_address;
1194 uint32_t *addrs = addresses;
1195 in.s_addr = addrs[0];
1196 addr = ntohl(addrs[0]);
1197 status = DNS_RESOLVE_SUCCEEDED;
1198 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1199 escaped_address = esc_for_log(string_address);
1201 if (answer_is_wildcarded(answer_buf)) {
1202 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1203 "address %s; treating as a failure.",
1204 safe_str(escaped_address),
1205 escaped_safe_str(answer_buf));
1206 was_wildcarded = 1;
1207 addr = 0;
1208 status = DNS_RESOLVE_FAILED_PERMANENT;
1209 } else {
1210 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1211 safe_str(escaped_address),
1212 escaped_safe_str(answer_buf));
1214 tor_free(escaped_address);
1215 } else if (type == DNS_PTR && count) {
1216 char *escaped_address;
1217 is_reverse = 1;
1218 hostname = ((char**)addresses)[0];
1219 status = DNS_RESOLVE_SUCCEEDED;
1220 escaped_address = esc_for_log(string_address);
1221 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1222 safe_str(escaped_address),
1223 escaped_safe_str(hostname));
1224 tor_free(escaped_address);
1225 } else if (count) {
1226 log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
1227 escaped_safe_str(string_address));
1228 } else {
1229 log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
1230 escaped_safe_str(string_address));
1232 } else {
1233 if (evdns_err_is_transient(result))
1234 status = DNS_RESOLVE_FAILED_TRANSIENT;
1236 if (was_wildcarded) {
1237 if (is_test_address(string_address)) {
1238 /* Ick. We're getting redirected on known-good addresses. Our DNS
1239 * server must really hate us. */
1240 add_wildcarded_test_address(string_address);
1243 if (result != DNS_ERR_SHUTDOWN)
1244 dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
1245 tor_free(string_address);
1248 /** For eventdns: start resolving as necessary to find the target for
1249 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1250 * 0 on "resolve launched." */
1251 static int
1252 launch_resolve(edge_connection_t *exitconn)
1254 char *addr = tor_strdup(exitconn->_base.address);
1255 struct in_addr in;
1256 int r;
1257 int options = get_options()->ServerDNSSearchDomains ? 0
1258 : DNS_QUERY_NO_SEARCH;
1259 /* What? Nameservers not configured? Sounds like a bug. */
1260 if (!nameservers_configured) {
1261 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1262 "launched. Configuring.");
1263 if (configure_nameservers(1) < 0)
1264 return -1;
1267 r = parse_inaddr_arpa_address(exitconn->_base.address, &in);
1268 if (r == 0) {
1269 log_info(LD_EXIT, "Launching eventdns request for %s",
1270 escaped_safe_str(exitconn->_base.address));
1271 r = evdns_resolve_ipv4(exitconn->_base.address, options,
1272 evdns_callback, addr);
1273 } else if (r == 1) {
1274 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1275 escaped_safe_str(exitconn->_base.address));
1276 r = evdns_resolve_reverse(&in, DNS_QUERY_NO_SEARCH,
1277 evdns_callback, addr);
1278 } else if (r == -1) {
1279 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1282 if (r) {
1283 log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
1284 escaped_safe_str(addr), r);
1285 r = evdns_err_is_transient(r) ? -2 : -1;
1286 tor_free(addr); /* There is no evdns request in progress; stop
1287 * addr from getting leaked. */
1289 return r;
1292 /** How many requests for bogus addresses have we launched so far? */
1293 static int n_wildcard_requests = 0;
1295 /** Map from dotted-quad IP address in response to an int holding how many
1296 * times we've seen it for a randomly generated (hopefully bogus) address. It
1297 * would be easier to use definitely-invalid addresses (as specified by
1298 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1299 static strmap_t *dns_wildcard_response_count = NULL;
1301 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1302 * nameserver wants to return in response to requests for nonexistent domains.
1304 static smartlist_t *dns_wildcard_list = NULL;
1305 /** True iff we've logged about a single address getting wildcarded.
1306 * Subsequent warnings will be less severe. */
1307 static int dns_wildcard_one_notice_given = 0;
1308 /** True iff we've warned that our DNS server is wildcarding too many failures.
1310 static int dns_wildcard_notice_given = 0;
1312 /** List of supposedly good addresses that are getting wildcarded to the
1313 * same addresses as nonexistent addresses. */
1314 static smartlist_t *dns_wildcarded_test_address_list = NULL;
1315 /** True iff we've warned about a test address getting wildcarded */
1316 static int dns_wildcarded_test_address_notice_given = 0;
1317 /** True iff all addresses seem to be getting wildcarded. */
1318 static int dns_is_completely_invalid = 0;
1320 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1321 * a hopefully bogus address. */
1322 static void
1323 wildcard_increment_answer(const char *id)
1325 int *ip;
1326 if (!dns_wildcard_response_count)
1327 dns_wildcard_response_count = strmap_new();
1329 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1330 if (!ip) {
1331 ip = tor_malloc_zero(sizeof(int));
1332 strmap_set(dns_wildcard_response_count, id, ip);
1334 ++*ip;
1336 if (*ip > 5 && n_wildcard_requests > 10) {
1337 if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
1338 if (!smartlist_string_isin(dns_wildcard_list, id)) {
1339 log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1340 "Your DNS provider has given \"%s\" as an answer for %d different "
1341 "invalid addresses. Apparently they are hijacking DNS failures. "
1342 "I'll try to correct for this by treating future occurrences of "
1343 "\"%s\" as 'not found'.", id, *ip, id);
1344 smartlist_add(dns_wildcard_list, tor_strdup(id));
1346 if (!dns_wildcard_notice_given)
1347 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1348 dns_wildcard_notice_given = 1;
1352 /** Note that a single test address (one believed to be good) seems to be
1353 * getting redirected to the same IP as failures are. */
1354 static void
1355 add_wildcarded_test_address(const char *address)
1357 int n, n_test_addrs;
1358 if (!dns_wildcarded_test_address_list)
1359 dns_wildcarded_test_address_list = smartlist_create();
1361 if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
1362 return;
1364 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1365 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1367 smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
1368 n = smartlist_len(dns_wildcarded_test_address_list);
1369 if (n > n_test_addrs/2) {
1370 log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
1371 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1372 "address. It has done this with %d test addresses so far. I'm "
1373 "going to stop being an exit node for now, since our DNS seems so "
1374 "broken.", address, n);
1375 if (!dns_is_completely_invalid) {
1376 dns_is_completely_invalid = 1;
1377 mark_my_descriptor_dirty();
1379 if (!dns_wildcarded_test_address_notice_given)
1380 control_event_server_status(LOG_WARN, "DNS_USELESS");
1381 dns_wildcarded_test_address_notice_given = 1;
1385 /** Callback function when we get an answer (possibly failing) for a request
1386 * for a (hopefully) nonexistent domain. */
1387 static void
1388 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1389 void *addresses, void *arg)
1391 (void)ttl;
1392 ++n_wildcard_requests;
1393 if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
1394 uint32_t *addrs = addresses;
1395 int i;
1396 char *string_address = arg;
1397 for (i = 0; i < count; ++i) {
1398 char answer_buf[INET_NTOA_BUF_LEN+1];
1399 struct in_addr in;
1400 in.s_addr = addrs[i];
1401 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1402 wildcard_increment_answer(answer_buf);
1404 log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1405 "Your DNS provider gave an answer for \"%s\", which "
1406 "is not supposed to exist. Apparently they are hijacking "
1407 "DNS failures. Trying to correct for this. We've noticed %d possibly "
1408 "bad addresses so far.",
1409 string_address, strmap_size(dns_wildcard_response_count));
1410 dns_wildcard_one_notice_given = 1;
1412 tor_free(arg);
1415 /** Launch a single request for a nonexistent hostname consisting of between
1416 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1417 * <b>suffix</b> */
1418 static void
1419 launch_wildcard_check(int min_len, int max_len, const char *suffix)
1421 char random_bytes[20], name[64], *addr;
1422 size_t len;
1423 int r;
1425 len = min_len + crypto_rand_int(max_len-min_len+1);
1426 if (crypto_rand(random_bytes, sizeof(random_bytes)) < 0)
1427 return;
1428 base32_encode(name, sizeof(name), random_bytes, sizeof(random_bytes));
1429 name[len] = '\0';
1430 strlcat(name, suffix, sizeof(name));
1432 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1433 "domains with request for bogus hostname \"%s\"", name);
1435 addr = tor_strdup(name);
1436 r = evdns_resolve_ipv4(name, DNS_QUERY_NO_SEARCH,
1437 evdns_wildcard_check_callback, addr);
1438 if (r)
1439 tor_free(addr);
1442 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1443 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1444 static void
1445 launch_test_addresses(int fd, short event, void *args)
1447 or_options_t *options = get_options();
1448 (void)fd;
1449 (void)event;
1450 (void)args;
1452 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1453 "hijack *everything*.");
1454 /* This situation is worse than the failure-hijacking situation. When this
1455 * happens, we're no good for DNS requests at all, and we shouldn't really
1456 * be an exit server.*/
1457 if (!options->ServerDNSTestAddresses)
1458 return;
1459 SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
1461 evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
1462 tor_strdup(address));
1466 #define N_WILDCARD_CHECKS 2
1468 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1469 * hostnames, and see if we can catch our nameserver trying to hijack them and
1470 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1471 * buy these lovely encyclopedias" page. */
1472 static void
1473 dns_launch_wildcard_checks(void)
1475 int i;
1476 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
1477 "to hijack DNS failures.");
1478 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
1479 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1480 * to 'comply' with rfc2606, refrain from giving A records for these.
1481 * This is the standards-compliance equivalent of making sure that your
1482 * crackhouse's elevator inspection certificate is up to date.
1484 launch_wildcard_check(2, 16, ".invalid");
1485 launch_wildcard_check(2, 16, ".test");
1487 /* These will break specs if there are ever any number of
1488 * 8+-character top-level domains. */
1489 launch_wildcard_check(8, 16, "");
1491 /* Try some random .com/org/net domains. This will work fine so long as
1492 * not too many resolve to the same place. */
1493 launch_wildcard_check(8, 16, ".com");
1494 launch_wildcard_check(8, 16, ".org");
1495 launch_wildcard_check(8, 16, ".net");
1499 /** If appropriate, start testing whether our DNS servers tend to lie to
1500 * us. */
1501 void
1502 dns_launch_correctness_checks(void)
1504 static struct event launch_event;
1505 struct timeval timeout;
1506 if (!get_options()->ServerDNSDetectHijacking)
1507 return;
1508 dns_launch_wildcard_checks();
1510 /* Wait a while before launching requests for test addresses, so we can
1511 * get the results from checking for wildcarding. */
1512 evtimer_set(&launch_event, launch_test_addresses, NULL);
1513 timeout.tv_sec = 30;
1514 timeout.tv_usec = 0;
1515 evtimer_add(&launch_event, &timeout);
1518 /** Return true iff our DNS servers lie to us too much to be trustd. */
1520 dns_seems_to_be_broken(void)
1522 return dns_is_completely_invalid;
1525 /** Forget what we've previously learned about our DNS servers' correctness. */
1526 void
1527 dns_reset_correctness_checks(void)
1529 if (dns_wildcard_response_count) {
1530 strmap_free(dns_wildcard_response_count, _tor_free);
1531 dns_wildcard_response_count = NULL;
1533 n_wildcard_requests = 0;
1535 if (dns_wildcard_list) {
1536 SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
1537 smartlist_clear(dns_wildcard_list);
1539 if (dns_wildcarded_test_address_list) {
1540 SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
1541 tor_free(cp));
1542 smartlist_clear(dns_wildcarded_test_address_list);
1544 dns_wildcard_one_notice_given = dns_wildcard_notice_given =
1545 dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
1548 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1549 * returned in response to requests for nonexistent hostnames. */
1550 static int
1551 answer_is_wildcarded(const char *ip)
1553 return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
1556 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1557 static void
1558 assert_resolve_ok(cached_resolve_t *resolve)
1560 tor_assert(resolve);
1561 tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
1562 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
1563 tor_assert(tor_strisnonupper(resolve->address));
1564 if (resolve->state != CACHE_STATE_PENDING) {
1565 tor_assert(!resolve->pending_connections);
1567 if (resolve->state == CACHE_STATE_PENDING ||
1568 resolve->state == CACHE_STATE_DONE) {
1569 tor_assert(!resolve->ttl);
1570 if (resolve->is_reverse)
1571 tor_assert(!resolve->result.hostname);
1572 else
1573 tor_assert(!resolve->result.addr);
1577 #ifdef DEBUG_DNS_CACHE
1578 /** Exit with an assertion if the DNS cache is corrupt. */
1579 static void
1580 _assert_cache_ok(void)
1582 cached_resolve_t **resolve;
1583 int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
1584 if (bad_rep) {
1585 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
1586 tor_assert(!bad_rep);
1589 HT_FOREACH(resolve, cache_map, &cache_root) {
1590 assert_resolve_ok(*resolve);
1591 tor_assert((*resolve)->state != CACHE_STATE_DONE);
1593 if (!cached_resolve_pqueue)
1594 return;
1596 smartlist_pqueue_assert_ok(cached_resolve_pqueue,
1597 _compare_cached_resolves_by_expiry);
1599 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
1601 if (res->state == CACHE_STATE_DONE) {
1602 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1603 tor_assert(!found || found != res);
1604 } else {
1605 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1606 tor_assert(found);
1610 #endif