tor  0.4.0.1-alpha
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-2019, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 
50 #define DNS_PRIVATE
51 
52 #include "core/or/or.h"
53 #include "app/config/config.h"
55 #include "core/mainloop/mainloop.h"
56 #include "core/mainloop/netstatus.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 
70 #include "core/or/edge_connection_st.h"
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 
84 #define RESOLVE_MAX_TIMEOUT 300
85 
87 static struct evdns_base *the_evdns_base = NULL;
88 
90 static int nameservers_configured = 0;
92 static int nameserver_config_failed = 0;
95 static char *resolv_conf_fname = NULL;
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 
122 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
123 
125 static uint64_t n_ipv6_requests_made = 0;
127 static uint64_t n_ipv6_timeouts = 0;
129 static int dns_is_broken_for_ipv6 = 0;
130 
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 
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 
154 static void
155 init_cache_map(void)
156 {
157  HT_INIT(cache_map, &cache_root);
158 }
159 
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 
216 static void
217 dns_randfn_(char *b, size_t n)
218 {
219  crypto_rand(b,n);
220 }
221 
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 
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 
265 int
267 {
269 }
270 
274 uint32_t
275 dns_clip_ttl(uint32_t ttl)
276 {
277  /* This logic is a defense against "DefectTor" DNS-based traffic
278  * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
279  * We only give two values: a "low" value and a "high" value.
280  */
281  if (ttl < MIN_DNS_TTL_AT_EXIT)
282  return MIN_DNS_TTL_AT_EXIT;
283  else
284  return MAX_DNS_TTL_AT_EXIT;
285 }
286 
288 static void
290 {
291  if (!r)
292  return;
293  while (r->pending_connections) {
295  r->pending_connections = victim->next;
296  tor_free(victim);
297  }
298  if (r->res_status_hostname == RES_STATUS_DONE_OK)
299  tor_free(r->result_ptr.hostname);
300  r->magic = 0xFF00FF00;
301  tor_free(r);
302 }
303 
307 static int
308 compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
309 {
310  const cached_resolve_t *a = _a, *b = _b;
311  if (a->expire < b->expire)
312  return -1;
313  else if (a->expire == b->expire)
314  return 0;
315  else
316  return 1;
317 }
318 
322 
323 static void
324 cached_resolve_add_answer(cached_resolve_t *resolve,
325  int query_type,
326  int dns_result,
327  const tor_addr_t *answer_addr,
328  const char *answer_hostname,
329  uint32_t ttl)
330 {
331  if (query_type == DNS_PTR) {
332  if (resolve->res_status_hostname != RES_STATUS_INFLIGHT)
333  return;
334 
335  if (dns_result == DNS_ERR_NONE && answer_hostname) {
336  resolve->result_ptr.hostname = tor_strdup(answer_hostname);
337  resolve->res_status_hostname = RES_STATUS_DONE_OK;
338  } else {
339  resolve->result_ptr.err_hostname = dns_result;
340  resolve->res_status_hostname = RES_STATUS_DONE_ERR;
341  }
342  resolve->ttl_hostname = ttl;
343  } else if (query_type == DNS_IPv4_A) {
344  if (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT)
345  return;
346 
347  if (dns_result == DNS_ERR_NONE && answer_addr &&
348  tor_addr_family(answer_addr) == AF_INET) {
349  resolve->result_ipv4.addr_ipv4 = tor_addr_to_ipv4h(answer_addr);
350  resolve->res_status_ipv4 = RES_STATUS_DONE_OK;
351  } else {
352  resolve->result_ipv4.err_ipv4 = dns_result;
353  resolve->res_status_ipv4 = RES_STATUS_DONE_ERR;
354  }
355  resolve->ttl_ipv4 = ttl;
356  } else if (query_type == DNS_IPv6_AAAA) {
357  if (resolve->res_status_ipv6 != RES_STATUS_INFLIGHT)
358  return;
359 
360  if (dns_result == DNS_ERR_NONE && answer_addr &&
361  tor_addr_family(answer_addr) == AF_INET6) {
362  memcpy(&resolve->result_ipv6.addr_ipv6,
363  tor_addr_to_in6(answer_addr),
364  sizeof(struct in6_addr));
365  resolve->res_status_ipv6 = RES_STATUS_DONE_OK;
366  } else {
367  resolve->result_ipv6.err_ipv6 = dns_result;
368  resolve->res_status_ipv6 = RES_STATUS_DONE_ERR;
369  }
370  resolve->ttl_ipv6 = ttl;
371  }
372 }
373 
375 static int
377 {
378  return (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT &&
379  resolve->res_status_ipv6 != RES_STATUS_INFLIGHT &&
380  resolve->res_status_hostname != RES_STATUS_INFLIGHT);
381 }
382 
385 static void
386 set_expiry(cached_resolve_t *resolve, time_t expires)
387 {
388  tor_assert(resolve && resolve->expire == 0);
390  cached_resolve_pqueue = smartlist_new();
391  resolve->expire = expires;
394  offsetof(cached_resolve_t, minheap_idx),
395  resolve);
396 }
397 
399 void
401 {
402  cached_resolve_t **ptr, **next, *item;
403  assert_cache_ok();
404  if (cached_resolve_pqueue) {
406  {
407  if (res->state == CACHE_STATE_DONE)
409  });
410  }
411  for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
412  item = *ptr;
413  next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
414  free_cached_resolve_(item);
415  }
416  HT_CLEAR(cache_map, &cache_root);
417  smartlist_free(cached_resolve_pqueue);
418  cached_resolve_pqueue = NULL;
420 }
421 
424 static void
426 {
427  cached_resolve_t *resolve, *removed;
428  pending_connection_t *pend;
429  edge_connection_t *pendconn;
430 
431  assert_cache_ok();
433  return;
434 
435  while (smartlist_len(cached_resolve_pqueue)) {
436  resolve = smartlist_get(cached_resolve_pqueue, 0);
437  if (resolve->expire > now)
438  break;
441  offsetof(cached_resolve_t, minheap_idx));
442 
443  if (resolve->state == CACHE_STATE_PENDING) {
444  log_debug(LD_EXIT,
445  "Expiring a dns resolve %s that's still pending. Forgot to "
446  "cull it? DNS resolve didn't tell us about the timeout?",
447  escaped_safe_str(resolve->address));
448  } else if (resolve->state == CACHE_STATE_CACHED) {
449  log_debug(LD_EXIT,
450  "Forgetting old cached resolve (address %s, expires %lu)",
451  escaped_safe_str(resolve->address),
452  (unsigned long)resolve->expire);
453  tor_assert(!resolve->pending_connections);
454  } else {
455  tor_assert(resolve->state == CACHE_STATE_DONE);
456  tor_assert(!resolve->pending_connections);
457  }
458 
459  if (resolve->pending_connections) {
460  log_debug(LD_EXIT,
461  "Closing pending connections on timed-out DNS resolve!");
462  while (resolve->pending_connections) {
463  pend = resolve->pending_connections;
464  resolve->pending_connections = pend->next;
465  /* Connections should only be pending if they have no socket. */
466  tor_assert(!SOCKET_OK(pend->conn->base_.s));
467  pendconn = pend->conn;
468  /* Prevent double-remove */
469  pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
470  if (!pendconn->base_.marked_for_close) {
471  connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
472  circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
473  connection_free_(TO_CONN(pendconn));
474  }
475  tor_free(pend);
476  }
477  }
478 
479  if (resolve->state == CACHE_STATE_CACHED ||
480  resolve->state == CACHE_STATE_PENDING) {
481  removed = HT_REMOVE(cache_map, &cache_root, resolve);
482  if (removed != resolve) {
483  log_err(LD_BUG, "The expired resolve we purged didn't match any in"
484  " the cache. Tried to purge %s (%p); instead got %s (%p).",
485  resolve->address, (void*)resolve,
486  removed ? removed->address : "NULL", (void*)removed);
487  }
488  tor_assert(removed == resolve);
489  } else {
490  /* This should be in state DONE. Make sure it's not in the cache. */
491  cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
492  tor_assert(tmp != resolve);
493  }
494  if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
495  tor_free(resolve->result_ptr.hostname);
496  resolve->magic = 0xF0BBF0BB;
497  tor_free(resolve);
498  }
499 
500  assert_cache_ok();
501 }
502 
503 /* argument for send_resolved_cell only, meaning "let the answer type be ipv4
504  * or ipv6 depending on the connection's address". */
505 #define RESOLVED_TYPE_AUTO 0xff
506 
515 MOCK_IMPL(STATIC void,
516 send_resolved_cell,(edge_connection_t *conn, uint8_t answer_type,
517  const cached_resolve_t *resolved))
518 {
519  char buf[RELAY_PAYLOAD_SIZE], *cp = buf;
520  size_t buflen = 0;
521  uint32_t ttl;
522 
523  buf[0] = answer_type;
524  ttl = dns_clip_ttl(conn->address_ttl);
525 
526  switch (answer_type)
527  {
528  case RESOLVED_TYPE_AUTO:
529  if (resolved && resolved->res_status_ipv4 == RES_STATUS_DONE_OK) {
530  cp[0] = RESOLVED_TYPE_IPV4;
531  cp[1] = 4;
532  set_uint32(cp+2, htonl(resolved->result_ipv4.addr_ipv4));
533  set_uint32(cp+6, htonl(ttl));
534  cp += 10;
535  }
536  if (resolved && resolved->res_status_ipv6 == RES_STATUS_DONE_OK) {
537  const uint8_t *bytes = resolved->result_ipv6.addr_ipv6.s6_addr;
538  cp[0] = RESOLVED_TYPE_IPV6;
539  cp[1] = 16;
540  memcpy(cp+2, bytes, 16);
541  set_uint32(cp+18, htonl(ttl));
542  cp += 22;
543  }
544  if (cp != buf) {
545  buflen = cp - buf;
546  break;
547  } else {
548  answer_type = RESOLVED_TYPE_ERROR;
549  /* fall through. */
550  }
551  /* Falls through. */
552  case RESOLVED_TYPE_ERROR_TRANSIENT:
553  case RESOLVED_TYPE_ERROR:
554  {
555  const char *errmsg = "Error resolving hostname";
556  size_t msglen = strlen(errmsg);
557 
558  buf[0] = answer_type;
559  buf[1] = msglen;
560  strlcpy(buf+2, errmsg, sizeof(buf)-2);
561  set_uint32(buf+2+msglen, htonl(ttl));
562  buflen = 6+msglen;
563  break;
564  }
565  default:
566  tor_assert(0);
567  return;
568  }
569  // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
570 
571  connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
572 }
573 
582 MOCK_IMPL(STATIC void,
583 send_resolved_hostname_cell,(edge_connection_t *conn,
584  const char *hostname))
585 {
586  char buf[RELAY_PAYLOAD_SIZE];
587  size_t buflen;
588  uint32_t ttl;
589 
590  if (BUG(!hostname))
591  return;
592 
593  size_t namelen = strlen(hostname);
594 
595  tor_assert(namelen < 256);
596  ttl = dns_clip_ttl(conn->address_ttl);
597 
598  buf[0] = RESOLVED_TYPE_HOSTNAME;
599  buf[1] = (uint8_t)namelen;
600  memcpy(buf+2, hostname, namelen);
601  set_uint32(buf+2+namelen, htonl(ttl));
602  buflen = 2+namelen+4;
603 
604  // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
605  connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
606  // log_notice(LD_EXIT, "Sent");
607 }
608 
633 int
635 {
636  or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
637  int is_resolve, r;
638  int made_connection_pending = 0;
639  char *hostname = NULL;
640  cached_resolve_t *resolve = NULL;
641  is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
642 
643  r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
644  &made_connection_pending, &resolve);
645 
646  switch (r) {
647  case 1:
648  /* We got an answer without a lookup -- either the answer was
649  * cached, or it was obvious (like an IP address). */
650  if (is_resolve) {
651  /* Send the answer back right now, and detach. */
652  if (hostname)
653  send_resolved_hostname_cell(exitconn, hostname);
654  else
655  send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO, resolve);
656  exitconn->on_circuit = NULL;
657  } else {
658  /* Add to the n_streams list; the calling function will send back a
659  * connected cell. */
660  exitconn->next_stream = oncirc->n_streams;
661  oncirc->n_streams = exitconn;
662  }
663  break;
664  case 0:
665  /* The request is pending: add the connection into the linked list of
666  * resolving_streams on this circuit. */
667  exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
668  exitconn->next_stream = oncirc->resolving_streams;
669  oncirc->resolving_streams = exitconn;
670  break;
671  case -2:
672  case -1:
673  /* The request failed before it could start: cancel this connection,
674  * and stop everybody waiting for the same connection. */
675  if (is_resolve) {
676  send_resolved_cell(exitconn,
677  (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
678  NULL);
679  }
680 
681  exitconn->on_circuit = NULL;
682 
683  dns_cancel_pending_resolve(exitconn->base_.address);
684 
685  if (!made_connection_pending && !exitconn->base_.marked_for_close) {
686  /* If we made the connection pending, then we freed it already in
687  * dns_cancel_pending_resolve(). If we marked it for close, it'll
688  * get freed from the main loop. Otherwise, can free it now. */
689  connection_free_(TO_CONN(exitconn));
690  }
691  break;
692  default:
693  tor_assert(0);
694  }
695 
696  tor_free(hostname);
697  return r;
698 }
699 
715 MOCK_IMPL(STATIC int,
716 dns_resolve_impl,(edge_connection_t *exitconn, int is_resolve,
717  or_circuit_t *oncirc, char **hostname_out,
718  int *made_connection_pending_out,
719  cached_resolve_t **resolve_out))
720 {
721  cached_resolve_t *resolve;
722  cached_resolve_t search;
723  pending_connection_t *pending_connection;
724  int is_reverse = 0;
725  tor_addr_t addr;
726  time_t now = time(NULL);
727  int r;
728  assert_connection_ok(TO_CONN(exitconn), 0);
729  tor_assert(!SOCKET_OK(exitconn->base_.s));
730  assert_cache_ok();
731  tor_assert(oncirc);
732  *made_connection_pending_out = 0;
733 
734  /* first check if exitconn->base_.address is an IP. If so, we already
735  * know the answer. */
736  if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
737  if (tor_addr_family(&addr) == AF_INET ||
738  tor_addr_family(&addr) == AF_INET6) {
739  tor_addr_copy(&exitconn->base_.addr, &addr);
740  exitconn->address_ttl = DEFAULT_DNS_TTL;
741  return 1;
742  } else {
743  /* XXXX unspec? Bogus? */
744  return -1;
745  }
746  }
747 
748  /* If we're a non-exit, don't even do DNS lookups. */
749  if (router_my_exit_policy_is_reject_star())
750  return -1;
751 
752  if (address_is_invalid_destination(exitconn->base_.address, 0)) {
753  tor_log(LOG_PROTOCOL_WARN, LD_EXIT,
754  "Rejecting invalid destination address %s",
755  escaped_safe_str(exitconn->base_.address));
756  return -1;
757  }
758 
759  /* then take this opportunity to see if there are any expired
760  * resolves in the hash table. */
762 
763  /* lower-case exitconn->base_.address, so it's in canonical form */
764  tor_strlower(exitconn->base_.address);
765 
766  /* Check whether this is a reverse lookup. If it's malformed, or it's a
767  * .in-addr.arpa address but this isn't a resolve request, kill the
768  * connection.
769  */
770  if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
771  AF_UNSPEC, 0)) != 0) {
772  if (r == 1) {
773  is_reverse = 1;
774  if (tor_addr_is_internal(&addr, 0)) /* internal address? */
775  return -1;
776  }
777 
778  if (!is_reverse || !is_resolve) {
779  if (!is_reverse)
780  log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
781  escaped_safe_str(exitconn->base_.address));
782  else if (!is_resolve)
783  log_info(LD_EXIT,
784  "Attempt to connect to a .in-addr.arpa address \"%s\"; "
785  "sending error.",
786  escaped_safe_str(exitconn->base_.address));
787 
788  return -1;
789  }
790  //log_notice(LD_EXIT, "Looks like an address %s",
791  //exitconn->base_.address);
792  }
793  exitconn->is_reverse_dns_lookup = is_reverse;
794 
795  /* now check the hash table to see if 'address' is already there. */
796  strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
797  resolve = HT_FIND(cache_map, &cache_root, &search);
798  if (resolve && resolve->expire > now) { /* already there */
799  switch (resolve->state) {
800  case CACHE_STATE_PENDING:
801  /* add us to the pending list */
802  pending_connection = tor_malloc_zero(
803  sizeof(pending_connection_t));
804  pending_connection->conn = exitconn;
805  pending_connection->next = resolve->pending_connections;
806  resolve->pending_connections = pending_connection;
807  *made_connection_pending_out = 1;
808  log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") waiting "
809  "for pending DNS resolve of %s", exitconn->base_.s,
810  escaped_safe_str(exitconn->base_.address));
811  return 0;
812  case CACHE_STATE_CACHED:
813  log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") found "
814  "cached answer for %s",
815  exitconn->base_.s,
816  escaped_safe_str(resolve->address));
817 
818  *resolve_out = resolve;
819 
820  return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
821  case CACHE_STATE_DONE:
822  log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
824  }
825  tor_assert(0);
826  }
827  tor_assert(!resolve);
828  /* not there, need to add it */
829  resolve = tor_malloc_zero(sizeof(cached_resolve_t));
830  resolve->magic = CACHED_RESOLVE_MAGIC;
831  resolve->state = CACHE_STATE_PENDING;
832  resolve->minheap_idx = -1;
833  strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
834 
835  /* add this connection to the pending list */
836  pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
837  pending_connection->conn = exitconn;
838  resolve->pending_connections = pending_connection;
839  *made_connection_pending_out = 1;
840 
841  /* Add this resolve to the cache and priority queue. */
842  HT_INSERT(cache_map, &cache_root, resolve);
843  set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
844 
845  log_debug(LD_EXIT,"Launching %s.",
846  escaped_safe_str(exitconn->base_.address));
847  assert_cache_ok();
848 
849  return launch_resolve(resolve);
850 }
851 
868 MOCK_IMPL(STATIC int,
869 set_exitconn_info_from_resolve,(edge_connection_t *exitconn,
870  const cached_resolve_t *resolve,
871  char **hostname_out))
872 {
873  int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
874  uint32_t begincell_flags;
875  const int is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
876  tor_assert(exitconn);
877  tor_assert(resolve);
878 
879  if (exitconn->is_reverse_dns_lookup) {
880  exitconn->address_ttl = resolve->ttl_hostname;
881  if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
882  *hostname_out = tor_strdup(resolve->result_ptr.hostname);
883  return 1;
884  } else {
885  return -1;
886  }
887  }
888 
889  /* If we're here then the connection wants one or either of ipv4, ipv6, and
890  * we can give it one or both. */
891  if (is_resolve) {
892  begincell_flags = BEGIN_FLAG_IPV6_OK;
893  } else {
894  begincell_flags = exitconn->begincell_flags;
895  }
896 
897  ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
898  ! (begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
899  ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
900  (begincell_flags & BEGIN_FLAG_IPV6_OK) &&
901  get_options()->IPv6Exit;
902 
903  /* Now decide which one to actually give. */
904  if (ipv4_ok && ipv6_ok && is_resolve) {
905  answer_with_ipv4 = 1;
906  } else if (ipv4_ok && ipv6_ok) {
907  /* If we have both, see if our exit policy has an opinion. */
908  const uint16_t port = exitconn->base_.port;
909  int ipv4_allowed, ipv6_allowed;
910  tor_addr_t a4, a6;
912  tor_addr_from_in6(&a6, &resolve->result_ipv6.addr_ipv6);
913  ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
914  ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
915  if (ipv4_allowed && !ipv6_allowed) {
916  answer_with_ipv4 = 1;
917  } else if (ipv6_allowed && !ipv4_allowed) {
918  answer_with_ipv4 = 0;
919  } else {
920  /* Our exit policy would permit both. Answer with whichever the user
921  * prefers */
922  answer_with_ipv4 = !(begincell_flags &
924  }
925  } else {
926  /* Otherwise if one is okay, send it back. */
927  if (ipv4_ok) {
928  answer_with_ipv4 = 1;
929  } else if (ipv6_ok) {
930  answer_with_ipv4 = 0;
931  } else {
932  /* Neither one was okay. Choose based on user preference. */
933  answer_with_ipv4 = !(begincell_flags &
935  }
936  }
937 
938  /* Finally, we write the answer back. */
939  r = 1;
940  if (answer_with_ipv4) {
941  if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
942  tor_addr_from_ipv4h(&exitconn->base_.addr,
943  resolve->result_ipv4.addr_ipv4);
944  } else {
945  r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
946  }
947 
948  exitconn->address_ttl = resolve->ttl_ipv4;
949  } else {
950  if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
951  tor_addr_from_in6(&exitconn->base_.addr,
952  &resolve->result_ipv6.addr_ipv6);
953  } else {
954  r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
955  }
956 
957  exitconn->address_ttl = resolve->ttl_ipv6;
958  }
959 
960  return r;
961 }
962 
965 void
967 {
968  pending_connection_t *pend;
969  cached_resolve_t search;
970 
971 #if 1
972  cached_resolve_t *resolve;
973  strlcpy(search.address, conn->base_.address, sizeof(search.address));
974  resolve = HT_FIND(cache_map, &cache_root, &search);
975  if (!resolve)
976  return;
977  for (pend = resolve->pending_connections; pend; pend = pend->next) {
978  tor_assert(pend->conn != conn);
979  }
980 #else /* !(1) */
981  cached_resolve_t **resolve;
982  HT_FOREACH(resolve, cache_map, &cache_root) {
983  for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
984  tor_assert(pend->conn != conn);
985  }
986  }
987 #endif /* 1 */
988 }
989 
992 void
994 {
995  pending_connection_t *pend;
996  cached_resolve_t **resolve;
997 
998  HT_FOREACH(resolve, cache_map, &cache_root) {
999  for (pend = (*resolve)->pending_connections;
1000  pend;
1001  pend = pend->next) {
1002  assert_connection_ok(TO_CONN(pend->conn), 0);
1003  tor_assert(!SOCKET_OK(pend->conn->base_.s));
1004  tor_assert(!connection_in_array(TO_CONN(pend->conn)));
1005  }
1006  }
1007 }
1008 
1011 void
1013 {
1014  pending_connection_t *pend, *victim;
1015  cached_resolve_t search;
1016  cached_resolve_t *resolve;
1017 
1018  tor_assert(conn->base_.type == CONN_TYPE_EXIT);
1019  tor_assert(conn->base_.state == EXIT_CONN_STATE_RESOLVING);
1020 
1021  strlcpy(search.address, conn->base_.address, sizeof(search.address));
1022 
1023  resolve = HT_FIND(cache_map, &cache_root, &search);
1024  if (!resolve) {
1025  log_notice(LD_BUG, "Address %s is not pending. Dropping.",
1026  escaped_safe_str(conn->base_.address));
1027  return;
1028  }
1029 
1030  tor_assert(resolve->pending_connections);
1031  assert_connection_ok(TO_CONN(conn),0);
1032 
1033  pend = resolve->pending_connections;
1034 
1035  if (pend->conn == conn) {
1036  resolve->pending_connections = pend->next;
1037  tor_free(pend);
1038  log_debug(LD_EXIT, "First connection (fd "TOR_SOCKET_T_FORMAT") no "
1039  "longer waiting for resolve of %s",
1040  conn->base_.s,
1041  escaped_safe_str(conn->base_.address));
1042  return;
1043  } else {
1044  for ( ; pend->next; pend = pend->next) {
1045  if (pend->next->conn == conn) {
1046  victim = pend->next;
1047  pend->next = victim->next;
1048  tor_free(victim);
1049  log_debug(LD_EXIT,
1050  "Connection (fd "TOR_SOCKET_T_FORMAT") no longer waiting "
1051  "for resolve of %s",
1052  conn->base_.s, escaped_safe_str(conn->base_.address));
1053  return; /* more are pending */
1054  }
1055  }
1056  log_warn(LD_BUG, "Connection (fd "TOR_SOCKET_T_FORMAT") was not waiting "
1057  "for a resolve of %s, but we tried to remove it.",
1058  conn->base_.s, escaped_safe_str(conn->base_.address));
1059  }
1060 }
1061 
1067 dns_cancel_pending_resolve,(const char *address))
1068 {
1069  pending_connection_t *pend;
1070  cached_resolve_t search;
1071  cached_resolve_t *resolve, *tmp;
1072  edge_connection_t *pendconn;
1073  circuit_t *circ;
1074 
1075  strlcpy(search.address, address, sizeof(search.address));
1076 
1077  resolve = HT_FIND(cache_map, &cache_root, &search);
1078  if (!resolve)
1079  return;
1080 
1081  if (resolve->state != CACHE_STATE_PENDING) {
1082  /* We can get into this state if we never actually created the pending
1083  * resolve, due to finding an earlier cached error or something. Just
1084  * ignore it. */
1085  if (resolve->pending_connections) {
1086  log_warn(LD_BUG,
1087  "Address %s is not pending but has pending connections!",
1088  escaped_safe_str(address));
1090  }
1091  return;
1092  }
1093 
1094  if (!resolve->pending_connections) {
1095  log_warn(LD_BUG,
1096  "Address %s is pending but has no pending connections!",
1097  escaped_safe_str(address));
1099  return;
1100  }
1101  tor_assert(resolve->pending_connections);
1102 
1103  /* mark all pending connections to fail */
1104  log_debug(LD_EXIT,
1105  "Failing all connections waiting on DNS resolve of %s",
1106  escaped_safe_str(address));
1107  while (resolve->pending_connections) {
1108  pend = resolve->pending_connections;
1109  pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1110  pendconn = pend->conn;
1111  assert_connection_ok(TO_CONN(pendconn), 0);
1112  tor_assert(!SOCKET_OK(pendconn->base_.s));
1113  if (!pendconn->base_.marked_for_close) {
1114  connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1115  }
1116  circ = circuit_get_by_edge_conn(pendconn);
1117  if (circ)
1118  circuit_detach_stream(circ, pendconn);
1119  if (!pendconn->base_.marked_for_close)
1120  connection_free_(TO_CONN(pendconn));
1121  resolve->pending_connections = pend->next;
1122  tor_free(pend);
1123  }
1124 
1125  tmp = HT_REMOVE(cache_map, &cache_root, resolve);
1126  if (tmp != resolve) {
1127  log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
1128  " the cache. Tried to purge %s (%p); instead got %s (%p).",
1129  resolve->address, (void*)resolve,
1130  tmp ? tmp->address : "NULL", (void*)tmp);
1131  }
1132  tor_assert(tmp == resolve);
1133 
1134  resolve->state = CACHE_STATE_DONE;
1135 }
1136 
1139 static inline int
1140 is_test_address(const char *address)
1141 {
1142  const or_options_t *options = get_options();
1143  return options->ServerDNSTestAddresses &&
1145 }
1146 
1156 static void
1157 dns_found_answer(const char *address, uint8_t query_type,
1158  int dns_answer,
1159  const tor_addr_t *addr,
1160  const char *hostname, uint32_t ttl)
1161 {
1162  cached_resolve_t search;
1163  cached_resolve_t *resolve;
1164 
1165  assert_cache_ok();
1166 
1167  strlcpy(search.address, address, sizeof(search.address));
1168 
1169  resolve = HT_FIND(cache_map, &cache_root, &search);
1170  if (!resolve) {
1171  int is_test_addr = is_test_address(address);
1172  if (!is_test_addr)
1173  log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
1174  escaped_safe_str(address));
1175  return;
1176  }
1177  assert_resolve_ok(resolve);
1178 
1179  if (resolve->state != CACHE_STATE_PENDING) {
1180  /* XXXX Maybe update addr? or check addr for consistency? Or let
1181  * VALID replace FAILED? */
1182  int is_test_addr = is_test_address(address);
1183  if (!is_test_addr)
1184  log_notice(LD_EXIT,
1185  "Resolved %s which was already resolved; ignoring",
1186  escaped_safe_str(address));
1187  tor_assert(resolve->pending_connections == NULL);
1188  return;
1189  }
1190 
1191  cached_resolve_add_answer(resolve, query_type, dns_answer,
1192  addr, hostname, ttl);
1193 
1194  if (cached_resolve_have_all_answers(resolve)) {
1195  inform_pending_connections(resolve);
1196 
1197  make_pending_resolve_cached(resolve);
1198  }
1199 }
1200 
1209 static void
1211 {
1212  pending_connection_t *pend;
1213  edge_connection_t *pendconn;
1214  int r;
1215 
1216  while (resolve->pending_connections) {
1217  char *hostname = NULL;
1218  pend = resolve->pending_connections;
1219  pendconn = pend->conn; /* don't pass complex things to the
1220  connection_mark_for_close macro */
1221  assert_connection_ok(TO_CONN(pendconn),time(NULL));
1222 
1223  if (pendconn->base_.marked_for_close) {
1224  /* prevent double-remove. */
1225  pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1226  resolve->pending_connections = pend->next;
1227  tor_free(pend);
1228  continue;
1229  }
1230 
1231  r = set_exitconn_info_from_resolve(pendconn,
1232  resolve,
1233  &hostname);
1234 
1235  if (r < 0) {
1236  /* prevent double-remove. */
1237  pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1238  if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1239  connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
1240  /* This detach must happen after we send the end cell. */
1241  circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1242  } else {
1243  send_resolved_cell(pendconn, r == -1 ?
1244  RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
1245  NULL);
1246  /* This detach must happen after we send the resolved cell. */
1247  circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
1248  }
1249  connection_free_(TO_CONN(pendconn));
1250  } else {
1251  circuit_t *circ;
1252  if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
1253  /* prevent double-remove. */
1254  pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
1255 
1256  circ = circuit_get_by_edge_conn(pend->conn);
1257  tor_assert(circ);
1258  tor_assert(!CIRCUIT_IS_ORIGIN(circ));
1259  /* unlink pend->conn from resolving_streams, */
1260  circuit_detach_stream(circ, pend->conn);
1261  /* and link it to n_streams */
1262  pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
1263  pend->conn->on_circuit = circ;
1264  TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
1265 
1266  connection_exit_connect(pend->conn);
1267  } else {
1268  /* prevent double-remove. This isn't really an accurate state,
1269  * but it does the right thing. */
1270  pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
1271  if (pendconn->is_reverse_dns_lookup)
1272  send_resolved_hostname_cell(pendconn, hostname);
1273  else
1274  send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO, resolve);
1275  circ = circuit_get_by_edge_conn(pendconn);
1276  tor_assert(circ);
1277  circuit_detach_stream(circ, pendconn);
1278  connection_free_(TO_CONN(pendconn));
1279  }
1280  }
1281  resolve->pending_connections = pend->next;
1282  tor_free(pend);
1283  tor_free(hostname);
1284  }
1285 }
1286 
1293 static void
1295 {
1296  cached_resolve_t *removed;
1297 
1298  resolve->state = CACHE_STATE_DONE;
1299  removed = HT_REMOVE(cache_map, &cache_root, resolve);
1300  if (removed != resolve) {
1301  log_err(LD_BUG, "The pending resolve we found wasn't removable from"
1302  " the cache. Tried to purge %s (%p); instead got %s (%p).",
1303  resolve->address, (void*)resolve,
1304  removed ? removed->address : "NULL", (void*)removed);
1305  }
1306  assert_resolve_ok(resolve);
1307  assert_cache_ok();
1308  /* The resolve will eventually just hit the time-out in the expiry queue and
1309  * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
1310  * way. XXXXX we could do better!*/
1311 
1312  {
1313  cached_resolve_t *new_resolve = tor_memdup(resolve,
1314  sizeof(cached_resolve_t));
1315  uint32_t ttl = UINT32_MAX;
1316  new_resolve->expire = 0; /* So that set_expiry won't croak. */
1317  if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
1318  new_resolve->result_ptr.hostname =
1319  tor_strdup(resolve->result_ptr.hostname);
1320 
1321  new_resolve->state = CACHE_STATE_CACHED;
1322 
1323  assert_resolve_ok(new_resolve);
1324  HT_INSERT(cache_map, &cache_root, new_resolve);
1325 
1326  if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
1327  resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
1328  resolve->ttl_ipv4 < ttl)
1329  ttl = resolve->ttl_ipv4;
1330 
1331  if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
1332  resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
1333  resolve->ttl_ipv6 < ttl)
1334  ttl = resolve->ttl_ipv6;
1335 
1336  if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
1337  resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
1338  resolve->ttl_hostname < ttl)
1339  ttl = resolve->ttl_hostname;
1340 
1341  set_expiry(new_resolve, time(NULL) + dns_clip_ttl(ttl));
1342  }
1343 
1344  assert_cache_ok();
1345 }
1346 
1349 static int
1351 {
1352  switch (err)
1353  {
1354  case DNS_ERR_SERVERFAILED:
1355  case DNS_ERR_TRUNCATED:
1356  case DNS_ERR_TIMEOUT:
1357  return 1;
1358  default:
1359  return 0;
1360  }
1361 }
1362 
1366 size_t
1368 {
1369  return evdns_base_count_nameservers(the_evdns_base);
1370 }
1371 
1372 #ifdef HAVE_EVDNS_BASE_GET_NAMESERVER_ADDR
1373 
1377 tor_addr_t *
1378 configured_nameserver_address(const size_t idx)
1379 {
1380  struct sockaddr_storage sa;
1381  ev_socklen_t sa_len = sizeof(sa);
1382 
1383  if (evdns_base_get_nameserver_addr(the_evdns_base, (int)idx,
1384  (struct sockaddr *)&sa,
1385  sa_len) > 0) {
1386  tor_addr_t *tor_addr = tor_malloc(sizeof(tor_addr_t));
1387  if (tor_addr_from_sockaddr(tor_addr,
1388  (const struct sockaddr *)&sa,
1389  NULL) == 0) {
1390  return tor_addr;
1391  }
1392  tor_free(tor_addr);
1393  }
1394 
1395  return NULL;
1396 }
1397 #endif
1398 
1405 static int
1407 {
1408  const or_options_t *options;
1409  const char *conf_fname;
1410  struct stat st;
1411  int r, flags;
1412  options = get_options();
1413  conf_fname = options->ServerDNSResolvConfFile;
1414 #ifndef _WIN32
1415  if (!conf_fname)
1416  conf_fname = "/etc/resolv.conf";
1417 #endif
1418  flags = DNS_OPTIONS_ALL;
1419 
1420  if (!the_evdns_base) {
1421  if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
1422  log_err(LD_BUG, "Couldn't create an evdns_base");
1423  return -1;
1424  }
1425  }
1426 
1427  evdns_set_log_fn(evdns_log_cb);
1428  if (conf_fname) {
1429  log_debug(LD_FS, "stat()ing %s", conf_fname);
1430  int missing_resolv_conf = 0;
1431  int stat_res = stat(sandbox_intern_string(conf_fname), &st);
1432 
1433  if (stat_res) {
1434  log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
1435  conf_fname, strerror(errno));
1436  missing_resolv_conf = 1;
1437  } else if (!force && resolv_conf_fname &&
1438  !strcmp(conf_fname,resolv_conf_fname)
1439  && st.st_mtime == resolv_conf_mtime) {
1440  log_info(LD_EXIT, "No change to '%s'", conf_fname);
1441  return 0;
1442  }
1443 
1444  if (stat_res == 0 && st.st_size == 0)
1445  missing_resolv_conf = 1;
1446 
1447  if (nameservers_configured) {
1448  evdns_base_search_clear(the_evdns_base);
1449  evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1450  }
1451 #if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
1452  if (flags & DNS_OPTION_HOSTSFILE) {
1453  flags ^= DNS_OPTION_HOSTSFILE;
1454  log_debug(LD_FS, "Loading /etc/hosts");
1455  evdns_base_load_hosts(the_evdns_base,
1456  sandbox_intern_string("/etc/hosts"));
1457  }
1458 #endif /* defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP) */
1459 
1460  if (!missing_resolv_conf) {
1461  log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
1462  if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
1463  sandbox_intern_string(conf_fname)))) {
1464  log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers "
1465  "in '%s' (%d)", conf_fname, conf_fname, r);
1466 
1467  if (r != 6) // "r = 6" means "no DNS servers were in resolv.conf" -
1468  goto err; // in which case we expect libevent to add 127.0.0.1 as
1469  // fallback.
1470  }
1471  if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1472  log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.",
1473  conf_fname);
1474  }
1475 
1477  resolv_conf_fname = tor_strdup(conf_fname);
1478  resolv_conf_mtime = st.st_mtime;
1479  } else {
1480  log_warn(LD_EXIT, "Could not read your DNS config from '%s' - "
1481  "please investigate your DNS configuration. "
1482  "This is possibly a problem. Meanwhile, falling"
1483  " back to local DNS at 127.0.0.1.", conf_fname);
1484  evdns_base_nameserver_ip_add(the_evdns_base, "127.0.0.1");
1485  }
1486 
1488  evdns_base_resume(the_evdns_base);
1489  }
1490 #ifdef _WIN32
1491  else {
1492  if (nameservers_configured) {
1493  evdns_base_search_clear(the_evdns_base);
1494  evdns_base_clear_nameservers_and_suspend(the_evdns_base);
1495  }
1496  if (evdns_base_config_windows_nameservers(the_evdns_base)) {
1497  log_warn(LD_EXIT,"Could not config nameservers.");
1498  goto err;
1499  }
1500  if (evdns_base_count_nameservers(the_evdns_base) == 0) {
1501  log_warn(LD_EXIT, "Unable to find any platform nameservers in "
1502  "your Windows configuration.");
1503  goto err;
1504  }
1506  evdns_base_resume(the_evdns_base);
1508  resolv_conf_mtime = 0;
1509  }
1510 #endif /* defined(_WIN32) */
1511 
1512 #define SET(k,v) evdns_base_set_option(the_evdns_base, (k), (v))
1513 
1514  // If we only have one nameserver, it does not make sense to back off
1515  // from it for a timeout. Unfortunately, the value for max-timeouts is
1516  // currently clamped by libevent to 255, but it does not hurt to set
1517  // it higher in case libevent gets a patch for this. Higher-than-
1518  // default maximum of 3 with multiple nameservers to avoid spuriously
1519  // marking one down on bursts of timeouts resulting from scans/attacks
1520  // against non-responding authoritative DNS servers.
1521  if (evdns_base_count_nameservers(the_evdns_base) == 1) {
1522  SET("max-timeouts:", "1000000");
1523  } else {
1524  SET("max-timeouts:", "10");
1525  }
1526 
1527  // Elongate the queue of maximum inflight dns requests, so if a bunch
1528  // remain pending at the resolver (happens commonly with Unbound) we won't
1529  // stall every other DNS request. This potentially means some wasted
1530  // CPU as there's a walk over a linear queue involved, but this is a
1531  // much better tradeoff compared to just failing DNS requests because
1532  // of a full queue.
1533  SET("max-inflight:", "8192");
1534 
1535  // Two retries at 5 and 10 seconds for bind9/named which relies on
1536  // clients to handle retries. Second retry for retried circuits with
1537  // extended 15 second timeout. Superfluous with local-system Unbound
1538  // instance--has its own elaborate retry scheme.
1539  SET("timeout:", "5");
1540  SET("attempts:","3");
1541 
1542  if (options->ServerDNSRandomizeCase)
1543  SET("randomize-case:", "1");
1544  else
1545  SET("randomize-case:", "0");
1546 
1547 #undef SET
1548 
1550 
1554  /* XXX the three calls to republish the descriptor might be producing
1555  * descriptors that are only cosmetically different, especially on
1556  * non-exit relays! -RD */
1557  mark_my_descriptor_dirty("dns resolvers back");
1558  }
1559  return 0;
1560  err:
1562  if (! nameserver_config_failed) {
1564  mark_my_descriptor_dirty("dns resolvers failed");
1565  }
1566  return -1;
1567 }
1568 
1572 static void
1573 evdns_callback(int result, char type, int count, int ttl, void *addresses,
1574  void *arg)
1575 {
1576  char *arg_ = arg;
1577  uint8_t orig_query_type = arg_[0];
1578  char *string_address = arg_ + 1;
1579  tor_addr_t addr;
1580  const char *hostname = NULL;
1581  int was_wildcarded = 0;
1582 
1583  tor_addr_make_unspec(&addr);
1584 
1585  /* Keep track of whether IPv6 is working */
1586  if (type == DNS_IPv6_AAAA) {
1587  if (result == DNS_ERR_TIMEOUT) {
1588  ++n_ipv6_timeouts;
1589  }
1590 
1591  if (n_ipv6_timeouts > 10 &&
1592  n_ipv6_timeouts > n_ipv6_requests_made / 2) {
1593  if (! dns_is_broken_for_ipv6) {
1594  log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
1595  "have timed out. I'm going to assume I can't get AAAA "
1596  "responses.");
1597  dns_is_broken_for_ipv6 = 1;
1598  }
1599  }
1600  }
1601 
1602  if (result == DNS_ERR_NONE) {
1603  if (type == DNS_IPv4_A && count) {
1604  char answer_buf[INET_NTOA_BUF_LEN+1];
1605  char *escaped_address;
1606  uint32_t *addrs = addresses;
1607  tor_addr_from_ipv4n(&addr, addrs[0]);
1608 
1609  tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
1610  escaped_address = esc_for_log(string_address);
1611 
1612  if (answer_is_wildcarded(answer_buf)) {
1613  log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1614  "address %s; treating as a failure.",
1615  safe_str(escaped_address),
1616  escaped_safe_str(answer_buf));
1617  was_wildcarded = 1;
1618  tor_addr_make_unspec(&addr);
1619  result = DNS_ERR_NOTEXIST;
1620  } else {
1621  log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1622  safe_str(escaped_address),
1623  escaped_safe_str(answer_buf));
1624  }
1625  tor_free(escaped_address);
1626  } else if (type == DNS_IPv6_AAAA && count) {
1627  char answer_buf[TOR_ADDR_BUF_LEN];
1628  char *escaped_address;
1629  struct in6_addr *addrs = addresses;
1630  tor_addr_from_in6(&addr, &addrs[0]);
1631  tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
1632  escaped_address = esc_for_log(string_address);
1633 
1634  if (answer_is_wildcarded(answer_buf)) {
1635  log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
1636  "address %s; treating as a failure.",
1637  safe_str(escaped_address),
1638  escaped_safe_str(answer_buf));
1639  was_wildcarded = 1;
1640  tor_addr_make_unspec(&addr);
1641  result = DNS_ERR_NOTEXIST;
1642  } else {
1643  log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1644  safe_str(escaped_address),
1645  escaped_safe_str(answer_buf));
1646  }
1647  tor_free(escaped_address);
1648  } else if (type == DNS_PTR && count) {
1649  char *escaped_address;
1650  hostname = ((char**)addresses)[0];
1651  escaped_address = esc_for_log(string_address);
1652  log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
1653  safe_str(escaped_address),
1654  escaped_safe_str(hostname));
1655  tor_free(escaped_address);
1656  } else if (count) {
1657  log_info(LD_EXIT, "eventdns returned only unrecognized answer types "
1658  " for %s.",
1659  escaped_safe_str(string_address));
1660  } else {
1661  log_info(LD_EXIT, "eventdns returned no addresses or error for %s.",
1662  escaped_safe_str(string_address));
1663  }
1664  }
1665  if (was_wildcarded) {
1666  if (is_test_address(string_address)) {
1667  /* Ick. We're getting redirected on known-good addresses. Our DNS
1668  * server must really hate us. */
1669  add_wildcarded_test_address(string_address);
1670  }
1671  }
1672 
1673  if (orig_query_type && type && orig_query_type != type) {
1674  log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
1675  (int)orig_query_type, (int)type);
1676  }
1677  if (result != DNS_ERR_SHUTDOWN)
1678  dns_found_answer(string_address, orig_query_type,
1679  result, &addr, hostname, ttl);
1680 
1681  tor_free(arg_);
1682 }
1683 
1687 static int
1688 launch_one_resolve(const char *address, uint8_t query_type,
1689  const tor_addr_t *ptr_address)
1690 {
1691  const int options = get_options()->ServerDNSSearchDomains ? 0
1692  : DNS_QUERY_NO_SEARCH;
1693  const size_t addr_len = strlen(address);
1694  struct evdns_request *req = 0;
1695  char *addr = tor_malloc(addr_len + 2);
1696  addr[0] = (char) query_type;
1697  memcpy(addr+1, address, addr_len + 1);
1698 
1699  switch (query_type) {
1700  case DNS_IPv4_A:
1701  req = evdns_base_resolve_ipv4(the_evdns_base,
1702  address, options, evdns_callback, addr);
1703  break;
1704  case DNS_IPv6_AAAA:
1705  req = evdns_base_resolve_ipv6(the_evdns_base,
1706  address, options, evdns_callback, addr);
1707  ++n_ipv6_requests_made;
1708  break;
1709  case DNS_PTR:
1710  if (tor_addr_family(ptr_address) == AF_INET)
1711  req = evdns_base_resolve_reverse(the_evdns_base,
1712  tor_addr_to_in(ptr_address),
1713  DNS_QUERY_NO_SEARCH,
1714  evdns_callback, addr);
1715  else if (tor_addr_family(ptr_address) == AF_INET6)
1716  req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
1717  tor_addr_to_in6(ptr_address),
1718  DNS_QUERY_NO_SEARCH,
1719  evdns_callback, addr);
1720  else
1721  log_warn(LD_BUG, "Called with PTR query and unexpected address family");
1722  break;
1723  default:
1724  log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
1725  break;
1726  }
1727 
1728  if (req) {
1729  return 0;
1730  } else {
1731  tor_free(addr);
1732  return -1;
1733  }
1734 }
1735 
1739 MOCK_IMPL(STATIC int,
1740 launch_resolve,(cached_resolve_t *resolve))
1741 {
1742  tor_addr_t a;
1743  int r;
1744 
1745  if (net_is_disabled())
1746  return -1;
1747 
1748  /* What? Nameservers not configured? Sounds like a bug. */
1749  if (!nameservers_configured) {
1750  log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
1751  "launched. Configuring.");
1752  if (configure_nameservers(1) < 0) {
1753  return -1;
1754  }
1755  }
1756 
1758  &a, resolve->address, AF_UNSPEC, 0);
1759 
1761  if (r == 0) {
1762  log_info(LD_EXIT, "Launching eventdns request for %s",
1763  escaped_safe_str(resolve->address));
1764  resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
1765  if (get_options()->IPv6Exit)
1766  resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
1767 
1768  if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
1769  resolve->res_status_ipv4 = 0;
1770  r = -1;
1771  }
1772 
1773  if (r==0 && get_options()->IPv6Exit) {
1774  /* We ask for an IPv6 address for *everything*. */
1775  if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
1776  resolve->res_status_ipv6 = 0;
1777  r = -1;
1778  }
1779  }
1780  } else if (r == 1) {
1781  r = 0;
1782  log_info(LD_EXIT, "Launching eventdns reverse request for %s",
1783  escaped_safe_str(resolve->address));
1784  resolve->res_status_hostname = RES_STATUS_INFLIGHT;
1785  if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
1786  resolve->res_status_hostname = 0;
1787  r = -1;
1788  }
1789  } else if (r == -1) {
1790  log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
1791  }
1792 
1793  if (r < 0) {
1794  log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
1795  escaped_safe_str(resolve->address));
1796  }
1797  return r;
1798 }
1799 
1801 static int n_wildcard_requests = 0;
1802 
1807 static strmap_t *dns_wildcard_response_count = NULL;
1808 
1819 
1827 
1830 static void
1832 {
1833  int *ip;
1835  dns_wildcard_response_count = strmap_new();
1836 
1837  ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
1838  if (!ip) {
1839  ip = tor_malloc_zero(sizeof(int));
1840  strmap_set(dns_wildcard_response_count, id, ip);
1841  }
1842  ++*ip;
1843 
1844  if (*ip > 5 && n_wildcard_requests > 10) {
1845  if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
1848  "Your DNS provider has given \"%s\" as an answer for %d different "
1849  "invalid addresses. Apparently they are hijacking DNS failures. "
1850  "I'll try to correct for this by treating future occurrences of "
1851  "\"%s\" as 'not found'.", id, *ip, id);
1853  }
1855  control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
1857  }
1858 }
1859 
1862 static void
1863 add_wildcarded_test_address(const char *address)
1864 {
1865  int n, n_test_addrs;
1867  dns_wildcarded_test_address_list = smartlist_new();
1868 
1870  address))
1871  return;
1872 
1873  n_test_addrs = get_options()->ServerDNSTestAddresses ?
1874  smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
1875 
1877  n = smartlist_len(dns_wildcarded_test_address_list);
1878  if (n > n_test_addrs/2) {
1880  LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
1881  "address. It has done this with %d test addresses so far. I'm "
1882  "going to stop being an exit node for now, since our DNS seems so "
1883  "broken.", address, n);
1886  mark_my_descriptor_dirty("dns hijacking confirmed");
1887  }
1889  control_event_server_status(LOG_WARN, "DNS_USELESS");
1891  }
1892 }
1893 
1896 static void
1897 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
1898  void *addresses, void *arg)
1899 {
1900  (void)ttl;
1902  if (result == DNS_ERR_NONE && count) {
1903  char *string_address = arg;
1904  int i;
1905  if (type == DNS_IPv4_A) {
1906  const uint32_t *addrs = addresses;
1907  for (i = 0; i < count; ++i) {
1908  char answer_buf[INET_NTOA_BUF_LEN+1];
1909  struct in_addr in;
1910  in.s_addr = addrs[i];
1911  tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
1912  wildcard_increment_answer(answer_buf);
1913  }
1914  } else if (type == DNS_IPv6_AAAA) {
1915  const struct in6_addr *addrs = addresses;
1916  for (i = 0; i < count; ++i) {
1917  char answer_buf[TOR_ADDR_BUF_LEN+1];
1918  tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
1919  wildcard_increment_answer(answer_buf);
1920  }
1921  }
1922 
1924  "Your DNS provider gave an answer for \"%s\", which "
1925  "is not supposed to exist. Apparently they are hijacking "
1926  "DNS failures. Trying to correct for this. We've noticed %d "
1927  "possibly bad address%s so far.",
1928  string_address, strmap_size(dns_wildcard_response_count),
1929  (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
1931  }
1932  tor_free(arg);
1933 }
1934 
1938 static void
1939 launch_wildcard_check(int min_len, int max_len, int is_ipv6,
1940  const char *suffix)
1941 {
1942  char *addr;
1943  struct evdns_request *req;
1944 
1945  addr = crypto_random_hostname(min_len, max_len, "", suffix);
1946  log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
1947  "domains with request for bogus hostname \"%s\"", addr);
1948 
1950  if (is_ipv6)
1951  req = evdns_base_resolve_ipv6(
1953  /* This "addr" tells us which address to resolve */
1954  addr,
1955  DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1956  /* This "addr" is an argument to the callback*/ addr);
1957  else
1958  req = evdns_base_resolve_ipv4(
1960  /* This "addr" tells us which address to resolve */
1961  addr,
1962  DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
1963  /* This "addr" is an argument to the callback*/ addr);
1964  if (!req) {
1965  /* There is no evdns request in progress; stop addr from getting leaked */
1966  tor_free(addr);
1967  }
1968 }
1969 
1972 static void
1973 launch_test_addresses(evutil_socket_t fd, short event, void *args)
1974 {
1975  const or_options_t *options = get_options();
1976  (void)fd;
1977  (void)event;
1978  (void)args;
1979 
1980  if (net_is_disabled())
1981  return;
1982 
1983  log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
1984  "hijack *everything*.");
1985  /* This situation is worse than the failure-hijacking situation. When this
1986  * happens, we're no good for DNS requests at all, and we shouldn't really
1987  * be an exit server.*/
1988  if (options->ServerDNSTestAddresses) {
1989 
1992  const char *, address) {
1993  if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
1994  log_info(LD_EXIT, "eventdns rejected test address %s",
1995  escaped_safe_str(address));
1996  }
1997 
1998  if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
1999  log_info(LD_EXIT, "eventdns rejected test address %s",
2000  escaped_safe_str(address));
2001  }
2002  } SMARTLIST_FOREACH_END(address);
2003  }
2004 }
2005 
2006 #define N_WILDCARD_CHECKS 2
2007 
2012 static void
2014 {
2015  int i, ipv6;
2016  log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
2017  "to hijack DNS failures.");
2018  for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
2019  for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
2020  /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
2021  * attempt to 'comply' with rfc2606, refrain from giving A records for
2022  * these. This is the standards-compliance equivalent of making sure
2023  * that your crackhouse's elevator inspection certificate is up to date.
2024  */
2025  launch_wildcard_check(2, 16, ipv6, ".invalid");
2026  launch_wildcard_check(2, 16, ipv6, ".test");
2027 
2028  /* These will break specs if there are ever any number of
2029  * 8+-character top-level domains. */
2030  launch_wildcard_check(8, 16, ipv6, "");
2031 
2032  /* Try some random .com/org/net domains. This will work fine so long as
2033  * not too many resolve to the same place. */
2034  launch_wildcard_check(8, 16, ipv6, ".com");
2035  launch_wildcard_check(8, 16, ipv6, ".org");
2036  launch_wildcard_check(8, 16, ipv6, ".net");
2037  }
2038  }
2039 }
2040 
2043 void
2045 {
2046  static struct event *launch_event = NULL;
2047  struct timeval timeout;
2048  if (!get_options()->ServerDNSDetectHijacking)
2049  return;
2051 
2052  /* Wait a while before launching requests for test addresses, so we can
2053  * get the results from checking for wildcarding. */
2054  if (! launch_event)
2055  launch_event = tor_evtimer_new(tor_libevent_get_base(),
2056  launch_test_addresses, NULL);
2057  timeout.tv_sec = 30;
2058  timeout.tv_usec = 0;
2059  if (evtimer_add(launch_event, &timeout)<0) {
2060  log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
2061  }
2062 }
2063 
2065 int
2067 {
2069 }
2070 
2072 int
2074 {
2075  return dns_is_broken_for_ipv6;
2076 }
2077 
2079 void
2081 {
2082  strmap_free(dns_wildcard_response_count, tor_free_);
2084 
2085  n_wildcard_requests = 0;
2086 
2087  n_ipv6_requests_made = n_ipv6_timeouts = 0;
2088 
2089  if (dns_wildcard_list) {
2090  SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
2092  }
2095  tor_free(cp));
2097  }
2100  dns_is_broken_for_ipv6 = 0;
2101 }
2102 
2105 static int
2106 answer_is_wildcarded(const char *ip)
2107 {
2109 }
2110 
2112 static void
2114 {
2115  tor_assert(resolve);
2116  tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
2117  tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
2119  if (resolve->state != CACHE_STATE_PENDING) {
2120  tor_assert(!resolve->pending_connections);
2121  }
2122  if (resolve->state == CACHE_STATE_PENDING ||
2123  resolve->state == CACHE_STATE_DONE) {
2124 #if 0
2125  tor_assert(!resolve->ttl);
2126  if (resolve->is_reverse)
2127  tor_assert(!resolve->hostname);
2128  else
2129  tor_assert(!resolve->result_ipv4.addr_ipv4);
2130 #endif /* 0 */
2131  /*XXXXX ADD MORE */
2132  }
2133 }
2134 
2136 static int
2138 {
2139  return HT_SIZE(&cache_root);
2140 }
2141 
2142 /* Return the total size in bytes of the DNS cache. */
2143 size_t
2144 dns_cache_total_allocation(void)
2145 {
2146  return sizeof(struct cached_resolve_t) * dns_cache_entry_count() +
2147  HT_MEM_USAGE(&cache_root);
2148 }
2149 
2151 void
2152 dump_dns_mem_usage(int severity)
2153 {
2154  /* This should never be larger than INT_MAX. */
2155  int hash_count = dns_cache_entry_count();
2156  size_t hash_mem = dns_cache_total_allocation();
2157 
2158  /* Print out the count and estimated size of our &cache_root. It undercounts
2159  hostnames in cached reverse resolves.
2160  */
2161  tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
2162  tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
2163  (unsigned)hash_mem);
2164 }
2165 
2166 /* Do a round of OOM cleanup on all DNS entries. Return the amount of removed
2167  * bytes. It is possible that the returned value is lower than min_remove_bytes
2168  * if the caches get emptied out so the caller should be aware of this. */
2169 size_t
2170 dns_cache_handle_oom(time_t now, size_t min_remove_bytes)
2171 {
2172  time_t time_inc = 0;
2173  size_t total_bytes_removed = 0;
2174  size_t current_size = dns_cache_total_allocation();
2175 
2176  do {
2177  /* If no DNS entries left, break loop. */
2178  if (!dns_cache_entry_count())
2179  break;
2180 
2181  /* Get cutoff interval and remove entries. */
2182  time_t cutoff = now + time_inc;
2183  purge_expired_resolves(cutoff);
2184 
2185  /* Update amount of bytes removed and array size. */
2186  size_t bytes_removed = current_size - dns_cache_total_allocation();
2187  current_size -= bytes_removed;
2188  total_bytes_removed += bytes_removed;
2189 
2190  time_inc += 3600; /* Increase time_inc by 1 hour. */
2191  } while (total_bytes_removed < min_remove_bytes);
2192 
2193  return total_bytes_removed;
2194 }
2195 
2196 #ifdef DEBUG_DNS_CACHE
2197 
2198 static void
2199 assert_cache_ok_(void)
2200 {
2201  cached_resolve_t **resolve;
2202  int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
2203  if (bad_rep) {
2204  log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
2205  tor_assert(!bad_rep);
2206  }
2207 
2208  HT_FOREACH(resolve, cache_map, &cache_root) {
2209  assert_resolve_ok(*resolve);
2210  tor_assert((*resolve)->state != CACHE_STATE_DONE);
2211  }
2212  if (!cached_resolve_pqueue)
2213  return;
2214 
2217  offsetof(cached_resolve_t, minheap_idx));
2218 
2220  {
2221  if (res->state == CACHE_STATE_DONE) {
2222  cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2223  tor_assert(!found || found != res);
2224  } else {
2225  cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
2226  tor_assert(found);
2227  }
2228  });
2229 }
2230 
2231 #endif /* defined(DEBUG_DNS_CACHE) */
2232 
2234 dns_get_cache_entry(cached_resolve_t *query)
2235 {
2236  return HT_FIND(cache_map, &cache_root, query);
2237 }
2238 
2239 void
2240 dns_insert_cache_entry(cached_resolve_t *new_entry)
2241 {
2242  HT_INSERT(cache_map, &cache_root, new_entry);
2243 }
#define DEFAULT_DNS_TTL
Definition: dns.h:25
#define RELAY_PAYLOAD_SIZE
Definition: or.h:605
tor_socket_t s
Definition: connection_st.h:88
static void evdns_callback(int result, char type, int count, int ttl, void *addresses, void *arg)
Definition: dns.c:1573
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:862
#define BEGIN_FLAG_IPV6_PREFERRED
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:317
static int dns_cache_entry_count(void)
Definition: dns.c:2137
unsigned int is_reverse_dns_lookup
#define TOR_ADDR_BUF_LEN
Definition: address.h:205
Common functions for using (pseudo-)random number generators.
#define MIN_DNS_TTL_AT_EXIT
Definition: dns.h:16
static void dns_launch_wildcard_checks(void)
Definition: dns.c:2013
void assert_connection_edge_not_dns_pending(edge_connection_t *conn)
Definition: dns.c:966
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define TO_CONN(c)
Definition: or.h:735
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
const char * escaped_safe_str(const char *address)
Definition: config.c:1101
#define RES_STATUS_DONE_OK
Definition: dns_structs.h:51
void connection_dns_remove(edge_connection_t *conn)
Definition: dns.c:1012
MOCK_IMPL(STATIC void, send_resolved_cell,(edge_connection_t *conn, uint8_t answer_type, const cached_resolve_t *resolved))
Definition: dns.c:515
static int cached_resolve_have_all_answers(const cached_resolve_t *resolve)
Definition: dns.c:376
tor_addr_t addr
#define EXIT_PURPOSE_CONNECT
static int evdns_err_is_transient(int err)
Definition: dns.c:1350
#define RESOLVE_MAX_TIMEOUT
Definition: dns.c:84
#define EXIT_CONN_STATE_RESOLVING
Header file for connection.c.
#define EXIT_CONN_STATE_RESOLVEFAILED
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
int tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, int family, int accept_regular)
Definition: address.c:368
static strmap_t * dns_wildcard_response_count
Definition: dns.c:1807
static time_t resolv_conf_mtime
Definition: dns.c:98
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:143
static int launch_one_resolve(const char *address, uint8_t query_type, const tor_addr_t *ptr_address)
Definition: dns.c:1688
uint8_t state
Definition: connection_st.h:44
#define MAX_DNS_TTL_AT_EXIT
Definition: dns.h:18
#define MAX_ADDRESSLEN
Definition: dns_structs.h:17
#define LOG_INFO
Definition: log.h:41
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:631
int dns_init(void)
Definition: dns.c:224
#define CACHE_STATE_DONE
Definition: dns_structs.h:40
#define RES_STATUS_DONE_ERR
Definition: dns_structs.h:53
static int dns_wildcarded_test_address_notice_given
Definition: dns.c:1824
static void set_expiry(cached_resolve_t *resolve, time_t expires)
Definition: dns.c:386
void smartlist_pqueue_add(smartlist_t *sl, int(*compare)(const void *a, const void *b), int idx_field_offset, void *item)
Definition: smartlist.c:726
Header file for config.c.
static int dns_wildcard_notice_given
Definition: dns.c:1818
static int configure_nameservers(int force)
Definition: dns.c:1406
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition: address.h:152
uint16_t port
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:209
static void inform_pending_connections(cached_resolve_t *resolve)
Definition: dns.c:1210
#define tor_free(p)
Definition: malloc.h:52
#define tor_fragile_assert()
Definition: util_bug.h:221
int dns_seems_to_be_broken_for_ipv6(void)
Definition: dns.c:2073
#define LOG_NOTICE
Definition: log.h:46
static void wildcard_increment_answer(const char *id)
Definition: dns.c:1831
Header file for mainloop.c.
#define INET_NTOA_BUF_LEN
Definition: inaddr.h:21
#define EXIT_PURPOSE_RESOLVE
union cached_resolve_t::@22 result_ipv6
void dns_reset_correctness_checks(void)
Definition: dns.c:2080
static void make_pending_resolve_cached(cached_resolve_t *cached)
Definition: dns.c:1294
void * tor_reallocarray_(void *ptr, size_t sz1, size_t sz2)
Definition: malloc.c:146
#define sandbox_intern_string(s)
Definition: sandbox.h:112
unsigned int purpose
Definition: connection_st.h:46
static int dns_wildcard_one_notice_given
Definition: dns.c:1815
int connection_edge_send_command(edge_connection_t *fromconn, uint8_t relay_command, const char *payload, size_t payload_len)
Definition: relay.c:661
const char * tor_inet_ntop(int af, const void *src, char *dst, size_t len)
Definition: inaddr.c:77
uint32_t ttl_hostname
Definition: dns_structs.h:94
static void set_uint32(void *cp, uint32_t v)
Definition: bytes.h:82
void assert_all_pending_dns_resolves_ok(void)
Definition: dns.c:993
static void launch_wildcard_check(int min_len, int max_len, int is_ipv6, const char *suffix)
Definition: dns.c:1939
char * ServerDNSResolvConfFile
static const struct in_addr * tor_addr_to_in(const tor_addr_t *a)
Definition: address.h:186
#define SOCKET_OK(s)
Definition: nettypes.h:39
#define RES_STATUS_INFLIGHT
Definition: dns_structs.h:49
uint32_t dns_clip_ttl(uint32_t ttl)
Definition: dns.c:275
Header file for policies.c.
void smartlist_pqueue_assert_ok(smartlist_t *sl, int(*compare)(const void *a, const void *b), int idx_field_offset)
Definition: smartlist.c:803
tor_assert(buffer)
edge_connection_t * n_streams
Definition: or_circuit_st.h:42
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1078
#define tor_addr_from_ipv4h(dest, v4addr)
Definition: address.h:287
Header file for routermode.c.
void dns_free_all(void)
Definition: dns.c:400
uint32_t magic
Definition: dns_structs.h:62
int has_dns_init_failed(void)
Definition: dns.c:266
static smartlist_t * dns_wildcard_list
Definition: dns.c:1812
static smartlist_t * cached_resolve_pqueue
Definition: dns.c:321
Header file for sandbox.c.
int smartlist_contains_string_case(const smartlist_t *sl, const char *element)
Definition: smartlist.c:133
void * smartlist_pqueue_pop(smartlist_t *sl, int(*compare)(const void *a, const void *b), int idx_field_offset)
Definition: smartlist.c:755
static void dns_randfn_(char *b, size_t n)
Definition: dns.c:217
static int n_wildcard_requests
Definition: dns.c:1801
static HT_HEAD(cache_map, cached_resolve_t)
Definition: dns.c:122
Master header file for Tor-specific functionality.
int dns_reset(void)
Definition: dns.c:238
#define CACHED_RESOLVE_MAGIC
Definition: dns_structs.h:27
#define BEGIN_FLAG_IPV4_NOT_OK
char address[MAX_ADDRESSLEN]
Definition: dns_structs.h:63
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1185
uint16_t marked_for_close
#define LOG_WARN
Definition: log.h:49
unsigned int type
Definition: connection_st.h:45
int dns_resolve(edge_connection_t *exitconn)
Definition: dns.c:634
void dns_servers_relaunch_checks(void)
Definition: mainloop.c:2796
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:260
Header file for circuituse.c.
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:1157
void tor_free_(void *mem)
Definition: malloc.c:227
int connection_in_array(connection_t *conn)
Definition: mainloop.c:445
void tor_strlower(char *s)
Definition: util_string.c:130
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2244
static unsigned int cached_resolve_hash(cached_resolve_t *a)
Definition: dns.c:143
Header file for circuitlist.c.
int dns_seems_to_be_broken(void)
Definition: dns.c:2066
size_t number_of_configured_nameservers(void)
Definition: dns.c:1367
#define CACHE_STATE_CACHED
Definition: dns_structs.h:43
static void evdns_wildcard_check_callback(int result, char type, int count, int ttl, void *addresses, void *arg)
Definition: dns.c:1897
static void launch_test_addresses(evutil_socket_t fd, short event, void *args)
Definition: dns.c:1973
#define LD_FS
Definition: log.h:66
static int answer_is_wildcarded(const char *ip)
Definition: dns.c:2106
HT_PROTOTYPE(HT_GENERATE2(cache_map, HT_GENERATE2(cached_resolve_t, HT_GENERATE2(node, HT_GENERATE2(cached_resolve_hash, HT_GENERATE2(cached_resolves_eq)
Definition: dns.c:148
int tor_strisnonupper(const char *s)
Definition: util_string.c:165
Header file for connection_edge.c.
uint32_t ttl_ipv6
Definition: dns_structs.h:93
int smartlist_contains_string(const smartlist_t *sl, const char *element)
Definition: smartlist.c:93
int control_event_server_status(int severity, const char *format,...)
Definition: control.c:6847
void assert_connection_ok(connection_t *conn, time_t now)
Definition: connection.c:5218
int router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
Definition: router.c:1542
struct smartlist_t * ServerDNSTestAddresses
#define CACHE_STATE_PENDING
Definition: dns_structs.h:36
void connection_exit_connect(edge_connection_t *edge_conn)
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:884
Header file for relay.c.
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Header file for router.c.
const char * escaped(const char *s)
Definition: escape.c:126
static void evdns_log_cb(int warn, const char *msg)
Definition: dns.c:162
static smartlist_t * dns_wildcarded_test_address_list
Definition: dns.c:1822
edge_connection_t * resolving_streams
Definition: or_circuit_st.h:45
static const struct in6_addr * tor_addr_to_in6(const tor_addr_t *a)
Definition: address.h:111
static int dns_is_completely_invalid
Definition: dns.c:1826
#define log_fn(severity, domain, args,...)
Definition: log.h:255
static char * resolv_conf_fname
Definition: dns.c:95
static int nameserver_config_failed
Definition: dns.c:92
#define CONN_TYPE_EXIT
Definition: connection.h:26
void dump_dns_mem_usage(int severity)
Definition: dns.c:2152
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:151
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
Header file for control.c.
int tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
Definition: inaddr.c:58
struct in6_addr addr_ipv6
Definition: dns_structs.h:71
static int is_test_address(const char *address)
Definition: dns.c:1140
uint32_t addr_ipv4
Definition: dns_structs.h:66
static int compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
Definition: dns.c:308
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1576
struct circuit_t * on_circuit
union cached_resolve_t::@21 result_ipv4
int ServerDNSRandomizeCase
uint32_t ttl_ipv4
Definition: dns_structs.h:92
char * esc_for_log(const char *s)
Definition: escape.c:30
static void purge_expired_resolves(time_t now)
Definition: dns.c:425
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1383
struct edge_connection_t * next_stream
Header for compat_libevent.c.
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:892
#define BEGIN_FLAG_IPV6_OK
static void add_wildcarded_test_address(const char *address)
Definition: dns.c:1863
void smartlist_clear(smartlist_t *sl)
#define LD_MM
Definition: log.h:70
static int nameservers_configured
Definition: dns.c:90
static void free_cached_resolve_(cached_resolve_t *r)
Definition: dns.c:289
int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out)
Definition: address.c:165
char * crypto_random_hostname(int min_rand_len, int max_rand_len, const char *prefix, const char *suffix)
Definition: crypto_rand.c:659
static void assert_resolve_ok(cached_resolve_t *resolve)
Definition: dns.c:2113
#define LD_BUG
Definition: log.h:82
static struct evdns_base * the_evdns_base
Definition: dns.c:87
Header file for dns.c.
const char * safe_str(const char *address)
Definition: config.c:1076
pending_connection_t * pending_connections
Definition: dns_structs.h:96
#define EXIT_CONN_STATE_CONNECTING
void dns_launch_correctness_checks(void)
Definition: dns.c:2044
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:179