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