eventdns.c 89.1 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
 *	 - Replace all externally visible magic numbers with #defined constants.
 *	 - Write documentation for APIs of all external functions.
12
 */
13

14
15
/* Async DNS Library
 * Adam Langley <agl@imperialviolet.org>
16
 * Public Domain code
17
18
19
20
21
22
23
 *
 * 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:
24
 *	Parts developed by Adam Langley <agl@imperialviolet.org>
25
26
27
28
29
30
31
32
33
34
35
 *
 * 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
 */

#include "eventdns_tor.h"
36
#include <sys/types.h>
37
/* #define NDEBUG */
38
39
40
41
42

#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
43
#error Please see the documentation.
44
45
46
47
#endif
#endif
#endif

48
/* #define _POSIX_C_SOURCE 200507 */
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#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

#include <string.h>
69
#ifdef HAVE_FCNTL_H
70
#include <fcntl.h>
71
72
#endif
#ifdef HAVE_SYS_TIME_H
73
#include <sys/time.h>
74
#endif
75
76
77
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
78
79
80
81
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
82
#ifdef HAVE_UNISTD_H
83
#include <unistd.h>
84
85
#endif
#ifdef HAVE_LIMITS_H
86
#include <limits.h>
87
#endif
88
#include <sys/stat.h>
89
#include <ctype.h>
90
91
#include <stdio.h>
#include <stdarg.h>
92

93
#include "eventdns.h"
94
95
96
97
98
99
100
101
102
103
#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

104
#ifdef HAVE_NETINET_IN6_H
105
#include <netinet6/in6.h>
106
107
#endif

108
109
110
111
#ifdef WIN32
typedef int socklen_t;
#endif

112
113
#define EVDNS_LOG_DEBUG 0
#define EVDNS_LOG_WARN 1
114

115
116
117
118
119
120
121
122
#ifndef HOST_NAME_MAX
#define HOST_NAME_MAX 255
#endif

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

123
/* for debugging possible memory leaks. */
124
125
126
127
128
#define malloc(x) tor_malloc(x)
#define realloc(x,y) tor_realloc((x),(y))
#define free(x) tor_free(x)
#define _free(x) _tor_free(x)

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

132
#if 0
133
#ifdef __USE_ISOC99B
134
/* libevent doesn't work without this */
135
136
137
typedef uint8_t u_char;
typedef unsigned int uint;
#endif
138
#endif
139
140
141
142
143
#include <event.h>

#define u64 uint64_t
#define u32 uint32_t
#define u16 uint16_t
144
#define u8	uint8_t
145

146
147
#define MAX_ADDRS 4	 /* maximum number of addresses from a single packet */
/* which we bother recording */
148

149
150
151
#define TYPE_A		EVDNS_TYPE_A
#define TYPE_PTR	EVDNS_TYPE_PTR
#define TYPE_AAAA	EVDNS_TYPE_AAAA
152

153
#define CLASS_INET	EVDNS_CLASS_INET
154

155
156
#define CLEAR(x) do { memset((x), 0, sizeof(*(x))); } while(0)

157
struct request {
158
	u8 *request; /* the dns packet data */
159
	unsigned int request_len;
160
	int reissue_count;
161
162
163
	int tx_count;  /* the number of times that this packet has been sent */
	unsigned int request_type; /* TYPE_PTR or TYPE_A */
	void *user_pointer;	 /* the pointer given to us for this request */
164
	evdns_callback_type user_callback;
165
	struct nameserver *ns;	/* the server which we last sent it */
166

167
	/* elements used by the searching code */
168
169
	int search_index;
	struct search_state *search_state;
170
	char *search_origname;	/* needs to be free()ed */
171
172
	int search_flags;

173
	/* these objects are kept in a circular list */
174
175
176
177
	struct request *next, *prev;

	struct event timeout_event;

178
179
180
	u16 trans_id;  /* the transaction id */
	char request_appended;	/* true if the request pointer is data which follows this struct */
	char transmit_me;  /* needs to be transmitted */
181
182
};

183
184
#ifndef HAVE_STRUCT_IN6_ADDR
struct in6_addr {
185
	u8 s6_addr[16];
186
187
188
};
#endif

