dns.c 58 KB

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