eventdns.c 62.8 KB
Newer Older
1
2
/* $Id$ */

3
4
5
/* The original version of this module was written by Adam Langley; for
 * a history of modifications, check out the subversion logs.
 *
6
 * When editing this module, try to keep it re-mergeable by Adam.  Don't
7
8
9
 * reformat the whitespace, add Tor dependencies, or so on.
 *
 * TODO:
10
11
12
13
14
 *   - Have a way to query for AAAA and A records simultaneously.
 *   - Improve request API.
 *   - (Can we suppress cnames? Should we?)
 *   - Replace all externally visible magic numbers with #defined constants.
 *   - Write documentation for APIs of all external functions.
15
 */
16

17
18
/* Async DNS Library
 * Adam Langley <agl@imperialviolet.org>
19
 * http://www.imperialviolet.org/eventdns.html
20
 * Public Domain code
21
22
23
24
25
26
27
 *
 * This software is Public Domain. To view a copy of the public domain dedication,
 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
 *
 * I ask and expect, but do not require, that all derivative works contain an
 * attribution similar to:
28
 *  Parts developed by Adam Langley <agl@imperialviolet.org>
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
 *
 * You may wish to replace the word "Parts" with something else depending on
 * the amount of original code.
 *
 * (Derivative works does not include programs which link against, run or include
 * the source verbatim in their source distributions)
 *
 * Version: 0.1b
 *
 *
 * Welcome, gentle reader
 *
 * Async DNS lookups are really a whole lot harder than they should be,
 * mostly stemming from the fact that the libc resolver has never been
 * very good at them. Before you use this library you should see if libc
44
45
46
 * can do the job for you with the modern async call getaddrinfo_a
 * (see http://www.imperialviolet.org/page25.html#e498). Otherwise,
 * please continue.
47
 *
48
49
50
51
52
53
 * This code is based on libevent and you must call event_init before
 * any of the APIs in this file. You must also seed the OpenSSL random
 * source if you are using OpenSSL for ids (see below).
 *
 * This library is designed to be included and shipped with your source
 * code. You statically link with it. You should also test for the
Roger Dingledine's avatar
Roger Dingledine committed
54
 * existence of strtok_r and define HAVE_STRTOK_R if you have it.
55
56
57
58
59
60
61
 *
 * The DNS protocol requires a good source of id numbers and these
 * numbers should be unpredictable for spoofing reasons. There are
 * three methods for generating them here and you must define exactly
 * one of them. In increasing order of preference:
 *
 * DNS_USE_GETTIMEOFDAY_FOR_ID:
62
63
 *   Using the bottom 16 bits of the usec result from gettimeofday. This
 *   is a pretty poor solution but should work anywhere.
64
 * DNS_USE_CPU_CLOCK_FOR_ID:
65
66
67
68
 *  Using the bottom 16 bits of the nsec result from the CPU's time
 *  counter. This is better, but may not work everywhere. Requires
 *  POSIX realtime support and you'll need to link against -lrt on
 *  glibc systems at least.
69
 * DNS_USE_OPENSSL_FOR_ID:
70
71
 *  Uses the OpenSSL RAND_bytes call to generate the data. You must
 *  have seeded the pool before making any calls to this library.
72
73
74
75
76
 *
 * The library keeps track of the state of nameservers and will avoid
 * them when they go down. Otherwise it will round robin between them.
 *
 * Quick start guide:
77
78
 *	 #include "eventdns.h"
 *	 void callback(int result, char type, int count, int ttl,
79
80
81
 *     void *addresses, void *arg);
 *	 evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
 *	 evdns_resolve("www.hostname.com", 0, callback, NULL);
82
83
84
85
86
87
88
 *
 * When the lookup is complete the callback function is called. The
 * first argument will be one of the DNS_ERR_* defines in eventdns.h.
 * Hopefully it will be DNS_ERR_NONE, in which case type will be
 * DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
 * which the data can be cached for (in seconds), addresses will point
 * to an array of uint32_t's and arg will be whatever you passed to
89
 * evdns_resolve.
90
91
92
 *
 * Searching:
 *
93
 * In order for this library to be a good replacement for glibc's resolver it
94
 * supports searching. This involves setting a list of default domains, in
95
 * which names will be queried for. The number of dots in the query name
96
97
98
99
 * determines the order in which this list is used.
 *
 * Searching appears to be a single lookup from the point of view of the API,
 * although many DNS queries may be generated from a single call to
100
 * evdns_resolve. Searching can also drastically slow down the resolution
101
 * of names.
102
103
 *
 * To disable searching:
104
105
 *	 1. Never set it up. If you never call evdns_resolv_conf_parse or
 *   evdns_search_add then no searching will occur.
106
 *
107
108
 *	 2. If you do call evdns_resolv_conf_parse then don't pass
 *   DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
109
 *
110
 *	 3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag.
111
112
113
114
115
116
 *
 * The order of searches depends on the number of dots in the name. If the
 * number is greater than the ndots setting then the names is first tried
 * globally. Otherwise each search domain is appended in turn.
 *
 * The ndots setting can either be set from a resolv.conf, or by calling
117
 * evdns_search_ndots_set.
118
119
120
 *
 * For example, with ndots set to 1 (the default) and a search domain list of
 * ["myhome.net"]:
121
122
 *	Query: www
 *	Order: www.myhome.net, www.
123
 *
124
125
 *	Query: www.abc
 *	Order: www.abc., www.abc.myhome.net
126
127
128
 *
 * API reference:
 *
129
 * int evdns_nameserver_add(unsigned long int address)
130
131
132
133
 *	 Add a nameserver. The address should be an IP address in
 *	 network byte order. The type of address is chosen so that
 *	 it matches in_addr.s_addr.
 *	 Returns non-zero on error.
134
 *
135
 * int evdns_nameserver_ip_add(const char *ip_as_string)
136
137
138
 *	 This wraps the above function by parsing a string as an IP
 *	 address and adds it as a nameserver.
 *	 Returns non-zero on error
139
 *
140
141
142
 * int evdns_resolve(const char *name, int flags,
 *            evdns_callback_type callback,
 *            void *ptr)
143
144
145
146
 *	 Resolve a name. The name parameter should be a DNS name.
 *	 The flags parameter should be 0, or DNS_QUERY_NO_SEARCH
 *	 which disables searching for this query. (see defn of
 *	 searching above).
147
 *
148
149
150
 *	 The callback argument is a function which is called when
 *	 this query completes and ptr is an argument which is passed
 *	 to that callback function.
151
 *
152
 *	 Returns non-zero on error
153
 *
154
 * void evdns_search_clear()
155
 *	 Clears the list of search domains
156
 *
157
 * void evdns_search_add(const char *domain)
158
 *	 Add a domain to the list of search domains
159
 *
160
 * void evdns_search_ndots_set(int ndots)
161
162
 *	 Set the number of dots which, when found in a name, causes
 *	 the first query to be without any search domain.
163
 *
164
 * int evdns_count_nameservers(void)
165
166
167
168
 *	 Return the number of configured nameservers (not necessarily the
 *	 number of running nameservers).  This is useful for double-checking
 *	 whether our calls to the various nameserver configuration functions
 *	 have been successful.
169
 *
170
 * int evdns_clear_nameservers_and_suspend(void)
171
172
 *	 Remove all currently configured nameservers, and suspend all pending
 *	 resolves.	Resolves will not necessarily be re-attempted until
173
 *	 evdns_resume() is called.
174
 *
175
 * int evdns_resume(void)
176
 *	 Re-attempt resolves left in limbo after an earlier call to
177
 *	 evdns_clear_nameservers_and_suspend().
178
 *
179
 * int evdns_config_windows_nameservers(void)
180
181
182
 *	 Attempt to configure a set of nameservers based on platform settings on
 *	 a win32 host.	Preferentially tries to use GetNetworkParams; if that fails,
 *	 looks in the registry.	 Returns 0 on success, nonzero on failure.
183
 *
184
 * int evdns_resolv_conf_parse(int flags, const char *filename)
185
 *	 Parse a resolv.conf like file from the given filename.
186
 *
187
188
189
190
191
192
193
194
195
 *	 See the man page for resolv.conf for the format of this file.
 *	 The flags argument determines what information is parsed from
 *	 this file:
 *	   DNS_OPTION_SEARCH - domain, search and ndots options
 *	   DNS_OPTION_NAMESERVERS - nameserver lines
 *	   DNS_OPTION_MISC - timeout and attempts options
 *	   DNS_OPTIONS_ALL - all of the above
 *	 The following directives are not parsed from the file:
 *	   sortlist, rotate, no-check-names, inet6, debug
196
 *
197
198
199
200
201
202
203
 *	 Returns non-zero on error:
 *	  0 no errors
 *	  1 failed to open file
 *	  2 failed to stat file
 *	  3 file too large
 *	  4 out of memory
 *	  5 short read from file
204
205
206
207
208
209
210
211
212
213
214
 *
 * Internals:
 *
 * Requests are kept in two queues. The first is the inflight queue. In
 * this queue requests have an allocated transaction id and nameserver.
 * They will soon be transmitted if they haven't already been.
 *
 * The second is the waiting queue. The size of the inflight ring is
 * limited and all other requests wait in waiting queue for space. This
 * bounds the number of concurrent requests so that we don't flood the
 * nameserver. Several algorithms require a full walk of the inflight
215
 * queue and so bounding its size keeps thing going nicely under huge
216
217
 * (many thousands of requests) loads.
 *
Roger Dingledine's avatar
Roger Dingledine committed
218
 * If a nameserver loses too many requests it is considered down and we
219
220
221
222
223
224
225
226
227
228
229
230
231
232
 * try not to use it. After a while we send a probe to that nameserver
 * (a lookup for google.com) and, if it replies, we consider it working
 * again. If the nameserver fails a probe we wait longer to try again
 * with the next probe.
 */

