dns.c 61 KB

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