1 /* The original version of this module was written by Adam Langley; for
2 * a history of modifications, check out the subversion logs.
4 * When editing this module, try to keep it re-mergeable by Adam. Don't
5 * reformat the whitespace, add Tor dependencies, or so on.
8 * - Replace all externally visible magic numbers with #defined constants.
9 * - Write documentation for APIs of all external functions.
13 * Adam Langley <agl@imperialviolet.org>
16 * This software is Public Domain. To view a copy of the public domain dedication,
17 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
18 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
20 * I ask and expect, but do not require, that all derivative works contain an
21 * attribution similar to:
22 * Parts developed by Adam Langley <agl@imperialviolet.org>
24 * You may wish to replace the word "Parts" with something else depending on
25 * the amount of original code.
27 * (Derivative works does not include programs which link against, run or include
28 * the source verbatim in their source distributions)
33 #include "eventdns_tor.h"
34 #include <sys/types.h>
37 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
38 #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
39 #ifndef DNS_USE_OPENSSL_FOR_ID
40 #error Must configure at least one id generation method.
41 #error Please see the documentation.
46 /* #define _POSIX_C_SOURCE 200507 */
49 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
50 #ifdef DNS_USE_OPENSSL_FOR_ID
51 #error Multiple id options selected
53 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
54 #error Multiple id options selected
59 #ifdef DNS_USE_OPENSSL_FOR_ID
60 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
61 #error Multiple id options selected
63 #include <openssl/rand.h>
70 #ifdef HAVE_SYS_TIME_H
97 #include <sys/socket.h>
98 #include <netinet/in.h>
99 #include <arpa/inet.h>
102 #ifdef HAVE_NETINET_IN6_H
103 #include <netinet/in6.h>
107 typedef int socklen_t
;
110 #define EVDNS_LOG_DEBUG 0
111 #define EVDNS_LOG_WARN 1
113 #ifndef HOST_NAME_MAX
114 #define HOST_NAME_MAX 255
121 /* for debugging possible memory leaks. */
122 #define mm_malloc(x) tor_malloc(x)
123 #define mm_realloc(x,y) tor_realloc((x),(y))
124 #define mm_free(x) tor_free(x)
125 #define mm_strdup(x) tor_strdup(x)
126 #define _mm_free(x) _tor_free(x)
129 #define MIN(a,b) ((a)<(b)?(a):(b))
133 /* libevent doesn't work without this */
134 typedef uint8_t u_char
;
135 typedef unsigned int uint
;
145 #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
146 /* which we bother recording */
148 #define TYPE_A EVDNS_TYPE_A
150 #define TYPE_PTR EVDNS_TYPE_PTR
151 #define TYPE_AAAA EVDNS_TYPE_AAAA
153 #define CLASS_INET EVDNS_CLASS_INET
155 #define CLEAR(x) do { memset((x), 0xF0, sizeof(*(x))); } while(0)
157 struct evdns_request
{
158 u8
*request
; /* the dns packet data */
159 unsigned int request_len
;
161 int tx_count
; /* the number of times that this packet has been sent */
162 unsigned int request_type
; /* TYPE_PTR or TYPE_A */
163 void *user_pointer
; /* the pointer given to us for this request */
164 evdns_callback_type user_callback
;
165 struct nameserver
*ns
; /* the server which we last sent it */
167 /* elements used by the searching code */
169 struct search_state
*search_state
;
170 char *search_origname
; /* needs to be mm_free()ed */
173 /* these objects are kept in a circular list */
174 struct evdns_request
*next
, *prev
;
176 u16 timeout_event_deleted
; /**< Debugging: where was timeout_event
177 * deleted? 0 for "it's added." */
178 struct event timeout_event
;
180 u16 trans_id
; /* the transaction id */
181 char request_appended
; /* true if the request pointer is data which follows this struct */
182 char transmit_me
; /* needs to be transmitted */
185 #ifndef HAVE_STRUCT_IN6_ADDR
193 unsigned int have_answer
;
197 u32 addresses
[MAX_ADDRS
];
201 struct in6_addr addresses
[MAX_ADDRS
];
204 char name
[HOST_NAME_MAX
];
210 int socket
; /* a connected UDP socket */
211 struct sockaddr_storage address
;
212 int failed_times
; /* number of times which we have given this server a chance */
213 int timedout
; /* number of times in a row a request has timed out */
215 /* these objects are kept in a circular list */
216 struct nameserver
*next
, *prev
;
217 u16 timeout_event_deleted
; /**< Debugging: where was timeout_event
218 * deleted? 0 for "it's added." */
219 struct event timeout_event
; /* used to keep the timeout for */
220 /* when we next probe this server. */
221 /* Valid if state == 0 */
222 char state
; /* zero if we think that this server is down */
223 char choked
; /* true if we have an EAGAIN from this server's socket */
224 char write_waiting
; /* true if we are waiting for EV_WRITE events */
227 static struct evdns_request
*req_head
= NULL
, *req_waiting_head
= NULL
;
228 static struct nameserver
*server_head
= NULL
;
230 /* Represents a local port where we're listening for DNS requests. Right now, */
231 /* only UDP is supported. */
232 struct evdns_server_port
{
233 int socket
; /* socket we use to read queries and write replies. */
234 int refcnt
; /* reference count. */
235 char choked
; /* Are we currently blocked from writing? */
236 char closing
; /* Are we trying to close this port, pending writes? */
237 evdns_request_callback_fn_type user_callback
; /* Fn to handle requests */
238 void *user_data
; /* Opaque pointer passed to user_callback */
239 struct event event
; /* Read/write event */
240 /* circular list of replies that we want to write. */
241 struct server_request
*pending_replies
;
244 /* Represents part of a reply being built. (That is, a single RR.) */
245 struct server_reply_item
{
246 struct server_reply_item
*next
; /* next item in sequence. */
247 char *name
; /* name part of the RR */
248 u16 type
: 16; /* The RR type */
249 u16
class : 16; /* The RR class (usually CLASS_INET) */
250 u32 ttl
; /* The RR TTL */
251 char is_name
; /* True iff data is a label */
252 u16 datalen
; /* Length of data; -1 if data is a label */
253 void *data
; /* The contents of the RR */
256 /* Represents a request that we've received as a DNS server, and holds */
257 /* the components of the reply as we're constructing it. */
258 struct server_request
{
259 /* Pointers to the next and previous entries on the list of replies */
260 /* that we're waiting to write. Only set if we have tried to respond */
261 /* and gotten EAGAIN. */
262 struct server_request
*next_pending
;
263 struct server_request
*prev_pending
;
265 u16 trans_id
; /* Transaction id. */
266 struct evdns_server_port
*port
; /* Which port received this request on? */
267 struct sockaddr_storage addr
; /* Where to send the response */
268 socklen_t addrlen
; /* length of addr */
270 int n_answer
; /* how many answer RRs have been set? */
271 int n_authority
; /* how many authority RRs have been set? */
272 int n_additional
; /* how many additional RRs have been set? */
274 struct server_reply_item
*answer
; /* linked list of answer RRs */
275 struct server_reply_item
*authority
; /* linked list of authority RRs */
276 struct server_reply_item
*additional
; /* linked list of additional RRs */
278 /* Constructed response. Only set once we're ready to send a reply. */
279 /* Once this is set, the RR fields are cleared, and no more should be set. */
283 /* Caller-visible fields: flags, questions. */
284 struct evdns_server_request base
;
288 #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
290 /* Given a pointer to an evdns_server_request, get the corresponding */
291 /* server_request. */
292 #define TO_SERVER_REQUEST(base_ptr) \
293 ((struct server_request*) \
294 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
296 /* The number of good nameservers that we have */
297 static int global_good_nameservers
= 0;
299 /* inflight requests are contained in the req_head list */
300 /* and are actually going out across the network */
301 static int global_requests_inflight
= 0;
302 /* requests which aren't inflight are in the waiting list */
303 /* and are counted here */
304 static int global_requests_waiting
= 0;
306 static int global_max_requests_inflight
= 64;
308 static struct timeval global_timeout
= {5, 0}; /* 5 seconds */
309 static int global_max_reissues
= 1; /* a reissue occurs when we get some errors from the server */
310 static int global_max_retransmits
= 3; /* number of times we'll retransmit a request which timed out */
311 /* number of timeouts in a row before we consider this server to be down */
312 static int global_max_nameserver_timeout
= 3;
314 /* true iff we should use the 0x20 hack. */
315 static int global_randomize_case
= 1;
317 /* These are the timeout values for nameservers. If we find a nameserver is down */
318 /* we try to probe it at intervals as given below. Values are in seconds. */
319 static const struct timeval global_nameserver_timeouts
[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
320 static const int global_nameserver_timeouts_length
= (int)(sizeof(global_nameserver_timeouts
)/sizeof(struct timeval
));
322 static struct nameserver
*nameserver_pick(void);
323 static void evdns_request_insert(struct evdns_request
*req
, struct evdns_request
**head
);
324 static void nameserver_ready_callback(int fd
, short events
, void *arg
);
325 static int evdns_transmit(void);
326 static int evdns_request_transmit(struct evdns_request
*req
);
327 static void nameserver_send_probe(struct nameserver
*const ns
);
328 static void search_request_finished(struct evdns_request
*const);
329 static int search_try_next(struct evdns_request
*const req
);
330 static int search_request_new(int type
, const char *const name
, int flags
, evdns_callback_type user_callback
, void *user_arg
);
331 static void evdns_requests_pump_waiting_queue(void);
332 static u16
transaction_id_pick(void);
333 static struct evdns_request
*request_new(int type
, const char *name
, int flags
, evdns_callback_type callback
, void *ptr
);
334 static void request_submit(struct evdns_request
*req
);
336 static int server_request_free(struct server_request
*req
);
337 static void server_request_free_answers(struct server_request
*req
);
338 static void server_port_free(struct evdns_server_port
*port
);
339 static void server_port_ready_callback(int fd
, short events
, void *arg
);
341 static int strtoint(const char *const str
);
347 int optval
, optvallen
=sizeof(optval
);
348 int err
= WSAGetLastError();
349 if (err
== WSAEWOULDBLOCK
&& sock
>= 0) {
350 if (getsockopt(sock
, SOL_SOCKET
, SO_ERROR
, (void*)&optval
,
360 error_is_eagain(int err
)
362 return err
== EAGAIN
|| err
== WSAEWOULDBLOCK
;
364 #define inet_aton(c, addr) tor_inet_aton((c), (addr))
365 #define CLOSE_SOCKET(x) closesocket(x)
367 #define last_error(sock) (errno)
368 #define error_is_eagain(err) ((err) == EAGAIN)
369 #define CLOSE_SOCKET(x) close(x)
372 #define ISSPACE(c) TOR_ISSPACE(c)
373 #define ISDIGIT(c) TOR_ISDIGIT(c)
374 #define ISALPHA(c) TOR_ISALPHA(c)
375 #define TOLOWER(c) TOR_TOLOWER(c)
376 #define TOUPPER(c) TOR_TOUPPER(c)
380 debug_ntoa(u32 address
)
383 u32 a
= ntohl(address
);
384 snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d",
385 (int)(u8
)((a
>>24)&0xff),
386 (int)(u8
)((a
>>16)&0xff),
387 (int)(u8
)((a
>>8 )&0xff),
388 (int)(u8
)((a
)&0xff));
392 debug_ntop(const struct sockaddr
*sa
)
394 if (sa
->sa_family
== AF_INET
) {
395 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
396 return debug_ntoa(sin
->sin_addr
.s_addr
);
398 if (sa
->sa_family
== AF_INET6
) {
399 /* Tor-specific. In libevent, add more check code. */
400 static char buf
[128];
401 struct sockaddr_in6
*sin
= (struct sockaddr_in6
*) sa
;
402 tor_inet_ntop(AF_INET6
, &sin
->sin6_addr
, buf
, sizeof(buf
));
409 static evdns_debug_log_fn_type evdns_log_fn
= NULL
;
412 evdns_set_log_fn(evdns_debug_log_fn_type fn
)
418 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
420 #define EVDNS_LOG_CHECK
423 static void _evdns_log(int warn
, const char *fmt
, ...) EVDNS_LOG_CHECK
;
425 _evdns_log(int warn
, const char *fmt
, ...)
428 static char buf
[512];
433 _vsnprintf(buf
, sizeof(buf
), fmt
, args
);
435 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
437 buf
[sizeof(buf
)-1] = '\0';
438 evdns_log_fn(warn
, buf
);
442 #define log _evdns_log
445 sockaddr_eq(const struct sockaddr
*sa1
, const struct sockaddr
*sa2
,
448 if (sa1
->sa_family
!= sa2
->sa_family
)
450 if (sa1
->sa_family
== AF_INET
) {
451 const struct sockaddr_in
*sin1
, *sin2
;
452 sin1
= (const struct sockaddr_in
*)sa1
;
453 sin2
= (const struct sockaddr_in
*)sa2
;
454 if (sin1
->sin_addr
.s_addr
!= sin2
->sin_addr
.s_addr
)
456 else if (include_port
&& sin1
->sin_port
!= sin2
->sin_port
)
462 if (sa1
->sa_family
== AF_INET6
) {
463 const struct sockaddr_in6
*sin1
, *sin2
;
464 sin1
= (const struct sockaddr_in6
*)sa1
;
465 sin2
= (const struct sockaddr_in6
*)sa2
;
466 if (memcmp(sin1
->sin6_addr
.s6_addr
, sin2
->sin6_addr
.s6_addr
, 16))
468 else if (include_port
&& sin1
->sin6_port
!= sin2
->sin6_port
)
477 /* for debugging bug 929. XXXX021 */
479 _add_timeout_event(u16
*lineno
, struct event
*ev
, struct timeval
*to
)
482 return evtimer_add(ev
, to
);
484 #define add_timeout_event(s, to) \
485 (_add_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, (to)))
487 /* for debugging bug 929. XXXX021 */
489 _del_timeout_event(u16
*lineno
, struct event
*ev
, int line
)
493 "Duplicate timeout event_del from line %d: first call "
494 "was at %d.", line
, (int)*lineno
);
498 return event_del(ev
);
501 #define del_timeout_event(s) \
502 (_del_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, \
505 /* This walks the list of inflight requests to find the */
506 /* one with a matching transaction id. Returns NULL on */
508 static struct evdns_request
*
509 request_find_from_trans_id(u16 trans_id
) {
510 struct evdns_request
*req
= req_head
, *const started_at
= req_head
;
514 if (req
->trans_id
== trans_id
) return req
;
516 } while (req
!= started_at
);
522 /* a libevent callback function which is called when a nameserver */
523 /* has gone down and we want to test if it has came back to life yet */
525 nameserver_prod_callback(int fd
, short events
, void *arg
) {
526 struct nameserver
*const ns
= (struct nameserver
*) arg
;
530 nameserver_send_probe(ns
);
533 /* a libevent callback which is called when a nameserver probe (to see if */
534 /* it has come back to life) times out. We increment the count of failed_times */
535 /* and wait longer to send the next probe packet. */
537 nameserver_probe_failed(struct nameserver
*const ns
) {
538 const struct timeval
* timeout
;
539 del_timeout_event(ns
);
540 CLEAR(&ns
->timeout_event
);
541 if (ns
->state
== 1) {
542 /* This can happen if the nameserver acts in a way which makes us mark */
543 /* it as bad and then starts sending good replies. */
548 &global_nameserver_timeouts
[MIN(ns
->failed_times
,
549 global_nameserver_timeouts_length
- 1)];
552 evtimer_set(&ns
->timeout_event
, nameserver_prod_callback
, ns
);
553 if (add_timeout_event(ns
, (struct timeval
*) timeout
) < 0) {
555 "Error from libevent when adding timer event for %s",
556 debug_ntop((struct sockaddr
*)&ns
->address
));
561 /* called when a nameserver has been deemed to have failed. For example, too */
562 /* many packets have timed out etc */
564 nameserver_failed(struct nameserver
*const ns
, const char *msg
) {
565 struct evdns_request
*req
, *started_at
;
566 /* if this nameserver has already been marked as failed */
567 /* then don't do anything */
568 if (!ns
->state
) return;
570 log(EVDNS_LOG_WARN
, "Nameserver %s has failed: %s",
571 debug_ntop((struct sockaddr
*)&ns
->address
), msg
);
572 global_good_nameservers
--;
573 assert(global_good_nameservers
>= 0);
574 if (global_good_nameservers
== 0) {
575 log(EVDNS_LOG_WARN
, "All nameservers have failed");
579 ns
->failed_times
= 1;
581 evtimer_set(&ns
->timeout_event
, nameserver_prod_callback
, ns
);
582 if (add_timeout_event(ns
, (struct timeval
*) &global_nameserver_timeouts
[0]) < 0) {
584 "Error from libevent when adding timer event for %s",
585 debug_ntop((struct sockaddr
*)&ns
->address
));
589 /* walk the list of inflight requests to see if any can be reassigned to */
590 /* a different server. Requests in the waiting queue don't have a */
591 /* nameserver assigned yet */
593 /* if we don't have *any* good nameservers then there's no point */
594 /* trying to reassign requests to one */
595 if (!global_good_nameservers
) return;
598 started_at
= req_head
;
601 if (req
->tx_count
== 0 && req
->ns
== ns
) {
602 /* still waiting to go out, can be moved */
603 /* to another server */
604 req
->ns
= nameserver_pick();
607 } while (req
!= started_at
);
612 nameserver_up(struct nameserver
*const ns
) {
613 if (ns
->state
) return;
614 log(EVDNS_LOG_WARN
, "Nameserver %s is back up",
615 debug_ntop((struct sockaddr
*)&ns
->address
));
616 del_timeout_event(ns
);
617 CLEAR(&ns
->timeout_event
);
619 ns
->failed_times
= 0;
621 global_good_nameservers
++;
625 request_trans_id_set(struct evdns_request
*const req
, const u16 trans_id
) {
626 req
->trans_id
= trans_id
;
627 *((u16
*) req
->request
) = htons(trans_id
);
630 /* Called to remove a request from a list and dealloc it. */
631 /* head is a pointer to the head of the list it should be */
632 /* removed from or NULL if the request isn't in a list. */
634 request_finished(struct evdns_request
*const req
, struct evdns_request
**head
) {
636 if (req
->next
== req
) {
637 /* only item in the list */
640 req
->next
->prev
= req
->prev
;
641 req
->prev
->next
= req
->next
;
642 if (*head
== req
) *head
= req
->next
;
646 log(EVDNS_LOG_DEBUG
, "Removing timeout for request %lx",
647 (unsigned long) req
);
648 del_timeout_event(req
);
649 CLEAR(&req
->timeout_event
);
651 search_request_finished(req
);
652 global_requests_inflight
--;
654 if (!req
->request_appended
) {
655 /* need to free the request data on it's own */
656 mm_free(req
->request
);
658 /* the request data is appended onto the header */
659 /* so everything gets mm_free()ed when we: */
665 evdns_requests_pump_waiting_queue();
668 /* This is called when a server returns a funny error code. */
669 /* We try the request again with another server. */
673 /* 1 failed/reissue is pointless */
675 request_reissue(struct evdns_request
*req
) {
676 const struct nameserver
*const last_ns
= req
->ns
;
677 /* the last nameserver should have been marked as failing */
678 /* by the caller of this function, therefore pick will try */
679 /* not to return it */
680 req
->ns
= nameserver_pick();
681 if (req
->ns
== last_ns
) {
682 /* ... but pick did return it */
683 /* not a lot of point in trying again with the */
688 req
->reissue_count
++;
690 req
->transmit_me
= 1;
695 /* this function looks for space on the inflight queue and promotes */
696 /* requests from the waiting queue if it can. */
698 evdns_requests_pump_waiting_queue(void) {
699 while (global_requests_inflight
< global_max_requests_inflight
&&
700 global_requests_waiting
) {
701 struct evdns_request
*req
;
702 /* move a request from the waiting queue to the inflight queue */
703 assert(req_waiting_head
);
704 if (req_waiting_head
->next
== req_waiting_head
) {
705 /* only one item in the queue */
706 req
= req_waiting_head
;
707 req_waiting_head
= NULL
;
709 req
= req_waiting_head
;
710 req
->next
->prev
= req
->prev
;
711 req
->prev
->next
= req
->next
;
712 req_waiting_head
= req
->next
;
715 global_requests_waiting
--;
716 global_requests_inflight
++;
718 req
->ns
= nameserver_pick();
719 request_trans_id_set(req
, transaction_id_pick());
721 evdns_request_insert(req
, &req_head
);
722 evdns_request_transmit(req
);
728 reply_callback(struct evdns_request
*const req
, u32 ttl
, u32 err
, struct reply
*reply
) {
729 switch (req
->request_type
) {
732 req
->user_callback(DNS_ERR_NONE
, DNS_IPv4_A
,
733 reply
->data
.a
.addrcount
, ttl
,
734 reply
->data
.a
.addresses
,
737 req
->user_callback(err
, 0, 0, 0, NULL
, req
->user_pointer
);
741 char *name
= reply
->data
.ptr
.name
;
742 req
->user_callback(DNS_ERR_NONE
, DNS_PTR
, 1, ttl
,
743 &name
, req
->user_pointer
);
745 req
->user_callback(err
, 0, 0, 0, NULL
,
751 req
->user_callback(DNS_ERR_NONE
, DNS_IPv6_AAAA
,
752 reply
->data
.aaaa
.addrcount
, ttl
,
753 reply
->data
.aaaa
.addresses
,
756 req
->user_callback(err
, 0, 0, 0, NULL
, req
->user_pointer
);
762 /* this processes a parsed reply packet */
764 reply_handle(struct evdns_request
*const req
, u16 flags
, u32 ttl
, struct reply
*reply
) {
766 static const int error_codes
[] = {DNS_ERR_FORMAT
, DNS_ERR_SERVERFAILED
, DNS_ERR_NOTEXIST
, DNS_ERR_NOTIMPL
, DNS_ERR_REFUSED
};
768 if (flags
& 0x020f || !reply
|| !reply
->have_answer
) {
769 /* there was an error */
770 if (flags
& 0x0200) {
771 error
= DNS_ERR_TRUNCATED
;
773 u16 error_code
= (flags
& 0x000f) - 1;
774 if (error_code
> 4) {
775 error
= DNS_ERR_UNKNOWN
;
777 error
= error_codes
[error_code
];
782 case DNS_ERR_NOTIMPL
:
783 case DNS_ERR_REFUSED
:
784 /* we regard these errors as marking a bad nameserver */
785 if (req
->reissue_count
< global_max_reissues
) {
787 snprintf(msg
, sizeof(msg
), "Bad response %d (%s)",
788 error
, evdns_err_to_string(error
));
789 nameserver_failed(req
->ns
, msg
);
790 if (!request_reissue(req
)) return;
793 case DNS_ERR_SERVERFAILED
:
794 /* rcode 2 (servfailed) sometimes means "we are broken" and
795 * sometimes (with some binds) means "that request was very
796 * confusing." Treat this as a timeout, not a failure.
798 /*XXXX refactor the parts of */
799 log(EVDNS_LOG_DEBUG
, "Got a SERVERFAILED from nameserver %s; "
800 "will allow the request to time out.",
801 debug_ntop((struct sockaddr
*)&req
->ns
->address
));
804 /* we got a good reply from the nameserver */
805 nameserver_up(req
->ns
);
808 if (req
->search_state
&& req
->request_type
!= TYPE_PTR
) {
809 /* if we have a list of domains to search in, try the next one */
810 if (!search_try_next(req
)) {
811 /* a new request was issued so this request is finished and */
812 /* the user callback will be made when that request (or a */
813 /* child of it) finishes. */
814 request_finished(req
, &req_head
);
819 /* all else failed. Pass the failure up */
820 reply_callback(req
, 0, error
, NULL
);
821 request_finished(req
, &req_head
);
823 /* all ok, tell the user */
824 reply_callback(req
, ttl
, 0, reply
);
825 nameserver_up(req
->ns
);
826 request_finished(req
, &req_head
);
831 name_parse(u8
*packet
, int length
, int *idx
, char *name_out
, size_t name_out_len
) {
835 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
836 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
837 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
840 const char *const end
= name_out
+ name_out_len
;
842 /* Normally, names are a series of length prefixed strings terminated */
843 /* with a length of 0 (the lengths are u8's < 63). */
844 /* However, the length can start with a pair of 1 bits and that */
845 /* means that the next 14 bits are a pointer within the current */
850 if (j
>= length
) return -1;
852 if (!label_len
) break;
853 if (label_len
& 0xc0) {
856 if (name_end
< 0) name_end
= j
;
857 j
= (((int)label_len
& 0x3f) << 8) + ptr_low
;
858 /* Make sure that the target offset is in-bounds. */
859 if (j
< 0 || j
>= length
) return -1;
860 /* If we've jumped more times than there are characters in the
861 * message, we must have a loop. */
862 if (++ptr_count
> length
) return -1;
865 if (label_len
> 63) return -1;
866 if (cp
!= name_out
) {
867 if (cp
+ 1 >= end
) return -1;
870 if (cp
+ label_len
>= end
) return -1;
871 memcpy(cp
, packet
+ j
, label_len
);
875 if (cp
>= end
) return -1;
886 /* parses a raw reply from a nameserver. */
888 reply_parse(u8
*packet
, int length
) {
889 int j
= 0; /* index into packet */
891 u16 _t
; /* used by the macros */
892 u32 _t32
; /* used by the macros */
893 char tmp_name
[256], cmp_name
[256]; /* used by the macros */
895 u16 trans_id
, questions
, answers
, authority
, additional
, datalength
;
897 u32 ttl
, ttl_r
= 0xffffffff;
899 struct evdns_request
*req
= NULL
;
901 int name_matches
= 0;
909 (void) authority
; /* suppress "unused variable" warnings. */
910 (void) additional
; /* suppress "unused variable" warnings. */
912 req
= request_find_from_trans_id(trans_id
);
913 /* if no request, can't do anything. */
916 memset(&reply
, 0, sizeof(reply
));
918 /* If it's not an answer, it doesn't go with any of our requests. */
919 if (!(flags
& 0x8000)) return -1; /* must be an answer */
920 if (flags
& 0x020f) {
921 /* there was an error */
924 /* if (!answers) return; */ /* must have an answer of some form */
926 /* This macro skips a name in the DNS reply. */
928 do { tmp_name[0] = '\0'; \
929 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
933 do { tmp_name[0] = '\0'; \
934 cmp_name[0] = '\0'; \
936 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
938 if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \
940 if (global_randomize_case) { \
941 if (strcmp(tmp_name, cmp_name) == 0) \
942 name_matches = 1; /* we ignore mismatching names */ \
944 if (strcasecmp(tmp_name, cmp_name) == 0) \
949 reply
.type
= req
->request_type
;
951 /* skip over each question in the reply */
952 for (i
= 0; i
< questions
; ++i
) {
953 /* the question looks like
954 * <label:name><u16:type><u16:class>
958 if (j
>= length
) goto err
;
964 /* now we have the answer section which looks like
965 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
968 for (i
= 0; i
< answers
; ++i
) {
977 if (type
== TYPE_A
&& class == CLASS_INET
) {
978 int addrcount
, addrtocopy
;
979 if (req
->request_type
!= TYPE_A
) {
980 j
+= datalength
; continue;
982 if ((datalength
& 3) != 0) /* not an even number of As. */
984 addrcount
= datalength
>> 2;
985 addrtocopy
= MIN(MAX_ADDRS
- reply
.data
.a
.addrcount
, (unsigned)addrcount
);
987 ttl_r
= MIN(ttl_r
, ttl
);
988 /* we only bother with the first four addresses. */
989 if (j
+ 4*addrtocopy
> length
) goto err
;
990 memcpy(&reply
.data
.a
.addresses
[reply
.data
.a
.addrcount
],
991 packet
+ j
, 4*addrtocopy
);
992 reply
.data
.a
.addrcount
+= addrtocopy
;
993 reply
.have_answer
= 1;
994 if (reply
.data
.a
.addrcount
== MAX_ADDRS
) break;
996 } else if (type
== TYPE_PTR
&& class == CLASS_INET
) {
997 if (req
->request_type
!= TYPE_PTR
) {
998 j
+= datalength
; continue;
1001 strlcpy(reply
.data
.ptr
.name
, tmp_name
,
1002 sizeof(reply
.data
.ptr
.name
));
1003 ttl_r
= MIN(ttl_r
, ttl
);
1004 reply
.have_answer
= 1;
1006 } else if (type
== TYPE_AAAA
&& class == CLASS_INET
) {
1007 int addrcount
, addrtocopy
;
1008 if (req
->request_type
!= TYPE_AAAA
) {
1009 j
+= datalength
; continue;
1011 if ((datalength
& 15) != 0) /* not an even number of AAAAs. */
1013 addrcount
= datalength
>> 4; /* each address is 16 bytes long */
1014 addrtocopy
= MIN(MAX_ADDRS
- reply
.data
.aaaa
.addrcount
, (unsigned)addrcount
);
1015 ttl_r
= MIN(ttl_r
, ttl
);
1017 /* we only bother with the first four addresses. */
1018 if (j
+ 16*addrtocopy
> length
) goto err
;
1019 memcpy(&reply
.data
.aaaa
.addresses
[reply
.data
.aaaa
.addrcount
],
1020 packet
+ j
, 16*addrtocopy
);
1021 reply
.data
.aaaa
.addrcount
+= addrtocopy
;
1022 reply
.have_answer
= 1;
1023 if (reply
.data
.aaaa
.addrcount
== MAX_ADDRS
) break;
1026 /* skip over any other type of resource */
1031 reply_handle(req
, flags
, ttl_r
, &reply
);
1035 reply_handle(req
, flags
, 0, NULL
);
1039 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1040 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1043 request_parse(u8
*packet
, ssize_t length
, struct evdns_server_port
*port
, struct sockaddr
*addr
, socklen_t addrlen
)
1045 int j
= 0; /* index into packet */
1046 u16 _t
; /* used by the macros */
1047 char tmp_name
[256]; /* used by the macros */
1050 u16 trans_id
, flags
, questions
, answers
, authority
, additional
;
1051 struct server_request
*server_req
= NULL
;
1053 /* Get the header fields */
1061 if (flags
& 0x8000) return -1; /* Must not be an answer. */
1062 flags
&= 0x0110; /* Only RD and CD get preserved. */
1064 if (length
> INT_MAX
)
1067 server_req
= mm_malloc(sizeof(struct server_request
));
1068 if (server_req
== NULL
) return -1;
1069 memset(server_req
, 0, sizeof(struct server_request
));
1071 server_req
->trans_id
= trans_id
;
1072 memcpy(&server_req
->addr
, addr
, addrlen
);
1073 server_req
->addrlen
= addrlen
;
1075 server_req
->base
.flags
= flags
;
1076 server_req
->base
.nquestions
= 0;
1077 server_req
->base
.questions
= mm_malloc(sizeof(struct evdns_server_question
*) * questions
);
1078 if (server_req
->base
.questions
== NULL
)
1081 for (i
= 0; i
< questions
; ++i
) {
1083 struct evdns_server_question
*q
;
1085 if (name_parse(packet
, (int)length
, &j
, tmp_name
, sizeof(tmp_name
))<0)
1089 namelen
= strlen(tmp_name
);
1090 q
= mm_malloc(sizeof(struct evdns_server_question
) + namelen
);
1094 q
->dns_question_class
= class;
1095 memcpy(q
->name
, tmp_name
, namelen
+1);
1096 server_req
->base
.questions
[server_req
->base
.nquestions
++] = q
;
1099 /* Ignore answers, authority, and additional. */
1101 server_req
->port
= port
;
1104 /* Only standard queries are supported. */
1105 if (flags
& 0x7800) {
1106 evdns_server_request_respond(&(server_req
->base
), DNS_ERR_NOTIMPL
);
1110 port
->user_callback(&(server_req
->base
), port
->user_data
);
1115 if (server_req
->base
.questions
) {
1116 for (i
= 0; i
< server_req
->base
.nquestions
; ++i
)
1117 mm_free(server_req
->base
.questions
[i
]);
1118 mm_free(server_req
->base
.questions
);
1121 mm_free(server_req
);
1132 default_transaction_id_fn(void)
1135 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
1137 #ifdef CLOCK_MONOTONIC
1138 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == -1)
1140 if (clock_gettime(CLOCK_REALTIME
, &ts
) == -1)
1142 event_err(1, "clock_gettime");
1143 trans_id
= ts
.tv_nsec
& 0xffff;
1146 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
1148 gettimeofday(&tv
, NULL
);
1149 trans_id
= tv
.tv_usec
& 0xffff;
1152 #ifdef DNS_USE_OPENSSL_FOR_ID
1153 if (RAND_pseudo_bytes((u8
*) &trans_id
, 2) == -1) {
1154 /* in the case that the RAND call fails we back */
1155 /* down to using gettimeofday. */
1158 gettimeofday(&tv, NULL);
1159 trans_id = tv.tv_usec & 0xffff;
1164 return (unsigned short) trans_id
;
1167 static uint16_t (*trans_id_function
)(void) = default_transaction_id_fn
;
1170 default_random_bytes_fn(char *buf
, size_t n
)
1173 for (i
= 0; i
< n
; i
+= 2) {
1174 u16 tid
= trans_id_function();
1175 buf
[i
] = (tid
>> 8) & 0xff;
1177 buf
[i
+1] = tid
& 0xff;
1181 static void (*rand_bytes_function
)(char *buf
, size_t n
) =
1182 default_random_bytes_fn
;
1185 trans_id_from_random_bytes_fn(void)
1188 rand_bytes_function((char*) &tid
, sizeof(tid
));
1193 evdns_set_transaction_id_fn(uint16_t (*fn
)(void))
1196 trans_id_function
= fn
;
1198 trans_id_function
= default_transaction_id_fn
;
1199 rand_bytes_function
= default_random_bytes_fn
;
1203 evdns_set_random_bytes_fn(void (*fn
)(char *, size_t))
1205 rand_bytes_function
= fn
;
1206 trans_id_function
= trans_id_from_random_bytes_fn
;
1209 /* Try to choose a strong transaction id which isn't already in flight */
1211 transaction_id_pick(void) {
1213 const struct evdns_request
*req
= req_head
, *started_at
;
1214 u16 trans_id
= trans_id_function();
1216 if (trans_id
== 0xffff) continue;
1217 /* now check to see if that id is already inflight */
1218 req
= started_at
= req_head
;
1221 if (req
->trans_id
== trans_id
) break;
1223 } while (req
!= started_at
);
1225 /* we didn't find it, so this is a good id */
1226 if (req
== started_at
) return trans_id
;
1230 /* choose a namesever to use. This function will try to ignore */
1231 /* nameservers which we think are down and load balance across the rest */
1232 /* by updating the server_head global each time. */
1233 static struct nameserver
*
1234 nameserver_pick(void) {
1235 struct nameserver
*started_at
= server_head
, *picked
;
1236 if (!server_head
) return NULL
;
1238 /* if we don't have any good nameservers then there's no */
1239 /* point in trying to find one. */
1240 if (!global_good_nameservers
) {
1241 server_head
= server_head
->next
;
1245 /* remember that nameservers are in a circular list */
1247 if (server_head
->state
) {
1248 /* we think this server is currently good */
1249 picked
= server_head
;
1250 server_head
= server_head
->next
;
1254 server_head
= server_head
->next
;
1255 if (server_head
== started_at
) {
1256 /* all the nameservers seem to be down */
1257 /* so we just return this one and hope for the */
1259 assert(global_good_nameservers
== 0);
1260 picked
= server_head
;
1261 server_head
= server_head
->next
;
1267 /* this is called when a namesever socket is ready for reading */
1269 nameserver_read(struct nameserver
*ns
) {
1270 struct sockaddr_storage ss
;
1271 struct sockaddr
*sa
= (struct sockaddr
*) &ss
;
1272 socklen_t addrlen
= sizeof(ss
);
1277 (int)recvfrom(ns
->socket
, packet
, (socklen_t
)sizeof(packet
), 0,
1280 int err
= last_error(ns
->socket
);
1281 if (error_is_eagain(err
)) return;
1282 nameserver_failed(ns
, strerror(err
));
1285 /* XXX Match port too? */
1286 if (!sockaddr_eq(sa
, (struct sockaddr
*)&ns
->address
, 0)) {
1288 "Address mismatch on received DNS packet. Address was %s",
1293 reply_parse(packet
, r
);
1297 /* Read a packet from a DNS client on a server port s, parse it, and */
1298 /* act accordingly. */
1300 server_port_read(struct evdns_server_port
*s
) {
1302 struct sockaddr_storage addr
;
1307 addrlen
= (socklen_t
)sizeof(struct sockaddr_storage
);
1308 r
= recvfrom(s
->socket
, packet
, sizeof(packet
), 0,
1309 (struct sockaddr
*) &addr
, &addrlen
);
1311 int err
= last_error(s
->socket
);
1312 if (error_is_eagain(err
)) return;
1313 log(EVDNS_LOG_WARN
, "Error %s (%d) while reading request.",
1314 strerror(err
), err
);
1317 request_parse(packet
, r
, s
, (struct sockaddr
*) &addr
, addrlen
);
1321 /* Try to write all pending replies on a given DNS server port. */
1323 server_port_flush(struct evdns_server_port
*port
)
1325 while (port
->pending_replies
) {
1326 struct server_request
*req
= port
->pending_replies
;
1327 ssize_t r
= sendto(port
->socket
, req
->response
, req
->response_len
, 0,
1328 (struct sockaddr
*) &req
->addr
, (socklen_t
)req
->addrlen
);
1330 int err
= last_error(port
->socket
);
1331 if (error_is_eagain(err
))
1333 log(EVDNS_LOG_WARN
, "Error %s (%d) while writing response to port; dropping", strerror(err
), err
);
1335 if (server_request_free(req
)) {
1336 /* we released the last reference to req->port. */
1341 /* We have no more pending requests; stop listening for 'writeable' events. */
1342 (void) event_del(&port
->event
);
1343 CLEAR(&port
->event
);
1344 event_set(&port
->event
, port
->socket
, EV_READ
| EV_PERSIST
,
1345 server_port_ready_callback
, port
);
1346 if (event_add(&port
->event
, NULL
) < 0) {
1347 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server.");
1352 /* set if we are waiting for the ability to write to this server. */
1353 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1354 /* we stop these events. */
1356 nameserver_write_waiting(struct nameserver
*ns
, char waiting
) {
1357 if (ns
->write_waiting
== waiting
) return;
1359 ns
->write_waiting
= waiting
;
1360 (void) event_del(&ns
->event
);
1362 event_set(&ns
->event
, ns
->socket
, EV_READ
| (waiting
? EV_WRITE
: 0) | EV_PERSIST
,
1363 nameserver_ready_callback
, ns
);
1364 if (event_add(&ns
->event
, NULL
) < 0) {
1365 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for %s",
1366 debug_ntop((struct sockaddr
*)&ns
->address
));
1371 /* a callback function. Called by libevent when the kernel says that */
1372 /* a nameserver socket is ready for writing or reading */
1374 nameserver_ready_callback(int fd
, short events
, void *arg
) {
1375 struct nameserver
*ns
= (struct nameserver
*) arg
;
1378 if (events
& EV_WRITE
) {
1380 if (!evdns_transmit()) {
1381 nameserver_write_waiting(ns
, 0);
1384 if (events
& EV_READ
) {
1385 nameserver_read(ns
);
1389 /* a callback function. Called by libevent when the kernel says that */
1390 /* a server socket is ready for writing or reading. */
1392 server_port_ready_callback(int fd
, short events
, void *arg
) {
1393 struct evdns_server_port
*port
= (struct evdns_server_port
*) arg
;
1396 if (events
& EV_WRITE
) {
1398 server_port_flush(port
);
1400 if (events
& EV_READ
) {
1401 server_port_read(port
);
1405 /* This is an inefficient representation; only use it via the dnslabel_table_*
1406 * functions, so that is can be safely replaced with something smarter later. */
1407 #define MAX_LABELS 128
1408 /* Structures used to implement name compression */
1409 struct dnslabel_entry
{ char *v
; off_t pos
; };
1410 struct dnslabel_table
{
1411 int n_labels
; /* number of current entries */
1412 /* map from name to position in message */
1413 struct dnslabel_entry labels
[MAX_LABELS
];
1416 /* Initialize dnslabel_table. */
1418 dnslabel_table_init(struct dnslabel_table
*table
)
1420 table
->n_labels
= 0;
1423 /* Free all storage held by table, but not the table itself. */
1425 dnslabel_clear(struct dnslabel_table
*table
)
1428 for (i
= 0; i
< table
->n_labels
; ++i
)
1429 mm_free(table
->labels
[i
].v
);
1430 table
->n_labels
= 0;
1433 /* return the position of the label in the current message, or -1 if the label */
1434 /* hasn't been used yet. */
1436 dnslabel_table_get_pos(const struct dnslabel_table
*table
, const char *label
)
1439 for (i
= 0; i
< table
->n_labels
; ++i
) {
1440 if (!strcmp(label
, table
->labels
[i
].v
)) {
1441 off_t pos
= table
->labels
[i
].pos
;
1450 /* remember that we've used the label at position pos */
1452 dnslabel_table_add(struct dnslabel_table
*table
, const char *label
, off_t pos
)
1456 if (table
->n_labels
== MAX_LABELS
)
1458 v
= mm_strdup(label
);
1461 p
= table
->n_labels
++;
1462 table
->labels
[p
].v
= v
;
1463 table
->labels
[p
].pos
= pos
;
1468 /* Converts a string to a length-prefixed set of DNS labels, starting */
1469 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1470 /* of name. table is optional, and is used for compression. */
1472 /* Input: abc.def */
1473 /* Output: <3>abc<3>def<0> */
1475 /* Returns the first index after the encoded name, or negative on error. */
1476 /* -1 label was > 63 bytes */
1477 /* -2 name too long to fit in buffer. */
1480 dnsname_to_labels(u8
*const buf
, size_t buf_len
, off_t j
,
1481 const char *name
, const size_t name_len
,
1482 struct dnslabel_table
*table
) {
1483 const char *end
= name
+ name_len
;
1487 #define APPEND16(x) do { \
1488 if (j + 2 > (off_t)buf_len) \
1491 memcpy(buf + j, &_t, 2); \
1494 #define APPEND32(x) do { \
1495 if (j + 4 > (off_t)buf_len) \
1498 memcpy(buf + j, &_t32, 4); \
1502 if (name_len
> 255) return -2;
1505 const char *const start
= name
;
1506 if (table
&& (ref
= dnslabel_table_get_pos(table
, name
)) >= 0) {
1507 APPEND16(ref
| 0xc000);
1510 name
= strchr(name
, '.');
1512 const size_t label_len
= end
- start
;
1513 if (label_len
> 63) return -1;
1514 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1515 if (table
) dnslabel_table_add(table
, start
, j
);
1516 buf
[j
++] = (uint8_t)label_len
;
1518 memcpy(buf
+ j
, start
, label_len
);
1522 /* append length of the label. */
1523 const size_t label_len
= name
- start
;
1524 if (label_len
> 63) return -1;
1525 if ((size_t)(j
+label_len
+1) > buf_len
) return -2;
1526 if (table
) dnslabel_table_add(table
, start
, j
);
1527 buf
[j
++] = (uint8_t)label_len
;
1529 memcpy(buf
+ j
, start
, name
- start
);
1531 /* hop over the '.' */
1536 /* the labels must be terminated by a 0. */
1537 /* It's possible that the name ended in a . */
1538 /* in which case the zero is already there */
1539 if (!j
|| buf
[j
-1]) buf
[j
++] = 0;
1545 /* Finds the length of a dns request for a DNS name of the given */
1546 /* length. The actual request may be smaller than the value returned */
1549 evdns_request_len(const size_t name_len
) {
1550 return 96 + /* length of the DNS standard header */
1552 4; /* space for the resource type */
1555 /* build a dns request packet into buf. buf should be at least as long */
1556 /* as evdns_request_len told you it should be. */
1558 /* Returns the amount of space used. Negative on error. */
1560 evdns_request_data_build(const char *const name
, const size_t name_len
,
1561 const u16 trans_id
, const u16 type
, const u16
class,
1562 u8
*const buf
, size_t buf_len
) {
1563 off_t j
= 0; /* current offset into buf */
1564 u16 _t
; /* used by the macros */
1567 APPEND16(0x0100); /* standard query, recusion needed */
1568 APPEND16(1); /* one question */
1569 APPEND16(0); /* no answers */
1570 APPEND16(0); /* no authority */
1571 APPEND16(0); /* no additional */
1573 j
= dnsname_to_labels(buf
, buf_len
, j
, name
, name_len
, NULL
);
1586 /* exported function */
1587 struct evdns_server_port
*
1588 evdns_add_server_port(int socket
, int is_tcp
, evdns_request_callback_fn_type cb
, void *user_data
)
1590 struct evdns_server_port
*port
;
1591 if (!(port
= mm_malloc(sizeof(struct evdns_server_port
))))
1593 memset(port
, 0, sizeof(struct evdns_server_port
));
1595 assert(!is_tcp
); /* TCP sockets not yet implemented */
1596 port
->socket
= socket
;
1600 port
->user_callback
= cb
;
1601 port
->user_data
= user_data
;
1602 port
->pending_replies
= NULL
;
1604 event_set(&port
->event
, port
->socket
, EV_READ
| EV_PERSIST
,
1605 server_port_ready_callback
, port
);
1606 if (event_add(&port
->event
, NULL
)<0) {
1613 /* exported function */
1615 evdns_close_server_port(struct evdns_server_port
*port
)
1618 if (--port
->refcnt
== 0)
1619 server_port_free(port
);
1622 /* exported function */
1624 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
)
1626 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1627 struct server_reply_item
**itemp
, *item
;
1630 if (req
->response
) /* have we already answered? */
1634 case EVDNS_ANSWER_SECTION
:
1635 itemp
= &req
->answer
;
1636 countp
= &req
->n_answer
;
1638 case EVDNS_AUTHORITY_SECTION
:
1639 itemp
= &req
->authority
;
1640 countp
= &req
->n_authority
;
1642 case EVDNS_ADDITIONAL_SECTION
:
1643 itemp
= &req
->additional
;
1644 countp
= &req
->n_additional
;
1650 itemp
= &((*itemp
)->next
);
1652 item
= mm_malloc(sizeof(struct server_reply_item
));
1657 if (!(item
->name
= mm_strdup(name
))) {
1663 item
->class = class;
1665 item
->is_name
= is_name
!= 0;
1669 if (item
->is_name
) {
1670 if (!(item
->data
= mm_strdup(data
))) {
1671 mm_free(item
->name
);
1676 item
->datalen
= (u16
)-1;
1678 if (!(item
->data
= mm_malloc(datalen
))) {
1679 mm_free(item
->name
);
1684 item
->datalen
= datalen
;
1685 memcpy(item
->data
, data
, datalen
);
1694 /* exported function */
1696 evdns_server_request_add_a_reply(struct evdns_server_request
*req
, const char *name
, int n
, void *addrs
, int ttl
)
1698 return evdns_server_request_add_reply(
1699 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_A
, CLASS_INET
,
1700 ttl
, n
*4, 0, addrs
);
1703 /* exported function */
1705 evdns_server_request_add_aaaa_reply(struct evdns_server_request
*req
, const char *name
, int n
, void *addrs
, int ttl
)
1707 return evdns_server_request_add_reply(
1708 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_AAAA
, CLASS_INET
,
1709 ttl
, n
*16, 0, addrs
);
1712 /* exported function */
1714 evdns_server_request_add_ptr_reply(struct evdns_server_request
*req
, struct in_addr
*in
, const char *inaddr_name
, const char *hostname
, int ttl
)
1718 assert(in
|| inaddr_name
);
1719 assert(!(in
&& inaddr_name
));
1721 a
= ntohl(in
->s_addr
);
1722 snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
1723 (int)(u8
)((a
)&0xff),
1724 (int)(u8
)((a
>>8 )&0xff),
1725 (int)(u8
)((a
>>16)&0xff),
1726 (int)(u8
)((a
>>24)&0xff));
1729 return evdns_server_request_add_reply(
1730 req
, EVDNS_ANSWER_SECTION
, inaddr_name
, TYPE_PTR
, CLASS_INET
,
1731 ttl
, -1, 1, hostname
);
1734 /* exported function */
1736 evdns_server_request_add_cname_reply(struct evdns_server_request
*req
, const char *name
, const char *cname
, int ttl
)
1738 return evdns_server_request_add_reply(
1739 req
, EVDNS_ANSWER_SECTION
, name
, TYPE_CNAME
, CLASS_INET
,
1745 evdns_server_request_format_response(struct server_request
*req
, int err
)
1747 unsigned char buf
[1500];
1748 size_t buf_len
= sizeof(buf
);
1754 struct dnslabel_table table
;
1756 if (err
< 0 || err
> 15) return -1;
1758 /* Set response bit and error code; copy OPCODE and RD fields from
1759 * question; copy RA and AA if set by caller. */
1760 flags
= req
->base
.flags
;
1761 flags
|= (0x8000 | err
);
1763 dnslabel_table_init(&table
);
1764 APPEND16(req
->trans_id
);
1766 APPEND16(req
->base
.nquestions
);
1767 APPEND16(req
->n_answer
);
1768 APPEND16(req
->n_authority
);
1769 APPEND16(req
->n_additional
);
1771 /* Add questions. */
1772 for (i
=0; i
< req
->base
.nquestions
; ++i
) {
1773 const char *s
= req
->base
.questions
[i
]->name
;
1774 j
= dnsname_to_labels(buf
, buf_len
, j
, s
, strlen(s
), &table
);
1776 dnslabel_clear(&table
);
1779 APPEND16(req
->base
.questions
[i
]->type
);
1780 APPEND16(req
->base
.questions
[i
]->dns_question_class
);
1783 /* Add answer, authority, and additional sections. */
1784 for (i
=0; i
<3; ++i
) {
1785 struct server_reply_item
*item
;
1789 item
= req
->authority
;
1791 item
= req
->additional
;
1793 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->name
, strlen(item
->name
), &table
);
1798 APPEND16(item
->type
);
1799 APPEND16(item
->class);
1800 APPEND32(item
->ttl
);
1801 if (item
->is_name
) {
1802 off_t len_idx
= j
, name_start
;
1805 r
= dnsname_to_labels(buf
, buf_len
, j
, item
->data
, strlen(item
->data
), &table
);
1809 _t
= htons( (j
-name_start
) );
1810 memcpy(buf
+len_idx
, &_t
, 2);
1812 APPEND16(item
->datalen
);
1813 if (j
+item
->datalen
> (off_t
)buf_len
)
1815 memcpy(buf
+j
, item
->data
, item
->datalen
);
1825 buf
[3] |= 0x02; /* set the truncated bit. */
1828 req
->response_len
= (size_t)j
;
1830 if (!(req
->response
= mm_malloc(req
->response_len
))) {
1831 server_request_free_answers(req
);
1832 dnslabel_clear(&table
);
1835 memcpy(req
->response
, buf
, req
->response_len
);
1836 server_request_free_answers(req
);
1837 dnslabel_clear(&table
);
1841 /* exported function */
1843 evdns_server_request_respond(struct evdns_server_request
*_req
, int err
)
1845 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1846 struct evdns_server_port
*port
= req
->port
;
1848 if (!req
->response
) {
1849 if ((r
= evdns_server_request_format_response(req
, err
))<0)
1853 r
= sendto(port
->socket
, req
->response
, req
->response_len
, 0,
1854 (struct sockaddr
*) &req
->addr
, req
->addrlen
);
1856 int err
= last_error(port
->socket
);
1857 if (! error_is_eagain(err
))
1860 if (port
->pending_replies
) {
1861 req
->prev_pending
= port
->pending_replies
->prev_pending
;
1862 req
->next_pending
= port
->pending_replies
;
1863 req
->prev_pending
->next_pending
=
1864 req
->next_pending
->prev_pending
= req
;
1866 req
->prev_pending
= req
->next_pending
= req
;
1867 port
->pending_replies
= req
;
1870 (void) event_del(&port
->event
);
1871 CLEAR(&port
->event
);
1872 event_set(&port
->event
, port
->socket
, (port
->closing
?0:EV_READ
) | EV_WRITE
| EV_PERSIST
, server_port_ready_callback
, port
);
1874 if (event_add(&port
->event
, NULL
) < 0) {
1875 log(EVDNS_LOG_WARN
, "Error from libevent when adding event for DNS server");
1882 if (server_request_free(req
))
1885 if (port
->pending_replies
)
1886 server_port_flush(port
);
1891 /* Free all storage held by RRs in req. */
1893 server_request_free_answers(struct server_request
*req
)
1895 struct server_reply_item
*victim
, *next
, **list
;
1897 for (i
= 0; i
< 3; ++i
) {
1899 list
= &req
->answer
;
1901 list
= &req
->authority
;
1903 list
= &req
->additional
;
1907 next
= victim
->next
;
1908 mm_free(victim
->name
);
1910 mm_free(victim
->data
);
1918 /* Free all storage held by req, and remove links to it. */
1919 /* return true iff we just wound up freeing the server_port. */
1921 server_request_free(struct server_request
*req
)
1924 if (req
->base
.questions
) {
1925 for (i
= 0; i
< req
->base
.nquestions
; ++i
)
1926 mm_free(req
->base
.questions
[i
]);
1927 mm_free(req
->base
.questions
);
1931 if (req
->port
->pending_replies
== req
) {
1932 if (req
->next_pending
)
1933 req
->port
->pending_replies
= req
->next_pending
;
1935 req
->port
->pending_replies
= NULL
;
1937 rc
= --req
->port
->refcnt
;
1940 if (req
->response
) {
1941 mm_free(req
->response
);
1944 server_request_free_answers(req
);
1946 if (req
->next_pending
&& req
->next_pending
!= req
) {
1947 req
->next_pending
->prev_pending
= req
->prev_pending
;
1948 req
->prev_pending
->next_pending
= req
->next_pending
;
1952 server_port_free(req
->port
);
1962 /* Free all storage held by an evdns_server_port. Only called when the
1963 * reference count is down to 0. */
1965 server_port_free(struct evdns_server_port
*port
)
1968 assert(!port
->refcnt
);
1969 assert(!port
->pending_replies
);
1970 if (port
->socket
> 0) {
1971 CLOSE_SOCKET(port
->socket
);
1974 (void) event_del(&port
->event
);
1975 CLEAR(&port
->event
);
1980 /* exported function */
1982 evdns_server_request_drop(struct evdns_server_request
*_req
)
1984 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1985 server_request_free(req
);
1989 /* exported function */
1991 evdns_server_request_get_requesting_addr(struct evdns_server_request
*_req
, struct sockaddr
*sa
, int addr_len
)
1993 struct server_request
*req
= TO_SERVER_REQUEST(_req
);
1994 if (addr_len
< (int)req
->addrlen
)
1996 memcpy(sa
, &(req
->addr
), req
->addrlen
);
1997 return req
->addrlen
;
2003 /* this is a libevent callback function which is called when a request */
2004 /* has timed out. */
2006 evdns_request_timeout_callback(int fd
, short events
, void *arg
) {
2007 struct evdns_request
*const req
= (struct evdns_request
*) arg
;
2011 log(EVDNS_LOG_DEBUG
, "Request %lx timed out", (unsigned long) arg
);
2013 req
->ns
->timedout
++;
2014 if (req
->ns
->timedout
> global_max_nameserver_timeout
) {
2015 req
->ns
->timedout
= 0;
2016 nameserver_failed(req
->ns
, "request timed out.");
2019 if (req
->tx_count
>= global_max_retransmits
) {
2020 /* this request has failed */
2021 reply_callback(req
, 0, DNS_ERR_TIMEOUT
, NULL
);
2022 request_finished(req
, &req_head
);
2025 /* Stop waiting for the timeout. No need to do this in
2026 * request_finished; that one already deletes the timeout event.
2027 * XXXX021 port this change to libevent. */
2028 del_timeout_event(req
);
2029 CLEAR(&req
->timeout_event
);
2030 evdns_request_transmit(req
);
2034 /* try to send a request to a given server. */
2038 /* 1 temporary failure */
2039 /* 2 other failure */
2041 evdns_request_transmit_to(struct evdns_request
*req
, struct nameserver
*server
) {
2042 const ssize_t r
= send(server
->socket
, req
->request
, req
->request_len
, 0);
2044 int err
= last_error(server
->socket
);
2045 if (error_is_eagain(err
)) return 1;
2046 nameserver_failed(req
->ns
, strerror(err
));
2048 } else if (r
!= (ssize_t
)req
->request_len
) {
2049 return 1; /* short write */
2055 /* try to send a request, updating the fields of the request */
2062 evdns_request_transmit(struct evdns_request
*req
) {
2065 /* if we fail to send this packet then this flag marks it */
2066 /* for evdns_transmit */
2067 req
->transmit_me
= 1;
2068 if (req
->trans_id
== 0xffff) abort();
2070 if (req
->ns
->choked
) {
2071 /* don't bother trying to write to a socket */
2072 /* which we have had EAGAIN from */
2076 r
= evdns_request_transmit_to(req
, req
->ns
);
2080 req
->ns
->choked
= 1;
2081 nameserver_write_waiting(req
->ns
, 1);
2084 /* failed to transmit the request entirely. */
2086 /* fall through: we'll set a timeout, which will time out,
2087 * and make us retransmit the request anyway. */
2089 /* transmitted; we need to check for timeout. */
2090 log(EVDNS_LOG_DEBUG
,
2091 "Setting timeout for request %lx", (unsigned long) req
);
2092 evtimer_set(&req
->timeout_event
, evdns_request_timeout_callback
, req
);
2093 if (add_timeout_event(req
, &global_timeout
) < 0) {
2095 "Error from libevent when adding timer for request %lx",
2096 (unsigned long) req
);
2100 req
->transmit_me
= 0;
2106 nameserver_probe_callback(int result
, char type
, int count
, int ttl
, void *addresses
, void *arg
) {
2107 struct sockaddr
*addr
= arg
;
2108 struct nameserver
*server
;
2114 for (server
= server_head
; server
; server
= server
->next
) {
2115 if (sockaddr_eq(addr
, (struct sockaddr
*) &server
->address
, 1)) {
2116 if (result
== DNS_ERR_NONE
|| result
== DNS_ERR_NOTEXIST
) {
2117 /* this is a good reply */
2118 nameserver_up(server
);
2120 nameserver_probe_failed(server
);
2123 if (server
->next
== server_head
)
2131 nameserver_send_probe(struct nameserver
*const ns
) {
2132 struct evdns_request
*req
;
2133 struct sockaddr_storage
*addr
;
2134 /* here we need to send a probe to a given nameserver */
2135 /* in the hope that it is up now. */
2137 /* We identify the nameserver by its address, in case it is removed before
2138 * our probe comes back. */
2139 addr
= mm_malloc(sizeof(struct sockaddr_storage
));
2140 memcpy(addr
, &ns
->address
, sizeof(struct sockaddr_storage
));
2142 log(EVDNS_LOG_DEBUG
, "Sending probe to %s", debug_ntop((struct sockaddr
*)&ns
->address
));
2144 req
= request_new(TYPE_A
, "www.google.com", DNS_QUERY_NO_SEARCH
, nameserver_probe_callback
, addr
);
2149 /* we force this into the inflight queue no matter what */
2150 request_trans_id_set(req
, transaction_id_pick());
2152 request_submit(req
);
2156 /* 0 didn't try to transmit anything */
2157 /* 1 tried to transmit something */
2159 evdns_transmit(void) {
2160 char did_try_to_transmit
= 0;
2163 struct evdns_request
*const started_at
= req_head
, *req
= req_head
;
2164 /* first transmit all the requests which are currently waiting */
2166 if (req
->transmit_me
) {
2167 did_try_to_transmit
= 1;
2168 evdns_request_transmit(req
);
2172 } while (req
!= started_at
);
2175 return did_try_to_transmit
;
2178 /* exported function */
2180 evdns_count_nameservers(void)
2182 const struct nameserver
*server
= server_head
;
2188 server
= server
->next
;
2189 } while (server
!= server_head
);
2193 /* exported function */
2195 evdns_clear_nameservers_and_suspend(void)
2197 struct nameserver
*server
= server_head
, *started_at
= server_head
;
2198 struct evdns_request
*req
= req_head
, *req_started_at
= req_head
;
2203 struct nameserver
*next
= server
->next
;
2204 (void) event_del(&server
->event
);
2205 CLEAR(&server
->event
);
2206 del_timeout_event(server
);
2207 CLEAR(&server
->timeout_event
);
2208 if (server
->socket
>= 0)
2209 CLOSE_SOCKET(server
->socket
);
2212 if (next
== started_at
)
2217 global_good_nameservers
= 0;
2220 struct evdns_request
*next
= req
->next
;
2221 req
->tx_count
= req
->reissue_count
= 0;
2223 /* ???? What to do about searches? */
2224 del_timeout_event(req
);
2225 CLEAR(&req
->timeout_event
);
2227 req
->transmit_me
= 0;
2229 global_requests_waiting
++;
2230 evdns_request_insert(req
, &req_waiting_head
);
2231 /* We want to insert these suspended elements at the front of
2232 * the waiting queue, since they were pending before any of
2233 * the waiting entries were added. This is a circular list,
2234 * so we can just shift the start back by one.*/
2235 req_waiting_head
= req_waiting_head
->prev
;
2237 if (next
== req_started_at
)
2242 global_requests_inflight
= 0;
2247 static struct sockaddr_storage global_bind_address
;
2248 static socklen_t global_bind_addrlen
= 0;
2249 static int global_bind_addr_is_set
= 0;
2251 evdns_set_default_outgoing_bind_address(const struct sockaddr
*addr
,
2254 memset(&global_bind_address
, 0, sizeof(global_bind_address
));
2256 assert(addrlen
<= (socklen_t
)sizeof(global_bind_address
));
2257 memcpy(&global_bind_address
, addr
, addrlen
);
2258 global_bind_addrlen
= addrlen
;
2259 global_bind_addr_is_set
= 1;
2261 global_bind_addr_is_set
= 0;
2265 /* exported function */
2269 evdns_requests_pump_waiting_queue();
2274 _evdns_nameserver_add_impl(const struct sockaddr
*address
,
2275 socklen_t addrlen
) {
2276 /* first check to see if we already have this nameserver */
2278 const struct nameserver
*server
= server_head
, *const started_at
= server_head
;
2279 struct nameserver
*ns
;
2284 if (sockaddr_eq(address
, (struct sockaddr
*)&server
->address
, 1)) {
2285 log(EVDNS_LOG_DEBUG
, "Duplicate nameserver.");
2288 server
= server
->next
;
2289 } while (server
!= started_at
);
2291 if (addrlen
> (int)sizeof(ns
->address
)) {
2292 log(EVDNS_LOG_DEBUG
, "Addrlen %d too long.", (int)addrlen
);
2296 ns
= (struct nameserver
*) mm_malloc(sizeof(struct nameserver
));
2299 memset(ns
, 0, sizeof(struct nameserver
));
2301 ns
->socket
= socket(PF_INET
, SOCK_DGRAM
, 0);
2302 if (ns
->socket
< 0) { err
= 1; goto out1
; }
2305 u_long nonblocking
= 1;
2306 ioctlsocket(ns
->socket
, FIONBIO
, &nonblocking
);
2309 fcntl(ns
->socket
, F_SETFL
, O_NONBLOCK
);
2312 if (global_bind_addr_is_set
) {
2313 if (bind(ns
->socket
, (struct sockaddr
*)&global_bind_address
,
2314 global_bind_addrlen
) < 0) {
2315 log(EVDNS_LOG_DEBUG
, "Couldn't bind to outgoing address.");
2321 if (connect(ns
->socket
, address
, addrlen
) != 0) {
2322 log(EVDNS_LOG_DEBUG
, "Couldn't open socket to nameserver.");
2327 memcpy(&ns
->address
, address
, addrlen
);
2329 event_set(&ns
->event
, ns
->socket
, EV_READ
| EV_PERSIST
, nameserver_ready_callback
, ns
);
2330 if (event_add(&ns
->event
, NULL
) < 0) {
2331 log(EVDNS_LOG_DEBUG
, "Couldn't add event for nameserver.");
2336 log(EVDNS_LOG_DEBUG
, "Added nameserver %s", debug_ntop(address
));
2338 /* insert this nameserver into the list of them */
2340 ns
->next
= ns
->prev
= ns
;
2343 ns
->next
= server_head
->next
;
2344 ns
->prev
= server_head
;
2345 server_head
->next
= ns
;
2346 if (server_head
->prev
== server_head
) {
2347 server_head
->prev
= ns
;
2351 global_good_nameservers
++;
2356 CLOSE_SOCKET(ns
->socket
);
2360 log(EVDNS_LOG_WARN
, "Unable to add nameserver %s: error %d", debug_ntop(address
), err
);
2364 /* exported function */
2366 evdns_nameserver_add(unsigned long int address
) {
2367 struct sockaddr_in sin
;
2368 memset(&sin
, 0, sizeof(sin
));
2369 sin
.sin_family
= AF_INET
;
2370 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2371 sin
.sin_len
= sizeof(sin
);
2373 sin
.sin_addr
.s_addr
= htonl(address
);
2375 return _evdns_nameserver_add_impl((struct sockaddr
*) &sin
, sizeof(sin
));
2378 /* exported function */
2380 evdns_nameserver_ip_add(const char *ip_as_string
) {
2383 const char *cp
, *addr_part
, *port_part
;
2385 /* recognized formats are:
2393 log(EVDNS_LOG_DEBUG
, "Trying to add nameserver <%s>", ip_as_string
);
2395 cp
= strchr(ip_as_string
, ':');
2396 if (*ip_as_string
== '[') {
2398 if (!(cp
= strchr(ip_as_string
, ']'))) {
2399 log(EVDNS_LOG_DEBUG
, "Nameserver missing closing ]");
2402 len
= cp
-(ip_as_string
+ 1);
2403 if (len
> (int)sizeof(buf
)-1) {
2404 log(EVDNS_LOG_DEBUG
, "[Nameserver] does not fit in buffer.");
2407 memcpy(buf
, ip_as_string
+1, len
);
2415 } else if (cp
&& strchr(cp
+1, ':')) {
2417 addr_part
= ip_as_string
;
2421 if (cp
- ip_as_string
> (int)sizeof(buf
)-1) {
2422 log(EVDNS_LOG_DEBUG
, "Nameserver does not fit in buffer.");
2425 memcpy(buf
, ip_as_string
, cp
-ip_as_string
);
2426 buf
[cp
-ip_as_string
] = '\0';
2430 addr_part
= ip_as_string
;
2435 if (port_part
== NULL
) {
2438 port
= strtoint(port_part
);
2439 if (port
<= 0 || port
> 65535) {
2440 log(EVDNS_LOG_DEBUG
, "Nameserver port <%s> out of range",
2446 /* Tor-only. needs a more general fix. */
2449 struct sockaddr_in6 sin6
;
2450 memset(&sin6
, 0, sizeof(sin6
));
2451 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2452 sin6
.sin6_len
= sizeof(sin6
);
2454 sin6
.sin6_family
= AF_INET6
;
2455 sin6
.sin6_port
= htons(port
);
2456 if (1 != tor_inet_pton(AF_INET6
, addr_part
, &sin6
.sin6_addr
)) {
2457 log(EVDNS_LOG_DEBUG
, "inet_pton(%s) failed", addr_part
);
2460 return _evdns_nameserver_add_impl((struct sockaddr
*)&sin6
,
2463 struct sockaddr_in sin
;
2464 memset(&sin
, 0, sizeof(sin
));
2465 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2466 sin
.sin_len
= sizeof(sin
);
2468 sin
.sin_family
= AF_INET
;
2469 sin
.sin_port
= htons(port
);
2470 if (!inet_aton(addr_part
, &sin
.sin_addr
)) {
2471 log(EVDNS_LOG_DEBUG
, "inet_pton(%s) failed", addr_part
);
2474 return _evdns_nameserver_add_impl((struct sockaddr
*)&sin
,
2480 evdns_nameserver_sockaddr_add(const struct sockaddr
*sa
, socklen_t len
)
2482 return _evdns_nameserver_add_impl(sa
, len
);
2485 /* insert into the tail of the queue */
2487 evdns_request_insert(struct evdns_request
*req
, struct evdns_request
**head
) {
2490 req
->next
= req
->prev
= req
;
2494 req
->prev
= (*head
)->prev
;
2495 req
->prev
->next
= req
;
2497 (*head
)->prev
= req
;
2501 string_num_dots(const char *s
) {
2503 while ((s
= strchr(s
, '.'))) {
2510 static struct evdns_request
*
2511 request_new(int type
, const char *name
, int flags
,
2512 evdns_callback_type callback
, void *user_ptr
) {
2513 const char issuing_now
=
2514 (global_requests_inflight
< global_max_requests_inflight
) ? 1 : 0;
2516 const size_t name_len
= strlen(name
);
2517 const size_t request_max_len
= evdns_request_len(name_len
);
2518 const u16 trans_id
= issuing_now
? transaction_id_pick() : 0xffff;
2519 /* the request data is alloced in a single block with the header */
2520 struct evdns_request
*const req
=
2521 (struct evdns_request
*) mm_malloc(sizeof(struct evdns_request
) + request_max_len
);
2526 if (!req
) return NULL
;
2528 if (name_len
>= sizeof(namebuf
)) {
2533 memset(req
, 0, sizeof(struct evdns_request
));
2535 if (global_randomize_case
) {
2538 strlcpy(namebuf
, name
, sizeof(namebuf
));
2539 rand_bytes_function(randbits
, (name_len
+7)/8);
2540 for (i
= 0; i
< name_len
; ++i
) {
2541 if (ISALPHA(namebuf
[i
])) {
2542 if ((randbits
[i
>> 3] & (1<<(i
%7))))
2543 namebuf
[i
] = TOLOWER(namebuf
[i
]);
2545 namebuf
[i
] = TOUPPER(namebuf
[i
]);
2551 /* request data lives just after the header */
2552 req
->request
= ((u8
*) req
) + sizeof(struct evdns_request
);
2553 /* denotes that the request data shouldn't be mm_free()ed */
2554 req
->request_appended
= 1;
2555 rlen
= evdns_request_data_build(name
, name_len
, trans_id
,
2556 type
, CLASS_INET
, req
->request
, request_max_len
);
2559 req
->request_len
= rlen
;
2560 req
->trans_id
= trans_id
;
2562 req
->request_type
= type
;
2563 req
->user_pointer
= user_ptr
;
2564 req
->user_callback
= callback
;
2565 req
->ns
= issuing_now
? nameserver_pick() : NULL
;
2566 req
->next
= req
->prev
= NULL
;
2576 request_submit(struct evdns_request
*const req
) {
2578 /* if it has a nameserver assigned then this is going */
2579 /* straight into the inflight queue */
2580 evdns_request_insert(req
, &req_head
);
2581 global_requests_inflight
++;
2582 evdns_request_transmit(req
);
2584 evdns_request_insert(req
, &req_waiting_head
);
2585 global_requests_waiting
++;
2589 /* exported function */
2590 int evdns_resolve_ipv4(const char *name
, int flags
,
2591 evdns_callback_type callback
, void *ptr
) {
2592 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2593 if (flags
& DNS_QUERY_NO_SEARCH
) {
2594 struct evdns_request
*const req
=
2595 request_new(TYPE_A
, name
, flags
, callback
, ptr
);
2598 request_submit(req
);
2601 return (search_request_new(TYPE_A
, name
, flags
, callback
, ptr
));
2605 /* exported function */
2606 int evdns_resolve_ipv6(const char *name
, int flags
,
2607 evdns_callback_type callback
, void *ptr
) {
2608 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s", name
);
2609 if (flags
& DNS_QUERY_NO_SEARCH
) {
2610 struct evdns_request
*const req
=
2611 request_new(TYPE_AAAA
, name
, flags
, callback
, ptr
);
2614 request_submit(req
);
2617 return (search_request_new(TYPE_AAAA
, name
, flags
, callback
, ptr
));
2621 int evdns_resolve_reverse(const struct in_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2623 struct evdns_request
*req
;
2626 a
= ntohl(in
->s_addr
);
2627 snprintf(buf
, sizeof(buf
), "%d.%d.%d.%d.in-addr.arpa",
2628 (int)(u8
)((a
)&0xff),
2629 (int)(u8
)((a
>>8 )&0xff),
2630 (int)(u8
)((a
>>16)&0xff),
2631 (int)(u8
)((a
>>24)&0xff));
2632 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2633 req
= request_new(TYPE_PTR
, buf
, flags
, callback
, ptr
);
2635 request_submit(req
);
2639 int evdns_resolve_reverse_ipv6(const struct in6_addr
*in
, int flags
, evdns_callback_type callback
, void *ptr
) {
2640 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2643 struct evdns_request
*req
;
2647 for (i
=15; i
>= 0; --i
) {
2648 u8 byte
= in
->s6_addr
[i
];
2649 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
2651 *cp
++ = "0123456789abcdef"[byte
>> 4];
2654 assert(cp
+ strlen("ip6.arpa") < buf
+sizeof(buf
));
2655 memcpy(cp
, "ip6.arpa", strlen("ip6.arpa")+1);
2656 log(EVDNS_LOG_DEBUG
, "Resolve requested for %s (reverse)", buf
);
2657 req
= request_new(TYPE_PTR
, buf
, flags
, callback
, ptr
);
2659 request_submit(req
);
2663 /*/////////////////////////////////////////////////////////////////// */
2664 /* Search support */
2666 /* the libc resolver has support for searching a number of domains */
2667 /* to find a name. If nothing else then it takes the single domain */
2668 /* from the gethostname() call. */
2670 /* It can also be configured via the domain and search options in a */
2673 /* The ndots option controls how many dots it takes for the resolver */
2674 /* to decide that a name is non-local and so try a raw lookup first. */
2676 struct search_domain
{
2678 struct search_domain
*next
;
2679 /* the text string is appended to this structure */
2682 struct search_state
{
2686 struct search_domain
*head
;
2689 static struct search_state
*global_search_state
= NULL
;
2692 search_state_decref(struct search_state
*const state
) {
2695 if (!state
->refcount
) {
2696 struct search_domain
*next
, *dom
;
2697 for (dom
= state
->head
; dom
; dom
= next
) {
2707 static struct search_state
*
2708 search_state_new(void) {
2709 struct search_state
*state
= (struct search_state
*) mm_malloc(sizeof(struct search_state
));
2710 if (!state
) return NULL
;
2711 memset(state
, 0, sizeof(struct search_state
));
2712 state
->refcount
= 1;
2719 search_postfix_clear(void) {
2720 search_state_decref(global_search_state
);
2722 global_search_state
= search_state_new();
2725 /* exported function */
2727 evdns_search_clear(void) {
2728 search_postfix_clear();
2732 search_postfix_add(const char *domain
) {
2734 struct search_domain
*sdomain
;
2735 while (domain
[0] == '.') domain
++;
2736 domain_len
= strlen(domain
);
2738 if (!global_search_state
) global_search_state
= search_state_new();
2739 if (!global_search_state
) return;
2740 global_search_state
->num_domains
++;
2742 sdomain
= (struct search_domain
*) mm_malloc(sizeof(struct search_domain
) + domain_len
);
2743 if (!sdomain
) return;
2744 memcpy( ((u8
*) sdomain
) + sizeof(struct search_domain
), domain
, domain_len
);
2745 sdomain
->next
= global_search_state
->head
;
2746 sdomain
->len
= domain_len
;
2748 global_search_state
->head
= sdomain
;
2751 /* reverse the order of members in the postfix list. This is needed because, */
2752 /* when parsing resolv.conf we push elements in the wrong order */
2754 search_reverse(void) {
2755 struct search_domain
*cur
, *prev
= NULL
, *next
;
2756 cur
= global_search_state
->head
;
2764 global_search_state
->head
= prev
;
2767 /* exported function */
2769 evdns_search_add(const char *domain
) {
2770 search_postfix_add(domain
);
2773 /* exported function */
2775 evdns_search_ndots_set(const int ndots
) {
2776 if (!global_search_state
) global_search_state
= search_state_new();
2777 if (!global_search_state
) return;
2778 global_search_state
->ndots
= ndots
;
2782 search_set_from_hostname(void) {
2783 char hostname
[HOST_NAME_MAX
+ 1], *domainname
;
2785 search_postfix_clear();
2786 if (gethostname(hostname
, sizeof(hostname
))) return;
2787 domainname
= strchr(hostname
, '.');
2788 if (!domainname
) return;
2789 search_postfix_add(domainname
);
2792 /* warning: returns malloced string */
2794 search_make_new(const struct search_state
*const state
, int n
, const char *const base_name
) {
2795 const size_t base_len
= strlen(base_name
);
2796 const char need_to_append_dot
= base_name
[base_len
- 1] == '.' ? 0 : 1;
2797 struct search_domain
*dom
;
2799 for (dom
= state
->head
; dom
; dom
= dom
->next
) {
2801 /* this is the postfix we want */
2802 /* the actual postfix string is kept at the end of the structure */
2803 const u8
*const postfix
= ((u8
*) dom
) + sizeof(struct search_domain
);
2804 const size_t postfix_len
= dom
->len
;
2805 char *const newname
= (char *) mm_malloc(base_len
+ need_to_append_dot
+ postfix_len
+ 1);
2806 if (!newname
) return NULL
;
2807 memcpy(newname
, base_name
, base_len
);
2808 if (need_to_append_dot
) newname
[base_len
] = '.';
2809 memcpy(newname
+ base_len
+ need_to_append_dot
, postfix
, postfix_len
);
2810 newname
[base_len
+ need_to_append_dot
+ postfix_len
] = 0;
2815 /* we ran off the end of the list and still didn't find the requested string */
2817 return NULL
; /* unreachable; stops warnings in some compilers. */
2821 search_request_new(int type
, const char *const name
, int flags
, evdns_callback_type user_callback
, void *user_arg
) {
2822 assert(type
== TYPE_A
|| type
== TYPE_AAAA
);
2823 if ( ((flags
& DNS_QUERY_NO_SEARCH
) == 0) &&
2824 global_search_state
&&
2825 global_search_state
->num_domains
) {
2826 /* we have some domains to search */
2827 struct evdns_request
*req
;
2828 if (string_num_dots(name
) >= global_search_state
->ndots
) {
2829 req
= request_new(type
, name
, flags
, user_callback
, user_arg
);
2831 req
->search_index
= -1;
2833 char *const new_name
= search_make_new(global_search_state
, 0, name
);
2834 if (!new_name
) return 1;
2835 req
= request_new(type
, new_name
, flags
, user_callback
, user_arg
);
2838 req
->search_index
= 0;
2840 req
->search_origname
= mm_strdup(name
);
2841 req
->search_state
= global_search_state
;
2842 req
->search_flags
= flags
;
2843 global_search_state
->refcount
++;
2844 request_submit(req
);
2847 struct evdns_request
*const req
= request_new(type
, name
, flags
, user_callback
, user_arg
);
2849 request_submit(req
);
2854 /* this is called when a request has failed to find a name. We need to check */
2855 /* if it is part of a search and, if so, try the next name in the list */
2857 /* 0 another request has been submitted */
2858 /* 1 no more requests needed */
2860 search_try_next(struct evdns_request
*const req
) {
2861 if (req
->search_state
) {
2862 /* it is part of a search */
2864 struct evdns_request
*newreq
;
2865 req
->search_index
++;
2866 if (req
->search_index
>= req
->search_state
->num_domains
) {
2867 /* no more postfixes to try, however we may need to try */
2868 /* this name without a postfix */
2869 if (string_num_dots(req
->search_origname
) < req
->search_state
->ndots
) {
2870 /* yep, we need to try it raw */
2871 struct evdns_request
*const newreq
= request_new(req
->request_type
, req
->search_origname
, req
->search_flags
, req
->user_callback
, req
->user_pointer
);
2872 log(EVDNS_LOG_DEBUG
, "Search: trying raw query %s", req
->search_origname
);
2874 request_submit(newreq
);
2881 new_name
= search_make_new(req
->search_state
, req
->search_index
, req
->search_origname
);
2882 if (!new_name
) return 1;
2883 log(EVDNS_LOG_DEBUG
, "Search: now trying %s (%d)", new_name
, req
->search_index
);
2884 newreq
= request_new(req
->request_type
, new_name
, req
->search_flags
, req
->user_callback
, req
->user_pointer
);
2886 if (!newreq
) return 1;
2887 newreq
->search_origname
= req
->search_origname
;
2888 req
->search_origname
= NULL
;
2889 newreq
->search_state
= req
->search_state
;
2890 newreq
->search_flags
= req
->search_flags
;
2891 newreq
->search_index
= req
->search_index
;
2892 newreq
->search_state
->refcount
++;
2893 request_submit(newreq
);
2900 search_request_finished(struct evdns_request
*const req
) {
2901 if (req
->search_state
) {
2902 search_state_decref(req
->search_state
);
2903 req
->search_state
= NULL
;
2905 if (req
->search_origname
) {
2906 mm_free(req
->search_origname
);
2907 req
->search_origname
= NULL
;
2911 /*/////////////////////////////////////////////////////////////////// */
2912 /* Parsing resolv.conf files */
2915 evdns_resolv_set_defaults(int flags
) {
2916 /* if the file isn't found then we assume a local resolver */
2917 if (flags
& DNS_OPTION_SEARCH
) search_set_from_hostname();
2918 if (flags
& DNS_OPTION_NAMESERVERS
) evdns_nameserver_ip_add("127.0.0.1");
2921 #ifndef HAVE_STRTOK_R
2923 strtok_r(char *s
, const char *delim
, char **state
) {
2925 return strtok(s
, delim
);
2929 /* helper version of atoi which returns -1 on error */
2931 strtoint(const char *const str
) {
2933 const long r
= strtol(str
, &endptr
, 10);
2934 if (*endptr
|| r
> INT_MAX
) return -1;
2938 /* helper version of atoi that returns -1 on error and clips to bounds. */
2940 strtoint_clipped(const char *const str
, int min
, int max
)
2942 int r
= strtoint(str
);
2953 /* exported function */
2955 evdns_set_option(const char *option
, const char *val
, int flags
)
2957 if (!strncmp(option
, "ndots:", 6)) {
2958 const int ndots
= strtoint(val
);
2959 if (ndots
== -1) return -1;
2960 if (!(flags
& DNS_OPTION_SEARCH
)) return 0;
2961 log(EVDNS_LOG_DEBUG
, "Setting ndots to %d", ndots
);
2962 if (!global_search_state
) global_search_state
= search_state_new();
2963 if (!global_search_state
) return -1;
2964 global_search_state
->ndots
= ndots
;
2965 } else if (!strncmp(option
, "timeout:", 8)) {
2966 const int timeout
= strtoint(val
);
2967 if (timeout
== -1) return -1;
2968 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2969 log(EVDNS_LOG_DEBUG
, "Setting timeout to %d", timeout
);
2970 global_timeout
.tv_sec
= timeout
;
2971 } else if (!strncmp(option
, "max-timeouts:", 12)) {
2972 const int maxtimeout
= strtoint_clipped(val
, 1, 255);
2973 if (maxtimeout
== -1) return -1;
2974 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2975 log(EVDNS_LOG_DEBUG
, "Setting maximum allowed timeouts to %d",
2977 global_max_nameserver_timeout
= maxtimeout
;
2978 } else if (!strncmp(option
, "max-inflight:", 13)) {
2979 const int maxinflight
= strtoint_clipped(val
, 1, 65000);
2980 if (maxinflight
== -1) return -1;
2981 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2982 log(EVDNS_LOG_DEBUG
, "Setting maximum inflight requests to %d",
2984 global_max_requests_inflight
= maxinflight
;
2985 } else if (!strncmp(option
, "attempts:", 9)) {
2986 int retries
= strtoint(val
);
2987 if (retries
== -1) return -1;
2988 if (retries
> 255) retries
= 255;
2989 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2990 log(EVDNS_LOG_DEBUG
, "Setting retries to %d", retries
);
2991 global_max_retransmits
= retries
;
2992 } else if (!strncmp(option
, "randomize-case:", 15)) {
2993 int randcase
= strtoint(val
);
2994 if (!(flags
& DNS_OPTION_MISC
)) return 0;
2995 log(EVDNS_LOG_DEBUG
, "Setting randomize_case to %d", randcase
);
2996 global_randomize_case
= randcase
;
3002 resolv_conf_parse_line(char *const start
, int flags
) {
3004 static const char *const delims
= " \t";
3005 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3007 char *const first_token
= strtok_r(start
, delims
, &strtok_state
);
3008 if (!first_token
) return;
3010 if (!strcmp(first_token
, "nameserver") && (flags
& DNS_OPTION_NAMESERVERS
)) {
3011 const char *const nameserver
= NEXT_TOKEN
;
3012 evdns_nameserver_ip_add(nameserver
);
3013 } else if (!strcmp(first_token
, "domain") && (flags
& DNS_OPTION_SEARCH
)) {
3014 const char *const domain
= NEXT_TOKEN
;
3016 search_postfix_clear();
3017 search_postfix_add(domain
);
3019 } else if (!strcmp(first_token
, "search") && (flags
& DNS_OPTION_SEARCH
)) {
3021 search_postfix_clear();
3023 while ((domain
= NEXT_TOKEN
)) {
3024 search_postfix_add(domain
);
3027 } else if (!strcmp(first_token
, "options")) {
3029 while ((option
= NEXT_TOKEN
)) {
3030 const char *val
= strchr(option
, ':');
3031 evdns_set_option(option
, val
? val
+1 : "", flags
);
3037 /* exported function */
3040 /* 1 failed to open file */
3041 /* 2 failed to stat file */
3042 /* 3 file too large */
3043 /* 4 out of memory */
3044 /* 5 short read from file */
3046 evdns_resolv_conf_parse(int flags
, const char *const filename
) {
3053 log(EVDNS_LOG_DEBUG
, "Parsing resolv.conf file %s", filename
);
3055 fd
= open(filename
, O_RDONLY
);
3057 evdns_resolv_set_defaults(flags
);
3061 if (fstat(fd
, &st
)) { err
= 2; goto out1
; }
3063 evdns_resolv_set_defaults(flags
);
3064 err
= (flags
& DNS_OPTION_NAMESERVERS
) ? 6 : 0;
3067 if (st
.st_size
> 65535) { err
= 3; goto out1
; } /* no resolv.conf should be any bigger */
3069 resolv
= (u8
*) mm_malloc((size_t)st
.st_size
+ 1);
3070 if (!resolv
) { err
= 4; goto out1
; }
3073 while ((r
= (int)read(fd
, resolv
+n
, (size_t)st
.st_size
-n
)) > 0) {
3075 if (n
== st
.st_size
)
3077 assert(n
< st
.st_size
);
3079 if (r
< 0) { err
= 5; goto out2
; }
3080 resolv
[n
] = 0; /* we malloced an extra byte; this should be fine. */
3082 start
= (char *) resolv
;
3084 char *const newline
= strchr(start
, '\n');
3086 resolv_conf_parse_line(start
, flags
);
3090 resolv_conf_parse_line(start
, flags
);
3091 start
= newline
+ 1;
3095 if (!server_head
&& (flags
& DNS_OPTION_NAMESERVERS
)) {
3096 /* no nameservers were configured. */
3097 evdns_nameserver_ip_add("127.0.0.1");
3100 if (flags
& DNS_OPTION_SEARCH
&& (!global_search_state
|| global_search_state
->num_domains
== 0)) {
3101 search_set_from_hostname();
3112 /* Add multiple nameservers from a space-or-comma-separated list. */
3114 evdns_nameserver_ip_add_line(const char *ips
) {
3119 while (ISSPACE(*ips
) || *ips
== ',' || *ips
== '\t')
3122 while (ISDIGIT(*ips
) || *ips
== '.' || *ips
== ':' || *ips
== '[' || *ips
== ']')
3124 buf
= mm_malloc(ips
-addr
+1);
3126 memcpy(buf
, addr
, ips
-addr
);
3127 buf
[ips
-addr
] = '\0';
3128 r
= evdns_nameserver_ip_add(buf
);
3135 typedef DWORD(WINAPI
*GetNetworkParams_fn_t
)(FIXED_INFO
*, DWORD
*);
3137 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3138 /* figure out what our nameservers are. */
3140 load_nameservers_with_getnetworkparams(void)
3142 /* Based on MSDN examples and inspection of c-ares code. */
3145 ULONG size
= sizeof(FIXED_INFO
);
3147 int status
= 0, r
, added_any
;
3149 GetNetworkParams_fn_t fn
;
3151 /* XXXX Possibly, we should hardcode the location of this DLL. */
3152 if (!(handle
= LoadLibrary("iphlpapi.dll"))) {
3153 log(EVDNS_LOG_WARN
, "Could not open iphlpapi.dll");
3154 /* right now status = 0, doesn't that mean "good" - mikec */
3158 if (!(fn
= (GetNetworkParams_fn_t
) GetProcAddress(handle
, "GetNetworkParams"))) {
3159 log(EVDNS_LOG_WARN
, "Could not get address of function.");
3165 buf
= mm_malloc(size
);
3166 if (!buf
) { status
= 4; goto done
; }
3168 r
= fn(fixed
, &size
);
3169 if (r
!= ERROR_SUCCESS
&& r
!= ERROR_BUFFER_OVERFLOW
) {
3173 if (r
!= ERROR_SUCCESS
) {
3175 buf
= mm_malloc(size
);
3176 if (!buf
) { status
= 4; goto done
; }
3178 r
= fn(fixed
, &size
);
3179 if (r
!= ERROR_SUCCESS
) {
3180 log(EVDNS_LOG_DEBUG
, "fn() failed.");
3188 ns
= &(fixed
->DnsServerList
);
3190 r
= evdns_nameserver_ip_add_line(ns
->IpAddress
.String
);
3192 log(EVDNS_LOG_DEBUG
,"Could not add nameserver %s to list, "
3193 "error: %d; status: %d",
3194 (ns
->IpAddress
.String
),(int)GetLastError(), r
);
3197 log(EVDNS_LOG_DEBUG
,"Successfully added %s as nameserver",ns
->IpAddress
.String
);
3205 log(EVDNS_LOG_DEBUG
, "No nameservers added.");
3216 FreeLibrary(handle
);
3221 config_nameserver_from_reg_key(HKEY key
, const char *subkey
)
3224 DWORD bufsz
= 0, type
= 0;
3227 if (RegQueryValueEx(key
, subkey
, 0, &type
, NULL
, &bufsz
)
3230 if (!(buf
= mm_malloc(bufsz
)))
3233 if (RegQueryValueEx(key
, subkey
, 0, &type
, (LPBYTE
)buf
, &bufsz
)
3234 == ERROR_SUCCESS
&& bufsz
> 1) {
3235 status
= evdns_nameserver_ip_add_line(buf
);
3242 #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
3243 #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
3244 #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
3247 load_nameservers_from_registry(void)
3251 #define TRY(k, name) \
3252 if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
3253 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3255 } else if (!found) { \
3256 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3260 if (((int)GetVersion()) > 0) { /* NT */
3261 HKEY nt_key
= 0, interfaces_key
= 0;
3263 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_NT_KEY
, 0,
3264 KEY_READ
, &nt_key
) != ERROR_SUCCESS
) {
3265 log(EVDNS_LOG_DEBUG
,"Couldn't open nt key, %d",(int)GetLastError());
3268 r
= RegOpenKeyEx(nt_key
, "Interfaces", 0,
3269 KEY_QUERY_VALUE
|KEY_ENUMERATE_SUB_KEYS
,
3271 if (r
!= ERROR_SUCCESS
) {
3272 log(EVDNS_LOG_DEBUG
,"Couldn't open interfaces key, %d",(int)GetLastError());
3275 TRY(nt_key
, "NameServer");
3276 TRY(nt_key
, "DhcpNameServer");
3277 TRY(interfaces_key
, "NameServer");
3278 TRY(interfaces_key
, "DhcpNameServer");
3279 RegCloseKey(interfaces_key
);
3280 RegCloseKey(nt_key
);
3283 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE
, WIN_NS_9X_KEY
, 0,
3284 KEY_READ
, &win_key
) != ERROR_SUCCESS
) {
3285 log(EVDNS_LOG_DEBUG
, "Couldn't open registry key, %d", (int)GetLastError());
3288 TRY(win_key
, "NameServer");
3289 RegCloseKey(win_key
);
3293 log(EVDNS_LOG_WARN
,"Didn't find any nameservers.");
3296 return found
? 0 : -1;
3301 evdns_config_windows_nameservers(void)
3303 if (load_nameservers_with_getnetworkparams() == 0)
3305 return load_nameservers_from_registry();
3314 evdns_config_windows_nameservers();
3316 res
= evdns_resolv_conf_parse(DNS_OPTIONS_ALL
, "/etc/resolv.conf");
3323 evdns_err_to_string(int err
)
3326 case DNS_ERR_NONE
: return "no error";
3327 case DNS_ERR_FORMAT
: return "misformatted query";
3328 case DNS_ERR_SERVERFAILED
: return "server failed";
3329 case DNS_ERR_NOTEXIST
: return "name does not exist";
3330 case DNS_ERR_NOTIMPL
: return "query not implemented";
3331 case DNS_ERR_REFUSED
: return "refused";
3333 case DNS_ERR_TRUNCATED
: return "reply truncated or ill-formed";
3334 case DNS_ERR_UNKNOWN
: return "unknown";
3335 case DNS_ERR_TIMEOUT
: return "request timed out";
3336 case DNS_ERR_SHUTDOWN
: return "dns subsystem shut down";
3337 default: return "[Unknown error code]";
3342 evdns_shutdown(int fail_requests
)
3344 struct nameserver
*server
, *server_next
;
3345 struct search_domain
*dom
, *dom_next
;
3349 reply_callback(req_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
3350 request_finished(req_head
, &req_head
);
3352 while (req_waiting_head
) {
3354 reply_callback(req_waiting_head
, 0, DNS_ERR_SHUTDOWN
, NULL
);
3355 request_finished(req_waiting_head
, &req_waiting_head
);
3357 global_requests_inflight
= global_requests_waiting
= 0;
3359 for (server
= server_head
; server
; server
= server_next
) {
3360 server_next
= server
->next
;
3361 if (server
->socket
>= 0)
3362 CLOSE_SOCKET(server
->socket
);
3363 (void) event_del(&server
->event
);
3364 if (server
->state
== 0)
3365 del_timeout_event(server
);
3368 if (server_next
== server_head
)
3372 global_good_nameservers
= 0;
3374 if (global_search_state
) {
3375 for (dom
= global_search_state
->head
; dom
; dom
= dom_next
) {
3376 dom_next
= dom
->next
;
3380 CLEAR(global_search_state
);
3381 mm_free(global_search_state
);
3382 global_search_state
= NULL
;
3384 evdns_log_fn
= NULL
;
3389 main_callback(int result
, char type
, int count
, int ttl
,
3390 void *addrs
, void *orig
) {
3391 char *n
= (char*)orig
;
3393 for (i
= 0; i
< count
; ++i
) {
3394 if (type
== DNS_IPv4_A
) {
3395 printf("%s: %s\n", n
, debug_ntoa(((u32
*)addrs
)[i
]));
3396 } else if (type
== DNS_PTR
) {
3397 printf("%s: %s\n", n
, ((char**)addrs
)[i
]);
3401 printf("%s: No answer (%d)\n", n
, result
);
3406 evdns_server_callback(struct evdns_server_request
*req
, void *data
)
3410 /* dummy; give 192.168.11.11 as an answer for all A questions,
3411 * give foo.bar.example.com as an answer for all PTR questions. */
3412 for (i
= 0; i
< req
->nquestions
; ++i
) {
3413 u32 ans
= htonl(0xc0a80b0bUL
);
3414 if (req
->questions
[i
]->type
== EVDNS_TYPE_A
&&
3415 req
->questions
[i
]->dns_question_class
== EVDNS_CLASS_INET
) {
3416 printf(" -- replying for %s (A)\n", req
->questions
[i
]->name
);
3417 r
= evdns_server_request_add_a_reply(req
, req
->questions
[i
]->name
,
3420 printf("eeep, didn't work.\n");
3421 } else if (req
->questions
[i
]->type
== EVDNS_TYPE_PTR
&&
3422 req
->questions
[i
]->dns_question_class
== EVDNS_CLASS_INET
) {
3423 printf(" -- replying for %s (PTR)\n", req
->questions
[i
]->name
);
3424 r
= evdns_server_request_add_ptr_reply(req
, NULL
, req
->questions
[i
]->name
,
3425 "foo.bar.example.com", 10);
3427 printf(" -- skipping %s [%d %d]\n", req
->questions
[i
]->name
,
3428 req
->questions
[i
]->type
, req
->questions
[i
]->dns_question_class
);
3432 r
= evdns_server_request_respond(req
, 0);
3434 printf("eeek, couldn't send reply.\n");
3438 logfn(int is_warn
, const char *msg
) {
3440 fprintf(stderr
, "%s\n", msg
);
3443 main(int c
, char **v
) {
3445 int reverse
= 0, verbose
= 1, servertest
= 0;
3447 fprintf(stderr
, "syntax: %s [-x] [-v] hostname\n", v
[0]);
3448 fprintf(stderr
, "syntax: %s [-servertest]\n", v
[0]);
3452 while (idx
< c
&& v
[idx
][0] == '-') {
3453 if (!strcmp(v
[idx
], "-x"))
3455 else if (!strcmp(v
[idx
], "-v"))
3457 else if (!strcmp(v
[idx
], "-servertest"))
3460 fprintf(stderr
, "Unknown option %s\n", v
[idx
]);
3465 evdns_set_log_fn(logfn
);
3466 evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS
, "/etc/resolv.conf");
3469 struct sockaddr_in my_addr
;
3470 sock
= socket(PF_INET
, SOCK_DGRAM
, 0);
3471 fcntl(sock
, F_SETFL
, O_NONBLOCK
);
3472 my_addr
.sin_family
= AF_INET
;
3473 my_addr
.sin_port
= htons(10053);
3474 my_addr
.sin_addr
.s_addr
= INADDR_ANY
;
3475 if (bind(sock
, (struct sockaddr
*)&my_addr
, sizeof(my_addr
))<0) {
3479 evdns_add_server_port(sock
, 0, evdns_server_callback
, NULL
);
3481 for (; idx
< c
; ++idx
) {
3483 struct in_addr addr
;
3484 if (!inet_aton(v
[idx
], &addr
)) {
3485 fprintf(stderr
, "Skipping non-IP %s\n", v
[idx
]);
3488 fprintf(stderr
, "resolving %s...\n",v
[idx
]);
3489 evdns_resolve_reverse(&addr
, 0, main_callback
, v
[idx
]);
3491 fprintf(stderr
, "resolving (fwd) %s...\n",v
[idx
]);
3492 evdns_resolve_ipv4(v
[idx
], 0, main_callback
, v
[idx
]);
3501 /* Local Variables: */
3503 /* c-basic-offset: 4 */
3504 /* indent-tabs-mode: t */