dns.c 56 KB

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