resolver.c 199 KB
Newer Older
Michael Graff's avatar
Michael Graff committed
1
/*
Automatic Updater's avatar
Automatic Updater committed
2
 * Copyright (C) 2004-2008  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

18
/* $Id: resolver.c,v 1.366 2008/04/03 23:14:52 jinmei Exp $ */
19 20

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

22 23
#include <config.h>

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

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

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

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

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

Bob Halley's avatar
Bob Halley committed
118 119
typedef struct fetchctx fetchctx_t;

Bob Halley's avatar
Bob Halley committed
120
typedef struct query {
Mark Andrews's avatar
Mark Andrews committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
	/* 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
141 142
} resquery_t;

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

146
#define RESQUERY_ATTR_CANCELED          0x02
147

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

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

Bob Halley's avatar
Bob Halley committed
159
struct fetchctx {
Mark Andrews's avatar
Mark Andrews committed
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
	/*% 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.
	 */
227
	dns_name_t 			nsname;
Mark Andrews's avatar
Mark Andrews committed
228 229 230 231 232 233 234
	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
235
};
Bob Halley's avatar
Bob Halley committed
236

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

#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
251
				 0)
252
#define GLUING(f)               (((f)->attributes & FCTX_ATTR_GLUING) != \
Mark Andrews's avatar
Mark Andrews committed
253
				 0)
254
#define ADDRWAIT(f)             (((f)->attributes & FCTX_ATTR_ADDRWAIT) != \
Mark Andrews's avatar
Mark Andrews committed
255
				 0)
256
#define SHUTTINGDOWN(f)         (((f)->attributes & FCTX_ATTR_SHUTTINGDOWN) \
Mark Andrews's avatar
Mark Andrews committed
257
				 != 0)
258 259 260 261 262
#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
263

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

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

Mark Andrews's avatar
Mark Andrews committed
274 275
#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
276 277

typedef struct fctxbucket {
Mark Andrews's avatar
Mark Andrews committed
278 279 280 281 282
	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
283 284
} fctxbucket_t;

285
typedef struct alternate {
Mark Andrews's avatar
Mark Andrews committed
286 287 288 289 290 291 292 293 294
	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;
295 296
} alternate_t;

297 298 299 300 301 302 303
#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
304
#define RES_INITLOCK(l)		isc_rwlock_init((l), 0, 0)
305
#define RES_DESTROYLOCK(l)      isc_rwlock_destroy(l)
Mark Andrews's avatar
Mark Andrews committed
306 307
#define RES_LOCK(l, t)		RWLOCK((l), (t))
#define RES_UNLOCK(l, t)	RWUNLOCK((l), (t))
308
#else
Mark Andrews's avatar
Mark Andrews committed
309
#define RES_INITLOCK(l)		isc_mutex_init(l)
310
#define RES_DESTROYLOCK(l)      DESTROYLOCK(l)
Mark Andrews's avatar
Mark Andrews committed
311 312
#define RES_LOCK(l, t)		LOCK(l)
#define RES_UNLOCK(l, t)	UNLOCK(l)
313 314
#endif

