dns.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2012, 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 "circuitlist.h"
  14. #include "circuituse.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "connection_edge.h"
  18. #include "control.h"
  19. #include "dns.h"
  20. #include "main.h"
  21. #include "policies.h"
  22. #include "relay.h"
  23. #include "router.h"
  24. #include "ht.h"
  25. #ifdef HAVE_EVENT2_DNS_H
  26. #include <event2/event.h>
  27. #include <event2/dns.h>
  28. #else
  29. #include <event.h>
  30. #include "eventdns.h"
  31. #ifndef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  32. #define HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  33. #endif
  34. #endif
  35. #ifndef HAVE_EVENT2_DNS_H
  36. struct evdns_base;
  37. struct evdns_request;
  38. #define evdns_base_new(x,y) tor_malloc(1)
  39. #define evdns_base_clear_nameservers_and_suspend(base) \
  40. evdns_clear_nameservers_and_suspend()
  41. #define evdns_base_search_clear(base) evdns_search_clear()
  42. #define evdns_base_set_default_outgoing_bind_address(base, a, len) \
  43. evdns_set_default_outgoing_bind_address((a),(len))
  44. #define evdns_base_resolv_conf_parse(base, options, fname) \
  45. evdns_resolv_conf_parse((options), (fname))
  46. #define evdns_base_count_nameservers(base) \
  47. evdns_count_nameservers()
  48. #define evdns_base_resume(base) \
  49. evdns_resume()
  50. #define evdns_base_config_windows_nameservers(base) \
  51. evdns_config_windows_nameservers()
  52. #define evdns_base_set_option_(base, opt, val) \
  53. evdns_set_option((opt),(val),DNS_OPTIONS_ALL)
  54. /* Note: our internal eventdns.c, plus Libevent 1.4, used a 1 return to
  55. * signify failure to launch a resolve. Libevent 2.0 uses a -1 return to
  56. * signify a failure on a resolve, though if we're on Libevent 2.0, we should
  57. * have event2/dns.h and never hit these macros. Regardless, 0 is success. */
  58. #define evdns_base_resolve_ipv4(base, addr, options, cb, ptr) \
  59. ((evdns_resolve_ipv4((addr), (options), (cb), (ptr))!=0) \
  60. ? NULL : ((void*)1))
  61. #define evdns_base_resolve_ipv6(base, addr, options, cb, ptr) \
  62. ((evdns_resolve_ipv6((addr), (options), (cb), (ptr))!=0) \
  63. ? NULL : ((void*)1))
  64. #define evdns_base_resolve_reverse(base, addr, options, cb, ptr) \
  65. ((evdns_resolve_reverse((addr), (options), (cb), (ptr))!=0) \
  66. ? NULL : ((void*)1))
  67. #define evdns_base_resolve_reverse_ipv6(base, addr, options, cb, ptr) \
  68. ((evdns_resolve_reverse_ipv6((addr), (options), (cb), (ptr))!=0) \
  69. ? NULL : ((void*)1))
  70. #elif defined(LIBEVENT_VERSION_NUMBER) && LIBEVENT_VERSION_NUMBER < 0x02000303
  71. #define evdns_base_set_option_(base, opt, val) \
  72. evdns_base_set_option((base), (opt),(val),DNS_OPTIONS_ALL)
  73. #else
  74. #define evdns_base_set_option_ evdns_base_set_option
  75. #endif
  76. /** Longest hostname we're willing to resolve. */
  77. #define MAX_ADDRESSLEN 256
  78. /** How long will we wait for an answer from the resolver before we decide
  79. * that the resolver is wedged? */
  80. #define RESOLVE_MAX_TIMEOUT 300
  81. /** Our evdns_base; this structure handles all our name lookups. */
  82. static struct evdns_base *the_evdns_base = NULL;
  83. /** Have we currently configured nameservers with eventdns? */
  84. static int nameservers_configured = 0;
  85. /** Did our most recent attempt to configure nameservers with eventdns fail? */
  86. static int nameserver_config_failed = 0;
  87. /** What was the resolv_conf fname we last used when configuring the
  88. * nameservers? Used to check whether we need to reconfigure. */
  89. static char *resolv_conf_fname = NULL;
  90. /** What was the mtime on the resolv.conf file we last used when configuring
  91. * the nameservers? Used to check whether we need to reconfigure. */
  92. static time_t resolv_conf_mtime = 0;
  93. /** Linked list of connections waiting for a DNS answer. */
  94. typedef struct pending_connection_t {
  95. edge_connection_t *conn;
  96. struct pending_connection_t *next;
  97. } pending_connection_t;
  98. /** Value of 'magic' field for cached_resolve_t. Used to try to catch bad
  99. * pointers and memory stomping. */
  100. #define CACHED_RESOLVE_MAGIC 0x1234F00D
  101. /* Possible states for a cached resolve_t */
  102. /** We are waiting for the resolver system to tell us an answer here.
  103. * When we get one, or when we time out, the state of this cached_resolve_t
  104. * will become "DONE" and we'll possibly add a CACHED
  105. * entry. This cached_resolve_t will be in the hash table so that we will
  106. * know not to launch more requests for this addr, but rather to add more
  107. * connections to the pending list for the addr. */
  108. #define CACHE_STATE_PENDING 0
  109. /** This used to be a pending cached_resolve_t, and we got an answer for it.
  110. * Now we're waiting for this cached_resolve_t to expire. This should
  111. * have no pending connections, and should not appear in the hash table. */
  112. #define CACHE_STATE_DONE 1
  113. /** We are caching an answer for this address. This should have no pending
  114. * connections, and should appear in the hash table. */
  115. #define CACHE_STATE_CACHED 2
  116. /** @name status values for a single DNS request.
  117. *
  118. * @{ */
  119. /** The DNS request is in progress. */
  120. #define RES_STATUS_INFLIGHT 1
  121. /** The DNS request finished and gave an answer */
  122. #define RES_STATUS_DONE_OK 2
  123. /** The DNS request finished and gave an error */
  124. #define RES_STATUS_DONE_ERR 3
  125. /**@}*/
  126. /** A DNS request: possibly completed, possibly pending; cached_resolve
  127. * structs are stored at the OR side in a hash table, and as a linked
  128. * list from oldest to newest.
  129. */
  130. typedef struct cached_resolve_t {
  131. HT_ENTRY(cached_resolve_t) node;
  132. uint32_t magic; /**< Must be CACHED_RESOLVE_MAGIC */
  133. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  134. union {
  135. uint32_t addr_ipv4; /**< IPv4 addr for <b>address</b>, if successful */
  136. int err_ipv4; /**< One of DNS_ERR_*, if IPv4 lookup failed. */
  137. } result_ipv4; /**< Outcome of IPv4 lookup */
  138. union {
  139. struct in6_addr addr_ipv6; /**< IPv6 addr for <b>address</b>, if
  140. * successful */
  141. int err_ipv6; /**< One of DNS_ERR_*, if IPv6 lookup failed. */
  142. } result_ipv6; /**< Outcome of IPv6 lookup, if any */
  143. union {
  144. char *hostname; /** A hostname, if PTR lookup happened successfully*/
  145. int err_hostname; /** One of DNS_ERR_*, if PTR lookup failed. */
  146. } result_ptr;
  147. /** @name Status fields
  148. *
  149. * These take one of the RES_STATUS_* values, depending on the state
  150. * of the corresponding lookup.
  151. *
  152. * @{ */
  153. unsigned int res_status_ipv4 : 2;
  154. unsigned int res_status_ipv6 : 2;
  155. unsigned int res_status_hostname : 2;
  156. /**@}*/
  157. uint8_t state; /**< Is this cached entry pending/done/informative? */
  158. time_t expire; /**< Remove items from cache after this time. */
  159. uint32_t ttl_ipv4; /**< What TTL did the nameserver tell us? */
  160. uint32_t ttl_ipv6; /**< What TTL did the nameserver tell us? */
  161. uint32_t ttl_hostname; /**< What TTL did the nameserver tell us? */
  162. /** Connections that want to know when we get an answer for this resolve. */
  163. pending_connection_t *pending_connections;
  164. /** Position of this element in the heap*/
  165. int minheap_idx;
  166. } cached_resolve_t;
  167. static void purge_expired_resolves(time_t now);
  168. static void dns_found_answer(const char *address, uint8_t query_type,
  169. int dns_answer,
  170. const tor_addr_t *addr,
  171. const char *hostname,
  172. uint32_t ttl);
  173. static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
  174. static int launch_resolve(cached_resolve_t *resolve);
  175. static void add_wildcarded_test_address(const char *address);
  176. static int configure_nameservers(int force);
  177. static int answer_is_wildcarded(const char *ip);
  178. static int dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
  179. or_circuit_t *oncirc, char **resolved_to_hostname,
  180. int *made_connection_pending_out);
  181. static int set_exitconn_info_from_resolve(edge_connection_t *exitconn,
  182. const cached_resolve_t *resolve,
  183. char **hostname_out);
  184. static int evdns_err_is_transient(int err);
  185. static void inform_pending_connections(cached_resolve_t *resolve);
  186. static void make_pending_resolve_cached(cached_resolve_t *cached);
  187. #ifdef DEBUG_DNS_CACHE
  188. static void assert_cache_ok_(void);
  189. #define assert_cache_ok() assert_cache_ok_()
  190. #else
  191. #define assert_cache_ok() STMT_NIL
  192. #endif
  193. static void assert_resolve_ok(cached_resolve_t *resolve);
  194. /** Hash table of cached_resolve objects. */
  195. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  196. /** Global: how many IPv6 requests have we made in all? */
  197. static uint64_t n_ipv6_requests_made = 0;
  198. /** Global: how many IPv6 requests have timed out? */
  199. static uint64_t n_ipv6_timeouts = 0;
  200. /** Global: Do we think that IPv6 DNS is broken? */
  201. static int dns_is_broken_for_ipv6 = 0;
  202. /** Function to compare hashed resolves on their addresses; used to
  203. * implement hash tables. */
  204. static INLINE int
  205. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  206. {
  207. /* make this smarter one day? */
  208. assert_resolve_ok(a); // Not b; b may be just a search.
  209. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  210. }
  211. /** Hash function for cached_resolve objects */
  212. static INLINE unsigned int
  213. cached_resolve_hash(cached_resolve_t *a)
  214. {
  215. return ht_string_hash(a->address);
  216. }
  217. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  218. cached_resolves_eq)
  219. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  220. cached_resolves_eq, 0.6, malloc, realloc, free)
  221. /** Initialize the DNS cache. */
  222. static void
  223. init_cache_map(void)
  224. {
  225. HT_INIT(cache_map, &cache_root);
  226. }
  227. /** Helper: called by eventdns when eventdns wants to log something. */
  228. static void
  229. evdns_log_cb(int warn, const char *msg)
  230. {
  231. const char *cp;
  232. static int all_down = 0;
  233. int severity = warn ? LOG_WARN : LOG_INFO;
  234. if (!strcmpstart(msg, "Resolve requested for") &&
  235. get_options()->SafeLogging) {
  236. log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
  237. return;
  238. } else if (!strcmpstart(msg, "Search: ")) {
  239. return;
  240. }
  241. if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
  242. char *ns = tor_strndup(msg+11, cp-(msg+11));
  243. const char *err = strchr(cp, ':')+2;
  244. tor_assert(err);
  245. /* Don't warn about a single failed nameserver; we'll warn with 'all
  246. * nameservers have failed' if we're completely out of nameservers;
  247. * otherwise, the situation is tolerable. */
  248. severity = LOG_INFO;
  249. control_event_server_status(LOG_NOTICE,
  250. "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
  251. ns, escaped(err));
  252. tor_free(ns);
  253. } else if (!strcmpstart(msg, "Nameserver ") &&
  254. (cp=strstr(msg, " is back up"))) {
  255. char *ns = tor_strndup(msg+11, cp-(msg+11));
  256. severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
  257. all_down = 0;
  258. control_event_server_status(LOG_NOTICE,
  259. "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
  260. tor_free(ns);
  261. } else if (!strcmp(msg, "All nameservers have failed")) {
  262. control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
  263. all_down = 1;
  264. }
  265. log(severity, LD_EXIT, "eventdns: %s", msg);
  266. }
  267. /** Helper: passed to eventdns.c as a callback so it can generate random
  268. * numbers for transaction IDs and 0x20-hack coding. */
  269. static void
  270. dns_randfn_(char *b, size_t n)
  271. {
  272. crypto_rand(b,n);
  273. }
  274. /** Initialize the DNS subsystem; called by the OR process. */
  275. int
  276. dns_init(void)
  277. {
  278. init_cache_map();
  279. evdns_set_random_bytes_fn(dns_randfn_);
  280. if (server_mode(get_options())) {
  281. int r = configure_nameservers(1);
  282. return r;
  283. }
  284. return 0;
  285. }
  286. /** Called when DNS-related options change (or may have changed). Returns -1
  287. * on failure, 0 on success. */
  288. int
  289. dns_reset(void)
  290. {
  291. const or_options_t *options = get_options();
  292. if (! server_mode(options)) {
  293. if (!the_evdns_base) {
  294. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  295. log_err(LD_BUG, "Couldn't create an evdns_base");
  296. return -1;
  297. }
  298. }
  299. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  300. evdns_base_search_clear(the_evdns_base);
  301. nameservers_configured = 0;
  302. tor_free(resolv_conf_fname);
  303. resolv_conf_mtime = 0;
  304. } else {
  305. if (configure_nameservers(0) < 0) {
  306. return -1;
  307. }
  308. }
  309. return 0;
  310. }
  311. /** Return true iff the most recent attempt to initialize the DNS subsystem
  312. * failed. */
  313. int
  314. has_dns_init_failed(void)
  315. {
  316. return nameserver_config_failed;
  317. }
  318. /** Helper: Given a TTL from a DNS response, determine what TTL to give the
  319. * OP that asked us to resolve it. */
  320. uint32_t
  321. dns_clip_ttl(uint32_t ttl)
  322. {
  323. if (ttl < MIN_DNS_TTL)
  324. return MIN_DNS_TTL;
  325. else if (ttl > MAX_DNS_TTL)
  326. return MAX_DNS_TTL;
  327. else
  328. return ttl;
  329. }
  330. /** Helper: Given a TTL from a DNS response, determine how long to hold it in
  331. * our cache. */
  332. static uint32_t
  333. dns_get_expiry_ttl(uint32_t ttl)
  334. {
  335. if (ttl < MIN_DNS_TTL)
  336. return MIN_DNS_TTL;
  337. else if (ttl > MAX_DNS_ENTRY_AGE)
  338. return MAX_DNS_ENTRY_AGE;
  339. else
  340. return ttl;
  341. }
  342. /** Helper: free storage held by an entry in the DNS cache. */
  343. static void
  344. free_cached_resolve_(cached_resolve_t *r)
  345. {
  346. if (!r)
  347. return;
  348. while (r->pending_connections) {
  349. pending_connection_t *victim = r->pending_connections;
  350. r->pending_connections = victim->next;
  351. tor_free(victim);
  352. }
  353. if (r->res_status_hostname == RES_STATUS_DONE_OK)
  354. tor_free(r->result_ptr.hostname);
  355. r->magic = 0xFF00FF00;
  356. tor_free(r);
  357. }
  358. /** Compare two cached_resolve_t pointers by expiry time, and return
  359. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  360. * the priority queue implementation. */
  361. static int
  362. compare_cached_resolves_by_expiry_(const void *_a, const void *_b)
  363. {
  364. const cached_resolve_t *a = _a, *b = _b;
  365. if (a->expire < b->expire)
  366. return -1;
  367. else if (a->expire == b->expire)
  368. return 0;
  369. else
  370. return 1;
  371. }
  372. /** Priority queue of cached_resolve_t objects to let us know when they
  373. * will expire. */
  374. static smartlist_t *cached_resolve_pqueue = NULL;
  375. static void
  376. cached_resolve_add_answer(cached_resolve_t *resolve,
  377. int query_type,
  378. int dns_result,
  379. const tor_addr_t *answer_addr,
  380. const char *answer_hostname,
  381. uint32_t ttl)
  382. {
  383. if (query_type == DNS_PTR) {
  384. if (resolve->res_status_hostname != RES_STATUS_INFLIGHT)
  385. return;
  386. if (dns_result == DNS_ERR_NONE && answer_hostname) {
  387. resolve->result_ptr.hostname = tor_strdup(answer_hostname);
  388. resolve->res_status_hostname = RES_STATUS_DONE_OK;
  389. } else {
  390. resolve->result_ptr.err_hostname = dns_result;
  391. resolve->res_status_hostname = RES_STATUS_DONE_ERR;
  392. }
  393. resolve->ttl_hostname = ttl;
  394. } else if (query_type == DNS_IPv4_A) {
  395. if (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT)
  396. return;
  397. if (dns_result == DNS_ERR_NONE && answer_addr) {
  398. tor_assert(tor_addr_family(answer_addr) == AF_INET);
  399. resolve->result_ipv4.addr_ipv4 = tor_addr_to_ipv4h(answer_addr);
  400. resolve->res_status_ipv4 = RES_STATUS_DONE_OK;
  401. } else {
  402. resolve->result_ipv4.err_ipv4 = dns_result;
  403. resolve->res_status_ipv4 = RES_STATUS_DONE_ERR;
  404. }
  405. } else if (query_type == DNS_IPv6_AAAA) {
  406. if (resolve->res_status_ipv6 != RES_STATUS_INFLIGHT)
  407. return;
  408. if (dns_result == DNS_ERR_NONE && answer_addr) {
  409. tor_assert(tor_addr_family(answer_addr) == AF_INET6);
  410. memcpy(&resolve->result_ipv6.addr_ipv6,
  411. tor_addr_to_in6(answer_addr),
  412. sizeof(struct in6_addr));
  413. resolve->res_status_ipv6 = RES_STATUS_DONE_OK;
  414. } else {
  415. resolve->result_ipv6.err_ipv6 = dns_result;
  416. resolve->res_status_ipv6 = RES_STATUS_DONE_ERR;
  417. }
  418. }
  419. }
  420. /** Return true iff there are no in-flight requests for <b>resolve</b>. */
  421. static int
  422. cached_resolve_have_all_answers(const cached_resolve_t *resolve)
  423. {
  424. return (resolve->res_status_ipv4 != RES_STATUS_INFLIGHT &&
  425. resolve->res_status_ipv6 != RES_STATUS_INFLIGHT &&
  426. resolve->res_status_hostname != RES_STATUS_INFLIGHT);
  427. }
  428. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  429. * priority queue */
  430. static void
  431. set_expiry(cached_resolve_t *resolve, time_t expires)
  432. {
  433. tor_assert(resolve && resolve->expire == 0);
  434. if (!cached_resolve_pqueue)
  435. cached_resolve_pqueue = smartlist_new();
  436. resolve->expire = expires;
  437. smartlist_pqueue_add(cached_resolve_pqueue,
  438. compare_cached_resolves_by_expiry_,
  439. STRUCT_OFFSET(cached_resolve_t, minheap_idx),
  440. resolve);
  441. }
  442. /** Free all storage held in the DNS cache and related structures. */
  443. void
  444. dns_free_all(void)
  445. {
  446. cached_resolve_t **ptr, **next, *item;
  447. assert_cache_ok();
  448. if (cached_resolve_pqueue) {
  449. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  450. {
  451. if (res->state == CACHE_STATE_DONE)
  452. free_cached_resolve_(res);
  453. });
  454. }
  455. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  456. item = *ptr;
  457. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  458. free_cached_resolve_(item);
  459. }
  460. HT_CLEAR(cache_map, &cache_root);
  461. smartlist_free(cached_resolve_pqueue);
  462. cached_resolve_pqueue = NULL;
  463. tor_free(resolv_conf_fname);
  464. }
  465. /** Remove every cached_resolve whose <b>expire</b> time is before or
  466. * equal to <b>now</b> from the cache. */
  467. static void
  468. purge_expired_resolves(time_t now)
  469. {
  470. cached_resolve_t *resolve, *removed;
  471. pending_connection_t *pend;
  472. edge_connection_t *pendconn;
  473. assert_cache_ok();
  474. if (!cached_resolve_pqueue)
  475. return;
  476. while (smartlist_len(cached_resolve_pqueue)) {
  477. resolve = smartlist_get(cached_resolve_pqueue, 0);
  478. if (resolve->expire > now)
  479. break;
  480. smartlist_pqueue_pop(cached_resolve_pqueue,
  481. compare_cached_resolves_by_expiry_,
  482. STRUCT_OFFSET(cached_resolve_t, minheap_idx));
  483. if (resolve->state == CACHE_STATE_PENDING) {
  484. log_debug(LD_EXIT,
  485. "Expiring a dns resolve %s that's still pending. Forgot to "
  486. "cull it? DNS resolve didn't tell us about the timeout?",
  487. escaped_safe_str(resolve->address));
  488. } else if (resolve->state == CACHE_STATE_CACHED) {
  489. log_debug(LD_EXIT,
  490. "Forgetting old cached resolve (address %s, expires %lu)",
  491. escaped_safe_str(resolve->address),
  492. (unsigned long)resolve->expire);
  493. tor_assert(!resolve->pending_connections);
  494. } else {
  495. tor_assert(resolve->state == CACHE_STATE_DONE);
  496. tor_assert(!resolve->pending_connections);
  497. }
  498. if (resolve->pending_connections) {
  499. log_debug(LD_EXIT,
  500. "Closing pending connections on timed-out DNS resolve!");
  501. while (resolve->pending_connections) {
  502. pend = resolve->pending_connections;
  503. resolve->pending_connections = pend->next;
  504. /* Connections should only be pending if they have no socket. */
  505. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  506. pendconn = pend->conn;
  507. if (!pendconn->base_.marked_for_close) {
  508. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
  509. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  510. connection_free(TO_CONN(pendconn));
  511. }
  512. tor_free(pend);
  513. }
  514. }
  515. if (resolve->state == CACHE_STATE_CACHED ||
  516. resolve->state == CACHE_STATE_PENDING) {
  517. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  518. if (removed != resolve) {
  519. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  520. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  521. resolve->address, (void*)resolve,
  522. removed ? removed->address : "NULL", (void*)removed);
  523. }
  524. tor_assert(removed == resolve);
  525. } else {
  526. /* This should be in state DONE. Make sure it's not in the cache. */
  527. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  528. tor_assert(tmp != resolve);
  529. }
  530. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  531. tor_free(resolve->result_ptr.hostname);
  532. resolve->magic = 0xF0BBF0BB;
  533. tor_free(resolve);
  534. }
  535. assert_cache_ok();
  536. }
  537. /* argument for send_resolved_cell only, meaning "let the answer type be ipv4
  538. * or ipv6 depending on the connection's address". */
  539. #define RESOLVED_TYPE_AUTO 0xff
  540. /** Send a response to the RESOLVE request of a connection.
  541. * <b>answer_type</b> must be one of
  542. * RESOLVED_TYPE_(IPV4|IPV6|ERROR|ERROR_TRANSIENT|AUTO).
  543. *
  544. * If <b>circ</b> is provided, and we have a cached answer, send the
  545. * answer back along circ; otherwise, send the answer back along
  546. * <b>conn</b>'s attached circuit.
  547. */
  548. static void
  549. send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
  550. {
  551. char buf[RELAY_PAYLOAD_SIZE];
  552. size_t buflen;
  553. uint32_t ttl;
  554. if (answer_type == RESOLVED_TYPE_AUTO) {
  555. sa_family_t family = tor_addr_family(&conn->base_.addr);
  556. if (family == AF_INET)
  557. answer_type = RESOLVED_TYPE_IPV4;
  558. else if (family == AF_INET6)
  559. answer_type = RESOLVED_TYPE_IPV6;
  560. else
  561. answer_type = RESOLVED_TYPE_ERROR_TRANSIENT;
  562. }
  563. buf[0] = answer_type;
  564. ttl = dns_clip_ttl(conn->address_ttl);
  565. switch (answer_type)
  566. {
  567. case RESOLVED_TYPE_IPV4:
  568. buf[1] = 4;
  569. set_uint32(buf+2, tor_addr_to_ipv4n(&conn->base_.addr));
  570. set_uint32(buf+6, htonl(ttl));
  571. buflen = 10;
  572. break;
  573. case RESOLVED_TYPE_IPV6:
  574. {
  575. const uint8_t *bytes = tor_addr_to_in6_addr8(&conn->base_.addr);
  576. buf[1] = 16;
  577. memcpy(buf+2, bytes, 16);
  578. set_uint32(buf+18, htonl(ttl));
  579. buflen = 22;
  580. }
  581. break;
  582. case RESOLVED_TYPE_ERROR_TRANSIENT:
  583. case RESOLVED_TYPE_ERROR:
  584. {
  585. const char *errmsg = "Error resolving hostname";
  586. size_t msglen = strlen(errmsg);
  587. buf[1] = msglen;
  588. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  589. set_uint32(buf+2+msglen, htonl(ttl));
  590. buflen = 6+msglen;
  591. break;
  592. }
  593. default:
  594. tor_assert(0);
  595. return;
  596. }
  597. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  598. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  599. }
  600. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  601. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  602. * The answer type will be RESOLVED_HOSTNAME.
  603. *
  604. * If <b>circ</b> is provided, and we have a cached answer, send the
  605. * answer back along circ; otherwise, send the answer back along
  606. * <b>conn</b>'s attached circuit.
  607. */
  608. static void
  609. send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
  610. {
  611. char buf[RELAY_PAYLOAD_SIZE];
  612. size_t buflen;
  613. uint32_t ttl;
  614. size_t namelen = strlen(hostname);
  615. tor_assert(hostname);
  616. tor_assert(namelen < 256);
  617. ttl = dns_clip_ttl(conn->address_ttl);
  618. buf[0] = RESOLVED_TYPE_HOSTNAME;
  619. buf[1] = (uint8_t)namelen;
  620. memcpy(buf+2, hostname, namelen);
  621. set_uint32(buf+2+namelen, htonl(ttl));
  622. buflen = 2+namelen+4;
  623. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  624. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  625. // log_notice(LD_EXIT, "Sent");
  626. }
  627. /** See if we have a cache entry for <b>exitconn</b>-\>address. If so,
  628. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  629. * If resolve failed, free exitconn and return -1.
  630. *
  631. * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
  632. * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
  633. * need to send back an END cell, since connection_exit_begin_conn will
  634. * do that for us.)
  635. *
  636. * If we have a cached answer, send the answer back along <b>exitconn</b>'s
  637. * circuit.
  638. *
  639. * Else, if seen before and pending, add conn to the pending list,
  640. * and return 0.
  641. *
  642. * Else, if not seen before, add conn to pending list, hand to
  643. * dns farm, and return 0.
  644. *
  645. * Exitconn's on_circuit field must be set, but exitconn should not
  646. * yet be linked onto the n_streams/resolving_streams list of that circuit.
  647. * On success, link the connection to n_streams if it's an exit connection.
  648. * On "pending", link the connection to resolving streams. Otherwise,
  649. * clear its on_circuit field.
  650. */
  651. int
  652. dns_resolve(edge_connection_t *exitconn)
  653. {
  654. or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
  655. int is_resolve, r;
  656. int made_connection_pending = 0;
  657. char *hostname = NULL;
  658. is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
  659. r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
  660. &made_connection_pending);
  661. switch (r) {
  662. case 1:
  663. /* We got an answer without a lookup -- either the answer was
  664. * cached, or it was obvious (like an IP address). */
  665. if (is_resolve) {
  666. /* Send the answer back right now, and detach. */
  667. if (hostname)
  668. send_resolved_hostname_cell(exitconn, hostname);
  669. else
  670. send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO);
  671. exitconn->on_circuit = NULL;
  672. } else {
  673. /* Add to the n_streams list; the calling function will send back a
  674. * connected cell. */
  675. exitconn->next_stream = oncirc->n_streams;
  676. oncirc->n_streams = exitconn;
  677. }
  678. break;
  679. case 0:
  680. /* The request is pending: add the connection into the linked list of
  681. * resolving_streams on this circuit. */
  682. exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
  683. exitconn->next_stream = oncirc->resolving_streams;
  684. oncirc->resolving_streams = exitconn;
  685. break;
  686. case -2:
  687. case -1:
  688. /* The request failed before it could start: cancel this connection,
  689. * and stop everybody waiting for the same connection. */
  690. if (is_resolve) {
  691. send_resolved_cell(exitconn,
  692. (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  693. }
  694. exitconn->on_circuit = NULL;
  695. dns_cancel_pending_resolve(exitconn->base_.address);
  696. if (!made_connection_pending && !exitconn->base_.marked_for_close) {
  697. /* If we made the connection pending, then we freed it already in
  698. * dns_cancel_pending_resolve(). If we marked it for close, it'll
  699. * get freed from the main loop. Otherwise, can free it now. */
  700. connection_free(TO_CONN(exitconn));
  701. }
  702. break;
  703. default:
  704. tor_assert(0);
  705. }
  706. tor_free(hostname);
  707. return r;
  708. }
  709. /** Helper function for dns_resolve: same functionality, but does not handle:
  710. * - marking connections on error and clearing their on_circuit
  711. * - linking connections to n_streams/resolving_streams,
  712. * - sending resolved cells if we have an answer/error right away,
  713. *
  714. * Return -2 on a transient error. If it's a reverse resolve and it's
  715. * successful, sets *<b>hostname_out</b> to a newly allocated string
  716. * holding the cached reverse DNS value.
  717. *
  718. * Set *<b>made_connection_pending_out</b> to true if we have placed
  719. * <b>exitconn</b> on the list of pending connections for some resolve; set it
  720. * to false otherwise.
  721. */
  722. static int
  723. dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
  724. or_circuit_t *oncirc, char **hostname_out,
  725. int *made_connection_pending_out)
  726. {
  727. cached_resolve_t *resolve;
  728. cached_resolve_t search;
  729. pending_connection_t *pending_connection;
  730. int is_reverse = 0;
  731. tor_addr_t addr;
  732. time_t now = time(NULL);
  733. int r;
  734. assert_connection_ok(TO_CONN(exitconn), 0);
  735. tor_assert(!SOCKET_OK(exitconn->base_.s));
  736. assert_cache_ok();
  737. tor_assert(oncirc);
  738. *made_connection_pending_out = 0;
  739. /* first check if exitconn->base_.address is an IP. If so, we already
  740. * know the answer. */
  741. if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
  742. if (tor_addr_family(&addr) == AF_INET ||
  743. tor_addr_family(&addr) == AF_INET6) {
  744. tor_addr_copy(&exitconn->base_.addr, &addr);
  745. exitconn->address_ttl = DEFAULT_DNS_TTL;
  746. return 1;
  747. } else {
  748. /* XXXX unspec? Bogus? */
  749. return -1;
  750. }
  751. }
  752. /* If we're a non-exit, don't even do DNS lookups. */
  753. if (router_my_exit_policy_is_reject_star())
  754. return -1;
  755. if (address_is_invalid_destination(exitconn->base_.address, 0)) {
  756. log(LOG_PROTOCOL_WARN, LD_EXIT,
  757. "Rejecting invalid destination address %s",
  758. escaped_safe_str(exitconn->base_.address));
  759. return -1;
  760. }
  761. /* then take this opportunity to see if there are any expired
  762. * resolves in the hash table. */
  763. purge_expired_resolves(now);
  764. /* lower-case exitconn->base_.address, so it's in canonical form */
  765. tor_strlower(exitconn->base_.address);
  766. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  767. * .in-addr.arpa address but this isn't a resolve request, kill the
  768. * connection.
  769. */
  770. if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
  771. AF_UNSPEC, 0)) != 0) {
  772. if (r == 1) {
  773. is_reverse = 1;
  774. if (tor_addr_is_internal(&addr, 0)) /* internal address? */
  775. return -1;
  776. }
  777. if (!is_reverse || !is_resolve) {
  778. if (!is_reverse)
  779. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  780. escaped_safe_str(exitconn->base_.address));
  781. else if (!is_resolve)
  782. log_info(LD_EXIT,
  783. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  784. "sending error.",
  785. escaped_safe_str(exitconn->base_.address));
  786. return -1;
  787. }
  788. //log_notice(LD_EXIT, "Looks like an address %s",
  789. //exitconn->base_.address);
  790. }
  791. exitconn->is_reverse_dns_lookup = is_reverse;
  792. /* now check the hash table to see if 'address' is already there. */
  793. strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
  794. resolve = HT_FIND(cache_map, &cache_root, &search);
  795. if (resolve && resolve->expire > now) { /* already there */
  796. switch (resolve->state) {
  797. case CACHE_STATE_PENDING:
  798. /* add us to the pending list */
  799. pending_connection = tor_malloc_zero(
  800. sizeof(pending_connection_t));
  801. pending_connection->conn = exitconn;
  802. pending_connection->next = resolve->pending_connections;
  803. resolve->pending_connections = pending_connection;
  804. *made_connection_pending_out = 1;
  805. log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  806. "resolve of %s", exitconn->base_.s,
  807. escaped_safe_str(exitconn->base_.address));
  808. return 0;
  809. case CACHE_STATE_CACHED:
  810. log_debug(LD_EXIT,"Connection (fd %d) found cachedresult for %s",
  811. exitconn->base_.s,
  812. escaped_safe_str(resolve->address));
  813. return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
  814. case CACHE_STATE_DONE:
  815. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  816. tor_fragile_assert();
  817. }
  818. tor_assert(0);
  819. }
  820. tor_assert(!resolve);
  821. /* not there, need to add it */
  822. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  823. resolve->magic = CACHED_RESOLVE_MAGIC;
  824. resolve->state = CACHE_STATE_PENDING;
  825. resolve->minheap_idx = -1;
  826. strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
  827. /* add this connection to the pending list */
  828. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  829. pending_connection->conn = exitconn;
  830. resolve->pending_connections = pending_connection;
  831. *made_connection_pending_out = 1;
  832. /* Add this resolve to the cache and priority queue. */
  833. HT_INSERT(cache_map, &cache_root, resolve);
  834. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  835. log_debug(LD_EXIT,"Launching %s.",
  836. escaped_safe_str(exitconn->base_.address));
  837. assert_cache_ok();
  838. return launch_resolve(resolve);
  839. }
  840. /** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
  841. * <b>resolve</b> whose DNS lookups have all succeeded or failed, update the
  842. * appropriate fields (address_ttl and addr) of <b>exitconn</b>.
  843. *
  844. * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
  845. * copy of the name resulting hostname.
  846. *
  847. * Return -2 on a transient error, -1 on a permenent error, and 1 on
  848. * a successful lookup.
  849. */
  850. static int
  851. set_exitconn_info_from_resolve(edge_connection_t *exitconn,
  852. const cached_resolve_t *resolve,
  853. char **hostname_out)
  854. {
  855. int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
  856. tor_assert(exitconn);
  857. tor_assert(resolve);
  858. if (exitconn->is_reverse_dns_lookup) {
  859. exitconn->address_ttl = resolve->ttl_hostname;
  860. if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
  861. *hostname_out = tor_strdup(resolve->result_ptr.hostname);
  862. return 1;
  863. } else {
  864. return -1;
  865. }
  866. }
  867. /* If we're here then the connection wants one or either of ipv4, ipv6, and
  868. * we can give it one or both. */
  869. ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
  870. ! (exitconn->begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
  871. ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
  872. (exitconn->begincell_flags & BEGIN_FLAG_IPV6_OK) &&
  873. get_options()->IPv6Exit;
  874. /* Now decide which one to actually give. */
  875. if (ipv4_ok && ipv6_ok) {
  876. /* If we have both, see if our exit policy has an opinion. */
  877. const uint16_t port = exitconn->base_.port;
  878. int ipv4_allowed, ipv6_allowed;
  879. tor_addr_t a4, a6;
  880. tor_addr_from_ipv4h(&a4, resolve->result_ipv4.addr_ipv4);
  881. tor_addr_from_in6(&a6, &resolve->result_ipv6.addr_ipv6);
  882. ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
  883. ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
  884. if (ipv4_allowed && !ipv6_allowed) {
  885. answer_with_ipv4 = 1;
  886. } else if (ipv6_allowed && !ipv4_allowed) {
  887. answer_with_ipv4 = 0;
  888. } else {
  889. /* Our exit policy would permit both. Answer with whichever the user
  890. * prefers */
  891. answer_with_ipv4 = !(exitconn->begincell_flags &
  892. BEGIN_FLAG_IPV6_PREFERRED);
  893. }
  894. } else {
  895. /* Otherwise if one is okay, send it back. */
  896. if (ipv4_ok) {
  897. answer_with_ipv4 = 1;
  898. } else if (ipv6_ok) {
  899. answer_with_ipv4 = 0;
  900. } else {
  901. /* Neither one was okay. Choose based on user preference. */
  902. answer_with_ipv4 = !(exitconn->begincell_flags &
  903. BEGIN_FLAG_IPV6_PREFERRED);
  904. }
  905. }
  906. /* Finally, we write the answer back. */
  907. r = 1;
  908. if (answer_with_ipv4) {
  909. if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
  910. tor_addr_from_ipv4h(&exitconn->base_.addr,
  911. resolve->result_ipv4.addr_ipv4);
  912. } else {
  913. r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
  914. }
  915. exitconn->address_ttl = resolve->ttl_ipv4;
  916. } else {
  917. if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
  918. tor_addr_from_in6(&exitconn->base_.addr,
  919. &resolve->result_ipv6.addr_ipv6);
  920. } else {
  921. r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
  922. }
  923. exitconn->address_ttl = resolve->ttl_ipv6;
  924. }
  925. return r;
  926. }
  927. /** Log an error and abort if conn is waiting for a DNS resolve.
  928. */
  929. void
  930. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  931. {
  932. pending_connection_t *pend;
  933. cached_resolve_t search;
  934. #if 1
  935. cached_resolve_t *resolve;
  936. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  937. resolve = HT_FIND(cache_map, &cache_root, &search);
  938. if (!resolve)
  939. return;
  940. for (pend = resolve->pending_connections; pend; pend = pend->next) {
  941. tor_assert(pend->conn != conn);
  942. }
  943. #else
  944. cached_resolve_t **resolve;
  945. HT_FOREACH(resolve, cache_map, &cache_root) {
  946. for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
  947. tor_assert(pend->conn != conn);
  948. }
  949. }
  950. #endif
  951. }
  952. /** Log an error and abort if any connection waiting for a DNS resolve is
  953. * corrupted. */
  954. void
  955. assert_all_pending_dns_resolves_ok(void)
  956. {
  957. pending_connection_t *pend;
  958. cached_resolve_t **resolve;
  959. HT_FOREACH(resolve, cache_map, &cache_root) {
  960. for (pend = (*resolve)->pending_connections;
  961. pend;
  962. pend = pend->next) {
  963. assert_connection_ok(TO_CONN(pend->conn), 0);
  964. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  965. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  966. }
  967. }
  968. }
  969. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  970. */
  971. void
  972. connection_dns_remove(edge_connection_t *conn)
  973. {
  974. pending_connection_t *pend, *victim;
  975. cached_resolve_t search;
  976. cached_resolve_t *resolve;
  977. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  978. tor_assert(conn->base_.state == EXIT_CONN_STATE_RESOLVING);
  979. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  980. resolve = HT_FIND(cache_map, &cache_root, &search);
  981. if (!resolve) {
  982. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  983. escaped_safe_str(conn->base_.address));
  984. return;
  985. }
  986. tor_assert(resolve->pending_connections);
  987. assert_connection_ok(TO_CONN(conn),0);
  988. pend = resolve->pending_connections;
  989. if (pend->conn == conn) {
  990. resolve->pending_connections = pend->next;
  991. tor_free(pend);
  992. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  993. "for resolve of %s",
  994. conn->base_.s,
  995. escaped_safe_str(conn->base_.address));
  996. return;
  997. } else {
  998. for ( ; pend->next; pend = pend->next) {
  999. if (pend->next->conn == conn) {
  1000. victim = pend->next;
  1001. pend->next = victim->next;
  1002. tor_free(victim);
  1003. log_debug(LD_EXIT,
  1004. "Connection (fd %d) no longer waiting for resolve of %s",
  1005. conn->base_.s, escaped_safe_str(conn->base_.address));
  1006. return; /* more are pending */
  1007. }
  1008. }
  1009. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  1010. }
  1011. }
  1012. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  1013. * the resolve for <b>address</b> itself, and remove any cached results for
  1014. * <b>address</b> from the cache.
  1015. */
  1016. void
  1017. dns_cancel_pending_resolve(const char *address)
  1018. {
  1019. pending_connection_t *pend;
  1020. cached_resolve_t search;
  1021. cached_resolve_t *resolve, *tmp;
  1022. edge_connection_t *pendconn;
  1023. circuit_t *circ;
  1024. strlcpy(search.address, address, sizeof(search.address));
  1025. resolve = HT_FIND(cache_map, &cache_root, &search);
  1026. if (!resolve)
  1027. return;
  1028. if (resolve->state != CACHE_STATE_PENDING) {
  1029. /* We can get into this state if we never actually created the pending
  1030. * resolve, due to finding an earlier cached error or something. Just
  1031. * ignore it. */
  1032. if (resolve->pending_connections) {
  1033. log_warn(LD_BUG,
  1034. "Address %s is not pending but has pending connections!",
  1035. escaped_safe_str(address));
  1036. tor_fragile_assert();
  1037. }
  1038. return;
  1039. }
  1040. if (!resolve->pending_connections) {
  1041. log_warn(LD_BUG,
  1042. "Address %s is pending but has no pending connections!",
  1043. escaped_safe_str(address));
  1044. tor_fragile_assert();
  1045. return;
  1046. }
  1047. tor_assert(resolve->pending_connections);
  1048. /* mark all pending connections to fail */
  1049. log_debug(LD_EXIT,
  1050. "Failing all connections waiting on DNS resolve of %s",
  1051. escaped_safe_str(address));
  1052. while (resolve->pending_connections) {
  1053. pend = resolve->pending_connections;
  1054. pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1055. pendconn = pend->conn;
  1056. assert_connection_ok(TO_CONN(pendconn), 0);
  1057. tor_assert(!SOCKET_OK(pendconn->base_.s));
  1058. if (!pendconn->base_.marked_for_close) {
  1059. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1060. }
  1061. circ = circuit_get_by_edge_conn(pendconn);
  1062. if (circ)
  1063. circuit_detach_stream(circ, pendconn);
  1064. if (!pendconn->base_.marked_for_close)
  1065. connection_free(TO_CONN(pendconn));
  1066. resolve->pending_connections = pend->next;
  1067. tor_free(pend);
  1068. }
  1069. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  1070. if (tmp != resolve) {
  1071. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  1072. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1073. resolve->address, (void*)resolve,
  1074. tmp ? tmp->address : "NULL", (void*)tmp);
  1075. }
  1076. tor_assert(tmp == resolve);
  1077. resolve->state = CACHE_STATE_DONE;
  1078. }
  1079. /** Return true iff <b>address</b> is one of the addresses we use to verify
  1080. * that well-known sites aren't being hijacked by our DNS servers. */
  1081. static INLINE int
  1082. is_test_address(const char *address)
  1083. {
  1084. const or_options_t *options = get_options();
  1085. return options->ServerDNSTestAddresses &&
  1086. smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
  1087. }
  1088. /** Called on the OR side when the eventdns library tells us the outcome of a
  1089. * single DNS resolve: remember the answer, and tell all pending connections
  1090. * about the result of the lookup if the lookup is now done. (<b>address</b>
  1091. * is a NUL-terminated string containing the address to look up;
  1092. * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
  1093. * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
  1094. * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
  1095. * <b>ttl</b> is the time-to-live of this answer, in seconds.)
  1096. */
  1097. static void
  1098. dns_found_answer(const char *address, uint8_t query_type,
  1099. int dns_answer,
  1100. const tor_addr_t *addr,
  1101. const char *hostname, uint32_t ttl)
  1102. {
  1103. cached_resolve_t search;
  1104. cached_resolve_t *resolve;
  1105. assert_cache_ok();
  1106. strlcpy(search.address, address, sizeof(search.address));
  1107. resolve = HT_FIND(cache_map, &cache_root, &search);
  1108. if (!resolve) {
  1109. int is_test_addr = is_test_address(address);
  1110. if (!is_test_addr)
  1111. log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
  1112. escaped_safe_str(address));
  1113. return;
  1114. }
  1115. assert_resolve_ok(resolve);
  1116. if (resolve->state != CACHE_STATE_PENDING) {
  1117. /* XXXX Maybe update addr? or check addr for consistency? Or let
  1118. * VALID replace FAILED? */
  1119. int is_test_addr = is_test_address(address);
  1120. if (!is_test_addr)
  1121. log_notice(LD_EXIT,
  1122. "Resolved %s which was already resolved; ignoring",
  1123. escaped_safe_str(address));
  1124. tor_assert(resolve->pending_connections == NULL);
  1125. return;
  1126. }
  1127. cached_resolve_add_answer(resolve, query_type, dns_answer,
  1128. addr, hostname, ttl);
  1129. if (cached_resolve_have_all_answers(resolve)) {
  1130. inform_pending_connections(resolve);
  1131. make_pending_resolve_cached(resolve);
  1132. }
  1133. }
  1134. /** Given a pending cached_resolve_t that we just finished resolving,
  1135. * inform every connection that was waiting for the outcome of that
  1136. * resolution. */
  1137. static void
  1138. inform_pending_connections(cached_resolve_t *resolve)
  1139. {
  1140. pending_connection_t *pend;
  1141. edge_connection_t *pendconn;
  1142. int r;
  1143. while (resolve->pending_connections) {
  1144. char *hostname = NULL;
  1145. pend = resolve->pending_connections;
  1146. pendconn = pend->conn; /* don't pass complex things to the
  1147. connection_mark_for_close macro */
  1148. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  1149. if (pendconn->base_.marked_for_close) {
  1150. /* prevent double-remove. */
  1151. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1152. resolve->pending_connections = pend->next;
  1153. tor_free(pend);
  1154. continue;
  1155. }
  1156. r = set_exitconn_info_from_resolve(pendconn,
  1157. resolve,
  1158. &hostname);
  1159. if (r < 0) {
  1160. /* prevent double-remove. */
  1161. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1162. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1163. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1164. /* This detach must happen after we send the end cell. */
  1165. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1166. } else {
  1167. send_resolved_cell(pendconn, r == -1 ?
  1168. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  1169. /* This detach must happen after we send the resolved cell. */
  1170. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1171. }
  1172. connection_free(TO_CONN(pendconn));
  1173. } else {
  1174. circuit_t *circ;
  1175. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1176. /* prevent double-remove. */
  1177. pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  1178. circ = circuit_get_by_edge_conn(pend->conn);
  1179. tor_assert(circ);
  1180. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1181. /* unlink pend->conn from resolving_streams, */
  1182. circuit_detach_stream(circ, pend->conn);
  1183. /* and link it to n_streams */
  1184. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1185. pend->conn->on_circuit = circ;
  1186. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  1187. connection_exit_connect(pend->conn);
  1188. } else {
  1189. /* prevent double-remove. This isn't really an accurate state,
  1190. * but it does the right thing. */
  1191. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1192. if (pendconn->is_reverse_dns_lookup)
  1193. send_resolved_hostname_cell(pendconn, hostname);
  1194. else
  1195. send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO);
  1196. circ = circuit_get_by_edge_conn(pendconn);
  1197. tor_assert(circ);
  1198. circuit_detach_stream(circ, pendconn);
  1199. connection_free(TO_CONN(pendconn));
  1200. }
  1201. }
  1202. resolve->pending_connections = pend->next;
  1203. tor_free(pend);
  1204. }
  1205. }
  1206. /** Remove a pending cached_resolve_t from the hashtable, and add a
  1207. * corresponding cached cached_resolve_t.
  1208. *
  1209. * This function is only necessary because of the perversity of our
  1210. * cache timeout code; see inline comment for ideas on eliminating it.
  1211. **/
  1212. static void
  1213. make_pending_resolve_cached(cached_resolve_t *resolve)
  1214. {
  1215. cached_resolve_t *removed;
  1216. resolve->state = CACHE_STATE_DONE;
  1217. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  1218. if (removed != resolve) {
  1219. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  1220. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1221. resolve->address, (void*)resolve,
  1222. removed ? removed->address : "NULL", (void*)removed);
  1223. }
  1224. assert_resolve_ok(resolve);
  1225. assert_cache_ok();
  1226. /* The resolve will eventually just hit the time-out in the expiry queue and
  1227. * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
  1228. * way. XXXXX we could do better!*/
  1229. {
  1230. cached_resolve_t *new_resolve = tor_memdup(resolve,
  1231. sizeof(cached_resolve_t));
  1232. uint32_t ttl = UINT32_MAX;
  1233. new_resolve->expire = 0; /* So that set_expiry won't croak. */
  1234. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  1235. new_resolve->result_ptr.hostname =
  1236. tor_strdup(resolve->result_ptr.hostname);
  1237. new_resolve->state = CACHE_STATE_CACHED;
  1238. assert_resolve_ok(new_resolve);
  1239. HT_INSERT(cache_map, &cache_root, new_resolve);
  1240. if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
  1241. resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
  1242. resolve->ttl_ipv4 < ttl)
  1243. ttl = resolve->ttl_ipv4;
  1244. if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
  1245. resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
  1246. resolve->ttl_ipv6 < ttl)
  1247. ttl = resolve->ttl_ipv6;
  1248. if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
  1249. resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
  1250. resolve->ttl_hostname < ttl)
  1251. ttl = resolve->ttl_hostname;
  1252. set_expiry(new_resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  1253. }
  1254. assert_cache_ok();
  1255. }
  1256. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1257. * a transient failure. */
  1258. static int
  1259. evdns_err_is_transient(int err)
  1260. {
  1261. switch (err)
  1262. {
  1263. case DNS_ERR_SERVERFAILED:
  1264. case DNS_ERR_TRUNCATED:
  1265. case DNS_ERR_TIMEOUT:
  1266. return 1;
  1267. default:
  1268. return 0;
  1269. }
  1270. }
  1271. /** Configure eventdns nameservers if force is true, or if the configuration
  1272. * has changed since the last time we called this function, or if we failed on
  1273. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1274. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1275. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1276. * -1 on failure. */
  1277. static int
  1278. configure_nameservers(int force)
  1279. {
  1280. const or_options_t *options;
  1281. const char *conf_fname;
  1282. struct stat st;
  1283. int r;
  1284. options = get_options();
  1285. conf_fname = options->ServerDNSResolvConfFile;
  1286. #ifndef _WIN32
  1287. if (!conf_fname)
  1288. conf_fname = "/etc/resolv.conf";
  1289. #endif
  1290. if (!the_evdns_base) {
  1291. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  1292. log_err(LD_BUG, "Couldn't create an evdns_base");
  1293. return -1;
  1294. }
  1295. }
  1296. #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  1297. if (! tor_addr_is_null(&options->OutboundBindAddressIPv4_)) {
  1298. int socklen;
  1299. struct sockaddr_storage ss;
  1300. socklen = tor_addr_to_sockaddr(&options->OutboundBindAddressIPv4_, 0,
  1301. (struct sockaddr *)&ss, sizeof(ss));
  1302. if (socklen <= 0) {
  1303. log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
  1304. " Ignoring.");
  1305. } else {
  1306. evdns_base_set_default_outgoing_bind_address(the_evdns_base,
  1307. (struct sockaddr *)&ss,
  1308. socklen);
  1309. }
  1310. }
  1311. #endif
  1312. evdns_set_log_fn(evdns_log_cb);
  1313. if (conf_fname) {
  1314. if (stat(conf_fname, &st)) {
  1315. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1316. conf_fname, strerror(errno));
  1317. goto err;
  1318. }
  1319. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1320. && st.st_mtime == resolv_conf_mtime) {
  1321. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1322. return 0;
  1323. }
  1324. if (nameservers_configured) {
  1325. evdns_base_search_clear(the_evdns_base);
  1326. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1327. }
  1328. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1329. if ((r = evdns_base_resolv_conf_parse(the_evdns_base,
  1330. DNS_OPTIONS_ALL, conf_fname))) {
  1331. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  1332. conf_fname, conf_fname, r);
  1333. goto err;
  1334. }
  1335. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1336. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1337. goto err;
  1338. }
  1339. tor_free(resolv_conf_fname);
  1340. resolv_conf_fname = tor_strdup(conf_fname);
  1341. resolv_conf_mtime = st.st_mtime;
  1342. if (nameservers_configured)
  1343. evdns_base_resume(the_evdns_base);
  1344. }
  1345. #ifdef _WIN32
  1346. else {
  1347. if (nameservers_configured) {
  1348. evdns_base_search_clear(the_evdns_base);
  1349. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1350. }
  1351. if (evdns_base_config_windows_nameservers(the_evdns_base)) {
  1352. log_warn(LD_EXIT,"Could not config nameservers.");
  1353. goto err;
  1354. }
  1355. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1356. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1357. "your Windows configuration.");
  1358. goto err;
  1359. }
  1360. if (nameservers_configured)
  1361. evdns_base_resume(the_evdns_base);
  1362. tor_free(resolv_conf_fname);
  1363. resolv_conf_mtime = 0;
  1364. }
  1365. #endif
  1366. #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
  1367. if (evdns_base_count_nameservers(the_evdns_base) == 1) {
  1368. SET("max-timeouts:", "16");
  1369. SET("timeout:", "10");
  1370. } else {
  1371. SET("max-timeouts:", "3");
  1372. SET("timeout:", "5");
  1373. }
  1374. if (options->ServerDNSRandomizeCase)
  1375. SET("randomize-case:", "1");
  1376. else
  1377. SET("randomize-case:", "0");
  1378. #undef SET
  1379. dns_servers_relaunch_checks();
  1380. nameservers_configured = 1;
  1381. if (nameserver_config_failed) {
  1382. nameserver_config_failed = 0;
  1383. /* XXX the three calls to republish the descriptor might be producing
  1384. * descriptors that are only cosmetically different, especially on
  1385. * non-exit relays! -RD */
  1386. mark_my_descriptor_dirty("dns resolvers back");
  1387. }
  1388. return 0;
  1389. err:
  1390. nameservers_configured = 0;
  1391. if (! nameserver_config_failed) {
  1392. nameserver_config_failed = 1;
  1393. mark_my_descriptor_dirty("dns resolvers failed");
  1394. }
  1395. return -1;
  1396. }
  1397. /** For eventdns: Called when we get an answer for a request we launched.
  1398. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1399. */
  1400. static void
  1401. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1402. void *arg)
  1403. {
  1404. char *arg_ = arg;
  1405. uint8_t orig_query_type = arg_[0];
  1406. char *string_address = arg_ + 1;
  1407. tor_addr_t addr;
  1408. const char *hostname = NULL;
  1409. int was_wildcarded = 0;
  1410. tor_addr_make_unspec(&addr); /*WRONG WRONG WRONG XXXX XXXXX IPV6 prop208*/
  1411. /* Keep track of whether IPv6 is working */
  1412. if (type == DNS_IPv6_AAAA) {
  1413. if (result == DNS_ERR_TIMEOUT) {
  1414. ++n_ipv6_timeouts;
  1415. }
  1416. if (n_ipv6_timeouts > 10 &&
  1417. n_ipv6_timeouts > n_ipv6_requests_made / 2) {
  1418. if (! dns_is_broken_for_ipv6) {
  1419. log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
  1420. "have timed out. I'm going to assume I can't get AAAA "
  1421. "responses.");
  1422. dns_is_broken_for_ipv6 = 1;
  1423. }
  1424. }
  1425. }
  1426. if (result == DNS_ERR_NONE) {
  1427. if (type == DNS_IPv4_A && count) {
  1428. char answer_buf[INET_NTOA_BUF_LEN+1];
  1429. char *escaped_address;
  1430. uint32_t *addrs = addresses;
  1431. tor_addr_from_ipv4n(&addr, addrs[0]);
  1432. tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
  1433. escaped_address = esc_for_log(string_address);
  1434. if (answer_is_wildcarded(answer_buf)) {
  1435. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1436. "address %s; treating as a failure.",
  1437. safe_str(escaped_address),
  1438. escaped_safe_str(answer_buf));
  1439. was_wildcarded = 1;
  1440. tor_addr_make_null(&addr, AF_INET); /* ???? */
  1441. result = DNS_ERR_NOTEXIST;
  1442. } else {
  1443. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1444. safe_str(escaped_address),
  1445. escaped_safe_str(answer_buf));
  1446. }
  1447. tor_free(escaped_address);
  1448. } else if (type == DNS_IPv6_AAAA && count) {
  1449. char answer_buf[TOR_ADDR_BUF_LEN];
  1450. char *escaped_address;
  1451. struct in6_addr *addrs = addresses;
  1452. tor_addr_from_in6(&addr, &addrs[0]);
  1453. tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
  1454. escaped_address = esc_for_log(string_address);
  1455. if (answer_is_wildcarded(answer_buf)) {
  1456. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1457. "address %s; treating as a failure.",
  1458. safe_str(escaped_address),
  1459. escaped_safe_str(answer_buf));
  1460. was_wildcarded = 1;
  1461. tor_addr_make_unspec(&addr); /* WRONG WRONG ETC XXXXXXXX */
  1462. result = DNS_ERR_NOTEXIST;
  1463. } else {
  1464. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1465. safe_str(escaped_address),
  1466. escaped_safe_str(answer_buf));
  1467. }
  1468. tor_free(escaped_address);
  1469. } else if (type == DNS_PTR && count) {
  1470. char *escaped_address;
  1471. hostname = ((char**)addresses)[0];
  1472. escaped_address = esc_for_log(string_address);
  1473. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1474. safe_str(escaped_address),
  1475. escaped_safe_str(hostname));
  1476. tor_free(escaped_address);
  1477. } else if (count) {
  1478. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1479. escaped_safe_str(string_address));
  1480. } else {
  1481. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1482. escaped_safe_str(string_address));
  1483. }
  1484. }
  1485. if (was_wildcarded) {
  1486. if (is_test_address(string_address)) {
  1487. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1488. * server must really hate us. */
  1489. add_wildcarded_test_address(string_address);
  1490. }
  1491. }
  1492. if (orig_query_type && type && orig_query_type != type) {
  1493. log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
  1494. (int)orig_query_type, (int)type);
  1495. }
  1496. if (result != DNS_ERR_SHUTDOWN)
  1497. dns_found_answer(string_address, orig_query_type,
  1498. result, &addr, hostname, ttl);
  1499. tor_free(arg_);
  1500. }
  1501. /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
  1502. * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
  1503. * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
  1504. static int
  1505. launch_one_resolve(const char *address, uint8_t query_type,
  1506. const tor_addr_t *ptr_address)
  1507. {
  1508. const int options = get_options()->ServerDNSSearchDomains ? 0
  1509. : DNS_QUERY_NO_SEARCH;
  1510. const size_t addr_len = strlen(address);
  1511. struct evdns_request *req = 0;
  1512. char *addr = tor_malloc(addr_len + 2);
  1513. addr[0] = (char) query_type;
  1514. memcpy(addr+1, address, addr_len + 1);
  1515. switch (query_type) {
  1516. case DNS_IPv4_A:
  1517. req = evdns_base_resolve_ipv4(the_evdns_base,
  1518. address, options, evdns_callback, addr);
  1519. break;
  1520. case DNS_IPv6_AAAA:
  1521. req = evdns_base_resolve_ipv6(the_evdns_base,
  1522. address, options, evdns_callback, addr);
  1523. ++n_ipv6_requests_made;
  1524. break;
  1525. case DNS_PTR:
  1526. if (tor_addr_family(ptr_address) == AF_INET)
  1527. req = evdns_base_resolve_reverse(the_evdns_base,
  1528. tor_addr_to_in(ptr_address),
  1529. DNS_QUERY_NO_SEARCH,
  1530. evdns_callback, addr);
  1531. else if (tor_addr_family(ptr_address) == AF_INET6)
  1532. req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
  1533. tor_addr_to_in6(ptr_address),
  1534. DNS_QUERY_NO_SEARCH,
  1535. evdns_callback, addr);
  1536. else
  1537. log_warn(LD_BUG, "Called with PTR query and unexpected address family");
  1538. break;
  1539. default:
  1540. log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
  1541. break;
  1542. }
  1543. if (req) {
  1544. return 0;
  1545. } else {
  1546. tor_free(addr);
  1547. return -1;
  1548. }
  1549. }
  1550. /** For eventdns: start resolving as necessary to find the target for
  1551. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1552. * 0 on "resolve launched." */
  1553. static int
  1554. launch_resolve(cached_resolve_t *resolve)
  1555. {
  1556. tor_addr_t a;
  1557. int r;
  1558. if (get_options()->DisableNetwork)
  1559. return -1;
  1560. /* What? Nameservers not configured? Sounds like a bug. */
  1561. if (!nameservers_configured) {
  1562. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1563. "launched. Configuring.");
  1564. if (configure_nameservers(1) < 0) {
  1565. return -1;
  1566. }
  1567. }
  1568. r = tor_addr_parse_PTR_name(
  1569. &a, resolve->address, AF_UNSPEC, 0);
  1570. tor_assert(the_evdns_base);
  1571. if (r == 0) {
  1572. log_info(LD_EXIT, "Launching eventdns request for %s",
  1573. escaped_safe_str(resolve->address));
  1574. resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
  1575. if (get_options()->IPv6Exit)
  1576. resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
  1577. if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
  1578. resolve->res_status_ipv4 = 0;
  1579. r = -1;
  1580. }
  1581. if (r==0 && get_options()->IPv6Exit) {
  1582. /* We ask for an IPv6 address for *everything*. */
  1583. if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
  1584. resolve->res_status_ipv6 = 0;
  1585. r = -1;
  1586. }
  1587. }
  1588. } else if (r == 1) {
  1589. r = 0;
  1590. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1591. escaped_safe_str(resolve->address));
  1592. resolve->res_status_hostname = RES_STATUS_INFLIGHT;
  1593. if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
  1594. resolve->res_status_hostname = 0;
  1595. r = -1;
  1596. }
  1597. } else if (r == -1) {
  1598. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1599. }
  1600. if (r < 0) {
  1601. log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
  1602. escaped_safe_str(resolve->address));
  1603. }
  1604. return r;
  1605. }
  1606. /** How many requests for bogus addresses have we launched so far? */
  1607. static int n_wildcard_requests = 0;
  1608. /** Map from dotted-quad IP address in response to an int holding how many
  1609. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1610. * would be easier to use definitely-invalid addresses (as specified by
  1611. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1612. static strmap_t *dns_wildcard_response_count = NULL;
  1613. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1614. * nameserver wants to return in response to requests for nonexistent domains.
  1615. */
  1616. static smartlist_t *dns_wildcard_list = NULL;
  1617. /** True iff we've logged about a single address getting wildcarded.
  1618. * Subsequent warnings will be less severe. */
  1619. static int dns_wildcard_one_notice_given = 0;
  1620. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1621. */
  1622. static int dns_wildcard_notice_given = 0;
  1623. /** List of supposedly good addresses that are getting wildcarded to the
  1624. * same addresses as nonexistent addresses. */
  1625. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1626. /** True iff we've warned about a test address getting wildcarded */
  1627. static int dns_wildcarded_test_address_notice_given = 0;
  1628. /** True iff all addresses seem to be getting wildcarded. */
  1629. static int dns_is_completely_invalid = 0;
  1630. /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
  1631. * to a request for a hopefully bogus address. */
  1632. static void
  1633. wildcard_increment_answer(const char *id)
  1634. {
  1635. int *ip;
  1636. if (!dns_wildcard_response_count)
  1637. dns_wildcard_response_count = strmap_new();
  1638. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1639. if (!ip) {
  1640. ip = tor_malloc_zero(sizeof(int));
  1641. strmap_set(dns_wildcard_response_count, id, ip);
  1642. }
  1643. ++*ip;
  1644. if (*ip > 5 && n_wildcard_requests > 10) {
  1645. if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
  1646. if (!smartlist_string_isin(dns_wildcard_list, id)) {
  1647. log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1648. "Your DNS provider has given \"%s\" as an answer for %d different "
  1649. "invalid addresses. Apparently they are hijacking DNS failures. "
  1650. "I'll try to correct for this by treating future occurrences of "
  1651. "\"%s\" as 'not found'.", id, *ip, id);
  1652. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1653. }
  1654. if (!dns_wildcard_notice_given)
  1655. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1656. dns_wildcard_notice_given = 1;
  1657. }
  1658. }
  1659. /** Note that a single test address (one believed to be good) seems to be
  1660. * getting redirected to the same IP as failures are. */
  1661. static void
  1662. add_wildcarded_test_address(const char *address)
  1663. {
  1664. int n, n_test_addrs;
  1665. if (!dns_wildcarded_test_address_list)
  1666. dns_wildcarded_test_address_list = smartlist_new();
  1667. if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
  1668. return;
  1669. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1670. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1671. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1672. n = smartlist_len(dns_wildcarded_test_address_list);
  1673. if (n > n_test_addrs/2) {
  1674. log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1675. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1676. "address. It has done this with %d test addresses so far. I'm "
  1677. "going to stop being an exit node for now, since our DNS seems so "
  1678. "broken.", address, n);
  1679. if (!dns_is_completely_invalid) {
  1680. dns_is_completely_invalid = 1;
  1681. mark_my_descriptor_dirty("dns hijacking confirmed");
  1682. }
  1683. if (!dns_wildcarded_test_address_notice_given)
  1684. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1685. dns_wildcarded_test_address_notice_given = 1;
  1686. }
  1687. }
  1688. /** Callback function when we get an answer (possibly failing) for a request
  1689. * for a (hopefully) nonexistent domain. */
  1690. static void
  1691. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1692. void *addresses, void *arg)
  1693. {
  1694. (void)ttl;
  1695. ++n_wildcard_requests;
  1696. if (result == DNS_ERR_NONE && count) {
  1697. char *string_address = arg;
  1698. int i;
  1699. if (type == DNS_IPv4_A) {
  1700. const uint32_t *addrs = addresses;
  1701. for (i = 0; i < count; ++i) {
  1702. char answer_buf[INET_NTOA_BUF_LEN+1];
  1703. struct in_addr in;
  1704. in.s_addr = addrs[i];
  1705. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1706. wildcard_increment_answer(answer_buf);
  1707. }
  1708. } else if (type == DNS_IPv6_AAAA) {
  1709. const struct in6_addr *addrs = addresses;
  1710. for (i = 0; i < count; ++i) {
  1711. char answer_buf[TOR_ADDR_BUF_LEN+1];
  1712. tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
  1713. wildcard_increment_answer(answer_buf);
  1714. }
  1715. }
  1716. log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1717. "Your DNS provider gave an answer for \"%s\", which "
  1718. "is not supposed to exist. Apparently they are hijacking "
  1719. "DNS failures. Trying to correct for this. We've noticed %d "
  1720. "possibly bad address%s so far.",
  1721. string_address, strmap_size(dns_wildcard_response_count),
  1722. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1723. dns_wildcard_one_notice_given = 1;
  1724. }
  1725. tor_free(arg);
  1726. }
  1727. /** Launch a single request for a nonexistent hostname consisting of between
  1728. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1729. * <b>suffix</b> */
  1730. static void
  1731. launch_wildcard_check(int min_len, int max_len, int is_ipv6,
  1732. const char *suffix)
  1733. {
  1734. char *addr;
  1735. struct evdns_request *req;
  1736. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1737. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1738. "domains with request for bogus hostname \"%s\"", addr);
  1739. tor_assert(the_evdns_base);
  1740. if (is_ipv6)
  1741. req = evdns_base_resolve_ipv6(
  1742. the_evdns_base,
  1743. /* This "addr" tells us which address to resolve */
  1744. addr,
  1745. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1746. /* This "addr" is an argument to the callback*/ addr);
  1747. else
  1748. req = evdns_base_resolve_ipv4(
  1749. the_evdns_base,
  1750. /* This "addr" tells us which address to resolve */
  1751. addr,
  1752. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1753. /* This "addr" is an argument to the callback*/ addr);
  1754. if (!req) {
  1755. /* There is no evdns request in progress; stop addr from getting leaked */
  1756. tor_free(addr);
  1757. }
  1758. }
  1759. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1760. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1761. static void
  1762. launch_test_addresses(int fd, short event, void *args)
  1763. {
  1764. const or_options_t *options = get_options();
  1765. (void)fd;
  1766. (void)event;
  1767. (void)args;
  1768. if (options->DisableNetwork)
  1769. return;
  1770. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1771. "hijack *everything*.");
  1772. /* This situation is worse than the failure-hijacking situation. When this
  1773. * happens, we're no good for DNS requests at all, and we shouldn't really
  1774. * be an exit server.*/
  1775. if (options->ServerDNSTestAddresses) {
  1776. tor_assert(the_evdns_base);
  1777. SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
  1778. const char *, address) {
  1779. if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
  1780. log_info(LD_EXIT, "eventdns rejected test address %s",
  1781. escaped_safe_str(address));
  1782. }
  1783. if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
  1784. log_info(LD_EXIT, "eventdns rejected test address %s",
  1785. escaped_safe_str(address));
  1786. }
  1787. } SMARTLIST_FOREACH_END(address);
  1788. }
  1789. }
  1790. #define N_WILDCARD_CHECKS 2
  1791. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1792. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1793. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1794. * buy these lovely encyclopedias" page. */
  1795. static void
  1796. dns_launch_wildcard_checks(void)
  1797. {
  1798. int i, ipv6;
  1799. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1800. "to hijack DNS failures.");
  1801. for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
  1802. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1803. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
  1804. * attempt to 'comply' with rfc2606, refrain from giving A records for
  1805. * these. This is the standards-compliance equivalent of making sure
  1806. * that your crackhouse's elevator inspection certificate is up to date.
  1807. */
  1808. launch_wildcard_check(2, 16, ipv6, ".invalid");
  1809. launch_wildcard_check(2, 16, ipv6, ".test");
  1810. /* These will break specs if there are ever any number of
  1811. * 8+-character top-level domains. */
  1812. launch_wildcard_check(8, 16, ipv6, "");
  1813. /* Try some random .com/org/net domains. This will work fine so long as
  1814. * not too many resolve to the same place. */
  1815. launch_wildcard_check(8, 16, ipv6, ".com");
  1816. launch_wildcard_check(8, 16, ipv6, ".org");
  1817. launch_wildcard_check(8, 16, ipv6, ".net");
  1818. }
  1819. }
  1820. }
  1821. /** If appropriate, start testing whether our DNS servers tend to lie to
  1822. * us. */
  1823. void
  1824. dns_launch_correctness_checks(void)
  1825. {
  1826. static struct event *launch_event = NULL;
  1827. struct timeval timeout;
  1828. if (!get_options()->ServerDNSDetectHijacking)
  1829. return;
  1830. dns_launch_wildcard_checks();
  1831. /* Wait a while before launching requests for test addresses, so we can
  1832. * get the results from checking for wildcarding. */
  1833. if (! launch_event)
  1834. launch_event = tor_evtimer_new(tor_libevent_get_base(),
  1835. launch_test_addresses, NULL);
  1836. timeout.tv_sec = 30;
  1837. timeout.tv_usec = 0;
  1838. if (evtimer_add(launch_event, &timeout)<0) {
  1839. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1840. }
  1841. }
  1842. /** Return true iff our DNS servers lie to us too much to be trusted. */
  1843. int
  1844. dns_seems_to_be_broken(void)
  1845. {
  1846. return dns_is_completely_invalid;
  1847. }
  1848. /** Return true iff we think that IPv6 hostname lookup is broken */
  1849. int
  1850. dns_seems_to_be_broken_for_ipv6(void)
  1851. {
  1852. return dns_is_broken_for_ipv6;
  1853. }
  1854. /** Forget what we've previously learned about our DNS servers' correctness. */
  1855. void
  1856. dns_reset_correctness_checks(void)
  1857. {
  1858. strmap_free(dns_wildcard_response_count, tor_free_);
  1859. dns_wildcard_response_count = NULL;
  1860. n_wildcard_requests = 0;
  1861. n_ipv6_requests_made = n_ipv6_timeouts = 0;
  1862. if (dns_wildcard_list) {
  1863. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1864. smartlist_clear(dns_wildcard_list);
  1865. }
  1866. if (dns_wildcarded_test_address_list) {
  1867. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1868. tor_free(cp));
  1869. smartlist_clear(dns_wildcarded_test_address_list);
  1870. }
  1871. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1872. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid =
  1873. dns_is_broken_for_ipv6 = 0;
  1874. }
  1875. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1876. * returned in response to requests for nonexistent hostnames. */
  1877. static int
  1878. answer_is_wildcarded(const char *ip)
  1879. {
  1880. return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
  1881. }
  1882. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1883. static void
  1884. assert_resolve_ok(cached_resolve_t *resolve)
  1885. {
  1886. tor_assert(resolve);
  1887. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1888. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1889. tor_assert(tor_strisnonupper(resolve->address));
  1890. if (resolve->state != CACHE_STATE_PENDING) {
  1891. tor_assert(!resolve->pending_connections);
  1892. }
  1893. if (resolve->state == CACHE_STATE_PENDING ||
  1894. resolve->state == CACHE_STATE_DONE) {
  1895. #if 0
  1896. tor_assert(!resolve->ttl);
  1897. if (resolve->is_reverse)
  1898. tor_assert(!resolve->hostname);
  1899. else
  1900. tor_assert(!resolve->result_ipv4.addr_ipv4);
  1901. #endif
  1902. /*XXXXX ADD MORE */
  1903. }
  1904. }
  1905. /** Return the number of DNS cache entries as an int */
  1906. static int
  1907. dns_cache_entry_count(void)
  1908. {
  1909. return HT_SIZE(&cache_root);
  1910. }
  1911. /** Log memory information about our internal DNS cache at level 'severity'. */
  1912. void
  1913. dump_dns_mem_usage(int severity)
  1914. {
  1915. /* This should never be larger than INT_MAX. */
  1916. int hash_count = dns_cache_entry_count();
  1917. size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
  1918. hash_mem += HT_MEM_USAGE(&cache_root);
  1919. /* Print out the count and estimated size of our &cache_root. It undercounts
  1920. hostnames in cached reverse resolves.
  1921. */
  1922. log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
  1923. log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
  1924. (unsigned)hash_mem);
  1925. }
  1926. #ifdef DEBUG_DNS_CACHE
  1927. /** Exit with an assertion if the DNS cache is corrupt. */
  1928. static void
  1929. assert_cache_ok_(void)
  1930. {
  1931. cached_resolve_t **resolve;
  1932. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1933. if (bad_rep) {
  1934. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1935. tor_assert(!bad_rep);
  1936. }
  1937. HT_FOREACH(resolve, cache_map, &cache_root) {
  1938. assert_resolve_ok(*resolve);
  1939. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1940. }
  1941. if (!cached_resolve_pqueue)
  1942. return;
  1943. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1944. compare_cached_resolves_by_expiry_,
  1945. STRUCT_OFFSET(cached_resolve_t, minheap_idx));
  1946. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1947. {
  1948. if (res->state == CACHE_STATE_DONE) {
  1949. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1950. tor_assert(!found || found != res);
  1951. } else {
  1952. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1953. tor_assert(found);
  1954. }
  1955. });
  1956. }
  1957. #endif