resolver.c 194 KB
Newer Older
Michael Graff's avatar
Michael Graff committed
1
/*
Mark Andrews's avatar
Mark Andrews committed
2
 * Copyright (C) 2004-2007  Internet Systems Consortium, Inc. ("ISC")
Mark Andrews's avatar
Mark Andrews committed
3
 * Copyright (C) 1999-2003  Internet Software Consortium.
4
 *
Automatic Updater's avatar
Automatic Updater committed
5
 * Permission to use, copy, modify, and/or distribute this software for any
Michael Graff's avatar
Michael Graff committed
6 7
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
8
 *
Mark Andrews's avatar
Mark Andrews committed
9 10 11 12 13 14 15
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
Michael Graff's avatar
Michael Graff committed
16
 */
Bob Halley's avatar
Bob Halley committed
17

Mark Andrews's avatar
Mark Andrews committed
18
/* $Id: resolver.c,v 1.356 2008/01/15 01:47:17 marka Exp $ */
19 20

/*! \file */
David Lawrence's avatar
David Lawrence committed
21

22 23
#include <config.h>

24
#include <isc/print.h>
Mark Andrews's avatar
Mark Andrews committed
25
#include <isc/string.h>
26
#include <isc/random.h>
Bob Halley's avatar
Bob Halley committed
27
#include <isc/task.h>
28
#include <isc/timer.h>
Michael Graff's avatar
Michael Graff committed
29
#include <isc/util.h>
Bob Halley's avatar
Bob Halley committed
30

31
#include <dns/acl.h>
Bob Halley's avatar
Bob Halley committed
32
#include <dns/adb.h>
33
#include <dns/cache.h>
Bob Halley's avatar
Bob Halley committed
34
#include <dns/db.h>
35
#include <dns/dispatch.h>
36
#include <dns/ds.h>
Bob Halley's avatar
Bob Halley committed
37
#include <dns/events.h>
38
#include <dns/forward.h>
Bob Halley's avatar
Bob Halley committed
39
#include <dns/keytable.h>
40
#include <dns/log.h>
Bob Halley's avatar
Bob Halley committed
41
#include <dns/message.h>
42
#include <dns/ncache.h>
43
#include <dns/opcode.h>
44
#include <dns/peer.h>
45
#include <dns/rbt.h>
46
#include <dns/rcode.h>
47
#include <dns/rdata.h>
48
#include <dns/rdataclass.h>
Bob Halley's avatar
Bob Halley committed
49
#include <dns/rdatalist.h>
Bob Halley's avatar
Bob Halley committed
50
#include <dns/rdataset.h>
51
#include <dns/rdatastruct.h>
52
#include <dns/rdatatype.h>
53 54
#include <dns/resolver.h>
#include <dns/result.h>
55
#include <dns/rootns.h>
56
#include <dns/tsig.h>
57
#include <dns/validator.h>
Bob Halley's avatar
Bob Halley committed
58

Bob Halley's avatar
Bob Halley committed
59 60
#define DNS_RESOLVER_TRACE
#ifdef DNS_RESOLVER_TRACE
61
#define RTRACE(m)       isc_log_write(dns_lctx, \
Mark Andrews's avatar
Mark Andrews committed
62 63 64 65
				      DNS_LOGCATEGORY_RESOLVER, \
				      DNS_LOGMODULE_RESOLVER, \
				      ISC_LOG_DEBUG(3), \
				      "res %p: %s", res, (m))
66
#define RRTRACE(r, m)   isc_log_write(dns_lctx, \
Mark Andrews's avatar
Mark Andrews committed
67 68 69 70
				      DNS_LOGCATEGORY_RESOLVER, \
				      DNS_LOGMODULE_RESOLVER, \
				      ISC_LOG_DEBUG(3), \
				      "res %p: %s", (r), (m))
71
#define FCTXTRACE(m)    isc_log_write(dns_lctx, \
Mark Andrews's avatar
Mark Andrews committed
72 73 74 75
				      DNS_LOGCATEGORY_RESOLVER, \
				      DNS_LOGMODULE_RESOLVER, \
				      ISC_LOG_DEBUG(3), \
				      "fctx %p(%s'): %s", fctx, fctx->info, (m))
76
#define FCTXTRACE2(m1, m2) \
Mark Andrews's avatar
Mark Andrews committed
77 78 79 80 81 82
			isc_log_write(dns_lctx, \
				      DNS_LOGCATEGORY_RESOLVER, \
				      DNS_LOGMODULE_RESOLVER, \
				      ISC_LOG_DEBUG(3), \
				      "fctx %p(%s): %s %s", \
				      fctx, fctx->info, (m1), (m2))
83
#define FTRACE(m)       isc_log_write(dns_lctx, \
Mark Andrews's avatar
Mark Andrews committed
84 85 86 87 88 89
				      DNS_LOGCATEGORY_RESOLVER, \
				      DNS_LOGMODULE_RESOLVER, \
				      ISC_LOG_DEBUG(3), \
				      "fetch %p (fctx %p(%s)): %s", \
				      fetch, fetch->private, \
				      fetch->private->info, (m))
90
#define QTRACE(m)       isc_log_write(dns_lctx, \
Mark Andrews's avatar
Mark Andrews committed
91 92 93 94 95 96
				      DNS_LOGCATEGORY_RESOLVER, \
				      DNS_LOGMODULE_RESOLVER, \
				      ISC_LOG_DEBUG(3), \
				      "resquery %p (fctx %p(%s)): %s", \
				      query, query->fctx, \
				      query->fctx->info, (m))
Bob Halley's avatar
Bob Halley committed
97 98 99 100 101
#else
#define RTRACE(m)
#define RRTRACE(r, m)
#define FCTXTRACE(m)
#define FTRACE(m)
Bob Halley's avatar
Bob Halley committed
102
#define QTRACE(m)
Bob Halley's avatar
Bob Halley committed
103 104
#endif

105
/*%
Bob Halley's avatar
Bob Halley committed
106 107
 * Maximum EDNS0 input packet size.
 */
108
#define RECV_BUFFER_SIZE                4096            /* XXXRTH  Constant. */
109

110
/*%
111
 * This defines the maximum number of timeouts we will permit before we
112 113
 * disable EDNS0 on the query.
 */
114
#define MAX_EDNS0_TIMEOUTS      3
115

Bob Halley's avatar
Bob Halley committed
116 117
typedef struct fetchctx fetchctx_t;

Bob Halley's avatar
Bob Halley committed
118
typedef struct query {
Mark Andrews's avatar
Mark Andrews committed
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
	/* Locked by task event serialization. */
	unsigned int			magic;
	fetchctx_t *			fctx;
	isc_mem_t *			mctx;
	dns_dispatchmgr_t *		dispatchmgr;
	dns_dispatch_t *		dispatch;
	dns_adbaddrinfo_t *		addrinfo;
	isc_socket_t *			tcpsocket;
	isc_time_t			start;
	dns_messageid_t			id;
	dns_dispentry_t *		dispentry;
	ISC_LINK(struct query)		link;
	isc_buffer_t			buffer;
	isc_buffer_t			*tsig;
	dns_tsigkey_t			*tsigkey;
	unsigned int			options;
	unsigned int			attributes;
	unsigned int			sends;
	unsigned int			connects;
	unsigned char			data[512];
Bob Halley's avatar
Bob Halley committed
139 140
} resquery_t;