Bob Halley's avatar
Bob Halley committed
315
struct dns_resolver {
Mark Andrews's avatar
Mark Andrews committed
316 317 318 319 320 321
	/* Unlocked. */
	unsigned int			magic;
	isc_mem_t *			mctx;
	isc_mutex_t			lock;
	isc_mutex_t			nlock;
	isc_mutex_t			primelock;
322
#if DNS_RESOLVER_USERWLOCK
Mark Andrews's avatar
Mark Andrews committed
323
	isc_rwlock_t			poollock;
324
#else
Mark Andrews's avatar
Mark Andrews committed
325
	isc_mutex_t			poollock;
326
#endif
Mark Andrews's avatar
Mark Andrews committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
	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;
343
#if USE_ALGLOCK
Mark Andrews's avatar
Mark Andrews committed
344
	isc_rwlock_t			alglock;
345
#endif
Mark Andrews's avatar
Mark Andrews committed
346
	dns_rbt_t *			algorithms;
347
#if USE_MBSLOCK
Mark Andrews's avatar
Mark Andrews committed
348
	isc_rwlock_t			mbslock;
349
#endif
Mark Andrews's avatar
Mark Andrews committed
350 351 352 353 354 355
	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;
356 357
#ifdef LRU_DEBUG
#define DUMP_INTERVAL 30        /* seconds */
Mark Andrews's avatar
Mark Andrews committed
358 359
	isc_timer_t *			dumptimer;
	isc_time_t			dump_time;
360
#endif
Mark Andrews's avatar
Mark Andrews committed
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
	/* 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;
376 377

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

Mark Andrews's avatar
Mark Andrews committed
387 388
#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
389

390
/*%
391 392 393
 * Private addrinfo flags.  These must not conflict with DNS_FETCHOPT_NOEDNS0,
 * which we also use as an addrinfo flag.
 */
394 395 396
#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
397
					 == 0)
398
#define ISFORWARDER(a)                  (((a)->flags & \
Mark Andrews's avatar
Mark Andrews committed
399
					 FCTX_ADDRINFO_FORWARDER) != 0)
Bob Halley's avatar
Bob Halley committed
400

401 402
#define NXDOMAIN(r) (((r)->attributes & DNS_RDATASETATTR_NXDOMAIN) != 0)

Bob Halley's avatar
Bob Halley committed
403
static void destroy(dns_resolver_t *res);
Bob Halley's avatar
Bob Halley committed
404
static void empty_bucket(dns_resolver_t *res);
Bob Halley's avatar
Bob Halley committed
405
static isc_result_t resquery_send(resquery_t *query);
Bob Halley's avatar
Bob Halley committed
406
static void resquery_response(isc_task_t *task, isc_event_t *event);
Bob Halley's avatar
Bob Halley committed
407
static void resquery_connected(isc_task_t *task, isc_event_t *event);
Bob Halley's avatar
Bob Halley committed
408
static void fctx_try(fetchctx_t *fctx);
Bob Halley's avatar
Bob Halley committed
409
static isc_boolean_t fctx_destroy(fetchctx_t *fctx);
410
static isc_result_t ncache_adderesult(dns_message_t *message,
Mark Andrews's avatar
Mark Andrews committed
411 412 413 414 415
				      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);
416
static void validated(isc_task_t *task, isc_event_t *event);
417
static void maybe_destroy(fetchctx_t *fctx);
418

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

423 424 425 426 427 428 429 430 431
/*%
 * Increment resolver-related statistics counters.
 */
static inline void
inc_stats(dns_resolver_t *res, dns_statscounter_t counter) {
	if (res->view->resstats != NULL)
		dns_generalstats_increment(res->view->resstats, counter);
}

432 433
static isc_result_t
valcreate(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo, dns_name_t *name,
Mark Andrews's avatar
Mark Andrews committed
434 435 436
	  dns_rdatatype_t type, dns_rdataset_t *rdataset,
	  dns_rdataset_t *sigrdataset, unsigned int valoptions,
	  isc_task_t *task)
437
{
Mark Andrews's avatar
Mark Andrews committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
	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) {
458
		inc_stats(fctx->res, dns_resstatscounter_val);
Mark Andrews's avatar
Mark Andrews committed
459 460 461 462 463 464 465 466 467
		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);
468
}
Bob Halley's avatar
Bob Halley committed
469

470
static isc_boolean_t
471
fix_mustbedelegationornxdomain(dns_message_t *message, fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
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 522 523 524 525 526 527 528 529 530 531 532 533
	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);
	}
534 535

 munge:
Mark Andrews's avatar
Mark Andrews committed
536 537 538 539 540 541
	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);
542 543
}

