dns.c 56 KB

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