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