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

Francis Dupont's avatar
Francis Dupont committed
18
/* $Id: resolver.c,v 1.389 2009/01/17 14:59:03 fdupont 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
	/* Locked by task event serialization. */
	unsigned int			magic;
	fetchctx_t *			fctx;
	isc_mem_t *			mctx;
	dns_dispatchmgr_t *		dispatchmgr;
	dns_dispatch_t *		dispatch;
127
	isc_boolean_t			exclusivesocket;
Mark Andrews's avatar
Mark Andrews committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141
	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
142 143
} resquery_t;

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

147
#define RESQUERY_ATTR_CANCELED          0x02
148

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

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

160 161 162 163 164 165
typedef enum {
	badns_unreachable = 0,
	badns_response,
	badns_validation
} badnstype_t;

Bob Halley's avatar
Bob Halley committed
166
struct fetchctx {
Mark Andrews's avatar
Mark Andrews committed
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 233
	/*% 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.
	 */
234
	dns_name_t 			nsname;
Mark Andrews's avatar
Mark Andrews committed
235 236 237 238 239 240 241
	dns_fetch_t *			nsfetch;
	dns_rdataset_t			nsrrset;

	/*%
	 * Number of queries that reference this context.
	 */
	unsigned int			nqueries;
242 243 244 245 246 247

	/*%
	 * The reason to print when logging a successful
	 * response to a query.
	 */
	const char *			reason;
Evan Hunt's avatar
Evan Hunt committed
248 249 250 251 252 253

	/*%
	 * Random numbers to use for mixing up server addresses.
	 */
	isc_uint32_t                    rand_buf;
	isc_uint32_t                    rand_bits;
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

	/*%
	 * Fetch-local statistics for detailed logging.
	 */
	isc_result_t			result; /*%< fetch result  */
	isc_result_t			vresult; /*%< validation result  */
	int				exitline;
	isc_time_t			start;
	isc_uint64_t			duration;
	isc_boolean_t			logged;
	unsigned int			querysent;
	unsigned int			referrals;
	unsigned int			lamecount;
	unsigned int			neterr;
	unsigned int			badresp;
	unsigned int			adberr;
	unsigned int			findfail;
	unsigned int			valfail;
Bob Halley's avatar
Bob Halley committed
272
};
Bob Halley's avatar
Bob Halley committed
273

Mark Andrews's avatar
Mark Andrews committed
274 275
#define FCTX_MAGIC			ISC_MAGIC('F', '!', '!', '!')
#define VALID_FCTX(fctx)		ISC_MAGIC_VALID(fctx, FCTX_MAGIC)
276 277 278 279 280 281 282 283 284 285 286 287

#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
288
				 0)
289
#define GLUING(f)               (((f)->attributes & FCTX_ATTR_GLUING) != \
Mark Andrews's avatar
Mark Andrews committed
290
				 0)
291
#define ADDRWAIT(f)             (((f)->attributes & FCTX_ATTR_ADDRWAIT) != \
Mark Andrews's avatar
Mark Andrews committed
292
				 0)
293
#define SHUTTINGDOWN(f)         (((f)->attributes & FCTX_ATTR_SHUTTINGDOWN) \
Mark Andrews's avatar
Mark Andrews committed
294
				 != 0)
295 296 297 298 299
#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
300

301
typedef struct {
Mark Andrews's avatar
Mark Andrews committed
302 303
	dns_adbaddrinfo_t *		addrinfo;
	fetchctx_t *			fctx;
304 305
} dns_valarg_t;

Bob Halley's avatar
Bob Halley committed
306
struct dns_fetch {
Mark Andrews's avatar
Mark Andrews committed
307 308
	unsigned int			magic;
	fetchctx_t *			private;
Bob Halley's avatar
Bob Halley committed
309 310
};

Mark Andrews's avatar
Mark Andrews committed
311 312
#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
313 314

typedef struct fctxbucket {
Mark Andrews's avatar
Mark Andrews committed
315 316 317 318 319
	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
320 321
} fctxbucket_t;

322
typedef struct alternate {
Mark Andrews's avatar
Mark Andrews committed
323 324 325 326 327 328 329 330 331
	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;
332 333
} alternate_t;