Mark Andrews's avatar
Mark Andrews committed
141 142
#define QUERY_MAGIC			ISC_MAGIC('Q', '!', '!', '!')
#define VALID_QUERY(query)		ISC_MAGIC_VALID(query, QUERY_MAGIC)
Bob Halley's avatar
Bob Halley committed
143

144
#define RESQUERY_ATTR_CANCELED          0x02
145

146 147
#define RESQUERY_CONNECTING(q)          ((q)->connects > 0)
#define RESQUERY_CANCELED(q)            (((q)->attributes & \
Mark Andrews's avatar
Mark Andrews committed
148
					  RESQUERY_ATTR_CANCELED) != 0)
149
#define RESQUERY_SENDING(q)             ((q)->sends > 0)
150

Bob Halley's avatar
Bob Halley committed
151
typedef enum {
Mark Andrews's avatar
Mark Andrews committed
152 153 154
	fetchstate_init = 0,            /*%< Start event has not run yet. */
	fetchstate_active,
	fetchstate_done                 /*%< FETCHDONE events posted. */
Bob Halley's avatar
Bob Halley committed
155 156
} fetchstate;

Bob Halley's avatar
Bob Halley committed
157
struct fetchctx {
Mark Andrews's avatar
Mark Andrews committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
	/*% Not locked. */
	unsigned int			magic;
	dns_resolver_t *		res;
	dns_name_t			name;
	dns_rdatatype_t			type;
	unsigned int			options;
	unsigned int			bucketnum;
	char *			info;
	/*% Locked by appropriate bucket lock. */
	fetchstate			state;
	isc_boolean_t			want_shutdown;
	isc_boolean_t			cloned;
	isc_boolean_t			spilled;
	unsigned int			references;
	isc_event_t			control_event;
	ISC_LINK(struct fetchctx)       link;
	ISC_LIST(dns_fetchevent_t)      events;
	/*% Locked by task event serialization. */
	dns_name_t			domain;
	dns_rdataset_t			nameservers;
	unsigned int			attributes;
	isc_timer_t *			timer;
	isc_time_t			expires;
	isc_interval_t			interval;
	dns_message_t *			qmessage;
	dns_message_t *			rmessage;
	ISC_LIST(resquery_t)		queries;
	dns_adbfindlist_t		finds;
	dns_adbfind_t *			find;
	dns_adbfindlist_t		altfinds;
	dns_adbfind_t *			altfind;
	dns_adbaddrinfolist_t		forwaddrs;
	dns_adbaddrinfolist_t		altaddrs;
	isc_sockaddrlist_t		forwarders;
	dns_fwdpolicy_t			fwdpolicy;
	isc_sockaddrlist_t		bad;
	isc_sockaddrlist_t		edns;
	isc_sockaddrlist_t		edns512;
	dns_validator_t			*validator;
	ISC_LIST(dns_validator_t)       validators;
	dns_db_t *			cache;
	dns_adb_t *			adb;

	/*%
	 * The number of events we're waiting for.
	 */
	unsigned int			pending;

	/*%
	 * The number of times we've "restarted" the current
	 * nameserver set.  This acts as a failsafe to prevent
	 * us from pounding constantly on a particular set of
	 * servers that, for whatever reason, are not giving
	 * us useful responses, but are responding in such a
	 * way that they are not marked "bad".
	 */
	unsigned int			restarts;

	/*%
	 * The number of timeouts that have occurred since we
	 * last successfully received a response packet.  This
	 * is used for EDNS0 black hole detection.
	 */
	unsigned int			timeouts;
	/*%
	 * Look aside state for DS lookups.
	 */
	dns_name_t			nsname;
	dns_fetch_t *			nsfetch;
	dns_rdataset_t			nsrrset;

	/*%
	 * Number of queries that reference this context.
	 */
	unsigned int			nqueries;
Bob Halley's avatar
Bob Halley committed
233
};
Bob Halley's avatar
Bob Halley committed
234

Mark Andrews's avatar
Mark Andrews committed
235 236
#define FCTX_MAGIC			ISC_MAGIC('F', '!', '!', '!')
#define VALID_FCTX(fctx)		ISC_MAGIC_VALID(fctx, FCTX_MAGIC)
237 238 239 240 241 242 243 244 245 246 247 248

#define FCTX_ATTR_HAVEANSWER            0x0001
#define FCTX_ATTR_GLUING                0x0002
#define FCTX_ATTR_ADDRWAIT              0x0004
#define FCTX_ATTR_SHUTTINGDOWN          0x0008
#define FCTX_ATTR_WANTCACHE             0x0010
#define FCTX_ATTR_WANTNCACHE            0x0020
#define FCTX_ATTR_NEEDEDNS0             0x0040
#define FCTX_ATTR_TRIEDFIND             0x0080
#define FCTX_ATTR_TRIEDALT              0x0100

#define HAVE_ANSWER(f)          (((f)->attributes & FCTX_ATTR_HAVEANSWER) != \
Mark Andrews's avatar
Mark Andrews committed
249
				 0)
250
#define GLUING(f)               (((f)->attributes & FCTX_ATTR_GLUING) != \
Mark Andrews's avatar
Mark Andrews committed
251
				 0)
252
#define ADDRWAIT(f)             (((f)->attributes & FCTX_ATTR_ADDRWAIT) != \
Mark Andrews's avatar
Mark Andrews committed
253
				 0)
254
#define SHUTTINGDOWN(f)         (((f)->attributes & FCTX_ATTR_SHUTTINGDOWN) \
Mark Andrews's avatar
Mark Andrews committed
255
				 != 0)
256 257 258 259 260
#define WANTCACHE(f)            (((f)->attributes & FCTX_ATTR_WANTCACHE) != 0)
#define WANTNCACHE(f)           (((f)->attributes & FCTX_ATTR_WANTNCACHE) != 0)
#define NEEDEDNS0(f)            (((f)->attributes & FCTX_ATTR_NEEDEDNS0) != 0)
#define TRIEDFIND(f)            (((f)->attributes & FCTX_ATTR_TRIEDFIND) != 0)
#define TRIEDALT(f)             (((f)->attributes & FCTX_ATTR_TRIEDALT) != 0)
Bob Halley's avatar
Bob Halley committed
261

262
typedef struct {
Mark Andrews's avatar
Mark Andrews committed
263 264
	dns_adbaddrinfo_t *		addrinfo;
	fetchctx_t *			fctx;
265 266
} dns_valarg_t;

Bob Halley's avatar
Bob Halley committed
267
struct dns_fetch {
Mark Andrews's avatar
Mark Andrews committed
268 269
	unsigned int			magic;
	fetchctx_t *			private;
Bob Halley's avatar
Bob Halley committed
270 271
};

Mark Andrews's avatar
Mark Andrews committed
272 273
#define DNS_FETCH_MAGIC			ISC_MAGIC('F', 't', 'c', 'h')
#define DNS_FETCH_VALID(fetch)		ISC_MAGIC_VALID(fetch, DNS_FETCH_MAGIC)
Bob Halley's avatar
Bob Halley committed
274 275

