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