dns.c 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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. tor_free(hostname);
  1228. }
  1229. }
  1230. /** Remove a pending cached_resolve_t from the hashtable, and add a
  1231. * corresponding cached cached_resolve_t.
  1232. *
  1233. * This function is only necessary because of the perversity of our
  1234. * cache timeout code; see inline comment for ideas on eliminating it.
  1235. **/
  1236. static void
  1237. make_pending_resolve_cached(cached_resolve_t *resolve)
  1238. {
  1239. cached_resolve_t *removed;
  1240. resolve->state = CACHE_STATE_DONE;
  1241. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  1242. if (removed != resolve) {
  1243. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  1244. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1245. resolve->address, (void*)resolve,
  1246. removed ? removed->address : "NULL", (void*)removed);
  1247. }
  1248. assert_resolve_ok(resolve);
  1249. assert_cache_ok();
  1250. /* The resolve will eventually just hit the time-out in the expiry queue and
  1251. * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
  1252. * way. XXXXX we could do better!*/
  1253. {
  1254. cached_resolve_t *new_resolve = tor_memdup(resolve,
  1255. sizeof(cached_resolve_t));
  1256. uint32_t ttl = UINT32_MAX;
  1257. new_resolve->expire = 0; /* So that set_expiry won't croak. */
  1258. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  1259. new_resolve->result_ptr.hostname =
  1260. tor_strdup(resolve->result_ptr.hostname);
  1261. new_resolve->state = CACHE_STATE_CACHED;
  1262. assert_resolve_ok(new_resolve);
  1263. HT_INSERT(cache_map, &cache_root, new_resolve);
  1264. if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
  1265. resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
  1266. resolve->ttl_ipv4 < ttl)
  1267. ttl = resolve->ttl_ipv4;
  1268. if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
  1269. resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
  1270. resolve->ttl_ipv6 < ttl)
  1271. ttl = resolve->ttl_ipv6;
  1272. if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
  1273. resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
  1274. resolve->ttl_hostname < ttl)
  1275. ttl = resolve->ttl_hostname;
  1276. set_expiry(new_resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  1277. }
  1278. assert_cache_ok();
  1279. }
  1280. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1281. * a transient failure. */
  1282. static int
  1283. evdns_err_is_transient(int err)
  1284. {
  1285. switch (err)
  1286. {
  1287. case DNS_ERR_SERVERFAILED:
  1288. case DNS_ERR_TRUNCATED:
  1289. case DNS_ERR_TIMEOUT:
  1290. return 1;
  1291. default:
  1292. return 0;
  1293. }
  1294. }
  1295. /** Configure eventdns nameservers if force is true, or if the configuration
  1296. * has changed since the last time we called this function, or if we failed on
  1297. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1298. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1299. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1300. * -1 on failure. */
  1301. static int
  1302. configure_nameservers(int force)
  1303. {
  1304. const or_options_t *options;
  1305. const char *conf_fname;
  1306. struct stat st;
  1307. int r, flags;
  1308. options = get_options();
  1309. conf_fname = options->ServerDNSResolvConfFile;
  1310. #ifndef _WIN32
  1311. if (!conf_fname)
  1312. conf_fname = "/etc/resolv.conf";
  1313. #endif
  1314. flags = DNS_OPTIONS_ALL;
  1315. if (!the_evdns_base) {
  1316. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  1317. log_err(LD_BUG, "Couldn't create an evdns_base");
  1318. return -1;
  1319. }
  1320. }
  1321. #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  1322. if (! tor_addr_is_null(&options->OutboundBindAddressIPv4_)) {
  1323. int socklen;
  1324. struct sockaddr_storage ss;
  1325. socklen = tor_addr_to_sockaddr(&options->OutboundBindAddressIPv4_, 0,
  1326. (struct sockaddr *)&ss, sizeof(ss));
  1327. if (socklen <= 0) {
  1328. log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
  1329. " Ignoring.");
  1330. } else {
  1331. evdns_base_set_default_outgoing_bind_address(the_evdns_base,
  1332. (struct sockaddr *)&ss,
  1333. socklen);
  1334. }
  1335. }
  1336. #endif
  1337. evdns_set_log_fn(evdns_log_cb);
  1338. if (conf_fname) {
  1339. log_debug(LD_FS, "stat()ing %s", conf_fname);
  1340. if (stat(sandbox_intern_string(conf_fname), &st)) {
  1341. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1342. conf_fname, strerror(errno));
  1343. goto err;
  1344. }
  1345. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1346. && st.st_mtime == resolv_conf_mtime) {
  1347. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1348. return 0;
  1349. }
  1350. if (nameservers_configured) {
  1351. evdns_base_search_clear(the_evdns_base);
  1352. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1353. }
  1354. #if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
  1355. if (flags & DNS_OPTION_HOSTSFILE) {
  1356. flags ^= DNS_OPTION_HOSTSFILE;
  1357. log_debug(LD_FS, "Loading /etc/hosts");
  1358. evdns_base_load_hosts(the_evdns_base,
  1359. sandbox_intern_string("/etc/hosts"));
  1360. }
  1361. #endif
  1362. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1363. if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
  1364. sandbox_intern_string(conf_fname)))) {
  1365. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  1366. conf_fname, conf_fname, r);
  1367. goto err;
  1368. }
  1369. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1370. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1371. goto err;
  1372. }
  1373. tor_free(resolv_conf_fname);
  1374. resolv_conf_fname = tor_strdup(conf_fname);
  1375. resolv_conf_mtime = st.st_mtime;
  1376. if (nameservers_configured)
  1377. evdns_base_resume(the_evdns_base);
  1378. }
  1379. #ifdef _WIN32
  1380. else {
  1381. if (nameservers_configured) {
  1382. evdns_base_search_clear(the_evdns_base);
  1383. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1384. }
  1385. if (evdns_base_config_windows_nameservers(the_evdns_base)) {
  1386. log_warn(LD_EXIT,"Could not config nameservers.");
  1387. goto err;
  1388. }
  1389. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1390. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1391. "your Windows configuration.");
  1392. goto err;
  1393. }
  1394. if (nameservers_configured)
  1395. evdns_base_resume(the_evdns_base);
  1396. tor_free(resolv_conf_fname);
  1397. resolv_conf_mtime = 0;
  1398. }
  1399. #endif
  1400. #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
  1401. if (evdns_base_count_nameservers(the_evdns_base) == 1) {
  1402. SET("max-timeouts:", "16");
  1403. SET("timeout:", "10");
  1404. } else {
  1405. SET("max-timeouts:", "3");
  1406. SET("timeout:", "5");
  1407. }
  1408. if (options->ServerDNSRandomizeCase)
  1409. SET("randomize-case:", "1");
  1410. else
  1411. SET("randomize-case:", "0");
  1412. #undef SET
  1413. dns_servers_relaunch_checks();
  1414. nameservers_configured = 1;
  1415. if (nameserver_config_failed) {
  1416. nameserver_config_failed = 0;
  1417. /* XXX the three calls to republish the descriptor might be producing
  1418. * descriptors that are only cosmetically different, especially on
  1419. * non-exit relays! -RD */
  1420. mark_my_descriptor_dirty("dns resolvers back");
  1421. }
  1422. return 0;
  1423. err:
  1424. nameservers_configured = 0;
  1425. if (! nameserver_config_failed) {
  1426. nameserver_config_failed = 1;
  1427. mark_my_descriptor_dirty("dns resolvers failed");
  1428. }
  1429. return -1;
  1430. }
  1431. /** For eventdns: Called when we get an answer for a request we launched.
  1432. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1433. */
  1434. static void
  1435. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1436. void *arg)
  1437. {
  1438. char *arg_ = arg;
  1439. uint8_t orig_query_type = arg_[0];
  1440. char *string_address = arg_ + 1;
  1441. tor_addr_t addr;
  1442. const char *hostname = NULL;
  1443. int was_wildcarded = 0;
  1444. tor_addr_make_unspec(&addr);
  1445. /* Keep track of whether IPv6 is working */
  1446. if (type == DNS_IPv6_AAAA) {
  1447. if (result == DNS_ERR_TIMEOUT) {
  1448. ++n_ipv6_timeouts;
  1449. }
  1450. if (n_ipv6_timeouts > 10 &&
  1451. n_ipv6_timeouts > n_ipv6_requests_made / 2) {
  1452. if (! dns_is_broken_for_ipv6) {
  1453. log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
  1454. "have timed out. I'm going to assume I can't get AAAA "
  1455. "responses.");
  1456. dns_is_broken_for_ipv6 = 1;
  1457. }
  1458. }
  1459. }
  1460. if (result == DNS_ERR_NONE) {
  1461. if (type == DNS_IPv4_A && count) {
  1462. char answer_buf[INET_NTOA_BUF_LEN+1];
  1463. char *escaped_address;
  1464. uint32_t *addrs = addresses;
  1465. tor_addr_from_ipv4n(&addr, addrs[0]);
  1466. tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
  1467. escaped_address = esc_for_log(string_address);
  1468. if (answer_is_wildcarded(answer_buf)) {
  1469. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1470. "address %s; treating as a failure.",
  1471. safe_str(escaped_address),
  1472. escaped_safe_str(answer_buf));
  1473. was_wildcarded = 1;
  1474. tor_addr_make_unspec(&addr);
  1475. result = DNS_ERR_NOTEXIST;
  1476. } else {
  1477. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1478. safe_str(escaped_address),
  1479. escaped_safe_str(answer_buf));
  1480. }
  1481. tor_free(escaped_address);
  1482. } else if (type == DNS_IPv6_AAAA && count) {
  1483. char answer_buf[TOR_ADDR_BUF_LEN];
  1484. char *escaped_address;
  1485. struct in6_addr *addrs = addresses;
  1486. tor_addr_from_in6(&addr, &addrs[0]);
  1487. tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
  1488. escaped_address = esc_for_log(string_address);
  1489. if (answer_is_wildcarded(answer_buf)) {
  1490. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1491. "address %s; treating as a failure.",
  1492. safe_str(escaped_address),
  1493. escaped_safe_str(answer_buf));
  1494. was_wildcarded = 1;
  1495. tor_addr_make_unspec(&addr);
  1496. result = DNS_ERR_NOTEXIST;
  1497. } else {
  1498. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1499. safe_str(escaped_address),
  1500. escaped_safe_str(answer_buf));
  1501. }
  1502. tor_free(escaped_address);
  1503. } else if (type == DNS_PTR && count) {
  1504. char *escaped_address;
  1505. hostname = ((char**)addresses)[0];
  1506. escaped_address = esc_for_log(string_address);
  1507. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1508. safe_str(escaped_address),
  1509. escaped_safe_str(hostname));
  1510. tor_free(escaped_address);
  1511. } else if (count) {
  1512. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1513. escaped_safe_str(string_address));
  1514. } else {
  1515. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1516. escaped_safe_str(string_address));
  1517. }
  1518. }
  1519. if (was_wildcarded) {
  1520. if (is_test_address(string_address)) {
  1521. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1522. * server must really hate us. */
  1523. add_wildcarded_test_address(string_address);
  1524. }
  1525. }
  1526. if (orig_query_type && type && orig_query_type != type) {
  1527. log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
  1528. (int)orig_query_type, (int)type);
  1529. }
  1530. if (result != DNS_ERR_SHUTDOWN)
  1531. dns_found_answer(string_address, orig_query_type,
  1532. result, &addr, hostname, ttl);
  1533. tor_free(arg_);
  1534. }
  1535. /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
  1536. * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
  1537. * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
  1538. static int
  1539. launch_one_resolve(const char *address, uint8_t query_type,
  1540. const tor_addr_t *ptr_address)
  1541. {
  1542. const int options = get_options()->ServerDNSSearchDomains ? 0
  1543. : DNS_QUERY_NO_SEARCH;
  1544. const size_t addr_len = strlen(address);
  1545. struct evdns_request *req = 0;
  1546. char *addr = tor_malloc(addr_len + 2);
  1547. addr[0] = (char) query_type;
  1548. memcpy(addr+1, address, addr_len + 1);
  1549. switch (query_type) {
  1550. case DNS_IPv4_A:
  1551. req = evdns_base_resolve_ipv4(the_evdns_base,
  1552. address, options, evdns_callback, addr);
  1553. break;
  1554. case DNS_IPv6_AAAA:
  1555. req = evdns_base_resolve_ipv6(the_evdns_base,
  1556. address, options, evdns_callback, addr);
  1557. ++n_ipv6_requests_made;
  1558. break;
  1559. case DNS_PTR:
  1560. if (tor_addr_family(ptr_address) == AF_INET)
  1561. req = evdns_base_resolve_reverse(the_evdns_base,
  1562. tor_addr_to_in(ptr_address),
  1563. DNS_QUERY_NO_SEARCH,
  1564. evdns_callback, addr);
  1565. else if (tor_addr_family(ptr_address) == AF_INET6)
  1566. req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
  1567. tor_addr_to_in6(ptr_address),
  1568. DNS_QUERY_NO_SEARCH,
  1569. evdns_callback, addr);
  1570. else
  1571. log_warn(LD_BUG, "Called with PTR query and unexpected address family");
  1572. break;
  1573. default:
  1574. log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
  1575. break;
  1576. }
  1577. if (req) {
  1578. return 0;
  1579. } else {
  1580. tor_free(addr);
  1581. return -1;
  1582. }
  1583. }
  1584. /** For eventdns: start resolving as necessary to find the target for
  1585. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1586. * 0 on "resolve launched." */
  1587. static int
  1588. launch_resolve(cached_resolve_t *resolve)
  1589. {
  1590. tor_addr_t a;
  1591. int r;
  1592. if (get_options()->DisableNetwork)
  1593. return -1;
  1594. /* What? Nameservers not configured? Sounds like a bug. */
  1595. if (!nameservers_configured) {
  1596. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1597. "launched. Configuring.");
  1598. if (configure_nameservers(1) < 0) {
  1599. return -1;
  1600. }
  1601. }
  1602. r = tor_addr_parse_PTR_name(
  1603. &a, resolve->address, AF_UNSPEC, 0);
  1604. tor_assert(the_evdns_base);
  1605. if (r == 0) {
  1606. log_info(LD_EXIT, "Launching eventdns request for %s",
  1607. escaped_safe_str(resolve->address));
  1608. resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
  1609. if (get_options()->IPv6Exit)
  1610. resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
  1611. if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
  1612. resolve->res_status_ipv4 = 0;
  1613. r = -1;
  1614. }
  1615. if (r==0 && get_options()->IPv6Exit) {
  1616. /* We ask for an IPv6 address for *everything*. */
  1617. if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
  1618. resolve->res_status_ipv6 = 0;
  1619. r = -1;
  1620. }
  1621. }
  1622. } else if (r == 1) {
  1623. r = 0;
  1624. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1625. escaped_safe_str(resolve->address));
  1626. resolve->res_status_hostname = RES_STATUS_INFLIGHT;
  1627. if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
  1628. resolve->res_status_hostname = 0;
  1629. r = -1;
  1630. }
  1631. } else if (r == -1) {
  1632. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1633. }
  1634. if (r < 0) {
  1635. log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
  1636. escaped_safe_str(resolve->address));
  1637. }
  1638. return r;
  1639. }
  1640. /** How many requests for bogus addresses have we launched so far? */
  1641. static int n_wildcard_requests = 0;
  1642. /** Map from dotted-quad IP address in response to an int holding how many
  1643. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1644. * would be easier to use definitely-invalid addresses (as specified by
  1645. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1646. static strmap_t *dns_wildcard_response_count = NULL;
  1647. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1648. * nameserver wants to return in response to requests for nonexistent domains.
  1649. */
  1650. static smartlist_t *dns_wildcard_list = NULL;
  1651. /** True iff we've logged about a single address getting wildcarded.
  1652. * Subsequent warnings will be less severe. */
  1653. static int dns_wildcard_one_notice_given = 0;
  1654. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1655. */
  1656. static int dns_wildcard_notice_given = 0;
  1657. /** List of supposedly good addresses that are getting wildcarded to the
  1658. * same addresses as nonexistent addresses. */
  1659. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1660. /** True iff we've warned about a test address getting wildcarded */
  1661. static int dns_wildcarded_test_address_notice_given = 0;
  1662. /** True iff all addresses seem to be getting wildcarded. */
  1663. static int dns_is_completely_invalid = 0;
  1664. /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
  1665. * to a request for a hopefully bogus address. */
  1666. static void
  1667. wildcard_increment_answer(const char *id)
  1668. {
  1669. int *ip;
  1670. if (!dns_wildcard_response_count)
  1671. dns_wildcard_response_count = strmap_new();
  1672. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1673. if (!ip) {
  1674. ip = tor_malloc_zero(sizeof(int));
  1675. strmap_set(dns_wildcard_response_count, id, ip);
  1676. }
  1677. ++*ip;
  1678. if (*ip > 5 && n_wildcard_requests > 10) {
  1679. if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
  1680. if (!smartlist_contains_string(dns_wildcard_list, id)) {
  1681. tor_log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1682. "Your DNS provider has given \"%s\" as an answer for %d different "
  1683. "invalid addresses. Apparently they are hijacking DNS failures. "
  1684. "I'll try to correct for this by treating future occurrences of "
  1685. "\"%s\" as 'not found'.", id, *ip, id);
  1686. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1687. }
  1688. if (!dns_wildcard_notice_given)
  1689. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1690. dns_wildcard_notice_given = 1;
  1691. }
  1692. }
  1693. /** Note that a single test address (one believed to be good) seems to be
  1694. * getting redirected to the same IP as failures are. */
  1695. static void
  1696. add_wildcarded_test_address(const char *address)
  1697. {
  1698. int n, n_test_addrs;
  1699. if (!dns_wildcarded_test_address_list)
  1700. dns_wildcarded_test_address_list = smartlist_new();
  1701. if (smartlist_contains_string_case(dns_wildcarded_test_address_list,
  1702. address))
  1703. return;
  1704. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1705. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1706. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1707. n = smartlist_len(dns_wildcarded_test_address_list);
  1708. if (n > n_test_addrs/2) {
  1709. tor_log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1710. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1711. "address. It has done this with %d test addresses so far. I'm "
  1712. "going to stop being an exit node for now, since our DNS seems so "
  1713. "broken.", address, n);
  1714. if (!dns_is_completely_invalid) {
  1715. dns_is_completely_invalid = 1;
  1716. mark_my_descriptor_dirty("dns hijacking confirmed");
  1717. }
  1718. if (!dns_wildcarded_test_address_notice_given)
  1719. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1720. dns_wildcarded_test_address_notice_given = 1;
  1721. }
  1722. }
  1723. /** Callback function when we get an answer (possibly failing) for a request
  1724. * for a (hopefully) nonexistent domain. */
  1725. static void
  1726. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1727. void *addresses, void *arg)
  1728. {
  1729. (void)ttl;
  1730. ++n_wildcard_requests;
  1731. if (result == DNS_ERR_NONE && count) {
  1732. char *string_address = arg;
  1733. int i;
  1734. if (type == DNS_IPv4_A) {
  1735. const uint32_t *addrs = addresses;
  1736. for (i = 0; i < count; ++i) {
  1737. char answer_buf[INET_NTOA_BUF_LEN+1];
  1738. struct in_addr in;
  1739. in.s_addr = addrs[i];
  1740. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1741. wildcard_increment_answer(answer_buf);
  1742. }
  1743. } else if (type == DNS_IPv6_AAAA) {
  1744. const struct in6_addr *addrs = addresses;
  1745. for (i = 0; i < count; ++i) {
  1746. char answer_buf[TOR_ADDR_BUF_LEN+1];
  1747. tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
  1748. wildcard_increment_answer(answer_buf);
  1749. }
  1750. }
  1751. tor_log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1752. "Your DNS provider gave an answer for \"%s\", which "
  1753. "is not supposed to exist. Apparently they are hijacking "
  1754. "DNS failures. Trying to correct for this. We've noticed %d "
  1755. "possibly bad address%s so far.",
  1756. string_address, strmap_size(dns_wildcard_response_count),
  1757. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1758. dns_wildcard_one_notice_given = 1;
  1759. }
  1760. tor_free(arg);
  1761. }
  1762. /** Launch a single request for a nonexistent hostname consisting of between
  1763. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1764. * <b>suffix</b> */
  1765. static void
  1766. launch_wildcard_check(int min_len, int max_len, int is_ipv6,
  1767. const char *suffix)
  1768. {
  1769. char *addr;
  1770. struct evdns_request *req;
  1771. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1772. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1773. "domains with request for bogus hostname \"%s\"", addr);
  1774. tor_assert(the_evdns_base);
  1775. if (is_ipv6)
  1776. req = evdns_base_resolve_ipv6(
  1777. the_evdns_base,
  1778. /* This "addr" tells us which address to resolve */
  1779. addr,
  1780. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1781. /* This "addr" is an argument to the callback*/ addr);
  1782. else
  1783. req = evdns_base_resolve_ipv4(
  1784. the_evdns_base,
  1785. /* This "addr" tells us which address to resolve */
  1786. addr,
  1787. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1788. /* This "addr" is an argument to the callback*/ addr);
  1789. if (!req) {
  1790. /* There is no evdns request in progress; stop addr from getting leaked */
  1791. tor_free(addr);
  1792. }
  1793. }
  1794. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1795. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1796. static void
  1797. launch_test_addresses(evutil_socket_t fd, short event, void *args)
  1798. {
  1799. const or_options_t *options = get_options();
  1800. (void)fd;
  1801. (void)event;
  1802. (void)args;
  1803. if (options->DisableNetwork)
  1804. return;
  1805. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1806. "hijack *everything*.");
  1807. /* This situation is worse than the failure-hijacking situation. When this
  1808. * happens, we're no good for DNS requests at all, and we shouldn't really
  1809. * be an exit server.*/
  1810. if (options->ServerDNSTestAddresses) {
  1811. tor_assert(the_evdns_base);
  1812. SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
  1813. const char *, address) {
  1814. if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
  1815. log_info(LD_EXIT, "eventdns rejected test address %s",
  1816. escaped_safe_str(address));
  1817. }
  1818. if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
  1819. log_info(LD_EXIT, "eventdns rejected test address %s",
  1820. escaped_safe_str(address));
  1821. }
  1822. } SMARTLIST_FOREACH_END(address);
  1823. }
  1824. }
  1825. #define N_WILDCARD_CHECKS 2
  1826. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1827. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1828. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1829. * buy these lovely encyclopedias" page. */
  1830. static void
  1831. dns_launch_wildcard_checks(void)
  1832. {
  1833. int i, ipv6;
  1834. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1835. "to hijack DNS failures.");
  1836. for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
  1837. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1838. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
  1839. * attempt to 'comply' with rfc2606, refrain from giving A records for
  1840. * these. This is the standards-compliance equivalent of making sure
  1841. * that your crackhouse's elevator inspection certificate is up to date.
  1842. */
  1843. launch_wildcard_check(2, 16, ipv6, ".invalid");
  1844. launch_wildcard_check(2, 16, ipv6, ".test");
  1845. /* These will break specs if there are ever any number of
  1846. * 8+-character top-level domains. */
  1847. launch_wildcard_check(8, 16, ipv6, "");
  1848. /* Try some random .com/org/net domains. This will work fine so long as
  1849. * not too many resolve to the same place. */
  1850. launch_wildcard_check(8, 16, ipv6, ".com");
  1851. launch_wildcard_check(8, 16, ipv6, ".org");
  1852. launch_wildcard_check(8, 16, ipv6, ".net");
  1853. }
  1854. }
  1855. }
  1856. /** If appropriate, start testing whether our DNS servers tend to lie to
  1857. * us. */
  1858. void
  1859. dns_launch_correctness_checks(void)
  1860. {
  1861. static struct event *launch_event = NULL;
  1862. struct timeval timeout;
  1863. if (!get_options()->ServerDNSDetectHijacking)
  1864. return;
  1865. dns_launch_wildcard_checks();
  1866. /* Wait a while before launching requests for test addresses, so we can
  1867. * get the results from checking for wildcarding. */
  1868. if (! launch_event)
  1869. launch_event = tor_evtimer_new(tor_libevent_get_base(),
  1870. launch_test_addresses, NULL);
  1871. timeout.tv_sec = 30;
  1872. timeout.tv_usec = 0;
  1873. if (evtimer_add(launch_event, &timeout)<0) {
  1874. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1875. }
  1876. }
  1877. /** Return true iff our DNS servers lie to us too much to be trusted. */
  1878. int
  1879. dns_seems_to_be_broken(void)
  1880. {
  1881. return dns_is_completely_invalid;
  1882. }
  1883. /** Return true iff we think that IPv6 hostname lookup is broken */
  1884. int
  1885. dns_seems_to_be_broken_for_ipv6(void)
  1886. {
  1887. return dns_is_broken_for_ipv6;
  1888. }
  1889. /** Forget what we've previously learned about our DNS servers' correctness. */
  1890. void
  1891. dns_reset_correctness_checks(void)
  1892. {
  1893. strmap_free(dns_wildcard_response_count, tor_free_);
  1894. dns_wildcard_response_count = NULL;
  1895. n_wildcard_requests = 0;
  1896. n_ipv6_requests_made = n_ipv6_timeouts = 0;
  1897. if (dns_wildcard_list) {
  1898. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1899. smartlist_clear(dns_wildcard_list);
  1900. }
  1901. if (dns_wildcarded_test_address_list) {
  1902. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1903. tor_free(cp));
  1904. smartlist_clear(dns_wildcarded_test_address_list);
  1905. }
  1906. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1907. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid =
  1908. dns_is_broken_for_ipv6 = 0;
  1909. }
  1910. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1911. * returned in response to requests for nonexistent hostnames. */
  1912. static int
  1913. answer_is_wildcarded(const char *ip)
  1914. {
  1915. return dns_wildcard_list && smartlist_contains_string(dns_wildcard_list, ip);
  1916. }
  1917. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1918. static void
  1919. assert_resolve_ok(cached_resolve_t *resolve)
  1920. {
  1921. tor_assert(resolve);
  1922. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1923. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1924. tor_assert(tor_strisnonupper(resolve->address));
  1925. if (resolve->state != CACHE_STATE_PENDING) {
  1926. tor_assert(!resolve->pending_connections);
  1927. }
  1928. if (resolve->state == CACHE_STATE_PENDING ||
  1929. resolve->state == CACHE_STATE_DONE) {
  1930. #if 0
  1931. tor_assert(!resolve->ttl);
  1932. if (resolve->is_reverse)
  1933. tor_assert(!resolve->hostname);
  1934. else
  1935. tor_assert(!resolve->result_ipv4.addr_ipv4);
  1936. #endif
  1937. /*XXXXX ADD MORE */
  1938. }
  1939. }
  1940. /** Return the number of DNS cache entries as an int */
  1941. static int
  1942. dns_cache_entry_count(void)
  1943. {
  1944. return HT_SIZE(&cache_root);
  1945. }
  1946. /** Log memory information about our internal DNS cache at level 'severity'. */
  1947. void
  1948. dump_dns_mem_usage(int severity)
  1949. {
  1950. /* This should never be larger than INT_MAX. */
  1951. int hash_count = dns_cache_entry_count();
  1952. size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
  1953. hash_mem += HT_MEM_USAGE(&cache_root);
  1954. /* Print out the count and estimated size of our &cache_root. It undercounts
  1955. hostnames in cached reverse resolves.
  1956. */
  1957. tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
  1958. tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
  1959. (unsigned)hash_mem);
  1960. }
  1961. #ifdef DEBUG_DNS_CACHE
  1962. /** Exit with an assertion if the DNS cache is corrupt. */
  1963. static void
  1964. assert_cache_ok_(void)
  1965. {
  1966. cached_resolve_t **resolve;
  1967. int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
  1968. if (bad_rep) {
  1969. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1970. tor_assert(!bad_rep);
  1971. }
  1972. HT_FOREACH(resolve, cache_map, &cache_root) {
  1973. assert_resolve_ok(*resolve);
  1974. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1975. }
  1976. if (!cached_resolve_pqueue)
  1977. return;
  1978. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1979. compare_cached_resolves_by_expiry_,
  1980. STRUCT_OFFSET(cached_resolve_t, minheap_idx));
  1981. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1982. {
  1983. if (res->state == CACHE_STATE_DONE) {
  1984. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1985. tor_assert(!found || found != res);
  1986. } else {
  1987. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1988. tor_assert(found);
  1989. }
  1990. });
  1991. }
  1992. #endif