typedef struct fctxbucket {
Mark Andrews's avatar
Mark Andrews committed
276 277 278 279 280
	isc_task_t *			task;
	isc_mutex_t			lock;
	ISC_LIST(fetchctx_t)		fctxs;
	isc_boolean_t			exiting;
	isc_mem_t *			mctx;
Bob Halley's avatar
Bob Halley committed
281 282
} fctxbucket_t;

283
typedef struct alternate {
Mark Andrews's avatar
Mark Andrews committed
284 285 286 287 288 289 290 291 292
	isc_boolean_t			isaddress;
	union   {
		isc_sockaddr_t		addr;
		struct {
			dns_name_t      name;
			in_port_t       port;
		} _n;
	} _u;
	ISC_LINK(struct alternate)      link;
293 294
} alternate_t;

295 296 297 298 299 300 301
#ifdef ISC_RWLOCK_USEATOMIC
#define DNS_RESOLVER_USERWLOCK 1
#else
#define DNS_RESOLVER_USERWLOCK 0
#endif

#if DNS_RESOLVER_USERWLOCK
Mark Andrews's avatar
Mark Andrews committed
302
#define RES_INITLOCK(l)		isc_rwlock_init((l), 0, 0)
303
#define RES_DESTROYLOCK(l)      isc_rwlock_destroy(l)
Mark Andrews's avatar
Mark Andrews committed
304 305
#define RES_LOCK(l, t)		RWLOCK((l), (t))
#define RES_UNLOCK(l, t)	RWUNLOCK((l), (t))
306
#else
Mark Andrews's avatar
Mark Andrews committed
307
#define RES_INITLOCK(l)		isc_mutex_init(l)
308
#define RES_DESTROYLOCK(l)      DESTROYLOCK(l)
Mark Andrews's avatar
Mark Andrews committed
309 310
#define RES_LOCK(l, t)		LOCK(l)
#define RES_UNLOCK(l, t)	UNLOCK(l)
311 312
#endif

Bob Halley's avatar
Bob Halley committed
313
struct dns_resolver {
Mark Andrews's avatar
Mark Andrews committed
314 315 316 317 318 319
	/* Unlocked. */
	unsigned int			magic;
	isc_mem_t *			mctx;
	isc_mutex_t			lock;
	isc_mutex_t			nlock;
	isc_mutex_t			primelock;
320
#if DNS_RESOLVER_USERWLOCK
Mark Andrews's avatar
Mark Andrews committed
321
	isc_rwlock_t			poollock;
322
#else
Mark Andrews's avatar
Mark Andrews committed
323
	isc_mutex_t			poollock;
324
#endif
Mark Andrews's avatar
Mark Andrews committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
	dns_rdataclass_t		rdclass;
	isc_socketmgr_t *		socketmgr;
	isc_timermgr_t *		timermgr;
	isc_taskmgr_t *			taskmgr;
	dns_view_t *			view;
	isc_boolean_t			frozen;
	unsigned int			options;
	dns_dispatchmgr_t *		dispatchmgr;
	dns_dispatch_t *		dispatchv4;
	dns_dispatch_t *		dispatchv6;
	unsigned int			ndisps;
	unsigned int			nbuckets;
	fctxbucket_t *			buckets;
	isc_uint32_t			lame_ttl;
	ISC_LIST(alternate_t)		alternates;
	isc_uint16_t			udpsize;
341
#if USE_ALGLOCK
Mark Andrews's avatar
Mark Andrews committed
342
	isc_rwlock_t			alglock;
343
#endif
Mark Andrews's avatar
Mark Andrews committed
344
	dns_rbt_t *			algorithms;
345
#if USE_MBSLOCK
Mark Andrews's avatar
Mark Andrews committed
346
	isc_rwlock_t			mbslock;
347
#endif
Mark Andrews's avatar
Mark Andrews committed
348 349 350 351 352 353
	dns_rbt_t *			mustbesecure;
	unsigned int			spillatmax;
	unsigned int			spillatmin;
	isc_timer_t *			spillattimer;
	isc_boolean_t			zero_no_soa_ttl;
	isc_timer_t *			disppooltimer;
354 355
#ifdef LRU_DEBUG
#define DUMP_INTERVAL 30        /* seconds */
Mark Andrews's avatar
Mark Andrews committed
356 357
	isc_timer_t *			dumptimer;
	isc_time_t			dump_time;
358
#endif
Mark Andrews's avatar
Mark Andrews committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
	/* Locked by lock. */
	unsigned int			references;
	isc_boolean_t			exiting;
	isc_eventlist_t			whenshutdown;
	unsigned int			activebuckets;
	isc_boolean_t			priming;
	unsigned int			spillat;	/* clients-per-query */
	unsigned int			nextdisp;
	/* Locked by primelock. */
	dns_fetch_t *			primefetch;
	/* Locked by nlock. */
	unsigned int			nfctx;
	/* Locked by poollock. */
	dns_dispatch_t **		dispatchv4pool;
	dns_dispatch_t **		dispatchv6pool;
374 375

#ifdef LRU_DEBUG
Mark Andrews's avatar
Mark Andrews committed
376 377 378 379 380 381
	/* Unlocked: just for debug */
	unsigned int			extqueries;
	unsigned int			extqueries_ns;
	unsigned int			extqueries_soa;
	unsigned int			extqueries_a;
	unsigned int			extqueries_aaaa;
382
#endif
Bob Halley's avatar
Bob Halley committed
383 384
};

Mark Andrews's avatar
Mark Andrews committed
385 386
#define RES_MAGIC			ISC_MAGIC('R', 'e', 's', '!')
#define VALID_RESOLVER(res)		ISC_MAGIC_VALID(res, RES_MAGIC)
Bob Halley's avatar
Bob Halley committed
387

388
/*%
389 390 391
 * Private addrinfo flags.  These must not conflict with DNS_FETCHOPT_NOEDNS0,
 * which we also use as an addrinfo flag.
 */
392 393 394
#define FCTX_ADDRINFO_MARK              0x0001
#define FCTX_ADDRINFO_FORWARDER         0x1000
#define UNMARKED(a)                     (((a)->flags & FCTX_ADDRINFO_MARK) \
Mark Andrews's avatar
Mark Andrews committed
395
					 == 0)
396
#define ISFORWARDER(a)                  (((a)->flags & \
Mark Andrews's avatar
Mark Andrews committed
397
					 FCTX_ADDRINFO_FORWARDER) != 0)
Bob Halley's avatar
Bob Halley committed
398

399 400
#define NXDOMAIN(r) (((r)->attributes & DNS_RDATASETATTR_NXDOMAIN) != 0)

Bob Halley's avatar
Bob Halley committed
401
static void destroy(dns_resolver_t *res);
Bob Halley's avatar
Bob Halley committed
402
static void empty_bucket(dns_resolver_t *res);
Bob Halley's avatar
Bob Halley committed
403
static isc_result_t resquery_send(resquery_t *query);
Bob Halley's avatar
Bob Halley committed
404
static void resquery_response(isc_task_t *task, isc_event_t *event);
Bob Halley's avatar
Bob Halley committed
405
static void resquery_connected(isc_task_t *task, isc_event_t *event);
Bob Halley's avatar
Bob Halley committed
406
static void fctx_try(fetchctx_t *fctx);
Bob Halley's avatar
Bob Halley committed
407
static isc_boolean_t fctx_destroy(fetchctx_t *fctx);
408
static isc_result_t ncache_adderesult(dns_message_t *message,
Mark Andrews's avatar
Mark Andrews committed
409 410 411 412 413
				      dns_db_t *cache, dns_dbnode_t *node,
				      dns_rdatatype_t covers,
				      isc_stdtime_t now, dns_ttl_t maxttl,
				      dns_rdataset_t *ardataset,
				      isc_result_t *eresultp);
