1 /* Copyright 2006-2007 Niels Provos
2 * Copyright 2007-2012 Nick Mathewson and Niels Provos
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * 3. The name of the author may not be used to endorse or promote products
13 * derived from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 /* Based on software by Adam Langly. Adam's original message:
30 * Adam Langley <agl@imperialviolet.org>
31 * http://www.imperialviolet.org/eventdns.html
34 * This software is Public Domain. To view a copy of the public domain dedication,
35 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
36 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
38 * I ask and expect, but do not require, that all derivative works contain an
39 * attribution similar to:
40 * Parts developed by Adam Langley <agl@imperialviolet.org>
42 * You may wish to replace the word "Parts" with something else depending on
43 * the amount of original code.
45 * (Derivative works does not include programs which link against, run or include
46 * the source verbatim in their source distributions)
51 #include <sys/types.h>
52 #include "event2/event-config.h"
54 #ifndef _FORTIFY_SOURCE
55 #define _FORTIFY_SOURCE 3
60 #ifdef _EVENT_HAVE_SYS_TIME_H
63 #ifdef _EVENT_HAVE_STDINT_H
69 #ifdef _EVENT_HAVE_UNISTD_H
80 #define _WIN32_IE 0x400
85 #include "event2/dns.h"
86 #include "event2/dns_struct.h"
87 #include "event2/dns_compat.h"
88 #include "event2/util.h"
89 #include "event2/event.h"
90 #include "event2/event_struct.h"
91 #include "event2/thread.h"
93 #include "event2/bufferevent.h"
94 #include "event2/bufferevent_struct.h"
95 #include "bufferevent-internal.h"
97 #include "defer-internal.h"
98 #include "log-internal.h"
99 #include "mm-internal.h"
100 #include "strlcpy-internal.h"
101 #include "ipv6-internal.h"
102 #include "util-internal.h"
103 #include "evthread-internal.h"
106 #include <winsock2.h>
108 #include <iphlpapi.h>
111 #include <sys/socket.h>
112 #include <netinet/in.h>
113 #include <arpa/inet.h>
116 #ifdef _EVENT_HAVE_NETINET_IN6_H
117 #include <netinet/in6.h>
120 #define EVDNS_LOG_DEBUG 0
121 #define EVDNS_LOG_WARN 1
122 #define EVDNS_LOG_MSG 2
124 #ifndef HOST_NAME_MAX
125 #define HOST_NAME_MAX 255
131 #define MIN(a,b) ((a)<(b)?(a):(b))
133 #define ASSERT_VALID_REQUEST(req) \
134 EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
136 #define u64 ev_uint64_t
137 #define u32 ev_uint32_t
138 #define u16 ev_uint16_t
139 #define u8 ev_uint8_t
141 /* maximum number of addresses from a single packet */
142 /* that we bother recording */
143 #define MAX_V4_ADDRS 32
144 #define MAX_V6_ADDRS 32
145 #define MAX_TXT_SIZE 255
148 #define TYPE_A EVDNS_TYPE_A
150 #define TYPE_PTR EVDNS_TYPE_PTR
151 #define TYPE_SOA EVDNS_TYPE_SOA
152 #define TYPE_AAAA EVDNS_TYPE_AAAA
153 #define TYPE_TXT EVDNS_TYPE_TXT
155 #define CLASS_INET EVDNS_CLASS_INET
157 /* Persistent handle. We keep this separate from 'struct request' since we
158 * need some object to last for as long as an evdns_request is outstanding so
159 * that it can be canceled, whereas a search request can lead to multiple
160 * 'struct request' instances being created over its lifetime. */
161 struct evdns_request
{
162 struct request
*current_req
;
163 struct evdns_base
*base
;
165 int pending_cb
; /* Waiting for its callback to be invoked; not
166 * owned by event base any more. */
168 /* elements used by the searching code */
170 struct search_state
*search_state
;
171 char *search_origname
; /* needs to be free()ed */
176 u8
*request
; /* the dns packet data */
177 u8 request_type
; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
178 unsigned int request_len
;
180 int tx_count
; /* the number of times that this packet has been sent */
181 void *user_pointer
; /* the pointer given to us for this request */
182 evdns_callback_type user_callback
;
183 struct nameserver
*ns
; /* the server which we last sent it */
185 /* these objects are kept in a circular list */
186 /* XXX We could turn this into a CIRCLEQ. */
187 struct request
*next
, *prev
;
189 struct event timeout_event
;
191 u16 trans_id
; /* the transaction id */
192 unsigned request_appended
:1; /* true if the request pointer is data which follows this struct */
193 unsigned transmit_me
:1; /* needs to be transmitted */
195 /* XXXX This is a horrible hack. */
196 char **put_cname_in_ptr
; /* store the cname here if we get one. */
198 struct evdns_base
*base
;
200 struct evdns_request
*handle
;
205 unsigned int have_answer
: 1;
209 u32 addresses
[MAX_V4_ADDRS
];
213 struct in6_addr addresses
[MAX_V6_ADDRS
];
216 char name
[HOST_NAME_MAX
];
220 struct txt_record records
[1];
226 evutil_socket_t socket
; /* a connected UDP socket */
227 struct sockaddr_storage address
;
228 ev_socklen_t addrlen
;
229 int failed_times
; /* number of times which we have given this server a chance */
230 int timedout
; /* number of times in a row a request has timed out */
232 /* these objects are kept in a circular list */
233 struct nameserver
*next
, *prev
;
234 struct event timeout_event
; /* used to keep the timeout for */
235 /* when we next probe this server. */
236 /* Valid if state == 0 */
237 /* Outstanding probe request for this nameserver, if any */
238 struct evdns_request
*probe_request
;
239 char state
; /* zero if we think that this server is down */
240 char choked
; /* true if we have an EAGAIN from this server's socket */
241 char write_waiting
; /* true if we are waiting for EV_WRITE events */
242 struct evdns_base
*base
;
246 /* Represents a local port where we're listening for DNS requests. Right now, */
247 /* only UDP is supported. */
248 struct evdns_server_port
{
249 evutil_socket_t socket
; /* socket we use to read queries and write replies. */
250 int refcnt
; /* reference count. */
251 char choked
; /* Are we currently blocked from writing? */
252 char closing
; /* Are we trying to close this port, pending writes? */
253 evdns_request_callback_fn_type user_callback
; /* Fn to handle requests */
254 void *user_data
; /* Opaque pointer passed to user_callback */
255 struct event event
; /* Read/write event */
256 /* circular list of replies that we want to write. */
257 struct server_request
*pending_replies
;
258 struct event_base
*event_base
;
260 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
265 /* Represents part of a reply being built. (That is, a single RR.) */
266 struct server_reply_item
{
267 struct server_reply_item
*next
; /* next item in sequence. */
268 char *name
; /* name part of the RR */
269 u16 type
; /* The RR type */
270 u16
class; /* The RR class (usually CLASS_INET) */
271 u32 ttl
; /* The RR TTL */
272 char is_name
; /* True iff data is a label */
273 u16 datalen
; /* Length of data; -1 if data is a label */
274 void *data
; /* The contents of the RR */
277 /* Represents a request that we've received as a DNS server, and holds */
278 /* the components of the reply as we're constructing it. */
279 struct server_request
{
280 /* Pointers to the next and previous entries on the list of replies */
281 /* that we're waiting to write. Only set if we have tried to respond */
282 /* and gotten EAGAIN. */
283 struct server_request
*next_pending
;
284 struct server_request
*prev_pending
;
286 u16 trans_id
; /* Transaction id. */
287 struct evdns_server_port
*port
; /* Which port received this request on? */
288 struct sockaddr_storage addr
; /* Where to send the response */
289 ev_socklen_t addrlen
; /* length of addr */
291 int n_answer
; /* how many answer RRs have been set? */
292 int n_authority
; /* how many authority RRs have been set? */
293 int n_additional
; /* how many additional RRs have been set? */
295 struct server_reply_item
*answer
; /* linked list of answer RRs */
296 struct server_reply_item
*authority
; /* linked list of authority RRs */
297 struct server_reply_item
*additional
; /* linked list of additional RRs */
299 /* Constructed response. Only set once we're ready to send a reply. */
300 /* Once this is set, the RR fields are cleared, and no more should be set. */
304 /* Caller-visible fields: flags, questions. */
305 struct evdns_server_request base
;
309 /* An array of n_req_heads circular lists for inflight requests.
310 * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
312 struct request
**req_heads
;
313 /* A circular list of requests that we're waiting to send, but haven't
314 * sent yet because there are too many requests inflight */
315 struct request
*req_waiting_head
;
316 /* A circular list of nameservers. */
317 struct nameserver
*server_head
;
320 struct event_base
*event_base
;
322 /* The number of good nameservers that we have */
323 int global_good_nameservers
;
325 /* inflight requests are contained in the req_head list */
326 /* and are actually going out across the network */
327 int global_requests_inflight
;
328 /* requests which aren't inflight are in the waiting list */
329 /* and are counted here */
330 int global_requests_waiting
;
332 int global_max_requests_inflight
;
334 struct timeval global_timeout
; /* 5 seconds by default */
335 int global_max_reissues
; /* a reissue occurs when we get some errors from the server */
336 int global_max_retransmits
; /* number of times we'll retransmit a request which timed out */
337 /* number of timeouts in a row before we consider this server to be down */
338 int global_max_nameserver_timeout
;
339 /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
340 int global_randomize_case
;
342 /* The first time that a nameserver fails, how long do we wait before
343 * probing to see if it has returned? */
344 struct timeval global_nameserver_probe_initial_timeout
;
346 /** Port to bind to for outgoing DNS packets. */
347 struct sockaddr_storage global_outgoing_address
;
348 /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
349 ev_socklen_t global_outgoing_addrlen
;
351 struct timeval global_getaddrinfo_allow_skew
;
353 int getaddrinfo_ipv4_timeouts
;
354 int getaddrinfo_ipv6_timeouts
;
355 int getaddrinfo_ipv4_answered
;
356 int getaddrinfo_ipv6_answered
;
358 struct search_state
*global_search_state
;
360 TAILQ_HEAD(hosts_list
, hosts_entry
) hostsdb
;
362 #ifndef _EVENT_DISABLE_THREAD_SUPPORT
368 TAILQ_ENTRY(hosts_entry
) next
;
371 struct sockaddr_in sin
;
372 struct sockaddr_in6 sin6
;
378 static struct evdns_base
*current_base
= NULL
;
381 evdns_get_global_base(void)
386 /* Given a pointer to an evdns_server_request, get the corresponding */
387 /* server_request. */
388 #define TO_SERVER_REQUEST(base_ptr) \
389 ((struct server_request*) \
390 (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
392 #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
394 static struct nameserver
*nameserver_pick(struct evdns_base
*base
);
395 static void evdns_request_insert(struct request
*req
, struct request
**head
);
396 static void evdns_request_remove(struct request
*req
, struct request
**head
);
397 static void nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
398 static int evdns_transmit(struct evdns_base
*base
);
399 static int evdns_request_transmit(struct request
*req
);
400 static void nameserver_send_probe(struct nameserver
*const ns
);
401 static void search_request_finished(struct evdns_request
*const);
402 static int search_try_next(struct evdns_request
*const req
);
403 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
);
404 static void evdns_requests_pump_waiting_queue(struct evdns_base
*base
);
405 static u16
transaction_id_pick(struct evdns_base
*base
);
406 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
);
407 static void request_submit(struct request
*const req
);
409 static int server_request_free(struct server_request
*req
);
410 static void server_request_free_answers(struct server_request
*req
);
411 static void server_port_free(struct evdns_server_port
*port
);
412 static void server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
);
413 static int evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
);
414 static int evdns_base_set_option_impl(struct evdns_base
*base
,
415 const char *option
, const char *val
, int flags
);
416 static void evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
);
418 static int strtoint(const char *const str
);
420 #ifdef _EVENT_DISABLE_THREAD_SUPPORT
421 #define EVDNS_LOCK(base) _EVUTIL_NIL_STMT
422 #define EVDNS_UNLOCK(base) _EVUTIL_NIL_STMT
423 #define ASSERT_LOCKED(base) _EVUTIL_NIL_STMT
425 #define EVDNS_LOCK(base) \
426 EVLOCK_LOCK((base)->lock, 0)
427 #define EVDNS_UNLOCK(base) \
428 EVLOCK_UNLOCK((base)->lock, 0)
429 #define ASSERT_LOCKED(base) \
430 EVLOCK_ASSERT_LOCKED((base)->lock)
434 default_evdns_log_fn(int warning
, const char *buf
)
436 if (warning
== EVDNS_LOG_WARN
)
437 event_warnx("[evdns] %s", buf
);
438 else if (warning
== EVDNS_LOG_MSG
)
439 event_msgx("[evdns] %s", buf
);
441 event_debug(("[evdns] %s", buf
));
444 static evdns_debug_log_fn_type evdns_log_fn
= NULL
;
447 evdns_set_log_fn(evdns_debug_log_fn_type fn
)
453 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
455 #define EVDNS_LOG_CHECK
458 static void _evdns_log(int warn
, const char *fmt
, ...) EVDNS_LOG_CHECK
;
460 _evdns_log(int warn
, const char *fmt
, ...)
467 evutil_vsnprintf(buf
, sizeof(buf
), fmt
, args
);
470 if (warn
== EVDNS_LOG_MSG
)
471 warn
= EVDNS_LOG_WARN
;
472 evdns_log_fn(warn
, buf
);
474 default_evdns_log_fn(warn
, buf
);
479 #define log _evdns_log
481 /* This walks the list of inflight requests to find the */
482 /* one with a matching transaction id. Returns NULL on */
484 static struct request
*
485 request_find_from_trans_id(struct evdns_base
*base
, u16 trans_id
) {
486 struct request
*req
= REQ_HEAD(base
, trans_id
);
487 struct request
*const started_at
= req
;
493 if (req
->trans_id
== trans_id
) return req
;
495 } while (req
!= started_at
);
501 /* a libevent callback function which is called when a nameserver */
502 /* has gone down and we want to test if it has came back to life yet */
504 nameserver_prod_callback(evutil_socket_t fd
, short events
, void *arg
) {
505 struct nameserver
*const ns
= (struct nameserver
*) arg
;
509 EVDNS_LOCK(ns
->base
);
510 nameserver_send_probe(ns
);
511 EVDNS_UNLOCK(ns
->base
);
514 /* a libevent callback which is called when a nameserver probe (to see if */
515 /* it has come back to life) times out. We increment the count of failed_times */
516 /* and wait longer to send the next probe packet. */
518 nameserver_probe_failed(struct nameserver
*const ns
) {
519 struct timeval timeout
;
522 ASSERT_LOCKED(ns
->base
);
523 (void) evtimer_del(&ns
->timeout_event
);
524 if (ns
->state
== 1) {
525 /* This can happen if the nameserver acts in a way which makes us mark */
526 /* it as bad and then starts sending good replies. */
530 #define MAX_PROBE_TIMEOUT 3600
531 #define TIMEOUT_BACKOFF_FACTOR 3
533 memcpy(&timeout
, &ns
->base
->global_nameserver_probe_initial_timeout
,
534 sizeof(struct timeval
));
535 for (i
=ns
->failed_times
; i
> 0 && timeout
.tv_sec
< MAX_PROBE_TIMEOUT
; --i
) {
536 timeout
.tv_sec
*= TIMEOUT_BACKOFF_FACTOR
;
537 timeout
.tv_usec
*= TIMEOUT_BACKOFF_FACTOR
;
538 if (timeout
.tv_usec
> 1000000) {
539 timeout
.tv_sec
+= timeout
.tv_usec
/ 1000000;
540 timeout
.tv_usec
%= 1000000;
543 if (timeout
.tv_sec
> MAX_PROBE_TIMEOUT
) {
544 timeout
.tv_sec
= MAX_PROBE_TIMEOUT
;
550 if (evtimer_add(&ns
->timeout_event
, &timeout
) < 0) {
553 "Error from libevent when adding timer event for %s",
554 evutil_format_sockaddr_port(
555 (struct sockaddr
*)&ns
->address
,
556 addrbuf
, sizeof(addrbuf
)));
560 /* called when a nameserver has been deemed to have failed. For example, too */
561 /* many packets have timed out etc */
563 nameserver_failed(struct nameserver
*const ns
, const char *msg
) {
564 struct request
*req
, *started_at
;
565 struct evdns_base
*base
= ns
->base
;
570 /* if this nameserver has already been marked as failed */
571 /* then don't do anything */
572 if (!ns
->state
) return;
574 log(EVDNS_LOG_MSG
, "Nameserver %s has failed: %s",
575 evutil_format_sockaddr_port(
576 (struct sockaddr
*)&ns
->address
,
577 addrbuf
, sizeof(addrbuf
)),
580 base
->global_good_nameservers
--;
581 EVUTIL_ASSERT(base
->global_good_nameservers
>= 0);
582 if (base
->global_good_nameservers
== 0) {
583 log(EVDNS_LOG_MSG
, "All nameservers have failed");
587 ns
->failed_times
= 1;
589 if (evtimer_add(&ns
->timeout_event
,
590 &base
->global_nameserver_probe_initial_timeout
) < 0) {
592 "Error from libevent when adding timer event for %s",
593 evutil_format_sockaddr_port(
594 (struct sockaddr
*)&ns
->address
,
595 addrbuf
, sizeof(addrbuf
)));
599 /* walk the list of inflight requests to see if any can be reassigned to */
600 /* a different server. Requests in the waiting queue don't have a */
601 /* nameserver assigned yet */
603 /* if we don't have *any* good nameservers then there's no point */
604 /* trying to reassign requests to one */
605 if (!base
->global_good_nameservers
) return;
607 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
608 req
= started_at
= base
->req_heads
[i
];
611 if (req
->tx_count
== 0 && req
->ns
== ns
) {
612 /* still waiting to go out, can be moved */
613 /* to another server */
614 req
->ns
= nameserver_pick(base
);
617 } while (req
!= started_at
);
623 nameserver_up(struct nameserver
*const ns
)
626 ASSERT_LOCKED(ns
->base
);
627 if (ns
->state
) return;
628 log(EVDNS_LOG_MSG
, "Nameserver %s is back up",
629 evutil_format_sockaddr_port(
630 (struct sockaddr
*)&ns
->address
,
631 addrbuf
, sizeof(addrbuf
)));
632 evtimer_del(&ns
->timeout_event
);
633 if (ns
->probe_request
) {
634 evdns_cancel_request(ns
->base
, ns
->probe_request
);
635 ns
->probe_request
= NULL
;
638 ns
->failed_times
= 0;
640 ns
->base
->global_good_nameservers
++;
644 request_trans_id_set(struct request
*const req
, const u16 trans_id
) {
645 req
->trans_id
= trans_id
;
646 *((u16
*) req
->request
) = htons(trans_id
);
649 /* Called to remove a request from a list and dealloc it. */
650 /* head is a pointer to the head of the list it should be */
651 /* removed from or NULL if the request isn't in a list. */
652 /* when free_handle is one, free the handle as well. */
654 request_finished(struct request
*const req
, struct request
**head
, int free_handle
) {
655 struct evdns_base
*base
= req
->base
;
656 int was_inflight
= (head
!= &base
->req_waiting_head
);
658 ASSERT_VALID_REQUEST(req
);
661 evdns_request_remove(req
, head
);
663 log(EVDNS_LOG_DEBUG
, "Removing timeout for request %p", req
);
665 evtimer_del(&req
->timeout_event
);
666 base
->global_requests_inflight
--;
668 base
->global_requests_waiting
--;
670 /* it was initialized during request_new / evtimer_assign */
671 event_debug_unassign(&req
->timeout_event
);
673 if (!req
->request_appended
) {
674 /* need to free the request data on it's own */
675 mm_free(req
->request
);
677 /* the request data is appended onto the header */
678 /* so everything gets free()ed when we: */
682 EVUTIL_ASSERT(req
->handle
->current_req
== req
);
685 search_request_finished(req
->handle
);
686 req
->handle
->current_req
= NULL
;
687 if (! req
->handle
->pending_cb
) {
688 /* If we're planning to run the callback,
689 * don't free the handle until later. */
690 mm_free(req
->handle
);
692 req
->handle
= NULL
; /* If we have a bug, let's crash
695 req
->handle
->current_req
= NULL
;
701 evdns_requests_pump_waiting_queue(base
);
705 /* This is called when a server returns a funny error code. */
706 /* We try the request again with another server. */
710 /* 1 failed/reissue is pointless */
712 request_reissue(struct request
*req
) {
713 const struct nameserver
*const last_ns
= req
->ns
;
714 ASSERT_LOCKED(req
->base
);
715 ASSERT_VALID_REQUEST(req
);
716 /* the last nameserver should have been marked as failing */
717 /* by the caller of this function, therefore pick will try */
718 /* not to return it */
719 req
->ns
= nameserver_pick(req
->base
);
720 if (req
->ns
== last_ns
) {
721 /* ... but pick did return it */
722 /* not a lot of point in trying again with the */
727 req
->reissue_count
++;
729 req
->transmit_me
= 1;
734 /* this function looks for space on the inflight queue and promotes */
735 /* requests from the waiting queue if it can. */
737 evdns_requests_pump_waiting_queue(struct evdns_base
*base
) {
739 while (base
->global_requests_inflight
< base
->global_max_requests_inflight
&&
740 base
->global_requests_waiting
) {
742 /* move a request from the waiting queue to the inflight queue */
743 EVUTIL_ASSERT(base
->req_waiting_head
);
744 req
= base
->req_waiting_head
;
745 evdns_request_remove(req
, &base
->req_waiting_head
);
747 base
->global_requests_waiting
--;
748 base
->global_requests_inflight
++;
750 req
->ns
= nameserver_pick(base
);
751 request_trans_id_set(req
, transaction_id_pick(base
));
753 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
754 evdns_request_transmit(req
);
755 evdns_transmit(base
);
759 /* TODO(nickm) document */
760 struct deferred_reply_callback
{
761 struct deferred_cb deferred
;
762 struct evdns_request
*handle
;
767 evdns_callback_type user_callback
;
772 reply_run_callback(struct deferred_cb
*d
, void *user_pointer
)
774 struct deferred_reply_callback
*cb
=
775 EVUTIL_UPCAST(d
, struct deferred_reply_callback
, deferred
);
777 switch (cb
->request_type
) {
780 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv4_A
,
781 cb
->reply
.data
.a
.addrcount
, cb
->ttl
,
782 cb
->reply
.data
.a
.addresses
,
785 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
788 if (cb
->have_reply
) {
789 char *name
= cb
->reply
.data
.ptr
.name
;
790 cb
->user_callback(DNS_ERR_NONE
, DNS_PTR
, 1, cb
->ttl
,
791 &name
, user_pointer
);
793 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
798 cb
->user_callback(DNS_ERR_NONE
, DNS_IPv6_AAAA
,
799 cb
->reply
.data
.aaaa
.addrcount
, cb
->ttl
,
800 cb
->reply
.data
.aaaa
.addresses
,
803 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
807 cb
->user_callback(DNS_ERR_NONE
, DNS_TXT
,
808 cb
->reply
.data
.txt
.recordscount
, cb
->ttl
,
809 cb
->reply
.data
.txt
.records
,
812 cb
->user_callback(cb
->err
, 0, 0, cb
->ttl
, NULL
, user_pointer
);
818 if (cb
->handle
&& cb
->handle
->pending_cb
) {
826 reply_schedule_callback(struct request
*const req
, u32 ttl
, u32 err
, struct reply
*reply
)
828 struct deferred_reply_callback
*d
= mm_calloc(1, sizeof(*d
));
831 event_warn("%s: Couldn't allocate space for deferred callback.",
836 ASSERT_LOCKED(req
->base
);
838 d
->request_type
= req
->request_type
;
839 d
->user_callback
= req
->user_callback
;
844 memcpy(&d
->reply
, reply
, sizeof(struct reply
));
848 req
->handle
->pending_cb
= 1;
849 d
->handle
= req
->handle
;
852 event_deferred_cb_init(&d
->deferred
, reply_run_callback
,
854 event_deferred_cb_schedule(
855 event_base_get_deferred_cb_queue(req
->base
->event_base
),
859 /* this processes a parsed reply packet */
861 reply_handle(struct request
*const req
, u16 flags
, u32 ttl
, struct reply
*reply
) {
864 static const int error_codes
[] = {
865 DNS_ERR_FORMAT
, DNS_ERR_SERVERFAILED
, DNS_ERR_NOTEXIST
,
866 DNS_ERR_NOTIMPL
, DNS_ERR_REFUSED
869 ASSERT_LOCKED(req
->base
);
870 ASSERT_VALID_REQUEST(req
);
872 if (flags
& 0x020f || !reply
|| !reply
->have_answer
) {
873 /* there was an error */
874 if (flags
& 0x0200) {
875 error
= DNS_ERR_TRUNCATED
;
876 } else if (flags
& 0x000f) {
877 u16 error_code
= (flags
& 0x000f) - 1;
878 if (error_code
> 4) {
879 error
= DNS_ERR_UNKNOWN
;
881 error
= error_codes
[error_code
];
883 } else if (reply
&& !reply
->have_answer
) {
884 error
= DNS_ERR_NODATA
;
886 error
= DNS_ERR_UNKNOWN
;
890 case DNS_ERR_NOTIMPL
:
891 case DNS_ERR_REFUSED
:
892 /* we regard these errors as marking a bad nameserver */
893 if (req
->reissue_count
< req
->base
->global_max_reissues
) {
895 evutil_snprintf(msg
, sizeof(msg
), "Bad response %d (%s)",
896 error
, evdns_err_to_string(error
));
897 nameserver_failed(req
->ns
, msg
);
898 if (!request_reissue(req
)) return;
901 case DNS_ERR_SERVERFAILED
:
902 /* rcode 2 (servfailed) sometimes means "we
903 * are broken" and sometimes (with some binds)
904 * means "that request was very confusing."
905 * Treat this as a timeout, not a failure.
907 log(EVDNS_LOG_DEBUG
, "Got a SERVERFAILED from nameserver"
908 "at %s; will allow the request to time out.",
909 evutil_format_sockaddr_port(
910 (struct sockaddr
*)&req
->ns
->address
,
911 addrbuf
, sizeof(addrbuf
)));
914 /* we got a good reply from the nameserver: it is up. */
915 if (req
->handle
== req
->ns
->probe_request
) {
916 /* Avoid double-free */
917 req
->ns
->probe_request
= NULL
;
920 nameserver_up(req
->ns
);
923 if (req
->handle
->search_state
&&
924 req
->request_type
!= TYPE_PTR
) {
925 /* if we have a list of domains to search in,
926 * try the next one */
927 if (!search_try_next(req
->handle
)) {
928 /* a new request was issued so this
929 * request is finished and */
930 /* the user callback will be made when
931 * that request (or a */
932 /* child of it) finishes. */
937 /* all else failed. Pass the failure up */
938 reply_schedule_callback(req
, ttl
, error
, NULL
);
939 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
941 /* all ok, tell the user */
942 reply_schedule_callback(req
, ttl
, 0, reply
);
943 if (req
->handle
== req
->ns
->probe_request
)
944 req
->ns
->probe_request
= NULL
; /* Avoid double-free */
945 nameserver_up(req
->ns
);
946 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
951 name_parse(u8
*packet
, int length
, int *idx
, char *name_out
, int name_out_len
) {
955 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while (0)
956 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while (0)
957 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
960 const char *const end
= name_out
+ name_out_len
;
962 /* Normally, names are a series of length prefixed strings terminated */
963 /* with a length of 0 (the lengths are u8's < 63). */
964 /* However, the length can start with a pair of 1 bits and that */
965 /* means that the next 14 bits are a pointer within the current */
970 if (j
>= length
) return -1;
972 if (!label_len
) break;
973 if (label_len
& 0xc0) {
976 if (name_end
< 0) name_end
= j
;
977 j
= (((int)label_len
& 0x3f) << 8) + ptr_low
;
978 /* Make sure that the target offset is in-bounds. */
979 if (j
< 0 || j
>= length
) return -1;
980 /* If we've jumped more times than there are characters in the
981 * message, we must have a loop. */
982 if (++ptr_count
> length
) return -1;
985 if (label_len
> 63) return -1;
986 if (cp
!= name_out
) {
987 if (cp
+ 1 >= end
) return -1;
990 if (cp
+ label_len
>= end
) return -1;
991 memcpy(cp
, packet
+ j
, label_len
);
995 if (cp
>= end
) return -1;
1006 /* parses a raw request from a nameserver */
1008 reply_parse(struct evdns_base
*base
, u8
*packet
, int length
) {
1009 int j
= 0, k
= 0; /* index into packet */
1010 u16 _t
; /* used by the macros */
1011 u32 _t32
; /* used by the macros */
1012 char tmp_name
[256], cmp_name
[256]; /* used by the macros */
1013 int name_matches
= 0;
1015 u16 trans_id
, questions
, answers
, authority
, additional
, datalength
;
1017 u32 ttl
, ttl_r
= 0xffffffff;
1019 struct request
*req
= NULL
;
1022 ASSERT_LOCKED(base
);
1030 (void) authority
; /* suppress "unused variable" warnings. */
1031 (void) additional
; /* suppress "unused variable" warnings. */
1033 req
= request_find_from_trans_id(base
, trans_id
);
1034 if (!req
) return -1;
1035 EVUTIL_ASSERT(req
->base
== base
);
1037 memset(&reply
, 0, sizeof(reply
));
1039 /* If it's not an answer, it doesn't correspond to any request. */
1040 if (!(flags
& 0x8000)) return -1; /* must be an answer */
1041 if ((flags
& 0x020f) && (flags
& 0x020f) != DNS_ERR_NOTEXIST
) {
1042 /* there was an error and it's not NXDOMAIN */
1045 /* if (!answers) return; */ /* must have an answer of some form */
1047 /* This macro skips a name in the DNS reply. */
1049 do { tmp_name[0] = '\0'; \
1050 if (name_parse(packet, length, &j, tmp_name, \
1051 sizeof(tmp_name))<0) \
1055 do { tmp_name[0] = '\0'; \
1056 cmp_name[0] = '\0'; \
1058 if (name_parse(packet, length, &j, tmp_name, \
1059 sizeof(tmp_name))<0) \
1061 if (name_parse(req->request, req->request_len, &k, \
1062 cmp_name, sizeof(cmp_name))<0) \
1064 if (base->global_randomize_case) { \
1065 if (strcmp(tmp_name, cmp_name) == 0) \
1068 if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0) \
1073 reply
.type
= req
->request_type
;
1075 /* skip over each question in the reply */
1076 for (i
= 0; i
< questions
; ++i
) {
1077 /* the question looks like
1078 * <label:name><u16:type><u16:class>
1082 if (j
> length
) goto err
;
1088 /* now we have the answer section which looks like
1089 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
1092 for (i
= 0; i
< answers
; ++i
) {
1101 if (type
== TYPE_A
&& class == CLASS_INET
) {
1102 int addrcount
, addrtocopy
;
1103 if (req
->request_type
!= TYPE_A
) {
1104 j
+= datalength
; continue;
1106 if ((datalength
& 3) != 0) /* not an even number of As. */
1108 addrcount
= datalength
>> 2;
1109 addrtocopy
= MIN(MAX_V4_ADDRS
- reply
.data
.a
.addrcount
, (unsigned)addrcount
);
1111 ttl_r
= MIN(ttl_r
, ttl
);
1112 /* we only bother with the first four addresses. */
1113 if (j
+ 4*addrtocopy
> length
) goto err
;
1114 memcpy(&reply
.data
.a
.addresses
[reply
.data
.a
.addrcount
],
1115 packet
+ j
, 4*addrtocopy
);
1117 reply
.data
.a
.addrcount
+= addrtocopy
;
1118 reply
.have_answer
= 1;
1119 if (reply
.data
.a
.addrcount
== MAX_V4_ADDRS
) break;
1120 } else if (type
== TYPE_PTR
&& class == CLASS_INET
) {
1121 if (req
->request_type
!= TYPE_PTR
) {
1122 j
+= datalength
; continue;
1124 if (name_parse(packet
, length
, &j
, reply
.data
.ptr
.name
,
1125 sizeof(reply
.data
.ptr
.name
))<0)
1127 ttl_r
= MIN(ttl_r
, ttl
);
1128 reply
.have_answer
= 1;
1130 } else if (type
== TYPE_CNAME
) {
1131 char cname
[HOST_NAME_MAX
];
1132 if (!req
->put_cname_in_ptr
|| *req
->put_cname_in_ptr
) {
1133 j
+= datalength
; continue;
1135 if (name_parse(packet
, length
, &j
, cname
,
1138 *req
->put_cname_in_ptr
= mm_strdup(cname
);
1139 } else if (type
== TYPE_AAAA
&& class == CLASS_INET
) {
1140 int addrcount
, addrtocopy
;
1141 if (req
->request_type
!= TYPE_AAAA
) {
1142 j
+= datalength
; continue;
1144 if ((datalength
& 15) != 0) /* not an even number of AAAAs. */
1146 addrcount
= datalength
>> 4; /* each address is 16 bytes long */
1147 addrtocopy
= MIN(MAX_V6_ADDRS
- reply
.data
.aaaa
.addrcount
, (unsigned)addrcount
);
1148 ttl_r
= MIN(ttl_r
, ttl
);
1150 /* we only bother with the first four addresses. */
1151 if (j
+ 16*addrtocopy
> length
) goto err
;
1152 memcpy(&reply
.data
.aaaa
.addresses
[reply
.data
.aaaa
.addrcount
],
1153 packet
+ j
, 16*addrtocopy
);
1154 reply
.data
.aaaa
.addrcount
+= addrtocopy
;
1156 reply
.have_answer
= 1;
1157 if (reply
.data
.aaaa
.addrcount
== MAX_V6_ADDRS
) break;
1158 } else if (type
== TYPE_TXT
) {
1160 if (req
->request_type
!= TYPE_TXT
) {
1161 j
+= datalength
; continue;
1164 if (txtlen
> sizeof reply
.data
.txt
.records
[0].txt
||
1165 datalength
<= txtlen
) {
1168 memcpy(reply
.data
.txt
.records
[0].txt
, &packet
[j
+ 1], txtlen
);
1169 reply
.data
.txt
.records
[0].len
= (size_t) txtlen
;
1170 reply
.data
.txt
.recordscount
= (u32
) 1U;
1171 ttl_r
= MIN(ttl_r
, ttl
);
1172 reply
.have_answer
= 1;
1175 /* skip over any other type of resource */
1180 if (!reply
.have_answer
) {
1181 for (i
= 0; i
< authority
; ++i
) {
1188 if (type
== TYPE_SOA
&& class == CLASS_INET
) {
1189 u32 serial
, refresh
, retry
, expire
, minimum
;
1201 ttl_r
= MIN(ttl_r
, ttl
);
1202 ttl_r
= MIN(ttl_r
, minimum
);
1204 /* skip over any other type of resource */
1210 if (ttl_r
== 0xffffffff)
1213 reply_handle(req
, flags
, ttl_r
, &reply
);
1217 reply_handle(req
, flags
, 0, NULL
);
1221 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1222 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1225 request_parse(u8
*packet
, int length
, struct evdns_server_port
*port
, struct sockaddr
*addr
, ev_socklen_t addrlen
)
1227 int j
= 0; /* index into packet */
1228 u16 _t
; /* used by the macros */
1229 char tmp_name
[256]; /* used by the macros */
1232 u16 trans_id
, flags
, questions
, answers
, authority
, additional
;
1233 struct server_request
*server_req
= NULL
;
1235 ASSERT_LOCKED(port
);
1237 /* Get the header fields */
1248 if (flags
& 0x8000) return -1; /* Must not be an answer. */
1249 flags
&= 0x0110; /* Only RD and CD get preserved. */
1251 server_req
= mm_malloc(sizeof(struct server_request
));
1252 if (server_req
== NULL
) return -1;
1253 memset(server_req
, 0, sizeof(struct server_request
));
1255 server_req
->trans_id
= trans_id
;
1256 memcpy(&server_req
->addr
, addr
, addrlen
);
1257 server_req
->addrlen
= addrlen
;
1259 server_req
->base
.flags
= flags
;
1260 server_req
->base
.nquestions
= 0;
1261 server_req
->base
.questions
= mm_calloc(sizeof(struct evdns_server_question
*), questions
);
1262 if (server_req
->base
.questions
== NULL
)
1265 for (i
= 0; i
< questions
; ++i
) {
1267 struct evdns_server_question
*q
;
1269 if (name_parse(packet
, length
, &j
, tmp_name
, sizeof(tmp_name
))<0)
1273 namelen
= (int)strlen(tmp_name
);
1274 q
= mm_malloc(sizeof(struct evdns_server_question
) + namelen
);
1278 q
->dns_question_class
= class;
1279 memcpy(q
->name
, tmp_name
, namelen
+1);
1280 server_req
->base
.questions
[server_req
->base
.nquestions
++] = q
;
1283 /* Ignore answers, authority, and additional. */
1285 server_req
->port
= port
;
1288 /* Only standard queries are supported. */
1289 if (flags
& 0x7800) {
1290 evdns_server_request_respond(&(server_req
->base
), DNS_ERR_NOTIMPL
);
1294 port
->user_callback(&(server_req
->base
), port
->user_data
);
1299 if (server_req
->base
.questions
) {
1300 for (i
= 0; i
< server_req
->base
.nquestions
; ++i
)
1301 mm_free(server_req
->base
.questions
[i
]);
1302 mm_free(server_req
->base
.questions
);
1304 mm_free(server_req
);
1314 static int (*rand_init_function
)(void) = evutil_secure_rng_init
;
1316 static void (*rand_bytes_function
)(void *buf
, size_t n
) =
1317 evutil_secure_rng_get_bytes
;
1320 evdns_set_transaction_id_fn(ev_uint16_t (*fn
)(void))
1325 evdns_set_random_init_fn(int (*fn
)(void))
1327 rand_init_function
= fn
;
1331 evdns_set_random_bytes_fn(void (*fn
)(void *, size_t))
1333 rand_bytes_function
= fn
;
1336 /* Try to choose a strong transaction id which isn't already in flight */
1338 transaction_id_pick(struct evdns_base
*base
) {
1339 ASSERT_LOCKED(base
);
1342 rand_bytes_function(&trans_id
, sizeof(trans_id
));
1344 if (trans_id
== 0xffff) continue;
1345 /* now check to see if that id is already inflight */
1346 if (request_find_from_trans_id(base
, trans_id
) == NULL
)
1351 /* choose a namesever to use. This function will try to ignore */
1352 /* nameservers which we think are down and load balance across the rest */
1353 /* by updating the server_head global each time. */
1354 static struct nameserver
*
1355 nameserver_pick(struct evdns_base
*base
) {
1356 struct nameserver
*started_at
= base
->server_head
, *picked
;
1357 ASSERT_LOCKED(base
);
1358 if (!base
->server_head
) return NULL
;
1360 /* if we don't have any good nameservers then there's no */
1361 /* point in trying to find one. */
1362 if (!base
->global_good_nameservers
) {
1363 base
->server_head
= base
->server_head
->next
;
1364 return base
->server_head
;
1367 /* remember that nameservers are in a circular list */
1369 if (base
->server_head
->state
) {
1370 /* we think this server is currently good */
1371 picked
= base
->server_head
;
1372 base
->server_head
= base
->server_head
->next
;
1376 base
->server_head
= base
->server_head
->next
;
1377 if (base
->server_head
== started_at
) {
1378 /* all the nameservers seem to be down */
1379 /* so we just return this one and hope for the */
1381 EVUTIL_ASSERT(base
->global_good_nameservers
== 0);
1382 picked
= base
->server_head
;
1383 base
->server_head
= base
->server_head
->next
;
1389 /* this is called when a namesever socket is ready for reading */
1391 nameserver_read(struct nameserver
*ns
) {
1392 struct sockaddr_storage ss
;
1393 ev_socklen_t addrlen
= sizeof(ss
);
1396 ASSERT_LOCKED(ns
->base
);
1399 const int r
= recvfrom(ns
->socket
, (void*)packet
,
1401 (struct sockaddr
*)&ss
, &addrlen
);
1403 int err
= evutil_socket_geterror(ns
->socket
);
1404 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1406 nameserver_failed(ns
,
1407 evutil_socket_error_to_string(err
));
1410 if (evutil_sockaddr_cmp((struct sockaddr
*)&ss
,
1411 (struct sockaddr
*)&ns
->address
, 0)) {
1412 log(EVDNS_LOG_WARN
, "Address mismatch on received "
1413 "DNS packet. Apparent source was %s",
1414 evutil_format_sockaddr_port(
1415 (struct sockaddr
*)&ss
,
1416 addrbuf
, sizeof(addrbuf
)));
1421 reply_parse(ns
->base
, packet
, r
);
1425 /* Read a packet from a DNS client on a server port s, parse it, and */
1426 /* act accordingly. */
1428 server_port_read(struct evdns_server_port
*s
) {
1430 struct sockaddr_storage addr
;
1431 ev_socklen_t addrlen
;
1436 addrlen
= sizeof(struct sockaddr_storage
);
1437 r
= recvfrom(s
->socket
, (void*)packet
, sizeof(packet
), 0,
1438 (struct sockaddr
*) &addr
, &addrlen
);
1440 int err
= evutil_socket_geterror(s
->socket
);
1441 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1444 "Error %s (%d) while reading request.",
1445 evutil_socket_error_to_string(err
), err
);
1448 request_parse(packet
, r
, s
, (struct sockaddr
*) &addr
, addrlen
);
1452 /* Try to write all pending replies on a given DNS server port. */
1454 server_port_flush(struct evdns_server_port
*port
)
1456 struct server_request
*req
= port
->pending_replies
;
1457 ASSERT_LOCKED(port
);
1459 int r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
1460 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
1462 int err
= evutil_socket_geterror(port
->socket
);
1463 if (EVUTIL_ERR_RW_RETRIABLE(err
))
1465 log(EVDNS_LOG_WARN
, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err
), err
);
1467 if (server_request_free(req
)) {
1468 /* we released the last reference to req->port. */
1471 EVUTIL_ASSERT(req
!= port
->pending_replies
);
1472 req
= port
->pending_replies
;
1476 /* We have no more pending requests; stop listening for 'writeable' events. */
1477 (void) event_del(&port
->event
);
1478 event_assign(&port
->event
, port
->event_base
,
1479 port
->socket
, EV_READ
| EV_PERSIST
,
1480 server_port_ready_callback
, port
);
1482 if (event_add(&port
->event
, NULL
) < 0) {
1483 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server.");
1488 /* set if we are waiting for the ability to write to this server. */
1489 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1490 /* we stop these events. */
1492 nameserver_write_waiting(struct nameserver
*ns
, char waiting
) {
1493 ASSERT_LOCKED(ns
->base
);
1494 if (ns
->write_waiting
== waiting
) return;
1496 ns
->write_waiting
= waiting
;
1497 (void) event_del(&ns
->event
);
1498 event_assign(&ns
->event
, ns
->base
->event_base
,
1499 ns
->socket
, EV_READ
| (waiting
? EV_WRITE
: 0) | EV_PERSIST
,
1500 nameserver_ready_callback
, ns
);
1501 if (event_add(&ns
->event
, NULL
) < 0) {
1503 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for %s",
1504 evutil_format_sockaddr_port(
1505 (struct sockaddr
*)&ns
->address
,
1506 addrbuf
, sizeof(addrbuf
)));
1511 /* a callback function. Called by libevent when the kernel says that */
1512 /* a nameserver socket is ready for writing or reading */
1514 nameserver_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1515 struct nameserver
*ns
= (struct nameserver
*) arg
;
1518 EVDNS_LOCK(ns
->base
);
1519 if (events
& EV_WRITE
) {
1521 if (!evdns_transmit(ns
->base
)) {
1522 nameserver_write_waiting(ns
, 0);
1525 if (events
& EV_READ
) {
1526 nameserver_read(ns
);
1528 EVDNS_UNLOCK(ns
->base
);
1531 /* a callback function. Called by libevent when the kernel says that */
1532 /* a server socket is ready for writing or reading. */
1534 server_port_ready_callback(evutil_socket_t fd
, short events
, void *arg
) {
1535 struct evdns_server_port
*port
= (struct evdns_server_port
*) arg
;
1539 if (events
& EV_WRITE
) {
1541 server_port_flush(port
);
1543 if (events
& EV_READ
) {
1544 server_port_read(port
);
1549 /* This is an inefficient representation; only use it via the dnslabel_table_*
1550 * functions, so that is can be safely replaced with something smarter later. */
1551 #define MAX_LABELS 128
1552 /* Structures used to implement name compression */
1553 struct dnslabel_entry
{ char *v
; off_t pos
; };
1554 struct dnslabel_table
{
1555 int n_labels
; /* number of current entries */
1556 /* map from name to position in message */
1557 struct dnslabel_entry labels
[MAX_LABELS
];
1560 /* Initialize dnslabel_table. */
1562 dnslabel_table_init(struct dnslabel_table
*table
)
1564 table
->n_labels
= 0;
1567 /* Free all storage held by table, but not the table itself. */
1569 dnslabel_clear(struct dnslabel_table
*table
)
1572 for (i
= 0; i
< table
->n_labels
; ++i
)
1573 mm_free(table
->labels
[i
].v
);
1574 table
->n_labels
= 0;
1577 /* return the position of the label in the current message, or -1 if the label */
1578 /* hasn't been used yet. */
1580 dnslabel_table_get_pos(const struct dnslabel_table
*table
, const char *label
)
1583 for (i
= 0; i
< table
->n_labels
; ++i
) {
1584 if (!strcmp(label
, table
->labels
[i
].v
))
1585 return table
->labels
[i
].pos
;
1590 /* remember that we've used the label at position pos */
1592 dnslabel_table_add(struct dnslabel_table
*table
, const char *label
, off_t pos
)
1596 if (table
->n_labels
== MAX_LABELS
)
1598 v
= mm_strdup(label
);
1601 p
= table
->n_labels
++;
1602 table
->labels
[p
].v
= v
;
1603 table
->labels
[p
].pos
= pos
;
1608 /* Converts a string to a length-prefixed set of DNS labels, starting */
1609 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1610 /* of name. table is optional, and is used for compression. */
1612 /* Input: abc.def */
1613 /* Output: <3>abc<3>def<0> */
1615 /* Returns the first index after the encoded name, or negative on error. */
1616 /* -1 label was > 63 bytes */
1617 /* -2 name too long to fit in buffer. */
1620 dnsname_to_labels(u8
*const buf
, size_t buf_len
, off_t j
,
1621 const char *name
, const size_t name_len
,
1622 struct dnslabel_table
*table
) {
1623 const char *end
= name
+ name_len
;
1627 #define APPEND16(x) do { \
1628 if (j + 2 > (off_t)buf_len) \
1631 memcpy(buf + j, &_t, 2); \
1634 #define APPEND32(x) do { \
1635 if (j + 4 > (off_t)buf_len) \
1638 memcpy(buf + j, &_t32, 4); \
1642 if (name_len
> 255) return -2;
1645 const char *const start
= name
;
1646 if (table
&& (ref
= dnslabel_table_get_pos(table
, name
)) >= 0) {
1647 APPEND16(ref
| 0xc000);
1650 name
= strchr(name
, '.');
1652 const size_t label_len
= end
- start
;
1653 if (label_len
> 63) return -1;
1654 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1655 if (table
) dnslabel_table_add(table
, start
, j
);
1656 buf
[j
++] = (ev_uint8_t
)label_len
;
1658 memcpy(buf
+ j
, start
, label_len
);
1659 j
+= (int) label_len
;
1662 /* append length of the label. */
1663 const size_t label_len
= name
- start
;
1664 if (label_len
> 63) return -1;
1665 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1666 if (table
) dnslabel_table_add(table
, start
, j
);
1667 buf
[j
++] = (ev_uint8_t
)label_len
;
1669 memcpy(buf
+ j
, start
, label_len
);
1670 j
+= (int) label_len
;
1671 /* hop over the '.' */
1676 /* the labels must be terminated by a 0. */
1677 /* It's possible that the name ended in a . */
1678 /* in which case the zero is already there */
1679 if (!j
|| buf
[j
-1]) buf
[j
++] = 0;
1685 /* Finds the length of a dns request for a DNS name of the given */
1686 /* length. The actual request may be smaller than the value returned */
1689 evdns_request_len(const size_t name_len
) {
1690 return 96 + /* length of the DNS standard header */
1692 4; /* space for the resource type */
1695 /* build a dns request packet into buf. buf should be at least as long */
1696 /* as evdns_request_len told you it should be. */
1698 /* Returns the amount of space used. Negative on error. */
1700 evdns_request_data_build(const char *const name
, const size_t name_len
,
1701 const u16 trans_id
, const u16 type
, const u16
class,
1702 u8
*const buf
, size_t buf_len
) {
1703 off_t j
= 0; /* current offset into buf */
1704 u16 _t
; /* used by the macros */
1707 APPEND16(0x0100); /* standard query, recusion needed */
1708 APPEND16(1); /* one question */
1709 APPEND16(0); /* no answers */
1710 APPEND16(0); /* no authority */
1711 APPEND16(0); /* no additional */
1713 j
= dnsname_to_labels(buf
, buf_len
, j
, name
, name_len
, NULL
);
1726 /* exported function */
1727 struct evdns_server_port
*
1728 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
)
1730 struct evdns_server_port
*port
;
1732 return NULL
; /* flags not yet implemented */
1733 if (!(port
= mm_malloc(sizeof(struct evdns_server_port
))))
1735 memset(port
, 0, sizeof(struct evdns_server_port
));
1738 port
->socket
= socket
;
1742 port
->user_callback
= cb
;
1743 port
->user_data
= user_data
;
1744 port
->pending_replies
= NULL
;
1745 port
->event_base
= base
;
1747 event_assign(&port
->event
, port
->event_base
,
1748 port
->socket
, EV_READ
| EV_PERSIST
,
1749 server_port_ready_callback
, port
);
1750 if (event_add(&port
->event
, NULL
) < 0) {
1754 EVTHREAD_ALLOC_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
1758 struct evdns_server_port
*
1759 evdns_add_server_port(evutil_socket_t socket
, int flags
, evdns_request_callback_fn_type cb
, void *user_data
)
1761 return evdns_add_server_port_with_base(NULL
, socket
, flags
, cb
, user_data
);
1764 /* exported function */
1766 evdns_close_server_port(struct evdns_server_port
*port
)
1769 if (--port
->refcnt
== 0) {
1771 server_port_free(port
);
1777 /* exported function */
1779 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
)
1781 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1782 struct server_reply_item
**itemp
, *item
;
1786 EVDNS_LOCK(req
->port
);
1787 if (req
->response
) /* have we already answered? */
1791 case EVDNS_ANSWER_SECTION
:
1792 itemp
= &req
->answer
;
1793 countp
= &req
->n_answer
;
1795 case EVDNS_AUTHORITY_SECTION
:
1796 itemp
= &req
->authority
;
1797 countp
= &req
->n_authority
;
1799 case EVDNS_ADDITIONAL_SECTION
:
1800 itemp
= &req
->additional
;
1801 countp
= &req
->n_additional
;
1807 itemp
= &((*itemp
)->next
);
1809 item
= mm_malloc(sizeof(struct server_reply_item
));
1813 if (!(item
->name
= mm_strdup(name
))) {
1818 item
->dns_question_class
= class;
1820 item
->is_name
= is_name
!= 0;
1824 if (item
->is_name
) {
1825 if (!(item
->data
= mm_strdup(data
))) {
1826 mm_free(item
->name
);
1830 item
->datalen
= (u16
)-1;
1832 if (!(item
->data
= mm_malloc(datalen
))) {
1833 mm_free(item
->name
);
1837 item
->datalen
= datalen
;
1838 memcpy(item
->data
, data
, datalen
);
1846 EVDNS_UNLOCK(req
->port
);
1850 /* exported function */
1852 evdns_server_request_add_a_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1854 return evdns_server_request_add_reply(
1855 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_A
, CLASS_INET
,
1856 ttl
, n
*4, 0, addrs
);
1859 /* exported function */
1861 evdns_server_request_add_aaaa_reply(struct evdns_server_request
*req
, const char *name
, int n
, const void *addrs
, int ttl
)
1863 return evdns_server_request_add_reply(
1864 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_AAAA
, CLASS_INET
,
1865 ttl
, n
*16, 0, addrs
);
1868 /* exported function */
1870 evdns_server_request_add_ptr_reply(struct evdns_server_request
*req
, struct in_addr
*in
, const char *inaddr_name
, const char *hostname
, int ttl
)
1874 if (in
&& inaddr_name
)
1876 else if (!in
&& !inaddr_name
)
1879 a
= ntohl(in
->s_addr
);
1880 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
1881 (int)(u8
)((a
)&0xff),
1882 (int)(u8
)((a
>>8 )&0xff),
1883 (int)(u8
)((a
>>16)&0xff),
1884 (int)(u8
)((a
>>24)&0xff));
1887 return evdns_server_request_add_reply(
1888 req
, EVDNS_ANSWER_SECTION
, inaddr_name
, TYPE_PTR
, CLASS_INET
,
1889 ttl
, -1, 1, hostname
);
1892 /* exported function */
1894 evdns_server_request_add_cname_reply(struct evdns_server_request
*req
, const char *name
, const char *cname
, int ttl
)
1896 return evdns_server_request_add_reply(
1897 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_CNAME
, CLASS_INET
,
1901 /* exported function */
1903 evdns_server_request_set_flags(struct evdns_server_request
*exreq
, int flags
)
1905 struct server_request
*req
= TO_SERVER_REQUEST(exreq
);
1906 req
->base
.flags
&= ~(EVDNS_FLAGS_AA
|EVDNS_FLAGS_RD
);
1907 req
->base
.flags
|= flags
;
1911 evdns_server_request_format_response(struct server_request
*req
, int err
)
1913 unsigned char buf
[1500];
1914 size_t buf_len
= sizeof(buf
);
1920 struct dnslabel_table table
;
1922 if (err
< 0 || err
> 15) return -1;
1924 /* Set response bit and error code; copy OPCODE and RD fields from
1925 * question; copy RA and AA if set by caller. */
1926 flags
= req
->base
.flags
;
1927 flags
|= (0x8000 | err
);
1929 dnslabel_table_init(&table
);
1930 APPEND16(req
->trans_id
);
1932 APPEND16(req
->base
.nquestions
);
1933 APPEND16(req
->n_answer
);
1934 APPEND16(req
->n_authority
);
1935 APPEND16(req
->n_additional
);
1937 /* Add questions. */
1938 for (i
=0; i
< req
->base
.nquestions
; ++i
) {
1939 const char *s
= req
->base
.questions
[i
]->name
;
1940 j
= dnsname_to_labels(buf
, buf_len
, j
, s
, strlen(s
), &table
);
1942 dnslabel_clear(&table
);
1945 APPEND16(req
->base
.questions
[i
]->type
);
1946 APPEND16(req
->base
.questions
[i
]->dns_question_class
);
1949 /* Add answer, authority, and additional sections. */
1950 for (i
=0; i
<3; ++i
) {
1951 struct server_reply_item
*item
;
1955 item
= req
->authority
;
1957 item
= req
->additional
;
1959 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->name
, strlen(item
->name
), &table
);
1964 APPEND16(item
->type
);
1965 APPEND16(item
->dns_question_class
);
1966 APPEND32(item
->ttl
);
1967 if (item
->is_name
) {
1968 off_t len_idx
= j
, name_start
;
1971 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->data
, strlen(item
->data
), &table
);
1975 _t
= htons( (short) (j
-name_start
) );
1976 memcpy(buf
+len_idx
, &_t
, 2);
1978 APPEND16(item
->datalen
);
1979 if (j
+item
->datalen
> (off_t
)buf_len
)
1981 memcpy(buf
+j
, item
->data
, item
->datalen
);
1991 buf
[2] |= 0x02; /* set the truncated bit. */
1994 req
->response_len
= j
;
1996 if (!(req
->response
= mm_malloc(req
->response_len
))) {
1997 server_request_free_answers(req
);
1998 dnslabel_clear(&table
);
2001 memcpy(req
->response
, buf
, req
->response_len
);
2002 server_request_free_answers(req
);
2003 dnslabel_clear(&table
);
2007 /* exported function */
2009 evdns_server_request_respond(struct evdns_server_request
*_req
, int err
)
2011 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2012 struct evdns_server_port
*port
= req
->port
;
2016 if (!req
->response
) {
2017 if ((r
= evdns_server_request_format_response(req
, err
))<0)
2021 r
= sendto(port
->socket
, req
->response
, (int)req
->response_len
, 0,
2022 (struct sockaddr
*) &req
->addr
, (ev_socklen_t
)req
->addrlen
);
2024 int sock_err
= evutil_socket_geterror(port
->socket
);
2025 if (EVUTIL_ERR_RW_RETRIABLE(sock_err
))
2028 if (port
->pending_replies
) {
2029 req
->prev_pending
= port
->pending_replies
->prev_pending
;
2030 req
->next_pending
= port
->pending_replies
;
2031 req
->prev_pending
->next_pending
=
2032 req
->next_pending
->prev_pending
= req
;
2034 req
->prev_pending
= req
->next_pending
= req
;
2035 port
->pending_replies
= req
;
2038 (void) event_del(&port
->event
);
2039 event_assign(&port
->event
, port
->event_base
, port
->socket
, (port
->closing
?0:EV_READ
) | EV_WRITE
| EV_PERSIST
, server_port_ready_callback
, port
);
2041 if (event_add(&port
->event
, NULL
) < 0) {
2042 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server");
2050 if (server_request_free(req
)) {
2055 if (port
->pending_replies
)
2056 server_port_flush(port
);
2064 /* Free all storage held by RRs in req. */
2066 server_request_free_answers(struct server_request
*req
)
2068 struct server_reply_item
*victim
, *next
, **list
;
2070 for (i
= 0; i
< 3; ++i
) {
2072 list
= &req
->answer
;
2074 list
= &req
->authority
;
2076 list
= &req
->additional
;
2080 next
= victim
->next
;
2081 mm_free(victim
->name
);
2083 mm_free(victim
->data
);
2091 /* Free all storage held by req, and remove links to it. */
2092 /* return true iff we just wound up freeing the server_port. */
2094 server_request_free(struct server_request
*req
)
2096 int i
, rc
=1, lock
=0;
2097 if (req
->base
.questions
) {
2098 for (i
= 0; i
< req
->base
.nquestions
; ++i
)
2099 mm_free(req
->base
.questions
[i
]);
2100 mm_free(req
->base
.questions
);
2104 EVDNS_LOCK(req
->port
);
2106 if (req
->port
->pending_replies
== req
) {
2107 if (req
->next_pending
&& req
->next_pending
!= req
)
2108 req
->port
->pending_replies
= req
->next_pending
;
2110 req
->port
->pending_replies
= NULL
;
2112 rc
= --req
->port
->refcnt
;
2115 if (req
->response
) {
2116 mm_free(req
->response
);
2119 server_request_free_answers(req
);
2121 if (req
->next_pending
&& req
->next_pending
!= req
) {
2122 req
->next_pending
->prev_pending
= req
->prev_pending
;
2123 req
->prev_pending
->next_pending
= req
->next_pending
;
2127 EVDNS_UNLOCK(req
->port
); /* ????? nickm */
2128 server_port_free(req
->port
);
2133 EVDNS_UNLOCK(req
->port
);
2138 /* Free all storage held by an evdns_server_port. Only called when */
2140 server_port_free(struct evdns_server_port
*port
)
2142 EVUTIL_ASSERT(port
);
2143 EVUTIL_ASSERT(!port
->refcnt
);
2144 EVUTIL_ASSERT(!port
->pending_replies
);
2145 if (port
->socket
> 0) {
2146 evutil_closesocket(port
->socket
);
2149 (void) event_del(&port
->event
);
2150 event_debug_unassign(&port
->event
);
2151 EVTHREAD_FREE_LOCK(port
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
2155 /* exported function */
2157 evdns_server_request_drop(struct evdns_server_request
*_req
)
2159 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2160 server_request_free(req
);
2164 /* exported function */
2166 evdns_server_request_get_requesting_addr(struct evdns_server_request
*_req
, struct sockaddr
*sa
, int addr_len
)
2168 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
2169 if (addr_len
< (int)req
->addrlen
)
2171 memcpy(sa
, &(req
->addr
), req
->addrlen
);
2172 return req
->addrlen
;
2178 /* this is a libevent callback function which is called when a request */
2179 /* has timed out. */
2181 evdns_request_timeout_callback(evutil_socket_t fd
, short events
, void *arg
) {
2182 struct request
*const req
= (struct request
*) arg
;
2183 struct evdns_base
*base
= req
->base
;
2188 log(EVDNS_LOG_DEBUG
, "Request %p timed out", arg
);
2191 req
->ns
->timedout
++;
2192 if (req
->ns
->timedout
> req
->base
->global_max_nameserver_timeout
) {
2193 req
->ns
->timedout
= 0;
2194 nameserver_failed(req
->ns
, "request timed out.");
2197 if (req
->tx_count
>= req
->base
->global_max_retransmits
) {
2198 /* this request has failed */
2199 log(EVDNS_LOG_DEBUG
, "Giving up on request %p; tx_count==%d",
2200 arg
, req
->tx_count
);
2201 reply_schedule_callback(req
, 0, DNS_ERR_TIMEOUT
, NULL
);
2202 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 1);
2205 struct nameserver
*new_ns
;
2206 log(EVDNS_LOG_DEBUG
, "Retransmitting request %p; tx_count==%d",
2207 arg
, req
->tx_count
);
2208 (void) evtimer_del(&req
->timeout_event
);
2209 new_ns
= nameserver_pick(base
);
2212 evdns_request_transmit(req
);
2217 /* try to send a request to a given server. */
2221 /* 1 temporary failure */
2222 /* 2 other failure */
2224 evdns_request_transmit_to(struct request
*req
, struct nameserver
*server
) {
2226 ASSERT_LOCKED(req
->base
);
2227 ASSERT_VALID_REQUEST(req
);
2228 r
= sendto(server
->socket
, (void*)req
->request
, req
->request_len
, 0,
2229 (struct sockaddr
*)&server
->address
, server
->addrlen
);
2231 int err
= evutil_socket_geterror(server
->socket
);
2232 if (EVUTIL_ERR_RW_RETRIABLE(err
))
2234 nameserver_failed(req
->ns
, evutil_socket_error_to_string(err
));
2236 } else if (r
!= (int)req
->request_len
) {
2237 return 1; /* short write */
2243 /* try to send a request, updating the fields of the request */
2250 evdns_request_transmit(struct request
*req
) {
2253 ASSERT_LOCKED(req
->base
);
2254 ASSERT_VALID_REQUEST(req
);
2255 /* if we fail to send this packet then this flag marks it */
2256 /* for evdns_transmit */
2257 req
->transmit_me
= 1;
2258 EVUTIL_ASSERT(req
->trans_id
!= 0xffff);
2260 if (req
->ns
->choked
) {
2261 /* don't bother trying to write to a socket */
2262 /* which we have had EAGAIN from */
2266 r
= evdns_request_transmit_to(req
, req
->ns
);
2270 req
->ns
->choked
= 1;
2271 nameserver_write_waiting(req
->ns
, 1);
2274 /* failed to transmit the request entirely. */
2276 /* fall through: we'll set a timeout, which will time out,
2277 * and make us retransmit the request anyway. */
2280 log(EVDNS_LOG_DEBUG
,
2281 "Setting timeout for request %p, sent to nameserver %p", req
, req
->ns
);
2282 if (evtimer_add(&req
->timeout_event
, &req
->base
->global_timeout
) < 0) {
2284 "Error from libevent when adding timer for request %p",
2289 req
->transmit_me
= 0;
2295 nameserver_probe_callback(int result
, char type
, int count
, int ttl
, void *addresses
, void *arg
) {
2296 struct nameserver
*const ns
= (struct nameserver
*) arg
;
2302 if (result
== DNS_ERR_CANCEL
) {
2303 /* We canceled this request because the nameserver came up
2304 * for some other reason. Do not change our opinion about
2305 * the nameserver. */
2309 EVDNS_LOCK(ns
->base
);
2310 ns
->probe_request
= NULL
;
2311 if (result
== DNS_ERR_NONE
|| result
== DNS_ERR_NOTEXIST
) {
2312 /* this is a good reply */
2315 nameserver_probe_failed(ns
);
2317 EVDNS_UNLOCK(ns
->base
);
2321 nameserver_send_probe(struct nameserver
*const ns
) {
2322 struct evdns_request
*handle
;
2323 struct request
*req
;
2325 /* here we need to send a probe to a given nameserver */
2326 /* in the hope that it is up now. */
2328 ASSERT_LOCKED(ns
->base
);
2329 log(EVDNS_LOG_DEBUG
, "Sending probe to %s",
2330 evutil_format_sockaddr_port(
2331 (struct sockaddr
*)&ns
->address
,
2332 addrbuf
, sizeof(addrbuf
)));
2333 handle
= mm_calloc(1, sizeof(*handle
));
2334 if (!handle
) return;
2335 req
= request_new(ns
->base
, handle
, TYPE_A
, "google.com", DNS_QUERY_NO_SEARCH
, nameserver_probe_callback
, ns
);
2337 ns
->probe_request
= handle
;
2338 /* we force this into the inflight queue no matter what */
2339 request_trans_id_set(req
, transaction_id_pick(ns
->base
));
2341 request_submit(req
);
2345 /* 0 didn't try to transmit anything */
2346 /* 1 tried to transmit something */
2348 evdns_transmit(struct evdns_base
*base
) {
2349 char did_try_to_transmit
= 0;
2352 ASSERT_LOCKED(base
);
2353 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2354 if (base
->req_heads
[i
]) {
2355 struct request
*const started_at
= base
->req_heads
[i
], *req
= started_at
;
2356 /* first transmit all the requests which are currently waiting */
2358 if (req
->transmit_me
) {
2359 did_try_to_transmit
= 1;
2360 evdns_request_transmit(req
);
2364 } while (req
!= started_at
);
2368 return did_try_to_transmit
;
2371 /* exported function */
2373 evdns_base_count_nameservers(struct evdns_base
*base
)
2375 const struct nameserver
*server
;
2379 server
= base
->server_head
;
2384 server
= server
->next
;
2385 } while (server
!= base
->server_head
);
2392 evdns_count_nameservers(void)
2394 return evdns_base_count_nameservers(current_base
);
2397 /* exported function */
2399 evdns_base_clear_nameservers_and_suspend(struct evdns_base
*base
)
2401 struct nameserver
*server
, *started_at
;
2405 server
= base
->server_head
;
2406 started_at
= base
->server_head
;
2412 struct nameserver
*next
= server
->next
;
2413 (void) event_del(&server
->event
);
2414 if (evtimer_initialized(&server
->timeout_event
))
2415 (void) evtimer_del(&server
->timeout_event
);
2416 if (server
->probe_request
) {
2417 evdns_cancel_request(server
->base
, server
->probe_request
);
2418 server
->probe_request
= NULL
;
2420 if (server
->socket
>= 0)
2421 evutil_closesocket(server
->socket
);
2423 if (next
== started_at
)
2427 base
->server_head
= NULL
;
2428 base
->global_good_nameservers
= 0;
2430 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
2431 struct request
*req
, *req_started_at
;
2432 req
= req_started_at
= base
->req_heads
[i
];
2434 struct request
*next
= req
->next
;
2435 req
->tx_count
= req
->reissue_count
= 0;
2437 /* ???? What to do about searches? */
2438 (void) evtimer_del(&req
->timeout_event
);
2440 req
->transmit_me
= 0;
2442 base
->global_requests_waiting
++;
2443 evdns_request_insert(req
, &base
->req_waiting_head
);
2444 /* We want to insert these suspended elements at the front of
2445 * the waiting queue, since they were pending before any of
2446 * the waiting entries were added. This is a circular list,
2447 * so we can just shift the start back by one.*/
2448 base
->req_waiting_head
= base
->req_waiting_head
->prev
;
2450 if (next
== req_started_at
)
2454 base
->req_heads
[i
] = NULL
;
2457 base
->global_requests_inflight
= 0;
2464 evdns_clear_nameservers_and_suspend(void)
2466 return evdns_base_clear_nameservers_and_suspend(current_base
);
2470 /* exported function */
2472 evdns_base_resume(struct evdns_base
*base
)
2475 evdns_requests_pump_waiting_queue(base
);
2483 return evdns_base_resume(current_base
);
2487 _evdns_nameserver_add_impl(struct evdns_base
*base
, const struct sockaddr
*address
, int addrlen
) {
2488 /* first check to see if we already have this nameserver */
2490 const struct nameserver
*server
= base
->server_head
, *const started_at
= base
->server_head
;
2491 struct nameserver
*ns
;
2495 ASSERT_LOCKED(base
);
2498 if (!evutil_sockaddr_cmp((struct sockaddr
*)&server
->address
, address
, 1)) return 3;
2499 server
= server
->next
;
2500 } while (server
!= started_at
);
2502 if (addrlen
> (int)sizeof(ns
->address
)) {
2503 log(EVDNS_LOG_DEBUG
, "Addrlen %d too long.", (int)addrlen
);
2507 ns
= (struct nameserver
*) mm_malloc(sizeof(struct nameserver
));
2510 memset(ns
, 0, sizeof(struct nameserver
));
2513 evtimer_assign(&ns
->timeout_event
, ns
->base
->event_base
, nameserver_prod_callback
, ns
);
2515 ns
->socket
= socket(address
->sa_family
, SOCK_DGRAM
, 0);
2516 if (ns
->socket
< 0) { err
= 1; goto out1
; }
2517 evutil_make_socket_closeonexec(ns
->socket
);
2518 evutil_make_socket_nonblocking(ns
->socket
);
2520 if (base
->global_outgoing_addrlen
&&
2521 !evutil_sockaddr_is_loopback(address
)) {
2522 if (bind(ns
->socket
,
2523 (struct sockaddr
*)&base
->global_outgoing_address
,
2524 base
->global_outgoing_addrlen
) < 0) {
2525 log(EVDNS_LOG_WARN
,"Couldn't bind to outgoing address");
2531 memcpy(&ns
->address
, address
, addrlen
);
2532 ns
->addrlen
= addrlen
;
2534 event_assign(&ns
->event
, ns
->base
->event_base
, ns
->socket
, EV_READ
| EV_PERSIST
, nameserver_ready_callback
, ns
);
2535 if (event_add(&ns
->event
, NULL
) < 0) {
2540 log(EVDNS_LOG_DEBUG
, "Added nameserver %s as %p",
2541 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)), ns
);
2543 /* insert this nameserver into the list of them */
2544 if (!base
->server_head
) {
2545 ns
->next
= ns
->prev
= ns
;
2546 base
->server_head
= ns
;
2548 ns
->next
= base
->server_head
->next
;
2549 ns
->prev
= base
->server_head
;
2550 base
->server_head
->next
= ns
;
2551 ns
->next
->prev
= ns
;
2554 base
->global_good_nameservers
++;
2559 evutil_closesocket(ns
->socket
);
2561 event_debug_unassign(&ns
->event
);
2563 log(EVDNS_LOG_WARN
, "Unable to add nameserver %s: error %d",
2564 evutil_format_sockaddr_port(address
, addrbuf
, sizeof(addrbuf
)), err
);
2568 /* exported function */
2570 evdns_base_nameserver_add(struct evdns_base
*base
, unsigned long int address
)
2572 struct sockaddr_in sin
;
2574 sin
.sin_addr
.s_addr
= address
;
2575 sin
.sin_port
= htons(53);
2576 sin
.sin_family
= AF_INET
;
2578 res
= _evdns_nameserver_add_impl(base
, (struct sockaddr
*)&sin
, sizeof(sin
));
2584 evdns_nameserver_add(unsigned long int address
) {
2586 current_base
= evdns_base_new(NULL
, 0);
2587 return evdns_base_nameserver_add(current_base
, address
);
2591 sockaddr_setport(struct sockaddr
*sa
, ev_uint16_t port
)
2593 if (sa
->sa_family
== AF_INET
) {
2594 ((struct sockaddr_in
*)sa
)->sin_port
= htons(port
);
2595 } else if (sa
->sa_family
== AF_INET6
) {
2596 ((struct sockaddr_in6
*)sa
)->sin6_port
= htons(port
);
2601 sockaddr_getport(struct sockaddr
*sa
)
2603 if (sa
->sa_family
== AF_INET
) {
2604 return ntohs(((struct sockaddr_in
*)sa
)->sin_port
);
2605 } else if (sa
->sa_family
== AF_INET6
) {
2606 return ntohs(((struct sockaddr_in6
*)sa
)->sin6_port
);
2612 /* exported function */
2614 evdns_base_nameserver_ip_add(struct evdns_base
*base
, const char *ip_as_string
) {
2615 struct sockaddr_storage ss
;
2616 struct sockaddr
*sa
;
2617 int len
= sizeof(ss
);
2619 if (evutil_parse_sockaddr_port(ip_as_string
, (struct sockaddr
*)&ss
,
2621 log(EVDNS_LOG_WARN
, "Unable to parse nameserver address %s",
2625 sa
= (struct sockaddr
*) &ss
;
2626 if (sockaddr_getport(sa
) == 0)
2627 sockaddr_setport(sa
, 53);
2630 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2636 evdns_nameserver_ip_add(const char *ip_as_string
) {
2638 current_base
= evdns_base_new(NULL
, 0);
2639 return evdns_base_nameserver_ip_add(current_base
, ip_as_string
);
2643 evdns_base_nameserver_sockaddr_add(struct evdns_base
*base
,
2644 const struct sockaddr
*sa
, ev_socklen_t len
, unsigned flags
)
2647 EVUTIL_ASSERT(base
);
2649 res
= _evdns_nameserver_add_impl(base
, sa
, len
);
2654 /* remove from the queue */
2656 evdns_request_remove(struct request
*req
, struct request
**head
)
2658 ASSERT_LOCKED(req
->base
);
2659 ASSERT_VALID_REQUEST(req
);
2663 struct request
*ptr
;
2665 EVUTIL_ASSERT(*head
!= NULL
);
2674 } while (ptr
!= *head
);
2675 EVUTIL_ASSERT(found
);
2677 EVUTIL_ASSERT(req
->next
);
2681 if (req
->next
== req
) {
2682 /* only item in the list */
2685 req
->next
->prev
= req
->prev
;
2686 req
->prev
->next
= req
->next
;
2687 if (*head
== req
) *head
= req
->next
;
2689 req
->next
= req
->prev
= NULL
;
2692 /* insert into the tail of the queue */
2694 evdns_request_insert(struct request
*req
, struct request
**head
) {
2695 ASSERT_LOCKED(req
->base
);
2696 ASSERT_VALID_REQUEST(req
);
2699 req
->next
= req
->prev
= req
;
2703 req
->prev
= (*head
)->prev
;
2704 req
->prev
->next
= req
;
2706 (*head
)->prev
= req
;
2710 string_num_dots(const char *s
) {
2712 while ((s
= strchr(s
, '.'))) {
2719 static struct request
*
2720 request_new(struct evdns_base
*base
, struct evdns_request
*handle
, int type
,
2721 const char *name
, int flags
, evdns_callback_type callback
,
2724 const char issuing_now
=
2725 (base
->global_requests_inflight
< base
->global_max_requests_inflight
) ? 1 : 0;
2727 const size_t name_len
= strlen(name
);
2728 const size_t request_max_len
= evdns_request_len(name_len
);
2729 const u16 trans_id
= issuing_now
? transaction_id_pick(base
) : 0xffff;
2730 /* the request data is alloced in a single block with the header */
2731 struct request
*const req
=
2732 mm_malloc(sizeof(struct request
) + request_max_len
);
2737 ASSERT_LOCKED(base
);
2739 if (!req
) return NULL
;
2741 if (name_len
>= sizeof(namebuf
)) {
2746 memset(req
, 0, sizeof(struct request
));
2749 evtimer_assign(&req
->timeout_event
, req
->base
->event_base
, evdns_request_timeout_callback
, req
);
2751 if (base
->global_randomize_case
) {
2753 char randbits
[(sizeof(namebuf
)+7)/8];
2754 strlcpy(namebuf
, name
, sizeof(namebuf
));
2755 rand_bytes_function(randbits
, (name_len
+7)/8);
2756 for (i
= 0; i
< name_len
; ++i
) {
2757 if (EVUTIL_ISALPHA(namebuf
[i
])) {
2758 if ((randbits
[i
>> 3] & (1<<(i
& 7))))
2761 namebuf
[i
] &= ~0x20;
2767 /* request data lives just after the header */
2768 req
->request
= ((u8
*) req
) + sizeof(struct request
);
2769 /* denotes that the request data shouldn't be free()ed */
2770 req
->request_appended
= 1;
2771 rlen
= evdns_request_data_build(name
, name_len
, trans_id
,
2772 type
, CLASS_INET
, req
->request
, request_max_len
);
2776 req
->request_len
= rlen
;
2777 req
->trans_id
= trans_id
;
2779 req
->request_type
= type
;
2780 req
->user_pointer
= user_ptr
;
2781 req
->user_callback
= callback
;
2782 req
->ns
= issuing_now
? nameserver_pick(base
) : NULL
;
2783 req
->next
= req
->prev
= NULL
;
2784 req
->handle
= handle
;
2786 handle
->current_req
= req
;
2787 handle
->base
= base
;
2797 request_submit(struct request
*const req
) {
2798 struct evdns_base
*base
= req
->base
;
2799 ASSERT_LOCKED(base
);
2800 ASSERT_VALID_REQUEST(req
);
2802 /* if it has a nameserver assigned then this is going */
2803 /* straight into the inflight queue */
2804 evdns_request_insert(req
, &REQ_HEAD(base
, req
->trans_id
));
2805 base
->global_requests_inflight
++;
2806 evdns_request_transmit(req
);
2808 evdns_request_insert(req
, &base
->req_waiting_head
);
2809 base
->global_requests_waiting
++;
2813 /* exported function */
2815 evdns_cancel_request(struct evdns_base
*base
, struct evdns_request
*handle
)
2817 struct request
*req
;
2819 if (!handle
->current_req
)
2823 /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
2824 base
= handle
->base
;
2826 base
= handle
->current_req
->base
;
2830 if (handle
->pending_cb
) {
2835 req
= handle
->current_req
;
2836 ASSERT_VALID_REQUEST(req
);
2838 reply_schedule_callback(req
, 0, DNS_ERR_CANCEL
, NULL
);
2840 /* remove from inflight queue */
2841 request_finished(req
, &REQ_HEAD(base
, req
->trans_id
), 1);
2843 /* remove from global_waiting head */
2844 request_finished(req
, &base
->req_waiting_head
, 1);
2849 /* exported function */
2850 struct evdns_request
*
2851 evdns_base_resolve_ipv4(struct evdns_base
*base
, const char *name
, int flags
,
2852 evdns_callback_type callback
, void *ptr
) {
2853 struct evdns_request
*handle
;
2854 struct request
*req
;
2855 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2856 handle
= mm_calloc(1, sizeof(*handle
));
2860 if (flags
& DNS_QUERY_NO_SEARCH
) {
2862 request_new(base
, handle
, TYPE_A
, name
, flags
,
2865 request_submit(req
);
2867 search_request_new(base
, handle
, TYPE_A
, name
, flags
,
2870 if (handle
->current_req
== NULL
) {
2878 int evdns_resolve_ipv4(const char *name
, int flags
,
2879 evdns_callback_type callback
, void *ptr
)
2881 return evdns_base_resolve_ipv4(current_base
, name
, flags
, callback
, ptr
)
2886 /* exported function */
2887 struct evdns_request
*
2888 evdns_base_resolve_ipv6(struct evdns_base
*base
,
2889 const char *name
, int flags
,
2890 evdns_callback_type callback
, void *ptr
)
2892 struct evdns_request
*handle
;
2893 struct request
*req
;
2894 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2895 handle
= mm_calloc(1, sizeof(*handle
));
2899 if (flags
& DNS_QUERY_NO_SEARCH
) {
2900 req
= request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2903 request_submit(req
);
2905 search_request_new(base
, handle
, TYPE_AAAA
, name
, flags
,
2908 if (handle
->current_req
== NULL
) {
2916 int evdns_resolve_ipv6(const char *name
, int flags
,
2917 evdns_callback_type callback
, void *ptr
) {
2918 return evdns_base_resolve_ipv6(current_base
, name
, flags
, callback
, ptr
)
2922 struct evdns_request
*
2923 evdns_base_resolve_reverse(struct evdns_base
*base
, const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2925 struct evdns_request
*handle
;
2926 struct request
*req
;
2929 a
= ntohl(in
->s_addr
);
2930 evutil_snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
2931 (int)(u8
)((a
)&0xff),
2932 (int)(u8
)((a
>>8 )&0xff),
2933 (int)(u8
)((a
>>16)&0xff),
2934 (int)(u8
)((a
>>24)&0xff));
2935 handle
= mm_calloc(1, sizeof(*handle
));
2938 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2940 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2942 request_submit(req
);
2943 if (handle
->current_req
== NULL
) {
2951 int evdns_resolve_reverse(const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2952 return evdns_base_resolve_reverse(current_base
, in
, flags
, callback
, ptr
)
2956 struct evdns_request
*
2957 evdns_base_resolve_reverse_ipv6(struct evdns_base
*base
, const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2958 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2961 struct evdns_request
*handle
;
2962 struct request
*req
;
2966 for (i
=15; i
>= 0; --i
) {
2967 u8 byte
= in
->s6_addr
[i
];
2968 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
2970 *cp
++ = "0123456789abcdef"[byte
>> 4];
2973 EVUTIL_ASSERT(cp
+ strlen("ip6.arpa") < buf
+sizeof(buf
));
2974 memcpy(cp
, "ip6.arpa", strlen("ip6.arpa")+1);
2975 handle
= mm_calloc(1, sizeof(*handle
));
2978 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2980 req
= request_new(base
, handle
, TYPE_PTR
, buf
, flags
, callback
, ptr
);
2982 request_submit(req
);
2983 if (handle
->current_req
== NULL
) {
2991 int evdns_resolve_reverse_ipv6(const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2992 return evdns_base_resolve_reverse_ipv6(current_base
, in
, flags
, callback
, ptr
)
2996 /* exported function */
2997 struct evdns_request
*
2998 evdns_base_resolve_txt(struct evdns_base
*base
, const char *name
, int flags
,
2999 evdns_callback_type callback
, void *ptr
) {
3000 struct evdns_request
*handle
;
3001 struct request
*req
;
3002 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (txt)", name
);
3003 handle
= mm_calloc(1, sizeof(*handle
));
3007 if (flags
& DNS_QUERY_NO_SEARCH
) {
3009 request_new(base
, handle
, TYPE_TXT
, name
, flags
,
3012 request_submit(req
);
3014 search_request_new(base
, handle
, TYPE_TXT
, name
, flags
,
3017 if (handle
->current_req
== NULL
) {
3025 /* ================================================================= */
3026 /* Search support */
3028 /* the libc resolver has support for searching a number of domains */
3029 /* to find a name. If nothing else then it takes the single domain */
3030 /* from the gethostname() call. */
3032 /* It can also be configured via the domain and search options in a */
3035 /* The ndots option controls how many dots it takes for the resolver */
3036 /* to decide that a name is non-local and so try a raw lookup first. */
3038 struct search_domain
{
3040 struct search_domain
*next
;
3041 /* the text string is appended to this structure */
3044 struct search_state
{
3048 struct search_domain
*head
;
3052 search_state_decref(struct search_state
*const state
) {
3055 if (!state
->refcount
) {
3056 struct search_domain
*next
, *dom
;
3057 for (dom
= state
->head
; dom
; dom
= next
) {
3065 static struct search_state
*
3066 search_state_new(void) {
3067 struct search_state
*state
= (struct search_state
*) mm_malloc(sizeof(struct search_state
));
3068 if (!state
) return NULL
;
3069 memset(state
, 0, sizeof(struct search_state
));
3070 state
->refcount
= 1;
3077 search_postfix_clear(struct evdns_base
*base
) {
3078 search_state_decref(base
->global_search_state
);
3080 base
->global_search_state
= search_state_new();
3083 /* exported function */
3085 evdns_base_search_clear(struct evdns_base
*base
)
3088 search_postfix_clear(base
);
3093 evdns_search_clear(void) {
3094 evdns_base_search_clear(current_base
);
3098 search_postfix_add(struct evdns_base
*base
, const char *domain
) {
3100 struct search_domain
*sdomain
;
3101 while (domain
[0] == '.') domain
++;
3102 domain_len
= strlen(domain
);
3104 ASSERT_LOCKED(base
);
3105 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3106 if (!base
->global_search_state
) return;
3107 base
->global_search_state
->num_domains
++;
3109 sdomain
= (struct search_domain
*) mm_malloc(sizeof(struct search_domain
) + domain_len
);
3110 if (!sdomain
) return;
3111 memcpy( ((u8
*) sdomain
) + sizeof(struct search_domain
), domain
, domain_len
);
3112 sdomain
->next
= base
->global_search_state
->head
;
3113 sdomain
->len
= (int) domain_len
;
3115 base
->global_search_state
->head
= sdomain
;
3118 /* reverse the order of members in the postfix list. This is needed because, */
3119 /* when parsing resolv.conf we push elements in the wrong order */
3121 search_reverse(struct evdns_base
*base
) {
3122 struct search_domain
*cur
, *prev
= NULL
, *next
;
3123 ASSERT_LOCKED(base
);
3124 cur
= base
->global_search_state
->head
;
3132 base
->global_search_state
->head
= prev
;
3135 /* exported function */
3137 evdns_base_search_add(struct evdns_base
*base
, const char *domain
) {
3139 search_postfix_add(base
, domain
);
3143 evdns_search_add(const char *domain
) {
3144 evdns_base_search_add(current_base
, domain
);
3147 /* exported function */
3149 evdns_base_search_ndots_set(struct evdns_base
*base
, const int ndots
) {
3151 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3152 if (base
->global_search_state
)
3153 base
->global_search_state
->ndots
= ndots
;
3157 evdns_search_ndots_set(const int ndots
) {
3158 evdns_base_search_ndots_set(current_base
, ndots
);
3162 search_set_from_hostname(struct evdns_base
*base
) {
3163 char hostname
[HOST_NAME_MAX
+ 1], *domainname
;
3165 ASSERT_LOCKED(base
);
3166 search_postfix_clear(base
);
3167 if (gethostname(hostname
, sizeof(hostname
))) return;
3168 domainname
= strchr(hostname
, '.');
3169 if (!domainname
) return;
3170 search_postfix_add(base
, domainname
);
3173 /* warning: returns malloced string */
3175 search_make_new(const struct search_state
*const state
, int n
, const char *const base_name
) {
3176 const size_t base_len
= strlen(base_name
);
3177 const char need_to_append_dot
= base_name
[base_len
- 1] == '.' ? 0 : 1;
3178 struct search_domain
*dom
;
3180 for (dom
= state
->head
; dom
; dom
= dom
->next
) {
3182 /* this is the postfix we want */
3183 /* the actual postfix string is kept at the end of the structure */
3184 const u8
*const postfix
= ((u8
*) dom
) + sizeof(struct search_domain
);
3185 const int postfix_len
= dom
->len
;
3186 char *const newname
= (char *) mm_malloc(base_len
+ need_to_append_dot
+ postfix_len
+ 1);
3187 if (!newname
) return NULL
;
3188 memcpy(newname
, base_name
, base_len
);
3189 if (need_to_append_dot
) newname
[base_len
] = '.';
3190 memcpy(newname
+ base_len
+ need_to_append_dot
, postfix
, postfix_len
);
3191 newname
[base_len
+ need_to_append_dot
+ postfix_len
] = 0;
3196 /* we ran off the end of the list and still didn't find the requested string */
3198 return NULL
; /* unreachable; stops warnings in some compilers. */
3201 static struct request
*
3202 search_request_new(struct evdns_base
*base
, struct evdns_request
*handle
,
3203 int type
, const char *const name
, int flags
,
3204 evdns_callback_type user_callback
, void *user_arg
) {
3205 ASSERT_LOCKED(base
);
3206 EVUTIL_ASSERT(type
== TYPE_A
|| type
== TYPE_AAAA
);
3207 EVUTIL_ASSERT(handle
->current_req
== NULL
);
3208 if ( ((flags
& DNS_QUERY_NO_SEARCH
) == 0) &&
3209 base
->global_search_state
&&
3210 base
->global_search_state
->num_domains
) {
3211 /* we have some domains to search */
3212 struct request
*req
;
3213 if (string_num_dots(name
) >= base
->global_search_state
->ndots
) {
3214 req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3215 if (!req
) return NULL
;
3216 handle
->search_index
= -1;
3218 char *const new_name
= search_make_new(base
->global_search_state
, 0, name
);
3219 if (!new_name
) return NULL
;
3220 req
= request_new(base
, handle
, type
, new_name
, flags
, user_callback
, user_arg
);
3222 if (!req
) return NULL
;
3223 handle
->search_index
= 0;
3225 EVUTIL_ASSERT(handle
->search_origname
== NULL
);
3226 handle
->search_origname
= mm_strdup(name
);
3227 if (handle
->search_origname
== NULL
) {
3228 /* XXX Should we dealloc req? If yes, how? */
3231 handle
->search_state
= base
->global_search_state
;
3232 handle
->search_flags
= flags
;
3233 base
->global_search_state
->refcount
++;
3234 request_submit(req
);
3237 struct request
*const req
= request_new(base
, handle
, type
, name
, flags
, user_callback
, user_arg
);
3238 if (!req
) return NULL
;
3239 request_submit(req
);
3244 /* this is called when a request has failed to find a name. We need to check */
3245 /* if it is part of a search and, if so, try the next name in the list */
3247 /* 0 another request has been submitted */
3248 /* 1 no more requests needed */
3250 search_try_next(struct evdns_request
*const handle
) {
3251 struct request
*req
= handle
->current_req
;
3252 struct evdns_base
*base
= req
->base
;
3253 struct request
*newreq
;
3254 ASSERT_LOCKED(base
);
3255 if (handle
->search_state
) {
3256 /* it is part of a search */
3258 handle
->search_index
++;
3259 if (handle
->search_index
>= handle
->search_state
->num_domains
) {
3260 /* no more postfixes to try, however we may need to try */
3261 /* this name without a postfix */
3262 if (string_num_dots(handle
->search_origname
) < handle
->search_state
->ndots
) {
3263 /* yep, we need to try it raw */
3264 newreq
= request_new(base
, NULL
, req
->request_type
, handle
->search_origname
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3265 log(EVDNS_LOG_DEBUG
, "Search: trying raw query %s", handle
->search_origname
);
3267 search_request_finished(handle
);
3274 new_name
= search_make_new(handle
->search_state
, handle
->search_index
, handle
->search_origname
);
3275 if (!new_name
) return 1;
3276 log(EVDNS_LOG_DEBUG
, "Search: now trying %s (%d)", new_name
, handle
->search_index
);
3277 newreq
= request_new(base
, NULL
, req
->request_type
, new_name
, handle
->search_flags
, req
->user_callback
, req
->user_pointer
);
3279 if (!newreq
) return 1;
3285 request_finished(req
, &REQ_HEAD(req
->base
, req
->trans_id
), 0);
3286 handle
->current_req
= newreq
;
3287 newreq
->handle
= handle
;
3288 request_submit(newreq
);
3293 search_request_finished(struct evdns_request
*const handle
) {
3294 ASSERT_LOCKED(handle
->current_req
->base
);
3295 if (handle
->search_state
) {
3296 search_state_decref(handle
->search_state
);
3297 handle
->search_state
= NULL
;
3299 if (handle
->search_origname
) {
3300 mm_free(handle
->search_origname
);
3301 handle
->search_origname
= NULL
;
3305 /* ================================================================= */
3306 /* Parsing resolv.conf files */
3309 evdns_resolv_set_defaults(struct evdns_base
*base
, int flags
) {
3310 /* if the file isn't found then we assume a local resolver */
3311 ASSERT_LOCKED(base
);
3312 if (flags
& DNS_OPTION_SEARCH
) search_set_from_hostname(base
);
3313 if (flags
& DNS_OPTION_NAMESERVERS
) evdns_base_nameserver_ip_add(base
,"127.0.0.1");
3316 #ifndef _EVENT_HAVE_STRTOK_R
3318 strtok_r(char *s
, const char *delim
, char **state
) {
3320 start
= cp
= s
? s
: *state
;
3323 while (*cp
&& !strchr(delim
, *cp
))
3338 /* helper version of atoi which returns -1 on error */
3340 strtoint(const char *const str
)
3343 const int r
= strtol(str
, &endptr
, 10);
3344 if (*endptr
) return -1;
3348 /* Parse a number of seconds into a timeval; return -1 on error. */
3350 strtotimeval(const char *const str
, struct timeval
*out
)
3354 d
= strtod(str
, &endptr
);
3355 if (*endptr
) return -1;
3356 if (d
< 0) return -1;
3357 out
->tv_sec
= (int) d
;
3358 out
->tv_usec
= (int) ((d
- (int) d
)*1000000);
3359 if (out
->tv_sec
== 0 && out
->tv_usec
< 1000) /* less than 1 msec */
3364 /* helper version of atoi that returns -1 on error and clips to bounds. */
3366 strtoint_clipped(const char *const str
, int min
, int max
)
3368 int r
= strtoint(str
);
3380 evdns_base_set_max_requests_inflight(struct evdns_base
*base
, int maxinflight
)
3382 int old_n_heads
= base
->n_req_heads
, n_heads
;
3383 struct request
**old_heads
= base
->req_heads
, **new_heads
, *req
;
3386 ASSERT_LOCKED(base
);
3387 if (maxinflight
< 1)
3389 n_heads
= (maxinflight
+4) / 5;
3390 EVUTIL_ASSERT(n_heads
> 0);
3391 new_heads
= mm_calloc(n_heads
, sizeof(struct request
*));
3395 for (i
= 0; i
< old_n_heads
; ++i
) {
3396 while (old_heads
[i
]) {
3398 evdns_request_remove(req
, &old_heads
[i
]);
3399 evdns_request_insert(req
, &new_heads
[req
->trans_id
% n_heads
]);
3404 base
->req_heads
= new_heads
;
3405 base
->n_req_heads
= n_heads
;
3406 base
->global_max_requests_inflight
= maxinflight
;
3410 /* exported function */
3412 evdns_base_set_option(struct evdns_base
*base
,
3413 const char *option
, const char *val
)
3417 res
= evdns_base_set_option_impl(base
, option
, val
, DNS_OPTIONS_ALL
);
3423 str_matches_option(const char *s1
, const char *optionname
)
3425 /* Option names are given as "option:" We accept either 'option' in
3426 * s1, or 'option:randomjunk'. The latter form is to implement the
3427 * resolv.conf parser. */
3428 size_t optlen
= strlen(optionname
);
3429 size_t slen
= strlen(s1
);
3430 if (slen
== optlen
|| slen
== optlen
- 1)
3431 return !strncmp(s1
, optionname
, slen
);
3432 else if (slen
> optlen
)
3433 return !strncmp(s1
, optionname
, optlen
);
3439 evdns_base_set_option_impl(struct evdns_base
*base
,
3440 const char *option
, const char *val
, int flags
)
3442 ASSERT_LOCKED(base
);
3443 if (str_matches_option(option
, "ndots:")) {
3444 const int ndots
= strtoint(val
);
3445 if (ndots
== -1) return -1;
3446 if (!(flags
& DNS_OPTION_SEARCH
)) return 0;
3447 log(EVDNS_LOG_DEBUG
, "Setting ndots to %d", ndots
);
3448 if (!base
->global_search_state
) base
->global_search_state
= search_state_new();
3449 if (!base
->global_search_state
) return -1;
3450 base
->global_search_state
->ndots
= ndots
;
3451 } else if (str_matches_option(option
, "timeout:")) {
3453 if (strtotimeval(val
, &tv
) == -1) return -1;
3454 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3455 log(EVDNS_LOG_DEBUG
, "Setting timeout to %s", val
);
3456 memcpy(&base
->global_timeout
, &tv
, sizeof(struct timeval
));
3457 } else if (str_matches_option(option
, "getaddrinfo-allow-skew:")) {
3459 if (strtotimeval(val
, &tv
) == -1) return -1;
3460 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3461 log(EVDNS_LOG_DEBUG
, "Setting getaddrinfo-allow-skew to %s",
3463 memcpy(&base
->global_getaddrinfo_allow_skew
, &tv
,
3464 sizeof(struct timeval
));
3465 } else if (str_matches_option(option
, "max-timeouts:")) {
3466 const int maxtimeout
= strtoint_clipped(val
, 1, 255);
3467 if (maxtimeout
== -1) return -1;
3468 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3469 log(EVDNS_LOG_DEBUG
, "Setting maximum allowed timeouts to %d",
3471 base
->global_max_nameserver_timeout
= maxtimeout
;
3472 } else if (str_matches_option(option
, "max-inflight:")) {
3473 const int maxinflight
= strtoint_clipped(val
, 1, 65000);
3474 if (maxinflight
== -1) return -1;
3475 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3476 log(EVDNS_LOG_DEBUG
, "Setting maximum inflight requests to %d",
3478 evdns_base_set_max_requests_inflight(base
, maxinflight
);
3479 } else if (str_matches_option(option
, "attempts:")) {
3480 int retries
= strtoint(val
);
3481 if (retries
== -1) return -1;
3482 if (retries
> 255) retries
= 255;
3483 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3484 log(EVDNS_LOG_DEBUG
, "Setting retries to %d", retries
);
3485 base
->global_max_retransmits
= retries
;
3486 } else if (str_matches_option(option
, "randomize-case:")) {
3487 int randcase
= strtoint(val
);
3488 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3489 base
->global_randomize_case
= randcase
;
3490 } else if (str_matches_option(option
, "bind-to:")) {
3491 /* XXX This only applies to successive nameservers, not
3492 * to already-configured ones. We might want to fix that. */
3493 int len
= sizeof(base
->global_outgoing_address
);
3494 if (!(flags
& DNS_OPTION_NAMESERVERS
)) return 0;
3495 if (evutil_parse_sockaddr_port(val
,
3496 (struct sockaddr
*)&base
->global_outgoing_address
, &len
))
3498 base
->global_outgoing_addrlen
= len
;
3499 } else if (str_matches_option(option
, "initial-probe-timeout:")) {
3501 if (strtotimeval(val
, &tv
) == -1) return -1;
3502 if (tv
.tv_sec
> 3600)
3504 if (!(flags
& DNS_OPTION_MISC
)) return 0;
3505 log(EVDNS_LOG_DEBUG
, "Setting initial probe timeout to %s",
3507 memcpy(&base
->global_nameserver_probe_initial_timeout
, &tv
,
3514 evdns_set_option(const char *option
, const char *val
, int flags
)
3517 current_base
= evdns_base_new(NULL
, 0);
3518 return evdns_base_set_option(current_base
, option
, val
);
3522 resolv_conf_parse_line(struct evdns_base
*base
, char *const start
, int flags
) {
3524 static const char *const delims
= " \t";
3525 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3528 char *const first_token
= strtok_r(start
, delims
, &strtok_state
);
3529 ASSERT_LOCKED(base
);
3530 if (!first_token
) return;
3532 if (!strcmp(first_token
, "nameserver") && (flags
& DNS_OPTION_NAMESERVERS
)) {
3533 const char *const nameserver
= NEXT_TOKEN
;
3536 evdns_base_nameserver_ip_add(base
, nameserver
);
3537 } else if (!strcmp(first_token
, "domain") && (flags
& DNS_OPTION_SEARCH
)) {
3538 const char *const domain
= NEXT_TOKEN
;
3540 search_postfix_clear(base
);
3541 search_postfix_add(base
, domain
);
3543 } else if (!strcmp(first_token
, "search") && (flags
& DNS_OPTION_SEARCH
)) {
3545 search_postfix_clear(base
);
3547 while ((domain
= NEXT_TOKEN
)) {
3548 search_postfix_add(base
, domain
);
3550 search_reverse(base
);
3551 } else if (!strcmp(first_token
, "options")) {
3553 while ((option
= NEXT_TOKEN
)) {
3554 const char *val
= strchr(option
, ':');
3555 evdns_base_set_option_impl(base
, option
, val
? val
+1 : "", flags
);
3561 /* exported function */
3564 /* 1 failed to open file */
3565 /* 2 failed to stat file */
3566 /* 3 file too large */
3567 /* 4 out of memory */
3568 /* 5 short read from file */
3570 evdns_base_resolv_conf_parse(struct evdns_base
*base
, int flags
, const char *const filename
) {
3573 res
= evdns_base_resolv_conf_parse_impl(base
, flags
, filename
);
3579 evdns_get_default_hosts_filename(void)
3582 /* Windows is a little coy about where it puts its configuration
3583 * files. Sure, they're _usually_ in C:\windows\system32, but
3584 * there's no reason in principle they couldn't be in
3585 * W:\hoboken chicken emergency\
3587 char path
[MAX_PATH
+1];
3588 static const char hostfile
[] = "\\drivers\\etc\\hosts";
3592 if (! SHGetSpecialFolderPathA(NULL
, path
, CSIDL_SYSTEM
, 0))
3594 len_out
= strlen(path
)+strlen(hostfile
);
3595 path_out
= mm_malloc(len_out
+1);
3596 evutil_snprintf(path_out
, len_out
, "%s%s", path
, hostfile
);
3599 return mm_strdup("/etc/hosts");
3604 evdns_base_resolv_conf_parse_impl(struct evdns_base
*base
, int flags
, const char *const filename
) {
3610 log(EVDNS_LOG_DEBUG
, "Parsing resolv.conf file %s", filename
);
3612 if (flags
& DNS_OPTION_HOSTSFILE
) {
3613 char *fname
= evdns_get_default_hosts_filename();
3614 evdns_base_load_hosts(base
, fname
);
3619 if ((err
= evutil_read_file(filename
, &resolv
, &n
, 0)) < 0) {
3622 evdns_resolv_set_defaults(base
, flags
);
3631 char *const newline
= strchr(start
, '\n');
3633 resolv_conf_parse_line(base
, start
, flags
);
3637 resolv_conf_parse_line(base
, start
, flags
);
3638 start
= newline
+ 1;
3642 if (!base
->server_head
&& (flags
& DNS_OPTION_NAMESERVERS
)) {
3643 /* no nameservers were configured. */
3644 evdns_base_nameserver_ip_add(base
, "127.0.0.1");
3647 if (flags
& DNS_OPTION_SEARCH
&& (!base
->global_search_state
|| base
->global_search_state
->num_domains
== 0)) {
3648 search_set_from_hostname(base
);
3656 evdns_resolv_conf_parse(int flags
, const char *const filename
) {
3658 current_base
= evdns_base_new(NULL
, 0);
3659 return evdns_base_resolv_conf_parse(current_base
, flags
, filename
);
3664 /* Add multiple nameservers from a space-or-comma-separated list. */
3666 evdns_nameserver_ip_add_line(struct evdns_base
*base
, const char *ips
) {
3670 ASSERT_LOCKED(base
);
3672 while (isspace(*ips
) || *ips
== ',' || *ips
== '\t')
3675 while (isdigit(*ips
) || *ips
== '.' || *ips
== ':' ||
3676 *ips
=='[' || *ips
==']')
3678 buf
= mm_malloc(ips
-addr
+1);
3680 memcpy(buf
, addr
, ips
-addr
);
3681 buf
[ips
-addr
] = '\0';
3682 r
= evdns_base_nameserver_ip_add(base
, buf
);
3689 typedef DWORD(WINAPI
*GetNetworkParams_fn_t
)(FIXED_INFO
*, DWORD
*);
3691 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3692 /* figure out what our nameservers are. */
3694 load_nameservers_with_getnetworkparams(struct evdns_base
*base
)
3696 /* Based on MSDN examples and inspection of c-ares code. */
3699 ULONG size
= sizeof(FIXED_INFO
);
3701 int status
= 0, r
, added_any
;
3703 GetNetworkParams_fn_t fn
;
3705 ASSERT_LOCKED(base
);
3706 if (!(handle
= evutil_load_windows_system_library(
3707 TEXT("iphlpapi.dll")))) {
3708 log(EVDNS_LOG_WARN
, "Could not open iphlpapi.dll");
3712 if (!(fn
= (GetNetworkParams_fn_t
) GetProcAddress(handle
, "GetNetworkParams"))) {
3713 log(EVDNS_LOG_WARN
, "Could not get address of function.");
3718 buf
= mm_malloc(size
);
3719 if (!buf
) { status
= 4; goto done
; }
3721 r
= fn(fixed
, &size
);
3722 if (r
!= ERROR_SUCCESS
&& r
!= ERROR_BUFFER_OVERFLOW
) {
3726 if (r
!= ERROR_SUCCESS
) {
3728 buf
= mm_malloc(size
);
3729 if (!buf
) { status
= 4; goto done
; }
3731 r
= fn(fixed
, &size
);
3732 if (r
!= ERROR_SUCCESS
) {
3733 log(EVDNS_LOG_DEBUG
, "fn() failed.");
3739 EVUTIL_ASSERT(fixed
);
3741 ns
= &(fixed
->DnsServerList
);
3743 r
= evdns_nameserver_ip_add_line(base
, ns
->IpAddress
.String
);
3745 log(EVDNS_LOG_DEBUG
,"Could not add nameserver %s to list,error: %d",
3746 (ns
->IpAddress
.String
),(int)GetLastError());
3750 log(EVDNS_LOG_DEBUG
,"Successfully added %s as nameserver",ns
->IpAddress
.String
);
3757 log(EVDNS_LOG_DEBUG
, "No nameservers added.");
3768 FreeLibrary(handle
);
3773 config_nameserver_from_reg_key(struct evdns_base
*base
, HKEY key
, const TCHAR
*subkey
)
3776 DWORD bufsz
= 0, type
= 0;
3779 ASSERT_LOCKED(base
);
3780 if (RegQueryValueEx(key
, subkey
, 0, &type
, NULL
, &bufsz
)
3783 if (!(buf
= mm_malloc(bufsz
)))
3786 if (RegQueryValueEx(key
, subkey
, 0, &type
, (LPBYTE
)buf
, &bufsz
)
3787 == ERROR_SUCCESS
&& bufsz
> 1) {
3788 status
= evdns_nameserver_ip_add_line(base
,buf
);
3795 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3796 #define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
3797 #define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
3800 load_nameservers_from_registry(struct evdns_base
*base
)
3804 #define TRY(k, name) \
3805 if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3806 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3808 } else if (!found) { \
3809 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3813 ASSERT_LOCKED(base
);
3815 if (((int)GetVersion()) > 0) { /* NT */
3816 HKEY nt_key
= 0, interfaces_key
= 0;
3818 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_NT_KEY
, 0,
3819 KEY_READ
, &nt_key
) != ERROR_SUCCESS
) {
3820 log(EVDNS_LOG_DEBUG
,"Couldn't open nt key, %d",(int)GetLastError());
3823 r
= RegOpenKeyEx(nt_key
, TEXT("Interfaces"), 0,
3824 KEY_QUERY_VALUE
|KEY_ENUMERATE_SUB_KEYS
,
3826 if (r
!= ERROR_SUCCESS
) {
3827 log(EVDNS_LOG_DEBUG
,"Couldn't open interfaces key, %d",(int)GetLastError());
3830 TRY(nt_key
, "NameServer");
3831 TRY(nt_key
, "DhcpNameServer");
3832 TRY(interfaces_key
, "NameServer");
3833 TRY(interfaces_key
, "DhcpNameServer");
3834 RegCloseKey(interfaces_key
);
3835 RegCloseKey(nt_key
);
3838 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_9X_KEY
, 0,
3839 KEY_READ
, &win_key
) != ERROR_SUCCESS
) {
3840 log(EVDNS_LOG_DEBUG
, "Couldn't open registry key, %d", (int)GetLastError());
3843 TRY(win_key
, "NameServer");
3844 RegCloseKey(win_key
);
3848 log(EVDNS_LOG_WARN
,"Didn't find any nameservers.");
3851 return found
? 0 : -1;
3856 evdns_base_config_windows_nameservers(struct evdns_base
*base
)
3861 base
= current_base
;
3865 if (load_nameservers_with_getnetworkparams(base
) == 0) {
3869 r
= load_nameservers_from_registry(base
);
3871 fname
= evdns_get_default_hosts_filename();
3872 evdns_base_load_hosts(base
, fname
);
3881 evdns_config_windows_nameservers(void)
3883 if (!current_base
) {
3884 current_base
= evdns_base_new(NULL
, 1);
3885 return current_base
== NULL
? -1 : 0;
3887 return evdns_base_config_windows_nameservers(current_base
);
3893 evdns_base_new(struct event_base
*event_base
, int initialize_nameservers
)
3895 struct evdns_base
*base
;
3897 if (rand_init_function
!= NULL
&& rand_init_function() < 0) {
3898 log(EVDNS_LOG_WARN
, "Unable to seed random number generator; "
3903 /* Give the evutil library a hook into its evdns-enabled
3904 * functionality. We can't just call evdns_getaddrinfo directly or
3905 * else libevent-core will depend on libevent-extras. */
3906 evutil_set_evdns_getaddrinfo_fn(evdns_getaddrinfo
);
3908 base
= mm_malloc(sizeof(struct evdns_base
));
3911 memset(base
, 0, sizeof(struct evdns_base
));
3912 base
->req_waiting_head
= NULL
;
3914 EVTHREAD_ALLOC_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
3917 /* Set max requests inflight and allocate req_heads. */
3918 base
->req_heads
= NULL
;
3920 evdns_base_set_max_requests_inflight(base
, 64);
3922 base
->server_head
= NULL
;
3923 base
->event_base
= event_base
;
3924 base
->global_good_nameservers
= base
->global_requests_inflight
=
3925 base
->global_requests_waiting
= 0;
3927 base
->global_timeout
.tv_sec
= 5;
3928 base
->global_timeout
.tv_usec
= 0;
3929 base
->global_max_reissues
= 1;
3930 base
->global_max_retransmits
= 3;
3931 base
->global_max_nameserver_timeout
= 3;
3932 base
->global_search_state
= NULL
;
3933 base
->global_randomize_case
= 1;
3934 base
->global_getaddrinfo_allow_skew
.tv_sec
= 3;
3935 base
->global_getaddrinfo_allow_skew
.tv_usec
= 0;
3936 base
->global_nameserver_probe_initial_timeout
.tv_sec
= 10;
3937 base
->global_nameserver_probe_initial_timeout
.tv_usec
= 0;
3939 TAILQ_INIT(&base
->hostsdb
);
3941 if (initialize_nameservers
) {
3944 r
= evdns_base_config_windows_nameservers(base
);
3946 r
= evdns_base_resolv_conf_parse(base
, DNS_OPTIONS_ALL
, "/etc/resolv.conf");
3949 evdns_base_free_and_unlock(base
, 0);
3960 struct evdns_base
*base
= evdns_base_new(NULL
, 1);
3962 current_base
= base
;
3970 evdns_err_to_string(int err
)
3973 case DNS_ERR_NONE
: return "no error";
3974 case DNS_ERR_FORMAT
: return "misformatted query";
3975 case DNS_ERR_SERVERFAILED
: return "server failed";
3976 case DNS_ERR_NOTEXIST
: return "name does not exist";
3977 case DNS_ERR_NOTIMPL
: return "query not implemented";
3978 case DNS_ERR_REFUSED
: return "refused";
3980 case DNS_ERR_TRUNCATED
: return "reply truncated or ill-formed";
3981 case DNS_ERR_UNKNOWN
: return "unknown";
3982 case DNS_ERR_TIMEOUT
: return "request timed out";
3983 case DNS_ERR_SHUTDOWN
: return "dns subsystem shut down";
3984 case DNS_ERR_CANCEL
: return "dns request canceled";
3985 case DNS_ERR_NODATA
: return "no records in the reply";
3986 default: return "[Unknown error code]";
3991 evdns_nameserver_free(struct nameserver
*server
)
3993 if (server
->socket
>= 0)
3994 evutil_closesocket(server
->socket
);
3995 (void) event_del(&server
->event
);
3996 event_debug_unassign(&server
->event
);
3997 if (server
->state
== 0)
3998 (void) event_del(&server
->timeout_event
);
3999 event_debug_unassign(&server
->timeout_event
);
4004 evdns_base_free_and_unlock(struct evdns_base
*base
, int fail_requests
)
4006 struct nameserver
*server
, *server_next
;
4007 struct search_domain
*dom
, *dom_next
;
4010 /* Requires that we hold the lock. */
4012 /* TODO(nickm) we might need to refcount here. */
4014 for (i
= 0; i
< base
->n_req_heads
; ++i
) {
4015 while (base
->req_heads
[i
]) {
4017 reply_schedule_callback(base
->req_heads
[i
], 0, DNS_ERR_SHUTDOWN
, NULL
);
4018 request_finished(base
->req_heads
[i
], &REQ_HEAD(base
, base
->req_heads
[i
]->trans_id
), 1);
4021 while (base
->req_waiting_head
) {
4023 reply_schedule_callback(base
->req_waiting_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
4024 request_finished(base
->req_waiting_head
, &base
->req_waiting_head
, 1);
4026 base
->global_requests_inflight
= base
->global_requests_waiting
= 0;
4028 for (server
= base
->server_head
; server
; server
= server_next
) {
4029 server_next
= server
->next
;
4030 evdns_nameserver_free(server
);
4031 if (server_next
== base
->server_head
)
4034 base
->server_head
= NULL
;
4035 base
->global_good_nameservers
= 0;
4037 if (base
->global_search_state
) {
4038 for (dom
= base
->global_search_state
->head
; dom
; dom
= dom_next
) {
4039 dom_next
= dom
->next
;
4042 mm_free(base
->global_search_state
);
4043 base
->global_search_state
= NULL
;
4047 struct hosts_entry
*victim
;
4048 while ((victim
= TAILQ_FIRST(&base
->hostsdb
))) {
4049 TAILQ_REMOVE(&base
->hostsdb
, victim
, next
);
4054 mm_free(base
->req_heads
);
4057 EVTHREAD_FREE_LOCK(base
->lock
, EVTHREAD_LOCKTYPE_RECURSIVE
);
4063 evdns_base_free(struct evdns_base
*base
, int fail_requests
)
4066 evdns_base_free_and_unlock(base
, fail_requests
);
4070 evdns_shutdown(int fail_requests
)
4073 struct evdns_base
*b
= current_base
;
4074 current_base
= NULL
;
4075 evdns_base_free(b
, fail_requests
);
4077 evdns_log_fn
= NULL
;
4081 evdns_base_parse_hosts_line(struct evdns_base
*base
, char *line
)
4084 static const char *const delims
= " \t";
4085 char *const addr
= strtok_r(line
, delims
, &strtok_state
);
4086 char *hostname
, *hash
;
4087 struct sockaddr_storage ss
;
4088 int socklen
= sizeof(ss
);
4089 ASSERT_LOCKED(base
);
4091 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
4093 if (!addr
|| *addr
== '#')
4096 memset(&ss
, 0, sizeof(ss
));
4097 if (evutil_parse_sockaddr_port(addr
, (struct sockaddr
*)&ss
, &socklen
)<0)
4099 if (socklen
> (int)sizeof(struct sockaddr_in6
))
4102 if (sockaddr_getport((struct sockaddr
*)&ss
))
4105 while ((hostname
= NEXT_TOKEN
)) {
4106 struct hosts_entry
*he
;
4108 if ((hash
= strchr(hostname
, '#'))) {
4109 if (hash
== hostname
)
4114 namelen
= strlen(hostname
);
4116 he
= mm_calloc(1, sizeof(struct hosts_entry
)+namelen
);
4119 EVUTIL_ASSERT(socklen
<= (int)sizeof(he
->addr
));
4120 memcpy(&he
->addr
, &ss
, socklen
);
4121 memcpy(he
->hostname
, hostname
, namelen
+1);
4122 he
->addrlen
= socklen
;
4124 TAILQ_INSERT_TAIL(&base
->hostsdb
, he
, next
);
4135 evdns_base_load_hosts_impl(struct evdns_base
*base
, const char *hosts_fname
)
4137 char *str
=NULL
, *cp
, *eol
;
4141 ASSERT_LOCKED(base
);
4143 if (hosts_fname
== NULL
||
4144 (err
= evutil_read_file(hosts_fname
, &str
, &len
, 0)) < 0) {
4146 strlcpy(tmp
, "127.0.0.1 localhost", sizeof(tmp
));
4147 evdns_base_parse_hosts_line(base
, tmp
);
4148 strlcpy(tmp
, "::1 localhost", sizeof(tmp
));
4149 evdns_base_parse_hosts_line(base
, tmp
);
4150 return err
? -1 : 0;
4153 /* This will break early if there is a NUL in the hosts file.
4154 * Probably not a problem.*/
4157 eol
= strchr(cp
, '\n');
4161 evdns_base_parse_hosts_line(base
, cp
);
4164 evdns_base_parse_hosts_line(base
, cp
);
4174 evdns_base_load_hosts(struct evdns_base
*base
, const char *hosts_fname
)
4178 base
= current_base
;
4180 res
= evdns_base_load_hosts_impl(base
, hosts_fname
);
4185 /* A single request for a getaddrinfo, either v4 or v6. */
4186 struct getaddrinfo_subrequest
{
4187 struct evdns_request
*r
;
4191 /* State data used to implement an in-progress getaddrinfo. */
4192 struct evdns_getaddrinfo_request
{
4193 struct evdns_base
*evdns_base
;
4194 /* Copy of the modified 'hints' data that we'll use to build
4196 struct evutil_addrinfo hints
;
4197 /* The callback to invoke when we're done */
4198 evdns_getaddrinfo_cb user_cb
;
4199 /* User-supplied data to give to the callback. */
4201 /* The port to use when building sockaddrs. */
4203 /* The sub_request for an A record (if any) */
4204 struct getaddrinfo_subrequest ipv4_request
;
4205 /* The sub_request for an AAAA record (if any) */
4206 struct getaddrinfo_subrequest ipv6_request
;
4208 /* The cname result that we were told (if any) */
4211 /* If we have one request answered and one request still inflight,
4212 * then this field holds the answer from the first request... */
4213 struct evutil_addrinfo
*pending_result
;
4214 /* And this event is a timeout that will tell us to cancel the second
4215 * request if it's taking a long time. */
4216 struct event timeout
;
4218 /* And this field holds the error code from the first request... */
4220 /* If this is set, the user canceled this request. */
4221 unsigned user_canceled
: 1;
4222 /* If this is set, the user can no longer cancel this request; we're
4223 * just waiting for the free. */
4224 unsigned request_done
: 1;
4227 /* Convert an evdns errors to the equivalent getaddrinfo error. */
4229 evdns_err_to_getaddrinfo_err(int e1
)
4231 /* XXX Do this better! */
4232 if (e1
== DNS_ERR_NONE
)
4234 else if (e1
== DNS_ERR_NOTEXIST
)
4235 return EVUTIL_EAI_NONAME
;
4237 return EVUTIL_EAI_FAIL
;
4240 /* Return the more informative of two getaddrinfo errors. */
4242 getaddrinfo_merge_err(int e1
, int e2
)
4244 /* XXXX be cleverer here. */
4252 free_getaddrinfo_request(struct evdns_getaddrinfo_request
*data
)
4254 /* DO NOT CALL this if either of the requests is pending. Only once
4255 * both callbacks have been invoked is it safe to free the request */
4256 if (data
->pending_result
)
4257 evutil_freeaddrinfo(data
->pending_result
);
4258 if (data
->cname_result
)
4259 mm_free(data
->cname_result
);
4260 event_del(&data
->timeout
);
4266 add_cname_to_reply(struct evdns_getaddrinfo_request
*data
,
4267 struct evutil_addrinfo
*ai
)
4269 if (data
->cname_result
&& ai
) {
4270 ai
->ai_canonname
= data
->cname_result
;
4271 data
->cname_result
= NULL
;
4275 /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
4276 * request has finished, but the other one took too long to answer. Pass
4277 * along the answer we got, and cancel the other request.
4280 evdns_getaddrinfo_timeout_cb(evutil_socket_t fd
, short what
, void *ptr
)
4282 int v4_timedout
= 0, v6_timedout
= 0;
4283 struct evdns_getaddrinfo_request
*data
= ptr
;
4285 /* Cancel any pending requests, and note which one */
4286 if (data
->ipv4_request
.r
) {
4287 evdns_cancel_request(NULL
, data
->ipv4_request
.r
);
4289 EVDNS_LOCK(data
->evdns_base
);
4290 ++data
->evdns_base
->getaddrinfo_ipv4_timeouts
;
4291 EVDNS_UNLOCK(data
->evdns_base
);
4293 if (data
->ipv6_request
.r
) {
4294 evdns_cancel_request(NULL
, data
->ipv6_request
.r
);
4296 EVDNS_LOCK(data
->evdns_base
);
4297 ++data
->evdns_base
->getaddrinfo_ipv6_timeouts
;
4298 EVDNS_UNLOCK(data
->evdns_base
);
4301 /* We only use this timeout callback when we have an answer for
4303 EVUTIL_ASSERT(!v4_timedout
|| !v6_timedout
);
4305 /* Report the outcome of the other request that didn't time out. */
4306 if (data
->pending_result
) {
4307 add_cname_to_reply(data
, data
->pending_result
);
4308 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4309 data
->pending_result
= NULL
;
4311 int e
= data
->pending_error
;
4313 e
= EVUTIL_EAI_AGAIN
;
4314 data
->user_cb(e
, NULL
, data
->user_data
);
4317 if (!v4_timedout
&& !v6_timedout
) {
4318 /* should be impossible? XXXX */
4319 free_getaddrinfo_request(data
);
4324 evdns_getaddrinfo_set_timeout(struct evdns_base
*evdns_base
,
4325 struct evdns_getaddrinfo_request
*data
)
4327 return event_add(&data
->timeout
, &evdns_base
->global_getaddrinfo_allow_skew
);
4331 evdns_result_is_answer(int result
)
4333 return (result
!= DNS_ERR_NOTIMPL
&& result
!= DNS_ERR_REFUSED
&&
4334 result
!= DNS_ERR_SERVERFAILED
&& result
!= DNS_ERR_CANCEL
);
4338 evdns_getaddrinfo_gotresolve(int result
, char type
, int count
,
4339 int ttl
, void *addresses
, void *arg
)
4342 struct getaddrinfo_subrequest
*req
= arg
;
4343 struct getaddrinfo_subrequest
*other_req
;
4344 struct evdns_getaddrinfo_request
*data
;
4346 struct evutil_addrinfo
*res
;
4348 struct sockaddr_in sin
;
4349 struct sockaddr_in6 sin6
;
4350 struct sockaddr
*sa
;
4351 int socklen
, addrlen
;
4356 EVUTIL_ASSERT(req
->type
== DNS_IPv4_A
|| req
->type
== DNS_IPv6_AAAA
);
4357 if (req
->type
== DNS_IPv4_A
) {
4358 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv4_request
);
4359 other_req
= &data
->ipv6_request
;
4361 data
= EVUTIL_UPCAST(req
, struct evdns_getaddrinfo_request
, ipv6_request
);
4362 other_req
= &data
->ipv4_request
;
4365 EVDNS_LOCK(data
->evdns_base
);
4366 if (evdns_result_is_answer(result
)) {
4367 if (req
->type
== DNS_IPv4_A
)
4368 ++data
->evdns_base
->getaddrinfo_ipv4_answered
;
4370 ++data
->evdns_base
->getaddrinfo_ipv6_answered
;
4372 user_canceled
= data
->user_canceled
;
4373 if (other_req
->r
== NULL
)
4374 data
->request_done
= 1;
4375 EVDNS_UNLOCK(data
->evdns_base
);
4379 if (result
== DNS_ERR_CANCEL
&& ! user_canceled
) {
4380 /* Internal cancel request from timeout or internal error.
4381 * we already answered the user. */
4382 if (other_req
->r
== NULL
)
4383 free_getaddrinfo_request(data
);
4387 if (result
== DNS_ERR_NONE
) {
4389 err
= EVUTIL_EAI_NODATA
;
4393 err
= evdns_err_to_getaddrinfo_err(result
);
4397 /* Looks like we got an error. */
4399 /* The other request is still working; maybe it will
4401 /* XXXX handle failure from set_timeout */
4402 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4403 data
->pending_error
= err
;
4407 if (user_canceled
) {
4408 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4409 } else if (data
->pending_result
) {
4410 /* If we have an answer waiting, and we weren't
4411 * canceled, ignore this error. */
4412 add_cname_to_reply(data
, data
->pending_result
);
4413 data
->user_cb(0, data
->pending_result
, data
->user_data
);
4414 data
->pending_result
= NULL
;
4416 if (data
->pending_error
)
4417 err
= getaddrinfo_merge_err(err
,
4418 data
->pending_error
);
4419 data
->user_cb(err
, NULL
, data
->user_data
);
4421 free_getaddrinfo_request(data
);
4423 } else if (user_canceled
) {
4425 /* The other request is still working; let it hit this
4426 * callback with EVUTIL_EAI_CANCEL callback and report
4430 data
->user_cb(EVUTIL_EAI_CANCEL
, NULL
, data
->user_data
);
4431 free_getaddrinfo_request(data
);
4435 /* Looks like we got some answers. We should turn them into addrinfos
4436 * and then either queue those or return them all. */
4437 EVUTIL_ASSERT(type
== DNS_IPv4_A
|| type
== DNS_IPv6_AAAA
);
4439 if (type
== DNS_IPv4_A
) {
4440 memset(&sin
, 0, sizeof(sin
));
4441 sin
.sin_family
= AF_INET
;
4442 sin
.sin_port
= htons(data
->port
);
4444 sa
= (struct sockaddr
*)&sin
;
4445 socklen
= sizeof(sin
);
4447 addrp
= &sin
.sin_addr
.s_addr
;
4449 memset(&sin6
, 0, sizeof(sin6
));
4450 sin6
.sin6_family
= AF_INET6
;
4451 sin6
.sin6_port
= htons(data
->port
);
4453 sa
= (struct sockaddr
*)&sin6
;
4454 socklen
= sizeof(sin6
);
4456 addrp
= &sin6
.sin6_addr
.s6_addr
;
4460 for (i
=0; i
< count
; ++i
) {
4461 struct evutil_addrinfo
*ai
;
4462 memcpy(addrp
, ((char*)addresses
)+i
*addrlen
, addrlen
);
4463 ai
= evutil_new_addrinfo(sa
, socklen
, &data
->hints
);
4466 evdns_cancel_request(NULL
, other_req
->r
);
4468 data
->user_cb(EVUTIL_EAI_MEMORY
, NULL
, data
->user_data
);
4470 evutil_freeaddrinfo(res
);
4472 if (other_req
->r
== NULL
)
4473 free_getaddrinfo_request(data
);
4476 res
= evutil_addrinfo_append(res
, ai
);
4480 /* The other request is still in progress; wait for it */
4481 /* XXXX handle failure from set_timeout */
4482 evdns_getaddrinfo_set_timeout(data
->evdns_base
, data
);
4483 data
->pending_result
= res
;
4486 /* The other request is done or never started; append its
4487 * results (if any) and return them. */
4488 if (data
->pending_result
) {
4489 if (req
->type
== DNS_IPv4_A
)
4490 res
= evutil_addrinfo_append(res
,
4491 data
->pending_result
);
4493 res
= evutil_addrinfo_append(
4494 data
->pending_result
, res
);
4495 data
->pending_result
= NULL
;
4498 /* Call the user callback. */
4499 add_cname_to_reply(data
, res
);
4500 data
->user_cb(0, res
, data
->user_data
);
4503 free_getaddrinfo_request(data
);
4507 static struct hosts_entry
*
4508 find_hosts_entry(struct evdns_base
*base
, const char *hostname
,
4509 struct hosts_entry
*find_after
)
4511 struct hosts_entry
*e
;
4514 e
= TAILQ_NEXT(find_after
, next
);
4516 e
= TAILQ_FIRST(&base
->hostsdb
);
4518 for (; e
; e
= TAILQ_NEXT(e
, next
)) {
4519 if (!evutil_ascii_strcasecmp(e
->hostname
, hostname
))
4526 evdns_getaddrinfo_fromhosts(struct evdns_base
*base
,
4527 const char *nodename
, struct evutil_addrinfo
*hints
, ev_uint16_t port
,
4528 struct evutil_addrinfo
**res
)
4531 struct hosts_entry
*e
;
4532 struct evutil_addrinfo
*ai
=NULL
;
4533 int f
= hints
->ai_family
;
4536 for (e
= find_hosts_entry(base
, nodename
, NULL
); e
;
4537 e
= find_hosts_entry(base
, nodename
, e
)) {
4538 struct evutil_addrinfo
*ai_new
;
4540 if ((e
->addr
.sa
.sa_family
== AF_INET
&& f
== PF_INET6
) ||
4541 (e
->addr
.sa
.sa_family
== AF_INET6
&& f
== PF_INET
))
4543 ai_new
= evutil_new_addrinfo(&e
->addr
.sa
, e
->addrlen
, hints
);
4548 sockaddr_setport(ai_new
->ai_addr
, port
);
4549 ai
= evutil_addrinfo_append(ai
, ai_new
);
4554 /* Note that we return an empty answer if we found entries for
4555 * this hostname but none were of the right address type. */
4560 evutil_freeaddrinfo(ai
);
4565 struct evdns_getaddrinfo_request
*
4566 evdns_getaddrinfo(struct evdns_base
*dns_base
,
4567 const char *nodename
, const char *servname
,
4568 const struct evutil_addrinfo
*hints_in
,
4569 evdns_getaddrinfo_cb cb
, void *arg
)
4571 struct evdns_getaddrinfo_request
*data
;
4572 struct evutil_addrinfo hints
;
4573 struct evutil_addrinfo
*res
= NULL
;
4579 dns_base
= current_base
;
4582 "Call to getaddrinfo_async with no "
4583 "evdns_base configured.");
4584 cb(EVUTIL_EAI_FAIL
, NULL
, arg
); /* ??? better error? */
4589 /* If we _must_ answer this immediately, do so. */
4590 if ((hints_in
&& (hints_in
->ai_flags
& EVUTIL_AI_NUMERICHOST
))) {
4592 err
= evutil_getaddrinfo(nodename
, servname
, hints_in
, &res
);
4598 memcpy(&hints
, hints_in
, sizeof(hints
));
4600 memset(&hints
, 0, sizeof(hints
));
4601 hints
.ai_family
= PF_UNSPEC
;
4604 evutil_adjust_hints_for_addrconfig(&hints
);
4606 /* Now try to see if we _can_ answer immediately. */
4607 /* (It would be nice to do this by calling getaddrinfo directly, with
4608 * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
4609 * a reliable way to distinguish the "that wasn't a numeric host!" case
4610 * from any other EAI_NONAME cases.) */
4611 err
= evutil_getaddrinfo_common(nodename
, servname
, &hints
, &res
, &port
);
4612 if (err
!= EVUTIL_EAI_NEED_RESOLVE
) {
4617 /* If there is an entry in the hosts file, we should give it now. */
4618 if (!evdns_getaddrinfo_fromhosts(dns_base
, nodename
, &hints
, port
, &res
)) {
4623 /* Okay, things are serious now. We're going to need to actually
4626 data
= mm_calloc(1,sizeof(struct evdns_getaddrinfo_request
));
4628 cb(EVUTIL_EAI_MEMORY
, NULL
, arg
);
4632 memcpy(&data
->hints
, &hints
, sizeof(data
->hints
));
4633 data
->port
= (ev_uint16_t
)port
;
4634 data
->ipv4_request
.type
= DNS_IPv4_A
;
4635 data
->ipv6_request
.type
= DNS_IPv6_AAAA
;
4637 data
->user_data
= arg
;
4638 data
->evdns_base
= dns_base
;
4640 want_cname
= (hints
.ai_flags
& EVUTIL_AI_CANONNAME
);
4642 /* If we are asked for a PF_UNSPEC address, we launch two requests in
4643 * parallel: one for an A address and one for an AAAA address. We
4644 * can't send just one request, since many servers only answer one
4645 * question per DNS request.
4647 * Once we have the answer to one request, we allow for a short
4648 * timeout before we report it, to see if the other one arrives. If
4649 * they both show up in time, then we report both the answers.
4651 * If too many addresses of one type time out or fail, we should stop
4652 * launching those requests. (XXX we don't do that yet.)
4655 if (hints
.ai_family
!= PF_INET6
) {
4656 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv4 as %p",
4657 nodename
, &data
->ipv4_request
);
4659 data
->ipv4_request
.r
= evdns_base_resolve_ipv4(dns_base
,
4660 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4661 &data
->ipv4_request
);
4663 data
->ipv4_request
.r
->current_req
->put_cname_in_ptr
=
4664 &data
->cname_result
;
4666 if (hints
.ai_family
!= PF_INET
) {
4667 log(EVDNS_LOG_DEBUG
, "Sending request for %s on ipv6 as %p",
4668 nodename
, &data
->ipv6_request
);
4670 data
->ipv6_request
.r
= evdns_base_resolve_ipv6(dns_base
,
4671 nodename
, 0, evdns_getaddrinfo_gotresolve
,
4672 &data
->ipv6_request
);
4674 data
->ipv6_request
.r
->current_req
->put_cname_in_ptr
=
4675 &data
->cname_result
;
4678 evtimer_assign(&data
->timeout
, dns_base
->event_base
,
4679 evdns_getaddrinfo_timeout_cb
, data
);
4681 if (data
->ipv4_request
.r
|| data
->ipv6_request
.r
) {
4685 cb(EVUTIL_EAI_FAIL
, NULL
, arg
);
4691 evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request
*data
)
4693 EVDNS_LOCK(data
->evdns_base
);
4694 if (data
->request_done
) {
4695 EVDNS_UNLOCK(data
->evdns_base
);
4698 event_del(&data
->timeout
);
4699 data
->user_canceled
= 1;
4700 if (data
->ipv4_request
.r
)
4701 evdns_cancel_request(data
->evdns_base
, data
->ipv4_request
.r
);
4702 if (data
->ipv6_request
.r
)
4703 evdns_cancel_request(data
->evdns_base
, data
->ipv6_request
.r
);
4704 EVDNS_UNLOCK(data
->evdns_base
);