dns.c 74 KB

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