dns.c 60 KB

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