xref: /openbsd-src/usr.sbin/nsd/query.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /*
2  * query.c -- nsd(8) the resolver.
3  *
4  * Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
5  *
6  * See LICENSE for the license.
7  *
8  */
9 
10 #include "config.h"
11 
12 #include <sys/types.h>
13 #include <sys/socket.h>
14 #include <netinet/in.h>
15 #include <arpa/inet.h>
16 #include <assert.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <limits.h>
20 #include <stddef.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <time.h>
25 #include <unistd.h>
26 #include <netdb.h>
27 
28 #include "answer.h"
29 #include "axfr.h"
30 #include "dns.h"
31 #include "dname.h"
32 #include "nsd.h"
33 #include "namedb.h"
34 #include "query.h"
35 #include "util.h"
36 #include "options.h"
37 #include "nsec3.h"
38 #include "tsig.h"
39 
40 /* [Bug #253] Adding unnecessary NS RRset may lead to undesired truncation.
41  * This function determines if the final response packet needs the NS RRset
42  * included. Currently, it will only return negative if QTYPE == DNSKEY|DS.
43  * This way, resolvers won't fallback to TCP unnecessarily when priming
44  * trust anchors.
45  */
46 static int answer_needs_ns(struct query  *query);
47 
48 static int add_rrset(struct query  *query,
49 		     answer_type    *answer,
50 		     rr_section_type section,
51 		     domain_type    *owner,
52 		     rrset_type     *rrset);
53 
54 static void answer_authoritative(struct nsd	  *nsd,
55 				 struct query     *q,
56 				 answer_type      *answer,
57 				 size_t            domain_number,
58 				 int               exact,
59 				 domain_type      *closest_match,
60 				 domain_type      *closest_encloser,
61 				 const dname_type *qname);
62 
63 static void answer_lookup_zone(struct nsd *nsd, struct query *q,
64 			       answer_type *answer, size_t domain_number,
65 			       int exact, domain_type *closest_match,
66 			       domain_type *closest_encloser,
67 			       const dname_type *qname);
68 
69 void
70 query_put_dname_offset(struct query *q, domain_type *domain, uint16_t offset)
71 {
72 	assert(q);
73 	assert(domain);
74 	assert(domain->number > 0);
75 
76 	if (offset > MAX_COMPRESSION_OFFSET)
77 		return;
78 	if (q->compressed_dname_count >= MAX_COMPRESSED_DNAMES)
79 		return;
80 
81 	q->compressed_dname_offsets[domain->number] = offset;
82 	q->compressed_dnames[q->compressed_dname_count] = domain;
83 	++q->compressed_dname_count;
84 }
85 
86 void
87 query_clear_dname_offsets(struct query *q, size_t max_offset)
88 {
89 	while (q->compressed_dname_count > 0
90 	       && (q->compressed_dname_offsets[q->compressed_dnames[q->compressed_dname_count - 1]->number]
91 		   >= max_offset))
92 	{
93 		q->compressed_dname_offsets[q->compressed_dnames[q->compressed_dname_count - 1]->number] = 0;
94 		--q->compressed_dname_count;
95 	}
96 }
97 
98 void
99 query_clear_compression_tables(struct query *q)
100 {
101 	uint16_t i;
102 
103 	for (i = 0; i < q->compressed_dname_count; ++i) {
104 		assert(q->compressed_dnames);
105 		q->compressed_dname_offsets[q->compressed_dnames[i]->number] = 0;
106 	}
107 	q->compressed_dname_count = 0;
108 }
109 
110 void
111 query_add_compression_domain(struct query *q, domain_type *domain, uint16_t offset)
112 {
113 	while (domain->parent) {
114 		DEBUG(DEBUG_NAME_COMPRESSION, 2,
115 		      (LOG_INFO, "query dname: %s, number: %lu, offset: %u\n",
116 		       domain_to_string(domain),
117 		       (unsigned long) domain->number,
118 		       offset));
119 		query_put_dname_offset(q, domain, offset);
120 		offset += label_length(dname_name(domain_dname(domain))) + 1;
121 		domain = domain->parent;
122 	}
123 }
124 
125 /*
126  * Generate an error response with the specified RCODE.
127  */
128 query_state_type
129 query_error (struct query *q, nsd_rc_type rcode)
130 {
131 	if (rcode == NSD_RC_DISCARD) {
132 		return QUERY_DISCARDED;
133 	}
134 
135 	buffer_clear(q->packet);
136 
137 	QR_SET(q->packet);	   /* This is an answer.  */
138 	AD_CLR(q->packet);
139 	RCODE_SET(q->packet, (int) rcode); /* Error code.  */
140 
141 	/* Truncate the question as well... */
142 	QDCOUNT_SET(q->packet, 0);
143 	ANCOUNT_SET(q->packet, 0);
144 	NSCOUNT_SET(q->packet, 0);
145 	ARCOUNT_SET(q->packet, 0);
146 	buffer_set_position(q->packet, QHEADERSZ);
147 	return QUERY_PROCESSED;
148 }
149 
150 static int
151 query_ratelimit_err(nsd_type* nsd)
152 {
153 	time_t now = time(NULL);
154 	if(nsd->err_limit_time == now) {
155 		/* see if limit is exceeded for this second */
156 		if(nsd->err_limit_count++ > ERROR_RATELIMIT)
157 			return 1;
158 	} else {
159 		/* new second, new limits */
160 		nsd->err_limit_time = now;
161 		nsd->err_limit_count = 1;
162 	}
163 	return 0;
164 }
165 
166 static query_state_type
167 query_formerr (struct query *query, nsd_type* nsd)
168 {
169 	int opcode = OPCODE(query->packet);
170 	if(query_ratelimit_err(nsd))
171 		return QUERY_DISCARDED;
172 	FLAGS_SET(query->packet, FLAGS(query->packet) & 0x0100U);
173 			/* Preserve the RD flag. Clear the rest. */
174 	OPCODE_SET(query->packet, opcode);
175 	return query_error(query, NSD_RC_FORMAT);
176 }
177 
178 static void
179 query_cleanup(void *data)
180 {
181 	query_type *query = (query_type *) data;
182 	region_destroy(query->region);
183 }
184 
185 query_type *
186 query_create(region_type *region, uint16_t *compressed_dname_offsets,
187 	size_t compressed_dname_size, domain_type **compressed_dnames)
188 {
189 	query_type *query
190 		= (query_type *) region_alloc_zero(region, sizeof(query_type));
191 	/* create region with large block size, because the initial chunk
192 	   saves many mallocs in the server */
193 	query->region = region_create_custom(xalloc, free, 16384, 16384/8, 32, 0);
194 	query->compressed_dname_offsets = compressed_dname_offsets;
195 	query->compressed_dnames = compressed_dnames;
196 	query->packet = buffer_create(region, QIOBUFSZ);
197 	region_add_cleanup(region, query_cleanup, query);
198 	query->compressed_dname_offsets_size = compressed_dname_size;
199 	tsig_create_record(&query->tsig, region);
200 	query->tsig_prepare_it = 1;
201 	query->tsig_update_it = 1;
202 	query->tsig_sign_it = 1;
203 	return query;
204 }
205 
206 void
207 query_reset(query_type *q, size_t maxlen, int is_tcp)
208 {
209 	/*
210 	 * As long as less than 4Kb (region block size) has been used,
211 	 * this call to free_all is free, the block is saved for re-use,
212 	 * so no malloc() or free() calls are done.
213 	 * at present use of the region is for:
214 	 *   o query qname dname_type (255 max).
215 	 *   o wildcard expansion domain_type (7*ptr+u32+2bytes)+(5*ptr nsec3)
216 	 *   o wildcard expansion for additional section domain_type.
217 	 *   o nsec3 hashed name(s) (3 dnames for a nonexist_proof,
218 	 *     one proof per wildcard and for nx domain).
219 	 */
220 	region_free_all(q->region);
221 	q->addrlen = sizeof(q->addr);
222 	q->maxlen = maxlen;
223 	q->reserved_space = 0;
224 	buffer_clear(q->packet);
225 	edns_init_record(&q->edns);
226 	tsig_init_record(&q->tsig, NULL, NULL);
227 	q->tsig_prepare_it = 1;
228 	q->tsig_update_it = 1;
229 	q->tsig_sign_it = 1;
230 	q->tcp = is_tcp;
231 	q->qname = NULL;
232 	q->qtype = 0;
233 	q->qclass = 0;
234 	q->zone = NULL;
235 	q->opcode = 0;
236 	q->cname_count = 0;
237 	q->delegation_domain = NULL;
238 	q->delegation_rrset = NULL;
239 	q->compressed_dname_count = 0;
240 	q->number_temporary_domains = 0;
241 
242 	q->axfr_is_done = 0;
243 	q->axfr_zone = NULL;
244 	q->axfr_current_domain = NULL;
245 	q->axfr_current_rrset = NULL;
246 	q->axfr_current_rr = 0;
247 
248 #ifdef RATELIMIT
249 	q->wildcard_domain = NULL;
250 #endif
251 }
252 
253 /* get a temporary domain number (or 0=failure) */
254 static domain_type*
255 query_get_tempdomain(struct query *q)
256 {
257 	static domain_type d[EXTRA_DOMAIN_NUMBERS];
258 	if(q->number_temporary_domains >= EXTRA_DOMAIN_NUMBERS)
259 		return 0;
260 	q->number_temporary_domains ++;
261 	memset(&d[q->number_temporary_domains-1], 0, sizeof(domain_type));
262 	d[q->number_temporary_domains-1].number = q->compressed_dname_offsets_size +
263 		q->number_temporary_domains - 1;
264 	return &d[q->number_temporary_domains-1];
265 }
266 
267 static void
268 query_addtxt(struct query  *q,
269 	     const uint8_t *dname,
270 	     uint16_t       klass,
271 	     uint32_t       ttl,
272 	     const char    *txt)
273 {
274 	size_t txt_length = strlen(txt);
275 	uint8_t len = (uint8_t) txt_length;
276 
277 	assert(txt_length <= UCHAR_MAX);
278 
279 	/* Add the dname */
280 	if (dname >= buffer_begin(q->packet)
281 	    && dname <= buffer_current(q->packet))
282 	{
283 		buffer_write_u16(q->packet,
284 				 0xc000 | (dname - buffer_begin(q->packet)));
285 	} else {
286 		buffer_write(q->packet, dname + 1, *dname);
287 	}
288 
289 	buffer_write_u16(q->packet, TYPE_TXT);
290 	buffer_write_u16(q->packet, klass);
291 	buffer_write_u32(q->packet, ttl);
292 	buffer_write_u16(q->packet, len + 1);
293 	buffer_write_u8(q->packet, len);
294 	buffer_write(q->packet, txt, len);
295 }
296 
297 /*
298  * Parse the question section of a query.  The normalized query name
299  * is stored in QUERY->name, the class in QUERY->klass, and the type
300  * in QUERY->type.
301  */
302 static int
303 process_query_section(query_type *query)
304 {
305 	uint8_t qnamebuf[MAXDOMAINLEN];
306 
307 	buffer_set_position(query->packet, QHEADERSZ);
308 	/* Lets parse the query name and convert it to lower case.  */
309 	if(!packet_read_query_section(query->packet, qnamebuf,
310 		&query->qtype, &query->qclass))
311 		return 0;
312 	query->qname = dname_make(query->region, qnamebuf, 1);
313 	return 1;
314 }
315 
316 
317 /*
318  * Process an optional EDNS OPT record.  Sets QUERY->EDNS to 0 if
319  * there was no EDNS record, to -1 if there was an invalid or
320  * unsupported EDNS record, and to 1 otherwise.  Updates QUERY->MAXLEN
321  * if the EDNS record specifies a maximum supported response length.
322  *
323  * Return NSD_RC_FORMAT on failure, NSD_RC_OK on success.
324  */
325 static nsd_rc_type
326 process_edns(nsd_type* nsd, struct query *q)
327 {
328 	if (q->edns.status == EDNS_ERROR) {
329 		/* The only error is VERSION not implemented */
330 		return NSD_RC_FORMAT;
331 	}
332 
333 	if (q->edns.status == EDNS_OK) {
334 		/* Only care about UDP size larger than normal... */
335 		if (!q->tcp && q->edns.maxlen > UDP_MAX_MESSAGE_LEN) {
336 			size_t edns_size;
337 #if defined(INET6)
338 			if (q->addr.ss_family == AF_INET6) {
339 				edns_size = nsd->ipv6_edns_size;
340 			} else
341 #endif
342 			edns_size = nsd->ipv4_edns_size;
343 
344 			if (q->edns.maxlen < edns_size) {
345 				q->maxlen = q->edns.maxlen;
346 			} else {
347 				q->maxlen = edns_size;
348 			}
349 
350 #if defined(INET6) && !defined(IPV6_USE_MIN_MTU) && !defined(IPV6_MTU)
351 			/*
352 			 * Use IPv6 minimum MTU to avoid sending
353 			 * packets that are too large for some links.
354 			 * IPv6 will not automatically fragment in
355 			 * this case (unlike IPv4).
356 			 */
357 			if (q->addr.ss_family == AF_INET6
358 			    && q->maxlen > IPV6_MIN_MTU)
359 			{
360 				q->maxlen = IPV6_MIN_MTU;
361 			}
362 #endif
363 		}
364 
365 		/* Strip the OPT resource record off... */
366 		buffer_set_position(q->packet, q->edns.position);
367 		buffer_set_limit(q->packet, q->edns.position);
368 		ARCOUNT_SET(q->packet, ARCOUNT(q->packet) - 1);
369 	}
370 	return NSD_RC_OK;
371 }
372 
373 /*
374  * Processes TSIG.
375  * Sets error when tsig does not verify on the query.
376  */
377 static nsd_rc_type
378 process_tsig(struct query* q)
379 {
380 	if(q->tsig.status == TSIG_ERROR)
381 		return NSD_RC_FORMAT;
382 	if(q->tsig.status == TSIG_OK) {
383 		if(!tsig_from_query(&q->tsig)) {
384 			char a[128];
385 			addr2str(&q->addr, a, sizeof(a));
386 			log_msg(LOG_ERR, "query: bad tsig (%s) for key %s from %s",
387 				tsig_error(q->tsig.error_code),
388 				dname_to_string(q->tsig.key_name, NULL), a);
389 			return NSD_RC_NOTAUTH;
390 		}
391 		buffer_set_limit(q->packet, q->tsig.position);
392 		ARCOUNT_SET(q->packet, ARCOUNT(q->packet) - 1);
393 		tsig_prepare(&q->tsig);
394 		tsig_update(&q->tsig, q->packet, buffer_limit(q->packet));
395 		if(!tsig_verify(&q->tsig)) {
396 			char a[128];
397 			addr2str(&q->addr, a, sizeof(a));
398 			log_msg(LOG_ERR, "query: bad tsig signature for key %s from %s",
399 				dname_to_string(q->tsig.key->name, NULL), a);
400 			return NSD_RC_NOTAUTH;
401 		}
402 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "query good tsig signature for %s",
403 			dname_to_string(q->tsig.key->name, NULL)));
404 	}
405 	return NSD_RC_OK;
406 }
407 
408 /*
409  * Check notify acl and forward to xfrd (or return an error).
410  */
411 static query_state_type
412 answer_notify(struct nsd* nsd, struct query *query)
413 {
414 	int acl_num, acl_num_xfr;
415 	struct acl_options *why;
416 	nsd_rc_type rc;
417 
418 	struct zone_options* zone_opt;
419 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "got notify %s processing acl",
420 		dname_to_string(query->qname, NULL)));
421 
422 	zone_opt = zone_options_find(nsd->options, query->qname);
423 	if(!zone_opt)
424 		return query_error(query, NSD_RC_NXDOMAIN);
425 
426 	if(!nsd->this_child) /* we are in debug mode or something */
427 		return query_error(query, NSD_RC_SERVFAIL);
428 
429 	if(!tsig_find_rr(&query->tsig, query->packet)) {
430 		DEBUG(DEBUG_XFRD,2, (LOG_ERR, "bad tsig RR format"));
431 		return query_error(query, NSD_RC_FORMAT);
432 	}
433 	rc = process_tsig(query);
434 	if(rc != NSD_RC_OK)
435 		return query_error(query, rc);
436 
437 	/* check if it passes acl */
438 	if((acl_num = acl_check_incoming(zone_opt->pattern->allow_notify, query,
439 		&why)) != -1)
440 	{
441 		sig_atomic_t mode = NSD_PASS_TO_XFRD;
442 		int s = nsd->this_child->parent_fd;
443 		uint16_t sz;
444 		uint32_t acl_send = htonl(acl_num);
445 		uint32_t acl_xfr;
446 		size_t pos;
447 
448 		/* Find priority candidate for request XFR. -1 if no match */
449 		acl_num_xfr = acl_check_incoming(
450 			zone_opt->pattern->request_xfr, query, NULL);
451 
452 		acl_xfr = htonl(acl_num_xfr);
453 
454 		assert(why);
455 		DEBUG(DEBUG_XFRD,1, (LOG_INFO, "got notify %s passed acl %s %s",
456 			dname_to_string(query->qname, NULL),
457 			why->ip_address_spec,
458 			why->nokey?"NOKEY":
459 			(why->blocked?"BLOCKED":why->key_name)));
460 		sz = buffer_limit(query->packet);
461 		if(buffer_limit(query->packet) > MAX_PACKET_SIZE)
462 			return query_error(query, NSD_RC_SERVFAIL);
463 		/* forward to xfrd for processing
464 		   Note. Blocking IPC I/O, but acl is OK. */
465 		sz = htons(sz);
466 		if(!write_socket(s, &mode, sizeof(mode)) ||
467 			!write_socket(s, &sz, sizeof(sz)) ||
468 			!write_socket(s, buffer_begin(query->packet),
469 				buffer_limit(query->packet)) ||
470 			!write_socket(s, &acl_send, sizeof(acl_send)) ||
471 			!write_socket(s, &acl_xfr, sizeof(acl_xfr))) {
472 			log_msg(LOG_ERR, "error in IPC notify server2main, %s",
473 				strerror(errno));
474 			return query_error(query, NSD_RC_SERVFAIL);
475 		}
476 		if(verbosity >= 1) {
477 			uint32_t serial = 0;
478 			char address[128];
479 			addr2str(&query->addr, address, sizeof(address));
480 			if(packet_find_notify_serial(query->packet, &serial))
481 			  VERBOSITY(1, (LOG_INFO, "notify for %s from %s serial %u",
482 				dname_to_string(query->qname, NULL), address,
483 				(unsigned)serial));
484 			else
485 			  VERBOSITY(1, (LOG_INFO, "notify for %s from %s",
486 				dname_to_string(query->qname, NULL), address));
487 		}
488 
489 		/* create notify reply - keep same query contents */
490 		QR_SET(query->packet);         /* This is an answer.  */
491 		AA_SET(query->packet);	   /* we are authoritative. */
492 		ANCOUNT_SET(query->packet, 0);
493 		NSCOUNT_SET(query->packet, 0);
494 		ARCOUNT_SET(query->packet, 0);
495 		RCODE_SET(query->packet, RCODE_OK); /* Error code.  */
496 		/* position is right after the query */
497 		pos = buffer_position(query->packet);
498 		buffer_clear(query->packet);
499 		buffer_set_position(query->packet, pos);
500 		/* tsig is added in add_additional later (if needed) */
501 		return QUERY_PROCESSED;
502 	}
503 
504 	if (verbosity >= 2) {
505 		char address[128];
506 		addr2str(&query->addr, address, sizeof(address));
507 		VERBOSITY(2, (LOG_INFO, "notify for %s from %s refused, %s%s",
508 			dname_to_string(query->qname, NULL),
509 			address,
510 			why?why->key_name:"no acl matches",
511 			why?why->ip_address_spec:"."));
512 	}
513 
514 	return query_error(query, NSD_RC_REFUSE);
515 }
516 
517 
518 /*
519  * Answer a query in the CHAOS class.
520  */
521 static query_state_type
522 answer_chaos(struct nsd *nsd, query_type *q)
523 {
524 	AA_CLR(q->packet);
525 	switch (q->qtype) {
526 	case TYPE_ANY:
527 	case TYPE_TXT:
528 		if ((q->qname->name_size == 11
529 		     && memcmp(dname_name(q->qname), "\002id\006server", 11) == 0) ||
530 		    (q->qname->name_size ==  15
531 		     && memcmp(dname_name(q->qname), "\010hostname\004bind", 15) == 0))
532 		{
533 			if(!nsd->options->hide_identity) {
534 				/* Add ID */
535 				query_addtxt(q,
536 				     buffer_begin(q->packet) + QHEADERSZ,
537 				     CLASS_CH,
538 				     0,
539 				     nsd->identity);
540 				ANCOUNT_SET(q->packet, ANCOUNT(q->packet) + 1);
541 			} else {
542 				RCODE_SET(q->packet, RCODE_REFUSE);
543 			}
544 		} else if ((q->qname->name_size == 16
545 			    && memcmp(dname_name(q->qname), "\007version\006server", 16) == 0) ||
546 			   (q->qname->name_size == 14
547 			    && memcmp(dname_name(q->qname), "\007version\004bind", 14) == 0))
548 		{
549 			if(!nsd->options->hide_version) {
550 				/* Add version */
551 				query_addtxt(q,
552 				     buffer_begin(q->packet) + QHEADERSZ,
553 				     CLASS_CH,
554 				     0,
555 				     nsd->version);
556 				ANCOUNT_SET(q->packet, ANCOUNT(q->packet) + 1);
557 			} else {
558 				RCODE_SET(q->packet, RCODE_REFUSE);
559 			}
560 		} else {
561 			RCODE_SET(q->packet, RCODE_REFUSE);
562 		}
563 		break;
564 	default:
565 		RCODE_SET(q->packet, RCODE_REFUSE);
566 		break;
567 	}
568 
569 	return QUERY_PROCESSED;
570 }
571 
572 
573 /*
574  * Find the covering NSEC for a non-existent domain name.  Normally
575  * the NSEC will be located at CLOSEST_MATCH, except when it is an
576  * empty non-terminal.  In this case the NSEC may be located at the
577  * previous domain name (in canonical ordering).
578  */
579 static domain_type *
580 find_covering_nsec(domain_type *closest_match,
581 		   zone_type   *zone,
582 		   rrset_type **nsec_rrset)
583 {
584 	assert(closest_match);
585 	assert(nsec_rrset);
586 
587 	/* loop away temporary created domains. For real ones it is &RBTREE_NULL */
588 #ifdef USE_RADIX_TREE
589 	while (closest_match->rnode == NULL)
590 #else
591 	while (closest_match->node.parent == NULL)
592 #endif
593 		closest_match = closest_match->parent;
594 	while (closest_match) {
595 		*nsec_rrset = domain_find_rrset(closest_match, zone, TYPE_NSEC);
596 		if (*nsec_rrset) {
597 			return closest_match;
598 		}
599 		if (closest_match == zone->apex) {
600 			/* Don't look outside the current zone.  */
601 			return NULL;
602 		}
603 		closest_match = domain_previous(closest_match);
604 	}
605 	return NULL;
606 }
607 
608 
609 struct additional_rr_types
610 {
611 	uint16_t        rr_type;
612 	rr_section_type rr_section;
613 };
614 
615 struct additional_rr_types default_additional_rr_types[] = {
616 	{ TYPE_A, ADDITIONAL_A_SECTION },
617 	{ TYPE_AAAA, ADDITIONAL_AAAA_SECTION },
618 	{ 0, (rr_section_type) 0 }
619 };
620 
621 struct additional_rr_types swap_aaaa_additional_rr_types[] = {
622 	{ TYPE_AAAA, ADDITIONAL_A_SECTION },
623 	{ TYPE_A, ADDITIONAL_AAAA_SECTION },
624 	{ 0, (rr_section_type) 0 }
625 };
626 
627 struct additional_rr_types rt_additional_rr_types[] = {
628 	{ TYPE_A, ADDITIONAL_A_SECTION },
629 	{ TYPE_AAAA, ADDITIONAL_AAAA_SECTION },
630 	{ TYPE_X25, ADDITIONAL_OTHER_SECTION },
631 	{ TYPE_ISDN, ADDITIONAL_OTHER_SECTION },
632 	{ 0, (rr_section_type) 0 }
633 };
634 
635 static void
636 add_additional_rrsets(struct query *query, answer_type *answer,
637 		      rrset_type *master_rrset, size_t rdata_index,
638 		      int allow_glue, struct additional_rr_types types[])
639 {
640 	size_t i;
641 
642 	assert(query);
643 	assert(answer);
644 	assert(master_rrset);
645 	assert(rdata_atom_is_domain(rrset_rrtype(master_rrset), rdata_index));
646 
647 	for (i = 0; i < master_rrset->rr_count; ++i) {
648 		int j;
649 		domain_type *additional = rdata_atom_domain(master_rrset->rrs[i].rdatas[rdata_index]);
650 		domain_type *match = additional;
651 
652 		assert(additional);
653 
654 		if (!allow_glue && domain_is_glue(match, query->zone))
655 			continue;
656 
657 		/*
658 		 * Check to see if we need to generate the dependent
659 		 * based on a wildcard domain.
660 		 */
661 		while (!match->is_existing) {
662 			match = match->parent;
663 		}
664 		if (additional != match && domain_wildcard_child(match)) {
665 			domain_type *wildcard_child = domain_wildcard_child(match);
666 			domain_type *temp = (domain_type *) region_alloc(
667 				query->region, sizeof(domain_type));
668 #ifdef USE_RADIX_TREE
669 			temp->rnode = NULL;
670 			temp->dname = additional->dname;
671 #else
672 			memcpy(&temp->node, &additional->node, sizeof(rbnode_type));
673 			temp->node.parent = NULL;
674 #endif
675 			temp->number = additional->number;
676 			temp->parent = match;
677 			temp->wildcard_child_closest_match = temp;
678 			temp->rrsets = wildcard_child->rrsets;
679 			temp->is_existing = wildcard_child->is_existing;
680 			additional = temp;
681 		}
682 
683 		for (j = 0; types[j].rr_type != 0; ++j) {
684 			rrset_type *rrset = domain_find_rrset(
685 				additional, query->zone, types[j].rr_type);
686 			if (rrset) {
687 				answer_add_rrset(answer, types[j].rr_section,
688 						 additional, rrset);
689 			}
690 		}
691 	}
692 }
693 
694 static int
695 answer_needs_ns(struct query* query)
696 {
697 	assert(query);
698 	/* Currently, only troublesome for DNSKEY and DS,
699          * cuz their RRSETs are quite large. */
700 	return (query->qtype != TYPE_DNSKEY && query->qtype != TYPE_DS
701 		&& query->qtype != TYPE_ANY);
702 }
703 
704 static int
705 add_rrset(struct query   *query,
706 	  answer_type    *answer,
707 	  rr_section_type section,
708 	  domain_type    *owner,
709 	  rrset_type     *rrset)
710 {
711 	int result;
712 
713 	assert(query);
714 	assert(answer);
715 	assert(owner);
716 	assert(rrset);
717 	assert(rrset_rrclass(rrset) == CLASS_IN);
718 
719 	result = answer_add_rrset(answer, section, owner, rrset);
720 	if(minimal_responses && section != AUTHORITY_SECTION &&
721 		query->qtype != TYPE_NS)
722 		return result;
723 	switch (rrset_rrtype(rrset)) {
724 	case TYPE_NS:
725 #if defined(INET6)
726 		/* if query over IPv6, swap A and AAAA; put AAAA first */
727 		add_additional_rrsets(query, answer, rrset, 0, 1,
728 			(query->addr.ss_family == AF_INET6)?
729 			swap_aaaa_additional_rr_types:
730 			default_additional_rr_types);
731 #else
732 		add_additional_rrsets(query, answer, rrset, 0, 1,
733 				      default_additional_rr_types);
734 #endif
735 		break;
736 	case TYPE_MB:
737 		add_additional_rrsets(query, answer, rrset, 0, 0,
738 				      default_additional_rr_types);
739 		break;
740 	case TYPE_MX:
741 	case TYPE_KX:
742 		add_additional_rrsets(query, answer, rrset, 1, 0,
743 				      default_additional_rr_types);
744 		break;
745 	case TYPE_RT:
746 		add_additional_rrsets(query, answer, rrset, 1, 0,
747 				      rt_additional_rr_types);
748 		break;
749 	case TYPE_SRV:
750 		add_additional_rrsets(query, answer, rrset, 3, 0,
751 				      default_additional_rr_types);
752 		break;
753 	default:
754 		break;
755 	}
756 
757 	return result;
758 }
759 
760 
761 /* returns 0 on error, or the domain number for to_name.
762    from_name is changes to to_name by the DNAME rr.
763    DNAME rr is from src to dest.
764    closest encloser encloses the to_name. */
765 static size_t
766 query_synthesize_cname(struct query* q, struct answer* answer, const dname_type* from_name,
767 	const dname_type* to_name, domain_type* src, domain_type* to_closest_encloser,
768 	domain_type** to_closest_match, uint32_t ttl)
769 {
770 	/* add temporary domains for from_name and to_name and all
771 	   their (not allocated yet) parents */
772 	/* any domains below src are not_existing (because of DNAME at src) */
773 	int i;
774 	domain_type* cname_domain;
775 	domain_type* cname_dest;
776 	rrset_type* rrset;
777 
778 	/* allocate source part */
779 	domain_type* lastparent = src;
780 	assert(q && answer && from_name && to_name && src && to_closest_encloser);
781 	assert(to_closest_match);
782 	for(i=0; i < from_name->label_count - domain_dname(src)->label_count; i++)
783 	{
784 		domain_type* newdom = query_get_tempdomain(q);
785 		if(!newdom)
786 			return 0;
787 		newdom->is_existing = 1;
788 		newdom->parent = lastparent;
789 #ifdef USE_RADIX_TREE
790 		newdom->dname
791 #else
792 		newdom->node.key
793 #endif
794 			= dname_partial_copy(q->region,
795 			from_name, domain_dname(src)->label_count + i + 1);
796 		if(dname_compare(domain_dname(newdom), q->qname) == 0) {
797 			/* 0 good for query name, otherwise new number */
798 			newdom->number = 0;
799 		}
800 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "created temp domain src %d. %s nr %d", i,
801 			domain_to_string(newdom), (int)newdom->number));
802 		lastparent = newdom;
803 	}
804 	cname_domain = lastparent;
805 
806 	/* allocate dest part */
807 	lastparent = to_closest_encloser;
808 	for(i=0; i < to_name->label_count - domain_dname(to_closest_encloser)->label_count;
809 		i++)
810 	{
811 		domain_type* newdom = query_get_tempdomain(q);
812 		if(!newdom)
813 			return 0;
814 		newdom->is_existing = 0;
815 		newdom->parent = lastparent;
816 #ifdef USE_RADIX_TREE
817 		newdom->dname
818 #else
819 		newdom->node.key
820 #endif
821 			= dname_partial_copy(q->region,
822 			to_name, domain_dname(to_closest_encloser)->label_count + i + 1);
823 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "created temp domain dest %d. %s nr %d", i,
824 			domain_to_string(newdom), (int)newdom->number));
825 		lastparent = newdom;
826 	}
827 	cname_dest = lastparent;
828 	*to_closest_match = cname_dest;
829 
830 	/* allocate the CNAME RR */
831 	rrset = (rrset_type*) region_alloc(q->region, sizeof(rrset_type));
832 	memset(rrset, 0, sizeof(rrset_type));
833 	rrset->zone = q->zone;
834 	rrset->rr_count = 1;
835 	rrset->rrs = (rr_type*) region_alloc(q->region, sizeof(rr_type));
836 	memset(rrset->rrs, 0, sizeof(rr_type));
837 	rrset->rrs->owner = cname_domain;
838 	rrset->rrs->ttl = ttl;
839 	rrset->rrs->type = TYPE_CNAME;
840 	rrset->rrs->klass = CLASS_IN;
841 	rrset->rrs->rdata_count = 1;
842 	rrset->rrs->rdatas = (rdata_atom_type*)region_alloc(q->region,
843 		sizeof(rdata_atom_type));
844 	rrset->rrs->rdatas->domain = cname_dest;
845 
846 	if(!add_rrset(q, answer, ANSWER_SECTION, cname_domain, rrset)) {
847 		log_msg(LOG_ERR, "could not add synthesized CNAME rrset to packet");
848 	}
849 
850 	return cname_dest->number;
851 }
852 
853 /*
854  * Answer delegation information.
855  *
856  * DNSSEC: Include the DS RRset if present.  Otherwise include an NSEC
857  * record proving the DS RRset does not exist.
858  */
859 static void
860 answer_delegation(query_type *query, answer_type *answer)
861 {
862 	assert(answer);
863 	assert(query->delegation_domain);
864 	assert(query->delegation_rrset);
865 
866 	if (query->cname_count == 0) {
867 		AA_CLR(query->packet);
868 	} else {
869 		AA_SET(query->packet);
870 	}
871 
872 	add_rrset(query,
873 		  answer,
874 		  AUTHORITY_SECTION,
875 		  query->delegation_domain,
876 		  query->delegation_rrset);
877 	if (query->edns.dnssec_ok && zone_is_secure(query->zone)) {
878 		rrset_type *rrset;
879 		if ((rrset = domain_find_rrset(query->delegation_domain, query->zone, TYPE_DS))) {
880 			add_rrset(query, answer, AUTHORITY_SECTION,
881 				  query->delegation_domain, rrset);
882 #ifdef NSEC3
883 		} else if (query->zone->nsec3_param) {
884 			nsec3_answer_delegation(query, answer);
885 #endif
886 		} else if ((rrset = domain_find_rrset(query->delegation_domain, query->zone, TYPE_NSEC))) {
887 			add_rrset(query, answer, AUTHORITY_SECTION,
888 				  query->delegation_domain, rrset);
889 		}
890 	}
891 }
892 
893 
894 /*
895  * Answer SOA information.
896  */
897 static void
898 answer_soa(struct query *query, answer_type *answer)
899 {
900 	if (query->qclass != CLASS_ANY) {
901 		add_rrset(query, answer,
902 			  AUTHORITY_SECTION,
903 			  query->zone->apex,
904 			  query->zone->soa_nx_rrset);
905 	}
906 }
907 
908 
909 /*
910  * Answer that the domain name exists but there is no RRset with the
911  * requested type.
912  *
913  * DNSSEC: Include the correct NSEC record proving that the type does
914  * not exist.  In the wildcard no data (3.1.3.4) case the wildcard IS
915  * NOT expanded, so the ORIGINAL parameter must point to the original
916  * wildcard entry, not to the generated entry.
917  */
918 static void
919 answer_nodata(struct query *query, answer_type *answer, domain_type *original)
920 {
921 	answer_soa(query, answer);
922 
923 #ifdef NSEC3
924 	if (query->edns.dnssec_ok && query->zone->nsec3_param) {
925 		nsec3_answer_nodata(query, answer, original);
926 	} else
927 #endif
928 	if (query->edns.dnssec_ok && zone_is_secure(query->zone)) {
929 		domain_type *nsec_domain;
930 		rrset_type *nsec_rrset;
931 
932 		nsec_domain = find_covering_nsec(original, query->zone, &nsec_rrset);
933 		if (nsec_domain) {
934 			add_rrset(query, answer, AUTHORITY_SECTION, nsec_domain, nsec_rrset);
935 		}
936 	}
937 }
938 
939 static void
940 answer_nxdomain(query_type *query, answer_type *answer)
941 {
942 	RCODE_SET(query->packet, RCODE_NXDOMAIN);
943 	answer_soa(query, answer);
944 }
945 
946 
947 /*
948  * Answer domain information (or SOA if we do not have an RRset for
949  * the type specified by the query).
950  */
951 static void
952 answer_domain(struct nsd* nsd, struct query *q, answer_type *answer,
953 	      domain_type *domain, domain_type *original)
954 {
955 	rrset_type *rrset;
956 
957 	if (q->qtype == TYPE_ANY) {
958 		rrset_type *preferred_rrset = NULL;
959 		rrset_type *normal_rrset = NULL;
960 		rrset_type *non_preferred_rrset = NULL;
961 
962 		/*
963 		 * Minimize response size for ANY, with one RRset
964 		 * according to RFC 8482(4.1).
965 		 * Prefers popular and not large rtypes (A,AAAA,...)
966 		 * lowering large ones (DNSKEY,RRSIG,...).
967 		 */
968 		for (rrset = domain_find_any_rrset(domain, q->zone); rrset; rrset = rrset->next) {
969 			if (rrset->zone == q->zone
970 #ifdef NSEC3
971 				&& rrset_rrtype(rrset) != TYPE_NSEC3
972 #endif
973 			    /*
974 			     * Don't include the RRSIG RRset when
975 			     * DNSSEC is used, because it is added
976 			     * automatically on an per-RRset basis.
977 			     */
978 			    && !(q->edns.dnssec_ok
979 				 && zone_is_secure(q->zone)
980 				 && rrset_rrtype(rrset) == TYPE_RRSIG))
981 			{
982 				switch(rrset_rrtype(rrset)) {
983 					case TYPE_A:
984 					case TYPE_AAAA:
985 					case TYPE_SOA:
986 					case TYPE_MX:
987 					case TYPE_PTR:
988 						preferred_rrset = rrset;
989 						break;
990 					case TYPE_DNSKEY:
991 					case TYPE_RRSIG:
992 					case TYPE_NSEC:
993 						non_preferred_rrset = rrset;
994 						break;
995 					default:
996 						normal_rrset = rrset;
997 				}
998 				if (preferred_rrset) break;
999 			}
1000 		}
1001 		if (preferred_rrset) {
1002 			add_rrset(q, answer, ANSWER_SECTION, domain, preferred_rrset);
1003 		} else if (normal_rrset) {
1004 			add_rrset(q, answer, ANSWER_SECTION, domain, normal_rrset);
1005 		} else if (non_preferred_rrset) {
1006 			add_rrset(q, answer, ANSWER_SECTION, domain, non_preferred_rrset);
1007 		} else {
1008 			answer_nodata(q, answer, original);
1009 			return;
1010 		}
1011 #ifdef NSEC3
1012 	} else if (q->qtype == TYPE_NSEC3) {
1013 		answer_nodata(q, answer, original);
1014 		return;
1015 #endif
1016 	} else if ((rrset = domain_find_rrset(domain, q->zone, q->qtype))) {
1017 		add_rrset(q, answer, ANSWER_SECTION, domain, rrset);
1018 	} else if ((rrset = domain_find_rrset(domain, q->zone, TYPE_CNAME))) {
1019 		int added;
1020 
1021 		/*
1022 		 * If the CNAME is not added it is already in the
1023 		 * answer, so we have a CNAME loop.  Don't follow the
1024 		 * CNAME target in this case.
1025 		 */
1026 		added = add_rrset(q, answer, ANSWER_SECTION, domain, rrset);
1027 		assert(rrset->rr_count > 0);
1028 		if (added) {
1029 			/* only process first CNAME record */
1030 			domain_type *closest_match = rdata_atom_domain(rrset->rrs[0].rdatas[0]);
1031 			domain_type *closest_encloser = closest_match;
1032 			zone_type* origzone = q->zone;
1033 			++q->cname_count;
1034 
1035 			answer_lookup_zone(nsd, q, answer, closest_match->number,
1036 					     closest_match == closest_encloser,
1037 					     closest_match, closest_encloser,
1038 					     domain_dname(closest_match));
1039 			q->zone = origzone;
1040 		}
1041 		return;
1042 	} else {
1043 		answer_nodata(q, answer, original);
1044 		return;
1045 	}
1046 
1047 	if (q->qclass != CLASS_ANY && q->zone->ns_rrset && answer_needs_ns(q)
1048 		&& !minimal_responses) {
1049 		add_rrset(q, answer, OPTIONAL_AUTHORITY_SECTION, q->zone->apex,
1050 			  q->zone->ns_rrset);
1051 	}
1052 }
1053 
1054 
1055 /*
1056  * Answer with authoritative data.  If a wildcard is matched the owner
1057  * name will be expanded to the domain name specified by
1058  * DOMAIN_NUMBER.  DOMAIN_NUMBER 0 (zero) is reserved for the original
1059  * query name.
1060  *
1061  * DNSSEC: Include the necessary NSEC records in case the request
1062  * domain name does not exist and/or a wildcard match does not exist.
1063  */
1064 static void
1065 answer_authoritative(struct nsd   *nsd,
1066 		     struct query *q,
1067 		     answer_type  *answer,
1068 		     size_t        domain_number,
1069 		     int           exact,
1070 		     domain_type  *closest_match,
1071 		     domain_type  *closest_encloser,
1072 		     const dname_type *qname)
1073 {
1074 	domain_type *match;
1075 	domain_type *original = closest_match;
1076 	domain_type *dname_ce;
1077 	rrset_type *rrset;
1078 
1079 #ifdef NSEC3
1080 	if(exact && domain_has_only_NSEC3(closest_match, q->zone)) {
1081 		exact = 0; /* pretend it does not exist */
1082 		if(closest_encloser->parent)
1083 			closest_encloser = closest_encloser->parent;
1084 	}
1085 #endif /* NSEC3 */
1086 	if((dname_ce = find_dname_above(closest_encloser, q->zone)) != NULL) {
1087 		/* occlude the found data, the DNAME is closest_encloser */
1088 		closest_encloser = dname_ce;
1089 		exact = 0;
1090 	}
1091 
1092 	if (exact) {
1093 		match = closest_match;
1094 	} else if ((rrset=domain_find_rrset(closest_encloser, q->zone, TYPE_DNAME))) {
1095 		/* process DNAME */
1096 		const dname_type* name = qname;
1097 		domain_type *dest = rdata_atom_domain(rrset->rrs[0].rdatas[0]);
1098 		int added;
1099 		assert(rrset->rr_count > 0);
1100 		if(domain_number != 0) /* we followed CNAMEs or DNAMEs */
1101 			name = domain_dname(closest_match);
1102 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "expanding DNAME for q=%s", dname_to_string(name, NULL)));
1103 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "->src is %s",
1104 			domain_to_string(closest_encloser)));
1105 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "->dest is %s",
1106 			domain_to_string(dest)));
1107 		/* if the DNAME set is not added we have a loop, do not follow */
1108 		added = add_rrset(q, answer, ANSWER_SECTION, closest_encloser, rrset);
1109 		if(added) {
1110 			domain_type* src = closest_encloser;
1111 			const dname_type* newname = dname_replace(q->region, name,
1112 				domain_dname(src), domain_dname(dest));
1113 			size_t newnum = 0;
1114 			zone_type* origzone = q->zone;
1115 			++q->cname_count;
1116 			if(!newname) { /* newname too long */
1117 				RCODE_SET(q->packet, RCODE_YXDOMAIN);
1118 				return;
1119 			}
1120 			DEBUG(DEBUG_QUERY,2, (LOG_INFO, "->result is %s", dname_to_string(newname, NULL)));
1121 			/* follow the DNAME */
1122 			(void)namedb_lookup(nsd->db, newname, &closest_match, &closest_encloser);
1123 			/* synthesize CNAME record */
1124 			newnum = query_synthesize_cname(q, answer, name, newname,
1125 				src, closest_encloser, &closest_match, rrset->rrs[0].ttl);
1126 			if(!newnum) {
1127 				/* could not synthesize the CNAME. */
1128 				/* return previous CNAMEs to make resolver recurse for us */
1129 				return;
1130 			}
1131 
1132 			answer_lookup_zone(nsd, q, answer, newnum,
1133 				closest_match == closest_encloser,
1134 				closest_match, closest_encloser, newname);
1135 			q->zone = origzone;
1136 		}
1137 		if(!added)  /* log the error so operator can find looping recursors */
1138 			log_msg(LOG_INFO, "DNAME processing stopped due to loop, qname %s",
1139 				dname_to_string(q->qname, NULL));
1140 		return;
1141 	} else if (domain_wildcard_child(closest_encloser)) {
1142 		/* Generate the domain from the wildcard.  */
1143 		domain_type *wildcard_child = domain_wildcard_child(closest_encloser);
1144 #ifdef RATELIMIT
1145 		q->wildcard_domain = wildcard_child;
1146 #endif
1147 
1148 		match = (domain_type *) region_alloc(q->region,
1149 						     sizeof(domain_type));
1150 #ifdef USE_RADIX_TREE
1151 		match->rnode = NULL;
1152 		match->dname = wildcard_child->dname;
1153 #else
1154 		memcpy(&match->node, &wildcard_child->node, sizeof(rbnode_type));
1155 		match->node.parent = NULL;
1156 #endif
1157 		match->parent = closest_encloser;
1158 		match->wildcard_child_closest_match = match;
1159 		match->number = domain_number;
1160 		match->rrsets = wildcard_child->rrsets;
1161 		match->is_existing = wildcard_child->is_existing;
1162 #ifdef NSEC3
1163 		match->nsec3 = wildcard_child->nsec3;
1164 		/* copy over these entries:
1165 		match->nsec3_is_exact = wildcard_child->nsec3_is_exact;
1166 		match->nsec3_cover = wildcard_child->nsec3_cover;
1167 		match->nsec3_wcard_child_cover = wildcard_child->nsec3_wcard_child_cover;
1168 		match->nsec3_ds_parent_is_exact = wildcard_child->nsec3_ds_parent_is_exact;
1169 		match->nsec3_ds_parent_cover = wildcard_child->nsec3_ds_parent_cover;
1170 		*/
1171 
1172 		if (q->edns.dnssec_ok && q->zone->nsec3_param) {
1173 			/* Only add nsec3 wildcard data when do bit is set */
1174 			nsec3_answer_wildcard(q, answer, wildcard_child, qname);
1175 		}
1176 #endif
1177 
1178 		/*
1179 		 * Remember the original domain in case a Wildcard No
1180 		 * Data (3.1.3.4) response needs to be generated.  In
1181 		 * this particular case the wildcard IS NOT
1182 		 * expanded.
1183 		 */
1184 		original = wildcard_child;
1185 	} else {
1186 		match = NULL;
1187 	}
1188 
1189 	/* Authoritative zone.  */
1190 #ifdef NSEC3
1191 	if (q->edns.dnssec_ok && q->zone->nsec3_param) {
1192 		nsec3_answer_authoritative(&match, q, answer,
1193 			closest_encloser, qname);
1194 	} else
1195 #endif
1196 	if (q->edns.dnssec_ok && zone_is_secure(q->zone)) {
1197 		if (match != closest_encloser) {
1198 			domain_type *nsec_domain;
1199 			rrset_type *nsec_rrset;
1200 
1201 			/*
1202 			 * No match found or generated from wildcard,
1203 			 * include NSEC record.
1204 			 */
1205 			nsec_domain = find_covering_nsec(closest_match, q->zone, &nsec_rrset);
1206 			if (nsec_domain) {
1207 				add_rrset(q, answer, AUTHORITY_SECTION, nsec_domain, nsec_rrset);
1208 			}
1209 		}
1210 		if (!match) {
1211 			domain_type *nsec_domain;
1212 			rrset_type *nsec_rrset;
1213 
1214 			/*
1215 			 * No match and no wildcard.  Include NSEC
1216 			 * proving there is no wildcard.
1217 			 */
1218 			if(closest_encloser && (nsec_domain =
1219 				find_covering_nsec(closest_encloser->
1220 					wildcard_child_closest_match, q->zone,
1221 					&nsec_rrset)) != NULL) {
1222 				add_rrset(q, answer, AUTHORITY_SECTION, nsec_domain, nsec_rrset);
1223 			}
1224 		}
1225 	}
1226 
1227 #ifdef NSEC3
1228 	if (RCODE(q->packet)!=RCODE_OK) {
1229 		return; /* nsec3 collision failure */
1230 	}
1231 #endif
1232 	if (match) {
1233 		answer_domain(nsd, q, answer, match, original);
1234 	} else {
1235 		answer_nxdomain(q, answer);
1236 	}
1237 }
1238 
1239 /*
1240  * qname may be different after CNAMEs have been followed from query->qname.
1241  */
1242 static void
1243 answer_lookup_zone(struct nsd *nsd, struct query *q, answer_type *answer,
1244 	size_t domain_number, int exact, domain_type *closest_match,
1245 	domain_type *closest_encloser, const dname_type *qname)
1246 {
1247 	zone_type* origzone = q->zone;
1248 	q->zone = domain_find_zone(nsd->db, closest_encloser);
1249 	if (!q->zone) {
1250 		/* no zone for this */
1251 		if(q->cname_count == 0)
1252 			RCODE_SET(q->packet, RCODE_REFUSE);
1253 		return;
1254 	}
1255 	assert(closest_encloser); /* otherwise, no q->zone would be found */
1256 	if(!q->zone->apex || !q->zone->soa_rrset) {
1257 		/* zone is configured but not loaded */
1258 		if(q->cname_count == 0)
1259 			RCODE_SET(q->packet, RCODE_SERVFAIL);
1260 		return;
1261 	}
1262 
1263 	/*
1264 	 * If confine-to-zone is set to yes do not return additional
1265 	 * information for a zone with a different apex from the query zone.
1266 	*/
1267 	if (nsd->options->confine_to_zone &&
1268 	   (origzone != NULL && dname_compare(domain_dname(origzone->apex), domain_dname(q->zone->apex)) != 0)) {
1269 		return;
1270 	}
1271 
1272 	/* now move up the closest encloser until it exists, previous
1273 	 * (possibly empty) closest encloser was useful to finding the zone
1274 	 * (for empty zones too), but now we want actual data nodes */
1275 	if (closest_encloser && !closest_encloser->is_existing) {
1276 		exact = 0;
1277 		while (closest_encloser != NULL && !closest_encloser->is_existing)
1278 			closest_encloser = closest_encloser->parent;
1279 	}
1280 
1281 	/*
1282 	 * See RFC 4035 (DNSSEC protocol) section 3.1.4.1 Responding
1283 	 * to Queries for DS RRs.
1284 	 */
1285 	if (exact && q->qtype == TYPE_DS && closest_encloser == q->zone->apex) {
1286 		/*
1287 		 * Type DS query at a zone cut, use the responsible
1288 		 * parent zone to generate the answer if we are
1289 		 * authoritative for the parent zone.
1290 		 */
1291 		zone_type *zone = domain_find_parent_zone(nsd->db, q->zone);
1292 		if (zone) {
1293 			q->zone = zone;
1294 			if(!q->zone->apex || !q->zone->soa_rrset) {
1295 				/* zone is configured but not loaded */
1296 				if(q->cname_count == 0)
1297 					RCODE_SET(q->packet, RCODE_SERVFAIL);
1298 				return;
1299 			}
1300 		}
1301 	}
1302 
1303 	/* see if the zone has expired (for secondary zones) */
1304 	if(q->zone && q->zone->opts && q->zone->opts->pattern &&
1305 		q->zone->opts->pattern->request_xfr != 0 && !q->zone->is_ok) {
1306 		if(q->cname_count == 0)
1307 			RCODE_SET(q->packet, RCODE_SERVFAIL);
1308 		return;
1309 	}
1310 
1311 	if (exact && q->qtype == TYPE_DS && closest_encloser == q->zone->apex) {
1312 		/*
1313 		 * Type DS query at the zone apex (and the server is
1314 		 * not authoritative for the parent zone).
1315 		 */
1316 		if (q->qclass == CLASS_ANY) {
1317 			AA_CLR(q->packet);
1318 		} else {
1319 			AA_SET(q->packet);
1320 		}
1321 		answer_nodata(q, answer, closest_encloser);
1322 	} else {
1323 		q->delegation_domain = domain_find_ns_rrsets(
1324 			closest_encloser, q->zone, &q->delegation_rrset);
1325 		if(q->delegation_domain && find_dname_above(q->delegation_domain, q->zone)) {
1326 			q->delegation_domain = NULL; /* use higher DNAME */
1327 		}
1328 
1329 		if (!q->delegation_domain
1330 		    || (exact && q->qtype == TYPE_DS && closest_encloser == q->delegation_domain))
1331 		{
1332 			if (q->qclass == CLASS_ANY) {
1333 				AA_CLR(q->packet);
1334 			} else {
1335 				AA_SET(q->packet);
1336 			}
1337 			answer_authoritative(nsd, q, answer, domain_number, exact,
1338 					     closest_match, closest_encloser, qname);
1339 		}
1340 		else {
1341 			answer_delegation(q, answer);
1342 		}
1343 	}
1344 }
1345 
1346 static void
1347 answer_query(struct nsd *nsd, struct query *q)
1348 {
1349 	domain_type *closest_match;
1350 	domain_type *closest_encloser;
1351 	int exact;
1352 	uint16_t offset;
1353 	answer_type answer;
1354 
1355 	answer_init(&answer);
1356 
1357 	exact = namedb_lookup(nsd->db, q->qname, &closest_match, &closest_encloser);
1358 
1359 	answer_lookup_zone(nsd, q, &answer, 0, exact, closest_match,
1360 		closest_encloser, q->qname);
1361 	ZTATUP2(nsd, q->zone, opcode, q->opcode);
1362 	ZTATUP2(nsd, q->zone, qtype, q->qtype);
1363 	ZTATUP2(nsd, q->zone, qclass, q->qclass);
1364 
1365 	offset = dname_label_offsets(q->qname)[domain_dname(closest_encloser)->label_count - 1] + QHEADERSZ;
1366 	query_add_compression_domain(q, closest_encloser, offset);
1367 	encode_answer(q, &answer);
1368 	query_clear_compression_tables(q);
1369 }
1370 
1371 void
1372 query_prepare_response(query_type *q)
1373 {
1374 	uint16_t flags;
1375 
1376 	/*
1377 	 * Preserve the data up-to the current packet's limit.
1378 	 */
1379 	buffer_set_position(q->packet, buffer_limit(q->packet));
1380 	buffer_set_limit(q->packet, buffer_capacity(q->packet));
1381 
1382 	/*
1383 	 * Reserve space for the EDNS records if required.
1384 	 */
1385 	q->reserved_space = edns_reserved_space(&q->edns);
1386 	q->reserved_space += tsig_reserved_space(&q->tsig);
1387 
1388 	/* Update the flags.  */
1389 	flags = FLAGS(q->packet);
1390 	flags &= 0x0100U;	/* Preserve the RD flag.  */
1391 				/* CD flag must be cleared for auth answers */
1392 	flags |= 0x8000U;	/* Set the QR flag.  */
1393 	FLAGS_SET(q->packet, flags);
1394 }
1395 
1396 /*
1397  * Processes the query.
1398  *
1399  */
1400 query_state_type
1401 query_process(query_type *q, nsd_type *nsd)
1402 {
1403 	/* The query... */
1404 	nsd_rc_type rc;
1405 	query_state_type query_state;
1406 	uint16_t arcount;
1407 
1408 	/* Sanity checks */
1409 	if (buffer_limit(q->packet) < QHEADERSZ) {
1410 		/* packet too small to contain DNS header.
1411 		Now packet investigation macros will work without problems. */
1412 		return QUERY_DISCARDED;
1413 	}
1414 	if (QR(q->packet)) {
1415 		/* Not a query? Drop it on the floor. */
1416 		return QUERY_DISCARDED;
1417 	}
1418 
1419 	/* check opcode early on, because new opcodes may have different
1420 	 * specification of the meaning of the rest of the packet */
1421 	q->opcode = OPCODE(q->packet);
1422 	if(q->opcode != OPCODE_QUERY && q->opcode != OPCODE_NOTIFY) {
1423 		if(query_ratelimit_err(nsd))
1424 			return QUERY_DISCARDED;
1425 		if(nsd->options->drop_updates && q->opcode == OPCODE_UPDATE)
1426 			return QUERY_DISCARDED;
1427 		return query_error(q, NSD_RC_IMPL);
1428 	}
1429 
1430 	if (RCODE(q->packet) != RCODE_OK || !process_query_section(q)) {
1431 		return query_formerr(q, nsd);
1432 	}
1433 
1434 	/* Update statistics.  */
1435 	STATUP2(nsd, opcode, q->opcode);
1436 	STATUP2(nsd, qtype, q->qtype);
1437 	STATUP2(nsd, qclass, q->qclass);
1438 
1439 	if (q->opcode != OPCODE_QUERY) {
1440 		if (q->opcode == OPCODE_NOTIFY) {
1441 			return answer_notify(nsd, q);
1442 		} else {
1443 			if(query_ratelimit_err(nsd))
1444 				return QUERY_DISCARDED;
1445 			return query_error(q, NSD_RC_IMPL);
1446 		}
1447 	}
1448 
1449 	/* Dont bother to answer more than one question at once... */
1450 	if (QDCOUNT(q->packet) != 1) {
1451 		if(QDCOUNT(q->packet) == 0 && ANCOUNT(q->packet) == 0 &&
1452 			NSCOUNT(q->packet) == 0 && ARCOUNT(q->packet) == 1 &&
1453 			buffer_limit(q->packet) >= QHEADERSZ+OPT_LEN+
1454 			OPT_RDATA) {
1455 			/* add edns section to answer */
1456 			buffer_set_position(q->packet, QHEADERSZ);
1457 			if (edns_parse_record(&q->edns, q->packet, q, nsd)) {
1458 				if(process_edns(nsd, q) == NSD_RC_OK) {
1459 					int opcode = OPCODE(q->packet);
1460 					(void)query_error(q, NSD_RC_FORMAT);
1461 					query_add_optional(q, nsd);
1462 					FLAGS_SET(q->packet, FLAGS(q->packet) & 0x0100U);
1463 						/* Preserve the RD flag. Clear the rest. */
1464 					OPCODE_SET(q->packet, opcode);
1465 					QR_SET(q->packet);
1466 					return QUERY_PROCESSED;
1467 				}
1468 			}
1469 		}
1470 		FLAGS_SET(q->packet, 0);
1471 		return query_formerr(q, nsd);
1472 	}
1473 	/* Ignore settings of flags */
1474 
1475 	/* Dont allow any records in the answer or authority section...
1476 	   except for IXFR queries. */
1477 	if (ANCOUNT(q->packet) != 0 ||
1478 		(q->qtype!=TYPE_IXFR && NSCOUNT(q->packet) != 0)) {
1479 		return query_formerr(q, nsd);
1480 	}
1481 	if(q->qtype==TYPE_IXFR && NSCOUNT(q->packet) > 0) {
1482 		unsigned int i; /* skip ixfr soa information data here */
1483 		unsigned int nscount = (unsigned)NSCOUNT(q->packet);
1484 		/* define a bound on the number of extraneous records allowed,
1485 		 * we expect 1, a SOA serial record, and no more.
1486 		 * perhaps RRSIGs (but not needed), otherwise we do not
1487 		 * understand what this means.  We do not want too many
1488 		 * because the high iteration counts slow down. */
1489 		if(nscount > 64) return query_formerr(q, nsd);
1490 		for(i=0; i< nscount; i++)
1491 			if(!packet_skip_rr(q->packet, 0))
1492 				return query_formerr(q, nsd);
1493 	}
1494 
1495 	arcount = ARCOUNT(q->packet);
1496 	if (arcount > 0) {
1497 		/* According to draft-ietf-dnsext-rfc2671bis-edns0-10:
1498 		 * "The placement flexibility for the OPT RR does not
1499 		 * override the need for the TSIG or SIG(0) RRs to be
1500 		 * the last in the additional section whenever they are
1501 		 * present."
1502 		 * So we should not have to check for TSIG RR before
1503 		 * OPT RR. Keep the code for backwards compatibility.
1504 		 */
1505 
1506 		/* see if tsig is before edns record */
1507 		if (!tsig_parse_rr(&q->tsig, q->packet))
1508 			return query_formerr(q, nsd);
1509 		if(q->tsig.status != TSIG_NOT_PRESENT)
1510 			--arcount;
1511 	}
1512 	/* See if there is an OPT RR. */
1513 	if (arcount > 0) {
1514 		if (edns_parse_record(&q->edns, q->packet, q, nsd))
1515 			--arcount;
1516 	}
1517 	/* See if there is a TSIG RR. */
1518 	if (arcount > 0 && q->tsig.status == TSIG_NOT_PRESENT) {
1519 		/* see if tsig is after the edns record */
1520 		if (!tsig_parse_rr(&q->tsig, q->packet))
1521 			return query_formerr(q, nsd);
1522 		if(q->tsig.status != TSIG_NOT_PRESENT)
1523 			--arcount;
1524 	}
1525 	/* If more RRs left in Add. Section, FORMERR. */
1526 	if (arcount > 0) {
1527 		return query_formerr(q, nsd);
1528 	}
1529 
1530 	/* Do we have any trailing garbage? */
1531 #ifdef	STRICT_MESSAGE_PARSE
1532 	if (buffer_remaining(q->packet) > 0) {
1533 		/* If we're strict.... */
1534 		return query_formerr(q, nsd);
1535 	}
1536 #endif
1537 	/* Remove trailing garbage.  */
1538 	buffer_set_limit(q->packet, buffer_position(q->packet));
1539 
1540 	rc = process_tsig(q);
1541 	if (rc != NSD_RC_OK) {
1542 		return query_error(q, rc);
1543 	}
1544 	rc = process_edns(nsd, q);
1545 	if (rc != NSD_RC_OK) {
1546 		/* We should not return FORMERR, but BADVERS (=16).
1547 		 * BADVERS is created with Ext. RCODE, followed by RCODE.
1548 		 * Ext. RCODE is set to 1, RCODE must be 0 (getting 0x10 = 16).
1549 		 * Thus RCODE = NOERROR = NSD_RC_OK. */
1550 		RCODE_SET(q->packet, NSD_RC_OK);
1551 		buffer_clear(q->packet);
1552 		buffer_set_position(q->packet,
1553 			QHEADERSZ + 4 + q->qname->name_size);
1554 		QR_SET(q->packet);
1555 		AD_CLR(q->packet);
1556 		QDCOUNT_SET(q->packet, 1);
1557 		ANCOUNT_SET(q->packet, 0);
1558 		NSCOUNT_SET(q->packet, 0);
1559 		ARCOUNT_SET(q->packet, 0);
1560 		return QUERY_PROCESSED;
1561 	}
1562 
1563 	query_prepare_response(q);
1564 
1565 	if (q->qclass != CLASS_IN && q->qclass != CLASS_ANY) {
1566 		if (q->qclass == CLASS_CH) {
1567 			return answer_chaos(nsd, q);
1568 		} else {
1569 			return query_error(q, NSD_RC_REFUSE);
1570 		}
1571 	}
1572 
1573 	query_state = answer_axfr_ixfr(nsd, q);
1574 	if (query_state == QUERY_PROCESSED || query_state == QUERY_IN_AXFR) {
1575 		return query_state;
1576 	}
1577 	if(q->qtype == TYPE_ANY && nsd->options->refuse_any && !q->tcp) {
1578 		TC_SET(q->packet);
1579 		return query_error(q, NSD_RC_OK);
1580 	}
1581 
1582 	answer_query(nsd, q);
1583 
1584 	return QUERY_PROCESSED;
1585 }
1586 
1587 void
1588 query_add_optional(query_type *q, nsd_type *nsd)
1589 {
1590 	struct edns_data *edns = &nsd->edns_ipv4;
1591 #if defined(INET6)
1592 	if (q->addr.ss_family == AF_INET6) {
1593 		edns = &nsd->edns_ipv6;
1594 	}
1595 #endif
1596 	if (RCODE(q->packet) == RCODE_FORMAT) {
1597 		return;
1598 	}
1599 	switch (q->edns.status) {
1600 	case EDNS_NOT_PRESENT:
1601 		break;
1602 	case EDNS_OK:
1603 		if (q->edns.dnssec_ok)	edns->ok[7] = 0x80;
1604 		else			edns->ok[7] = 0x00;
1605 		buffer_write(q->packet, edns->ok, OPT_LEN);
1606 		if(q->edns.opt_reserved_space == 0 || !buffer_available(
1607 			q->packet, 2+q->edns.opt_reserved_space)) {
1608 			/* fill with NULLs */
1609 			buffer_write(q->packet, edns->rdata_none, OPT_RDATA);
1610 		} else {
1611 			/* rdata length */
1612 			buffer_write_u16(q->packet, q->edns.opt_reserved_space);
1613 			/* edns options */
1614 			if(q->edns.nsid) {
1615 				/* nsid opt header */
1616 				buffer_write(q->packet, edns->nsid, OPT_HDR);
1617 				/* nsid payload */
1618 				buffer_write(q->packet, nsd->nsid, nsd->nsid_len);
1619 			}
1620 		}
1621 		ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1622 		STATUP(nsd, edns);
1623 		ZTATUP(nsd, q->zone, edns);
1624 		break;
1625 	case EDNS_ERROR:
1626 		if (q->edns.dnssec_ok)	edns->error[7] = 0x80;
1627 		else			edns->error[7] = 0x00;
1628 		buffer_write(q->packet, edns->error, OPT_LEN);
1629 		buffer_write(q->packet, edns->rdata_none, OPT_RDATA);
1630 		ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1631 		STATUP(nsd, ednserr);
1632 		ZTATUP(nsd, q->zone, ednserr);
1633 		break;
1634 	}
1635 
1636 	if (q->tsig.status != TSIG_NOT_PRESENT) {
1637 		if (q->tsig.status == TSIG_ERROR ||
1638 			q->tsig.error_code != TSIG_ERROR_NOERROR) {
1639 			tsig_error_reply(&q->tsig);
1640 			tsig_append_rr(&q->tsig, q->packet);
1641 			ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1642 		} else if(q->tsig.status == TSIG_OK &&
1643 			q->tsig.error_code == TSIG_ERROR_NOERROR)
1644 		{
1645 			if(q->tsig_prepare_it)
1646 				tsig_prepare(&q->tsig);
1647 			if(q->tsig_update_it)
1648 				tsig_update(&q->tsig, q->packet, buffer_position(q->packet));
1649 			if(q->tsig_sign_it) {
1650 				tsig_sign(&q->tsig);
1651 				tsig_append_rr(&q->tsig, q->packet);
1652 				ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1653 			}
1654 		}
1655 	}
1656 }
1657