kernel - VM PAGER part 2/2 - Expand vinitvmio() and vnode_pager_alloc()
[dragonfly.git] / contrib / libevent / evdns.c
bloba052668d67981960025ee5ac09cd60ea39f5e8d5
1 /* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */
3 /* The original version of this module was written by Adam Langley; for
4 * a history of modifications, check out the subversion logs.
6 * When editing this module, try to keep it re-mergeable by Adam. Don't
7 * reformat the whitespace, add Tor dependencies, or so on.
9 * TODO:
10 * - Support IPv6 and PTR records.
11 * - Replace all externally visible magic numbers with #defined constants.
12 * - Write doccumentation for APIs of all external functions.
15 /* Async DNS Library
16 * Adam Langley <agl@imperialviolet.org>
17 * http://www.imperialviolet.org/eventdns.html
18 * Public Domain code
20 * This software is Public Domain. To view a copy of the public domain dedication,
21 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
22 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
24 * I ask and expect, but do not require, that all derivative works contain an
25 * attribution similar to:
26 * Parts developed by Adam Langley <agl@imperialviolet.org>
28 * You may wish to replace the word "Parts" with something else depending on
29 * the amount of original code.
31 * (Derivative works does not include programs which link against, run or include
32 * the source verbatim in their source distributions)
34 * Version: 0.1b
37 #include <sys/types.h>
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
42 #ifdef WIN32
43 #include "misc.h"
44 #endif
46 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
47 #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
48 #ifndef DNS_USE_OPENSSL_FOR_ID
49 #error Must configure at least one id generation method.
50 #error Please see the documentation.
51 #endif
52 #endif
53 #endif
55 /* #define _POSIX_C_SOURCE 200507 */
56 #define _GNU_SOURCE
58 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
59 #ifdef DNS_USE_OPENSSL_FOR_ID
60 #error Multiple id options selected
61 #endif
62 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
63 #error Multiple id options selected
64 #endif
65 #include <time.h>
66 #endif
68 #ifdef DNS_USE_OPENSSL_FOR_ID
69 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
70 #error Multiple id options selected
71 #endif
72 #include <openssl/rand.h>
73 #endif
75 #define _FORTIFY_SOURCE 3
77 #include <string.h>
78 #include <fcntl.h>
79 #include <sys/time.h>
80 #ifdef HAVE_STDINT_H
81 #include <stdint.h>
82 #endif
83 #include <stdlib.h>
84 #include <string.h>
85 #include <errno.h>
86 #include <assert.h>
87 #include <unistd.h>
88 #include <limits.h>
89 #include <sys/stat.h>
90 #include <ctype.h>
91 #include <stdio.h>
92 #include <stdarg.h>
94 #include "evdns.h"
95 #include "log.h"
96 #ifdef WIN32
97 #include <windows.h>
98 #include <winsock2.h>
99 #include <iphlpapi.h>
100 #else
101 #include <sys/socket.h>
102 #include <netinet/in.h>
103 #include <arpa/inet.h>
104 #endif
106 #ifdef HAVE_NETINET_IN6_H
107 #include <netinet/in6.h>
108 #endif
110 #ifdef WIN32
111 typedef int socklen_t;
112 #endif
114 #define EVDNS_LOG_DEBUG 0
115 #define EVDNS_LOG_WARN 1
117 #ifndef HOST_NAME_MAX
118 #define HOST_NAME_MAX 255
119 #endif
121 #include <stdio.h>
123 #undef MIN
124 #define MIN(a,b) ((a)<(b)?(a):(b))
126 #ifdef __USE_ISOC99B
127 /* libevent doesn't work without this */
128 typedef uint8_t u_char;
129 typedef unsigned int uint;
130 #endif
131 #include <event.h>
133 #define u64 uint64_t
134 #define u32 uint32_t
135 #define u16 uint16_t
136 #define u8 uint8_t
138 #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
139 /* which we bother recording */
141 #define TYPE_A EVDNS_TYPE_A
142 #define TYPE_CNAME 5
143 #define TYPE_PTR EVDNS_TYPE_PTR
144 #define TYPE_AAAA EVDNS_TYPE_AAAA
146 #define CLASS_INET EVDNS_CLASS_INET
148 struct request {
149 u8 *request; /* the dns packet data */
150 unsigned int request_len;
151 int reissue_count;
152 int tx_count; /* the number of times that this packet has been sent */
153 unsigned int request_type; /* TYPE_PTR or TYPE_A */
154 void *user_pointer; /* the pointer given to us for this request */
155 evdns_callback_type user_callback;
156 struct nameserver *ns; /* the server which we last sent it */
158 /* elements used by the searching code */
159 int search_index;
160 struct search_state *search_state;
161 char *search_origname; /* needs to be free()ed */
162 int search_flags;
164 /* these objects are kept in a circular list */
165 struct request *next, *prev;
167 struct event timeout_event;
169 u16 trans_id; /* the transaction id */
170 char request_appended; /* true if the request pointer is data which follows this struct */
171 char transmit_me; /* needs to be transmitted */
174 #ifndef HAVE_STRUCT_IN6_ADDR
175 struct in6_addr {
176 u8 s6_addr[16];
178 #endif
180 struct reply {
181 unsigned int type;
182 unsigned int have_answer;
183 union {
184 struct {
185 u32 addrcount;
186 u32 addresses[MAX_ADDRS];
187 } a;
188 struct {
189 u32 addrcount;
190 struct in6_addr addresses[MAX_ADDRS];
191 } aaaa;
192 struct {
193 char name[HOST_NAME_MAX];
194 } ptr;
195 } data;
198 struct nameserver {
199 int socket; /* a connected UDP socket */
200 u32 address;
201 int failed_times; /* number of times which we have given this server a chance */
202 int timedout; /* number of times in a row a request has timed out */
203 struct event event;
204 /* these objects are kept in a circular list */
205 struct nameserver *next, *prev;
206 struct event timeout_event; /* used to keep the timeout for */
207 /* when we next probe this server. */
208 /* Valid if state == 0 */
209 char state; /* zero if we think that this server is down */
210 char choked; /* true if we have an EAGAIN from this server's socket */
211 char write_waiting; /* true if we are waiting for EV_WRITE events */
214 static struct request *req_head = NULL, *req_waiting_head = NULL;
215 static struct nameserver *server_head = NULL;
217 /* Represents a local port where we're listening for DNS requests. Right now, */
218 /* only UDP is supported. */
219 struct evdns_server_port {
220 int socket; /* socket we use to read queries and write replies. */
221 int refcnt; /* reference count. */
222 char choked; /* Are we currently blocked from writing? */
223 char closing; /* Are we trying to close this port, pending writes? */
224 evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
225 void *user_data; /* Opaque pointer passed to user_callback */
226 struct event event; /* Read/write event */
227 /* circular list of replies that we want to write. */
228 struct server_request *pending_replies;
231 /* Represents part of a reply being built. (That is, a single RR.) */
232 struct server_reply_item {
233 struct server_reply_item *next; /* next item in sequence. */
234 char *name; /* name part of the RR */
235 u16 type : 16; /* The RR type */
236 u16 class : 16; /* The RR class (usually CLASS_INET) */
237 u32 ttl; /* The RR TTL */
238 char is_name; /* True iff data is a label */
239 u16 datalen; /* Length of data; -1 if data is a label */
240 void *data; /* The contents of the RR */
243 /* Represents a request that we've received as a DNS server, and holds */
244 /* the components of the reply as we're constructing it. */
245 struct server_request {
246 /* Pointers to the next and previous entries on the list of replies */
247 /* that we're waiting to write. Only set if we have tried to respond */
248 /* and gotten EAGAIN. */
249 struct server_request *next_pending;
250 struct server_request *prev_pending;
252 u16 trans_id; /* Transaction id. */
253 struct evdns_server_port *port; /* Which port received this request on? */
254 struct sockaddr_storage addr; /* Where to send the response */
255 socklen_t addrlen; /* length of addr */
257 int n_answer; /* how many answer RRs have been set? */
258 int n_authority; /* how many authority RRs have been set? */
259 int n_additional; /* how many additional RRs have been set? */
261 struct server_reply_item *answer; /* linked list of answer RRs */
262 struct server_reply_item *authority; /* linked list of authority RRs */
263 struct server_reply_item *additional; /* linked list of additional RRs */
265 /* Constructed response. Only set once we're ready to send a reply. */
266 /* Once this is set, the RR fields are cleared, and no more should be set. */
267 char *response;
268 size_t response_len;
270 /* Caller-visible fields: flags, questions. */
271 struct evdns_server_request base;
274 /* helper macro */
275 #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
277 /* Given a pointer to an evdns_server_request, get the corresponding */
278 /* server_request. */
279 #define TO_SERVER_REQUEST(base_ptr) \
280 ((struct server_request*) \
281 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
283 /* The number of good nameservers that we have */
284 static int global_good_nameservers = 0;
286 /* inflight requests are contained in the req_head list */
287 /* and are actually going out across the network */
288 static int global_requests_inflight = 0;
289 /* requests which aren't inflight are in the waiting list */
290 /* and are counted here */
291 static int global_requests_waiting = 0;
293 static int global_max_requests_inflight = 64;
295 static struct timeval global_timeout = {5, 0}; /* 5 seconds */
296 static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */
297 static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */
298 /* number of timeouts in a row before we consider this server to be down */
299 static int global_max_nameserver_timeout = 3;
301 /* These are the timeout values for nameservers. If we find a nameserver is down */
302 /* we try to probe it at intervals as given below. Values are in seconds. */
303 static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
304 static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
306 static struct nameserver *nameserver_pick(void);
307 static void evdns_request_insert(struct request *req, struct request **head);
308 static void nameserver_ready_callback(int fd, short events, void *arg);
309 static int evdns_transmit(void);
310 static int evdns_request_transmit(struct request *req);
311 static void nameserver_send_probe(struct nameserver *const ns);
312 static void search_request_finished(struct request *const);
313 static int search_try_next(struct request *const req);
314 static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
315 static void evdns_requests_pump_waiting_queue(void);
316 static u16 transaction_id_pick(void);
317 static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
318 static void request_submit(struct request *req);
320 static int server_request_free(struct server_request *req);
321 static void server_request_free_answers(struct server_request *req);
322 static void server_port_free(struct evdns_server_port *port);
323 static void server_port_ready_callback(int fd, short events, void *arg);
325 static int strtoint(const char *const str);
327 #ifdef WIN32
328 static int
329 last_error(int sock)
331 int optval, optvallen=sizeof(optval);
332 int err = WSAGetLastError();
333 if (err == WSAEWOULDBLOCK && sock >= 0) {
334 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
335 &optvallen))
336 return err;
337 if (optval)
338 return optval;
340 return err;
343 static int
344 error_is_eagain(int err)
346 return err == EAGAIN || err == WSAEWOULDBLOCK;
348 static int
349 inet_aton(const char *c, struct in_addr *addr)
351 uint32_t r;
352 if (strcmp(c, "255.255.255.255") == 0) {
353 addr->s_addr = 0xffffffffu;
354 } else {
355 r = inet_addr(c);
356 if (r == INADDR_NONE)
357 return 0;
358 addr->s_addr = r;
360 return 1;
362 #define CLOSE_SOCKET(x) closesocket(x)
363 #else
364 #define last_error(sock) (errno)
365 #define error_is_eagain(err) ((err) == EAGAIN)
366 #define CLOSE_SOCKET(x) close(x)
367 #endif
369 #define ISSPACE(c) isspace((int)(unsigned char)(c))
370 #define ISDIGIT(c) isdigit((int)(unsigned char)(c))
372 static const char *
373 debug_ntoa(u32 address)
375 static char buf[32];
376 u32 a = ntohl(address);
377 snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
378 (int)(u8)((a>>24)&0xff),
379 (int)(u8)((a>>16)&0xff),
380 (int)(u8)((a>>8 )&0xff),
381 (int)(u8)((a )&0xff));
382 return buf;
385 static evdns_debug_log_fn_type evdns_log_fn = NULL;
387 void
388 evdns_set_log_fn(evdns_debug_log_fn_type fn)
390 evdns_log_fn = fn;
393 #ifdef __GNUC__
394 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
395 #else
396 #define EVDNS_LOG_CHECK
397 #endif
399 static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
400 static void
401 _evdns_log(int warn, const char *fmt, ...)
403 va_list args;
404 static char buf[512];
405 if (!evdns_log_fn)
406 return;
407 va_start(args,fmt);
408 #ifdef WIN32
409 _vsnprintf(buf, sizeof(buf), fmt, args);
410 #else
411 vsnprintf(buf, sizeof(buf), fmt, args);
412 #endif
413 buf[sizeof(buf)-1] = '\0';
414 evdns_log_fn(warn, buf);
415 va_end(args);
418 #define log _evdns_log
420 /* This walks the list of inflight requests to find the */
421 /* one with a matching transaction id. Returns NULL on */
422 /* failure */
423 static struct request *
424 request_find_from_trans_id(u16 trans_id) {
425 struct request *req = req_head, *const started_at = req_head;
427 if (req) {
428 do {
429 if (req->trans_id == trans_id) return req;
430 req = req->next;
431 } while (req != started_at);
434 return NULL;
437 /* a libevent callback function which is called when a nameserver */
438 /* has gone down and we want to test if it has came back to life yet */
439 static void
440 nameserver_prod_callback(int fd, short events, void *arg) {
441 struct nameserver *const ns = (struct nameserver *) arg;
442 (void)fd;
443 (void)events;
445 nameserver_send_probe(ns);
448 /* a libevent callback which is called when a nameserver probe (to see if */
449 /* it has come back to life) times out. We increment the count of failed_times */
450 /* and wait longer to send the next probe packet. */
451 static void
452 nameserver_probe_failed(struct nameserver *const ns) {
453 const struct timeval * timeout;
454 (void) evtimer_del(&ns->timeout_event);
455 if (ns->state == 1) {
456 /* This can happen if the nameserver acts in a way which makes us mark */
457 /* it as bad and then starts sending good replies. */
458 return;
461 timeout =
462 &global_nameserver_timeouts[MIN(ns->failed_times,
463 global_nameserver_timeouts_length - 1)];
464 ns->failed_times++;
466 evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
467 if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
468 log(EVDNS_LOG_WARN,
469 "Error from libevent when adding timer event for %s",
470 debug_ntoa(ns->address));
471 /* ???? Do more? */
475 /* called when a nameserver has been deemed to have failed. For example, too */
476 /* many packets have timed out etc */
477 static void
478 nameserver_failed(struct nameserver *const ns, const char *msg) {
479 struct request *req, *started_at;
480 /* if this nameserver has already been marked as failed */
481 /* then don't do anything */
482 if (!ns->state) return;
484 log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
485 debug_ntoa(ns->address), msg);
486 global_good_nameservers--;
487 assert(global_good_nameservers >= 0);
488 if (global_good_nameservers == 0) {
489 log(EVDNS_LOG_WARN, "All nameservers have failed");
492 ns->state = 0;
493 ns->failed_times = 1;
495 evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
496 if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
497 log(EVDNS_LOG_WARN,
498 "Error from libevent when adding timer event for %s",
499 debug_ntoa(ns->address));
500 /* ???? Do more? */
503 /* walk the list of inflight requests to see if any can be reassigned to */
504 /* a different server. Requests in the waiting queue don't have a */
505 /* nameserver assigned yet */
507 /* if we don't have *any* good nameservers then there's no point */
508 /* trying to reassign requests to one */
509 if (!global_good_nameservers) return;
511 req = req_head;
512 started_at = req_head;
513 if (req) {
514 do {
515 if (req->tx_count == 0 && req->ns == ns) {
516 /* still waiting to go out, can be moved */
517 /* to another server */
518 req->ns = nameserver_pick();
520 req = req->next;
521 } while (req != started_at);
525 static void
526 nameserver_up(struct nameserver *const ns) {
527 if (ns->state) return;
528 log(EVDNS_LOG_WARN, "Nameserver %s is back up",
529 debug_ntoa(ns->address));
530 evtimer_del(&ns->timeout_event);
531 ns->state = 1;
532 ns->failed_times = 0;
533 ns->timedout = 0;
534 global_good_nameservers++;
537 static void
538 request_trans_id_set(struct request *const req, const u16 trans_id) {
539 req->trans_id = trans_id;
540 *((u16 *) req->request) = htons(trans_id);
543 /* Called to remove a request from a list and dealloc it. */
544 /* head is a pointer to the head of the list it should be */
545 /* removed from or NULL if the request isn't in a list. */
546 static void
547 request_finished(struct request *const req, struct request **head) {
548 if (head) {
549 if (req->next == req) {
550 /* only item in the list */
551 *head = NULL;
552 } else {
553 req->next->prev = req->prev;
554 req->prev->next = req->next;
555 if (*head == req) *head = req->next;
559 log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
560 (unsigned long) req);
561 evtimer_del(&req->timeout_event);
563 search_request_finished(req);
564 global_requests_inflight--;
566 if (!req->request_appended) {
567 /* need to free the request data on it's own */
568 free(req->request);
569 } else {
570 /* the request data is appended onto the header */
571 /* so everything gets free()ed when we: */
574 free(req);
576 evdns_requests_pump_waiting_queue();
579 /* This is called when a server returns a funny error code. */
580 /* We try the request again with another server. */
581 /* */
582 /* return: */
583 /* 0 ok */
584 /* 1 failed/reissue is pointless */
585 static int
586 request_reissue(struct request *req) {
587 const struct nameserver *const last_ns = req->ns;
588 /* the last nameserver should have been marked as failing */
589 /* by the caller of this function, therefore pick will try */
590 /* not to return it */
591 req->ns = nameserver_pick();
592 if (req->ns == last_ns) {
593 /* ... but pick did return it */
594 /* not a lot of point in trying again with the */
595 /* same server */
596 return 1;
599 req->reissue_count++;
600 req->tx_count = 0;
601 req->transmit_me = 1;
603 return 0;
606 /* this function looks for space on the inflight queue and promotes */
607 /* requests from the waiting queue if it can. */
608 static void
609 evdns_requests_pump_waiting_queue(void) {
610 while (global_requests_inflight < global_max_requests_inflight &&
611 global_requests_waiting) {
612 struct request *req;
613 /* move a request from the waiting queue to the inflight queue */
614 assert(req_waiting_head);
615 if (req_waiting_head->next == req_waiting_head) {
616 /* only one item in the queue */
617 req = req_waiting_head;
618 req_waiting_head = NULL;
619 } else {
620 req = req_waiting_head;
621 req->next->prev = req->prev;
622 req->prev->next = req->next;
623 req_waiting_head = req->next;
626 global_requests_waiting--;
627 global_requests_inflight++;
629 req->ns = nameserver_pick();
630 request_trans_id_set(req, transaction_id_pick());
632 evdns_request_insert(req, &req_head);
633 evdns_request_transmit(req);
634 evdns_transmit();
638 static void
639 reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
640 switch (req->request_type) {
641 case TYPE_A:
642 if (reply)
643 req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
644 reply->data.a.addrcount, ttl,
645 reply->data.a.addresses,
646 req->user_pointer);
647 else
648 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
649 return;
650 case TYPE_PTR:
651 if (reply) {
652 char *name = reply->data.ptr.name;
653 req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
654 &name, req->user_pointer);
655 } else {
656 req->user_callback(err, 0, 0, 0, NULL,
657 req->user_pointer);
659 return;
660 case TYPE_AAAA:
661 if (reply)
662 req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
663 reply->data.aaaa.addrcount, ttl,
664 reply->data.aaaa.addresses,
665 req->user_pointer);
666 else
667 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
668 return;
670 assert(0);
673 /* this processes a parsed reply packet */
674 static void
675 reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
676 int error;
677 static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
679 if (flags & 0x020f || !reply || !reply->have_answer) {
680 /* there was an error */
681 if (flags & 0x0200) {
682 error = DNS_ERR_TRUNCATED;
683 } else {
684 u16 error_code = (flags & 0x000f) - 1;
685 if (error_code > 4) {
686 error = DNS_ERR_UNKNOWN;
687 } else {
688 error = error_codes[error_code];
692 switch(error) {
693 case DNS_ERR_NOTIMPL:
694 case DNS_ERR_REFUSED:
695 /* we regard these errors as marking a bad nameserver */
696 if (req->reissue_count < global_max_reissues) {
697 char msg[64];
698 snprintf(msg, sizeof(msg), "Bad response %d (%s)",
699 error, evdns_err_to_string(error));
700 nameserver_failed(req->ns, msg);
701 if (!request_reissue(req)) return;
703 break;
704 case DNS_ERR_SERVERFAILED:
705 /* rcode 2 (servfailed) sometimes means "we are broken" and
706 * sometimes (with some binds) means "that request was very
707 * confusing." Treat this as a timeout, not a failure.
709 log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
710 "will allow the request to time out.",
711 debug_ntoa(req->ns->address));
712 break;
713 default:
714 /* we got a good reply from the nameserver */
715 nameserver_up(req->ns);
718 if (req->search_state && req->request_type != TYPE_PTR) {
719 /* if we have a list of domains to search in, try the next one */
720 if (!search_try_next(req)) {
721 /* a new request was issued so this request is finished and */
722 /* the user callback will be made when that request (or a */
723 /* child of it) finishes. */
724 request_finished(req, &req_head);
725 return;
729 /* all else failed. Pass the failure up */
730 reply_callback(req, 0, error, NULL);
731 request_finished(req, &req_head);
732 } else {
733 /* all ok, tell the user */
734 reply_callback(req, ttl, 0, reply);
735 nameserver_up(req->ns);
736 request_finished(req, &req_head);
740 static int
741 name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
742 int name_end = -1;
743 int j = *idx;
744 int ptr_count = 0;
745 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
746 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
747 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
749 char *cp = name_out;
750 const char *const end = name_out + name_out_len;
752 /* Normally, names are a series of length prefixed strings terminated */
753 /* with a length of 0 (the lengths are u8's < 63). */
754 /* However, the length can start with a pair of 1 bits and that */
755 /* means that the next 14 bits are a pointer within the current */
756 /* packet. */
758 for(;;) {
759 u8 label_len;
760 if (j >= length) return -1;
761 GET8(label_len);
762 if (!label_len) break;
763 if (label_len & 0xc0) {
764 u8 ptr_low;
765 GET8(ptr_low);
766 if (name_end < 0) name_end = j;
767 j = (((int)label_len & 0x3f) << 8) + ptr_low;
768 /* Make sure that the target offset is in-bounds. */
769 if (j < 0 || j >= length) return -1;
770 /* If we've jumped more times than there are characters in the
771 * message, we must have a loop. */
772 if (++ptr_count > length) return -1;
773 continue;
775 if (label_len > 63) return -1;
776 if (cp != name_out) {
777 if (cp + 1 >= end) return -1;
778 *cp++ = '.';
780 if (cp + label_len >= end) return -1;
781 memcpy(cp, packet + j, label_len);
782 cp += label_len;
783 j += label_len;
785 if (cp >= end) return -1;
786 *cp = '\0';
787 if (name_end < 0)
788 *idx = j;
789 else
790 *idx = name_end;
791 return 0;
792 err:
793 return -1;
796 /* parses a raw request from a nameserver */
797 static int
798 reply_parse(u8 *packet, int length) {
799 int j = 0; /* index into packet */
800 u16 _t; /* used by the macros */
801 u32 _t32; /* used by the macros */
802 char tmp_name[256]; /* used by the macros */
804 u16 trans_id, questions, answers, authority, additional, datalength;
805 u16 flags = 0;
806 u32 ttl, ttl_r = 0xffffffff;
807 struct reply reply;
808 struct request *req = NULL;
809 unsigned int i;
811 GET16(trans_id);
812 GET16(flags);
813 GET16(questions);
814 GET16(answers);
815 GET16(authority);
816 GET16(additional);
817 (void) authority; /* suppress "unused variable" warnings. */
818 (void) additional; /* suppress "unused variable" warnings. */
820 req = request_find_from_trans_id(trans_id);
821 if (!req) return -1;
823 memset(&reply, 0, sizeof(reply));
825 /* If it's not an answer, it doesn't correspond to any request. */
826 if (!(flags & 0x8000)) return -1; /* must be an answer */
827 if (flags & 0x020f) {
828 /* there was an error */
829 goto err;
831 /* if (!answers) return; */ /* must have an answer of some form */
833 /* This macro skips a name in the DNS reply. */
834 #define SKIP_NAME \
835 do { tmp_name[0] = '\0'; \
836 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
837 goto err; \
838 } while(0);
840 reply.type = req->request_type;
842 /* skip over each question in the reply */
843 for (i = 0; i < questions; ++i) {
844 /* the question looks like
845 * <label:name><u16:type><u16:class>
847 SKIP_NAME;
848 j += 4;
849 if (j >= length) goto err;
852 /* now we have the answer section which looks like
853 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
856 for (i = 0; i < answers; ++i) {
857 u16 type, class;
859 SKIP_NAME;
860 GET16(type);
861 GET16(class);
862 GET32(ttl);
863 GET16(datalength);
865 if (type == TYPE_A && class == CLASS_INET) {
866 int addrcount, addrtocopy;
867 if (req->request_type != TYPE_A) {
868 j += datalength; continue;
870 if ((datalength & 3) != 0) /* not an even number of As. */
871 goto err;
872 addrcount = datalength >> 2;
873 addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
875 ttl_r = MIN(ttl_r, ttl);
876 /* we only bother with the first four addresses. */
877 if (j + 4*addrtocopy > length) goto err;
878 memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
879 packet + j, 4*addrtocopy);
880 j += 4*addrtocopy;
881 reply.data.a.addrcount += addrtocopy;
882 reply.have_answer = 1;
883 if (reply.data.a.addrcount == MAX_ADDRS) break;
884 } else if (type == TYPE_PTR && class == CLASS_INET) {
885 if (req->request_type != TYPE_PTR) {
886 j += datalength; continue;
888 if (name_parse(packet, length, &j, reply.data.ptr.name,
889 sizeof(reply.data.ptr.name))<0)
890 goto err;
891 ttl_r = MIN(ttl_r, ttl);
892 reply.have_answer = 1;
893 break;
894 } else if (type == TYPE_AAAA && class == CLASS_INET) {
895 int addrcount, addrtocopy;
896 if (req->request_type != TYPE_AAAA) {
897 j += datalength; continue;
899 if ((datalength & 15) != 0) /* not an even number of AAAAs. */
900 goto err;
901 addrcount = datalength >> 4; /* each address is 16 bytes long */
902 addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
903 ttl_r = MIN(ttl_r, ttl);
905 /* we only bother with the first four addresses. */
906 if (j + 16*addrtocopy > length) goto err;
907 memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
908 packet + j, 16*addrtocopy);
909 reply.data.aaaa.addrcount += addrtocopy;
910 j += 16*addrtocopy;
911 reply.have_answer = 1;
912 if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
913 } else {
914 /* skip over any other type of resource */
915 j += datalength;
919 reply_handle(req, flags, ttl_r, &reply);
920 return 0;
921 err:
922 if (req)
923 reply_handle(req, flags, 0, NULL);
924 return -1;
927 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
928 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
929 /* callback. */
930 static int
931 request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
933 int j = 0; /* index into packet */
934 u16 _t; /* used by the macros */
935 char tmp_name[256]; /* used by the macros */
937 int i;
938 u16 trans_id, flags, questions, answers, authority, additional;
939 struct server_request *server_req = NULL;
941 /* Get the header fields */
942 GET16(trans_id);
943 GET16(flags);
944 GET16(questions);
945 GET16(answers);
946 GET16(authority);
947 GET16(additional);
949 if (flags & 0x8000) return -1; /* Must not be an answer. */
950 if (flags & 0x7800) return -1; /* only standard queries are supported */
951 flags &= 0x0300; /* Only TC and RD get preserved. */
953 server_req = malloc(sizeof(struct server_request));
954 if (server_req == NULL) return -1;
955 memset(server_req, 0, sizeof(struct server_request));
957 server_req->trans_id = trans_id;
958 memcpy(&server_req->addr, addr, addrlen);
959 server_req->addrlen = addrlen;
961 server_req->base.flags = flags;
962 server_req->base.nquestions = 0;
963 server_req->base.questions = malloc(sizeof(struct evdns_server_question *) * questions);
964 if (server_req->base.questions == NULL)
965 goto err;
967 for (i = 0; i < questions; ++i) {
968 u16 type, class;
969 struct evdns_server_question *q;
970 int namelen;
971 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
972 goto err;
973 GET16(type);
974 GET16(class);
975 namelen = strlen(tmp_name);
976 q = malloc(sizeof(struct evdns_server_question) + namelen);
977 if (!q)
978 goto err;
979 q->type = type;
980 q->class = class;
981 memcpy(q->name, tmp_name, namelen+1);
982 server_req->base.questions[server_req->base.nquestions++] = q;
985 /* Ignore answers, authority, and additional. */
987 server_req->port = port;
988 port->refcnt++;
989 port->user_callback(&(server_req->base), port->user_data);
991 return 0;
992 err:
993 if (server_req) {
994 if (server_req->base.questions) {
995 for (i = 0; i < server_req->base.nquestions; ++i)
996 free(server_req->base.questions[i]);
997 free(server_req->base.questions);
999 free(server_req);
1001 return -1;
1003 #undef SKIP_NAME
1004 #undef GET32
1005 #undef GET16
1006 #undef GET8
1009 /* Try to choose a strong transaction id which isn't already in flight */
1010 static u16
1011 transaction_id_pick(void) {
1012 for (;;) {
1013 const struct request *req = req_head, *started_at;
1014 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
1015 struct timespec ts;
1016 u16 trans_id;
1017 #ifdef CLOCK_MONOTONIC
1018 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
1019 #else
1020 if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
1021 #endif
1022 event_err(1, "clock_gettime");
1023 trans_id = ts.tv_nsec & 0xffff;
1024 #endif
1026 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
1027 struct timeval tv;
1028 u16 trans_id;
1029 gettimeofday(&tv, NULL);
1030 trans_id = tv.tv_usec & 0xffff;
1031 #endif
1033 #ifdef DNS_USE_OPENSSL_FOR_ID
1034 u16 trans_id;
1035 if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
1036 /* in the case that the RAND call fails we back */
1037 /* down to using gettimeofday. */
1038 struct timeval tv;
1039 gettimeofday(&tv, NULL);
1040 trans_id = tv.tv_usec & 0xffff; */
1041 abort();
1043 #endif
1045 if (trans_id == 0xffff) continue;
1046 /* now check to see if that id is already inflight */
1047 req = started_at = req_head;
1048 if (req) {
1049 do {
1050 if (req->trans_id == trans_id) break;
1051 req = req->next;
1052 } while (req != started_at);
1054 /* we didn't find it, so this is a good id */
1055 if (req == started_at) return trans_id;
1059 /* choose a namesever to use. This function will try to ignore */
1060 /* nameservers which we think are down and load balance across the rest */
1061 /* by updating the server_head global each time. */
1062 static struct nameserver *
1063 nameserver_pick(void) {
1064 struct nameserver *started_at = server_head, *picked;
1065 if (!server_head) return NULL;
1067 /* if we don't have any good nameservers then there's no */
1068 /* point in trying to find one. */
1069 if (!global_good_nameservers) {
1070 server_head = server_head->next;
1071 return server_head;
1074 /* remember that nameservers are in a circular list */
1075 for (;;) {
1076 if (server_head->state) {
1077 /* we think this server is currently good */
1078 picked = server_head;
1079 server_head = server_head->next;
1080 return picked;
1083 server_head = server_head->next;
1084 if (server_head == started_at) {
1085 /* all the nameservers seem to be down */
1086 /* so we just return this one and hope for the */
1087 /* best */
1088 assert(global_good_nameservers == 0);
1089 picked = server_head;
1090 server_head = server_head->next;
1091 return picked;
1096 /* this is called when a namesever socket is ready for reading */
1097 static void
1098 nameserver_read(struct nameserver *ns) {
1099 u8 packet[1500];
1101 for (;;) {
1102 const int r = recv(ns->socket, packet, sizeof(packet), 0);
1103 if (r < 0) {
1104 int err = last_error(ns->socket);
1105 if (error_is_eagain(err)) return;
1106 nameserver_failed(ns, strerror(err));
1107 return;
1109 ns->timedout = 0;
1110 reply_parse(packet, r);
1114 /* Read a packet from a DNS client on a server port s, parse it, and */
1115 /* act accordingly. */
1116 static void
1117 server_port_read(struct evdns_server_port *s) {
1118 u8 packet[1500];
1119 struct sockaddr_storage addr;
1120 socklen_t addrlen;
1121 int r;
1123 for (;;) {
1124 addrlen = sizeof(struct sockaddr_storage);
1125 r = recvfrom(s->socket, packet, sizeof(packet), 0,
1126 (struct sockaddr*) &addr, &addrlen);
1127 if (r < 0) {
1128 int err = last_error(s->socket);
1129 if (error_is_eagain(err)) return;
1130 log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
1131 strerror(err), err);
1132 return;
1134 request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
1138 /* Try to write all pending replies on a given DNS server port. */
1139 static void
1140 server_port_flush(struct evdns_server_port *port)
1142 while (port->pending_replies) {
1143 struct server_request *req = port->pending_replies;
1144 int r = sendto(port->socket, req->response, req->response_len, 0,
1145 (struct sockaddr*) &req->addr, req->addrlen);
1146 if (r < 0) {
1147 int err = last_error(port->socket);
1148 if (error_is_eagain(err))
1149 return;
1150 log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
1152 if (server_request_free(req)) {
1153 /* we released the last reference to req->port. */
1154 return;
1158 /* We have no more pending requests; stop listening for 'writeable' events. */
1159 (void) event_del(&port->event);
1160 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1161 server_port_ready_callback, port);
1162 if (event_add(&port->event, NULL) < 0) {
1163 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
1164 /* ???? Do more? */
1168 /* set if we are waiting for the ability to write to this server. */
1169 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1170 /* we stop these events. */
1171 static void
1172 nameserver_write_waiting(struct nameserver *ns, char waiting) {
1173 if (ns->write_waiting == waiting) return;
1175 ns->write_waiting = waiting;
1176 (void) event_del(&ns->event);
1177 event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1178 nameserver_ready_callback, ns);
1179 if (event_add(&ns->event, NULL) < 0) {
1180 log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
1181 debug_ntoa(ns->address));
1182 /* ???? Do more? */
1186 /* a callback function. Called by libevent when the kernel says that */
1187 /* a nameserver socket is ready for writing or reading */
1188 static void
1189 nameserver_ready_callback(int fd, short events, void *arg) {
1190 struct nameserver *ns = (struct nameserver *) arg;
1191 (void)fd;
1193 if (events & EV_WRITE) {
1194 ns->choked = 0;
1195 if (!evdns_transmit()) {
1196 nameserver_write_waiting(ns, 0);
1199 if (events & EV_READ) {
1200 nameserver_read(ns);
1204 /* a callback function. Called by libevent when the kernel says that */
1205 /* a server socket is ready for writing or reading. */
1206 static void
1207 server_port_ready_callback(int fd, short events, void *arg) {
1208 struct evdns_server_port *port = (struct evdns_server_port *) arg;
1209 (void) fd;
1211 if (events & EV_WRITE) {
1212 port->choked = 0;
1213 server_port_flush(port);
1215 if (events & EV_READ) {
1216 server_port_read(port);
1220 /* This is an inefficient representation; only use it via the dnslabel_table_*
1221 * functions, so that is can be safely replaced with something smarter later. */
1222 #define MAX_LABELS 128
1223 /* Structures used to implement name compression */
1224 struct dnslabel_entry { char *v; off_t pos; };
1225 struct dnslabel_table {
1226 int n_labels; /* number of current entries */
1227 /* map from name to position in message */
1228 struct dnslabel_entry labels[MAX_LABELS];
1231 /* Initialize dnslabel_table. */
1232 static void
1233 dnslabel_table_init(struct dnslabel_table *table)
1235 table->n_labels = 0;
1238 /* Free all storage held by table, but not the table itself. */
1239 static void
1240 dnslabel_clear(struct dnslabel_table *table)
1242 int i;
1243 for (i = 0; i < table->n_labels; ++i)
1244 free(table->labels[i].v);
1245 table->n_labels = 0;
1248 /* return the position of the label in the current message, or -1 if the label */
1249 /* hasn't been used yet. */
1250 static int
1251 dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
1253 int i;
1254 for (i = 0; i < table->n_labels; ++i) {
1255 if (!strcmp(label, table->labels[i].v))
1256 return table->labels[i].pos;
1258 return -1;
1261 /* remember that we've used the label at position pos */
1262 static int
1263 dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
1265 char *v;
1266 int p;
1267 if (table->n_labels == MAX_LABELS)
1268 return (-1);
1269 v = strdup(label);
1270 if (v == NULL)
1271 return (-1);
1272 p = table->n_labels++;
1273 table->labels[p].v = v;
1274 table->labels[p].pos = pos;
1276 return (0);
1279 /* Converts a string to a length-prefixed set of DNS labels, starting */
1280 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1281 /* of name. table is optional, and is used for compression. */
1282 /* */
1283 /* Input: abc.def */
1284 /* Output: <3>abc<3>def<0> */
1285 /* */
1286 /* Returns the first index after the encoded name, or negative on error. */
1287 /* -1 label was > 63 bytes */
1288 /* -2 name too long to fit in buffer. */
1289 /* */
1290 static off_t
1291 dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
1292 const char *name, const int name_len,
1293 struct dnslabel_table *table) {
1294 const char *end = name + name_len;
1295 int ref = 0;
1296 u16 _t;
1298 #define APPEND16(x) do { \
1299 if (j + 2 > (off_t)buf_len) \
1300 goto overflow; \
1301 _t = htons(x); \
1302 memcpy(buf + j, &_t, 2); \
1303 j += 2; \
1304 } while (0)
1305 #define APPEND32(x) do { \
1306 if (j + 4 > (off_t)buf_len) \
1307 goto overflow; \
1308 _t32 = htonl(x); \
1309 memcpy(buf + j, &_t32, 4); \
1310 j += 4; \
1311 } while (0)
1313 if (name_len > 255) return -2;
1315 for (;;) {
1316 const char *const start = name;
1317 if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1318 APPEND16(ref | 0xc000);
1319 return j;
1321 name = strchr(name, '.');
1322 if (!name) {
1323 const unsigned int label_len = end - start;
1324 if (label_len > 63) return -1;
1325 if ((size_t)(j+label_len+1) > buf_len) return -2;
1326 if (table) dnslabel_table_add(table, start, j);
1327 buf[j++] = label_len;
1329 memcpy(buf + j, start, end - start);
1330 j += end - start;
1331 break;
1332 } else {
1333 /* append length of the label. */
1334 const unsigned int label_len = name - start;
1335 if (label_len > 63) return -1;
1336 if ((size_t)(j+label_len+1) > buf_len) return -2;
1337 if (table) dnslabel_table_add(table, start, j);
1338 buf[j++] = label_len;
1340 memcpy(buf + j, start, name - start);
1341 j += name - start;
1342 /* hop over the '.' */
1343 name++;
1347 /* the labels must be terminated by a 0. */
1348 /* It's possible that the name ended in a . */
1349 /* in which case the zero is already there */
1350 if (!j || buf[j-1]) buf[j++] = 0;
1351 return j;
1352 overflow:
1353 return (-2);
1356 /* Finds the length of a dns request for a DNS name of the given */
1357 /* length. The actual request may be smaller than the value returned */
1358 /* here */
1359 static int
1360 evdns_request_len(const int name_len) {
1361 return 96 + /* length of the DNS standard header */
1362 name_len + 2 +
1363 4; /* space for the resource type */
1366 /* build a dns request packet into buf. buf should be at least as long */
1367 /* as evdns_request_len told you it should be. */
1368 /* */
1369 /* Returns the amount of space used. Negative on error. */
1370 static int
1371 evdns_request_data_build(const char *const name, const int name_len,
1372 const u16 trans_id, const u16 type, const u16 class,
1373 u8 *const buf, size_t buf_len) {
1374 off_t j = 0; /* current offset into buf */
1375 u16 _t; /* used by the macros */
1377 APPEND16(trans_id);
1378 APPEND16(0x0100); /* standard query, recusion needed */
1379 APPEND16(1); /* one question */
1380 APPEND16(0); /* no answers */
1381 APPEND16(0); /* no authority */
1382 APPEND16(0); /* no additional */
1384 j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1385 if (j < 0) {
1386 return (int)j;
1389 APPEND16(type);
1390 APPEND16(class);
1392 return (int)j;
1393 overflow:
1394 return (-1);
1397 /* exported function */
1398 struct evdns_server_port *
1399 evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
1401 struct evdns_server_port *port;
1402 if (!(port = malloc(sizeof(struct evdns_server_port))))
1403 return NULL;
1404 memset(port, 0, sizeof(struct evdns_server_port));
1406 assert(!is_tcp); /* TCP sockets not yet implemented */
1407 port->socket = socket;
1408 port->refcnt = 1;
1409 port->choked = 0;
1410 port->closing = 0;
1411 port->user_callback = cb;
1412 port->user_data = user_data;
1413 port->pending_replies = NULL;
1415 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1416 server_port_ready_callback, port);
1417 event_add(&port->event, NULL); /* check return. */
1418 return port;
1421 /* exported function */
1422 void
1423 evdns_close_server_port(struct evdns_server_port *port)
1425 if (--port->refcnt == 0)
1426 server_port_free(port);
1427 port->closing = 1;
1430 /* exported function */
1432 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)
1434 struct server_request *req = TO_SERVER_REQUEST(_req);
1435 struct server_reply_item **itemp, *item;
1436 int *countp;
1438 if (req->response) /* have we already answered? */
1439 return (-1);
1441 switch (section) {
1442 case EVDNS_ANSWER_SECTION:
1443 itemp = &req->answer;
1444 countp = &req->n_answer;
1445 break;
1446 case EVDNS_AUTHORITY_SECTION:
1447 itemp = &req->authority;
1448 countp = &req->n_authority;
1449 break;
1450 case EVDNS_ADDITIONAL_SECTION:
1451 itemp = &req->additional;
1452 countp = &req->n_additional;
1453 break;
1454 default:
1455 return (-1);
1457 while (*itemp) {
1458 itemp = &((*itemp)->next);
1460 item = malloc(sizeof(struct server_reply_item));
1461 if (!item)
1462 return -1;
1463 item->next = NULL;
1464 if (!(item->name = strdup(name))) {
1465 free(item);
1466 return -1;
1468 item->type = type;
1469 item->class = class;
1470 item->ttl = ttl;
1471 item->is_name = is_name != 0;
1472 item->datalen = 0;
1473 item->data = NULL;
1474 if (data) {
1475 if (item->is_name) {
1476 if (!(item->data = strdup(data))) {
1477 free(item->name);
1478 free(item);
1479 return -1;
1481 item->datalen = (u16)-1;
1482 } else {
1483 if (!(item->data = malloc(datalen))) {
1484 free(item->name);
1485 free(item);
1486 return -1;
1488 item->datalen = datalen;
1489 memcpy(item->data, data, datalen);
1493 *itemp = item;
1494 ++(*countp);
1495 return 0;
1498 /* exported function */
1500 evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1502 return evdns_server_request_add_reply(
1503 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1504 ttl, n*4, 0, addrs);
1507 /* exported function */
1509 evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1511 return evdns_server_request_add_reply(
1512 req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1513 ttl, n*16, 0, addrs);
1516 /* exported function */
1518 evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
1520 u32 a;
1521 char buf[32];
1522 assert(in || inaddr_name);
1523 assert(!(in && inaddr_name));
1524 if (in) {
1525 a = ntohl(in->s_addr);
1526 snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
1527 (int)(u8)((a )&0xff),
1528 (int)(u8)((a>>8 )&0xff),
1529 (int)(u8)((a>>16)&0xff),
1530 (int)(u8)((a>>24)&0xff));
1531 inaddr_name = buf;
1533 return evdns_server_request_add_reply(
1534 req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1535 ttl, -1, 1, hostname);
1538 /* exported function */
1540 evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
1542 return evdns_server_request_add_reply(
1543 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1544 ttl, -1, 1, cname);
1548 static int
1549 evdns_server_request_format_response(struct server_request *req, int err)
1551 unsigned char buf[1500];
1552 size_t buf_len = sizeof(buf);
1553 off_t j = 0, r;
1554 u16 _t;
1555 u32 _t32;
1556 int i;
1557 u16 flags;
1558 struct dnslabel_table table;
1560 if (err < 0 || err > 15) return -1;
1562 /* Set response bit and error code; copy OPCODE and RD fields from
1563 * question; copy RA and AA if set by caller. */
1564 flags = req->base.flags;
1565 flags |= (0x8000 | err);
1567 dnslabel_table_init(&table);
1568 APPEND16(req->trans_id);
1569 APPEND16(flags);
1570 APPEND16(req->base.nquestions);
1571 APPEND16(req->n_answer);
1572 APPEND16(req->n_authority);
1573 APPEND16(req->n_additional);
1575 /* Add questions. */
1576 for (i=0; i < req->base.nquestions; ++i) {
1577 const char *s = req->base.questions[i]->name;
1578 j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1579 if (j < 0) {
1580 dnslabel_clear(&table);
1581 return (int) j;
1583 APPEND16(req->base.questions[i]->type);
1584 APPEND16(req->base.questions[i]->class);
1587 /* Add answer, authority, and additional sections. */
1588 for (i=0; i<3; ++i) {
1589 struct server_reply_item *item;
1590 if (i==0)
1591 item = req->answer;
1592 else if (i==1)
1593 item = req->authority;
1594 else
1595 item = req->additional;
1596 while (item) {
1597 r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1598 if (r < 0)
1599 goto overflow;
1600 j = r;
1602 APPEND16(item->type);
1603 APPEND16(item->class);
1604 APPEND32(item->ttl);
1605 if (item->is_name) {
1606 off_t len_idx = j, name_start;
1607 j += 2;
1608 name_start = j;
1609 r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1610 if (r < 0)
1611 goto overflow;
1612 j = r;
1613 _t = htons( (j-name_start) );
1614 memcpy(buf+len_idx, &_t, 2);
1615 } else {
1616 APPEND16(item->datalen);
1617 if (j+item->datalen > (off_t)buf_len)
1618 goto overflow;
1619 memcpy(buf+j, item->data, item->datalen);
1620 j += item->datalen;
1622 item = item->next;
1626 if (j > 512) {
1627 overflow:
1628 j = 512;
1629 buf[3] |= 0x02; /* set the truncated bit. */
1632 req->response_len = j;
1634 if (!(req->response = malloc(req->response_len))) {
1635 server_request_free_answers(req);
1636 dnslabel_clear(&table);
1637 return (-1);
1639 memcpy(req->response, buf, req->response_len);
1640 server_request_free_answers(req);
1641 dnslabel_clear(&table);
1642 return (0);
1645 /* exported function */
1647 evdns_server_request_respond(struct evdns_server_request *_req, int err)
1649 struct server_request *req = TO_SERVER_REQUEST(_req);
1650 struct evdns_server_port *port = req->port;
1651 int r;
1652 if (!req->response) {
1653 if ((r = evdns_server_request_format_response(req, err))<0)
1654 return r;
1657 r = sendto(port->socket, req->response, req->response_len, 0,
1658 (struct sockaddr*) &req->addr, req->addrlen);
1659 if (r<0) {
1660 int err = last_error(port->socket);
1661 if (! error_is_eagain(err))
1662 return -1;
1664 if (port->pending_replies) {
1665 req->prev_pending = port->pending_replies->prev_pending;
1666 req->next_pending = port->pending_replies;
1667 req->prev_pending->next_pending =
1668 req->next_pending->prev_pending = req;
1669 } else {
1670 req->prev_pending = req->next_pending = req;
1671 port->pending_replies = req;
1672 port->choked = 1;
1674 (void) event_del(&port->event);
1675 event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
1677 if (event_add(&port->event, NULL) < 0) {
1678 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
1683 return 1;
1685 if (server_request_free(req))
1686 return 0;
1688 if (port->pending_replies)
1689 server_port_flush(port);
1691 return 0;
1694 /* Free all storage held by RRs in req. */
1695 static void
1696 server_request_free_answers(struct server_request *req)
1698 struct server_reply_item *victim, *next, **list;
1699 int i;
1700 for (i = 0; i < 3; ++i) {
1701 if (i==0)
1702 list = &req->answer;
1703 else if (i==1)
1704 list = &req->authority;
1705 else
1706 list = &req->additional;
1708 victim = *list;
1709 while (victim) {
1710 next = victim->next;
1711 free(victim->name);
1712 if (victim->data)
1713 free(victim->data);
1714 free(victim);
1715 victim = next;
1717 *list = NULL;
1721 /* Free all storage held by req, and remove links to it. */
1722 /* return true iff we just wound up freeing the server_port. */
1723 static int
1724 server_request_free(struct server_request *req)
1726 int i, rc=1;
1727 if (req->base.questions) {
1728 for (i = 0; i < req->base.nquestions; ++i)
1729 free(req->base.questions[i]);
1730 free(req->base.questions);
1733 if (req->port) {
1734 if (req->port->pending_replies == req) {
1735 if (req->next_pending)
1736 req->port->pending_replies = req->next_pending;
1737 else
1738 req->port->pending_replies = NULL;
1740 rc = --req->port->refcnt;
1743 if (req->response) {
1744 free(req->response);
1747 server_request_free_answers(req);
1749 if (req->next_pending && req->next_pending != req) {
1750 req->next_pending->prev_pending = req->prev_pending;
1751 req->prev_pending->next_pending = req->next_pending;
1754 if (rc == 0) {
1755 server_port_free(req->port);
1756 free(req);
1757 return (1);
1759 free(req);
1760 return (0);
1763 /* Free all storage held by an evdns_server_port. Only called when */
1764 static void
1765 server_port_free(struct evdns_server_port *port)
1767 assert(port);
1768 assert(!port->refcnt);
1769 assert(!port->pending_replies);
1770 if (port->socket > 0) {
1771 CLOSE_SOCKET(port->socket);
1772 port->socket = -1;
1774 (void) event_del(&port->event);
1775 /* XXXX actually free the port? -NM */
1778 /* exported function */
1780 evdns_server_request_drop(struct evdns_server_request *_req)
1782 struct server_request *req = TO_SERVER_REQUEST(_req);
1783 server_request_free(req);
1784 return 0;
1787 /* exported function */
1789 evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
1791 struct server_request *req = TO_SERVER_REQUEST(_req);
1792 if (addr_len < (int)req->addrlen)
1793 return -1;
1794 memcpy(sa, &(req->addr), req->addrlen);
1795 return req->addrlen;
1798 #undef APPEND16
1799 #undef APPEND32
1801 /* this is a libevent callback function which is called when a request */
1802 /* has timed out. */
1803 static void
1804 evdns_request_timeout_callback(int fd, short events, void *arg) {
1805 struct request *const req = (struct request *) arg;
1806 (void) fd;
1807 (void) events;
1809 log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
1811 req->ns->timedout++;
1812 if (req->ns->timedout > global_max_nameserver_timeout) {
1813 req->ns->timedout = 0;
1814 nameserver_failed(req->ns, "request timed out.");
1817 (void) evtimer_del(&req->timeout_event);
1818 if (req->tx_count >= global_max_retransmits) {
1819 /* this request has failed */
1820 reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
1821 request_finished(req, &req_head);
1822 } else {
1823 /* retransmit it */
1824 evdns_request_transmit(req);
1828 /* try to send a request to a given server. */
1829 /* */
1830 /* return: */
1831 /* 0 ok */
1832 /* 1 temporary failure */
1833 /* 2 other failure */
1834 static int
1835 evdns_request_transmit_to(struct request *req, struct nameserver *server) {
1836 const int r = send(server->socket, req->request, req->request_len, 0);
1837 if (r < 0) {
1838 int err = last_error(server->socket);
1839 if (error_is_eagain(err)) return 1;
1840 nameserver_failed(req->ns, strerror(err));
1841 return 2;
1842 } else if (r != (int)req->request_len) {
1843 return 1; /* short write */
1844 } else {
1845 return 0;
1849 /* try to send a request, updating the fields of the request */
1850 /* as needed */
1851 /* */
1852 /* return: */
1853 /* 0 ok */
1854 /* 1 failed */
1855 static int
1856 evdns_request_transmit(struct request *req) {
1857 int retcode = 0, r;
1859 /* if we fail to send this packet then this flag marks it */
1860 /* for evdns_transmit */
1861 req->transmit_me = 1;
1862 if (req->trans_id == 0xffff) abort();
1864 if (req->ns->choked) {
1865 /* don't bother trying to write to a socket */
1866 /* which we have had EAGAIN from */
1867 return 1;
1870 r = evdns_request_transmit_to(req, req->ns);
1871 switch (r) {
1872 case 1:
1873 /* temp failure */
1874 req->ns->choked = 1;
1875 nameserver_write_waiting(req->ns, 1);
1876 return 1;
1877 case 2:
1878 /* failed in some other way */
1879 retcode = 1;
1880 /* fall through */
1881 default:
1882 /* all ok */
1883 log(EVDNS_LOG_DEBUG,
1884 "Setting timeout for request %lx", (unsigned long) req);
1885 evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
1886 if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
1887 log(EVDNS_LOG_WARN,
1888 "Error from libevent when adding timer for request %lx",
1889 (unsigned long) req);
1890 /* ???? Do more? */
1892 req->tx_count++;
1893 req->transmit_me = 0;
1894 return retcode;
1898 static void
1899 nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
1900 struct nameserver *const ns = (struct nameserver *) arg;
1901 (void) type;
1902 (void) count;
1903 (void) ttl;
1904 (void) addresses;
1906 if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
1907 /* this is a good reply */
1908 nameserver_up(ns);
1909 } else nameserver_probe_failed(ns);
1912 static void
1913 nameserver_send_probe(struct nameserver *const ns) {
1914 struct request *req;
1915 /* here we need to send a probe to a given nameserver */
1916 /* in the hope that it is up now. */
1918 log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
1920 req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
1921 if (!req) return;
1922 /* we force this into the inflight queue no matter what */
1923 request_trans_id_set(req, transaction_id_pick());
1924 req->ns = ns;
1925 request_submit(req);
1928 /* returns: */
1929 /* 0 didn't try to transmit anything */
1930 /* 1 tried to transmit something */
1931 static int
1932 evdns_transmit(void) {
1933 char did_try_to_transmit = 0;
1935 if (req_head) {
1936 struct request *const started_at = req_head, *req = req_head;
1937 /* first transmit all the requests which are currently waiting */
1938 do {
1939 if (req->transmit_me) {
1940 did_try_to_transmit = 1;
1941 evdns_request_transmit(req);
1944 req = req->next;
1945 } while (req != started_at);
1948 return did_try_to_transmit;
1951 /* exported function */
1953 evdns_count_nameservers(void)
1955 const struct nameserver *server = server_head;
1956 int n = 0;
1957 if (!server)
1958 return 0;
1959 do {
1960 ++n;
1961 server = server->next;
1962 } while (server != server_head);
1963 return n;
1966 /* exported function */
1968 evdns_clear_nameservers_and_suspend(void)
1970 struct nameserver *server = server_head, *started_at = server_head;
1971 struct request *req = req_head, *req_started_at = req_head;
1973 if (!server)
1974 return 0;
1975 while (1) {
1976 struct nameserver *next = server->next;
1977 (void) event_del(&server->event);
1978 (void) evtimer_del(&server->timeout_event);
1979 if (server->socket >= 0)
1980 CLOSE_SOCKET(server->socket);
1981 free(server);
1982 if (next == started_at)
1983 break;
1984 server = next;
1986 server_head = NULL;
1987 global_good_nameservers = 0;
1989 while (req) {
1990 struct request *next = req->next;
1991 req->tx_count = req->reissue_count = 0;
1992 req->ns = NULL;
1993 /* ???? What to do about searches? */
1994 (void) evtimer_del(&req->timeout_event);
1995 req->trans_id = 0;
1996 req->transmit_me = 0;
1998 global_requests_waiting++;
1999 evdns_request_insert(req, &req_waiting_head);
2000 /* We want to insert these suspended elements at the front of
2001 * the waiting queue, since they were pending before any of
2002 * the waiting entries were added. This is a circular list,
2003 * so we can just shift the start back by one.*/
2004 req_waiting_head = req_waiting_head->prev;
2006 if (next == req_started_at)
2007 break;
2008 req = next;
2010 req_head = NULL;
2011 global_requests_inflight = 0;
2013 return 0;
2017 /* exported function */
2019 evdns_resume(void)
2021 evdns_requests_pump_waiting_queue();
2022 return 0;
2025 static int
2026 _evdns_nameserver_add_impl(unsigned long int address, int port) {
2027 /* first check to see if we already have this nameserver */
2029 const struct nameserver *server = server_head, *const started_at = server_head;
2030 struct nameserver *ns;
2031 struct sockaddr_in sin;
2032 int err = 0;
2033 if (server) {
2034 do {
2035 if (server->address == address) return 3;
2036 server = server->next;
2037 } while (server != started_at);
2040 ns = (struct nameserver *) malloc(sizeof(struct nameserver));
2041 if (!ns) return -1;
2043 memset(ns, 0, sizeof(struct nameserver));
2045 ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
2046 if (ns->socket < 0) { err = 1; goto out1; }
2047 #ifdef WIN32
2049 u_long nonblocking = 1;
2050 ioctlsocket(ns->socket, FIONBIO, &nonblocking);
2052 #else
2053 fcntl(ns->socket, F_SETFL, O_NONBLOCK);
2054 #endif
2055 sin.sin_addr.s_addr = address;
2056 sin.sin_port = htons(port);
2057 sin.sin_family = AF_INET;
2058 if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
2059 err = 2;
2060 goto out2;
2063 ns->address = address;
2064 ns->state = 1;
2065 event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
2066 if (event_add(&ns->event, NULL) < 0) {
2067 err = 2;
2068 goto out2;
2071 log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
2073 /* insert this nameserver into the list of them */
2074 if (!server_head) {
2075 ns->next = ns->prev = ns;
2076 server_head = ns;
2077 } else {
2078 ns->next = server_head->next;
2079 ns->prev = server_head;
2080 server_head->next = ns;
2081 if (server_head->prev == server_head) {
2082 server_head->prev = ns;
2086 global_good_nameservers++;
2088 return 0;
2090 out2:
2091 CLOSE_SOCKET(ns->socket);
2092 out1:
2093 free(ns);
2094 log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
2095 return err;
2098 /* exported function */
2100 evdns_nameserver_add(unsigned long int address) {
2101 return _evdns_nameserver_add_impl(address, 53);
2104 /* exported function */
2106 evdns_nameserver_ip_add(const char *ip_as_string) {
2107 struct in_addr ina;
2108 int port;
2109 char buf[20];
2110 const char *cp;
2111 cp = strchr(ip_as_string, ':');
2112 if (! cp) {
2113 cp = ip_as_string;
2114 port = 53;
2115 } else {
2116 port = strtoint(cp+1);
2117 if (port < 0 || port > 65535) {
2118 return 4;
2120 if ((cp-ip_as_string) >= (int)sizeof(buf)) {
2121 return 4;
2123 memcpy(buf, ip_as_string, cp-ip_as_string);
2124 buf[cp-ip_as_string] = '\0';
2125 cp = buf;
2127 if (!inet_aton(cp, &ina)) {
2128 return 4;
2130 return _evdns_nameserver_add_impl(ina.s_addr, port);
2133 /* insert into the tail of the queue */
2134 static void
2135 evdns_request_insert(struct request *req, struct request **head) {
2136 if (!*head) {
2137 *head = req;
2138 req->next = req->prev = req;
2139 return;
2142 req->prev = (*head)->prev;
2143 req->prev->next = req;
2144 req->next = *head;
2145 (*head)->prev = req;
2148 static int
2149 string_num_dots(const char *s) {
2150 int count = 0;
2151 while ((s = strchr(s, '.'))) {
2152 s++;
2153 count++;
2155 return count;
2158 static struct request *
2159 request_new(int type, const char *name, int flags,
2160 evdns_callback_type callback, void *user_ptr) {
2161 const char issuing_now =
2162 (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
2164 const int name_len = strlen(name);
2165 const int request_max_len = evdns_request_len(name_len);
2166 const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
2167 /* the request data is alloced in a single block with the header */
2168 struct request *const req =
2169 (struct request *) malloc(sizeof(struct request) + request_max_len);
2170 int rlen;
2171 (void) flags;
2173 if (!req) return NULL;
2174 memset(req, 0, sizeof(struct request));
2176 /* request data lives just after the header */
2177 req->request = ((u8 *) req) + sizeof(struct request);
2178 /* denotes that the request data shouldn't be free()ed */
2179 req->request_appended = 1;
2180 rlen = evdns_request_data_build(name, name_len, trans_id,
2181 type, CLASS_INET, req->request, request_max_len);
2182 if (rlen < 0)
2183 goto err1;
2184 req->request_len = rlen;
2185 req->trans_id = trans_id;
2186 req->tx_count = 0;
2187 req->request_type = type;
2188 req->user_pointer = user_ptr;
2189 req->user_callback = callback;
2190 req->ns = issuing_now ? nameserver_pick() : NULL;
2191 req->next = req->prev = NULL;
2193 return req;
2194 err1:
2195 free(req);
2196 return NULL;
2199 static void
2200 request_submit(struct request *const req) {
2201 if (req->ns) {
2202 /* if it has a nameserver assigned then this is going */
2203 /* straight into the inflight queue */
2204 evdns_request_insert(req, &req_head);
2205 global_requests_inflight++;
2206 evdns_request_transmit(req);
2207 } else {
2208 evdns_request_insert(req, &req_waiting_head);
2209 global_requests_waiting++;
2213 /* exported function */
2214 int evdns_resolve_ipv4(const char *name, int flags,
2215 evdns_callback_type callback, void *ptr) {
2216 log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2217 if (flags & DNS_QUERY_NO_SEARCH) {
2218 struct request *const req =
2219 request_new(TYPE_A, name, flags, callback, ptr);
2220 if (req == NULL)
2221 return (1);
2222 request_submit(req);
2223 return (0);
2224 } else {
2225 return (search_request_new(TYPE_A, name, flags, callback, ptr));
2229 /* exported function */
2230 int evdns_resolve_ipv6(const char *name, int flags,
2231 evdns_callback_type callback, void *ptr) {
2232 log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2233 if (flags & DNS_QUERY_NO_SEARCH) {
2234 struct request *const req =
2235 request_new(TYPE_AAAA, name, flags, callback, ptr);
2236 if (req == NULL)
2237 return (1);
2238 request_submit(req);
2239 return (0);
2240 } else {
2241 return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
2245 int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2246 char buf[32];
2247 struct request *req;
2248 u32 a;
2249 assert(in);
2250 a = ntohl(in->s_addr);
2251 snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
2252 (int)(u8)((a )&0xff),
2253 (int)(u8)((a>>8 )&0xff),
2254 (int)(u8)((a>>16)&0xff),
2255 (int)(u8)((a>>24)&0xff));
2256 log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2257 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2258 if (!req) return 1;
2259 request_submit(req);
2260 return 0;
2263 int evdns_resolve_reverse_ipv6(struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2264 char buf[64];
2265 char *cp;
2266 struct request *req;
2267 int i;
2268 assert(in);
2269 cp = buf;
2270 for (i=15; i >= 0; --i) {
2271 u8 byte = in->s6_addr[i];
2272 *cp++ = "0123456789abcdef"[byte & 0x0f];
2273 *cp++ = '.';
2274 *cp++ = "0123456789abcdef"[byte >> 4];
2275 *cp++ = '.';
2277 assert(cp + strlen(".ip6.arpa") < buf+sizeof(buf));
2278 memcpy(cp, ".ip6.arpa", strlen(".ip6.arpa")+1);
2279 log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2280 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2281 if (!req) return 1;
2282 request_submit(req);
2283 return 0;
2286 /*/////////////////////////////////////////////////////////////////// */
2287 /* Search support */
2288 /* */
2289 /* the libc resolver has support for searching a number of domains */
2290 /* to find a name. If nothing else then it takes the single domain */
2291 /* from the gethostname() call. */
2292 /* */
2293 /* It can also be configured via the domain and search options in a */
2294 /* resolv.conf. */
2295 /* */
2296 /* The ndots option controls how many dots it takes for the resolver */
2297 /* to decide that a name is non-local and so try a raw lookup first. */
2299 struct search_domain {
2300 int len;
2301 struct search_domain *next;
2302 /* the text string is appended to this structure */
2305 struct search_state {
2306 int refcount;
2307 int ndots;
2308 int num_domains;
2309 struct search_domain *head;
2312 static struct search_state *global_search_state = NULL;
2314 static void
2315 search_state_decref(struct search_state *const state) {
2316 if (!state) return;
2317 state->refcount--;
2318 if (!state->refcount) {
2319 struct search_domain *next, *dom;
2320 for (dom = state->head; dom; dom = next) {
2321 next = dom->next;
2322 free(dom);
2324 free(state);
2328 static struct search_state *
2329 search_state_new(void) {
2330 struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
2331 if (!state) return NULL;
2332 memset(state, 0, sizeof(struct search_state));
2333 state->refcount = 1;
2334 state->ndots = 1;
2336 return state;
2339 static void
2340 search_postfix_clear(void) {
2341 search_state_decref(global_search_state);
2343 global_search_state = search_state_new();
2346 /* exported function */
2347 void
2348 evdns_search_clear(void) {
2349 search_postfix_clear();
2352 static void
2353 search_postfix_add(const char *domain) {
2354 int domain_len;
2355 struct search_domain *sdomain;
2356 while (domain[0] == '.') domain++;
2357 domain_len = strlen(domain);
2359 if (!global_search_state) global_search_state = search_state_new();
2360 if (!global_search_state) return;
2361 global_search_state->num_domains++;
2363 sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
2364 if (!sdomain) return;
2365 memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
2366 sdomain->next = global_search_state->head;
2367 sdomain->len = domain_len;
2369 global_search_state->head = sdomain;
2372 /* reverse the order of members in the postfix list. This is needed because, */
2373 /* when parsing resolv.conf we push elements in the wrong order */
2374 static void
2375 search_reverse(void) {
2376 struct search_domain *cur, *prev = NULL, *next;
2377 cur = global_search_state->head;
2378 while (cur) {
2379 next = cur->next;
2380 cur->next = prev;
2381 prev = cur;
2382 cur = next;
2385 global_search_state->head = prev;
2388 /* exported function */
2389 void
2390 evdns_search_add(const char *domain) {
2391 search_postfix_add(domain);
2394 /* exported function */
2395 void
2396 evdns_search_ndots_set(const int ndots) {
2397 if (!global_search_state) global_search_state = search_state_new();
2398 if (!global_search_state) return;
2399 global_search_state->ndots = ndots;
2402 static void
2403 search_set_from_hostname(void) {
2404 char hostname[HOST_NAME_MAX + 1], *domainname;
2406 search_postfix_clear();
2407 if (gethostname(hostname, sizeof(hostname))) return;
2408 domainname = strchr(hostname, '.');
2409 if (!domainname) return;
2410 search_postfix_add(domainname);
2413 /* warning: returns malloced string */
2414 static char *
2415 search_make_new(const struct search_state *const state, int n, const char *const base_name) {
2416 const int base_len = strlen(base_name);
2417 const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
2418 struct search_domain *dom;
2420 for (dom = state->head; dom; dom = dom->next) {
2421 if (!n--) {
2422 /* this is the postfix we want */
2423 /* the actual postfix string is kept at the end of the structure */
2424 const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
2425 const int postfix_len = dom->len;
2426 char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
2427 if (!newname) return NULL;
2428 memcpy(newname, base_name, base_len);
2429 if (need_to_append_dot) newname[base_len] = '.';
2430 memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
2431 newname[base_len + need_to_append_dot + postfix_len] = 0;
2432 return newname;
2436 /* we ran off the end of the list and still didn't find the requested string */
2437 abort();
2438 return NULL; /* unreachable; stops warnings in some compilers. */
2441 static int
2442 search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
2443 assert(type == TYPE_A || type == TYPE_AAAA);
2444 if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
2445 global_search_state &&
2446 global_search_state->num_domains) {
2447 /* we have some domains to search */
2448 struct request *req;
2449 if (string_num_dots(name) >= global_search_state->ndots) {
2450 req = request_new(type, name, flags, user_callback, user_arg);
2451 if (!req) return 1;
2452 req->search_index = -1;
2453 } else {
2454 char *const new_name = search_make_new(global_search_state, 0, name);
2455 if (!new_name) return 1;
2456 req = request_new(type, new_name, flags, user_callback, user_arg);
2457 free(new_name);
2458 if (!req) return 1;
2459 req->search_index = 0;
2461 req->search_origname = strdup(name);
2462 req->search_state = global_search_state;
2463 req->search_flags = flags;
2464 global_search_state->refcount++;
2465 request_submit(req);
2466 return 0;
2467 } else {
2468 struct request *const req = request_new(type, name, flags, user_callback, user_arg);
2469 if (!req) return 1;
2470 request_submit(req);
2471 return 0;
2475 /* this is called when a request has failed to find a name. We need to check */
2476 /* if it is part of a search and, if so, try the next name in the list */
2477 /* returns: */
2478 /* 0 another request has been submitted */
2479 /* 1 no more requests needed */
2480 static int
2481 search_try_next(struct request *const req) {
2482 if (req->search_state) {
2483 /* it is part of a search */
2484 char *new_name;
2485 struct request *newreq;
2486 req->search_index++;
2487 if (req->search_index >= req->search_state->num_domains) {
2488 /* no more postfixes to try, however we may need to try */
2489 /* this name without a postfix */
2490 if (string_num_dots(req->search_origname) < req->search_state->ndots) {
2491 /* yep, we need to try it raw */
2492 struct request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
2493 log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
2494 if (newreq) {
2495 request_submit(newreq);
2496 return 0;
2499 return 1;
2502 new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
2503 if (!new_name) return 1;
2504 log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
2505 newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
2506 free(new_name);
2507 if (!newreq) return 1;
2508 newreq->search_origname = req->search_origname;
2509 req->search_origname = NULL;
2510 newreq->search_state = req->search_state;
2511 newreq->search_flags = req->search_flags;
2512 newreq->search_index = req->search_index;
2513 newreq->search_state->refcount++;
2514 request_submit(newreq);
2515 return 0;
2517 return 1;
2520 static void
2521 search_request_finished(struct request *const req) {
2522 if (req->search_state) {
2523 search_state_decref(req->search_state);
2524 req->search_state = NULL;
2526 if (req->search_origname) {
2527 free(req->search_origname);
2528 req->search_origname = NULL;
2532 /*/////////////////////////////////////////////////////////////////// */
2533 /* Parsing resolv.conf files */
2535 static void
2536 evdns_resolv_set_defaults(int flags) {
2537 /* if the file isn't found then we assume a local resolver */
2538 if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
2539 if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
2542 #ifndef HAVE_STRTOK_R
2543 static char *
2544 strtok_r(char *s, const char *delim, char **state) {
2545 return strtok(s, delim);
2547 #endif
2549 /* helper version of atoi which returns -1 on error */
2550 static int
2551 strtoint(const char *const str) {
2552 char *endptr;
2553 const int r = strtol(str, &endptr, 10);
2554 if (*endptr) return -1;
2555 return r;
2558 /* helper version of atoi that returns -1 on error and clips to bounds. */
2559 static int
2560 strtoint_clipped(const char *const str, int min, int max)
2562 int r = strtoint(str);
2563 if (r == -1)
2564 return r;
2565 else if (r<min)
2566 return min;
2567 else if (r>max)
2568 return max;
2569 else
2570 return r;
2573 /* exported function */
2575 evdns_set_option(const char *option, const char *val, int flags)
2577 if (!strncmp(option, "ndots:", 6)) {
2578 const int ndots = strtoint(val);
2579 if (ndots == -1) return -1;
2580 if (!(flags & DNS_OPTION_SEARCH)) return 0;
2581 log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
2582 if (!global_search_state) global_search_state = search_state_new();
2583 if (!global_search_state) return -1;
2584 global_search_state->ndots = ndots;
2585 } else if (!strncmp(option, "timeout:", 8)) {
2586 const int timeout = strtoint(val);
2587 if (timeout == -1) return -1;
2588 if (!(flags & DNS_OPTION_MISC)) return 0;
2589 log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
2590 global_timeout.tv_sec = timeout;
2591 } else if (!strncmp(option, "max-timeouts:", 12)) {
2592 const int maxtimeout = strtoint_clipped(val, 1, 255);
2593 if (maxtimeout == -1) return -1;
2594 if (!(flags & DNS_OPTION_MISC)) return 0;
2595 log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
2596 maxtimeout);
2597 global_max_nameserver_timeout = maxtimeout;
2598 } else if (!strncmp(option, "max-inflight:", 13)) {
2599 const int maxinflight = strtoint_clipped(val, 1, 65000);
2600 if (maxinflight == -1) return -1;
2601 if (!(flags & DNS_OPTION_MISC)) return 0;
2602 log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
2603 maxinflight);
2604 global_max_requests_inflight = maxinflight;
2605 } else if (!strncmp(option, "attempts:", 9)) {
2606 int retries = strtoint(val);
2607 if (retries == -1) return -1;
2608 if (retries > 255) retries = 255;
2609 if (!(flags & DNS_OPTION_MISC)) return 0;
2610 log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
2611 global_max_retransmits = retries;
2613 return 0;
2616 static void
2617 resolv_conf_parse_line(char *const start, int flags) {
2618 char *strtok_state;
2619 static const char *const delims = " \t";
2620 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
2622 char *const first_token = strtok_r(start, delims, &strtok_state);
2623 if (!first_token) return;
2625 if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
2626 const char *const nameserver = NEXT_TOKEN;
2627 struct in_addr ina;
2629 if (inet_aton(nameserver, &ina)) {
2630 /* address is valid */
2631 evdns_nameserver_add(ina.s_addr);
2633 } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
2634 const char *const domain = NEXT_TOKEN;
2635 if (domain) {
2636 search_postfix_clear();
2637 search_postfix_add(domain);
2639 } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
2640 const char *domain;
2641 search_postfix_clear();
2643 while ((domain = NEXT_TOKEN)) {
2644 search_postfix_add(domain);
2646 search_reverse();
2647 } else if (!strcmp(first_token, "options")) {
2648 const char *option;
2649 while ((option = NEXT_TOKEN)) {
2650 const char *val = strchr(option, ':');
2651 evdns_set_option(option, val ? val+1 : "", flags);
2654 #undef NEXT_TOKEN
2657 /* exported function */
2658 /* returns: */
2659 /* 0 no errors */
2660 /* 1 failed to open file */
2661 /* 2 failed to stat file */
2662 /* 3 file too large */
2663 /* 4 out of memory */
2664 /* 5 short read from file */
2666 evdns_resolv_conf_parse(int flags, const char *const filename) {
2667 struct stat st;
2668 int fd, n, r;
2669 u8 *resolv;
2670 char *start;
2671 int err = 0;
2673 log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
2675 fd = open(filename, O_RDONLY);
2676 if (fd < 0) {
2677 evdns_resolv_set_defaults(flags);
2678 return 1;
2681 if (fstat(fd, &st)) { err = 2; goto out1; }
2682 if (!st.st_size) {
2683 evdns_resolv_set_defaults(flags);
2684 err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
2685 goto out1;
2687 if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */
2689 resolv = (u8 *) malloc((size_t)st.st_size + 1);
2690 if (!resolv) { err = 4; goto out1; }
2692 n = 0;
2693 while ((r = read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
2694 n += r;
2695 if (n == st.st_size)
2696 break;
2697 assert(n < st.st_size);
2699 if (r < 0) { err = 5; goto out2; }
2700 resolv[n] = 0; /* we malloced an extra byte; this should be fine. */
2702 start = (char *) resolv;
2703 for (;;) {
2704 char *const newline = strchr(start, '\n');
2705 if (!newline) {
2706 resolv_conf_parse_line(start, flags);
2707 break;
2708 } else {
2709 *newline = 0;
2710 resolv_conf_parse_line(start, flags);
2711 start = newline + 1;
2715 if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
2716 /* no nameservers were configured. */
2717 evdns_nameserver_ip_add("127.0.0.1");
2718 err = 6;
2720 if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
2721 search_set_from_hostname();
2724 out2:
2725 free(resolv);
2726 out1:
2727 close(fd);
2728 return err;
2731 #ifdef WIN32
2732 /* Add multiple nameservers from a space-or-comma-separated list. */
2733 static int
2734 evdns_nameserver_ip_add_line(const char *ips) {
2735 const char *addr;
2736 char *buf;
2737 int r;
2738 while (*ips) {
2739 while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
2740 ++ips;
2741 addr = ips;
2742 while (ISDIGIT(*ips) || *ips == '.' || *ips == ':')
2743 ++ips;
2744 buf = malloc(ips-addr+1);
2745 if (!buf) return 4;
2746 memcpy(buf, addr, ips-addr);
2747 buf[ips-addr] = '\0';
2748 r = evdns_nameserver_ip_add(buf);
2749 free(buf);
2750 if (r) return r;
2752 return 0;
2755 typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
2757 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
2758 /* figure out what our nameservers are. */
2759 static int
2760 load_nameservers_with_getnetworkparams(void)
2762 /* Based on MSDN examples and inspection of c-ares code. */
2763 FIXED_INFO *fixed;
2764 HMODULE handle = 0;
2765 ULONG size = sizeof(FIXED_INFO);
2766 void *buf = NULL;
2767 int status = 0, r, added_any;
2768 IP_ADDR_STRING *ns;
2769 GetNetworkParams_fn_t fn;
2771 if (!(handle = LoadLibrary("iphlpapi.dll"))) {
2772 log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
2773 status = -1;
2774 goto done;
2776 if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
2777 log(EVDNS_LOG_WARN, "Could not get address of function.");
2778 status = -1;
2779 goto done;
2782 buf = malloc(size);
2783 if (!buf) { status = 4; goto done; }
2784 fixed = buf;
2785 r = fn(fixed, &size);
2786 if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
2787 status = -1;
2788 goto done;
2790 if (r != ERROR_SUCCESS) {
2791 free(buf);
2792 buf = malloc(size);
2793 if (!buf) { status = 4; goto done; }
2794 fixed = buf;
2795 r = fn(fixed, &size);
2796 if (r != ERROR_SUCCESS) {
2797 log(EVDNS_LOG_DEBUG, "fn() failed.");
2798 status = -1;
2799 goto done;
2803 assert(fixed);
2804 added_any = 0;
2805 ns = &(fixed->DnsServerList);
2806 while (ns) {
2807 r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
2808 if (r) {
2809 log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
2810 (ns->IpAddress.String),(int)GetLastError());
2811 status = r;
2812 goto done;
2813 } else {
2814 log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
2817 added_any++;
2818 ns = ns->Next;
2821 if (!added_any) {
2822 log(EVDNS_LOG_DEBUG, "No nameservers added.");
2823 status = -1;
2826 done:
2827 if (buf)
2828 free(buf);
2829 if (handle)
2830 FreeLibrary(handle);
2831 return status;
2834 static int
2835 config_nameserver_from_reg_key(HKEY key, const char *subkey)
2837 char *buf;
2838 DWORD bufsz = 0, type = 0;
2839 int status = 0;
2841 if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
2842 != ERROR_MORE_DATA)
2843 return -1;
2844 if (!(buf = malloc(bufsz)))
2845 return -1;
2847 if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
2848 == ERROR_SUCCESS && bufsz > 1) {
2849 status = evdns_nameserver_ip_add_line(buf);
2852 free(buf);
2853 return status;
2856 #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
2857 #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
2858 #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
2860 static int
2861 load_nameservers_from_registry(void)
2863 int found = 0;
2864 int r;
2865 #define TRY(k, name) \
2866 if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
2867 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
2868 found = 1; \
2869 } else if (!found) { \
2870 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
2871 #k,#name); \
2874 if (((int)GetVersion()) > 0) { /* NT */
2875 HKEY nt_key = 0, interfaces_key = 0;
2877 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
2878 KEY_READ, &nt_key) != ERROR_SUCCESS) {
2879 log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
2880 return -1;
2882 r = RegOpenKeyEx(nt_key, "Interfaces", 0,
2883 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
2884 &interfaces_key);
2885 if (r != ERROR_SUCCESS) {
2886 log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
2887 return -1;
2889 TRY(nt_key, "NameServer");
2890 TRY(nt_key, "DhcpNameServer");
2891 TRY(interfaces_key, "NameServer");
2892 TRY(interfaces_key, "DhcpNameServer");
2893 RegCloseKey(interfaces_key);
2894 RegCloseKey(nt_key);
2895 } else {
2896 HKEY win_key = 0;
2897 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
2898 KEY_READ, &win_key) != ERROR_SUCCESS) {
2899 log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
2900 return -1;
2902 TRY(win_key, "NameServer");
2903 RegCloseKey(win_key);
2906 if (found == 0) {
2907 log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
2910 return found ? 0 : -1;
2911 #undef TRY
2915 evdns_config_windows_nameservers(void)
2917 if (load_nameservers_with_getnetworkparams() == 0)
2918 return 0;
2919 return load_nameservers_from_registry();
2921 #endif
2924 evdns_init(void)
2926 int res = 0;
2927 #ifdef WIN32
2928 evdns_config_windows_nameservers();
2929 #else
2930 res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
2931 #endif
2933 return (res);
2936 const char *
2937 evdns_err_to_string(int err)
2939 switch (err) {
2940 case DNS_ERR_NONE: return "no error";
2941 case DNS_ERR_FORMAT: return "misformatted query";
2942 case DNS_ERR_SERVERFAILED: return "server failed";
2943 case DNS_ERR_NOTEXIST: return "name does not exist";
2944 case DNS_ERR_NOTIMPL: return "query not implemented";
2945 case DNS_ERR_REFUSED: return "refused";
2947 case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
2948 case DNS_ERR_UNKNOWN: return "unknown";
2949 case DNS_ERR_TIMEOUT: return "request timed out";
2950 case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
2951 default: return "[Unknown error code]";
2955 void
2956 evdns_shutdown(int fail_requests)
2958 struct nameserver *server, *server_next;
2959 struct search_domain *dom, *dom_next;
2961 while (req_head) {
2962 if (fail_requests)
2963 reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
2964 request_finished(req_head, &req_head);
2966 while (req_waiting_head) {
2967 if (fail_requests)
2968 reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
2969 request_finished(req_waiting_head, &req_waiting_head);
2971 global_requests_inflight = global_requests_waiting = 0;
2973 for (server = server_head; server; server = server_next) {
2974 server_next = server->next;
2975 if (server->socket >= 0)
2976 CLOSE_SOCKET(server->socket);
2977 (void) event_del(&server->event);
2978 if (server->state == 0)
2979 (void) event_del(&server->timeout_event);
2980 free(server);
2981 if (server_next == server_head)
2982 break;
2984 server_head = NULL;
2985 global_good_nameservers = 0;
2987 if (global_search_state) {
2988 for (dom = global_search_state->head; dom; dom = dom_next) {
2989 dom_next = dom->next;
2990 free(dom);
2992 free(global_search_state);
2993 global_search_state = NULL;
2995 evdns_log_fn = NULL;
2998 #ifdef EVDNS_MAIN
2999 void
3000 main_callback(int result, char type, int count, int ttl,
3001 void *addrs, void *orig) {
3002 char *n = (char*)orig;
3003 int i;
3004 for (i = 0; i < count; ++i) {
3005 if (type == DNS_IPv4_A) {
3006 printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
3007 } else if (type == DNS_PTR) {
3008 printf("%s: %s\n", n, ((char**)addrs)[i]);
3011 if (!count) {
3012 printf("%s: No answer (%d)\n", n, result);
3014 fflush(stdout);
3016 void
3017 evdns_server_callback(struct evdns_server_request *req, void *data)
3019 int i, r;
3020 (void)data;
3021 /* dummy; give 192.168.11.11 as an answer for all A questions,
3022 * give foo.bar.example.com as an answer for all PTR questions. */
3023 for (i = 0; i < req->nquestions; ++i) {
3024 u32 ans = htonl(0xc0a80b0bUL);
3025 if (req->questions[i]->type == EVDNS_TYPE_A &&
3026 req->questions[i]->class == EVDNS_CLASS_INET) {
3027 printf(" -- replying for %s (A)\n", req->questions[i]->name);
3028 r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
3029 1, &ans, 10);
3030 if (r<0)
3031 printf("eeep, didn't work.\n");
3032 } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
3033 req->questions[i]->class == EVDNS_CLASS_INET) {
3034 printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
3035 r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
3036 "foo.bar.example.com", 10);
3037 } else {
3038 printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
3039 req->questions[i]->type, req->questions[i]->class);
3043 r = evdns_request_respond(req, 0);
3044 if (r<0)
3045 printf("eeek, couldn't send reply.\n");
3048 void
3049 logfn(int is_warn, const char *msg) {
3050 (void) is_warn;
3051 fprintf(stderr, "%s\n", msg);
3054 main(int c, char **v) {
3055 int idx;
3056 int reverse = 0, verbose = 1, servertest = 0;
3057 if (c<2) {
3058 fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
3059 fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
3060 return 1;
3062 idx = 1;
3063 while (idx < c && v[idx][0] == '-') {
3064 if (!strcmp(v[idx], "-x"))
3065 reverse = 1;
3066 else if (!strcmp(v[idx], "-v"))
3067 verbose = 1;
3068 else if (!strcmp(v[idx], "-servertest"))
3069 servertest = 1;
3070 else
3071 fprintf(stderr, "Unknown option %s\n", v[idx]);
3072 ++idx;
3074 event_init();
3075 if (verbose)
3076 evdns_set_log_fn(logfn);
3077 evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
3078 if (servertest) {
3079 int sock;
3080 struct sockaddr_in my_addr;
3081 sock = socket(PF_INET, SOCK_DGRAM, 0);
3082 fcntl(sock, F_SETFL, O_NONBLOCK);
3083 my_addr.sin_family = AF_INET;
3084 my_addr.sin_port = htons(10053);
3085 my_addr.sin_addr.s_addr = INADDR_ANY;
3086 if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
3087 perror("bind");
3088 exit(1);
3090 evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
3092 for (; idx < c; ++idx) {
3093 if (reverse) {
3094 struct in_addr addr;
3095 if (!inet_aton(v[idx], &addr)) {
3096 fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
3097 continue;
3099 fprintf(stderr, "resolving %s...\n",v[idx]);
3100 evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
3101 } else {
3102 fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
3103 evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
3106 fflush(stdout);
3107 event_dispatch();
3108 return 0;
3110 #endif