#include "eventdns.h"
#include "eventdns_tor.h"
//#define NDEBUG

#ifndef DNS_USE_CPU_CLOCK_FOR_ID
#ifndef DNS_USE_GETTIMEOFDAY_FOR_ID
#ifndef DNS_USE_OPENSSL_FOR_ID
#error Must configure at least one id generation method.
Roger Dingledine's avatar
Roger Dingledine committed
233
#error Please see the documentation.
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#endif
#endif
#endif

// #define _POSIX_C_SOURCE 200507
#define _GNU_SOURCE

#ifdef DNS_USE_CPU_CLOCK_FOR_ID
#ifdef DNS_USE_OPENSSL_FOR_ID
#error Multiple id options selected
#endif
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
#error Multiple id options selected
#endif
#include <time.h>
#endif

#ifdef DNS_USE_OPENSSL_FOR_ID
#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
#error Multiple id options selected
#endif
#include <openssl/rand.h>
#endif

#define _FORTIFY_SOURCE 3

#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/time.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>
272
#include <ctype.h>
273
274
#include <stdio.h>
#include <stdarg.h>
275

276
277
278
279
280
281
282
283
284
285
#ifdef WIN32
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

286
287
#define EVDNS_LOG_DEBUG 0
#define EVDNS_LOG_WARN 1
288