189
struct reply {
190
191
	unsigned int type;
	unsigned int have_answer;
192
193
194
195
196
	union {
		struct {
			u32 addrcount;
			u32 addresses[MAX_ADDRS];
		} a;
197
198
199
200
		struct {
			u32 addrcount;
			struct in6_addr addresses[MAX_ADDRS];
		} aaaa;
201
202
203
204
205
206
		struct {
			char name[HOST_NAME_MAX];
		} ptr;
	} data;
};

207
struct nameserver {
208
	int socket;	 /* a connected UDP socket */
209
	struct sockaddr_storage address;
210
211
	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 */
212
	struct event event;
213
	/* these objects are kept in a circular list */
214
	struct nameserver *next, *prev;
215
216
217
218
219
220
	struct event timeout_event; /* used to keep the timeout for */
								/* when we next probe this server. */
								/* Valid if state == 0 */
	char state;	 /* zero if we think that this server is down */
	char choked;  /* true if we have an EAGAIN from this server's socket */
	char write_waiting;	 /* true if we are waiting for EV_WRITE events */
221
222
223
224
225
};

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

226
227
/* Represents a local port where we're listening for DNS requests. Right now, */
/* only UDP is supported. */
228
struct evdns_server_port {
229
230
231
232
233
234
235
236
	int socket; /* socket we use to read queries and write replies. */
	int refcnt; /* reference count. */
	char choked; /* Are we currently blocked from writing? */
	char closing; /* Are we trying to close this port, pending writes? */
	evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
	void *user_data; /* Opaque pointer passed to user_callback */
	struct event event; /* Read/write event */
	/* circular list of replies that we want to write. */
237
238
239
	struct server_request *pending_replies;
};

240
/* Represents part of a reply being built.	(That is, a single RR.) */
241
struct server_reply_item {
242
243
244
245
246
247
248
249
	struct server_reply_item *next; /* next item in sequence. */
	char *name; /* name part of the RR */
	u16 type : 16; /* The RR type */
	u16 class : 16; /* The RR class (usually CLASS_INET) */
	u32 ttl; /* The RR TTL */
	char is_name; /* True iff data is a label */
	u16 datalen; /* Length of data; -1 if data is a label */
	void *data; /* The contents of the RR */
250
251
};

252
253
/* Represents a request that we've received as a DNS server, and holds */
/* the components of the reply as we're constructing it. */
254
struct server_request {
255
256
257
	/* Pointers to the next and previous entries on the list of replies */
	/* that we're waiting to write.	 Only set if we have tried to respond */
	/* and gotten EAGAIN. */
258
259
260
	struct server_request *next_pending;
	struct server_request *prev_pending;

261
262
263
264
	u16 trans_id; /* Transaction id. */
	struct evdns_server_port *port; /* Which port received this request on? */
	struct sockaddr_storage addr; /* Where to send the response */
	socklen_t addrlen; /* length of addr */
265

266
267
268
	int n_answer; /* how many answer RRs have been set? */
	int n_authority; /* how many authority RRs have been set? */
	int n_additional; /* how many additional RRs have been set? */
269

270
271
272
	struct server_reply_item *answer; /* linked list of answer RRs */
	struct server_reply_item *authority; /* linked list of authority RRs */
	struct server_reply_item *additional; /* linked list of additional RRs */
273

274
275
	/* Constructed response.  Only set once we're ready to send a reply. */
	/* Once this is set, the RR fields are cleared, and no more should be set. */
276
277
278
	char *response;
	size_t response_len;

279
	/* Caller-visible fields: flags, questions. */
280
	struct evdns_server_request base;
281
};
282

283
/* helper macro */
284
285
#define OFFSET_OF(st, member) ((off_t) (((char*)&((st*)0)->member)-(char*)0))

286
287
/* Given a pointer to an evdns_server_request, get the corresponding */
/* server_request. */
288
289
290
291
#define TO_SERVER_REQUEST(base_ptr)										\
	((struct server_request*)											\
	 (((char*)(base_ptr) - OFFSET_OF(struct server_request, base))))

292
/* The number of good nameservers that we have */
293
294
static int global_good_nameservers = 0;

