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