dns.c 76 KB

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