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