a bit more debug info
[tor.git] / src / or / dns.c
blobff02efc050bcc11f815fe23293a7117907322902
1 /* Copyright 2003-2004 Roger Dingledine.
2 * Copyright 2004-2005 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 strncmp(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 static void
103 _free_cached_resolve(struct cached_resolve *r) {
104 while (r->pending_connections) {
105 struct pending_connection_t *victim = r->pending_connections;
106 r->pending_connections = victim->next;
107 tor_free(victim);
109 tor_free(r);
112 void
113 dns_free_all(void)
115 struct cached_resolve *ptr, *next;
116 for (ptr = SPLAY_MIN(cache_tree, &cache_root); ptr != NULL; ptr = next) {
117 next = SPLAY_NEXT(cache_tree, &cache_root, ptr);
118 SPLAY_REMOVE(cache_tree, &cache_root, ptr);
119 _free_cached_resolve(ptr);
123 /** Linked list of resolved addresses, oldest to newest. */
124 static struct cached_resolve *oldest_cached_resolve = NULL;
125 static struct cached_resolve *newest_cached_resolve = NULL;
127 /** Remove every cached_resolve whose <b>expire</b> time is before <b>now</b>
128 * from the cache. */
129 static void purge_expired_resolves(uint32_t now) {
130 struct cached_resolve *resolve;
131 struct pending_connection_t *pend;
132 connection_t *pendconn;
134 /* this is fast because the linked list
135 * oldest_cached_resolve is ordered by when they came in.
137 while (oldest_cached_resolve && (oldest_cached_resolve->expire < now)) {
138 resolve = oldest_cached_resolve;
139 log(LOG_DEBUG,"Forgetting old cached resolve (address %s, expires %lu)",
140 resolve->address, (unsigned long)resolve->expire);
141 if (resolve->state == CACHE_STATE_PENDING) {
142 log_fn(LOG_WARN,"Bug: Expiring a dns resolve ('%s') that's still pending. Forgot to cull it?", resolve->address);
143 tor_fragile_assert();
145 if (resolve->pending_connections) {
146 log_fn(LOG_WARN, "Closing pending connections on expiring DNS resolve!");
147 tor_fragile_assert();
148 while (resolve->pending_connections) {
149 pend = resolve->pending_connections;
150 resolve->pending_connections = pend->next;
151 /* Connections should only be pending if they have no socket. */
152 tor_assert(pend->conn->s == -1);
153 pendconn = pend->conn;
154 connection_edge_end(pendconn, END_STREAM_REASON_TIMEOUT,
155 pendconn->cpath_layer);
156 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
157 connection_free(pendconn);
158 tor_free(pend);
161 oldest_cached_resolve = resolve->next;
162 if (!oldest_cached_resolve) /* if there are no more, */
163 newest_cached_resolve = NULL; /* then make sure the list's tail knows that too */
164 SPLAY_REMOVE(cache_tree, &cache_root, resolve);
165 tor_free(resolve);
169 static void send_resolved_cell(connection_t *conn, uint8_t answer_type)
171 char buf[RELAY_PAYLOAD_SIZE];
172 size_t buflen;
174 buf[0] = answer_type;
176 switch (answer_type)
178 case RESOLVED_TYPE_IPV4:
179 buf[1] = 4;
180 set_uint32(buf+2, htonl(conn->addr));
181 buflen = 6;
182 break;
183 case RESOLVED_TYPE_ERROR_TRANSIENT:
184 case RESOLVED_TYPE_ERROR:
185 buf[1] = 24; /* length of "error resolving hostname" */
186 strlcpy(buf+2, "error resolving hostname", sizeof(buf)-2);
187 buflen = 26;
188 break;
189 default:
190 tor_assert(0);
192 connection_edge_send_command(conn, circuit_get_by_edge_conn(conn),
193 RELAY_COMMAND_RESOLVED, buf, buflen,
194 conn->cpath_layer);
197 /** Link <b>r</b> into the tree of address-to-result mappings, and add it to
198 * the linked list of resolves-by-age. */
199 static void
200 insert_resolve(struct cached_resolve *r)
202 /* add us to the linked list of resolves */
203 if (!oldest_cached_resolve) {
204 oldest_cached_resolve = r;
205 } else {
206 newest_cached_resolve->next = r;
208 newest_cached_resolve = r;
210 SPLAY_INSERT(cache_tree, &cache_root, r);
213 /** See if we have a cache entry for <b>exitconn</b>-\>address. if so,
214 * if resolve valid, put it into <b>exitconn</b>-\>addr and return 1.
215 * If resolve failed, unlink exitconn if needed, free it, and return -1.
217 * Else, if seen before and pending, add conn to the pending list,
218 * and return 0.
220 * Else, if not seen before, add conn to pending list, hand to
221 * dns farm, and return 0.
223 int dns_resolve(connection_t *exitconn) {
224 struct cached_resolve *resolve;
225 struct cached_resolve search;
226 struct pending_connection_t *pending_connection;
227 struct in_addr in;
228 circuit_t *circ;
229 uint32_t now = time(NULL);
230 assert_connection_ok(exitconn, 0);
231 tor_assert(exitconn->s == -1);
233 /* first check if exitconn->address is an IP. If so, we already
234 * know the answer. */
235 if (tor_inet_aton(exitconn->address, &in) != 0) {
236 exitconn->addr = ntohl(in.s_addr);
237 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
238 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
239 return 1;
242 /* then take this opportunity to see if there are any expired
243 * resolves in the tree. */
244 purge_expired_resolves(now);
246 /* lower-case exitconn->address, so it's in canonical form */
247 tor_strlower(exitconn->address);
249 /* now check the tree to see if 'address' is already there. */
250 strlcpy(search.address, exitconn->address, sizeof(search.address));
251 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
252 if (resolve) { /* already there */
253 switch (resolve->state) {
254 case CACHE_STATE_PENDING:
255 /* add us to the pending list */
256 pending_connection = tor_malloc_zero(
257 sizeof(struct pending_connection_t));
258 pending_connection->conn = exitconn;
259 pending_connection->next = resolve->pending_connections;
260 resolve->pending_connections = pending_connection;
261 log_fn(LOG_DEBUG,"Connection (fd %d) waiting for pending DNS resolve of '%s'",
262 exitconn->s, exitconn->address);
263 exitconn->state = EXIT_CONN_STATE_RESOLVING;
264 return 0;
265 case CACHE_STATE_VALID:
266 exitconn->addr = resolve->addr;
267 log_fn(LOG_DEBUG,"Connection (fd %d) found cached answer for '%s'",
268 exitconn->s, exitconn->address);
269 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
270 send_resolved_cell(exitconn, RESOLVED_TYPE_IPV4);
271 return 1;
272 case CACHE_STATE_FAILED:
273 log_fn(LOG_DEBUG,"Connection (fd %d) found cached error for '%s'",
274 exitconn->s, exitconn->address);
275 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
276 send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR);
277 circ = circuit_get_by_edge_conn(exitconn);
278 if (circ)
279 circuit_detach_stream(circ, exitconn);
280 if (!exitconn->marked_for_close)
281 connection_free(exitconn);
282 return -1;
284 tor_assert(0);
286 /* not there, need to add it */
287 resolve = tor_malloc_zero(sizeof(struct cached_resolve));
288 resolve->state = CACHE_STATE_PENDING;
289 resolve->expire = now + MAX_DNS_ENTRY_AGE;
290 strlcpy(resolve->address, exitconn->address, sizeof(resolve->address));
292 /* add us to the pending list */
293 pending_connection = tor_malloc_zero(sizeof(struct pending_connection_t));
294 pending_connection->conn = exitconn;
295 resolve->pending_connections = pending_connection;
296 exitconn->state = EXIT_CONN_STATE_RESOLVING;
298 insert_resolve(resolve);
299 return assign_to_dnsworker(exitconn);
302 /** Find or spawn a dns worker process to handle resolving
303 * <b>exitconn</b>-\>address; tell that dns worker to begin resolving.
305 static int assign_to_dnsworker(connection_t *exitconn) {
306 connection_t *dnsconn;
307 unsigned char len;
309 tor_assert(exitconn->state == EXIT_CONN_STATE_RESOLVING);
310 tor_assert(exitconn->s == -1);
312 spawn_enough_dnsworkers(); /* respawn here, to be sure there are enough */
314 dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
316 if (!dnsconn) {
317 log_fn(LOG_WARN,"no idle dns workers. Failing.");
318 if (exitconn->purpose == EXIT_PURPOSE_RESOLVE)
319 send_resolved_cell(exitconn, RESOLVED_TYPE_ERROR_TRANSIENT);
320 dns_cancel_pending_resolve(exitconn->address); /* also sends end and frees! */
321 return -1;
324 log_fn(LOG_DEBUG, "Connection (fd %d) needs to resolve '%s'; assigning to DNSWorker (fd %d)",
325 exitconn->s, exitconn->address, dnsconn->s);
327 tor_free(dnsconn->address);
328 dnsconn->address = tor_strdup(exitconn->address);
329 dnsconn->state = DNSWORKER_STATE_BUSY;
330 num_dnsworkers_busy++;
332 len = strlen(dnsconn->address);
333 connection_write_to_buf(&len, 1, dnsconn);
334 connection_write_to_buf(dnsconn->address, len, dnsconn);
336 // log_fn(LOG_DEBUG,"submitted '%s'", exitconn->address);
337 return 0;
340 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
342 void connection_dns_remove(connection_t *conn)
344 struct pending_connection_t *pend, *victim;
345 struct cached_resolve search;
346 struct cached_resolve *resolve;
348 tor_assert(conn->type == CONN_TYPE_EXIT);
349 tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);
351 strlcpy(search.address, conn->address, sizeof(search.address));
353 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
354 if (!resolve) {
355 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", conn->address);
356 return;
359 tor_assert(resolve->pending_connections);
360 assert_connection_ok(conn,0);
362 pend = resolve->pending_connections;
364 if (pend->conn == conn) {
365 resolve->pending_connections = pend->next;
366 tor_free(pend);
367 log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
368 conn->s, conn->address);
369 return;
370 } else {
371 for ( ; pend->next; pend = pend->next) {
372 if (pend->next->conn == conn) {
373 victim = pend->next;
374 pend->next = victim->next;
375 tor_free(victim);
376 log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
377 conn->s, conn->address);
378 return; /* more are pending */
381 tor_assert(0); /* not reachable unless onlyconn not in pending list */
385 /** Log an error and abort if conn is waiting for a DNS resolve.
387 void assert_connection_edge_not_dns_pending(connection_t *conn) {
388 struct pending_connection_t *pend;
389 struct cached_resolve *resolve;
391 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
392 for (pend = resolve->pending_connections;
393 pend;
394 pend = pend->next) {
395 tor_assert(pend->conn != conn);
400 /** Log an error and abort if any connection waiting for a DNS resolve is
401 * corrupted. */
402 void assert_all_pending_dns_resolves_ok(void) {
403 struct pending_connection_t *pend;
404 struct cached_resolve *resolve;
406 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
407 for (pend = resolve->pending_connections;
408 pend;
409 pend = pend->next) {
410 assert_connection_ok(pend->conn, 0);
411 tor_assert(pend->conn->s == -1);
412 tor_assert(!connection_in_array(pend->conn));
417 /** Mark all connections waiting for <b>address</b> for close. Then cancel
418 * the resolve for <b>address</b> itself, and remove any cached results for
419 * <b>address</b> from the cache.
421 void dns_cancel_pending_resolve(char *address) {
422 struct pending_connection_t *pend;
423 struct cached_resolve search;
424 struct cached_resolve *resolve;
425 connection_t *pendconn;
426 circuit_t *circ;
428 strlcpy(search.address, address, sizeof(search.address));
430 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
431 if (!resolve) {
432 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", address);
433 return;
436 if (!resolve->pending_connections) {
437 /* XXX this should never trigger, but sometimes it does */
438 log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!", address);
439 tor_fragile_assert();
440 return;
442 tor_assert(resolve->pending_connections);
444 /* mark all pending connections to fail */
445 log_fn(LOG_DEBUG, "Failing all connections waiting on DNS resolve of '%s'",
446 address);
447 while (resolve->pending_connections) {
448 pend = resolve->pending_connections;
449 pend->conn->state = EXIT_CONN_STATE_RESOLVEFAILED;
450 pendconn = pend->conn;
451 tor_assert(pendconn->s == -1);
452 if (!pendconn->marked_for_close) {
453 connection_edge_end(pendconn, END_STREAM_REASON_RESOURCELIMIT,
454 pendconn->cpath_layer);
456 circ = circuit_get_by_edge_conn(pendconn);
457 if (circ)
458 circuit_detach_stream(circ, pendconn);
459 connection_free(pendconn);
460 resolve->pending_connections = pend->next;
461 tor_free(pend);
464 dns_purge_resolve(resolve);
467 /** Remove <b>resolve</b> from the cache.
469 static void dns_purge_resolve(struct cached_resolve *resolve) {
470 struct cached_resolve *tmp;
472 /* remove resolve from the linked list */
473 if (resolve == oldest_cached_resolve) {
474 oldest_cached_resolve = resolve->next;
475 if (oldest_cached_resolve == NULL)
476 newest_cached_resolve = NULL;
477 } else {
478 /* FFFF make it a doubly linked list if this becomes too slow */
479 for (tmp=oldest_cached_resolve; tmp && tmp->next != resolve; tmp=tmp->next) ;
480 tor_assert(tmp); /* it's got to be in the list, or we screwed up somewhere else */
481 tmp->next = resolve->next; /* unlink it */
483 if (newest_cached_resolve == resolve)
484 newest_cached_resolve = tmp;
487 /* remove resolve from the tree */
488 SPLAY_REMOVE(cache_tree, &cache_root, resolve);
490 tor_free(resolve);
493 /** Called on the OR side when a DNS worker tells us the outcome of a DNS
494 * resolve: tell all pending connections about the result of the lookup, and
495 * cache the value. (<b>address</b> is a NUL-terminated string containing the
496 * address to look up; <b>addr</b> is an IPv4 address in host order;
497 * <b>outcome</b> is one of
498 * DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
500 static void dns_found_answer(char *address, uint32_t addr, char outcome) {
501 struct pending_connection_t *pend;
502 struct cached_resolve search;
503 struct cached_resolve *resolve;
504 connection_t *pendconn;
505 circuit_t *circ;
507 strlcpy(search.address, address, sizeof(search.address));
509 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
510 if (!resolve) {
511 log_fn(LOG_INFO,"Resolved unasked address '%s'; caching anyway.", address);
512 resolve = tor_malloc_zero(sizeof(struct cached_resolve));
513 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
514 CACHE_STATE_VALID : CACHE_STATE_FAILED;
515 resolve->addr = addr;
516 resolve->expire = time(NULL) + MAX_DNS_ENTRY_AGE;
517 insert_resolve(resolve);
518 return;
521 if (resolve->state != CACHE_STATE_PENDING) {
522 /* XXXX Maybe update addr? or check addr for consistency? Or let
523 * VALID replace FAILED? */
524 log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
525 address);
526 tor_assert(resolve->pending_connections == NULL);
527 return;
529 /* Removed this assertion: in fact, we'll sometimes get a double answer
530 * to the same question. This can happen when we ask one worker to resolve
531 * X.Y.Z., then we cancel the request, and then we ask another worker to
532 * resolve X.Y.Z. */
533 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
535 resolve->addr = addr;
536 if (outcome == DNS_RESOLVE_SUCCEEDED)
537 resolve->state = CACHE_STATE_VALID;
538 else
539 resolve->state = CACHE_STATE_FAILED;
541 while (resolve->pending_connections) {
542 pend = resolve->pending_connections;
543 assert_connection_ok(pend->conn,time(NULL));
544 pend->conn->addr = resolve->addr;
545 pendconn = pend->conn; /* don't pass complex things to the
546 connection_mark_for_close macro */
548 if (resolve->state == CACHE_STATE_FAILED) {
549 /* prevent double-remove. */
550 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
551 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
552 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
553 /* This detach must happen after we send the end cell. */
554 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
555 } else {
556 send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
557 /* This detach must happen after we send the resolved cell. */
558 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
560 connection_free(pendconn);
561 } else {
562 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
563 /* prevent double-remove. */
564 pend->conn->state = EXIT_CONN_STATE_CONNECTING;
566 circ = circuit_get_by_edge_conn(pend->conn);
567 tor_assert(circ);
568 /* unlink pend->conn from resolving_streams, */
569 circuit_detach_stream(circ, pend->conn);
570 /* and link it to n_streams */
571 pend->conn->next_stream = circ->n_streams;
572 pend->conn->on_circuit = circ;
573 circ->n_streams = pend->conn;
575 connection_exit_connect(pend->conn);
576 } else {
577 /* prevent double-remove. This isn't really an accurate state,
578 * but it does the right thing. */
579 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
580 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
581 circ = circuit_get_by_edge_conn(pendconn);
582 tor_assert(circ);
583 circuit_detach_stream(circ, pendconn);
584 connection_free(pendconn);
587 resolve->pending_connections = pend->next;
588 tor_free(pend);
591 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
592 dns_purge_resolve(resolve);
596 /******************************************************************/
599 * Connection between OR and dnsworker
602 /** Write handler: called when we've pushed a request to a dnsworker. */
603 int connection_dns_finished_flushing(connection_t *conn) {
604 tor_assert(conn);
605 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
606 connection_stop_writing(conn);
607 return 0;
610 int connection_dns_reached_eof(connection_t *conn) {
611 log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
612 if (conn->state == DNSWORKER_STATE_BUSY) {
613 /* don't cancel the resolve here -- it would be cancelled in
614 * connection_about_to_close_connection(), since conn is still
615 * in state BUSY
617 num_dnsworkers_busy--;
619 num_dnsworkers--;
620 connection_mark_for_close(conn);
621 return 0;
624 /** Read handler: called when we get data from a dnsworker. See
625 * if we have a complete answer. If so, call dns_found_answer on the
626 * result. If not, wait. Returns 0. */
627 int connection_dns_process_inbuf(connection_t *conn) {
628 char success;
629 uint32_t addr;
631 tor_assert(conn);
632 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
634 if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
635 log_fn(LOG_WARN,"Bug: read data (%d bytes) from an idle dns worker (fd %d, address '%s'). Please report.",
636 (int)buf_datalen(conn->inbuf), conn->s, conn->address);
637 tor_fragile_assert();
639 /* Pull it off the buffer anyway, or it will just stay there.
640 * Keep pulling things off because sometimes we get several
641 * answers at once (!). */
642 while (buf_datalen(conn->inbuf)) {
643 connection_fetch_from_buf(&success,1,conn);
644 connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
645 log_fn(LOG_WARN,"Discarding idle dns answer (success %d, addr %d.)",
646 success, addr);
648 return 0;
650 if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
651 return 0; /* not yet */
652 tor_assert(conn->state == DNSWORKER_STATE_BUSY);
653 tor_assert(buf_datalen(conn->inbuf) == 5);
655 connection_fetch_from_buf(&success,1,conn);
656 connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
658 log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
659 conn->s, conn->address);
661 tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
662 tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
663 dns_found_answer(conn->address, ntohl(addr), success);
665 tor_free(conn->address);
666 conn->address = tor_strdup("<idle>");
667 conn->state = DNSWORKER_STATE_IDLE;
668 num_dnsworkers_busy--;
669 if (conn->timestamp_created < last_rotation_time) {
670 connection_mark_for_close(conn);
671 num_dnsworkers--;
672 spawn_enough_dnsworkers();
674 return 0;
677 /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
678 * and re-opened once they're no longer busy.
680 void dnsworkers_rotate(void)
682 connection_t *dnsconn;
683 log_fn(LOG_INFO, "Rotating DNS workers.");
684 while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
685 DNSWORKER_STATE_IDLE))) {
686 connection_mark_for_close(dnsconn);
687 num_dnsworkers--;
689 last_rotation_time = time(NULL);
690 spawn_enough_dnsworkers();
693 /** Implementation for DNS workers; this code runs in a separate
694 * execution context. It takes as its argument an fdarray as returned
695 * by socketpair(), and communicates via fdarray[1]. The protocol is
696 * as follows:
697 * - The OR says:
698 * - ADDRESSLEN [1 byte]
699 * - ADDRESS [ADDRESSLEN bytes]
700 * - The DNS worker does the lookup, and replies:
701 * - OUTCOME [1 byte]
702 * - IP [4 bytes]
704 * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
705 * IP is in host order.
707 * The dnsworker runs indefinitely, until its connection is closed or an error
708 * occurs.
710 static int dnsworker_main(void *data) {
711 char address[MAX_ADDRESSLEN];
712 unsigned char address_len;
713 char answer[5];
714 uint32_t ip;
715 int *fdarray = data;
716 int fd;
717 int result;
719 /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
721 fd = fdarray[1]; /* this side is ours */
722 #ifndef TOR_IS_MULTITHREADED
723 tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
724 connection_free_all(); /* so the child doesn't hold the parent's fd's open */
725 handle_signals(0); /* ignore interrupts from the keyboard, etc */
726 #endif
727 tor_free(data);
729 for (;;) {
730 int r;
732 if ((r = recv(fd, &address_len, 1, 0)) != 1) {
733 if (r == 0) {
734 log_fn(LOG_INFO,"DNS worker exiting because Tor process closed connection (either pruned idle dnsworker or died).");
735 } else {
736 log_fn(LOG_INFO,"DNS worker exiting because of error on connection to Tor process.");
737 log_fn(LOG_INFO,"(Error on %d was %s)", fd, tor_socket_strerror(tor_socket_errno(fd)));
739 tor_close_socket(fd);
740 spawn_exit();
743 if (address_len && read_all(fd, address, address_len, 1) != address_len) {
744 log_fn(LOG_ERR,"read hostname failed. Child exiting.");
745 tor_close_socket(fd);
746 spawn_exit();
748 address[address_len] = 0; /* null terminate it */
750 result = tor_lookup_hostname(address, &ip);
751 /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
752 if (!ip)
753 result = -1;
754 switch (result) {
755 case 1:
756 /* XXX result can never be 1, because we set it to -1 above on error */
757 log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",address);
758 answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
759 break;
760 case -1:
761 log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",address);
762 answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
763 break;
764 case 0:
765 log_fn(LOG_INFO,"Resolved address '%s'.",address);
766 answer[0] = DNS_RESOLVE_SUCCEEDED;
767 break;
769 set_uint32(answer+1, ip);
770 if (write_all(fd, answer, 5, 1) != 5) {
771 log_fn(LOG_ERR,"writing answer failed. Child exiting.");
772 tor_close_socket(fd);
773 spawn_exit();
776 return 0; /* windows wants this function to return an int */
779 /** Launch a new DNS worker; return 0 on success, -1 on failure.
781 static int spawn_dnsworker(void) {
782 int *fdarray;
783 int fd;
784 connection_t *conn;
786 fdarray = tor_malloc(sizeof(int)*2);
787 if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray) < 0) {
788 log(LOG_ERR, "Couldn't construct socketpair: %s",
789 tor_socket_strerror(tor_socket_errno(-1)));
790 tor_cleanup();
791 tor_free(fdarray);
792 exit(1);
795 /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
797 fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free fdarray */
798 spawn_func(dnsworker_main, (void*)fdarray);
799 log_fn(LOG_DEBUG,"just spawned a worker.");
800 #ifndef TOR_IS_MULTITHREADED
801 tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
802 tor_free(fdarray);
803 #endif
805 conn = connection_new(CONN_TYPE_DNSWORKER);
807 set_socket_nonblocking(fd);
809 /* set up conn so it's got all the data we need to remember */
810 conn->s = fd;
811 conn->address = tor_strdup("<unused>");
813 if (connection_add(conn) < 0) { /* no space, forget it */
814 log_fn(LOG_WARN,"connection_add failed. Giving up.");
815 connection_free(conn); /* this closes fd */
816 return -1;
819 conn->state = DNSWORKER_STATE_IDLE;
820 connection_start_reading(conn);
822 return 0; /* success */
825 /** If we have too many or too few DNS workers, spawn or kill some.
827 static void spawn_enough_dnsworkers(void) {
828 int num_dnsworkers_needed; /* aim to have 1 more than needed,
829 * but no less than min and no more than max */
830 connection_t *dnsconn;
832 /* XXX This may not be the best strategy. Maybe we should queue pending
833 * requests until the old ones finish or time out: otherwise, if
834 * the connection requests come fast enough, we never get any DNS done. -NM
835 * XXX But if we queue them, then the adversary can pile even more
836 * queries onto us, blocking legitimate requests for even longer.
837 * Maybe we should compromise and only kill if it's been at it for
838 * more than, e.g., 2 seconds. -RD
840 if (num_dnsworkers_busy == MAX_DNSWORKERS) {
841 /* We always want at least one worker idle.
842 * So find the oldest busy worker and kill it.
844 dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
845 DNSWORKER_STATE_BUSY);
846 tor_assert(dnsconn);
848 log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
849 MAX_DNSWORKERS);
851 connection_mark_for_close(dnsconn);
852 num_dnsworkers_busy--;
853 num_dnsworkers--;
856 if (num_dnsworkers_busy >= MIN_DNSWORKERS)
857 num_dnsworkers_needed = num_dnsworkers_busy+1;
858 else
859 num_dnsworkers_needed = MIN_DNSWORKERS;
861 while (num_dnsworkers < num_dnsworkers_needed) {
862 if (spawn_dnsworker() < 0) {
863 log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
864 return;
866 num_dnsworkers++;
869 while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
870 /* cull excess workers */
871 log_fn(LOG_NOTICE,"%d of %d dnsworkers are idle. Killing one.",
872 num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
873 dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
874 tor_assert(dnsconn);
875 connection_mark_for_close(dnsconn);
876 num_dnsworkers--;