be more explicit about a harmless thing that freaked veracode out
[tor.git] / src / or / dns.c
blobc45caf09d4ac9ed3cc25520b4f1afce63c6e7ff9
1 /* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char dns_c_id[] =
7 "$Id$";
9 /**
10 * \file dns.c
11 * \brief Implements a local cache for DNS results for Tor servers.
12 * This is implemented as a wrapper around Adam Langley's eventdns.c code.
13 * (We can't just use gethostbyname() and friends because we really need to
14 * be nonblocking.)
15 **/
17 #include "or.h"
18 #include "ht.h"
19 #include "eventdns.h"
21 /** Longest hostname we're willing to resolve. */
22 #define MAX_ADDRESSLEN 256
24 /** How long will we wait for an answer from the resolver before we decide
25 * that the resolver is wedged? */
26 #define RESOLVE_MAX_TIMEOUT 300
28 /** Possible outcomes from hostname lookup: permanent failure,
29 * transient (retryable) failure, and success. */
30 #define DNS_RESOLVE_FAILED_TRANSIENT 1
31 #define DNS_RESOLVE_FAILED_PERMANENT 2
32 #define DNS_RESOLVE_SUCCEEDED 3
34 /** Have we currently configured nameservers with eventdns? */
35 static int nameservers_configured = 0;
36 /** 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 tor_assert(err);
161 /* Don't warn about a single failed nameserver; we'll warn with 'all
162 * nameservers have failed' if we're completely out of nameservers;
163 * otherwise, the situation is tolerable. */
164 severity = LOG_INFO;
165 control_event_server_status(LOG_NOTICE,
166 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
167 ns, escaped(err));
168 tor_free(ns);
169 } else if (!strcmpstart(msg, "Nameserver ") &&
170 (cp=strstr(msg, " is back up"))) {
171 char *ns = tor_strndup(msg+11, cp-(msg+11));
172 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
173 all_down = 0;
174 control_event_server_status(LOG_NOTICE,
175 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
176 tor_free(ns);
177 } else if (!strcmp(msg, "All nameservers have failed")) {
178 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
179 all_down = 1;
181 log(severity, LD_EXIT, "eventdns: %s", msg);
184 /** Helper: generate a good random transaction ID. */
185 static uint16_t
186 dns_get_transaction_id(void)
188 uint16_t result;
189 crypto_rand((void*)&result, sizeof(result));
190 return result;
193 /** Initialize the DNS subsystem; called by the OR process. */
195 dns_init(void)
197 init_cache_map();
198 evdns_set_transaction_id_fn(dns_get_transaction_id);
199 if (server_mode(get_options()))
200 return configure_nameservers(1);
201 return 0;
204 /** Called when DNS-related options change (or may have changed). Returns -1
205 * on failure, 0 on success. */
207 dns_reset(void)
209 or_options_t *options = get_options();
210 if (! server_mode(options)) {
211 evdns_clear_nameservers_and_suspend();
212 evdns_search_clear();
213 nameservers_configured = 0;
214 tor_free(resolv_conf_fname);
215 resolv_conf_mtime = 0;
216 } else {
217 if (configure_nameservers(0) < 0)
218 return -1;
220 return 0;
223 /** Helper: Given a TTL from a DNS response, determine what TTL to give the
224 * OP that asked us to resolve it. */
225 uint32_t
226 dns_clip_ttl(uint32_t ttl)
228 if (ttl < MIN_DNS_TTL)
229 return MIN_DNS_TTL;
230 else if (ttl > MAX_DNS_TTL)
231 return MAX_DNS_TTL;
232 else
233 return ttl;
236 /** Helper: Given a TTL from a DNS response, determine how long to hold it in
237 * our cache. */
238 static uint32_t
239 dns_get_expiry_ttl(uint32_t ttl)
241 if (ttl < MIN_DNS_TTL)
242 return MIN_DNS_TTL;
243 else if (ttl > MAX_DNS_ENTRY_AGE)
244 return MAX_DNS_ENTRY_AGE;
245 else
246 return ttl;
249 /** Helper: free storage held by an entry in the DNS cache. */
250 static void
251 _free_cached_resolve(cached_resolve_t *r)
253 while (r->pending_connections) {
254 pending_connection_t *victim = r->pending_connections;
255 r->pending_connections = victim->next;
256 tor_free(victim);
258 if (r->is_reverse)
259 tor_free(r->result.hostname);
260 r->magic = 0xFF00FF00;
261 tor_free(r);
264 /** Compare two cached_resolve_t pointers by expiry time, and return
265 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
266 * the priority queue implementation. */
267 static int
268 _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
270 const cached_resolve_t *a = _a, *b = _b;
271 return a->expire - b->expire;
274 /** Priority queue of cached_resolve_t objects to let us know when they
275 * will expire. */
276 static smartlist_t *cached_resolve_pqueue = NULL;
278 /** Set an expiry time for a cached_resolve_t, and add it to the expiry
279 * priority queue */
280 static void
281 set_expiry(cached_resolve_t *resolve, time_t expires)
283 tor_assert(resolve && resolve->expire == 0);
284 if (!cached_resolve_pqueue)
285 cached_resolve_pqueue = smartlist_create();
286 resolve->expire = expires;
287 smartlist_pqueue_add(cached_resolve_pqueue,
288 _compare_cached_resolves_by_expiry,
289 resolve);
292 /** Free all storage held in the DNS cache and related structures. */
293 void
294 dns_free_all(void)
296 cached_resolve_t **ptr, **next, *item;
297 assert_cache_ok();
298 if (cached_resolve_pqueue) {
299 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
301 if (res->state == CACHE_STATE_DONE)
302 _free_cached_resolve(res);
305 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
306 item = *ptr;
307 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
308 _free_cached_resolve(item);
310 HT_CLEAR(cache_map, &cache_root);
311 if (cached_resolve_pqueue)
312 smartlist_free(cached_resolve_pqueue);
313 cached_resolve_pqueue = NULL;
314 tor_free(resolv_conf_fname);
317 /** Remove every cached_resolve whose <b>expire</b> time is before or
318 * equal to <b>now</b> from the cache. */
319 static void
320 purge_expired_resolves(time_t now)
322 cached_resolve_t *resolve, *removed;
323 pending_connection_t *pend;
324 edge_connection_t *pendconn;
326 assert_cache_ok();
327 if (!cached_resolve_pqueue)
328 return;
330 while (smartlist_len(cached_resolve_pqueue)) {
331 resolve = smartlist_get(cached_resolve_pqueue, 0);
332 if (resolve->expire > now)
333 break;
334 smartlist_pqueue_pop(cached_resolve_pqueue,
335 _compare_cached_resolves_by_expiry);
337 if (resolve->state == CACHE_STATE_PENDING) {
338 log_debug(LD_EXIT,
339 "Expiring a dns resolve %s that's still pending. Forgot to "
340 "cull it? DNS resolve didn't tell us about the timeout?",
341 escaped_safe_str(resolve->address));
342 } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
343 resolve->state == CACHE_STATE_CACHED_FAILED) {
344 log_debug(LD_EXIT,
345 "Forgetting old cached resolve (address %s, expires %lu)",
346 escaped_safe_str(resolve->address),
347 (unsigned long)resolve->expire);
348 tor_assert(!resolve->pending_connections);
349 } else {
350 tor_assert(resolve->state == CACHE_STATE_DONE);
351 tor_assert(!resolve->pending_connections);
354 if (resolve->pending_connections) {
355 log_debug(LD_EXIT,
356 "Closing pending connections on timed-out DNS resolve!");
357 tor_fragile_assert();
358 while (resolve->pending_connections) {
359 pend = resolve->pending_connections;
360 resolve->pending_connections = pend->next;
361 /* Connections should only be pending if they have no socket. */
362 tor_assert(pend->conn->_base.s == -1);
363 pendconn = pend->conn;
364 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
365 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
366 connection_free(TO_CONN(pendconn));
367 tor_free(pend);
371 if (resolve->state == CACHE_STATE_CACHED_VALID ||
372 resolve->state == CACHE_STATE_CACHED_FAILED ||
373 resolve->state == CACHE_STATE_PENDING) {
374 removed = HT_REMOVE(cache_map, &cache_root, resolve);
375 if (removed != resolve) {
376 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
377 " the cache. Tried to purge %s (%p); instead got %s (%p).",
378 resolve->address, (void*)resolve,
379 removed ? removed->address : "NULL", (void*)remove);
381 tor_assert(removed == resolve);
382 } else {
383 /* This should be in state DONE. Make sure it's not in the cache. */
384 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
385 tor_assert(tmp != resolve);
387 if (resolve->is_reverse)
388 tor_free(resolve->result.hostname);
389 resolve->magic = 0xF0BBF0BB;
390 tor_free(resolve);
393 assert_cache_ok();
396 /** Send a response to the RESOLVE request of a connection.
397 * <b>answer_type</b> must be one of
398 * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
400 * If <b>circ</b> is provided, and we have a cached answer, send the
401 * answer back along circ; otherwise, send the answer back along
402 * <b>conn</b>'s attached circuit.
404 static void
405 send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
407 char buf[RELAY_PAYLOAD_SIZE];
408 size_t buflen;
409 uint32_t ttl;
411 buf[0] = answer_type;
412 ttl = dns_clip_ttl(conn->address_ttl);
414 switch (answer_type)
416 case RESOLVED_TYPE_IPV4:
417 buf[1] = 4;
418 set_uint32(buf+2, htonl(conn->_base.addr));
419 set_uint32(buf+6, htonl(ttl));
420 buflen = 10;
421 break;
422 case RESOLVED_TYPE_ERROR_TRANSIENT:
423 case RESOLVED_TYPE_ERROR:
425 const char *errmsg = "Error resolving hostname";
426 int msglen = strlen(errmsg);
428 buf[1] = msglen;
429 strlcpy(buf+2, errmsg, sizeof(buf)-2);
430 set_uint32(buf+2+msglen, htonl(ttl));
431 buflen = 6+msglen;
432 break;
434 default:
435 tor_assert(0);
436 return;
438 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
440 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
443 /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
444 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
445 * The answer type will be RESOLVED_HOSTNAME.
447 * If <b>circ</b> is provided, and we have a cached answer, send the
448 * answer back along circ; otherwise, send the answer back along
449 * <b>conn</b>'s attached circuit.
451 static void
452 send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
454 char buf[RELAY_PAYLOAD_SIZE];
455 size_t buflen;
456 uint32_t ttl;
457 size_t namelen = strlen(hostname);
458 tor_assert(hostname);
460 tor_assert(namelen < 256);
461 ttl = dns_clip_ttl(conn->address_ttl);
463 buf[0] = RESOLVED_TYPE_HOSTNAME;
464 buf[1] = (uint8_t)namelen;
465 memcpy(buf+2, hostname, namelen);
466 set_uint32(buf+2+namelen, htonl(ttl));
467 buflen = 2+namelen+4;
469 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
470 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
471 // log_notice(LD_EXIT, "Sent");
474 /** Given a lower-case <b>address</b>, check to see whether it's a
475 * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
476 * parse it and place the address in <b>in</b> if present. Return 1 on success;
477 * 0 if the address is not in in-addr.arpa format, and -1 if the address is
478 * malformed. */
479 static int
480 parse_inaddr_arpa_address(const char *address, struct in_addr *in)
482 char buf[INET_NTOA_BUF_LEN];
483 char *cp;
484 size_t len;
485 struct in_addr inaddr;
487 cp = strstr(address, ".in-addr.arpa");
488 if (!cp || *(cp+strlen(".in-addr.arpa")))
489 return 0; /* not an .in-addr.arpa address */
491 len = cp - address;
493 if (len >= INET_NTOA_BUF_LEN)
494 return -1; /* Too long. */
496 memcpy(buf, address, len);
497 buf[len] = '\0';
498 if (tor_inet_aton(buf, &inaddr) == 0)
499 return -1; /* malformed. */
501 if (in) {
502 uint32_t a;
503 /* reverse the bytes */
504 a = ( ((inaddr.s_addr & 0x000000fful) << 24)
505 |((inaddr.s_addr & 0x0000ff00ul) << 8)
506 |((inaddr.s_addr & 0x00ff0000ul) >> 8)
507 |((inaddr.s_addr & 0xff000000ul) >> 24));
508 inaddr.s_addr = a;
510 memcpy(in, &inaddr, sizeof(inaddr));
513 return 1;
516 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
517 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
518 * If resolve failed, free exitconn and return -1.
520 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
521 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
522 * need to send back an END cell, since connection_exit_begin_conn will
523 * do that for us.)
525 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
526 * circuit.
528 * Else, if seen before and pending, add conn to the pending list,
529 * and return 0.
531 * Else, if not seen before, add conn to pending list, hand to
532 * dns farm, and return 0.
534 * Exitconn's on_circuit field must be set, but exitconn should not
535 * yet be linked onto the n_streams/resolving_streams list of that circuit.
536 * On success, link the connection to n_streams if it's an exit connection.
537 * On "pending", link the connection to resolving streams. Otherwise,
538 * clear its on_circuit field.
541 dns_resolve(edge_connection_t *exitconn)
543 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
544 int is_resolve, r;
545 char *hostname = NULL;
546 is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
548 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
549 switch (r) {
550 case 1:
551 /* We got an answer without a lookup -- either the answer was
552 * cached, or it was obvious (like an IP address). */
553 if (is_resolve) {
554 /* Send the answer back right now, and detach. */
555 if (hostname)
556 send_resolved_hostname_cell(exitconn, hostname);
557 else
558 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
559 exitconn->on_circuit = NULL;
560 } else {
561 /* Add to the n_streams list; the calling function will send back a
562 * connected cell. */
563 exitconn->next_stream = oncirc->n_streams;
564 oncirc->n_streams = exitconn;
566 break;
567 case 0:
568 /* The request is pending: add the connection into the linked list of
569 * resolving_streams on this circuit. */
570 exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
571 exitconn->next_stream = oncirc->resolving_streams;
572 oncirc->resolving_streams = exitconn;
573 break;
574 case -2:
575 case -1:
576 /* The request failed before it could start: cancel this connection,
577 * and stop everybody waiting for the same connection. */
578 if (is_resolve) {
579 send_resolved_cell(exitconn,
580 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
583 exitconn->on_circuit = NULL;
585 dns_cancel_pending_resolve(exitconn->_base.address);
587 if (!exitconn->_base.marked_for_close) {
588 connection_free(TO_CONN(exitconn));
589 //XXX020 ... and we just leak exitconn otherwise? -RD
590 // If it's marked for close, it's on closeable_connection_lst in
591 // main.c. If it's on the closeable list, it will get freed from
592 // main.c. -NM
593 // "<armadev> If that's true, there are other bugs around, where we
594 // don't check if it's marked, and will end up double-freeing."
596 break;
597 default:
598 tor_assert(0);
601 tor_free(hostname);
602 return r;
605 /** Helper function for dns_resolve: same functionality, but does not handle:
606 * - marking connections on error and clearing their on_circuit
607 * - linking connections to n_streams/resolving_streams,
608 * - sending resolved cells if we have an answer/error right away,
610 * Return -2 on a transient error. If it's a reverse resolve and it's
611 * successful, sets *<b>hostname_out</b> to a newly allocated string
612 * holding the cached reverse DNS value.
614 static int
615 dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
616 or_circuit_t *oncirc, char **hostname_out)
618 cached_resolve_t *resolve;
619 cached_resolve_t search;
620 pending_connection_t *pending_connection;
621 struct in_addr in;
622 time_t now = time(NULL);
623 int is_reverse = 0, r;
624 assert_connection_ok(TO_CONN(exitconn), 0);
625 tor_assert(exitconn->_base.s == -1);
626 assert_cache_ok();
627 tor_assert(oncirc);
629 /* first check if exitconn->_base.address is an IP. If so, we already
630 * know the answer. */
631 if (tor_inet_aton(exitconn->_base.address, &in) != 0) {
632 exitconn->_base.addr = ntohl(in.s_addr);
633 exitconn->address_ttl = DEFAULT_DNS_TTL;
634 return 1;
636 if (address_is_invalid_destination(exitconn->_base.address, 0)) {
637 log(LOG_PROTOCOL_WARN, LD_EXIT,
638 "Rejecting invalid destination address %s",
639 escaped_safe_str(exitconn->_base.address));
640 return -1;
643 /* then take this opportunity to see if there are any expired
644 * resolves in the hash table. */
645 purge_expired_resolves(now);
647 /* lower-case exitconn->_base.address, so it's in canonical form */
648 tor_strlower(exitconn->_base.address);
650 /* Check whether this is a reverse lookup. If it's malformed, or it's a
651 * .in-addr.arpa address but this isn't a resolve request, kill the
652 * connection.
654 if ((r = parse_inaddr_arpa_address(exitconn->_base.address, NULL)) != 0) {
655 if (r == 1)
656 is_reverse = 1;
658 if (!is_reverse || !is_resolve) {
659 if (!is_reverse)
660 log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
661 escaped_safe_str(exitconn->_base.address));
662 else if (!is_resolve)
663 log_info(LD_EXIT,
664 "Attempt to connect to a .in-addr.arpa address \"%s\"; "
665 "sending error.",
666 escaped_safe_str(exitconn->_base.address));
668 return -1;
670 //log_notice(LD_EXIT, "Looks like an address %s",
671 //exitconn->_base.address);
674 /* now check the hash table to see if 'address' is already there. */
675 strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
676 resolve = HT_FIND(cache_map, &cache_root, &search);
677 if (resolve && resolve->expire > now) { /* already there */
678 switch (resolve->state) {
679 case CACHE_STATE_PENDING:
680 /* add us to the pending list */
681 pending_connection = tor_malloc_zero(
682 sizeof(pending_connection_t));
683 pending_connection->conn = exitconn;
684 pending_connection->next = resolve->pending_connections;
685 resolve->pending_connections = pending_connection;
686 log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
687 "resolve of %s", exitconn->_base.s,
688 escaped_safe_str(exitconn->_base.address));
689 return 0;
690 case CACHE_STATE_CACHED_VALID:
691 log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
692 exitconn->_base.s,
693 escaped_safe_str(resolve->address));
694 exitconn->address_ttl = resolve->ttl;
695 if (resolve->is_reverse) {
696 tor_assert(is_resolve);
697 *hostname_out = tor_strdup(resolve->result.hostname);
698 } else {
699 exitconn->_base.addr = resolve->result.addr;
701 return 1;
702 case CACHE_STATE_CACHED_FAILED:
703 log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
704 exitconn->_base.s,
705 escaped_safe_str(exitconn->_base.address));
706 return -1;
707 case CACHE_STATE_DONE:
708 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
709 tor_fragile_assert();
711 tor_assert(0);
713 tor_assert(!resolve);
714 /* not there, need to add it */
715 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
716 resolve->magic = CACHED_RESOLVE_MAGIC;
717 resolve->state = CACHE_STATE_PENDING;
718 resolve->is_reverse = is_reverse;
719 strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
721 /* add this connection to the pending list */
722 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
723 pending_connection->conn = exitconn;
724 resolve->pending_connections = pending_connection;
726 /* Add this resolve to the cache and priority queue. */
727 HT_INSERT(cache_map, &cache_root, resolve);
728 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
730 log_debug(LD_EXIT,"Launching %s.",
731 escaped_safe_str(exitconn->_base.address));
732 assert_cache_ok();
734 return launch_resolve(exitconn);
737 /** Log an error and abort if conn is waiting for a DNS resolve.
739 void
740 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
742 pending_connection_t *pend;
743 cached_resolve_t **resolve;
745 HT_FOREACH(resolve, cache_map, &cache_root) {
746 for (pend = (*resolve)->pending_connections;
747 pend;
748 pend = pend->next) {
749 tor_assert(pend->conn != conn);
754 /** Log an error and abort if any connection waiting for a DNS resolve is
755 * corrupted. */
756 void
757 assert_all_pending_dns_resolves_ok(void)
759 pending_connection_t *pend;
760 cached_resolve_t **resolve;
762 HT_FOREACH(resolve, cache_map, &cache_root) {
763 for (pend = (*resolve)->pending_connections;
764 pend;
765 pend = pend->next) {
766 assert_connection_ok(TO_CONN(pend->conn), 0);
767 tor_assert(pend->conn->_base.s == -1);
768 tor_assert(!connection_in_array(TO_CONN(pend->conn)));
773 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
775 void
776 connection_dns_remove(edge_connection_t *conn)
778 pending_connection_t *pend, *victim;
779 cached_resolve_t search;
780 cached_resolve_t *resolve;
782 tor_assert(conn->_base.type == CONN_TYPE_EXIT);
783 tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
785 strlcpy(search.address, conn->_base.address, sizeof(search.address));
787 resolve = HT_FIND(cache_map, &cache_root, &search);
788 if (!resolve) {
789 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
790 escaped_safe_str(conn->_base.address));
791 return;
794 tor_assert(resolve->pending_connections);
795 assert_connection_ok(TO_CONN(conn),0);
797 pend = resolve->pending_connections;
799 if (pend->conn == conn) {
800 resolve->pending_connections = pend->next;
801 tor_free(pend);
802 log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
803 "for resolve of %s",
804 conn->_base.s, escaped_safe_str(conn->_base.address));
805 return;
806 } else {
807 for ( ; pend->next; pend = pend->next) {
808 if (pend->next->conn == conn) {
809 victim = pend->next;
810 pend->next = victim->next;
811 tor_free(victim);
812 log_debug(LD_EXIT,
813 "Connection (fd %d) no longer waiting for resolve of %s",
814 conn->_base.s, escaped_safe_str(conn->_base.address));
815 return; /* more are pending */
818 tor_assert(0); /* not reachable unless onlyconn not in pending list */
822 /** Mark all connections waiting for <b>address</b> for close. Then cancel
823 * the resolve for <b>address</b> itself, and remove any cached results for
824 * <b>address</b> from the cache.
826 void
827 dns_cancel_pending_resolve(const char *address)
829 pending_connection_t *pend;
830 cached_resolve_t search;
831 cached_resolve_t *resolve, *tmp;
832 edge_connection_t *pendconn;
833 circuit_t *circ;
835 strlcpy(search.address, address, sizeof(search.address));
837 resolve = HT_FIND(cache_map, &cache_root, &search);
838 if (!resolve)
839 return;
841 if (resolve->state != CACHE_STATE_PENDING) {
842 /* We can get into this state if we never actually created the pending
843 * resolve, due to finding an earlier cached error or something. Just
844 * ignore it. */
845 if (resolve->pending_connections) {
846 log_warn(LD_BUG,
847 "Address %s is not pending but has pending connections!",
848 escaped_safe_str(address));
849 tor_fragile_assert();
851 return;
854 if (!resolve->pending_connections) {
855 log_warn(LD_BUG,
856 "Address %s is pending but has no pending connections!",
857 escaped_safe_str(address));
858 tor_fragile_assert();
859 return;
861 tor_assert(resolve->pending_connections);
863 /* mark all pending connections to fail */
864 log_debug(LD_EXIT,
865 "Failing all connections waiting on DNS resolve of %s",
866 escaped_safe_str(address));
867 while (resolve->pending_connections) {
868 pend = resolve->pending_connections;
869 pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
870 pendconn = pend->conn;
871 assert_connection_ok(TO_CONN(pendconn), 0);
872 tor_assert(pendconn->_base.s == -1);
873 if (!pendconn->_base.marked_for_close) {
874 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
876 circ = circuit_get_by_edge_conn(pendconn);
877 if (circ)
878 circuit_detach_stream(circ, pendconn);
879 if (!pendconn->_base.marked_for_close)
880 connection_free(TO_CONN(pendconn));
881 resolve->pending_connections = pend->next;
882 tor_free(pend);
885 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
886 if (tmp != resolve) {
887 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
888 " the cache. Tried to purge %s (%p); instead got %s (%p).",
889 resolve->address, (void*)resolve,
890 tmp ? tmp->address : "NULL", (void*)tmp);
892 tor_assert(tmp == resolve);
894 resolve->state = CACHE_STATE_DONE;
897 /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
898 * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
899 * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
900 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
902 static void
903 add_answer_to_cache(const char *address, int is_reverse, uint32_t addr,
904 const char *hostname, char outcome, uint32_t ttl)
906 cached_resolve_t *resolve;
907 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
908 return;
910 //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
911 // address, is_reverse?"(reverse)":"", (unsigned long)addr,
912 // hostname?hostname:"NULL",(int)outcome);
914 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
915 resolve->magic = CACHED_RESOLVE_MAGIC;
916 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
917 CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
918 strlcpy(resolve->address, address, sizeof(resolve->address));
919 resolve->is_reverse = is_reverse;
920 if (is_reverse) {
921 if (outcome == DNS_RESOLVE_SUCCEEDED) {
922 tor_assert(hostname);
923 resolve->result.hostname = tor_strdup(hostname);
924 } else {
925 tor_assert(! hostname);
926 resolve->result.hostname = NULL;
928 } else {
929 tor_assert(!hostname);
930 resolve->result.addr = addr;
932 resolve->ttl = ttl;
933 assert_resolve_ok(resolve);
934 HT_INSERT(cache_map, &cache_root, resolve);
935 set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
938 /** Return true iff <b>address</b> is one of the addresses we use to verify
939 * that well-known sites aren't being hijacked by our DNS servers. */
940 static INLINE int
941 is_test_address(const char *address)
943 or_options_t *options = get_options();
944 return options->ServerDNSTestAddresses &&
945 smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
948 /** Called on the OR side when a DNS worker or the eventdns library tells us
949 * the outcome of a DNS resolve: tell all pending connections about the result
950 * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
951 * string containing the address to look up; <b>addr</b> is an IPv4 address in
952 * host order; <b>outcome</b> is one of
953 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
955 static void
956 dns_found_answer(const char *address, int is_reverse, uint32_t addr,
957 const char *hostname, char outcome, uint32_t ttl)
959 pending_connection_t *pend;
960 cached_resolve_t search;
961 cached_resolve_t *resolve, *removed;
962 edge_connection_t *pendconn;
963 circuit_t *circ;
965 assert_cache_ok();
967 strlcpy(search.address, address, sizeof(search.address));
969 resolve = HT_FIND(cache_map, &cache_root, &search);
970 if (!resolve) {
971 int is_test_addr = is_test_address(address);
972 if (!is_test_addr)
973 log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
974 escaped_safe_str(address));
975 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
976 return;
978 assert_resolve_ok(resolve);
980 if (resolve->state != CACHE_STATE_PENDING) {
981 /* XXXX020 Maybe update addr? or check addr for consistency? Or let
982 * VALID replace FAILED? */
983 int is_test_addr = is_test_address(address);
984 if (!is_test_addr)
985 log_notice(LD_EXIT,
986 "Resolved %s which was already resolved; ignoring",
987 escaped_safe_str(address));
988 tor_assert(resolve->pending_connections == NULL);
989 return;
991 /* Removed this assertion: in fact, we'll sometimes get a double answer
992 * to the same question. This can happen when we ask one worker to resolve
993 * X.Y.Z., then we cancel the request, and then we ask another worker to
994 * resolve X.Y.Z. */
995 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
997 while (resolve->pending_connections) {
998 pend = resolve->pending_connections;
999 pendconn = pend->conn; /* don't pass complex things to the
1000 connection_mark_for_close macro */
1001 assert_connection_ok(TO_CONN(pendconn),time(NULL));
1002 pendconn->_base.addr = addr;
1003 pendconn->address_ttl = ttl;
1005 if (outcome != DNS_RESOLVE_SUCCEEDED) {
1006 /* prevent double-remove. */
1007 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1008 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1009 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1010 /* This detach must happen after we send the end cell. */
1011 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1012 } else {
1013 send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
1014 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
1015 /* This detach must happen after we send the resolved cell. */
1016 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1018 connection_free(TO_CONN(pendconn));
1019 } else {
1020 if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
1021 tor_assert(!is_reverse);
1022 /* prevent double-remove. */
1023 pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
1025 circ = circuit_get_by_edge_conn(pend->conn);
1026 tor_assert(circ);
1027 tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1028 /* unlink pend->conn from resolving_streams, */
1029 circuit_detach_stream(circ, pend->conn);
1030 /* and link it to n_streams */
1031 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1032 pend->conn->on_circuit = circ;
1033 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1035 connection_exit_connect(pend->conn);
1036 } else {
1037 /* prevent double-remove. This isn't really an accurate state,
1038 * but it does the right thing. */
1039 pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
1040 if (is_reverse)
1041 send_resolved_hostname_cell(pendconn, hostname);
1042 else
1043 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
1044 circ = circuit_get_by_edge_conn(pendconn);
1045 tor_assert(circ);
1046 circuit_detach_stream(circ, pendconn);
1047 connection_free(TO_CONN(pendconn));
1050 resolve->pending_connections = pend->next;
1051 tor_free(pend);
1054 resolve->state = CACHE_STATE_DONE;
1055 removed = HT_REMOVE(cache_map, &cache_root, &search);
1056 if (removed != resolve) {
1057 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1058 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1059 resolve->address, (void*)resolve,
1060 removed ? removed->address : "NULL", (void*)removed);
1062 assert_resolve_ok(resolve);
1063 assert_cache_ok();
1065 add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
1066 assert_cache_ok();
1069 /** Eventdns helper: return true iff the eventdns result <b>err</b> is
1070 * a transient failure. */
1071 static int
1072 evdns_err_is_transient(int err)
1074 switch (err)
1076 case DNS_ERR_SERVERFAILED:
1077 case DNS_ERR_TRUNCATED:
1078 case DNS_ERR_TIMEOUT:
1079 return 1;
1080 default:
1081 return 0;
1085 /** Configure eventdns nameservers if force is true, or if the configuration
1086 * has changed since the last time we called this function. On Unix, this
1087 * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
1088 * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
1089 * Return 0 on success or -1 on failure. */
1090 static int
1091 configure_nameservers(int force)
1093 or_options_t *options;
1094 const char *conf_fname;
1095 struct stat st;
1096 int r;
1097 options = get_options();
1098 conf_fname = options->ServerDNSResolvConfFile;
1099 #ifndef MS_WINDOWS
1100 if (!conf_fname)
1101 conf_fname = "/etc/resolv.conf";
1102 #endif
1104 evdns_set_log_fn(evdns_log_cb);
1105 if (conf_fname) {
1106 if (stat(conf_fname, &st)) {
1107 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1108 conf_fname, strerror(errno));
1109 return options->ServerDNSAllowBrokenResolvConf ? 0 : -1;
1111 if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
1112 && st.st_mtime == resolv_conf_mtime) {
1113 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1114 return 0;
1116 if (nameservers_configured) {
1117 evdns_search_clear();
1118 evdns_clear_nameservers_and_suspend();
1120 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1121 if ((r = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname))) {
1122 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
1123 conf_fname, conf_fname, r);
1124 return options->ServerDNSAllowBrokenResolvConf ? 0 : -1;
1126 if (evdns_count_nameservers() == 0) {
1127 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
1128 return options->ServerDNSAllowBrokenResolvConf ? 0 : -1;
1130 tor_free(resolv_conf_fname);
1131 resolv_conf_fname = tor_strdup(conf_fname);
1132 resolv_conf_mtime = st.st_mtime;
1133 if (nameservers_configured)
1134 evdns_resume();
1136 #ifdef MS_WINDOWS
1137 else {
1138 if (nameservers_configured) {
1139 evdns_search_clear();
1140 evdns_clear_nameservers_and_suspend();
1142 if (evdns_config_windows_nameservers()) {
1143 log_warn(LD_EXIT,"Could not config nameservers.");
1144 return options->ServerDNSAllowBrokenResolvConf ? 0 : -1;
1146 if (evdns_count_nameservers() == 0) {
1147 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1148 "your Windows configuration. Perhaps you should list a "
1149 "ServerDNSResolvConfFile file in your torrc?");
1150 return options->ServerDNSAllowBrokenResolvConf ? 0 : -1;
1152 if (nameservers_configured)
1153 evdns_resume();
1154 tor_free(resolv_conf_fname);
1155 resolv_conf_mtime = 0;
1157 #endif
1159 if (evdns_count_nameservers() == 1) {
1160 evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
1161 evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
1162 } else {
1163 evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
1164 evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
1167 dns_servers_relaunch_checks();
1169 nameservers_configured = 1;
1170 return 0;
1173 /** For eventdns: Called when we get an answer for a request we launched.
1174 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1176 static void
1177 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1178 void *arg)
1180 char *string_address = arg;
1181 int is_reverse = 0;
1182 int status = DNS_RESOLVE_FAILED_PERMANENT;
1183 uint32_t addr = 0;
1184 const char *hostname = NULL;
1185 int was_wildcarded = 0;
1187 if (result == DNS_ERR_NONE) {
1188 if (type == DNS_IPv4_A && count) {
1189 char answer_buf[INET_NTOA_BUF_LEN+1];
1190 struct in_addr in;
1191 char *escaped_address;
1192 uint32_t *addrs = addresses;
1193 in.s_addr = addrs[0];
1194 addr = ntohl(addrs[0]);
1195 status = DNS_RESOLVE_SUCCEEDED;
1196 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1197 escaped_address = esc_for_log(string_address);
1199 if (answer_is_wildcarded(answer_buf)) {
1200 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1201 "address %s; treating as a failure.",
1202 safe_str(escaped_address),
1203 escaped_safe_str(answer_buf));
1204 was_wildcarded = 1;
1205 addr = 0;
1206 status = DNS_RESOLVE_FAILED_PERMANENT;
1207 } else {
1208 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1209 safe_str(escaped_address),
1210 escaped_safe_str(answer_buf));
1212 tor_free(escaped_address);
1213 } else if (type == DNS_PTR && count) {
1214 char *escaped_address;
1215 is_reverse = 1;
1216 hostname = ((char**)addresses)[0];
1217 status = DNS_RESOLVE_SUCCEEDED;
1218 escaped_address = esc_for_log(string_address);
1219 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1220 safe_str(escaped_address),
1221 escaped_safe_str(hostname));
1222 tor_free(escaped_address);
1223 } else if (count) {
1224 log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
1225 escaped_safe_str(string_address));
1226 } else {
1227 log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
1228 escaped_safe_str(string_address));
1230 } else {
1231 if (evdns_err_is_transient(result))
1232 status = DNS_RESOLVE_FAILED_TRANSIENT;
1234 if (was_wildcarded) {
1235 if (is_test_address(string_address)) {
1236 /* Ick. We're getting redirected on known-good addresses. Our DNS
1237 * server must really hate us. */
1238 add_wildcarded_test_address(string_address);
1241 if (result != DNS_ERR_SHUTDOWN)
1242 dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
1243 tor_free(string_address);
1246 /** For eventdns: start resolving as necessary to find the target for
1247 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1248 * 0 on "resolve launched." */
1249 static int
1250 launch_resolve(edge_connection_t *exitconn)
1252 char *addr = tor_strdup(exitconn->_base.address);
1253 struct in_addr in;
1254 int r;
1255 int options = get_options()->ServerDNSSearchDomains ? 0
1256 : DNS_QUERY_NO_SEARCH;
1257 /* What? Nameservers not configured? Sounds like a bug. */
1258 if (!nameservers_configured) {
1259 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1260 "launched. Configuring.");
1261 if (configure_nameservers(1) < 0)
1262 return -1;
1265 r = parse_inaddr_arpa_address(exitconn->_base.address, &in);
1266 if (r == 0) {
1267 log_info(LD_EXIT, "Launching eventdns request for %s",
1268 escaped_safe_str(exitconn->_base.address));
1269 r = evdns_resolve_ipv4(exitconn->_base.address, options,
1270 evdns_callback, addr);
1271 } else if (r == 1) {
1272 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1273 escaped_safe_str(exitconn->_base.address));
1274 r = evdns_resolve_reverse(&in, DNS_QUERY_NO_SEARCH,
1275 evdns_callback, addr);
1276 } else if (r == -1) {
1277 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1280 if (r) {
1281 log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
1282 escaped_safe_str(addr), r);
1283 r = evdns_err_is_transient(r) ? -2 : -1;
1284 tor_free(addr); /* There is no evdns request in progress; stop
1285 * addr from getting leaked. */
1287 return r;
1290 /** How many requests for bogus addresses have we launched so far? */
1291 static int n_wildcard_requests = 0;
1293 /** Map from dotted-quad IP address in response to an int holding how many
1294 * times we've seen it for a randomly generated (hopefully bogus) address. It
1295 * would be easier to use definitely-invalid addresses (as specified by
1296 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1297 static strmap_t *dns_wildcard_response_count = NULL;
1299 /** If present, a list of dotted-quad IP addresses that we are pretty sure our
1300 * nameserver wants to return in response to requests for nonexistent domains.
1302 static smartlist_t *dns_wildcard_list = NULL;
1303 /** True iff we've logged about a single address getting wildcarded.
1304 * Subsequent warnings will be less severe. */
1305 static int dns_wildcard_one_notice_given = 0;
1306 /** True iff we've warned that our DNS server is wildcarding too many failures.
1308 static int dns_wildcard_notice_given = 0;
1310 /** List of supposedly good addresses that are getting wildcarded to the
1311 * same addresses as nonexistent addresses. */
1312 static smartlist_t *dns_wildcarded_test_address_list = NULL;
1313 /** True iff we've warned about a test address getting wildcarded */
1314 static int dns_wildcarded_test_address_notice_given = 0;
1315 /** True iff all addresses seem to be getting wildcarded. */
1316 static int dns_is_completely_invalid = 0;
1318 /** Called when we see <b>id</b> (a dotted quad) in response to a request for
1319 * a hopefully bogus address. */
1320 static void
1321 wildcard_increment_answer(const char *id)
1323 int *ip;
1324 if (!dns_wildcard_response_count)
1325 dns_wildcard_response_count = strmap_new();
1327 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1328 if (!ip) {
1329 ip = tor_malloc_zero(sizeof(int));
1330 strmap_set(dns_wildcard_response_count, id, ip);
1332 ++*ip;
1334 if (*ip > 5 && n_wildcard_requests > 10) {
1335 if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
1336 if (!smartlist_string_isin(dns_wildcard_list, id)) {
1337 log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1338 "Your DNS provider has given \"%s\" as an answer for %d different "
1339 "invalid addresses. Apparently they are hijacking DNS failures. "
1340 "I'll try to correct for this by treating future occurrences of "
1341 "\"%s\" as 'not found'.", id, *ip, id);
1342 smartlist_add(dns_wildcard_list, tor_strdup(id));
1344 if (!dns_wildcard_notice_given)
1345 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1346 dns_wildcard_notice_given = 1;
1350 /** Note that a single test address (one believed to be good) seems to be
1351 * getting redirected to the same IP as failures are. */
1352 static void
1353 add_wildcarded_test_address(const char *address)
1355 int n, n_test_addrs;
1356 if (!dns_wildcarded_test_address_list)
1357 dns_wildcarded_test_address_list = smartlist_create();
1359 if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
1360 return;
1362 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1363 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1365 smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
1366 n = smartlist_len(dns_wildcarded_test_address_list);
1367 if (n > n_test_addrs/2) {
1368 log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
1369 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1370 "address. It has done this with %d test addresses so far. I'm "
1371 "going to stop being an exit node for now, since our DNS seems so "
1372 "broken.", address, n);
1373 if (!dns_is_completely_invalid) {
1374 dns_is_completely_invalid = 1;
1375 mark_my_descriptor_dirty();
1377 if (!dns_wildcarded_test_address_notice_given)
1378 control_event_server_status(LOG_WARN, "DNS_USELESS");
1379 dns_wildcarded_test_address_notice_given = 1;
1383 /** Callback function when we get an answer (possibly failing) for a request
1384 * for a (hopefully) nonexistent domain. */
1385 static void
1386 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1387 void *addresses, void *arg)
1389 (void)ttl;
1390 ++n_wildcard_requests;
1391 if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
1392 uint32_t *addrs = addresses;
1393 int i;
1394 char *string_address = arg;
1395 for (i = 0; i < count; ++i) {
1396 char answer_buf[INET_NTOA_BUF_LEN+1];
1397 struct in_addr in;
1398 in.s_addr = addrs[i];
1399 tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1400 wildcard_increment_answer(answer_buf);
1402 log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
1403 "Your DNS provider gave an answer for \"%s\", which "
1404 "is not supposed to exist. Apparently they are hijacking "
1405 "DNS failures. Trying to correct for this. We've noticed %d possibly "
1406 "bad addresses so far.",
1407 string_address, strmap_size(dns_wildcard_response_count));
1408 dns_wildcard_one_notice_given = 1;
1410 tor_free(arg);
1413 /** Launch a single request for a nonexistent hostname consisting of between
1414 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
1415 * <b>suffix</b> */
1416 static void
1417 launch_wildcard_check(int min_len, int max_len, const char *suffix)
1419 char *addr;
1420 int r;
1422 addr = crypto_random_hostname(min_len, max_len, "", suffix);
1423 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1424 "domains with request for bogus hostname \"%s\"", addr);
1426 r = evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
1427 addr,
1428 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1429 /* This "addr" is an argument to the callback*/ addr);
1430 if (r) {
1431 /* There is no evdns request in progress; stop addr from getting leaked */
1432 tor_free(addr);
1436 /** Launch attempts to resolve a bunch of known-good addresses (configured in
1437 * ServerDNSTestAddresses). [Callback for a libevent timer] */
1438 static void
1439 launch_test_addresses(int fd, short event, void *args)
1441 or_options_t *options = get_options();
1442 (void)fd;
1443 (void)event;
1444 (void)args;
1446 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1447 "hijack *everything*.");
1448 /* This situation is worse than the failure-hijacking situation. When this
1449 * happens, we're no good for DNS requests at all, and we shouldn't really
1450 * be an exit server.*/
1451 if (!options->ServerDNSTestAddresses)
1452 return;
1453 SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
1455 int r = evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
1456 tor_strdup(address));
1457 if (r)
1458 log_info(LD_EXIT, "eventdns rejected test address %s: error %d",
1459 escaped_safe_str(address), r);
1463 #define N_WILDCARD_CHECKS 2
1465 /** Launch DNS requests for a few nonexistent hostnames and a few well-known
1466 * hostnames, and see if we can catch our nameserver trying to hijack them and
1467 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
1468 * buy these lovely encyclopedias" page. */
1469 static void
1470 dns_launch_wildcard_checks(void)
1472 int i;
1473 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
1474 "to hijack DNS failures.");
1475 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
1476 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
1477 * to 'comply' with rfc2606, refrain from giving A records for these.
1478 * This is the standards-compliance equivalent of making sure that your
1479 * crackhouse's elevator inspection certificate is up to date.
1481 launch_wildcard_check(2, 16, ".invalid");
1482 launch_wildcard_check(2, 16, ".test");
1484 /* These will break specs if there are ever any number of
1485 * 8+-character top-level domains. */
1486 launch_wildcard_check(8, 16, "");
1488 /* Try some random .com/org/net domains. This will work fine so long as
1489 * not too many resolve to the same place. */
1490 launch_wildcard_check(8, 16, ".com");
1491 launch_wildcard_check(8, 16, ".org");
1492 launch_wildcard_check(8, 16, ".net");
1496 /** If appropriate, start testing whether our DNS servers tend to lie to
1497 * us. */
1498 void
1499 dns_launch_correctness_checks(void)
1501 static struct event launch_event;
1502 struct timeval timeout;
1503 if (!get_options()->ServerDNSDetectHijacking)
1504 return;
1505 dns_launch_wildcard_checks();
1507 /* Wait a while before launching requests for test addresses, so we can
1508 * get the results from checking for wildcarding. */
1509 evtimer_set(&launch_event, launch_test_addresses, NULL);
1510 timeout.tv_sec = 30;
1511 timeout.tv_usec = 0;
1512 if (evtimer_add(&launch_event, &timeout)<0) {
1513 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
1517 /** Return true iff our DNS servers lie to us too much to be trustd. */
1519 dns_seems_to_be_broken(void)
1521 return dns_is_completely_invalid;
1524 /** Forget what we've previously learned about our DNS servers' correctness. */
1525 void
1526 dns_reset_correctness_checks(void)
1528 if (dns_wildcard_response_count) {
1529 strmap_free(dns_wildcard_response_count, _tor_free);
1530 dns_wildcard_response_count = NULL;
1532 n_wildcard_requests = 0;
1534 if (dns_wildcard_list) {
1535 SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
1536 smartlist_clear(dns_wildcard_list);
1538 if (dns_wildcarded_test_address_list) {
1539 SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
1540 tor_free(cp));
1541 smartlist_clear(dns_wildcarded_test_address_list);
1543 dns_wildcard_one_notice_given = dns_wildcard_notice_given =
1544 dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
1547 /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
1548 * returned in response to requests for nonexistent hostnames. */
1549 static int
1550 answer_is_wildcarded(const char *ip)
1552 return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
1555 /** Exit with an assertion if <b>resolve</b> is corrupt. */
1556 static void
1557 assert_resolve_ok(cached_resolve_t *resolve)
1559 tor_assert(resolve);
1560 tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
1561 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
1562 tor_assert(tor_strisnonupper(resolve->address));
1563 if (resolve->state != CACHE_STATE_PENDING) {
1564 tor_assert(!resolve->pending_connections);
1566 if (resolve->state == CACHE_STATE_PENDING ||
1567 resolve->state == CACHE_STATE_DONE) {
1568 tor_assert(!resolve->ttl);
1569 if (resolve->is_reverse)
1570 tor_assert(!resolve->result.hostname);
1571 else
1572 tor_assert(!resolve->result.addr);
1576 #ifdef DEBUG_DNS_CACHE
1577 /** Exit with an assertion if the DNS cache is corrupt. */
1578 static void
1579 _assert_cache_ok(void)
1581 cached_resolve_t **resolve;
1582 int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
1583 if (bad_rep) {
1584 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
1585 tor_assert(!bad_rep);
1588 HT_FOREACH(resolve, cache_map, &cache_root) {
1589 assert_resolve_ok(*resolve);
1590 tor_assert((*resolve)->state != CACHE_STATE_DONE);
1592 if (!cached_resolve_pqueue)
1593 return;
1595 smartlist_pqueue_assert_ok(cached_resolve_pqueue,
1596 _compare_cached_resolves_by_expiry);
1598 SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
1600 if (res->state == CACHE_STATE_DONE) {
1601 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1602 tor_assert(!found || found != res);
1603 } else {
1604 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
1605 tor_assert(found);
1609 #endif