Tor 0.4.9.0-alpha-dev
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 char buf[RELAY_PAYLOAD_SIZE], *cp = buf;
512 size_t buflen = 0;
513 uint32_t ttl;
514
515 buf[0] = answer_type;
516 ttl = conn->address_ttl;
517
518 switch (answer_type)
519 {
520 case RESOLVED_TYPE_AUTO:
521 if (resolved && resolved->res_status_ipv4 == RES_STATUS_DONE_OK) {
522 cp[0] = RESOLVED_TYPE_IPV4;
523 cp[1] = 4;
524 set_uint32(cp+2, htonl(resolved->result_ipv4.addr_ipv4));
525 set_uint32(cp+6, htonl(ttl));
526 cp += 10;
527 }
528 if (resolved && resolved->res_status_ipv6 == RES_STATUS_DONE_OK) {
529 const uint8_t *bytes = resolved->result_ipv6.addr_ipv6.s6_addr;
530 cp[0] = RESOLVED_TYPE_IPV6;
531 cp[1] = 16;
532 memcpy(cp+2, bytes, 16);
533 set_uint32(cp+18, htonl(ttl));
534 cp += 22;
535 }
536 if (cp != buf) {
537 buflen = cp - buf;
538 break;
539 } else {
540 answer_type = RESOLVED_TYPE_ERROR;
541 /* We let this fall through and treat it as an error. */
542 }
543 FALLTHROUGH;
544 case RESOLVED_TYPE_ERROR_TRANSIENT:
545 case RESOLVED_TYPE_ERROR:
546 {
547 const char *errmsg = "Error resolving hostname";
548 size_t msglen = strlen(errmsg);
549
550 buf[0] = answer_type;
551 buf[1] = msglen;
552 strlcpy(buf+2, errmsg, sizeof(buf)-2);
553 set_uint32(buf+2+msglen, htonl(ttl));
554 buflen = 6+msglen;
555 break;
556 }
557 default:
558 tor_assert(0);
559 return;
560 }
561 // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
562
563 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
564}
565
566void
567dns_send_resolved_error_cell(edge_connection_t *conn, uint8_t answer_type)
568{
569 send_resolved_cell(conn, answer_type, NULL);
570}
571
572/** Send a response to the RESOLVE request of a connection for an in-addr.arpa
573 * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
574 * The answer type will be RESOLVED_HOSTNAME.
575 *
576 * If <b>circ</b> is provided, and we have a cached answer, send the
577 * answer back along circ; otherwise, send the answer back along
578 * <b>conn</b>'s attached circuit.
579 */
580MOCK_IMPL(STATIC void,
582 const char *hostname))
583{
584 char buf[RELAY_PAYLOAD_SIZE];
585 size_t buflen;
586 uint32_t ttl;
587
588 if (BUG(!hostname))
589 return;
590
591 size_t namelen = strlen(hostname);
592
593 tor_assert(namelen < 256);
594 ttl = conn->address_ttl;
595
596 buf[0] = RESOLVED_TYPE_HOSTNAME;
597 buf[1] = (uint8_t)namelen;
598 memcpy(buf+2, hostname, namelen);
599 set_uint32(buf+2+namelen, htonl(ttl));
600 buflen = 2+namelen+4;
601
602 // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
603 connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
604 // log_notice(LD_EXIT, "Sent");
605}
606
607/** See if we have a cache entry for <b>exitconn</b>->address. If so,
608 * if resolve valid, put it into <b>exitconn</b>->addr and return 1.
609 * If resolve failed, free exitconn and return -1.
610 *
611 * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
612 * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
613 * need to send back an END cell, since connection_exit_begin_conn will
614 * do that for us.)
615 *
616 * If we have a cached answer, send the answer back along <b>exitconn</b>'s
617 * circuit.
618 *
619 * Else, if seen before and pending, add conn to the pending list,
620 * and return 0.
621 *
622 * Else, if not seen before, add conn to pending list, hand to
623 * dns farm, and return 0.
624 *
625 * Exitconn's on_circuit field must be set, but exitconn should not
626 * yet be linked onto the n_streams/resolving_streams list of that circuit.
627 * On success, link the connection to n_streams if it's an exit connection.
628 * On "pending", link the connection to resolving streams. Otherwise,
629 * clear its on_circuit field.
630 */
631int
633{
634 or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
635 int is_resolve, r;
636 int made_connection_pending = 0;
637 char *hostname = NULL;
638 cached_resolve_t *resolve = NULL;
639 is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
640
641 r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
642 &made_connection_pending, &resolve);
643
644 switch (r) {
645 case 1:
646 /* We got an answer without a lookup -- either the answer was
647 * cached, or it was obvious (like an IP address). */
648 if (is_resolve) {
649 /* Send the answer back right now, and detach. */
650 if (hostname)
651 send_resolved_hostname_cell(exitconn, hostname);
652 else
653 send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO, resolve);
654 exitconn->on_circuit = NULL;
655 } else {
656 /* Add to the n_streams list; the calling function will send back a
657 * connected cell. */
658 exitconn->next_stream = oncirc->n_streams;
659 oncirc->n_streams = exitconn;
660 conflux_update_n_streams(oncirc, exitconn);
661 }
662 break;
663 case 0:
664 /* The request is pending: add the connection into the linked list of
665 * resolving_streams on this circuit. */
666 exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
667 exitconn->next_stream = oncirc->resolving_streams;
668 oncirc->resolving_streams = exitconn;
669 conflux_update_resolving_streams(oncirc, exitconn);
670 break;
671 case -2:
672 case -1:
673 /* The request failed before it could start: cancel this connection,
674 * and stop everybody waiting for the same connection. */
675 if (is_resolve) {
676 send_resolved_cell(exitconn,
677 (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
678 NULL);
679 }
680
681 exitconn->on_circuit = NULL;
682
683 dns_cancel_pending_resolve(exitconn->base_.address);
684
685 if (!made_connection_pending && !exitconn->base_.marked_for_close) {
686 /* If we made the connection pending, then we freed it already in
687 * dns_cancel_pending_resolve(). If we marked it for close, it'll
688 * get freed from the main loop. Otherwise, can free it now. */
689 connection_free_(TO_CONN(exitconn));
690 }
691 break;
692 default:
693 tor_assert(0);
694 }
695
696 tor_free(hostname);
697 return r;
698}
699
700/** Helper function for dns_resolve: same functionality, but does not handle:
701 * - marking connections on error and clearing their on_circuit
702 * - linking connections to n_streams/resolving_streams,
703 * - sending resolved cells if we have an answer/error right away,
704 *
705 * Return -2 on a transient error. If it's a reverse resolve and it's
706 * successful, sets *<b>hostname_out</b> to a newly allocated string
707 * holding the cached reverse DNS value.
708 *
709 * Set *<b>made_connection_pending_out</b> to true if we have placed
710 * <b>exitconn</b> on the list of pending connections for some resolve; set it
711 * to false otherwise.
712 *
713 * Set *<b>resolve_out</b> to a cached resolve, if we found one.
714 */
715MOCK_IMPL(STATIC int,
716dns_resolve_impl,(edge_connection_t *exitconn, int is_resolve,
717 or_circuit_t *oncirc, char **hostname_out,
718 int *made_connection_pending_out,
719 cached_resolve_t **resolve_out))
720{
721 cached_resolve_t *resolve;
722 cached_resolve_t search;
723 pending_connection_t *pending_connection;
724 int is_reverse = 0;
725 tor_addr_t addr;
726 time_t now = time(NULL);
727 int r;
728 assert_connection_ok(TO_CONN(exitconn), 0);
729 tor_assert(!SOCKET_OK(exitconn->base_.s));
730 assert_cache_ok();
731 tor_assert(oncirc);
732 *made_connection_pending_out = 0;
733
734 /* first check if exitconn->base_.address is an IP. If so, we already
735 * know the answer. */
736 if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
737 if (tor_addr_family(&addr) == AF_INET ||
738 tor_addr_family(&addr) == AF_INET6) {
739 tor_addr_copy(&exitconn->base_.addr, &addr);
740 exitconn->address_ttl = DEFAULT_DNS_TTL;
741 return 1;
742 } else {
743 /* XXXX unspec? Bogus? */
744 return -1;
745 }
746 }
747
748 /* If we're a non-exit, don't even do DNS lookups. */
750 return -1;
751
752 if (address_is_invalid_destination(exitconn->base_.address, 0)) {
753 tor_log(LOG_PROTOCOL_WARN, LD_EXIT,
754 "Rejecting invalid destination address %s",
755 escaped_safe_str(exitconn->base_.address));
756 return -1;
757 }
758
759 /* then take this opportunity to see if there are any expired
760 * resolves in the hash table. */
762
763 /* lower-case exitconn->base_.address, so it's in canonical form */
764 tor_strlower(exitconn->base_.address);
765
766 /* Check whether this is a reverse lookup. If it's malformed, or it's a
767 * .in-addr.arpa address but this isn't a resolve request, kill the
768 * connection.
769 */
770 if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
771 AF_UNSPEC, 0)) != 0) {
772 if (r == 1) {
773 is_reverse = 1;
774 if (tor_addr_is_internal(&addr, 0)) /* internal address? */
775 return -1;
776 }
777
778 if (!is_reverse || !is_resolve) {
779 if (!is_reverse)
780 log_info(LD_EXIT, "Bad .in-addr.arpa address %s; sending error.",
781 escaped_safe_str(exitconn->base_.address));
782 else if (!is_resolve)
783 log_info(LD_EXIT,
784 "Attempt to connect to a .in-addr.arpa address %s; "
785 "sending error.",
786 escaped_safe_str(exitconn->base_.address));
787
788 return -1;
789 }
790 //log_notice(LD_EXIT, "Looks like an address %s",
791 //exitconn->base_.address);
792 }
793 exitconn->is_reverse_dns_lookup = is_reverse;
794
795 /* now check the hash table to see if 'address' is already there. */
796 strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
797 resolve = HT_FIND(cache_map, &cache_root, &search);
798 if (resolve && resolve->expire > now) { /* already there */
799 switch (resolve->state) {
801 /* add us to the pending list */
802 pending_connection = tor_malloc_zero(
803 sizeof(pending_connection_t));
804 pending_connection->conn = exitconn;
805 pending_connection->next = resolve->pending_connections;
806 resolve->pending_connections = pending_connection;
807 *made_connection_pending_out = 1;
808 log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") waiting "
809 "for pending DNS resolve of %s", exitconn->base_.s,
810 escaped_safe_str(exitconn->base_.address));
811 return 0;
813 log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") found "
814 "cached answer for %s",
815 exitconn->base_.s,
816 escaped_safe_str(resolve->address));
817
818 *resolve_out = resolve;
819
820 return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
821 case CACHE_STATE_DONE:
822 log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
824 }
825 tor_assert(0);
826 }
827 tor_assert(!resolve);
828 /* not there, need to add it */
829 resolve = tor_malloc_zero(sizeof(cached_resolve_t));
830 resolve->magic = CACHED_RESOLVE_MAGIC;
831 resolve->state = CACHE_STATE_PENDING;
832 resolve->minheap_idx = -1;
833 strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
834
835 /* add this connection to the pending list */
836 pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
837 pending_connection->conn = exitconn;
838 resolve->pending_connections = pending_connection;
839 *made_connection_pending_out = 1;
840
841 /* Add this resolve to the cache and priority queue. */
842 HT_INSERT(cache_map, &cache_root, resolve);
843 set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
844
845 log_debug(LD_EXIT,"Launching %s.",
846 escaped_safe_str(exitconn->base_.address));
847 assert_cache_ok();
848
849 return launch_resolve(resolve);
850}
851
852/** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
853 * <b>resolve</b> whose DNS lookups have all either succeeded or failed,
854 * update the appropriate fields (address_ttl and addr) of <b>exitconn</b>.
855 *
856 * The logic can be complicated here, since we might have launched both
857 * an A lookup and an AAAA lookup, and since either of those might have
858 * succeeded or failed, and since we want to answer a RESOLVE cell with
859 * a full answer but answer a BEGIN cell with whatever answer the client
860 * would accept <i>and</i> we could still connect to.
861 *
862 * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
863 * copy of the name resulting hostname.
864 *
865 * Return -2 on a transient error, -1 on a permenent error, and 1 on
866 * a successful lookup.
867 */
868MOCK_IMPL(STATIC int,
870 const cached_resolve_t *resolve,
871 char **hostname_out))
872{
873 int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
874 uint32_t begincell_flags;
875 const int is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
876 tor_assert(exitconn);
877 tor_assert(resolve);
878
879 if (exitconn->is_reverse_dns_lookup) {
880 exitconn->address_ttl = resolve->ttl_hostname;
881 if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
882 *hostname_out = tor_strdup(resolve->result_ptr.hostname);
883 return 1;
884 } else {
885 return -1;
886 }
887 }
888
889 /* If we're here then the connection wants one or either of ipv4, ipv6, and
890 * we can give it one or both. */
891 if (is_resolve) {
892 begincell_flags = BEGIN_FLAG_IPV6_OK;
893 } else {
894 begincell_flags = exitconn->begincell_flags;
895 }
896
897 ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
898 ! (begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
899 ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
900 (begincell_flags & BEGIN_FLAG_IPV6_OK) &&
902
903 /* Now decide which one to actually give. */
904 if (ipv4_ok && ipv6_ok && is_resolve) {
905 answer_with_ipv4 = 1;
906 } else if (ipv4_ok && ipv6_ok) {
907 /* If we have both, see if our exit policy has an opinion. */
908 const uint16_t port = exitconn->base_.port;
909 int ipv4_allowed, ipv6_allowed;
910 tor_addr_t a4, a6;
913 ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
914 ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
915 if (ipv4_allowed && !ipv6_allowed) {
916 answer_with_ipv4 = 1;
917 } else if (ipv6_allowed && !ipv4_allowed) {
918 answer_with_ipv4 = 0;
919 } else {
920 /* Our exit policy would permit both. Answer with whichever the user
921 * prefers */
922 answer_with_ipv4 = !(begincell_flags &
924 }
925 } else {
926 /* Otherwise if one is okay, send it back. */
927 if (ipv4_ok) {
928 answer_with_ipv4 = 1;
929 } else if (ipv6_ok) {
930 answer_with_ipv4 = 0;
931 } else {
932 /* Neither one was okay. Choose based on user preference. */
933 answer_with_ipv4 = !(begincell_flags &
935 }
936 }
937
938 /* Finally, we write the answer back. */
939 r = 1;
940 if (answer_with_ipv4) {
941 if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
942 tor_addr_from_ipv4h(&exitconn->base_.addr,
943 resolve->result_ipv4.addr_ipv4);
944 } else {
945 r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
946 }
947
948 exitconn->address_ttl = resolve->ttl_ipv4;
949 } else {
950 if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
951 tor_addr_from_in6(&exitconn->base_.addr,
952 &resolve->result_ipv6.addr_ipv6);
953 } else {
954 r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
955 }
956
957 exitconn->address_ttl = resolve->ttl_ipv6;
958 }
959
960 return r;
961}
962
963/** Log an error and abort if conn is waiting for a DNS resolve.
964 */
965void
967{
969 cached_resolve_t search;
970
971#if 1
972 cached_resolve_t *resolve;
973 strlcpy(search.address, conn->base_.address, sizeof(search.address));
974 resolve = HT_FIND(cache_map, &cache_root, &search);
975 if (!resolve)
976 return;
977 for (pend = resolve->pending_connections; pend; pend = pend->next) {
978 tor_assert(pend->conn != conn);
979 }
980#else /* !(1) */
981 cached_resolve_t **resolve;
982 HT_FOREACH(resolve, cache_map, &cache_root) {
983 for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
984 tor_assert(pend->conn != conn);
985 }
986 }
987#endif /* 1 */
988}
989
990/** Remove <b>conn</b> from the list of connections waiting for conn->address.
991 */
992void
994{
995 pending_connection_t *pend, *victim;
996 cached_resolve_t search;
997 cached_resolve_t *resolve;
998
999 tor_assert(conn->base_.type == CONN_TYPE_EXIT);
1001
1002 strlcpy(search.address, conn->base_.address, sizeof(search.address));
1003
1004 resolve = HT_FIND(cache_map, &cache_root, &search);
1005 if (!resolve) {
1006 log_notice(LD_BUG, "Address %s is not pending. Dropping.",
1007 escaped_safe_str(conn->base_.address));
1008 return;
1009 }
1010
1013
1014 pend = resolve->pending_connections;
1015
1016 if (pend->conn == conn) {
1017 resolve->pending_connections = pend->next;
1018 tor_free(pend);
1019 log_debug(LD_EXIT, "First connection (fd "TOR_SOCKET_T_FORMAT") no "
1020 "longer waiting for resolve of %s",
1021 conn->base_.s,
1022 escaped_safe_str(conn->base_.address));
1023 return;
1024 } else {
1025 for ( ; pend->next; pend = pend->next) {
1026 if (pend->next->conn == conn) {
1027 victim = pend->next;
1028 pend->next = victim->next;
1029 tor_free(victim);
1030 log_debug(LD_EXIT,
1031 "Connection (fd "TOR_SOCKET_T_FORMAT") no longer waiting "
1032 "for resolve of %s",
1033 conn->base_.s, escaped_safe_str(conn->base_.address));
1034 return; /* more are pending */
1035 }
1036 }
1037 log_warn(LD_BUG, "Connection (fd "TOR_SOCKET_T_FORMAT") was not waiting "
1038 "for a resolve of %s, but we tried to remove it.",
1039 conn->base_.s, escaped_safe_str(conn->base_.address));
1040 }
1041}
1042
1043/** Mark all connections waiting for <b>address</b> for close. Then cancel
1044 * the resolve for <b>address</b> itself, and remove any cached results for
1045 * <b>address</b> from the cache.
1046 */
1047MOCK_IMPL(STATIC void,
1048dns_cancel_pending_resolve,(const char *address))
1049{
1051 cached_resolve_t search;
1052 cached_resolve_t *resolve, *tmp;
1053 edge_connection_t *pendconn;
1054 circuit_t *circ;
1055
1056 strlcpy(search.address, address, sizeof(search.address));
1057
1058 resolve = HT_FIND(cache_map, &cache_root, &search);
1059 if (!resolve)
1060 return;
1061
1062 if (resolve->state != CACHE_STATE_PENDING) {
1063 /* We can get into this state if we never actually created the pending
1064 * resolve, due to finding an earlier cached error or something. Just
1065 * ignore it. */
1066 if (resolve->pending_connections) {
1067 log_warn(LD_BUG,
1068 "Address %s is not pending but has pending connections!",
1069 escaped_safe_str(address));
1071 }
1072 return;
1073 }
1074
1075 if (!resolve->pending_connections) {
1076 log_warn(LD_BUG,
1077 "Address %s is pending but has no pending connections!",
1078 escaped_safe_str(address));
1080 return;
1081 }
1083
1084 /* mark all pending connections to fail */
1085 log_debug(LD_EXIT,
1086 "Failing all connections waiting on DNS resolve of %s",
1087 escaped_safe_str(address));
1088 while (resolve->pending_connections) {
1089 pend = resolve->pending_connections;
1090 pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1091 pendconn = pend->conn;
1092 assert_connection_ok(TO_CONN(pendconn), 0);
1093 tor_assert(!SOCKET_OK(pendconn->base_.s));
1094 if (!pendconn->base_.marked_for_close) {
1095 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1096 }
1097 circ = circuit_get_by_edge_conn(pendconn);
1098 if (circ)
1099 circuit_detach_stream(circ, pendconn);
1100 if (!pendconn->base_.marked_for_close)
1101 connection_free_(TO_CONN(pendconn));
1102 resolve->pending_connections = pend->next;
1103 tor_free(pend);
1104 }
1105
1106 tmp = HT_REMOVE(cache_map, &cache_root, resolve);
1107 if (tmp != resolve) {
1108 log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
1109 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1110 resolve->address, (void*)resolve,
1111 tmp ? tmp->address : "NULL", (void*)tmp);
1112 }
1113 tor_assert(tmp == resolve);
1114
1115 resolve->state = CACHE_STATE_DONE;
1116}
1117
1118/** Return true iff <b>address</b> is one of the addresses we use to verify
1119 * that well-known sites aren't being hijacked by our DNS servers. */
1120static inline int
1121is_test_address(const char *address)
1122{
1123 const or_options_t *options = get_options();
1124 return options->ServerDNSTestAddresses &&
1126}
1127
1128/** Called on the OR side when the eventdns library tells us the outcome of a
1129 * single DNS resolve: remember the answer, and tell all pending connections
1130 * about the result of the lookup if the lookup is now done. (<b>address</b>
1131 * is a NUL-terminated string containing the address to look up;
1132 * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
1133 * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
1134 * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
1135 * <b>ttl</b> is the time-to-live of this answer, in seconds.)
1136 */
1137static void
1138dns_found_answer(const char *address, uint8_t query_type,
1139 int dns_answer,
1140 const tor_addr_t *addr,
1141 const char *hostname, uint32_t ttl)
1142{
1143 cached_resolve_t search;
1144 cached_resolve_t *resolve;
1145
1146 assert_cache_ok();
1147
1148 strlcpy(search.address, address, sizeof(search.address));
1149
1150 resolve = HT_FIND(cache_map, &cache_root, &search);
1151 if (!resolve) {
1152 int is_test_addr = is_test_address(address);
1153 if (!is_test_addr)
1154 log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
1155 escaped_safe_str(address));
1156 return;
1157 }
1158 assert_resolve_ok(resolve);
1159
1160 if (resolve->state != CACHE_STATE_PENDING) {
1161 /* XXXX Maybe update addr? or check addr for consistency? Or let
1162 * VALID replace FAILED? */
1163 int is_test_addr = is_test_address(address);
1164 if (!is_test_addr)
1165 log_notice(LD_EXIT,
1166 "Resolved %s which was already resolved; ignoring",
1167 escaped_safe_str(address));
1168 tor_assert(resolve->pending_connections == NULL);
1169 return;
1170 }
1171
1172 cached_resolve_add_answer(resolve, query_type, dns_answer,
1173 addr, hostname, ttl);
1174
1175 if (cached_resolve_have_all_answers(resolve)) {
1177
1179 }
1180}
1181
1182/** Given a pending cached_resolve_t that we just finished resolving,
1183 * inform every connection that was waiting for the outcome of that
1184 * resolution.
1185 *
1186 * Do this by sending a RELAY_RESOLVED cell (if the pending stream had sent us
1187 * RELAY_RESOLVE cell), or by launching an exit connection (if the pending
1188 * stream had send us a RELAY_BEGIN cell).
1189 */
1190static void
1192{
1194 edge_connection_t *pendconn;
1195 int r;
1196
1197 while (resolve->pending_connections) {
1198 char *hostname = NULL;
1199 pend = resolve->pending_connections;
1200 pendconn = pend->conn; /* don't pass complex things to the
1201 connection_mark_for_close macro */
1202 assert_connection_ok(TO_CONN(pendconn),time(NULL));
1203
1204 if (pendconn->base_.marked_for_close) {
1205 /* prevent double-remove. */
1206 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1207 resolve->pending_connections = pend->next;
1208 tor_free(pend);
1209 continue;
1210 }
1211
1212 r = set_exitconn_info_from_resolve(pendconn,
1213 resolve,
1214 &hostname);
1215
1216 if (r < 0) {
1217 /* prevent double-remove. */
1218 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1219 if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1220 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1221 /* This detach must happen after we send the end cell. */
1223 } else {
1224 send_resolved_cell(pendconn, r == -1 ?
1225 RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
1226 NULL);
1227 /* This detach must happen after we send the resolved cell. */
1229 }
1230 connection_free_(TO_CONN(pendconn));
1231 } else {
1232 circuit_t *circ;
1233 if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1234 /* prevent double-remove. */
1235 pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
1236
1237 circ = circuit_get_by_edge_conn(pend->conn);
1238 tor_assert(circ);
1240 /* unlink pend->conn from resolving_streams, */
1241 circuit_detach_stream(circ, pend->conn);
1242 /* and link it to n_streams */
1243 pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1244 pend->conn->on_circuit = circ;
1245 TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1246 conflux_update_n_streams(TO_OR_CIRCUIT(circ), pend->conn);
1247
1248 connection_exit_connect(pend->conn);
1249 } else {
1250 /* prevent double-remove. This isn't really an accurate state,
1251 * but it does the right thing. */
1252 pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1253 if (pendconn->is_reverse_dns_lookup)
1254 send_resolved_hostname_cell(pendconn, hostname);
1255 else
1256 send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO, resolve);
1257 circ = circuit_get_by_edge_conn(pendconn);
1258 tor_assert(circ);
1259 circuit_detach_stream(circ, pendconn);
1260 connection_free_(TO_CONN(pendconn));
1261 }
1262 }
1263 resolve->pending_connections = pend->next;
1264 tor_free(pend);
1265 tor_free(hostname);
1266 }
1267}
1268
1269/** Remove a pending cached_resolve_t from the hashtable, and add a
1270 * corresponding cached cached_resolve_t.
1271 *
1272 * This function is only necessary because of the perversity of our
1273 * cache timeout code; see inline comment for ideas on eliminating it.
1274 **/
1275static void
1277{
1278 cached_resolve_t *removed;
1279
1280 resolve->state = CACHE_STATE_DONE;
1281 removed = HT_REMOVE(cache_map, &cache_root, resolve);
1282 if (removed != resolve) {
1283 log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1284 " the cache. Tried to purge %s (%p); instead got %s (%p).",
1285 resolve->address, (void*)resolve,
1286 removed ? removed->address : "NULL", (void*)removed);
1287 }
1288 assert_resolve_ok(resolve);
1289 assert_cache_ok();
1290 /* The resolve will eventually just hit the time-out in the expiry queue and
1291 * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
1292 * way. XXXXX we could do better!*/
1293
1294 {
1295 cached_resolve_t *new_resolve = tor_memdup(resolve,
1296 sizeof(cached_resolve_t));
1297 uint32_t ttl = UINT32_MAX;
1298 new_resolve->expire = 0; /* So that set_expiry won't croak. */
1299 if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
1300 new_resolve->result_ptr.hostname =
1301 tor_strdup(resolve->result_ptr.hostname);
1302
1303 new_resolve->state = CACHE_STATE_CACHED;
1304
1305 assert_resolve_ok(new_resolve);
1306 HT_INSERT(cache_map, &cache_root, new_resolve);
1307
1308 if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
1309 resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
1310 resolve->ttl_ipv4 < ttl)
1311 ttl = resolve->ttl_ipv4;
1312
1313 if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
1314 resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
1315 resolve->ttl_ipv6 < ttl)
1316 ttl = resolve->ttl_ipv6;
1317
1318 if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
1319 resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
1320 resolve->ttl_hostname < ttl)
1321 ttl = resolve->ttl_hostname;
1322
1323 set_expiry(new_resolve, time(NULL) + ttl);
1324 }
1325
1326 assert_cache_ok();
1327}
1328
1329/** Eventdns helper: return true iff the eventdns result <b>err</b> is
1330 * a transient failure. */
1331static int
1333{
1334 switch (err)
1335 {
1336 case DNS_ERR_SERVERFAILED:
1337 case DNS_ERR_TRUNCATED:
1338 case DNS_ERR_TIMEOUT:
1339 return 1;
1340 default:
1341 return 0;
1342 }
1343}
1344
1345/**
1346 * Return number of configured nameservers in <b>the_evdns_base</b>.
1347 */
1348size_t
1350{
1351 return evdns_base_count_nameservers(the_evdns_base);
1352}
1353
1354#ifdef HAVE_EVDNS_BASE_GET_NAMESERVER_ADDR
1355/**
1356 * Return address of configured nameserver in <b>the_evdns_base</b>
1357 * at index <b>idx</b>.
1358 */
1359tor_addr_t *
1360configured_nameserver_address(const size_t idx)
1361{
1362 struct sockaddr_storage sa;
1363 ev_socklen_t sa_len = sizeof(sa);
1364
1365 if (evdns_base_get_nameserver_addr(the_evdns_base, (int)idx,
1366 (struct sockaddr *)&sa,
1367 sa_len) > 0) {
1368 tor_addr_t *tor_addr = tor_malloc(sizeof(tor_addr_t));
1369 if (tor_addr_from_sockaddr(tor_addr,
1370 (const struct sockaddr *)&sa,
1371 NULL) == 0) {
1372 return tor_addr;
1373 }
1374 tor_free(tor_addr);
1375 }
1376
1377 return NULL;
1378}
1379#endif /* defined(HAVE_EVDNS_BASE_GET_NAMESERVER_ADDR) */
1380
1381/** Return a pointer to a stack allocated buffer containing the string
1382 * representation of the exit_dns_timeout consensus parameter. */
1383static const char *
1385{
1386 static char str[4];
1387
1388 /* Get the Exit DNS timeout value from the consensus or default. This is in
1389 * milliseconds. */
1390#define EXIT_DNS_TIMEOUT_DEFAULT (1000)
1391#define EXIT_DNS_TIMEOUT_MIN (1)
1392#define EXIT_DNS_TIMEOUT_MAX (120000)
1393 int32_t val = networkstatus_get_param(NULL, "exit_dns_timeout",
1394 EXIT_DNS_TIMEOUT_DEFAULT,
1395 EXIT_DNS_TIMEOUT_MIN,
1396 EXIT_DNS_TIMEOUT_MAX);
1397 /* NOTE: We convert it to seconds because libevent only supports that. In the
1398 * future, if we support different resolver(s), we might want to specialize
1399 * this call. */
1400
1401 /* NOTE: We also don't allow 0 and so we must cap the division to 1 second
1402 * else all DNS request would fail if the consensus would ever tell us a
1403 * value below 1000 (1 sec). */
1404 val = MAX(1, val / 1000);
1405
1406 tor_snprintf(str, sizeof(str), "%d", val);
1407 return str;
1408}
1409
1410/** Return a pointer to a stack allocated buffer containing the string
1411 * representation of the exit_dns_num_attempts consensus parameter. */
1412static const char *
1414{
1415 static char str[4];
1416
1417 /* Get the Exit DNS number of attempt value from the consensus or default. */
1418#define EXIT_DNS_NUM_ATTEMPTS_DEFAULT (2)
1419#define EXIT_DNS_NUM_ATTEMPTS_MIN (0)
1420#define EXIT_DNS_NUM_ATTEMPTS_MAX (255)
1421 int32_t val = networkstatus_get_param(NULL, "exit_dns_num_attempts",
1422 EXIT_DNS_NUM_ATTEMPTS_DEFAULT,
1423 EXIT_DNS_NUM_ATTEMPTS_MIN,
1424 EXIT_DNS_NUM_ATTEMPTS_MAX);
1425 tor_snprintf(str, sizeof(str), "%d", val);
1426 return str;
1427}
1428
1429/** Configure the libevent options. This can safely be called after
1430 * initialization or even if the evdns base is not set. */
1431static void
1433{
1434 /* This is possible because we can get called when a new consensus is set
1435 * while the DNS subsystem is not initialized just yet. It should be
1436 * harmless. */
1437 if (!the_evdns_base) {
1438 return;
1439 }
1440
1441#define SET(k,v) evdns_base_set_option(the_evdns_base, (k), (v))
1442
1443 // If we only have one nameserver, it does not make sense to back off
1444 // from it for a timeout. Unfortunately, the value for max-timeouts is
1445 // currently clamped by libevent to 255, but it does not hurt to set
1446 // it higher in case libevent gets a patch for this. Higher-than-
1447 // default maximum of 3 with multiple nameservers to avoid spuriously
1448 // marking one down on bursts of timeouts resulting from scans/attacks
1449 // against non-responding authoritative DNS servers.
1450 if (evdns_base_count_nameservers(the_evdns_base) == 1) {
1451 SET("max-timeouts:", "1000000");
1452 } else {
1453 SET("max-timeouts:", "10");
1454 }
1455
1456 // Elongate the queue of maximum inflight dns requests, so if a bunch
1457 // remain pending at the resolver (happens commonly with Unbound) we won't
1458 // stall every other DNS request. This potentially means some wasted
1459 // CPU as there's a walk over a linear queue involved, but this is a
1460 // much better tradeoff compared to just failing DNS requests because
1461 // of a full queue.
1462 SET("max-inflight:", "8192");
1463
1464 /* Set timeout to be 1 second. This tells libevent that it shouldn't wait
1465 * more than N second to drop a DNS query and consider it "timed out". It is
1466 * very important to differentiate here a libevent timeout and a DNS server
1467 * timeout. And so, by setting this to N second, libevent sends back
1468 * "DNS_ERR_TIMEOUT" if that N second is reached which does NOT indicate that
1469 * the query itself timed out in transit. */
1470 SET("timeout:", get_consensus_param_exit_dns_timeout());
1471
1472 /* This tells libevent to attempt up to X times a DNS query if the previous
1473 * one failed to complete within N second. We believe that this should be
1474 * enough to catch temporary hiccups on the first query. But after that, it
1475 * should signal us that it won't be able to resolve it. */
1476 SET("attempts:", get_consensus_param_exit_dns_attempts());
1477
1478 if (get_options()->ServerDNSRandomizeCase)
1479 SET("randomize-case:", "1");
1480 else
1481 SET("randomize-case:", "0");
1482
1483#undef SET
1484}
1485
1486/** Configure eventdns nameservers if force is true, or if the configuration
1487 * has changed since the last time we called this function, or if we failed on
1488 * our last attempt. On Unix, this reads from /etc/resolv.conf or
1489 * options->ServerDNSResolvConfFile; on Windows, this reads from
1490 * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
1491 * -1 on failure. */
1492static int
1494{
1495 const or_options_t *options;
1496 const char *conf_fname;
1497 struct stat st;
1498 int r, flags;
1499 options = get_options();
1500 conf_fname = options->ServerDNSResolvConfFile;
1501#ifndef _WIN32
1502 if (!conf_fname)
1503 conf_fname = "/etc/resolv.conf";
1504#endif
1505 flags = DNS_OPTIONS_ALL;
1506
1507 if (!the_evdns_base) {
1508 if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
1509 log_err(LD_BUG, "Couldn't create an evdns_base");
1510 return -1;
1511 }
1512 }
1513
1514 evdns_set_log_fn(evdns_log_cb);
1515 if (conf_fname) {
1516 log_debug(LD_FS, "stat()ing %s", conf_fname);
1517 int missing_resolv_conf = 0;
1518 int stat_res = stat(sandbox_intern_string(conf_fname), &st);
1519
1520 if (stat_res) {
1521 log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1522 conf_fname, strerror(errno));
1523 missing_resolv_conf = 1;
1524 } else if (!force && resolv_conf_fname &&
1525 !strcmp(conf_fname,resolv_conf_fname)
1526 && st.st_mtime == resolv_conf_mtime) {
1527 log_info(LD_EXIT, "No change to '%s'", conf_fname);
1528 return 0;
1529 }
1530
1531 if (stat_res == 0 && st.st_size == 0)
1532 missing_resolv_conf = 1;
1533
1535 evdns_base_search_clear(the_evdns_base);
1536 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1537 }
1538#if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
1539 if (flags & DNS_OPTION_HOSTSFILE) {
1540 flags ^= DNS_OPTION_HOSTSFILE;
1541 log_debug(LD_FS, "Loading /etc/hosts");
1542 evdns_base_load_hosts(the_evdns_base,
1543 sandbox_intern_string("/etc/hosts"));
1544 }
1545#endif /* defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP) */
1546
1547 if (!missing_resolv_conf) {
1548 log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1549 if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
1550 sandbox_intern_string(conf_fname)))) {
1551 log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers "
1552 "in '%s' (%d)", conf_fname, conf_fname, r);
1553
1554 if (r != 6) // "r = 6" means "no DNS servers were in resolv.conf" -
1555 goto err; // in which case we expect libevent to add 127.0.0.1 as
1556 // fallback.
1557 }
1558 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1559 log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.",
1560 conf_fname);
1561 }
1562
1564 resolv_conf_fname = tor_strdup(conf_fname);
1565 resolv_conf_mtime = st.st_mtime;
1566 } else {
1567 log_warn(LD_EXIT, "Could not read your DNS config from '%s' - "
1568 "please investigate your DNS configuration. "
1569 "This is possibly a problem. Meanwhile, falling"
1570 " back to local DNS at 127.0.0.1.", conf_fname);
1571 evdns_base_nameserver_ip_add(the_evdns_base, "127.0.0.1");
1572 }
1573
1575 evdns_base_resume(the_evdns_base);
1576 }
1577#ifdef _WIN32
1578 else {
1580 evdns_base_search_clear(the_evdns_base);
1581 evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1582 }
1583 if (evdns_base_config_windows_nameservers(the_evdns_base)) {
1584 log_warn(LD_EXIT,"Could not config nameservers.");
1585 goto err;
1586 }
1587 if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1588 log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1589 "your Windows configuration.");
1590 goto err;
1591 }
1593 evdns_base_resume(the_evdns_base);
1596 }
1597#endif /* defined(_WIN32) */
1598
1599 /* Setup libevent options. */
1601
1602 /* Relaunch periodical DNS check event. */
1604
1608 /* XXX the three calls to republish the descriptor might be producing
1609 * descriptors that are only cosmetically different, especially on
1610 * non-exit relays! -RD */
1611 mark_my_descriptor_dirty("dns resolvers back");
1612 }
1613 return 0;
1614 err:
1618 mark_my_descriptor_dirty("dns resolvers failed");
1619 }
1620 return -1;
1621}
1622
1623/** For eventdns: Called when we get an answer for a request we launched.
1624 * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
1625 */
1626static void
1627evdns_callback(int result, char type, int count, int ttl, void *addresses,
1628 void *arg)
1629{
1630 char *arg_ = arg;
1631 uint8_t orig_query_type = arg_[0];
1632 char *string_address = arg_ + 1;
1633 tor_addr_t addr;
1634 const char *hostname = NULL;
1635 int was_wildcarded = 0;
1636
1637 tor_addr_make_unspec(&addr);
1638
1639 /* Keep track of whether IPv6 is working */
1640 if (type == DNS_IPv6_AAAA) {
1641 if (result == DNS_ERR_TIMEOUT) {
1642 ++n_ipv6_timeouts;
1643 }
1644
1645 if (n_ipv6_timeouts > 10 &&
1646 n_ipv6_timeouts > n_ipv6_requests_made / 2) {
1647 if (! dns_is_broken_for_ipv6) {
1648 log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
1649 "have timed out. I'm going to assume I can't get AAAA "
1650 "responses.");
1651 dns_is_broken_for_ipv6 = 1;
1652 }
1653 }
1654 }
1655
1656 if (result == DNS_ERR_NONE) {
1657 if (type == DNS_IPv4_A && count) {
1658 char answer_buf[INET_NTOA_BUF_LEN+1];
1659 char *escaped_address;
1660 uint32_t *addrs = addresses;
1661 tor_addr_from_ipv4n(&addr, addrs[0]);
1662
1663 tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
1664 escaped_address = esc_for_log(string_address);
1665
1666 if (answer_is_wildcarded(answer_buf)) {
1667 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1668 "address %s; treating as a failure.",
1669 safe_str(escaped_address),
1670 escaped_safe_str(answer_buf));
1671 was_wildcarded = 1;
1672 tor_addr_make_unspec(&addr);
1673 result = DNS_ERR_NOTEXIST;
1674 } else {
1675 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1676 safe_str(escaped_address),
1677 escaped_safe_str(answer_buf));
1678 }
1679 tor_free(escaped_address);
1680 } else if (type == DNS_IPv6_AAAA && count) {
1681 char answer_buf[TOR_ADDR_BUF_LEN];
1682 char *escaped_address;
1683 const char *ip_str;
1684 struct in6_addr *addrs = addresses;
1685 tor_addr_from_in6(&addr, &addrs[0]);
1686 ip_str = tor_inet_ntop(AF_INET6, &addrs[0], answer_buf,
1687 sizeof(answer_buf));
1688 escaped_address = esc_for_log(string_address);
1689
1690 if (BUG(ip_str == NULL)) {
1691 log_warn(LD_EXIT, "tor_inet_ntop() failed!");
1692 result = DNS_ERR_NOTEXIST;
1693 } else if (answer_is_wildcarded(answer_buf)) {
1694 log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1695 "address %s; treating as a failure.",
1696 safe_str(escaped_address),
1697 escaped_safe_str(answer_buf));
1698 was_wildcarded = 1;
1699 tor_addr_make_unspec(&addr);
1700 result = DNS_ERR_NOTEXIST;
1701 } else {
1702 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1703 safe_str(escaped_address),
1704 escaped_safe_str(answer_buf));
1705 }
1706 tor_free(escaped_address);
1707 } else if (type == DNS_PTR && count) {
1708 char *escaped_address;
1709 hostname = ((char**)addresses)[0];
1710 escaped_address = esc_for_log(string_address);
1711 log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1712 safe_str(escaped_address),
1713 escaped_safe_str(hostname));
1714 tor_free(escaped_address);
1715 } else if (count) {
1716 log_info(LD_EXIT, "eventdns returned only unrecognized answer types "
1717 " for %s.",
1718 escaped_safe_str(string_address));
1719 } else {
1720 log_info(LD_EXIT, "eventdns returned no addresses or error for %s.",
1721 escaped_safe_str(string_address));
1722 }
1723 }
1724 if (was_wildcarded) {
1725 if (is_test_address(string_address)) {
1726 /* Ick. We're getting redirected on known-good addresses. Our DNS
1727 * server must really hate us. */
1728 add_wildcarded_test_address(string_address);
1729 }
1730 }
1731
1732 if (orig_query_type && type && orig_query_type != type) {
1733 log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
1734 (int)orig_query_type, (int)type);
1735 }
1736 if (result != DNS_ERR_SHUTDOWN)
1737 dns_found_answer(string_address, orig_query_type,
1738 result, &addr, hostname, clip_dns_fuzzy_ttl(ttl));
1739
1740 /* The result can be changed within this function thus why we note the result
1741 * at the end. */
1742 rep_hist_note_dns_error(type, result);
1743
1744 tor_free(arg_);
1745}
1746
1747/** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
1748 * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
1749 * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
1750static int
1751launch_one_resolve(const char *address, uint8_t query_type,
1752 const tor_addr_t *ptr_address)
1753{
1754 const int options = get_options()->ServerDNSSearchDomains ? 0
1755 : DNS_QUERY_NO_SEARCH;
1756 const size_t addr_len = strlen(address);
1757 struct evdns_request *req = 0;
1758 char *addr = tor_malloc(addr_len + 2);
1759 addr[0] = (char) query_type;
1760 memcpy(addr+1, address, addr_len + 1);
1761
1762 /* Note the query for our statistics. */
1763 rep_hist_note_dns_request(query_type);
1764
1765 switch (query_type) {
1766 case DNS_IPv4_A:
1767 req = evdns_base_resolve_ipv4(the_evdns_base,
1768 address, options, evdns_callback, addr);
1769 break;
1770 case DNS_IPv6_AAAA:
1771 req = evdns_base_resolve_ipv6(the_evdns_base,
1772 address, options, evdns_callback, addr);
1773 ++n_ipv6_requests_made;
1774 break;
1775 case DNS_PTR:
1776 if (tor_addr_family(ptr_address) == AF_INET)
1777 req = evdns_base_resolve_reverse(the_evdns_base,
1778 tor_addr_to_in(ptr_address),
1779 DNS_QUERY_NO_SEARCH,
1780 evdns_callback, addr);
1781 else if (tor_addr_family(ptr_address) == AF_INET6)
1782 req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
1783 tor_addr_to_in6(ptr_address),
1784 DNS_QUERY_NO_SEARCH,
1785 evdns_callback, addr);
1786 else
1787 log_warn(LD_BUG, "Called with PTR query and unexpected address family");
1788 break;
1789 default:
1790 log_warn(LD_BUG, "Called with unexpected query type %d", (int)query_type);
1791 break;
1792 }
1793
1794 if (req) {
1795 return 0;
1796 } else {
1797 tor_free(addr);
1798 return -1;
1799 }
1800}
1801
1802/** For eventdns: start resolving as necessary to find the target for
1803 * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
1804 * 0 on "resolve launched." */
1805MOCK_IMPL(STATIC int,
1807{
1808 tor_addr_t a;
1809 int r;
1810
1811 if (net_is_disabled())
1812 return -1;
1813
1814 /* What? Nameservers not configured? Sounds like a bug. */
1816 log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1817 "launched. Configuring.");
1818 if (configure_nameservers(1) < 0) {
1819 return -1;
1820 }
1821 }
1822
1824 &a, resolve->address, AF_UNSPEC, 0);
1825
1827 if (r == 0) {
1828 log_info(LD_EXIT, "Launching eventdns request for %s",
1829 escaped_safe_str(resolve->address));
1830 resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
1831 if (get_options()->IPv6Exit)
1832 resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
1833
1834 if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
1835 resolve->res_status_ipv4 = 0;
1836 r = -1;
1837 }
1838
1839 if (r==0 && get_options()->IPv6Exit) {
1840 /* We ask for an IPv6 address for *everything*. */
1841 if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
1842 resolve->res_status_ipv6 = 0;
1843 r = -1;
1844 }
1845 }
1846 } else if (r == 1) {
1847 r = 0;
1848 log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1849 escaped_safe_str(resolve->address));
1850 resolve->res_status_hostname = RES_STATUS_INFLIGHT;
1851 if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
1852 resolve->res_status_hostname = 0;
1853 r = -1;
1854 }
1855 } else if (r == -1) {
1856 log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1857 }
1858
1859 if (r < 0) {
1860 log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
1861 escaped_safe_str(resolve->address));
1862 }
1863 return r;
1864}
1865
1866/** How many requests for bogus addresses have we launched so far? */
1867static int n_wildcard_requests = 0;
1868
1869/** Map from dotted-quad IP address in response to an int holding how many
1870 * times we've seen it for a randomly generated (hopefully bogus) address. It
1871 * would be easier to use definitely-invalid addresses (as specified by
1872 * RFC2606), but see comment in dns_launch_wildcard_checks(). */
1873static strmap_t *dns_wildcard_response_count = NULL;
1874
1875/** If present, a list of dotted-quad IP addresses that we are pretty sure our
1876 * nameserver wants to return in response to requests for nonexistent domains.
1877 */
1879/** True iff we've logged about a single address getting wildcarded.
1880 * Subsequent warnings will be less severe. */
1882/** True iff we've warned that our DNS server is wildcarding too many failures.
1883 */
1885
1886/** List of supposedly good addresses that are getting wildcarded to the
1887 * same addresses as nonexistent addresses. */
1889/** True iff we've warned about a test address getting wildcarded */
1891/** True iff all addresses seem to be getting wildcarded. */
1893
1894/** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
1895 * to a request for a hopefully bogus address. */
1896static void
1898{
1899 int *ip;
1901 dns_wildcard_response_count = strmap_new();
1902
1903 ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1904 if (!ip) {
1905 ip = tor_malloc_zero(sizeof(int));
1906 strmap_set(dns_wildcard_response_count, id, ip);
1907 }
1908 ++*ip;
1909
1910 if (*ip > 5 && n_wildcard_requests > 10) {
1914 "Your DNS provider has given \"%s\" as an answer for %d different "
1915 "invalid addresses. Apparently they are hijacking DNS failures. "
1916 "I'll try to correct for this by treating future occurrences of "
1917 "\"%s\" as 'not found'.", id, *ip, id);
1919 }
1921 control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1923 }
1924}
1925
1926/** Note that a single test address (one believed to be good) seems to be
1927 * getting redirected to the same IP as failures are. */
1928static void
1930{
1931 int n, n_test_addrs;
1934
1936 address))
1937 return;
1938
1939 n_test_addrs = get_options()->ServerDNSTestAddresses ?
1940 smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1941
1943 n = smartlist_len(dns_wildcarded_test_address_list);
1944 if (n > n_test_addrs/2) {
1946 LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1947 "address. It has done this with %d test addresses so far. I'm "
1948 "going to stop being an exit node for now, since our DNS seems so "
1949 "broken.", address, n);
1952 mark_my_descriptor_dirty("dns hijacking confirmed");
1953 }
1955 control_event_server_status(LOG_WARN, "DNS_USELESS");
1957 }
1958}
1959
1960/** Callback function when we get an answer (possibly failing) for a request
1961 * for a (hopefully) nonexistent domain. */
1962static void
1963evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1964 void *addresses, void *arg)
1965{
1966 (void)ttl;
1967 const char *ip_str;
1969 if (result == DNS_ERR_NONE && count) {
1970 char *string_address = arg;
1971 int i;
1972 if (type == DNS_IPv4_A) {
1973 const uint32_t *addrs = addresses;
1974 for (i = 0; i < count; ++i) {
1975 char answer_buf[INET_NTOA_BUF_LEN+1];
1976 struct in_addr in;
1977 int ntoa_res;
1978 in.s_addr = addrs[i];
1979 ntoa_res = tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1980 tor_assert_nonfatal(ntoa_res >= 0);
1981 if (ntoa_res > 0)
1982 wildcard_increment_answer(answer_buf);
1983 }
1984 } else if (type == DNS_IPv6_AAAA) {
1985 const struct in6_addr *addrs = addresses;
1986 for (i = 0; i < count; ++i) {
1987 char answer_buf[TOR_ADDR_BUF_LEN+1];
1988 ip_str = tor_inet_ntop(AF_INET6, &addrs[i], answer_buf,
1989 sizeof(answer_buf));
1990 tor_assert_nonfatal(ip_str);
1991 if (ip_str)
1992 wildcard_increment_answer(answer_buf);
1993 }
1994 }
1995
1997 "Your DNS provider gave an answer for \"%s\", which "
1998 "is not supposed to exist. Apparently they are hijacking "
1999 "DNS failures. Trying to correct for this. We've noticed %d "
2000 "possibly bad address%s so far.",
2001 string_address, strmap_size(dns_wildcard_response_count),
2002 (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
2004 }
2005 tor_free(arg);
2006}
2007
2008/** Launch a single request for a nonexistent hostname consisting of between
2009 * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
2010 * <b>suffix</b> */
2011static void
2012launch_wildcard_check(int min_len, int max_len, int is_ipv6,
2013 const char *suffix)
2014{
2015 char *addr;
2016 struct evdns_request *req;
2017
2018 addr = crypto_random_hostname(min_len, max_len, "", suffix);
2019 log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
2020 "domains with request for bogus hostname \"%s\"", addr);
2021
2023 if (is_ipv6)
2024 req = evdns_base_resolve_ipv6(
2026 /* This "addr" tells us which address to resolve */
2027 addr,
2028 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
2029 /* This "addr" is an argument to the callback*/ addr);
2030 else
2031 req = evdns_base_resolve_ipv4(
2033 /* This "addr" tells us which address to resolve */
2034 addr,
2035 DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
2036 /* This "addr" is an argument to the callback*/ addr);
2037 if (!req) {
2038 /* There is no evdns request in progress; stop addr from getting leaked */
2039 tor_free(addr);
2040 }
2041}
2042
2043/** Launch attempts to resolve a bunch of known-good addresses (configured in
2044 * ServerDNSTestAddresses). [Callback for a libevent timer] */
2045static void
2046launch_test_addresses(evutil_socket_t fd, short event, void *args)
2047{
2048 const or_options_t *options = get_options();
2049 (void)fd;
2050 (void)event;
2051 (void)args;
2052
2053 if (net_is_disabled())
2054 return;
2055
2056 log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
2057 "hijack *everything*.");
2058 /* This situation is worse than the failure-hijacking situation. When this
2059 * happens, we're no good for DNS requests at all, and we shouldn't really
2060 * be an exit server.*/
2061 if (options->ServerDNSTestAddresses) {
2062
2065 const char *, address) {
2066 if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
2067 log_info(LD_EXIT, "eventdns rejected test address %s",
2068 escaped_safe_str(address));
2069 }
2070
2071 if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
2072 log_info(LD_EXIT, "eventdns rejected test address %s",
2073 escaped_safe_str(address));
2074 }
2075 } SMARTLIST_FOREACH_END(address);
2076 }
2077}
2078
2079#define N_WILDCARD_CHECKS 2
2080
2081/** Launch DNS requests for a few nonexistent hostnames and a few well-known
2082 * hostnames, and see if we can catch our nameserver trying to hijack them and
2083 * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
2084 * buy these lovely encyclopedias" page. */
2085static void
2087{
2088 int i, ipv6;
2089 log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
2090 "to hijack DNS failures.");
2091 for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
2092 for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
2093 /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
2094 * attempt to 'comply' with rfc2606, refrain from giving A records for
2095 * these. This is the standards-compliance equivalent of making sure
2096 * that your crackhouse's elevator inspection certificate is up to date.
2097 */
2098 launch_wildcard_check(2, 16, ipv6, ".invalid");
2099 launch_wildcard_check(2, 16, ipv6, ".test");
2100
2101 /* These will break specs if there are ever any number of
2102 * 8+-character top-level domains. */
2103 launch_wildcard_check(8, 16, ipv6, "");
2104
2105 /* Try some random .com/org/net domains. This will work fine so long as
2106 * not too many resolve to the same place. */
2107 launch_wildcard_check(8, 16, ipv6, ".com");
2108 launch_wildcard_check(8, 16, ipv6, ".org");
2109 launch_wildcard_check(8, 16, ipv6, ".net");
2110 }
2111 }
2112}
2113
2114/** If appropriate, start testing whether our DNS servers tend to lie to
2115 * us. */
2116void
2118{
2119 static struct event *launch_event = NULL;
2120 struct timeval timeout;
2121 if (!get_options()->ServerDNSDetectHijacking)
2122 return;
2124
2125 /* Wait a while before launching requests for test addresses, so we can
2126 * get the results from checking for wildcarding. */
2127 if (!launch_event)
2128 launch_event = tor_evtimer_new(tor_libevent_get_base(),
2129 launch_test_addresses, NULL);
2130 timeout.tv_sec = 30;
2131 timeout.tv_usec = 0;
2132 if (evtimer_add(launch_event, &timeout) < 0) {
2133 log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
2134 }
2135}
2136
2137/** Return true iff our DNS servers lie to us too much to be trusted. */
2138int
2140{
2142}
2143
2144/** Return true iff we think that IPv6 hostname lookup is broken */
2145int
2147{
2148 return dns_is_broken_for_ipv6;
2149}
2150
2151/** Forget what we've previously learned about our DNS servers' correctness. */
2152void
2154{
2157
2159
2160 n_ipv6_requests_made = n_ipv6_timeouts = 0;
2161
2162 if (dns_wildcard_list) {
2165 }
2168 tor_free(cp));
2170 }
2173 dns_is_broken_for_ipv6 = 0;
2174}
2175
2176/** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
2177 * returned in response to requests for nonexistent hostnames. */
2178static int
2180{
2182}
2183
2184/** Exit with an assertion if <b>resolve</b> is corrupt. */
2185static void
2187{
2188 tor_assert(resolve);
2190 tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
2192 if (resolve->state != CACHE_STATE_PENDING) {
2194 }
2195 if (resolve->state == CACHE_STATE_PENDING ||
2196 resolve->state == CACHE_STATE_DONE) {
2197#if 0
2198 tor_assert(!resolve->ttl);
2199 if (resolve->is_reverse)
2200 tor_assert(!resolve->hostname);
2201 else
2202 tor_assert(!resolve->result_ipv4.addr_ipv4);
2203#endif /* 0 */
2204 /*XXXXX ADD MORE */
2205 }
2206}
2207
2208/** Return the number of DNS cache entries as an int */
2209static int
2211{
2212 return HT_SIZE(&cache_root);
2213}
2214
2215/* Return the total size in bytes of the DNS cache. */
2216size_t
2217dns_cache_total_allocation(void)
2218{
2219 return sizeof(struct cached_resolve_t) * dns_cache_entry_count() +
2220 HT_MEM_USAGE(&cache_root);
2221}
2222
2223/** Log memory information about our internal DNS cache at level 'severity'. */
2224void
2226{
2227 /* This should never be larger than INT_MAX. */
2228 int hash_count = dns_cache_entry_count();
2229 size_t hash_mem = dns_cache_total_allocation();
2230
2231 /* Print out the count and estimated size of our &cache_root. It undercounts
2232 hostnames in cached reverse resolves.
2233 */
2234 tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
2235 tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
2236 (unsigned)hash_mem);
2237}
2238
2239/* Do a round of OOM cleanup on all DNS entries. Return the amount of removed
2240 * bytes. It is possible that the returned value is lower than min_remove_bytes
2241 * if the caches get emptied out so the caller should be aware of this. */
2242size_t
2243dns_cache_handle_oom(time_t now, size_t min_remove_bytes)
2244{
2245 time_t time_inc = 0;
2246 size_t total_bytes_removed = 0;
2247 size_t current_size = dns_cache_total_allocation();
2248
2249 do {
2250 /* If no DNS entries left, break loop. */
2251 if (!dns_cache_entry_count())
2252 break;
2253
2254 /* Get cutoff interval and remove entries. */
2255 time_t cutoff = now + time_inc;
2256 purge_expired_resolves(cutoff);
2257
2258 /* Update amount of bytes removed and array size. */
2259 size_t bytes_removed = current_size - dns_cache_total_allocation();
2260 current_size -= bytes_removed;
2261 total_bytes_removed += bytes_removed;
2262
2263 /* Increase time_inc by a reasonable fraction. */
2264 time_inc += (MAX_DNS_TTL / 4);
2265 } while (total_bytes_removed < min_remove_bytes);
2266
2267 return total_bytes_removed;
2268}
2269
2270#ifdef DEBUG_DNS_CACHE
2271/** Exit with an assertion if the DNS cache is corrupt. */
2272static void
2273assert_cache_ok_(void)
2274{
2275 cached_resolve_t **resolve;
2276 int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
2277 if (bad_rep) {
2278 log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
2279 tor_assert(!bad_rep);
2280 }
2281
2282 HT_FOREACH(resolve, cache_map, &cache_root) {
2283 assert_resolve_ok(*resolve);
2284 tor_assert((*resolve)->state != CACHE_STATE_DONE);
2285 }
2287 return;
2288
2291 offsetof(cached_resolve_t, minheap_idx));
2292
2294 {
2295 if (res->state == CACHE_STATE_DONE) {
2296 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2297 tor_assert(!found || found != res);
2298 } else {
2299 cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2300 tor_assert(found);
2301 }
2302 });
2303}
2304
2305#endif /* defined(DEBUG_DNS_CACHE) */
2306
2308dns_get_cache_entry(cached_resolve_t *query)
2309{
2310 return HT_FIND(cache_map, &cache_root, query);
2311}
2312
2313void
2314dns_insert_cache_entry(cached_resolve_t *new_entry)
2315{
2316 HT_INSERT(cache_map, &cache_root, new_entry);
2317}
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:1352
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:1148
const or_options_t * get_options(void)
Definition: config.c:944
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:5673
void connection_free_(connection_t *conn)
Definition: connection.c:972
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:1884
STATIC int set_exitconn_info_from_resolve(edge_connection_t *exitconn, const cached_resolve_t *resolve, char **hostname_out)
Definition: dns.c:871
static const char * get_consensus_param_exit_dns_attempts(void)
Definition: dns.c:1413
static int dns_wildcard_one_notice_given
Definition: dns.c:1881
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:1929
static int nameserver_config_failed
Definition: dns.c:95
static void dns_launch_wildcard_checks(void)
Definition: dns.c:2086
static void assert_resolve_ok(cached_resolve_t *resolve)
Definition: dns.c:2186
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:2210
int dns_seems_to_be_broken(void)
Definition: dns.c:2139
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:2153
STATIC void send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
Definition: dns.c:582
static int n_wildcard_requests
Definition: dns.c:1867
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:1627
static int configure_nameservers(int force)
Definition: dns.c:1493
static void inform_pending_connections(cached_resolve_t *resolve)
Definition: dns.c:1191
static smartlist_t * dns_wildcard_list
Definition: dns.c:1878
static void evdns_wildcard_check_callback(int result, char type, int count, int ttl, void *addresses, void *arg)
Definition: dns.c:1963
#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:1048
static int evdns_err_is_transient(int err)
Definition: dns.c:1332
size_t number_of_configured_nameservers(void)
Definition: dns.c:1349
void connection_dns_remove(edge_connection_t *conn)
Definition: dns.c:993
static smartlist_t * dns_wildcarded_test_address_list
Definition: dns.c:1888
int has_dns_init_failed(void)
Definition: dns.c:274
static int dns_is_completely_invalid
Definition: dns.c:1892
void dump_dns_mem_usage(int severity)
Definition: dns.c:2225
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:719
static void launch_test_addresses(evutil_socket_t fd, short event, void *args)
Definition: dns.c:2046
static int dns_wildcarded_test_address_notice_given
Definition: dns.c:1890
static int launch_one_resolve(const char *address, uint8_t query_type, const tor_addr_t *ptr_address)
Definition: dns.c:1751
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:2179
STATIC int launch_resolve(cached_resolve_t *resolve)
Definition: dns.c:1806
int dns_seems_to_be_broken_for_ipv6(void)
Definition: dns.c:2146
int dns_resolve(edge_connection_t *exitconn)
Definition: dns.c:632
static strmap_t * dns_wildcard_response_count
Definition: dns.c:1873
static const char * get_consensus_param_exit_dns_timeout(void)
Definition: dns.c:1384
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:2012
static int is_test_address(const char *address)
Definition: dns.c:1121
static void configure_libevent_options(void)
Definition: dns.c:1432
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:1276
void dns_launch_correctness_checks(void)
Definition: dns.c:2117
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:1138
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:966
static void wildcard_increment_answer(const char *id)
Definition: dns.c:1897
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
Definition: or.h:494
#define TO_CONN(c)
Definition: or.h:612
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:801
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:1697
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2572
int router_my_exit_policy_is_reject_star(void)
Definition: router.c:1732
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