dns.c 58 KB

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