414
static void validated(isc_task_t *task, isc_event_t *event);
415
static void maybe_destroy(fetchctx_t *fctx);
416

417 418 419 420
#ifdef LRU_DEBUG
static void timer_dump(isc_task_t *task, isc_event_t *ev);
#endif

421 422
static isc_result_t
valcreate(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo, dns_name_t *name,
Mark Andrews's avatar
Mark Andrews committed
423 424 425
	  dns_rdatatype_t type, dns_rdataset_t *rdataset,
	  dns_rdataset_t *sigrdataset, unsigned int valoptions,
	  isc_task_t *task)
426
{
Mark Andrews's avatar
Mark Andrews committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
	dns_validator_t *validator = NULL;
	dns_valarg_t *valarg;
	isc_result_t result;

	valarg = isc_mem_get(fctx->res->buckets[fctx->bucketnum].mctx,
			     sizeof(*valarg));
	if (valarg == NULL)
		return (ISC_R_NOMEMORY);

	valarg->fctx = fctx;
	valarg->addrinfo = addrinfo;

	if (!ISC_LIST_EMPTY(fctx->validators))
		INSIST((valoptions & DNS_VALIDATOR_DEFER) != 0);

	result = dns_validator_create(fctx->res->view, name, type, rdataset,
				      sigrdataset, fctx->rmessage,
				      valoptions, task, validated, valarg,
				      &validator);
	if (result == ISC_R_SUCCESS) {
		if ((valoptions & DNS_VALIDATOR_DEFER) == 0) {
			INSIST(fctx->validator == NULL);
			fctx->validator  = validator;
		}
		ISC_LIST_APPEND(fctx->validators, validator, link);
	} else
		isc_mem_put(fctx->res->buckets[fctx->bucketnum].mctx,
			    valarg, sizeof(*valarg));
	return (result);
456
}
Bob Halley's avatar
Bob Halley committed
457

458
static isc_boolean_t
459
fix_mustbedelegationornxdomain(dns_message_t *message, fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
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 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
	dns_name_t *name;
	dns_name_t *domain = &fctx->domain;
	dns_rdataset_t *rdataset;
	dns_rdatatype_t type;
	isc_result_t result;
	isc_boolean_t keep_auth = ISC_FALSE;

	if (message->rcode == dns_rcode_nxdomain)
		return (ISC_FALSE);

	/*
	 * Look for BIND 8 style delegations.
	 * Also look for answers to ANY queries where the duplicate NS RRset
	 * may have been stripped from the authority section.
	 */
	if (message->counts[DNS_SECTION_ANSWER] != 0 &&
	    (fctx->type == dns_rdatatype_ns ||
	     fctx->type == dns_rdatatype_any)) {
		result = dns_message_firstname(message, DNS_SECTION_ANSWER);
		while (result == ISC_R_SUCCESS) {
			name = NULL;
			dns_message_currentname(message, DNS_SECTION_ANSWER,
						&name);
			for (rdataset = ISC_LIST_HEAD(name->list);
			     rdataset != NULL;
			     rdataset = ISC_LIST_NEXT(rdataset, link)) {
				type = rdataset->type;
				if (type != dns_rdatatype_ns)
					continue;
				if (dns_name_issubdomain(name, domain))
					return (ISC_FALSE);
			}
			result = dns_message_nextname(message,
						      DNS_SECTION_ANSWER);
		}
	}

	/* Look for referral. */
	if (message->counts[DNS_SECTION_AUTHORITY] == 0)
		goto munge;

	result = dns_message_firstname(message, DNS_SECTION_AUTHORITY);
	while (result == ISC_R_SUCCESS) {
		name = NULL;
		dns_message_currentname(message, DNS_SECTION_AUTHORITY, &name);
		for (rdataset = ISC_LIST_HEAD(name->list);
		     rdataset != NULL;
		     rdataset = ISC_LIST_NEXT(rdataset, link)) {
			type = rdataset->type;
			if (type == dns_rdatatype_soa &&
			    dns_name_equal(name, domain))
				keep_auth = ISC_TRUE;
			if (type != dns_rdatatype_ns &&
			    type != dns_rdatatype_soa)
				continue;
			if (dns_name_equal(name, domain))
				goto munge;
			if (dns_name_issubdomain(name, domain))
				return (ISC_FALSE);
		}
		result = dns_message_nextname(message, DNS_SECTION_AUTHORITY);
	}
522 523

 munge:
Mark Andrews's avatar
Mark Andrews committed
524 525 526 527 528 529
	message->rcode = dns_rcode_nxdomain;
	message->counts[DNS_SECTION_ANSWER] = 0;
	if (!keep_auth)
		message->counts[DNS_SECTION_AUTHORITY] = 0;
	message->counts[DNS_SECTION_ADDITIONAL] = 0;
	return (ISC_TRUE);
530 531
}

Bob Halley's avatar
Bob Halley committed
532
static inline isc_result_t
Bob Halley's avatar
Bob Halley committed
533
fctx_starttimer(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
534 535 536 537 538 539 540 541 542
	/*
	 * Start the lifetime timer for fctx.
	 *
	 * This is also used for stopping the idle timer; in that
	 * case we must purge events already posted to ensure that
	 * no further idle events are delivered.
	 */
	return (isc_timer_reset(fctx->timer, isc_timertype_once,
				&fctx->expires, NULL, ISC_TRUE));
Bob Halley's avatar
Bob Halley committed
543 544
}

Bob Halley's avatar
Bob Halley committed
545 546
static inline void
fctx_stoptimer(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
	isc_result_t result;

	/*
	 * We don't return a result if resetting the timer to inactive fails
	 * since there's nothing to be done about it.  Resetting to inactive
	 * should never fail anyway, since the code as currently written
	 * cannot fail in that case.
	 */
	result = isc_timer_reset(fctx->timer, isc_timertype_inactive,
				  NULL, NULL, ISC_TRUE);
	if (result != ISC_R_SUCCESS) {
		UNEXPECTED_ERROR(__FILE__, __LINE__,
				 "isc_timer_reset(): %s",
				 isc_result_totext(result));
	}
Bob Halley's avatar
Bob Halley committed
562 563
}

564 565 566

static inline isc_result_t
fctx_startidletimer(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
567 568 569 570 571 572 573
	/*
	 * Start the idle timer for fctx.  The lifetime timer continues
	 * to be in effect.
	 */
	return (isc_timer_reset(fctx->timer, isc_timertype_once,
				&fctx->expires, &fctx->interval,
				ISC_FALSE));
574 575 576 577 578 579
}

/*
 * Stopping the idle timer is equivalent to calling fctx_starttimer(), but
 * we use fctx_stopidletimer for readability in the code below.
 */
580
#define fctx_stopidletimer      fctx_starttimer
581 582


