Fix valgrind error when marking a descriptor as never-downloadable.
[tor/rransom.git] / src / or / eventdns.c
blob63851483f38d701bb04ec2c1e780e22e4aa7503f
1 /* The original version of this module was written by Adam Langley; for
2 * a history of modifications, check out the subversion logs.
4 * When editing this module, try to keep it re-mergeable by Adam. Don't
5 * reformat the whitespace, add Tor dependencies, or so on.
7 * TODO:
8 * - Replace all externally visible magic numbers with #defined constants.
9 * - Write documentation for APIs of all external functions.
12 /* Async DNS Library
13 * Adam Langley <agl@imperialviolet.org>
14 * Public Domain code
16 * This software is Public Domain. To view a copy of the public domain dedication,
17 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
18 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
20 * I ask and expect, but do not require, that all derivative works contain an
21 * attribution similar to:
22 * Parts developed by Adam Langley <agl@imperialviolet.org>
24 * You may wish to replace the word "Parts" with something else depending on
25 * the amount of original code.
27 * (Derivative works does not include programs which link against, run or include
28 * the source verbatim in their source distributions)
30 * Version: 0.1b
33 #include "eventdns_tor.h"
34 #include <sys/types.h>
35 /* #define NDEBUG */
37 #ifndef DNS_USE_CPU_CLOCK_FOR_ID
38 #ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
39 #ifndef DNS_USE_OPENSSL_FOR_ID
40 #error Must configure at least one id generation method.
41 #error Please see the documentation.
42 #endif
43 #endif
44 #endif
46 /* #define _POSIX_C_SOURCE 200507 */
47 #define _GNU_SOURCE
49 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
50 #ifdef DNS_USE_OPENSSL_FOR_ID
51 #error Multiple id options selected
52 #endif
53 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
54 #error Multiple id options selected
55 #endif
56 #include <time.h>
57 #endif
59 #ifdef DNS_USE_OPENSSL_FOR_ID
60 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
61 #error Multiple id options selected
62 #endif
63 #include <openssl/rand.h>
64 #endif
66 #include <string.h>
67 #ifdef HAVE_FCNTL_H
68 #include <fcntl.h>
69 #endif
70 #ifdef HAVE_SYS_TIME_H
71 #include <sys/time.h>
72 #endif
73 #ifdef HAVE_STDINT_H
74 #include <stdint.h>
75 #endif
76 #include <stdlib.h>
77 #include <string.h>
78 #include <errno.h>
79 #include <assert.h>
80 #ifdef HAVE_UNISTD_H
81 #include <unistd.h>
82 #endif
83 #ifdef HAVE_LIMITS_H
84 #include <limits.h>
85 #endif
86 #include <sys/stat.h>
87 #include <ctype.h>
88 #include <stdio.h>
89 #include <stdarg.h>
91 #include "eventdns.h"
92 #ifdef WIN32
93 #include <windows.h>
94 #include <winsock2.h>
95 #include <iphlpapi.h>
96 #else
97 #include <sys/socket.h>
98 #include <netinet/in.h>
99 #include <arpa/inet.h>
100 #endif
102 #ifdef HAVE_NETINET_IN6_H
103 #include <netinet/in6.h>
104 #endif
106 #ifdef WIN32
107 typedef int socklen_t;
108 #endif
110 #define EVDNS_LOG_DEBUG 0
111 #define EVDNS_LOG_WARN 1
113 #ifndef HOST_NAME_MAX
114 #define HOST_NAME_MAX 255
115 #endif
117 #ifndef NDEBUG
118 #include <stdio.h>
119 #endif
121 /* for debugging possible memory leaks. */
122 #define mm_malloc(x) tor_malloc(x)
123 #define mm_realloc(x,y) tor_realloc((x),(y))
124 #define mm_free(x) tor_free(x)
125 #define mm_strdup(x) tor_strdup(x)
126 #define _mm_free(x) _tor_free(x)
128 #undef MIN
129 #define MIN(a,b) ((a)<(b)?(a):(b))
131 #if 0
132 #ifdef __USE_ISOC99B
133 /* libevent doesn't work without this */
134 typedef uint8_t u_char;
135 typedef unsigned int uint;
136 #endif
137 #endif
138 #include <event.h>
140 #define u64 uint64_t
141 #define u32 uint32_t
142 #define u16 uint16_t
143 #define u8 uint8_t
145 #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
146 /* which we bother recording */
148 #define TYPE_A EVDNS_TYPE_A
149 #define TYPE_CNAME 5
150 #define TYPE_PTR EVDNS_TYPE_PTR
151 #define TYPE_AAAA EVDNS_TYPE_AAAA
153 #define CLASS_INET EVDNS_CLASS_INET
155 #define CLEAR(x) do { memset((x), 0xF0, sizeof(*(x))); } while(0)
157 struct evdns_request {
158 u8 *request; /* the dns packet data */
159 unsigned int request_len;
160 int reissue_count;
161 int tx_count; /* the number of times that this packet has been sent */
162 unsigned int request_type; /* TYPE_PTR or TYPE_A */
163 void *user_pointer; /* the pointer given to us for this request */
164 evdns_callback_type user_callback;
165 struct nameserver *ns; /* the server which we last sent it */
167 /* elements used by the searching code */
168 int search_index;
169 struct search_state *search_state;
170 char *search_origname; /* needs to be mm_free()ed */
171 int search_flags;
173 /* these objects are kept in a circular list */
174 struct evdns_request *next, *prev;
176 u16 timeout_event_deleted; /**< Debugging: where was timeout_event
177 * deleted? 0 for "it's added." */
178 struct event timeout_event;
180 u16 trans_id; /* the transaction id */
181 char request_appended; /* true if the request pointer is data which follows this struct */
182 char transmit_me; /* needs to be transmitted */
185 #ifndef HAVE_STRUCT_IN6_ADDR
186 struct in6_addr {
187 u8 s6_addr[16];
189 #endif
191 struct reply {
192 unsigned int type;
193 unsigned int have_answer;
194 union {
195 struct {
196 u32 addrcount;
197 u32 addresses[MAX_ADDRS];
198 } a;
199 struct {
200 u32 addrcount;
201 struct in6_addr addresses[MAX_ADDRS];
202 } aaaa;
203 struct {
204 char name[HOST_NAME_MAX];
205 } ptr;
206 } data;
209 struct nameserver {
210 int socket; /* a connected UDP socket */
211 struct sockaddr_storage address;
212 int failed_times; /* number of times which we have given this server a chance */
213 int timedout; /* number of times in a row a request has timed out */
214 struct event event;
215 /* these objects are kept in a circular list */
216 struct nameserver *next, *prev;
217 u16 timeout_event_deleted; /**< Debugging: where was timeout_event
218 * deleted? 0 for "it's added." */
219 struct event timeout_event; /* used to keep the timeout for */
220 /* when we next probe this server. */
221 /* Valid if state == 0 */
222 char state; /* zero if we think that this server is down */
223 char choked; /* true if we have an EAGAIN from this server's socket */
224 char write_waiting; /* true if we are waiting for EV_WRITE events */
227 static struct evdns_request *req_head = NULL, *req_waiting_head = NULL;
228 static struct nameserver *server_head = NULL;
230 /* Represents a local port where we're listening for DNS requests. Right now, */
231 /* only UDP is supported. */
232 struct evdns_server_port {
233 int socket; /* socket we use to read queries and write replies. */
234 int refcnt; /* reference count. */
235 char choked; /* Are we currently blocked from writing? */
236 char closing; /* Are we trying to close this port, pending writes? */
237 evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
238 void *user_data; /* Opaque pointer passed to user_callback */
239 struct event event; /* Read/write event */
240 /* circular list of replies that we want to write. */
241 struct server_request *pending_replies;
244 /* Represents part of a reply being built. (That is, a single RR.) */
245 struct server_reply_item {
246 struct server_reply_item *next; /* next item in sequence. */
247 char *name; /* name part of the RR */
248 u16 type : 16; /* The RR type */
249 u16 class : 16; /* The RR class (usually CLASS_INET) */
250 u32 ttl; /* The RR TTL */
251 char is_name; /* True iff data is a label */
252 u16 datalen; /* Length of data; -1 if data is a label */
253 void *data; /* The contents of the RR */
256 /* Represents a request that we've received as a DNS server, and holds */
257 /* the components of the reply as we're constructing it. */
258 struct server_request {
259 /* Pointers to the next and previous entries on the list of replies */
260 /* that we're waiting to write. Only set if we have tried to respond */
261 /* and gotten EAGAIN. */
262 struct server_request *next_pending;
263 struct server_request *prev_pending;
265 u16 trans_id; /* Transaction id. */
266 struct evdns_server_port *port; /* Which port received this request on? */
267 struct sockaddr_storage addr; /* Where to send the response */
268 socklen_t addrlen; /* length of addr */
270 int n_answer; /* how many answer RRs have been set? */
271 int n_authority; /* how many authority RRs have been set? */
272 int n_additional; /* how many additional RRs have been set? */
274 struct server_reply_item *answer; /* linked list of answer RRs */
275 struct server_reply_item *authority; /* linked list of authority RRs */
276 struct server_reply_item *additional; /* linked list of additional RRs */
278 /* Constructed response. Only set once we're ready to send a reply. */
279 /* Once this is set, the RR fields are cleared, and no more should be set. */
280 char *response;
281 size_t response_len;
283 /* Caller-visible fields: flags, questions. */
284 struct evdns_server_request base;
287 /* helper macro */
288 #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
290 /* Given a pointer to an evdns_server_request, get the corresponding */
291 /* server_request. */
292 #define TO_SERVER_REQUEST(base_ptr) \
293 ((struct server_request*) \
294 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
296 /* The number of good nameservers that we have */
297 static int global_good_nameservers = 0;
299 /* inflight requests are contained in the req_head list */
300 /* and are actually going out across the network */
301 static int global_requests_inflight = 0;
302 /* requests which aren't inflight are in the waiting list */
303 /* and are counted here */
304 static int global_requests_waiting = 0;
306 static int global_max_requests_inflight = 64;
308 static struct timeval global_timeout = {5, 0}; /* 5 seconds */
309 static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */
310 static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */
311 /* number of timeouts in a row before we consider this server to be down */
312 static int global_max_nameserver_timeout = 3;
314 /* true iff we should use the 0x20 hack. */
315 static int global_randomize_case = 1;
317 /* These are the timeout values for nameservers. If we find a nameserver is down */
318 /* we try to probe it at intervals as given below. Values are in seconds. */
319 static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
320 static const int global_nameserver_timeouts_length = (int)(sizeof(global_nameserver_timeouts)/sizeof(struct timeval));
322 static struct nameserver *nameserver_pick(void);
323 static void evdns_request_insert(struct evdns_request *req, struct evdns_request **head);
324 static void nameserver_ready_callback(int fd, short events, void *arg);
325 static int evdns_transmit(void);
326 static int evdns_request_transmit(struct evdns_request *req);
327 static void nameserver_send_probe(struct nameserver *const ns);
328 static void search_request_finished(struct evdns_request *const);
329 static int search_try_next(struct evdns_request *const req);
330 static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
331 static void evdns_requests_pump_waiting_queue(void);
332 static u16 transaction_id_pick(void);
333 static struct evdns_request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
334 static void request_submit(struct evdns_request *req);
336 static int server_request_free(struct server_request *req);
337 static void server_request_free_answers(struct server_request *req);
338 static void server_port_free(struct evdns_server_port *port);
339 static void server_port_ready_callback(int fd, short events, void *arg);
341 static int strtoint(const char *const str);
343 #ifdef WIN32
344 static int
345 last_error(int sock)
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;
356 return err;
359 static int
360 error_is_eagain(int err)
362 return err == EAGAIN || err == WSAEWOULDBLOCK;
364 #define inet_aton(c, addr) tor_inet_aton((c), (addr))
365 #define CLOSE_SOCKET(x) closesocket(x)
366 #else
367 #define last_error(sock) (errno)
368 #define error_is_eagain(err) ((err) == EAGAIN)
369 #define CLOSE_SOCKET(x) close(x)
370 #endif
372 #define ISSPACE(c) TOR_ISSPACE(c)
373 #define ISDIGIT(c) TOR_ISDIGIT(c)
374 #define ISALPHA(c) TOR_ISALPHA(c)
375 #define TOLOWER(c) TOR_TOLOWER(c)
376 #define TOUPPER(c) TOR_TOUPPER(c)
378 #ifndef NDEBUG
379 static const char *
380 debug_ntoa(u32 address)
382 static char buf[32];
383 u32 a = ntohl(address);
384 snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
385 (int)(u8)((a>>24)&0xff),
386 (int)(u8)((a>>16)&0xff),
387 (int)(u8)((a>>8 )&0xff),
388 (int)(u8)((a )&0xff));
389 return buf;
391 static const char *
392 debug_ntop(const struct sockaddr *sa)
394 if (sa->sa_family == AF_INET) {
395 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
396 return debug_ntoa(sin->sin_addr.s_addr);
398 if (sa->sa_family == AF_INET6) {
399 /* Tor-specific. In libevent, add more check code. */
400 static char buf[128];
401 struct sockaddr_in6 *sin = (struct sockaddr_in6 *) sa;
402 tor_inet_ntop(AF_INET6, &sin->sin6_addr, buf, sizeof(buf));
403 return buf;
405 return "<unknown>";
407 #endif
409 static evdns_debug_log_fn_type evdns_log_fn = NULL;
411 void
412 evdns_set_log_fn(evdns_debug_log_fn_type fn)
414 evdns_log_fn = fn;
417 #ifdef __GNUC__
418 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
419 #else
420 #define EVDNS_LOG_CHECK
421 #endif
423 static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
424 static void
425 _evdns_log(int warn, const char *fmt, ...)
427 va_list args;
428 static char buf[512];
429 if (!evdns_log_fn)
430 return;
431 va_start(args,fmt);
432 #ifdef WIN32
433 _vsnprintf(buf, sizeof(buf), fmt, args);
434 #else
435 vsnprintf(buf, sizeof(buf), fmt, args);
436 #endif
437 buf[sizeof(buf)-1] = '\0';
438 evdns_log_fn(warn, buf);
439 va_end(args);
442 #define log _evdns_log
444 static int
445 sockaddr_eq(const struct sockaddr *sa1, const struct sockaddr *sa2,
446 int include_port)
448 if (sa1->sa_family != sa2->sa_family)
449 return 0;
450 if (sa1->sa_family == AF_INET) {
451 const struct sockaddr_in *sin1, *sin2;
452 sin1 = (const struct sockaddr_in *)sa1;
453 sin2 = (const struct sockaddr_in *)sa2;
454 if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr)
455 return 0;
456 else if (include_port && sin1->sin_port != sin2->sin_port)
457 return 0;
458 else
459 return 1;
461 #ifdef AF_INET6
462 if (sa1->sa_family == AF_INET6) {
463 const struct sockaddr_in6 *sin1, *sin2;
464 sin1 = (const struct sockaddr_in6 *)sa1;
465 sin2 = (const struct sockaddr_in6 *)sa2;
466 if (memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16))
467 return 0;
468 else if (include_port && sin1->sin6_port != sin2->sin6_port)
469 return 0;
470 else
471 return 1;
473 #endif
474 return 1;
477 /* for debugging bug 929. XXXX021 */
478 static int
479 _add_timeout_event(u16 *lineno, struct event *ev, struct timeval *to)
481 *lineno = 0;
482 return evtimer_add(ev, to);
484 #define add_timeout_event(s, to) \
485 (_add_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, (to)))
487 /* for debugging bug 929. XXXX021 */
488 static int
489 _del_timeout_event(u16 *lineno, struct event *ev, int line)
491 if (*lineno) {
492 log(EVDNS_LOG_WARN,
493 "Duplicate timeout event_del from line %d: first call "
494 "was at %d.", line, (int)*lineno);
495 return 0;
496 } else {
497 *lineno = (u16)line;
498 return event_del(ev);
501 #define del_timeout_event(s) \
502 (_del_timeout_event(&(s)->timeout_event_deleted, &(s)->timeout_event, \
503 __LINE__))
505 /* This walks the list of inflight requests to find the */
506 /* one with a matching transaction id. Returns NULL on */
507 /* failure */
508 static struct evdns_request *
509 request_find_from_trans_id(u16 trans_id) {
510 struct evdns_request *req = req_head, *const started_at = req_head;
512 if (req) {
513 do {
514 if (req->trans_id == trans_id) return req;
515 req = req->next;
516 } while (req != started_at);
519 return NULL;
522 /* a libevent callback function which is called when a nameserver */
523 /* has gone down and we want to test if it has came back to life yet */
524 static void
525 nameserver_prod_callback(int fd, short events, void *arg) {
526 struct nameserver *const ns = (struct nameserver *) arg;
527 (void)fd;
528 (void)events;
530 nameserver_send_probe(ns);
533 /* a libevent callback which is called when a nameserver probe (to see if */
534 /* it has come back to life) times out. We increment the count of failed_times */
535 /* and wait longer to send the next probe packet. */
536 static void
537 nameserver_probe_failed(struct nameserver *const ns) {
538 const struct timeval * timeout;
539 del_timeout_event(ns);
540 CLEAR(&ns->timeout_event);
541 if (ns->state == 1) {
542 /* This can happen if the nameserver acts in a way which makes us mark */
543 /* it as bad and then starts sending good replies. */
544 return;
547 timeout =
548 &global_nameserver_timeouts[MIN(ns->failed_times,
549 global_nameserver_timeouts_length - 1)];
550 ns->failed_times++;
552 evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
553 if (add_timeout_event(ns, (struct timeval *) timeout) < 0) {
554 log(EVDNS_LOG_WARN,
555 "Error from libevent when adding timer event for %s",
556 debug_ntop((struct sockaddr *)&ns->address));
557 /* ???? Do more? */
561 /* called when a nameserver has been deemed to have failed. For example, too */
562 /* many packets have timed out etc */
563 static void
564 nameserver_failed(struct nameserver *const ns, const char *msg) {
565 struct evdns_request *req, *started_at;
566 /* if this nameserver has already been marked as failed */
567 /* then don't do anything */
568 if (!ns->state) return;
570 log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
571 debug_ntop((struct sockaddr *)&ns->address), msg);
572 global_good_nameservers--;
573 assert(global_good_nameservers >= 0);
574 if (global_good_nameservers == 0) {
575 log(EVDNS_LOG_WARN, "All nameservers have failed");
578 ns->state = 0;
579 ns->failed_times = 1;
581 evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
582 if (add_timeout_event(ns, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
583 log(EVDNS_LOG_WARN,
584 "Error from libevent when adding timer event for %s",
585 debug_ntop((struct sockaddr *)&ns->address));
586 /* ???? Do more? */
589 /* walk the list of inflight requests to see if any can be reassigned to */
590 /* a different server. Requests in the waiting queue don't have a */
591 /* nameserver assigned yet */
593 /* if we don't have *any* good nameservers then there's no point */
594 /* trying to reassign requests to one */
595 if (!global_good_nameservers) return;
597 req = req_head;
598 started_at = req_head;
599 if (req) {
600 do {
601 if (req->tx_count == 0 && req->ns == ns) {
602 /* still waiting to go out, can be moved */
603 /* to another server */
604 req->ns = nameserver_pick();
606 req = req->next;
607 } while (req != started_at);
611 static void
612 nameserver_up(struct nameserver *const ns) {
613 if (ns->state) return;
614 log(EVDNS_LOG_WARN, "Nameserver %s is back up",
615 debug_ntop((struct sockaddr *)&ns->address));
616 del_timeout_event(ns);
617 CLEAR(&ns->timeout_event);
618 ns->state = 1;
619 ns->failed_times = 0;
620 ns->timedout = 0;
621 global_good_nameservers++;
624 static void
625 request_trans_id_set(struct evdns_request *const req, const u16 trans_id) {
626 req->trans_id = trans_id;
627 *((u16 *) req->request) = htons(trans_id);
630 /* Called to remove a request from a list and dealloc it. */
631 /* head is a pointer to the head of the list it should be */
632 /* removed from or NULL if the request isn't in a list. */
633 static void
634 request_finished(struct evdns_request *const req, struct evdns_request **head) {
635 if (head) {
636 if (req->next == req) {
637 /* only item in the list */
638 *head = NULL;
639 } else {
640 req->next->prev = req->prev;
641 req->prev->next = req->next;
642 if (*head == req) *head = req->next;
646 log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
647 (unsigned long) req);
648 del_timeout_event(req);
649 CLEAR(&req->timeout_event);
651 search_request_finished(req);
652 global_requests_inflight--;
654 if (!req->request_appended) {
655 /* need to free the request data on it's own */
656 mm_free(req->request);
657 } else {
658 /* the request data is appended onto the header */
659 /* so everything gets mm_free()ed when we: */
662 CLEAR(req);
663 _mm_free(req);
665 evdns_requests_pump_waiting_queue();
668 /* This is called when a server returns a funny error code. */
669 /* We try the request again with another server. */
670 /* */
671 /* return: */
672 /* 0 ok */
673 /* 1 failed/reissue is pointless */
674 static int
675 request_reissue(struct evdns_request *req) {
676 const struct nameserver *const last_ns = req->ns;
677 /* the last nameserver should have been marked as failing */
678 /* by the caller of this function, therefore pick will try */
679 /* not to return it */
680 req->ns = nameserver_pick();
681 if (req->ns == last_ns) {
682 /* ... but pick did return it */
683 /* not a lot of point in trying again with the */
684 /* same server */
685 return 1;
688 req->reissue_count++;
689 req->tx_count = 0;
690 req->transmit_me = 1;
692 return 0;
695 /* this function looks for space on the inflight queue and promotes */
696 /* requests from the waiting queue if it can. */
697 static void
698 evdns_requests_pump_waiting_queue(void) {
699 while (global_requests_inflight < global_max_requests_inflight &&
700 global_requests_waiting) {
701 struct evdns_request *req;
702 /* move a request from the waiting queue to the inflight queue */
703 assert(req_waiting_head);
704 if (req_waiting_head->next == req_waiting_head) {
705 /* only one item in the queue */
706 req = req_waiting_head;
707 req_waiting_head = NULL;
708 } else {
709 req = req_waiting_head;
710 req->next->prev = req->prev;
711 req->prev->next = req->next;
712 req_waiting_head = req->next;
715 global_requests_waiting--;
716 global_requests_inflight++;
718 req->ns = nameserver_pick();
719 request_trans_id_set(req, transaction_id_pick());
721 evdns_request_insert(req, &req_head);
722 evdns_request_transmit(req);
723 evdns_transmit();
727 static void
728 reply_callback(struct evdns_request *const req, u32 ttl, u32 err, struct reply *reply) {
729 switch (req->request_type) {
730 case TYPE_A:
731 if (reply)
732 req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
733 reply->data.a.addrcount, ttl,
734 reply->data.a.addresses,
735 req->user_pointer);
736 else
737 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
738 return;
739 case TYPE_PTR:
740 if (reply) {
741 char *name = reply->data.ptr.name;
742 req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
743 &name, req->user_pointer);
744 } else {
745 req->user_callback(err, 0, 0, 0, NULL,
746 req->user_pointer);
748 return;
749 case TYPE_AAAA:
750 if (reply)
751 req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
752 reply->data.aaaa.addrcount, ttl,
753 reply->data.aaaa.addresses,
754 req->user_pointer);
755 else
756 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
757 return;
759 assert(0);
762 /* this processes a parsed reply packet */
763 static void
764 reply_handle(struct evdns_request *const req, u16 flags, u32 ttl, struct reply *reply) {
765 int error;
766 static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
768 if (flags & 0x020f || !reply || !reply->have_answer) {
769 /* there was an error */
770 if (flags & 0x0200) {
771 error = DNS_ERR_TRUNCATED;
772 } else {
773 u16 error_code = (flags & 0x000f) - 1;
774 if (error_code > 4) {
775 error = DNS_ERR_UNKNOWN;
776 } else {
777 error = error_codes[error_code];
781 switch(error) {
782 case DNS_ERR_NOTIMPL:
783 case DNS_ERR_REFUSED:
784 /* we regard these errors as marking a bad nameserver */
785 if (req->reissue_count < global_max_reissues) {
786 char msg[64];
787 snprintf(msg, sizeof(msg), "Bad response %d (%s)",
788 error, evdns_err_to_string(error));
789 nameserver_failed(req->ns, msg);
790 if (!request_reissue(req)) return;
792 break;
793 case DNS_ERR_SERVERFAILED:
794 /* rcode 2 (servfailed) sometimes means "we are broken" and
795 * sometimes (with some binds) means "that request was very
796 * confusing." Treat this as a timeout, not a failure.
798 /*XXXX refactor the parts of */
799 log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
800 "will allow the request to time out.",
801 debug_ntop((struct sockaddr *)&req->ns->address));
802 break;
803 default:
804 /* we got a good reply from the nameserver */
805 nameserver_up(req->ns);
808 if (req->search_state && req->request_type != TYPE_PTR) {
809 /* if we have a list of domains to search in, try the next one */
810 if (!search_try_next(req)) {
811 /* a new request was issued so this request is finished and */
812 /* the user callback will be made when that request (or a */
813 /* child of it) finishes. */
814 request_finished(req, &req_head);
815 return;
819 /* all else failed. Pass the failure up */
820 reply_callback(req, 0, error, NULL);
821 request_finished(req, &req_head);
822 } else {
823 /* all ok, tell the user */
824 reply_callback(req, ttl, 0, reply);
825 nameserver_up(req->ns);
826 request_finished(req, &req_head);
830 static INLINE int
831 name_parse(u8 *packet, int length, int *idx, char *name_out, size_t name_out_len) {
832 int name_end = -1;
833 int j = *idx;
834 int ptr_count = 0;
835 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
836 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
837 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
839 char *cp = name_out;
840 const char *const end = name_out + name_out_len;
842 /* Normally, names are a series of length prefixed strings terminated */
843 /* with a length of 0 (the lengths are u8's < 63). */
844 /* However, the length can start with a pair of 1 bits and that */
845 /* means that the next 14 bits are a pointer within the current */
846 /* packet. */
848 for(;;) {
849 u8 label_len;
850 if (j >= length) return -1;
851 GET8(label_len);
852 if (!label_len) break;
853 if (label_len & 0xc0) {
854 u8 ptr_low;
855 GET8(ptr_low);
856 if (name_end < 0) name_end = j;
857 j = (((int)label_len & 0x3f) << 8) + ptr_low;
858 /* Make sure that the target offset is in-bounds. */
859 if (j < 0 || j >= length) return -1;
860 /* If we've jumped more times than there are characters in the
861 * message, we must have a loop. */
862 if (++ptr_count > length) return -1;
863 continue;
865 if (label_len > 63) return -1;
866 if (cp != name_out) {
867 if (cp + 1 >= end) return -1;
868 *cp++ = '.';
870 if (cp + label_len >= end) return -1;
871 memcpy(cp, packet + j, label_len);
872 cp += label_len;
873 j += label_len;
875 if (cp >= end) return -1;
876 *cp = '\0';
877 if (name_end < 0)
878 *idx = j;
879 else
880 *idx = name_end;
881 return 0;
882 err:
883 return -1;
886 /* parses a raw reply from a nameserver. */
887 static int
888 reply_parse(u8 *packet, int length) {
889 int j = 0; /* index into packet */
890 int k;
891 u16 _t; /* used by the macros */
892 u32 _t32; /* used by the macros */
893 char tmp_name[256], cmp_name[256]; /* used by the macros */
895 u16 trans_id, questions, answers, authority, additional, datalength;
896 u16 flags = 0;
897 u32 ttl, ttl_r = 0xffffffff;
898 struct reply reply;
899 struct evdns_request *req = NULL;
900 unsigned int i;
901 int name_matches = 0;
903 GET16(trans_id);
904 GET16(flags);
905 GET16(questions);
906 GET16(answers);
907 GET16(authority);
908 GET16(additional);
909 (void) authority; /* suppress "unused variable" warnings. */
910 (void) additional; /* suppress "unused variable" warnings. */
912 req = request_find_from_trans_id(trans_id);
913 /* if no request, can't do anything. */
914 if (!req) return -1;
916 memset(&reply, 0, sizeof(reply));
918 /* If it's not an answer, it doesn't go with any of our requests. */
919 if (!(flags & 0x8000)) return -1; /* must be an answer */
920 if (flags & 0x020f) {
921 /* there was an error */
922 goto err;
924 /* if (!answers) return; */ /* must have an answer of some form */
926 /* This macro skips a name in the DNS reply. */
927 #define GET_NAME \
928 do { tmp_name[0] = '\0'; \
929 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
930 goto err; \
931 } while(0)
932 #define TEST_NAME \
933 do { tmp_name[0] = '\0'; \
934 cmp_name[0] = '\0'; \
935 k = j; \
936 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
937 goto err; \
938 if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \
939 goto err; \
940 if (global_randomize_case) { \
941 if (strcmp(tmp_name, cmp_name) == 0) \
942 name_matches = 1; /* we ignore mismatching names */ \
943 } else { \
944 if (strcasecmp(tmp_name, cmp_name) == 0) \
945 name_matches = 1; \
947 } while(0)
949 reply.type = req->request_type;
951 /* skip over each question in the reply */
952 for (i = 0; i < questions; ++i) {
953 /* the question looks like
954 * <label:name><u16:type><u16:class>
956 TEST_NAME;
957 j += 4;
958 if (j >= length) goto err;
961 if (!name_matches)
962 goto err;
964 /* now we have the answer section which looks like
965 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
968 for (i = 0; i < answers; ++i) {
969 u16 type, class;
971 GET_NAME;
972 GET16(type);
973 GET16(class);
974 GET32(ttl);
975 GET16(datalength);
977 if (type == TYPE_A && class == CLASS_INET) {
978 int addrcount, addrtocopy;
979 if (req->request_type != TYPE_A) {
980 j += datalength; continue;
982 if ((datalength & 3) != 0) /* not an even number of As. */
983 goto err;
984 addrcount = datalength >> 2;
985 addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
987 ttl_r = MIN(ttl_r, ttl);
988 /* we only bother with the first four addresses. */
989 if (j + 4*addrtocopy > length) goto err;
990 memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
991 packet + j, 4*addrtocopy);
992 reply.data.a.addrcount += addrtocopy;
993 reply.have_answer = 1;
994 if (reply.data.a.addrcount == MAX_ADDRS) break;
995 j += 4*addrtocopy;
996 } else if (type == TYPE_PTR && class == CLASS_INET) {
997 if (req->request_type != TYPE_PTR) {
998 j += datalength; continue;
1000 GET_NAME;
1001 strlcpy(reply.data.ptr.name, tmp_name,
1002 sizeof(reply.data.ptr.name));
1003 ttl_r = MIN(ttl_r, ttl);
1004 reply.have_answer = 1;
1005 break;
1006 } else if (type == TYPE_AAAA && class == CLASS_INET) {
1007 int addrcount, addrtocopy;
1008 if (req->request_type != TYPE_AAAA) {
1009 j += datalength; continue;
1011 if ((datalength & 15) != 0) /* not an even number of AAAAs. */
1012 goto err;
1013 addrcount = datalength >> 4; /* each address is 16 bytes long */
1014 addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
1015 ttl_r = MIN(ttl_r, ttl);
1017 /* we only bother with the first four addresses. */
1018 if (j + 16*addrtocopy > length) goto err;
1019 memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
1020 packet + j, 16*addrtocopy);
1021 reply.data.aaaa.addrcount += addrtocopy;
1022 reply.have_answer = 1;
1023 if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
1024 j += 16*addrtocopy;
1025 } else {
1026 /* skip over any other type of resource */
1027 j += datalength;
1031 reply_handle(req, flags, ttl_r, &reply);
1032 return 0;
1033 err:
1034 if (req)
1035 reply_handle(req, flags, 0, NULL);
1036 return -1;
1039 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1040 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1041 /* callback. */
1042 static int
1043 request_parse(u8 *packet, ssize_t length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
1045 int j = 0; /* index into packet */
1046 u16 _t; /* used by the macros */
1047 char tmp_name[256]; /* used by the macros */
1049 int i;
1050 u16 trans_id, flags, questions, answers, authority, additional;
1051 struct server_request *server_req = NULL;
1053 /* Get the header fields */
1054 GET16(trans_id);
1055 GET16(flags);
1056 GET16(questions);
1057 GET16(answers);
1058 GET16(authority);
1059 GET16(additional);
1061 if (flags & 0x8000) return -1; /* Must not be an answer. */
1062 flags &= 0x0110; /* Only RD and CD get preserved. */
1064 if (length > INT_MAX)
1065 return -1;
1067 server_req = mm_malloc(sizeof(struct server_request));
1068 if (server_req == NULL) return -1;
1069 memset(server_req, 0, sizeof(struct server_request));
1071 server_req->trans_id = trans_id;
1072 memcpy(&server_req->addr, addr, addrlen);
1073 server_req->addrlen = addrlen;
1075 server_req->base.flags = flags;
1076 server_req->base.nquestions = 0;
1077 server_req->base.questions = mm_malloc(sizeof(struct evdns_server_question *) * questions);
1078 if (server_req->base.questions == NULL)
1079 goto err;
1081 for (i = 0; i < questions; ++i) {
1082 u16 type, class;
1083 struct evdns_server_question *q;
1084 size_t namelen;
1085 if (name_parse(packet, (int)length, &j, tmp_name, sizeof(tmp_name))<0)
1086 goto err;
1087 GET16(type);
1088 GET16(class);
1089 namelen = strlen(tmp_name);
1090 q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
1091 if (!q)
1092 goto err;
1093 q->type = type;
1094 q->dns_question_class = class;
1095 memcpy(q->name, tmp_name, namelen+1);
1096 server_req->base.questions[server_req->base.nquestions++] = q;
1099 /* Ignore answers, authority, and additional. */
1101 server_req->port = port;
1102 port->refcnt++;
1104 /* Only standard queries are supported. */
1105 if (flags & 0x7800) {
1106 evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
1107 return -1;
1110 port->user_callback(&(server_req->base), port->user_data);
1112 return 0;
1113 err:
1114 if (server_req) {
1115 if (server_req->base.questions) {
1116 for (i = 0; i < server_req->base.nquestions; ++i)
1117 mm_free(server_req->base.questions[i]);
1118 mm_free(server_req->base.questions);
1120 CLEAR(server_req);
1121 mm_free(server_req);
1123 return -1;
1125 #undef SKIP_NAME
1126 #undef GET32
1127 #undef GET16
1128 #undef GET8
1131 static uint16_t
1132 default_transaction_id_fn(void)
1134 u16 trans_id;
1135 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
1136 struct timespec ts;
1137 #ifdef CLOCK_MONOTONIC
1138 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
1139 #else
1140 if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
1141 #endif
1142 event_err(1, "clock_gettime");
1143 trans_id = ts.tv_nsec & 0xffff;
1144 #endif
1146 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
1147 struct timeval tv;
1148 gettimeofday(&tv, NULL);
1149 trans_id = tv.tv_usec & 0xffff;
1150 #endif
1152 #ifdef DNS_USE_OPENSSL_FOR_ID
1153 if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
1154 /* in the case that the RAND call fails we back */
1155 /* down to using gettimeofday. */
1157 struct timeval tv;
1158 gettimeofday(&tv, NULL);
1159 trans_id = tv.tv_usec & 0xffff;
1161 abort();
1163 #endif
1164 return (unsigned short) trans_id;
1167 static uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
1169 static void
1170 default_random_bytes_fn(char *buf, size_t n)
1172 unsigned i;
1173 for (i = 0; i < n; i += 2) {
1174 u16 tid = trans_id_function();
1175 buf[i] = (tid >> 8) & 0xff;
1176 if (i+1<n)
1177 buf[i+1] = tid & 0xff;
1181 static void (*rand_bytes_function)(char *buf, size_t n) =
1182 default_random_bytes_fn;
1184 static u16
1185 trans_id_from_random_bytes_fn(void)
1187 u16 tid;
1188 rand_bytes_function((char*) &tid, sizeof(tid));
1189 return tid;
1192 void
1193 evdns_set_transaction_id_fn(uint16_t (*fn)(void))
1195 if (fn)
1196 trans_id_function = fn;
1197 else
1198 trans_id_function = default_transaction_id_fn;
1199 rand_bytes_function = default_random_bytes_fn;
1202 void
1203 evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
1205 rand_bytes_function = fn;
1206 trans_id_function = trans_id_from_random_bytes_fn;
1209 /* Try to choose a strong transaction id which isn't already in flight */
1210 static u16
1211 transaction_id_pick(void) {
1212 for (;;) {
1213 const struct evdns_request *req = req_head, *started_at;
1214 u16 trans_id = trans_id_function();
1216 if (trans_id == 0xffff) continue;
1217 /* now check to see if that id is already inflight */
1218 req = started_at = req_head;
1219 if (req) {
1220 do {
1221 if (req->trans_id == trans_id) break;
1222 req = req->next;
1223 } while (req != started_at);
1225 /* we didn't find it, so this is a good id */
1226 if (req == started_at) return trans_id;
1230 /* choose a namesever to use. This function will try to ignore */
1231 /* nameservers which we think are down and load balance across the rest */
1232 /* by updating the server_head global each time. */
1233 static struct nameserver *
1234 nameserver_pick(void) {
1235 struct nameserver *started_at = server_head, *picked;
1236 if (!server_head) return NULL;
1238 /* if we don't have any good nameservers then there's no */
1239 /* point in trying to find one. */
1240 if (!global_good_nameservers) {
1241 server_head = server_head->next;
1242 return server_head;
1245 /* remember that nameservers are in a circular list */
1246 for (;;) {
1247 if (server_head->state) {
1248 /* we think this server is currently good */
1249 picked = server_head;
1250 server_head = server_head->next;
1251 return picked;
1254 server_head = server_head->next;
1255 if (server_head == started_at) {
1256 /* all the nameservers seem to be down */
1257 /* so we just return this one and hope for the */
1258 /* best */
1259 assert(global_good_nameservers == 0);
1260 picked = server_head;
1261 server_head = server_head->next;
1262 return picked;
1267 /* this is called when a namesever socket is ready for reading */
1268 static void
1269 nameserver_read(struct nameserver *ns) {
1270 struct sockaddr_storage ss;
1271 struct sockaddr *sa = (struct sockaddr *) &ss;
1272 socklen_t addrlen = sizeof(ss);
1273 u8 packet[1500];
1275 for (;;) {
1276 const int r =
1277 (int)recvfrom(ns->socket, packet, (socklen_t)sizeof(packet), 0,
1278 sa, &addrlen);
1279 if (r < 0) {
1280 int err = last_error(ns->socket);
1281 if (error_is_eagain(err)) return;
1282 nameserver_failed(ns, strerror(err));
1283 return;
1285 /* XXX Match port too? */
1286 if (!sockaddr_eq(sa, (struct sockaddr*)&ns->address, 0)) {
1287 log(EVDNS_LOG_WARN,
1288 "Address mismatch on received DNS packet. Address was %s",
1289 debug_ntop(sa));
1290 return;
1292 ns->timedout = 0;
1293 reply_parse(packet, r);
1297 /* Read a packet from a DNS client on a server port s, parse it, and */
1298 /* act accordingly. */
1299 static void
1300 server_port_read(struct evdns_server_port *s) {
1301 u8 packet[1500];
1302 struct sockaddr_storage addr;
1303 socklen_t addrlen;
1304 ssize_t r;
1306 for (;;) {
1307 addrlen = (socklen_t)sizeof(struct sockaddr_storage);
1308 r = recvfrom(s->socket, packet, sizeof(packet), 0,
1309 (struct sockaddr*) &addr, &addrlen);
1310 if (r < 0) {
1311 int err = last_error(s->socket);
1312 if (error_is_eagain(err)) return;
1313 log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
1314 strerror(err), err);
1315 return;
1317 request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
1321 /* Try to write all pending replies on a given DNS server port. */
1322 static void
1323 server_port_flush(struct evdns_server_port *port)
1325 while (port->pending_replies) {
1326 struct server_request *req = port->pending_replies;
1327 ssize_t r = sendto(port->socket, req->response, req->response_len, 0,
1328 (struct sockaddr*) &req->addr, (socklen_t)req->addrlen);
1329 if (r < 0) {
1330 int err = last_error(port->socket);
1331 if (error_is_eagain(err))
1332 return;
1333 log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", strerror(err), err);
1335 if (server_request_free(req)) {
1336 /* we released the last reference to req->port. */
1337 return;
1341 /* We have no more pending requests; stop listening for 'writeable' events. */
1342 (void) event_del(&port->event);
1343 CLEAR(&port->event);
1344 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1345 server_port_ready_callback, port);
1346 if (event_add(&port->event, NULL) < 0) {
1347 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
1348 /* ???? Do more? */
1352 /* set if we are waiting for the ability to write to this server. */
1353 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1354 /* we stop these events. */
1355 static void
1356 nameserver_write_waiting(struct nameserver *ns, char waiting) {
1357 if (ns->write_waiting == waiting) return;
1359 ns->write_waiting = waiting;
1360 (void) event_del(&ns->event);
1361 CLEAR(&ns->event);
1362 event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1363 nameserver_ready_callback, ns);
1364 if (event_add(&ns->event, NULL) < 0) {
1365 log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
1366 debug_ntop((struct sockaddr *)&ns->address));
1367 /* ???? Do more? */
1371 /* a callback function. Called by libevent when the kernel says that */
1372 /* a nameserver socket is ready for writing or reading */
1373 static void
1374 nameserver_ready_callback(int fd, short events, void *arg) {
1375 struct nameserver *ns = (struct nameserver *) arg;
1376 (void)fd;
1378 if (events & EV_WRITE) {
1379 ns->choked = 0;
1380 if (!evdns_transmit()) {
1381 nameserver_write_waiting(ns, 0);
1384 if (events & EV_READ) {
1385 nameserver_read(ns);
1389 /* a callback function. Called by libevent when the kernel says that */
1390 /* a server socket is ready for writing or reading. */
1391 static void
1392 server_port_ready_callback(int fd, short events, void *arg) {
1393 struct evdns_server_port *port = (struct evdns_server_port *) arg;
1394 (void) fd;
1396 if (events & EV_WRITE) {
1397 port->choked = 0;
1398 server_port_flush(port);
1400 if (events & EV_READ) {
1401 server_port_read(port);
1405 /* This is an inefficient representation; only use it via the dnslabel_table_*
1406 * functions, so that is can be safely replaced with something smarter later. */
1407 #define MAX_LABELS 128
1408 /* Structures used to implement name compression */
1409 struct dnslabel_entry { char *v; off_t pos; };
1410 struct dnslabel_table {
1411 int n_labels; /* number of current entries */
1412 /* map from name to position in message */
1413 struct dnslabel_entry labels[MAX_LABELS];
1416 /* Initialize dnslabel_table. */
1417 static void
1418 dnslabel_table_init(struct dnslabel_table *table)
1420 table->n_labels = 0;
1423 /* Free all storage held by table, but not the table itself. */
1424 static void
1425 dnslabel_clear(struct dnslabel_table *table)
1427 int i;
1428 for (i = 0; i < table->n_labels; ++i)
1429 mm_free(table->labels[i].v);
1430 table->n_labels = 0;
1433 /* return the position of the label in the current message, or -1 if the label */
1434 /* hasn't been used yet. */
1435 static int
1436 dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
1438 int i;
1439 for (i = 0; i < table->n_labels; ++i) {
1440 if (!strcmp(label, table->labels[i].v)) {
1441 off_t pos = table->labels[i].pos;
1442 if (pos > 65535)
1443 return -1;
1444 return (int)pos;
1447 return -1;
1450 /* remember that we've used the label at position pos */
1451 static int
1452 dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
1454 char *v;
1455 int p;
1456 if (table->n_labels == MAX_LABELS)
1457 return (-1);
1458 v = mm_strdup(label);
1459 if (v == NULL)
1460 return (-1);
1461 p = table->n_labels++;
1462 table->labels[p].v = v;
1463 table->labels[p].pos = pos;
1465 return (0);
1468 /* Converts a string to a length-prefixed set of DNS labels, starting */
1469 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1470 /* of name. table is optional, and is used for compression. */
1471 /* */
1472 /* Input: abc.def */
1473 /* Output: <3>abc<3>def<0> */
1474 /* */
1475 /* Returns the first index after the encoded name, or negative on error. */
1476 /* -1 label was > 63 bytes */
1477 /* -2 name too long to fit in buffer. */
1478 /* */
1479 static off_t
1480 dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
1481 const char *name, const size_t name_len,
1482 struct dnslabel_table *table) {
1483 const char *end = name + name_len;
1484 int ref = 0;
1485 u16 _t;
1487 #define APPEND16(x) do { \
1488 if (j + 2 > (off_t)buf_len) \
1489 goto overflow; \
1490 _t = htons(x); \
1491 memcpy(buf + j, &_t, 2); \
1492 j += 2; \
1493 } while (0)
1494 #define APPEND32(x) do { \
1495 if (j + 4 > (off_t)buf_len) \
1496 goto overflow; \
1497 _t32 = htonl(x); \
1498 memcpy(buf + j, &_t32, 4); \
1499 j += 4; \
1500 } while (0)
1502 if (name_len > 255) return -2;
1504 for (;;) {
1505 const char *const start = name;
1506 if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1507 APPEND16(ref | 0xc000);
1508 return j;
1510 name = strchr(name, '.');
1511 if (!name) {
1512 const size_t label_len = end - start;
1513 if (label_len > 63) return -1;
1514 if ((size_t)(j+label_len+1) > buf_len) return -2;
1515 if (table) dnslabel_table_add(table, start, j);
1516 buf[j++] = (uint8_t)label_len;
1518 memcpy(buf + j, start, label_len);
1519 j += end - start;
1520 break;
1521 } else {
1522 /* append length of the label. */
1523 const size_t label_len = name - start;
1524 if (label_len > 63) return -1;
1525 if ((size_t)(j+label_len+1) > buf_len) return -2;
1526 if (table) dnslabel_table_add(table, start, j);
1527 buf[j++] = (uint8_t)label_len;
1529 memcpy(buf + j, start, name - start);
1530 j += name - start;
1531 /* hop over the '.' */
1532 name++;
1536 /* the labels must be terminated by a 0. */
1537 /* It's possible that the name ended in a . */
1538 /* in which case the zero is already there */
1539 if (!j || buf[j-1]) buf[j++] = 0;
1540 return j;
1541 overflow:
1542 return (-2);
1545 /* Finds the length of a dns request for a DNS name of the given */
1546 /* length. The actual request may be smaller than the value returned */
1547 /* here */
1548 static size_t
1549 evdns_request_len(const size_t name_len) {
1550 return 96 + /* length of the DNS standard header */
1551 name_len + 2 +
1552 4; /* space for the resource type */
1555 /* build a dns request packet into buf. buf should be at least as long */
1556 /* as evdns_request_len told you it should be. */
1557 /* */
1558 /* Returns the amount of space used. Negative on error. */
1559 static int
1560 evdns_request_data_build(const char *const name, const size_t name_len,
1561 const u16 trans_id, const u16 type, const u16 class,
1562 u8 *const buf, size_t buf_len) {
1563 off_t j = 0; /* current offset into buf */
1564 u16 _t; /* used by the macros */
1566 APPEND16(trans_id);
1567 APPEND16(0x0100); /* standard query, recusion needed */
1568 APPEND16(1); /* one question */
1569 APPEND16(0); /* no answers */
1570 APPEND16(0); /* no authority */
1571 APPEND16(0); /* no additional */
1573 j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1574 if (j < 0) {
1575 return (int)j;
1578 APPEND16(type);
1579 APPEND16(class);
1581 return (int)j;
1582 overflow:
1583 return (-1);
1586 /* exported function */
1587 struct evdns_server_port *
1588 evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
1590 struct evdns_server_port *port;
1591 if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
1592 return NULL;
1593 memset(port, 0, sizeof(struct evdns_server_port));
1595 assert(!is_tcp); /* TCP sockets not yet implemented */
1596 port->socket = socket;
1597 port->refcnt = 1;
1598 port->choked = 0;
1599 port->closing = 0;
1600 port->user_callback = cb;
1601 port->user_data = user_data;
1602 port->pending_replies = NULL;
1604 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1605 server_port_ready_callback, port);
1606 if (event_add(&port->event, NULL)<0) {
1607 mm_free(port);
1608 return NULL;
1610 return port;
1613 /* exported function */
1614 void
1615 evdns_close_server_port(struct evdns_server_port *port)
1617 port->closing = 1;
1618 if (--port->refcnt == 0)
1619 server_port_free(port);
1622 /* exported function */
1624 evdns_server_request_add_reply(struct evdns_server_request *_req, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
1626 struct server_request *req = TO_SERVER_REQUEST(_req);
1627 struct server_reply_item **itemp, *item;
1628 int *countp;
1630 if (req->response) /* have we already answered? */
1631 return (-1);
1633 switch (section) {
1634 case EVDNS_ANSWER_SECTION:
1635 itemp = &req->answer;
1636 countp = &req->n_answer;
1637 break;
1638 case EVDNS_AUTHORITY_SECTION:
1639 itemp = &req->authority;
1640 countp = &req->n_authority;
1641 break;
1642 case EVDNS_ADDITIONAL_SECTION:
1643 itemp = &req->additional;
1644 countp = &req->n_additional;
1645 break;
1646 default:
1647 return (-1);
1649 while (*itemp) {
1650 itemp = &((*itemp)->next);
1652 item = mm_malloc(sizeof(struct server_reply_item));
1653 if (!item)
1654 return -1;
1655 CLEAR(item);
1656 item->next = NULL;
1657 if (!(item->name = mm_strdup(name))) {
1658 CLEAR(item);
1659 mm_free(item);
1660 return -1;
1662 item->type = type;
1663 item->class = class;
1664 item->ttl = ttl;
1665 item->is_name = is_name != 0;
1666 item->datalen = 0;
1667 item->data = NULL;
1668 if (data) {
1669 if (item->is_name) {
1670 if (!(item->data = mm_strdup(data))) {
1671 mm_free(item->name);
1672 CLEAR(item);
1673 mm_free(item);
1674 return -1;
1676 item->datalen = (u16)-1;
1677 } else {
1678 if (!(item->data = mm_malloc(datalen))) {
1679 mm_free(item->name);
1680 CLEAR(item);
1681 mm_free(item);
1682 return -1;
1684 item->datalen = datalen;
1685 memcpy(item->data, data, datalen);
1689 *itemp = item;
1690 ++(*countp);
1691 return 0;
1694 /* exported function */
1696 evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1698 return evdns_server_request_add_reply(
1699 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1700 ttl, n*4, 0, addrs);
1703 /* exported function */
1705 evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1707 return evdns_server_request_add_reply(
1708 req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1709 ttl, n*16, 0, addrs);
1712 /* exported function */
1714 evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
1716 u32 a;
1717 char buf[32];
1718 assert(in || inaddr_name);
1719 assert(!(in && inaddr_name));
1720 if (in) {
1721 a = ntohl(in->s_addr);
1722 snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
1723 (int)(u8)((a )&0xff),
1724 (int)(u8)((a>>8 )&0xff),
1725 (int)(u8)((a>>16)&0xff),
1726 (int)(u8)((a>>24)&0xff));
1727 inaddr_name = buf;
1729 return evdns_server_request_add_reply(
1730 req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1731 ttl, -1, 1, hostname);
1734 /* exported function */
1736 evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
1738 return evdns_server_request_add_reply(
1739 req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
1740 ttl, -1, 1, cname);
1744 static int
1745 evdns_server_request_format_response(struct server_request *req, int err)
1747 unsigned char buf[1500];
1748 size_t buf_len = sizeof(buf);
1749 off_t j = 0, r;
1750 u16 _t;
1751 u32 _t32;
1752 int i;
1753 u16 flags;
1754 struct dnslabel_table table;
1756 if (err < 0 || err > 15) return -1;
1758 /* Set response bit and error code; copy OPCODE and RD fields from
1759 * question; copy RA and AA if set by caller. */
1760 flags = req->base.flags;
1761 flags |= (0x8000 | err);
1763 dnslabel_table_init(&table);
1764 APPEND16(req->trans_id);
1765 APPEND16(flags);
1766 APPEND16(req->base.nquestions);
1767 APPEND16(req->n_answer);
1768 APPEND16(req->n_authority);
1769 APPEND16(req->n_additional);
1771 /* Add questions. */
1772 for (i=0; i < req->base.nquestions; ++i) {
1773 const char *s = req->base.questions[i]->name;
1774 j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1775 if (j < 0) {
1776 dnslabel_clear(&table);
1777 return (int) j;
1779 APPEND16(req->base.questions[i]->type);
1780 APPEND16(req->base.questions[i]->dns_question_class);
1783 /* Add answer, authority, and additional sections. */
1784 for (i=0; i<3; ++i) {
1785 struct server_reply_item *item;
1786 if (i==0)
1787 item = req->answer;
1788 else if (i==1)
1789 item = req->authority;
1790 else
1791 item = req->additional;
1792 while (item) {
1793 r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1794 if (r < 0)
1795 goto overflow;
1796 j = r;
1798 APPEND16(item->type);
1799 APPEND16(item->class);
1800 APPEND32(item->ttl);
1801 if (item->is_name) {
1802 off_t len_idx = j, name_start;
1803 j += 2;
1804 name_start = j;
1805 r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1806 if (r < 0)
1807 goto overflow;
1808 j = r;
1809 _t = htons( (j-name_start) );
1810 memcpy(buf+len_idx, &_t, 2);
1811 } else {
1812 APPEND16(item->datalen);
1813 if (j+item->datalen > (off_t)buf_len)
1814 goto overflow;
1815 memcpy(buf+j, item->data, item->datalen);
1816 j += item->datalen;
1818 item = item->next;
1822 if (j > 512) {
1823 overflow:
1824 j = 512;
1825 buf[3] |= 0x02; /* set the truncated bit. */
1828 req->response_len = (size_t)j;
1830 if (!(req->response = mm_malloc(req->response_len))) {
1831 server_request_free_answers(req);
1832 dnslabel_clear(&table);
1833 return (-1);
1835 memcpy(req->response, buf, req->response_len);
1836 server_request_free_answers(req);
1837 dnslabel_clear(&table);
1838 return (0);
1841 /* exported function */
1843 evdns_server_request_respond(struct evdns_server_request *_req, int err)
1845 struct server_request *req = TO_SERVER_REQUEST(_req);
1846 struct evdns_server_port *port = req->port;
1847 ssize_t r;
1848 if (!req->response) {
1849 if ((r = evdns_server_request_format_response(req, err))<0)
1850 return (int)r;
1853 r = sendto(port->socket, req->response, req->response_len, 0,
1854 (struct sockaddr*) &req->addr, req->addrlen);
1855 if (r<0) {
1856 int err = last_error(port->socket);
1857 if (! error_is_eagain(err))
1858 return -1;
1860 if (port->pending_replies) {
1861 req->prev_pending = port->pending_replies->prev_pending;
1862 req->next_pending = port->pending_replies;
1863 req->prev_pending->next_pending =
1864 req->next_pending->prev_pending = req;
1865 } else {
1866 req->prev_pending = req->next_pending = req;
1867 port->pending_replies = req;
1868 port->choked = 1;
1870 (void) event_del(&port->event);
1871 CLEAR(&port->event);
1872 event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
1874 if (event_add(&port->event, NULL) < 0) {
1875 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
1880 return 1;
1882 if (server_request_free(req))
1883 return 0;
1885 if (port->pending_replies)
1886 server_port_flush(port);
1888 return 0;
1891 /* Free all storage held by RRs in req. */
1892 static void
1893 server_request_free_answers(struct server_request *req)
1895 struct server_reply_item *victim, *next, **list;
1896 int i;
1897 for (i = 0; i < 3; ++i) {
1898 if (i==0)
1899 list = &req->answer;
1900 else if (i==1)
1901 list = &req->authority;
1902 else
1903 list = &req->additional;
1905 victim = *list;
1906 while (victim) {
1907 next = victim->next;
1908 mm_free(victim->name);
1909 if (victim->data)
1910 mm_free(victim->data);
1911 mm_free(victim);
1912 victim = next;
1914 *list = NULL;
1918 /* Free all storage held by req, and remove links to it. */
1919 /* return true iff we just wound up freeing the server_port. */
1920 static int
1921 server_request_free(struct server_request *req)
1923 int i, rc=1;
1924 if (req->base.questions) {
1925 for (i = 0; i < req->base.nquestions; ++i)
1926 mm_free(req->base.questions[i]);
1927 mm_free(req->base.questions);
1930 if (req->port) {
1931 if (req->port->pending_replies == req) {
1932 if (req->next_pending)
1933 req->port->pending_replies = req->next_pending;
1934 else
1935 req->port->pending_replies = NULL;
1937 rc = --req->port->refcnt;
1940 if (req->response) {
1941 mm_free(req->response);
1944 server_request_free_answers(req);
1946 if (req->next_pending && req->next_pending != req) {
1947 req->next_pending->prev_pending = req->prev_pending;
1948 req->prev_pending->next_pending = req->next_pending;
1951 if (rc == 0) {
1952 server_port_free(req->port);
1953 CLEAR(req);
1954 mm_free(req);
1955 return (1);
1957 CLEAR(req);
1958 mm_free(req);
1959 return (0);
1962 /* Free all storage held by an evdns_server_port. Only called when the
1963 * reference count is down to 0. */
1964 static void
1965 server_port_free(struct evdns_server_port *port)
1967 assert(port);
1968 assert(!port->refcnt);
1969 assert(!port->pending_replies);
1970 if (port->socket > 0) {
1971 CLOSE_SOCKET(port->socket);
1972 port->socket = -1;
1974 (void) event_del(&port->event);
1975 CLEAR(&port->event);
1976 CLEAR(port);
1977 mm_free(port);
1980 /* exported function */
1982 evdns_server_request_drop(struct evdns_server_request *_req)
1984 struct server_request *req = TO_SERVER_REQUEST(_req);
1985 server_request_free(req);
1986 return 0;
1989 /* exported function */
1991 evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
1993 struct server_request *req = TO_SERVER_REQUEST(_req);
1994 if (addr_len < (int)req->addrlen)
1995 return -1;
1996 memcpy(sa, &(req->addr), req->addrlen);
1997 return req->addrlen;
2000 #undef APPEND16
2001 #undef APPEND32
2003 /* this is a libevent callback function which is called when a request */
2004 /* has timed out. */
2005 static void
2006 evdns_request_timeout_callback(int fd, short events, void *arg) {
2007 struct evdns_request *const req = (struct evdns_request *) arg;
2008 (void) fd;
2009 (void) events;
2011 log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
2013 req->ns->timedout++;
2014 if (req->ns->timedout > global_max_nameserver_timeout) {
2015 req->ns->timedout = 0;
2016 nameserver_failed(req->ns, "request timed out.");
2019 if (req->tx_count >= global_max_retransmits) {
2020 /* this request has failed */
2021 reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
2022 request_finished(req, &req_head);
2023 } else {
2024 /* retransmit it */
2025 /* Stop waiting for the timeout. No need to do this in
2026 * request_finished; that one already deletes the timeout event.
2027 * XXXX021 port this change to libevent. */
2028 del_timeout_event(req);
2029 CLEAR(&req->timeout_event);
2030 evdns_request_transmit(req);
2034 /* try to send a request to a given server. */
2035 /* */
2036 /* return: */
2037 /* 0 ok */
2038 /* 1 temporary failure */
2039 /* 2 other failure */
2040 static int
2041 evdns_request_transmit_to(struct evdns_request *req, struct nameserver *server) {
2042 const ssize_t r = send(server->socket, req->request, req->request_len, 0);
2043 if (r < 0) {
2044 int err = last_error(server->socket);
2045 if (error_is_eagain(err)) return 1;
2046 nameserver_failed(req->ns, strerror(err));
2047 return 2;
2048 } else if (r != (ssize_t)req->request_len) {
2049 return 1; /* short write */
2050 } else {
2051 return 0;
2055 /* try to send a request, updating the fields of the request */
2056 /* as needed */
2057 /* */
2058 /* return: */
2059 /* 0 ok */
2060 /* 1 failed */
2061 static int
2062 evdns_request_transmit(struct evdns_request *req) {
2063 int retcode = 0, r;
2065 /* if we fail to send this packet then this flag marks it */
2066 /* for evdns_transmit */
2067 req->transmit_me = 1;
2068 if (req->trans_id == 0xffff) abort();
2070 if (req->ns->choked) {
2071 /* don't bother trying to write to a socket */
2072 /* which we have had EAGAIN from */
2073 return 1;
2076 r = evdns_request_transmit_to(req, req->ns);
2077 switch (r) {
2078 case 1:
2079 /* temp failure */
2080 req->ns->choked = 1;
2081 nameserver_write_waiting(req->ns, 1);
2082 return 1;
2083 case 2:
2084 /* failed to transmit the request entirely. */
2085 retcode = 1;
2086 /* fall through: we'll set a timeout, which will time out,
2087 * and make us retransmit the request anyway. */
2088 default:
2089 /* transmitted; we need to check for timeout. */
2090 log(EVDNS_LOG_DEBUG,
2091 "Setting timeout for request %lx", (unsigned long) req);
2092 evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
2093 if (add_timeout_event(req, &global_timeout) < 0) {
2094 log(EVDNS_LOG_WARN,
2095 "Error from libevent when adding timer for request %lx",
2096 (unsigned long) req);
2097 /* ???? Do more? */
2099 req->tx_count++;
2100 req->transmit_me = 0;
2101 return retcode;
2105 static void
2106 nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
2107 struct sockaddr *addr = arg;
2108 struct nameserver *server;
2109 (void) type;
2110 (void) count;
2111 (void) ttl;
2112 (void) addresses;
2114 for (server = server_head; server; server = server->next) {
2115 if (sockaddr_eq(addr, (struct sockaddr*) &server->address, 1)) {
2116 if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
2117 /* this is a good reply */
2118 nameserver_up(server);
2119 } else {
2120 nameserver_probe_failed(server);
2123 if (server->next == server_head)
2124 break;
2127 mm_free(addr);
2130 static void
2131 nameserver_send_probe(struct nameserver *const ns) {
2132 struct evdns_request *req;
2133 struct sockaddr_storage *addr;
2134 /* here we need to send a probe to a given nameserver */
2135 /* in the hope that it is up now. */
2137 /* We identify the nameserver by its address, in case it is removed before
2138 * our probe comes back. */
2139 addr = mm_malloc(sizeof(struct sockaddr_storage));
2140 memcpy(addr, &ns->address, sizeof(struct sockaddr_storage));
2142 log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntop((struct sockaddr *)&ns->address));
2144 req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, addr);
2145 if (!req) {
2146 mm_free(addr);
2147 return;
2149 /* we force this into the inflight queue no matter what */
2150 request_trans_id_set(req, transaction_id_pick());
2151 req->ns = ns;
2152 request_submit(req);
2155 /* returns: */
2156 /* 0 didn't try to transmit anything */
2157 /* 1 tried to transmit something */
2158 static int
2159 evdns_transmit(void) {
2160 char did_try_to_transmit = 0;
2162 if (req_head) {
2163 struct evdns_request *const started_at = req_head, *req = req_head;
2164 /* first transmit all the requests which are currently waiting */
2165 do {
2166 if (req->transmit_me) {
2167 did_try_to_transmit = 1;
2168 evdns_request_transmit(req);
2171 req = req->next;
2172 } while (req != started_at);
2175 return did_try_to_transmit;
2178 /* exported function */
2180 evdns_count_nameservers(void)
2182 const struct nameserver *server = server_head;
2183 int n = 0;
2184 if (!server)
2185 return 0;
2186 do {
2187 ++n;
2188 server = server->next;
2189 } while (server != server_head);
2190 return n;
2193 /* exported function */
2195 evdns_clear_nameservers_and_suspend(void)
2197 struct nameserver *server = server_head, *started_at = server_head;
2198 struct evdns_request *req = req_head, *req_started_at = req_head;
2200 if (!server)
2201 return 0;
2202 while (1) {
2203 struct nameserver *next = server->next;
2204 (void) event_del(&server->event);
2205 CLEAR(&server->event);
2206 del_timeout_event(server);
2207 CLEAR(&server->timeout_event);
2208 if (server->socket >= 0)
2209 CLOSE_SOCKET(server->socket);
2210 CLEAR(server);
2211 mm_free(server);
2212 if (next == started_at)
2213 break;
2214 server = next;
2216 server_head = NULL;
2217 global_good_nameservers = 0;
2219 while (req) {
2220 struct evdns_request *next = req->next;
2221 req->tx_count = req->reissue_count = 0;
2222 req->ns = NULL;
2223 /* ???? What to do about searches? */
2224 del_timeout_event(req);
2225 CLEAR(&req->timeout_event);
2226 req->trans_id = 0;
2227 req->transmit_me = 0;
2229 global_requests_waiting++;
2230 evdns_request_insert(req, &req_waiting_head);
2231 /* We want to insert these suspended elements at the front of
2232 * the waiting queue, since they were pending before any of
2233 * the waiting entries were added. This is a circular list,
2234 * so we can just shift the start back by one.*/
2235 req_waiting_head = req_waiting_head->prev;
2237 if (next == req_started_at)
2238 break;
2239 req = next;
2241 req_head = NULL;
2242 global_requests_inflight = 0;
2244 return 0;
2247 static struct sockaddr_storage global_bind_address;
2248 static socklen_t global_bind_addrlen = 0;
2249 static int global_bind_addr_is_set = 0;
2250 void
2251 evdns_set_default_outgoing_bind_address(const struct sockaddr *addr,
2252 socklen_t addrlen)
2254 memset(&global_bind_address, 0, sizeof(global_bind_address));
2255 if (addr) {
2256 assert(addrlen <= (socklen_t)sizeof(global_bind_address));
2257 memcpy(&global_bind_address, addr, addrlen);
2258 global_bind_addrlen = addrlen;
2259 global_bind_addr_is_set = 1;
2260 } else {
2261 global_bind_addr_is_set = 0;
2265 /* exported function */
2267 evdns_resume(void)
2269 evdns_requests_pump_waiting_queue();
2270 return 0;
2273 static int
2274 _evdns_nameserver_add_impl(const struct sockaddr *address,
2275 socklen_t addrlen) {
2276 /* first check to see if we already have this nameserver */
2278 const struct nameserver *server = server_head, *const started_at = server_head;
2279 struct nameserver *ns;
2281 int err = 0;
2282 if (server) {
2283 do {
2284 if (sockaddr_eq(address, (struct sockaddr *)&server->address, 1)) {
2285 log(EVDNS_LOG_DEBUG, "Duplicate nameserver.");
2286 return 3;
2288 server = server->next;
2289 } while (server != started_at);
2291 if (addrlen > (int)sizeof(ns->address)) {
2292 log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
2293 return 2;
2296 ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
2297 if (!ns) return -1;
2299 memset(ns, 0, sizeof(struct nameserver));
2301 ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
2302 if (ns->socket < 0) { err = 1; goto out1; }
2303 #ifdef WIN32
2305 u_long nonblocking = 1;
2306 ioctlsocket(ns->socket, FIONBIO, &nonblocking);
2308 #else
2309 fcntl(ns->socket, F_SETFL, O_NONBLOCK);
2310 #endif
2312 if (global_bind_addr_is_set) {
2313 if (bind(ns->socket, (struct sockaddr *)&global_bind_address,
2314 global_bind_addrlen) < 0) {
2315 log(EVDNS_LOG_DEBUG, "Couldn't bind to outgoing address.");
2316 err = 2;
2317 goto out2;
2321 if (connect(ns->socket, address, addrlen) != 0) {
2322 log(EVDNS_LOG_DEBUG, "Couldn't open socket to nameserver.");
2323 err = 2;
2324 goto out2;
2327 memcpy(&ns->address, address, addrlen);
2328 ns->state = 1;
2329 event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
2330 if (event_add(&ns->event, NULL) < 0) {
2331 log(EVDNS_LOG_DEBUG, "Couldn't add event for nameserver.");
2332 err = 2;
2333 goto out2;
2336 log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntop(address));
2338 /* insert this nameserver into the list of them */
2339 if (!server_head) {
2340 ns->next = ns->prev = ns;
2341 server_head = ns;
2342 } else {
2343 ns->next = server_head->next;
2344 ns->prev = server_head;
2345 server_head->next = ns;
2346 if (server_head->prev == server_head) {
2347 server_head->prev = ns;
2351 global_good_nameservers++;
2353 return 0;
2355 out2:
2356 CLOSE_SOCKET(ns->socket);
2357 out1:
2358 CLEAR(ns);
2359 mm_free(ns);
2360 log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntop(address), err);
2361 return err;
2364 /* exported function */
2366 evdns_nameserver_add(unsigned long int address) {
2367 struct sockaddr_in sin;
2368 memset(&sin, 0, sizeof(sin));
2369 sin.sin_family = AF_INET;
2370 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2371 sin.sin_len = sizeof(sin);
2372 #endif
2373 sin.sin_addr.s_addr = htonl(address);
2374 sin.sin_port = 53;
2375 return _evdns_nameserver_add_impl((struct sockaddr*) &sin, sizeof(sin));
2378 /* exported function */
2380 evdns_nameserver_ip_add(const char *ip_as_string) {
2381 int port;
2382 char buf[128];
2383 const char *cp, *addr_part, *port_part;
2384 int is_ipv6;
2385 /* recognized formats are:
2386 * [ipv6]:port
2387 * ipv6
2388 * [ipv6]
2389 * ipv4:port
2390 * ipv4
2393 log(EVDNS_LOG_DEBUG, "Trying to add nameserver <%s>", ip_as_string);
2395 cp = strchr(ip_as_string, ':');
2396 if (*ip_as_string == '[') {
2397 int len;
2398 if (!(cp = strchr(ip_as_string, ']'))) {
2399 log(EVDNS_LOG_DEBUG, "Nameserver missing closing ]");
2400 return 4;
2402 len = cp-(ip_as_string + 1);
2403 if (len > (int)sizeof(buf)-1) {
2404 log(EVDNS_LOG_DEBUG, "[Nameserver] does not fit in buffer.");
2405 return 4;
2407 memcpy(buf, ip_as_string+1, len);
2408 buf[len] = '\0';
2409 addr_part = buf;
2410 if (cp[1] == ':')
2411 port_part = cp+2;
2412 else
2413 port_part = NULL;
2414 is_ipv6 = 1;
2415 } else if (cp && strchr(cp+1, ':')) {
2416 is_ipv6 = 1;
2417 addr_part = ip_as_string;
2418 port_part = NULL;
2419 } else if (cp) {
2420 is_ipv6 = 0;
2421 if (cp - ip_as_string > (int)sizeof(buf)-1) {
2422 log(EVDNS_LOG_DEBUG, "Nameserver does not fit in buffer.");
2423 return 4;
2425 memcpy(buf, ip_as_string, cp-ip_as_string);
2426 buf[cp-ip_as_string] = '\0';
2427 addr_part = buf;
2428 port_part = cp+1;
2429 } else {
2430 addr_part = ip_as_string;
2431 port_part = NULL;
2432 is_ipv6 = 0;
2435 if (port_part == NULL) {
2436 port = 53;
2437 } else {
2438 port = strtoint(port_part);
2439 if (port <= 0 || port > 65535) {
2440 log(EVDNS_LOG_DEBUG, "Nameserver port <%s> out of range",
2441 port_part);
2442 return 4;
2446 /* Tor-only. needs a more general fix. */
2447 assert(addr_part);
2448 if (is_ipv6) {
2449 struct sockaddr_in6 sin6;
2450 memset(&sin6, 0, sizeof(sin6));
2451 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2452 sin6.sin6_len = sizeof(sin6);
2453 #endif
2454 sin6.sin6_family = AF_INET6;
2455 sin6.sin6_port = htons(port);
2456 if (1 != tor_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) {
2457 log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
2458 return 4;
2460 return _evdns_nameserver_add_impl((struct sockaddr*)&sin6,
2461 sizeof(sin6));
2462 } else {
2463 struct sockaddr_in sin;
2464 memset(&sin, 0, sizeof(sin));
2465 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2466 sin.sin_len = sizeof(sin);
2467 #endif
2468 sin.sin_family = AF_INET;
2469 sin.sin_port = htons(port);
2470 if (!inet_aton(addr_part, &sin.sin_addr)) {
2471 log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
2472 return 4;
2474 return _evdns_nameserver_add_impl((struct sockaddr*)&sin,
2475 sizeof(sin));
2480 evdns_nameserver_sockaddr_add(const struct sockaddr *sa, socklen_t len)
2482 return _evdns_nameserver_add_impl(sa, len);
2485 /* insert into the tail of the queue */
2486 static void
2487 evdns_request_insert(struct evdns_request *req, struct evdns_request **head) {
2488 if (!*head) {
2489 *head = req;
2490 req->next = req->prev = req;
2491 return;
2494 req->prev = (*head)->prev;
2495 req->prev->next = req;
2496 req->next = *head;
2497 (*head)->prev = req;
2500 static int
2501 string_num_dots(const char *s) {
2502 int count = 0;
2503 while ((s = strchr(s, '.'))) {
2504 s++;
2505 count++;
2507 return count;
2510 static struct evdns_request *
2511 request_new(int type, const char *name, int flags,
2512 evdns_callback_type callback, void *user_ptr) {
2513 const char issuing_now =
2514 (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
2516 const size_t name_len = strlen(name);
2517 const size_t request_max_len = evdns_request_len(name_len);
2518 const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
2519 /* the request data is alloced in a single block with the header */
2520 struct evdns_request *const req =
2521 (struct evdns_request *) mm_malloc(sizeof(struct evdns_request) + request_max_len);
2522 char namebuf[256];
2523 int rlen;
2524 (void) flags;
2526 if (!req) return NULL;
2528 if (name_len >= sizeof(namebuf)) {
2529 _mm_free(req);
2530 return NULL;
2533 memset(req, 0, sizeof(struct evdns_request));
2535 if (global_randomize_case) {
2536 unsigned i;
2537 char randbits[32];
2538 strlcpy(namebuf, name, sizeof(namebuf));
2539 rand_bytes_function(randbits, (name_len+7)/8);
2540 for (i = 0; i < name_len; ++i) {
2541 if (ISALPHA(namebuf[i])) {
2542 if ((randbits[i >> 3] & (1<<(i%7))))
2543 namebuf[i] = TOLOWER(namebuf[i]);
2544 else
2545 namebuf[i] = TOUPPER(namebuf[i]);
2548 name = namebuf;
2551 /* request data lives just after the header */
2552 req->request = ((u8 *) req) + sizeof(struct evdns_request);
2553 /* denotes that the request data shouldn't be mm_free()ed */
2554 req->request_appended = 1;
2555 rlen = evdns_request_data_build(name, name_len, trans_id,
2556 type, CLASS_INET, req->request, request_max_len);
2557 if (rlen < 0)
2558 goto err1;
2559 req->request_len = rlen;
2560 req->trans_id = trans_id;
2561 req->tx_count = 0;
2562 req->request_type = type;
2563 req->user_pointer = user_ptr;
2564 req->user_callback = callback;
2565 req->ns = issuing_now ? nameserver_pick() : NULL;
2566 req->next = req->prev = NULL;
2568 return req;
2569 err1:
2570 CLEAR(req);
2571 _mm_free(req);
2572 return NULL;
2575 static void
2576 request_submit(struct evdns_request *const req) {
2577 if (req->ns) {
2578 /* if it has a nameserver assigned then this is going */
2579 /* straight into the inflight queue */
2580 evdns_request_insert(req, &req_head);
2581 global_requests_inflight++;
2582 evdns_request_transmit(req);
2583 } else {
2584 evdns_request_insert(req, &req_waiting_head);
2585 global_requests_waiting++;
2589 /* exported function */
2590 int evdns_resolve_ipv4(const char *name, int flags,
2591 evdns_callback_type callback, void *ptr) {
2592 log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2593 if (flags & DNS_QUERY_NO_SEARCH) {
2594 struct evdns_request *const req =
2595 request_new(TYPE_A, name, flags, callback, ptr);
2596 if (req == NULL)
2597 return (1);
2598 request_submit(req);
2599 return (0);
2600 } else {
2601 return (search_request_new(TYPE_A, name, flags, callback, ptr));
2605 /* exported function */
2606 int evdns_resolve_ipv6(const char *name, int flags,
2607 evdns_callback_type callback, void *ptr) {
2608 log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2609 if (flags & DNS_QUERY_NO_SEARCH) {
2610 struct evdns_request *const req =
2611 request_new(TYPE_AAAA, name, flags, callback, ptr);
2612 if (req == NULL)
2613 return (1);
2614 request_submit(req);
2615 return (0);
2616 } else {
2617 return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
2621 int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2622 char buf[32];
2623 struct evdns_request *req;
2624 u32 a;
2625 assert(in);
2626 a = ntohl(in->s_addr);
2627 snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
2628 (int)(u8)((a )&0xff),
2629 (int)(u8)((a>>8 )&0xff),
2630 (int)(u8)((a>>16)&0xff),
2631 (int)(u8)((a>>24)&0xff));
2632 log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2633 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2634 if (!req) return 1;
2635 request_submit(req);
2636 return 0;
2639 int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2640 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2641 char buf[73];
2642 char *cp;
2643 struct evdns_request *req;
2644 int i;
2645 assert(in);
2646 cp = buf;
2647 for (i=15; i >= 0; --i) {
2648 u8 byte = in->s6_addr[i];
2649 *cp++ = "0123456789abcdef"[byte & 0x0f];
2650 *cp++ = '.';
2651 *cp++ = "0123456789abcdef"[byte >> 4];
2652 *cp++ = '.';
2654 assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
2655 memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
2656 log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2657 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2658 if (!req) return 1;
2659 request_submit(req);
2660 return 0;
2663 /*/////////////////////////////////////////////////////////////////// */
2664 /* Search support */
2665 /* */
2666 /* the libc resolver has support for searching a number of domains */
2667 /* to find a name. If nothing else then it takes the single domain */
2668 /* from the gethostname() call. */
2669 /* */
2670 /* It can also be configured via the domain and search options in a */
2671 /* resolv.conf. */
2672 /* */
2673 /* The ndots option controls how many dots it takes for the resolver */
2674 /* to decide that a name is non-local and so try a raw lookup first. */
2676 struct search_domain {
2677 size_t len;
2678 struct search_domain *next;
2679 /* the text string is appended to this structure */
2682 struct search_state {
2683 int refcount;
2684 int ndots;
2685 int num_domains;
2686 struct search_domain *head;
2689 static struct search_state *global_search_state = NULL;
2691 static void
2692 search_state_decref(struct search_state *const state) {
2693 if (!state) return;
2694 state->refcount--;
2695 if (!state->refcount) {
2696 struct search_domain *next, *dom;
2697 for (dom = state->head; dom; dom = next) {
2698 next = dom->next;
2699 CLEAR(dom);
2700 _mm_free(dom);
2702 CLEAR(state);
2703 _mm_free(state);
2707 static struct search_state *
2708 search_state_new(void) {
2709 struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
2710 if (!state) return NULL;
2711 memset(state, 0, sizeof(struct search_state));
2712 state->refcount = 1;
2713 state->ndots = 1;
2715 return state;
2718 static void
2719 search_postfix_clear(void) {
2720 search_state_decref(global_search_state);
2722 global_search_state = search_state_new();
2725 /* exported function */
2726 void
2727 evdns_search_clear(void) {
2728 search_postfix_clear();
2731 static void
2732 search_postfix_add(const char *domain) {
2733 size_t domain_len;
2734 struct search_domain *sdomain;
2735 while (domain[0] == '.') domain++;
2736 domain_len = strlen(domain);
2738 if (!global_search_state) global_search_state = search_state_new();
2739 if (!global_search_state) return;
2740 global_search_state->num_domains++;
2742 sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
2743 if (!sdomain) return;
2744 memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
2745 sdomain->next = global_search_state->head;
2746 sdomain->len = domain_len;
2748 global_search_state->head = sdomain;
2751 /* reverse the order of members in the postfix list. This is needed because, */
2752 /* when parsing resolv.conf we push elements in the wrong order */
2753 static void
2754 search_reverse(void) {
2755 struct search_domain *cur, *prev = NULL, *next;
2756 cur = global_search_state->head;
2757 while (cur) {
2758 next = cur->next;
2759 cur->next = prev;
2760 prev = cur;
2761 cur = next;
2764 global_search_state->head = prev;
2767 /* exported function */
2768 void
2769 evdns_search_add(const char *domain) {
2770 search_postfix_add(domain);
2773 /* exported function */
2774 void
2775 evdns_search_ndots_set(const int ndots) {
2776 if (!global_search_state) global_search_state = search_state_new();
2777 if (!global_search_state) return;
2778 global_search_state->ndots = ndots;
2781 static void
2782 search_set_from_hostname(void) {
2783 char hostname[HOST_NAME_MAX + 1], *domainname;
2785 search_postfix_clear();
2786 if (gethostname(hostname, sizeof(hostname))) return;
2787 domainname = strchr(hostname, '.');
2788 if (!domainname) return;
2789 search_postfix_add(domainname);
2792 /* warning: returns malloced string */
2793 static char *
2794 search_make_new(const struct search_state *const state, int n, const char *const base_name) {
2795 const size_t base_len = strlen(base_name);
2796 const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
2797 struct search_domain *dom;
2799 for (dom = state->head; dom; dom = dom->next) {
2800 if (!n--) {
2801 /* this is the postfix we want */
2802 /* the actual postfix string is kept at the end of the structure */
2803 const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
2804 const size_t postfix_len = dom->len;
2805 char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
2806 if (!newname) return NULL;
2807 memcpy(newname, base_name, base_len);
2808 if (need_to_append_dot) newname[base_len] = '.';
2809 memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
2810 newname[base_len + need_to_append_dot + postfix_len] = 0;
2811 return newname;
2815 /* we ran off the end of the list and still didn't find the requested string */
2816 abort();
2817 return NULL; /* unreachable; stops warnings in some compilers. */
2820 static int
2821 search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
2822 assert(type == TYPE_A || type == TYPE_AAAA);
2823 if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
2824 global_search_state &&
2825 global_search_state->num_domains) {
2826 /* we have some domains to search */
2827 struct evdns_request *req;
2828 if (string_num_dots(name) >= global_search_state->ndots) {
2829 req = request_new(type, name, flags, user_callback, user_arg);
2830 if (!req) return 1;
2831 req->search_index = -1;
2832 } else {
2833 char *const new_name = search_make_new(global_search_state, 0, name);
2834 if (!new_name) return 1;
2835 req = request_new(type, new_name, flags, user_callback, user_arg);
2836 _mm_free(new_name);
2837 if (!req) return 1;
2838 req->search_index = 0;
2840 req->search_origname = mm_strdup(name);
2841 req->search_state = global_search_state;
2842 req->search_flags = flags;
2843 global_search_state->refcount++;
2844 request_submit(req);
2845 return 0;
2846 } else {
2847 struct evdns_request *const req = request_new(type, name, flags, user_callback, user_arg);
2848 if (!req) return 1;
2849 request_submit(req);
2850 return 0;
2854 /* this is called when a request has failed to find a name. We need to check */
2855 /* if it is part of a search and, if so, try the next name in the list */
2856 /* returns: */
2857 /* 0 another request has been submitted */
2858 /* 1 no more requests needed */
2859 static int
2860 search_try_next(struct evdns_request *const req) {
2861 if (req->search_state) {
2862 /* it is part of a search */
2863 char *new_name;
2864 struct evdns_request *newreq;
2865 req->search_index++;
2866 if (req->search_index >= req->search_state->num_domains) {
2867 /* no more postfixes to try, however we may need to try */
2868 /* this name without a postfix */
2869 if (string_num_dots(req->search_origname) < req->search_state->ndots) {
2870 /* yep, we need to try it raw */
2871 struct evdns_request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
2872 log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
2873 if (newreq) {
2874 request_submit(newreq);
2875 return 0;
2878 return 1;
2881 new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
2882 if (!new_name) return 1;
2883 log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
2884 newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
2885 mm_free(new_name);
2886 if (!newreq) return 1;
2887 newreq->search_origname = req->search_origname;
2888 req->search_origname = NULL;
2889 newreq->search_state = req->search_state;
2890 newreq->search_flags = req->search_flags;
2891 newreq->search_index = req->search_index;
2892 newreq->search_state->refcount++;
2893 request_submit(newreq);
2894 return 0;
2896 return 1;
2899 static void
2900 search_request_finished(struct evdns_request *const req) {
2901 if (req->search_state) {
2902 search_state_decref(req->search_state);
2903 req->search_state = NULL;
2905 if (req->search_origname) {
2906 mm_free(req->search_origname);
2907 req->search_origname = NULL;
2911 /*/////////////////////////////////////////////////////////////////// */
2912 /* Parsing resolv.conf files */
2914 static void
2915 evdns_resolv_set_defaults(int flags) {
2916 /* if the file isn't found then we assume a local resolver */
2917 if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
2918 if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
2921 #ifndef HAVE_STRTOK_R
2922 static char *
2923 strtok_r(char *s, const char *delim, char **state) {
2924 (void)state;
2925 return strtok(s, delim);
2927 #endif
2929 /* helper version of atoi which returns -1 on error */
2930 static int
2931 strtoint(const char *const str) {
2932 char *endptr;
2933 const long r = strtol(str, &endptr, 10);
2934 if (*endptr || r > INT_MAX) return -1;
2935 return (int)r;
2938 /* helper version of atoi that returns -1 on error and clips to bounds. */
2939 static int
2940 strtoint_clipped(const char *const str, int min, int max)
2942 int r = strtoint(str);
2943 if (r == -1)
2944 return r;
2945 else if (r<min)
2946 return min;
2947 else if (r>max)
2948 return max;
2949 else
2950 return r;
2953 /* exported function */
2955 evdns_set_option(const char *option, const char *val, int flags)
2957 if (!strncmp(option, "ndots:", 6)) {
2958 const int ndots = strtoint(val);
2959 if (ndots == -1) return -1;
2960 if (!(flags & DNS_OPTION_SEARCH)) return 0;
2961 log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
2962 if (!global_search_state) global_search_state = search_state_new();
2963 if (!global_search_state) return -1;
2964 global_search_state->ndots = ndots;
2965 } else if (!strncmp(option, "timeout:", 8)) {
2966 const int timeout = strtoint(val);
2967 if (timeout == -1) return -1;
2968 if (!(flags & DNS_OPTION_MISC)) return 0;
2969 log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
2970 global_timeout.tv_sec = timeout;
2971 } else if (!strncmp(option, "max-timeouts:", 12)) {
2972 const int maxtimeout = strtoint_clipped(val, 1, 255);
2973 if (maxtimeout == -1) return -1;
2974 if (!(flags & DNS_OPTION_MISC)) return 0;
2975 log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
2976 maxtimeout);
2977 global_max_nameserver_timeout = maxtimeout;
2978 } else if (!strncmp(option, "max-inflight:", 13)) {
2979 const int maxinflight = strtoint_clipped(val, 1, 65000);
2980 if (maxinflight == -1) return -1;
2981 if (!(flags & DNS_OPTION_MISC)) return 0;
2982 log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
2983 maxinflight);
2984 global_max_requests_inflight = maxinflight;
2985 } else if (!strncmp(option, "attempts:", 9)) {
2986 int retries = strtoint(val);
2987 if (retries == -1) return -1;
2988 if (retries > 255) retries = 255;
2989 if (!(flags & DNS_OPTION_MISC)) return 0;
2990 log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
2991 global_max_retransmits = retries;
2992 } else if (!strncmp(option, "randomize-case:", 15)) {
2993 int randcase = strtoint(val);
2994 if (!(flags & DNS_OPTION_MISC)) return 0;
2995 log(EVDNS_LOG_DEBUG, "Setting randomize_case to %d", randcase);
2996 global_randomize_case = randcase;
2998 return 0;
3001 static void
3002 resolv_conf_parse_line(char *const start, int flags) {
3003 char *strtok_state;
3004 static const char *const delims = " \t";
3005 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3007 char *const first_token = strtok_r(start, delims, &strtok_state);
3008 if (!first_token) return;
3010 if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
3011 const char *const nameserver = NEXT_TOKEN;
3012 evdns_nameserver_ip_add(nameserver);
3013 } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
3014 const char *const domain = NEXT_TOKEN;
3015 if (domain) {
3016 search_postfix_clear();
3017 search_postfix_add(domain);
3019 } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
3020 const char *domain;
3021 search_postfix_clear();
3023 while ((domain = NEXT_TOKEN)) {
3024 search_postfix_add(domain);
3026 search_reverse();
3027 } else if (!strcmp(first_token, "options")) {
3028 const char *option;
3029 while ((option = NEXT_TOKEN)) {
3030 const char *val = strchr(option, ':');
3031 evdns_set_option(option, val ? val+1 : "", flags);
3034 #undef NEXT_TOKEN
3037 /* exported function */
3038 /* returns: */
3039 /* 0 no errors */
3040 /* 1 failed to open file */
3041 /* 2 failed to stat file */
3042 /* 3 file too large */
3043 /* 4 out of memory */
3044 /* 5 short read from file */
3046 evdns_resolv_conf_parse(int flags, const char *const filename) {
3047 struct stat st;
3048 int fd, n, r;
3049 u8 *resolv;
3050 char *start;
3051 int err = 0;
3053 log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
3055 fd = open(filename, O_RDONLY);
3056 if (fd < 0) {
3057 evdns_resolv_set_defaults(flags);
3058 return 1;
3061 if (fstat(fd, &st)) { err = 2; goto out1; }
3062 if (!st.st_size) {
3063 evdns_resolv_set_defaults(flags);
3064 err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
3065 goto out1;
3067 if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */
3069 resolv = (u8 *) mm_malloc((size_t)st.st_size + 1);
3070 if (!resolv) { err = 4; goto out1; }
3072 n = 0;
3073 while ((r = (int)read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
3074 n += r;
3075 if (n == st.st_size)
3076 break;
3077 assert(n < st.st_size);
3079 if (r < 0) { err = 5; goto out2; }
3080 resolv[n] = 0; /* we malloced an extra byte; this should be fine. */
3082 start = (char *) resolv;
3083 for (;;) {
3084 char *const newline = strchr(start, '\n');
3085 if (!newline) {
3086 resolv_conf_parse_line(start, flags);
3087 break;
3088 } else {
3089 *newline = 0;
3090 resolv_conf_parse_line(start, flags);
3091 start = newline + 1;
3095 if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
3096 /* no nameservers were configured. */
3097 evdns_nameserver_ip_add("127.0.0.1");
3098 err = 6;
3100 if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
3101 search_set_from_hostname();
3104 out2:
3105 mm_free(resolv);
3106 out1:
3107 close(fd);
3108 return err;
3111 #ifdef WIN32
3112 /* Add multiple nameservers from a space-or-comma-separated list. */
3113 static int
3114 evdns_nameserver_ip_add_line(const char *ips) {
3115 const char *addr;
3116 char *buf;
3117 int r;
3118 while (*ips) {
3119 while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
3120 ++ips;
3121 addr = ips;
3122 while (ISDIGIT(*ips) || *ips == '.' || *ips == ':' || *ips == '[' || *ips == ']')
3123 ++ips;
3124 buf = mm_malloc(ips-addr+1);
3125 if (!buf) return 4;
3126 memcpy(buf, addr, ips-addr);
3127 buf[ips-addr] = '\0';
3128 r = evdns_nameserver_ip_add(buf);
3129 mm_free(buf);
3130 if (r) return r;
3132 return 0;
3135 typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
3137 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3138 /* figure out what our nameservers are. */
3139 static int
3140 load_nameservers_with_getnetworkparams(void)
3142 /* Based on MSDN examples and inspection of c-ares code. */
3143 FIXED_INFO *fixed;
3144 HMODULE handle = 0;
3145 ULONG size = sizeof(FIXED_INFO);
3146 void *buf = NULL;
3147 int status = 0, r, added_any;
3148 IP_ADDR_STRING *ns;
3149 GetNetworkParams_fn_t fn;
3151 /* XXXX Possibly, we should hardcode the location of this DLL. */
3152 if (!(handle = LoadLibrary("iphlpapi.dll"))) {
3153 log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
3154 /* right now status = 0, doesn't that mean "good" - mikec */
3155 status = -1;
3156 goto done;
3158 if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
3159 log(EVDNS_LOG_WARN, "Could not get address of function.");
3160 /* same as above */
3161 status = -1;
3162 goto done;
3165 buf = mm_malloc(size);
3166 if (!buf) { status = 4; goto done; }
3167 fixed = buf;
3168 r = fn(fixed, &size);
3169 if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
3170 status = -1;
3171 goto done;
3173 if (r != ERROR_SUCCESS) {
3174 mm_free(buf);
3175 buf = mm_malloc(size);
3176 if (!buf) { status = 4; goto done; }
3177 fixed = buf;
3178 r = fn(fixed, &size);
3179 if (r != ERROR_SUCCESS) {
3180 log(EVDNS_LOG_DEBUG, "fn() failed.");
3181 status = -1;
3182 goto done;
3186 assert(fixed);
3187 added_any = 0;
3188 ns = &(fixed->DnsServerList);
3189 while (ns) {
3190 r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
3191 if (r) {
3192 log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list, "
3193 "error: %d; status: %d",
3194 (ns->IpAddress.String),(int)GetLastError(), r);
3195 status = r;
3196 } else {
3197 log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
3198 added_any++;
3201 ns = ns->Next;
3204 if (!added_any) {
3205 log(EVDNS_LOG_DEBUG, "No nameservers added.");
3206 if (status == 0)
3207 status = -1;
3208 } else {
3209 status = 0;
3212 done:
3213 if (buf)
3214 mm_free(buf);
3215 if (handle)
3216 FreeLibrary(handle);
3217 return status;
3220 static int
3221 config_nameserver_from_reg_key(HKEY key, const char *subkey)
3223 char *buf;
3224 DWORD bufsz = 0, type = 0;
3225 int status = 0;
3227 if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
3228 != ERROR_MORE_DATA)
3229 return -1;
3230 if (!(buf = mm_malloc(bufsz)))
3231 return -1;
3233 if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
3234 == ERROR_SUCCESS && bufsz > 1) {
3235 status = evdns_nameserver_ip_add_line(buf);
3238 mm_free(buf);
3239 return status;
3242 #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
3243 #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
3244 #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
3246 static int
3247 load_nameservers_from_registry(void)
3249 int found = 0;
3250 int r;
3251 #define TRY(k, name) \
3252 if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
3253 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3254 found = 1; \
3255 } else if (!found) { \
3256 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3257 #k,#name); \
3260 if (((int)GetVersion()) > 0) { /* NT */
3261 HKEY nt_key = 0, interfaces_key = 0;
3263 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
3264 KEY_READ, &nt_key) != ERROR_SUCCESS) {
3265 log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
3266 return -1;
3268 r = RegOpenKeyEx(nt_key, "Interfaces", 0,
3269 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
3270 &interfaces_key);
3271 if (r != ERROR_SUCCESS) {
3272 log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
3273 return -1;
3275 TRY(nt_key, "NameServer");
3276 TRY(nt_key, "DhcpNameServer");
3277 TRY(interfaces_key, "NameServer");
3278 TRY(interfaces_key, "DhcpNameServer");
3279 RegCloseKey(interfaces_key);
3280 RegCloseKey(nt_key);
3281 } else {
3282 HKEY win_key = 0;
3283 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
3284 KEY_READ, &win_key) != ERROR_SUCCESS) {
3285 log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
3286 return -1;
3288 TRY(win_key, "NameServer");
3289 RegCloseKey(win_key);
3292 if (found == 0) {
3293 log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
3296 return found ? 0 : -1;
3297 #undef TRY
3301 evdns_config_windows_nameservers(void)
3303 if (load_nameservers_with_getnetworkparams() == 0)
3304 return 0;
3305 return load_nameservers_from_registry();
3307 #endif
3310 evdns_init(void)
3312 int res = 0;
3313 #ifdef WIN32
3314 evdns_config_windows_nameservers();
3315 #else
3316 res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
3317 #endif
3319 return (res);
3322 const char *
3323 evdns_err_to_string(int err)
3325 switch (err) {
3326 case DNS_ERR_NONE: return "no error";
3327 case DNS_ERR_FORMAT: return "misformatted query";
3328 case DNS_ERR_SERVERFAILED: return "server failed";
3329 case DNS_ERR_NOTEXIST: return "name does not exist";
3330 case DNS_ERR_NOTIMPL: return "query not implemented";
3331 case DNS_ERR_REFUSED: return "refused";
3333 case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
3334 case DNS_ERR_UNKNOWN: return "unknown";
3335 case DNS_ERR_TIMEOUT: return "request timed out";
3336 case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
3337 default: return "[Unknown error code]";
3341 void
3342 evdns_shutdown(int fail_requests)
3344 struct nameserver *server, *server_next;
3345 struct search_domain *dom, *dom_next;
3347 while (req_head) {
3348 if (fail_requests)
3349 reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
3350 request_finished(req_head, &req_head);
3352 while (req_waiting_head) {
3353 if (fail_requests)
3354 reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
3355 request_finished(req_waiting_head, &req_waiting_head);
3357 global_requests_inflight = global_requests_waiting = 0;
3359 for (server = server_head; server; server = server_next) {
3360 server_next = server->next;
3361 if (server->socket >= 0)
3362 CLOSE_SOCKET(server->socket);
3363 (void) event_del(&server->event);
3364 if (server->state == 0)
3365 del_timeout_event(server);
3366 CLEAR(server);
3367 mm_free(server);
3368 if (server_next == server_head)
3369 break;
3371 server_head = NULL;
3372 global_good_nameservers = 0;
3374 if (global_search_state) {
3375 for (dom = global_search_state->head; dom; dom = dom_next) {
3376 dom_next = dom->next;
3377 CLEAR(dom);
3378 mm_free(dom);
3380 CLEAR(global_search_state);
3381 mm_free(global_search_state);
3382 global_search_state = NULL;
3384 evdns_log_fn = NULL;
3387 #ifdef EVDNS_MAIN
3388 void
3389 main_callback(int result, char type, int count, int ttl,
3390 void *addrs, void *orig) {
3391 char *n = (char*)orig;
3392 int i;
3393 for (i = 0; i < count; ++i) {
3394 if (type == DNS_IPv4_A) {
3395 printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
3396 } else if (type == DNS_PTR) {
3397 printf("%s: %s\n", n, ((char**)addrs)[i]);
3400 if (!count) {
3401 printf("%s: No answer (%d)\n", n, result);
3403 fflush(stdout);
3405 void
3406 evdns_server_callback(struct evdns_server_request *req, void *data)
3408 int i, r;
3409 (void)data;
3410 /* dummy; give 192.168.11.11 as an answer for all A questions,
3411 * give foo.bar.example.com as an answer for all PTR questions. */
3412 for (i = 0; i < req->nquestions; ++i) {
3413 u32 ans = htonl(0xc0a80b0bUL);
3414 if (req->questions[i]->type == EVDNS_TYPE_A &&
3415 req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
3416 printf(" -- replying for %s (A)\n", req->questions[i]->name);
3417 r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
3418 1, &ans, 10);
3419 if (r<0)
3420 printf("eeep, didn't work.\n");
3421 } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
3422 req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
3423 printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
3424 r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
3425 "foo.bar.example.com", 10);
3426 } else {
3427 printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
3428 req->questions[i]->type, req->questions[i]->dns_question_class);
3432 r = evdns_server_request_respond(req, 0);
3433 if (r<0)
3434 printf("eeek, couldn't send reply.\n");
3437 void
3438 logfn(int is_warn, const char *msg) {
3439 (void) is_warn;
3440 fprintf(stderr, "%s\n", msg);
3443 main(int c, char **v) {
3444 int idx;
3445 int reverse = 0, verbose = 1, servertest = 0;
3446 if (c<2) {
3447 fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
3448 fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
3449 return 1;
3451 idx = 1;
3452 while (idx < c && v[idx][0] == '-') {
3453 if (!strcmp(v[idx], "-x"))
3454 reverse = 1;
3455 else if (!strcmp(v[idx], "-v"))
3456 verbose = 1;
3457 else if (!strcmp(v[idx], "-servertest"))
3458 servertest = 1;
3459 else
3460 fprintf(stderr, "Unknown option %s\n", v[idx]);
3461 ++idx;
3463 event_init();
3464 if (verbose)
3465 evdns_set_log_fn(logfn);
3466 evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
3467 if (servertest) {
3468 int sock;
3469 struct sockaddr_in my_addr;
3470 sock = socket(PF_INET, SOCK_DGRAM, 0);
3471 fcntl(sock, F_SETFL, O_NONBLOCK);
3472 my_addr.sin_family = AF_INET;
3473 my_addr.sin_port = htons(10053);
3474 my_addr.sin_addr.s_addr = INADDR_ANY;
3475 if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
3476 perror("bind");
3477 exit(1);
3479 evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
3481 for (; idx < c; ++idx) {
3482 if (reverse) {
3483 struct in_addr addr;
3484 if (!inet_aton(v[idx], &addr)) {
3485 fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
3486 continue;
3488 fprintf(stderr, "resolving %s...\n",v[idx]);
3489 evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
3490 } else {
3491 fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
3492 evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
3495 fflush(stdout);
3496 event_dispatch();
3497 return 0;
3499 #endif
3501 /* Local Variables: */
3502 /* tab-width: 4 */
3503 /* c-basic-offset: 4 */
3504 /* indent-tabs-mode: t */
3505 /* End: */