295
296
/* inflight requests are contained in the req_head list */
/* and are actually going out across the network */
297
static int global_requests_inflight = 0;
298
299
/* requests which aren't inflight are in the waiting list */
/* and are counted here */
300
301
302
303
static int global_requests_waiting = 0;

static int global_max_requests_inflight = 64;

304
305
306
307
static struct timeval global_timeout = {5, 0};	/* 5 seconds */
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 */
/* number of timeouts in a row before we consider this server to be down */
308
309
static int global_max_nameserver_timeout = 3;

310
311
312
/* DOCDOC */
static int global_randomize_case = 1;

313
314
/* 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. */
315
static const struct timeval global_nameserver_timeouts[] = {{10, 0}, {60, 0}, {300, 0}, {900, 0}, {3600, 0}};
316
static const int global_nameserver_timeouts_length = (int)(sizeof(global_nameserver_timeouts)/sizeof(struct timeval));
317

318
static struct nameserver *nameserver_pick(void);
319
static void evdns_request_insert(struct request *req, struct request **head);
320
static void nameserver_ready_callback(int fd, short events, void *arg);
321
322
static int evdns_transmit(void);
static int evdns_request_transmit(struct request *req);
323
324
325
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);
326
327
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);
328
static u16 transaction_id_pick(void);
329
static struct request *request_new(int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
330
331
static void request_submit(struct request *req);

332
333
334
335
336
static int server_request_free(struct server_request *req);
static void server_request_free_answers(struct server_request *req);
static void server_port_free(struct evdns_server_port *port);
static void server_port_ready_callback(int fd, short events, void *arg);

337
338
static int strtoint(const char *const str);

339
#ifdef WIN32
340
static int
341
342
last_error(int sock)
{
343
344
345
346
	int optval, optvallen=sizeof(optval);
	int err = WSAGetLastError();
	if (err == WSAEWOULDBLOCK && sock >= 0) {
		if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
347
					   &optvallen))
348
349
350
351
352
353
354
355
			return err;
		if (optval)
			return optval;
	}
	return err;

}
static int
356
357
error_is_eagain(int err)
{
358
359
	return err == EAGAIN || err == WSAEWOULDBLOCK;
}
360
static int
361
362
inet_aton(const char *c, struct in_addr *addr)
{
363
364
365
366
367
368
369
370
371
372
	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;
373
}
374
#define CLOSE_SOCKET(x) closesocket(x)
375
376
#else
#define last_error(sock) (errno)
377
#define error_is_eagain(err) ((err) == EAGAIN)
378
#define CLOSE_SOCKET(x) close(x)
379
380
#endif

381
382
#define ISSPACE(c) isspace((int)(unsigned char)(c))
#define ISDIGIT(c) isdigit((int)(unsigned char)(c))
383
384
385
#define ISALPHA(c) isalpha((int)(unsigned char)(c))
#define TOLOWER(c) (char)tolower((int)(unsigned char)(c))
#define TOUPPER(c) (char)toupper((int)(unsigned char)(c))
386

387
388
#ifndef NDEBUG
static const char *
389
390
debug_ntoa(u32 address)
{
391
392
	static char buf[32];
	u32 a = ntohl(address);
393
	snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
394
395
396
397
			(int)(u8)((a>>24)&0xff),
			(int)(u8)((a>>16)&0xff),
			(int)(u8)((a>>8 )&0xff),
			(int)(u8)((a	)&0xff));
398
399
	return buf;
}
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
static const char *
debug_ntop(const struct sockaddr *sa)
{
	if (sa->sa_family == AF_INET) {
		struct sockaddr_in *sin = (struct sockaddr_in *) sa;
		return debug_ntoa(ntohl(sin->sin_addr.s_addr));
	}
	if (sa->sa_family == AF_INET6) {
		/* Tor-specific.  In libevent, add more check code. */
		static char buf[128];
		struct sockaddr_in6 *sin = (struct sockaddr_in6 *) sa;
		tor_inet_ntop(AF_INET6, &sin->sin6_addr, buf, sizeof(buf));
		return buf;
	}
	return "<unknown>";
}
416
417
#endif

418
static evdns_debug_log_fn_type evdns_log_fn = NULL;
419
420

void
421
422
423
evdns_set_log_fn(evdns_debug_log_fn_type fn)
{
	evdns_log_fn = fn;
424
425
}