583 584
static inline void
resquery_destroy(resquery_t **queryp) {
Mark Andrews's avatar
Mark Andrews committed
585
	resquery_t *query;
586

Mark Andrews's avatar
Mark Andrews committed
587 588 589
	REQUIRE(queryp != NULL);
	query = *queryp;
	REQUIRE(!ISC_LINK_LINKED(query, link));
590

Mark Andrews's avatar
Mark Andrews committed
591
	INSIST(query->tcpsocket == NULL);
592

Mark Andrews's avatar
Mark Andrews committed
593 594 595 596 597 598
	query->fctx->nqueries--;
	if (SHUTTINGDOWN(query->fctx))
		maybe_destroy(query->fctx);     /* Locks bucket. */
	query->magic = 0;
	isc_mem_put(query->mctx, query, sizeof(*query));
	*queryp = NULL;
599 600
}

Bob Halley's avatar
Bob Halley committed
601
static void
Bob Halley's avatar
Bob Halley committed
602
fctx_cancelquery(resquery_t **queryp, dns_dispatchevent_t **deventp,
Mark Andrews's avatar
Mark Andrews committed
603
		 isc_time_t *finish, isc_boolean_t no_response)
Bob Halley's avatar
Bob Halley committed
604
{
Mark Andrews's avatar
Mark Andrews committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 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 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
	fetchctx_t *fctx;
	resquery_t *query;
	unsigned int rtt;
	unsigned int factor;
	dns_adbfind_t *find;
	dns_adbaddrinfo_t *addrinfo;

	query = *queryp;
	fctx = query->fctx;

	FCTXTRACE("cancelquery");

	REQUIRE(!RESQUERY_CANCELED(query));

	query->attributes |= RESQUERY_ATTR_CANCELED;

	/*
	 * Should we update the RTT?
	 */
	if (finish != NULL || no_response) {
		if (finish != NULL) {
			/*
			 * We have both the start and finish times for this
			 * packet, so we can compute a real RTT.
			 */
			rtt = (unsigned int)isc_time_microdiff(finish,
							       &query->start);
			factor = DNS_ADB_RTTADJDEFAULT;
		} else {
			/*
			 * We don't have an RTT for this query.  Maybe the
			 * packet was lost, or maybe this server is very
			 * slow.  We don't know.  Increase the RTT.
			 */
			INSIST(no_response);
			rtt = query->addrinfo->srtt + 200000;
			if (rtt > 10000000)
				rtt = 10000000;
			/*
			 * Replace the current RTT with our value.
			 */
			factor = DNS_ADB_RTTADJREPLACE;
		}
		dns_adb_adjustsrtt(fctx->adb, query->addrinfo, rtt, factor);
	}

	/*
	 * Age RTTs of servers not tried.
	 */
	factor = DNS_ADB_RTTADJAGE;
	if (finish != NULL)
		for (addrinfo = ISC_LIST_HEAD(fctx->forwaddrs);
		     addrinfo != NULL;
		     addrinfo = ISC_LIST_NEXT(addrinfo, publink))
			if (UNMARKED(addrinfo))
				dns_adb_adjustsrtt(fctx->adb, addrinfo,
						   0, factor);

	if (finish != NULL && TRIEDFIND(fctx))
		for (find = ISC_LIST_HEAD(fctx->finds);
		     find != NULL;
		     find = ISC_LIST_NEXT(find, publink))
			for (addrinfo = ISC_LIST_HEAD(find->list);
			     addrinfo != NULL;
			     addrinfo = ISC_LIST_NEXT(addrinfo, publink))
				if (UNMARKED(addrinfo))
					dns_adb_adjustsrtt(fctx->adb, addrinfo,
							   0, factor);

	if (finish != NULL && TRIEDALT(fctx)) {
		for (addrinfo = ISC_LIST_HEAD(fctx->altaddrs);
		     addrinfo != NULL;
		     addrinfo = ISC_LIST_NEXT(addrinfo, publink))
			if (UNMARKED(addrinfo))
				dns_adb_adjustsrtt(fctx->adb, addrinfo,
						   0, factor);
		for (find = ISC_LIST_HEAD(fctx->altfinds);
		     find != NULL;
		     find = ISC_LIST_NEXT(find, publink))
			for (addrinfo = ISC_LIST_HEAD(find->list);
			     addrinfo != NULL;
			     addrinfo = ISC_LIST_NEXT(addrinfo, publink))
				if (UNMARKED(addrinfo))
					dns_adb_adjustsrtt(fctx->adb, addrinfo,
							   0, factor);
	}

	if (query->dispentry != NULL)
		dns_dispatch_removeresponse(&query->dispentry, deventp);

	ISC_LIST_UNLINK(fctx->queries, query, link);

	if (query->tsig != NULL)
		isc_buffer_free(&query->tsig);

	if (query->tsigkey != NULL)
		dns_tsigkey_detach(&query->tsigkey);

	/*
	 * Check for any outstanding socket events.  If they exist, cancel
	 * them and let the event handlers finish the cleanup.  The resolver
	 * only needs to worry about managing the connect and send events;
	 * the dispatcher manages the recv events.
	 */
	if (RESQUERY_CONNECTING(query))
		/*
		 * Cancel the connect.
		 */
		isc_socket_cancel(query->tcpsocket, NULL,
				  ISC_SOCKCANCEL_CONNECT);
	else if (RESQUERY_SENDING(query))
		/*
		 * Cancel the pending send.
		 */
		isc_socket_cancel(dns_dispatch_getsocket(query->dispatch),
				  NULL, ISC_SOCKCANCEL_SEND);

	if (query->dispatch != NULL)
		dns_dispatch_detach(&query->dispatch);

	if (! (RESQUERY_CONNECTING(query) || RESQUERY_SENDING(query)))
		/*
		 * It's safe to destroy the query now.
		 */
		resquery_destroy(&query);
Bob Halley's avatar
Bob Halley committed
730 731 732
}

static void
733
fctx_cancelqueries(fetchctx_t *fctx, isc_boolean_t no_response) {
Mark Andrews's avatar
Mark Andrews committed
734
	resquery_t *query, *next_query;
Bob Halley's avatar
Bob Halley committed
735

Mark Andrews's avatar
Mark Andrews committed
736
	FCTXTRACE("cancelqueries");
Bob Halley's avatar
Bob Halley committed
737

Mark Andrews's avatar
Mark Andrews committed
738 739 740 741 742 743
	for (query = ISC_LIST_HEAD(fctx->queries);
	     query != NULL;
	     query = next_query) {
		next_query = ISC_LIST_NEXT(query, link);
		fctx_cancelquery(&query, NULL, NULL, no_response);
	}
Bob Halley's avatar
Bob Halley committed
744 745
}

Bob Halley's avatar
Bob Halley committed
746
static void
Bob Halley's avatar
Bob Halley committed
747
fctx_cleanupfinds(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
748 749 750 751 752 753 754 755 756 757 758 759
	dns_adbfind_t *find, *next_find;

	REQUIRE(ISC_LIST_EMPTY(fctx->queries));

	for (find = ISC_LIST_HEAD(fctx->finds);
	     find != NULL;
	     find = next_find) {
		next_find = ISC_LIST_NEXT(find, publink);
		ISC_LIST_UNLINK(fctx->finds, find, publink);
		dns_adb_destroyfind(&find);
	}
	fctx->find = NULL;
Bob Halley's avatar
Bob Halley committed
760 761
}

