dns.c 43 KB

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