dns.c 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  1. /* Copyright 2003-2004 Roger Dingledine.
  2. * Copyright 2004-2006 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dns_c_id[] =
  6. "$Id$";
  7. /**
  8. * \file dns.c
  9. * \brief Implements a local cache for DNS results for Tor servers.
  10. * We provide two asynchronous backend implementations:
  11. * 1) A farm of 'DNS worker' threads or processes to perform DNS lookups for
  12. * onion routers and cache the results.
  13. * 2) A wrapper around Adam Langley's eventdns.c code, to send requests
  14. * to the nameservers asynchronously.
  15. * (We can't just use gethostbyname() and friends because we really need to
  16. * be nonblocking.)
  17. **/
  18. #include "or.h"
  19. #include "../common/ht.h"
  20. #ifdef USE_EVENTDNS
  21. #include "eventdns.h"
  22. #endif
  23. /** Longest hostname we're willing to resolve. */
  24. #define MAX_ADDRESSLEN 256
  25. /** Maximum DNS processes to spawn. */
  26. #define MAX_DNSWORKERS 100
  27. /** Minimum DNS processes to spawn. */
  28. #define MIN_DNSWORKERS 3
  29. /** If more than this many processes are idle, shut down the extras. */
  30. #define MAX_IDLE_DNSWORKERS 10
  31. /** How long will we wait for an answer from the resolver before we decide
  32. * that the resolver is wedged? */
  33. #define RESOLVE_MAX_TIMEOUT 300
  34. /** Possible outcomes from hostname lookup: permanent failure,
  35. * transient (retryable) failure, and success. */
  36. #define DNS_RESOLVE_FAILED_TRANSIENT 1
  37. #define DNS_RESOLVE_FAILED_PERMANENT 2
  38. #define DNS_RESOLVE_SUCCEEDED 3
  39. #ifndef USE_EVENTDNS
  40. /** How many dnsworkers we have running right now. */
  41. static int num_dnsworkers=0;
  42. /** How many of the running dnsworkers have an assigned task right now. */
  43. static int num_dnsworkers_busy=0;
  44. /** When did we last rotate the dnsworkers? */
  45. static time_t last_rotation_time=0;
  46. #else
  47. /** Have we currently configured nameservers with eventdns? */
  48. static int nameservers_configured = 0;
  49. /** What was the resolv_conf fname we last used when configuring the
  50. * nameservers? Used to check whether we need to reconfigure. */
  51. static char *resolv_conf_fname = NULL;
  52. /** What was the mtime on the resolv.conf file we last used when configuring
  53. * the nameservers? Used to check whether we need to reconfigure. */
  54. static time_t resolv_conf_mtime = 0;
  55. #endif
  56. /** Linked list of connections waiting for a DNS answer. */
  57. typedef struct pending_connection_t {
  58. edge_connection_t *conn;
  59. struct pending_connection_t *next;
  60. } pending_connection_t;
  61. #define CACHED_RESOLVE_MAGIC 0x1234F00D
  62. /* Possible states for a cached resolve_t */
  63. /** We are waiting for the resolver system to tell us an answer here.
  64. * When we get one, or when we time out, the state of this cached_resolve_t
  65. * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
  66. * entry. This cached_resolve_t will be in the hash table so that we will
  67. * know not to launch more requests for this addr, but rather to add more
  68. * connections to the pending list for the addr. */
  69. #define CACHE_STATE_PENDING 0
  70. /** This used to be a pending cached_resolve_t, and we got an answer for it.
  71. * Now we're waiting for this cached_resolve_t to expire. This should
  72. * have no pending connections, and should not appear in the hash table. */
  73. #define CACHE_STATE_DONE 1
  74. /** We are caching an answer for this address. This should have no pending
  75. * connections, and should appear in the hash table. */
  76. #define CACHE_STATE_CACHED_VALID 2
  77. /** We are caching a failure for this address. This should have no pending
  78. * connections, and should appear in the hash table */
  79. #define CACHE_STATE_CACHED_FAILED 3
  80. /** A DNS request: possibly completed, possibly pending; cached_resolve
  81. * structs are stored at the OR side in a hash table, and as a linked
  82. * list from oldest to newest.
  83. */
  84. typedef struct cached_resolve_t {
  85. HT_ENTRY(cached_resolve_t) node;
  86. uint32_t magic;
  87. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  88. union {
  89. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  90. char *hostname; /**< Hostname for <b>address</b> (if a reverse lookup) */
  91. } result;
  92. uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
  93. uint8_t is_reverse; /**< Is this a reverse (addr-to-hostname) lookup? */
  94. time_t expire; /**< Remove items from cache after this time. */
  95. uint32_t ttl; /**< What TTL did the nameserver tell us? */
  96. /** Connections that want to know when we get an answer for this resolve. */
  97. pending_connection_t *pending_connections;
  98. } cached_resolve_t;
  99. static void purge_expired_resolves(time_t now);
  100. static void dns_found_answer(const char *address, int is_reverse,
  101. uint32_t addr, const char *hostname, char outcome,
  102. uint32_t ttl);
  103. static void send_resolved_cell(edge_connection_t *conn, or_circuit_t *circ,
  104. uint8_t answer_type);
  105. static int launch_resolve(edge_connection_t *exitconn, or_circuit_t *circ);
  106. #ifndef USE_EVENTDNS
  107. static void dnsworkers_rotate(void);
  108. static void dnsworker_main(void *data);
  109. static int spawn_dnsworker(void);
  110. static int spawn_enough_dnsworkers(void);
  111. #else
  112. static void add_wildcarded_test_address(const char *address);
  113. static int configure_nameservers(int force);
  114. static int answer_is_wildcarded(const char *ip);
  115. #endif
  116. #ifdef DEBUG_DNS_CACHE
  117. static void _assert_cache_ok(void);
  118. #define assert_cache_ok() _assert_cache_ok()
  119. #else
  120. #define assert_cache_ok() do {} while (0)
  121. #endif
  122. static void assert_resolve_ok(cached_resolve_t *resolve);
  123. /** Hash table of cached_resolve objects. */
  124. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  125. /** Function to compare hashed resolves on their addresses; used to
  126. * implement hash tables. */
  127. static INLINE int
  128. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  129. {
  130. /* make this smarter one day? */
  131. assert_resolve_ok(a); // Not b; b may be just a search.
  132. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  133. }
  134. /** Hash function for cached_resolve objects */
  135. static INLINE unsigned int
  136. cached_resolve_hash(cached_resolve_t *a)
  137. {
  138. return ht_string_hash(a->address);
  139. }
  140. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  141. cached_resolves_eq);
  142. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  143. cached_resolves_eq, 0.6, malloc, realloc, free);
  144. /** Initialize the DNS cache. */
  145. static void
  146. init_cache_map(void)
  147. {
  148. HT_INIT(cache_map, &cache_root);
  149. }
  150. #ifdef USE_EVENTDNS
  151. /** Helper: called by eventdns when eventdns wants to log something. */
  152. static void
  153. evdns_log_cb(int warn, const char *msg)
  154. {
  155. const char *cp;
  156. static int all_down = 0;
  157. int severity = warn ? LOG_WARN : LOG_INFO;
  158. if (!strcmpstart(msg, "Resolve requested for") &&
  159. get_options()->SafeLogging) {
  160. log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
  161. return;
  162. } else if (!strcmpstart(msg, "Search: ")) {
  163. return;
  164. }
  165. if (!strcmpstart(msg, "Nameserver ") && (cp=strstr(msg, " has failed: "))) {
  166. char *ns = tor_strndup(msg+11, cp-(msg+11));
  167. const char *err = strchr(cp, ':'+2);
  168. /* Don't warn about a single failed nameserver; we'll warn with 'all
  169. * nameservers have failed' if we're completely out of nameservers;
  170. * otherwise, the situation is tolerable. */
  171. severity = LOG_INFO;
  172. control_event_server_status(LOG_NOTICE,
  173. "NAMESERVER_STATUS NS=%s STATUS=DOWN ERR=%s",
  174. ns, escaped(err));
  175. tor_free(ns);
  176. } else if (!strcmpstart(msg, "Nameserver ") &&
  177. (cp=strstr(msg, " is back up"))) {
  178. char *ns = tor_strndup(msg+11, cp-(msg+11));
  179. severity = (all_down && warn) ? LOG_NOTICE : LOG_INFO;
  180. all_down = 0;
  181. control_event_server_status(LOG_NOTICE,
  182. "NAMESERVER_STATUS NS=%s STATUS=UP", ns);
  183. tor_free(ns);
  184. } else if (!strcmp(msg, "All nameservers have failed")) {
  185. control_event_server_status(LOG_WARN, "NAMESERVER_ALL_DOWN");
  186. all_down = 1;
  187. }
  188. log(severity, LD_EXIT, "eventdns: %s", msg);
  189. }
  190. #endif
  191. /** Initialize the DNS subsystem; called by the OR process. */
  192. int
  193. dns_init(void)
  194. {
  195. init_cache_map();
  196. #ifdef USE_EVENTDNS
  197. if (server_mode(get_options()))
  198. return configure_nameservers(1);
  199. #else
  200. dnsworkers_rotate();
  201. #endif
  202. return 0;
  203. }
  204. /** Called when DNS-related options change (or may have changed). Returns -1
  205. * on failure, 0 on success. */
  206. int
  207. dns_reset(void)
  208. {
  209. #ifdef USE_EVENTDNS
  210. or_options_t *options = get_options();
  211. if (! server_mode(options)) {
  212. evdns_clear_nameservers_and_suspend();
  213. evdns_search_clear();
  214. nameservers_configured = 0;
  215. tor_free(resolv_conf_fname);
  216. resolv_conf_mtime = 0;
  217. } else {
  218. if (configure_nameservers(0) < 0)
  219. return -1;
  220. }
  221. #else
  222. dnsworkers_rotate();
  223. #endif
  224. }
  225. /** Helper: Given a TTL from a DNS response, determine what TTL to give the
  226. * OP that asked us to resolve it. */
  227. uint32_t
  228. dns_clip_ttl(uint32_t ttl)
  229. {
  230. if (ttl < MIN_DNS_TTL)
  231. return MIN_DNS_TTL;
  232. else if (ttl > MAX_DNS_TTL)
  233. return MAX_DNS_TTL;
  234. else
  235. return ttl;
  236. }
  237. /** Helper: Given a TTL from a DNS response, determine how long to hold it in
  238. * our cache. */
  239. static uint32_t
  240. dns_get_expiry_ttl(uint32_t ttl)
  241. {
  242. if (ttl < MIN_DNS_TTL)
  243. return MIN_DNS_TTL;
  244. else if (ttl > MAX_DNS_ENTRY_AGE)
  245. return MAX_DNS_ENTRY_AGE;
  246. else
  247. return ttl;
  248. }
  249. /** Helper: free storage held by an entry in the DNS cache. */
  250. static void
  251. _free_cached_resolve(cached_resolve_t *r)
  252. {
  253. while (r->pending_connections) {
  254. pending_connection_t *victim = r->pending_connections;
  255. r->pending_connections = victim->next;
  256. tor_free(victim);
  257. }
  258. if (r->is_reverse)
  259. tor_free(r->result.hostname);
  260. r->magic = 0xFF00FF00;
  261. tor_free(r);
  262. }
  263. /** Compare two cached_resolve_t pointers by expiry time, and return
  264. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  265. * the priority queue implementation. */
  266. static int
  267. _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
  268. {
  269. const cached_resolve_t *a = _a, *b = _b;
  270. return a->expire - b->expire;
  271. }
  272. /** Priority queue of cached_resolve_t objects to let us know when they
  273. * will expire. */
  274. static smartlist_t *cached_resolve_pqueue = NULL;
  275. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  276. * priority queue */
  277. static void
  278. set_expiry(cached_resolve_t *resolve, time_t expires)
  279. {
  280. tor_assert(resolve && resolve->expire == 0);
  281. if (!cached_resolve_pqueue)
  282. cached_resolve_pqueue = smartlist_create();
  283. resolve->expire = expires;
  284. smartlist_pqueue_add(cached_resolve_pqueue,
  285. _compare_cached_resolves_by_expiry,
  286. resolve);
  287. }
  288. /** Free all storage held in the DNS cache and related structures. */
  289. void
  290. dns_free_all(void)
  291. {
  292. cached_resolve_t **ptr, **next, *item;
  293. if (cached_resolve_pqueue) {
  294. SMARTLIST_FOREACH(cached_resolve_pqueue, cached_resolve_t *, res,
  295. {
  296. /* XXXX012 The hash lookups here could be quite slow; remove them
  297. * once we're happy. (Leave them in for at least 0.1.2.7-alpha, so they
  298. * get some testing.) -NM */
  299. if (res->state == CACHE_STATE_DONE) {
  300. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  301. tor_assert(!found || found != res);
  302. _free_cached_resolve(res);
  303. } else {
  304. cached_resolve_t *found = HT_FIND(cache_map, &cache_root, res);
  305. tor_assert(found);
  306. }
  307. });
  308. }
  309. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  310. item = *ptr;
  311. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  312. _free_cached_resolve(item);
  313. }
  314. HT_CLEAR(cache_map, &cache_root);
  315. if (cached_resolve_pqueue)
  316. smartlist_free(cached_resolve_pqueue);
  317. cached_resolve_pqueue = NULL;
  318. #ifdef USE_EVENTDNS
  319. tor_free(resolv_conf_fname);
  320. #endif
  321. }
  322. /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
  323. * from the cache. */
  324. static void
  325. purge_expired_resolves(time_t now)
  326. {
  327. cached_resolve_t *resolve, *removed;
  328. pending_connection_t *pend;
  329. edge_connection_t *pendconn;
  330. assert_cache_ok();
  331. if (!cached_resolve_pqueue)
  332. return;
  333. while (smartlist_len(cached_resolve_pqueue)) {
  334. resolve = smartlist_get(cached_resolve_pqueue, 0);
  335. if (resolve->expire > now)
  336. break;
  337. smartlist_pqueue_pop(cached_resolve_pqueue,
  338. _compare_cached_resolves_by_expiry);
  339. if (resolve->state == CACHE_STATE_PENDING) {
  340. log_debug(LD_EXIT,
  341. "Expiring a dns resolve %s that's still pending. Forgot to "
  342. "cull it? DNS resolve didn't tell us about the timeout?",
  343. escaped_safe_str(resolve->address));
  344. } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
  345. resolve->state == CACHE_STATE_CACHED_FAILED) {
  346. log_debug(LD_EXIT,
  347. "Forgetting old cached resolve (address %s, expires %lu)",
  348. escaped_safe_str(resolve->address),
  349. (unsigned long)resolve->expire);
  350. tor_assert(!resolve->pending_connections);
  351. } else {
  352. tor_assert(resolve->state == CACHE_STATE_DONE);
  353. tor_assert(!resolve->pending_connections);
  354. }
  355. if (resolve->pending_connections) {
  356. log_debug(LD_EXIT,
  357. "Closing pending connections on timed-out DNS resolve!");
  358. tor_fragile_assert();
  359. while (resolve->pending_connections) {
  360. pend = resolve->pending_connections;
  361. resolve->pending_connections = pend->next;
  362. /* Connections should only be pending if they have no socket. */
  363. tor_assert(pend->conn->_base.s == -1);
  364. pendconn = pend->conn;
  365. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
  366. pendconn->cpath_layer);
  367. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  368. connection_free(TO_CONN(pendconn));
  369. tor_free(pend);
  370. }
  371. }
  372. if (resolve->state == CACHE_STATE_CACHED_VALID ||
  373. resolve->state == CACHE_STATE_CACHED_FAILED ||
  374. resolve->state == CACHE_STATE_PENDING) {
  375. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  376. if (removed != resolve) {
  377. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  378. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  379. resolve->address, (void*)resolve,
  380. removed ? removed->address : "NULL", (void*)remove);
  381. }
  382. tor_assert(removed == resolve);
  383. if (resolve->is_reverse)
  384. tor_free(resolve->result.hostname);
  385. resolve->magic = 0xF0BBF0BB;
  386. tor_free(resolve);
  387. } else {
  388. /* This should be in state DONE. Make sure it's not in the cache. */
  389. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  390. tor_assert(tmp != resolve);
  391. }
  392. }
  393. assert_cache_ok();
  394. }
  395. /** Send a response to the RESOLVE request of a connection.
  396. * <b>answer_type</b> must be one of
  397. * RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT).
  398. *
  399. * If <b>circ</b> is provided, and we have a cached answer, send the
  400. * answer back along circ; otherwise, send the answer back along
  401. * <b>conn</b>'s attached circuit.
  402. */
  403. static void
  404. send_resolved_cell(edge_connection_t *conn, or_circuit_t *circ,
  405. uint8_t answer_type)
  406. {
  407. char buf[RELAY_PAYLOAD_SIZE];
  408. size_t buflen;
  409. uint32_t ttl;
  410. buf[0] = answer_type;
  411. ttl = dns_clip_ttl(conn->address_ttl);
  412. switch (answer_type)
  413. {
  414. case RESOLVED_TYPE_IPV4:
  415. buf[1] = 4;
  416. set_uint32(buf+2, htonl(conn->_base.addr));
  417. set_uint32(buf+6, htonl(ttl));
  418. buflen = 10;
  419. break;
  420. case RESOLVED_TYPE_ERROR_TRANSIENT:
  421. case RESOLVED_TYPE_ERROR:
  422. {
  423. const char *errmsg = "Error resolving hostname";
  424. int msglen = strlen(errmsg);
  425. buf[1] = msglen;
  426. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  427. set_uint32(buf+2+msglen, htonl(ttl));
  428. buflen = 6+msglen;
  429. break;
  430. }
  431. default:
  432. tor_assert(0);
  433. return;
  434. }
  435. // log_notice(LD_EXIT, "Sending a regular RESOLVED reply: ");
  436. if (!circ) {
  437. circuit_t *tmp = circuit_get_by_edge_conn(conn);
  438. if (! CIRCUIT_IS_ORIGIN(tmp))
  439. circ = TO_OR_CIRCUIT(tmp);
  440. }
  441. connection_edge_send_command(conn, TO_CIRCUIT(circ),
  442. RELAY_COMMAND_RESOLVED, buf, buflen,
  443. conn->cpath_layer);
  444. }
  445. /** Send a response to the RESOLVE request of a connection for an in-addr.arpa
  446. * address on connection <b>conn</b> which yielded the result <b>hostname</b>.
  447. * The answer type will be RESOLVED_HOSTNAME.
  448. *
  449. * If <b>circ</b> is provided, and we have a cached answer, send the
  450. * answer back along circ; otherwise, send the answer back along
  451. * <b>conn</b>'s attached circuit.
  452. */
  453. static void
  454. send_resolved_hostname_cell(edge_connection_t *conn, or_circuit_t *circ,
  455. const char *hostname)
  456. {
  457. char buf[RELAY_PAYLOAD_SIZE];
  458. size_t buflen;
  459. uint32_t ttl;
  460. size_t namelen = strlen(hostname);
  461. tor_assert(hostname);
  462. tor_assert(namelen < 256);
  463. ttl = dns_clip_ttl(conn->address_ttl);
  464. buf[0] = RESOLVED_TYPE_HOSTNAME;
  465. buf[1] = (uint8_t)namelen;
  466. memcpy(buf+2, hostname, namelen);
  467. set_uint32(buf+2+namelen, htonl(ttl));
  468. buflen = 2+namelen+4;
  469. if (!circ) {
  470. circuit_t *tmp = circuit_get_by_edge_conn(conn);
  471. if (! CIRCUIT_IS_ORIGIN(tmp))
  472. circ = TO_OR_CIRCUIT(tmp);
  473. }
  474. // log_notice(LD_EXIT, "Sending a reply RESOLVED reply: %s", hostname);
  475. connection_edge_send_command(conn, TO_CIRCUIT(circ),
  476. RELAY_COMMAND_RESOLVED, buf, buflen,
  477. conn->cpath_layer);
  478. // log_notice(LD_EXIT, "Sent");
  479. }
  480. /** Given a lower-case <b>address</b>, check to see whether it's a
  481. * 1.2.3.4.in-addr.arpa address used for reverse lookups. If so,
  482. * parse it and place the address in <b>in</b> if present. Return 1 on success;
  483. * 0 if the address is not in in-addr.arpa format, and -1 if the address is
  484. * malformed. */
  485. static int
  486. parse_inaddr_arpa_address(const char *address, struct in_addr *in)
  487. {
  488. char buf[INET_NTOA_BUF_LEN];
  489. char *cp;
  490. size_t len;
  491. struct in_addr inaddr;
  492. cp = strstr(address, ".in-addr.arpa");
  493. if (!cp || *(cp+strlen(".in-addr.arpa")))
  494. return 0; /* not an .in-addr.arpa address */
  495. len = cp - address;
  496. if (len >= INET_NTOA_BUF_LEN)
  497. return -1; /* Too long. */
  498. memcpy(buf, address, len);
  499. buf[len] = '\0';
  500. if (tor_inet_aton(buf, &inaddr) == 0)
  501. return -1; /* malformed. */
  502. if (in) {
  503. uint32_t a;
  504. /* reverse the bytes */
  505. a = ( ((inaddr.s_addr & 0x000000fful) << 24)
  506. |((inaddr.s_addr & 0x0000ff00ul) << 8)
  507. |((inaddr.s_addr & 0x00ff0000ul) >> 8)
  508. |((inaddr.s_addr & 0xff000000ul) >> 24));
  509. inaddr.s_addr = a;
  510. memcpy(in, &inaddr, sizeof(inaddr));
  511. }
  512. return 1;
  513. }
  514. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  515. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  516. * If resolve failed, unlink exitconn if needed, free it, and return -1.
  517. *
  518. * If <b>oncirc</b> is provided, and this is a resolve request, we have
  519. * a cached answer, send the answer back along oncirc; otherwise, send
  520. * the answer back along <b>exitconn</b>'s attached circuit.
  521. *
  522. * Else, if seen before and pending, add conn to the pending list,
  523. * and return 0.
  524. *
  525. * Else, if not seen before, add conn to pending list, hand to
  526. * dns farm, and return 0.
  527. */
  528. int
  529. dns_resolve(edge_connection_t *exitconn, or_circuit_t *oncirc)
  530. {
  531. cached_resolve_t *resolve;
  532. cached_resolve_t search;
  533. pending_connection_t *pending_connection;
  534. circuit_t *circ;
  535. struct in_addr in;
  536. time_t now = time(NULL);
  537. int is_reverse = 0, is_resolve, r;
  538. assert_connection_ok(TO_CONN(exitconn), 0);
  539. tor_assert(exitconn->_base.s == -1);
  540. assert_cache_ok();
  541. is_resolve = exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE;
  542. /* first check if exitconn->_base.address is an IP. If so, we already
  543. * know the answer. */
  544. if (tor_inet_aton(exitconn->_base.address, &in) != 0) {
  545. exitconn->_base.addr = ntohl(in.s_addr);
  546. exitconn->address_ttl = DEFAULT_DNS_TTL;
  547. if (is_resolve)
  548. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_IPV4);
  549. return 1;
  550. }
  551. if (address_is_invalid_destination(exitconn->_base.address, 0)) {
  552. log(LOG_PROTOCOL_WARN, LD_EXIT,
  553. "Rejecting invalid destination address %s",
  554. escaped_safe_str(exitconn->_base.address));
  555. if (is_resolve)
  556. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_ERROR);
  557. /* XXXX012 send error in connect case? -NM */
  558. circ = circuit_get_by_edge_conn(exitconn);
  559. if (circ)
  560. circuit_detach_stream(circ, exitconn);
  561. if (!exitconn->_base.marked_for_close)
  562. connection_free(TO_CONN(exitconn));
  563. return -1;
  564. }
  565. /* then take this opportunity to see if there are any expired
  566. * resolves in the hash table. */
  567. purge_expired_resolves(now);
  568. /* lower-case exitconn->_base.address, so it's in canonical form */
  569. tor_strlower(exitconn->_base.address);
  570. /* Check whether this is a reverse lookup. If it's malformed, or it's a
  571. * .in-addr.arpa address but this isn't a resolve request, kill the
  572. * connection.
  573. */
  574. if ((r = parse_inaddr_arpa_address(exitconn->_base.address, NULL)) != 0) {
  575. if (r == 1)
  576. is_reverse = 1;
  577. #ifdef USE_EVENTDNS
  578. if (!is_reverse || !is_resolve) {
  579. if (!is_reverse)
  580. log_info(LD_EXIT, "Bad .in-addr.arpa address \"%s\"; sending error.",
  581. escaped_safe_str(exitconn->_base.address));
  582. else if (!is_resolve)
  583. log_info(LD_EXIT,
  584. "Attempt to connect to a .in-addr.arpa address \"%s\"; "
  585. "sending error.",
  586. escaped_safe_str(exitconn->_base.address));
  587. #else
  588. if (1) {
  589. log_info(LD_PROTOCOL, "Dnsworker code does not support in-addr.arpa "
  590. "domain, but received a request for \"%s\"; sending error.",
  591. escaped_safe_str(exitconn->_base.address));
  592. #endif
  593. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  594. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_ERROR);
  595. circ = circuit_get_by_edge_conn(exitconn);
  596. if (circ)
  597. circuit_detach_stream(circ, exitconn);
  598. if (!exitconn->_base.marked_for_close)
  599. connection_free(TO_CONN(exitconn));
  600. return -1;
  601. }
  602. //log_notice(LD_EXIT, "Looks like an address %s",
  603. //exitconn->_base.address);
  604. }
  605. /* now check the hash table to see if 'address' is already there. */
  606. strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
  607. resolve = HT_FIND(cache_map, &cache_root, &search);
  608. if (resolve && resolve->expire > now) { /* already there */
  609. switch (resolve->state) {
  610. case CACHE_STATE_PENDING:
  611. /* add us to the pending list */
  612. pending_connection = tor_malloc_zero(
  613. sizeof(pending_connection_t));
  614. pending_connection->conn = exitconn;
  615. pending_connection->next = resolve->pending_connections;
  616. resolve->pending_connections = pending_connection;
  617. log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  618. "resolve of %s", exitconn->_base.s,
  619. escaped_safe_str(exitconn->_base.address));
  620. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  621. return 0;
  622. case CACHE_STATE_CACHED_VALID:
  623. log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
  624. exitconn->_base.s,
  625. escaped_safe_str(resolve->address));
  626. exitconn->address_ttl = resolve->ttl;
  627. if (resolve->is_reverse) {
  628. tor_assert(is_resolve);
  629. send_resolved_hostname_cell(exitconn, oncirc,
  630. resolve->result.hostname);
  631. } else {
  632. exitconn->_base.addr = resolve->result.addr;
  633. if (is_resolve)
  634. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_IPV4);
  635. }
  636. return 1;
  637. case CACHE_STATE_CACHED_FAILED:
  638. log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
  639. exitconn->_base.s,
  640. escaped_safe_str(exitconn->_base.address));
  641. /* XXXX012 send back indication of failure for connect case? -NM*/
  642. if (is_resolve)
  643. send_resolved_cell(exitconn, oncirc, RESOLVED_TYPE_ERROR);
  644. circ = circuit_get_by_edge_conn(exitconn);
  645. if (circ)
  646. circuit_detach_stream(circ, exitconn);
  647. if (!exitconn->_base.marked_for_close)
  648. connection_free(TO_CONN(exitconn));
  649. return -1;
  650. case CACHE_STATE_DONE:
  651. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  652. tor_fragile_assert();
  653. }
  654. tor_assert(0);
  655. }
  656. /* not there, need to add it */
  657. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  658. resolve->magic = CACHED_RESOLVE_MAGIC;
  659. resolve->state = CACHE_STATE_PENDING;
  660. resolve->is_reverse = is_reverse;
  661. strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
  662. /* add this connection to the pending list */
  663. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  664. pending_connection->conn = exitconn;
  665. resolve->pending_connections = pending_connection;
  666. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  667. /* Add this resolve to the cache and priority queue. */
  668. HT_INSERT(cache_map, &cache_root, resolve);
  669. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  670. log_debug(LD_EXIT,"Launching %s.",
  671. escaped_safe_str(exitconn->_base.address));
  672. assert_cache_ok();
  673. return launch_resolve(exitconn, oncirc);
  674. }
  675. /** Log an error and abort if conn is waiting for a DNS resolve.
  676. */
  677. void
  678. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  679. {
  680. pending_connection_t *pend;
  681. cached_resolve_t **resolve;
  682. HT_FOREACH(resolve, cache_map, &cache_root) {
  683. for (pend = (*resolve)->pending_connections;
  684. pend;
  685. pend = pend->next) {
  686. tor_assert(pend->conn != conn);
  687. }
  688. }
  689. }
  690. /** Log an error and abort if any connection waiting for a DNS resolve is
  691. * corrupted. */
  692. void
  693. assert_all_pending_dns_resolves_ok(void)
  694. {
  695. pending_connection_t *pend;
  696. cached_resolve_t **resolve;
  697. HT_FOREACH(resolve, cache_map, &cache_root) {
  698. for (pend = (*resolve)->pending_connections;
  699. pend;
  700. pend = pend->next) {
  701. assert_connection_ok(TO_CONN(pend->conn), 0);
  702. tor_assert(pend->conn->_base.s == -1);
  703. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  704. }
  705. }
  706. }
  707. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  708. */
  709. void
  710. connection_dns_remove(edge_connection_t *conn)
  711. {
  712. pending_connection_t *pend, *victim;
  713. cached_resolve_t search;
  714. cached_resolve_t *resolve;
  715. tor_assert(conn->_base.type == CONN_TYPE_EXIT);
  716. tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
  717. strlcpy(search.address, conn->_base.address, sizeof(search.address));
  718. resolve = HT_FIND(cache_map, &cache_root, &search);
  719. if (!resolve) {
  720. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  721. escaped_safe_str(conn->_base.address));
  722. return;
  723. }
  724. tor_assert(resolve->pending_connections);
  725. assert_connection_ok(TO_CONN(conn),0);
  726. pend = resolve->pending_connections;
  727. if (pend->conn == conn) {
  728. resolve->pending_connections = pend->next;
  729. tor_free(pend);
  730. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  731. "for resolve of %s",
  732. conn->_base.s, escaped_safe_str(conn->_base.address));
  733. return;
  734. } else {
  735. for ( ; pend->next; pend = pend->next) {
  736. if (pend->next->conn == conn) {
  737. victim = pend->next;
  738. pend->next = victim->next;
  739. tor_free(victim);
  740. log_debug(LD_EXIT,
  741. "Connection (fd %d) no longer waiting for resolve of %s",
  742. conn->_base.s, escaped_safe_str(conn->_base.address));
  743. return; /* more are pending */
  744. }
  745. }
  746. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  747. }
  748. }
  749. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  750. * the resolve for <b>address</b> itself, and remove any cached results for
  751. * <b>address</b> from the cache.
  752. */
  753. void
  754. dns_cancel_pending_resolve(const char *address)
  755. {
  756. pending_connection_t *pend;
  757. cached_resolve_t search;
  758. cached_resolve_t *resolve, *tmp;
  759. edge_connection_t *pendconn;
  760. circuit_t *circ;
  761. strlcpy(search.address, address, sizeof(search.address));
  762. resolve = HT_FIND(cache_map, &cache_root, &search);
  763. if (!resolve || resolve->state != CACHE_STATE_PENDING) {
  764. log_notice(LD_BUG,"Address %s is not pending. Dropping.",
  765. escaped_safe_str(address));
  766. return;
  767. }
  768. if (!resolve->pending_connections) {
  769. /* XXX this should never trigger, but sometimes it does */
  770. log_warn(LD_BUG,
  771. "Bug: Address %s is pending but has no pending connections!",
  772. escaped_safe_str(address));
  773. tor_fragile_assert();
  774. return;
  775. }
  776. tor_assert(resolve->pending_connections);
  777. /* mark all pending connections to fail */
  778. log_debug(LD_EXIT,
  779. "Failing all connections waiting on DNS resolve of %s",
  780. escaped_safe_str(address));
  781. while (resolve->pending_connections) {
  782. pend = resolve->pending_connections;
  783. pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  784. pendconn = pend->conn;
  785. assert_connection_ok(TO_CONN(pendconn), 0);
  786. tor_assert(pendconn->_base.s == -1);
  787. if (!pendconn->_base.marked_for_close) {
  788. connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
  789. pendconn->cpath_layer);
  790. }
  791. circ = circuit_get_by_edge_conn(pendconn);
  792. if (circ)
  793. circuit_detach_stream(circ, pendconn);
  794. connection_free(TO_CONN(pendconn));
  795. resolve->pending_connections = pend->next;
  796. tor_free(pend);
  797. }
  798. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  799. if (tmp != resolve) {
  800. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  801. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  802. resolve->address, (void*)resolve,
  803. tmp ? tmp->address : "NULL", (void*)tmp);
  804. }
  805. tor_assert(tmp == resolve);
  806. resolve->state = CACHE_STATE_DONE;
  807. }
  808. /** Helper: adds an entry to the DNS cache mapping <b>address</b> to the ipv4
  809. * address <b>addr</b> (if is_reverse is 0) or the hostname <b>hostname</b> (if
  810. * is_reverse is 1). <b>ttl</b> is a cache ttl; <b>outcome</b> is one of
  811. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  812. **/
  813. static void
  814. add_answer_to_cache(const char *address, int is_reverse, uint32_t addr,
  815. const char *hostname, char outcome, uint32_t ttl)
  816. {
  817. cached_resolve_t *resolve;
  818. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
  819. return;
  820. //log_notice(LD_EXIT, "Adding to cache: %s -> %s (%lx, %s), %d",
  821. // address, is_reverse?"(reverse)":"", (unsigned long)addr,
  822. // hostname?hostname:"NULL",(int)outcome);
  823. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  824. resolve->magic = CACHED_RESOLVE_MAGIC;
  825. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  826. CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
  827. strlcpy(resolve->address, address, sizeof(resolve->address));
  828. resolve->is_reverse = is_reverse;
  829. if (is_reverse) {
  830. if (outcome == DNS_RESOLVE_SUCCEEDED) {
  831. tor_assert(hostname);
  832. resolve->result.hostname = tor_strdup(hostname);
  833. } else {
  834. tor_assert(! hostname);
  835. resolve->result.hostname = NULL;
  836. }
  837. } else {
  838. tor_assert(!hostname);
  839. resolve->result.addr = addr;
  840. }
  841. resolve->ttl = ttl;
  842. assert_resolve_ok(resolve);
  843. HT_INSERT(cache_map, &cache_root, resolve);
  844. set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  845. }
  846. /** Return true iff <b>address</b> is one of the addresses we use to verify
  847. * that well-known sites aren't being hijacked by our DNS servers. */
  848. static INLINE int
  849. is_test_address(const char *address)
  850. {
  851. or_options_t *options = get_options();
  852. return options->ServerDNSTestAddresses &&
  853. smartlist_string_isin_case(options->ServerDNSTestAddresses, address);
  854. }
  855. /** Called on the OR side when a DNS worker or the eventdns library tells us
  856. * the outcome of a DNS resolve: tell all pending connections about the result
  857. * of the lookup, and cache the value. (<b>address</b> is a NUL-terminated
  858. * string containing the address to look up; <b>addr</b> is an IPv4 address in
  859. * host order; <b>outcome</b> is one of
  860. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  861. */
  862. static void
  863. dns_found_answer(const char *address, int is_reverse, uint32_t addr,
  864. const char *hostname, char outcome, uint32_t ttl)
  865. {
  866. pending_connection_t *pend;
  867. cached_resolve_t search;
  868. cached_resolve_t *resolve, *removed;
  869. edge_connection_t *pendconn;
  870. circuit_t *circ;
  871. assert_cache_ok();
  872. strlcpy(search.address, address, sizeof(search.address));
  873. resolve = HT_FIND(cache_map, &cache_root, &search);
  874. if (!resolve) {
  875. int is_test_addr = is_test_address(address);
  876. if (!is_test_addr)
  877. log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
  878. escaped_safe_str(address));
  879. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  880. return;
  881. }
  882. assert_resolve_ok(resolve);
  883. if (resolve->state != CACHE_STATE_PENDING) {
  884. /* XXXX Maybe update addr? or check addr for consistency? Or let
  885. * VALID replace FAILED? */
  886. int is_test_addr = is_test_address(address);
  887. if (!is_test_addr)
  888. log_notice(LD_EXIT,
  889. "Resolved %s which was already resolved; ignoring",
  890. escaped_safe_str(address));
  891. tor_assert(resolve->pending_connections == NULL);
  892. return;
  893. }
  894. /* Removed this assertion: in fact, we'll sometimes get a double answer
  895. * to the same question. This can happen when we ask one worker to resolve
  896. * X.Y.Z., then we cancel the request, and then we ask another worker to
  897. * resolve X.Y.Z. */
  898. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  899. while (resolve->pending_connections) {
  900. pend = resolve->pending_connections;
  901. pendconn = pend->conn; /* don't pass complex things to the
  902. connection_mark_for_close macro */
  903. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  904. pendconn->_base.addr = addr;
  905. pendconn->address_ttl = ttl;
  906. if (outcome != DNS_RESOLVE_SUCCEEDED) {
  907. /* prevent double-remove. */
  908. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  909. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  910. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED,
  911. pendconn->cpath_layer);
  912. /* This detach must happen after we send the end cell. */
  913. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  914. } else {
  915. send_resolved_cell(pendconn, NULL, RESOLVED_TYPE_ERROR);
  916. /* This detach must happen after we send the resolved cell. */
  917. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  918. }
  919. connection_free(TO_CONN(pendconn));
  920. } else {
  921. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  922. tor_assert(!is_reverse);
  923. /* prevent double-remove. */
  924. pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
  925. circ = circuit_get_by_edge_conn(pend->conn);
  926. tor_assert(circ);
  927. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  928. /* unlink pend->conn from resolving_streams, */
  929. circuit_detach_stream(circ, pend->conn);
  930. /* and link it to n_streams */
  931. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  932. pend->conn->on_circuit = circ;
  933. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  934. connection_exit_connect(pend->conn);
  935. } else {
  936. /* prevent double-remove. This isn't really an accurate state,
  937. * but it does the right thing. */
  938. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  939. if (is_reverse)
  940. send_resolved_hostname_cell(pendconn, NULL, hostname);
  941. else
  942. send_resolved_cell(pendconn, NULL, RESOLVED_TYPE_IPV4);
  943. circ = circuit_get_by_edge_conn(pendconn);
  944. tor_assert(circ);
  945. circuit_detach_stream(circ, pendconn);
  946. connection_free(TO_CONN(pendconn));
  947. }
  948. }
  949. resolve->pending_connections = pend->next;
  950. tor_free(pend);
  951. }
  952. resolve->state = CACHE_STATE_DONE;
  953. removed = HT_REMOVE(cache_map, &cache_root, &search);
  954. if (removed != resolve) {
  955. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  956. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  957. resolve->address, (void*)resolve,
  958. removed ? removed->address : "NULL", (void*)removed);
  959. }
  960. assert_resolve_ok(resolve);
  961. assert_cache_ok();
  962. add_answer_to_cache(address, is_reverse, addr, hostname, outcome, ttl);
  963. assert_cache_ok();
  964. }
  965. #ifndef USE_EVENTDNS
  966. /** Find or spawn a dns worker process to handle resolving
  967. * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
  968. */
  969. static int
  970. launch_resolve(edge_connection_t *exitconn, or_circuit_t *circ)
  971. {
  972. connection_t *dnsconn;
  973. unsigned char len;
  974. tor_assert(exitconn->_base.state == EXIT_CONN_STATE_RESOLVING);
  975. assert_connection_ok(TO_CONN(exitconn), 0);
  976. tor_assert(exitconn->_base.s == -1);
  977. /* respawn here, to be sure there are enough */
  978. if (spawn_enough_dnsworkers() < 0) {
  979. goto err;
  980. }
  981. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  982. DNSWORKER_STATE_IDLE);
  983. if (!dnsconn) {
  984. log_warn(LD_EXIT,"no idle dns workers. Failing.");
  985. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  986. send_resolved_cell(exitconn, circ, RESOLVED_TYPE_ERROR_TRANSIENT);
  987. goto err;
  988. }
  989. log_debug(LD_EXIT,
  990. "Connection (fd %d) needs to resolve %s; assigning "
  991. "to DNSWorker (fd %d)", exitconn->_base.s,
  992. escaped_safe_str(exitconn->_base.address), dnsconn->s);
  993. tor_free(dnsconn->address);
  994. dnsconn->address = tor_strdup(exitconn->_base.address);
  995. dnsconn->state = DNSWORKER_STATE_BUSY;
  996. /* touch the lastwritten timestamp, since that's how we check to
  997. * see how long it's been since we asked the question, and sometimes
  998. * we check before the first call to connection_handle_write(). */
  999. dnsconn->timestamp_lastwritten = time(NULL);
  1000. num_dnsworkers_busy++;
  1001. len = strlen(dnsconn->address);
  1002. connection_write_to_buf((char*)&len, 1, dnsconn);
  1003. connection_write_to_buf(dnsconn->address, len, dnsconn);
  1004. return 0;
  1005. err:
  1006. /* also sends end and frees */
  1007. dns_cancel_pending_resolve(exitconn->_base.address);
  1008. return -1;
  1009. }
  1010. /******************************************************************/
  1011. /*
  1012. * Connection between OR and dnsworker
  1013. */
  1014. /** Write handler: called when we've pushed a request to a dnsworker. */
  1015. int
  1016. connection_dns_finished_flushing(connection_t *conn)
  1017. {
  1018. tor_assert(conn);
  1019. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  1020. connection_stop_writing(conn);
  1021. return 0;
  1022. }
  1023. /** Called when a connection to a dnsworker hits an EOF; this only happens
  1024. * when a dnsworker dies unexpectedly. */
  1025. int
  1026. connection_dns_reached_eof(connection_t *conn)
  1027. {
  1028. log_warn(LD_EXIT,"Read eof. DNS worker died unexpectedly.");
  1029. if (conn->state == DNSWORKER_STATE_BUSY) {
  1030. /* don't cancel the resolve here -- it would be cancelled in
  1031. * connection_about_to_close_connection(), since conn is still
  1032. * in state BUSY
  1033. */
  1034. num_dnsworkers_busy--;
  1035. }
  1036. num_dnsworkers--;
  1037. connection_mark_for_close(conn);
  1038. return 0;
  1039. }
  1040. /** Read handler: called when we get data from a dnsworker. See
  1041. * if we have a complete answer. If so, call dns_found_answer on the
  1042. * result. If not, wait. Returns 0. */
  1043. int
  1044. connection_dns_process_inbuf(connection_t *conn)
  1045. {
  1046. char success;
  1047. uint32_t addr;
  1048. int ttl;
  1049. tor_assert(conn);
  1050. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  1051. if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
  1052. log_warn(LD_BUG,
  1053. "Bug: read data (%d bytes) from an idle dns worker (fd %d, "
  1054. "address %s). Please report.", (int)buf_datalen(conn->inbuf),
  1055. conn->s, escaped_safe_str(conn->address));
  1056. tor_fragile_assert();
  1057. /* Pull it off the buffer anyway, or it will just stay there.
  1058. * Keep pulling things off because sometimes we get several
  1059. * answers at once (!). */
  1060. while (buf_datalen(conn->inbuf)) {
  1061. connection_fetch_from_buf(&success,1,conn);
  1062. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  1063. log_warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
  1064. success, addr);
  1065. }
  1066. return 0;
  1067. }
  1068. if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  1069. return 0; /* not yet */
  1070. tor_assert(conn->state == DNSWORKER_STATE_BUSY);
  1071. tor_assert(buf_datalen(conn->inbuf) == 5);
  1072. connection_fetch_from_buf(&success,1,conn);
  1073. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  1074. log_debug(LD_EXIT, "DNSWorker (fd %d) returned answer for %s",
  1075. conn->s, escaped_safe_str(conn->address));
  1076. tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  1077. tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
  1078. ttl = (success == DNS_RESOLVE_FAILED_TRANSIENT) ? 0 : MAX_DNS_ENTRY_AGE;
  1079. dns_found_answer(conn->address, 0, ntohl(addr), NULL, success, ttl);
  1080. tor_free(conn->address);
  1081. conn->address = tor_strdup("<idle>");
  1082. conn->state = DNSWORKER_STATE_IDLE;
  1083. num_dnsworkers_busy--;
  1084. if (conn->timestamp_created < last_rotation_time) {
  1085. connection_mark_for_close(conn);
  1086. num_dnsworkers--;
  1087. spawn_enough_dnsworkers();
  1088. }
  1089. return 0;
  1090. }
  1091. /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
  1092. * and re-opened once they're no longer busy.
  1093. **/
  1094. static void
  1095. dnsworkers_rotate(void)
  1096. {
  1097. connection_t *dnsconn;
  1098. while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  1099. DNSWORKER_STATE_IDLE))) {
  1100. connection_mark_for_close(dnsconn);
  1101. num_dnsworkers--;
  1102. }
  1103. last_rotation_time = time(NULL);
  1104. if (server_mode(get_options()))
  1105. spawn_enough_dnsworkers();
  1106. }
  1107. /** Implementation for DNS workers; this code runs in a separate
  1108. * execution context. It takes as its argument an fdarray as returned
  1109. * by socketpair(), and communicates via fdarray[1]. The protocol is
  1110. * as follows:
  1111. * - The OR says:
  1112. * - ADDRESSLEN [1 byte]
  1113. * - ADDRESS [ADDRESSLEN bytes]
  1114. * - The DNS worker does the lookup, and replies:
  1115. * - OUTCOME [1 byte]
  1116. * - IP [4 bytes]
  1117. *
  1118. * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  1119. * IP is in host order.
  1120. *
  1121. * The dnsworker runs indefinitely, until its connection is closed or an error
  1122. * occurs.
  1123. */
  1124. static void
  1125. dnsworker_main(void *data)
  1126. {
  1127. char address[MAX_ADDRESSLEN+1]; /* Plus a byte for a final '.' */
  1128. unsigned char address_len;
  1129. char *log_address;
  1130. char answer[5];
  1131. uint32_t ip;
  1132. int *fdarray = data;
  1133. int fd;
  1134. int result;
  1135. int search = get_options()->ServerDNSSearchDomains;
  1136. /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray,
  1137. * fdarray[0],fdarray[1]); */
  1138. fd = fdarray[1]; /* this side is ours */
  1139. #ifndef TOR_IS_MULTITHREADED
  1140. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  1141. * parent uses */
  1142. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  1143. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  1144. #endif
  1145. tor_free(data);
  1146. for (;;) {
  1147. int r;
  1148. if ((r = recv(fd, &address_len, 1, 0)) != 1) {
  1149. if (r == 0) {
  1150. log_info(LD_EXIT,"DNS worker exiting because Tor process closed "
  1151. "connection (either pruned idle dnsworker or died).");
  1152. } else {
  1153. log_info(LD_EXIT,"DNS worker exiting because of error on connection "
  1154. "to Tor process.");
  1155. log_info(LD_EXIT,"(Error on %d was %s)", fd,
  1156. tor_socket_strerror(tor_socket_errno(fd)));
  1157. }
  1158. tor_close_socket(fd);
  1159. crypto_thread_cleanup();
  1160. spawn_exit();
  1161. }
  1162. if (address_len && read_all(fd, address, address_len, 1) != address_len) {
  1163. log_err(LD_BUG,"read hostname failed. Child exiting.");
  1164. tor_close_socket(fd);
  1165. crypto_thread_cleanup();
  1166. spawn_exit();
  1167. }
  1168. /* Add a period to prevent local domain search, and NUL-terminate. */
  1169. if (address[address_len-1] != '.' && !search) {
  1170. address[address_len] = '.';
  1171. address[address_len+1] = '\0';
  1172. } else {
  1173. address[address_len] = '\0';
  1174. }
  1175. log_address = esc_for_log(safe_str(address));
  1176. result = tor_lookup_hostname(address, &ip);
  1177. /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
  1178. if (!ip)
  1179. result = -1;
  1180. switch (result) {
  1181. case 1:
  1182. /* XXX result can never be 1, because we set it to -1 above on error */
  1183. log_info(LD_NET,"Could not resolve dest addr %s (transient)",
  1184. log_address);
  1185. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  1186. break;
  1187. case -1:
  1188. log_info(LD_NET,"Could not resolve dest addr %s (permanent)",
  1189. log_address);
  1190. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  1191. break;
  1192. case 0:
  1193. log_info(LD_NET,"Resolved address %s", log_address);
  1194. answer[0] = DNS_RESOLVE_SUCCEEDED;
  1195. break;
  1196. }
  1197. tor_free(log_address);
  1198. set_uint32(answer+1, ip);
  1199. if (write_all(fd, answer, 5, 1) != 5) {
  1200. log_err(LD_NET,"writing answer failed. Child exiting.");
  1201. tor_close_socket(fd);
  1202. crypto_thread_cleanup();
  1203. spawn_exit();
  1204. }
  1205. }
  1206. }
  1207. /** Launch a new DNS worker; return 0 on success, -1 on failure.
  1208. */
  1209. static int
  1210. spawn_dnsworker(void)
  1211. {
  1212. int *fdarray;
  1213. int fd;
  1214. connection_t *conn;
  1215. int err;
  1216. fdarray = tor_malloc(sizeof(int)*2);
  1217. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  1218. log_warn(LD_NET, "Couldn't construct socketpair for dns worker: %s",
  1219. tor_socket_strerror(-err));
  1220. tor_free(fdarray);
  1221. return -1;
  1222. }
  1223. tor_assert(fdarray[0] >= 0);
  1224. tor_assert(fdarray[1] >= 0);
  1225. /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d",
  1226. (int)fdarray, fdarray[0],fdarray[1]); */
  1227. fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free
  1228. * fdarray */
  1229. spawn_func((void*) dnsworker_main, (void*)fdarray);
  1230. log_debug(LD_EXIT,"just spawned a dns worker.");
  1231. #ifndef TOR_IS_MULTITHREADED
  1232. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  1233. tor_free(fdarray);
  1234. #endif
  1235. conn = connection_new(CONN_TYPE_DNSWORKER);
  1236. set_socket_nonblocking(fd);
  1237. /* set up conn so it's got all the data we need to remember */
  1238. conn->s = fd;
  1239. conn->address = tor_strdup("<unused>");
  1240. if (connection_add(conn) < 0) { /* no space, forget it */
  1241. log_warn(LD_NET,"connection_add for dnsworker failed. Giving up.");
  1242. connection_free(conn); /* this closes fd */
  1243. return -1;
  1244. }
  1245. conn->state = DNSWORKER_STATE_IDLE;
  1246. connection_start_reading(conn);
  1247. return 0; /* success */
  1248. }
  1249. /** If we have too many or too few DNS workers, spawn or kill some.
  1250. * Return 0 if we are happy, return -1 if we tried to spawn more but
  1251. * we couldn't.
  1252. */
  1253. static int
  1254. spawn_enough_dnsworkers(void)
  1255. {
  1256. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  1257. * but no less than min and no more than max */
  1258. connection_t *dnsconn;
  1259. /* XXX This may not be the best strategy. Maybe we should queue pending
  1260. * requests until the old ones finish or time out: otherwise, if the
  1261. * connection requests come fast enough, we never get any DNS done. -NM
  1262. *
  1263. * XXX But if we queue them, then the adversary can pile even more
  1264. * queries onto us, blocking legitimate requests for even longer. Maybe
  1265. * we should compromise and only kill if it's been at it for more than,
  1266. * e.g., 2 seconds. -RD
  1267. */
  1268. if (num_dnsworkers_busy == MAX_DNSWORKERS) {
  1269. /* We always want at least one worker idle.
  1270. * So find the oldest busy worker and kill it.
  1271. */
  1272. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  1273. DNSWORKER_STATE_BUSY);
  1274. tor_assert(dnsconn);
  1275. log_warn(LD_EXIT, "%d DNS workers are spawned; all are busy. Killing one.",
  1276. MAX_DNSWORKERS);
  1277. connection_mark_for_close(dnsconn);
  1278. num_dnsworkers_busy--;
  1279. num_dnsworkers--;
  1280. }
  1281. if (num_dnsworkers_busy >= MIN_DNSWORKERS)
  1282. num_dnsworkers_needed = num_dnsworkers_busy+1;
  1283. else
  1284. num_dnsworkers_needed = MIN_DNSWORKERS;
  1285. while (num_dnsworkers < num_dnsworkers_needed) {
  1286. if (spawn_dnsworker() < 0) {
  1287. log_warn(LD_EXIT,"DNS worker spawn failed. Will try again later.");
  1288. return -1;
  1289. }
  1290. num_dnsworkers++;
  1291. }
  1292. while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) {
  1293. /* too many idle? */
  1294. /* cull excess workers */
  1295. log_info(LD_EXIT,"%d of %d dnsworkers are idle. Killing one.",
  1296. num_dnsworkers-num_dnsworkers_busy, num_dnsworkers);
  1297. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  1298. DNSWORKER_STATE_IDLE);
  1299. tor_assert(dnsconn);
  1300. connection_mark_for_close(dnsconn);
  1301. num_dnsworkers--;
  1302. }
  1303. return 0;
  1304. }
  1305. void
  1306. dns_launch_correctness_checks(void)
  1307. {
  1308. }
  1309. int
  1310. dns_seems_to_be_broken(void)
  1311. {
  1312. return 0;
  1313. }
  1314. void
  1315. dns_reset_correctness_checks(void)
  1316. {
  1317. }
  1318. #else /* !USE_EVENTDNS */
  1319. /** Eventdns helper: return true iff the eventdns result <b>err</b> is
  1320. * a transient failure. */
  1321. static int
  1322. evdns_err_is_transient(int err)
  1323. {
  1324. switch (err)
  1325. {
  1326. case DNS_ERR_SERVERFAILED:
  1327. case DNS_ERR_TRUNCATED:
  1328. case DNS_ERR_TIMEOUT:
  1329. return 1;
  1330. default:
  1331. return 0;
  1332. }
  1333. }
  1334. /* Dummy function; never called with eventdns enabled. */
  1335. int
  1336. connection_dns_finished_flushing(connection_t *conn)
  1337. {
  1338. (void)conn;
  1339. tor_assert(0);
  1340. return 0;
  1341. }
  1342. /* Dummy function; never called with eventdns enabled. */
  1343. int
  1344. connection_dns_process_inbuf(connection_t *conn)
  1345. {
  1346. (void)conn;
  1347. tor_assert(0);
  1348. return 0;
  1349. }
  1350. /* Dummy function; never called with eventdns enabled. */
  1351. int
  1352. connection_dns_reached_eof(connection_t *conn)
  1353. {
  1354. (void)conn;
  1355. tor_assert(0);
  1356. return 0;
  1357. }
  1358. /** Configure eventdns nameservers if force is true, or if the configuration
  1359. * has changed since the last time we called this function. On Unix, this
  1360. * reads from options->ServerDNSResolvConfFile or /etc/resolv.conf; on
  1361. * Windows, this reads from options->ServerDNSResolvConfFile or the registry.
  1362. * Return 0 on success or -1 on failure. */
  1363. static int
  1364. configure_nameservers(int force)
  1365. {
  1366. or_options_t *options;
  1367. const char *conf_fname;
  1368. struct stat st;
  1369. options = get_options();
  1370. conf_fname = options->ServerDNSResolvConfFile;
  1371. #ifndef MS_WINDOWS
  1372. if (!conf_fname)
  1373. conf_fname = "/etc/resolv.conf";
  1374. #endif
  1375. evdns_set_log_fn(evdns_log_cb);
  1376. if (conf_fname) {
  1377. if (stat(conf_fname, &st)) {
  1378. log_warn(LD_EXIT, "Unable to stat resolver configuration in '%s': %s",
  1379. conf_fname, strerror(errno));
  1380. return -1;
  1381. }
  1382. if (!force && resolv_conf_fname && !strcmp(conf_fname,resolv_conf_fname)
  1383. && st.st_mtime == resolv_conf_mtime) {
  1384. log_info(LD_EXIT, "No change to '%s'", conf_fname);
  1385. return 0;
  1386. }
  1387. if (nameservers_configured) {
  1388. evdns_search_clear();
  1389. evdns_clear_nameservers_and_suspend();
  1390. }
  1391. log_info(LD_EXIT, "Parsing resolver configuration in '%s'", conf_fname);
  1392. if (evdns_resolv_conf_parse(DNS_OPTIONS_ALL, conf_fname)) {
  1393. log_warn(LD_EXIT, "Unable to parse '%s', or no nameservers in '%s'",
  1394. conf_fname, conf_fname);
  1395. return -1;
  1396. }
  1397. if (evdns_count_nameservers() == 0) {
  1398. log_warn(LD_EXIT, "Unable to find any nameservers in '%s'.", conf_fname);
  1399. return -1;
  1400. }
  1401. tor_free(resolv_conf_fname);
  1402. resolv_conf_fname = tor_strdup(conf_fname);
  1403. resolv_conf_mtime = st.st_mtime;
  1404. if (nameservers_configured)
  1405. evdns_resume();
  1406. }
  1407. #ifdef MS_WINDOWS
  1408. else {
  1409. if (nameservers_configured) {
  1410. evdns_search_clear();
  1411. evdns_clear_nameservers_and_suspend();
  1412. }
  1413. if (evdns_config_windows_nameservers()) {
  1414. log_warn(LD_EXIT,"Could not config nameservers.");
  1415. return -1;
  1416. }
  1417. if (evdns_count_nameservers() == 0) {
  1418. log_warn(LD_EXIT, "Unable to find any platform nameservers in "
  1419. "your Windows configuration. Perhaps you should list a "
  1420. "ServerDNSResolvConfFile file in your torrc?");
  1421. return -1;
  1422. }
  1423. if (nameservers_configured)
  1424. evdns_resume();
  1425. tor_free(resolv_conf_fname);
  1426. resolv_conf_mtime = 0;
  1427. }
  1428. #endif
  1429. if (evdns_count_nameservers() == 1) {
  1430. evdns_set_option("max-timeouts:", "16", DNS_OPTIONS_ALL);
  1431. evdns_set_option("timeout:", "10", DNS_OPTIONS_ALL);
  1432. } else {
  1433. evdns_set_option("max-timeouts:", "3", DNS_OPTIONS_ALL);
  1434. evdns_set_option("timeout:", "5", DNS_OPTIONS_ALL);
  1435. }
  1436. dns_servers_relaunch_checks();
  1437. nameservers_configured = 1;
  1438. return 0;
  1439. }
  1440. /** For eventdns: Called when we get an answer for a request we launched.
  1441. * See eventdns.h for arguments; 'arg' holds the address we tried to resolve.
  1442. */
  1443. static void
  1444. evdns_callback(int result, char type, int count, int ttl, void *addresses,
  1445. void *arg)
  1446. {
  1447. char *string_address = arg;
  1448. int is_reverse = 0;
  1449. int status = DNS_RESOLVE_FAILED_PERMANENT;
  1450. uint32_t addr = 0;
  1451. const char *hostname = NULL;
  1452. int was_wildcarded = 0;
  1453. if (result == DNS_ERR_NONE) {
  1454. if (type == DNS_IPv4_A && count) {
  1455. char answer_buf[INET_NTOA_BUF_LEN+1];
  1456. struct in_addr in;
  1457. char *escaped_address;
  1458. uint32_t *addrs = addresses;
  1459. in.s_addr = addrs[0];
  1460. addr = ntohl(addrs[0]);
  1461. status = DNS_RESOLVE_SUCCEEDED;
  1462. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1463. escaped_address = esc_for_log(string_address);
  1464. if (answer_is_wildcarded(answer_buf)) {
  1465. log_debug(LD_EXIT, "eventdns said that %s resolves to ISP-hijacked "
  1466. "address %s; treating as a failure.",
  1467. safe_str(escaped_address),
  1468. escaped_safe_str(answer_buf));
  1469. was_wildcarded = 1;
  1470. addr = 0;
  1471. status = DNS_RESOLVE_FAILED_PERMANENT;
  1472. } else {
  1473. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1474. safe_str(escaped_address),
  1475. escaped_safe_str(answer_buf));
  1476. }
  1477. tor_free(escaped_address);
  1478. } else if (type == DNS_PTR && count) {
  1479. char *escaped_address;
  1480. is_reverse = 1;
  1481. hostname = ((char**)addresses)[0];
  1482. status = DNS_RESOLVE_SUCCEEDED;
  1483. escaped_address = esc_for_log(string_address);
  1484. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1485. safe_str(escaped_address),
  1486. escaped_safe_str(hostname));
  1487. tor_free(escaped_address);
  1488. } else if (count) {
  1489. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1490. escaped_safe_str(string_address));
  1491. } else {
  1492. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1493. escaped_safe_str(string_address));
  1494. }
  1495. } else {
  1496. if (evdns_err_is_transient(result))
  1497. status = DNS_RESOLVE_FAILED_TRANSIENT;
  1498. }
  1499. if (was_wildcarded) {
  1500. if (is_test_address(string_address)) {
  1501. /* Ick. We're getting redirected on known-good addresses. Our DNS
  1502. * server must really hate us. */
  1503. add_wildcarded_test_address(string_address);
  1504. }
  1505. }
  1506. if (result != DNS_ERR_SHUTDOWN)
  1507. dns_found_answer(string_address, is_reverse, addr, hostname, status, ttl);
  1508. tor_free(string_address);
  1509. }
  1510. /** For eventdns: start resolving as necessary to find the target for
  1511. * <b>exitconn</b> */
  1512. static int
  1513. launch_resolve(edge_connection_t *exitconn, or_circuit_t *circ)
  1514. {
  1515. char *addr = tor_strdup(exitconn->_base.address);
  1516. struct in_addr in;
  1517. int r;
  1518. int options = get_options()->ServerDNSSearchDomains ? 0
  1519. : DNS_QUERY_NO_SEARCH;
  1520. /* What? Nameservers not configured? Sounds like a bug. */
  1521. if (!nameservers_configured) {
  1522. log_warn(LD_EXIT, "Harmless bug: nameservers not configured, but resolve "
  1523. "launched. Configuring.");
  1524. if (configure_nameservers(1) < 0)
  1525. return -1;
  1526. }
  1527. r = parse_inaddr_arpa_address(exitconn->_base.address, &in);
  1528. if (r == 0) {
  1529. log_info(LD_EXIT, "Launching eventdns request for %s",
  1530. escaped_safe_str(exitconn->_base.address));
  1531. r = evdns_resolve_ipv4(exitconn->_base.address, options,
  1532. evdns_callback, addr);
  1533. } else if (r == 1) {
  1534. log_info(LD_EXIT, "Launching eventdns reverse request for %s",
  1535. escaped_safe_str(exitconn->_base.address));
  1536. r = evdns_resolve_reverse(&in, DNS_QUERY_NO_SEARCH,
  1537. evdns_callback, addr);
  1538. } else if (r == -1) {
  1539. log_warn(LD_BUG, "Somehow a malformed in-addr.arpa address reached here.");
  1540. }
  1541. if (r) {
  1542. log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
  1543. escaped_safe_str(addr), r);
  1544. /* XXX012 the above warning triggers sometimes on my exit
  1545. * node, with "error 1". Is there anything the user can do to
  1546. * resolve this? -RD */
  1547. /* XXX012 Are you sure I didn't fix that in version r9336 with
  1548. * ServerDNSAllowNonRFC953Addreesses? If it's still not working,
  1549. * let me know which addresses are breaking. If it _is_ working,
  1550. * please remove these comments. :) -NM */
  1551. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE) {
  1552. if (evdns_err_is_transient(r))
  1553. send_resolved_cell(exitconn, circ, RESOLVED_TYPE_ERROR_TRANSIENT);
  1554. else {
  1555. exitconn->address_ttl = DEFAULT_DNS_TTL;
  1556. send_resolved_cell(exitconn, circ, RESOLVED_TYPE_ERROR);
  1557. }
  1558. }
  1559. dns_cancel_pending_resolve(addr); /* also sends end and frees */
  1560. tor_free(addr);
  1561. }
  1562. return r ? -1 : 0;
  1563. }
  1564. /** How many requests for bogus addresses have we launched so far? */
  1565. static int n_wildcard_requests = 0;
  1566. /** Map from dotted-quad IP address in response to an int holding how many
  1567. * times we've seen it for a randomly generated (hopefully bogus) address. It
  1568. * would be easier to use definitely-invalid addresses (as specified by
  1569. * RFC2606), but see comment in dns_launch_wildcard_checks(). */
  1570. static strmap_t *dns_wildcard_response_count = NULL;
  1571. /** If present, a list of dotted-quad IP addresses that we are pretty sure our
  1572. * nameserver wants to return in response to requests for nonexistent domains.
  1573. */
  1574. static smartlist_t *dns_wildcard_list = NULL;
  1575. /** True iff we've logged about a single address getting wildcarded.
  1576. * Subsequent warnings will be less severe. */
  1577. static int dns_wildcard_one_notice_given = 0;
  1578. /** True iff we've warned that our DNS server is wildcarding too many failures.
  1579. */
  1580. static int dns_wildcard_notice_given = 0;
  1581. /** List of supposedly good addresses that are getting wildcarded to the
  1582. * same addresses as nonexistent addresses. */
  1583. static smartlist_t *dns_wildcarded_test_address_list = NULL;
  1584. /** True iff we've warned about a test address getting wildcarded */
  1585. static int dns_wildcarded_test_address_notice_given = 0;
  1586. /** True iff all addresses seem to be getting wildcarded. */
  1587. static int dns_is_completely_invalid = 0;
  1588. /** Called when we see <b>id</b> (a dotted quad) in response to a request for
  1589. * a hopefully bogus address. */
  1590. static void
  1591. wildcard_increment_answer(const char *id)
  1592. {
  1593. int *ip;
  1594. if (!dns_wildcard_response_count)
  1595. dns_wildcard_response_count = strmap_new();
  1596. ip = strmap_get(dns_wildcard_response_count, id); // may be null (0)
  1597. if (!ip) {
  1598. ip = tor_malloc_zero(sizeof(int));
  1599. strmap_set(dns_wildcard_response_count, id, ip);
  1600. }
  1601. ++*ip;
  1602. if (*ip > 5 && n_wildcard_requests > 10) {
  1603. if (!dns_wildcard_list) dns_wildcard_list = smartlist_create();
  1604. if (!smartlist_string_isin(dns_wildcard_list, id)) {
  1605. log(dns_wildcard_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1606. "Your DNS provider has given \"%s\" as an answer for %d different "
  1607. "invalid addresses. Apparently they are hijacking DNS failures. "
  1608. "I'll try to correct for this by treating future occurrences of "
  1609. "\"%s\" as 'not found'.", id, *ip, id);
  1610. smartlist_add(dns_wildcard_list, tor_strdup(id));
  1611. }
  1612. if (!dns_wildcard_notice_given)
  1613. control_event_server_status(LOG_NOTICE, "DNS_HIJACKED");
  1614. dns_wildcard_notice_given = 1;
  1615. }
  1616. }
  1617. /** Note that a single test address (one believed to be good) seems to be
  1618. * getting redirected to the same IP as failures are. */
  1619. static void
  1620. add_wildcarded_test_address(const char *address)
  1621. {
  1622. int n, n_test_addrs;
  1623. if (!dns_wildcarded_test_address_list)
  1624. dns_wildcarded_test_address_list = smartlist_create();
  1625. if (smartlist_string_isin_case(dns_wildcarded_test_address_list, 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. 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();
  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 && type == DNS_IPv4_A && count) {
  1655. uint32_t *addrs = addresses;
  1656. int i;
  1657. char *string_address = arg;
  1658. for (i = 0; i < count; ++i) {
  1659. char answer_buf[INET_NTOA_BUF_LEN+1];
  1660. struct in_addr in;
  1661. in.s_addr = addrs[i];
  1662. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1663. wildcard_increment_answer(answer_buf);
  1664. }
  1665. log(dns_wildcard_one_notice_given ? LOG_INFO : LOG_NOTICE, LD_EXIT,
  1666. "Your DNS provider gave an answer for \"%s\", which "
  1667. "is not supposed to exist. Apparently they are hijacking "
  1668. "DNS failures. Trying to correct for this. We've noticed %d possibly "
  1669. "bad addresses so far.",
  1670. string_address, strmap_size(dns_wildcard_response_count));
  1671. dns_wildcard_one_notice_given = 1;
  1672. }
  1673. tor_free(arg);
  1674. }
  1675. /** Launch a single request for a nonexistent hostname consisting of between
  1676. * <b>min_len</b> and <b>max_len</b> random (plausible) characters followed by
  1677. * <b>suffix</b> */
  1678. static void
  1679. launch_wildcard_check(int min_len, int max_len, const char *suffix)
  1680. {
  1681. char random_bytes[20], name[64], *addr;
  1682. size_t len;
  1683. int r;
  1684. len = min_len + crypto_rand_int(max_len-min_len+1);
  1685. if (crypto_rand(random_bytes, sizeof(random_bytes)) < 0)
  1686. return;
  1687. base32_encode(name, sizeof(name), random_bytes, sizeof(random_bytes));
  1688. name[len] = '\0';
  1689. strlcat(name, suffix, sizeof(name));
  1690. addr = tor_strdup(name);
  1691. r = evdns_resolve_ipv4(name, DNS_QUERY_NO_SEARCH,
  1692. evdns_wildcard_check_callback, addr);
  1693. if (r)
  1694. tor_free(addr);
  1695. }
  1696. /** Launch attempts to resolve a bunch of known-good addresses (configured in
  1697. * ServerDNSTestAddresses). [Callback for a libevent timer] */
  1698. static void
  1699. launch_test_addresses(int fd, short event, void *args)
  1700. {
  1701. or_options_t *options = get_options();
  1702. (void)fd;
  1703. (void)event;
  1704. (void)args;
  1705. log_info(LD_EXIT, "Launching checks to see whether our nameservers like to "
  1706. "hijack *everything*.");
  1707. /* This situation is worse than the failure-hijacking situation. When this
  1708. * happens, we're no good for DNS requests at all, and we shouldn't really
  1709. * be an exit server.*/
  1710. if (!options->ServerDNSTestAddresses)
  1711. return;
  1712. SMARTLIST_FOREACH(options->ServerDNSTestAddresses, const char *, address,
  1713. {
  1714. evdns_resolve_ipv4(address, DNS_QUERY_NO_SEARCH, evdns_callback,
  1715. tor_strdup(address));
  1716. });
  1717. }
  1718. #define N_WILDCARD_CHECKS 2
  1719. /** Launch DNS requests for a few nonexistent hostnames and a few well-known
  1720. * hostnames, and see if we can catch our nameserver trying to hijack them and
  1721. * map them to a stupid "I couldn't find ggoogle.com but maybe you'd like to
  1722. * buy these lovely encyclopedias" page. */
  1723. static void
  1724. dns_launch_wildcard_checks(void)
  1725. {
  1726. int i;
  1727. log_info(LD_EXIT, "Launching checks to see whether our nameservers like "
  1728. "to hijack DNS failures.");
  1729. for (i = 0; i < N_WILDCARD_CHECKS; ++i) {
  1730. /* RFC2606 reserves these. Sadly, some DNS hijackers, in a silly attempt
  1731. * to 'comply' with rfc2606, refrain from giving A records for these.
  1732. * This is the standards-compliance equivalent of making sure that your
  1733. * crackhouse's elevator inspection certificate is up to date.
  1734. */
  1735. launch_wildcard_check(2, 16, ".invalid");
  1736. launch_wildcard_check(2, 16, ".test");
  1737. /* These will break specs if there are ever any number of
  1738. * 8+-character top-level domains. */
  1739. launch_wildcard_check(8, 16, "");
  1740. /* Try some random .com/org/net domains. This will work fine so long as
  1741. * not too many resolve to the same place. */
  1742. launch_wildcard_check(8, 16, ".com");
  1743. launch_wildcard_check(8, 16, ".org");
  1744. launch_wildcard_check(8, 16, ".net");
  1745. }
  1746. }
  1747. /** If appropriate, start testing whether our DNS servers tend to lie to
  1748. * us. */
  1749. void
  1750. dns_launch_correctness_checks(void)
  1751. {
  1752. static struct event launch_event;
  1753. struct timeval timeout;
  1754. if (!get_options()->ServerDNSDetectHijacking)
  1755. return;
  1756. dns_launch_wildcard_checks();
  1757. /* Wait a while before launching requests for test addresses, so we can
  1758. * get the results from checking for wildcarding. */
  1759. evtimer_set(&launch_event, launch_test_addresses, NULL);
  1760. timeout.tv_sec = 30;
  1761. timeout.tv_usec = 0;
  1762. evtimer_add(&launch_event, &timeout);
  1763. }
  1764. /** Return true iff our DNS servers lie to us too much to be trustd. */
  1765. int
  1766. dns_seems_to_be_broken(void)
  1767. {
  1768. return dns_is_completely_invalid;
  1769. }
  1770. /** Forget what we've previously learned about our DNS servers' correctness. */
  1771. void
  1772. dns_reset_correctness_checks(void)
  1773. {
  1774. if (dns_wildcard_response_count) {
  1775. strmap_free(dns_wildcard_response_count, _tor_free);
  1776. dns_wildcard_response_count = NULL;
  1777. }
  1778. n_wildcard_requests = 0;
  1779. if (dns_wildcard_list) {
  1780. SMARTLIST_FOREACH(dns_wildcard_list, char *, cp, tor_free(cp));
  1781. smartlist_clear(dns_wildcard_list);
  1782. }
  1783. if (dns_wildcarded_test_address_list) {
  1784. SMARTLIST_FOREACH(dns_wildcarded_test_address_list, char *, cp,
  1785. tor_free(cp));
  1786. smartlist_clear(dns_wildcarded_test_address_list);
  1787. }
  1788. dns_wildcard_one_notice_given = dns_wildcard_notice_given =
  1789. dns_wildcarded_test_address_notice_given = dns_is_completely_invalid = 0;
  1790. }
  1791. /** Return true iff we have noticed that the dotted-quad <b>ip</b> has been
  1792. * returned in response to requests for nonexistent hostnames. */
  1793. static int
  1794. answer_is_wildcarded(const char *ip)
  1795. {
  1796. return dns_wildcard_list && smartlist_string_isin(dns_wildcard_list, ip);
  1797. }
  1798. #endif /* USE_EVENTDNS */
  1799. /** Exit with an assertion if <b>resolve</b> is corrupt. */
  1800. static void
  1801. assert_resolve_ok(cached_resolve_t *resolve)
  1802. {
  1803. tor_assert(resolve);
  1804. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1805. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1806. tor_assert(tor_strisnonupper(resolve->address));
  1807. if (resolve->state != CACHE_STATE_PENDING) {
  1808. tor_assert(!resolve->pending_connections);
  1809. }
  1810. if (resolve->state == CACHE_STATE_PENDING ||
  1811. resolve->state == CACHE_STATE_DONE) {
  1812. tor_assert(!resolve->ttl);
  1813. if (resolve->is_reverse)
  1814. tor_assert(!resolve->result.hostname);
  1815. else
  1816. tor_assert(!resolve->result.addr);
  1817. }
  1818. }
  1819. #ifdef DEBUG_DNS_CACHE
  1820. /** Exit with an assertion if the DNS cache is corrupt. */
  1821. static void
  1822. _assert_cache_ok(void)
  1823. {
  1824. cached_resolve_t **resolve;
  1825. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1826. if (bad_rep) {
  1827. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1828. tor_assert(!bad_rep);
  1829. }
  1830. HT_FOREACH(resolve, cache_map, &cache_root) {
  1831. assert_resolve_ok(*resolve);
  1832. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1833. }
  1834. if (!cached_resolve_pqueue)
  1835. return;
  1836. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1837. _compare_cached_resolves_by_expiry);
  1838. }
  1839. #endif