426
#ifdef __GNUC__
427
#define EVDNS_LOG_CHECK	__attribute__ ((format(printf, 2, 3)))
428
#else
429
#define EVDNS_LOG_CHECK
430
431
#endif

432
static void _evdns_log(int warn, const char *fmt, ...) EVDNS_LOG_CHECK;
433
static void
434
435
_evdns_log(int warn, const char *fmt, ...)
{
436
437
	va_list args;
	static char buf[512];
438
	if (!evdns_log_fn)
439
440
		return;
	va_start(args,fmt);
441
#ifdef WIN32
442
	_vsnprintf(buf, sizeof(buf), fmt, args);
443
#else
444
	vsnprintf(buf, sizeof(buf), fmt, args);
445
#endif
446
	buf[sizeof(buf)-1] = '\0';
447
	evdns_log_fn(warn, buf);
448
	va_end(args);
449
450
}

451
#define log _evdns_log
452

453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
static int
sockaddr_eq(const struct sockaddr *sa1, const struct sockaddr *sa2,
			int include_port)
{
	if (sa1->sa_family != sa2->sa_family)
		return 0;
	if (sa1->sa_family == AF_INET) {
		const struct sockaddr_in *sin1, *sin2;
		sin1 = (const struct sockaddr_in *)sa1;
		sin2 = (const struct sockaddr_in *)sa2;
		if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr)
			return 0;
		else if (include_port && sin1->sin_port != sin2->sin_port)
			return 0;
		else
			return 1;
	}
#ifdef AF_INET6
	if (sa1->sa_family == AF_INET6) {
		const struct sockaddr_in6 *sin1, *sin2;
		sin1 = (const struct sockaddr_in6 *)sa1;
		sin2 = (const struct sockaddr_in6 *)sa2;
		if (memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16))
			return 0;
		else if (include_port && sin1->sin6_port != sin2->sin6_port)
			return 0;
		else
			return 1;
	}
#endif
	return 1;
}

486
487
488
/* This walks the list of inflight requests to find the */
/* one with a matching transaction id. Returns NULL on */
/* failure */
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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;
}

503
504
/* 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 */
505
506
507
static void
nameserver_prod_callback(int fd, short events, void *arg) {
	struct nameserver *const ns = (struct nameserver *) arg;
508
509
	(void)fd;
	(void)events;
510
511
512
513

	nameserver_send_probe(ns);
}

514
515
516
/* 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. */
517
518
static void
nameserver_probe_failed(struct nameserver *const ns) {
519
	const struct timeval * timeout;
520
	(void) evtimer_del(&ns->timeout_event);
521
	CLEAR(&ns->timeout_event);
522
	if (ns->state == 1) {
523
524
		/* This can happen if the nameserver acts in a way which makes us mark */
		/* it as bad and then starts sending good replies. */
525
526
527
		return;
	}

528
	timeout =
529
530
		&global_nameserver_timeouts[MIN(ns->failed_times,
										global_nameserver_timeouts_length - 1)];
531
532
533
	ns->failed_times++;

	evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
534
	if (evtimer_add(&ns->timeout_event, (struct timeval *) timeout) < 0) {
535
		log(EVDNS_LOG_WARN,
536
			"Error from libevent when adding timer event for %s",
537
			debug_ntop((struct sockaddr *)&ns->address));
538
		/* ???? Do more? */
539
	}
540
541
}

