dns.c 56 KB

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