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 "event2/event-config.h"
52 #include "evconfig-private.h"
54 #include <sys/types.h>
56 #ifndef _FORTIFY_SOURCE
57 #define _FORTIFY_SOURCE 3
62 #ifdef EVENT__HAVE_SYS_TIME_H
65 #ifdef EVENT__HAVE_STDINT_H
71 #ifdef EVENT__HAVE_UNISTD_H
82 #define _WIN32_IE 0x400
87 #include "event2/dns.h"
88 #include "event2/dns_struct.h"
89 #include "event2/dns_compat.h"
90 #include "event2/util.h"
91 #include "event2/event.h"
92 #include "event2/event_struct.h"
93 #include "event2/thread.h"
95 #include "defer-internal.h"
96 #include "log-internal.h"
97 #include "mm-internal.h"
98 #include "strlcpy-internal.h"
99 #include "ipv6-internal.h"
100 #include "util-internal.h"
101 #include "evthread-internal.h"
104 #include <winsock2.h>
106 #include <iphlpapi.h>
109 #include <sys/socket.h>
110 #include <netinet/in.h>
111 #include <arpa/inet.h>
114 #ifdef EVENT__HAVE_NETINET_IN6_H
115 #include <netinet/in6.h>
118 #define EVDNS_LOG_DEBUG EVENT_LOG_DEBUG
119 #define EVDNS_LOG_WARN EVENT_LOG_WARN
120 #define EVDNS_LOG_MSG EVENT_LOG_MSG
122 #ifndef HOST_NAME_MAX
123 #define HOST_NAME_MAX 255
129 #define MIN(a,b) ((a)<(b)?(a):(b))
131 #define ASSERT_VALID_REQUEST(req) \
132 EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
134 #define u64 ev_uint64_t
135 #define u32 ev_uint32_t
136 #define u16 ev_uint16_t
137 #define u8 ev_uint8_t
139 /* maximum number of addresses from a single packet */
140 /* that we bother recording */
141 #define MAX_V4_ADDRS 32
142 #define MAX_V6_ADDRS 32
145 #define TYPE_A EVDNS_TYPE_A
147 #define TYPE_PTR EVDNS_TYPE_PTR
148 #define TYPE_SOA EVDNS_TYPE_SOA
149 #define TYPE_AAAA EVDNS_TYPE_AAAA
151 #define CLASS_INET EVDNS_CLASS_INET
153 /* Persistent handle. We keep this separate from 'struct request' since we
154 * need some object to last for as long as an evdns_request is outstanding so
155 * that it can be canceled, whereas a search request can lead to multiple
156 * 'struct request' instances being created over its lifetime. */
157 struct evdns_request
{
158 struct request
*current_req
;
159 struct evdns_base
*base
;
161 int pending_cb
; /* Waiting for its callback to be invoked; not
162 * owned by event base any more. */
164 /* elements used by the searching code */
166 struct search_state
*search_state
;
167 char *search_origname
; /* needs to be free()ed */
172 u8
*request
; /* the dns packet data */
173 u8 request_type
; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
174 unsigned int request_len
;
176 int tx_count
; /* the number of times that this packet has been sent */
177 void *user_pointer
; /* the pointer given to us for this request */
178 evdns_callback_type user_callback
;
179 struct nameserver
*ns
; /* the server which we last sent it */
181 /* these objects are kept in a circular list */
182 /* XXX We could turn this into a CIRCLEQ. */
183 struct request
*next
, *prev
;
185 struct event timeout_event
;
187 u16 trans_id
; /* the transaction id */
188 unsigned request_appended
:1; /* true if the request pointer is data which follows this struct */
189 unsigned transmit_me
:1; /* needs to be transmitted */
191 /* XXXX This is a horrible hack. */
192 char **put_cname_in_ptr
; /* store the cname here if we get one. */
194 struct evdns_base
*base
;
196 struct evdns_request
*handle
;
201 unsigned int have_answer
: 1;
205 u32 addresses
[MAX_V4_ADDRS
];
209 struct in6_addr addresses
[MAX_V6_ADDRS
];
212 char name
[HOST_NAME_MAX
];
218 evutil_socket_t socket
; /* a connected UDP socket */
219 struct sockaddr_storage address
;
220 ev_socklen_t addrlen
;
221 int failed_times
; /* number of times which we have given this server a chance */
222 int timedout
; /* number of times in a row a request has timed out */
224 /* these objects are kept in a circular list */
225 struct nameserver
*next
, *prev
;
226 struct event timeout_event
; /* used to keep the timeout for */
227 /* when we next probe this server. */
228 /* Valid if state == 0 */
229 /* Outstanding probe request for this nameserver, if any */
230 struct evdns_request
*probe_request
;
231 char state
; /* zero if we think that this server is down */
232 char choked
; /* true if we have an EAGAIN from this server's socket */
233 char write_waiting
; /* true if we are waiting for EV_WRITE events */
234 struct evdns_base
*base
;
236 /* Number of currently inflight requests: used
237 * to track when we should add/del the event. */
238 int requests_inflight
;
242 /* Represents a local port where we're listening for DNS requests. Right now, */
243 /* only UDP is supported. */
244 struct evdns_server_port
{
245 evutil_socket_t socket
; /* socket we use to read queries and write replies. */
246 int refcnt
; /* reference count. */
247 char choked
; /* Are we currently blocked from writing? */
248 char closing
; /* Are we trying to close this port, pending writes? */
249 evdns_request_callback_fn_type user_callback
; /* Fn to handle requests */
250 void *user_data
; /* Opaque pointer passed to user_callback */
251 struct event event
; /* Read/write event */
252 /* circular list of replies that we want to write. */
253 struct server_request
*pending_replies
;
254 struct event_base
*event_base
;
256 #ifndef EVENT__DISABLE_THREAD_SUPPORT
261 /* Represents part of a reply being built. (That is, a single RR.) */
262 struct server_reply_item
{
263 struct server_reply_item
*next
; /* next item in sequence. */
264 char *name
; /* name part of the RR */
265 u16 type
; /* The RR type */
266 u16
class; /* The RR class (usually CLASS_INET) */
267 u32 ttl
; /* The RR TTL */
268 char is_name
; /* True iff data is a label */
269 u16 datalen
; /* Length of data; -1 if data is a label */
270 void *data
; /* The contents of the RR */
273 /* Represents a request that we've received as a DNS server, and holds */
274 /* the components of the reply as we're constructing it. */
275 struct server_request
{
276 /* Pointers to the next and previous entries on the list of replies */
277 /* that we're waiting to write. Only set if we have tried to respond */
278 /* and gotten EAGAIN. */
279 struct server_request
*next_pending
;
280 struct server_request
*prev_pending
;
282 u16 trans_id
; /* Transaction id. */
283 struct evdns_server_port
*port
; /* Which port received this request on? */
284 struct sockaddr_storage addr
; /* Where to send the response */
285 ev_socklen_t addrlen
; /* length of addr */
287 int n_answer
; /* how many answer RRs have been set? */
288 int n_authority
; /* how many authority RRs have been set? */
289 int n_additional
; /* how many additional RRs have been set? */
291 struct server_reply_item
*answer
; /* linked list of answer RRs */
292 struct server_reply_item
*authority
; /* linked list of authority RRs */
293 struct server_reply_item
*additional
; /* linked list of additional RRs */
295 /* Constructed response. Only set once we're ready to send a reply. */
296 /* Once this is set, the RR fields are cleared, and no more should be set. */
300 /* Caller-visible fields: flags, questions. */
301 struct evdns_server_request base
;
305 /* An array of n_req_heads circular lists for inflight requests.
306 * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
308 struct request
**req_heads
;
309 /* A circular list of requests that we're waiting to send, but haven't
310 * sent yet because there are too many requests inflight */
311 struct request
*req_waiting_head
;
312 /* A circular list of nameservers. */
313 struct nameserver
*server_head
;
316 struct event_base
*event_base
;
318 /* The number of good nameservers that we have */
319 int global_good_nameservers
;
321 /* inflight requests are contained in the req_head list */
322 /* and are actually going out across the network */
323 int global_requests_inflight
;
324 /* requests which aren't inflight are in the waiting list */
325 /* and are counted here */
326 int global_requests_waiting
;
328 int global_max_requests_inflight
;
330 struct timeval global_timeout
; /* 5 seconds by default */
331 int global_max_reissues
; /* a reissue occurs when we get some errors from the server */
332 int global_max_retransmits
; /* number of times we'll retransmit a request which timed out */
333 /* number of timeouts in a row before we consider this server to be down */
334 int global_max_nameserver_timeout
;
335 /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
336 int global_randomize_case
;
338 /* The first time that a nameserver fails, how long do we wait before
339 * probing to see if it has returned? */
340 struct timeval global_nameserver_probe_initial_timeout
;
342 /** Port to bind to for outgoing DNS packets. */
343 struct sockaddr_storage global_outgoing_address
;
344 /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
345 ev_socklen_t global_outgoing_addrlen
;
347 struct timeval global_getaddrinfo_allow_skew
;
349 int getaddrinfo_ipv4_timeouts
;
350 int getaddrinfo_ipv6_timeouts
;
351 int getaddrinfo_ipv4_answered
;
352 int getaddrinfo_ipv6_answered
;
354 struct search_state
*global_search_state
;
356 TAILQ_HEAD(hosts_list
, hosts_entry
) hostsdb
;
358 #ifndef EVENT__DISABLE_THREAD_SUPPORT
362 int disable_when_inactive
;
366 TAILQ_ENTRY(hosts_entry
) next
;
369 struct sockaddr_in sin
;
370 struct sockaddr_in6 sin6
;
376 static struct evdns_base
*current_base
= NULL
;
379 evdns_get_global_base(void)
384 /* Given a pointer to an evdns_server_request, get the corresponding */
385 /* server_request. */
386 #define TO_SERVER_REQUEST(base_ptr) \
387 ((struct server_request*) \
388 (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
390 #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
392 static struct nameserver
*nameserver_pick(struct evdns_base
*base
);
393 static void evdns_request_insert(struct request
*req
, struct request
**head
);
394 static void evdns_request_remove(struct request
*req
, struct request
**head
);
395 static void nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
396 static int evdns_transmit(struct evdns_base
*base
);
397 static int evdns_request_transmit(struct request
*req
);
398 static void nameserver_send_probe(struct nameserver
*const ns
);
399 static void search_request_finished(struct evdns_request
*const);
400 static int search_try_next(struct evdns_request
*const req
);
401 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
);
402 static void evdns_requests_pump_waiting_queue(struct evdns_base
*base
);
403 static u16
transaction_id_pick(struct evdns_base
*base
);
404 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
);
405 static void request_submit(struct request
*const req
);
407 static int server_request_free(struct server_request
*req
);
408 static void server_request_free_answers(struct server_request
*req
);
409 static void server_port_free(struct evdns_server_port
*port
);
410 static void server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
411 static int evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
);
412 static int evdns_base_set_option_impl(struct evdns_base
*base
,
413 const char *option
, const char *val
, int flags
);
414 static void evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
);
415 static void evdns_request_timeout_callback(evutil_socket_t fd
, short events
, void *arg
);
417 static int strtoint(const char *const str
);
419 #ifdef EVENT__DISABLE_THREAD_SUPPORT
420 #define EVDNS_LOCK(base) EVUTIL_NIL_STMT_
421 #define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
422 #define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
424 #define EVDNS_LOCK(base) \
425 EVLOCK_LOCK((base)->lock, 0)
426 #define EVDNS_UNLOCK(base) \
427 EVLOCK_UNLOCK((base)->lock, 0)
428 #define ASSERT_LOCKED(base) \
429 EVLOCK_ASSERT_LOCKED((base)->lock)
432 static evdns_debug_log_fn_type evdns_log_fn
= NULL
;
435 evdns_set_log_fn(evdns_debug_log_fn_type fn
)
441 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
443 #define EVDNS_LOG_CHECK
446 static void evdns_log_(int severity
, const char *fmt
, ...) EVDNS_LOG_CHECK
;
448 evdns_log_(int severity
, const char *fmt
, ...)
454 int is_warn
= (severity
== EVDNS_LOG_WARN
);
455 evutil_vsnprintf(buf
, sizeof(buf
), fmt
, args
);
456 evdns_log_fn(is_warn
, buf
);
458 event_logv_(severity
, NULL
, fmt
, args
);
463 #define log evdns_log_
465 /* This walks the list of inflight requests to find the */
466 /* one with a matching transaction id. Returns NULL on */
468 static struct request
*
469 request_find_from_trans_id(struct evdns_base
*base
, u16 trans_id
) {
470 struct request
*req
= REQ_HEAD(base
, trans_id
);
471 struct request
*const started_at
= req
;
477 if (req
->trans_id
== trans_id
) return req
;
479 } while (req
!= started_at
);
485 /* a libevent callback function which is called when a nameserver */
486 /* has gone down and we want to test if it has came back to life yet */
488 nameserver_prod_callback(evutil_socket_t fd
, short events
, void *arg
) {
489 struct nameserver
*const ns
= (struct nameserver
*) arg
;
493 EVDNS_LOCK(ns
->base
);
494 nameserver_send_probe(ns
);
495 EVDNS_UNLOCK(ns
->base
);
498 /* a libevent callback which is called when a nameserver probe (to see if */
499 /* it has come back to life) times out. We increment the count of failed_times */
500 /* and wait longer to send the next probe packet. */
502 nameserver_probe_failed(struct nameserver
*const ns
) {
503 struct timeval timeout
;
506 ASSERT_LOCKED(ns
->base
);
507 (void) evtimer_del(&ns
->timeout_event
);
508 if (ns
->state
== 1) {
509 /* This can happen if the nameserver acts in a way which makes us mark */
510 /* it as bad and then starts sending good replies. */
514 #define MAX_PROBE_TIMEOUT 3600
515 #define TIMEOUT_BACKOFF_FACTOR 3
517 memcpy(&timeout
, &ns
->base
->global_nameserver_probe_initial_timeout
,
518 sizeof(struct timeval
));
519 for (i
=ns
->failed_times
; i
> 0 && timeout
.tv_sec
< MAX_PROBE_TIMEOUT
; --i
) {
520 timeout
.tv_sec
*= TIMEOUT_BACKOFF_FACTOR
;
521 timeout
.tv_usec
*= TIMEOUT_BACKOFF_FACTOR
;
522 if (timeout
.tv_usec
> 1000000) {
523 timeout
.tv_sec
+= timeout
.tv_usec
/ 1000000;
524 timeout
.tv_usec
%= 1000000;
527 if (timeout
.tv_sec
> MAX_PROBE_TIMEOUT
) {
528 timeout
.tv_sec
= MAX_PROBE_TIMEOUT
;
534 if (evtimer_add(&ns
->timeout_event
, &timeout
) < 0) {
537 "Error from libevent when adding timer event for %s",
538 evutil_format_sockaddr_port_(
539 (struct sockaddr
*)&ns
->address
,
540 addrbuf
, sizeof(addrbuf
)));
545 request_swap_ns(struct request
*req
, struct nameserver
*ns
) {
546 if (ns
&& req
->ns
!= ns
) {
547 EVUTIL_ASSERT(req
->ns
->requests_inflight
> 0);
548 req
->ns
->requests_inflight
--;
549 ns
->requests_inflight
++;
555 /* called when a nameserver has been deemed to have failed. For example, too */
556 /* many packets have timed out etc */
558 nameserver_failed(struct nameserver
*const ns
, const char *msg
) {
559 struct request
*req
, *started_at
;
560 struct evdns_base
*base
= ns
->base
;
565 /* if this nameserver has already been marked as failed */
566 /* then don't do anything */
567 if (!ns
->state
) return;
569 log(EVDNS_LOG_MSG
, "Nameserver %s has failed: %s",
570 evutil_format_sockaddr_port_(
571 (struct sockaddr
*)&ns
->address
,
572 addrbuf
, sizeof(addrbuf
)),
575 base
->global_good_nameservers
--;
576 EVUTIL_ASSERT(base
->global_good_nameservers
>= 0);
577 if (base
->global_good_nameservers
== 0) {
578 log(EVDNS_LOG_MSG
, "All nameservers have failed");
582 ns
->failed_times
= 1;
584 if (evtimer_add(&ns
->timeout_event
,
585 &base
->global_nameserver_probe_initial_timeout
) < 0) {
587 "Error from libevent when adding timer event for %s",
588 evutil_format_sockaddr_port_(
589 (struct sockaddr
*)&ns
->address
,
590 addrbuf
, sizeof(addrbuf
)));
594 /* walk the list of inflight requests to see if any can be reassigned to */
595 /* a different server. Requests in the waiting queue don't have a */
596 /* nameserver assigned yet */
598 /* if we don't have *any* good nameservers then there's no point */
599 /* trying to reassign requests to one */
600 if (!base
->global_good_nameservers
) return;
602 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
603 req
= started_at
= base
->req_heads
[i
];
606 if (req
->tx_count
== 0 && req
->ns
== ns
) {
607 /* still waiting to go out, can be moved */
608 /* to another server */
609 request_swap_ns(req
, nameserver_pick(base
));
612 } while (req
!= started_at
);
618 nameserver_up(struct nameserver
*const ns
)
621 ASSERT_LOCKED(ns
->base
);
622 if (ns
->state
) return;
623 log(EVDNS_LOG_MSG
, "Nameserver %s is back up",
624 evutil_format_sockaddr_port_(
625 (struct sockaddr
*)&ns
->address
,
626 addrbuf
, sizeof(addrbuf
)));
627 evtimer_del(&ns
->timeout_event
);
628 if (ns
->probe_request
) {
629 evdns_cancel_request(ns
->base
, ns
->probe_request
);
630 ns
->probe_request
= NULL
;
633 ns
->failed_times
= 0;
635 ns
->base
->global_good_nameservers
++;
639 request_trans_id_set(struct request
*const req
, const u16 trans_id
) {
640 req
->trans_id
= trans_id
;
641 *((u16
*) req
->request
) = htons(trans_id
);
644 /* Called to remove a request from a list and dealloc it. */
645 /* head is a pointer to the head of the list it should be */
646 /* removed from or NULL if the request isn't in a list. */
647 /* when free_handle is one, free the handle as well. */
649 request_finished(struct request
*const req
, struct request
**head
, int free_handle
) {
650 struct evdns_base
*base
= req
->base
;
651 int was_inflight
= (head
!= &base
->req_waiting_head
);
653 ASSERT_VALID_REQUEST(req
);
656 evdns_request_remove(req
, head
);
658 log(EVDNS_LOG_DEBUG
, "Removing timeout for request %p", req
);
660 evtimer_del(&req
->timeout_event
);
661 base
->global_requests_inflight
--;
662 req
->ns
->requests_inflight
--;
664 base
->global_requests_waiting
--;
666 /* it was initialized during request_new / evtimer_assign */
667 event_debug_unassign(&req
->timeout_event
);
670 req
->ns
->requests_inflight
== 0 &&
671 req
->base
->disable_when_inactive
) {
672 event_del(&req
->ns
->event
);
673 evtimer_del(&req
->ns
->timeout_event
);
676 if (!req
->request_appended
) {
677 /* need to free the request data on it's own */
678 mm_free(req
->request
);
680 /* the request data is appended onto the header */
681 /* so everything gets free()ed when we: */
685 EVUTIL_ASSERT(req
->handle
->current_req
== req
);
688 search_request_finished(req
->handle
);
689 req
->handle
->current_req
= NULL
;
690 if (! req
->handle
->pending_cb
) {
691 /* If we're planning to run the callback,
692 * don't free the handle until later. */
693 mm_free(req
->handle
);
695 req
->handle
= NULL
; /* If we have a bug, let's crash
698 req
->handle
->current_req
= NULL
;
704 evdns_requests_pump_waiting_queue(base
);
708 /* This is called when a server returns a funny error code. */
709 /* We try the request again with another server. */
713 /* 1 failed/reissue is pointless */
715 request_reissue(struct request
*req
) {
716 const struct nameserver
*const last_ns
= req
->ns
;
717 ASSERT_LOCKED(req
->base
);
718 ASSERT_VALID_REQUEST(req
);
719 /* the last nameserver should have been marked as failing */
720 /* by the caller of this function, therefore pick will try */
721 /* not to return it */
722 request_swap_ns(req
, nameserver_pick(req
->base
));
723 if (req
->ns
== last_ns
) {
724 /* ... but pick did return it */
725 /* not a lot of point in trying again with the */
730 req
->reissue_count
++;
732 req
->transmit_me
= 1;
737 /* this function looks for space on the inflight queue and promotes */
738 /* requests from the waiting queue if it can. */
741 /* add return code, see at nameserver_pick() and other functions. */
743 evdns_requests_pump_waiting_queue(struct evdns_base
*base
) {
745 while (base
->global_requests_inflight
< base
->global_max_requests_inflight
&&
746 base
->global_requests_waiting
) {
749 EVUTIL_ASSERT(base
->req_waiting_head
);
750 req
= base
->req_waiting_head
;
752 req
->ns
= nameserver_pick(base
);
756 /* move a request from the waiting queue to the inflight queue */
757 req
->ns
->requests_inflight
++;
759 evdns_request_remove(req
, &base
->req_waiting_head
);
761 base
->global_requests_waiting
--;
762 base
->global_requests_inflight
++;
764 request_trans_id_set(req
, transaction_id_pick(base
));
766 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
767 evdns_request_transmit(req
);
768 evdns_transmit(base
);
772 /* TODO(nickm) document */
773 struct deferred_reply_callback
{
774 struct event_callback deferred
;
775 struct evdns_request
*handle
;
780 evdns_callback_type user_callback
;
785 reply_run_callback(struct event_callback
*d
, void *user_pointer
)
787 struct deferred_reply_callback
*cb
=
788 EVUTIL_UPCAST(d
, struct deferred_reply_callback
, deferred
);
790 switch (cb
->request_type
) {
793 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv4_A
,
794 cb
->reply
.data
.a
.addrcount
, cb
->ttl
,
795 cb
->reply
.data
.a
.addresses
,
798 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
801 if (cb
->have_reply
) {
802 char *name
= cb
->reply
.data
.ptr
.name
;
803 cb
->user_callback(DNS_ERR_NONE
, DNS_PTR
, 1, cb
->ttl
,
804 &name
, user_pointer
);
806 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
811 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv6_AAAA
,
812 cb
->reply
.data
.aaaa
.addrcount
, cb
->ttl
,
813 cb
->reply
.data
.aaaa
.addresses
,
816 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
822 if (cb
->handle
&& cb
->handle
->pending_cb
) {
830 reply_schedule_callback(struct request
*const req
, u32 ttl
, u32 err
, struct reply
*reply
)
832 struct deferred_reply_callback
*d
= mm_calloc(1, sizeof(*d
));
835 event_warn("%s: Couldn't allocate space for deferred callback.",
840 ASSERT_LOCKED(req
->base
);
842 d
->request_type
= req
->request_type
;
843 d
->user_callback
= req
->user_callback
;
848 memcpy(&d
->reply
, reply
, sizeof(struct reply
));
852 req
->handle
->pending_cb
= 1;
853 d
->handle
= req
->handle
;
856 event_deferred_cb_init_(
858 event_get_priority(&req
->timeout_event
),
861 event_deferred_cb_schedule_(
862 req
->base
->event_base
,
866 /* this processes a parsed reply packet */
868 reply_handle(struct request
*const req
, u16 flags
, u32 ttl
, struct reply
*reply
) {
871 static const int error_codes
[] = {
872 DNS_ERR_FORMAT
, DNS_ERR_SERVERFAILED
, DNS_ERR_NOTEXIST
,
873 DNS_ERR_NOTIMPL
, DNS_ERR_REFUSED
876 ASSERT_LOCKED(req
->base
);
877 ASSERT_VALID_REQUEST(req
);
879 if (flags
& 0x020f || !reply
|| !reply
->have_answer
) {
880 /* there was an error */
881 if (flags
& 0x0200) {
882 error
= DNS_ERR_TRUNCATED
;
883 } else if (flags
& 0x000f) {
884 u16 error_code
= (flags
& 0x000f) - 1;
885 if (error_code
> 4) {
886 error
= DNS_ERR_UNKNOWN
;
888 error
= error_codes
[error_code
];
890 } else if (reply
&& !reply
->have_answer
) {
891 error
= DNS_ERR_NODATA
;
893 error
= DNS_ERR_UNKNOWN
;
897 case DNS_ERR_NOTIMPL
:
898 case DNS_ERR_REFUSED
:
899 /* we regard these errors as marking a bad nameserver */
900 if (req
->reissue_count
< req
->base
->global_max_reissues
) {
902 evutil_snprintf(msg
, sizeof(msg
), "Bad response %d (%s)",
903 error
, evdns_err_to_string(error
));
904 nameserver_failed(req
->ns
, msg
);
905 if (!request_reissue(req
)) return;
908 case DNS_ERR_SERVERFAILED
:
909 /* rcode 2 (servfailed) sometimes means "we
910 * are broken" and sometimes (with some binds)
911 * means "that request was very confusing."
912 * Treat this as a timeout, not a failure.
914 log(EVDNS_LOG_DEBUG
, "Got a SERVERFAILED from nameserver"
915 "at %s; will allow the request to time out.",
916 evutil_format_sockaddr_port_(
917 (struct sockaddr
*)&req
->ns
->address
,
918 addrbuf
, sizeof(addrbuf
)));
919 /* Call the timeout function */
920 evdns_request_timeout_callback(0, 0, req
);
923 /* we got a good reply from the nameserver: it is up. */
924 if (req
->handle
== req
->ns
->probe_request
) {
925 /* Avoid double-free */
926 req
->ns
->probe_request
= NULL
;
929 nameserver_up(req
->ns
);
932 if (req
->handle
->search_state
&&
933 req
->request_type
!= TYPE_PTR
) {
934 /* if we have a list of domains to search in,
935 * try the next one */
936 if (!search_try_next(req
->handle
)) {
937 /* a new request was issued so this
938 * request is finished and */
939 /* the user callback will be made when
940 * that request (or a */
941 /* child of it) finishes. */
946 /* all else failed. Pass the failure up */
947 reply_schedule_callback(req
, ttl
, error
, NULL
);
948 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
950 /* all ok, tell the user */
951 reply_schedule_callback(req
, ttl
, 0, reply
);
952 if (req
->handle
== req
->ns
->probe_request
)
953 req
->ns
->probe_request
= NULL
; /* Avoid double-free */
954 nameserver_up(req
->ns
);
955 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
960 name_parse(u8
*packet
, int length
, int *idx
, char *name_out
, int name_out_len
) {
964 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
965 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
966 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
969 const char *const end
= name_out
+ name_out_len
;
971 /* Normally, names are a series of length prefixed strings terminated */
972 /* with a length of 0 (the lengths are u8's < 63). */
973 /* However, the length can start with a pair of 1 bits and that */
974 /* means that the next 14 bits are a pointer within the current */
979 if (j
>= length
) return -1;
981 if (!label_len
) break;
982 if (label_len
& 0xc0) {
985 if (name_end
< 0) name_end
= j
;
986 j
= (((int)label_len
& 0x3f) << 8) + ptr_low
;
987 /* Make sure that the target offset is in-bounds. */
988 if (j
< 0 || j
>= length
) return -1;
989 /* If we've jumped more times than there are characters in the
990 * message, we must have a loop. */
991 if (++ptr_count
> length
) return -1;
994 if (label_len
> 63) return -1;
995 if (cp
!= name_out
) {
996 if (cp
+ 1 >= end
) return -1;
999 if (cp
+ label_len
>= end
) return -1;
1000 memcpy(cp
, packet
+ j
, label_len
);
1004 if (cp
>= end
) return -1;
1015 /* parses a raw request from a nameserver */
1017 reply_parse(struct evdns_base
*base
, u8
*packet
, int length
) {
1018 int j
= 0, k
= 0; /* index into packet */
1019 u16 t_
; /* used by the macros */
1020 u32 t32_
; /* used by the macros */
1021 char tmp_name
[256], cmp_name
[256]; /* used by the macros */
1022 int name_matches
= 0;
1024 u16 trans_id
, questions
, answers
, authority
, additional
, datalength
;
1026 u32 ttl
, ttl_r
= 0xffffffff;
1028 struct request
*req
= NULL
;
1031 ASSERT_LOCKED(base
);
1039 (void) authority
; /* suppress "unused variable" warnings. */
1040 (void) additional
; /* suppress "unused variable" warnings. */
1042 req
= request_find_from_trans_id(base
, trans_id
);
1043 if (!req
) return -1;
1044 EVUTIL_ASSERT(req
->base
== base
);
1046 memset(&reply
, 0, sizeof(reply
));
1048 /* If it's not an answer, it doesn't correspond to any request. */
1049 if (!(flags
& 0x8000)) return -1; /* must be an answer */
1050 if ((flags
& 0x020f) && (flags
& 0x020f) != DNS_ERR_NOTEXIST
) {
1051 /* there was an error and it's not NXDOMAIN */
1054 /* if (!answers) return; */ /* must have an answer of some form */
1056 /* This macro skips a name in the DNS reply. */
1058 do { tmp_name[0] = '\0'; \
1059 if (name_parse(packet, length, &j, tmp_name, \
1060 sizeof(tmp_name))<0) \
1064 reply
.type
= req
->request_type
;
1066 /* skip over each question in the reply */
1067 for (i
= 0; i
< questions
; ++i
) {
1068 /* the question looks like
1069 * <label:name><u16:type><u16:class>
1074 if (name_parse(packet
, length
, &j
, tmp_name
, sizeof(tmp_name
)) < 0)
1076 if (name_parse(req
->request
, req
->request_len
, &k
,
1077 cmp_name
, sizeof(cmp_name
))<0)
1079 if (!base
->global_randomize_case
) {
1080 if (strcmp(tmp_name
, cmp_name
) == 0)
1083 if (evutil_ascii_strcasecmp(tmp_name
, cmp_name
) == 0)
1095 /* now we have the answer section which looks like
1096 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
1099 for (i
= 0; i
< answers
; ++i
) {
1108 if (type
== TYPE_A
&& class == CLASS_INET
) {
1109 int addrcount
, addrtocopy
;
1110 if (req
->request_type
!= TYPE_A
) {
1111 j
+= datalength
; continue;
1113 if ((datalength
& 3) != 0) /* not an even number of As. */
1115 addrcount
= datalength
>> 2;
1116 addrtocopy
= MIN(MAX_V4_ADDRS
- reply
.data
.a
.addrcount
, (unsigned)addrcount
);
1118 ttl_r
= MIN(ttl_r
, ttl
);
1119 /* we only bother with the first four addresses. */
1120 if (j
+ 4*addrtocopy
> length
) goto err
;
1121 memcpy(&reply
.data
.a
.addresses
[reply
.data
.a
.addrcount
],
1122 packet
+ j
, 4*addrtocopy
);
1124 reply
.data
.a
.addrcount
+= addrtocopy
;
1125 reply
.have_answer
= 1;
1126 if (reply
.data
.a
.addrcount
== MAX_V4_ADDRS
) break;
1127 } else if (type
== TYPE_PTR
&& class == CLASS_INET
) {
1128 if (req
->request_type
!= TYPE_PTR
) {
1129 j
+= datalength
; continue;
1131 if (name_parse(packet
, length
, &j
, reply
.data
.ptr
.name
,
1132 sizeof(reply
.data
.ptr
.name
))<0)
1134 ttl_r
= MIN(ttl_r
, ttl
);
1135 reply
.have_answer
= 1;
1137 } else if (type
== TYPE_CNAME
) {
1138 char cname
[HOST_NAME_MAX
];
1139 if (!req
->put_cname_in_ptr
|| *req
->put_cname_in_ptr
) {
1140 j
+= datalength
; continue;
1142 if (name_parse(packet
, length
, &j
, cname
,
1145 *req
->put_cname_in_ptr
= mm_strdup(cname
);
1146 } else if (type
== TYPE_AAAA
&& class == CLASS_INET
) {
1147 int addrcount
, addrtocopy
;
1148 if (req
->request_type
!= TYPE_AAAA
) {
1149 j
+= datalength
; continue;
1151 if ((datalength
& 15) != 0) /* not an even number of AAAAs. */
1153 addrcount
= datalength
>> 4; /* each address is 16 bytes long */
1154 addrtocopy
= MIN(MAX_V6_ADDRS
- reply
.data
.aaaa
.addrcount
, (unsigned)addrcount
);
1155 ttl_r
= MIN(ttl_r
, ttl
);
1157 /* we only bother with the first four addresses. */
1158 if (j
+ 16*addrtocopy
> length
) goto err
;
1159 memcpy(&reply
.data
.aaaa
.addresses
[reply
.data
.aaaa
.addrcount
],
1160 packet
+ j
, 16*addrtocopy
);
1161 reply
.data
.aaaa
.addrcount
+= addrtocopy
;
1163 reply
.have_answer
= 1;
1164 if (reply
.data
.aaaa
.addrcount
== MAX_V6_ADDRS
) break;
1166 /* skip over any other type of resource */
1171 if (!reply
.have_answer
) {
1172 for (i
= 0; i
< authority
; ++i
) {
1179 if (type
== TYPE_SOA
&& class == CLASS_INET
) {
1180 u32 serial
, refresh
, retry
, expire
, minimum
;
1192 ttl_r
= MIN(ttl_r
, ttl
);
1193 ttl_r
= MIN(ttl_r
, minimum
);
1195 /* skip over any other type of resource */
1201 if (ttl_r
== 0xffffffff)
1204 reply_handle(req
, flags
, ttl_r
, &reply
);
1208 reply_handle(req
, flags
, 0, NULL
);
1212 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1213 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1216 request_parse(u8
*packet
, int length
, struct evdns_server_port
*port
, struct sockaddr
*addr
, ev_socklen_t addrlen
)
1218 int j
= 0; /* index into packet */
1219 u16 t_
; /* used by the macros */
1220 char tmp_name
[256]; /* used by the macros */
1223 u16 trans_id
, flags
, questions
, answers
, authority
, additional
;
1224 struct server_request
*server_req
= NULL
;
1226 ASSERT_LOCKED(port
);
1228 /* Get the header fields */
1239 if (flags
& 0x8000) return -1; /* Must not be an answer. */
1240 flags
&= 0x0110; /* Only RD and CD get preserved. */
1242 server_req
= mm_malloc(sizeof(struct server_request
));
1243 if (server_req
== NULL
) return -1;
1244 memset(server_req
, 0, sizeof(struct server_request
));
1246 server_req
->trans_id
= trans_id
;
1247 memcpy(&server_req
->addr
, addr
, addrlen
);
1248 server_req
->addrlen
= addrlen
;
1250 server_req
->base
.flags
= flags
;
1251 server_req
->base
.nquestions
= 0;
1252 server_req
->base
.questions
= mm_calloc(sizeof(struct evdns_server_question
*), questions
);
1253 if (server_req
->base
.questions
== NULL
)
1256 for (i
= 0; i
< questions
; ++i
) {
1258 struct evdns_server_question
*q
;
1260 if (name_parse(packet
, length
, &j
, tmp_name
, sizeof(tmp_name
))<0)
1264 namelen
= (int)strlen(tmp_name
);
1265 q
= mm_malloc(sizeof(struct evdns_server_question
) + namelen
);
1269 q
->dns_question_class
= class;
1270 memcpy(q
->name
, tmp_name
, namelen
+1);
1271 server_req
->base
.questions
[server_req
->base
.nquestions
++] = q
;
1274 /* Ignore answers, authority, and additional. */
1276 server_req
->port
= port
;
1279 /* Only standard queries are supported. */
1280 if (flags
& 0x7800) {
1281 evdns_server_request_respond(&(server_req
->base
), DNS_ERR_NOTIMPL
);
1285 port
->user_callback(&(server_req
->base
), port
->user_data
);
1290 if (server_req
->base
.questions
) {
1291 for (i
= 0; i
< server_req
->base
.nquestions
; ++i
)
1292 mm_free(server_req
->base
.questions
[i
]);
1293 mm_free(server_req
->base
.questions
);
1295 mm_free(server_req
);
1307 evdns_set_transaction_id_fn(ev_uint16_t (*fn
)(void))
1312 evdns_set_random_bytes_fn(void (*fn
)(char *, size_t))
1316 /* Try to choose a strong transaction id which isn't already in flight */
1318 transaction_id_pick(struct evdns_base
*base
) {
1319 ASSERT_LOCKED(base
);
1322 evutil_secure_rng_get_bytes(&trans_id
, sizeof(trans_id
));
1324 if (trans_id
== 0xffff) continue;
1325 /* now check to see if that id is already inflight */
1326 if (request_find_from_trans_id(base
, trans_id
) == NULL
)
1331 /* choose a namesever to use. This function will try to ignore */
1332 /* nameservers which we think are down and load balance across the rest */
1333 /* by updating the server_head global each time. */
1334 static struct nameserver
*
1335 nameserver_pick(struct evdns_base
*base
) {
1336 struct nameserver
*started_at
= base
->server_head
, *picked
;
1337 ASSERT_LOCKED(base
);
1338 if (!base
->server_head
) return NULL
;
1340 /* if we don't have any good nameservers then there's no */
1341 /* point in trying to find one. */
1342 if (!base
->global_good_nameservers
) {
1343 base
->server_head
= base
->server_head
->next
;
1344 return base
->server_head
;
1347 /* remember that nameservers are in a circular list */
1349 if (base
->server_head
->state
) {
1350 /* we think this server is currently good */
1351 picked
= base
->server_head
;
1352 base
->server_head
= base
->server_head
->next
;
1356 base
->server_head
= base
->server_head
->next
;
1357 if (base
->server_head
== started_at
) {
1358 /* all the nameservers seem to be down */
1359 /* so we just return this one and hope for the */
1361 EVUTIL_ASSERT(base
->global_good_nameservers
== 0);
1362 picked
= base
->server_head
;
1363 base
->server_head
= base
->server_head
->next
;
1369 /* this is called when a namesever socket is ready for reading */
1371 nameserver_read(struct nameserver
*ns
) {
1372 struct sockaddr_storage ss
;
1373 ev_socklen_t addrlen
= sizeof(ss
);
1376 ASSERT_LOCKED(ns
->base
);
1379 const int r
= recvfrom(ns
->socket
, (void*)packet
,
1381 (struct sockaddr
*)&ss
, &addrlen
);
1383 int err
= evutil_socket_geterror(ns
->socket
);
1384 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1386 nameserver_failed(ns
,
1387 evutil_socket_error_to_string(err
));
1390 if (evutil_sockaddr_cmp((struct sockaddr
*)&ss
,
1391 (struct sockaddr
*)&ns
->address
, 0)) {
1392 log(EVDNS_LOG_WARN
, "Address mismatch on received "
1393 "DNS packet. Apparent source was %s",
1394 evutil_format_sockaddr_port_(
1395 (struct sockaddr
*)&ss
,
1396 addrbuf
, sizeof(addrbuf
)));
1401 reply_parse(ns
->base
, packet
, r
);
1405 /* Read a packet from a DNS client on a server port s, parse it, and */
1406 /* act accordingly. */
1408 server_port_read(struct evdns_server_port
*s
) {
1410 struct sockaddr_storage addr
;
1411 ev_socklen_t addrlen
;
1416 addrlen
= sizeof(struct sockaddr_storage
);
1417 r
= recvfrom(s
->socket
, (void*)packet
, sizeof(packet
), 0,
1418 (struct sockaddr
*) &addr
, &addrlen
);
1420 int err
= evutil_socket_geterror(s
->socket
);
1421 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1424 "Error %s (%d) while reading request.",
1425 evutil_socket_error_to_string(err
), err
);
1428 request_parse(packet
, r
, s
, (struct sockaddr
*) &addr
, addrlen
);
1432 /* Try to write all pending replies on a given DNS server port. */
1434 server_port_flush(struct evdns_server_port
*port
)
1436 struct server_request
*req
= port
->pending_replies
;
1437 ASSERT_LOCKED(port
);
1439 int r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
1440 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
1442 int err
= evutil_socket_geterror(port
->socket
);
1443 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1445 log(EVDNS_LOG_WARN
, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err
), err
);
1447 if (server_request_free(req
)) {
1448 /* we released the last reference to req->port. */
1451 EVUTIL_ASSERT(req
!= port
->pending_replies
);
1452 req
= port
->pending_replies
;
1456 /* We have no more pending requests; stop listening for 'writeable' events. */
1457 (void) event_del(&port
->event
);
1458 event_assign(&port
->event
, port
->event_base
,
1459 port
->socket
, EV_READ
| EV_PERSIST
,
1460 server_port_ready_callback
, port
);
1462 if (event_add(&port
->event
, NULL
) < 0) {
1463 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server.");
1468 /* set if we are waiting for the ability to write to this server. */
1469 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1470 /* we stop these events. */
1472 nameserver_write_waiting(struct nameserver
*ns
, char waiting
) {
1473 ASSERT_LOCKED(ns
->base
);
1474 if (ns
->write_waiting
== waiting
) return;
1476 ns
->write_waiting
= waiting
;
1477 (void) event_del(&ns
->event
);
1478 event_assign(&ns
->event
, ns
->base
->event_base
,
1479 ns
->socket
, EV_READ
| (waiting
? EV_WRITE
: 0) | EV_PERSIST
,
1480 nameserver_ready_callback
, ns
);
1481 if (event_add(&ns
->event
, NULL
) < 0) {
1483 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for %s",
1484 evutil_format_sockaddr_port_(
1485 (struct sockaddr
*)&ns
->address
,
1486 addrbuf
, sizeof(addrbuf
)));
1491 /* a callback function. Called by libevent when the kernel says that */
1492 /* a nameserver socket is ready for writing or reading */
1494 nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1495 struct nameserver
*ns
= (struct nameserver
*) arg
;
1498 EVDNS_LOCK(ns
->base
);
1499 if (events
& EV_WRITE
) {
1501 if (!evdns_transmit(ns
->base
)) {
1502 nameserver_write_waiting(ns
, 0);
1505 if (events
& EV_READ
) {
1506 nameserver_read(ns
);
1508 EVDNS_UNLOCK(ns
->base
);
1511 /* a callback function. Called by libevent when the kernel says that */
1512 /* a server socket is ready for writing or reading. */
1514 server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1515 struct evdns_server_port
*port
= (struct evdns_server_port
*) arg
;
1519 if (events
& EV_WRITE
) {
1521 server_port_flush(port
);
1523 if (events
& EV_READ
) {
1524 server_port_read(port
);
1529 /* This is an inefficient representation; only use it via the dnslabel_table_*
1530 * functions, so that is can be safely replaced with something smarter later. */
1531 #define MAX_LABELS 128
1532 /* Structures used to implement name compression */
1533 struct dnslabel_entry
{ char *v
; off_t pos
; };
1534 struct dnslabel_table
{
1535 int n_labels
; /* number of current entries */
1536 /* map from name to position in message */
1537 struct dnslabel_entry labels
[MAX_LABELS
];
1540 /* Initialize dnslabel_table. */
1542 dnslabel_table_init(struct dnslabel_table
*table
)
1544 table
->n_labels
= 0;
1547 /* Free all storage held by table, but not the table itself. */
1549 dnslabel_clear(struct dnslabel_table
*table
)
1552 for (i
= 0; i
< table
->n_labels
; ++i
)
1553 mm_free(table
->labels
[i
].v
);
1554 table
->n_labels
= 0;
1557 /* return the position of the label in the current message, or -1 if the label */
1558 /* hasn't been used yet. */
1560 dnslabel_table_get_pos(const struct dnslabel_table
*table
, const char *label
)
1563 for (i
= 0; i
< table
->n_labels
; ++i
) {
1564 if (!strcmp(label
, table
->labels
[i
].v
))
1565 return table
->labels
[i
].pos
;
1570 /* remember that we've used the label at position pos */
1572 dnslabel_table_add(struct dnslabel_table
*table
, const char *label
, off_t pos
)
1576 if (table
->n_labels
== MAX_LABELS
)
1578 v
= mm_strdup(label
);
1581 p
= table
->n_labels
++;
1582 table
->labels
[p
].v
= v
;
1583 table
->labels
[p
].pos
= pos
;
1588 /* Converts a string to a length-prefixed set of DNS labels, starting */
1589 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1590 /* of name. table is optional, and is used for compression. */
1592 /* Input: abc.def */
1593 /* Output: <3>abc<3>def<0> */
1595 /* Returns the first index after the encoded name, or negative on error. */
1596 /* -1 label was > 63 bytes */
1597 /* -2 name too long to fit in buffer. */
1600 dnsname_to_labels(u8
*const buf
, size_t buf_len
, off_t j
,
1601 const char *name
, const size_t name_len
,
1602 struct dnslabel_table
*table
) {
1603 const char *end
= name
+ name_len
;
1607 #define APPEND16(x) do { \
1608 if (j + 2 > (off_t)buf_len) \
1611 memcpy(buf + j, &t_, 2); \
1614 #define APPEND32(x) do { \
1615 if (j + 4 > (off_t)buf_len) \
1618 memcpy(buf + j, &t32_, 4); \
1622 if (name_len
> 255) return -2;
1625 const char *const start
= name
;
1626 if (table
&& (ref
= dnslabel_table_get_pos(table
, name
)) >= 0) {
1627 APPEND16(ref
| 0xc000);
1630 name
= strchr(name
, '.');
1632 const size_t label_len
= end
- start
;
1633 if (label_len
> 63) return -1;
1634 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1635 if (table
) dnslabel_table_add(table
, start
, j
);
1636 buf
[j
++] = (ev_uint8_t
)label_len
;
1638 memcpy(buf
+ j
, start
, label_len
);
1639 j
+= (int) label_len
;
1642 /* append length of the label. */
1643 const size_t label_len
= name
- start
;
1644 if (label_len
> 63) return -1;
1645 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1646 if (table
) dnslabel_table_add(table
, start
, j
);
1647 buf
[j
++] = (ev_uint8_t
)label_len
;
1649 memcpy(buf
+ j
, start
, label_len
);
1650 j
+= (int) label_len
;
1651 /* hop over the '.' */
1656 /* the labels must be terminated by a 0. */
1657 /* It's possible that the name ended in a . */
1658 /* in which case the zero is already there */
1659 if (!j
|| buf
[j
-1]) buf
[j
++] = 0;
1665 /* Finds the length of a dns request for a DNS name of the given */
1666 /* length. The actual request may be smaller than the value returned */
1669 evdns_request_len(const size_t name_len
) {
1670 return 96 + /* length of the DNS standard header */
1672 4; /* space for the resource type */
1675 /* build a dns request packet into buf. buf should be at least as long */
1676 /* as evdns_request_len told you it should be. */
1678 /* Returns the amount of space used. Negative on error. */
1680 evdns_request_data_build(const char *const name
, const size_t name_len
,
1681 const u16 trans_id
, const u16 type
, const u16
class,
1682 u8
*const buf
, size_t buf_len
) {
1683 off_t j
= 0; /* current offset into buf */
1684 u16 t_
; /* used by the macros */
1687 APPEND16(0x0100); /* standard query, recusion needed */
1688 APPEND16(1); /* one question */
1689 APPEND16(0); /* no answers */
1690 APPEND16(0); /* no authority */
1691 APPEND16(0); /* no additional */
1693 j
= dnsname_to_labels(buf
, buf_len
, j
, name
, name_len
, NULL
);
1706 /* exported function */
1707 struct evdns_server_port
*
1708 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
)
1710 struct evdns_server_port
*port
;
1712 return NULL
; /* flags not yet implemented */
1713 if (!(port
= mm_malloc(sizeof(struct evdns_server_port
))))
1715 memset(port
, 0, sizeof(struct evdns_server_port
));
1718 port
->socket
= socket
;
1722 port
->user_callback
= cb
;
1723 port
->user_data
= user_data
;
1724 port
->pending_replies
= NULL
;
1725 port
->event_base
= base
;
1727 event_assign(&port
->event
, port
->event_base
,
1728 port
->socket
, EV_READ
| EV_PERSIST
,
1729 server_port_ready_callback
, port
);
1730 if (event_add(&port
->event
, NULL
) < 0) {
1734 EVTHREAD_ALLOC_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
1738 struct evdns_server_port
*
1739 evdns_add_server_port(evutil_socket_t socket
, int flags
, evdns_request_callback_fn_type cb
, void *user_data
)
1741 return evdns_add_server_port_with_base(NULL
, socket
, flags
, cb
, user_data
);
1744 /* exported function */
1746 evdns_close_server_port(struct evdns_server_port
*port
)
1749 if (--port
->refcnt
== 0) {
1751 server_port_free(port
);
1757 /* exported function */
1759 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
)
1761 struct server_request
*req
= TO_SERVER_REQUEST(req_
);
1762 struct server_reply_item
**itemp
, *item
;
1766 EVDNS_LOCK(req
->port
);
1767 if (req
->response
) /* have we already answered? */
1771 case EVDNS_ANSWER_SECTION
:
1772 itemp
= &req
->answer
;
1773 countp
= &req
->n_answer
;
1775 case EVDNS_AUTHORITY_SECTION
:
1776 itemp
= &req
->authority
;
1777 countp
= &req
->n_authority
;
1779 case EVDNS_ADDITIONAL_SECTION
:
1780 itemp
= &req
->additional
;
1781 countp
= &req
->n_additional
;
1787 itemp
= &((*itemp
)->next
);
1789 item
= mm_malloc(sizeof(struct server_reply_item
));
1793 if (!(item
->name
= mm_strdup(name
))) {
1798 item
->dns_question_class
= class;
1800 item
->is_name
= is_name
!= 0;
1804 if (item
->is_name
) {
1805 if (!(item
->data
= mm_strdup(data
))) {
1806 mm_free(item
->name
);
1810 item
->datalen
= (u16
)-1;
1812 if (!(item
->data
= mm_malloc(datalen
))) {
1813 mm_free(item
->name
);
1817 item
->datalen
= datalen
;
1818 memcpy(item
->data
, data
, datalen
);
1826 EVDNS_UNLOCK(req
->port
);
1830 /* exported function */
1832 evdns_server_request_add_a_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1834 return evdns_server_request_add_reply(
1835 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_A
, CLASS_INET
,
1836 ttl
, n
*4, 0, addrs
);
1839 /* exported function */
1841 evdns_server_request_add_aaaa_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1843 return evdns_server_request_add_reply(
1844 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_AAAA
, CLASS_INET
,
1845 ttl
, n
*16, 0, addrs
);
1848 /* exported function */
1850 evdns_server_request_add_ptr_reply(struct evdns_server_request
*req
, struct in_addr
*in
, const char *inaddr_name
, const char *hostname
, int ttl
)
1854 if (in
&& inaddr_name
)
1856 else if (!in
&& !inaddr_name
)
1859 a
= ntohl(in
->s_addr
);
1860 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
1861 (int)(u8
)((a
)&0xff),
1862 (int)(u8
)((a
>>8 )&0xff),
1863 (int)(u8
)((a
>>16)&0xff),
1864 (int)(u8
)((a
>>24)&0xff));
1867 return evdns_server_request_add_reply(
1868 req
, EVDNS_ANSWER_SECTION
, inaddr_name
, TYPE_PTR
, CLASS_INET
,
1869 ttl
, -1, 1, hostname
);
1872 /* exported function */
1874 evdns_server_request_add_cname_reply(struct evdns_server_request
*req
, const char *name
, const char *cname
, int ttl
)
1876 return evdns_server_request_add_reply(
1877 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_CNAME
, CLASS_INET
,
1881 /* exported function */
1883 evdns_server_request_set_flags(struct evdns_server_request
*exreq
, int flags
)
1885 struct server_request
*req
= TO_SERVER_REQUEST(exreq
);
1886 req
->base
.flags
&= ~(EVDNS_FLAGS_AA
|EVDNS_FLAGS_RD
);
1887 req
->base
.flags
|= flags
;
1891 evdns_server_request_format_response(struct server_request
*req
, int err
)
1893 unsigned char buf
[1500];
1894 size_t buf_len
= sizeof(buf
);
1900 struct dnslabel_table table
;
1902 if (err
< 0 || err
> 15) return -1;
1904 /* Set response bit and error code; copy OPCODE and RD fields from
1905 * question; copy RA and AA if set by caller. */
1906 flags
= req
->base
.flags
;
1907 flags
|= (0x8000 | err
);
1909 dnslabel_table_init(&table
);
1910 APPEND16(req
->trans_id
);
1912 APPEND16(req
->base
.nquestions
);
1913 APPEND16(req
->n_answer
);
1914 APPEND16(req
->n_authority
);
1915 APPEND16(req
->n_additional
);
1917 /* Add questions. */
1918 for (i
=0; i
< req
->base
.nquestions
; ++i
) {
1919 const char *s
= req
->base
.questions
[i
]->name
;
1920 j
= dnsname_to_labels(buf
, buf_len
, j
, s
, strlen(s
), &table
);
1922 dnslabel_clear(&table
);
1925 APPEND16(req
->base
.questions
[i
]->type
);
1926 APPEND16(req
->base
.questions
[i
]->dns_question_class
);
1929 /* Add answer, authority, and additional sections. */
1930 for (i
=0; i
<3; ++i
) {
1931 struct server_reply_item
*item
;
1935 item
= req
->authority
;
1937 item
= req
->additional
;
1939 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->name
, strlen(item
->name
), &table
);
1944 APPEND16(item
->type
);
1945 APPEND16(item
->dns_question_class
);
1946 APPEND32(item
->ttl
);
1947 if (item
->is_name
) {
1948 off_t len_idx
= j
, name_start
;
1951 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->data
, strlen(item
->data
), &table
);
1955 t_
= htons( (short) (j
-name_start
) );
1956 memcpy(buf
+len_idx
, &t_
, 2);
1958 APPEND16(item
->datalen
);
1959 if (j
+item
->datalen
> (off_t
)buf_len
)
1961 memcpy(buf
+j
, item
->data
, item
->datalen
);
1971 buf
[2] |= 0x02; /* set the truncated bit. */
1974 req
->response_len
= j
;
1976 if (!(req
->response
= mm_malloc(req
->response_len
))) {
1977 server_request_free_answers(req
);
1978 dnslabel_clear(&table
);
1981 memcpy(req
->response
, buf
, req
->response_len
);
1982 server_request_free_answers(req
);
1983 dnslabel_clear(&table
);
1987 /* exported function */
1989 evdns_server_request_respond(struct evdns_server_request
*req_
, int err
)
1991 struct server_request
*req
= TO_SERVER_REQUEST(req_
);
1992 struct evdns_server_port
*port
= req
->port
;
1996 if (!req
->response
) {
1997 if ((r
= evdns_server_request_format_response(req
, err
))<0)
2001 r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
2002 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
2004 int sock_err
= evutil_socket_geterror(port
->socket
);
2005 if (EVUTIL_ERR_RW_RETRIABLE(sock_err
))
2008 if (port
->pending_replies
) {
2009 req
->prev_pending
= port
->pending_replies
->prev_pending
;
2010 req
->next_pending
= port
->pending_replies
;
2011 req
->prev_pending
->next_pending
=
2012 req
->next_pending
->prev_pending
= req
;
2014 req
->prev_pending
= req
->next_pending
= req
;
2015 port
->pending_replies
= req
;
2018 (void) event_del(&port
->event
);
2019 event_assign(&port
->event
, port
->event_base
, port
->socket
, (port
->closing
?0:EV_READ
) | EV_WRITE
| EV_PERSIST
, server_port_ready_callback
, port
);
2021 if (event_add(&port
->event
, NULL
) < 0) {
2022 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server");
2030 if (server_request_free(req
)) {
2035 if (port
->pending_replies
)
2036 server_port_flush(port
);
2044 /* Free all storage held by RRs in req. */
2046 server_request_free_answers(struct server_request
*req
)
2048 struct server_reply_item
*victim
, *next
, **list
;
2050 for (i
= 0; i
< 3; ++i
) {
2052 list
= &req
->answer
;
2054 list
= &req
->authority
;
2056 list
= &req
->additional
;
2060 next
= victim
->next
;
2061 mm_free(victim
->name
);
2063 mm_free(victim
->data
);
2071 /* Free all storage held by req, and remove links to it. */
2072 /* return true iff we just wound up freeing the server_port. */
2074 server_request_free(struct server_request
*req
)
2076 int i
, rc
=1, lock
=0;
2077 if (req
->base
.questions
) {
2078 for (i
= 0; i
< req
->base
.nquestions
; ++i
)
2079 mm_free(req
->base
.questions
[i
]);
2080 mm_free(req
->base
.questions
);
2084 EVDNS_LOCK(req
->port
);
2086 if (req
->port
->pending_replies
== req
) {
2087 if (req
->next_pending
&& req
->next_pending
!= req
)
2088 req
->port
->pending_replies
= req
->next_pending
;
2090 req
->port
->pending_replies
= NULL
;
2092 rc
= --req
->port
->refcnt
;
2095 if (req
->response
) {
2096 mm_free(req
->response
);
2099 server_request_free_answers(req
);
2101 if (req
->next_pending
&& req
->next_pending
!= req
) {
2102 req
->next_pending
->prev_pending
= req
->prev_pending
;
2103 req
->prev_pending
->next_pending
= req
->next_pending
;
2107 EVDNS_UNLOCK(req
->port
); /* ????? nickm */
2108 server_port_free(req
->port
);
2113 EVDNS_UNLOCK(req
->port
);
2118 /* Free all storage held by an evdns_server_port. Only called when */
2120 server_port_free(struct evdns_server_port
*port
)
2122 EVUTIL_ASSERT(port
);
2123 EVUTIL_ASSERT(!port
->refcnt
);
2124 EVUTIL_ASSERT(!port
->pending_replies
);
2125 if (port
->socket
> 0) {
2126 evutil_closesocket(port
->socket
);
2129 (void) event_del(&port
->event
);
2130 event_debug_unassign(&port
->event
);
2131 EVTHREAD_FREE_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
2135 /* exported function */
2137 evdns_server_request_drop(struct evdns_server_request
*req_
)
2139 struct server_request
*req
= TO_SERVER_REQUEST(req_
);
2140 server_request_free(req
);
2144 /* exported function */
2146 evdns_server_request_get_requesting_addr(struct evdns_server_request
*req_
, struct sockaddr
*sa
, int addr_len
)
2148 struct server_request
*req
= TO_SERVER_REQUEST(req_
);
2149 if (addr_len
< (int)req
->addrlen
)
2151 memcpy(sa
, &(req
->addr
), req
->addrlen
);
2152 return req
->addrlen
;
2158 /* this is a libevent callback function which is called when a request */
2159 /* has timed out. */
2161 evdns_request_timeout_callback(evutil_socket_t fd
, short events
, void *arg
) {
2162 struct request
*const req
= (struct request
*) arg
;
2163 struct evdns_base
*base
= req
->base
;
2168 log(EVDNS_LOG_DEBUG
, "Request %p timed out", arg
);
2171 if (req
->tx_count
>= req
->base
->global_max_retransmits
) {
2172 struct nameserver
*ns
= req
->ns
;
2173 /* this request has failed */
2174 log(EVDNS_LOG_DEBUG
, "Giving up on request %p; tx_count==%d",
2175 arg
, req
->tx_count
);
2176 reply_schedule_callback(req
, 0, DNS_ERR_TIMEOUT
, NULL
);
2178 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
2179 nameserver_failed(ns
, "request timed out.");
2182 log(EVDNS_LOG_DEBUG
, "Retransmitting request %p; tx_count==%d",
2183 arg
, req
->tx_count
);
2184 (void) evtimer_del(&req
->timeout_event
);
2185 request_swap_ns(req
, nameserver_pick(base
));
2186 evdns_request_transmit(req
);
2188 req
->ns
->timedout
++;
2189 if (req
->ns
->timedout
> req
->base
->global_max_nameserver_timeout
) {
2190 req
->ns
->timedout
= 0;
2191 nameserver_failed(req
->ns
, "request timed out.");
2198 /* try to send a request to a given server. */
2202 /* 1 temporary failure */
2203 /* 2 other failure */
2205 evdns_request_transmit_to(struct request
*req
, struct nameserver
*server
) {
2207 ASSERT_LOCKED(req
->base
);
2208 ASSERT_VALID_REQUEST(req
);
2210 if (server
->requests_inflight
== 1 &&
2211 req
->base
->disable_when_inactive
&&
2212 event_add(&server
->event
, NULL
) < 0) {
2216 r
= sendto(server
->socket
, (void*)req
->request
, req
->request_len
, 0,
2217 (struct sockaddr
*)&server
->address
, server
->addrlen
);
2219 int err
= evutil_socket_geterror(server
->socket
);
2220 if (EVUTIL_ERR_RW_RETRIABLE(err
))
2222 nameserver_failed(req
->ns
, evutil_socket_error_to_string(err
));
2224 } else if (r
!= (int)req
->request_len
) {
2225 return 1; /* short write */
2231 /* try to send a request, updating the fields of the request */
2238 evdns_request_transmit(struct request
*req
) {
2241 ASSERT_LOCKED(req
->base
);
2242 ASSERT_VALID_REQUEST(req
);
2243 /* if we fail to send this packet then this flag marks it */
2244 /* for evdns_transmit */
2245 req
->transmit_me
= 1;
2246 EVUTIL_ASSERT(req
->trans_id
!= 0xffff);
2250 /* unable to transmit request if no nameservers */
2254 if (req
->ns
->choked
) {
2255 /* don't bother trying to write to a socket */
2256 /* which we have had EAGAIN from */
2260 r
= evdns_request_transmit_to(req
, req
->ns
);
2264 req
->ns
->choked
= 1;
2265 nameserver_write_waiting(req
->ns
, 1);
2268 /* failed to transmit the request entirely. */
2270 /* fall through: we'll set a timeout, which will time out,
2271 * and make us retransmit the request anyway. */
2274 log(EVDNS_LOG_DEBUG
,
2275 "Setting timeout for request %p, sent to nameserver %p", req
, req
->ns
);
2276 if (evtimer_add(&req
->timeout_event
, &req
->base
->global_timeout
) < 0) {
2278 "Error from libevent when adding timer for request %p",
2283 req
->transmit_me
= 0;
2289 nameserver_probe_callback(int result
, char type
, int count
, int ttl
, void *addresses
, void *arg
) {
2290 struct nameserver
*const ns
= (struct nameserver
*) arg
;
2296 if (result
== DNS_ERR_CANCEL
) {
2297 /* We canceled this request because the nameserver came up
2298 * for some other reason. Do not change our opinion about
2299 * the nameserver. */
2303 EVDNS_LOCK(ns
->base
);
2304 ns
->probe_request
= NULL
;
2305 if (result
== DNS_ERR_NONE
|| result
== DNS_ERR_NOTEXIST
) {
2306 /* this is a good reply */
2309 nameserver_probe_failed(ns
);
2311 EVDNS_UNLOCK(ns
->base
);
2315 nameserver_send_probe(struct nameserver
*const ns
) {
2316 struct evdns_request
*handle
;
2317 struct request
*req
;
2319 /* here we need to send a probe to a given nameserver */
2320 /* in the hope that it is up now. */
2322 ASSERT_LOCKED(ns
->base
);
2323 log(EVDNS_LOG_DEBUG
, "Sending probe to %s",
2324 evutil_format_sockaddr_port_(
2325 (struct sockaddr
*)&ns
->address
,
2326 addrbuf
, sizeof(addrbuf
)));
2327 handle
= mm_calloc(1, sizeof(*handle
));
2328 if (!handle
) return;
2329 req
= request_new(ns
->base
, handle
, TYPE_A
, "google.com", DNS_QUERY_NO_SEARCH
, nameserver_probe_callback
, ns
);
2334 ns
->probe_request
= handle
;
2335 /* we force this into the inflight queue no matter what */
2336 request_trans_id_set(req
, transaction_id_pick(ns
->base
));
2338 request_submit(req
);
2342 /* 0 didn't try to transmit anything */
2343 /* 1 tried to transmit something */
2345 evdns_transmit(struct evdns_base
*base
) {
2346 char did_try_to_transmit
= 0;
2349 ASSERT_LOCKED(base
);
2350 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2351 if (base
->req_heads
[i
]) {
2352 struct request
*const started_at
= base
->req_heads
[i
], *req
= started_at
;
2353 /* first transmit all the requests which are currently waiting */
2355 if (req
->transmit_me
) {
2356 did_try_to_transmit
= 1;
2357 evdns_request_transmit(req
);
2361 } while (req
!= started_at
);
2365 return did_try_to_transmit
;
2368 /* exported function */
2370 evdns_base_count_nameservers(struct evdns_base
*base
)
2372 const struct nameserver
*server
;
2376 server
= base
->server_head
;
2381 server
= server
->next
;
2382 } while (server
!= base
->server_head
);
2389 evdns_count_nameservers(void)
2391 return evdns_base_count_nameservers(current_base
);
2394 /* exported function */
2396 evdns_base_clear_nameservers_and_suspend(struct evdns_base
*base
)
2398 struct nameserver
*server
, *started_at
;
2402 server
= base
->server_head
;
2403 started_at
= base
->server_head
;
2409 struct nameserver
*next
= server
->next
;
2410 (void) event_del(&server
->event
);
2411 if (evtimer_initialized(&server
->timeout_event
))
2412 (void) evtimer_del(&server
->timeout_event
);
2413 if (server
->probe_request
) {
2414 evdns_cancel_request(server
->base
, server
->probe_request
);
2415 server
->probe_request
= NULL
;
2417 if (server
->socket
>= 0)
2418 evutil_closesocket(server
->socket
);
2420 if (next
== started_at
)
2424 base
->server_head
= NULL
;
2425 base
->global_good_nameservers
= 0;
2427 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2428 struct request
*req
, *req_started_at
;
2429 req
= req_started_at
= base
->req_heads
[i
];
2431 struct request
*next
= req
->next
;
2432 req
->tx_count
= req
->reissue_count
= 0;
2434 /* ???? What to do about searches? */
2435 (void) evtimer_del(&req
->timeout_event
);
2437 req
->transmit_me
= 0;
2439 base
->global_requests_waiting
++;
2440 evdns_request_insert(req
, &base
->req_waiting_head
);
2441 /* We want to insert these suspended elements at the front of
2442 * the waiting queue, since they were pending before any of
2443 * the waiting entries were added. This is a circular list,
2444 * so we can just shift the start back by one.*/
2445 base
->req_waiting_head
= base
->req_waiting_head
->prev
;
2447 if (next
== req_started_at
)
2451 base
->req_heads
[i
] = NULL
;
2454 base
->global_requests_inflight
= 0;
2461 evdns_clear_nameservers_and_suspend(void)
2463 return evdns_base_clear_nameservers_and_suspend(current_base
);
2467 /* exported function */
2469 evdns_base_resume(struct evdns_base
*base
)
2472 evdns_requests_pump_waiting_queue(base
);
2481 return evdns_base_resume(current_base
);
2485 evdns_nameserver_add_impl_(struct evdns_base
*base
, const struct sockaddr
*address
, int addrlen
) {
2486 /* first check to see if we already have this nameserver */
2488 const struct nameserver
*server
= base
->server_head
, *const started_at
= base
->server_head
;
2489 struct nameserver
*ns
;
2493 ASSERT_LOCKED(base
);
2496 if (!evutil_sockaddr_cmp((struct sockaddr
*)&server
->address
, address
, 1)) return 3;
2497 server
= server
->next
;
2498 } while (server
!= started_at
);
2500 if (addrlen
> (int)sizeof(ns
->address
)) {
2501 log(EVDNS_LOG_DEBUG
, "Addrlen %d too long.", (int)addrlen
);
2505 ns
= (struct nameserver
*) mm_malloc(sizeof(struct nameserver
));
2508 memset(ns
, 0, sizeof(struct nameserver
));
2511 evtimer_assign(&ns
->timeout_event
, ns
->base
->event_base
, nameserver_prod_callback
, ns
);
2513 ns
->socket
= evutil_socket_(address
->sa_family
,
2514 SOCK_DGRAM
|EVUTIL_SOCK_NONBLOCK
|EVUTIL_SOCK_CLOEXEC
, 0);
2515 if (ns
->socket
< 0) { err
= 1; goto out1
; }
2517 if (base
->global_outgoing_addrlen
&&
2518 !evutil_sockaddr_is_loopback_(address
)) {
2519 if (bind(ns
->socket
,
2520 (struct sockaddr
*)&base
->global_outgoing_address
,
2521 base
->global_outgoing_addrlen
) < 0) {
2522 log(EVDNS_LOG_WARN
,"Couldn't bind to outgoing address");
2528 memcpy(&ns
->address
, address
, addrlen
);
2529 ns
->addrlen
= addrlen
;
2531 event_assign(&ns
->event
, ns
->base
->event_base
, ns
->socket
,
2532 EV_READ
| EV_PERSIST
, nameserver_ready_callback
, ns
);
2533 if (!base
->disable_when_inactive
&& event_add(&ns
->event
, NULL
) < 0) {
2538 log(EVDNS_LOG_DEBUG
, "Added nameserver %s as %p",
2539 evutil_format_sockaddr_port_(address
, addrbuf
, sizeof(addrbuf
)), ns
);
2541 /* insert this nameserver into the list of them */
2542 if (!base
->server_head
) {
2543 ns
->next
= ns
->prev
= ns
;
2544 base
->server_head
= ns
;
2546 ns
->next
= base
->server_head
->next
;
2547 ns
->prev
= base
->server_head
;
2548 base
->server_head
->next
= ns
;
2549 ns
->next
->prev
= ns
;
2552 base
->global_good_nameservers
++;
2557 evutil_closesocket(ns
->socket
);
2559 event_debug_unassign(&ns
->event
);
2561 log(EVDNS_LOG_WARN
, "Unable to add nameserver %s: error %d",
2562 evutil_format_sockaddr_port_(address
, addrbuf
, sizeof(addrbuf
)), err
);
2566 /* exported function */
2568 evdns_base_nameserver_add(struct evdns_base
*base
, unsigned long int address
)
2570 struct sockaddr_in sin
;
2572 memset(&sin
, 0, sizeof(sin
));
2573 sin
.sin_addr
.s_addr
= address
;
2574 sin
.sin_port
= htons(53);
2575 sin
.sin_family
= AF_INET
;
2577 res
= evdns_nameserver_add_impl_(base
, (struct sockaddr
*)&sin
, sizeof(sin
));
2583 evdns_nameserver_add(unsigned long int address
) {
2585 current_base
= evdns_base_new(NULL
, 0);
2586 return evdns_base_nameserver_add(current_base
, address
);
2590 sockaddr_setport(struct sockaddr
*sa
, ev_uint16_t port
)
2592 if (sa
->sa_family
== AF_INET
) {
2593 ((struct sockaddr_in
*)sa
)->sin_port
= htons(port
);
2594 } else if (sa
->sa_family
== AF_INET6
) {
2595 ((struct sockaddr_in6
*)sa
)->sin6_port
= htons(port
);
2600 sockaddr_getport(struct sockaddr
*sa
)
2602 if (sa
->sa_family
== AF_INET
) {
2603 return ntohs(((struct sockaddr_in
*)sa
)->sin_port
);
2604 } else if (sa
->sa_family
== AF_INET6
) {
2605 return ntohs(((struct sockaddr_in6
*)sa
)->sin6_port
);
2611 /* exported function */
2613 evdns_base_nameserver_ip_add(struct evdns_base
*base
, const char *ip_as_string
) {
2614 struct sockaddr_storage ss
;
2615 struct sockaddr
*sa
;
2616 int len
= sizeof(ss
);
2618 if (evutil_parse_sockaddr_port(ip_as_string
, (struct sockaddr
*)&ss
,
2620 log(EVDNS_LOG_WARN
, "Unable to parse nameserver address %s",
2624 sa
= (struct sockaddr
*) &ss
;
2625 if (sockaddr_getport(sa
) == 0)
2626 sockaddr_setport(sa
, 53);
2629 res
= evdns_nameserver_add_impl_(base
, sa
, len
);
2635 evdns_nameserver_ip_add(const char *ip_as_string
) {
2637 current_base
= evdns_base_new(NULL
, 0);
2638 return evdns_base_nameserver_ip_add(current_base
, ip_as_string
);
2642 evdns_base_nameserver_sockaddr_add(struct evdns_base
*base
,
2643 const struct sockaddr
*sa
, ev_socklen_t len
, unsigned flags
)
2646 EVUTIL_ASSERT(base
);
2648 res
= evdns_nameserver_add_impl_(base
, sa
, len
);
2654 evdns_base_get_nameserver_addr(struct evdns_base
*base
, int idx
,
2655 struct sockaddr
*sa
, ev_socklen_t len
)
2659 struct nameserver
*server
;
2661 server
= base
->server_head
;
2662 for (i
= 0; i
< idx
&& server
; ++i
, server
= server
->next
) {
2663 if (server
->next
== base
->server_head
)
2669 if (server
->addrlen
> len
) {
2670 result
= (int) server
->addrlen
;
2674 memcpy(sa
, &server
->address
, server
->addrlen
);
2675 result
= (int) server
->addrlen
;
2681 /* remove from the queue */
2683 evdns_request_remove(struct request
*req
, struct request
**head
)
2685 ASSERT_LOCKED(req
->base
);
2686 ASSERT_VALID_REQUEST(req
);
2690 struct request
*ptr
;
2692 EVUTIL_ASSERT(*head
!= NULL
);
2701 } while (ptr
!= *head
);
2702 EVUTIL_ASSERT(found
);
2704 EVUTIL_ASSERT(req
->next
);
2708 if (req
->next
== req
) {
2709 /* only item in the list */
2712 req
->next
->prev
= req
->prev
;
2713 req
->prev
->next
= req
->next
;
2714 if (*head
== req
) *head
= req
->next
;
2716 req
->next
= req
->prev
= NULL
;
2719 /* insert into the tail of the queue */
2721 evdns_request_insert(struct request
*req
, struct request
**head
) {
2722 ASSERT_LOCKED(req
->base
);
2723 ASSERT_VALID_REQUEST(req
);
2726 req
->next
= req
->prev
= req
;
2730 req
->prev
= (*head
)->prev
;
2731 req
->prev
->next
= req
;
2733 (*head
)->prev
= req
;
2737 string_num_dots(const char *s
) {
2739 while ((s
= strchr(s
, '.'))) {
2746 static struct request
*
2747 request_new(struct evdns_base
*base
, struct evdns_request
*handle
, int type
,
2748 const char *name
, int flags
, evdns_callback_type callback
,
2751 const char issuing_now
=
2752 (base
->global_requests_inflight
< base
->global_max_requests_inflight
) ? 1 : 0;
2754 const size_t name_len
= strlen(name
);
2755 const size_t request_max_len
= evdns_request_len(name_len
);
2756 const u16 trans_id
= issuing_now
? transaction_id_pick(base
) : 0xffff;
2757 /* the request data is alloced in a single block with the header */
2758 struct request
*const req
=
2759 mm_malloc(sizeof(struct request
) + request_max_len
);
2764 ASSERT_LOCKED(base
);
2766 if (!req
) return NULL
;
2768 if (name_len
>= sizeof(namebuf
)) {
2773 memset(req
, 0, sizeof(struct request
));
2776 evtimer_assign(&req
->timeout_event
, req
->base
->event_base
, evdns_request_timeout_callback
, req
);
2778 if (base
->global_randomize_case
) {
2780 char randbits
[(sizeof(namebuf
)+7)/8];
2781 strlcpy(namebuf
, name
, sizeof(namebuf
));
2782 evutil_secure_rng_get_bytes(randbits
, (name_len
+7)/8);
2783 for (i
= 0; i
< name_len
; ++i
) {
2784 if (EVUTIL_ISALPHA_(namebuf
[i
])) {
2785 if ((randbits
[i
>> 3] & (1<<(i
& 7))))
2788 namebuf
[i
] &= ~0x20;
2794 /* request data lives just after the header */
2795 req
->request
= ((u8
*) req
) + sizeof(struct request
);
2796 /* denotes that the request data shouldn't be free()ed */
2797 req
->request_appended
= 1;
2798 rlen
= evdns_request_data_build(name
, name_len
, trans_id
,
2799 type
, CLASS_INET
, req
->request
, request_max_len
);
2803 req
->request_len
= rlen
;
2804 req
->trans_id
= trans_id
;
2806 req
->request_type
= type
;
2807 req
->user_pointer
= user_ptr
;
2808 req
->user_callback
= callback
;
2809 req
->ns
= issuing_now
? nameserver_pick(base
) : NULL
;
2810 req
->next
= req
->prev
= NULL
;
2811 req
->handle
= handle
;
2813 handle
->current_req
= req
;
2814 handle
->base
= base
;
2824 request_submit(struct request
*const req
) {
2825 struct evdns_base
*base
= req
->base
;
2826 ASSERT_LOCKED(base
);
2827 ASSERT_VALID_REQUEST(req
);
2829 /* if it has a nameserver assigned then this is going */
2830 /* straight into the inflight queue */
2831 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
2833 base
->global_requests_inflight
++;
2834 req
->ns
->requests_inflight
++;
2836 evdns_request_transmit(req
);
2838 evdns_request_insert(req
, &base
->req_waiting_head
);
2839 base
->global_requests_waiting
++;
2843 /* exported function */
2845 evdns_cancel_request(struct evdns_base
*base
, struct evdns_request
*handle
)
2847 struct request
*req
;
2849 if (!handle
->current_req
)
2853 /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
2854 base
= handle
->base
;
2856 base
= handle
->current_req
->base
;
2860 if (handle
->pending_cb
) {
2865 req
= handle
->current_req
;
2866 ASSERT_VALID_REQUEST(req
);
2868 reply_schedule_callback(req
, 0, DNS_ERR_CANCEL
, NULL
);
2870 /* remove from inflight queue */
2871 request_finished(req
, &REQ_HEAD(base
, req
->trans_id
), 1);
2873 /* remove from global_waiting head */
2874 request_finished(req
, &base
->req_waiting_head
, 1);
2879 /* exported function */
2880 struct evdns_request
*
2881 evdns_base_resolve_ipv4(struct evdns_base
*base
, const char *name
, int flags
,
2882 evdns_callback_type callback
, void *ptr
) {
2883 struct evdns_request
*handle
;
2884 struct request
*req
;
2885 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2886 handle
= mm_calloc(1, sizeof(*handle
));
2890 if (flags
& DNS_QUERY_NO_SEARCH
) {
2892 request_new(base
, handle
, TYPE_A
, name
, flags
,
2895 request_submit(req
);
2897 search_request_new(base
, handle
, TYPE_A
, name
, flags
,
2900 if (handle
->current_req
== NULL
) {
2908 int evdns_resolve_ipv4(const char *name
, int flags
,
2909 evdns_callback_type callback
, void *ptr
)
2911 return evdns_base_resolve_ipv4(current_base
, name
, flags
, callback
, ptr
)
2916 /* exported function */
2917 struct evdns_request
*
2918 evdns_base_resolve_ipv6(struct evdns_base
*base
,
2919 const char *name
, int flags
,
2920 evdns_callback_type callback
, void *ptr
)
2922 struct evdns_request
*handle
;
2923 struct request
*req
;
2924 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2925 handle
= mm_calloc(1, sizeof(*handle
));
2929 if (flags
& DNS_QUERY_NO_SEARCH
) {
2930 req
= request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2933 request_submit(req
);
2935 search_request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2938 if (handle
->current_req
== NULL
) {
2946 int evdns_resolve_ipv6(const char *name
, int flags
,
2947 evdns_callback_type callback
, void *ptr
) {
2948 return evdns_base_resolve_ipv6(current_base
, name
, flags
, callback
, ptr
)
2952 struct evdns_request
*
2953 evdns_base_resolve_reverse(struct evdns_base
*base
, const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2955 struct evdns_request
*handle
;
2956 struct request
*req
;
2959 a
= ntohl(in
->s_addr
);
2960 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
2961 (int)(u8
)((a
)&0xff),
2962 (int)(u8
)((a
>>8 )&0xff),
2963 (int)(u8
)((a
>>16)&0xff),
2964 (int)(u8
)((a
>>24)&0xff));
2965 handle
= mm_calloc(1, sizeof(*handle
));
2968 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2970 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2972 request_submit(req
);
2973 if (handle
->current_req
== NULL
) {
2981 int evdns_resolve_reverse(const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2982 return evdns_base_resolve_reverse(current_base
, in
, flags
, callback
, ptr
)
2986 struct evdns_request
*
2987 evdns_base_resolve_reverse_ipv6(struct evdns_base
*base
, const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2988 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2991 struct evdns_request
*handle
;
2992 struct request
*req
;
2996 for (i
=15; i
>= 0; --i
) {
2997 u8 byte
= in
->s6_addr
[i
];
2998 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
3000 *cp
++ = "0123456789abcdef"[byte
>> 4];
3003 EVUTIL_ASSERT(cp
+ strlen("ip6.arpa") < buf
+sizeof(buf
));
3004 memcpy(cp
, "ip6.arpa", strlen("ip6.arpa")+1);
3005 handle
= mm_calloc(1, sizeof(*handle
));
3008 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
3010 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
3012 request_submit(req
);
3013 if (handle
->current_req
== NULL
) {
3021 int evdns_resolve_reverse_ipv6(const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
3022 return evdns_base_resolve_reverse_ipv6(current_base
, in
, flags
, callback
, ptr
)
3026 /* ================================================================= */
3027 /* Search support */
3029 /* the libc resolver has support for searching a number of domains */
3030 /* to find a name. If nothing else then it takes the single domain */
3031 /* from the gethostname() call. */
3033 /* It can also be configured via the domain and search options in a */
3036 /* The ndots option controls how many dots it takes for the resolver */
3037 /* to decide that a name is non-local and so try a raw lookup first. */
3039 struct search_domain
{
3041 struct search_domain
*next
;
3042 /* the text string is appended to this structure */
3045 struct search_state
{
3049 struct search_domain
*head
;
3053 search_state_decref(struct search_state
*const state
) {
3056 if (!state
->refcount
) {
3057 struct search_domain
*next
, *dom
;
3058 for (dom
= state
->head
; dom
; dom
= next
) {
3066 static struct search_state
*
3067 search_state_new(void) {
3068 struct search_state
*state
= (struct search_state
*) mm_malloc(sizeof(struct search_state
));
3069 if (!state
) return NULL
;
3070 memset(state
, 0, sizeof(struct search_state
));
3071 state
->refcount
= 1;
3078 search_postfix_clear(struct evdns_base
*base
) {
3079 search_state_decref(base
->global_search_state
);
3081 base
->global_search_state
= search_state_new();
3084 /* exported function */
3086 evdns_base_search_clear(struct evdns_base
*base
)
3089 search_postfix_clear(base
);
3094 evdns_search_clear(void) {
3095 evdns_base_search_clear(current_base
);
3099 search_postfix_add(struct evdns_base
*base
, const char *domain
) {
3101 struct search_domain
*sdomain
;
3102 while (domain
[0] == '.') domain
++;
3103 domain_len
= strlen(domain
);
3105 ASSERT_LOCKED(base
);
3106 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3107 if (!base
->global_search_state
) return;
3108 base
->global_search_state
->num_domains
++;
3110 sdomain
= (struct search_domain
*) mm_malloc(sizeof(struct search_domain
) + domain_len
);
3111 if (!sdomain
) return;
3112 memcpy( ((u8
*) sdomain
) + sizeof(struct search_domain
), domain
, domain_len
);
3113 sdomain
->next
= base
->global_search_state
->head
;
3114 sdomain
->len
= (int) domain_len
;
3116 base
->global_search_state
->head
= sdomain
;
3119 /* reverse the order of members in the postfix list. This is needed because, */
3120 /* when parsing resolv.conf we push elements in the wrong order */
3122 search_reverse(struct evdns_base
*base
) {
3123 struct search_domain
*cur
, *prev
= NULL
, *next
;
3124 ASSERT_LOCKED(base
);
3125 cur
= base
->global_search_state
->head
;
3133 base
->global_search_state
->head
= prev
;
3136 /* exported function */
3138 evdns_base_search_add(struct evdns_base
*base
, const char *domain
) {
3140 search_postfix_add(base
, domain
);
3144 evdns_search_add(const char *domain
) {
3145 evdns_base_search_add(current_base
, domain
);
3148 /* exported function */
3150 evdns_base_search_ndots_set(struct evdns_base
*base
, const int ndots
) {
3152 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3153 if (base
->global_search_state
)
3154 base
->global_search_state
->ndots
= ndots
;
3158 evdns_search_ndots_set(const int ndots
) {
3159 evdns_base_search_ndots_set(current_base
, ndots
);
3163 search_set_from_hostname(struct evdns_base
*base
) {
3164 char hostname
[HOST_NAME_MAX
+ 1], *domainname
;
3166 ASSERT_LOCKED(base
);
3167 search_postfix_clear(base
);
3168 if (gethostname(hostname
, sizeof(hostname
))) return;
3169 domainname
= strchr(hostname
, '.');
3170 if (!domainname
) return;
3171 search_postfix_add(base
, domainname
);
3174 /* warning: returns malloced string */
3176 search_make_new(const struct search_state
*const state
, int n
, const char *const base_name
) {
3177 const size_t base_len
= strlen(base_name
);
3178 const char need_to_append_dot
= base_name
[base_len
- 1] == '.' ? 0 : 1;
3179 struct search_domain
*dom
;
3181 for (dom
= state
->head
; dom
; dom
= dom
->next
) {
3183 /* this is the postfix we want */
3184 /* the actual postfix string is kept at the end of the structure */
3185 const u8
*const postfix
= ((u8
*) dom
) + sizeof(struct search_domain
);
3186 const int postfix_len
= dom
->len
;
3187 char *const newname
= (char *) mm_malloc(base_len
+ need_to_append_dot
+ postfix_len
+ 1);
3188 if (!newname
) return NULL
;
3189 memcpy(newname
, base_name
, base_len
);
3190 if (need_to_append_dot
) newname
[base_len
] = '.';
3191 memcpy(newname
+ base_len
+ need_to_append_dot
, postfix
, postfix_len
);
3192 newname
[base_len
+ need_to_append_dot
+ postfix_len
] = 0;
3197 /* we ran off the end of the list and still didn't find the requested string */
3199 return NULL
; /* unreachable; stops warnings in some compilers. */
3202 static struct request
*
3203 search_request_new(struct evdns_base
*base
, struct evdns_request
*handle
,
3204 int type
, const char *const name
, int flags
,
3205 evdns_callback_type user_callback
, void *user_arg
) {
3206 ASSERT_LOCKED(base
);
3207 EVUTIL_ASSERT(type
== TYPE_A
|| type
== TYPE_AAAA
);
3208 EVUTIL_ASSERT(handle
->current_req
== NULL
);
3209 if ( ((flags
& DNS_QUERY_NO_SEARCH
) == 0) &&
3210 base
->global_search_state
&&
3211 base
->global_search_state
->num_domains
) {
3212 /* we have some domains to search */
3213 struct request
*req
;
3214 if (string_num_dots(name
) >= base
->global_search_state
->ndots
) {
3215 req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3216 if (!req
) return NULL
;
3217 handle
->search_index
= -1;
3219 char *const new_name
= search_make_new(base
->global_search_state
, 0, name
);
3220 if (!new_name
) return NULL
;
3221 req
= request_new(base
, handle
, type
, new_name
, flags
, user_callback
, user_arg
);
3223 if (!req
) return NULL
;
3224 handle
->search_index
= 0;
3226 EVUTIL_ASSERT(handle
->search_origname
== NULL
);
3227 handle
->search_origname
= mm_strdup(name
);
3228 if (handle
->search_origname
== NULL
) {
3229 /* XXX Should we dealloc req? If yes, how? */
3234 handle
->search_state
= base
->global_search_state
;
3235 handle
->search_flags
= flags
;
3236 base
->global_search_state
->refcount
++;
3237 request_submit(req
);
3240 struct request
*const req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3241 if (!req
) return NULL
;
3242 request_submit(req
);
3247 /* this is called when a request has failed to find a name. We need to check */
3248 /* if it is part of a search and, if so, try the next name in the list */
3250 /* 0 another request has been submitted */
3251 /* 1 no more requests needed */
3253 search_try_next(struct evdns_request
*const handle
) {
3254 struct request
*req
= handle
->current_req
;
3255 struct evdns_base
*base
= req
->base
;
3256 struct request
*newreq
;
3257 ASSERT_LOCKED(base
);
3258 if (handle
->search_state
) {
3259 /* it is part of a search */
3261 handle
->search_index
++;
3262 if (handle
->search_index
>= handle
->search_state
->num_domains
) {
3263 /* no more postfixes to try, however we may need to try */
3264 /* this name without a postfix */
3265 if (string_num_dots(handle
->search_origname
) < handle
->search_state
->ndots
) {
3266 /* yep, we need to try it raw */
3267 newreq
= request_new(base
, NULL
, req
->request_type
, handle
->search_origname
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3268 log(EVDNS_LOG_DEBUG
, "Search: trying raw query %s", handle
->search_origname
);
3270 search_request_finished(handle
);
3277 new_name
= search_make_new(handle
->search_state
, handle
->search_index
, handle
->search_origname
);
3278 if (!new_name
) return 1;
3279 log(EVDNS_LOG_DEBUG
, "Search: now trying %s (%d)", new_name
, handle
->search_index
);
3280 newreq
= request_new(base
, NULL
, req
->request_type
, new_name
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3282 if (!newreq
) return 1;
3288 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 0);
3289 handle
->current_req
= newreq
;
3290 newreq
->handle
= handle
;
3291 request_submit(newreq
);
3296 search_request_finished(struct evdns_request
*const handle
) {
3297 ASSERT_LOCKED(handle
->current_req
->base
);
3298 if (handle
->search_state
) {
3299 search_state_decref(handle
->search_state
);
3300 handle
->search_state
= NULL
;
3302 if (handle
->search_origname
) {
3303 mm_free(handle
->search_origname
);
3304 handle
->search_origname
= NULL
;
3308 /* ================================================================= */
3309 /* Parsing resolv.conf files */
3312 evdns_resolv_set_defaults(struct evdns_base
*base
, int flags
) {
3313 /* if the file isn't found then we assume a local resolver */
3314 ASSERT_LOCKED(base
);
3315 if (flags
& DNS_OPTION_SEARCH
) search_set_from_hostname(base
);
3316 if (flags
& DNS_OPTION_NAMESERVERS
) evdns_base_nameserver_ip_add(base
,"127.0.0.1");
3319 #ifndef EVENT__HAVE_STRTOK_R
3321 strtok_r(char *s
, const char *delim
, char **state
) {
3323 start
= cp
= s
? s
: *state
;
3326 while (*cp
&& !strchr(delim
, *cp
))
3341 /* helper version of atoi which returns -1 on error */
3343 strtoint(const char *const str
)
3346 const int r
= strtol(str
, &endptr
, 10);
3347 if (*endptr
) return -1;
3351 /* Parse a number of seconds into a timeval; return -1 on error. */
3353 evdns_strtotimeval(const char *const str
, struct timeval
*out
)
3357 d
= strtod(str
, &endptr
);
3358 if (*endptr
) return -1;
3359 if (d
< 0) return -1;
3360 out
->tv_sec
= (int) d
;
3361 out
->tv_usec
= (int) ((d
- (int) d
)*1000000);
3362 if (out
->tv_sec
== 0 && out
->tv_usec
< 1000) /* less than 1 msec */
3367 /* helper version of atoi that returns -1 on error and clips to bounds. */
3369 strtoint_clipped(const char *const str
, int min
, int max
)
3371 int r
= strtoint(str
);
3383 evdns_base_set_max_requests_inflight(struct evdns_base
*base
, int maxinflight
)
3385 int old_n_heads
= base
->n_req_heads
, n_heads
;
3386 struct request
**old_heads
= base
->req_heads
, **new_heads
, *req
;
3389 ASSERT_LOCKED(base
);
3390 if (maxinflight
< 1)
3392 n_heads
= (maxinflight
+4) / 5;
3393 EVUTIL_ASSERT(n_heads
> 0);
3394 new_heads
= mm_calloc(n_heads
, sizeof(struct request
*));
3398 for (i
= 0; i
< old_n_heads
; ++i
) {
3399 while (old_heads
[i
]) {
3401 evdns_request_remove(req
, &old_heads
[i
]);
3402 evdns_request_insert(req
, &new_heads
[req
->trans_id
% n_heads
]);
3407 base
->req_heads
= new_heads
;
3408 base
->n_req_heads
= n_heads
;
3409 base
->global_max_requests_inflight
= maxinflight
;
3413 /* exported function */
3415 evdns_base_set_option(struct evdns_base
*base
,
3416 const char *option
, const char *val
)
3420 res
= evdns_base_set_option_impl(base
, option
, val
, DNS_OPTIONS_ALL
);
3426 str_matches_option(const char *s1
, const char *optionname
)
3428 /* Option names are given as "option:" We accept either 'option' in
3429 * s1, or 'option:randomjunk'. The latter form is to implement the
3430 * resolv.conf parser. */
3431 size_t optlen
= strlen(optionname
);
3432 size_t slen
= strlen(s1
);
3433 if (slen
== optlen
|| slen
== optlen
- 1)
3434 return !strncmp(s1
, optionname
, slen
);
3435 else if (slen
> optlen
)
3436 return !strncmp(s1
, optionname
, optlen
);
3442 evdns_base_set_option_impl(struct evdns_base
*base
,
3443 const char *option
, const char *val
, int flags
)
3445 ASSERT_LOCKED(base
);
3446 if (str_matches_option(option
, "ndots:")) {
3447 const int ndots
= strtoint(val
);
3448 if (ndots
== -1) return -1;
3449 if (!(flags
& DNS_OPTION_SEARCH
)) return 0;
3450 log(EVDNS_LOG_DEBUG
, "Setting ndots to %d", ndots
);
3451 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3452 if (!base
->global_search_state
) return -1;
3453 base
->global_search_state
->ndots
= ndots
;
3454 } else if (str_matches_option(option
, "timeout:")) {
3456 if (evdns_strtotimeval(val
, &tv
) == -1) return -1;
3457 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3458 log(EVDNS_LOG_DEBUG
, "Setting timeout to %s", val
);
3459 memcpy(&base
->global_timeout
, &tv
, sizeof(struct timeval
));
3460 } else if (str_matches_option(option
, "getaddrinfo-allow-skew:")) {
3462 if (evdns_strtotimeval(val
, &tv
) == -1) return -1;
3463 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3464 log(EVDNS_LOG_DEBUG
, "Setting getaddrinfo-allow-skew to %s",
3466 memcpy(&base
->global_getaddrinfo_allow_skew
, &tv
,
3467 sizeof(struct timeval
));
3468 } else if (str_matches_option(option
, "max-timeouts:")) {
3469 const int maxtimeout
= strtoint_clipped(val
, 1, 255);
3470 if (maxtimeout
== -1) return -1;
3471 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3472 log(EVDNS_LOG_DEBUG
, "Setting maximum allowed timeouts to %d",
3474 base
->global_max_nameserver_timeout
= maxtimeout
;
3475 } else if (str_matches_option(option
, "max-inflight:")) {
3476 const int maxinflight
= strtoint_clipped(val
, 1, 65000);
3477 if (maxinflight
== -1) return -1;
3478 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3479 log(EVDNS_LOG_DEBUG
, "Setting maximum inflight requests to %d",
3481 evdns_base_set_max_requests_inflight(base
, maxinflight
);
3482 } else if (str_matches_option(option
, "attempts:")) {
3483 int retries
= strtoint(val
);
3484 if (retries
== -1) return -1;
3485 if (retries
> 255) retries
= 255;
3486 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3487 log(EVDNS_LOG_DEBUG
, "Setting retries to %d", retries
);
3488 base
->global_max_retransmits
= retries
;
3489 } else if (str_matches_option(option
, "randomize-case:")) {
3490 int randcase
= strtoint(val
);
3491 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3492 base
->global_randomize_case
= randcase
;
3493 } else if (str_matches_option(option
, "bind-to:")) {
3494 /* XXX This only applies to successive nameservers, not
3495 * to already-configured ones. We might want to fix that. */
3496 int len
= sizeof(base
->global_outgoing_address
);
3497 if (!(flags
& DNS_OPTION_NAMESERVERS
)) return 0;
3498 if (evutil_parse_sockaddr_port(val
,
3499 (struct sockaddr
*)&base
->global_outgoing_address
, &len
))
3501 base
->global_outgoing_addrlen
= len
;
3502 } else if (str_matches_option(option
, "initial-probe-timeout:")) {
3504 if (evdns_strtotimeval(val
, &tv
) == -1) return -1;
3505 if (tv
.tv_sec
> 3600)
3507 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3508 log(EVDNS_LOG_DEBUG
, "Setting initial probe timeout to %s",
3510 memcpy(&base
->global_nameserver_probe_initial_timeout
, &tv
,
3517 evdns_set_option(const char *option
, const char *val
, int flags
)
3520 current_base
= evdns_base_new(NULL
, 0);
3521 return evdns_base_set_option(current_base
, option
, val
);
3525 resolv_conf_parse_line(struct evdns_base
*base
, char *const start
, int flags
) {
3527 static const char *const delims
= " \t";
3528 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3531 char *const first_token
= strtok_r(start
, delims
, &strtok_state
);
3532 ASSERT_LOCKED(base
);
3533 if (!first_token
) return;
3535 if (!strcmp(first_token
, "nameserver") && (flags
& DNS_OPTION_NAMESERVERS
)) {
3536 const char *const nameserver
= NEXT_TOKEN
;
3539 evdns_base_nameserver_ip_add(base
, nameserver
);
3540 } else if (!strcmp(first_token
, "domain") && (flags
& DNS_OPTION_SEARCH
)) {
3541 const char *const domain
= NEXT_TOKEN
;
3543 search_postfix_clear(base
);
3544 search_postfix_add(base
, domain
);
3546 } else if (!strcmp(first_token
, "search") && (flags
& DNS_OPTION_SEARCH
)) {
3548 search_postfix_clear(base
);
3550 while ((domain
= NEXT_TOKEN
)) {
3551 search_postfix_add(base
, domain
);
3553 search_reverse(base
);
3554 } else if (!strcmp(first_token
, "options")) {
3556 while ((option
= NEXT_TOKEN
)) {
3557 const char *val
= strchr(option
, ':');
3558 evdns_base_set_option_impl(base
, option
, val
? val
+1 : "", flags
);
3564 /* exported function */
3567 /* 1 failed to open file */
3568 /* 2 failed to stat file */
3569 /* 3 file too large */
3570 /* 4 out of memory */
3571 /* 5 short read from file */
3573 evdns_base_resolv_conf_parse(struct evdns_base
*base
, int flags
, const char *const filename
) {
3576 res
= evdns_base_resolv_conf_parse_impl(base
, flags
, filename
);
3582 evdns_get_default_hosts_filename(void)
3585 /* Windows is a little coy about where it puts its configuration
3586 * files. Sure, they're _usually_ in C:\windows\system32, but
3587 * there's no reason in principle they couldn't be in
3588 * W:\hoboken chicken emergency\
3590 char path
[MAX_PATH
+1];
3591 static const char hostfile
[] = "\\drivers\\etc\\hosts";
3595 if (! SHGetSpecialFolderPathA(NULL
, path
, CSIDL_SYSTEM
, 0))
3597 len_out
= strlen(path
)+strlen(hostfile
)+1;
3598 path_out
= mm_malloc(len_out
);
3599 evutil_snprintf(path_out
, len_out
, "%s%s", path
, hostfile
);
3602 return mm_strdup("/etc/hosts");
3607 evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
) {
3613 log(EVDNS_LOG_DEBUG
, "Parsing resolv.conf file %s", filename
);
3615 if (flags
& DNS_OPTION_HOSTSFILE
) {
3616 char *fname
= evdns_get_default_hosts_filename();
3617 evdns_base_load_hosts(base
, fname
);
3622 if ((err
= evutil_read_file_(filename
, &resolv
, &n
, 0)) < 0) {
3625 evdns_resolv_set_defaults(base
, flags
);
3634 char *const newline
= strchr(start
, '\n');
3636 resolv_conf_parse_line(base
, start
, flags
);
3640 resolv_conf_parse_line(base
, start
, flags
);
3641 start
= newline
+ 1;
3645 if (!base
->server_head
&& (flags
& DNS_OPTION_NAMESERVERS
)) {
3646 /* no nameservers were configured. */
3647 evdns_base_nameserver_ip_add(base
, "127.0.0.1");
3650 if (flags
& DNS_OPTION_SEARCH
&& (!base
->global_search_state
|| base
->global_search_state
->num_domains
== 0)) {
3651 search_set_from_hostname(base
);
3659 evdns_resolv_conf_parse(int flags
, const char *const filename
) {
3661 current_base
= evdns_base_new(NULL
, 0);
3662 return evdns_base_resolv_conf_parse(current_base
, flags
, filename
);
3667 /* Add multiple nameservers from a space-or-comma-separated list. */
3669 evdns_nameserver_ip_add_line(struct evdns_base
*base
, const char *ips
) {
3673 ASSERT_LOCKED(base
);
3675 while (isspace(*ips
) || *ips
== ',' || *ips
== '\t')
3678 while (isdigit(*ips
) || *ips
== '.' || *ips
== ':' ||
3679 *ips
=='[' || *ips
==']')
3681 buf
= mm_malloc(ips
-addr
+1);
3683 memcpy(buf
, addr
, ips
-addr
);
3684 buf
[ips
-addr
] = '\0';
3685 r
= evdns_base_nameserver_ip_add(base
, buf
);
3692 typedef DWORD(WINAPI
*GetNetworkParams_fn_t
)(FIXED_INFO
*, DWORD
*);
3694 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3695 /* figure out what our nameservers are. */
3697 load_nameservers_with_getnetworkparams(struct evdns_base
*base
)
3699 /* Based on MSDN examples and inspection of c-ares code. */
3702 ULONG size
= sizeof(FIXED_INFO
);
3704 int status
= 0, r
, added_any
;
3706 GetNetworkParams_fn_t fn
;
3708 ASSERT_LOCKED(base
);
3709 if (!(handle
= evutil_load_windows_system_library_(
3710 TEXT("iphlpapi.dll")))) {
3711 log(EVDNS_LOG_WARN
, "Could not open iphlpapi.dll");
3715 if (!(fn
= (GetNetworkParams_fn_t
) GetProcAddress(handle
, "GetNetworkParams"))) {
3716 log(EVDNS_LOG_WARN
, "Could not get address of function.");
3721 buf
= mm_malloc(size
);
3722 if (!buf
) { status
= 4; goto done
; }
3724 r
= fn(fixed
, &size
);
3725 if (r
!= ERROR_SUCCESS
&& r
!= ERROR_BUFFER_OVERFLOW
) {
3729 if (r
!= ERROR_SUCCESS
) {
3731 buf
= mm_malloc(size
);
3732 if (!buf
) { status
= 4; goto done
; }
3734 r
= fn(fixed
, &size
);
3735 if (r
!= ERROR_SUCCESS
) {
3736 log(EVDNS_LOG_DEBUG
, "fn() failed.");
3742 EVUTIL_ASSERT(fixed
);
3744 ns
= &(fixed
->DnsServerList
);
3746 r
= evdns_nameserver_ip_add_line(base
, ns
->IpAddress
.String
);
3748 log(EVDNS_LOG_DEBUG
,"Could not add nameserver %s to list,error: %d",
3749 (ns
->IpAddress
.String
),(int)GetLastError());
3753 log(EVDNS_LOG_DEBUG
,"Successfully added %s as nameserver",ns
->IpAddress
.String
);
3760 log(EVDNS_LOG_DEBUG
, "No nameservers added.");
3771 FreeLibrary(handle
);
3776 config_nameserver_from_reg_key(struct evdns_base
*base
, HKEY key
, const TCHAR
*subkey
)
3779 DWORD bufsz
= 0, type
= 0;
3782 ASSERT_LOCKED(base
);
3783 if (RegQueryValueEx(key
, subkey
, 0, &type
, NULL
, &bufsz
)
3786 if (!(buf
= mm_malloc(bufsz
)))
3789 if (RegQueryValueEx(key
, subkey
, 0, &type
, (LPBYTE
)buf
, &bufsz
)
3790 == ERROR_SUCCESS
&& bufsz
> 1) {
3791 status
= evdns_nameserver_ip_add_line(base
,buf
);
3798 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3799 #define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
3800 #define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
3803 load_nameservers_from_registry(struct evdns_base
*base
)
3807 #define TRY(k, name) \
3808 if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3809 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3811 } else if (!found) { \
3812 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3816 ASSERT_LOCKED(base
);
3818 if (((int)GetVersion()) > 0) { /* NT */
3819 HKEY nt_key
= 0, interfaces_key
= 0;
3821 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_NT_KEY
, 0,
3822 KEY_READ
, &nt_key
) != ERROR_SUCCESS
) {
3823 log(EVDNS_LOG_DEBUG
,"Couldn't open nt key, %d",(int)GetLastError());
3826 r
= RegOpenKeyEx(nt_key
, TEXT("Interfaces"), 0,
3827 KEY_QUERY_VALUE
|KEY_ENUMERATE_SUB_KEYS
,
3829 if (r
!= ERROR_SUCCESS
) {
3830 log(EVDNS_LOG_DEBUG
,"Couldn't open interfaces key, %d",(int)GetLastError());
3833 TRY(nt_key
, "NameServer");
3834 TRY(nt_key
, "DhcpNameServer");
3835 TRY(interfaces_key
, "NameServer");
3836 TRY(interfaces_key
, "DhcpNameServer");
3837 RegCloseKey(interfaces_key
);
3838 RegCloseKey(nt_key
);
3841 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_9X_KEY
, 0,
3842 KEY_READ
, &win_key
) != ERROR_SUCCESS
) {
3843 log(EVDNS_LOG_DEBUG
, "Couldn't open registry key, %d", (int)GetLastError());
3846 TRY(win_key
, "NameServer");
3847 RegCloseKey(win_key
);
3851 log(EVDNS_LOG_WARN
,"Didn't find any nameservers.");
3854 return found
? 0 : -1;
3859 evdns_base_config_windows_nameservers(struct evdns_base
*base
)
3864 base
= current_base
;
3868 fname
= evdns_get_default_hosts_filename();
3869 log(EVDNS_LOG_DEBUG
, "Loading hosts entries from %s", fname
);
3870 evdns_base_load_hosts(base
, fname
);
3874 if (load_nameservers_with_getnetworkparams(base
) == 0) {
3878 r
= load_nameservers_from_registry(base
);
3885 evdns_config_windows_nameservers(void)
3887 if (!current_base
) {
3888 current_base
= evdns_base_new(NULL
, 1);
3889 return current_base
== NULL
? -1 : 0;
3891 return evdns_base_config_windows_nameservers(current_base
);
3897 evdns_base_new(struct event_base
*event_base
, int flags
)
3899 struct evdns_base
*base
;
3901 if (evutil_secure_rng_init() < 0) {
3902 log(EVDNS_LOG_WARN
, "Unable to seed random number generator; "
3907 /* Give the evutil library a hook into its evdns-enabled
3908 * functionality. We can't just call evdns_getaddrinfo directly or
3909 * else libevent-core will depend on libevent-extras. */
3910 evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo
);
3912 base
= mm_malloc(sizeof(struct evdns_base
));
3915 memset(base
, 0, sizeof(struct evdns_base
));
3916 base
->req_waiting_head
= NULL
;
3918 EVTHREAD_ALLOC_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
3921 /* Set max requests inflight and allocate req_heads. */
3922 base
->req_heads
= NULL
;
3924 evdns_base_set_max_requests_inflight(base
, 64);
3926 base
->server_head
= NULL
;
3927 base
->event_base
= event_base
;
3928 base
->global_good_nameservers
= base
->global_requests_inflight
=
3929 base
->global_requests_waiting
= 0;
3931 base
->global_timeout
.tv_sec
= 5;
3932 base
->global_timeout
.tv_usec
= 0;
3933 base
->global_max_reissues
= 1;
3934 base
->global_max_retransmits
= 3;
3935 base
->global_max_nameserver_timeout
= 3;
3936 base
->global_search_state
= NULL
;
3937 base
->global_randomize_case
= 1;
3938 base
->global_getaddrinfo_allow_skew
.tv_sec
= 3;
3939 base
->global_getaddrinfo_allow_skew
.tv_usec
= 0;
3940 base
->global_nameserver_probe_initial_timeout
.tv_sec
= 10;
3941 base
->global_nameserver_probe_initial_timeout
.tv_usec
= 0;
3943 TAILQ_INIT(&base
->hostsdb
);
3945 #define EVDNS_BASE_ALL_FLAGS (0x8001)
3946 if (flags
& ~EVDNS_BASE_ALL_FLAGS
) {
3947 flags
= EVDNS_BASE_INITIALIZE_NAMESERVERS
;
3949 "Unrecognized flag passed to evdns_base_new(). Assuming "
3950 "you meant EVDNS_BASE_INITIALIZE_NAMESERVERS.");
3952 #undef EVDNS_BASE_ALL_FLAGS
3954 if (flags
& EVDNS_BASE_INITIALIZE_NAMESERVERS
) {
3957 r
= evdns_base_config_windows_nameservers(base
);
3959 r
= evdns_base_resolv_conf_parse(base
, DNS_OPTIONS_ALL
, "/etc/resolv.conf");
3962 evdns_base_free_and_unlock(base
, 0);
3966 if (flags
& EVDNS_BASE_DISABLE_WHEN_INACTIVE
) {
3967 base
->disable_when_inactive
= 1;
3977 struct evdns_base
*base
= evdns_base_new(NULL
, 1);
3979 current_base
= base
;
3987 evdns_err_to_string(int err
)
3990 case DNS_ERR_NONE
: return "no error";
3991 case DNS_ERR_FORMAT
: return "misformatted query";
3992 case DNS_ERR_SERVERFAILED
: return "server failed";
3993 case DNS_ERR_NOTEXIST
: return "name does not exist";
3994 case DNS_ERR_NOTIMPL
: return "query not implemented";
3995 case DNS_ERR_REFUSED
: return "refused";
3997 case DNS_ERR_TRUNCATED
: return "reply truncated or ill-formed";
3998 case DNS_ERR_UNKNOWN
: return "unknown";
3999 case DNS_ERR_TIMEOUT
: return "request timed out";
4000 case DNS_ERR_SHUTDOWN
: return "dns subsystem shut down";
4001 case DNS_ERR_CANCEL
: return "dns request canceled";
4002 case DNS_ERR_NODATA
: return "no records in the reply";
4003 default: return "[Unknown error code]";
4008 evdns_nameserver_free(struct nameserver
*server
)
4010 if (server
->socket
>= 0)
4011 evutil_closesocket(server
->socket
);
4012 (void) event_del(&server
->event
);
4013 event_debug_unassign(&server
->event
);
4014 if (server
->state
== 0)
4015 (void) event_del(&server
->timeout_event
);
4016 if (server
->probe_request
) {
4017 evdns_cancel_request(server
->base
, server
->probe_request
);
4018 server
->probe_request
= NULL
;
4020 event_debug_unassign(&server
->timeout_event
);
4025 evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
)
4027 struct nameserver
*server
, *server_next
;
4028 struct search_domain
*dom
, *dom_next
;
4031 /* Requires that we hold the lock. */
4033 /* TODO(nickm) we might need to refcount here. */
4035 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
4036 while (base
->req_heads
[i
]) {
4038 reply_schedule_callback(base
->req_heads
[i
], 0, DNS_ERR_SHUTDOWN
, NULL
);
4039 request_finished(base
->req_heads
[i
], &REQ_HEAD(base
, base
->req_heads
[i
]->trans_id
), 1);
4042 while (base
->req_waiting_head
) {
4044 reply_schedule_callback(base
->req_waiting_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
4045 request_finished(base
->req_waiting_head
, &base
->req_waiting_head
, 1);
4047 base
->global_requests_inflight
= base
->global_requests_waiting
= 0;
4049 for (server
= base
->server_head
; server
; server
= server_next
) {
4050 server_next
= server
->next
;
4051 evdns_nameserver_free(server
);
4052 if (server_next
== base
->server_head
)
4055 base
->server_head
= NULL
;
4056 base
->global_good_nameservers
= 0;
4058 if (base
->global_search_state
) {
4059 for (dom
= base
->global_search_state
->head
; dom
; dom
= dom_next
) {
4060 dom_next
= dom
->next
;
4063 mm_free(base
->global_search_state
);
4064 base
->global_search_state
= NULL
;
4068 struct hosts_entry
*victim
;
4069 while ((victim
= TAILQ_FIRST(&base
->hostsdb
))) {
4070 TAILQ_REMOVE(&base
->hostsdb
, victim
, next
);
4075 mm_free(base
->req_heads
);
4078 EVTHREAD_FREE_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
4084 evdns_base_free(struct evdns_base
*base
, int fail_requests
)
4087 evdns_base_free_and_unlock(base
, fail_requests
);
4091 evdns_base_clear_host_addresses(struct evdns_base
*base
)
4093 struct hosts_entry
*victim
;
4095 while ((victim
= TAILQ_FIRST(&base
->hostsdb
))) {
4096 TAILQ_REMOVE(&base
->hostsdb
, victim
, next
);
4103 evdns_shutdown(int fail_requests
)
4106 struct evdns_base
*b
= current_base
;
4107 current_base
= NULL
;
4108 evdns_base_free(b
, fail_requests
);
4110 evdns_log_fn
= NULL
;
4114 evdns_base_parse_hosts_line(struct evdns_base
*base
, char *line
)
4117 static const char *const delims
= " \t";
4118 char *const addr
= strtok_r(line
, delims
, &strtok_state
);
4119 char *hostname
, *hash
;
4120 struct sockaddr_storage ss
;
4121 int socklen
= sizeof(ss
);
4122 ASSERT_LOCKED(base
);
4124 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
4126 if (!addr
|| *addr
== '#')
4129 memset(&ss
, 0, sizeof(ss
));
4130 if (evutil_parse_sockaddr_port(addr
, (struct sockaddr
*)&ss
, &socklen
)<0)
4132 if (socklen
> (int)sizeof(struct sockaddr_in6
))
4135 if (sockaddr_getport((struct sockaddr
*)&ss
))
4138 while ((hostname
= NEXT_TOKEN
)) {
4139 struct hosts_entry
*he
;
4141 if ((hash
= strchr(hostname
, '#'))) {
4142 if (hash
== hostname
)
4147 namelen
= strlen(hostname
);
4149 he
= mm_calloc(1, sizeof(struct hosts_entry
)+namelen
);
4152 EVUTIL_ASSERT(socklen
<= (int)sizeof(he
->addr
));
4153 memcpy(&he
->addr
, &ss
, socklen
);
4154 memcpy(he
->hostname
, hostname
, namelen
+1);
4155 he
->addrlen
= socklen
;
4157 TAILQ_INSERT_TAIL(&base
->hostsdb
, he
, next
);
4168 evdns_base_load_hosts_impl(struct evdns_base
*base
, const char *hosts_fname
)
4170 char *str
=NULL
, *cp
, *eol
;
4174 ASSERT_LOCKED(base
);
4176 if (hosts_fname
== NULL
||
4177 (err
= evutil_read_file_(hosts_fname
, &str
, &len
, 0)) < 0) {
4179 strlcpy(tmp
, "127.0.0.1 localhost", sizeof(tmp
));
4180 evdns_base_parse_hosts_line(base
, tmp
);
4181 strlcpy(tmp
, "::1 localhost", sizeof(tmp
));
4182 evdns_base_parse_hosts_line(base
, tmp
);
4183 return err
? -1 : 0;
4186 /* This will break early if there is a NUL in the hosts file.
4187 * Probably not a problem.*/
4190 eol
= strchr(cp
, '\n');
4194 evdns_base_parse_hosts_line(base
, cp
);
4197 evdns_base_parse_hosts_line(base
, cp
);
4207 evdns_base_load_hosts(struct evdns_base
*base
, const char *hosts_fname
)
4211 base
= current_base
;
4213 res
= evdns_base_load_hosts_impl(base
, hosts_fname
);
4218 /* A single request for a getaddrinfo, either v4 or v6. */
4219 struct getaddrinfo_subrequest
{
4220 struct evdns_request
*r
;
4224 /* State data used to implement an in-progress getaddrinfo. */
4225 struct evdns_getaddrinfo_request
{
4226 struct evdns_base
*evdns_base
;
4227 /* Copy of the modified 'hints' data that we'll use to build
4229 struct evutil_addrinfo hints
;
4230 /* The callback to invoke when we're done */
4231 evdns_getaddrinfo_cb user_cb
;
4232 /* User-supplied data to give to the callback. */
4234 /* The port to use when building sockaddrs. */
4236 /* The sub_request for an A record (if any) */
4237 struct getaddrinfo_subrequest ipv4_request
;
4238 /* The sub_request for an AAAA record (if any) */
4239 struct getaddrinfo_subrequest ipv6_request
;
4241 /* The cname result that we were told (if any) */
4244 /* If we have one request answered and one request still inflight,
4245 * then this field holds the answer from the first request... */
4246 struct evutil_addrinfo
*pending_result
;
4247 /* And this event is a timeout that will tell us to cancel the second
4248 * request if it's taking a long time. */
4249 struct event timeout
;
4251 /* And this field holds the error code from the first request... */
4253 /* If this is set, the user canceled this request. */
4254 unsigned user_canceled
: 1;
4255 /* If this is set, the user can no longer cancel this request; we're
4256 * just waiting for the free. */
4257 unsigned request_done
: 1;
4260 /* Convert an evdns errors to the equivalent getaddrinfo error. */
4262 evdns_err_to_getaddrinfo_err(int e1
)
4264 /* XXX Do this better! */
4265 if (e1
== DNS_ERR_NONE
)
4267 else if (e1
== DNS_ERR_NOTEXIST
)
4268 return EVUTIL_EAI_NONAME
;
4270 return EVUTIL_EAI_FAIL
;
4273 /* Return the more informative of two getaddrinfo errors. */
4275 getaddrinfo_merge_err(int e1
, int e2
)
4277 /* XXXX be cleverer here. */
4285 free_getaddrinfo_request(struct evdns_getaddrinfo_request
*data
)
4287 /* DO NOT CALL this if either of the requests is pending. Only once
4288 * both callbacks have been invoked is it safe to free the request */
4289 if (data
->pending_result
)
4290 evutil_freeaddrinfo(data
->pending_result
);
4291 if (data
->cname_result
)
4292 mm_free(data
->cname_result
);
4293 event_del(&data
->timeout
);
4299 add_cname_to_reply(struct evdns_getaddrinfo_request
*data
,
4300 struct evutil_addrinfo
*ai
)
4302 if (data
->cname_result
&& ai
) {
4303 ai
->ai_canonname
= data
->cname_result
;
4304 data
->cname_result
= NULL
;
4308 /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
4309 * request has finished, but the other one took too long to answer. Pass
4310 * along the answer we got, and cancel the other request.
4313 evdns_getaddrinfo_timeout_cb(evutil_socket_t fd
, short what
, void *ptr
)
4315 int v4_timedout
= 0, v6_timedout
= 0;
4316 struct evdns_getaddrinfo_request
*data
= ptr
;
4318 /* Cancel any pending requests, and note which one */
4319 if (data
->ipv4_request
.r
) {
4320 /* XXXX This does nothing if the request's callback is already
4321 * running (pending_cb is set). */
4322 evdns_cancel_request(NULL
, data
->ipv4_request
.r
);
4324 EVDNS_LOCK(data
->evdns_base
);
4325 ++data
->evdns_base
->getaddrinfo_ipv4_timeouts
;
4326 EVDNS_UNLOCK(data
->evdns_base
);
4328 if (data
->ipv6_request
.r
) {
4329 /* XXXX This does nothing if the request's callback is already
4330 * running (pending_cb is set). */
4331 evdns_cancel_request(NULL
, data
->ipv6_request
.r
);
4333 EVDNS_LOCK(data
->evdns_base
);
4334 ++data
->evdns_base
->getaddrinfo_ipv6_timeouts
;
4335 EVDNS_UNLOCK(data
->evdns_base
);
4338 /* We only use this timeout callback when we have an answer for
4340 EVUTIL_ASSERT(!v4_timedout
|| !v6_timedout
);
4342 /* Report the outcome of the other request that didn't time out. */
4343 if (data
->pending_result
) {
4344 add_cname_to_reply(data
, data
->pending_result
);
4345 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4346 data
->pending_result
= NULL
;
4348 int e
= data
->pending_error
;
4350 e
= EVUTIL_EAI_AGAIN
;
4351 data
->user_cb(e
, NULL
, data
->user_data
);
4354 data
->user_cb
= NULL
; /* prevent double-call if evdns callbacks are
4355 * in-progress. XXXX It would be better if this
4356 * weren't necessary. */
4358 if (!v4_timedout
&& !v6_timedout
) {
4359 /* should be impossible? XXXX */
4360 free_getaddrinfo_request(data
);
4365 evdns_getaddrinfo_set_timeout(struct evdns_base
*evdns_base
,
4366 struct evdns_getaddrinfo_request
*data
)
4368 return event_add(&data
->timeout
, &evdns_base
->global_getaddrinfo_allow_skew
);
4372 evdns_result_is_answer(int result
)
4374 return (result
!= DNS_ERR_NOTIMPL
&& result
!= DNS_ERR_REFUSED
&&
4375 result
!= DNS_ERR_SERVERFAILED
&& result
!= DNS_ERR_CANCEL
);
4379 evdns_getaddrinfo_gotresolve(int result
, char type
, int count
,
4380 int ttl
, void *addresses
, void *arg
)
4383 struct getaddrinfo_subrequest
*req
= arg
;
4384 struct getaddrinfo_subrequest
*other_req
;
4385 struct evdns_getaddrinfo_request
*data
;
4387 struct evutil_addrinfo
*res
;
4389 struct sockaddr_in sin
;
4390 struct sockaddr_in6 sin6
;
4391 struct sockaddr
*sa
;
4392 int socklen
, addrlen
;
4397 EVUTIL_ASSERT(req
->type
== DNS_IPv4_A
|| req
->type
== DNS_IPv6_AAAA
);
4398 if (req
->type
== DNS_IPv4_A
) {
4399 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv4_request
);
4400 other_req
= &data
->ipv6_request
;
4402 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv6_request
);
4403 other_req
= &data
->ipv4_request
;
4406 /** Called from evdns_base_free() with @fail_requests == 1 */
4407 if (result
!= DNS_ERR_SHUTDOWN
) {
4408 EVDNS_LOCK(data
->evdns_base
);
4409 if (evdns_result_is_answer(result
)) {
4410 if (req
->type
== DNS_IPv4_A
)
4411 ++data
->evdns_base
->getaddrinfo_ipv4_answered
;
4413 ++data
->evdns_base
->getaddrinfo_ipv6_answered
;
4415 user_canceled
= data
->user_canceled
;
4416 if (other_req
->r
== NULL
)
4417 data
->request_done
= 1;
4418 EVDNS_UNLOCK(data
->evdns_base
);
4420 data
->evdns_base
= NULL
;
4421 user_canceled
= data
->user_canceled
;
4426 if (result
== DNS_ERR_CANCEL
&& ! user_canceled
) {
4427 /* Internal cancel request from timeout or internal error.
4428 * we already answered the user. */
4429 if (other_req
->r
== NULL
)
4430 free_getaddrinfo_request(data
);
4434 if (data
->user_cb
== NULL
) {
4435 /* We already answered. XXXX This shouldn't be needed; see
4436 * comments in evdns_getaddrinfo_timeout_cb */
4437 free_getaddrinfo_request(data
);
4441 if (result
== DNS_ERR_NONE
) {
4443 err
= EVUTIL_EAI_NODATA
;
4447 err
= evdns_err_to_getaddrinfo_err(result
);
4451 /* Looks like we got an error. */
4453 /* The other request is still working; maybe it will
4455 /* XXXX handle failure from set_timeout */
4456 if (result
!= DNS_ERR_SHUTDOWN
) {
4457 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4459 data
->pending_error
= err
;
4463 if (user_canceled
) {
4464 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4465 } else if (data
->pending_result
) {
4466 /* If we have an answer waiting, and we weren't
4467 * canceled, ignore this error. */
4468 add_cname_to_reply(data
, data
->pending_result
);
4469 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4470 data
->pending_result
= NULL
;
4472 if (data
->pending_error
)
4473 err
= getaddrinfo_merge_err(err
,
4474 data
->pending_error
);
4475 data
->user_cb(err
, NULL
, data
->user_data
);
4477 free_getaddrinfo_request(data
);
4479 } else if (user_canceled
) {
4481 /* The other request is still working; let it hit this
4482 * callback with EVUTIL_EAI_CANCEL callback and report
4486 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4487 free_getaddrinfo_request(data
);
4491 /* Looks like we got some answers. We should turn them into addrinfos
4492 * and then either queue those or return them all. */
4493 EVUTIL_ASSERT(type
== DNS_IPv4_A
|| type
== DNS_IPv6_AAAA
);
4495 if (type
== DNS_IPv4_A
) {
4496 memset(&sin
, 0, sizeof(sin
));
4497 sin
.sin_family
= AF_INET
;
4498 sin
.sin_port
= htons(data
->port
);
4500 sa
= (struct sockaddr
*)&sin
;
4501 socklen
= sizeof(sin
);
4503 addrp
= &sin
.sin_addr
.s_addr
;
4505 memset(&sin6
, 0, sizeof(sin6
));
4506 sin6
.sin6_family
= AF_INET6
;
4507 sin6
.sin6_port
= htons(data
->port
);
4509 sa
= (struct sockaddr
*)&sin6
;
4510 socklen
= sizeof(sin6
);
4512 addrp
= &sin6
.sin6_addr
.s6_addr
;
4516 for (i
=0; i
< count
; ++i
) {
4517 struct evutil_addrinfo
*ai
;
4518 memcpy(addrp
, ((char*)addresses
)+i
*addrlen
, addrlen
);
4519 ai
= evutil_new_addrinfo_(sa
, socklen
, &data
->hints
);
4522 evdns_cancel_request(NULL
, other_req
->r
);
4524 data
->user_cb(EVUTIL_EAI_MEMORY
, NULL
, data
->user_data
);
4526 evutil_freeaddrinfo(res
);
4528 if (other_req
->r
== NULL
)
4529 free_getaddrinfo_request(data
);
4532 res
= evutil_addrinfo_append_(res
, ai
);
4536 /* The other request is still in progress; wait for it */
4537 /* XXXX handle failure from set_timeout */
4538 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4539 data
->pending_result
= res
;
4542 /* The other request is done or never started; append its
4543 * results (if any) and return them. */
4544 if (data
->pending_result
) {
4545 if (req
->type
== DNS_IPv4_A
)
4546 res
= evutil_addrinfo_append_(res
,
4547 data
->pending_result
);
4549 res
= evutil_addrinfo_append_(
4550 data
->pending_result
, res
);
4551 data
->pending_result
= NULL
;
4554 /* Call the user callback. */
4555 add_cname_to_reply(data
, res
);
4556 data
->user_cb(0, res
, data
->user_data
);
4559 free_getaddrinfo_request(data
);
4563 static struct hosts_entry
*
4564 find_hosts_entry(struct evdns_base
*base
, const char *hostname
,
4565 struct hosts_entry
*find_after
)
4567 struct hosts_entry
*e
;
4570 e
= TAILQ_NEXT(find_after
, next
);
4572 e
= TAILQ_FIRST(&base
->hostsdb
);
4574 for (; e
; e
= TAILQ_NEXT(e
, next
)) {
4575 if (!evutil_ascii_strcasecmp(e
->hostname
, hostname
))
4582 evdns_getaddrinfo_fromhosts(struct evdns_base
*base
,
4583 const char *nodename
, struct evutil_addrinfo
*hints
, ev_uint16_t port
,
4584 struct evutil_addrinfo
**res
)
4587 struct hosts_entry
*e
;
4588 struct evutil_addrinfo
*ai
=NULL
;
4589 int f
= hints
->ai_family
;
4592 for (e
= find_hosts_entry(base
, nodename
, NULL
); e
;
4593 e
= find_hosts_entry(base
, nodename
, e
)) {
4594 struct evutil_addrinfo
*ai_new
;
4596 if ((e
->addr
.sa
.sa_family
== AF_INET
&& f
== PF_INET6
) ||
4597 (e
->addr
.sa
.sa_family
== AF_INET6
&& f
== PF_INET
))
4599 ai_new
= evutil_new_addrinfo_(&e
->addr
.sa
, e
->addrlen
, hints
);
4604 sockaddr_setport(ai_new
->ai_addr
, port
);
4605 ai
= evutil_addrinfo_append_(ai
, ai_new
);
4610 /* Note that we return an empty answer if we found entries for
4611 * this hostname but none were of the right address type. */
4616 evutil_freeaddrinfo(ai
);
4621 struct evdns_getaddrinfo_request
*
4622 evdns_getaddrinfo(struct evdns_base
*dns_base
,
4623 const char *nodename
, const char *servname
,
4624 const struct evutil_addrinfo
*hints_in
,
4625 evdns_getaddrinfo_cb cb
, void *arg
)
4627 struct evdns_getaddrinfo_request
*data
;
4628 struct evutil_addrinfo hints
;
4629 struct evutil_addrinfo
*res
= NULL
;
4635 dns_base
= current_base
;
4638 "Call to getaddrinfo_async with no "
4639 "evdns_base configured.");
4640 cb(EVUTIL_EAI_FAIL
, NULL
, arg
); /* ??? better error? */
4645 /* If we _must_ answer this immediately, do so. */
4646 if ((hints_in
&& (hints_in
->ai_flags
& EVUTIL_AI_NUMERICHOST
))) {
4648 err
= evutil_getaddrinfo(nodename
, servname
, hints_in
, &res
);
4654 memcpy(&hints
, hints_in
, sizeof(hints
));
4656 memset(&hints
, 0, sizeof(hints
));
4657 hints
.ai_family
= PF_UNSPEC
;
4660 evutil_adjust_hints_for_addrconfig_(&hints
);
4662 /* Now try to see if we _can_ answer immediately. */
4663 /* (It would be nice to do this by calling getaddrinfo directly, with
4664 * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
4665 * a reliable way to distinguish the "that wasn't a numeric host!" case
4666 * from any other EAI_NONAME cases.) */
4667 err
= evutil_getaddrinfo_common_(nodename
, servname
, &hints
, &res
, &port
);
4668 if (err
!= EVUTIL_EAI_NEED_RESOLVE
) {
4673 /* If there is an entry in the hosts file, we should give it now. */
4674 if (!evdns_getaddrinfo_fromhosts(dns_base
, nodename
, &hints
, port
, &res
)) {
4679 /* Okay, things are serious now. We're going to need to actually
4682 data
= mm_calloc(1,sizeof(struct evdns_getaddrinfo_request
));
4684 cb(EVUTIL_EAI_MEMORY
, NULL
, arg
);
4688 memcpy(&data
->hints
, &hints
, sizeof(data
->hints
));
4689 data
->port
= (ev_uint16_t
)port
;
4690 data
->ipv4_request
.type
= DNS_IPv4_A
;
4691 data
->ipv6_request
.type
= DNS_IPv6_AAAA
;
4693 data
->user_data
= arg
;
4694 data
->evdns_base
= dns_base
;
4696 want_cname
= (hints
.ai_flags
& EVUTIL_AI_CANONNAME
);
4698 /* If we are asked for a PF_UNSPEC address, we launch two requests in
4699 * parallel: one for an A address and one for an AAAA address. We
4700 * can't send just one request, since many servers only answer one
4701 * question per DNS request.
4703 * Once we have the answer to one request, we allow for a short
4704 * timeout before we report it, to see if the other one arrives. If
4705 * they both show up in time, then we report both the answers.
4707 * If too many addresses of one type time out or fail, we should stop
4708 * launching those requests. (XXX we don't do that yet.)
4711 if (hints
.ai_family
!= PF_INET6
) {
4712 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv4 as %p",
4713 nodename
, &data
->ipv4_request
);
4715 data
->ipv4_request
.r
= evdns_base_resolve_ipv4(dns_base
,
4716 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4717 &data
->ipv4_request
);
4718 if (want_cname
&& data
->ipv4_request
.r
)
4719 data
->ipv4_request
.r
->current_req
->put_cname_in_ptr
=
4720 &data
->cname_result
;
4722 if (hints
.ai_family
!= PF_INET
) {
4723 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv6 as %p",
4724 nodename
, &data
->ipv6_request
);
4726 data
->ipv6_request
.r
= evdns_base_resolve_ipv6(dns_base
,
4727 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4728 &data
->ipv6_request
);
4729 if (want_cname
&& data
->ipv6_request
.r
)
4730 data
->ipv6_request
.r
->current_req
->put_cname_in_ptr
=
4731 &data
->cname_result
;
4734 evtimer_assign(&data
->timeout
, dns_base
->event_base
,
4735 evdns_getaddrinfo_timeout_cb
, data
);
4737 if (data
->ipv4_request
.r
|| data
->ipv6_request
.r
) {
4741 cb(EVUTIL_EAI_FAIL
, NULL
, arg
);
4747 evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request
*data
)
4749 EVDNS_LOCK(data
->evdns_base
);
4750 if (data
->request_done
) {
4751 EVDNS_UNLOCK(data
->evdns_base
);
4754 event_del(&data
->timeout
);
4755 data
->user_canceled
= 1;
4756 if (data
->ipv4_request
.r
)
4757 evdns_cancel_request(data
->evdns_base
, data
->ipv4_request
.r
);
4758 if (data
->ipv6_request
.r
)
4759 evdns_cancel_request(data
->evdns_base
, data
->ipv6_request
.r
);
4760 EVDNS_UNLOCK(data
->evdns_base
);