dns.c 61 KB

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