dns.c 71 KB

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