dns.c 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173
  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. const routerinfo_t *me;
  732. tor_addr_t addr;
  733. time_t now = time(NULL);
  734. int r;
  735. assert_connection_ok(TO_CONN(exitconn), 0);
  736. tor_assert(!SOCKET_OK(exitconn->base_.s));
  737. assert_cache_ok();
  738. tor_assert(oncirc);
  739. *made_connection_pending_out = 0;
  740. /* first check if exitconn->base_.address is an IP. If so, we already
  741. * know the answer. */
  742. if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
  743. if (tor_addr_family(&addr) == AF_INET ||
  744. tor_addr_family(&addr) == AF_INET6) {
  745. tor_addr_copy(&exitconn->base_.addr, &addr);
  746. exitconn->address_ttl = DEFAULT_DNS_TTL;
  747. return 1;
  748. } else {
  749. /* XXXX unspec? Bogus? */
  750. return -1;
  751. }
  752. }
  753. /* If we're a non-exit, don't even do DNS lookups. */
  754. if (!(me = router_get_my_routerinfo()) ||
  755. policy_is_reject_star(me->exit_policy)) {
  756. return -1;
  757. }
  758. if (address_is_invalid_destination(exitconn->base_.address, 0)) {
  759. log(LOG_PROTOCOL_WARN, LD_EXIT,
  760. "Rejecting invalid destination address %s",
  761. escaped_safe_str(exitconn->base_.address));
  762. return -1;
  763. }
  764. /* then take this opportunity to see if there are any expired
  765. * resolves in the hash table. */
  766. purge_expired_resolves(now);
  767. /* lower-case exitconn->base_.address, so it's in canonical form */
  768. tor_strlower(exitconn->base_.address);
  769. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  770. * .in-addr.arpa address but this isn't a resolve request, kill the
  771. * connection.
  772. */
  773. if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
  774. AF_UNSPEC, 0)) != 0) {
  775. if (r == 1) {
  776. is_reverse = 1;
  777. if (tor_addr_is_internal(&addr, 0)) /* internal address? */
  778. return -1;
  779. }
  780. if (!is_reverse || !is_resolve) {
  781. if (!is_reverse)
  782. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  783. escaped_safe_str(exitconn->base_.address));
  784. else if (!is_resolve)
  785. log_info(LD_EXIT,
  786. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  787. "sending error.",
  788. escaped_safe_str(exitconn->base_.address));
  789. return -1;
  790. }
  791. //log_notice(LD_EXIT, "Looks like an address %s",
  792. //exitconn->base_.address);
  793. }
  794. exitconn->is_reverse_dns_lookup = is_reverse;
  795. /* now check the hash table to see if 'address' is already there. */
  796. strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
  797. resolve = HT_FIND(cache_map, &cache_root, &search);
  798. if (resolve && resolve->expire > now) { /* already there */
  799. switch (resolve->state) {
  800. case CACHE_STATE_PENDING:
  801. /* add us to the pending list */
  802. pending_connection = tor_malloc_zero(
  803. sizeof(pending_connection_t));
  804. pending_connection->conn = exitconn;
  805. pending_connection->next = resolve->pending_connections;
  806. resolve->pending_connections = pending_connection;
  807. *made_connection_pending_out = 1;
  808. log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  809. "resolve of %s", exitconn->base_.s,
  810. escaped_safe_str(exitconn->base_.address));
  811. return 0;
  812. case CACHE_STATE_CACHED:
  813. log_debug(LD_EXIT,"Connection (fd %d) found cachedresult for %s",
  814. exitconn->base_.s,
  815. escaped_safe_str(resolve->address));
  816. return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
  817. case CACHE_STATE_DONE:
  818. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  819. tor_fragile_assert();
  820. }
  821. tor_assert(0);
  822. }
  823. tor_assert(!resolve);
  824. /* not there, need to add it */
  825. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  826. resolve->magic = CACHED_RESOLVE_MAGIC;
  827. resolve->state = CACHE_STATE_PENDING;
  828. resolve->minheap_idx = -1;
  829. strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
  830. /* add this connection to the pending list */
  831. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  832. pending_connection->conn = exitconn;
  833. resolve->pending_connections = pending_connection;
  834. *made_connection_pending_out = 1;
  835. /* Add this resolve to the cache and priority queue. */
  836. HT_INSERT(cache_map, &cache_root, resolve);
  837. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  838. log_debug(LD_EXIT,"Launching %s.",
  839. escaped_safe_str(exitconn->base_.address));
  840. assert_cache_ok();
  841. return launch_resolve(resolve);
  842. }
  843. /** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
  844. * <b>resolve</b> whose DNS lookups have all succeeded or failed, update the
  845. * appropriate fields (address_ttl and addr) of <b>exitconn</b>.
  846. *
  847. * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
  848. * copy of the name resulting hostname.
  849. *
  850. * Return -2 on a transient error, -1 on a permenent error, and 1 on
  851. * a successful lookup.
  852. */
  853. static int
  854. set_exitconn_info_from_resolve(edge_connection_t *exitconn,
  855. const cached_resolve_t *resolve,
  856. char **hostname_out)
  857. {
  858. int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
  859. tor_assert(exitconn);
  860. tor_assert(resolve);
  861. if (exitconn->is_reverse_dns_lookup) {
  862. exitconn->address_ttl = resolve->ttl_hostname;
  863. if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
  864. *hostname_out = tor_strdup(resolve->result_ptr.hostname);
  865. return 1;
  866. } else {
  867. return -1;
  868. }
  869. }
  870. /* If we're here then the connection wants one or either of ipv4, ipv6, and
  871. * we can give it one or both. */
  872. ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
  873. ! (exitconn->begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
  874. ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
  875. (exitconn->begincell_flags & BEGIN_FLAG_IPV6_OK) &&
  876. get_options()->IPv6Exit;
  877. /* Now decide which one to actually give. */
  878. if (ipv4_ok && ipv6_ok) {
  879. /* If we have both, see if our exit policy has an opinion. */
  880. const uint16_t port = exitconn->base_.port;
  881. int ipv4_allowed, ipv6_allowed;
  882. tor_addr_t a4, a6;
  883. tor_addr_from_ipv4h(&a4, resolve->result_ipv4.addr_ipv4);
  884. tor_addr_from_in6(&a6, &resolve->result_ipv6.addr_ipv6);
  885. ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
  886. ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
  887. if (ipv4_allowed && !ipv6_allowed) {
  888. answer_with_ipv4 = 1;
  889. } else if (ipv6_allowed && !ipv4_allowed) {
  890. answer_with_ipv4 = 0;
  891. } else {
  892. /* Our exit policy would permit both. Answer with whichever the user
  893. * prefers */
  894. answer_with_ipv4 = !(exitconn->begincell_flags &
  895. BEGIN_FLAG_IPV6_PREFERRED);
  896. }
  897. } else {
  898. /* Otherwise if one is okay, send it back. */
  899. if (ipv4_ok) {
  900. answer_with_ipv4 = 1;
  901. } else if (ipv6_ok) {
  902. answer_with_ipv4 = 0;
  903. } else {
  904. /* Neither one was okay. Choose based on user preference. */
  905. answer_with_ipv4 = !(exitconn->begincell_flags &
  906. BEGIN_FLAG_IPV6_PREFERRED);
  907. }
  908. }
  909. /* Finally, we write the answer back. */
  910. r = 1;
  911. if (answer_with_ipv4) {
  912. if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
  913. tor_addr_from_ipv4h(&exitconn->base_.addr,
  914. resolve->result_ipv4.addr_ipv4);
  915. } else {
  916. r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
  917. }
  918. exitconn->address_ttl = resolve->ttl_ipv4;
  919. } else {
  920. if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
  921. tor_addr_from_in6(&exitconn->base_.addr,
  922. &resolve->result_ipv6.addr_ipv6);
  923. } else {
  924. r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
  925. }
  926. exitconn->address_ttl = resolve->ttl_ipv6;
  927. }
  928. return r;
  929. }
  930. /** Log an error and abort if conn is waiting for a DNS resolve.
  931. */
  932. void
  933. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  934. {
  935. pending_connection_t *pend;
  936. cached_resolve_t search;
  937. #if 1
  938. cached_resolve_t *resolve;
  939. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  940. resolve = HT_FIND(cache_map, &cache_root, &search);
  941. if (!resolve)
  942. return;
  943. for (pend = resolve->pending_connections; pend; pend = pend->next) {
  944. tor_assert(pend->conn != conn);
  945. }
  946. #else
  947. cached_resolve_t **resolve;
  948. HT_FOREACH(resolve, cache_map, &cache_root) {
  949. for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
  950. tor_assert(pend->conn != conn);
  951. }
  952. }
  953. #endif
  954. }
  955. /** Log an error and abort if any connection waiting for a DNS resolve is
  956. * corrupted. */
  957. void
  958. assert_all_pending_dns_resolves_ok(void)
  959. {
  960. pending_connection_t *pend;
  961. cached_resolve_t **resolve;
  962. HT_FOREACH(resolve, cache_map, &cache_root) {
  963. for (pend = (*resolve)->pending_connections;
  964. pend;
  965. pend = pend->next) {
  966. assert_connection_ok(TO_CONN(pend->conn), 0);
  967. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  968. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  969. }
  970. }
  971. }
  972. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  973. */
  974. void
  975. connection_dns_remove(edge_connection_t *conn)
  976. {
  977. pending_connection_t *pend, *victim;
  978. cached_resolve_t search;
  979. cached_resolve_t *resolve;
  980. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  981. tor_assert(conn->base_.state == EXIT_CONN_STATE_RESOLVING);
  982. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  983. resolve = HT_FIND(cache_map, &cache_root, &search);
  984. if (!resolve) {
  985. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  986. escaped_safe_str(conn->base_.address));
  987. return;
  988. }
  989. tor_assert(resolve->pending_connections);
  990. assert_connection_ok(TO_CONN(conn),0);
  991. pend = resolve->pending_connections;
  992. if (pend->conn == conn) {
  993. resolve->pending_connections = pend->next;
  994. tor_free(pend);
  995. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  996. "for resolve of %s",
  997. conn->base_.s,
  998. escaped_safe_str(conn->base_.address));
  999. return;
  1000. } else {
  1001. for ( ; pend->next; pend = pend->next) {
  1002. if (pend->next->conn == conn) {
  1003. victim = pend->next;
  1004. pend->next = victim->next;
  1005. tor_free(victim);
  1006. log_debug(LD_EXIT,
  1007. "Connection (fd %d) no longer waiting for resolve of %s",
  1008. conn->base_.s, escaped_safe_str(conn->base_.address));
  1009. return; /* more are pending */
  1010. }
  1011. }
  1012. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  1013. }
  1014. }
  1015. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  1016. * the resolve for <b>address</b> itself, and remove any cached results for
  1017. * <b>address</b> from the cache.
  1018. */
  1019. void
  1020. dns_cancel_pending_resolve(const char *address)
  1021. {
  1022. pending_connection_t *pend;
  1023. cached_resolve_t search;
  1024. cached_resolve_t *resolve, *tmp;
  1025. edge_connection_t *pendconn;
  1026. circuit_t *circ;
  1027. strlcpy(search.address, address, sizeof(search.address));
  1028. resolve = HT_FIND(cache_map, &cache_root, &search);
  1029. if (!resolve)
  1030. return;
  1031. if (resolve->state != CACHE_STATE_PENDING) {
  1032. /* We can get into this state if we never actually created the pending
  1033. * resolve, due to finding an earlier cached error or something. Just
  1034. * ignore it. */
  1035. if (resolve->pending_connections) {
  1036. log_warn(LD_BUG,
  1037. "Address %s is not pending but has pending connections!",
  1038. escaped_safe_str(address));
  1039. tor_fragile_assert();
  1040. }
  1041. return;
  1042. }
  1043. if (!resolve->pending_connections) {
  1044. log_warn(LD_BUG,
  1045. "Address %s is pending but has no pending connections!",
  1046. escaped_safe_str(address));
  1047. tor_fragile_assert();
  1048. return;
  1049. }
  1050. tor_assert(resolve->pending_connections);
  1051. /* mark all pending connections to fail */
  1052. log_debug(LD_EXIT,
  1053. "Failing all connections waiting on DNS resolve of %s",
  1054. escaped_safe_str(address));
  1055. while (resolve->pending_connections) {
  1056. pend = resolve->pending_connections;
  1057. pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1058. pendconn = pend->conn;
  1059. assert_connection_ok(TO_CONN(pendconn), 0);
  1060. tor_assert(!SOCKET_OK(pendconn->base_.s));
  1061. if (!pendconn->base_.marked_for_close) {
  1062. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1063. }
  1064. circ = circuit_get_by_edge_conn(pendconn);
  1065. if (circ)
  1066. circuit_detach_stream(circ, pendconn);
  1067. if (!pendconn->base_.marked_for_close)
  1068. connection_free(TO_CONN(pendconn));
  1069. resolve->pending_connections = pend->next;
  1070. tor_free(pend);
  1071. }
  1072. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  1073. if (tmp != resolve) {
  1074. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  1075. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1076. resolve->address, (void*)resolve,
  1077. tmp ? tmp->address : "NULL", (void*)tmp);
  1078. }
  1079. tor_assert(tmp == resolve);
  1080. resolve->state = CACHE_STATE_DONE;
  1081. }
  1082. /** Return true iff <b>address</b> is one of the addresses we use to verify
  1083. * that well-known sites aren't being hijacked by our DNS servers. */
  1084. static INLINE int
  1085. is_test_address(const char *address)
  1086. {
  1087. const or_options_t *options = get_options();
  1088. return options->ServerDNSTestAddresses &&
  1089. smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
  1090. }
  1091. /** Called on the OR side when the eventdns library tells us the outcome of a
  1092. * single DNS resolve: remember the answer, and tell all pending connections
  1093. * about the result of the lookup if the lookup is now done. (<b>address</b>
  1094. * is a NUL-terminated string containing the address to look up;
  1095. * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
  1096. * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
  1097. * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
  1098. * <b>ttl</b> is the time-to-live of this answer, in seconds.)
  1099. */
  1100. static void
  1101. dns_found_answer(const char *address, uint8_t query_type,
  1102. int dns_answer,
  1103. const tor_addr_t *addr,
  1104. const char *hostname, uint32_t ttl)
  1105. {
  1106. cached_resolve_t search;
  1107. cached_resolve_t *resolve;
  1108. assert_cache_ok();
  1109. strlcpy(search.address, address, sizeof(search.address));
  1110. resolve = HT_FIND(cache_map, &cache_root, &search);
  1111. if (!resolve) {
  1112. int is_test_addr = is_test_address(address);
  1113. if (!is_test_addr)
  1114. log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
  1115. escaped_safe_str(address));
  1116. return;
  1117. }
  1118. assert_resolve_ok(resolve);
  1119. if (resolve->state != CACHE_STATE_PENDING) {
  1120. /* XXXX Maybe update addr? or check addr for consistency? Or let
  1121. * VALID replace FAILED? */
  1122. int is_test_addr = is_test_address(address);
  1123. if (!is_test_addr)
  1124. log_notice(LD_EXIT,
  1125. "Resolved %s which was already resolved; ignoring",
  1126. escaped_safe_str(address));
  1127. tor_assert(resolve->pending_connections == NULL);
  1128. return;
  1129. }
  1130. cached_resolve_add_answer(resolve, query_type, dns_answer,
  1131. addr, hostname, ttl);
  1132. if (cached_resolve_have_all_answers(resolve)) {
  1133. inform_pending_connections(resolve);
  1134. make_pending_resolve_cached(resolve);
  1135. }
  1136. }
  1137. /** Given a pending cached_resolve_t that we just finished resolving,
  1138. * inform every connection that was waiting for the outcome of that
  1139. * resolution. */
  1140. static void
  1141. inform_pending_connections(cached_resolve_t *resolve)
  1142. {
  1143. pending_connection_t *pend;
  1144. edge_connection_t *pendconn;
  1145. int r;
  1146. while (resolve->pending_connections) {
  1147. char *hostname = NULL;
  1148. pend = resolve->pending_connections;
  1149. pendconn = pend->conn; /* don't pass complex things to the
  1150. connection_mark_for_close macro */
  1151. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  1152. if (pendconn->base_.marked_for_close) {
  1153. /* prevent double-remove. */
  1154. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1155. resolve->pending_connections = pend->next;
  1156. tor_free(pend);
  1157. continue;
  1158. }
  1159. r = set_exitconn_info_from_resolve(pendconn,
  1160. resolve,
  1161. &hostname);
  1162. if (r < 0) {
  1163. /* prevent double-remove. */
  1164. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1165. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1166. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1167. /* This detach must happen after we send the end cell. */
  1168. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1169. } else {
  1170. send_resolved_cell(pendconn, r == -1 ?
  1171. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT);
  1172. /* This detach must happen after we send the resolved cell. */
  1173. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1174. }
  1175. connection_free(TO_CONN(pendconn));
  1176. } else {
  1177. circuit_t *circ;
  1178. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1179. /* prevent double-remove. */
  1180. pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  1181. circ = circuit_get_by_edge_conn(pend->conn);
  1182. tor_assert(circ);
  1183. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1184. /* unlink pend->conn from resolving_streams, */
  1185. circuit_detach_stream(circ, pend->conn);
  1186. /* and link it to n_streams */
  1187. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1188. pend->conn->on_circuit = circ;
  1189. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  1190. connection_exit_connect(pend->conn);
  1191. } else {
  1192. /* prevent double-remove. This isn't really an accurate state,
  1193. * but it does the right thing. */
  1194. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1195. if (pendconn->is_reverse_dns_lookup)
  1196. send_resolved_hostname_cell(pendconn, hostname);
  1197. else
  1198. send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO);
  1199. circ = circuit_get_by_edge_conn(pendconn);
  1200. tor_assert(circ);
  1201. circuit_detach_stream(circ, pendconn);
  1202. connection_free(TO_CONN(pendconn));
  1203. }
  1204. }
  1205. resolve->pending_connections = pend->next;
  1206. tor_free(pend);
  1207. }
  1208. }
  1209. /** Remove a pending cached_resolve_t from the hashtable, and add a
  1210. * corresponding cached cached_resolve_t.
  1211. *
  1212. * This function is only necessary because of the perversity of our
  1213. * cache timeout code; see inline comment for ideas on eliminating it.
  1214. **/
  1215. static void
  1216. make_pending_resolve_cached(cached_resolve_t *resolve)
  1217. {
  1218. cached_resolve_t *removed;
  1219. resolve->state = CACHE_STATE_DONE;
  1220. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  1221. if (removed != resolve) {
  1222. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  1223. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1224. resolve->address, (void*)resolve,
  1225. removed ? removed->address : "NULL", (void*)removed);
  1226. }
  1227. assert_resolve_ok(resolve);
  1228. assert_cache_ok();
  1229. /* The resolve will eventually just hit the time-out in the expiry queue and
  1230. * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
  1231. * way. XXXXX we could do better!*/
  1232. {
  1233. cached_resolve_t *new_resolve = tor_memdup(resolve,
  1234. sizeof(cached_resolve_t));
  1235. uint32_t ttl = UINT32_MAX;
  1236. new_resolve->expire = 0; /* So that set_expiry won't croak. */
  1237. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  1238. new_resolve->result_ptr.hostname =
  1239. tor_strdup(resolve->result_ptr.hostname);
  1240. new_resolve->state = CACHE_STATE_CACHED;
  1241. assert_resolve_ok(new_resolve);
  1242. HT_INSERT(cache_map, &cache_root, new_resolve);
  1243. if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
  1244. resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
  1245. resolve->ttl_ipv4 < ttl)
  1246. ttl = resolve->ttl_ipv4;
  1247. if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
  1248. resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
  1249. resolve->ttl_ipv6 < ttl)
  1250. ttl = resolve->ttl_ipv6;
  1251. if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
  1252. resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
  1253. resolve->ttl_hostname < ttl)
  1254. ttl = resolve->ttl_hostname;
  1255. set_expiry(new_resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  1256. }
  1257. assert_cache_ok();
  1258. }
  1259. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1260. * a transient failure. */
  1261. static int
  1262. evdns_err_is_transient(int err)
  1263. {
  1264. switch (err)
  1265. {
  1266. case DNS_ERR_SERVERFAILED:
  1267. case DNS_ERR_TRUNCATED:
  1268. case DNS_ERR_TIMEOUT:
  1269. return 1;
  1270. default:
  1271. return 0;
  1272. }
  1273. }
  1274. /** Configure eventdns nameservers if force is true, or if the configuration
  1275. * has changed since the last time we called this function, or if we failed on
  1276. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1277. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1278. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1279. * -1 on failure. */
  1280. static int
  1281. configure_nameservers(int force)
  1282. {
  1283. const or_options_t *options;
  1284. const char *conf_fname;
  1285. struct stat st;
  1286. int r;
  1287. options = get_options();
  1288. conf_fname = options->ServerDNSResolvConfFile;
  1289. #ifndef _WIN32
  1290. if (!conf_fname)
  1291. conf_fname = "/etc/resolv.conf";
  1292. #endif
  1293. if (!the_evdns_base) {
  1294. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  1295. log_err(LD_BUG, "Couldn't create an evdns_base");
  1296. return -1;
  1297. }
  1298. }
  1299. #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  1300. if (! tor_addr_is_null(&options->OutboundBindAddressIPv4_)) {
  1301. int socklen;
  1302. struct sockaddr_storage ss;
  1303. socklen = tor_addr_to_sockaddr(&options->OutboundBindAddressIPv4_, 0,
  1304. (struct sockaddr *)&ss, sizeof(ss));
  1305. if (socklen <= 0) {
  1306. log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
  1307. " Ignoring.");
  1308. } else {
  1309. evdns_base_set_default_outgoing_bind_address(the_evdns_base,
  1310. (struct sockaddr *)&ss,
  1311. socklen);
  1312. }
  1313. }
  1314. #endif
  1315. evdns_set_log_fn(evdns_log_cb);
  1316. if (conf_fname) {
  1317. if (stat(conf_fname, &st)) {
  1318. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1319. conf_fname, strerror(errno));
  1320. goto err;
  1321. }
  1322. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1323. && st.st_mtime == resolv_conf_mtime) {
  1324. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1325. return 0;
  1326. }
  1327. if (nameservers_configured) {
  1328. evdns_base_search_clear(the_evdns_base);
  1329. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1330. }
  1331. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1332. if ((r = evdns_base_resolv_conf_parse(the_evdns_base,
  1333. DNS_OPTIONS_ALL, conf_fname))) {
  1334. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  1335. conf_fname, conf_fname, r);
  1336. goto err;
  1337. }
  1338. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1339. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1340. goto err;
  1341. }
  1342. tor_free(resolv_conf_fname);
  1343. resolv_conf_fname = tor_strdup(conf_fname);
  1344. resolv_conf_mtime = st.st_mtime;
  1345. if (nameservers_configured)
  1346. evdns_base_resume(the_evdns_base);
  1347. }
  1348. #ifdef _WIN32
  1349. else {
  1350. if (nameservers_configured) {
  1351. evdns_base_search_clear(the_evdns_base);
  1352. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1353. }
  1354. if (evdns_base_config_windows_nameservers(the_evdns_base)) {
  1355. log_warn(LD_EXIT,"Could not config nameservers.");
  1356. goto err;
  1357. }
  1358. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1359. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1360. "your Windows configuration.");
  1361. goto err;
  1362. }
  1363. if (nameservers_configured)
  1364. evdns_base_resume(the_evdns_base);
  1365. tor_free(resolv_conf_fname);
  1366. resolv_conf_mtime = 0;
  1367. }
  1368. #endif
  1369. #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
  1370. if (evdns_base_count_nameservers(the_evdns_base) == 1) {
  1371. SET("max-timeouts:", "16");
  1372. SET("timeout:", "10");
  1373. } else {
  1374. SET("max-timeouts:", "3");
  1375. SET("timeout:", "5");
  1376. }
  1377. if (options->ServerDNSRandomizeCase)
  1378. SET("randomize-case:", "1");
  1379. else
  1380. SET("randomize-case:", "0");
  1381. #undef SET
  1382. dns_servers_relaunch_checks();
  1383. nameservers_configured = 1;
  1384. if (nameserver_config_failed) {
  1385. nameserver_config_failed = 0;
  1386. /* XXX the three calls to republish the descriptor might be producing
  1387. * descriptors that are only cosmetically different, especially on
  1388. * non-exit relays! -RD */
  1389. mark_my_descriptor_dirty("dns resolvers back");
  1390. }
  1391. return 0;
  1392. err:
  1393. nameservers_configured = 0;
  1394. if (! nameserver_config_failed) {
  1395. nameserver_config_failed = 1;
  1396. mark_my_descriptor_dirty("dns resolvers failed");
  1397. }
  1398. return -1;
  1399. }
  1400. /** For eventdns: Called when we get an answer for a request we launched.
  1401. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1402. */
  1403. static void
  1404. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1405. void *arg)
  1406. {
  1407. char *arg_ = arg;
  1408. uint8_t orig_query_type = arg_[0];
  1409. char *string_address = arg_ + 1;
  1410. tor_addr_t addr;
  1411. const char *hostname = NULL;
  1412. int was_wildcarded = 0;
  1413. tor_addr_make_unspec(&addr); /*WRONG WRONG WRONG XXXX XXXXX IPV6 prop208*/
  1414. /* Keep track of whether IPv6 is working */
  1415. if (type == DNS_IPv6_AAAA) {
  1416. if (result == DNS_ERR_TIMEOUT) {
  1417. ++n_ipv6_timeouts;
  1418. }
  1419. if (n_ipv6_timeouts > 10 &&
  1420. n_ipv6_timeouts > n_ipv6_requests_made / 2) {
  1421. if (! dns_is_broken_for_ipv6) {
  1422. log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
  1423. "have timed out. I'm going to assume I can't get AAAA "
  1424. "responses.");
  1425. dns_is_broken_for_ipv6 = 1;
  1426. }
  1427. }
  1428. }
  1429. if (result == DNS_ERR_NONE) {
  1430. if (type == DNS_IPv4_A && count) {
  1431. char answer_buf[INET_NTOA_BUF_LEN+1];
  1432. char *escaped_address;
  1433. uint32_t *addrs = addresses;
  1434. tor_addr_from_ipv4n(&addr, addrs[0]);
  1435. tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
  1436. escaped_address = esc_for_log(string_address);
  1437. if (answer_is_wildcarded(answer_buf)) {
  1438. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1439. "address %s; treating as a failure.",
  1440. safe_str(escaped_address),
  1441. escaped_safe_str(answer_buf));
  1442. was_wildcarded = 1;
  1443. tor_addr_make_null(&addr, AF_INET); /* ???? */
  1444. result = DNS_ERR_NOTEXIST;
  1445. } else {
  1446. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1447. safe_str(escaped_address),
  1448. escaped_safe_str(answer_buf));
  1449. }
  1450. tor_free(escaped_address);
  1451. } else if (type == DNS_IPv6_AAAA && count) {
  1452. char answer_buf[TOR_ADDR_BUF_LEN];
  1453. char *escaped_address;
  1454. struct in6_addr *addrs = addresses;
  1455. tor_addr_from_in6(&addr, &addrs[0]);
  1456. tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
  1457. escaped_address = esc_for_log(string_address);
  1458. if (answer_is_wildcarded(answer_buf)) {
  1459. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1460. "address %s; treating as a failure.",
  1461. safe_str(escaped_address),
  1462. escaped_safe_str(answer_buf));
  1463. was_wildcarded = 1;
  1464. tor_addr_make_unspec(&addr); /* WRONG WRONG ETC XXXXXXXX */
  1465. result = DNS_ERR_NOTEXIST;
  1466. } else {
  1467. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1468. safe_str(escaped_address),
  1469. escaped_safe_str(answer_buf));
  1470. }
  1471. tor_free(escaped_address);
  1472. } else if (type == DNS_PTR && count) {
  1473. char *escaped_address;
  1474. hostname = ((char**)addresses)[0];
  1475. escaped_address = esc_for_log(string_address);
  1476. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1477. safe_str(escaped_address),
  1478. escaped_safe_str(hostname));
  1479. tor_free(escaped_address);
  1480. } else if (count) {
  1481. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1482. escaped_safe_str(string_address));
  1483. } else {
  1484. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1485. escaped_safe_str(string_address));
  1486. }
  1487. }
  1488. if (was_wildcarded) {
  1489. if (is_test_address(string_address)) {
  1490. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1491. * server must really hate us. */
  1492. add_wildcarded_test_address(string_address);
  1493. }
  1494. }
  1495. if (orig_query_type && type && orig_query_type != type) {
  1496. log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
  1497. (int)orig_query_type, (int)type);
  1498. }
  1499. if (result != DNS_ERR_SHUTDOWN)
  1500. dns_found_answer(string_address, orig_query_type,
  1501. result, &addr, hostname, ttl);
  1502. tor_free(arg_);
  1503. }
  1504. /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
  1505. * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
  1506. * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
  1507. static int
  1508. launch_one_resolve(const char *address, uint8_t query_type,
  1509. const tor_addr_t *ptr_address)
  1510. {
  1511. const int options = get_options()->ServerDNSSearchDomains ? 0
  1512. : DNS_QUERY_NO_SEARCH;
  1513. const size_t addr_len = strlen(address);
  1514. struct evdns_request *req = 0;
  1515. char *addr = tor_malloc(addr_len + 2);
  1516. addr[0] = (char) query_type;
  1517. memcpy(addr+1, address, addr_len + 1);
  1518. switch (query_type) {
  1519. case DNS_IPv4_A:
  1520. req = evdns_base_resolve_ipv4(the_evdns_base,
  1521. address, options, evdns_callback, addr);
  1522. break;
  1523. case DNS_IPv6_AAAA:
  1524. req = evdns_base_resolve_ipv6(the_evdns_base,
  1525. address, options, evdns_callback, addr);
  1526. ++n_ipv6_requests_made;
  1527. break;
  1528. case DNS_PTR:
  1529. if (tor_addr_family(ptr_address) == AF_INET)
  1530. req = evdns_base_resolve_reverse(the_evdns_base,
  1531. tor_addr_to_in(ptr_address),
  1532. DNS_QUERY_NO_SEARCH,
  1533. evdns_callback, addr);
  1534. else if (tor_addr_family(ptr_address) == AF_INET6)
  1535. req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
  1536. tor_addr_to_in6(ptr_address),
  1537. DNS_QUERY_NO_SEARCH,
  1538. evdns_callback, addr);
  1539. else
  1540. log_warn(LD_BUG, "Called with PTR query and unexpected address family");
  1541. break;
  1542. default:
  1543. log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
  1544. break;
  1545. }
  1546. if (req) {
  1547. return 0;
  1548. } else {
  1549. tor_free(addr);
  1550. return -1;
  1551. }
  1552. }
  1553. /** For eventdns: start resolving as necessary to find the target for
  1554. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1555. * 0 on "resolve launched." */
  1556. static int
  1557. launch_resolve(cached_resolve_t *resolve)
  1558. {
  1559. tor_addr_t a;
  1560. int r;
  1561. if (get_options()->DisableNetwork)
  1562. return -1;
  1563. /* What? Nameservers not configured? Sounds like a bug. */
  1564. if (!nameservers_configured) {
  1565. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1566. "launched. Configuring.");
  1567. if (configure_nameservers(1) < 0) {
  1568. return -1;
  1569. }
  1570. }
  1571. r = tor_addr_parse_PTR_name(
  1572. &a, resolve->address, AF_UNSPEC, 0);
  1573. tor_assert(the_evdns_base);
  1574. if (r == 0) {
  1575. log_info(LD_EXIT, "Launching eventdns request for %s",
  1576. escaped_safe_str(resolve->address));
  1577. resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
  1578. if (get_options()->IPv6Exit)
  1579. resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
  1580. if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
  1581. resolve->res_status_ipv4 = 0;
  1582. r = -1;
  1583. }
  1584. if (r==0 && get_options()->IPv6Exit) {
  1585. /* We ask for an IPv6 address for *everything*. */
  1586. if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
  1587. resolve->res_status_ipv6 = 0;
  1588. r = -1;
  1589. }
  1590. }
  1591. } else if (r == 1) {
  1592. r = 0;
  1593. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1594. escaped_safe_str(resolve->address));
  1595. resolve->res_status_hostname = RES_STATUS_INFLIGHT;
  1596. if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
  1597. resolve->res_status_hostname = 0;
  1598. r = -1;
  1599. }
  1600. } else if (r == -1) {
  1601. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1602. }
  1603. if (r < 0) {
  1604. log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
  1605. escaped_safe_str(resolve->address));
  1606. }
  1607. return r;
  1608. }
  1609. /** How many requests for bogus addresses have we launched so far? */
  1610. static int n_wildcard_requests = 0;
  1611. /** Map from dotted-quad IP address in response to an int holding how many
  1612. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1613. * would be easier to use definitely-invalid addresses (as specified by
  1614. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1615. static strmap_t *dns_wildcard_response_count = NULL;
  1616. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1617. * nameserver wants to return in response to requests for nonexistent domains.
  1618. */
  1619. static smartlist_t *dns_wildcard_list = NULL;
  1620. /** True iff we've logged about a single address getting wildcarded.
  1621. * Subsequent warnings will be less severe. */
  1622. static int dns_wildcard_one_notice_given = 0;
  1623. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1624. */
  1625. static int dns_wildcard_notice_given = 0;
  1626. /** List of supposedly good addresses that are getting wildcarded to the
  1627. * same addresses as nonexistent addresses. */
  1628. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1629. /** True iff we've warned about a test address getting wildcarded */
  1630. static int dns_wildcarded_test_address_notice_given = 0;
  1631. /** True iff all addresses seem to be getting wildcarded. */
  1632. static int dns_is_completely_invalid = 0;
  1633. /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
  1634. * to a request for a hopefully bogus address. */
  1635. static void
  1636. wildcard_increment_answer(const char *id)
  1637. {
  1638. int *ip;
  1639. if (!dns_wildcard_response_count)
  1640. dns_wildcard_response_count = strmap_new();
  1641. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1642. if (!ip) {
  1643. ip = tor_malloc_zero(sizeof(int));
  1644. strmap_set(dns_wildcard_response_count, id, ip);
  1645. }
  1646. ++*ip;
  1647. if (*ip > 5 && n_wildcard_requests > 10) {
  1648. if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
  1649. if (!smartlist_string_isin(dns_wildcard_list, id)) {
  1650. log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1651. "Your DNS provider has given \"%s\" as an answer for %d different "
  1652. "invalid addresses. Apparently they are hijacking DNS failures. "
  1653. "I'll try to correct for this by treating future occurrences of "
  1654. "\"%s\" as 'not found'.", id, *ip, id);
  1655. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1656. }
  1657. if (!dns_wildcard_notice_given)
  1658. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1659. dns_wildcard_notice_given = 1;
  1660. }
  1661. }
  1662. /** Note that a single test address (one believed to be good) seems to be
  1663. * getting redirected to the same IP as failures are. */
  1664. static void
  1665. add_wildcarded_test_address(const char *address)
  1666. {
  1667. int n, n_test_addrs;
  1668. if (!dns_wildcarded_test_address_list)
  1669. dns_wildcarded_test_address_list = smartlist_new();
  1670. if (smartlist_string_isin_case(dns_wildcarded_test_address_list, address))
  1671. return;
  1672. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1673. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1674. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1675. n = smartlist_len(dns_wildcarded_test_address_list);
  1676. if (n > n_test_addrs/2) {
  1677. log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1678. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1679. "address. It has done this with %d test addresses so far. I'm "
  1680. "going to stop being an exit node for now, since our DNS seems so "
  1681. "broken.", address, n);
  1682. if (!dns_is_completely_invalid) {
  1683. dns_is_completely_invalid = 1;
  1684. mark_my_descriptor_dirty("dns hijacking confirmed");
  1685. }
  1686. if (!dns_wildcarded_test_address_notice_given)
  1687. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1688. dns_wildcarded_test_address_notice_given = 1;
  1689. }
  1690. }
  1691. /** Callback function when we get an answer (possibly failing) for a request
  1692. * for a (hopefully) nonexistent domain. */
  1693. static void
  1694. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1695. void *addresses, void *arg)
  1696. {
  1697. (void)ttl;
  1698. ++n_wildcard_requests;
  1699. if (result == DNS_ERR_NONE && count) {
  1700. char *string_address = arg;
  1701. int i;
  1702. if (type == DNS_IPv4_A) {
  1703. const uint32_t *addrs = addresses;
  1704. for (i = 0; i < count; ++i) {
  1705. char answer_buf[INET_NTOA_BUF_LEN+1];
  1706. struct in_addr in;
  1707. in.s_addr = addrs[i];
  1708. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1709. wildcard_increment_answer(answer_buf);
  1710. }
  1711. } else if (type == DNS_IPv6_AAAA) {
  1712. const struct in6_addr *addrs = addresses;
  1713. for (i = 0; i < count; ++i) {
  1714. char answer_buf[TOR_ADDR_BUF_LEN+1];
  1715. tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
  1716. wildcard_increment_answer(answer_buf);
  1717. }
  1718. }
  1719. log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1720. "Your DNS provider gave an answer for \"%s\", which "
  1721. "is not supposed to exist. Apparently they are hijacking "
  1722. "DNS failures. Trying to correct for this. We've noticed %d "
  1723. "possibly bad address%s so far.",
  1724. string_address, strmap_size(dns_wildcard_response_count),
  1725. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1726. dns_wildcard_one_notice_given = 1;
  1727. }
  1728. tor_free(arg);
  1729. }
  1730. /** Launch a single request for a nonexistent hostname consisting of between
  1731. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1732. * <b>suffix</b> */
  1733. static void
  1734. launch_wildcard_check(int min_len, int max_len, int is_ipv6,
  1735. const char *suffix)
  1736. {
  1737. char *addr;
  1738. struct evdns_request *req;
  1739. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1740. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1741. "domains with request for bogus hostname \"%s\"", addr);
  1742. tor_assert(the_evdns_base);
  1743. if (is_ipv6)
  1744. req = evdns_base_resolve_ipv6(
  1745. the_evdns_base,
  1746. /* This "addr" tells us which address to resolve */
  1747. addr,
  1748. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1749. /* This "addr" is an argument to the callback*/ addr);
  1750. else
  1751. req = evdns_base_resolve_ipv4(
  1752. the_evdns_base,
  1753. /* This "addr" tells us which address to resolve */
  1754. addr,
  1755. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1756. /* This "addr" is an argument to the callback*/ addr);
  1757. if (!req) {
  1758. /* There is no evdns request in progress; stop addr from getting leaked */
  1759. tor_free(addr);
  1760. }
  1761. }
  1762. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1763. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1764. static void
  1765. launch_test_addresses(int fd, short event, void *args)
  1766. {
  1767. const or_options_t *options = get_options();
  1768. (void)fd;
  1769. (void)event;
  1770. (void)args;
  1771. if (options->DisableNetwork)
  1772. return;
  1773. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1774. "hijack *everything*.");
  1775. /* This situation is worse than the failure-hijacking situation. When this
  1776. * happens, we're no good for DNS requests at all, and we shouldn't really
  1777. * be an exit server.*/
  1778. if (options->ServerDNSTestAddresses) {
  1779. tor_assert(the_evdns_base);
  1780. SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
  1781. const char *, address) {
  1782. if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
  1783. log_info(LD_EXIT, "eventdns rejected test address %s",
  1784. escaped_safe_str(address));
  1785. }
  1786. if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
  1787. log_info(LD_EXIT, "eventdns rejected test address %s",
  1788. escaped_safe_str(address));
  1789. }
  1790. } SMARTLIST_FOREACH_END(address);
  1791. }
  1792. }
  1793. #define N_WILDCARD_CHECKS 2
  1794. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1795. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1796. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1797. * buy these lovely encyclopedias" page. */
  1798. static void
  1799. dns_launch_wildcard_checks(void)
  1800. {
  1801. int i, ipv6;
  1802. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1803. "to hijack DNS failures.");
  1804. for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
  1805. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1806. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
  1807. * attempt to 'comply' with rfc2606, refrain from giving A records for
  1808. * these. This is the standards-compliance equivalent of making sure
  1809. * that your crackhouse's elevator inspection certificate is up to date.
  1810. */
  1811. launch_wildcard_check(2, 16, ipv6, ".invalid");
  1812. launch_wildcard_check(2, 16, ipv6, ".test");
  1813. /* These will break specs if there are ever any number of
  1814. * 8+-character top-level domains. */
  1815. launch_wildcard_check(8, 16, ipv6, "");
  1816. /* Try some random .com/org/net domains. This will work fine so long as
  1817. * not too many resolve to the same place. */
  1818. launch_wildcard_check(8, 16, ipv6, ".com");
  1819. launch_wildcard_check(8, 16, ipv6, ".org");
  1820. launch_wildcard_check(8, 16, ipv6, ".net");
  1821. }
  1822. }
  1823. }
  1824. /** If appropriate, start testing whether our DNS servers tend to lie to
  1825. * us. */
  1826. void
  1827. dns_launch_correctness_checks(void)
  1828. {
  1829. static struct event *launch_event = NULL;
  1830. struct timeval timeout;
  1831. if (!get_options()->ServerDNSDetectHijacking)
  1832. return;
  1833. dns_launch_wildcard_checks();
  1834. /* Wait a while before launching requests for test addresses, so we can
  1835. * get the results from checking for wildcarding. */
  1836. if (! launch_event)
  1837. launch_event = tor_evtimer_new(tor_libevent_get_base(),
  1838. launch_test_addresses, NULL);
  1839. timeout.tv_sec = 30;
  1840. timeout.tv_usec = 0;
  1841. if (evtimer_add(launch_event, &timeout)<0) {
  1842. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1843. }
  1844. }
  1845. /** Return true iff our DNS servers lie to us too much to be trusted. */
  1846. int
  1847. dns_seems_to_be_broken(void)
  1848. {
  1849. return dns_is_completely_invalid;
  1850. }
  1851. /** Return true iff we think that IPv6 hostname lookup is broken */
  1852. int
  1853. dns_seems_to_be_broken_for_ipv6(void)
  1854. {
  1855. return dns_is_broken_for_ipv6;
  1856. }
  1857. /** Forget what we've previously learned about our DNS servers' correctness. */
  1858. void
  1859. dns_reset_correctness_checks(void)
  1860. {
  1861. strmap_free(dns_wildcard_response_count, tor_free_);
  1862. dns_wildcard_response_count = NULL;
  1863. n_wildcard_requests = 0;
  1864. n_ipv6_requests_made = n_ipv6_timeouts = 0;
  1865. if (dns_wildcard_list) {
  1866. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1867. smartlist_clear(dns_wildcard_list);
  1868. }
  1869. if (dns_wildcarded_test_address_list) {
  1870. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1871. tor_free(cp));
  1872. smartlist_clear(dns_wildcarded_test_address_list);
  1873. }
  1874. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1875. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid =
  1876. dns_is_broken_for_ipv6 = 0;
  1877. }
  1878. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1879. * returned in response to requests for nonexistent hostnames. */
  1880. static int
  1881. answer_is_wildcarded(const char *ip)
  1882. {
  1883. return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
  1884. }
  1885. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1886. static void
  1887. assert_resolve_ok(cached_resolve_t *resolve)
  1888. {
  1889. tor_assert(resolve);
  1890. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1891. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1892. tor_assert(tor_strisnonupper(resolve->address));
  1893. if (resolve->state != CACHE_STATE_PENDING) {
  1894. tor_assert(!resolve->pending_connections);
  1895. }
  1896. if (resolve->state == CACHE_STATE_PENDING ||
  1897. resolve->state == CACHE_STATE_DONE) {
  1898. #if 0
  1899. tor_assert(!resolve->ttl);
  1900. if (resolve->is_reverse)
  1901. tor_assert(!resolve->hostname);
  1902. else
  1903. tor_assert(!resolve->result_ipv4.addr_ipv4);
  1904. #endif
  1905. /*XXXXX ADD MORE */
  1906. }
  1907. }
  1908. /** Return the number of DNS cache entries as an int */
  1909. static int
  1910. dns_cache_entry_count(void)
  1911. {
  1912. return HT_SIZE(&cache_root);
  1913. }
  1914. /** Log memory information about our internal DNS cache at level 'severity'. */
  1915. void
  1916. dump_dns_mem_usage(int severity)
  1917. {
  1918. /* This should never be larger than INT_MAX. */
  1919. int hash_count = dns_cache_entry_count();
  1920. size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
  1921. hash_mem += HT_MEM_USAGE(&cache_root);
  1922. /* Print out the count and estimated size of our &cache_root. It undercounts
  1923. hostnames in cached reverse resolves.
  1924. */
  1925. log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
  1926. log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
  1927. (unsigned)hash_mem);
  1928. }
  1929. #ifdef DEBUG_DNS_CACHE
  1930. /** Exit with an assertion if the DNS cache is corrupt. */
  1931. static void
  1932. assert_cache_ok_(void)
  1933. {
  1934. cached_resolve_t **resolve;
  1935. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1936. if (bad_rep) {
  1937. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1938. tor_assert(!bad_rep);
  1939. }
  1940. HT_FOREACH(resolve, cache_map, &cache_root) {
  1941. assert_resolve_ok(*resolve);
  1942. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1943. }
  1944. if (!cached_resolve_pqueue)
  1945. return;
  1946. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1947. compare_cached_resolves_by_expiry_,
  1948. STRUCT_OFFSET(cached_resolve_t, minheap_idx));
  1949. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1950. {
  1951. if (res->state == CACHE_STATE_DONE) {
  1952. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1953. tor_assert(!found || found != res);
  1954. } else {
  1955. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1956. tor_assert(found);
  1957. }
  1958. });
  1959. }
  1960. #endif