xref: /libevent-2.1.12/evdns.c (revision c2972453)
1e49e2891SNick Mathewson /* Copyright 2006-2007 Niels Provos
2e49e2891SNick Mathewson  * Copyright 2007-2012 Nick Mathewson and Niels Provos
3cca7249eSNiels Provos  *
4e49e2891SNick Mathewson  * Redistribution and use in source and binary forms, with or without
5e49e2891SNick Mathewson  * modification, are permitted provided that the following conditions
6e49e2891SNick Mathewson  * are met:
7e49e2891SNick Mathewson  * 1. Redistributions of source code must retain the above copyright
8e49e2891SNick Mathewson  *    notice, this list of conditions and the following disclaimer.
9e49e2891SNick Mathewson  * 2. Redistributions in binary form must reproduce the above copyright
10e49e2891SNick Mathewson  *    notice, this list of conditions and the following disclaimer in the
11e49e2891SNick Mathewson  *    documentation and/or other materials provided with the distribution.
12e49e2891SNick Mathewson  * 3. The name of the author may not be used to endorse or promote products
13e49e2891SNick Mathewson  *    derived from this software without specific prior written permission.
14cca7249eSNiels Provos  *
15e49e2891SNick Mathewson  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16e49e2891SNick Mathewson  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17e49e2891SNick Mathewson  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18e49e2891SNick Mathewson  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19e49e2891SNick Mathewson  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20e49e2891SNick Mathewson  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21e49e2891SNick Mathewson  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22e49e2891SNick Mathewson  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23e49e2891SNick Mathewson  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24e49e2891SNick Mathewson  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25cca7249eSNiels Provos  */
26cca7249eSNiels Provos 
27e49e2891SNick Mathewson /* Based on software by Adam Langly. Adam's original message:
28e49e2891SNick Mathewson  *
29e49e2891SNick Mathewson  * Async DNS Library
30cca7249eSNiels Provos  * Adam Langley <[email protected]>
31cca7249eSNiels Provos  * http://www.imperialviolet.org/eventdns.html
32fe1dfe0fSNiels Provos  * Public Domain code
33cca7249eSNiels Provos  *
34cca7249eSNiels Provos  * This software is Public Domain. To view a copy of the public domain dedication,
35cca7249eSNiels Provos  * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
36cca7249eSNiels Provos  * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
37cca7249eSNiels Provos  *
38cca7249eSNiels Provos  * I ask and expect, but do not require, that all derivative works contain an
39cca7249eSNiels Provos  * attribution similar to:
40cca7249eSNiels Provos  *	Parts developed by Adam Langley <[email protected]>
41cca7249eSNiels Provos  *
42cca7249eSNiels Provos  * You may wish to replace the word "Parts" with something else depending on
43cca7249eSNiels Provos  * the amount of original code.
44cca7249eSNiels Provos  *
45cca7249eSNiels Provos  * (Derivative works does not include programs which link against, run or include
46cca7249eSNiels Provos  * the source verbatim in their source distributions)
47cca7249eSNiels Provos  *
48cca7249eSNiels Provos  * Version: 0.1b
49cca7249eSNiels Provos  */
50cca7249eSNiels Provos 
51ec347b92SNick Mathewson #include "event2/event-config.h"
520915ca0aSKevin Bowling #include "evconfig-private.h"
530915ca0aSKevin Bowling 
540915ca0aSKevin Bowling #include <sys/types.h>
55d0d8f9b4SNiels Provos 
56e83a32dfSNick Mathewson #ifndef _FORTIFY_SOURCE
57cca7249eSNiels Provos #define _FORTIFY_SOURCE 3
58e83a32dfSNick Mathewson #endif
59cca7249eSNiels Provos 
60cca7249eSNiels Provos #include <string.h>
61cca7249eSNiels Provos #include <fcntl.h>
6268120d9bSNick Mathewson #ifdef EVENT__HAVE_SYS_TIME_H
63cca7249eSNiels Provos #include <sys/time.h>
644e1ec3e0SNick Mathewson #endif
6568120d9bSNick Mathewson #ifdef EVENT__HAVE_STDINT_H
66cca7249eSNiels Provos #include <stdint.h>
67ddf70659SNiels Provos #endif
68cca7249eSNiels Provos #include <stdlib.h>
69cca7249eSNiels Provos #include <string.h>
70cca7249eSNiels Provos #include <errno.h>
7168120d9bSNick Mathewson #ifdef EVENT__HAVE_UNISTD_H
72cca7249eSNiels Provos #include <unistd.h>
734e1ec3e0SNick Mathewson #endif
74cca7249eSNiels Provos #include <limits.h>
75cca7249eSNiels Provos #include <sys/stat.h>
76cca7249eSNiels Provos #include <stdio.h>
77cca7249eSNiels Provos #include <stdarg.h>
789f560bfaSNick Mathewson #ifdef _WIN32
79e865eb93SNick Mathewson #include <winsock2.h>
809559349cSyuangongji #include <winerror.h>
81e865eb93SNick Mathewson #include <ws2tcpip.h>
82da6135e3SNick Mathewson #ifndef _WIN32_IE
8366c02c78SNick Mathewson #define _WIN32_IE 0x400
84da6135e3SNick Mathewson #endif
8566c02c78SNick Mathewson #include <shlobj.h>
86e865eb93SNick Mathewson #endif
87cca7249eSNiels Provos 
88fbe64f21SEvan Jones #include "event2/dns.h"
89fbe64f21SEvan Jones #include "event2/dns_struct.h"
90fbe64f21SEvan Jones #include "event2/dns_compat.h"
91fbe64f21SEvan Jones #include "event2/util.h"
92fbe64f21SEvan Jones #include "event2/event.h"
93fbe64f21SEvan Jones #include "event2/event_struct.h"
94fbe64f21SEvan Jones #include "event2/thread.h"
95ac3fc991SNick Mathewson 
962d9619d7SNick Mathewson #include "defer-internal.h"
97169321c9SNick Mathewson #include "log-internal.h"
987eb250e9SNick Mathewson #include "mm-internal.h"
99dd731685SNick Mathewson #include "strlcpy-internal.h"
100980bcd68SNick Mathewson #include "ipv6-internal.h"
10181ab45adSNick Mathewson #include "util-internal.h"
102327165b3SNick Mathewson #include "evthread-internal.h"
1039f560bfaSNick Mathewson #ifdef _WIN32
104cd731b77SNick Mathewson #include <ctype.h>
1055b5b880bSNick Mathewson #include <winsock2.h>
1064e1ec3e0SNick Mathewson #include <windows.h>
107fe1dfe0fSNiels Provos #include <iphlpapi.h>
1084e1ec3e0SNick Mathewson #include <io.h>
109fe1dfe0fSNiels Provos #else
110fe1dfe0fSNiels Provos #include <sys/socket.h>
111fe1dfe0fSNiels Provos #include <netinet/in.h>
112fe1dfe0fSNiels Provos #include <arpa/inet.h>
113fe1dfe0fSNiels Provos #endif
114fe1dfe0fSNiels Provos 
11568120d9bSNick Mathewson #ifdef EVENT__HAVE_NETINET_IN6_H
1166318fca2SNiels Provos #include <netinet/in6.h>
1176318fca2SNiels Provos #endif
1186318fca2SNiels Provos 
119e1766a1bSNick Mathewson #define EVDNS_LOG_DEBUG EVENT_LOG_DEBUG
120e1766a1bSNick Mathewson #define EVDNS_LOG_WARN EVENT_LOG_WARN
121e1766a1bSNick Mathewson #define EVDNS_LOG_MSG EVENT_LOG_MSG
122d0d8f9b4SNiels Provos 
123cca7249eSNiels Provos #ifndef HOST_NAME_MAX
124cca7249eSNiels Provos #define HOST_NAME_MAX 255
125cca7249eSNiels Provos #endif
126cca7249eSNiels Provos 
127cca7249eSNiels Provos #include <stdio.h>
128cca7249eSNiels Provos 
129cca7249eSNiels Provos #undef MIN
130cca7249eSNiels Provos #define MIN(a,b) ((a)<(b)?(a):(b))
131cca7249eSNiels Provos 
13267072f3cSChristopher Davis #define ASSERT_VALID_REQUEST(req) \
13367072f3cSChristopher Davis 	EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
13467072f3cSChristopher Davis 
1354e1ec3e0SNick Mathewson #define u64 ev_uint64_t
1364e1ec3e0SNick Mathewson #define u32 ev_uint32_t
1374e1ec3e0SNick Mathewson #define u16 ev_uint16_t
1384e1ec3e0SNick Mathewson #define u8  ev_uint8_t
1394e1ec3e0SNick Mathewson 
14086f57420SNick Mathewson /* maximum number of addresses from a single packet */
14186f57420SNick Mathewson /* that we bother recording */
14286f57420SNick Mathewson #define MAX_V4_ADDRS 32
14386f57420SNick Mathewson #define MAX_V6_ADDRS 32
14486f57420SNick Mathewson 
145cca7249eSNiels Provos 
146faf5f73aSNiels Provos #define TYPE_A	       EVDNS_TYPE_A
147cca7249eSNiels Provos #define TYPE_CNAME     5
148faf5f73aSNiels Provos #define TYPE_PTR       EVDNS_TYPE_PTR
149f72e8f66SLeonid Evdokimov #define TYPE_SOA       EVDNS_TYPE_SOA
150faf5f73aSNiels Provos #define TYPE_AAAA      EVDNS_TYPE_AAAA
151cca7249eSNiels Provos 
152faf5f73aSNiels Provos #define CLASS_INET     EVDNS_CLASS_INET
153cca7249eSNiels Provos 
154ceefbe87SNick Mathewson /* Persistent handle.  We keep this separate from 'struct request' since we
155ceefbe87SNick Mathewson  * need some object to last for as long as an evdns_request is outstanding so
15649418612SNick Mathewson  * that it can be canceled, whereas a search request can lead to multiple
157ceefbe87SNick Mathewson  * 'struct request' instances being created over its lifetime. */
158803dc36aSNick Mathewson struct evdns_request {
15915bb82d6SChristopher Davis 	struct request *current_req;
1609ed30de7SNick Mathewson 	struct evdns_base *base;
1619ed30de7SNick Mathewson 
1629ed30de7SNick Mathewson 	int pending_cb; /* Waiting for its callback to be invoked; not
1639ed30de7SNick Mathewson 			 * owned by event base any more. */
164beaa14a4SChristopher Davis 
165beaa14a4SChristopher Davis 	/* elements used by the searching code */
166beaa14a4SChristopher Davis 	int search_index;
167beaa14a4SChristopher Davis 	struct search_state *search_state;
168beaa14a4SChristopher Davis 	char *search_origname;	/* needs to be free()ed */
169beaa14a4SChristopher Davis 	int search_flags;
17015bb82d6SChristopher Davis };
17115bb82d6SChristopher Davis 
17215bb82d6SChristopher Davis struct request {
1737c6df310SNiels Provos 	u8 *request;  /* the dns packet data */
17486f57420SNick Mathewson 	u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
175fe1dfe0fSNiels Provos 	unsigned int request_len;
176cca7249eSNiels Provos 	int reissue_count;
1777c6df310SNiels Provos 	int tx_count;  /* the number of times that this packet has been sent */
1787c6df310SNiels Provos 	void *user_pointer;  /* the pointer given to us for this request */
17952bfcab8SNiels Provos 	evdns_callback_type user_callback;
1807c6df310SNiels Provos 	struct nameserver *ns;	/* the server which we last sent it */
181cca7249eSNiels Provos 
1827c6df310SNiels Provos 	/* these objects are kept in a circular list */
183d6094b16SNick Mathewson 	/* XXX We could turn this into a CIRCLEQ. */
18415bb82d6SChristopher Davis 	struct request *next, *prev;
185cca7249eSNiels Provos 
186cca7249eSNiels Provos 	struct event timeout_event;
187cca7249eSNiels Provos 
1887c6df310SNiels Provos 	u16 trans_id;  /* the transaction id */
18986f57420SNick Mathewson 	unsigned request_appended :1;	/* true if the request pointer is data which follows this struct */
19086f57420SNick Mathewson 	unsigned transmit_me :1;  /* needs to be transmitted */
19186f57420SNick Mathewson 
19286f57420SNick Mathewson 	/* XXXX This is a horrible hack. */
19386f57420SNick Mathewson 	char **put_cname_in_ptr; /* store the cname here if we get one. */
194e688a88aSNick Mathewson 
195e688a88aSNick Mathewson 	struct evdns_base *base;
19615bb82d6SChristopher Davis 
19715bb82d6SChristopher Davis 	struct evdns_request *handle;
198cca7249eSNiels Provos };
199cca7249eSNiels Provos 
200fe1dfe0fSNiels Provos struct reply {
201fe1dfe0fSNiels Provos 	unsigned int type;
20286f57420SNick Mathewson 	unsigned int have_answer : 1;
203fe1dfe0fSNiels Provos 	union {
204fe1dfe0fSNiels Provos 		struct {
205fe1dfe0fSNiels Provos 			u32 addrcount;
20686f57420SNick Mathewson 			u32 addresses[MAX_V4_ADDRS];
207fe1dfe0fSNiels Provos 		} a;
208fe1dfe0fSNiels Provos 		struct {
2096318fca2SNiels Provos 			u32 addrcount;
21086f57420SNick Mathewson 			struct in6_addr addresses[MAX_V6_ADDRS];
2116318fca2SNiels Provos 		} aaaa;
2126318fca2SNiels Provos 		struct {
213fe1dfe0fSNiels Provos 			char name[HOST_NAME_MAX];
214fe1dfe0fSNiels Provos 		} ptr;
215fe1dfe0fSNiels Provos 	} data;
216fe1dfe0fSNiels Provos };
217fe1dfe0fSNiels Provos 
218cca7249eSNiels Provos struct nameserver {
2191120f04fSNick Mathewson 	evutil_socket_t socket;	 /* a connected UDP socket */
220135591aeSNick Mathewson 	struct sockaddr_storage address;
2217c20a6aeSNick Mathewson 	ev_socklen_t addrlen;
2227c6df310SNiels Provos 	int failed_times;  /* number of times which we have given this server a chance */
2237c6df310SNiels Provos 	int timedout;  /* number of times in a row a request has timed out */
224cca7249eSNiels Provos 	struct event event;
2257c6df310SNiels Provos 	/* these objects are kept in a circular list */
226cca7249eSNiels Provos 	struct nameserver *next, *prev;
2277c6df310SNiels Provos 	struct event timeout_event;  /* used to keep the timeout for */
2287c6df310SNiels Provos 				     /* when we next probe this server. */
2297c6df310SNiels Provos 				     /* Valid if state == 0 */
230684c022aSNick Mathewson 	/* Outstanding probe request for this nameserver, if any */
231684c022aSNick Mathewson 	struct evdns_request *probe_request;
2327c6df310SNiels Provos 	char state;  /* zero if we think that this server is down */
2337c6df310SNiels Provos 	char choked;  /* true if we have an EAGAIN from this server's socket */
2347c6df310SNiels Provos 	char write_waiting;  /* true if we are waiting for EV_WRITE events */
235e688a88aSNick Mathewson 	struct evdns_base *base;
2366b7fa620SAzat Khuzhin 
2376b7fa620SAzat Khuzhin 	/* Number of currently inflight requests: used
2386b7fa620SAzat Khuzhin 	 * to track when we should add/del the event. */
2396b7fa620SAzat Khuzhin 	int requests_inflight;
240cca7249eSNiels Provos };
241cca7249eSNiels Provos 
242cca7249eSNiels Provos 
2437c6df310SNiels Provos /* Represents a local port where we're listening for DNS requests. Right now, */
2447c6df310SNiels Provos /* only UDP is supported. */
245faf5f73aSNiels Provos struct evdns_server_port {
2461120f04fSNick Mathewson 	evutil_socket_t socket; /* socket we use to read queries and write replies. */
2477c6df310SNiels Provos 	int refcnt; /* reference count. */
2487c6df310SNiels Provos 	char choked; /* Are we currently blocked from writing? */
2497c6df310SNiels Provos 	char closing; /* Are we trying to close this port, pending writes? */
2507c6df310SNiels Provos 	evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
2517c6df310SNiels Provos 	void *user_data; /* Opaque pointer passed to user_callback */
2527c6df310SNiels Provos 	struct event event; /* Read/write event */
2537c6df310SNiels Provos 	/* circular list of replies that we want to write. */
254faf5f73aSNiels Provos 	struct server_request *pending_replies;
255e688a88aSNick Mathewson 	struct event_base *event_base;
256327165b3SNick Mathewson 
25768120d9bSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
258327165b3SNick Mathewson 	void *lock;
259327165b3SNick Mathewson #endif
260faf5f73aSNiels Provos };
261faf5f73aSNiels Provos 
2627c6df310SNiels Provos /* Represents part of a reply being built.	(That is, a single RR.) */
263faf5f73aSNiels Provos struct server_reply_item {
2647c6df310SNiels Provos 	struct server_reply_item *next; /* next item in sequence. */
2657c6df310SNiels Provos 	char *name; /* name part of the RR */
2669516df0eSNick Mathewson 	u16 type; /* The RR type */
2679516df0eSNick Mathewson 	u16 class; /* The RR class (usually CLASS_INET) */
2687c6df310SNiels Provos 	u32 ttl; /* The RR TTL */
2697c6df310SNiels Provos 	char is_name; /* True iff data is a label */
2707c6df310SNiels Provos 	u16 datalen; /* Length of data; -1 if data is a label */
2717c6df310SNiels Provos 	void *data; /* The contents of the RR */
272faf5f73aSNiels Provos };
273faf5f73aSNiels Provos 
2747c6df310SNiels Provos /* Represents a request that we've received as a DNS server, and holds */
2757c6df310SNiels Provos /* the components of the reply as we're constructing it. */
276faf5f73aSNiels Provos struct server_request {
2777c6df310SNiels Provos 	/* Pointers to the next and previous entries on the list of replies */
2787c6df310SNiels Provos 	/* that we're waiting to write.	 Only set if we have tried to respond */
2797c6df310SNiels Provos 	/* and gotten EAGAIN. */
280faf5f73aSNiels Provos 	struct server_request *next_pending;
281faf5f73aSNiels Provos 	struct server_request *prev_pending;
282faf5f73aSNiels Provos 
2837c6df310SNiels Provos 	u16 trans_id; /* Transaction id. */
2847c6df310SNiels Provos 	struct evdns_server_port *port; /* Which port received this request on? */
2857c6df310SNiels Provos 	struct sockaddr_storage addr; /* Where to send the response */
2867c20a6aeSNick Mathewson 	ev_socklen_t addrlen; /* length of addr */
287faf5f73aSNiels Provos 
2887c6df310SNiels Provos 	int n_answer; /* how many answer RRs have been set? */
2897c6df310SNiels Provos 	int n_authority; /* how many authority RRs have been set? */
2907c6df310SNiels Provos 	int n_additional; /* how many additional RRs have been set? */
291faf5f73aSNiels Provos 
2927c6df310SNiels Provos 	struct server_reply_item *answer; /* linked list of answer RRs */
2937c6df310SNiels Provos 	struct server_reply_item *authority; /* linked list of authority RRs */
2947c6df310SNiels Provos 	struct server_reply_item *additional; /* linked list of additional RRs */
295faf5f73aSNiels Provos 
2967c6df310SNiels Provos 	/* Constructed response.  Only set once we're ready to send a reply. */
2977c6df310SNiels Provos 	/* Once this is set, the RR fields are cleared, and no more should be set. */
298faf5f73aSNiels Provos 	char *response;
299faf5f73aSNiels Provos 	size_t response_len;
300faf5f73aSNiels Provos 
3017c6df310SNiels Provos 	/* Caller-visible fields: flags, questions. */
302faf5f73aSNiels Provos 	struct evdns_server_request base;
303faf5f73aSNiels Provos };
304faf5f73aSNiels Provos 
305e688a88aSNick Mathewson struct evdns_base {
30649868b61SNick Mathewson 	/* An array of n_req_heads circular lists for inflight requests.
30749868b61SNick Mathewson 	 * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
30849868b61SNick Mathewson 	 */
30915bb82d6SChristopher Davis 	struct request **req_heads;
31049868b61SNick Mathewson 	/* A circular list of requests that we're waiting to send, but haven't
31149868b61SNick Mathewson 	 * sent yet because there are too many requests inflight */
31215bb82d6SChristopher Davis 	struct request *req_waiting_head;
31349868b61SNick Mathewson 	/* A circular list of nameservers. */
314e688a88aSNick Mathewson 	struct nameserver *server_head;
31549868b61SNick Mathewson 	int n_req_heads;
316e688a88aSNick Mathewson 
317e688a88aSNick Mathewson 	struct event_base *event_base;
318e688a88aSNick Mathewson 
319e688a88aSNick Mathewson 	/* The number of good nameservers that we have */
320e688a88aSNick Mathewson 	int global_good_nameservers;
321e688a88aSNick Mathewson 
322e688a88aSNick Mathewson 	/* inflight requests are contained in the req_head list */
323e688a88aSNick Mathewson 	/* and are actually going out across the network */
324e688a88aSNick Mathewson 	int global_requests_inflight;
325e688a88aSNick Mathewson 	/* requests which aren't inflight are in the waiting list */
326e688a88aSNick Mathewson 	/* and are counted here */
327e688a88aSNick Mathewson 	int global_requests_waiting;
328e688a88aSNick Mathewson 
329e688a88aSNick Mathewson 	int global_max_requests_inflight;
330e688a88aSNick Mathewson 
33186f57420SNick Mathewson 	struct timeval global_timeout;	/* 5 seconds by default */
332e688a88aSNick Mathewson 	int global_max_reissues;  /* a reissue occurs when we get some errors from the server */
333e688a88aSNick Mathewson 	int global_max_retransmits;  /* number of times we'll retransmit a request which timed out */
334e688a88aSNick Mathewson 	/* number of timeouts in a row before we consider this server to be down */
335e688a88aSNick Mathewson 	int global_max_nameserver_timeout;
336dd731685SNick Mathewson 	/* true iff we will use the 0x20 hack to prevent poisoning attacks. */
337dd731685SNick Mathewson 	int global_randomize_case;
338e688a88aSNick Mathewson 
3391e56a32dSNick Mathewson 	/* The first time that a nameserver fails, how long do we wait before
3401e56a32dSNick Mathewson 	 * probing to see if it has returned?  */
3411e56a32dSNick Mathewson 	struct timeval global_nameserver_probe_initial_timeout;
3421e56a32dSNick Mathewson 
34377c80b8dSNick Mathewson 	/** Port to bind to for outgoing DNS packets. */
34477c80b8dSNick Mathewson 	struct sockaddr_storage global_outgoing_address;
3457c20a6aeSNick Mathewson 	/** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
3467c20a6aeSNick Mathewson 	ev_socklen_t global_outgoing_addrlen;
34777c80b8dSNick Mathewson 
34886f57420SNick Mathewson 	struct timeval global_getaddrinfo_allow_skew;
34986f57420SNick Mathewson 
350546a366cSAzat Khuzhin 	int so_rcvbuf;
351546a366cSAzat Khuzhin 	int so_sndbuf;
352546a366cSAzat Khuzhin 
35386f57420SNick Mathewson 	int getaddrinfo_ipv4_timeouts;
35486f57420SNick Mathewson 	int getaddrinfo_ipv6_timeouts;
35586f57420SNick Mathewson 	int getaddrinfo_ipv4_answered;
35686f57420SNick Mathewson 	int getaddrinfo_ipv6_answered;
35786f57420SNick Mathewson 
358e688a88aSNick Mathewson 	struct search_state *global_search_state;
359327165b3SNick Mathewson 
36072dd6667SNick Mathewson 	TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
36172dd6667SNick Mathewson 
36268120d9bSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
363327165b3SNick Mathewson 	void *lock;
364327165b3SNick Mathewson #endif
3656b7fa620SAzat Khuzhin 
3666b7fa620SAzat Khuzhin 	int disable_when_inactive;
367e688a88aSNick Mathewson };
368e688a88aSNick Mathewson 
36972dd6667SNick Mathewson struct hosts_entry {
37072dd6667SNick Mathewson 	TAILQ_ENTRY(hosts_entry) next;
37172dd6667SNick Mathewson 	union {
37272dd6667SNick Mathewson 		struct sockaddr sa;
37372dd6667SNick Mathewson 		struct sockaddr_in sin;
37472dd6667SNick Mathewson 		struct sockaddr_in6 sin6;
37572dd6667SNick Mathewson 	} addr;
37672dd6667SNick Mathewson 	int addrlen;
37772dd6667SNick Mathewson 	char hostname[1];
37872dd6667SNick Mathewson };
37972dd6667SNick Mathewson 
380e688a88aSNick Mathewson static struct evdns_base *current_base = NULL;
381e688a88aSNick Mathewson 
38286f57420SNick Mathewson struct evdns_base *
evdns_get_global_base(void)38386f57420SNick Mathewson evdns_get_global_base(void)
38486f57420SNick Mathewson {
38586f57420SNick Mathewson 	return current_base;
38686f57420SNick Mathewson }
38786f57420SNick Mathewson 
3887c6df310SNiels Provos /* Given a pointer to an evdns_server_request, get the corresponding */
3897c6df310SNiels Provos /* server_request. */
390faf5f73aSNiels Provos #define TO_SERVER_REQUEST(base_ptr)					\
391faf5f73aSNiels Provos 	((struct server_request*)					\
3921ed27048SNick Mathewson 	  (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
393faf5f73aSNiels Provos 
39449868b61SNick Mathewson #define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
39549868b61SNick Mathewson 
396e688a88aSNick Mathewson static struct nameserver *nameserver_pick(struct evdns_base *base);
39715bb82d6SChristopher Davis static void evdns_request_insert(struct request *req, struct request **head);
39815bb82d6SChristopher Davis static void evdns_request_remove(struct request *req, struct request **head);
3991120f04fSNick Mathewson static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
400e688a88aSNick Mathewson static int evdns_transmit(struct evdns_base *base);
40115bb82d6SChristopher Davis static int evdns_request_transmit(struct request *req);
402cca7249eSNiels Provos static void nameserver_send_probe(struct nameserver *const ns);
403beaa14a4SChristopher Davis static void search_request_finished(struct evdns_request *const);
404beaa14a4SChristopher Davis static int search_try_next(struct evdns_request *const req);
40515bb82d6SChristopher Davis 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);
406e688a88aSNick Mathewson static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
407e688a88aSNick Mathewson static u16 transaction_id_pick(struct evdns_base *base);
40815bb82d6SChristopher Davis 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);
40915bb82d6SChristopher Davis static void request_submit(struct request *const req);
410cca7249eSNiels Provos 
411faf5f73aSNiels Provos static int server_request_free(struct server_request *req);
412faf5f73aSNiels Provos static void server_request_free_answers(struct server_request *req);
413faf5f73aSNiels Provos static void server_port_free(struct evdns_server_port *port);
4141120f04fSNick Mathewson static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
415327165b3SNick Mathewson static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
416327165b3SNick Mathewson static int evdns_base_set_option_impl(struct evdns_base *base,
417327165b3SNick Mathewson     const char *option, const char *val, int flags);
41812199fa7SNick Mathewson static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
41962f596b7SAntony Antony static void evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg);
420faf5f73aSNiels Provos 
421faf5f73aSNiels Provos static int strtoint(const char *const str);
422faf5f73aSNiels Provos 
42368120d9bSNick Mathewson #ifdef EVENT__DISABLE_THREAD_SUPPORT
424cb9da0bfSNick Mathewson #define EVDNS_LOCK(base)  EVUTIL_NIL_STMT_
425cb9da0bfSNick Mathewson #define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
426cb9da0bfSNick Mathewson #define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
427327165b3SNick Mathewson #else
428327165b3SNick Mathewson #define EVDNS_LOCK(base)			\
4290cd3bb9fSNick Mathewson 	EVLOCK_LOCK((base)->lock, 0)
430327165b3SNick Mathewson #define EVDNS_UNLOCK(base)			\
4310cd3bb9fSNick Mathewson 	EVLOCK_UNLOCK((base)->lock, 0)
4320cd3bb9fSNick Mathewson #define ASSERT_LOCKED(base)			\
4330cd3bb9fSNick Mathewson 	EVLOCK_ASSERT_LOCKED((base)->lock)
434327165b3SNick Mathewson #endif
435327165b3SNick Mathewson 
43652bfcab8SNiels Provos static evdns_debug_log_fn_type evdns_log_fn = NULL;
437cca7249eSNiels Provos 
438cca7249eSNiels Provos void
evdns_set_log_fn(evdns_debug_log_fn_type fn)43952bfcab8SNiels Provos evdns_set_log_fn(evdns_debug_log_fn_type fn)
440cca7249eSNiels Provos {
44152bfcab8SNiels Provos 	evdns_log_fn = fn;
442cca7249eSNiels Provos }
443cca7249eSNiels Provos 
444cca7249eSNiels Provos #ifdef __GNUC__
445fe1dfe0fSNiels Provos #define EVDNS_LOG_CHECK	 __attribute__ ((format(printf, 2, 3)))
446cca7249eSNiels Provos #else
447fe1dfe0fSNiels Provos #define EVDNS_LOG_CHECK
448cca7249eSNiels Provos #endif
449cca7249eSNiels Provos 
450e1766a1bSNick Mathewson static void evdns_log_(int severity, const char *fmt, ...) EVDNS_LOG_CHECK;
451cca7249eSNiels Provos static void
evdns_log_(int severity,const char * fmt,...)452e1766a1bSNick Mathewson evdns_log_(int severity, const char *fmt, ...)
453cca7249eSNiels Provos {
454cca7249eSNiels Provos 	va_list args;
455cca7249eSNiels Provos 	va_start(args,fmt);
456b2f2be6eSNick Mathewson 	if (evdns_log_fn) {
457e1766a1bSNick Mathewson 		char buf[512];
458e1766a1bSNick Mathewson 		int is_warn = (severity == EVDNS_LOG_WARN);
459e1766a1bSNick Mathewson 		evutil_vsnprintf(buf, sizeof(buf), fmt, args);
460e1766a1bSNick Mathewson 		evdns_log_fn(is_warn, buf);
461b2f2be6eSNick Mathewson 	} else {
462e1766a1bSNick Mathewson 		event_logv_(severity, NULL, fmt, args);
463b2f2be6eSNick Mathewson 	}
464e1766a1bSNick Mathewson 	va_end(args);
465cca7249eSNiels Provos }
466cca7249eSNiels Provos 
467cb9da0bfSNick Mathewson #define log evdns_log_
468cca7249eSNiels Provos 
4697c6df310SNiels Provos /* This walks the list of inflight requests to find the */
4707c6df310SNiels Provos /* one with a matching transaction id. Returns NULL on */
4717c6df310SNiels Provos /* failure */
47215bb82d6SChristopher Davis static struct request *
request_find_from_trans_id(struct evdns_base * base,u16 trans_id)473e688a88aSNick Mathewson request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
47415bb82d6SChristopher Davis 	struct request *req = REQ_HEAD(base, trans_id);
47515bb82d6SChristopher Davis 	struct request *const started_at = req;
476cca7249eSNiels Provos 
477327165b3SNick Mathewson 	ASSERT_LOCKED(base);
478327165b3SNick Mathewson 
479cca7249eSNiels Provos 	if (req) {
480cca7249eSNiels Provos 		do {
481cca7249eSNiels Provos 			if (req->trans_id == trans_id) return req;
482cca7249eSNiels Provos 			req = req->next;
483cca7249eSNiels Provos 		} while (req != started_at);
484cca7249eSNiels Provos 	}
485cca7249eSNiels Provos 
486cca7249eSNiels Provos 	return NULL;
487cca7249eSNiels Provos }
488cca7249eSNiels Provos 
4897c6df310SNiels Provos /* a libevent callback function which is called when a nameserver */
4907c6df310SNiels Provos /* has gone down and we want to test if it has came back to life yet */
491cca7249eSNiels Provos static void
nameserver_prod_callback(evutil_socket_t fd,short events,void * arg)4921120f04fSNick Mathewson nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
493cca7249eSNiels Provos 	struct nameserver *const ns = (struct nameserver *) arg;
494cca7249eSNiels Provos 	(void)fd;
495cca7249eSNiels Provos 	(void)events;
496cca7249eSNiels Provos 
497327165b3SNick Mathewson 	EVDNS_LOCK(ns->base);
498cca7249eSNiels Provos 	nameserver_send_probe(ns);
499327165b3SNick Mathewson 	EVDNS_UNLOCK(ns->base);
500cca7249eSNiels Provos }
501cca7249eSNiels Provos 
5027c6df310SNiels Provos /* a libevent callback which is called when a nameserver probe (to see if */
5037c6df310SNiels Provos /* it has come back to life) times out. We increment the count of failed_times */
5047c6df310SNiels Provos /* and wait longer to send the next probe packet. */
505cca7249eSNiels Provos static void
nameserver_probe_failed(struct nameserver * const ns)506cca7249eSNiels Provos nameserver_probe_failed(struct nameserver *const ns) {
5071e56a32dSNick Mathewson 	struct timeval timeout;
5081e56a32dSNick Mathewson 	int i;
509327165b3SNick Mathewson 
510327165b3SNick Mathewson 	ASSERT_LOCKED(ns->base);
511cca7249eSNiels Provos 	(void) evtimer_del(&ns->timeout_event);
512fe1dfe0fSNiels Provos 	if (ns->state == 1) {
5137c6df310SNiels Provos 		/* This can happen if the nameserver acts in a way which makes us mark */
5147c6df310SNiels Provos 		/* it as bad and then starts sending good replies. */
515fe1dfe0fSNiels Provos 		return;
516fe1dfe0fSNiels Provos 	}
517fe1dfe0fSNiels Provos 
5181e56a32dSNick Mathewson #define MAX_PROBE_TIMEOUT 3600
5191e56a32dSNick Mathewson #define TIMEOUT_BACKOFF_FACTOR 3
5201e56a32dSNick Mathewson 
5211e56a32dSNick Mathewson 	memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
5221e56a32dSNick Mathewson 	    sizeof(struct timeval));
5231e56a32dSNick Mathewson 	for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
5241e56a32dSNick Mathewson 		timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
5251e56a32dSNick Mathewson 		timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
5261e56a32dSNick Mathewson 		if (timeout.tv_usec > 1000000) {
5271e56a32dSNick Mathewson 			timeout.tv_sec += timeout.tv_usec / 1000000;
5281e56a32dSNick Mathewson 			timeout.tv_usec %= 1000000;
5291e56a32dSNick Mathewson 		}
5301e56a32dSNick Mathewson 	}
5311e56a32dSNick Mathewson 	if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
5321e56a32dSNick Mathewson 		timeout.tv_sec = MAX_PROBE_TIMEOUT;
5331e56a32dSNick Mathewson 		timeout.tv_usec = 0;
5341e56a32dSNick Mathewson 	}
5351e56a32dSNick Mathewson 
536cca7249eSNiels Provos 	ns->failed_times++;
537cca7249eSNiels Provos 
5381e56a32dSNick Mathewson 	if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
539b1c79500SNick Mathewson 		char addrbuf[128];
540fe1dfe0fSNiels Provos 		log(EVDNS_LOG_WARN,
541fe1dfe0fSNiels Provos 		    "Error from libevent when adding timer event for %s",
5428ac3c4c2SNick Mathewson 		    evutil_format_sockaddr_port_(
543b1c79500SNick Mathewson 			    (struct sockaddr *)&ns->address,
544b1c79500SNick Mathewson 			    addrbuf, sizeof(addrbuf)));
545cca7249eSNiels Provos 	}
546cca7249eSNiels Provos }
547cca7249eSNiels Provos 
54874d0eee8SAzat Khuzhin static void
request_swap_ns(struct request * req,struct nameserver * ns)54974d0eee8SAzat Khuzhin request_swap_ns(struct request *req, struct nameserver *ns) {
55074d0eee8SAzat Khuzhin 	if (ns && req->ns != ns) {
55174d0eee8SAzat Khuzhin 		EVUTIL_ASSERT(req->ns->requests_inflight > 0);
55274d0eee8SAzat Khuzhin 		req->ns->requests_inflight--;
55374d0eee8SAzat Khuzhin 		ns->requests_inflight++;
55474d0eee8SAzat Khuzhin 
55574d0eee8SAzat Khuzhin 		req->ns = ns;
55674d0eee8SAzat Khuzhin 	}
55774d0eee8SAzat Khuzhin }
55874d0eee8SAzat Khuzhin 
5597c6df310SNiels Provos /* called when a nameserver has been deemed to have failed. For example, too */
5607c6df310SNiels Provos /* many packets have timed out etc */
561cca7249eSNiels Provos static void
nameserver_failed(struct nameserver * const ns,const char * msg)562cca7249eSNiels Provos nameserver_failed(struct nameserver *const ns, const char *msg) {
56315bb82d6SChristopher Davis 	struct request *req, *started_at;
564e688a88aSNick Mathewson 	struct evdns_base *base = ns->base;
56549868b61SNick Mathewson 	int i;
566b1c79500SNick Mathewson 	char addrbuf[128];
567327165b3SNick Mathewson 
568327165b3SNick Mathewson 	ASSERT_LOCKED(base);
5697c6df310SNiels Provos 	/* if this nameserver has already been marked as failed */
5707c6df310SNiels Provos 	/* then don't do anything */
571cca7249eSNiels Provos 	if (!ns->state) return;
572cca7249eSNiels Provos 
573b2f2be6eSNick Mathewson 	log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
5748ac3c4c2SNick Mathewson 	    evutil_format_sockaddr_port_(
575b1c79500SNick Mathewson 		    (struct sockaddr *)&ns->address,
576b1c79500SNick Mathewson 		    addrbuf, sizeof(addrbuf)),
577b1c79500SNick Mathewson 	    msg);
578b1c79500SNick Mathewson 
579e688a88aSNick Mathewson 	base->global_good_nameservers--;
5802e36dbe1SNick Mathewson 	EVUTIL_ASSERT(base->global_good_nameservers >= 0);
581e688a88aSNick Mathewson 	if (base->global_good_nameservers == 0) {
582b2f2be6eSNick Mathewson 		log(EVDNS_LOG_MSG, "All nameservers have failed");
583cca7249eSNiels Provos 	}
584cca7249eSNiels Provos 
585cca7249eSNiels Provos 	ns->state = 0;
586cca7249eSNiels Provos 	ns->failed_times = 1;
587cca7249eSNiels Provos 
5881e56a32dSNick Mathewson 	if (evtimer_add(&ns->timeout_event,
5891e56a32dSNick Mathewson 		&base->global_nameserver_probe_initial_timeout) < 0) {
590fe1dfe0fSNiels Provos 		log(EVDNS_LOG_WARN,
591fe1dfe0fSNiels Provos 		    "Error from libevent when adding timer event for %s",
5928ac3c4c2SNick Mathewson 		    evutil_format_sockaddr_port_(
593b1c79500SNick Mathewson 			    (struct sockaddr *)&ns->address,
594b1c79500SNick Mathewson 			    addrbuf, sizeof(addrbuf)));
5957c6df310SNiels Provos 		/* ???? Do more? */
596cca7249eSNiels Provos 	}
597cca7249eSNiels Provos 
5987c6df310SNiels Provos 	/* walk the list of inflight requests to see if any can be reassigned to */
5997c6df310SNiels Provos 	/* a different server. Requests in the waiting queue don't have a */
6007c6df310SNiels Provos 	/* nameserver assigned yet */
601cca7249eSNiels Provos 
6027c6df310SNiels Provos 	/* if we don't have *any* good nameservers then there's no point */
6037c6df310SNiels Provos 	/* trying to reassign requests to one */
604e688a88aSNick Mathewson 	if (!base->global_good_nameservers) return;
605cca7249eSNiels Provos 
60649868b61SNick Mathewson 	for (i = 0; i < base->n_req_heads; ++i) {
60749868b61SNick Mathewson 		req = started_at = base->req_heads[i];
608cca7249eSNiels Provos 		if (req) {
609cca7249eSNiels Provos 			do {
610cca7249eSNiels Provos 				if (req->tx_count == 0 && req->ns == ns) {
6117c6df310SNiels Provos 					/* still waiting to go out, can be moved */
6127c6df310SNiels Provos 					/* to another server */
61374d0eee8SAzat Khuzhin 					request_swap_ns(req, nameserver_pick(base));
614cca7249eSNiels Provos 				}
615cca7249eSNiels Provos 				req = req->next;
616cca7249eSNiels Provos 			} while (req != started_at);
617cca7249eSNiels Provos 		}
618cca7249eSNiels Provos 	}
61949868b61SNick Mathewson }
620cca7249eSNiels Provos 
621cca7249eSNiels Provos static void
nameserver_up(struct nameserver * const ns)6222df1f82bSZhuang Yuyao nameserver_up(struct nameserver *const ns)
6232df1f82bSZhuang Yuyao {
624b1c79500SNick Mathewson 	char addrbuf[128];
6252df1f82bSZhuang Yuyao 	ASSERT_LOCKED(ns->base);
626cca7249eSNiels Provos 	if (ns->state) return;
627b2f2be6eSNick Mathewson 	log(EVDNS_LOG_MSG, "Nameserver %s is back up",
6288ac3c4c2SNick Mathewson 	    evutil_format_sockaddr_port_(
629b1c79500SNick Mathewson 		    (struct sockaddr *)&ns->address,
630b1c79500SNick Mathewson 		    addrbuf, sizeof(addrbuf)));
631cca7249eSNiels Provos 	evtimer_del(&ns->timeout_event);
632684c022aSNick Mathewson 	if (ns->probe_request) {
633684c022aSNick Mathewson 		evdns_cancel_request(ns->base, ns->probe_request);
634684c022aSNick Mathewson 		ns->probe_request = NULL;
635684c022aSNick Mathewson 	}
636cca7249eSNiels Provos 	ns->state = 1;
637cca7249eSNiels Provos 	ns->failed_times = 0;
6380147ef3aSNiels Provos 	ns->timedout = 0;
639e688a88aSNick Mathewson 	ns->base->global_good_nameservers++;
640cca7249eSNiels Provos }
641cca7249eSNiels Provos 
642cca7249eSNiels Provos static void
request_trans_id_set(struct request * const req,const u16 trans_id)64315bb82d6SChristopher Davis request_trans_id_set(struct request *const req, const u16 trans_id) {
644cca7249eSNiels Provos 	req->trans_id = trans_id;
645cca7249eSNiels Provos 	*((u16 *) req->request) = htons(trans_id);
646cca7249eSNiels Provos }
647cca7249eSNiels Provos 
6487c6df310SNiels Provos /* Called to remove a request from a list and dealloc it. */
6497c6df310SNiels Provos /* head is a pointer to the head of the list it should be */
6507c6df310SNiels Provos /* removed from or NULL if the request isn't in a list. */
65115bb82d6SChristopher Davis /* when free_handle is one, free the handle as well. */
652cca7249eSNiels Provos static void
request_finished(struct request * const req,struct request ** head,int free_handle)65315bb82d6SChristopher Davis request_finished(struct request *const req, struct request **head, int free_handle) {
654e688a88aSNick Mathewson 	struct evdns_base *base = req->base;
655d2e9caa6SNick Mathewson 	int was_inflight = (head != &base->req_waiting_head);
656213dc2a2SNick Mathewson 	EVDNS_LOCK(base);
65767072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
65867072f3cSChristopher Davis 
6591eeb96aaSNiels Provos 	if (head)
6601eeb96aaSNiels Provos 		evdns_request_remove(req, head);
661cca7249eSNiels Provos 
6627bcace2dSNick Mathewson 	log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
663d2e9caa6SNick Mathewson 	if (was_inflight) {
664d2e9caa6SNick Mathewson 		evtimer_del(&req->timeout_event);
665e688a88aSNick Mathewson 		base->global_requests_inflight--;
6666b7fa620SAzat Khuzhin 		req->ns->requests_inflight--;
667d2e9caa6SNick Mathewson 	} else {
668d2e9caa6SNick Mathewson 		base->global_requests_waiting--;
669d2e9caa6SNick Mathewson 	}
670aff6ba15SLeonid Evdokimov 	/* it was initialized during request_new / evtimer_assign */
671aff6ba15SLeonid Evdokimov 	event_debug_unassign(&req->timeout_event);
672cca7249eSNiels Provos 
6736b7fa620SAzat Khuzhin 	if (req->ns &&
6746b7fa620SAzat Khuzhin 	    req->ns->requests_inflight == 0 &&
6756b7fa620SAzat Khuzhin 	    req->base->disable_when_inactive) {
6766b7fa620SAzat Khuzhin 		event_del(&req->ns->event);
677610410b5SAzat Khuzhin 		evtimer_del(&req->ns->timeout_event);
6786b7fa620SAzat Khuzhin 	}
6796b7fa620SAzat Khuzhin 
680cca7249eSNiels Provos 	if (!req->request_appended) {
6817c6df310SNiels Provos 		/* need to free the request data on it's own */
68249868b61SNick Mathewson 		mm_free(req->request);
683cca7249eSNiels Provos 	} else {
6847c6df310SNiels Provos 		/* the request data is appended onto the header */
6857c6df310SNiels Provos 		/* so everything gets free()ed when we: */
686cca7249eSNiels Provos 	}
687cca7249eSNiels Provos 
68867072f3cSChristopher Davis 	if (req->handle) {
68967072f3cSChristopher Davis 		EVUTIL_ASSERT(req->handle->current_req == req);
6909ed30de7SNick Mathewson 
69167072f3cSChristopher Davis 		if (free_handle) {
692beaa14a4SChristopher Davis 			search_request_finished(req->handle);
69367072f3cSChristopher Davis 			req->handle->current_req = NULL;
6949ed30de7SNick Mathewson 			if (! req->handle->pending_cb) {
6959ed30de7SNick Mathewson 				/* If we're planning to run the callback,
6969ed30de7SNick Mathewson 				 * don't free the handle until later. */
6979ed30de7SNick Mathewson 				mm_free(req->handle);
6989ed30de7SNick Mathewson 			}
6999ed30de7SNick Mathewson 			req->handle = NULL; /* If we have a bug, let's crash
7009ed30de7SNick Mathewson 					     * early */
7019ed30de7SNick Mathewson 		} else {
7029ed30de7SNick Mathewson 			req->handle->current_req = NULL;
7039ed30de7SNick Mathewson 		}
704beaa14a4SChristopher Davis 	}
70515bb82d6SChristopher Davis 
70649868b61SNick Mathewson 	mm_free(req);
707cca7249eSNiels Provos 
708e688a88aSNick Mathewson 	evdns_requests_pump_waiting_queue(base);
709213dc2a2SNick Mathewson 	EVDNS_UNLOCK(base);
710cca7249eSNiels Provos }
711cca7249eSNiels Provos 
7127c6df310SNiels Provos /* This is called when a server returns a funny error code. */
7137c6df310SNiels Provos /* We try the request again with another server. */
7147c6df310SNiels Provos /* */
7157c6df310SNiels Provos /* return: */
7167c6df310SNiels Provos /*   0 ok */
7177c6df310SNiels Provos /*   1 failed/reissue is pointless */
718cca7249eSNiels Provos static int
request_reissue(struct request * req)71915bb82d6SChristopher Davis request_reissue(struct request *req) {
720cca7249eSNiels Provos 	const struct nameserver *const last_ns = req->ns;
721327165b3SNick Mathewson 	ASSERT_LOCKED(req->base);
72267072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
7237c6df310SNiels Provos 	/* the last nameserver should have been marked as failing */
7247c6df310SNiels Provos 	/* by the caller of this function, therefore pick will try */
7257c6df310SNiels Provos 	/* not to return it */
72674d0eee8SAzat Khuzhin 	request_swap_ns(req, nameserver_pick(req->base));
727cca7249eSNiels Provos 	if (req->ns == last_ns) {
7287c6df310SNiels Provos 		/* ... but pick did return it */
7297c6df310SNiels Provos 		/* not a lot of point in trying again with the */
7307c6df310SNiels Provos 		/* same server */
731cca7249eSNiels Provos 		return 1;
732cca7249eSNiels Provos 	}
733cca7249eSNiels Provos 
734cca7249eSNiels Provos 	req->reissue_count++;
735cca7249eSNiels Provos 	req->tx_count = 0;
736cca7249eSNiels Provos 	req->transmit_me = 1;
737cca7249eSNiels Provos 
738cca7249eSNiels Provos 	return 0;
739cca7249eSNiels Provos }
740cca7249eSNiels Provos 
7417c6df310SNiels Provos /* this function looks for space on the inflight queue and promotes */
7427c6df310SNiels Provos /* requests from the waiting queue if it can. */
74314971a83SAzat Khuzhin /* */
74414971a83SAzat Khuzhin /* TODO: */
74514971a83SAzat Khuzhin /* add return code, see at nameserver_pick() and other functions. */
746cca7249eSNiels Provos static void
evdns_requests_pump_waiting_queue(struct evdns_base * base)747e688a88aSNick Mathewson evdns_requests_pump_waiting_queue(struct evdns_base *base) {
748327165b3SNick Mathewson 	ASSERT_LOCKED(base);
749e688a88aSNick Mathewson 	while (base->global_requests_inflight < base->global_max_requests_inflight &&
750e688a88aSNick Mathewson 		   base->global_requests_waiting) {
75115bb82d6SChristopher Davis 		struct request *req;
75214971a83SAzat Khuzhin 
7532e36dbe1SNick Mathewson 		EVUTIL_ASSERT(base->req_waiting_head);
754e688a88aSNick Mathewson 		req = base->req_waiting_head;
75514971a83SAzat Khuzhin 
75614971a83SAzat Khuzhin 		req->ns = nameserver_pick(base);
75714971a83SAzat Khuzhin 		if (!req->ns)
75814971a83SAzat Khuzhin 			return;
75914971a83SAzat Khuzhin 
76014971a83SAzat Khuzhin 		/* move a request from the waiting queue to the inflight queue */
76114971a83SAzat Khuzhin 		req->ns->requests_inflight++;
76214971a83SAzat Khuzhin 
7631eeb96aaSNiels Provos 		evdns_request_remove(req, &base->req_waiting_head);
764cca7249eSNiels Provos 
765e688a88aSNick Mathewson 		base->global_requests_waiting--;
766e688a88aSNick Mathewson 		base->global_requests_inflight++;
767cca7249eSNiels Provos 
768e688a88aSNick Mathewson 		request_trans_id_set(req, transaction_id_pick(base));
769cca7249eSNiels Provos 
77049868b61SNick Mathewson 		evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
77152bfcab8SNiels Provos 		evdns_request_transmit(req);
772e688a88aSNick Mathewson 		evdns_transmit(base);
773cca7249eSNiels Provos 	}
774cca7249eSNiels Provos }
775cca7249eSNiels Provos 
7762d9619d7SNick Mathewson /* TODO(nickm) document */
7772d9619d7SNick Mathewson struct deferred_reply_callback {
778a4079aa8SNick Mathewson 	struct event_callback deferred;
7799ed30de7SNick Mathewson 	struct evdns_request *handle;
7802d9619d7SNick Mathewson 	u8 request_type;
7812d9619d7SNick Mathewson 	u8 have_reply;
7822d9619d7SNick Mathewson 	u32 ttl;
7832d9619d7SNick Mathewson 	u32 err;
7842d9619d7SNick Mathewson 	evdns_callback_type user_callback;
7852d9619d7SNick Mathewson 	struct reply reply;
7862d9619d7SNick Mathewson };
7872d9619d7SNick Mathewson 
788fe1dfe0fSNiels Provos static void
reply_run_callback(struct event_callback * d,void * user_pointer)789a4079aa8SNick Mathewson reply_run_callback(struct event_callback *d, void *user_pointer)
7902d9619d7SNick Mathewson {
7912d9619d7SNick Mathewson 	struct deferred_reply_callback *cb =
7922d9619d7SNick Mathewson 	    EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
7932d9619d7SNick Mathewson 
7942d9619d7SNick Mathewson 	switch (cb->request_type) {
795fe1dfe0fSNiels Provos 	case TYPE_A:
7962d9619d7SNick Mathewson 		if (cb->have_reply)
7972d9619d7SNick Mathewson 			cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
7982d9619d7SNick Mathewson 			    cb->reply.data.a.addrcount, cb->ttl,
7992d9619d7SNick Mathewson 			    cb->reply.data.a.addresses,
8002d9619d7SNick Mathewson 			    user_pointer);
801fe1dfe0fSNiels Provos 		else
802f72e8f66SLeonid Evdokimov 			cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
8032d9619d7SNick Mathewson 		break;
804fe1dfe0fSNiels Provos 	case TYPE_PTR:
8052d9619d7SNick Mathewson 		if (cb->have_reply) {
8062d9619d7SNick Mathewson 			char *name = cb->reply.data.ptr.name;
8072d9619d7SNick Mathewson 			cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
8082d9619d7SNick Mathewson 			    &name, user_pointer);
809fe1dfe0fSNiels Provos 		} else {
810f72e8f66SLeonid Evdokimov 			cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
811fe1dfe0fSNiels Provos 		}
8122d9619d7SNick Mathewson 		break;
8136318fca2SNiels Provos 	case TYPE_AAAA:
8142d9619d7SNick Mathewson 		if (cb->have_reply)
8152d9619d7SNick Mathewson 			cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
8162d9619d7SNick Mathewson 			    cb->reply.data.aaaa.addrcount, cb->ttl,
8172d9619d7SNick Mathewson 			    cb->reply.data.aaaa.addresses,
8182d9619d7SNick Mathewson 			    user_pointer);
8196318fca2SNiels Provos 		else
820f72e8f66SLeonid Evdokimov 			cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
8212d9619d7SNick Mathewson 		break;
8222d9619d7SNick Mathewson 	default:
8232e36dbe1SNick Mathewson 		EVUTIL_ASSERT(0);
824fe1dfe0fSNiels Provos 	}
825fe1dfe0fSNiels Provos 
8269ed30de7SNick Mathewson 	if (cb->handle && cb->handle->pending_cb) {
8279ed30de7SNick Mathewson 		mm_free(cb->handle);
8289ed30de7SNick Mathewson 	}
8299ed30de7SNick Mathewson 
8302d9619d7SNick Mathewson 	mm_free(cb);
8312d9619d7SNick Mathewson }
8322d9619d7SNick Mathewson 
8332d9619d7SNick Mathewson static void
reply_schedule_callback(struct request * const req,u32 ttl,u32 err,struct reply * reply)83415bb82d6SChristopher Davis reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
8352d9619d7SNick Mathewson {
8362d9619d7SNick Mathewson 	struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
8372d9619d7SNick Mathewson 
838364291e9SNick Mathewson 	if (!d) {
839364291e9SNick Mathewson 		event_warn("%s: Couldn't allocate space for deferred callback.",
840364291e9SNick Mathewson 		    __func__);
841364291e9SNick Mathewson 		return;
842364291e9SNick Mathewson 	}
843364291e9SNick Mathewson 
8442d9619d7SNick Mathewson 	ASSERT_LOCKED(req->base);
8452d9619d7SNick Mathewson 
8462d9619d7SNick Mathewson 	d->request_type = req->request_type;
8472d9619d7SNick Mathewson 	d->user_callback = req->user_callback;
8482d9619d7SNick Mathewson 	d->ttl = ttl;
8492d9619d7SNick Mathewson 	d->err = err;
8502d9619d7SNick Mathewson 	if (reply) {
8512d9619d7SNick Mathewson 		d->have_reply = 1;
8522d9619d7SNick Mathewson 		memcpy(&d->reply, reply, sizeof(struct reply));
8532d9619d7SNick Mathewson 	}
8542d9619d7SNick Mathewson 
8559ed30de7SNick Mathewson 	if (req->handle) {
8569ed30de7SNick Mathewson 		req->handle->pending_cb = 1;
8579ed30de7SNick Mathewson 		d->handle = req->handle;
8589ed30de7SNick Mathewson 	}
8599ed30de7SNick Mathewson 
860c0e425abSNick Mathewson 	event_deferred_cb_init_(
861c0e425abSNick Mathewson 	    &d->deferred,
862c0e425abSNick Mathewson 	    event_get_priority(&req->timeout_event),
863c0e425abSNick Mathewson 	    reply_run_callback,
8642d9619d7SNick Mathewson 	    req->user_pointer);
8658ac3c4c2SNick Mathewson 	event_deferred_cb_schedule_(
866a4079aa8SNick Mathewson 		req->base->event_base,
867b06b2649SNick Mathewson 		&d->deferred);
8682d9619d7SNick Mathewson }
8692d9619d7SNick Mathewson 
870fcdda24bSNathan French 
871fcdda24bSNathan French #define _QR_MASK    0x8000U
872fcdda24bSNathan French #define _OP_MASK    0x7800U
873fcdda24bSNathan French #define _AA_MASK    0x0400U
874fcdda24bSNathan French #define _TC_MASK    0x0200U
875fcdda24bSNathan French #define _RD_MASK    0x0100U
876fcdda24bSNathan French #define _RA_MASK    0x0080U
877fcdda24bSNathan French #define _Z_MASK     0x0040U
878fcdda24bSNathan French #define _AD_MASK    0x0020U
879fcdda24bSNathan French #define _CD_MASK    0x0010U
880fcdda24bSNathan French #define _RCODE_MASK 0x000fU
881fcdda24bSNathan French #define _Z_MASK_DEPRECATED 0x0070U
882fcdda24bSNathan French 
8837c6df310SNiels Provos /* this processes a parsed reply packet */
884cca7249eSNiels Provos static void
reply_handle(struct request * const req,u16 flags,u32 ttl,struct reply * reply)88515bb82d6SChristopher Davis reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
886cca7249eSNiels Provos 	int error;
887b1c79500SNick Mathewson 	char addrbuf[128];
888a710d817SNiels Provos 	static const int error_codes[] = {
889a710d817SNiels Provos 		DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
890a710d817SNiels Provos 		DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
891a710d817SNiels Provos 	};
892cca7249eSNiels Provos 
893327165b3SNick Mathewson 	ASSERT_LOCKED(req->base);
89467072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
895327165b3SNick Mathewson 
896fcdda24bSNathan French 	if (flags & (_RCODE_MASK | _TC_MASK) || !reply || !reply->have_answer) {
8977c6df310SNiels Provos 		/* there was an error */
898fcdda24bSNathan French 		if (flags & _TC_MASK) {
899cca7249eSNiels Provos 			error = DNS_ERR_TRUNCATED;
900fcdda24bSNathan French 		} else if (flags & _RCODE_MASK) {
901fcdda24bSNathan French 			u16 error_code = (flags & _RCODE_MASK) - 1;
902cca7249eSNiels Provos 			if (error_code > 4) {
903cca7249eSNiels Provos 				error = DNS_ERR_UNKNOWN;
904cca7249eSNiels Provos 			} else {
905cca7249eSNiels Provos 				error = error_codes[error_code];
906cca7249eSNiels Provos 			}
90794fba5b9SLeonid Evdokimov 		} else if (reply && !reply->have_answer) {
90894fba5b9SLeonid Evdokimov 			error = DNS_ERR_NODATA;
90994fba5b9SLeonid Evdokimov 		} else {
91094fba5b9SLeonid Evdokimov 			error = DNS_ERR_UNKNOWN;
911cca7249eSNiels Provos 		}
912cca7249eSNiels Provos 
913cca7249eSNiels Provos 		switch (error) {
914cca7249eSNiels Provos 		case DNS_ERR_NOTIMPL:
915cca7249eSNiels Provos 		case DNS_ERR_REFUSED:
9167c6df310SNiels Provos 			/* we regard these errors as marking a bad nameserver */
917e688a88aSNick Mathewson 			if (req->reissue_count < req->base->global_max_reissues) {
918cca7249eSNiels Provos 				char msg[64];
919c6da86ffSNick Mathewson 				evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
920fe1dfe0fSNiels Provos 					 error, evdns_err_to_string(error));
921cca7249eSNiels Provos 				nameserver_failed(req->ns, msg);
922cca7249eSNiels Provos 				if (!request_reissue(req)) return;
923cca7249eSNiels Provos 			}
924cca7249eSNiels Provos 			break;
92528246587SNiels Provos 		case DNS_ERR_SERVERFAILED:
926a710d817SNiels Provos 			/* rcode 2 (servfailed) sometimes means "we
927a710d817SNiels Provos 			 * are broken" and sometimes (with some binds)
928a710d817SNiels Provos 			 * means "that request was very confusing."
929a710d817SNiels Provos 			 * Treat this as a timeout, not a failure.
9307c6df310SNiels Provos 			 */
931b1c79500SNick Mathewson 			log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
932b1c79500SNick Mathewson 				"at %s; will allow the request to time out.",
9338ac3c4c2SNick Mathewson 			    evutil_format_sockaddr_port_(
934b1c79500SNick Mathewson 				    (struct sockaddr *)&req->ns->address,
935b1c79500SNick Mathewson 				    addrbuf, sizeof(addrbuf)));
93662f596b7SAntony Antony 			/* Call the timeout function */
93762f596b7SAntony Antony 			evdns_request_timeout_callback(0, 0, req);
93862f596b7SAntony Antony 			return;
939cca7249eSNiels Provos 		default:
940bec50680SNick Mathewson 			/* we got a good reply from the nameserver: it is up. */
941bec50680SNick Mathewson 			if (req->handle == req->ns->probe_request) {
942bec50680SNick Mathewson 				/* Avoid double-free */
943bec50680SNick Mathewson 				req->ns->probe_request = NULL;
944bec50680SNick Mathewson 			}
945bec50680SNick Mathewson 
946cca7249eSNiels Provos 			nameserver_up(req->ns);
947cca7249eSNiels Provos 		}
948cca7249eSNiels Provos 
94967072f3cSChristopher Davis 		if (req->handle->search_state &&
95067072f3cSChristopher Davis 		    req->request_type != TYPE_PTR) {
951a710d817SNiels Provos 			/* if we have a list of domains to search in,
952a710d817SNiels Provos 			 * try the next one */
953beaa14a4SChristopher Davis 			if (!search_try_next(req->handle)) {
954a710d817SNiels Provos 				/* a new request was issued so this
955a710d817SNiels Provos 				 * request is finished and */
956a710d817SNiels Provos 				/* the user callback will be made when
957a710d817SNiels Provos 				 * that request (or a */
9587c6df310SNiels Provos 				/* child of it) finishes. */
959cca7249eSNiels Provos 				return;
960cca7249eSNiels Provos 			}
961cca7249eSNiels Provos 		}
962cca7249eSNiels Provos 
9637c6df310SNiels Provos 		/* all else failed. Pass the failure up */
964f72e8f66SLeonid Evdokimov 		reply_schedule_callback(req, ttl, error, NULL);
96515bb82d6SChristopher Davis 		request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
966cca7249eSNiels Provos 	} else {
9677c6df310SNiels Provos 		/* all ok, tell the user */
9682d9619d7SNick Mathewson 		reply_schedule_callback(req, ttl, 0, reply);
96915bb82d6SChristopher Davis 		if (req->handle == req->ns->probe_request)
970213dc2a2SNick Mathewson 			req->ns->probe_request = NULL; /* Avoid double-free */
971cca7249eSNiels Provos 		nameserver_up(req->ns);
97215bb82d6SChristopher Davis 		request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
973cca7249eSNiels Provos 	}
974cca7249eSNiels Provos }
975cca7249eSNiels Provos 
976f0ff792aSNiels Provos static int
name_parse(u8 * packet,int length,int * idx,char * name_out,int name_out_len)977fe1dfe0fSNiels Provos name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
978fe1dfe0fSNiels Provos 	int name_end = -1;
979fe1dfe0fSNiels Provos 	int j = *idx;
980b04043aeSNiels Provos 	int ptr_count = 0;
981cb9da0bfSNick Mathewson #define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
982cb9da0bfSNick Mathewson #define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
983f0ff792aSNiels Provos #define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
984fe1dfe0fSNiels Provos 
985fe1dfe0fSNiels Provos 	char *cp = name_out;
986fe1dfe0fSNiels Provos 	const char *const end = name_out + name_out_len;
987fe1dfe0fSNiels Provos 
9887c6df310SNiels Provos 	/* Normally, names are a series of length prefixed strings terminated */
9897c6df310SNiels Provos 	/* with a length of 0 (the lengths are u8's < 63). */
9907c6df310SNiels Provos 	/* However, the length can start with a pair of 1 bits and that */
9917c6df310SNiels Provos 	/* means that the next 14 bits are a pointer within the current */
9927c6df310SNiels Provos 	/* packet. */
993fe1dfe0fSNiels Provos 
994fe1dfe0fSNiels Provos 	for (;;) {
995fe1dfe0fSNiels Provos 		u8 label_len;
996fe1dfe0fSNiels Provos 		GET8(label_len);
997fe1dfe0fSNiels Provos 		if (!label_len) break;
998fe1dfe0fSNiels Provos 		if (label_len & 0xc0) {
999fe1dfe0fSNiels Provos 			u8 ptr_low;
1000fe1dfe0fSNiels Provos 			GET8(ptr_low);
1001fe1dfe0fSNiels Provos 			if (name_end < 0) name_end = j;
1002fe1dfe0fSNiels Provos 			j = (((int)label_len & 0x3f) << 8) + ptr_low;
1003b04043aeSNiels Provos 			/* Make sure that the target offset is in-bounds. */
1004fe1dfe0fSNiels Provos 			if (j < 0 || j >= length) return -1;
1005b04043aeSNiels Provos 			/* If we've jumped more times than there are characters in the
1006b04043aeSNiels Provos 			 * message, we must have a loop. */
1007b04043aeSNiels Provos 			if (++ptr_count > length) return -1;
1008fe1dfe0fSNiels Provos 			continue;
1009fe1dfe0fSNiels Provos 		}
1010fe1dfe0fSNiels Provos 		if (label_len > 63) return -1;
1011fe1dfe0fSNiels Provos 		if (cp != name_out) {
1012fe1dfe0fSNiels Provos 			if (cp + 1 >= end) return -1;
1013fe1dfe0fSNiels Provos 			*cp++ = '.';
1014fe1dfe0fSNiels Provos 		}
1015fe1dfe0fSNiels Provos 		if (cp + label_len >= end) return -1;
101696f64a02SAzat Khuzhin 		if (j + label_len > length) return -1;
1017fe1dfe0fSNiels Provos 		memcpy(cp, packet + j, label_len);
1018fe1dfe0fSNiels Provos 		cp += label_len;
1019fe1dfe0fSNiels Provos 		j += label_len;
1020fe1dfe0fSNiels Provos 	}
1021fe1dfe0fSNiels Provos 	if (cp >= end) return -1;
1022fe1dfe0fSNiels Provos 	*cp = '\0';
1023fe1dfe0fSNiels Provos 	if (name_end < 0)
1024fe1dfe0fSNiels Provos 		*idx = j;
1025fe1dfe0fSNiels Provos 	else
1026fe1dfe0fSNiels Provos 		*idx = name_end;
1027fe1dfe0fSNiels Provos 	return 0;
10285baf8ecfSNiels Provos  err:
10295baf8ecfSNiels Provos 	return -1;
1030fe1dfe0fSNiels Provos }
1031fe1dfe0fSNiels Provos 
10327c6df310SNiels Provos /* parses a raw request from a nameserver */
1033fe1dfe0fSNiels Provos static int
reply_parse(struct evdns_base * base,u8 * packet,int length)1034e688a88aSNick Mathewson reply_parse(struct evdns_base *base, u8 *packet, int length) {
1035a710d817SNiels Provos 	int j = 0, k = 0;  /* index into packet */
1036cb9da0bfSNick Mathewson 	u16 t_;	 /* used by the macros */
1037cb9da0bfSNick Mathewson 	u32 t32_;  /* used by the macros */
1038a710d817SNiels Provos 	char tmp_name[256], cmp_name[256]; /* used by the macros */
1039dd731685SNick Mathewson 	int name_matches = 0;
1040cca7249eSNiels Provos 
10415d3b6a83SNiels Provos 	u16 trans_id, questions, answers, authority, additional, datalength;
10425d3b6a83SNiels Provos 	u16 flags = 0;
1043cca7249eSNiels Provos 	u32 ttl, ttl_r = 0xffffffff;
1044fe1dfe0fSNiels Provos 	struct reply reply;
104515bb82d6SChristopher Davis 	struct request *req = NULL;
1046fe1dfe0fSNiels Provos 	unsigned int i;
1047cca7249eSNiels Provos 
1048327165b3SNick Mathewson 	ASSERT_LOCKED(base);
1049327165b3SNick Mathewson 
1050cca7249eSNiels Provos 	GET16(trans_id);
1051cca7249eSNiels Provos 	GET16(flags);
1052cca7249eSNiels Provos 	GET16(questions);
1053cca7249eSNiels Provos 	GET16(answers);
1054cca7249eSNiels Provos 	GET16(authority);
1055cca7249eSNiels Provos 	GET16(additional);
10565baf8ecfSNiels Provos 	(void) authority; /* suppress "unused variable" warnings. */
10575baf8ecfSNiels Provos 	(void) additional; /* suppress "unused variable" warnings. */
1058cca7249eSNiels Provos 
1059e688a88aSNick Mathewson 	req = request_find_from_trans_id(base, trans_id);
1060fe1dfe0fSNiels Provos 	if (!req) return -1;
10612e36dbe1SNick Mathewson 	EVUTIL_ASSERT(req->base == base);
1062fe1dfe0fSNiels Provos 
1063fe1dfe0fSNiels Provos 	memset(&reply, 0, sizeof(reply));
1064fe1dfe0fSNiels Provos 
10657c6df310SNiels Provos 	/* If it's not an answer, it doesn't correspond to any request. */
1066fcdda24bSNathan French 	if (!(flags & _QR_MASK)) return -1;  /* must be an answer */
1067fcdda24bSNathan French 	if ((flags & (_RCODE_MASK|_TC_MASK)) && (flags & (_RCODE_MASK|_TC_MASK)) != DNS_ERR_NOTEXIST) {
1068f72e8f66SLeonid Evdokimov 		/* there was an error and it's not NXDOMAIN */
10695d3b6a83SNiels Provos 		goto err;
1070cca7249eSNiels Provos 	}
10717c6df310SNiels Provos 	/* if (!answers) return; */  /* must have an answer of some form */
1072cca7249eSNiels Provos 
10737c6df310SNiels Provos 	/* This macro skips a name in the DNS reply. */
1074cca7249eSNiels Provos #define SKIP_NAME						\
1075fe1dfe0fSNiels Provos 	do { tmp_name[0] = '\0';				\
1076d0a9c90eSNick Mathewson 		if (name_parse(packet, length, &j, tmp_name,	\
1077d0a9c90eSNick Mathewson 			sizeof(tmp_name))<0)			\
10785baf8ecfSNiels Provos 			goto err;				\
1079a710d817SNiels Provos 	} while (0)
1080fe1dfe0fSNiels Provos 
1081fe1dfe0fSNiels Provos 	reply.type = req->request_type;
1082cca7249eSNiels Provos 
10837c6df310SNiels Provos 	/* skip over each question in the reply */
1084cca7249eSNiels Provos 	for (i = 0; i < questions; ++i) {
10857c6df310SNiels Provos 		/* the question looks like
10867c6df310SNiels Provos 		 *   <label:name><u16:type><u16:class>
10877c6df310SNiels Provos 		 */
10880c615f4eSAzat Khuzhin 		tmp_name[0] = '\0';
10890c615f4eSAzat Khuzhin 		cmp_name[0] = '\0';
10900c615f4eSAzat Khuzhin 		k = j;
10910c615f4eSAzat Khuzhin 		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name)) < 0)
10920c615f4eSAzat Khuzhin 			goto err;
10930c615f4eSAzat Khuzhin 		if (name_parse(req->request, req->request_len, &k,
10940c615f4eSAzat Khuzhin 			cmp_name, sizeof(cmp_name))<0)
10950c615f4eSAzat Khuzhin 			goto err;
10969c238debSAzat Khuzhin 		if (!base->global_randomize_case) {
10970c615f4eSAzat Khuzhin 			if (strcmp(tmp_name, cmp_name) == 0)
10980c615f4eSAzat Khuzhin 				name_matches = 1;
10990c615f4eSAzat Khuzhin 		} else {
11000c615f4eSAzat Khuzhin 			if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0)
11010c615f4eSAzat Khuzhin 				name_matches = 1;
11020c615f4eSAzat Khuzhin 		}
11030c615f4eSAzat Khuzhin 
1104cca7249eSNiels Provos 		j += 4;
11050c615f4eSAzat Khuzhin 		if (j > length)
11060c615f4eSAzat Khuzhin 			goto err;
1107cca7249eSNiels Provos 	}
1108cca7249eSNiels Provos 
1109dd731685SNick Mathewson 	if (!name_matches)
1110dd731685SNick Mathewson 		goto err;
1111dd731685SNick Mathewson 
11127c6df310SNiels Provos 	/* now we have the answer section which looks like
11137c6df310SNiels Provos 	 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
11147c6df310SNiels Provos 	 */
1115cca7249eSNiels Provos 
1116cca7249eSNiels Provos 	for (i = 0; i < answers; ++i) {
1117cca7249eSNiels Provos 		u16 type, class;
1118cca7249eSNiels Provos 
1119cca7249eSNiels Provos 		SKIP_NAME;
1120cca7249eSNiels Provos 		GET16(type);
1121cca7249eSNiels Provos 		GET16(class);
1122cca7249eSNiels Provos 		GET32(ttl);
1123cca7249eSNiels Provos 		GET16(datalength);
1124cca7249eSNiels Provos 
1125cca7249eSNiels Provos 		if (type == TYPE_A && class == CLASS_INET) {
1126fe1dfe0fSNiels Provos 			int addrcount, addrtocopy;
1127fe1dfe0fSNiels Provos 			if (req->request_type != TYPE_A) {
1128fe1dfe0fSNiels Provos 				j += datalength; continue;
1129fe1dfe0fSNiels Provos 			}
11305baf8ecfSNiels Provos 			if ((datalength & 3) != 0) /* not an even number of As. */
11315d3b6a83SNiels Provos 			    goto err;
1132fe1dfe0fSNiels Provos 			addrcount = datalength >> 2;
113386f57420SNick Mathewson 			addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
1134cca7249eSNiels Provos 
1135cca7249eSNiels Provos 			ttl_r = MIN(ttl_r, ttl);
11367c6df310SNiels Provos 			/* we only bother with the first four addresses. */
11375d3b6a83SNiels Provos 			if (j + 4*addrtocopy > length) goto err;
1138fe1dfe0fSNiels Provos 			memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
1139fe1dfe0fSNiels Provos 				   packet + j, 4*addrtocopy);
1140cca7249eSNiels Provos 			j += 4*addrtocopy;
1141fe1dfe0fSNiels Provos 			reply.data.a.addrcount += addrtocopy;
1142fe1dfe0fSNiels Provos 			reply.have_answer = 1;
114386f57420SNick Mathewson 			if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
1144fe1dfe0fSNiels Provos 		} else if (type == TYPE_PTR && class == CLASS_INET) {
1145fe1dfe0fSNiels Provos 			if (req->request_type != TYPE_PTR) {
1146fe1dfe0fSNiels Provos 				j += datalength; continue;
1147fe1dfe0fSNiels Provos 			}
1148fe1dfe0fSNiels Provos 			if (name_parse(packet, length, &j, reply.data.ptr.name,
1149fe1dfe0fSNiels Provos 						   sizeof(reply.data.ptr.name))<0)
11505d3b6a83SNiels Provos 				goto err;
1151faf5f73aSNiels Provos 			ttl_r = MIN(ttl_r, ttl);
1152fe1dfe0fSNiels Provos 			reply.have_answer = 1;
1153fe1dfe0fSNiels Provos 			break;
115486f57420SNick Mathewson 		} else if (type == TYPE_CNAME) {
115586f57420SNick Mathewson 			char cname[HOST_NAME_MAX];
115686f57420SNick Mathewson 			if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
115786f57420SNick Mathewson 				j += datalength; continue;
115886f57420SNick Mathewson 			}
115986f57420SNick Mathewson 			if (name_parse(packet, length, &j, cname,
116086f57420SNick Mathewson 				sizeof(cname))<0)
116186f57420SNick Mathewson 				goto err;
116286f57420SNick Mathewson 			*req->put_cname_in_ptr = mm_strdup(cname);
11636318fca2SNiels Provos 		} else if (type == TYPE_AAAA && class == CLASS_INET) {
11646318fca2SNiels Provos 			int addrcount, addrtocopy;
11656318fca2SNiels Provos 			if (req->request_type != TYPE_AAAA) {
11666318fca2SNiels Provos 				j += datalength; continue;
11676318fca2SNiels Provos 			}
11685baf8ecfSNiels Provos 			if ((datalength & 15) != 0) /* not an even number of AAAAs. */
11695d3b6a83SNiels Provos 				goto err;
11707c6df310SNiels Provos 			addrcount = datalength >> 4;  /* each address is 16 bytes long */
117186f57420SNick Mathewson 			addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
11726318fca2SNiels Provos 			ttl_r = MIN(ttl_r, ttl);
11736318fca2SNiels Provos 
11747c6df310SNiels Provos 			/* we only bother with the first four addresses. */
11755d3b6a83SNiels Provos 			if (j + 16*addrtocopy > length) goto err;
11766318fca2SNiels Provos 			memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
11776318fca2SNiels Provos 				   packet + j, 16*addrtocopy);
11786318fca2SNiels Provos 			reply.data.aaaa.addrcount += addrtocopy;
11796318fca2SNiels Provos 			j += 16*addrtocopy;
11806318fca2SNiels Provos 			reply.have_answer = 1;
118186f57420SNick Mathewson 			if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
1182cca7249eSNiels Provos 		} else {
11837c6df310SNiels Provos 			/* skip over any other type of resource */
1184cca7249eSNiels Provos 			j += datalength;
1185cca7249eSNiels Provos 		}
1186cca7249eSNiels Provos 	}
1187cca7249eSNiels Provos 
1188f72e8f66SLeonid Evdokimov 	if (!reply.have_answer) {
1189f72e8f66SLeonid Evdokimov 		for (i = 0; i < authority; ++i) {
1190f72e8f66SLeonid Evdokimov 			u16 type, class;
1191f72e8f66SLeonid Evdokimov 			SKIP_NAME;
1192f72e8f66SLeonid Evdokimov 			GET16(type);
1193f72e8f66SLeonid Evdokimov 			GET16(class);
1194f72e8f66SLeonid Evdokimov 			GET32(ttl);
1195f72e8f66SLeonid Evdokimov 			GET16(datalength);
1196f72e8f66SLeonid Evdokimov 			if (type == TYPE_SOA && class == CLASS_INET) {
1197f72e8f66SLeonid Evdokimov 				u32 serial, refresh, retry, expire, minimum;
1198f72e8f66SLeonid Evdokimov 				SKIP_NAME;
1199f72e8f66SLeonid Evdokimov 				SKIP_NAME;
1200f72e8f66SLeonid Evdokimov 				GET32(serial);
1201f72e8f66SLeonid Evdokimov 				GET32(refresh);
1202f72e8f66SLeonid Evdokimov 				GET32(retry);
1203f72e8f66SLeonid Evdokimov 				GET32(expire);
1204f72e8f66SLeonid Evdokimov 				GET32(minimum);
120539c0cf7cSNick Mathewson 				(void)expire;
120639c0cf7cSNick Mathewson 				(void)retry;
120739c0cf7cSNick Mathewson 				(void)refresh;
120839c0cf7cSNick Mathewson 				(void)serial;
1209f72e8f66SLeonid Evdokimov 				ttl_r = MIN(ttl_r, ttl);
1210f72e8f66SLeonid Evdokimov 				ttl_r = MIN(ttl_r, minimum);
1211f72e8f66SLeonid Evdokimov 			} else {
1212f72e8f66SLeonid Evdokimov 				/* skip over any other type of resource */
1213f72e8f66SLeonid Evdokimov 				j += datalength;
1214f72e8f66SLeonid Evdokimov 			}
1215f72e8f66SLeonid Evdokimov 		}
1216f72e8f66SLeonid Evdokimov 	}
1217f72e8f66SLeonid Evdokimov 
1218f72e8f66SLeonid Evdokimov 	if (ttl_r == 0xffffffff)
1219f72e8f66SLeonid Evdokimov 		ttl_r = 0;
1220f72e8f66SLeonid Evdokimov 
1221fe1dfe0fSNiels Provos 	reply_handle(req, flags, ttl_r, &reply);
1222fe1dfe0fSNiels Provos 	return 0;
12235baf8ecfSNiels Provos  err:
12245d3b6a83SNiels Provos 	if (req)
12255d3b6a83SNiels Provos 		reply_handle(req, flags, 0, NULL);
12265baf8ecfSNiels Provos 	return -1;
1227faf5f73aSNiels Provos }
1228faf5f73aSNiels Provos 
12297c6df310SNiels Provos /* Parse a raw request (packet,length) sent to a nameserver port (port) from */
12307c6df310SNiels Provos /* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
12317c6df310SNiels Provos /* callback. */
1232faf5f73aSNiels Provos static int
request_parse(u8 * packet,int length,struct evdns_server_port * port,struct sockaddr * addr,ev_socklen_t addrlen)12337c20a6aeSNick Mathewson request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
1234faf5f73aSNiels Provos {
12357c6df310SNiels Provos 	int j = 0;	/* index into packet */
1236cb9da0bfSNick Mathewson 	u16 t_;	 /* used by the macros */
12377c6df310SNiels Provos 	char tmp_name[256]; /* used by the macros */
1238faf5f73aSNiels Provos 
1239faf5f73aSNiels Provos 	int i;
1240faf5f73aSNiels Provos 	u16 trans_id, flags, questions, answers, authority, additional;
1241faf5f73aSNiels Provos 	struct server_request *server_req = NULL;
1242faf5f73aSNiels Provos 
1243327165b3SNick Mathewson 	ASSERT_LOCKED(port);
1244327165b3SNick Mathewson 
12457c6df310SNiels Provos 	/* Get the header fields */
1246faf5f73aSNiels Provos 	GET16(trans_id);
1247faf5f73aSNiels Provos 	GET16(flags);
1248faf5f73aSNiels Provos 	GET16(questions);
1249faf5f73aSNiels Provos 	GET16(answers);
1250faf5f73aSNiels Provos 	GET16(authority);
1251faf5f73aSNiels Provos 	GET16(additional);
125206a714ffSNick Mathewson 	(void)answers;
125306a714ffSNick Mathewson 	(void)additional;
125406a714ffSNick Mathewson 	(void)authority;
1255faf5f73aSNiels Provos 
1256fcdda24bSNathan French 	if (flags & _QR_MASK) return -1; /* Must not be an answer. */
1257fcdda24bSNathan French 	flags &= (_RD_MASK|_CD_MASK); /* Only RD and CD get preserved. */
1258faf5f73aSNiels Provos 
125949868b61SNick Mathewson 	server_req = mm_malloc(sizeof(struct server_request));
1260faf5f73aSNiels Provos 	if (server_req == NULL) return -1;
1261faf5f73aSNiels Provos 	memset(server_req, 0, sizeof(struct server_request));
1262faf5f73aSNiels Provos 
1263faf5f73aSNiels Provos 	server_req->trans_id = trans_id;
1264faf5f73aSNiels Provos 	memcpy(&server_req->addr, addr, addrlen);
1265faf5f73aSNiels Provos 	server_req->addrlen = addrlen;
1266faf5f73aSNiels Provos 
1267faf5f73aSNiels Provos 	server_req->base.flags = flags;
1268faf5f73aSNiels Provos 	server_req->base.nquestions = 0;
126918a8cfacSNick Mathewson 	server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
1270faf5f73aSNiels Provos 	if (server_req->base.questions == NULL)
1271faf5f73aSNiels Provos 		goto err;
1272faf5f73aSNiels Provos 
1273faf5f73aSNiels Provos 	for (i = 0; i < questions; ++i) {
1274faf5f73aSNiels Provos 		u16 type, class;
1275faf5f73aSNiels Provos 		struct evdns_server_question *q;
1276faf5f73aSNiels Provos 		int namelen;
1277faf5f73aSNiels Provos 		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
1278faf5f73aSNiels Provos 			goto err;
1279faf5f73aSNiels Provos 		GET16(type);
1280faf5f73aSNiels Provos 		GET16(class);
1281545a6114SNick Mathewson 		namelen = (int)strlen(tmp_name);
128249868b61SNick Mathewson 		q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
1283faf5f73aSNiels Provos 		if (!q)
1284faf5f73aSNiels Provos 			goto err;
1285faf5f73aSNiels Provos 		q->type = type;
12867c507668SNick Mathewson 		q->dns_question_class = class;
1287faf5f73aSNiels Provos 		memcpy(q->name, tmp_name, namelen+1);
1288faf5f73aSNiels Provos 		server_req->base.questions[server_req->base.nquestions++] = q;
1289faf5f73aSNiels Provos 	}
1290faf5f73aSNiels Provos 
12917c6df310SNiels Provos 	/* Ignore answers, authority, and additional. */
1292faf5f73aSNiels Provos 
1293faf5f73aSNiels Provos 	server_req->port = port;
1294faf5f73aSNiels Provos 	port->refcnt++;
129582153e6eSNick Mathewson 
129682153e6eSNick Mathewson 	/* Only standard queries are supported. */
1297fcdda24bSNathan French 	if (flags & _OP_MASK) {
129882153e6eSNick Mathewson 		evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
129982153e6eSNick Mathewson 		return -1;
130082153e6eSNick Mathewson 	}
130182153e6eSNick Mathewson 
1302faf5f73aSNiels Provos 	port->user_callback(&(server_req->base), port->user_data);
1303faf5f73aSNiels Provos 
1304faf5f73aSNiels Provos 	return 0;
1305faf5f73aSNiels Provos err:
1306faf5f73aSNiels Provos 	if (server_req->base.questions) {
1307faf5f73aSNiels Provos 		for (i = 0; i < server_req->base.nquestions; ++i)
130849868b61SNick Mathewson 			mm_free(server_req->base.questions[i]);
130949868b61SNick Mathewson 		mm_free(server_req->base.questions);
1310faf5f73aSNiels Provos 	}
131149868b61SNick Mathewson 	mm_free(server_req);
1312faf5f73aSNiels Provos 	return -1;
1313faf5f73aSNiels Provos 
1314cca7249eSNiels Provos #undef SKIP_NAME
1315cca7249eSNiels Provos #undef GET32
1316cca7249eSNiels Provos #undef GET16
1317cca7249eSNiels Provos #undef GET8
1318cca7249eSNiels Provos }
1319cca7249eSNiels Provos 
1320dd731685SNick Mathewson 
1321626cc5f9SNick Mathewson void
evdns_set_transaction_id_fn(ev_uint16_t (* fn)(void))132211230f7eSNick Mathewson evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
1323626cc5f9SNick Mathewson {
1324dd731685SNick Mathewson }
1325dd731685SNick Mathewson 
1326dd731685SNick Mathewson void
evdns_set_random_bytes_fn(void (* fn)(char *,size_t))1327dd731685SNick Mathewson evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
1328dd731685SNick Mathewson {
1329626cc5f9SNick Mathewson }
1330626cc5f9SNick Mathewson 
1331626cc5f9SNick Mathewson /* Try to choose a strong transaction id which isn't already in flight */
1332626cc5f9SNick Mathewson static u16
transaction_id_pick(struct evdns_base * base)1333e688a88aSNick Mathewson transaction_id_pick(struct evdns_base *base) {
1334327165b3SNick Mathewson 	ASSERT_LOCKED(base);
1335626cc5f9SNick Mathewson 	for (;;) {
1336d4de062eSNick Mathewson 		u16 trans_id;
1337d4de062eSNick Mathewson 		evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
1338cca7249eSNiels Provos 
1339cca7249eSNiels Provos 		if (trans_id == 0xffff) continue;
13407c6df310SNiels Provos 		/* now check to see if that id is already inflight */
134149868b61SNick Mathewson 		if (request_find_from_trans_id(base, trans_id) == NULL)
134249868b61SNick Mathewson 			return trans_id;
1343cca7249eSNiels Provos 	}
1344cca7249eSNiels Provos }
1345cca7249eSNiels Provos 
13467c6df310SNiels Provos /* choose a namesever to use. This function will try to ignore */
13477c6df310SNiels Provos /* nameservers which we think are down and load balance across the rest */
13487c6df310SNiels Provos /* by updating the server_head global each time. */
1349cca7249eSNiels Provos static struct nameserver *
nameserver_pick(struct evdns_base * base)1350e688a88aSNick Mathewson nameserver_pick(struct evdns_base *base) {
1351e688a88aSNick Mathewson 	struct nameserver *started_at = base->server_head, *picked;
1352327165b3SNick Mathewson 	ASSERT_LOCKED(base);
1353e688a88aSNick Mathewson 	if (!base->server_head) return NULL;
1354cca7249eSNiels Provos 
13557c6df310SNiels Provos 	/* if we don't have any good nameservers then there's no */
13567c6df310SNiels Provos 	/* point in trying to find one. */
1357e688a88aSNick Mathewson 	if (!base->global_good_nameservers) {
1358e688a88aSNick Mathewson 		base->server_head = base->server_head->next;
1359e688a88aSNick Mathewson 		return base->server_head;
1360cca7249eSNiels Provos 	}
1361cca7249eSNiels Provos 
13627c6df310SNiels Provos 	/* remember that nameservers are in a circular list */
1363cca7249eSNiels Provos 	for (;;) {
1364e688a88aSNick Mathewson 		if (base->server_head->state) {
13657c6df310SNiels Provos 			/* we think this server is currently good */
1366e688a88aSNick Mathewson 			picked = base->server_head;
1367e688a88aSNick Mathewson 			base->server_head = base->server_head->next;
1368cca7249eSNiels Provos 			return picked;
1369cca7249eSNiels Provos 		}
1370cca7249eSNiels Provos 
1371e688a88aSNick Mathewson 		base->server_head = base->server_head->next;
1372e688a88aSNick Mathewson 		if (base->server_head == started_at) {
13737c6df310SNiels Provos 			/* all the nameservers seem to be down */
13747c6df310SNiels Provos 			/* so we just return this one and hope for the */
13757c6df310SNiels Provos 			/* best */
13762e36dbe1SNick Mathewson 			EVUTIL_ASSERT(base->global_good_nameservers == 0);
1377e688a88aSNick Mathewson 			picked = base->server_head;
1378e688a88aSNick Mathewson 			base->server_head = base->server_head->next;
1379cca7249eSNiels Provos 			return picked;
1380cca7249eSNiels Provos 		}
1381cca7249eSNiels Provos 	}
1382cca7249eSNiels Provos }
1383cca7249eSNiels Provos 
13847c6df310SNiels Provos /* this is called when a namesever socket is ready for reading */
1385cca7249eSNiels Provos static void
nameserver_read(struct nameserver * ns)1386cca7249eSNiels Provos nameserver_read(struct nameserver *ns) {
1387c6f4dc98SNick Mathewson 	struct sockaddr_storage ss;
13887c20a6aeSNick Mathewson 	ev_socklen_t addrlen = sizeof(ss);
1389cca7249eSNiels Provos 	u8 packet[1500];
1390b1c79500SNick Mathewson 	char addrbuf[128];
1391327165b3SNick Mathewson 	ASSERT_LOCKED(ns->base);
1392cca7249eSNiels Provos 
1393cca7249eSNiels Provos 	for (;;) {
13945b7a3706SNick Mathewson 		const int r = recvfrom(ns->socket, (void*)packet,
13955b7a3706SNick Mathewson 		    sizeof(packet), 0,
1396c6f4dc98SNick Mathewson 		    (struct sockaddr*)&ss, &addrlen);
1397cca7249eSNiels Provos 		if (r < 0) {
1398de069b99SNick Mathewson 			int err = evutil_socket_geterror(ns->socket);
139981ab45adSNick Mathewson 			if (EVUTIL_ERR_RW_RETRIABLE(err))
140081ab45adSNick Mathewson 				return;
1401c6f4dc98SNick Mathewson 			nameserver_failed(ns,
1402c6f4dc98SNick Mathewson 			    evutil_socket_error_to_string(err));
1403cca7249eSNiels Provos 			return;
1404cca7249eSNiels Provos 		}
1405621aafd2SNick Mathewson 		if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
1406c6f4dc98SNick Mathewson 			(struct sockaddr*)&ns->address, 0)) {
1407c6f4dc98SNick Mathewson 			log(EVDNS_LOG_WARN, "Address mismatch on received "
1408c6f4dc98SNick Mathewson 			    "DNS packet.  Apparent source was %s",
14098ac3c4c2SNick Mathewson 			    evutil_format_sockaddr_port_(
1410b1c79500SNick Mathewson 				    (struct sockaddr *)&ss,
1411b1c79500SNick Mathewson 				    addrbuf, sizeof(addrbuf)));
1412c6f4dc98SNick Mathewson 			return;
1413c6f4dc98SNick Mathewson 		}
1414c6f4dc98SNick Mathewson 
14150147ef3aSNiels Provos 		ns->timedout = 0;
1416e688a88aSNick Mathewson 		reply_parse(ns->base, packet, r);
1417cca7249eSNiels Provos 	}
1418cca7249eSNiels Provos }
1419cca7249eSNiels Provos 
14207c6df310SNiels Provos /* Read a packet from a DNS client on a server port s, parse it, and */
14217c6df310SNiels Provos /* act accordingly. */
1422faf5f73aSNiels Provos static void
server_port_read(struct evdns_server_port * s)1423faf5f73aSNiels Provos server_port_read(struct evdns_server_port *s) {
1424faf5f73aSNiels Provos 	u8 packet[1500];
1425faf5f73aSNiels Provos 	struct sockaddr_storage addr;
14267c20a6aeSNick Mathewson 	ev_socklen_t addrlen;
1427faf5f73aSNiels Provos 	int r;
1428327165b3SNick Mathewson 	ASSERT_LOCKED(s);
1429faf5f73aSNiels Provos 
1430faf5f73aSNiels Provos 	for (;;) {
1431faf5f73aSNiels Provos 		addrlen = sizeof(struct sockaddr_storage);
14325b7a3706SNick Mathewson 		r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
1433faf5f73aSNiels Provos 					 (struct sockaddr*) &addr, &addrlen);
1434faf5f73aSNiels Provos 		if (r < 0) {
1435de069b99SNick Mathewson 			int err = evutil_socket_geterror(s->socket);
143681ab45adSNick Mathewson 			if (EVUTIL_ERR_RW_RETRIABLE(err))
143781ab45adSNick Mathewson 				return;
1438b2f2be6eSNick Mathewson 			log(EVDNS_LOG_WARN,
1439b2f2be6eSNick Mathewson 			    "Error %s (%d) while reading request.",
1440de069b99SNick Mathewson 			    evutil_socket_error_to_string(err), err);
1441faf5f73aSNiels Provos 			return;
1442faf5f73aSNiels Provos 		}
1443faf5f73aSNiels Provos 		request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
1444faf5f73aSNiels Provos 	}
1445faf5f73aSNiels Provos }
1446faf5f73aSNiels Provos 
14477c6df310SNiels Provos /* Try to write all pending replies on a given DNS server port. */
1448faf5f73aSNiels Provos static void
server_port_flush(struct evdns_server_port * port)1449faf5f73aSNiels Provos server_port_flush(struct evdns_server_port *port)
1450faf5f73aSNiels Provos {
1451faf5f73aSNiels Provos 	struct server_request *req = port->pending_replies;
1452439aea0dSNick Mathewson 	ASSERT_LOCKED(port);
1453439aea0dSNick Mathewson 	while (req) {
1454545a6114SNick Mathewson 		int r = sendto(port->socket, req->response, (int)req->response_len, 0,
1455545a6114SNick Mathewson 			   (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
1456faf5f73aSNiels Provos 		if (r < 0) {
1457de069b99SNick Mathewson 			int err = evutil_socket_geterror(port->socket);
145881ab45adSNick Mathewson 			if (EVUTIL_ERR_RW_RETRIABLE(err))
1459faf5f73aSNiels Provos 				return;
1460de069b99SNick Mathewson 			log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
1461faf5f73aSNiels Provos 		}
1462faf5f73aSNiels Provos 		if (server_request_free(req)) {
14637c6df310SNiels Provos 			/* we released the last reference to req->port. */
1464faf5f73aSNiels Provos 			return;
1465439aea0dSNick Mathewson 		} else {
1466439aea0dSNick Mathewson 			EVUTIL_ASSERT(req != port->pending_replies);
1467439aea0dSNick Mathewson 			req = port->pending_replies;
1468faf5f73aSNiels Provos 		}
1469faf5f73aSNiels Provos 	}
1470faf5f73aSNiels Provos 
14717c6df310SNiels Provos 	/* We have no more pending requests; stop listening for 'writeable' events. */
1472faf5f73aSNiels Provos 	(void) event_del(&port->event);
14735fbc7f0aSNick Mathewson 	event_assign(&port->event, port->event_base,
14745fbc7f0aSNick Mathewson 				 port->socket, EV_READ | EV_PERSIST,
1475faf5f73aSNiels Provos 				 server_port_ready_callback, port);
14765fbc7f0aSNick Mathewson 
1477faf5f73aSNiels Provos 	if (event_add(&port->event, NULL) < 0) {
1478faf5f73aSNiels Provos 		log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
14797c6df310SNiels Provos 		/* ???? Do more? */
1480faf5f73aSNiels Provos 	}
1481faf5f73aSNiels Provos }
1482faf5f73aSNiels Provos 
14837c6df310SNiels Provos /* set if we are waiting for the ability to write to this server. */
14847c6df310SNiels Provos /* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
14857c6df310SNiels Provos /* we stop these events. */
1486cca7249eSNiels Provos static void
nameserver_write_waiting(struct nameserver * ns,char waiting)1487cca7249eSNiels Provos nameserver_write_waiting(struct nameserver *ns, char waiting) {
1488327165b3SNick Mathewson 	ASSERT_LOCKED(ns->base);
1489cca7249eSNiels Provos 	if (ns->write_waiting == waiting) return;
1490cca7249eSNiels Provos 
1491cca7249eSNiels Provos 	ns->write_waiting = waiting;
1492cca7249eSNiels Provos 	(void) event_del(&ns->event);
14935fbc7f0aSNick Mathewson 	event_assign(&ns->event, ns->base->event_base,
14945fbc7f0aSNick Mathewson 	    ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
1495cca7249eSNiels Provos 	    nameserver_ready_callback, ns);
1496cca7249eSNiels Provos 	if (event_add(&ns->event, NULL) < 0) {
1497b1c79500SNick Mathewson 		char addrbuf[128];
1498fe1dfe0fSNiels Provos 		log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
14998ac3c4c2SNick Mathewson 		    evutil_format_sockaddr_port_(
1500b1c79500SNick Mathewson 			    (struct sockaddr *)&ns->address,
1501b1c79500SNick Mathewson 			    addrbuf, sizeof(addrbuf)));
15027c6df310SNiels Provos 		/* ???? Do more? */
1503cca7249eSNiels Provos 	}
1504cca7249eSNiels Provos }
1505cca7249eSNiels Provos 
15067c6df310SNiels Provos /* a callback function. Called by libevent when the kernel says that */
15077c6df310SNiels Provos /* a nameserver socket is ready for writing or reading */
1508cca7249eSNiels Provos static void
nameserver_ready_callback(evutil_socket_t fd,short events,void * arg)15091120f04fSNick Mathewson nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
1510cca7249eSNiels Provos 	struct nameserver *ns = (struct nameserver *) arg;
1511cca7249eSNiels Provos 	(void)fd;
1512cca7249eSNiels Provos 
1513327165b3SNick Mathewson 	EVDNS_LOCK(ns->base);
1514cca7249eSNiels Provos 	if (events & EV_WRITE) {
15155baf8ecfSNiels Provos 		ns->choked = 0;
1516e688a88aSNick Mathewson 		if (!evdns_transmit(ns->base)) {
1517cca7249eSNiels Provos 			nameserver_write_waiting(ns, 0);
1518cca7249eSNiels Provos 		}
1519cca7249eSNiels Provos 	}
1520cca7249eSNiels Provos 	if (events & EV_READ) {
1521cca7249eSNiels Provos 		nameserver_read(ns);
1522cca7249eSNiels Provos 	}
1523327165b3SNick Mathewson 	EVDNS_UNLOCK(ns->base);
1524cca7249eSNiels Provos }
1525cca7249eSNiels Provos 
15267c6df310SNiels Provos /* a callback function. Called by libevent when the kernel says that */
15277c6df310SNiels Provos /* a server socket is ready for writing or reading. */
1528faf5f73aSNiels Provos static void
server_port_ready_callback(evutil_socket_t fd,short events,void * arg)15291120f04fSNick Mathewson server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
1530faf5f73aSNiels Provos 	struct evdns_server_port *port = (struct evdns_server_port *) arg;
1531faf5f73aSNiels Provos 	(void) fd;
1532faf5f73aSNiels Provos 
1533327165b3SNick Mathewson 	EVDNS_LOCK(port);
1534faf5f73aSNiels Provos 	if (events & EV_WRITE) {
1535faf5f73aSNiels Provos 		port->choked = 0;
1536faf5f73aSNiels Provos 		server_port_flush(port);
1537faf5f73aSNiels Provos 	}
1538faf5f73aSNiels Provos 	if (events & EV_READ) {
1539faf5f73aSNiels Provos 		server_port_read(port);
1540faf5f73aSNiels Provos 	}
1541327165b3SNick Mathewson 	EVDNS_UNLOCK(port);
1542faf5f73aSNiels Provos }
1543faf5f73aSNiels Provos 
1544b776b2daSNiels Provos /* This is an inefficient representation; only use it via the dnslabel_table_*
1545b776b2daSNiels Provos  * functions, so that is can be safely replaced with something smarter later. */
1546b776b2daSNiels Provos #define MAX_LABELS 128
15477c6df310SNiels Provos /* Structures used to implement name compression */
1548f0ff792aSNiels Provos struct dnslabel_entry { char *v; off_t pos; };
1549b776b2daSNiels Provos struct dnslabel_table {
15507c6df310SNiels Provos 	int n_labels; /* number of current entries */
15517c6df310SNiels Provos 	/* map from name to position in message */
1552b776b2daSNiels Provos 	struct dnslabel_entry labels[MAX_LABELS];
1553b776b2daSNiels Provos };
1554b776b2daSNiels Provos 
15557c6df310SNiels Provos /* Initialize dnslabel_table. */
1556b776b2daSNiels Provos static void
dnslabel_table_init(struct dnslabel_table * table)1557b776b2daSNiels Provos dnslabel_table_init(struct dnslabel_table *table)
1558b776b2daSNiels Provos {
1559b776b2daSNiels Provos 	table->n_labels = 0;
1560b776b2daSNiels Provos }
1561b776b2daSNiels Provos 
15627c6df310SNiels Provos /* Free all storage held by table, but not the table itself. */
1563b776b2daSNiels Provos static void
dnslabel_clear(struct dnslabel_table * table)1564b776b2daSNiels Provos dnslabel_clear(struct dnslabel_table *table)
1565b776b2daSNiels Provos {
1566b776b2daSNiels Provos 	int i;
1567b776b2daSNiels Provos 	for (i = 0; i < table->n_labels; ++i)
156849868b61SNick Mathewson 		mm_free(table->labels[i].v);
1569b776b2daSNiels Provos 	table->n_labels = 0;
1570b776b2daSNiels Provos }
1571b776b2daSNiels Provos 
15727c6df310SNiels Provos /* return the position of the label in the current message, or -1 if the label */
15737c6df310SNiels Provos /* hasn't been used yet. */
1574b776b2daSNiels Provos static int
dnslabel_table_get_pos(const struct dnslabel_table * table,const char * label)1575b776b2daSNiels Provos dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
1576b776b2daSNiels Provos {
1577b776b2daSNiels Provos 	int i;
1578b776b2daSNiels Provos 	for (i = 0; i < table->n_labels; ++i) {
1579b776b2daSNiels Provos 		if (!strcmp(label, table->labels[i].v))
1580b776b2daSNiels Provos 			return table->labels[i].pos;
1581b776b2daSNiels Provos 	}
1582b776b2daSNiels Provos 	return -1;
1583b776b2daSNiels Provos }
1584b776b2daSNiels Provos 
15857c6df310SNiels Provos /* remember that we've used the label at position pos */
1586b776b2daSNiels Provos static int
dnslabel_table_add(struct dnslabel_table * table,const char * label,off_t pos)1587f0ff792aSNiels Provos dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
1588b776b2daSNiels Provos {
1589b776b2daSNiels Provos 	char *v;
1590b776b2daSNiels Provos 	int p;
1591b776b2daSNiels Provos 	if (table->n_labels == MAX_LABELS)
1592b776b2daSNiels Provos 		return (-1);
159349868b61SNick Mathewson 	v = mm_strdup(label);
1594b776b2daSNiels Provos 	if (v == NULL)
1595b776b2daSNiels Provos 		return (-1);
1596b776b2daSNiels Provos 	p = table->n_labels++;
1597b776b2daSNiels Provos 	table->labels[p].v = v;
1598b776b2daSNiels Provos 	table->labels[p].pos = pos;
1599b776b2daSNiels Provos 
1600b776b2daSNiels Provos 	return (0);
1601b776b2daSNiels Provos }
1602b776b2daSNiels Provos 
16037c6df310SNiels Provos /* Converts a string to a length-prefixed set of DNS labels, starting */
16047c6df310SNiels Provos /* at buf[j]. name and buf must not overlap. name_len should be the length */
16057c6df310SNiels Provos /* of name.	 table is optional, and is used for compression. */
16067c6df310SNiels Provos /* */
16077c6df310SNiels Provos /* Input: abc.def */
16087c6df310SNiels Provos /* Output: <3>abc<3>def<0> */
16097c6df310SNiels Provos /* */
16107c6df310SNiels Provos /* Returns the first index after the encoded name, or negative on error. */
16117c6df310SNiels Provos /*	 -1	 label was > 63 bytes */
16127c6df310SNiels Provos /*	 -2	 name too long to fit in buffer. */
16137c6df310SNiels Provos /* */
1614b776b2daSNiels Provos 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)1615b776b2daSNiels Provos dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
1616545a6114SNick Mathewson 				  const char *name, const size_t name_len,
1617b776b2daSNiels Provos 				  struct dnslabel_table *table) {
1618fe1dfe0fSNiels Provos 	const char *end = name + name_len;
1619b776b2daSNiels Provos 	int ref = 0;
1620cb9da0bfSNick Mathewson 	u16 t_;
1621b776b2daSNiels Provos 
1622b776b2daSNiels Provos #define APPEND16(x) do {						\
1623b776b2daSNiels Provos 		if (j + 2 > (off_t)buf_len)				\
1624b776b2daSNiels Provos 			goto overflow;					\
1625cb9da0bfSNick Mathewson 		t_ = htons(x);						\
1626cb9da0bfSNick Mathewson 		memcpy(buf + j, &t_, 2);				\
1627b776b2daSNiels Provos 		j += 2;							\
1628b776b2daSNiels Provos 	} while (0)
1629b776b2daSNiels Provos #define APPEND32(x) do {						\
1630b776b2daSNiels Provos 		if (j + 4 > (off_t)buf_len)				\
1631b776b2daSNiels Provos 			goto overflow;					\
1632cb9da0bfSNick Mathewson 		t32_ = htonl(x);					\
1633cb9da0bfSNick Mathewson 		memcpy(buf + j, &t32_, 4);				\
1634b776b2daSNiels Provos 		j += 4;							\
1635b776b2daSNiels Provos 	} while (0)
1636cca7249eSNiels Provos 
1637cca7249eSNiels Provos 	if (name_len > 255) return -2;
1638cca7249eSNiels Provos 
1639cca7249eSNiels Provos 	for (;;) {
1640cca7249eSNiels Provos 		const char *const start = name;
1641b776b2daSNiels Provos 		if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
1642b776b2daSNiels Provos 			APPEND16(ref | 0xc000);
1643b776b2daSNiels Provos 			return j;
1644b776b2daSNiels Provos 		}
1645cca7249eSNiels Provos 		name = strchr(name, '.');
1646cca7249eSNiels Provos 		if (!name) {
1647545a6114SNick Mathewson 			const size_t label_len = end - start;
1648cca7249eSNiels Provos 			if (label_len > 63) return -1;
1649b776b2daSNiels Provos 			if ((size_t)(j+label_len+1) > buf_len) return -2;
1650b776b2daSNiels Provos 			if (table) dnslabel_table_add(table, start, j);
1651545a6114SNick Mathewson 			buf[j++] = (ev_uint8_t)label_len;
1652cca7249eSNiels Provos 
1653ba014569SNick Mathewson 			memcpy(buf + j, start, label_len);
1654ba014569SNick Mathewson 			j += (int) label_len;
1655cca7249eSNiels Provos 			break;
1656cca7249eSNiels Provos 		} else {
16577c6df310SNiels Provos 			/* append length of the label. */
1658545a6114SNick Mathewson 			const size_t label_len = name - start;
1659cca7249eSNiels Provos 			if (label_len > 63) return -1;
1660b776b2daSNiels Provos 			if ((size_t)(j+label_len+1) > buf_len) return -2;
1661b776b2daSNiels Provos 			if (table) dnslabel_table_add(table, start, j);
1662545a6114SNick Mathewson 			buf[j++] = (ev_uint8_t)label_len;
1663cca7249eSNiels Provos 
1664ba014569SNick Mathewson 			memcpy(buf + j, start, label_len);
1665ba014569SNick Mathewson 			j += (int) label_len;
16667c6df310SNiels Provos 			/* hop over the '.' */
1667cca7249eSNiels Provos 			name++;
1668cca7249eSNiels Provos 		}
1669cca7249eSNiels Provos 	}
1670cca7249eSNiels Provos 
16717c6df310SNiels Provos 	/* the labels must be terminated by a 0. */
16727c6df310SNiels Provos 	/* It's possible that the name ended in a . */
16737c6df310SNiels Provos 	/* in which case the zero is already there */
1674cca7249eSNiels Provos 	if (!j || buf[j-1]) buf[j++] = 0;
1675cca7249eSNiels Provos 	return j;
1676b776b2daSNiels Provos  overflow:
1677b776b2daSNiels Provos 	return (-2);
1678cca7249eSNiels Provos }
1679cca7249eSNiels Provos 
16807c6df310SNiels Provos /* Finds the length of a dns request for a DNS name of the given */
16817c6df310SNiels Provos /* length. The actual request may be smaller than the value returned */
16827c6df310SNiels Provos /* here */
1683e3e696c8SNick Mathewson static size_t
evdns_request_len(const size_t name_len)1684e3e696c8SNick Mathewson evdns_request_len(const size_t name_len) {
16857c6df310SNiels Provos 	return 96 + /* length of the DNS standard header */
1686cca7249eSNiels Provos 		name_len + 2 +
16877c6df310SNiels Provos 		4;  /* space for the resource type */
1688cca7249eSNiels Provos }
1689cca7249eSNiels Provos 
16907c6df310SNiels Provos /* build a dns request packet into buf. buf should be at least as long */
16917c6df310SNiels Provos /* as evdns_request_len told you it should be. */
16927c6df310SNiels Provos /* */
16937c6df310SNiels Provos /* Returns the amount of space used. Negative on error. */
1694cca7249eSNiels Provos 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)1695545a6114SNick Mathewson evdns_request_data_build(const char *const name, const size_t name_len,
169607c3fb50SNiels Provos     const u16 trans_id, const u16 type, const u16 class,
169707c3fb50SNiels Provos     u8 *const buf, size_t buf_len) {
16987c6df310SNiels Provos 	off_t j = 0;  /* current offset into buf */
1699cb9da0bfSNick Mathewson 	u16 t_;	 /* used by the macros */
170007c3fb50SNiels Provos 
1701cca7249eSNiels Provos 	APPEND16(trans_id);
17027c6df310SNiels Provos 	APPEND16(0x0100);  /* standard query, recusion needed */
17037c6df310SNiels Provos 	APPEND16(1);  /* one question */
17047c6df310SNiels Provos 	APPEND16(0);  /* no answers */
17057c6df310SNiels Provos 	APPEND16(0);  /* no authority */
17067c6df310SNiels Provos 	APPEND16(0);  /* no additional */
1707cca7249eSNiels Provos 
1708b776b2daSNiels Provos 	j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
1709b776b2daSNiels Provos 	if (j < 0) {
1710b776b2daSNiels Provos 		return (int)j;
171107c3fb50SNiels Provos 	}
1712cca7249eSNiels Provos 
1713cca7249eSNiels Provos 	APPEND16(type);
1714cca7249eSNiels Provos 	APPEND16(class);
1715cca7249eSNiels Provos 
1716b776b2daSNiels Provos 	return (int)j;
1717b776b2daSNiels Provos  overflow:
1718b776b2daSNiels Provos 	return (-1);
1719cca7249eSNiels Provos }
1720cca7249eSNiels Provos 
17217c6df310SNiels Provos /* exported function */
1722faf5f73aSNiels Provos 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)1723e1c1167cSNick Mathewson 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)
1724faf5f73aSNiels Provos {
1725faf5f73aSNiels Provos 	struct evdns_server_port *port;
1726e1c1167cSNick Mathewson 	if (flags)
1727e1c1167cSNick Mathewson 		return NULL; /* flags not yet implemented */
172849868b61SNick Mathewson 	if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
1729faf5f73aSNiels Provos 		return NULL;
1730faf5f73aSNiels Provos 	memset(port, 0, sizeof(struct evdns_server_port));
1731faf5f73aSNiels Provos 
17327e87a599SNick Mathewson 
1733faf5f73aSNiels Provos 	port->socket = socket;
1734faf5f73aSNiels Provos 	port->refcnt = 1;
1735faf5f73aSNiels Provos 	port->choked = 0;
1736faf5f73aSNiels Provos 	port->closing = 0;
1737faf5f73aSNiels Provos 	port->user_callback = cb;
1738faf5f73aSNiels Provos 	port->user_data = user_data;
1739faf5f73aSNiels Provos 	port->pending_replies = NULL;
1740e688a88aSNick Mathewson 	port->event_base = base;
1741faf5f73aSNiels Provos 
17425fbc7f0aSNick Mathewson 	event_assign(&port->event, port->event_base,
17435fbc7f0aSNick Mathewson 				 port->socket, EV_READ | EV_PERSIST,
1744faf5f73aSNiels Provos 				 server_port_ready_callback, port);
1745c6f4dc98SNick Mathewson 	if (event_add(&port->event, NULL) < 0) {
1746c6f4dc98SNick Mathewson 		mm_free(port);
1747c6f4dc98SNick Mathewson 		return NULL;
1748c6f4dc98SNick Mathewson 	}
1749347952ffSNick Mathewson 	EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
1750faf5f73aSNiels Provos 	return port;
1751faf5f73aSNiels Provos }
1752faf5f73aSNiels Provos 
1753e688a88aSNick Mathewson struct evdns_server_port *
evdns_add_server_port(evutil_socket_t socket,int flags,evdns_request_callback_fn_type cb,void * user_data)1754e1c1167cSNick Mathewson evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
1755e688a88aSNick Mathewson {
1756e1c1167cSNick Mathewson 	return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
1757e688a88aSNick Mathewson }
1758e688a88aSNick Mathewson 
17597c6df310SNiels Provos /* exported function */
1760faf5f73aSNiels Provos void
evdns_close_server_port(struct evdns_server_port * port)1761faf5f73aSNiels Provos evdns_close_server_port(struct evdns_server_port *port)
1762faf5f73aSNiels Provos {
1763327165b3SNick Mathewson 	EVDNS_LOCK(port);
1764327165b3SNick Mathewson 	if (--port->refcnt == 0) {
1765327165b3SNick Mathewson 		EVDNS_UNLOCK(port);
1766faf5f73aSNiels Provos 		server_port_free(port);
1767327165b3SNick Mathewson 	} else {
1768faf5f73aSNiels Provos 		port->closing = 1;
176954103883Szhuizhuhaomeng 		EVDNS_UNLOCK(port);
1770faf5f73aSNiels Provos 	}
1771327165b3SNick Mathewson }
1772faf5f73aSNiels Provos 
17737c6df310SNiels Provos /* exported function */
1774faf5f73aSNiels Provos 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)1775946b5841SNick Mathewson 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)
1776faf5f73aSNiels Provos {
1777946b5841SNick Mathewson 	struct server_request *req = TO_SERVER_REQUEST(req_);
1778faf5f73aSNiels Provos 	struct server_reply_item **itemp, *item;
1779faf5f73aSNiels Provos 	int *countp;
1780327165b3SNick Mathewson 	int result = -1;
1781faf5f73aSNiels Provos 
1782327165b3SNick Mathewson 	EVDNS_LOCK(req->port);
1783faf5f73aSNiels Provos 	if (req->response) /* have we already answered? */
1784327165b3SNick Mathewson 		goto done;
1785faf5f73aSNiels Provos 
1786faf5f73aSNiels Provos 	switch (section) {
1787faf5f73aSNiels Provos 	case EVDNS_ANSWER_SECTION:
1788faf5f73aSNiels Provos 		itemp = &req->answer;
1789faf5f73aSNiels Provos 		countp = &req->n_answer;
1790faf5f73aSNiels Provos 		break;
1791faf5f73aSNiels Provos 	case EVDNS_AUTHORITY_SECTION:
1792faf5f73aSNiels Provos 		itemp = &req->authority;
1793faf5f73aSNiels Provos 		countp = &req->n_authority;
1794faf5f73aSNiels Provos 		break;
1795faf5f73aSNiels Provos 	case EVDNS_ADDITIONAL_SECTION:
1796faf5f73aSNiels Provos 		itemp = &req->additional;
1797faf5f73aSNiels Provos 		countp = &req->n_additional;
1798faf5f73aSNiels Provos 		break;
1799faf5f73aSNiels Provos 	default:
1800327165b3SNick Mathewson 		goto done;
1801faf5f73aSNiels Provos 	}
1802faf5f73aSNiels Provos 	while (*itemp) {
1803faf5f73aSNiels Provos 		itemp = &((*itemp)->next);
1804faf5f73aSNiels Provos 	}
180549868b61SNick Mathewson 	item = mm_malloc(sizeof(struct server_reply_item));
1806faf5f73aSNiels Provos 	if (!item)
1807327165b3SNick Mathewson 		goto done;
1808faf5f73aSNiels Provos 	item->next = NULL;
180949868b61SNick Mathewson 	if (!(item->name = mm_strdup(name))) {
181049868b61SNick Mathewson 		mm_free(item);
1811327165b3SNick Mathewson 		goto done;
1812faf5f73aSNiels Provos 	}
1813faf5f73aSNiels Provos 	item->type = type;
18147c507668SNick Mathewson 	item->dns_question_class = class;
1815faf5f73aSNiels Provos 	item->ttl = ttl;
1816faf5f73aSNiels Provos 	item->is_name = is_name != 0;
1817faf5f73aSNiels Provos 	item->datalen = 0;
1818faf5f73aSNiels Provos 	item->data = NULL;
1819faf5f73aSNiels Provos 	if (data) {
1820faf5f73aSNiels Provos 		if (item->is_name) {
182149868b61SNick Mathewson 			if (!(item->data = mm_strdup(data))) {
182249868b61SNick Mathewson 				mm_free(item->name);
182349868b61SNick Mathewson 				mm_free(item);
1824327165b3SNick Mathewson 				goto done;
1825faf5f73aSNiels Provos 			}
1826f0ff792aSNiels Provos 			item->datalen = (u16)-1;
1827faf5f73aSNiels Provos 		} else {
182849868b61SNick Mathewson 			if (!(item->data = mm_malloc(datalen))) {
182949868b61SNick Mathewson 				mm_free(item->name);
183049868b61SNick Mathewson 				mm_free(item);
1831327165b3SNick Mathewson 				goto done;
1832faf5f73aSNiels Provos 			}
1833faf5f73aSNiels Provos 			item->datalen = datalen;
1834faf5f73aSNiels Provos 			memcpy(item->data, data, datalen);
1835faf5f73aSNiels Provos 		}
1836faf5f73aSNiels Provos 	}
1837faf5f73aSNiels Provos 
1838faf5f73aSNiels Provos 	*itemp = item;
1839faf5f73aSNiels Provos 	++(*countp);
1840327165b3SNick Mathewson 	result = 0;
1841327165b3SNick Mathewson done:
1842327165b3SNick Mathewson 	EVDNS_UNLOCK(req->port);
1843327165b3SNick Mathewson 	return result;
1844faf5f73aSNiels Provos }
1845faf5f73aSNiels Provos 
18467c6df310SNiels Provos /* exported function */
1847faf5f73aSNiels Provos int
evdns_server_request_add_a_reply(struct evdns_server_request * req,const char * name,int n,const void * addrs,int ttl)1848cc2379d2SNick Mathewson evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
1849faf5f73aSNiels Provos {
1850faf5f73aSNiels Provos 	return evdns_server_request_add_reply(
1851faf5f73aSNiels Provos 		  req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
1852faf5f73aSNiels Provos 		  ttl, n*4, 0, addrs);
1853faf5f73aSNiels Provos }
1854faf5f73aSNiels Provos 
18557c6df310SNiels Provos /* exported function */
1856faf5f73aSNiels Provos int
evdns_server_request_add_aaaa_reply(struct evdns_server_request * req,const char * name,int n,const void * addrs,int ttl)1857cc2379d2SNick Mathewson evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
1858faf5f73aSNiels Provos {
1859faf5f73aSNiels Provos 	return evdns_server_request_add_reply(
1860faf5f73aSNiels Provos 		  req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
1861faf5f73aSNiels Provos 		  ttl, n*16, 0, addrs);
1862faf5f73aSNiels Provos }
1863faf5f73aSNiels Provos 
18647c6df310SNiels Provos /* exported function */
1865faf5f73aSNiels Provos 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)1866faf5f73aSNiels Provos evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
1867faf5f73aSNiels Provos {
1868faf5f73aSNiels Provos 	u32 a;
1869faf5f73aSNiels Provos 	char buf[32];
1870cc2379d2SNick Mathewson 	if (in && inaddr_name)
1871cc2379d2SNick Mathewson 		return -1;
1872cc2379d2SNick Mathewson 	else if (!in && !inaddr_name)
1873cc2379d2SNick Mathewson 		return -1;
1874faf5f73aSNiels Provos 	if (in) {
1875faf5f73aSNiels Provos 		a = ntohl(in->s_addr);
1876c6da86ffSNick Mathewson 		evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
1877faf5f73aSNiels Provos 				(int)(u8)((a	)&0xff),
1878faf5f73aSNiels Provos 				(int)(u8)((a>>8 )&0xff),
1879faf5f73aSNiels Provos 				(int)(u8)((a>>16)&0xff),
1880faf5f73aSNiels Provos 				(int)(u8)((a>>24)&0xff));
1881faf5f73aSNiels Provos 		inaddr_name = buf;
1882faf5f73aSNiels Provos 	}
1883faf5f73aSNiels Provos 	return evdns_server_request_add_reply(
1884faf5f73aSNiels Provos 		  req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
1885faf5f73aSNiels Provos 		  ttl, -1, 1, hostname);
1886faf5f73aSNiels Provos }
1887faf5f73aSNiels Provos 
18887c6df310SNiels Provos /* exported function */
1889faf5f73aSNiels Provos int
evdns_server_request_add_cname_reply(struct evdns_server_request * req,const char * name,const char * cname,int ttl)1890faf5f73aSNiels Provos evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
1891faf5f73aSNiels Provos {
1892faf5f73aSNiels Provos 	return evdns_server_request_add_reply(
1893506f3d0cSNiels Provos 		  req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
1894faf5f73aSNiels Provos 		  ttl, -1, 1, cname);
1895faf5f73aSNiels Provos }
1896faf5f73aSNiels Provos 
189712077b4eSNiels Provos /* exported function */
189812077b4eSNiels Provos void
evdns_server_request_set_flags(struct evdns_server_request * exreq,int flags)189912077b4eSNiels Provos evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
190012077b4eSNiels Provos {
190112077b4eSNiels Provos 	struct server_request *req = TO_SERVER_REQUEST(exreq);
190212077b4eSNiels Provos 	req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
190312077b4eSNiels Provos 	req->base.flags |= flags;
190412077b4eSNiels Provos }
1905faf5f73aSNiels Provos 
1906faf5f73aSNiels Provos static int
evdns_server_request_format_response(struct server_request * req,int err)1907faf5f73aSNiels Provos evdns_server_request_format_response(struct server_request *req, int err)
1908faf5f73aSNiels Provos {
1909faf5f73aSNiels Provos 	unsigned char buf[1500];
1910faf5f73aSNiels Provos 	size_t buf_len = sizeof(buf);
1911faf5f73aSNiels Provos 	off_t j = 0, r;
1912cb9da0bfSNick Mathewson 	u16 t_;
1913cb9da0bfSNick Mathewson 	u32 t32_;
1914faf5f73aSNiels Provos 	int i;
1915faf5f73aSNiels Provos 	u16 flags;
1916faf5f73aSNiels Provos 	struct dnslabel_table table;
1917faf5f73aSNiels Provos 
1918faf5f73aSNiels Provos 	if (err < 0 || err > 15) return -1;
1919faf5f73aSNiels Provos 
1920faf5f73aSNiels Provos 	/* Set response bit and error code; copy OPCODE and RD fields from
1921faf5f73aSNiels Provos 	 * question; copy RA and AA if set by caller. */
1922faf5f73aSNiels Provos 	flags = req->base.flags;
1923fcdda24bSNathan French 	flags |= (_QR_MASK | err);
1924faf5f73aSNiels Provos 
1925faf5f73aSNiels Provos 	dnslabel_table_init(&table);
1926faf5f73aSNiels Provos 	APPEND16(req->trans_id);
1927faf5f73aSNiels Provos 	APPEND16(flags);
1928faf5f73aSNiels Provos 	APPEND16(req->base.nquestions);
1929faf5f73aSNiels Provos 	APPEND16(req->n_answer);
1930faf5f73aSNiels Provos 	APPEND16(req->n_authority);
1931faf5f73aSNiels Provos 	APPEND16(req->n_additional);
1932faf5f73aSNiels Provos 
1933faf5f73aSNiels Provos 	/* Add questions. */
1934faf5f73aSNiels Provos 	for (i=0; i < req->base.nquestions; ++i) {
1935faf5f73aSNiels Provos 		const char *s = req->base.questions[i]->name;
1936faf5f73aSNiels Provos 		j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
1937faf5f73aSNiels Provos 		if (j < 0) {
1938faf5f73aSNiels Provos 			dnslabel_clear(&table);
1939faf5f73aSNiels Provos 			return (int) j;
1940faf5f73aSNiels Provos 		}
1941faf5f73aSNiels Provos 		APPEND16(req->base.questions[i]->type);
19427c507668SNick Mathewson 		APPEND16(req->base.questions[i]->dns_question_class);
1943faf5f73aSNiels Provos 	}
1944faf5f73aSNiels Provos 
1945faf5f73aSNiels Provos 	/* Add answer, authority, and additional sections. */
1946faf5f73aSNiels Provos 	for (i=0; i<3; ++i) {
1947faf5f73aSNiels Provos 		struct server_reply_item *item;
1948faf5f73aSNiels Provos 		if (i==0)
1949faf5f73aSNiels Provos 			item = req->answer;
1950faf5f73aSNiels Provos 		else if (i==1)
1951faf5f73aSNiels Provos 			item = req->authority;
1952faf5f73aSNiels Provos 		else
1953faf5f73aSNiels Provos 			item = req->additional;
1954faf5f73aSNiels Provos 		while (item) {
1955faf5f73aSNiels Provos 			r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
1956faf5f73aSNiels Provos 			if (r < 0)
1957faf5f73aSNiels Provos 				goto overflow;
1958faf5f73aSNiels Provos 			j = r;
1959faf5f73aSNiels Provos 
1960faf5f73aSNiels Provos 			APPEND16(item->type);
19617c507668SNick Mathewson 			APPEND16(item->dns_question_class);
1962faf5f73aSNiels Provos 			APPEND32(item->ttl);
1963faf5f73aSNiels Provos 			if (item->is_name) {
1964faf5f73aSNiels Provos 				off_t len_idx = j, name_start;
1965faf5f73aSNiels Provos 				j += 2;
1966faf5f73aSNiels Provos 				name_start = j;
1967faf5f73aSNiels Provos 				r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
1968faf5f73aSNiels Provos 				if (r < 0)
1969faf5f73aSNiels Provos 					goto overflow;
1970faf5f73aSNiels Provos 				j = r;
1971cb9da0bfSNick Mathewson 				t_ = htons( (short) (j-name_start) );
1972cb9da0bfSNick Mathewson 				memcpy(buf+len_idx, &t_, 2);
1973faf5f73aSNiels Provos 			} else {
1974faf5f73aSNiels Provos 				APPEND16(item->datalen);
1975faf5f73aSNiels Provos 				if (j+item->datalen > (off_t)buf_len)
1976faf5f73aSNiels Provos 					goto overflow;
1977faf5f73aSNiels Provos 				memcpy(buf+j, item->data, item->datalen);
1978faf5f73aSNiels Provos 				j += item->datalen;
1979faf5f73aSNiels Provos 			}
1980faf5f73aSNiels Provos 			item = item->next;
1981faf5f73aSNiels Provos 		}
1982faf5f73aSNiels Provos 	}
1983faf5f73aSNiels Provos 
1984faf5f73aSNiels Provos 	if (j > 512) {
1985faf5f73aSNiels Provos overflow:
1986faf5f73aSNiels Provos 		j = 512;
1987342ad355SNick Mathewson 		buf[2] |= 0x02; /* set the truncated bit. */
1988faf5f73aSNiels Provos 	}
1989faf5f73aSNiels Provos 
1990faf5f73aSNiels Provos 	req->response_len = j;
1991faf5f73aSNiels Provos 
199249868b61SNick Mathewson 	if (!(req->response = mm_malloc(req->response_len))) {
1993faf5f73aSNiels Provos 		server_request_free_answers(req);
1994faf5f73aSNiels Provos 		dnslabel_clear(&table);
1995faf5f73aSNiels Provos 		return (-1);
1996faf5f73aSNiels Provos 	}
1997faf5f73aSNiels Provos 	memcpy(req->response, buf, req->response_len);
1998faf5f73aSNiels Provos 	server_request_free_answers(req);
1999faf5f73aSNiels Provos 	dnslabel_clear(&table);
2000faf5f73aSNiels Provos 	return (0);
2001faf5f73aSNiels Provos }
2002faf5f73aSNiels Provos 
20037c6df310SNiels Provos /* exported function */
2004faf5f73aSNiels Provos int
evdns_server_request_respond(struct evdns_server_request * req_,int err)2005946b5841SNick Mathewson evdns_server_request_respond(struct evdns_server_request *req_, int err)
2006faf5f73aSNiels Provos {
2007946b5841SNick Mathewson 	struct server_request *req = TO_SERVER_REQUEST(req_);
2008faf5f73aSNiels Provos 	struct evdns_server_port *port = req->port;
2009327165b3SNick Mathewson 	int r = -1;
2010327165b3SNick Mathewson 
2011327165b3SNick Mathewson 	EVDNS_LOCK(port);
2012faf5f73aSNiels Provos 	if (!req->response) {
2013faf5f73aSNiels Provos 		if ((r = evdns_server_request_format_response(req, err))<0)
2014327165b3SNick Mathewson 			goto done;
2015faf5f73aSNiels Provos 	}
2016faf5f73aSNiels Provos 
2017545a6114SNick Mathewson 	r = sendto(port->socket, req->response, (int)req->response_len, 0,
2018545a6114SNick Mathewson 			   (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
2019faf5f73aSNiels Provos 	if (r<0) {
2020de069b99SNick Mathewson 		int sock_err = evutil_socket_geterror(port->socket);
202181ab45adSNick Mathewson 		if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
2022327165b3SNick Mathewson 			goto done;
2023faf5f73aSNiels Provos 
2024faf5f73aSNiels Provos 		if (port->pending_replies) {
2025faf5f73aSNiels Provos 			req->prev_pending = port->pending_replies->prev_pending;
2026faf5f73aSNiels Provos 			req->next_pending = port->pending_replies;
2027faf5f73aSNiels Provos 			req->prev_pending->next_pending =
2028faf5f73aSNiels Provos 				req->next_pending->prev_pending = req;
2029faf5f73aSNiels Provos 		} else {
2030faf5f73aSNiels Provos 			req->prev_pending = req->next_pending = req;
2031faf5f73aSNiels Provos 			port->pending_replies = req;
2032faf5f73aSNiels Provos 			port->choked = 1;
2033faf5f73aSNiels Provos 
2034faf5f73aSNiels Provos 			(void) event_del(&port->event);
20355fbc7f0aSNick Mathewson 			event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
2036faf5f73aSNiels Provos 
2037faf5f73aSNiels Provos 			if (event_add(&port->event, NULL) < 0) {
2038faf5f73aSNiels Provos 				log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
2039faf5f73aSNiels Provos 			}
2040faf5f73aSNiels Provos 
2041faf5f73aSNiels Provos 		}
2042faf5f73aSNiels Provos 
2043327165b3SNick Mathewson 		r = 1;
2044327165b3SNick Mathewson 		goto done;
2045faf5f73aSNiels Provos 	}
2046327165b3SNick Mathewson 	if (server_request_free(req)) {
2047327165b3SNick Mathewson 		r = 0;
2048327165b3SNick Mathewson 		goto done;
2049327165b3SNick Mathewson 	}
2050faf5f73aSNiels Provos 
2051d06ab856SNiels Provos 	if (port->pending_replies)
2052faf5f73aSNiels Provos 		server_port_flush(port);
2053faf5f73aSNiels Provos 
2054327165b3SNick Mathewson 	r = 0;
2055327165b3SNick Mathewson done:
2056327165b3SNick Mathewson 	EVDNS_UNLOCK(port);
2057327165b3SNick Mathewson 	return r;
2058faf5f73aSNiels Provos }
2059faf5f73aSNiels Provos 
20607c6df310SNiels Provos /* Free all storage held by RRs in req. */
2061faf5f73aSNiels Provos static void
server_request_free_answers(struct server_request * req)2062faf5f73aSNiels Provos server_request_free_answers(struct server_request *req)
2063faf5f73aSNiels Provos {
2064faf5f73aSNiels Provos 	struct server_reply_item *victim, *next, **list;
2065faf5f73aSNiels Provos 	int i;
2066faf5f73aSNiels Provos 	for (i = 0; i < 3; ++i) {
2067faf5f73aSNiels Provos 		if (i==0)
2068faf5f73aSNiels Provos 			list = &req->answer;
2069faf5f73aSNiels Provos 		else if (i==1)
2070faf5f73aSNiels Provos 			list = &req->authority;
2071faf5f73aSNiels Provos 		else
2072faf5f73aSNiels Provos 			list = &req->additional;
2073faf5f73aSNiels Provos 
2074faf5f73aSNiels Provos 		victim = *list;
2075faf5f73aSNiels Provos 		while (victim) {
2076faf5f73aSNiels Provos 			next = victim->next;
207749868b61SNick Mathewson 			mm_free(victim->name);
2078faf5f73aSNiels Provos 			if (victim->data)
207949868b61SNick Mathewson 				mm_free(victim->data);
208049868b61SNick Mathewson 			mm_free(victim);
2081faf5f73aSNiels Provos 			victim = next;
2082faf5f73aSNiels Provos 		}
2083faf5f73aSNiels Provos 		*list = NULL;
2084faf5f73aSNiels Provos 	}
2085faf5f73aSNiels Provos }
2086faf5f73aSNiels Provos 
20877c6df310SNiels Provos /* Free all storage held by req, and remove links to it. */
20887c6df310SNiels Provos /* return true iff we just wound up freeing the server_port. */
2089faf5f73aSNiels Provos static int
server_request_free(struct server_request * req)2090faf5f73aSNiels Provos server_request_free(struct server_request *req)
2091faf5f73aSNiels Provos {
2092327165b3SNick Mathewson 	int i, rc=1, lock=0;
2093faf5f73aSNiels Provos 	if (req->base.questions) {
2094faf5f73aSNiels Provos 		for (i = 0; i < req->base.nquestions; ++i)
209549868b61SNick Mathewson 			mm_free(req->base.questions[i]);
209649868b61SNick Mathewson 		mm_free(req->base.questions);
2097faf5f73aSNiels Provos 	}
2098faf5f73aSNiels Provos 
2099faf5f73aSNiels Provos 	if (req->port) {
2100327165b3SNick Mathewson 		EVDNS_LOCK(req->port);
2101327165b3SNick Mathewson 		lock=1;
2102faf5f73aSNiels Provos 		if (req->port->pending_replies == req) {
210300e91b3cSNick Mathewson 			if (req->next_pending && req->next_pending != req)
2104faf5f73aSNiels Provos 				req->port->pending_replies = req->next_pending;
2105faf5f73aSNiels Provos 			else
2106faf5f73aSNiels Provos 				req->port->pending_replies = NULL;
2107faf5f73aSNiels Provos 		}
2108faf5f73aSNiels Provos 		rc = --req->port->refcnt;
2109faf5f73aSNiels Provos 	}
2110faf5f73aSNiels Provos 
2111faf5f73aSNiels Provos 	if (req->response) {
211249868b61SNick Mathewson 		mm_free(req->response);
2113faf5f73aSNiels Provos 	}
2114faf5f73aSNiels Provos 
2115faf5f73aSNiels Provos 	server_request_free_answers(req);
2116faf5f73aSNiels Provos 
2117faf5f73aSNiels Provos 	if (req->next_pending && req->next_pending != req) {
2118faf5f73aSNiels Provos 		req->next_pending->prev_pending = req->prev_pending;
2119faf5f73aSNiels Provos 		req->prev_pending->next_pending = req->next_pending;
2120faf5f73aSNiels Provos 	}
2121faf5f73aSNiels Provos 
2122faf5f73aSNiels Provos 	if (rc == 0) {
2123327165b3SNick Mathewson 		EVDNS_UNLOCK(req->port); /* ????? nickm */
2124faf5f73aSNiels Provos 		server_port_free(req->port);
212549868b61SNick Mathewson 		mm_free(req);
2126faf5f73aSNiels Provos 		return (1);
2127faf5f73aSNiels Provos 	}
2128327165b3SNick Mathewson 	if (lock)
2129327165b3SNick Mathewson 		EVDNS_UNLOCK(req->port);
213049868b61SNick Mathewson 	mm_free(req);
2131faf5f73aSNiels Provos 	return (0);
2132faf5f73aSNiels Provos }
2133faf5f73aSNiels Provos 
21347c6df310SNiels Provos /* Free all storage held by an evdns_server_port.  Only called when  */
2135faf5f73aSNiels Provos static void
server_port_free(struct evdns_server_port * port)2136faf5f73aSNiels Provos server_port_free(struct evdns_server_port *port)
2137faf5f73aSNiels Provos {
21382e36dbe1SNick Mathewson 	EVUTIL_ASSERT(port);
21392e36dbe1SNick Mathewson 	EVUTIL_ASSERT(!port->refcnt);
21402e36dbe1SNick Mathewson 	EVUTIL_ASSERT(!port->pending_replies);
2141faf5f73aSNiels Provos 	if (port->socket > 0) {
2142899c1dccSSebastian Sjöberg 		evutil_closesocket(port->socket);
2143faf5f73aSNiels Provos 		port->socket = -1;
2144faf5f73aSNiels Provos 	}
2145faf5f73aSNiels Provos 	(void) event_del(&port->event);
2146a19b4a05SNick Mathewson 	event_debug_unassign(&port->event);
2147347952ffSNick Mathewson 	EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
2148c6f4dc98SNick Mathewson 	mm_free(port);
2149faf5f73aSNiels Provos }
2150faf5f73aSNiels Provos 
21517c6df310SNiels Provos /* exported function */
2152faf5f73aSNiels Provos int
evdns_server_request_drop(struct evdns_server_request * req_)2153946b5841SNick Mathewson evdns_server_request_drop(struct evdns_server_request *req_)
2154faf5f73aSNiels Provos {
2155946b5841SNick Mathewson 	struct server_request *req = TO_SERVER_REQUEST(req_);
2156faf5f73aSNiels Provos 	server_request_free(req);
2157faf5f73aSNiels Provos 	return 0;
2158faf5f73aSNiels Provos }
2159faf5f73aSNiels Provos 
21607c6df310SNiels Provos /* exported function */
2161f0d0559cSNiels Provos int
evdns_server_request_get_requesting_addr(struct evdns_server_request * req_,struct sockaddr * sa,int addr_len)2162946b5841SNick Mathewson evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len)
2163f0d0559cSNiels Provos {
2164946b5841SNick Mathewson 	struct server_request *req = TO_SERVER_REQUEST(req_);
2165f0d0559cSNiels Provos 	if (addr_len < (int)req->addrlen)
2166f0d0559cSNiels Provos 		return -1;
2167f0d0559cSNiels Provos 	memcpy(sa, &(req->addr), req->addrlen);
2168f0d0559cSNiels Provos 	return req->addrlen;
2169f0d0559cSNiels Provos }
2170f0d0559cSNiels Provos 
2171b776b2daSNiels Provos #undef APPEND16
2172b776b2daSNiels Provos #undef APPEND32
2173b776b2daSNiels Provos 
21747c6df310SNiels Provos /* this is a libevent callback function which is called when a request */
21757c6df310SNiels Provos /* has timed out. */
2176cca7249eSNiels Provos static void
evdns_request_timeout_callback(evutil_socket_t fd,short events,void * arg)21771120f04fSNick Mathewson evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
217815bb82d6SChristopher Davis 	struct request *const req = (struct request *) arg;
2179213dc2a2SNick Mathewson 	struct evdns_base *base = req->base;
2180265e6779SNick Mathewson 
2181cca7249eSNiels Provos 	(void) fd;
2182cca7249eSNiels Provos 	(void) events;
2183cca7249eSNiels Provos 
21847bcace2dSNick Mathewson 	log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
2185213dc2a2SNick Mathewson 	EVDNS_LOCK(base);
2186cca7249eSNiels Provos 
2187e688a88aSNick Mathewson 	if (req->tx_count >= req->base->global_max_retransmits) {
21888afbdbc4SThomas Bernard 		struct nameserver *ns = req->ns;
21897c6df310SNiels Provos 		/* this request has failed */
2190d873d678SNick Mathewson 		log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
2191d873d678SNick Mathewson 		    arg, req->tx_count);
21922d9619d7SNick Mathewson 		reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
219361262a0fSAzat Khuzhin 
219415bb82d6SChristopher Davis 		request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
219561262a0fSAzat Khuzhin 		nameserver_failed(ns, "request timed out.");
2196cca7249eSNiels Provos 	} else {
21977c6df310SNiels Provos 		/* retransmit it */
2198d873d678SNick Mathewson 		log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
2199d873d678SNick Mathewson 		    arg, req->tx_count);
22000f3c0983SNick Mathewson 		(void) evtimer_del(&req->timeout_event);
220174d0eee8SAzat Khuzhin 		request_swap_ns(req, nameserver_pick(base));
220252bfcab8SNiels Provos 		evdns_request_transmit(req);
220397c750d6SAzat Khuzhin 
220497c750d6SAzat Khuzhin 		req->ns->timedout++;
220597c750d6SAzat Khuzhin 		if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
220697c750d6SAzat Khuzhin 			req->ns->timedout = 0;
220797c750d6SAzat Khuzhin 			nameserver_failed(req->ns, "request timed out.");
220897c750d6SAzat Khuzhin 		}
220961262a0fSAzat Khuzhin 	}
221097c750d6SAzat Khuzhin 
2211213dc2a2SNick Mathewson 	EVDNS_UNLOCK(base);
2212cca7249eSNiels Provos }
2213cca7249eSNiels Provos 
22147c6df310SNiels Provos /* try to send a request to a given server. */
22157c6df310SNiels Provos /* */
22167c6df310SNiels Provos /* return: */
22177c6df310SNiels Provos /*   0 ok */
22187c6df310SNiels Provos /*   1 temporary failure */
22197c6df310SNiels Provos /*   2 other failure */
2220cca7249eSNiels Provos static int
evdns_request_transmit_to(struct request * req,struct nameserver * server)222115bb82d6SChristopher Davis evdns_request_transmit_to(struct request *req, struct nameserver *server) {
2222327165b3SNick Mathewson 	int r;
2223327165b3SNick Mathewson 	ASSERT_LOCKED(req->base);
222467072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
22256b7fa620SAzat Khuzhin 
22266b7fa620SAzat Khuzhin 	if (server->requests_inflight == 1 &&
22276b7fa620SAzat Khuzhin 		req->base->disable_when_inactive &&
22286b7fa620SAzat Khuzhin 		event_add(&server->event, NULL) < 0) {
22296b7fa620SAzat Khuzhin 		return 1;
22306b7fa620SAzat Khuzhin 	}
22316b7fa620SAzat Khuzhin 
22325b7a3706SNick Mathewson 	r = sendto(server->socket, (void*)req->request, req->request_len, 0,
2233f901f986SNick Mathewson 	    (struct sockaddr *)&server->address, server->addrlen);
2234cca7249eSNiels Provos 	if (r < 0) {
2235de069b99SNick Mathewson 		int err = evutil_socket_geterror(server->socket);
223681ab45adSNick Mathewson 		if (EVUTIL_ERR_RW_RETRIABLE(err))
223781ab45adSNick Mathewson 			return 1;
2238de069b99SNick Mathewson 		nameserver_failed(req->ns, evutil_socket_error_to_string(err));
2239cca7249eSNiels Provos 		return 2;
2240cca7249eSNiels Provos 	} else if (r != (int)req->request_len) {
22417c6df310SNiels Provos 		return 1;  /* short write */
2242cca7249eSNiels Provos 	} else {
2243cca7249eSNiels Provos 		return 0;
2244cca7249eSNiels Provos 	}
2245cca7249eSNiels Provos }
2246cca7249eSNiels Provos 
22477c6df310SNiels Provos /* try to send a request, updating the fields of the request */
22487c6df310SNiels Provos /* as needed */
22497c6df310SNiels Provos /* */
22507c6df310SNiels Provos /* return: */
22517c6df310SNiels Provos /*   0 ok */
22527c6df310SNiels Provos /*   1 failed */
2253cca7249eSNiels Provos static int
evdns_request_transmit(struct request * req)225415bb82d6SChristopher Davis evdns_request_transmit(struct request *req) {
2255cca7249eSNiels Provos 	int retcode = 0, r;
2256cca7249eSNiels Provos 
2257327165b3SNick Mathewson 	ASSERT_LOCKED(req->base);
225867072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
22597c6df310SNiels Provos 	/* if we fail to send this packet then this flag marks it */
22607c6df310SNiels Provos 	/* for evdns_transmit */
2261cca7249eSNiels Provos 	req->transmit_me = 1;
226291fe23fcSNick Mathewson 	EVUTIL_ASSERT(req->trans_id != 0xffff);
2263cca7249eSNiels Provos 
22645c710c03SBelobrov Andrey 	if (!req->ns)
22655c710c03SBelobrov Andrey 	{
22665c710c03SBelobrov Andrey 		/* unable to transmit request if no nameservers */
22675c710c03SBelobrov Andrey 		return 1;
22685c710c03SBelobrov Andrey 	}
22695c710c03SBelobrov Andrey 
22705baf8ecfSNiels Provos 	if (req->ns->choked) {
22717c6df310SNiels Provos 		/* don't bother trying to write to a socket */
22727c6df310SNiels Provos 		/* which we have had EAGAIN from */
2273cca7249eSNiels Provos 		return 1;
2274cca7249eSNiels Provos 	}
2275cca7249eSNiels Provos 
227652bfcab8SNiels Provos 	r = evdns_request_transmit_to(req, req->ns);
2277cca7249eSNiels Provos 	switch (r) {
2278cca7249eSNiels Provos 	case 1:
22797c6df310SNiels Provos 		/* temp failure */
22805baf8ecfSNiels Provos 		req->ns->choked = 1;
2281cca7249eSNiels Provos 		nameserver_write_waiting(req->ns, 1);
2282cca7249eSNiels Provos 		return 1;
2283cca7249eSNiels Provos 	case 2:
228440da44bdSAzat Khuzhin 		/* failed to transmit the request entirely. we can fallthrough since
228540da44bdSAzat Khuzhin 		 * we'll set a timeout, which will time out, and make us retransmit the
228640da44bdSAzat Khuzhin 		 * request anyway. */
2287cca7249eSNiels Provos 		retcode = 1;
228840da44bdSAzat Khuzhin 		EVUTIL_FALLTHROUGH;
2289cca7249eSNiels Provos 	default:
22907c6df310SNiels Provos 		/* all ok */
2291fe1dfe0fSNiels Provos 		log(EVDNS_LOG_DEBUG,
2292d873d678SNick Mathewson 		    "Setting timeout for request %p, sent to nameserver %p", req, req->ns);
2293e688a88aSNick Mathewson 		if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
2294fe1dfe0fSNiels Provos 			log(EVDNS_LOG_WARN,
22957bcace2dSNick Mathewson 		      "Error from libevent when adding timer for request %p",
22967bcace2dSNick Mathewson 			    req);
22977c6df310SNiels Provos 			/* ???? Do more? */
2298cca7249eSNiels Provos 		}
2299cca7249eSNiels Provos 		req->tx_count++;
2300cca7249eSNiels Provos 		req->transmit_me = 0;
2301cca7249eSNiels Provos 		return retcode;
2302cca7249eSNiels Provos 	}
2303cca7249eSNiels Provos }
2304cca7249eSNiels Provos 
2305cca7249eSNiels Provos static void
nameserver_probe_callback(int result,char type,int count,int ttl,void * addresses,void * arg)2306cca7249eSNiels Provos nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
2307cca7249eSNiels Provos 	struct nameserver *const ns = (struct nameserver *) arg;
2308cca7249eSNiels Provos 	(void) type;
2309cca7249eSNiels Provos 	(void) count;
2310cca7249eSNiels Provos 	(void) ttl;
2311cca7249eSNiels Provos 	(void) addresses;
2312327165b3SNick Mathewson 
2313684c022aSNick Mathewson 	if (result == DNS_ERR_CANCEL) {
2314684c022aSNick Mathewson 		/* We canceled this request because the nameserver came up
2315684c022aSNick Mathewson 		 * for some other reason.  Do not change our opinion about
2316684c022aSNick Mathewson 		 * the nameserver. */
231794d23360SGreg Hazel 		return;
231894d23360SGreg Hazel 	}
231994d23360SGreg Hazel 
2320cca7249eSNiels Provos 	EVDNS_LOCK(ns->base);
2321684c022aSNick Mathewson 	ns->probe_request = NULL;
232246b80608SGreg Hazel 	if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
23237c6df310SNiels Provos 		/* this is a good reply */
2324cca7249eSNiels Provos 		nameserver_up(ns);
2325684c022aSNick Mathewson 	} else {
2326684c022aSNick Mathewson 		nameserver_probe_failed(ns);
2327684c022aSNick Mathewson 	}
2328327165b3SNick Mathewson 	EVDNS_UNLOCK(ns->base);
2329cca7249eSNiels Provos }
2330cca7249eSNiels Provos 
2331cca7249eSNiels Provos static void
nameserver_send_probe(struct nameserver * const ns)2332cca7249eSNiels Provos nameserver_send_probe(struct nameserver *const ns) {
233315bb82d6SChristopher Davis 	struct evdns_request *handle;
233415bb82d6SChristopher Davis 	struct request *req;
2335b1c79500SNick Mathewson 	char addrbuf[128];
23367c6df310SNiels Provos 	/* here we need to send a probe to a given nameserver */
23377c6df310SNiels Provos 	/* in the hope that it is up now. */
2338cca7249eSNiels Provos 
2339327165b3SNick Mathewson 	ASSERT_LOCKED(ns->base);
2340135591aeSNick Mathewson 	log(EVDNS_LOG_DEBUG, "Sending probe to %s",
23418ac3c4c2SNick Mathewson 	    evutil_format_sockaddr_port_(
2342b1c79500SNick Mathewson 		    (struct sockaddr *)&ns->address,
2343b1c79500SNick Mathewson 		    addrbuf, sizeof(addrbuf)));
234415bb82d6SChristopher Davis 	handle = mm_calloc(1, sizeof(*handle));
234515bb82d6SChristopher Davis 	if (!handle) return;
234615bb82d6SChristopher Davis 	req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
234773e85dd0SGeorge Danchev 	if (!req) {
234873e85dd0SGeorge Danchev 		mm_free(handle);
234973e85dd0SGeorge Danchev 		return;
235073e85dd0SGeorge Danchev 	}
235115bb82d6SChristopher Davis 	ns->probe_request = handle;
23527c6df310SNiels Provos 	/* we force this into the inflight queue no matter what */
2353e688a88aSNick Mathewson 	request_trans_id_set(req, transaction_id_pick(ns->base));
2354cca7249eSNiels Provos 	req->ns = ns;
2355cca7249eSNiels Provos 	request_submit(req);
2356cca7249eSNiels Provos }
2357cca7249eSNiels Provos 
23587c6df310SNiels Provos /* returns: */
23597c6df310SNiels Provos /*   0 didn't try to transmit anything */
23607c6df310SNiels Provos /*   1 tried to transmit something */
2361cca7249eSNiels Provos static int
evdns_transmit(struct evdns_base * base)2362e688a88aSNick Mathewson evdns_transmit(struct evdns_base *base) {
2363cca7249eSNiels Provos 	char did_try_to_transmit = 0;
236449868b61SNick Mathewson 	int i;
2365cca7249eSNiels Provos 
2366327165b3SNick Mathewson 	ASSERT_LOCKED(base);
236749868b61SNick Mathewson 	for (i = 0; i < base->n_req_heads; ++i) {
236849868b61SNick Mathewson 		if (base->req_heads[i]) {
236915bb82d6SChristopher Davis 			struct request *const started_at = base->req_heads[i], *req = started_at;
23707c6df310SNiels Provos 			/* first transmit all the requests which are currently waiting */
2371cca7249eSNiels Provos 			do {
2372cca7249eSNiels Provos 				if (req->transmit_me) {
2373cca7249eSNiels Provos 					did_try_to_transmit = 1;
237452bfcab8SNiels Provos 					evdns_request_transmit(req);
2375cca7249eSNiels Provos 				}
2376cca7249eSNiels Provos 
2377cca7249eSNiels Provos 				req = req->next;
2378cca7249eSNiels Provos 			} while (req != started_at);
2379cca7249eSNiels Provos 		}
238049868b61SNick Mathewson 	}
2381cca7249eSNiels Provos 
2382cca7249eSNiels Provos 	return did_try_to_transmit;
2383cca7249eSNiels Provos }
2384cca7249eSNiels Provos 
23857c6df310SNiels Provos /* exported function */
2386cca7249eSNiels Provos int
evdns_base_count_nameservers(struct evdns_base * base)2387e688a88aSNick Mathewson evdns_base_count_nameservers(struct evdns_base *base)
2388cca7249eSNiels Provos {
2389327165b3SNick Mathewson 	const struct nameserver *server;
2390cca7249eSNiels Provos 	int n = 0;
2391327165b3SNick Mathewson 
2392327165b3SNick Mathewson 	EVDNS_LOCK(base);
2393327165b3SNick Mathewson 	server = base->server_head;
2394cca7249eSNiels Provos 	if (!server)
2395327165b3SNick Mathewson 		goto done;
2396cca7249eSNiels Provos 	do {
2397cca7249eSNiels Provos 		++n;
2398cca7249eSNiels Provos 		server = server->next;
2399e688a88aSNick Mathewson 	} while (server != base->server_head);
2400327165b3SNick Mathewson done:
2401327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
2402cca7249eSNiels Provos 	return n;
2403cca7249eSNiels Provos }
2404cca7249eSNiels Provos 
2405e688a88aSNick Mathewson int
evdns_count_nameservers(void)2406e688a88aSNick Mathewson evdns_count_nameservers(void)
2407e688a88aSNick Mathewson {
2408e688a88aSNick Mathewson 	return evdns_base_count_nameservers(current_base);
2409e688a88aSNick Mathewson }
2410e688a88aSNick Mathewson 
24117c6df310SNiels Provos /* exported function */
2412cca7249eSNiels Provos int
evdns_base_clear_nameservers_and_suspend(struct evdns_base * base)2413e688a88aSNick Mathewson evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
2414cca7249eSNiels Provos {
2415327165b3SNick Mathewson 	struct nameserver *server, *started_at;
241649868b61SNick Mathewson 	int i;
2417cca7249eSNiels Provos 
2418327165b3SNick Mathewson 	EVDNS_LOCK(base);
2419327165b3SNick Mathewson 	server = base->server_head;
2420327165b3SNick Mathewson 	started_at = base->server_head;
2421327165b3SNick Mathewson 	if (!server) {
2422327165b3SNick Mathewson 		EVDNS_UNLOCK(base);
2423cca7249eSNiels Provos 		return 0;
2424327165b3SNick Mathewson 	}
2425cca7249eSNiels Provos 	while (1) {
2426cca7249eSNiels Provos 		struct nameserver *next = server->next;
2427cca7249eSNiels Provos 		(void) event_del(&server->event);
24283ef1f504SNiels Provos 		if (evtimer_initialized(&server->timeout_event))
2429cca7249eSNiels Provos 			(void) evtimer_del(&server->timeout_event);
243094d23360SGreg Hazel 		if (server->probe_request) {
243194d23360SGreg Hazel 			evdns_cancel_request(server->base, server->probe_request);
243294d23360SGreg Hazel 			server->probe_request = NULL;
243394d23360SGreg Hazel 		}
2434cca7249eSNiels Provos 		if (server->socket >= 0)
2435899c1dccSSebastian Sjöberg 			evutil_closesocket(server->socket);
243649868b61SNick Mathewson 		mm_free(server);
2437cca7249eSNiels Provos 		if (next == started_at)
2438cca7249eSNiels Provos 			break;
2439cca7249eSNiels Provos 		server = next;
2440cca7249eSNiels Provos 	}
2441e688a88aSNick Mathewson 	base->server_head = NULL;
2442e688a88aSNick Mathewson 	base->global_good_nameservers = 0;
2443cca7249eSNiels Provos 
244449868b61SNick Mathewson 	for (i = 0; i < base->n_req_heads; ++i) {
244515bb82d6SChristopher Davis 		struct request *req, *req_started_at;
244649868b61SNick Mathewson 		req = req_started_at = base->req_heads[i];
2447cca7249eSNiels Provos 		while (req) {
244815bb82d6SChristopher Davis 			struct request *next = req->next;
2449cca7249eSNiels Provos 			req->tx_count = req->reissue_count = 0;
2450cca7249eSNiels Provos 			req->ns = NULL;
24517c6df310SNiels Provos 			/* ???? What to do about searches? */
2452cca7249eSNiels Provos 			(void) evtimer_del(&req->timeout_event);
2453cca7249eSNiels Provos 			req->trans_id = 0;
2454cca7249eSNiels Provos 			req->transmit_me = 0;
2455cca7249eSNiels Provos 
2456e688a88aSNick Mathewson 			base->global_requests_waiting++;
2457e688a88aSNick Mathewson 			evdns_request_insert(req, &base->req_waiting_head);
2458cca7249eSNiels Provos 			/* We want to insert these suspended elements at the front of
2459cca7249eSNiels Provos 			 * the waiting queue, since they were pending before any of
2460cca7249eSNiels Provos 			 * the waiting entries were added.  This is a circular list,
2461cca7249eSNiels Provos 			 * so we can just shift the start back by one.*/
2462e688a88aSNick Mathewson 			base->req_waiting_head = base->req_waiting_head->prev;
2463cca7249eSNiels Provos 
2464cca7249eSNiels Provos 			if (next == req_started_at)
2465cca7249eSNiels Provos 				break;
2466cca7249eSNiels Provos 			req = next;
2467cca7249eSNiels Provos 		}
246849868b61SNick Mathewson 		base->req_heads[i] = NULL;
246949868b61SNick Mathewson 	}
247049868b61SNick Mathewson 
2471e688a88aSNick Mathewson 	base->global_requests_inflight = 0;
2472cca7249eSNiels Provos 
2473327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
2474cca7249eSNiels Provos 	return 0;
2475cca7249eSNiels Provos }
2476cca7249eSNiels Provos 
2477e688a88aSNick Mathewson int
evdns_clear_nameservers_and_suspend(void)2478e688a88aSNick Mathewson evdns_clear_nameservers_and_suspend(void)
2479e688a88aSNick Mathewson {
2480e688a88aSNick Mathewson 	return evdns_base_clear_nameservers_and_suspend(current_base);
2481e688a88aSNick Mathewson }
2482e688a88aSNick Mathewson 
2483cca7249eSNiels Provos 
24847c6df310SNiels Provos /* exported function */
2485cca7249eSNiels Provos int
evdns_base_resume(struct evdns_base * base)2486e688a88aSNick Mathewson evdns_base_resume(struct evdns_base *base)
2487cca7249eSNiels Provos {
2488327165b3SNick Mathewson 	EVDNS_LOCK(base);
2489e688a88aSNick Mathewson 	evdns_requests_pump_waiting_queue(base);
2490327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
249114971a83SAzat Khuzhin 
2492cca7249eSNiels Provos 	return 0;
2493cca7249eSNiels Provos }
2494cca7249eSNiels Provos 
2495e688a88aSNick Mathewson int
evdns_resume(void)2496e688a88aSNick Mathewson evdns_resume(void)
2497e688a88aSNick Mathewson {
2498e688a88aSNick Mathewson 	return evdns_base_resume(current_base);
2499e688a88aSNick Mathewson }
2500e688a88aSNick Mathewson 
2501faf5f73aSNiels Provos static int
evdns_nameserver_add_impl_(struct evdns_base * base,const struct sockaddr * address,int addrlen)2502cb9da0bfSNick Mathewson evdns_nameserver_add_impl_(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
25037c6df310SNiels Provos 	/* first check to see if we already have this nameserver */
2504cca7249eSNiels Provos 
2505e688a88aSNick Mathewson 	const struct nameserver *server = base->server_head, *const started_at = base->server_head;
2506cca7249eSNiels Provos 	struct nameserver *ns;
2507cca7249eSNiels Provos 	int err = 0;
2508b1c79500SNick Mathewson 	char addrbuf[128];
2509135591aeSNick Mathewson 
2510327165b3SNick Mathewson 	ASSERT_LOCKED(base);
2511cca7249eSNiels Provos 	if (server) {
2512cca7249eSNiels Provos 		do {
2513621aafd2SNick Mathewson 			if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3;
2514cca7249eSNiels Provos 			server = server->next;
2515cca7249eSNiels Provos 		} while (server != started_at);
2516cca7249eSNiels Provos 	}
2517c6f4dc98SNick Mathewson 	if (addrlen > (int)sizeof(ns->address)) {
2518c6f4dc98SNick Mathewson 		log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
2519c6f4dc98SNick Mathewson 		return 2;
2520c6f4dc98SNick Mathewson 	}
2521135591aeSNick Mathewson 
252249868b61SNick Mathewson 	ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
2523cca7249eSNiels Provos 	if (!ns) return -1;
2524cca7249eSNiels Provos 
2525cca7249eSNiels Provos 	memset(ns, 0, sizeof(struct nameserver));
2526e688a88aSNick Mathewson 	ns->base = base;
2527cca7249eSNiels Provos 
25287289d7f8SNick Mathewson 	evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
25297289d7f8SNick Mathewson 
25308ac3c4c2SNick Mathewson 	ns->socket = evutil_socket_(address->sa_family,
2531713e570aSNick Mathewson 	    SOCK_DGRAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
2532cca7249eSNiels Provos 	if (ns->socket < 0) { err = 1; goto out1; }
253377c80b8dSNick Mathewson 
25348d4aaf90SNick Mathewson 	if (base->global_outgoing_addrlen &&
25358ac3c4c2SNick Mathewson 	    !evutil_sockaddr_is_loopback_(address)) {
253677c80b8dSNick Mathewson 		if (bind(ns->socket,
253777c80b8dSNick Mathewson 			(struct sockaddr*)&base->global_outgoing_address,
253877c80b8dSNick Mathewson 			base->global_outgoing_addrlen) < 0) {
253977c80b8dSNick Mathewson 			log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
254077c80b8dSNick Mathewson 			err = 2;
254177c80b8dSNick Mathewson 			goto out2;
254277c80b8dSNick Mathewson 		}
254377c80b8dSNick Mathewson 	}
254477c80b8dSNick Mathewson 
2545546a366cSAzat Khuzhin 	if (base->so_rcvbuf) {
2546546a366cSAzat Khuzhin 		if (setsockopt(ns->socket, SOL_SOCKET, SO_RCVBUF,
2547546a366cSAzat Khuzhin 		    (void *)&base->so_rcvbuf, sizeof(base->so_rcvbuf))) {
2548546a366cSAzat Khuzhin 			log(EVDNS_LOG_WARN, "Couldn't set SO_RCVBUF to %i", base->so_rcvbuf);
2549546a366cSAzat Khuzhin 			err = -SO_RCVBUF;
2550546a366cSAzat Khuzhin 			goto out2;
2551546a366cSAzat Khuzhin 		}
2552546a366cSAzat Khuzhin 	}
2553546a366cSAzat Khuzhin 	if (base->so_sndbuf) {
2554546a366cSAzat Khuzhin 		if (setsockopt(ns->socket, SOL_SOCKET, SO_SNDBUF,
2555546a366cSAzat Khuzhin 		    (void *)&base->so_sndbuf, sizeof(base->so_sndbuf))) {
2556546a366cSAzat Khuzhin 			log(EVDNS_LOG_WARN, "Couldn't set SO_SNDBUF to %i", base->so_sndbuf);
2557546a366cSAzat Khuzhin 			err = -SO_SNDBUF;
2558546a366cSAzat Khuzhin 			goto out2;
2559546a366cSAzat Khuzhin 		}
2560546a366cSAzat Khuzhin 	}
2561546a366cSAzat Khuzhin 
2562135591aeSNick Mathewson 	memcpy(&ns->address, address, addrlen);
2563f901f986SNick Mathewson 	ns->addrlen = addrlen;
2564cca7249eSNiels Provos 	ns->state = 1;
25656b7fa620SAzat Khuzhin 	event_assign(&ns->event, ns->base->event_base, ns->socket,
25666b7fa620SAzat Khuzhin 				 EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
25676b7fa620SAzat Khuzhin 	if (!base->disable_when_inactive && event_add(&ns->event, NULL) < 0) {
2568cca7249eSNiels Provos 		err = 2;
2569cca7249eSNiels Provos 		goto out2;
2570cca7249eSNiels Provos 	}
2571cca7249eSNiels Provos 
2572d873d678SNick Mathewson 	log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
25734b70286eSNick Mathewson 	    evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), ns);
2574cca7249eSNiels Provos 
25757c6df310SNiels Provos 	/* insert this nameserver into the list of them */
2576e688a88aSNick Mathewson 	if (!base->server_head) {
2577cca7249eSNiels Provos 		ns->next = ns->prev = ns;
2578e688a88aSNick Mathewson 		base->server_head = ns;
2579cca7249eSNiels Provos 	} else {
2580e688a88aSNick Mathewson 		ns->next = base->server_head->next;
2581e688a88aSNick Mathewson 		ns->prev = base->server_head;
2582e688a88aSNick Mathewson 		base->server_head->next = ns;
2583d6094b16SNick Mathewson 		ns->next->prev = ns;
2584cca7249eSNiels Provos 	}
2585cca7249eSNiels Provos 
2586e688a88aSNick Mathewson 	base->global_good_nameservers++;
2587cca7249eSNiels Provos 
2588cca7249eSNiels Provos 	return 0;
2589cca7249eSNiels Provos 
2590cca7249eSNiels Provos out2:
2591899c1dccSSebastian Sjöberg 	evutil_closesocket(ns->socket);
2592cca7249eSNiels Provos out1:
2593a19b4a05SNick Mathewson 	event_debug_unassign(&ns->event);
259449868b61SNick Mathewson 	mm_free(ns);
2595b1c79500SNick Mathewson 	log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
25968ac3c4c2SNick Mathewson 	    evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), err);
2597cca7249eSNiels Provos 	return err;
2598cca7249eSNiels Provos }
2599cca7249eSNiels Provos 
26007c6df310SNiels Provos /* exported function */
2601cca7249eSNiels Provos int
evdns_base_nameserver_add(struct evdns_base * base,unsigned long int address)2602b1c79500SNick Mathewson evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
2603135591aeSNick Mathewson {
2604135591aeSNick Mathewson 	struct sockaddr_in sin;
2605327165b3SNick Mathewson 	int res;
2606a1a0e675SNick Mathewson 	memset(&sin, 0, sizeof(sin));
2607135591aeSNick Mathewson 	sin.sin_addr.s_addr = address;
2608135591aeSNick Mathewson 	sin.sin_port = htons(53);
2609135591aeSNick Mathewson 	sin.sin_family = AF_INET;
2610327165b3SNick Mathewson 	EVDNS_LOCK(base);
2611cb9da0bfSNick Mathewson 	res = evdns_nameserver_add_impl_(base, (struct sockaddr*)&sin, sizeof(sin));
2612327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
2613327165b3SNick Mathewson 	return res;
2614e688a88aSNick Mathewson }
2615e688a88aSNick Mathewson 
2616e688a88aSNick Mathewson int
evdns_nameserver_add(unsigned long int address)2617faf5f73aSNiels Provos evdns_nameserver_add(unsigned long int address) {
2618e688a88aSNick Mathewson 	if (!current_base)
2619e688a88aSNick Mathewson 		current_base = evdns_base_new(NULL, 0);
2620e688a88aSNick Mathewson 	return evdns_base_nameserver_add(current_base, address);
2621faf5f73aSNiels Provos }
2622faf5f73aSNiels Provos 
262372dd6667SNick Mathewson static void
sockaddr_setport(struct sockaddr * sa,ev_uint16_t port)262472dd6667SNick Mathewson sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
262572dd6667SNick Mathewson {
262672dd6667SNick Mathewson 	if (sa->sa_family == AF_INET) {
262772dd6667SNick Mathewson 		((struct sockaddr_in *)sa)->sin_port = htons(port);
262872dd6667SNick Mathewson 	} else if (sa->sa_family == AF_INET6) {
262972dd6667SNick Mathewson 		((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
263072dd6667SNick Mathewson 	}
263172dd6667SNick Mathewson }
263272dd6667SNick Mathewson 
263372dd6667SNick Mathewson static ev_uint16_t
sockaddr_getport(struct sockaddr * sa)263472dd6667SNick Mathewson sockaddr_getport(struct sockaddr *sa)
263572dd6667SNick Mathewson {
263672dd6667SNick Mathewson 	if (sa->sa_family == AF_INET) {
263772dd6667SNick Mathewson 		return ntohs(((struct sockaddr_in *)sa)->sin_port);
263872dd6667SNick Mathewson 	} else if (sa->sa_family == AF_INET6) {
263972dd6667SNick Mathewson 		return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
264072dd6667SNick Mathewson 	} else {
264172dd6667SNick Mathewson 		return 0;
264272dd6667SNick Mathewson 	}
264372dd6667SNick Mathewson }
264472dd6667SNick Mathewson 
26457c6df310SNiels Provos /* exported function */
2646faf5f73aSNiels Provos int
evdns_base_nameserver_ip_add(struct evdns_base * base,const char * ip_as_string)2647e688a88aSNick Mathewson evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
2648135591aeSNick Mathewson 	struct sockaddr_storage ss;
2649135591aeSNick Mathewson 	struct sockaddr *sa;
2650acaf65c3SNick Mathewson 	int len = sizeof(ss);
2651327165b3SNick Mathewson 	int res;
2652135591aeSNick Mathewson 	if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
2653acaf65c3SNick Mathewson 		&len)) {
2654135591aeSNick Mathewson 		log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
2655135591aeSNick Mathewson 			ip_as_string);
2656868f10e7SNiels Provos 		return 4;
2657faf5f73aSNiels Provos 	}
2658135591aeSNick Mathewson 	sa = (struct sockaddr *) &ss;
265972dd6667SNick Mathewson 	if (sockaddr_getport(sa) == 0)
266072dd6667SNick Mathewson 		sockaddr_setport(sa, 53);
2661135591aeSNick Mathewson 
2662327165b3SNick Mathewson 	EVDNS_LOCK(base);
2663cb9da0bfSNick Mathewson 	res = evdns_nameserver_add_impl_(base, sa, len);
2664327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
2665327165b3SNick Mathewson 	return res;
2666e688a88aSNick Mathewson }
2667e688a88aSNick Mathewson 
2668e688a88aSNick Mathewson int
evdns_nameserver_ip_add(const char * ip_as_string)2669e688a88aSNick Mathewson evdns_nameserver_ip_add(const char *ip_as_string) {
2670e688a88aSNick Mathewson 	if (!current_base)
2671e688a88aSNick Mathewson 		current_base = evdns_base_new(NULL, 0);
2672e688a88aSNick Mathewson 	return evdns_base_nameserver_ip_add(current_base, ip_as_string);
2673cca7249eSNiels Provos }
2674cca7249eSNiels Provos 
267519521436SNick Mathewson int
evdns_base_nameserver_sockaddr_add(struct evdns_base * base,const struct sockaddr * sa,ev_socklen_t len,unsigned flags)267619521436SNick Mathewson evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
267719521436SNick Mathewson     const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
267819521436SNick Mathewson {
267919521436SNick Mathewson 	int res;
268019521436SNick Mathewson 	EVUTIL_ASSERT(base);
268119521436SNick Mathewson 	EVDNS_LOCK(base);
2682cb9da0bfSNick Mathewson 	res = evdns_nameserver_add_impl_(base, sa, len);
268319521436SNick Mathewson 	EVDNS_UNLOCK(base);
268419521436SNick Mathewson 	return res;
268519521436SNick Mathewson }
268619521436SNick Mathewson 
2687537177d3SNick Mathewson int
evdns_base_get_nameserver_addr(struct evdns_base * base,int idx,struct sockaddr * sa,ev_socklen_t len)2688537177d3SNick Mathewson evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
2689537177d3SNick Mathewson     struct sockaddr *sa, ev_socklen_t len)
2690537177d3SNick Mathewson {
2691537177d3SNick Mathewson 	int result = -1;
2692537177d3SNick Mathewson 	int i;
2693537177d3SNick Mathewson 	struct nameserver *server;
2694537177d3SNick Mathewson 	EVDNS_LOCK(base);
2695537177d3SNick Mathewson 	server = base->server_head;
2696537177d3SNick Mathewson 	for (i = 0; i < idx && server; ++i, server = server->next) {
2697537177d3SNick Mathewson 		if (server->next == base->server_head)
2698537177d3SNick Mathewson 			goto done;
2699537177d3SNick Mathewson 	}
2700537177d3SNick Mathewson 	if (! server)
2701537177d3SNick Mathewson 		goto done;
2702537177d3SNick Mathewson 
2703537177d3SNick Mathewson 	if (server->addrlen > len) {
2704537177d3SNick Mathewson 		result = (int) server->addrlen;
2705537177d3SNick Mathewson 		goto done;
2706537177d3SNick Mathewson 	}
2707537177d3SNick Mathewson 
2708537177d3SNick Mathewson 	memcpy(sa, &server->address, server->addrlen);
2709537177d3SNick Mathewson 	result = (int) server->addrlen;
2710537177d3SNick Mathewson done:
2711537177d3SNick Mathewson 	EVDNS_UNLOCK(base);
2712537177d3SNick Mathewson 	return result;
2713537177d3SNick Mathewson }
2714537177d3SNick Mathewson 
27151eeb96aaSNiels Provos /* remove from the queue */
27161eeb96aaSNiels Provos static void
evdns_request_remove(struct request * req,struct request ** head)271715bb82d6SChristopher Davis evdns_request_remove(struct request *req, struct request **head)
27181eeb96aaSNiels Provos {
2719327165b3SNick Mathewson 	ASSERT_LOCKED(req->base);
272067072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
2721213dc2a2SNick Mathewson 
2722213dc2a2SNick Mathewson #if 0
2723213dc2a2SNick Mathewson 	{
272415bb82d6SChristopher Davis 		struct request *ptr;
2725213dc2a2SNick Mathewson 		int found = 0;
27262e36dbe1SNick Mathewson 		EVUTIL_ASSERT(*head != NULL);
2727213dc2a2SNick Mathewson 
2728213dc2a2SNick Mathewson 		ptr = *head;
2729213dc2a2SNick Mathewson 		do {
2730213dc2a2SNick Mathewson 			if (ptr == req) {
2731213dc2a2SNick Mathewson 				found = 1;
2732213dc2a2SNick Mathewson 				break;
2733213dc2a2SNick Mathewson 			}
2734213dc2a2SNick Mathewson 			ptr = ptr->next;
2735213dc2a2SNick Mathewson 		} while (ptr != *head);
27362e36dbe1SNick Mathewson 		EVUTIL_ASSERT(found);
2737213dc2a2SNick Mathewson 
27382e36dbe1SNick Mathewson 		EVUTIL_ASSERT(req->next);
2739213dc2a2SNick Mathewson 	}
2740213dc2a2SNick Mathewson #endif
2741213dc2a2SNick Mathewson 
27421eeb96aaSNiels Provos 	if (req->next == req) {
27431eeb96aaSNiels Provos 		/* only item in the list */
27441eeb96aaSNiels Provos 		*head = NULL;
27451eeb96aaSNiels Provos 	} else {
27461eeb96aaSNiels Provos 		req->next->prev = req->prev;
27471eeb96aaSNiels Provos 		req->prev->next = req->next;
27481eeb96aaSNiels Provos 		if (*head == req) *head = req->next;
27491eeb96aaSNiels Provos 	}
2750213dc2a2SNick Mathewson 	req->next = req->prev = NULL;
27511eeb96aaSNiels Provos }
27521eeb96aaSNiels Provos 
27537c6df310SNiels Provos /* insert into the tail of the queue */
2754cca7249eSNiels Provos static void
evdns_request_insert(struct request * req,struct request ** head)275515bb82d6SChristopher Davis evdns_request_insert(struct request *req, struct request **head) {
2756327165b3SNick Mathewson 	ASSERT_LOCKED(req->base);
275767072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
2758cca7249eSNiels Provos 	if (!*head) {
2759cca7249eSNiels Provos 		*head = req;
2760cca7249eSNiels Provos 		req->next = req->prev = req;
2761cca7249eSNiels Provos 		return;
2762cca7249eSNiels Provos 	}
2763cca7249eSNiels Provos 
2764cca7249eSNiels Provos 	req->prev = (*head)->prev;
2765cca7249eSNiels Provos 	req->prev->next = req;
2766cca7249eSNiels Provos 	req->next = *head;
2767cca7249eSNiels Provos 	(*head)->prev = req;
2768cca7249eSNiels Provos }
2769cca7249eSNiels Provos 
2770cca7249eSNiels Provos static int
string_num_dots(const char * s)2771cca7249eSNiels Provos string_num_dots(const char *s) {
2772cca7249eSNiels Provos 	int count = 0;
2773cca7249eSNiels Provos 	while ((s = strchr(s, '.'))) {
2774cca7249eSNiels Provos 		s++;
2775cca7249eSNiels Provos 		count++;
2776cca7249eSNiels Provos 	}
2777cca7249eSNiels Provos 	return count;
2778cca7249eSNiels Provos }
2779cca7249eSNiels Provos 
278015bb82d6SChristopher Davis 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)278115bb82d6SChristopher Davis request_new(struct evdns_base *base, struct evdns_request *handle, int type,
278215bb82d6SChristopher Davis 	    const char *name, int flags, evdns_callback_type callback,
278315bb82d6SChristopher Davis 	    void *user_ptr) {
2784327165b3SNick Mathewson 
278507c3fb50SNiels Provos 	const char issuing_now =
2786e688a88aSNick Mathewson 	    (base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
2787cca7249eSNiels Provos 
2788e3e696c8SNick Mathewson 	const size_t name_len = strlen(name);
2789e3e696c8SNick Mathewson 	const size_t request_max_len = evdns_request_len(name_len);
2790e688a88aSNick Mathewson 	const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
27917c6df310SNiels Provos 	/* the request data is alloced in a single block with the header */
279215bb82d6SChristopher Davis 	struct request *const req =
279315bb82d6SChristopher Davis 	    mm_malloc(sizeof(struct request) + request_max_len);
2794cca7249eSNiels Provos 	int rlen;
2795dd731685SNick Mathewson 	char namebuf[256];
2796cca7249eSNiels Provos 	(void) flags;
2797cca7249eSNiels Provos 
2798327165b3SNick Mathewson 	ASSERT_LOCKED(base);
2799327165b3SNick Mathewson 
2800cca7249eSNiels Provos 	if (!req) return NULL;
2801f04b90e5SNick Mathewson 
2802f04b90e5SNick Mathewson 	if (name_len >= sizeof(namebuf)) {
28030546ce11SJardel Weyrich 		mm_free(req);
2804f04b90e5SNick Mathewson 		return NULL;
2805f04b90e5SNick Mathewson 	}
2806f04b90e5SNick Mathewson 
280715bb82d6SChristopher Davis 	memset(req, 0, sizeof(struct request));
2808e688a88aSNick Mathewson 	req->base = base;
2809cca7249eSNiels Provos 
28107289d7f8SNick Mathewson 	evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
28117289d7f8SNick Mathewson 
2812dd731685SNick Mathewson 	if (base->global_randomize_case) {
2813dd731685SNick Mathewson 		unsigned i;
2814dd731685SNick Mathewson 		char randbits[(sizeof(namebuf)+7)/8];
2815dd731685SNick Mathewson 		strlcpy(namebuf, name, sizeof(namebuf));
2816d4de062eSNick Mathewson 		evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
2817dd731685SNick Mathewson 		for (i = 0; i < name_len; ++i) {
28188ac3c4c2SNick Mathewson 			if (EVUTIL_ISALPHA_(namebuf[i])) {
2819dd731685SNick Mathewson 				if ((randbits[i >> 3] & (1<<(i & 7))))
2820dd731685SNick Mathewson 					namebuf[i] |= 0x20;
2821dd731685SNick Mathewson 				else
2822dd731685SNick Mathewson 					namebuf[i] &= ~0x20;
2823dd731685SNick Mathewson 			}
2824dd731685SNick Mathewson 		}
2825dd731685SNick Mathewson 		name = namebuf;
2826dd731685SNick Mathewson 	}
2827dd731685SNick Mathewson 
28287c6df310SNiels Provos 	/* request data lives just after the header */
282915bb82d6SChristopher Davis 	req->request = ((u8 *) req) + sizeof(struct request);
28307c6df310SNiels Provos 	/* denotes that the request data shouldn't be free()ed */
283107c3fb50SNiels Provos 	req->request_appended = 1;
283207c3fb50SNiels Provos 	rlen = evdns_request_data_build(name, name_len, trans_id,
2833fe1dfe0fSNiels Provos 	    type, CLASS_INET, req->request, request_max_len);
283407c3fb50SNiels Provos 	if (rlen < 0)
283507c3fb50SNiels Provos 		goto err1;
2836dd731685SNick Mathewson 
2837cca7249eSNiels Provos 	req->request_len = rlen;
2838cca7249eSNiels Provos 	req->trans_id = trans_id;
2839cca7249eSNiels Provos 	req->tx_count = 0;
2840fe1dfe0fSNiels Provos 	req->request_type = type;
2841fe1dfe0fSNiels Provos 	req->user_pointer = user_ptr;
2842cca7249eSNiels Provos 	req->user_callback = callback;
2843e688a88aSNick Mathewson 	req->ns = issuing_now ? nameserver_pick(base) : NULL;
2844cca7249eSNiels Provos 	req->next = req->prev = NULL;
284515bb82d6SChristopher Davis 	req->handle = handle;
28469ed30de7SNick Mathewson 	if (handle) {
284715bb82d6SChristopher Davis 		handle->current_req = req;
28489ed30de7SNick Mathewson 		handle->base = base;
28499ed30de7SNick Mathewson 	}
2850cca7249eSNiels Provos 
2851cca7249eSNiels Provos 	return req;
2852cca7249eSNiels Provos err1:
285349868b61SNick Mathewson 	mm_free(req);
2854cca7249eSNiels Provos 	return NULL;
2855cca7249eSNiels Provos }
2856cca7249eSNiels Provos 
2857cca7249eSNiels Provos static void
request_submit(struct request * const req)285815bb82d6SChristopher Davis request_submit(struct request *const req) {
2859e688a88aSNick Mathewson 	struct evdns_base *base = req->base;
2860327165b3SNick Mathewson 	ASSERT_LOCKED(base);
286167072f3cSChristopher Davis 	ASSERT_VALID_REQUEST(req);
2862cca7249eSNiels Provos 	if (req->ns) {
28637c6df310SNiels Provos 		/* if it has a nameserver assigned then this is going */
28647c6df310SNiels Provos 		/* straight into the inflight queue */
286549868b61SNick Mathewson 		evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
28666b7fa620SAzat Khuzhin 
2867e688a88aSNick Mathewson 		base->global_requests_inflight++;
28686b7fa620SAzat Khuzhin 		req->ns->requests_inflight++;
28696b7fa620SAzat Khuzhin 
287052bfcab8SNiels Provos 		evdns_request_transmit(req);
2871cca7249eSNiels Provos 	} else {
2872e688a88aSNick Mathewson 		evdns_request_insert(req, &base->req_waiting_head);
2873e688a88aSNick Mathewson 		base->global_requests_waiting++;
2874cca7249eSNiels Provos 	}
2875cca7249eSNiels Provos }
2876cca7249eSNiels Provos 
28777c6df310SNiels Provos /* exported function */
287887be18daSNiels Provos void
evdns_cancel_request(struct evdns_base * base,struct evdns_request * handle)287915bb82d6SChristopher Davis evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
288087be18daSNiels Provos {
28819ed30de7SNick Mathewson 	struct request *req;
288215bb82d6SChristopher Davis 
28835208544eSSebastian Hahn 	if (!handle->current_req)
28845208544eSSebastian Hahn 		return;
28855208544eSSebastian Hahn 
28869ed30de7SNick Mathewson 	if (!base) {
28879ed30de7SNick Mathewson 		/* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
28889ed30de7SNick Mathewson 		base = handle->base;
28895208544eSSebastian Hahn 		if (!base)
28909ed30de7SNick Mathewson 			base = handle->current_req->base;
28919ed30de7SNick Mathewson 	}
2892d2e9caa6SNick Mathewson 
2893327165b3SNick Mathewson 	EVDNS_LOCK(base);
28949ed30de7SNick Mathewson 	if (handle->pending_cb) {
28959ed30de7SNick Mathewson 		EVDNS_UNLOCK(base);
28969ed30de7SNick Mathewson 		return;
28979ed30de7SNick Mathewson 	}
28989ed30de7SNick Mathewson 
28999ed30de7SNick Mathewson 	req = handle->current_req;
29009ed30de7SNick Mathewson 	ASSERT_VALID_REQUEST(req);
29019ed30de7SNick Mathewson 
29022d9619d7SNick Mathewson 	reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
290387be18daSNiels Provos 	if (req->ns) {
290487be18daSNiels Provos 		/* remove from inflight queue */
290515bb82d6SChristopher Davis 		request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
290687be18daSNiels Provos 	} else {
290787be18daSNiels Provos 		/* remove from global_waiting head */
290815bb82d6SChristopher Davis 		request_finished(req, &base->req_waiting_head, 1);
290987be18daSNiels Provos 	}
2910327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
291187be18daSNiels Provos }
291287be18daSNiels Provos 
291387be18daSNiels Provos /* exported function */
2914803dc36aSNick Mathewson struct evdns_request *
evdns_base_resolve_ipv4(struct evdns_base * base,const char * name,int flags,evdns_callback_type callback,void * ptr)2915803dc36aSNick Mathewson evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
291607c3fb50SNiels Provos     evdns_callback_type callback, void *ptr) {
291715bb82d6SChristopher Davis 	struct evdns_request *handle;
291815bb82d6SChristopher Davis 	struct request *req;
2919fe1dfe0fSNiels Provos 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
292015bb82d6SChristopher Davis 	handle = mm_calloc(1, sizeof(*handle));
292115bb82d6SChristopher Davis 	if (handle == NULL)
292215bb82d6SChristopher Davis 		return NULL;
2923327165b3SNick Mathewson 	EVDNS_LOCK(base);
2924cca7249eSNiels Provos 	if (flags & DNS_QUERY_NO_SEARCH) {
2925327165b3SNick Mathewson 		req =
292615bb82d6SChristopher Davis 			request_new(base, handle, TYPE_A, name, flags,
292715bb82d6SChristopher Davis 				    callback, ptr);
2928327165b3SNick Mathewson 		if (req)
2929cca7249eSNiels Provos 			request_submit(req);
2930cca7249eSNiels Provos 	} else {
2931b14f151bSNick Mathewson 		search_request_new(base, handle, TYPE_A, name, flags,
293215bb82d6SChristopher Davis 		    callback, ptr);
2933cca7249eSNiels Provos 	}
2934b14f151bSNick Mathewson 	if (handle->current_req == NULL) {
2935b14f151bSNick Mathewson 		mm_free(handle);
2936b14f151bSNick Mathewson 		handle = NULL;
2937b14f151bSNick Mathewson 	}
2938327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
293915bb82d6SChristopher Davis 	return handle;
2940cca7249eSNiels Provos }
2941cca7249eSNiels Provos 
evdns_resolve_ipv4(const char * name,int flags,evdns_callback_type callback,void * ptr)2942e688a88aSNick Mathewson int evdns_resolve_ipv4(const char *name, int flags,
2943e688a88aSNick Mathewson 					   evdns_callback_type callback, void *ptr)
2944e688a88aSNick Mathewson {
2945803dc36aSNick Mathewson 	return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
2946803dc36aSNick Mathewson 		? 0 : -1;
2947e688a88aSNick Mathewson }
2948e688a88aSNick Mathewson 
2949e688a88aSNick Mathewson 
29507c6df310SNiels Provos /* exported function */
2951803dc36aSNick Mathewson struct evdns_request *
evdns_base_resolve_ipv6(struct evdns_base * base,const char * name,int flags,evdns_callback_type callback,void * ptr)2952803dc36aSNick Mathewson evdns_base_resolve_ipv6(struct evdns_base *base,
2953e688a88aSNick Mathewson     const char *name, int flags,
2954d0a9c90eSNick Mathewson     evdns_callback_type callback, void *ptr)
2955d0a9c90eSNick Mathewson {
295615bb82d6SChristopher Davis 	struct evdns_request *handle;
295715bb82d6SChristopher Davis 	struct request *req;
2958e688a88aSNick Mathewson 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
295915bb82d6SChristopher Davis 	handle = mm_calloc(1, sizeof(*handle));
296015bb82d6SChristopher Davis 	if (handle == NULL)
296115bb82d6SChristopher Davis 		return NULL;
2962327165b3SNick Mathewson 	EVDNS_LOCK(base);
2963e688a88aSNick Mathewson 	if (flags & DNS_QUERY_NO_SEARCH) {
296415bb82d6SChristopher Davis 		req = request_new(base, handle, TYPE_AAAA, name, flags,
296515bb82d6SChristopher Davis 				  callback, ptr);
2966327165b3SNick Mathewson 		if (req)
2967e688a88aSNick Mathewson 			request_submit(req);
2968e688a88aSNick Mathewson 	} else {
2969b14f151bSNick Mathewson 		search_request_new(base, handle, TYPE_AAAA, name, flags,
297015bb82d6SChristopher Davis 		    callback, ptr);
2971e688a88aSNick Mathewson 	}
2972b14f151bSNick Mathewson 	if (handle->current_req == NULL) {
2973b14f151bSNick Mathewson 		mm_free(handle);
2974b14f151bSNick Mathewson 		handle = NULL;
2975b14f151bSNick Mathewson 	}
2976327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
297715bb82d6SChristopher Davis 	return handle;
2978e688a88aSNick Mathewson }
2979e688a88aSNick Mathewson 
evdns_resolve_ipv6(const char * name,int flags,evdns_callback_type callback,void * ptr)29806318fca2SNiels Provos int evdns_resolve_ipv6(const char *name, int flags,
29816318fca2SNiels Provos     evdns_callback_type callback, void *ptr) {
2982803dc36aSNick Mathewson 	return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
2983803dc36aSNick Mathewson 		? 0 : -1;
29846318fca2SNiels Provos }
29856318fca2SNiels Provos 
2986803dc36aSNick Mathewson struct evdns_request *
evdns_base_resolve_reverse(struct evdns_base * base,const struct in_addr * in,int flags,evdns_callback_type callback,void * ptr)29874d92e426SNick Mathewson evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
2988fe1dfe0fSNiels Provos 	char buf[32];
298915bb82d6SChristopher Davis 	struct evdns_request *handle;
299015bb82d6SChristopher Davis 	struct request *req;
2991fe1dfe0fSNiels Provos 	u32 a;
29922e36dbe1SNick Mathewson 	EVUTIL_ASSERT(in);
2993fe1dfe0fSNiels Provos 	a = ntohl(in->s_addr);
2994c6da86ffSNick Mathewson 	evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
2995fe1dfe0fSNiels Provos 			(int)(u8)((a	)&0xff),
2996fe1dfe0fSNiels Provos 			(int)(u8)((a>>8 )&0xff),
2997fe1dfe0fSNiels Provos 			(int)(u8)((a>>16)&0xff),
2998fe1dfe0fSNiels Provos 			(int)(u8)((a>>24)&0xff));
299915bb82d6SChristopher Davis 	handle = mm_calloc(1, sizeof(*handle));
300015bb82d6SChristopher Davis 	if (handle == NULL)
300115bb82d6SChristopher Davis 		return NULL;
3002fe1dfe0fSNiels Provos 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
3003327165b3SNick Mathewson 	EVDNS_LOCK(base);
300415bb82d6SChristopher Davis 	req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
3005327165b3SNick Mathewson 	if (req)
3006fe1dfe0fSNiels Provos 		request_submit(req);
3007b14f151bSNick Mathewson 	if (handle->current_req == NULL) {
3008b14f151bSNick Mathewson 		mm_free(handle);
3009b14f151bSNick Mathewson 		handle = NULL;
3010b14f151bSNick Mathewson 	}
3011327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
301215bb82d6SChristopher Davis 	return (handle);
3013fe1dfe0fSNiels Provos }
3014fe1dfe0fSNiels Provos 
evdns_resolve_reverse(const struct in_addr * in,int flags,evdns_callback_type callback,void * ptr)30154d92e426SNick Mathewson int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
3016803dc36aSNick Mathewson 	return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
3017803dc36aSNick Mathewson 		? 0 : -1;
3018e688a88aSNick Mathewson }
3019e688a88aSNick Mathewson 
3020803dc36aSNick Mathewson 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)30214d92e426SNick Mathewson evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
30228b392549SNick Mathewson 	/* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
30238b392549SNick Mathewson 	char buf[73];
30246318fca2SNiels Provos 	char *cp;
302515bb82d6SChristopher Davis 	struct evdns_request *handle;
302615bb82d6SChristopher Davis 	struct request *req;
30276318fca2SNiels Provos 	int i;
30282e36dbe1SNick Mathewson 	EVUTIL_ASSERT(in);
30296318fca2SNiels Provos 	cp = buf;
30306318fca2SNiels Provos 	for (i=15; i >= 0; --i) {
30316318fca2SNiels Provos 		u8 byte = in->s6_addr[i];
30326318fca2SNiels Provos 		*cp++ = "0123456789abcdef"[byte & 0x0f];
30336318fca2SNiels Provos 		*cp++ = '.';
30346318fca2SNiels Provos 		*cp++ = "0123456789abcdef"[byte >> 4];
30356318fca2SNiels Provos 		*cp++ = '.';
30366318fca2SNiels Provos 	}
30372e36dbe1SNick Mathewson 	EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
30388b392549SNick Mathewson 	memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
303915bb82d6SChristopher Davis 	handle = mm_calloc(1, sizeof(*handle));
304015bb82d6SChristopher Davis 	if (handle == NULL)
304115bb82d6SChristopher Davis 		return NULL;
30426318fca2SNiels Provos 	log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
3043327165b3SNick Mathewson 	EVDNS_LOCK(base);
304415bb82d6SChristopher Davis 	req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
3045327165b3SNick Mathewson 	if (req)
30466318fca2SNiels Provos 		request_submit(req);
3047b14f151bSNick Mathewson 	if (handle->current_req == NULL) {
3048b14f151bSNick Mathewson 		mm_free(handle);
3049b14f151bSNick Mathewson 		handle = NULL;
3050b14f151bSNick Mathewson 	}
3051327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
305215bb82d6SChristopher Davis 	return (handle);
30536318fca2SNiels Provos }
30546318fca2SNiels Provos 
evdns_resolve_reverse_ipv6(const struct in6_addr * in,int flags,evdns_callback_type callback,void * ptr)30554d92e426SNick Mathewson int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
3056803dc36aSNick Mathewson 	return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
3057803dc36aSNick Mathewson 		? 0 : -1;
3058e688a88aSNick Mathewson }
3059e688a88aSNick Mathewson 
3060e2ca403fSNick Mathewson /* ================================================================= */
30617c6df310SNiels Provos /* Search support */
30627c6df310SNiels Provos /* */
30637c6df310SNiels Provos /* the libc resolver has support for searching a number of domains */
30647c6df310SNiels Provos /* to find a name. If nothing else then it takes the single domain */
30657c6df310SNiels Provos /* from the gethostname() call. */
30667c6df310SNiels Provos /* */
30677c6df310SNiels Provos /* It can also be configured via the domain and search options in a */
30687c6df310SNiels Provos /* resolv.conf. */
30697c6df310SNiels Provos /* */
30707c6df310SNiels Provos /* The ndots option controls how many dots it takes for the resolver */
30717c6df310SNiels Provos /* to decide that a name is non-local and so try a raw lookup first. */
3072cca7249eSNiels Provos 
3073cca7249eSNiels Provos struct search_domain {
3074cca7249eSNiels Provos 	int len;
3075cca7249eSNiels Provos 	struct search_domain *next;
30767c6df310SNiels Provos 	/* the text string is appended to this structure */
3077cca7249eSNiels Provos };
3078cca7249eSNiels Provos 
3079cca7249eSNiels Provos struct search_state {
3080cca7249eSNiels Provos 	int refcount;
3081cca7249eSNiels Provos 	int ndots;
3082cca7249eSNiels Provos 	int num_domains;
3083cca7249eSNiels Provos 	struct search_domain *head;
3084cca7249eSNiels Provos };
3085cca7249eSNiels Provos 
3086cca7249eSNiels Provos static void
search_state_decref(struct search_state * const state)3087cca7249eSNiels Provos search_state_decref(struct search_state *const state) {
3088cca7249eSNiels Provos 	if (!state) return;
3089cca7249eSNiels Provos 	state->refcount--;
3090cca7249eSNiels Provos 	if (!state->refcount) {
3091cca7249eSNiels Provos 		struct search_domain *next, *dom;
3092cca7249eSNiels Provos 		for (dom = state->head; dom; dom = next) {
3093cca7249eSNiels Provos 			next = dom->next;
309449868b61SNick Mathewson 			mm_free(dom);
3095cca7249eSNiels Provos 		}
309649868b61SNick Mathewson 		mm_free(state);
3097cca7249eSNiels Provos 	}
3098fe1dfe0fSNiels Provos }
3099cca7249eSNiels Provos 
3100cca7249eSNiels Provos static struct search_state *
search_state_new(void)3101cca7249eSNiels Provos search_state_new(void) {
310249868b61SNick Mathewson 	struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
3103cca7249eSNiels Provos 	if (!state) return NULL;
3104cca7249eSNiels Provos 	memset(state, 0, sizeof(struct search_state));
3105cca7249eSNiels Provos 	state->refcount = 1;
3106cca7249eSNiels Provos 	state->ndots = 1;
3107cca7249eSNiels Provos 
3108cca7249eSNiels Provos 	return state;
3109cca7249eSNiels Provos }
3110cca7249eSNiels Provos 
3111cca7249eSNiels Provos static void
search_postfix_clear(struct evdns_base * base)3112e688a88aSNick Mathewson search_postfix_clear(struct evdns_base *base) {
3113e688a88aSNick Mathewson 	search_state_decref(base->global_search_state);
3114cca7249eSNiels Provos 
3115e688a88aSNick Mathewson 	base->global_search_state = search_state_new();
3116cca7249eSNiels Provos }
3117cca7249eSNiels Provos 
31187c6df310SNiels Provos /* exported function */
3119cca7249eSNiels Provos void
evdns_base_search_clear(struct evdns_base * base)3120327165b3SNick Mathewson evdns_base_search_clear(struct evdns_base *base)
3121327165b3SNick Mathewson {
3122327165b3SNick Mathewson 	EVDNS_LOCK(base);
3123e688a88aSNick Mathewson 	search_postfix_clear(base);
3124327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
3125e688a88aSNick Mathewson }
3126e688a88aSNick Mathewson 
3127e688a88aSNick Mathewson void
evdns_search_clear(void)312852bfcab8SNiels Provos evdns_search_clear(void) {
3129e688a88aSNick Mathewson 	evdns_base_search_clear(current_base);
3130cca7249eSNiels Provos }
3131cca7249eSNiels Provos 
3132cca7249eSNiels Provos static void
search_postfix_add(struct evdns_base * base,const char * domain)3133e688a88aSNick Mathewson search_postfix_add(struct evdns_base *base, const char *domain) {
3134545a6114SNick Mathewson 	size_t domain_len;
3135cca7249eSNiels Provos 	struct search_domain *sdomain;
3136cca7249eSNiels Provos 	while (domain[0] == '.') domain++;
3137cca7249eSNiels Provos 	domain_len = strlen(domain);
3138cca7249eSNiels Provos 
3139327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3140e688a88aSNick Mathewson 	if (!base->global_search_state) base->global_search_state = search_state_new();
3141e688a88aSNick Mathewson 	if (!base->global_search_state) return;
3142e688a88aSNick Mathewson 	base->global_search_state->num_domains++;
3143cca7249eSNiels Provos 
314449868b61SNick Mathewson 	sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
3145cca7249eSNiels Provos 	if (!sdomain) return;
3146cca7249eSNiels Provos 	memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
3147e688a88aSNick Mathewson 	sdomain->next = base->global_search_state->head;
3148545a6114SNick Mathewson 	sdomain->len = (int) domain_len;
3149cca7249eSNiels Provos 
3150e688a88aSNick Mathewson 	base->global_search_state->head = sdomain;
3151cca7249eSNiels Provos }
3152cca7249eSNiels Provos 
31537c6df310SNiels Provos /* reverse the order of members in the postfix list. This is needed because, */
31547c6df310SNiels Provos /* when parsing resolv.conf we push elements in the wrong order */
3155cca7249eSNiels Provos static void
search_reverse(struct evdns_base * base)3156e688a88aSNick Mathewson search_reverse(struct evdns_base *base) {
3157cca7249eSNiels Provos 	struct search_domain *cur, *prev = NULL, *next;
3158327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3159e688a88aSNick Mathewson 	cur = base->global_search_state->head;
3160cca7249eSNiels Provos 	while (cur) {
3161cca7249eSNiels Provos 		next = cur->next;
3162cca7249eSNiels Provos 		cur->next = prev;
3163cca7249eSNiels Provos 		prev = cur;
3164cca7249eSNiels Provos 		cur = next;
3165cca7249eSNiels Provos 	}
3166cca7249eSNiels Provos 
3167e688a88aSNick Mathewson 	base->global_search_state->head = prev;
3168cca7249eSNiels Provos }
3169cca7249eSNiels Provos 
31707c6df310SNiels Provos /* exported function */
3171cca7249eSNiels Provos void
evdns_base_search_add(struct evdns_base * base,const char * domain)3172e688a88aSNick Mathewson evdns_base_search_add(struct evdns_base *base, const char *domain) {
3173327165b3SNick Mathewson 	EVDNS_LOCK(base);
3174e688a88aSNick Mathewson 	search_postfix_add(base, domain);
3175327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
3176e688a88aSNick Mathewson }
3177e688a88aSNick Mathewson void
evdns_search_add(const char * domain)317852bfcab8SNiels Provos evdns_search_add(const char *domain) {
3179e688a88aSNick Mathewson 	evdns_base_search_add(current_base, domain);
3180cca7249eSNiels Provos }
3181cca7249eSNiels Provos 
31827c6df310SNiels Provos /* exported function */
3183cca7249eSNiels Provos void
evdns_base_search_ndots_set(struct evdns_base * base,const int ndots)3184e688a88aSNick Mathewson evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
3185327165b3SNick Mathewson 	EVDNS_LOCK(base);
3186e688a88aSNick Mathewson 	if (!base->global_search_state) base->global_search_state = search_state_new();
3187327165b3SNick Mathewson 	if (base->global_search_state)
3188e688a88aSNick Mathewson 		base->global_search_state->ndots = ndots;
3189327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
3190e688a88aSNick Mathewson }
3191e688a88aSNick Mathewson void
evdns_search_ndots_set(const int ndots)319252bfcab8SNiels Provos evdns_search_ndots_set(const int ndots) {
31930bee2ff3SNiels Provos 	evdns_base_search_ndots_set(current_base, ndots);
3194cca7249eSNiels Provos }
3195cca7249eSNiels Provos 
3196cca7249eSNiels Provos static void
search_set_from_hostname(struct evdns_base * base)3197e688a88aSNick Mathewson search_set_from_hostname(struct evdns_base *base) {
3198cca7249eSNiels Provos 	char hostname[HOST_NAME_MAX + 1], *domainname;
3199cca7249eSNiels Provos 
3200327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3201e688a88aSNick Mathewson 	search_postfix_clear(base);
3202cca7249eSNiels Provos 	if (gethostname(hostname, sizeof(hostname))) return;
3203cca7249eSNiels Provos 	domainname = strchr(hostname, '.');
3204cca7249eSNiels Provos 	if (!domainname) return;
3205e688a88aSNick Mathewson 	search_postfix_add(base, domainname);
3206cca7249eSNiels Provos }
3207cca7249eSNiels Provos 
32087c6df310SNiels Provos /* warning: returns malloced string */
3209cca7249eSNiels Provos static char *
search_make_new(const struct search_state * const state,int n,const char * const base_name)3210cca7249eSNiels Provos search_make_new(const struct search_state *const state, int n, const char *const base_name) {
3211545a6114SNick Mathewson 	const size_t base_len = strlen(base_name);
3212ec65c420SAzat Khuzhin 	char need_to_append_dot;
3213cca7249eSNiels Provos 	struct search_domain *dom;
3214cca7249eSNiels Provos 
3215ec65c420SAzat Khuzhin 	if (!base_len) return NULL;
3216ec65c420SAzat Khuzhin 	need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
3217ec65c420SAzat Khuzhin 
3218cca7249eSNiels Provos 	for (dom = state->head; dom; dom = dom->next) {
3219cca7249eSNiels Provos 		if (!n--) {
32207c6df310SNiels Provos 			/* this is the postfix we want */
32217c6df310SNiels Provos 			/* the actual postfix string is kept at the end of the structure */
3222cca7249eSNiels Provos 			const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
3223cca7249eSNiels Provos 			const int postfix_len = dom->len;
322449868b61SNick Mathewson 			char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
3225cca7249eSNiels Provos 			if (!newname) return NULL;
3226cca7249eSNiels Provos 			memcpy(newname, base_name, base_len);
3227cca7249eSNiels Provos 			if (need_to_append_dot) newname[base_len] = '.';
3228cca7249eSNiels Provos 			memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
3229cca7249eSNiels Provos 			newname[base_len + need_to_append_dot + postfix_len] = 0;
3230cca7249eSNiels Provos 			return newname;
3231cca7249eSNiels Provos 		}
3232cca7249eSNiels Provos 	}
3233cca7249eSNiels Provos 
32347c6df310SNiels Provos 	/* we ran off the end of the list and still didn't find the requested string */
323591fe23fcSNick Mathewson 	EVUTIL_ASSERT(0);
32365baf8ecfSNiels Provos 	return NULL; /* unreachable; stops warnings in some compilers. */
3237cca7249eSNiels Provos }
3238cca7249eSNiels Provos 
323915bb82d6SChristopher Davis 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)324015bb82d6SChristopher Davis search_request_new(struct evdns_base *base, struct evdns_request *handle,
324115bb82d6SChristopher Davis 		   int type, const char *const name, int flags,
324215bb82d6SChristopher Davis 		   evdns_callback_type user_callback, void *user_arg) {
3243327165b3SNick Mathewson 	ASSERT_LOCKED(base);
32442e36dbe1SNick Mathewson 	EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
324567072f3cSChristopher Davis 	EVUTIL_ASSERT(handle->current_req == NULL);
3246cca7249eSNiels Provos 	if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
3247e688a88aSNick Mathewson 	     base->global_search_state &&
3248e688a88aSNick Mathewson 		 base->global_search_state->num_domains) {
32497c6df310SNiels Provos 		/* we have some domains to search */
325015bb82d6SChristopher Davis 		struct request *req;
3251e688a88aSNick Mathewson 		if (string_num_dots(name) >= base->global_search_state->ndots) {
325215bb82d6SChristopher Davis 			req = request_new(base, handle, type, name, flags, user_callback, user_arg);
3253803dc36aSNick Mathewson 			if (!req) return NULL;
3254beaa14a4SChristopher Davis 			handle->search_index = -1;
3255cca7249eSNiels Provos 		} else {
3256e688a88aSNick Mathewson 			char *const new_name = search_make_new(base->global_search_state, 0, name);
3257803dc36aSNick Mathewson 			if (!new_name) return NULL;
325815bb82d6SChristopher Davis 			req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
325949868b61SNick Mathewson 			mm_free(new_name);
3260803dc36aSNick Mathewson 			if (!req) return NULL;
3261beaa14a4SChristopher Davis 			handle->search_index = 0;
3262cca7249eSNiels Provos 		}
3263beaa14a4SChristopher Davis 		EVUTIL_ASSERT(handle->search_origname == NULL);
3264beaa14a4SChristopher Davis 		handle->search_origname = mm_strdup(name);
3265666b0966SJardel Weyrich 		if (handle->search_origname == NULL) {
3266666b0966SJardel Weyrich 			/* XXX Should we dealloc req? If yes, how? */
3267f2bff75eSGeorge Danchev 			if (req)
3268f2bff75eSGeorge Danchev 				mm_free(req);
3269666b0966SJardel Weyrich 			return NULL;
3270666b0966SJardel Weyrich 		}
3271beaa14a4SChristopher Davis 		handle->search_state = base->global_search_state;
3272beaa14a4SChristopher Davis 		handle->search_flags = flags;
3273e688a88aSNick Mathewson 		base->global_search_state->refcount++;
3274cca7249eSNiels Provos 		request_submit(req);
3275803dc36aSNick Mathewson 		return req;
3276cca7249eSNiels Provos 	} else {
327715bb82d6SChristopher Davis 		struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
3278803dc36aSNick Mathewson 		if (!req) return NULL;
3279cca7249eSNiels Provos 		request_submit(req);
3280803dc36aSNick Mathewson 		return req;
3281cca7249eSNiels Provos 	}
3282cca7249eSNiels Provos }
3283cca7249eSNiels Provos 
32847c6df310SNiels Provos /* this is called when a request has failed to find a name. We need to check */
32857c6df310SNiels Provos /* if it is part of a search and, if so, try the next name in the list */
32867c6df310SNiels Provos /* returns: */
32877c6df310SNiels Provos /*   0 another request has been submitted */
32887c6df310SNiels Provos /*   1 no more requests needed */
3289cca7249eSNiels Provos static int
search_try_next(struct evdns_request * const handle)3290beaa14a4SChristopher Davis search_try_next(struct evdns_request *const handle) {
3291beaa14a4SChristopher Davis 	struct request *req = handle->current_req;
3292e688a88aSNick Mathewson 	struct evdns_base *base = req->base;
329367072f3cSChristopher Davis 	struct request *newreq;
3294327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3295beaa14a4SChristopher Davis 	if (handle->search_state) {
32967c6df310SNiels Provos 		/* it is part of a search */
3297cca7249eSNiels Provos 		char *new_name;
3298beaa14a4SChristopher Davis 		handle->search_index++;
3299beaa14a4SChristopher Davis 		if (handle->search_index >= handle->search_state->num_domains) {
33007c6df310SNiels Provos 			/* no more postfixes to try, however we may need to try */
33017c6df310SNiels Provos 			/* this name without a postfix */
3302beaa14a4SChristopher Davis 			if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
33037c6df310SNiels Provos 				/* yep, we need to try it raw */
330467072f3cSChristopher Davis 				newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
3305beaa14a4SChristopher Davis 				log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
3306cca7249eSNiels Provos 				if (newreq) {
3307a6258400SChristopher Davis 					search_request_finished(handle);
330867072f3cSChristopher Davis 					goto submit_next;
3309cca7249eSNiels Provos 				}
3310cca7249eSNiels Provos 			}
3311cca7249eSNiels Provos 			return 1;
3312cca7249eSNiels Provos 		}
3313cca7249eSNiels Provos 
3314beaa14a4SChristopher Davis 		new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
3315cca7249eSNiels Provos 		if (!new_name) return 1;
3316beaa14a4SChristopher Davis 		log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
331767072f3cSChristopher Davis 		newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
331849868b61SNick Mathewson 		mm_free(new_name);
3319cca7249eSNiels Provos 		if (!newreq) return 1;
332067072f3cSChristopher Davis 		goto submit_next;
3321cca7249eSNiels Provos 	}
3322cca7249eSNiels Provos 	return 1;
332367072f3cSChristopher Davis 
332467072f3cSChristopher Davis submit_next:
332567072f3cSChristopher Davis 	request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
332667072f3cSChristopher Davis 	handle->current_req = newreq;
332767072f3cSChristopher Davis 	newreq->handle = handle;
332867072f3cSChristopher Davis 	request_submit(newreq);
332967072f3cSChristopher Davis 	return 0;
3330cca7249eSNiels Provos }
3331cca7249eSNiels Provos 
3332cca7249eSNiels Provos static void
search_request_finished(struct evdns_request * const handle)3333beaa14a4SChristopher Davis search_request_finished(struct evdns_request *const handle) {
3334beaa14a4SChristopher Davis 	ASSERT_LOCKED(handle->current_req->base);
3335beaa14a4SChristopher Davis 	if (handle->search_state) {
3336beaa14a4SChristopher Davis 		search_state_decref(handle->search_state);
3337beaa14a4SChristopher Davis 		handle->search_state = NULL;
3338cca7249eSNiels Provos 	}
3339beaa14a4SChristopher Davis 	if (handle->search_origname) {
3340beaa14a4SChristopher Davis 		mm_free(handle->search_origname);
3341beaa14a4SChristopher Davis 		handle->search_origname = NULL;
3342cca7249eSNiels Provos 	}
3343cca7249eSNiels Provos }
3344cca7249eSNiels Provos 
3345e2ca403fSNick Mathewson /* ================================================================= */
33467c6df310SNiels Provos /* Parsing resolv.conf files */
3347cca7249eSNiels Provos 
3348cca7249eSNiels Provos static void
evdns_resolv_set_defaults(struct evdns_base * base,int flags)3349e688a88aSNick Mathewson evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
335058e81106SAzat Khuzhin 	int add_default = flags & DNS_OPTION_NAMESERVERS;
335158e81106SAzat Khuzhin 	if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
335258e81106SAzat Khuzhin 		add_default = 0;
335358e81106SAzat Khuzhin 
33547c6df310SNiels Provos 	/* if the file isn't found then we assume a local resolver */
3355327165b3SNick Mathewson 	ASSERT_LOCKED(base);
335658e81106SAzat Khuzhin 	if (flags & DNS_OPTION_SEARCH)
335758e81106SAzat Khuzhin 		search_set_from_hostname(base);
335858e81106SAzat Khuzhin 	if (add_default)
335958e81106SAzat Khuzhin 		evdns_base_nameserver_ip_add(base, "127.0.0.1");
3360cca7249eSNiels Provos }
3361cca7249eSNiels Provos 
336268120d9bSNick Mathewson #ifndef EVENT__HAVE_STRTOK_R
3363cca7249eSNiels Provos static char *
strtok_r(char * s,const char * delim,char ** state)3364cca7249eSNiels Provos strtok_r(char *s, const char *delim, char **state) {
3365e688a88aSNick Mathewson 	char *cp, *start;
3366e688a88aSNick Mathewson 	start = cp = s ? s : *state;
3367e688a88aSNick Mathewson 	if (!cp)
3368e688a88aSNick Mathewson 		return NULL;
3369e688a88aSNick Mathewson 	while (*cp && !strchr(delim, *cp))
3370e688a88aSNick Mathewson 		++cp;
3371e688a88aSNick Mathewson 	if (!*cp) {
3372e688a88aSNick Mathewson 		if (cp == start)
3373e688a88aSNick Mathewson 			return NULL;
3374e688a88aSNick Mathewson 		*state = NULL;
3375e688a88aSNick Mathewson 		return start;
3376e688a88aSNick Mathewson 	} else {
3377e688a88aSNick Mathewson 		*cp++ = '\0';
3378e688a88aSNick Mathewson 		*state = cp;
3379e688a88aSNick Mathewson 		return start;
3380e688a88aSNick Mathewson 	}
3381cca7249eSNiels Provos }
3382cca7249eSNiels Provos #endif
3383cca7249eSNiels Provos 
33847c6df310SNiels Provos /* helper version of atoi which returns -1 on error */
3385cca7249eSNiels Provos static int
strtoint(const char * const str)3386213dc2a2SNick Mathewson strtoint(const char *const str)
3387213dc2a2SNick Mathewson {
3388cca7249eSNiels Provos 	char *endptr;
3389cca7249eSNiels Provos 	const int r = strtol(str, &endptr, 10);
3390cca7249eSNiels Provos 	if (*endptr) return -1;
3391cca7249eSNiels Provos 	return r;
3392cca7249eSNiels Provos }
3393cca7249eSNiels Provos 
3394213dc2a2SNick Mathewson /* Parse a number of seconds into a timeval; return -1 on error. */
3395213dc2a2SNick Mathewson static int
evdns_strtotimeval(const char * const str,struct timeval * out)3396bdbc823fSXiao Bao Clark evdns_strtotimeval(const char *const str, struct timeval *out)
3397213dc2a2SNick Mathewson {
3398213dc2a2SNick Mathewson 	double d;
3399213dc2a2SNick Mathewson 	char *endptr;
3400213dc2a2SNick Mathewson 	d = strtod(str, &endptr);
3401213dc2a2SNick Mathewson 	if (*endptr) return -1;
3402ee4953f8SNick Mathewson 	if (d < 0) return -1;
3403213dc2a2SNick Mathewson 	out->tv_sec = (int) d;
3404213dc2a2SNick Mathewson 	out->tv_usec = (int) ((d - (int) d)*1000000);
3405ee4953f8SNick Mathewson 	if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
3406ee4953f8SNick Mathewson 		return -1;
3407213dc2a2SNick Mathewson 	return 0;
3408213dc2a2SNick Mathewson }
3409213dc2a2SNick Mathewson 
34107c6df310SNiels Provos /* helper version of atoi that returns -1 on error and clips to bounds. */
341178f2aa30SNiels Provos static int
strtoint_clipped(const char * const str,int min,int max)341278f2aa30SNiels Provos strtoint_clipped(const char *const str, int min, int max)
341378f2aa30SNiels Provos {
341478f2aa30SNiels Provos 	int r = strtoint(str);
341578f2aa30SNiels Provos 	if (r == -1)
341678f2aa30SNiels Provos 		return r;
341778f2aa30SNiels Provos 	else if (r<min)
341878f2aa30SNiels Provos 		return min;
341978f2aa30SNiels Provos 	else if (r>max)
342078f2aa30SNiels Provos 		return max;
342178f2aa30SNiels Provos 	else
342278f2aa30SNiels Provos 		return r;
342378f2aa30SNiels Provos }
342478f2aa30SNiels Provos 
342549868b61SNick Mathewson static int
evdns_base_set_max_requests_inflight(struct evdns_base * base,int maxinflight)342649868b61SNick Mathewson evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
342749868b61SNick Mathewson {
342849868b61SNick Mathewson 	int old_n_heads = base->n_req_heads, n_heads;
342915bb82d6SChristopher Davis 	struct request **old_heads = base->req_heads, **new_heads, *req;
343049868b61SNick Mathewson 	int i;
3431327165b3SNick Mathewson 
3432327165b3SNick Mathewson 	ASSERT_LOCKED(base);
343349868b61SNick Mathewson 	if (maxinflight < 1)
343449868b61SNick Mathewson 		maxinflight = 1;
343549868b61SNick Mathewson 	n_heads = (maxinflight+4) / 5;
34362e36dbe1SNick Mathewson 	EVUTIL_ASSERT(n_heads > 0);
343715bb82d6SChristopher Davis 	new_heads = mm_calloc(n_heads, sizeof(struct request*));
343849868b61SNick Mathewson 	if (!new_heads)
343949868b61SNick Mathewson 		return (-1);
344049868b61SNick Mathewson 	if (old_heads) {
344149868b61SNick Mathewson 		for (i = 0; i < old_n_heads; ++i) {
344249868b61SNick Mathewson 			while (old_heads[i]) {
344349868b61SNick Mathewson 				req = old_heads[i];
34441eeb96aaSNiels Provos 				evdns_request_remove(req, &old_heads[i]);
344549868b61SNick Mathewson 				evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
344649868b61SNick Mathewson 			}
344749868b61SNick Mathewson 		}
344849868b61SNick Mathewson 		mm_free(old_heads);
344949868b61SNick Mathewson 	}
345049868b61SNick Mathewson 	base->req_heads = new_heads;
345149868b61SNick Mathewson 	base->n_req_heads = n_heads;
345249868b61SNick Mathewson 	base->global_max_requests_inflight = maxinflight;
345349868b61SNick Mathewson 	return (0);
345449868b61SNick Mathewson }
345549868b61SNick Mathewson 
34567c6df310SNiels Provos /* exported function */
345778f2aa30SNiels Provos int
evdns_base_set_option(struct evdns_base * base,const char * option,const char * val)3458e688a88aSNick Mathewson evdns_base_set_option(struct evdns_base *base,
34591dd7e6dcSNick Mathewson     const char *option, const char *val)
346078f2aa30SNiels Provos {
3461327165b3SNick Mathewson 	int res;
3462327165b3SNick Mathewson 	EVDNS_LOCK(base);
34631dd7e6dcSNick Mathewson 	res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
3464327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
3465327165b3SNick Mathewson 	return res;
3466327165b3SNick Mathewson }
3467327165b3SNick Mathewson 
346872bafc17SNick Mathewson static inline int
str_matches_option(const char * s1,const char * optionname)346972bafc17SNick Mathewson str_matches_option(const char *s1, const char *optionname)
347072bafc17SNick Mathewson {
347172bafc17SNick Mathewson 	/* Option names are given as "option:" We accept either 'option' in
347272bafc17SNick Mathewson 	 * s1, or 'option:randomjunk'.  The latter form is to implement the
347372bafc17SNick Mathewson 	 * resolv.conf parser. */
347472bafc17SNick Mathewson 	size_t optlen = strlen(optionname);
3475ee4953f8SNick Mathewson 	size_t slen = strlen(s1);
3476ee4953f8SNick Mathewson 	if (slen == optlen || slen == optlen - 1)
3477ee4953f8SNick Mathewson 		return !strncmp(s1, optionname, slen);
3478ee4953f8SNick Mathewson 	else if (slen > optlen)
347972bafc17SNick Mathewson 		return !strncmp(s1, optionname, optlen);
3480ee4953f8SNick Mathewson 	else
3481ee4953f8SNick Mathewson 		return 0;
348272bafc17SNick Mathewson }
348372bafc17SNick Mathewson 
3484327165b3SNick Mathewson static int
evdns_base_set_option_impl(struct evdns_base * base,const char * option,const char * val,int flags)3485327165b3SNick Mathewson evdns_base_set_option_impl(struct evdns_base *base,
3486327165b3SNick Mathewson     const char *option, const char *val, int flags)
3487327165b3SNick Mathewson {
3488327165b3SNick Mathewson 	ASSERT_LOCKED(base);
348972bafc17SNick Mathewson 	if (str_matches_option(option, "ndots:")) {
349078f2aa30SNiels Provos 		const int ndots = strtoint(val);
349178f2aa30SNiels Provos 		if (ndots == -1) return -1;
349278f2aa30SNiels Provos 		if (!(flags & DNS_OPTION_SEARCH)) return 0;
349378f2aa30SNiels Provos 		log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
3494e688a88aSNick Mathewson 		if (!base->global_search_state) base->global_search_state = search_state_new();
3495e688a88aSNick Mathewson 		if (!base->global_search_state) return -1;
3496e688a88aSNick Mathewson 		base->global_search_state->ndots = ndots;
349772bafc17SNick Mathewson 	} else if (str_matches_option(option, "timeout:")) {
3498213dc2a2SNick Mathewson 		struct timeval tv;
3499bdbc823fSXiao Bao Clark 		if (evdns_strtotimeval(val, &tv) == -1) return -1;
350078f2aa30SNiels Provos 		if (!(flags & DNS_OPTION_MISC)) return 0;
3501213dc2a2SNick Mathewson 		log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
3502213dc2a2SNick Mathewson 		memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
350386f57420SNick Mathewson 	} else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
350486f57420SNick Mathewson 		struct timeval tv;
3505bdbc823fSXiao Bao Clark 		if (evdns_strtotimeval(val, &tv) == -1) return -1;
350686f57420SNick Mathewson 		if (!(flags & DNS_OPTION_MISC)) return 0;
350786f57420SNick Mathewson 		log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
350886f57420SNick Mathewson 		    val);
350986f57420SNick Mathewson 		memcpy(&base->global_getaddrinfo_allow_skew, &tv,
351086f57420SNick Mathewson 		    sizeof(struct timeval));
351172bafc17SNick Mathewson 	} else if (str_matches_option(option, "max-timeouts:")) {
351278f2aa30SNiels Provos 		const int maxtimeout = strtoint_clipped(val, 1, 255);
351378f2aa30SNiels Provos 		if (maxtimeout == -1) return -1;
351478f2aa30SNiels Provos 		if (!(flags & DNS_OPTION_MISC)) return 0;
351578f2aa30SNiels Provos 		log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
351678f2aa30SNiels Provos 			maxtimeout);
3517e688a88aSNick Mathewson 		base->global_max_nameserver_timeout = maxtimeout;
351872bafc17SNick Mathewson 	} else if (str_matches_option(option, "max-inflight:")) {
351978f2aa30SNiels Provos 		const int maxinflight = strtoint_clipped(val, 1, 65000);
352078f2aa30SNiels Provos 		if (maxinflight == -1) return -1;
352178f2aa30SNiels Provos 		if (!(flags & DNS_OPTION_MISC)) return 0;
352278f2aa30SNiels Provos 		log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
352378f2aa30SNiels Provos 			maxinflight);
352449868b61SNick Mathewson 		evdns_base_set_max_requests_inflight(base, maxinflight);
352572bafc17SNick Mathewson 	} else if (str_matches_option(option, "attempts:")) {
352678f2aa30SNiels Provos 		int retries = strtoint(val);
352778f2aa30SNiels Provos 		if (retries == -1) return -1;
352878f2aa30SNiels Provos 		if (retries > 255) retries = 255;
352978f2aa30SNiels Provos 		if (!(flags & DNS_OPTION_MISC)) return 0;
353078f2aa30SNiels Provos 		log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
3531e688a88aSNick Mathewson 		base->global_max_retransmits = retries;
353272bafc17SNick Mathewson 	} else if (str_matches_option(option, "randomize-case:")) {
3533dd731685SNick Mathewson 		int randcase = strtoint(val);
3534*c2972453Sayuseleznev 		if (randcase == -1) return -1;
3535dd731685SNick Mathewson 		if (!(flags & DNS_OPTION_MISC)) return 0;
3536dd731685SNick Mathewson 		base->global_randomize_case = randcase;
353772bafc17SNick Mathewson 	} else if (str_matches_option(option, "bind-to:")) {
353877c80b8dSNick Mathewson 		/* XXX This only applies to successive nameservers, not
353977c80b8dSNick Mathewson 		 * to already-configured ones.	We might want to fix that. */
354077c80b8dSNick Mathewson 		int len = sizeof(base->global_outgoing_address);
354177c80b8dSNick Mathewson 		if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
354277c80b8dSNick Mathewson 		if (evutil_parse_sockaddr_port(val,
354377c80b8dSNick Mathewson 			(struct sockaddr*)&base->global_outgoing_address, &len))
354477c80b8dSNick Mathewson 			return -1;
354577c80b8dSNick Mathewson 		base->global_outgoing_addrlen = len;
35461e56a32dSNick Mathewson 	} else if (str_matches_option(option, "initial-probe-timeout:")) {
35471e56a32dSNick Mathewson 		struct timeval tv;
3548bdbc823fSXiao Bao Clark 		if (evdns_strtotimeval(val, &tv) == -1) return -1;
35491e56a32dSNick Mathewson 		if (tv.tv_sec > 3600)
35501e56a32dSNick Mathewson 			tv.tv_sec = 3600;
35511e56a32dSNick Mathewson 		if (!(flags & DNS_OPTION_MISC)) return 0;
35521e56a32dSNick Mathewson 		log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
35531e56a32dSNick Mathewson 		    val);
35541e56a32dSNick Mathewson 		memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
35551e56a32dSNick Mathewson 		    sizeof(tv));
3556546a366cSAzat Khuzhin 	} else if (str_matches_option(option, "so-rcvbuf:")) {
3557546a366cSAzat Khuzhin 		int buf = strtoint(val);
3558*c2972453Sayuseleznev 		if (buf == -1) return -1;
3559546a366cSAzat Khuzhin 		if (!(flags & DNS_OPTION_MISC)) return 0;
3560546a366cSAzat Khuzhin 		log(EVDNS_LOG_DEBUG, "Setting SO_RCVBUF to %s", val);
3561546a366cSAzat Khuzhin 		base->so_rcvbuf = buf;
3562546a366cSAzat Khuzhin 	} else if (str_matches_option(option, "so-sndbuf:")) {
3563546a366cSAzat Khuzhin 		int buf = strtoint(val);
3564*c2972453Sayuseleznev 		if (buf == -1) return -1;
3565546a366cSAzat Khuzhin 		if (!(flags & DNS_OPTION_MISC)) return 0;
3566546a366cSAzat Khuzhin 		log(EVDNS_LOG_DEBUG, "Setting SO_SNDBUF to %s", val);
3567546a366cSAzat Khuzhin 		base->so_sndbuf = buf;
356878f2aa30SNiels Provos 	}
356978f2aa30SNiels Provos 	return 0;
357078f2aa30SNiels Provos }
357178f2aa30SNiels Provos 
3572e688a88aSNick Mathewson int
evdns_set_option(const char * option,const char * val,int flags)3573e688a88aSNick Mathewson evdns_set_option(const char *option, const char *val, int flags)
3574e688a88aSNick Mathewson {
3575fc83ca3cSNick Mathewson 	if (!current_base)
3576fc83ca3cSNick Mathewson 		current_base = evdns_base_new(NULL, 0);
35771dd7e6dcSNick Mathewson 	return evdns_base_set_option(current_base, option, val);
3578e688a88aSNick Mathewson }
3579e688a88aSNick Mathewson 
3580cca7249eSNiels Provos static void
resolv_conf_parse_line(struct evdns_base * base,char * const start,int flags)3581e688a88aSNick Mathewson resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
3582cca7249eSNiels Provos 	char *strtok_state;
3583cca7249eSNiels Provos 	static const char *const delims = " \t";
3584cca7249eSNiels Provos #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
3585cca7249eSNiels Provos 
3586327165b3SNick Mathewson 
3587cca7249eSNiels Provos 	char *const first_token = strtok_r(start, delims, &strtok_state);
3588327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3589cca7249eSNiels Provos 	if (!first_token) return;
3590cca7249eSNiels Provos 
359178f2aa30SNiels Provos 	if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
3592cca7249eSNiels Provos 		const char *const nameserver = NEXT_TOKEN;
3593cca7249eSNiels Provos 
35946c7c5799SYasuoka Masahiko 		if (nameserver)
3595135591aeSNick Mathewson 			evdns_base_nameserver_ip_add(base, nameserver);
3596cca7249eSNiels Provos 	} else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
3597cca7249eSNiels Provos 		const char *const domain = NEXT_TOKEN;
3598cca7249eSNiels Provos 		if (domain) {
3599e688a88aSNick Mathewson 			search_postfix_clear(base);
3600e688a88aSNick Mathewson 			search_postfix_add(base, domain);
3601cca7249eSNiels Provos 		}
3602cca7249eSNiels Provos 	} else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
3603cca7249eSNiels Provos 		const char *domain;
3604e688a88aSNick Mathewson 		search_postfix_clear(base);
3605cca7249eSNiels Provos 
3606cca7249eSNiels Provos 		while ((domain = NEXT_TOKEN)) {
3607e688a88aSNick Mathewson 			search_postfix_add(base, domain);
3608cca7249eSNiels Provos 		}
3609e688a88aSNick Mathewson 		search_reverse(base);
3610cca7249eSNiels Provos 	} else if (!strcmp(first_token, "options")) {
3611cca7249eSNiels Provos 		const char *option;
3612cca7249eSNiels Provos 		while ((option = NEXT_TOKEN)) {
361378f2aa30SNiels Provos 			const char *val = strchr(option, ':');
36141dd7e6dcSNick Mathewson 			evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
3615cca7249eSNiels Provos 		}
3616cca7249eSNiels Provos 	}
3617cca7249eSNiels Provos #undef NEXT_TOKEN
3618cca7249eSNiels Provos }
3619cca7249eSNiels Provos 
36207c6df310SNiels Provos /* exported function */
36217c6df310SNiels Provos /* returns: */
36227c6df310SNiels Provos /*   0 no errors */
36237c6df310SNiels Provos /*   1 failed to open file */
36247c6df310SNiels Provos /*   2 failed to stat file */
36257c6df310SNiels Provos /*   3 file too large */
36267c6df310SNiels Provos /*   4 out of memory */
36277c6df310SNiels Provos /*   5 short read from file */
3628cca7249eSNiels Provos int
evdns_base_resolv_conf_parse(struct evdns_base * base,int flags,const char * const filename)3629e688a88aSNick Mathewson evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
3630327165b3SNick Mathewson 	int res;
3631327165b3SNick Mathewson 	EVDNS_LOCK(base);
3632327165b3SNick Mathewson 	res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
3633327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
3634327165b3SNick Mathewson 	return res;
3635327165b3SNick Mathewson }
3636327165b3SNick Mathewson 
363766c02c78SNick Mathewson static char *
evdns_get_default_hosts_filename(void)363866c02c78SNick Mathewson evdns_get_default_hosts_filename(void)
363966c02c78SNick Mathewson {
36409f560bfaSNick Mathewson #ifdef _WIN32
364166c02c78SNick Mathewson 	/* Windows is a little coy about where it puts its configuration
364266c02c78SNick Mathewson 	 * files.  Sure, they're _usually_ in C:\windows\system32, but
364366c02c78SNick Mathewson 	 * there's no reason in principle they couldn't be in
364466c02c78SNick Mathewson 	 * W:\hoboken chicken emergency\
364566c02c78SNick Mathewson 	 */
364666c02c78SNick Mathewson 	char path[MAX_PATH+1];
364766c02c78SNick Mathewson 	static const char hostfile[] = "\\drivers\\etc\\hosts";
364866c02c78SNick Mathewson 	char *path_out;
3649545a6114SNick Mathewson 	size_t len_out;
365066c02c78SNick Mathewson 
3651a7a94310SNick Mathewson 	if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
365266c02c78SNick Mathewson 		return NULL;
3653d0dc861bSVilmos Nebehaj 	len_out = strlen(path)+strlen(hostfile)+1;
3654d0dc861bSVilmos Nebehaj 	path_out = mm_malloc(len_out);
365566c02c78SNick Mathewson 	evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
365666c02c78SNick Mathewson 	return path_out;
365766c02c78SNick Mathewson #else
365866c02c78SNick Mathewson 	return mm_strdup("/etc/hosts");
365966c02c78SNick Mathewson #endif
366066c02c78SNick Mathewson }
366166c02c78SNick Mathewson 
3662327165b3SNick Mathewson static int
evdns_base_resolv_conf_parse_impl(struct evdns_base * base,int flags,const char * const filename)3663327165b3SNick Mathewson evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
366472dd6667SNick Mathewson 	size_t n;
366572dd6667SNick Mathewson 	char *resolv;
3666cca7249eSNiels Provos 	char *start;
3667cca7249eSNiels Provos 	int err = 0;
366858e81106SAzat Khuzhin 	int add_default;
3669cca7249eSNiels Provos 
3670fe1dfe0fSNiels Provos 	log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
3671cca7249eSNiels Provos 
367258e81106SAzat Khuzhin 	add_default = flags & DNS_OPTION_NAMESERVERS;
367358e81106SAzat Khuzhin 	if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
367458e81106SAzat Khuzhin 		add_default = 0;
367558e81106SAzat Khuzhin 
367672dd6667SNick Mathewson 	if (flags & DNS_OPTION_HOSTSFILE) {
367766c02c78SNick Mathewson 		char *fname = evdns_get_default_hosts_filename();
367866c02c78SNick Mathewson 		evdns_base_load_hosts(base, fname);
367966c02c78SNick Mathewson 		if (fname)
368066c02c78SNick Mathewson 			mm_free(fname);
368172dd6667SNick Mathewson 	}
368272dd6667SNick Mathewson 
36830033f5ccSBogdan Harjoc 	if (!filename) {
36840033f5ccSBogdan Harjoc 		evdns_resolv_set_defaults(base, flags);
36850033f5ccSBogdan Harjoc 		return 1;
36860033f5ccSBogdan Harjoc 	}
36870033f5ccSBogdan Harjoc 
36888ac3c4c2SNick Mathewson 	if ((err = evutil_read_file_(filename, &resolv, &n, 0)) < 0) {
368972dd6667SNick Mathewson 		if (err == -1) {
369072dd6667SNick Mathewson 			/* No file. */
3691e688a88aSNick Mathewson 			evdns_resolv_set_defaults(base, flags);
36923882669dSNiels Provos 			return 1;
369372dd6667SNick Mathewson 		} else {
369472dd6667SNick Mathewson 			return 2;
369572dd6667SNick Mathewson 		}
3696cca7249eSNiels Provos 	}
3697cca7249eSNiels Provos 
369872dd6667SNick Mathewson 	start = resolv;
3699cca7249eSNiels Provos 	for (;;) {
3700cca7249eSNiels Provos 		char *const newline = strchr(start, '\n');
3701cca7249eSNiels Provos 		if (!newline) {
3702e688a88aSNick Mathewson 			resolv_conf_parse_line(base, start, flags);
3703cca7249eSNiels Provos 			break;
3704cca7249eSNiels Provos 		} else {
3705cca7249eSNiels Provos 			*newline = 0;
3706e688a88aSNick Mathewson 			resolv_conf_parse_line(base, start, flags);
3707cca7249eSNiels Provos 			start = newline + 1;
3708cca7249eSNiels Provos 		}
3709cca7249eSNiels Provos 	}
3710cca7249eSNiels Provos 
371158e81106SAzat Khuzhin 	if (!base->server_head && add_default) {
37127c6df310SNiels Provos 		/* no nameservers were configured. */
3713e688a88aSNick Mathewson 		evdns_base_nameserver_ip_add(base, "127.0.0.1");
371478f2aa30SNiels Provos 		err = 6;
3715cca7249eSNiels Provos 	}
3716e688a88aSNick Mathewson 	if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
3717e688a88aSNick Mathewson 		search_set_from_hostname(base);
3718cca7249eSNiels Provos 	}
3719cca7249eSNiels Provos 
372049868b61SNick Mathewson 	mm_free(resolv);
3721cca7249eSNiels Provos 	return err;
3722cca7249eSNiels Provos }
3723cca7249eSNiels Provos 
3724e688a88aSNick Mathewson int
evdns_resolv_conf_parse(int flags,const char * const filename)3725e688a88aSNick Mathewson evdns_resolv_conf_parse(int flags, const char *const filename) {
3726fc83ca3cSNick Mathewson 	if (!current_base)
3727fc83ca3cSNick Mathewson 		current_base = evdns_base_new(NULL, 0);
3728e688a88aSNick Mathewson 	return evdns_base_resolv_conf_parse(current_base, flags, filename);
3729e688a88aSNick Mathewson }
373072dd6667SNick Mathewson 
373172dd6667SNick Mathewson 
37329f560bfaSNick Mathewson #ifdef _WIN32
37337c6df310SNiels Provos /* Add multiple nameservers from a space-or-comma-separated list. */
3734cca7249eSNiels Provos static int
evdns_nameserver_ip_add_line(struct evdns_base * base,const char * ips)3735e688a88aSNick Mathewson evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
3736cca7249eSNiels Provos 	const char *addr;
3737cca7249eSNiels Provos 	char *buf;
3738cca7249eSNiels Provos 	int r;
3739327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3740cca7249eSNiels Provos 	while (*ips) {
3741cd731b77SNick Mathewson 		while (isspace(*ips) || *ips == ',' || *ips == '\t')
3742cca7249eSNiels Provos 			++ips;
3743cca7249eSNiels Provos 		addr = ips;
3744c6f4dc98SNick Mathewson 		while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
3745c6f4dc98SNick Mathewson 		    *ips=='[' || *ips==']')
3746cca7249eSNiels Provos 			++ips;
374749868b61SNick Mathewson 		buf = mm_malloc(ips-addr+1);
3748cca7249eSNiels Provos 		if (!buf) return 4;
3749cca7249eSNiels Provos 		memcpy(buf, addr, ips-addr);
3750cca7249eSNiels Provos 		buf[ips-addr] = '\0';
375152161b47SNiels Provos 		r = evdns_base_nameserver_ip_add(base, buf);
375249868b61SNick Mathewson 		mm_free(buf);
3753cca7249eSNiels Provos 		if (r) return r;
3754cca7249eSNiels Provos 	}
3755cca7249eSNiels Provos 	return 0;
3756cca7249eSNiels Provos }
3757cca7249eSNiels Provos 
3758fe1dfe0fSNiels Provos typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
3759fe1dfe0fSNiels Provos 
37607c6df310SNiels Provos /* Use the windows GetNetworkParams interface in iphlpapi.dll to */
37617c6df310SNiels Provos /* figure out what our nameservers are. */
3762cca7249eSNiels Provos static int
load_nameservers_with_getnetworkparams(struct evdns_base * base)3763e688a88aSNick Mathewson load_nameservers_with_getnetworkparams(struct evdns_base *base)
3764cca7249eSNiels Provos {
37657c6df310SNiels Provos 	/* Based on MSDN examples and inspection of  c-ares code. */
3766cca7249eSNiels Provos 	FIXED_INFO *fixed;
3767cca7249eSNiels Provos 	HMODULE handle = 0;
3768cca7249eSNiels Provos 	ULONG size = sizeof(FIXED_INFO);
3769cca7249eSNiels Provos 	void *buf = NULL;
3770cca7249eSNiels Provos 	int status = 0, r, added_any;
3771cca7249eSNiels Provos 	IP_ADDR_STRING *ns;
3772fe1dfe0fSNiels Provos 	GetNetworkParams_fn_t fn;
3773cca7249eSNiels Provos 
37741ad03264SNick Mathewson 	ASSERT_LOCKED(base);
37758ac3c4c2SNick Mathewson 	if (!(handle = evutil_load_windows_system_library_(
3776d49b5e33SNick Mathewson 			TEXT("iphlpapi.dll")))) {
3777fe1dfe0fSNiels Provos 		log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
3778fe1dfe0fSNiels Provos 		status = -1;
3779cca7249eSNiels Provos 		goto done;
3780fe1dfe0fSNiels Provos 	}
37815fa30d2bSNick Mathewson 	if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
3782fe1dfe0fSNiels Provos 		log(EVDNS_LOG_WARN, "Could not get address of function.");
3783fe1dfe0fSNiels Provos 		status = -1;
3784cca7249eSNiels Provos 		goto done;
3785fe1dfe0fSNiels Provos 	}
3786cca7249eSNiels Provos 
378749868b61SNick Mathewson 	buf = mm_malloc(size);
3788cca7249eSNiels Provos 	if (!buf) { status = 4; goto done; }
3789cca7249eSNiels Provos 	fixed = buf;
3790cca7249eSNiels Provos 	r = fn(fixed, &size);
3791cca7249eSNiels Provos 	if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
3792cca7249eSNiels Provos 		status = -1;
3793cca7249eSNiels Provos 		goto done;
3794cca7249eSNiels Provos 	}
3795cca7249eSNiels Provos 	if (r != ERROR_SUCCESS) {
379649868b61SNick Mathewson 		mm_free(buf);
379749868b61SNick Mathewson 		buf = mm_malloc(size);
3798cca7249eSNiels Provos 		if (!buf) { status = 4; goto done; }
3799cca7249eSNiels Provos 		fixed = buf;
3800cca7249eSNiels Provos 		r = fn(fixed, &size);
3801fe1dfe0fSNiels Provos 		if (r != ERROR_SUCCESS) {
3802fe1dfe0fSNiels Provos 			log(EVDNS_LOG_DEBUG, "fn() failed.");
3803fe1dfe0fSNiels Provos 			status = -1;
3804fe1dfe0fSNiels Provos 			goto done;
3805fe1dfe0fSNiels Provos 		}
3806cca7249eSNiels Provos 	}
3807cca7249eSNiels Provos 
38082e36dbe1SNick Mathewson 	EVUTIL_ASSERT(fixed);
3809cca7249eSNiels Provos 	added_any = 0;
3810fe1dfe0fSNiels Provos 	ns = &(fixed->DnsServerList);
3811cca7249eSNiels Provos 	while (ns) {
3812e688a88aSNick Mathewson 		r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
3813fe1dfe0fSNiels Provos 		if (r) {
3814fe1dfe0fSNiels Provos 			log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
3815fe1dfe0fSNiels Provos 				(ns->IpAddress.String),(int)GetLastError());
3816fe1dfe0fSNiels Provos 			status = r;
3817fe1dfe0fSNiels Provos 		} else {
3818c6f4dc98SNick Mathewson 			++added_any;
3819e3fd294aSNick Mathewson 			log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
3820cca7249eSNiels Provos 		}
3821cca7249eSNiels Provos 
3822fe1dfe0fSNiels Provos 		ns = ns->Next;
3823fe1dfe0fSNiels Provos 	}
3824fe1dfe0fSNiels Provos 
3825fe1dfe0fSNiels Provos 	if (!added_any) {
3826fe1dfe0fSNiels Provos 		log(EVDNS_LOG_DEBUG, "No nameservers added.");
3827c6f4dc98SNick Mathewson 		if (status == 0)
3828cca7249eSNiels Provos 			status = -1;
3829c6f4dc98SNick Mathewson 	} else {
3830c6f4dc98SNick Mathewson 		status = 0;
3831fe1dfe0fSNiels Provos 	}
3832cca7249eSNiels Provos 
3833cca7249eSNiels Provos  done:
3834cca7249eSNiels Provos 	if (buf)
383549868b61SNick Mathewson 		mm_free(buf);
3836cca7249eSNiels Provos 	if (handle)
3837cca7249eSNiels Provos 		FreeLibrary(handle);
3838cca7249eSNiels Provos 	return status;
3839cca7249eSNiels Provos }
3840cca7249eSNiels Provos 
3841cca7249eSNiels Provos static int
config_nameserver_from_reg_key(struct evdns_base * base,HKEY key,const TCHAR * subkey)3842899b0a39SNick Mathewson config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
3843cca7249eSNiels Provos {
3844cca7249eSNiels Provos 	char *buf;
3845cca7249eSNiels Provos 	DWORD bufsz = 0, type = 0;
3846cca7249eSNiels Provos 	int status = 0;
3847cca7249eSNiels Provos 
3848327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3849899b0a39SNick Mathewson 	if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
3850cca7249eSNiels Provos 	    != ERROR_MORE_DATA)
3851cca7249eSNiels Provos 		return -1;
385249868b61SNick Mathewson 	if (!(buf = mm_malloc(bufsz)))
3853cca7249eSNiels Provos 		return -1;
3854cca7249eSNiels Provos 
3855899b0a39SNick Mathewson 	if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
3856cca7249eSNiels Provos 	    == ERROR_SUCCESS && bufsz > 1) {
3857e688a88aSNick Mathewson 		status = evdns_nameserver_ip_add_line(base,buf);
3858cca7249eSNiels Provos 	}
3859cca7249eSNiels Provos 
386049868b61SNick Mathewson 	mm_free(buf);
3861cca7249eSNiels Provos 	return status;
3862cca7249eSNiels Provos }
3863cca7249eSNiels Provos 
3864899b0a39SNick Mathewson #define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
3865899b0a39SNick Mathewson #define WIN_NS_9X_KEY  SERVICES_KEY TEXT("VxD\\MSTCP")
3866899b0a39SNick Mathewson #define WIN_NS_NT_KEY  SERVICES_KEY TEXT("Tcpip\\Parameters")
3867fe1dfe0fSNiels Provos 
3868cca7249eSNiels Provos static int
load_nameservers_from_registry(struct evdns_base * base)3869e688a88aSNick Mathewson load_nameservers_from_registry(struct evdns_base *base)
3870cca7249eSNiels Provos {
3871cca7249eSNiels Provos 	int found = 0;
3872fe1dfe0fSNiels Provos 	int r;
3873cca7249eSNiels Provos #define TRY(k, name) \
3874899b0a39SNick Mathewson 	if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
3875fe1dfe0fSNiels Provos 		log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
3876cca7249eSNiels Provos 		found = 1;						\
3877fe1dfe0fSNiels Provos 	} else if (!found) {						\
3878fe1dfe0fSNiels Provos 		log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
3879fe1dfe0fSNiels Provos 		    #k,#name);						\
3880cca7249eSNiels Provos 	}
3881cca7249eSNiels Provos 
3882327165b3SNick Mathewson 	ASSERT_LOCKED(base);
3883327165b3SNick Mathewson 
3884fe1dfe0fSNiels Provos 	if (((int)GetVersion()) > 0) { /* NT */
3885cca7249eSNiels Provos 		HKEY nt_key = 0, interfaces_key = 0;
3886cca7249eSNiels Provos 
3887899b0a39SNick Mathewson 		if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
3888fe1dfe0fSNiels Provos 				 KEY_READ, &nt_key) != ERROR_SUCCESS) {
3889fe1dfe0fSNiels Provos 			log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
3890cca7249eSNiels Provos 			return -1;
3891fe1dfe0fSNiels Provos 		}
3892899b0a39SNick Mathewson 		r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
3893fe1dfe0fSNiels Provos 			     KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
3894cca7249eSNiels Provos 			     &interfaces_key);
3895fe1dfe0fSNiels Provos 		if (r != ERROR_SUCCESS) {
3896fe1dfe0fSNiels Provos 			log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
3897fe1dfe0fSNiels Provos 			return -1;
3898fe1dfe0fSNiels Provos 		}
3899fe1dfe0fSNiels Provos 		TRY(nt_key, "NameServer");
3900fe1dfe0fSNiels Provos 		TRY(nt_key, "DhcpNameServer");
3901fe1dfe0fSNiels Provos 		TRY(interfaces_key, "NameServer");
3902fe1dfe0fSNiels Provos 		TRY(interfaces_key, "DhcpNameServer");
3903cca7249eSNiels Provos 		RegCloseKey(interfaces_key);
3904cca7249eSNiels Provos 		RegCloseKey(nt_key);
3905cca7249eSNiels Provos 	} else {
3906cca7249eSNiels Provos 		HKEY win_key = 0;
3907899b0a39SNick Mathewson 		if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
3908fe1dfe0fSNiels Provos 				 KEY_READ, &win_key) != ERROR_SUCCESS) {
3909fe1dfe0fSNiels Provos 			log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
3910cca7249eSNiels Provos 			return -1;
3911fe1dfe0fSNiels Provos 		}
3912fe1dfe0fSNiels Provos 		TRY(win_key, "NameServer");
3913cca7249eSNiels Provos 		RegCloseKey(win_key);
3914cca7249eSNiels Provos 	}
3915fe1dfe0fSNiels Provos 
3916fe1dfe0fSNiels Provos 	if (found == 0) {
3917fe1dfe0fSNiels Provos 		log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
3918fe1dfe0fSNiels Provos 	}
3919fe1dfe0fSNiels Provos 
3920cca7249eSNiels Provos 	return found ? 0 : -1;
3921cca7249eSNiels Provos #undef TRY
3922cca7249eSNiels Provos }
3923cca7249eSNiels Provos 
3924670658ebSNick Mathewson int
evdns_base_config_windows_nameservers(struct evdns_base * base)3925670658ebSNick Mathewson evdns_base_config_windows_nameservers(struct evdns_base *base)
3926cca7249eSNiels Provos {
3927670658ebSNick Mathewson 	int r;
392866c02c78SNick Mathewson 	char *fname;
3929670658ebSNick Mathewson 	if (base == NULL)
3930670658ebSNick Mathewson 		base = current_base;
3931670658ebSNick Mathewson 	if (base == NULL)
3932670658ebSNick Mathewson 		return -1;
3933670658ebSNick Mathewson 	EVDNS_LOCK(base);
3934a0b247cdSVilmos Nebehaj 	fname = evdns_get_default_hosts_filename();
3935a0b247cdSVilmos Nebehaj 	log(EVDNS_LOG_DEBUG, "Loading hosts entries from %s", fname);
3936a0b247cdSVilmos Nebehaj 	evdns_base_load_hosts(base, fname);
3937a0b247cdSVilmos Nebehaj 	if (fname)
3938a0b247cdSVilmos Nebehaj 		mm_free(fname);
3939a0b247cdSVilmos Nebehaj 
3940c51bb3c3Sunknown 	if (load_nameservers_with_getnetworkparams(base) == 0) {
3941c51bb3c3Sunknown 		EVDNS_UNLOCK(base);
3942cca7249eSNiels Provos 		return 0;
3943c51bb3c3Sunknown 	}
3944670658ebSNick Mathewson 	r = load_nameservers_from_registry(base);
394566c02c78SNick Mathewson 
3946670658ebSNick Mathewson 	EVDNS_UNLOCK(base);
3947670658ebSNick Mathewson 	return r;
3948670658ebSNick Mathewson }
3949670658ebSNick Mathewson 
3950670658ebSNick Mathewson int
evdns_config_windows_nameservers(void)3951670658ebSNick Mathewson evdns_config_windows_nameservers(void)
3952670658ebSNick Mathewson {
3953670658ebSNick Mathewson 	if (!current_base) {
3954670658ebSNick Mathewson 		current_base = evdns_base_new(NULL, 1);
3955670658ebSNick Mathewson 		return current_base == NULL ? -1 : 0;
3956670658ebSNick Mathewson 	} else {
3957670658ebSNick Mathewson 		return evdns_base_config_windows_nameservers(current_base);
3958670658ebSNick Mathewson 	}
3959cca7249eSNiels Provos }
3960cca7249eSNiels Provos #endif
3961e9c1e3f7SNiels Provos 
3962e688a88aSNick Mathewson struct evdns_base *
evdns_base_new(struct event_base * event_base,int flags)39636b7fa620SAzat Khuzhin evdns_base_new(struct event_base *event_base, int flags)
3964e688a88aSNick Mathewson {
3965e688a88aSNick Mathewson 	struct evdns_base *base;
39660b9eb1bfSNick Mathewson 
3967d4de062eSNick Mathewson 	if (evutil_secure_rng_init() < 0) {
3968d4de062eSNick Mathewson 		log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
3969d4de062eSNick Mathewson 		    "DNS can't run.");
3970d4de062eSNick Mathewson 		return NULL;
3971d4de062eSNick Mathewson 	}
3972d4de062eSNick Mathewson 
397386f57420SNick Mathewson 	/* Give the evutil library a hook into its evdns-enabled
397486f57420SNick Mathewson 	 * functionality.  We can't just call evdns_getaddrinfo directly or
397586f57420SNick Mathewson 	 * else libevent-core will depend on libevent-extras. */
39768ac3c4c2SNick Mathewson 	evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo);
39778cbe65d5SAzat Khuzhin 	evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel);
39780b9eb1bfSNick Mathewson 
397949868b61SNick Mathewson 	base = mm_malloc(sizeof(struct evdns_base));
3980e688a88aSNick Mathewson 	if (base == NULL)
3981e688a88aSNick Mathewson 		return (NULL);
3982e688a88aSNick Mathewson 	memset(base, 0, sizeof(struct evdns_base));
398349868b61SNick Mathewson 	base->req_waiting_head = NULL;
398449868b61SNick Mathewson 
3985347952ffSNick Mathewson 	EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
3986327165b3SNick Mathewson 	EVDNS_LOCK(base);
3987327165b3SNick Mathewson 
398849868b61SNick Mathewson 	/* Set max requests inflight and allocate req_heads. */
398949868b61SNick Mathewson 	base->req_heads = NULL;
3990327165b3SNick Mathewson 
399149868b61SNick Mathewson 	evdns_base_set_max_requests_inflight(base, 64);
399249868b61SNick Mathewson 
3993e688a88aSNick Mathewson 	base->server_head = NULL;
3994e688a88aSNick Mathewson 	base->event_base = event_base;
3995e688a88aSNick Mathewson 	base->global_good_nameservers = base->global_requests_inflight =
3996e688a88aSNick Mathewson 		base->global_requests_waiting = 0;
399749868b61SNick Mathewson 
3998e688a88aSNick Mathewson 	base->global_timeout.tv_sec = 5;
3999e688a88aSNick Mathewson 	base->global_timeout.tv_usec = 0;
4000e688a88aSNick Mathewson 	base->global_max_reissues = 1;
4001e688a88aSNick Mathewson 	base->global_max_retransmits = 3;
4002e688a88aSNick Mathewson 	base->global_max_nameserver_timeout = 3;
4003e688a88aSNick Mathewson 	base->global_search_state = NULL;
4004dd731685SNick Mathewson 	base->global_randomize_case = 1;
400586f57420SNick Mathewson 	base->global_getaddrinfo_allow_skew.tv_sec = 3;
400686f57420SNick Mathewson 	base->global_getaddrinfo_allow_skew.tv_usec = 0;
40071e56a32dSNick Mathewson 	base->global_nameserver_probe_initial_timeout.tv_sec = 10;
40081e56a32dSNick Mathewson 	base->global_nameserver_probe_initial_timeout.tv_usec = 0;
4009327165b3SNick Mathewson 
401072dd6667SNick Mathewson 	TAILQ_INIT(&base->hostsdb);
401172dd6667SNick Mathewson 
401258e81106SAzat Khuzhin #define EVDNS_BASE_ALL_FLAGS ( \
401358e81106SAzat Khuzhin 	EVDNS_BASE_INITIALIZE_NAMESERVERS | \
401458e81106SAzat Khuzhin 	EVDNS_BASE_DISABLE_WHEN_INACTIVE  | \
401558e81106SAzat Khuzhin 	EVDNS_BASE_NAMESERVERS_NO_DEFAULT | \
401658e81106SAzat Khuzhin 	0)
401758e81106SAzat Khuzhin 
40186b7fa620SAzat Khuzhin 	if (flags & ~EVDNS_BASE_ALL_FLAGS) {
40196b7fa620SAzat Khuzhin 		flags = EVDNS_BASE_INITIALIZE_NAMESERVERS;
40206b7fa620SAzat Khuzhin 		log(EVDNS_LOG_WARN,
40216b7fa620SAzat Khuzhin 		    "Unrecognized flag passed to evdns_base_new(). Assuming "
40226b7fa620SAzat Khuzhin 		    "you meant EVDNS_BASE_INITIALIZE_NAMESERVERS.");
40236b7fa620SAzat Khuzhin 	}
40246b7fa620SAzat Khuzhin #undef EVDNS_BASE_ALL_FLAGS
40256b7fa620SAzat Khuzhin 
40266b7fa620SAzat Khuzhin 	if (flags & EVDNS_BASE_INITIALIZE_NAMESERVERS) {
4027e688a88aSNick Mathewson 		int r;
402858e81106SAzat Khuzhin 		int opts = DNS_OPTIONS_ALL;
402958e81106SAzat Khuzhin 		if (flags & EVDNS_BASE_NAMESERVERS_NO_DEFAULT) {
403058e81106SAzat Khuzhin 			opts |= DNS_OPTION_NAMESERVERS_NO_DEFAULT;
403158e81106SAzat Khuzhin 		}
403258e81106SAzat Khuzhin 
40339f560bfaSNick Mathewson #ifdef _WIN32
4034670658ebSNick Mathewson 		r = evdns_base_config_windows_nameservers(base);
4035e688a88aSNick Mathewson #else
403658e81106SAzat Khuzhin 		r = evdns_base_resolv_conf_parse(base, opts, "/etc/resolv.conf");
4037e688a88aSNick Mathewson #endif
4038fc51bf2cSAzat Khuzhin 		if (r) {
403912199fa7SNick Mathewson 			evdns_base_free_and_unlock(base, 0);
404012199fa7SNick Mathewson 			return NULL;
4041e688a88aSNick Mathewson 		}
4042e688a88aSNick Mathewson 	}
40436b7fa620SAzat Khuzhin 	if (flags & EVDNS_BASE_DISABLE_WHEN_INACTIVE) {
40446b7fa620SAzat Khuzhin 		base->disable_when_inactive = 1;
40456b7fa620SAzat Khuzhin 	}
40466b7fa620SAzat Khuzhin 
4047327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
4048e688a88aSNick Mathewson 	return base;
4049e688a88aSNick Mathewson }
4050e688a88aSNick Mathewson 
4051e9c1e3f7SNiels Provos int
evdns_init(void)40525baf8ecfSNiels Provos evdns_init(void)
4053e9c1e3f7SNiels Provos {
4054e688a88aSNick Mathewson 	struct evdns_base *base = evdns_base_new(NULL, 1);
4055e688a88aSNick Mathewson 	if (base) {
4056e688a88aSNick Mathewson 		current_base = base;
4057e688a88aSNick Mathewson 		return 0;
4058e688a88aSNick Mathewson 	} else {
4059e688a88aSNick Mathewson 		return -1;
4060e688a88aSNick Mathewson 	}
4061e9c1e3f7SNiels Provos }
4062fe1dfe0fSNiels Provos 
4063fe1dfe0fSNiels Provos const char *
evdns_err_to_string(int err)4064fe1dfe0fSNiels Provos evdns_err_to_string(int err)
4065fe1dfe0fSNiels Provos {
4066fe1dfe0fSNiels Provos     switch (err) {
4067fe1dfe0fSNiels Provos 	case DNS_ERR_NONE: return "no error";
4068fe1dfe0fSNiels Provos 	case DNS_ERR_FORMAT: return "misformatted query";
4069fe1dfe0fSNiels Provos 	case DNS_ERR_SERVERFAILED: return "server failed";
4070fe1dfe0fSNiels Provos 	case DNS_ERR_NOTEXIST: return "name does not exist";
4071fe1dfe0fSNiels Provos 	case DNS_ERR_NOTIMPL: return "query not implemented";
4072fe1dfe0fSNiels Provos 	case DNS_ERR_REFUSED: return "refused";
4073fe1dfe0fSNiels Provos 
4074fe1dfe0fSNiels Provos 	case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
4075fe1dfe0fSNiels Provos 	case DNS_ERR_UNKNOWN: return "unknown";
4076fe1dfe0fSNiels Provos 	case DNS_ERR_TIMEOUT: return "request timed out";
4077fe1dfe0fSNiels Provos 	case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
4078d2e9caa6SNick Mathewson 	case DNS_ERR_CANCEL: return "dns request canceled";
407994fba5b9SLeonid Evdokimov 	case DNS_ERR_NODATA: return "no records in the reply";
4080fe1dfe0fSNiels Provos 	default: return "[Unknown error code]";
4081fe1dfe0fSNiels Provos     }
4082fe1dfe0fSNiels Provos }
4083fe1dfe0fSNiels Provos 
408412199fa7SNick Mathewson static void
evdns_nameserver_free(struct nameserver * server)4085a19b4a05SNick Mathewson evdns_nameserver_free(struct nameserver *server)
4086a19b4a05SNick Mathewson {
4087a19b4a05SNick Mathewson 	if (server->socket >= 0)
4088899c1dccSSebastian Sjöberg 		evutil_closesocket(server->socket);
4089a19b4a05SNick Mathewson 	(void) event_del(&server->event);
4090a19b4a05SNick Mathewson 	event_debug_unassign(&server->event);
4091a19b4a05SNick Mathewson 	if (server->state == 0)
4092a19b4a05SNick Mathewson 		(void) event_del(&server->timeout_event);
4093e8fe749dSNick Mathewson 	if (server->probe_request) {
4094e8fe749dSNick Mathewson 		evdns_cancel_request(server->base, server->probe_request);
4095e8fe749dSNick Mathewson 		server->probe_request = NULL;
4096e8fe749dSNick Mathewson 	}
4097a19b4a05SNick Mathewson 	event_debug_unassign(&server->timeout_event);
4098a19b4a05SNick Mathewson 	mm_free(server);
4099a19b4a05SNick Mathewson }
4100a19b4a05SNick Mathewson 
4101a19b4a05SNick Mathewson static void
evdns_base_free_and_unlock(struct evdns_base * base,int fail_requests)410212199fa7SNick Mathewson evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
4103fe1dfe0fSNiels Provos {
4104fe1dfe0fSNiels Provos 	struct nameserver *server, *server_next;
4105fe1dfe0fSNiels Provos 	struct search_domain *dom, *dom_next;
410649868b61SNick Mathewson 	int i;
4107fe1dfe0fSNiels Provos 
410812199fa7SNick Mathewson 	/* Requires that we hold the lock. */
4109327165b3SNick Mathewson 
411012199fa7SNick Mathewson 	/* TODO(nickm) we might need to refcount here. */
4111327165b3SNick Mathewson 
41126f8e0e97Sayuseleznev 	while (base->req_waiting_head) {
41136f8e0e97Sayuseleznev 		if (fail_requests)
41146f8e0e97Sayuseleznev 			reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
41156f8e0e97Sayuseleznev 		request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
41166f8e0e97Sayuseleznev 	}
4117e8fe749dSNick Mathewson 	for (i = 0; i < base->n_req_heads; ++i) {
4118e8fe749dSNick Mathewson 		while (base->req_heads[i]) {
4119e8fe749dSNick Mathewson 			if (fail_requests)
4120e8fe749dSNick Mathewson 				reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
4121e8fe749dSNick Mathewson 			request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
4122e8fe749dSNick Mathewson 		}
4123e8fe749dSNick Mathewson 	}
41249f39c887SNick Mathewson 	base->global_requests_inflight = base->global_requests_waiting = 0;
41259f39c887SNick Mathewson 
412614f84bbdSAzat Khuzhin 	for (server = base->server_head; server; server = server_next) {
412714f84bbdSAzat Khuzhin 		server_next = server->next;
41284db15e09SAzat Khuzhin 		/** already done something before */
41294db15e09SAzat Khuzhin 		server->probe_request = NULL;
413014f84bbdSAzat Khuzhin 		evdns_nameserver_free(server);
413114f84bbdSAzat Khuzhin 		if (server_next == base->server_head)
413214f84bbdSAzat Khuzhin 			break;
413314f84bbdSAzat Khuzhin 	}
413414f84bbdSAzat Khuzhin 	base->server_head = NULL;
413514f84bbdSAzat Khuzhin 	base->global_good_nameservers = 0;
4136fe1dfe0fSNiels Provos 
4137e688a88aSNick Mathewson 	if (base->global_search_state) {
4138e688a88aSNick Mathewson 		for (dom = base->global_search_state->head; dom; dom = dom_next) {
4139fe1dfe0fSNiels Provos 			dom_next = dom->next;
414049868b61SNick Mathewson 			mm_free(dom);
4141fe1dfe0fSNiels Provos 		}
414249868b61SNick Mathewson 		mm_free(base->global_search_state);
4143e688a88aSNick Mathewson 		base->global_search_state = NULL;
4144e688a88aSNick Mathewson 	}
414572dd6667SNick Mathewson 
414672dd6667SNick Mathewson 	{
414772dd6667SNick Mathewson 		struct hosts_entry *victim;
414872dd6667SNick Mathewson 		while ((victim = TAILQ_FIRST(&base->hostsdb))) {
414972dd6667SNick Mathewson 			TAILQ_REMOVE(&base->hostsdb, victim, next);
415072dd6667SNick Mathewson 			mm_free(victim);
415172dd6667SNick Mathewson 		}
415272dd6667SNick Mathewson 	}
415372dd6667SNick Mathewson 
4154859af677SNick Mathewson 	mm_free(base->req_heads);
4155859af677SNick Mathewson 
4156327165b3SNick Mathewson 	EVDNS_UNLOCK(base);
4157347952ffSNick Mathewson 	EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
4158327165b3SNick Mathewson 
415949868b61SNick Mathewson 	mm_free(base);
4160e688a88aSNick Mathewson }
4161e688a88aSNick Mathewson 
4162e688a88aSNick Mathewson void
evdns_base_free(struct evdns_base * base,int fail_requests)416312199fa7SNick Mathewson evdns_base_free(struct evdns_base *base, int fail_requests)
416412199fa7SNick Mathewson {
416512199fa7SNick Mathewson 	EVDNS_LOCK(base);
416612199fa7SNick Mathewson 	evdns_base_free_and_unlock(base, fail_requests);
416712199fa7SNick Mathewson }
416812199fa7SNick Mathewson 
416912199fa7SNick Mathewson void
evdns_base_clear_host_addresses(struct evdns_base * base)417045eba6ffSNick Mathewson evdns_base_clear_host_addresses(struct evdns_base *base)
4171954d2f94SKuldeep Gupta {
4172954d2f94SKuldeep Gupta 	struct hosts_entry *victim;
4173e6b2a267SJoakim Soderberg 	EVDNS_LOCK(base);
4174954d2f94SKuldeep Gupta 	while ((victim = TAILQ_FIRST(&base->hostsdb))) {
4175954d2f94SKuldeep Gupta 		TAILQ_REMOVE(&base->hostsdb, victim, next);
4176954d2f94SKuldeep Gupta 		mm_free(victim);
4177954d2f94SKuldeep Gupta 	}
4178954d2f94SKuldeep Gupta 	EVDNS_UNLOCK(base);
4179954d2f94SKuldeep Gupta }
4180954d2f94SKuldeep Gupta 
4181954d2f94SKuldeep Gupta void
evdns_shutdown(int fail_requests)4182e688a88aSNick Mathewson evdns_shutdown(int fail_requests)
4183e688a88aSNick Mathewson {
4184e688a88aSNick Mathewson 	if (current_base) {
418512199fa7SNick Mathewson 		struct evdns_base *b = current_base;
4186e688a88aSNick Mathewson 		current_base = NULL;
418712199fa7SNick Mathewson 		evdns_base_free(b, fail_requests);
4188fe1dfe0fSNiels Provos 	}
4189fe1dfe0fSNiels Provos 	evdns_log_fn = NULL;
4190fe1dfe0fSNiels Provos }
4191fe1dfe0fSNiels Provos 
419272dd6667SNick Mathewson static int
evdns_base_parse_hosts_line(struct evdns_base * base,char * line)419372dd6667SNick Mathewson evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
419472dd6667SNick Mathewson {
419572dd6667SNick Mathewson 	char *strtok_state;
419672dd6667SNick Mathewson 	static const char *const delims = " \t";
419772dd6667SNick Mathewson 	char *const addr = strtok_r(line, delims, &strtok_state);
419872dd6667SNick Mathewson 	char *hostname, *hash;
419972dd6667SNick Mathewson 	struct sockaddr_storage ss;
420072dd6667SNick Mathewson 	int socklen = sizeof(ss);
420172dd6667SNick Mathewson 	ASSERT_LOCKED(base);
420272dd6667SNick Mathewson 
420372dd6667SNick Mathewson #define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
420472dd6667SNick Mathewson 
420572dd6667SNick Mathewson 	if (!addr || *addr == '#')
420672dd6667SNick Mathewson 		return 0;
420772dd6667SNick Mathewson 
420872dd6667SNick Mathewson 	memset(&ss, 0, sizeof(ss));
420972dd6667SNick Mathewson 	if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
421072dd6667SNick Mathewson 		return -1;
42119c8db0f8SNick Mathewson 	if (socklen > (int)sizeof(struct sockaddr_in6))
421272dd6667SNick Mathewson 		return -1;
421372dd6667SNick Mathewson 
421472dd6667SNick Mathewson 	if (sockaddr_getport((struct sockaddr*)&ss))
421572dd6667SNick Mathewson 		return -1;
421672dd6667SNick Mathewson 
421772dd6667SNick Mathewson 	while ((hostname = NEXT_TOKEN)) {
421872dd6667SNick Mathewson 		struct hosts_entry *he;
421972dd6667SNick Mathewson 		size_t namelen;
422072dd6667SNick Mathewson 		if ((hash = strchr(hostname, '#'))) {
422172dd6667SNick Mathewson 			if (hash == hostname)
422272dd6667SNick Mathewson 				return 0;
422372dd6667SNick Mathewson 			*hash = '\0';
422472dd6667SNick Mathewson 		}
422572dd6667SNick Mathewson 
422672dd6667SNick Mathewson 		namelen = strlen(hostname);
422772dd6667SNick Mathewson 
422872dd6667SNick Mathewson 		he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
422972dd6667SNick Mathewson 		if (!he)
423072dd6667SNick Mathewson 			return -1;
42319c8db0f8SNick Mathewson 		EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
423272dd6667SNick Mathewson 		memcpy(&he->addr, &ss, socklen);
423372dd6667SNick Mathewson 		memcpy(he->hostname, hostname, namelen+1);
423472dd6667SNick Mathewson 		he->addrlen = socklen;
423572dd6667SNick Mathewson 
423672dd6667SNick Mathewson 		TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
423772dd6667SNick Mathewson 
423872dd6667SNick Mathewson 		if (hash)
423972dd6667SNick Mathewson 			return 0;
424072dd6667SNick Mathewson 	}
424172dd6667SNick Mathewson 
424272dd6667SNick Mathewson 	return 0;
424372dd6667SNick Mathewson #undef NEXT_TOKEN
424472dd6667SNick Mathewson }
424572dd6667SNick Mathewson 
424672dd6667SNick Mathewson static int
evdns_base_load_hosts_impl(struct evdns_base * base,const char * hosts_fname)424772dd6667SNick Mathewson evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
424872dd6667SNick Mathewson {
424972dd6667SNick Mathewson 	char *str=NULL, *cp, *eol;
425072dd6667SNick Mathewson 	size_t len;
425172dd6667SNick Mathewson 	int err=0;
425272dd6667SNick Mathewson 
425372dd6667SNick Mathewson 	ASSERT_LOCKED(base);
425472dd6667SNick Mathewson 
425572dd6667SNick Mathewson 	if (hosts_fname == NULL ||
42568ac3c4c2SNick Mathewson 	    (err = evutil_read_file_(hosts_fname, &str, &len, 0)) < 0) {
425772dd6667SNick Mathewson 		char tmp[64];
425872dd6667SNick Mathewson 		strlcpy(tmp, "127.0.0.1   localhost", sizeof(tmp));
425972dd6667SNick Mathewson 		evdns_base_parse_hosts_line(base, tmp);
426072dd6667SNick Mathewson 		strlcpy(tmp, "::1   localhost", sizeof(tmp));
426172dd6667SNick Mathewson 		evdns_base_parse_hosts_line(base, tmp);
426272dd6667SNick Mathewson 		return err ? -1 : 0;
426372dd6667SNick Mathewson 	}
426472dd6667SNick Mathewson 
426572dd6667SNick Mathewson 	/* This will break early if there is a NUL in the hosts file.
426672dd6667SNick Mathewson 	 * Probably not a problem.*/
426772dd6667SNick Mathewson 	cp = str;
426872dd6667SNick Mathewson 	for (;;) {
426972dd6667SNick Mathewson 		eol = strchr(cp, '\n');
427072dd6667SNick Mathewson 
427172dd6667SNick Mathewson 		if (eol) {
427272dd6667SNick Mathewson 			*eol = '\0';
427372dd6667SNick Mathewson 			evdns_base_parse_hosts_line(base, cp);
427472dd6667SNick Mathewson 			cp = eol+1;
427572dd6667SNick Mathewson 		} else {
427672dd6667SNick Mathewson 			evdns_base_parse_hosts_line(base, cp);
427772dd6667SNick Mathewson 			break;
427872dd6667SNick Mathewson 		}
427972dd6667SNick Mathewson 	}
428072dd6667SNick Mathewson 
428172dd6667SNick Mathewson 	mm_free(str);
428272dd6667SNick Mathewson 	return 0;
428372dd6667SNick Mathewson }
428472dd6667SNick Mathewson 
428572dd6667SNick Mathewson int
evdns_base_load_hosts(struct evdns_base * base,const char * hosts_fname)428672dd6667SNick Mathewson evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
428772dd6667SNick Mathewson {
428872dd6667SNick Mathewson 	int res;
428972dd6667SNick Mathewson 	if (!base)
429072dd6667SNick Mathewson 		base = current_base;
429172dd6667SNick Mathewson 	EVDNS_LOCK(base);
429272dd6667SNick Mathewson 	res = evdns_base_load_hosts_impl(base, hosts_fname);
429372dd6667SNick Mathewson 	EVDNS_UNLOCK(base);
429472dd6667SNick Mathewson 	return res;
429572dd6667SNick Mathewson }
429672dd6667SNick Mathewson 
429786f57420SNick Mathewson /* A single request for a getaddrinfo, either v4 or v6. */
429886f57420SNick Mathewson struct getaddrinfo_subrequest {
429986f57420SNick Mathewson 	struct evdns_request *r;
430086f57420SNick Mathewson 	ev_uint32_t type;
430186f57420SNick Mathewson };
430286f57420SNick Mathewson 
430386f57420SNick Mathewson /* State data used to implement an in-progress getaddrinfo. */
430486f57420SNick Mathewson struct evdns_getaddrinfo_request {
430586f57420SNick Mathewson 	struct evdns_base *evdns_base;
430686f57420SNick Mathewson 	/* Copy of the modified 'hints' data that we'll use to build
430786f57420SNick Mathewson 	 * answers. */
430886f57420SNick Mathewson 	struct evutil_addrinfo hints;
430986f57420SNick Mathewson 	/* The callback to invoke when we're done */
431086f57420SNick Mathewson 	evdns_getaddrinfo_cb user_cb;
431186f57420SNick Mathewson 	/* User-supplied data to give to the callback. */
431286f57420SNick Mathewson 	void *user_data;
431386f57420SNick Mathewson 	/* The port to use when building sockaddrs. */
431486f57420SNick Mathewson 	ev_uint16_t port;
431586f57420SNick Mathewson 	/* The sub_request for an A record (if any) */
431686f57420SNick Mathewson 	struct getaddrinfo_subrequest ipv4_request;
431786f57420SNick Mathewson 	/* The sub_request for an AAAA record (if any) */
431886f57420SNick Mathewson 	struct getaddrinfo_subrequest ipv6_request;
431986f57420SNick Mathewson 
432086f57420SNick Mathewson 	/* The cname result that we were told (if any) */
432186f57420SNick Mathewson 	char *cname_result;
432286f57420SNick Mathewson 
432386f57420SNick Mathewson 	/* If we have one request answered and one request still inflight,
432486f57420SNick Mathewson 	 * then this field holds the answer from the first request... */
432586f57420SNick Mathewson 	struct evutil_addrinfo *pending_result;
432686f57420SNick Mathewson 	/* And this event is a timeout that will tell us to cancel the second
432786f57420SNick Mathewson 	 * request if it's taking a long time. */
432886f57420SNick Mathewson 	struct event timeout;
432949418612SNick Mathewson 
433049418612SNick Mathewson 	/* And this field holds the error code from the first request... */
433149418612SNick Mathewson 	int pending_error;
433249418612SNick Mathewson 	/* If this is set, the user canceled this request. */
433349418612SNick Mathewson 	unsigned user_canceled : 1;
4334d51b2fc6SNick Mathewson 	/* If this is set, the user can no longer cancel this request; we're
4335d51b2fc6SNick Mathewson 	 * just waiting for the free. */
4336d51b2fc6SNick Mathewson 	unsigned request_done : 1;
433786f57420SNick Mathewson };
433886f57420SNick Mathewson 
433986f57420SNick Mathewson /* Convert an evdns errors to the equivalent getaddrinfo error. */
434086f57420SNick Mathewson static int
evdns_err_to_getaddrinfo_err(int e1)434186f57420SNick Mathewson evdns_err_to_getaddrinfo_err(int e1)
434286f57420SNick Mathewson {
434386f57420SNick Mathewson 	/* XXX Do this better! */
434486f57420SNick Mathewson 	if (e1 == DNS_ERR_NONE)
434586f57420SNick Mathewson 		return 0;
434686f57420SNick Mathewson 	else if (e1 == DNS_ERR_NOTEXIST)
434786f57420SNick Mathewson 		return EVUTIL_EAI_NONAME;
434886f57420SNick Mathewson 	else
434986f57420SNick Mathewson 		return EVUTIL_EAI_FAIL;
435086f57420SNick Mathewson }
435186f57420SNick Mathewson 
435286f57420SNick Mathewson /* Return the more informative of two getaddrinfo errors. */
435386f57420SNick Mathewson static int
getaddrinfo_merge_err(int e1,int e2)435486f57420SNick Mathewson getaddrinfo_merge_err(int e1, int e2)
435586f57420SNick Mathewson {
435686f57420SNick Mathewson 	/* XXXX be cleverer here. */
435786f57420SNick Mathewson 	if (e1 == 0)
435886f57420SNick Mathewson 		return e2;
435986f57420SNick Mathewson 	else
436086f57420SNick Mathewson 		return e1;
436186f57420SNick Mathewson }
436286f57420SNick Mathewson 
436386f57420SNick Mathewson static void
free_getaddrinfo_request(struct evdns_getaddrinfo_request * data)436486f57420SNick Mathewson free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
436586f57420SNick Mathewson {
4366c7cfbcf4SNick Mathewson 	/* DO NOT CALL this if either of the requests is pending.  Only once
4367c7cfbcf4SNick Mathewson 	 * both callbacks have been invoked is it safe to free the request */
436886f57420SNick Mathewson 	if (data->pending_result)
436986f57420SNick Mathewson 		evutil_freeaddrinfo(data->pending_result);
437086f57420SNick Mathewson 	if (data->cname_result)
437186f57420SNick Mathewson 		mm_free(data->cname_result);
437286f57420SNick Mathewson 	event_del(&data->timeout);
437386f57420SNick Mathewson 	mm_free(data);
437486f57420SNick Mathewson 	return;
437586f57420SNick Mathewson }
437686f57420SNick Mathewson 
437786f57420SNick Mathewson static void
add_cname_to_reply(struct evdns_getaddrinfo_request * data,struct evutil_addrinfo * ai)437886f57420SNick Mathewson add_cname_to_reply(struct evdns_getaddrinfo_request *data,
437986f57420SNick Mathewson     struct evutil_addrinfo *ai)
438086f57420SNick Mathewson {
438186f57420SNick Mathewson 	if (data->cname_result && ai) {
438286f57420SNick Mathewson 		ai->ai_canonname = data->cname_result;
438386f57420SNick Mathewson 		data->cname_result = NULL;
438486f57420SNick Mathewson 	}
438586f57420SNick Mathewson }
438686f57420SNick Mathewson 
438786f57420SNick Mathewson /* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
438886f57420SNick Mathewson  * request has finished, but the other one took too long to answer. Pass
438986f57420SNick Mathewson  * along the answer we got, and cancel the other request.
439086f57420SNick Mathewson  */
439186f57420SNick Mathewson static void
evdns_getaddrinfo_timeout_cb(evutil_socket_t fd,short what,void * ptr)439286f57420SNick Mathewson evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
439386f57420SNick Mathewson {
439486f57420SNick Mathewson 	int v4_timedout = 0, v6_timedout = 0;
439586f57420SNick Mathewson 	struct evdns_getaddrinfo_request *data = ptr;
439686f57420SNick Mathewson 
439786f57420SNick Mathewson 	/* Cancel any pending requests, and note which one */
439886f57420SNick Mathewson 	if (data->ipv4_request.r) {
4399dc320776SGreg Hazel 		/* XXXX This does nothing if the request's callback is already
4400dc320776SGreg Hazel 		 * running (pending_cb is set). */
440186f57420SNick Mathewson 		evdns_cancel_request(NULL, data->ipv4_request.r);
440286f57420SNick Mathewson 		v4_timedout = 1;
440386f57420SNick Mathewson 		EVDNS_LOCK(data->evdns_base);
440486f57420SNick Mathewson 		++data->evdns_base->getaddrinfo_ipv4_timeouts;
44052df1f82bSZhuang Yuyao 		EVDNS_UNLOCK(data->evdns_base);
440686f57420SNick Mathewson 	}
440786f57420SNick Mathewson 	if (data->ipv6_request.r) {
4408dc320776SGreg Hazel 		/* XXXX This does nothing if the request's callback is already
4409dc320776SGreg Hazel 		 * running (pending_cb is set). */
441086f57420SNick Mathewson 		evdns_cancel_request(NULL, data->ipv6_request.r);
441186f57420SNick Mathewson 		v6_timedout = 1;
441286f57420SNick Mathewson 		EVDNS_LOCK(data->evdns_base);
441386f57420SNick Mathewson 		++data->evdns_base->getaddrinfo_ipv6_timeouts;
441486f57420SNick Mathewson 		EVDNS_UNLOCK(data->evdns_base);
441586f57420SNick Mathewson 	}
441686f57420SNick Mathewson 
441786f57420SNick Mathewson 	/* We only use this timeout callback when we have an answer for
441886f57420SNick Mathewson 	 * one address. */
441986f57420SNick Mathewson 	EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
442086f57420SNick Mathewson 
442186f57420SNick Mathewson 	/* Report the outcome of the other request that didn't time out. */
442286f57420SNick Mathewson 	if (data->pending_result) {
442386f57420SNick Mathewson 		add_cname_to_reply(data, data->pending_result);
442486f57420SNick Mathewson 		data->user_cb(0, data->pending_result, data->user_data);
442586f57420SNick Mathewson 		data->pending_result = NULL;
442686f57420SNick Mathewson 	} else {
442786f57420SNick Mathewson 		int e = data->pending_error;
442886f57420SNick Mathewson 		if (!e)
442986f57420SNick Mathewson 			e = EVUTIL_EAI_AGAIN;
443086f57420SNick Mathewson 		data->user_cb(e, NULL, data->user_data);
443186f57420SNick Mathewson 	}
443286f57420SNick Mathewson 
4433dc320776SGreg Hazel 	data->user_cb = NULL; /* prevent double-call if evdns callbacks are
4434dc320776SGreg Hazel 			       * in-progress. XXXX It would be better if this
4435dc320776SGreg Hazel 			       * weren't necessary. */
4436dc320776SGreg Hazel 
4437c7cfbcf4SNick Mathewson 	if (!v4_timedout && !v6_timedout) {
4438c7cfbcf4SNick Mathewson 		/* should be impossible? XXXX */
443986f57420SNick Mathewson 		free_getaddrinfo_request(data);
444086f57420SNick Mathewson 	}
4441c7cfbcf4SNick Mathewson }
444286f57420SNick Mathewson 
4443ff3f6cd4SNick Mathewson static int
evdns_getaddrinfo_set_timeout(struct evdns_base * evdns_base,struct evdns_getaddrinfo_request * data)444486f57420SNick Mathewson evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
444586f57420SNick Mathewson     struct evdns_getaddrinfo_request *data)
444686f57420SNick Mathewson {
4447ff3f6cd4SNick Mathewson 	return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
444886f57420SNick Mathewson }
444986f57420SNick Mathewson 
445049418612SNick Mathewson static inline int
evdns_result_is_answer(int result)445149418612SNick Mathewson evdns_result_is_answer(int result)
445249418612SNick Mathewson {
445349418612SNick Mathewson 	return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
445449418612SNick Mathewson 	    result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
445549418612SNick Mathewson }
445649418612SNick Mathewson 
445786f57420SNick Mathewson static void
evdns_getaddrinfo_gotresolve(int result,char type,int count,int ttl,void * addresses,void * arg)445886f57420SNick Mathewson evdns_getaddrinfo_gotresolve(int result, char type, int count,
445986f57420SNick Mathewson     int ttl, void *addresses, void *arg)
446086f57420SNick Mathewson {
446186f57420SNick Mathewson 	int i;
446286f57420SNick Mathewson 	struct getaddrinfo_subrequest *req = arg;
446386f57420SNick Mathewson 	struct getaddrinfo_subrequest *other_req;
446486f57420SNick Mathewson 	struct evdns_getaddrinfo_request *data;
446586f57420SNick Mathewson 
446686f57420SNick Mathewson 	struct evutil_addrinfo *res;
446786f57420SNick Mathewson 
446886f57420SNick Mathewson 	struct sockaddr_in sin;
446986f57420SNick Mathewson 	struct sockaddr_in6 sin6;
447086f57420SNick Mathewson 	struct sockaddr *sa;
447186f57420SNick Mathewson 	int socklen, addrlen;
447286f57420SNick Mathewson 	void *addrp;
447386f57420SNick Mathewson 	int err;
4474d51b2fc6SNick Mathewson 	int user_canceled;
447586f57420SNick Mathewson 
447686f57420SNick Mathewson 	EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
447786f57420SNick Mathewson 	if (req->type == DNS_IPv4_A) {
447886f57420SNick Mathewson 		data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
447986f57420SNick Mathewson 		other_req = &data->ipv6_request;
448086f57420SNick Mathewson 	} else {
448186f57420SNick Mathewson 		data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
448286f57420SNick Mathewson 		other_req = &data->ipv4_request;
4483d51b2fc6SNick Mathewson 	}
4484d51b2fc6SNick Mathewson 
448500313c50SAzat Khuzhin 	/** Called from evdns_base_free() with @fail_requests == 1 */
448600313c50SAzat Khuzhin 	if (result != DNS_ERR_SHUTDOWN) {
448786f57420SNick Mathewson 		EVDNS_LOCK(data->evdns_base);
4488d51b2fc6SNick Mathewson 		if (evdns_result_is_answer(result)) {
4489d51b2fc6SNick Mathewson 			if (req->type == DNS_IPv4_A)
4490d51b2fc6SNick Mathewson 				++data->evdns_base->getaddrinfo_ipv4_answered;
4491d51b2fc6SNick Mathewson 			else
449286f57420SNick Mathewson 				++data->evdns_base->getaddrinfo_ipv6_answered;
4493d51b2fc6SNick Mathewson 		}
4494d51b2fc6SNick Mathewson 		user_canceled = data->user_canceled;
4495d51b2fc6SNick Mathewson 		if (other_req->r == NULL)
4496d51b2fc6SNick Mathewson 			data->request_done = 1;
449786f57420SNick Mathewson 		EVDNS_UNLOCK(data->evdns_base);
449800313c50SAzat Khuzhin 	} else {
449900313c50SAzat Khuzhin 		data->evdns_base = NULL;
450000313c50SAzat Khuzhin 		user_canceled = data->user_canceled;
450100313c50SAzat Khuzhin 	}
450286f57420SNick Mathewson 
450386f57420SNick Mathewson 	req->r = NULL;
450486f57420SNick Mathewson 
4505d51b2fc6SNick Mathewson 	if (result == DNS_ERR_CANCEL && ! user_canceled) {
4506c7cfbcf4SNick Mathewson 		/* Internal cancel request from timeout or internal error.
4507c7cfbcf4SNick Mathewson 		 * we already answered the user. */
4508c7cfbcf4SNick Mathewson 		if (other_req->r == NULL)
4509c7cfbcf4SNick Mathewson 			free_getaddrinfo_request(data);
4510c7cfbcf4SNick Mathewson 		return;
4511c7cfbcf4SNick Mathewson 	}
4512c7cfbcf4SNick Mathewson 
4513dc320776SGreg Hazel 	if (data->user_cb == NULL) {
4514dc320776SGreg Hazel 		/* We already answered.  XXXX This shouldn't be needed; see
4515dc320776SGreg Hazel 		 * comments in evdns_getaddrinfo_timeout_cb */
4516dc320776SGreg Hazel 		free_getaddrinfo_request(data);
4517dc320776SGreg Hazel 		return;
4518dc320776SGreg Hazel 	}
4519dc320776SGreg Hazel 
452086f57420SNick Mathewson 	if (result == DNS_ERR_NONE) {
452186f57420SNick Mathewson 		if (count == 0)
452286f57420SNick Mathewson 			err = EVUTIL_EAI_NODATA;
452386f57420SNick Mathewson 		else
452486f57420SNick Mathewson 			err = 0;
452586f57420SNick Mathewson 	} else {
452686f57420SNick Mathewson 		err = evdns_err_to_getaddrinfo_err(result);
452786f57420SNick Mathewson 	}
452886f57420SNick Mathewson 
452986f57420SNick Mathewson 	if (err) {
453086f57420SNick Mathewson 		/* Looks like we got an error. */
453186f57420SNick Mathewson 		if (other_req->r) {
453286f57420SNick Mathewson 			/* The other request is still working; maybe it will
453386f57420SNick Mathewson 			 * succeed. */
4534ff3f6cd4SNick Mathewson 			/* XXXX handle failure from set_timeout */
453500313c50SAzat Khuzhin 			if (result != DNS_ERR_SHUTDOWN) {
453686f57420SNick Mathewson 				evdns_getaddrinfo_set_timeout(data->evdns_base, data);
453700313c50SAzat Khuzhin 			}
453886f57420SNick Mathewson 			data->pending_error = err;
453986f57420SNick Mathewson 			return;
454086f57420SNick Mathewson 		}
454186f57420SNick Mathewson 
4542d51b2fc6SNick Mathewson 		if (user_canceled) {
454349418612SNick Mathewson 			data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
454449418612SNick Mathewson 		} else if (data->pending_result) {
454549418612SNick Mathewson 			/* If we have an answer waiting, and we weren't
454649418612SNick Mathewson 			 * canceled, ignore this error. */
454786f57420SNick Mathewson 			add_cname_to_reply(data, data->pending_result);
454886f57420SNick Mathewson 			data->user_cb(0, data->pending_result, data->user_data);
454986f57420SNick Mathewson 			data->pending_result = NULL;
455086f57420SNick Mathewson 		} else {
455186f57420SNick Mathewson 			if (data->pending_error)
455286f57420SNick Mathewson 				err = getaddrinfo_merge_err(err,
455386f57420SNick Mathewson 				    data->pending_error);
455486f57420SNick Mathewson 			data->user_cb(err, NULL, data->user_data);
455586f57420SNick Mathewson 		}
455686f57420SNick Mathewson 		free_getaddrinfo_request(data);
455786f57420SNick Mathewson 		return;
4558d51b2fc6SNick Mathewson 	} else if (user_canceled) {
4559abf01ed1SNick Mathewson 		if (other_req->r) {
4560c7cfbcf4SNick Mathewson 			/* The other request is still working; let it hit this
4561c7cfbcf4SNick Mathewson 			 * callback with EVUTIL_EAI_CANCEL callback and report
4562c7cfbcf4SNick Mathewson 			 * the failure. */
4563abf01ed1SNick Mathewson 			return;
4564abf01ed1SNick Mathewson 		}
456549418612SNick Mathewson 		data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
456649418612SNick Mathewson 		free_getaddrinfo_request(data);
456749418612SNick Mathewson 		return;
456886f57420SNick Mathewson 	}
456986f57420SNick Mathewson 
457086f57420SNick Mathewson 	/* Looks like we got some answers. We should turn them into addrinfos
457186f57420SNick Mathewson 	 * and then either queue those or return them all. */
457286f57420SNick Mathewson 	EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
457386f57420SNick Mathewson 
457486f57420SNick Mathewson 	if (type == DNS_IPv4_A) {
457586f57420SNick Mathewson 		memset(&sin, 0, sizeof(sin));
457686f57420SNick Mathewson 		sin.sin_family = AF_INET;
457786f57420SNick Mathewson 		sin.sin_port = htons(data->port);
457886f57420SNick Mathewson 
457986f57420SNick Mathewson 		sa = (struct sockaddr *)&sin;
458086f57420SNick Mathewson 		socklen = sizeof(sin);
458186f57420SNick Mathewson 		addrlen = 4;
458286f57420SNick Mathewson 		addrp = &sin.sin_addr.s_addr;
458386f57420SNick Mathewson 	} else {
458486f57420SNick Mathewson 		memset(&sin6, 0, sizeof(sin6));
458586f57420SNick Mathewson 		sin6.sin6_family = AF_INET6;
458686f57420SNick Mathewson 		sin6.sin6_port = htons(data->port);
458786f57420SNick Mathewson 
458886f57420SNick Mathewson 		sa = (struct sockaddr *)&sin6;
458986f57420SNick Mathewson 		socklen = sizeof(sin6);
459086f57420SNick Mathewson 		addrlen = 16;
459186f57420SNick Mathewson 		addrp = &sin6.sin6_addr.s6_addr;
459286f57420SNick Mathewson 	}
459386f57420SNick Mathewson 
459486f57420SNick Mathewson 	res = NULL;
459586f57420SNick Mathewson 	for (i=0; i < count; ++i) {
459686f57420SNick Mathewson 		struct evutil_addrinfo *ai;
459786f57420SNick Mathewson 		memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
45988ac3c4c2SNick Mathewson 		ai = evutil_new_addrinfo_(sa, socklen, &data->hints);
459986f57420SNick Mathewson 		if (!ai) {
460086f57420SNick Mathewson 			if (other_req->r) {
460186f57420SNick Mathewson 				evdns_cancel_request(NULL, other_req->r);
460286f57420SNick Mathewson 			}
460386f57420SNick Mathewson 			data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
46043417f680SNick Mathewson 			if (res)
460586f57420SNick Mathewson 				evutil_freeaddrinfo(res);
460686f57420SNick Mathewson 
4607c7cfbcf4SNick Mathewson 			if (other_req->r == NULL)
460886f57420SNick Mathewson 				free_getaddrinfo_request(data);
460986f57420SNick Mathewson 			return;
461086f57420SNick Mathewson 		}
46118ac3c4c2SNick Mathewson 		res = evutil_addrinfo_append_(res, ai);
461286f57420SNick Mathewson 	}
461386f57420SNick Mathewson 
461486f57420SNick Mathewson 	if (other_req->r) {
461586f57420SNick Mathewson 		/* The other request is still in progress; wait for it */
4616ff3f6cd4SNick Mathewson 		/* XXXX handle failure from set_timeout */
461786f57420SNick Mathewson 		evdns_getaddrinfo_set_timeout(data->evdns_base, data);
461886f57420SNick Mathewson 		data->pending_result = res;
461986f57420SNick Mathewson 		return;
462086f57420SNick Mathewson 	} else {
462186f57420SNick Mathewson 		/* The other request is done or never started; append its
462286f57420SNick Mathewson 		 * results (if any) and return them. */
462386f57420SNick Mathewson 		if (data->pending_result) {
462486f57420SNick Mathewson 			if (req->type == DNS_IPv4_A)
46258ac3c4c2SNick Mathewson 				res = evutil_addrinfo_append_(res,
462686f57420SNick Mathewson 				    data->pending_result);
462786f57420SNick Mathewson 			else
46288ac3c4c2SNick Mathewson 				res = evutil_addrinfo_append_(
462986f57420SNick Mathewson 				    data->pending_result, res);
463086f57420SNick Mathewson 			data->pending_result = NULL;
463186f57420SNick Mathewson 		}
463286f57420SNick Mathewson 
463386f57420SNick Mathewson 		/* Call the user callback. */
463486f57420SNick Mathewson 		add_cname_to_reply(data, res);
463586f57420SNick Mathewson 		data->user_cb(0, res, data->user_data);
463686f57420SNick Mathewson 
463786f57420SNick Mathewson 		/* Free data. */
463886f57420SNick Mathewson 		free_getaddrinfo_request(data);
463986f57420SNick Mathewson 	}
464086f57420SNick Mathewson }
464186f57420SNick Mathewson 
464272dd6667SNick Mathewson static struct hosts_entry *
find_hosts_entry(struct evdns_base * base,const char * hostname,struct hosts_entry * find_after)464372dd6667SNick Mathewson find_hosts_entry(struct evdns_base *base, const char *hostname,
464472dd6667SNick Mathewson     struct hosts_entry *find_after)
464572dd6667SNick Mathewson {
464672dd6667SNick Mathewson 	struct hosts_entry *e;
464772dd6667SNick Mathewson 
464872dd6667SNick Mathewson 	if (find_after)
464972dd6667SNick Mathewson 		e = TAILQ_NEXT(find_after, next);
465072dd6667SNick Mathewson 	else
465172dd6667SNick Mathewson 		e = TAILQ_FIRST(&base->hostsdb);
465272dd6667SNick Mathewson 
465372dd6667SNick Mathewson 	for (; e; e = TAILQ_NEXT(e, next)) {
465472dd6667SNick Mathewson 		if (!evutil_ascii_strcasecmp(e->hostname, hostname))
465572dd6667SNick Mathewson 			return e;
465672dd6667SNick Mathewson 	}
465772dd6667SNick Mathewson 	return NULL;
465872dd6667SNick Mathewson }
465972dd6667SNick Mathewson 
466072dd6667SNick Mathewson static int
evdns_getaddrinfo_fromhosts(struct evdns_base * base,const char * nodename,struct evutil_addrinfo * hints,ev_uint16_t port,struct evutil_addrinfo ** res)466172dd6667SNick Mathewson evdns_getaddrinfo_fromhosts(struct evdns_base *base,
466272dd6667SNick Mathewson     const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
466372dd6667SNick Mathewson     struct evutil_addrinfo **res)
466472dd6667SNick Mathewson {
466572dd6667SNick Mathewson 	int n_found = 0;
466672dd6667SNick Mathewson 	struct hosts_entry *e;
466772dd6667SNick Mathewson 	struct evutil_addrinfo *ai=NULL;
466872dd6667SNick Mathewson 	int f = hints->ai_family;
466972dd6667SNick Mathewson 
467072dd6667SNick Mathewson 	EVDNS_LOCK(base);
467172dd6667SNick Mathewson 	for (e = find_hosts_entry(base, nodename, NULL); e;
467272dd6667SNick Mathewson 	    e = find_hosts_entry(base, nodename, e)) {
467372dd6667SNick Mathewson 		struct evutil_addrinfo *ai_new;
467472dd6667SNick Mathewson 		++n_found;
467572dd6667SNick Mathewson 		if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
467672dd6667SNick Mathewson 		    (e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
467772dd6667SNick Mathewson 			continue;
46788ac3c4c2SNick Mathewson 		ai_new = evutil_new_addrinfo_(&e->addr.sa, e->addrlen, hints);
467972dd6667SNick Mathewson 		if (!ai_new) {
468072dd6667SNick Mathewson 			n_found = 0;
468172dd6667SNick Mathewson 			goto out;
468272dd6667SNick Mathewson 		}
468372dd6667SNick Mathewson 		sockaddr_setport(ai_new->ai_addr, port);
46848ac3c4c2SNick Mathewson 		ai = evutil_addrinfo_append_(ai, ai_new);
468572dd6667SNick Mathewson 	}
468672dd6667SNick Mathewson 	EVDNS_UNLOCK(base);
468772dd6667SNick Mathewson out:
468872dd6667SNick Mathewson 	if (n_found) {
468972dd6667SNick Mathewson 		/* Note that we return an empty answer if we found entries for
469072dd6667SNick Mathewson 		 * this hostname but none were of the right address type. */
469172dd6667SNick Mathewson 		*res = ai;
469272dd6667SNick Mathewson 		return 0;
469372dd6667SNick Mathewson 	} else {
469472dd6667SNick Mathewson 		if (ai)
469572dd6667SNick Mathewson 			evutil_freeaddrinfo(ai);
469672dd6667SNick Mathewson 		return -1;
469772dd6667SNick Mathewson 	}
469872dd6667SNick Mathewson }
469972dd6667SNick Mathewson 
470086f57420SNick Mathewson 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)470186f57420SNick Mathewson evdns_getaddrinfo(struct evdns_base *dns_base,
470286f57420SNick Mathewson     const char *nodename, const char *servname,
470386f57420SNick Mathewson     const struct evutil_addrinfo *hints_in,
470486f57420SNick Mathewson     evdns_getaddrinfo_cb cb, void *arg)
470586f57420SNick Mathewson {
470686f57420SNick Mathewson 	struct evdns_getaddrinfo_request *data;
470786f57420SNick Mathewson 	struct evutil_addrinfo hints;
470886f57420SNick Mathewson 	struct evutil_addrinfo *res = NULL;
470986f57420SNick Mathewson 	int err;
471086f57420SNick Mathewson 	int port = 0;
471186f57420SNick Mathewson 	int want_cname = 0;
47123237d697SAzat Khuzhin 	int started = 0;
471386f57420SNick Mathewson 
471486f57420SNick Mathewson 	if (!dns_base) {
471586f57420SNick Mathewson 		dns_base = current_base;
471686f57420SNick Mathewson 		if (!dns_base) {
471786f57420SNick Mathewson 			log(EVDNS_LOG_WARN,
471886f57420SNick Mathewson 			    "Call to getaddrinfo_async with no "
471986f57420SNick Mathewson 			    "evdns_base configured.");
472086f57420SNick Mathewson 			cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
472186f57420SNick Mathewson 			return NULL;
472286f57420SNick Mathewson 		}
472386f57420SNick Mathewson 	}
472486f57420SNick Mathewson 
472586f57420SNick Mathewson 	/* If we _must_ answer this immediately, do so. */
472686f57420SNick Mathewson 	if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
472786f57420SNick Mathewson 		res = NULL;
472886f57420SNick Mathewson 		err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
472986f57420SNick Mathewson 		cb(err, res, arg);
473086f57420SNick Mathewson 		return NULL;
473186f57420SNick Mathewson 	}
473286f57420SNick Mathewson 
473386f57420SNick Mathewson 	if (hints_in) {
473486f57420SNick Mathewson 		memcpy(&hints, hints_in, sizeof(hints));
473586f57420SNick Mathewson 	} else {
473686f57420SNick Mathewson 		memset(&hints, 0, sizeof(hints));
473786f57420SNick Mathewson 		hints.ai_family = PF_UNSPEC;
473886f57420SNick Mathewson 	}
473986f57420SNick Mathewson 
47408ac3c4c2SNick Mathewson 	evutil_adjust_hints_for_addrconfig_(&hints);
474186f57420SNick Mathewson 
474286f57420SNick Mathewson 	/* Now try to see if we _can_ answer immediately. */
474386f57420SNick Mathewson 	/* (It would be nice to do this by calling getaddrinfo directly, with
474486f57420SNick Mathewson 	 * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
474586f57420SNick Mathewson 	 * a reliable way to distinguish the "that wasn't a numeric host!" case
474686f57420SNick Mathewson 	 * from any other EAI_NONAME cases.) */
47478ac3c4c2SNick Mathewson 	err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
474886f57420SNick Mathewson 	if (err != EVUTIL_EAI_NEED_RESOLVE) {
474986f57420SNick Mathewson 		cb(err, res, arg);
475086f57420SNick Mathewson 		return NULL;
475186f57420SNick Mathewson 	}
475286f57420SNick Mathewson 
475372dd6667SNick Mathewson 	/* If there is an entry in the hosts file, we should give it now. */
475472dd6667SNick Mathewson 	if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
475572dd6667SNick Mathewson 		cb(0, res, arg);
475672dd6667SNick Mathewson 		return NULL;
475772dd6667SNick Mathewson 	}
475872dd6667SNick Mathewson 
475986f57420SNick Mathewson 	/* Okay, things are serious now. We're going to need to actually
476086f57420SNick Mathewson 	 * launch a request.
476186f57420SNick Mathewson 	 */
476286f57420SNick Mathewson 	data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
476386f57420SNick Mathewson 	if (!data) {
476486f57420SNick Mathewson 		cb(EVUTIL_EAI_MEMORY, NULL, arg);
476586f57420SNick Mathewson 		return NULL;
476686f57420SNick Mathewson 	}
476786f57420SNick Mathewson 
476886f57420SNick Mathewson 	memcpy(&data->hints, &hints, sizeof(data->hints));
476986f57420SNick Mathewson 	data->port = (ev_uint16_t)port;
477086f57420SNick Mathewson 	data->ipv4_request.type = DNS_IPv4_A;
477186f57420SNick Mathewson 	data->ipv6_request.type = DNS_IPv6_AAAA;
477286f57420SNick Mathewson 	data->user_cb = cb;
477386f57420SNick Mathewson 	data->user_data = arg;
477486f57420SNick Mathewson 	data->evdns_base = dns_base;
477586f57420SNick Mathewson 
477686f57420SNick Mathewson 	want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
477786f57420SNick Mathewson 
477886f57420SNick Mathewson 	/* If we are asked for a PF_UNSPEC address, we launch two requests in
477986f57420SNick Mathewson 	 * parallel: one for an A address and one for an AAAA address.  We
478086f57420SNick Mathewson 	 * can't send just one request, since many servers only answer one
478186f57420SNick Mathewson 	 * question per DNS request.
478286f57420SNick Mathewson 	 *
478386f57420SNick Mathewson 	 * Once we have the answer to one request, we allow for a short
478486f57420SNick Mathewson 	 * timeout before we report it, to see if the other one arrives.  If
478586f57420SNick Mathewson 	 * they both show up in time, then we report both the answers.
478686f57420SNick Mathewson 	 *
478786f57420SNick Mathewson 	 * If too many addresses of one type time out or fail, we should stop
478886f57420SNick Mathewson 	 * launching those requests. (XXX we don't do that yet.)
478986f57420SNick Mathewson 	 */
479086f57420SNick Mathewson 
47913237d697SAzat Khuzhin 	EVDNS_LOCK(dns_base);
47923237d697SAzat Khuzhin 
479386f57420SNick Mathewson 	if (hints.ai_family != PF_INET6) {
479486f57420SNick Mathewson 		log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
479586f57420SNick Mathewson 		    nodename, &data->ipv4_request);
479686f57420SNick Mathewson 
479786f57420SNick Mathewson 		data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
479886f57420SNick Mathewson 		    nodename, 0, evdns_getaddrinfo_gotresolve,
479986f57420SNick Mathewson 		    &data->ipv4_request);
48003a4d249cSufo2243 		if (want_cname && data->ipv4_request.r)
480115bb82d6SChristopher Davis 			data->ipv4_request.r->current_req->put_cname_in_ptr =
480286f57420SNick Mathewson 			    &data->cname_result;
480386f57420SNick Mathewson 	}
480486f57420SNick Mathewson 	if (hints.ai_family != PF_INET) {
480586f57420SNick Mathewson 		log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
480686f57420SNick Mathewson 		    nodename, &data->ipv6_request);
480786f57420SNick Mathewson 
480886f57420SNick Mathewson 		data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
480986f57420SNick Mathewson 		    nodename, 0, evdns_getaddrinfo_gotresolve,
481086f57420SNick Mathewson 		    &data->ipv6_request);
48116a53d153SNick Mathewson 		if (want_cname && data->ipv6_request.r)
481215bb82d6SChristopher Davis 			data->ipv6_request.r->current_req->put_cname_in_ptr =
481386f57420SNick Mathewson 			    &data->cname_result;
481486f57420SNick Mathewson 	}
481586f57420SNick Mathewson 
481686f57420SNick Mathewson 	evtimer_assign(&data->timeout, dns_base->event_base,
481786f57420SNick Mathewson 	    evdns_getaddrinfo_timeout_cb, data);
481886f57420SNick Mathewson 
48193237d697SAzat Khuzhin 	started = (data->ipv4_request.r || data->ipv6_request.r);
48203237d697SAzat Khuzhin 
48213237d697SAzat Khuzhin 	EVDNS_UNLOCK(dns_base);
48223237d697SAzat Khuzhin 
48233237d697SAzat Khuzhin 	if (started) {
482486f57420SNick Mathewson 		return data;
482586f57420SNick Mathewson 	} else {
482686f57420SNick Mathewson 		mm_free(data);
482786f57420SNick Mathewson 		cb(EVUTIL_EAI_FAIL, NULL, arg);
482886f57420SNick Mathewson 		return NULL;
482986f57420SNick Mathewson 	}
483086f57420SNick Mathewson }
483186f57420SNick Mathewson 
483286f57420SNick Mathewson void
evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request * data)483386f57420SNick Mathewson evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
483486f57420SNick Mathewson {
4835d51b2fc6SNick Mathewson 	EVDNS_LOCK(data->evdns_base);
4836d51b2fc6SNick Mathewson 	if (data->request_done) {
4837d51b2fc6SNick Mathewson 		EVDNS_UNLOCK(data->evdns_base);
4838d51b2fc6SNick Mathewson 		return;
4839d51b2fc6SNick Mathewson 	}
484086f57420SNick Mathewson 	event_del(&data->timeout);
484149418612SNick Mathewson 	data->user_canceled = 1;
484286f57420SNick Mathewson 	if (data->ipv4_request.r)
484386f57420SNick Mathewson 		evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
484486f57420SNick Mathewson 	if (data->ipv6_request.r)
484586f57420SNick Mathewson 		evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
4846d51b2fc6SNick Mathewson 	EVDNS_UNLOCK(data->evdns_base);
484786f57420SNick Mathewson }
4848