Fix a couple of smaller issues with gathering statistics.
[tor/rransom.git] / src / or / eventdns.c
blobedccb4bfa6b62f7db8016c26a40f46a3298042b1
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"
93 #ifdef WIN32
94 #include <windows.h>
95 #include <winsock2.h>
96 #include <iphlpapi.h>
97 #else
98 #include <sys/socket.h>
99 #include <netinet/in.h>
100 #include <arpa/inet.h>
101 #endif
103 #ifdef HAVE_NETINET_IN6_H
104 #include <netinet/in6.h>
105 #endif
107 #ifdef WIN32
108 typedef int socklen_t;
109 #endif
111 #define EVDNS_LOG_DEBUG 0
112 #define EVDNS_LOG_WARN 1
114 #ifndef HOST_NAME_MAX
115 #define HOST_NAME_MAX 255
116 #endif
118 #ifndef NDEBUG
119 #include <stdio.h>
120 #endif
122 /* for debugging possible memory leaks. */
123 #define mm_malloc(x) tor_malloc(x)
124 #define mm_realloc(x,y) tor_realloc((x),(y))
125 #define mm_free(x) tor_free(x)
126 #define mm_strdup(x) tor_strdup(x)
127 #define _mm_free(x) _tor_free(x)
129 #undef MIN
130 #define MIN(a,b) ((a)<(b)?(a):(b))
132 #if 0
133 #ifdef __USE_ISOC99B
134 /* libevent doesn't work without this */
135 typedef uint8_t u_char;
136 typedef unsigned int uint;
137 #endif
138 #endif
139 #include <event.h>
141 #define u64 uint64_t
142 #define u32 uint32_t
143 #define u16 uint16_t
144 #define u8 uint8_t
146 #define MAX_ADDRS 4 /* maximum number of addresses from a single packet */
147 /* which we bother recording */
149 #define TYPE_A EVDNS_TYPE_A
150 #define TYPE_CNAME 5
151 #define TYPE_PTR EVDNS_TYPE_PTR
152 #define TYPE_AAAA EVDNS_TYPE_AAAA
154 #define CLASS_INET EVDNS_CLASS_INET
156 #define CLEAR(x) do { memset((x), 0xF0, sizeof(*(x))); } while(0)
158 struct evdns_request {
159 u8 *request; /* the dns packet data */
160 unsigned int request_len;
161 int reissue_count;
162 int tx_count; /* the number of times that this packet has been sent */
163 unsigned int request_type; /* TYPE_PTR or TYPE_A */
164 void *user_pointer; /* the pointer given to us for this request */
165 evdns_callback_type user_callback;
166 struct nameserver *ns; /* the server which we last sent it */
168 /* elements used by the searching code */
169 int search_index;
170 struct search_state *search_state;
171 char *search_origname; /* needs to be mm_free()ed */
172 int search_flags;
174 /* these objects are kept in a circular list */
175 struct evdns_request *next, *prev;
177 struct event timeout_event;
179 u16 trans_id; /* the transaction id */
180 char request_appended; /* true if the request pointer is data which follows this struct */
181 char transmit_me; /* needs to be transmitted */
184 #ifndef HAVE_STRUCT_IN6_ADDR
185 struct in6_addr {
186 u8 s6_addr[16];
188 #endif
190 struct reply {
191 unsigned int type;
192 unsigned int have_answer;
193 union {
194 struct {
195 u32 addrcount;
196 u32 addresses[MAX_ADDRS];
197 } a;
198 struct {
199 u32 addrcount;
200 struct in6_addr addresses[MAX_ADDRS];
201 } aaaa;
202 struct {
203 char name[HOST_NAME_MAX];
204 } ptr;
205 } data;
208 struct nameserver {
209 int socket; /* a connected UDP socket */
210 struct sockaddr_storage address;
211 int failed_times; /* number of times which we have given this server a chance */
212 int timedout; /* number of times in a row a request has timed out */
213 struct event event;
214 /* these objects are kept in a circular list */
215 struct nameserver *next, *prev;
216 struct event timeout_event; /* used to keep the timeout for */
217 /* when we next probe this server. */
218 /* Valid if state == 0 */
219 char state; /* zero if we think that this server is down */
220 char choked; /* true if we have an EAGAIN from this server's socket */
221 char write_waiting; /* true if we are waiting for EV_WRITE events */
224 static struct evdns_request *req_head = NULL, *req_waiting_head = NULL;
225 static struct nameserver *server_head = NULL;
227 /* Represents a local port where we're listening for DNS requests. Right now, */
228 /* only UDP is supported. */
229 struct evdns_server_port {
230 int socket; /* socket we use to read queries and write replies. */
231 int refcnt; /* reference count. */
232 char choked; /* Are we currently blocked from writing? */
233 char closing; /* Are we trying to close this port, pending writes? */
234 evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
235 void *user_data; /* Opaque pointer passed to user_callback */
236 struct event event; /* Read/write event */
237 /* circular list of replies that we want to write. */
238 struct server_request *pending_replies;
241 /* Represents part of a reply being built. (That is, a single RR.) */
242 struct server_reply_item {
243 struct server_reply_item *next; /* next item in sequence. */
244 char *name; /* name part of the RR */
245 u16 type : 16; /* The RR type */
246 u16 class : 16; /* The RR class (usually CLASS_INET) */
247 u32 ttl; /* The RR TTL */
248 char is_name; /* True iff data is a label */
249 u16 datalen; /* Length of data; -1 if data is a label */
250 void *data; /* The contents of the RR */
253 /* Represents a request that we've received as a DNS server, and holds */
254 /* the components of the reply as we're constructing it. */
255 struct server_request {
256 /* Pointers to the next and previous entries on the list of replies */
257 /* that we're waiting to write. Only set if we have tried to respond */
258 /* and gotten EAGAIN. */
259 struct server_request *next_pending;
260 struct server_request *prev_pending;
262 u16 trans_id; /* Transaction id. */
263 struct evdns_server_port *port; /* Which port received this request on? */
264 struct sockaddr_storage addr; /* Where to send the response */
265 socklen_t addrlen; /* length of addr */
267 int n_answer; /* how many answer RRs have been set? */
268 int n_authority; /* how many authority RRs have been set? */
269 int n_additional; /* how many additional RRs have been set? */
271 struct server_reply_item *answer; /* linked list of answer RRs */
272 struct server_reply_item *authority; /* linked list of authority RRs */
273 struct server_reply_item *additional; /* linked list of additional RRs */
275 /* Constructed response. Only set once we're ready to send a reply. */
276 /* Once this is set, the RR fields are cleared, and no more should be set. */
277 char *response;
278 size_t response_len;
280 /* Caller-visible fields: flags, questions. */
281 struct evdns_server_request base;
284 /* helper macro */
285 #define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))
287 /* Given a pointer to an evdns_server_request, get the corresponding */
288 /* server_request. */
289 #define TO_SERVER_REQUEST(base_ptr) \
290 ((struct server_request*) \
291 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))
293 /* The number of good nameservers that we have */
294 static int global_good_nameservers = 0;
296 /* inflight requests are contained in the req_head list */
297 /* and are actually going out across the network */
298 static int global_requests_inflight = 0;
299 /* requests which aren't inflight are in the waiting list */
300 /* and are counted here */
301 static int global_requests_waiting = 0;
303 static int global_max_requests_inflight = 64;
305 static struct timeval global_timeout = {5, 0}; /* 5 seconds */
306 static int global_max_reissues = 1; /* a reissue occurs when we get some errors from the server */
307 static int global_max_retransmits = 3; /* number of times we'll retransmit a request which timed out */
308 /* number of timeouts in a row before we consider this server to be down */
309 static int global_max_nameserver_timeout = 3;
311 /* true iff we should use the 0x20 hack. */
312 static int global_randomize_case = 1;
314 /* These are the timeout values for nameservers. If we find a nameserver is down */
315 /* we try to probe it at intervals as given below. Values are in seconds. */
316 static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
317 static const int global_nameserver_timeouts_length = (int)(sizeof(global_nameserver_timeouts)/sizeof(struct timeval));
319 static struct nameserver *nameserver_pick(void);
320 static void evdns_request_insert(struct evdns_request *req, struct evdns_request **head);
321 static void nameserver_ready_callback(int fd, short events, void *arg);
322 static int evdns_transmit(void);
323 static int evdns_request_transmit(struct evdns_request *req);
324 static void nameserver_send_probe(struct nameserver *const ns);
325 static void search_request_finished(struct evdns_request *const);
326 static int search_try_next(struct evdns_request *const req);
327 static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
328 static void evdns_requests_pump_waiting_queue(void);
329 static u16 transaction_id_pick(void);
330 static struct evdns_request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
331 static void request_submit(struct evdns_request *req);
333 static int server_request_free(struct server_request *req);
334 static void server_request_free_answers(struct server_request *req);
335 static void server_port_free(struct evdns_server_port *port);
336 static void server_port_ready_callback(int fd, short events, void *arg);
338 static int strtoint(const char *const str);
340 #ifdef WIN32
341 static int
342 last_error(int sock)
344 int optval, optvallen=sizeof(optval);
345 int err = WSAGetLastError();
346 if (err == WSAEWOULDBLOCK && sock >= 0) {
347 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
348 &optvallen))
349 return err;
350 if (optval)
351 return optval;
353 return err;
356 static int
357 error_is_eagain(int err)
359 return err == EAGAIN || err == WSAEWOULDBLOCK;
361 #define inet_aton(c, addr) tor_inet_aton((c), (addr))
362 #define CLOSE_SOCKET(x) closesocket(x)
363 #else
364 #define last_error(sock) (errno)
365 #define error_is_eagain(err) ((err) == EAGAIN)
366 #define CLOSE_SOCKET(x) close(x)
367 #endif
369 #define ISSPACE(c) TOR_ISSPACE(c)
370 #define ISDIGIT(c) TOR_ISDIGIT(c)
371 #define ISALPHA(c) TOR_ISALPHA(c)
372 #define TOLOWER(c) TOR_TOLOWER(c)
373 #define TOUPPER(c) TOR_TOUPPER(c)
375 #ifndef NDEBUG
376 static const char *
377 debug_ntoa(u32 address)
379 static char buf[32];
380 u32 a = ntohl(address);
381 snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
382 (int)(u8)((a>>24)&0xff),
383 (int)(u8)((a>>16)&0xff),
384 (int)(u8)((a>>8 )&0xff),
385 (int)(u8)((a )&0xff));
386 return buf;
388 static const char *
389 debug_ntop(const struct sockaddr *sa)
391 if (sa->sa_family == AF_INET) {
392 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
393 return debug_ntoa(sin->sin_addr.s_addr);
395 if (sa->sa_family == AF_INET6) {
396 /* Tor-specific. In libevent, add more check code. */
397 static char buf[128];
398 struct sockaddr_in6 *sin = (struct sockaddr_in6 *) sa;
399 tor_inet_ntop(AF_INET6, &sin->sin6_addr, buf, sizeof(buf));
400 return buf;
402 return "<unknown>";
404 #endif
406 static evdns_debug_log_fn_type evdns_log_fn = NULL;
408 void
409 evdns_set_log_fn(evdns_debug_log_fn_type fn)
411 evdns_log_fn = fn;
414 #ifdef __GNUC__
415 #define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
416 #else
417 #define EVDNS_LOG_CHECK
418 #endif
420 static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
421 static void
422 _evdns_log(int warn, const char *fmt, ...)
424 va_list args;
425 static char buf[512];
426 if (!evdns_log_fn)
427 return;
428 va_start(args,fmt);
429 #ifdef WIN32
430 _vsnprintf(buf, sizeof(buf), fmt, args);
431 #else
432 vsnprintf(buf, sizeof(buf), fmt, args);
433 #endif
434 buf[sizeof(buf)-1] = '\0';
435 evdns_log_fn(warn, buf);
436 va_end(args);
439 #define log _evdns_log
441 static int
442 sockaddr_eq(const struct sockaddr *sa1, const struct sockaddr *sa2,
443 int include_port)
445 if (sa1->sa_family != sa2->sa_family)
446 return 0;
447 if (sa1->sa_family == AF_INET) {
448 const struct sockaddr_in *sin1, *sin2;
449 sin1 = (const struct sockaddr_in *)sa1;
450 sin2 = (const struct sockaddr_in *)sa2;
451 if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr)
452 return 0;
453 else if (include_port && sin1->sin_port != sin2->sin_port)
454 return 0;
455 else
456 return 1;
458 #ifdef AF_INET6
459 if (sa1->sa_family == AF_INET6) {
460 const struct sockaddr_in6 *sin1, *sin2;
461 sin1 = (const struct sockaddr_in6 *)sa1;
462 sin2 = (const struct sockaddr_in6 *)sa2;
463 if (memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16))
464 return 0;
465 else if (include_port && sin1->sin6_port != sin2->sin6_port)
466 return 0;
467 else
468 return 1;
470 #endif
471 return 1;
474 #define add_timeout_event(s, to) \
475 (event_add(&(s)->timeout_event, (to)))
476 #define del_timeout_event(s) \
477 (event_del(&(s)->timeout_event))
479 /* This walks the list of inflight requests to find the */
480 /* one with a matching transaction id. Returns NULL on */
481 /* failure */
482 static struct evdns_request *
483 request_find_from_trans_id(u16 trans_id) {
484 struct evdns_request *req = req_head, *const started_at = req_head;
486 if (req) {
487 do {
488 if (req->trans_id == trans_id) return req;
489 req = req->next;
490 } while (req != started_at);
493 return NULL;
496 /* a libevent callback function which is called when a nameserver */
497 /* has gone down and we want to test if it has came back to life yet */
498 static void
499 nameserver_prod_callback(int fd, short events, void *arg) {
500 struct nameserver *const ns = (struct nameserver *) arg;
501 (void)fd;
502 (void)events;
504 nameserver_send_probe(ns);
507 /* a libevent callback which is called when a nameserver probe (to see if */
508 /* it has come back to life) times out. We increment the count of failed_times */
509 /* and wait longer to send the next probe packet. */
510 static void
511 nameserver_probe_failed(struct nameserver *const ns) {
512 const struct timeval * timeout;
513 del_timeout_event(ns);
515 if (ns->state == 1) {
516 /* This can happen if the nameserver acts in a way which makes us mark */
517 /* it as bad and then starts sending good replies. */
518 return;
521 timeout =
522 &global_nameserver_timeouts[MIN(ns->failed_times,
523 global_nameserver_timeouts_length - 1)];
524 ns->failed_times++;
526 if (add_timeout_event(ns, (struct timeval *) timeout) < 0) {
527 log(EVDNS_LOG_WARN,
528 "Error from libevent when adding timer event for %s",
529 debug_ntop((struct sockaddr *)&ns->address));
530 /* ???? Do more? */
534 /* called when a nameserver has been deemed to have failed. For example, too */
535 /* many packets have timed out etc */
536 static void
537 nameserver_failed(struct nameserver *const ns, const char *msg) {
538 struct evdns_request *req, *started_at;
539 /* if this nameserver has already been marked as failed */
540 /* then don't do anything */
541 if (!ns->state) return;
543 log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
544 debug_ntop((struct sockaddr *)&ns->address), msg);
545 global_good_nameservers--;
546 assert(global_good_nameservers >= 0);
547 if (global_good_nameservers == 0) {
548 log(EVDNS_LOG_WARN, "All nameservers have failed");
551 ns->state = 0;
552 ns->failed_times = 1;
554 if (add_timeout_event(ns, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
555 log(EVDNS_LOG_WARN,
556 "Error from libevent when adding timer event for %s",
557 debug_ntop((struct sockaddr *)&ns->address));
558 /* ???? Do more? */
561 /* walk the list of inflight requests to see if any can be reassigned to */
562 /* a different server. Requests in the waiting queue don't have a */
563 /* nameserver assigned yet */
565 /* if we don't have *any* good nameservers then there's no point */
566 /* trying to reassign requests to one */
567 if (!global_good_nameservers) return;
569 req = req_head;
570 started_at = req_head;
571 if (req) {
572 do {
573 if (req->tx_count == 0 && req->ns == ns) {
574 /* still waiting to go out, can be moved */
575 /* to another server */
576 req->ns = nameserver_pick();
578 req = req->next;
579 } while (req != started_at);
583 static void
584 nameserver_up(struct nameserver *const ns) {
585 if (ns->state) return;
586 log(EVDNS_LOG_WARN, "Nameserver %s is back up",
587 debug_ntop((struct sockaddr *)&ns->address));
588 del_timeout_event(ns);
589 ns->state = 1;
590 ns->failed_times = 0;
591 ns->timedout = 0;
592 global_good_nameservers++;
595 static void
596 request_trans_id_set(struct evdns_request *const req, const u16 trans_id) {
597 req->trans_id = trans_id;
598 *((u16 *) req->request) = htons(trans_id);
601 /* Called to remove a request from a list and dealloc it. */
602 /* head is a pointer to the head of the list it should be */
603 /* removed from or NULL if the request isn't in a list. */
604 static void
605 request_finished(struct evdns_request *const req, struct evdns_request **head) {
606 if (head) {
607 if (req->next == req) {
608 /* only item in the list */
609 *head = NULL;
610 } else {
611 req->next->prev = req->prev;
612 req->prev->next = req->next;
613 if (*head == req) *head = req->next;
617 log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
618 (unsigned long) req);
619 del_timeout_event(req);
621 search_request_finished(req);
622 global_requests_inflight--;
624 if (!req->request_appended) {
625 /* need to free the request data on it's own */
626 mm_free(req->request);
627 } else {
628 /* the request data is appended onto the header */
629 /* so everything gets mm_free()ed when we: */
632 CLEAR(req);
633 _mm_free(req);
635 evdns_requests_pump_waiting_queue();
638 /* This is called when a server returns a funny error code. */
639 /* We try the request again with another server. */
640 /* */
641 /* return: */
642 /* 0 ok */
643 /* 1 failed/reissue is pointless */
644 static int
645 request_reissue(struct evdns_request *req) {
646 const struct nameserver *const last_ns = req->ns;
647 /* the last nameserver should have been marked as failing */
648 /* by the caller of this function, therefore pick will try */
649 /* not to return it */
650 req->ns = nameserver_pick();
651 if (req->ns == last_ns) {
652 /* ... but pick did return it */
653 /* not a lot of point in trying again with the */
654 /* same server */
655 return 1;
658 req->reissue_count++;
659 req->tx_count = 0;
660 req->transmit_me = 1;
662 return 0;
665 /* this function looks for space on the inflight queue and promotes */
666 /* requests from the waiting queue if it can. */
667 static void
668 evdns_requests_pump_waiting_queue(void) {
669 while (global_requests_inflight < global_max_requests_inflight &&
670 global_requests_waiting) {
671 struct evdns_request *req;
672 /* move a request from the waiting queue to the inflight queue */
673 assert(req_waiting_head);
674 if (req_waiting_head->next == req_waiting_head) {
675 /* only one item in the queue */
676 req = req_waiting_head;
677 req_waiting_head = NULL;
678 } else {
679 req = req_waiting_head;
680 req->next->prev = req->prev;
681 req->prev->next = req->next;
682 req_waiting_head = req->next;
685 global_requests_waiting--;
686 global_requests_inflight++;
688 req->ns = nameserver_pick();
689 request_trans_id_set(req, transaction_id_pick());
691 evdns_request_insert(req, &req_head);
692 evdns_request_transmit(req);
693 evdns_transmit();
697 static void
698 reply_callback(struct evdns_request *const req, u32 ttl, u32 err, struct reply *reply) {
699 switch (req->request_type) {
700 case TYPE_A:
701 if (reply)
702 req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
703 reply->data.a.addrcount, ttl,
704 reply->data.a.addresses,
705 req->user_pointer);
706 else
707 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
708 return;
709 case TYPE_PTR:
710 if (reply) {
711 char *name = reply->data.ptr.name;
712 req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
713 &name, req->user_pointer);
714 } else {
715 req->user_callback(err, 0, 0, 0, NULL,
716 req->user_pointer);
718 return;
719 case TYPE_AAAA:
720 if (reply)
721 req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
722 reply->data.aaaa.addrcount, ttl,
723 reply->data.aaaa.addresses,
724 req->user_pointer);
725 else
726 req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
727 return;
729 assert(0);
732 /* this processes a parsed reply packet */
733 static void
734 reply_handle(struct evdns_request *const req, u16 flags, u32 ttl, struct reply *reply) {
735 int error;
736 static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};
738 if (flags & 0x020f || !reply || !reply->have_answer) {
739 /* there was an error */
740 if (flags & 0x0200) {
741 error = DNS_ERR_TRUNCATED;
742 } else {
743 u16 error_code = (flags & 0x000f) - 1;
744 if (error_code > 4) {
745 error = DNS_ERR_UNKNOWN;
746 } else {
747 error = error_codes[error_code];
751 switch(error) {
752 case DNS_ERR_NOTIMPL:
753 case DNS_ERR_REFUSED:
754 /* we regard these errors as marking a bad nameserver */
755 if (req->reissue_count < global_max_reissues) {
756 char msg[64];
757 snprintf(msg, sizeof(msg), "Bad response %d (%s)",
758 error, evdns_err_to_string(error));
759 nameserver_failed(req->ns, msg);
760 if (!request_reissue(req)) return;
762 break;
763 case DNS_ERR_SERVERFAILED:
764 /* rcode 2 (servfailed) sometimes means "we are broken" and
765 * sometimes (with some binds) means "that request was very
766 * confusing." Treat this as a timeout, not a failure.
768 /*XXXX refactor the parts of */
769 log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
770 "will allow the request to time out.",
771 debug_ntop((struct sockaddr *)&req->ns->address));
772 break;
773 default:
774 /* we got a good reply from the nameserver */
775 nameserver_up(req->ns);
778 if (req->search_state && req->request_type != TYPE_PTR) {
779 /* if we have a list of domains to search in, try the next one */
780 if (!search_try_next(req)) {
781 /* a new request was issued so this request is finished and */
782 /* the user callback will be made when that request (or a */
783 /* child of it) finishes. */
784 request_finished(req, &req_head);
785 return;
789 /* all else failed. Pass the failure up */
790 reply_callback(req, 0, error, NULL);
791 request_finished(req, &req_head);
792 } else {
793 /* all ok, tell the user */
794 reply_callback(req, ttl, 0, reply);
795 nameserver_up(req->ns);
796 request_finished(req, &req_head);
800 static INLINE int
801 name_parse(u8 *packet, int length, int *idx, char *name_out, size_t name_out_len) {
802 int name_end = -1;
803 int j = *idx;
804 int ptr_count = 0;
805 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
806 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
807 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
809 char *cp = name_out;
810 const char *const end = name_out + name_out_len;
812 /* Normally, names are a series of length prefixed strings terminated */
813 /* with a length of 0 (the lengths are u8's < 63). */
814 /* However, the length can start with a pair of 1 bits and that */
815 /* means that the next 14 bits are a pointer within the current */
816 /* packet. */
818 for(;;) {
819 u8 label_len;
820 if (j >= length) return -1;
821 GET8(label_len);
822 if (!label_len) break;
823 if (label_len & 0xc0) {
824 u8 ptr_low;
825 GET8(ptr_low);
826 if (name_end < 0) name_end = j;
827 j = (((int)label_len & 0x3f) << 8) + ptr_low;
828 /* Make sure that the target offset is in-bounds. */
829 if (j < 0 || j >= length) return -1;
830 /* If we've jumped more times than there are characters in the
831 * message, we must have a loop. */
832 if (++ptr_count > length) return -1;
833 continue;
835 if (label_len > 63) return -1;
836 if (cp != name_out) {
837 if (cp + 1 >= end) return -1;
838 *cp++ = '.';
840 if (cp + label_len >= end) return -1;
841 memcpy(cp, packet + j, label_len);
842 cp += label_len;
843 j += label_len;
845 if (cp >= end) return -1;
846 *cp = '\0';
847 if (name_end < 0)
848 *idx = j;
849 else
850 *idx = name_end;
851 return 0;
852 err:
853 return -1;
856 /* parses a raw reply from a nameserver. */
857 static int
858 reply_parse(u8 *packet, int length) {
859 int j = 0; /* index into packet */
860 int k;
861 u16 _t; /* used by the macros */
862 u32 _t32; /* used by the macros */
863 char tmp_name[256], cmp_name[256]; /* used by the macros */
865 u16 trans_id, questions, answers, authority, additional, datalength;
866 u16 flags = 0;
867 u32 ttl, ttl_r = 0xffffffff;
868 struct reply reply;
869 struct evdns_request *req = NULL;
870 unsigned int i;
871 int name_matches = 0;
873 GET16(trans_id);
874 GET16(flags);
875 GET16(questions);
876 GET16(answers);
877 GET16(authority);
878 GET16(additional);
879 (void) authority; /* suppress "unused variable" warnings. */
880 (void) additional; /* suppress "unused variable" warnings. */
882 req = request_find_from_trans_id(trans_id);
883 /* if no request, can't do anything. */
884 if (!req) return -1;
886 memset(&reply, 0, sizeof(reply));
888 /* If it's not an answer, it doesn't go with any of our requests. */
889 if (!(flags & 0x8000)) return -1; /* must be an answer */
890 if (flags & 0x020f) {
891 /* there was an error */
892 goto err;
894 /* if (!answers) return; */ /* must have an answer of some form */
896 /* This macro skips a name in the DNS reply. */
897 #define GET_NAME \
898 do { tmp_name[0] = '\0'; \
899 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
900 goto err; \
901 } while(0)
902 #define TEST_NAME \
903 do { tmp_name[0] = '\0'; \
904 cmp_name[0] = '\0'; \
905 k = j; \
906 if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
907 goto err; \
908 if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0) \
909 goto err; \
910 if (global_randomize_case) { \
911 if (strcmp(tmp_name, cmp_name) == 0) \
912 name_matches = 1; /* we ignore mismatching names */ \
913 } else { \
914 if (strcasecmp(tmp_name, cmp_name) == 0) \
915 name_matches = 1; \
917 } while(0)
919 reply.type = req->request_type;
921 /* skip over each question in the reply */
922 for (i = 0; i < questions; ++i) {
923 /* the question looks like
924 * <label:name><u16:type><u16:class>
926 TEST_NAME;
927 j += 4;
928 if (j >= length) goto err;
931 if (!name_matches)
932 goto err;
934 /* now we have the answer section which looks like
935 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
938 for (i = 0; i < answers; ++i) {
939 u16 type, class;
941 GET_NAME;
942 GET16(type);
943 GET16(class);
944 GET32(ttl);
945 GET16(datalength);
947 if (type == TYPE_A && class == CLASS_INET) {
948 int addrcount, addrtocopy;
949 if (req->request_type != TYPE_A) {
950 j += datalength; continue;
952 if ((datalength & 3) != 0) /* not an even number of As. */
953 goto err;
954 addrcount = datalength >> 2;
955 addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
957 ttl_r = MIN(ttl_r, ttl);
958 /* we only bother with the first four addresses. */
959 if (j + 4*addrtocopy > length) goto err;
960 memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
961 packet + j, 4*addrtocopy);
962 reply.data.a.addrcount += addrtocopy;
963 reply.have_answer = 1;
964 if (reply.data.a.addrcount == MAX_ADDRS) break;
965 j += 4*addrtocopy;
966 } else if (type == TYPE_PTR && class == CLASS_INET) {
967 if (req->request_type != TYPE_PTR) {
968 j += datalength; continue;
970 GET_NAME;
971 strlcpy(reply.data.ptr.name, tmp_name,
972 sizeof(reply.data.ptr.name));
973 ttl_r = MIN(ttl_r, ttl);
974 reply.have_answer = 1;
975 break;
976 } else if (type == TYPE_AAAA && class == CLASS_INET) {
977 int addrcount, addrtocopy;
978 if (req->request_type != TYPE_AAAA) {
979 j += datalength; continue;
981 if ((datalength & 15) != 0) /* not an even number of AAAAs. */
982 goto err;
983 addrcount = datalength >> 4; /* each address is 16 bytes long */
984 addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
985 ttl_r = MIN(ttl_r, ttl);
987 /* we only bother with the first four addresses. */
988 if (j + 16*addrtocopy > length) goto err;
989 memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
990 packet + j, 16*addrtocopy);
991 reply.data.aaaa.addrcount += addrtocopy;
992 reply.have_answer = 1;
993 if (reply.data.aaaa.addrcount == MAX_ADDRS) break;
994 j += 16*addrtocopy;
995 } else {
996 /* skip over any other type of resource */
997 j += datalength;
1001 reply_handle(req, flags, ttl_r, &reply);
1002 return 0;
1003 err:
1004 if (req)
1005 reply_handle(req, flags, 0, NULL);
1006 return -1;
1009 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1010 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1011 /* callback. */
1012 static int
1013 request_parse(u8 *packet, ssize_t length, struct evdns_server_port *port, struct sockaddr *addr, socklen_t addrlen)
1015 int j = 0; /* index into packet */
1016 u16 _t; /* used by the macros */
1017 char tmp_name[256]; /* used by the macros */
1019 int i;
1020 u16 trans_id, flags, questions, answers, authority, additional;
1021 struct server_request *server_req = NULL;
1023 /* Get the header fields */
1024 GET16(trans_id);
1025 GET16(flags);
1026 GET16(questions);
1027 GET16(answers);
1028 GET16(authority);
1029 GET16(additional);
1031 if (flags & 0x8000) return -1; /* Must not be an answer. */
1032 flags &= 0x0110; /* Only RD and CD get preserved. */
1034 if (length > INT_MAX)
1035 return -1;
1037 server_req = mm_malloc(sizeof(struct server_request));
1038 if (server_req == NULL) return -1;
1039 memset(server_req, 0, sizeof(struct server_request));
1041 server_req->trans_id = trans_id;
1042 memcpy(&server_req->addr, addr, addrlen);
1043 server_req->addrlen = addrlen;
1045 server_req->base.flags = flags;
1046 server_req->base.nquestions = 0;
1047 server_req->base.questions = mm_malloc(sizeof(struct evdns_server_question *) * questions);
1048 if (server_req->base.questions == NULL)
1049 goto err;
1051 for (i = 0; i < questions; ++i) {
1052 u16 type, class;
1053 struct evdns_server_question *q;
1054 size_t namelen;
1055 if (name_parse(packet, (int)length, &j, tmp_name, sizeof(tmp_name))<0)
1056 goto err;
1057 GET16(type);
1058 GET16(class);
1059 namelen = strlen(tmp_name);
1060 q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
1061 if (!q)
1062 goto err;
1063 q->type = type;
1064 q->dns_question_class = class;
1065 memcpy(q->name, tmp_name, namelen+1);
1066 server_req->base.questions[server_req->base.nquestions++] = q;
1069 /* Ignore answers, authority, and additional. */
1071 server_req->port = port;
1072 port->refcnt++;
1074 /* Only standard queries are supported. */
1075 if (flags & 0x7800) {
1076 evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
1077 return -1;
1080 port->user_callback(&(server_req->base), port->user_data);
1082 return 0;
1083 err:
1084 if (server_req) {
1085 if (server_req->base.questions) {
1086 for (i = 0; i < server_req->base.nquestions; ++i)
1087 mm_free(server_req->base.questions[i]);
1088 mm_free(server_req->base.questions);
1090 CLEAR(server_req);
1091 mm_free(server_req);
1093 return -1;
1095 #undef SKIP_NAME
1096 #undef GET32
1097 #undef GET16
1098 #undef GET8
1101 static uint16_t
1102 default_transaction_id_fn(void)
1104 u16 trans_id;
1105 #ifdef DNS_USE_CPU_CLOCK_FOR_ID
1106 struct timespec ts;
1107 #ifdef CLOCK_MONOTONIC
1108 if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1)
1109 #else
1110 if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
1111 #endif
1112 event_err(1, "clock_gettime");
1113 trans_id = ts.tv_nsec & 0xffff;
1114 #endif
1116 #ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
1117 struct timeval tv;
1118 gettimeofday(&tv, NULL);
1119 trans_id = tv.tv_usec & 0xffff;
1120 #endif
1122 #ifdef DNS_USE_OPENSSL_FOR_ID
1123 if (RAND_pseudo_bytes((u8 *) &trans_id, 2) == -1) {
1124 /* in the case that the RAND call fails we back */
1125 /* down to using gettimeofday. */
1127 struct timeval tv;
1128 gettimeofday(&tv, NULL);
1129 trans_id = tv.tv_usec & 0xffff;
1131 abort();
1133 #endif
1134 return (unsigned short) trans_id;
1137 static uint16_t (*trans_id_function)(void) = default_transaction_id_fn;
1139 static void
1140 default_random_bytes_fn(char *buf, size_t n)
1142 unsigned i;
1143 for (i = 0; i < n; i += 2) {
1144 u16 tid = trans_id_function();
1145 buf[i] = (tid >> 8) & 0xff;
1146 if (i+1<n)
1147 buf[i+1] = tid & 0xff;
1151 static void (*rand_bytes_function)(char *buf, size_t n) =
1152 default_random_bytes_fn;
1154 static u16
1155 trans_id_from_random_bytes_fn(void)
1157 u16 tid;
1158 rand_bytes_function((char*) &tid, sizeof(tid));
1159 return tid;
1162 void
1163 evdns_set_transaction_id_fn(uint16_t (*fn)(void))
1165 if (fn)
1166 trans_id_function = fn;
1167 else
1168 trans_id_function = default_transaction_id_fn;
1169 rand_bytes_function = default_random_bytes_fn;
1172 void
1173 evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
1175 rand_bytes_function = fn;
1176 trans_id_function = trans_id_from_random_bytes_fn;
1179 /* Try to choose a strong transaction id which isn't already in flight */
1180 static u16
1181 transaction_id_pick(void) {
1182 for (;;) {
1183 const struct evdns_request *req = req_head, *started_at;
1184 u16 trans_id = trans_id_function();
1186 if (trans_id == 0xffff) continue;
1187 /* now check to see if that id is already inflight */
1188 req = started_at = req_head;
1189 if (req) {
1190 do {
1191 if (req->trans_id == trans_id) break;
1192 req = req->next;
1193 } while (req != started_at);
1195 /* we didn't find it, so this is a good id */
1196 if (req == started_at) return trans_id;
1200 /* choose a namesever to use. This function will try to ignore */
1201 /* nameservers which we think are down and load balance across the rest */
1202 /* by updating the server_head global each time. */
1203 static struct nameserver *
1204 nameserver_pick(void) {
1205 struct nameserver *started_at = server_head, *picked;
1206 if (!server_head) return NULL;
1208 /* if we don't have any good nameservers then there's no */
1209 /* point in trying to find one. */
1210 if (!global_good_nameservers) {
1211 server_head = server_head->next;
1212 return server_head;
1215 /* remember that nameservers are in a circular list */
1216 for (;;) {
1217 if (server_head->state) {
1218 /* we think this server is currently good */
1219 picked = server_head;
1220 server_head = server_head->next;
1221 return picked;
1224 server_head = server_head->next;
1225 if (server_head == started_at) {
1226 /* all the nameservers seem to be down */
1227 /* so we just return this one and hope for the */
1228 /* best */
1229 assert(global_good_nameservers == 0);
1230 picked = server_head;
1231 server_head = server_head->next;
1232 return picked;
1237 /* this is called when a namesever socket is ready for reading */
1238 static void
1239 nameserver_read(struct nameserver *ns) {
1240 struct sockaddr_storage ss;
1241 struct sockaddr *sa = (struct sockaddr *) &ss;
1242 socklen_t addrlen = sizeof(ss);
1243 u8 packet[1500];
1245 for (;;) {
1246 const int r =
1247 (int)recvfrom(ns->socket, packet, (socklen_t)sizeof(packet), 0,
1248 sa, &addrlen);
1249 if (r < 0) {
1250 int err = last_error(ns->socket);
1251 if (error_is_eagain(err)) return;
1252 nameserver_failed(ns, tor_socket_strerror(err));
1253 return;
1255 /* XXX Match port too? */
1256 if (!sockaddr_eq(sa, (struct sockaddr*)&ns->address, 0)) {
1257 log(EVDNS_LOG_WARN,
1258 "Address mismatch on received DNS packet. Address was %s",
1259 debug_ntop(sa));
1260 return;
1262 ns->timedout = 0;
1263 reply_parse(packet, r);
1267 /* Read a packet from a DNS client on a server port s, parse it, and */
1268 /* act accordingly. */
1269 static void
1270 server_port_read(struct evdns_server_port *s) {
1271 u8 packet[1500];
1272 struct sockaddr_storage addr;
1273 socklen_t addrlen;
1274 ssize_t r;
1276 for (;;) {
1277 addrlen = (socklen_t)sizeof(struct sockaddr_storage);
1278 r = recvfrom(s->socket, packet, sizeof(packet), 0,
1279 (struct sockaddr*) &addr, &addrlen);
1280 if (r < 0) {
1281 int err = last_error(s->socket);
1282 if (error_is_eagain(err)) return;
1283 log(EVDNS_LOG_WARN, "Error %s (%d) while reading request.",
1284 tor_socket_strerror(err), err);
1285 return;
1287 request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
1291 /* Try to write all pending replies on a given DNS server port. */
1292 static void
1293 server_port_flush(struct evdns_server_port *port)
1295 while (port->pending_replies) {
1296 struct server_request *req = port->pending_replies;
1297 ssize_t r = sendto(port->socket, req->response, req->response_len, 0,
1298 (struct sockaddr*) &req->addr, (socklen_t)req->addrlen);
1299 if (r < 0) {
1300 int err = last_error(port->socket);
1301 if (error_is_eagain(err))
1302 return;
1303 log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", tor_socket_strerror(err), err);
1305 if (server_request_free(req)) {
1306 /* we released the last reference to req->port. */
1307 return;
1311 /* We have no more pending requests; stop listening for 'writeable' events. */
1312 (void) event_del(&port->event);
1313 CLEAR(&port->event);
1314 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1315 server_port_ready_callback, port);
1316 if (event_add(&port->event, NULL) < 0) {
1317 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
1318 /* ???? Do more? */
1322 /* set if we are waiting for the ability to write to this server. */
1323 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1324 /* we stop these events. */
1325 static void
1326 nameserver_write_waiting(struct nameserver *ns, char waiting) {
1327 if (ns->write_waiting == waiting) return;
1329 ns->write_waiting = waiting;
1330 (void) event_del(&ns->event);
1331 CLEAR(&ns->event);
1332 event_set(&ns->event, ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1333 nameserver_ready_callback, ns);
1334 if (event_add(&ns->event, NULL) < 0) {
1335 log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
1336 debug_ntop((struct sockaddr *)&ns->address));
1337 /* ???? Do more? */
1341 /* a callback function. Called by libevent when the kernel says that */
1342 /* a nameserver socket is ready for writing or reading */
1343 static void
1344 nameserver_ready_callback(int fd, short events, void *arg) {
1345 struct nameserver *ns = (struct nameserver *) arg;
1346 (void)fd;
1348 if (events & EV_WRITE) {
1349 ns->choked = 0;
1350 if (!evdns_transmit()) {
1351 nameserver_write_waiting(ns, 0);
1354 if (events & EV_READ) {
1355 nameserver_read(ns);
1359 /* a callback function. Called by libevent when the kernel says that */
1360 /* a server socket is ready for writing or reading. */
1361 static void
1362 server_port_ready_callback(int fd, short events, void *arg) {
1363 struct evdns_server_port *port = (struct evdns_server_port *) arg;
1364 (void) fd;
1366 if (events & EV_WRITE) {
1367 port->choked = 0;
1368 server_port_flush(port);
1370 if (events & EV_READ) {
1371 server_port_read(port);
1375 /* This is an inefficient representation; only use it via the dnslabel_table_*
1376 * functions, so that is can be safely replaced with something smarter later. */
1377 #define MAX_LABELS 128
1378 /* Structures used to implement name compression */
1379 struct dnslabel_entry { char *v; off_t pos; };
1380 struct dnslabel_table {
1381 int n_labels; /* number of current entries */
1382 /* map from name to position in message */
1383 struct dnslabel_entry labels[MAX_LABELS];
1386 /* Initialize dnslabel_table. */
1387 static void
1388 dnslabel_table_init(struct dnslabel_table *table)
1390 table->n_labels = 0;
1393 /* Free all storage held by table, but not the table itself. */
1394 static void
1395 dnslabel_clear(struct dnslabel_table *table)
1397 int i;
1398 for (i = 0; i < table->n_labels; ++i)
1399 mm_free(table->labels[i].v);
1400 table->n_labels = 0;
1403 /* return the position of the label in the current message, or -1 if the label */
1404 /* hasn't been used yet. */
1405 static int
1406 dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
1408 int i;
1409 for (i = 0; i < table->n_labels; ++i) {
1410 if (!strcmp(label, table->labels[i].v)) {
1411 off_t pos = table->labels[i].pos;
1412 if (pos > 65535)
1413 return -1;
1414 return (int)pos;
1417 return -1;
1420 /* remember that we've used the label at position pos */
1421 static int
1422 dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
1424 char *v;
1425 int p;
1426 if (table->n_labels == MAX_LABELS)
1427 return (-1);
1428 v = mm_strdup(label);
1429 if (v == NULL)
1430 return (-1);
1431 p = table->n_labels++;
1432 table->labels[p].v = v;
1433 table->labels[p].pos = pos;
1435 return (0);
1438 /* Converts a string to a length-prefixed set of DNS labels, starting */
1439 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1440 /* of name. table is optional, and is used for compression. */
1441 /* */
1442 /* Input: abc.def */
1443 /* Output: <3>abc<3>def<0> */
1444 /* */
1445 /* Returns the first index after the encoded name, or negative on error. */
1446 /* -1 label was > 63 bytes */
1447 /* -2 name too long to fit in buffer. */
1448 /* */
1449 static off_t
1450 dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
1451 const char *name, const size_t name_len,
1452 struct dnslabel_table *table) {
1453 const char *end = name + name_len;
1454 int ref = 0;
1455 u16 _t;
1457 #define APPEND16(x) do { \
1458 if (j + 2 > (off_t)buf_len) \
1459 goto overflow; \
1460 _t = htons(x); \
1461 memcpy(buf + j, &_t, 2); \
1462 j += 2; \
1463 } while (0)
1464 #define APPEND32(x) do { \
1465 if (j + 4 > (off_t)buf_len) \
1466 goto overflow; \
1467 _t32 = htonl(x); \
1468 memcpy(buf + j, &_t32, 4); \
1469 j += 4; \
1470 } while (0)
1472 if (name_len > 255) return -2;
1474 for (;;) {
1475 const char *const start = name;
1476 if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1477 APPEND16(ref | 0xc000);
1478 return j;
1480 name = strchr(name, '.');
1481 if (!name) {
1482 const size_t label_len = end - start;
1483 if (label_len > 63) return -1;
1484 if ((size_t)(j+label_len+1) > buf_len) return -2;
1485 if (table) dnslabel_table_add(table, start, j);
1486 buf[j++] = (uint8_t)label_len;
1488 memcpy(buf + j, start, label_len);
1489 j += end - start;
1490 break;
1491 } else {
1492 /* append length of the label. */
1493 const size_t label_len = name - start;
1494 if (label_len > 63) return -1;
1495 if ((size_t)(j+label_len+1) > buf_len) return -2;
1496 if (table) dnslabel_table_add(table, start, j);
1497 buf[j++] = (uint8_t)label_len;
1499 memcpy(buf + j, start, name - start);
1500 j += name - start;
1501 /* hop over the '.' */
1502 name++;
1506 /* the labels must be terminated by a 0. */
1507 /* It's possible that the name ended in a . */
1508 /* in which case the zero is already there */
1509 if (!j || buf[j-1]) buf[j++] = 0;
1510 return j;
1511 overflow:
1512 return (-2);
1515 /* Finds the length of a dns request for a DNS name of the given */
1516 /* length. The actual request may be smaller than the value returned */
1517 /* here */
1518 static size_t
1519 evdns_request_len(const size_t name_len) {
1520 return 96 + /* length of the DNS standard header */
1521 name_len + 2 +
1522 4; /* space for the resource type */
1525 /* build a dns request packet into buf. buf should be at least as long */
1526 /* as evdns_request_len told you it should be. */
1527 /* */
1528 /* Returns the amount of space used. Negative on error. */
1529 static int
1530 evdns_request_data_build(const char *const name, const size_t name_len,
1531 const u16 trans_id, const u16 type, const u16 class,
1532 u8 *const buf, size_t buf_len) {
1533 off_t j = 0; /* current offset into buf */
1534 u16 _t; /* used by the macros */
1536 APPEND16(trans_id);
1537 APPEND16(0x0100); /* standard query, recusion needed */
1538 APPEND16(1); /* one question */
1539 APPEND16(0); /* no answers */
1540 APPEND16(0); /* no authority */
1541 APPEND16(0); /* no additional */
1543 j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1544 if (j < 0) {
1545 return (int)j;
1548 APPEND16(type);
1549 APPEND16(class);
1551 return (int)j;
1552 overflow:
1553 return (-1);
1556 /* exported function */
1557 struct evdns_server_port *
1558 evdns_add_server_port(int socket, int is_tcp, evdns_request_callback_fn_type cb, void *user_data)
1560 struct evdns_server_port *port;
1561 if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
1562 return NULL;
1563 memset(port, 0, sizeof(struct evdns_server_port));
1565 assert(!is_tcp); /* TCP sockets not yet implemented */
1566 port->socket = socket;
1567 port->refcnt = 1;
1568 port->choked = 0;
1569 port->closing = 0;
1570 port->user_callback = cb;
1571 port->user_data = user_data;
1572 port->pending_replies = NULL;
1574 event_set(&port->event, port->socket, EV_READ | EV_PERSIST,
1575 server_port_ready_callback, port);
1576 if (event_add(&port->event, NULL)<0) {
1577 mm_free(port);
1578 return NULL;
1580 return port;
1583 /* exported function */
1584 void
1585 evdns_close_server_port(struct evdns_server_port *port)
1587 port->closing = 1;
1588 if (--port->refcnt == 0)
1589 server_port_free(port);
1592 /* exported function */
1594 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)
1596 struct server_request *req = TO_SERVER_REQUEST(_req);
1597 struct server_reply_item **itemp, *item;
1598 int *countp;
1600 if (req->response) /* have we already answered? */
1601 return (-1);
1603 switch (section) {
1604 case EVDNS_ANSWER_SECTION:
1605 itemp = &req->answer;
1606 countp = &req->n_answer;
1607 break;
1608 case EVDNS_AUTHORITY_SECTION:
1609 itemp = &req->authority;
1610 countp = &req->n_authority;
1611 break;
1612 case EVDNS_ADDITIONAL_SECTION:
1613 itemp = &req->additional;
1614 countp = &req->n_additional;
1615 break;
1616 default:
1617 return (-1);
1619 while (*itemp) {
1620 itemp = &((*itemp)->next);
1622 item = mm_malloc(sizeof(struct server_reply_item));
1623 if (!item)
1624 return -1;
1625 CLEAR(item);
1626 item->next = NULL;
1627 if (!(item->name = mm_strdup(name))) {
1628 CLEAR(item);
1629 mm_free(item);
1630 return -1;
1632 item->type = type;
1633 item->class = class;
1634 item->ttl = ttl;
1635 item->is_name = is_name != 0;
1636 item->datalen = 0;
1637 item->data = NULL;
1638 if (data) {
1639 if (item->is_name) {
1640 if (!(item->data = mm_strdup(data))) {
1641 mm_free(item->name);
1642 CLEAR(item);
1643 mm_free(item);
1644 return -1;
1646 item->datalen = (u16)-1;
1647 } else {
1648 if (!(item->data = mm_malloc(datalen))) {
1649 mm_free(item->name);
1650 CLEAR(item);
1651 mm_free(item);
1652 return -1;
1654 item->datalen = datalen;
1655 memcpy(item->data, data, datalen);
1659 *itemp = item;
1660 ++(*countp);
1661 return 0;
1664 /* exported function */
1666 evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1668 return evdns_server_request_add_reply(
1669 req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1670 ttl, n*4, 0, addrs);
1673 /* exported function */
1675 evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, void *addrs, int ttl)
1677 return evdns_server_request_add_reply(
1678 req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1679 ttl, n*16, 0, addrs);
1682 /* exported function */
1684 evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
1686 u32 a;
1687 char buf[32];
1688 assert(in || inaddr_name);
1689 assert(!(in && inaddr_name));
1690 if (in) {
1691 a = ntohl(in->s_addr);
1692 snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
1693 (int)(u8)((a )&0xff),
1694 (int)(u8)((a>>8 )&0xff),
1695 (int)(u8)((a>>16)&0xff),
1696 (int)(u8)((a>>24)&0xff));
1697 inaddr_name = buf;
1699 return evdns_server_request_add_reply(
1700 req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1701 ttl, -1, 1, hostname);
1704 /* exported function */
1706 evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
1708 return evdns_server_request_add_reply(
1709 req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
1710 ttl, -1, 1, cname);
1714 static int
1715 evdns_server_request_format_response(struct server_request *req, int err)
1717 unsigned char buf[1500];
1718 size_t buf_len = sizeof(buf);
1719 off_t j = 0, r;
1720 u16 _t;
1721 u32 _t32;
1722 int i;
1723 u16 flags;
1724 struct dnslabel_table table;
1726 if (err < 0 || err > 15) return -1;
1728 /* Set response bit and error code; copy OPCODE and RD fields from
1729 * question; copy RA and AA if set by caller. */
1730 flags = req->base.flags;
1731 flags |= (0x8000 | err);
1733 dnslabel_table_init(&table);
1734 APPEND16(req->trans_id);
1735 APPEND16(flags);
1736 APPEND16(req->base.nquestions);
1737 APPEND16(req->n_answer);
1738 APPEND16(req->n_authority);
1739 APPEND16(req->n_additional);
1741 /* Add questions. */
1742 for (i=0; i < req->base.nquestions; ++i) {
1743 const char *s = req->base.questions[i]->name;
1744 j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1745 if (j < 0) {
1746 dnslabel_clear(&table);
1747 return (int) j;
1749 APPEND16(req->base.questions[i]->type);
1750 APPEND16(req->base.questions[i]->dns_question_class);
1753 /* Add answer, authority, and additional sections. */
1754 for (i=0; i<3; ++i) {
1755 struct server_reply_item *item;
1756 if (i==0)
1757 item = req->answer;
1758 else if (i==1)
1759 item = req->authority;
1760 else
1761 item = req->additional;
1762 while (item) {
1763 r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1764 if (r < 0)
1765 goto overflow;
1766 j = r;
1768 APPEND16(item->type);
1769 APPEND16(item->class);
1770 APPEND32(item->ttl);
1771 if (item->is_name) {
1772 off_t len_idx = j, name_start;
1773 j += 2;
1774 name_start = j;
1775 r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1776 if (r < 0)
1777 goto overflow;
1778 j = r;
1779 _t = htons( (j-name_start) );
1780 memcpy(buf+len_idx, &_t, 2);
1781 } else {
1782 APPEND16(item->datalen);
1783 if (j+item->datalen > (off_t)buf_len)
1784 goto overflow;
1785 memcpy(buf+j, item->data, item->datalen);
1786 j += item->datalen;
1788 item = item->next;
1792 if (j > 512) {
1793 overflow:
1794 j = 512;
1795 buf[2] |= 0x02; /* set the truncated bit. */
1798 req->response_len = (size_t)j;
1800 if (!(req->response = mm_malloc(req->response_len))) {
1801 server_request_free_answers(req);
1802 dnslabel_clear(&table);
1803 return (-1);
1805 memcpy(req->response, buf, req->response_len);
1806 server_request_free_answers(req);
1807 dnslabel_clear(&table);
1808 return (0);
1811 /* exported function */
1813 evdns_server_request_respond(struct evdns_server_request *_req, int err)
1815 struct server_request *req = TO_SERVER_REQUEST(_req);
1816 struct evdns_server_port *port = req->port;
1817 ssize_t r;
1818 if (!req->response) {
1819 if ((r = evdns_server_request_format_response(req, err))<0)
1820 return (int)r;
1823 r = sendto(port->socket, req->response, req->response_len, 0,
1824 (struct sockaddr*) &req->addr, req->addrlen);
1825 if (r<0) {
1826 int err = last_error(port->socket);
1827 if (! error_is_eagain(err))
1828 return -1;
1830 if (port->pending_replies) {
1831 req->prev_pending = port->pending_replies->prev_pending;
1832 req->next_pending = port->pending_replies;
1833 req->prev_pending->next_pending =
1834 req->next_pending->prev_pending = req;
1835 } else {
1836 req->prev_pending = req->next_pending = req;
1837 port->pending_replies = req;
1838 port->choked = 1;
1840 (void) event_del(&port->event);
1841 CLEAR(&port->event);
1842 event_set(&port->event, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
1844 if (event_add(&port->event, NULL) < 0) {
1845 log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
1850 return 1;
1852 if (server_request_free(req))
1853 return 0;
1855 if (port->pending_replies)
1856 server_port_flush(port);
1858 return 0;
1861 /* Free all storage held by RRs in req. */
1862 static void
1863 server_request_free_answers(struct server_request *req)
1865 struct server_reply_item *victim, *next, **list;
1866 int i;
1867 for (i = 0; i < 3; ++i) {
1868 if (i==0)
1869 list = &req->answer;
1870 else if (i==1)
1871 list = &req->authority;
1872 else
1873 list = &req->additional;
1875 victim = *list;
1876 while (victim) {
1877 next = victim->next;
1878 mm_free(victim->name);
1879 if (victim->data)
1880 mm_free(victim->data);
1881 mm_free(victim);
1882 victim = next;
1884 *list = NULL;
1888 /* Free all storage held by req, and remove links to it. */
1889 /* return true iff we just wound up freeing the server_port. */
1890 static int
1891 server_request_free(struct server_request *req)
1893 int i, rc=1;
1894 if (req->base.questions) {
1895 for (i = 0; i < req->base.nquestions; ++i)
1896 mm_free(req->base.questions[i]);
1897 mm_free(req->base.questions);
1900 if (req->port) {
1901 if (req->port->pending_replies == req) {
1902 if (req->next_pending)
1903 req->port->pending_replies = req->next_pending;
1904 else
1905 req->port->pending_replies = NULL;
1907 rc = --req->port->refcnt;
1910 if (req->response) {
1911 mm_free(req->response);
1914 server_request_free_answers(req);
1916 if (req->next_pending && req->next_pending != req) {
1917 req->next_pending->prev_pending = req->prev_pending;
1918 req->prev_pending->next_pending = req->next_pending;
1921 if (rc == 0) {
1922 server_port_free(req->port);
1923 CLEAR(req);
1924 mm_free(req);
1925 return (1);
1927 CLEAR(req);
1928 mm_free(req);
1929 return (0);
1932 /* Free all storage held by an evdns_server_port. Only called when the
1933 * reference count is down to 0. */
1934 static void
1935 server_port_free(struct evdns_server_port *port)
1937 assert(port);
1938 assert(!port->refcnt);
1939 assert(!port->pending_replies);
1940 if (port->socket > 0) {
1941 CLOSE_SOCKET(port->socket);
1942 port->socket = -1;
1944 (void) event_del(&port->event);
1945 CLEAR(&port->event);
1946 CLEAR(port);
1947 mm_free(port);
1950 /* exported function */
1952 evdns_server_request_drop(struct evdns_server_request *_req)
1954 struct server_request *req = TO_SERVER_REQUEST(_req);
1955 server_request_free(req);
1956 return 0;
1959 /* exported function */
1961 evdns_server_request_get_requesting_addr(struct evdns_server_request *_req, struct sockaddr *sa, int addr_len)
1963 struct server_request *req = TO_SERVER_REQUEST(_req);
1964 if (addr_len < (int)req->addrlen)
1965 return -1;
1966 memcpy(sa, &(req->addr), req->addrlen);
1967 return req->addrlen;
1970 #undef APPEND16
1971 #undef APPEND32
1973 /* this is a libevent callback function which is called when a request */
1974 /* has timed out. */
1975 static void
1976 evdns_request_timeout_callback(int fd, short events, void *arg) {
1977 struct evdns_request *const req = (struct evdns_request *) arg;
1978 (void) fd;
1979 (void) events;
1981 log(EVDNS_LOG_DEBUG, "Request %lx timed out", (unsigned long) arg);
1983 req->ns->timedout++;
1984 if (req->ns->timedout > global_max_nameserver_timeout) {
1985 req->ns->timedout = 0;
1986 nameserver_failed(req->ns, "request timed out.");
1989 if (req->tx_count >= global_max_retransmits) {
1990 /* this request has failed */
1991 reply_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
1992 request_finished(req, &req_head);
1993 } else {
1994 /* retransmit it */
1995 /* Stop waiting for the timeout. No need to do this in
1996 * request_finished; that one already deletes the timeout event.
1997 * XXXX021 port this change to libevent. */
1998 del_timeout_event(req);
1999 evdns_request_transmit(req);
2003 /* try to send a request to a given server. */
2004 /* */
2005 /* return: */
2006 /* 0 ok */
2007 /* 1 temporary failure */
2008 /* 2 other failure */
2009 static int
2010 evdns_request_transmit_to(struct evdns_request *req, struct nameserver *server) {
2011 const ssize_t r = send(server->socket, req->request, req->request_len, 0);
2012 if (r < 0) {
2013 int err = last_error(server->socket);
2014 if (error_is_eagain(err)) return 1;
2015 nameserver_failed(req->ns, tor_socket_strerror(err));
2016 return 2;
2017 } else if (r != (ssize_t)req->request_len) {
2018 return 1; /* short write */
2019 } else {
2020 return 0;
2024 /* try to send a request, updating the fields of the request */
2025 /* as needed */
2026 /* */
2027 /* return: */
2028 /* 0 ok */
2029 /* 1 failed */
2030 static int
2031 evdns_request_transmit(struct evdns_request *req) {
2032 int retcode = 0, r;
2034 /* if we fail to send this packet then this flag marks it */
2035 /* for evdns_transmit */
2036 req->transmit_me = 1;
2037 if (req->trans_id == 0xffff) abort();
2039 if (req->ns->choked) {
2040 /* don't bother trying to write to a socket */
2041 /* which we have had EAGAIN from */
2042 return 1;
2045 r = evdns_request_transmit_to(req, req->ns);
2046 switch (r) {
2047 case 1:
2048 /* temp failure */
2049 req->ns->choked = 1;
2050 nameserver_write_waiting(req->ns, 1);
2051 return 1;
2052 case 2:
2053 /* failed to transmit the request entirely. */
2054 retcode = 1;
2055 /* fall through: we'll set a timeout, which will time out,
2056 * and make us retransmit the request anyway. */
2057 default:
2058 /* transmitted; we need to check for timeout. */
2059 log(EVDNS_LOG_DEBUG,
2060 "Setting timeout for request %lx", (unsigned long) req);
2062 if (add_timeout_event(req, &global_timeout) < 0) {
2063 log(EVDNS_LOG_WARN,
2064 "Error from libevent when adding timer for request %lx",
2065 (unsigned long) req);
2066 /* ???? Do more? */
2068 req->tx_count++;
2069 req->transmit_me = 0;
2070 return retcode;
2074 static void
2075 nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
2076 struct sockaddr *addr = arg;
2077 struct nameserver *server;
2078 (void) type;
2079 (void) count;
2080 (void) ttl;
2081 (void) addresses;
2083 for (server = server_head; server; server = server->next) {
2084 if (sockaddr_eq(addr, (struct sockaddr*) &server->address, 1)) {
2085 if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
2086 /* this is a good reply */
2087 nameserver_up(server);
2088 } else {
2089 nameserver_probe_failed(server);
2092 if (server->next == server_head)
2093 break;
2096 mm_free(addr);
2099 static void
2100 nameserver_send_probe(struct nameserver *const ns) {
2101 struct evdns_request *req;
2102 struct sockaddr_storage *addr;
2103 /* here we need to send a probe to a given nameserver */
2104 /* in the hope that it is up now. */
2106 /* We identify the nameserver by its address, in case it is removed before
2107 * our probe comes back. */
2108 addr = mm_malloc(sizeof(struct sockaddr_storage));
2109 memcpy(addr, &ns->address, sizeof(struct sockaddr_storage));
2111 log(EVDNS_LOG_DEBUG, "Sending probe to %s", debug_ntop((struct sockaddr *)&ns->address));
2113 req = request_new(TYPE_A, "www.google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, addr);
2114 if (!req) {
2115 mm_free(addr);
2116 return;
2118 /* we force this into the inflight queue no matter what */
2119 request_trans_id_set(req, transaction_id_pick());
2120 req->ns = ns;
2121 request_submit(req);
2124 /* returns: */
2125 /* 0 didn't try to transmit anything */
2126 /* 1 tried to transmit something */
2127 static int
2128 evdns_transmit(void) {
2129 char did_try_to_transmit = 0;
2131 if (req_head) {
2132 struct evdns_request *const started_at = req_head, *req = req_head;
2133 /* first transmit all the requests which are currently waiting */
2134 do {
2135 if (req->transmit_me) {
2136 did_try_to_transmit = 1;
2137 evdns_request_transmit(req);
2140 req = req->next;
2141 } while (req != started_at);
2144 return did_try_to_transmit;
2147 /* exported function */
2149 evdns_count_nameservers(void)
2151 const struct nameserver *server = server_head;
2152 int n = 0;
2153 if (!server)
2154 return 0;
2155 do {
2156 ++n;
2157 server = server->next;
2158 } while (server != server_head);
2159 return n;
2162 /* exported function */
2164 evdns_clear_nameservers_and_suspend(void)
2166 struct nameserver *server = server_head, *started_at = server_head;
2167 struct evdns_request *req = req_head, *req_started_at = req_head;
2169 if (!server)
2170 return 0;
2171 while (1) {
2172 struct nameserver *next = server->next;
2173 (void) event_del(&server->event);
2174 CLEAR(&server->event);
2175 del_timeout_event(server);
2176 if (server->socket >= 0)
2177 CLOSE_SOCKET(server->socket);
2178 CLEAR(server);
2179 mm_free(server);
2180 if (next == started_at)
2181 break;
2182 server = next;
2184 server_head = NULL;
2185 global_good_nameservers = 0;
2187 while (req) {
2188 struct evdns_request *next = req->next;
2189 req->tx_count = req->reissue_count = 0;
2190 req->ns = NULL;
2191 /* ???? What to do about searches? */
2192 del_timeout_event(req);
2193 req->trans_id = 0;
2194 req->transmit_me = 0;
2196 global_requests_waiting++;
2197 evdns_request_insert(req, &req_waiting_head);
2198 /* We want to insert these suspended elements at the front of
2199 * the waiting queue, since they were pending before any of
2200 * the waiting entries were added. This is a circular list,
2201 * so we can just shift the start back by one.*/
2202 req_waiting_head = req_waiting_head->prev;
2204 if (next == req_started_at)
2205 break;
2206 req = next;
2208 req_head = NULL;
2209 global_requests_inflight = 0;
2211 return 0;
2214 static struct sockaddr_storage global_bind_address;
2215 static socklen_t global_bind_addrlen = 0;
2216 static int global_bind_addr_is_set = 0;
2217 void
2218 evdns_set_default_outgoing_bind_address(const struct sockaddr *addr,
2219 socklen_t addrlen)
2221 memset(&global_bind_address, 0, sizeof(global_bind_address));
2222 if (addr) {
2223 assert(addrlen <= (socklen_t)sizeof(global_bind_address));
2224 memcpy(&global_bind_address, addr, addrlen);
2225 global_bind_addrlen = addrlen;
2226 global_bind_addr_is_set = 1;
2227 } else {
2228 global_bind_addr_is_set = 0;
2232 /* exported function */
2234 evdns_resume(void)
2236 evdns_requests_pump_waiting_queue();
2237 return 0;
2240 static int
2241 _evdns_nameserver_add_impl(const struct sockaddr *address,
2242 socklen_t addrlen) {
2243 /* first check to see if we already have this nameserver */
2245 const struct nameserver *server = server_head, *const started_at = server_head;
2246 struct nameserver *ns;
2248 int err = 0;
2249 if (server) {
2250 do {
2251 if (sockaddr_eq(address, (struct sockaddr *)&server->address, 1)) {
2252 log(EVDNS_LOG_DEBUG, "Duplicate nameserver.");
2253 return 3;
2255 server = server->next;
2256 } while (server != started_at);
2258 if (addrlen > (int)sizeof(ns->address)) {
2259 log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
2260 return 2;
2263 ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
2264 if (!ns) return -1;
2266 memset(ns, 0, sizeof(struct nameserver));
2268 evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
2270 ns->socket = socket(PF_INET, SOCK_DGRAM, 0);
2271 if (ns->socket < 0) { err = 1; goto out1; }
2272 #ifdef WIN32
2274 u_long nonblocking = 1;
2275 ioctlsocket(ns->socket, FIONBIO, &nonblocking);
2277 #else
2278 fcntl(ns->socket, F_SETFL, O_NONBLOCK);
2279 #endif
2281 if (global_bind_addr_is_set) {
2282 if (bind(ns->socket, (struct sockaddr *)&global_bind_address,
2283 global_bind_addrlen) < 0) {
2284 log(EVDNS_LOG_DEBUG, "Couldn't bind to outgoing address.");
2285 err = 2;
2286 goto out2;
2290 if (connect(ns->socket, address, addrlen) != 0) {
2291 log(EVDNS_LOG_DEBUG, "Couldn't open socket to nameserver.");
2292 err = 2;
2293 goto out2;
2296 memcpy(&ns->address, address, addrlen);
2297 ns->state = 1;
2298 event_set(&ns->event, ns->socket, EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
2299 if (event_add(&ns->event, NULL) < 0) {
2300 log(EVDNS_LOG_DEBUG, "Couldn't add event for nameserver.");
2301 err = 2;
2302 goto out2;
2305 log(EVDNS_LOG_DEBUG, "Added nameserver %s", debug_ntop(address));
2307 /* insert this nameserver into the list of them */
2308 if (!server_head) {
2309 ns->next = ns->prev = ns;
2310 server_head = ns;
2311 } else {
2312 ns->next = server_head->next;
2313 ns->prev = server_head;
2314 server_head->next = ns;
2315 if (server_head->prev == server_head) {
2316 server_head->prev = ns;
2320 global_good_nameservers++;
2322 return 0;
2324 out2:
2325 CLOSE_SOCKET(ns->socket);
2326 out1:
2327 CLEAR(ns);
2328 mm_free(ns);
2329 log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d", debug_ntop(address), err);
2330 return err;
2333 /* exported function */
2335 evdns_nameserver_add(uint32_t address) {
2336 struct sockaddr_in sin;
2337 memset(&sin, 0, sizeof(sin));
2338 sin.sin_family = AF_INET;
2339 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2340 sin.sin_len = sizeof(sin);
2341 #endif
2342 sin.sin_addr.s_addr = htonl(address);
2343 sin.sin_port = 53;
2344 return _evdns_nameserver_add_impl((struct sockaddr*) &sin, sizeof(sin));
2347 /* exported function */
2349 evdns_nameserver_ip_add(const char *ip_as_string) {
2350 int port;
2351 char buf[128];
2352 const char *cp, *addr_part, *port_part;
2353 int is_ipv6;
2354 /* recognized formats are:
2355 * [ipv6]:port
2356 * ipv6
2357 * [ipv6]
2358 * ipv4:port
2359 * ipv4
2362 log(EVDNS_LOG_DEBUG, "Trying to add nameserver <%s>", ip_as_string);
2364 cp = strchr(ip_as_string, ':');
2365 if (*ip_as_string == '[') {
2366 size_t len;
2367 if (!(cp = strchr(ip_as_string, ']'))) {
2368 log(EVDNS_LOG_DEBUG, "Nameserver missing closing ]");
2369 return 4;
2371 len = cp-(ip_as_string + 1);
2372 if (len > sizeof(buf)-1) {
2373 log(EVDNS_LOG_DEBUG, "[Nameserver] does not fit in buffer.");
2374 return 4;
2376 memcpy(buf, ip_as_string+1, len);
2377 buf[len] = '\0';
2378 addr_part = buf;
2379 if (cp[1] == ':')
2380 port_part = cp+2;
2381 else
2382 port_part = NULL;
2383 is_ipv6 = 1;
2384 } else if (cp && strchr(cp+1, ':')) {
2385 is_ipv6 = 1;
2386 addr_part = ip_as_string;
2387 port_part = NULL;
2388 } else if (cp) {
2389 is_ipv6 = 0;
2390 if (cp - ip_as_string > (int)sizeof(buf)-1) {
2391 log(EVDNS_LOG_DEBUG, "Nameserver does not fit in buffer.");
2392 return 4;
2394 memcpy(buf, ip_as_string, cp-ip_as_string);
2395 buf[cp-ip_as_string] = '\0';
2396 addr_part = buf;
2397 port_part = cp+1;
2398 } else {
2399 addr_part = ip_as_string;
2400 port_part = NULL;
2401 is_ipv6 = 0;
2404 if (port_part == NULL) {
2405 port = 53;
2406 } else {
2407 port = strtoint(port_part);
2408 if (port <= 0 || port > 65535) {
2409 log(EVDNS_LOG_DEBUG, "Nameserver port <%s> out of range",
2410 port_part);
2411 return 4;
2415 /* Tor-only. needs a more general fix. */
2416 assert(addr_part);
2417 if (is_ipv6) {
2418 struct sockaddr_in6 sin6;
2419 memset(&sin6, 0, sizeof(sin6));
2420 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
2421 sin6.sin6_len = sizeof(sin6);
2422 #endif
2423 sin6.sin6_family = AF_INET6;
2424 sin6.sin6_port = htons(port);
2425 if (1 != tor_inet_pton(AF_INET6, addr_part, &sin6.sin6_addr)) {
2426 log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
2427 return 4;
2429 return _evdns_nameserver_add_impl((struct sockaddr*)&sin6,
2430 sizeof(sin6));
2431 } else {
2432 struct sockaddr_in sin;
2433 memset(&sin, 0, sizeof(sin));
2434 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
2435 sin.sin_len = sizeof(sin);
2436 #endif
2437 sin.sin_family = AF_INET;
2438 sin.sin_port = htons(port);
2439 if (!inet_aton(addr_part, &sin.sin_addr)) {
2440 log(EVDNS_LOG_DEBUG, "inet_pton(%s) failed", addr_part);
2441 return 4;
2443 return _evdns_nameserver_add_impl((struct sockaddr*)&sin,
2444 sizeof(sin));
2449 evdns_nameserver_sockaddr_add(const struct sockaddr *sa, socklen_t len)
2451 return _evdns_nameserver_add_impl(sa, len);
2454 /* insert into the tail of the queue */
2455 static void
2456 evdns_request_insert(struct evdns_request *req, struct evdns_request **head) {
2457 if (!*head) {
2458 *head = req;
2459 req->next = req->prev = req;
2460 return;
2463 req->prev = (*head)->prev;
2464 req->prev->next = req;
2465 req->next = *head;
2466 (*head)->prev = req;
2469 static int
2470 string_num_dots(const char *s) {
2471 int count = 0;
2472 while ((s = strchr(s, '.'))) {
2473 s++;
2474 count++;
2476 return count;
2479 static struct evdns_request *
2480 request_new(int type, const char *name, int flags,
2481 evdns_callback_type callback, void *user_ptr) {
2482 const char issuing_now =
2483 (global_requests_inflight < global_max_requests_inflight) ? 1 : 0;
2485 const size_t name_len = strlen(name);
2486 const size_t request_max_len = evdns_request_len(name_len);
2487 const u16 trans_id = issuing_now ? transaction_id_pick() : 0xffff;
2488 /* the request data is alloced in a single block with the header */
2489 struct evdns_request *const req =
2490 (struct evdns_request *) mm_malloc(sizeof(struct evdns_request) + request_max_len);
2491 char namebuf[256];
2492 int rlen;
2493 (void) flags;
2495 if (!req) return NULL;
2497 if (name_len >= sizeof(namebuf)) {
2498 _mm_free(req);
2499 return NULL;
2502 memset(req, 0, sizeof(struct evdns_request));
2504 evtimer_set(&req->timeout_event, evdns_request_timeout_callback, req);
2506 if (global_randomize_case) {
2507 unsigned i;
2508 char randbits[32];
2509 strlcpy(namebuf, name, sizeof(namebuf));
2510 rand_bytes_function(randbits, (name_len+7)/8);
2511 for (i = 0; i < name_len; ++i) {
2512 if (ISALPHA(namebuf[i])) {
2513 if ((randbits[i >> 3] & (1<<(i%7))))
2514 namebuf[i] = TOLOWER(namebuf[i]);
2515 else
2516 namebuf[i] = TOUPPER(namebuf[i]);
2519 name = namebuf;
2522 /* request data lives just after the header */
2523 req->request = ((u8 *) req) + sizeof(struct evdns_request);
2524 /* denotes that the request data shouldn't be mm_free()ed */
2525 req->request_appended = 1;
2526 rlen = evdns_request_data_build(name, name_len, trans_id,
2527 type, CLASS_INET, req->request, request_max_len);
2528 if (rlen < 0)
2529 goto err1;
2530 req->request_len = rlen;
2531 req->trans_id = trans_id;
2532 req->tx_count = 0;
2533 req->request_type = type;
2534 req->user_pointer = user_ptr;
2535 req->user_callback = callback;
2536 req->ns = issuing_now ? nameserver_pick() : NULL;
2537 req->next = req->prev = NULL;
2539 return req;
2540 err1:
2541 CLEAR(req);
2542 _mm_free(req);
2543 return NULL;
2546 static void
2547 request_submit(struct evdns_request *const req) {
2548 if (req->ns) {
2549 /* if it has a nameserver assigned then this is going */
2550 /* straight into the inflight queue */
2551 evdns_request_insert(req, &req_head);
2552 global_requests_inflight++;
2553 evdns_request_transmit(req);
2554 } else {
2555 evdns_request_insert(req, &req_waiting_head);
2556 global_requests_waiting++;
2560 /* exported function */
2561 int evdns_resolve_ipv4(const char *name, int flags,
2562 evdns_callback_type callback, void *ptr) {
2563 log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2564 if (flags & DNS_QUERY_NO_SEARCH) {
2565 struct evdns_request *const req =
2566 request_new(TYPE_A, name, flags, callback, ptr);
2567 if (req == NULL)
2568 return (1);
2569 request_submit(req);
2570 return (0);
2571 } else {
2572 return (search_request_new(TYPE_A, name, flags, callback, ptr));
2576 /* exported function */
2577 int evdns_resolve_ipv6(const char *name, int flags,
2578 evdns_callback_type callback, void *ptr) {
2579 log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2580 if (flags & DNS_QUERY_NO_SEARCH) {
2581 struct evdns_request *const req =
2582 request_new(TYPE_AAAA, name, flags, callback, ptr);
2583 if (req == NULL)
2584 return (1);
2585 request_submit(req);
2586 return (0);
2587 } else {
2588 return (search_request_new(TYPE_AAAA, name, flags, callback, ptr));
2592 int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2593 char buf[32];
2594 struct evdns_request *req;
2595 u32 a;
2596 assert(in);
2597 a = ntohl(in->s_addr);
2598 snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
2599 (int)(u8)((a )&0xff),
2600 (int)(u8)((a>>8 )&0xff),
2601 (int)(u8)((a>>16)&0xff),
2602 (int)(u8)((a>>24)&0xff));
2603 log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2604 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2605 if (!req) return 1;
2606 request_submit(req);
2607 return 0;
2610 int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2611 /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
2612 char buf[73];
2613 char *cp;
2614 struct evdns_request *req;
2615 int i;
2616 assert(in);
2617 cp = buf;
2618 for (i=15; i >= 0; --i) {
2619 u8 byte = in->s6_addr[i];
2620 *cp++ = "0123456789abcdef"[byte & 0x0f];
2621 *cp++ = '.';
2622 *cp++ = "0123456789abcdef"[byte >> 4];
2623 *cp++ = '.';
2625 assert(cp + strlen("ip6.arpa") < buf+sizeof(buf));
2626 memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
2627 log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
2628 req = request_new(TYPE_PTR, buf, flags, callback, ptr);
2629 if (!req) return 1;
2630 request_submit(req);
2631 return 0;
2634 /*/////////////////////////////////////////////////////////////////// */
2635 /* Search support */
2636 /* */
2637 /* the libc resolver has support for searching a number of domains */
2638 /* to find a name. If nothing else then it takes the single domain */
2639 /* from the gethostname() call. */
2640 /* */
2641 /* It can also be configured via the domain and search options in a */
2642 /* resolv.conf. */
2643 /* */
2644 /* The ndots option controls how many dots it takes for the resolver */
2645 /* to decide that a name is non-local and so try a raw lookup first. */
2647 struct search_domain {
2648 size_t len;
2649 struct search_domain *next;
2650 /* the text string is appended to this structure */
2653 struct search_state {
2654 int refcount;
2655 int ndots;
2656 int num_domains;
2657 struct search_domain *head;
2660 static struct search_state *global_search_state = NULL;
2662 static void
2663 search_state_decref(struct search_state *const state) {
2664 if (!state) return;
2665 state->refcount--;
2666 if (!state->refcount) {
2667 struct search_domain *next, *dom;
2668 for (dom = state->head; dom; dom = next) {
2669 next = dom->next;
2670 CLEAR(dom);
2671 _mm_free(dom);
2673 CLEAR(state);
2674 _mm_free(state);
2678 static struct search_state *
2679 search_state_new(void) {
2680 struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
2681 if (!state) return NULL;
2682 memset(state, 0, sizeof(struct search_state));
2683 state->refcount = 1;
2684 state->ndots = 1;
2686 return state;
2689 static void
2690 search_postfix_clear(void) {
2691 search_state_decref(global_search_state);
2693 global_search_state = search_state_new();
2696 /* exported function */
2697 void
2698 evdns_search_clear(void) {
2699 search_postfix_clear();
2702 static void
2703 search_postfix_add(const char *domain) {
2704 size_t domain_len;
2705 struct search_domain *sdomain;
2706 while (domain[0] == '.') domain++;
2707 domain_len = strlen(domain);
2709 if (!global_search_state) global_search_state = search_state_new();
2710 if (!global_search_state) return;
2711 global_search_state->num_domains++;
2713 sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
2714 if (!sdomain) return;
2715 memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
2716 sdomain->next = global_search_state->head;
2717 sdomain->len = domain_len;
2719 global_search_state->head = sdomain;
2722 /* reverse the order of members in the postfix list. This is needed because, */
2723 /* when parsing resolv.conf we push elements in the wrong order */
2724 static void
2725 search_reverse(void) {
2726 struct search_domain *cur, *prev = NULL, *next;
2727 cur = global_search_state->head;
2728 while (cur) {
2729 next = cur->next;
2730 cur->next = prev;
2731 prev = cur;
2732 cur = next;
2735 global_search_state->head = prev;
2738 /* exported function */
2739 void
2740 evdns_search_add(const char *domain) {
2741 search_postfix_add(domain);
2744 /* exported function */
2745 void
2746 evdns_search_ndots_set(const int ndots) {
2747 if (!global_search_state) global_search_state = search_state_new();
2748 if (!global_search_state) return;
2749 global_search_state->ndots = ndots;
2752 static void
2753 search_set_from_hostname(void) {
2754 char hostname[HOST_NAME_MAX + 1], *domainname;
2756 search_postfix_clear();
2757 if (gethostname(hostname, sizeof(hostname))) return;
2758 domainname = strchr(hostname, '.');
2759 if (!domainname) return;
2760 search_postfix_add(domainname);
2763 /* warning: returns malloced string */
2764 static char *
2765 search_make_new(const struct search_state *const state, int n, const char *const base_name) {
2766 const size_t base_len = strlen(base_name);
2767 const char need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
2768 struct search_domain *dom;
2770 for (dom = state->head; dom; dom = dom->next) {
2771 if (!n--) {
2772 /* this is the postfix we want */
2773 /* the actual postfix string is kept at the end of the structure */
2774 const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
2775 const size_t postfix_len = dom->len;
2776 char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
2777 if (!newname) return NULL;
2778 memcpy(newname, base_name, base_len);
2779 if (need_to_append_dot) newname[base_len] = '.';
2780 memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
2781 newname[base_len + need_to_append_dot + postfix_len] = 0;
2782 return newname;
2786 /* we ran off the end of the list and still didn't find the requested string */
2787 abort();
2788 return NULL; /* unreachable; stops warnings in some compilers. */
2791 static int
2792 search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg) {
2793 assert(type == TYPE_A || type == TYPE_AAAA);
2794 if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
2795 global_search_state &&
2796 global_search_state->num_domains) {
2797 /* we have some domains to search */
2798 struct evdns_request *req;
2799 if (string_num_dots(name) >= global_search_state->ndots) {
2800 req = request_new(type, name, flags, user_callback, user_arg);
2801 if (!req) return 1;
2802 req->search_index = -1;
2803 } else {
2804 char *const new_name = search_make_new(global_search_state, 0, name);
2805 if (!new_name) return 1;
2806 req = request_new(type, new_name, flags, user_callback, user_arg);
2807 _mm_free(new_name);
2808 if (!req) return 1;
2809 req->search_index = 0;
2811 req->search_origname = mm_strdup(name);
2812 req->search_state = global_search_state;
2813 req->search_flags = flags;
2814 global_search_state->refcount++;
2815 request_submit(req);
2816 return 0;
2817 } else {
2818 struct evdns_request *const req = request_new(type, name, flags, user_callback, user_arg);
2819 if (!req) return 1;
2820 request_submit(req);
2821 return 0;
2825 /* this is called when a request has failed to find a name. We need to check */
2826 /* if it is part of a search and, if so, try the next name in the list */
2827 /* returns: */
2828 /* 0 another request has been submitted */
2829 /* 1 no more requests needed */
2830 static int
2831 search_try_next(struct evdns_request *const req) {
2832 if (req->search_state) {
2833 /* it is part of a search */
2834 char *new_name;
2835 struct evdns_request *newreq;
2836 req->search_index++;
2837 if (req->search_index >= req->search_state->num_domains) {
2838 /* no more postfixes to try, however we may need to try */
2839 /* this name without a postfix */
2840 if (string_num_dots(req->search_origname) < req->search_state->ndots) {
2841 /* yep, we need to try it raw */
2842 struct evdns_request *const newreq = request_new(req->request_type, req->search_origname, req->search_flags, req->user_callback, req->user_pointer);
2843 log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", req->search_origname);
2844 if (newreq) {
2845 request_submit(newreq);
2846 return 0;
2849 return 1;
2852 new_name = search_make_new(req->search_state, req->search_index, req->search_origname);
2853 if (!new_name) return 1;
2854 log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, req->search_index);
2855 newreq = request_new(req->request_type, new_name, req->search_flags, req->user_callback, req->user_pointer);
2856 mm_free(new_name);
2857 if (!newreq) return 1;
2858 newreq->search_origname = req->search_origname;
2859 req->search_origname = NULL;
2860 newreq->search_state = req->search_state;
2861 newreq->search_flags = req->search_flags;
2862 newreq->search_index = req->search_index;
2863 newreq->search_state->refcount++;
2864 request_submit(newreq);
2865 return 0;
2867 return 1;
2870 static void
2871 search_request_finished(struct evdns_request *const req) {
2872 if (req->search_state) {
2873 search_state_decref(req->search_state);
2874 req->search_state = NULL;
2876 if (req->search_origname) {
2877 mm_free(req->search_origname);
2878 req->search_origname = NULL;
2882 /*/////////////////////////////////////////////////////////////////// */
2883 /* Parsing resolv.conf files */
2885 static void
2886 evdns_resolv_set_defaults(int flags) {
2887 /* if the file isn't found then we assume a local resolver */
2888 if (flags & DNS_OPTION_SEARCH) search_set_from_hostname();
2889 if (flags & DNS_OPTION_NAMESERVERS) evdns_nameserver_ip_add("127.0.0.1");
2892 /* helper version of atoi which returns -1 on error */
2893 static int
2894 strtoint(const char *const str) {
2895 char *endptr;
2896 const long r = strtol(str, &endptr, 10);
2897 if (*endptr || r > INT_MAX) return -1;
2898 return (int)r;
2901 /* helper version of atoi that returns -1 on error and clips to bounds. */
2902 static int
2903 strtoint_clipped(const char *const str, int min, int max)
2905 int r = strtoint(str);
2906 if (r == -1)
2907 return r;
2908 else if (r<min)
2909 return min;
2910 else if (r>max)
2911 return max;
2912 else
2913 return r;
2916 /* exported function */
2918 evdns_set_option(const char *option, const char *val, int flags)
2920 if (!strncmp(option, "ndots:", 6)) {
2921 const int ndots = strtoint(val);
2922 if (ndots == -1) return -1;
2923 if (!(flags & DNS_OPTION_SEARCH)) return 0;
2924 log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
2925 if (!global_search_state) global_search_state = search_state_new();
2926 if (!global_search_state) return -1;
2927 global_search_state->ndots = ndots;
2928 } else if (!strncmp(option, "timeout:", 8)) {
2929 const int timeout = strtoint(val);
2930 if (timeout == -1) return -1;
2931 if (!(flags & DNS_OPTION_MISC)) return 0;
2932 log(EVDNS_LOG_DEBUG, "Setting timeout to %d", timeout);
2933 global_timeout.tv_sec = timeout;
2934 } else if (!strncmp(option, "max-timeouts:", 12)) {
2935 const int maxtimeout = strtoint_clipped(val, 1, 255);
2936 if (maxtimeout == -1) return -1;
2937 if (!(flags & DNS_OPTION_MISC)) return 0;
2938 log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
2939 maxtimeout);
2940 global_max_nameserver_timeout = maxtimeout;
2941 } else if (!strncmp(option, "max-inflight:", 13)) {
2942 const int maxinflight = strtoint_clipped(val, 1, 65000);
2943 if (maxinflight == -1) return -1;
2944 if (!(flags & DNS_OPTION_MISC)) return 0;
2945 log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
2946 maxinflight);
2947 global_max_requests_inflight = maxinflight;
2948 } else if (!strncmp(option, "attempts:", 9)) {
2949 int retries = strtoint(val);
2950 if (retries == -1) return -1;
2951 if (retries > 255) retries = 255;
2952 if (!(flags & DNS_OPTION_MISC)) return 0;
2953 log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
2954 global_max_retransmits = retries;
2955 } else if (!strncmp(option, "randomize-case:", 15)) {
2956 int randcase = strtoint(val);
2957 if (!(flags & DNS_OPTION_MISC)) return 0;
2958 log(EVDNS_LOG_DEBUG, "Setting randomize_case to %d", randcase);
2959 global_randomize_case = randcase;
2961 return 0;
2964 static void
2965 resolv_conf_parse_line(char *const start, int flags) {
2966 char *strtok_state;
2967 static const char *const delims = " \t";
2968 #define NEXT_TOKEN tor_strtok_r(NULL, delims, &strtok_state)
2970 char *const first_token = tor_strtok_r(start, delims, &strtok_state);
2971 if (!first_token) return;
2973 if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
2974 const char *const nameserver = NEXT_TOKEN;
2975 evdns_nameserver_ip_add(nameserver);
2976 } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
2977 const char *const domain = NEXT_TOKEN;
2978 if (domain) {
2979 search_postfix_clear();
2980 search_postfix_add(domain);
2982 } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
2983 const char *domain;
2984 search_postfix_clear();
2986 while ((domain = NEXT_TOKEN)) {
2987 search_postfix_add(domain);
2989 search_reverse();
2990 } else if (!strcmp(first_token, "options")) {
2991 const char *option;
2992 while ((option = NEXT_TOKEN)) {
2993 const char *val = strchr(option, ':');
2994 evdns_set_option(option, val ? val+1 : "", flags);
2997 #undef NEXT_TOKEN
3000 /* exported function */
3001 /* returns: */
3002 /* 0 no errors */
3003 /* 1 failed to open file */
3004 /* 2 failed to stat file */
3005 /* 3 file too large */
3006 /* 4 out of memory */
3007 /* 5 short read from file */
3009 evdns_resolv_conf_parse(int flags, const char *const filename) {
3010 struct stat st;
3011 int fd, n, r;
3012 u8 *resolv;
3013 char *start;
3014 int err = 0;
3016 log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
3018 fd = open(filename, O_RDONLY);
3019 if (fd < 0) {
3020 evdns_resolv_set_defaults(flags);
3021 return 1;
3024 if (fstat(fd, &st)) { err = 2; goto out1; }
3025 if (!st.st_size) {
3026 evdns_resolv_set_defaults(flags);
3027 err = (flags & DNS_OPTION_NAMESERVERS) ? 6 : 0;
3028 goto out1;
3030 if (st.st_size > 65535) { err = 3; goto out1; } /* no resolv.conf should be any bigger */
3032 resolv = (u8 *) mm_malloc((size_t)st.st_size + 1);
3033 if (!resolv) { err = 4; goto out1; }
3035 n = 0;
3036 while ((r = (int)read(fd, resolv+n, (size_t)st.st_size-n)) > 0) {
3037 n += r;
3038 if (n == st.st_size)
3039 break;
3040 assert(n < st.st_size);
3042 if (r < 0) { err = 5; goto out2; }
3043 resolv[n] = 0; /* we malloced an extra byte; this should be fine. */
3045 start = (char *) resolv;
3046 for (;;) {
3047 char *const newline = strchr(start, '\n');
3048 if (!newline) {
3049 resolv_conf_parse_line(start, flags);
3050 break;
3051 } else {
3052 *newline = 0;
3053 resolv_conf_parse_line(start, flags);
3054 start = newline + 1;
3058 if (!server_head && (flags & DNS_OPTION_NAMESERVERS)) {
3059 /* no nameservers were configured. */
3060 evdns_nameserver_ip_add("127.0.0.1");
3061 err = 6;
3063 if (flags & DNS_OPTION_SEARCH && (!global_search_state || global_search_state->num_domains == 0)) {
3064 search_set_from_hostname();
3067 out2:
3068 mm_free(resolv);
3069 out1:
3070 close(fd);
3071 return err;
3074 #ifdef WIN32
3075 /* Add multiple nameservers from a space-or-comma-separated list. */
3076 static int
3077 evdns_nameserver_ip_add_line(const char *ips) {
3078 const char *addr;
3079 char *buf;
3080 int r;
3081 while (*ips) {
3082 while (ISSPACE(*ips) || *ips == ',' || *ips == '\t')
3083 ++ips;
3084 addr = ips;
3085 while (ISDIGIT(*ips) || *ips == '.' || *ips == ':' || *ips == '[' || *ips == ']')
3086 ++ips;
3087 buf = mm_malloc(ips-addr+1);
3088 if (!buf) return 4;
3089 memcpy(buf, addr, ips-addr);
3090 buf[ips-addr] = '\0';
3091 r = evdns_nameserver_ip_add(buf);
3092 mm_free(buf);
3093 if (r) return r;
3095 return 0;
3098 typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
3100 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3101 /* figure out what our nameservers are. */
3102 static int
3103 load_nameservers_with_getnetworkparams(void)
3105 /* Based on MSDN examples and inspection of c-ares code. */
3106 FIXED_INFO *fixed;
3107 HMODULE handle = 0;
3108 ULONG size = sizeof(FIXED_INFO);
3109 void *buf = NULL;
3110 int status = 0, r, added_any;
3111 IP_ADDR_STRING *ns;
3112 GetNetworkParams_fn_t fn;
3114 /* XXXX Possibly, we should hardcode the location of this DLL. */
3115 if (!(handle = LoadLibrary("iphlpapi.dll"))) {
3116 log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
3117 /* right now status = 0, doesn't that mean "good" - mikec */
3118 status = -1;
3119 goto done;
3121 if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
3122 log(EVDNS_LOG_WARN, "Could not get address of function.");
3123 /* same as above */
3124 status = -1;
3125 goto done;
3128 buf = mm_malloc(size);
3129 if (!buf) { status = 4; goto done; }
3130 fixed = buf;
3131 r = fn(fixed, &size);
3132 if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
3133 status = -1;
3134 goto done;
3136 if (r != ERROR_SUCCESS) {
3137 mm_free(buf);
3138 buf = mm_malloc(size);
3139 if (!buf) { status = 4; goto done; }
3140 fixed = buf;
3141 r = fn(fixed, &size);
3142 if (r != ERROR_SUCCESS) {
3143 log(EVDNS_LOG_DEBUG, "fn() failed.");
3144 status = -1;
3145 goto done;
3149 assert(fixed);
3150 added_any = 0;
3151 ns = &(fixed->DnsServerList);
3152 while (ns) {
3153 r = evdns_nameserver_ip_add_line(ns->IpAddress.String);
3154 if (r) {
3155 log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list, "
3156 "error: %d; status: %d",
3157 (ns->IpAddress.String),(int)GetLastError(), r);
3158 status = r;
3159 } else {
3160 log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
3161 added_any++;
3164 ns = ns->Next;
3167 if (!added_any) {
3168 log(EVDNS_LOG_DEBUG, "No nameservers added.");
3169 if (status == 0)
3170 status = -1;
3171 } else {
3172 status = 0;
3175 done:
3176 if (buf)
3177 mm_free(buf);
3178 if (handle)
3179 FreeLibrary(handle);
3180 return status;
3183 static int
3184 config_nameserver_from_reg_key(HKEY key, const char *subkey)
3186 char *buf;
3187 DWORD bufsz = 0, type = 0;
3188 int status = 0;
3190 if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
3191 != ERROR_MORE_DATA)
3192 return -1;
3193 if (!(buf = mm_malloc(bufsz)))
3194 return -1;
3196 if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
3197 == ERROR_SUCCESS && bufsz > 1) {
3198 status = evdns_nameserver_ip_add_line(buf);
3201 mm_free(buf);
3202 return status;
3205 #define SERVICES_KEY "System\\CurrentControlSet\\Services\\"
3206 #define WIN_NS_9X_KEY SERVICES_KEY "VxD\\MSTCP"
3207 #define WIN_NS_NT_KEY SERVICES_KEY "Tcpip\\Parameters"
3209 static int
3210 load_nameservers_from_registry(void)
3212 int found = 0;
3213 int r;
3214 #define TRY(k, name) \
3215 if (!found && config_nameserver_from_reg_key(k,name) == 0) { \
3216 log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3217 found = 1; \
3218 } else if (!found) { \
3219 log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3220 #k,#name); \
3223 if (((int)GetVersion()) > 0) { /* NT */
3224 HKEY nt_key = 0, interfaces_key = 0;
3226 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
3227 KEY_READ, &nt_key) != ERROR_SUCCESS) {
3228 log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
3229 return -1;
3231 r = RegOpenKeyEx(nt_key, "Interfaces", 0,
3232 KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
3233 &interfaces_key);
3234 if (r != ERROR_SUCCESS) {
3235 log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
3236 return -1;
3238 TRY(nt_key, "NameServer");
3239 TRY(nt_key, "DhcpNameServer");
3240 TRY(interfaces_key, "NameServer");
3241 TRY(interfaces_key, "DhcpNameServer");
3242 RegCloseKey(interfaces_key);
3243 RegCloseKey(nt_key);
3244 } else {
3245 HKEY win_key = 0;
3246 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
3247 KEY_READ, &win_key) != ERROR_SUCCESS) {
3248 log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
3249 return -1;
3251 TRY(win_key, "NameServer");
3252 RegCloseKey(win_key);
3255 if (found == 0) {
3256 log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
3259 return found ? 0 : -1;
3260 #undef TRY
3264 evdns_config_windows_nameservers(void)
3266 if (load_nameservers_with_getnetworkparams() == 0)
3267 return 0;
3268 return load_nameservers_from_registry();
3270 #endif
3273 evdns_init(void)
3275 int res = 0;
3276 #ifdef WIN32
3277 evdns_config_windows_nameservers();
3278 #else
3279 res = evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
3280 #endif
3282 return (res);
3285 const char *
3286 evdns_err_to_string(int err)
3288 switch (err) {
3289 case DNS_ERR_NONE: return "no error";
3290 case DNS_ERR_FORMAT: return "misformatted query";
3291 case DNS_ERR_SERVERFAILED: return "server failed";
3292 case DNS_ERR_NOTEXIST: return "name does not exist";
3293 case DNS_ERR_NOTIMPL: return "query not implemented";
3294 case DNS_ERR_REFUSED: return "refused";
3296 case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
3297 case DNS_ERR_UNKNOWN: return "unknown";
3298 case DNS_ERR_TIMEOUT: return "request timed out";
3299 case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
3300 default: return "[Unknown error code]";
3304 void
3305 evdns_shutdown(int fail_requests)
3307 struct nameserver *server, *server_next;
3308 struct search_domain *dom, *dom_next;
3310 while (req_head) {
3311 if (fail_requests)
3312 reply_callback(req_head, 0, DNS_ERR_SHUTDOWN, NULL);
3313 request_finished(req_head, &req_head);
3315 while (req_waiting_head) {
3316 if (fail_requests)
3317 reply_callback(req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
3318 request_finished(req_waiting_head, &req_waiting_head);
3320 global_requests_inflight = global_requests_waiting = 0;
3322 for (server = server_head; server; server = server_next) {
3323 server_next = server->next;
3324 if (server->socket >= 0)
3325 CLOSE_SOCKET(server->socket);
3326 (void) event_del(&server->event);
3327 del_timeout_event(server);
3328 CLEAR(server);
3329 mm_free(server);
3330 if (server_next == server_head)
3331 break;
3333 server_head = NULL;
3334 global_good_nameservers = 0;
3336 if (global_search_state) {
3337 for (dom = global_search_state->head; dom; dom = dom_next) {
3338 dom_next = dom->next;
3339 CLEAR(dom);
3340 mm_free(dom);
3342 CLEAR(global_search_state);
3343 mm_free(global_search_state);
3344 global_search_state = NULL;
3346 evdns_log_fn = NULL;
3349 #ifdef EVDNS_MAIN
3350 void
3351 main_callback(int result, char type, int count, int ttl,
3352 void *addrs, void *orig) {
3353 char *n = (char*)orig;
3354 int i;
3355 for (i = 0; i < count; ++i) {
3356 if (type == DNS_IPv4_A) {
3357 printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
3358 } else if (type == DNS_PTR) {
3359 printf("%s: %s\n", n, ((char**)addrs)[i]);
3362 if (!count) {
3363 printf("%s: No answer (%d)\n", n, result);
3365 fflush(stdout);
3367 void
3368 evdns_server_callback(struct evdns_server_request *req, void *data)
3370 int i, r;
3371 (void)data;
3372 /* dummy; give 192.168.11.11 as an answer for all A questions,
3373 * give foo.bar.example.com as an answer for all PTR questions. */
3374 for (i = 0; i < req->nquestions; ++i) {
3375 u32 ans = htonl(0xc0a80b0bUL);
3376 if (req->questions[i]->type == EVDNS_TYPE_A &&
3377 req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
3378 printf(" -- replying for %s (A)\n", req->questions[i]->name);
3379 r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
3380 1, &ans, 10);
3381 if (r<0)
3382 printf("eeep, didn't work.\n");
3383 } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
3384 req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
3385 printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
3386 r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
3387 "foo.bar.example.com", 10);
3388 } else {
3389 printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
3390 req->questions[i]->type, req->questions[i]->dns_question_class);
3394 r = evdns_server_request_respond(req, 0);
3395 if (r<0)
3396 printf("eeek, couldn't send reply.\n");
3399 void
3400 logfn(int is_warn, const char *msg) {
3401 (void) is_warn;
3402 fprintf(stderr, "%s\n", msg);
3405 main(int c, char **v) {
3406 int idx;
3407 int reverse = 0, verbose = 1, servertest = 0;
3408 if (c<2) {
3409 fprintf(stderr, "syntax: %s [-x] [-v] hostname\n", v[0]);
3410 fprintf(stderr, "syntax: %s [-servertest]\n", v[0]);
3411 return 1;
3413 idx = 1;
3414 while (idx < c && v[idx][0] == '-') {
3415 if (!strcmp(v[idx], "-x"))
3416 reverse = 1;
3417 else if (!strcmp(v[idx], "-v"))
3418 verbose = 1;
3419 else if (!strcmp(v[idx], "-servertest"))
3420 servertest = 1;
3421 else
3422 fprintf(stderr, "Unknown option %s\n", v[idx]);
3423 ++idx;
3425 event_init();
3426 if (verbose)
3427 evdns_set_log_fn(logfn);
3428 evdns_resolv_conf_parse(DNS_OPTION_NAMESERVERS, "/etc/resolv.conf");
3429 if (servertest) {
3430 int sock;
3431 struct sockaddr_in my_addr;
3432 sock = socket(PF_INET, SOCK_DGRAM, 0);
3433 fcntl(sock, F_SETFL, O_NONBLOCK);
3434 my_addr.sin_family = AF_INET;
3435 my_addr.sin_port = htons(10053);
3436 my_addr.sin_addr.s_addr = INADDR_ANY;
3437 if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
3438 perror("bind");
3439 exit(1);
3441 evdns_add_server_port(sock, 0, evdns_server_callback, NULL);
3443 for (; idx < c; ++idx) {
3444 if (reverse) {
3445 struct in_addr addr;
3446 if (!inet_aton(v[idx], &addr)) {
3447 fprintf(stderr, "Skipping non-IP %s\n", v[idx]);
3448 continue;
3450 fprintf(stderr, "resolving %s...\n",v[idx]);
3451 evdns_resolve_reverse(&addr, 0, main_callback, v[idx]);
3452 } else {
3453 fprintf(stderr, "resolving (fwd) %s...\n",v[idx]);
3454 evdns_resolve_ipv4(v[idx], 0, main_callback, v[idx]);
3457 fflush(stdout);
3458 event_dispatch();
3459 return 0;
3461 #endif
3463 /* Local Variables: */
3464 /* tab-width: 4 */
3465 /* c-basic-offset: 4 */
3466 /* indent-tabs-mode: t */
3467 /* End: */