Bob Halley's avatar
Bob Halley committed
544
static inline isc_result_t
Bob Halley's avatar
Bob Halley committed
545
fctx_starttimer(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
546 547 548 549 550 551 552 553 554
	/*
	 * 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
555 556
}

Bob Halley's avatar
Bob Halley committed
557 558
static inline void
fctx_stoptimer(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
	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
574 575
}

576 577 578

static inline isc_result_t
fctx_startidletimer(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
579 580 581 582 583 584 585
	/*
	 * 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));
586 587 588 589 590 591
}

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


595 596
static inline void
resquery_destroy(resquery_t **queryp) {
Mark Andrews's avatar
Mark Andrews committed
597
	resquery_t *query;
598

Mark Andrews's avatar
Mark Andrews committed
599 600 601
	REQUIRE(queryp != NULL);
	query = *queryp;
	REQUIRE(!ISC_LINK_LINKED(query, link));
602

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

Mark Andrews's avatar
Mark Andrews committed
605 606 607 608 609 610
	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;
611 612
}

Bob Halley's avatar
Bob Halley committed
613
static void
Bob Halley's avatar
Bob Halley committed
614
fctx_cancelquery(resquery_t **queryp, dns_dispatchevent_t **deventp,
Mark Andrews's avatar
Mark Andrews committed
615
		 isc_time_t *finish, isc_boolean_t no_response)
Bob Halley's avatar
Bob Halley committed
616
{
Mark Andrews's avatar
Mark Andrews committed
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 730 731 732 733 734 735 736 737 738 739 740 741
	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
742 743 744
}

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

Mark Andrews's avatar
Mark Andrews committed
748
	FCTXTRACE("cancelqueries");
Bob Halley's avatar
Bob Halley committed
749

Mark Andrews's avatar
Mark Andrews committed
750 751 752 753 754 755
	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
756 757
}

Bob Halley's avatar
Bob Halley committed
758
static void
Bob Halley's avatar
Bob Halley committed
759
fctx_cleanupfinds(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
760 761 762 763 764 765 766 767 768 769 770 771
	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
772 773
}

774 775
static void
fctx_cleanupaltfinds(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
776 777 778 779 780 781 782 783 784 785 786 787
	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;
788 789
}

790 791
static void
fctx_cleanupforwaddrs(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
792
	dns_adbaddrinfo_t *addr, *next_addr;
793

Mark Andrews's avatar
Mark Andrews committed
794
	REQUIRE(ISC_LIST_EMPTY(fctx->queries));
795

Mark Andrews's avatar
Mark Andrews committed
796 797 798 799 800 801 802
	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);
	}
803 804
}

805 806
static void
fctx_cleanupaltaddrs(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
807
	dns_adbaddrinfo_t *addr, *next_addr;
808

Mark Andrews's avatar
Mark Andrews committed
809
	REQUIRE(ISC_LIST_EMPTY(fctx->queries));
810

Mark Andrews's avatar
Mark Andrews committed
811 812 813 814 815 816 817
	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);
	}
818 819
}

Bob Halley's avatar
Bob Halley committed
820
static inline void
821
fctx_stopeverything(fetchctx_t *fctx, isc_boolean_t no_response) {
Mark Andrews's avatar
Mark Andrews committed
822 823 824 825 826 827 828
	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
829
}
Bob Halley's avatar
Bob Halley committed
830

Bob Halley's avatar
Bob Halley committed
831 832
static inline void
fctx_sendevents(fetchctx_t *fctx, isc_result_t result) {
Mark Andrews's avatar
Mark Andrews committed
833 834 835 836 837
	dns_fetchevent_t *event, *next_event;
	isc_task_t *task;
	unsigned int count = 0;
	isc_interval_t i;
	isc_boolean_t logit = ISC_FALSE;
838
	unsigned int old_spillat;
Automatic Updater's avatar
Automatic Updater committed
839
	unsigned int new_spillat = 0;	/* initialized to silence
840
					   compiler warnings */
841

Mark Andrews's avatar
Mark Andrews committed
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 871 872 873 874 875 876 877 878 879 880 881 882
	/*
	 * 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) {
883
			old_spillat = fctx->res->spillat;
Mark Andrews's avatar
Mark Andrews committed
884 885 886 887
			fctx->res->spillat += 5;
			if (fctx->res->spillat > fctx->res->spillatmax &&
			    fctx->res->spillatmax != 0)
				fctx->res->spillat = fctx->res->spillatmax;
888 889
			new_spillat = fctx->res->spillat;
			if (new_spillat != old_spillat) {
Mark Andrews's avatar
Mark Andrews committed
890
				logit = ISC_TRUE;
891
			}
Mark Andrews's avatar
Mark Andrews committed
892 893 894 895 896 897 898 899 900 901 902 903 904
			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
905
}
Bob Halley's avatar
Bob Halley committed
906

Bob Halley's avatar
Bob Halley committed
907 908
static void
fctx_done(fetchctx_t *fctx, isc_result_t result) {
Mark Andrews's avatar
Mark Andrews committed
909 910
	dns_resolver_t *res;
	isc_boolean_t no_response;
Bob Halley's avatar
Bob Halley committed
911

Mark Andrews's avatar
Mark Andrews committed
912
	FCTXTRACE("done");
Bob Halley's avatar
Bob Halley committed
913

Mark Andrews's avatar
Mark Andrews committed
914
	res = fctx->res;
Bob Halley's avatar
Bob Halley committed
915

Mark Andrews's avatar
Mark Andrews committed
916 917 918 919 920
	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
921

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

Mark Andrews's avatar
Mark Andrews committed
924 925 926
	fctx->state = fetchstate_done;
	fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
	fctx_sendevents(fctx, result);
Bob Halley's avatar
Bob Halley committed
927

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

Bob Halley's avatar
Bob Halley committed
931
static void
Bob Halley's avatar
Bob Halley committed
932
resquery_senddone(isc_task_t *task, isc_event_t *event) {
Mark Andrews's avatar
Mark Andrews committed
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 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
	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
1005 1006
}

Bob Halley's avatar
Bob Halley committed
1007
static inline isc_result_t
1008 1009
fctx_addopt(dns_message_t *message, unsigned int version,
	    isc_uint16_t udpsize, isc_boolean_t request_nsid)
1010
{
Mark Andrews's avatar
Mark Andrews committed
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;

	/*
1045
	 * Set EDNS options if applicable
Mark Andrews's avatar
Mark Andrews committed
1046
	 */
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
	if (request_nsid) {
		/* Send empty NSID option (RFC5001) */
		unsigned char data[4];
		isc_buffer_t buf;

		isc_buffer_init(&buf, data, sizeof(data));
		isc_buffer_putuint16(&buf, DNS_OPT_NSID);
		isc_buffer_putuint16(&buf, 0);
		rdata->data = data;
		rdata->length = sizeof(data);
	} else {
		rdata->data = NULL;
		rdata->length = 0;
	}

Mark Andrews's avatar
Mark Andrews committed
1062 1063 1064 1065 1066 1067 1068 1069 1070
	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
1071 1072
}

1073 1074
static inline void
fctx_setretryinterval(fetchctx_t *fctx, unsigned int rtt) {
Mark Andrews's avatar
Mark Andrews committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
	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);
1107 1108
}

Bob Halley's avatar
Bob Halley committed
1109 1110
static isc_result_t
fctx_query(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
Mark Andrews's avatar
Mark Andrews committed
1111
	   unsigned int options)
Bob Halley's avatar
Bob Halley committed
1112
{
Mark Andrews's avatar
Mark Andrews committed
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 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
	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;
1203

1204
#ifndef BROKEN_TCP_BIND_BEFORE_CONNECT
Mark Andrews's avatar
Mark Andrews committed
1205 1206 1207
		result = isc_socket_bind(query->tcpsocket, &addr);
		if (result != ISC_R_SUCCESS)
			goto cleanup_socket;
1208
#endif
1209

Mark Andrews's avatar
Mark Andrews committed
1210 1211 1212 1213 1214 1215 1216 1217