1 /* $NetBSD: evdns.c,v 1.3 2015/01/29 07:26:02 spz Exp $ */
2 /* Copyright 2006-2007 Niels Provos
3 * Copyright 2007-2012 Nick Mathewson and Niels Provos
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 /* Based on software by Adam Langly. Adam's original message:
31 * Adam Langley <agl@imperialviolet.org>
32 * http://www.imperialviolet.org/eventdns.html
35 * This software is Public Domain. To view a copy of the public domain dedication,
36 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
37 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
39 * I ask and expect, but do not require, that all derivative works contain an
40 * attribution similar to:
41 * Parts developed by Adam Langley <agl@imperialviolet.org>
43 * You may wish to replace the word "Parts" with something else depending on
44 * the amount of original code.
46 * (Derivative works does not include programs which link against, run or include
47 * the source verbatim in their source distributions)
52 #include <sys/types.h>
53 #include "event2/event-config.h"
54 #include <sys/cdefs.h>
55 __RCSID("$NetBSD: evdns.c,v 1.3 2015/01/29 07:26:02 spz Exp $");
57 #ifndef _FORTIFY_SOURCE
58 #define _FORTIFY_SOURCE 3
63 #ifdef _EVENT_HAVE_SYS_TIME_H
66 #ifdef _EVENT_HAVE_STDINT_H
72 #ifdef _EVENT_HAVE_UNISTD_H
83 #define _WIN32_IE 0x400
88 #include "event2/dns.h"
89 #include "event2/dns_struct.h"
90 #include "event2/dns_compat.h"
91 #include "event2/util.h"
92 #include "event2/event.h"
93 #include "event2/event_struct.h"
94 #include "event2/thread.h"
96 #include "event2/bufferevent.h"
97 #include "event2/bufferevent_struct.h"
98 #include "bufferevent-internal.h"
100 #include "defer-internal.h"
101 #include "log-internal.h"
102 #include "mm-internal.h"
103 #include "strlcpy-internal.h"
104 #include "ipv6-internal.h"
105 #include "util-internal.h"
106 #include "evthread-internal.h"
109 #include <winsock2.h>
111 #include <iphlpapi.h>
114 #include <sys/socket.h>
115 #include <netinet/in.h>
116 #include <arpa/inet.h>
119 #ifdef _EVENT_HAVE_NETINET_IN6_H
120 #include <netinet/in6.h>
123 #define EVDNS_LOG_DEBUG 0
124 #define EVDNS_LOG_WARN 1
125 #define EVDNS_LOG_MSG 2
127 #ifndef HOST_NAME_MAX
128 #define HOST_NAME_MAX 255
134 #define MIN(a,b) ((a)<(b)?(a):(b))
136 #define ASSERT_VALID_REQUEST(req) \
137 EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
139 #define u64 ev_uint64_t
140 #define u32 ev_uint32_t
141 #define u16 ev_uint16_t
142 #define u8 ev_uint8_t
144 /* maximum number of addresses from a single packet */
145 /* that we bother recording */
146 #define MAX_V4_ADDRS 32
147 #define MAX_V6_ADDRS 32
150 #define TYPE_A EVDNS_TYPE_A
152 #define TYPE_PTR EVDNS_TYPE_PTR
153 #define TYPE_SOA EVDNS_TYPE_SOA
154 #define TYPE_AAAA EVDNS_TYPE_AAAA
156 #define CLASS_INET EVDNS_CLASS_INET
158 /* Persistent handle. We keep this separate from 'struct request' since we
159 * need some object to last for as long as an evdns_request is outstanding so
160 * that it can be canceled, whereas a search request can lead to multiple
161 * 'struct request' instances being created over its lifetime. */
162 struct evdns_request
{
163 struct request
*current_req
;
164 struct evdns_base
*base
;
166 int pending_cb
; /* Waiting for its callback to be invoked; not
167 * owned by event base any more. */
169 /* elements used by the searching code */
171 struct search_state
*search_state
;
172 char *search_origname
; /* needs to be free()ed */
177 u8
*request
; /* the dns packet data */
178 u8 request_type
; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
179 unsigned int request_len
;
181 int tx_count
; /* the number of times that this packet has been sent */
182 void *user_pointer
; /* the pointer given to us for this request */
183 evdns_callback_type user_callback
;
184 struct nameserver
*ns
; /* the server which we last sent it */
186 /* these objects are kept in a circular list */
187 /* XXX We could turn this into a CIRCLEQ. */
188 struct request
*next
, *prev
;
190 struct event timeout_event
;
192 u16 trans_id
; /* the transaction id */
193 unsigned request_appended
:1; /* true if the request pointer is data which follows this struct */
194 unsigned transmit_me
:1; /* needs to be transmitted */
196 /* XXXX This is a horrible hack. */
197 char **put_cname_in_ptr
; /* store the cname here if we get one. */
199 struct evdns_base
*base
;
201 struct evdns_request
*handle
;
206 unsigned int have_answer
: 1;
210 u32 addresses
[MAX_V4_ADDRS
];
214 struct in6_addr addresses
[MAX_V6_ADDRS
];
217 char name
[HOST_NAME_MAX
];
223 evutil_socket_t socket
; /* a connected UDP socket */
224 struct sockaddr_storage address
;
225 ev_socklen_t addrlen
;
226 int failed_times
; /* number of times which we have given this server a chance */
227 int timedout
; /* number of times in a row a request has timed out */
229 /* these objects are kept in a circular list */
230 struct nameserver
*next
, *prev
;
231 struct event timeout_event
; /* used to keep the timeout for */
232 /* when we next probe this server. */
233 /* Valid if state == 0 */
234 /* Outstanding probe request for this nameserver, if any */
235 struct evdns_request
*probe_request
;
236 char state
; /* zero if we think that this server is down */
237 char choked
; /* true if we have an EAGAIN from this server's socket */
238 char write_waiting
; /* true if we are waiting for EV_WRITE events */
239 struct evdns_base
*base
;
243 /* Represents a local port where we're listening for DNS requests. Right now, */
244 /* only UDP is supported. */
245 struct evdns_server_port
{
246 evutil_socket_t socket
; /* socket we use to read queries and write replies. */
247 int refcnt
; /* reference count. */
248 char choked
; /* Are we currently blocked from writing? */
249 char closing
; /* Are we trying to close this port, pending writes? */
250 evdns_request_callback_fn_type user_callback
; /* Fn to handle requests */
251 void *user_data
; /* Opaque pointer passed to user_callback */
252 struct event event
; /* Read/write event */
253 /* circular list of replies that we want to write. */
254 struct server_request
*pending_replies
;
255 struct event_base
*event_base
;
257 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
262 /* Represents part of a reply being built. (That is, a single RR.) */
263 struct server_reply_item
{
264 struct server_reply_item
*next
; /* next item in sequence. */
265 char *name
; /* name part of the RR */
266 u16 type
; /* The RR type */
267 u16
class; /* The RR class (usually CLASS_INET) */
268 u32 ttl
; /* The RR TTL */
269 char is_name
; /* True iff data is a label */
270 u16 datalen
; /* Length of data; -1 if data is a label */
271 void *data
; /* The contents of the RR */
274 /* Represents a request that we've received as a DNS server, and holds */
275 /* the components of the reply as we're constructing it. */
276 struct server_request
{
277 /* Pointers to the next and previous entries on the list of replies */
278 /* that we're waiting to write. Only set if we have tried to respond */
279 /* and gotten EAGAIN. */
280 struct server_request
*next_pending
;
281 struct server_request
*prev_pending
;
283 u16 trans_id
; /* Transaction id. */
284 struct evdns_server_port
*port
; /* Which port received this request on? */
285 struct sockaddr_storage addr
; /* Where to send the response */
286 ev_socklen_t addrlen
; /* length of addr */
288 int n_answer
; /* how many answer RRs have been set? */
289 int n_authority
; /* how many authority RRs have been set? */
290 int n_additional
; /* how many additional RRs have been set? */
292 struct server_reply_item
*answer
; /* linked list of answer RRs */
293 struct server_reply_item
*authority
; /* linked list of authority RRs */
294 struct server_reply_item
*additional
; /* linked list of additional RRs */
296 /* Constructed response. Only set once we're ready to send a reply. */
297 /* Once this is set, the RR fields are cleared, and no more should be set. */
301 /* Caller-visible fields: flags, questions. */
302 struct evdns_server_request base
;
306 /* An array of n_req_heads circular lists for inflight requests.
307 * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
309 struct request
**req_heads
;
310 /* A circular list of requests that we're waiting to send, but haven't
311 * sent yet because there are too many requests inflight */
312 struct request
*req_waiting_head
;
313 /* A circular list of nameservers. */
314 struct nameserver
*server_head
;
317 struct event_base
*event_base
;
319 /* The number of good nameservers that we have */
320 int global_good_nameservers
;
322 /* inflight requests are contained in the req_head list */
323 /* and are actually going out across the network */
324 int global_requests_inflight
;
325 /* requests which aren't inflight are in the waiting list */
326 /* and are counted here */
327 int global_requests_waiting
;
329 int global_max_requests_inflight
;
331 struct timeval global_timeout
; /* 5 seconds by default */
332 int global_max_reissues
; /* a reissue occurs when we get some errors from the server */
333 int global_max_retransmits
; /* number of times we'll retransmit a request which timed out */
334 /* number of timeouts in a row before we consider this server to be down */
335 int global_max_nameserver_timeout
;
336 /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
337 int global_randomize_case
;
339 /* The first time that a nameserver fails, how long do we wait before
340 * probing to see if it has returned? */
341 struct timeval global_nameserver_probe_initial_timeout
;
343 /** Port to bind to for outgoing DNS packets. */
344 struct sockaddr_storage global_outgoing_address
;
345 /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
346 ev_socklen_t global_outgoing_addrlen
;
348 struct timeval global_getaddrinfo_allow_skew
;
350 int getaddrinfo_ipv4_timeouts
;
351 int getaddrinfo_ipv6_timeouts
;
352 int getaddrinfo_ipv4_answered
;
353 int getaddrinfo_ipv6_answered
;
355 struct search_state
*global_search_state
;
357 TAILQ_HEAD(hosts_list
, hosts_entry
) hostsdb
;
359 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
365 TAILQ_ENTRY(hosts_entry
) next
;
368 struct sockaddr_in sin
;
369 struct sockaddr_in6 sin6
;
375 static struct evdns_base
*current_base
= NULL
;
378 evdns_get_global_base(void)
383 /* Given a pointer to an evdns_server_request, get the corresponding */
384 /* server_request. */
385 #define TO_SERVER_REQUEST(base_ptr) \
386 ((struct server_request*) \
387 (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
389 #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
391 static struct nameserver
*nameserver_pick(struct evdns_base
*base
);
392 static void evdns_request_insert(struct request
*req
, struct request
**head
);
393 static void evdns_request_remove(struct request
*req
, struct request
**head
);
394 static void nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
395 static int evdns_transmit(struct evdns_base
*base
);
396 static int evdns_request_transmit(struct request
*req
);
397 static void nameserver_send_probe(struct nameserver
*const ns
);
398 static void search_request_finished(struct evdns_request
*const);
399 static int search_try_next(struct evdns_request
*const req
);
400 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
);
401 static void evdns_requests_pump_waiting_queue(struct evdns_base
*base
);
402 static u16
transaction_id_pick(struct evdns_base
*base
);
403 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
);
404 static void request_submit(struct request
*const req
);
406 static int server_request_free(struct server_request
*req
);
407 static void server_request_free_answers(struct server_request
*req
);
408 static void server_port_free(struct evdns_server_port
*port
);
409 static void server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
410 static int evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
);
411 static int evdns_base_set_option_impl(struct evdns_base
*base
,
412 const char *option
, const char *val
, int flags
);
413 static void evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
);
415 static int strtoint(const char *const str
);
417 #ifdef _EVENT_DISABLE_THREAD_SUPPORT
418 #define EVDNS_LOCK(base) _EVUTIL_NIL_STMT
419 #define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT
420 #define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT
422 #define EVDNS_LOCK(base) \
423 EVLOCK_LOCK((base)->lock, 0)
424 #define EVDNS_UNLOCK(base) \
425 EVLOCK_UNLOCK((base)->lock, 0)
426 #define ASSERT_LOCKED(base) \
427 EVLOCK_ASSERT_LOCKED((base)->lock)
431 default_evdns_log_fn(int warning
, const char *buf
)
433 if (warning
== EVDNS_LOG_WARN
)
434 event_warnx("[evdns] %s", buf
);
435 else if (warning
== EVDNS_LOG_MSG
)
436 event_msgx("[evdns] %s", buf
);
438 event_debug(("[evdns] %s", buf
));
441 static evdns_debug_log_fn_type evdns_log_fn
= NULL
;
444 evdns_set_log_fn(evdns_debug_log_fn_type fn
)
450 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
452 #define EVDNS_LOG_CHECK
455 static void _evdns_log(int warn
, const char *fmt
, ...) EVDNS_LOG_CHECK
;
457 _evdns_log(int warn
, const char *fmt
, ...)
464 evutil_vsnprintf(buf
, sizeof(buf
), fmt
, args
);
467 if (warn
== EVDNS_LOG_MSG
)
468 warn
= EVDNS_LOG_WARN
;
469 evdns_log_fn(warn
, buf
);
471 default_evdns_log_fn(warn
, buf
);
476 #define log _evdns_log
478 /* This walks the list of inflight requests to find the */
479 /* one with a matching transaction id. Returns NULL on */
481 static struct request
*
482 request_find_from_trans_id(struct evdns_base
*base
, u16 trans_id
) {
483 struct request
*req
= REQ_HEAD(base
, trans_id
);
484 struct request
*const started_at
= req
;
490 if (req
->trans_id
== trans_id
) return req
;
492 } while (req
!= started_at
);
498 /* a libevent callback function which is called when a nameserver */
499 /* has gone down and we want to test if it has came back to life yet */
501 nameserver_prod_callback(evutil_socket_t fd
, short events
, void *arg
) {
502 struct nameserver
*const ns
= (struct nameserver
*) arg
;
506 EVDNS_LOCK(ns
->base
);
507 nameserver_send_probe(ns
);
508 EVDNS_UNLOCK(ns
->base
);
511 /* a libevent callback which is called when a nameserver probe (to see if */
512 /* it has come back to life) times out. We increment the count of failed_times */
513 /* and wait longer to send the next probe packet. */
515 nameserver_probe_failed(struct nameserver
*const ns
) {
516 struct timeval timeout
;
519 ASSERT_LOCKED(ns
->base
);
520 (void) evtimer_del(&ns
->timeout_event
);
521 if (ns
->state
== 1) {
522 /* This can happen if the nameserver acts in a way which makes us mark */
523 /* it as bad and then starts sending good replies. */
527 #define MAX_PROBE_TIMEOUT 3600
528 #define TIMEOUT_BACKOFF_FACTOR 3
530 memcpy(&timeout
, &ns
->base
->global_nameserver_probe_initial_timeout
,
531 sizeof(struct timeval
));
532 for (i
=ns
->failed_times
; i
> 0 && timeout
.tv_sec
< MAX_PROBE_TIMEOUT
; --i
) {
533 timeout
.tv_sec
*= TIMEOUT_BACKOFF_FACTOR
;
534 timeout
.tv_usec
*= TIMEOUT_BACKOFF_FACTOR
;
535 if (timeout
.tv_usec
> 1000000) {
536 timeout
.tv_sec
+= timeout
.tv_usec
/ 1000000;
537 timeout
.tv_usec
%= 1000000;
540 if (timeout
.tv_sec
> MAX_PROBE_TIMEOUT
) {
541 timeout
.tv_sec
= MAX_PROBE_TIMEOUT
;
547 if (evtimer_add(&ns
->timeout_event
, &timeout
) < 0) {
550 "Error from libevent when adding timer event for %s",
551 evutil_format_sockaddr_port(
552 (struct sockaddr
*)&ns
->address
,
553 addrbuf
, sizeof(addrbuf
)));
557 /* called when a nameserver has been deemed to have failed. For example, too */
558 /* many packets have timed out etc */
560 nameserver_failed(struct nameserver
*const ns
, const char *msg
) {
561 struct request
*req
, *started_at
;
562 struct evdns_base
*base
= ns
->base
;
567 /* if this nameserver has already been marked as failed */
568 /* then don't do anything */
569 if (!ns
->state
) return;
571 log(EVDNS_LOG_MSG
, "Nameserver %s has failed: %s",
572 evutil_format_sockaddr_port(
573 (struct sockaddr
*)&ns
->address
,
574 addrbuf
, sizeof(addrbuf
)),
577 base
->global_good_nameservers
--;
578 EVUTIL_ASSERT(base
->global_good_nameservers
>= 0);
579 if (base
->global_good_nameservers
== 0) {
580 log(EVDNS_LOG_MSG
, "All nameservers have failed");
584 ns
->failed_times
= 1;
586 if (evtimer_add(&ns
->timeout_event
,
587 &base
->global_nameserver_probe_initial_timeout
) < 0) {
589 "Error from libevent when adding timer event for %s",
590 evutil_format_sockaddr_port(
591 (struct sockaddr
*)&ns
->address
,
592 addrbuf
, sizeof(addrbuf
)));
596 /* walk the list of inflight requests to see if any can be reassigned to */
597 /* a different server. Requests in the waiting queue don't have a */
598 /* nameserver assigned yet */
600 /* if we don't have *any* good nameservers then there's no point */
601 /* trying to reassign requests to one */
602 if (!base
->global_good_nameservers
) return;
604 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
605 req
= started_at
= base
->req_heads
[i
];
608 if (req
->tx_count
== 0 && req
->ns
== ns
) {
609 /* still waiting to go out, can be moved */
610 /* to another server */
611 req
->ns
= nameserver_pick(base
);
614 } while (req
!= started_at
);
620 nameserver_up(struct nameserver
*const ns
)
623 ASSERT_LOCKED(ns
->base
);
624 if (ns
->state
) return;
625 log(EVDNS_LOG_MSG
, "Nameserver %s is back up",
626 evutil_format_sockaddr_port(
627 (struct sockaddr
*)&ns
->address
,
628 addrbuf
, sizeof(addrbuf
)));
629 evtimer_del(&ns
->timeout_event
);
630 if (ns
->probe_request
) {
631 evdns_cancel_request(ns
->base
, ns
->probe_request
);
632 ns
->probe_request
= NULL
;
635 ns
->failed_times
= 0;
637 ns
->base
->global_good_nameservers
++;
641 request_trans_id_set(struct request
*const req
, const u16 trans_id
) {
642 req
->trans_id
= trans_id
;
643 *((u16
*) req
->request
) = htons(trans_id
);
646 /* Called to remove a request from a list and dealloc it. */
647 /* head is a pointer to the head of the list it should be */
648 /* removed from or NULL if the request isn't in a list. */
649 /* when free_handle is one, free the handle as well. */
651 request_finished(struct request
*const req
, struct request
**head
, int free_handle
) {
652 struct evdns_base
*base
= req
->base
;
653 int was_inflight
= (head
!= &base
->req_waiting_head
);
655 ASSERT_VALID_REQUEST(req
);
658 evdns_request_remove(req
, head
);
660 log(EVDNS_LOG_DEBUG
, "Removing timeout for request %p", req
);
662 evtimer_del(&req
->timeout_event
);
663 base
->global_requests_inflight
--;
665 base
->global_requests_waiting
--;
667 /* it was initialized during request_new / evtimer_assign */
668 event_debug_unassign(&req
->timeout_event
);
670 if (!req
->request_appended
) {
671 /* need to free the request data on it's own */
672 mm_free(req
->request
);
674 /* the request data is appended onto the header */
675 /* so everything gets free()ed when we: */
679 EVUTIL_ASSERT(req
->handle
->current_req
== req
);
682 search_request_finished(req
->handle
);
683 req
->handle
->current_req
= NULL
;
684 if (! req
->handle
->pending_cb
) {
685 /* If we're planning to run the callback,
686 * don't free the handle until later. */
687 mm_free(req
->handle
);
689 req
->handle
= NULL
; /* If we have a bug, let's crash
692 req
->handle
->current_req
= NULL
;
698 evdns_requests_pump_waiting_queue(base
);
702 /* This is called when a server returns a funny error code. */
703 /* We try the request again with another server. */
707 /* 1 failed/reissue is pointless */
709 request_reissue(struct request
*req
) {
710 const struct nameserver
*const last_ns
= req
->ns
;
711 ASSERT_LOCKED(req
->base
);
712 ASSERT_VALID_REQUEST(req
);
713 /* the last nameserver should have been marked as failing */
714 /* by the caller of this function, therefore pick will try */
715 /* not to return it */
716 req
->ns
= nameserver_pick(req
->base
);
717 if (req
->ns
== last_ns
) {
718 /* ... but pick did return it */
719 /* not a lot of point in trying again with the */
724 req
->reissue_count
++;
726 req
->transmit_me
= 1;
731 /* this function looks for space on the inflight queue and promotes */
732 /* requests from the waiting queue if it can. */
735 /* add return code, see at nameserver_pick() and other functions. */
737 evdns_requests_pump_waiting_queue(struct evdns_base
*base
) {
739 while (base
->global_requests_inflight
< base
->global_max_requests_inflight
&&
740 base
->global_requests_waiting
) {
743 EVUTIL_ASSERT(base
->req_waiting_head
);
744 req
= base
->req_waiting_head
;
746 req
->ns
= nameserver_pick(base
);
750 /* move a request from the waiting queue to the inflight queue */
751 evdns_request_remove(req
, &base
->req_waiting_head
);
753 base
->global_requests_waiting
--;
754 base
->global_requests_inflight
++;
756 request_trans_id_set(req
, transaction_id_pick(base
));
758 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
759 evdns_request_transmit(req
);
760 evdns_transmit(base
);
764 /* TODO(nickm) document */
765 struct deferred_reply_callback
{
766 struct deferred_cb deferred
;
767 struct evdns_request
*handle
;
772 evdns_callback_type user_callback
;
777 reply_run_callback(struct deferred_cb
*d
, void *user_pointer
)
779 struct deferred_reply_callback
*cb
=
780 EVUTIL_UPCAST(d
, struct deferred_reply_callback
, deferred
);
782 switch (cb
->request_type
) {
785 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv4_A
,
786 cb
->reply
.data
.a
.addrcount
, cb
->ttl
,
787 cb
->reply
.data
.a
.addresses
,
790 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
793 if (cb
->have_reply
) {
794 char *name
= cb
->reply
.data
.ptr
.name
;
795 cb
->user_callback(DNS_ERR_NONE
, DNS_PTR
, 1, cb
->ttl
,
796 &name
, user_pointer
);
798 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
803 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv6_AAAA
,
804 cb
->reply
.data
.aaaa
.addrcount
, cb
->ttl
,
805 cb
->reply
.data
.aaaa
.addresses
,
808 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
814 if (cb
->handle
&& cb
->handle
->pending_cb
) {
822 reply_schedule_callback(struct request
*const req
, u32 ttl
, u32 err
, struct reply
*reply
)
824 struct deferred_reply_callback
*d
= mm_calloc(1, sizeof(*d
));
827 event_warn("%s: Couldn't allocate space for deferred callback.",
832 ASSERT_LOCKED(req
->base
);
834 d
->request_type
= req
->request_type
;
835 d
->user_callback
= req
->user_callback
;
840 memcpy(&d
->reply
, reply
, sizeof(struct reply
));
844 req
->handle
->pending_cb
= 1;
845 d
->handle
= req
->handle
;
848 event_deferred_cb_init(&d
->deferred
, reply_run_callback
,
850 event_deferred_cb_schedule(
851 event_base_get_deferred_cb_queue(req
->base
->event_base
),
855 /* this processes a parsed reply packet */
857 reply_handle(struct request
*const req
, u16 flags
, u32 ttl
, struct reply
*reply
) {
860 static const int error_codes
[] = {
861 DNS_ERR_FORMAT
, DNS_ERR_SERVERFAILED
, DNS_ERR_NOTEXIST
,
862 DNS_ERR_NOTIMPL
, DNS_ERR_REFUSED
865 ASSERT_LOCKED(req
->base
);
866 ASSERT_VALID_REQUEST(req
);
868 if (flags
& 0x020f || !reply
|| !reply
->have_answer
) {
869 /* there was an error */
870 if (flags
& 0x0200) {
871 error
= DNS_ERR_TRUNCATED
;
872 } else if (flags
& 0x000f) {
873 u16 error_code
= (flags
& 0x000f) - 1;
874 if (error_code
> 4) {
875 error
= DNS_ERR_UNKNOWN
;
877 error
= error_codes
[error_code
];
879 } else if (reply
&& !reply
->have_answer
) {
880 error
= DNS_ERR_NODATA
;
882 error
= DNS_ERR_UNKNOWN
;
886 case DNS_ERR_NOTIMPL
:
887 case DNS_ERR_REFUSED
:
888 /* we regard these errors as marking a bad nameserver */
889 if (req
->reissue_count
< req
->base
->global_max_reissues
) {
891 evutil_snprintf(msg
, sizeof(msg
), "Bad response %d (%s)",
892 error
, evdns_err_to_string(error
));
893 nameserver_failed(req
->ns
, msg
);
894 if (!request_reissue(req
)) return;
897 case DNS_ERR_SERVERFAILED
:
898 /* rcode 2 (servfailed) sometimes means "we
899 * are broken" and sometimes (with some binds)
900 * means "that request was very confusing."
901 * Treat this as a timeout, not a failure.
903 log(EVDNS_LOG_DEBUG
, "Got a SERVERFAILED from nameserver"
904 "at %s; will allow the request to time out.",
905 evutil_format_sockaddr_port(
906 (struct sockaddr
*)&req
->ns
->address
,
907 addrbuf
, sizeof(addrbuf
)));
910 /* we got a good reply from the nameserver: it is up. */
911 if (req
->handle
== req
->ns
->probe_request
) {
912 /* Avoid double-free */
913 req
->ns
->probe_request
= NULL
;
916 nameserver_up(req
->ns
);
919 if (req
->handle
->search_state
&&
920 req
->request_type
!= TYPE_PTR
) {
921 /* if we have a list of domains to search in,
922 * try the next one */
923 if (!search_try_next(req
->handle
)) {
924 /* a new request was issued so this
925 * request is finished and */
926 /* the user callback will be made when
927 * that request (or a */
928 /* child of it) finishes. */
933 /* all else failed. Pass the failure up */
934 reply_schedule_callback(req
, ttl
, error
, NULL
);
935 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
937 /* all ok, tell the user */
938 reply_schedule_callback(req
, ttl
, 0, reply
);
939 if (req
->handle
== req
->ns
->probe_request
)
940 req
->ns
->probe_request
= NULL
; /* Avoid double-free */
941 nameserver_up(req
->ns
);
942 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
947 name_parse(u8
*packet
, int length
, int *idx
, char *name_out
, int name_out_len
) {
951 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (/*CONSTCOND*/0)
952 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (/*CONSTCOND*/0)
953 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (/*CONSTCOND*/0)
956 const char *const end
= name_out
+ name_out_len
;
958 /* Normally, names are a series of length prefixed strings terminated */
959 /* with a length of 0 (the lengths are u8's < 63). */
960 /* However, the length can start with a pair of 1 bits and that */
961 /* means that the next 14 bits are a pointer within the current */
966 if (j
>= length
) return -1;
968 if (!label_len
) break;
969 if (label_len
& 0xc0) {
972 if (name_end
< 0) name_end
= j
;
973 j
= (((int)label_len
& 0x3f) << 8) + ptr_low
;
974 /* Make sure that the target offset is in-bounds. */
975 if (j
< 0 || j
>= length
) return -1;
976 /* If we've jumped more times than there are characters in the
977 * message, we must have a loop. */
978 if (++ptr_count
> length
) return -1;
981 if (label_len
> 63) return -1;
982 if (cp
!= name_out
) {
983 if (cp
+ 1 >= end
) return -1;
986 if (cp
+ label_len
>= end
) return -1;
987 memcpy(cp
, packet
+ j
, label_len
);
991 if (cp
>= end
) return -1;
1002 /* parses a raw request from a nameserver */
1004 reply_parse(struct evdns_base
*base
, u8
*packet
, int length
) {
1005 int j
= 0, k
= 0; /* index into packet */
1006 u16 _t
; /* used by the macros */
1007 u32 _t32
; /* used by the macros */
1008 char tmp_name
[256], cmp_name
[256]; /* used by the macros */
1009 int name_matches
= 0;
1011 u16 trans_id
, questions
, answers
, authority
, additional
, datalength
;
1013 u32 ttl
, ttl_r
= 0xffffffff;
1015 struct request
*req
= NULL
;
1018 ASSERT_LOCKED(base
);
1026 (void) authority
; /* suppress "unused variable" warnings. */
1027 (void) additional
; /* suppress "unused variable" warnings. */
1029 req
= request_find_from_trans_id(base
, trans_id
);
1030 if (!req
) return -1;
1031 EVUTIL_ASSERT(req
->base
== base
);
1033 memset(&reply
, 0, sizeof(reply
));
1035 /* If it's not an answer, it doesn't correspond to any request. */
1036 if (!(flags
& 0x8000)) return -1; /* must be an answer */
1037 if ((flags
& 0x020f) && (flags
& 0x020f) != DNS_ERR_NOTEXIST
) {
1038 /* there was an error and it's not NXDOMAIN */
1041 /* if (!answers) return; */ /* must have an answer of some form */
1043 /* This macro skips a name in the DNS reply. */
1045 do { tmp_name[0] = '\0'; \
1046 if (name_parse(packet, length, &j, tmp_name, \
1047 sizeof(tmp_name))<0) \
1049 } while (/*CONSTCOND*/0)
1051 do { tmp_name[0] = '\0'; \
1052 cmp_name[0] = '\0'; \
1054 if (name_parse(packet, length, &j, tmp_name, \
1055 sizeof(tmp_name))<0) \
1057 if (name_parse(req->request, req->request_len, &k, \
1058 cmp_name, sizeof(cmp_name))<0) \
1060 if (base->global_randomize_case) { \
1061 if (strcmp(tmp_name, cmp_name) == 0) \
1064 if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0) \
1067 } while (/*CONSTCOND*/0)
1069 reply
.type
= req
->request_type
;
1071 /* skip over each question in the reply */
1072 for (i
= 0; i
< questions
; ++i
) {
1073 /* the question looks like
1074 * <label:name><u16:type><u16:class>
1078 if (j
> length
) goto err
;
1084 /* now we have the answer section which looks like
1085 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
1088 for (i
= 0; i
< answers
; ++i
) {
1097 if (type
== TYPE_A
&& class == CLASS_INET
) {
1098 int addrcount
, addrtocopy
;
1099 if (req
->request_type
!= TYPE_A
) {
1100 j
+= datalength
; continue;
1102 if ((datalength
& 3) != 0) /* not an even number of As. */
1104 addrcount
= datalength
>> 2;
1105 addrtocopy
= MIN(MAX_V4_ADDRS
- reply
.data
.a
.addrcount
, (unsigned)addrcount
);
1107 ttl_r
= MIN(ttl_r
, ttl
);
1108 /* we only bother with the first four addresses. */
1109 if (j
+ 4*addrtocopy
> length
) goto err
;
1110 memcpy(&reply
.data
.a
.addresses
[reply
.data
.a
.addrcount
],
1111 packet
+ j
, 4*addrtocopy
);
1113 reply
.data
.a
.addrcount
+= addrtocopy
;
1114 reply
.have_answer
= 1;
1115 if (reply
.data
.a
.addrcount
== MAX_V4_ADDRS
) break;
1116 } else if (type
== TYPE_PTR
&& class == CLASS_INET
) {
1117 if (req
->request_type
!= TYPE_PTR
) {
1118 j
+= datalength
; continue;
1120 if (name_parse(packet
, length
, &j
, reply
.data
.ptr
.name
,
1121 sizeof(reply
.data
.ptr
.name
))<0)
1123 ttl_r
= MIN(ttl_r
, ttl
);
1124 reply
.have_answer
= 1;
1126 } else if (type
== TYPE_CNAME
) {
1127 char cname
[HOST_NAME_MAX
];
1128 if (!req
->put_cname_in_ptr
|| *req
->put_cname_in_ptr
) {
1129 j
+= datalength
; continue;
1131 if (name_parse(packet
, length
, &j
, cname
,
1134 *req
->put_cname_in_ptr
= mm_strdup(cname
);
1135 } else if (type
== TYPE_AAAA
&& class == CLASS_INET
) {
1136 int addrcount
, addrtocopy
;
1137 if (req
->request_type
!= TYPE_AAAA
) {
1138 j
+= datalength
; continue;
1140 if ((datalength
& 15) != 0) /* not an even number of AAAAs. */
1142 addrcount
= datalength
>> 4; /* each address is 16 bytes long */
1143 addrtocopy
= MIN(MAX_V6_ADDRS
- reply
.data
.aaaa
.addrcount
, (unsigned)addrcount
);
1144 ttl_r
= MIN(ttl_r
, ttl
);
1146 /* we only bother with the first four addresses. */
1147 if (j
+ 16*addrtocopy
> length
) goto err
;
1148 memcpy(&reply
.data
.aaaa
.addresses
[reply
.data
.aaaa
.addrcount
],
1149 packet
+ j
, 16*addrtocopy
);
1150 reply
.data
.aaaa
.addrcount
+= addrtocopy
;
1152 reply
.have_answer
= 1;
1153 if (reply
.data
.aaaa
.addrcount
== MAX_V6_ADDRS
) break;
1155 /* skip over any other type of resource */
1160 if (!reply
.have_answer
) {
1161 for (i
= 0; i
< authority
; ++i
) {
1168 if (type
== TYPE_SOA
&& class == CLASS_INET
) {
1169 u32 serial
, refresh
, retry
, expire
, minimum
;
1181 ttl_r
= MIN(ttl_r
, ttl
);
1182 ttl_r
= MIN(ttl_r
, minimum
);
1184 /* skip over any other type of resource */
1190 if (ttl_r
== 0xffffffff)
1193 reply_handle(req
, flags
, ttl_r
, &reply
);
1197 reply_handle(req
, flags
, 0, NULL
);
1201 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1202 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1205 request_parse(u8
*packet
, int length
, struct evdns_server_port
*port
, struct sockaddr
*addr
, ev_socklen_t addrlen
)
1207 int j
= 0; /* index into packet */
1208 u16 _t
; /* used by the macros */
1209 char tmp_name
[256]; /* used by the macros */
1212 u16 trans_id
, flags
, questions
, answers
, authority
, additional
;
1213 struct server_request
*server_req
= NULL
;
1215 ASSERT_LOCKED(port
);
1217 /* Get the header fields */
1228 if (flags
& 0x8000) return -1; /* Must not be an answer. */
1229 flags
&= 0x0110; /* Only RD and CD get preserved. */
1231 server_req
= mm_malloc(sizeof(struct server_request
));
1232 if (server_req
== NULL
) return -1;
1233 memset(server_req
, 0, sizeof(struct server_request
));
1235 server_req
->trans_id
= trans_id
;
1236 memcpy(&server_req
->addr
, addr
, addrlen
);
1237 server_req
->addrlen
= addrlen
;
1239 server_req
->base
.flags
= flags
;
1240 server_req
->base
.nquestions
= 0;
1241 server_req
->base
.questions
= mm_calloc(sizeof(struct evdns_server_question
*), questions
);
1242 if (server_req
->base
.questions
== NULL
)
1245 for (i
= 0; i
< questions
; ++i
) {
1247 struct evdns_server_question
*q
;
1249 if (name_parse(packet
, length
, &j
, tmp_name
, sizeof(tmp_name
))<0)
1253 namelen
= (int)strlen(tmp_name
);
1254 q
= mm_malloc(sizeof(struct evdns_server_question
) + namelen
);
1258 q
->dns_question_class
= class;
1259 memcpy(q
->name
, tmp_name
, namelen
+1);
1260 server_req
->base
.questions
[server_req
->base
.nquestions
++] = q
;
1263 /* Ignore answers, authority, and additional. */
1265 server_req
->port
= port
;
1268 /* Only standard queries are supported. */
1269 if (flags
& 0x7800) {
1270 evdns_server_request_respond(&(server_req
->base
), DNS_ERR_NOTIMPL
);
1274 port
->user_callback(&(server_req
->base
), port
->user_data
);
1279 if (server_req
->base
.questions
) {
1280 for (i
= 0; i
< server_req
->base
.nquestions
; ++i
)
1281 mm_free(server_req
->base
.questions
[i
]);
1282 mm_free(server_req
->base
.questions
);
1284 mm_free(server_req
);
1296 evdns_set_transaction_id_fn(ev_uint16_t (*fn
)(void))
1301 evdns_set_random_bytes_fn(void (*fn
)(char *, size_t))
1305 /* Try to choose a strong transaction id which isn't already in flight */
1307 transaction_id_pick(struct evdns_base
*base
) {
1308 ASSERT_LOCKED(base
);
1311 evutil_secure_rng_get_bytes(&trans_id
, sizeof(trans_id
));
1313 if (trans_id
== 0xffff) continue;
1314 /* now check to see if that id is already inflight */
1315 if (request_find_from_trans_id(base
, trans_id
) == NULL
)
1320 /* choose a namesever to use. This function will try to ignore */
1321 /* nameservers which we think are down and load balance across the rest */
1322 /* by updating the server_head global each time. */
1323 static struct nameserver
*
1324 nameserver_pick(struct evdns_base
*base
) {
1325 struct nameserver
*started_at
= base
->server_head
, *picked
;
1326 ASSERT_LOCKED(base
);
1327 if (!base
->server_head
) return NULL
;
1329 /* if we don't have any good nameservers then there's no */
1330 /* point in trying to find one. */
1331 if (!base
->global_good_nameservers
) {
1332 base
->server_head
= base
->server_head
->next
;
1333 return base
->server_head
;
1336 /* remember that nameservers are in a circular list */
1338 if (base
->server_head
->state
) {
1339 /* we think this server is currently good */
1340 picked
= base
->server_head
;
1341 base
->server_head
= base
->server_head
->next
;
1345 base
->server_head
= base
->server_head
->next
;
1346 if (base
->server_head
== started_at
) {
1347 /* all the nameservers seem to be down */
1348 /* so we just return this one and hope for the */
1350 EVUTIL_ASSERT(base
->global_good_nameservers
== 0);
1351 picked
= base
->server_head
;
1352 base
->server_head
= base
->server_head
->next
;
1358 /* this is called when a namesever socket is ready for reading */
1360 nameserver_read(struct nameserver
*ns
) {
1361 struct sockaddr_storage ss
;
1362 ev_socklen_t addrlen
= sizeof(ss
);
1365 ASSERT_LOCKED(ns
->base
);
1368 const int r
= recvfrom(ns
->socket
, (void*)packet
,
1370 (struct sockaddr
*)&ss
, &addrlen
);
1372 int err
= evutil_socket_geterror(ns
->socket
);
1373 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1375 nameserver_failed(ns
,
1376 evutil_socket_error_to_string(err
));
1379 if (evutil_sockaddr_cmp((struct sockaddr
*)&ss
,
1380 (struct sockaddr
*)&ns
->address
, 0)) {
1381 log(EVDNS_LOG_WARN
, "Address mismatch on received "
1382 "DNS packet. Apparent source was %s",
1383 evutil_format_sockaddr_port(
1384 (struct sockaddr
*)&ss
,
1385 addrbuf
, sizeof(addrbuf
)));
1390 reply_parse(ns
->base
, packet
, r
);
1394 /* Read a packet from a DNS client on a server port s, parse it, and */
1395 /* act accordingly. */
1397 server_port_read(struct evdns_server_port
*s
) {
1399 struct sockaddr_storage addr
;
1400 ev_socklen_t addrlen
;
1405 addrlen
= sizeof(struct sockaddr_storage
);
1406 r
= recvfrom(s
->socket
, (void*)packet
, sizeof(packet
), 0,
1407 (struct sockaddr
*) &addr
, &addrlen
);
1409 int err
= evutil_socket_geterror(s
->socket
);
1410 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1413 "Error %s (%d) while reading request.",
1414 evutil_socket_error_to_string(err
), err
);
1417 request_parse(packet
, r
, s
, (struct sockaddr
*) &addr
, addrlen
);
1421 /* Try to write all pending replies on a given DNS server port. */
1423 server_port_flush(struct evdns_server_port
*port
)
1425 struct server_request
*req
= port
->pending_replies
;
1426 ASSERT_LOCKED(port
);
1428 int r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
1429 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
1431 int err
= evutil_socket_geterror(port
->socket
);
1432 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1434 log(EVDNS_LOG_WARN
, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err
), err
);
1436 if (server_request_free(req
)) {
1437 /* we released the last reference to req->port. */
1440 EVUTIL_ASSERT(req
!= port
->pending_replies
);
1441 req
= port
->pending_replies
;
1445 /* We have no more pending requests; stop listening for 'writeable' events. */
1446 (void) event_del(&port
->event
);
1447 event_assign(&port
->event
, port
->event_base
,
1448 port
->socket
, EV_READ
| EV_PERSIST
,
1449 server_port_ready_callback
, port
);
1451 if (event_add(&port
->event
, NULL
) < 0) {
1452 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server.");
1457 /* set if we are waiting for the ability to write to this server. */
1458 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1459 /* we stop these events. */
1461 nameserver_write_waiting(struct nameserver
*ns
, char waiting
) {
1462 ASSERT_LOCKED(ns
->base
);
1463 if (ns
->write_waiting
== waiting
) return;
1465 ns
->write_waiting
= waiting
;
1466 (void) event_del(&ns
->event
);
1467 event_assign(&ns
->event
, ns
->base
->event_base
,
1468 ns
->socket
, EV_READ
| (waiting
? EV_WRITE
: 0) | EV_PERSIST
,
1469 nameserver_ready_callback
, ns
);
1470 if (event_add(&ns
->event
, NULL
) < 0) {
1472 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for %s",
1473 evutil_format_sockaddr_port(
1474 (struct sockaddr
*)&ns
->address
,
1475 addrbuf
, sizeof(addrbuf
)));
1480 /* a callback function. Called by libevent when the kernel says that */
1481 /* a nameserver socket is ready for writing or reading */
1483 nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1484 struct nameserver
*ns
= (struct nameserver
*) arg
;
1487 EVDNS_LOCK(ns
->base
);
1488 if (events
& EV_WRITE
) {
1490 if (!evdns_transmit(ns
->base
)) {
1491 nameserver_write_waiting(ns
, 0);
1494 if (events
& EV_READ
) {
1495 nameserver_read(ns
);
1497 EVDNS_UNLOCK(ns
->base
);
1500 /* a callback function. Called by libevent when the kernel says that */
1501 /* a server socket is ready for writing or reading. */
1503 server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1504 struct evdns_server_port
*port
= (struct evdns_server_port
*) arg
;
1508 if (events
& EV_WRITE
) {
1510 server_port_flush(port
);
1512 if (events
& EV_READ
) {
1513 server_port_read(port
);
1518 /* This is an inefficient representation; only use it via the dnslabel_table_*
1519 * functions, so that is can be safely replaced with something smarter later. */
1520 #define MAX_LABELS 128
1521 /* Structures used to implement name compression */
1522 struct dnslabel_entry
{ char *v
; off_t pos
; };
1523 struct dnslabel_table
{
1524 int n_labels
; /* number of current entries */
1525 /* map from name to position in message */
1526 struct dnslabel_entry labels
[MAX_LABELS
];
1529 /* Initialize dnslabel_table. */
1531 dnslabel_table_init(struct dnslabel_table
*table
)
1533 table
->n_labels
= 0;
1536 /* Free all storage held by table, but not the table itself. */
1538 dnslabel_clear(struct dnslabel_table
*table
)
1541 for (i
= 0; i
< table
->n_labels
; ++i
)
1542 mm_free(table
->labels
[i
].v
);
1543 table
->n_labels
= 0;
1546 /* return the position of the label in the current message, or -1 if the label */
1547 /* hasn't been used yet. */
1549 dnslabel_table_get_pos(const struct dnslabel_table
*table
, const char *label
)
1552 for (i
= 0; i
< table
->n_labels
; ++i
) {
1553 if (!strcmp(label
, table
->labels
[i
].v
))
1554 return table
->labels
[i
].pos
;
1559 /* remember that we've used the label at position pos */
1561 dnslabel_table_add(struct dnslabel_table
*table
, const char *label
, off_t pos
)
1565 if (table
->n_labels
== MAX_LABELS
)
1567 v
= mm_strdup(label
);
1570 p
= table
->n_labels
++;
1571 table
->labels
[p
].v
= v
;
1572 table
->labels
[p
].pos
= pos
;
1577 /* Converts a string to a length-prefixed set of DNS labels, starting */
1578 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1579 /* of name. table is optional, and is used for compression. */
1581 /* Input: abc.def */
1582 /* Output: <3>abc<3>def<0> */
1584 /* Returns the first index after the encoded name, or negative on error. */
1585 /* -1 label was > 63 bytes */
1586 /* -2 name too long to fit in buffer. */
1589 dnsname_to_labels(u8
*const buf
, size_t buf_len
, off_t j
,
1590 const char *name
, const size_t name_len
,
1591 struct dnslabel_table
*table
) {
1592 const char *end
= name
+ name_len
;
1596 #define APPEND16(x) do { \
1597 if (j + 2 > (off_t)buf_len) \
1600 memcpy(buf + j, &_t, 2); \
1602 } while (/*CONSTCOND*/0)
1603 #define APPEND32(x) do { \
1604 if (j + 4 > (off_t)buf_len) \
1607 memcpy(buf + j, &_t32, 4); \
1609 } while (/*CONSTCOND*/0)
1611 if (name_len
> 255) return -2;
1614 const char *const start
= name
;
1615 if (table
&& (ref
= dnslabel_table_get_pos(table
, name
)) >= 0) {
1616 APPEND16(ref
| 0xc000);
1619 name
= strchr(name
, '.');
1621 const size_t label_len
= end
- start
;
1622 if (label_len
> 63) return -1;
1623 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1624 if (table
) dnslabel_table_add(table
, start
, j
);
1625 buf
[j
++] = (ev_uint8_t
)label_len
;
1627 memcpy(buf
+ j
, start
, label_len
);
1628 j
+= (int) label_len
;
1631 /* append length of the label. */
1632 const size_t label_len
= name
- 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
;
1640 /* hop over the '.' */
1645 /* the labels must be terminated by a 0. */
1646 /* It's possible that the name ended in a . */
1647 /* in which case the zero is already there */
1648 if (!j
|| buf
[j
-1]) buf
[j
++] = 0;
1654 /* Finds the length of a dns request for a DNS name of the given */
1655 /* length. The actual request may be smaller than the value returned */
1658 evdns_request_len(const size_t name_len
) {
1659 return 96 + /* length of the DNS standard header */
1661 4; /* space for the resource type */
1664 /* build a dns request packet into buf. buf should be at least as long */
1665 /* as evdns_request_len told you it should be. */
1667 /* Returns the amount of space used. Negative on error. */
1669 evdns_request_data_build(const char *const name
, const size_t name_len
,
1670 const u16 trans_id
, const u16 type
, const u16
class,
1671 u8
*const buf
, size_t buf_len
) {
1672 off_t j
= 0; /* current offset into buf */
1673 u16 _t
; /* used by the macros */
1676 APPEND16(0x0100); /* standard query, recusion needed */
1677 APPEND16(1); /* one question */
1678 APPEND16(0); /* no answers */
1679 APPEND16(0); /* no authority */
1680 APPEND16(0); /* no additional */
1682 j
= dnsname_to_labels(buf
, buf_len
, j
, name
, name_len
, NULL
);
1695 /* exported function */
1696 struct evdns_server_port
*
1697 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
)
1699 struct evdns_server_port
*port
;
1701 return NULL
; /* flags not yet implemented */
1702 if (!(port
= mm_malloc(sizeof(struct evdns_server_port
))))
1704 memset(port
, 0, sizeof(struct evdns_server_port
));
1707 port
->socket
= socket
;
1711 port
->user_callback
= cb
;
1712 port
->user_data
= user_data
;
1713 port
->pending_replies
= NULL
;
1714 port
->event_base
= base
;
1716 event_assign(&port
->event
, port
->event_base
,
1717 port
->socket
, EV_READ
| EV_PERSIST
,
1718 server_port_ready_callback
, port
);
1719 if (event_add(&port
->event
, NULL
) < 0) {
1723 EVTHREAD_ALLOC_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
1727 struct evdns_server_port
*
1728 evdns_add_server_port(evutil_socket_t socket
, int flags
, evdns_request_callback_fn_type cb
, void *user_data
)
1730 return evdns_add_server_port_with_base(NULL
, socket
, flags
, cb
, user_data
);
1733 /* exported function */
1735 evdns_close_server_port(struct evdns_server_port
*port
)
1738 if (--port
->refcnt
== 0) {
1740 server_port_free(port
);
1746 /* exported function */
1748 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
)
1750 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1751 struct server_reply_item
**itemp
, *item
;
1755 EVDNS_LOCK(req
->port
);
1756 if (req
->response
) /* have we already answered? */
1760 case EVDNS_ANSWER_SECTION
:
1761 itemp
= &req
->answer
;
1762 countp
= &req
->n_answer
;
1764 case EVDNS_AUTHORITY_SECTION
:
1765 itemp
= &req
->authority
;
1766 countp
= &req
->n_authority
;
1768 case EVDNS_ADDITIONAL_SECTION
:
1769 itemp
= &req
->additional
;
1770 countp
= &req
->n_additional
;
1776 itemp
= &((*itemp
)->next
);
1778 item
= mm_malloc(sizeof(struct server_reply_item
));
1782 if (!(item
->name
= mm_strdup(name
))) {
1787 item
->dns_question_class
= class;
1789 item
->is_name
= is_name
!= 0;
1793 if (item
->is_name
) {
1794 if (!(item
->data
= mm_strdup(data
))) {
1795 mm_free(item
->name
);
1799 item
->datalen
= (u16
)-1;
1801 if (!(item
->data
= mm_malloc(datalen
))) {
1802 mm_free(item
->name
);
1806 item
->datalen
= datalen
;
1807 memcpy(item
->data
, data
, datalen
);
1815 EVDNS_UNLOCK(req
->port
);
1819 /* exported function */
1821 evdns_server_request_add_a_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1823 return evdns_server_request_add_reply(
1824 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_A
, CLASS_INET
,
1825 ttl
, n
*4, 0, addrs
);
1828 /* exported function */
1830 evdns_server_request_add_aaaa_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1832 return evdns_server_request_add_reply(
1833 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_AAAA
, CLASS_INET
,
1834 ttl
, n
*16, 0, addrs
);
1837 /* exported function */
1839 evdns_server_request_add_ptr_reply(struct evdns_server_request
*req
, struct in_addr
*in
, const char *inaddr_name
, const char *hostname
, int ttl
)
1843 if (in
&& inaddr_name
)
1845 else if (!in
&& !inaddr_name
)
1848 a
= ntohl(in
->s_addr
);
1849 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
1850 (int)(u8
)((a
)&0xff),
1851 (int)(u8
)((a
>>8 )&0xff),
1852 (int)(u8
)((a
>>16)&0xff),
1853 (int)(u8
)((a
>>24)&0xff));
1856 return evdns_server_request_add_reply(
1857 req
, EVDNS_ANSWER_SECTION
, inaddr_name
, TYPE_PTR
, CLASS_INET
,
1858 ttl
, -1, 1, hostname
);
1861 /* exported function */
1863 evdns_server_request_add_cname_reply(struct evdns_server_request
*req
, const char *name
, const char *cname
, int ttl
)
1865 return evdns_server_request_add_reply(
1866 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_CNAME
, CLASS_INET
,
1870 /* exported function */
1872 evdns_server_request_set_flags(struct evdns_server_request
*exreq
, int flags
)
1874 struct server_request
*req
= TO_SERVER_REQUEST(exreq
);
1875 req
->base
.flags
&= ~(EVDNS_FLAGS_AA
|EVDNS_FLAGS_RD
);
1876 req
->base
.flags
|= flags
;
1880 evdns_server_request_format_response(struct server_request
*req
, int err
)
1882 unsigned char buf
[1500];
1883 size_t buf_len
= sizeof(buf
);
1889 struct dnslabel_table table
;
1891 if (err
< 0 || err
> 15) return -1;
1893 /* Set response bit and error code; copy OPCODE and RD fields from
1894 * question; copy RA and AA if set by caller. */
1895 flags
= req
->base
.flags
;
1896 flags
|= (0x8000 | err
);
1898 dnslabel_table_init(&table
);
1899 APPEND16(req
->trans_id
);
1901 APPEND16(req
->base
.nquestions
);
1902 APPEND16(req
->n_answer
);
1903 APPEND16(req
->n_authority
);
1904 APPEND16(req
->n_additional
);
1906 /* Add questions. */
1907 for (i
=0; i
< req
->base
.nquestions
; ++i
) {
1908 const char *s
= req
->base
.questions
[i
]->name
;
1909 j
= dnsname_to_labels(buf
, buf_len
, j
, s
, strlen(s
), &table
);
1911 dnslabel_clear(&table
);
1914 APPEND16(req
->base
.questions
[i
]->type
);
1915 APPEND16(req
->base
.questions
[i
]->dns_question_class
);
1918 /* Add answer, authority, and additional sections. */
1919 for (i
=0; i
<3; ++i
) {
1920 struct server_reply_item
*item
;
1924 item
= req
->authority
;
1926 item
= req
->additional
;
1928 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->name
, strlen(item
->name
), &table
);
1933 APPEND16(item
->type
);
1934 APPEND16(item
->dns_question_class
);
1935 APPEND32(item
->ttl
);
1936 if (item
->is_name
) {
1937 off_t len_idx
= j
, name_start
;
1940 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->data
, strlen(item
->data
), &table
);
1944 _t
= htons( (short) (j
-name_start
) );
1945 memcpy(buf
+len_idx
, &_t
, 2);
1947 APPEND16(item
->datalen
);
1948 if (j
+item
->datalen
> (off_t
)buf_len
)
1950 memcpy(buf
+j
, item
->data
, item
->datalen
);
1960 buf
[2] |= 0x02; /* set the truncated bit. */
1963 req
->response_len
= j
;
1965 if (!(req
->response
= mm_malloc(req
->response_len
))) {
1966 server_request_free_answers(req
);
1967 dnslabel_clear(&table
);
1970 memcpy(req
->response
, buf
, req
->response_len
);
1971 server_request_free_answers(req
);
1972 dnslabel_clear(&table
);
1976 /* exported function */
1978 evdns_server_request_respond(struct evdns_server_request
*_req
, int err
)
1980 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1981 struct evdns_server_port
*port
= req
->port
;
1985 if (!req
->response
) {
1986 if ((r
= evdns_server_request_format_response(req
, err
))<0)
1990 r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
1991 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
1993 int sock_err
= evutil_socket_geterror(port
->socket
);
1994 if (EVUTIL_ERR_RW_RETRIABLE(sock_err
))
1997 if (port
->pending_replies
) {
1998 req
->prev_pending
= port
->pending_replies
->prev_pending
;
1999 req
->next_pending
= port
->pending_replies
;
2000 req
->prev_pending
->next_pending
=
2001 req
->next_pending
->prev_pending
= req
;
2003 req
->prev_pending
= req
->next_pending
= req
;
2004 port
->pending_replies
= req
;
2007 (void) event_del(&port
->event
);
2008 event_assign(&port
->event
, port
->event_base
, port
->socket
, (port
->closing
?0:EV_READ
) | EV_WRITE
| EV_PERSIST
, server_port_ready_callback
, port
);
2010 if (event_add(&port
->event
, NULL
) < 0) {
2011 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server");
2019 if (server_request_free(req
)) {
2024 if (port
->pending_replies
)
2025 server_port_flush(port
);
2033 /* Free all storage held by RRs in req. */
2035 server_request_free_answers(struct server_request
*req
)
2037 struct server_reply_item
*victim
, *next
, **list
;
2039 for (i
= 0; i
< 3; ++i
) {
2041 list
= &req
->answer
;
2043 list
= &req
->authority
;
2045 list
= &req
->additional
;
2049 next
= victim
->next
;
2050 mm_free(victim
->name
);
2052 mm_free(victim
->data
);
2060 /* Free all storage held by req, and remove links to it. */
2061 /* return true iff we just wound up freeing the server_port. */
2063 server_request_free(struct server_request
*req
)
2065 int i
, rc
=1, lock
=0;
2066 if (req
->base
.questions
) {
2067 for (i
= 0; i
< req
->base
.nquestions
; ++i
)
2068 mm_free(req
->base
.questions
[i
]);
2069 mm_free(req
->base
.questions
);
2073 EVDNS_LOCK(req
->port
);
2075 if (req
->port
->pending_replies
== req
) {
2076 if (req
->next_pending
&& req
->next_pending
!= req
)
2077 req
->port
->pending_replies
= req
->next_pending
;
2079 req
->port
->pending_replies
= NULL
;
2081 rc
= --req
->port
->refcnt
;
2084 if (req
->response
) {
2085 mm_free(req
->response
);
2088 server_request_free_answers(req
);
2090 if (req
->next_pending
&& req
->next_pending
!= req
) {
2091 req
->next_pending
->prev_pending
= req
->prev_pending
;
2092 req
->prev_pending
->next_pending
= req
->next_pending
;
2096 EVDNS_UNLOCK(req
->port
); /* ????? nickm */
2097 server_port_free(req
->port
);
2102 EVDNS_UNLOCK(req
->port
);
2107 /* Free all storage held by an evdns_server_port. Only called when */
2109 server_port_free(struct evdns_server_port
*port
)
2111 EVUTIL_ASSERT(port
);
2112 EVUTIL_ASSERT(!port
->refcnt
);
2113 EVUTIL_ASSERT(!port
->pending_replies
);
2114 if (port
->socket
> 0) {
2115 evutil_closesocket(port
->socket
);
2118 (void) event_del(&port
->event
);
2119 event_debug_unassign(&port
->event
);
2120 EVTHREAD_FREE_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
2124 /* exported function */
2126 evdns_server_request_drop(struct evdns_server_request
*_req
)
2128 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2129 server_request_free(req
);
2133 /* exported function */
2135 evdns_server_request_get_requesting_addr(struct evdns_server_request
*_req
, struct sockaddr
*sa
, int addr_len
)
2137 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2138 if (addr_len
< (int)req
->addrlen
)
2140 memcpy(sa
, &(req
->addr
), req
->addrlen
);
2141 return req
->addrlen
;
2147 /* this is a libevent callback function which is called when a request */
2148 /* has timed out. */
2150 evdns_request_timeout_callback(evutil_socket_t fd
, short events
, void *arg
) {
2151 struct request
*const req
= (struct request
*) arg
;
2152 struct evdns_base
*base
= req
->base
;
2157 log(EVDNS_LOG_DEBUG
, "Request %p timed out", arg
);
2160 req
->ns
->timedout
++;
2161 if (req
->ns
->timedout
> req
->base
->global_max_nameserver_timeout
) {
2162 req
->ns
->timedout
= 0;
2163 nameserver_failed(req
->ns
, "request timed out.");
2166 if (req
->tx_count
>= req
->base
->global_max_retransmits
) {
2167 /* this request has failed */
2168 log(EVDNS_LOG_DEBUG
, "Giving up on request %p; tx_count==%d",
2169 arg
, req
->tx_count
);
2170 reply_schedule_callback(req
, 0, DNS_ERR_TIMEOUT
, NULL
);
2171 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
2174 struct nameserver
*new_ns
;
2175 log(EVDNS_LOG_DEBUG
, "Retransmitting request %p; tx_count==%d",
2176 arg
, req
->tx_count
);
2177 (void) evtimer_del(&req
->timeout_event
);
2178 new_ns
= nameserver_pick(base
);
2181 evdns_request_transmit(req
);
2186 /* try to send a request to a given server. */
2190 /* 1 temporary failure */
2191 /* 2 other failure */
2193 evdns_request_transmit_to(struct request
*req
, struct nameserver
*server
) {
2195 ASSERT_LOCKED(req
->base
);
2196 ASSERT_VALID_REQUEST(req
);
2197 r
= sendto(server
->socket
, (void*)req
->request
, req
->request_len
, 0,
2198 (struct sockaddr
*)&server
->address
, server
->addrlen
);
2200 int err
= evutil_socket_geterror(server
->socket
);
2201 if (EVUTIL_ERR_RW_RETRIABLE(err
))
2203 nameserver_failed(req
->ns
, evutil_socket_error_to_string(err
));
2205 } else if (r
!= (int)req
->request_len
) {
2206 return 1; /* short write */
2212 /* try to send a request, updating the fields of the request */
2219 evdns_request_transmit(struct request
*req
) {
2222 ASSERT_LOCKED(req
->base
);
2223 ASSERT_VALID_REQUEST(req
);
2224 /* if we fail to send this packet then this flag marks it */
2225 /* for evdns_transmit */
2226 req
->transmit_me
= 1;
2227 EVUTIL_ASSERT(req
->trans_id
!= 0xffff);
2231 /* unable to transmit request if no nameservers */
2235 if (req
->ns
->choked
) {
2236 /* don't bother trying to write to a socket */
2237 /* which we have had EAGAIN from */
2241 r
= evdns_request_transmit_to(req
, req
->ns
);
2245 req
->ns
->choked
= 1;
2246 nameserver_write_waiting(req
->ns
, 1);
2249 /* failed to transmit the request entirely. */
2251 /* fall through: we'll set a timeout, which will time out,
2252 * and make us retransmit the request anyway. */
2255 log(EVDNS_LOG_DEBUG
,
2256 "Setting timeout for request %p, sent to nameserver %p", req
, req
->ns
);
2257 if (evtimer_add(&req
->timeout_event
, &req
->base
->global_timeout
) < 0) {
2259 "Error from libevent when adding timer for request %p",
2264 req
->transmit_me
= 0;
2270 nameserver_probe_callback(int result
, char type
, int count
, int ttl
, void *addresses
, void *arg
) {
2271 struct nameserver
*const ns
= (struct nameserver
*) arg
;
2277 if (result
== DNS_ERR_CANCEL
) {
2278 /* We canceled this request because the nameserver came up
2279 * for some other reason. Do not change our opinion about
2280 * the nameserver. */
2284 EVDNS_LOCK(ns
->base
);
2285 ns
->probe_request
= NULL
;
2286 if (result
== DNS_ERR_NONE
|| result
== DNS_ERR_NOTEXIST
) {
2287 /* this is a good reply */
2290 nameserver_probe_failed(ns
);
2292 EVDNS_UNLOCK(ns
->base
);
2296 nameserver_send_probe(struct nameserver
*const ns
) {
2297 struct evdns_request
*handle
;
2298 struct request
*req
;
2300 /* here we need to send a probe to a given nameserver */
2301 /* in the hope that it is up now. */
2303 ASSERT_LOCKED(ns
->base
);
2304 log(EVDNS_LOG_DEBUG
, "Sending probe to %s",
2305 evutil_format_sockaddr_port(
2306 (struct sockaddr
*)&ns
->address
,
2307 addrbuf
, sizeof(addrbuf
)));
2308 handle
= mm_calloc(1, sizeof(*handle
));
2309 if (!handle
) return;
2310 req
= request_new(ns
->base
, handle
, TYPE_A
, "google.com", DNS_QUERY_NO_SEARCH
, nameserver_probe_callback
, ns
);
2315 ns
->probe_request
= handle
;
2316 /* we force this into the inflight queue no matter what */
2317 request_trans_id_set(req
, transaction_id_pick(ns
->base
));
2319 request_submit(req
);
2323 /* 0 didn't try to transmit anything */
2324 /* 1 tried to transmit something */
2326 evdns_transmit(struct evdns_base
*base
) {
2327 char did_try_to_transmit
= 0;
2330 ASSERT_LOCKED(base
);
2331 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2332 if (base
->req_heads
[i
]) {
2333 struct request
*const started_at
= base
->req_heads
[i
], *req
= started_at
;
2334 /* first transmit all the requests which are currently waiting */
2336 if (req
->transmit_me
) {
2337 did_try_to_transmit
= 1;
2338 evdns_request_transmit(req
);
2342 } while (req
!= started_at
);
2346 return did_try_to_transmit
;
2349 /* exported function */
2351 evdns_base_count_nameservers(struct evdns_base
*base
)
2353 const struct nameserver
*server
;
2357 server
= base
->server_head
;
2362 server
= server
->next
;
2363 } while (server
!= base
->server_head
);
2370 evdns_count_nameservers(void)
2372 return evdns_base_count_nameservers(current_base
);
2375 /* exported function */
2377 evdns_base_clear_nameservers_and_suspend(struct evdns_base
*base
)
2379 struct nameserver
*server
, *started_at
;
2383 server
= base
->server_head
;
2384 started_at
= base
->server_head
;
2390 struct nameserver
*next
= server
->next
;
2391 (void) event_del(&server
->event
);
2392 if (evtimer_initialized(&server
->timeout_event
))
2393 (void) evtimer_del(&server
->timeout_event
);
2394 if (server
->probe_request
) {
2395 evdns_cancel_request(server
->base
, server
->probe_request
);
2396 server
->probe_request
= NULL
;
2398 if (server
->socket
>= 0)
2399 evutil_closesocket(server
->socket
);
2401 if (next
== started_at
)
2405 base
->server_head
= NULL
;
2406 base
->global_good_nameservers
= 0;
2408 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2409 struct request
*req
, *req_started_at
;
2410 req
= req_started_at
= base
->req_heads
[i
];
2412 struct request
*next
= req
->next
;
2413 req
->tx_count
= req
->reissue_count
= 0;
2415 /* ???? What to do about searches? */
2416 (void) evtimer_del(&req
->timeout_event
);
2418 req
->transmit_me
= 0;
2420 base
->global_requests_waiting
++;
2421 evdns_request_insert(req
, &base
->req_waiting_head
);
2422 /* We want to insert these suspended elements at the front of
2423 * the waiting queue, since they were pending before any of
2424 * the waiting entries were added. This is a circular list,
2425 * so we can just shift the start back by one.*/
2426 base
->req_waiting_head
= base
->req_waiting_head
->prev
;
2428 if (next
== req_started_at
)
2432 base
->req_heads
[i
] = NULL
;
2435 base
->global_requests_inflight
= 0;
2442 evdns_clear_nameservers_and_suspend(void)
2444 return evdns_base_clear_nameservers_and_suspend(current_base
);
2448 /* exported function */
2450 evdns_base_resume(struct evdns_base
*base
)
2453 evdns_requests_pump_waiting_queue(base
);
2462 return evdns_base_resume(current_base
);
2466 _evdns_nameserver_add_impl(struct evdns_base
*base
, const struct sockaddr
*address
, int addrlen
) {
2467 /* first check to see if we already have this nameserver */
2469 const struct nameserver
*server
= base
->server_head
, *const started_at
= base
->server_head
;
2470 struct nameserver
*ns
;
2474 ASSERT_LOCKED(base
);
2477 if (!evutil_sockaddr_cmp((const struct sockaddr
*)&server
->address
, address
, 1)) return 3;
2478 server
= server
->next
;
2479 } while (server
!= started_at
);
2481 if (addrlen
> (int)sizeof(ns
->address
)) {
2482 log(EVDNS_LOG_DEBUG
, "Addrlen %d too long.", (int)addrlen
);
2486 ns
= (struct nameserver
*) mm_malloc(sizeof(struct nameserver
));
2489 memset(ns
, 0, sizeof(struct nameserver
));
2492 evtimer_assign(&ns
->timeout_event
, ns
->base
->event_base
, nameserver_prod_callback
, ns
);
2494 ns
->socket
= socket(address
->sa_family
, SOCK_DGRAM
, 0);
2495 if (ns
->socket
< 0) { err
= 1; goto out1
; }
2496 evutil_make_socket_closeonexec(ns
->socket
);
2497 evutil_make_socket_nonblocking(ns
->socket
);
2499 if (base
->global_outgoing_addrlen
&&
2500 !evutil_sockaddr_is_loopback(address
)) {
2501 if (bind(ns
->socket
,
2502 (struct sockaddr
*)&base
->global_outgoing_address
,
2503 base
->global_outgoing_addrlen
) < 0) {
2504 log(EVDNS_LOG_WARN
,"Couldn't bind to outgoing address");
2510 memcpy(&ns
->address
, address
, addrlen
);
2511 ns
->addrlen
= addrlen
;
2513 event_assign(&ns
->event
, ns
->base
->event_base
, ns
->socket
, EV_READ
| EV_PERSIST
, nameserver_ready_callback
, ns
);
2514 if (event_add(&ns
->event
, NULL
) < 0) {
2519 log(EVDNS_LOG_DEBUG
, "Added nameserver %s as %p",
2520 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)), ns
);
2522 /* insert this nameserver into the list of them */
2523 if (!base
->server_head
) {
2524 ns
->next
= ns
->prev
= ns
;
2525 base
->server_head
= ns
;
2527 ns
->next
= base
->server_head
->next
;
2528 ns
->prev
= base
->server_head
;
2529 base
->server_head
->next
= ns
;
2530 ns
->next
->prev
= ns
;
2533 base
->global_good_nameservers
++;
2538 evutil_closesocket(ns
->socket
);
2540 event_debug_unassign(&ns
->event
);
2542 log(EVDNS_LOG_WARN
, "Unable to add nameserver %s: error %d",
2543 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)), err
);
2547 /* exported function */
2549 evdns_base_nameserver_add(struct evdns_base
*base
, unsigned long int address
)
2551 struct sockaddr_in sin
;
2553 memset(&sin
, 0, sizeof(sin
));
2554 sin
.sin_addr
.s_addr
= address
;
2555 sin
.sin_port
= htons(53);
2556 sin
.sin_family
= AF_INET
;
2558 res
= _evdns_nameserver_add_impl(base
, (struct sockaddr
*)&sin
, sizeof(sin
));
2564 evdns_nameserver_add(unsigned long int address
) {
2566 current_base
= evdns_base_new(NULL
, 0);
2567 return evdns_base_nameserver_add(current_base
, address
);
2571 sockaddr_setport(struct sockaddr
*sa
, ev_uint16_t port
)
2573 if (sa
->sa_family
== AF_INET
) {
2574 ((struct sockaddr_in
*)sa
)->sin_port
= htons(port
);
2575 } else if (sa
->sa_family
== AF_INET6
) {
2576 ((struct sockaddr_in6
*)sa
)->sin6_port
= htons(port
);
2581 sockaddr_getport(struct sockaddr
*sa
)
2583 if (sa
->sa_family
== AF_INET
) {
2584 return ntohs(((struct sockaddr_in
*)sa
)->sin_port
);
2585 } else if (sa
->sa_family
== AF_INET6
) {
2586 return ntohs(((struct sockaddr_in6
*)sa
)->sin6_port
);
2592 /* exported function */
2594 evdns_base_nameserver_ip_add(struct evdns_base
*base
, const char *ip_as_string
) {
2595 struct sockaddr_storage ss
;
2596 struct sockaddr
*sa
;
2597 int len
= sizeof(ss
);
2599 if (evutil_parse_sockaddr_port(ip_as_string
, (struct sockaddr
*)&ss
,
2601 log(EVDNS_LOG_WARN
, "Unable to parse nameserver address %s",
2605 sa
= (struct sockaddr
*) &ss
;
2606 if (sockaddr_getport(sa
) == 0)
2607 sockaddr_setport(sa
, 53);
2610 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2616 evdns_nameserver_ip_add(const char *ip_as_string
) {
2618 current_base
= evdns_base_new(NULL
, 0);
2619 return evdns_base_nameserver_ip_add(current_base
, ip_as_string
);
2623 evdns_base_nameserver_sockaddr_add(struct evdns_base
*base
,
2624 const struct sockaddr
*sa
, ev_socklen_t len
, unsigned flags
)
2627 EVUTIL_ASSERT(base
);
2629 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2634 /* remove from the queue */
2636 evdns_request_remove(struct request
*req
, struct request
**head
)
2638 ASSERT_LOCKED(req
->base
);
2639 ASSERT_VALID_REQUEST(req
);
2643 struct request
*ptr
;
2645 EVUTIL_ASSERT(*head
!= NULL
);
2654 } while (ptr
!= *head
);
2655 EVUTIL_ASSERT(found
);
2657 EVUTIL_ASSERT(req
->next
);
2661 if (req
->next
== req
) {
2662 /* only item in the list */
2665 req
->next
->prev
= req
->prev
;
2666 req
->prev
->next
= req
->next
;
2667 if (*head
== req
) *head
= req
->next
;
2669 req
->next
= req
->prev
= NULL
;
2672 /* insert into the tail of the queue */
2674 evdns_request_insert(struct request
*req
, struct request
**head
) {
2675 ASSERT_LOCKED(req
->base
);
2676 ASSERT_VALID_REQUEST(req
);
2679 req
->next
= req
->prev
= req
;
2683 req
->prev
= (*head
)->prev
;
2684 req
->prev
->next
= req
;
2686 (*head
)->prev
= req
;
2690 string_num_dots(const char *s
) {
2692 while ((s
= strchr(s
, '.'))) {
2699 static struct request
*
2700 request_new(struct evdns_base
*base
, struct evdns_request
*handle
, int type
,
2701 const char *name
, int flags
, evdns_callback_type callback
,
2704 const char issuing_now
=
2705 (base
->global_requests_inflight
< base
->global_max_requests_inflight
) ? 1 : 0;
2707 const size_t name_len
= strlen(name
);
2708 const size_t request_max_len
= evdns_request_len(name_len
);
2709 const u16 trans_id
= issuing_now
? transaction_id_pick(base
) : 0xffff;
2710 /* the request data is alloced in a single block with the header */
2711 struct request
*const req
=
2712 mm_malloc(sizeof(struct request
) + request_max_len
);
2717 ASSERT_LOCKED(base
);
2719 if (!req
) return NULL
;
2721 if (name_len
>= sizeof(namebuf
)) {
2726 memset(req
, 0, sizeof(struct request
));
2729 evtimer_assign(&req
->timeout_event
, req
->base
->event_base
, evdns_request_timeout_callback
, req
);
2731 if (base
->global_randomize_case
) {
2733 char randbits
[(sizeof(namebuf
)+7)/8];
2734 strlcpy(namebuf
, name
, sizeof(namebuf
));
2735 evutil_secure_rng_get_bytes(randbits
, (name_len
+7)/8);
2736 for (i
= 0; i
< name_len
; ++i
) {
2737 if (EVUTIL_ISALPHA(namebuf
[i
])) {
2738 if ((randbits
[i
>> 3] & (1<<(i
& 7))))
2741 namebuf
[i
] &= ~0x20;
2747 /* request data lives just after the header */
2748 req
->request
= ((u8
*) req
) + sizeof(struct request
);
2749 /* denotes that the request data shouldn't be free()ed */
2750 req
->request_appended
= 1;
2751 rlen
= evdns_request_data_build(name
, name_len
, trans_id
,
2752 type
, CLASS_INET
, req
->request
, request_max_len
);
2756 req
->request_len
= rlen
;
2757 req
->trans_id
= trans_id
;
2759 req
->request_type
= type
;
2760 req
->user_pointer
= user_ptr
;
2761 req
->user_callback
= callback
;
2762 req
->ns
= issuing_now
? nameserver_pick(base
) : NULL
;
2763 req
->next
= req
->prev
= NULL
;
2764 req
->handle
= handle
;
2766 handle
->current_req
= req
;
2767 handle
->base
= base
;
2777 request_submit(struct request
*const req
) {
2778 struct evdns_base
*base
= req
->base
;
2779 ASSERT_LOCKED(base
);
2780 ASSERT_VALID_REQUEST(req
);
2782 /* if it has a nameserver assigned then this is going */
2783 /* straight into the inflight queue */
2784 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
2785 base
->global_requests_inflight
++;
2786 evdns_request_transmit(req
);
2788 evdns_request_insert(req
, &base
->req_waiting_head
);
2789 base
->global_requests_waiting
++;
2793 /* exported function */
2795 evdns_cancel_request(struct evdns_base
*base
, struct evdns_request
*handle
)
2797 struct request
*req
;
2799 if (!handle
->current_req
)
2803 /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
2804 base
= handle
->base
;
2806 base
= handle
->current_req
->base
;
2810 if (handle
->pending_cb
) {
2815 req
= handle
->current_req
;
2816 ASSERT_VALID_REQUEST(req
);
2818 reply_schedule_callback(req
, 0, DNS_ERR_CANCEL
, NULL
);
2820 /* remove from inflight queue */
2821 request_finished(req
, &REQ_HEAD(base
, req
->trans_id
), 1);
2823 /* remove from global_waiting head */
2824 request_finished(req
, &base
->req_waiting_head
, 1);
2829 /* exported function */
2830 struct evdns_request
*
2831 evdns_base_resolve_ipv4(struct evdns_base
*base
, const char *name
, int flags
,
2832 evdns_callback_type callback
, void *ptr
) {
2833 struct evdns_request
*handle
;
2834 struct request
*req
;
2835 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2836 handle
= mm_calloc(1, sizeof(*handle
));
2840 if (flags
& DNS_QUERY_NO_SEARCH
) {
2842 request_new(base
, handle
, TYPE_A
, name
, flags
,
2845 request_submit(req
);
2847 search_request_new(base
, handle
, TYPE_A
, name
, flags
,
2850 if (handle
->current_req
== NULL
) {
2858 int evdns_resolve_ipv4(const char *name
, int flags
,
2859 evdns_callback_type callback
, void *ptr
)
2861 return evdns_base_resolve_ipv4(current_base
, name
, flags
, callback
, ptr
)
2866 /* exported function */
2867 struct evdns_request
*
2868 evdns_base_resolve_ipv6(struct evdns_base
*base
,
2869 const char *name
, int flags
,
2870 evdns_callback_type callback
, void *ptr
)
2872 struct evdns_request
*handle
;
2873 struct request
*req
;
2874 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2875 handle
= mm_calloc(1, sizeof(*handle
));
2879 if (flags
& DNS_QUERY_NO_SEARCH
) {
2880 req
= request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2883 request_submit(req
);
2885 search_request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2888 if (handle
->current_req
== NULL
) {
2896 int evdns_resolve_ipv6(const char *name
, int flags
,
2897 evdns_callback_type callback
, void *ptr
) {
2898 return evdns_base_resolve_ipv6(current_base
, name
, flags
, callback
, ptr
)
2902 struct evdns_request
*
2903 evdns_base_resolve_reverse(struct evdns_base
*base
, const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2905 struct evdns_request
*handle
;
2906 struct request
*req
;
2909 a
= ntohl(in
->s_addr
);
2910 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
2911 (int)(u8
)((a
)&0xff),
2912 (int)(u8
)((a
>>8 )&0xff),
2913 (int)(u8
)((a
>>16)&0xff),
2914 (int)(u8
)((a
>>24)&0xff));
2915 handle
= mm_calloc(1, sizeof(*handle
));
2918 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2920 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2922 request_submit(req
);
2923 if (handle
->current_req
== NULL
) {
2931 int evdns_resolve_reverse(const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2932 return evdns_base_resolve_reverse(current_base
, in
, flags
, callback
, ptr
)
2936 struct evdns_request
*
2937 evdns_base_resolve_reverse_ipv6(struct evdns_base
*base
, const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2938 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2941 struct evdns_request
*handle
;
2942 struct request
*req
;
2946 for (i
=15; i
>= 0; --i
) {
2947 u8 byte
= in
->s6_addr
[i
];
2948 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
2950 *cp
++ = "0123456789abcdef"[byte
>> 4];
2953 EVUTIL_ASSERT(cp
+ strlen("ip6.arpa") < buf
+sizeof(buf
));
2954 memcpy(cp
, "ip6.arpa", strlen("ip6.arpa")+1);
2955 handle
= mm_calloc(1, sizeof(*handle
));
2958 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2960 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2962 request_submit(req
);
2963 if (handle
->current_req
== NULL
) {
2971 int evdns_resolve_reverse_ipv6(const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2972 return evdns_base_resolve_reverse_ipv6(current_base
, in
, flags
, callback
, ptr
)
2976 /* ================================================================= */
2977 /* Search support */
2979 /* the libc resolver has support for searching a number of domains */
2980 /* to find a name. If nothing else then it takes the single domain */
2981 /* from the gethostname() call. */
2983 /* It can also be configured via the domain and search options in a */
2986 /* The ndots option controls how many dots it takes for the resolver */
2987 /* to decide that a name is non-local and so try a raw lookup first. */
2989 struct search_domain
{
2991 struct search_domain
*next
;
2992 /* the text string is appended to this structure */
2995 struct search_state
{
2999 struct search_domain
*head
;
3003 search_state_decref(struct search_state
*const state
) {
3006 if (!state
->refcount
) {
3007 struct search_domain
*next
, *dom
;
3008 for (dom
= state
->head
; dom
; dom
= next
) {
3016 static struct search_state
*
3017 search_state_new(void) {
3018 struct search_state
*state
= (struct search_state
*) mm_malloc(sizeof(struct search_state
));
3019 if (!state
) return NULL
;
3020 memset(state
, 0, sizeof(struct search_state
));
3021 state
->refcount
= 1;
3028 search_postfix_clear(struct evdns_base
*base
) {
3029 search_state_decref(base
->global_search_state
);
3031 base
->global_search_state
= search_state_new();
3034 /* exported function */
3036 evdns_base_search_clear(struct evdns_base
*base
)
3039 search_postfix_clear(base
);
3044 evdns_search_clear(void) {
3045 evdns_base_search_clear(current_base
);
3049 search_postfix_add(struct evdns_base
*base
, const char *domain
) {
3051 struct search_domain
*sdomain
;
3052 while (domain
[0] == '.') domain
++;
3053 domain_len
= strlen(domain
);
3055 ASSERT_LOCKED(base
);
3056 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3057 if (!base
->global_search_state
) return;
3058 base
->global_search_state
->num_domains
++;
3060 sdomain
= (struct search_domain
*) mm_malloc(sizeof(struct search_domain
) + domain_len
);
3061 if (!sdomain
) return;
3062 memcpy( ((u8
*) sdomain
) + sizeof(struct search_domain
), domain
, domain_len
);
3063 sdomain
->next
= base
->global_search_state
->head
;
3064 sdomain
->len
= (int) domain_len
;
3066 base
->global_search_state
->head
= sdomain
;
3069 /* reverse the order of members in the postfix list. This is needed because, */
3070 /* when parsing resolv.conf we push elements in the wrong order */
3072 search_reverse(struct evdns_base
*base
) {
3073 struct search_domain
*cur
, *prev
= NULL
, *next
;
3074 ASSERT_LOCKED(base
);
3075 cur
= base
->global_search_state
->head
;
3083 base
->global_search_state
->head
= prev
;
3086 /* exported function */
3088 evdns_base_search_add(struct evdns_base
*base
, const char *domain
) {
3090 search_postfix_add(base
, domain
);
3094 evdns_search_add(const char *domain
) {
3095 evdns_base_search_add(current_base
, domain
);
3098 /* exported function */
3100 evdns_base_search_ndots_set(struct evdns_base
*base
, const int ndots
) {
3102 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3103 if (base
->global_search_state
)
3104 base
->global_search_state
->ndots
= ndots
;
3108 evdns_search_ndots_set(const int ndots
) {
3109 evdns_base_search_ndots_set(current_base
, ndots
);
3113 search_set_from_hostname(struct evdns_base
*base
) {
3114 char hostname
[HOST_NAME_MAX
+ 1], *domainname
;
3116 ASSERT_LOCKED(base
);
3117 search_postfix_clear(base
);
3118 if (gethostname(hostname
, sizeof(hostname
))) return;
3119 domainname
= strchr(hostname
, '.');
3120 if (!domainname
) return;
3121 search_postfix_add(base
, domainname
);
3124 /* warning: returns malloced string */
3126 search_make_new(const struct search_state
*const state
, int n
, const char *const base_name
) {
3127 const size_t base_len
= strlen(base_name
);
3128 const char need_to_append_dot
= base_name
[base_len
- 1] == '.' ? 0 : 1;
3129 struct search_domain
*dom
;
3131 for (dom
= state
->head
; dom
; dom
= dom
->next
) {
3133 /* this is the postfix we want */
3134 /* the actual postfix string is kept at the end of the structure */
3135 const u8
*const postfix
= ((u8
*) dom
) + sizeof(struct search_domain
);
3136 const int postfix_len
= dom
->len
;
3137 char *const newname
= (char *) mm_malloc(base_len
+ need_to_append_dot
+ postfix_len
+ 1);
3138 if (!newname
) return NULL
;
3139 memcpy(newname
, base_name
, base_len
);
3140 if (need_to_append_dot
) newname
[base_len
] = '.';
3141 memcpy(newname
+ base_len
+ need_to_append_dot
, postfix
, postfix_len
);
3142 newname
[base_len
+ need_to_append_dot
+ postfix_len
] = 0;
3147 /* we ran off the end of the list and still didn't find the requested string */
3149 return NULL
; /* unreachable; stops warnings in some compilers. */
3152 static struct request
*
3153 search_request_new(struct evdns_base
*base
, struct evdns_request
*handle
,
3154 int type
, const char *const name
, int flags
,
3155 evdns_callback_type user_callback
, void *user_arg
) {
3156 ASSERT_LOCKED(base
);
3157 EVUTIL_ASSERT(type
== TYPE_A
|| type
== TYPE_AAAA
);
3158 EVUTIL_ASSERT(handle
->current_req
== NULL
);
3159 if ( ((flags
& DNS_QUERY_NO_SEARCH
) == 0) &&
3160 base
->global_search_state
&&
3161 base
->global_search_state
->num_domains
) {
3162 /* we have some domains to search */
3163 struct request
*req
;
3164 if (string_num_dots(name
) >= base
->global_search_state
->ndots
) {
3165 req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3166 if (!req
) return NULL
;
3167 handle
->search_index
= -1;
3169 char *const new_name
= search_make_new(base
->global_search_state
, 0, name
);
3170 if (!new_name
) return NULL
;
3171 req
= request_new(base
, handle
, type
, new_name
, flags
, user_callback
, user_arg
);
3173 if (!req
) return NULL
;
3174 handle
->search_index
= 0;
3176 EVUTIL_ASSERT(handle
->search_origname
== NULL
);
3177 handle
->search_origname
= mm_strdup(name
);
3178 if (handle
->search_origname
== NULL
) {
3179 /* XXX Should we dealloc req? If yes, how? */
3184 handle
->search_state
= base
->global_search_state
;
3185 handle
->search_flags
= flags
;
3186 base
->global_search_state
->refcount
++;
3187 request_submit(req
);
3190 struct request
*const req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3191 if (!req
) return NULL
;
3192 request_submit(req
);
3197 /* this is called when a request has failed to find a name. We need to check */
3198 /* if it is part of a search and, if so, try the next name in the list */
3200 /* 0 another request has been submitted */
3201 /* 1 no more requests needed */
3203 search_try_next(struct evdns_request
*const handle
) {
3204 struct request
*req
= handle
->current_req
;
3205 struct evdns_base
*base
= req
->base
;
3206 struct request
*newreq
;
3207 ASSERT_LOCKED(base
);
3208 if (handle
->search_state
) {
3209 /* it is part of a search */
3211 handle
->search_index
++;
3212 if (handle
->search_index
>= handle
->search_state
->num_domains
) {
3213 /* no more postfixes to try, however we may need to try */
3214 /* this name without a postfix */
3215 if (string_num_dots(handle
->search_origname
) < handle
->search_state
->ndots
) {
3216 /* yep, we need to try it raw */
3217 newreq
= request_new(base
, NULL
, req
->request_type
, handle
->search_origname
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3218 log(EVDNS_LOG_DEBUG
, "Search: trying raw query %s", handle
->search_origname
);
3220 search_request_finished(handle
);
3227 new_name
= search_make_new(handle
->search_state
, handle
->search_index
, handle
->search_origname
);
3228 if (!new_name
) return 1;
3229 log(EVDNS_LOG_DEBUG
, "Search: now trying %s (%d)", new_name
, handle
->search_index
);
3230 newreq
= request_new(base
, NULL
, req
->request_type
, new_name
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3232 if (!newreq
) return 1;
3238 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 0);
3239 handle
->current_req
= newreq
;
3240 newreq
->handle
= handle
;
3241 request_submit(newreq
);
3246 search_request_finished(struct evdns_request
*const handle
) {
3247 ASSERT_LOCKED(handle
->current_req
->base
);
3248 if (handle
->search_state
) {
3249 search_state_decref(handle
->search_state
);
3250 handle
->search_state
= NULL
;
3252 if (handle
->search_origname
) {
3253 mm_free(handle
->search_origname
);
3254 handle
->search_origname
= NULL
;
3258 /* ================================================================= */
3259 /* Parsing resolv.conf files */
3262 evdns_resolv_set_defaults(struct evdns_base
*base
, int flags
) {
3263 /* if the file isn't found then we assume a local resolver */
3264 ASSERT_LOCKED(base
);
3265 if (flags
& DNS_OPTION_SEARCH
) search_set_from_hostname(base
);
3266 if (flags
& DNS_OPTION_NAMESERVERS
) evdns_base_nameserver_ip_add(base
,"127.0.0.1");
3269 #ifndef _EVENT_HAVE_STRTOK_R
3271 strtok_r(char *s
, const char *delim
, char **state
) {
3273 start
= cp
= s
? s
: *state
;
3276 while (*cp
&& !strchr(delim
, *cp
))
3291 /* helper version of atoi which returns -1 on error */
3293 strtoint(const char *const str
)
3296 const int r
= strtol(str
, &endptr
, 10);
3297 if (*endptr
) return -1;
3301 /* Parse a number of seconds into a timeval; return -1 on error. */
3303 strtotimeval(const char *const str
, struct timeval
*out
)
3307 d
= strtod(str
, &endptr
);
3308 if (*endptr
) return -1;
3309 if (d
< 0) return -1;
3310 out
->tv_sec
= (int) d
;
3311 out
->tv_usec
= (int) ((d
- (int) d
)*1000000);
3312 if (out
->tv_sec
== 0 && out
->tv_usec
< 1000) /* less than 1 msec */
3317 /* helper version of atoi that returns -1 on error and clips to bounds. */
3319 strtoint_clipped(const char *const str
, int min
, int max
)
3321 int r
= strtoint(str
);
3333 evdns_base_set_max_requests_inflight(struct evdns_base
*base
, int maxinflight
)
3335 int old_n_heads
= base
->n_req_heads
, n_heads
;
3336 struct request
**old_heads
= base
->req_heads
, **new_heads
, *req
;
3339 ASSERT_LOCKED(base
);
3340 if (maxinflight
< 1)
3342 n_heads
= (maxinflight
+4) / 5;
3343 EVUTIL_ASSERT(n_heads
> 0);
3344 new_heads
= mm_calloc(n_heads
, sizeof(struct request
*));
3348 for (i
= 0; i
< old_n_heads
; ++i
) {
3349 while (old_heads
[i
]) {
3351 evdns_request_remove(req
, &old_heads
[i
]);
3352 evdns_request_insert(req
, &new_heads
[req
->trans_id
% n_heads
]);
3357 base
->req_heads
= new_heads
;
3358 base
->n_req_heads
= n_heads
;
3359 base
->global_max_requests_inflight
= maxinflight
;
3363 /* exported function */
3365 evdns_base_set_option(struct evdns_base
*base
,
3366 const char *option
, const char *val
)
3370 res
= evdns_base_set_option_impl(base
, option
, val
, DNS_OPTIONS_ALL
);
3376 str_matches_option(const char *s1
, const char *optionname
)
3378 /* Option names are given as "option:" We accept either 'option' in
3379 * s1, or 'option:randomjunk'. The latter form is to implement the
3380 * resolv.conf parser. */
3381 size_t optlen
= strlen(optionname
);
3382 size_t slen
= strlen(s1
);
3383 if (slen
== optlen
|| slen
== optlen
- 1)
3384 return !strncmp(s1
, optionname
, slen
);
3385 else if (slen
> optlen
)
3386 return !strncmp(s1
, optionname
, optlen
);
3392 evdns_base_set_option_impl(struct evdns_base
*base
,
3393 const char *option
, const char *val
, int flags
)
3395 ASSERT_LOCKED(base
);
3396 if (str_matches_option(option
, "ndots:")) {
3397 const int ndots
= strtoint(val
);
3398 if (ndots
== -1) return -1;
3399 if (!(flags
& DNS_OPTION_SEARCH
)) return 0;
3400 log(EVDNS_LOG_DEBUG
, "Setting ndots to %d", ndots
);
3401 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3402 if (!base
->global_search_state
) return -1;
3403 base
->global_search_state
->ndots
= ndots
;
3404 } else if (str_matches_option(option
, "timeout:")) {
3406 if (strtotimeval(val
, &tv
) == -1) return -1;
3407 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3408 log(EVDNS_LOG_DEBUG
, "Setting timeout to %s", val
);
3409 memcpy(&base
->global_timeout
, &tv
, sizeof(struct timeval
));
3410 } else if (str_matches_option(option
, "getaddrinfo-allow-skew:")) {
3412 if (strtotimeval(val
, &tv
) == -1) return -1;
3413 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3414 log(EVDNS_LOG_DEBUG
, "Setting getaddrinfo-allow-skew to %s",
3416 memcpy(&base
->global_getaddrinfo_allow_skew
, &tv
,
3417 sizeof(struct timeval
));
3418 } else if (str_matches_option(option
, "max-timeouts:")) {
3419 const int maxtimeout
= strtoint_clipped(val
, 1, 255);
3420 if (maxtimeout
== -1) return -1;
3421 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3422 log(EVDNS_LOG_DEBUG
, "Setting maximum allowed timeouts to %d",
3424 base
->global_max_nameserver_timeout
= maxtimeout
;
3425 } else if (str_matches_option(option
, "max-inflight:")) {
3426 const int maxinflight
= strtoint_clipped(val
, 1, 65000);
3427 if (maxinflight
== -1) return -1;
3428 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3429 log(EVDNS_LOG_DEBUG
, "Setting maximum inflight requests to %d",
3431 evdns_base_set_max_requests_inflight(base
, maxinflight
);
3432 } else if (str_matches_option(option
, "attempts:")) {
3433 int retries
= strtoint(val
);
3434 if (retries
== -1) return -1;
3435 if (retries
> 255) retries
= 255;
3436 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3437 log(EVDNS_LOG_DEBUG
, "Setting retries to %d", retries
);
3438 base
->global_max_retransmits
= retries
;
3439 } else if (str_matches_option(option
, "randomize-case:")) {
3440 int randcase
= strtoint(val
);
3441 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3442 base
->global_randomize_case
= randcase
;
3443 } else if (str_matches_option(option
, "bind-to:")) {
3444 /* XXX This only applies to successive nameservers, not
3445 * to already-configured ones. We might want to fix that. */
3446 int len
= sizeof(base
->global_outgoing_address
);
3447 if (!(flags
& DNS_OPTION_NAMESERVERS
)) return 0;
3448 if (evutil_parse_sockaddr_port(val
,
3449 (struct sockaddr
*)&base
->global_outgoing_address
, &len
))
3451 base
->global_outgoing_addrlen
= len
;
3452 } else if (str_matches_option(option
, "initial-probe-timeout:")) {
3454 if (strtotimeval(val
, &tv
) == -1) return -1;
3455 if (tv
.tv_sec
> 3600)
3457 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3458 log(EVDNS_LOG_DEBUG
, "Setting initial probe timeout to %s",
3460 memcpy(&base
->global_nameserver_probe_initial_timeout
, &tv
,
3467 evdns_set_option(const char *option
, const char *val
, int flags
)
3470 current_base
= evdns_base_new(NULL
, 0);
3471 return evdns_base_set_option(current_base
, option
, val
);
3475 resolv_conf_parse_line(struct evdns_base
*base
, char *const start
, int flags
) {
3477 static const char *const delims
= " \t";
3478 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3481 char *const first_token
= strtok_r(start
, delims
, &strtok_state
);
3482 ASSERT_LOCKED(base
);
3483 if (!first_token
) return;
3485 if (!strcmp(first_token
, "nameserver") && (flags
& DNS_OPTION_NAMESERVERS
)) {
3486 const char *const nameserver
= NEXT_TOKEN
;
3489 evdns_base_nameserver_ip_add(base
, nameserver
);
3490 } else if (!strcmp(first_token
, "domain") && (flags
& DNS_OPTION_SEARCH
)) {
3491 const char *const domain
= NEXT_TOKEN
;
3493 search_postfix_clear(base
);
3494 search_postfix_add(base
, domain
);
3496 } else if (!strcmp(first_token
, "search") && (flags
& DNS_OPTION_SEARCH
)) {
3498 search_postfix_clear(base
);
3500 while ((domain
= NEXT_TOKEN
)) {
3501 search_postfix_add(base
, domain
);
3503 search_reverse(base
);
3504 } else if (!strcmp(first_token
, "options")) {
3506 while ((option
= NEXT_TOKEN
)) {
3507 const char *val
= strchr(option
, ':');
3508 evdns_base_set_option_impl(base
, option
, val
? val
+1 : "", flags
);
3514 /* exported function */
3517 /* 1 failed to open file */
3518 /* 2 failed to stat file */
3519 /* 3 file too large */
3520 /* 4 out of memory */
3521 /* 5 short read from file */
3523 evdns_base_resolv_conf_parse(struct evdns_base
*base
, int flags
, const char *const filename
) {
3526 res
= evdns_base_resolv_conf_parse_impl(base
, flags
, filename
);
3532 evdns_get_default_hosts_filename(void)
3535 /* Windows is a little coy about where it puts its configuration
3536 * files. Sure, they're _usually_ in C:\windows\system32, but
3537 * there's no reason in principle they couldn't be in
3538 * W:\hoboken chicken emergency\
3540 char path
[MAX_PATH
+1];
3541 static const char hostfile
[] = "\\drivers\\etc\\hosts";
3545 if (! SHGetSpecialFolderPathA(NULL
, path
, CSIDL_SYSTEM
, 0))
3547 len_out
= strlen(path
)+strlen(hostfile
);
3548 path_out
= mm_malloc(len_out
+1);
3549 evutil_snprintf(path_out
, len_out
, "%s%s", path
, hostfile
);
3552 return mm_strdup("/etc/hosts");
3557 evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
) {
3563 log(EVDNS_LOG_DEBUG
, "Parsing resolv.conf file %s", filename
);
3565 if (flags
& DNS_OPTION_HOSTSFILE
) {
3566 char *fname
= evdns_get_default_hosts_filename();
3567 evdns_base_load_hosts(base
, fname
);
3572 if ((err
= evutil_read_file(filename
, &resolv
, &n
, 0)) < 0) {
3575 evdns_resolv_set_defaults(base
, flags
);
3584 char *const newline
= strchr(start
, '\n');
3586 resolv_conf_parse_line(base
, start
, flags
);
3590 resolv_conf_parse_line(base
, start
, flags
);
3591 start
= newline
+ 1;
3595 if (!base
->server_head
&& (flags
& DNS_OPTION_NAMESERVERS
)) {
3596 /* no nameservers were configured. */
3597 evdns_base_nameserver_ip_add(base
, "127.0.0.1");
3600 if (flags
& DNS_OPTION_SEARCH
&& (!base
->global_search_state
|| base
->global_search_state
->num_domains
== 0)) {
3601 search_set_from_hostname(base
);
3609 evdns_resolv_conf_parse(int flags
, const char *const filename
) {
3611 current_base
= evdns_base_new(NULL
, 0);
3612 return evdns_base_resolv_conf_parse(current_base
, flags
, filename
);
3617 /* Add multiple nameservers from a space-or-comma-separated list. */
3619 evdns_nameserver_ip_add_line(struct evdns_base
*base
, const char *ips
) {
3623 ASSERT_LOCKED(base
);
3625 while (isspace(*ips
) || *ips
== ',' || *ips
== '\t')
3628 while (isdigit(*ips
) || *ips
== '.' || *ips
== ':' ||
3629 *ips
=='[' || *ips
==']')
3631 buf
= mm_malloc(ips
-addr
+1);
3633 memcpy(buf
, addr
, ips
-addr
);
3634 buf
[ips
-addr
] = '\0';
3635 r
= evdns_base_nameserver_ip_add(base
, buf
);
3642 typedef DWORD(WINAPI
*GetNetworkParams_fn_t
)(FIXED_INFO
*, DWORD
*);
3644 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3645 /* figure out what our nameservers are. */
3647 load_nameservers_with_getnetworkparams(struct evdns_base
*base
)
3649 /* Based on MSDN examples and inspection of c-ares code. */
3652 ULONG size
= sizeof(FIXED_INFO
);
3654 int status
= 0, r
, added_any
;
3656 GetNetworkParams_fn_t fn
;
3658 ASSERT_LOCKED(base
);
3659 if (!(handle
= evutil_load_windows_system_library(
3660 TEXT("iphlpapi.dll")))) {
3661 log(EVDNS_LOG_WARN
, "Could not open iphlpapi.dll");
3665 if (!(fn
= (GetNetworkParams_fn_t
) GetProcAddress(handle
, "GetNetworkParams"))) {
3666 log(EVDNS_LOG_WARN
, "Could not get address of function.");
3671 buf
= mm_malloc(size
);
3672 if (!buf
) { status
= 4; goto done
; }
3674 r
= fn(fixed
, &size
);
3675 if (r
!= ERROR_SUCCESS
&& r
!= ERROR_BUFFER_OVERFLOW
) {
3679 if (r
!= ERROR_SUCCESS
) {
3681 buf
= mm_malloc(size
);
3682 if (!buf
) { status
= 4; goto done
; }
3684 r
= fn(fixed
, &size
);
3685 if (r
!= ERROR_SUCCESS
) {
3686 log(EVDNS_LOG_DEBUG
, "fn() failed.");
3692 EVUTIL_ASSERT(fixed
);
3694 ns
= &(fixed
->DnsServerList
);
3696 r
= evdns_nameserver_ip_add_line(base
, ns
->IpAddress
.String
);
3698 log(EVDNS_LOG_DEBUG
,"Could not add nameserver %s to list,error: %d",
3699 (ns
->IpAddress
.String
),(int)GetLastError());
3703 log(EVDNS_LOG_DEBUG
,"Successfully added %s as nameserver",ns
->IpAddress
.String
);
3710 log(EVDNS_LOG_DEBUG
, "No nameservers added.");
3721 FreeLibrary(handle
);
3726 config_nameserver_from_reg_key(struct evdns_base
*base
, HKEY key
, const TCHAR
*subkey
)
3729 DWORD bufsz
= 0, type
= 0;
3732 ASSERT_LOCKED(base
);
3733 if (RegQueryValueEx(key
, subkey
, 0, &type
, NULL
, &bufsz
)
3736 if (!(buf
= mm_malloc(bufsz
)))
3739 if (RegQueryValueEx(key
, subkey
, 0, &type
, (LPBYTE
)buf
, &bufsz
)
3740 == ERROR_SUCCESS
&& bufsz
> 1) {
3741 status
= evdns_nameserver_ip_add_line(base
,buf
);
3748 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3749 #define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
3750 #define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
3753 load_nameservers_from_registry(struct evdns_base
*base
)
3757 #define TRY(k, name) \
3758 if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3759 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3761 } else if (!found) { \
3762 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3766 ASSERT_LOCKED(base
);
3768 if (((int)GetVersion()) > 0) { /* NT */
3769 HKEY nt_key
= 0, interfaces_key
= 0;
3771 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_NT_KEY
, 0,
3772 KEY_READ
, &nt_key
) != ERROR_SUCCESS
) {
3773 log(EVDNS_LOG_DEBUG
,"Couldn't open nt key, %d",(int)GetLastError());
3776 r
= RegOpenKeyEx(nt_key
, TEXT("Interfaces"), 0,
3777 KEY_QUERY_VALUE
|KEY_ENUMERATE_SUB_KEYS
,
3779 if (r
!= ERROR_SUCCESS
) {
3780 log(EVDNS_LOG_DEBUG
,"Couldn't open interfaces key, %d",(int)GetLastError());
3783 TRY(nt_key
, "NameServer");
3784 TRY(nt_key
, "DhcpNameServer");
3785 TRY(interfaces_key
, "NameServer");
3786 TRY(interfaces_key
, "DhcpNameServer");
3787 RegCloseKey(interfaces_key
);
3788 RegCloseKey(nt_key
);
3791 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_9X_KEY
, 0,
3792 KEY_READ
, &win_key
) != ERROR_SUCCESS
) {
3793 log(EVDNS_LOG_DEBUG
, "Couldn't open registry key, %d", (int)GetLastError());
3796 TRY(win_key
, "NameServer");
3797 RegCloseKey(win_key
);
3801 log(EVDNS_LOG_WARN
,"Didn't find any nameservers.");
3804 return found
? 0 : -1;
3809 evdns_base_config_windows_nameservers(struct evdns_base
*base
)
3814 base
= current_base
;
3818 if (load_nameservers_with_getnetworkparams(base
) == 0) {
3822 r
= load_nameservers_from_registry(base
);
3824 fname
= evdns_get_default_hosts_filename();
3825 evdns_base_load_hosts(base
, fname
);
3834 evdns_config_windows_nameservers(void)
3836 if (!current_base
) {
3837 current_base
= evdns_base_new(NULL
, 1);
3838 return current_base
== NULL
? -1 : 0;
3840 return evdns_base_config_windows_nameservers(current_base
);
3846 evdns_base_new(struct event_base
*event_base
, int initialize_nameservers
)
3848 struct evdns_base
*base
;
3850 if (evutil_secure_rng_init() < 0) {
3851 log(EVDNS_LOG_WARN
, "Unable to seed random number generator; "
3856 /* Give the evutil library a hook into its evdns-enabled
3857 * functionality. We can't just call evdns_getaddrinfo directly or
3858 * else libevent-core will depend on libevent-extras. */
3859 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo
);
3861 base
= mm_malloc(sizeof(struct evdns_base
));
3864 memset(base
, 0, sizeof(struct evdns_base
));
3865 base
->req_waiting_head
= NULL
;
3867 EVTHREAD_ALLOC_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
3870 /* Set max requests inflight and allocate req_heads. */
3871 base
->req_heads
= NULL
;
3873 evdns_base_set_max_requests_inflight(base
, 64);
3875 base
->server_head
= NULL
;
3876 base
->event_base
= event_base
;
3877 base
->global_good_nameservers
= base
->global_requests_inflight
=
3878 base
->global_requests_waiting
= 0;
3880 base
->global_timeout
.tv_sec
= 5;
3881 base
->global_timeout
.tv_usec
= 0;
3882 base
->global_max_reissues
= 1;
3883 base
->global_max_retransmits
= 3;
3884 base
->global_max_nameserver_timeout
= 3;
3885 base
->global_search_state
= NULL
;
3886 base
->global_randomize_case
= 1;
3887 base
->global_getaddrinfo_allow_skew
.tv_sec
= 3;
3888 base
->global_getaddrinfo_allow_skew
.tv_usec
= 0;
3889 base
->global_nameserver_probe_initial_timeout
.tv_sec
= 10;
3890 base
->global_nameserver_probe_initial_timeout
.tv_usec
= 0;
3892 TAILQ_INIT(&base
->hostsdb
);
3894 if (initialize_nameservers
) {
3897 r
= evdns_base_config_windows_nameservers(base
);
3899 r
= evdns_base_resolv_conf_parse(base
, DNS_OPTIONS_ALL
, "/etc/resolv.conf");
3902 evdns_base_free_and_unlock(base
, 0);
3913 struct evdns_base
*base
= evdns_base_new(NULL
, 1);
3915 current_base
= base
;
3923 evdns_err_to_string(int err
)
3926 case DNS_ERR_NONE
: return "no error";
3927 case DNS_ERR_FORMAT
: return "misformatted query";
3928 case DNS_ERR_SERVERFAILED
: return "server failed";
3929 case DNS_ERR_NOTEXIST
: return "name does not exist";
3930 case DNS_ERR_NOTIMPL
: return "query not implemented";
3931 case DNS_ERR_REFUSED
: return "refused";
3933 case DNS_ERR_TRUNCATED
: return "reply truncated or ill-formed";
3934 case DNS_ERR_UNKNOWN
: return "unknown";
3935 case DNS_ERR_TIMEOUT
: return "request timed out";
3936 case DNS_ERR_SHUTDOWN
: return "dns subsystem shut down";
3937 case DNS_ERR_CANCEL
: return "dns request canceled";
3938 case DNS_ERR_NODATA
: return "no records in the reply";
3939 default: return "[Unknown error code]";
3944 evdns_nameserver_free(struct nameserver
*server
)
3946 if (server
->socket
>= 0)
3947 evutil_closesocket(server
->socket
);
3948 (void) event_del(&server
->event
);
3949 event_debug_unassign(&server
->event
);
3950 if (server
->state
== 0)
3951 (void) event_del(&server
->timeout_event
);
3952 if (server
->probe_request
) {
3953 evdns_cancel_request(server
->base
, server
->probe_request
);
3954 server
->probe_request
= NULL
;
3956 event_debug_unassign(&server
->timeout_event
);
3961 evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
)
3963 struct nameserver
*server
, *server_next
;
3964 struct search_domain
*dom
, *dom_next
;
3967 /* Requires that we hold the lock. */
3969 /* TODO(nickm) we might need to refcount here. */
3971 for (server
= base
->server_head
; server
; server
= server_next
) {
3972 server_next
= server
->next
;
3973 evdns_nameserver_free(server
);
3974 if (server_next
== base
->server_head
)
3977 base
->server_head
= NULL
;
3978 base
->global_good_nameservers
= 0;
3980 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
3981 while (base
->req_heads
[i
]) {
3983 reply_schedule_callback(base
->req_heads
[i
], 0, DNS_ERR_SHUTDOWN
, NULL
);
3984 request_finished(base
->req_heads
[i
], &REQ_HEAD(base
, base
->req_heads
[i
]->trans_id
), 1);
3987 while (base
->req_waiting_head
) {
3989 reply_schedule_callback(base
->req_waiting_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
3990 request_finished(base
->req_waiting_head
, &base
->req_waiting_head
, 1);
3992 base
->global_requests_inflight
= base
->global_requests_waiting
= 0;
3995 if (base
->global_search_state
) {
3996 for (dom
= base
->global_search_state
->head
; dom
; dom
= dom_next
) {
3997 dom_next
= dom
->next
;
4000 mm_free(base
->global_search_state
);
4001 base
->global_search_state
= NULL
;
4005 struct hosts_entry
*victim
;
4006 while ((victim
= TAILQ_FIRST(&base
->hostsdb
))) {
4007 TAILQ_REMOVE(&base
->hostsdb
, victim
, next
);
4012 mm_free(base
->req_heads
);
4015 EVTHREAD_FREE_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
4021 evdns_base_free(struct evdns_base
*base
, int fail_requests
)
4024 evdns_base_free_and_unlock(base
, fail_requests
);
4028 evdns_shutdown(int fail_requests
)
4031 struct evdns_base
*b
= current_base
;
4032 current_base
= NULL
;
4033 evdns_base_free(b
, fail_requests
);
4035 evdns_log_fn
= NULL
;
4039 evdns_base_parse_hosts_line(struct evdns_base
*base
, char *line
)
4042 static const char *const delims
= " \t";
4043 char *const addr
= strtok_r(line
, delims
, &strtok_state
);
4044 char *hostname
, *hash
;
4045 struct sockaddr_storage ss
;
4046 int socklen
= sizeof(ss
);
4047 ASSERT_LOCKED(base
);
4049 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
4051 if (!addr
|| *addr
== '#')
4054 memset(&ss
, 0, sizeof(ss
));
4055 if (evutil_parse_sockaddr_port(addr
, (struct sockaddr
*)&ss
, &socklen
)<0)
4057 if (socklen
> (int)sizeof(struct sockaddr_in6
))
4060 if (sockaddr_getport((struct sockaddr
*)&ss
))
4063 while ((hostname
= NEXT_TOKEN
)) {
4064 struct hosts_entry
*he
;
4066 if ((hash
= strchr(hostname
, '#'))) {
4067 if (hash
== hostname
)
4072 namelen
= strlen(hostname
);
4074 he
= mm_calloc(1, sizeof(struct hosts_entry
)+namelen
);
4077 EVUTIL_ASSERT(socklen
<= (int)sizeof(he
->addr
));
4078 memcpy(&he
->addr
, &ss
, socklen
);
4079 memcpy(he
->hostname
, hostname
, namelen
+1);
4080 he
->addrlen
= socklen
;
4082 TAILQ_INSERT_TAIL(&base
->hostsdb
, he
, next
);
4093 evdns_base_load_hosts_impl(struct evdns_base
*base
, const char *hosts_fname
)
4095 char *str
=NULL
, *cp
, *eol
;
4099 ASSERT_LOCKED(base
);
4101 if (hosts_fname
== NULL
||
4102 (err
= evutil_read_file(hosts_fname
, &str
, &len
, 0)) < 0) {
4104 strlcpy(tmp
, "127.0.0.1 localhost", sizeof(tmp
));
4105 evdns_base_parse_hosts_line(base
, tmp
);
4106 strlcpy(tmp
, "::1 localhost", sizeof(tmp
));
4107 evdns_base_parse_hosts_line(base
, tmp
);
4108 return err
? -1 : 0;
4111 /* This will break early if there is a NUL in the hosts file.
4112 * Probably not a problem.*/
4115 eol
= strchr(cp
, '\n');
4119 evdns_base_parse_hosts_line(base
, cp
);
4122 evdns_base_parse_hosts_line(base
, cp
);
4132 evdns_base_load_hosts(struct evdns_base
*base
, const char *hosts_fname
)
4136 base
= current_base
;
4138 res
= evdns_base_load_hosts_impl(base
, hosts_fname
);
4143 /* A single request for a getaddrinfo, either v4 or v6. */
4144 struct getaddrinfo_subrequest
{
4145 struct evdns_request
*r
;
4149 /* State data used to implement an in-progress getaddrinfo. */
4150 struct evdns_getaddrinfo_request
{
4151 struct evdns_base
*evdns_base
;
4152 /* Copy of the modified 'hints' data that we'll use to build
4154 struct evutil_addrinfo hints
;
4155 /* The callback to invoke when we're done */
4156 evdns_getaddrinfo_cb user_cb
;
4157 /* User-supplied data to give to the callback. */
4159 /* The port to use when building sockaddrs. */
4161 /* The sub_request for an A record (if any) */
4162 struct getaddrinfo_subrequest ipv4_request
;
4163 /* The sub_request for an AAAA record (if any) */
4164 struct getaddrinfo_subrequest ipv6_request
;
4166 /* The cname result that we were told (if any) */
4169 /* If we have one request answered and one request still inflight,
4170 * then this field holds the answer from the first request... */
4171 struct evutil_addrinfo
*pending_result
;
4172 /* And this event is a timeout that will tell us to cancel the second
4173 * request if it's taking a long time. */
4174 struct event timeout
;
4176 /* And this field holds the error code from the first request... */
4178 /* If this is set, the user canceled this request. */
4179 unsigned user_canceled
: 1;
4180 /* If this is set, the user can no longer cancel this request; we're
4181 * just waiting for the free. */
4182 unsigned request_done
: 1;
4185 /* Convert an evdns errors to the equivalent getaddrinfo error. */
4187 evdns_err_to_getaddrinfo_err(int e1
)
4189 /* XXX Do this better! */
4190 if (e1
== DNS_ERR_NONE
)
4192 else if (e1
== DNS_ERR_NOTEXIST
)
4193 return EVUTIL_EAI_NONAME
;
4195 return EVUTIL_EAI_FAIL
;
4198 /* Return the more informative of two getaddrinfo errors. */
4200 getaddrinfo_merge_err(int e1
, int e2
)
4202 /* XXXX be cleverer here. */
4210 free_getaddrinfo_request(struct evdns_getaddrinfo_request
*data
)
4212 /* DO NOT CALL this if either of the requests is pending. Only once
4213 * both callbacks have been invoked is it safe to free the request */
4214 if (data
->pending_result
)
4215 evutil_freeaddrinfo(data
->pending_result
);
4216 if (data
->cname_result
)
4217 mm_free(data
->cname_result
);
4218 event_del(&data
->timeout
);
4224 add_cname_to_reply(struct evdns_getaddrinfo_request
*data
,
4225 struct evutil_addrinfo
*ai
)
4227 if (data
->cname_result
&& ai
) {
4228 ai
->ai_canonname
= data
->cname_result
;
4229 data
->cname_result
= NULL
;
4233 /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
4234 * request has finished, but the other one took too long to answer. Pass
4235 * along the answer we got, and cancel the other request.
4238 evdns_getaddrinfo_timeout_cb(evutil_socket_t fd
, short what
, void *ptr
)
4240 int v4_timedout
= 0, v6_timedout
= 0;
4241 struct evdns_getaddrinfo_request
*data
= ptr
;
4243 /* Cancel any pending requests, and note which one */
4244 if (data
->ipv4_request
.r
) {
4245 /* XXXX This does nothing if the request's callback is already
4246 * running (pending_cb is set). */
4247 evdns_cancel_request(NULL
, data
->ipv4_request
.r
);
4249 EVDNS_LOCK(data
->evdns_base
);
4250 ++data
->evdns_base
->getaddrinfo_ipv4_timeouts
;
4251 EVDNS_UNLOCK(data
->evdns_base
);
4253 if (data
->ipv6_request
.r
) {
4254 /* XXXX This does nothing if the request's callback is already
4255 * running (pending_cb is set). */
4256 evdns_cancel_request(NULL
, data
->ipv6_request
.r
);
4258 EVDNS_LOCK(data
->evdns_base
);
4259 ++data
->evdns_base
->getaddrinfo_ipv6_timeouts
;
4260 EVDNS_UNLOCK(data
->evdns_base
);
4263 /* We only use this timeout callback when we have an answer for
4265 EVUTIL_ASSERT(!v4_timedout
|| !v6_timedout
);
4267 /* Report the outcome of the other request that didn't time out. */
4268 if (data
->pending_result
) {
4269 add_cname_to_reply(data
, data
->pending_result
);
4270 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4271 data
->pending_result
= NULL
;
4273 int e
= data
->pending_error
;
4275 e
= EVUTIL_EAI_AGAIN
;
4276 data
->user_cb(e
, NULL
, data
->user_data
);
4279 data
->user_cb
= NULL
; /* prevent double-call if evdns callbacks are
4280 * in-progress. XXXX It would be better if this
4281 * weren't necessary. */
4283 if (!v4_timedout
&& !v6_timedout
) {
4284 /* should be impossible? XXXX */
4285 free_getaddrinfo_request(data
);
4290 evdns_getaddrinfo_set_timeout(struct evdns_base
*evdns_base
,
4291 struct evdns_getaddrinfo_request
*data
)
4293 return event_add(&data
->timeout
, &evdns_base
->global_getaddrinfo_allow_skew
);
4297 evdns_result_is_answer(int result
)
4299 return (result
!= DNS_ERR_NOTIMPL
&& result
!= DNS_ERR_REFUSED
&&
4300 result
!= DNS_ERR_SERVERFAILED
&& result
!= DNS_ERR_CANCEL
);
4304 evdns_getaddrinfo_gotresolve(int result
, char type
, int count
,
4305 int ttl
, void *addresses
, void *arg
)
4308 struct getaddrinfo_subrequest
*req
= arg
;
4309 struct getaddrinfo_subrequest
*other_req
;
4310 struct evdns_getaddrinfo_request
*data
;
4312 struct evutil_addrinfo
*res
;
4314 struct sockaddr_in sin
;
4315 struct sockaddr_in6 sin6
;
4316 struct sockaddr
*sa
;
4317 int socklen
, addrlen
;
4322 EVUTIL_ASSERT(req
->type
== DNS_IPv4_A
|| req
->type
== DNS_IPv6_AAAA
);
4323 if (req
->type
== DNS_IPv4_A
) {
4324 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv4_request
);
4325 other_req
= &data
->ipv6_request
;
4327 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv6_request
);
4328 other_req
= &data
->ipv4_request
;
4331 EVDNS_LOCK(data
->evdns_base
);
4332 if (evdns_result_is_answer(result
)) {
4333 if (req
->type
== DNS_IPv4_A
)
4334 ++data
->evdns_base
->getaddrinfo_ipv4_answered
;
4336 ++data
->evdns_base
->getaddrinfo_ipv6_answered
;
4338 user_canceled
= data
->user_canceled
;
4339 if (other_req
->r
== NULL
)
4340 data
->request_done
= 1;
4341 EVDNS_UNLOCK(data
->evdns_base
);
4345 if (result
== DNS_ERR_CANCEL
&& ! user_canceled
) {
4346 /* Internal cancel request from timeout or internal error.
4347 * we already answered the user. */
4348 if (other_req
->r
== NULL
)
4349 free_getaddrinfo_request(data
);
4353 if (data
->user_cb
== NULL
) {
4354 /* We already answered. XXXX This shouldn't be needed; see
4355 * comments in evdns_getaddrinfo_timeout_cb */
4356 free_getaddrinfo_request(data
);
4360 if (result
== DNS_ERR_NONE
) {
4362 err
= EVUTIL_EAI_NODATA
;
4366 err
= evdns_err_to_getaddrinfo_err(result
);
4370 /* Looks like we got an error. */
4372 /* The other request is still working; maybe it will
4374 /* XXXX handle failure from set_timeout */
4375 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4376 data
->pending_error
= err
;
4380 if (user_canceled
) {
4381 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4382 } else if (data
->pending_result
) {
4383 /* If we have an answer waiting, and we weren't
4384 * canceled, ignore this error. */
4385 add_cname_to_reply(data
, data
->pending_result
);
4386 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4387 data
->pending_result
= NULL
;
4389 if (data
->pending_error
)
4390 err
= getaddrinfo_merge_err(err
,
4391 data
->pending_error
);
4392 data
->user_cb(err
, NULL
, data
->user_data
);
4394 free_getaddrinfo_request(data
);
4396 } else if (user_canceled
) {
4398 /* The other request is still working; let it hit this
4399 * callback with EVUTIL_EAI_CANCEL callback and report
4403 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4404 free_getaddrinfo_request(data
);
4408 /* Looks like we got some answers. We should turn them into addrinfos
4409 * and then either queue those or return them all. */
4410 EVUTIL_ASSERT(type
== DNS_IPv4_A
|| type
== DNS_IPv6_AAAA
);
4412 if (type
== DNS_IPv4_A
) {
4413 memset(&sin
, 0, sizeof(sin
));
4414 sin
.sin_family
= AF_INET
;
4415 sin
.sin_port
= htons(data
->port
);
4417 sa
= (struct sockaddr
*)&sin
;
4418 socklen
= sizeof(sin
);
4420 addrp
= &sin
.sin_addr
.s_addr
;
4422 memset(&sin6
, 0, sizeof(sin6
));
4423 sin6
.sin6_family
= AF_INET6
;
4424 sin6
.sin6_port
= htons(data
->port
);
4426 sa
= (struct sockaddr
*)&sin6
;
4427 socklen
= sizeof(sin6
);
4429 addrp
= &sin6
.sin6_addr
.s6_addr
;
4433 for (i
=0; i
< count
; ++i
) {
4434 struct evutil_addrinfo
*ai
;
4435 memcpy(addrp
, ((char*)addresses
)+i
*addrlen
, addrlen
);
4436 ai
= evutil_new_addrinfo(sa
, socklen
, &data
->hints
);
4439 evdns_cancel_request(NULL
, other_req
->r
);
4441 data
->user_cb(EVUTIL_EAI_MEMORY
, NULL
, data
->user_data
);
4443 evutil_freeaddrinfo(res
);
4445 if (other_req
->r
== NULL
)
4446 free_getaddrinfo_request(data
);
4449 res
= evutil_addrinfo_append(res
, ai
);
4453 /* The other request is still in progress; wait for it */
4454 /* XXXX handle failure from set_timeout */
4455 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4456 data
->pending_result
= res
;
4459 /* The other request is done or never started; append its
4460 * results (if any) and return them. */
4461 if (data
->pending_result
) {
4462 if (req
->type
== DNS_IPv4_A
)
4463 res
= evutil_addrinfo_append(res
,
4464 data
->pending_result
);
4466 res
= evutil_addrinfo_append(
4467 data
->pending_result
, res
);
4468 data
->pending_result
= NULL
;
4471 /* Call the user callback. */
4472 add_cname_to_reply(data
, res
);
4473 data
->user_cb(0, res
, data
->user_data
);
4476 free_getaddrinfo_request(data
);
4480 static struct hosts_entry
*
4481 find_hosts_entry(struct evdns_base
*base
, const char *hostname
,
4482 struct hosts_entry
*find_after
)
4484 struct hosts_entry
*e
;
4487 e
= TAILQ_NEXT(find_after
, next
);
4489 e
= TAILQ_FIRST(&base
->hostsdb
);
4491 for (; e
; e
= TAILQ_NEXT(e
, next
)) {
4492 if (!evutil_ascii_strcasecmp(e
->hostname
, hostname
))
4499 evdns_getaddrinfo_fromhosts(struct evdns_base
*base
,
4500 const char *nodename
, struct evutil_addrinfo
*hints
, ev_uint16_t port
,
4501 struct evutil_addrinfo
**res
)
4504 struct hosts_entry
*e
;
4505 struct evutil_addrinfo
*ai
=NULL
;
4506 int f
= hints
->ai_family
;
4509 for (e
= find_hosts_entry(base
, nodename
, NULL
); e
;
4510 e
= find_hosts_entry(base
, nodename
, e
)) {
4511 struct evutil_addrinfo
*ai_new
;
4513 if ((e
->addr
.sa
.sa_family
== AF_INET
&& f
== PF_INET6
) ||
4514 (e
->addr
.sa
.sa_family
== AF_INET6
&& f
== PF_INET
))
4516 ai_new
= evutil_new_addrinfo(&e
->addr
.sa
, e
->addrlen
, hints
);
4521 sockaddr_setport(ai_new
->ai_addr
, port
);
4522 ai
= evutil_addrinfo_append(ai
, ai_new
);
4527 /* Note that we return an empty answer if we found entries for
4528 * this hostname but none were of the right address type. */
4533 evutil_freeaddrinfo(ai
);
4538 struct evdns_getaddrinfo_request
*
4539 evdns_getaddrinfo(struct evdns_base
*dns_base
,
4540 const char *nodename
, const char *servname
,
4541 const struct evutil_addrinfo
*hints_in
,
4542 evdns_getaddrinfo_cb cb
, void *arg
)
4544 struct evdns_getaddrinfo_request
*data
;
4545 struct evutil_addrinfo hints
;
4546 struct evutil_addrinfo
*res
= NULL
;
4552 dns_base
= current_base
;
4555 "Call to getaddrinfo_async with no "
4556 "evdns_base configured.");
4557 cb(EVUTIL_EAI_FAIL
, NULL
, arg
); /* ??? better error? */
4562 /* If we _must_ answer this immediately, do so. */
4563 if ((hints_in
&& (hints_in
->ai_flags
& EVUTIL_AI_NUMERICHOST
))) {
4565 err
= evutil_getaddrinfo(nodename
, servname
, hints_in
, &res
);
4571 memcpy(&hints
, hints_in
, sizeof(hints
));
4573 memset(&hints
, 0, sizeof(hints
));
4574 hints
.ai_family
= PF_UNSPEC
;
4577 evutil_adjust_hints_for_addrconfig(&hints
);
4579 /* Now try to see if we _can_ answer immediately. */
4580 /* (It would be nice to do this by calling getaddrinfo directly, with
4581 * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
4582 * a reliable way to distinguish the "that wasn't a numeric host!" case
4583 * from any other EAI_NONAME cases.) */
4584 err
= evutil_getaddrinfo_common(nodename
, servname
, &hints
, &res
, &port
);
4585 if (err
!= EVUTIL_EAI_NEED_RESOLVE
) {
4590 /* If there is an entry in the hosts file, we should give it now. */
4591 if (!evdns_getaddrinfo_fromhosts(dns_base
, nodename
, &hints
, port
, &res
)) {
4596 /* Okay, things are serious now. We're going to need to actually
4599 data
= mm_calloc(1,sizeof(struct evdns_getaddrinfo_request
));
4601 cb(EVUTIL_EAI_MEMORY
, NULL
, arg
);
4605 memcpy(&data
->hints
, &hints
, sizeof(data
->hints
));
4606 data
->port
= (ev_uint16_t
)port
;
4607 data
->ipv4_request
.type
= DNS_IPv4_A
;
4608 data
->ipv6_request
.type
= DNS_IPv6_AAAA
;
4610 data
->user_data
= arg
;
4611 data
->evdns_base
= dns_base
;
4613 want_cname
= (hints
.ai_flags
& EVUTIL_AI_CANONNAME
);
4615 /* If we are asked for a PF_UNSPEC address, we launch two requests in
4616 * parallel: one for an A address and one for an AAAA address. We
4617 * can't send just one request, since many servers only answer one
4618 * question per DNS request.
4620 * Once we have the answer to one request, we allow for a short
4621 * timeout before we report it, to see if the other one arrives. If
4622 * they both show up in time, then we report both the answers.
4624 * If too many addresses of one type time out or fail, we should stop
4625 * launching those requests. (XXX we don't do that yet.)
4628 if (hints
.ai_family
!= PF_INET6
) {
4629 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv4 as %p",
4630 nodename
, &data
->ipv4_request
);
4632 data
->ipv4_request
.r
= evdns_base_resolve_ipv4(dns_base
,
4633 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4634 &data
->ipv4_request
);
4636 data
->ipv4_request
.r
->current_req
->put_cname_in_ptr
=
4637 &data
->cname_result
;
4639 if (hints
.ai_family
!= PF_INET
) {
4640 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv6 as %p",
4641 nodename
, &data
->ipv6_request
);
4643 data
->ipv6_request
.r
= evdns_base_resolve_ipv6(dns_base
,
4644 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4645 &data
->ipv6_request
);
4647 data
->ipv6_request
.r
->current_req
->put_cname_in_ptr
=
4648 &data
->cname_result
;
4651 evtimer_assign(&data
->timeout
, dns_base
->event_base
,
4652 evdns_getaddrinfo_timeout_cb
, data
);
4654 if (data
->ipv4_request
.r
|| data
->ipv6_request
.r
) {
4658 cb(EVUTIL_EAI_FAIL
, NULL
, arg
);
4664 evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request
*data
)
4666 EVDNS_LOCK(data
->evdns_base
);
4667 if (data
->request_done
) {
4668 EVDNS_UNLOCK(data
->evdns_base
);
4671 event_del(&data
->timeout
);
4672 data
->user_canceled
= 1;
4673 if (data
->ipv4_request
.r
)
4674 evdns_cancel_request(data
->evdns_base
, data
->ipv4_request
.r
);
4675 if (data
->ipv6_request
.r
)
4676 evdns_cancel_request(data
->evdns_base
, data
->ipv6_request
.r
);
4677 EVDNS_UNLOCK(data
->evdns_base
);