fix compile error if you're not multithreaded
[tor.git] / src / or / dns.c
blob3ed03a2d8f0b785dc9a2d17edfb784f508000905
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 safe_str(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?", safe_str(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, safe_str(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, safe_str(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, safe_str(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, safe_str(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 return 0;
339 /** Remove <b>conn</b> from the list of connections waiting for conn-\>address.
341 void connection_dns_remove(connection_t *conn)
343 struct pending_connection_t *pend, *victim;
344 struct cached_resolve search;
345 struct cached_resolve *resolve;
347 tor_assert(conn->type == CONN_TYPE_EXIT);
348 tor_assert(conn->state == EXIT_CONN_STATE_RESOLVING);
350 strlcpy(search.address, conn->address, sizeof(search.address));
352 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
353 if (!resolve) {
354 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(conn->address));
355 return;
358 tor_assert(resolve->pending_connections);
359 assert_connection_ok(conn,0);
361 pend = resolve->pending_connections;
363 if (pend->conn == conn) {
364 resolve->pending_connections = pend->next;
365 tor_free(pend);
366 log_fn(LOG_DEBUG, "First connection (fd %d) no longer waiting for resolve of '%s'",
367 conn->s, safe_str(conn->address));
368 return;
369 } else {
370 for ( ; pend->next; pend = pend->next) {
371 if (pend->next->conn == conn) {
372 victim = pend->next;
373 pend->next = victim->next;
374 tor_free(victim);
375 log_fn(LOG_DEBUG, "Connection (fd %d) no longer waiting for resolve of '%s'",
376 conn->s, safe_str(conn->address));
377 return; /* more are pending */
380 tor_assert(0); /* not reachable unless onlyconn not in pending list */
384 /** Log an error and abort if conn is waiting for a DNS resolve.
386 void assert_connection_edge_not_dns_pending(connection_t *conn) {
387 struct pending_connection_t *pend;
388 struct cached_resolve *resolve;
390 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
391 for (pend = resolve->pending_connections;
392 pend;
393 pend = pend->next) {
394 tor_assert(pend->conn != conn);
399 /** Log an error and abort if any connection waiting for a DNS resolve is
400 * corrupted. */
401 void assert_all_pending_dns_resolves_ok(void) {
402 struct pending_connection_t *pend;
403 struct cached_resolve *resolve;
405 SPLAY_FOREACH(resolve, cache_tree, &cache_root) {
406 for (pend = resolve->pending_connections;
407 pend;
408 pend = pend->next) {
409 assert_connection_ok(pend->conn, 0);
410 tor_assert(pend->conn->s == -1);
411 tor_assert(!connection_in_array(pend->conn));
416 /** Mark all connections waiting for <b>address</b> for close. Then cancel
417 * the resolve for <b>address</b> itself, and remove any cached results for
418 * <b>address</b> from the cache.
420 void dns_cancel_pending_resolve(char *address) {
421 struct pending_connection_t *pend;
422 struct cached_resolve search;
423 struct cached_resolve *resolve;
424 connection_t *pendconn;
425 circuit_t *circ;
427 strlcpy(search.address, address, sizeof(search.address));
429 resolve = SPLAY_FIND(cache_tree, &cache_root, &search);
430 if (!resolve) {
431 log_fn(LOG_NOTICE,"Address '%s' is not pending. Dropping.", safe_str(address));
432 return;
435 if (!resolve->pending_connections) {
436 /* XXX this should never trigger, but sometimes it does */
437 log_fn(LOG_WARN,"Bug: Address '%s' is pending but has no pending connections!",
438 safe_str(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 safe_str(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.",
512 safe_str(address));
513 resolve = tor_malloc_zero(sizeof(struct cached_resolve));
514 resolve->state = (outcome == DNS_RESOLVE_SUCCEEDED) ?
515 CACHE_STATE_VALID : CACHE_STATE_FAILED;
516 resolve->addr = addr;
517 resolve->expire = time(NULL) + MAX_DNS_ENTRY_AGE;
518 insert_resolve(resolve);
519 return;
522 if (resolve->state != CACHE_STATE_PENDING) {
523 /* XXXX Maybe update addr? or check addr for consistency? Or let
524 * VALID replace FAILED? */
525 log_fn(LOG_NOTICE, "Resolved '%s' which was already resolved; ignoring",
526 safe_str(address));
527 tor_assert(resolve->pending_connections == NULL);
528 return;
530 /* Removed this assertion: in fact, we'll sometimes get a double answer
531 * to the same question. This can happen when we ask one worker to resolve
532 * X.Y.Z., then we cancel the request, and then we ask another worker to
533 * resolve X.Y.Z. */
534 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
536 resolve->addr = addr;
537 if (outcome == DNS_RESOLVE_SUCCEEDED)
538 resolve->state = CACHE_STATE_VALID;
539 else
540 resolve->state = CACHE_STATE_FAILED;
542 while (resolve->pending_connections) {
543 pend = resolve->pending_connections;
544 assert_connection_ok(pend->conn,time(NULL));
545 pend->conn->addr = resolve->addr;
546 pendconn = pend->conn; /* don't pass complex things to the
547 connection_mark_for_close macro */
549 if (resolve->state == CACHE_STATE_FAILED) {
550 /* prevent double-remove. */
551 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
552 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
553 connection_edge_end(pendconn, END_STREAM_REASON_RESOLVEFAILED, pendconn->cpath_layer);
554 /* This detach must happen after we send the end cell. */
555 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
556 } else {
557 send_resolved_cell(pendconn, RESOLVED_TYPE_ERROR);
558 /* This detach must happen after we send the resolved cell. */
559 circuit_detach_stream(circuit_get_by_edge_conn(pendconn), pendconn);
561 connection_free(pendconn);
562 } else {
563 if (pendconn->purpose == EXIT_PURPOSE_CONNECT) {
564 /* prevent double-remove. */
565 pend->conn->state = EXIT_CONN_STATE_CONNECTING;
567 circ = circuit_get_by_edge_conn(pend->conn);
568 tor_assert(circ);
569 /* unlink pend->conn from resolving_streams, */
570 circuit_detach_stream(circ, pend->conn);
571 /* and link it to n_streams */
572 pend->conn->next_stream = circ->n_streams;
573 pend->conn->on_circuit = circ;
574 circ->n_streams = pend->conn;
576 connection_exit_connect(pend->conn);
577 } else {
578 /* prevent double-remove. This isn't really an accurate state,
579 * but it does the right thing. */
580 pendconn->state = EXIT_CONN_STATE_RESOLVEFAILED;
581 send_resolved_cell(pendconn, RESOLVED_TYPE_IPV4);
582 circ = circuit_get_by_edge_conn(pendconn);
583 tor_assert(circ);
584 circuit_detach_stream(circ, pendconn);
585 connection_free(pendconn);
588 resolve->pending_connections = pend->next;
589 tor_free(pend);
592 if (outcome == DNS_RESOLVE_FAILED_TRANSIENT) { /* remove from cache */
593 dns_purge_resolve(resolve);
597 /******************************************************************/
600 * Connection between OR and dnsworker
603 /** Write handler: called when we've pushed a request to a dnsworker. */
604 int connection_dns_finished_flushing(connection_t *conn) {
605 tor_assert(conn);
606 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
607 connection_stop_writing(conn);
608 return 0;
611 int connection_dns_reached_eof(connection_t *conn) {
612 log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
613 if (conn->state == DNSWORKER_STATE_BUSY) {
614 /* don't cancel the resolve here -- it would be cancelled in
615 * connection_about_to_close_connection(), since conn is still
616 * in state BUSY
618 num_dnsworkers_busy--;
620 num_dnsworkers--;
621 connection_mark_for_close(conn);
622 return 0;
625 /** Read handler: called when we get data from a dnsworker. See
626 * if we have a complete answer. If so, call dns_found_answer on the
627 * result. If not, wait. Returns 0. */
628 int connection_dns_process_inbuf(connection_t *conn) {
629 char success;
630 uint32_t addr;
632 tor_assert(conn);
633 tor_assert(conn->type == CONN_TYPE_DNSWORKER);
635 if (conn->state != DNSWORKER_STATE_BUSY && buf_datalen(conn->inbuf)) {
636 log_fn(LOG_WARN,"Bug: read data (%d bytes) from an idle dns worker (fd %d, address '%s'). Please report.",
637 (int)buf_datalen(conn->inbuf), conn->s, safe_str(conn->address));
638 tor_fragile_assert();
640 /* Pull it off the buffer anyway, or it will just stay there.
641 * Keep pulling things off because sometimes we get several
642 * answers at once (!). */
643 while (buf_datalen(conn->inbuf)) {
644 connection_fetch_from_buf(&success,1,conn);
645 connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
646 log_fn(LOG_WARN,"Discarding idle dns answer (success %d, addr %d.)",
647 success, addr); // XXX safe_str
649 return 0;
651 if (buf_datalen(conn->inbuf) < 5) /* entire answer available? */
652 return 0; /* not yet */
653 tor_assert(conn->state == DNSWORKER_STATE_BUSY);
654 tor_assert(buf_datalen(conn->inbuf) == 5);
656 connection_fetch_from_buf(&success,1,conn);
657 connection_fetch_from_buf((char *)&addr,sizeof(uint32_t),conn);
659 log_fn(LOG_DEBUG, "DNSWorker (fd %d) returned answer for '%s'",
660 conn->s, safe_str(conn->address));
662 tor_assert(success >= DNS_RESOLVE_FAILED_TRANSIENT);
663 tor_assert(success <= DNS_RESOLVE_SUCCEEDED);
664 dns_found_answer(conn->address, ntohl(addr), success);
666 tor_free(conn->address);
667 conn->address = tor_strdup("<idle>");
668 conn->state = DNSWORKER_STATE_IDLE;
669 num_dnsworkers_busy--;
670 if (conn->timestamp_created < last_rotation_time) {
671 connection_mark_for_close(conn);
672 num_dnsworkers--;
673 spawn_enough_dnsworkers();
675 return 0;
678 /** Close and re-open all idle dnsworkers; schedule busy ones to be closed
679 * and re-opened once they're no longer busy.
681 void dnsworkers_rotate(void)
683 connection_t *dnsconn;
684 log_fn(LOG_INFO, "Rotating DNS workers.");
685 while ((dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER,
686 DNSWORKER_STATE_IDLE))) {
687 connection_mark_for_close(dnsconn);
688 num_dnsworkers--;
690 last_rotation_time = time(NULL);
691 spawn_enough_dnsworkers();
694 /** Implementation for DNS workers; this code runs in a separate
695 * execution context. It takes as its argument an fdarray as returned
696 * by socketpair(), and communicates via fdarray[1]. The protocol is
697 * as follows:
698 * - The OR says:
699 * - ADDRESSLEN [1 byte]
700 * - ADDRESS [ADDRESSLEN bytes]
701 * - The DNS worker does the lookup, and replies:
702 * - OUTCOME [1 byte]
703 * - IP [4 bytes]
705 * OUTCOME is one of DNS_RESOLVE_{FAILED_TRANSIENT|FAILED_PERMANENT|SUCCEEDED}.
706 * IP is in host order.
708 * The dnsworker runs indefinitely, until its connection is closed or an error
709 * occurs.
711 static int dnsworker_main(void *data) {
712 char address[MAX_ADDRESSLEN];
713 unsigned char address_len;
714 char answer[5];
715 uint32_t ip;
716 int *fdarray = data;
717 int fd;
718 int result;
720 /* log_fn(LOG_NOTICE,"After spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
722 fd = fdarray[1]; /* this side is ours */
723 #ifndef TOR_IS_MULTITHREADED
724 tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
725 tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
726 handle_signals(0); /* ignore interrupts from the keyboard, etc */
727 #endif
728 tor_free(data);
730 for (;;) {
731 int r;
733 if ((r = recv(fd, &address_len, 1, 0)) != 1) {
734 if (r == 0) {
735 log_fn(LOG_INFO,"DNS worker exiting because Tor process closed connection (either pruned idle dnsworker or died).");
736 } else {
737 log_fn(LOG_INFO,"DNS worker exiting because of error on connection to Tor process.");
738 log_fn(LOG_INFO,"(Error on %d was %s)", fd, tor_socket_strerror(tor_socket_errno(fd)));
740 tor_close_socket(fd);
741 spawn_exit();
744 if (address_len && read_all(fd, address, address_len, 1) != address_len) {
745 log_fn(LOG_ERR,"read hostname failed. Child exiting.");
746 tor_close_socket(fd);
747 spawn_exit();
749 address[address_len] = 0; /* null terminate it */
751 result = tor_lookup_hostname(address, &ip);
752 /* Make 0.0.0.0 an error, so that we can use "0" to mean "no addr") */
753 if (!ip)
754 result = -1;
755 switch (result) {
756 case 1:
757 /* XXX result can never be 1, because we set it to -1 above on error */
758 log_fn(LOG_INFO,"Could not resolve dest addr %s (transient).",safe_str(address));
759 answer[0] = DNS_RESOLVE_FAILED_TRANSIENT;
760 break;
761 case -1:
762 log_fn(LOG_INFO,"Could not resolve dest addr %s (permanent).",safe_str(address));
763 answer[0] = DNS_RESOLVE_FAILED_PERMANENT;
764 break;
765 case 0:
766 log_fn(LOG_INFO,"Resolved address '%s'.",safe_str(address));
767 answer[0] = DNS_RESOLVE_SUCCEEDED;
768 break;
770 set_uint32(answer+1, ip);
771 if (write_all(fd, answer, 5, 1) != 5) {
772 log_fn(LOG_ERR,"writing answer failed. Child exiting.");
773 tor_close_socket(fd);
774 spawn_exit();
777 return 0; /* windows wants this function to return an int */
780 /** Launch a new DNS worker; return 0 on success, -1 on failure.
782 static int spawn_dnsworker(void) {
783 int *fdarray;
784 int fd;
785 connection_t *conn;
787 fdarray = tor_malloc(sizeof(int)*2);
788 if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray) < 0) {
789 log(LOG_ERR, "Couldn't construct socketpair: %s",
790 tor_socket_strerror(tor_socket_errno(-1)));
791 tor_cleanup();
792 tor_free(fdarray);
793 exit(1);
796 /* log_fn(LOG_NOTICE,"Before spawn: fdarray @%d has %d:%d", (int)fdarray, fdarray[0],fdarray[1]); */
798 fd = fdarray[0]; /* We copy this out here, since dnsworker_main may free fdarray */
799 spawn_func(dnsworker_main, (void*)fdarray);
800 log_fn(LOG_DEBUG,"just spawned a worker.");
801 #ifndef TOR_IS_MULTITHREADED
802 tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
803 tor_free(fdarray);
804 #endif
806 conn = connection_new(CONN_TYPE_DNSWORKER);
808 set_socket_nonblocking(fd);
810 /* set up conn so it's got all the data we need to remember */
811 conn->s = fd;
812 conn->address = tor_strdup("<unused>");
814 if (connection_add(conn) < 0) { /* no space, forget it */
815 log_fn(LOG_WARN,"connection_add failed. Giving up.");
816 connection_free(conn); /* this closes fd */
817 return -1;
820 conn->state = DNSWORKER_STATE_IDLE;
821 connection_start_reading(conn);
823 return 0; /* success */
826 /** If we have too many or too few DNS workers, spawn or kill some.
828 static void spawn_enough_dnsworkers(void) {
829 int num_dnsworkers_needed; /* aim to have 1 more than needed,
830 * but no less than min and no more than max */
831 connection_t *dnsconn;
833 /* XXX This may not be the best strategy. Maybe we should queue pending
834 * requests until the old ones finish or time out: otherwise, if
835 * the connection requests come fast enough, we never get any DNS done. -NM
836 * XXX But if we queue them, then the adversary can pile even more
837 * queries onto us, blocking legitimate requests for even longer.
838 * Maybe we should compromise and only kill if it's been at it for
839 * more than, e.g., 2 seconds. -RD
841 if (num_dnsworkers_busy == MAX_DNSWORKERS) {
842 /* We always want at least one worker idle.
843 * So find the oldest busy worker and kill it.
845 dnsconn = connection_get_by_type_state_lastwritten(CONN_TYPE_DNSWORKER,
846 DNSWORKER_STATE_BUSY);
847 tor_assert(dnsconn);
849 log_fn(LOG_WARN, "%d DNS workers are spawned; all are busy. Killing one.",
850 MAX_DNSWORKERS);
852 connection_mark_for_close(dnsconn);
853 num_dnsworkers_busy--;
854 num_dnsworkers--;
857 if (num_dnsworkers_busy >= MIN_DNSWORKERS)
858 num_dnsworkers_needed = num_dnsworkers_busy+1;
859 else
860 num_dnsworkers_needed = MIN_DNSWORKERS;
862 while (num_dnsworkers < num_dnsworkers_needed) {
863 if (spawn_dnsworker() < 0) {
864 log(LOG_WARN,"spawn_enough_dnsworkers(): spawn failed!");
865 return;
867 num_dnsworkers++;
870 while (num_dnsworkers > num_dnsworkers_busy+MAX_IDLE_DNSWORKERS) { /* too many idle? */
871 /* cull excess workers */
872 log_fn(LOG_NOTICE,"%d of %d dnsworkers are idle. Killing one.",
873 num_dnsworkers-num_dnsworkers_needed, num_dnsworkers);
874 dnsconn = connection_get_by_type_state(CONN_TYPE_DNSWORKER, DNSWORKER_STATE_IDLE);
875 tor_assert(dnsconn);
876 connection_mark_for_close(dnsconn);
877 num_dnsworkers--;