xref: /openbsd-src/usr.sbin/nsd/query.c (revision d1df930ffab53da22f3324c32bed7ac5709915e6)
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 			/* Add ID */
534 			query_addtxt(q,
535 				     buffer_begin(q->packet) + QHEADERSZ,
536 				     CLASS_CH,
537 				     0,
538 				     nsd->identity);
539 			ANCOUNT_SET(q->packet, ANCOUNT(q->packet) + 1);
540 		} else if ((q->qname->name_size == 16
541 			    && memcmp(dname_name(q->qname), "\007version\006server", 16) == 0) ||
542 			   (q->qname->name_size == 14
543 			    && memcmp(dname_name(q->qname), "\007version\004bind", 14) == 0))
544 		{
545 			if(!nsd->options->hide_version) {
546 				/* Add version */
547 				query_addtxt(q,
548 				     buffer_begin(q->packet) + QHEADERSZ,
549 				     CLASS_CH,
550 				     0,
551 				     nsd->version);
552 				ANCOUNT_SET(q->packet, ANCOUNT(q->packet) + 1);
553 			} else {
554 				RCODE_SET(q->packet, RCODE_REFUSE);
555 			}
556 		} else {
557 			RCODE_SET(q->packet, RCODE_REFUSE);
558 		}
559 		break;
560 	default:
561 		RCODE_SET(q->packet, RCODE_REFUSE);
562 		break;
563 	}
564 
565 	return QUERY_PROCESSED;
566 }
567 
568 
569 /*
570  * Find the covering NSEC for a non-existent domain name.  Normally
571  * the NSEC will be located at CLOSEST_MATCH, except when it is an
572  * empty non-terminal.  In this case the NSEC may be located at the
573  * previous domain name (in canonical ordering).
574  */
575 static domain_type *
576 find_covering_nsec(domain_type *closest_match,
577 		   zone_type   *zone,
578 		   rrset_type **nsec_rrset)
579 {
580 	assert(closest_match);
581 	assert(nsec_rrset);
582 
583 	/* loop away temporary created domains. For real ones it is &RBTREE_NULL */
584 #ifdef USE_RADIX_TREE
585 	while (closest_match->rnode == NULL)
586 #else
587 	while (closest_match->node.parent == NULL)
588 #endif
589 		closest_match = closest_match->parent;
590 	while (closest_match) {
591 		*nsec_rrset = domain_find_rrset(closest_match, zone, TYPE_NSEC);
592 		if (*nsec_rrset) {
593 			return closest_match;
594 		}
595 		if (closest_match == zone->apex) {
596 			/* Don't look outside the current zone.  */
597 			return NULL;
598 		}
599 		closest_match = domain_previous(closest_match);
600 	}
601 	return NULL;
602 }
603 
604 
605 struct additional_rr_types
606 {
607 	uint16_t        rr_type;
608 	rr_section_type rr_section;
609 };
610 
611 struct additional_rr_types default_additional_rr_types[] = {
612 	{ TYPE_A, ADDITIONAL_A_SECTION },
613 	{ TYPE_AAAA, ADDITIONAL_AAAA_SECTION },
614 	{ 0, (rr_section_type) 0 }
615 };
616 
617 struct additional_rr_types swap_aaaa_additional_rr_types[] = {
618 	{ TYPE_AAAA, ADDITIONAL_A_SECTION },
619 	{ TYPE_A, ADDITIONAL_AAAA_SECTION },
620 	{ 0, (rr_section_type) 0 }
621 };
622 
623 struct additional_rr_types rt_additional_rr_types[] = {
624 	{ TYPE_A, ADDITIONAL_A_SECTION },
625 	{ TYPE_AAAA, ADDITIONAL_AAAA_SECTION },
626 	{ TYPE_X25, ADDITIONAL_OTHER_SECTION },
627 	{ TYPE_ISDN, ADDITIONAL_OTHER_SECTION },
628 	{ 0, (rr_section_type) 0 }
629 };
630 
631 static void
632 add_additional_rrsets(struct query *query, answer_type *answer,
633 		      rrset_type *master_rrset, size_t rdata_index,
634 		      int allow_glue, struct additional_rr_types types[])
635 {
636 	size_t i;
637 
638 	assert(query);
639 	assert(answer);
640 	assert(master_rrset);
641 	assert(rdata_atom_is_domain(rrset_rrtype(master_rrset), rdata_index));
642 
643 	for (i = 0; i < master_rrset->rr_count; ++i) {
644 		int j;
645 		domain_type *additional = rdata_atom_domain(master_rrset->rrs[i].rdatas[rdata_index]);
646 		domain_type *match = additional;
647 
648 		assert(additional);
649 
650 		if (!allow_glue && domain_is_glue(match, query->zone))
651 			continue;
652 
653 		/*
654 		 * Check to see if we need to generate the dependent
655 		 * based on a wildcard domain.
656 		 */
657 		while (!match->is_existing) {
658 			match = match->parent;
659 		}
660 		if (additional != match && domain_wildcard_child(match)) {
661 			domain_type *wildcard_child = domain_wildcard_child(match);
662 			domain_type *temp = (domain_type *) region_alloc(
663 				query->region, sizeof(domain_type));
664 #ifdef USE_RADIX_TREE
665 			temp->rnode = NULL;
666 			temp->dname = additional->dname;
667 #else
668 			memcpy(&temp->node, &additional->node, sizeof(rbnode_type));
669 			temp->node.parent = NULL;
670 #endif
671 			temp->number = additional->number;
672 			temp->parent = match;
673 			temp->wildcard_child_closest_match = temp;
674 			temp->rrsets = wildcard_child->rrsets;
675 			temp->is_existing = wildcard_child->is_existing;
676 			additional = temp;
677 		}
678 
679 		for (j = 0; types[j].rr_type != 0; ++j) {
680 			rrset_type *rrset = domain_find_rrset(
681 				additional, query->zone, types[j].rr_type);
682 			if (rrset) {
683 				answer_add_rrset(answer, types[j].rr_section,
684 						 additional, rrset);
685 			}
686 		}
687 	}
688 }
689 
690 static int
691 answer_needs_ns(struct query* query)
692 {
693 	assert(query);
694 	/* Currently, only troublesome for DNSKEY and DS,
695          * cuz their RRSETs are quite large. */
696 	return (query->qtype != TYPE_DNSKEY && query->qtype != TYPE_DS);
697 }
698 
699 static int
700 add_rrset(struct query   *query,
701 	  answer_type    *answer,
702 	  rr_section_type section,
703 	  domain_type    *owner,
704 	  rrset_type     *rrset)
705 {
706 	int result;
707 
708 	assert(query);
709 	assert(answer);
710 	assert(owner);
711 	assert(rrset);
712 	assert(rrset_rrclass(rrset) == CLASS_IN);
713 
714 	result = answer_add_rrset(answer, section, owner, rrset);
715 	if(minimal_responses && section != AUTHORITY_SECTION &&
716 		query->qtype != TYPE_NS)
717 		return result;
718 	switch (rrset_rrtype(rrset)) {
719 	case TYPE_NS:
720 #if defined(INET6)
721 		/* if query over IPv6, swap A and AAAA; put AAAA first */
722 		add_additional_rrsets(query, answer, rrset, 0, 1,
723 			(query->addr.ss_family == AF_INET6)?
724 			swap_aaaa_additional_rr_types:
725 			default_additional_rr_types);
726 #else
727 		add_additional_rrsets(query, answer, rrset, 0, 1,
728 				      default_additional_rr_types);
729 #endif
730 		break;
731 	case TYPE_MB:
732 		add_additional_rrsets(query, answer, rrset, 0, 0,
733 				      default_additional_rr_types);
734 		break;
735 	case TYPE_MX:
736 	case TYPE_KX:
737 		add_additional_rrsets(query, answer, rrset, 1, 0,
738 				      default_additional_rr_types);
739 		break;
740 	case TYPE_RT:
741 		add_additional_rrsets(query, answer, rrset, 1, 0,
742 				      rt_additional_rr_types);
743 		break;
744 	case TYPE_SRV:
745 		add_additional_rrsets(query, answer, rrset, 3, 0,
746 				      default_additional_rr_types);
747 		break;
748 	default:
749 		break;
750 	}
751 
752 	return result;
753 }
754 
755 
756 /* returns 0 on error, or the domain number for to_name.
757    from_name is changes to to_name by the DNAME rr.
758    DNAME rr is from src to dest.
759    closest encloser encloses the to_name. */
760 static size_t
761 query_synthesize_cname(struct query* q, struct answer* answer, const dname_type* from_name,
762 	const dname_type* to_name, domain_type* src, domain_type* to_closest_encloser,
763 	domain_type** to_closest_match, uint32_t ttl)
764 {
765 	/* add temporary domains for from_name and to_name and all
766 	   their (not allocated yet) parents */
767 	/* any domains below src are not_existing (because of DNAME at src) */
768 	int i;
769 	domain_type* cname_domain;
770 	domain_type* cname_dest;
771 	rrset_type* rrset;
772 
773 	/* allocate source part */
774 	domain_type* lastparent = src;
775 	assert(q && answer && from_name && to_name && src && to_closest_encloser);
776 	assert(to_closest_match);
777 	for(i=0; i < from_name->label_count - domain_dname(src)->label_count; i++)
778 	{
779 		domain_type* newdom = query_get_tempdomain(q);
780 		if(!newdom)
781 			return 0;
782 		newdom->is_existing = 1;
783 		newdom->parent = lastparent;
784 #ifdef USE_RADIX_TREE
785 		newdom->dname
786 #else
787 		newdom->node.key
788 #endif
789 			= dname_partial_copy(q->region,
790 			from_name, domain_dname(src)->label_count + i + 1);
791 		if(dname_compare(domain_dname(newdom), q->qname) == 0) {
792 			/* 0 good for query name, otherwise new number */
793 			newdom->number = 0;
794 		}
795 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "created temp domain src %d. %s nr %d", i,
796 			domain_to_string(newdom), (int)newdom->number));
797 		lastparent = newdom;
798 	}
799 	cname_domain = lastparent;
800 
801 	/* allocate dest part */
802 	lastparent = to_closest_encloser;
803 	for(i=0; i < to_name->label_count - domain_dname(to_closest_encloser)->label_count;
804 		i++)
805 	{
806 		domain_type* newdom = query_get_tempdomain(q);
807 		if(!newdom)
808 			return 0;
809 		newdom->is_existing = 0;
810 		newdom->parent = lastparent;
811 #ifdef USE_RADIX_TREE
812 		newdom->dname
813 #else
814 		newdom->node.key
815 #endif
816 			= dname_partial_copy(q->region,
817 			to_name, domain_dname(to_closest_encloser)->label_count + i + 1);
818 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "created temp domain dest %d. %s nr %d", i,
819 			domain_to_string(newdom), (int)newdom->number));
820 		lastparent = newdom;
821 	}
822 	cname_dest = lastparent;
823 	*to_closest_match = cname_dest;
824 
825 	/* allocate the CNAME RR */
826 	rrset = (rrset_type*) region_alloc(q->region, sizeof(rrset_type));
827 	memset(rrset, 0, sizeof(rrset_type));
828 	rrset->zone = q->zone;
829 	rrset->rr_count = 1;
830 	rrset->rrs = (rr_type*) region_alloc(q->region, sizeof(rr_type));
831 	memset(rrset->rrs, 0, sizeof(rr_type));
832 	rrset->rrs->owner = cname_domain;
833 	rrset->rrs->ttl = ttl;
834 	rrset->rrs->type = TYPE_CNAME;
835 	rrset->rrs->klass = CLASS_IN;
836 	rrset->rrs->rdata_count = 1;
837 	rrset->rrs->rdatas = (rdata_atom_type*)region_alloc(q->region,
838 		sizeof(rdata_atom_type));
839 	rrset->rrs->rdatas->domain = cname_dest;
840 
841 	if(!add_rrset(q, answer, ANSWER_SECTION, cname_domain, rrset)) {
842 		log_msg(LOG_ERR, "could not add synthesized CNAME rrset to packet");
843 	}
844 
845 	return cname_dest->number;
846 }
847 
848 /*
849  * Answer delegation information.
850  *
851  * DNSSEC: Include the DS RRset if present.  Otherwise include an NSEC
852  * record proving the DS RRset does not exist.
853  */
854 static void
855 answer_delegation(query_type *query, answer_type *answer)
856 {
857 	assert(answer);
858 	assert(query->delegation_domain);
859 	assert(query->delegation_rrset);
860 
861 	if (query->cname_count == 0) {
862 		AA_CLR(query->packet);
863 	} else {
864 		AA_SET(query->packet);
865 	}
866 
867 	add_rrset(query,
868 		  answer,
869 		  AUTHORITY_SECTION,
870 		  query->delegation_domain,
871 		  query->delegation_rrset);
872 	if (query->edns.dnssec_ok && zone_is_secure(query->zone)) {
873 		rrset_type *rrset;
874 		if ((rrset = domain_find_rrset(query->delegation_domain, query->zone, TYPE_DS))) {
875 			add_rrset(query, answer, AUTHORITY_SECTION,
876 				  query->delegation_domain, rrset);
877 #ifdef NSEC3
878 		} else if (query->zone->nsec3_param) {
879 			nsec3_answer_delegation(query, answer);
880 #endif
881 		} else if ((rrset = domain_find_rrset(query->delegation_domain, query->zone, TYPE_NSEC))) {
882 			add_rrset(query, answer, AUTHORITY_SECTION,
883 				  query->delegation_domain, rrset);
884 		}
885 	}
886 }
887 
888 
889 /*
890  * Answer SOA information.
891  */
892 static void
893 answer_soa(struct query *query, answer_type *answer)
894 {
895 	if (query->qclass != CLASS_ANY) {
896 		add_rrset(query, answer,
897 			  AUTHORITY_SECTION,
898 			  query->zone->apex,
899 			  query->zone->soa_nx_rrset);
900 	}
901 }
902 
903 
904 /*
905  * Answer that the domain name exists but there is no RRset with the
906  * requested type.
907  *
908  * DNSSEC: Include the correct NSEC record proving that the type does
909  * not exist.  In the wildcard no data (3.1.3.4) case the wildcard IS
910  * NOT expanded, so the ORIGINAL parameter must point to the original
911  * wildcard entry, not to the generated entry.
912  */
913 static void
914 answer_nodata(struct query *query, answer_type *answer, domain_type *original)
915 {
916 	if (query->cname_count == 0) {
917 		answer_soa(query, answer);
918 	}
919 
920 #ifdef NSEC3
921 	if (query->edns.dnssec_ok && query->zone->nsec3_param) {
922 		nsec3_answer_nodata(query, answer, original);
923 	} else
924 #endif
925 	if (query->edns.dnssec_ok && zone_is_secure(query->zone)) {
926 		domain_type *nsec_domain;
927 		rrset_type *nsec_rrset;
928 
929 		nsec_domain = find_covering_nsec(original, query->zone, &nsec_rrset);
930 		if (nsec_domain) {
931 			add_rrset(query, answer, AUTHORITY_SECTION, nsec_domain, nsec_rrset);
932 		}
933 	}
934 }
935 
936 static void
937 answer_nxdomain(query_type *query, answer_type *answer)
938 {
939 	RCODE_SET(query->packet, RCODE_NXDOMAIN);
940 	answer_soa(query, answer);
941 }
942 
943 
944 /*
945  * Answer domain information (or SOA if we do not have an RRset for
946  * the type specified by the query).
947  */
948 static void
949 answer_domain(struct nsd* nsd, struct query *q, answer_type *answer,
950 	      domain_type *domain, domain_type *original)
951 {
952 	rrset_type *rrset;
953 
954 	if (q->qtype == TYPE_ANY) {
955 		int added = 0;
956 		for (rrset = domain_find_any_rrset(domain, q->zone); rrset; rrset = rrset->next) {
957 			if (rrset->zone == q->zone
958 #ifdef NSEC3
959 				&& rrset_rrtype(rrset) != TYPE_NSEC3
960 #endif
961 			    /*
962 			     * Don't include the RRSIG RRset when
963 			     * DNSSEC is used, because it is added
964 			     * automatically on an per-RRset basis.
965 			     */
966 			    && !(q->edns.dnssec_ok
967 				 && zone_is_secure(q->zone)
968 				 && rrset_rrtype(rrset) == TYPE_RRSIG))
969 			{
970 				add_rrset(q, answer, ANSWER_SECTION, domain, rrset);
971 				++added;
972 			}
973 		}
974 		if (added == 0) {
975 			answer_nodata(q, answer, original);
976 			return;
977 		}
978 #ifdef NSEC3
979 	} else if (q->qtype == TYPE_NSEC3) {
980 		answer_nodata(q, answer, original);
981 		return;
982 #endif
983 	} else if ((rrset = domain_find_rrset(domain, q->zone, q->qtype))) {
984 		add_rrset(q, answer, ANSWER_SECTION, domain, rrset);
985 	} else if ((rrset = domain_find_rrset(domain, q->zone, TYPE_CNAME))) {
986 		int added;
987 
988 		/*
989 		 * If the CNAME is not added it is already in the
990 		 * answer, so we have a CNAME loop.  Don't follow the
991 		 * CNAME target in this case.
992 		 */
993 		added = add_rrset(q, answer, ANSWER_SECTION, domain, rrset);
994 		assert(rrset->rr_count > 0);
995 		if (added) {
996 			/* only process first CNAME record */
997 			domain_type *closest_match = rdata_atom_domain(rrset->rrs[0].rdatas[0]);
998 			domain_type *closest_encloser = closest_match;
999 			zone_type* origzone = q->zone;
1000 			++q->cname_count;
1001 
1002 			answer_lookup_zone(nsd, q, answer, closest_match->number,
1003 					     closest_match == closest_encloser,
1004 					     closest_match, closest_encloser,
1005 					     domain_dname(closest_match));
1006 			q->zone = origzone;
1007 		}
1008 		return;
1009 	} else {
1010 		answer_nodata(q, answer, original);
1011 		return;
1012 	}
1013 
1014 	if (q->qclass != CLASS_ANY && q->zone->ns_rrset && answer_needs_ns(q)
1015 		&& !minimal_responses) {
1016 		add_rrset(q, answer, OPTIONAL_AUTHORITY_SECTION, q->zone->apex,
1017 			  q->zone->ns_rrset);
1018 	}
1019 }
1020 
1021 
1022 /*
1023  * Answer with authoritative data.  If a wildcard is matched the owner
1024  * name will be expanded to the domain name specified by
1025  * DOMAIN_NUMBER.  DOMAIN_NUMBER 0 (zero) is reserved for the original
1026  * query name.
1027  *
1028  * DNSSEC: Include the necessary NSEC records in case the request
1029  * domain name does not exist and/or a wildcard match does not exist.
1030  */
1031 static void
1032 answer_authoritative(struct nsd   *nsd,
1033 		     struct query *q,
1034 		     answer_type  *answer,
1035 		     size_t        domain_number,
1036 		     int           exact,
1037 		     domain_type  *closest_match,
1038 		     domain_type  *closest_encloser,
1039 		     const dname_type *qname)
1040 {
1041 	domain_type *match;
1042 	domain_type *original = closest_match;
1043 	domain_type *dname_ce;
1044 	rrset_type *rrset;
1045 
1046 #ifdef NSEC3
1047 	if(exact && domain_has_only_NSEC3(closest_match, q->zone)) {
1048 		exact = 0; /* pretend it does not exist */
1049 		if(closest_encloser->parent)
1050 			closest_encloser = closest_encloser->parent;
1051 	}
1052 #endif /* NSEC3 */
1053 	if((dname_ce = find_dname_above(closest_encloser, q->zone)) != NULL) {
1054 		/* occlude the found data, the DNAME is closest_encloser */
1055 		closest_encloser = dname_ce;
1056 		exact = 0;
1057 	}
1058 
1059 	if (exact) {
1060 		match = closest_match;
1061 	} else if ((rrset=domain_find_rrset(closest_encloser, q->zone, TYPE_DNAME))) {
1062 		/* process DNAME */
1063 		const dname_type* name = qname;
1064 		domain_type *dest = rdata_atom_domain(rrset->rrs[0].rdatas[0]);
1065 		int added;
1066 		assert(rrset->rr_count > 0);
1067 		if(domain_number != 0) /* we followed CNAMEs or DNAMEs */
1068 			name = domain_dname(closest_match);
1069 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "expanding DNAME for q=%s", dname_to_string(name, NULL)));
1070 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "->src is %s",
1071 			domain_to_string(closest_encloser)));
1072 		DEBUG(DEBUG_QUERY,2, (LOG_INFO, "->dest is %s",
1073 			domain_to_string(dest)));
1074 		/* if the DNAME set is not added we have a loop, do not follow */
1075 		added = add_rrset(q, answer, ANSWER_SECTION, closest_encloser, rrset);
1076 		if(added) {
1077 			domain_type* src = closest_encloser;
1078 			const dname_type* newname = dname_replace(q->region, name,
1079 				domain_dname(src), domain_dname(dest));
1080 			size_t newnum = 0;
1081 			zone_type* origzone = q->zone;
1082 			++q->cname_count;
1083 			if(!newname) { /* newname too long */
1084 				RCODE_SET(q->packet, RCODE_YXDOMAIN);
1085 				return;
1086 			}
1087 			DEBUG(DEBUG_QUERY,2, (LOG_INFO, "->result is %s", dname_to_string(newname, NULL)));
1088 			/* follow the DNAME */
1089 			(void)namedb_lookup(nsd->db, newname, &closest_match, &closest_encloser);
1090 			/* synthesize CNAME record */
1091 			newnum = query_synthesize_cname(q, answer, name, newname,
1092 				src, closest_encloser, &closest_match, rrset->rrs[0].ttl);
1093 			if(!newnum) {
1094 				/* could not synthesize the CNAME. */
1095 				/* return previous CNAMEs to make resolver recurse for us */
1096 				return;
1097 			}
1098 
1099 			answer_lookup_zone(nsd, q, answer, newnum,
1100 				closest_match == closest_encloser,
1101 				closest_match, closest_encloser, newname);
1102 			q->zone = origzone;
1103 		}
1104 		if(!added)  /* log the error so operator can find looping recursors */
1105 			log_msg(LOG_INFO, "DNAME processing stopped due to loop, qname %s",
1106 				dname_to_string(q->qname, NULL));
1107 		return;
1108 	} else if (domain_wildcard_child(closest_encloser)) {
1109 		/* Generate the domain from the wildcard.  */
1110 		domain_type *wildcard_child = domain_wildcard_child(closest_encloser);
1111 #ifdef RATELIMIT
1112 		q->wildcard_domain = wildcard_child;
1113 #endif
1114 
1115 		match = (domain_type *) region_alloc(q->region,
1116 						     sizeof(domain_type));
1117 #ifdef USE_RADIX_TREE
1118 		match->rnode = NULL;
1119 		match->dname = wildcard_child->dname;
1120 #else
1121 		memcpy(&match->node, &wildcard_child->node, sizeof(rbnode_type));
1122 		match->node.parent = NULL;
1123 #endif
1124 		match->parent = closest_encloser;
1125 		match->wildcard_child_closest_match = match;
1126 		match->number = domain_number;
1127 		match->rrsets = wildcard_child->rrsets;
1128 		match->is_existing = wildcard_child->is_existing;
1129 #ifdef NSEC3
1130 		match->nsec3 = wildcard_child->nsec3;
1131 		/* copy over these entries:
1132 		match->nsec3_is_exact = wildcard_child->nsec3_is_exact;
1133 		match->nsec3_cover = wildcard_child->nsec3_cover;
1134 		match->nsec3_wcard_child_cover = wildcard_child->nsec3_wcard_child_cover;
1135 		match->nsec3_ds_parent_is_exact = wildcard_child->nsec3_ds_parent_is_exact;
1136 		match->nsec3_ds_parent_cover = wildcard_child->nsec3_ds_parent_cover;
1137 		*/
1138 
1139 		if (q->edns.dnssec_ok && q->zone->nsec3_param) {
1140 			/* Only add nsec3 wildcard data when do bit is set */
1141 			nsec3_answer_wildcard(q, answer, wildcard_child, qname);
1142 		}
1143 #endif
1144 
1145 		/*
1146 		 * Remember the original domain in case a Wildcard No
1147 		 * Data (3.1.3.4) response needs to be generated.  In
1148 		 * this particular case the wildcard IS NOT
1149 		 * expanded.
1150 		 */
1151 		original = wildcard_child;
1152 	} else {
1153 		match = NULL;
1154 	}
1155 
1156 	/* Authoritative zone.  */
1157 #ifdef NSEC3
1158 	if (q->edns.dnssec_ok && q->zone->nsec3_param) {
1159 		nsec3_answer_authoritative(&match, q, answer,
1160 			closest_encloser, qname);
1161 	} else
1162 #endif
1163 	if (q->edns.dnssec_ok && zone_is_secure(q->zone)) {
1164 		if (match != closest_encloser) {
1165 			domain_type *nsec_domain;
1166 			rrset_type *nsec_rrset;
1167 
1168 			/*
1169 			 * No match found or generated from wildcard,
1170 			 * include NSEC record.
1171 			 */
1172 			nsec_domain = find_covering_nsec(closest_match, q->zone, &nsec_rrset);
1173 			if (nsec_domain) {
1174 				add_rrset(q, answer, AUTHORITY_SECTION, nsec_domain, nsec_rrset);
1175 			}
1176 		}
1177 		if (!match) {
1178 			domain_type *nsec_domain;
1179 			rrset_type *nsec_rrset;
1180 
1181 			/*
1182 			 * No match and no wildcard.  Include NSEC
1183 			 * proving there is no wildcard.
1184 			 */
1185 			nsec_domain = find_covering_nsec(closest_encloser->wildcard_child_closest_match, q->zone, &nsec_rrset);
1186 			if (nsec_domain) {
1187 				add_rrset(q, answer, AUTHORITY_SECTION, nsec_domain, nsec_rrset);
1188 			}
1189 		}
1190 	}
1191 
1192 #ifdef NSEC3
1193 	if (RCODE(q->packet)!=RCODE_OK) {
1194 		return; /* nsec3 collision failure */
1195 	}
1196 #endif
1197 	if (match) {
1198 		answer_domain(nsd, q, answer, match, original);
1199 	} else {
1200 		answer_nxdomain(q, answer);
1201 	}
1202 }
1203 
1204 /*
1205  * qname may be different after CNAMEs have been followed from query->qname.
1206  */
1207 static void
1208 answer_lookup_zone(struct nsd *nsd, struct query *q, answer_type *answer,
1209 	size_t domain_number, int exact, domain_type *closest_match,
1210 	domain_type *closest_encloser, const dname_type *qname)
1211 {
1212 	q->zone = domain_find_zone(nsd->db, closest_encloser);
1213 	if (!q->zone) {
1214 		/* no zone for this */
1215 		if(q->cname_count == 0)
1216 			RCODE_SET(q->packet, RCODE_REFUSE);
1217 		return;
1218 	}
1219 	assert(closest_encloser); /* otherwise, no q->zone would be found */
1220 	if(!q->zone->apex || !q->zone->soa_rrset) {
1221 		/* zone is configured but not loaded */
1222 		if(q->cname_count == 0)
1223 			RCODE_SET(q->packet, RCODE_SERVFAIL);
1224 		return;
1225 	}
1226 	/* now move up the closest encloser until it exists, previous
1227 	 * (possibly empty) closest encloser was useful to finding the zone
1228 	 * (for empty zones too), but now we want actual data nodes */
1229 	if (closest_encloser && !closest_encloser->is_existing) {
1230 		exact = 0;
1231 		while (closest_encloser != NULL && !closest_encloser->is_existing)
1232 			closest_encloser = closest_encloser->parent;
1233 	}
1234 
1235 	/*
1236 	 * See RFC 4035 (DNSSEC protocol) section 3.1.4.1 Responding
1237 	 * to Queries for DS RRs.
1238 	 */
1239 	if (exact && q->qtype == TYPE_DS && closest_encloser == q->zone->apex) {
1240 		/*
1241 		 * Type DS query at a zone cut, use the responsible
1242 		 * parent zone to generate the answer if we are
1243 		 * authoritative for the parent zone.
1244 		 */
1245 		zone_type *zone = domain_find_parent_zone(nsd->db, q->zone);
1246 		if (zone) {
1247 			q->zone = zone;
1248 			if(!q->zone->apex || !q->zone->soa_rrset) {
1249 				/* zone is configured but not loaded */
1250 				if(q->cname_count == 0)
1251 					RCODE_SET(q->packet, RCODE_SERVFAIL);
1252 				return;
1253 			}
1254 		}
1255 	}
1256 
1257 	/* see if the zone has expired (for secondary zones) */
1258 	if(q->zone && q->zone->opts && q->zone->opts->pattern &&
1259 		q->zone->opts->pattern->request_xfr != 0 && !q->zone->is_ok) {
1260 		if(q->cname_count == 0)
1261 			RCODE_SET(q->packet, RCODE_SERVFAIL);
1262 		return;
1263 	}
1264 
1265 	if (exact && q->qtype == TYPE_DS && closest_encloser == q->zone->apex) {
1266 		/*
1267 		 * Type DS query at the zone apex (and the server is
1268 		 * not authoritative for the parent zone).
1269 		 */
1270 		if (q->qclass == CLASS_ANY) {
1271 			AA_CLR(q->packet);
1272 		} else {
1273 			AA_SET(q->packet);
1274 		}
1275 		answer_nodata(q, answer, closest_encloser);
1276 	} else {
1277 		q->delegation_domain = domain_find_ns_rrsets(
1278 			closest_encloser, q->zone, &q->delegation_rrset);
1279 		if(q->delegation_domain && find_dname_above(q->delegation_domain, q->zone)) {
1280 			q->delegation_domain = NULL; /* use higher DNAME */
1281 		}
1282 
1283 		if (!q->delegation_domain
1284 		    || (exact && q->qtype == TYPE_DS && closest_encloser == q->delegation_domain))
1285 		{
1286 			if (q->qclass == CLASS_ANY) {
1287 				AA_CLR(q->packet);
1288 			} else {
1289 				AA_SET(q->packet);
1290 			}
1291 			answer_authoritative(nsd, q, answer, domain_number, exact,
1292 					     closest_match, closest_encloser, qname);
1293 		}
1294 		else {
1295 			answer_delegation(q, answer);
1296 		}
1297 	}
1298 }
1299 
1300 static void
1301 answer_query(struct nsd *nsd, struct query *q)
1302 {
1303 	domain_type *closest_match;
1304 	domain_type *closest_encloser;
1305 	int exact;
1306 	uint16_t offset;
1307 	answer_type answer;
1308 
1309 	answer_init(&answer);
1310 
1311 	exact = namedb_lookup(nsd->db, q->qname, &closest_match, &closest_encloser);
1312 
1313 	answer_lookup_zone(nsd, q, &answer, 0, exact, closest_match,
1314 		closest_encloser, q->qname);
1315 	ZTATUP2(nsd, q->zone, opcode, q->opcode);
1316 	ZTATUP2(nsd, q->zone, qtype, q->qtype);
1317 	ZTATUP2(nsd, q->zone, qclass, q->qclass);
1318 
1319 	offset = dname_label_offsets(q->qname)[domain_dname(closest_encloser)->label_count - 1] + QHEADERSZ;
1320 	query_add_compression_domain(q, closest_encloser, offset);
1321 	encode_answer(q, &answer);
1322 	query_clear_compression_tables(q);
1323 }
1324 
1325 void
1326 query_prepare_response(query_type *q)
1327 {
1328 	uint16_t flags;
1329 
1330 	/*
1331 	 * Preserve the data up-to the current packet's limit.
1332 	 */
1333 	buffer_set_position(q->packet, buffer_limit(q->packet));
1334 	buffer_set_limit(q->packet, buffer_capacity(q->packet));
1335 
1336 	/*
1337 	 * Reserve space for the EDNS records if required.
1338 	 */
1339 	q->reserved_space = edns_reserved_space(&q->edns);
1340 	q->reserved_space += tsig_reserved_space(&q->tsig);
1341 
1342 	/* Update the flags.  */
1343 	flags = FLAGS(q->packet);
1344 	flags &= 0x0100U;	/* Preserve the RD flag.  */
1345 				/* CD flag must be cleared for auth answers */
1346 	flags |= 0x8000U;	/* Set the QR flag.  */
1347 	FLAGS_SET(q->packet, flags);
1348 }
1349 
1350 /*
1351  * Processes the query.
1352  *
1353  */
1354 query_state_type
1355 query_process(query_type *q, nsd_type *nsd)
1356 {
1357 	/* The query... */
1358 	nsd_rc_type rc;
1359 	query_state_type query_state;
1360 	uint16_t arcount;
1361 
1362 	/* Sanity checks */
1363 	if (buffer_limit(q->packet) < QHEADERSZ) {
1364 		/* packet too small to contain DNS header.
1365 		Now packet investigation macros will work without problems. */
1366 		return QUERY_DISCARDED;
1367 	}
1368 	if (QR(q->packet)) {
1369 		/* Not a query? Drop it on the floor. */
1370 		return QUERY_DISCARDED;
1371 	}
1372 
1373 	/* check opcode early on, because new opcodes may have different
1374 	 * specification of the meaning of the rest of the packet */
1375 	q->opcode = OPCODE(q->packet);
1376 	if(q->opcode != OPCODE_QUERY && q->opcode != OPCODE_NOTIFY) {
1377 		if(query_ratelimit_err(nsd))
1378 			return QUERY_DISCARDED;
1379 		return query_error(q, NSD_RC_IMPL);
1380 	}
1381 
1382 	if (RCODE(q->packet) != RCODE_OK || !process_query_section(q)) {
1383 		return query_formerr(q, nsd);
1384 	}
1385 
1386 	/* Update statistics.  */
1387 	STATUP2(nsd, opcode, q->opcode);
1388 	STATUP2(nsd, qtype, q->qtype);
1389 	STATUP2(nsd, qclass, q->qclass);
1390 
1391 	if (q->opcode != OPCODE_QUERY) {
1392 		if (q->opcode == OPCODE_NOTIFY) {
1393 			return answer_notify(nsd, q);
1394 		} else {
1395 			if(query_ratelimit_err(nsd))
1396 				return QUERY_DISCARDED;
1397 			return query_error(q, NSD_RC_IMPL);
1398 		}
1399 	}
1400 
1401 	/* Dont bother to answer more than one question at once... */
1402 	if (QDCOUNT(q->packet) != 1) {
1403 		FLAGS_SET(q->packet, 0);
1404 		return query_formerr(q, nsd);
1405 	}
1406 	/* Ignore settings of flags */
1407 
1408 	/* Dont allow any records in the answer or authority section...
1409 	   except for IXFR queries. */
1410 	if (ANCOUNT(q->packet) != 0 ||
1411 		(q->qtype!=TYPE_IXFR && NSCOUNT(q->packet) != 0)) {
1412 		return query_formerr(q, nsd);
1413 	}
1414 	if(q->qtype==TYPE_IXFR && NSCOUNT(q->packet) > 0) {
1415 		int i; /* skip ixfr soa information data here */
1416 		for(i=0; i< NSCOUNT(q->packet); i++)
1417 			if(!packet_skip_rr(q->packet, 0))
1418 				return query_formerr(q, nsd);
1419 	}
1420 
1421 	arcount = ARCOUNT(q->packet);
1422 	if (arcount > 0) {
1423 		/* According to draft-ietf-dnsext-rfc2671bis-edns0-10:
1424 		 * "The placement flexibility for the OPT RR does not
1425 		 * override the need for the TSIG or SIG(0) RRs to be
1426 		 * the last in the additional section whenever they are
1427 		 * present."
1428 		 * So we should not have to check for TSIG RR before
1429 		 * OPT RR. Keep the code for backwards compatibility.
1430 		 */
1431 
1432 		/* see if tsig is before edns record */
1433 		if (!tsig_parse_rr(&q->tsig, q->packet))
1434 			return query_formerr(q, nsd);
1435 		if(q->tsig.status != TSIG_NOT_PRESENT)
1436 			--arcount;
1437 	}
1438 	/* See if there is an OPT RR. */
1439 	if (arcount > 0) {
1440 		if (edns_parse_record(&q->edns, q->packet, q, nsd))
1441 			--arcount;
1442 	}
1443 	/* See if there is a TSIG RR. */
1444 	if (arcount > 0 && q->tsig.status == TSIG_NOT_PRESENT) {
1445 		/* see if tsig is after the edns record */
1446 		if (!tsig_parse_rr(&q->tsig, q->packet))
1447 			return query_formerr(q, nsd);
1448 		if(q->tsig.status != TSIG_NOT_PRESENT)
1449 			--arcount;
1450 	}
1451 	/* If more RRs left in Add. Section, FORMERR. */
1452 	if (arcount > 0) {
1453 		return query_formerr(q, nsd);
1454 	}
1455 
1456 	/* Do we have any trailing garbage? */
1457 #ifdef	STRICT_MESSAGE_PARSE
1458 	if (buffer_remaining(q->packet) > 0) {
1459 		/* If we're strict.... */
1460 		return query_formerr(q, nsd);
1461 	}
1462 #endif
1463 	/* Remove trailing garbage.  */
1464 	buffer_set_limit(q->packet, buffer_position(q->packet));
1465 
1466 	rc = process_tsig(q);
1467 	if (rc != NSD_RC_OK) {
1468 		return query_error(q, rc);
1469 	}
1470 	rc = process_edns(nsd, q);
1471 	if (rc != NSD_RC_OK) {
1472 		/* We should not return FORMERR, but BADVERS (=16).
1473 		 * BADVERS is created with Ext. RCODE, followed by RCODE.
1474 		 * Ext. RCODE is set to 1, RCODE must be 0 (getting 0x10 = 16).
1475 		 * Thus RCODE = NOERROR = NSD_RC_OK. */
1476 		return query_error(q, NSD_RC_OK);
1477 	}
1478 
1479 	query_prepare_response(q);
1480 
1481 	if (q->qclass != CLASS_IN && q->qclass != CLASS_ANY) {
1482 		if (q->qclass == CLASS_CH) {
1483 			return answer_chaos(nsd, q);
1484 		} else {
1485 			return query_error(q, NSD_RC_REFUSE);
1486 		}
1487 	}
1488 
1489 	query_state = answer_axfr_ixfr(nsd, q);
1490 	if (query_state == QUERY_PROCESSED || query_state == QUERY_IN_AXFR) {
1491 		return query_state;
1492 	}
1493 	if(q->qtype == TYPE_ANY && nsd->options->refuse_any && !q->tcp) {
1494 		TC_SET(q->packet);
1495 		return query_error(q, NSD_RC_OK);
1496 	}
1497 
1498 	answer_query(nsd, q);
1499 
1500 	return QUERY_PROCESSED;
1501 }
1502 
1503 void
1504 query_add_optional(query_type *q, nsd_type *nsd)
1505 {
1506 	struct edns_data *edns = &nsd->edns_ipv4;
1507 #if defined(INET6)
1508 	if (q->addr.ss_family == AF_INET6) {
1509 		edns = &nsd->edns_ipv6;
1510 	}
1511 #endif
1512 	if (RCODE(q->packet) == RCODE_FORMAT) {
1513 		return;
1514 	}
1515 	switch (q->edns.status) {
1516 	case EDNS_NOT_PRESENT:
1517 		break;
1518 	case EDNS_OK:
1519 		if (q->edns.dnssec_ok)	edns->ok[7] = 0x80;
1520 		else			edns->ok[7] = 0x00;
1521 		buffer_write(q->packet, edns->ok, OPT_LEN);
1522 		if(q->edns.opt_reserved_space == 0 || !buffer_available(
1523 			q->packet, 2+q->edns.opt_reserved_space)) {
1524 			/* fill with NULLs */
1525 			buffer_write(q->packet, edns->rdata_none, OPT_RDATA);
1526 		} else {
1527 			/* rdata length */
1528 			buffer_write_u16(q->packet, q->edns.opt_reserved_space);
1529 			/* edns options */
1530 			if(q->edns.nsid) {
1531 				/* nsid opt header */
1532 				buffer_write(q->packet, edns->nsid, OPT_HDR);
1533 				/* nsid payload */
1534 				buffer_write(q->packet, nsd->nsid, nsd->nsid_len);
1535 			}
1536 		}
1537 		ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1538 		STATUP(nsd, edns);
1539 		ZTATUP(nsd, q->zone, edns);
1540 		break;
1541 	case EDNS_ERROR:
1542 		if (q->edns.dnssec_ok)	edns->error[7] = 0x80;
1543 		else			edns->error[7] = 0x00;
1544 		buffer_write(q->packet, edns->error, OPT_LEN);
1545 		buffer_write(q->packet, edns->rdata_none, OPT_RDATA);
1546 		ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1547 		STATUP(nsd, ednserr);
1548 		ZTATUP(nsd, q->zone, ednserr);
1549 		break;
1550 	}
1551 
1552 	if (q->tsig.status != TSIG_NOT_PRESENT) {
1553 		if (q->tsig.status == TSIG_ERROR ||
1554 			q->tsig.error_code != TSIG_ERROR_NOERROR) {
1555 			tsig_error_reply(&q->tsig);
1556 			tsig_append_rr(&q->tsig, q->packet);
1557 			ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1558 		} else if(q->tsig.status == TSIG_OK &&
1559 			q->tsig.error_code == TSIG_ERROR_NOERROR)
1560 		{
1561 			if(q->tsig_prepare_it)
1562 				tsig_prepare(&q->tsig);
1563 			if(q->tsig_update_it)
1564 				tsig_update(&q->tsig, q->packet, buffer_position(q->packet));
1565 			if(q->tsig_sign_it) {
1566 				tsig_sign(&q->tsig);
1567 				tsig_append_rr(&q->tsig, q->packet);
1568 				ARCOUNT_SET(q->packet, ARCOUNT(q->packet) + 1);
1569 			}
1570 		}
1571 	}
1572 }
1573