289
290
291
292
293
294
295
296
297
298
299
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif

#ifndef NDEBUG
#include <stdio.h>
#endif

#undef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))

300
#if 0
301
302
303
304
305
#ifdef __USE_ISOC99B
// libevent doesn't work without this
typedef uint8_t u_char;
typedef unsigned int uint;
#endif
306
#endif
307
308
309
310
311
#include <event.h>

#define u64 uint64_t
#define u32 uint32_t
#define u16 uint16_t
312
#define u8	uint8_t
313
314
315

#include "eventdns.h"

316
#define MAX_ADDRS 4	 // maximum number of addresses from a single packet
317
318
// which we bother recording

319
320
321
322
#define TYPE_A		   1
#define TYPE_CNAME	   5
#define TYPE_PTR	  12
#define TYPE_AAAA	  28
323

324
325
326
327
#define CLASS_INET 1

struct request {
	u8 *request;  // the dns packet data
328
	unsigned int request_len;
329
330
331
	int reissue_count;
	int tx_count;  // the number of times that this packet has been sent
	unsigned int request_type; // TYPE_PTR or TYPE_A
332
	void *user_pointer;	 // the pointer given to us for this request
333
	evdns_callback_type user_callback;
334
	struct nameserver *ns;	// the server which we last sent it
335
336
337
338

	// elements used by the searching code
	int search_index;
	struct search_state *search_state;
339
	char *search_origname;	// needs to be free()ed
340
341
342
343
344
345
346
347
	int search_flags;

