dns.c 75 KB

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