dns.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char dns_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file dns.c
  10. * \brief Implements a local cache for DNS results for Tor servers.
  11. * This is implemented as a wrapper around Adam Langley's eventdns.c code.
  12. * (We can't just use gethostbyname() and friends because we really need to
  13. * be nonblocking.)
  14. **/
  15. #include "or.h"
  16. #include "ht.h"
  17. #include "eventdns.h"
  18. /** Longest hostname we're willing to resolve. */
  19. #define MAX_ADDRESSLEN 256
  20. /** How long will we wait for an answer from the resolver before we decide
  21. * that the resolver is wedged? */
  22. #define RESOLVE_MAX_TIMEOUT 300
  23. /** Possible outcomes from hostname lookup: permanent failure,
  24. * transient (retryable) failure, and success. */
  25. #define DNS_RESOLVE_FAILED_TRANSIENT 1
  26. #define DNS_RESOLVE_FAILED_PERMANENT 2
  27. #define DNS_RESOLVE_SUCCEEDED 3
  28. /** Have we currently configured nameservers with eventdns? */
  29. static int nameservers_configured = 0;
  30. /** Did our most recent attempt to configure nameservers with eventdns fail? */
  31. static int nameserver_config_failed = 0;
  32. /** What was the resolv_conf fname we last used when configuring the
  33. * nameservers? Used to check whether we need to reconfigure. */
  34. static char *resolv_conf_fname = NULL;
  35. /** What was the mtime on the resolv.conf file we last used when configuring
  36. * the nameservers? Used to check whether we need to reconfigure. */
  37. static time_t resolv_conf_mtime = 0;
  38. /** Linked list of connections waiting for a DNS answer. */
  39. typedef struct pending_connection_t {
  40. edge_connection_t *conn;
  41. struct pending_connection_t *next;
  42. } pending_connection_t;
  43. /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
  44. * pointers and memory stomping. */
  45. #define CACHED_RESOLVE_MAGIC 0x1234F00D
  46. /* Possible states for a cached resolve_t */
  47. /** We are waiting for the resolver system to tell us an answer here.
  48. * When we get one, or when we time out, the state of this cached_resolve_t
  49. * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
  50. * entry. This cached_resolve_t will be in the hash table so that we will
  51. * know not to launch more requests for this addr, but rather to add more
  52. * connections to the pending list for the addr. */
  53. #define CACHE_STATE_PENDING 0
  54. /** This used to be a pending cached_resolve_t, and we got an answer for it.
  55. * Now we're waiting for this cached_resolve_t to expire. This should
  56. * have no pending connections, and should not appear in the hash table. */
  57. #define CACHE_STATE_DONE 1
  58. /** We are caching an answer for this address. This should have no pending
  59. * connections, and should appear in the hash table. */
  60. #define CACHE_STATE_CACHED_VALID 2
  61. /** We are caching a failure for this address. This should have no pending
  62. * connections, and should appear in the hash table */
  63. #define CACHE_STATE_CACHED_FAILED 3
  64. /** A DNS request: possibly completed, possibly pending; cached_resolve
  65. * structs are stored at the OR side in a hash table, and as a linked
  66. * list from oldest to newest.
  67. */
  68. typedef struct cached_resolve_t {
  69. HT_ENTRY(cached_resolve_t) node;
  70. uint32_t magic;
  71. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  72. union {
  73. struct {
  74. struct in6_addr addr6; /**< IPv6 addr for <b>address</b>. */
  75. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  76. } a;
  77. char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
  78. } result;
  79. uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
  80. uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
  81. time_t expire; /**< Remove items from cache after this time. */
  82. uint32_t ttl; /**< What TTL did the nameserver tell us? */
  83. /** Connections that want to know when we get an answer for this resolve. */
  84. pending_connection_t *pending_connections;
  85. } cached_resolve_t;
  86. static void purge_expired_resolves(time_t now);
  87. static void dns_found_answer(const char *address, uint8_t is_reverse,
  88. uint32_t addr, const char *hostname, char outcome,
  89. uint32_t ttl);
  90. static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
  91. static int launch_resolve(edge_connection_t *exitconn);
  92. static void add_wildcarded_test_address(const char *address);
  93. static int configure_nameservers(int force);
  94. static int answer_is_wildcarded(const char *ip);
  95. static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
  96. or_circuit_t *oncirc, char **resolved_to_hostname);
  97. #ifdef DEBUG_DNS_CACHE
  98. static void _assert_cache_ok(void);
  99. #define assert_cache_ok() _assert_cache_ok()
  100. #else
  101. #define assert_cache_ok() STMT_NIL
  102. #endif
  103. static void assert_resolve_ok(cached_resolve_t *resolve);
  104. /** Hash table of cached_resolve objects. */
  105. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  106. /** Function to compare hashed resolves on their addresses; used to
  107. * implement hash tables. */
  108. static INLINE int
  109. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  110. {
  111. /* make this smarter one day? */
  112. assert_resolve_ok(a); // Not b; b may be just a search.
  113. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  114. }
  115. /** Hash function for cached_resolve objects */
  116. static INLINE unsigned int
  117. cached_resolve_hash(cached_resolve_t *a)
  118. {
  119. return ht_string_hash(a->address);
  120. }
  121. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  122. cached_resolves_eq)
  123. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  124. cached_resolves_eq, 0.6, malloc, realloc, free)
  125. /** Initialize the DNS cache. */
  126. static void
  127. init_cache_map(void)
  128. {
  129. HT_INIT(cache_map, &cache_root);
  130. }
  131. /** Helper: called by eventdns when eventdns wants to log something. */
  132. static void
  133. evdns_log_cb(int warn, const char *msg)
  134. {
  135. const char *cp;
  136. static int all_down = 0;
  137. int severity = warn ? LOG_WARN : LOG_INFO;
  138. if (!strcmpstart(msg, "Resolve requested for") &&
  139. get_options()->SafeLogging) {
  140. log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
  141. return;
  142. } else if (!strcmpstart(msg, "Search: ")) {
  143. return;
  144. }
  145. if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
  146. char *ns = tor_strndup(msg+11, cp-(msg+11));
  147. const char *err = strchr(cp, ':')+2;
  148. tor_assert(err);
  149. /* Don't warn about a single failed nameserver; we'll warn with 'all
  150. * nameservers have failed' if we're completely out of nameservers;
  151. * otherwise, the situation is tolerable. */
  152. severity = LOG_INFO;
  153. control_event_server_status(LOG_NOTICE,
  154. "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
  155. ns, escaped(err));
  156. tor_free(ns);
  157. } else if (!strcmpstart(msg, "Nameserver ") &&
  158. (cp=strstr(msg, " is back up"))) {
  159. char *ns = tor_strndup(msg+11, cp-(msg+11));
  160. severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
  161. all_down = 0;
  162. control_event_server_status(LOG_NOTICE,
  163. "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
  164. tor_free(ns);
  165. } else if (!strcmp(msg, "All nameservers have failed")) {
  166. control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
  167. all_down = 1;
  168. }
  169. log(severity, LD_EXIT, "eventdns: %s", msg);
  170. }
  171. static void
  172. randfn(char *b, size_t n)
  173. {
  174. crypto_rand(b,n);
  175. }
  176. /** Initialize the DNS subsystem; called by the OR process. */
  177. int
  178. dns_init(void)
  179. {
  180. init_cache_map();
  181. evdns_set_random_bytes_fn(randfn);
  182. if (get_options()->ServerDNSRandomizeCase)
  183. evdns_set_option("randomize-case", "1", DNS_OPTIONS_ALL);
  184. else
  185. evdns_set_option("randomize-case", "0", DNS_OPTIONS_ALL);
  186. if (server_mode(get_options())) {
  187. int r = configure_nameservers(1);
  188. return r;
  189. }
  190. return 0;
  191. }
  192. /** Called when DNS-related options change (or may have changed). Returns -1
  193. * on failure, 0 on success. */
  194. int
  195. dns_reset(void)
  196. {
  197. or_options_t *options = get_options();
  198. if (! server_mode(options)) {
  199. evdns_clear_nameservers_and_suspend();
  200. evdns_search_clear();
  201. nameservers_configured = 0;
  202. tor_free(resolv_conf_fname);
  203. resolv_conf_mtime = 0;
  204. } else {
  205. if (configure_nameservers(0) < 0) {
  206. return -1;
  207. }
  208. }
  209. return 0;
  210. }
  211. /** Return true iff the most recent attempt to initialize the DNS subsystem
  212. * failed. */
  213. int
  214. has_dns_init_failed(void)
  215. {
  216. return nameserver_config_failed;
  217. }
  218. /** Helper: Given a TTL from a DNS response, determine what TTL to give the
  219. * OP that asked us to resolve it. */
  220. uint32_t
  221. dns_clip_ttl(uint32_t ttl)
  222. {
  223. if (ttl < MIN_DNS_TTL)
  224. return MIN_DNS_TTL;
  225. else if (ttl > MAX_DNS_TTL)
  226. return MAX_DNS_TTL;
  227. else
  228. return ttl;
  229. }
  230. /** Helper: Given a TTL from a DNS response, determine how long to hold it in
  231. * our cache. */
  232. static uint32_t
  233. dns_get_expiry_ttl(uint32_t ttl)
  234. {
  235. if (ttl < MIN_DNS_TTL)
  236. return MIN_DNS_TTL;
  237. else if (ttl > MAX_DNS_ENTRY_AGE)
  238. return MAX_DNS_ENTRY_AGE;
  239. else
  240. return ttl;
  241. }
  242. /** Helper: free storage held by an entry in the DNS cache. */
  243. static void
  244. _free_cached_resolve(cached_resolve_t *r)
  245. {
  246. while (r->pending_connections) {
  247. pending_connection_t *victim = r->pending_connections;
  248. r->pending_connections = victim->next;
  249. tor_free(victim);
  250. }
  251. if (r->is_reverse)
  252. tor_free(r->result.hostname);
  253. r->magic = 0xFF00FF00;
  254. tor_free(r);
  255. }
  256. /** Compare two cached_resolve_t pointers by expiry time, and return
  257. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  258. * the priority queue implementation. */
  259. static int
  260. _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
  261. {
  262. const cached_resolve_t *a = _a, *b = _b;
  263. if (a->expire < b->expire)
  264. return -1;
  265. else if (a->expire == b->expire)
  266. return 0;
  267. else
  268. return 1;
  269. }
  270. /** Priority queue of cached_resolve_t objects to let us know when they
  271. * will expire. */
  272. static smartlist_t *cached_resolve_pqueue = NULL;
  273. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  274. * priority queue */
  275. static void
  276. set_expiry(cached_resolve_t *resolve, time_t expires)
  277. {
  278. tor_assert(resolve && resolve->expire == 0);
  279. if (!cached_resolve_pqueue)
  280. cached_resolve_pqueue = smartlist_create();
  281. resolve->expire = expires;
  282. smartlist_pqueue_add(cached_resolve_pqueue,
  283. _compare_cached_resolves_by_expiry,
  284. resolve);
  285. }
  286. /** Free all storage held in the DNS cache and related structures. */
  287. void
  288. dns_free_all(void)
  289. {
  290. cached_resolve_t **ptr, **next, *item;
  291. assert_cache_ok();
  292. if (cached_resolve_pqueue) {
  293. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  294. {
  295. if (res->state == CACHE_STATE_DONE)
  296. _free_cached_resolve(res);
  297. });
  298. }
  299. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  300. item = *ptr;
  301. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  302. _free_cached_resolve(item);
  303. }
  304. HT_CLEAR(cache_map, &cache_root);
  305. if (cached_resolve_pqueue)
  306. smartlist_free(cached_resolve_pqueue);
  307. cached_resolve_pqueue = NULL;
  308. tor_free(resolv_conf_fname);
  309. }
  310. /** Remove every cached_resolve whose <b>expire</b> time is before or
  311. * equal to <b>now</b> from the cache. */
  312. static void
  313. purge_expired_resolves(time_t now)
  314. {
  315. cached_resolve_t *resolve, *removed;
  316. pending_connection_t *pend;
  317. edge_connection_t *pendconn;
  318. assert_cache_ok();
  319. if (!cached_resolve_pqueue)
  320. return;
  321. while (smartlist_len(cached_resolve_pqueue)) {
  322. resolve = smartlist_get(cached_resolve_pqueue, 0);
  323. if (resolve->expire > now)
  324. break;
  325. smartlist_pqueue_pop(cached_resolve_pqueue,
  326. _compare_cached_resolves_by_expiry);
  327. if (resolve->state == CACHE_STATE_PENDING) {
  328. log_debug(LD_EXIT,
  329. "Expiring a dns resolve %s that's still pending. Forgot to "
  330. "cull it? DNS resolve didn't tell us about the timeout?",
  331. escaped_safe_str(resolve->address));
  332. } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
  333. resolve->state == CACHE_STATE_CACHED_FAILED) {
  334. log_debug(LD_EXIT,
  335. "Forgetting old cached resolve (address %s, expires %lu)",
  336. escaped_safe_str(resolve->address),
  337. (unsigned long)resolve->expire);
  338. tor_assert(!resolve->pending_connections);
  339. } else {
  340. tor_assert(resolve->state == CACHE_STATE_DONE);
  341. tor_assert(!resolve->pending_connections);
  342. }
  343. if (resolve->pending_connections) {
  344. log_debug(LD_EXIT,
  345. "Closing pending connections on timed-out DNS resolve!");
  346. tor_fragile_assert();
  347. while (resolve->pending_connections) {
  348. pend = resolve->pending_connections;
  349. resolve->pending_connections = pend->next;
  350. /* Connections should only be pending if they have no socket. */
  351. tor_assert(pend->conn->_base.s == -1);
  352. pendconn = pend->conn;
  353. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
  354. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  355. connection_free(TO_CONN(pendconn));
  356. tor_free(pend);
  357. }
  358. }
  359. if (resolve->state == CACHE_STATE_CACHED_VALID ||
  360. resolve->state == CACHE_STATE_CACHED_FAILED ||
  361. resolve->state == CACHE_STATE_PENDING) {
  362. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  363. if (removed != resolve) {
  364. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  365. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  366. resolve->address, (void*)resolve,
  367. removed ? removed->address : "NULL", (void*)remove);
  368. }
  369. tor_assert(removed == resolve);
  370. } else {
  371. /* This should be in state DONE. Make sure it's not in the cache. */
  372. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  373. tor_assert(tmp != resolve);
  374. }
  375. if (resolve->is_reverse)
  376. tor_free(resolve->result.hostname);
  377. resolve->magic = 0xF0BBF0BB;
  378. tor_free(resolve);
  379. }
  380. assert_cache_ok();
  381. }
  382. /** Send a response to the RESOLVE request of a connection.
  383. * <b>answer_type</b> must be one of
  384. * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
  385. *
  386. * If <b>circ</b> is provided, and we have a cached answer, send the
  387. * answer back along circ; otherwise, send the answer back along
  388. * <b>conn</b>'s attached circuit.
  389. */
  390. static void
  391. send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
  392. {
  393. char buf[RELAY_PAYLOAD_SIZE];
  394. size_t buflen;
  395. uint32_t ttl;
  396. buf[0] = answer_type;
  397. ttl = dns_clip_ttl(conn->address_ttl);
  398. switch (answer_type)
  399. {
  400. case RESOLVED_TYPE_IPV4:
  401. buf[1] = 4;
  402. set_uint32(buf+2, tor_addr_to_ipv4n(&conn->_base.addr));
  403. set_uint32(buf+6, htonl(ttl));
  404. buflen = 10;
  405. break;
  406. /*XXXX IP6 need ipv6 implementation */
  407. case RESOLVED_TYPE_ERROR_TRANSIENT:
  408. case RESOLVED_TYPE_ERROR:
  409. {
  410. const char *errmsg = "Error resolving hostname";
  411. size_t msglen = strlen(errmsg);
  412. buf[1] = msglen;
  413. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  414. set_uint32(buf+2+msglen, htonl(ttl));
  415. buflen = 6+msglen;
  416. break;
  417. }
  418. default:
  419. tor_assert(0);
  420. return;
  421. }
  422. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  423. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  424. }
  425. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  426. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  427. * The answer type will be RESOLVED_HOSTNAME.
  428. *
  429. * If <b>circ</b> is provided, and we have a cached answer, send the
  430. * answer back along circ; otherwise, send the answer back along
  431. * <b>conn</b>'s attached circuit.
  432. */
  433. static void
  434. send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
  435. {
  436. char buf[RELAY_PAYLOAD_SIZE];
  437. size_t buflen;
  438. uint32_t ttl;
  439. size_t namelen = strlen(hostname);
  440. tor_assert(hostname);
  441. tor_assert(namelen < 256);
  442. ttl = dns_clip_ttl(conn->address_ttl);
  443. buf[0] = RESOLVED_TYPE_HOSTNAME;
  444. buf[1] = (uint8_t)namelen;
  445. memcpy(buf+2, hostname, namelen);
  446. set_uint32(buf+2+namelen, htonl(ttl));
  447. buflen = 2+namelen+4;
  448. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  449. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  450. // log_notice(LD_EXIT, "Sent");
  451. }
  452. /** Given a lower-case <b>address</b>, check to see whether it's a
  453. * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
  454. * parse it and place the address in <b>in</b> if present. Return 1 on success;
  455. * 0 if the address is not in in-addr.arpa format, and -1 if the address is
  456. * malformed. */
  457. /* XXXX021 move this to address.c; unify with logic in connection_edge.c */
  458. int
  459. parse_inaddr_arpa_address(const char *address, struct in_addr *in)
  460. {
  461. char buf[INET_NTOA_BUF_LEN];
  462. char *cp;
  463. size_t len;
  464. struct in_addr inaddr;
  465. cp = strstr(address, ".in-addr.arpa");
  466. if (!cp || *(cp+strlen(".in-addr.arpa")))
  467. return 0; /* not an .in-addr.arpa address */
  468. len = cp - address;
  469. if (len >= INET_NTOA_BUF_LEN)
  470. return -1; /* Too long. */
  471. memcpy(buf, address, len);
  472. buf[len] = '\0';
  473. if (tor_inet_aton(buf, &inaddr) == 0)
  474. return -1; /* malformed. */
  475. if (in) {
  476. uint32_t a;
  477. /* reverse the bytes */
  478. a = (uint32_t) ( ((inaddr.s_addr & 0x000000fful) << 24)
  479. |((inaddr.s_addr & 0x0000ff00ul) << 8)
  480. |((inaddr.s_addr & 0x00ff0000ul) >> 8)
  481. |((inaddr.s_addr & 0xff000000ul) >> 24));
  482. inaddr.s_addr = a;
  483. memcpy(in, &inaddr, sizeof(inaddr));
  484. }
  485. return 1;
  486. }
  487. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  488. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  489. * If resolve failed, free exitconn and return -1.
  490. *
  491. * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
  492. * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
  493. * need to send back an END cell, since connection_exit_begin_conn will
  494. * do that for us.)
  495. *
  496. * If we have a cached answer, send the answer back along <b>exitconn</b>'s
  497. * circuit.
  498. *
  499. * Else, if seen before and pending, add conn to the pending list,
  500. * and return 0.
  501. *
  502. * Else, if not seen before, add conn to pending list, hand to
  503. * dns farm, and return 0.
  504. *
  505. * Exitconn's on_circuit field must be set, but exitconn should not
  506. * yet be linked onto the n_streams/resolving_streams list of that circuit.
  507. * On success, link the connection to n_streams if it's an exit connection.
  508. * On "pending", link the connection to resolving streams. Otherwise,
  509. * clear its on_circuit field.
  510. */
  511. int
  512. dns_resolve(edge_connection_t *exitconn)
  513. {
  514. or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
  515. int is_resolve, r;
  516. char *hostname = NULL;
  517. is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
  518. r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname);
  519. switch (r) {
  520. case 1:
  521. /* We got an answer without a lookup -- either the answer was
  522. * cached, or it was obvious (like an IP address). */
  523. if (is_resolve) {
  524. /* Send the answer back right now, and detach. */
  525. if (hostname)
  526. send_resolved_hostname_cell(exitconn, hostname);
  527. else
  528. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  529. exitconn->on_circuit = NULL;
  530. } else {
  531. /* Add to the n_streams list; the calling function will send back a
  532. * connected cell. */
  533. exitconn->next_stream = oncirc->n_streams;
  534. oncirc->n_streams = exitconn;
  535. }
  536. break;
  537. case 0:
  538. /* The request is pending: add the connection into the linked list of
  539. * resolving_streams on this circuit. */
  540. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  541. exitconn->next_stream = oncirc->resolving_streams;
  542. oncirc->resolving_streams = exitconn;
  543. break;
  544. case -2:
  545. case -1:
  546. /* The request failed before it could start: cancel this connection,
  547. * and stop everybody waiting for the same connection. */
  548. if (is_resolve) {
  549. send_resolved_cell(exitconn,
  550. (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  551. }
  552. exitconn->on_circuit = NULL;
  553. dns_cancel_pending_resolve(exitconn->_base.address);
  554. if (!exitconn->_base.marked_for_close) {
  555. connection_free(TO_CONN(exitconn));
  556. // XXX ... and we just leak exitconn otherwise? -RD
  557. // If it's marked for close, it's on closeable_connection_lst in
  558. // main.c. If it's on the closeable list, it will get freed from
  559. // main.c. -NM
  560. // "<armadev> If that's true, there are other bugs around, where we
  561. // don't check if it's marked, and will end up double-freeing."
  562. // On the other hand, I don't know of any actual bugs here, so this
  563. // shouldn't be holding up the rc. -RD
  564. }
  565. break;
  566. default:
  567. tor_assert(0);
  568. }
  569. tor_free(hostname);
  570. return r;
  571. }
  572. /** Helper function for dns_resolve: same functionality, but does not handle:
  573. * - marking connections on error and clearing their on_circuit
  574. * - linking connections to n_streams/resolving_streams,
  575. * - sending resolved cells if we have an answer/error right away,
  576. *
  577. * Return -2 on a transient error. If it's a reverse resolve and it's
  578. * successful, sets *<b>hostname_out</b> to a newly allocated string
  579. * holding the cached reverse DNS value.
  580. */
  581. static int
  582. dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
  583. or_circuit_t *oncirc, char **hostname_out)
  584. {
  585. cached_resolve_t *resolve;
  586. cached_resolve_t search;
  587. pending_connection_t *pending_connection;
  588. routerinfo_t *me;
  589. struct in_addr in;
  590. time_t now = time(NULL);
  591. uint8_t is_reverse = 0;
  592. int r;
  593. assert_connection_ok(TO_CONN(exitconn), 0);
  594. tor_assert(exitconn->_base.s == -1);
  595. assert_cache_ok();
  596. tor_assert(oncirc);
  597. /* first check if exitconn->_base.address is an IP. If so, we already
  598. * know the answer. */
  599. if (tor_inet_aton(exitconn->_base.address, &in) != 0) {
  600. tor_addr_from_ipv4n(&exitconn->_base.addr, in.s_addr);
  601. exitconn->address_ttl = DEFAULT_DNS_TTL;
  602. return 1;
  603. }
  604. /* If we're a non-exit, don't even do DNS lookups. */
  605. if (!(me = router_get_my_routerinfo()) ||
  606. policy_is_reject_star(me->exit_policy)) {
  607. return -1;
  608. }
  609. if (address_is_invalid_destination(exitconn->_base.address, 0)) {
  610. log(LOG_PROTOCOL_WARN, LD_EXIT,
  611. "Rejecting invalid destination address %s",
  612. escaped_safe_str(exitconn->_base.address));
  613. return -1;
  614. }
  615. /* then take this opportunity to see if there are any expired
  616. * resolves in the hash table. */
  617. purge_expired_resolves(now);
  618. /* lower-case exitconn->_base.address, so it's in canonical form */
  619. tor_strlower(exitconn->_base.address);
  620. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  621. * .in-addr.arpa address but this isn't a resolve request, kill the
  622. * connection.
  623. */
  624. if ((r = parse_inaddr_arpa_address(exitconn->_base.address, &in)) != 0) {
  625. if (r == 1) {
  626. is_reverse = 1;
  627. if (is_internal_IP(ntohl(in.s_addr), 0)) /* internal address */
  628. return -1;
  629. }
  630. if (!is_reverse || !is_resolve) {
  631. if (!is_reverse)
  632. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  633. escaped_safe_str(exitconn->_base.address));
  634. else if (!is_resolve)
  635. log_info(LD_EXIT,
  636. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  637. "sending error.",
  638. escaped_safe_str(exitconn->_base.address));
  639. return -1;
  640. }
  641. //log_notice(LD_EXIT, "Looks like an address %s",
  642. //exitconn->_base.address);
  643. }
  644. /* now check the hash table to see if 'address' is already there. */
  645. strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
  646. resolve = HT_FIND(cache_map, &cache_root, &search);
  647. if (resolve && resolve->expire > now) { /* already there */
  648. switch (resolve->state) {
  649. case CACHE_STATE_PENDING:
  650. /* add us to the pending list */
  651. pending_connection = tor_malloc_zero(
  652. sizeof(pending_connection_t));
  653. pending_connection->conn = exitconn;
  654. pending_connection->next = resolve->pending_connections;
  655. resolve->pending_connections = pending_connection;
  656. log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  657. "resolve of %s", exitconn->_base.s,
  658. escaped_safe_str(exitconn->_base.address));
  659. return 0;
  660. case CACHE_STATE_CACHED_VALID:
  661. log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
  662. exitconn->_base.s,
  663. escaped_safe_str(resolve->address));
  664. exitconn->address_ttl = resolve->ttl;
  665. if (resolve->is_reverse) {
  666. tor_assert(is_resolve);
  667. *hostname_out = tor_strdup(resolve->result.hostname);
  668. } else {
  669. tor_addr_from_ipv4h(&exitconn->_base.addr, resolve->result.a.addr);
  670. }
  671. return 1;
  672. case CACHE_STATE_CACHED_FAILED:
  673. log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
  674. exitconn->_base.s,
  675. escaped_safe_str(exitconn->_base.address));
  676. return -1;
  677. case CACHE_STATE_DONE:
  678. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  679. tor_fragile_assert();
  680. }
  681. tor_assert(0);
  682. }
  683. tor_assert(!resolve);
  684. /* not there, need to add it */
  685. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  686. resolve->magic = CACHED_RESOLVE_MAGIC;
  687. resolve->state = CACHE_STATE_PENDING;
  688. resolve->is_reverse = is_reverse;
  689. strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
  690. /* add this connection to the pending list */
  691. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  692. pending_connection->conn = exitconn;
  693. resolve->pending_connections = pending_connection;
  694. /* Add this resolve to the cache and priority queue. */
  695. HT_INSERT(cache_map, &cache_root, resolve);
  696. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  697. log_debug(LD_EXIT,"Launching %s.",
  698. escaped_safe_str(exitconn->_base.address));
  699. assert_cache_ok();
  700. return launch_resolve(exitconn);
  701. }
  702. /** Log an error and abort if conn is waiting for a DNS resolve.
  703. */
  704. void
  705. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  706. {
  707. pending_connection_t *pend;
  708. cached_resolve_t **resolve;
  709. HT_FOREACH(resolve, cache_map, &cache_root) {
  710. for (pend = (*resolve)->pending_connections;
  711. pend;
  712. pend = pend->next) {
  713. tor_assert(pend->conn != conn);
  714. }
  715. }
  716. }
  717. /** Log an error and abort if any connection waiting for a DNS resolve is
  718. * corrupted. */
  719. void
  720. assert_all_pending_dns_resolves_ok(void)
  721. {
  722. pending_connection_t *pend;
  723. cached_resolve_t **resolve;
  724. HT_FOREACH(resolve, cache_map, &cache_root) {
  725. for (pend = (*resolve)->pending_connections;
  726. pend;
  727. pend = pend->next) {
  728. assert_connection_ok(TO_CONN(pend->conn), 0);
  729. tor_assert(pend->conn->_base.s == -1);
  730. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  731. }
  732. }
  733. }
  734. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  735. */
  736. void
  737. connection_dns_remove(edge_connection_t *conn)
  738. {
  739. pending_connection_t *pend, *victim;
  740. cached_resolve_t search;
  741. cached_resolve_t *resolve;
  742. tor_assert(conn->_base.type == CONN_TYPE_EXIT);
  743. tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
  744. strlcpy(search.address, conn->_base.address, sizeof(search.address));
  745. resolve = HT_FIND(cache_map, &cache_root, &search);
  746. if (!resolve) {
  747. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  748. escaped_safe_str(conn->_base.address));
  749. return;
  750. }
  751. tor_assert(resolve->pending_connections);
  752. assert_connection_ok(TO_CONN(conn),0);
  753. pend = resolve->pending_connections;
  754. if (pend->conn == conn) {
  755. resolve->pending_connections = pend->next;
  756. tor_free(pend);
  757. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  758. "for resolve of %s",
  759. conn->_base.s, escaped_safe_str(conn->_base.address));
  760. return;
  761. } else {
  762. for ( ; pend->next; pend = pend->next) {
  763. if (pend->next->conn == conn) {
  764. victim = pend->next;
  765. pend->next = victim->next;
  766. tor_free(victim);
  767. log_debug(LD_EXIT,
  768. "Connection (fd %d) no longer waiting for resolve of %s",
  769. conn->_base.s, escaped_safe_str(conn->_base.address));
  770. return; /* more are pending */
  771. }
  772. }
  773. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  774. }
  775. }
  776. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  777. * the resolve for <b>address</b> itself, and remove any cached results for
  778. * <b>address</b> from the cache.
  779. */
  780. void
  781. dns_cancel_pending_resolve(const char *address)
  782. {
  783. pending_connection_t *pend;
  784. cached_resolve_t search;
  785. cached_resolve_t *resolve, *tmp;
  786. edge_connection_t *pendconn;
  787. circuit_t *circ;
  788. strlcpy(search.address, address, sizeof(search.address));
  789. resolve = HT_FIND(cache_map, &cache_root, &search);
  790. if (!resolve)
  791. return;
  792. if (resolve->state != CACHE_STATE_PENDING) {
  793. /* We can get into this state if we never actually created the pending
  794. * resolve, due to finding an earlier cached error or something. Just
  795. * ignore it. */
  796. if (resolve->pending_connections) {
  797. log_warn(LD_BUG,
  798. "Address %s is not pending but has pending connections!",
  799. escaped_safe_str(address));
  800. tor_fragile_assert();
  801. }
  802. return;
  803. }
  804. if (!resolve->pending_connections) {
  805. log_warn(LD_BUG,
  806. "Address %s is pending but has no pending connections!",
  807. escaped_safe_str(address));
  808. tor_fragile_assert();
  809. return;
  810. }
  811. tor_assert(resolve->pending_connections);
  812. /* mark all pending connections to fail */
  813. log_debug(LD_EXIT,
  814. "Failing all connections waiting on DNS resolve of %s",
  815. escaped_safe_str(address));
  816. while (resolve->pending_connections) {
  817. pend = resolve->pending_connections;
  818. pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  819. pendconn = pend->conn;
  820. assert_connection_ok(TO_CONN(pendconn), 0);
  821. tor_assert(pendconn->_base.s == -1);
  822. if (!pendconn->_base.marked_for_close) {
  823. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  824. }
  825. circ = circuit_get_by_edge_conn(pendconn);
  826. if (circ)
  827. circuit_detach_stream(circ, pendconn);
  828. if (!pendconn->_base.marked_for_close)
  829. connection_free(TO_CONN(pendconn));
  830. resolve->pending_connections = pend->next;
  831. tor_free(pend);
  832. }
  833. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  834. if (tmp != resolve) {
  835. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  836. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  837. resolve->address, (void*)resolve,
  838. tmp ? tmp->address : "NULL", (void*)tmp);
  839. }
  840. tor_assert(tmp == resolve);
  841. resolve->state = CACHE_STATE_DONE;
  842. }
  843. /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
  844. * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
  845. * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
  846. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  847. **/
  848. static void
  849. add_answer_to_cache(const char *address, uint8_t is_reverse, uint32_t addr,
  850. const char *hostname, char outcome, uint32_t ttl)
  851. {
  852. cached_resolve_t *resolve;
  853. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
  854. return;
  855. //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
  856. // address, is_reverse?"(reverse)":"", (unsigned long)addr,
  857. // hostname?hostname:"NULL",(int)outcome);
  858. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  859. resolve->magic = CACHED_RESOLVE_MAGIC;
  860. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  861. CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
  862. strlcpy(resolve->address, address, sizeof(resolve->address));
  863. resolve->is_reverse = is_reverse;
  864. if (is_reverse) {
  865. if (outcome == DNS_RESOLVE_SUCCEEDED) {
  866. tor_assert(hostname);
  867. resolve->result.hostname = tor_strdup(hostname);
  868. } else {
  869. tor_assert(! hostname);
  870. resolve->result.hostname = NULL;
  871. }
  872. } else {
  873. tor_assert(!hostname);
  874. resolve->result.a.addr = addr;
  875. }
  876. resolve->ttl = ttl;
  877. assert_resolve_ok(resolve);
  878. HT_INSERT(cache_map, &cache_root, resolve);
  879. set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  880. }
  881. /** Return true iff <b>address</b> is one of the addresses we use to verify
  882. * that well-known sites aren't being hijacked by our DNS servers. */
  883. static INLINE int
  884. is_test_address(const char *address)
  885. {
  886. or_options_t *options = get_options();
  887. return options->ServerDNSTestAddresses &&
  888. smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
  889. }
  890. /** Called on the OR side when a DNS worker or the eventdns library tells us
  891. * the outcome of a DNS resolve: tell all pending connections about the result
  892. * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
  893. * string containing the address to look up; <b>addr</b> is an IPv4 address in
  894. * host order; <b>outcome</b> is one of
  895. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  896. */
  897. static void
  898. dns_found_answer(const char *address, uint8_t is_reverse, uint32_t addr,
  899. const char *hostname, char outcome, uint32_t ttl)
  900. {
  901. pending_connection_t *pend;
  902. cached_resolve_t search;
  903. cached_resolve_t *resolve, *removed;
  904. edge_connection_t *pendconn;
  905. circuit_t *circ;
  906. assert_cache_ok();
  907. strlcpy(search.address, address, sizeof(search.address));
  908. resolve = HT_FIND(cache_map, &cache_root, &search);
  909. if (!resolve) {
  910. int is_test_addr = is_test_address(address);
  911. if (!is_test_addr)
  912. log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
  913. escaped_safe_str(address));
  914. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  915. return;
  916. }
  917. assert_resolve_ok(resolve);
  918. if (resolve->state != CACHE_STATE_PENDING) {
  919. /* XXXX Maybe update addr? or check addr for consistency? Or let
  920. * VALID replace FAILED? */
  921. int is_test_addr = is_test_address(address);
  922. if (!is_test_addr)
  923. log_notice(LD_EXIT,
  924. "Resolved %s which was already resolved; ignoring",
  925. escaped_safe_str(address));
  926. tor_assert(resolve->pending_connections == NULL);
  927. return;
  928. }
  929. /* Removed this assertion: in fact, we'll sometimes get a double answer
  930. * to the same question. This can happen when we ask one worker to resolve
  931. * X.Y.Z., then we cancel the request, and then we ask another worker to
  932. * resolve X.Y.Z. */
  933. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  934. while (resolve->pending_connections) {
  935. pend = resolve->pending_connections;
  936. pendconn = pend->conn; /* don't pass complex things to the
  937. connection_mark_for_close macro */
  938. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  939. tor_addr_from_ipv4h(&pendconn->_base.addr, addr);
  940. pendconn->address_ttl = ttl;
  941. if (outcome != DNS_RESOLVE_SUCCEEDED) {
  942. /* prevent double-remove. */
  943. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  944. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  945. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  946. /* This detach must happen after we send the end cell. */
  947. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  948. } else {
  949. send_resolved_cell(pendconn, outcome == DNS_RESOLVE_FAILED_PERMANENT ?
  950. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  951. /* This detach must happen after we send the resolved cell. */
  952. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  953. }
  954. connection_free(TO_CONN(pendconn));
  955. } else {
  956. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  957. tor_assert(!is_reverse);
  958. /* prevent double-remove. */
  959. pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
  960. circ = circuit_get_by_edge_conn(pend->conn);
  961. tor_assert(circ);
  962. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  963. /* unlink pend->conn from resolving_streams, */
  964. circuit_detach_stream(circ, pend->conn);
  965. /* and link it to n_streams */
  966. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  967. pend->conn->on_circuit = circ;
  968. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  969. connection_exit_connect(pend->conn);
  970. } else {
  971. /* prevent double-remove. This isn't really an accurate state,
  972. * but it does the right thing. */
  973. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  974. if (is_reverse)
  975. send_resolved_hostname_cell(pendconn, hostname);
  976. else
  977. send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
  978. circ = circuit_get_by_edge_conn(pendconn);
  979. tor_assert(circ);
  980. circuit_detach_stream(circ, pendconn);
  981. connection_free(TO_CONN(pendconn));
  982. }
  983. }
  984. resolve->pending_connections = pend->next;
  985. tor_free(pend);
  986. }
  987. resolve->state = CACHE_STATE_DONE;
  988. removed = HT_REMOVE(cache_map, &cache_root, &search);
  989. if (removed != resolve) {
  990. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  991. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  992. resolve->address, (void*)resolve,
  993. removed ? removed->address : "NULL", (void*)removed);
  994. }
  995. assert_resolve_ok(resolve);
  996. assert_cache_ok();
  997. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  998. assert_cache_ok();
  999. }
  1000. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1001. * a transient failure. */
  1002. static int
  1003. evdns_err_is_transient(int err)
  1004. {
  1005. switch (err)
  1006. {
  1007. case DNS_ERR_SERVERFAILED:
  1008. case DNS_ERR_TRUNCATED:
  1009. case DNS_ERR_TIMEOUT:
  1010. return 1;
  1011. default:
  1012. return 0;
  1013. }
  1014. }
  1015. /** Configure eventdns nameservers if force is true, or if the configuration
  1016. * has changed since the last time we called this function, or if we failed on
  1017. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1018. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1019. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1020. * -1 on failure. */
  1021. static int
  1022. configure_nameservers(int force)
  1023. {
  1024. or_options_t *options;
  1025. const char *conf_fname;
  1026. struct stat st;
  1027. int r;
  1028. options = get_options();
  1029. conf_fname = options->ServerDNSResolvConfFile;
  1030. #ifndef MS_WINDOWS
  1031. if (!conf_fname)
  1032. conf_fname = "/etc/resolv.conf";
  1033. #endif
  1034. evdns_set_log_fn(evdns_log_cb);
  1035. if (conf_fname) {
  1036. if (stat(conf_fname, &st)) {
  1037. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1038. conf_fname, strerror(errno));
  1039. goto err;
  1040. }
  1041. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1042. && st.st_mtime == resolv_conf_mtime) {
  1043. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1044. return 0;
  1045. }
  1046. if (nameservers_configured) {
  1047. evdns_search_clear();
  1048. evdns_clear_nameservers_and_suspend();
  1049. }
  1050. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1051. if ((r = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname))) {
  1052. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  1053. conf_fname, conf_fname, r);
  1054. goto err;
  1055. }
  1056. if (evdns_count_nameservers() == 0) {
  1057. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1058. goto err;
  1059. }
  1060. tor_free(resolv_conf_fname);
  1061. resolv_conf_fname = tor_strdup(conf_fname);
  1062. resolv_conf_mtime = st.st_mtime;
  1063. if (nameservers_configured)
  1064. evdns_resume();
  1065. }
  1066. #ifdef MS_WINDOWS
  1067. else {
  1068. if (nameservers_configured) {
  1069. evdns_search_clear();
  1070. evdns_clear_nameservers_and_suspend();
  1071. }
  1072. if (evdns_config_windows_nameservers()) {
  1073. log_warn(LD_EXIT,"Could not config nameservers.");
  1074. goto err;
  1075. }
  1076. if (evdns_count_nameservers() == 0) {
  1077. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1078. "your Windows configuration.");
  1079. goto err;
  1080. }
  1081. if (nameservers_configured)
  1082. evdns_resume();
  1083. tor_free(resolv_conf_fname);
  1084. resolv_conf_mtime = 0;
  1085. }
  1086. #endif
  1087. if (evdns_count_nameservers() == 1) {
  1088. evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
  1089. evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
  1090. } else {
  1091. evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
  1092. evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
  1093. }
  1094. dns_servers_relaunch_checks();
  1095. nameservers_configured = 1;
  1096. if (nameserver_config_failed) {
  1097. nameserver_config_failed = 0;
  1098. mark_my_descriptor_dirty();
  1099. }
  1100. return 0;
  1101. err:
  1102. nameservers_configured = 0;
  1103. if (! nameserver_config_failed) {
  1104. nameserver_config_failed = 1;
  1105. mark_my_descriptor_dirty();
  1106. }
  1107. return -1;
  1108. }
  1109. /** For eventdns: Called when we get an answer for a request we launched.
  1110. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1111. */
  1112. static void
  1113. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1114. void *arg)
  1115. {
  1116. char *string_address = arg;
  1117. uint8_t is_reverse = 0;
  1118. int status = DNS_RESOLVE_FAILED_PERMANENT;
  1119. uint32_t addr = 0;
  1120. const char *hostname = NULL;
  1121. int was_wildcarded = 0;
  1122. if (result == DNS_ERR_NONE) {
  1123. if (type == DNS_IPv4_A && count) {
  1124. char answer_buf[INET_NTOA_BUF_LEN+1];
  1125. struct in_addr in;
  1126. char *escaped_address;
  1127. uint32_t *addrs = addresses;
  1128. in.s_addr = addrs[0];
  1129. addr = ntohl(addrs[0]);
  1130. status = DNS_RESOLVE_SUCCEEDED;
  1131. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1132. escaped_address = esc_for_log(string_address);
  1133. if (answer_is_wildcarded(answer_buf)) {
  1134. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1135. "address %s; treating as a failure.",
  1136. safe_str(escaped_address),
  1137. escaped_safe_str(answer_buf));
  1138. was_wildcarded = 1;
  1139. addr = 0;
  1140. status = DNS_RESOLVE_FAILED_PERMANENT;
  1141. } else {
  1142. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1143. safe_str(escaped_address),
  1144. escaped_safe_str(answer_buf));
  1145. }
  1146. tor_free(escaped_address);
  1147. } else if (type == DNS_PTR && count) {
  1148. char *escaped_address;
  1149. is_reverse = 1;
  1150. hostname = ((char**)addresses)[0];
  1151. status = DNS_RESOLVE_SUCCEEDED;
  1152. escaped_address = esc_for_log(string_address);
  1153. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1154. safe_str(escaped_address),
  1155. escaped_safe_str(hostname));
  1156. tor_free(escaped_address);
  1157. } else if (count) {
  1158. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1159. escaped_safe_str(string_address));
  1160. } else {
  1161. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1162. escaped_safe_str(string_address));
  1163. }
  1164. } else {
  1165. if (evdns_err_is_transient(result))
  1166. status = DNS_RESOLVE_FAILED_TRANSIENT;
  1167. }
  1168. if (was_wildcarded) {
  1169. if (is_test_address(string_address)) {
  1170. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1171. * server must really hate us. */
  1172. add_wildcarded_test_address(string_address);
  1173. }
  1174. }
  1175. if (result != DNS_ERR_SHUTDOWN)
  1176. dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
  1177. tor_free(string_address);
  1178. }
  1179. /** For eventdns: start resolving as necessary to find the target for
  1180. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1181. * 0 on "resolve launched." */
  1182. static int
  1183. launch_resolve(edge_connection_t *exitconn)
  1184. {
  1185. char *addr = tor_strdup(exitconn->_base.address);
  1186. struct in_addr in;
  1187. int r;
  1188. int options = get_options()->ServerDNSSearchDomains ? 0
  1189. : DNS_QUERY_NO_SEARCH;
  1190. /* What? Nameservers not configured? Sounds like a bug. */
  1191. if (!nameservers_configured) {
  1192. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1193. "launched. Configuring.");
  1194. if (configure_nameservers(1) < 0) {
  1195. return -1;
  1196. }
  1197. }
  1198. r = parse_inaddr_arpa_address(exitconn->_base.address, &in);
  1199. if (r == 0) {
  1200. log_info(LD_EXIT, "Launching eventdns request for %s",
  1201. escaped_safe_str(exitconn->_base.address));
  1202. r = evdns_resolve_ipv4(exitconn->_base.address, options,
  1203. evdns_callback, addr);
  1204. } else if (r == 1) {
  1205. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1206. escaped_safe_str(exitconn->_base.address));
  1207. r = evdns_resolve_reverse(&in, DNS_QUERY_NO_SEARCH,
  1208. evdns_callback, addr);
  1209. } else if (r == -1) {
  1210. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1211. }
  1212. if (r) {
  1213. log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
  1214. escaped_safe_str(addr), r);
  1215. r = evdns_err_is_transient(r) ? -2 : -1;
  1216. tor_free(addr); /* There is no evdns request in progress; stop
  1217. * addr from getting leaked. */
  1218. }
  1219. return r;
  1220. }
  1221. /** How many requests for bogus addresses have we launched so far? */
  1222. static int n_wildcard_requests = 0;
  1223. /** Map from dotted-quad IP address in response to an int holding how many
  1224. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1225. * would be easier to use definitely-invalid addresses (as specified by
  1226. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1227. static strmap_t *dns_wildcard_response_count = NULL;
  1228. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1229. * nameserver wants to return in response to requests for nonexistent domains.
  1230. */
  1231. static smartlist_t *dns_wildcard_list = NULL;
  1232. /** True iff we've logged about a single address getting wildcarded.
  1233. * Subsequent warnings will be less severe. */
  1234. static int dns_wildcard_one_notice_given = 0;
  1235. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1236. */
  1237. static int dns_wildcard_notice_given = 0;
  1238. /** List of supposedly good addresses that are getting wildcarded to the
  1239. * same addresses as nonexistent addresses. */
  1240. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1241. /** True iff we've warned about a test address getting wildcarded */
  1242. static int dns_wildcarded_test_address_notice_given = 0;
  1243. /** True iff all addresses seem to be getting wildcarded. */
  1244. static int dns_is_completely_invalid = 0;
  1245. /** Called when we see <b>id</b> (a dotted quad) in response to a request for
  1246. * a hopefully bogus address. */
  1247. static void
  1248. wildcard_increment_answer(const char *id)
  1249. {
  1250. int *ip;
  1251. if (!dns_wildcard_response_count)
  1252. dns_wildcard_response_count = strmap_new();
  1253. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1254. if (!ip) {
  1255. ip = tor_malloc_zero(sizeof(int));
  1256. strmap_set(dns_wildcard_response_count, id, ip);
  1257. }
  1258. ++*ip;
  1259. if (*ip > 5 && n_wildcard_requests > 10) {
  1260. if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
  1261. if (!smartlist_string_isin(dns_wildcard_list, id)) {
  1262. log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1263. "Your DNS provider has given \"%s\" as an answer for %d different "
  1264. "invalid addresses. Apparently they are hijacking DNS failures. "
  1265. "I'll try to correct for this by treating future occurrences of "
  1266. "\"%s\" as 'not found'.", id, *ip, id);
  1267. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1268. }
  1269. if (!dns_wildcard_notice_given)
  1270. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1271. dns_wildcard_notice_given = 1;
  1272. }
  1273. }
  1274. /** Note that a single test address (one believed to be good) seems to be
  1275. * getting redirected to the same IP as failures are. */
  1276. static void
  1277. add_wildcarded_test_address(const char *address)
  1278. {
  1279. int n, n_test_addrs;
  1280. if (!dns_wildcarded_test_address_list)
  1281. dns_wildcarded_test_address_list = smartlist_create();
  1282. if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
  1283. return;
  1284. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1285. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1286. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1287. n = smartlist_len(dns_wildcarded_test_address_list);
  1288. if (n > n_test_addrs/2) {
  1289. log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1290. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1291. "address. It has done this with %d test addresses so far. I'm "
  1292. "going to stop being an exit node for now, since our DNS seems so "
  1293. "broken.", address, n);
  1294. if (!dns_is_completely_invalid) {
  1295. dns_is_completely_invalid = 1;
  1296. mark_my_descriptor_dirty();
  1297. }
  1298. if (!dns_wildcarded_test_address_notice_given)
  1299. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1300. dns_wildcarded_test_address_notice_given = 1;
  1301. }
  1302. }
  1303. /** Callback function when we get an answer (possibly failing) for a request
  1304. * for a (hopefully) nonexistent domain. */
  1305. static void
  1306. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1307. void *addresses, void *arg)
  1308. {
  1309. (void)ttl;
  1310. ++n_wildcard_requests;
  1311. if (result == DNS_ERR_NONE && type == DNS_IPv4_A && count) {
  1312. uint32_t *addrs = addresses;
  1313. int i;
  1314. char *string_address = arg;
  1315. for (i = 0; i < count; ++i) {
  1316. char answer_buf[INET_NTOA_BUF_LEN+1];
  1317. struct in_addr in;
  1318. in.s_addr = addrs[i];
  1319. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1320. wildcard_increment_answer(answer_buf);
  1321. }
  1322. log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1323. "Your DNS provider gave an answer for \"%s\", which "
  1324. "is not supposed to exist. Apparently they are hijacking "
  1325. "DNS failures. Trying to correct for this. We've noticed %d "
  1326. "possibly bad address%s so far.",
  1327. string_address, strmap_size(dns_wildcard_response_count),
  1328. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1329. dns_wildcard_one_notice_given = 1;
  1330. }
  1331. tor_free(arg);
  1332. }
  1333. /** Launch a single request for a nonexistent hostname consisting of between
  1334. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1335. * <b>suffix</b> */
  1336. static void
  1337. launch_wildcard_check(int min_len, int max_len, const char *suffix)
  1338. {
  1339. char *addr;
  1340. int r;
  1341. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1342. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1343. "domains with request for bogus hostname \"%s\"", addr);
  1344. r = evdns_resolve_ipv4(/* This "addr" tells us which address to resolve */
  1345. addr,
  1346. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1347. /* This "addr" is an argument to the callback*/ addr);
  1348. if (r) {
  1349. /* There is no evdns request in progress; stop addr from getting leaked */
  1350. tor_free(addr);
  1351. }
  1352. }
  1353. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1354. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1355. static void
  1356. launch_test_addresses(int fd, short event, void *args)
  1357. {
  1358. or_options_t *options = get_options();
  1359. (void)fd;
  1360. (void)event;
  1361. (void)args;
  1362. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1363. "hijack *everything*.");
  1364. /* This situation is worse than the failure-hijacking situation. When this
  1365. * happens, we're no good for DNS requests at all, and we shouldn't really
  1366. * be an exit server.*/
  1367. if (!options->ServerDNSTestAddresses)
  1368. return;
  1369. SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
  1370. {
  1371. int r = evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
  1372. tor_strdup(address));
  1373. if (r)
  1374. log_info(LD_EXIT, "eventdns rejected test address %s: error %d",
  1375. escaped_safe_str(address), r);
  1376. });
  1377. }
  1378. #define N_WILDCARD_CHECKS 2
  1379. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1380. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1381. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1382. * buy these lovely encyclopedias" page. */
  1383. static void
  1384. dns_launch_wildcard_checks(void)
  1385. {
  1386. int i;
  1387. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1388. "to hijack DNS failures.");
  1389. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1390. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
  1391. * to 'comply' with rfc2606, refrain from giving A records for these.
  1392. * This is the standards-compliance equivalent of making sure that your
  1393. * crackhouse's elevator inspection certificate is up to date.
  1394. */
  1395. launch_wildcard_check(2, 16, ".invalid");
  1396. launch_wildcard_check(2, 16, ".test");
  1397. /* These will break specs if there are ever any number of
  1398. * 8+-character top-level domains. */
  1399. launch_wildcard_check(8, 16, "");
  1400. /* Try some random .com/org/net domains. This will work fine so long as
  1401. * not too many resolve to the same place. */
  1402. launch_wildcard_check(8, 16, ".com");
  1403. launch_wildcard_check(8, 16, ".org");
  1404. launch_wildcard_check(8, 16, ".net");
  1405. }
  1406. }
  1407. /** If appropriate, start testing whether our DNS servers tend to lie to
  1408. * us. */
  1409. void
  1410. dns_launch_correctness_checks(void)
  1411. {
  1412. static struct event launch_event;
  1413. struct timeval timeout;
  1414. if (!get_options()->ServerDNSDetectHijacking)
  1415. return;
  1416. dns_launch_wildcard_checks();
  1417. /* Wait a while before launching requests for test addresses, so we can
  1418. * get the results from checking for wildcarding. */
  1419. evtimer_set(&launch_event, launch_test_addresses, NULL);
  1420. timeout.tv_sec = 30;
  1421. timeout.tv_usec = 0;
  1422. if (evtimer_add(&launch_event, &timeout)<0) {
  1423. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1424. }
  1425. }
  1426. /** Return true iff our DNS servers lie to us too much to be trustd. */
  1427. int
  1428. dns_seems_to_be_broken(void)
  1429. {
  1430. return dns_is_completely_invalid;
  1431. }
  1432. /** Forget what we've previously learned about our DNS servers' correctness. */
  1433. void
  1434. dns_reset_correctness_checks(void)
  1435. {
  1436. if (dns_wildcard_response_count) {
  1437. strmap_free(dns_wildcard_response_count, _tor_free);
  1438. dns_wildcard_response_count = NULL;
  1439. }
  1440. n_wildcard_requests = 0;
  1441. if (dns_wildcard_list) {
  1442. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1443. smartlist_clear(dns_wildcard_list);
  1444. }
  1445. if (dns_wildcarded_test_address_list) {
  1446. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1447. tor_free(cp));
  1448. smartlist_clear(dns_wildcarded_test_address_list);
  1449. }
  1450. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1451. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
  1452. }
  1453. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1454. * returned in response to requests for nonexistent hostnames. */
  1455. static int
  1456. answer_is_wildcarded(const char *ip)
  1457. {
  1458. return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
  1459. }
  1460. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1461. static void
  1462. assert_resolve_ok(cached_resolve_t *resolve)
  1463. {
  1464. tor_assert(resolve);
  1465. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1466. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1467. tor_assert(tor_strisnonupper(resolve->address));
  1468. if (resolve->state != CACHE_STATE_PENDING) {
  1469. tor_assert(!resolve->pending_connections);
  1470. }
  1471. if (resolve->state == CACHE_STATE_PENDING ||
  1472. resolve->state == CACHE_STATE_DONE) {
  1473. tor_assert(!resolve->ttl);
  1474. if (resolve->is_reverse)
  1475. tor_assert(!resolve->result.hostname);
  1476. else
  1477. tor_assert(!resolve->result.a.addr);
  1478. }
  1479. }
  1480. #ifdef DEBUG_DNS_CACHE
  1481. /** Exit with an assertion if the DNS cache is corrupt. */
  1482. static void
  1483. _assert_cache_ok(void)
  1484. {
  1485. cached_resolve_t **resolve;
  1486. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1487. if (bad_rep) {
  1488. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1489. tor_assert(!bad_rep);
  1490. }
  1491. HT_FOREACH(resolve, cache_map, &cache_root) {
  1492. assert_resolve_ok(*resolve);
  1493. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1494. }
  1495. if (!cached_resolve_pqueue)
  1496. return;
  1497. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1498. _compare_cached_resolves_by_expiry);
  1499. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1500. {
  1501. if (res->state == CACHE_STATE_DONE) {
  1502. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1503. tor_assert(!found || found != res);
  1504. } else {
  1505. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1506. tor_assert(found);
  1507. }
  1508. });
  1509. }
  1510. #endif