1 /* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */
3 /* The original version of this module was written by Adam Langley; for
4 * a history of modifications, check out the subversion logs.
6 * When editing this module, try to keep it re-mergeable by Adam. Don't
7 * reformat the whitespace, add Tor dependencies, or so on.
10 * - Support IPv6 and PTR records.
11 * - Replace all externally visible magic numbers with #defined constants.
12 * - Write documentation for APIs of all external functions.
16 * Adam Langley <agl@imperialviolet.org>
17 * http://www.imperialviolet.org/eventdns.html
20 * This software is Public Domain. To view a copy of the public domain dedication,
21 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
22 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
24 * I ask and expect, but do not require, that all derivative works contain an
25 * attribution similar to:
26 * Parts developed by Adam Langley <agl@imperialviolet.org>
28 * You may wish to replace the word "Parts" with something else depending on
29 * the amount of original code.
31 * (Derivative works does not include programs which link against, run or include
32 * the source verbatim in their source distributions)
37 #include <sys/types.h>
38 #include "event2/event-config.h"
40 #ifndef _FORTIFY_SOURCE
41 #define _FORTIFY_SOURCE 3
46 #ifdef _EVENT_HAVE_SYS_TIME_H
49 #ifdef _EVENT_HAVE_STDINT_H
55 #ifdef _EVENT_HAVE_UNISTD_H
66 #define _WIN32_IE 0x400
71 #include "event2/dns.h"
72 #include "event2/dns_struct.h"
73 #include "event2/dns_compat.h"
74 #include "event2/util.h"
75 #include "event2/event.h"
76 #include "event2/event_struct.h"
77 #include "event2/thread.h"
79 #include "event2/bufferevent.h"
80 #include "event2/bufferevent_struct.h"
81 #include "bufferevent-internal.h"
83 #include "defer-internal.h"
84 #include "log-internal.h"
85 #include "mm-internal.h"
86 #include "strlcpy-internal.h"
87 #include "ipv6-internal.h"
88 #include "util-internal.h"
89 #include "evthread-internal.h"
97 #include <sys/socket.h>
98 #include <netinet/in.h>
99 #include <arpa/inet.h>
102 #ifdef _EVENT_HAVE_NETINET_IN6_H
103 #include <netinet/in6.h>
106 #define EVDNS_LOG_DEBUG 0
107 #define EVDNS_LOG_WARN 1
108 #define EVDNS_LOG_MSG 2
110 #ifndef HOST_NAME_MAX
111 #define HOST_NAME_MAX 255
117 #define MIN(a,b) ((a)<(b)?(a):(b))
119 #define ASSERT_VALID_REQUEST(req) \
120 EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
122 #define u64 ev_uint64_t
123 #define u32 ev_uint32_t
124 #define u16 ev_uint16_t
125 #define u8 ev_uint8_t
127 /* maximum number of addresses from a single packet */
128 /* that we bother recording */
129 #define MAX_V4_ADDRS 32
130 #define MAX_V6_ADDRS 32
133 #define TYPE_A EVDNS_TYPE_A
135 #define TYPE_PTR EVDNS_TYPE_PTR
136 #define TYPE_AAAA EVDNS_TYPE_AAAA
138 #define CLASS_INET EVDNS_CLASS_INET
140 /* Persistent handle. We keep this separate from 'struct request' since we
141 * need some object to last for as long as an evdns_request is outstanding so
142 * that it can be canceled, whereas a search request can lead to multiple
143 * 'struct request' instances being created over its lifetime. */
144 struct evdns_request
{
145 struct request
*current_req
;
146 struct evdns_base
*base
;
148 int pending_cb
; /* Waiting for its callback to be invoked; not
149 * owned by event base any more. */
151 /* elements used by the searching code */
153 struct search_state
*search_state
;
154 char *search_origname
; /* needs to be free()ed */
159 u8
*request
; /* the dns packet data */
160 u8 request_type
; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
161 unsigned int request_len
;
163 int tx_count
; /* the number of times that this packet has been sent */
164 void *user_pointer
; /* the pointer given to us for this request */
165 evdns_callback_type user_callback
;
166 struct nameserver
*ns
; /* the server which we last sent it */
168 /* these objects are kept in a circular list */
169 struct request
*next
, *prev
;
171 struct event timeout_event
;
173 u16 trans_id
; /* the transaction id */
174 unsigned request_appended
:1; /* true if the request pointer is data which follows this struct */
175 unsigned transmit_me
:1; /* needs to be transmitted */
177 /* XXXX This is a horrible hack. */
178 char **put_cname_in_ptr
; /* store the cname here if we get one. */
180 struct evdns_base
*base
;
182 struct evdns_request
*handle
;
187 unsigned int have_answer
: 1;
191 u32 addresses
[MAX_V4_ADDRS
];
195 struct in6_addr addresses
[MAX_V6_ADDRS
];
198 char name
[HOST_NAME_MAX
];
204 evutil_socket_t socket
; /* a connected UDP socket */
205 struct sockaddr_storage address
;
206 ev_socklen_t addrlen
;
207 int failed_times
; /* number of times which we have given this server a chance */
208 int timedout
; /* number of times in a row a request has timed out */
210 /* these objects are kept in a circular list */
211 struct nameserver
*next
, *prev
;
212 struct event timeout_event
; /* used to keep the timeout for */
213 /* when we next probe this server. */
214 /* Valid if state == 0 */
215 /* Outstanding probe request for this nameserver, if any */
216 struct evdns_request
*probe_request
;
217 char state
; /* zero if we think that this server is down */
218 char choked
; /* true if we have an EAGAIN from this server's socket */
219 char write_waiting
; /* true if we are waiting for EV_WRITE events */
220 struct evdns_base
*base
;
224 /* Represents a local port where we're listening for DNS requests. Right now, */
225 /* only UDP is supported. */
226 struct evdns_server_port
{
227 evutil_socket_t socket
; /* socket we use to read queries and write replies. */
228 int refcnt
; /* reference count. */
229 char choked
; /* Are we currently blocked from writing? */
230 char closing
; /* Are we trying to close this port, pending writes? */
231 evdns_request_callback_fn_type user_callback
; /* Fn to handle requests */
232 void *user_data
; /* Opaque pointer passed to user_callback */
233 struct event event
; /* Read/write event */
234 /* circular list of replies that we want to write. */
235 struct server_request
*pending_replies
;
236 struct event_base
*event_base
;
238 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
243 /* Represents part of a reply being built. (That is, a single RR.) */
244 struct server_reply_item
{
245 struct server_reply_item
*next
; /* next item in sequence. */
246 char *name
; /* name part of the RR */
247 u16 type
; /* The RR type */
248 u16
class; /* The RR class (usually CLASS_INET) */
249 u32 ttl
; /* The RR TTL */
250 char is_name
; /* True iff data is a label */
251 u16 datalen
; /* Length of data; -1 if data is a label */
252 void *data
; /* The contents of the RR */
255 /* Represents a request that we've received as a DNS server, and holds */
256 /* the components of the reply as we're constructing it. */
257 struct server_request
{
258 /* Pointers to the next and previous entries on the list of replies */
259 /* that we're waiting to write. Only set if we have tried to respond */
260 /* and gotten EAGAIN. */
261 struct server_request
*next_pending
;
262 struct server_request
*prev_pending
;
264 u16 trans_id
; /* Transaction id. */
265 struct evdns_server_port
*port
; /* Which port received this request on? */
266 struct sockaddr_storage addr
; /* Where to send the response */
267 ev_socklen_t addrlen
; /* length of addr */
269 int n_answer
; /* how many answer RRs have been set? */
270 int n_authority
; /* how many authority RRs have been set? */
271 int n_additional
; /* how many additional RRs have been set? */
273 struct server_reply_item
*answer
; /* linked list of answer RRs */
274 struct server_reply_item
*authority
; /* linked list of authority RRs */
275 struct server_reply_item
*additional
; /* linked list of additional RRs */
277 /* Constructed response. Only set once we're ready to send a reply. */
278 /* Once this is set, the RR fields are cleared, and no more should be set. */
282 /* Caller-visible fields: flags, questions. */
283 struct evdns_server_request base
;
287 /* An array of n_req_heads circular lists for inflight requests.
288 * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
290 struct request
**req_heads
;
291 /* A circular list of requests that we're waiting to send, but haven't
292 * sent yet because there are too many requests inflight */
293 struct request
*req_waiting_head
;
294 /* A circular list of nameservers. */
295 struct nameserver
*server_head
;
298 struct event_base
*event_base
;
300 /* The number of good nameservers that we have */
301 int global_good_nameservers
;
303 /* inflight requests are contained in the req_head list */
304 /* and are actually going out across the network */
305 int global_requests_inflight
;
306 /* requests which aren't inflight are in the waiting list */
307 /* and are counted here */
308 int global_requests_waiting
;
310 int global_max_requests_inflight
;
312 struct timeval global_timeout
; /* 5 seconds by default */
313 int global_max_reissues
; /* a reissue occurs when we get some errors from the server */
314 int global_max_retransmits
; /* number of times we'll retransmit a request which timed out */
315 /* number of timeouts in a row before we consider this server to be down */
316 int global_max_nameserver_timeout
;
317 /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
318 int global_randomize_case
;
320 /* The first time that a nameserver fails, how long do we wait before
321 * probing to see if it has returned? */
322 struct timeval global_nameserver_probe_initial_timeout
;
324 /** Port to bind to for outgoing DNS packets. */
325 struct sockaddr_storage global_outgoing_address
;
326 /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
327 ev_socklen_t global_outgoing_addrlen
;
329 struct timeval global_getaddrinfo_allow_skew
;
331 int getaddrinfo_ipv4_timeouts
;
332 int getaddrinfo_ipv6_timeouts
;
333 int getaddrinfo_ipv4_answered
;
334 int getaddrinfo_ipv6_answered
;
336 struct search_state
*global_search_state
;
338 TAILQ_HEAD(hosts_list
, hosts_entry
) hostsdb
;
340 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
346 TAILQ_ENTRY(hosts_entry
) next
;
349 struct sockaddr_in sin
;
350 struct sockaddr_in6 sin6
;
356 static struct evdns_base
*current_base
= NULL
;
359 evdns_get_global_base(void)
364 /* Given a pointer to an evdns_server_request, get the corresponding */
365 /* server_request. */
366 #define TO_SERVER_REQUEST(base_ptr) \
367 ((struct server_request*) \
368 (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
370 #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
372 static struct nameserver
*nameserver_pick(struct evdns_base
*base
);
373 static void evdns_request_insert(struct request
*req
, struct request
**head
);
374 static void evdns_request_remove(struct request
*req
, struct request
**head
);
375 static void nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
376 static int evdns_transmit(struct evdns_base
*base
);
377 static int evdns_request_transmit(struct request
*req
);
378 static void nameserver_send_probe(struct nameserver
*const ns
);
379 static void search_request_finished(struct evdns_request
*const);
380 static int search_try_next(struct evdns_request
*const req
);
381 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
);
382 static void evdns_requests_pump_waiting_queue(struct evdns_base
*base
);
383 static u16
transaction_id_pick(struct evdns_base
*base
);
384 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
);
385 static void request_submit(struct request
*const req
);
387 static int server_request_free(struct server_request
*req
);
388 static void server_request_free_answers(struct server_request
*req
);
389 static void server_port_free(struct evdns_server_port
*port
);
390 static void server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
391 static int evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
);
392 static int evdns_base_set_option_impl(struct evdns_base
*base
,
393 const char *option
, const char *val
, int flags
);
394 static void evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
);
396 static int strtoint(const char *const str
);
398 #ifdef _EVENT_DISABLE_THREAD_SUPPORT
399 #define EVDNS_LOCK(base) _EVUTIL_NIL_STMT
400 #define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT
401 #define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT
403 #define EVDNS_LOCK(base) \
404 EVLOCK_LOCK((base)->lock, 0)
405 #define EVDNS_UNLOCK(base) \
406 EVLOCK_UNLOCK((base)->lock, 0)
407 #define ASSERT_LOCKED(base) \
408 EVLOCK_ASSERT_LOCKED((base)->lock)
412 default_evdns_log_fn(int warning
, const char *buf
)
414 if (warning
== EVDNS_LOG_WARN
)
415 event_warnx("[evdns] %s", buf
);
416 else if (warning
== EVDNS_LOG_MSG
)
417 event_msgx("[evdns] %s", buf
);
419 event_debug(("[evdns] %s", buf
));
422 static evdns_debug_log_fn_type evdns_log_fn
= NULL
;
425 evdns_set_log_fn(evdns_debug_log_fn_type fn
)
431 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
433 #define EVDNS_LOG_CHECK
436 static void _evdns_log(int warn
, const char *fmt
, ...) EVDNS_LOG_CHECK
;
438 _evdns_log(int warn
, const char *fmt
, ...)
445 evutil_vsnprintf(buf
, sizeof(buf
), fmt
, args
);
448 if (warn
== EVDNS_LOG_MSG
)
449 warn
= EVDNS_LOG_WARN
;
450 evdns_log_fn(warn
, buf
);
452 default_evdns_log_fn(warn
, buf
);
457 #define log _evdns_log
459 /* This walks the list of inflight requests to find the */
460 /* one with a matching transaction id. Returns NULL on */
462 static struct request
*
463 request_find_from_trans_id(struct evdns_base
*base
, u16 trans_id
) {
464 struct request
*req
= REQ_HEAD(base
, trans_id
);
465 struct request
*const started_at
= req
;
471 if (req
->trans_id
== trans_id
) return req
;
473 } while (req
!= started_at
);
479 /* a libevent callback function which is called when a nameserver */
480 /* has gone down and we want to test if it has came back to life yet */
482 nameserver_prod_callback(evutil_socket_t fd
, short events
, void *arg
) {
483 struct nameserver
*const ns
= (struct nameserver
*) arg
;
487 EVDNS_LOCK(ns
->base
);
488 nameserver_send_probe(ns
);
489 EVDNS_UNLOCK(ns
->base
);
492 /* a libevent callback which is called when a nameserver probe (to see if */
493 /* it has come back to life) times out. We increment the count of failed_times */
494 /* and wait longer to send the next probe packet. */
496 nameserver_probe_failed(struct nameserver
*const ns
) {
497 struct timeval timeout
;
500 ASSERT_LOCKED(ns
->base
);
501 (void) evtimer_del(&ns
->timeout_event
);
502 if (ns
->state
== 1) {
503 /* This can happen if the nameserver acts in a way which makes us mark */
504 /* it as bad and then starts sending good replies. */
508 #define MAX_PROBE_TIMEOUT 3600
509 #define TIMEOUT_BACKOFF_FACTOR 3
511 memcpy(&timeout
, &ns
->base
->global_nameserver_probe_initial_timeout
,
512 sizeof(struct timeval
));
513 for (i
=ns
->failed_times
; i
> 0 && timeout
.tv_sec
< MAX_PROBE_TIMEOUT
; --i
) {
514 timeout
.tv_sec
*= TIMEOUT_BACKOFF_FACTOR
;
515 timeout
.tv_usec
*= TIMEOUT_BACKOFF_FACTOR
;
516 if (timeout
.tv_usec
> 1000000) {
517 timeout
.tv_sec
+= timeout
.tv_usec
/ 1000000;
518 timeout
.tv_usec
%= 1000000;
521 if (timeout
.tv_sec
> MAX_PROBE_TIMEOUT
) {
522 timeout
.tv_sec
= MAX_PROBE_TIMEOUT
;
528 if (evtimer_add(&ns
->timeout_event
, &timeout
) < 0) {
531 "Error from libevent when adding timer event for %s",
532 evutil_format_sockaddr_port(
533 (struct sockaddr
*)&ns
->address
,
534 addrbuf
, sizeof(addrbuf
)));
538 /* called when a nameserver has been deemed to have failed. For example, too */
539 /* many packets have timed out etc */
541 nameserver_failed(struct nameserver
*const ns
, const char *msg
) {
542 struct request
*req
, *started_at
;
543 struct evdns_base
*base
= ns
->base
;
548 /* if this nameserver has already been marked as failed */
549 /* then don't do anything */
550 if (!ns
->state
) return;
552 log(EVDNS_LOG_MSG
, "Nameserver %s has failed: %s",
553 evutil_format_sockaddr_port(
554 (struct sockaddr
*)&ns
->address
,
555 addrbuf
, sizeof(addrbuf
)),
558 base
->global_good_nameservers
--;
559 EVUTIL_ASSERT(base
->global_good_nameservers
>= 0);
560 if (base
->global_good_nameservers
== 0) {
561 log(EVDNS_LOG_MSG
, "All nameservers have failed");
565 ns
->failed_times
= 1;
567 if (evtimer_add(&ns
->timeout_event
,
568 &base
->global_nameserver_probe_initial_timeout
) < 0) {
570 "Error from libevent when adding timer event for %s",
571 evutil_format_sockaddr_port(
572 (struct sockaddr
*)&ns
->address
,
573 addrbuf
, sizeof(addrbuf
)));
577 /* walk the list of inflight requests to see if any can be reassigned to */
578 /* a different server. Requests in the waiting queue don't have a */
579 /* nameserver assigned yet */
581 /* if we don't have *any* good nameservers then there's no point */
582 /* trying to reassign requests to one */
583 if (!base
->global_good_nameservers
) return;
585 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
586 req
= started_at
= base
->req_heads
[i
];
589 if (req
->tx_count
== 0 && req
->ns
== ns
) {
590 /* still waiting to go out, can be moved */
591 /* to another server */
592 req
->ns
= nameserver_pick(base
);
595 } while (req
!= started_at
);
601 nameserver_up(struct nameserver
*const ns
)
604 ASSERT_LOCKED(ns
->base
);
605 if (ns
->state
) return;
606 log(EVDNS_LOG_MSG
, "Nameserver %s is back up",
607 evutil_format_sockaddr_port(
608 (struct sockaddr
*)&ns
->address
,
609 addrbuf
, sizeof(addrbuf
)));
610 evtimer_del(&ns
->timeout_event
);
611 if (ns
->probe_request
) {
612 evdns_cancel_request(ns
->base
, ns
->probe_request
);
613 ns
->probe_request
= NULL
;
616 ns
->failed_times
= 0;
618 ns
->base
->global_good_nameservers
++;
622 request_trans_id_set(struct request
*const req
, const u16 trans_id
) {
623 req
->trans_id
= trans_id
;
624 *((u16
*) req
->request
) = htons(trans_id
);
627 /* Called to remove a request from a list and dealloc it. */
628 /* head is a pointer to the head of the list it should be */
629 /* removed from or NULL if the request isn't in a list. */
630 /* when free_handle is one, free the handle as well. */
632 request_finished(struct request
*const req
, struct request
**head
, int free_handle
) {
633 struct evdns_base
*base
= req
->base
;
634 int was_inflight
= (head
!= &base
->req_waiting_head
);
636 ASSERT_VALID_REQUEST(req
);
639 evdns_request_remove(req
, head
);
641 log(EVDNS_LOG_DEBUG
, "Removing timeout for request %p", req
);
643 evtimer_del(&req
->timeout_event
);
644 base
->global_requests_inflight
--;
646 base
->global_requests_waiting
--;
649 if (!req
->request_appended
) {
650 /* need to free the request data on it's own */
651 mm_free(req
->request
);
653 /* the request data is appended onto the header */
654 /* so everything gets free()ed when we: */
658 EVUTIL_ASSERT(req
->handle
->current_req
== req
);
661 search_request_finished(req
->handle
);
662 req
->handle
->current_req
= NULL
;
663 if (! req
->handle
->pending_cb
) {
664 /* If we're planning to run the callback,
665 * don't free the handle until later. */
666 mm_free(req
->handle
);
668 req
->handle
= NULL
; /* If we have a bug, let's crash
671 req
->handle
->current_req
= NULL
;
677 evdns_requests_pump_waiting_queue(base
);
681 /* This is called when a server returns a funny error code. */
682 /* We try the request again with another server. */
686 /* 1 failed/reissue is pointless */
688 request_reissue(struct request
*req
) {
689 const struct nameserver
*const last_ns
= req
->ns
;
690 ASSERT_LOCKED(req
->base
);
691 ASSERT_VALID_REQUEST(req
);
692 /* the last nameserver should have been marked as failing */
693 /* by the caller of this function, therefore pick will try */
694 /* not to return it */
695 req
->ns
= nameserver_pick(req
->base
);
696 if (req
->ns
== last_ns
) {
697 /* ... but pick did return it */
698 /* not a lot of point in trying again with the */
703 req
->reissue_count
++;
705 req
->transmit_me
= 1;
710 /* this function looks for space on the inflight queue and promotes */
711 /* requests from the waiting queue if it can. */
713 evdns_requests_pump_waiting_queue(struct evdns_base
*base
) {
715 while (base
->global_requests_inflight
< base
->global_max_requests_inflight
&&
716 base
->global_requests_waiting
) {
718 /* move a request from the waiting queue to the inflight queue */
719 EVUTIL_ASSERT(base
->req_waiting_head
);
720 req
= base
->req_waiting_head
;
721 evdns_request_remove(req
, &base
->req_waiting_head
);
723 base
->global_requests_waiting
--;
724 base
->global_requests_inflight
++;
726 req
->ns
= nameserver_pick(base
);
727 request_trans_id_set(req
, transaction_id_pick(base
));
729 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
730 evdns_request_transmit(req
);
731 evdns_transmit(base
);
735 /* TODO(nickm) document */
736 struct deferred_reply_callback
{
737 struct deferred_cb deferred
;
738 struct evdns_request
*handle
;
743 evdns_callback_type user_callback
;
748 reply_run_callback(struct deferred_cb
*d
, void *user_pointer
)
750 struct deferred_reply_callback
*cb
=
751 EVUTIL_UPCAST(d
, struct deferred_reply_callback
, deferred
);
753 switch (cb
->request_type
) {
756 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv4_A
,
757 cb
->reply
.data
.a
.addrcount
, cb
->ttl
,
758 cb
->reply
.data
.a
.addresses
,
761 cb
->user_callback(cb
->err
, 0, 0, 0, NULL
, user_pointer
);
764 if (cb
->have_reply
) {
765 char *name
= cb
->reply
.data
.ptr
.name
;
766 cb
->user_callback(DNS_ERR_NONE
, DNS_PTR
, 1, cb
->ttl
,
767 &name
, user_pointer
);
769 cb
->user_callback(cb
->err
, 0, 0, 0, NULL
, user_pointer
);
774 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv6_AAAA
,
775 cb
->reply
.data
.aaaa
.addrcount
, cb
->ttl
,
776 cb
->reply
.data
.aaaa
.addresses
,
779 cb
->user_callback(cb
->err
, 0, 0, 0, NULL
, user_pointer
);
785 if (cb
->handle
&& cb
->handle
->pending_cb
) {
793 reply_schedule_callback(struct request
*const req
, u32 ttl
, u32 err
, struct reply
*reply
)
795 struct deferred_reply_callback
*d
= mm_calloc(1, sizeof(*d
));
798 event_warn("%s: Couldn't allocate space for deferred callback.",
803 ASSERT_LOCKED(req
->base
);
805 d
->request_type
= req
->request_type
;
806 d
->user_callback
= req
->user_callback
;
811 memcpy(&d
->reply
, reply
, sizeof(struct reply
));
815 req
->handle
->pending_cb
= 1;
816 d
->handle
= req
->handle
;
819 event_deferred_cb_init(&d
->deferred
, reply_run_callback
,
821 event_deferred_cb_schedule(
822 event_base_get_deferred_cb_queue(req
->base
->event_base
),
826 /* this processes a parsed reply packet */
828 reply_handle(struct request
*const req
, u16 flags
, u32 ttl
, struct reply
*reply
) {
831 static const int error_codes
[] = {
832 DNS_ERR_FORMAT
, DNS_ERR_SERVERFAILED
, DNS_ERR_NOTEXIST
,
833 DNS_ERR_NOTIMPL
, DNS_ERR_REFUSED
836 ASSERT_LOCKED(req
->base
);
837 ASSERT_VALID_REQUEST(req
);
839 if (flags
& 0x020f || !reply
|| !reply
->have_answer
) {
840 /* there was an error */
841 if (flags
& 0x0200) {
842 error
= DNS_ERR_TRUNCATED
;
844 u16 error_code
= (flags
& 0x000f) - 1;
845 if (error_code
> 4) {
846 error
= DNS_ERR_UNKNOWN
;
848 error
= error_codes
[error_code
];
853 case DNS_ERR_NOTIMPL
:
854 case DNS_ERR_REFUSED
:
855 /* we regard these errors as marking a bad nameserver */
856 if (req
->reissue_count
< req
->base
->global_max_reissues
) {
858 evutil_snprintf(msg
, sizeof(msg
), "Bad response %d (%s)",
859 error
, evdns_err_to_string(error
));
860 nameserver_failed(req
->ns
, msg
);
861 if (!request_reissue(req
)) return;
864 case DNS_ERR_SERVERFAILED
:
865 /* rcode 2 (servfailed) sometimes means "we
866 * are broken" and sometimes (with some binds)
867 * means "that request was very confusing."
868 * Treat this as a timeout, not a failure.
870 log(EVDNS_LOG_DEBUG
, "Got a SERVERFAILED from nameserver"
871 "at %s; will allow the request to time out.",
872 evutil_format_sockaddr_port(
873 (struct sockaddr
*)&req
->ns
->address
,
874 addrbuf
, sizeof(addrbuf
)));
877 /* we got a good reply from the nameserver */
878 nameserver_up(req
->ns
);
881 if (req
->handle
->search_state
&&
882 req
->request_type
!= TYPE_PTR
) {
883 /* if we have a list of domains to search in,
884 * try the next one */
885 if (!search_try_next(req
->handle
)) {
886 /* a new request was issued so this
887 * request is finished and */
888 /* the user callback will be made when
889 * that request (or a */
890 /* child of it) finishes. */
895 /* all else failed. Pass the failure up */
896 reply_schedule_callback(req
, 0, error
, NULL
);
897 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
899 /* all ok, tell the user */
900 reply_schedule_callback(req
, ttl
, 0, reply
);
901 if (req
->handle
== req
->ns
->probe_request
)
902 req
->ns
->probe_request
= NULL
; /* Avoid double-free */
903 nameserver_up(req
->ns
);
904 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
909 name_parse(u8
*packet
, int length
, int *idx
, char *name_out
, int name_out_len
) {
913 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (0)
914 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (0)
915 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
918 const char *const end
= name_out
+ name_out_len
;
920 /* Normally, names are a series of length prefixed strings terminated */
921 /* with a length of 0 (the lengths are u8's < 63). */
922 /* However, the length can start with a pair of 1 bits and that */
923 /* means that the next 14 bits are a pointer within the current */
928 if (j
>= length
) return -1;
930 if (!label_len
) break;
931 if (label_len
& 0xc0) {
934 if (name_end
< 0) name_end
= j
;
935 j
= (((int)label_len
& 0x3f) << 8) + ptr_low
;
936 /* Make sure that the target offset is in-bounds. */
937 if (j
< 0 || j
>= length
) return -1;
938 /* If we've jumped more times than there are characters in the
939 * message, we must have a loop. */
940 if (++ptr_count
> length
) return -1;
943 if (label_len
> 63) return -1;
944 if (cp
!= name_out
) {
945 if (cp
+ 1 >= end
) return -1;
948 if (cp
+ label_len
>= end
) return -1;
949 memcpy(cp
, packet
+ j
, label_len
);
953 if (cp
>= end
) return -1;
964 /* parses a raw request from a nameserver */
966 reply_parse(struct evdns_base
*base
, u8
*packet
, int length
) {
967 int j
= 0, k
= 0; /* index into packet */
968 u16 _t
; /* used by the macros */
969 u32 _t32
; /* used by the macros */
970 char tmp_name
[256], cmp_name
[256]; /* used by the macros */
971 int name_matches
= 0;
973 u16 trans_id
, questions
, answers
, authority
, additional
, datalength
;
975 u32 ttl
, ttl_r
= 0xffffffff;
977 struct request
*req
= NULL
;
988 (void) authority
; /* suppress "unused variable" warnings. */
989 (void) additional
; /* suppress "unused variable" warnings. */
991 req
= request_find_from_trans_id(base
, trans_id
);
993 EVUTIL_ASSERT(req
->base
== base
);
995 memset(&reply
, 0, sizeof(reply
));
997 /* If it's not an answer, it doesn't correspond to any request. */
998 if (!(flags
& 0x8000)) return -1; /* must be an answer */
999 if (flags
& 0x020f) {
1000 /* there was an error */
1003 /* if (!answers) return; */ /* must have an answer of some form */
1005 /* This macro skips a name in the DNS reply. */
1007 do { tmp_name[0] = '\0'; \
1008 if (name_parse(packet, length, &j, tmp_name, \
1009 sizeof(tmp_name))<0) \
1013 do { tmp_name[0] = '\0'; \
1014 cmp_name[0] = '\0'; \
1016 if (name_parse(packet, length, &j, tmp_name, \
1017 sizeof(tmp_name))<0) \
1019 if (name_parse(req->request, req->request_len, &k, \
1020 cmp_name, sizeof(cmp_name))<0) \
1022 if (base->global_randomize_case) { \
1023 if (strcmp(tmp_name, cmp_name) == 0) \
1026 if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0) \
1031 reply
.type
= req
->request_type
;
1033 /* skip over each question in the reply */
1034 for (i
= 0; i
< questions
; ++i
) {
1035 /* the question looks like
1036 * <label:name><u16:type><u16:class>
1040 if (j
>= length
) goto err
;
1046 /* now we have the answer section which looks like
1047 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
1050 for (i
= 0; i
< answers
; ++i
) {
1059 if (type
== TYPE_A
&& class == CLASS_INET
) {
1060 int addrcount
, addrtocopy
;
1061 if (req
->request_type
!= TYPE_A
) {
1062 j
+= datalength
; continue;
1064 if ((datalength
& 3) != 0) /* not an even number of As. */
1066 addrcount
= datalength
>> 2;
1067 addrtocopy
= MIN(MAX_V4_ADDRS
- reply
.data
.a
.addrcount
, (unsigned)addrcount
);
1069 ttl_r
= MIN(ttl_r
, ttl
);
1070 /* we only bother with the first four addresses. */
1071 if (j
+ 4*addrtocopy
> length
) goto err
;
1072 memcpy(&reply
.data
.a
.addresses
[reply
.data
.a
.addrcount
],
1073 packet
+ j
, 4*addrtocopy
);
1075 reply
.data
.a
.addrcount
+= addrtocopy
;
1076 reply
.have_answer
= 1;
1077 if (reply
.data
.a
.addrcount
== MAX_V4_ADDRS
) break;
1078 } else if (type
== TYPE_PTR
&& class == CLASS_INET
) {
1079 if (req
->request_type
!= TYPE_PTR
) {
1080 j
+= datalength
; continue;
1082 if (name_parse(packet
, length
, &j
, reply
.data
.ptr
.name
,
1083 sizeof(reply
.data
.ptr
.name
))<0)
1085 ttl_r
= MIN(ttl_r
, ttl
);
1086 reply
.have_answer
= 1;
1088 } else if (type
== TYPE_CNAME
) {
1089 char cname
[HOST_NAME_MAX
];
1090 if (!req
->put_cname_in_ptr
|| *req
->put_cname_in_ptr
) {
1091 j
+= datalength
; continue;
1093 if (name_parse(packet
, length
, &j
, cname
,
1096 *req
->put_cname_in_ptr
= mm_strdup(cname
);
1097 } else if (type
== TYPE_AAAA
&& class == CLASS_INET
) {
1098 int addrcount
, addrtocopy
;
1099 if (req
->request_type
!= TYPE_AAAA
) {
1100 j
+= datalength
; continue;
1102 if ((datalength
& 15) != 0) /* not an even number of AAAAs. */
1104 addrcount
= datalength
>> 4; /* each address is 16 bytes long */
1105 addrtocopy
= MIN(MAX_V6_ADDRS
- reply
.data
.aaaa
.addrcount
, (unsigned)addrcount
);
1106 ttl_r
= MIN(ttl_r
, ttl
);
1108 /* we only bother with the first four addresses. */
1109 if (j
+ 16*addrtocopy
> length
) goto err
;
1110 memcpy(&reply
.data
.aaaa
.addresses
[reply
.data
.aaaa
.addrcount
],
1111 packet
+ j
, 16*addrtocopy
);
1112 reply
.data
.aaaa
.addrcount
+= addrtocopy
;
1114 reply
.have_answer
= 1;
1115 if (reply
.data
.aaaa
.addrcount
== MAX_V6_ADDRS
) break;
1117 /* skip over any other type of resource */
1122 reply_handle(req
, flags
, ttl_r
, &reply
);
1126 reply_handle(req
, flags
, 0, NULL
);
1130 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1131 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1134 request_parse(u8
*packet
, int length
, struct evdns_server_port
*port
, struct sockaddr
*addr
, ev_socklen_t addrlen
)
1136 int j
= 0; /* index into packet */
1137 u16 _t
; /* used by the macros */
1138 char tmp_name
[256]; /* used by the macros */
1141 u16 trans_id
, flags
, questions
, answers
, authority
, additional
;
1142 struct server_request
*server_req
= NULL
;
1144 ASSERT_LOCKED(port
);
1146 /* Get the header fields */
1154 if (flags
& 0x8000) return -1; /* Must not be an answer. */
1155 flags
&= 0x0110; /* Only RD and CD get preserved. */
1157 server_req
= mm_malloc(sizeof(struct server_request
));
1158 if (server_req
== NULL
) return -1;
1159 memset(server_req
, 0, sizeof(struct server_request
));
1161 server_req
->trans_id
= trans_id
;
1162 memcpy(&server_req
->addr
, addr
, addrlen
);
1163 server_req
->addrlen
= addrlen
;
1165 server_req
->base
.flags
= flags
;
1166 server_req
->base
.nquestions
= 0;
1167 server_req
->base
.questions
= mm_calloc(sizeof(struct evdns_server_question
*), questions
);
1168 if (server_req
->base
.questions
== NULL
)
1171 for (i
= 0; i
< questions
; ++i
) {
1173 struct evdns_server_question
*q
;
1175 if (name_parse(packet
, length
, &j
, tmp_name
, sizeof(tmp_name
))<0)
1179 namelen
= (int)strlen(tmp_name
);
1180 q
= mm_malloc(sizeof(struct evdns_server_question
) + namelen
);
1184 q
->dns_question_class
= class;
1185 memcpy(q
->name
, tmp_name
, namelen
+1);
1186 server_req
->base
.questions
[server_req
->base
.nquestions
++] = q
;
1189 /* Ignore answers, authority, and additional. */
1191 server_req
->port
= port
;
1194 /* Only standard queries are supported. */
1195 if (flags
& 0x7800) {
1196 evdns_server_request_respond(&(server_req
->base
), DNS_ERR_NOTIMPL
);
1200 port
->user_callback(&(server_req
->base
), port
->user_data
);
1205 if (server_req
->base
.questions
) {
1206 for (i
= 0; i
< server_req
->base
.nquestions
; ++i
)
1207 mm_free(server_req
->base
.questions
[i
]);
1208 mm_free(server_req
->base
.questions
);
1210 mm_free(server_req
);
1222 evdns_set_transaction_id_fn(ev_uint16_t (*fn
)(void))
1227 evdns_set_random_bytes_fn(void (*fn
)(char *, size_t))
1231 /* Try to choose a strong transaction id which isn't already in flight */
1233 transaction_id_pick(struct evdns_base
*base
) {
1234 ASSERT_LOCKED(base
);
1237 evutil_secure_rng_get_bytes(&trans_id
, sizeof(trans_id
));
1239 if (trans_id
== 0xffff) continue;
1240 /* now check to see if that id is already inflight */
1241 if (request_find_from_trans_id(base
, trans_id
) == NULL
)
1246 /* choose a namesever to use. This function will try to ignore */
1247 /* nameservers which we think are down and load balance across the rest */
1248 /* by updating the server_head global each time. */
1249 static struct nameserver
*
1250 nameserver_pick(struct evdns_base
*base
) {
1251 struct nameserver
*started_at
= base
->server_head
, *picked
;
1252 ASSERT_LOCKED(base
);
1253 if (!base
->server_head
) return NULL
;
1255 /* if we don't have any good nameservers then there's no */
1256 /* point in trying to find one. */
1257 if (!base
->global_good_nameservers
) {
1258 base
->server_head
= base
->server_head
->next
;
1259 return base
->server_head
;
1262 /* remember that nameservers are in a circular list */
1264 if (base
->server_head
->state
) {
1265 /* we think this server is currently good */
1266 picked
= base
->server_head
;
1267 base
->server_head
= base
->server_head
->next
;
1271 base
->server_head
= base
->server_head
->next
;
1272 if (base
->server_head
== started_at
) {
1273 /* all the nameservers seem to be down */
1274 /* so we just return this one and hope for the */
1276 EVUTIL_ASSERT(base
->global_good_nameservers
== 0);
1277 picked
= base
->server_head
;
1278 base
->server_head
= base
->server_head
->next
;
1284 /* this is called when a namesever socket is ready for reading */
1286 nameserver_read(struct nameserver
*ns
) {
1287 struct sockaddr_storage ss
;
1288 ev_socklen_t addrlen
= sizeof(ss
);
1291 ASSERT_LOCKED(ns
->base
);
1294 const int r
= recvfrom(ns
->socket
, (void*)packet
,
1296 (struct sockaddr
*)&ss
, &addrlen
);
1298 int err
= evutil_socket_geterror(ns
->socket
);
1299 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1301 nameserver_failed(ns
,
1302 evutil_socket_error_to_string(err
));
1305 if (evutil_sockaddr_cmp((struct sockaddr
*)&ss
,
1306 (struct sockaddr
*)&ns
->address
, 0)) {
1307 log(EVDNS_LOG_WARN
, "Address mismatch on received "
1308 "DNS packet. Apparent source was %s",
1309 evutil_format_sockaddr_port(
1310 (struct sockaddr
*)&ss
,
1311 addrbuf
, sizeof(addrbuf
)));
1316 reply_parse(ns
->base
, packet
, r
);
1320 /* Read a packet from a DNS client on a server port s, parse it, and */
1321 /* act accordingly. */
1323 server_port_read(struct evdns_server_port
*s
) {
1325 struct sockaddr_storage addr
;
1326 ev_socklen_t addrlen
;
1331 addrlen
= sizeof(struct sockaddr_storage
);
1332 r
= recvfrom(s
->socket
, (void*)packet
, sizeof(packet
), 0,
1333 (struct sockaddr
*) &addr
, &addrlen
);
1335 int err
= evutil_socket_geterror(s
->socket
);
1336 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1339 "Error %s (%d) while reading request.",
1340 evutil_socket_error_to_string(err
), err
);
1343 request_parse(packet
, r
, s
, (struct sockaddr
*) &addr
, addrlen
);
1347 /* Try to write all pending replies on a given DNS server port. */
1349 server_port_flush(struct evdns_server_port
*port
)
1351 struct server_request
*req
= port
->pending_replies
;
1352 ASSERT_LOCKED(port
);
1354 int r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
1355 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
1357 int err
= evutil_socket_geterror(port
->socket
);
1358 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1360 log(EVDNS_LOG_WARN
, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err
), err
);
1362 if (server_request_free(req
)) {
1363 /* we released the last reference to req->port. */
1366 EVUTIL_ASSERT(req
!= port
->pending_replies
);
1367 req
= port
->pending_replies
;
1371 /* We have no more pending requests; stop listening for 'writeable' events. */
1372 (void) event_del(&port
->event
);
1373 event_assign(&port
->event
, port
->event_base
,
1374 port
->socket
, EV_READ
| EV_PERSIST
,
1375 server_port_ready_callback
, port
);
1377 if (event_add(&port
->event
, NULL
) < 0) {
1378 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server.");
1383 /* set if we are waiting for the ability to write to this server. */
1384 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1385 /* we stop these events. */
1387 nameserver_write_waiting(struct nameserver
*ns
, char waiting
) {
1388 ASSERT_LOCKED(ns
->base
);
1389 if (ns
->write_waiting
== waiting
) return;
1391 ns
->write_waiting
= waiting
;
1392 (void) event_del(&ns
->event
);
1393 event_assign(&ns
->event
, ns
->base
->event_base
,
1394 ns
->socket
, EV_READ
| (waiting
? EV_WRITE
: 0) | EV_PERSIST
,
1395 nameserver_ready_callback
, ns
);
1396 if (event_add(&ns
->event
, NULL
) < 0) {
1398 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for %s",
1399 evutil_format_sockaddr_port(
1400 (struct sockaddr
*)&ns
->address
,
1401 addrbuf
, sizeof(addrbuf
)));
1406 /* a callback function. Called by libevent when the kernel says that */
1407 /* a nameserver socket is ready for writing or reading */
1409 nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1410 struct nameserver
*ns
= (struct nameserver
*) arg
;
1413 EVDNS_LOCK(ns
->base
);
1414 if (events
& EV_WRITE
) {
1416 if (!evdns_transmit(ns
->base
)) {
1417 nameserver_write_waiting(ns
, 0);
1420 if (events
& EV_READ
) {
1421 nameserver_read(ns
);
1423 EVDNS_UNLOCK(ns
->base
);
1426 /* a callback function. Called by libevent when the kernel says that */
1427 /* a server socket is ready for writing or reading. */
1429 server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1430 struct evdns_server_port
*port
= (struct evdns_server_port
*) arg
;
1434 if (events
& EV_WRITE
) {
1436 server_port_flush(port
);
1438 if (events
& EV_READ
) {
1439 server_port_read(port
);
1444 /* This is an inefficient representation; only use it via the dnslabel_table_*
1445 * functions, so that is can be safely replaced with something smarter later. */
1446 #define MAX_LABELS 128
1447 /* Structures used to implement name compression */
1448 struct dnslabel_entry
{ char *v
; off_t pos
; };
1449 struct dnslabel_table
{
1450 int n_labels
; /* number of current entries */
1451 /* map from name to position in message */
1452 struct dnslabel_entry labels
[MAX_LABELS
];
1455 /* Initialize dnslabel_table. */
1457 dnslabel_table_init(struct dnslabel_table
*table
)
1459 table
->n_labels
= 0;
1462 /* Free all storage held by table, but not the table itself. */
1464 dnslabel_clear(struct dnslabel_table
*table
)
1467 for (i
= 0; i
< table
->n_labels
; ++i
)
1468 mm_free(table
->labels
[i
].v
);
1469 table
->n_labels
= 0;
1472 /* return the position of the label in the current message, or -1 if the label */
1473 /* hasn't been used yet. */
1475 dnslabel_table_get_pos(const struct dnslabel_table
*table
, const char *label
)
1478 for (i
= 0; i
< table
->n_labels
; ++i
) {
1479 if (!strcmp(label
, table
->labels
[i
].v
))
1480 return table
->labels
[i
].pos
;
1485 /* remember that we've used the label at position pos */
1487 dnslabel_table_add(struct dnslabel_table
*table
, const char *label
, off_t pos
)
1491 if (table
->n_labels
== MAX_LABELS
)
1493 v
= mm_strdup(label
);
1496 p
= table
->n_labels
++;
1497 table
->labels
[p
].v
= v
;
1498 table
->labels
[p
].pos
= pos
;
1503 /* Converts a string to a length-prefixed set of DNS labels, starting */
1504 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1505 /* of name. table is optional, and is used for compression. */
1507 /* Input: abc.def */
1508 /* Output: <3>abc<3>def<0> */
1510 /* Returns the first index after the encoded name, or negative on error. */
1511 /* -1 label was > 63 bytes */
1512 /* -2 name too long to fit in buffer. */
1515 dnsname_to_labels(u8
*const buf
, size_t buf_len
, off_t j
,
1516 const char *name
, const size_t name_len
,
1517 struct dnslabel_table
*table
) {
1518 const char *end
= name
+ name_len
;
1522 #define APPEND16(x) do { \
1523 if (j + 2 > (off_t)buf_len) \
1526 memcpy(buf + j, &_t, 2); \
1529 #define APPEND32(x) do { \
1530 if (j + 4 > (off_t)buf_len) \
1533 memcpy(buf + j, &_t32, 4); \
1537 if (name_len
> 255) return -2;
1540 const char *const start
= name
;
1541 if (table
&& (ref
= dnslabel_table_get_pos(table
, name
)) >= 0) {
1542 APPEND16(ref
| 0xc000);
1545 name
= strchr(name
, '.');
1547 const size_t label_len
= end
- start
;
1548 if (label_len
> 63) return -1;
1549 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1550 if (table
) dnslabel_table_add(table
, start
, j
);
1551 buf
[j
++] = (ev_uint8_t
)label_len
;
1553 memcpy(buf
+ j
, start
, label_len
);
1554 j
+= (int) label_len
;
1557 /* append length of the label. */
1558 const size_t label_len
= name
- start
;
1559 if (label_len
> 63) return -1;
1560 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1561 if (table
) dnslabel_table_add(table
, start
, j
);
1562 buf
[j
++] = (ev_uint8_t
)label_len
;
1564 memcpy(buf
+ j
, start
, label_len
);
1565 j
+= (int) label_len
;
1566 /* hop over the '.' */
1571 /* the labels must be terminated by a 0. */
1572 /* It's possible that the name ended in a . */
1573 /* in which case the zero is already there */
1574 if (!j
|| buf
[j
-1]) buf
[j
++] = 0;
1580 /* Finds the length of a dns request for a DNS name of the given */
1581 /* length. The actual request may be smaller than the value returned */
1584 evdns_request_len(const size_t name_len
) {
1585 return 96 + /* length of the DNS standard header */
1587 4; /* space for the resource type */
1590 /* build a dns request packet into buf. buf should be at least as long */
1591 /* as evdns_request_len told you it should be. */
1593 /* Returns the amount of space used. Negative on error. */
1595 evdns_request_data_build(const char *const name
, const size_t name_len
,
1596 const u16 trans_id
, const u16 type
, const u16
class,
1597 u8
*const buf
, size_t buf_len
) {
1598 off_t j
= 0; /* current offset into buf */
1599 u16 _t
; /* used by the macros */
1602 APPEND16(0x0100); /* standard query, recusion needed */
1603 APPEND16(1); /* one question */
1604 APPEND16(0); /* no answers */
1605 APPEND16(0); /* no authority */
1606 APPEND16(0); /* no additional */
1608 j
= dnsname_to_labels(buf
, buf_len
, j
, name
, name_len
, NULL
);
1621 /* exported function */
1622 struct evdns_server_port
*
1623 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
)
1625 struct evdns_server_port
*port
;
1627 return NULL
; /* flags not yet implemented */
1628 if (!(port
= mm_malloc(sizeof(struct evdns_server_port
))))
1630 memset(port
, 0, sizeof(struct evdns_server_port
));
1633 port
->socket
= socket
;
1637 port
->user_callback
= cb
;
1638 port
->user_data
= user_data
;
1639 port
->pending_replies
= NULL
;
1640 port
->event_base
= base
;
1642 event_assign(&port
->event
, port
->event_base
,
1643 port
->socket
, EV_READ
| EV_PERSIST
,
1644 server_port_ready_callback
, port
);
1645 if (event_add(&port
->event
, NULL
) < 0) {
1649 EVTHREAD_ALLOC_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
1653 struct evdns_server_port
*
1654 evdns_add_server_port(evutil_socket_t socket
, int flags
, evdns_request_callback_fn_type cb
, void *user_data
)
1656 return evdns_add_server_port_with_base(NULL
, socket
, flags
, cb
, user_data
);
1659 /* exported function */
1661 evdns_close_server_port(struct evdns_server_port
*port
)
1664 if (--port
->refcnt
== 0) {
1666 server_port_free(port
);
1672 /* exported function */
1674 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
)
1676 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1677 struct server_reply_item
**itemp
, *item
;
1681 EVDNS_LOCK(req
->port
);
1682 if (req
->response
) /* have we already answered? */
1686 case EVDNS_ANSWER_SECTION
:
1687 itemp
= &req
->answer
;
1688 countp
= &req
->n_answer
;
1690 case EVDNS_AUTHORITY_SECTION
:
1691 itemp
= &req
->authority
;
1692 countp
= &req
->n_authority
;
1694 case EVDNS_ADDITIONAL_SECTION
:
1695 itemp
= &req
->additional
;
1696 countp
= &req
->n_additional
;
1702 itemp
= &((*itemp
)->next
);
1704 item
= mm_malloc(sizeof(struct server_reply_item
));
1708 if (!(item
->name
= mm_strdup(name
))) {
1713 item
->dns_question_class
= class;
1715 item
->is_name
= is_name
!= 0;
1719 if (item
->is_name
) {
1720 if (!(item
->data
= mm_strdup(data
))) {
1721 mm_free(item
->name
);
1725 item
->datalen
= (u16
)-1;
1727 if (!(item
->data
= mm_malloc(datalen
))) {
1728 mm_free(item
->name
);
1732 item
->datalen
= datalen
;
1733 memcpy(item
->data
, data
, datalen
);
1741 EVDNS_UNLOCK(req
->port
);
1745 /* exported function */
1747 evdns_server_request_add_a_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1749 return evdns_server_request_add_reply(
1750 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_A
, CLASS_INET
,
1751 ttl
, n
*4, 0, addrs
);
1754 /* exported function */
1756 evdns_server_request_add_aaaa_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1758 return evdns_server_request_add_reply(
1759 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_AAAA
, CLASS_INET
,
1760 ttl
, n
*16, 0, addrs
);
1763 /* exported function */
1765 evdns_server_request_add_ptr_reply(struct evdns_server_request
*req
, struct in_addr
*in
, const char *inaddr_name
, const char *hostname
, int ttl
)
1769 if (in
&& inaddr_name
)
1771 else if (!in
&& !inaddr_name
)
1774 a
= ntohl(in
->s_addr
);
1775 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
1776 (int)(u8
)((a
)&0xff),
1777 (int)(u8
)((a
>>8 )&0xff),
1778 (int)(u8
)((a
>>16)&0xff),
1779 (int)(u8
)((a
>>24)&0xff));
1782 return evdns_server_request_add_reply(
1783 req
, EVDNS_ANSWER_SECTION
, inaddr_name
, TYPE_PTR
, CLASS_INET
,
1784 ttl
, -1, 1, hostname
);
1787 /* exported function */
1789 evdns_server_request_add_cname_reply(struct evdns_server_request
*req
, const char *name
, const char *cname
, int ttl
)
1791 return evdns_server_request_add_reply(
1792 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_CNAME
, CLASS_INET
,
1796 /* exported function */
1798 evdns_server_request_set_flags(struct evdns_server_request
*exreq
, int flags
)
1800 struct server_request
*req
= TO_SERVER_REQUEST(exreq
);
1801 req
->base
.flags
&= ~(EVDNS_FLAGS_AA
|EVDNS_FLAGS_RD
);
1802 req
->base
.flags
|= flags
;
1806 evdns_server_request_format_response(struct server_request
*req
, int err
)
1808 unsigned char buf
[1500];
1809 size_t buf_len
= sizeof(buf
);
1815 struct dnslabel_table table
;
1817 if (err
< 0 || err
> 15) return -1;
1819 /* Set response bit and error code; copy OPCODE and RD fields from
1820 * question; copy RA and AA if set by caller. */
1821 flags
= req
->base
.flags
;
1822 flags
|= (0x8000 | err
);
1824 dnslabel_table_init(&table
);
1825 APPEND16(req
->trans_id
);
1827 APPEND16(req
->base
.nquestions
);
1828 APPEND16(req
->n_answer
);
1829 APPEND16(req
->n_authority
);
1830 APPEND16(req
->n_additional
);
1832 /* Add questions. */
1833 for (i
=0; i
< req
->base
.nquestions
; ++i
) {
1834 const char *s
= req
->base
.questions
[i
]->name
;
1835 j
= dnsname_to_labels(buf
, buf_len
, j
, s
, strlen(s
), &table
);
1837 dnslabel_clear(&table
);
1840 APPEND16(req
->base
.questions
[i
]->type
);
1841 APPEND16(req
->base
.questions
[i
]->dns_question_class
);
1844 /* Add answer, authority, and additional sections. */
1845 for (i
=0; i
<3; ++i
) {
1846 struct server_reply_item
*item
;
1850 item
= req
->authority
;
1852 item
= req
->additional
;
1854 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->name
, strlen(item
->name
), &table
);
1859 APPEND16(item
->type
);
1860 APPEND16(item
->dns_question_class
);
1861 APPEND32(item
->ttl
);
1862 if (item
->is_name
) {
1863 off_t len_idx
= j
, name_start
;
1866 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->data
, strlen(item
->data
), &table
);
1870 _t
= htons( (short) (j
-name_start
) );
1871 memcpy(buf
+len_idx
, &_t
, 2);
1873 APPEND16(item
->datalen
);
1874 if (j
+item
->datalen
> (off_t
)buf_len
)
1876 memcpy(buf
+j
, item
->data
, item
->datalen
);
1886 buf
[2] |= 0x02; /* set the truncated bit. */
1889 req
->response_len
= j
;
1891 if (!(req
->response
= mm_malloc(req
->response_len
))) {
1892 server_request_free_answers(req
);
1893 dnslabel_clear(&table
);
1896 memcpy(req
->response
, buf
, req
->response_len
);
1897 server_request_free_answers(req
);
1898 dnslabel_clear(&table
);
1902 /* exported function */
1904 evdns_server_request_respond(struct evdns_server_request
*_req
, int err
)
1906 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1907 struct evdns_server_port
*port
= req
->port
;
1911 if (!req
->response
) {
1912 if ((r
= evdns_server_request_format_response(req
, err
))<0)
1916 r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
1917 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
1919 int sock_err
= evutil_socket_geterror(port
->socket
);
1920 if (EVUTIL_ERR_RW_RETRIABLE(sock_err
))
1923 if (port
->pending_replies
) {
1924 req
->prev_pending
= port
->pending_replies
->prev_pending
;
1925 req
->next_pending
= port
->pending_replies
;
1926 req
->prev_pending
->next_pending
=
1927 req
->next_pending
->prev_pending
= req
;
1929 req
->prev_pending
= req
->next_pending
= req
;
1930 port
->pending_replies
= req
;
1933 (void) event_del(&port
->event
);
1934 event_assign(&port
->event
, port
->event_base
, port
->socket
, (port
->closing
?0:EV_READ
) | EV_WRITE
| EV_PERSIST
, server_port_ready_callback
, port
);
1936 if (event_add(&port
->event
, NULL
) < 0) {
1937 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server");
1945 if (server_request_free(req
)) {
1950 if (port
->pending_replies
)
1951 server_port_flush(port
);
1959 /* Free all storage held by RRs in req. */
1961 server_request_free_answers(struct server_request
*req
)
1963 struct server_reply_item
*victim
, *next
, **list
;
1965 for (i
= 0; i
< 3; ++i
) {
1967 list
= &req
->answer
;
1969 list
= &req
->authority
;
1971 list
= &req
->additional
;
1975 next
= victim
->next
;
1976 mm_free(victim
->name
);
1978 mm_free(victim
->data
);
1986 /* Free all storage held by req, and remove links to it. */
1987 /* return true iff we just wound up freeing the server_port. */
1989 server_request_free(struct server_request
*req
)
1991 int i
, rc
=1, lock
=0;
1992 if (req
->base
.questions
) {
1993 for (i
= 0; i
< req
->base
.nquestions
; ++i
)
1994 mm_free(req
->base
.questions
[i
]);
1995 mm_free(req
->base
.questions
);
1999 EVDNS_LOCK(req
->port
);
2001 if (req
->port
->pending_replies
== req
) {
2002 if (req
->next_pending
&& req
->next_pending
!= req
)
2003 req
->port
->pending_replies
= req
->next_pending
;
2005 req
->port
->pending_replies
= NULL
;
2007 rc
= --req
->port
->refcnt
;
2010 if (req
->response
) {
2011 mm_free(req
->response
);
2014 server_request_free_answers(req
);
2016 if (req
->next_pending
&& req
->next_pending
!= req
) {
2017 req
->next_pending
->prev_pending
= req
->prev_pending
;
2018 req
->prev_pending
->next_pending
= req
->next_pending
;
2022 EVDNS_UNLOCK(req
->port
); /* ????? nickm */
2023 server_port_free(req
->port
);
2028 EVDNS_UNLOCK(req
->port
);
2033 /* Free all storage held by an evdns_server_port. Only called when */
2035 server_port_free(struct evdns_server_port
*port
)
2037 EVUTIL_ASSERT(port
);
2038 EVUTIL_ASSERT(!port
->refcnt
);
2039 EVUTIL_ASSERT(!port
->pending_replies
);
2040 if (port
->socket
> 0) {
2041 evutil_closesocket(port
->socket
);
2044 (void) event_del(&port
->event
);
2045 event_debug_unassign(&port
->event
);
2046 EVTHREAD_FREE_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
2050 /* exported function */
2052 evdns_server_request_drop(struct evdns_server_request
*_req
)
2054 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2055 server_request_free(req
);
2059 /* exported function */
2061 evdns_server_request_get_requesting_addr(struct evdns_server_request
*_req
, struct sockaddr
*sa
, int addr_len
)
2063 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2064 if (addr_len
< (int)req
->addrlen
)
2066 memcpy(sa
, &(req
->addr
), req
->addrlen
);
2067 return req
->addrlen
;
2073 /* this is a libevent callback function which is called when a request */
2074 /* has timed out. */
2076 evdns_request_timeout_callback(evutil_socket_t fd
, short events
, void *arg
) {
2077 struct request
*const req
= (struct request
*) arg
;
2078 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
2079 struct evdns_base
*base
= req
->base
;
2084 log(EVDNS_LOG_DEBUG
, "Request %p timed out", arg
);
2087 req
->ns
->timedout
++;
2088 if (req
->ns
->timedout
> req
->base
->global_max_nameserver_timeout
) {
2089 req
->ns
->timedout
= 0;
2090 nameserver_failed(req
->ns
, "request timed out.");
2093 if (req
->tx_count
>= req
->base
->global_max_retransmits
) {
2094 /* this request has failed */
2095 reply_schedule_callback(req
, 0, DNS_ERR_TIMEOUT
, NULL
);
2096 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
2099 (void) evtimer_del(&req
->timeout_event
);
2100 evdns_request_transmit(req
);
2105 /* try to send a request to a given server. */
2109 /* 1 temporary failure */
2110 /* 2 other failure */
2112 evdns_request_transmit_to(struct request
*req
, struct nameserver
*server
) {
2114 ASSERT_LOCKED(req
->base
);
2115 ASSERT_VALID_REQUEST(req
);
2116 r
= sendto(server
->socket
, (void*)req
->request
, req
->request_len
, 0,
2117 (struct sockaddr
*)&server
->address
, server
->addrlen
);
2119 int err
= evutil_socket_geterror(server
->socket
);
2120 if (EVUTIL_ERR_RW_RETRIABLE(err
))
2122 nameserver_failed(req
->ns
, evutil_socket_error_to_string(err
));
2124 } else if (r
!= (int)req
->request_len
) {
2125 return 1; /* short write */
2131 /* try to send a request, updating the fields of the request */
2138 evdns_request_transmit(struct request
*req
) {
2141 ASSERT_LOCKED(req
->base
);
2142 ASSERT_VALID_REQUEST(req
);
2143 /* if we fail to send this packet then this flag marks it */
2144 /* for evdns_transmit */
2145 req
->transmit_me
= 1;
2146 EVUTIL_ASSERT(req
->trans_id
!= 0xffff);
2148 if (req
->ns
->choked
) {
2149 /* don't bother trying to write to a socket */
2150 /* which we have had EAGAIN from */
2154 r
= evdns_request_transmit_to(req
, req
->ns
);
2158 req
->ns
->choked
= 1;
2159 nameserver_write_waiting(req
->ns
, 1);
2162 /* failed to transmit the request entirely. */
2164 /* fall through: we'll set a timeout, which will time out,
2165 * and make us retransmit the request anyway. */
2168 log(EVDNS_LOG_DEBUG
,
2169 "Setting timeout for request %p", req
);
2170 if (evtimer_add(&req
->timeout_event
, &req
->base
->global_timeout
) < 0) {
2172 "Error from libevent when adding timer for request %p",
2177 req
->transmit_me
= 0;
2183 nameserver_probe_callback(int result
, char type
, int count
, int ttl
, void *addresses
, void *arg
) {
2184 struct nameserver
*const ns
= (struct nameserver
*) arg
;
2190 EVDNS_LOCK(ns
->base
);
2191 ns
->probe_request
= NULL
;
2192 if (result
== DNS_ERR_CANCEL
) {
2193 /* We canceled this request because the nameserver came up
2194 * for some other reason. Do not change our opinion about
2195 * the nameserver. */
2196 } else if (result
== DNS_ERR_NONE
|| result
== DNS_ERR_NOTEXIST
) {
2197 /* this is a good reply */
2200 nameserver_probe_failed(ns
);
2202 EVDNS_UNLOCK(ns
->base
);
2206 nameserver_send_probe(struct nameserver
*const ns
) {
2207 struct evdns_request
*handle
;
2208 struct request
*req
;
2210 /* here we need to send a probe to a given nameserver */
2211 /* in the hope that it is up now. */
2213 ASSERT_LOCKED(ns
->base
);
2214 log(EVDNS_LOG_DEBUG
, "Sending probe to %s",
2215 evutil_format_sockaddr_port(
2216 (struct sockaddr
*)&ns
->address
,
2217 addrbuf
, sizeof(addrbuf
)));
2218 handle
= mm_calloc(1, sizeof(*handle
));
2219 if (!handle
) return;
2220 req
= request_new(ns
->base
, handle
, TYPE_A
, "google.com", DNS_QUERY_NO_SEARCH
, nameserver_probe_callback
, ns
);
2222 ns
->probe_request
= handle
;
2223 /* we force this into the inflight queue no matter what */
2224 request_trans_id_set(req
, transaction_id_pick(ns
->base
));
2226 request_submit(req
);
2230 /* 0 didn't try to transmit anything */
2231 /* 1 tried to transmit something */
2233 evdns_transmit(struct evdns_base
*base
) {
2234 char did_try_to_transmit
= 0;
2237 ASSERT_LOCKED(base
);
2238 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2239 if (base
->req_heads
[i
]) {
2240 struct request
*const started_at
= base
->req_heads
[i
], *req
= started_at
;
2241 /* first transmit all the requests which are currently waiting */
2243 if (req
->transmit_me
) {
2244 did_try_to_transmit
= 1;
2245 evdns_request_transmit(req
);
2249 } while (req
!= started_at
);
2253 return did_try_to_transmit
;
2256 /* exported function */
2258 evdns_base_count_nameservers(struct evdns_base
*base
)
2260 const struct nameserver
*server
;
2264 server
= base
->server_head
;
2269 server
= server
->next
;
2270 } while (server
!= base
->server_head
);
2277 evdns_count_nameservers(void)
2279 return evdns_base_count_nameservers(current_base
);
2282 /* exported function */
2284 evdns_base_clear_nameservers_and_suspend(struct evdns_base
*base
)
2286 struct nameserver
*server
, *started_at
;
2290 server
= base
->server_head
;
2291 started_at
= base
->server_head
;
2297 struct nameserver
*next
= server
->next
;
2298 (void) event_del(&server
->event
);
2299 if (evtimer_initialized(&server
->timeout_event
))
2300 (void) evtimer_del(&server
->timeout_event
);
2301 if (server
->socket
>= 0)
2302 evutil_closesocket(server
->socket
);
2304 if (next
== started_at
)
2308 base
->server_head
= NULL
;
2309 base
->global_good_nameservers
= 0;
2311 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2312 struct request
*req
, *req_started_at
;
2313 req
= req_started_at
= base
->req_heads
[i
];
2315 struct request
*next
= req
->next
;
2316 req
->tx_count
= req
->reissue_count
= 0;
2318 /* ???? What to do about searches? */
2319 (void) evtimer_del(&req
->timeout_event
);
2321 req
->transmit_me
= 0;
2323 base
->global_requests_waiting
++;
2324 evdns_request_insert(req
, &base
->req_waiting_head
);
2325 /* We want to insert these suspended elements at the front of
2326 * the waiting queue, since they were pending before any of
2327 * the waiting entries were added. This is a circular list,
2328 * so we can just shift the start back by one.*/
2329 base
->req_waiting_head
= base
->req_waiting_head
->prev
;
2331 if (next
== req_started_at
)
2335 base
->req_heads
[i
] = NULL
;
2338 base
->global_requests_inflight
= 0;
2345 evdns_clear_nameservers_and_suspend(void)
2347 return evdns_base_clear_nameservers_and_suspend(current_base
);
2351 /* exported function */
2353 evdns_base_resume(struct evdns_base
*base
)
2356 evdns_requests_pump_waiting_queue(base
);
2364 return evdns_base_resume(current_base
);
2368 _evdns_nameserver_add_impl(struct evdns_base
*base
, const struct sockaddr
*address
, int addrlen
) {
2369 /* first check to see if we already have this nameserver */
2371 const struct nameserver
*server
= base
->server_head
, *const started_at
= base
->server_head
;
2372 struct nameserver
*ns
;
2376 ASSERT_LOCKED(base
);
2379 if (!evutil_sockaddr_cmp((struct sockaddr
*)&server
->address
, address
, 1)) return 3;
2380 server
= server
->next
;
2381 } while (server
!= started_at
);
2383 if (addrlen
> (int)sizeof(ns
->address
)) {
2384 log(EVDNS_LOG_DEBUG
, "Addrlen %d too long.", (int)addrlen
);
2388 ns
= (struct nameserver
*) mm_malloc(sizeof(struct nameserver
));
2391 memset(ns
, 0, sizeof(struct nameserver
));
2394 evtimer_assign(&ns
->timeout_event
, ns
->base
->event_base
, nameserver_prod_callback
, ns
);
2396 ns
->socket
= socket(PF_INET
, SOCK_DGRAM
, 0);
2397 if (ns
->socket
< 0) { err
= 1; goto out1
; }
2398 evutil_make_socket_closeonexec(ns
->socket
);
2399 evutil_make_socket_nonblocking(ns
->socket
);
2401 if (base
->global_outgoing_addrlen
&&
2402 !evutil_sockaddr_is_loopback(address
)) {
2403 if (bind(ns
->socket
,
2404 (struct sockaddr
*)&base
->global_outgoing_address
,
2405 base
->global_outgoing_addrlen
) < 0) {
2406 log(EVDNS_LOG_WARN
,"Couldn't bind to outgoing address");
2412 memcpy(&ns
->address
, address
, addrlen
);
2413 ns
->addrlen
= addrlen
;
2415 event_assign(&ns
->event
, ns
->base
->event_base
, ns
->socket
, EV_READ
| EV_PERSIST
, nameserver_ready_callback
, ns
);
2416 if (event_add(&ns
->event
, NULL
) < 0) {
2421 log(EVDNS_LOG_DEBUG
, "Added nameserver %s",
2422 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)));
2424 /* insert this nameserver into the list of them */
2425 if (!base
->server_head
) {
2426 ns
->next
= ns
->prev
= ns
;
2427 base
->server_head
= ns
;
2429 ns
->next
= base
->server_head
->next
;
2430 ns
->prev
= base
->server_head
;
2431 base
->server_head
->next
= ns
;
2432 if (base
->server_head
->prev
== base
->server_head
) {
2433 base
->server_head
->prev
= ns
;
2437 base
->global_good_nameservers
++;
2442 evutil_closesocket(ns
->socket
);
2444 event_debug_unassign(&ns
->event
);
2446 log(EVDNS_LOG_WARN
, "Unable to add nameserver %s: error %d",
2447 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)), err
);
2451 /* exported function */
2453 evdns_base_nameserver_add(struct evdns_base
*base
, unsigned long int address
)
2455 struct sockaddr_in sin
;
2457 sin
.sin_addr
.s_addr
= address
;
2458 sin
.sin_port
= htons(53);
2459 sin
.sin_family
= AF_INET
;
2461 res
= _evdns_nameserver_add_impl(base
, (struct sockaddr
*)&sin
, sizeof(sin
));
2467 evdns_nameserver_add(unsigned long int address
) {
2469 current_base
= evdns_base_new(NULL
, 0);
2470 return evdns_base_nameserver_add(current_base
, address
);
2474 sockaddr_setport(struct sockaddr
*sa
, ev_uint16_t port
)
2476 if (sa
->sa_family
== AF_INET
) {
2477 ((struct sockaddr_in
*)sa
)->sin_port
= htons(port
);
2478 } else if (sa
->sa_family
== AF_INET6
) {
2479 ((struct sockaddr_in6
*)sa
)->sin6_port
= htons(port
);
2484 sockaddr_getport(struct sockaddr
*sa
)
2486 if (sa
->sa_family
== AF_INET
) {
2487 return ntohs(((struct sockaddr_in
*)sa
)->sin_port
);
2488 } else if (sa
->sa_family
== AF_INET6
) {
2489 return ntohs(((struct sockaddr_in6
*)sa
)->sin6_port
);
2495 /* exported function */
2497 evdns_base_nameserver_ip_add(struct evdns_base
*base
, const char *ip_as_string
) {
2498 struct sockaddr_storage ss
;
2499 struct sockaddr
*sa
;
2500 int len
= sizeof(ss
);
2502 if (evutil_parse_sockaddr_port(ip_as_string
, (struct sockaddr
*)&ss
,
2504 log(EVDNS_LOG_WARN
, "Unable to parse nameserver address %s",
2508 sa
= (struct sockaddr
*) &ss
;
2509 if (sockaddr_getport(sa
) == 0)
2510 sockaddr_setport(sa
, 53);
2513 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2519 evdns_nameserver_ip_add(const char *ip_as_string
) {
2521 current_base
= evdns_base_new(NULL
, 0);
2522 return evdns_base_nameserver_ip_add(current_base
, ip_as_string
);
2526 evdns_base_nameserver_sockaddr_add(struct evdns_base
*base
,
2527 const struct sockaddr
*sa
, ev_socklen_t len
, unsigned flags
)
2530 EVUTIL_ASSERT(base
);
2532 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2537 /* remove from the queue */
2539 evdns_request_remove(struct request
*req
, struct request
**head
)
2541 ASSERT_LOCKED(req
->base
);
2542 ASSERT_VALID_REQUEST(req
);
2546 struct request
*ptr
;
2548 EVUTIL_ASSERT(*head
!= NULL
);
2557 } while (ptr
!= *head
);
2558 EVUTIL_ASSERT(found
);
2560 EVUTIL_ASSERT(req
->next
);
2564 if (req
->next
== req
) {
2565 /* only item in the list */
2568 req
->next
->prev
= req
->prev
;
2569 req
->prev
->next
= req
->next
;
2570 if (*head
== req
) *head
= req
->next
;
2572 req
->next
= req
->prev
= NULL
;
2575 /* insert into the tail of the queue */
2577 evdns_request_insert(struct request
*req
, struct request
**head
) {
2578 ASSERT_LOCKED(req
->base
);
2579 ASSERT_VALID_REQUEST(req
);
2582 req
->next
= req
->prev
= req
;
2586 req
->prev
= (*head
)->prev
;
2587 req
->prev
->next
= req
;
2589 (*head
)->prev
= req
;
2593 string_num_dots(const char *s
) {
2595 while ((s
= strchr(s
, '.'))) {
2602 static struct request
*
2603 request_new(struct evdns_base
*base
, struct evdns_request
*handle
, int type
,
2604 const char *name
, int flags
, evdns_callback_type callback
,
2607 const char issuing_now
=
2608 (base
->global_requests_inflight
< base
->global_max_requests_inflight
) ? 1 : 0;
2610 const size_t name_len
= strlen(name
);
2611 const size_t request_max_len
= evdns_request_len(name_len
);
2612 const u16 trans_id
= issuing_now
? transaction_id_pick(base
) : 0xffff;
2613 /* the request data is alloced in a single block with the header */
2614 struct request
*const req
=
2615 mm_malloc(sizeof(struct request
) + request_max_len
);
2620 ASSERT_LOCKED(base
);
2622 if (!req
) return NULL
;
2624 if (name_len
>= sizeof(namebuf
)) {
2629 memset(req
, 0, sizeof(struct request
));
2632 evtimer_assign(&req
->timeout_event
, req
->base
->event_base
, evdns_request_timeout_callback
, req
);
2634 if (base
->global_randomize_case
) {
2636 char randbits
[(sizeof(namebuf
)+7)/8];
2637 strlcpy(namebuf
, name
, sizeof(namebuf
));
2638 evutil_secure_rng_get_bytes(randbits
, (name_len
+7)/8);
2639 for (i
= 0; i
< name_len
; ++i
) {
2640 if (EVUTIL_ISALPHA(namebuf
[i
])) {
2641 if ((randbits
[i
>> 3] & (1<<(i
& 7))))
2644 namebuf
[i
] &= ~0x20;
2650 /* request data lives just after the header */
2651 req
->request
= ((u8
*) req
) + sizeof(struct request
);
2652 /* denotes that the request data shouldn't be free()ed */
2653 req
->request_appended
= 1;
2654 rlen
= evdns_request_data_build(name
, name_len
, trans_id
,
2655 type
, CLASS_INET
, req
->request
, request_max_len
);
2659 req
->request_len
= rlen
;
2660 req
->trans_id
= trans_id
;
2662 req
->request_type
= type
;
2663 req
->user_pointer
= user_ptr
;
2664 req
->user_callback
= callback
;
2665 req
->ns
= issuing_now
? nameserver_pick(base
) : NULL
;
2666 req
->next
= req
->prev
= NULL
;
2667 req
->handle
= handle
;
2669 handle
->current_req
= req
;
2670 handle
->base
= base
;
2680 request_submit(struct request
*const req
) {
2681 struct evdns_base
*base
= req
->base
;
2682 ASSERT_LOCKED(base
);
2683 ASSERT_VALID_REQUEST(req
);
2685 /* if it has a nameserver assigned then this is going */
2686 /* straight into the inflight queue */
2687 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
2688 base
->global_requests_inflight
++;
2689 evdns_request_transmit(req
);
2691 evdns_request_insert(req
, &base
->req_waiting_head
);
2692 base
->global_requests_waiting
++;
2696 /* exported function */
2698 evdns_cancel_request(struct evdns_base
*base
, struct evdns_request
*handle
)
2700 struct request
*req
;
2702 if (!handle
->current_req
)
2706 /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
2707 base
= handle
->base
;
2709 base
= handle
->current_req
->base
;
2713 if (handle
->pending_cb
) {
2718 req
= handle
->current_req
;
2719 ASSERT_VALID_REQUEST(req
);
2721 reply_schedule_callback(req
, 0, DNS_ERR_CANCEL
, NULL
);
2723 /* remove from inflight queue */
2724 request_finished(req
, &REQ_HEAD(base
, req
->trans_id
), 1);
2726 /* remove from global_waiting head */
2727 request_finished(req
, &base
->req_waiting_head
, 1);
2732 /* exported function */
2733 struct evdns_request
*
2734 evdns_base_resolve_ipv4(struct evdns_base
*base
, const char *name
, int flags
,
2735 evdns_callback_type callback
, void *ptr
) {
2736 struct evdns_request
*handle
;
2737 struct request
*req
;
2738 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2739 handle
= mm_calloc(1, sizeof(*handle
));
2743 if (flags
& DNS_QUERY_NO_SEARCH
) {
2745 request_new(base
, handle
, TYPE_A
, name
, flags
,
2748 request_submit(req
);
2750 search_request_new(base
, handle
, TYPE_A
, name
, flags
,
2753 if (handle
->current_req
== NULL
) {
2761 int evdns_resolve_ipv4(const char *name
, int flags
,
2762 evdns_callback_type callback
, void *ptr
)
2764 return evdns_base_resolve_ipv4(current_base
, name
, flags
, callback
, ptr
)
2769 /* exported function */
2770 struct evdns_request
*
2771 evdns_base_resolve_ipv6(struct evdns_base
*base
,
2772 const char *name
, int flags
,
2773 evdns_callback_type callback
, void *ptr
)
2775 struct evdns_request
*handle
;
2776 struct request
*req
;
2777 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2778 handle
= mm_calloc(1, sizeof(*handle
));
2782 if (flags
& DNS_QUERY_NO_SEARCH
) {
2783 req
= request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2786 request_submit(req
);
2788 search_request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2791 if (handle
->current_req
== NULL
) {
2799 int evdns_resolve_ipv6(const char *name
, int flags
,
2800 evdns_callback_type callback
, void *ptr
) {
2801 return evdns_base_resolve_ipv6(current_base
, name
, flags
, callback
, ptr
)
2805 struct evdns_request
*
2806 evdns_base_resolve_reverse(struct evdns_base
*base
, const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2808 struct evdns_request
*handle
;
2809 struct request
*req
;
2812 a
= ntohl(in
->s_addr
);
2813 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
2814 (int)(u8
)((a
)&0xff),
2815 (int)(u8
)((a
>>8 )&0xff),
2816 (int)(u8
)((a
>>16)&0xff),
2817 (int)(u8
)((a
>>24)&0xff));
2818 handle
= mm_calloc(1, sizeof(*handle
));
2821 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2823 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2825 request_submit(req
);
2826 if (handle
->current_req
== NULL
) {
2834 int evdns_resolve_reverse(const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2835 return evdns_base_resolve_reverse(current_base
, in
, flags
, callback
, ptr
)
2839 struct evdns_request
*
2840 evdns_base_resolve_reverse_ipv6(struct evdns_base
*base
, const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2841 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2844 struct evdns_request
*handle
;
2845 struct request
*req
;
2849 for (i
=15; i
>= 0; --i
) {
2850 u8 byte
= in
->s6_addr
[i
];
2851 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
2853 *cp
++ = "0123456789abcdef"[byte
>> 4];
2856 EVUTIL_ASSERT(cp
+ strlen("ip6.arpa") < buf
+sizeof(buf
));
2857 memcpy(cp
, "ip6.arpa", strlen("ip6.arpa")+1);
2858 handle
= mm_calloc(1, sizeof(*handle
));
2861 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2863 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2865 request_submit(req
);
2866 if (handle
->current_req
== NULL
) {
2874 int evdns_resolve_reverse_ipv6(const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2875 return evdns_base_resolve_reverse_ipv6(current_base
, in
, flags
, callback
, ptr
)
2879 /* ================================================================= */
2880 /* Search support */
2882 /* the libc resolver has support for searching a number of domains */
2883 /* to find a name. If nothing else then it takes the single domain */
2884 /* from the gethostname() call. */
2886 /* It can also be configured via the domain and search options in a */
2889 /* The ndots option controls how many dots it takes for the resolver */
2890 /* to decide that a name is non-local and so try a raw lookup first. */
2892 struct search_domain
{
2894 struct search_domain
*next
;
2895 /* the text string is appended to this structure */
2898 struct search_state
{
2902 struct search_domain
*head
;
2906 search_state_decref(struct search_state
*const state
) {
2909 if (!state
->refcount
) {
2910 struct search_domain
*next
, *dom
;
2911 for (dom
= state
->head
; dom
; dom
= next
) {
2919 static struct search_state
*
2920 search_state_new(void) {
2921 struct search_state
*state
= (struct search_state
*) mm_malloc(sizeof(struct search_state
));
2922 if (!state
) return NULL
;
2923 memset(state
, 0, sizeof(struct search_state
));
2924 state
->refcount
= 1;
2931 search_postfix_clear(struct evdns_base
*base
) {
2932 search_state_decref(base
->global_search_state
);
2934 base
->global_search_state
= search_state_new();
2937 /* exported function */
2939 evdns_base_search_clear(struct evdns_base
*base
)
2942 search_postfix_clear(base
);
2947 evdns_search_clear(void) {
2948 evdns_base_search_clear(current_base
);
2952 search_postfix_add(struct evdns_base
*base
, const char *domain
) {
2954 struct search_domain
*sdomain
;
2955 while (domain
[0] == '.') domain
++;
2956 domain_len
= strlen(domain
);
2958 ASSERT_LOCKED(base
);
2959 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
2960 if (!base
->global_search_state
) return;
2961 base
->global_search_state
->num_domains
++;
2963 sdomain
= (struct search_domain
*) mm_malloc(sizeof(struct search_domain
) + domain_len
);
2964 if (!sdomain
) return;
2965 memcpy( ((u8
*) sdomain
) + sizeof(struct search_domain
), domain
, domain_len
);
2966 sdomain
->next
= base
->global_search_state
->head
;
2967 sdomain
->len
= (int) domain_len
;
2969 base
->global_search_state
->head
= sdomain
;
2972 /* reverse the order of members in the postfix list. This is needed because, */
2973 /* when parsing resolv.conf we push elements in the wrong order */
2975 search_reverse(struct evdns_base
*base
) {
2976 struct search_domain
*cur
, *prev
= NULL
, *next
;
2977 ASSERT_LOCKED(base
);
2978 cur
= base
->global_search_state
->head
;
2986 base
->global_search_state
->head
= prev
;
2989 /* exported function */
2991 evdns_base_search_add(struct evdns_base
*base
, const char *domain
) {
2993 search_postfix_add(base
, domain
);
2997 evdns_search_add(const char *domain
) {
2998 evdns_base_search_add(current_base
, domain
);
3001 /* exported function */
3003 evdns_base_search_ndots_set(struct evdns_base
*base
, const int ndots
) {
3005 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3006 if (base
->global_search_state
)
3007 base
->global_search_state
->ndots
= ndots
;
3011 evdns_search_ndots_set(const int ndots
) {
3012 evdns_base_search_ndots_set(current_base
, ndots
);
3016 search_set_from_hostname(struct evdns_base
*base
) {
3017 char hostname
[HOST_NAME_MAX
+ 1], *domainname
;
3019 ASSERT_LOCKED(base
);
3020 search_postfix_clear(base
);
3021 if (gethostname(hostname
, sizeof(hostname
))) return;
3022 domainname
= strchr(hostname
, '.');
3023 if (!domainname
) return;
3024 search_postfix_add(base
, domainname
);
3027 /* warning: returns malloced string */
3029 search_make_new(const struct search_state
*const state
, int n
, const char *const base_name
) {
3030 const size_t base_len
= strlen(base_name
);
3031 const char need_to_append_dot
= base_name
[base_len
- 1] == '.' ? 0 : 1;
3032 struct search_domain
*dom
;
3034 for (dom
= state
->head
; dom
; dom
= dom
->next
) {
3036 /* this is the postfix we want */
3037 /* the actual postfix string is kept at the end of the structure */
3038 const u8
*const postfix
= ((u8
*) dom
) + sizeof(struct search_domain
);
3039 const int postfix_len
= dom
->len
;
3040 char *const newname
= (char *) mm_malloc(base_len
+ need_to_append_dot
+ postfix_len
+ 1);
3041 if (!newname
) return NULL
;
3042 memcpy(newname
, base_name
, base_len
);
3043 if (need_to_append_dot
) newname
[base_len
] = '.';
3044 memcpy(newname
+ base_len
+ need_to_append_dot
, postfix
, postfix_len
);
3045 newname
[base_len
+ need_to_append_dot
+ postfix_len
] = 0;
3050 /* we ran off the end of the list and still didn't find the requested string */
3052 return NULL
; /* unreachable; stops warnings in some compilers. */
3055 static struct request
*
3056 search_request_new(struct evdns_base
*base
, struct evdns_request
*handle
,
3057 int type
, const char *const name
, int flags
,
3058 evdns_callback_type user_callback
, void *user_arg
) {
3059 ASSERT_LOCKED(base
);
3060 EVUTIL_ASSERT(type
== TYPE_A
|| type
== TYPE_AAAA
);
3061 EVUTIL_ASSERT(handle
->current_req
== NULL
);
3062 if ( ((flags
& DNS_QUERY_NO_SEARCH
) == 0) &&
3063 base
->global_search_state
&&
3064 base
->global_search_state
->num_domains
) {
3065 /* we have some domains to search */
3066 struct request
*req
;
3067 if (string_num_dots(name
) >= base
->global_search_state
->ndots
) {
3068 req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3069 if (!req
) return NULL
;
3070 handle
->search_index
= -1;
3072 char *const new_name
= search_make_new(base
->global_search_state
, 0, name
);
3073 if (!new_name
) return NULL
;
3074 req
= request_new(base
, handle
, type
, new_name
, flags
, user_callback
, user_arg
);
3076 if (!req
) return NULL
;
3077 handle
->search_index
= 0;
3079 EVUTIL_ASSERT(handle
->search_origname
== NULL
);
3080 handle
->search_origname
= mm_strdup(name
);
3081 if (handle
->search_origname
== NULL
) {
3082 /* XXX Should we dealloc req? If yes, how? */
3085 handle
->search_state
= base
->global_search_state
;
3086 handle
->search_flags
= flags
;
3087 base
->global_search_state
->refcount
++;
3088 request_submit(req
);
3091 struct request
*const req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3092 if (!req
) return NULL
;
3093 request_submit(req
);
3098 /* this is called when a request has failed to find a name. We need to check */
3099 /* if it is part of a search and, if so, try the next name in the list */
3101 /* 0 another request has been submitted */
3102 /* 1 no more requests needed */
3104 search_try_next(struct evdns_request
*const handle
) {
3105 struct request
*req
= handle
->current_req
;
3106 struct evdns_base
*base
= req
->base
;
3107 struct request
*newreq
;
3108 ASSERT_LOCKED(base
);
3109 if (handle
->search_state
) {
3110 /* it is part of a search */
3112 handle
->search_index
++;
3113 if (handle
->search_index
>= handle
->search_state
->num_domains
) {
3114 /* no more postfixes to try, however we may need to try */
3115 /* this name without a postfix */
3116 if (string_num_dots(handle
->search_origname
) < handle
->search_state
->ndots
) {
3117 /* yep, we need to try it raw */
3118 newreq
= request_new(base
, NULL
, req
->request_type
, handle
->search_origname
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3119 log(EVDNS_LOG_DEBUG
, "Search: trying raw query %s", handle
->search_origname
);
3121 search_request_finished(handle
);
3128 new_name
= search_make_new(handle
->search_state
, handle
->search_index
, handle
->search_origname
);
3129 if (!new_name
) return 1;
3130 log(EVDNS_LOG_DEBUG
, "Search: now trying %s (%d)", new_name
, handle
->search_index
);
3131 newreq
= request_new(base
, NULL
, req
->request_type
, new_name
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3133 if (!newreq
) return 1;
3139 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 0);
3140 handle
->current_req
= newreq
;
3141 newreq
->handle
= handle
;
3142 request_submit(newreq
);
3147 search_request_finished(struct evdns_request
*const handle
) {
3148 ASSERT_LOCKED(handle
->current_req
->base
);
3149 if (handle
->search_state
) {
3150 search_state_decref(handle
->search_state
);
3151 handle
->search_state
= NULL
;
3153 if (handle
->search_origname
) {
3154 mm_free(handle
->search_origname
);
3155 handle
->search_origname
= NULL
;
3159 /* ================================================================= */
3160 /* Parsing resolv.conf files */
3163 evdns_resolv_set_defaults(struct evdns_base
*base
, int flags
) {
3164 /* if the file isn't found then we assume a local resolver */
3165 ASSERT_LOCKED(base
);
3166 if (flags
& DNS_OPTION_SEARCH
) search_set_from_hostname(base
);
3167 if (flags
& DNS_OPTION_NAMESERVERS
) evdns_base_nameserver_ip_add(base
,"127.0.0.1");
3170 #ifndef _EVENT_HAVE_STRTOK_R
3172 strtok_r(char *s
, const char *delim
, char **state
) {
3174 start
= cp
= s
? s
: *state
;
3177 while (*cp
&& !strchr(delim
, *cp
))
3192 /* helper version of atoi which returns -1 on error */
3194 strtoint(const char *const str
)
3197 const int r
= strtol(str
, &endptr
, 10);
3198 if (*endptr
) return -1;
3202 /* Parse a number of seconds into a timeval; return -1 on error. */
3204 strtotimeval(const char *const str
, struct timeval
*out
)
3208 d
= strtod(str
, &endptr
);
3209 if (*endptr
) return -1;
3210 if (d
< 0) return -1;
3211 out
->tv_sec
= (int) d
;
3212 out
->tv_usec
= (int) ((d
- (int) d
)*1000000);
3213 if (out
->tv_sec
== 0 && out
->tv_usec
< 1000) /* less than 1 msec */
3218 /* helper version of atoi that returns -1 on error and clips to bounds. */
3220 strtoint_clipped(const char *const str
, int min
, int max
)
3222 int r
= strtoint(str
);
3234 evdns_base_set_max_requests_inflight(struct evdns_base
*base
, int maxinflight
)
3236 int old_n_heads
= base
->n_req_heads
, n_heads
;
3237 struct request
**old_heads
= base
->req_heads
, **new_heads
, *req
;
3240 ASSERT_LOCKED(base
);
3241 if (maxinflight
< 1)
3243 n_heads
= (maxinflight
+4) / 5;
3244 EVUTIL_ASSERT(n_heads
> 0);
3245 new_heads
= mm_calloc(n_heads
, sizeof(struct request
*));
3249 for (i
= 0; i
< old_n_heads
; ++i
) {
3250 while (old_heads
[i
]) {
3252 evdns_request_remove(req
, &old_heads
[i
]);
3253 evdns_request_insert(req
, &new_heads
[req
->trans_id
% n_heads
]);
3258 base
->req_heads
= new_heads
;
3259 base
->n_req_heads
= n_heads
;
3260 base
->global_max_requests_inflight
= maxinflight
;
3264 /* exported function */
3266 evdns_base_set_option(struct evdns_base
*base
,
3267 const char *option
, const char *val
)
3271 res
= evdns_base_set_option_impl(base
, option
, val
, DNS_OPTIONS_ALL
);
3277 str_matches_option(const char *s1
, const char *optionname
)
3279 /* Option names are given as "option:" We accept either 'option' in
3280 * s1, or 'option:randomjunk'. The latter form is to implement the
3281 * resolv.conf parser. */
3282 size_t optlen
= strlen(optionname
);
3283 size_t slen
= strlen(s1
);
3284 if (slen
== optlen
|| slen
== optlen
- 1)
3285 return !strncmp(s1
, optionname
, slen
);
3286 else if (slen
> optlen
)
3287 return !strncmp(s1
, optionname
, optlen
);
3293 evdns_base_set_option_impl(struct evdns_base
*base
,
3294 const char *option
, const char *val
, int flags
)
3296 ASSERT_LOCKED(base
);
3297 if (str_matches_option(option
, "ndots:")) {
3298 const int ndots
= strtoint(val
);
3299 if (ndots
== -1) return -1;
3300 if (!(flags
& DNS_OPTION_SEARCH
)) return 0;
3301 log(EVDNS_LOG_DEBUG
, "Setting ndots to %d", ndots
);
3302 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3303 if (!base
->global_search_state
) return -1;
3304 base
->global_search_state
->ndots
= ndots
;
3305 } else if (str_matches_option(option
, "timeout:")) {
3307 if (strtotimeval(val
, &tv
) == -1) return -1;
3308 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3309 log(EVDNS_LOG_DEBUG
, "Setting timeout to %s", val
);
3310 memcpy(&base
->global_timeout
, &tv
, sizeof(struct timeval
));
3311 } else if (str_matches_option(option
, "getaddrinfo-allow-skew:")) {
3313 if (strtotimeval(val
, &tv
) == -1) return -1;
3314 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3315 log(EVDNS_LOG_DEBUG
, "Setting getaddrinfo-allow-skew to %s",
3317 memcpy(&base
->global_getaddrinfo_allow_skew
, &tv
,
3318 sizeof(struct timeval
));
3319 } else if (str_matches_option(option
, "max-timeouts:")) {
3320 const int maxtimeout
= strtoint_clipped(val
, 1, 255);
3321 if (maxtimeout
== -1) return -1;
3322 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3323 log(EVDNS_LOG_DEBUG
, "Setting maximum allowed timeouts to %d",
3325 base
->global_max_nameserver_timeout
= maxtimeout
;
3326 } else if (str_matches_option(option
, "max-inflight:")) {
3327 const int maxinflight
= strtoint_clipped(val
, 1, 65000);
3328 if (maxinflight
== -1) return -1;
3329 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3330 log(EVDNS_LOG_DEBUG
, "Setting maximum inflight requests to %d",
3332 evdns_base_set_max_requests_inflight(base
, maxinflight
);
3333 } else if (str_matches_option(option
, "attempts:")) {
3334 int retries
= strtoint(val
);
3335 if (retries
== -1) return -1;
3336 if (retries
> 255) retries
= 255;
3337 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3338 log(EVDNS_LOG_DEBUG
, "Setting retries to %d", retries
);
3339 base
->global_max_retransmits
= retries
;
3340 } else if (str_matches_option(option
, "randomize-case:")) {
3341 int randcase
= strtoint(val
);
3342 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3343 base
->global_randomize_case
= randcase
;
3344 } else if (str_matches_option(option
, "bind-to:")) {
3345 /* XXX This only applies to successive nameservers, not
3346 * to already-configured ones. We might want to fix that. */
3347 int len
= sizeof(base
->global_outgoing_address
);
3348 if (!(flags
& DNS_OPTION_NAMESERVERS
)) return 0;
3349 if (evutil_parse_sockaddr_port(val
,
3350 (struct sockaddr
*)&base
->global_outgoing_address
, &len
))
3352 base
->global_outgoing_addrlen
= len
;
3353 } else if (str_matches_option(option
, "initial-probe-timeout:")) {
3355 if (strtotimeval(val
, &tv
) == -1) return -1;
3356 if (tv
.tv_sec
> 3600)
3358 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3359 log(EVDNS_LOG_DEBUG
, "Setting initial probe timeout to %s",
3361 memcpy(&base
->global_nameserver_probe_initial_timeout
, &tv
,
3368 evdns_set_option(const char *option
, const char *val
, int flags
)
3371 current_base
= evdns_base_new(NULL
, 0);
3372 return evdns_base_set_option(current_base
, option
, val
);
3376 resolv_conf_parse_line(struct evdns_base
*base
, char *const start
, int flags
) {
3378 static const char *const delims
= " \t";
3379 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3382 char *const first_token
= strtok_r(start
, delims
, &strtok_state
);
3383 ASSERT_LOCKED(base
);
3384 if (!first_token
) return;
3386 if (!strcmp(first_token
, "nameserver") && (flags
& DNS_OPTION_NAMESERVERS
)) {
3387 const char *const nameserver
= NEXT_TOKEN
;
3390 evdns_base_nameserver_ip_add(base
, nameserver
);
3391 } else if (!strcmp(first_token
, "domain") && (flags
& DNS_OPTION_SEARCH
)) {
3392 const char *const domain
= NEXT_TOKEN
;
3394 search_postfix_clear(base
);
3395 search_postfix_add(base
, domain
);
3397 } else if (!strcmp(first_token
, "search") && (flags
& DNS_OPTION_SEARCH
)) {
3399 search_postfix_clear(base
);
3401 while ((domain
= NEXT_TOKEN
)) {
3402 search_postfix_add(base
, domain
);
3404 search_reverse(base
);
3405 } else if (!strcmp(first_token
, "options")) {
3407 while ((option
= NEXT_TOKEN
)) {
3408 const char *val
= strchr(option
, ':');
3409 evdns_base_set_option_impl(base
, option
, val
? val
+1 : "", flags
);
3415 /* exported function */
3418 /* 1 failed to open file */
3419 /* 2 failed to stat file */
3420 /* 3 file too large */
3421 /* 4 out of memory */
3422 /* 5 short read from file */
3424 evdns_base_resolv_conf_parse(struct evdns_base
*base
, int flags
, const char *const filename
) {
3427 res
= evdns_base_resolv_conf_parse_impl(base
, flags
, filename
);
3433 evdns_get_default_hosts_filename(void)
3436 /* Windows is a little coy about where it puts its configuration
3437 * files. Sure, they're _usually_ in C:\windows\system32, but
3438 * there's no reason in principle they couldn't be in
3439 * W:\hoboken chicken emergency\
3441 char path
[MAX_PATH
+1];
3442 static const char hostfile
[] = "\\drivers\\etc\\hosts";
3446 if (! SHGetSpecialFolderPathA(NULL
, path
, CSIDL_SYSTEM
, 0))
3448 len_out
= strlen(path
)+strlen(hostfile
);
3449 path_out
= mm_malloc(len_out
+1);
3450 evutil_snprintf(path_out
, len_out
, "%s%s", path
, hostfile
);
3453 return mm_strdup("/etc/hosts");
3458 evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
) {
3464 log(EVDNS_LOG_DEBUG
, "Parsing resolv.conf file %s", filename
);
3466 if (flags
& DNS_OPTION_HOSTSFILE
) {
3467 char *fname
= evdns_get_default_hosts_filename();
3468 evdns_base_load_hosts(base
, fname
);
3473 if ((err
= evutil_read_file(filename
, &resolv
, &n
, 0)) < 0) {
3476 evdns_resolv_set_defaults(base
, flags
);
3485 char *const newline
= strchr(start
, '\n');
3487 resolv_conf_parse_line(base
, start
, flags
);
3491 resolv_conf_parse_line(base
, start
, flags
);
3492 start
= newline
+ 1;
3496 if (!base
->server_head
&& (flags
& DNS_OPTION_NAMESERVERS
)) {
3497 /* no nameservers were configured. */
3498 evdns_base_nameserver_ip_add(base
, "127.0.0.1");
3501 if (flags
& DNS_OPTION_SEARCH
&& (!base
->global_search_state
|| base
->global_search_state
->num_domains
== 0)) {
3502 search_set_from_hostname(base
);
3510 evdns_resolv_conf_parse(int flags
, const char *const filename
) {
3512 current_base
= evdns_base_new(NULL
, 0);
3513 return evdns_base_resolv_conf_parse(current_base
, flags
, filename
);
3518 /* Add multiple nameservers from a space-or-comma-separated list. */
3520 evdns_nameserver_ip_add_line(struct evdns_base
*base
, const char *ips
) {
3524 ASSERT_LOCKED(base
);
3526 while (isspace(*ips
) || *ips
== ',' || *ips
== '\t')
3529 while (isdigit(*ips
) || *ips
== '.' || *ips
== ':' ||
3530 *ips
=='[' || *ips
==']')
3532 buf
= mm_malloc(ips
-addr
+1);
3534 memcpy(buf
, addr
, ips
-addr
);
3535 buf
[ips
-addr
] = '\0';
3536 r
= evdns_base_nameserver_ip_add(base
, buf
);
3543 typedef DWORD(WINAPI
*GetNetworkParams_fn_t
)(FIXED_INFO
*, DWORD
*);
3545 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3546 /* figure out what our nameservers are. */
3548 load_nameservers_with_getnetworkparams(struct evdns_base
*base
)
3550 /* Based on MSDN examples and inspection of c-ares code. */
3553 ULONG size
= sizeof(FIXED_INFO
);
3555 int status
= 0, r
, added_any
;
3557 GetNetworkParams_fn_t fn
;
3559 ASSERT_LOCKED(base
);
3560 if (!(handle
= evutil_load_windows_system_library(
3561 TEXT("iphlpapi.dll")))) {
3562 log(EVDNS_LOG_WARN
, "Could not open iphlpapi.dll");
3566 if (!(fn
= (GetNetworkParams_fn_t
) GetProcAddress(handle
, "GetNetworkParams"))) {
3567 log(EVDNS_LOG_WARN
, "Could not get address of function.");
3572 buf
= mm_malloc(size
);
3573 if (!buf
) { status
= 4; goto done
; }
3575 r
= fn(fixed
, &size
);
3576 if (r
!= ERROR_SUCCESS
&& r
!= ERROR_BUFFER_OVERFLOW
) {
3580 if (r
!= ERROR_SUCCESS
) {
3582 buf
= mm_malloc(size
);
3583 if (!buf
) { status
= 4; goto done
; }
3585 r
= fn(fixed
, &size
);
3586 if (r
!= ERROR_SUCCESS
) {
3587 log(EVDNS_LOG_DEBUG
, "fn() failed.");
3593 EVUTIL_ASSERT(fixed
);
3595 ns
= &(fixed
->DnsServerList
);
3597 r
= evdns_nameserver_ip_add_line(base
, ns
->IpAddress
.String
);
3599 log(EVDNS_LOG_DEBUG
,"Could not add nameserver %s to list,error: %d",
3600 (ns
->IpAddress
.String
),(int)GetLastError());
3604 log(EVDNS_LOG_DEBUG
,"Successfully added %s as nameserver",ns
->IpAddress
.String
);
3611 log(EVDNS_LOG_DEBUG
, "No nameservers added.");
3622 FreeLibrary(handle
);
3627 config_nameserver_from_reg_key(struct evdns_base
*base
, HKEY key
, const TCHAR
*subkey
)
3630 DWORD bufsz
= 0, type
= 0;
3633 ASSERT_LOCKED(base
);
3634 if (RegQueryValueEx(key
, subkey
, 0, &type
, NULL
, &bufsz
)
3637 if (!(buf
= mm_malloc(bufsz
)))
3640 if (RegQueryValueEx(key
, subkey
, 0, &type
, (LPBYTE
)buf
, &bufsz
)
3641 == ERROR_SUCCESS
&& bufsz
> 1) {
3642 status
= evdns_nameserver_ip_add_line(base
,buf
);
3649 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3650 #define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
3651 #define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
3654 load_nameservers_from_registry(struct evdns_base
*base
)
3658 #define TRY(k, name) \
3659 if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3660 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3662 } else if (!found) { \
3663 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3667 ASSERT_LOCKED(base
);
3669 if (((int)GetVersion()) > 0) { /* NT */
3670 HKEY nt_key
= 0, interfaces_key
= 0;
3672 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_NT_KEY
, 0,
3673 KEY_READ
, &nt_key
) != ERROR_SUCCESS
) {
3674 log(EVDNS_LOG_DEBUG
,"Couldn't open nt key, %d",(int)GetLastError());
3677 r
= RegOpenKeyEx(nt_key
, TEXT("Interfaces"), 0,
3678 KEY_QUERY_VALUE
|KEY_ENUMERATE_SUB_KEYS
,
3680 if (r
!= ERROR_SUCCESS
) {
3681 log(EVDNS_LOG_DEBUG
,"Couldn't open interfaces key, %d",(int)GetLastError());
3684 TRY(nt_key
, "NameServer");
3685 TRY(nt_key
, "DhcpNameServer");
3686 TRY(interfaces_key
, "NameServer");
3687 TRY(interfaces_key
, "DhcpNameServer");
3688 RegCloseKey(interfaces_key
);
3689 RegCloseKey(nt_key
);
3692 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_9X_KEY
, 0,
3693 KEY_READ
, &win_key
) != ERROR_SUCCESS
) {
3694 log(EVDNS_LOG_DEBUG
, "Couldn't open registry key, %d", (int)GetLastError());
3697 TRY(win_key
, "NameServer");
3698 RegCloseKey(win_key
);
3702 log(EVDNS_LOG_WARN
,"Didn't find any nameservers.");
3705 return found
? 0 : -1;
3710 evdns_base_config_windows_nameservers(struct evdns_base
*base
)
3715 base
= current_base
;
3719 if (load_nameservers_with_getnetworkparams(base
) == 0) {
3723 r
= load_nameservers_from_registry(base
);
3725 fname
= evdns_get_default_hosts_filename();
3726 evdns_base_load_hosts(base
, fname
);
3735 evdns_config_windows_nameservers(void)
3737 if (!current_base
) {
3738 current_base
= evdns_base_new(NULL
, 1);
3739 return current_base
== NULL
? -1 : 0;
3741 return evdns_base_config_windows_nameservers(current_base
);
3747 evdns_base_new(struct event_base
*event_base
, int initialize_nameservers
)
3749 struct evdns_base
*base
;
3751 if (evutil_secure_rng_init() < 0) {
3752 log(EVDNS_LOG_WARN
, "Unable to seed random number generator; "
3757 /* Give the evutil library a hook into its evdns-enabled
3758 * functionality. We can't just call evdns_getaddrinfo directly or
3759 * else libevent-core will depend on libevent-extras. */
3760 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo
);
3762 base
= mm_malloc(sizeof(struct evdns_base
));
3765 memset(base
, 0, sizeof(struct evdns_base
));
3766 base
->req_waiting_head
= NULL
;
3768 EVTHREAD_ALLOC_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
3771 /* Set max requests inflight and allocate req_heads. */
3772 base
->req_heads
= NULL
;
3774 evdns_base_set_max_requests_inflight(base
, 64);
3776 base
->server_head
= NULL
;
3777 base
->event_base
= event_base
;
3778 base
->global_good_nameservers
= base
->global_requests_inflight
=
3779 base
->global_requests_waiting
= 0;
3781 base
->global_timeout
.tv_sec
= 5;
3782 base
->global_timeout
.tv_usec
= 0;
3783 base
->global_max_reissues
= 1;
3784 base
->global_max_retransmits
= 3;
3785 base
->global_max_nameserver_timeout
= 3;
3786 base
->global_search_state
= NULL
;
3787 base
->global_randomize_case
= 1;
3788 base
->global_getaddrinfo_allow_skew
.tv_sec
= 3;
3789 base
->global_getaddrinfo_allow_skew
.tv_usec
= 0;
3790 base
->global_nameserver_probe_initial_timeout
.tv_sec
= 10;
3791 base
->global_nameserver_probe_initial_timeout
.tv_usec
= 0;
3793 TAILQ_INIT(&base
->hostsdb
);
3795 if (initialize_nameservers
) {
3798 r
= evdns_base_config_windows_nameservers(base
);
3800 r
= evdns_base_resolv_conf_parse(base
, DNS_OPTIONS_ALL
, "/etc/resolv.conf");
3803 evdns_base_free_and_unlock(base
, 0);
3814 struct evdns_base
*base
= evdns_base_new(NULL
, 1);
3816 current_base
= base
;
3824 evdns_err_to_string(int err
)
3827 case DNS_ERR_NONE
: return "no error";
3828 case DNS_ERR_FORMAT
: return "misformatted query";
3829 case DNS_ERR_SERVERFAILED
: return "server failed";
3830 case DNS_ERR_NOTEXIST
: return "name does not exist";
3831 case DNS_ERR_NOTIMPL
: return "query not implemented";
3832 case DNS_ERR_REFUSED
: return "refused";
3834 case DNS_ERR_TRUNCATED
: return "reply truncated or ill-formed";
3835 case DNS_ERR_UNKNOWN
: return "unknown";
3836 case DNS_ERR_TIMEOUT
: return "request timed out";
3837 case DNS_ERR_SHUTDOWN
: return "dns subsystem shut down";
3838 case DNS_ERR_CANCEL
: return "dns request canceled";
3839 default: return "[Unknown error code]";
3844 evdns_nameserver_free(struct nameserver
*server
)
3846 if (server
->socket
>= 0)
3847 evutil_closesocket(server
->socket
);
3848 (void) event_del(&server
->event
);
3849 event_debug_unassign(&server
->event
);
3850 if (server
->state
== 0)
3851 (void) event_del(&server
->timeout_event
);
3852 event_debug_unassign(&server
->timeout_event
);
3857 evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
)
3859 struct nameserver
*server
, *server_next
;
3860 struct search_domain
*dom
, *dom_next
;
3863 /* Requires that we hold the lock. */
3865 /* TODO(nickm) we might need to refcount here. */
3867 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
3868 while (base
->req_heads
[i
]) {
3870 reply_schedule_callback(base
->req_heads
[i
], 0, DNS_ERR_SHUTDOWN
, NULL
);
3871 request_finished(base
->req_heads
[i
], &REQ_HEAD(base
, base
->req_heads
[i
]->trans_id
), 1);
3874 while (base
->req_waiting_head
) {
3876 reply_schedule_callback(base
->req_waiting_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
3877 request_finished(base
->req_waiting_head
, &base
->req_waiting_head
, 1);
3879 base
->global_requests_inflight
= base
->global_requests_waiting
= 0;
3881 for (server
= base
->server_head
; server
; server
= server_next
) {
3882 server_next
= server
->next
;
3883 evdns_nameserver_free(server
);
3884 if (server_next
== base
->server_head
)
3887 base
->server_head
= NULL
;
3888 base
->global_good_nameservers
= 0;
3890 if (base
->global_search_state
) {
3891 for (dom
= base
->global_search_state
->head
; dom
; dom
= dom_next
) {
3892 dom_next
= dom
->next
;
3895 mm_free(base
->global_search_state
);
3896 base
->global_search_state
= NULL
;
3900 struct hosts_entry
*victim
;
3901 while ((victim
= TAILQ_FIRST(&base
->hostsdb
))) {
3902 TAILQ_REMOVE(&base
->hostsdb
, victim
, next
);
3907 mm_free(base
->req_heads
);
3910 EVTHREAD_FREE_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
3916 evdns_base_free(struct evdns_base
*base
, int fail_requests
)
3919 evdns_base_free_and_unlock(base
, fail_requests
);
3923 evdns_shutdown(int fail_requests
)
3926 struct evdns_base
*b
= current_base
;
3927 current_base
= NULL
;
3928 evdns_base_free(b
, fail_requests
);
3930 evdns_log_fn
= NULL
;
3934 evdns_base_parse_hosts_line(struct evdns_base
*base
, char *line
)
3937 static const char *const delims
= " \t";
3938 char *const addr
= strtok_r(line
, delims
, &strtok_state
);
3939 char *hostname
, *hash
;
3940 struct sockaddr_storage ss
;
3941 int socklen
= sizeof(ss
);
3942 ASSERT_LOCKED(base
);
3944 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3946 if (!addr
|| *addr
== '#')
3949 memset(&ss
, 0, sizeof(ss
));
3950 if (evutil_parse_sockaddr_port(addr
, (struct sockaddr
*)&ss
, &socklen
)<0)
3952 if (socklen
> (int)sizeof(struct sockaddr_in6
))
3955 if (sockaddr_getport((struct sockaddr
*)&ss
))
3958 while ((hostname
= NEXT_TOKEN
)) {
3959 struct hosts_entry
*he
;
3961 if ((hash
= strchr(hostname
, '#'))) {
3962 if (hash
== hostname
)
3967 namelen
= strlen(hostname
);
3969 he
= mm_calloc(1, sizeof(struct hosts_entry
)+namelen
);
3972 EVUTIL_ASSERT(socklen
<= (int)sizeof(he
->addr
));
3973 memcpy(&he
->addr
, &ss
, socklen
);
3974 memcpy(he
->hostname
, hostname
, namelen
+1);
3975 he
->addrlen
= socklen
;
3977 TAILQ_INSERT_TAIL(&base
->hostsdb
, he
, next
);
3988 evdns_base_load_hosts_impl(struct evdns_base
*base
, const char *hosts_fname
)
3990 char *str
=NULL
, *cp
, *eol
;
3994 ASSERT_LOCKED(base
);
3996 if (hosts_fname
== NULL
||
3997 (err
= evutil_read_file(hosts_fname
, &str
, &len
, 0)) < 0) {
3999 strlcpy(tmp
, "127.0.0.1 localhost", sizeof(tmp
));
4000 evdns_base_parse_hosts_line(base
, tmp
);
4001 strlcpy(tmp
, "::1 localhost", sizeof(tmp
));
4002 evdns_base_parse_hosts_line(base
, tmp
);
4003 return err
? -1 : 0;
4006 /* This will break early if there is a NUL in the hosts file.
4007 * Probably not a problem.*/
4010 eol
= strchr(cp
, '\n');
4014 evdns_base_parse_hosts_line(base
, cp
);
4017 evdns_base_parse_hosts_line(base
, cp
);
4027 evdns_base_load_hosts(struct evdns_base
*base
, const char *hosts_fname
)
4031 base
= current_base
;
4033 res
= evdns_base_load_hosts_impl(base
, hosts_fname
);
4038 /* A single request for a getaddrinfo, either v4 or v6. */
4039 struct getaddrinfo_subrequest
{
4040 struct evdns_request
*r
;
4044 /* State data used to implement an in-progress getaddrinfo. */
4045 struct evdns_getaddrinfo_request
{
4046 struct evdns_base
*evdns_base
;
4047 /* Copy of the modified 'hints' data that we'll use to build
4049 struct evutil_addrinfo hints
;
4050 /* The callback to invoke when we're done */
4051 evdns_getaddrinfo_cb user_cb
;
4052 /* User-supplied data to give to the callback. */
4054 /* The port to use when building sockaddrs. */
4056 /* The sub_request for an A record (if any) */
4057 struct getaddrinfo_subrequest ipv4_request
;
4058 /* The sub_request for an AAAA record (if any) */
4059 struct getaddrinfo_subrequest ipv6_request
;
4061 /* The cname result that we were told (if any) */
4064 /* If we have one request answered and one request still inflight,
4065 * then this field holds the answer from the first request... */
4066 struct evutil_addrinfo
*pending_result
;
4067 /* And this event is a timeout that will tell us to cancel the second
4068 * request if it's taking a long time. */
4069 struct event timeout
;
4071 /* And this field holds the error code from the first request... */
4073 /* If this is set, the user canceled this request. */
4074 unsigned user_canceled
: 1;
4075 /* If this is set, the user can no longer cancel this request; we're
4076 * just waiting for the free. */
4077 unsigned request_done
: 1;
4080 /* Convert an evdns errors to the equivalent getaddrinfo error. */
4082 evdns_err_to_getaddrinfo_err(int e1
)
4084 /* XXX Do this better! */
4085 if (e1
== DNS_ERR_NONE
)
4087 else if (e1
== DNS_ERR_NOTEXIST
)
4088 return EVUTIL_EAI_NONAME
;
4090 return EVUTIL_EAI_FAIL
;
4093 /* Return the more informative of two getaddrinfo errors. */
4095 getaddrinfo_merge_err(int e1
, int e2
)
4097 /* XXXX be cleverer here. */
4105 free_getaddrinfo_request(struct evdns_getaddrinfo_request
*data
)
4107 /* DO NOT CALL this if either of the requests is pending. Only once
4108 * both callbacks have been invoked is it safe to free the request */
4109 if (data
->pending_result
)
4110 evutil_freeaddrinfo(data
->pending_result
);
4111 if (data
->cname_result
)
4112 mm_free(data
->cname_result
);
4113 event_del(&data
->timeout
);
4119 add_cname_to_reply(struct evdns_getaddrinfo_request
*data
,
4120 struct evutil_addrinfo
*ai
)
4122 if (data
->cname_result
&& ai
) {
4123 ai
->ai_canonname
= data
->cname_result
;
4124 data
->cname_result
= NULL
;
4128 /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
4129 * request has finished, but the other one took too long to answer. Pass
4130 * along the answer we got, and cancel the other request.
4133 evdns_getaddrinfo_timeout_cb(evutil_socket_t fd
, short what
, void *ptr
)
4135 int v4_timedout
= 0, v6_timedout
= 0;
4136 struct evdns_getaddrinfo_request
*data
= ptr
;
4138 /* Cancel any pending requests, and note which one */
4139 if (data
->ipv4_request
.r
) {
4140 evdns_cancel_request(NULL
, data
->ipv4_request
.r
);
4142 EVDNS_LOCK(data
->evdns_base
);
4143 ++data
->evdns_base
->getaddrinfo_ipv4_timeouts
;
4144 EVDNS_UNLOCK(data
->evdns_base
);
4146 if (data
->ipv6_request
.r
) {
4147 evdns_cancel_request(NULL
, data
->ipv6_request
.r
);
4149 EVDNS_LOCK(data
->evdns_base
);
4150 ++data
->evdns_base
->getaddrinfo_ipv6_timeouts
;
4151 EVDNS_UNLOCK(data
->evdns_base
);
4154 /* We only use this timeout callback when we have an answer for
4156 EVUTIL_ASSERT(!v4_timedout
|| !v6_timedout
);
4158 /* Report the outcome of the other request that didn't time out. */
4159 if (data
->pending_result
) {
4160 add_cname_to_reply(data
, data
->pending_result
);
4161 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4162 data
->pending_result
= NULL
;
4164 int e
= data
->pending_error
;
4166 e
= EVUTIL_EAI_AGAIN
;
4167 data
->user_cb(e
, NULL
, data
->user_data
);
4170 if (!v4_timedout
&& !v6_timedout
) {
4171 /* should be impossible? XXXX */
4172 free_getaddrinfo_request(data
);
4177 evdns_getaddrinfo_set_timeout(struct evdns_base
*evdns_base
,
4178 struct evdns_getaddrinfo_request
*data
)
4180 return event_add(&data
->timeout
, &evdns_base
->global_getaddrinfo_allow_skew
);
4184 evdns_result_is_answer(int result
)
4186 return (result
!= DNS_ERR_NOTIMPL
&& result
!= DNS_ERR_REFUSED
&&
4187 result
!= DNS_ERR_SERVERFAILED
&& result
!= DNS_ERR_CANCEL
);
4191 evdns_getaddrinfo_gotresolve(int result
, char type
, int count
,
4192 int ttl
, void *addresses
, void *arg
)
4195 struct getaddrinfo_subrequest
*req
= arg
;
4196 struct getaddrinfo_subrequest
*other_req
;
4197 struct evdns_getaddrinfo_request
*data
;
4199 struct evutil_addrinfo
*res
;
4201 struct sockaddr_in sin
;
4202 struct sockaddr_in6 sin6
;
4203 struct sockaddr
*sa
;
4204 int socklen
, addrlen
;
4209 EVUTIL_ASSERT(req
->type
== DNS_IPv4_A
|| req
->type
== DNS_IPv6_AAAA
);
4210 if (req
->type
== DNS_IPv4_A
) {
4211 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv4_request
);
4212 other_req
= &data
->ipv6_request
;
4214 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv6_request
);
4215 other_req
= &data
->ipv4_request
;
4218 EVDNS_LOCK(data
->evdns_base
);
4219 if (evdns_result_is_answer(result
)) {
4220 if (req
->type
== DNS_IPv4_A
)
4221 ++data
->evdns_base
->getaddrinfo_ipv4_answered
;
4223 ++data
->evdns_base
->getaddrinfo_ipv6_answered
;
4225 user_canceled
= data
->user_canceled
;
4226 if (other_req
->r
== NULL
)
4227 data
->request_done
= 1;
4228 EVDNS_UNLOCK(data
->evdns_base
);
4232 if (result
== DNS_ERR_CANCEL
&& ! user_canceled
) {
4233 /* Internal cancel request from timeout or internal error.
4234 * we already answered the user. */
4235 if (other_req
->r
== NULL
)
4236 free_getaddrinfo_request(data
);
4240 if (result
== DNS_ERR_NONE
) {
4242 err
= EVUTIL_EAI_NODATA
;
4246 err
= evdns_err_to_getaddrinfo_err(result
);
4250 /* Looks like we got an error. */
4252 /* The other request is still working; maybe it will
4254 /* XXXX handle failure from set_timeout */
4255 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4256 data
->pending_error
= err
;
4260 if (user_canceled
) {
4261 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4262 } else if (data
->pending_result
) {
4263 /* If we have an answer waiting, and we weren't
4264 * canceled, ignore this error. */
4265 add_cname_to_reply(data
, data
->pending_result
);
4266 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4267 data
->pending_result
= NULL
;
4269 if (data
->pending_error
)
4270 err
= getaddrinfo_merge_err(err
,
4271 data
->pending_error
);
4272 data
->user_cb(err
, NULL
, data
->user_data
);
4274 free_getaddrinfo_request(data
);
4276 } else if (user_canceled
) {
4278 /* The other request is still working; let it hit this
4279 * callback with EVUTIL_EAI_CANCEL callback and report
4283 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4284 free_getaddrinfo_request(data
);
4288 /* Looks like we got some answers. We should turn them into addrinfos
4289 * and then either queue those or return them all. */
4290 EVUTIL_ASSERT(type
== DNS_IPv4_A
|| type
== DNS_IPv6_AAAA
);
4292 if (type
== DNS_IPv4_A
) {
4293 memset(&sin
, 0, sizeof(sin
));
4294 sin
.sin_family
= AF_INET
;
4295 sin
.sin_port
= htons(data
->port
);
4297 sa
= (struct sockaddr
*)&sin
;
4298 socklen
= sizeof(sin
);
4300 addrp
= &sin
.sin_addr
.s_addr
;
4302 memset(&sin6
, 0, sizeof(sin6
));
4303 sin6
.sin6_family
= AF_INET6
;
4304 sin6
.sin6_port
= htons(data
->port
);
4306 sa
= (struct sockaddr
*)&sin6
;
4307 socklen
= sizeof(sin6
);
4309 addrp
= &sin6
.sin6_addr
.s6_addr
;
4313 for (i
=0; i
< count
; ++i
) {
4314 struct evutil_addrinfo
*ai
;
4315 memcpy(addrp
, ((char*)addresses
)+i
*addrlen
, addrlen
);
4316 ai
= evutil_new_addrinfo(sa
, socklen
, &data
->hints
);
4319 evdns_cancel_request(NULL
, other_req
->r
);
4321 data
->user_cb(EVUTIL_EAI_MEMORY
, NULL
, data
->user_data
);
4323 evutil_freeaddrinfo(res
);
4325 if (other_req
->r
== NULL
)
4326 free_getaddrinfo_request(data
);
4329 res
= evutil_addrinfo_append(res
, ai
);
4333 /* The other request is still in progress; wait for it */
4334 /* XXXX handle failure from set_timeout */
4335 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4336 data
->pending_result
= res
;
4339 /* The other request is done or never started; append its
4340 * results (if any) and return them. */
4341 if (data
->pending_result
) {
4342 if (req
->type
== DNS_IPv4_A
)
4343 res
= evutil_addrinfo_append(res
,
4344 data
->pending_result
);
4346 res
= evutil_addrinfo_append(
4347 data
->pending_result
, res
);
4348 data
->pending_result
= NULL
;
4351 /* Call the user callback. */
4352 add_cname_to_reply(data
, res
);
4353 data
->user_cb(0, res
, data
->user_data
);
4356 free_getaddrinfo_request(data
);
4360 static struct hosts_entry
*
4361 find_hosts_entry(struct evdns_base
*base
, const char *hostname
,
4362 struct hosts_entry
*find_after
)
4364 struct hosts_entry
*e
;
4367 e
= TAILQ_NEXT(find_after
, next
);
4369 e
= TAILQ_FIRST(&base
->hostsdb
);
4371 for (; e
; e
= TAILQ_NEXT(e
, next
)) {
4372 if (!evutil_ascii_strcasecmp(e
->hostname
, hostname
))
4379 evdns_getaddrinfo_fromhosts(struct evdns_base
*base
,
4380 const char *nodename
, struct evutil_addrinfo
*hints
, ev_uint16_t port
,
4381 struct evutil_addrinfo
**res
)
4384 struct hosts_entry
*e
;
4385 struct evutil_addrinfo
*ai
=NULL
;
4386 int f
= hints
->ai_family
;
4389 for (e
= find_hosts_entry(base
, nodename
, NULL
); e
;
4390 e
= find_hosts_entry(base
, nodename
, e
)) {
4391 struct evutil_addrinfo
*ai_new
;
4393 if ((e
->addr
.sa
.sa_family
== AF_INET
&& f
== PF_INET6
) ||
4394 (e
->addr
.sa
.sa_family
== AF_INET6
&& f
== PF_INET
))
4396 ai_new
= evutil_new_addrinfo(&e
->addr
.sa
, e
->addrlen
, hints
);
4401 sockaddr_setport(ai_new
->ai_addr
, port
);
4402 ai
= evutil_addrinfo_append(ai
, ai_new
);
4407 /* Note that we return an empty answer if we found entries for
4408 * this hostname but none were of the right address type. */
4413 evutil_freeaddrinfo(ai
);
4418 struct evdns_getaddrinfo_request
*
4419 evdns_getaddrinfo(struct evdns_base
*dns_base
,
4420 const char *nodename
, const char *servname
,
4421 const struct evutil_addrinfo
*hints_in
,
4422 evdns_getaddrinfo_cb cb
, void *arg
)
4424 struct evdns_getaddrinfo_request
*data
;
4425 struct evutil_addrinfo hints
;
4426 struct evutil_addrinfo
*res
= NULL
;
4432 dns_base
= current_base
;
4435 "Call to getaddrinfo_async with no "
4436 "evdns_base configured.");
4437 cb(EVUTIL_EAI_FAIL
, NULL
, arg
); /* ??? better error? */
4442 /* If we _must_ answer this immediately, do so. */
4443 if ((hints_in
&& (hints_in
->ai_flags
& EVUTIL_AI_NUMERICHOST
))) {
4445 err
= evutil_getaddrinfo(nodename
, servname
, hints_in
, &res
);
4451 memcpy(&hints
, hints_in
, sizeof(hints
));
4453 memset(&hints
, 0, sizeof(hints
));
4454 hints
.ai_family
= PF_UNSPEC
;
4457 evutil_adjust_hints_for_addrconfig(&hints
);
4459 /* Now try to see if we _can_ answer immediately. */
4460 /* (It would be nice to do this by calling getaddrinfo directly, with
4461 * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
4462 * a reliable way to distinguish the "that wasn't a numeric host!" case
4463 * from any other EAI_NONAME cases.) */
4464 err
= evutil_getaddrinfo_common(nodename
, servname
, &hints
, &res
, &port
);
4465 if (err
!= EVUTIL_EAI_NEED_RESOLVE
) {
4470 /* If there is an entry in the hosts file, we should give it now. */
4471 if (!evdns_getaddrinfo_fromhosts(dns_base
, nodename
, &hints
, port
, &res
)) {
4476 /* Okay, things are serious now. We're going to need to actually
4479 data
= mm_calloc(1,sizeof(struct evdns_getaddrinfo_request
));
4481 cb(EVUTIL_EAI_MEMORY
, NULL
, arg
);
4485 memcpy(&data
->hints
, &hints
, sizeof(data
->hints
));
4486 data
->port
= (ev_uint16_t
)port
;
4487 data
->ipv4_request
.type
= DNS_IPv4_A
;
4488 data
->ipv6_request
.type
= DNS_IPv6_AAAA
;
4490 data
->user_data
= arg
;
4491 data
->evdns_base
= dns_base
;
4493 want_cname
= (hints
.ai_flags
& EVUTIL_AI_CANONNAME
);
4495 /* If we are asked for a PF_UNSPEC address, we launch two requests in
4496 * parallel: one for an A address and one for an AAAA address. We
4497 * can't send just one request, since many servers only answer one
4498 * question per DNS request.
4500 * Once we have the answer to one request, we allow for a short
4501 * timeout before we report it, to see if the other one arrives. If
4502 * they both show up in time, then we report both the answers.
4504 * If too many addresses of one type time out or fail, we should stop
4505 * launching those requests. (XXX we don't do that yet.)
4508 if (hints
.ai_family
!= PF_INET6
) {
4509 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv4 as %p",
4510 nodename
, &data
->ipv4_request
);
4512 data
->ipv4_request
.r
= evdns_base_resolve_ipv4(dns_base
,
4513 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4514 &data
->ipv4_request
);
4516 data
->ipv4_request
.r
->current_req
->put_cname_in_ptr
=
4517 &data
->cname_result
;
4519 if (hints
.ai_family
!= PF_INET
) {
4520 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv6 as %p",
4521 nodename
, &data
->ipv6_request
);
4523 data
->ipv6_request
.r
= evdns_base_resolve_ipv6(dns_base
,
4524 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4525 &data
->ipv6_request
);
4527 data
->ipv6_request
.r
->current_req
->put_cname_in_ptr
=
4528 &data
->cname_result
;
4531 evtimer_assign(&data
->timeout
, dns_base
->event_base
,
4532 evdns_getaddrinfo_timeout_cb
, data
);
4534 if (data
->ipv4_request
.r
|| data
->ipv6_request
.r
) {
4538 cb(EVUTIL_EAI_FAIL
, NULL
, arg
);
4544 evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request
*data
)
4546 EVDNS_LOCK(data
->evdns_base
);
4547 if (data
->request_done
) {
4548 EVDNS_UNLOCK(data
->evdns_base
);
4551 event_del(&data
->timeout
);
4552 data
->user_canceled
= 1;
4553 if (data
->ipv4_request
.r
)
4554 evdns_cancel_request(data
->evdns_base
, data
->ipv4_request
.r
);
4555 if (data
->ipv6_request
.r
)
4556 evdns_cancel_request(data
->evdns_base
, data
->ipv6_request
.r
);
4557 EVDNS_UNLOCK(data
->evdns_base
);