Bob Halley's avatar
Bob Halley committed
334
struct dns_resolver {
Mark Andrews's avatar
Mark Andrews committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
	/* Unlocked. */
	unsigned int			magic;
	isc_mem_t *			mctx;
	isc_mutex_t			lock;
	isc_mutex_t			nlock;
	isc_mutex_t			primelock;
	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;
350
	isc_boolean_t			exclusivev4;
Mark Andrews's avatar
Mark Andrews committed
351
	dns_dispatch_t *		dispatchv6;
352
	isc_boolean_t			exclusivev6;
Mark Andrews's avatar
Mark Andrews committed
353 354 355 356 357 358
	unsigned int			ndisps;
	unsigned int			nbuckets;
	fctxbucket_t *			buckets;
	isc_uint32_t			lame_ttl;
	ISC_LIST(alternate_t)		alternates;
	isc_uint16_t			udpsize;
359
#if USE_ALGLOCK
Mark Andrews's avatar
Mark Andrews committed
360
	isc_rwlock_t			alglock;
361
#endif
Mark Andrews's avatar
Mark Andrews committed
362
	dns_rbt_t *			algorithms;
363
#if USE_MBSLOCK
Mark Andrews's avatar
Mark Andrews committed
364
	isc_rwlock_t			mbslock;
365
#endif
Mark Andrews's avatar
Mark Andrews committed
366 367 368 369 370
	dns_rbt_t *			mustbesecure;
	unsigned int			spillatmax;
	unsigned int			spillatmin;
	isc_timer_t *			spillattimer;
	isc_boolean_t			zero_no_soa_ttl;
371

Mark Andrews's avatar
Mark Andrews committed
372 373 374 375 376 377 378 379 380 381 382 383
	/* 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;
Bob Halley's avatar
Bob Halley committed
384 385
};

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

389
/*%
390 391 392
 * Private addrinfo flags.  These must not conflict with DNS_FETCHOPT_NOEDNS0,
 * which we also use as an addrinfo flag.
 */
393 394
#define FCTX_ADDRINFO_MARK              0x0001
#define FCTX_ADDRINFO_FORWARDER         0x1000
Evan Hunt's avatar
Evan Hunt committed
395
#define FCTX_ADDRINFO_TRIED             0x2000
396
#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)
Evan Hunt's avatar
Evan Hunt committed
400 401
#define TRIED(a)                        (((a)->flags & \
					 FCTX_ADDRINFO_TRIED) != 0)
Bob Halley's avatar
Bob Halley committed
402

403 404
#define NXDOMAIN(r) (((r)->attributes & DNS_RDATASETATTR_NXDOMAIN) != 0)

Bob Halley's avatar
Bob Halley committed
405
static void destroy(dns_resolver_t *res);
Bob Halley's avatar
Bob Halley committed
406
static void empty_bucket(dns_resolver_t *res);
Bob Halley's avatar
Bob Halley committed
407
static isc_result_t resquery_send(resquery_t *query);
Bob Halley's avatar
Bob Halley committed
408
static void resquery_response(isc_task_t *task, isc_event_t *event);
Bob Halley's avatar
Bob Halley committed
409
static void resquery_connected(isc_task_t *task, isc_event_t *event);
410
static void fctx_try(fetchctx_t *fctx, isc_boolean_t retrying);
Bob Halley's avatar
Bob Halley committed
411
static isc_boolean_t fctx_destroy(fetchctx_t *fctx);
412
static isc_result_t ncache_adderesult(dns_message_t *message,
Mark Andrews's avatar
Mark Andrews committed
413 414 415
				      dns_db_t *cache, dns_dbnode_t *node,
				      dns_rdatatype_t covers,
				      isc_stdtime_t now, dns_ttl_t maxttl,
416
				      isc_boolean_t optout,
Mark Andrews's avatar
Mark Andrews committed
417 418
				      dns_rdataset_t *ardataset,
				      isc_result_t *eresultp);
419
static void validated(isc_task_t *task, isc_event_t *event);
420
static void maybe_destroy(fetchctx_t *fctx);
421
static void add_bad(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
422
		    isc_result_t reason, badnstype_t badtype);
423

