dns.c 61 KB

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