762 763
static void
fctx_cleanupaltfinds(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
764 765 766 767 768 769 770 771 772 773 774 775
	dns_adbfind_t *find, *next_find;

	REQUIRE(ISC_LIST_EMPTY(fctx->queries));

	for (find = ISC_LIST_HEAD(fctx->altfinds);
	     find != NULL;
	     find = next_find) {
		next_find = ISC_LIST_NEXT(find, publink);
		ISC_LIST_UNLINK(fctx->altfinds, find, publink);
		dns_adb_destroyfind(&find);
	}
	fctx->altfind = NULL;
776 777
}

778 779
static void
fctx_cleanupforwaddrs(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
780
	dns_adbaddrinfo_t *addr, *next_addr;
781

Mark Andrews's avatar
Mark Andrews committed
782
	REQUIRE(ISC_LIST_EMPTY(fctx->queries));
783

Mark Andrews's avatar
Mark Andrews committed
784 785 786 787 788 789 790
	for (addr = ISC_LIST_HEAD(fctx->forwaddrs);
	     addr != NULL;
	     addr = next_addr) {
		next_addr = ISC_LIST_NEXT(addr, publink);
		ISC_LIST_UNLINK(fctx->forwaddrs, addr, publink);
		dns_adb_freeaddrinfo(fctx->adb, &addr);
	}
791 792
}

793 794
static void
fctx_cleanupaltaddrs(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
795
	dns_adbaddrinfo_t *addr, *next_addr;
796

Mark Andrews's avatar
Mark Andrews committed
797
	REQUIRE(ISC_LIST_EMPTY(fctx->queries));
798

Mark Andrews's avatar
Mark Andrews committed
799 800 801 802 803 804 805
	for (addr = ISC_LIST_HEAD(fctx->altaddrs);
	     addr != NULL;
	     addr = next_addr) {
		next_addr = ISC_LIST_NEXT(addr, publink);
		ISC_LIST_UNLINK(fctx->altaddrs, addr, publink);
		dns_adb_freeaddrinfo(fctx->adb, &addr);
	}
806 807
}

Bob Halley's avatar
Bob Halley committed
808
static inline void
809
fctx_stopeverything(fetchctx_t *fctx, isc_boolean_t no_response) {
Mark Andrews's avatar
Mark Andrews committed
810 811 812 813 814 815 816
	FCTXTRACE("stopeverything");
	fctx_cancelqueries(fctx, no_response);
	fctx_cleanupfinds(fctx);
	fctx_cleanupaltfinds(fctx);
	fctx_cleanupforwaddrs(fctx);
	fctx_cleanupaltaddrs(fctx);
	fctx_stoptimer(fctx);
Bob Halley's avatar
Bob Halley committed
817
}
Bob Halley's avatar
Bob Halley committed
818

Bob Halley's avatar
Bob Halley committed
819 820
static inline void
fctx_sendevents(fetchctx_t *fctx, isc_result_t result) {
Mark Andrews's avatar
Mark Andrews committed
821 822 823 824 825
	dns_fetchevent_t *event, *next_event;
	isc_task_t *task;
	unsigned int count = 0;
	isc_interval_t i;
	isc_boolean_t logit = ISC_FALSE;
826 827 828
	unsigned int old_spillat;
	unsigned int new_spillat = 0;	/* initialized to silence 
					   compiler warnings */
829

Mark Andrews's avatar
Mark Andrews committed
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
	/*
	 * Caller must be holding the appropriate bucket lock.
	 */
	REQUIRE(fctx->state == fetchstate_done);

	FCTXTRACE("sendevents");

	for (event = ISC_LIST_HEAD(fctx->events);
	     event != NULL;
	     event = next_event) {
		next_event = ISC_LIST_NEXT(event, ev_link);
		ISC_LIST_UNLINK(fctx->events, event, ev_link);
		task = event->ev_sender;
		event->ev_sender = fctx;
		if (!HAVE_ANSWER(fctx))
			event->result = result;

		INSIST(result != ISC_R_SUCCESS ||
		       dns_rdataset_isassociated(event->rdataset) ||
		       fctx->type == dns_rdatatype_any ||
		       fctx->type == dns_rdatatype_rrsig ||
		       fctx->type == dns_rdatatype_sig);

		/*
		 * Negative results must be indicated in event->result.
		 */
		if (dns_rdataset_isassociated(event->rdataset) &&
		    event->rdataset->type == dns_rdatatype_none) {
			INSIST(event->result == DNS_R_NCACHENXDOMAIN ||
			       event->result == DNS_R_NCACHENXRRSET);
		}

		isc_task_sendanddetach(&task, ISC_EVENT_PTR(&event));
		count++;
	}

	if ((fctx->attributes & FCTX_ATTR_HAVEANSWER) != 0 &&
	    fctx->spilled &&
	    (count < fctx->res->spillatmax || fctx->res->spillatmax == 0)) {
		LOCK(&fctx->res->lock);
		if (count == fctx->res->spillat && !fctx->res->exiting) {
871
			old_spillat = fctx->res->spillat;
Mark Andrews's avatar
Mark Andrews committed
872 873 874 875
			fctx->res->spillat += 5;
			if (fctx->res->spillat > fctx->res->spillatmax &&
			    fctx->res->spillatmax != 0)
				fctx->res->spillat = fctx->res->spillatmax;
876 877
			new_spillat = fctx->res->spillat;
			if (new_spillat != old_spillat) {
Mark Andrews's avatar
Mark Andrews committed
878
				logit = ISC_TRUE;
879
			}
Mark Andrews's avatar
Mark Andrews committed
880 881 882 883 884 885 886 887 888 889 890 891 892
			isc_interval_set(&i, 20 * 60, 0);
			result = isc_timer_reset(fctx->res->spillattimer,
						 isc_timertype_ticker, NULL,
						 &i, ISC_TRUE);
			RUNTIME_CHECK(result == ISC_R_SUCCESS);
		}
		UNLOCK(&fctx->res->lock);
		if (logit)
			isc_log_write(dns_lctx, DNS_LOGCATEGORY_RESOLVER,
				      DNS_LOGMODULE_RESOLVER, ISC_LOG_NOTICE,
				      "clients-per-query increased to %u",
				      new_spillat);
	}
Bob Halley's avatar
Bob Halley committed
893
}
Bob Halley's avatar
Bob Halley committed
894

Bob Halley's avatar
Bob Halley committed
895 896
static void
fctx_done(fetchctx_t *fctx, isc_result_t result) {
Mark Andrews's avatar
Mark Andrews committed
897 898
	dns_resolver_t *res;
	isc_boolean_t no_response;
Bob Halley's avatar
Bob Halley committed
899

Mark Andrews's avatar
Mark Andrews committed
900
	FCTXTRACE("done");
Bob Halley's avatar
Bob Halley committed
901

Mark Andrews's avatar
Mark Andrews committed
902
	res = fctx->res;
Bob Halley's avatar
Bob Halley committed
903

Mark Andrews's avatar
Mark Andrews committed
904 905 906 907 908
	if (result == ISC_R_SUCCESS)
		no_response = ISC_TRUE;
	else
		no_response = ISC_FALSE;
	fctx_stopeverything(fctx, no_response);
Bob Halley's avatar
Bob Halley committed
909

Mark Andrews's avatar
Mark Andrews committed
910
	LOCK(&res->buckets[fctx->bucketnum].lock);
Bob Halley's avatar
Bob Halley committed
911

Mark Andrews's avatar
Mark Andrews committed
912 913 914
	fctx->state = fetchstate_done;
	fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
	fctx_sendevents(fctx, result);
Bob Halley's avatar
Bob Halley committed
915

Mark Andrews's avatar
Mark Andrews committed
916
	UNLOCK(&res->buckets[fctx->bucketnum].lock);
Bob Halley's avatar
Bob Halley committed
917 918
}