542
543
/* called when a nameserver has been deemed to have failed. For example, too */
/* many packets have timed out etc */
544
static void
545
nameserver_failed(struct nameserver *const ns, const char *msg) {
546
	struct request *req, *started_at;
547
548
	/* if this nameserver has already been marked as failed */
	/* then don't do anything */
549
550
	if (!ns->state) return;

551
	log(EVDNS_LOG_WARN, "Nameserver %s has failed: %s",
552
		debug_ntop((struct sockaddr *)&ns->address), msg);
553
554
555
	global_good_nameservers--;
	assert(global_good_nameservers >= 0);
	if (global_good_nameservers == 0) {
556
		log(EVDNS_LOG_WARN, "All nameservers have failed");
557
558
559
560
561
562
	}

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

	evtimer_set(&ns->timeout_event, nameserver_prod_callback, ns);
563
	if (evtimer_add(&ns->timeout_event, (struct timeval *) &global_nameserver_timeouts[0]) < 0) {
564
		log(EVDNS_LOG_WARN,
565
			"Error from libevent when adding timer event for %s",
566
			debug_ntop((struct sockaddr *)&ns->address));
567
		/* ???? Do more? */
568
	}
569

570
571
572
	/* 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 */
573

574
575
	/* if we don't have *any* good nameservers then there's no point */
	/* trying to reassign requests to one */
576
577
	if (!global_good_nameservers) return;

578
579
	req = req_head;
	started_at = req_head;
580
581
582
	if (req) {
		do {
			if (req->tx_count == 0 && req->ns == ns) {
583
584
				/* still waiting to go out, can be moved */
				/* to another server */
585
586
587
588
589
590
591
592
593
594
				req->ns = nameserver_pick();
			}
			req = req->next;
		} while (req != started_at);
	}
}

static void
nameserver_up(struct nameserver *const ns) {
	if (ns->state) return;
595
	log(EVDNS_LOG_WARN, "Nameserver %s is back up",
596
		debug_ntop((struct sockaddr *)&ns->address));
597
	evtimer_del(&ns->timeout_event);
598
	CLEAR(&ns->timeout_event);
599
600
	ns->state = 1;
	ns->failed_times = 0;
601
	ns->timedout = 0;
602
603
604
605
606
607
608
609
610
	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);
}

611
612
613
/* 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. */
614
615
616
617
static void
request_finished(struct request *const req, struct request **head) {
	if (head) {
		if (req->next == req) {
618
			/* only item in the list */
619
620
621
622
623
624
625
626
			*head = NULL;
		} else {
			req->next->prev = req->prev;
			req->prev->next = req->next;
			if (*head == req) *head = req->next;
		}
	}

627
	log(EVDNS_LOG_DEBUG, "Removing timeout for request %lx",
628
		(unsigned long) req);
629
	evtimer_del(&req->timeout_event);
630
	CLEAR(&req->timeout_event);
631
632
633
634
635

	search_request_finished(req);
	global_requests_inflight--;

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

643
	CLEAR(req);
644
	_free(req);
645

646
	evdns_requests_pump_waiting_queue();
647
648
}

649
650
651
652
653
654
/* This is called when a server returns a funny error code. */
/* We try the request again with another server. */
/* */
/* return: */
/* 0 ok */
/* 1 failed/reissue is pointless */
655
656
657
static int
request_reissue(struct request *req) {
	const struct nameserver *const last_ns = req->ns;
658
659
660
	/* the last nameserver should have been marked as failing */
	/* by the caller of this function, therefore pick will try */
	/* not to return it */
661
662
	req->ns = nameserver_pick();
	if (req->ns == last_ns) {
663
664
665
		/* ... but pick did return it */
		/* not a lot of point in trying again with the */
		/* same server */
666
667
668
669
670
671
672
673
674
675
		return 1;
	}

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

	return 0;
}

676
677
/* this function looks for space on the inflight queue and promotes */
/* requests from the waiting queue if it can. */
678
static void
679
evdns_requests_pump_waiting_queue(void) {
680
	while (global_requests_inflight < global_max_requests_inflight &&
681
		global_requests_waiting) {
682
		struct request *req;
683
		/* move a request from the waiting queue to the inflight queue */
684
685
		assert(req_waiting_head);
		if (req_waiting_head->next == req_waiting_head) {
686
			/* only one item in the queue */
687
688
689
690
691
692
693
694
695
696
697
			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++;
698

699
700
701
		req->ns = nameserver_pick();
		request_trans_id_set(req, transaction_id_pick());

702
703
704
		evdns_request_insert(req, &req_head);
		evdns_request_transmit(req);
		evdns_transmit();
705
706
707
	}
}

708
709
710
711
712
713
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,
714
							   reply->data.a.addrcount, ttl,
715
							   reply->data.a.addresses,
716
							   req->user_pointer);
