dns.c 60 KB

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