forward-port the logic skew and double-free thing
[tor.git] / src / or / dns.c
blob5e68c63f9d7d2e6e6f3a766b56c46d2a1d2635b5
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, unlink exitconn if needed, free it, and 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 circuit_t *circ;
211 uint32_t now = time(NULL);
212 assert_connection_ok(exitconn, 0);
213 tor_assert(exitconn->s == -1);
215 /* first check if exitconn->address is an IP. If so, we already
216 * know the answer. */
217 if (tor_inet_aton(exitconn->address, &in) != 0) {
218 exitconn->addr = ntohl(in.s_addr);
219 return 1;
222 /* then take this opportunity to see if there are any expired
223 * resolves in the tree. */
224 purge_expired_resolves(now);
226 /* now check the tree to see if 'address' is already there. */
227 strlcpy(search.address, exitconn->address, sizeof(search.address));
228 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
229 if (resolve) { /* already there */
230 switch (resolve->state) {
231 case CACHE_STATE_PENDING:
232 /* add us to the pending list */
233 pending_connection = tor_malloc_zero(
234 sizeof(struct pending_connection_t));
235 pending_connection->conn = exitconn;
236 pending_connection->next = resolve->pending_connections;
237 resolve->pending_connections = pending_connection;
238 log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
239 exitconn->s, exitconn->address);
240 exitconn->state = EXIT_CONN_STATE_RESOLVING;
241 return 0;
242 case CACHE_STATE_VALID:
243 exitconn->addr = resolve->addr;
244 log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
245 exitconn->s, exitconn->address);
246 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
247 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
248 return 1;
249 case CACHE_STATE_FAILED:
250 log_fn(LOG_DEBUG,"Connection (fd %d) found cached error for '%s'",
251 exitconn->s, exitconn->address);
252 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
253 send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
254 circ = circuit_get_by_conn(exitconn);
255 if (circ)
256 circuit_detach_stream(circ, exitconn);
257 connection_free(exitconn);
258 return -1;
260 tor_assert(0);
262 /* not there, need to add it */
263 resolve = tor_malloc_zero(sizeof(struct cached_resolve));
264 resolve->state = CACHE_STATE_PENDING;
265 resolve->expire = now + MAX_DNS_ENTRY_AGE;
266 strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
268 /* add us to the pending list */
269 pending_connection = tor_malloc_zero(sizeof(struct pending_connection_t));
270 pending_connection->conn = exitconn;
271 resolve->pending_connections = pending_connection;
272 exitconn->state = EXIT_CONN_STATE_RESOLVING;
274 insert_resolve(resolve);
275 return assign_to_dnsworker(exitconn);
278 /** Find or spawn a dns worker process to handle resolving
279 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
281 static int assign_to_dnsworker(connection_t *exitconn) {
282 connection_t *dnsconn;
283 unsigned char len;
285 tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
286 tor_assert(exitconn->s == -1);
288 spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
290 dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
292 if (!dnsconn) {
293 log_fn(LOG_WARN,"no idle dns workers. Failing.");
294 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
295 send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
296 dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees! */
297 return -1;
300 log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
301 exitconn->s, exitconn->address, dnsconn->s);
303 tor_free(dnsconn->address);
304 dnsconn->address = tor_strdup(exitconn->address);
305 dnsconn->state = DNSWORKER_STATE_BUSY;
306 num_dnsworkers_busy++;
308 len = strlen(dnsconn->address);
309 connection_write_to_buf(&len, 1, dnsconn);
310 connection_write_to_buf(dnsconn->address, len, dnsconn);
312 // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
313 return 0;
316 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
318 void connection_dns_remove(connection_t *conn)
320 struct pending_connection_t *pend, *victim;
321 struct cached_resolve search;
322 struct cached_resolve *resolve;
324 tor_assert(conn->type == CONN_TYPE_EXIT);
325 tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);
327 strlcpy(search.address, conn->address, sizeof(search.address));
329 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
330 if (!resolve) {
331 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", conn->address);
332 return;
335 tor_assert(resolve->pending_connections);
336 assert_connection_ok(conn,0);
338 pend = resolve->pending_connections;
340 if (pend->conn == conn) {
341 resolve->pending_connections = pend->next;
342 tor_free(pend);
343 log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
344 conn->s, conn->address);
345 return;
346 } else {
347 for ( ; pend->next; pend = pend->next) {
348 if (pend->next->conn == conn) {
349 victim = pend->next;
350 pend->next = victim->next;
351 tor_free(victim);
352 log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
353 conn->s, conn->address);
354 return; /* more are pending */
357 tor_assert(0); /* not reachable unless onlyconn not in pending list */
361 /** Log an error and abort if conn is waiting for a DNS resolve.
363 void assert_connection_edge_not_dns_pending(connection_t *conn) {
364 struct pending_connection_t *pend;
365 struct cached_resolve *resolve;
367 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
368 for (pend = resolve->pending_connections;
369 pend;
370 pend = pend->next) {
371 tor_assert(pend->conn != conn);
376 /** Log an error and abort if any connection waiting for a DNS resolve is
377 * corrupted. */
378 void assert_all_pending_dns_resolves_ok(void) {
379 struct pending_connection_t *pend;
380 struct cached_resolve *resolve;
382 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
383 for (pend = resolve->pending_connections;
384 pend;
385 pend = pend->next) {
386 assert_connection_ok(pend->conn, 0);
387 tor_assert(pend->conn->s == -1);
388 tor_assert(!connection_in_array(pend->conn));
393 /** Mark all connections waiting for <b>address</b> for close. Then cancel
394 * the resolve for <b>address</b> itself, and remove any cached results for
395 * <b>address</b> from the cache.
397 void dns_cancel_pending_resolve(char *address) {
398 struct pending_connection_t *pend;
399 struct cached_resolve search;
400 struct cached_resolve *resolve;
401 connection_t *pendconn;
402 circuit_t *circ;
404 strlcpy(search.address, address, sizeof(search.address));
406 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
407 if (!resolve) {
408 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", address);
409 return;
412 if (!resolve->pending_connections) {
413 /* XXX this should never trigger, but sometimes it does */
414 log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!", address);
415 #ifdef TOR_FRAGILE
416 tor_assert(0);
417 #endif
418 return;
420 tor_assert(resolve->pending_connections);
422 /* mark all pending connections to fail */
423 log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
424 address);
425 while (resolve->pending_connections) {
426 pend = resolve->pending_connections;
427 pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
428 pendconn = pend->conn;
429 tor_assert(pendconn->s == -1);
430 if (!pendconn->marked_for_close) {
431 connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
432 pendconn->cpath_layer);
434 circ = circuit_get_by_conn(pendconn);
435 if (circ)
436 circuit_detach_stream(circ, pendconn);
437 connection_free(pendconn);
438 resolve->pending_connections = pend->next;
439 tor_free(pend);
442 dns_purge_resolve(resolve);
445 /** Remove <b>resolve</b> from the cache.
447 static void dns_purge_resolve(struct cached_resolve *resolve) {
448 struct cached_resolve *tmp;
450 /* remove resolve from the linked list */
451 if (resolve == oldest_cached_resolve) {
452 oldest_cached_resolve = resolve->next;
453 if (oldest_cached_resolve == NULL)
454 newest_cached_resolve = NULL;
455 } else {
456 /* FFFF make it a doubly linked list if this becomes too slow */
457 for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
458 tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
459 tmp->next = resolve->next; /* unlink it */
461 if (newest_cached_resolve == resolve)
462 newest_cached_resolve = tmp;
465 /* remove resolve from the tree */
466 SPLAY_REMOVE(cache_tree, &cache_root, resolve);
468 tor_free(resolve);
471 /** Called on the OR side when a DNS worker tells us the outcome of a DNS
472 * resolve: tell all pending connections about the result of the lookup, and
473 * cache the value. (<b>address</b> is a NUL-terminated string containing the
474 * address to look up; <b>addr</b> is an IPv4 address in host order;
475 * <b>outcome</b> is one of
476 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
478 static void dns_found_answer(char *address, uint32_t addr, char outcome) {
479 struct pending_connection_t *pend;
480 struct cached_resolve search;
481 struct cached_resolve *resolve;
482 connection_t *pendconn;
483 circuit_t *circ;
485 strlcpy(search.address, address, sizeof(search.address));
487 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
488 if (!resolve) {
489 log_fn(LOG_INFO,"Resolved unasked address '%s'; caching anyway.", address);
490 resolve = tor_malloc_zero(sizeof(struct cached_resolve));
491 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
492 CACHE_STATE_VALID : CACHE_STATE_FAILED;
493 resolve->addr = addr;
494 resolve->expire = time(NULL) + MAX_DNS_ENTRY_AGE;
495 insert_resolve(resolve);
496 return;
499 if (resolve->state != CACHE_STATE_PENDING) {
500 /* XXXX Maybe update addr? or check addr for consistency? Or let
501 * VALID replace FAILED? */
502 log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
503 address);
504 tor_assert(resolve->pending_connections == NULL);
505 return;
507 /* Removed this assertion: in fact, we'll sometimes get a double answer
508 * to the same question. This can happen when we ask one worker to resolve
509 * X.Y.Z., then we cancel the request, and then we ask another worker to
510 * resolve X.Y.Z. */
511 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
513 resolve->addr = addr;
514 if (outcome == DNS_RESOLVE_SUCCEEDED)
515 resolve->state = CACHE_STATE_VALID;
516 else
517 resolve->state = CACHE_STATE_FAILED;
519 while (resolve->pending_connections) {
520 pend = resolve->pending_connections;
521 assert_connection_ok(pend->conn,time(NULL));
522 pend->conn->addr = resolve->addr;
523 pendconn = pend->conn; /* don't pass complex things to the
524 connection_mark_for_close macro */
526 if (resolve->state == CACHE_STATE_FAILED) {
527 /* prevent double-remove. */
528 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
529 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
530 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
531 /* This detach must happen after we send the end cell. */
532 circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
533 } else {
534 send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
535 /* This detach must happen after we send the resolved cell. */
536 circuit_detach_stream(circuit_get_by_conn(pendconn), pendconn);
538 connection_free(pendconn);
539 } else {
540 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
541 /* prevent double-remove. */
542 pend->conn->state = EXIT_CONN_STATE_CONNECTING;
544 circ = circuit_get_by_conn(pend->conn);
545 tor_assert(circ);
546 /* unlink pend->conn from resolving_streams, */
547 circuit_detach_stream(circ, pend->conn);
548 /* and link it to n_streams */
549 pend->conn->next_stream = circ->n_streams;
550 circ->n_streams = pend->conn;
552 connection_exit_connect(pend->conn);
553 } else {
554 /* prevent double-remove. This isn't really an accurate state,
555 * but it does the right thing. */
556 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
557 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
558 circ = circuit_get_by_conn(pendconn);
559 tor_assert(circ);
560 circuit_detach_stream(circ, pendconn);
561 connection_free(pendconn);
564 resolve->pending_connections = pend->next;
565 tor_free(pend);
568 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
569 dns_purge_resolve(resolve);
573 /******************************************************************/
576 * Connection between OR and dnsworker
579 /** Write handler: called when we've pushed a request to a dnsworker. */
580 int connection_dns_finished_flushing(connection_t *conn) {
581 tor_assert(conn);
582 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
583 connection_stop_writing(conn);
584 return 0;
587 int connection_dns_reached_eof(connection_t *conn) {
588 log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
589 if (conn->state == DNSWORKER_STATE_BUSY) {
590 /* don't cancel the resolve here -- it would be cancelled in
591 * connection_about_to_close_connection(), since conn is still
592 * in state BUSY
594 num_dnsworkers_busy--;
596 num_dnsworkers--;
597 connection_mark_for_close(conn);
598 return 0;
601 /** Read handler: called when we get data from a dnsworker. See
602 * if we have a complete answer. If so, call dns_found_answer on the
603 * result. If not, wait. Returns 0. */
604 int connection_dns_process_inbuf(connection_t *conn) {
605 char success;
606 uint32_t addr;
608 tor_assert(conn);
609 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
611 if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
612 log_fn(LOG_WARN,"Bug: read data from an idle dns worker. Please report.");
613 #ifdef TOR_FRAGILE
614 tor_assert(0);
615 #endif
616 return 0;
618 if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
619 return 0; /* not yet */
620 tor_assert(conn->state == DNSWORKER_STATE_BUSY);
621 tor_assert(buf_datalen(conn->inbuf) == 5);
623 connection_fetch_from_buf(&success,1,conn);
624 connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
626 log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
627 conn->s, conn->address);
629 tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
630 tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
631 dns_found_answer(conn->address, ntohl(addr), success);
633 tor_free(conn->address);
634 conn->address = tor_strdup("<idle>");
635 conn->state = DNSWORKER_STATE_IDLE;
636 num_dnsworkers_busy--;
637 if (conn->timestamp_created < last_rotation_time) {
638 connection_mark_for_close(conn);
639 num_dnsworkers--;
640 spawn_enough_dnsworkers();
642 return 0;
645 /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
646 * and re-opened once they're no longer busy.
648 void dnsworkers_rotate(void)
650 connection_t *dnsconn;
651 log_fn(LOG_INFO, "Rotating DNS workers.");
652 while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
653 DNSWORKER_STATE_IDLE))) {
654 connection_mark_for_close(dnsconn);
655 num_dnsworkers--;
657 last_rotation_time = time(NULL);
658 spawn_enough_dnsworkers();
661 /** Implementation for DNS workers; this code runs in a separate
662 * execution context. It takes as its argument an fdarray as returned
663 * by socketpair(), and communicates via fdarray[1]. The protocol is
664 * as follows:
665 * - The OR says:
666 * - ADDRESSLEN [1 byte]
667 * - ADDRESS [ADDRESSLEN bytes]
668 * - The DNS worker does the lookup, and replies:
669 * - OUTCOME [1 byte]
670 * - IP [4 bytes]
672 * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
673 * IP is in host order.
675 * The dnsworker runs indefinitely, until its connection is closed or an error
676 * occurs.
678 static int dnsworker_main(void *data) {
679 char address[MAX_ADDRESSLEN];
680 unsigned char address_len;
681 char answer[5];
682 uint32_t ip;
683 int *fdarray = data;
684 int fd;
685 int result;
687 /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
689 fd = fdarray[1]; /* this side is ours */
690 #ifndef TOR_IS_MULTITHREADED
691 tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
692 connection_free_all(); /* so the child doesn't hold the parent's fd's open */
693 handle_signals(0); /* ignore interrupts from the keyboard, etc */
694 #endif
695 tor_free(data);
697 for (;;) {
698 int r;
700 if ((r = recv(fd, &address_len, 1, 0)) != 1) {
701 if (r == 0) {
702 log_fn(LOG_INFO,"DNS worker exiting because Tor process closed connection (either pruned idle dnsworker or died).");
703 } else {
704 log_fn(LOG_INFO,"DNS worker exiting because of error on connection to Tor process.");
705 log_fn(LOG_INFO,"(Error on %d was %s)", fd, tor_socket_strerror(tor_socket_errno(fd)));
707 spawn_exit();
710 if (address_len && read_all(fd, address, address_len, 1) != address_len) {
711 log_fn(LOG_ERR,"read hostname failed. Child exiting.");
712 spawn_exit();
714 address[address_len] = 0; /* null terminate it */
716 result = tor_lookup_hostname(address, &ip);
717 /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
718 if (!ip)
719 result = -1;
720 switch (result) {
721 case 1:
722 /* XXX result can never be 1, because we set it to -1 above on error */
723 log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
724 answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
725 break;
726 case -1:
727 log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
728 answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
729 break;
730 case 0:
731 log_fn(LOG_INFO,"Resolved address '%s'.",address);
732 answer[0] = DNS_RESOLVE_SUCCEEDED;
733 break;
735 set_uint32(answer+1, ip);
736 if (write_all(fd, answer, 5, 1) != 5) {
737 log_fn(LOG_ERR,"writing answer failed. Child exiting.");
738 spawn_exit();
741 return 0; /* windows wants this function to return an int */
744 /** Launch a new DNS worker; return 0 on success, -1 on failure.
746 static int spawn_dnsworker(void) {
747 int *fdarray;
748 int fd;
749 connection_t *conn;
751 fdarray = tor_malloc(sizeof(int)*2);
752 if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray) < 0) {
753 log(LOG_ERR, "Couldn't construct socketpair: %s",
754 tor_socket_strerror(tor_socket_errno(-1)));
755 tor_cleanup();
756 tor_free(fdarray);
757 exit(1);
760 /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
762 fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free fdarray */
763 spawn_func(dnsworker_main, (void*)fdarray);
764 log_fn(LOG_DEBUG,"just spawned a worker.");
765 #ifndef TOR_IS_MULTITHREADED
766 tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
767 tor_free(fdarray);
768 #endif
770 conn = connection_new(CONN_TYPE_DNSWORKER);
772 set_socket_nonblocking(fd);
774 /* set up conn so it's got all the data we need to remember */
775 conn->s = fd;
776 conn->address = tor_strdup("<unused>");
778 if (connection_add(conn) < 0) { /* no space, forget it */
779 log_fn(LOG_WARN,"connection_add failed. Giving up.");
780 connection_free(conn); /* this closes fd */
781 return -1;
784 conn->state = DNSWORKER_STATE_IDLE;
785 connection_start_reading(conn);
787 return 0; /* success */
790 /** If we have too many or too few DNS workers, spawn or kill some.
792 static void spawn_enough_dnsworkers(void) {
793 int num_dnsworkers_needed; /* aim to have 1 more than needed,
794 * but no less than min and no more than max */
795 connection_t *dnsconn;
797 /* XXX This may not be the best strategy. Maybe we should queue pending
798 * requests until the old ones finish or time out: otherwise, if
799 * the connection requests come fast enough, we never get any DNS done. -NM
800 * XXX But if we queue them, then the adversary can pile even more
801 * queries onto us, blocking legitimate requests for even longer.
802 * Maybe we should compromise and only kill if it's been at it for
803 * more than, e.g., 2 seconds. -RD
805 if (num_dnsworkers_busy == MAX_DNSWORKERS) {
806 /* We always want at least one worker idle.
807 * So find the oldest busy worker and kill it.
809 dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
810 DNSWORKER_STATE_BUSY);
811 tor_assert(dnsconn);
813 log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
814 MAX_DNSWORKERS);
816 connection_mark_for_close(dnsconn);
817 num_dnsworkers_busy--;
818 num_dnsworkers--;
821 if (num_dnsworkers_busy >= MIN_DNSWORKERS)
822 num_dnsworkers_needed = num_dnsworkers_busy+1;
823 else
824 num_dnsworkers_needed = MIN_DNSWORKERS;
826 while (num_dnsworkers < num_dnsworkers_needed) {
827 if (spawn_dnsworker() < 0) {
828 log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
829 return;
831 num_dnsworkers++;
834 while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
835 /* cull excess workers */
836 log_fn(LOG_NOTICE,"%d of %d dnsworkers are idle. Killing one.",
837 num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
838 dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
839 tor_assert(dnsconn);
840 connection_mark_for_close(dnsconn);
841 num_dnsworkers--;