Forward port changelog
[tor.git] / src / or / dns.c
blob3e862ce69244eeeaea2d2413854aa108be6ed96b
1 /* Copyright 2003-2004 Roger Dingledine.
2 * Copyright 2004 Roger Dingledine, Nick Mathewson. */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char dns_c_id[] = "$Id$";
7 /**
8 * \file dns.c
9 * \brief Resolve hostnames in separate processes.
10 **/
12 /* See http://elvin.dstc.com/ListArchive/elvin-dev/archive/2001/09/msg00027.html
13 * for some approaches to asynchronous dns. We will want to switch once one of
14 * them becomes more commonly available.
17 #include "or.h"
18 #include "tree.h"
20 /** Longest hostname we're willing to resolve. */
21 #define MAX_ADDRESSLEN 256
23 /** Maximum DNS processes to spawn. */
24 #define MAX_DNSWORKERS 100
25 /** Minimum DNS processes to spawn. */
26 #define MIN_DNSWORKERS 3
28 /** If more than this many processes are idle, shut down the extras. */
29 #define MAX_IDLE_DNSWORKERS 10
31 /** Possible outcomes from hostname lookup: permanent failure,
32 * transient (retryable) failure, and success. */
33 #define DNS_RESOLVE_FAILED_TRANSIENT 1
34 #define DNS_RESOLVE_FAILED_PERMANENT 2
35 #define DNS_RESOLVE_SUCCEEDED 3
37 /** How many dnsworkers we have running right now. */
38 static int num_dnsworkers=0;
39 /** How many of the running dnsworkers have an assigned task right now. */
40 static int num_dnsworkers_busy=0;
41 /** When did we last rotate the dnsworkers? */
42 static time_t last_rotation_time=0;
44 /** Linked list of connections waiting for a DNS answer. */
45 struct pending_connection_t {
46 struct connection_t *conn;
47 struct pending_connection_t *next;
50 /** A DNS request: possibly completed, possibly pending; cached_resolve
51 * structs are stored at the OR side in a splay tree, and as a linked
52 * list from oldest to newest.
54 struct cached_resolve {
55 SPLAY_ENTRY(cached_resolve) node;
56 char address[MAX_ADDRESSLEN]; /**< The hostname to be resolved. */
57 uint32_t addr; /**< IPv4 addr for <b>address</b>. */
58 char state; /**< 0 is pending; 1 means answer is valid; 2 means resolve failed. */
59 #define CACHE_STATE_PENDING 0
60 #define CACHE_STATE_VALID 1
61 #define CACHE_STATE_FAILED 2
62 uint32_t expire; /**< Remove items from cache after this time. */
63 struct pending_connection_t *pending_connections;
64 struct cached_resolve *next;
67 static void purge_expired_resolves(uint32_t now);
68 static int assign_to_dnsworker(connection_t *exitconn);
69 static void dns_purge_resolve(struct cached_resolve *resolve);
70 static void dns_found_answer(char *address, uint32_t addr, char outcome);
71 static int dnsworker_main(void *data);
72 static int spawn_dnsworker(void);
73 static void spawn_enough_dnsworkers(void);
74 static void send_resolved_cell(connection_t *conn, uint8_t answer_type);
76 /** Splay tree of cached_resolve objects. */
77 static SPLAY_HEAD(cache_tree, cached_resolve) cache_root;
79 /** Function to compare hashed resolves on their addresses; used to
80 * implement splay trees. */
81 static int compare_cached_resolves(struct cached_resolve *a,
82 struct cached_resolve *b) {
83 /* make this smarter one day? */
84 return strncasecmp(a->address, b->address, MAX_ADDRESSLEN);
87 SPLAY_PROTOTYPE(cache_tree, cached_resolve, node, compare_cached_resolves);
88 SPLAY_GENERATE(cache_tree, cached_resolve, node, compare_cached_resolves);
90 /** Initialize the DNS cache. */
91 static void init_cache_tree(void) {
92 SPLAY_INIT(&cache_root);
95 /** Initialize the DNS subsystem; called by the OR process. */
96 void dns_init(void) {
97 init_cache_tree();
98 last_rotation_time=time(NULL);
99 spawn_enough_dnsworkers();
102 /** Linked list of resolved addresses, oldest to newest. */
103 static struct cached_resolve *oldest_cached_resolve = NULL;
104 static struct cached_resolve *newest_cached_resolve = NULL;
106 /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
107 * from the cache. */
108 static void purge_expired_resolves(uint32_t now) {
109 struct cached_resolve *resolve;
110 struct pending_connection_t *pend;
111 connection_t *pendconn;
113 /* this is fast because the linked list
114 * oldest_cached_resolve is ordered by when they came in.
116 while (oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
117 resolve = oldest_cached_resolve;
118 log(LOG_DEBUG,"Forgetting old cached resolve (expires %lu)", (unsigned long)resolve->expire);
119 if (resolve->state == CACHE_STATE_PENDING) {
120 log_fn(LOG_WARN,"Bug: Expiring a dns resolve that's still pending. Forgot to cull it?");
121 #ifdef TOR_FRAGILE
122 tor_assert(0);
123 #endif
125 if (resolve->pending_connections) {
126 log_fn(LOG_WARN, "Closing pending connections on expiring DNS resolve!");
127 #ifdef TOR_FRAGILE
128 tor_assert(0);
129 #endif
130 while (resolve->pending_connections) {
131 pend = resolve->pending_connections;
132 resolve->pending_connections = pend->next;
133 /* Connections should only be pending if they have no socket. */
134 tor_assert(pend->conn->s == -1);
135 pendconn = pend->conn;
136 connection_edge_end(pendconn, END_STREAM_REASON_MISC,
137 pendconn->cpath_layer);
138 circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
139 connection_free(pendconn);
140 tor_free(pend);
143 oldest_cached_resolve = resolve->next;
144 if (!oldest_cached_resolve) /* if there are no more, */
145 newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
146 SPLAY_REMOVE(cache_tree, &cache_root, resolve);
147 tor_free(resolve);
151 static void send_resolved_cell(connection_t *conn, uint8_t answer_type)
153 char buf[RELAY_PAYLOAD_SIZE];
154 size_t buflen;
156 buf[0] = answer_type;
158 switch (answer_type)
160 case RESOLVED_TYPE_IPV4:
161 buf[1] = 4;
162 set_uint32(buf+2, htonl(conn->addr));
163 buflen = 6;
164 break;
165 case RESOLVED_TYPE_ERROR_TRANSIENT:
166 case RESOLVED_TYPE_ERROR:
167 buf[1] = 24; /* length of "error resolving hostname" */
168 strlcpy(buf+2, "error resolving hostname", sizeof(buf)-2);
169 buflen = 26;
170 break;
171 default:
172 tor_assert(0);
174 connection_edge_send_command(conn, circuit_get_by_conn(conn),
175 RELAY_COMMAND_RESOLVED, buf, buflen,
176 conn->cpath_layer);
179 /** Link <b>r</b> into the tree of address-to-result mappings, and add it to
180 * the linked list of resolves-by-age. */
181 static void
182 insert_resolve(struct cached_resolve *r)
184 /* add us to the linked list of resolves */
185 if (!oldest_cached_resolve) {
186 oldest_cached_resolve = r;
187 } else {
188 newest_cached_resolve->next = r;
190 newest_cached_resolve = r;
192 SPLAY_INSERT(cache_tree, &cache_root, r);
195 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
196 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
197 * If resolve failed, return -1.
199 * Else, if seen before and pending, add conn to the pending list,
200 * and return 0.
202 * Else, if not seen before, add conn to pending list, hand to
203 * dns farm, and return 0.
205 int dns_resolve(connection_t *exitconn) {
206 struct cached_resolve *resolve;
207 struct cached_resolve search;
208 struct pending_connection_t *pending_connection;
209 struct in_addr in;
210 uint32_t now = time(NULL);
211 assert_connection_ok(exitconn, 0);
212 tor_assert(exitconn->s == -1);
214 /* first check if exitconn->address is an IP. If so, we already
215 * know the answer. */
216 if (tor_inet_aton(exitconn->address, &in) != 0) {
217 exitconn->addr = ntohl(in.s_addr);
218 return 1;
221 /* then take this opportunity to see if there are any expired
222 * resolves in the tree. */
223 purge_expired_resolves(now);
225 /* now check the tree to see if 'address' is already there. */
226 strlcpy(search.address, exitconn->address, sizeof(search.address));
227 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
228 if (resolve) { /* already there */
229 switch (resolve->state) {
230 case CACHE_STATE_PENDING:
231 /* add us to the pending list */
232 pending_connection = tor_malloc_zero(
233 sizeof(struct pending_connection_t));
234 pending_connection->conn = exitconn;
235 pending_connection->next = resolve->pending_connections;
236 resolve->pending_connections = pending_connection;
237 log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
238 exitconn->s, exitconn->address);
239 exitconn->state = EXIT_CONN_STATE_RESOLVING;
240 return 0;
241 case CACHE_STATE_VALID:
242 exitconn->addr = resolve->addr;
243 log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
244 exitconn->s, exitconn->address);
245 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
246 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
247 return 1;
248 case CACHE_STATE_FAILED:
249 log_fn(LOG_DEBUG,"Connection (fd %d) found cached error for '%s'",
250 exitconn->s, exitconn->address);
251 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
252 send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
253 return -1;
255 tor_assert(0);
257 /* not there, need to add it */
258 resolve = tor_malloc_zero(sizeof(struct cached_resolve));
259 resolve->state = CACHE_STATE_PENDING;
260 resolve->expire = now + MAX_DNS_ENTRY_AGE;
261 strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
263 /* add us to the pending list */
264 pending_connection = tor_malloc_zero(sizeof(struct pending_connection_t));
265 pending_connection->conn = exitconn;
266 resolve->pending_connections = pending_connection;
267 exitconn->state = EXIT_CONN_STATE_RESOLVING;
269 insert_resolve(resolve);
270 return assign_to_dnsworker(exitconn);
273 /** Find or spawn a dns worker process to handle resolving
274 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
276 static int assign_to_dnsworker(connection_t *exitconn) {
277 connection_t *dnsconn;
278 unsigned char len;
280 tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
281 tor_assert(exitconn->s == -1);
283 spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
285 dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
287 if (!dnsconn) {
288 log_fn(LOG_WARN,"no idle dns workers. Failing.");
289 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
290 send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
291 dns_cancel_pending_resolve(exitconn->address); /* also sends end */
292 return -1;
295 log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
296 exitconn->s, exitconn->address, dnsconn->s);
298 tor_free(dnsconn->address);
299 dnsconn->address = tor_strdup(exitconn->address);
300 dnsconn->state = DNSWORKER_STATE_BUSY;
301 num_dnsworkers_busy++;
303 len = strlen(dnsconn->address);
304 connection_write_to_buf(&len, 1, dnsconn);
305 connection_write_to_buf(dnsconn->address, len, dnsconn);
307 // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
308 return 0;
311 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
313 void connection_dns_remove(connection_t *conn)
315 struct pending_connection_t *pend, *victim;
316 struct cached_resolve search;
317 struct cached_resolve *resolve;
319 tor_assert(conn->type == CONN_TYPE_EXIT);
320 tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);
322 strlcpy(search.address, conn->address, sizeof(search.address));
324 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
325 if (!resolve) {
326 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", conn->address);
327 return;
330 tor_assert(resolve->pending_connections);
331 assert_connection_ok(conn,0);
333 pend = resolve->pending_connections;
335 if (pend->conn == conn) {
336 resolve->pending_connections = pend->next;
337 tor_free(pend);
338 log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
339 conn->s, conn->address);
340 return;
341 } else {
342 for ( ; pend->next; pend = pend->next) {
343 if (pend->next->conn == conn) {
344 victim = pend->next;
345 pend->next = victim->next;
346 tor_free(victim);
347 log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
348 conn->s, conn->address);
349 return; /* more are pending */
352 tor_assert(0); /* not reachable unless onlyconn not in pending list */
356 /** Log an error and abort if conn is waiting for a DNS resolve.
358 void assert_connection_edge_not_dns_pending(connection_t *conn) {
359 struct pending_connection_t *pend;
360 struct cached_resolve *resolve;
362 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
363 for (pend = resolve->pending_connections;
364 pend;
365 pend = pend->next) {
366 tor_assert(pend->conn != conn);
371 /** Log an error and abort if any connection waiting for a DNS resolve is
372 * corrupted. */
373 void assert_all_pending_dns_resolves_ok(void) {
374 struct pending_connection_t *pend;
375 struct cached_resolve *resolve;
377 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
378 for (pend = resolve->pending_connections;
379 pend;
380 pend = pend->next) {
381 assert_connection_ok(pend->conn, 0);
382 tor_assert(pend->conn->s == -1);
383 tor_assert(!connection_in_array(pend->conn));
388 /** Mark all connections waiting for <b>address</b> for close. Then cancel
389 * the resolve for <b>address</b> itself, and remove any cached results for
390 * <b>address</b> from the cache.
392 void dns_cancel_pending_resolve(char *address) {
393 struct pending_connection_t *pend;
394 struct cached_resolve search;
395 struct cached_resolve *resolve;
396 connection_t *pendconn;
397 circuit_t *circ;
399 strlcpy(search.address, address, sizeof(search.address));
401 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
402 if (!resolve) {
403 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", address);
404 return;
407 if (!resolve->pending_connections) {
408 /* XXX this should never trigger, but sometimes it does */
409 log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!", address);
410 #ifdef TOR_FRAGILE
411 tor_assert(0);
412 #endif
413 return;
415 tor_assert(resolve->pending_connections);
417 /* mark all pending connections to fail */
418 log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
419 address);
420 while (resolve->pending_connections) {
421 pend = resolve->pending_connections;
422 pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
423 pendconn = pend->conn;
424 tor_assert(pendconn->s == -1);
425 if (!pendconn->marked_for_close) {
426 connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
427 pendconn->cpath_layer);
429 circ = circuit_get_by_conn(pendconn);
430 if (circ)
431 circuit_detach_stream(circ, pendconn);
432 connection_free(pendconn);
433 resolve->pending_connections = pend->next;
434 tor_free(pend);
437 dns_purge_resolve(resolve);
440 /** Remove <b>resolve</b> from the cache.
442 static void dns_purge_resolve(struct cached_resolve *resolve) {
443 struct cached_resolve *tmp;
445 /* remove resolve from the linked list */
446 if (resolve == oldest_cached_resolve) {
447 oldest_cached_resolve = resolve->next;
448 if (oldest_cached_resolve == NULL)
449 newest_cached_resolve = NULL;
450 } else {
451 /* FFFF make it a doubly linked list if this becomes too slow */
452 for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
453 tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
454 tmp->next = resolve->next; /* unlink it */
456 if (newest_cached_resolve == resolve)
457 newest_cached_resolve = tmp;
460 /* remove resolve from the tree */
461 SPLAY_REMOVE(cache_tree, &cache_root, resolve);
463 tor_free(resolve);
466 /** Called on the OR side when a DNS worker tells us the outcome of a DNS
467 * resolve: tell all pending connections about the result of the lookup, and
468 * cache the value. (<b>address</b> is a NUL-terminated string containing the
469 * address to look up; <b>addr</b> is an IPv4 address in host order;
470 * <b>outcome</b> is one of
471 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
473 static void dns_found_answer(char *address, uint32_t addr, char outcome) {
474 struct pending_connection_t *pend;
475 struct cached_resolve search;
476 struct cached_resolve *resolve;
477 connection_t *pendconn;
478 circuit_t *circ;
480 strlcpy(search.address, address, sizeof(search.address));
482 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
483 if (!resolve) {
484 log_fn(LOG_INFO,"Resolved unasked address '%s'; caching anyway.", address);
485 resolve = tor_malloc_zero(sizeof(struct cached_resolve));
486 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
487 CACHE_STATE_VALID : CACHE_STATE_FAILED;
488 resolve->addr = addr;
489 resolve->expire = time(NULL) + MAX_DNS_ENTRY_AGE;
490 insert_resolve(resolve);
491 return;
494 if (resolve->state != CACHE_STATE_PENDING) {
495 /* XXXX Maybe update addr? or check addr for consistency? Or let
496 * VALID replace FAILED? */
497 log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
498 address);
499 tor_assert(resolve->pending_connections == NULL);
500 return;
502 /* Removed this assertion: in fact, we'll sometimes get a double answer
503 * to the same question. This can happen when we ask one worker to resolve
504 * X.Y.Z., then we cancel the request, and then we ask another worker to
505 * resolve X.Y.Z. */
506 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
508 resolve->addr = addr;
509 if (outcome == DNS_RESOLVE_SUCCEEDED)
510 resolve->state = CACHE_STATE_VALID;
511 else
512 resolve->state = CACHE_STATE_FAILED;
514 while (resolve->pending_connections) {
515 pend = resolve->pending_connections;
516 assert_connection_ok(pend->conn,time(NULL));
517 pend->conn->addr = resolve->addr;
518 pendconn = pend->conn; /* don't pass complex things to the
519 connection_mark_for_close macro */
521 if (resolve->state == CACHE_STATE_FAILED) {
522 /* prevent double-remove. */
523 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
524 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
525 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
526 /* This detach must happen after we send the end cell. */
527 circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
528 } else {
529 send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
530 /* This detach must happen after we send the resolved cell. */
531 circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
533 connection_free(pendconn);
534 } else {
535 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
536 /* prevent double-remove. */
537 pend->conn->state = EXIT_CONN_STATE_CONNECTING;
539 circ = circuit_get_by_conn(pend->conn);
540 tor_assert(circ);
541 /* unlink pend->conn from resolving_streams, */
542 circuit_detach_stream(circ, pend->conn);
543 /* and link it to n_streams */
544 pend->conn->next_stream = circ->n_streams;
545 circ->n_streams = pend->conn;
547 connection_exit_connect(pend->conn);
548 } else {
549 /* prevent double-remove. This isn't really an accurate state,
550 * but it does the right thing. */
551 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
552 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
553 circ = circuit_get_by_conn(pendconn);
554 tor_assert(circ);
555 circuit_detach_stream(circ, pendconn);
556 connection_free(pendconn);
559 resolve->pending_connections = pend->next;
560 tor_free(pend);
563 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
564 dns_purge_resolve(resolve);
568 /******************************************************************/
571 * Connection between OR and dnsworker
574 /** Write handler: called when we've pushed a request to a dnsworker. */
575 int connection_dns_finished_flushing(connection_t *conn) {
576 tor_assert(conn);
577 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
578 connection_stop_writing(conn);
579 return 0;
582 int connection_dns_reached_eof(connection_t *conn) {
583 log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
584 if (conn->state == DNSWORKER_STATE_BUSY) {
585 /* don't cancel the resolve here -- it would be cancelled in
586 * connection_about_to_close_connection(), since conn is still
587 * in state BUSY
589 num_dnsworkers_busy--;
591 num_dnsworkers--;
592 connection_mark_for_close(conn);
593 return 0;
596 /** Read handler: called when we get data from a dnsworker. See
597 * if we have a complete answer. If so, call dns_found_answer on the
598 * result. If not, wait. Returns 0. */
599 int connection_dns_process_inbuf(connection_t *conn) {
600 char success;
601 uint32_t addr;
603 tor_assert(conn);
604 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
606 if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
607 log_fn(LOG_WARN,"Bug: read data from an idle dns worker. Please report.");
608 #ifdef TOR_FRAGILE
609 tor_assert(0);
610 #endif
611 return 0;
613 if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
614 return 0; /* not yet */
615 tor_assert(conn->state == DNSWORKER_STATE_BUSY);
616 tor_assert(buf_datalen(conn->inbuf) == 5);
618 connection_fetch_from_buf(&success,1,conn);
619 connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
621 log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
622 conn->s, conn->address);
624 tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
625 tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
626 dns_found_answer(conn->address, ntohl(addr), success);
628 tor_free(conn->address);
629 conn->address = tor_strdup("<idle>");
630 conn->state = DNSWORKER_STATE_IDLE;
631 num_dnsworkers_busy--;
632 if (conn->timestamp_created < last_rotation_time) {
633 connection_mark_for_close(conn);
634 num_dnsworkers--;
635 spawn_enough_dnsworkers();
637 return 0;
640 /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
641 * and re-opened once they're no longer busy.
643 void dnsworkers_rotate(void)
645 connection_t *dnsconn;
646 log_fn(LOG_INFO, "Rotating DNS workers.");
647 while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
648 DNSWORKER_STATE_IDLE))) {
649 connection_mark_for_close(dnsconn);
650 num_dnsworkers--;
652 last_rotation_time = time(NULL);
653 spawn_enough_dnsworkers();
656 /** Implementation for DNS workers; this code runs in a separate
657 * execution context. It takes as its argument an fdarray as returned
658 * by socketpair(), and communicates via fdarray[1]. The protocol is
659 * as follows:
660 * - The OR says:
661 * - ADDRESSLEN [1 byte]
662 * - ADDRESS [ADDRESSLEN bytes]
663 * - The DNS worker does the lookup, and replies:
664 * - OUTCOME [1 byte]
665 * - IP [4 bytes]
667 * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
668 * IP is in host order.
670 * The dnsworker runs indefinitely, until its connection is closed or an error
671 * occurs.
673 static int dnsworker_main(void *data) {
674 char address[MAX_ADDRESSLEN];
675 unsigned char address_len;
676 char answer[5];
677 uint32_t ip;
678 int *fdarray = data;
679 int fd;
680 int result;
682 /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
684 fd = fdarray[1]; /* this side is ours */
685 #ifndef TOR_IS_MULTITHREADED
686 tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
687 connection_free_all(); /* so the child doesn't hold the parent's fd's open */
688 handle_signals(0); /* ignore interrupts from the keyboard, etc */
689 #endif
690 tor_free(data);
692 for (;;) {
693 int r;
695 if ((r = recv(fd, &address_len, 1, 0)) != 1) {
696 if (r == 0) {
697 log_fn(LOG_INFO,"DNS worker exiting because Tor process closed connection (either pruned idle dnsworker or died).");
698 } else {
699 log_fn(LOG_INFO,"DNS worker exiting because of error on connection to Tor process.");
700 log_fn(LOG_INFO,"(Error on %d was %s)", fd, tor_socket_strerror(tor_socket_errno(fd)));
702 spawn_exit();
705 if (address_len && read_all(fd, address, address_len, 1) != address_len) {
706 log_fn(LOG_ERR,"read hostname failed. Child exiting.");
707 spawn_exit();
709 address[address_len] = 0; /* null terminate it */
711 result = tor_lookup_hostname(address, &ip);
712 /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
713 if (!ip)
714 result = -1;
715 switch (result) {
716 case 1:
717 /* XXX result can never be 1, because we set it to -1 above on error */
718 log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
719 answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
720 break;
721 case -1:
722 log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
723 answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
724 break;
725 case 0:
726 log_fn(LOG_INFO,"Resolved address '%s'.",address);
727 answer[0] = DNS_RESOLVE_SUCCEEDED;
728 break;
730 set_uint32(answer+1, ip);
731 if (write_all(fd, answer, 5, 1) != 5) {
732 log_fn(LOG_ERR,"writing answer failed. Child exiting.");
733 spawn_exit();
736 return 0; /* windows wants this function to return an int */
739 /** Launch a new DNS worker; return 0 on success, -1 on failure.
741 static int spawn_dnsworker(void) {
742 int *fdarray;
743 int fd;
744 connection_t *conn;
746 fdarray = tor_malloc(sizeof(int)*2);
747 if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray) < 0) {
748 log(LOG_ERR, "Couldn't construct socketpair: %s",
749 tor_socket_strerror(tor_socket_errno(-1)));
750 tor_cleanup();
751 tor_free(fdarray);
752 exit(1);
755 /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
757 fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free fdarray */
758 spawn_func(dnsworker_main, (void*)fdarray);
759 log_fn(LOG_DEBUG,"just spawned a worker.");
760 #ifndef TOR_IS_MULTITHREADED
761 tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
762 tor_free(fdarray);
763 #endif
765 conn = connection_new(CONN_TYPE_DNSWORKER);
767 set_socket_nonblocking(fd);
769 /* set up conn so it's got all the data we need to remember */
770 conn->s = fd;
771 conn->address = tor_strdup("<unused>");
773 if (connection_add(conn) < 0) { /* no space, forget it */
774 log_fn(LOG_WARN,"connection_add failed. Giving up.");
775 connection_free(conn); /* this closes fd */
776 return -1;
779 conn->state = DNSWORKER_STATE_IDLE;
780 connection_start_reading(conn);
782 return 0; /* success */
785 /** If we have too many or too few DNS workers, spawn or kill some.
787 static void spawn_enough_dnsworkers(void) {
788 int num_dnsworkers_needed; /* aim to have 1 more than needed,
789 * but no less than min and no more than max */
790 connection_t *dnsconn;
792 /* XXX This may not be the best strategy. Maybe we should queue pending
793 * requests until the old ones finish or time out: otherwise, if
794 * the connection requests come fast enough, we never get any DNS done. -NM
795 * XXX But if we queue them, then the adversary can pile even more
796 * queries onto us, blocking legitimate requests for even longer.
797 * Maybe we should compromise and only kill if it's been at it for
798 * more than, e.g., 2 seconds. -RD
800 if (num_dnsworkers_busy == MAX_DNSWORKERS) {
801 /* We always want at least one worker idle.
802 * So find the oldest busy worker and kill it.
804 dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
805 DNSWORKER_STATE_BUSY);
806 tor_assert(dnsconn);
808 log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
809 MAX_DNSWORKERS);
811 connection_mark_for_close(dnsconn);
812 num_dnsworkers_busy--;
813 num_dnsworkers--;
816 if (num_dnsworkers_busy >= MIN_DNSWORKERS)
817 num_dnsworkers_needed = num_dnsworkers_busy+1;
818 else
819 num_dnsworkers_needed = MIN_DNSWORKERS;
821 while (num_dnsworkers < num_dnsworkers_needed) {
822 if (spawn_dnsworker() < 0) {
823 log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
824 return;
826 num_dnsworkers++;
829 while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
830 /* cull excess workers */
831 log_fn(LOG_NOTICE,"%d of %d dnsworkers are idle. Killing one.",
832 num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
833 dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
834 tor_assert(dnsconn);
835 connection_mark_for_close(dnsconn);
836 num_dnsworkers--;