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