dns.c 22 KB

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