	// these objects are kept in a circular list
	struct request *next, *prev;

	struct event timeout_event;

	u16 trans_id;  // the transaction id
348
	char request_appended;	// true if the request pointer is data which follows this struct
349
350
351
	char transmit_me;  // needs to be transmitted
};

352
struct reply {
353
354
	unsigned int type;
	unsigned int have_answer;
355
356
357
358
359
360
361
362
363
364
365
	union {
		struct {
			u32 addrcount;
			u32 addresses[MAX_ADDRS];
		} a;
		struct {
			char name[HOST_NAME_MAX];
		} ptr;
	} data;
};

366
struct nameserver {
367
	int socket;	 // a connected UDP socket
368
369
370
371
372
373
	u32 address;
	int failed_times;  // number of times which we have given this server a chance
	int timedout;  // number of times in a row a request has timed out
	struct event event;
	// these objects are kept in a circular list
	struct nameserver *next, *prev;
374
375
	struct event timeout_event; // used to keep the timeout for
								// when we next probe this server.
376
377
								// Valid if state == 0
	char state;	 // zero if we think that this server is down
378
	char choaked;  // true if we have an EAGAIN from this server's socket
379
	char write_waiting;	 // true if we are waiting for EV_WRITE events
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
};

static struct request *req_head = NULL, *req_waiting_head = NULL;
static struct nameserver *server_head = NULL;

// The number of good nameservers that we have
static int global_good_nameservers = 0;

// inflight requests are contained in the req_head list
// and are actually going out across the network
static int global_requests_inflight = 0;
// requests which aren't inflight are in the waiting list
// and are counted here
static int global_requests_waiting = 0;

static int global_max_requests_inflight = 64;

397
static struct timeval global_timeout = {3, 0};	// 3 seconds
398
399
static int global_max_reissues = 1;	// a reissue occurs when we get some errors from the server
static int global_max_retransmits = 3;  // number of times we'll retransmit a request which timed out
400
401
402
403
404
405
406
407
// number of timeouts in a row before we consider this server to be down
static int global_max_nameserver_timeout = 3;

// These are the timeout values for nameservers. If we find a nameserver is down
// we try to probe it at intervals as given below. Values are in seconds.
static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
static const int global_nameserver_timeouts_length = sizeof(global_nameserver_timeouts)/sizeof(struct timeval);

408
const char *const evdns_error_strings[] = {"no error", "The name server was unable to interpret the query", "The name server suffered an internal error", "The requested domain name does not exist", "The name server refused to reply to the request"};
409

410
static struct nameserver *nameserver_pick(void);
411
static void evdns_request_insert(struct request *req, struct request **head);
412
static void nameserver_ready_callback(int fd, short events, void *arg);
413
414
static int evdns_transmit(void);
static int evdns_request_transmit(struct request *req);
415
416
417
static void nameserver_send_probe(struct nameserver *const ns);
static void search_request_finished(struct request *const);
static int search_try_next(struct request *const req);
418
419
static int search_request_new(int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
static void evdns_requests_pump_waiting_queue(void);
420
static u16 transaction_id_pick(void);
421
static struct request *request_new(int type, const char *name, int flags, evdns_callback_type, void *ptr);
422
423
static void request_submit(struct request *req);

424
425
#ifdef MS_WINDOWS
static int
426
427
last_error(int sock)
{
428
429
430
431
	int optval, optvallen=sizeof(optval);
	int err = WSAGetLastError();
	if (err == WSAEWOULDBLOCK && sock >= 0) {
		if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
432
					   &optvallen))
433
434
435
436
437
438
439
440
			return err;
		if (optval)
			return optval;
	}
	return err;

}
static int
441
442
error_is_eagain(int err)
{
443
444
	return err == EAGAIN || err == WSAEWOULDBLOCK;
}
445
static int
446
447
inet_aton(const char *c, struct in_addr *addr)
{
448
449
450
451
452
453
454
455
456
457
	uint32_t r;
	if (strcmp(c, "255.255.255.255") == 0) {
		addr->s_addr = 0xffffffffu;
	} else {
		r = inet_addr(c);
		if (r == INADDR_NONE)
			return 0;
		addr->s_addr = r;
	}
	return 1;
458
}
459
#define CLOSE_SOCKET(x) closesocket(x)
460
461
#else
#define last_error(sock) (errno)
462
#define error_is_eagain(err) ((err) == EAGAIN)
463
#define CLOSE_SOCKET(x) close(x)
464
465
#endif

