dns.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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 asynchrounous 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. #endif
  47. /** Linked list of connections waiting for a DNS answer. */
  48. typedef struct pending_connection_t {
  49. edge_connection_t *conn;
  50. struct pending_connection_t *next;
  51. } pending_connection_t;
  52. #define CACHED_RESOLVE_MAGIC 0x1234F00D
  53. /* Possible states for a cached resolve_t */
  54. /** We are waiting for the resolver system to tell us an answer here.
  55. * When we get one, or when we time out, the state of this cached_resolve_t
  56. * will become "DONE" and we'll possibly add a CACHED_VALID or a CACHED_FAILED
  57. * entry. This cached_resolve_t will be in the hash table so that we will
  58. * know not to launch more requests for this addr, but rather to add more
  59. * connections to the pending list for the addr. */
  60. #define CACHE_STATE_PENDING 0
  61. /** This used to be a pending cached_resolve_t, and we got an answer for it.
  62. * Now we're waiting for this cached_resolve_t to expire. This should
  63. * have no pending connections, and should not appear in the hash table. */
  64. #define CACHE_STATE_DONE 1
  65. /** We are caching an answer for this address. This should have no pending
  66. * connections, and should appear in the hash table. */
  67. #define CACHE_STATE_CACHED_VALID 2
  68. /** We are caching a failure for this address. This should have no pending
  69. * connections, and should appear in the hash table */
  70. #define CACHE_STATE_CACHED_FAILED 3
  71. /** A DNS request: possibly completed, possibly pending; cached_resolve
  72. * structs are stored at the OR side in a hash table, and as a linked
  73. * list from oldest to newest.
  74. */
  75. typedef struct cached_resolve_t {
  76. HT_ENTRY(cached_resolve_t) node;
  77. uint32_t magic;
  78. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  79. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  80. uint8_t state; /**< Is this cached entry pending/done/valid/failed? */
  81. time_t expire; /**< Remove items from cache after this time. */
  82. uint32_t ttl; /**< What TTL did the nameserver tell us? */
  83. pending_connection_t *pending_connections;
  84. } cached_resolve_t;
  85. static void purge_expired_resolves(uint32_t now);
  86. static void dns_found_answer(const char *address, uint32_t addr, char outcome,
  87. uint32_t ttl);
  88. static void send_resolved_cell(edge_connection_t *conn, uint8_t answer_type);
  89. static int launch_resolve(edge_connection_t *exitconn);
  90. #ifndef USE_EVENTDNS
  91. static int dnsworker_main(void *data);
  92. static int spawn_dnsworker(void);
  93. static int spawn_enough_dnsworkers(void);
  94. #else
  95. static void configure_nameservers(void);
  96. #endif
  97. static void assert_cache_ok(void);
  98. static void assert_resolve_ok(cached_resolve_t *resolve);
  99. /** Hash table of cached_resolve objects. */
  100. static HT_HEAD(cache_map, cached_resolve_t) cache_root;
  101. /** Function to compare hashed resolves on their addresses; used to
  102. * implement hash tables. */
  103. static INLINE int
  104. cached_resolves_eq(cached_resolve_t *a, cached_resolve_t *b)
  105. {
  106. /* make this smarter one day? */
  107. assert_resolve_ok(a); // Not b; b may be just a search.
  108. return !strncmp(a->address, b->address, MAX_ADDRESSLEN);
  109. }
  110. static INLINE unsigned int
  111. cached_resolve_hash(cached_resolve_t *a)
  112. {
  113. return ht_string_hash(a->address);
  114. }
  115. HT_PROTOTYPE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  116. cached_resolves_eq);
  117. HT_GENERATE(cache_map, cached_resolve_t, node, cached_resolve_hash,
  118. cached_resolves_eq, 0.6, malloc, realloc, free);
  119. /** Initialize the DNS cache. */
  120. static void
  121. init_cache_map(void)
  122. {
  123. HT_INIT(&cache_root);
  124. }
  125. #ifdef USE_EVENTDNS
  126. static void
  127. eventdns_log_cb(const char *msg)
  128. {
  129. if (!strcmpstart(msg, "Resolve requested for") &&
  130. get_options()->SafeLogging) {
  131. log(LOG_INFO, LD_EXIT, "eventdns: Resolve requested.");
  132. return;
  133. }
  134. log(LOG_INFO, LD_EXIT, "eventdns: %s", msg);
  135. }
  136. #endif
  137. /** Initialize the DNS subsystem; called by the OR process. */
  138. void
  139. dns_init(void)
  140. {
  141. init_cache_map();
  142. dnsworkers_rotate();
  143. if (server_mode(get_options()))
  144. configure_nameservers();
  145. }
  146. uint32_t
  147. dns_clip_ttl(uint32_t ttl)
  148. {
  149. if (ttl < MIN_DNS_TTL)
  150. return MIN_DNS_TTL;
  151. else if (ttl > MAX_DNS_TTL)
  152. return MAX_DNS_TTL;
  153. else
  154. return ttl;
  155. }
  156. static uint32_t
  157. dns_get_expiry_ttl(uint32_t ttl)
  158. {
  159. if (ttl < MIN_DNS_TTL)
  160. return MIN_DNS_TTL;
  161. else if (ttl > MAX_DNS_ENTRY_AGE)
  162. return MAX_DNS_ENTRY_AGE;
  163. else
  164. return ttl;
  165. }
  166. /** Helper: free storage held by an entry in the DNS cache. */
  167. static void
  168. _free_cached_resolve(cached_resolve_t *r)
  169. {
  170. while (r->pending_connections) {
  171. pending_connection_t *victim = r->pending_connections;
  172. r->pending_connections = victim->next;
  173. tor_free(victim);
  174. }
  175. r->magic = 0xFF00FF00;
  176. tor_free(r);
  177. }
  178. /** Compare two cached_resolve_t pointers by expiry time, and return
  179. * less-than-zero, zero, or greater-than-zero as appropriate. Used for
  180. * the priority queue implementation. */
  181. static int
  182. _compare_cached_resolves_by_expiry(const void *_a, const void *_b)
  183. {
  184. const cached_resolve_t *a = _a, *b = _b;
  185. if (a->expire < b->expire)
  186. return -1;
  187. else if (a->expire == b->expire)
  188. return 0;
  189. else
  190. return 1;
  191. }
  192. /** Priority queue of cached_resolve_t objects to let us know when they
  193. * will expire. */
  194. static smartlist_t *cached_resolve_pqueue = NULL;
  195. /** Set an expiry time for a cached_resolve_t, and add it to the expiry
  196. * priority queue */
  197. static void
  198. set_expiry(cached_resolve_t *resolve, time_t expires)
  199. {
  200. tor_assert(resolve && resolve->expire == 0);
  201. if (!cached_resolve_pqueue)
  202. cached_resolve_pqueue = smartlist_create();
  203. resolve->expire = expires;
  204. smartlist_pqueue_add(cached_resolve_pqueue,
  205. _compare_cached_resolves_by_expiry,
  206. resolve);
  207. }
  208. /** Free all storage held in the DNS cache */
  209. void
  210. dns_free_all(void)
  211. {
  212. cached_resolve_t **ptr, **next, *item;
  213. for (ptr = HT_START(cache_map, &cache_root); ptr != NULL; ptr = next) {
  214. item = *ptr;
  215. next = HT_NEXT_RMV(cache_map, &cache_root, ptr);
  216. _free_cached_resolve(item);
  217. }
  218. HT_CLEAR(cache_map, &cache_root);
  219. if (cached_resolve_pqueue)
  220. smartlist_free(cached_resolve_pqueue);
  221. cached_resolve_pqueue = NULL;
  222. }
  223. /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
  224. * from the cache. */
  225. static void
  226. purge_expired_resolves(uint32_t now)
  227. {
  228. cached_resolve_t *resolve, *removed;
  229. pending_connection_t *pend;
  230. edge_connection_t *pendconn;
  231. assert_cache_ok();
  232. if (!cached_resolve_pqueue)
  233. return;
  234. while (smartlist_len(cached_resolve_pqueue)) {
  235. resolve = smartlist_get(cached_resolve_pqueue, 0);
  236. if (resolve->expire > now)
  237. break;
  238. smartlist_pqueue_pop(cached_resolve_pqueue,
  239. _compare_cached_resolves_by_expiry);
  240. if (resolve->state == CACHE_STATE_PENDING) {
  241. log_debug(LD_EXIT,
  242. "Expiring a dns resolve %s that's still pending. Forgot to cull"
  243. " it? DNS resolve didn't tell us about the timeout?",
  244. escaped_safe_str(resolve->address));
  245. } else if (resolve->state == CACHE_STATE_CACHED_VALID ||
  246. resolve->state == CACHE_STATE_CACHED_FAILED) {
  247. log_debug(LD_EXIT,
  248. "Forgetting old cached resolve (address %s, expires %lu)",
  249. escaped_safe_str(resolve->address),
  250. (unsigned long)resolve->expire);
  251. tor_assert(!resolve->pending_connections);
  252. } else {
  253. tor_assert(resolve->state == CACHE_STATE_DONE);
  254. tor_assert(!resolve->pending_connections);
  255. }
  256. if (resolve->pending_connections) {
  257. log_debug(LD_EXIT,
  258. "Closing pending connections on timed-out DNS resolve!");
  259. tor_fragile_assert();
  260. while (resolve->pending_connections) {
  261. pend = resolve->pending_connections;
  262. resolve->pending_connections = pend->next;
  263. /* Connections should only be pending if they have no socket. */
  264. tor_assert(pend->conn->_base.s == -1);
  265. pendconn = pend->conn;
  266. connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
  267. pendconn->cpath_layer);
  268. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  269. connection_free(TO_CONN(pendconn));
  270. tor_free(pend);
  271. }
  272. }
  273. if (resolve->state == CACHE_STATE_CACHED_VALID ||
  274. resolve->state == CACHE_STATE_CACHED_FAILED ||
  275. resolve->state == CACHE_STATE_PENDING) {
  276. removed = HT_REMOVE(cache_map, &cache_root, resolve);
  277. if (removed != resolve) {
  278. log_err(LD_BUG, "The expired resolve we purged didn't match any in"
  279. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  280. resolve->address, resolve,
  281. removed ? removed->address : "NULL", remove);
  282. }
  283. tor_assert(removed == resolve);
  284. resolve->magic = 0xF0BBF0BB;
  285. tor_free(resolve);
  286. } else {
  287. /* This should be in state DONE. Make sure it's not in the cache. */
  288. cached_resolve_t *tmp = HT_FIND(cache_map, &cache_root, resolve);
  289. tor_assert(tmp != resolve);
  290. }
  291. }
  292. assert_cache_ok();
  293. }
  294. /** Send a response to the RESOLVE request of a connection. answer_type must
  295. * be one of RESOLVED_TYPE_(IPV4|ERROR|ERROR_TRANSIENT) */
  296. static void
  297. send_resolved_cell(edge_connection_t *conn, uint8_t answer_type)
  298. {
  299. char buf[RELAY_PAYLOAD_SIZE];
  300. size_t buflen;
  301. uint32_t ttl;
  302. buf[0] = answer_type;
  303. ttl = dns_clip_ttl(conn->address_ttl);
  304. switch (answer_type)
  305. {
  306. case RESOLVED_TYPE_IPV4:
  307. buf[1] = 4;
  308. set_uint32(buf+2, htonl(conn->_base.addr));
  309. set_uint32(buf+6, htonl(ttl));
  310. buflen = 10;
  311. break;
  312. case RESOLVED_TYPE_ERROR_TRANSIENT:
  313. case RESOLVED_TYPE_ERROR:
  314. {
  315. const char *errmsg = "Error resolving hostname";
  316. int msglen = strlen(errmsg);
  317. buf[1] = msglen;
  318. strlcpy(buf+2, errmsg, sizeof(buf)-2);
  319. set_uint32(buf+2+msglen, htonl(ttl));
  320. buflen = 6+msglen;
  321. break;
  322. }
  323. default:
  324. tor_assert(0);
  325. }
  326. connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
  327. RELAY_COMMAND_RESOLVED, buf, buflen,
  328. conn->cpath_layer);
  329. }
  330. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  331. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  332. * If resolve failed, unlink exitconn if needed, free it, and return -1.
  333. *
  334. * Else, if seen before and pending, add conn to the pending list,
  335. * and return 0.
  336. *
  337. * Else, if not seen before, add conn to pending list, hand to
  338. * dns farm, and return 0.
  339. */
  340. int
  341. dns_resolve(edge_connection_t *exitconn)
  342. {
  343. cached_resolve_t *resolve;
  344. cached_resolve_t search;
  345. pending_connection_t *pending_connection;
  346. struct in_addr in;
  347. circuit_t *circ;
  348. uint32_t now = time(NULL);
  349. assert_connection_ok(TO_CONN(exitconn), 0);
  350. tor_assert(exitconn->_base.s == -1);
  351. assert_cache_ok();
  352. /* first check if exitconn->_base.address is an IP. If so, we already
  353. * know the answer. */
  354. if (tor_inet_aton(exitconn->_base.address, &in) != 0) {
  355. exitconn->_base.addr = ntohl(in.s_addr);
  356. exitconn->address_ttl = DEFAULT_DNS_TTL;
  357. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  358. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  359. return 1;
  360. }
  361. /* then take this opportunity to see if there are any expired
  362. * resolves in the hash table. */
  363. purge_expired_resolves(now);
  364. /* lower-case exitconn->_base.address, so it's in canonical form */
  365. tor_strlower(exitconn->_base.address);
  366. /* now check the hash table to see if 'address' is already there. */
  367. strlcpy(search.address, exitconn->_base.address, sizeof(search.address));
  368. resolve = HT_FIND(cache_map, &cache_root, &search);
  369. if (resolve && resolve->expire > now) { /* already there */
  370. switch (resolve->state) {
  371. case CACHE_STATE_PENDING:
  372. /* add us to the pending list */
  373. pending_connection = tor_malloc_zero(
  374. sizeof(pending_connection_t));
  375. pending_connection->conn = exitconn;
  376. pending_connection->next = resolve->pending_connections;
  377. resolve->pending_connections = pending_connection;
  378. log_debug(LD_EXIT,"Connection (fd %d) waiting for pending DNS "
  379. "resolve of %s", exitconn->_base.s,
  380. escaped_safe_str(exitconn->_base.address));
  381. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  382. return 0;
  383. case CACHE_STATE_CACHED_VALID:
  384. exitconn->_base.addr = resolve->addr;
  385. exitconn->address_ttl = resolve->ttl;
  386. log_debug(LD_EXIT,"Connection (fd %d) found cached answer for %s",
  387. exitconn->_base.s,
  388. escaped_safe_str(exitconn->_base.address));
  389. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  390. send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
  391. return 1;
  392. case CACHE_STATE_CACHED_FAILED:
  393. log_debug(LD_EXIT,"Connection (fd %d) found cached error for %s",
  394. exitconn->_base.s,
  395. escaped_safe_str(exitconn->_base.address));
  396. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  397. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
  398. circ = circuit_get_by_edge_conn(exitconn);
  399. if (circ)
  400. circuit_detach_stream(circ, exitconn);
  401. if (!exitconn->_base.marked_for_close)
  402. connection_free(TO_CONN(exitconn));
  403. return -1;
  404. case CACHE_STATE_DONE:
  405. log_err(LD_BUG, "Found a 'DONE' dns resolve still in the cache.");
  406. tor_fragile_assert();
  407. }
  408. tor_assert(0);
  409. }
  410. /* not there, need to add it */
  411. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  412. resolve->magic = CACHED_RESOLVE_MAGIC;
  413. resolve->state = CACHE_STATE_PENDING;
  414. strlcpy(resolve->address, exitconn->_base.address, sizeof(resolve->address));
  415. /* add this connection to the pending list */
  416. pending_connection = tor_malloc_zero(sizeof(pending_connection_t));
  417. pending_connection->conn = exitconn;
  418. resolve->pending_connections = pending_connection;
  419. exitconn->_base.state = EXIT_CONN_STATE_RESOLVING;
  420. /* Add this resolve to the cache and priority queue. */
  421. HT_INSERT(cache_map, &cache_root, resolve);
  422. set_expiry(resolve, now + RESOLVE_MAX_TIMEOUT);
  423. log_debug(LD_EXIT,"Launching %s.",
  424. escaped_safe_str(exitconn->_base.address));
  425. assert_cache_ok();
  426. return launch_resolve(exitconn);
  427. }
  428. /** Log an error and abort if conn is waiting for a DNS resolve.
  429. */
  430. void
  431. assert_connection_edge_not_dns_pending(edge_connection_t *conn)
  432. {
  433. pending_connection_t *pend;
  434. cached_resolve_t **resolve;
  435. HT_FOREACH(resolve, cache_map, &cache_root) {
  436. for (pend = (*resolve)->pending_connections;
  437. pend;
  438. pend = pend->next) {
  439. tor_assert(pend->conn != conn);
  440. }
  441. }
  442. }
  443. /** Log an error and abort if any connection waiting for a DNS resolve is
  444. * corrupted. */
  445. void
  446. assert_all_pending_dns_resolves_ok(void)
  447. {
  448. pending_connection_t *pend;
  449. cached_resolve_t **resolve;
  450. HT_FOREACH(resolve, cache_map, &cache_root) {
  451. for (pend = (*resolve)->pending_connections;
  452. pend;
  453. pend = pend->next) {
  454. assert_connection_ok(TO_CONN(pend->conn), 0);
  455. tor_assert(pend->conn->_base.s == -1);
  456. tor_assert(!connection_in_array(TO_CONN(pend->conn)));
  457. }
  458. }
  459. }
  460. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  461. */
  462. void
  463. connection_dns_remove(edge_connection_t *conn)
  464. {
  465. pending_connection_t *pend, *victim;
  466. cached_resolve_t search;
  467. cached_resolve_t *resolve;
  468. tor_assert(conn->_base.type == CONN_TYPE_EXIT);
  469. tor_assert(conn->_base.state == EXIT_CONN_STATE_RESOLVING);
  470. strlcpy(search.address, conn->_base.address, sizeof(search.address));
  471. resolve = HT_FIND(cache_map, &cache_root, &search);
  472. if (!resolve) {
  473. log_notice(LD_BUG, "Address %s is not pending. Dropping.",
  474. escaped_safe_str(conn->_base.address));
  475. return;
  476. }
  477. tor_assert(resolve->pending_connections);
  478. assert_connection_ok(TO_CONN(conn),0);
  479. pend = resolve->pending_connections;
  480. if (pend->conn == conn) {
  481. resolve->pending_connections = pend->next;
  482. tor_free(pend);
  483. log_debug(LD_EXIT, "First connection (fd %d) no longer waiting "
  484. "for resolve of %s",
  485. conn->_base.s, escaped_safe_str(conn->_base.address));
  486. return;
  487. } else {
  488. for ( ; pend->next; pend = pend->next) {
  489. if (pend->next->conn == conn) {
  490. victim = pend->next;
  491. pend->next = victim->next;
  492. tor_free(victim);
  493. log_debug(LD_EXIT,
  494. "Connection (fd %d) no longer waiting for resolve of %s",
  495. conn->_base.s, escaped_safe_str(conn->_base.address));
  496. return; /* more are pending */
  497. }
  498. }
  499. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  500. }
  501. }
  502. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  503. * the resolve for <b>address</b> itself, and remove any cached results for
  504. * <b>address</b> from the cache.
  505. */
  506. void
  507. dns_cancel_pending_resolve(char *address)
  508. {
  509. pending_connection_t *pend;
  510. cached_resolve_t search;
  511. cached_resolve_t *resolve, *tmp;
  512. edge_connection_t *pendconn;
  513. circuit_t *circ;
  514. strlcpy(search.address, address, sizeof(search.address));
  515. resolve = HT_FIND(cache_map, &cache_root, &search);
  516. if (!resolve || resolve->state != CACHE_STATE_PENDING) {
  517. log_notice(LD_BUG,"Address %s is not pending. Dropping.",
  518. escaped_safe_str(address));
  519. return;
  520. }
  521. if (!resolve->pending_connections) {
  522. /* XXX this should never trigger, but sometimes it does */
  523. log_warn(LD_BUG,
  524. "Bug: Address %s is pending but has no pending connections!",
  525. escaped_safe_str(address));
  526. tor_fragile_assert();
  527. return;
  528. }
  529. tor_assert(resolve->pending_connections);
  530. tor_assert(! resolve->expire);
  531. /* mark all pending connections to fail */
  532. log_debug(LD_EXIT,
  533. "Failing all connections waiting on DNS resolve of %s",
  534. escaped_safe_str(address));
  535. while (resolve->pending_connections) {
  536. pend = resolve->pending_connections;
  537. pend->conn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  538. pendconn = pend->conn;
  539. assert_connection_ok(TO_CONN(pendconn), 0);
  540. tor_assert(pendconn->_base.s == -1);
  541. if (!pendconn->_base.marked_for_close) {
  542. connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
  543. pendconn->cpath_layer);
  544. }
  545. circ = circuit_get_by_edge_conn(pendconn);
  546. if (circ)
  547. circuit_detach_stream(circ, pendconn);
  548. connection_free(TO_CONN(pendconn));
  549. resolve->pending_connections = pend->next;
  550. tor_free(pend);
  551. }
  552. tmp = HT_REMOVE(cache_map, &cache_root, resolve);
  553. if (tmp != resolve) {
  554. log_err(LD_BUG, "The cancelled resolve we purged didn't match any in"
  555. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  556. resolve->address, resolve,
  557. tmp ? tmp->address : "NULL", tmp);
  558. }
  559. tor_assert(tmp == resolve);
  560. resolve->magic = 0xABABABAB;
  561. tor_free(resolve);
  562. }
  563. static void
  564. add_answer_to_cache(const char *address, uint32_t addr, char outcome,
  565. uint32_t ttl)
  566. {
  567. cached_resolve_t *resolve;
  568. if (outcome == DNS_RESOLVE_FAILED_TRANSIENT)
  569. return;
  570. resolve = tor_malloc_zero(sizeof(cached_resolve_t));
  571. resolve->magic = CACHED_RESOLVE_MAGIC;
  572. resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
  573. CACHE_STATE_CACHED_VALID : CACHE_STATE_CACHED_FAILED;
  574. strlcpy(resolve->address, address, sizeof(resolve->address));
  575. resolve->addr = addr;
  576. resolve->ttl = ttl;
  577. assert_resolve_ok(resolve);
  578. HT_INSERT(cache_map, &cache_root, resolve);
  579. set_expiry(resolve, time(NULL) + dns_get_expiry_ttl(ttl));
  580. }
  581. /** Called on the OR side when a DNS worker tells us the outcome of a DNS
  582. * resolve: tell all pending connections about the result of the lookup, and
  583. * cache the value. (<b>address</b> is a NUL-terminated string containing the
  584. * address to look up; <b>addr</b> is an IPv4 address in host order;
  585. * <b>outcome</b> is one of
  586. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  587. */
  588. static void
  589. dns_found_answer(const char *address, uint32_t addr, char outcome,
  590. uint32_t ttl)
  591. {
  592. pending_connection_t *pend;
  593. cached_resolve_t search;
  594. cached_resolve_t *resolve, *removed;
  595. edge_connection_t *pendconn;
  596. circuit_t *circ;
  597. assert_cache_ok();
  598. strlcpy(search.address, address, sizeof(search.address));
  599. resolve = HT_FIND(cache_map, &cache_root, &search);
  600. if (!resolve) {
  601. log_info(LD_EXIT,"Resolved unasked address %s; caching anyway.",
  602. escaped_safe_str(address));
  603. add_answer_to_cache(address, addr, outcome, ttl);
  604. return;
  605. }
  606. assert_resolve_ok(resolve);
  607. if (resolve->state != CACHE_STATE_PENDING) {
  608. /* XXXX Maybe update addr? or check addr for consistency? Or let
  609. * VALID replace FAILED? */
  610. log_notice(LD_EXIT, "Resolved %s which was already resolved; ignoring",
  611. escaped_safe_str(address));
  612. tor_assert(resolve->pending_connections == NULL);
  613. return;
  614. }
  615. /* Removed this assertion: in fact, we'll sometimes get a double answer
  616. * to the same question. This can happen when we ask one worker to resolve
  617. * X.Y.Z., then we cancel the request, and then we ask another worker to
  618. * resolve X.Y.Z. */
  619. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  620. while (resolve->pending_connections) {
  621. pend = resolve->pending_connections;
  622. pendconn = pend->conn; /* don't pass complex things to the
  623. connection_mark_for_close macro */
  624. assert_connection_ok(TO_CONN(pendconn),time(NULL));
  625. pendconn->_base.addr = addr;
  626. pendconn->address_ttl = ttl;
  627. if (outcome != DNS_RESOLVE_SUCCEEDED) {
  628. /* prevent double-remove. */
  629. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  630. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  631. connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED,
  632. pendconn->cpath_layer);
  633. /* This detach must happen after we send the end cell. */
  634. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  635. } else {
  636. send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
  637. /* This detach must happen after we send the resolved cell. */
  638. circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
  639. }
  640. connection_free(TO_CONN(pendconn));
  641. } else {
  642. if (pendconn->_base.purpose == EXIT_PURPOSE_CONNECT) {
  643. /* prevent double-remove. */
  644. pend->conn->_base.state = EXIT_CONN_STATE_CONNECTING;
  645. circ = circuit_get_by_edge_conn(pend->conn);
  646. tor_assert(circ);
  647. tor_assert(!CIRCUIT_IS_ORIGIN(circ));
  648. /* unlink pend->conn from resolving_streams, */
  649. circuit_detach_stream(circ, pend->conn);
  650. /* and link it to n_streams */
  651. pend->conn->next_stream = TO_OR_CIRCUIT(circ)->n_streams;
  652. pend->conn->on_circuit = circ;
  653. TO_OR_CIRCUIT(circ)->n_streams = pend->conn;
  654. connection_exit_connect(pend->conn);
  655. } else {
  656. /* prevent double-remove. This isn't really an accurate state,
  657. * but it does the right thing. */
  658. pendconn->_base.state = EXIT_CONN_STATE_RESOLVEFAILED;
  659. send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
  660. circ = circuit_get_by_edge_conn(pendconn);
  661. tor_assert(circ);
  662. circuit_detach_stream(circ, pendconn);
  663. connection_free(TO_CONN(pendconn));
  664. }
  665. }
  666. resolve->pending_connections = pend->next;
  667. tor_free(pend);
  668. }
  669. resolve->state = CACHE_STATE_DONE;
  670. removed = HT_REMOVE(cache_map, &cache_root, &search);
  671. if (removed != resolve) {
  672. log_err(LD_BUG, "The pending resolve we found wasn't removable from"
  673. " the cache. Tried to purge %s (%p); instead got %s (%p).",
  674. resolve->address, resolve,
  675. removed ? removed->address : "NULL", removed);
  676. }
  677. assert_resolve_ok(resolve);
  678. assert_cache_ok();
  679. add_answer_to_cache(address, addr, outcome, ttl);
  680. assert_cache_ok();
  681. }
  682. #ifndef USE_EVENTDNS
  683. /** Find or spawn a dns worker process to handle resolving
  684. * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
  685. */
  686. static int
  687. launch_resolve(edge_connection_t *exitconn)
  688. {
  689. connection_t *dnsconn;
  690. unsigned char len;
  691. tor_assert(exitconn->_base.state == EXIT_CONN_STATE_RESOLVING);
  692. assert_connection_ok(TO_CONN(exitconn), 0);
  693. tor_assert(exitconn->_base.s == -1);
  694. /* respawn here, to be sure there are enough */
  695. if (spawn_enough_dnsworkers() < 0) {
  696. goto err;
  697. }
  698. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  699. DNSWORKER_STATE_IDLE);
  700. if (!dnsconn) {
  701. log_warn(LD_EXIT,"no idle dns workers. Failing.");
  702. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE)
  703. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
  704. goto err;
  705. }
  706. log_debug(LD_EXIT,
  707. "Connection (fd %d) needs to resolve %s; assigning "
  708. "to DNSWorker (fd %d)", exitconn->_base.s,
  709. escaped_safe_str(exitconn->_base.address), dnsconn->s);
  710. tor_free(dnsconn->address);
  711. dnsconn->address = tor_strdup(exitconn->_base.address);
  712. dnsconn->state = DNSWORKER_STATE_BUSY;
  713. /* touch the lastwritten timestamp, since that's how we check to
  714. * see how long it's been since we asked the question, and sometimes
  715. * we check before the first call to connection_handle_write(). */
  716. dnsconn->timestamp_lastwritten = time(NULL);
  717. num_dnsworkers_busy++;
  718. len = strlen(dnsconn->address);
  719. connection_write_to_buf((char*)&len, 1, dnsconn);
  720. connection_write_to_buf(dnsconn->address, len, dnsconn);
  721. return 0;
  722. err:
  723. /* also sends end and frees */
  724. dns_cancel_pending_resolve(exitconn->_base.address);
  725. return -1;
  726. }
  727. /******************************************************************/
  728. /*
  729. * Connection between OR and dnsworker
  730. */
  731. /** Write handler: called when we've pushed a request to a dnsworker. */
  732. int
  733. connection_dns_finished_flushing(connection_t *conn)
  734. {
  735. tor_assert(conn);
  736. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  737. connection_stop_writing(conn);
  738. return 0;
  739. }
  740. int
  741. connection_dns_reached_eof(connection_t *conn)
  742. {
  743. log_warn(LD_EXIT,"Read eof. Worker died unexpectedly.");
  744. if (conn->state == DNSWORKER_STATE_BUSY) {
  745. /* don't cancel the resolve here -- it would be cancelled in
  746. * connection_about_to_close_connection(), since conn is still
  747. * in state BUSY
  748. */
  749. num_dnsworkers_busy--;
  750. }
  751. num_dnsworkers--;
  752. connection_mark_for_close(conn);
  753. return 0;
  754. }
  755. /** Read handler: called when we get data from a dnsworker. See
  756. * if we have a complete answer. If so, call dns_found_answer on the
  757. * result. If not, wait. Returns 0. */
  758. int
  759. connection_dns_process_inbuf(connection_t *conn)
  760. {
  761. char success;
  762. uint32_t addr;
  763. int ttl;
  764. tor_assert(conn);
  765. tor_assert(conn->type == CONN_TYPE_DNSWORKER);
  766. if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
  767. log_warn(LD_BUG,
  768. "Bug: read data (%d bytes) from an idle dns worker (fd %d, "
  769. "address %s). Please report.", (int)buf_datalen(conn->inbuf),
  770. conn->s, escaped_safe_str(conn->address));
  771. tor_fragile_assert();
  772. /* Pull it off the buffer anyway, or it will just stay there.
  773. * Keep pulling things off because sometimes we get several
  774. * answers at once (!). */
  775. while (buf_datalen(conn->inbuf)) {
  776. connection_fetch_from_buf(&success,1,conn);
  777. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  778. log_warn(LD_EXIT,"Discarding idle dns answer (success %d, addr %d.)",
  779. success, addr);
  780. }
  781. return 0;
  782. }
  783. if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  784. return 0; /* not yet */
  785. tor_assert(conn->state == DNSWORKER_STATE_BUSY);
  786. tor_assert(buf_datalen(conn->inbuf) == 5);
  787. connection_fetch_from_buf(&success,1,conn);
  788. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  789. log_debug(LD_EXIT, "DNSWorker (fd %d) returned answer for %s",
  790. conn->s, escaped_safe_str(conn->address));
  791. tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  792. tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
  793. ttl = (success == DNS_RESOLVE_FAILED_TRANSIENT) ? 0 : MAX_DNS_ENTRY_AGE;
  794. dns_found_answer(conn->address, ntohl(addr), success, ttl);
  795. tor_free(conn->address);
  796. conn->address = tor_strdup("<idle>");
  797. conn->state = DNSWORKER_STATE_IDLE;
  798. num_dnsworkers_busy--;
  799. if (conn->timestamp_created < last_rotation_time) {
  800. connection_mark_for_close(conn);
  801. num_dnsworkers--;
  802. spawn_enough_dnsworkers();
  803. }
  804. return 0;
  805. }
  806. /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
  807. * and re-opened once they're no longer busy.
  808. **/
  809. void
  810. dnsworkers_rotate(void)
  811. {
  812. connection_t *dnsconn;
  813. while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  814. DNSWORKER_STATE_IDLE))) {
  815. connection_mark_for_close(dnsconn);
  816. num_dnsworkers--;
  817. }
  818. last_rotation_time = time(NULL);
  819. if (server_mode(get_options()))
  820. spawn_enough_dnsworkers();
  821. }
  822. /** Implementation for DNS workers; this code runs in a separate
  823. * execution context. It takes as its argument an fdarray as returned
  824. * by socketpair(), and communicates via fdarray[1]. The protocol is
  825. * as follows:
  826. * - The OR says:
  827. * - ADDRESSLEN [1 byte]
  828. * - ADDRESS [ADDRESSLEN bytes]
  829. * - The DNS worker does the lookup, and replies:
  830. * - OUTCOME [1 byte]
  831. * - IP [4 bytes]
  832. *
  833. * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  834. * IP is in host order.
  835. *
  836. * The dnsworker runs indefinitely, until its connection is closed or an error
  837. * occurs.
  838. */
  839. static int
  840. dnsworker_main(void *data)
  841. {
  842. char address[MAX_ADDRESSLEN];
  843. unsigned char address_len;
  844. char *log_address;
  845. char answer[5];
  846. uint32_t ip;
  847. int *fdarray = data;
  848. int fd;
  849. int result;
  850. /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray,
  851. * fdarray[0],fdarray[1]); */
  852. fd = fdarray[1]; /* this side is ours */
  853. #ifndef TOR_IS_MULTITHREADED
  854. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  855. * parent uses */
  856. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  857. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  858. #endif
  859. tor_free(data);
  860. for (;;) {
  861. int r;
  862. if ((r = recv(fd, &address_len, 1, 0)) != 1) {
  863. if (r == 0) {
  864. log_info(LD_EXIT,"DNS worker exiting because Tor process closed "
  865. "connection (either pruned idle dnsworker or died).");
  866. } else {
  867. log_info(LD_EXIT,"DNS worker exiting because of error on connection "
  868. "to Tor process.");
  869. log_info(LD_EXIT,"(Error on %d was %s)", fd,
  870. tor_socket_strerror(tor_socket_errno(fd)));
  871. }
  872. tor_close_socket(fd);
  873. crypto_thread_cleanup();
  874. spawn_exit();
  875. }
  876. if (address_len && read_all(fd, address, address_len, 1) != address_len) {
  877. log_err(LD_BUG,"read hostname failed. Child exiting.");
  878. tor_close_socket(fd);
  879. crypto_thread_cleanup();
  880. spawn_exit();
  881. }
  882. address[address_len] = 0; /* nul terminate it */
  883. log_address = esc_for_log(safe_str(address));
  884. result = tor_lookup_hostname(address, &ip);
  885. /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
  886. if (!ip)
  887. result = -1;
  888. switch (result) {
  889. case 1:
  890. /* XXX result can never be 1, because we set it to -1 above on error */
  891. log_info(LD_NET,"Could not resolve dest addr %s (transient).",
  892. log_address);
  893. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  894. break;
  895. case -1:
  896. log_info(LD_NET,"Could not resolve dest addr %s (permanent).",
  897. log_address);
  898. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  899. break;
  900. case 0:
  901. log_info(LD_NET,"Resolved address %s.", log_address);
  902. answer[0] = DNS_RESOLVE_SUCCEEDED;
  903. break;
  904. }
  905. tor_free(log_address);
  906. set_uint32(answer+1, ip);
  907. if (write_all(fd, answer, 5, 1) != 5) {
  908. log_err(LD_NET,"writing answer failed. Child exiting.");
  909. tor_close_socket(fd);
  910. crypto_thread_cleanup();
  911. spawn_exit();
  912. }
  913. }
  914. return 0; /* windows wants this function to return an int */
  915. }
  916. /** Launch a new DNS worker; return 0 on success, -1 on failure.
  917. */
  918. static int
  919. spawn_dnsworker(void)
  920. {
  921. int *fdarray;
  922. int fd;
  923. connection_t *conn;
  924. int err;
  925. fdarray = tor_malloc(sizeof(int)*2);
  926. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  927. log_warn(LD_NET, "Couldn't construct socketpair: %s",
  928. tor_socket_strerror(-err));
  929. tor_free(fdarray);
  930. return -1;
  931. }
  932. tor_assert(fdarray[0] >= 0);
  933. tor_assert(fdarray[1] >= 0);
  934. /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d",
  935. (int)fdarray, fdarray[0],fdarray[1]); */
  936. fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free
  937. * fdarray */
  938. spawn_func(dnsworker_main, (void*)fdarray);
  939. log_debug(LD_EXIT,"just spawned a dns worker.");
  940. #ifndef TOR_IS_MULTITHREADED
  941. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  942. tor_free(fdarray);
  943. #endif
  944. conn = connection_new(CONN_TYPE_DNSWORKER);
  945. set_socket_nonblocking(fd);
  946. /* set up conn so it's got all the data we need to remember */
  947. conn->s = fd;
  948. conn->address = tor_strdup("<unused>");
  949. if (connection_add(conn) < 0) { /* no space, forget it */
  950. log_warn(LD_NET,"connection_add failed. Giving up.");
  951. connection_free(conn); /* this closes fd */
  952. return -1;
  953. }
  954. conn->state = DNSWORKER_STATE_IDLE;
  955. connection_start_reading(conn);
  956. return 0; /* success */
  957. }
  958. /** If we have too many or too few DNS workers, spawn or kill some.
  959. * Return 0 if we are happy, return -1 if we tried to spawn more but
  960. * we couldn't.
  961. */
  962. static int
  963. spawn_enough_dnsworkers(void)
  964. {
  965. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  966. * but no less than min and no more than max */
  967. connection_t *dnsconn;
  968. /* XXX This may not be the best strategy. Maybe we should queue pending
  969. * requests until the old ones finish or time out: otherwise, if the
  970. * connection requests come fast enough, we never get any DNS done. -NM
  971. *
  972. * XXX But if we queue them, then the adversary can pile even more
  973. * queries onto us, blocking legitimate requests for even longer. Maybe
  974. * we should compromise and only kill if it's been at it for more than,
  975. * e.g., 2 seconds. -RD
  976. */
  977. if (num_dnsworkers_busy == MAX_DNSWORKERS) {
  978. /* We always want at least one worker idle.
  979. * So find the oldest busy worker and kill it.
  980. */
  981. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  982. DNSWORKER_STATE_BUSY);
  983. tor_assert(dnsconn);
  984. log_warn(LD_EXIT, "%d DNS workers are spawned; all are busy. Killing one.",
  985. MAX_DNSWORKERS);
  986. connection_mark_for_close(dnsconn);
  987. num_dnsworkers_busy--;
  988. num_dnsworkers--;
  989. }
  990. if (num_dnsworkers_busy >= MIN_DNSWORKERS)
  991. num_dnsworkers_needed = num_dnsworkers_busy+1;
  992. else
  993. num_dnsworkers_needed = MIN_DNSWORKERS;
  994. while (num_dnsworkers < num_dnsworkers_needed) {
  995. if (spawn_dnsworker() < 0) {
  996. log_warn(LD_EXIT,"Spawn failed. Will try again later.");
  997. return -1;
  998. }
  999. num_dnsworkers++;
  1000. }
  1001. while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) {
  1002. /* too many idle? */
  1003. /* cull excess workers */
  1004. log_info(LD_EXIT,"%d of %d dnsworkers are idle. Killing one.",
  1005. num_dnsworkers-num_dnsworkers_busy, num_dnsworkers);
  1006. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
  1007. DNSWORKER_STATE_IDLE);
  1008. tor_assert(dnsconn);
  1009. connection_mark_for_close(dnsconn);
  1010. num_dnsworkers--;
  1011. }
  1012. return 0;
  1013. }
  1014. #else /* !USE_EVENTDNS */
  1015. static int
  1016. eventdns_err_is_transient(int err)
  1017. {
  1018. switch (err)
  1019. {
  1020. case DNS_ERR_SERVERFAILED:
  1021. case DNS_ERR_TRUNCATED:
  1022. case DNS_ERR_TIMEOUT:
  1023. return 1;
  1024. default:
  1025. return 0;
  1026. }
  1027. }
  1028. void
  1029. dnsworkers_rotate(void)
  1030. {
  1031. }
  1032. int
  1033. connection_dns_finished_flushing(connection_t *conn)
  1034. {
  1035. (void)conn;
  1036. tor_assert(0);
  1037. return 0;
  1038. }
  1039. int
  1040. connection_dns_process_inbuf(connection_t *conn)
  1041. {
  1042. (void)conn;
  1043. tor_assert(0);
  1044. return 0;
  1045. }
  1046. int
  1047. connection_dns_reached_eof(connection_t *conn)
  1048. {
  1049. (void)conn;
  1050. tor_assert(0);
  1051. return 0;
  1052. }
  1053. static int nameservers_configured = 0;
  1054. static void
  1055. configure_nameservers(void)
  1056. {
  1057. or_options_t *options;
  1058. if (nameservers_configured)
  1059. return;
  1060. options = get_options();
  1061. eventdns_set_log_fn(eventdns_log_cb);
  1062. if (options->Nameservers && smartlist_len(options->Nameservers)) {
  1063. log_info(LD_EXIT, "Configuring nameservers from Tor configuration");
  1064. SMARTLIST_FOREACH(options->Nameservers, const char *, ip,
  1065. {
  1066. struct in_addr in;
  1067. if (tor_inet_aton(ip, &in)) {
  1068. log_info(LD_EXIT, "Adding nameserver '%s'", ip);
  1069. eventdns_nameserver_add(in.s_addr);
  1070. }
  1071. });
  1072. } else {
  1073. #ifdef MS_WINDOWS
  1074. eventdns_config_windows_nameservers();
  1075. #else
  1076. log_info(LD_EXIT, "Parsing /etc/resolv.conf");
  1077. eventdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS|DNS_OPTION_MISC,
  1078. "/etc/resolv.conf");
  1079. #endif
  1080. }
  1081. nameservers_configured = 1;
  1082. }
  1083. static void
  1084. eventdns_callback(int result, char type, int count, int ttl, void *addresses,
  1085. void *arg)
  1086. {
  1087. char *string_address = arg;
  1088. int status = DNS_RESOLVE_FAILED_PERMANENT;
  1089. uint32_t addr = 0;
  1090. if (result == DNS_ERR_NONE) {
  1091. if (type == DNS_IPv4_A && count) {
  1092. char answer_buf[INET_NTOA_BUF_LEN+1];
  1093. struct in_addr in;
  1094. uint32_t *addrs = addresses;
  1095. in.s_addr = addrs[0];
  1096. addr = ntohl(addrs[0]);
  1097. status = DNS_RESOLVE_SUCCEEDED;
  1098. tor_inet_ntoa(&in, answer_buf, sizeof(answer_buf));
  1099. log_debug(LD_EXIT, "eventdns said that %s resolves to %s",
  1100. escaped_safe_str(string_address),
  1101. escaped_safe_str(answer_buf));
  1102. } else if (count) {
  1103. log_warn(LD_EXIT, "eventdns returned only non-IPv4 answers for %s.",
  1104. escaped_safe_str(string_address));
  1105. } else {
  1106. log_warn(LD_BUG, "eventdns returned no addresses or error for %s!",
  1107. escaped_safe_str(string_address));
  1108. }
  1109. } else {
  1110. if (eventdns_err_is_transient(result))
  1111. status = DNS_RESOLVE_FAILED_TRANSIENT;
  1112. }
  1113. dns_found_answer(string_address, addr, status, ttl);
  1114. tor_free(string_address);
  1115. }
  1116. static int
  1117. launch_resolve(edge_connection_t *exitconn)
  1118. {
  1119. char *addr = tor_strdup(exitconn->_base.address);
  1120. int r;
  1121. if (!nameservers_configured)
  1122. configure_nameservers();
  1123. log_info(LD_EXIT, "Launching eventdns request for %s",
  1124. escaped_safe_str(exitconn->_base.address));
  1125. r = eventdns_resolve(exitconn->_base.address, DNS_QUERY_NO_SEARCH,
  1126. eventdns_callback, addr);
  1127. if (r) {
  1128. log_warn(LD_EXIT, "eventdns rejected address %s: error %d.",
  1129. escaped_safe_str(addr), r);
  1130. if (exitconn->_base.purpose == EXIT_PURPOSE_RESOLVE) {
  1131. if (eventdns_err_is_transient(r))
  1132. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
  1133. else {
  1134. exitconn->address_ttl = DEFAULT_DNS_TTL;
  1135. send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
  1136. }
  1137. }
  1138. dns_cancel_pending_resolve(addr);/* also sends end and frees */
  1139. tor_free(addr);
  1140. }
  1141. return r ? -1 : 0;
  1142. }
  1143. #endif /* USE_EVENTDNS */
  1144. static void
  1145. assert_resolve_ok(cached_resolve_t *resolve)
  1146. {
  1147. tor_assert(resolve);
  1148. tor_assert(resolve->magic == CACHED_RESOLVE_MAGIC);
  1149. tor_assert(strlen(resolve->address) < MAX_ADDRESSLEN);
  1150. tor_assert(tor_strisnonupper(resolve->address));
  1151. if (resolve->state != CACHE_STATE_PENDING) {
  1152. tor_assert(!resolve->pending_connections);
  1153. }
  1154. if (resolve->state == CACHE_STATE_PENDING ||
  1155. resolve->state == CACHE_STATE_DONE) {
  1156. tor_assert(!resolve->ttl);
  1157. tor_assert(!resolve->addr);
  1158. }
  1159. }
  1160. static void
  1161. assert_cache_ok(void)
  1162. {
  1163. cached_resolve_t **resolve;
  1164. int bad_rep = _cache_map_HT_REP_IS_BAD(&cache_root);
  1165. if (bad_rep) {
  1166. log_err(LD_BUG, "Bad rep type %d on dns cache hash table", bad_rep);
  1167. tor_assert(!bad_rep);
  1168. }
  1169. HT_FOREACH(resolve, cache_map, &cache_root) {
  1170. assert_resolve_ok(*resolve);
  1171. tor_assert((*resolve)->state != CACHE_STATE_DONE);
  1172. }
  1173. if (!cached_resolve_pqueue)
  1174. return;
  1175. smartlist_pqueue_assert_ok(cached_resolve_pqueue,
  1176. _compare_cached_resolves_by_expiry);
  1177. }