dns.c 74 KB

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