dns.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2015, 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 "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_GENERATE2(cache_map, cached_resolve_t, node, cached_resolve_hash,
  224. cached_resolves_eq, 0.6, tor_reallocarray_, tor_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. /* Prevent double-remove */
  512. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  513. if (!pendconn->base_.marked_for_close) {
  514. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT);
  515. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  516. connection_free(TO_CONN(pendconn));
  517. }
  518. tor_free(pend);
  519. }
  520. }
  521. if (resolve->state == CACHE_STATE_CACHED ||
  522. resolve->state == CACHE_STATE_PENDING) {
  523. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  524. if (removed != resolve) {
  525. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  526. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  527. resolve->address, (void*)resolve,
  528. removed ? removed->address : "NULL", (void*)removed);
  529. }
  530. tor_assert(removed == resolve);
  531. } else {
  532. /* This should be in state DONE. Make sure it's not in the cache. */
  533. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  534. tor_assert(tmp != resolve);
  535. }
  536. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  537. tor_free(resolve->result_ptr.hostname);
  538. resolve->magic = 0xF0BBF0BB;
  539. tor_free(resolve);
  540. }
  541. assert_cache_ok();
  542. }
  543. /* argument for send_resolved_cell only, meaning "let the answer type be ipv4
  544. * or ipv6 depending on the connection's address". */
  545. #define RESOLVED_TYPE_AUTO 0xff
  546. /** Send a response to the RESOLVE request of a connection.
  547. * <b>answer_type</b> must be one of
  548. * RESOLVED_TYPE_(AUTO|ERROR|ERROR_TRANSIENT|).
  549. *
  550. * If <b>circ</b> is provided, and we have a cached answer, send the
  551. * answer back along circ; otherwise, send the answer back along
  552. * <b>conn</b>'s attached circuit.
  553. */
  554. static void
  555. send_resolved_cell(edge_connection_t *conn, uint8_t answer_type,
  556. const cached_resolve_t *resolved)
  557. {
  558. char buf[RELAY_PAYLOAD_SIZE], *cp = buf;
  559. size_t buflen = 0;
  560. uint32_t ttl;
  561. buf[0] = answer_type;
  562. ttl = dns_clip_ttl(conn->address_ttl);
  563. switch (answer_type)
  564. {
  565. case RESOLVED_TYPE_AUTO:
  566. if (resolved && resolved->res_status_ipv4 == RES_STATUS_DONE_OK) {
  567. cp[0] = RESOLVED_TYPE_IPV4;
  568. cp[1] = 4;
  569. set_uint32(cp+2, htonl(resolved->result_ipv4.addr_ipv4));
  570. set_uint32(cp+6, htonl(ttl));
  571. cp += 10;
  572. }
  573. if (resolved && resolved->res_status_ipv6 == RES_STATUS_DONE_OK) {
  574. const uint8_t *bytes = resolved->result_ipv6.addr_ipv6.s6_addr;
  575. cp[0] = RESOLVED_TYPE_IPV6;
  576. cp[1] = 16;
  577. memcpy(cp+2, bytes, 16);
  578. set_uint32(cp+18, htonl(ttl));
  579. cp += 22;
  580. }
  581. if (cp != buf) {
  582. buflen = cp - buf;
  583. break;
  584. } else {
  585. answer_type = RESOLVED_TYPE_ERROR;
  586. /* fall through. */
  587. }
  588. case RESOLVED_TYPE_ERROR_TRANSIENT:
  589. case RESOLVED_TYPE_ERROR:
  590. {
  591. const char *errmsg = "Error resolving hostname";
  592. size_t msglen = strlen(errmsg);
  593. buf[0] = answer_type;
  594. buf[1] = msglen;
  595. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  596. set_uint32(buf+2+msglen, htonl(ttl));
  597. buflen = 6+msglen;
  598. break;
  599. }
  600. default:
  601. tor_assert(0);
  602. return;
  603. }
  604. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  605. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  606. }
  607. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  608. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  609. * The answer type will be RESOLVED_HOSTNAME.
  610. *
  611. * If <b>circ</b> is provided, and we have a cached answer, send the
  612. * answer back along circ; otherwise, send the answer back along
  613. * <b>conn</b>'s attached circuit.
  614. */
  615. static void
  616. send_resolved_hostname_cell(edge_connection_t *conn, const char *hostname)
  617. {
  618. char buf[RELAY_PAYLOAD_SIZE];
  619. size_t buflen;
  620. uint32_t ttl;
  621. size_t namelen = strlen(hostname);
  622. tor_assert(hostname);
  623. tor_assert(namelen < 256);
  624. ttl = dns_clip_ttl(conn->address_ttl);
  625. buf[0] = RESOLVED_TYPE_HOSTNAME;
  626. buf[1] = (uint8_t)namelen;
  627. memcpy(buf+2, hostname, namelen);
  628. set_uint32(buf+2+namelen, htonl(ttl));
  629. buflen = 2+namelen+4;
  630. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  631. connection_edge_send_command(conn, RELAY_COMMAND_RESOLVED, buf, buflen);
  632. // log_notice(LD_EXIT, "Sent");
  633. }
  634. /** See if we have a cache entry for <b>exitconn</b>-\>address. If so,
  635. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  636. * If resolve failed, free exitconn and return -1.
  637. *
  638. * (For EXIT_PURPOSE_RESOLVE connections, send back a RESOLVED error cell
  639. * on returning -1. For EXIT_PURPOSE_CONNECT connections, there's no
  640. * need to send back an END cell, since connection_exit_begin_conn will
  641. * do that for us.)
  642. *
  643. * If we have a cached answer, send the answer back along <b>exitconn</b>'s
  644. * circuit.
  645. *
  646. * Else, if seen before and pending, add conn to the pending list,
  647. * and return 0.
  648. *
  649. * Else, if not seen before, add conn to pending list, hand to
  650. * dns farm, and return 0.
  651. *
  652. * Exitconn's on_circuit field must be set, but exitconn should not
  653. * yet be linked onto the n_streams/resolving_streams list of that circuit.
  654. * On success, link the connection to n_streams if it's an exit connection.
  655. * On "pending", link the connection to resolving streams. Otherwise,
  656. * clear its on_circuit field.
  657. */
  658. int
  659. dns_resolve(edge_connection_t *exitconn)
  660. {
  661. or_circuit_t *oncirc = TO_OR_CIRCUIT(exitconn->on_circuit);
  662. int is_resolve, r;
  663. int made_connection_pending = 0;
  664. char *hostname = NULL;
  665. cached_resolve_t *resolve = NULL;
  666. is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
  667. r = dns_resolve_impl(exitconn, is_resolve, oncirc, &hostname,
  668. &made_connection_pending, &resolve);
  669. switch (r) {
  670. case 1:
  671. /* We got an answer without a lookup -- either the answer was
  672. * cached, or it was obvious (like an IP address). */
  673. if (is_resolve) {
  674. /* Send the answer back right now, and detach. */
  675. if (hostname)
  676. send_resolved_hostname_cell(exitconn, hostname);
  677. else
  678. send_resolved_cell(exitconn, RESOLVED_TYPE_AUTO, resolve);
  679. exitconn->on_circuit = NULL;
  680. } else {
  681. /* Add to the n_streams list; the calling function will send back a
  682. * connected cell. */
  683. exitconn->next_stream = oncirc->n_streams;
  684. oncirc->n_streams = exitconn;
  685. }
  686. break;
  687. case 0:
  688. /* The request is pending: add the connection into the linked list of
  689. * resolving_streams on this circuit. */
  690. exitconn->base_.state = EXIT_CONN_STATE_RESOLVING;
  691. exitconn->next_stream = oncirc->resolving_streams;
  692. oncirc->resolving_streams = exitconn;
  693. break;
  694. case -2:
  695. case -1:
  696. /* The request failed before it could start: cancel this connection,
  697. * and stop everybody waiting for the same connection. */
  698. if (is_resolve) {
  699. send_resolved_cell(exitconn,
  700. (r == -1) ? RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
  701. NULL);
  702. }
  703. exitconn->on_circuit = NULL;
  704. dns_cancel_pending_resolve(exitconn->base_.address);
  705. if (!made_connection_pending && !exitconn->base_.marked_for_close) {
  706. /* If we made the connection pending, then we freed it already in
  707. * dns_cancel_pending_resolve(). If we marked it for close, it'll
  708. * get freed from the main loop. Otherwise, can free it now. */
  709. connection_free(TO_CONN(exitconn));
  710. }
  711. break;
  712. default:
  713. tor_assert(0);
  714. }
  715. tor_free(hostname);
  716. return r;
  717. }
  718. /** Helper function for dns_resolve: same functionality, but does not handle:
  719. * - marking connections on error and clearing their on_circuit
  720. * - linking connections to n_streams/resolving_streams,
  721. * - sending resolved cells if we have an answer/error right away,
  722. *
  723. * Return -2 on a transient error. If it's a reverse resolve and it's
  724. * successful, sets *<b>hostname_out</b> to a newly allocated string
  725. * holding the cached reverse DNS value.
  726. *
  727. * Set *<b>made_connection_pending_out</b> to true if we have placed
  728. * <b>exitconn</b> on the list of pending connections for some resolve; set it
  729. * to false otherwise.
  730. *
  731. * Set *<b>resolve_out</b> to a cached resolve, if we found one.
  732. */
  733. static int
  734. dns_resolve_impl(edge_connection_t *exitconn, int is_resolve,
  735. or_circuit_t *oncirc, char **hostname_out,
  736. int *made_connection_pending_out,
  737. cached_resolve_t **resolve_out)
  738. {
  739. cached_resolve_t *resolve;
  740. cached_resolve_t search;
  741. pending_connection_t *pending_connection;
  742. int is_reverse = 0;
  743. tor_addr_t addr;
  744. time_t now = time(NULL);
  745. int r;
  746. assert_connection_ok(TO_CONN(exitconn), 0);
  747. tor_assert(!SOCKET_OK(exitconn->base_.s));
  748. assert_cache_ok();
  749. tor_assert(oncirc);
  750. *made_connection_pending_out = 0;
  751. /* first check if exitconn->base_.address is an IP. If so, we already
  752. * know the answer. */
  753. if (tor_addr_parse(&addr, exitconn->base_.address) >= 0) {
  754. if (tor_addr_family(&addr) == AF_INET ||
  755. tor_addr_family(&addr) == AF_INET6) {
  756. tor_addr_copy(&exitconn->base_.addr, &addr);
  757. exitconn->address_ttl = DEFAULT_DNS_TTL;
  758. return 1;
  759. } else {
  760. /* XXXX unspec? Bogus? */
  761. return -1;
  762. }
  763. }
  764. /* If we're a non-exit, don't even do DNS lookups. */
  765. if (router_my_exit_policy_is_reject_star())
  766. return -1;
  767. if (address_is_invalid_destination(exitconn->base_.address, 0)) {
  768. tor_log(LOG_PROTOCOL_WARN, LD_EXIT,
  769. "Rejecting invalid destination address %s",
  770. escaped_safe_str(exitconn->base_.address));
  771. return -1;
  772. }
  773. /* then take this opportunity to see if there are any expired
  774. * resolves in the hash table. */
  775. purge_expired_resolves(now);
  776. /* lower-case exitconn->base_.address, so it's in canonical form */
  777. tor_strlower(exitconn->base_.address);
  778. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  779. * .in-addr.arpa address but this isn't a resolve request, kill the
  780. * connection.
  781. */
  782. if ((r = tor_addr_parse_PTR_name(&addr, exitconn->base_.address,
  783. AF_UNSPEC, 0)) != 0) {
  784. if (r == 1) {
  785. is_reverse = 1;
  786. if (tor_addr_is_internal(&addr, 0)) /* internal address? */
  787. return -1;
  788. }
  789. if (!is_reverse || !is_resolve) {
  790. if (!is_reverse)
  791. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  792. escaped_safe_str(exitconn->base_.address));
  793. else if (!is_resolve)
  794. log_info(LD_EXIT,
  795. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  796. "sending error.",
  797. escaped_safe_str(exitconn->base_.address));
  798. return -1;
  799. }
  800. //log_notice(LD_EXIT, "Looks like an address %s",
  801. //exitconn->base_.address);
  802. }
  803. exitconn->is_reverse_dns_lookup = is_reverse;
  804. /* now check the hash table to see if 'address' is already there. */
  805. strlcpy(search.address, exitconn->base_.address, sizeof(search.address));
  806. resolve = HT_FIND(cache_map, &cache_root, &search);
  807. if (resolve && resolve->expire > now) { /* already there */
  808. switch (resolve->state) {
  809. case CACHE_STATE_PENDING:
  810. /* add us to the pending list */
  811. pending_connection = tor_malloc_zero(
  812. sizeof(pending_connection_t));
  813. pending_connection->conn = exitconn;
  814. pending_connection->next = resolve->pending_connections;
  815. resolve->pending_connections = pending_connection;
  816. *made_connection_pending_out = 1;
  817. log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") waiting "
  818. "for pending DNS resolve of %s", exitconn->base_.s,
  819. escaped_safe_str(exitconn->base_.address));
  820. return 0;
  821. case CACHE_STATE_CACHED:
  822. log_debug(LD_EXIT,"Connection (fd "TOR_SOCKET_T_FORMAT") found "
  823. "cached answer for %s",
  824. exitconn->base_.s,
  825. escaped_safe_str(resolve->address));
  826. *resolve_out = resolve;
  827. return set_exitconn_info_from_resolve(exitconn, resolve, hostname_out);
  828. case CACHE_STATE_DONE:
  829. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  830. tor_fragile_assert();
  831. }
  832. tor_assert(0);
  833. }
  834. tor_assert(!resolve);
  835. /* not there, need to add it */
  836. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  837. resolve->magic = CACHED_RESOLVE_MAGIC;
  838. resolve->state = CACHE_STATE_PENDING;
  839. resolve->minheap_idx = -1;
  840. strlcpy(resolve->address, exitconn->base_.address, sizeof(resolve->address));
  841. /* add this connection to the pending list */
  842. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  843. pending_connection->conn = exitconn;
  844. resolve->pending_connections = pending_connection;
  845. *made_connection_pending_out = 1;
  846. /* Add this resolve to the cache and priority queue. */
  847. HT_INSERT(cache_map, &cache_root, resolve);
  848. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  849. log_debug(LD_EXIT,"Launching %s.",
  850. escaped_safe_str(exitconn->base_.address));
  851. assert_cache_ok();
  852. return launch_resolve(resolve);
  853. }
  854. /** Given an exit connection <b>exitconn</b>, and a cached_resolve_t
  855. * <b>resolve</b> whose DNS lookups have all succeeded or failed, update the
  856. * appropriate fields (address_ttl and addr) of <b>exitconn</b>.
  857. *
  858. * If this is a reverse lookup, set *<b>hostname_out</b> to a newly allocated
  859. * copy of the name resulting hostname.
  860. *
  861. * Return -2 on a transient error, -1 on a permenent error, and 1 on
  862. * a successful lookup.
  863. */
  864. static int
  865. set_exitconn_info_from_resolve(edge_connection_t *exitconn,
  866. const cached_resolve_t *resolve,
  867. char **hostname_out)
  868. {
  869. int ipv4_ok, ipv6_ok, answer_with_ipv4, r;
  870. uint32_t begincell_flags;
  871. const int is_resolve = exitconn->base_.purpose == EXIT_PURPOSE_RESOLVE;
  872. tor_assert(exitconn);
  873. tor_assert(resolve);
  874. if (exitconn->is_reverse_dns_lookup) {
  875. exitconn->address_ttl = resolve->ttl_hostname;
  876. if (resolve->res_status_hostname == RES_STATUS_DONE_OK) {
  877. *hostname_out = tor_strdup(resolve->result_ptr.hostname);
  878. return 1;
  879. } else {
  880. return -1;
  881. }
  882. }
  883. /* If we're here then the connection wants one or either of ipv4, ipv6, and
  884. * we can give it one or both. */
  885. if (is_resolve) {
  886. begincell_flags = BEGIN_FLAG_IPV6_OK;
  887. } else {
  888. begincell_flags = exitconn->begincell_flags;
  889. }
  890. ipv4_ok = (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) &&
  891. ! (begincell_flags & BEGIN_FLAG_IPV4_NOT_OK);
  892. ipv6_ok = (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) &&
  893. (begincell_flags & BEGIN_FLAG_IPV6_OK) &&
  894. get_options()->IPv6Exit;
  895. /* Now decide which one to actually give. */
  896. if (ipv4_ok && ipv6_ok && is_resolve) {
  897. answer_with_ipv4 = 1;
  898. } else if (ipv4_ok && ipv6_ok) {
  899. /* If we have both, see if our exit policy has an opinion. */
  900. const uint16_t port = exitconn->base_.port;
  901. int ipv4_allowed, ipv6_allowed;
  902. tor_addr_t a4, a6;
  903. tor_addr_from_ipv4h(&a4, resolve->result_ipv4.addr_ipv4);
  904. tor_addr_from_in6(&a6, &resolve->result_ipv6.addr_ipv6);
  905. ipv4_allowed = !router_compare_to_my_exit_policy(&a4, port);
  906. ipv6_allowed = !router_compare_to_my_exit_policy(&a6, port);
  907. if (ipv4_allowed && !ipv6_allowed) {
  908. answer_with_ipv4 = 1;
  909. } else if (ipv6_allowed && !ipv4_allowed) {
  910. answer_with_ipv4 = 0;
  911. } else {
  912. /* Our exit policy would permit both. Answer with whichever the user
  913. * prefers */
  914. answer_with_ipv4 = !(begincell_flags &
  915. BEGIN_FLAG_IPV6_PREFERRED);
  916. }
  917. } else {
  918. /* Otherwise if one is okay, send it back. */
  919. if (ipv4_ok) {
  920. answer_with_ipv4 = 1;
  921. } else if (ipv6_ok) {
  922. answer_with_ipv4 = 0;
  923. } else {
  924. /* Neither one was okay. Choose based on user preference. */
  925. answer_with_ipv4 = !(begincell_flags &
  926. BEGIN_FLAG_IPV6_PREFERRED);
  927. }
  928. }
  929. /* Finally, we write the answer back. */
  930. r = 1;
  931. if (answer_with_ipv4) {
  932. if (resolve->res_status_ipv4 == RES_STATUS_DONE_OK) {
  933. tor_addr_from_ipv4h(&exitconn->base_.addr,
  934. resolve->result_ipv4.addr_ipv4);
  935. } else {
  936. r = evdns_err_is_transient(resolve->result_ipv4.err_ipv4) ? -2 : -1;
  937. }
  938. exitconn->address_ttl = resolve->ttl_ipv4;
  939. } else {
  940. if (resolve->res_status_ipv6 == RES_STATUS_DONE_OK) {
  941. tor_addr_from_in6(&exitconn->base_.addr,
  942. &resolve->result_ipv6.addr_ipv6);
  943. } else {
  944. r = evdns_err_is_transient(resolve->result_ipv6.err_ipv6) ? -2 : -1;
  945. }
  946. exitconn->address_ttl = resolve->ttl_ipv6;
  947. }
  948. return r;
  949. }
  950. /** Log an error and abort if conn is waiting for a DNS resolve.
  951. */
  952. void
  953. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  954. {
  955. pending_connection_t *pend;
  956. cached_resolve_t search;
  957. #if 1
  958. cached_resolve_t *resolve;
  959. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  960. resolve = HT_FIND(cache_map, &cache_root, &search);
  961. if (!resolve)
  962. return;
  963. for (pend = resolve->pending_connections; pend; pend = pend->next) {
  964. tor_assert(pend->conn != conn);
  965. }
  966. #else
  967. cached_resolve_t **resolve;
  968. HT_FOREACH(resolve, cache_map, &cache_root) {
  969. for (pend = (*resolve)->pending_connections; pend; pend = pend->next) {
  970. tor_assert(pend->conn != conn);
  971. }
  972. }
  973. #endif
  974. }
  975. /** Log an error and abort if any connection waiting for a DNS resolve is
  976. * corrupted. */
  977. void
  978. assert_all_pending_dns_resolves_ok(void)
  979. {
  980. pending_connection_t *pend;
  981. cached_resolve_t **resolve;
  982. HT_FOREACH(resolve, cache_map, &cache_root) {
  983. for (pend = (*resolve)->pending_connections;
  984. pend;
  985. pend = pend->next) {
  986. assert_connection_ok(TO_CONN(pend->conn), 0);
  987. tor_assert(!SOCKET_OK(pend->conn->base_.s));
  988. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  989. }
  990. }
  991. }
  992. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  993. */
  994. void
  995. connection_dns_remove(edge_connection_t *conn)
  996. {
  997. pending_connection_t *pend, *victim;
  998. cached_resolve_t search;
  999. cached_resolve_t *resolve;
  1000. tor_assert(conn->base_.type == CONN_TYPE_EXIT);
  1001. tor_assert(conn->base_.state == EXIT_CONN_STATE_RESOLVING);
  1002. strlcpy(search.address, conn->base_.address, sizeof(search.address));
  1003. resolve = HT_FIND(cache_map, &cache_root, &search);
  1004. if (!resolve) {
  1005. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  1006. escaped_safe_str(conn->base_.address));
  1007. return;
  1008. }
  1009. tor_assert(resolve->pending_connections);
  1010. assert_connection_ok(TO_CONN(conn),0);
  1011. pend = resolve->pending_connections;
  1012. if (pend->conn == conn) {
  1013. resolve->pending_connections = pend->next;
  1014. tor_free(pend);
  1015. log_debug(LD_EXIT, "First connection (fd "TOR_SOCKET_T_FORMAT") no "
  1016. "longer waiting for resolve of %s",
  1017. conn->base_.s,
  1018. escaped_safe_str(conn->base_.address));
  1019. return;
  1020. } else {
  1021. for ( ; pend->next; pend = pend->next) {
  1022. if (pend->next->conn == conn) {
  1023. victim = pend->next;
  1024. pend->next = victim->next;
  1025. tor_free(victim);
  1026. log_debug(LD_EXIT,
  1027. "Connection (fd "TOR_SOCKET_T_FORMAT") no longer waiting "
  1028. "for resolve of %s",
  1029. conn->base_.s, escaped_safe_str(conn->base_.address));
  1030. return; /* more are pending */
  1031. }
  1032. }
  1033. log_warn(LD_BUG, "Connection (fd "TOR_SOCKET_T_FORMAT") was not waiting "
  1034. "for a resolve of %s, but we tried to remove it.",
  1035. conn->base_.s, escaped_safe_str(conn->base_.address));
  1036. }
  1037. }
  1038. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  1039. * the resolve for <b>address</b> itself, and remove any cached results for
  1040. * <b>address</b> from the cache.
  1041. */
  1042. void
  1043. dns_cancel_pending_resolve(const char *address)
  1044. {
  1045. pending_connection_t *pend;
  1046. cached_resolve_t search;
  1047. cached_resolve_t *resolve, *tmp;
  1048. edge_connection_t *pendconn;
  1049. circuit_t *circ;
  1050. strlcpy(search.address, address, sizeof(search.address));
  1051. resolve = HT_FIND(cache_map, &cache_root, &search);
  1052. if (!resolve)
  1053. return;
  1054. if (resolve->state != CACHE_STATE_PENDING) {
  1055. /* We can get into this state if we never actually created the pending
  1056. * resolve, due to finding an earlier cached error or something. Just
  1057. * ignore it. */
  1058. if (resolve->pending_connections) {
  1059. log_warn(LD_BUG,
  1060. "Address %s is not pending but has pending connections!",
  1061. escaped_safe_str(address));
  1062. tor_fragile_assert();
  1063. }
  1064. return;
  1065. }
  1066. if (!resolve->pending_connections) {
  1067. log_warn(LD_BUG,
  1068. "Address %s is pending but has no pending connections!",
  1069. escaped_safe_str(address));
  1070. tor_fragile_assert();
  1071. return;
  1072. }
  1073. tor_assert(resolve->pending_connections);
  1074. /* mark all pending connections to fail */
  1075. log_debug(LD_EXIT,
  1076. "Failing all connections waiting on DNS resolve of %s",
  1077. escaped_safe_str(address));
  1078. while (resolve->pending_connections) {
  1079. pend = resolve->pending_connections;
  1080. pend->conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1081. pendconn = pend->conn;
  1082. assert_connection_ok(TO_CONN(pendconn), 0);
  1083. tor_assert(!SOCKET_OK(pendconn->base_.s));
  1084. if (!pendconn->base_.marked_for_close) {
  1085. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1086. }
  1087. circ = circuit_get_by_edge_conn(pendconn);
  1088. if (circ)
  1089. circuit_detach_stream(circ, pendconn);
  1090. if (!pendconn->base_.marked_for_close)
  1091. connection_free(TO_CONN(pendconn));
  1092. resolve->pending_connections = pend->next;
  1093. tor_free(pend);
  1094. }
  1095. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  1096. if (tmp != resolve) {
  1097. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  1098. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1099. resolve->address, (void*)resolve,
  1100. tmp ? tmp->address : "NULL", (void*)tmp);
  1101. }
  1102. tor_assert(tmp == resolve);
  1103. resolve->state = CACHE_STATE_DONE;
  1104. }
  1105. /** Return true iff <b>address</b> is one of the addresses we use to verify
  1106. * that well-known sites aren't being hijacked by our DNS servers. */
  1107. static INLINE int
  1108. is_test_address(const char *address)
  1109. {
  1110. const or_options_t *options = get_options();
  1111. return options->ServerDNSTestAddresses &&
  1112. smartlist_contains_string_case(options->ServerDNSTestAddresses, address);
  1113. }
  1114. /** Called on the OR side when the eventdns library tells us the outcome of a
  1115. * single DNS resolve: remember the answer, and tell all pending connections
  1116. * about the result of the lookup if the lookup is now done. (<b>address</b>
  1117. * is a NUL-terminated string containing the address to look up;
  1118. * <b>query_type</b> is one of DNS_{IPv4_A,IPv6_AAAA,PTR}; <b>dns_answer</b>
  1119. * is DNS_OK or one of DNS_ERR_*, <b>addr</b> is an IPv4 or IPv6 address if we
  1120. * got one; <b>hostname</b> is a hostname fora PTR request if we got one, and
  1121. * <b>ttl</b> is the time-to-live of this answer, in seconds.)
  1122. */
  1123. static void
  1124. dns_found_answer(const char *address, uint8_t query_type,
  1125. int dns_answer,
  1126. const tor_addr_t *addr,
  1127. const char *hostname, uint32_t ttl)
  1128. {
  1129. cached_resolve_t search;
  1130. cached_resolve_t *resolve;
  1131. assert_cache_ok();
  1132. strlcpy(search.address, address, sizeof(search.address));
  1133. resolve = HT_FIND(cache_map, &cache_root, &search);
  1134. if (!resolve) {
  1135. int is_test_addr = is_test_address(address);
  1136. if (!is_test_addr)
  1137. log_info(LD_EXIT,"Resolved unasked address %s; ignoring.",
  1138. escaped_safe_str(address));
  1139. return;
  1140. }
  1141. assert_resolve_ok(resolve);
  1142. if (resolve->state != CACHE_STATE_PENDING) {
  1143. /* XXXX Maybe update addr? or check addr for consistency? Or let
  1144. * VALID replace FAILED? */
  1145. int is_test_addr = is_test_address(address);
  1146. if (!is_test_addr)
  1147. log_notice(LD_EXIT,
  1148. "Resolved %s which was already resolved; ignoring",
  1149. escaped_safe_str(address));
  1150. tor_assert(resolve->pending_connections == NULL);
  1151. return;
  1152. }
  1153. cached_resolve_add_answer(resolve, query_type, dns_answer,
  1154. addr, hostname, ttl);
  1155. if (cached_resolve_have_all_answers(resolve)) {
  1156. inform_pending_connections(resolve);
  1157. make_pending_resolve_cached(resolve);
  1158. }
  1159. }
  1160. /** Given a pending cached_resolve_t that we just finished resolving,
  1161. * inform every connection that was waiting for the outcome of that
  1162. * resolution. */
  1163. static void
  1164. inform_pending_connections(cached_resolve_t *resolve)
  1165. {
  1166. pending_connection_t *pend;
  1167. edge_connection_t *pendconn;
  1168. int r;
  1169. while (resolve->pending_connections) {
  1170. char *hostname = NULL;
  1171. pend = resolve->pending_connections;
  1172. pendconn = pend->conn; /* don't pass complex things to the
  1173. connection_mark_for_close macro */
  1174. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  1175. if (pendconn->base_.marked_for_close) {
  1176. /* prevent double-remove. */
  1177. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1178. resolve->pending_connections = pend->next;
  1179. tor_free(pend);
  1180. continue;
  1181. }
  1182. r = set_exitconn_info_from_resolve(pendconn,
  1183. resolve,
  1184. &hostname);
  1185. if (r < 0) {
  1186. /* prevent double-remove. */
  1187. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1188. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1189. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  1190. /* This detach must happen after we send the end cell. */
  1191. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1192. } else {
  1193. send_resolved_cell(pendconn, r == -1 ?
  1194. RESOLVED_TYPE_ERROR : RESOLVED_TYPE_ERROR_TRANSIENT,
  1195. NULL);
  1196. /* This detach must happen after we send the resolved cell. */
  1197. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  1198. }
  1199. connection_free(TO_CONN(pendconn));
  1200. } else {
  1201. circuit_t *circ;
  1202. if (pendconn->base_.purpose == EXIT_PURPOSE_CONNECT) {
  1203. /* prevent double-remove. */
  1204. pend->conn->base_.state = EXIT_CONN_STATE_CONNECTING;
  1205. circ = circuit_get_by_edge_conn(pend->conn);
  1206. tor_assert(circ);
  1207. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  1208. /* unlink pend->conn from resolving_streams, */
  1209. circuit_detach_stream(circ, pend->conn);
  1210. /* and link it to n_streams */
  1211. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  1212. pend->conn->on_circuit = circ;
  1213. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  1214. connection_exit_connect(pend->conn);
  1215. } else {
  1216. /* prevent double-remove. This isn't really an accurate state,
  1217. * but it does the right thing. */
  1218. pendconn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
  1219. if (pendconn->is_reverse_dns_lookup)
  1220. send_resolved_hostname_cell(pendconn, hostname);
  1221. else
  1222. send_resolved_cell(pendconn, RESOLVED_TYPE_AUTO, resolve);
  1223. circ = circuit_get_by_edge_conn(pendconn);
  1224. tor_assert(circ);
  1225. circuit_detach_stream(circ, pendconn);
  1226. connection_free(TO_CONN(pendconn));
  1227. }
  1228. }
  1229. resolve->pending_connections = pend->next;
  1230. tor_free(pend);
  1231. tor_free(hostname);
  1232. }
  1233. }
  1234. /** Remove a pending cached_resolve_t from the hashtable, and add a
  1235. * corresponding cached cached_resolve_t.
  1236. *
  1237. * This function is only necessary because of the perversity of our
  1238. * cache timeout code; see inline comment for ideas on eliminating it.
  1239. **/
  1240. static void
  1241. make_pending_resolve_cached(cached_resolve_t *resolve)
  1242. {
  1243. cached_resolve_t *removed;
  1244. resolve->state = CACHE_STATE_DONE;
  1245. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  1246. if (removed != resolve) {
  1247. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  1248. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  1249. resolve->address, (void*)resolve,
  1250. removed ? removed->address : "NULL", (void*)removed);
  1251. }
  1252. assert_resolve_ok(resolve);
  1253. assert_cache_ok();
  1254. /* The resolve will eventually just hit the time-out in the expiry queue and
  1255. * expire. See fd0bafb0dedc7e2 for a brief explanation of how this got that
  1256. * way. XXXXX we could do better!*/
  1257. {
  1258. cached_resolve_t *new_resolve = tor_memdup(resolve,
  1259. sizeof(cached_resolve_t));
  1260. uint32_t ttl = UINT32_MAX;
  1261. new_resolve->expire = 0; /* So that set_expiry won't croak. */
  1262. if (resolve->res_status_hostname == RES_STATUS_DONE_OK)
  1263. new_resolve->result_ptr.hostname =
  1264. tor_strdup(resolve->result_ptr.hostname);
  1265. new_resolve->state = CACHE_STATE_CACHED;
  1266. assert_resolve_ok(new_resolve);
  1267. HT_INSERT(cache_map, &cache_root, new_resolve);
  1268. if ((resolve->res_status_ipv4 == RES_STATUS_DONE_OK ||
  1269. resolve->res_status_ipv4 == RES_STATUS_DONE_ERR) &&
  1270. resolve->ttl_ipv4 < ttl)
  1271. ttl = resolve->ttl_ipv4;
  1272. if ((resolve->res_status_ipv6 == RES_STATUS_DONE_OK ||
  1273. resolve->res_status_ipv6 == RES_STATUS_DONE_ERR) &&
  1274. resolve->ttl_ipv6 < ttl)
  1275. ttl = resolve->ttl_ipv6;
  1276. if ((resolve->res_status_hostname == RES_STATUS_DONE_OK ||
  1277. resolve->res_status_hostname == RES_STATUS_DONE_ERR) &&
  1278. resolve->ttl_hostname < ttl)
  1279. ttl = resolve->ttl_hostname;
  1280. set_expiry(new_resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  1281. }
  1282. assert_cache_ok();
  1283. }
  1284. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1285. * a transient failure. */
  1286. static int
  1287. evdns_err_is_transient(int err)
  1288. {
  1289. switch (err)
  1290. {
  1291. case DNS_ERR_SERVERFAILED:
  1292. case DNS_ERR_TRUNCATED:
  1293. case DNS_ERR_TIMEOUT:
  1294. return 1;
  1295. default:
  1296. return 0;
  1297. }
  1298. }
  1299. /** Configure eventdns nameservers if force is true, or if the configuration
  1300. * has changed since the last time we called this function, or if we failed on
  1301. * our last attempt. On Unix, this reads from /etc/resolv.conf or
  1302. * options->ServerDNSResolvConfFile; on Windows, this reads from
  1303. * options->ServerDNSResolvConfFile or the registry. Return 0 on success or
  1304. * -1 on failure. */
  1305. static int
  1306. configure_nameservers(int force)
  1307. {
  1308. const or_options_t *options;
  1309. const char *conf_fname;
  1310. struct stat st;
  1311. int r, flags;
  1312. options = get_options();
  1313. conf_fname = options->ServerDNSResolvConfFile;
  1314. #ifndef _WIN32
  1315. if (!conf_fname)
  1316. conf_fname = "/etc/resolv.conf";
  1317. #endif
  1318. flags = DNS_OPTIONS_ALL;
  1319. if (!the_evdns_base) {
  1320. if (!(the_evdns_base = evdns_base_new(tor_libevent_get_base(), 0))) {
  1321. log_err(LD_BUG, "Couldn't create an evdns_base");
  1322. return -1;
  1323. }
  1324. }
  1325. #ifdef HAVE_EVDNS_SET_DEFAULT_OUTGOING_BIND_ADDRESS
  1326. if (! tor_addr_is_null(&options->OutboundBindAddressIPv4_)) {
  1327. int socklen;
  1328. struct sockaddr_storage ss;
  1329. socklen = tor_addr_to_sockaddr(&options->OutboundBindAddressIPv4_, 0,
  1330. (struct sockaddr *)&ss, sizeof(ss));
  1331. if (socklen <= 0) {
  1332. log_warn(LD_BUG, "Couldn't convert outbound bind address to sockaddr."
  1333. " Ignoring.");
  1334. } else {
  1335. evdns_base_set_default_outgoing_bind_address(the_evdns_base,
  1336. (struct sockaddr *)&ss,
  1337. socklen);
  1338. }
  1339. }
  1340. #endif
  1341. evdns_set_log_fn(evdns_log_cb);
  1342. if (conf_fname) {
  1343. log_debug(LD_FS, "stat()ing %s", conf_fname);
  1344. if (stat(sandbox_intern_string(conf_fname), &st)) {
  1345. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1346. conf_fname, strerror(errno));
  1347. goto err;
  1348. }
  1349. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1350. && st.st_mtime == resolv_conf_mtime) {
  1351. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1352. return 0;
  1353. }
  1354. if (nameservers_configured) {
  1355. evdns_base_search_clear(the_evdns_base);
  1356. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1357. }
  1358. #if defined(DNS_OPTION_HOSTSFILE) && defined(USE_LIBSECCOMP)
  1359. if (flags & DNS_OPTION_HOSTSFILE) {
  1360. flags ^= DNS_OPTION_HOSTSFILE;
  1361. log_debug(LD_FS, "Loading /etc/hosts");
  1362. evdns_base_load_hosts(the_evdns_base,
  1363. sandbox_intern_string("/etc/hosts"));
  1364. }
  1365. #endif
  1366. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1367. if ((r = evdns_base_resolv_conf_parse(the_evdns_base, flags,
  1368. sandbox_intern_string(conf_fname)))) {
  1369. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s' (%d)",
  1370. conf_fname, conf_fname, r);
  1371. goto err;
  1372. }
  1373. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1374. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1375. goto err;
  1376. }
  1377. tor_free(resolv_conf_fname);
  1378. resolv_conf_fname = tor_strdup(conf_fname);
  1379. resolv_conf_mtime = st.st_mtime;
  1380. if (nameservers_configured)
  1381. evdns_base_resume(the_evdns_base);
  1382. }
  1383. #ifdef _WIN32
  1384. else {
  1385. if (nameservers_configured) {
  1386. evdns_base_search_clear(the_evdns_base);
  1387. evdns_base_clear_nameservers_and_suspend(the_evdns_base);
  1388. }
  1389. if (evdns_base_config_windows_nameservers(the_evdns_base)) {
  1390. log_warn(LD_EXIT,"Could not config nameservers.");
  1391. goto err;
  1392. }
  1393. if (evdns_base_count_nameservers(the_evdns_base) == 0) {
  1394. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1395. "your Windows configuration.");
  1396. goto err;
  1397. }
  1398. if (nameservers_configured)
  1399. evdns_base_resume(the_evdns_base);
  1400. tor_free(resolv_conf_fname);
  1401. resolv_conf_mtime = 0;
  1402. }
  1403. #endif
  1404. #define SET(k,v) evdns_base_set_option_(the_evdns_base, (k), (v))
  1405. if (evdns_base_count_nameservers(the_evdns_base) == 1) {
  1406. SET("max-timeouts:", "16");
  1407. SET("timeout:", "10");
  1408. } else {
  1409. SET("max-timeouts:", "3");
  1410. SET("timeout:", "5");
  1411. }
  1412. if (options->ServerDNSRandomizeCase)
  1413. SET("randomize-case:", "1");
  1414. else
  1415. SET("randomize-case:", "0");
  1416. #undef SET
  1417. dns_servers_relaunch_checks();
  1418. nameservers_configured = 1;
  1419. if (nameserver_config_failed) {
  1420. nameserver_config_failed = 0;
  1421. /* XXX the three calls to republish the descriptor might be producing
  1422. * descriptors that are only cosmetically different, especially on
  1423. * non-exit relays! -RD */
  1424. mark_my_descriptor_dirty("dns resolvers back");
  1425. }
  1426. return 0;
  1427. err:
  1428. nameservers_configured = 0;
  1429. if (! nameserver_config_failed) {
  1430. nameserver_config_failed = 1;
  1431. mark_my_descriptor_dirty("dns resolvers failed");
  1432. }
  1433. return -1;
  1434. }
  1435. /** For eventdns: Called when we get an answer for a request we launched.
  1436. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1437. */
  1438. static void
  1439. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1440. void *arg)
  1441. {
  1442. char *arg_ = arg;
  1443. uint8_t orig_query_type = arg_[0];
  1444. char *string_address = arg_ + 1;
  1445. tor_addr_t addr;
  1446. const char *hostname = NULL;
  1447. int was_wildcarded = 0;
  1448. tor_addr_make_unspec(&addr);
  1449. /* Keep track of whether IPv6 is working */
  1450. if (type == DNS_IPv6_AAAA) {
  1451. if (result == DNS_ERR_TIMEOUT) {
  1452. ++n_ipv6_timeouts;
  1453. }
  1454. if (n_ipv6_timeouts > 10 &&
  1455. n_ipv6_timeouts > n_ipv6_requests_made / 2) {
  1456. if (! dns_is_broken_for_ipv6) {
  1457. log_notice(LD_EXIT, "More than half of our IPv6 requests seem to "
  1458. "have timed out. I'm going to assume I can't get AAAA "
  1459. "responses.");
  1460. dns_is_broken_for_ipv6 = 1;
  1461. }
  1462. }
  1463. }
  1464. if (result == DNS_ERR_NONE) {
  1465. if (type == DNS_IPv4_A && count) {
  1466. char answer_buf[INET_NTOA_BUF_LEN+1];
  1467. char *escaped_address;
  1468. uint32_t *addrs = addresses;
  1469. tor_addr_from_ipv4n(&addr, addrs[0]);
  1470. tor_addr_to_str(answer_buf, &addr, sizeof(answer_buf), 0);
  1471. escaped_address = esc_for_log(string_address);
  1472. if (answer_is_wildcarded(answer_buf)) {
  1473. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1474. "address %s; treating as a failure.",
  1475. safe_str(escaped_address),
  1476. escaped_safe_str(answer_buf));
  1477. was_wildcarded = 1;
  1478. tor_addr_make_unspec(&addr);
  1479. result = DNS_ERR_NOTEXIST;
  1480. } else {
  1481. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1482. safe_str(escaped_address),
  1483. escaped_safe_str(answer_buf));
  1484. }
  1485. tor_free(escaped_address);
  1486. } else if (type == DNS_IPv6_AAAA && count) {
  1487. char answer_buf[TOR_ADDR_BUF_LEN];
  1488. char *escaped_address;
  1489. struct in6_addr *addrs = addresses;
  1490. tor_addr_from_in6(&addr, &addrs[0]);
  1491. tor_inet_ntop(AF_INET6, &addrs[0], answer_buf, sizeof(answer_buf));
  1492. escaped_address = esc_for_log(string_address);
  1493. if (answer_is_wildcarded(answer_buf)) {
  1494. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1495. "address %s; treating as a failure.",
  1496. safe_str(escaped_address),
  1497. escaped_safe_str(answer_buf));
  1498. was_wildcarded = 1;
  1499. tor_addr_make_unspec(&addr);
  1500. result = DNS_ERR_NOTEXIST;
  1501. } else {
  1502. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1503. safe_str(escaped_address),
  1504. escaped_safe_str(answer_buf));
  1505. }
  1506. tor_free(escaped_address);
  1507. } else if (type == DNS_PTR && count) {
  1508. char *escaped_address;
  1509. hostname = ((char**)addresses)[0];
  1510. escaped_address = esc_for_log(string_address);
  1511. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1512. safe_str(escaped_address),
  1513. escaped_safe_str(hostname));
  1514. tor_free(escaped_address);
  1515. } else if (count) {
  1516. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1517. escaped_safe_str(string_address));
  1518. } else {
  1519. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1520. escaped_safe_str(string_address));
  1521. }
  1522. }
  1523. if (was_wildcarded) {
  1524. if (is_test_address(string_address)) {
  1525. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1526. * server must really hate us. */
  1527. add_wildcarded_test_address(string_address);
  1528. }
  1529. }
  1530. if (orig_query_type && type && orig_query_type != type) {
  1531. log_warn(LD_BUG, "Weird; orig_query_type == %d but type == %d",
  1532. (int)orig_query_type, (int)type);
  1533. }
  1534. if (result != DNS_ERR_SHUTDOWN)
  1535. dns_found_answer(string_address, orig_query_type,
  1536. result, &addr, hostname, ttl);
  1537. tor_free(arg_);
  1538. }
  1539. /** Start a single DNS resolve for <b>address</b> (if <b>query_type</b> is
  1540. * DNS_IPv4_A or DNS_IPv6_AAAA) <b>ptr_address</b> (if <b>query_type</b> is
  1541. * DNS_PTR). Return 0 if we launched the request, -1 otherwise. */
  1542. static int
  1543. launch_one_resolve(const char *address, uint8_t query_type,
  1544. const tor_addr_t *ptr_address)
  1545. {
  1546. const int options = get_options()->ServerDNSSearchDomains ? 0
  1547. : DNS_QUERY_NO_SEARCH;
  1548. const size_t addr_len = strlen(address);
  1549. struct evdns_request *req = 0;
  1550. char *addr = tor_malloc(addr_len + 2);
  1551. addr[0] = (char) query_type;
  1552. memcpy(addr+1, address, addr_len + 1);
  1553. switch (query_type) {
  1554. case DNS_IPv4_A:
  1555. req = evdns_base_resolve_ipv4(the_evdns_base,
  1556. address, options, evdns_callback, addr);
  1557. break;
  1558. case DNS_IPv6_AAAA:
  1559. req = evdns_base_resolve_ipv6(the_evdns_base,
  1560. address, options, evdns_callback, addr);
  1561. ++n_ipv6_requests_made;
  1562. break;
  1563. case DNS_PTR:
  1564. if (tor_addr_family(ptr_address) == AF_INET)
  1565. req = evdns_base_resolve_reverse(the_evdns_base,
  1566. tor_addr_to_in(ptr_address),
  1567. DNS_QUERY_NO_SEARCH,
  1568. evdns_callback, addr);
  1569. else if (tor_addr_family(ptr_address) == AF_INET6)
  1570. req = evdns_base_resolve_reverse_ipv6(the_evdns_base,
  1571. tor_addr_to_in6(ptr_address),
  1572. DNS_QUERY_NO_SEARCH,
  1573. evdns_callback, addr);
  1574. else
  1575. log_warn(LD_BUG, "Called with PTR query and unexpected address family");
  1576. break;
  1577. default:
  1578. log_warn(LD_BUG, "Called with unexpectd query type %d", (int)query_type);
  1579. break;
  1580. }
  1581. if (req) {
  1582. return 0;
  1583. } else {
  1584. tor_free(addr);
  1585. return -1;
  1586. }
  1587. }
  1588. /** For eventdns: start resolving as necessary to find the target for
  1589. * <b>exitconn</b>. Returns -1 on error, -2 on transient error,
  1590. * 0 on "resolve launched." */
  1591. static int
  1592. launch_resolve(cached_resolve_t *resolve)
  1593. {
  1594. tor_addr_t a;
  1595. int r;
  1596. if (get_options()->DisableNetwork)
  1597. return -1;
  1598. /* What? Nameservers not configured? Sounds like a bug. */
  1599. if (!nameservers_configured) {
  1600. log_warn(LD_EXIT, "(Harmless.) Nameservers not configured, but resolve "
  1601. "launched. Configuring.");
  1602. if (configure_nameservers(1) < 0) {
  1603. return -1;
  1604. }
  1605. }
  1606. r = tor_addr_parse_PTR_name(
  1607. &a, resolve->address, AF_UNSPEC, 0);
  1608. tor_assert(the_evdns_base);
  1609. if (r == 0) {
  1610. log_info(LD_EXIT, "Launching eventdns request for %s",
  1611. escaped_safe_str(resolve->address));
  1612. resolve->res_status_ipv4 = RES_STATUS_INFLIGHT;
  1613. if (get_options()->IPv6Exit)
  1614. resolve->res_status_ipv6 = RES_STATUS_INFLIGHT;
  1615. if (launch_one_resolve(resolve->address, DNS_IPv4_A, NULL) < 0) {
  1616. resolve->res_status_ipv4 = 0;
  1617. r = -1;
  1618. }
  1619. if (r==0 && get_options()->IPv6Exit) {
  1620. /* We ask for an IPv6 address for *everything*. */
  1621. if (launch_one_resolve(resolve->address, DNS_IPv6_AAAA, NULL) < 0) {
  1622. resolve->res_status_ipv6 = 0;
  1623. r = -1;
  1624. }
  1625. }
  1626. } else if (r == 1) {
  1627. r = 0;
  1628. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1629. escaped_safe_str(resolve->address));
  1630. resolve->res_status_hostname = RES_STATUS_INFLIGHT;
  1631. if (launch_one_resolve(resolve->address, DNS_PTR, &a) < 0) {
  1632. resolve->res_status_hostname = 0;
  1633. r = -1;
  1634. }
  1635. } else if (r == -1) {
  1636. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1637. }
  1638. if (r < 0) {
  1639. log_fn(LOG_PROTOCOL_WARN, LD_EXIT, "eventdns rejected address %s.",
  1640. escaped_safe_str(resolve->address));
  1641. }
  1642. return r;
  1643. }
  1644. /** How many requests for bogus addresses have we launched so far? */
  1645. static int n_wildcard_requests = 0;
  1646. /** Map from dotted-quad IP address in response to an int holding how many
  1647. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1648. * would be easier to use definitely-invalid addresses (as specified by
  1649. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1650. static strmap_t *dns_wildcard_response_count = NULL;
  1651. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1652. * nameserver wants to return in response to requests for nonexistent domains.
  1653. */
  1654. static smartlist_t *dns_wildcard_list = NULL;
  1655. /** True iff we've logged about a single address getting wildcarded.
  1656. * Subsequent warnings will be less severe. */
  1657. static int dns_wildcard_one_notice_given = 0;
  1658. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1659. */
  1660. static int dns_wildcard_notice_given = 0;
  1661. /** List of supposedly good addresses that are getting wildcarded to the
  1662. * same addresses as nonexistent addresses. */
  1663. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1664. /** True iff we've warned about a test address getting wildcarded */
  1665. static int dns_wildcarded_test_address_notice_given = 0;
  1666. /** True iff all addresses seem to be getting wildcarded. */
  1667. static int dns_is_completely_invalid = 0;
  1668. /** Called when we see <b>id</b> (a dotted quad or IPv6 address) in response
  1669. * to a request for a hopefully bogus address. */
  1670. static void
  1671. wildcard_increment_answer(const char *id)
  1672. {
  1673. int *ip;
  1674. if (!dns_wildcard_response_count)
  1675. dns_wildcard_response_count = strmap_new();
  1676. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1677. if (!ip) {
  1678. ip = tor_malloc_zero(sizeof(int));
  1679. strmap_set(dns_wildcard_response_count, id, ip);
  1680. }
  1681. ++*ip;
  1682. if (*ip > 5 && n_wildcard_requests > 10) {
  1683. if (!dns_wildcard_list) dns_wildcard_list = smartlist_new();
  1684. if (!smartlist_contains_string(dns_wildcard_list, id)) {
  1685. tor_log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1686. "Your DNS provider has given \"%s\" as an answer for %d different "
  1687. "invalid addresses. Apparently they are hijacking DNS failures. "
  1688. "I'll try to correct for this by treating future occurrences of "
  1689. "\"%s\" as 'not found'.", id, *ip, id);
  1690. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1691. }
  1692. if (!dns_wildcard_notice_given)
  1693. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1694. dns_wildcard_notice_given = 1;
  1695. }
  1696. }
  1697. /** Note that a single test address (one believed to be good) seems to be
  1698. * getting redirected to the same IP as failures are. */
  1699. static void
  1700. add_wildcarded_test_address(const char *address)
  1701. {
  1702. int n, n_test_addrs;
  1703. if (!dns_wildcarded_test_address_list)
  1704. dns_wildcarded_test_address_list = smartlist_new();
  1705. if (smartlist_contains_string_case(dns_wildcarded_test_address_list,
  1706. address))
  1707. return;
  1708. n_test_addrs = get_options()->ServerDNSTestAddresses ?
  1709. smartlist_len(get_options()->ServerDNSTestAddresses) : 0;
  1710. smartlist_add(dns_wildcarded_test_address_list, tor_strdup(address));
  1711. n = smartlist_len(dns_wildcarded_test_address_list);
  1712. if (n > n_test_addrs/2) {
  1713. tor_log(dns_wildcarded_test_address_notice_given ? LOG_INFO : LOG_NOTICE,
  1714. LD_EXIT, "Your DNS provider tried to redirect \"%s\" to a junk "
  1715. "address. It has done this with %d test addresses so far. I'm "
  1716. "going to stop being an exit node for now, since our DNS seems so "
  1717. "broken.", address, n);
  1718. if (!dns_is_completely_invalid) {
  1719. dns_is_completely_invalid = 1;
  1720. mark_my_descriptor_dirty("dns hijacking confirmed");
  1721. }
  1722. if (!dns_wildcarded_test_address_notice_given)
  1723. control_event_server_status(LOG_WARN, "DNS_USELESS");
  1724. dns_wildcarded_test_address_notice_given = 1;
  1725. }
  1726. }
  1727. /** Callback function when we get an answer (possibly failing) for a request
  1728. * for a (hopefully) nonexistent domain. */
  1729. static void
  1730. evdns_wildcard_check_callback(int result, char type, int count, int ttl,
  1731. void *addresses, void *arg)
  1732. {
  1733. (void)ttl;
  1734. ++n_wildcard_requests;
  1735. if (result == DNS_ERR_NONE && count) {
  1736. char *string_address = arg;
  1737. int i;
  1738. if (type == DNS_IPv4_A) {
  1739. const uint32_t *addrs = addresses;
  1740. for (i = 0; i < count; ++i) {
  1741. char answer_buf[INET_NTOA_BUF_LEN+1];
  1742. struct in_addr in;
  1743. in.s_addr = addrs[i];
  1744. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1745. wildcard_increment_answer(answer_buf);
  1746. }
  1747. } else if (type == DNS_IPv6_AAAA) {
  1748. const struct in6_addr *addrs = addresses;
  1749. for (i = 0; i < count; ++i) {
  1750. char answer_buf[TOR_ADDR_BUF_LEN+1];
  1751. tor_inet_ntop(AF_INET6, &addrs[i], answer_buf, sizeof(answer_buf));
  1752. wildcard_increment_answer(answer_buf);
  1753. }
  1754. }
  1755. tor_log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1756. "Your DNS provider gave an answer for \"%s\", which "
  1757. "is not supposed to exist. Apparently they are hijacking "
  1758. "DNS failures. Trying to correct for this. We've noticed %d "
  1759. "possibly bad address%s so far.",
  1760. string_address, strmap_size(dns_wildcard_response_count),
  1761. (strmap_size(dns_wildcard_response_count) == 1) ? "" : "es");
  1762. dns_wildcard_one_notice_given = 1;
  1763. }
  1764. tor_free(arg);
  1765. }
  1766. /** Launch a single request for a nonexistent hostname consisting of between
  1767. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1768. * <b>suffix</b> */
  1769. static void
  1770. launch_wildcard_check(int min_len, int max_len, int is_ipv6,
  1771. const char *suffix)
  1772. {
  1773. char *addr;
  1774. struct evdns_request *req;
  1775. addr = crypto_random_hostname(min_len, max_len, "", suffix);
  1776. log_info(LD_EXIT, "Testing whether our DNS server is hijacking nonexistent "
  1777. "domains with request for bogus hostname \"%s\"", addr);
  1778. tor_assert(the_evdns_base);
  1779. if (is_ipv6)
  1780. req = evdns_base_resolve_ipv6(
  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. else
  1787. req = evdns_base_resolve_ipv4(
  1788. the_evdns_base,
  1789. /* This "addr" tells us which address to resolve */
  1790. addr,
  1791. DNS_QUERY_NO_SEARCH, evdns_wildcard_check_callback,
  1792. /* This "addr" is an argument to the callback*/ addr);
  1793. if (!req) {
  1794. /* There is no evdns request in progress; stop addr from getting leaked */
  1795. tor_free(addr);
  1796. }
  1797. }
  1798. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1799. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1800. static void
  1801. launch_test_addresses(evutil_socket_t fd, short event, void *args)
  1802. {
  1803. const or_options_t *options = get_options();
  1804. (void)fd;
  1805. (void)event;
  1806. (void)args;
  1807. if (options->DisableNetwork)
  1808. return;
  1809. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1810. "hijack *everything*.");
  1811. /* This situation is worse than the failure-hijacking situation. When this
  1812. * happens, we're no good for DNS requests at all, and we shouldn't really
  1813. * be an exit server.*/
  1814. if (options->ServerDNSTestAddresses) {
  1815. tor_assert(the_evdns_base);
  1816. SMARTLIST_FOREACH_BEGIN(options->ServerDNSTestAddresses,
  1817. const char *, address) {
  1818. if (launch_one_resolve(address, DNS_IPv4_A, NULL) < 0) {
  1819. log_info(LD_EXIT, "eventdns rejected test address %s",
  1820. escaped_safe_str(address));
  1821. }
  1822. if (launch_one_resolve(address, DNS_IPv6_AAAA, NULL) < 0) {
  1823. log_info(LD_EXIT, "eventdns rejected test address %s",
  1824. escaped_safe_str(address));
  1825. }
  1826. } SMARTLIST_FOREACH_END(address);
  1827. }
  1828. }
  1829. #define N_WILDCARD_CHECKS 2
  1830. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1831. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1832. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1833. * buy these lovely encyclopedias" page. */
  1834. static void
  1835. dns_launch_wildcard_checks(void)
  1836. {
  1837. int i, ipv6;
  1838. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1839. "to hijack DNS failures.");
  1840. for (ipv6 = 0; ipv6 <= 1; ++ipv6) {
  1841. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1842. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly
  1843. * attempt to 'comply' with rfc2606, refrain from giving A records for
  1844. * these. This is the standards-compliance equivalent of making sure
  1845. * that your crackhouse's elevator inspection certificate is up to date.
  1846. */
  1847. launch_wildcard_check(2, 16, ipv6, ".invalid");
  1848. launch_wildcard_check(2, 16, ipv6, ".test");
  1849. /* These will break specs if there are ever any number of
  1850. * 8+-character top-level domains. */
  1851. launch_wildcard_check(8, 16, ipv6, "");
  1852. /* Try some random .com/org/net domains. This will work fine so long as
  1853. * not too many resolve to the same place. */
  1854. launch_wildcard_check(8, 16, ipv6, ".com");
  1855. launch_wildcard_check(8, 16, ipv6, ".org");
  1856. launch_wildcard_check(8, 16, ipv6, ".net");
  1857. }
  1858. }
  1859. }
  1860. /** If appropriate, start testing whether our DNS servers tend to lie to
  1861. * us. */
  1862. void
  1863. dns_launch_correctness_checks(void)
  1864. {
  1865. static struct event *launch_event = NULL;
  1866. struct timeval timeout;
  1867. if (!get_options()->ServerDNSDetectHijacking)
  1868. return;
  1869. dns_launch_wildcard_checks();
  1870. /* Wait a while before launching requests for test addresses, so we can
  1871. * get the results from checking for wildcarding. */
  1872. if (! launch_event)
  1873. launch_event = tor_evtimer_new(tor_libevent_get_base(),
  1874. launch_test_addresses, NULL);
  1875. timeout.tv_sec = 30;
  1876. timeout.tv_usec = 0;
  1877. if (evtimer_add(launch_event, &timeout)<0) {
  1878. log_warn(LD_BUG, "Couldn't add timer for checking for dns hijacking");
  1879. }
  1880. }
  1881. /** Return true iff our DNS servers lie to us too much to be trusted. */
  1882. int
  1883. dns_seems_to_be_broken(void)
  1884. {
  1885. return dns_is_completely_invalid;
  1886. }
  1887. /** Return true iff we think that IPv6 hostname lookup is broken */
  1888. int
  1889. dns_seems_to_be_broken_for_ipv6(void)
  1890. {
  1891. return dns_is_broken_for_ipv6;
  1892. }
  1893. /** Forget what we've previously learned about our DNS servers' correctness. */
  1894. void
  1895. dns_reset_correctness_checks(void)
  1896. {
  1897. strmap_free(dns_wildcard_response_count, tor_free_);
  1898. dns_wildcard_response_count = NULL;
  1899. n_wildcard_requests = 0;
  1900. n_ipv6_requests_made = n_ipv6_timeouts = 0;
  1901. if (dns_wildcard_list) {
  1902. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1903. smartlist_clear(dns_wildcard_list);
  1904. }
  1905. if (dns_wildcarded_test_address_list) {
  1906. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1907. tor_free(cp));
  1908. smartlist_clear(dns_wildcarded_test_address_list);
  1909. }
  1910. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1911. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid =
  1912. dns_is_broken_for_ipv6 = 0;
  1913. }
  1914. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1915. * returned in response to requests for nonexistent hostnames. */
  1916. static int
  1917. answer_is_wildcarded(const char *ip)
  1918. {
  1919. return dns_wildcard_list && smartlist_contains_string(dns_wildcard_list, ip);
  1920. }
  1921. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1922. static void
  1923. assert_resolve_ok(cached_resolve_t *resolve)
  1924. {
  1925. tor_assert(resolve);
  1926. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1927. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1928. tor_assert(tor_strisnonupper(resolve->address));
  1929. if (resolve->state != CACHE_STATE_PENDING) {
  1930. tor_assert(!resolve->pending_connections);
  1931. }
  1932. if (resolve->state == CACHE_STATE_PENDING ||
  1933. resolve->state == CACHE_STATE_DONE) {
  1934. #if 0
  1935. tor_assert(!resolve->ttl);
  1936. if (resolve->is_reverse)
  1937. tor_assert(!resolve->hostname);
  1938. else
  1939. tor_assert(!resolve->result_ipv4.addr_ipv4);
  1940. #endif
  1941. /*XXXXX ADD MORE */
  1942. }
  1943. }
  1944. /** Return the number of DNS cache entries as an int */
  1945. static int
  1946. dns_cache_entry_count(void)
  1947. {
  1948. return HT_SIZE(&cache_root);
  1949. }
  1950. /** Log memory information about our internal DNS cache at level 'severity'. */
  1951. void
  1952. dump_dns_mem_usage(int severity)
  1953. {
  1954. /* This should never be larger than INT_MAX. */
  1955. int hash_count = dns_cache_entry_count();
  1956. size_t hash_mem = sizeof(struct cached_resolve_t) * hash_count;
  1957. hash_mem += HT_MEM_USAGE(&cache_root);
  1958. /* Print out the count and estimated size of our &cache_root. It undercounts
  1959. hostnames in cached reverse resolves.
  1960. */
  1961. tor_log(severity, LD_MM, "Our DNS cache has %d entries.", hash_count);
  1962. tor_log(severity, LD_MM, "Our DNS cache size is approximately %u bytes.",
  1963. (unsigned)hash_mem);
  1964. }
  1965. #ifdef DEBUG_DNS_CACHE
  1966. /** Exit with an assertion if the DNS cache is corrupt. */
  1967. static void
  1968. assert_cache_ok_(void)
  1969. {
  1970. cached_resolve_t **resolve;
  1971. int bad_rep = HT_REP_IS_BAD_(cache_map, &cache_root);
  1972. if (bad_rep) {
  1973. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1974. tor_assert(!bad_rep);
  1975. }
  1976. HT_FOREACH(resolve, cache_map, &cache_root) {
  1977. assert_resolve_ok(*resolve);
  1978. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1979. }
  1980. if (!cached_resolve_pqueue)
  1981. return;
  1982. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1983. compare_cached_resolves_by_expiry_,
  1984. STRUCT_OFFSET(cached_resolve_t, minheap_idx));
  1985. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  1986. {
  1987. if (res->state == CACHE_STATE_DONE) {
  1988. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1989. tor_assert(!found || found != res);
  1990. } else {
  1991. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  1992. tor_assert(found);
  1993. }
  1994. });
  1995. }
  1996. #endif