dns.c 72 KB

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