dns.c 61 KB

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