dns.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. /* Copyright 2003 Roger Dingledine. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file dns.c
  6. * \brief Resolve hostnames in separate processes.
  7. **/
  8. /* See http://elvin.dstc.com/ListArchive/elvin-dev/archive/2001/09/msg00027.html
  9. * for some approaches to asynchronous dns. We will want to switch once one of
  10. * them becomes more commonly available.
  11. */
  12. #include "or.h"
  13. #include "tree.h"
  14. extern or_options_t options; /* command-line and config-file options */
  15. /** Longest hostname we're willing to resolve. */
  16. #define MAX_ADDRESSLEN 256
  17. /** Maximum DNS processes to spawn. */
  18. #define MAX_DNSWORKERS 50
  19. /** Minimum DNS processes to spawn. */
  20. #define MIN_DNSWORKERS 3
  21. /** If more than this many processes are idle, shut down the extras. */
  22. #define MAX_IDLE_DNSWORKERS 10
  23. /** Possible outcomes from hostname lookup: permanent failure,
  24. * transient (retryable) failure, and success. */
  25. #define DNS_RESOLVE_FAILED_TRANSIENT 1
  26. #define DNS_RESOLVE_FAILED_PERMANENT 2
  27. #define DNS_RESOLVE_SUCCEEDED 3
  28. /** How many dnsworkers we have running right now. */
  29. int num_dnsworkers=0;
  30. /** How many of the running dnsworkers have an assigned task right now. */
  31. int num_dnsworkers_busy=0;
  32. /** Linked list of connections waiting for a DNS answer. */
  33. struct pending_connection_t {
  34. struct connection_t *conn;
  35. struct pending_connection_t *next;
  36. };
  37. /** A DNS request: possibly completed, possibly pending; cached_resolve
  38. * structs are stored at the OR side in a splay tree, and as a linked
  39. * list from oldest to newest.
  40. */
  41. struct cached_resolve {
  42. SPLAY_ENTRY(cached_resolve) node;
  43. char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
  44. uint32_t addr; /**< IPv4 addr for <b>address</b>. */
  45. char state; /**< 0 is pending; 1 means answer is valid; 2 means resolve failed. */
  46. #define CACHE_STATE_PENDING 0
  47. #define CACHE_STATE_VALID 1
  48. #define CACHE_STATE_FAILED 2
  49. uint32_t expire; /**< Remove items from cache after this time. */
  50. struct pending_connection_t *pending_connections;
  51. struct cached_resolve *next;
  52. };
  53. static void purge_expired_resolves(uint32_t now);
  54. static int assign_to_dnsworker(connection_t *exitconn);
  55. static void dns_purge_resolve(struct cached_resolve *resolve);
  56. static void dns_found_answer(char *address, uint32_t addr, char outcome);
  57. int dnsworker_main(void *data);
  58. static int spawn_dnsworker(void);
  59. static void spawn_enough_dnsworkers(void);
  60. /** Splay tree of cached_resolve objects. */
  61. static SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
  62. /** Function to compare hashed resolves on their addresses; used to
  63. * implement splay trees. */
  64. static int compare_cached_resolves(struct cached_resolve *a,
  65. struct cached_resolve *b) {
  66. /* make this smarter one day? */
  67. return strncasecmp(a->address, b->address, MAX_ADDRESSLEN);
  68. }
  69. SPLAY_PROTOTYPE(cache_tree, cached_resolve, node, compare_cached_resolves);
  70. SPLAY_GENERATE(cache_tree, cached_resolve, node, compare_cached_resolves);
  71. /** Initialize the DNS cache. */
  72. static void init_cache_tree(void) {
  73. SPLAY_INIT(&cache_root);
  74. }
  75. /** Initialize the DNS subsystem; called by the OR process. */
  76. void dns_init(void) {
  77. init_cache_tree();
  78. spawn_enough_dnsworkers();
  79. }
  80. /** Linked list of resolved addresses, oldest to newest. */
  81. static struct cached_resolve *oldest_cached_resolve = NULL;
  82. static struct cached_resolve *newest_cached_resolve = NULL;
  83. /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
  84. * from the cache. */
  85. static void purge_expired_resolves(uint32_t now) {
  86. struct cached_resolve *resolve;
  87. /* this is fast because the linked list
  88. * oldest_cached_resolve is ordered by when they came in.
  89. */
  90. while(oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
  91. resolve = oldest_cached_resolve;
  92. log(LOG_DEBUG,"Forgetting old cached resolve (expires %lu)", (unsigned long)resolve->expire);
  93. if(resolve->state == CACHE_STATE_PENDING) {
  94. log_fn(LOG_WARN,"Expiring a dns resolve that's still pending. Forgot to cull it?");
  95. /* XXX if resolve->pending_connections is used, then we're probably
  96. * introducing bugs by closing resolve without notifying those streams.
  97. */
  98. }
  99. oldest_cached_resolve = resolve->next;
  100. if(!oldest_cached_resolve) /* if there are no more, */
  101. newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
  102. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  103. tor_free(resolve);
  104. }
  105. }
  106. /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
  107. * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
  108. * If resolve failed, return -1.
  109. *
  110. * Else, if seen before and pending, add conn to the pending list,
  111. * and return 0.
  112. *
  113. * Else, if not seen before, add conn to pending list, hand to
  114. * dns farm, and return 0.
  115. */
  116. int dns_resolve(connection_t *exitconn) {
  117. struct cached_resolve *resolve;
  118. struct cached_resolve search;
  119. struct pending_connection_t *pending_connection;
  120. struct in_addr in;
  121. uint32_t now = time(NULL);
  122. assert_connection_ok(exitconn, 0);
  123. /* first check if exitconn->address is an IP. If so, we already
  124. * know the answer. */
  125. if (tor_inet_aton(exitconn->address, &in) != 0) {
  126. exitconn->addr = ntohl(in.s_addr);
  127. return 1;
  128. }
  129. /* then take this opportunity to see if there are any expired
  130. * resolves in the tree. */
  131. purge_expired_resolves(now);
  132. /* now check the tree to see if 'address' is already there. */
  133. strncpy(search.address, exitconn->address, MAX_ADDRESSLEN);
  134. search.address[MAX_ADDRESSLEN-1] = 0;
  135. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  136. if(resolve) { /* already there */
  137. switch(resolve->state) {
  138. case CACHE_STATE_PENDING:
  139. /* add us to the pending list */
  140. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  141. pending_connection->conn = exitconn;
  142. pending_connection->next = resolve->pending_connections;
  143. resolve->pending_connections = pending_connection;
  144. log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
  145. exitconn->s, exitconn->address);
  146. exitconn->state = EXIT_CONN_STATE_RESOLVING;
  147. return 0;
  148. case CACHE_STATE_VALID:
  149. exitconn->addr = resolve->addr;
  150. log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
  151. exitconn->s, exitconn->address);
  152. return 1;
  153. case CACHE_STATE_FAILED:
  154. return -1;
  155. }
  156. tor_assert(0);
  157. }
  158. /* not there, need to add it */
  159. resolve = tor_malloc_zero(sizeof(struct cached_resolve));
  160. resolve->state = CACHE_STATE_PENDING;
  161. resolve->expire = now + MAX_DNS_ENTRY_AGE;
  162. strncpy(resolve->address, exitconn->address, MAX_ADDRESSLEN);
  163. resolve->address[MAX_ADDRESSLEN-1] = 0;
  164. /* add us to the pending list */
  165. pending_connection = tor_malloc(sizeof(struct pending_connection_t));
  166. pending_connection->conn = exitconn;
  167. pending_connection->next = NULL;
  168. resolve->pending_connections = pending_connection;
  169. exitconn->state = EXIT_CONN_STATE_RESOLVING;
  170. /* add us to the linked list of resolves */
  171. if (!oldest_cached_resolve) {
  172. oldest_cached_resolve = resolve;
  173. } else {
  174. newest_cached_resolve->next = resolve;
  175. }
  176. newest_cached_resolve = resolve;
  177. SPLAY_INSERT(cache_tree, &cache_root, resolve);
  178. return assign_to_dnsworker(exitconn);
  179. }
  180. /** Find or spawn a dns worker process to handle resolving
  181. * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
  182. */
  183. static int assign_to_dnsworker(connection_t *exitconn) {
  184. connection_t *dnsconn;
  185. unsigned char len;
  186. tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
  187. spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
  188. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  189. if(!dnsconn) {
  190. log_fn(LOG_WARN,"no idle dns workers. Failing.");
  191. dns_cancel_pending_resolve(exitconn->address);
  192. return -1;
  193. }
  194. log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
  195. exitconn->s, exitconn->address, dnsconn->s);
  196. tor_free(dnsconn->address);
  197. dnsconn->address = tor_strdup(exitconn->address);
  198. dnsconn->state = DNSWORKER_STATE_BUSY;
  199. num_dnsworkers_busy++;
  200. len = strlen(dnsconn->address);
  201. connection_write_to_buf(&len, 1, dnsconn);
  202. connection_write_to_buf(dnsconn->address, len, dnsconn);
  203. // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
  204. return 0;
  205. }
  206. /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
  207. */
  208. void connection_dns_remove(connection_t *conn)
  209. {
  210. struct pending_connection_t *pend, *victim;
  211. struct cached_resolve search;
  212. struct cached_resolve *resolve;
  213. strncpy(search.address, conn->address, MAX_ADDRESSLEN);
  214. search.address[MAX_ADDRESSLEN-1] = 0;
  215. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  216. if(!resolve) {
  217. log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", conn->address);
  218. return;
  219. }
  220. tor_assert(resolve->pending_connections);
  221. assert_connection_ok(conn,0);
  222. pend = resolve->pending_connections;
  223. if(pend->conn == conn) {
  224. resolve->pending_connections = pend->next;
  225. tor_free(pend);
  226. log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
  227. conn->s, conn->address);
  228. return;
  229. } else {
  230. for( ; pend->next; pend = pend->next) {
  231. if(pend->next->conn == conn) {
  232. victim = pend->next;
  233. pend->next = victim->next;
  234. tor_free(victim);
  235. log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
  236. conn->s, conn->address);
  237. return; /* more are pending */
  238. }
  239. }
  240. tor_assert(0); /* not reachable unless onlyconn not in pending list */
  241. }
  242. }
  243. /** Log an error and abort if conn is waiting for a DNS resolve.
  244. */
  245. void assert_connection_edge_not_dns_pending(connection_t *conn) {
  246. struct pending_connection_t *pend;
  247. struct cached_resolve *resolve;
  248. SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
  249. for(pend = resolve->pending_connections;
  250. pend;
  251. pend = pend->next) {
  252. tor_assert(pend->conn != conn);
  253. }
  254. }
  255. }
  256. /** Log an error and abort if any connection waiting for a DNS resolve is
  257. * corrupted. */
  258. void assert_all_pending_dns_resolves_ok(void) {
  259. struct pending_connection_t *pend;
  260. struct cached_resolve *resolve;
  261. SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
  262. for(pend = resolve->pending_connections;
  263. pend;
  264. pend = pend->next) {
  265. assert_connection_ok(pend->conn, 0);
  266. }
  267. }
  268. }
  269. /** Mark all connections waiting for <b>address</b> for close. Then cancel
  270. * the resolve for <b>address</b> itself, and remove any cached results for
  271. * <b>address</b> from the cache.
  272. */
  273. void dns_cancel_pending_resolve(char *address) {
  274. struct pending_connection_t *pend;
  275. struct cached_resolve search;
  276. struct cached_resolve *resolve;
  277. connection_t *pendconn;
  278. strncpy(search.address, address, MAX_ADDRESSLEN);
  279. search.address[MAX_ADDRESSLEN-1] = 0;
  280. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  281. if(!resolve) {
  282. log_fn(LOG_WARN,"Address '%s' is not pending. Dropping.", address);
  283. return;
  284. }
  285. tor_assert(resolve->pending_connections);
  286. /* mark all pending connections to fail */
  287. log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
  288. address);
  289. while(resolve->pending_connections) {
  290. pend = resolve->pending_connections;
  291. /* So that mark_for_close doesn't double-remove the connection. */
  292. pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  293. pendconn = pend->conn; /* don't pass complex things to the
  294. connection_mark_for_close macro */
  295. connection_mark_for_close(pendconn, END_STREAM_REASON_MISC);
  296. resolve->pending_connections = pend->next;
  297. tor_free(pend);
  298. }
  299. dns_purge_resolve(resolve);
  300. }
  301. /** Remove <b>resolve</b> from the cache.
  302. */
  303. static void dns_purge_resolve(struct cached_resolve *resolve) {
  304. struct cached_resolve *tmp;
  305. /* remove resolve from the linked list */
  306. if(resolve == oldest_cached_resolve) {
  307. oldest_cached_resolve = resolve->next;
  308. if(oldest_cached_resolve == NULL)
  309. newest_cached_resolve = NULL;
  310. } else {
  311. /* FFFF make it a doubly linked list if this becomes too slow */
  312. for(tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
  313. tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
  314. tmp->next = resolve->next; /* unlink it */
  315. if(newest_cached_resolve == resolve)
  316. newest_cached_resolve = tmp;
  317. }
  318. /* remove resolve from the tree */
  319. SPLAY_REMOVE(cache_tree, &cache_root, resolve);
  320. tor_free(resolve);
  321. }
  322. /** Called on the OR side when a DNS worker tells us the outcome of a DNS
  323. * resolve: tell all pending connections about the result of the lookup, and
  324. * cache the value. (<b>address</b> is a NUL-terminated string containing the
  325. * address to look up; <b>addr</b> is an IPv4 address in host order;
  326. * <b>outcome</b> is one of
  327. * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  328. */
  329. static void dns_found_answer(char *address, uint32_t addr, char outcome) {
  330. struct pending_connection_t *pend;
  331. struct cached_resolve search;
  332. struct cached_resolve *resolve;
  333. connection_t *pendconn;
  334. circuit_t *circ;
  335. strncpy(search.address, address, MAX_ADDRESSLEN);
  336. search.address[MAX_ADDRESSLEN-1] = 0;
  337. resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
  338. if(!resolve) {
  339. log_fn(LOG_INFO,"Resolved unasked address '%s'? Dropping.", address);
  340. /* XXX Why drop? Just because we don't care now doesn't mean we shouldn't
  341. * XXX cache the result for later. */
  342. return;
  343. }
  344. if (resolve->state != CACHE_STATE_PENDING) {
  345. /* XXXX Maybe update addr? or check addr for consistency? Or let
  346. * VALID replace FAILED? */
  347. log_fn(LOG_WARN, "Resolved '%s' which was already resolved; ignoring",
  348. address);
  349. tor_assert(resolve->pending_connections == NULL);
  350. return;
  351. }
  352. /* Removed this assertion: in fact, we'll sometimes get a double answer
  353. * to the same question. This can happen when we ask one worker to resolve
  354. * X.Y.Z., then we cancel the request, and then we ask another worker to
  355. * resolve X.Y.Z. */
  356. /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
  357. resolve->addr = ntohl(addr);
  358. if(outcome == DNS_RESOLVE_SUCCEEDED)
  359. resolve->state = CACHE_STATE_VALID;
  360. else
  361. resolve->state = CACHE_STATE_FAILED;
  362. while(resolve->pending_connections) {
  363. pend = resolve->pending_connections;
  364. assert_connection_ok(pend->conn,time(NULL));
  365. pend->conn->addr = resolve->addr;
  366. if(resolve->state == CACHE_STATE_FAILED) {
  367. pendconn = pend->conn; /* don't pass complex things to the
  368. connection_mark_for_close macro */
  369. /* prevent double-remove. */
  370. pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
  371. connection_mark_for_close(pendconn, END_STREAM_REASON_RESOLVEFAILED);
  372. connection_free(pendconn);
  373. } else {
  374. /* prevent double-remove. */
  375. pend->conn->state = EXIT_CONN_STATE_CONNECTING;
  376. circ = circuit_get_by_conn(pend->conn);
  377. assert(circ);
  378. /* unlink pend->conn from resolving_streams, */
  379. circuit_detach_stream(circ, pend->conn);
  380. /* and link it to n_streams */
  381. pend->conn->next_stream = circ->n_streams;
  382. circ->n_streams = pend->conn;
  383. connection_exit_connect(pend->conn);
  384. }
  385. resolve->pending_connections = pend->next;
  386. tor_free(pend);
  387. }
  388. if(outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
  389. dns_purge_resolve(resolve);
  390. }
  391. }
  392. /******************************************************************/
  393. /*
  394. * Connection between OR and dnsworker
  395. */
  396. /** Write handler: called when we've pushed a request to a dnsworker. */
  397. int connection_dns_finished_flushing(connection_t *conn) {
  398. tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  399. connection_stop_writing(conn);
  400. return 0;
  401. }
  402. /** Read handler: called when we get data from a dnsworker. If the
  403. * connection is closed, mark the dnsworker as dead. Otherwise, see
  404. * if we have a complete answer. If so, call dns_found_answer on the
  405. * result. If not, wait. Returns 0. */
  406. int connection_dns_process_inbuf(connection_t *conn) {
  407. char success;
  408. uint32_t addr;
  409. tor_assert(conn && conn->type == CONN_TYPE_DNSWORKER);
  410. if(conn->inbuf_reached_eof) {
  411. log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
  412. if(conn->state == DNSWORKER_STATE_BUSY) {
  413. dns_cancel_pending_resolve(conn->address);
  414. num_dnsworkers_busy--;
  415. }
  416. num_dnsworkers--;
  417. connection_mark_for_close(conn,0);
  418. return 0;
  419. }
  420. tor_assert(conn->state == DNSWORKER_STATE_BUSY);
  421. if(buf_datalen(conn->inbuf) < 5) /* entire answer available? */
  422. return 0; /* not yet */
  423. tor_assert(buf_datalen(conn->inbuf) == 5);
  424. connection_fetch_from_buf(&success,1,conn);
  425. connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
  426. log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
  427. conn->s, conn->address);
  428. tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
  429. tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
  430. dns_found_answer(conn->address, addr, success);
  431. tor_free(conn->address);
  432. conn->address = tor_strdup("<idle>");
  433. conn->state = DNSWORKER_STATE_IDLE;
  434. num_dnsworkers_busy--;
  435. return 0;
  436. }
  437. /** Implementation for DNS workers; this code runs in a separate
  438. * execution context. It takes as its argument an fdarray as returned
  439. * by socketpair(), and communicates via fdarray[1]. The protocol is
  440. * as follows:
  441. * - The OR says:
  442. * - ADDRESSLEN [1 byte]
  443. * - ADDRESS [ADDRESSLEN bytes]
  444. * - The DNS worker does the lookup, and replies:
  445. * - OUTCOME [1 byte]
  446. * - IP [4 bytes]
  447. *
  448. * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
  449. * IP is in host order.
  450. *
  451. * The dnsworker runs indefinitely, until its connection is closed or an error
  452. * occurs.
  453. */
  454. int dnsworker_main(void *data) {
  455. char address[MAX_ADDRESSLEN];
  456. unsigned char address_len;
  457. char answer[5];
  458. uint32_t ip;
  459. int *fdarray = data;
  460. int fd;
  461. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
  462. fd = fdarray[1]; /* this side is ours */
  463. #ifndef MS_WINDOWS
  464. connection_free_all(); /* so the child doesn't hold the parent's fd's open */
  465. #endif
  466. for(;;) {
  467. if(recv(fd, &address_len, 1, 0) != 1) {
  468. log_fn(LOG_INFO,"dnsworker exiting because tor process died.");
  469. spawn_exit();
  470. }
  471. tor_assert(address_len > 0);
  472. if(read_all(fd, address, address_len, 1) != address_len) {
  473. log_fn(LOG_ERR,"read hostname failed. Child exiting.");
  474. spawn_exit();
  475. }
  476. address[address_len] = 0; /* null terminate it */
  477. switch (tor_lookup_hostname(address, &ip)) {
  478. case 1:
  479. log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
  480. answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
  481. break;
  482. case -1:
  483. log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
  484. answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
  485. break;
  486. case 0:
  487. log_fn(LOG_INFO,"Resolved address '%s'.",address);
  488. answer[0] = DNS_RESOLVE_SUCCEEDED;
  489. break;
  490. }
  491. set_uint32(answer+1, ip);
  492. if(write_all(fd, answer, 5, 1) != 5) {
  493. log_fn(LOG_ERR,"writing answer failed. Child exiting.");
  494. spawn_exit();
  495. }
  496. }
  497. return 0; /* windows wants this function to return an int */
  498. }
  499. /** Launch a new DNS worker; return 0 on success, -1 on failure.
  500. */
  501. static int spawn_dnsworker(void) {
  502. int fd[2];
  503. connection_t *conn;
  504. if(tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0) {
  505. log(LOG_ERR, "Couldn't construct socketpair: %s",
  506. tor_socket_strerror(tor_socket_errno(-1)));
  507. exit(1);
  508. }
  509. spawn_func(dnsworker_main, (void*)fd);
  510. log_fn(LOG_DEBUG,"just spawned a worker.");
  511. tor_close_socket(fd[1]); /* we don't need the worker's side of the pipe */
  512. conn = connection_new(CONN_TYPE_DNSWORKER);
  513. set_socket_nonblocking(fd[0]);
  514. /* set up conn so it's got all the data we need to remember */
  515. conn->s = fd[0];
  516. conn->address = tor_strdup("<unused>");
  517. if(connection_add(conn) < 0) { /* no space, forget it */
  518. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  519. connection_free(conn); /* this closes fd[0] */
  520. return -1;
  521. }
  522. conn->state = DNSWORKER_STATE_IDLE;
  523. connection_start_reading(conn);
  524. return 0; /* success */
  525. }
  526. /** If we have too many or too few DNS workers, spawn or kill some.
  527. */
  528. static void spawn_enough_dnsworkers(void) {
  529. int num_dnsworkers_needed; /* aim to have 1 more than needed,
  530. * but no less than min and no more than max */
  531. connection_t *dnsconn;
  532. /* XXX This may not be the best strategy. Maybe we should queue pending
  533. * requests until the old ones finish or time out: otherwise, if
  534. * the connection requests come fast enough, we never get any DNS done. -NM
  535. * XXX But if we queue them, then the adversary can pile even more
  536. * queries onto us, blocking legitimate requests for even longer.
  537. * Maybe we should compromise and only kill if it's been at it for
  538. * more than, e.g., 2 seconds. -RD
  539. */
  540. if(num_dnsworkers_busy == MAX_DNSWORKERS) {
  541. /* We always want at least one worker idle.
  542. * So find the oldest busy worker and kill it.
  543. */
  544. dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
  545. DNSWORKER_STATE_BUSY);
  546. tor_assert(dnsconn);
  547. log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
  548. MAX_DNSWORKERS);
  549. connection_mark_for_close(dnsconn,0);
  550. num_dnsworkers_busy--;
  551. num_dnsworkers--;
  552. }
  553. if(num_dnsworkers_busy >= MIN_DNSWORKERS)
  554. num_dnsworkers_needed = num_dnsworkers_busy+1;
  555. else
  556. num_dnsworkers_needed = MIN_DNSWORKERS;
  557. while(num_dnsworkers < num_dnsworkers_needed) {
  558. if(spawn_dnsworker() < 0) {
  559. log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
  560. return;
  561. }
  562. num_dnsworkers++;
  563. }
  564. while(num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
  565. /* cull excess workers */
  566. log_fn(LOG_WARN,"%d of %d dnsworkers are idle. Killing one.",
  567. num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
  568. dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
  569. tor_assert(dnsconn);
  570. connection_mark_for_close(dnsconn,0);
  571. num_dnsworkers--;
  572. }
  573. }
  574. /*
  575. Local Variables:
  576. mode:c
  577. indent-tabs-mode:nil
  578. c-basic-offset:2
  579. End:
  580. */