Back to index

tor  0.2.3.19-rc
dns.c
Go to the documentation of this file.
00001 /* Copyright (c) 2003-2004, Roger Dingledine.
00002  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00003  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00004 /* See LICENSE for licensing information */
00005 
00014 #include "or.h"
00015 #include "circuitlist.h"
00016 #include "circuituse.h"
00017 #include "config.h"
00018 #include "connection.h"
00019 #include "connection_edge.h"
00020 #include "control.h"
00021 #include "dns.h"
00022 #include "main.h"
00023 #include "policies.h"
00024 #include "relay.h"
00025 #include "router.h"
00026 #include "ht.h"
00027 #ifdef HAVE_EVENT2_DNS_H
00028 #include <event2/event.h>
00029 #include <event2/dns.h>
00030 #else
00031 #include <event.h>
00032 #include "eventdns.h"
00033 #ifndef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
00034 #define HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
00035 #endif
00036 #endif
00037 
00038 #ifndef HAVE_EVENT2_DNS_H
00039 struct evdns_base;
00040 struct evdns_request;
00041 #define evdns_base_new(x,y) tor_malloc(1)
00042 #define evdns_base_clear_nameservers_and_suspend(base) \
00043   evdns_clear_nameservers_and_suspend()
00044 #define evdns_base_search_clear(base) evdns_search_clear()
00045 #define evdns_base_set_default_outgoing_bind_address(base, a, len)  \
00046   evdns_set_default_outgoing_bind_address((a),(len))
00047 #define evdns_base_resolv_conf_parse(base, options, fname) \
00048   evdns_resolv_conf_parse((options), (fname))
00049 #define evdns_base_count_nameservers(base)      \
00050   evdns_count_nameservers()
00051 #define evdns_base_resume(base)                 \
00052   evdns_resume()
00053 #define evdns_base_config_windows_nameservers(base)     \
00054   evdns_config_windows_nameservers()
00055 #define evdns_base_set_option_(base, opt, val) \
00056   evdns_set_option((opt),(val),DNS_OPTIONS_ALL)
00057 /* Note: our internal eventdns.c, plus Libevent 1.4, used a 1 return to
00058  * signify failure to launch a resolve. Libevent 2.0 uses a -1 return to
00059  * signify a failure on a resolve, though if we're on Libevent 2.0, we should
00060  * have event2/dns.h and never hit these macros.  Regardless, 0 is success. */
00061 #define evdns_base_resolve_ipv4(base, addr, options, cb, ptr) \
00062   ((evdns_resolve_ipv4((addr), (options), (cb), (ptr))!=0)    \
00063    ? NULL : ((void*)1))
00064 #define evdns_base_resolve_reverse(base, addr, options, cb, ptr)        \
00065   ((evdns_resolve_reverse((addr), (options), (cb), (ptr))!=0)           \
00066    ? NULL : ((void*)1))
00067 #define evdns_base_resolve_reverse_ipv6(base, addr, options, cb, ptr)   \
00068   ((evdns_resolve_reverse_ipv6((addr), (options), (cb), (ptr))!=0)      \
00069    ? NULL : ((void*)1))
00070 
00071 #elif defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER < 0x02000303
00072 #define evdns_base_set_option_(base, opt, val) \
00073   evdns_base_set_option((base), (opt),(val),DNS_OPTIONS_ALL)
00074 
00075 #else
00076 #define evdns_base_set_option_ evdns_base_set_option
00077 
00078 #endif
00079 
00081 #define MAX_ADDRESSLEN 256
00082 
00085 #define RESOLVE_MAX_TIMEOUT 300
00086 
00089 #define DNS_RESOLVE_FAILED_TRANSIENT 1
00090 #define DNS_RESOLVE_FAILED_PERMANENT 2
00091 #define DNS_RESOLVE_SUCCEEDED 3
00092 
00094 static struct evdns_base *the_evdns_base = NULL;
00095 
00097 static int nameservers_configured = 0;
00099 static int nameserver_config_failed = 0;
00102 static char *resolv_conf_fname = NULL;
00105 static time_t resolv_conf_mtime = 0;
00106 
00108 typedef struct pending_connection_t {
00109   edge_connection_t *conn;
00110   struct pending_connection_t *next;
00111 } pending_connection_t;
00112 
00115 #define CACHED_RESOLVE_MAGIC 0x1234F00D
00116 
00117 /* Possible states for a cached resolve_t */
00124 #define CACHE_STATE_PENDING 0
00125 
00128 #define CACHE_STATE_DONE 1
00129 
00131 #define CACHE_STATE_CACHED_VALID 2
00132 
00134 #define CACHE_STATE_CACHED_FAILED 3
00135 
00140 typedef struct cached_resolve_t {
00141   HT_ENTRY(cached_resolve_t) node;
00142   uint32_t magic;
00143   char address[MAX_ADDRESSLEN]; 
00144   union {
00145     struct {
00146       struct in6_addr addr6; 
00147       uint32_t addr;  
00148     } a;
00149     char *hostname; 
00150   } result;
00151   uint8_t state; 
00152   uint8_t is_reverse; 
00153   time_t expire; 
00154   uint32_t ttl; 
00156   pending_connection_t *pending_connections;
00158   int minheap_idx;
00159 } cached_resolve_t;
00160 
00161 static void purge_expired_resolves(time_t now);
00162 static void dns_found_answer(const char *address, uint8_t is_reverse,
00163                              uint32_t addr, const char *hostname, char outcome,
00164                              uint32_t ttl);
00165 static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
00166 static int launch_resolve(edge_connection_t *exitconn);
00167 static void add_wildcarded_test_address(const char *address);
00168 static int configure_nameservers(int force);
00169 static int answer_is_wildcarded(const char *ip);
00170 static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
00171                             or_circuit_t *oncirc, char **resolved_to_hostname);
00172 #ifdef DEBUG_DNS_CACHE
00173 static void _assert_cache_ok(void);
00174 #define assert_cache_ok() _assert_cache_ok()
00175 #else
00176 #define assert_cache_ok() STMT_NIL
00177 #endif
00178 static void assert_resolve_ok(cached_resolve_t *resolve);
00179 
00181 static HT_HEAD(cache_map, cached_resolve_t) cache_root;
00182 
00185 static INLINE int
00186 cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
00187 {
00188   /* make this smarter one day? */
00189   assert_resolve_ok(a); // Not b; b may be just a search.
00190   return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
00191 }
00192 
00194 static INLINE unsigned int
00195 cached_resolve_hash(cached_resolve_t *a)
00196 {
00197   return ht_string_hash(a->address);
00198 }
00199 
00200 HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
00201              cached_resolves_eq)
00202 HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
00203             cached_resolves_eq, 0.6, malloc, realloc, free)
00204 
00206 static void
00207 init_cache_map(void)
00208 {
00209   HT_INIT(cache_map, &cache_root);
00210 }
00211 
00213 static void
00214 evdns_log_cb(int warn, const char *msg)
00215 {
00216   const char *cp;
00217   static int all_down = 0;
00218   int severity = warn ? LOG_WARN : LOG_INFO;
00219   if (!strcmpstart(msg, "Resolve requested for") &&
00220       get_options()->SafeLogging) {
00221     log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
00222     return;
00223   } else if (!strcmpstart(msg, "Search: ")) {
00224     return;
00225   }
00226   if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
00227     char *ns = tor_strndup(msg+11, cp-(msg+11));
00228     const char *err = strchr(cp, ':')+2;
00229     tor_assert(err);
00230     /* Don't warn about a single failed nameserver; we'll warn with 'all
00231      * nameservers have failed' if we're completely out of nameservers;
00232      * otherwise, the situation is tolerable. */
00233     severity = LOG_INFO;
00234     control_event_server_status(LOG_NOTICE,
00235                                 "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
00236                                 ns, escaped(err));
00237     tor_free(ns);
00238   } else if (!strcmpstart(msg, "Nameserver ") &&
00239              (cp=strstr(msg, " is back up"))) {
00240     char *ns = tor_strndup(msg+11, cp-(msg+11));
00241     severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
00242     all_down = 0;
00243     control_event_server_status(LOG_NOTICE,
00244                                 "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
00245     tor_free(ns);
00246   } else if (!strcmp(msg, "All nameservers have failed")) {
00247     control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
00248     all_down = 1;
00249   }
00250   log(severity, LD_EXIT, "eventdns: %s", msg);
00251 }
00252 
00255 static void
00256 _dns_randfn(char *b, size_t n)
00257 {
00258   crypto_rand(b,n);
00259 }
00260 
00262 int
00263 dns_init(void)
00264 {
00265   init_cache_map();
00266   evdns_set_random_bytes_fn(_dns_randfn);
00267   if (server_mode(get_options())) {
00268     int r = configure_nameservers(1);
00269     return r;
00270   }
00271   return 0;
00272 }
00273 
00276 int
00277 dns_reset(void)
00278 {
00279   const or_options_t *options = get_options();
00280   if (! server_mode(options)) {
00281 
00282     if (!the_evdns_base) {
00283       if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
00284         log_err(LD_BUG, "Couldn't create an evdns_base");
00285         return -1;
00286       }
00287     }
00288 
00289     evdns_base_clear_nameservers_and_suspend(the_evdns_base);
00290     evdns_base_search_clear(the_evdns_base);
00291     nameservers_configured = 0;
00292     tor_free(resolv_conf_fname);
00293     resolv_conf_mtime = 0;
00294   } else {
00295     if (configure_nameservers(0) < 0) {
00296       return -1;
00297     }
00298   }
00299   return 0;
00300 }
00301 
00304 int
00305 has_dns_init_failed(void)
00306 {
00307   return nameserver_config_failed;
00308 }
00309 
00312 uint32_t
00313 dns_clip_ttl(uint32_t ttl)
00314 {
00315   if (ttl < MIN_DNS_TTL)
00316     return MIN_DNS_TTL;
00317   else if (ttl > MAX_DNS_TTL)
00318     return MAX_DNS_TTL;
00319   else
00320     return ttl;
00321 }
00322 
00325 static uint32_t
00326 dns_get_expiry_ttl(uint32_t ttl)
00327 {
00328   if (ttl < MIN_DNS_TTL)
00329     return MIN_DNS_TTL;
00330   else if (ttl > MAX_DNS_ENTRY_AGE)
00331     return MAX_DNS_ENTRY_AGE;
00332   else
00333     return ttl;
00334 }
00335 
00337 static void
00338 _free_cached_resolve(cached_resolve_t *r)
00339 {
00340   if (!r)
00341     return;
00342   while (r->pending_connections) {
00343     pending_connection_t *victim = r->pending_connections;
00344     r->pending_connections = victim->next;
00345     tor_free(victim);
00346   }
00347   if (r->is_reverse)
00348     tor_free(r->result.hostname);
00349   r->magic = 0xFF00FF00;
00350   tor_free(r);
00351 }
00352 
00356 static int
00357 _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
00358 {
00359   const cached_resolve_t *a = _a, *b = _b;
00360   if (a->expire < b->expire)
00361     return -1;
00362   else if (a->expire == b->expire)
00363     return 0;
00364   else
00365     return 1;
00366 }
00367 
00370 static smartlist_t *cached_resolve_pqueue = NULL;
00371 
00374 static void
00375 set_expiry(cached_resolve_t *resolve, time_t expires)
00376 {
00377   tor_assert(resolve && resolve->expire == 0);
00378   if (!cached_resolve_pqueue)
00379     cached_resolve_pqueue = smartlist_new();
00380   resolve->expire = expires;
00381   smartlist_pqueue_add(cached_resolve_pqueue,
00382                        _compare_cached_resolves_by_expiry,
00383                        STRUCT_OFFSET(cached_resolve_t, minheap_idx),
00384                        resolve);
00385 }
00386 
00388 void
00389 dns_free_all(void)
00390 {
00391   cached_resolve_t **ptr, **next, *item;
00392   assert_cache_ok();
00393   if (cached_resolve_pqueue) {
00394     SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
00395       {
00396         if (res->state == CACHE_STATE_DONE)
00397           _free_cached_resolve(res);
00398       });
00399   }
00400   for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
00401     item = *ptr;
00402     next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
00403     _free_cached_resolve(item);
00404   }
00405   HT_CLEAR(cache_map, &cache_root);
00406   smartlist_free(cached_resolve_pqueue);
00407   cached_resolve_pqueue = NULL;
00408   tor_free(resolv_conf_fname);
00409 }
00410 
00413 static void
00414 purge_expired_resolves(time_t now)
00415 {
00416   cached_resolve_t *resolve, *removed;
00417   pending_connection_t *pend;
00418   edge_connection_t *pendconn;
00419 
00420   assert_cache_ok();
00421   if (!cached_resolve_pqueue)
00422     return;
00423 
00424   while (smartlist_len(cached_resolve_pqueue)) {
00425     resolve = smartlist_get(cached_resolve_pqueue, 0);
00426     if (resolve->expire > now)
00427       break;
00428     smartlist_pqueue_pop(cached_resolve_pqueue,
00429                          _compare_cached_resolves_by_expiry,
00430                          STRUCT_OFFSET(cached_resolve_t, minheap_idx));
00431 
00432     if (resolve->state == CACHE_STATE_PENDING) {
00433       log_debug(LD_EXIT,
00434                 "Expiring a dns resolve %s that's still pending. Forgot to "
00435                 "cull it? DNS resolve didn't tell us about the timeout?",
00436                 escaped_safe_str(resolve->address));
00437     } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
00438                resolve->state == CACHE_STATE_CACHED_FAILED) {
00439       log_debug(LD_EXIT,
00440                 "Forgetting old cached resolve (address %s, expires %lu)",
00441                 escaped_safe_str(resolve->address),
00442                 (unsigned long)resolve->expire);
00443       tor_assert(!resolve->pending_connections);
00444     } else {
00445       tor_assert(resolve->state == CACHE_STATE_DONE);
00446       tor_assert(!resolve->pending_connections);
00447     }
00448 
00449     if (resolve->pending_connections) {
00450       log_debug(LD_EXIT,
00451                 "Closing pending connections on timed-out DNS resolve!");
00452       tor_fragile_assert();
00453       while (resolve->pending_connections) {
00454         pend = resolve->pending_connections;
00455         resolve->pending_connections = pend->next;
00456         /* Connections should only be pending if they have no socket. */
00457         tor_assert(!SOCKET_OK(pend->conn->_base.s));
00458         pendconn = pend->conn;
00459         connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
00460         circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
00461         connection_free(TO_CONN(pendconn));
00462         tor_free(pend);
00463       }
00464     }
00465 
00466     if (resolve->state == CACHE_STATE_CACHED_VALID ||
00467         resolve->state == CACHE_STATE_CACHED_FAILED ||
00468         resolve->state == CACHE_STATE_PENDING) {
00469       removed = HT_REMOVE(cache_map, &cache_root, resolve);
00470       if (removed != resolve) {
00471         log_err(LD_BUG, "The expired resolve we purged didn't match any in"
00472                 " the cache. Tried to purge %s (%p); instead got %s (%p).",
00473                 resolve->address, (void*)resolve,
00474                 removed ? removed->address : "NULL", (void*)removed);
00475       }
00476       tor_assert(removed == resolve);
00477     } else {
00478       /* This should be in state DONE. Make sure it's not in the cache. */
00479       cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
00480       tor_assert(tmp != resolve);
00481     }
00482     if (resolve->is_reverse)
00483       tor_free(resolve->result.hostname);
00484     resolve->magic = 0xF0BBF0BB;
00485     tor_free(resolve);
00486   }
00487 
00488   assert_cache_ok();
00489 }
00490 
00499 static void
00500 send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
00501 {
00502   char buf[RELAY_PAYLOAD_SIZE];
00503   size_t buflen;
00504   uint32_t ttl;
00505 
00506   buf[0] = answer_type;
00507   ttl = dns_clip_ttl(conn->address_ttl);
00508 
00509   switch (answer_type)
00510     {
00511     case RESOLVED_TYPE_IPV4:
00512       buf[1] = 4;
00513       set_uint32(buf+2, tor_addr_to_ipv4n(&conn->_base.addr));
00514       set_uint32(buf+6, htonl(ttl));
00515       buflen = 10;
00516       break;
00517     /*XXXX IP6 need ipv6 implementation */
00518     case RESOLVED_TYPE_ERROR_TRANSIENT:
00519     case RESOLVED_TYPE_ERROR:
00520       {
00521         const char *errmsg = "Error resolving hostname";
00522         size_t msglen = strlen(errmsg);
00523 
00524         buf[1] = msglen;
00525         strlcpy(buf+2, errmsg, sizeof(buf)-2);
00526         set_uint32(buf+2+msglen, htonl(ttl));
00527         buflen = 6+msglen;
00528         break;
00529       }
00530     default:
00531       tor_assert(0);
00532       return;
00533     }
00534   // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
00535 
00536   connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
00537 }
00538 
00547 static void
00548 send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
00549 {
00550   char buf[RELAY_PAYLOAD_SIZE];
00551   size_t buflen;
00552   uint32_t ttl;
00553   size_t namelen = strlen(hostname);
00554   tor_assert(hostname);
00555 
00556   tor_assert(namelen < 256);
00557   ttl = dns_clip_ttl(conn->address_ttl);
00558 
00559   buf[0] = RESOLVED_TYPE_HOSTNAME;
00560   buf[1] = (uint8_t)namelen;
00561   memcpy(buf+2, hostname, namelen);
00562   set_uint32(buf+2+namelen, htonl(ttl));
00563   buflen = 2+namelen+4;
00564 
00565   // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
00566   connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
00567   // log_notice(LD_EXIT, "Sent");
00568 }
00569 
00594 int
00595 dns_resolve(edge_connection_t *exitconn)
00596 {
00597   or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
00598   int is_resolve, r;
00599   char *hostname = NULL;
00600   is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
00601 
00602   r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
00603 
00604   switch (r) {
00605     case 1:
00606       /* We got an answer without a lookup -- either the answer was
00607        * cached, or it was obvious (like an IP address). */
00608       if (is_resolve) {
00609         /* Send the answer back right now, and detach. */
00610         if (hostname)
00611           send_resolved_hostname_cell(exitconn, hostname);
00612         else
00613           send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
00614         exitconn->on_circuit = NULL;
00615       } else {
00616         /* Add to the n_streams list; the calling function will send back a
00617          * connected cell. */
00618         exitconn->next_stream = oncirc->n_streams;
00619         oncirc->n_streams = exitconn;
00620       }
00621       break;
00622     case 0:
00623       /* The request is pending: add the connection into the linked list of
00624        * resolving_streams on this circuit. */
00625       exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
00626       exitconn->next_stream = oncirc->resolving_streams;
00627       oncirc->resolving_streams = exitconn;
00628       break;
00629     case -2:
00630     case -1:
00631       /* The request failed before it could start: cancel this connection,
00632        * and stop everybody waiting for the same connection. */
00633       if (is_resolve) {
00634         send_resolved_cell(exitconn,
00635              (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
00636       }
00637 
00638       exitconn->on_circuit = NULL;
00639 
00640       dns_cancel_pending_resolve(exitconn->_base.address);
00641 
00642       if (!exitconn->_base.marked_for_close) {
00643         connection_free(TO_CONN(exitconn));
00644         // XXX ... and we just leak exitconn otherwise? -RD
00645         // If it's marked for close, it's on closeable_connection_lst in
00646         // main.c.  If it's on the closeable list, it will get freed from
00647         // main.c. -NM
00648         // "<armadev> If that's true, there are other bugs around, where we
00649         //  don't check if it's marked, and will end up double-freeing."
00650         // On the other hand, I don't know of any actual bugs here, so this
00651         // shouldn't be holding up the rc. -RD
00652       }
00653       break;
00654     default:
00655       tor_assert(0);
00656   }
00657 
00658   tor_free(hostname);
00659   return r;
00660 }
00661 
00671 static int
00672 dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
00673                  or_circuit_t *oncirc, char **hostname_out)
00674 {
00675   cached_resolve_t *resolve;
00676   cached_resolve_t search;
00677   pending_connection_t *pending_connection;
00678   const routerinfo_t *me;
00679   tor_addr_t addr;
00680   time_t now = time(NULL);
00681   uint8_t is_reverse = 0;
00682   int r;
00683   assert_connection_ok(TO_CONN(exitconn), 0);
00684   tor_assert(!SOCKET_OK(exitconn->_base.s));
00685   assert_cache_ok();
00686   tor_assert(oncirc);
00687 
00688   /* first check if exitconn->_base.address is an IP. If so, we already
00689    * know the answer. */
00690   if (tor_addr_parse(&addr, exitconn->_base.address) >= 0) {
00691     if (tor_addr_family(&addr) == AF_INET) {
00692       tor_addr_copy(&exitconn->_base.addr, &addr);
00693       exitconn->address_ttl = DEFAULT_DNS_TTL;
00694       return 1;
00695     } else {
00696       /* XXXX IPv6 */
00697       return -1;
00698     }
00699   }
00700 
00701   /* If we're a non-exit, don't even do DNS lookups. */
00702   if (!(me = router_get_my_routerinfo()) ||
00703       policy_is_reject_star(me->exit_policy)) {
00704     return -1;
00705   }
00706   if (address_is_invalid_destination(exitconn->_base.address, 0)) {
00707     log(LOG_PROTOCOL_WARN, LD_EXIT,
00708         "Rejecting invalid destination address %s",
00709         escaped_safe_str(exitconn->_base.address));
00710     return -1;
00711   }
00712 
00713   /* then take this opportunity to see if there are any expired
00714    * resolves in the hash table. */
00715   purge_expired_resolves(now);
00716 
00717   /* lower-case exitconn->_base.address, so it's in canonical form */
00718   tor_strlower(exitconn->_base.address);
00719 
00720   /* Check whether this is a reverse lookup.  If it's malformed, or it's a
00721    * .in-addr.arpa address but this isn't a resolve request, kill the
00722    * connection.
00723    */
00724   if ((r = tor_addr_parse_PTR_name(&addr, exitconn->_base.address,
00725                                               AF_UNSPEC, 0)) != 0) {
00726     if (r == 1) {
00727       is_reverse = 1;
00728       if (tor_addr_is_internal(&addr, 0)) /* internal address? */
00729         return -1;
00730     }
00731 
00732     if (!is_reverse || !is_resolve) {
00733       if (!is_reverse)
00734         log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
00735                  escaped_safe_str(exitconn->_base.address));
00736       else if (!is_resolve)
00737         log_info(LD_EXIT,
00738                  "Attempt to connect to a .in-addr.arpa address \"%s\"; "
00739                  "sending error.",
00740                  escaped_safe_str(exitconn->_base.address));
00741 
00742       return -1;
00743     }
00744     //log_notice(LD_EXIT, "Looks like an address %s",
00745     //exitconn->_base.address);
00746   }
00747 
00748   /* now check the hash table to see if 'address' is already there. */
00749   strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
00750   resolve = HT_FIND(cache_map, &cache_root, &search);
00751   if (resolve && resolve->expire > now) { /* already there */
00752     switch (resolve->state) {
00753       case CACHE_STATE_PENDING:
00754         /* add us to the pending list */
00755         pending_connection = tor_malloc_zero(
00756                                       sizeof(pending_connection_t));
00757         pending_connection->conn = exitconn;
00758         pending_connection->next = resolve->pending_connections;
00759         resolve->pending_connections = pending_connection;
00760         log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
00761                   "resolve of %s", exitconn->_base.s,
00762                   escaped_safe_str(exitconn->_base.address));
00763         return 0;
00764       case CACHE_STATE_CACHED_VALID:
00765         log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
00766                   exitconn->_base.s,
00767                   escaped_safe_str(resolve->address));
00768         exitconn->address_ttl = resolve->ttl;
00769         if (resolve->is_reverse) {
00770           tor_assert(is_resolve);
00771           *hostname_out = tor_strdup(resolve->result.hostname);
00772         } else {
00773           tor_addr_from_ipv4h(&exitconn->_base.addr, resolve->result.a.addr);
00774         }
00775         return 1;
00776       case CACHE_STATE_CACHED_FAILED:
00777         log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
00778                   exitconn->_base.s,
00779                   escaped_safe_str(exitconn->_base.address));
00780         return -1;
00781       case CACHE_STATE_DONE:
00782         log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
00783         tor_fragile_assert();
00784     }
00785     tor_assert(0);
00786   }
00787   tor_assert(!resolve);
00788   /* not there, need to add it */
00789   resolve = tor_malloc_zero(sizeof(cached_resolve_t));
00790   resolve->magic = CACHED_RESOLVE_MAGIC;
00791   resolve->state = CACHE_STATE_PENDING;
00792   resolve->minheap_idx = -1;
00793   resolve->is_reverse = is_reverse;
00794   strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
00795 
00796   /* add this connection to the pending list */
00797   pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
00798   pending_connection->conn = exitconn;
00799   resolve->pending_connections = pending_connection;
00800 
00801   /* Add this resolve to the cache and priority queue. */
00802   HT_INSERT(cache_map, &cache_root, resolve);
00803   set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
00804 
00805   log_debug(LD_EXIT,"Launching %s.",
00806             escaped_safe_str(exitconn->_base.address));
00807   assert_cache_ok();
00808 
00809   return launch_resolve(exitconn);
00810 }
00811 
00814 void
00815 assert_connection_edge_not_dns_pending(edge_connection_t *conn)
00816 {
00817   pending_connection_t *pend;
00818   cached_resolve_t search;
00819 
00820 #if 1
00821   cached_resolve_t *resolve;
00822   strlcpy(search.address, conn->_base.address, sizeof(search.address));
00823   resolve = HT_FIND(cache_map, &cache_root, &search);
00824   if (!resolve)
00825     return;
00826   for (pend = resolve->pending_connections; pend; pend = pend->next) {
00827     tor_assert(pend->conn != conn);
00828   }
00829 #else
00830   cached_resolve_t **resolve;
00831   HT_FOREACH(resolve, cache_map, &cache_root) {
00832     for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
00833       tor_assert(pend->conn != conn);
00834     }
00835   }
00836 #endif
00837 }
00838 
00841 void
00842 assert_all_pending_dns_resolves_ok(void)
00843 {
00844   pending_connection_t *pend;
00845   cached_resolve_t **resolve;
00846 
00847   HT_FOREACH(resolve, cache_map, &cache_root) {
00848     for (pend = (*resolve)->pending_connections;
00849          pend;
00850          pend = pend->next) {
00851       assert_connection_ok(TO_CONN(pend->conn), 0);
00852       tor_assert(!SOCKET_OK(pend->conn->_base.s));
00853       tor_assert(!connection_in_array(TO_CONN(pend->conn)));
00854     }
00855   }
00856 }
00857 
00860 void
00861 connection_dns_remove(edge_connection_t *conn)
00862 {
00863   pending_connection_t *pend, *victim;
00864   cached_resolve_t search;
00865   cached_resolve_t *resolve;
00866 
00867   tor_assert(conn->_base.type == CONN_TYPE_EXIT);
00868   tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
00869 
00870   strlcpy(search.address, conn->_base.address, sizeof(search.address));
00871 
00872   resolve = HT_FIND(cache_map, &cache_root, &search);
00873   if (!resolve) {
00874     log_notice(LD_BUG, "Address %s is not pending. Dropping.",
00875                escaped_safe_str(conn->_base.address));
00876     return;
00877   }
00878 
00879   tor_assert(resolve->pending_connections);
00880   assert_connection_ok(TO_CONN(conn),0);
00881 
00882   pend = resolve->pending_connections;
00883 
00884   if (pend->conn == conn) {
00885     resolve->pending_connections = pend->next;
00886     tor_free(pend);
00887     log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
00888               "for resolve of %s",
00889               conn->_base.s,
00890               escaped_safe_str(conn->_base.address));
00891     return;
00892   } else {
00893     for ( ; pend->next; pend = pend->next) {
00894       if (pend->next->conn == conn) {
00895         victim = pend->next;
00896         pend->next = victim->next;
00897         tor_free(victim);
00898         log_debug(LD_EXIT,
00899                   "Connection (fd %d) no longer waiting for resolve of %s",
00900                   conn->_base.s, escaped_safe_str(conn->_base.address));
00901         return; /* more are pending */
00902       }
00903     }
00904     tor_assert(0); /* not reachable unless onlyconn not in pending list */
00905   }
00906 }
00907 
00912 void
00913 dns_cancel_pending_resolve(const char *address)
00914 {
00915   pending_connection_t *pend;
00916   cached_resolve_t search;
00917   cached_resolve_t *resolve, *tmp;
00918   edge_connection_t *pendconn;
00919   circuit_t *circ;
00920 
00921   strlcpy(search.address, address, sizeof(search.address));
00922 
00923   resolve = HT_FIND(cache_map, &cache_root, &search);
00924   if (!resolve)
00925     return;
00926 
00927   if (resolve->state != CACHE_STATE_PENDING) {
00928     /* We can get into this state if we never actually created the pending
00929      * resolve, due to finding an earlier cached error or something.  Just
00930      * ignore it. */
00931     if (resolve->pending_connections) {
00932       log_warn(LD_BUG,
00933                "Address %s is not pending but has pending connections!",
00934                escaped_safe_str(address));
00935       tor_fragile_assert();
00936     }
00937     return;
00938   }
00939 
00940   if (!resolve->pending_connections) {
00941     log_warn(LD_BUG,
00942              "Address %s is pending but has no pending connections!",
00943              escaped_safe_str(address));
00944     tor_fragile_assert();
00945     return;
00946   }
00947   tor_assert(resolve->pending_connections);
00948 
00949   /* mark all pending connections to fail */
00950   log_debug(LD_EXIT,
00951              "Failing all connections waiting on DNS resolve of %s",
00952              escaped_safe_str(address));
00953   while (resolve->pending_connections) {
00954     pend = resolve->pending_connections;
00955     pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
00956     pendconn = pend->conn;
00957     assert_connection_ok(TO_CONN(pendconn), 0);
00958     tor_assert(!SOCKET_OK(pendconn->_base.s));
00959     if (!pendconn->_base.marked_for_close) {
00960       connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
00961     }
00962     circ = circuit_get_by_edge_conn(pendconn);
00963     if (circ)
00964       circuit_detach_stream(circ, pendconn);
00965     if (!pendconn->_base.marked_for_close)
00966       connection_free(TO_CONN(pendconn));
00967     resolve->pending_connections = pend->next;
00968     tor_free(pend);
00969   }
00970 
00971   tmp = HT_REMOVE(cache_map, &cache_root, resolve);
00972   if (tmp != resolve) {
00973     log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
00974             " the cache. Tried to purge %s (%p); instead got %s (%p).",
00975             resolve->address, (void*)resolve,
00976             tmp ? tmp->address : "NULL", (void*)tmp);
00977   }
00978   tor_assert(tmp == resolve);
00979 
00980   resolve->state = CACHE_STATE_DONE;
00981 }
00982 
00988 static void
00989 add_answer_to_cache(const char *address, uint8_t is_reverse, uint32_t addr,
00990                     const char *hostname, char outcome, uint32_t ttl)
00991 {
00992   cached_resolve_t *resolve;
00993   if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
00994     return;
00995 
00996   //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
00997   //           address, is_reverse?"(reverse)":"", (unsigned long)addr,
00998   //           hostname?hostname:"NULL",(int)outcome);
00999 
01000   resolve = tor_malloc_zero(sizeof(cached_resolve_t));
01001   resolve->magic = CACHED_RESOLVE_MAGIC;
01002   resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
01003     CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
01004   strlcpy(resolve->address, address, sizeof(resolve->address));
01005   resolve->is_reverse = is_reverse;
01006   if (is_reverse) {
01007     if (outcome == DNS_RESOLVE_SUCCEEDED) {
01008       tor_assert(hostname);
01009       resolve->result.hostname = tor_strdup(hostname);
01010     } else {
01011       tor_assert(! hostname);
01012       resolve->result.hostname = NULL;
01013     }
01014   } else {
01015     tor_assert(!hostname);
01016     resolve->result.a.addr = addr;
01017   }
01018   resolve->ttl = ttl;
01019   assert_resolve_ok(resolve);
01020   HT_INSERT(cache_map, &cache_root, resolve);
01021   set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
01022 }
01023 
01026 static INLINE int
01027 is_test_address(const char *address)
01028 {
01029   const or_options_t *options = get_options();
01030   return options->ServerDNSTestAddresses &&
01031     smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
01032 }
01033 
01041 static void
01042 dns_found_answer(const char *address, uint8_t is_reverse, uint32_t addr,
01043                  const char *hostname, char outcome, uint32_t ttl)
01044 {
01045   pending_connection_t *pend;
01046   cached_resolve_t search;
01047   cached_resolve_t *resolve, *removed;
01048   edge_connection_t *pendconn;
01049   circuit_t *circ;
01050 
01051   assert_cache_ok();
01052 
01053   strlcpy(search.address, address, sizeof(search.address));
01054 
01055   resolve = HT_FIND(cache_map, &cache_root, &search);
01056   if (!resolve) {
01057     int is_test_addr = is_test_address(address);
01058     if (!is_test_addr)
01059       log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
01060                escaped_safe_str(address));
01061     add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
01062     return;
01063   }
01064   assert_resolve_ok(resolve);
01065 
01066   if (resolve->state != CACHE_STATE_PENDING) {
01067     /* XXXX Maybe update addr? or check addr for consistency? Or let
01068      * VALID replace FAILED? */
01069     int is_test_addr = is_test_address(address);
01070     if (!is_test_addr)
01071       log_notice(LD_EXIT,
01072                  "Resolved %s which was already resolved; ignoring",
01073                  escaped_safe_str(address));
01074     tor_assert(resolve->pending_connections == NULL);
01075     return;
01076   }
01077   /* Removed this assertion: in fact, we'll sometimes get a double answer
01078    * to the same question.  This can happen when we ask one worker to resolve
01079    * X.Y.Z., then we cancel the request, and then we ask another worker to
01080    * resolve X.Y.Z. */
01081   /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
01082 
01083   while (resolve->pending_connections) {
01084     pend = resolve->pending_connections;
01085     pendconn = pend->conn; /* don't pass complex things to the
01086                               connection_mark_for_close macro */
01087     assert_connection_ok(TO_CONN(pendconn),time(NULL));
01088     tor_addr_from_ipv4h(&pendconn->_base.addr, addr);
01089     pendconn->address_ttl = ttl;
01090 
01091     if (outcome != DNS_RESOLVE_SUCCEEDED) {
01092       /* prevent double-remove. */
01093       pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
01094       if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
01095         connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
01096         /* This detach must happen after we send the end cell. */
01097         circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
01098       } else {
01099         send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
01100                           RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
01101         /* This detach must happen after we send the resolved cell. */
01102         circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
01103       }
01104       connection_free(TO_CONN(pendconn));
01105     } else {
01106       if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
01107         tor_assert(!is_reverse);
01108         /* prevent double-remove. */
01109         pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
01110 
01111         circ = circuit_get_by_edge_conn(pend->conn);
01112         tor_assert(circ);
01113         tor_assert(!CIRCUIT_IS_ORIGIN(circ));
01114         /* unlink pend->conn from resolving_streams, */
01115         circuit_detach_stream(circ, pend->conn);
01116         /* and link it to n_streams */
01117         pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
01118         pend->conn->on_circuit = circ;
01119         TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
01120 
01121         connection_exit_connect(pend->conn);
01122       } else {
01123         /* prevent double-remove.  This isn't really an accurate state,
01124          * but it does the right thing. */
01125         pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
01126         if (is_reverse)
01127           send_resolved_hostname_cell(pendconn, hostname);
01128         else
01129           send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
01130         circ = circuit_get_by_edge_conn(pendconn);
01131         tor_assert(circ);
01132         circuit_detach_stream(circ, pendconn);
01133         connection_free(TO_CONN(pendconn));
01134       }
01135     }
01136     resolve->pending_connections = pend->next;
01137     tor_free(pend);
01138   }
01139 
01140   resolve->state = CACHE_STATE_DONE;
01141   removed = HT_REMOVE(cache_map, &cache_root, &search);
01142   if (removed != resolve) {
01143     log_err(LD_BUG, "The pending resolve we found wasn't removable from"
01144             " the cache. Tried to purge %s (%p); instead got %s (%p).",
01145             resolve->address, (void*)resolve,
01146             removed ? removed->address : "NULL", (void*)removed);
01147   }
01148   assert_resolve_ok(resolve);
01149   assert_cache_ok();
01150 
01151   add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
01152   assert_cache_ok();
01153 }
01154 
01157 static int
01158 evdns_err_is_transient(int err)
01159 {
01160   switch (err)
01161   {
01162     case DNS_ERR_SERVERFAILED:
01163     case DNS_ERR_TRUNCATED:
01164     case DNS_ERR_TIMEOUT:
01165       return 1;
01166     default:
01167       return 0;
01168   }
01169 }
01170 
01177 static int
01178 configure_nameservers(int force)
01179 {
01180   const or_options_t *options;
01181   const char *conf_fname;
01182   struct stat st;
01183   int r;
01184   options = get_options();
01185   conf_fname = options->ServerDNSResolvConfFile;
01186 #ifndef _WIN32
01187   if (!conf_fname)
01188     conf_fname = "/etc/resolv.conf";
01189 #endif
01190 
01191   if (!the_evdns_base) {
01192     if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
01193       log_err(LD_BUG, "Couldn't create an evdns_base");
01194       return -1;
01195     }
01196   }
01197 
01198 #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
01199   if (options->OutboundBindAddress) {
01200     tor_addr_t addr;
01201     if (tor_addr_parse(&addr, options->OutboundBindAddress) < 0) {
01202       log_warn(LD_CONFIG,"Outbound bind address '%s' didn't parse. Ignoring.",
01203                options->OutboundBindAddress);
01204     } else {
01205       int socklen;
01206       struct sockaddr_storage ss;
01207       socklen = tor_addr_to_sockaddr(&addr, 0,
01208                                      (struct sockaddr *)&ss, sizeof(ss));
01209       if (socklen <= 0) {
01210         log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
01211                  " Ignoring.");
01212       } else {
01213         evdns_base_set_default_outgoing_bind_address(the_evdns_base,
01214                                                      (struct sockaddr *)&ss,
01215                                                      socklen);
01216       }
01217     }
01218   }
01219 #endif
01220 
01221   evdns_set_log_fn(evdns_log_cb);
01222   if (conf_fname) {
01223     if (stat(conf_fname, &st)) {
01224       log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
01225                conf_fname, strerror(errno));
01226       goto err;
01227     }
01228     if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
01229         && st.st_mtime == resolv_conf_mtime) {
01230       log_info(LD_EXIT, "No change to '%s'", conf_fname);
01231       return 0;
01232     }
01233     if (nameservers_configured) {
01234       evdns_base_search_clear(the_evdns_base);
01235       evdns_base_clear_nameservers_and_suspend(the_evdns_base);
01236     }
01237     log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
01238     if ((r = evdns_base_resolv_conf_parse(the_evdns_base,
01239                                           DNS_OPTIONS_ALL, conf_fname))) {
01240       log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
01241                conf_fname, conf_fname, r);
01242       goto err;
01243     }
01244     if (evdns_base_count_nameservers(the_evdns_base) == 0) {
01245       log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
01246       goto err;
01247     }
01248     tor_free(resolv_conf_fname);
01249     resolv_conf_fname = tor_strdup(conf_fname);
01250     resolv_conf_mtime = st.st_mtime;
01251     if (nameservers_configured)
01252       evdns_base_resume(the_evdns_base);
01253   }
01254 #ifdef _WIN32
01255   else {
01256     if (nameservers_configured) {
01257       evdns_base_search_clear(the_evdns_base);
01258       evdns_base_clear_nameservers_and_suspend(the_evdns_base);
01259     }
01260     if (evdns_base_config_windows_nameservers(the_evdns_base))  {
01261       log_warn(LD_EXIT,"Could not config nameservers.");
01262       goto err;
01263     }
01264     if (evdns_base_count_nameservers(the_evdns_base) == 0) {
01265       log_warn(LD_EXIT, "Unable to find any platform nameservers in "
01266                "your Windows configuration.");
01267       goto err;
01268     }
01269     if (nameservers_configured)
01270       evdns_base_resume(the_evdns_base);
01271     tor_free(resolv_conf_fname);
01272     resolv_conf_mtime = 0;
01273   }
01274 #endif
01275 
01276 #define SET(k,v)  evdns_base_set_option_(the_evdns_base, (k), (v))
01277 
01278   if (evdns_base_count_nameservers(the_evdns_base) == 1) {
01279     SET("max-timeouts:", "16");
01280     SET("timeout:", "10");
01281   } else {
01282     SET("max-timeouts:", "3");
01283     SET("timeout:", "5");
01284   }
01285 
01286   if (options->ServerDNSRandomizeCase)
01287     SET("randomize-case:", "1");
01288   else
01289     SET("randomize-case:", "0");
01290 
01291 #undef SET
01292 
01293   dns_servers_relaunch_checks();
01294 
01295   nameservers_configured = 1;
01296   if (nameserver_config_failed) {
01297     nameserver_config_failed = 0;
01298     /* XXX the three calls to republish the descriptor might be producing
01299      * descriptors that are only cosmetically different, especially on
01300      * non-exit relays! -RD */
01301     mark_my_descriptor_dirty("dns resolvers back");
01302   }
01303   return 0;
01304  err:
01305   nameservers_configured = 0;
01306   if (! nameserver_config_failed) {
01307     nameserver_config_failed = 1;
01308     mark_my_descriptor_dirty("dns resolvers failed");
01309   }
01310   return -1;
01311 }
01312 
01316 static void
01317 evdns_callback(int result, char type, int count, int ttl, void *addresses,
01318                void *arg)
01319 {
01320   char *string_address = arg;
01321   uint8_t is_reverse = 0;
01322   int status = DNS_RESOLVE_FAILED_PERMANENT;
01323   uint32_t addr = 0;
01324   const char *hostname = NULL;
01325   int was_wildcarded = 0;
01326 
01327   if (result == DNS_ERR_NONE) {
01328     if (type == DNS_IPv4_A && count) {
01329       char answer_buf[INET_NTOA_BUF_LEN+1];
01330       struct in_addr in;
01331       char *escaped_address;
01332       uint32_t *addrs = addresses;
01333       in.s_addr = addrs[0];
01334       addr = ntohl(addrs[0]);
01335       status = DNS_RESOLVE_SUCCEEDED;
01336       tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
01337       escaped_address = esc_for_log(string_address);
01338 
01339       if (answer_is_wildcarded(answer_buf)) {
01340         log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
01341                   "address %s; treating as a failure.",
01342                   safe_str(escaped_address),
01343                   escaped_safe_str(answer_buf));
01344         was_wildcarded = 1;
01345         addr = 0;
01346         status = DNS_RESOLVE_FAILED_PERMANENT;
01347       } else {
01348         log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
01349                   safe_str(escaped_address),
01350                   escaped_safe_str(answer_buf));
01351       }
01352       tor_free(escaped_address);
01353     } else if (type == DNS_PTR && count) {
01354       char *escaped_address;
01355       is_reverse = 1;
01356       hostname = ((char**)addresses)[0];
01357       status = DNS_RESOLVE_SUCCEEDED;
01358       escaped_address = esc_for_log(string_address);
01359       log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
01360                 safe_str(escaped_address),
01361                 escaped_safe_str(hostname));
01362       tor_free(escaped_address);
01363     } else if (count) {
01364       log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
01365                escaped_safe_str(string_address));
01366     } else {
01367       log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
01368                escaped_safe_str(string_address));
01369     }
01370   } else {
01371     if (evdns_err_is_transient(result))
01372       status = DNS_RESOLVE_FAILED_TRANSIENT;
01373   }
01374   if (was_wildcarded) {
01375     if (is_test_address(string_address)) {
01376       /* Ick.  We're getting redirected on known-good addresses.  Our DNS
01377        * server must really hate us.  */
01378       add_wildcarded_test_address(string_address);
01379     }
01380   }
01381   if (result != DNS_ERR_SHUTDOWN)
01382     dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
01383   tor_free(string_address);
01384 }
01385 
01389 static int
01390 launch_resolve(edge_connection_t *exitconn)
01391 {
01392   char *addr;
01393   struct evdns_request *req = NULL;
01394   tor_addr_t a;
01395   int r;
01396   int options = get_options()->ServerDNSSearchDomains ? 0
01397     : DNS_QUERY_NO_SEARCH;
01398 
01399   if (get_options()->DisableNetwork)
01400     return -1;
01401 
01402   /* What? Nameservers not configured?  Sounds like a bug. */
01403   if (!nameservers_configured) {
01404     log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
01405              "launched.  Configuring.");
01406     if (configure_nameservers(1) < 0) {
01407       return -1;
01408     }
01409   }
01410 
01411   addr = tor_strdup(exitconn->_base.address);
01412 
01413   r = tor_addr_parse_PTR_name(
01414                             &a, exitconn->_base.address, AF_UNSPEC, 0);
01415 
01416   tor_assert(the_evdns_base);
01417   if (r == 0) {
01418     log_info(LD_EXIT, "Launching eventdns request for %s",
01419              escaped_safe_str(exitconn->_base.address));
01420     req = evdns_base_resolve_ipv4(the_evdns_base,
01421                                 exitconn->_base.address, options,
01422                                 evdns_callback, addr);
01423   } else if (r == 1) {
01424     log_info(LD_EXIT, "Launching eventdns reverse request for %s",
01425              escaped_safe_str(exitconn->_base.address));
01426     if (tor_addr_family(&a) == AF_INET)
01427       req = evdns_base_resolve_reverse(the_evdns_base,
01428                                 tor_addr_to_in(&a), DNS_QUERY_NO_SEARCH,
01429                                 evdns_callback, addr);
01430     else
01431       req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
01432                                      tor_addr_to_in6(&a), DNS_QUERY_NO_SEARCH,
01433                                      evdns_callback, addr);
01434   } else if (r == -1) {
01435     log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
01436   }
01437 
01438   r = 0;
01439   if (!req) {
01440     log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
01441              escaped_safe_str(addr));
01442     r = -1;
01443     tor_free(addr); /* There is no evdns request in progress; stop
01444                      * addr from getting leaked. */
01445   }
01446   return r;
01447 }
01448 
01450 static int n_wildcard_requests = 0;
01451 
01456 static strmap_t *dns_wildcard_response_count = NULL;
01457 
01461 static smartlist_t *dns_wildcard_list = NULL;
01464 static int dns_wildcard_one_notice_given = 0;
01467 static int dns_wildcard_notice_given = 0;
01468 
01471 static smartlist_t *dns_wildcarded_test_address_list = NULL;
01473 static int dns_wildcarded_test_address_notice_given = 0;
01475 static int dns_is_completely_invalid = 0;
01476 
01479 static void
01480 wildcard_increment_answer(const char *id)
01481 {
01482   int *ip;
01483   if (!dns_wildcard_response_count)
01484     dns_wildcard_response_count = strmap_new();
01485 
01486   ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
01487   if (!ip) {
01488     ip = tor_malloc_zero(sizeof(int));
01489     strmap_set(dns_wildcard_response_count, id, ip);
01490   }
01491   ++*ip;
01492 
01493   if (*ip > 5 && n_wildcard_requests > 10) {
01494     if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
01495     if (!smartlist_string_isin(dns_wildcard_list, id)) {
01496     log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
01497         "Your DNS provider has given \"%s\" as an answer for %d different "
01498         "invalid addresses. Apparently they are hijacking DNS failures. "
01499         "I'll try to correct for this by treating future occurrences of "
01500         "\"%s\" as 'not found'.", id, *ip, id);
01501       smartlist_add(dns_wildcard_list, tor_strdup(id));
01502     }
01503     if (!dns_wildcard_notice_given)
01504       control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
01505     dns_wildcard_notice_given = 1;
01506   }
01507 }
01508 
01511 static void
01512 add_wildcarded_test_address(const char *address)
01513 {
01514   int n, n_test_addrs;
01515   if (!dns_wildcarded_test_address_list)
01516     dns_wildcarded_test_address_list = smartlist_new();
01517 
01518   if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
01519     return;
01520 
01521   n_test_addrs = get_options()->ServerDNSTestAddresses ?
01522     smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
01523 
01524   smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
01525   n = smartlist_len(dns_wildcarded_test_address_list);
01526   if (n > n_test_addrs/2) {
01527     log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
01528         LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
01529         "address.  It has done this with %d test addresses so far.  I'm "
01530         "going to stop being an exit node for now, since our DNS seems so "
01531         "broken.", address, n);
01532     if (!dns_is_completely_invalid) {
01533       dns_is_completely_invalid = 1;
01534       mark_my_descriptor_dirty("dns hijacking confirmed");
01535     }
01536     if (!dns_wildcarded_test_address_notice_given)
01537       control_event_server_status(LOG_WARN, "DNS_USELESS");
01538     dns_wildcarded_test_address_notice_given = 1;
01539   }
01540 }
01541 
01544 static void
01545 evdns_wildcard_check_callback(int result, char type, int count, int ttl,
01546                               void *addresses, void *arg)
01547 {
01548   (void)ttl;
01549   ++n_wildcard_requests;
01550   if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
01551     uint32_t *addrs = addresses;
01552     int i;
01553     char *string_address = arg;
01554     for (i = 0; i < count; ++i) {
01555       char answer_buf[INET_NTOA_BUF_LEN+1];
01556       struct in_addr in;
01557       in.s_addr = addrs[i];
01558       tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
01559       wildcard_increment_answer(answer_buf);
01560     }
01561     log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
01562         "Your DNS provider gave an answer for \"%s\", which "
01563         "is not supposed to exist. Apparently they are hijacking "
01564         "DNS failures. Trying to correct for this. We've noticed %d "
01565         "possibly bad address%s so far.",
01566         string_address, strmap_size(dns_wildcard_response_count),
01567         (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
01568     dns_wildcard_one_notice_given = 1;
01569   }
01570   tor_free(arg);
01571 }
01572 
01576 static void
01577 launch_wildcard_check(int min_len, int max_len, const char *suffix)
01578 {
01579   char *addr;
01580   struct evdns_request *req;
01581 
01582   addr = crypto_random_hostname(min_len, max_len, "", suffix);
01583   log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
01584            "domains with request for bogus hostname \"%s\"", addr);
01585 
01586   tor_assert(the_evdns_base);
01587   req = evdns_base_resolve_ipv4(
01588                          the_evdns_base,
01589                          /* This "addr" tells us which address to resolve */
01590                          addr,
01591                          DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
01592                          /* This "addr" is an argument to the callback*/ addr);
01593   if (!req) {
01594     /* There is no evdns request in progress; stop addr from getting leaked */
01595     tor_free(addr);
01596   }
01597 }
01598 
01601 static void
01602 launch_test_addresses(int fd, short event, void *args)
01603 {
01604   const or_options_t *options = get_options();
01605   struct evdns_request *req;
01606   (void)fd;
01607   (void)event;
01608   (void)args;
01609 
01610   if (options->DisableNetwork)
01611     return;
01612 
01613   log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
01614            "hijack *everything*.");
01615   /* This situation is worse than the failure-hijacking situation.  When this
01616    * happens, we're no good for DNS requests at all, and we shouldn't really
01617    * be an exit server.*/
01618   if (!options->ServerDNSTestAddresses)
01619     return;
01620   tor_assert(the_evdns_base);
01621   SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
01622                           const char *, address) {
01623     char *a = tor_strdup(address);
01624     req = evdns_base_resolve_ipv4(the_evdns_base,
01625                               address, DNS_QUERY_NO_SEARCH, evdns_callback, a);
01626 
01627     if (!req) {
01628       log_info(LD_EXIT, "eventdns rejected test address %s",
01629                escaped_safe_str(address));
01630       tor_free(a);
01631     }
01632   } SMARTLIST_FOREACH_END(address);
01633 }
01634 
01635 #define N_WILDCARD_CHECKS 2
01636 
01641 static void
01642 dns_launch_wildcard_checks(void)
01643 {
01644   int i;
01645   log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
01646            "to hijack DNS failures.");
01647   for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
01648     /* RFC2606 reserves these.  Sadly, some DNS hijackers, in a silly attempt
01649      * to 'comply' with rfc2606, refrain from giving A records for these.
01650      * This is the standards-compliance equivalent of making sure that your
01651      * crackhouse's elevator inspection certificate is up to date.
01652      */
01653     launch_wildcard_check(2, 16, ".invalid");
01654     launch_wildcard_check(2, 16, ".test");
01655 
01656     /* These will break specs if there are ever any number of
01657      * 8+-character top-level domains. */
01658     launch_wildcard_check(8, 16, "");
01659 
01660     /* Try some random .com/org/net domains. This will work fine so long as
01661      * not too many resolve to the same place. */
01662     launch_wildcard_check(8, 16, ".com");
01663     launch_wildcard_check(8, 16, ".org");
01664     launch_wildcard_check(8, 16, ".net");
01665   }
01666 }
01667 
01670 void
01671 dns_launch_correctness_checks(void)
01672 {
01673   static struct event *launch_event = NULL;
01674   struct timeval timeout;
01675   if (!get_options()->ServerDNSDetectHijacking)
01676     return;
01677   dns_launch_wildcard_checks();
01678 
01679   /* Wait a while before launching requests for test addresses, so we can
01680    * get the results from checking for wildcarding. */
01681   if (! launch_event)
01682     launch_event = tor_evtimer_new(tor_libevent_get_base(),
01683                                    launch_test_addresses, NULL);
01684   timeout.tv_sec = 30;
01685   timeout.tv_usec = 0;
01686   if (evtimer_add(launch_event, &timeout)<0) {
01687     log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
01688   }
01689 }
01690 
01692 int
01693 dns_seems_to_be_broken(void)
01694 {
01695   return dns_is_completely_invalid;
01696 }
01697 
01699 void
01700 dns_reset_correctness_checks(void)
01701 {
01702   strmap_free(dns_wildcard_response_count, _tor_free);
01703   dns_wildcard_response_count = NULL;
01704 
01705   n_wildcard_requests = 0;
01706 
01707   if (dns_wildcard_list) {
01708     SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
01709     smartlist_clear(dns_wildcard_list);
01710   }
01711   if (dns_wildcarded_test_address_list) {
01712     SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
01713                       tor_free(cp));
01714     smartlist_clear(dns_wildcarded_test_address_list);
01715   }
01716   dns_wildcard_one_notice_given = dns_wildcard_notice_given =
01717     dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
01718 }
01719 
01722 static int
01723 answer_is_wildcarded(const char *ip)
01724 {
01725   return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
01726 }
01727 
01729 static void
01730 assert_resolve_ok(cached_resolve_t *resolve)
01731 {
01732   tor_assert(resolve);
01733   tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
01734   tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
01735   tor_assert(tor_strisnonupper(resolve->address));
01736   if (resolve->state != CACHE_STATE_PENDING) {
01737     tor_assert(!resolve->pending_connections);
01738   }
01739   if (resolve->state == CACHE_STATE_PENDING ||
01740       resolve->state == CACHE_STATE_DONE) {
01741     tor_assert(!resolve->ttl);
01742     if (resolve->is_reverse)
01743       tor_assert(!resolve->result.hostname);
01744     else
01745       tor_assert(!resolve->result.a.addr);
01746   }
01747 }
01748 
01750 static int
01751 dns_cache_entry_count(void)
01752 {
01753    return HT_SIZE(&cache_root);
01754 }
01755 
01757 void
01758 dump_dns_mem_usage(int severity)
01759 {
01760   /* This should never be larger than INT_MAX. */
01761   int hash_count = dns_cache_entry_count();
01762   size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
01763   hash_mem += HT_MEM_USAGE(&cache_root);
01764 
01765   /* Print out the count and estimated size of our &cache_root.  It undercounts
01766      hostnames in cached reverse resolves.
01767    */
01768   log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
01769   log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
01770       (unsigned)hash_mem);
01771 }
01772 
01773 #ifdef DEBUG_DNS_CACHE
01774 
01775 static void
01776 _assert_cache_ok(void)
01777 {
01778   cached_resolve_t **resolve;
01779   int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
01780   if (bad_rep) {
01781     log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
01782     tor_assert(!bad_rep);
01783   }
01784 
01785   HT_FOREACH(resolve, cache_map, &cache_root) {
01786     assert_resolve_ok(*resolve);
01787     tor_assert((*resolve)->state != CACHE_STATE_DONE);
01788   }
01789   if (!cached_resolve_pqueue)
01790     return;
01791 
01792   smartlist_pqueue_assert_ok(cached_resolve_pqueue,
01793                              _compare_cached_resolves_by_expiry,
01794                              STRUCT_OFFSET(cached_resolve_t, minheap_idx));
01795 
01796   SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
01797     {
01798       if (res->state == CACHE_STATE_DONE) {
01799         cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
01800         tor_assert(!found || found != res);
01801       } else {
01802         cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
01803         tor_assert(found);
01804       }
01805     });
01806 }
01807 #endif
01808