466
467
468
#define ISSPACE(c) isspace((int)(unsigned char)(c))
#define ISDIGIT(c) isdigit((int)(unsigned char)(c))

469
470
#ifndef NDEBUG
static const char *
471
472
debug_ntoa(u32 address)
{
473
474
475
	static char buf[32];
	u32 a = ntohl(address);
	sprintf(buf, "%d.%d.%d.%d",
476
477
478
479
			(int)(u8)((a>>24)&0xff),
			(int)(u8)((a>>16)&0xff),
			(int)(u8)((a>>8 )&0xff),
			(int)(u8)((a	)&0xff));
480
481
482
483
	return buf;
}
#endif

484
static evdns_debug_log_fn_type evdns_log_fn = NULL;
485
486

void
487
488
489
evdns_set_log_fn(evdns_debug_log_fn_type fn)
{
	evdns_log_fn = fn;
490
491
}

492
#ifdef __GNUC__
493
#define EVDNS_LOG_CHECK	__attribute__ ((format(printf, 2, 3)))
494
#else
495
#define EVDNS_LOG_CHECK
496
497
#endif

498
static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
499
static void
500
_evdns_log(int warn, const char *fmt, ...) {
501
502
	va_list args;
	static char buf[512];
503
	if (!evdns_log_fn)
504
505
		return;
	va_start(args,fmt);
506
#ifdef MS_WINDOWS
507
	_vsnprintf(buf, sizeof(buf), fmt, args);
508
#else
509
	vsnprintf(buf, sizeof(buf), fmt, args);
510
#endif
511
	buf[sizeof(buf)-1] = '\0';
512
	evdns_log_fn(warn, buf);
513
	va_end(args);
514
515
}

516
#define log _evdns_log
517

518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
// This walks the list of inflight requests to find the
// one with a matching transaction id. Returns NULL on
// failure
static struct request *
request_find_from_trans_id(u16 trans_id) {
	struct request *req = req_head, *const started_at = req_head;

	if (req) {
		do {
			if (req->trans_id == trans_id) return req;
			req = req->next;
		} while (req != started_at);
	}

	return NULL;
}

// a libevent callback function which is called when a nameserver
// has gone down and we want to test if it has came back to life yet
static void
nameserver_prod_callback(int fd, short events, void *arg) {
	struct nameserver *const ns = (struct nameserver *) arg;
540
541
	(void)fd;
	(void)events;
542
543
544
545
546
547
548
549
550

	nameserver_send_probe(ns);
}

// a libevent callback which is called when a nameserver probe (to see if
// it has come back to life) times out. We increment the count of failed_times
// and wait longer to send the next probe packet.
static void
nameserver_probe_failed(struct nameserver *const ns) {
551
	const struct timeval * timeout;
552
	(void) evtimer_del(&ns->timeout_event);
553
554
555
556
557
558
	if (ns->state == 1) {
		// This can happen if the nameserver acts in a way which makes us mark
		// it as bad and then starts sending good replies.
		return;
	}

559
	timeout =
560
561
		&global_nameserver_timeouts[MIN(ns->failed_times,
										global_nameserver_timeouts_length - 1)];
562
563
564
	ns->failed_times++;

	evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
565
	if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
566
		log(EVDNS_LOG_WARN,
567
568
569
570
			"Error from libevent when adding timer event for %s",
			debug_ntoa(ns->address));
		// ???? Do more?
	}
571
572
573
574
575
}

// called when a nameserver has been deemed to have failed. For example, too
// many packets have timed out etc
static void
576
nameserver_failed(struct nameserver *const ns, const char *msg) {
577
	struct request *req, *started_at;
578
579
580
581
	// if this nameserver has already been marked as failed
	// then don't do anything
	if (!ns->state) return;

582
	log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
583
			debug_ntoa(ns->address), msg);
584
585
586
	global_good_nameservers--;
	assert(global_good_nameservers >= 0);
	if (global_good_nameservers == 0) {
587
		log(EVDNS_LOG_WARN, "All nameservers have failed");
588
589
590
591
592
593
	}

	ns->state = 0;
	ns->failed_times = 1;

	evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
