Tor 0.4.9.2-alpha-dev
All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
dns.c
Go to the documentation of this file.
1/* Copyright (c) 2003-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
4/* See LICENSE for licensing information */
5
6/**
7 * \file dns.c
8 * \brief Implements a local cache for DNS results for Tor servers.
9 * This is implemented as a wrapper around Adam Langley's eventdns.c code.
10 * (We can't just use gethostbyname() and friends because we really need to
11 * be nonblocking.)
12 *
13 * There are three main cases when a Tor relay uses dns.c to launch a DNS
14 * request:
15 * <ol>
16 * <li>To check whether the DNS server is working more or less correctly.
17 * This happens via dns_launch_correctness_checks(). The answer is
18 * reported in the return value from later calls to
19 * dns_seems_to_be_broken().
20 * <li>When a client has asked the relay, in a RELAY_BEGIN cell, to connect
21 * to a given server by hostname. This happens via dns_resolve().
22 * <li>When a client has asked the relay, in a RELAY_RESOLVE cell, to look
23 * up a given server's IP address(es) by hostname. This also happens via
24 * dns_resolve().
25 * </ol>
26 *
27 * Each of these gets handled a little differently.
28 *
29 * To check for correctness, we look up some hostname we expect to exist and
30 * have real entries, some hostnames which we expect to definitely not exist,
31 * and some hostnames that we expect to probably not exist. If too many of
32 * the hostnames that shouldn't exist do exist, that's a DNS hijacking
33 * attempt. If too many of the hostnames that should exist have the same
34 * addresses as the ones that shouldn't exist, that's a very bad DNS hijacking
35 * attempt, or a very naughty captive portal. And if the hostnames that
36 * should exist simply don't exist, we probably have a broken nameserver.
37 *
38 * To handle client requests, we first check our cache for answers. If there
39 * isn't something up-to-date, we've got to launch A or AAAA requests as
40 * appropriate. How we handle responses to those in particular is a bit
41 * complex; see dns_lookup() and set_exitconn_info_from_resolve().
42 *
43 * When a lookup is finally complete, the inform_pending_connections()
44 * function will tell all of the streams that have been waiting for the
45 * resolve, by calling connection_exit_connect() if the client sent a
46 * RELAY_BEGIN cell, and by calling send_resolved_cell() or
47 * send_hostname_cell() if the client sent a RELAY_RESOLVE cell.
48 **/
49
50#define DNS_PRIVATE
51
52#include "core/or/or.h"
53#include "app/config/config.h"
57#include "core/or/circuitlist.h"
58#include "core/or/circuituse.h"
60#include "core/or/policies.h"
61#include "core/or/relay.h"
63#include "feature/relay/dns.h"
70#include "lib/sandbox/sandbox.h"
71
73#include "core/or/or_circuit_st.h"
75
76#include "ht.h"
77
78#ifdef HAVE_SYS_STAT_H
79#include <sys/stat.h>
80#endif
81
82#include <event2/event.h>
83#include <event2/dns.h>
84
85/** How long will we wait for an answer from the resolver before we decide
86 * that the resolver is wedged? */
87#define RESOLVE_MAX_TIMEOUT 300
88
89/** Our evdns_base; this structure handles all our name lookups. */
90static struct evdns_base *the_evdns_base = NULL;
91
92/** Have we currently configured nameservers with eventdns? */
94/** Did our most recent attempt to configure nameservers with eventdns fail? */
96/** What was the resolv_conf fname we last used when configuring the
97 * nameservers? Used to check whether we need to reconfigure. */
98static char *resolv_conf_fname = NULL;
99/** What was the mtime on the resolv.conf file we last used when configuring
100 * the nameservers? Used to check whether we need to reconfigure. */
101static time_t resolv_conf_mtime = 0;
102
103static void purge_expired_resolves(time_t now);
104static void dns_found_answer(const char *address, uint8_t query_type,
105 int dns_answer,
106 const tor_addr_t *addr,
107 const char *hostname,
108 uint32_t ttl);
109static void add_wildcarded_test_address(const char *address);
110static int configure_nameservers(int force);
111static int answer_is_wildcarded(const char *ip);
112static int evdns_err_is_transient(int err);
113static void inform_pending_connections(cached_resolve_t *resolve);
115static void configure_libevent_options(void);
116
117#ifdef DEBUG_DNS_CACHE
118static void assert_cache_ok_(void);
119#define assert_cache_ok() assert_cache_ok_()
120#else
121#define assert_cache_ok() STMT_NIL
122#endif /* defined(DEBUG_DNS_CACHE) */
123static void assert_resolve_ok(cached_resolve_t *resolve);
124
125/** Hash table of cached_resolve objects. */
126static HT_HEAD(cache_map, cached_resolve_t) cache_root;
127
128/** Global: how many IPv6 requests have we made in all? */
129static uint64_t n_ipv6_requests_made = 0;
130/** Global: how many IPv6 requests have timed out? */
131static uint64_t n_ipv6_timeouts = 0;
132/** Global: Do we think that IPv6 DNS is broken? */
133static int dns_is_broken_for_ipv6 = 0;
134
135/** Function to compare hashed resolves on their addresses; used to
136 * implement hash tables. */
137static inline int
138cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
139{
140 /* make this smarter one day? */
141 assert_resolve_ok(a); // Not b; b may be just a search.
142 return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
143}
144
145/** Hash function for cached_resolve objects */
146static inline unsigned int
148{
149 return (unsigned) siphash24g((const uint8_t*)a->address, strlen(a->address));
150}
151
153 cached_resolves_eq);
154HT_GENERATE2(cache_map, cached_resolve_t, node, cached_resolve_hash,
155 cached_resolves_eq, 0.6, tor_reallocarray_, tor_free_);
156
157/** Initialize the DNS cache. */
158static void
160{
161 HT_INIT(cache_map, &cache_root);
162}
163
164/** Helper: called by eventdns when eventdns wants to log something. */
165static void
166evdns_log_cb(int warn, const char *msg)
167{
168 const char *cp;
169 static int all_down = 0;
170 int severity = warn ? LOG_WARN : LOG_INFO;
171 if (!strcmpstart(msg, "Resolve requested for") &&
172 get_options()->SafeLogging) {
173 log_info(LD_EXIT, "eventdns: Resolve requested.");
174 return;
175 } else if (!strcmpstart(msg, "Search: ")) {
176 return;
177 }
178 if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
179 char *ns = tor_strndup(msg+11, cp-(msg+11));
180 const char *colon = strchr(cp, ':');
181 tor_assert(colon);
182 const char *err = colon+2;
183 /* Don't warn about a single failed nameserver; we'll warn with 'all
184 * nameservers have failed' if we're completely out of nameservers;
185 * otherwise, the situation is tolerable. */
186 severity = LOG_INFO;
188 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
189 ns, escaped(err));
190 tor_free(ns);
191 } else if (!strcmpstart(msg, "Nameserver ") &&
192 (cp=strstr(msg, " is back up"))) {
193 char *ns = tor_strndup(msg+11, cp-(msg+11));
194 severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
195 all_down = 0;
197 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
198 tor_free(ns);
199 } else if (!strcmp(msg, "All nameservers have failed")) {
200 control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
201 all_down = 1;
202 } else if (!strcmpstart(msg, "Address mismatch on received DNS")) {
203 static ratelim_t mismatch_limit = RATELIM_INIT(3600);
204 const char *src = strstr(msg, " Apparent source");
205 if (!src || get_options()->SafeLogging) {
206 src = "";
207 }
208 log_fn_ratelim(&mismatch_limit, severity, LD_EXIT,
209 "eventdns: Received a DNS packet from "
210 "an IP address to which we did not send a request. This "
211 "could be a DNS spoofing attempt, or some kind of "
212 "misconfiguration.%s", src);
213 return;
214 }
215 tor_log(severity, LD_EXIT, "eventdns: %s", msg);
216}
217
218/** New consensus just appeared, take appropriate actions if need be. */
219void
221{
222 (void) ns;
223
224 /* Consensus has parameters for the Exit relay DNS side and so we only reset
225 * the DNS nameservers if we are in server mode. */
226 if (server_mode(get_options())) {
228 }
229}
230
231/** Initialize the DNS subsystem; called by the OR process. */
232int
234{
236 if (server_mode(get_options())) {
237 int r = configure_nameservers(1);
238 return r;
239 }
240 return 0;
241}
242
243/** Called when DNS-related options change (or may have changed). Returns -1
244 * on failure, 0 on success. */
245int
247{
248 const or_options_t *options = get_options();
249 if (! server_mode(options)) {
250
251 if (!the_evdns_base) {
252 if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
253 log_err(LD_BUG, "Couldn't create an evdns_base");
254 return -1;
255 }
256 }
257
258 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
259 evdns_base_search_clear(the_evdns_base);
263 } else {
264 if (configure_nameservers(0) < 0) {
265 return -1;
266 }
267 }
268 return 0;
269}
270
271/** Return true iff the most recent attempt to initialize the DNS subsystem
272 * failed. */
273int
275{
277}
278
279/** Helper: free storage held by an entry in the DNS cache. */
280static void
282{
283 if (!r)
284 return;
285 while (r->pending_connections) {
287 r->pending_connections = victim->next;
288 tor_free(victim);
289 }
290 if (r->res_status_hostname == RES_STATUS_DONE_OK)
291 tor_free(r->result_ptr.hostname);
292 r->magic = 0xFF00FF00;
293 tor_free(r);
294}
295
296/** Compare two cached_resolve_t pointers by expiry time, and return
297 * less-than-zero, zero, or greater-than-zero as appropriate. Used for
298 * the priority queue implementation. */
299static int
300compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
301{
302 const cached_resolve_t *a = _a, *b = _b;
303 if (a->expire < b->expire)
304 return -1;
305 else if (a->expire == b->expire)
306 return 0;
307 else
308 return 1;
309}
310
311/** Priority queue of cached_resolve_t objects to let us know when they
312 * will expire. */
314
315static void
316cached_resolve_add_answer(cached_resolve_t *resolve,
317 int query_type,
318 int dns_result,
319 const tor_addr_t *answer_addr,
320 const char *answer_hostname,
321 uint32_t ttl)
322{
323 if (query_type == DNS_PTR) {
324 if (resolve->res_status_hostname != RES_STATUS_INFLIGHT)
325 return;
326
327 if (dns_result == DNS_ERR_NONE && answer_hostname) {
328 resolve->result_ptr.hostname = tor_strdup(answer_hostname);
329 resolve->res_status_hostname = RES_STATUS_DONE_OK;
330 } else {
331 resolve->result_ptr.err_hostname = dns_result;
332 resolve->res_status_hostname = RES_STATUS_DONE_ERR;
333 }
334 resolve->ttl_hostname = ttl;
335 } else if (query_type == DNS_IPv4_A) {
336 if (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT)
337 return;
338
339 if (dns_result == DNS_ERR_NONE && answer_addr &&
340 tor_addr_family(answer_addr) == AF_INET) {
341 resolve->result_ipv4.addr_ipv4 = tor_addr_to_ipv4h(answer_addr);
342 resolve->res_status_ipv4 = RES_STATUS_DONE_OK;
343 } else {
344 resolve->result_ipv4.err_ipv4 = dns_result;
345 resolve->res_status_ipv4 = RES_STATUS_DONE_ERR;
346 }
347 resolve->ttl_ipv4 = ttl;
348 } else if (query_type == DNS_IPv6_AAAA) {
349 if (resolve->res_status_ipv6 != RES_STATUS_INFLIGHT)
350 return;
351
352 if (dns_result == DNS_ERR_NONE && answer_addr &&
353 tor_addr_family(answer_addr) == AF_INET6) {
354 memcpy(&resolve->result_ipv6.addr_ipv6,
355 tor_addr_to_in6(answer_addr),
356 sizeof(struct in6_addr));
357 resolve->res_status_ipv6 = RES_STATUS_DONE_OK;
358 } else {
359 resolve->result_ipv6.err_ipv6 = dns_result;
360 resolve->res_status_ipv6 = RES_STATUS_DONE_ERR;
361 }
362 resolve->ttl_ipv6 = ttl;
363 }
364}
365
366/** Return true iff there are no in-flight requests for <b>resolve</b>. */
367static int
369{
370 return (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT &&
371 resolve->res_status_ipv6 != RES_STATUS_INFLIGHT &&
372 resolve->res_status_hostname != RES_STATUS_INFLIGHT);
373}
374
375/** Set an expiry time for a cached_resolve_t, and add it to the expiry
376 * priority queue */
377static void
378set_expiry(cached_resolve_t *resolve, time_t expires)
379{
380 tor_assert(resolve && resolve->expire == 0);
383 resolve->expire = expires;
386 offsetof(cached_resolve_t, minheap_idx),
387 resolve);
388}
389
390/** Free all storage held in the DNS cache and related structures. */
391void
393{
394 cached_resolve_t **ptr, **next, *item;
395 assert_cache_ok();
398 {
399 if (res->state == CACHE_STATE_DONE)
401 });
402 }
403 for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
404 item = *ptr;
405 next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
407 }
408 HT_CLEAR(cache_map, &cache_root);
409 smartlist_free(cached_resolve_pqueue);
412}
413
414/** Remove every cached_resolve whose <b>expire</b> time is before or
415 * equal to <b>now</b> from the cache. */
416static void
418{
419 cached_resolve_t *resolve, *removed;
421 edge_connection_t *pendconn;
422
423 assert_cache_ok();
425 return;
426
427 while (smartlist_len(cached_resolve_pqueue)) {
428 resolve = smartlist_get(cached_resolve_pqueue, 0);
429 if (resolve->expire > now)
430 break;
433 offsetof(cached_resolve_t, minheap_idx));
434
435 if (resolve->state == CACHE_STATE_PENDING) {
436 log_debug(LD_EXIT,
437 "Expiring a dns resolve %s that's still pending. Forgot to "
438 "cull it? DNS resolve didn't tell us about the timeout?",
439 escaped_safe_str(resolve->address));
440 } else if (resolve->state == CACHE_STATE_CACHED) {
441 log_debug(LD_EXIT,
442 "Forgetting old cached resolve (address %s, expires %lu)",
443 escaped_safe_str(resolve->address),
444 (unsigned long)resolve->expire);
446 } else {
447 tor_assert(resolve->state == CACHE_STATE_DONE);
449 }
450
451 if (resolve->pending_connections) {
452 log_debug(LD_EXIT,
453 "Closing pending connections on timed-out DNS resolve!");
454 while (resolve->pending_connections) {
455 pend = resolve->pending_connections;
456 resolve->pending_connections = pend->next;
457 /* Connections should only be pending if they have no socket. */
458 tor_assert(!SOCKET_OK(pend->conn->base_.s));
459 pendconn = pend->conn;
460 /* Prevent double-remove */
461 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
462 if (!pendconn->base_.marked_for_close) {
463 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
465 connection_free_(TO_CONN(pendconn));
466 }
467 tor_free(pend);
468 }
469 }
470
471 if (resolve->state == CACHE_STATE_CACHED ||
472 resolve->state == CACHE_STATE_PENDING) {
473 removed = HT_REMOVE(cache_map, &cache_root, resolve);
474 if (removed != resolve) {
475 log_err(LD_BUG, "The expired resolve we purged didn't match any in"
476 " the cache. Tried to purge %s (%p); instead got %s (%p).",
477 resolve->address, (void*)resolve,
478 removed ? removed->address : "NULL", (void*)removed);
479 }
480 tor_assert(removed == resolve);
481 } else {
482 /* This should be in state DONE. Make sure it's not in the cache. */
483 cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
484 tor_assert(tmp != resolve);
485 }
486 if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
487 tor_free(resolve->result_ptr.hostname);
488 resolve->magic = 0xF0BBF0BB;
489 tor_free(resolve);
490 }
491
492 assert_cache_ok();
493}
494
495/* argument for send_resolved_cell only, meaning "let the answer type be ipv4
496 * or ipv6 depending on the connection's address". */
497#define RESOLVED_TYPE_AUTO 0xff
498
499/** Send a response to the RESOLVE request of a connection.
500 * <b>answer_type</b> must be one of
501 * RESOLVED_TYPE_(AUTO|ERROR|ERROR_TRANSIENT|).
502 *
503 * If <b>circ</b> is provided, and we have a cached answer, send the
504 * answer back along circ; otherwise, send the answer back along
505 * <b>conn</b>'s attached circuit.
506 */
507MOCK_IMPL(STATIC void,
508send_resolved_cell,(edge_connection_t *conn, uint8_t answer_type,
509 const cached_resolve_t *resolved))
510{
511 // (We use the minimum here to ensure that we never
512 // generate a too-big message.)
513 char buf[RELAY_PAYLOAD_SIZE_MIN], *cp = buf;
514 size_t buflen = 0;
515 uint32_t ttl;
516
517 buf[0] = answer_type;
518 ttl = conn->address_ttl;
519
520 switch (answer_type)
521 {
522 case RESOLVED_TYPE_AUTO:
523 if (resolved && resolved->res_status_ipv4 == RES_STATUS_DONE_OK) {
524 cp[0] = RESOLVED_TYPE_IPV4;
525 cp[1] = 4;
526 set_uint32(cp+2, htonl(resolved->result_ipv4.addr_ipv4));
527 set_uint32(cp+6, htonl(ttl));
528 cp += 10;
529 }
530 if (resolved && resolved->res_status_ipv6 == RES_STATUS_DONE_OK) {
531 const uint8_t *bytes = resolved->result_ipv6.addr_ipv6.s6_addr;
532 cp[0] = RESOLVED_TYPE_IPV6;
533 cp[1] = 16;
534 memcpy(cp+2, bytes, 16);
535 set_uint32(cp+18, htonl(ttl));
536 cp += 22;
537 }
538 if (cp != buf) {
539 buflen = cp - buf;
540 break;
541 } else {
542 answer_type = RESOLVED_TYPE_ERROR;
543 /* We let this fall through and treat it as an error. */
544 }
545 FALLTHROUGH;
546 case RESOLVED_TYPE_ERROR_TRANSIENT:
547 case RESOLVED_TYPE_ERROR:
548 {
549 const char *errmsg = "Error resolving hostname";
550 size_t msglen = strlen(errmsg);
551
552 buf[0] = answer_type;
553 buf[1] = msglen;
554 strlcpy(buf+2, errmsg, sizeof(buf)-2);
555 set_uint32(buf+2+msglen, htonl(ttl));
556 buflen = 6+msglen;
557 break;
558 }
559 default:
560 tor_assert(0);
561 return;
562 }
563 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
564
565 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
566}
567
568void
569dns_send_resolved_error_cell(edge_connection_t *conn, uint8_t answer_type)
570{
571 send_resolved_cell(conn, answer_type, NULL);
572}
573
574/** Send a response to the RESOLVE request of a connection for an in-addr.arpa
575 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
576 * The answer type will be RESOLVED_HOSTNAME.
577 *
578 * If <b>circ</b> is provided, and we have a cached answer, send the
579 * answer back along circ; otherwise, send the answer back along
580 * <b>conn</b>'s attached circuit.
581 */
582MOCK_IMPL(STATIC void,
584 const char *hostname))
585{
586 char buf[RELAY_PAYLOAD_SIZE_MAX];
587 size_t buflen;
588 uint32_t ttl;
589
590 if (BUG(!hostname))
591 return;
592
593 size_t namelen = strlen(hostname);
594
595 if (BUG(namelen >= 256)) {
596 return;
597 }
598 ttl = conn->address_ttl;
599
600 buf[0] = RESOLVED_TYPE_HOSTNAME;
601 buf[1] = (uint8_t)namelen;
602 memcpy(buf+2, hostname, namelen);
603 set_uint32(buf+2+namelen, htonl(ttl));
604 buflen = 2+namelen+4;
605
606 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
607 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
608 // log_notice(LD_EXIT, "Sent");
609}
610
611/** See if we have a cache entry for <b>exitconn</b>->address. If so,
612 * if resolve valid, put it into <b>exitconn</b>->addr and return 1.
613 * If resolve failed, free exitconn and return -1.
614 *
615 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
616 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
617 * need to send back an END cell, since connection_exit_begin_conn will
618 * do that for us.)
619 *
620 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
621 * circuit.
622 *
623 * Else, if seen before and pending, add conn to the pending list,
624 * and return 0.
625 *
626 * Else, if not seen before, add conn to pending list, hand to
627 * dns farm, and return 0.
628 *
629 * Exitconn's on_circuit field must be set, but exitconn should not
630 * yet be linked onto the n_streams/resolving_streams list of that circuit.
631 * On success, link the connection to n_streams if it's an exit connection.
632 * On "pending", link the connection to resolving streams. Otherwise,
633 * clear its on_circuit field.
634 */
635int
637{
638 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
639 int is_resolve, r;
640 int made_connection_pending = 0;
641 char *hostname = NULL;
642 cached_resolve_t *resolve = NULL;
643 is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
644
645 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
646 &made_connection_pending, &resolve);
647
648 switch (r) {
649 case 1:
650 /* We got an answer without a lookup -- either the answer was
651 * cached, or it was obvious (like an IP address). */
652 if (is_resolve) {
653 /* Send the answer back right now, and detach. */
654 if (hostname)
655 send_resolved_hostname_cell(exitconn, hostname);
656 else
657 send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO, resolve);
658 exitconn->on_circuit = NULL;
659 } else {
660 /* Add to the n_streams list; the calling function will send back a
661 * connected cell. */
662 exitconn->next_stream = oncirc->n_streams;
663 oncirc->n_streams = exitconn;
664 conflux_update_n_streams(oncirc, exitconn);
665 }
666 break;
667 case 0:
668 /* The request is pending: add the connection into the linked list of
669 * resolving_streams on this circuit. */
670 exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
671 exitconn->next_stream = oncirc->resolving_streams;
672 oncirc->resolving_streams = exitconn;
673 conflux_update_resolving_streams(oncirc, exitconn);
674 break;
675 case -2:
676 case -1:
677 /* The request failed before it could start: cancel this connection,
678 * and stop everybody waiting for the same connection. */
679 if (is_resolve) {
680 send_resolved_cell(exitconn,
681 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
682 NULL);
683 }
684
685 exitconn->on_circuit = NULL;
686
687 dns_cancel_pending_resolve(exitconn->base_.address);
688
689 if (!made_connection_pending && !exitconn->base_.marked_for_close) {
690 /* If we made the connection pending, then we freed it already in
691 * dns_cancel_pending_resolve(). If we marked it for close, it'll
692 * get freed from the main loop. Otherwise, can free it now. */
693 connection_free_(TO_CONN(exitconn));
694 }
695 break;
696 default:
697 tor_assert(0);
698 }
699
700 tor_free(hostname);
701 return r;
702}
703
704/** Helper function for dns_resolve: same functionality, but does not handle:
705 * - marking connections on error and clearing their on_circuit
706 * - linking connections to n_streams/resolving_streams,
707 * - sending resolved cells if we have an answer/error right away,
708 *
709 * Return -2 on a transient error. If it's a reverse resolve and it's
710 * successful, sets *<b>hostname_out</b> to a newly allocated string
711 * holding the cached reverse DNS value.
712 *
713 * Set *<b>made_connection_pending_out</b> to true if we have placed
714 * <b>exitconn</b> on the list of pending connections for some resolve; set it
715 * to false otherwise.
716 *
717 * Set *<b>resolve_out</b> to a cached resolve, if we found one.
718 */
719MOCK_IMPL(STATIC int,
720dns_resolve_impl,(edge_connection_t *exitconn, int is_resolve,
721 or_circuit_t *oncirc, char **hostname_out,
722 int *made_connection_pending_out,
723 cached_resolve_t **resolve_out))
724{
725 cached_resolve_t *resolve;
726 cached_resolve_t search;
727 pending_connection_t *pending_connection;
728 int is_reverse = 0;
729 tor_addr_t addr;
730 time_t now = time(NULL);
731 int r;
732 assert_connection_ok(TO_CONN(exitconn), 0);
733 tor_assert(!SOCKET_OK(exitconn->base_.s));
734 assert_cache_ok();
735 tor_assert(oncirc);
736 *made_connection_pending_out = 0;
737
738 /* first check if exitconn->base_.address is an IP. If so, we already
739 * know the answer. */
740 if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
741 if (tor_addr_family(&addr) == AF_INET ||
742 tor_addr_family(&addr) == AF_INET6) {
743 tor_addr_copy(&exitconn->base_.addr, &addr);
744 exitconn->address_ttl = DEFAULT_DNS_TTL;
745 return 1;
746 } else {
747 /* XXXX unspec? Bogus? */
748 return -1;
749 }
750 }
751
752 /* If we're a non-exit, don't even do DNS lookups. */
754 return -1;
755
756 if (address_is_invalid_destination(exitconn->base_.address, 0)) {
757 tor_log(LOG_PROTOCOL_WARN, LD_EXIT,
758 "Rejecting invalid destination address %s",
759 escaped_safe_str(exitconn->base_.address));
760 return -1;
761 }
762
763 /* then take this opportunity to see if there are any expired
764 * resolves in the hash table. */
766
767 /* lower-case exitconn->base_.address, so it's in canonical form */
768 tor_strlower(exitconn->base_.address);
769
770 /* Check whether this is a reverse lookup. If it's malformed, or it's a
771 * .in-addr.arpa address but this isn't a resolve request, kill the
772 * connection.
773 */
774 if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
775 AF_UNSPEC, 0)) != 0) {
776 if (r == 1) {
777 is_reverse = 1;
778 if (tor_addr_is_internal(&addr, 0)) /* internal address? */
779 return -1;
780 }
781
782 if (!is_reverse || !is_resolve) {
783 if (!is_reverse)
784 log_info(LD_EXIT, "Bad .in-addr.arpa address %s; sending error.",
785 escaped_safe_str(exitconn->base_.address));
786 else if (!is_resolve)
787 log_info(LD_EXIT,
788 "Attempt to connect to a .in-addr.arpa address %s; "
789 "sending error.",
790 escaped_safe_str(exitconn->base_.address));
791
792 return -1;
793 }
794 //log_notice(LD_EXIT, "Looks like an address %s",
795 //exitconn->base_.address);
796 }
797 exitconn->is_reverse_dns_lookup = is_reverse;
798
799 /* now check the hash table to see if 'address' is already there. */
800 strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
801 resolve = HT_FIND(cache_map, &cache_root, &search);
802 if (resolve && resolve->expire > now) { /* already there */
803 switch (resolve->state) {
805 /* add us to the pending list */
806 pending_connection = tor_malloc_zero(
807 sizeof(pending_connection_t));
808 pending_connection->conn = exitconn;
809 pending_connection->next = resolve->pending_connections;
810 resolve->pending_connections = pending_connection;
811 *made_connection_pending_out = 1;
812 log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") waiting "
813 "for pending DNS resolve of %s", exitconn->base_.s,
814 escaped_safe_str(exitconn->base_.address));
815 return 0;
817 log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") found "
818 "cached answer for %s",
819 exitconn->base_.s,
820 escaped_safe_str(resolve->address));
821
822 *resolve_out = resolve;
823
824 return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
825 case CACHE_STATE_DONE:
826 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
828 }
829 tor_assert(0);
830 }
831 tor_assert(!resolve);
832 /* not there, need to add it */
833 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
834 resolve->magic = CACHED_RESOLVE_MAGIC;
835 resolve->state = CACHE_STATE_PENDING;
836 resolve->minheap_idx = -1;
837 strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
838
839 /* add this connection to the pending list */
840 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
841 pending_connection->conn = exitconn;
842 resolve->pending_connections = pending_connection;
843 *made_connection_pending_out = 1;
844
845 /* Add this resolve to the cache and priority queue. */
846 HT_INSERT(cache_map, &cache_root, resolve);
847 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
848
849 log_debug(LD_EXIT,"Launching %s.",
850 escaped_safe_str(exitconn->base_.address));
851 assert_cache_ok();
852
853 return launch_resolve(resolve);
854}
855
856/** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
857 * <b>resolve</b> whose DNS lookups have all either succeeded or failed,
858 * update the appropriate fields (address_ttl and addr) of <b>exitconn</b>.
859 *
860 * The logic can be complicated here, since we might have launched both
861 * an A lookup and an AAAA lookup, and since either of those might have
862 * succeeded or failed, and since we want to answer a RESOLVE cell with
863 * a full answer but answer a BEGIN cell with whatever answer the client
864 * would accept <i>and</i> we could still connect to.
865 *
866 * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
867 * copy of the name resulting hostname.
868 *
869 * Return -2 on a transient error, -1 on a permenent error, and 1 on
870 * a successful lookup.
871 */
872MOCK_IMPL(STATIC int,
874 const cached_resolve_t *resolve,
875 char **hostname_out))
876{
877 int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
878 uint32_t begincell_flags;
879 const int is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
880 tor_assert(exitconn);
881 tor_assert(resolve);
882
883 if (exitconn->is_reverse_dns_lookup) {
884 exitconn->address_ttl = resolve->ttl_hostname;
885 if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
886 *hostname_out = tor_strdup(resolve->result_ptr.hostname);
887 return 1;
888 } else {
889 return -1;
890 }
891 }
892
893 /* If we're here then the connection wants one or either of ipv4, ipv6, and
894 * we can give it one or both. */
895 if (is_resolve) {
896 begincell_flags = BEGIN_FLAG_IPV6_OK;
897 } else {
898 begincell_flags = exitconn->begincell_flags;
899 }
900
901 ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
902 ! (begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
903 ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
904 (begincell_flags & BEGIN_FLAG_IPV6_OK) &&
906
907 /* Now decide which one to actually give. */
908 if (ipv4_ok && ipv6_ok && is_resolve) {
909 answer_with_ipv4 = 1;
910 } else if (ipv4_ok && ipv6_ok) {
911 /* If we have both, see if our exit policy has an opinion. */
912 const uint16_t port = exitconn->base_.port;
913 int ipv4_allowed, ipv6_allowed;
914 tor_addr_t a4, a6;
917 ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
918 ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
919 if (ipv4_allowed && !ipv6_allowed) {
920 answer_with_ipv4 = 1;
921 } else if (ipv6_allowed && !ipv4_allowed) {
922 answer_with_ipv4 = 0;
923 } else {
924 /* Our exit policy would permit both. Answer with whichever the user
925 * prefers */
926 answer_with_ipv4 = !(begincell_flags &
928 }
929 } else {
930 /* Otherwise if one is okay, send it back. */
931 if (ipv4_ok) {
932 answer_with_ipv4 = 1;
933 } else if (ipv6_ok) {
934 answer_with_ipv4 = 0;
935 } else {
936 /* Neither one was okay. Choose based on user preference. */
937 answer_with_ipv4 = !(begincell_flags &
939 }
940 }
941
942 /* Finally, we write the answer back. */
943 r = 1;
944 if (answer_with_ipv4) {
945 if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
946 tor_addr_from_ipv4h(&exitconn->base_.addr,
947 resolve->result_ipv4.addr_ipv4);
948 } else {
949 r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
950 }
951
952 exitconn->address_ttl = resolve->ttl_ipv4;
953 } else {
954 if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
955 tor_addr_from_in6(&exitconn->base_.addr,
956 &resolve->result_ipv6.addr_ipv6);
957 } else {
958 r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
959 }
960
961 exitconn->address_ttl = resolve->ttl_ipv6;
962 }
963
964 return r;
965}
966
967/** Log an error and abort if conn is waiting for a DNS resolve.
968 */
969void
971{
973 cached_resolve_t search;
974
975#if 1
976 cached_resolve_t *resolve;
977 strlcpy(search.address, conn->base_.address, sizeof(search.address));
978 resolve = HT_FIND(cache_map, &cache_root, &search);
979 if (!resolve)
980 return;
981 for (pend = resolve->pending_connections; pend; pend = pend->next) {
982 tor_assert(pend->conn != conn);
983 }
984#else /* !(1) */
985 cached_resolve_t **resolve;
986 HT_FOREACH(resolve, cache_map, &cache_root) {
987 for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
988 tor_assert(pend->conn != conn);
989 }
990 }
991#endif /* 1 */
992}
993
994/** Remove <b>conn</b> from the list of connections waiting for conn->address.
995 */
996void
998{
999 pending_connection_t *pend, *victim;
1000 cached_resolve_t search;
1001 cached_resolve_t *resolve;
1002
1003 tor_assert(conn->base_.type == CONN_TYPE_EXIT);
1005
1006 strlcpy(search.address, conn->base_.address, sizeof(search.address));
1007
1008 resolve = HT_FIND(cache_map, &cache_root, &search);
1009 if (!resolve) {
1010 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
1011 escaped_safe_str(conn->base_.address));
1012 return;
1013 }
1014
1017
1018 pend = resolve->pending_connections;
1019
1020 if (pend->conn == conn) {
1021 resolve->pending_connections = pend->next;
1022 tor_free(pend);
1023 log_debug(LD_EXIT, "First connection (fd "TOR_SOCKET_T_FORMAT") no "
1024 "longer waiting for resolve of %s",
1025 conn->base_.s,
1026 escaped_safe_str(conn->base_.address));
1027 return;
1028 } else {
1029 for ( ; pend->next; pend = pend->next) {
1030 if (pend->next->conn == conn) {
1031 victim = pend->next;
1032 pend->next = victim->next;
1033 tor_free(victim);
1034 log_debug(LD_EXIT,
1035 "Connection (fd "TOR_SOCKET_T_FORMAT") no longer waiting "
1036 "for resolve of %s",
1037 conn->base_.s, escaped_safe_str(conn->base_.address));
1038 return; /* more are pending */
1039 }
1040 }
1041 log_warn(LD_BUG, "Connection (fd "TOR_SOCKET_T_FORMAT") was not waiting "
1042 "for a resolve of %s, but we tried to remove it.",
1043 conn->base_.s, escaped_safe_str(conn->base_.address));
1044 }
1045}
1046
1047/** Mark all connections waiting for <b>address</b> for close. Then cancel
1048 * the resolve for <b>address</b> itself, and remove any cached results for
1049 * <b>address</b> from the cache.
1050 */
1051MOCK_IMPL(STATIC void,
1052dns_cancel_pending_resolve,(const char *address))
1053{
1055 cached_resolve_t search;
1056 cached_resolve_t *resolve, *tmp;
1057 edge_connection_t *pendconn;
1058 circuit_t *circ;
1059
1060 strlcpy(search.address, address, sizeof(search.address));
1061
1062 resolve = HT_FIND(cache_map, &cache_root, &search);
1063 if (!resolve)
1064 return;
1065
1066 if (resolve->state != CACHE_STATE_PENDING) {
1067 /* We can get into this state if we never actually created the pending
1068 * resolve, due to finding an earlier cached error or something. Just
1069 * ignore it. */
1070 if (resolve->pending_connections) {
1071 log_warn(LD_BUG,
1072 "Address %s is not pending but has pending connections!",
1073 escaped_safe_str(address));
1075 }
1076 return;
1077 }
1078
1079 if (!resolve->pending_connections) {
1080 log_warn(LD_BUG,
1081 "Address %s is pending but has no pending connections!",
1082 escaped_safe_str(address));
1084 return;
1085 }
1087
1088 /* mark all pending connections to fail */
1089 log_debug(LD_EXIT,
1090 "Failing all connections waiting on DNS resolve of %s",
1091 escaped_safe_str(address));
1092 while (resolve->pending_connections) {
1093 pend = resolve->pending_connections;
1094 pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1095 pendconn = pend->conn;
1096 assert_connection_ok(TO_CONN(pendconn), 0);
1097 tor_assert(!SOCKET_OK(pendconn->base_.s));
1098 if (!pendconn->base_.marked_for_close) {
1099 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1100 }
1101 circ = circuit_get_by_edge_conn(pendconn);
1102 if (circ)
1103 circuit_detach_stream(circ, pendconn);
1104 if (!pendconn->base_.marked_for_close)
1105 connection_free_(TO_CONN(pendconn));
1106 resolve->pending_connections = pend->next;
1107 tor_free(pend);
1108 }
1109
1110 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
1111 if (tmp != resolve) {
1112 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
1113 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1114 resolve->address, (void*)resolve,
1115 tmp ? tmp->address : "NULL", (void*)tmp);
1116 }
1117 tor_assert(tmp == resolve);
1118
1119 resolve->state = CACHE_STATE_DONE;
1120}
1121
1122/** Return true iff <b>address</b> is one of the addresses we use to verify
1123 * that well-known sites aren't being hijacked by our DNS servers. */
1124static inline int
1125is_test_address(const char *address)
1126{
1127 const or_options_t *options = get_options();
1128 return options->ServerDNSTestAddresses &&
1130}
1131
1132/** Called on the OR side when the eventdns library tells us the outcome of a
1133 * single DNS resolve: remember the answer, and tell all pending connections
1134 * about the result of the lookup if the lookup is now done. (<b>address</b>
1135 * is a NUL-terminated string containing the address to look up;
1136 * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
1137 * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
1138 * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
1139 * <b>ttl</b> is the time-to-live of this answer, in seconds.)
1140 */
1141static void
1142dns_found_answer(const char *address, uint8_t query_type,
1143 int dns_answer,
1144 const tor_addr_t *addr,
1145 const char *hostname, uint32_t ttl)
1146{
1147 cached_resolve_t search;
1148 cached_resolve_t *resolve;
1149
1150 assert_cache_ok();
1151
1152 strlcpy(search.address, address, sizeof(search.address));
1153
1154 resolve = HT_FIND(cache_map, &cache_root, &search);
1155 if (!resolve) {
1156 int is_test_addr = is_test_address(address);
1157 if (!is_test_addr)
1158 log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
1159 escaped_safe_str(address));
1160 return;
1161 }
1162 assert_resolve_ok(resolve);
1163
1164 if (resolve->state != CACHE_STATE_PENDING) {
1165 /* XXXX Maybe update addr? or check addr for consistency? Or let
1166 * VALID replace FAILED? */
1167 int is_test_addr = is_test_address(address);
1168 if (!is_test_addr)
1169 log_notice(LD_EXIT,
1170 "Resolved %s which was already resolved; ignoring",
1171 escaped_safe_str(address));
1172 tor_assert(resolve->pending_connections == NULL);
1173 return;
1174 }
1175
1176 cached_resolve_add_answer(resolve, query_type, dns_answer,
1177 addr, hostname, ttl);
1178
1179 if (cached_resolve_have_all_answers(resolve)) {
1181
1183 }
1184}
1185
1186/** Given a pending cached_resolve_t that we just finished resolving,
1187 * inform every connection that was waiting for the outcome of that
1188 * resolution.
1189 *
1190 * Do this by sending a RELAY_RESOLVED cell (if the pending stream had sent us
1191 * a RELAY_RESOLVE cell), or by launching an exit connection (if the pending
1192 * stream had sent us a RELAY_BEGIN cell).
1193 */
1194static void
1196{
1198 edge_connection_t *pendconn;
1199 int r;
1200
1201 while (resolve->pending_connections) {
1202 char *hostname = NULL;
1203 pend = resolve->pending_connections;
1204 pendconn = pend->conn; /* don't pass complex things to the
1205 connection_mark_for_close macro */
1206 assert_connection_ok(TO_CONN(pendconn),time(NULL));
1207
1208 if (pendconn->base_.marked_for_close) {
1209 /* prevent double-remove. */
1210 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1211 resolve->pending_connections = pend->next;
1212 tor_free(pend);
1213 continue;
1214 }
1215
1216 r = set_exitconn_info_from_resolve(pendconn,
1217 resolve,
1218 &hostname);
1219
1220 if (r < 0) {
1221 /* prevent double-remove. */
1222 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1223 if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1224 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1225 /* This detach must happen after we send the end cell. */
1227 } else {
1228 send_resolved_cell(pendconn, r == -1 ?
1229 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
1230 NULL);
1231 /* This detach must happen after we send the resolved cell. */
1233 }
1234 connection_free_(TO_CONN(pendconn));
1235 } else {
1236 circuit_t *circ;
1237 if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1238 /* prevent double-remove. */
1239 pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
1240
1241 circ = circuit_get_by_edge_conn(pend->conn);
1242 tor_assert(circ);
1244 /* unlink pend->conn from resolving_streams, */
1245 circuit_detach_stream(circ, pend->conn);
1246 /* and link it to n_streams */
1247 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1248 pend->conn->on_circuit = circ;
1249 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1250 conflux_update_n_streams(TO_OR_CIRCUIT(circ), pend->conn);
1251
1252 connection_exit_connect(pend->conn);
1253 } else {
1254 /* prevent double-remove. This isn't really an accurate state,
1255 * but it does the right thing. */
1256 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1257 if (pendconn->is_reverse_dns_lookup)
1258 send_resolved_hostname_cell(pendconn, hostname);
1259 else
1260 send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO, resolve);
1261 circ = circuit_get_by_edge_conn(pendconn);
1262 tor_assert(circ);
1263 circuit_detach_stream(circ, pendconn);
1264 connection_free_(TO_CONN(pendconn));
1265 }
1266 }
1267 resolve->pending_connections = pend->next;
1268 tor_free(pend);
1269 tor_free(hostname);
1270 }
1271}
1272
1273/** Remove a pending cached_resolve_t from the hashtable, and add a
1274 * corresponding cached cached_resolve_t.
1275 *
1276 * This function is only necessary because of the perversity of our
1277 * cache timeout code; see inline comment for ideas on eliminating it.
1278 **/
1279static void
1281{
1282 cached_resolve_t *removed;
1283
1284 resolve->state = CACHE_STATE_DONE;
1285 removed = HT_REMOVE(cache_map, &cache_root, resolve);
1286 if (removed != resolve) {
1287 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1288 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1289 resolve->address, (void*)resolve,
1290 removed ? removed->address : "NULL", (void*)removed);
1291 }
1292 assert_resolve_ok(resolve);
1293 assert_cache_ok();
1294 /* The resolve will eventually just hit the time-out in the expiry queue and
1295 * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
1296 * way. XXXXX we could do better!*/
1297
1298 {
1299 cached_resolve_t *new_resolve = tor_memdup(resolve,
1300 sizeof(cached_resolve_t));
1301 uint32_t ttl = UINT32_MAX;
1302 new_resolve->expire = 0; /* So that set_expiry won't croak. */
1303 if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
1304 new_resolve->result_ptr.hostname =
1305 tor_strdup(resolve->result_ptr.hostname);
1306
1307 new_resolve->state = CACHE_STATE_CACHED;
1308
1309 assert_resolve_ok(new_resolve);
1310 HT_INSERT(cache_map, &cache_root, new_resolve);
1311
1312 if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
1313 resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
1314 resolve->ttl_ipv4 < ttl)
1315 ttl = resolve->ttl_ipv4;
1316
1317 if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
1318 resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
1319 resolve->ttl_ipv6 < ttl)
1320 ttl = resolve->ttl_ipv6;
1321
1322 if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
1323 resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
1324 resolve->ttl_hostname < ttl)
1325 ttl = resolve->ttl_hostname;
1326
1327 set_expiry(new_resolve, time(NULL) + ttl);
1328 }
1329
1330 assert_cache_ok();
1331}
1332
1333/** Eventdns helper: return true iff the eventdns result <b>err</b> is
1334 * a transient failure. */
1335static int
1337{
1338 switch (err)
1339 {
1340 case DNS_ERR_SERVERFAILED:
1341 case DNS_ERR_TRUNCATED:
1342 case DNS_ERR_TIMEOUT:
1343 return 1;
1344 default:
1345 return 0;
1346 }
1347}
1348
1349/**
1350 * Return number of configured nameservers in <b>the_evdns_base</b>.
1351 */
1352size_t
1354{
1355 return evdns_base_count_nameservers(the_evdns_base);
1356}
1357
1358#ifdef HAVE_EVDNS_BASE_GET_NAMESERVER_ADDR
1359/**
1360 * Return address of configured nameserver in <b>the_evdns_base</b>
1361 * at index <b>idx</b>.
1362 */
1363tor_addr_t *
1364configured_nameserver_address(const size_t idx)
1365{
1366 struct sockaddr_storage sa;
1367 ev_socklen_t sa_len = sizeof(sa);
1368
1369 if (evdns_base_get_nameserver_addr(the_evdns_base, (int)idx,
1370 (struct sockaddr *)&sa,
1371 sa_len) > 0) {
1372 tor_addr_t *tor_addr = tor_malloc(sizeof(tor_addr_t));
1373 if (tor_addr_from_sockaddr(tor_addr,
1374 (const struct sockaddr *)&sa,
1375 NULL) == 0) {
1376 return tor_addr;
1377 }
1378 tor_free(tor_addr);
1379 }
1380
1381 return NULL;
1382}
1383#endif /* defined(HAVE_EVDNS_BASE_GET_NAMESERVER_ADDR) */
1384
1385/** Return a pointer to a stack allocated buffer containing the string
1386 * representation of the exit_dns_timeout consensus parameter. */
1387static const char *
1389{
1390 static char str[4];
1391
1392 /* Get the Exit DNS timeout value from the consensus or default. This is in
1393 * milliseconds. */
1394#define EXIT_DNS_TIMEOUT_DEFAULT (1000)
1395#define EXIT_DNS_TIMEOUT_MIN (1)
1396#define EXIT_DNS_TIMEOUT_MAX (120000)
1397 int32_t val = networkstatus_get_param(NULL, "exit_dns_timeout",
1398 EXIT_DNS_TIMEOUT_DEFAULT,
1399 EXIT_DNS_TIMEOUT_MIN,
1400 EXIT_DNS_TIMEOUT_MAX);
1401 /* NOTE: We convert it to seconds because libevent only supports that. In the
1402 * future, if we support different resolver(s), we might want to specialize
1403 * this call. */
1404
1405 /* NOTE: We also don't allow 0 and so we must cap the division to 1 second
1406 * else all DNS request would fail if the consensus would ever tell us a
1407 * value below 1000 (1 sec). */
1408 val = MAX(1, val / 1000);
1409
1410 tor_snprintf(str, sizeof(str), "%d", val);
1411 return str;
1412}
1413
1414/** Return a pointer to a stack allocated buffer containing the string
1415 * representation of the exit_dns_num_attempts consensus parameter. */
1416static const char *
1418{
1419 static char str[4];
1420
1421 /* Get the Exit DNS number of attempt value from the consensus or default. */
1422#define EXIT_DNS_NUM_ATTEMPTS_DEFAULT (2)
1423#define EXIT_DNS_NUM_ATTEMPTS_MIN (0)
1424#define EXIT_DNS_NUM_ATTEMPTS_MAX (255)
1425 int32_t val = networkstatus_get_param(NULL, "exit_dns_num_attempts",
1426 EXIT_DNS_NUM_ATTEMPTS_DEFAULT,
1427 EXIT_DNS_NUM_ATTEMPTS_MIN,
1428 EXIT_DNS_NUM_ATTEMPTS_MAX);
1429 tor_snprintf(str, sizeof(str), "%d", val);
1430 return str;
1431}
1432
1433/** Configure the libevent options. This can safely be called after
1434 * initialization or even if the evdns base is not set. */
1435static void
1437{
1438 /* This is possible because we can get called when a new consensus is set
1439 * while the DNS subsystem is not initialized just yet. It should be
1440 * harmless. */
1441 if (!the_evdns_base) {
1442 return;
1443 }
1444
1445#define SET(k,v) evdns_base_set_option(the_evdns_base, (k), (v))
1446
1447 // If we only have one nameserver, it does not make sense to back off
1448 // from it for a timeout. Unfortunately, the value for max-timeouts is
1449 // currently clamped by libevent to 255, but it does not hurt to set
1450 // it higher in case libevent gets a patch for this. Higher-than-
1451 // default maximum of 3 with multiple nameservers to avoid spuriously
1452 // marking one down on bursts of timeouts resulting from scans/attacks
1453 // against non-responding authoritative DNS servers.
1454 if (evdns_base_count_nameservers(the_evdns_base) == 1) {
1455 SET("max-timeouts:", "1000000");
1456 } else {
1457 SET("max-timeouts:", "10");
1458 }
1459
1460 // Elongate the queue of maximum inflight dns requests, so if a bunch
1461 // remain pending at the resolver (happens commonly with Unbound) we won't
1462 // stall every other DNS request. This potentially means some wasted
1463 // CPU as there's a walk over a linear queue involved, but this is a
1464 // much better tradeoff compared to just failing DNS requests because
1465 // of a full queue.
1466 SET("max-inflight:", "8192");
1467
1468 /* Set timeout to be 1 second. This tells libevent that it shouldn't wait
1469 * more than N second to drop a DNS query and consider it "timed out". It is
1470 * very important to differentiate here a libevent timeout and a DNS server
1471 * timeout. And so, by setting this to N second, libevent sends back
1472 * "DNS_ERR_TIMEOUT" if that N second is reached which does NOT indicate that
1473 * the query itself timed out in transit. */
1474 SET("timeout:", get_consensus_param_exit_dns_timeout());
1475
1476 /* This tells libevent to attempt up to X times a DNS query if the previous
1477 * one failed to complete within N second. We believe that this should be
1478 * enough to catch temporary hiccups on the first query. But after that, it
1479 * should signal us that it won't be able to resolve it. */
1480 SET("attempts:", get_consensus_param_exit_dns_attempts());
1481
1482 if (get_options()->ServerDNSRandomizeCase)
1483 SET("randomize-case:", "1");
1484 else
1485 SET("randomize-case:", "0");
1486
1487#undef SET
1488}
1489
1490/** Configure eventdns nameservers if force is true, or if the configuration
1491 * has changed since the last time we called this function, or if we failed on
1492 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1493 * options->ServerDNSResolvConfFile; on Windows, this reads from
1494 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1495 * -1 on failure. */
1496static int
1498{
1499 const or_options_t *options;
1500 const char *conf_fname;
1501 struct stat st;
1502 int r, flags;
1503 options = get_options();
1504 conf_fname = options->ServerDNSResolvConfFile;
1505#ifndef _WIN32
1506 if (!conf_fname)
1507 conf_fname = "/etc/resolv.conf";
1508#endif
1509 flags = DNS_OPTIONS_ALL;
1510
1511 if (!the_evdns_base) {
1512 if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
1513 log_err(LD_BUG, "Couldn't create an evdns_base");
1514 return -1;
1515 }
1516 }
1517
1518 evdns_set_log_fn(evdns_log_cb);
1519 if (conf_fname) {
1520 log_debug(LD_FS, "stat()ing %s", conf_fname);
1521 int missing_resolv_conf = 0;
1522 int stat_res = stat(sandbox_intern_string(conf_fname), &st);
1523
1524 if (stat_res) {
1525 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1526 conf_fname, strerror(errno));
1527 missing_resolv_conf = 1;
1528 } else if (!force && resolv_conf_fname &&
1529 !strcmp(conf_fname,resolv_conf_fname)
1530 && st.st_mtime == resolv_conf_mtime) {
1531 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1532 return 0;
1533 }
1534
1535 if (stat_res == 0 && st.st_size == 0)
1536 missing_resolv_conf = 1;
1537
1539 evdns_base_search_clear(the_evdns_base);
1540 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1541 }
1542#if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
1543 if (flags & DNS_OPTION_HOSTSFILE) {
1544 flags ^= DNS_OPTION_HOSTSFILE;
1545 log_debug(LD_FS, "Loading /etc/hosts");
1546 evdns_base_load_hosts(the_evdns_base,
1547 sandbox_intern_string("/etc/hosts"));
1548 }
1549#endif /* defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP) */
1550
1551 if (!missing_resolv_conf) {
1552 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1553 if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
1554 sandbox_intern_string(conf_fname)))) {
1555 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers "
1556 "in '%s' (%d)", conf_fname, conf_fname, r);
1557
1558 if (r != 6) // "r = 6" means "no DNS servers were in resolv.conf" -
1559 goto err; // in which case we expect libevent to add 127.0.0.1 as
1560 // fallback.
1561 }
1562 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1563 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.",
1564 conf_fname);
1565 }
1566
1568 resolv_conf_fname = tor_strdup(conf_fname);
1569 resolv_conf_mtime = st.st_mtime;
1570 } else {
1571 log_warn(LD_EXIT, "Could not read your DNS config from '%s' - "
1572 "please investigate your DNS configuration. "
1573 "This is possibly a problem. Meanwhile, falling"
1574 " back to local DNS at 127.0.0.1.", conf_fname);
1575 evdns_base_nameserver_ip_add(the_evdns_base, "127.0.0.1");
1576 }
1577
1579 evdns_base_resume(the_evdns_base);
1580 }
1581#ifdef _WIN32
1582 else {
1584 evdns_base_search_clear(the_evdns_base);
1585 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1586 }
1587 if (evdns_base_config_windows_nameservers(the_evdns_base)) {
1588 log_warn(LD_EXIT,"Could not config nameservers.");
1589 goto err;
1590 }
1591 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1592 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1593 "your Windows configuration.");
1594 goto err;
1595 }
1597 evdns_base_resume(the_evdns_base);
1600 }
1601#endif /* defined(_WIN32) */
1602
1603 /* Setup libevent options. */
1605
1606 /* Relaunch periodical DNS check event. */
1608
1612 /* XXX the three calls to republish the descriptor might be producing
1613 * descriptors that are only cosmetically different, especially on
1614 * non-exit relays! -RD */
1615 mark_my_descriptor_dirty("dns resolvers back");
1616 }
1617 return 0;
1618 err:
1622 mark_my_descriptor_dirty("dns resolvers failed");
1623 }
1624 return -1;
1625}
1626
1627/** For eventdns: Called when we get an answer for a request we launched.
1628 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1629 */
1630static void
1631evdns_callback(int result, char type, int count, int ttl, void *addresses,
1632 void *arg)
1633{
1634 char *arg_ = arg;
1635 uint8_t orig_query_type = arg_[0];
1636 char *string_address = arg_ + 1;
1637 tor_addr_t addr;
1638 const char *hostname = NULL;
1639 int was_wildcarded = 0;
1640
1641 tor_addr_make_unspec(&addr);
1642
1643 /* Keep track of whether IPv6 is working */
1644 if (type == DNS_IPv6_AAAA) {
1645 if (result == DNS_ERR_TIMEOUT) {
1646 ++n_ipv6_timeouts;
1647 }
1648
1649 if (n_ipv6_timeouts > 10 &&
1650 n_ipv6_timeouts > n_ipv6_requests_made / 2) {
1651 if (! dns_is_broken_for_ipv6) {
1652 log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
1653 "have timed out. I'm going to assume I can't get AAAA "
1654 "responses.");
1655 dns_is_broken_for_ipv6 = 1;
1656 }
1657 }
1658 }
1659
1660 if (result == DNS_ERR_NONE) {
1661 if (type == DNS_IPv4_A && count) {
1662 char answer_buf[INET_NTOA_BUF_LEN+1];
1663 char *escaped_address;
1664 uint32_t *addrs = addresses;
1665 tor_addr_from_ipv4n(&addr, addrs[0]);
1666
1667 tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
1668 escaped_address = esc_for_log(string_address);
1669
1670 if (answer_is_wildcarded(answer_buf)) {
1671 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1672 "address %s; treating as a failure.",
1673 safe_str(escaped_address),
1674 escaped_safe_str(answer_buf));
1675 was_wildcarded = 1;
1676 tor_addr_make_unspec(&addr);
1677 result = DNS_ERR_NOTEXIST;
1678 } else {
1679 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1680 safe_str(escaped_address),
1681 escaped_safe_str(answer_buf));
1682 }
1683 tor_free(escaped_address);
1684 } else if (type == DNS_IPv6_AAAA && count) {
1685 char answer_buf[TOR_ADDR_BUF_LEN];
1686 char *escaped_address;
1687 const char *ip_str;
1688 struct in6_addr *addrs = addresses;
1689 tor_addr_from_in6(&addr, &addrs[0]);
1690 ip_str = tor_inet_ntop(AF_INET6, &addrs[0], answer_buf,
1691 sizeof(answer_buf));
1692 escaped_address = esc_for_log(string_address);
1693
1694 if (BUG(ip_str == NULL)) {
1695 log_warn(LD_EXIT, "tor_inet_ntop() failed!");
1696 result = DNS_ERR_NOTEXIST;
1697 } else if (answer_is_wildcarded(answer_buf)) {
1698 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1699 "address %s; treating as a failure.",
1700 safe_str(escaped_address),
1701 escaped_safe_str(answer_buf));
1702 was_wildcarded = 1;
1703 tor_addr_make_unspec(&addr);
1704 result = DNS_ERR_NOTEXIST;
1705 } else {
1706 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1707 safe_str(escaped_address),
1708 escaped_safe_str(answer_buf));
1709 }
1710 tor_free(escaped_address);
1711 } else if (type == DNS_PTR && count) {
1712 char *escaped_address;
1713 hostname = ((char**)addresses)[0];
1714 escaped_address = esc_for_log(string_address);
1715 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1716 safe_str(escaped_address),
1717 escaped_safe_str(hostname));
1718 tor_free(escaped_address);
1719 } else if (count) {
1720 log_info(LD_EXIT, "eventdns returned only unrecognized answer types "
1721 " for %s.",
1722 escaped_safe_str(string_address));
1723 } else {
1724 log_info(LD_EXIT, "eventdns returned no addresses or error for %s.",
1725 escaped_safe_str(string_address));
1726 }
1727 }
1728 if (was_wildcarded) {
1729 if (is_test_address(string_address)) {
1730 /* Ick. We're getting redirected on known-good addresses. Our DNS
1731 * server must really hate us. */
1732 add_wildcarded_test_address(string_address);
1733 }
1734 }
1735
1736 if (orig_query_type && type && orig_query_type != type) {
1737 log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
1738 (int)orig_query_type, (int)type);
1739 }
1740 if (result != DNS_ERR_SHUTDOWN)
1741 dns_found_answer(string_address, orig_query_type,
1742 result, &addr, hostname, clip_dns_fuzzy_ttl(ttl));
1743
1744 /* The result can be changed within this function thus why we note the result
1745 * at the end. */
1746 rep_hist_note_dns_error(type, result);
1747
1748 tor_free(arg_);
1749}
1750
1751/** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
1752 * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
1753 * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
1754static int
1755launch_one_resolve(const char *address, uint8_t query_type,
1756 const tor_addr_t *ptr_address)
1757{
1758 const int options = get_options()->ServerDNSSearchDomains ? 0
1759 : DNS_QUERY_NO_SEARCH;
1760 const size_t addr_len = strlen(address);
1761 struct evdns_request *req = 0;
1762 char *addr = tor_malloc(addr_len + 2);
1763 addr[0] = (char) query_type;
1764 memcpy(addr+1, address, addr_len + 1);
1765
1766 /* Note the query for our statistics. */
1767 rep_hist_note_dns_request(query_type);
1768
1769 switch (query_type) {
1770 case DNS_IPv4_A:
1771 req = evdns_base_resolve_ipv4(the_evdns_base,
1772 address, options, evdns_callback, addr);
1773 break;
1774 case DNS_IPv6_AAAA:
1775 req = evdns_base_resolve_ipv6(the_evdns_base,
1776 address, options, evdns_callback, addr);
1777 ++n_ipv6_requests_made;
1778 break;
1779 case DNS_PTR:
1780 if (tor_addr_family(ptr_address) == AF_INET)
1781 req = evdns_base_resolve_reverse(the_evdns_base,
1782 tor_addr_to_in(ptr_address),
1783 DNS_QUERY_NO_SEARCH,
1784 evdns_callback, addr);
1785 else if (tor_addr_family(ptr_address) == AF_INET6)
1786 req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
1787 tor_addr_to_in6(ptr_address),
1788 DNS_QUERY_NO_SEARCH,
1789 evdns_callback, addr);
1790 else
1791 log_warn(LD_BUG, "Called with PTR query and unexpected address family");
1792 break;
1793 default:
1794 log_warn(LD_BUG, "Called with unexpected query type %d", (int)query_type);
1795 break;
1796 }
1797
1798 if (req) {
1799 return 0;
1800 } else {
1801 tor_free(addr);
1802 return -1;
1803 }
1804}
1805
1806/** For eventdns: start resolving as necessary to find the target for
1807 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1808 * 0 on "resolve launched." */
1809MOCK_IMPL(STATIC int,
1811{
1812 tor_addr_t a;
1813 int r;
1814
1815 if (net_is_disabled())
1816 return -1;
1817
1818 /* What? Nameservers not configured? Sounds like a bug. */
1820 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1821 "launched. Configuring.");
1822 if (configure_nameservers(1) < 0) {
1823 return -1;
1824 }
1825 }
1826
1828 &a, resolve->address, AF_UNSPEC, 0);
1829
1831 if (r == 0) {
1832 log_info(LD_EXIT, "Launching eventdns request for %s",
1833 escaped_safe_str(resolve->address));
1834 resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
1835 if (get_options()->IPv6Exit)
1836 resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
1837
1838 if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
1839 resolve->res_status_ipv4 = 0;
1840 r = -1;
1841 }
1842
1843 if (r==0 && get_options()->IPv6Exit) {
1844 /* We ask for an IPv6 address for *everything*. */
1845 if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
1846 resolve->res_status_ipv6 = 0;
1847 r = -1;
1848 }
1849 }
1850 } else if (r == 1) {
1851 r = 0;
1852 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1853 escaped_safe_str(resolve->address));
1854 resolve->res_status_hostname = RES_STATUS_INFLIGHT;
1855 if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
1856 resolve->res_status_hostname = 0;
1857 r = -1;
1858 }
1859 } else if (r == -1) {
1860 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1861 }
1862
1863 if (r < 0) {
1864 log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
1865 escaped_safe_str(resolve->address));
1866 }
1867 return r;
1868}
1869
1870/** How many requests for bogus addresses have we launched so far? */
1871static int n_wildcard_requests = 0;
1872
1873/** Map from dotted-quad IP address in response to an int holding how many
1874 * times we've seen it for a randomly generated (hopefully bogus) address. It
1875 * would be easier to use definitely-invalid addresses (as specified by
1876 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1877static strmap_t *dns_wildcard_response_count = NULL;
1878
1879/** If present, a list of dotted-quad IP addresses that we are pretty sure our
1880 * nameserver wants to return in response to requests for nonexistent domains.
1881 */
1883/** True iff we've logged about a single address getting wildcarded.
1884 * Subsequent warnings will be less severe. */
1886/** True iff we've warned that our DNS server is wildcarding too many failures.
1887 */
1889
1890/** List of supposedly good addresses that are getting wildcarded to the
1891 * same addresses as nonexistent addresses. */
1893/** True iff we've warned about a test address getting wildcarded */
1895/** True iff all addresses seem to be getting wildcarded. */
1897
1898/** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
1899 * to a request for a hopefully bogus address. */
1900static void
1902{
1903 int *ip;
1905 dns_wildcard_response_count = strmap_new();
1906
1907 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1908 if (!ip) {
1909 ip = tor_malloc_zero(sizeof(int));
1910 strmap_set(dns_wildcard_response_count, id, ip);
1911 }
1912 ++*ip;
1913
1914 if (*ip > 5 && n_wildcard_requests > 10) {
1918 "Your DNS provider has given \"%s\" as an answer for %d different "
1919 "invalid addresses. Apparently they are hijacking DNS failures. "
1920 "I'll try to correct for this by treating future occurrences of "
1921 "\"%s\" as 'not found'.", id, *ip, id);
1923 }
1925 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1927 }
1928}
1929
1930/** Note that a single test address (one believed to be good) seems to be
1931 * getting redirected to the same IP as failures are. */
1932static void
1934{
1935 int n, n_test_addrs;
1938
1940 address))
1941 return;
1942
1943 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1944 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1945
1947 n = smartlist_len(dns_wildcarded_test_address_list);
1948 if (n > n_test_addrs/2) {
1950 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1951 "address. It has done this with %d test addresses so far. I'm "
1952 "going to stop being an exit node for now, since our DNS seems so "
1953 "broken.", address, n);
1956 mark_my_descriptor_dirty("dns hijacking confirmed");
1957 }
1959 control_event_server_status(LOG_WARN, "DNS_USELESS");
1961 }
1962}
1963
1964/** Callback function when we get an answer (possibly failing) for a request
1965 * for a (hopefully) nonexistent domain. */
1966static void
1967evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1968 void *addresses, void *arg)
1969{
1970 (void)ttl;
1971 const char *ip_str;
1973 if (result == DNS_ERR_NONE && count) {
1974 char *string_address = arg;
1975 int i;
1976 if (type == DNS_IPv4_A) {
1977 const uint32_t *addrs = addresses;
1978 for (i = 0; i < count; ++i) {
1979 char answer_buf[INET_NTOA_BUF_LEN+1];
1980 struct in_addr in;
1981 int ntoa_res;
1982 in.s_addr = addrs[i];
1983 ntoa_res = tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1984 tor_assert_nonfatal(ntoa_res >= 0);
1985 if (ntoa_res > 0)
1986 wildcard_increment_answer(answer_buf);
1987 }
1988 } else if (type == DNS_IPv6_AAAA) {
1989 const struct in6_addr *addrs = addresses;
1990 for (i = 0; i < count; ++i) {
1991 char answer_buf[TOR_ADDR_BUF_LEN+1];
1992 ip_str = tor_inet_ntop(AF_INET6, &addrs[i], answer_buf,
1993 sizeof(answer_buf));
1994 tor_assert_nonfatal(ip_str);
1995 if (ip_str)
1996 wildcard_increment_answer(answer_buf);
1997 }
1998 }
1999
2001 "Your DNS provider gave an answer for \"%s\", which "
2002 "is not supposed to exist. Apparently they are hijacking "
2003 "DNS failures. Trying to correct for this. We've noticed %d "
2004 "possibly bad address%s so far.",
2005 string_address, strmap_size(dns_wildcard_response_count),
2006 (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
2008 }
2009 tor_free(arg);
2010}
2011
2012/** Launch a single request for a nonexistent hostname consisting of between
2013 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
2014 * <b>suffix</b> */
2015static void
2016launch_wildcard_check(int min_len, int max_len, int is_ipv6,
2017 const char *suffix)
2018{
2019 char *addr;
2020 struct evdns_request *req;
2021
2022 addr = crypto_random_hostname(min_len, max_len, "", suffix);
2023 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
2024 "domains with request for bogus hostname \"%s\"", addr);
2025
2027 if (is_ipv6)
2028 req = evdns_base_resolve_ipv6(
2030 /* This "addr" tells us which address to resolve */
2031 addr,
2032 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
2033 /* This "addr" is an argument to the callback*/ addr);
2034 else
2035 req = evdns_base_resolve_ipv4(
2037 /* This "addr" tells us which address to resolve */
2038 addr,
2039 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
2040 /* This "addr" is an argument to the callback*/ addr);
2041 if (!req) {
2042 /* There is no evdns request in progress; stop addr from getting leaked */
2043 tor_free(addr);
2044 }
2045}
2046
2047/** Launch attempts to resolve a bunch of known-good addresses (configured in
2048 * ServerDNSTestAddresses). [Callback for a libevent timer] */
2049static void
2050launch_test_addresses(evutil_socket_t fd, short event, void *args)
2051{
2052 const or_options_t *options = get_options();
2053 (void)fd;
2054 (void)event;
2055 (void)args;
2056
2057 if (net_is_disabled())
2058 return;
2059
2060 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
2061 "hijack *everything*.");
2062 /* This situation is worse than the failure-hijacking situation. When this
2063 * happens, we're no good for DNS requests at all, and we shouldn't really
2064 * be an exit server.*/
2065 if (options->ServerDNSTestAddresses) {
2066
2069 const char *, address) {
2070 if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
2071 log_info(LD_EXIT, "eventdns rejected test address %s",
2072 escaped_safe_str(address));
2073 }
2074
2075 if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
2076 log_info(LD_EXIT, "eventdns rejected test address %s",
2077 escaped_safe_str(address));
2078 }
2079 } SMARTLIST_FOREACH_END(address);
2080 }
2081}
2082
2083#define N_WILDCARD_CHECKS 2
2084
2085/** Launch DNS requests for a few nonexistent hostnames and a few well-known
2086 * hostnames, and see if we can catch our nameserver trying to hijack them and
2087 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
2088 * buy these lovely encyclopedias" page. */
2089static void
2091{
2092 int i, ipv6;
2093 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
2094 "to hijack DNS failures.");
2095 for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
2096 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
2097 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
2098 * attempt to 'comply' with rfc2606, refrain from giving A records for
2099 * these. This is the standards-compliance equivalent of making sure
2100 * that your crackhouse's elevator inspection certificate is up to date.
2101 */
2102 launch_wildcard_check(2, 16, ipv6, ".invalid");
2103 launch_wildcard_check(2, 16, ipv6, ".test");
2104
2105 /* These will break specs if there are ever any number of
2106 * 8+-character top-level domains. */
2107 launch_wildcard_check(8, 16, ipv6, "");
2108
2109 /* Try some random .com/org/net domains. This will work fine so long as
2110 * not too many resolve to the same place. */
2111 launch_wildcard_check(8, 16, ipv6, ".com");
2112 launch_wildcard_check(8, 16, ipv6, ".org");
2113 launch_wildcard_check(8, 16, ipv6, ".net");
2114 }
2115 }
2116}
2117
2118/** If appropriate, start testing whether our DNS servers tend to lie to
2119 * us. */
2120void
2122{
2123 static struct event *launch_event = NULL;
2124 struct timeval timeout;
2125 if (!get_options()->ServerDNSDetectHijacking)
2126 return;
2128
2129 /* Wait a while before launching requests for test addresses, so we can
2130 * get the results from checking for wildcarding. */
2131 if (!launch_event)
2132 launch_event = tor_evtimer_new(tor_libevent_get_base(),
2133 launch_test_addresses, NULL);
2134 timeout.tv_sec = 30;
2135 timeout.tv_usec = 0;
2136 if (evtimer_add(launch_event, &timeout) < 0) {
2137 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
2138 }
2139}
2140
2141/** Return true iff our DNS servers lie to us too much to be trusted. */
2142int
2144{
2146}
2147
2148/** Return true iff we think that IPv6 hostname lookup is broken */
2149int
2151{
2152 return dns_is_broken_for_ipv6;
2153}
2154
2155/** Forget what we've previously learned about our DNS servers' correctness. */
2156void
2158{
2161
2163
2164 n_ipv6_requests_made = n_ipv6_timeouts = 0;
2165
2166 if (dns_wildcard_list) {
2169 }
2172 tor_free(cp));
2174 }
2177 dns_is_broken_for_ipv6 = 0;
2178}
2179
2180/** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
2181 * returned in response to requests for nonexistent hostnames. */
2182static int
2184{
2186}
2187
2188/** Exit with an assertion if <b>resolve</b> is corrupt. */
2189static void
2191{
2192 tor_assert(resolve);
2194 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
2196 if (resolve->state != CACHE_STATE_PENDING) {
2198 }
2199 if (resolve->state == CACHE_STATE_PENDING ||
2200 resolve->state == CACHE_STATE_DONE) {
2201#if 0
2202 tor_assert(!resolve->ttl);
2203 if (resolve->is_reverse)
2204 tor_assert(!resolve->hostname);
2205 else
2206 tor_assert(!resolve->result_ipv4.addr_ipv4);
2207#endif /* 0 */
2208 /*XXXXX ADD MORE */
2209 }
2210}
2211
2212/** Return the number of DNS cache entries as an int */
2213static int
2215{
2216 return HT_SIZE(&cache_root);
2217}
2218
2219/* Return the total size in bytes of the DNS cache. */
2220size_t
2221dns_cache_total_allocation(void)
2222{
2223 return sizeof(struct cached_resolve_t) * dns_cache_entry_count() +
2224 HT_MEM_USAGE(&cache_root);
2225}
2226
2227/** Log memory information about our internal DNS cache at level 'severity'. */
2228void
2230{
2231 /* This should never be larger than INT_MAX. */
2232 int hash_count = dns_cache_entry_count();
2233 size_t hash_mem = dns_cache_total_allocation();
2234
2235 /* Print out the count and estimated size of our &cache_root. It undercounts
2236 hostnames in cached reverse resolves.
2237 */
2238 tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
2239 tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
2240 (unsigned)hash_mem);
2241}
2242
2243/* Do a round of OOM cleanup on all DNS entries. Return the amount of removed
2244 * bytes. It is possible that the returned value is lower than min_remove_bytes
2245 * if the caches get emptied out so the caller should be aware of this. */
2246size_t
2247dns_cache_handle_oom(time_t now, size_t min_remove_bytes)
2248{
2249 time_t time_inc = 0;
2250 size_t total_bytes_removed = 0;
2251 size_t current_size = dns_cache_total_allocation();
2252
2253 do {
2254 /* If no DNS entries left, break loop. */
2255 if (!dns_cache_entry_count())
2256 break;
2257
2258 /* Get cutoff interval and remove entries. */
2259 time_t cutoff = now + time_inc;
2260 purge_expired_resolves(cutoff);
2261
2262 /* Update amount of bytes removed and array size. */
2263 size_t bytes_removed = current_size - dns_cache_total_allocation();
2264 current_size -= bytes_removed;
2265 total_bytes_removed += bytes_removed;
2266
2267 /* Increase time_inc by a reasonable fraction. */
2268 time_inc += (MAX_DNS_TTL / 4);
2269 } while (total_bytes_removed < min_remove_bytes);
2270
2271 return total_bytes_removed;
2272}
2273
2274#ifdef DEBUG_DNS_CACHE
2275/** Exit with an assertion if the DNS cache is corrupt. */
2276static void
2277assert_cache_ok_(void)
2278{
2279 cached_resolve_t **resolve;
2280 int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
2281 if (bad_rep) {
2282 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
2283 tor_assert(!bad_rep);
2284 }
2285
2286 HT_FOREACH(resolve, cache_map, &cache_root) {
2287 assert_resolve_ok(*resolve);
2288 tor_assert((*resolve)->state != CACHE_STATE_DONE);
2289 }
2291 return;
2292
2295 offsetof(cached_resolve_t, minheap_idx));
2296
2298 {
2299 if (res->state == CACHE_STATE_DONE) {
2300 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2301 tor_assert(!found || found != res);
2302 } else {
2303 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2304 tor_assert(found);
2305 }
2306 });
2307}
2308
2309#endif /* defined(DEBUG_DNS_CACHE) */
2310
2312dns_get_cache_entry(cached_resolve_t *query)
2313{
2314 return HT_FIND(cache_map, &cache_root, query);
2315}
2316
2317void
2318dns_insert_cache_entry(cached_resolve_t *new_entry)
2319{
2320 HT_INSERT(cache_map, &cache_root, new_entry);
2321}
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:889
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1349
int tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, int family, int accept_regular)
Definition: address.c:380
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:911
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out)
Definition: address.c:165
static const struct in_addr * tor_addr_to_in(const tor_addr_t *a)
Definition: address.h:204
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:187
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition: address.h:160
static const struct in6_addr * tor_addr_to_in6(const tor_addr_t *a)
Definition: address.h:117
#define tor_addr_from_ipv4h(dest, v4addr)
Definition: address.h:327
#define TOR_ADDR_BUF_LEN
Definition: address.h:224
static void set_uint32(void *cp, uint32_t v)
Definition: bytes.h:87
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1606
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:173
Header file for circuitlist.c.
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:154
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1357
Header file for circuituse.c.
#define MAX(a, b)
Definition: cmp.h:22
struct event_base * tor_libevent_get_base(void)
Header for compat_libevent.c.
const char * escaped_safe_str(const char *address)
Definition: config.c:1157
const or_options_t * get_options(void)
Definition: config.c:947
Header file for config.c.
void conflux_update_resolving_streams(or_circuit_t *circ, edge_connection_t *stream)
Definition: conflux_util.c:340
void conflux_update_n_streams(or_circuit_t *circ, edge_connection_t *stream)
Definition: conflux_util.c:324
Header file for conflux_util.c.
void assert_connection_ok(connection_t *conn, time_t now)
Definition: connection.c:5668
void connection_free_(connection_t *conn)
Definition: connection.c:968
Header file for connection.c.
#define CONN_TYPE_EXIT
Definition: connection.h:46
uint32_t clip_dns_fuzzy_ttl(uint32_t ttl)
void connection_exit_connect(edge_connection_t *edge_conn)
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
Header file for connection_edge.c.
#define EXIT_CONN_STATE_CONNECTING
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1082
#define BEGIN_FLAG_IPV6_PREFERRED
#define EXIT_CONN_STATE_RESOLVEFAILED
#define EXIT_PURPOSE_CONNECT
#define BEGIN_FLAG_IPV4_NOT_OK
#define EXIT_CONN_STATE_RESOLVING
#define DEFAULT_DNS_TTL
#define BEGIN_FLAG_IPV6_OK
#define EXIT_PURPOSE_RESOLVE
#define MAX_DNS_TTL
int control_event_server_status(int severity, const char *format,...)
Header file for control_events.c.
char * crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix, const char *suffix)
Definition: crypto_rand.c:554
Common functions for using (pseudo-)random number generators.
static int dns_wildcard_notice_given
Definition: dns.c:1888
STATIC int set_exitconn_info_from_resolve(edge_connection_t *exitconn, const cached_resolve_t *resolve, char **hostname_out)
Definition: dns.c:875
static const char * get_consensus_param_exit_dns_attempts(void)
Definition: dns.c:1417
static int dns_wildcard_one_notice_given
Definition: dns.c:1885
static int nameservers_configured
Definition: dns.c:93
int dns_init(void)
Definition: dns.c:233
static unsigned int cached_resolve_hash(cached_resolve_t *a)
Definition: dns.c:147
static void add_wildcarded_test_address(const char *address)
Definition: dns.c:1933
static int nameserver_config_failed
Definition: dns.c:95
static void dns_launch_wildcard_checks(void)
Definition: dns.c:2090
static void assert_resolve_ok(cached_resolve_t *resolve)
Definition: dns.c:2190
static char * resolv_conf_fname
Definition: dns.c:98
void dns_new_consensus_params(const networkstatus_t *ns)
Definition: dns.c:220
static int dns_cache_entry_count(void)
Definition: dns.c:2214
int dns_seems_to_be_broken(void)
Definition: dns.c:2143
STATIC void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type, const cached_resolve_t *resolved)
Definition: dns.c:509
void dns_reset_correctness_checks(void)
Definition: dns.c:2157
STATIC void send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
Definition: dns.c:584
static int n_wildcard_requests
Definition: dns.c:1871
static void init_cache_map(void)
Definition: dns.c:159
static struct evdns_base * the_evdns_base
Definition: dns.c:90
static void evdns_callback(int result, char type, int count, int ttl, void *addresses, void *arg)
Definition: dns.c:1631
static int configure_nameservers(int force)
Definition: dns.c:1497
static void inform_pending_connections(cached_resolve_t *resolve)
Definition: dns.c:1195
static smartlist_t * dns_wildcard_list
Definition: dns.c:1882
static void evdns_wildcard_check_callback(int result, char type, int count, int ttl, void *addresses, void *arg)
Definition: dns.c:1967
#define RESOLVE_MAX_TIMEOUT
Definition: dns.c:87
static void purge_expired_resolves(time_t now)
Definition: dns.c:417
STATIC void dns_cancel_pending_resolve(const char *address)
Definition: dns.c:1052
static int evdns_err_is_transient(int err)
Definition: dns.c:1336
size_t number_of_configured_nameservers(void)
Definition: dns.c:1353
void connection_dns_remove(edge_connection_t *conn)
Definition: dns.c:997
static smartlist_t * dns_wildcarded_test_address_list
Definition: dns.c:1892
int has_dns_init_failed(void)
Definition: dns.c:274
static int dns_is_completely_invalid
Definition: dns.c:1896
void dump_dns_mem_usage(int severity)
Definition: dns.c:2229
static void free_cached_resolve_(cached_resolve_t *r)
Definition: dns.c:281
void dns_free_all(void)
Definition: dns.c:392
STATIC int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve, or_circuit_t *oncirc, char **hostname_out, int *made_connection_pending_out, cached_resolve_t **resolve_out)
Definition: dns.c:723
static void launch_test_addresses(evutil_socket_t fd, short event, void *args)
Definition: dns.c:2050
static int dns_wildcarded_test_address_notice_given
Definition: dns.c:1894
static int launch_one_resolve(const char *address, uint8_t query_type, const tor_addr_t *ptr_address)
Definition: dns.c:1755
static void evdns_log_cb(int warn, const char *msg)
Definition: dns.c:166
static int answer_is_wildcarded(const char *ip)
Definition: dns.c:2183
STATIC int launch_resolve(cached_resolve_t *resolve)
Definition: dns.c:1810
int dns_seems_to_be_broken_for_ipv6(void)
Definition: dns.c:2150
int dns_resolve(edge_connection_t *exitconn)
Definition: dns.c:636
static strmap_t * dns_wildcard_response_count
Definition: dns.c:1877
static const char * get_consensus_param_exit_dns_timeout(void)
Definition: dns.c:1388
static time_t resolv_conf_mtime
Definition: dns.c:101
int dns_reset(void)
Definition: dns.c:246
static void launch_wildcard_check(int min_len, int max_len, int is_ipv6, const char *suffix)
Definition: dns.c:2016
static int is_test_address(const char *address)
Definition: dns.c:1125
static void configure_libevent_options(void)
Definition: dns.c:1436
static int compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
Definition: dns.c:300
static void make_pending_resolve_cached(cached_resolve_t *cached)
Definition: dns.c:1280
void dns_launch_correctness_checks(void)
Definition: dns.c:2121
static smartlist_t * cached_resolve_pqueue
Definition: dns.c:313
static int cached_resolve_have_all_answers(const cached_resolve_t *resolve)
Definition: dns.c:368
static void set_expiry(cached_resolve_t *resolve, time_t expires)
Definition: dns.c:378
static void dns_found_answer(const char *address, uint8_t query_type, int dns_answer, const tor_addr_t *addr, const char *hostname, uint32_t ttl)
Definition: dns.c:1142
static HT_HEAD(cache_map, cached_resolve_t)
Definition: dns.c:126
void assert_connection_edge_not_dns_pending(edge_connection_t *conn)
Definition: dns.c:970
static void wildcard_increment_answer(const char *id)
Definition: dns.c:1901
Header file for dns.c.
#define CACHE_STATE_PENDING
Definition: dns_structs.h:38
#define RES_STATUS_DONE_OK
Definition: dns_structs.h:53
#define MAX_ADDRESSLEN
Definition: dns_structs.h:19
#define CACHED_RESOLVE_MAGIC
Definition: dns_structs.h:29
#define CACHE_STATE_CACHED
Definition: dns_structs.h:45
#define RES_STATUS_DONE_ERR
Definition: dns_structs.h:55
#define RES_STATUS_INFLIGHT
Definition: dns_structs.h:51
#define CACHE_STATE_DONE
Definition: dns_structs.h:42
Edge-connection structure.
char * esc_for_log(const char *s)
Definition: escape.c:30
const char * escaped(const char *s)
Definition: escape.c:126
HT_PROTOTYPE(hs_circuitmap_ht, circuit_t, hs_circuitmap_node, hs_circuit_hash_token, hs_circuits_have_same_token)
int tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
Definition: inaddr.c:79
const char * tor_inet_ntop(int af, const void *src, char *dst, size_t len)
Definition: inaddr.c:98
#define INET_NTOA_BUF_LEN
Definition: inaddr.h:21
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:591
#define log_fn(severity, domain, args,...)
Definition: log.h:283
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:288
#define LD_MM
Definition: log.h:74
#define LD_FS
Definition: log.h:70
#define LD_BUG
Definition: log.h:86
#define LOG_NOTICE
Definition: log.h:50
#define LOG_WARN
Definition: log.h:53
#define LOG_INFO
Definition: log.h:45
void dns_servers_relaunch_checks(void)
Definition: mainloop.c:2349
Header file for mainloop.c.
void * tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
Definition: malloc.c:146
void tor_free_(void *mem)
Definition: malloc.c:227
#define tor_free(p)
Definition: malloc.h:56
int net_is_disabled(void)
Definition: netstatus.c:25
Header for netstatus.c.
#define SOCKET_OK(s)
Definition: nettypes.h:39
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
Header file for networkstatus.c.
Master header file for Tor-specific functionality.
#define RELAY_PAYLOAD_SIZE_MIN
Definition: or.h:570
#define TO_CONN(c)
Definition: or.h:700
#define RELAY_PAYLOAD_SIZE_MAX
Definition: or.h:567
Header file for policies.c.
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
int connection_edge_send_command(edge_connection_t *fromconn, uint8_t relay_command, const char *payload, size_t payload_len)
Definition: relay.c:766
Header file for relay.c.
void rep_hist_note_dns_error(int type, uint8_t error)
Definition: rephist.c:375
void rep_hist_note_dns_request(int type)
Definition: rephist.c:434
Header file for rephist.c.
int router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
Definition: router.c:1728
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2621
int router_my_exit_policy_is_reject_star(void)
Definition: router.c:1763
Header file for router.c.
int server_mode(const or_options_t *options)
Definition: routermode.c:34
Header file for routermode.c.
Header file for sandbox.c.
#define sandbox_intern_string(s)
Definition: sandbox.h:110
void smartlist_pqueue_assert_ok(smartlist_t *sl, int(*compare)(const void *a, const void *b), ptrdiff_t idx_field_offset)
Definition: smartlist.c:803
int smartlist_contains_string_case(const smartlist_t *sl, const char *element)
Definition: smartlist.c:133
void * smartlist_pqueue_pop(smartlist_t *sl, int(*compare)(const void *a, const void *b), ptrdiff_t idx_field_offset)
Definition: smartlist.c:755
void smartlist_pqueue_add(smartlist_t *sl, int(*compare)(const void *a, const void *b), ptrdiff_t idx_field_offset, void *item)
Definition: smartlist.c:726
int smartlist_contains_string(const smartlist_t *sl, const char *element)
Definition: smartlist.c:93
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
smartlist_t * smartlist_new(void)
void smartlist_clear(smartlist_t *sl)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
union cached_resolve_t::@24 result_ipv4
struct in6_addr addr_ipv6
Definition: dns_structs.h:73
uint32_t magic
Definition: dns_structs.h:64
union cached_resolve_t::@25 result_ipv6
uint32_t addr_ipv4
Definition: dns_structs.h:68
uint32_t ttl_ipv6
Definition: dns_structs.h:95
char address[MAX_ADDRESSLEN]
Definition: dns_structs.h:65
uint32_t ttl_ipv4
Definition: dns_structs.h:94
uint32_t ttl_hostname
Definition: dns_structs.h:96
pending_connection_t * pending_connections
Definition: dns_structs.h:98
uint8_t state
Definition: connection_st.h:49
unsigned int type
Definition: connection_st.h:50
uint16_t marked_for_close
uint16_t port
unsigned int purpose
Definition: connection_st.h:51
tor_socket_t s
tor_addr_t addr
unsigned int is_reverse_dns_lookup
struct edge_connection_t * next_stream
struct circuit_t * on_circuit
edge_connection_t * resolving_streams
Definition: or_circuit_st.h:50
edge_connection_t * n_streams
Definition: or_circuit_st.h:43
char * ServerDNSResolvConfFile
struct smartlist_t * ServerDNSTestAddresses
int ServerDNSSearchDomains
#define STATIC
Definition: testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
#define tor_assert(expr)
Definition: util_bug.h:103
#define tor_fragile_assert()
Definition: util_bug.h:278
void tor_strlower(char *s)
Definition: util_string.c:129
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:217
int tor_strisnonupper(const char *s)
Definition: util_string.c:173