Bob Halley's avatar
Bob Halley committed
919
static void
Bob Halley's avatar
Bob Halley committed
920
resquery_senddone(isc_task_t *task, isc_event_t *event) {
Mark Andrews's avatar
Mark Andrews committed
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
	isc_socketevent_t *sevent = (isc_socketevent_t *)event;
	resquery_t *query = event->ev_arg;
	isc_boolean_t retry = ISC_FALSE;
	isc_result_t result;
	fetchctx_t *fctx;

	REQUIRE(event->ev_type == ISC_SOCKEVENT_SENDDONE);

	QTRACE("senddone");

	/*
	 * XXXRTH
	 *
	 * Currently we don't wait for the senddone event before retrying
	 * a query.  This means that if we get really behind, we may end
	 * up doing extra work!
	 */

	UNUSED(task);

	INSIST(RESQUERY_SENDING(query));

	query->sends--;
	fctx = query->fctx;

	if (RESQUERY_CANCELED(query)) {
		if (query->sends == 0) {
			/*
			 * This query was canceled while the
			 * isc_socket_sendto() was in progress.
			 */
			if (query->tcpsocket != NULL)
				isc_socket_detach(&query->tcpsocket);
			resquery_destroy(&query);
		}
	} else
		switch (sevent->result) {
		case ISC_R_SUCCESS:
			break;

		case ISC_R_HOSTUNREACH:
		case ISC_R_NETUNREACH:
		case ISC_R_NOPERM:
		case ISC_R_ADDRNOTAVAIL:
		case ISC_R_CONNREFUSED:

			/*
			 * No route to remote.
			 */
			fctx_cancelquery(&query, NULL, NULL, ISC_TRUE);
			retry = ISC_TRUE;
			break;

		default:
			fctx_cancelquery(&query, NULL, NULL, ISC_FALSE);
			break;
		}

	isc_event_free(&event);

	if (retry) {
		/*
		 * Behave as if the idle timer has expired.  For TCP
		 * this may not actually reflect the latest timer.
		 */
		fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
		result = fctx_stopidletimer(fctx);
		if (result != ISC_R_SUCCESS)
			fctx_done(fctx, result);
		else
			fctx_try(fctx);
	}
Bob Halley's avatar
Bob Halley committed
993 994
}

Bob Halley's avatar
Bob Halley committed
995
static inline isc_result_t
996
fctx_addopt(dns_message_t *message, unsigned int version, isc_uint16_t udpsize)
997
{
Mark Andrews's avatar
Mark Andrews committed
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
	dns_rdataset_t *rdataset;
	dns_rdatalist_t *rdatalist;
	dns_rdata_t *rdata;
	isc_result_t result;

	rdatalist = NULL;
	result = dns_message_gettemprdatalist(message, &rdatalist);
	if (result != ISC_R_SUCCESS)
		return (result);
	rdata = NULL;
	result = dns_message_gettemprdata(message, &rdata);
	if (result != ISC_R_SUCCESS)
		return (result);
	rdataset = NULL;
	result = dns_message_gettemprdataset(message, &rdataset);
	if (result != ISC_R_SUCCESS)
		return (result);
	dns_rdataset_init(rdataset);

	rdatalist->type = dns_rdatatype_opt;
	rdatalist->covers = 0;

	/*
	 * Set Maximum UDP buffer size.
	 */
	rdatalist->rdclass = udpsize;

	/*
	 * Set EXTENDED-RCODE and Z to 0, DO to 1.
	 */
	rdatalist->ttl = (version << 16);
	rdatalist->ttl |= DNS_MESSAGEEXTFLAG_DO;

	/*
	 * No EDNS options.
	 */
	rdata->data = NULL;
	rdata->length = 0;
	rdata->rdclass = rdatalist->rdclass;
	rdata->type = rdatalist->type;
	rdata->flags = 0;

	ISC_LIST_INIT(rdatalist->rdata);
	ISC_LIST_APPEND(rdatalist->rdata, rdata, link);
	RUNTIME_CHECK(dns_rdatalist_tordataset(rdatalist, rdataset) == ISC_R_SUCCESS);

	return (dns_message_setopt(message, rdataset));
Bob Halley's avatar
Bob Halley committed
1045 1046
}

1047 1048
static inline void
fctx_setretryinterval(fetchctx_t *fctx, unsigned int rtt) {
Mark Andrews's avatar
Mark Andrews committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
	unsigned int seconds;
	unsigned int us;

	/*
	 * We retry every .5 seconds the first two times through the address
	 * list, and then we do exponential back-off.
	 */
	if (fctx->restarts < 3)
		us = 500000;
	else
		us = (500000 << (fctx->restarts - 2));

	/*
	 * Double the round-trip time.
	 */
	rtt *= 2;

	/*
	 * Always wait for at least the doubled round-trip time.
	 */
	if (us < rtt)
		us = rtt;

	/*
	 * But don't ever wait for more than 10 seconds.
	 */
	if (us > 10000000)
		us = 10000000;

	seconds = us / 1000000;
	us -= seconds * 1000000;
	isc_interval_set(&fctx->interval, seconds, us * 1000);
1081 1082
}

Bob Halley's avatar
Bob Halley committed
1083 1084
static isc_result_t
fctx_query(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
Mark Andrews's avatar
Mark Andrews committed
1085
	   unsigned int options)