594
	if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
595
		log(EVDNS_LOG_WARN,
596
597
598
599
			"Error from libevent when adding timer event for %s",
			debug_ntoa(ns->address));
		// ???? Do more?
	}
600
601
602
603

	// walk the list of inflight requests to see if any can be reassigned to
	// a different server. Requests in the waiting queue don't have a
	// nameserver assigned yet
604
605

	// if we don't have *any* good nameservers then there's no point
606
607
608
	// trying to reassign requests to one
	if (!global_good_nameservers) return;

609
610
	req = req_head;
	started_at = req_head;
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
	if (req) {
		do {
			if (req->tx_count == 0 && req->ns == ns) {
				// still waiting to go out, can be moved
				// to another server
				req->ns = nameserver_pick();
			}
			req = req->next;
		} while (req != started_at);
	}
}

static void
nameserver_up(struct nameserver *const ns) {
	if (ns->state) return;
626
	log(EVDNS_LOG_WARN, "Nameserver %s is back up",
627
		debug_ntoa(ns->address));
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
	evtimer_del(&ns->timeout_event);
	ns->state = 1;
	ns->failed_times = 0;
	global_good_nameservers++;
}

static void
request_trans_id_set(struct request *const req, const u16 trans_id) {
	req->trans_id = trans_id;
	*((u16 *) req->request) = htons(trans_id);
}

// Called to remove a request from a list and dealloc it.
// head is a pointer to the head of the list it should be
// removed from or NULL if the request isn't in a list.
static void
request_finished(struct request *const req, struct request **head) {
	if (head) {
		if (req->next == req) {
			// only item in the list
			*head = NULL;
		} else {
			req->next->prev = req->prev;
			req->prev->next = req->next;
			if (*head == req) *head = req->next;
		}
	}

656
	log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
657
		(unsigned long) req);
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
	evtimer_del(&req->timeout_event);

	search_request_finished(req);
	global_requests_inflight--;

	if (!req->request_appended) {
		// need to free the request data on it's own
		free(req->request);
	} else {
		// the request data is appended onto the header
		// so everything gets free()ed when we:
	}

	free(req);

673
	evdns_requests_pump_waiting_queue();
674
675
676
677
678
679
}

// This is called when a server returns a funny error code.
// We try the request again with another server.
//
// return:
680
681
//	 0 ok
//	 1 failed/reissue is pointless
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
static int
request_reissue(struct request *req) {
	const struct nameserver *const last_ns = req->ns;
	// the last nameserver should have been marked as failing
	// by the caller of this function, therefore pick will try
	// not to return it
	req->ns = nameserver_pick();
	if (req->ns == last_ns) {
		// ... but pick did return it
		// not a lot of point in trying again with the
		// same server
		return 1;
	}

	req->reissue_count++;
	req->tx_count = 0;
	req->transmit_me = 1;

	return 0;
}

// this function looks for space on the inflight queue and promotes
// requests from the waiting queue if it can.
static void
706
evdns_requests_pump_waiting_queue(void) {
707
	while (global_requests_inflight < global_max_requests_inflight &&
708
		global_requests_waiting) {
709
		struct request *req;
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
		// move a request from the waiting queue to the inflight queue
		assert(req_waiting_head);
		if (req_waiting_head->next == req_waiting_head) {
			// only one item in the queue
			req = req_waiting_head;
			req_waiting_head = NULL;
		} else {
			req = req_waiting_head;
			req->next->prev = req->prev;
			req->prev->next = req->next;
			req_waiting_head = req->next;
		}

		global_requests_waiting--;
		global_requests_inflight++;
725

726
727
728
		req->ns = nameserver_pick();
		request_trans_id_set(req, transaction_id_pick());

729
730
731
		evdns_request_insert(req, &req_head);
		evdns_request_transmit(req);
		evdns_transmit();
732
733
734
	}
}

735
736
737
738
739
740
static void
reply_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply) {
	switch (req->request_type) {
	case TYPE_A:
		if (reply)
			req->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
741
742
743
							   reply->data.a.addrcount, ttl,
						 reply->data.a.addresses,
							   req->user_pointer);
744
745
746
747
748
		else
			req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
		return;
	case TYPE_PTR:
		if (reply) {
749
			char *name = reply->data.ptr.name;
750
			req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
751
752
							   &name, req->user_pointer);
		} else {
753
			req->user_callback(err, 0, 0, 0, NULL,
754
755
756
							   req->user_pointer);
		}
		return;
