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