424 425 426 427 428 429 430 431 432
/*%
 * 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);
}

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

471
static isc_boolean_t
472
fix_mustbedelegationornxdomain(dns_message_t *message, fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
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 534
	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);
	}
535 536

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

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

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

577 578

static inline isc_result_t
579
fctx_startidletimer(fetchctx_t *fctx, isc_interval_t *interval) {
Mark Andrews's avatar
Mark Andrews committed
580 581 582 583 584
	/*
	 * Start the idle timer for fctx.  The lifetime timer continues
	 * to be in effect.
	 */
	return (isc_timer_reset(fctx->timer, isc_timertype_once,
585
				&fctx->expires, 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
	fetchctx_t *fctx;
	resquery_t *query;
	unsigned int rtt;
	unsigned int factor;
	dns_adbfind_t *find;
	dns_adbaddrinfo_t *addrinfo;
623
	isc_socket_t *socket;
Mark Andrews's avatar
Mark Andrews committed
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

	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);
	}

Evan Hunt's avatar
Evan Hunt committed
664 665 666 667 668 669
	/* Remember that the server has been tried. */
	if (!TRIED(query->addrinfo)) {
		dns_adb_changeflags(fctx->adb, query->addrinfo,
				    FCTX_ADDRINFO_TRIED, FCTX_ADDRINFO_TRIED);
	}

Mark Andrews's avatar
Mark Andrews committed
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
	/*
	 * 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);
	}

	/*
	 * 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.
	 */
717
	if (RESQUERY_CONNECTING(query)) {
Mark Andrews's avatar
Mark Andrews committed
718 719 720
		/*
		 * Cancel the connect.
		 */
721 722 723 724 725 726 727 728 729 730 731
		if (query->tcpsocket != NULL) {
			isc_socket_cancel(query->tcpsocket, NULL,
					  ISC_SOCKCANCEL_CONNECT);
		} else if (query->dispentry != NULL) {
			INSIST(query->exclusivesocket);
			socket = dns_dispatch_getentrysocket(query->dispentry);
			if (socket != NULL)
				isc_socket_cancel(socket, NULL,
						  ISC_SOCKCANCEL_CONNECT);
		}
	} else if (RESQUERY_SENDING(query)) {
Mark Andrews's avatar
Mark Andrews committed
732 733 734
		/*
		 * Cancel the pending send.
		 */
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
		if (query->exclusivesocket && query->dispentry != NULL)
			socket = dns_dispatch_getentrysocket(query->dispentry);
		else
			socket = dns_dispatch_getsocket(query->dispatch);
		if (socket != NULL)
			isc_socket_cancel(socket, NULL, ISC_SOCKCANCEL_SEND);
	}

	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);
Mark Andrews's avatar
Mark Andrews committed
753 754 755 756 757 758 759 760 761

	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
762 763 764
}

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

Mark Andrews's avatar
Mark Andrews committed
768
	FCTXTRACE("cancelqueries");
Bob Halley's avatar
Bob Halley committed
769

Mark Andrews's avatar
Mark Andrews committed
770 771 772 773 774 775
	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
776 777
}

Bob Halley's avatar
Bob Halley committed
778
static void
Bob Halley's avatar
Bob Halley committed
779
fctx_cleanupfinds(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
780 781 782 783 784 785 786 787 788 789 790 791
	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
792 793
}

794 795
static void
fctx_cleanupaltfinds(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
796 797 798 799 800 801 802 803 804 805 806 807
	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;
808 809
}

810 811
static void
fctx_cleanupforwaddrs(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
812
	dns_adbaddrinfo_t *addr, *next_addr;
813

Mark Andrews's avatar
Mark Andrews committed
814
	REQUIRE(ISC_LIST_EMPTY(fctx->queries));
815

Mark Andrews's avatar
Mark Andrews committed
816 817 818 819 820 821 822
	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);
	}
823 824
}

825 826
static void
fctx_cleanupaltaddrs(fetchctx_t *fctx) {
Mark Andrews's avatar
Mark Andrews committed
827
	dns_adbaddrinfo_t *addr, *next_addr;
828

Mark Andrews's avatar
Mark Andrews committed
829
	REQUIRE(ISC_LIST_EMPTY(fctx->queries));
830

Mark Andrews's avatar
Mark Andrews committed
831 832 833 834 835 836 837
	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);
	}
838 839
}

Bob Halley's avatar
Bob Halley committed
840
static inline void
841
fctx_stopeverything(fetchctx_t *fctx, isc_boolean_t no_response) {
Mark Andrews's avatar
Mark Andrews committed
842 843 844 845 846 847 848
	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
849
}
Bob Halley's avatar
Bob Halley committed
850

