1 /* Copyright 2006-2007 Niels Provos
2 * Copyright 2007-2012 Nick Mathewson and Niels Provos
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. The name of the author may not be used to endorse or promote products
13 * derived from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 /* Based on software by Adam Langly. Adam's original message:
30 * Adam Langley <agl@imperialviolet.org>
31 * http://www.imperialviolet.org/eventdns.html
34 * This software is Public Domain. To view a copy of the public domain dedication,
35 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
36 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
38 * I ask and expect, but do not require, that all derivative works contain an
39 * attribution similar to:
40 * Parts developed by Adam Langley <agl@imperialviolet.org>
42 * You may wish to replace the word "Parts" with something else depending on
43 * the amount of original code.
45 * (Derivative works does not include programs which link against, run or include
46 * the source verbatim in their source distributions)
51 #include <sys/types.h>
52 #include "event2/event-config.h"
54 #ifndef _FORTIFY_SOURCE
55 #define _FORTIFY_SOURCE 3
60 #ifdef _EVENT_HAVE_SYS_TIME_H
63 #ifdef _EVENT_HAVE_STDINT_H
69 #ifdef _EVENT_HAVE_UNISTD_H
80 #define _WIN32_IE 0x400
85 #include "event2/dns.h"
86 #include "event2/dns_struct.h"
87 #include "event2/dns_compat.h"
88 #include "event2/util.h"
89 #include "event2/event.h"
90 #include "event2/event_struct.h"
91 #include "event2/thread.h"
93 #include "event2/bufferevent.h"
94 #include "event2/bufferevent_struct.h"
95 #include "bufferevent-internal.h"
97 #include "defer-internal.h"
98 #include "log-internal.h"
99 #include "mm-internal.h"
100 #include "strlcpy-internal.h"
101 #include "ipv6-internal.h"
102 #include "util-internal.h"
103 #include "evthread-internal.h"
106 #include <winsock2.h>
108 #include <iphlpapi.h>
111 #include <sys/socket.h>
112 #include <netinet/in.h>
113 #include <arpa/inet.h>
116 #ifdef _EVENT_HAVE_NETINET_IN6_H
117 #include <netinet/in6.h>
120 #define EVDNS_LOG_DEBUG 0
121 #define EVDNS_LOG_WARN 1
122 #define EVDNS_LOG_MSG 2
124 #ifndef HOST_NAME_MAX
125 #define HOST_NAME_MAX 255
131 #define MIN(a,b) ((a)<(b)?(a):(b))
133 #define ASSERT_VALID_REQUEST(req) \
134 EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
136 #define u64 ev_uint64_t
137 #define u32 ev_uint32_t
138 #define u16 ev_uint16_t
139 #define u8 ev_uint8_t
141 /* maximum number of addresses from a single packet */
142 /* that we bother recording */
143 #define MAX_V4_ADDRS 32
144 #define MAX_V6_ADDRS 32
145 #define MAX_TXT_RRS 32
146 #define MAX_TXT_SIZE 255
149 #define TYPE_A EVDNS_TYPE_A
151 #define TYPE_PTR EVDNS_TYPE_PTR
152 #define TYPE_SOA EVDNS_TYPE_SOA
153 #define TYPE_AAAA EVDNS_TYPE_AAAA
154 #define TYPE_TXT EVDNS_TYPE_TXT
156 #define CLASS_INET EVDNS_CLASS_INET
158 /* Persistent handle. We keep this separate from 'struct request' since we
159 * need some object to last for as long as an evdns_request is outstanding so
160 * that it can be canceled, whereas a search request can lead to multiple
161 * 'struct request' instances being created over its lifetime. */
162 struct evdns_request
{
163 struct request
*current_req
;
164 struct evdns_base
*base
;
166 int pending_cb
; /* Waiting for its callback to be invoked; not
167 * owned by event base any more. */
169 /* elements used by the searching code */
171 struct search_state
*search_state
;
172 char *search_origname
; /* needs to be free()ed */
177 u8
*request
; /* the dns packet data */
178 u8 request_type
; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
179 unsigned int request_len
;
181 int tx_count
; /* the number of times that this packet has been sent */
182 void *user_pointer
; /* the pointer given to us for this request */
183 evdns_callback_type user_callback
;
184 struct nameserver
*ns
; /* the server which we last sent it */
186 /* these objects are kept in a circular list */
187 /* XXX We could turn this into a CIRCLEQ. */
188 struct request
*next
, *prev
;
190 struct event timeout_event
;
192 u16 trans_id
; /* the transaction id */
193 unsigned request_appended
:1; /* true if the request pointer is data which follows this struct */
194 unsigned transmit_me
:1; /* needs to be transmitted */
196 /* XXXX This is a horrible hack. */
197 char **put_cname_in_ptr
; /* store the cname here if we get one. */
199 struct evdns_base
*base
;
201 struct evdns_request
*handle
;
206 unsigned int have_answer
: 1;
210 u32 addresses
[MAX_V4_ADDRS
];
214 struct in6_addr addresses
[MAX_V6_ADDRS
];
217 char name
[HOST_NAME_MAX
];
221 struct txt_record records
[MAX_TXT_RRS
];
227 evutil_socket_t socket
; /* a connected UDP socket */
228 struct sockaddr_storage address
;
229 ev_socklen_t addrlen
;
230 int failed_times
; /* number of times which we have given this server a chance */
231 int timedout
; /* number of times in a row a request has timed out */
233 /* these objects are kept in a circular list */
234 struct nameserver
*next
, *prev
;
235 struct event timeout_event
; /* used to keep the timeout for */
236 /* when we next probe this server. */
237 /* Valid if state == 0 */
238 /* Outstanding probe request for this nameserver, if any */
239 struct evdns_request
*probe_request
;
240 char state
; /* zero if we think that this server is down */
241 char choked
; /* true if we have an EAGAIN from this server's socket */
242 char write_waiting
; /* true if we are waiting for EV_WRITE events */
243 struct evdns_base
*base
;
247 /* Represents a local port where we're listening for DNS requests. Right now, */
248 /* only UDP is supported. */
249 struct evdns_server_port
{
250 evutil_socket_t socket
; /* socket we use to read queries and write replies. */
251 int refcnt
; /* reference count. */
252 char choked
; /* Are we currently blocked from writing? */
253 char closing
; /* Are we trying to close this port, pending writes? */
254 evdns_request_callback_fn_type user_callback
; /* Fn to handle requests */
255 void *user_data
; /* Opaque pointer passed to user_callback */
256 struct event event
; /* Read/write event */
257 /* circular list of replies that we want to write. */
258 struct server_request
*pending_replies
;
259 struct event_base
*event_base
;
261 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
266 /* Represents part of a reply being built. (That is, a single RR.) */
267 struct server_reply_item
{
268 struct server_reply_item
*next
; /* next item in sequence. */
269 char *name
; /* name part of the RR */
270 u16 type
; /* The RR type */
271 u16
class; /* The RR class (usually CLASS_INET) */
272 u32 ttl
; /* The RR TTL */
273 char is_name
; /* True iff data is a label */
274 u16 datalen
; /* Length of data; -1 if data is a label */
275 void *data
; /* The contents of the RR */
278 /* Represents a request that we've received as a DNS server, and holds */
279 /* the components of the reply as we're constructing it. */
280 struct server_request
{
281 /* Pointers to the next and previous entries on the list of replies */
282 /* that we're waiting to write. Only set if we have tried to respond */
283 /* and gotten EAGAIN. */
284 struct server_request
*next_pending
;
285 struct server_request
*prev_pending
;
287 u16 trans_id
; /* Transaction id. */
288 struct evdns_server_port
*port
; /* Which port received this request on? */
289 struct sockaddr_storage addr
; /* Where to send the response */
290 ev_socklen_t addrlen
; /* length of addr */
292 int n_answer
; /* how many answer RRs have been set? */
293 int n_authority
; /* how many authority RRs have been set? */
294 int n_additional
; /* how many additional RRs have been set? */
296 struct server_reply_item
*answer
; /* linked list of answer RRs */
297 struct server_reply_item
*authority
; /* linked list of authority RRs */
298 struct server_reply_item
*additional
; /* linked list of additional RRs */
300 /* Constructed response. Only set once we're ready to send a reply. */
301 /* Once this is set, the RR fields are cleared, and no more should be set. */
305 /* Caller-visible fields: flags, questions. */
306 struct evdns_server_request base
;
310 /* An array of n_req_heads circular lists for inflight requests.
311 * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
313 struct request
**req_heads
;
314 /* A circular list of requests that we're waiting to send, but haven't
315 * sent yet because there are too many requests inflight */
316 struct request
*req_waiting_head
;
317 /* A circular list of nameservers. */
318 struct nameserver
*server_head
;
321 struct event_base
*event_base
;
323 /* The number of good nameservers that we have */
324 int global_good_nameservers
;
326 /* inflight requests are contained in the req_head list */
327 /* and are actually going out across the network */
328 int global_requests_inflight
;
329 /* requests which aren't inflight are in the waiting list */
330 /* and are counted here */
331 int global_requests_waiting
;
333 int global_max_requests_inflight
;
335 struct timeval global_timeout
; /* 5 seconds by default */
336 int global_max_reissues
; /* a reissue occurs when we get some errors from the server */
337 int global_max_retransmits
; /* number of times we'll retransmit a request which timed out */
338 /* number of timeouts in a row before we consider this server to be down */
339 int global_max_nameserver_timeout
;
340 /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
341 int global_randomize_case
;
343 /* The first time that a nameserver fails, how long do we wait before
344 * probing to see if it has returned? */
345 struct timeval global_nameserver_probe_initial_timeout
;
347 /** Port to bind to for outgoing DNS packets. */
348 struct sockaddr_storage global_outgoing_address
;
349 /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
350 ev_socklen_t global_outgoing_addrlen
;
352 struct timeval global_getaddrinfo_allow_skew
;
354 int getaddrinfo_ipv4_timeouts
;
355 int getaddrinfo_ipv6_timeouts
;
356 int getaddrinfo_ipv4_answered
;
357 int getaddrinfo_ipv6_answered
;
359 struct search_state
*global_search_state
;
361 TAILQ_HEAD(hosts_list
, hosts_entry
) hostsdb
;
363 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
369 TAILQ_ENTRY(hosts_entry
) next
;
372 struct sockaddr_in sin
;
373 struct sockaddr_in6 sin6
;
379 static struct evdns_base
*current_base
= NULL
;
382 evdns_get_global_base(void)
387 /* Given a pointer to an evdns_server_request, get the corresponding */
388 /* server_request. */
389 #define TO_SERVER_REQUEST(base_ptr) \
390 ((struct server_request*) \
391 (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
393 #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
395 static struct nameserver
*nameserver_pick(struct evdns_base
*base
);
396 static void evdns_request_insert(struct request
*req
, struct request
**head
);
397 static void evdns_request_remove(struct request
*req
, struct request
**head
);
398 static void nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
399 static int evdns_transmit(struct evdns_base
*base
);
400 static int evdns_request_transmit(struct request
*req
);
401 static void nameserver_send_probe(struct nameserver
*const ns
);
402 static void search_request_finished(struct evdns_request
*const);
403 static int search_try_next(struct evdns_request
*const req
);
404 static struct request
*search_request_new(struct evdns_base
*base
, struct evdns_request
*handle
, int type
, const char *const name
, int flags
, evdns_callback_type user_callback
, void *user_arg
);
405 static void evdns_requests_pump_waiting_queue(struct evdns_base
*base
);
406 static u16
transaction_id_pick(struct evdns_base
*base
);
407 static struct request
*request_new(struct evdns_base
*base
, struct evdns_request
*handle
, int type
, const char *name
, int flags
, evdns_callback_type callback
, void *ptr
);
408 static void request_submit(struct request
*const req
);
410 static int server_request_free(struct server_request
*req
);
411 static void server_request_free_answers(struct server_request
*req
);
412 static void server_port_free(struct evdns_server_port
*port
);
413 static void server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
414 static int evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
);
415 static int evdns_base_set_option_impl(struct evdns_base
*base
,
416 const char *option
, const char *val
, int flags
);
417 static void evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
);
419 static int strtoint(const char *const str
);
421 #ifdef _EVENT_DISABLE_THREAD_SUPPORT
422 #define EVDNS_LOCK(base) _EVUTIL_NIL_STMT
423 #define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT
424 #define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT
426 #define EVDNS_LOCK(base) \
427 EVLOCK_LOCK((base)->lock, 0)
428 #define EVDNS_UNLOCK(base) \
429 EVLOCK_UNLOCK((base)->lock, 0)
430 #define ASSERT_LOCKED(base) \
431 EVLOCK_ASSERT_LOCKED((base)->lock)
435 default_evdns_log_fn(int warning
, const char *buf
)
437 if (warning
== EVDNS_LOG_WARN
)
438 event_warnx("[evdns] %s", buf
);
439 else if (warning
== EVDNS_LOG_MSG
)
440 event_msgx("[evdns] %s", buf
);
442 event_debug(("[evdns] %s", buf
));
445 static evdns_debug_log_fn_type evdns_log_fn
= NULL
;
448 evdns_set_log_fn(evdns_debug_log_fn_type fn
)
454 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
456 #define EVDNS_LOG_CHECK
459 static void _evdns_log(int warn
, const char *fmt
, ...) EVDNS_LOG_CHECK
;
461 _evdns_log(int warn
, const char *fmt
, ...)
468 evutil_vsnprintf(buf
, sizeof(buf
), fmt
, args
);
471 if (warn
== EVDNS_LOG_MSG
)
472 warn
= EVDNS_LOG_WARN
;
473 evdns_log_fn(warn
, buf
);
475 default_evdns_log_fn(warn
, buf
);
480 #define log _evdns_log
482 /* This walks the list of inflight requests to find the */
483 /* one with a matching transaction id. Returns NULL on */
485 static struct request
*
486 request_find_from_trans_id(struct evdns_base
*base
, u16 trans_id
) {
487 struct request
*req
= REQ_HEAD(base
, trans_id
);
488 struct request
*const started_at
= req
;
494 if (req
->trans_id
== trans_id
) return req
;
496 } while (req
!= started_at
);
502 /* a libevent callback function which is called when a nameserver */
503 /* has gone down and we want to test if it has came back to life yet */
505 nameserver_prod_callback(evutil_socket_t fd
, short events
, void *arg
) {
506 struct nameserver
*const ns
= (struct nameserver
*) arg
;
510 EVDNS_LOCK(ns
->base
);
511 nameserver_send_probe(ns
);
512 EVDNS_UNLOCK(ns
->base
);
515 /* a libevent callback which is called when a nameserver probe (to see if */
516 /* it has come back to life) times out. We increment the count of failed_times */
517 /* and wait longer to send the next probe packet. */
519 nameserver_probe_failed(struct nameserver
*const ns
) {
520 struct timeval timeout
;
523 ASSERT_LOCKED(ns
->base
);
524 (void) evtimer_del(&ns
->timeout_event
);
525 if (ns
->state
== 1) {
526 /* This can happen if the nameserver acts in a way which makes us mark */
527 /* it as bad and then starts sending good replies. */
531 #define MAX_PROBE_TIMEOUT 3600
532 #define TIMEOUT_BACKOFF_FACTOR 3
534 memcpy(&timeout
, &ns
->base
->global_nameserver_probe_initial_timeout
,
535 sizeof(struct timeval
));
536 for (i
=ns
->failed_times
; i
> 0 && timeout
.tv_sec
< MAX_PROBE_TIMEOUT
; --i
) {
537 timeout
.tv_sec
*= TIMEOUT_BACKOFF_FACTOR
;
538 timeout
.tv_usec
*= TIMEOUT_BACKOFF_FACTOR
;
539 if (timeout
.tv_usec
> 1000000) {
540 timeout
.tv_sec
+= timeout
.tv_usec
/ 1000000;
541 timeout
.tv_usec
%= 1000000;
544 if (timeout
.tv_sec
> MAX_PROBE_TIMEOUT
) {
545 timeout
.tv_sec
= MAX_PROBE_TIMEOUT
;
551 if (evtimer_add(&ns
->timeout_event
, &timeout
) < 0) {
554 "Error from libevent when adding timer event for %s",
555 evutil_format_sockaddr_port(
556 (struct sockaddr
*)&ns
->address
,
557 addrbuf
, sizeof(addrbuf
)));
561 /* called when a nameserver has been deemed to have failed. For example, too */
562 /* many packets have timed out etc */
564 nameserver_failed(struct nameserver
*const ns
, const char *msg
) {
565 struct request
*req
, *started_at
;
566 struct evdns_base
*base
= ns
->base
;
571 /* if this nameserver has already been marked as failed */
572 /* then don't do anything */
573 if (!ns
->state
) return;
575 log(EVDNS_LOG_MSG
, "Nameserver %s has failed: %s",
576 evutil_format_sockaddr_port(
577 (struct sockaddr
*)&ns
->address
,
578 addrbuf
, sizeof(addrbuf
)),
581 base
->global_good_nameservers
--;
582 EVUTIL_ASSERT(base
->global_good_nameservers
>= 0);
583 if (base
->global_good_nameservers
== 0) {
584 log(EVDNS_LOG_MSG
, "All nameservers have failed");
588 ns
->failed_times
= 1;
590 if (evtimer_add(&ns
->timeout_event
,
591 &base
->global_nameserver_probe_initial_timeout
) < 0) {
593 "Error from libevent when adding timer event for %s",
594 evutil_format_sockaddr_port(
595 (struct sockaddr
*)&ns
->address
,
596 addrbuf
, sizeof(addrbuf
)));
600 /* walk the list of inflight requests to see if any can be reassigned to */
601 /* a different server. Requests in the waiting queue don't have a */
602 /* nameserver assigned yet */
604 /* if we don't have *any* good nameservers then there's no point */
605 /* trying to reassign requests to one */
606 if (!base
->global_good_nameservers
) return;
608 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
609 req
= started_at
= base
->req_heads
[i
];
612 if (req
->tx_count
== 0 && req
->ns
== ns
) {
613 /* still waiting to go out, can be moved */
614 /* to another server */
615 req
->ns
= nameserver_pick(base
);
618 } while (req
!= started_at
);
624 nameserver_up(struct nameserver
*const ns
)
627 ASSERT_LOCKED(ns
->base
);
628 if (ns
->state
) return;
629 log(EVDNS_LOG_MSG
, "Nameserver %s is back up",
630 evutil_format_sockaddr_port(
631 (struct sockaddr
*)&ns
->address
,
632 addrbuf
, sizeof(addrbuf
)));
633 evtimer_del(&ns
->timeout_event
);
634 if (ns
->probe_request
) {
635 evdns_cancel_request(ns
->base
, ns
->probe_request
);
636 ns
->probe_request
= NULL
;
639 ns
->failed_times
= 0;
641 ns
->base
->global_good_nameservers
++;
645 request_trans_id_set(struct request
*const req
, const u16 trans_id
) {
646 req
->trans_id
= trans_id
;
647 *((u16
*) req
->request
) = htons(trans_id
);
650 /* Called to remove a request from a list and dealloc it. */
651 /* head is a pointer to the head of the list it should be */
652 /* removed from or NULL if the request isn't in a list. */
653 /* when free_handle is one, free the handle as well. */
655 request_finished(struct request
*const req
, struct request
**head
, int free_handle
) {
656 struct evdns_base
*base
= req
->base
;
657 int was_inflight
= (head
!= &base
->req_waiting_head
);
659 ASSERT_VALID_REQUEST(req
);
662 evdns_request_remove(req
, head
);
664 log(EVDNS_LOG_DEBUG
, "Removing timeout for request %p", req
);
666 evtimer_del(&req
->timeout_event
);
667 base
->global_requests_inflight
--;
669 base
->global_requests_waiting
--;
671 /* it was initialized during request_new / evtimer_assign */
672 event_debug_unassign(&req
->timeout_event
);
674 if (!req
->request_appended
) {
675 /* need to free the request data on it's own */
676 mm_free(req
->request
);
678 /* the request data is appended onto the header */
679 /* so everything gets free()ed when we: */
683 EVUTIL_ASSERT(req
->handle
->current_req
== req
);
686 search_request_finished(req
->handle
);
687 req
->handle
->current_req
= NULL
;
688 if (! req
->handle
->pending_cb
) {
689 /* If we're planning to run the callback,
690 * don't free the handle until later. */
691 mm_free(req
->handle
);
693 req
->handle
= NULL
; /* If we have a bug, let's crash
696 req
->handle
->current_req
= NULL
;
702 evdns_requests_pump_waiting_queue(base
);
706 /* This is called when a server returns a funny error code. */
707 /* We try the request again with another server. */
711 /* 1 failed/reissue is pointless */
713 request_reissue(struct request
*req
) {
714 const struct nameserver
*const last_ns
= req
->ns
;
715 ASSERT_LOCKED(req
->base
);
716 ASSERT_VALID_REQUEST(req
);
717 /* the last nameserver should have been marked as failing */
718 /* by the caller of this function, therefore pick will try */
719 /* not to return it */
720 req
->ns
= nameserver_pick(req
->base
);
721 if (req
->ns
== last_ns
) {
722 /* ... but pick did return it */
723 /* not a lot of point in trying again with the */
728 req
->reissue_count
++;
730 req
->transmit_me
= 1;
735 /* this function looks for space on the inflight queue and promotes */
736 /* requests from the waiting queue if it can. */
738 evdns_requests_pump_waiting_queue(struct evdns_base
*base
) {
740 while (base
->global_requests_inflight
< base
->global_max_requests_inflight
&&
741 base
->global_requests_waiting
) {
743 /* move a request from the waiting queue to the inflight queue */
744 EVUTIL_ASSERT(base
->req_waiting_head
);
745 req
= base
->req_waiting_head
;
746 evdns_request_remove(req
, &base
->req_waiting_head
);
748 base
->global_requests_waiting
--;
749 base
->global_requests_inflight
++;
751 req
->ns
= nameserver_pick(base
);
752 request_trans_id_set(req
, transaction_id_pick(base
));
754 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
755 evdns_request_transmit(req
);
756 evdns_transmit(base
);
760 /* TODO(nickm) document */
761 struct deferred_reply_callback
{
762 struct deferred_cb deferred
;
763 struct evdns_request
*handle
;
768 evdns_callback_type user_callback
;
773 reply_run_callback(struct deferred_cb
*d
, void *user_pointer
)
775 struct deferred_reply_callback
*cb
=
776 EVUTIL_UPCAST(d
, struct deferred_reply_callback
, deferred
);
778 switch (cb
->request_type
) {
781 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv4_A
,
782 cb
->reply
.data
.a
.addrcount
, cb
->ttl
,
783 cb
->reply
.data
.a
.addresses
,
786 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
789 if (cb
->have_reply
) {
790 char *name
= cb
->reply
.data
.ptr
.name
;
791 cb
->user_callback(DNS_ERR_NONE
, DNS_PTR
, 1, cb
->ttl
,
792 &name
, user_pointer
);
794 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
799 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv6_AAAA
,
800 cb
->reply
.data
.aaaa
.addrcount
, cb
->ttl
,
801 cb
->reply
.data
.aaaa
.addresses
,
804 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
808 cb
->user_callback(DNS_ERR_NONE
, DNS_TXT
,
809 cb
->reply
.data
.txt
.recordscount
, cb
->ttl
,
810 cb
->reply
.data
.txt
.records
,
813 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
819 if (cb
->handle
&& cb
->handle
->pending_cb
) {
827 reply_schedule_callback(struct request
*const req
, u32 ttl
, u32 err
, struct reply
*reply
)
829 struct deferred_reply_callback
*d
= mm_calloc(1, sizeof(*d
));
832 event_warn("%s: Couldn't allocate space for deferred callback.",
837 ASSERT_LOCKED(req
->base
);
839 d
->request_type
= req
->request_type
;
840 d
->user_callback
= req
->user_callback
;
845 memcpy(&d
->reply
, reply
, sizeof(struct reply
));
849 req
->handle
->pending_cb
= 1;
850 d
->handle
= req
->handle
;
853 event_deferred_cb_init(&d
->deferred
, reply_run_callback
,
855 event_deferred_cb_schedule(
856 event_base_get_deferred_cb_queue(req
->base
->event_base
),
860 /* this processes a parsed reply packet */
862 reply_handle(struct request
*const req
, u16 flags
, u32 ttl
, struct reply
*reply
) {
865 static const int error_codes
[] = {
866 DNS_ERR_FORMAT
, DNS_ERR_SERVERFAILED
, DNS_ERR_NOTEXIST
,
867 DNS_ERR_NOTIMPL
, DNS_ERR_REFUSED
870 ASSERT_LOCKED(req
->base
);
871 ASSERT_VALID_REQUEST(req
);
873 if (flags
& 0x020f || !reply
|| !reply
->have_answer
) {
874 /* there was an error */
875 if (flags
& 0x0200) {
876 error
= DNS_ERR_TRUNCATED
;
877 } else if (flags
& 0x000f) {
878 u16 error_code
= (flags
& 0x000f) - 1;
879 if (error_code
> 4) {
880 error
= DNS_ERR_UNKNOWN
;
882 error
= error_codes
[error_code
];
884 } else if (reply
&& !reply
->have_answer
) {
885 error
= DNS_ERR_NODATA
;
887 error
= DNS_ERR_UNKNOWN
;
891 case DNS_ERR_NOTIMPL
:
892 case DNS_ERR_REFUSED
:
893 /* we regard these errors as marking a bad nameserver */
894 if (req
->reissue_count
< req
->base
->global_max_reissues
) {
896 evutil_snprintf(msg
, sizeof(msg
), "Bad response %d (%s)",
897 error
, evdns_err_to_string(error
));
898 nameserver_failed(req
->ns
, msg
);
899 if (!request_reissue(req
)) return;
902 case DNS_ERR_SERVERFAILED
:
903 /* rcode 2 (servfailed) sometimes means "we
904 * are broken" and sometimes (with some binds)
905 * means "that request was very confusing."
906 * Treat this as a timeout, not a failure.
908 log(EVDNS_LOG_DEBUG
, "Got a SERVERFAILED from nameserver"
909 "at %s; will allow the request to time out.",
910 evutil_format_sockaddr_port(
911 (struct sockaddr
*)&req
->ns
->address
,
912 addrbuf
, sizeof(addrbuf
)));
915 /* we got a good reply from the nameserver: it is up. */
916 if (req
->handle
== req
->ns
->probe_request
) {
917 /* Avoid double-free */
918 req
->ns
->probe_request
= NULL
;
921 nameserver_up(req
->ns
);
924 if (req
->handle
->search_state
&&
925 req
->request_type
!= TYPE_PTR
) {
926 /* if we have a list of domains to search in,
927 * try the next one */
928 if (!search_try_next(req
->handle
)) {
929 /* a new request was issued so this
930 * request is finished and */
931 /* the user callback will be made when
932 * that request (or a */
933 /* child of it) finishes. */
938 /* all else failed. Pass the failure up */
939 reply_schedule_callback(req
, ttl
, error
, NULL
);
940 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
942 /* all ok, tell the user */
943 reply_schedule_callback(req
, ttl
, 0, reply
);
944 if (req
->handle
== req
->ns
->probe_request
)
945 req
->ns
->probe_request
= NULL
; /* Avoid double-free */
946 nameserver_up(req
->ns
);
947 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
952 name_parse(u8
*packet
, int length
, int *idx
, char *name_out
, int name_out_len
) {
956 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (0)
957 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (0)
958 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
961 const char *const end
= name_out
+ name_out_len
;
963 /* Normally, names are a series of length prefixed strings terminated */
964 /* with a length of 0 (the lengths are u8's < 63). */
965 /* However, the length can start with a pair of 1 bits and that */
966 /* means that the next 14 bits are a pointer within the current */
971 if (j
>= length
) return -1;
973 if (!label_len
) break;
974 if (label_len
& 0xc0) {
977 if (name_end
< 0) name_end
= j
;
978 j
= (((int)label_len
& 0x3f) << 8) + ptr_low
;
979 /* Make sure that the target offset is in-bounds. */
980 if (j
< 0 || j
>= length
) return -1;
981 /* If we've jumped more times than there are characters in the
982 * message, we must have a loop. */
983 if (++ptr_count
> length
) return -1;
986 if (label_len
> 63) return -1;
987 if (cp
!= name_out
) {
988 if (cp
+ 1 >= end
) return -1;
991 if (cp
+ label_len
>= end
) return -1;
992 memcpy(cp
, packet
+ j
, label_len
);
996 if (cp
>= end
) return -1;
1007 /* parses a raw request from a nameserver */
1009 reply_parse(struct evdns_base
*base
, u8
*packet
, int length
) {
1010 int j
= 0, k
= 0; /* index into packet */
1011 u16 _t
; /* used by the macros */
1012 u32 _t32
; /* used by the macros */
1013 char tmp_name
[256], cmp_name
[256]; /* used by the macros */
1014 int name_matches
= 0;
1016 u16 trans_id
, questions
, answers
, authority
, additional
, datalength
;
1018 u32 ttl
, ttl_r
= 0xffffffff;
1020 struct request
*req
= NULL
;
1023 ASSERT_LOCKED(base
);
1031 (void) authority
; /* suppress "unused variable" warnings. */
1032 (void) additional
; /* suppress "unused variable" warnings. */
1034 req
= request_find_from_trans_id(base
, trans_id
);
1035 if (!req
) return -1;
1036 EVUTIL_ASSERT(req
->base
== base
);
1038 memset(&reply
, 0, sizeof(reply
));
1040 /* If it's not an answer, it doesn't correspond to any request. */
1041 if (!(flags
& 0x8000)) return -1; /* must be an answer */
1042 if ((flags
& 0x020f) && (flags
& 0x020f) != DNS_ERR_NOTEXIST
) {
1043 /* there was an error and it's not NXDOMAIN */
1046 /* if (!answers) return; */ /* must have an answer of some form */
1048 /* This macro skips a name in the DNS reply. */
1050 do { tmp_name[0] = '\0'; \
1051 if (name_parse(packet, length, &j, tmp_name, \
1052 sizeof(tmp_name))<0) \
1056 do { tmp_name[0] = '\0'; \
1057 cmp_name[0] = '\0'; \
1059 if (name_parse(packet, length, &j, tmp_name, \
1060 sizeof(tmp_name))<0) \
1062 if (name_parse(req->request, req->request_len, &k, \
1063 cmp_name, sizeof(cmp_name))<0) \
1065 if (base->global_randomize_case) { \
1066 if (strcmp(tmp_name, cmp_name) == 0) \
1069 if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0) \
1074 reply
.type
= req
->request_type
;
1076 /* skip over each question in the reply */
1077 for (i
= 0; i
< questions
; ++i
) {
1078 /* the question looks like
1079 * <label:name><u16:type><u16:class>
1083 if (j
> length
) goto err
;
1089 /* now we have the answer section which looks like
1090 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
1093 for (i
= 0; i
< answers
; ++i
) {
1102 EVUTIL_ASSERT(INT_MAX
> 0xFFFF + 0xFFFF);
1103 if (datalength
<= 0U || j
+ datalength
> length
)
1105 if (type
== TYPE_A
&& class == CLASS_INET
) {
1106 int addrcount
, addrtocopy
;
1107 if (req
->request_type
!= TYPE_A
) {
1108 j
+= datalength
; continue;
1110 if ((datalength
& 3) != 0) /* not an even number of As. */
1112 addrcount
= datalength
>> 2;
1113 addrtocopy
= MIN(MAX_V4_ADDRS
- reply
.data
.a
.addrcount
, (unsigned)addrcount
);
1115 ttl_r
= MIN(ttl_r
, ttl
);
1116 /* we only bother with the first four addresses. */
1117 if (j
+ 4*addrtocopy
> length
) goto err
;
1118 memcpy(&reply
.data
.a
.addresses
[reply
.data
.a
.addrcount
],
1119 packet
+ j
, 4*addrtocopy
);
1121 reply
.data
.a
.addrcount
+= addrtocopy
;
1122 reply
.have_answer
= 1;
1123 if (reply
.data
.a
.addrcount
== MAX_V4_ADDRS
) break;
1124 } else if (type
== TYPE_PTR
&& class == CLASS_INET
) {
1125 if (req
->request_type
!= TYPE_PTR
) {
1126 j
+= datalength
; continue;
1128 if (name_parse(packet
, length
, &j
, reply
.data
.ptr
.name
,
1129 sizeof(reply
.data
.ptr
.name
))<0)
1131 ttl_r
= MIN(ttl_r
, ttl
);
1132 reply
.have_answer
= 1;
1134 } else if (type
== TYPE_CNAME
) {
1135 char cname
[HOST_NAME_MAX
];
1136 if (!req
->put_cname_in_ptr
|| *req
->put_cname_in_ptr
) {
1137 j
+= datalength
; continue;
1139 if (name_parse(packet
, length
, &j
, cname
,
1142 *req
->put_cname_in_ptr
= mm_strdup(cname
);
1143 } else if (type
== TYPE_AAAA
&& class == CLASS_INET
) {
1144 int addrcount
, addrtocopy
;
1145 if (req
->request_type
!= TYPE_AAAA
) {
1146 j
+= datalength
; continue;
1148 if ((datalength
& 15) != 0) /* not an even number of AAAAs. */
1150 addrcount
= datalength
>> 4; /* each address is 16 bytes long */
1151 addrtocopy
= MIN(MAX_V6_ADDRS
- reply
.data
.aaaa
.addrcount
, (unsigned)addrcount
);
1152 ttl_r
= MIN(ttl_r
, ttl
);
1154 /* we only bother with the first four addresses. */
1155 if (j
+ 16*addrtocopy
> length
) goto err
;
1156 memcpy(&reply
.data
.aaaa
.addresses
[reply
.data
.aaaa
.addrcount
],
1157 packet
+ j
, 16*addrtocopy
);
1158 reply
.data
.aaaa
.addrcount
+= addrtocopy
;
1160 reply
.have_answer
= 1;
1161 if (reply
.data
.aaaa
.addrcount
== MAX_V6_ADDRS
) break;
1162 } else if (type
== TYPE_TXT
) {
1163 if (req
->request_type
!= TYPE_TXT
) {
1164 j
+= datalength
; continue;
1166 size_t mergedlen
= 0U;
1167 size_t mergenum
= 0U;
1168 while (mergedlen
+ mergenum
< datalength
) {
1170 txtlen
= packet
[j
+ mergedlen
+ mergenum
];
1171 if (mergedlen
+ txtlen
> sizeof reply
.data
.txt
.records
[0].txt
||
1172 datalength
<= mergedlen
+ txtlen
|| j
+ mergedlen
+ txtlen
>= length
) {
1175 memcpy(reply
.data
.txt
.records
[reply
.data
.txt
.recordscount
].txt
+ mergedlen
,
1176 &packet
[j
+ mergedlen
+ mergenum
+ 1], txtlen
);
1177 mergedlen
+= txtlen
;
1180 reply
.data
.txt
.records
[reply
.data
.txt
.recordscount
].len
= mergedlen
;
1181 reply
.data
.txt
.recordscount
++;
1182 ttl_r
= MIN(ttl_r
, ttl
);
1183 reply
.have_answer
= 1;
1185 if (reply
.data
.txt
.recordscount
>= MAX_TXT_RRS
) {
1189 /* skip over any other type of resource */
1194 if (!reply
.have_answer
) {
1195 for (i
= 0; i
< authority
; ++i
) {
1202 if (type
== TYPE_SOA
&& class == CLASS_INET
) {
1203 u32 serial
, refresh
, retry
, expire
, minimum
;
1215 ttl_r
= MIN(ttl_r
, ttl
);
1216 ttl_r
= MIN(ttl_r
, minimum
);
1218 /* skip over any other type of resource */
1224 if (ttl_r
== 0xffffffff)
1227 reply_handle(req
, flags
, ttl_r
, &reply
);
1231 reply_handle(req
, flags
, 0, NULL
);
1235 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1236 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1239 request_parse(u8
*packet
, int length
, struct evdns_server_port
*port
, struct sockaddr
*addr
, ev_socklen_t addrlen
)
1241 int j
= 0; /* index into packet */
1242 u16 _t
; /* used by the macros */
1243 char tmp_name
[256]; /* used by the macros */
1246 u16 trans_id
, flags
, questions
, answers
, authority
, additional
;
1247 struct server_request
*server_req
= NULL
;
1249 ASSERT_LOCKED(port
);
1251 /* Get the header fields */
1262 if (flags
& 0x8000) return -1; /* Must not be an answer. */
1263 flags
&= 0x0110; /* Only RD and CD get preserved. */
1265 server_req
= mm_malloc(sizeof(struct server_request
));
1266 if (server_req
== NULL
) return -1;
1267 memset(server_req
, 0, sizeof(struct server_request
));
1269 server_req
->trans_id
= trans_id
;
1270 memcpy(&server_req
->addr
, addr
, addrlen
);
1271 server_req
->addrlen
= addrlen
;
1273 server_req
->base
.flags
= flags
;
1274 server_req
->base
.nquestions
= 0;
1275 server_req
->base
.questions
= mm_calloc(sizeof(struct evdns_server_question
*), questions
);
1276 if (server_req
->base
.questions
== NULL
)
1279 for (i
= 0; i
< questions
; ++i
) {
1281 struct evdns_server_question
*q
;
1283 if (name_parse(packet
, length
, &j
, tmp_name
, sizeof(tmp_name
))<0)
1287 namelen
= (int)strlen(tmp_name
);
1288 q
= mm_malloc(sizeof(struct evdns_server_question
) + namelen
);
1292 q
->dns_question_class
= class;
1293 memcpy(q
->name
, tmp_name
, namelen
+1);
1294 server_req
->base
.questions
[server_req
->base
.nquestions
++] = q
;
1297 /* Ignore answers, authority, and additional. */
1299 server_req
->port
= port
;
1302 /* Only standard queries are supported. */
1303 if (flags
& 0x7800) {
1304 evdns_server_request_respond(&(server_req
->base
), DNS_ERR_NOTIMPL
);
1308 port
->user_callback(&(server_req
->base
), port
->user_data
);
1313 if (server_req
->base
.questions
) {
1314 for (i
= 0; i
< server_req
->base
.nquestions
; ++i
)
1315 mm_free(server_req
->base
.questions
[i
]);
1316 mm_free(server_req
->base
.questions
);
1318 mm_free(server_req
);
1328 static int (*rand_init_function
)(void) = evutil_secure_rng_init
;
1330 static void (*rand_bytes_function
)(void *buf
, size_t n
) =
1331 evutil_secure_rng_get_bytes
;
1334 evdns_set_transaction_id_fn(ev_uint16_t (*fn
)(void))
1339 evdns_set_random_init_fn(int (*fn
)(void))
1341 rand_init_function
= fn
;
1345 evdns_set_random_bytes_fn(void (*fn
)(void *, size_t))
1347 rand_bytes_function
= fn
;
1350 /* Try to choose a strong transaction id which isn't already in flight */
1352 transaction_id_pick(struct evdns_base
*base
) {
1353 ASSERT_LOCKED(base
);
1356 rand_bytes_function(&trans_id
, sizeof(trans_id
));
1358 if (trans_id
== 0xffff) continue;
1359 /* now check to see if that id is already inflight */
1360 if (request_find_from_trans_id(base
, trans_id
) == NULL
)
1365 /* choose a namesever to use. This function will try to ignore */
1366 /* nameservers which we think are down and load balance across the rest */
1367 /* by updating the server_head global each time. */
1368 static struct nameserver
*
1369 nameserver_pick(struct evdns_base
*base
) {
1370 struct nameserver
*started_at
= base
->server_head
, *picked
;
1371 ASSERT_LOCKED(base
);
1372 if (!base
->server_head
) return NULL
;
1374 /* if we don't have any good nameservers then there's no */
1375 /* point in trying to find one. */
1376 if (!base
->global_good_nameservers
) {
1377 base
->server_head
= base
->server_head
->next
;
1378 return base
->server_head
;
1381 /* remember that nameservers are in a circular list */
1383 if (base
->server_head
->state
) {
1384 /* we think this server is currently good */
1385 picked
= base
->server_head
;
1386 base
->server_head
= base
->server_head
->next
;
1390 base
->server_head
= base
->server_head
->next
;
1391 if (base
->server_head
== started_at
) {
1392 /* all the nameservers seem to be down */
1393 /* so we just return this one and hope for the */
1395 EVUTIL_ASSERT(base
->global_good_nameservers
== 0);
1396 picked
= base
->server_head
;
1397 base
->server_head
= base
->server_head
->next
;
1403 /* this is called when a namesever socket is ready for reading */
1405 nameserver_read(struct nameserver
*ns
) {
1406 struct sockaddr_storage ss
;
1407 ev_socklen_t addrlen
= sizeof(ss
);
1410 ASSERT_LOCKED(ns
->base
);
1413 const int r
= recvfrom(ns
->socket
, (void*)packet
,
1415 (struct sockaddr
*)&ss
, &addrlen
);
1417 int err
= evutil_socket_geterror(ns
->socket
);
1418 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1420 nameserver_failed(ns
,
1421 evutil_socket_error_to_string(err
));
1424 if (evutil_sockaddr_cmp((struct sockaddr
*)&ss
,
1425 (struct sockaddr
*)&ns
->address
, 0)) {
1426 log(EVDNS_LOG_WARN
, "Address mismatch on received "
1427 "DNS packet. Apparent source was %s",
1428 evutil_format_sockaddr_port(
1429 (struct sockaddr
*)&ss
,
1430 addrbuf
, sizeof(addrbuf
)));
1435 reply_parse(ns
->base
, packet
, r
);
1439 /* Read a packet from a DNS client on a server port s, parse it, and */
1440 /* act accordingly. */
1442 server_port_read(struct evdns_server_port
*s
) {
1444 struct sockaddr_storage addr
;
1445 ev_socklen_t addrlen
;
1450 addrlen
= sizeof(struct sockaddr_storage
);
1451 r
= recvfrom(s
->socket
, (void*)packet
, sizeof(packet
), 0,
1452 (struct sockaddr
*) &addr
, &addrlen
);
1454 int err
= evutil_socket_geterror(s
->socket
);
1455 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1458 "Error %s (%d) while reading request.",
1459 evutil_socket_error_to_string(err
), err
);
1462 request_parse(packet
, r
, s
, (struct sockaddr
*) &addr
, addrlen
);
1466 /* Try to write all pending replies on a given DNS server port. */
1468 server_port_flush(struct evdns_server_port
*port
)
1470 struct server_request
*req
= port
->pending_replies
;
1471 ASSERT_LOCKED(port
);
1473 int r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
1474 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
1476 int err
= evutil_socket_geterror(port
->socket
);
1477 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1479 log(EVDNS_LOG_WARN
, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err
), err
);
1481 if (server_request_free(req
)) {
1482 /* we released the last reference to req->port. */
1485 EVUTIL_ASSERT(req
!= port
->pending_replies
);
1486 req
= port
->pending_replies
;
1490 /* We have no more pending requests; stop listening for 'writeable' events. */
1491 (void) event_del(&port
->event
);
1492 event_assign(&port
->event
, port
->event_base
,
1493 port
->socket
, EV_READ
| EV_PERSIST
,
1494 server_port_ready_callback
, port
);
1496 if (event_add(&port
->event
, NULL
) < 0) {
1497 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server.");
1502 /* set if we are waiting for the ability to write to this server. */
1503 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1504 /* we stop these events. */
1506 nameserver_write_waiting(struct nameserver
*ns
, char waiting
) {
1507 ASSERT_LOCKED(ns
->base
);
1508 if (ns
->write_waiting
== waiting
) return;
1510 ns
->write_waiting
= waiting
;
1511 (void) event_del(&ns
->event
);
1512 event_assign(&ns
->event
, ns
->base
->event_base
,
1513 ns
->socket
, EV_READ
| (waiting
? EV_WRITE
: 0) | EV_PERSIST
,
1514 nameserver_ready_callback
, ns
);
1515 if (event_add(&ns
->event
, NULL
) < 0) {
1517 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for %s",
1518 evutil_format_sockaddr_port(
1519 (struct sockaddr
*)&ns
->address
,
1520 addrbuf
, sizeof(addrbuf
)));
1525 /* a callback function. Called by libevent when the kernel says that */
1526 /* a nameserver socket is ready for writing or reading */
1528 nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1529 struct nameserver
*ns
= (struct nameserver
*) arg
;
1532 EVDNS_LOCK(ns
->base
);
1533 if (events
& EV_WRITE
) {
1535 if (!evdns_transmit(ns
->base
)) {
1536 nameserver_write_waiting(ns
, 0);
1539 if (events
& EV_READ
) {
1540 nameserver_read(ns
);
1542 EVDNS_UNLOCK(ns
->base
);
1545 /* a callback function. Called by libevent when the kernel says that */
1546 /* a server socket is ready for writing or reading. */
1548 server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1549 struct evdns_server_port
*port
= (struct evdns_server_port
*) arg
;
1553 if (events
& EV_WRITE
) {
1555 server_port_flush(port
);
1557 if (events
& EV_READ
) {
1558 server_port_read(port
);
1563 /* This is an inefficient representation; only use it via the dnslabel_table_*
1564 * functions, so that is can be safely replaced with something smarter later. */
1565 #define MAX_LABELS 128
1566 /* Structures used to implement name compression */
1567 struct dnslabel_entry
{ char *v
; off_t pos
; };
1568 struct dnslabel_table
{
1569 int n_labels
; /* number of current entries */
1570 /* map from name to position in message */
1571 struct dnslabel_entry labels
[MAX_LABELS
];
1574 /* Initialize dnslabel_table. */
1576 dnslabel_table_init(struct dnslabel_table
*table
)
1578 table
->n_labels
= 0;
1581 /* Free all storage held by table, but not the table itself. */
1583 dnslabel_clear(struct dnslabel_table
*table
)
1586 for (i
= 0; i
< table
->n_labels
; ++i
)
1587 mm_free(table
->labels
[i
].v
);
1588 table
->n_labels
= 0;
1591 /* return the position of the label in the current message, or -1 if the label */
1592 /* hasn't been used yet. */
1594 dnslabel_table_get_pos(const struct dnslabel_table
*table
, const char *label
)
1597 for (i
= 0; i
< table
->n_labels
; ++i
) {
1598 if (!strcmp(label
, table
->labels
[i
].v
))
1599 return table
->labels
[i
].pos
;
1604 /* remember that we've used the label at position pos */
1606 dnslabel_table_add(struct dnslabel_table
*table
, const char *label
, off_t pos
)
1610 if (table
->n_labels
== MAX_LABELS
)
1612 v
= mm_strdup(label
);
1615 p
= table
->n_labels
++;
1616 table
->labels
[p
].v
= v
;
1617 table
->labels
[p
].pos
= pos
;
1622 /* Converts a string to a length-prefixed set of DNS labels, starting */
1623 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1624 /* of name. table is optional, and is used for compression. */
1626 /* Input: abc.def */
1627 /* Output: <3>abc<3>def<0> */
1629 /* Returns the first index after the encoded name, or negative on error. */
1630 /* -1 label was > 63 bytes */
1631 /* -2 name too long to fit in buffer. */
1634 dnsname_to_labels(u8
*const buf
, size_t buf_len
, off_t j
,
1635 const char *name
, const size_t name_len
,
1636 struct dnslabel_table
*table
) {
1637 const char *end
= name
+ name_len
;
1641 #define APPEND16(x) do { \
1642 if (j + 2 > (off_t)buf_len) \
1645 memcpy(buf + j, &_t, 2); \
1648 #define APPEND32(x) do { \
1649 if (j + 4 > (off_t)buf_len) \
1652 memcpy(buf + j, &_t32, 4); \
1656 if (name_len
> 255) return -2;
1659 const char *const start
= name
;
1660 if (table
&& (ref
= dnslabel_table_get_pos(table
, name
)) >= 0) {
1661 APPEND16(ref
| 0xc000);
1664 name
= strchr(name
, '.');
1666 const size_t label_len
= end
- start
;
1667 if (label_len
> 63) return -1;
1668 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1669 if (table
) dnslabel_table_add(table
, start
, j
);
1670 buf
[j
++] = (ev_uint8_t
)label_len
;
1672 memcpy(buf
+ j
, start
, label_len
);
1673 j
+= (int) label_len
;
1676 /* append length of the label. */
1677 const size_t label_len
= name
- start
;
1678 if (label_len
> 63) return -1;
1679 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1680 if (table
) dnslabel_table_add(table
, start
, j
);
1681 buf
[j
++] = (ev_uint8_t
)label_len
;
1683 memcpy(buf
+ j
, start
, label_len
);
1684 j
+= (int) label_len
;
1685 /* hop over the '.' */
1690 /* the labels must be terminated by a 0. */
1691 /* It's possible that the name ended in a . */
1692 /* in which case the zero is already there */
1693 if (!j
|| buf
[j
-1]) buf
[j
++] = 0;
1699 /* Finds the length of a dns request for a DNS name of the given */
1700 /* length. The actual request may be smaller than the value returned */
1703 evdns_request_len(const size_t name_len
) {
1704 return 96 + /* length of the DNS standard header */
1706 4; /* space for the resource type */
1709 /* build a dns request packet into buf. buf should be at least as long */
1710 /* as evdns_request_len told you it should be. */
1712 /* Returns the amount of space used. Negative on error. */
1714 evdns_request_data_build(const char *const name
, const size_t name_len
,
1715 const u16 trans_id
, const u16 type
, const u16
class,
1716 u8
*const buf
, size_t buf_len
) {
1717 off_t j
= 0; /* current offset into buf */
1718 u16 _t
; /* used by the macros */
1721 APPEND16(0x0100); /* standard query, recusion needed */
1722 APPEND16(1); /* one question */
1723 APPEND16(0); /* no answers */
1724 APPEND16(0); /* no authority */
1725 APPEND16(0); /* no additional */
1727 j
= dnsname_to_labels(buf
, buf_len
, j
, name
, name_len
, NULL
);
1740 /* exported function */
1741 struct evdns_server_port
*
1742 evdns_add_server_port_with_base(struct event_base
*base
, evutil_socket_t socket
, int flags
, evdns_request_callback_fn_type cb
, void *user_data
)
1744 struct evdns_server_port
*port
;
1746 return NULL
; /* flags not yet implemented */
1747 if (!(port
= mm_malloc(sizeof(struct evdns_server_port
))))
1749 memset(port
, 0, sizeof(struct evdns_server_port
));
1752 port
->socket
= socket
;
1756 port
->user_callback
= cb
;
1757 port
->user_data
= user_data
;
1758 port
->pending_replies
= NULL
;
1759 port
->event_base
= base
;
1761 event_assign(&port
->event
, port
->event_base
,
1762 port
->socket
, EV_READ
| EV_PERSIST
,
1763 server_port_ready_callback
, port
);
1764 if (event_add(&port
->event
, NULL
) < 0) {
1768 EVTHREAD_ALLOC_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
1772 struct evdns_server_port
*
1773 evdns_add_server_port(evutil_socket_t socket
, int flags
, evdns_request_callback_fn_type cb
, void *user_data
)
1775 return evdns_add_server_port_with_base(NULL
, socket
, flags
, cb
, user_data
);
1778 /* exported function */
1780 evdns_close_server_port(struct evdns_server_port
*port
)
1783 if (--port
->refcnt
== 0) {
1785 server_port_free(port
);
1791 /* exported function */
1793 evdns_server_request_add_reply(struct evdns_server_request
*_req
, int section
, const char *name
, int type
, int class, int ttl
, int datalen
, int is_name
, const char *data
)
1795 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1796 struct server_reply_item
**itemp
, *item
;
1800 EVDNS_LOCK(req
->port
);
1801 if (req
->response
) /* have we already answered? */
1805 case EVDNS_ANSWER_SECTION
:
1806 itemp
= &req
->answer
;
1807 countp
= &req
->n_answer
;
1809 case EVDNS_AUTHORITY_SECTION
:
1810 itemp
= &req
->authority
;
1811 countp
= &req
->n_authority
;
1813 case EVDNS_ADDITIONAL_SECTION
:
1814 itemp
= &req
->additional
;
1815 countp
= &req
->n_additional
;
1821 itemp
= &((*itemp
)->next
);
1823 item
= mm_malloc(sizeof(struct server_reply_item
));
1827 if (!(item
->name
= mm_strdup(name
))) {
1832 item
->dns_question_class
= class;
1834 item
->is_name
= is_name
!= 0;
1838 if (item
->is_name
) {
1839 if (!(item
->data
= mm_strdup(data
))) {
1840 mm_free(item
->name
);
1844 item
->datalen
= (u16
)-1;
1846 if (!(item
->data
= mm_malloc(datalen
))) {
1847 mm_free(item
->name
);
1851 item
->datalen
= datalen
;
1852 memcpy(item
->data
, data
, datalen
);
1860 EVDNS_UNLOCK(req
->port
);
1864 /* exported function */
1866 evdns_server_request_add_a_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1868 return evdns_server_request_add_reply(
1869 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_A
, CLASS_INET
,
1870 ttl
, n
*4, 0, addrs
);
1873 /* exported function */
1875 evdns_server_request_add_aaaa_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1877 return evdns_server_request_add_reply(
1878 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_AAAA
, CLASS_INET
,
1879 ttl
, n
*16, 0, addrs
);
1882 /* exported function */
1884 evdns_server_request_add_ptr_reply(struct evdns_server_request
*req
, struct in_addr
*in
, const char *inaddr_name
, const char *hostname
, int ttl
)
1888 if (in
&& inaddr_name
)
1890 else if (!in
&& !inaddr_name
)
1893 a
= ntohl(in
->s_addr
);
1894 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
1895 (int)(u8
)((a
)&0xff),
1896 (int)(u8
)((a
>>8 )&0xff),
1897 (int)(u8
)((a
>>16)&0xff),
1898 (int)(u8
)((a
>>24)&0xff));
1901 return evdns_server_request_add_reply(
1902 req
, EVDNS_ANSWER_SECTION
, inaddr_name
, TYPE_PTR
, CLASS_INET
,
1903 ttl
, -1, 1, hostname
);
1906 /* exported function */
1908 evdns_server_request_add_cname_reply(struct evdns_server_request
*req
, const char *name
, const char *cname
, int ttl
)
1910 return evdns_server_request_add_reply(
1911 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_CNAME
, CLASS_INET
,
1915 /* exported function */
1917 evdns_server_request_set_flags(struct evdns_server_request
*exreq
, int flags
)
1919 struct server_request
*req
= TO_SERVER_REQUEST(exreq
);
1920 req
->base
.flags
&= ~(EVDNS_FLAGS_AA
|EVDNS_FLAGS_RD
);
1921 req
->base
.flags
|= flags
;
1925 evdns_server_request_format_response(struct server_request
*req
, int err
)
1927 unsigned char buf
[1500];
1928 size_t buf_len
= sizeof(buf
);
1934 struct dnslabel_table table
;
1936 if (err
< 0 || err
> 15) return -1;
1938 /* Set response bit and error code; copy OPCODE and RD fields from
1939 * question; copy RA and AA if set by caller. */
1940 flags
= req
->base
.flags
;
1941 flags
|= (0x8000 | err
);
1943 dnslabel_table_init(&table
);
1944 APPEND16(req
->trans_id
);
1946 APPEND16(req
->base
.nquestions
);
1947 APPEND16(req
->n_answer
);
1948 APPEND16(req
->n_authority
);
1949 APPEND16(req
->n_additional
);
1951 /* Add questions. */
1952 for (i
=0; i
< req
->base
.nquestions
; ++i
) {
1953 const char *s
= req
->base
.questions
[i
]->name
;
1954 j
= dnsname_to_labels(buf
, buf_len
, j
, s
, strlen(s
), &table
);
1956 dnslabel_clear(&table
);
1959 APPEND16(req
->base
.questions
[i
]->type
);
1960 APPEND16(req
->base
.questions
[i
]->dns_question_class
);
1963 /* Add answer, authority, and additional sections. */
1964 for (i
=0; i
<3; ++i
) {
1965 struct server_reply_item
*item
;
1969 item
= req
->authority
;
1971 item
= req
->additional
;
1973 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->name
, strlen(item
->name
), &table
);
1978 APPEND16(item
->type
);
1979 APPEND16(item
->dns_question_class
);
1980 APPEND32(item
->ttl
);
1981 if (item
->is_name
) {
1982 off_t len_idx
= j
, name_start
;
1985 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->data
, strlen(item
->data
), &table
);
1989 _t
= htons( (short) (j
-name_start
) );
1990 memcpy(buf
+len_idx
, &_t
, 2);
1992 APPEND16(item
->datalen
);
1993 if (j
+item
->datalen
> (off_t
)buf_len
)
1995 memcpy(buf
+j
, item
->data
, item
->datalen
);
2005 buf
[2] |= 0x02; /* set the truncated bit. */
2008 req
->response_len
= j
;
2010 if (!(req
->response
= mm_malloc(req
->response_len
))) {
2011 server_request_free_answers(req
);
2012 dnslabel_clear(&table
);
2015 memcpy(req
->response
, buf
, req
->response_len
);
2016 server_request_free_answers(req
);
2017 dnslabel_clear(&table
);
2021 /* exported function */
2023 evdns_server_request_respond(struct evdns_server_request
*_req
, int err
)
2025 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2026 struct evdns_server_port
*port
= req
->port
;
2030 if (!req
->response
) {
2031 if ((r
= evdns_server_request_format_response(req
, err
))<0)
2035 r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
2036 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
2038 int sock_err
= evutil_socket_geterror(port
->socket
);
2039 if (EVUTIL_ERR_RW_RETRIABLE(sock_err
))
2042 if (port
->pending_replies
) {
2043 req
->prev_pending
= port
->pending_replies
->prev_pending
;
2044 req
->next_pending
= port
->pending_replies
;
2045 req
->prev_pending
->next_pending
=
2046 req
->next_pending
->prev_pending
= req
;
2048 req
->prev_pending
= req
->next_pending
= req
;
2049 port
->pending_replies
= req
;
2052 (void) event_del(&port
->event
);
2053 event_assign(&port
->event
, port
->event_base
, port
->socket
, (port
->closing
?0:EV_READ
) | EV_WRITE
| EV_PERSIST
, server_port_ready_callback
, port
);
2055 if (event_add(&port
->event
, NULL
) < 0) {
2056 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server");
2064 if (server_request_free(req
)) {
2069 if (port
->pending_replies
)
2070 server_port_flush(port
);
2078 /* Free all storage held by RRs in req. */
2080 server_request_free_answers(struct server_request
*req
)
2082 struct server_reply_item
*victim
, *next
, **list
;
2084 for (i
= 0; i
< 3; ++i
) {
2086 list
= &req
->answer
;
2088 list
= &req
->authority
;
2090 list
= &req
->additional
;
2094 next
= victim
->next
;
2095 mm_free(victim
->name
);
2097 mm_free(victim
->data
);
2105 /* Free all storage held by req, and remove links to it. */
2106 /* return true iff we just wound up freeing the server_port. */
2108 server_request_free(struct server_request
*req
)
2110 int i
, rc
=1, lock
=0;
2111 if (req
->base
.questions
) {
2112 for (i
= 0; i
< req
->base
.nquestions
; ++i
)
2113 mm_free(req
->base
.questions
[i
]);
2114 mm_free(req
->base
.questions
);
2118 EVDNS_LOCK(req
->port
);
2120 if (req
->port
->pending_replies
== req
) {
2121 if (req
->next_pending
&& req
->next_pending
!= req
)
2122 req
->port
->pending_replies
= req
->next_pending
;
2124 req
->port
->pending_replies
= NULL
;
2126 rc
= --req
->port
->refcnt
;
2129 if (req
->response
) {
2130 mm_free(req
->response
);
2133 server_request_free_answers(req
);
2135 if (req
->next_pending
&& req
->next_pending
!= req
) {
2136 req
->next_pending
->prev_pending
= req
->prev_pending
;
2137 req
->prev_pending
->next_pending
= req
->next_pending
;
2141 EVDNS_UNLOCK(req
->port
); /* ????? nickm */
2142 server_port_free(req
->port
);
2147 EVDNS_UNLOCK(req
->port
);
2152 /* Free all storage held by an evdns_server_port. Only called when */
2154 server_port_free(struct evdns_server_port
*port
)
2156 EVUTIL_ASSERT(port
);
2157 EVUTIL_ASSERT(!port
->refcnt
);
2158 EVUTIL_ASSERT(!port
->pending_replies
);
2159 if (port
->socket
> 0) {
2160 evutil_closesocket(port
->socket
);
2163 (void) event_del(&port
->event
);
2164 event_debug_unassign(&port
->event
);
2165 EVTHREAD_FREE_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
2169 /* exported function */
2171 evdns_server_request_drop(struct evdns_server_request
*_req
)
2173 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2174 server_request_free(req
);
2178 /* exported function */
2180 evdns_server_request_get_requesting_addr(struct evdns_server_request
*_req
, struct sockaddr
*sa
, int addr_len
)
2182 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2183 if (addr_len
< (int)req
->addrlen
)
2185 memcpy(sa
, &(req
->addr
), req
->addrlen
);
2186 return req
->addrlen
;
2192 /* this is a libevent callback function which is called when a request */
2193 /* has timed out. */
2195 evdns_request_timeout_callback(evutil_socket_t fd
, short events
, void *arg
) {
2196 struct request
*const req
= (struct request
*) arg
;
2197 struct evdns_base
*base
= req
->base
;
2202 log(EVDNS_LOG_DEBUG
, "Request %p timed out", arg
);
2205 req
->ns
->timedout
++;
2206 if (req
->ns
->timedout
> req
->base
->global_max_nameserver_timeout
) {
2207 req
->ns
->timedout
= 0;
2208 nameserver_failed(req
->ns
, "request timed out.");
2211 if (req
->tx_count
>= req
->base
->global_max_retransmits
) {
2212 /* this request has failed */
2213 log(EVDNS_LOG_DEBUG
, "Giving up on request %p; tx_count==%d",
2214 arg
, req
->tx_count
);
2215 reply_schedule_callback(req
, 0, DNS_ERR_TIMEOUT
, NULL
);
2216 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
2219 struct nameserver
*new_ns
;
2220 log(EVDNS_LOG_DEBUG
, "Retransmitting request %p; tx_count==%d",
2221 arg
, req
->tx_count
);
2222 (void) evtimer_del(&req
->timeout_event
);
2223 new_ns
= nameserver_pick(base
);
2226 evdns_request_transmit(req
);
2231 /* try to send a request to a given server. */
2235 /* 1 temporary failure */
2236 /* 2 other failure */
2238 evdns_request_transmit_to(struct request
*req
, struct nameserver
*server
) {
2240 ASSERT_LOCKED(req
->base
);
2241 ASSERT_VALID_REQUEST(req
);
2242 r
= sendto(server
->socket
, (void*)req
->request
, req
->request_len
, 0,
2243 (struct sockaddr
*)&server
->address
, server
->addrlen
);
2245 int err
= evutil_socket_geterror(server
->socket
);
2246 if (EVUTIL_ERR_RW_RETRIABLE(err
))
2248 nameserver_failed(req
->ns
, evutil_socket_error_to_string(err
));
2250 } else if (r
!= (int)req
->request_len
) {
2251 return 1; /* short write */
2257 /* try to send a request, updating the fields of the request */
2264 evdns_request_transmit(struct request
*req
) {
2267 ASSERT_LOCKED(req
->base
);
2268 ASSERT_VALID_REQUEST(req
);
2269 /* if we fail to send this packet then this flag marks it */
2270 /* for evdns_transmit */
2271 req
->transmit_me
= 1;
2272 EVUTIL_ASSERT(req
->trans_id
!= 0xffff);
2274 if (req
->ns
->choked
) {
2275 /* don't bother trying to write to a socket */
2276 /* which we have had EAGAIN from */
2280 r
= evdns_request_transmit_to(req
, req
->ns
);
2284 req
->ns
->choked
= 1;
2285 nameserver_write_waiting(req
->ns
, 1);
2288 /* failed to transmit the request entirely. */
2290 /* fall through: we'll set a timeout, which will time out,
2291 * and make us retransmit the request anyway. */
2294 log(EVDNS_LOG_DEBUG
,
2295 "Setting timeout for request %p, sent to nameserver %p", req
, req
->ns
);
2296 if (evtimer_add(&req
->timeout_event
, &req
->base
->global_timeout
) < 0) {
2298 "Error from libevent when adding timer for request %p",
2303 req
->transmit_me
= 0;
2309 nameserver_probe_callback(int result
, char type
, int count
, int ttl
, void *addresses
, void *arg
) {
2310 struct nameserver
*const ns
= (struct nameserver
*) arg
;
2316 if (result
== DNS_ERR_CANCEL
) {
2317 /* We canceled this request because the nameserver came up
2318 * for some other reason. Do not change our opinion about
2319 * the nameserver. */
2323 EVDNS_LOCK(ns
->base
);
2324 ns
->probe_request
= NULL
;
2325 if (result
== DNS_ERR_NONE
|| result
== DNS_ERR_NOTEXIST
) {
2326 /* this is a good reply */
2329 nameserver_probe_failed(ns
);
2331 EVDNS_UNLOCK(ns
->base
);
2335 nameserver_send_probe(struct nameserver
*const ns
) {
2336 struct evdns_request
*handle
;
2337 struct request
*req
;
2339 /* here we need to send a probe to a given nameserver */
2340 /* in the hope that it is up now. */
2342 ASSERT_LOCKED(ns
->base
);
2343 log(EVDNS_LOG_DEBUG
, "Sending probe to %s",
2344 evutil_format_sockaddr_port(
2345 (struct sockaddr
*)&ns
->address
,
2346 addrbuf
, sizeof(addrbuf
)));
2347 handle
= mm_calloc(1, sizeof(*handle
));
2348 if (!handle
) return;
2349 req
= request_new(ns
->base
, handle
, TYPE_A
, "google.com", DNS_QUERY_NO_SEARCH
, nameserver_probe_callback
, ns
);
2354 ns
->probe_request
= handle
;
2355 /* we force this into the inflight queue no matter what */
2356 request_trans_id_set(req
, transaction_id_pick(ns
->base
));
2358 request_submit(req
);
2362 /* 0 didn't try to transmit anything */
2363 /* 1 tried to transmit something */
2365 evdns_transmit(struct evdns_base
*base
) {
2366 char did_try_to_transmit
= 0;
2369 ASSERT_LOCKED(base
);
2370 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2371 if (base
->req_heads
[i
]) {
2372 struct request
*const started_at
= base
->req_heads
[i
], *req
= started_at
;
2373 /* first transmit all the requests which are currently waiting */
2375 if (req
->transmit_me
) {
2376 did_try_to_transmit
= 1;
2377 evdns_request_transmit(req
);
2381 } while (req
!= started_at
);
2385 return did_try_to_transmit
;
2388 /* exported function */
2390 evdns_base_count_nameservers(struct evdns_base
*base
)
2392 const struct nameserver
*server
;
2396 server
= base
->server_head
;
2401 server
= server
->next
;
2402 } while (server
!= base
->server_head
);
2409 evdns_count_nameservers(void)
2411 return evdns_base_count_nameservers(current_base
);
2414 /* exported function */
2416 evdns_base_clear_nameservers_and_suspend(struct evdns_base
*base
)
2418 struct nameserver
*server
, *started_at
;
2422 server
= base
->server_head
;
2423 started_at
= base
->server_head
;
2429 struct nameserver
*next
= server
->next
;
2430 (void) event_del(&server
->event
);
2431 if (evtimer_initialized(&server
->timeout_event
))
2432 (void) evtimer_del(&server
->timeout_event
);
2433 if (server
->probe_request
) {
2434 evdns_cancel_request(server
->base
, server
->probe_request
);
2435 server
->probe_request
= NULL
;
2437 if (server
->socket
>= 0)
2438 evutil_closesocket(server
->socket
);
2440 if (next
== started_at
)
2444 base
->server_head
= NULL
;
2445 base
->global_good_nameservers
= 0;
2447 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2448 struct request
*req
, *req_started_at
;
2449 req
= req_started_at
= base
->req_heads
[i
];
2451 struct request
*next
= req
->next
;
2452 req
->tx_count
= req
->reissue_count
= 0;
2454 /* ???? What to do about searches? */
2455 (void) evtimer_del(&req
->timeout_event
);
2457 req
->transmit_me
= 0;
2459 base
->global_requests_waiting
++;
2460 evdns_request_insert(req
, &base
->req_waiting_head
);
2461 /* We want to insert these suspended elements at the front of
2462 * the waiting queue, since they were pending before any of
2463 * the waiting entries were added. This is a circular list,
2464 * so we can just shift the start back by one.*/
2465 base
->req_waiting_head
= base
->req_waiting_head
->prev
;
2467 if (next
== req_started_at
)
2471 base
->req_heads
[i
] = NULL
;
2474 base
->global_requests_inflight
= 0;
2481 evdns_clear_nameservers_and_suspend(void)
2483 return evdns_base_clear_nameservers_and_suspend(current_base
);
2487 /* exported function */
2489 evdns_base_resume(struct evdns_base
*base
)
2492 evdns_requests_pump_waiting_queue(base
);
2500 return evdns_base_resume(current_base
);
2504 _evdns_nameserver_add_impl(struct evdns_base
*base
, const struct sockaddr
*address
, int addrlen
) {
2505 /* first check to see if we already have this nameserver */
2507 const struct nameserver
*server
= base
->server_head
, *const started_at
= base
->server_head
;
2508 struct nameserver
*ns
;
2512 ASSERT_LOCKED(base
);
2515 if (!evutil_sockaddr_cmp((struct sockaddr
*)&server
->address
, address
, 1)) return 3;
2516 server
= server
->next
;
2517 } while (server
!= started_at
);
2519 if (addrlen
> (int)sizeof(ns
->address
)) {
2520 log(EVDNS_LOG_DEBUG
, "Addrlen %d too long.", (int)addrlen
);
2524 ns
= (struct nameserver
*) mm_malloc(sizeof(struct nameserver
));
2527 memset(ns
, 0, sizeof(struct nameserver
));
2530 evtimer_assign(&ns
->timeout_event
, ns
->base
->event_base
, nameserver_prod_callback
, ns
);
2532 ns
->socket
= socket(address
->sa_family
, SOCK_DGRAM
, 0);
2533 if (ns
->socket
< 0) { err
= 1; goto out1
; }
2534 evutil_make_socket_closeonexec(ns
->socket
);
2535 evutil_make_socket_nonblocking(ns
->socket
);
2537 if (base
->global_outgoing_addrlen
&&
2538 !evutil_sockaddr_is_loopback(address
)) {
2539 if (bind(ns
->socket
,
2540 (struct sockaddr
*)&base
->global_outgoing_address
,
2541 base
->global_outgoing_addrlen
) < 0) {
2542 log(EVDNS_LOG_WARN
,"Couldn't bind to outgoing address");
2548 memcpy(&ns
->address
, address
, addrlen
);
2549 ns
->addrlen
= addrlen
;
2551 event_assign(&ns
->event
, ns
->base
->event_base
, ns
->socket
, EV_READ
| EV_PERSIST
, nameserver_ready_callback
, ns
);
2552 if (event_add(&ns
->event
, NULL
) < 0) {
2557 log(EVDNS_LOG_DEBUG
, "Added nameserver %s as %p",
2558 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)), ns
);
2560 /* insert this nameserver into the list of them */
2561 if (!base
->server_head
) {
2562 ns
->next
= ns
->prev
= ns
;
2563 base
->server_head
= ns
;
2565 ns
->next
= base
->server_head
->next
;
2566 ns
->prev
= base
->server_head
;
2567 base
->server_head
->next
= ns
;
2568 ns
->next
->prev
= ns
;
2571 base
->global_good_nameservers
++;
2576 evutil_closesocket(ns
->socket
);
2578 event_debug_unassign(&ns
->event
);
2580 log(EVDNS_LOG_WARN
, "Unable to add nameserver %s: error %d",
2581 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)), err
);
2585 /* exported function */
2587 evdns_base_nameserver_add(struct evdns_base
*base
, unsigned long int address
)
2589 struct sockaddr_in sin
;
2591 memset(&sin
, 0, sizeof(sin
));
2592 sin
.sin_addr
.s_addr
= address
;
2593 sin
.sin_port
= htons(53);
2594 sin
.sin_family
= AF_INET
;
2596 res
= _evdns_nameserver_add_impl(base
, (struct sockaddr
*)&sin
, sizeof(sin
));
2602 evdns_nameserver_add(unsigned long int address
) {
2604 current_base
= evdns_base_new(NULL
, 0);
2605 return evdns_base_nameserver_add(current_base
, address
);
2609 sockaddr_setport(struct sockaddr
*sa
, ev_uint16_t port
)
2611 if (sa
->sa_family
== AF_INET
) {
2612 ((struct sockaddr_in
*)sa
)->sin_port
= htons(port
);
2613 } else if (sa
->sa_family
== AF_INET6
) {
2614 ((struct sockaddr_in6
*)sa
)->sin6_port
= htons(port
);
2619 sockaddr_getport(struct sockaddr
*sa
)
2621 if (sa
->sa_family
== AF_INET
) {
2622 return ntohs(((struct sockaddr_in
*)sa
)->sin_port
);
2623 } else if (sa
->sa_family
== AF_INET6
) {
2624 return ntohs(((struct sockaddr_in6
*)sa
)->sin6_port
);
2630 /* exported function */
2632 evdns_base_nameserver_ip_add(struct evdns_base
*base
, const char *ip_as_string
) {
2633 struct sockaddr_storage ss
;
2634 struct sockaddr
*sa
;
2635 int len
= sizeof(ss
);
2637 if (evutil_parse_sockaddr_port(ip_as_string
, (struct sockaddr
*)&ss
,
2639 log(EVDNS_LOG_WARN
, "Unable to parse nameserver address %s",
2643 sa
= (struct sockaddr
*) &ss
;
2644 if (sockaddr_getport(sa
) == 0)
2645 sockaddr_setport(sa
, 53);
2648 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2654 evdns_nameserver_ip_add(const char *ip_as_string
) {
2656 current_base
= evdns_base_new(NULL
, 0);
2657 return evdns_base_nameserver_ip_add(current_base
, ip_as_string
);
2661 evdns_base_nameserver_sockaddr_add(struct evdns_base
*base
,
2662 const struct sockaddr
*sa
, ev_socklen_t len
, unsigned flags
)
2665 EVUTIL_ASSERT(base
);
2667 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2672 /* remove from the queue */
2674 evdns_request_remove(struct request
*req
, struct request
**head
)
2676 ASSERT_LOCKED(req
->base
);
2677 ASSERT_VALID_REQUEST(req
);
2681 struct request
*ptr
;
2683 EVUTIL_ASSERT(*head
!= NULL
);
2692 } while (ptr
!= *head
);
2693 EVUTIL_ASSERT(found
);
2695 EVUTIL_ASSERT(req
->next
);
2699 if (req
->next
== req
) {
2700 /* only item in the list */
2703 req
->next
->prev
= req
->prev
;
2704 req
->prev
->next
= req
->next
;
2705 if (*head
== req
) *head
= req
->next
;
2707 req
->next
= req
->prev
= NULL
;
2710 /* insert into the tail of the queue */
2712 evdns_request_insert(struct request
*req
, struct request
**head
) {
2713 ASSERT_LOCKED(req
->base
);
2714 ASSERT_VALID_REQUEST(req
);
2717 req
->next
= req
->prev
= req
;
2721 req
->prev
= (*head
)->prev
;
2722 req
->prev
->next
= req
;
2724 (*head
)->prev
= req
;
2728 string_num_dots(const char *s
) {
2730 while ((s
= strchr(s
, '.'))) {
2737 static struct request
*
2738 request_new(struct evdns_base
*base
, struct evdns_request
*handle
, int type
,
2739 const char *name
, int flags
, evdns_callback_type callback
,
2742 const char issuing_now
=
2743 (base
->global_requests_inflight
< base
->global_max_requests_inflight
) ? 1 : 0;
2745 const size_t name_len
= strlen(name
);
2746 const size_t request_max_len
= evdns_request_len(name_len
);
2747 const u16 trans_id
= issuing_now
? transaction_id_pick(base
) : 0xffff;
2748 /* the request data is alloced in a single block with the header */
2749 struct request
*const req
=
2750 mm_malloc(sizeof(struct request
) + request_max_len
);
2755 ASSERT_LOCKED(base
);
2757 if (!req
) return NULL
;
2759 if (name_len
>= sizeof(namebuf
)) {
2764 memset(req
, 0, sizeof(struct request
));
2767 evtimer_assign(&req
->timeout_event
, req
->base
->event_base
, evdns_request_timeout_callback
, req
);
2769 if (base
->global_randomize_case
) {
2771 char randbits
[(sizeof(namebuf
)+7)/8];
2772 strlcpy(namebuf
, name
, sizeof(namebuf
));
2773 rand_bytes_function(randbits
, (name_len
+7)/8);
2774 for (i
= 0; i
< name_len
; ++i
) {
2775 if (EVUTIL_ISALPHA(namebuf
[i
])) {
2776 if ((randbits
[i
>> 3] & (1<<(i
& 7))))
2779 namebuf
[i
] &= ~0x20;
2785 /* request data lives just after the header */
2786 req
->request
= ((u8
*) req
) + sizeof(struct request
);
2787 /* denotes that the request data shouldn't be free()ed */
2788 req
->request_appended
= 1;
2789 rlen
= evdns_request_data_build(name
, name_len
, trans_id
,
2790 type
, CLASS_INET
, req
->request
, request_max_len
);
2794 req
->request_len
= rlen
;
2795 req
->trans_id
= trans_id
;
2797 req
->request_type
= type
;
2798 req
->user_pointer
= user_ptr
;
2799 req
->user_callback
= callback
;
2800 req
->ns
= issuing_now
? nameserver_pick(base
) : NULL
;
2801 req
->next
= req
->prev
= NULL
;
2802 req
->handle
= handle
;
2804 handle
->current_req
= req
;
2805 handle
->base
= base
;
2815 request_submit(struct request
*const req
) {
2816 struct evdns_base
*base
= req
->base
;
2817 ASSERT_LOCKED(base
);
2818 ASSERT_VALID_REQUEST(req
);
2820 /* if it has a nameserver assigned then this is going */
2821 /* straight into the inflight queue */
2822 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
2823 base
->global_requests_inflight
++;
2824 evdns_request_transmit(req
);
2826 evdns_request_insert(req
, &base
->req_waiting_head
);
2827 base
->global_requests_waiting
++;
2831 /* exported function */
2833 evdns_cancel_request(struct evdns_base
*base
, struct evdns_request
*handle
)
2835 struct request
*req
;
2837 if (!handle
->current_req
)
2841 /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
2842 base
= handle
->base
;
2844 base
= handle
->current_req
->base
;
2848 if (handle
->pending_cb
) {
2853 req
= handle
->current_req
;
2854 ASSERT_VALID_REQUEST(req
);
2856 reply_schedule_callback(req
, 0, DNS_ERR_CANCEL
, NULL
);
2858 /* remove from inflight queue */
2859 request_finished(req
, &REQ_HEAD(base
, req
->trans_id
), 1);
2861 /* remove from global_waiting head */
2862 request_finished(req
, &base
->req_waiting_head
, 1);
2867 /* exported function */
2868 struct evdns_request
*
2869 evdns_base_resolve_ipv4(struct evdns_base
*base
, const char *name
, int flags
,
2870 evdns_callback_type callback
, void *ptr
) {
2871 struct evdns_request
*handle
;
2872 struct request
*req
;
2873 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2874 handle
= mm_calloc(1, sizeof(*handle
));
2878 if (flags
& DNS_QUERY_NO_SEARCH
) {
2880 request_new(base
, handle
, TYPE_A
, name
, flags
,
2883 request_submit(req
);
2885 search_request_new(base
, handle
, TYPE_A
, name
, flags
,
2888 if (handle
->current_req
== NULL
) {
2896 int evdns_resolve_ipv4(const char *name
, int flags
,
2897 evdns_callback_type callback
, void *ptr
)
2899 return evdns_base_resolve_ipv4(current_base
, name
, flags
, callback
, ptr
)
2904 /* exported function */
2905 struct evdns_request
*
2906 evdns_base_resolve_ipv6(struct evdns_base
*base
,
2907 const char *name
, int flags
,
2908 evdns_callback_type callback
, void *ptr
)
2910 struct evdns_request
*handle
;
2911 struct request
*req
;
2912 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2913 handle
= mm_calloc(1, sizeof(*handle
));
2917 if (flags
& DNS_QUERY_NO_SEARCH
) {
2918 req
= request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2921 request_submit(req
);
2923 search_request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2926 if (handle
->current_req
== NULL
) {
2934 int evdns_resolve_ipv6(const char *name
, int flags
,
2935 evdns_callback_type callback
, void *ptr
) {
2936 return evdns_base_resolve_ipv6(current_base
, name
, flags
, callback
, ptr
)
2940 struct evdns_request
*
2941 evdns_base_resolve_reverse(struct evdns_base
*base
, const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2943 struct evdns_request
*handle
;
2944 struct request
*req
;
2947 a
= ntohl(in
->s_addr
);
2948 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
2949 (int)(u8
)((a
)&0xff),
2950 (int)(u8
)((a
>>8 )&0xff),
2951 (int)(u8
)((a
>>16)&0xff),
2952 (int)(u8
)((a
>>24)&0xff));
2953 handle
= mm_calloc(1, sizeof(*handle
));
2956 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2958 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2960 request_submit(req
);
2961 if (handle
->current_req
== NULL
) {
2969 int evdns_resolve_reverse(const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2970 return evdns_base_resolve_reverse(current_base
, in
, flags
, callback
, ptr
)
2974 struct evdns_request
*
2975 evdns_base_resolve_reverse_ipv6(struct evdns_base
*base
, const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2976 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2979 struct evdns_request
*handle
;
2980 struct request
*req
;
2984 for (i
=15; i
>= 0; --i
) {
2985 u8 byte
= in
->s6_addr
[i
];
2986 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
2988 *cp
++ = "0123456789abcdef"[byte
>> 4];
2991 EVUTIL_ASSERT(cp
+ strlen("ip6.arpa") < buf
+sizeof(buf
));
2992 memcpy(cp
, "ip6.arpa", strlen("ip6.arpa")+1);
2993 handle
= mm_calloc(1, sizeof(*handle
));
2996 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2998 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
3000 request_submit(req
);
3001 if (handle
->current_req
== NULL
) {
3009 int evdns_resolve_reverse_ipv6(const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
3010 return evdns_base_resolve_reverse_ipv6(current_base
, in
, flags
, callback
, ptr
)
3014 /* exported function */
3015 struct evdns_request
*
3016 evdns_base_resolve_txt(struct evdns_base
*base
, const char *name
, int flags
,
3017 evdns_callback_type callback
, void *ptr
) {
3018 struct evdns_request
*handle
;
3019 struct request
*req
;
3020 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (txt)", name
);
3021 handle
= mm_calloc(1, sizeof(*handle
));
3025 if (flags
& DNS_QUERY_NO_SEARCH
) {
3027 request_new(base
, handle
, TYPE_TXT
, name
, flags
,
3030 request_submit(req
);
3032 search_request_new(base
, handle
, TYPE_TXT
, name
, flags
,
3035 if (handle
->current_req
== NULL
) {
3043 /* ================================================================= */
3044 /* Search support */
3046 /* the libc resolver has support for searching a number of domains */
3047 /* to find a name. If nothing else then it takes the single domain */
3048 /* from the gethostname() call. */
3050 /* It can also be configured via the domain and search options in a */
3053 /* The ndots option controls how many dots it takes for the resolver */
3054 /* to decide that a name is non-local and so try a raw lookup first. */
3056 struct search_domain
{
3058 struct search_domain
*next
;
3059 /* the text string is appended to this structure */
3062 struct search_state
{
3066 struct search_domain
*head
;
3070 search_state_decref(struct search_state
*const state
) {
3073 if (!state
->refcount
) {
3074 struct search_domain
*next
, *dom
;
3075 for (dom
= state
->head
; dom
; dom
= next
) {
3083 static struct search_state
*
3084 search_state_new(void) {
3085 struct search_state
*state
= (struct search_state
*) mm_malloc(sizeof(struct search_state
));
3086 if (!state
) return NULL
;
3087 memset(state
, 0, sizeof(struct search_state
));
3088 state
->refcount
= 1;
3095 search_postfix_clear(struct evdns_base
*base
) {
3096 search_state_decref(base
->global_search_state
);
3098 base
->global_search_state
= search_state_new();
3101 /* exported function */
3103 evdns_base_search_clear(struct evdns_base
*base
)
3106 search_postfix_clear(base
);
3111 evdns_search_clear(void) {
3112 evdns_base_search_clear(current_base
);
3116 search_postfix_add(struct evdns_base
*base
, const char *domain
) {
3118 struct search_domain
*sdomain
;
3119 while (domain
[0] == '.') domain
++;
3120 domain_len
= strlen(domain
);
3122 ASSERT_LOCKED(base
);
3123 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3124 if (!base
->global_search_state
) return;
3125 base
->global_search_state
->num_domains
++;
3127 sdomain
= (struct search_domain
*) mm_malloc(sizeof(struct search_domain
) + domain_len
);
3128 if (!sdomain
) return;
3129 memcpy( ((u8
*) sdomain
) + sizeof(struct search_domain
), domain
, domain_len
);
3130 sdomain
->next
= base
->global_search_state
->head
;
3131 sdomain
->len
= (int) domain_len
;
3133 base
->global_search_state
->head
= sdomain
;
3136 /* reverse the order of members in the postfix list. This is needed because, */
3137 /* when parsing resolv.conf we push elements in the wrong order */
3139 search_reverse(struct evdns_base
*base
) {
3140 struct search_domain
*cur
, *prev
= NULL
, *next
;
3141 ASSERT_LOCKED(base
);
3142 cur
= base
->global_search_state
->head
;
3150 base
->global_search_state
->head
= prev
;
3153 /* exported function */
3155 evdns_base_search_add(struct evdns_base
*base
, const char *domain
) {
3157 search_postfix_add(base
, domain
);
3161 evdns_search_add(const char *domain
) {
3162 evdns_base_search_add(current_base
, domain
);
3165 /* exported function */
3167 evdns_base_search_ndots_set(struct evdns_base
*base
, const int ndots
) {
3169 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3170 if (base
->global_search_state
)
3171 base
->global_search_state
->ndots
= ndots
;
3175 evdns_search_ndots_set(const int ndots
) {
3176 evdns_base_search_ndots_set(current_base
, ndots
);
3180 search_set_from_hostname(struct evdns_base
*base
) {
3181 char hostname
[HOST_NAME_MAX
+ 1], *domainname
;
3183 ASSERT_LOCKED(base
);
3184 search_postfix_clear(base
);
3185 if (gethostname(hostname
, sizeof(hostname
))) return;
3186 domainname
= strchr(hostname
, '.');
3187 if (!domainname
) return;
3188 search_postfix_add(base
, domainname
);
3191 /* warning: returns malloced string */
3193 search_make_new(const struct search_state
*const state
, int n
, const char *const base_name
) {
3194 const size_t base_len
= strlen(base_name
);
3195 const char need_to_append_dot
= base_name
[base_len
- 1] == '.' ? 0 : 1;
3196 struct search_domain
*dom
;
3198 for (dom
= state
->head
; dom
; dom
= dom
->next
) {
3200 /* this is the postfix we want */
3201 /* the actual postfix string is kept at the end of the structure */
3202 const u8
*const postfix
= ((u8
*) dom
) + sizeof(struct search_domain
);
3203 const int postfix_len
= dom
->len
;
3204 char *const newname
= (char *) mm_malloc(base_len
+ need_to_append_dot
+ postfix_len
+ 1);
3205 if (!newname
) return NULL
;
3206 memcpy(newname
, base_name
, base_len
);
3207 if (need_to_append_dot
) newname
[base_len
] = '.';
3208 memcpy(newname
+ base_len
+ need_to_append_dot
, postfix
, postfix_len
);
3209 newname
[base_len
+ need_to_append_dot
+ postfix_len
] = 0;
3214 /* we ran off the end of the list and still didn't find the requested string */
3216 return NULL
; /* unreachable; stops warnings in some compilers. */
3219 static struct request
*
3220 search_request_new(struct evdns_base
*base
, struct evdns_request
*handle
,
3221 int type
, const char *const name
, int flags
,
3222 evdns_callback_type user_callback
, void *user_arg
) {
3223 ASSERT_LOCKED(base
);
3224 EVUTIL_ASSERT(type
== TYPE_A
|| type
== TYPE_AAAA
);
3225 EVUTIL_ASSERT(handle
->current_req
== NULL
);
3226 if ( ((flags
& DNS_QUERY_NO_SEARCH
) == 0) &&
3227 base
->global_search_state
&&
3228 base
->global_search_state
->num_domains
) {
3229 /* we have some domains to search */
3230 struct request
*req
;
3231 if (string_num_dots(name
) >= base
->global_search_state
->ndots
) {
3232 req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3233 if (!req
) return NULL
;
3234 handle
->search_index
= -1;
3236 char *const new_name
= search_make_new(base
->global_search_state
, 0, name
);
3237 if (!new_name
) return NULL
;
3238 req
= request_new(base
, handle
, type
, new_name
, flags
, user_callback
, user_arg
);
3240 if (!req
) return NULL
;
3241 handle
->search_index
= 0;
3243 EVUTIL_ASSERT(handle
->search_origname
== NULL
);
3244 handle
->search_origname
= mm_strdup(name
);
3245 if (handle
->search_origname
== NULL
) {
3246 /* XXX Should we dealloc req? If yes, how? */
3251 handle
->search_state
= base
->global_search_state
;
3252 handle
->search_flags
= flags
;
3253 base
->global_search_state
->refcount
++;
3254 request_submit(req
);
3257 struct request
*const req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3258 if (!req
) return NULL
;
3259 request_submit(req
);
3264 /* this is called when a request has failed to find a name. We need to check */
3265 /* if it is part of a search and, if so, try the next name in the list */
3267 /* 0 another request has been submitted */
3268 /* 1 no more requests needed */
3270 search_try_next(struct evdns_request
*const handle
) {
3271 struct request
*req
= handle
->current_req
;
3272 struct evdns_base
*base
= req
->base
;
3273 struct request
*newreq
;
3274 ASSERT_LOCKED(base
);
3275 if (handle
->search_state
) {
3276 /* it is part of a search */
3278 handle
->search_index
++;
3279 if (handle
->search_index
>= handle
->search_state
->num_domains
) {
3280 /* no more postfixes to try, however we may need to try */
3281 /* this name without a postfix */
3282 if (string_num_dots(handle
->search_origname
) < handle
->search_state
->ndots
) {
3283 /* yep, we need to try it raw */
3284 newreq
= request_new(base
, NULL
, req
->request_type
, handle
->search_origname
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3285 log(EVDNS_LOG_DEBUG
, "Search: trying raw query %s", handle
->search_origname
);
3287 search_request_finished(handle
);
3294 new_name
= search_make_new(handle
->search_state
, handle
->search_index
, handle
->search_origname
);
3295 if (!new_name
) return 1;
3296 log(EVDNS_LOG_DEBUG
, "Search: now trying %s (%d)", new_name
, handle
->search_index
);
3297 newreq
= request_new(base
, NULL
, req
->request_type
, new_name
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3299 if (!newreq
) return 1;
3305 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 0);
3306 handle
->current_req
= newreq
;
3307 newreq
->handle
= handle
;
3308 request_submit(newreq
);
3313 search_request_finished(struct evdns_request
*const handle
) {
3314 ASSERT_LOCKED(handle
->current_req
->base
);
3315 if (handle
->search_state
) {
3316 search_state_decref(handle
->search_state
);
3317 handle
->search_state
= NULL
;
3319 if (handle
->search_origname
) {
3320 mm_free(handle
->search_origname
);
3321 handle
->search_origname
= NULL
;
3325 /* ================================================================= */
3326 /* Parsing resolv.conf files */
3329 evdns_resolv_set_defaults(struct evdns_base
*base
, int flags
) {
3330 /* if the file isn't found then we assume a local resolver */
3331 ASSERT_LOCKED(base
);
3332 if (flags
& DNS_OPTION_SEARCH
) search_set_from_hostname(base
);
3333 if (flags
& DNS_OPTION_NAMESERVERS
) evdns_base_nameserver_ip_add(base
,"127.0.0.1");
3336 #ifndef _EVENT_HAVE_STRTOK_R
3338 strtok_r(char *s
, const char *delim
, char **state
) {
3340 start
= cp
= s
? s
: *state
;
3343 while (*cp
&& !strchr(delim
, *cp
))
3358 /* helper version of atoi which returns -1 on error */
3360 strtoint(const char *const str
)
3363 const int r
= strtol(str
, &endptr
, 10);
3364 if (*endptr
) return -1;
3368 /* Parse a number of seconds into a timeval; return -1 on error. */
3370 strtotimeval(const char *const str
, struct timeval
*out
)
3374 d
= strtod(str
, &endptr
);
3375 if (*endptr
) return -1;
3376 if (d
< 0) return -1;
3377 out
->tv_sec
= (int) d
;
3378 out
->tv_usec
= (int) ((d
- (int) d
)*1000000);
3379 if (out
->tv_sec
== 0 && out
->tv_usec
< 1000) /* less than 1 msec */
3384 /* helper version of atoi that returns -1 on error and clips to bounds. */
3386 strtoint_clipped(const char *const str
, int min
, int max
)
3388 int r
= strtoint(str
);
3400 evdns_base_set_max_requests_inflight(struct evdns_base
*base
, int maxinflight
)
3402 int old_n_heads
= base
->n_req_heads
, n_heads
;
3403 struct request
**old_heads
= base
->req_heads
, **new_heads
, *req
;
3406 ASSERT_LOCKED(base
);
3407 if (maxinflight
< 1)
3409 n_heads
= (maxinflight
+4) / 5;
3410 EVUTIL_ASSERT(n_heads
> 0);
3411 new_heads
= mm_calloc(n_heads
, sizeof(struct request
*));
3415 for (i
= 0; i
< old_n_heads
; ++i
) {
3416 while (old_heads
[i
]) {
3418 evdns_request_remove(req
, &old_heads
[i
]);
3419 evdns_request_insert(req
, &new_heads
[req
->trans_id
% n_heads
]);
3424 base
->req_heads
= new_heads
;
3425 base
->n_req_heads
= n_heads
;
3426 base
->global_max_requests_inflight
= maxinflight
;
3430 /* exported function */
3432 evdns_base_set_option(struct evdns_base
*base
,
3433 const char *option
, const char *val
)
3437 res
= evdns_base_set_option_impl(base
, option
, val
, DNS_OPTIONS_ALL
);
3443 str_matches_option(const char *s1
, const char *optionname
)
3445 /* Option names are given as "option:" We accept either 'option' in
3446 * s1, or 'option:randomjunk'. The latter form is to implement the
3447 * resolv.conf parser. */
3448 size_t optlen
= strlen(optionname
);
3449 size_t slen
= strlen(s1
);
3450 if (slen
== optlen
|| slen
== optlen
- 1)
3451 return !strncmp(s1
, optionname
, slen
);
3452 else if (slen
> optlen
)
3453 return !strncmp(s1
, optionname
, optlen
);
3459 evdns_base_set_option_impl(struct evdns_base
*base
,
3460 const char *option
, const char *val
, int flags
)
3462 ASSERT_LOCKED(base
);
3463 if (str_matches_option(option
, "ndots:")) {
3464 const int ndots
= strtoint(val
);
3465 if (ndots
== -1) return -1;
3466 if (!(flags
& DNS_OPTION_SEARCH
)) return 0;
3467 log(EVDNS_LOG_DEBUG
, "Setting ndots to %d", ndots
);
3468 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3469 if (!base
->global_search_state
) return -1;
3470 base
->global_search_state
->ndots
= ndots
;
3471 } else if (str_matches_option(option
, "timeout:")) {
3473 if (strtotimeval(val
, &tv
) == -1) return -1;
3474 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3475 log(EVDNS_LOG_DEBUG
, "Setting timeout to %s", val
);
3476 memcpy(&base
->global_timeout
, &tv
, sizeof(struct timeval
));
3477 } else if (str_matches_option(option
, "getaddrinfo-allow-skew:")) {
3479 if (strtotimeval(val
, &tv
) == -1) return -1;
3480 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3481 log(EVDNS_LOG_DEBUG
, "Setting getaddrinfo-allow-skew to %s",
3483 memcpy(&base
->global_getaddrinfo_allow_skew
, &tv
,
3484 sizeof(struct timeval
));
3485 } else if (str_matches_option(option
, "max-timeouts:")) {
3486 const int maxtimeout
= strtoint_clipped(val
, 1, 255);
3487 if (maxtimeout
== -1) return -1;
3488 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3489 log(EVDNS_LOG_DEBUG
, "Setting maximum allowed timeouts to %d",
3491 base
->global_max_nameserver_timeout
= maxtimeout
;
3492 } else if (str_matches_option(option
, "max-inflight:")) {
3493 const int maxinflight
= strtoint_clipped(val
, 1, 65000);
3494 if (maxinflight
== -1) return -1;
3495 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3496 log(EVDNS_LOG_DEBUG
, "Setting maximum inflight requests to %d",
3498 evdns_base_set_max_requests_inflight(base
, maxinflight
);
3499 } else if (str_matches_option(option
, "attempts:")) {
3500 int retries
= strtoint(val
);
3501 if (retries
== -1) return -1;
3502 if (retries
> 255) retries
= 255;
3503 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3504 log(EVDNS_LOG_DEBUG
, "Setting retries to %d", retries
);
3505 base
->global_max_retransmits
= retries
;
3506 } else if (str_matches_option(option
, "randomize-case:")) {
3507 int randcase
= strtoint(val
);
3508 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3509 base
->global_randomize_case
= randcase
;
3510 } else if (str_matches_option(option
, "bind-to:")) {
3511 /* XXX This only applies to successive nameservers, not
3512 * to already-configured ones. We might want to fix that. */
3513 int len
= sizeof(base
->global_outgoing_address
);
3514 if (!(flags
& DNS_OPTION_NAMESERVERS
)) return 0;
3515 if (evutil_parse_sockaddr_port(val
,
3516 (struct sockaddr
*)&base
->global_outgoing_address
, &len
))
3518 base
->global_outgoing_addrlen
= len
;
3519 } else if (str_matches_option(option
, "initial-probe-timeout:")) {
3521 if (strtotimeval(val
, &tv
) == -1) return -1;
3522 if (tv
.tv_sec
> 3600)
3524 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3525 log(EVDNS_LOG_DEBUG
, "Setting initial probe timeout to %s",
3527 memcpy(&base
->global_nameserver_probe_initial_timeout
, &tv
,
3534 evdns_set_option(const char *option
, const char *val
, int flags
)
3537 current_base
= evdns_base_new(NULL
, 0);
3538 return evdns_base_set_option(current_base
, option
, val
);
3542 resolv_conf_parse_line(struct evdns_base
*base
, char *const start
, int flags
) {
3544 static const char *const delims
= " \t";
3545 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3548 char *const first_token
= strtok_r(start
, delims
, &strtok_state
);
3549 ASSERT_LOCKED(base
);
3550 if (!first_token
) return;
3552 if (!strcmp(first_token
, "nameserver") && (flags
& DNS_OPTION_NAMESERVERS
)) {
3553 const char *const nameserver
= NEXT_TOKEN
;
3556 evdns_base_nameserver_ip_add(base
, nameserver
);
3557 } else if (!strcmp(first_token
, "domain") && (flags
& DNS_OPTION_SEARCH
)) {
3558 const char *const domain
= NEXT_TOKEN
;
3560 search_postfix_clear(base
);
3561 search_postfix_add(base
, domain
);
3563 } else if (!strcmp(first_token
, "search") && (flags
& DNS_OPTION_SEARCH
)) {
3565 search_postfix_clear(base
);
3567 while ((domain
= NEXT_TOKEN
)) {
3568 search_postfix_add(base
, domain
);
3570 search_reverse(base
);
3571 } else if (!strcmp(first_token
, "options")) {
3573 while ((option
= NEXT_TOKEN
)) {
3574 const char *val
= strchr(option
, ':');
3575 evdns_base_set_option_impl(base
, option
, val
? val
+1 : "", flags
);
3581 /* exported function */
3584 /* 1 failed to open file */
3585 /* 2 failed to stat file */
3586 /* 3 file too large */
3587 /* 4 out of memory */
3588 /* 5 short read from file */
3590 evdns_base_resolv_conf_parse(struct evdns_base
*base
, int flags
, const char *const filename
) {
3593 res
= evdns_base_resolv_conf_parse_impl(base
, flags
, filename
);
3599 evdns_get_default_hosts_filename(void)
3602 /* Windows is a little coy about where it puts its configuration
3603 * files. Sure, they're _usually_ in C:\windows\system32, but
3604 * there's no reason in principle they couldn't be in
3605 * W:\hoboken chicken emergency\
3607 char path
[MAX_PATH
+1];
3608 static const char hostfile
[] = "\\drivers\\etc\\hosts";
3612 if (! SHGetSpecialFolderPathA(NULL
, path
, CSIDL_SYSTEM
, 0))
3614 len_out
= strlen(path
)+strlen(hostfile
);
3615 path_out
= mm_malloc(len_out
+1);
3616 evutil_snprintf(path_out
, len_out
, "%s%s", path
, hostfile
);
3619 return mm_strdup("/etc/hosts");
3624 evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
) {
3630 log(EVDNS_LOG_DEBUG
, "Parsing resolv.conf file %s", filename
);
3632 if (flags
& DNS_OPTION_HOSTSFILE
) {
3633 char *fname
= evdns_get_default_hosts_filename();
3634 evdns_base_load_hosts(base
, fname
);
3639 if ((err
= evutil_read_file(filename
, &resolv
, &n
, 0)) < 0) {
3642 evdns_resolv_set_defaults(base
, flags
);
3651 char *const newline
= strchr(start
, '\n');
3653 resolv_conf_parse_line(base
, start
, flags
);
3657 resolv_conf_parse_line(base
, start
, flags
);
3658 start
= newline
+ 1;
3662 if (!base
->server_head
&& (flags
& DNS_OPTION_NAMESERVERS
)) {
3663 /* no nameservers were configured. */
3664 evdns_base_nameserver_ip_add(base
, "127.0.0.1");
3667 if (flags
& DNS_OPTION_SEARCH
&& (!base
->global_search_state
|| base
->global_search_state
->num_domains
== 0)) {
3668 search_set_from_hostname(base
);
3676 evdns_resolv_conf_parse(int flags
, const char *const filename
) {
3678 current_base
= evdns_base_new(NULL
, 0);
3679 return evdns_base_resolv_conf_parse(current_base
, flags
, filename
);
3684 /* Add multiple nameservers from a space-or-comma-separated list. */
3686 evdns_nameserver_ip_add_line(struct evdns_base
*base
, const char *ips
) {
3690 ASSERT_LOCKED(base
);
3692 while (isspace(*ips
) || *ips
== ',' || *ips
== '\t')
3695 while (isdigit(*ips
) || *ips
== '.' || *ips
== ':' ||
3696 *ips
=='[' || *ips
==']')
3698 buf
= mm_malloc(ips
-addr
+1);
3700 memcpy(buf
, addr
, ips
-addr
);
3701 buf
[ips
-addr
] = '\0';
3702 r
= evdns_base_nameserver_ip_add(base
, buf
);
3709 typedef DWORD(WINAPI
*GetNetworkParams_fn_t
)(FIXED_INFO
*, DWORD
*);
3711 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3712 /* figure out what our nameservers are. */
3714 load_nameservers_with_getnetworkparams(struct evdns_base
*base
)
3716 /* Based on MSDN examples and inspection of c-ares code. */
3719 ULONG size
= sizeof(FIXED_INFO
);
3721 int status
= 0, r
, added_any
;
3723 GetNetworkParams_fn_t fn
;
3725 ASSERT_LOCKED(base
);
3726 if (!(handle
= evutil_load_windows_system_library(
3727 TEXT("iphlpapi.dll")))) {
3728 log(EVDNS_LOG_WARN
, "Could not open iphlpapi.dll");
3732 if (!(fn
= (GetNetworkParams_fn_t
) GetProcAddress(handle
, "GetNetworkParams"))) {
3733 log(EVDNS_LOG_WARN
, "Could not get address of function.");
3738 buf
= mm_malloc(size
);
3739 if (!buf
) { status
= 4; goto done
; }
3741 r
= fn(fixed
, &size
);
3742 if (r
!= ERROR_SUCCESS
&& r
!= ERROR_BUFFER_OVERFLOW
) {
3746 if (r
!= ERROR_SUCCESS
) {
3748 buf
= mm_malloc(size
);
3749 if (!buf
) { status
= 4; goto done
; }
3751 r
= fn(fixed
, &size
);
3752 if (r
!= ERROR_SUCCESS
) {
3753 log(EVDNS_LOG_DEBUG
, "fn() failed.");
3759 EVUTIL_ASSERT(fixed
);
3761 ns
= &(fixed
->DnsServerList
);
3763 r
= evdns_nameserver_ip_add_line(base
, ns
->IpAddress
.String
);
3765 log(EVDNS_LOG_DEBUG
,"Could not add nameserver %s to list,error: %d",
3766 (ns
->IpAddress
.String
),(int)GetLastError());
3770 log(EVDNS_LOG_DEBUG
,"Successfully added %s as nameserver",ns
->IpAddress
.String
);
3777 log(EVDNS_LOG_DEBUG
, "No nameservers added.");
3788 FreeLibrary(handle
);
3793 config_nameserver_from_reg_key(struct evdns_base
*base
, HKEY key
, const TCHAR
*subkey
)
3796 DWORD bufsz
= 0, type
= 0;
3799 ASSERT_LOCKED(base
);
3800 if (RegQueryValueEx(key
, subkey
, 0, &type
, NULL
, &bufsz
)
3803 if (!(buf
= mm_malloc(bufsz
)))
3806 if (RegQueryValueEx(key
, subkey
, 0, &type
, (LPBYTE
)buf
, &bufsz
)
3807 == ERROR_SUCCESS
&& bufsz
> 1) {
3808 status
= evdns_nameserver_ip_add_line(base
,buf
);
3815 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3816 #define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
3817 #define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
3820 load_nameservers_from_registry(struct evdns_base
*base
)
3824 #define TRY(k, name) \
3825 if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3826 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3828 } else if (!found) { \
3829 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3833 ASSERT_LOCKED(base
);
3835 if (((int)GetVersion()) > 0) { /* NT */
3836 HKEY nt_key
= 0, interfaces_key
= 0;
3838 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_NT_KEY
, 0,
3839 KEY_READ
, &nt_key
) != ERROR_SUCCESS
) {
3840 log(EVDNS_LOG_DEBUG
,"Couldn't open nt key, %d",(int)GetLastError());
3843 r
= RegOpenKeyEx(nt_key
, TEXT("Interfaces"), 0,
3844 KEY_QUERY_VALUE
|KEY_ENUMERATE_SUB_KEYS
,
3846 if (r
!= ERROR_SUCCESS
) {
3847 log(EVDNS_LOG_DEBUG
,"Couldn't open interfaces key, %d",(int)GetLastError());
3850 TRY(nt_key
, "NameServer");
3851 TRY(nt_key
, "DhcpNameServer");
3852 TRY(interfaces_key
, "NameServer");
3853 TRY(interfaces_key
, "DhcpNameServer");
3854 RegCloseKey(interfaces_key
);
3855 RegCloseKey(nt_key
);
3858 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_9X_KEY
, 0,
3859 KEY_READ
, &win_key
) != ERROR_SUCCESS
) {
3860 log(EVDNS_LOG_DEBUG
, "Couldn't open registry key, %d", (int)GetLastError());
3863 TRY(win_key
, "NameServer");
3864 RegCloseKey(win_key
);
3868 log(EVDNS_LOG_WARN
,"Didn't find any nameservers.");
3871 return found
? 0 : -1;
3876 evdns_base_config_windows_nameservers(struct evdns_base
*base
)
3881 base
= current_base
;
3885 if (load_nameservers_with_getnetworkparams(base
) == 0) {
3889 r
= load_nameservers_from_registry(base
);
3891 fname
= evdns_get_default_hosts_filename();
3892 evdns_base_load_hosts(base
, fname
);
3901 evdns_config_windows_nameservers(void)
3903 if (!current_base
) {
3904 current_base
= evdns_base_new(NULL
, 1);
3905 return current_base
== NULL
? -1 : 0;
3907 return evdns_base_config_windows_nameservers(current_base
);
3913 evdns_base_new(struct event_base
*event_base
, int initialize_nameservers
)
3915 struct evdns_base
*base
;
3917 if (rand_init_function
!= NULL
&& rand_init_function() < 0) {
3918 log(EVDNS_LOG_WARN
, "Unable to seed random number generator; "
3923 /* Give the evutil library a hook into its evdns-enabled
3924 * functionality. We can't just call evdns_getaddrinfo directly or
3925 * else libevent-core will depend on libevent-extras. */
3926 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo
);
3928 base
= mm_malloc(sizeof(struct evdns_base
));
3931 memset(base
, 0, sizeof(struct evdns_base
));
3932 base
->req_waiting_head
= NULL
;
3934 EVTHREAD_ALLOC_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
3937 /* Set max requests inflight and allocate req_heads. */
3938 base
->req_heads
= NULL
;
3940 evdns_base_set_max_requests_inflight(base
, 64);
3942 base
->server_head
= NULL
;
3943 base
->event_base
= event_base
;
3944 base
->global_good_nameservers
= base
->global_requests_inflight
=
3945 base
->global_requests_waiting
= 0;
3947 base
->global_timeout
.tv_sec
= 5;
3948 base
->global_timeout
.tv_usec
= 0;
3949 base
->global_max_reissues
= 1;
3950 base
->global_max_retransmits
= 3;
3951 base
->global_max_nameserver_timeout
= 3;
3952 base
->global_search_state
= NULL
;
3953 base
->global_randomize_case
= 1;
3954 base
->global_getaddrinfo_allow_skew
.tv_sec
= 3;
3955 base
->global_getaddrinfo_allow_skew
.tv_usec
= 0;
3956 base
->global_nameserver_probe_initial_timeout
.tv_sec
= 10;
3957 base
->global_nameserver_probe_initial_timeout
.tv_usec
= 0;
3959 TAILQ_INIT(&base
->hostsdb
);
3961 if (initialize_nameservers
) {
3964 r
= evdns_base_config_windows_nameservers(base
);
3966 r
= evdns_base_resolv_conf_parse(base
, DNS_OPTIONS_ALL
, "/etc/resolv.conf");
3969 evdns_base_free_and_unlock(base
, 0);
3980 struct evdns_base
*base
= evdns_base_new(NULL
, 1);
3982 current_base
= base
;
3990 evdns_err_to_string(int err
)
3993 case DNS_ERR_NONE
: return "no error";
3994 case DNS_ERR_FORMAT
: return "misformatted query";
3995 case DNS_ERR_SERVERFAILED
: return "server failed";
3996 case DNS_ERR_NOTEXIST
: return "name does not exist";
3997 case DNS_ERR_NOTIMPL
: return "query not implemented";
3998 case DNS_ERR_REFUSED
: return "refused";
4000 case DNS_ERR_TRUNCATED
: return "reply truncated or ill-formed";
4001 case DNS_ERR_UNKNOWN
: return "unknown";
4002 case DNS_ERR_TIMEOUT
: return "request timed out";
4003 case DNS_ERR_SHUTDOWN
: return "dns subsystem shut down";
4004 case DNS_ERR_CANCEL
: return "dns request canceled";
4005 case DNS_ERR_NODATA
: return "no records in the reply";
4006 default: return "[Unknown error code]";
4011 evdns_nameserver_free(struct nameserver
*server
)
4013 if (server
->socket
>= 0)
4014 evutil_closesocket(server
->socket
);
4015 (void) event_del(&server
->event
);
4016 event_debug_unassign(&server
->event
);
4017 if (server
->state
== 0)
4018 (void) event_del(&server
->timeout_event
);
4019 event_debug_unassign(&server
->timeout_event
);
4024 evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
)
4026 struct nameserver
*server
, *server_next
;
4027 struct search_domain
*dom
, *dom_next
;
4030 /* Requires that we hold the lock. */
4032 /* TODO(nickm) we might need to refcount here. */
4034 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
4035 while (base
->req_heads
[i
]) {
4037 reply_schedule_callback(base
->req_heads
[i
], 0, DNS_ERR_SHUTDOWN
, NULL
);
4038 request_finished(base
->req_heads
[i
], &REQ_HEAD(base
, base
->req_heads
[i
]->trans_id
), 1);
4041 while (base
->req_waiting_head
) {
4043 reply_schedule_callback(base
->req_waiting_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
4044 request_finished(base
->req_waiting_head
, &base
->req_waiting_head
, 1);
4046 base
->global_requests_inflight
= base
->global_requests_waiting
= 0;
4048 for (server
= base
->server_head
; server
; server
= server_next
) {
4049 server_next
= server
->next
;
4050 evdns_nameserver_free(server
);
4051 if (server_next
== base
->server_head
)
4054 base
->server_head
= NULL
;
4055 base
->global_good_nameservers
= 0;
4057 if (base
->global_search_state
) {
4058 for (dom
= base
->global_search_state
->head
; dom
; dom
= dom_next
) {
4059 dom_next
= dom
->next
;
4062 mm_free(base
->global_search_state
);
4063 base
->global_search_state
= NULL
;
4067 struct hosts_entry
*victim
;
4068 while ((victim
= TAILQ_FIRST(&base
->hostsdb
))) {
4069 TAILQ_REMOVE(&base
->hostsdb
, victim
, next
);
4074 mm_free(base
->req_heads
);
4077 EVTHREAD_FREE_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
4083 evdns_base_free(struct evdns_base
*base
, int fail_requests
)
4086 evdns_base_free_and_unlock(base
, fail_requests
);
4090 evdns_shutdown(int fail_requests
)
4093 struct evdns_base
*b
= current_base
;
4094 current_base
= NULL
;
4095 evdns_base_free(b
, fail_requests
);
4097 evdns_log_fn
= NULL
;
4101 evdns_base_parse_hosts_line(struct evdns_base
*base
, char *line
)
4104 static const char *const delims
= " \t";
4105 char *const addr
= strtok_r(line
, delims
, &strtok_state
);
4106 char *hostname
, *hash
;
4107 struct sockaddr_storage ss
;
4108 int socklen
= sizeof(ss
);
4109 ASSERT_LOCKED(base
);
4111 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
4113 if (!addr
|| *addr
== '#')
4116 memset(&ss
, 0, sizeof(ss
));
4117 if (evutil_parse_sockaddr_port(addr
, (struct sockaddr
*)&ss
, &socklen
)<0)
4119 if (socklen
> (int)sizeof(struct sockaddr_in6
))
4122 if (sockaddr_getport((struct sockaddr
*)&ss
))
4125 while ((hostname
= NEXT_TOKEN
)) {
4126 struct hosts_entry
*he
;
4128 if ((hash
= strchr(hostname
, '#'))) {
4129 if (hash
== hostname
)
4134 namelen
= strlen(hostname
);
4136 he
= mm_calloc(1, sizeof(struct hosts_entry
)+namelen
);
4139 EVUTIL_ASSERT(socklen
<= (int)sizeof(he
->addr
));
4140 memcpy(&he
->addr
, &ss
, socklen
);
4141 memcpy(he
->hostname
, hostname
, namelen
+1);
4142 he
->addrlen
= socklen
;
4144 TAILQ_INSERT_TAIL(&base
->hostsdb
, he
, next
);
4155 evdns_base_load_hosts_impl(struct evdns_base
*base
, const char *hosts_fname
)
4157 char *str
=NULL
, *cp
, *eol
;
4161 ASSERT_LOCKED(base
);
4163 if (hosts_fname
== NULL
||
4164 (err
= evutil_read_file(hosts_fname
, &str
, &len
, 0)) < 0) {
4166 strlcpy(tmp
, "127.0.0.1 localhost", sizeof(tmp
));
4167 evdns_base_parse_hosts_line(base
, tmp
);
4168 strlcpy(tmp
, "::1 localhost", sizeof(tmp
));
4169 evdns_base_parse_hosts_line(base
, tmp
);
4170 return err
? -1 : 0;
4173 /* This will break early if there is a NUL in the hosts file.
4174 * Probably not a problem.*/
4177 eol
= strchr(cp
, '\n');
4181 evdns_base_parse_hosts_line(base
, cp
);
4184 evdns_base_parse_hosts_line(base
, cp
);
4194 evdns_base_load_hosts(struct evdns_base
*base
, const char *hosts_fname
)
4198 base
= current_base
;
4200 res
= evdns_base_load_hosts_impl(base
, hosts_fname
);
4205 /* A single request for a getaddrinfo, either v4 or v6. */
4206 struct getaddrinfo_subrequest
{
4207 struct evdns_request
*r
;
4211 /* State data used to implement an in-progress getaddrinfo. */
4212 struct evdns_getaddrinfo_request
{
4213 struct evdns_base
*evdns_base
;
4214 /* Copy of the modified 'hints' data that we'll use to build
4216 struct evutil_addrinfo hints
;
4217 /* The callback to invoke when we're done */
4218 evdns_getaddrinfo_cb user_cb
;
4219 /* User-supplied data to give to the callback. */
4221 /* The port to use when building sockaddrs. */
4223 /* The sub_request for an A record (if any) */
4224 struct getaddrinfo_subrequest ipv4_request
;
4225 /* The sub_request for an AAAA record (if any) */
4226 struct getaddrinfo_subrequest ipv6_request
;
4228 /* The cname result that we were told (if any) */
4231 /* If we have one request answered and one request still inflight,
4232 * then this field holds the answer from the first request... */
4233 struct evutil_addrinfo
*pending_result
;
4234 /* And this event is a timeout that will tell us to cancel the second
4235 * request if it's taking a long time. */
4236 struct event timeout
;
4238 /* And this field holds the error code from the first request... */
4240 /* If this is set, the user canceled this request. */
4241 unsigned user_canceled
: 1;
4242 /* If this is set, the user can no longer cancel this request; we're
4243 * just waiting for the free. */
4244 unsigned request_done
: 1;
4247 /* Convert an evdns errors to the equivalent getaddrinfo error. */
4249 evdns_err_to_getaddrinfo_err(int e1
)
4251 /* XXX Do this better! */
4252 if (e1
== DNS_ERR_NONE
)
4254 else if (e1
== DNS_ERR_NOTEXIST
)
4255 return EVUTIL_EAI_NONAME
;
4257 return EVUTIL_EAI_FAIL
;
4260 /* Return the more informative of two getaddrinfo errors. */
4262 getaddrinfo_merge_err(int e1
, int e2
)
4264 /* XXXX be cleverer here. */
4272 free_getaddrinfo_request(struct evdns_getaddrinfo_request
*data
)
4274 /* DO NOT CALL this if either of the requests is pending. Only once
4275 * both callbacks have been invoked is it safe to free the request */
4276 if (data
->pending_result
)
4277 evutil_freeaddrinfo(data
->pending_result
);
4278 if (data
->cname_result
)
4279 mm_free(data
->cname_result
);
4280 event_del(&data
->timeout
);
4286 add_cname_to_reply(struct evdns_getaddrinfo_request
*data
,
4287 struct evutil_addrinfo
*ai
)
4289 if (data
->cname_result
&& ai
) {
4290 ai
->ai_canonname
= data
->cname_result
;
4291 data
->cname_result
= NULL
;
4295 /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
4296 * request has finished, but the other one took too long to answer. Pass
4297 * along the answer we got, and cancel the other request.
4300 evdns_getaddrinfo_timeout_cb(evutil_socket_t fd
, short what
, void *ptr
)
4302 int v4_timedout
= 0, v6_timedout
= 0;
4303 struct evdns_getaddrinfo_request
*data
= ptr
;
4305 /* Cancel any pending requests, and note which one */
4306 if (data
->ipv4_request
.r
) {
4307 /* XXXX This does nothing if the request's callback is already
4308 * running (pending_cb is set). */
4309 evdns_cancel_request(NULL
, data
->ipv4_request
.r
);
4311 EVDNS_LOCK(data
->evdns_base
);
4312 ++data
->evdns_base
->getaddrinfo_ipv4_timeouts
;
4313 EVDNS_UNLOCK(data
->evdns_base
);
4315 if (data
->ipv6_request
.r
) {
4316 /* XXXX This does nothing if the request's callback is already
4317 * running (pending_cb is set). */
4318 evdns_cancel_request(NULL
, data
->ipv6_request
.r
);
4320 EVDNS_LOCK(data
->evdns_base
);
4321 ++data
->evdns_base
->getaddrinfo_ipv6_timeouts
;
4322 EVDNS_UNLOCK(data
->evdns_base
);
4325 /* We only use this timeout callback when we have an answer for
4327 EVUTIL_ASSERT(!v4_timedout
|| !v6_timedout
);
4329 /* Report the outcome of the other request that didn't time out. */
4330 if (data
->pending_result
) {
4331 add_cname_to_reply(data
, data
->pending_result
);
4332 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4333 data
->pending_result
= NULL
;
4335 int e
= data
->pending_error
;
4337 e
= EVUTIL_EAI_AGAIN
;
4338 data
->user_cb(e
, NULL
, data
->user_data
);
4341 data
->user_cb
= NULL
; /* prevent double-call if evdns callbacks are
4342 * in-progress. XXXX It would be better if this
4343 * weren't necessary. */
4345 if (!v4_timedout
&& !v6_timedout
) {
4346 /* should be impossible? XXXX */
4347 free_getaddrinfo_request(data
);
4352 evdns_getaddrinfo_set_timeout(struct evdns_base
*evdns_base
,
4353 struct evdns_getaddrinfo_request
*data
)
4355 return event_add(&data
->timeout
, &evdns_base
->global_getaddrinfo_allow_skew
);
4359 evdns_result_is_answer(int result
)
4361 return (result
!= DNS_ERR_NOTIMPL
&& result
!= DNS_ERR_REFUSED
&&
4362 result
!= DNS_ERR_SERVERFAILED
&& result
!= DNS_ERR_CANCEL
);
4366 evdns_getaddrinfo_gotresolve(int result
, char type
, int count
,
4367 int ttl
, void *addresses
, void *arg
)
4370 struct getaddrinfo_subrequest
*req
= arg
;
4371 struct getaddrinfo_subrequest
*other_req
;
4372 struct evdns_getaddrinfo_request
*data
;
4374 struct evutil_addrinfo
*res
;
4376 struct sockaddr_in sin
;
4377 struct sockaddr_in6 sin6
;
4378 struct sockaddr
*sa
;
4379 int socklen
, addrlen
;
4384 EVUTIL_ASSERT(req
->type
== DNS_IPv4_A
|| req
->type
== DNS_IPv6_AAAA
);
4385 if (req
->type
== DNS_IPv4_A
) {
4386 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv4_request
);
4387 other_req
= &data
->ipv6_request
;
4389 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv6_request
);
4390 other_req
= &data
->ipv4_request
;
4393 EVDNS_LOCK(data
->evdns_base
);
4394 if (evdns_result_is_answer(result
)) {
4395 if (req
->type
== DNS_IPv4_A
)
4396 ++data
->evdns_base
->getaddrinfo_ipv4_answered
;
4398 ++data
->evdns_base
->getaddrinfo_ipv6_answered
;
4400 user_canceled
= data
->user_canceled
;
4401 if (other_req
->r
== NULL
)
4402 data
->request_done
= 1;
4403 EVDNS_UNLOCK(data
->evdns_base
);
4407 if (result
== DNS_ERR_CANCEL
&& ! user_canceled
) {
4408 /* Internal cancel request from timeout or internal error.
4409 * we already answered the user. */
4410 if (other_req
->r
== NULL
)
4411 free_getaddrinfo_request(data
);
4415 if (data
->user_cb
== NULL
) {
4416 /* We already answered. XXXX This shouldn't be needed; see
4417 * comments in evdns_getaddrinfo_timeout_cb */
4418 free_getaddrinfo_request(data
);
4422 if (result
== DNS_ERR_NONE
) {
4424 err
= EVUTIL_EAI_NODATA
;
4428 err
= evdns_err_to_getaddrinfo_err(result
);
4432 /* Looks like we got an error. */
4434 /* The other request is still working; maybe it will
4436 /* XXXX handle failure from set_timeout */
4437 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4438 data
->pending_error
= err
;
4442 if (user_canceled
) {
4443 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4444 } else if (data
->pending_result
) {
4445 /* If we have an answer waiting, and we weren't
4446 * canceled, ignore this error. */
4447 add_cname_to_reply(data
, data
->pending_result
);
4448 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4449 data
->pending_result
= NULL
;
4451 if (data
->pending_error
)
4452 err
= getaddrinfo_merge_err(err
,
4453 data
->pending_error
);
4454 data
->user_cb(err
, NULL
, data
->user_data
);
4456 free_getaddrinfo_request(data
);
4458 } else if (user_canceled
) {
4460 /* The other request is still working; let it hit this
4461 * callback with EVUTIL_EAI_CANCEL callback and report
4465 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4466 free_getaddrinfo_request(data
);
4470 /* Looks like we got some answers. We should turn them into addrinfos
4471 * and then either queue those or return them all. */
4472 EVUTIL_ASSERT(type
== DNS_IPv4_A
|| type
== DNS_IPv6_AAAA
);
4474 if (type
== DNS_IPv4_A
) {
4475 memset(&sin
, 0, sizeof(sin
));
4476 sin
.sin_family
= AF_INET
;
4477 sin
.sin_port
= htons(data
->port
);
4479 sa
= (struct sockaddr
*)&sin
;
4480 socklen
= sizeof(sin
);
4482 addrp
= &sin
.sin_addr
.s_addr
;
4484 memset(&sin6
, 0, sizeof(sin6
));
4485 sin6
.sin6_family
= AF_INET6
;
4486 sin6
.sin6_port
= htons(data
->port
);
4488 sa
= (struct sockaddr
*)&sin6
;
4489 socklen
= sizeof(sin6
);
4491 addrp
= &sin6
.sin6_addr
.s6_addr
;
4495 for (i
=0; i
< count
; ++i
) {
4496 struct evutil_addrinfo
*ai
;
4497 memcpy(addrp
, ((char*)addresses
)+i
*addrlen
, addrlen
);
4498 ai
= evutil_new_addrinfo(sa
, socklen
, &data
->hints
);
4501 evdns_cancel_request(NULL
, other_req
->r
);
4503 data
->user_cb(EVUTIL_EAI_MEMORY
, NULL
, data
->user_data
);
4505 evutil_freeaddrinfo(res
);
4507 if (other_req
->r
== NULL
)
4508 free_getaddrinfo_request(data
);
4511 res
= evutil_addrinfo_append(res
, ai
);
4515 /* The other request is still in progress; wait for it */
4516 /* XXXX handle failure from set_timeout */
4517 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4518 data
->pending_result
= res
;
4521 /* The other request is done or never started; append its
4522 * results (if any) and return them. */
4523 if (data
->pending_result
) {
4524 if (req
->type
== DNS_IPv4_A
)
4525 res
= evutil_addrinfo_append(res
,
4526 data
->pending_result
);
4528 res
= evutil_addrinfo_append(
4529 data
->pending_result
, res
);
4530 data
->pending_result
= NULL
;
4533 /* Call the user callback. */
4534 add_cname_to_reply(data
, res
);
4535 data
->user_cb(0, res
, data
->user_data
);
4538 free_getaddrinfo_request(data
);
4542 static struct hosts_entry
*
4543 find_hosts_entry(struct evdns_base
*base
, const char *hostname
,
4544 struct hosts_entry
*find_after
)
4546 struct hosts_entry
*e
;
4549 e
= TAILQ_NEXT(find_after
, next
);
4551 e
= TAILQ_FIRST(&base
->hostsdb
);
4553 for (; e
; e
= TAILQ_NEXT(e
, next
)) {
4554 if (!evutil_ascii_strcasecmp(e
->hostname
, hostname
))
4561 evdns_getaddrinfo_fromhosts(struct evdns_base
*base
,
4562 const char *nodename
, struct evutil_addrinfo
*hints
, ev_uint16_t port
,
4563 struct evutil_addrinfo
**res
)
4566 struct hosts_entry
*e
;
4567 struct evutil_addrinfo
*ai
=NULL
;
4568 int f
= hints
->ai_family
;
4571 for (e
= find_hosts_entry(base
, nodename
, NULL
); e
;
4572 e
= find_hosts_entry(base
, nodename
, e
)) {
4573 struct evutil_addrinfo
*ai_new
;
4575 if ((e
->addr
.sa
.sa_family
== AF_INET
&& f
== PF_INET6
) ||
4576 (e
->addr
.sa
.sa_family
== AF_INET6
&& f
== PF_INET
))
4578 ai_new
= evutil_new_addrinfo(&e
->addr
.sa
, e
->addrlen
, hints
);
4583 sockaddr_setport(ai_new
->ai_addr
, port
);
4584 ai
= evutil_addrinfo_append(ai
, ai_new
);
4589 /* Note that we return an empty answer if we found entries for
4590 * this hostname but none were of the right address type. */
4595 evutil_freeaddrinfo(ai
);
4600 struct evdns_getaddrinfo_request
*
4601 evdns_getaddrinfo(struct evdns_base
*dns_base
,
4602 const char *nodename
, const char *servname
,
4603 const struct evutil_addrinfo
*hints_in
,
4604 evdns_getaddrinfo_cb cb
, void *arg
)
4606 struct evdns_getaddrinfo_request
*data
;
4607 struct evutil_addrinfo hints
;
4608 struct evutil_addrinfo
*res
= NULL
;
4614 dns_base
= current_base
;
4617 "Call to getaddrinfo_async with no "
4618 "evdns_base configured.");
4619 cb(EVUTIL_EAI_FAIL
, NULL
, arg
); /* ??? better error? */
4624 /* If we _must_ answer this immediately, do so. */
4625 if ((hints_in
&& (hints_in
->ai_flags
& EVUTIL_AI_NUMERICHOST
))) {
4627 err
= evutil_getaddrinfo(nodename
, servname
, hints_in
, &res
);
4633 memcpy(&hints
, hints_in
, sizeof(hints
));
4635 memset(&hints
, 0, sizeof(hints
));
4636 hints
.ai_family
= PF_UNSPEC
;
4639 evutil_adjust_hints_for_addrconfig(&hints
);
4641 /* Now try to see if we _can_ answer immediately. */
4642 /* (It would be nice to do this by calling getaddrinfo directly, with
4643 * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
4644 * a reliable way to distinguish the "that wasn't a numeric host!" case
4645 * from any other EAI_NONAME cases.) */
4646 err
= evutil_getaddrinfo_common(nodename
, servname
, &hints
, &res
, &port
);
4647 if (err
!= EVUTIL_EAI_NEED_RESOLVE
) {
4652 /* If there is an entry in the hosts file, we should give it now. */
4653 if (!evdns_getaddrinfo_fromhosts(dns_base
, nodename
, &hints
, port
, &res
)) {
4658 /* Okay, things are serious now. We're going to need to actually
4661 data
= mm_calloc(1,sizeof(struct evdns_getaddrinfo_request
));
4663 cb(EVUTIL_EAI_MEMORY
, NULL
, arg
);
4667 memcpy(&data
->hints
, &hints
, sizeof(data
->hints
));
4668 data
->port
= (ev_uint16_t
)port
;
4669 data
->ipv4_request
.type
= DNS_IPv4_A
;
4670 data
->ipv6_request
.type
= DNS_IPv6_AAAA
;
4672 data
->user_data
= arg
;
4673 data
->evdns_base
= dns_base
;
4675 want_cname
= (hints
.ai_flags
& EVUTIL_AI_CANONNAME
);
4677 /* If we are asked for a PF_UNSPEC address, we launch two requests in
4678 * parallel: one for an A address and one for an AAAA address. We
4679 * can't send just one request, since many servers only answer one
4680 * question per DNS request.
4682 * Once we have the answer to one request, we allow for a short
4683 * timeout before we report it, to see if the other one arrives. If
4684 * they both show up in time, then we report both the answers.
4686 * If too many addresses of one type time out or fail, we should stop
4687 * launching those requests. (XXX we don't do that yet.)
4690 if (hints
.ai_family
!= PF_INET6
) {
4691 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv4 as %p",
4692 nodename
, &data
->ipv4_request
);
4694 data
->ipv4_request
.r
= evdns_base_resolve_ipv4(dns_base
,
4695 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4696 &data
->ipv4_request
);
4698 data
->ipv4_request
.r
->current_req
->put_cname_in_ptr
=
4699 &data
->cname_result
;
4701 if (hints
.ai_family
!= PF_INET
) {
4702 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv6 as %p",
4703 nodename
, &data
->ipv6_request
);
4705 data
->ipv6_request
.r
= evdns_base_resolve_ipv6(dns_base
,
4706 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4707 &data
->ipv6_request
);
4709 data
->ipv6_request
.r
->current_req
->put_cname_in_ptr
=
4710 &data
->cname_result
;
4713 evtimer_assign(&data
->timeout
, dns_base
->event_base
,
4714 evdns_getaddrinfo_timeout_cb
, data
);
4716 if (data
->ipv4_request
.r
|| data
->ipv6_request
.r
) {
4720 cb(EVUTIL_EAI_FAIL
, NULL
, arg
);
4726 evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request
*data
)
4728 EVDNS_LOCK(data
->evdns_base
);
4729 if (data
->request_done
) {
4730 EVDNS_UNLOCK(data
->evdns_base
);
4733 event_del(&data
->timeout
);
4734 data
->user_canceled
= 1;
4735 if (data
->ipv4_request
.r
)
4736 evdns_cancel_request(data
->evdns_base
, data
->ipv4_request
.r
);
4737 if (data
->ipv6_request
.r
)
4738 evdns_cancel_request(data
->evdns_base
, data
->ipv6_request
.r
);
4739 EVDNS_UNLOCK(data
->evdns_base
);