dns.c 71 KB

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