Bob Halley's avatar
Bob Halley committed
851
static inline void
852
fctx_sendevents(fetchctx_t *fctx, isc_result_t result, int line) {
Mark Andrews's avatar
Mark Andrews committed
853 854 855 856 857
	dns_fetchevent_t *event, *next_event;
	isc_task_t *task;
	unsigned int count = 0;
	isc_interval_t i;
	isc_boolean_t logit = ISC_FALSE;
858
	isc_time_t now;
859
	unsigned int old_spillat;
Automatic Updater's avatar
Automatic Updater committed
860
	unsigned int new_spillat = 0;	/* initialized to silence
861
					   compiler warnings */
862

Mark Andrews's avatar
Mark Andrews committed
863 864 865 866 867 868 869
	/*
	 * Caller must be holding the appropriate bucket lock.
	 */
	REQUIRE(fctx->state == fetchstate_done);

	FCTXTRACE("sendevents");

870
	/*
Automatic Updater's avatar
Automatic Updater committed
871
	 * Keep some record of fetch result for logging later (if required).
872 873 874 875 876 877
	 */
	fctx->result = result;
	fctx->exitline = line;
	TIME_NOW(&now);
	fctx->duration = isc_time_microdiff(&now, &fctx->start);

Mark Andrews's avatar
Mark Andrews committed
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
	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) {
912
			old_spillat = fctx->res->spillat;
Mark Andrews's avatar
Mark Andrews committed
913 914 915 916
			fctx->res->spillat += 5;
			if (fctx->res->spillat > fctx->res->spillatmax &&
			    fctx->res->spillatmax != 0)
				fctx->res->spillat = fctx->res->spillatmax;
917 918
			new_spillat = fctx->res->spillat;
			if (new_spillat != old_spillat) {
Mark Andrews's avatar
Mark Andrews committed
919
				logit = ISC_TRUE;
920
			}
Mark Andrews's avatar
Mark Andrews committed
921 922 923 924 925 926 927 928 929 930 931 932 933
			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
934
}
Bob Halley's avatar
Bob Halley committed
935

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
static inline void
log_edns(fetchctx_t *fctx) {
	char domainbuf[DNS_NAME_FORMATSIZE];

	if (fctx->reason == NULL)
		return;

	dns_name_format(&fctx->domain, domainbuf, sizeof(domainbuf));
	isc_log_write(dns_lctx, DNS_LOGCATEGORY_EDNS_DISABLED,
		      DNS_LOGMODULE_RESOLVER, ISC_LOG_INFO,
		      "success resolving '%s' (in '%s'?) after %s",
		      fctx->info, domainbuf, fctx->reason);

	fctx->reason = NULL;
}

Bob Halley's avatar
Bob Halley committed
952
static void
953
fctx_done(fetchctx_t *fctx, isc_result_t result, int line) {
Mark Andrews's avatar
Mark Andrews committed
954 955
	dns_resolver_t *res;
	isc_boolean_t no_response;
Bob Halley's avatar
Bob Halley committed
956

957 958
	REQUIRE(line >= 0);

Mark Andrews's avatar
Mark Andrews committed
959
	FCTXTRACE("done");
Bob Halley's avatar
Bob Halley committed
960

Mark Andrews's avatar
Mark Andrews committed
961
	res = fctx->res;
Bob Halley's avatar
Bob Halley committed
962

963 964 965 966 967
	if (result == ISC_R_SUCCESS) {
		/*%
		 * Log any deferred EDNS timeout messages.
		 */
		log_edns(fctx);
Mark Andrews's avatar
Mark Andrews committed
968
		no_response = ISC_TRUE;
969
	 } else
Mark Andrews's avatar
Mark Andrews committed
970
		no_response = ISC_FALSE;
971 972

	fctx->reason = NULL;
Mark Andrews's avatar
Mark Andrews committed
973
	fctx_stopeverything(fctx, no_response);
Bob Halley's avatar
Bob Halley committed
974

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

Mark Andrews's avatar
Mark Andrews committed
977 978
	fctx->state = fetchstate_done;
	fctx->attributes &= ~FCTX_ATTR_ADDRWAIT;
979
	fctx_sendevents(fctx, result, line);
Bob Halley's avatar
Bob Halley committed
980

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

Bob Halley's avatar
Bob Halley committed
984
static void
985
process_sendevent(resquery_t *query, isc_event_t *event) {
Mark Andrews's avatar
Mark Andrews committed
986 987 988 989 990 991 992 993
	isc_socketevent_t *sevent = (isc_socketevent_t *)event;
	isc_boolean_t retry = ISC_FALSE;
	isc_result_t result;
	fetchctx_t *fctx;

	fctx = query->fctx;

	if (RESQUERY_CANCELED(query)) {
994
		if (query->sends == 0 && query->connects == 0) {
Mark Andrews's avatar
Mark Andrews committed
995 996
			/*
			 * This query was canceled while the
997
			 * isc_socket_sendto/connect() was in progress.
Mark Andrews's avatar
Mark Andrews committed
998 999 1000 1001 1002
			 */
			if (query->tcpsocket != NULL)
				isc_socket_detach(&query->tcpsocket);
			resquery_destroy(&query);
		}
1003
	} else {
Mark Andrews's avatar
Mark Andrews committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
		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.
			 */
1017 1018
			add_bad(fctx, query->addrinfo, sevent->result,
				badns_unreachable);
Mark Andrews's avatar
Mark Andrews committed
1019 1020 1021 1022 1023 1024 1025 1026
			fctx_cancelquery(&query, NULL, NULL, ISC_TRUE);
			retry = ISC_TRUE;
			break;

		default:
			fctx_cancelquery(&query, NULL, NULL, ISC_FALSE);
			break;
		}
1027
	}
Mark Andrews's avatar
Mark Andrews committed
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

	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)