757
758
759
760
	}
	assert(0);
}

761
762
// this processes a parsed reply packet
static void
763
reply_handle(struct request *const req,
764
		 u16 flags, u32 ttl, struct reply *reply) {
765
766
767
	int error;
	static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};

768
	if (flags & 0x020f || !reply || !reply->have_answer) {
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
		// there was an error
		if (flags & 0x0200) {
			error = DNS_ERR_TRUNCATED;
		} else {
			u16 error_code = (flags & 0x000f) - 1;
			if (error_code > 4) {
				error = DNS_ERR_UNKNOWN;
			} else {
				error = error_codes[error_code];
			}
		}

		switch(error) {
		case DNS_ERR_SERVERFAILED:
		case DNS_ERR_NOTIMPL:
		case DNS_ERR_REFUSED:
			// we regard these errors as marking a bad nameserver
			if (req->reissue_count < global_max_reissues) {
787
788
789
790
				char msg[64];
				snprintf(msg, sizeof(msg), "Bad response %d",
					 error);
				nameserver_failed(req->ns, msg);
791
792
793
794
795
796
797
798
				if (!request_reissue(req)) return;
			}
			break;
		default:
			// we got a good reply from the nameserver
			nameserver_up(req->ns);
		}

799
		if (req->search_state && req->request_type != TYPE_PTR) {
800
801
802
803
804
805
806
807
808
			// if we have a list of domains to search in, try the next one
			if (!search_try_next(req)) {
				// a new request was issued so this request is finished and
				// the user callback will be made when that request (or a
				// child of it) finishes.
				request_finished(req, &req_head);
				return;
			}
		}
809

810
		// all else failed. Pass the failure up
811
		reply_callback(req, 0, error, NULL);
812
813
814
		request_finished(req, &req_head);
	} else {
		// all ok, tell the user
815
		reply_callback(req, ttl, 0, reply);
816
817
818
819
820
		nameserver_up(req->ns);
		request_finished(req, &req_head);
	}
}

821
static inline int
822
name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
	int name_end = -1;
	int j = *idx;
#define GET32(x) do { if (j + 4 > length) return -1; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0);
#define GET16(x) do { if (j + 2 > length) return -1; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0);
#define GET8(x) do { if (j >= length) return -1; x = packet[j++]; } while(0);

	char *cp = name_out;
	const char *const end = name_out + name_out_len;

	// Normally, names are a series of length prefixed strings terminated
	// with a length of 0 (the lengths are u8's < 63).
	// However, the length can start with a pair of 1 bits and that
	// means that the next 14 bits are a pointer within the current
	// packet.

	for(;;) {
		u8 label_len;
840
		if (j >= length) return -1;
841
842
843
844
845
		GET8(label_len);
		if (!label_len) break;
		if (label_len & 0xc0) {
			u8 ptr_low;
			GET8(ptr_low);
846
847
848
			if (name_end < 0) name_end = j;
			j = (((int)label_len & 0x3f) << 8) + ptr_low;
			if (j < 0 || j >= length) return -1;
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
			continue;
		}
		if (label_len > 63) return -1;
		if (cp != name_out) {
			if (cp + 1 >= end) return -1;
			*cp++ = '.';
		}
		if (cp + label_len >= end) return -1;
		memcpy(cp, packet + j, label_len);
		cp += label_len;
		j += label_len;
	}
	if (cp >= end) return -1;
	*cp = '\0';
	if (name_end < 0)
		*idx = j;
	else
		*idx = name_end;
	return 0;
}

