xref: /netbsd/external/bsd/libevent/dist/evdns.c (revision 7c5f803c)
1 /*	$NetBSD: evdns.c,v 1.7 2021/04/10 19:18:45 rillig Exp $	*/
2 
3 /* Copyright 2006-2007 Niels Provos
4  * Copyright 2007-2012 Nick Mathewson and Niels Provos
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /* Based on software by Adam Langly. Adam's original message:
30  *
31  * Async DNS Library
32  * Adam Langley <agl@imperialviolet.org>
33  * http://www.imperialviolet.org/eventdns.html
34  * Public Domain code
35  *
36  * This software is Public Domain. To view a copy of the public domain dedication,
37  * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
38  * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
39  *
40  * I ask and expect, but do not require, that all derivative works contain an
41  * attribution similar to:
42  *	Parts developed by Adam Langley <agl@imperialviolet.org>
43  *
44  * You may wish to replace the word "Parts" with something else depending on
45  * the amount of original code.
46  *
47  * (Derivative works does not include programs which link against, run or include
48  * the source verbatim in their source distributions)
49  *
50  * Version: 0.1b
51  */
52 
53 #include "event2/event-config.h"
54 #include <sys/cdefs.h>
55 __RCSID("$NetBSD: evdns.c,v 1.7 2021/04/10 19:18:45 rillig Exp $");
56 #include "evconfig-private.h"
57 
58 #include <sys/types.h>
59 
60 #ifndef _FORTIFY_SOURCE
61 #define _FORTIFY_SOURCE 3
62 #endif
63 
64 #include <string.h>
65 #include <fcntl.h>
66 #ifdef EVENT__HAVE_SYS_TIME_H
67 #include <sys/time.h>
68 #endif
69 #ifdef EVENT__HAVE_STDINT_H
70 #include <stdint.h>
71 #endif
72 #include <stdlib.h>
73 #include <string.h>
74 #include <errno.h>
75 #ifdef EVENT__HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78 #include <limits.h>
79 #include <sys/stat.h>
80 #include <stdio.h>
81 #include <stdarg.h>
82 #ifdef _WIN32
83 #include <winsock2.h>
84 #include <winerror.h>
85 #include <ws2tcpip.h>
86 #ifndef _WIN32_IE
87 #define _WIN32_IE 0x400
88 #endif
89 #include <shlobj.h>
90 #endif
91 
92 #include "event2/dns.h"
93 #include "event2/dns_struct.h"
94 #include "event2/dns_compat.h"
95 #include "event2/util.h"
96 #include "event2/event.h"
97 #include "event2/event_struct.h"
98 #include "event2/thread.h"
99 
100 #include "defer-internal.h"
101 #include "log-internal.h"
102 #include "mm-internal.h"
103 #include "strlcpy-internal.h"
104 #include "ipv6-internal.h"
105 #include "util-internal.h"
106 #include "evthread-internal.h"
107 #ifdef _WIN32
108 #include <ctype.h>
109 #include <winsock2.h>
110 #include <windows.h>
111 #include <iphlpapi.h>
112 #include <io.h>
113 #else
114 #include <sys/socket.h>
115 #include <netinet/in.h>
116 #include <arpa/inet.h>
117 #endif
118 
119 #ifdef EVENT__HAVE_NETINET_IN6_H
120 #include <netinet/in6.h>
121 #endif
122 
123 #define EVDNS_LOG_DEBUG EVENT_LOG_DEBUG
124 #define EVDNS_LOG_WARN EVENT_LOG_WARN
125 #define EVDNS_LOG_MSG EVENT_LOG_MSG
126 
127 #ifndef HOST_NAME_MAX
128 #define HOST_NAME_MAX 255
129 #endif
130 
131 #include <stdio.h>
132 
133 #undef MIN
134 #define MIN(a,b) ((a)<(b)?(a):(b))
135 
136 #define ASSERT_VALID_REQUEST(req) \
137 	EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
138 
139 #define u64 ev_uint64_t
140 #define u32 ev_uint32_t
141 #define u16 ev_uint16_t
142 #define u8  ev_uint8_t
143 
144 /* maximum number of addresses from a single packet */
145 /* that we bother recording */
146 #define MAX_V4_ADDRS 32
147 #define MAX_V6_ADDRS 32
148 
149 
150 #define TYPE_A	       EVDNS_TYPE_A
151 #define TYPE_CNAME     5
152 #define TYPE_PTR       EVDNS_TYPE_PTR
153 #define TYPE_SOA       EVDNS_TYPE_SOA
154 #define TYPE_AAAA      EVDNS_TYPE_AAAA
155 
156 #define CLASS_INET     EVDNS_CLASS_INET
157 
158 /* Persistent handle.  We keep this separate from 'struct request' since we
159  * need some object to last for as long as an evdns_request is outstanding so
160  * that it can be canceled, whereas a search request can lead to multiple
161  * 'struct request' instances being created over its lifetime. */
162 struct evdns_request {
163 	struct request *current_req;
164 	struct evdns_base *base;
165 
166 	int pending_cb; /* Waiting for its callback to be invoked; not
167 			 * owned by event base any more. */
168 
169 	/* elements used by the searching code */
170 	int search_index;
171 	struct search_state *search_state;
172 	char *search_origname;	/* needs to be free()ed */
173 	int search_flags;
174 };
175 
176 struct request {
177 	u8 *request;  /* the dns packet data */
178 	u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
179 	unsigned int request_len;
180 	int reissue_count;
181 	int tx_count;  /* the number of times that this packet has been sent */
182 	void *user_pointer;  /* the pointer given to us for this request */
183 	evdns_callback_type user_callback;
184 	struct nameserver *ns;	/* the server which we last sent it */
185 
186 	/* these objects are kept in a circular list */
187 	/* XXX We could turn this into a CIRCLEQ. */
188 	struct request *next, *prev;
189 
190 	struct event timeout_event;
191 
192 	u16 trans_id;  /* the transaction id */
193 	unsigned request_appended :1;	/* true if the request pointer is data which follows this struct */
194 	unsigned transmit_me :1;  /* needs to be transmitted */
195 
196 	/* XXXX This is a horrible hack. */
197 	char **put_cname_in_ptr; /* store the cname here if we get one. */
198 
199 	struct evdns_base *base;
200 
201 	struct evdns_request *handle;
202 };
203 
204 struct reply {
205 	unsigned int type;
206 	unsigned int have_answer : 1;
207 	union {
208 		struct {
209 			u32 addrcount;
210 			u32 addresses[MAX_V4_ADDRS];
211 		} a;
212 		struct {
213 			u32 addrcount;
214 			struct in6_addr addresses[MAX_V6_ADDRS];
215 		} aaaa;
216 		struct {
217 			char name[HOST_NAME_MAX];
218 		} ptr;
219 	} data;
220 };
221 
222 struct nameserver {
223 	evutil_socket_t socket;	 /* a connected UDP socket */
224 	struct sockaddr_storage address;
225 	ev_socklen_t addrlen;
226 	int failed_times;  /* number of times which we have given this server a chance */
227 	int timedout;  /* number of times in a row a request has timed out */
228 	struct event event;
229 	/* these objects are kept in a circular list */
230 	struct nameserver *next, *prev;
231 	struct event timeout_event;  /* used to keep the timeout for */
232 				     /* when we next probe this server. */
233 				     /* Valid if state == 0 */
234 	/* Outstanding probe request for this nameserver, if any */
235 	struct evdns_request *probe_request;
236 	char state;  /* zero if we think that this server is down */
237 	char choked;  /* true if we have an EAGAIN from this server's socket */
238 	char write_waiting;  /* true if we are waiting for EV_WRITE events */
239 	struct evdns_base *base;
240 
241 	/* Number of currently inflight requests: used
242 	 * to track when we should add/del the event. */
243 	int requests_inflight;
244 };
245 
246 
247 /* Represents a local port where we're listening for DNS requests. Right now, */
248 /* only UDP is supported. */
249 struct evdns_server_port {
250 	evutil_socket_t socket; /* socket we use to read queries and write replies. */
251 	int refcnt; /* reference count. */
252 	char choked; /* Are we currently blocked from writing? */
253 	char closing; /* Are we trying to close this port, pending writes? */
254 	evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
255 	void *user_data; /* Opaque pointer passed to user_callback */
256 	struct event event; /* Read/write event */
257 	/* circular list of replies that we want to write. */
258 	struct server_request *pending_replies;
259 	struct event_base *event_base;
260 
261 #ifndef EVENT__DISABLE_THREAD_SUPPORT
262 	void *lock;
263 #endif
264 };
265 
266 /* Represents part of a reply being built.	(That is, a single RR.) */
267 struct server_reply_item {
268 	struct server_reply_item *next; /* next item in sequence. */
269 	char *name; /* name part of the RR */
270 	u16 type; /* The RR type */
271 	u16 class; /* The RR class (usually CLASS_INET) */
272 	u32 ttl; /* The RR TTL */
273 	char is_name; /* True iff data is a label */
274 	u16 datalen; /* Length of data; -1 if data is a label */
275 	void *data; /* The contents of the RR */
276 };
277 
278 /* Represents a request that we've received as a DNS server, and holds */
279 /* the components of the reply as we're constructing it. */
280 struct server_request {
281 	/* Pointers to the next and previous entries on the list of replies */
282 	/* that we're waiting to write.	 Only set if we have tried to respond */
283 	/* and gotten EAGAIN. */
284 	struct server_request *next_pending;
285 	struct server_request *prev_pending;
286 
287 	u16 trans_id; /* Transaction id. */
288 	struct evdns_server_port *port; /* Which port received this request on? */
289 	struct sockaddr_storage addr; /* Where to send the response */
290 	ev_socklen_t addrlen; /* length of addr */
291 
292 	int n_answer; /* how many answer RRs have been set? */
293 	int n_authority; /* how many authority RRs have been set? */
294 	int n_additional; /* how many additional RRs have been set? */
295 
296 	struct server_reply_item *answer; /* linked list of answer RRs */
297 	struct server_reply_item *authority; /* linked list of authority RRs */
298 	struct server_reply_item *additional; /* linked list of additional RRs */
299 
300 	/* Constructed response.  Only set once we're ready to send a reply. */
301 	/* Once this is set, the RR fields are cleared, and no more should be set. */
302 	char *response;
303 	size_t response_len;
304 
305 	/* Caller-visible fields: flags, questions. */
306 	struct evdns_server_request base;
307 };
308 
309 struct evdns_base {
310 	/* An array of n_req_heads circular lists for inflight requests.
311 	 * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
312 	 */
313 	struct request **req_heads;
314 	/* A circular list of requests that we're waiting to send, but haven't
315 	 * sent yet because there are too many requests inflight */
316 	struct request *req_waiting_head;
317 	/* A circular list of nameservers. */
318 	struct nameserver *server_head;
319 	int n_req_heads;
320 
321 	struct event_base *event_base;
322 
323 	/* The number of good nameservers that we have */
324 	int global_good_nameservers;
325 
326 	/* inflight requests are contained in the req_head list */
327 	/* and are actually going out across the network */
328 	int global_requests_inflight;
329 	/* requests which aren't inflight are in the waiting list */
330 	/* and are counted here */
331 	int global_requests_waiting;
332 
333 	int global_max_requests_inflight;
334 
335 	struct timeval global_timeout;	/* 5 seconds by default */
336 	int global_max_reissues;  /* a reissue occurs when we get some errors from the server */
337 	int global_max_retransmits;  /* number of times we'll retransmit a request which timed out */
338 	/* number of timeouts in a row before we consider this server to be down */
339 	int global_max_nameserver_timeout;
340 	/* true iff we will use the 0x20 hack to prevent poisoning attacks. */
341 	int global_randomize_case;
342 
343 	/* The first time that a nameserver fails, how long do we wait before
344 	 * probing to see if it has returned?  */
345 	struct timeval global_nameserver_probe_initial_timeout;
346 
347 	/** Port to bind to for outgoing DNS packets. */
348 	struct sockaddr_storage global_outgoing_address;
349 	/** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
350 	ev_socklen_t global_outgoing_addrlen;
351 
352 	struct timeval global_getaddrinfo_allow_skew;
353 
354 	int so_rcvbuf;
355 	int so_sndbuf;
356 
357 	int getaddrinfo_ipv4_timeouts;
358 	int getaddrinfo_ipv6_timeouts;
359 	int getaddrinfo_ipv4_answered;
360 	int getaddrinfo_ipv6_answered;
361 
362 	struct search_state *global_search_state;
363 
364 	TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
365 
366 #ifndef EVENT__DISABLE_THREAD_SUPPORT
367 	void *lock;
368 #endif
369 
370 	int disable_when_inactive;
371 };
372 
373 struct hosts_entry {
374 	TAILQ_ENTRY(hosts_entry) next;
375 	union {
376 		struct sockaddr sa;
377 		struct sockaddr_in sin;
378 		struct sockaddr_in6 sin6;
379 	} addr;
380 	int addrlen;
381 	char hostname[1];
382 };
383 
384 static struct evdns_base *current_base = NULL;
385 
386 struct evdns_base *
evdns_get_global_base(void)387 evdns_get_global_base(void)
388 {
389 	return current_base;
390 }
391 
392 /* Given a pointer to an evdns_server_request, get the corresponding */
393 /* server_request. */
394 #define TO_SERVER_REQUEST(base_ptr)					\
395 	((struct server_request*)					\
396 	  (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
397 
398 #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
399 
400 static struct nameserver *nameserver_pick(struct evdns_base *base);
401 static void evdns_request_insert(struct request *req, struct request **head);
402 static void evdns_request_remove(struct request *req, struct request **head);
403 static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
404 static int evdns_transmit(struct evdns_base *base);
405 static int evdns_request_transmit(struct request *req);
406 static void nameserver_send_probe(struct nameserver *const ns);
407 static void search_request_finished(struct evdns_request *const);
408 static int search_try_next(struct evdns_request *const req);
409 static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
410 static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
411 static u16 transaction_id_pick(struct evdns_base *base);
412 static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
413 static void request_submit(struct request *const req);
414 
415 static int server_request_free(struct server_request *req);
416 static void server_request_free_answers(struct server_request *req);
417 static void server_port_free(struct evdns_server_port *port);
418 static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
419 static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
420 static int evdns_base_set_option_impl(struct evdns_base *base,
421     const char *option, const char *val, int flags);
422 static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
423 static void evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg);
424 
425 static int strtoint(const char *const str);
426 
427 #ifdef EVENT__DISABLE_THREAD_SUPPORT
428 #define EVDNS_LOCK(base)  EVUTIL_NIL_STMT_
429 #define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
430 #define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
431 #else
432 #define EVDNS_LOCK(base)			\
433 	EVLOCK_LOCK((base)->lock, 0)
434 #define EVDNS_UNLOCK(base)			\
435 	EVLOCK_UNLOCK((base)->lock, 0)
436 #define ASSERT_LOCKED(base)			\
437 	EVLOCK_ASSERT_LOCKED((base)->lock)
438 #endif
439 
440 static evdns_debug_log_fn_type evdns_log_fn = NULL;
441 
442 void
evdns_set_log_fn(evdns_debug_log_fn_type fn)443 evdns_set_log_fn(evdns_debug_log_fn_type fn)
444 {
445 	evdns_log_fn = fn;
446 }
447 
448 #ifdef __GNUC__
449 #define EVDNS_LOG_CHECK	 __attribute__ ((format(printf, 2, 3)))
450 #else
451 #define EVDNS_LOG_CHECK
452 #endif
453 
454 static void evdns_log_(int severity, const char *fmt, ...) EVDNS_LOG_CHECK;
455 static void
evdns_log_(int severity,const char * fmt,...)456 evdns_log_(int severity, const char *fmt, ...)
457 {
458 	va_list args;
459 	va_start(args,fmt);
460 	if (evdns_log_fn) {
461 		char buf[512];
462 		int is_warn = (severity == EVDNS_LOG_WARN);
463 		evutil_vsnprintf(buf, sizeof(buf), fmt, args);
464 		evdns_log_fn(is_warn, buf);
465 	} else {
466 		event_logv_(severity, NULL, fmt, args);
467 	}
468 	va_end(args);
469 }
470 
471 #define log evdns_log_
472 
473 /* This walks the list of inflight requests to find the */
474 /* one with a matching transaction id. Returns NULL on */
475 /* failure */
476 static struct request *
request_find_from_trans_id(struct evdns_base * base,u16 trans_id)477 request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
478 	struct request *req = REQ_HEAD(base, trans_id);
479 	struct request *const started_at = req;
480 
481 	ASSERT_LOCKED(base);
482 
483 	if (req) {
484 		do {
485 			if (req->trans_id == trans_id) return req;
486 			req = req->next;
487 		} while (req != started_at);
488 	}
489 
490 	return NULL;
491 }
492 
493 /* a libevent callback function which is called when a nameserver */
494 /* has gone down and we want to test if it has came back to life yet */
495 static void
nameserver_prod_callback(evutil_socket_t fd,short events,void * arg)496 nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
497 	struct nameserver *const ns = (struct nameserver *) arg;
498 	(void)fd;
499 	(void)events;
500 
501 	EVDNS_LOCK(ns->base);
502 	nameserver_send_probe(ns);
503 	EVDNS_UNLOCK(ns->base);
504 }
505 
506 /* a libevent callback which is called when a nameserver probe (to see if */
507 /* it has come back to life) times out. We increment the count of failed_times */
508 /* and wait longer to send the next probe packet. */
509 static void
nameserver_probe_failed(struct nameserver * const ns)510 nameserver_probe_failed(struct nameserver *const ns) {
511 	struct timeval timeout;
512 	int i;
513 
514 	ASSERT_LOCKED(ns->base);
515 	(void) evtimer_del(&ns->timeout_event);
516 	if (ns->state == 1) {
517 		/* This can happen if the nameserver acts in a way which makes us mark */
518 		/* it as bad and then starts sending good replies. */
519 		return;
520 	}
521 
522 #define MAX_PROBE_TIMEOUT 3600
523 #define TIMEOUT_BACKOFF_FACTOR 3
524 
525 	memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
526 	    sizeof(struct timeval));
527 	for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
528 		timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
529 		timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
530 		if (timeout.tv_usec > 1000000) {
531 			timeout.tv_sec += timeout.tv_usec / 1000000;
532 			timeout.tv_usec %= 1000000;
533 		}
534 	}
535 	if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
536 		timeout.tv_sec = MAX_PROBE_TIMEOUT;
537 		timeout.tv_usec = 0;
538 	}
539 
540 	ns->failed_times++;
541 
542 	if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
543 		char addrbuf[128];
544 		log(EVDNS_LOG_WARN,
545 		    "Error from libevent when adding timer event for %s",
546 		    evutil_format_sockaddr_port_(
547 			    (struct sockaddr *)&ns->address,
548 			    addrbuf, sizeof(addrbuf)));
549 	}
550 }
551 
552 static void
request_swap_ns(struct request * req,struct nameserver * ns)553 request_swap_ns(struct request *req, struct nameserver *ns) {
554 	if (ns && req->ns != ns) {
555 		EVUTIL_ASSERT(req->ns->requests_inflight > 0);
556 		req->ns->requests_inflight--;
557 		ns->requests_inflight++;
558 
559 		req->ns = ns;
560 	}
561 }
562 
563 /* called when a nameserver has been deemed to have failed. For example, too */
564 /* many packets have timed out etc */
565 static void
nameserver_failed(struct nameserver * const ns,const char * msg)566 nameserver_failed(struct nameserver *const ns, const char *msg) {
567 	struct request *req, *started_at;
568 	struct evdns_base *base = ns->base;
569 	int i;
570 	char addrbuf[128];
571 
572 	ASSERT_LOCKED(base);
573 	/* if this nameserver has already been marked as failed */
574 	/* then don't do anything */
575 	if (!ns->state) return;
576 
577 	log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
578 	    evutil_format_sockaddr_port_(
579 		    (struct sockaddr *)&ns->address,
580 		    addrbuf, sizeof(addrbuf)),
581 	    msg);
582 
583 	base->global_good_nameservers--;
584 	EVUTIL_ASSERT(base->global_good_nameservers >= 0);
585 	if (base->global_good_nameservers == 0) {
586 		log(EVDNS_LOG_MSG, "All nameservers have failed");
587 	}
588 
589 	ns->state = 0;
590 	ns->failed_times = 1;
591 
592 	if (evtimer_add(&ns->timeout_event,
593 		&base->global_nameserver_probe_initial_timeout) < 0) {
594 		log(EVDNS_LOG_WARN,
595 		    "Error from libevent when adding timer event for %s",
596 		    evutil_format_sockaddr_port_(
597 			    (struct sockaddr *)&ns->address,
598 			    addrbuf, sizeof(addrbuf)));
599 		/* ???? Do more? */
600 	}
601 
602 	/* walk the list of inflight requests to see if any can be reassigned to */
603 	/* a different server. Requests in the waiting queue don't have a */
604 	/* nameserver assigned yet */
605 
606 	/* if we don't have *any* good nameservers then there's no point */
607 	/* trying to reassign requests to one */
608 	if (!base->global_good_nameservers) return;
609 
610 	for (i = 0; i < base->n_req_heads; ++i) {
611 		req = started_at = base->req_heads[i];
612 		if (req) {
613 			do {
614 				if (req->tx_count == 0 && req->ns == ns) {
615 					/* still waiting to go out, can be moved */
616 					/* to another server */
617 					request_swap_ns(req, nameserver_pick(base));
618 				}
619 				req = req->next;
620 			} while (req != started_at);
621 		}
622 	}
623 }
624 
625 static void
nameserver_up(struct nameserver * const ns)626 nameserver_up(struct nameserver *const ns)
627 {
628 	char addrbuf[128];
629 	ASSERT_LOCKED(ns->base);
630 	if (ns->state) return;
631 	log(EVDNS_LOG_MSG, "Nameserver %s is back up",
632 	    evutil_format_sockaddr_port_(
633 		    (struct sockaddr *)&ns->address,
634 		    addrbuf, sizeof(addrbuf)));
635 	evtimer_del(&ns->timeout_event);
636 	if (ns->probe_request) {
637 		evdns_cancel_request(ns->base, ns->probe_request);
638 		ns->probe_request = NULL;
639 	}
640 	ns->state = 1;
641 	ns->failed_times = 0;
642 	ns->timedout = 0;
643 	ns->base->global_good_nameservers++;
644 }
645 
646 static void
request_trans_id_set(struct request * const req,const u16 trans_id)647 request_trans_id_set(struct request *const req, const u16 trans_id) {
648 	req->trans_id = trans_id;
649 	*((u16 *) req->request) = htons(trans_id);
650 }
651 
652 /* Called to remove a request from a list and dealloc it. */
653 /* head is a pointer to the head of the list it should be */
654 /* removed from or NULL if the request isn't in a list. */
655 /* when free_handle is one, free the handle as well. */
656 static void
request_finished(struct request * const req,struct request ** head,int free_handle)657 request_finished(struct request *const req, struct request **head, int free_handle) {
658 	struct evdns_base *base = req->base;
659 	int was_inflight = (head != &base->req_waiting_head);
660 	EVDNS_LOCK(base);
661 	ASSERT_VALID_REQUEST(req);
662 
663 	if (head)
664 		evdns_request_remove(req, head);
665 
666 	log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
667 	if (was_inflight) {
668 		evtimer_del(&req->timeout_event);
669 		base->global_requests_inflight--;
670 		req->ns->requests_inflight--;
671 	} else {
672 		base->global_requests_waiting--;
673 	}
674 	/* it was initialized during request_new / evtimer_assign */
675 	event_debug_unassign(&req->timeout_event);
676 
677 	if (req->ns &&
678 	    req->ns->requests_inflight == 0 &&
679 	    req->base->disable_when_inactive) {
680 		event_del(&req->ns->event);
681 		evtimer_del(&req->ns->timeout_event);
682 	}
683 
684 	if (!req->request_appended) {
685 		/* need to free the request data on it's own */
686 		mm_free(req->request);
687 	} else {
688 		/* the request data is appended onto the header */
689 		/* so everything gets free()ed when we: */
690 	}
691 
692 	if (req->handle) {
693 		EVUTIL_ASSERT(req->handle->current_req == req);
694 
695 		if (free_handle) {
696 			search_request_finished(req->handle);
697 			req->handle->current_req = NULL;
698 			if (! req->handle->pending_cb) {
699 				/* If we're planning to run the callback,
700 				 * don't free the handle until later. */
701 				mm_free(req->handle);
702 			}
703 			req->handle = NULL; /* If we have a bug, let's crash
704 					     * early */
705 		} else {
706 			req->handle->current_req = NULL;
707 		}
708 	}
709 
710 	mm_free(req);
711 
712 	evdns_requests_pump_waiting_queue(base);
713 	EVDNS_UNLOCK(base);
714 }
715 
716 /* This is called when a server returns a funny error code. */
717 /* We try the request again with another server. */
718 /* */
719 /* return: */
720 /*   0 ok */
721 /*   1 failed/reissue is pointless */
722 static int
request_reissue(struct request * req)723 request_reissue(struct request *req) {
724 	const struct nameserver *const last_ns = req->ns;
725 	ASSERT_LOCKED(req->base);
726 	ASSERT_VALID_REQUEST(req);
727 	/* the last nameserver should have been marked as failing */
728 	/* by the caller of this function, therefore pick will try */
729 	/* not to return it */
730 	request_swap_ns(req, nameserver_pick(req->base));
731 	if (req->ns == last_ns) {
732 		/* ... but pick did return it */
733 		/* not a lot of point in trying again with the */
734 		/* same server */
735 		return 1;
736 	}
737 
738 	req->reissue_count++;
739 	req->tx_count = 0;
740 	req->transmit_me = 1;
741 
742 	return 0;
743 }
744 
745 /* this function looks for space on the inflight queue and promotes */
746 /* requests from the waiting queue if it can. */
747 /* */
748 /* TODO: */
749 /* add return code, see at nameserver_pick() and other functions. */
750 static void
evdns_requests_pump_waiting_queue(struct evdns_base * base)751 evdns_requests_pump_waiting_queue(struct evdns_base *base) {
752 	ASSERT_LOCKED(base);
753 	while (base->global_requests_inflight < base->global_max_requests_inflight &&
754 		   base->global_requests_waiting) {
755 		struct request *req;
756 
757 		EVUTIL_ASSERT(base->req_waiting_head);
758 		req = base->req_waiting_head;
759 
760 		req->ns = nameserver_pick(base);
761 		if (!req->ns)
762 			return;
763 
764 		/* move a request from the waiting queue to the inflight queue */
765 		req->ns->requests_inflight++;
766 
767 		evdns_request_remove(req, &base->req_waiting_head);
768 
769 		base->global_requests_waiting--;
770 		base->global_requests_inflight++;
771 
772 		request_trans_id_set(req, transaction_id_pick(base));
773 
774 		evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
775 		evdns_request_transmit(req);
776 		evdns_transmit(base);
777 	}
778 }
779 
780 /* TODO(nickm) document */
781 struct deferred_reply_callback {
782 	struct event_callback deferred;
783 	struct evdns_request *handle;
784 	u8 request_type;
785 	u8 have_reply;
786 	u32 ttl;
787 	u32 err;
788 	evdns_callback_type user_callback;
789 	struct reply reply;
790 };
791 
792 static void
reply_run_callback(struct event_callback * d,void * user_pointer)793 reply_run_callback(struct event_callback *d, void *user_pointer)
794 {
795 	struct deferred_reply_callback *cb =
796 	    EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
797 
798 	switch (cb->request_type) {
799 	case TYPE_A:
800 		if (cb->have_reply)
801 			cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
802 			    cb->reply.data.a.addrcount, cb->ttl,
803 			    cb->reply.data.a.addresses,
804 			    user_pointer);
805 		else
806 			cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
807 		break;
808 	case TYPE_PTR:
809 		if (cb->have_reply) {
810 			char *name = cb->reply.data.ptr.name;
811 			cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
812 			    &name, user_pointer);
813 		} else {
814 			cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
815 		}
816 		break;
817 	case TYPE_AAAA:
818 		if (cb->have_reply)
819 			cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
820 			    cb->reply.data.aaaa.addrcount, cb->ttl,
821 			    cb->reply.data.aaaa.addresses,
822 			    user_pointer);
823 		else
824 			cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
825 		break;
826 	default:
827 		EVUTIL_ASSERT(0);
828 	}
829 
830 	if (cb->handle && cb->handle->pending_cb) {
831 		mm_free(cb->handle);
832 	}
833 
834 	mm_free(cb);
835 }
836 
837 static void
reply_schedule_callback(struct request * const req,u32 ttl,u32 err,struct reply * reply)838 reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
839 {
840 	struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
841 
842 	if (!d) {
843 		event_warn("%s: Couldn't allocate space for deferred callback.",
844 		    __func__);
845 		return;
846 	}
847 
848 	ASSERT_LOCKED(req->base);
849 
850 	d->request_type = req->request_type;
851 	d->user_callback = req->user_callback;
852 	d->ttl = ttl;
853 	d->err = err;
854 	if (reply) {
855 		d->have_reply = 1;
856 		memcpy(&d->reply, reply, sizeof(struct reply));
857 	}
858 
859 	if (req->handle) {
860 		req->handle->pending_cb = 1;
861 		d->handle = req->handle;
862 	}
863 
864 	event_deferred_cb_init_(
865 	    &d->deferred,
866 	    event_get_priority(&req->timeout_event),
867 	    reply_run_callback,
868 	    req->user_pointer);
869 	event_deferred_cb_schedule_(
870 		req->base->event_base,
871 		&d->deferred);
872 }
873 
874 
875 #define _QR_MASK    0x8000U
876 #define _OP_MASK    0x7800U
877 #define _AA_MASK    0x0400U
878 #define _TC_MASK    0x0200U
879 #define _RD_MASK    0x0100U
880 #define _RA_MASK    0x0080U
881 #define _Z_MASK     0x0040U
882 #define _AD_MASK    0x0020U
883 #define _CD_MASK    0x0010U
884 #define _RCODE_MASK 0x000fU
885 #define _Z_MASK_DEPRECATED 0x0070U
886 
887 /* this processes a parsed reply packet */
888 static void
reply_handle(struct request * const req,u16 flags,u32 ttl,struct reply * reply)889 reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
890 	int error;
891 	char addrbuf[128];
892 	static const int error_codes[] = {
893 		DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
894 		DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
895 	};
896 
897 	ASSERT_LOCKED(req->base);
898 	ASSERT_VALID_REQUEST(req);
899 
900 	if (flags & (_RCODE_MASK | _TC_MASK) || !reply || !reply->have_answer) {
901 		/* there was an error */
902 		if (flags & _TC_MASK) {
903 			error = DNS_ERR_TRUNCATED;
904 		} else if (flags & _RCODE_MASK) {
905 			u16 error_code = (flags & _RCODE_MASK) - 1;
906 			if (error_code > 4) {
907 				error = DNS_ERR_UNKNOWN;
908 			} else {
909 				error = error_codes[error_code];
910 			}
911 		} else if (reply && !reply->have_answer) {
912 			error = DNS_ERR_NODATA;
913 		} else {
914 			error = DNS_ERR_UNKNOWN;
915 		}
916 
917 		switch (error) {
918 		case DNS_ERR_NOTIMPL:
919 		case DNS_ERR_REFUSED:
920 			/* we regard these errors as marking a bad nameserver */
921 			if (req->reissue_count < req->base->global_max_reissues) {
922 				char msg[64];
923 				evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
924 					 error, evdns_err_to_string(error));
925 				nameserver_failed(req->ns, msg);
926 				if (!request_reissue(req)) return;
927 			}
928 			break;
929 		case DNS_ERR_SERVERFAILED:
930 			/* rcode 2 (servfailed) sometimes means "we
931 			 * are broken" and sometimes (with some binds)
932 			 * means "that request was very confusing."
933 			 * Treat this as a timeout, not a failure.
934 			 */
935 			log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
936 				"at %s; will allow the request to time out.",
937 			    evutil_format_sockaddr_port_(
938 				    (struct sockaddr *)&req->ns->address,
939 				    addrbuf, sizeof(addrbuf)));
940 			/* Call the timeout function */
941 			evdns_request_timeout_callback(0, 0, req);
942 			return;
943 		default:
944 			/* we got a good reply from the nameserver: it is up. */
945 			if (req->handle == req->ns->probe_request) {
946 				/* Avoid double-free */
947 				req->ns->probe_request = NULL;
948 			}
949 
950 			nameserver_up(req->ns);
951 		}
952 
953 		if (req->handle->search_state &&
954 		    req->request_type != TYPE_PTR) {
955 			/* if we have a list of domains to search in,
956 			 * try the next one */
957 			if (!search_try_next(req->handle)) {
958 				/* a new request was issued so this
959 				 * request is finished and */
960 				/* the user callback will be made when
961 				 * that request (or a */
962 				/* child of it) finishes. */
963 				return;
964 			}
965 		}
966 
967 		/* all else failed. Pass the failure up */
968 		reply_schedule_callback(req, ttl, error, NULL);
969 		request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
970 	} else {
971 		/* all ok, tell the user */
972 		reply_schedule_callback(req, ttl, 0, reply);
973 		if (req->handle == req->ns->probe_request)
974 			req->ns->probe_request = NULL; /* Avoid double-free */
975 		nameserver_up(req->ns);
976 		request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
977 	}
978 }
979 
980 static int
name_parse(u8 * packet,int length,int * idx,char * name_out,int name_out_len)981 name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
982 	int name_end = -1;
983 	int j = *idx;
984 	int ptr_count = 0;
985 #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
986 #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
987 #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
988 
989 	char *cp = name_out;
990 	const char *const end = name_out + name_out_len;
991 
992 	/* Normally, names are a series of length prefixed strings terminated */
993 	/* with a length of 0 (the lengths are u8's < 63). */
994 	/* However, the length can start with a pair of 1 bits and that */
995 	/* means that the next 14 bits are a pointer within the current */
996 	/* packet. */
997 
998 	for (;;) {
999 		u8 label_len;
1000 		GET8(label_len);
1001 		if (!label_len) break;
1002 		if (label_len & 0xc0) {
1003 			u8 ptr_low;
1004 			GET8(ptr_low);
1005 			if (name_end < 0) name_end = j;
1006 			j = (((int)label_len & 0x3f) << 8) + ptr_low;
1007 			/* Make sure that the target offset is in-bounds. */
1008 			if (j < 0 || j >= length) return -1;
1009 			/* If we've jumped more times than there are characters in the
1010 			 * message, we must have a loop. */
1011 			if (++ptr_count > length) return -1;
1012 			continue;
1013 		}
1014 		if (label_len > 63) return -1;
1015 		if (cp != name_out) {
1016 			if (cp + 1 >= end) return -1;
1017 			*cp++ = '.';
1018 		}
1019 		if (cp + label_len >= end) return -1;
1020 		if (j + label_len > length) return -1;
1021 		memcpy(cp, packet + j, label_len);
1022 		cp += label_len;
1023 		j += label_len;
1024 	}
1025 	if (cp >= end) return -1;
1026 	*cp = '\0';
1027 	if (name_end < 0)
1028 		*idx = j;
1029 	else
1030 		*idx = name_end;
1031 	return 0;
1032  err:
1033 	return -1;
1034 }
1035 
1036 /* parses a raw request from a nameserver */
1037 static int
reply_parse(struct evdns_base * base,u8 * packet,int length)1038 reply_parse(struct evdns_base *base, u8 *packet, int length) {
1039 	int j = 0, k = 0;  /* index into packet */
1040 	u16 t_;	 /* used by the macros */
1041 	u32 t32_;  /* used by the macros */
1042 	char tmp_name[256], cmp_name[256]; /* used by the macros */
1043 	int name_matches = 0;
1044 
1045 	u16 trans_id, questions, answers, authority, additional, datalength;
1046 	u16 flags = 0;
1047 	u32 ttl, ttl_r = 0xffffffff;
1048 	struct reply reply;
1049 	struct request *req = NULL;
1050 	unsigned int i;
1051 
1052 	ASSERT_LOCKED(base);
1053 
1054 	GET16(trans_id);
1055 	GET16(flags);
1056 	GET16(questions);
1057 	GET16(answers);
1058 	GET16(authority);
1059 	GET16(additional);
1060 	(void) authority; /* suppress "unused variable" warnings. */
1061 	(void) additional; /* suppress "unused variable" warnings. */
1062 
1063 	req = request_find_from_trans_id(base, trans_id);
1064 	if (!req) return -1;
1065 	EVUTIL_ASSERT(req->base == base);
1066 
1067 	memset(&reply, 0, sizeof(reply));
1068 
1069 	/* If it's not an answer, it doesn't correspond to any request. */
1070 	if (!(flags & _QR_MASK)) return -1;  /* must be an answer */
1071 	if ((flags & (_RCODE_MASK|_TC_MASK)) && (flags & (_RCODE_MASK|_TC_MASK)) != DNS_ERR_NOTEXIST) {
1072 		/* there was an error and it's not NXDOMAIN */
1073 		goto err;
1074 	}
1075 	/* if (!answers) return; */  /* must have an answer of some form */
1076 
1077 	/* This macro skips a name in the DNS reply. */
1078 #define SKIP_NAME						\
1079 	do { tmp_name[0] = '\0';				\
1080 		if (name_parse(packet, length, &j, tmp_name,	\
1081 			sizeof(tmp_name))<0)			\
1082 			goto err;				\
1083 	} while (0)
1084 
1085 	reply.type = req->request_type;
1086 
1087 	/* skip over each question in the reply */
1088 	for (i = 0; i < questions; ++i) {
1089 		/* the question looks like
1090 		 *   <label:name><u16:type><u16:class>
1091 		 */
1092 		tmp_name[0] = '\0';
1093 		cmp_name[0] = '\0';
1094 		k = j;
1095 		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name)) < 0)
1096 			goto err;
1097 		if (name_parse(req->request, req->request_len, &k,
1098 			cmp_name, sizeof(cmp_name))<0)
1099 			goto err;
1100 		if (!base->global_randomize_case) {
1101 			if (strcmp(tmp_name, cmp_name) == 0)
1102 				name_matches = 1;
1103 		} else {
1104 			if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0)
1105 				name_matches = 1;
1106 		}
1107 
1108 		j += 4;
1109 		if (j > length)
1110 			goto err;
1111 	}
1112 
1113 	if (!name_matches)
1114 		goto err;
1115 
1116 	/* now we have the answer section which looks like
1117 	 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
1118 	 */
1119 
1120 	for (i = 0; i < answers; ++i) {
1121 		u16 type, class;
1122 
1123 		SKIP_NAME;
1124 		GET16(type);
1125 		GET16(class);
1126 		GET32(ttl);
1127 		GET16(datalength);
1128 
1129 		if (type == TYPE_A && class == CLASS_INET) {
1130 			int addrcount, addrtocopy;
1131 			if (req->request_type != TYPE_A) {
1132 				j += datalength; continue;
1133 			}
1134 			if ((datalength & 3) != 0) /* not an even number of As. */
1135 			    goto err;
1136 			addrcount = datalength >> 2;
1137 			addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
1138 
1139 			ttl_r = MIN(ttl_r, ttl);
1140 			/* we only bother with the first four addresses. */
1141 			if (j + 4*addrtocopy > length) goto err;
1142 			memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
1143 				   packet + j, 4*addrtocopy);
1144 			j += 4*addrtocopy;
1145 			reply.data.a.addrcount += addrtocopy;
1146 			reply.have_answer = 1;
1147 			if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
1148 		} else if (type == TYPE_PTR && class == CLASS_INET) {
1149 			if (req->request_type != TYPE_PTR) {
1150 				j += datalength; continue;
1151 			}
1152 			if (name_parse(packet, length, &j, reply.data.ptr.name,
1153 						   sizeof(reply.data.ptr.name))<0)
1154 				goto err;
1155 			ttl_r = MIN(ttl_r, ttl);
1156 			reply.have_answer = 1;
1157 			break;
1158 		} else if (type == TYPE_CNAME) {
1159 			char cname[HOST_NAME_MAX];
1160 			if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
1161 				j += datalength; continue;
1162 			}
1163 			if (name_parse(packet, length, &j, cname,
1164 				sizeof(cname))<0)
1165 				goto err;
1166 			*req->put_cname_in_ptr = mm_strdup(cname);
1167 		} else if (type == TYPE_AAAA && class == CLASS_INET) {
1168 			int addrcount, addrtocopy;
1169 			if (req->request_type != TYPE_AAAA) {
1170 				j += datalength; continue;
1171 			}
1172 			if ((datalength & 15) != 0) /* not an even number of AAAAs. */
1173 				goto err;
1174 			addrcount = datalength >> 4;  /* each address is 16 bytes long */
1175 			addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
1176 			ttl_r = MIN(ttl_r, ttl);
1177 
1178 			/* we only bother with the first four addresses. */
1179 			if (j + 16*addrtocopy > length) goto err;
1180 			memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
1181 				   packet + j, 16*addrtocopy);
1182 			reply.data.aaaa.addrcount += addrtocopy;
1183 			j += 16*addrtocopy;
1184 			reply.have_answer = 1;
1185 			if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
1186 		} else {
1187 			/* skip over any other type of resource */
1188 			j += datalength;
1189 		}
1190 	}
1191 
1192 	if (!reply.have_answer) {
1193 		for (i = 0; i < authority; ++i) {
1194 			u16 type, class;
1195 			SKIP_NAME;
1196 			GET16(type);
1197 			GET16(class);
1198 			GET32(ttl);
1199 			GET16(datalength);
1200 			if (type == TYPE_SOA && class == CLASS_INET) {
1201 				u32 serial, refresh, retry, expire, minimum;
1202 				SKIP_NAME;
1203 				SKIP_NAME;
1204 				GET32(serial);
1205 				GET32(refresh);
1206 				GET32(retry);
1207 				GET32(expire);
1208 				GET32(minimum);
1209 				(void)expire;
1210 				(void)retry;
1211 				(void)refresh;
1212 				(void)serial;
1213 				ttl_r = MIN(ttl_r, ttl);
1214 				ttl_r = MIN(ttl_r, minimum);
1215 			} else {
1216 				/* skip over any other type of resource */
1217 				j += datalength;
1218 			}
1219 		}
1220 	}
1221 
1222 	if (ttl_r == 0xffffffff)
1223 		ttl_r = 0;
1224 
1225 	reply_handle(req, flags, ttl_r, &reply);
1226 	return 0;
1227  err:
1228 	if (req)
1229 		reply_handle(req, flags, 0, NULL);
1230 	return -1;
1231 }
1232 
1233 /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
1234 /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
1235 /* callback. */
1236 static int
request_parse(u8 * packet,int length,struct evdns_server_port * port,struct sockaddr * addr,ev_socklen_t addrlen)1237 request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
1238 {
1239 	int j = 0;	/* index into packet */
1240 	u16 t_;	 /* used by the macros */
1241 	char tmp_name[256]; /* used by the macros */
1242 
1243 	int i;
1244 	u16 trans_id, flags, questions, answers, authority, additional;
1245 	struct server_request *server_req = NULL;
1246 
1247 	ASSERT_LOCKED(port);
1248 
1249 	/* Get the header fields */
1250 	GET16(trans_id);
1251 	GET16(flags);
1252 	GET16(questions);
1253 	GET16(answers);
1254 	GET16(authority);
1255 	GET16(additional);
1256 	(void)answers;
1257 	(void)additional;
1258 	(void)authority;
1259 
1260 	if (flags & _QR_MASK) return -1; /* Must not be an answer. */
1261 	flags &= (_RD_MASK|_CD_MASK); /* Only RD and CD get preserved. */
1262 
1263 	server_req = mm_malloc(sizeof(struct server_request));
1264 	if (server_req == NULL) return -1;
1265 	memset(server_req, 0, sizeof(struct server_request));
1266 
1267 	server_req->trans_id = trans_id;
1268 	memcpy(&server_req->addr, addr, addrlen);
1269 	server_req->addrlen = addrlen;
1270 
1271 	server_req->base.flags = flags;
1272 	server_req->base.nquestions = 0;
1273 	server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
1274 	if (server_req->base.questions == NULL)
1275 		goto err;
1276 
1277 	for (i = 0; i < questions; ++i) {
1278 		u16 type, class;
1279 		struct evdns_server_question *q;
1280 		int namelen;
1281 		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
1282 			goto err;
1283 		GET16(type);
1284 		GET16(class);
1285 		namelen = (int)strlen(tmp_name);
1286 		q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
1287 		if (!q)
1288 			goto err;
1289 		q->type = type;
1290 		q->dns_question_class = class;
1291 		memcpy(q->name, tmp_name, namelen+1);
1292 		server_req->base.questions[server_req->base.nquestions++] = q;
1293 	}
1294 
1295 	/* Ignore answers, authority, and additional. */
1296 
1297 	server_req->port = port;
1298 	port->refcnt++;
1299 
1300 	/* Only standard queries are supported. */
1301 	if (flags & _OP_MASK) {
1302 		evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
1303 		return -1;
1304 	}
1305 
1306 	port->user_callback(&(server_req->base), port->user_data);
1307 
1308 	return 0;
1309 err:
1310 	if (server_req->base.questions) {
1311 		for (i = 0; i < server_req->base.nquestions; ++i)
1312 			mm_free(server_req->base.questions[i]);
1313 		mm_free(server_req->base.questions);
1314 	}
1315 	mm_free(server_req);
1316 	return -1;
1317 
1318 #undef SKIP_NAME
1319 #undef GET32
1320 #undef GET16
1321 #undef GET8
1322 }
1323 
1324 
1325 void
evdns_set_transaction_id_fn(ev_uint16_t (* fn)(void))1326 evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
1327 {
1328 }
1329 
1330 void
evdns_set_random_bytes_fn(void (* fn)(char *,size_t))1331 evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
1332 {
1333 }
1334 
1335 /* Try to choose a strong transaction id which isn't already in flight */
1336 static u16
transaction_id_pick(struct evdns_base * base)1337 transaction_id_pick(struct evdns_base *base) {
1338 	ASSERT_LOCKED(base);
1339 	for (;;) {
1340 		u16 trans_id;
1341 		evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
1342 
1343 		if (trans_id == 0xffff) continue;
1344 		/* now check to see if that id is already inflight */
1345 		if (request_find_from_trans_id(base, trans_id) == NULL)
1346 			return trans_id;
1347 	}
1348 }
1349 
1350 /* choose a namesever to use. This function will try to ignore */
1351 /* nameservers which we think are down and load balance across the rest */
1352 /* by updating the server_head global each time. */
1353 static struct nameserver *
nameserver_pick(struct evdns_base * base)1354 nameserver_pick(struct evdns_base *base) {
1355 	struct nameserver *started_at = base->server_head, *picked;
1356 	ASSERT_LOCKED(base);
1357 	if (!base->server_head) return NULL;
1358 
1359 	/* if we don't have any good nameservers then there's no */
1360 	/* point in trying to find one. */
1361 	if (!base->global_good_nameservers) {
1362 		base->server_head = base->server_head->next;
1363 		return base->server_head;
1364 	}
1365 
1366 	/* remember that nameservers are in a circular list */
1367 	for (;;) {
1368 		if (base->server_head->state) {
1369 			/* we think this server is currently good */
1370 			picked = base->server_head;
1371 			base->server_head = base->server_head->next;
1372 			return picked;
1373 		}
1374 
1375 		base->server_head = base->server_head->next;
1376 		if (base->server_head == started_at) {
1377 			/* all the nameservers seem to be down */
1378 			/* so we just return this one and hope for the */
1379 			/* best */
1380 			EVUTIL_ASSERT(base->global_good_nameservers == 0);
1381 			picked = base->server_head;
1382 			base->server_head = base->server_head->next;
1383 			return picked;
1384 		}
1385 	}
1386 }
1387 
1388 /* this is called when a namesever socket is ready for reading */
1389 static void
nameserver_read(struct nameserver * ns)1390 nameserver_read(struct nameserver *ns) {
1391 	struct sockaddr_storage ss;
1392 	ev_socklen_t addrlen = sizeof(ss);
1393 	u8 packet[1500];
1394 	char addrbuf[128];
1395 	ASSERT_LOCKED(ns->base);
1396 
1397 	for (;;) {
1398 		const int r = recvfrom(ns->socket, (void*)packet,
1399 		    sizeof(packet), 0,
1400 		    (struct sockaddr*)&ss, &addrlen);
1401 		if (r < 0) {
1402 			int err = evutil_socket_geterror(ns->socket);
1403 			if (EVUTIL_ERR_RW_RETRIABLE(err))
1404 				return;
1405 			nameserver_failed(ns,
1406 			    evutil_socket_error_to_string(err));
1407 			return;
1408 		}
1409 		if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
1410 			(struct sockaddr*)&ns->address, 0)) {
1411 			log(EVDNS_LOG_WARN, "Address mismatch on received "
1412 			    "DNS packet.  Apparent source was %s",
1413 			    evutil_format_sockaddr_port_(
1414 				    (struct sockaddr *)&ss,
1415 				    addrbuf, sizeof(addrbuf)));
1416 			return;
1417 		}
1418 
1419 		ns->timedout = 0;
1420 		reply_parse(ns->base, packet, r);
1421 	}
1422 }
1423 
1424 /* Read a packet from a DNS client on a server port s, parse it, and */
1425 /* act accordingly. */
1426 static void
server_port_read(struct evdns_server_port * s)1427 server_port_read(struct evdns_server_port *s) {
1428 	u8 packet[1500];
1429 	struct sockaddr_storage addr;
1430 	ev_socklen_t addrlen;
1431 	int r;
1432 	ASSERT_LOCKED(s);
1433 
1434 	for (;;) {
1435 		addrlen = sizeof(struct sockaddr_storage);
1436 		r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
1437 					 (struct sockaddr*) &addr, &addrlen);
1438 		if (r < 0) {
1439 			int err = evutil_socket_geterror(s->socket);
1440 			if (EVUTIL_ERR_RW_RETRIABLE(err))
1441 				return;
1442 			log(EVDNS_LOG_WARN,
1443 			    "Error %s (%d) while reading request.",
1444 			    evutil_socket_error_to_string(err), err);
1445 			return;
1446 		}
1447 		request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
1448 	}
1449 }
1450 
1451 /* Try to write all pending replies on a given DNS server port. */
1452 static void
server_port_flush(struct evdns_server_port * port)1453 server_port_flush(struct evdns_server_port *port)
1454 {
1455 	struct server_request *req = port->pending_replies;
1456 	ASSERT_LOCKED(port);
1457 	while (req) {
1458 		int r = sendto(port->socket, req->response, (int)req->response_len, 0,
1459 			   (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
1460 		if (r < 0) {
1461 			int err = evutil_socket_geterror(port->socket);
1462 			if (EVUTIL_ERR_RW_RETRIABLE(err))
1463 				return;
1464 			log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
1465 		}
1466 		if (server_request_free(req)) {
1467 			/* we released the last reference to req->port. */
1468 			return;
1469 		} else {
1470 			EVUTIL_ASSERT(req != port->pending_replies);
1471 			req = port->pending_replies;
1472 		}
1473 	}
1474 
1475 	/* We have no more pending requests; stop listening for 'writeable' events. */
1476 	(void) event_del(&port->event);
1477 	event_assign(&port->event, port->event_base,
1478 				 port->socket, EV_READ | EV_PERSIST,
1479 				 server_port_ready_callback, port);
1480 
1481 	if (event_add(&port->event, NULL) < 0) {
1482 		log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
1483 		/* ???? Do more? */
1484 	}
1485 }
1486 
1487 /* set if we are waiting for the ability to write to this server. */
1488 /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
1489 /* we stop these events. */
1490 static void
nameserver_write_waiting(struct nameserver * ns,char waiting)1491 nameserver_write_waiting(struct nameserver *ns, char waiting) {
1492 	ASSERT_LOCKED(ns->base);
1493 	if (ns->write_waiting == waiting) return;
1494 
1495 	ns->write_waiting = waiting;
1496 	(void) event_del(&ns->event);
1497 	event_assign(&ns->event, ns->base->event_base,
1498 	    ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1499 	    nameserver_ready_callback, ns);
1500 	if (event_add(&ns->event, NULL) < 0) {
1501 		char addrbuf[128];
1502 		log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
1503 		    evutil_format_sockaddr_port_(
1504 			    (struct sockaddr *)&ns->address,
1505 			    addrbuf, sizeof(addrbuf)));
1506 		/* ???? Do more? */
1507 	}
1508 }
1509 
1510 /* a callback function. Called by libevent when the kernel says that */
1511 /* a nameserver socket is ready for writing or reading */
1512 static void
nameserver_ready_callback(evutil_socket_t fd,short events,void * arg)1513 nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
1514 	struct nameserver *ns = (struct nameserver *) arg;
1515 	(void)fd;
1516 
1517 	EVDNS_LOCK(ns->base);
1518 	if (events & EV_WRITE) {
1519 		ns->choked = 0;
1520 		if (!evdns_transmit(ns->base)) {
1521 			nameserver_write_waiting(ns, 0);
1522 		}
1523 	}
1524 	if (events & EV_READ) {
1525 		nameserver_read(ns);
1526 	}
1527 	EVDNS_UNLOCK(ns->base);
1528 }
1529 
1530 /* a callback function. Called by libevent when the kernel says that */
1531 /* a server socket is ready for writing or reading. */
1532 static void
server_port_ready_callback(evutil_socket_t fd,short events,void * arg)1533 server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
1534 	struct evdns_server_port *port = (struct evdns_server_port *) arg;
1535 	(void) fd;
1536 
1537 	EVDNS_LOCK(port);
1538 	if (events & EV_WRITE) {
1539 		port->choked = 0;
1540 		server_port_flush(port);
1541 	}
1542 	if (events & EV_READ) {
1543 		server_port_read(port);
1544 	}
1545 	EVDNS_UNLOCK(port);
1546 }
1547 
1548 /* This is an inefficient representation; only use it via the dnslabel_table_*
1549  * functions, so that is can be safely replaced with something smarter later. */
1550 #define MAX_LABELS 128
1551 /* Structures used to implement name compression */
1552 struct dnslabel_entry { char *v; off_t pos; };
1553 struct dnslabel_table {
1554 	int n_labels; /* number of current entries */
1555 	/* map from name to position in message */
1556 	struct dnslabel_entry labels[MAX_LABELS];
1557 };
1558 
1559 /* Initialize dnslabel_table. */
1560 static void
dnslabel_table_init(struct dnslabel_table * table)1561 dnslabel_table_init(struct dnslabel_table *table)
1562 {
1563 	table->n_labels = 0;
1564 }
1565 
1566 /* Free all storage held by table, but not the table itself. */
1567 static void
dnslabel_clear(struct dnslabel_table * table)1568 dnslabel_clear(struct dnslabel_table *table)
1569 {
1570 	int i;
1571 	for (i = 0; i < table->n_labels; ++i)
1572 		mm_free(table->labels[i].v);
1573 	table->n_labels = 0;
1574 }
1575 
1576 /* return the position of the label in the current message, or -1 if the label */
1577 /* hasn't been used yet. */
1578 static int
dnslabel_table_get_pos(const struct dnslabel_table * table,const char * label)1579 dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
1580 {
1581 	int i;
1582 	for (i = 0; i < table->n_labels; ++i) {
1583 		if (!strcmp(label, table->labels[i].v))
1584 			return table->labels[i].pos;
1585 	}
1586 	return -1;
1587 }
1588 
1589 /* remember that we've used the label at position pos */
1590 static int
dnslabel_table_add(struct dnslabel_table * table,const char * label,off_t pos)1591 dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
1592 {
1593 	char *v;
1594 	int p;
1595 	if (table->n_labels == MAX_LABELS)
1596 		return (-1);
1597 	v = mm_strdup(label);
1598 	if (v == NULL)
1599 		return (-1);
1600 	p = table->n_labels++;
1601 	table->labels[p].v = v;
1602 	table->labels[p].pos = pos;
1603 
1604 	return (0);
1605 }
1606 
1607 /* Converts a string to a length-prefixed set of DNS labels, starting */
1608 /* at buf[j]. name and buf must not overlap. name_len should be the length */
1609 /* of name.	 table is optional, and is used for compression. */
1610 /* */
1611 /* Input: abc.def */
1612 /* Output: <3>abc<3>def<0> */
1613 /* */
1614 /* Returns the first index after the encoded name, or negative on error. */
1615 /*	 -1	 label was > 63 bytes */
1616 /*	 -2	 name too long to fit in buffer. */
1617 /* */
1618 static off_t
dnsname_to_labels(u8 * const buf,size_t buf_len,off_t j,const char * name,const size_t name_len,struct dnslabel_table * table)1619 dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
1620 				  const char *name, const size_t name_len,
1621 				  struct dnslabel_table *table) {
1622 	const char *end = name + name_len;
1623 	int ref = 0;
1624 	u16 t_;
1625 
1626 #define APPEND16(x) do {						\
1627 		if (j + 2 > (off_t)buf_len)				\
1628 			goto overflow;					\
1629 		t_ = htons(x);						\
1630 		memcpy(buf + j, &t_, 2);				\
1631 		j += 2;							\
1632 	} while (0)
1633 #define APPEND32(x) do {						\
1634 		if (j + 4 > (off_t)buf_len)				\
1635 			goto overflow;					\
1636 		t32_ = htonl(x);					\
1637 		memcpy(buf + j, &t32_, 4);				\
1638 		j += 4;							\
1639 	} while (0)
1640 
1641 	if (name_len > 255) return -2;
1642 
1643 	for (;;) {
1644 		const char *const start = name;
1645 		if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1646 			APPEND16(ref | 0xc000);
1647 			return j;
1648 		}
1649 		name = strchr(name, '.');
1650 		if (!name) {
1651 			const size_t label_len = end - start;
1652 			if (label_len > 63) return -1;
1653 			if ((size_t)(j+label_len+1) > buf_len) return -2;
1654 			if (table) dnslabel_table_add(table, start, j);
1655 			buf[j++] = (ev_uint8_t)label_len;
1656 
1657 			memcpy(buf + j, start, label_len);
1658 			j += (int) label_len;
1659 			break;
1660 		} else {
1661 			/* append length of the label. */
1662 			const size_t label_len = name - start;
1663 			if (label_len > 63) return -1;
1664 			if ((size_t)(j+label_len+1) > buf_len) return -2;
1665 			if (table) dnslabel_table_add(table, start, j);
1666 			buf[j++] = (ev_uint8_t)label_len;
1667 
1668 			memcpy(buf + j, start, label_len);
1669 			j += (int) label_len;
1670 			/* hop over the '.' */
1671 			name++;
1672 		}
1673 	}
1674 
1675 	/* the labels must be terminated by a 0. */
1676 	/* It's possible that the name ended in a . */
1677 	/* in which case the zero is already there */
1678 	if (!j || buf[j-1]) buf[j++] = 0;
1679 	return j;
1680  overflow:
1681 	return (-2);
1682 }
1683 
1684 /* Finds the length of a dns request for a DNS name of the given */
1685 /* length. The actual request may be smaller than the value returned */
1686 /* here */
1687 static size_t
evdns_request_len(const size_t name_len)1688 evdns_request_len(const size_t name_len) {
1689 	return 96 + /* length of the DNS standard header */
1690 		name_len + 2 +
1691 		4;  /* space for the resource type */
1692 }
1693 
1694 /* build a dns request packet into buf. buf should be at least as long */
1695 /* as evdns_request_len told you it should be. */
1696 /* */
1697 /* Returns the amount of space used. Negative on error. */
1698 static int
evdns_request_data_build(const char * const name,const size_t name_len,const u16 trans_id,const u16 type,const u16 class,u8 * const buf,size_t buf_len)1699 evdns_request_data_build(const char *const name, const size_t name_len,
1700     const u16 trans_id, const u16 type, const u16 class,
1701     u8 *const buf, size_t buf_len) {
1702 	off_t j = 0;  /* current offset into buf */
1703 	u16 t_;	 /* used by the macros */
1704 
1705 	APPEND16(trans_id);
1706 	APPEND16(0x0100);  /* standard query, recusion needed */
1707 	APPEND16(1);  /* one question */
1708 	APPEND16(0);  /* no answers */
1709 	APPEND16(0);  /* no authority */
1710 	APPEND16(0);  /* no additional */
1711 
1712 	j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1713 	if (j < 0) {
1714 		return (int)j;
1715 	}
1716 
1717 	APPEND16(type);
1718 	APPEND16(class);
1719 
1720 	return (int)j;
1721  overflow:
1722 	return (-1);
1723 }
1724 
1725 /* exported function */
1726 struct evdns_server_port *
evdns_add_server_port_with_base(struct event_base * base,evutil_socket_t socket,int flags,evdns_request_callback_fn_type cb,void * user_data)1727 evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
1728 {
1729 	struct evdns_server_port *port;
1730 	if (flags)
1731 		return NULL; /* flags not yet implemented */
1732 	if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
1733 		return NULL;
1734 	memset(port, 0, sizeof(struct evdns_server_port));
1735 
1736 
1737 	port->socket = socket;
1738 	port->refcnt = 1;
1739 	port->choked = 0;
1740 	port->closing = 0;
1741 	port->user_callback = cb;
1742 	port->user_data = user_data;
1743 	port->pending_replies = NULL;
1744 	port->event_base = base;
1745 
1746 	event_assign(&port->event, port->event_base,
1747 				 port->socket, EV_READ | EV_PERSIST,
1748 				 server_port_ready_callback, port);
1749 	if (event_add(&port->event, NULL) < 0) {
1750 		mm_free(port);
1751 		return NULL;
1752 	}
1753 	EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
1754 	return port;
1755 }
1756 
1757 struct evdns_server_port *
evdns_add_server_port(evutil_socket_t socket,int flags,evdns_request_callback_fn_type cb,void * user_data)1758 evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
1759 {
1760 	return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
1761 }
1762 
1763 /* exported function */
1764 void
evdns_close_server_port(struct evdns_server_port * port)1765 evdns_close_server_port(struct evdns_server_port *port)
1766 {
1767 	EVDNS_LOCK(port);
1768 	if (--port->refcnt == 0) {
1769 		EVDNS_UNLOCK(port);
1770 		server_port_free(port);
1771 	} else {
1772 		port->closing = 1;
1773 		EVDNS_UNLOCK(port);
1774 	}
1775 }
1776 
1777 /* exported function */
1778 int
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)1779 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)
1780 {
1781 	struct server_request *req = TO_SERVER_REQUEST(req_);
1782 	struct server_reply_item **itemp, *item;
1783 	int *countp;
1784 	int result = -1;
1785 
1786 	EVDNS_LOCK(req->port);
1787 	if (req->response) /* have we already answered? */
1788 		goto done;
1789 
1790 	switch (section) {
1791 	case EVDNS_ANSWER_SECTION:
1792 		itemp = &req->answer;
1793 		countp = &req->n_answer;
1794 		break;
1795 	case EVDNS_AUTHORITY_SECTION:
1796 		itemp = &req->authority;
1797 		countp = &req->n_authority;
1798 		break;
1799 	case EVDNS_ADDITIONAL_SECTION:
1800 		itemp = &req->additional;
1801 		countp = &req->n_additional;
1802 		break;
1803 	default:
1804 		goto done;
1805 	}
1806 	while (*itemp) {
1807 		itemp = &((*itemp)->next);
1808 	}
1809 	item = mm_malloc(sizeof(struct server_reply_item));
1810 	if (!item)
1811 		goto done;
1812 	item->next = NULL;
1813 	if (!(item->name = mm_strdup(name))) {
1814 		mm_free(item);
1815 		goto done;
1816 	}
1817 	item->type = type;
1818 	item->dns_question_class = class;
1819 	item->ttl = ttl;
1820 	item->is_name = is_name != 0;
1821 	item->datalen = 0;
1822 	item->data = NULL;
1823 	if (data) {
1824 		if (item->is_name) {
1825 			if (!(item->data = mm_strdup(data))) {
1826 				mm_free(item->name);
1827 				mm_free(item);
1828 				goto done;
1829 			}
1830 			item->datalen = (u16)-1;
1831 		} else {
1832 			if (!(item->data = mm_malloc(datalen))) {
1833 				mm_free(item->name);
1834 				mm_free(item);
1835 				goto done;
1836 			}
1837 			item->datalen = datalen;
1838 			memcpy(item->data, data, datalen);
1839 		}
1840 	}
1841 
1842 	*itemp = item;
1843 	++(*countp);
1844 	result = 0;
1845 done:
1846 	EVDNS_UNLOCK(req->port);
1847 	return result;
1848 }
1849 
1850 /* exported function */
1851 int
evdns_server_request_add_a_reply(struct evdns_server_request * req,const char * name,int n,const void * addrs,int ttl)1852 evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
1853 {
1854 	return evdns_server_request_add_reply(
1855 		  req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1856 		  ttl, n*4, 0, addrs);
1857 }
1858 
1859 /* exported function */
1860 int
evdns_server_request_add_aaaa_reply(struct evdns_server_request * req,const char * name,int n,const void * addrs,int ttl)1861 evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
1862 {
1863 	return evdns_server_request_add_reply(
1864 		  req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1865 		  ttl, n*16, 0, addrs);
1866 }
1867 
1868 /* exported function */
1869 int
evdns_server_request_add_ptr_reply(struct evdns_server_request * req,struct in_addr * in,const char * inaddr_name,const char * hostname,int ttl)1870 evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
1871 {
1872 	u32 a;
1873 	char buf[32];
1874 	if (in && inaddr_name)
1875 		return -1;
1876 	else if (!in && !inaddr_name)
1877 		return -1;
1878 	if (in) {
1879 		a = ntohl(in->s_addr);
1880 		evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
1881 				(int)(u8)((a	)&0xff),
1882 				(int)(u8)((a>>8 )&0xff),
1883 				(int)(u8)((a>>16)&0xff),
1884 				(int)(u8)((a>>24)&0xff));
1885 		inaddr_name = buf;
1886 	}
1887 	return evdns_server_request_add_reply(
1888 		  req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1889 		  ttl, -1, 1, hostname);
1890 }
1891 
1892 /* exported function */
1893 int
evdns_server_request_add_cname_reply(struct evdns_server_request * req,const char * name,const char * cname,int ttl)1894 evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
1895 {
1896 	return evdns_server_request_add_reply(
1897 		  req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
1898 		  ttl, -1, 1, cname);
1899 }
1900 
1901 /* exported function */
1902 void
evdns_server_request_set_flags(struct evdns_server_request * exreq,int flags)1903 evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
1904 {
1905 	struct server_request *req = TO_SERVER_REQUEST(exreq);
1906 	req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
1907 	req->base.flags |= flags;
1908 }
1909 
1910 static int
evdns_server_request_format_response(struct server_request * req,int err)1911 evdns_server_request_format_response(struct server_request *req, int err)
1912 {
1913 	unsigned char buf[1500];
1914 	size_t buf_len = sizeof(buf);
1915 	off_t j = 0, r;
1916 	u16 t_;
1917 	u32 t32_;
1918 	int i;
1919 	u16 flags;
1920 	struct dnslabel_table table;
1921 
1922 	if (err < 0 || err > 15) return -1;
1923 
1924 	/* Set response bit and error code; copy OPCODE and RD fields from
1925 	 * question; copy RA and AA if set by caller. */
1926 	flags = req->base.flags;
1927 	flags |= (_QR_MASK | err);
1928 
1929 	dnslabel_table_init(&table);
1930 	APPEND16(req->trans_id);
1931 	APPEND16(flags);
1932 	APPEND16(req->base.nquestions);
1933 	APPEND16(req->n_answer);
1934 	APPEND16(req->n_authority);
1935 	APPEND16(req->n_additional);
1936 
1937 	/* Add questions. */
1938 	for (i=0; i < req->base.nquestions; ++i) {
1939 		const char *s = req->base.questions[i]->name;
1940 		j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1941 		if (j < 0) {
1942 			dnslabel_clear(&table);
1943 			return (int) j;
1944 		}
1945 		APPEND16(req->base.questions[i]->type);
1946 		APPEND16(req->base.questions[i]->dns_question_class);
1947 	}
1948 
1949 	/* Add answer, authority, and additional sections. */
1950 	for (i=0; i<3; ++i) {
1951 		struct server_reply_item *item;
1952 		if (i==0)
1953 			item = req->answer;
1954 		else if (i==1)
1955 			item = req->authority;
1956 		else
1957 			item = req->additional;
1958 		while (item) {
1959 			r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1960 			if (r < 0)
1961 				goto overflow;
1962 			j = r;
1963 
1964 			APPEND16(item->type);
1965 			APPEND16(item->dns_question_class);
1966 			APPEND32(item->ttl);
1967 			if (item->is_name) {
1968 				off_t len_idx = j, name_start;
1969 				j += 2;
1970 				name_start = j;
1971 				r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1972 				if (r < 0)
1973 					goto overflow;
1974 				j = r;
1975 				t_ = htons( (short) (j-name_start) );
1976 				memcpy(buf+len_idx, &t_, 2);
1977 			} else {
1978 				APPEND16(item->datalen);
1979 				if (j+item->datalen > (off_t)buf_len)
1980 					goto overflow;
1981 				memcpy(buf+j, item->data, item->datalen);
1982 				j += item->datalen;
1983 			}
1984 			item = item->next;
1985 		}
1986 	}
1987 
1988 	if (j > 512) {
1989 overflow:
1990 		j = 512;
1991 		buf[2] |= 0x02; /* set the truncated bit. */
1992 	}
1993 
1994 	req->response_len = j;
1995 
1996 	if (!(req->response = mm_malloc(req->response_len))) {
1997 		server_request_free_answers(req);
1998 		dnslabel_clear(&table);
1999 		return (-1);
2000 	}
2001 	memcpy(req->response, buf, req->response_len);
2002 	server_request_free_answers(req);
2003 	dnslabel_clear(&table);
2004 	return (0);
2005 }
2006 
2007 /* exported function */
2008 int
evdns_server_request_respond(struct evdns_server_request * req_,int err)2009 evdns_server_request_respond(struct evdns_server_request *req_, int err)
2010 {
2011 	struct server_request *req = TO_SERVER_REQUEST(req_);
2012 	struct evdns_server_port *port = req->port;
2013 	int r = -1;
2014 
2015 	EVDNS_LOCK(port);
2016 	if (!req->response) {
2017 		if ((r = evdns_server_request_format_response(req, err))<0)
2018 			goto done;
2019 	}
2020 
2021 	r = sendto(port->socket, req->response, (int)req->response_len, 0,
2022 			   (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
2023 	if (r<0) {
2024 		int sock_err = evutil_socket_geterror(port->socket);
2025 		if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
2026 			goto done;
2027 
2028 		if (port->pending_replies) {
2029 			req->prev_pending = port->pending_replies->prev_pending;
2030 			req->next_pending = port->pending_replies;
2031 			req->prev_pending->next_pending =
2032 				req->next_pending->prev_pending = req;
2033 		} else {
2034 			req->prev_pending = req->next_pending = req;
2035 			port->pending_replies = req;
2036 			port->choked = 1;
2037 
2038 			(void) event_del(&port->event);
2039 			event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
2040 
2041 			if (event_add(&port->event, NULL) < 0) {
2042 				log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
2043 			}
2044 
2045 		}
2046 
2047 		r = 1;
2048 		goto done;
2049 	}
2050 	if (server_request_free(req)) {
2051 		r = 0;
2052 		goto done;
2053 	}
2054 
2055 	if (port->pending_replies)
2056 		server_port_flush(port);
2057 
2058 	r = 0;
2059 done:
2060 	EVDNS_UNLOCK(port);
2061 	return r;
2062 }
2063 
2064 /* Free all storage held by RRs in req. */
2065 static void
server_request_free_answers(struct server_request * req)2066 server_request_free_answers(struct server_request *req)
2067 {
2068 	struct server_reply_item *victim, *next, **list;
2069 	int i;
2070 	for (i = 0; i < 3; ++i) {
2071 		if (i==0)
2072 			list = &req->answer;
2073 		else if (i==1)
2074 			list = &req->authority;
2075 		else
2076 			list = &req->additional;
2077 
2078 		victim = *list;
2079 		while (victim) {
2080 			next = victim->next;
2081 			mm_free(victim->name);
2082 			if (victim->data)
2083 				mm_free(victim->data);
2084 			mm_free(victim);
2085 			victim = next;
2086 		}
2087 		*list = NULL;
2088 	}
2089 }
2090 
2091 /* Free all storage held by req, and remove links to it. */
2092 /* return true iff we just wound up freeing the server_port. */
2093 static int
server_request_free(struct server_request * req)2094 server_request_free(struct server_request *req)
2095 {
2096 	int i, rc=1, lock=0;
2097 	if (req->base.questions) {
2098 		for (i = 0; i < req->base.nquestions; ++i)
2099 			mm_free(req->base.questions[i]);
2100 		mm_free(req->base.questions);
2101 	}
2102 
2103 	if (req->port) {
2104 		EVDNS_LOCK(req->port);
2105 		lock=1;
2106 		if (req->port->pending_replies == req) {
2107 			if (req->next_pending && req->next_pending != req)
2108 				req->port->pending_replies = req->next_pending;
2109 			else
2110 				req->port->pending_replies = NULL;
2111 		}
2112 		rc = --req->port->refcnt;
2113 	}
2114 
2115 	if (req->response) {
2116 		mm_free(req->response);
2117 	}
2118 
2119 	server_request_free_answers(req);
2120 
2121 	if (req->next_pending && req->next_pending != req) {
2122 		req->next_pending->prev_pending = req->prev_pending;
2123 		req->prev_pending->next_pending = req->next_pending;
2124 	}
2125 
2126 	if (rc == 0) {
2127 		EVDNS_UNLOCK(req->port); /* ????? nickm */
2128 		server_port_free(req->port);
2129 		mm_free(req);
2130 		return (1);
2131 	}
2132 	if (lock)
2133 		EVDNS_UNLOCK(req->port);
2134 	mm_free(req);
2135 	return (0);
2136 }
2137 
2138 /* Free all storage held by an evdns_server_port.  Only called when  */
2139 static void
server_port_free(struct evdns_server_port * port)2140 server_port_free(struct evdns_server_port *port)
2141 {
2142 	EVUTIL_ASSERT(port);
2143 	EVUTIL_ASSERT(!port->refcnt);
2144 	EVUTIL_ASSERT(!port->pending_replies);
2145 	if (port->socket > 0) {
2146 		evutil_closesocket(port->socket);
2147 		port->socket = -1;
2148 	}
2149 	(void) event_del(&port->event);
2150 	event_debug_unassign(&port->event);
2151 	EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
2152 	mm_free(port);
2153 }
2154 
2155 /* exported function */
2156 int
evdns_server_request_drop(struct evdns_server_request * req_)2157 evdns_server_request_drop(struct evdns_server_request *req_)
2158 {
2159 	struct server_request *req = TO_SERVER_REQUEST(req_);
2160 	server_request_free(req);
2161 	return 0;
2162 }
2163 
2164 /* exported function */
2165 int
evdns_server_request_get_requesting_addr(struct evdns_server_request * req_,struct sockaddr * sa,int addr_len)2166 evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len)
2167 {
2168 	struct server_request *req = TO_SERVER_REQUEST(req_);
2169 	if (addr_len < (int)req->addrlen)
2170 		return -1;
2171 	memcpy(sa, &(req->addr), req->addrlen);
2172 	return req->addrlen;
2173 }
2174 
2175 #undef APPEND16
2176 #undef APPEND32
2177 
2178 /* this is a libevent callback function which is called when a request */
2179 /* has timed out. */
2180 static void
evdns_request_timeout_callback(evutil_socket_t fd,short events,void * arg)2181 evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
2182 	struct request *const req = (struct request *) arg;
2183 	struct evdns_base *base = req->base;
2184 
2185 	(void) fd;
2186 	(void) events;
2187 
2188 	log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
2189 	EVDNS_LOCK(base);
2190 
2191 	if (req->tx_count >= req->base->global_max_retransmits) {
2192 		struct nameserver *ns = req->ns;
2193 		/* this request has failed */
2194 		log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
2195 		    arg, req->tx_count);
2196 		reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
2197 
2198 		request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
2199 		nameserver_failed(ns, "request timed out.");
2200 	} else {
2201 		/* retransmit it */
2202 		log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
2203 		    arg, req->tx_count);
2204 		(void) evtimer_del(&req->timeout_event);
2205 		request_swap_ns(req, nameserver_pick(base));
2206 		evdns_request_transmit(req);
2207 
2208 		req->ns->timedout++;
2209 		if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
2210 			req->ns->timedout = 0;
2211 			nameserver_failed(req->ns, "request timed out.");
2212 		}
2213 	}
2214 
2215 	EVDNS_UNLOCK(base);
2216 }
2217 
2218 /* try to send a request to a given server. */
2219 /* */
2220 /* return: */
2221 /*   0 ok */
2222 /*   1 temporary failure */
2223 /*   2 other failure */
2224 static int
evdns_request_transmit_to(struct request * req,struct nameserver * server)2225 evdns_request_transmit_to(struct request *req, struct nameserver *server) {
2226 	int r;
2227 	ASSERT_LOCKED(req->base);
2228 	ASSERT_VALID_REQUEST(req);
2229 
2230 	if (server->requests_inflight == 1 &&
2231 		req->base->disable_when_inactive &&
2232 		event_add(&server->event, NULL) < 0) {
2233 		return 1;
2234 	}
2235 
2236 	r = sendto(server->socket, (void*)req->request, req->request_len, 0,
2237 	    (struct sockaddr *)&server->address, server->addrlen);
2238 	if (r < 0) {
2239 		int err = evutil_socket_geterror(server->socket);
2240 		if (EVUTIL_ERR_RW_RETRIABLE(err))
2241 			return 1;
2242 		nameserver_failed(req->ns, evutil_socket_error_to_string(err));
2243 		return 2;
2244 	} else if (r != (int)req->request_len) {
2245 		return 1;  /* short write */
2246 	} else {
2247 		return 0;
2248 	}
2249 }
2250 
2251 /* try to send a request, updating the fields of the request */
2252 /* as needed */
2253 /* */
2254 /* return: */
2255 /*   0 ok */
2256 /*   1 failed */
2257 static int
evdns_request_transmit(struct request * req)2258 evdns_request_transmit(struct request *req) {
2259 	int retcode = 0, r;
2260 
2261 	ASSERT_LOCKED(req->base);
2262 	ASSERT_VALID_REQUEST(req);
2263 	/* if we fail to send this packet then this flag marks it */
2264 	/* for evdns_transmit */
2265 	req->transmit_me = 1;
2266 	EVUTIL_ASSERT(req->trans_id != 0xffff);
2267 
2268 	if (!req->ns)
2269 	{
2270 		/* unable to transmit request if no nameservers */
2271 		return 1;
2272 	}
2273 
2274 	if (req->ns->choked) {
2275 		/* don't bother trying to write to a socket */
2276 		/* which we have had EAGAIN from */
2277 		return 1;
2278 	}
2279 
2280 	r = evdns_request_transmit_to(req, req->ns);
2281 	switch (r) {
2282 	case 1:
2283 		/* temp failure */
2284 		req->ns->choked = 1;
2285 		nameserver_write_waiting(req->ns, 1);
2286 		return 1;
2287 	case 2:
2288 		/* failed to transmit the request entirely. we can fallthrough since
2289 		 * we'll set a timeout, which will time out, and make us retransmit the
2290 		 * request anyway. */
2291 		retcode = 1;
2292 		EVUTIL_FALLTHROUGH;
2293 	default:
2294 		/* all ok */
2295 		log(EVDNS_LOG_DEBUG,
2296 		    "Setting timeout for request %p, sent to nameserver %p", req, req->ns);
2297 		if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
2298 			log(EVDNS_LOG_WARN,
2299 		      "Error from libevent when adding timer for request %p",
2300 			    req);
2301 			/* ???? Do more? */
2302 		}
2303 		req->tx_count++;
2304 		req->transmit_me = 0;
2305 		return retcode;
2306 	}
2307 }
2308 
2309 static void
nameserver_probe_callback(int result,char type,int count,int ttl,void * addresses,void * arg)2310 nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
2311 	struct nameserver *const ns = (struct nameserver *) arg;
2312 	(void) type;
2313 	(void) count;
2314 	(void) ttl;
2315 	(void) addresses;
2316 
2317 	if (result == DNS_ERR_CANCEL) {
2318 		/* We canceled this request because the nameserver came up
2319 		 * for some other reason.  Do not change our opinion about
2320 		 * the nameserver. */
2321 		return;
2322 	}
2323 
2324 	EVDNS_LOCK(ns->base);
2325 	ns->probe_request = NULL;
2326 	if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
2327 		/* this is a good reply */
2328 		nameserver_up(ns);
2329 	} else {
2330 		nameserver_probe_failed(ns);
2331 	}
2332 	EVDNS_UNLOCK(ns->base);
2333 }
2334 
2335 static void
nameserver_send_probe(struct nameserver * const ns)2336 nameserver_send_probe(struct nameserver *const ns) {
2337 	struct evdns_request *handle;
2338 	struct request *req;
2339 	char addrbuf[128];
2340 	/* here we need to send a probe to a given nameserver */
2341 	/* in the hope that it is up now. */
2342 
2343 	ASSERT_LOCKED(ns->base);
2344 	log(EVDNS_LOG_DEBUG, "Sending probe to %s",
2345 	    evutil_format_sockaddr_port_(
2346 		    (struct sockaddr *)&ns->address,
2347 		    addrbuf, sizeof(addrbuf)));
2348 	handle = mm_calloc(1, sizeof(*handle));
2349 	if (!handle) return;
2350 	req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
2351 	if (!req) {
2352 		mm_free(handle);
2353 		return;
2354 	}
2355 	ns->probe_request = handle;
2356 	/* we force this into the inflight queue no matter what */
2357 	request_trans_id_set(req, transaction_id_pick(ns->base));
2358 	req->ns = ns;
2359 	request_submit(req);
2360 }
2361 
2362 /* returns: */
2363 /*   0 didn't try to transmit anything */
2364 /*   1 tried to transmit something */
2365 static int
evdns_transmit(struct evdns_base * base)2366 evdns_transmit(struct evdns_base *base) {
2367 	char did_try_to_transmit = 0;
2368 	int i;
2369 
2370 	ASSERT_LOCKED(base);
2371 	for (i = 0; i < base->n_req_heads; ++i) {
2372 		if (base->req_heads[i]) {
2373 			struct request *const started_at = base->req_heads[i], *req = started_at;
2374 			/* first transmit all the requests which are currently waiting */
2375 			do {
2376 				if (req->transmit_me) {
2377 					did_try_to_transmit = 1;
2378 					evdns_request_transmit(req);
2379 				}
2380 
2381 				req = req->next;
2382 			} while (req != started_at);
2383 		}
2384 	}
2385 
2386 	return did_try_to_transmit;
2387 }
2388 
2389 /* exported function */
2390 int
evdns_base_count_nameservers(struct evdns_base * base)2391 evdns_base_count_nameservers(struct evdns_base *base)
2392 {
2393 	const struct nameserver *server;
2394 	int n = 0;
2395 
2396 	EVDNS_LOCK(base);
2397 	server = base->server_head;
2398 	if (!server)
2399 		goto done;
2400 	do {
2401 		++n;
2402 		server = server->next;
2403 	} while (server != base->server_head);
2404 done:
2405 	EVDNS_UNLOCK(base);
2406 	return n;
2407 }
2408 
2409 int
evdns_count_nameservers(void)2410 evdns_count_nameservers(void)
2411 {
2412 	return evdns_base_count_nameservers(current_base);
2413 }
2414 
2415 /* exported function */
2416 int
evdns_base_clear_nameservers_and_suspend(struct evdns_base * base)2417 evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
2418 {
2419 	struct nameserver *server, *started_at;
2420 	int i;
2421 
2422 	EVDNS_LOCK(base);
2423 	server = base->server_head;
2424 	started_at = base->server_head;
2425 	if (!server) {
2426 		EVDNS_UNLOCK(base);
2427 		return 0;
2428 	}
2429 	while (1) {
2430 		struct nameserver *next = server->next;
2431 		(void) event_del(&server->event);
2432 		if (evtimer_initialized(&server->timeout_event))
2433 			(void) evtimer_del(&server->timeout_event);
2434 		if (server->probe_request) {
2435 			evdns_cancel_request(server->base, server->probe_request);
2436 			server->probe_request = NULL;
2437 		}
2438 		if (server->socket >= 0)
2439 			evutil_closesocket(server->socket);
2440 		mm_free(server);
2441 		if (next == started_at)
2442 			break;
2443 		server = next;
2444 	}
2445 	base->server_head = NULL;
2446 	base->global_good_nameservers = 0;
2447 
2448 	for (i = 0; i < base->n_req_heads; ++i) {
2449 		struct request *req, *req_started_at;
2450 		req = req_started_at = base->req_heads[i];
2451 		while (req) {
2452 			struct request *next = req->next;
2453 			req->tx_count = req->reissue_count = 0;
2454 			req->ns = NULL;
2455 			/* ???? What to do about searches? */
2456 			(void) evtimer_del(&req->timeout_event);
2457 			req->trans_id = 0;
2458 			req->transmit_me = 0;
2459 
2460 			base->global_requests_waiting++;
2461 			evdns_request_insert(req, &base->req_waiting_head);
2462 			/* We want to insert these suspended elements at the front of
2463 			 * the waiting queue, since they were pending before any of
2464 			 * the waiting entries were added.  This is a circular list,
2465 			 * so we can just shift the start back by one.*/
2466 			base->req_waiting_head = base->req_waiting_head->prev;
2467 
2468 			if (next == req_started_at)
2469 				break;
2470 			req = next;
2471 		}
2472 		base->req_heads[i] = NULL;
2473 	}
2474 
2475 	base->global_requests_inflight = 0;
2476 
2477 	EVDNS_UNLOCK(base);
2478 	return 0;
2479 }
2480 
2481 int
evdns_clear_nameservers_and_suspend(void)2482 evdns_clear_nameservers_and_suspend(void)
2483 {
2484 	return evdns_base_clear_nameservers_and_suspend(current_base);
2485 }
2486 
2487 
2488 /* exported function */
2489 int
evdns_base_resume(struct evdns_base * base)2490 evdns_base_resume(struct evdns_base *base)
2491 {
2492 	EVDNS_LOCK(base);
2493 	evdns_requests_pump_waiting_queue(base);
2494 	EVDNS_UNLOCK(base);
2495 
2496 	return 0;
2497 }
2498 
2499 int
evdns_resume(void)2500 evdns_resume(void)
2501 {
2502 	return evdns_base_resume(current_base);
2503 }
2504 
2505 static int
evdns_nameserver_add_impl_(struct evdns_base * base,const struct sockaddr * address,int addrlen)2506 evdns_nameserver_add_impl_(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
2507 	/* first check to see if we already have this nameserver */
2508 
2509 	const struct nameserver *server = base->server_head, *const started_at = base->server_head;
2510 	struct nameserver *ns;
2511 	int err = 0;
2512 	char addrbuf[128];
2513 
2514 	ASSERT_LOCKED(base);
2515 	if (server) {
2516 		do {
2517 			if (!evutil_sockaddr_cmp((const struct sockaddr*)&server->address, address, 1)) return 3;
2518 			server = server->next;
2519 		} while (server != started_at);
2520 	}
2521 	if (addrlen > (int)sizeof(ns->address)) {
2522 		log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
2523 		return 2;
2524 	}
2525 
2526 	ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
2527 	if (!ns) return -1;
2528 
2529 	memset(ns, 0, sizeof(struct nameserver));
2530 	ns->base = base;
2531 
2532 	evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
2533 
2534 	ns->socket = evutil_socket_(address->sa_family,
2535 	    SOCK_DGRAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
2536 	if (ns->socket < 0) { err = 1; goto out1; }
2537 
2538 	if (base->global_outgoing_addrlen &&
2539 	    !evutil_sockaddr_is_loopback_(address)) {
2540 		if (bind(ns->socket,
2541 			(struct sockaddr*)&base->global_outgoing_address,
2542 			base->global_outgoing_addrlen) < 0) {
2543 			log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
2544 			err = 2;
2545 			goto out2;
2546 		}
2547 	}
2548 
2549 	if (base->so_rcvbuf) {
2550 		if (setsockopt(ns->socket, SOL_SOCKET, SO_RCVBUF,
2551 		    (void *)&base->so_rcvbuf, sizeof(base->so_rcvbuf))) {
2552 			log(EVDNS_LOG_WARN, "Couldn't set SO_RCVBUF to %i", base->so_rcvbuf);
2553 			err = -SO_RCVBUF;
2554 			goto out2;
2555 		}
2556 	}
2557 	if (base->so_sndbuf) {
2558 		if (setsockopt(ns->socket, SOL_SOCKET, SO_SNDBUF,
2559 		    (void *)&base->so_sndbuf, sizeof(base->so_sndbuf))) {
2560 			log(EVDNS_LOG_WARN, "Couldn't set SO_SNDBUF to %i", base->so_sndbuf);
2561 			err = -SO_SNDBUF;
2562 			goto out2;
2563 		}
2564 	}
2565 
2566 	memcpy(&ns->address, address, addrlen);
2567 	ns->addrlen = addrlen;
2568 	ns->state = 1;
2569 	event_assign(&ns->event, ns->base->event_base, ns->socket,
2570 				 EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
2571 	if (!base->disable_when_inactive && event_add(&ns->event, NULL) < 0) {
2572 		err = 2;
2573 		goto out2;
2574 	}
2575 
2576 	log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
2577 	    evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), ns);
2578 
2579 	/* insert this nameserver into the list of them */
2580 	if (!base->server_head) {
2581 		ns->next = ns->prev = ns;
2582 		base->server_head = ns;
2583 	} else {
2584 		ns->next = base->server_head->next;
2585 		ns->prev = base->server_head;
2586 		base->server_head->next = ns;
2587 		ns->next->prev = ns;
2588 	}
2589 
2590 	base->global_good_nameservers++;
2591 
2592 	return 0;
2593 
2594 out2:
2595 	evutil_closesocket(ns->socket);
2596 out1:
2597 	event_debug_unassign(&ns->event);
2598 	mm_free(ns);
2599 	log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
2600 	    evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), err);
2601 	return err;
2602 }
2603 
2604 /* exported function */
2605 int
evdns_base_nameserver_add(struct evdns_base * base,unsigned long int address)2606 evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
2607 {
2608 	struct sockaddr_in sin;
2609 	int res;
2610 	memset(&sin, 0, sizeof(sin));
2611 	sin.sin_addr.s_addr = address;
2612 	sin.sin_port = htons(53);
2613 	sin.sin_family = AF_INET;
2614 	EVDNS_LOCK(base);
2615 	res = evdns_nameserver_add_impl_(base, (struct sockaddr*)&sin, sizeof(sin));
2616 	EVDNS_UNLOCK(base);
2617 	return res;
2618 }
2619 
2620 int
evdns_nameserver_add(unsigned long int address)2621 evdns_nameserver_add(unsigned long int address) {
2622 	if (!current_base)
2623 		current_base = evdns_base_new(NULL, 0);
2624 	return evdns_base_nameserver_add(current_base, address);
2625 }
2626 
2627 static void
sockaddr_setport(struct sockaddr * sa,ev_uint16_t port)2628 sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
2629 {
2630 	if (sa->sa_family == AF_INET) {
2631 		((struct sockaddr_in *)sa)->sin_port = htons(port);
2632 	} else if (sa->sa_family == AF_INET6) {
2633 		((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
2634 	}
2635 }
2636 
2637 static ev_uint16_t
sockaddr_getport(struct sockaddr * sa)2638 sockaddr_getport(struct sockaddr *sa)
2639 {
2640 	if (sa->sa_family == AF_INET) {
2641 		return ntohs(((struct sockaddr_in *)sa)->sin_port);
2642 	} else if (sa->sa_family == AF_INET6) {
2643 		return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
2644 	} else {
2645 		return 0;
2646 	}
2647 }
2648 
2649 /* exported function */
2650 int
evdns_base_nameserver_ip_add(struct evdns_base * base,const char * ip_as_string)2651 evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
2652 	struct sockaddr_storage ss;
2653 	struct sockaddr *sa;
2654 	int len = sizeof(ss);
2655 	int res;
2656 	if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
2657 		&len)) {
2658 		log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
2659 			ip_as_string);
2660 		return 4;
2661 	}
2662 	sa = (struct sockaddr *) &ss;
2663 	if (sockaddr_getport(sa) == 0)
2664 		sockaddr_setport(sa, 53);
2665 
2666 	EVDNS_LOCK(base);
2667 	res = evdns_nameserver_add_impl_(base, sa, len);
2668 	EVDNS_UNLOCK(base);
2669 	return res;
2670 }
2671 
2672 int
evdns_nameserver_ip_add(const char * ip_as_string)2673 evdns_nameserver_ip_add(const char *ip_as_string) {
2674 	if (!current_base)
2675 		current_base = evdns_base_new(NULL, 0);
2676 	return evdns_base_nameserver_ip_add(current_base, ip_as_string);
2677 }
2678 
2679 int
evdns_base_nameserver_sockaddr_add(struct evdns_base * base,const struct sockaddr * sa,ev_socklen_t len,unsigned flags)2680 evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
2681     const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
2682 {
2683 	int res;
2684 	EVUTIL_ASSERT(base);
2685 	EVDNS_LOCK(base);
2686 	res = evdns_nameserver_add_impl_(base, sa, len);
2687 	EVDNS_UNLOCK(base);
2688 	return res;
2689 }
2690 
2691 int
evdns_base_get_nameserver_addr(struct evdns_base * base,int idx,struct sockaddr * sa,ev_socklen_t len)2692 evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
2693     struct sockaddr *sa, ev_socklen_t len)
2694 {
2695 	int result = -1;
2696 	int i;
2697 	struct nameserver *server;
2698 	EVDNS_LOCK(base);
2699 	server = base->server_head;
2700 	for (i = 0; i < idx && server; ++i, server = server->next) {
2701 		if (server->next == base->server_head)
2702 			goto done;
2703 	}
2704 	if (! server)
2705 		goto done;
2706 
2707 	if (server->addrlen > len) {
2708 		result = (int) server->addrlen;
2709 		goto done;
2710 	}
2711 
2712 	memcpy(sa, &server->address, server->addrlen);
2713 	result = (int) server->addrlen;
2714 done:
2715 	EVDNS_UNLOCK(base);
2716 	return result;
2717 }
2718 
2719 /* remove from the queue */
2720 static void
evdns_request_remove(struct request * req,struct request ** head)2721 evdns_request_remove(struct request *req, struct request **head)
2722 {
2723 	ASSERT_LOCKED(req->base);
2724 	ASSERT_VALID_REQUEST(req);
2725 
2726 #if 0
2727 	{
2728 		struct request *ptr;
2729 		int found = 0;
2730 		EVUTIL_ASSERT(*head != NULL);
2731 
2732 		ptr = *head;
2733 		do {
2734 			if (ptr == req) {
2735 				found = 1;
2736 				break;
2737 			}
2738 			ptr = ptr->next;
2739 		} while (ptr != *head);
2740 		EVUTIL_ASSERT(found);
2741 
2742 		EVUTIL_ASSERT(req->next);
2743 	}
2744 #endif
2745 
2746 	if (req->next == req) {
2747 		/* only item in the list */
2748 		*head = NULL;
2749 	} else {
2750 		req->next->prev = req->prev;
2751 		req->prev->next = req->next;
2752 		if (*head == req) *head = req->next;
2753 	}
2754 	req->next = req->prev = NULL;
2755 }
2756 
2757 /* insert into the tail of the queue */
2758 static void
evdns_request_insert(struct request * req,struct request ** head)2759 evdns_request_insert(struct request *req, struct request **head) {
2760 	ASSERT_LOCKED(req->base);
2761 	ASSERT_VALID_REQUEST(req);
2762 	if (!*head) {
2763 		*head = req;
2764 		req->next = req->prev = req;
2765 		return;
2766 	}
2767 
2768 	req->prev = (*head)->prev;
2769 	req->prev->next = req;
2770 	req->next = *head;
2771 	(*head)->prev = req;
2772 }
2773 
2774 static int
string_num_dots(const char * s)2775 string_num_dots(const char *s) {
2776 	int count = 0;
2777 	while ((s = strchr(s, '.'))) {
2778 		s++;
2779 		count++;
2780 	}
2781 	return count;
2782 }
2783 
2784 static struct request *
request_new(struct evdns_base * base,struct evdns_request * handle,int type,const char * name,int flags,evdns_callback_type callback,void * user_ptr)2785 request_new(struct evdns_base *base, struct evdns_request *handle, int type,
2786 	    const char *name, int flags, evdns_callback_type callback,
2787 	    void *user_ptr) {
2788 
2789 	const char issuing_now =
2790 	    (base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
2791 
2792 	const size_t name_len = strlen(name);
2793 	const size_t request_max_len = evdns_request_len(name_len);
2794 	const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
2795 	/* the request data is alloced in a single block with the header */
2796 	struct request *const req =
2797 	    mm_malloc(sizeof(struct request) + request_max_len);
2798 	int rlen;
2799 	char namebuf[256];
2800 	(void) flags;
2801 
2802 	ASSERT_LOCKED(base);
2803 
2804 	if (!req) return NULL;
2805 
2806 	if (name_len >= sizeof(namebuf)) {
2807 		mm_free(req);
2808 		return NULL;
2809 	}
2810 
2811 	memset(req, 0, sizeof(struct request));
2812 	req->base = base;
2813 
2814 	evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
2815 
2816 	if (base->global_randomize_case) {
2817 		unsigned i;
2818 		char randbits[(sizeof(namebuf)+7)/8];
2819 		strlcpy(namebuf, name, sizeof(namebuf));
2820 		evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
2821 		for (i = 0; i < name_len; ++i) {
2822 			if (EVUTIL_ISALPHA_(namebuf[i])) {
2823 				if ((randbits[i >> 3] & (1<<(i & 7))))
2824 					namebuf[i] |= 0x20;
2825 				else
2826 					namebuf[i] &= ~0x20;
2827 			}
2828 		}
2829 		name = namebuf;
2830 	}
2831 
2832 	/* request data lives just after the header */
2833 	req->request = ((u8 *) req) + sizeof(struct request);
2834 	/* denotes that the request data shouldn't be free()ed */
2835 	req->request_appended = 1;
2836 	rlen = evdns_request_data_build(name, name_len, trans_id,
2837 	    type, CLASS_INET, req->request, request_max_len);
2838 	if (rlen < 0)
2839 		goto err1;
2840 
2841 	req->request_len = rlen;
2842 	req->trans_id = trans_id;
2843 	req->tx_count = 0;
2844 	req->request_type = type;
2845 	req->user_pointer = user_ptr;
2846 	req->user_callback = callback;
2847 	req->ns = issuing_now ? nameserver_pick(base) : NULL;
2848 	req->next = req->prev = NULL;
2849 	req->handle = handle;
2850 	if (handle) {
2851 		handle->current_req = req;
2852 		handle->base = base;
2853 	}
2854 
2855 	return req;
2856 err1:
2857 	mm_free(req);
2858 	return NULL;
2859 }
2860 
2861 static void
request_submit(struct request * const req)2862 request_submit(struct request *const req) {
2863 	struct evdns_base *base = req->base;
2864 	ASSERT_LOCKED(base);
2865 	ASSERT_VALID_REQUEST(req);
2866 	if (req->ns) {
2867 		/* if it has a nameserver assigned then this is going */
2868 		/* straight into the inflight queue */
2869 		evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
2870 
2871 		base->global_requests_inflight++;
2872 		req->ns->requests_inflight++;
2873 
2874 		evdns_request_transmit(req);
2875 	} else {
2876 		evdns_request_insert(req, &base->req_waiting_head);
2877 		base->global_requests_waiting++;
2878 	}
2879 }
2880 
2881 /* exported function */
2882 void
evdns_cancel_request(struct evdns_base * base,struct evdns_request * handle)2883 evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
2884 {
2885 	struct request *req;
2886 
2887 	if (!handle->current_req)
2888 		return;
2889 
2890 	if (!base) {
2891 		/* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
2892 		base = handle->base;
2893 		if (!base)
2894 			base = handle->current_req->base;
2895 	}
2896 
2897 	EVDNS_LOCK(base);
2898 	if (handle->pending_cb) {
2899 		EVDNS_UNLOCK(base);
2900 		return;
2901 	}
2902 
2903 	req = handle->current_req;
2904 	ASSERT_VALID_REQUEST(req);
2905 
2906 	reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
2907 	if (req->ns) {
2908 		/* remove from inflight queue */
2909 		request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
2910 	} else {
2911 		/* remove from global_waiting head */
2912 		request_finished(req, &base->req_waiting_head, 1);
2913 	}
2914 	EVDNS_UNLOCK(base);
2915 }
2916 
2917 /* exported function */
2918 struct evdns_request *
evdns_base_resolve_ipv4(struct evdns_base * base,const char * name,int flags,evdns_callback_type callback,void * ptr)2919 evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
2920     evdns_callback_type callback, void *ptr) {
2921 	struct evdns_request *handle;
2922 	struct request *req;
2923 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2924 	handle = mm_calloc(1, sizeof(*handle));
2925 	if (handle == NULL)
2926 		return NULL;
2927 	EVDNS_LOCK(base);
2928 	if (flags & DNS_QUERY_NO_SEARCH) {
2929 		req =
2930 			request_new(base, handle, TYPE_A, name, flags,
2931 				    callback, ptr);
2932 		if (req)
2933 			request_submit(req);
2934 	} else {
2935 		search_request_new(base, handle, TYPE_A, name, flags,
2936 		    callback, ptr);
2937 	}
2938 	if (handle->current_req == NULL) {
2939 		mm_free(handle);
2940 		handle = NULL;
2941 	}
2942 	EVDNS_UNLOCK(base);
2943 	return handle;
2944 }
2945 
evdns_resolve_ipv4(const char * name,int flags,evdns_callback_type callback,void * ptr)2946 int evdns_resolve_ipv4(const char *name, int flags,
2947 					   evdns_callback_type callback, void *ptr)
2948 {
2949 	return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
2950 		? 0 : -1;
2951 }
2952 
2953 
2954 /* exported function */
2955 struct evdns_request *
evdns_base_resolve_ipv6(struct evdns_base * base,const char * name,int flags,evdns_callback_type callback,void * ptr)2956 evdns_base_resolve_ipv6(struct evdns_base *base,
2957     const char *name, int flags,
2958     evdns_callback_type callback, void *ptr)
2959 {
2960 	struct evdns_request *handle;
2961 	struct request *req;
2962 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
2963 	handle = mm_calloc(1, sizeof(*handle));
2964 	if (handle == NULL)
2965 		return NULL;
2966 	EVDNS_LOCK(base);
2967 	if (flags & DNS_QUERY_NO_SEARCH) {
2968 		req = request_new(base, handle, TYPE_AAAA, name, flags,
2969 				  callback, ptr);
2970 		if (req)
2971 			request_submit(req);
2972 	} else {
2973 		search_request_new(base, handle, TYPE_AAAA, name, flags,
2974 		    callback, ptr);
2975 	}
2976 	if (handle->current_req == NULL) {
2977 		mm_free(handle);
2978 		handle = NULL;
2979 	}
2980 	EVDNS_UNLOCK(base);
2981 	return handle;
2982 }
2983 
evdns_resolve_ipv6(const char * name,int flags,evdns_callback_type callback,void * ptr)2984 int evdns_resolve_ipv6(const char *name, int flags,
2985     evdns_callback_type callback, void *ptr) {
2986 	return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
2987 		? 0 : -1;
2988 }
2989 
2990 struct evdns_request *
evdns_base_resolve_reverse(struct evdns_base * base,const struct in_addr * in,int flags,evdns_callback_type callback,void * ptr)2991 evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2992 	char buf[32];
2993 	struct evdns_request *handle;
2994 	struct request *req;
2995 	u32 a;
2996 	EVUTIL_ASSERT(in);
2997 	a = ntohl(in->s_addr);
2998 	evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
2999 			(int)(u8)((a	)&0xff),
3000 			(int)(u8)((a>>8 )&0xff),
3001 			(int)(u8)((a>>16)&0xff),
3002 			(int)(u8)((a>>24)&0xff));
3003 	handle = mm_calloc(1, sizeof(*handle));
3004 	if (handle == NULL)
3005 		return NULL;
3006 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
3007 	EVDNS_LOCK(base);
3008 	req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
3009 	if (req)
3010 		request_submit(req);
3011 	if (handle->current_req == NULL) {
3012 		mm_free(handle);
3013 		handle = NULL;
3014 	}
3015 	EVDNS_UNLOCK(base);
3016 	return (handle);
3017 }
3018 
evdns_resolve_reverse(const struct in_addr * in,int flags,evdns_callback_type callback,void * ptr)3019 int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
3020 	return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
3021 		? 0 : -1;
3022 }
3023 
3024 struct evdns_request *
evdns_base_resolve_reverse_ipv6(struct evdns_base * base,const struct in6_addr * in,int flags,evdns_callback_type callback,void * ptr)3025 evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
3026 	/* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
3027 	char buf[73];
3028 	char *cp;
3029 	struct evdns_request *handle;
3030 	struct request *req;
3031 	int i;
3032 	EVUTIL_ASSERT(in);
3033 	cp = buf;
3034 	for (i=15; i >= 0; --i) {
3035 		u8 byte = in->s6_addr[i];
3036 		*cp++ = "0123456789abcdef"[byte & 0x0f];
3037 		*cp++ = '.';
3038 		*cp++ = "0123456789abcdef"[byte >> 4];
3039 		*cp++ = '.';
3040 	}
3041 	EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
3042 	memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
3043 	handle = mm_calloc(1, sizeof(*handle));
3044 	if (handle == NULL)
3045 		return NULL;
3046 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
3047 	EVDNS_LOCK(base);
3048 	req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
3049 	if (req)
3050 		request_submit(req);
3051 	if (handle->current_req == NULL) {
3052 		mm_free(handle);
3053 		handle = NULL;
3054 	}
3055 	EVDNS_UNLOCK(base);
3056 	return (handle);
3057 }
3058 
evdns_resolve_reverse_ipv6(const struct in6_addr * in,int flags,evdns_callback_type callback,void * ptr)3059 int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
3060 	return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
3061 		? 0 : -1;
3062 }
3063 
3064 /* ================================================================= */
3065 /* Search support */
3066 /* */
3067 /* the libc resolver has support for searching a number of domains */
3068 /* to find a name. If nothing else then it takes the single domain */
3069 /* from the gethostname() call. */
3070 /* */
3071 /* It can also be configured via the domain and search options in a */
3072 /* resolv.conf. */
3073 /* */
3074 /* The ndots option controls how many dots it takes for the resolver */
3075 /* to decide that a name is non-local and so try a raw lookup first. */
3076 
3077 struct search_domain {
3078 	int len;
3079 	struct search_domain *next;
3080 	/* the text string is appended to this structure */
3081 };
3082 
3083 struct search_state {
3084 	int refcount;
3085 	int ndots;
3086 	int num_domains;
3087 	struct search_domain *head;
3088 };
3089 
3090 static void
search_state_decref(struct search_state * const state)3091 search_state_decref(struct search_state *const state) {
3092 	if (!state) return;
3093 	state->refcount--;
3094 	if (!state->refcount) {
3095 		struct search_domain *next, *dom;
3096 		for (dom = state->head; dom; dom = next) {
3097 			next = dom->next;
3098 			mm_free(dom);
3099 		}
3100 		mm_free(state);
3101 	}
3102 }
3103 
3104 static struct search_state *
search_state_new(void)3105 search_state_new(void) {
3106 	struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
3107 	if (!state) return NULL;
3108 	memset(state, 0, sizeof(struct search_state));
3109 	state->refcount = 1;
3110 	state->ndots = 1;
3111 
3112 	return state;
3113 }
3114 
3115 static void
search_postfix_clear(struct evdns_base * base)3116 search_postfix_clear(struct evdns_base *base) {
3117 	search_state_decref(base->global_search_state);
3118 
3119 	base->global_search_state = search_state_new();
3120 }
3121 
3122 /* exported function */
3123 void
evdns_base_search_clear(struct evdns_base * base)3124 evdns_base_search_clear(struct evdns_base *base)
3125 {
3126 	EVDNS_LOCK(base);
3127 	search_postfix_clear(base);
3128 	EVDNS_UNLOCK(base);
3129 }
3130 
3131 void
evdns_search_clear(void)3132 evdns_search_clear(void) {
3133 	evdns_base_search_clear(current_base);
3134 }
3135 
3136 static void
search_postfix_add(struct evdns_base * base,const char * domain)3137 search_postfix_add(struct evdns_base *base, const char *domain) {
3138 	size_t domain_len;
3139 	struct search_domain *sdomain;
3140 	while (domain[0] == '.') domain++;
3141 	domain_len = strlen(domain);
3142 
3143 	ASSERT_LOCKED(base);
3144 	if (!base->global_search_state) base->global_search_state = search_state_new();
3145 	if (!base->global_search_state) return;
3146 	base->global_search_state->num_domains++;
3147 
3148 	sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
3149 	if (!sdomain) return;
3150 	memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
3151 	sdomain->next = base->global_search_state->head;
3152 	sdomain->len = (int) domain_len;
3153 
3154 	base->global_search_state->head = sdomain;
3155 }
3156 
3157 /* reverse the order of members in the postfix list. This is needed because, */
3158 /* when parsing resolv.conf we push elements in the wrong order */
3159 static void
search_reverse(struct evdns_base * base)3160 search_reverse(struct evdns_base *base) {
3161 	struct search_domain *cur, *prev = NULL, *next;
3162 	ASSERT_LOCKED(base);
3163 	cur = base->global_search_state->head;
3164 	while (cur) {
3165 		next = cur->next;
3166 		cur->next = prev;
3167 		prev = cur;
3168 		cur = next;
3169 	}
3170 
3171 	base->global_search_state->head = prev;
3172 }
3173 
3174 /* exported function */
3175 void
evdns_base_search_add(struct evdns_base * base,const char * domain)3176 evdns_base_search_add(struct evdns_base *base, const char *domain) {
3177 	EVDNS_LOCK(base);
3178 	search_postfix_add(base, domain);
3179 	EVDNS_UNLOCK(base);
3180 }
3181 void
evdns_search_add(const char * domain)3182 evdns_search_add(const char *domain) {
3183 	evdns_base_search_add(current_base, domain);
3184 }
3185 
3186 /* exported function */
3187 void
evdns_base_search_ndots_set(struct evdns_base * base,const int ndots)3188 evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
3189 	EVDNS_LOCK(base);
3190 	if (!base->global_search_state) base->global_search_state = search_state_new();
3191 	if (base->global_search_state)
3192 		base->global_search_state->ndots = ndots;
3193 	EVDNS_UNLOCK(base);
3194 }
3195 void
evdns_search_ndots_set(const int ndots)3196 evdns_search_ndots_set(const int ndots) {
3197 	evdns_base_search_ndots_set(current_base, ndots);
3198 }
3199 
3200 static void
search_set_from_hostname(struct evdns_base * base)3201 search_set_from_hostname(struct evdns_base *base) {
3202 	char hostname[HOST_NAME_MAX + 1], *domainname;
3203 
3204 	ASSERT_LOCKED(base);
3205 	search_postfix_clear(base);
3206 	if (gethostname(hostname, sizeof(hostname))) return;
3207 	domainname = strchr(hostname, '.');
3208 	if (!domainname) return;
3209 	search_postfix_add(base, domainname);
3210 }
3211 
3212 /* warning: returns malloced string */
3213 static char *
search_make_new(const struct search_state * const state,int n,const char * const base_name)3214 search_make_new(const struct search_state *const state, int n, const char *const base_name) {
3215 	const size_t base_len = strlen(base_name);
3216 	char need_to_append_dot;
3217 	struct search_domain *dom;
3218 
3219 	if (!base_len) return NULL;
3220 	need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
3221 
3222 	for (dom = state->head; dom; dom = dom->next) {
3223 		if (!n--) {
3224 			/* this is the postfix we want */
3225 			/* the actual postfix string is kept at the end of the structure */
3226 			const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
3227 			const int postfix_len = dom->len;
3228 			char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
3229 			if (!newname) return NULL;
3230 			memcpy(newname, base_name, base_len);
3231 			if (need_to_append_dot) newname[base_len] = '.';
3232 			memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
3233 			newname[base_len + need_to_append_dot + postfix_len] = 0;
3234 			return newname;
3235 		}
3236 	}
3237 
3238 	/* we ran off the end of the list and still didn't find the requested string */
3239 	EVUTIL_ASSERT(0);
3240 	return NULL; /* unreachable; stops warnings in some compilers. */
3241 }
3242 
3243 static struct request *
search_request_new(struct evdns_base * base,struct evdns_request * handle,int type,const char * const name,int flags,evdns_callback_type user_callback,void * user_arg)3244 search_request_new(struct evdns_base *base, struct evdns_request *handle,
3245 		   int type, const char *const name, int flags,
3246 		   evdns_callback_type user_callback, void *user_arg) {
3247 	ASSERT_LOCKED(base);
3248 	EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
3249 	EVUTIL_ASSERT(handle->current_req == NULL);
3250 	if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
3251 	     base->global_search_state &&
3252 		 base->global_search_state->num_domains) {
3253 		/* we have some domains to search */
3254 		struct request *req;
3255 		if (string_num_dots(name) >= base->global_search_state->ndots) {
3256 			req = request_new(base, handle, type, name, flags, user_callback, user_arg);
3257 			if (!req) return NULL;
3258 			handle->search_index = -1;
3259 		} else {
3260 			char *const new_name = search_make_new(base->global_search_state, 0, name);
3261 			if (!new_name) return NULL;
3262 			req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
3263 			mm_free(new_name);
3264 			if (!req) return NULL;
3265 			handle->search_index = 0;
3266 		}
3267 		EVUTIL_ASSERT(handle->search_origname == NULL);
3268 		handle->search_origname = mm_strdup(name);
3269 		if (handle->search_origname == NULL) {
3270 			/* XXX Should we dealloc req? If yes, how? */
3271 			if (req)
3272 				mm_free(req);
3273 			return NULL;
3274 		}
3275 		handle->search_state = base->global_search_state;
3276 		handle->search_flags = flags;
3277 		base->global_search_state->refcount++;
3278 		request_submit(req);
3279 		return req;
3280 	} else {
3281 		struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
3282 		if (!req) return NULL;
3283 		request_submit(req);
3284 		return req;
3285 	}
3286 }
3287 
3288 /* this is called when a request has failed to find a name. We need to check */
3289 /* if it is part of a search and, if so, try the next name in the list */
3290 /* returns: */
3291 /*   0 another request has been submitted */
3292 /*   1 no more requests needed */
3293 static int
search_try_next(struct evdns_request * const handle)3294 search_try_next(struct evdns_request *const handle) {
3295 	struct request *req = handle->current_req;
3296 	struct evdns_base *base = req->base;
3297 	struct request *newreq;
3298 	ASSERT_LOCKED(base);
3299 	if (handle->search_state) {
3300 		/* it is part of a search */
3301 		char *new_name;
3302 		handle->search_index++;
3303 		if (handle->search_index >= handle->search_state->num_domains) {
3304 			/* no more postfixes to try, however we may need to try */
3305 			/* this name without a postfix */
3306 			if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
3307 				/* yep, we need to try it raw */
3308 				newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
3309 				log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
3310 				if (newreq) {
3311 					search_request_finished(handle);
3312 					goto submit_next;
3313 				}
3314 			}
3315 			return 1;
3316 		}
3317 
3318 		new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
3319 		if (!new_name) return 1;
3320 		log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
3321 		newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
3322 		mm_free(new_name);
3323 		if (!newreq) return 1;
3324 		goto submit_next;
3325 	}
3326 	return 1;
3327 
3328 submit_next:
3329 	request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
3330 	handle->current_req = newreq;
3331 	newreq->handle = handle;
3332 	request_submit(newreq);
3333 	return 0;
3334 }
3335 
3336 static void
search_request_finished(struct evdns_request * const handle)3337 search_request_finished(struct evdns_request *const handle) {
3338 	ASSERT_LOCKED(handle->current_req->base);
3339 	if (handle->search_state) {
3340 		search_state_decref(handle->search_state);
3341 		handle->search_state = NULL;
3342 	}
3343 	if (handle->search_origname) {
3344 		mm_free(handle->search_origname);
3345 		handle->search_origname = NULL;
3346 	}
3347 }
3348 
3349 /* ================================================================= */
3350 /* Parsing resolv.conf files */
3351 
3352 static void
evdns_resolv_set_defaults(struct evdns_base * base,int flags)3353 evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
3354 	int add_default = flags & DNS_OPTION_NAMESERVERS;
3355 	if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
3356 		add_default = 0;
3357 
3358 	/* if the file isn't found then we assume a local resolver */
3359 	ASSERT_LOCKED(base);
3360 	if (flags & DNS_OPTION_SEARCH)
3361 		search_set_from_hostname(base);
3362 	if (add_default)
3363 		evdns_base_nameserver_ip_add(base, "127.0.0.1");
3364 }
3365 
3366 #ifndef EVENT__HAVE_STRTOK_R
3367 static char *
strtok_r(char * s,const char * delim,char ** state)3368 strtok_r(char *s, const char *delim, char **state) {
3369 	char *cp, *start;
3370 	start = cp = s ? s : *state;
3371 	if (!cp)
3372 		return NULL;
3373 	while (*cp && !strchr(delim, *cp))
3374 		++cp;
3375 	if (!*cp) {
3376 		if (cp == start)
3377 			return NULL;
3378 		*state = NULL;
3379 		return start;
3380 	} else {
3381 		*cp++ = '\0';
3382 		*state = cp;
3383 		return start;
3384 	}
3385 }
3386 #endif
3387 
3388 /* helper version of atoi which returns -1 on error */
3389 static int
strtoint(const char * const str)3390 strtoint(const char *const str)
3391 {
3392 	char *endptr;
3393 	const int r = strtol(str, &endptr, 10);
3394 	if (*endptr) return -1;
3395 	return r;
3396 }
3397 
3398 /* Parse a number of seconds into a timeval; return -1 on error. */
3399 static int
evdns_strtotimeval(const char * const str,struct timeval * out)3400 evdns_strtotimeval(const char *const str, struct timeval *out)
3401 {
3402 	double d;
3403 	char *endptr;
3404 	d = strtod(str, &endptr);
3405 	if (*endptr) return -1;
3406 	if (d < 0) return -1;
3407 	out->tv_sec = (int) d;
3408 	out->tv_usec = (int) ((d - (int) d)*1000000);
3409 	if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
3410 		return -1;
3411 	return 0;
3412 }
3413 
3414 /* helper version of atoi that returns -1 on error and clips to bounds. */
3415 static int
strtoint_clipped(const char * const str,int min,int max)3416 strtoint_clipped(const char *const str, int min, int max)
3417 {
3418 	int r = strtoint(str);
3419 	if (r == -1)
3420 		return r;
3421 	else if (r<min)
3422 		return min;
3423 	else if (r>max)
3424 		return max;
3425 	else
3426 		return r;
3427 }
3428 
3429 static int
evdns_base_set_max_requests_inflight(struct evdns_base * base,int maxinflight)3430 evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
3431 {
3432 	int old_n_heads = base->n_req_heads, n_heads;
3433 	struct request **old_heads = base->req_heads, **new_heads, *req;
3434 	int i;
3435 
3436 	ASSERT_LOCKED(base);
3437 	if (maxinflight < 1)
3438 		maxinflight = 1;
3439 	n_heads = (maxinflight+4) / 5;
3440 	EVUTIL_ASSERT(n_heads > 0);
3441 	new_heads = mm_calloc(n_heads, sizeof(struct request*));
3442 	if (!new_heads)
3443 		return (-1);
3444 	if (old_heads) {
3445 		for (i = 0; i < old_n_heads; ++i) {
3446 			while (old_heads[i]) {
3447 				req = old_heads[i];
3448 				evdns_request_remove(req, &old_heads[i]);
3449 				evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
3450 			}
3451 		}
3452 		mm_free(old_heads);
3453 	}
3454 	base->req_heads = new_heads;
3455 	base->n_req_heads = n_heads;
3456 	base->global_max_requests_inflight = maxinflight;
3457 	return (0);
3458 }
3459 
3460 /* exported function */
3461 int
evdns_base_set_option(struct evdns_base * base,const char * option,const char * val)3462 evdns_base_set_option(struct evdns_base *base,
3463     const char *option, const char *val)
3464 {
3465 	int res;
3466 	EVDNS_LOCK(base);
3467 	res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
3468 	EVDNS_UNLOCK(base);
3469 	return res;
3470 }
3471 
3472 static inline int
str_matches_option(const char * s1,const char * optionname)3473 str_matches_option(const char *s1, const char *optionname)
3474 {
3475 	/* Option names are given as "option:" We accept either 'option' in
3476 	 * s1, or 'option:randomjunk'.  The latter form is to implement the
3477 	 * resolv.conf parser. */
3478 	size_t optlen = strlen(optionname);
3479 	size_t slen = strlen(s1);
3480 	if (slen == optlen || slen == optlen - 1)
3481 		return !strncmp(s1, optionname, slen);
3482 	else if (slen > optlen)
3483 		return !strncmp(s1, optionname, optlen);
3484 	else
3485 		return 0;
3486 }
3487 
3488 static int
evdns_base_set_option_impl(struct evdns_base * base,const char * option,const char * val,int flags)3489 evdns_base_set_option_impl(struct evdns_base *base,
3490     const char *option, const char *val, int flags)
3491 {
3492 	ASSERT_LOCKED(base);
3493 	if (str_matches_option(option, "ndots:")) {
3494 		const int ndots = strtoint(val);
3495 		if (ndots == -1) return -1;
3496 		if (!(flags & DNS_OPTION_SEARCH)) return 0;
3497 		log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
3498 		if (!base->global_search_state) base->global_search_state = search_state_new();
3499 		if (!base->global_search_state) return -1;
3500 		base->global_search_state->ndots = ndots;
3501 	} else if (str_matches_option(option, "timeout:")) {
3502 		struct timeval tv;
3503 		if (evdns_strtotimeval(val, &tv) == -1) return -1;
3504 		if (!(flags & DNS_OPTION_MISC)) return 0;
3505 		log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
3506 		memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
3507 	} else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
3508 		struct timeval tv;
3509 		if (evdns_strtotimeval(val, &tv) == -1) return -1;
3510 		if (!(flags & DNS_OPTION_MISC)) return 0;
3511 		log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
3512 		    val);
3513 		memcpy(&base->global_getaddrinfo_allow_skew, &tv,
3514 		    sizeof(struct timeval));
3515 	} else if (str_matches_option(option, "max-timeouts:")) {
3516 		const int maxtimeout = strtoint_clipped(val, 1, 255);
3517 		if (maxtimeout == -1) return -1;
3518 		if (!(flags & DNS_OPTION_MISC)) return 0;
3519 		log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
3520 			maxtimeout);
3521 		base->global_max_nameserver_timeout = maxtimeout;
3522 	} else if (str_matches_option(option, "max-inflight:")) {
3523 		const int maxinflight = strtoint_clipped(val, 1, 65000);
3524 		if (maxinflight == -1) return -1;
3525 		if (!(flags & DNS_OPTION_MISC)) return 0;
3526 		log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
3527 			maxinflight);
3528 		evdns_base_set_max_requests_inflight(base, maxinflight);
3529 	} else if (str_matches_option(option, "attempts:")) {
3530 		int retries = strtoint(val);
3531 		if (retries == -1) return -1;
3532 		if (retries > 255) retries = 255;
3533 		if (!(flags & DNS_OPTION_MISC)) return 0;
3534 		log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
3535 		base->global_max_retransmits = retries;
3536 	} else if (str_matches_option(option, "randomize-case:")) {
3537 		int randcase = strtoint(val);
3538 		if (randcase == -1) return -1;
3539 		if (!(flags & DNS_OPTION_MISC)) return 0;
3540 		base->global_randomize_case = randcase;
3541 	} else if (str_matches_option(option, "bind-to:")) {
3542 		/* XXX This only applies to successive nameservers, not
3543 		 * to already-configured ones.	We might want to fix that. */
3544 		int len = sizeof(base->global_outgoing_address);
3545 		if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
3546 		if (evutil_parse_sockaddr_port(val,
3547 			(struct sockaddr*)&base->global_outgoing_address, &len))
3548 			return -1;
3549 		base->global_outgoing_addrlen = len;
3550 	} else if (str_matches_option(option, "initial-probe-timeout:")) {
3551 		struct timeval tv;
3552 		if (evdns_strtotimeval(val, &tv) == -1) return -1;
3553 		if (tv.tv_sec > 3600)
3554 			tv.tv_sec = 3600;
3555 		if (!(flags & DNS_OPTION_MISC)) return 0;
3556 		log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
3557 		    val);
3558 		memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
3559 		    sizeof(tv));
3560 	} else if (str_matches_option(option, "so-rcvbuf:")) {
3561 		int buf = strtoint(val);
3562 		if (buf == -1) return -1;
3563 		if (!(flags & DNS_OPTION_MISC)) return 0;
3564 		log(EVDNS_LOG_DEBUG, "Setting SO_RCVBUF to %s", val);
3565 		base->so_rcvbuf = buf;
3566 	} else if (str_matches_option(option, "so-sndbuf:")) {
3567 		int buf = strtoint(val);
3568 		if (buf == -1) return -1;
3569 		if (!(flags & DNS_OPTION_MISC)) return 0;
3570 		log(EVDNS_LOG_DEBUG, "Setting SO_SNDBUF to %s", val);
3571 		base->so_sndbuf = buf;
3572 	}
3573 	return 0;
3574 }
3575 
3576 int
evdns_set_option(const char * option,const char * val,int flags)3577 evdns_set_option(const char *option, const char *val, int flags)
3578 {
3579 	if (!current_base)
3580 		current_base = evdns_base_new(NULL, 0);
3581 	return evdns_base_set_option(current_base, option, val);
3582 }
3583 
3584 static void
resolv_conf_parse_line(struct evdns_base * base,char * const start,int flags)3585 resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
3586 	char *strtok_state;
3587 	static const char *const delims = " \t";
3588 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3589 
3590 
3591 	char *const first_token = strtok_r(start, delims, &strtok_state);
3592 	ASSERT_LOCKED(base);
3593 	if (!first_token) return;
3594 
3595 	if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
3596 		const char *const nameserver = NEXT_TOKEN;
3597 
3598 		if (nameserver)
3599 			evdns_base_nameserver_ip_add(base, nameserver);
3600 	} else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
3601 		const char *const domain = NEXT_TOKEN;
3602 		if (domain) {
3603 			search_postfix_clear(base);
3604 			search_postfix_add(base, domain);
3605 		}
3606 	} else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
3607 		const char *domain;
3608 		search_postfix_clear(base);
3609 
3610 		while ((domain = NEXT_TOKEN)) {
3611 			search_postfix_add(base, domain);
3612 		}
3613 		search_reverse(base);
3614 	} else if (!strcmp(first_token, "options")) {
3615 		const char *option;
3616 		while ((option = NEXT_TOKEN)) {
3617 			const char *val = strchr(option, ':');
3618 			evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
3619 		}
3620 	}
3621 #undef NEXT_TOKEN
3622 }
3623 
3624 /* exported function */
3625 /* returns: */
3626 /*   0 no errors */
3627 /*   1 failed to open file */
3628 /*   2 failed to stat file */
3629 /*   3 file too large */
3630 /*   4 out of memory */
3631 /*   5 short read from file */
3632 int
evdns_base_resolv_conf_parse(struct evdns_base * base,int flags,const char * const filename)3633 evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
3634 	int res;
3635 	EVDNS_LOCK(base);
3636 	res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
3637 	EVDNS_UNLOCK(base);
3638 	return res;
3639 }
3640 
3641 static char *
evdns_get_default_hosts_filename(void)3642 evdns_get_default_hosts_filename(void)
3643 {
3644 #ifdef _WIN32
3645 	/* Windows is a little coy about where it puts its configuration
3646 	 * files.  Sure, they're _usually_ in C:\windows\system32, but
3647 	 * there's no reason in principle they couldn't be in
3648 	 * W:\hoboken chicken emergency\
3649 	 */
3650 	char path[MAX_PATH+1];
3651 	static const char hostfile[] = "\\drivers\\etc\\hosts";
3652 	char *path_out;
3653 	size_t len_out;
3654 
3655 	if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
3656 		return NULL;
3657 	len_out = strlen(path)+strlen(hostfile)+1;
3658 	path_out = mm_malloc(len_out);
3659 	evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
3660 	return path_out;
3661 #else
3662 	return mm_strdup("/etc/hosts");
3663 #endif
3664 }
3665 
3666 static int
evdns_base_resolv_conf_parse_impl(struct evdns_base * base,int flags,const char * const filename)3667 evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
3668 	size_t n;
3669 	char *resolv;
3670 	char *start;
3671 	int err = 0;
3672 	int add_default;
3673 
3674 	log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
3675 
3676 	add_default = flags & DNS_OPTION_NAMESERVERS;
3677 	if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
3678 		add_default = 0;
3679 
3680 	if (flags & DNS_OPTION_HOSTSFILE) {
3681 		char *fname = evdns_get_default_hosts_filename();
3682 		evdns_base_load_hosts(base, fname);
3683 		if (fname)
3684 			mm_free(fname);
3685 	}
3686 
3687 	if (!filename) {
3688 		evdns_resolv_set_defaults(base, flags);
3689 		return 1;
3690 	}
3691 
3692 	if ((err = evutil_read_file_(filename, &resolv, &n, 0)) < 0) {
3693 		if (err == -1) {
3694 			/* No file. */
3695 			evdns_resolv_set_defaults(base, flags);
3696 			return 1;
3697 		} else {
3698 			return 2;
3699 		}
3700 	}
3701 
3702 	start = resolv;
3703 	for (;;) {
3704 		char *const newline = strchr(start, '\n');
3705 		if (!newline) {
3706 			resolv_conf_parse_line(base, start, flags);
3707 			break;
3708 		} else {
3709 			*newline = 0;
3710 			resolv_conf_parse_line(base, start, flags);
3711 			start = newline + 1;
3712 		}
3713 	}
3714 
3715 	if (!base->server_head && add_default) {
3716 		/* no nameservers were configured. */
3717 		evdns_base_nameserver_ip_add(base, "127.0.0.1");
3718 		err = 6;
3719 	}
3720 	if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
3721 		search_set_from_hostname(base);
3722 	}
3723 
3724 	mm_free(resolv);
3725 	return err;
3726 }
3727 
3728 int
evdns_resolv_conf_parse(int flags,const char * const filename)3729 evdns_resolv_conf_parse(int flags, const char *const filename) {
3730 	if (!current_base)
3731 		current_base = evdns_base_new(NULL, 0);
3732 	return evdns_base_resolv_conf_parse(current_base, flags, filename);
3733 }
3734 
3735 
3736 #ifdef _WIN32
3737 /* Add multiple nameservers from a space-or-comma-separated list. */
3738 static int
evdns_nameserver_ip_add_line(struct evdns_base * base,const char * ips)3739 evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
3740 	const char *addr;
3741 	char *buf;
3742 	int r;
3743 	ASSERT_LOCKED(base);
3744 	while (*ips) {
3745 		while (isspace(*ips) || *ips == ',' || *ips == '\t')
3746 			++ips;
3747 		addr = ips;
3748 		while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
3749 		    *ips=='[' || *ips==']')
3750 			++ips;
3751 		buf = mm_malloc(ips-addr+1);
3752 		if (!buf) return 4;
3753 		memcpy(buf, addr, ips-addr);
3754 		buf[ips-addr] = '\0';
3755 		r = evdns_base_nameserver_ip_add(base, buf);
3756 		mm_free(buf);
3757 		if (r) return r;
3758 	}
3759 	return 0;
3760 }
3761 
3762 typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
3763 
3764 /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
3765 /* figure out what our nameservers are. */
3766 static int
load_nameservers_with_getnetworkparams(struct evdns_base * base)3767 load_nameservers_with_getnetworkparams(struct evdns_base *base)
3768 {
3769 	/* Based on MSDN examples and inspection of  c-ares code. */
3770 	FIXED_INFO *fixed;
3771 	HMODULE handle = 0;
3772 	ULONG size = sizeof(FIXED_INFO);
3773 	void *buf = NULL;
3774 	int status = 0, r, added_any;
3775 	IP_ADDR_STRING *ns;
3776 	GetNetworkParams_fn_t fn;
3777 
3778 	ASSERT_LOCKED(base);
3779 	if (!(handle = evutil_load_windows_system_library_(
3780 			TEXT("iphlpapi.dll")))) {
3781 		log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
3782 		status = -1;
3783 		goto done;
3784 	}
3785 	if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
3786 		log(EVDNS_LOG_WARN, "Could not get address of function.");
3787 		status = -1;
3788 		goto done;
3789 	}
3790 
3791 	buf = mm_malloc(size);
3792 	if (!buf) { status = 4; goto done; }
3793 	fixed = buf;
3794 	r = fn(fixed, &size);
3795 	if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
3796 		status = -1;
3797 		goto done;
3798 	}
3799 	if (r != ERROR_SUCCESS) {
3800 		mm_free(buf);
3801 		buf = mm_malloc(size);
3802 		if (!buf) { status = 4; goto done; }
3803 		fixed = buf;
3804 		r = fn(fixed, &size);
3805 		if (r != ERROR_SUCCESS) {
3806 			log(EVDNS_LOG_DEBUG, "fn() failed.");
3807 			status = -1;
3808 			goto done;
3809 		}
3810 	}
3811 
3812 	EVUTIL_ASSERT(fixed);
3813 	added_any = 0;
3814 	ns = &(fixed->DnsServerList);
3815 	while (ns) {
3816 		r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
3817 		if (r) {
3818 			log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
3819 				(ns->IpAddress.String),(int)GetLastError());
3820 			status = r;
3821 		} else {
3822 			++added_any;
3823 			log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
3824 		}
3825 
3826 		ns = ns->Next;
3827 	}
3828 
3829 	if (!added_any) {
3830 		log(EVDNS_LOG_DEBUG, "No nameservers added.");
3831 		if (status == 0)
3832 			status = -1;
3833 	} else {
3834 		status = 0;
3835 	}
3836 
3837  done:
3838 	if (buf)
3839 		mm_free(buf);
3840 	if (handle)
3841 		FreeLibrary(handle);
3842 	return status;
3843 }
3844 
3845 static int
config_nameserver_from_reg_key(struct evdns_base * base,HKEY key,const TCHAR * subkey)3846 config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
3847 {
3848 	char *buf;
3849 	DWORD bufsz = 0, type = 0;
3850 	int status = 0;
3851 
3852 	ASSERT_LOCKED(base);
3853 	if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
3854 	    != ERROR_MORE_DATA)
3855 		return -1;
3856 	if (!(buf = mm_malloc(bufsz)))
3857 		return -1;
3858 
3859 	if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
3860 	    == ERROR_SUCCESS && bufsz > 1) {
3861 		status = evdns_nameserver_ip_add_line(base,buf);
3862 	}
3863 
3864 	mm_free(buf);
3865 	return status;
3866 }
3867 
3868 #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3869 #define WIN_NS_9X_KEY  SERVICES_KEY TEXT("VxD\\MSTCP")
3870 #define WIN_NS_NT_KEY  SERVICES_KEY TEXT("Tcpip\\Parameters")
3871 
3872 static int
load_nameservers_from_registry(struct evdns_base * base)3873 load_nameservers_from_registry(struct evdns_base *base)
3874 {
3875 	int found = 0;
3876 	int r;
3877 #define TRY(k, name) \
3878 	if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3879 		log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3880 		found = 1;						\
3881 	} else if (!found) {						\
3882 		log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3883 		    #k,#name);						\
3884 	}
3885 
3886 	ASSERT_LOCKED(base);
3887 
3888 	if (((int)GetVersion()) > 0) { /* NT */
3889 		HKEY nt_key = 0, interfaces_key = 0;
3890 
3891 		if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
3892 				 KEY_READ, &nt_key) != ERROR_SUCCESS) {
3893 			log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
3894 			return -1;
3895 		}
3896 		r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
3897 			     KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
3898 			     &interfaces_key);
3899 		if (r != ERROR_SUCCESS) {
3900 			log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
3901 			return -1;
3902 		}
3903 		TRY(nt_key, "NameServer");
3904 		TRY(nt_key, "DhcpNameServer");
3905 		TRY(interfaces_key, "NameServer");
3906 		TRY(interfaces_key, "DhcpNameServer");
3907 		RegCloseKey(interfaces_key);
3908 		RegCloseKey(nt_key);
3909 	} else {
3910 		HKEY win_key = 0;
3911 		if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
3912 				 KEY_READ, &win_key) != ERROR_SUCCESS) {
3913 			log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
3914 			return -1;
3915 		}
3916 		TRY(win_key, "NameServer");
3917 		RegCloseKey(win_key);
3918 	}
3919 
3920 	if (found == 0) {
3921 		log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
3922 	}
3923 
3924 	return found ? 0 : -1;
3925 #undef TRY
3926 }
3927 
3928 int
evdns_base_config_windows_nameservers(struct evdns_base * base)3929 evdns_base_config_windows_nameservers(struct evdns_base *base)
3930 {
3931 	int r;
3932 	char *fname;
3933 	if (base == NULL)
3934 		base = current_base;
3935 	if (base == NULL)
3936 		return -1;
3937 	EVDNS_LOCK(base);
3938 	fname = evdns_get_default_hosts_filename();
3939 	log(EVDNS_LOG_DEBUG, "Loading hosts entries from %s", fname);
3940 	evdns_base_load_hosts(base, fname);
3941 	if (fname)
3942 		mm_free(fname);
3943 
3944 	if (load_nameservers_with_getnetworkparams(base) == 0) {
3945 		EVDNS_UNLOCK(base);
3946 		return 0;
3947 	}
3948 	r = load_nameservers_from_registry(base);
3949 
3950 	EVDNS_UNLOCK(base);
3951 	return r;
3952 }
3953 
3954 int
evdns_config_windows_nameservers(void)3955 evdns_config_windows_nameservers(void)
3956 {
3957 	if (!current_base) {
3958 		current_base = evdns_base_new(NULL, 1);
3959 		return current_base == NULL ? -1 : 0;
3960 	} else {
3961 		return evdns_base_config_windows_nameservers(current_base);
3962 	}
3963 }
3964 #endif
3965 
3966 struct evdns_base *
evdns_base_new(struct event_base * event_base,int flags)3967 evdns_base_new(struct event_base *event_base, int flags)
3968 {
3969 	struct evdns_base *base;
3970 
3971 	if (evutil_secure_rng_init() < 0) {
3972 		log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
3973 		    "DNS can't run.");
3974 		return NULL;
3975 	}
3976 
3977 	/* Give the evutil library a hook into its evdns-enabled
3978 	 * functionality.  We can't just call evdns_getaddrinfo directly or
3979 	 * else libevent-core will depend on libevent-extras. */
3980 	evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo);
3981 	evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel);
3982 
3983 	base = mm_malloc(sizeof(struct evdns_base));
3984 	if (base == NULL)
3985 		return (NULL);
3986 	memset(base, 0, sizeof(struct evdns_base));
3987 	base->req_waiting_head = NULL;
3988 
3989 	EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
3990 	EVDNS_LOCK(base);
3991 
3992 	/* Set max requests inflight and allocate req_heads. */
3993 	base->req_heads = NULL;
3994 
3995 	evdns_base_set_max_requests_inflight(base, 64);
3996 
3997 	base->server_head = NULL;
3998 	base->event_base = event_base;
3999 	base->global_good_nameservers = base->global_requests_inflight =
4000 		base->global_requests_waiting = 0;
4001 
4002 	base->global_timeout.tv_sec = 5;
4003 	base->global_timeout.tv_usec = 0;
4004 	base->global_max_reissues = 1;
4005 	base->global_max_retransmits = 3;
4006 	base->global_max_nameserver_timeout = 3;
4007 	base->global_search_state = NULL;
4008 	base->global_randomize_case = 1;
4009 	base->global_getaddrinfo_allow_skew.tv_sec = 3;
4010 	base->global_getaddrinfo_allow_skew.tv_usec = 0;
4011 	base->global_nameserver_probe_initial_timeout.tv_sec = 10;
4012 	base->global_nameserver_probe_initial_timeout.tv_usec = 0;
4013 
4014 	TAILQ_INIT(&base->hostsdb);
4015 
4016 #define EVDNS_BASE_ALL_FLAGS ( \
4017 	EVDNS_BASE_INITIALIZE_NAMESERVERS | \
4018 	EVDNS_BASE_DISABLE_WHEN_INACTIVE  | \
4019 	EVDNS_BASE_NAMESERVERS_NO_DEFAULT | \
4020 	0)
4021 
4022 	if (flags & ~EVDNS_BASE_ALL_FLAGS) {
4023 		flags = EVDNS_BASE_INITIALIZE_NAMESERVERS;
4024 		log(EVDNS_LOG_WARN,
4025 		    "Unrecognized flag passed to evdns_base_new(). Assuming "
4026 		    "you meant EVDNS_BASE_INITIALIZE_NAMESERVERS.");
4027 	}
4028 #undef EVDNS_BASE_ALL_FLAGS
4029 
4030 	if (flags & EVDNS_BASE_INITIALIZE_NAMESERVERS) {
4031 		int r;
4032 		int opts = DNS_OPTIONS_ALL;
4033 		if (flags & EVDNS_BASE_NAMESERVERS_NO_DEFAULT) {
4034 			opts |= DNS_OPTION_NAMESERVERS_NO_DEFAULT;
4035 		}
4036 
4037 #ifdef _WIN32
4038 		r = evdns_base_config_windows_nameservers(base);
4039 #else
4040 		r = evdns_base_resolv_conf_parse(base, opts, "/etc/resolv.conf");
4041 #endif
4042 		if (r) {
4043 			evdns_base_free_and_unlock(base, 0);
4044 			return NULL;
4045 		}
4046 	}
4047 	if (flags & EVDNS_BASE_DISABLE_WHEN_INACTIVE) {
4048 		base->disable_when_inactive = 1;
4049 	}
4050 
4051 	EVDNS_UNLOCK(base);
4052 	return base;
4053 }
4054 
4055 int
evdns_init(void)4056 evdns_init(void)
4057 {
4058 	struct evdns_base *base = evdns_base_new(NULL, 1);
4059 	if (base) {
4060 		current_base = base;
4061 		return 0;
4062 	} else {
4063 		return -1;
4064 	}
4065 }
4066 
4067 const char *
evdns_err_to_string(int err)4068 evdns_err_to_string(int err)
4069 {
4070     switch (err) {
4071 	case DNS_ERR_NONE: return "no error";
4072 	case DNS_ERR_FORMAT: return "misformatted query";
4073 	case DNS_ERR_SERVERFAILED: return "server failed";
4074 	case DNS_ERR_NOTEXIST: return "name does not exist";
4075 	case DNS_ERR_NOTIMPL: return "query not implemented";
4076 	case DNS_ERR_REFUSED: return "refused";
4077 
4078 	case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
4079 	case DNS_ERR_UNKNOWN: return "unknown";
4080 	case DNS_ERR_TIMEOUT: return "request timed out";
4081 	case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
4082 	case DNS_ERR_CANCEL: return "dns request canceled";
4083 	case DNS_ERR_NODATA: return "no records in the reply";
4084 	default: return "[Unknown error code]";
4085     }
4086 }
4087 
4088 static void
evdns_nameserver_free(struct nameserver * server)4089 evdns_nameserver_free(struct nameserver *server)
4090 {
4091 	if (server->socket >= 0)
4092 		evutil_closesocket(server->socket);
4093 	(void) event_del(&server->event);
4094 	event_debug_unassign(&server->event);
4095 	if (server->state == 0)
4096 		(void) event_del(&server->timeout_event);
4097 	if (server->probe_request) {
4098 		evdns_cancel_request(server->base, server->probe_request);
4099 		server->probe_request = NULL;
4100 	}
4101 	event_debug_unassign(&server->timeout_event);
4102 	mm_free(server);
4103 }
4104 
4105 static void
evdns_base_free_and_unlock(struct evdns_base * base,int fail_requests)4106 evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
4107 {
4108 	struct nameserver *server, *server_next;
4109 	struct search_domain *dom, *dom_next;
4110 	int i;
4111 
4112 	/* Requires that we hold the lock. */
4113 
4114 	/* TODO(nickm) we might need to refcount here. */
4115 
4116 	while (base->req_waiting_head) {
4117 		if (fail_requests)
4118 			reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
4119 		request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
4120 	}
4121 	for (i = 0; i < base->n_req_heads; ++i) {
4122 		while (base->req_heads[i]) {
4123 			if (fail_requests)
4124 				reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
4125 			request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
4126 		}
4127 	}
4128 	base->global_requests_inflight = base->global_requests_waiting = 0;
4129 
4130 	for (server = base->server_head; server; server = server_next) {
4131 		server_next = server->next;
4132 		/** already done something before */
4133 		server->probe_request = NULL;
4134 		evdns_nameserver_free(server);
4135 		if (server_next == base->server_head)
4136 			break;
4137 	}
4138 	base->server_head = NULL;
4139 	base->global_good_nameservers = 0;
4140 
4141 	if (base->global_search_state) {
4142 		for (dom = base->global_search_state->head; dom; dom = dom_next) {
4143 			dom_next = dom->next;
4144 			mm_free(dom);
4145 		}
4146 		mm_free(base->global_search_state);
4147 		base->global_search_state = NULL;
4148 	}
4149 
4150 	{
4151 		struct hosts_entry *victim;
4152 		while ((victim = TAILQ_FIRST(&base->hostsdb))) {
4153 			TAILQ_REMOVE(&base->hostsdb, victim, next);
4154 			mm_free(victim);
4155 		}
4156 	}
4157 
4158 	mm_free(base->req_heads);
4159 
4160 	EVDNS_UNLOCK(base);
4161 	EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
4162 
4163 	mm_free(base);
4164 }
4165 
4166 void
evdns_base_free(struct evdns_base * base,int fail_requests)4167 evdns_base_free(struct evdns_base *base, int fail_requests)
4168 {
4169 	EVDNS_LOCK(base);
4170 	evdns_base_free_and_unlock(base, fail_requests);
4171 }
4172 
4173 void
evdns_base_clear_host_addresses(struct evdns_base * base)4174 evdns_base_clear_host_addresses(struct evdns_base *base)
4175 {
4176 	struct hosts_entry *victim;
4177 	EVDNS_LOCK(base);
4178 	while ((victim = TAILQ_FIRST(&base->hostsdb))) {
4179 		TAILQ_REMOVE(&base->hostsdb, victim, next);
4180 		mm_free(victim);
4181 	}
4182 	EVDNS_UNLOCK(base);
4183 }
4184 
4185 void
evdns_shutdown(int fail_requests)4186 evdns_shutdown(int fail_requests)
4187 {
4188 	if (current_base) {
4189 		struct evdns_base *b = current_base;
4190 		current_base = NULL;
4191 		evdns_base_free(b, fail_requests);
4192 	}
4193 	evdns_log_fn = NULL;
4194 }
4195 
4196 static int
evdns_base_parse_hosts_line(struct evdns_base * base,char * line)4197 evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
4198 {
4199 	char *strtok_state;
4200 	static const char *const delims = " \t";
4201 	char *const addr = strtok_r(line, delims, &strtok_state);
4202 	char *hostname, *hash;
4203 	struct sockaddr_storage ss;
4204 	int socklen = sizeof(ss);
4205 	ASSERT_LOCKED(base);
4206 
4207 #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
4208 
4209 	if (!addr || *addr == '#')
4210 		return 0;
4211 
4212 	memset(&ss, 0, sizeof(ss));
4213 	if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
4214 		return -1;
4215 	if (socklen > (int)sizeof(struct sockaddr_in6))
4216 		return -1;
4217 
4218 	if (sockaddr_getport((struct sockaddr*)&ss))
4219 		return -1;
4220 
4221 	while ((hostname = NEXT_TOKEN)) {
4222 		struct hosts_entry *he;
4223 		size_t namelen;
4224 		if ((hash = strchr(hostname, '#'))) {
4225 			if (hash == hostname)
4226 				return 0;
4227 			*hash = '\0';
4228 		}
4229 
4230 		namelen = strlen(hostname);
4231 
4232 		he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
4233 		if (!he)
4234 			return -1;
4235 		EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
4236 		memcpy(&he->addr, &ss, socklen);
4237 		memcpy(he->hostname, hostname, namelen+1);
4238 		he->addrlen = socklen;
4239 
4240 		TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
4241 
4242 		if (hash)
4243 			return 0;
4244 	}
4245 
4246 	return 0;
4247 #undef NEXT_TOKEN
4248 }
4249 
4250 static int
evdns_base_load_hosts_impl(struct evdns_base * base,const char * hosts_fname)4251 evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
4252 {
4253 	char *str=NULL, *cp, *eol;
4254 	size_t len;
4255 	int err=0;
4256 
4257 	ASSERT_LOCKED(base);
4258 
4259 	if (hosts_fname == NULL ||
4260 	    (err = evutil_read_file_(hosts_fname, &str, &len, 0)) < 0) {
4261 		char tmp[64];
4262 		strlcpy(tmp, "127.0.0.1   localhost", sizeof(tmp));
4263 		evdns_base_parse_hosts_line(base, tmp);
4264 		strlcpy(tmp, "::1   localhost", sizeof(tmp));
4265 		evdns_base_parse_hosts_line(base, tmp);
4266 		return err ? -1 : 0;
4267 	}
4268 
4269 	/* This will break early if there is a NUL in the hosts file.
4270 	 * Probably not a problem.*/
4271 	cp = str;
4272 	for (;;) {
4273 		eol = strchr(cp, '\n');
4274 
4275 		if (eol) {
4276 			*eol = '\0';
4277 			evdns_base_parse_hosts_line(base, cp);
4278 			cp = eol+1;
4279 		} else {
4280 			evdns_base_parse_hosts_line(base, cp);
4281 			break;
4282 		}
4283 	}
4284 
4285 	mm_free(str);
4286 	return 0;
4287 }
4288 
4289 int
evdns_base_load_hosts(struct evdns_base * base,const char * hosts_fname)4290 evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
4291 {
4292 	int res;
4293 	if (!base)
4294 		base = current_base;
4295 	EVDNS_LOCK(base);
4296 	res = evdns_base_load_hosts_impl(base, hosts_fname);
4297 	EVDNS_UNLOCK(base);
4298 	return res;
4299 }
4300 
4301 /* A single request for a getaddrinfo, either v4 or v6. */
4302 struct getaddrinfo_subrequest {
4303 	struct evdns_request *r;
4304 	ev_uint32_t type;
4305 };
4306 
4307 /* State data used to implement an in-progress getaddrinfo. */
4308 struct evdns_getaddrinfo_request {
4309 	struct evdns_base *evdns_base;
4310 	/* Copy of the modified 'hints' data that we'll use to build
4311 	 * answers. */
4312 	struct evutil_addrinfo hints;
4313 	/* The callback to invoke when we're done */
4314 	evdns_getaddrinfo_cb user_cb;
4315 	/* User-supplied data to give to the callback. */
4316 	void *user_data;
4317 	/* The port to use when building sockaddrs. */
4318 	ev_uint16_t port;
4319 	/* The sub_request for an A record (if any) */
4320 	struct getaddrinfo_subrequest ipv4_request;
4321 	/* The sub_request for an AAAA record (if any) */
4322 	struct getaddrinfo_subrequest ipv6_request;
4323 
4324 	/* The cname result that we were told (if any) */
4325 	char *cname_result;
4326 
4327 	/* If we have one request answered and one request still inflight,
4328 	 * then this field holds the answer from the first request... */
4329 	struct evutil_addrinfo *pending_result;
4330 	/* And this event is a timeout that will tell us to cancel the second
4331 	 * request if it's taking a long time. */
4332 	struct event timeout;
4333 
4334 	/* And this field holds the error code from the first request... */
4335 	int pending_error;
4336 	/* If this is set, the user canceled this request. */
4337 	unsigned user_canceled : 1;
4338 	/* If this is set, the user can no longer cancel this request; we're
4339 	 * just waiting for the free. */
4340 	unsigned request_done : 1;
4341 };
4342 
4343 /* Convert an evdns errors to the equivalent getaddrinfo error. */
4344 static int
evdns_err_to_getaddrinfo_err(int e1)4345 evdns_err_to_getaddrinfo_err(int e1)
4346 {
4347 	/* XXX Do this better! */
4348 	if (e1 == DNS_ERR_NONE)
4349 		return 0;
4350 	else if (e1 == DNS_ERR_NOTEXIST)
4351 		return EVUTIL_EAI_NONAME;
4352 	else
4353 		return EVUTIL_EAI_FAIL;
4354 }
4355 
4356 /* Return the more informative of two getaddrinfo errors. */
4357 static int
getaddrinfo_merge_err(int e1,int e2)4358 getaddrinfo_merge_err(int e1, int e2)
4359 {
4360 	/* XXXX be cleverer here. */
4361 	if (e1 == 0)
4362 		return e2;
4363 	else
4364 		return e1;
4365 }
4366 
4367 static void
free_getaddrinfo_request(struct evdns_getaddrinfo_request * data)4368 free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
4369 {
4370 	/* DO NOT CALL this if either of the requests is pending.  Only once
4371 	 * both callbacks have been invoked is it safe to free the request */
4372 	if (data->pending_result)
4373 		evutil_freeaddrinfo(data->pending_result);
4374 	if (data->cname_result)
4375 		mm_free(data->cname_result);
4376 	event_del(&data->timeout);
4377 	mm_free(data);
4378 	return;
4379 }
4380 
4381 static void
add_cname_to_reply(struct evdns_getaddrinfo_request * data,struct evutil_addrinfo * ai)4382 add_cname_to_reply(struct evdns_getaddrinfo_request *data,
4383     struct evutil_addrinfo *ai)
4384 {
4385 	if (data->cname_result && ai) {
4386 		ai->ai_canonname = data->cname_result;
4387 		data->cname_result = NULL;
4388 	}
4389 }
4390 
4391 /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
4392  * request has finished, but the other one took too long to answer. Pass
4393  * along the answer we got, and cancel the other request.
4394  */
4395 static void
evdns_getaddrinfo_timeout_cb(evutil_socket_t fd,short what,void * ptr)4396 evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
4397 {
4398 	int v4_timedout = 0, v6_timedout = 0;
4399 	struct evdns_getaddrinfo_request *data = ptr;
4400 
4401 	/* Cancel any pending requests, and note which one */
4402 	if (data->ipv4_request.r) {
4403 		/* XXXX This does nothing if the request's callback is already
4404 		 * running (pending_cb is set). */
4405 		evdns_cancel_request(NULL, data->ipv4_request.r);
4406 		v4_timedout = 1;
4407 		EVDNS_LOCK(data->evdns_base);
4408 		++data->evdns_base->getaddrinfo_ipv4_timeouts;
4409 		EVDNS_UNLOCK(data->evdns_base);
4410 	}
4411 	if (data->ipv6_request.r) {
4412 		/* XXXX This does nothing if the request's callback is already
4413 		 * running (pending_cb is set). */
4414 		evdns_cancel_request(NULL, data->ipv6_request.r);
4415 		v6_timedout = 1;
4416 		EVDNS_LOCK(data->evdns_base);
4417 		++data->evdns_base->getaddrinfo_ipv6_timeouts;
4418 		EVDNS_UNLOCK(data->evdns_base);
4419 	}
4420 
4421 	/* We only use this timeout callback when we have an answer for
4422 	 * one address. */
4423 	EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
4424 
4425 	/* Report the outcome of the other request that didn't time out. */
4426 	if (data->pending_result) {
4427 		add_cname_to_reply(data, data->pending_result);
4428 		data->user_cb(0, data->pending_result, data->user_data);
4429 		data->pending_result = NULL;
4430 	} else {
4431 		int e = data->pending_error;
4432 		if (!e)
4433 			e = EVUTIL_EAI_AGAIN;
4434 		data->user_cb(e, NULL, data->user_data);
4435 	}
4436 
4437 	data->user_cb = NULL; /* prevent double-call if evdns callbacks are
4438 			       * in-progress. XXXX It would be better if this
4439 			       * weren't necessary. */
4440 
4441 	if (!v4_timedout && !v6_timedout) {
4442 		/* should be impossible? XXXX */
4443 		free_getaddrinfo_request(data);
4444 	}
4445 }
4446 
4447 static int
evdns_getaddrinfo_set_timeout(struct evdns_base * evdns_base,struct evdns_getaddrinfo_request * data)4448 evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
4449     struct evdns_getaddrinfo_request *data)
4450 {
4451 	return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
4452 }
4453 
4454 static inline int
evdns_result_is_answer(int result)4455 evdns_result_is_answer(int result)
4456 {
4457 	return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
4458 	    result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
4459 }
4460 
4461 static void
evdns_getaddrinfo_gotresolve(int result,char type,int count,int ttl,void * addresses,void * arg)4462 evdns_getaddrinfo_gotresolve(int result, char type, int count,
4463     int ttl, void *addresses, void *arg)
4464 {
4465 	int i;
4466 	struct getaddrinfo_subrequest *req = arg;
4467 	struct getaddrinfo_subrequest *other_req;
4468 	struct evdns_getaddrinfo_request *data;
4469 
4470 	struct evutil_addrinfo *res;
4471 
4472 	struct sockaddr_in sin;
4473 	struct sockaddr_in6 sin6;
4474 	struct sockaddr *sa;
4475 	int socklen, addrlen;
4476 	void *addrp;
4477 	int err;
4478 	int user_canceled;
4479 
4480 	EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
4481 	if (req->type == DNS_IPv4_A) {
4482 		data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
4483 		other_req = &data->ipv6_request;
4484 	} else {
4485 		data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
4486 		other_req = &data->ipv4_request;
4487 	}
4488 
4489 	/** Called from evdns_base_free() with @fail_requests == 1 */
4490 	if (result != DNS_ERR_SHUTDOWN) {
4491 		EVDNS_LOCK(data->evdns_base);
4492 		if (evdns_result_is_answer(result)) {
4493 			if (req->type == DNS_IPv4_A)
4494 				++data->evdns_base->getaddrinfo_ipv4_answered;
4495 			else
4496 				++data->evdns_base->getaddrinfo_ipv6_answered;
4497 		}
4498 		user_canceled = data->user_canceled;
4499 		if (other_req->r == NULL)
4500 			data->request_done = 1;
4501 		EVDNS_UNLOCK(data->evdns_base);
4502 	} else {
4503 		data->evdns_base = NULL;
4504 		user_canceled = data->user_canceled;
4505 	}
4506 
4507 	req->r = NULL;
4508 
4509 	if (result == DNS_ERR_CANCEL && ! user_canceled) {
4510 		/* Internal cancel request from timeout or internal error.
4511 		 * we already answered the user. */
4512 		if (other_req->r == NULL)
4513 			free_getaddrinfo_request(data);
4514 		return;
4515 	}
4516 
4517 	if (data->user_cb == NULL) {
4518 		/* We already answered.  XXXX This shouldn't be needed; see
4519 		 * comments in evdns_getaddrinfo_timeout_cb */
4520 		free_getaddrinfo_request(data);
4521 		return;
4522 	}
4523 
4524 	if (result == DNS_ERR_NONE) {
4525 		if (count == 0)
4526 			err = EVUTIL_EAI_NODATA;
4527 		else
4528 			err = 0;
4529 	} else {
4530 		err = evdns_err_to_getaddrinfo_err(result);
4531 	}
4532 
4533 	if (err) {
4534 		/* Looks like we got an error. */
4535 		if (other_req->r) {
4536 			/* The other request is still working; maybe it will
4537 			 * succeed. */
4538 			/* XXXX handle failure from set_timeout */
4539 			if (result != DNS_ERR_SHUTDOWN) {
4540 				evdns_getaddrinfo_set_timeout(data->evdns_base, data);
4541 			}
4542 			data->pending_error = err;
4543 			return;
4544 		}
4545 
4546 		if (user_canceled) {
4547 			data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
4548 		} else if (data->pending_result) {
4549 			/* If we have an answer waiting, and we weren't
4550 			 * canceled, ignore this error. */
4551 			add_cname_to_reply(data, data->pending_result);
4552 			data->user_cb(0, data->pending_result, data->user_data);
4553 			data->pending_result = NULL;
4554 		} else {
4555 			if (data->pending_error)
4556 				err = getaddrinfo_merge_err(err,
4557 				    data->pending_error);
4558 			data->user_cb(err, NULL, data->user_data);
4559 		}
4560 		free_getaddrinfo_request(data);
4561 		return;
4562 	} else if (user_canceled) {
4563 		if (other_req->r) {
4564 			/* The other request is still working; let it hit this
4565 			 * callback with EVUTIL_EAI_CANCEL callback and report
4566 			 * the failure. */
4567 			return;
4568 		}
4569 		data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
4570 		free_getaddrinfo_request(data);
4571 		return;
4572 	}
4573 
4574 	/* Looks like we got some answers. We should turn them into addrinfos
4575 	 * and then either queue those or return them all. */
4576 	EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
4577 
4578 	if (type == DNS_IPv4_A) {
4579 		memset(&sin, 0, sizeof(sin));
4580 		sin.sin_family = AF_INET;
4581 		sin.sin_port = htons(data->port);
4582 
4583 		sa = (struct sockaddr *)&sin;
4584 		socklen = sizeof(sin);
4585 		addrlen = 4;
4586 		addrp = &sin.sin_addr.s_addr;
4587 	} else {
4588 		memset(&sin6, 0, sizeof(sin6));
4589 		sin6.sin6_family = AF_INET6;
4590 		sin6.sin6_port = htons(data->port);
4591 
4592 		sa = (struct sockaddr *)&sin6;
4593 		socklen = sizeof(sin6);
4594 		addrlen = 16;
4595 		addrp = &sin6.sin6_addr.s6_addr;
4596 	}
4597 
4598 	res = NULL;
4599 	for (i=0; i < count; ++i) {
4600 		struct evutil_addrinfo *ai;
4601 		memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
4602 		ai = evutil_new_addrinfo_(sa, socklen, &data->hints);
4603 		if (!ai) {
4604 			if (other_req->r) {
4605 				evdns_cancel_request(NULL, other_req->r);
4606 			}
4607 			data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
4608 			if (res)
4609 				evutil_freeaddrinfo(res);
4610 
4611 			if (other_req->r == NULL)
4612 				free_getaddrinfo_request(data);
4613 			return;
4614 		}
4615 		res = evutil_addrinfo_append_(res, ai);
4616 	}
4617 
4618 	if (other_req->r) {
4619 		/* The other request is still in progress; wait for it */
4620 		/* XXXX handle failure from set_timeout */
4621 		evdns_getaddrinfo_set_timeout(data->evdns_base, data);
4622 		data->pending_result = res;
4623 		return;
4624 	} else {
4625 		/* The other request is done or never started; append its
4626 		 * results (if any) and return them. */
4627 		if (data->pending_result) {
4628 			if (req->type == DNS_IPv4_A)
4629 				res = evutil_addrinfo_append_(res,
4630 				    data->pending_result);
4631 			else
4632 				res = evutil_addrinfo_append_(
4633 				    data->pending_result, res);
4634 			data->pending_result = NULL;
4635 		}
4636 
4637 		/* Call the user callback. */
4638 		add_cname_to_reply(data, res);
4639 		data->user_cb(0, res, data->user_data);
4640 
4641 		/* Free data. */
4642 		free_getaddrinfo_request(data);
4643 	}
4644 }
4645 
4646 static struct hosts_entry *
find_hosts_entry(struct evdns_base * base,const char * hostname,struct hosts_entry * find_after)4647 find_hosts_entry(struct evdns_base *base, const char *hostname,
4648     struct hosts_entry *find_after)
4649 {
4650 	struct hosts_entry *e;
4651 
4652 	if (find_after)
4653 		e = TAILQ_NEXT(find_after, next);
4654 	else
4655 		e = TAILQ_FIRST(&base->hostsdb);
4656 
4657 	for (; e; e = TAILQ_NEXT(e, next)) {
4658 		if (!evutil_ascii_strcasecmp(e->hostname, hostname))
4659 			return e;
4660 	}
4661 	return NULL;
4662 }
4663 
4664 static int
evdns_getaddrinfo_fromhosts(struct evdns_base * base,const char * nodename,struct evutil_addrinfo * hints,ev_uint16_t port,struct evutil_addrinfo ** res)4665 evdns_getaddrinfo_fromhosts(struct evdns_base *base,
4666     const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
4667     struct evutil_addrinfo **res)
4668 {
4669 	int n_found = 0;
4670 	struct hosts_entry *e;
4671 	struct evutil_addrinfo *ai=NULL;
4672 	int f = hints->ai_family;
4673 
4674 	EVDNS_LOCK(base);
4675 	for (e = find_hosts_entry(base, nodename, NULL); e;
4676 	    e = find_hosts_entry(base, nodename, e)) {
4677 		struct evutil_addrinfo *ai_new;
4678 		++n_found;
4679 		if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
4680 		    (e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
4681 			continue;
4682 		ai_new = evutil_new_addrinfo_(&e->addr.sa, e->addrlen, hints);
4683 		if (!ai_new) {
4684 			n_found = 0;
4685 			goto out;
4686 		}
4687 		sockaddr_setport(ai_new->ai_addr, port);
4688 		ai = evutil_addrinfo_append_(ai, ai_new);
4689 	}
4690 	EVDNS_UNLOCK(base);
4691 out:
4692 	if (n_found) {
4693 		/* Note that we return an empty answer if we found entries for
4694 		 * this hostname but none were of the right address type. */
4695 		*res = ai;
4696 		return 0;
4697 	} else {
4698 		if (ai)
4699 			evutil_freeaddrinfo(ai);
4700 		return -1;
4701 	}
4702 }
4703 
4704 struct evdns_getaddrinfo_request *
evdns_getaddrinfo(struct evdns_base * dns_base,const char * nodename,const char * servname,const struct evutil_addrinfo * hints_in,evdns_getaddrinfo_cb cb,void * arg)4705 evdns_getaddrinfo(struct evdns_base *dns_base,
4706     const char *nodename, const char *servname,
4707     const struct evutil_addrinfo *hints_in,
4708     evdns_getaddrinfo_cb cb, void *arg)
4709 {
4710 	struct evdns_getaddrinfo_request *data;
4711 	struct evutil_addrinfo hints;
4712 	struct evutil_addrinfo *res = NULL;
4713 	int err;
4714 	int port = 0;
4715 	int want_cname = 0;
4716 	int started = 0;
4717 
4718 	if (!dns_base) {
4719 		dns_base = current_base;
4720 		if (!dns_base) {
4721 			log(EVDNS_LOG_WARN,
4722 			    "Call to getaddrinfo_async with no "
4723 			    "evdns_base configured.");
4724 			cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
4725 			return NULL;
4726 		}
4727 	}
4728 
4729 	/* If we _must_ answer this immediately, do so. */
4730 	if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
4731 		res = NULL;
4732 		err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
4733 		cb(err, res, arg);
4734 		return NULL;
4735 	}
4736 
4737 	if (hints_in) {
4738 		memcpy(&hints, hints_in, sizeof(hints));
4739 	} else {
4740 		memset(&hints, 0, sizeof(hints));
4741 		hints.ai_family = PF_UNSPEC;
4742 	}
4743 
4744 	evutil_adjust_hints_for_addrconfig_(&hints);
4745 
4746 	/* Now try to see if we _can_ answer immediately. */
4747 	/* (It would be nice to do this by calling getaddrinfo directly, with
4748 	 * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
4749 	 * a reliable way to distinguish the "that wasn't a numeric host!" case
4750 	 * from any other EAI_NONAME cases.) */
4751 	err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
4752 	if (err != EVUTIL_EAI_NEED_RESOLVE) {
4753 		cb(err, res, arg);
4754 		return NULL;
4755 	}
4756 
4757 	/* If there is an entry in the hosts file, we should give it now. */
4758 	if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
4759 		cb(0, res, arg);
4760 		return NULL;
4761 	}
4762 
4763 	/* Okay, things are serious now. We're going to need to actually
4764 	 * launch a request.
4765 	 */
4766 	data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
4767 	if (!data) {
4768 		cb(EVUTIL_EAI_MEMORY, NULL, arg);
4769 		return NULL;
4770 	}
4771 
4772 	memcpy(&data->hints, &hints, sizeof(data->hints));
4773 	data->port = (ev_uint16_t)port;
4774 	data->ipv4_request.type = DNS_IPv4_A;
4775 	data->ipv6_request.type = DNS_IPv6_AAAA;
4776 	data->user_cb = cb;
4777 	data->user_data = arg;
4778 	data->evdns_base = dns_base;
4779 
4780 	want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
4781 
4782 	/* If we are asked for a PF_UNSPEC address, we launch two requests in
4783 	 * parallel: one for an A address and one for an AAAA address.  We
4784 	 * can't send just one request, since many servers only answer one
4785 	 * question per DNS request.
4786 	 *
4787 	 * Once we have the answer to one request, we allow for a short
4788 	 * timeout before we report it, to see if the other one arrives.  If
4789 	 * they both show up in time, then we report both the answers.
4790 	 *
4791 	 * If too many addresses of one type time out or fail, we should stop
4792 	 * launching those requests. (XXX we don't do that yet.)
4793 	 */
4794 
4795 	EVDNS_LOCK(dns_base);
4796 
4797 	if (hints.ai_family != PF_INET6) {
4798 		log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
4799 		    nodename, &data->ipv4_request);
4800 
4801 		data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
4802 		    nodename, 0, evdns_getaddrinfo_gotresolve,
4803 		    &data->ipv4_request);
4804 		if (want_cname && data->ipv4_request.r)
4805 			data->ipv4_request.r->current_req->put_cname_in_ptr =
4806 			    &data->cname_result;
4807 	}
4808 	if (hints.ai_family != PF_INET) {
4809 		log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
4810 		    nodename, &data->ipv6_request);
4811 
4812 		data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
4813 		    nodename, 0, evdns_getaddrinfo_gotresolve,
4814 		    &data->ipv6_request);
4815 		if (want_cname && data->ipv6_request.r)
4816 			data->ipv6_request.r->current_req->put_cname_in_ptr =
4817 			    &data->cname_result;
4818 	}
4819 
4820 	evtimer_assign(&data->timeout, dns_base->event_base,
4821 	    evdns_getaddrinfo_timeout_cb, data);
4822 
4823 	started = (data->ipv4_request.r || data->ipv6_request.r);
4824 
4825 	EVDNS_UNLOCK(dns_base);
4826 
4827 	if (started) {
4828 		return data;
4829 	} else {
4830 		mm_free(data);
4831 		cb(EVUTIL_EAI_FAIL, NULL, arg);
4832 		return NULL;
4833 	}
4834 }
4835 
4836 void
evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request * data)4837 evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
4838 {
4839 	EVDNS_LOCK(data->evdns_base);
4840 	if (data->request_done) {
4841 		EVDNS_UNLOCK(data->evdns_base);
4842 		return;
4843 	}
4844 	event_del(&data->timeout);
4845 	data->user_canceled = 1;
4846 	if (data->ipv4_request.r)
4847 		evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
4848 	if (data->ipv6_request.r)
4849 		evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
4850 	EVDNS_UNLOCK(data->evdns_base);
4851 }
4852