37 #include <sys/types.h>
42 #ifdef DNS_USE_FTIME_FOR_ID
43 #include <sys/timeb.h>
46 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
47 #ifdef HAVE_GETTIMEOFDAY
48 #define DNS_USE_GETTIMEOFDAY_FOR_ID 1
52 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
53 #ifdef HAVE_GETTIMEOFDAY
54 #define DNS_USE_GETTIMEOFDAY_FOR_ID 1
58 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
59 #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
60 #ifndef DNS_USE_OPENSSL_FOR_ID
61 #ifndef DNS_USE_FTIME_FOR_ID
62 #error Must configure at least one id generation method.
63 #error Please see the documentation.
72 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
73 #ifdef DNS_USE_OPENSSL_FOR_ID
74 #error Multiple id options selected
76 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
77 #error Multiple id options selected
82 #ifdef DNS_USE_OPENSSL_FOR_ID
83 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
84 #error Multiple id options selected
86 #include <openssl/rand.h>
89 #ifndef _FORTIFY_SOURCE
90 #define _FORTIFY_SOURCE 3
95 #ifdef HAVE_SYS_TIME_H
109 #include <sys/stat.h>
118 #include <winsock2.h>
120 #include <iphlpapi.h>
123 #include <sys/socket.h>
124 #include <netinet/in.h>
125 #include <arpa/inet.h>
128 #ifdef HAVE_NETINET_IN6_H
129 #include <netinet/in6.h>
132 #define EVDNS_LOG_DEBUG 0
133 #define EVDNS_LOG_WARN 1
135 #ifndef HOST_NAME_MAX
136 #define HOST_NAME_MAX 255
142 #define MIN(a,b) ((a)<(b)?(a):(b))
146 typedef ev_uint8_t u_char;
147 typedef unsigned int uint;
151 #define u64 ev_uint64_t
152 #define u32 ev_uint32_t
153 #define u16 ev_uint16_t
154 #define u8 ev_uint8_t
160 #define strdup _strdup
166 #define TYPE_A EVDNS_TYPE_A
168 #define TYPE_PTR EVDNS_TYPE_PTR
169 #define TYPE_AAAA EVDNS_TYPE_AAAA
171 #define CLASS_INET EVDNS_CLASS_INET
175 unsigned int request_len;
178 unsigned int request_type;
186 char *search_origname;
192 struct event timeout_event;
195 char request_appended;
199 #ifndef HAVE_STRUCT_IN6_ADDR
207 unsigned int have_answer;
211 u32 addresses[MAX_ADDRS];
215 struct in6_addr addresses[MAX_ADDRS];
218 char name[HOST_NAME_MAX];
232 struct event timeout_event;
240 static struct request *req_head = NULL, *req_waiting_head = NULL;
250 evdns_request_callback_fn_type user_callback;
280 struct sockaddr_storage addr;
301 #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
305 #define TO_SERVER_REQUEST(base_ptr) \
306 ((struct server_request*) \
307 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
310 static int global_good_nameservers = 0;
314 static int global_requests_inflight = 0;
317 static int global_requests_waiting = 0;
319 static int global_max_requests_inflight = 64;
321 static struct timeval global_timeout = {5, 0};
322 static int global_max_reissues = 1;
323 static int global_max_retransmits = 3;
325 static int global_max_nameserver_timeout = 3;
329 static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
330 static const int global_nameserver_timeouts_length =
sizeof(global_nameserver_timeouts)/
sizeof(
struct timeval);
332 static struct nameserver *nameserver_pick(
void);
333 static void evdns_request_insert(
struct request *req,
struct request **head);
334 static void nameserver_ready_callback(
int fd,
short events,
void *arg);
335 static int evdns_transmit(
void);
336 static int evdns_request_transmit(
struct request *req);
337 static void nameserver_send_probe(
struct nameserver *
const ns);
338 static void search_request_finished(
struct request *
const);
339 static int search_try_next(
struct request *
const req);
341 static void evdns_requests_pump_waiting_queue(
void);
342 static u16 transaction_id_pick(
void);
344 static void request_submit(
struct request *
const req);
347 static void server_request_free_answers(
struct server_request *req);
349 static void server_port_ready_callback(
int fd,
short events,
void *arg);
351 static int strtoint(
const char *
const str);
357 int optval, optvallen=
sizeof(optval);
358 int err = WSAGetLastError();
359 if (err == WSAEWOULDBLOCK && sock >= 0) {
360 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (
void*)&optval,
370 error_is_eagain(
int err)
372 return err == EAGAIN || err == WSAEWOULDBLOCK;
375 inet_aton(
const char *c,
struct in_addr *addr)
378 if (strcmp(c,
"255.255.255.255") == 0) {
379 addr->s_addr = 0xffffffffu;
382 if (r == INADDR_NONE)
389 #define last_error(sock) (errno)
390 #define error_is_eagain(err) ((err) == EAGAIN)
392 #define CLOSE_SOCKET(s) EVUTIL_CLOSESOCKET(s)
394 #define ISSPACE(c) isspace((int)(unsigned char)(c))
395 #define ISDIGIT(c) isdigit((int)(unsigned char)(c))
398 debug_ntoa(u32 address)
401 u32 a = ntohl(address);
402 evutil_snprintf(buf,
sizeof(buf),
"%d.%d.%d.%d",
403 (
int)(u8)((a>>24)&0xff),
404 (
int)(u8)((a>>16)&0xff),
405 (
int)(u8)((a>>8 )&0xff),
406 (
int)(u8)((a )&0xff));
419 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
421 #define EVDNS_LOG_CHECK
424 static void _evdns_log(
int warn,
const char *
fmt, ...) EVDNS_LOG_CHECK;
426 _evdns_log(
int warn, const
char *fmt, ...)
429 static char buf[512];
433 evutil_vsnprintf(buf,
sizeof(buf), fmt, args);
434 buf[
sizeof(
buf)-1] =
'\0';
435 evdns_log_fn(warn, buf);
439 #define log _evdns_log
445 request_find_from_trans_id(u16 trans_id) {
446 struct request *req = req_head, *
const started_at = req_head;
450 if (req->trans_id == trans_id)
return req;
452 }
while (req != started_at);
461 nameserver_prod_callback(
int fd,
short events,
void *arg) {
466 nameserver_send_probe(ns);
473 nameserver_probe_failed(
struct nameserver *
const ns) {
474 const struct timeval * timeout;
476 if (ns->state == 1) {
483 &global_nameserver_timeouts[MIN(ns->failed_times,
484 global_nameserver_timeouts_length - 1)];
489 "Error from libevent when adding timer event for %s",
490 debug_ntoa(ns->address));
498 nameserver_failed(
struct nameserver *
const ns,
const char *
msg) {
499 struct request *req, *started_at;
502 if (!ns->state)
return;
504 log(EVDNS_LOG_WARN,
"Nameserver %s has failed: %s",
505 debug_ntoa(ns->address), msg);
506 global_good_nameservers--;
507 assert(global_good_nameservers >= 0);
508 if (global_good_nameservers == 0) {
509 log(EVDNS_LOG_WARN,
"All nameservers have failed");
513 ns->failed_times = 1;
515 if (
evtimer_add(&ns->timeout_event, (
struct timeval *) &global_nameserver_timeouts[0]) < 0) {
517 "Error from libevent when adding timer event for %s",
518 debug_ntoa(ns->address));
528 if (!global_good_nameservers)
return;
531 started_at = req_head;
534 if (req->tx_count == 0 && req->ns == ns) {
537 req->ns = nameserver_pick();
540 }
while (req != started_at);
546 if (ns->state)
return;
547 log(EVDNS_LOG_WARN,
"Nameserver %s is back up",
548 debug_ntoa(ns->address));
551 ns->failed_times = 0;
553 global_good_nameservers++;
557 request_trans_id_set(
struct request *
const req,
const u16 trans_id) {
558 req->trans_id = trans_id;
559 *((u16 *) req->request) = htons(trans_id);
566 request_finished(
struct request *
const req,
struct request **head) {
568 if (req->next == req) {
572 req->next->prev = req->prev;
573 req->prev->next = req->next;
574 if (*head == req) *head = req->next;
578 log(EVDNS_LOG_DEBUG,
"Removing timeout for request %lx",
579 (
unsigned long) req);
582 search_request_finished(req);
583 global_requests_inflight--;
585 if (!req->request_appended) {
595 evdns_requests_pump_waiting_queue();
605 request_reissue(
struct request *req) {
606 const struct nameserver *
const last_ns = req->ns;
610 req->ns = nameserver_pick();
611 if (req->ns == last_ns) {
618 req->reissue_count++;
620 req->transmit_me = 1;
628 evdns_requests_pump_waiting_queue(
void) {
629 while (global_requests_inflight < global_max_requests_inflight &&
630 global_requests_waiting) {
633 assert(req_waiting_head);
634 if (req_waiting_head->next == req_waiting_head) {
636 req = req_waiting_head;
637 req_waiting_head = NULL;
639 req = req_waiting_head;
640 req->next->prev = req->prev;
641 req->prev->next = req->next;
642 req_waiting_head = req->next;
645 global_requests_waiting--;
646 global_requests_inflight++;
648 req->ns = nameserver_pick();
649 request_trans_id_set(req, transaction_id_pick());
651 evdns_request_insert(req, &req_head);
652 evdns_request_transmit(req);
658 reply_callback(
struct request *
const req, u32 ttl, u32 err,
struct reply *
reply) {
659 switch (req->request_type) {
663 reply->data.a.addrcount, ttl,
664 reply->data.a.addresses,
667 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
671 char *
name = reply->data.ptr.name;
673 &name, req->user_pointer);
675 req->user_callback(err, 0, 0, 0, NULL,
682 reply->data.aaaa.addrcount, ttl,
683 reply->data.aaaa.addresses,
686 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
694 reply_handle(
struct request *
const req, u16
flags, u32 ttl,
struct reply *reply) {
696 static const int error_codes[] = {
701 if (flags & 0x020f || !reply || !reply->have_answer) {
703 if (flags & 0x0200) {
706 u16 error_code = (flags & 0x000f) - 1;
707 if (error_code > 4) {
710 error = error_codes[error_code];
718 if (req->reissue_count < global_max_reissues) {
720 evutil_snprintf(msg,
sizeof(msg),
721 "Bad response %d (%s)",
722 error, evdns_err_to_string(error));
723 nameserver_failed(req->ns, msg);
724 if (!request_reissue(req))
return;
733 log(EVDNS_LOG_DEBUG,
"Got a SERVERFAILED from nameserver %s; "
734 "will allow the request to time out.",
735 debug_ntoa(req->ns->address));
739 nameserver_up(req->ns);
742 if (req->search_state && req->request_type != TYPE_PTR) {
745 if (!search_try_next(req)) {
751 request_finished(req, &req_head);
757 reply_callback(req, 0, error, NULL);
758 request_finished(req, &req_head);
761 reply_callback(req, ttl, 0, reply);
762 nameserver_up(req->ns);
763 request_finished(req, &req_head);
768 name_parse(u8 *packet,
int length,
int *idx,
char *name_out,
int name_out_len) {
772 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
773 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
774 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
777 const char *
const end = name_out + name_out_len;
787 if (j >= length)
return -1;
789 if (!label_len)
break;
790 if (label_len & 0xc0) {
793 if (name_end < 0) name_end = j;
794 j = (((int)label_len & 0x3f) << 8) + ptr_low;
796 if (j < 0 || j >= length)
return -1;
799 if (++ptr_count > length)
return -1;
802 if (label_len > 63)
return -1;
803 if (cp != name_out) {
804 if (cp + 1 >= end)
return -1;
807 if (cp + label_len >= end)
return -1;
808 memcpy(cp, packet + j, label_len);
812 if (cp >= end)
return -1;
825 reply_parse(u8 *packet,
int length) {
829 char tmp_name[256], cmp_name[256];
831 u16 trans_id, questions, answers, authority, additional, datalength;
833 u32 ttl, ttl_r = 0xffffffff;
847 req = request_find_from_trans_id(trans_id);
850 memset(&reply, 0,
sizeof(reply));
853 if (!(flags & 0x8000))
return -1;
854 if (flags & 0x020f) {
862 do { tmp_name[0] = '\0'; \
863 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
867 do { tmp_name[0] = '\0'; \
868 cmp_name[0] = '\0'; \
870 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
872 if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \
874 if (memcmp(tmp_name, cmp_name, strlen (tmp_name)) != 0) \
878 reply.type = req->request_type;
881 for (i = 0; i < questions; ++
i) {
887 if (j > length)
goto err;
894 for (i = 0; i < answers; ++
i) {
903 if (type == TYPE_A &&
class == CLASS_INET) {
904 int addrcount, addrtocopy;
905 if (req->request_type != TYPE_A) {
906 j += datalength;
continue;
908 if ((datalength & 3) != 0)
910 addrcount = datalength >> 2;
911 addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (
unsigned)addrcount);
913 ttl_r = MIN(ttl_r, ttl);
915 if (j + 4*addrtocopy > length)
goto err;
916 memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
917 packet + j, 4*addrtocopy);
919 reply.data.a.addrcount += addrtocopy;
920 reply.have_answer = 1;
921 if (reply.data.a.addrcount == MAX_ADDRS)
break;
922 }
else if (type == TYPE_PTR &&
class == CLASS_INET) {
923 if (req->request_type != TYPE_PTR) {
924 j += datalength;
continue;
926 if (name_parse(packet, length, &j, reply.data.ptr.name,
927 sizeof(reply.data.ptr.name))<0)
929 ttl_r = MIN(ttl_r, ttl);
930 reply.have_answer = 1;
932 }
else if (type == TYPE_AAAA &&
class == CLASS_INET) {
933 int addrcount, addrtocopy;
934 if (req->request_type != TYPE_AAAA) {
935 j += datalength;
continue;
937 if ((datalength & 15) != 0)
939 addrcount = datalength >> 4;
940 addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (
unsigned)addrcount);
941 ttl_r = MIN(ttl_r, ttl);
944 if (j + 16*addrtocopy > length)
goto err;
945 memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
946 packet + j, 16*addrtocopy);
947 reply.data.aaaa.addrcount += addrtocopy;
949 reply.have_answer = 1;
950 if (reply.data.aaaa.addrcount == MAX_ADDRS)
break;
957 reply_handle(req, flags, ttl_r, &reply);
961 reply_handle(req, flags, 0, NULL);
969 request_parse(u8 *packet,
int length,
struct evdns_server_port *port,
struct sockaddr *addr, socklen_t addrlen)
976 u16 trans_id,
flags, questions, answers, authority, additional;
987 if (flags & 0x8000)
return -1;
991 if (server_req == NULL)
return -1;
994 server_req->trans_id = trans_id;
995 memcpy(&server_req->addr, addr, addrlen);
996 server_req->addrlen = addrlen;
998 server_req->base.flags =
flags;
999 server_req->base.nquestions = 0;
1001 if (server_req->base.questions == NULL)
1004 for (i = 0; i < questions; ++
i) {
1008 if (name_parse(packet, length, &j, tmp_name,
sizeof(tmp_name))<0)
1012 namelen = strlen(tmp_name);
1017 q->dns_question_class =
class;
1018 memcpy(q->name, tmp_name, namelen+1);
1019 server_req->base.questions[server_req->base.nquestions++] = q;
1024 server_req->port = port;
1028 if (flags & 0x7800) {
1033 port->user_callback(&(server_req->base), port->user_data);
1038 if (server_req->base.questions) {
1039 for (i = 0; i < server_req->base.nquestions; ++
i)
1040 free(server_req->base.questions[i]);
1041 free(server_req->base.questions);
1054 default_transaction_id_fn(
void)
1057 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
1059 static int clkid = -1;
1061 clkid = CLOCK_REALTIME;
1062 #ifdef CLOCK_MONOTONIC
1063 if (clock_gettime(CLOCK_MONOTONIC, &ts) != -1)
1064 clkid = CLOCK_MONOTONIC;
1067 if (clock_gettime(clkid, &ts) == -1)
1068 event_err(1,
"clock_gettime");
1069 trans_id = ts.tv_nsec & 0xffff;
1072 #ifdef DNS_USE_FTIME_FOR_ID
1075 trans_id = tb.millitm & 0xffff;
1078 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
1080 evutil_gettimeofday(&tv, NULL);
1081 trans_id = tv.tv_usec & 0xffff;
1084 #ifdef DNS_USE_OPENSSL_FOR_ID
1085 if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
1099 static ev_uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
1102 evdns_set_transaction_id_fn(ev_uint16_t (*fn)(
void))
1105 trans_id_function = fn;
1107 trans_id_function = default_transaction_id_fn;
1112 transaction_id_pick(
void) {
1114 const struct request *req = req_head, *started_at;
1115 u16 trans_id = trans_id_function();
1117 if (trans_id == 0xffff)
continue;
1119 req = started_at = req_head;
1122 if (req->trans_id == trans_id)
break;
1124 }
while (req != started_at);
1127 if (req == started_at)
return trans_id;
1135 nameserver_pick(
void) {
1136 struct nameserver *started_at = server_head, *picked;
1137 if (!server_head)
return NULL;
1141 if (!global_good_nameservers) {
1142 server_head = server_head->next;
1148 if (server_head->state) {
1150 picked = server_head;
1151 server_head = server_head->next;
1155 server_head = server_head->next;
1156 if (server_head == started_at) {
1160 assert(global_good_nameservers == 0);
1161 picked = server_head;
1162 server_head = server_head->next;
1169 address_is_correct(
struct nameserver *ns,
struct sockaddr *sa, socklen_t slen)
1171 struct sockaddr_in *sin = (
struct sockaddr_in*) sa;
1172 if (sa->sa_family != AF_INET || slen !=
sizeof(
struct sockaddr_in))
1174 if (sin->sin_addr.s_addr != ns->address)
1183 struct sockaddr_storage ss;
1184 socklen_t addrlen =
sizeof(ss);
1187 const int r = recvfrom(ns->socket, packet,
sizeof(packet), 0,
1188 (
struct sockaddr*)&ss, &addrlen);
1190 int err = last_error(ns->socket);
1191 if (error_is_eagain(err))
return;
1192 nameserver_failed(ns, strerror(err));
1195 if (!address_is_correct(ns, (
struct sockaddr*)&ss, addrlen)) {
1196 log(EVDNS_LOG_WARN,
"Address mismatch on received "
1201 reply_parse(packet, r);
1210 struct sockaddr_storage addr;
1215 addrlen =
sizeof(
struct sockaddr_storage);
1216 r = recvfrom(s->socket, packet,
sizeof(packet), 0,
1217 (
struct sockaddr*) &addr, &addrlen);
1219 int err = last_error(s->socket);
1220 if (error_is_eagain(err))
return;
1221 log(EVDNS_LOG_WARN,
"Error %s (%d) while reading request.",
1222 strerror(err), err);
1225 request_parse(packet, r, s, (
struct sockaddr*) &addr, addrlen);
1233 while (port->pending_replies) {
1235 int r = sendto(port->socket, req->response, req->response_len, 0,
1236 (
struct sockaddr*) &req->addr, req->addrlen);
1238 int err = last_error(port->socket);
1239 if (error_is_eagain(err))
1241 log(EVDNS_LOG_WARN,
"Error %s (%d) while writing response to port; dropping", strerror(err), err);
1243 if (server_request_free(req)) {
1250 (void) event_del(&port->event);
1251 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1252 server_port_ready_callback, port);
1253 if (event_add(&port->event, NULL) < 0) {
1254 log(EVDNS_LOG_WARN,
"Error from libevent when adding event for DNS server.");
1263 nameserver_write_waiting(
struct nameserver *ns,
char waiting) {
1264 if (ns->write_waiting == waiting)
return;
1266 ns->write_waiting = waiting;
1267 (void) event_del(&ns->event);
1268 event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1269 nameserver_ready_callback, ns);
1270 if (event_add(&ns->event, NULL) < 0) {
1271 log(EVDNS_LOG_WARN,
"Error from libevent when adding event for %s",
1272 debug_ntoa(ns->address));
1280 nameserver_ready_callback(
int fd,
short events,
void *arg) {
1284 if (events & EV_WRITE) {
1286 if (!evdns_transmit()) {
1287 nameserver_write_waiting(ns, 0);
1290 if (events & EV_READ) {
1291 nameserver_read(ns);
1298 server_port_ready_callback(
int fd,
short events,
void *arg) {
1302 if (events & EV_WRITE) {
1304 server_port_flush(port);
1306 if (events & EV_READ) {
1307 server_port_read(port);
1313 #define MAX_LABELS 128
1326 table->n_labels = 0;
1334 for (i = 0; i < table->n_labels; ++
i)
1335 free(table->labels[i].v);
1336 table->n_labels = 0;
1342 dnslabel_table_get_pos(
const struct dnslabel_table *table,
const char *label)
1345 for (i = 0; i < table->n_labels; ++
i) {
1346 if (!strcmp(label, table->labels[i].v))
1347 return table->labels[
i].pos;
1354 dnslabel_table_add(
struct dnslabel_table *table,
const char *label, off_t pos)
1358 if (table->n_labels == MAX_LABELS)
1363 p = table->n_labels++;
1364 table->labels[p].v = v;
1365 table->labels[p].pos = pos;
1382 dnsname_to_labels(u8 *
const buf,
size_t buf_len, off_t j,
1383 const char *name,
const int name_len,
1385 const char *end = name + name_len;
1389 #define APPEND16(x) do { \
1390 if (j + 2 > (off_t)buf_len) \
1393 memcpy(buf + j, &_t, 2); \
1396 #define APPEND32(x) do { \
1397 if (j + 4 > (off_t)buf_len) \
1400 memcpy(buf + j, &_t32, 4); \
1404 if (name_len > 255)
return -2;
1407 const char *
const start =
name;
1408 if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1409 APPEND16(ref | 0xc000);
1412 name = strchr(name,
'.');
1414 const unsigned int label_len = end - start;
1415 if (label_len > 63)
return -1;
1416 if ((
size_t)(j+label_len+1) > buf_len)
return -2;
1417 if (table) dnslabel_table_add(table, start, j);
1418 buf[j++] = label_len;
1420 memcpy(buf + j, start, end - start);
1425 const unsigned int label_len = name - start;
1426 if (label_len > 63)
return -1;
1427 if ((
size_t)(j+label_len+1) > buf_len)
return -2;
1428 if (table) dnslabel_table_add(table, start, j);
1429 buf[j++] = label_len;
1431 memcpy(buf + j, start, name - start);
1441 if (!j || buf[j-1]) buf[j++] = 0;
1451 evdns_request_len(
const int name_len) {
1462 evdns_request_data_build(
const char *
const name,
const int name_len,
1463 const u16 trans_id,
const u16 type,
const u16
class,
1464 u8 *
const buf,
size_t buf_len) {
1475 j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1490 evdns_add_server_port(
int socket,
int is_tcp, evdns_request_callback_fn_type cb,
void *user_data)
1498 port->socket = socket;
1502 port->user_callback = cb;
1503 port->user_data = user_data;
1504 port->pending_replies = NULL;
1506 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1507 server_port_ready_callback, port);
1508 event_add(&port->event, NULL);
1516 if (--port->refcnt == 0)
1517 server_port_free(port);
1523 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)
1533 case EVDNS_ANSWER_SECTION:
1534 itemp = &req->answer;
1535 countp = &req->n_answer;
1537 case EVDNS_AUTHORITY_SECTION:
1538 itemp = &req->authority;
1539 countp = &req->n_authority;
1541 case EVDNS_ADDITIONAL_SECTION:
1542 itemp = &req->additional;
1543 countp = &req->n_additional;
1549 itemp = &((*itemp)->next);
1555 if (!(item->name = strdup(name))) {
1560 item->dns_question_class =
class;
1562 item->is_name = is_name != 0;
1566 if (item->is_name) {
1567 if (!(item->data = strdup(data))) {
1572 item->datalen = (u16)-1;
1574 if (!(item->data = malloc(datalen))) {
1579 item->datalen = datalen;
1580 memcpy(item->data, data, datalen);
1591 evdns_server_request_add_a_reply(
struct evdns_server_request *req,
const char *name,
int n,
void *addrs,
int ttl)
1593 return evdns_server_request_add_reply(
1594 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1595 ttl, n*4, 0, addrs);
1600 evdns_server_request_add_aaaa_reply(
struct evdns_server_request *req,
const char *name,
int n,
void *addrs,
int ttl)
1602 return evdns_server_request_add_reply(
1603 req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1604 ttl, n*16, 0, addrs);
1609 evdns_server_request_add_ptr_reply(
struct evdns_server_request *req,
struct in_addr *in,
const char *inaddr_name,
const char *hostname,
int ttl)
1613 assert(in || inaddr_name);
1614 assert(!(in && inaddr_name));
1616 a = ntohl(in->s_addr);
1617 evutil_snprintf(buf,
sizeof(buf),
"%d.%d.%d.%d.in-addr.arpa",
1618 (
int)(u8)((a )&0xff),
1619 (
int)(u8)((a>>8 )&0xff),
1620 (
int)(u8)((a>>16)&0xff),
1621 (
int)(u8)((a>>24)&0xff));
1624 return evdns_server_request_add_reply(
1625 req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1626 ttl, -1, 1, hostname);
1631 evdns_server_request_add_cname_reply(
struct evdns_server_request *req,
const char *name,
const char *cname,
int ttl)
1633 return evdns_server_request_add_reply(
1634 req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
1640 evdns_server_request_format_response(
struct server_request *req,
int err)
1642 unsigned char buf[1500];
1643 size_t buf_len =
sizeof(
buf);
1651 if (err < 0 || err > 15)
return -1;
1655 flags = req->base.flags;
1656 flags |= (0x8000 | err);
1658 dnslabel_table_init(&table);
1659 APPEND16(req->trans_id);
1661 APPEND16(req->base.nquestions);
1662 APPEND16(req->n_answer);
1663 APPEND16(req->n_authority);
1664 APPEND16(req->n_additional);
1667 for (i=0; i < req->base.nquestions; ++
i) {
1668 const char *s = req->base.questions[
i]->name;
1669 j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1671 dnslabel_clear(&table);
1674 APPEND16(req->base.questions[i]->type);
1675 APPEND16(req->base.questions[i]->dns_question_class);
1679 for (i=0; i<3; ++
i) {
1684 item = req->authority;
1686 item = req->additional;
1688 r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1693 APPEND16(item->type);
1694 APPEND16(item->dns_question_class);
1695 APPEND32(item->ttl);
1696 if (item->is_name) {
1697 off_t len_idx = j, name_start;
1700 r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1704 _t = htons( (
short) (j-name_start) );
1705 memcpy(buf+len_idx, &_t, 2);
1707 APPEND16(item->datalen);
1708 if (j+item->datalen > (off_t)buf_len)
1710 memcpy(buf+j, item->data, item->datalen);
1723 req->response_len = j;
1725 if (!(req->response = malloc(req->response_len))) {
1726 server_request_free_answers(req);
1727 dnslabel_clear(&table);
1730 memcpy(req->response, buf, req->response_len);
1731 server_request_free_answers(req);
1732 dnslabel_clear(&table);
1743 if (!req->response) {
1744 if ((r = evdns_server_request_format_response(req, err))<0)
1748 r = sendto(port->socket, req->response, req->response_len, 0,
1749 (
struct sockaddr*) &req->addr, req->addrlen);
1751 int sock_err = last_error(port->socket);
1752 if (! error_is_eagain(sock_err))
1755 if (port->pending_replies) {
1756 req->prev_pending = port->pending_replies->prev_pending;
1757 req->next_pending = port->pending_replies;
1758 req->prev_pending->next_pending =
1759 req->next_pending->prev_pending = req;
1761 req->prev_pending = req->next_pending = req;
1762 port->pending_replies = req;
1765 (void) event_del(&port->event);
1766 event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
1768 if (event_add(&port->event, NULL) < 0) {
1769 log(EVDNS_LOG_WARN,
"Error from libevent when adding event for DNS server");
1776 if (server_request_free(req))
1779 if (port->pending_replies)
1780 server_port_flush(port);
1791 for (i = 0; i < 3; ++
i) {
1793 list = &req->answer;
1795 list = &req->authority;
1797 list = &req->additional;
1801 next = victim->next;
1818 if (req->base.questions) {
1819 for (i = 0; i < req->base.nquestions; ++
i)
1820 free(req->base.questions[i]);
1821 free(req->base.questions);
1825 if (req->port->pending_replies == req) {
1826 if (req->next_pending)
1827 req->port->pending_replies = req->next_pending;
1829 req->port->pending_replies = NULL;
1831 rc = --req->port->refcnt;
1834 if (req->response) {
1835 free(req->response);
1838 server_request_free_answers(req);
1840 if (req->next_pending && req->next_pending != req) {
1841 req->next_pending->prev_pending = req->prev_pending;
1842 req->prev_pending->next_pending = req->next_pending;
1846 server_port_free(req->port);
1859 assert(!port->refcnt);
1860 assert(!port->pending_replies);
1861 if (port->socket > 0) {
1862 CLOSE_SOCKET(port->socket);
1865 (void) event_del(&port->event);
1874 server_request_free(req);
1880 evdns_server_request_get_requesting_addr(
struct evdns_server_request *_req,
struct sockaddr *sa,
int addr_len)
1883 if (addr_len < (
int)req->addrlen)
1885 memcpy(sa, &(req->addr), req->addrlen);
1886 return req->addrlen;
1895 evdns_request_timeout_callback(
int fd,
short events,
void *arg) {
1900 log(EVDNS_LOG_DEBUG,
"Request %lx timed out", (
unsigned long) arg);
1902 req->ns->timedout++;
1903 if (req->ns->timedout > global_max_nameserver_timeout) {
1904 req->ns->timedout = 0;
1905 nameserver_failed(req->ns,
"request timed out.");
1909 if (req->tx_count >= global_max_retransmits) {
1912 request_finished(req, &req_head);
1915 evdns_request_transmit(req);
1927 struct sockaddr_in sin;
1929 memset(&sin, 0,
sizeof(sin));
1930 sin.sin_addr.s_addr = req->ns->address;
1931 sin.sin_port = req->ns->port;
1932 sin.sin_family = AF_INET;
1934 r = sendto(server->socket, req->request, req->request_len, 0,
1935 (
struct sockaddr*)&sin,
sizeof(sin));
1937 int err = last_error(server->socket);
1938 if (error_is_eagain(err))
return 1;
1939 nameserver_failed(req->ns, strerror(err));
1941 }
else if (r != (
int)req->request_len) {
1955 evdns_request_transmit(
struct request *req) {
1960 req->transmit_me = 1;
1961 if (req->trans_id == 0xffff) abort();
1963 if (req->ns->choked) {
1969 r = evdns_request_transmit_to(req, req->ns);
1973 req->ns->choked = 1;
1974 nameserver_write_waiting(req->ns, 1);
1982 log(EVDNS_LOG_DEBUG,
1983 "Setting timeout for request %lx", (
unsigned long) req);
1984 if (
evtimer_add(&req->timeout_event, &global_timeout) < 0) {
1986 "Error from libevent when adding timer for request %lx",
1987 (
unsigned long) req);
1991 req->transmit_me = 0;
1997 nameserver_probe_callback(
int result,
char type,
int count,
int ttl,
void *addresses,
void *arg) {
2007 }
else nameserver_probe_failed(ns);
2011 nameserver_send_probe(
struct nameserver *
const ns) {
2016 log(EVDNS_LOG_DEBUG,
"Sending probe to %s", debug_ntoa(ns->address));
2018 req = request_new(TYPE_A,
"www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
2021 request_trans_id_set(req, transaction_id_pick());
2023 request_submit(req);
2030 evdns_transmit(
void) {
2031 char did_try_to_transmit = 0;
2034 struct request *
const started_at = req_head, *req = req_head;
2037 if (req->transmit_me) {
2038 did_try_to_transmit = 1;
2039 evdns_request_transmit(req);
2043 }
while (req != started_at);
2046 return did_try_to_transmit;
2051 evdns_count_nameservers(
void)
2053 const struct nameserver *server = server_head;
2059 server = server->next;
2060 }
while (server != server_head);
2066 evdns_clear_nameservers_and_suspend(
void)
2068 struct nameserver *server = server_head, *started_at = server_head;
2069 struct request *req = req_head, *req_started_at = req_head;
2075 (void) event_del(&server->event);
2076 if (evtimer_initialized(&server->timeout_event))
2078 if (server->socket >= 0)
2079 CLOSE_SOCKET(server->socket);
2081 if (next == started_at)
2086 global_good_nameservers = 0;
2089 struct request *next = req->next;
2090 req->tx_count = req->reissue_count = 0;
2095 req->transmit_me = 0;
2097 global_requests_waiting++;
2098 evdns_request_insert(req, &req_waiting_head);
2103 req_waiting_head = req_waiting_head->prev;
2105 if (next == req_started_at)
2110 global_requests_inflight = 0;
2120 evdns_requests_pump_waiting_queue();
2125 _evdns_nameserver_add_impl(
unsigned long int address,
int port) {
2128 const struct nameserver *server = server_head, *
const started_at = server_head;
2133 if (server->address == address)
return 3;
2134 server = server->next;
2135 }
while (server != started_at);
2143 evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
2145 ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
2146 if (ns->socket < 0) { err = 1;
goto out1; }
2147 evutil_make_socket_nonblocking(ns->socket);
2149 ns->address = address;
2150 ns->port = htons(port);
2152 event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
2153 if (event_add(&ns->event, NULL) < 0) {
2158 log(EVDNS_LOG_DEBUG,
"Added nameserver %s", debug_ntoa(address));
2162 ns->next = ns->prev = ns;
2165 ns->next = server_head->next;
2166 ns->prev = server_head;
2167 server_head->next = ns;
2168 if (server_head->prev == server_head) {
2169 server_head->prev = ns;
2173 global_good_nameservers++;
2178 CLOSE_SOCKET(ns->socket);
2181 log(EVDNS_LOG_WARN,
"Unable to add nameserver %s: error %d", debug_ntoa(address), err);
2187 evdns_nameserver_add(
unsigned long int address) {
2188 return _evdns_nameserver_add_impl(address, 53);
2193 evdns_nameserver_ip_add(
const char *ip_as_string) {
2198 cp = strchr(ip_as_string,
':');
2203 port = strtoint(cp+1);
2204 if (port < 0 || port > 65535) {
2207 if ((cp-ip_as_string) >= (
int)
sizeof(buf)) {
2210 memcpy(buf, ip_as_string, cp-ip_as_string);
2211 buf[cp-ip_as_string] =
'\0';
2214 if (!inet_aton(cp, &ina)) {
2217 return _evdns_nameserver_add_impl(ina.s_addr, port);
2222 evdns_request_insert(
struct request *req,
struct request **head) {
2225 req->next = req->prev = req;
2229 req->prev = (*head)->prev;
2230 req->prev->next = req;
2232 (*head)->prev = req;
2236 string_num_dots(
const char *s) {
2238 while ((s = strchr(s,
'.'))) {
2246 request_new(
int type,
const char *name,
int flags,
2248 const char issuing_now =
2249 (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
2251 const int name_len = strlen(name);
2252 const int request_max_len = evdns_request_len(name_len);
2253 const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
2256 (
struct request *) malloc(
sizeof(
struct request) + request_max_len);
2260 if (!req)
return NULL;
2261 memset(req, 0,
sizeof(
struct request));
2263 evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
2266 req->request = ((u8 *) req) +
sizeof(
struct request);
2268 req->request_appended = 1;
2269 rlen = evdns_request_data_build(name, name_len, trans_id,
2270 type, CLASS_INET, req->request, request_max_len);
2273 req->request_len = rlen;
2274 req->trans_id = trans_id;
2276 req->request_type =
type;
2277 req->user_pointer = user_ptr;
2278 req->user_callback = callback;
2279 req->ns = issuing_now ? nameserver_pick() : NULL;
2280 req->next = req->prev = NULL;
2289 request_submit(
struct request *
const req) {
2293 evdns_request_insert(req, &req_head);
2294 global_requests_inflight++;
2295 evdns_request_transmit(req);
2297 evdns_request_insert(req, &req_waiting_head);
2298 global_requests_waiting++;
2303 int evdns_resolve_ipv4(
const char *name,
int flags,
2305 log(EVDNS_LOG_DEBUG,
"Resolve requested for %s", name);
2306 if (flags & DNS_QUERY_NO_SEARCH) {
2308 request_new(TYPE_A, name, flags, callback, ptr);
2311 request_submit(req);
2314 return (search_request_new(TYPE_A, name, flags, callback, ptr));
2319 int evdns_resolve_ipv6(
const char *name,
int flags,
2321 log(EVDNS_LOG_DEBUG,
"Resolve requested for %s", name);
2322 if (flags & DNS_QUERY_NO_SEARCH) {
2324 request_new(TYPE_AAAA, name, flags, callback, ptr);
2327 request_submit(req);
2330 return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
2339 a = ntohl(in->s_addr);
2340 evutil_snprintf(buf,
sizeof(buf),
"%d.%d.%d.%d.in-addr.arpa",
2341 (
int)(u8)((a )&0xff),
2342 (
int)(u8)((a>>8 )&0xff),
2343 (
int)(u8)((a>>16)&0xff),
2344 (
int)(u8)((a>>24)&0xff));
2345 log(EVDNS_LOG_DEBUG,
"Resolve requested for %s (reverse)", buf);
2346 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2348 request_submit(req);
2360 for (i=15; i >= 0; --
i) {
2361 u8 byte = in->s6_addr[
i];
2362 *cp++ =
"0123456789abcdef"[byte & 0x0f];
2364 *cp++ =
"0123456789abcdef"[byte >> 4];
2367 assert(cp + strlen(
"ip6.arpa") < buf+
sizeof(buf));
2368 memcpy(cp,
"ip6.arpa", strlen(
"ip6.arpa")+1);
2369 log(EVDNS_LOG_DEBUG,
"Resolve requested for %s (reverse)", buf);
2370 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2372 request_submit(req);
2402 static struct search_state *global_search_state = NULL;
2405 search_state_decref(
struct search_state *
const state) {
2408 if (!state->refcount) {
2410 for (dom = state->head; dom; dom = next) {
2419 search_state_new(
void) {
2421 if (!state)
return NULL;
2423 state->refcount = 1;
2430 search_postfix_clear(
void) {
2431 search_state_decref(global_search_state);
2433 global_search_state = search_state_new();
2438 evdns_search_clear(
void) {
2439 search_postfix_clear();
2443 search_postfix_add(
const char *domain) {
2446 while (domain[0] ==
'.') domain++;
2447 domain_len = strlen(domain);
2449 if (!global_search_state) global_search_state = search_state_new();
2450 if (!global_search_state)
return;
2451 global_search_state->num_domains++;
2454 if (!sdomain)
return;
2455 memcpy( ((u8 *) sdomain) +
sizeof(
struct search_domain), domain, domain_len);
2456 sdomain->next = global_search_state->head;
2457 sdomain->len = domain_len;
2459 global_search_state->head = sdomain;
2465 search_reverse(
void) {
2467 cur = global_search_state->head;
2475 global_search_state->head = prev;
2480 evdns_search_add(
const char *domain) {
2481 search_postfix_add(domain);
2486 evdns_search_ndots_set(
const int ndots) {
2487 if (!global_search_state) global_search_state = search_state_new();
2488 if (!global_search_state)
return;
2489 global_search_state->ndots = ndots;
2493 search_set_from_hostname(
void) {
2494 char hostname[HOST_NAME_MAX + 1], *domainname;
2496 search_postfix_clear();
2497 if (gethostname(hostname,
sizeof(hostname)))
return;
2498 domainname = strchr(hostname,
'.');
2499 if (!domainname)
return;
2500 search_postfix_add(domainname);
2505 search_make_new(
const struct search_state *
const state,
int n,
const char *
const base_name) {
2506 const int base_len = strlen(base_name);
2507 const char need_to_append_dot = base_name[base_len - 1] ==
'.' ? 0 : 1;
2510 for (dom = state->head; dom; dom = dom->next) {
2514 const u8 *
const postfix = ((u8 *) dom) +
sizeof(
struct search_domain);
2515 const int postfix_len = dom->len;
2516 char *
const newname = (
char *) malloc(base_len + need_to_append_dot + postfix_len + 1);
2517 if (!newname)
return NULL;
2518 memcpy(newname, base_name, base_len);
2519 if (need_to_append_dot) newname[base_len] =
'.';
2520 memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
2521 newname[base_len + need_to_append_dot + postfix_len] = 0;
2532 search_request_new(
int type,
const char *
const name,
int flags,
evdns_callback_type user_callback,
void *user_arg) {
2533 assert(type == TYPE_A || type == TYPE_AAAA);
2534 if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
2535 global_search_state &&
2536 global_search_state->num_domains) {
2539 if (string_num_dots(name) >= global_search_state->ndots) {
2540 req = request_new(type, name, flags, user_callback, user_arg);
2542 req->search_index = -1;
2544 char *
const new_name = search_make_new(global_search_state, 0, name);
2545 if (!new_name)
return 1;
2546 req = request_new(type, new_name, flags, user_callback, user_arg);
2549 req->search_index = 0;
2551 req->search_origname = strdup(name);
2552 req->search_state = global_search_state;
2553 req->search_flags =
flags;
2554 global_search_state->refcount++;
2555 request_submit(req);
2558 struct request *
const req = request_new(type, name, flags, user_callback, user_arg);
2560 request_submit(req);
2571 search_try_next(
struct request *
const req) {
2572 if (req->search_state) {
2576 req->search_index++;
2577 if (req->search_index >= req->search_state->num_domains) {
2580 if (string_num_dots(req->search_origname) < req->search_state->ndots) {
2582 newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
2583 log(EVDNS_LOG_DEBUG,
"Search: trying raw query %s", req->search_origname);
2585 request_submit(newreq);
2592 new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
2593 if (!new_name)
return 1;
2594 log(EVDNS_LOG_DEBUG,
"Search: now trying %s (%d)", new_name, req->search_index);
2595 newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
2597 if (!newreq)
return 1;
2598 newreq->search_origname = req->search_origname;
2599 req->search_origname = NULL;
2600 newreq->search_state = req->search_state;
2601 newreq->search_flags = req->search_flags;
2602 newreq->search_index = req->search_index;
2603 newreq->search_state->refcount++;
2604 request_submit(newreq);
2611 search_request_finished(
struct request *
const req) {
2612 if (req->search_state) {
2613 search_state_decref(req->search_state);
2614 req->search_state = NULL;
2616 if (req->search_origname) {
2617 free(req->search_origname);
2618 req->search_origname = NULL;
2626 evdns_resolv_set_defaults(
int flags) {
2628 if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
2629 if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add(
"127.0.0.1");
2632 #ifndef HAVE_STRTOK_R
2634 strtok_r(
char *s,
const char *delim,
char **state) {
2635 return strtok(s, delim);
2641 strtoint(
const char *
const str) {
2643 const int r = strtol(str, &endptr, 10);
2644 if (*endptr)
return -1;
2650 strtoint_clipped(
const char *
const str,
int min,
int max)
2652 int r = strtoint(str);
2665 evdns_set_option(
const char *
option,
const char *val,
int flags)
2667 if (!strncmp(option,
"ndots:", 6)) {
2668 const int ndots = strtoint(val);
2669 if (ndots == -1)
return -1;
2670 if (!(flags & DNS_OPTION_SEARCH))
return 0;
2671 log(EVDNS_LOG_DEBUG,
"Setting ndots to %d", ndots);
2672 if (!global_search_state) global_search_state = search_state_new();
2673 if (!global_search_state)
return -1;
2674 global_search_state->ndots = ndots;
2675 }
else if (!strncmp(option,
"timeout:", 8)) {
2676 const int timeout = strtoint(val);
2677 if (timeout == -1)
return -1;
2678 if (!(flags & DNS_OPTION_MISC))
return 0;
2679 log(EVDNS_LOG_DEBUG,
"Setting timeout to %d", timeout);
2680 global_timeout.tv_sec = timeout;
2681 }
else if (!strncmp(option,
"max-timeouts:", 12)) {
2682 const int maxtimeout = strtoint_clipped(val, 1, 255);
2683 if (maxtimeout == -1)
return -1;
2684 if (!(flags & DNS_OPTION_MISC))
return 0;
2685 log(EVDNS_LOG_DEBUG,
"Setting maximum allowed timeouts to %d",
2687 global_max_nameserver_timeout = maxtimeout;
2688 }
else if (!strncmp(option,
"max-inflight:", 13)) {
2689 const int maxinflight = strtoint_clipped(val, 1, 65000);
2690 if (maxinflight == -1)
return -1;
2691 if (!(flags & DNS_OPTION_MISC))
return 0;
2692 log(EVDNS_LOG_DEBUG,
"Setting maximum inflight requests to %d",
2694 global_max_requests_inflight = maxinflight;
2695 }
else if (!strncmp(option,
"attempts:", 9)) {
2696 int retries = strtoint(val);
2697 if (retries == -1)
return -1;
2698 if (retries > 255) retries = 255;
2699 if (!(flags & DNS_OPTION_MISC))
return 0;
2700 log(EVDNS_LOG_DEBUG,
"Setting retries to %d", retries);
2701 global_max_retransmits = retries;
2707 resolv_conf_parse_line(
char *
const start,
int flags) {
2709 static const char *
const delims =
" \t";
2710 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
2712 char *
const first_token = strtok_r(start, delims, &strtok_state);
2713 if (!first_token)
return;
2715 if (!strcmp(first_token,
"nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
2719 if (inet_aton(nameserver, &ina)) {
2721 evdns_nameserver_add(ina.s_addr);
2723 }
else if (!strcmp(first_token,
"domain") && (flags & DNS_OPTION_SEARCH)) {
2724 const char *
const domain = NEXT_TOKEN;
2726 search_postfix_clear();
2727 search_postfix_add(domain);
2729 }
else if (!strcmp(first_token,
"search") && (flags & DNS_OPTION_SEARCH)) {
2731 search_postfix_clear();
2733 while ((domain = NEXT_TOKEN)) {
2734 search_postfix_add(domain);
2737 }
else if (!strcmp(first_token,
"options")) {
2739 while ((option = NEXT_TOKEN)) {
2740 const char *val = strchr(option,
':');
2741 evdns_set_option(option, val ? val+1 :
"", flags);
2756 evdns_resolv_conf_parse(
int flags,
const char *
const filename) {
2763 log(EVDNS_LOG_DEBUG,
"Parsing resolv.conf file %s", filename);
2765 fd = open(filename, O_RDONLY);
2767 evdns_resolv_set_defaults(flags);
2771 if (fstat(fd, &st)) { err = 2;
goto out1; }
2773 evdns_resolv_set_defaults(flags);
2774 err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
2777 if (st.st_size > 65535) { err = 3;
goto out1; }
2779 resolv = (u8 *) malloc((
size_t)st.st_size + 1);
2780 if (!resolv) { err = 4;
goto out1; }
2783 while ((r = read(fd, resolv+n, (
size_t)st.st_size-n)) > 0) {
2785 if (n == st.st_size)
2787 assert(n < st.st_size);
2789 if (r < 0) { err = 5;
goto out2; }
2792 start = (
char *) resolv;
2794 char *
const newline = strchr(start,
'\n');
2796 resolv_conf_parse_line(start, flags);
2800 resolv_conf_parse_line(start, flags);
2801 start = newline + 1;
2805 if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
2807 evdns_nameserver_ip_add(
"127.0.0.1");
2810 if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
2811 search_set_from_hostname();
2824 evdns_nameserver_ip_add_line(
const char *ips) {
2829 while (ISSPACE(*ips) || *ips ==
',' || *ips ==
'\t')
2832 while (ISDIGIT(*ips) || *ips ==
'.' || *ips ==
':')
2834 buf = malloc(ips-addr+1);
2836 memcpy(buf, addr, ips-addr);
2837 buf[ips-addr] =
'\0';
2838 r = evdns_nameserver_ip_add(buf);
2845 typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
2850 load_nameservers_with_getnetworkparams(
void)
2855 ULONG
size =
sizeof(FIXED_INFO);
2857 int status = 0, r, added_any;
2859 GetNetworkParams_fn_t fn;
2861 if (!(handle = LoadLibrary(
"iphlpapi.dll"))) {
2862 log(EVDNS_LOG_WARN,
"Could not open iphlpapi.dll");
2866 if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle,
"GetNetworkParams"))) {
2867 log(EVDNS_LOG_WARN,
"Could not get address of function.");
2873 if (!buf) { status = 4;
goto done; }
2875 r = fn(fixed, &size);
2876 if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
2880 if (r != ERROR_SUCCESS) {
2883 if (!buf) { status = 4;
goto done; }
2885 r = fn(fixed, &size);
2886 if (r != ERROR_SUCCESS) {
2887 log(EVDNS_LOG_DEBUG,
"fn() failed.");
2895 ns = &(fixed->DnsServerList);
2897 r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
2899 log(EVDNS_LOG_DEBUG,
"Could not add nameserver %s to list,error: %d",
2900 (ns->IpAddress.String),(
int)GetLastError());
2904 log(EVDNS_LOG_DEBUG,
"Succesfully added %s as nameserver",ns->IpAddress.String);
2912 log(EVDNS_LOG_DEBUG,
"No nameservers added.");
2920 FreeLibrary(handle);
2925 config_nameserver_from_reg_key(HKEY key,
const char *subkey)
2928 DWORD bufsz = 0, type = 0;
2931 if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
2934 if (!(buf = malloc(bufsz)))
2937 if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
2938 == ERROR_SUCCESS && bufsz > 1) {
2939 status = evdns_nameserver_ip_add_line(buf);
2946 #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
2947 #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
2948 #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
2951 load_nameservers_from_registry(
void)
2955 #define TRY(k, name) \
2956 if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
2957 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
2959 } else if (!found) { \
2960 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
2964 if (((
int)GetVersion()) > 0) {
2965 HKEY nt_key = 0, interfaces_key = 0;
2967 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
2968 KEY_READ, &nt_key) != ERROR_SUCCESS) {
2969 log(EVDNS_LOG_DEBUG,
"Couldn't open nt key, %d",(
int)GetLastError());
2972 r = RegOpenKeyEx(nt_key,
"Interfaces", 0,
2973 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
2975 if (r != ERROR_SUCCESS) {
2976 log(EVDNS_LOG_DEBUG,
"Couldn't open interfaces key, %d",(
int)GetLastError());
2979 TRY(nt_key,
"NameServer");
2980 TRY(nt_key,
"DhcpNameServer");
2981 TRY(interfaces_key,
"NameServer");
2982 TRY(interfaces_key,
"DhcpNameServer");
2983 RegCloseKey(interfaces_key);
2984 RegCloseKey(nt_key);
2987 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
2988 KEY_READ, &win_key) != ERROR_SUCCESS) {
2989 log(EVDNS_LOG_DEBUG,
"Couldn't open registry key, %d", (
int)GetLastError());
2992 TRY(win_key,
"NameServer");
2993 RegCloseKey(win_key);
2997 log(EVDNS_LOG_WARN,
"Didn't find any nameservers.");
3000 return found ? 0 : -1;
3005 evdns_config_windows_nameservers(
void)
3007 if (load_nameservers_with_getnetworkparams() == 0)
3009 return load_nameservers_from_registry();
3018 res = evdns_config_windows_nameservers();
3020 res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL,
"/etc/resolv.conf");
3027 evdns_err_to_string(
int err)
3041 default:
return "[Unknown error code]";
3046 evdns_shutdown(
int fail_requests)
3048 struct nameserver *server, *server_next;
3054 request_finished(req_head, &req_head);
3056 while (req_waiting_head) {
3059 request_finished(req_waiting_head, &req_waiting_head);
3061 global_requests_inflight = global_requests_waiting = 0;
3063 for (server = server_head; server; server = server_next) {
3064 server_next = server->next;
3065 if (server->socket >= 0)
3066 CLOSE_SOCKET(server->socket);
3067 (void) event_del(&server->event);
3068 if (server->state == 0)
3069 (void) event_del(&server->timeout_event);
3071 if (server_next == server_head)
3075 global_good_nameservers = 0;
3077 if (global_search_state) {
3078 for (dom = global_search_state->head; dom; dom = dom_next) {
3079 dom_next = dom->next;
3082 free(global_search_state);
3083 global_search_state = NULL;
3085 evdns_log_fn = NULL;
3090 main_callback(
int result,
char type,
int count,
int ttl,
3091 void *addrs,
void *orig) {
3092 char *n = (
char*)orig;
3094 for (i = 0; i < count; ++
i) {
3095 if (type == DNS_IPv4_A) {
3096 printf(
"%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
3097 }
else if (type == DNS_PTR) {
3098 printf(
"%s: %s\n", n, ((
char**)addrs)[i]);
3102 printf(
"%s: No answer (%d)\n", n, result);
3113 for (i = 0; i < req->nquestions; ++
i) {
3114 u32 ans = htonl(0xc0a80b0bUL);
3115 if (req->questions[i]->type == EVDNS_TYPE_A &&
3116 req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
3117 printf(
" -- replying for %s (A)\n", req->questions[i]->name);
3118 r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
3121 printf(
"eeep, didn't work.\n");
3122 }
else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
3123 req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
3124 printf(
" -- replying for %s (PTR)\n", req->questions[i]->name);
3125 r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
3126 "foo.bar.example.com", 10);
3128 printf(
" -- skipping %s [%d %d]\n", req->questions[i]->name,
3129 req->questions[i]->type, req->questions[i]->dns_question_class);
3133 r = evdns_request_respond(req, 0);
3135 printf(
"eeek, couldn't send reply.\n");
3139 logfn(
int is_warn,
const char *msg) {
3141 fprintf(stderr,
"%s\n", msg);
3144 main(
int c,
char **v) {
3146 int reverse = 0, verbose = 1, servertest = 0;
3148 fprintf(stderr,
"syntax: %s [-x] [-v] hostname\n", v[0]);
3149 fprintf(stderr,
"syntax: %s [-servertest]\n", v[0]);
3153 while (idx < c && v[idx][0] ==
'-') {
3154 if (!strcmp(v[idx],
"-x"))
3156 else if (!strcmp(v[idx],
"-v"))
3158 else if (!strcmp(v[idx],
"-servertest"))
3161 fprintf(stderr,
"Unknown option %s\n", v[idx]);
3166 evdns_set_log_fn(logfn);
3167 evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS,
"/etc/resolv.conf");
3170 struct sockaddr_in my_addr;
3171 sock = socket(PF_INET, SOCK_DGRAM, 0);
3172 evutil_make_socket_nonblocking(sock);
3173 my_addr.sin_family = AF_INET;
3174 my_addr.sin_port = htons(10053);
3175 my_addr.sin_addr.s_addr = INADDR_ANY;
3176 if (bind(sock, (
struct sockaddr*)&my_addr,
sizeof(my_addr))<0) {
3180 evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
3182 for (; idx < c; ++idx) {
3184 struct in_addr addr;
3185 if (!inet_aton(v[idx], &addr)) {
3186 fprintf(stderr,
"Skipping non-IP %s\n", v[idx]);
3189 fprintf(stderr,
"resolving %s...\n",v[idx]);
3190 evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
3192 fprintf(stderr,
"resolving (fwd) %s...\n",v[idx]);
3193 evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);