870
// parses a raw packet from the wire
871
static int
872
reply_parse(u8 *packet, int length) {
873
874
	int j = 0;	// index into packet
	u16 _t;	 // used by the macros
875
	u32 _t32;  // used by the macros
876
	char tmp_name[256]; // used by the macros
877
878
879

	u16 trans_id, flags, questions, answers, authority, additional, datalength;
	u32 ttl, ttl_r = 0xffffffff;
880
881
	struct reply reply;
	struct request *req;
882
	unsigned int i;
883
884
885
886
887
888
889
890

	GET16(trans_id);
	GET16(flags);
	GET16(questions);
	GET16(answers);
	GET16(authority);
	GET16(additional);

891
892
893
	req = request_find_from_trans_id(trans_id);
	if (!req) return -1;
	// XXXX should the other return points also call reply_handle? -NM
894
	// log("reqparse: trans was %d\n", (int)trans_id);
895
896
897
898

	memset(&reply, 0, sizeof(reply));

	if (!(flags & 0x8000)) return -1;  // must be an answer
899
900
	if (flags & 0x020f) {
		// there was an error
901
902
		reply_handle(req, flags, 0, NULL);
		return -1;
903
904
	}
	// if (!answers) return;  // must have an answer of some form
905

906
	// This macro skips a name in the DNS reply.
907
908
909
910
#define SKIP_NAME														\
	do { tmp_name[0] = '\0';											\
		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0) \
			return -1;													\
911
912
913
	} while(0);

	reply.type = req->request_type;
914
915
916
917

	// skip over each question in the reply
	for (i = 0; i < questions; ++i) {
		// the question looks like
918
		//	 <label:name><u16:type><u16:class>
919
920
		SKIP_NAME;
		j += 4;
921
		if (j >= length) return -1;
922
923
924
925
926
927
	}

	// now we have the answer section which looks like
	// <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
	for (i = 0; i < answers; ++i) {
		u16 type, class;
928
		//int pre = j;
929

930
931
		// XXX I'd be more comfortable if we actually checked the name
		// here. -NM
932
933
934
935
936
937
		SKIP_NAME;
		GET16(type);
		GET16(class);
		GET32(ttl);
		GET16(datalength);

938
		// log("@%d, Name %s, type %d, class %d, j=%d", pre, tmp_name, (int)type, (int)class, j);
939

940
		if (type == TYPE_A && class == CLASS_INET) {
941
942
943
944
			int addrcount, addrtocopy;
			if (req->request_type != TYPE_A) {
				j += datalength; continue;
			}
945
			// XXXX do something sane with malformed A answers.
946
			addrcount = datalength >> 2;  // each IP address is 4 bytes
947
			addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
948
949
			ttl_r = MIN(ttl_r, ttl);
			// we only bother with the first four addresses.
950
951
			if (j + 4*addrtocopy > length) return -1;
			memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
952
				   packet + j, 4*addrtocopy);
953
			j += 4*addrtocopy;
954
955
956
957
958
959
960
961
			reply.data.a.addrcount += addrtocopy;
			reply.have_answer = 1;
			if (reply.data.a.addrcount == MAX_ADDRS) break;
		} else if (type == TYPE_PTR && class == CLASS_INET) {
			if (req->request_type != TYPE_PTR) {
				j += datalength; continue;
			}
			if (name_parse(packet, length, &j, reply.data.ptr.name,
962
						   sizeof(reply.data.ptr.name))<0)
963
964
965
966
967
968
969
970
971
				return -1;
			reply.have_answer = 1;
			break;
		} else if (type == TYPE_AAAA && class == CLASS_INET) {
			if (req->request_type != TYPE_AAAA) {
				j += datalength; continue;
			}
			// XXXX Implement me. -NM
			j += datalength;
972
		} else {
973
974
975
976
977
			// skip over any other type of resource
			j += datalength;
		}
	}

978
979
	reply_handle(req, flags, ttl_r, &reply);
	return 0;
980
981
982
983
984
985
986
987
#undef SKIP_NAME
#undef GET32
#undef GET16
#undef GET8
}

// Try to choose a strong transaction id which isn't already in flight
static u16
988
transaction_id_pick(void) {
989
	for (;;) {
990
		const struct request *req = req_head, *started_at;
991
992
993
#ifdef DNS_USE_CPU_CLOCK_FOR_ID
		struct timespec ts;
		const u16 trans_id = ts.tv_nsec & 0xffff;
994
995
		if (clock_gettime(CLOCK_MONOTONIC, &ts))
			abort();
996
997
998
999
1000
#endif

#ifdef DNS_USE_GETTIMEOFDAY_FOR_ID
		struct timeval tv;
		const u16 trans_id = tv.tv_usec & 0xffff;