1
/* $Id: evdns.c 6979 2006-08-04 18:31:13Z nickm $ */
3
/* The original version of this module was written by Adam Langley; for
4
* a history of modifications, check out the subversion logs.
6
* When editing this module, try to keep it re-mergeable by Adam. Don't
7
* reformat the whitespace, add Tor dependencies, or so on.
10
* - Support IPv6 and PTR records.
11
* - Replace all externally visible magic numbers with #defined constants.
12
* - Write doccumentation for APIs of all external functions.
16
* Adam Langley <agl@imperialviolet.org>
17
* http://www.imperialviolet.org/eventdns.html
20
* This software is Public Domain. To view a copy of the public domain dedication,
21
* visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
22
* Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
24
* I ask and expect, but do not require, that all derivative works contain an
25
* attribution similar to:
26
* Parts developed by Adam Langley <agl@imperialviolet.org>
28
* You may wish to replace the word "Parts" with something else depending on
29
* the amount of original code.
31
* (Derivative works does not include programs which link against, run or include
32
* the source verbatim in their source distributions)
37
#include <sys/types.h>
48
#ifndef DNS_USE_CPU_CLOCK_FOR_ID
49
#ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
50
#ifndef DNS_USE_OPENSSL_FOR_ID
51
#error Must configure at least one id generation method.
52
#error Please see the documentation.
57
/* #define _POSIX_C_SOURCE 200507 */
60
#ifdef DNS_USE_CPU_CLOCK_FOR_ID
61
#ifdef DNS_USE_OPENSSL_FOR_ID
62
#error Multiple id options selected
64
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
65
#error Multiple id options selected
70
#ifdef DNS_USE_OPENSSL_FOR_ID
71
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
72
#error Multiple id options selected
74
#include <openssl/rand.h>
77
#define _FORTIFY_SOURCE 3
101
#include <winsock2.h>
102
#include <iphlpapi.h>
104
#include <sys/socket.h>
105
#include <netinet/in.h>
106
#include <arpa/inet.h>
109
#ifdef HAVE_NETINET_IN6_H
110
#include <netinet/in6.h>
113
#define EVDNS_LOG_DEBUG 0
114
#define EVDNS_LOG_WARN 1
116
#ifndef HOST_NAME_MAX
117
#define HOST_NAME_MAX 255
125
#define MIN(a,b) ((a)<(b)?(a):(b))
128
/* libevent doesn't work without this */
129
typedef uint8_t u_char;
130
typedef unsigned int uint;
139
#define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
140
/* which we bother recording */
142
#define TYPE_A EVDNS_TYPE_A
144
#define TYPE_PTR EVDNS_TYPE_PTR
145
#define TYPE_AAAA EVDNS_TYPE_AAAA
147
#define CLASS_INET EVDNS_CLASS_INET
150
u8 *request; /* the dns packet data */
151
unsigned int request_len;
153
int tx_count; /* the number of times that this packet has been sent */
154
unsigned int request_type; /* TYPE_PTR or TYPE_A */
155
void *user_pointer; /* the pointer given to us for this request */
156
evdns_callback_type user_callback;
157
struct nameserver *ns; /* the server which we last sent it */
159
/* elements used by the searching code */
161
struct search_state *search_state;
162
char *search_origname; /* needs to be free()ed */
165
/* these objects are kept in a circular list */
166
struct request *next, *prev;
168
struct event timeout_event;
170
u16 trans_id; /* the transaction id */
171
char request_appended; /* true if the request pointer is data which follows this struct */
172
char transmit_me; /* needs to be transmitted */
175
#ifndef HAVE_STRUCT_IN6_ADDR
183
unsigned int have_answer;
187
u32 addresses[MAX_ADDRS];
191
struct in6_addr addresses[MAX_ADDRS];
194
char name[HOST_NAME_MAX];
200
int socket; /* a connected UDP socket */
202
int failed_times; /* number of times which we have given this server a chance */
203
int timedout; /* number of times in a row a request has timed out */
205
/* these objects are kept in a circular list */
206
struct nameserver *next, *prev;
207
struct event timeout_event; /* used to keep the timeout for */
208
/* when we next probe this server. */
209
/* Valid if state == 0 */
210
char state; /* zero if we think that this server is down */
211
char choked; /* true if we have an EAGAIN from this server's socket */
212
char write_waiting; /* true if we are waiting for EV_WRITE events */
215
static struct request *req_head = NULL, *req_waiting_head = NULL;
216
static struct nameserver *server_head = NULL;
218
/* Represents a local port where we're listening for DNS requests. Right now, */
219
/* only UDP is supported. */
220
struct evdns_server_port {
221
int socket; /* socket we use to read queries and write replies. */
222
int refcnt; /* reference count. */
223
char choked; /* Are we currently blocked from writing? */
224
char closing; /* Are we trying to close this port, pending writes? */
225
evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
226
void *user_data; /* Opaque pointer passed to user_callback */
227
struct event event; /* Read/write event */
228
/* circular list of replies that we want to write. */
229
struct server_request *pending_replies;
232
/* Represents part of a reply being built. (That is, a single RR.) */
233
struct server_reply_item {
234
struct server_reply_item *next; /* next item in sequence. */
235
char *name; /* name part of the RR */
236
u16 type : 16; /* The RR type */
237
u16 class : 16; /* The RR class (usually CLASS_INET) */
238
u32 ttl; /* The RR TTL */
239
char is_name; /* True iff data is a label */
240
u16 datalen; /* Length of data; -1 if data is a label */
241
void *data; /* The contents of the RR */
244
/* Represents a request that we've received as a DNS server, and holds */
245
/* the components of the reply as we're constructing it. */
246
struct server_request {
247
/* Pointers to the next and previous entries on the list of replies */
248
/* that we're waiting to write. Only set if we have tried to respond */
249
/* and gotten EAGAIN. */
250
struct server_request *next_pending;
251
struct server_request *prev_pending;
253
u16 trans_id; /* Transaction id. */
254
struct evdns_server_port *port; /* Which port received this request on? */
255
struct sockaddr_storage addr; /* Where to send the response */
256
socklen_t addrlen; /* length of addr */
258
int n_answer; /* how many answer RRs have been set? */
259
int n_authority; /* how many authority RRs have been set? */
260
int n_additional; /* how many additional RRs have been set? */
262
struct server_reply_item *answer; /* linked list of answer RRs */
263
struct server_reply_item *authority; /* linked list of authority RRs */
264
struct server_reply_item *additional; /* linked list of additional RRs */
266
/* Constructed response. Only set once we're ready to send a reply. */
267
/* Once this is set, the RR fields are cleared, and no more should be set. */
271
/* Caller-visible fields: flags, questions. */
272
struct evdns_server_request base;
276
#define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
278
/* Given a pointer to an evdns_server_request, get the corresponding */
279
/* server_request. */
280
#define TO_SERVER_REQUEST(base_ptr) \
281
((struct server_request*) \
282
(((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
284
/* The number of good nameservers that we have */
285
static int global_good_nameservers = 0;
287
/* inflight requests are contained in the req_head list */
288
/* and are actually going out across the network */
289
static int global_requests_inflight = 0;
290
/* requests which aren't inflight are in the waiting list */
291
/* and are counted here */
292
static int global_requests_waiting = 0;
294
static int global_max_requests_inflight = 64;
296
static struct timeval global_timeout = {5, 0}; /* 5 seconds */
297
static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */
298
static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */
299
/* number of timeouts in a row before we consider this server to be down */
300
static int global_max_nameserver_timeout = 3;
302
/* These are the timeout values for nameservers. If we find a nameserver is down */
303
/* we try to probe it at intervals as given below. Values are in seconds. */
304
static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
305
static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);
307
static struct nameserver *nameserver_pick(void);
308
static void evdns_request_insert(struct request *req, struct request **head);
309
static void nameserver_ready_callback(int fd, short events, void *arg);
310
static int evdns_transmit(void);
311
static int evdns_request_transmit(struct request *req);
312
static void nameserver_send_probe(struct nameserver *const ns);
313
static void search_request_finished(struct request *const);
314
static int search_try_next(struct request *const req);
315
static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
316
static void evdns_requests_pump_waiting_queue(void);
317
static u16 transaction_id_pick(void);
318
static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
319
static void request_submit(struct request *req);
321
static int server_request_free(struct server_request *req);
322
static void server_request_free_answers(struct server_request *req);
323
static void server_port_free(struct evdns_server_port *port);
324
static void server_port_ready_callback(int fd, short events, void *arg);
326
static int strtoint(const char *const str);
332
int optval, optvallen=sizeof(optval);
333
int err = WSAGetLastError();
334
if (err == WSAEWOULDBLOCK && sock >= 0) {
335
if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
345
error_is_eagain(int err)
347
return err == EAGAIN || err == WSAEWOULDBLOCK;
350
inet_aton(const char *c, struct in_addr *addr)
353
if (strcmp(c, "255.255.255.255") == 0) {
354
addr->s_addr = 0xffffffffu;
357
if (r == INADDR_NONE)
364
#define last_error(sock) (errno)
365
#define error_is_eagain(err) ((err) == EAGAIN)
367
#define CLOSE_SOCKET(s) EVUTIL_CLOSESOCKET(s)
369
#define ISSPACE(c) isspace((int)(unsigned char)(c))
370
#define ISDIGIT(c) isdigit((int)(unsigned char)(c))
374
debug_ntoa(u32 address)
377
u32 a = ntohl(address);
378
snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
379
(int)(u8)((a>>24)&0xff),
380
(int)(u8)((a>>16)&0xff),
381
(int)(u8)((a>>8 )&0xff),
382
(int)(u8)((a )&0xff));
387
static evdns_debug_log_fn_type evdns_log_fn = NULL;
390
evdns_set_log_fn(evdns_debug_log_fn_type fn)
396
#define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
398
#define EVDNS_LOG_CHECK
401
static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
403
_evdns_log(int warn, const char *fmt, ...)
406
static char buf[512];
411
_vsnprintf(buf, sizeof(buf), fmt, args);
413
vsnprintf(buf, sizeof(buf), fmt, args);
415
buf[sizeof(buf)-1] = '\0';
416
evdns_log_fn(warn, buf);
420
#define log _evdns_log
422
/* This walks the list of inflight requests to find the */
423
/* one with a matching transaction id. Returns NULL on */
425
static struct request *
426
request_find_from_trans_id(u16 trans_id) {
427
struct request *req = req_head, *const started_at = req_head;
431
if (req->trans_id == trans_id) return req;
433
} while (req != started_at);
439
/* a libevent callback function which is called when a nameserver */
440
/* has gone down and we want to test if it has came back to life yet */
442
nameserver_prod_callback(int fd, short events, void *arg) {
443
struct nameserver *const ns = (struct nameserver *) arg;
447
nameserver_send_probe(ns);
450
/* a libevent callback which is called when a nameserver probe (to see if */
451
/* it has come back to life) times out. We increment the count of failed_times */
452
/* and wait longer to send the next probe packet. */
454
nameserver_probe_failed(struct nameserver *const ns) {
455
const struct timeval * timeout;
456
(void) evtimer_del(&ns->timeout_event);
457
if (ns->state == 1) {
458
/* This can happen if the nameserver acts in a way which makes us mark */
459
/* it as bad and then starts sending good replies. */
464
&global_nameserver_timeouts[MIN(ns->failed_times,
465
global_nameserver_timeouts_length - 1)];
468
evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
469
if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
471
"Error from libevent when adding timer event for %s",
472
debug_ntoa(ns->address));
477
/* called when a nameserver has been deemed to have failed. For example, too */
478
/* many packets have timed out etc */
480
nameserver_failed(struct nameserver *const ns, const char *msg) {
481
struct request *req, *started_at;
482
/* if this nameserver has already been marked as failed */
483
/* then don't do anything */
484
if (!ns->state) return;
486
log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
487
debug_ntoa(ns->address), msg);
488
global_good_nameservers--;
489
assert(global_good_nameservers >= 0);
490
if (global_good_nameservers == 0) {
491
log(EVDNS_LOG_WARN, "All nameservers have failed");
495
ns->failed_times = 1;
497
evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
498
if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
500
"Error from libevent when adding timer event for %s",
501
debug_ntoa(ns->address));
505
/* walk the list of inflight requests to see if any can be reassigned to */
506
/* a different server. Requests in the waiting queue don't have a */
507
/* nameserver assigned yet */
509
/* if we don't have *any* good nameservers then there's no point */
510
/* trying to reassign requests to one */
511
if (!global_good_nameservers) return;
514
started_at = req_head;
517
if (req->tx_count == 0 && req->ns == ns) {
518
/* still waiting to go out, can be moved */
519
/* to another server */
520
req->ns = nameserver_pick();
523
} while (req != started_at);
528
nameserver_up(struct nameserver *const ns) {
529
if (ns->state) return;
530
log(EVDNS_LOG_WARN, "Nameserver %s is back up",
531
debug_ntoa(ns->address));
532
evtimer_del(&ns->timeout_event);
534
ns->failed_times = 0;
536
global_good_nameservers++;
540
request_trans_id_set(struct request *const req, const u16 trans_id) {
541
req->trans_id = trans_id;
542
*((u16 *) req->request) = htons(trans_id);
545
/* Called to remove a request from a list and dealloc it. */
546
/* head is a pointer to the head of the list it should be */
547
/* removed from or NULL if the request isn't in a list. */
549
request_finished(struct request *const req, struct request **head) {
551
if (req->next == req) {
552
/* only item in the list */
555
req->next->prev = req->prev;
556
req->prev->next = req->next;
557
if (*head == req) *head = req->next;
561
log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
562
(unsigned long) req);
563
evtimer_del(&req->timeout_event);
565
search_request_finished(req);
566
global_requests_inflight--;
568
if (!req->request_appended) {
569
/* need to free the request data on it's own */
572
/* the request data is appended onto the header */
573
/* so everything gets free()ed when we: */
578
evdns_requests_pump_waiting_queue();
581
/* This is called when a server returns a funny error code. */
582
/* We try the request again with another server. */
586
/* 1 failed/reissue is pointless */
588
request_reissue(struct request *req) {
589
const struct nameserver *const last_ns = req->ns;
590
/* the last nameserver should have been marked as failing */
591
/* by the caller of this function, therefore pick will try */
592
/* not to return it */
593
req->ns = nameserver_pick();
594
if (req->ns == last_ns) {
595
/* ... but pick did return it */
596
/* not a lot of point in trying again with the */
601
req->reissue_count++;
603
req->transmit_me = 1;
608
/* this function looks for space on the inflight queue and promotes */
609
/* requests from the waiting queue if it can. */
611
evdns_requests_pump_waiting_queue(void) {
612
while (global_requests_inflight < global_max_requests_inflight &&
613
global_requests_waiting) {
615
/* move a request from the waiting queue to the inflight queue */
616
assert(req_waiting_head);
617
if (req_waiting_head->next == req_waiting_head) {
618
/* only one item in the queue */
619
req = req_waiting_head;
620
req_waiting_head = NULL;
622
req = req_waiting_head;
623
req->next->prev = req->prev;
624
req->prev->next = req->next;
625
req_waiting_head = req->next;
628
global_requests_waiting--;
629
global_requests_inflight++;
631
req->ns = nameserver_pick();
632
request_trans_id_set(req, transaction_id_pick());
634
evdns_request_insert(req, &req_head);
635
evdns_request_transmit(req);
641
reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
642
switch (req->request_type) {
645
req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
646
reply->data.a.addrcount, ttl,
647
reply->data.a.addresses,
650
req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
654
char *name = reply->data.ptr.name;
655
req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
656
&name, req->user_pointer);
658
req->user_callback(err, 0, 0, 0, NULL,
664
req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
665
reply->data.aaaa.addrcount, ttl,
666
reply->data.aaaa.addresses,
669
req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
675
/* this processes a parsed reply packet */
677
reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
679
static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
681
if (flags & 0x020f || !reply || !reply->have_answer) {
682
/* there was an error */
683
if (flags & 0x0200) {
684
error = DNS_ERR_TRUNCATED;
686
u16 error_code = (flags & 0x000f) - 1;
687
if (error_code > 4) {
688
error = DNS_ERR_UNKNOWN;
690
error = error_codes[error_code];
695
case DNS_ERR_NOTIMPL:
696
case DNS_ERR_REFUSED:
697
/* we regard these errors as marking a bad nameserver */
698
if (req->reissue_count < global_max_reissues) {
700
snprintf(msg, sizeof(msg), "Bad response %d (%s)",
701
error, evdns_err_to_string(error));
702
nameserver_failed(req->ns, msg);
703
if (!request_reissue(req)) return;
706
case DNS_ERR_SERVERFAILED:
707
/* rcode 2 (servfailed) sometimes means "we are broken" and
708
* sometimes (with some binds) means "that request was very
709
* confusing." Treat this as a timeout, not a failure.
711
log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
712
"will allow the request to time out.",
713
debug_ntoa(req->ns->address));
716
/* we got a good reply from the nameserver */
717
nameserver_up(req->ns);
720
if (req->search_state && req->request_type != TYPE_PTR) {
721
/* if we have a list of domains to search in, try the next one */
722
if (!search_try_next(req)) {
723
/* a new request was issued so this request is finished and */
724
/* the user callback will be made when that request (or a */
725
/* child of it) finishes. */
726
request_finished(req, &req_head);
731
/* all else failed. Pass the failure up */
732
reply_callback(req, 0, error, NULL);
733
request_finished(req, &req_head);
735
/* all ok, tell the user */
736
reply_callback(req, ttl, 0, reply);
737
nameserver_up(req->ns);
738
request_finished(req, &req_head);
743
name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
747
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
748
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
749
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
752
const char *const end = name_out + name_out_len;
754
/* Normally, names are a series of length prefixed strings terminated */
755
/* with a length of 0 (the lengths are u8's < 63). */
756
/* However, the length can start with a pair of 1 bits and that */
757
/* means that the next 14 bits are a pointer within the current */
762
if (j >= length) return -1;
764
if (!label_len) break;
765
if (label_len & 0xc0) {
768
if (name_end < 0) name_end = j;
769
j = (((int)label_len & 0x3f) << 8) + ptr_low;
770
/* Make sure that the target offset is in-bounds. */
771
if (j < 0 || j >= length) return -1;
772
/* If we've jumped more times than there are characters in the
773
* message, we must have a loop. */
774
if (++ptr_count > length) return -1;
777
if (label_len > 63) return -1;
778
if (cp != name_out) {
779
if (cp + 1 >= end) return -1;
782
if (cp + label_len >= end) return -1;
783
memcpy(cp, packet + j, label_len);
787
if (cp >= end) return -1;
798
/* parses a raw request from a nameserver */
800
reply_parse(u8 *packet, int length) {
801
int j = 0; /* index into packet */
802
u16 _t; /* used by the macros */
803
u32 _t32; /* used by the macros */
804
char tmp_name[256]; /* used by the macros */
806
u16 trans_id, questions, answers, authority, additional, datalength;
808
u32 ttl, ttl_r = 0xffffffff;
810
struct request *req = NULL;
819
(void) authority; /* suppress "unused variable" warnings. */
820
(void) additional; /* suppress "unused variable" warnings. */
822
req = request_find_from_trans_id(trans_id);
825
memset(&reply, 0, sizeof(reply));
827
/* If it's not an answer, it doesn't correspond to any request. */
828
if (!(flags & 0x8000)) return -1; /* must be an answer */
829
if (flags & 0x020f) {
830
/* there was an error */
833
/* if (!answers) return; */ /* must have an answer of some form */
835
/* This macro skips a name in the DNS reply. */
837
do { tmp_name[0] = '\0'; \
838
if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
842
reply.type = req->request_type;
844
/* skip over each question in the reply */
845
for (i = 0; i < questions; ++i) {
846
/* the question looks like
847
* <label:name><u16:type><u16:class>
851
if (j >= length) goto err;
854
/* now we have the answer section which looks like
855
* <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
858
for (i = 0; i < answers; ++i) {
867
if (type == TYPE_A && class == CLASS_INET) {
868
int addrcount, addrtocopy;
869
if (req->request_type != TYPE_A) {
870
j += datalength; continue;
872
if ((datalength & 3) != 0) /* not an even number of As. */
874
addrcount = datalength >> 2;
875
addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
877
ttl_r = MIN(ttl_r, ttl);
878
/* we only bother with the first four addresses. */
879
if (j + 4*addrtocopy > length) goto err;
880
memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
881
packet + j, 4*addrtocopy);
883
reply.data.a.addrcount += addrtocopy;
884
reply.have_answer = 1;
885
if (reply.data.a.addrcount == MAX_ADDRS) break;
886
} else if (type == TYPE_PTR && class == CLASS_INET) {
887
if (req->request_type != TYPE_PTR) {
888
j += datalength; continue;
890
if (name_parse(packet, length, &j, reply.data.ptr.name,
891
sizeof(reply.data.ptr.name))<0)
893
ttl_r = MIN(ttl_r, ttl);
894
reply.have_answer = 1;
896
} else if (type == TYPE_AAAA && class == CLASS_INET) {
897
int addrcount, addrtocopy;
898
if (req->request_type != TYPE_AAAA) {
899
j += datalength; continue;
901
if ((datalength & 15) != 0) /* not an even number of AAAAs. */
903
addrcount = datalength >> 4; /* each address is 16 bytes long */
904
addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
905
ttl_r = MIN(ttl_r, ttl);
907
/* we only bother with the first four addresses. */
908
if (j + 16*addrtocopy > length) goto err;
909
memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
910
packet + j, 16*addrtocopy);
911
reply.data.aaaa.addrcount += addrtocopy;
913
reply.have_answer = 1;
914
if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
916
/* skip over any other type of resource */
921
reply_handle(req, flags, ttl_r, &reply);
925
reply_handle(req, flags, 0, NULL);
929
/* Parse a raw request (packet,length) sent to a nameserver port (port) from */
930
/* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
933
request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
935
int j = 0; /* index into packet */
936
u16 _t; /* used by the macros */
937
char tmp_name[256]; /* used by the macros */
940
u16 trans_id, flags, questions, answers, authority, additional;
941
struct server_request *server_req = NULL;
943
/* Get the header fields */
951
if (flags & 0x8000) return -1; /* Must not be an answer. */
952
flags &= 0x0110; /* Only RD and CD get preserved. */
954
server_req = malloc(sizeof(struct server_request));
955
if (server_req == NULL) return -1;
956
memset(server_req, 0, sizeof(struct server_request));
958
server_req->trans_id = trans_id;
959
memcpy(&server_req->addr, addr, addrlen);
960
server_req->addrlen = addrlen;
962
server_req->base.flags = flags;
963
server_req->base.nquestions = 0;
964
server_req->base.questions = malloc(sizeof(struct evdns_server_question *) * questions);
965
if (server_req->base.questions == NULL)
968
for (i = 0; i < questions; ++i) {
970
struct evdns_server_question *q;
972
if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
976
namelen = strlen(tmp_name);
977
q = malloc(sizeof(struct evdns_server_question) + namelen);
982
memcpy(q->name, tmp_name, namelen+1);
983
server_req->base.questions[server_req->base.nquestions++] = q;
986
/* Ignore answers, authority, and additional. */
988
server_req->port = port;
991
/* Only standard queries are supported. */
992
if (flags & 0x7800) {
993
evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
997
port->user_callback(&(server_req->base), port->user_data);
1002
if (server_req->base.questions) {
1003
for (i = 0; i < server_req->base.nquestions; ++i)
1004
free(server_req->base.questions[i]);
1005
free(server_req->base.questions);
1018
default_transaction_id_fn(void)
1021
#ifdef DNS_USE_CPU_CLOCK_FOR_ID
1023
#ifdef CLOCK_MONOTONIC
1024
if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
1026
if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
1028
event_err(1, "clock_gettime");
1029
trans_id = ts.tv_nsec & 0xffff;
1032
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
1034
gettimeofday(&tv, NULL);
1035
trans_id = tv.tv_usec & 0xffff;
1038
#ifdef DNS_USE_OPENSSL_FOR_ID
1039
if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
1040
/* in the case that the RAND call fails we back */
1041
/* down to using gettimeofday. */
1044
gettimeofday(&tv, NULL);
1045
trans_id = tv.tv_usec & 0xffff;
1053
static uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
1056
evdns_set_transaction_id_fn(uint16_t (*fn)(void))
1059
trans_id_function = fn;
1061
trans_id_function = default_transaction_id_fn;
1064
/* Try to choose a strong transaction id which isn't already in flight */
1066
transaction_id_pick(void) {
1068
const struct request *req = req_head, *started_at;
1069
u16 trans_id = trans_id_function();
1071
if (trans_id == 0xffff) continue;
1072
/* now check to see if that id is already inflight */
1073
req = started_at = req_head;
1076
if (req->trans_id == trans_id) break;
1078
} while (req != started_at);
1080
/* we didn't find it, so this is a good id */
1081
if (req == started_at) return trans_id;
1085
/* choose a namesever to use. This function will try to ignore */
1086
/* nameservers which we think are down and load balance across the rest */
1087
/* by updating the server_head global each time. */
1088
static struct nameserver *
1089
nameserver_pick(void) {
1090
struct nameserver *started_at = server_head, *picked;
1091
if (!server_head) return NULL;
1093
/* if we don't have any good nameservers then there's no */
1094
/* point in trying to find one. */
1095
if (!global_good_nameservers) {
1096
server_head = server_head->next;
1100
/* remember that nameservers are in a circular list */
1102
if (server_head->state) {
1103
/* we think this server is currently good */
1104
picked = server_head;
1105
server_head = server_head->next;
1109
server_head = server_head->next;
1110
if (server_head == started_at) {
1111
/* all the nameservers seem to be down */
1112
/* so we just return this one and hope for the */
1114
assert(global_good_nameservers == 0);
1115
picked = server_head;
1116
server_head = server_head->next;
1122
/* this is called when a namesever socket is ready for reading */
1124
nameserver_read(struct nameserver *ns) {
1128
const int r = recv(ns->socket, packet, sizeof(packet), 0);
1130
int err = last_error(ns->socket);
1131
if (error_is_eagain(err)) return;
1132
nameserver_failed(ns, strerror(err));
1136
reply_parse(packet, r);
1140
/* Read a packet from a DNS client on a server port s, parse it, and */
1141
/* act accordingly. */
1143
server_port_read(struct evdns_server_port *s) {
1145
struct sockaddr_storage addr;
1150
addrlen = sizeof(struct sockaddr_storage);
1151
r = recvfrom(s->socket, packet, sizeof(packet), 0,
1152
(struct sockaddr*) &addr, &addrlen);
1154
int err = last_error(s->socket);
1155
if (error_is_eagain(err)) return;
1156
log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
1157
strerror(err), err);
1160
request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
1164
/* Try to write all pending replies on a given DNS server port. */
1166
server_port_flush(struct evdns_server_port *port)
1168
while (port->pending_replies) {
1169
struct server_request *req = port->pending_replies;
1170
int r = sendto(port->socket, req->response, req->response_len, 0,
1171
(struct sockaddr*) &req->addr, req->addrlen);
1173
int err = last_error(port->socket);
1174
if (error_is_eagain(err))
1176
log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
1178
if (server_request_free(req)) {
1179
/* we released the last reference to req->port. */
1184
/* We have no more pending requests; stop listening for 'writeable' events. */
1185
(void) event_del(&port->event);
1186
event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1187
server_port_ready_callback, port);
1188
if (event_add(&port->event, NULL) < 0) {
1189
log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
1194
/* set if we are waiting for the ability to write to this server. */
1195
/* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1196
/* we stop these events. */
1198
nameserver_write_waiting(struct nameserver *ns, char waiting) {
1199
if (ns->write_waiting == waiting) return;
1201
ns->write_waiting = waiting;
1202
(void) event_del(&ns->event);
1203
event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1204
nameserver_ready_callback, ns);
1205
if (event_add(&ns->event, NULL) < 0) {
1206
log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
1207
debug_ntoa(ns->address));
1212
/* a callback function. Called by libevent when the kernel says that */
1213
/* a nameserver socket is ready for writing or reading */
1215
nameserver_ready_callback(int fd, short events, void *arg) {
1216
struct nameserver *ns = (struct nameserver *) arg;
1219
if (events & EV_WRITE) {
1221
if (!evdns_transmit()) {
1222
nameserver_write_waiting(ns, 0);
1225
if (events & EV_READ) {
1226
nameserver_read(ns);
1230
/* a callback function. Called by libevent when the kernel says that */
1231
/* a server socket is ready for writing or reading. */
1233
server_port_ready_callback(int fd, short events, void *arg) {
1234
struct evdns_server_port *port = (struct evdns_server_port *) arg;
1237
if (events & EV_WRITE) {
1239
server_port_flush(port);
1241
if (events & EV_READ) {
1242
server_port_read(port);
1246
/* This is an inefficient representation; only use it via the dnslabel_table_*
1247
* functions, so that is can be safely replaced with something smarter later. */
1248
#define MAX_LABELS 128
1249
/* Structures used to implement name compression */
1250
struct dnslabel_entry { char *v; off_t pos; };
1251
struct dnslabel_table {
1252
int n_labels; /* number of current entries */
1253
/* map from name to position in message */
1254
struct dnslabel_entry labels[MAX_LABELS];
1257
/* Initialize dnslabel_table. */
1259
dnslabel_table_init(struct dnslabel_table *table)
1261
table->n_labels = 0;
1264
/* Free all storage held by table, but not the table itself. */
1266
dnslabel_clear(struct dnslabel_table *table)
1269
for (i = 0; i < table->n_labels; ++i)
1270
free(table->labels[i].v);
1271
table->n_labels = 0;
1274
/* return the position of the label in the current message, or -1 if the label */
1275
/* hasn't been used yet. */
1277
dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
1280
for (i = 0; i < table->n_labels; ++i) {
1281
if (!strcmp(label, table->labels[i].v))
1282
return table->labels[i].pos;
1287
/* remember that we've used the label at position pos */
1289
dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
1293
if (table->n_labels == MAX_LABELS)
1298
p = table->n_labels++;
1299
table->labels[p].v = v;
1300
table->labels[p].pos = pos;
1305
/* Converts a string to a length-prefixed set of DNS labels, starting */
1306
/* at buf[j]. name and buf must not overlap. name_len should be the length */
1307
/* of name. table is optional, and is used for compression. */
1309
/* Input: abc.def */
1310
/* Output: <3>abc<3>def<0> */
1312
/* Returns the first index after the encoded name, or negative on error. */
1313
/* -1 label was > 63 bytes */
1314
/* -2 name too long to fit in buffer. */
1317
dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
1318
const char *name, const int name_len,
1319
struct dnslabel_table *table) {
1320
const char *end = name + name_len;
1324
#define APPEND16(x) do { \
1325
if (j + 2 > (off_t)buf_len) \
1328
memcpy(buf + j, &_t, 2); \
1331
#define APPEND32(x) do { \
1332
if (j + 4 > (off_t)buf_len) \
1335
memcpy(buf + j, &_t32, 4); \
1339
if (name_len > 255) return -2;
1342
const char *const start = name;
1343
if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1344
APPEND16(ref | 0xc000);
1347
name = strchr(name, '.');
1349
const unsigned int label_len = end - start;
1350
if (label_len > 63) return -1;
1351
if ((size_t)(j+label_len+1) > buf_len) return -2;
1352
if (table) dnslabel_table_add(table, start, j);
1353
buf[j++] = label_len;
1355
memcpy(buf + j, start, end - start);
1359
/* append length of the label. */
1360
const unsigned int label_len = name - start;
1361
if (label_len > 63) return -1;
1362
if ((size_t)(j+label_len+1) > buf_len) return -2;
1363
if (table) dnslabel_table_add(table, start, j);
1364
buf[j++] = label_len;
1366
memcpy(buf + j, start, name - start);
1368
/* hop over the '.' */
1373
/* the labels must be terminated by a 0. */
1374
/* It's possible that the name ended in a . */
1375
/* in which case the zero is already there */
1376
if (!j || buf[j-1]) buf[j++] = 0;
1382
/* Finds the length of a dns request for a DNS name of the given */
1383
/* length. The actual request may be smaller than the value returned */
1386
evdns_request_len(const int name_len) {
1387
return 96 + /* length of the DNS standard header */
1389
4; /* space for the resource type */
1392
/* build a dns request packet into buf. buf should be at least as long */
1393
/* as evdns_request_len told you it should be. */
1395
/* Returns the amount of space used. Negative on error. */
1397
evdns_request_data_build(const char *const name, const int name_len,
1398
const u16 trans_id, const u16 type, const u16 class,
1399
u8 *const buf, size_t buf_len) {
1400
off_t j = 0; /* current offset into buf */
1401
u16 _t; /* used by the macros */
1404
APPEND16(0x0100); /* standard query, recusion needed */
1405
APPEND16(1); /* one question */
1406
APPEND16(0); /* no answers */
1407
APPEND16(0); /* no authority */
1408
APPEND16(0); /* no additional */
1410
j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1423
/* exported function */
1424
struct evdns_server_port *
1425
evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
1427
struct evdns_server_port *port;
1428
if (!(port = malloc(sizeof(struct evdns_server_port))))
1430
memset(port, 0, sizeof(struct evdns_server_port));
1432
assert(!is_tcp); /* TCP sockets not yet implemented */
1433
port->socket = socket;
1437
port->user_callback = cb;
1438
port->user_data = user_data;
1439
port->pending_replies = NULL;
1441
event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1442
server_port_ready_callback, port);
1443
event_add(&port->event, NULL); /* check return. */
1447
/* exported function */
1449
evdns_close_server_port(struct evdns_server_port *port)
1451
if (--port->refcnt == 0)
1452
server_port_free(port);
1456
/* exported function */
1458
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)
1460
struct server_request *req = TO_SERVER_REQUEST(_req);
1461
struct server_reply_item **itemp, *item;
1464
if (req->response) /* have we already answered? */
1468
case EVDNS_ANSWER_SECTION:
1469
itemp = &req->answer;
1470
countp = &req->n_answer;
1472
case EVDNS_AUTHORITY_SECTION:
1473
itemp = &req->authority;
1474
countp = &req->n_authority;
1476
case EVDNS_ADDITIONAL_SECTION:
1477
itemp = &req->additional;
1478
countp = &req->n_additional;
1484
itemp = &((*itemp)->next);
1486
item = malloc(sizeof(struct server_reply_item));
1490
if (!(item->name = strdup(name))) {
1495
item->class = class;
1497
item->is_name = is_name != 0;
1501
if (item->is_name) {
1502
if (!(item->data = strdup(data))) {
1507
item->datalen = (u16)-1;
1509
if (!(item->data = malloc(datalen))) {
1514
item->datalen = datalen;
1515
memcpy(item->data, data, datalen);
1524
/* exported function */
1526
evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1528
return evdns_server_request_add_reply(
1529
req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1530
ttl, n*4, 0, addrs);
1533
/* exported function */
1535
evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1537
return evdns_server_request_add_reply(
1538
req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1539
ttl, n*16, 0, addrs);
1542
/* exported function */
1544
evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
1548
assert(in || inaddr_name);
1549
assert(!(in && inaddr_name));
1551
a = ntohl(in->s_addr);
1552
snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
1553
(int)(u8)((a )&0xff),
1554
(int)(u8)((a>>8 )&0xff),
1555
(int)(u8)((a>>16)&0xff),
1556
(int)(u8)((a>>24)&0xff));
1559
return evdns_server_request_add_reply(
1560
req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1561
ttl, -1, 1, hostname);
1564
/* exported function */
1566
evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
1568
return evdns_server_request_add_reply(
1569
req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1575
evdns_server_request_format_response(struct server_request *req, int err)
1577
unsigned char buf[1500];
1578
size_t buf_len = sizeof(buf);
1584
struct dnslabel_table table;
1586
if (err < 0 || err > 15) return -1;
1588
/* Set response bit and error code; copy OPCODE and RD fields from
1589
* question; copy RA and AA if set by caller. */
1590
flags = req->base.flags;
1591
flags |= (0x8000 | err);
1593
dnslabel_table_init(&table);
1594
APPEND16(req->trans_id);
1596
APPEND16(req->base.nquestions);
1597
APPEND16(req->n_answer);
1598
APPEND16(req->n_authority);
1599
APPEND16(req->n_additional);
1601
/* Add questions. */
1602
for (i=0; i < req->base.nquestions; ++i) {
1603
const char *s = req->base.questions[i]->name;
1604
j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1606
dnslabel_clear(&table);
1609
APPEND16(req->base.questions[i]->type);
1610
APPEND16(req->base.questions[i]->class);
1613
/* Add answer, authority, and additional sections. */
1614
for (i=0; i<3; ++i) {
1615
struct server_reply_item *item;
1619
item = req->authority;
1621
item = req->additional;
1623
r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1628
APPEND16(item->type);
1629
APPEND16(item->class);
1630
APPEND32(item->ttl);
1631
if (item->is_name) {
1632
off_t len_idx = j, name_start;
1635
r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1639
_t = htons( (j-name_start) );
1640
memcpy(buf+len_idx, &_t, 2);
1642
APPEND16(item->datalen);
1643
if (j+item->datalen > (off_t)buf_len)
1645
memcpy(buf+j, item->data, item->datalen);
1655
buf[3] |= 0x02; /* set the truncated bit. */
1658
req->response_len = j;
1660
if (!(req->response = malloc(req->response_len))) {
1661
server_request_free_answers(req);
1662
dnslabel_clear(&table);
1665
memcpy(req->response, buf, req->response_len);
1666
server_request_free_answers(req);
1667
dnslabel_clear(&table);
1671
/* exported function */
1673
evdns_server_request_respond(struct evdns_server_request *_req, int err)
1675
struct server_request *req = TO_SERVER_REQUEST(_req);
1676
struct evdns_server_port *port = req->port;
1678
if (!req->response) {
1679
if ((r = evdns_server_request_format_response(req, err))<0)
1683
r = sendto(port->socket, req->response, req->response_len, 0,
1684
(struct sockaddr*) &req->addr, req->addrlen);
1686
int err = last_error(port->socket);
1687
if (! error_is_eagain(err))
1690
if (port->pending_replies) {
1691
req->prev_pending = port->pending_replies->prev_pending;
1692
req->next_pending = port->pending_replies;
1693
req->prev_pending->next_pending =
1694
req->next_pending->prev_pending = req;
1696
req->prev_pending = req->next_pending = req;
1697
port->pending_replies = req;
1700
(void) event_del(&port->event);
1701
event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
1703
if (event_add(&port->event, NULL) < 0) {
1704
log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
1711
if (server_request_free(req))
1714
if (port->pending_replies)
1715
server_port_flush(port);
1720
/* Free all storage held by RRs in req. */
1722
server_request_free_answers(struct server_request *req)
1724
struct server_reply_item *victim, *next, **list;
1726
for (i = 0; i < 3; ++i) {
1728
list = &req->answer;
1730
list = &req->authority;
1732
list = &req->additional;
1736
next = victim->next;
1747
/* Free all storage held by req, and remove links to it. */
1748
/* return true iff we just wound up freeing the server_port. */
1750
server_request_free(struct server_request *req)
1753
if (req->base.questions) {
1754
for (i = 0; i < req->base.nquestions; ++i)
1755
free(req->base.questions[i]);
1756
free(req->base.questions);
1760
if (req->port->pending_replies == req) {
1761
if (req->next_pending)
1762
req->port->pending_replies = req->next_pending;
1764
req->port->pending_replies = NULL;
1766
rc = --req->port->refcnt;
1769
if (req->response) {
1770
free(req->response);
1773
server_request_free_answers(req);
1775
if (req->next_pending && req->next_pending != req) {
1776
req->next_pending->prev_pending = req->prev_pending;
1777
req->prev_pending->next_pending = req->next_pending;
1781
server_port_free(req->port);
1789
/* Free all storage held by an evdns_server_port. Only called when */
1791
server_port_free(struct evdns_server_port *port)
1794
assert(!port->refcnt);
1795
assert(!port->pending_replies);
1796
if (port->socket > 0) {
1797
CLOSE_SOCKET(port->socket);
1800
(void) event_del(&port->event);
1801
/* XXXX actually free the port? -NM */
1804
/* exported function */
1806
evdns_server_request_drop(struct evdns_server_request *_req)
1808
struct server_request *req = TO_SERVER_REQUEST(_req);
1809
server_request_free(req);
1813
/* exported function */
1815
evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
1817
struct server_request *req = TO_SERVER_REQUEST(_req);
1818
if (addr_len < (int)req->addrlen)
1820
memcpy(sa, &(req->addr), req->addrlen);
1821
return req->addrlen;
1827
/* this is a libevent callback function which is called when a request */
1828
/* has timed out. */
1830
evdns_request_timeout_callback(int fd, short events, void *arg) {
1831
struct request *const req = (struct request *) arg;
1835
log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
1837
req->ns->timedout++;
1838
if (req->ns->timedout > global_max_nameserver_timeout) {
1839
req->ns->timedout = 0;
1840
nameserver_failed(req->ns, "request timed out.");
1843
(void) evtimer_del(&req->timeout_event);
1844
if (req->tx_count >= global_max_retransmits) {
1845
/* this request has failed */
1846
reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
1847
request_finished(req, &req_head);
1850
evdns_request_transmit(req);
1854
/* try to send a request to a given server. */
1858
/* 1 temporary failure */
1859
/* 2 other failure */
1861
evdns_request_transmit_to(struct request *req, struct nameserver *server) {
1862
const int r = send(server->socket, req->request, req->request_len, 0);
1864
int err = last_error(server->socket);
1865
if (error_is_eagain(err)) return 1;
1866
nameserver_failed(req->ns, strerror(err));
1868
} else if (r != (int)req->request_len) {
1869
return 1; /* short write */
1875
/* try to send a request, updating the fields of the request */
1882
evdns_request_transmit(struct request *req) {
1885
/* if we fail to send this packet then this flag marks it */
1886
/* for evdns_transmit */
1887
req->transmit_me = 1;
1888
if (req->trans_id == 0xffff) abort();
1890
if (req->ns->choked) {
1891
/* don't bother trying to write to a socket */
1892
/* which we have had EAGAIN from */
1896
r = evdns_request_transmit_to(req, req->ns);
1900
req->ns->choked = 1;
1901
nameserver_write_waiting(req->ns, 1);
1904
/* failed in some other way */
1909
log(EVDNS_LOG_DEBUG,
1910
"Setting timeout for request %lx", (unsigned long) req);
1911
evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
1912
if (evtimer_add(&req->timeout_event, &global_timeout) < 0) {
1914
"Error from libevent when adding timer for request %lx",
1915
(unsigned long) req);
1919
req->transmit_me = 0;
1925
nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
1926
struct nameserver *const ns = (struct nameserver *) arg;
1932
if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
1933
/* this is a good reply */
1935
} else nameserver_probe_failed(ns);
1939
nameserver_send_probe(struct nameserver *const ns) {
1940
struct request *req;
1941
/* here we need to send a probe to a given nameserver */
1942
/* in the hope that it is up now. */
1944
log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntoa(ns->address));
1946
req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
1948
/* we force this into the inflight queue no matter what */
1949
request_trans_id_set(req, transaction_id_pick());
1951
request_submit(req);
1955
/* 0 didn't try to transmit anything */
1956
/* 1 tried to transmit something */
1958
evdns_transmit(void) {
1959
char did_try_to_transmit = 0;
1962
struct request *const started_at = req_head, *req = req_head;
1963
/* first transmit all the requests which are currently waiting */
1965
if (req->transmit_me) {
1966
did_try_to_transmit = 1;
1967
evdns_request_transmit(req);
1971
} while (req != started_at);
1974
return did_try_to_transmit;
1977
/* exported function */
1979
evdns_count_nameservers(void)
1981
const struct nameserver *server = server_head;
1987
server = server->next;
1988
} while (server != server_head);
1992
/* exported function */
1994
evdns_clear_nameservers_and_suspend(void)
1996
struct nameserver *server = server_head, *started_at = server_head;
1997
struct request *req = req_head, *req_started_at = req_head;
2002
struct nameserver *next = server->next;
2003
(void) event_del(&server->event);
2004
(void) evtimer_del(&server->timeout_event);
2005
if (server->socket >= 0)
2006
CLOSE_SOCKET(server->socket);
2008
if (next == started_at)
2013
global_good_nameservers = 0;
2016
struct request *next = req->next;
2017
req->tx_count = req->reissue_count = 0;
2019
/* ???? What to do about searches? */
2020
(void) evtimer_del(&req->timeout_event);
2022
req->transmit_me = 0;
2024
global_requests_waiting++;
2025
evdns_request_insert(req, &req_waiting_head);
2026
/* We want to insert these suspended elements at the front of
2027
* the waiting queue, since they were pending before any of
2028
* the waiting entries were added. This is a circular list,
2029
* so we can just shift the start back by one.*/
2030
req_waiting_head = req_waiting_head->prev;
2032
if (next == req_started_at)
2037
global_requests_inflight = 0;
2043
/* exported function */
2047
evdns_requests_pump_waiting_queue();
2052
_evdns_nameserver_add_impl(unsigned long int address, int port) {
2053
/* first check to see if we already have this nameserver */
2055
const struct nameserver *server = server_head, *const started_at = server_head;
2056
struct nameserver *ns;
2057
struct sockaddr_in sin;
2061
if (server->address == address) return 3;
2062
server = server->next;
2063
} while (server != started_at);
2066
ns = (struct nameserver *) malloc(sizeof(struct nameserver));
2069
memset(ns, 0, sizeof(struct nameserver));
2071
ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
2072
if (ns->socket < 0) { err = 1; goto out1; }
2073
evutil_make_socket_nonblocking(ns->socket);
2074
sin.sin_addr.s_addr = address;
2075
sin.sin_port = htons(port);
2076
sin.sin_family = AF_INET;
2077
if (connect(ns->socket, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
2082
ns->address = address;
2084
event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
2085
if (event_add(&ns->event, NULL) < 0) {
2090
log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntoa(address));
2092
/* insert this nameserver into the list of them */
2094
ns->next = ns->prev = ns;
2097
ns->next = server_head->next;
2098
ns->prev = server_head;
2099
server_head->next = ns;
2100
if (server_head->prev == server_head) {
2101
server_head->prev = ns;
2105
global_good_nameservers++;
2110
CLOSE_SOCKET(ns->socket);
2113
log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntoa(address), err);
2117
/* exported function */
2119
evdns_nameserver_add(unsigned long int address) {
2120
return _evdns_nameserver_add_impl(address, 53);
2123
/* exported function */
2125
evdns_nameserver_ip_add(const char *ip_as_string) {
2130
cp = strchr(ip_as_string, ':');
2135
port = strtoint(cp+1);
2136
if (port < 0 || port > 65535) {
2139
if ((cp-ip_as_string) >= (int)sizeof(buf)) {
2142
memcpy(buf, ip_as_string, cp-ip_as_string);
2143
buf[cp-ip_as_string] = '\0';
2146
if (!inet_aton(cp, &ina)) {
2149
return _evdns_nameserver_add_impl(ina.s_addr, port);
2152
/* insert into the tail of the queue */
2154
evdns_request_insert(struct request *req, struct request **head) {
2157
req->next = req->prev = req;
2161
req->prev = (*head)->prev;
2162
req->prev->next = req;
2164
(*head)->prev = req;
2168
string_num_dots(const char *s) {
2170
while ((s = strchr(s, '.'))) {
2177
static struct request *
2178
request_new(int type, const char *name, int flags,
2179
evdns_callback_type callback, void *user_ptr) {
2180
const char issuing_now =
2181
(global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
2183
const int name_len = strlen(name);
2184
const int request_max_len = evdns_request_len(name_len);
2185
const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
2186
/* the request data is alloced in a single block with the header */
2187
struct request *const req =
2188
(struct request *) malloc(sizeof(struct request) + request_max_len);
2192
if (!req) return NULL;
2193
memset(req, 0, sizeof(struct request));
2195
/* request data lives just after the header */
2196
req->request = ((u8 *) req) + sizeof(struct request);
2197
/* denotes that the request data shouldn't be free()ed */
2198
req->request_appended = 1;
2199
rlen = evdns_request_data_build(name, name_len, trans_id,
2200
type, CLASS_INET, req->request, request_max_len);
2203
req->request_len = rlen;
2204
req->trans_id = trans_id;
2206
req->request_type = type;
2207
req->user_pointer = user_ptr;
2208
req->user_callback = callback;
2209
req->ns = issuing_now ? nameserver_pick() : NULL;
2210
req->next = req->prev = NULL;
2219
request_submit(struct request *const req) {
2221
/* if it has a nameserver assigned then this is going */
2222
/* straight into the inflight queue */
2223
evdns_request_insert(req, &req_head);
2224
global_requests_inflight++;
2225
evdns_request_transmit(req);
2227
evdns_request_insert(req, &req_waiting_head);
2228
global_requests_waiting++;
2232
/* exported function */
2233
int evdns_resolve_ipv4(const char *name, int flags,
2234
evdns_callback_type callback, void *ptr) {
2235
log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2236
if (flags & DNS_QUERY_NO_SEARCH) {
2237
struct request *const req =
2238
request_new(TYPE_A, name, flags, callback, ptr);
2241
request_submit(req);
2244
return (search_request_new(TYPE_A, name, flags, callback, ptr));
2248
/* exported function */
2249
int evdns_resolve_ipv6(const char *name, int flags,
2250
evdns_callback_type callback, void *ptr) {
2251
log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2252
if (flags & DNS_QUERY_NO_SEARCH) {
2253
struct request *const req =
2254
request_new(TYPE_AAAA, name, flags, callback, ptr);
2257
request_submit(req);
2260
return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
2264
int evdns_resolve_reverse(struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2266
struct request *req;
2269
a = ntohl(in->s_addr);
2270
snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
2271
(int)(u8)((a )&0xff),
2272
(int)(u8)((a>>8 )&0xff),
2273
(int)(u8)((a>>16)&0xff),
2274
(int)(u8)((a>>24)&0xff));
2275
log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2276
req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2278
request_submit(req);
2282
int evdns_resolve_reverse_ipv6(struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2283
/* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2286
struct request *req;
2290
for (i=15; i >= 0; --i) {
2291
u8 byte = in->s6_addr[i];
2292
*cp++ = "0123456789abcdef"[byte & 0x0f];
2294
*cp++ = "0123456789abcdef"[byte >> 4];
2297
assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
2298
memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
2299
log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2300
req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2302
request_submit(req);
2306
/*/////////////////////////////////////////////////////////////////// */
2307
/* Search support */
2309
/* the libc resolver has support for searching a number of domains */
2310
/* to find a name. If nothing else then it takes the single domain */
2311
/* from the gethostname() call. */
2313
/* It can also be configured via the domain and search options in a */
2316
/* The ndots option controls how many dots it takes for the resolver */
2317
/* to decide that a name is non-local and so try a raw lookup first. */
2319
struct search_domain {
2321
struct search_domain *next;
2322
/* the text string is appended to this structure */
2325
struct search_state {
2329
struct search_domain *head;
2332
static struct search_state *global_search_state = NULL;
2335
search_state_decref(struct search_state *const state) {
2338
if (!state->refcount) {
2339
struct search_domain *next, *dom;
2340
for (dom = state->head; dom; dom = next) {
2348
static struct search_state *
2349
search_state_new(void) {
2350
struct search_state *state = (struct search_state *) malloc(sizeof(struct search_state));
2351
if (!state) return NULL;
2352
memset(state, 0, sizeof(struct search_state));
2353
state->refcount = 1;
2360
search_postfix_clear(void) {
2361
search_state_decref(global_search_state);
2363
global_search_state = search_state_new();
2366
/* exported function */
2368
evdns_search_clear(void) {
2369
search_postfix_clear();
2373
search_postfix_add(const char *domain) {
2375
struct search_domain *sdomain;
2376
while (domain[0] == '.') domain++;
2377
domain_len = strlen(domain);
2379
if (!global_search_state) global_search_state = search_state_new();
2380
if (!global_search_state) return;
2381
global_search_state->num_domains++;
2383
sdomain = (struct search_domain *) malloc(sizeof(struct search_domain) + domain_len);
2384
if (!sdomain) return;
2385
memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
2386
sdomain->next = global_search_state->head;
2387
sdomain->len = domain_len;
2389
global_search_state->head = sdomain;
2392
/* reverse the order of members in the postfix list. This is needed because, */
2393
/* when parsing resolv.conf we push elements in the wrong order */
2395
search_reverse(void) {
2396
struct search_domain *cur, *prev = NULL, *next;
2397
cur = global_search_state->head;
2405
global_search_state->head = prev;
2408
/* exported function */
2410
evdns_search_add(const char *domain) {
2411
search_postfix_add(domain);
2414
/* exported function */
2416
evdns_search_ndots_set(const int ndots) {
2417
if (!global_search_state) global_search_state = search_state_new();
2418
if (!global_search_state) return;
2419
global_search_state->ndots = ndots;
2423
search_set_from_hostname(void) {
2424
char hostname[HOST_NAME_MAX + 1], *domainname;
2426
search_postfix_clear();
2427
if (gethostname(hostname, sizeof(hostname))) return;
2428
domainname = strchr(hostname, '.');
2429
if (!domainname) return;
2430
search_postfix_add(domainname);
2433
/* warning: returns malloced string */
2435
search_make_new(const struct search_state *const state, int n, const char *const base_name) {
2436
const int base_len = strlen(base_name);
2437
const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
2438
struct search_domain *dom;
2440
for (dom = state->head; dom; dom = dom->next) {
2442
/* this is the postfix we want */
2443
/* the actual postfix string is kept at the end of the structure */
2444
const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
2445
const int postfix_len = dom->len;
2446
char *const newname = (char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
2447
if (!newname) return NULL;
2448
memcpy(newname, base_name, base_len);
2449
if (need_to_append_dot) newname[base_len] = '.';
2450
memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
2451
newname[base_len + need_to_append_dot + postfix_len] = 0;
2456
/* we ran off the end of the list and still didn't find the requested string */
2458
return NULL; /* unreachable; stops warnings in some compilers. */
2462
search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
2463
assert(type == TYPE_A || type == TYPE_AAAA);
2464
if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
2465
global_search_state &&
2466
global_search_state->num_domains) {
2467
/* we have some domains to search */
2468
struct request *req;
2469
if (string_num_dots(name) >= global_search_state->ndots) {
2470
req = request_new(type, name, flags, user_callback, user_arg);
2472
req->search_index = -1;
2474
char *const new_name = search_make_new(global_search_state, 0, name);
2475
if (!new_name) return 1;
2476
req = request_new(type, new_name, flags, user_callback, user_arg);
2479
req->search_index = 0;
2481
req->search_origname = strdup(name);
2482
req->search_state = global_search_state;
2483
req->search_flags = flags;
2484
global_search_state->refcount++;
2485
request_submit(req);
2488
struct request *const req = request_new(type, name, flags, user_callback, user_arg);
2490
request_submit(req);
2495
/* this is called when a request has failed to find a name. We need to check */
2496
/* if it is part of a search and, if so, try the next name in the list */
2498
/* 0 another request has been submitted */
2499
/* 1 no more requests needed */
2501
search_try_next(struct request *const req) {
2502
if (req->search_state) {
2503
/* it is part of a search */
2505
struct request *newreq;
2506
req->search_index++;
2507
if (req->search_index >= req->search_state->num_domains) {
2508
/* no more postfixes to try, however we may need to try */
2509
/* this name without a postfix */
2510
if (string_num_dots(req->search_origname) < req->search_state->ndots) {
2511
/* yep, we need to try it raw */
2512
struct request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
2513
log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
2515
request_submit(newreq);
2522
new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
2523
if (!new_name) return 1;
2524
log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
2525
newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
2527
if (!newreq) return 1;
2528
newreq->search_origname = req->search_origname;
2529
req->search_origname = NULL;
2530
newreq->search_state = req->search_state;
2531
newreq->search_flags = req->search_flags;
2532
newreq->search_index = req->search_index;
2533
newreq->search_state->refcount++;
2534
request_submit(newreq);
2541
search_request_finished(struct request *const req) {
2542
if (req->search_state) {
2543
search_state_decref(req->search_state);
2544
req->search_state = NULL;
2546
if (req->search_origname) {
2547
free(req->search_origname);
2548
req->search_origname = NULL;
2552
/*/////////////////////////////////////////////////////////////////// */
2553
/* Parsing resolv.conf files */
2556
evdns_resolv_set_defaults(int flags) {
2557
/* if the file isn't found then we assume a local resolver */
2558
if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
2559
if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
2562
#ifndef HAVE_STRTOK_R
2564
strtok_r(char *s, const char *delim, char **state) {
2565
return strtok(s, delim);
2569
/* helper version of atoi which returns -1 on error */
2571
strtoint(const char *const str) {
2573
const int r = strtol(str, &endptr, 10);
2574
if (*endptr) return -1;
2578
/* helper version of atoi that returns -1 on error and clips to bounds. */
2580
strtoint_clipped(const char *const str, int min, int max)
2582
int r = strtoint(str);
2593
/* exported function */
2595
evdns_set_option(const char *option, const char *val, int flags)
2597
if (!strncmp(option, "ndots:", 6)) {
2598
const int ndots = strtoint(val);
2599
if (ndots == -1) return -1;
2600
if (!(flags & DNS_OPTION_SEARCH)) return 0;
2601
log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
2602
if (!global_search_state) global_search_state = search_state_new();
2603
if (!global_search_state) return -1;
2604
global_search_state->ndots = ndots;
2605
} else if (!strncmp(option, "timeout:", 8)) {
2606
const int timeout = strtoint(val);
2607
if (timeout == -1) return -1;
2608
if (!(flags & DNS_OPTION_MISC)) return 0;
2609
log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
2610
global_timeout.tv_sec = timeout;
2611
} else if (!strncmp(option, "max-timeouts:", 12)) {
2612
const int maxtimeout = strtoint_clipped(val, 1, 255);
2613
if (maxtimeout == -1) return -1;
2614
if (!(flags & DNS_OPTION_MISC)) return 0;
2615
log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
2617
global_max_nameserver_timeout = maxtimeout;
2618
} else if (!strncmp(option, "max-inflight:", 13)) {
2619
const int maxinflight = strtoint_clipped(val, 1, 65000);
2620
if (maxinflight == -1) return -1;
2621
if (!(flags & DNS_OPTION_MISC)) return 0;
2622
log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
2624
global_max_requests_inflight = maxinflight;
2625
} else if (!strncmp(option, "attempts:", 9)) {
2626
int retries = strtoint(val);
2627
if (retries == -1) return -1;
2628
if (retries > 255) retries = 255;
2629
if (!(flags & DNS_OPTION_MISC)) return 0;
2630
log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
2631
global_max_retransmits = retries;
2637
resolv_conf_parse_line(char *const start, int flags) {
2639
static const char *const delims = " \t";
2640
#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
2642
char *const first_token = strtok_r(start, delims, &strtok_state);
2643
if (!first_token) return;
2645
if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
2646
const char *const nameserver = NEXT_TOKEN;
2649
if (inet_aton(nameserver, &ina)) {
2650
/* address is valid */
2651
evdns_nameserver_add(ina.s_addr);
2653
} else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
2654
const char *const domain = NEXT_TOKEN;
2656
search_postfix_clear();
2657
search_postfix_add(domain);
2659
} else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
2661
search_postfix_clear();
2663
while ((domain = NEXT_TOKEN)) {
2664
search_postfix_add(domain);
2667
} else if (!strcmp(first_token, "options")) {
2669
while ((option = NEXT_TOKEN)) {
2670
const char *val = strchr(option, ':');
2671
evdns_set_option(option, val ? val+1 : "", flags);
2677
/* exported function */
2680
/* 1 failed to open file */
2681
/* 2 failed to stat file */
2682
/* 3 file too large */
2683
/* 4 out of memory */
2684
/* 5 short read from file */
2686
evdns_resolv_conf_parse(int flags, const char *const filename) {
2693
log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
2695
fd = open(filename, O_RDONLY);
2697
evdns_resolv_set_defaults(flags);
2701
if (fstat(fd, &st)) { err = 2; goto out1; }
2703
evdns_resolv_set_defaults(flags);
2704
err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
2707
if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */
2709
resolv = (u8 *) malloc((size_t)st.st_size + 1);
2710
if (!resolv) { err = 4; goto out1; }
2713
while ((r = read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
2715
if (n == st.st_size)
2717
assert(n < st.st_size);
2719
if (r < 0) { err = 5; goto out2; }
2720
resolv[n] = 0; /* we malloced an extra byte; this should be fine. */
2722
start = (char *) resolv;
2724
char *const newline = strchr(start, '\n');
2726
resolv_conf_parse_line(start, flags);
2730
resolv_conf_parse_line(start, flags);
2731
start = newline + 1;
2735
if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
2736
/* no nameservers were configured. */
2737
evdns_nameserver_ip_add("127.0.0.1");
2740
if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
2741
search_set_from_hostname();
2752
/* Add multiple nameservers from a space-or-comma-separated list. */
2754
evdns_nameserver_ip_add_line(const char *ips) {
2759
while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
2762
while (ISDIGIT(*ips) || *ips == '.' || *ips == ':')
2764
buf = malloc(ips-addr+1);
2766
memcpy(buf, addr, ips-addr);
2767
buf[ips-addr] = '\0';
2768
r = evdns_nameserver_ip_add(buf);
2775
typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
2777
/* Use the windows GetNetworkParams interface in iphlpapi.dll to */
2778
/* figure out what our nameservers are. */
2780
load_nameservers_with_getnetworkparams(void)
2782
/* Based on MSDN examples and inspection of c-ares code. */
2785
ULONG size = sizeof(FIXED_INFO);
2787
int status = 0, r, added_any;
2789
GetNetworkParams_fn_t fn;
2791
if (!(handle = LoadLibrary("iphlpapi.dll"))) {
2792
log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
2796
if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
2797
log(EVDNS_LOG_WARN, "Could not get address of function.");
2803
if (!buf) { status = 4; goto done; }
2805
r = fn(fixed, &size);
2806
if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
2810
if (r != ERROR_SUCCESS) {
2813
if (!buf) { status = 4; goto done; }
2815
r = fn(fixed, &size);
2816
if (r != ERROR_SUCCESS) {
2817
log(EVDNS_LOG_DEBUG, "fn() failed.");
2825
ns = &(fixed->DnsServerList);
2827
r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
2829
log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
2830
(ns->IpAddress.String),(int)GetLastError());
2834
log(EVDNS_LOG_DEBUG,"Succesfully added %s as nameserver",ns->IpAddress.String);
2842
log(EVDNS_LOG_DEBUG, "No nameservers added.");
2850
FreeLibrary(handle);
2855
config_nameserver_from_reg_key(HKEY key, const char *subkey)
2858
DWORD bufsz = 0, type = 0;
2861
if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
2864
if (!(buf = malloc(bufsz)))
2867
if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
2868
== ERROR_SUCCESS && bufsz > 1) {
2869
status = evdns_nameserver_ip_add_line(buf);
2876
#define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
2877
#define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
2878
#define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
2881
load_nameservers_from_registry(void)
2885
#define TRY(k, name) \
2886
if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
2887
log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
2889
} else if (!found) { \
2890
log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
2894
if (((int)GetVersion()) > 0) { /* NT */
2895
HKEY nt_key = 0, interfaces_key = 0;
2897
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
2898
KEY_READ, &nt_key) != ERROR_SUCCESS) {
2899
log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
2902
r = RegOpenKeyEx(nt_key, "Interfaces", 0,
2903
KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
2905
if (r != ERROR_SUCCESS) {
2906
log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
2909
TRY(nt_key, "NameServer");
2910
TRY(nt_key, "DhcpNameServer");
2911
TRY(interfaces_key, "NameServer");
2912
TRY(interfaces_key, "DhcpNameServer");
2913
RegCloseKey(interfaces_key);
2914
RegCloseKey(nt_key);
2917
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
2918
KEY_READ, &win_key) != ERROR_SUCCESS) {
2919
log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
2922
TRY(win_key, "NameServer");
2923
RegCloseKey(win_key);
2927
log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
2930
return found ? 0 : -1;
2935
evdns_config_windows_nameservers(void)
2937
if (load_nameservers_with_getnetworkparams() == 0)
2939
return load_nameservers_from_registry();
2948
evdns_config_windows_nameservers();
2950
res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
2957
evdns_err_to_string(int err)
2960
case DNS_ERR_NONE: return "no error";
2961
case DNS_ERR_FORMAT: return "misformatted query";
2962
case DNS_ERR_SERVERFAILED: return "server failed";
2963
case DNS_ERR_NOTEXIST: return "name does not exist";
2964
case DNS_ERR_NOTIMPL: return "query not implemented";
2965
case DNS_ERR_REFUSED: return "refused";
2967
case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
2968
case DNS_ERR_UNKNOWN: return "unknown";
2969
case DNS_ERR_TIMEOUT: return "request timed out";
2970
case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
2971
default: return "[Unknown error code]";
2976
evdns_shutdown(int fail_requests)
2978
struct nameserver *server, *server_next;
2979
struct search_domain *dom, *dom_next;
2983
reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
2984
request_finished(req_head, &req_head);
2986
while (req_waiting_head) {
2988
reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
2989
request_finished(req_waiting_head, &req_waiting_head);
2991
global_requests_inflight = global_requests_waiting = 0;
2993
for (server = server_head; server; server = server_next) {
2994
server_next = server->next;
2995
if (server->socket >= 0)
2996
CLOSE_SOCKET(server->socket);
2997
(void) event_del(&server->event);
2998
if (server->state == 0)
2999
(void) event_del(&server->timeout_event);
3001
if (server_next == server_head)
3005
global_good_nameservers = 0;
3007
if (global_search_state) {
3008
for (dom = global_search_state->head; dom; dom = dom_next) {
3009
dom_next = dom->next;
3012
free(global_search_state);
3013
global_search_state = NULL;
3015
evdns_log_fn = NULL;
3020
main_callback(int result, char type, int count, int ttl,
3021
void *addrs, void *orig) {
3022
char *n = (char*)orig;
3024
for (i = 0; i < count; ++i) {
3025
if (type == DNS_IPv4_A) {
3026
printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
3027
} else if (type == DNS_PTR) {
3028
printf("%s: %s\n", n, ((char**)addrs)[i]);
3032
printf("%s: No answer (%d)\n", n, result);
3037
evdns_server_callback(struct evdns_server_request *req, void *data)
3041
/* dummy; give 192.168.11.11 as an answer for all A questions,
3042
* give foo.bar.example.com as an answer for all PTR questions. */
3043
for (i = 0; i < req->nquestions; ++i) {
3044
u32 ans = htonl(0xc0a80b0bUL);
3045
if (req->questions[i]->type == EVDNS_TYPE_A &&
3046
req->questions[i]->class == EVDNS_CLASS_INET) {
3047
printf(" -- replying for %s (A)\n", req->questions[i]->name);
3048
r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
3051
printf("eeep, didn't work.\n");
3052
} else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
3053
req->questions[i]->class == EVDNS_CLASS_INET) {
3054
printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
3055
r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
3056
"foo.bar.example.com", 10);
3058
printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
3059
req->questions[i]->type, req->questions[i]->class);
3063
r = evdns_request_respond(req, 0);
3065
printf("eeek, couldn't send reply.\n");
3069
logfn(int is_warn, const char *msg) {
3071
fprintf(stderr, "%s\n", msg);
3074
main(int c, char **v) {
3076
int reverse = 0, verbose = 1, servertest = 0;
3078
fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
3079
fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
3083
while (idx < c && v[idx][0] == '-') {
3084
if (!strcmp(v[idx], "-x"))
3086
else if (!strcmp(v[idx], "-v"))
3088
else if (!strcmp(v[idx], "-servertest"))
3091
fprintf(stderr, "Unknown option %s\n", v[idx]);
3096
evdns_set_log_fn(logfn);
3097
evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
3100
struct sockaddr_in my_addr;
3101
sock = socket(PF_INET, SOCK_DGRAM, 0);
3102
evutil_make_socket_nonblocking(sock);
3103
my_addr.sin_family = AF_INET;
3104
my_addr.sin_port = htons(10053);
3105
my_addr.sin_addr.s_addr = INADDR_ANY;
3106
if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
3110
evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
3112
for (; idx < c; ++idx) {
3114
struct in_addr addr;
3115
if (!inet_aton(v[idx], &addr)) {
3116
fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
3119
fprintf(stderr, "resolving %s...\n",v[idx]);
3120
evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
3122
fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
3123
evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);