717
718
719
720
721
		else
			req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
		return;
	case TYPE_PTR:
		if (reply) {
722
			char *name = reply->data.ptr.name;
723
			req->user_callback(DNS_ERR_NONE, DNS_PTR, 1, ttl,
724
725
							   &name, req->user_pointer);
		} else {
726
			req->user_callback(err, 0, 0, 0, NULL,
727
728
729
							   req->user_pointer);
		}
		return;
730
731
	case TYPE_AAAA:
		if (reply)
732
			req->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
733
734
735
736
737
							   reply->data.aaaa.addrcount, ttl,
							   reply->data.aaaa.addresses,
							   req->user_pointer);
		else
			req->user_callback(err, 0, 0, 0, NULL, req->user_pointer);
738
		return;
739
740
741
742
	}
	assert(0);
}

743
/* this processes a parsed reply packet */
744
static void
745
reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
746
747
748
	int error;
	static const int error_codes[] = {DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST, DNS_ERR_NOTIMPL, DNS_ERR_REFUSED};

749
	if (flags & 0x020f || !reply || !reply->have_answer) {
750
		/* there was an error */
751
752
753
754
755
756
757
758
759
760
761
762
763
764
		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_NOTIMPL:
		case DNS_ERR_REFUSED:
765
			/* we regard these errors as marking a bad nameserver */
766
			if (req->reissue_count < global_max_reissues) {
767
				char msg[64];
768
769
				snprintf(msg, sizeof(msg), "Bad response %d (%s)",
						 error, evdns_err_to_string(error));
770
				nameserver_failed(req->ns, msg);
771
772
773
				if (!request_reissue(req)) return;
			}
			break;
774
		case DNS_ERR_SERVERFAILED:
775
776
			/* rcode 2 (servfailed) sometimes means "we are broken" and
			 * sometimes (with some binds) means "that request was very
777
778
			 * confusing."  Treat this as a timeout, not a failure.
			 */
779
780
781
			/*XXXX refactor the parts of */
			log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver %s; "
				"will allow the request to time out.",
782
				debug_ntop((struct sockaddr *)&req->ns->address));
783
			break;
784
		default:
785
			/* we got a good reply from the nameserver */
786
787
788
			nameserver_up(req->ns);
		}

789
		if (req->search_state && req->request_type != TYPE_PTR) {
790
			/* if we have a list of domains to search in, try the next one */
791
			if (!search_try_next(req)) {
792
793
794
				/* 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. */
795
796
797
798
				request_finished(req, &req_head);
				return;
			}
		}
799

800
		/* all else failed. Pass the failure up */
801
		reply_callback(req, 0, error, NULL);
802
803
		request_finished(req, &req_head);
	} else {
804
		/* all ok, tell the user */
805
		reply_callback(req, ttl, 0, reply);
806
807
808
809
810
		nameserver_up(req->ns);
		request_finished(req, &req_head);
	}
}

811
static INLINE int
812
name_parse(u8 *packet, int length, int *idx, char *name_out, size_t name_out_len) {
813
814
	int name_end = -1;
	int j = *idx;
815
	int ptr_count = 0;
816
817
818
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&_t32, packet + j, 4); j += 4; x = ntohl(_t32); } while(0)
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&_t, packet + j, 2); j += 2; x = ntohs(_t); } while(0)
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while(0)
819
820
821
822

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

823
824
825
826
827
	/* 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. */
