dns.c 41 KB

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