1 /* Copyright 2003-2004 Roger Dingledine.
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
3 /* See LICENSE for licensing information */
5 const char dns_c_id
[] = "$Id$";
9 * \brief Resolve hostnames in separate processes.
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.
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. */
98 last_rotation_time
=time(NULL
);
99 spawn_enough_dnsworkers();
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
;
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>
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
);
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
);
169 static void send_resolved_cell(connection_t
*conn
, uint8_t answer_type
)
171 char buf
[RELAY_PAYLOAD_SIZE
];
174 buf
[0] = answer_type
;
178 case RESOLVED_TYPE_IPV4
:
180 set_uint32(buf
+2, htonl(conn
->addr
));
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);
192 connection_edge_send_command(conn
, circuit_get_by_edge_conn(conn
),
193 RELAY_COMMAND_RESOLVED
, buf
, buflen
,
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. */
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
;
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,
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
;
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
);
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
;
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
);
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
);
279 circuit_detach_stream(circ
, exitconn
);
280 if (!exitconn
->marked_for_close
)
281 connection_free(exitconn
);
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
;
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
);
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! */
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);
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
);
355 log_fn(LOG_NOTICE
,"Address '%s' is not pending. Dropping.", conn
->address
);
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
;
367 log_fn(LOG_DEBUG
, "First connection (fd %d) no longer waiting for resolve of '%s'",
368 conn
->s
, conn
->address
);
371 for ( ; pend
->next
; pend
= pend
->next
) {
372 if (pend
->next
->conn
== conn
) {
374 pend
->next
= victim
->next
;
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
;
395 tor_assert(pend
->conn
!= conn
);
400 /** Log an error and abort if any connection waiting for a DNS resolve is
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
;
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
;
428 strlcpy(search
.address
, address
, sizeof(search
.address
));
430 resolve
= SPLAY_FIND(cache_tree
, &cache_root
, &search
);
432 log_fn(LOG_NOTICE
,"Address '%s' is not pending. Dropping.", address
);
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();
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'",
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
);
458 circuit_detach_stream(circ
, pendconn
);
459 connection_free(pendconn
);
460 resolve
->pending_connections
= pend
->next
;
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
;
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
);
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
;
507 strlcpy(search
.address
, address
, sizeof(search
.address
));
509 resolve
= SPLAY_FIND(cache_tree
, &cache_root
, &search
);
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
);
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",
526 tor_assert(resolve
->pending_connections
== NULL
);
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
533 /* tor_assert(resolve->state == CACHE_STATE_PENDING); */
535 resolve
->addr
= addr
;
536 if (outcome
== DNS_RESOLVE_SUCCEEDED
)
537 resolve
->state
= CACHE_STATE_VALID
;
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
);
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
);
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
);
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
);
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
);
583 circuit_detach_stream(circ
, pendconn
);
584 connection_free(pendconn
);
587 resolve
->pending_connections
= pend
->next
;
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
) {
605 tor_assert(conn
->type
== CONN_TYPE_DNSWORKER
);
606 connection_stop_writing(conn
);
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
617 num_dnsworkers_busy
--;
620 connection_mark_for_close(conn
);
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
) {
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.)",
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
);
672 spawn_enough_dnsworkers();
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
);
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
698 * - ADDRESSLEN [1 byte]
699 * - ADDRESS [ADDRESSLEN bytes]
700 * - The DNS worker does the lookup, and replies:
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
710 static int dnsworker_main(void *data
) {
711 char address
[MAX_ADDRESSLEN
];
712 unsigned char address_len
;
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 */
732 if ((r
= recv(fd
, &address_len
, 1, 0)) != 1) {
734 log_fn(LOG_INFO
,"DNS worker exiting because Tor process closed connection (either pruned idle dnsworker or died).");
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
);
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
);
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") */
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
;
761 log_fn(LOG_INFO
,"Could not resolve dest addr %s (permanent).",address
);
762 answer
[0] = DNS_RESOLVE_FAILED_PERMANENT
;
765 log_fn(LOG_INFO
,"Resolved address '%s'.",address
);
766 answer
[0] = DNS_RESOLVE_SUCCEEDED
;
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
);
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) {
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)));
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 */
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 */
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 */
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
);
848 log_fn(LOG_WARN
, "%d DNS workers are spawned; all are busy. Killing one.",
851 connection_mark_for_close(dnsconn
);
852 num_dnsworkers_busy
--;
856 if (num_dnsworkers_busy
>= MIN_DNSWORKERS
)
857 num_dnsworkers_needed
= num_dnsworkers_busy
+1;
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!");
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
);
875 connection_mark_for_close(dnsconn
);