1039
			fctx_done(fctx, result, __LINE__);
Mark Andrews's avatar
Mark Andrews committed
1040
		else
1041
			fctx_try(fctx, ISC_TRUE);
Mark Andrews's avatar
Mark Andrews committed
1042
	}
Bob Halley's avatar
Bob Halley committed
1043 1044
}

1045 1046 1047 1048 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 1081 1082 1083 1084 1085 1086
static void
resquery_udpconnected(isc_task_t *task, isc_event_t *event) {
	resquery_t *query = event->ev_arg;

	REQUIRE(event->ev_type == ISC_SOCKEVENT_CONNECT);

	QTRACE("udpconnected");

	UNUSED(task);

	INSIST(RESQUERY_CONNECTING(query));

	query->connects--;

	process_sendevent(query, event);
}

static void
resquery_senddone(isc_task_t *task, isc_event_t *event) {
	resquery_t *query = event->ev_arg;

	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--;

	process_sendevent(query, event);
}

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

	/*
1125
	 * Set EDNS options if applicable
Mark Andrews's avatar
Mark Andrews committed
1126
	 */
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
	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
1142 1143 1144 1145 1146 1147 1148 1149 1150
	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
1151 1152
}

1153 1154
static inline void
fctx_setretryinterval(fetchctx_t *fctx, unsigned int rtt) {
Mark Andrews's avatar
Mark Andrews committed
1155 1156 1157 1158
	unsigned int seconds;
	unsigned int us;

	/*
1159
	 * We retry every .8 seconds the first two times through the address
Mark Andrews's avatar
Mark Andrews committed
1160 1161 1162
	 * list, and then we do exponential back-off.
	 */
	if (fctx->restarts < 3)
1163
		us = 800000;
Mark Andrews's avatar
Mark Andrews committed
1164
	else
1165
		us = (800000 << (fctx->restarts - 2));
Mark Andrews's avatar
Mark Andrews committed
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

	/*
	 * 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);
1187 1188
}

Bob Halley's avatar
Bob Halley committed
1189 1190
static isc_result_t
fctx_query(fetchctx_t *fctx, dns_adbaddrinfo_t *addrinfo,
Mark Andrews's avatar
Mark Andrews committed
1191
	   unsigned int options)
Bob Halley's avatar
Bob Halley committed
1192
{
Mark Andrews's avatar
Mark Andrews committed
1193 1194 1195 1196 1197 1198
	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;
1199
	unsigned int srtt;
Mark Andrews's avatar
Mark Andrews committed
1200 1201 1202 1203 1204 1205

	FCTXTRACE("query");

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

1206 1207 1208 1209 1210
	srtt = addrinfo->srtt;
	if (ISFORWARDER(addrinfo) && srtt < 1000000)
		srtt = 1000000;

	fctx_setretryinterval(fctx, srtt);
1211
	result = fctx_startidletimer(fctx, &fctx->interval);
Mark Andrews's avatar
Mark Andrews committed
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
	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;
1244
	query->exclusivesocket = ISC_FALSE;