Bob Halley's avatar
Bob Halley committed
1086
{
Mark Andrews's avatar
Mark Andrews committed
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
	dns_resolver_t *res;
	isc_task_t *task;
	isc_result_t result;
	resquery_t *query;
	isc_sockaddr_t addr;
	isc_boolean_t have_addr = ISC_FALSE;

	FCTXTRACE("query");

	res = fctx->res;
	task = res->buckets[fctx->bucketnum].task;

	fctx_setretryinterval(fctx, addrinfo->srtt);
	result = fctx_startidletimer(fctx);
	if (result != ISC_R_SUCCESS)
		return (result);

	INSIST(ISC_LIST_EMPTY(fctx->validators));

	dns_message_reset(fctx->rmessage, DNS_MESSAGE_INTENTPARSE);

	query = isc_mem_get(res->buckets[fctx->bucketnum].mctx,
			    sizeof(*query));
	if (query == NULL) {
		result = ISC_R_NOMEMORY;
		goto stop_idle_timer;
	}
	query->mctx = res->buckets[fctx->bucketnum].mctx;
	query->options = options;
	query->attributes = 0;
	query->sends = 0;
	query->connects = 0;
	/*
	 * Note that the caller MUST guarantee that 'addrinfo' will remain
	 * valid until this query is canceled.
	 */
	query->addrinfo = addrinfo;
	TIME_NOW(&query->start);

	/*
	 * If this is a TCP query, then we need to make a socket and
	 * a dispatch for it here.  Otherwise we use the resolver's
	 * shared dispatch.
	 */
	query->dispatchmgr = res->dispatchmgr;
	query->dispatch = NULL;
	query->tcpsocket = NULL;
	if (res->view->peers != NULL) {
		dns_peer_t *peer = NULL;
		isc_netaddr_t dstip;
		isc_netaddr_fromsockaddr(&dstip, &addrinfo->sockaddr);
		result = dns_peerlist_peerbyaddr(res->view->peers,
						 &dstip, &peer);
		if (result == ISC_R_SUCCESS) {
			result = dns_peer_getquerysource(peer, &addr);
			if (result == ISC_R_SUCCESS)
				have_addr = ISC_TRUE;
		}
	}

	if ((query->options & DNS_FETCHOPT_TCP) != 0) {
		int pf;

		pf = isc_sockaddr_pf(&addrinfo->sockaddr);
		if (!have_addr) {
			switch (pf) {
			case PF_INET:
				result =
				  dns_dispatch_getlocaladdress(res->dispatchv4,
							       &addr);
				break;
			case PF_INET6:
				result =
				  dns_dispatch_getlocaladdress(res->dispatchv6,
							       &addr);
				break;
			default:
				result = ISC_R_NOTIMPLEMENTED;
				break;
			}
			if (result != ISC_R_SUCCESS)
				goto cleanup_query;
		}
		isc_sockaddr_setport(&addr, 0);

		result = isc_socket_create(res->socketmgr, pf,
					   isc_sockettype_tcp,
					   &query->tcpsocket);
		if (result != ISC_R_SUCCESS)
			goto cleanup_query;
1177

1178
#ifndef BROKEN_TCP_BIND_BEFORE_CONNECT
Mark Andrews's avatar
Mark Andrews committed
1179 1180 1181
		result = isc_socket_bind(query->tcpsocket, &addr);
		if (result != ISC_R_SUCCESS)
			goto cleanup_socket;
1182
#endif
1183

Mark Andrews's avatar
Mark Andrews committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
		/*
		 * A dispatch will be created once the connect succeeds.
		 */
	} else {
		if (have_addr) {
			unsigned int attrs, attrmask;
			attrs = DNS_DISPATCHATTR_UDP;
			switch (isc_sockaddr_pf(&addr)) {
			case AF_INET:
				attrs |= DNS_DISPATCHATTR_IPV4;
				break;
			case AF_INET6:
				attrs |= DNS_DISPATCHATTR_IPV6;
				break;
			default:
				result = ISC_R_NOTIMPLEMENTED;
				goto cleanup_query;
			}
			attrmask = DNS_DISPATCHATTR_UDP;
			attrmask |= DNS_DISPATCHATTR_TCP;
			attrmask |= DNS_DISPATCHATTR_IPV4;
			attrmask |= DNS_DISPATCHATTR_IPV6;
			result = dns_dispatch_getudp(res->dispatchmgr,
						     res->socketmgr,
						     res->taskmgr, &addr,
						     4096, 1000, 32768, 16411,
						     16433, attrs, attrmask,
						     &query->dispatch);
			if (result != ISC_R_SUCCESS)
				goto cleanup_query;
		} else {
			int did = 0;
			isc_uint32_t val;

			if (res->ndisps > 0) {
				isc_random_get(&val);
				did = val % res->ndisps;
			}
			switch (isc_sockaddr_pf(&addrinfo->sockaddr)) {
			case PF_INET:
				if (res->dispatchv4pool != NULL) {
					RES_LOCK(&res->poollock,
						 isc_rwlocktype_read);
					dns_dispatch_attach(res->dispatchv4pool[did],
							    &query->dispatch);
					RES_UNLOCK(&res->poollock,
						   isc_rwlocktype_read);
				} else {
					dns_dispatch_attach(res->dispatchv4,
							    &query->dispatch);
				}
				break;
			case PF_INET6:
				if (res->dispatchv6pool != NULL) {
					RES_LOCK(&res->poollock,
						 isc_rwlocktype_read);
					dns_dispatch_attach(res->dispatchv6pool[did],
							    &query->dispatch);
					RES_UNLOCK(&res->poollock,
						   isc_rwlocktype_read);
				} else {
					dns_dispatch_attach(res->dispatchv6,
							    &query->dispatch);
				}
				break;
			default:
				result = ISC_R_NOTIMPLEMENTED;
				goto cleanup_query;
			}
		}
		/*
		 * We should always have a valid dispatcher here.  If we
		 * don't support a protocol family, then its dispatcher
		 * will be NULL, but we shouldn't be finding addresses for
		 * protocol types we don't support, so the dispatcher
		 * we found should never be NULL.
		 */
		INSIST(query->dispatch != NULL);
	}

	query->dispentry = NULL;
	query->fctx = fctx;
	query->tsig = NULL;
	query->tsigkey = NULL;
	ISC_LINK_INIT(query, link);
	query->magic = QUERY_MAGIC;

	if ((query->options & DNS_FETCHOPT_TCP) != 0) {
		/*
		 * Connect to the remote server.
		 *
		 * XXXRTH  Should we attach to the socket?
		 */
		result = isc_socket_connect(query->tcpsocket,
					    &addrinfo->sockaddr, task,
					    resquery_connected, query);
		if (result != ISC_R_SUCCESS)
			goto cleanup_socket;
		query->connects++;
		QTRACE("connecting via TCP");
	} else {
		result = resquery_send(query);
		if (result != ISC_R_SUCCESS)
			goto cleanup_dispatch;
	}

	ISC_LIST_APPEND(fctx->queries, query, link);
	query->fctx->nqueries++;

	return (ISC_R_SUCCESS);
Bob Halley's avatar
Bob Halley committed
1294

1295
 cleanup_socket:
Mark Andrews's avatar
Mark Andrews committed
1296
	isc_socket_detach(&query->tcpsocket);
1297

Bob Halley's avatar
Bob Halley committed
1298
 cleanup_dispatch:
Mark Andrews's avatar
Mark Andrews committed
1299 1300
	if (query->dispatch != NULL)
		dns_dispatch_detach(&query->dispatch);
Bob Halley's avatar
Bob Halley committed
1301 1302

 cleanup_query:
Mark Andrews's avatar
Mark Andrews committed
1303 1304 1305
	query->magic = 0;
	isc_mem_put(res->buckets[fctx->bucketnum].mctx,
		    query, sizeof(*query));
Bob Halley's avatar
Bob Halley committed
1306

1307
 stop_idle_timer:
Mark Andrews's avatar
Mark Andrews committed
1308
	RUNTIME_CHECK(fctx_stopidletimer(fctx) == ISC_R_SUCCESS);
Bob Halley's avatar
Bob Halley committed
1309

Mark Andrews's avatar
Mark Andrews committed
1310
	return (result);
Bob Halley's avatar
Bob Halley committed
1311 1312
}

1313 1314
static isc_boolean_t
triededns(fetchctx_t *fctx, isc_sockaddr_t *address) {
Mark Andrews's avatar
Mark Andrews committed
1315
	isc_sockaddr_t *sa;
1316

Mark Andrews's avatar
Mark Andrews committed
1317 1318 1319 1320 1321 1322
	for (sa = ISC_LIST_HEAD(fctx->edns);
	     sa != NULL;
	     sa = ISC_LIST_NEXT(sa, link)) {
		if (isc_sockaddr_equal(sa, address))
			return (ISC_TRUE);
	}
Mark Andrews's avatar
2