828
829
830

	for(;;) {
		u8 label_len;
831
		if (j >= length) return -1;
832
833
834
835
836
		GET8(label_len);
		if (!label_len) break;
		if (label_len & 0xc0) {
			u8 ptr_low;
			GET8(ptr_low);
837
838
			if (name_end < 0) name_end = j;
			j = (((int)label_len & 0x3f) << 8) + ptr_low;
839
			/* Make sure that the target offset is in-bounds. */
840
			if (j < 0 || j >= length) return -1;
841
842
843
			/* If we've jumped more times than there are characters in the
			 * message, we must have a loop. */
			if (++ptr_count > length) return -1;
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
			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;
863
864
 err:
	return -1;
865
866
}

867
/* parses a raw reply from a nameserver. */
868
static int
869
reply_parse(u8 *packet, int length) {
870
	int j = 0;	/* index into packet */
871
	int k;
872
873
	u16 _t;	 /* used by the macros */
	u32 _t32;  /* used by the macros */
874
	char tmp_name[256], cmp_name[256]; /* used by the macros */
875

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

	GET16(trans_id);
	GET16(flags);
	GET16(questions);
	GET16(answers);
	GET16(authority);
	GET16(additional);
890
891
	(void) authority; /* suppress "unused variable" warnings. */
	(void) additional; /* suppress "unused variable" warnings. */
892

893
	req = request_find_from_trans_id(trans_id);
894
	/* if no request, can't do anything. */
895
896
897
898
	if (!req) return -1;

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

899
	/* If it's not an answer, it doesn't go with any of our requests. */
900
	if (!(flags & 0x8000)) return -1;  /* must be an answer */
901
	if (flags & 0x020f) {
902
		/* there was an error */
903
		goto err;
904
	}
905
	/* if (!answers) return; */  /* must have an answer of some form */
906

907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
	/* This macro skips a name in the DNS reply. */
#define GET_NAME \
	do { tmp_name[0] = '\0';				\
		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
			goto err;				\
	} while(0)
#define TEST_NAME \
	do { tmp_name[0] = '\0';				\
		cmp_name[0] = '\0';				\
		k = j;						\
		if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)\
			goto err;					\
		if (name_parse(req->request, req->request_len, &k, cmp_name, sizeof(cmp_name))<0)	\
			goto err;				\
		if (global_randomize_case) {							\
			if (strcmp(tmp_name, cmp_name) == 0)				\
				name_matches = 1; /* we ignore mismatching names */	\
		} else {													\
			if (strcasecmp(tmp_name, cmp_name) == 0)				\
				name_matches = 1;									\
		}															\
928
	} while(0)
929

930
	reply.type = req->request_type;
931

932
	/* skip over each question in the reply */
933
	for (i = 0; i < questions; ++i) {
934
935
936
		/* the question looks like
		 * <label:name><u16:type><u16:class>
		 */
937
		TEST_NAME;
938
		j += 4;
939
		if (j >= length) goto err;
940
	}
941

942
943
944
	if (!name_matches)
		goto err;

945
946
947
	/* now we have the answer section which looks like
	 * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
	 */
948

949
950
951
	for (i = 0; i < answers; ++i) {
		u16 type, class;

952
		GET_NAME;
953
954
955
956
957
		GET16(type);
		GET16(class);
		GET32(ttl);
		GET16(datalength);

958
		if (type == TYPE_A && class == CLASS_INET) {
959
			int addrcount, addrtocopy;
960
			if (req->request_type != TYPE_A) {
961
962
				j += datalength; continue;
			}
963
			if ((datalength & 3) != 0) /* not an even number of As. */
964
				goto err;
965
			addrcount = datalength >> 2;
966
			addrtocopy = MIN(MAX_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
967

968
			ttl_r = MIN(ttl_r, ttl);
969
			/* we only bother with the first four addresses. */
970
			if (j + 4*addrtocopy > length) goto err;
971
972
973
974
975
			memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
				   packet + j, 4*addrtocopy);
			reply.data.a.addrcount += addrtocopy;
			reply.have_answer = 1;
			if (reply.data.a.addrcount == MAX_ADDRS) break;
976
			j += 4*addrtocopy;
977
978
979
980
		} else if (type == TYPE_PTR && class == CLASS_INET) {
			if (req->request_type != TYPE_PTR) {
				j += datalength; continue;
			}
981
			GET_NAME;
982
983
984
985
			strlcpy(reply.data.ptr.name, tmp_name,
					sizeof(reply.data.ptr.name));
			ttl_r = MIN(ttl_r, ttl);
			reply.have_answer = 1;
986
			break;
987
		} else if (type == TYPE_AAAA && class == CLASS_INET) {
988
			int addrcount, addrtocopy;
989
			if (req->request_type != TYPE_AAAA) {
990
991
				j += datalength; continue;
			}
992
			if ((datalength & 15) != 0) /* not an even number of AAAAs. */
993
				goto err;
994
			addrcount = datalength >> 4;  /* each address is 16 bytes long */
995
996
997
			addrtocopy = MIN(MAX_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
			ttl_r = MIN(ttl_r, ttl);

998
			/* we only bother with the first four addresses. */
999
			if (j + 16*addrtocopy > length) goto err;
1000
			memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],