xref: /freebsd/contrib/unbound/services/localzone.c (revision 9e5787d2284e187abb5b654d924394a65772e004)
1 /*
2  * services/localzone.c - local zones authority service.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains functions to enable local zone authority service.
40  */
41 #include "config.h"
42 #include "services/localzone.h"
43 #include "sldns/str2wire.h"
44 #include "util/regional.h"
45 #include "util/config_file.h"
46 #include "util/data/dname.h"
47 #include "util/data/packed_rrset.h"
48 #include "util/data/msgencode.h"
49 #include "util/net_help.h"
50 #include "util/netevent.h"
51 #include "util/data/msgreply.h"
52 #include "util/data/msgparse.h"
53 #include "util/as112.h"
54 
55 /* maximum RRs in an RRset, to cap possible 'endless' list RRs.
56  * with 16 bytes for an A record, a 64K packet has about 4000 max */
57 #define LOCALZONE_RRSET_COUNT_MAX 4096
58 
59 struct local_zones*
60 local_zones_create(void)
61 {
62 	struct local_zones* zones = (struct local_zones*)calloc(1,
63 		sizeof(*zones));
64 	if(!zones)
65 		return NULL;
66 	rbtree_init(&zones->ztree, &local_zone_cmp);
67 	lock_rw_init(&zones->lock);
68 	lock_protect(&zones->lock, &zones->ztree, sizeof(zones->ztree));
69 	/* also lock protects the rbnode's in struct local_zone */
70 	return zones;
71 }
72 
73 /** helper traverse to delete zones */
74 static void
75 lzdel(rbnode_type* n, void* ATTR_UNUSED(arg))
76 {
77 	struct local_zone* z = (struct local_zone*)n->key;
78 	local_zone_delete(z);
79 }
80 
81 void
82 local_zones_delete(struct local_zones* zones)
83 {
84 	if(!zones)
85 		return;
86 	lock_rw_destroy(&zones->lock);
87 	/* walk through zones and delete them all */
88 	traverse_postorder(&zones->ztree, lzdel, NULL);
89 	free(zones);
90 }
91 
92 void
93 local_zone_delete(struct local_zone* z)
94 {
95 	if(!z)
96 		return;
97 	lock_rw_destroy(&z->lock);
98 	regional_destroy(z->region);
99 	free(z->name);
100 	free(z->taglist);
101 	free(z);
102 }
103 
104 int
105 local_zone_cmp(const void* z1, const void* z2)
106 {
107 	/* first sort on class, so that hierarchy can be maintained within
108 	 * a class */
109 	struct local_zone* a = (struct local_zone*)z1;
110 	struct local_zone* b = (struct local_zone*)z2;
111 	int m;
112 	if(a->dclass != b->dclass) {
113 		if(a->dclass < b->dclass)
114 			return -1;
115 		return 1;
116 	}
117 	return dname_lab_cmp(a->name, a->namelabs, b->name, b->namelabs, &m);
118 }
119 
120 int
121 local_data_cmp(const void* d1, const void* d2)
122 {
123 	struct local_data* a = (struct local_data*)d1;
124 	struct local_data* b = (struct local_data*)d2;
125 	int m;
126 	return dname_canon_lab_cmp(a->name, a->namelabs, b->name,
127 		b->namelabs, &m);
128 }
129 
130 /* form wireformat from text format domain name */
131 int
132 parse_dname(const char* str, uint8_t** res, size_t* len, int* labs)
133 {
134 	*res = sldns_str2wire_dname(str, len);
135 	*labs = 0;
136 	if(!*res) {
137 		log_err("cannot parse name %s", str);
138 		return 0;
139 	}
140 	*labs = dname_count_size_labels(*res, len);
141 	return 1;
142 }
143 
144 /** create a new localzone */
145 static struct local_zone*
146 local_zone_create(uint8_t* nm, size_t len, int labs,
147 	enum localzone_type t, uint16_t dclass)
148 {
149 	struct local_zone* z = (struct local_zone*)calloc(1, sizeof(*z));
150 	if(!z) {
151 		return NULL;
152 	}
153 	z->node.key = z;
154 	z->dclass = dclass;
155 	z->type = t;
156 	z->name = nm;
157 	z->namelen = len;
158 	z->namelabs = labs;
159 	lock_rw_init(&z->lock);
160 	z->region = regional_create_custom(sizeof(struct regional));
161 	if(!z->region) {
162 		free(z);
163 		return NULL;
164 	}
165 	rbtree_init(&z->data, &local_data_cmp);
166 	lock_protect(&z->lock, &z->parent, sizeof(*z)-sizeof(rbnode_type));
167 	/* also the zones->lock protects node, parent, name*, class */
168 	return z;
169 }
170 
171 /** enter a new zone with allocated dname returns with WRlock */
172 static struct local_zone*
173 lz_enter_zone_dname(struct local_zones* zones, uint8_t* nm, size_t len,
174 	int labs, enum localzone_type t, uint16_t c)
175 {
176 	struct local_zone* z = local_zone_create(nm, len, labs, t, c);
177 	if(!z) {
178 		free(nm);
179 		log_err("out of memory");
180 		return NULL;
181 	}
182 
183 	/* add to rbtree */
184 	lock_rw_wrlock(&zones->lock);
185 	lock_rw_wrlock(&z->lock);
186 	if(!rbtree_insert(&zones->ztree, &z->node)) {
187 		struct local_zone* oldz;
188 		char str[256];
189 		dname_str(nm, str);
190 		log_warn("duplicate local-zone %s", str);
191 		lock_rw_unlock(&z->lock);
192 		/* save zone name locally before deallocation,
193 		 * otherwise, nm is gone if we zone_delete now. */
194 		oldz = z;
195 		/* find the correct zone, so not an error for duplicate */
196 		z = local_zones_find(zones, nm, len, labs, c);
197 		lock_rw_wrlock(&z->lock);
198 		lock_rw_unlock(&zones->lock);
199 		local_zone_delete(oldz);
200 		return z;
201 	}
202 	lock_rw_unlock(&zones->lock);
203 	return z;
204 }
205 
206 /** enter a new zone */
207 static struct local_zone*
208 lz_enter_zone(struct local_zones* zones, const char* name, const char* type,
209 	uint16_t dclass)
210 {
211 	struct local_zone* z;
212 	enum localzone_type t;
213 	uint8_t* nm;
214 	size_t len;
215 	int labs;
216 	if(!parse_dname(name, &nm, &len, &labs)) {
217 		log_err("bad zone name %s %s", name, type);
218 		return NULL;
219 	}
220 	if(!local_zone_str2type(type, &t)) {
221 		log_err("bad lz_enter_zone type %s %s", name, type);
222 		free(nm);
223 		return NULL;
224 	}
225 	if(!(z=lz_enter_zone_dname(zones, nm, len, labs, t, dclass))) {
226 		log_err("could not enter zone %s %s", name, type);
227 		return NULL;
228 	}
229 	return z;
230 }
231 
232 int
233 rrstr_get_rr_content(const char* str, uint8_t** nm, uint16_t* type,
234 	uint16_t* dclass, time_t* ttl, uint8_t* rr, size_t len,
235 	uint8_t** rdata, size_t* rdata_len)
236 {
237 	size_t dname_len = 0;
238 	int e = sldns_str2wire_rr_buf(str, rr, &len, &dname_len, 3600,
239 		NULL, 0, NULL, 0);
240 	if(e) {
241 		log_err("error parsing local-data at %d: '%s': %s",
242 			LDNS_WIREPARSE_OFFSET(e), str,
243 			sldns_get_errorstr_parse(e));
244 		return 0;
245 	}
246 	*nm = memdup(rr, dname_len);
247 	if(!*nm) {
248 		log_err("out of memory");
249 		return 0;
250 	}
251 	*dclass = sldns_wirerr_get_class(rr, len, dname_len);
252 	*type = sldns_wirerr_get_type(rr, len, dname_len);
253 	*ttl = (time_t)sldns_wirerr_get_ttl(rr, len, dname_len);
254 	*rdata = sldns_wirerr_get_rdatawl(rr, len, dname_len);
255 	*rdata_len = sldns_wirerr_get_rdatalen(rr, len, dname_len)+2;
256 	return 1;
257 }
258 
259 /** return name and class of rr; parses string */
260 static int
261 get_rr_nameclass(const char* str, uint8_t** nm, uint16_t* dclass,
262 	uint16_t* dtype)
263 {
264 	uint8_t rr[LDNS_RR_BUF_SIZE];
265 	size_t len = sizeof(rr), dname_len = 0;
266 	int s = sldns_str2wire_rr_buf(str, rr, &len, &dname_len, 3600,
267 		NULL, 0, NULL, 0);
268 	if(s != 0) {
269 		log_err("error parsing local-data at %d '%s': %s",
270 			LDNS_WIREPARSE_OFFSET(s), str,
271 			sldns_get_errorstr_parse(s));
272 		return 0;
273 	}
274 	*nm = memdup(rr, dname_len);
275 	*dclass = sldns_wirerr_get_class(rr, len, dname_len);
276 	*dtype = sldns_wirerr_get_type(rr, len, dname_len);
277 	if(!*nm) {
278 		log_err("out of memory");
279 		return 0;
280 	}
281 	return 1;
282 }
283 
284 /**
285  * Find an rrset in local data structure.
286  * @param data: local data domain name structure.
287  * @param type: type to look for (host order).
288  * @param alias_ok: 1 if matching a non-exact, alias type such as CNAME is
289  * allowed.  otherwise 0.
290  * @return rrset pointer or NULL if not found.
291  */
292 static struct local_rrset*
293 local_data_find_type(struct local_data* data, uint16_t type, int alias_ok)
294 {
295 	struct local_rrset* p;
296 	type = htons(type);
297 	for(p = data->rrsets; p; p = p->next) {
298 		if(p->rrset->rk.type == type)
299 			return p;
300 		if(alias_ok && p->rrset->rk.type == htons(LDNS_RR_TYPE_CNAME))
301 			return p;
302 	}
303 	return NULL;
304 }
305 
306 /** check for RR duplicates */
307 static int
308 rr_is_duplicate(struct packed_rrset_data* pd, uint8_t* rdata, size_t rdata_len)
309 {
310 	size_t i;
311 	for(i=0; i<pd->count; i++) {
312 		if(pd->rr_len[i] == rdata_len &&
313 			memcmp(pd->rr_data[i], rdata, rdata_len) == 0)
314 			return 1;
315 	}
316 	return 0;
317 }
318 
319 /** new local_rrset */
320 static struct local_rrset*
321 new_local_rrset(struct regional* region, struct local_data* node,
322 	uint16_t rrtype, uint16_t rrclass)
323 {
324 	struct packed_rrset_data* pd;
325 	struct local_rrset* rrset = (struct local_rrset*)
326 		regional_alloc_zero(region, sizeof(*rrset));
327 	if(!rrset) {
328 		log_err("out of memory");
329 		return NULL;
330 	}
331 	rrset->next = node->rrsets;
332 	node->rrsets = rrset;
333 	rrset->rrset = (struct ub_packed_rrset_key*)
334 		regional_alloc_zero(region, sizeof(*rrset->rrset));
335 	if(!rrset->rrset) {
336 		log_err("out of memory");
337 		return NULL;
338 	}
339 	rrset->rrset->entry.key = rrset->rrset;
340 	pd = (struct packed_rrset_data*)regional_alloc_zero(region,
341 		sizeof(*pd));
342 	if(!pd) {
343 		log_err("out of memory");
344 		return NULL;
345 	}
346 	pd->trust = rrset_trust_prim_noglue;
347 	pd->security = sec_status_insecure;
348 	rrset->rrset->entry.data = pd;
349 	rrset->rrset->rk.dname = node->name;
350 	rrset->rrset->rk.dname_len = node->namelen;
351 	rrset->rrset->rk.type = htons(rrtype);
352 	rrset->rrset->rk.rrset_class = htons(rrclass);
353 	return rrset;
354 }
355 
356 /** insert RR into RRset data structure; Wastes a couple of bytes */
357 int
358 rrset_insert_rr(struct regional* region, struct packed_rrset_data* pd,
359 	uint8_t* rdata, size_t rdata_len, time_t ttl, const char* rrstr)
360 {
361 	size_t* oldlen = pd->rr_len;
362 	time_t* oldttl = pd->rr_ttl;
363 	uint8_t** olddata = pd->rr_data;
364 
365 	/* add RR to rrset */
366 	if(pd->count > LOCALZONE_RRSET_COUNT_MAX) {
367 		log_warn("RRset '%s' has more than %d records, record ignored",
368 			rrstr, LOCALZONE_RRSET_COUNT_MAX);
369 		return 1;
370 	}
371 	pd->count++;
372 	pd->rr_len = regional_alloc(region, sizeof(*pd->rr_len)*pd->count);
373 	pd->rr_ttl = regional_alloc(region, sizeof(*pd->rr_ttl)*pd->count);
374 	pd->rr_data = regional_alloc(region, sizeof(*pd->rr_data)*pd->count);
375 	if(!pd->rr_len || !pd->rr_ttl || !pd->rr_data) {
376 		log_err("out of memory");
377 		return 0;
378 	}
379 	if(pd->count > 1) {
380 		memcpy(pd->rr_len+1, oldlen,
381 			sizeof(*pd->rr_len)*(pd->count-1));
382 		memcpy(pd->rr_ttl+1, oldttl,
383 			sizeof(*pd->rr_ttl)*(pd->count-1));
384 		memcpy(pd->rr_data+1, olddata,
385 			sizeof(*pd->rr_data)*(pd->count-1));
386 	}
387 	pd->rr_len[0] = rdata_len;
388 	pd->rr_ttl[0] = ttl;
389 	pd->rr_data[0] = regional_alloc_init(region, rdata, rdata_len);
390 	if(!pd->rr_data[0]) {
391 		log_err("out of memory");
392 		return 0;
393 	}
394 	return 1;
395 }
396 
397 /** Delete RR from local-zone RRset, wastes memory as the deleted RRs cannot be
398  * free'd (regionally alloc'd) */
399 int
400 local_rrset_remove_rr(struct packed_rrset_data* pd, size_t index)
401 {
402 	log_assert(pd->count > 0);
403 	if(index >= pd->count) {
404 		log_warn("Trying to remove RR with out of bound index");
405 		return 0;
406 	}
407 	if(index + 1 < pd->count) {
408 		/* not removing last element */
409 		size_t nexti = index + 1;
410 		size_t num = pd->count - nexti;
411 		memmove(pd->rr_len+index, pd->rr_len+nexti, sizeof(*pd->rr_len)*num);
412 		memmove(pd->rr_ttl+index, pd->rr_ttl+nexti, sizeof(*pd->rr_ttl)*num);
413 		memmove(pd->rr_data+index, pd->rr_data+nexti, sizeof(*pd->rr_data)*num);
414 	}
415 	pd->count--;
416 	return 1;
417 }
418 
419 struct local_data*
420 local_zone_find_data(struct local_zone* z, uint8_t* nm, size_t nmlen, int nmlabs)
421 {
422 	struct local_data key;
423 	key.node.key = &key;
424 	key.name = nm;
425 	key.namelen = nmlen;
426 	key.namelabs = nmlabs;
427 	return (struct local_data*)rbtree_search(&z->data, &key.node);
428 }
429 
430 /** find a node, create it if not and all its empty nonterminal parents */
431 static int
432 lz_find_create_node(struct local_zone* z, uint8_t* nm, size_t nmlen,
433 	int nmlabs, struct local_data** res)
434 {
435 	struct local_data* ld = local_zone_find_data(z, nm, nmlen, nmlabs);
436 	if(!ld) {
437 		/* create a domain name to store rr. */
438 		ld = (struct local_data*)regional_alloc_zero(z->region,
439 			sizeof(*ld));
440 		if(!ld) {
441 			log_err("out of memory adding local data");
442 			return 0;
443 		}
444 		ld->node.key = ld;
445 		ld->name = regional_alloc_init(z->region, nm, nmlen);
446 		if(!ld->name) {
447 			log_err("out of memory");
448 			return 0;
449 		}
450 		ld->namelen = nmlen;
451 		ld->namelabs = nmlabs;
452 		if(!rbtree_insert(&z->data, &ld->node)) {
453 			log_assert(0); /* duplicate name */
454 		}
455 		/* see if empty nonterminals need to be created */
456 		if(nmlabs > z->namelabs) {
457 			dname_remove_label(&nm, &nmlen);
458 			if(!lz_find_create_node(z, nm, nmlen, nmlabs-1, res))
459 				return 0;
460 		}
461 	}
462 	*res = ld;
463 	return 1;
464 }
465 
466 int
467 local_zone_enter_rr(struct local_zone* z, uint8_t* nm, size_t nmlen,
468 	int nmlabs, uint16_t rrtype, uint16_t rrclass, time_t ttl,
469 	uint8_t* rdata, size_t rdata_len, const char* rrstr)
470 {
471 	struct local_data* node;
472 	struct local_rrset* rrset;
473 	struct packed_rrset_data* pd;
474 
475 	if(!lz_find_create_node(z, nm, nmlen, nmlabs, &node)) {
476 		return 0;
477 	}
478 	log_assert(node);
479 
480 	/* Reject it if we would end up having CNAME and other data (including
481 	 * another CNAME) for a redirect zone. */
482 	if((z->type == local_zone_redirect ||
483 		z->type == local_zone_inform_redirect) && node->rrsets) {
484 		const char* othertype = NULL;
485 		if (rrtype == LDNS_RR_TYPE_CNAME)
486 			othertype = "other";
487 		else if (node->rrsets->rrset->rk.type ==
488 			 htons(LDNS_RR_TYPE_CNAME)) {
489 			othertype = "CNAME";
490 		}
491 		if(othertype) {
492 			log_err("local-data '%s' in redirect zone must not "
493 				"coexist with %s local-data", rrstr, othertype);
494 			return 0;
495 		}
496 	}
497 	rrset = local_data_find_type(node, rrtype, 0);
498 	if(!rrset) {
499 		rrset = new_local_rrset(z->region, node, rrtype, rrclass);
500 		if(!rrset)
501 			return 0;
502 		if(query_dname_compare(node->name, z->name) == 0) {
503 			if(rrtype == LDNS_RR_TYPE_NSEC)
504 			  rrset->rrset->rk.flags = PACKED_RRSET_NSEC_AT_APEX;
505 			if(rrtype == LDNS_RR_TYPE_SOA)
506 				z->soa = rrset->rrset;
507 		}
508 	}
509 	pd = (struct packed_rrset_data*)rrset->rrset->entry.data;
510 	log_assert(rrset && pd);
511 
512 	/* check for duplicate RR */
513 	if(rr_is_duplicate(pd, rdata, rdata_len)) {
514 		verbose(VERB_ALGO, "ignoring duplicate RR: %s", rrstr);
515 		return 1;
516 	}
517 	return rrset_insert_rr(z->region, pd, rdata, rdata_len, ttl, rrstr);
518 }
519 
520 /** enter data RR into auth zone */
521 static int
522 lz_enter_rr_into_zone(struct local_zone* z, const char* rrstr)
523 {
524 	uint8_t* nm;
525 	size_t nmlen;
526 	int nmlabs, ret;
527 	uint16_t rrtype = 0, rrclass = 0;
528 	time_t ttl = 0;
529 	uint8_t rr[LDNS_RR_BUF_SIZE];
530 	uint8_t* rdata;
531 	size_t rdata_len;
532 	if(!rrstr_get_rr_content(rrstr, &nm, &rrtype, &rrclass, &ttl, rr,
533 		sizeof(rr), &rdata, &rdata_len)) {
534 		log_err("bad local-data: %s", rrstr);
535 		return 0;
536 	}
537 	log_assert(z->dclass == rrclass);
538 	if((z->type == local_zone_redirect ||
539 		z->type == local_zone_inform_redirect) &&
540 		query_dname_compare(z->name, nm) != 0) {
541 		log_err("local-data in redirect zone must reside at top of zone"
542 			", not at %s", rrstr);
543 		free(nm);
544 		return 0;
545 	}
546 	nmlabs = dname_count_size_labels(nm, &nmlen);
547 	ret = local_zone_enter_rr(z, nm, nmlen, nmlabs, rrtype, rrclass, ttl,
548 		rdata, rdata_len, rrstr);
549 	free(nm);
550 	return ret;
551 }
552 
553 /** enter a data RR into auth data; a zone for it must exist */
554 static int
555 lz_enter_rr_str(struct local_zones* zones, const char* rr)
556 {
557 	uint8_t* rr_name;
558 	uint16_t rr_class, rr_type;
559 	size_t len;
560 	int labs;
561 	struct local_zone* z;
562 	int r;
563 	if(!get_rr_nameclass(rr, &rr_name, &rr_class, &rr_type)) {
564 		log_err("bad rr %s", rr);
565 		return 0;
566 	}
567 	labs = dname_count_size_labels(rr_name, &len);
568 	lock_rw_rdlock(&zones->lock);
569 	z = local_zones_lookup(zones, rr_name, len, labs, rr_class, rr_type);
570 	if(!z) {
571 		lock_rw_unlock(&zones->lock);
572 		fatal_exit("internal error: no zone for rr %s", rr);
573 	}
574 	lock_rw_wrlock(&z->lock);
575 	lock_rw_unlock(&zones->lock);
576 	free(rr_name);
577 	r = lz_enter_rr_into_zone(z, rr);
578 	lock_rw_unlock(&z->lock);
579 	return r;
580 }
581 
582 /** enter tagstring into zone */
583 static int
584 lz_enter_zone_tag(struct local_zones* zones, char* zname, uint8_t* list,
585 	size_t len, uint16_t rr_class)
586 {
587 	uint8_t dname[LDNS_MAX_DOMAINLEN+1];
588 	size_t dname_len = sizeof(dname);
589 	int dname_labs, r = 0;
590 	struct local_zone* z;
591 
592 	if(sldns_str2wire_dname_buf(zname, dname, &dname_len) != 0) {
593 		log_err("cannot parse zone name in local-zone-tag: %s", zname);
594 		return 0;
595 	}
596 	dname_labs = dname_count_labels(dname);
597 
598 	lock_rw_rdlock(&zones->lock);
599 	z = local_zones_find(zones, dname, dname_len, dname_labs, rr_class);
600 	if(!z) {
601 		lock_rw_unlock(&zones->lock);
602 		log_err("no local-zone for tag %s", zname);
603 		return 0;
604 	}
605 	lock_rw_wrlock(&z->lock);
606 	lock_rw_unlock(&zones->lock);
607 	free(z->taglist);
608 	z->taglist = memdup(list, len);
609 	z->taglen = len;
610 	if(z->taglist)
611 		r = 1;
612 	lock_rw_unlock(&z->lock);
613 	return r;
614 }
615 
616 /** enter override into zone */
617 static int
618 lz_enter_override(struct local_zones* zones, char* zname, char* netblock,
619 	char* type, uint16_t rr_class)
620 {
621 	uint8_t dname[LDNS_MAX_DOMAINLEN+1];
622 	size_t dname_len = sizeof(dname);
623 	int dname_labs;
624 	struct sockaddr_storage addr;
625 	int net;
626 	socklen_t addrlen;
627 	struct local_zone* z;
628 	enum localzone_type t;
629 
630 	/* parse zone name */
631 	if(sldns_str2wire_dname_buf(zname, dname, &dname_len) != 0) {
632 		log_err("cannot parse zone name in local-zone-override: %s %s",
633 			zname, netblock);
634 		return 0;
635 	}
636 	dname_labs = dname_count_labels(dname);
637 
638 	/* parse netblock */
639 	if(!netblockstrtoaddr(netblock, UNBOUND_DNS_PORT, &addr, &addrlen,
640 		&net)) {
641 		log_err("cannot parse netblock in local-zone-override: %s %s",
642 			zname, netblock);
643 		return 0;
644 	}
645 
646 	/* parse zone type */
647 	if(!local_zone_str2type(type, &t)) {
648 		log_err("cannot parse type in local-zone-override: %s %s %s",
649 			zname, netblock, type);
650 		return 0;
651 	}
652 
653 	/* find localzone entry */
654 	lock_rw_rdlock(&zones->lock);
655 	z = local_zones_find(zones, dname, dname_len, dname_labs, rr_class);
656 	if(!z) {
657 		lock_rw_unlock(&zones->lock);
658 		log_err("no local-zone for local-zone-override %s", zname);
659 		return 0;
660 	}
661 	lock_rw_wrlock(&z->lock);
662 	lock_rw_unlock(&zones->lock);
663 
664 	/* create netblock addr_tree if not present yet */
665 	if(!z->override_tree) {
666 		z->override_tree = (struct rbtree_type*)regional_alloc_zero(
667 			z->region, sizeof(*z->override_tree));
668 		if(!z->override_tree) {
669 			lock_rw_unlock(&z->lock);
670 			log_err("out of memory");
671 			return 0;
672 		}
673 		addr_tree_init(z->override_tree);
674 	}
675 	/* add new elem to tree */
676 	if(z->override_tree) {
677 		struct local_zone_override* n;
678 		n = (struct local_zone_override*)regional_alloc_zero(
679 			z->region, sizeof(*n));
680 		if(!n) {
681 			lock_rw_unlock(&z->lock);
682 			log_err("out of memory");
683 			return 0;
684 		}
685 		n->type = t;
686 		if(!addr_tree_insert(z->override_tree,
687 			(struct addr_tree_node*)n, &addr, addrlen, net)) {
688 			lock_rw_unlock(&z->lock);
689 			log_err("duplicate local-zone-override %s %s",
690 				zname, netblock);
691 			return 1;
692 		}
693 	}
694 
695 	lock_rw_unlock(&z->lock);
696 	return 1;
697 }
698 
699 /** parse local-zone: statements */
700 static int
701 lz_enter_zones(struct local_zones* zones, struct config_file* cfg)
702 {
703 	struct config_str2list* p;
704 	struct local_zone* z;
705 	for(p = cfg->local_zones; p; p = p->next) {
706 		if(!(z=lz_enter_zone(zones, p->str, p->str2,
707 			LDNS_RR_CLASS_IN)))
708 			return 0;
709 		lock_rw_unlock(&z->lock);
710 	}
711 	return 1;
712 }
713 
714 /** lookup a zone in rbtree; exact match only; SLOW due to parse */
715 static int
716 lz_exists(struct local_zones* zones, const char* name)
717 {
718 	struct local_zone z;
719 	z.node.key = &z;
720 	z.dclass = LDNS_RR_CLASS_IN;
721 	if(!parse_dname(name, &z.name, &z.namelen, &z.namelabs)) {
722 		log_err("bad name %s", name);
723 		return 0;
724 	}
725 	lock_rw_rdlock(&zones->lock);
726 	if(rbtree_search(&zones->ztree, &z.node)) {
727 		lock_rw_unlock(&zones->lock);
728 		free(z.name);
729 		return 1;
730 	}
731 	lock_rw_unlock(&zones->lock);
732 	free(z.name);
733 	return 0;
734 }
735 
736 /** lookup a zone in cfg->nodefault list */
737 static int
738 lz_nodefault(struct config_file* cfg, const char* name)
739 {
740 	struct config_strlist* p;
741 	size_t len = strlen(name);
742 	if(len == 0) return 0;
743 	if(name[len-1] == '.') len--;
744 
745 	for(p = cfg->local_zones_nodefault; p; p = p->next) {
746 		/* compare zone name, lowercase, compare without ending . */
747 		if(strncasecmp(p->str, name, len) == 0 &&
748 			(strlen(p->str) == len || (strlen(p->str)==len+1 &&
749 			p->str[len] == '.')))
750 			return 1;
751 	}
752 	return 0;
753 }
754 
755 /** enter (AS112) empty default zone */
756 static int
757 add_empty_default(struct local_zones* zones, struct config_file* cfg,
758         const char* name)
759 {
760 	struct local_zone* z;
761 	char str[1024]; /* known long enough */
762 	if(lz_exists(zones, name) || lz_nodefault(cfg, name))
763 		return 1; /* do not enter default content */
764 	if(!(z=lz_enter_zone(zones, name, "static", LDNS_RR_CLASS_IN)))
765 		return 0;
766 	snprintf(str, sizeof(str), "%s 10800 IN SOA localhost. "
767 		"nobody.invalid. 1 3600 1200 604800 10800", name);
768 	if(!lz_enter_rr_into_zone(z, str)) {
769 		lock_rw_unlock(&z->lock);
770 		return 0;
771 	}
772 	snprintf(str, sizeof(str), "%s 10800 IN NS localhost. ", name);
773 	if(!lz_enter_rr_into_zone(z, str)) {
774 		lock_rw_unlock(&z->lock);
775 		return 0;
776 	}
777 	lock_rw_unlock(&z->lock);
778 	return 1;
779 }
780 
781 /** enter default zones */
782 int local_zone_enter_defaults(struct local_zones* zones, struct config_file* cfg)
783 {
784 	struct local_zone* z;
785 	const char** zstr;
786 
787 	/* Do not add any default */
788 	if(cfg->local_zones_disable_default)
789 		return 1;
790 
791 	/* this list of zones is from RFC 6303 and RFC 7686 */
792 
793 	/* block localhost level zones first, then onion and later the LAN zones */
794 
795 	/* localhost. zone */
796 	if(!lz_exists(zones, "localhost.") &&
797 		!lz_nodefault(cfg, "localhost.")) {
798 		if(!(z=lz_enter_zone(zones, "localhost.", "redirect",
799 			LDNS_RR_CLASS_IN)) ||
800 		   !lz_enter_rr_into_zone(z,
801 			"localhost. 10800 IN NS localhost.") ||
802 		   !lz_enter_rr_into_zone(z,
803 			"localhost. 10800 IN SOA localhost. nobody.invalid. "
804 			"1 3600 1200 604800 10800") ||
805 		   !lz_enter_rr_into_zone(z,
806 			"localhost. 10800 IN A 127.0.0.1") ||
807 		   !lz_enter_rr_into_zone(z,
808 			"localhost. 10800 IN AAAA ::1")) {
809 			log_err("out of memory adding default zone");
810 			if(z) { lock_rw_unlock(&z->lock); }
811 			return 0;
812 		}
813 		lock_rw_unlock(&z->lock);
814 	}
815 	/* reverse ip4 zone */
816 	if(!lz_exists(zones, "127.in-addr.arpa.") &&
817 		!lz_nodefault(cfg, "127.in-addr.arpa.")) {
818 		if(!(z=lz_enter_zone(zones, "127.in-addr.arpa.", "static",
819 			LDNS_RR_CLASS_IN)) ||
820 		   !lz_enter_rr_into_zone(z,
821 			"127.in-addr.arpa. 10800 IN NS localhost.") ||
822 		   !lz_enter_rr_into_zone(z,
823 			"127.in-addr.arpa. 10800 IN SOA localhost. "
824 			"nobody.invalid. 1 3600 1200 604800 10800") ||
825 		   !lz_enter_rr_into_zone(z,
826 			"1.0.0.127.in-addr.arpa. 10800 IN PTR localhost.")) {
827 			log_err("out of memory adding default zone");
828 			if(z) { lock_rw_unlock(&z->lock); }
829 			return 0;
830 		}
831 		lock_rw_unlock(&z->lock);
832 	}
833 	/* reverse ip6 zone */
834 	if(!lz_exists(zones, "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.") &&
835 		!lz_nodefault(cfg, "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.")) {
836 		if(!(z=lz_enter_zone(zones, "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa.", "static",
837 			LDNS_RR_CLASS_IN)) ||
838 		   !lz_enter_rr_into_zone(z,
839 			"1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. 10800 IN NS localhost.") ||
840 		   !lz_enter_rr_into_zone(z,
841 			"1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. 10800 IN SOA localhost. "
842 			"nobody.invalid. 1 3600 1200 604800 10800") ||
843 		   !lz_enter_rr_into_zone(z,
844 			"1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. 10800 IN PTR localhost.")) {
845 			log_err("out of memory adding default zone");
846 			if(z) { lock_rw_unlock(&z->lock); }
847 			return 0;
848 		}
849 		lock_rw_unlock(&z->lock);
850 	}
851 	/* onion. zone (RFC 7686) */
852 	if(!add_empty_default(zones, cfg, "onion.")) {
853 		log_err("out of memory adding default zone");
854 		return 0;
855 	}
856 	/* test. zone (RFC 6761) */
857 	if(!add_empty_default(zones, cfg, "test.")) {
858 		log_err("out of memory adding default zone");
859 		return 0;
860 	}
861 	/* invalid. zone (RFC 6761) */
862 	if(!add_empty_default(zones, cfg, "invalid.")) {
863 		log_err("out of memory adding default zone");
864 		return 0;
865 	}
866 	/* block AS112 zones, unless asked not to */
867 	if(!cfg->unblock_lan_zones) {
868 		for(zstr = as112_zones; *zstr; zstr++) {
869 			if(!add_empty_default(zones, cfg, *zstr)) {
870 				log_err("out of memory adding default zone");
871 				return 0;
872 			}
873 		}
874 	}
875 	return 1;
876 }
877 
878 /** parse local-zone-override: statements */
879 static int
880 lz_enter_overrides(struct local_zones* zones, struct config_file* cfg)
881 {
882 	struct config_str3list* p;
883 	for(p = cfg->local_zone_overrides; p; p = p->next) {
884 		if(!lz_enter_override(zones, p->str, p->str2, p->str3,
885 			LDNS_RR_CLASS_IN))
886 			return 0;
887 	}
888 	return 1;
889 }
890 
891 /** setup parent pointers, so that a lookup can be done for closest match */
892 static void
893 init_parents(struct local_zones* zones)
894 {
895         struct local_zone* node, *prev = NULL, *p;
896         int m;
897 	lock_rw_wrlock(&zones->lock);
898         RBTREE_FOR(node, struct local_zone*, &zones->ztree) {
899 		lock_rw_wrlock(&node->lock);
900                 node->parent = NULL;
901                 if(!prev || prev->dclass != node->dclass) {
902                         prev = node;
903 			lock_rw_unlock(&node->lock);
904                         continue;
905                 }
906                 (void)dname_lab_cmp(prev->name, prev->namelabs, node->name,
907                         node->namelabs, &m); /* we know prev is smaller */
908                 /* sort order like: . com. bla.com. zwb.com. net. */
909                 /* find the previous, or parent-parent-parent */
910                 for(p = prev; p; p = p->parent)
911                         /* looking for name with few labels, a parent */
912                         if(p->namelabs <= m) {
913                                 /* ==: since prev matched m, this is closest*/
914                                 /* <: prev matches more, but is not a parent,
915                                  * this one is a (grand)parent */
916                                 node->parent = p;
917                                 break;
918                         }
919                 prev = node;
920 
921 		if(node->override_tree)
922 			addr_tree_init_parents(node->override_tree);
923 		lock_rw_unlock(&node->lock);
924         }
925 	lock_rw_unlock(&zones->lock);
926 }
927 
928 /** enter implicit transparent zone for local-data: without local-zone: */
929 static int
930 lz_setup_implicit(struct local_zones* zones, struct config_file* cfg)
931 {
932 	/* walk over all items that have no parent zone and find
933 	 * the name that covers them all (could be the root) and
934 	 * add that as a transparent zone */
935 	struct config_strlist* p;
936 	int have_name = 0;
937 	int have_other_classes = 0;
938 	uint16_t dclass = 0;
939 	uint8_t* nm = 0;
940 	size_t nmlen = 0;
941 	int nmlabs = 0;
942 	int match = 0; /* number of labels match count */
943 
944 	init_parents(zones); /* to enable local_zones_lookup() */
945 	for(p = cfg->local_data; p; p = p->next) {
946 		uint8_t* rr_name;
947 		uint16_t rr_class, rr_type;
948 		size_t len;
949 		int labs;
950 		if(!get_rr_nameclass(p->str, &rr_name, &rr_class, &rr_type)) {
951 			log_err("Bad local-data RR %s", p->str);
952 			return 0;
953 		}
954 		labs = dname_count_size_labels(rr_name, &len);
955 		lock_rw_rdlock(&zones->lock);
956 		if(!local_zones_lookup(zones, rr_name, len, labs, rr_class,
957 			rr_type)) {
958 			if(!have_name) {
959 				dclass = rr_class;
960 				nm = rr_name;
961 				nmlen = len;
962 				nmlabs = labs;
963 				match = labs;
964 				have_name = 1;
965 			} else {
966 				int m;
967 				if(rr_class != dclass) {
968 					/* process other classes later */
969 					free(rr_name);
970 					have_other_classes = 1;
971 					lock_rw_unlock(&zones->lock);
972 					continue;
973 				}
974 				/* find smallest shared topdomain */
975 				(void)dname_lab_cmp(nm, nmlabs,
976 					rr_name, labs, &m);
977 				free(rr_name);
978 				if(m < match)
979 					match = m;
980 			}
981 		} else free(rr_name);
982 		lock_rw_unlock(&zones->lock);
983 	}
984 	if(have_name) {
985 		uint8_t* n2;
986 		struct local_zone* z;
987 		/* allocate zone of smallest shared topdomain to contain em */
988 		n2 = nm;
989 		dname_remove_labels(&n2, &nmlen, nmlabs - match);
990 		n2 = memdup(n2, nmlen);
991 		free(nm);
992 		if(!n2) {
993 			log_err("out of memory");
994 			return 0;
995 		}
996 		log_nametypeclass(VERB_ALGO, "implicit transparent local-zone",
997 			n2, 0, dclass);
998 		if(!(z=lz_enter_zone_dname(zones, n2, nmlen, match,
999 			local_zone_transparent, dclass))) {
1000 			return 0;
1001 		}
1002 		lock_rw_unlock(&z->lock);
1003 	}
1004 	if(have_other_classes) {
1005 		/* restart to setup other class */
1006 		return lz_setup_implicit(zones, cfg);
1007 	}
1008 	return 1;
1009 }
1010 
1011 /** enter local-zone-tag info */
1012 static int
1013 lz_enter_zone_tags(struct local_zones* zones, struct config_file* cfg)
1014 {
1015 	struct config_strbytelist* p;
1016 	int c = 0;
1017 	for(p = cfg->local_zone_tags; p; p = p->next) {
1018 		if(!lz_enter_zone_tag(zones, p->str, p->str2, p->str2len,
1019 			LDNS_RR_CLASS_IN))
1020 			return 0;
1021 		c++;
1022 	}
1023 	if(c) verbose(VERB_ALGO, "applied tags to %d local zones", c);
1024 	return 1;
1025 }
1026 
1027 /** enter auth data */
1028 static int
1029 lz_enter_data(struct local_zones* zones, struct config_file* cfg)
1030 {
1031 	struct config_strlist* p;
1032 	for(p = cfg->local_data; p; p = p->next) {
1033 		if(!lz_enter_rr_str(zones, p->str))
1034 			return 0;
1035 	}
1036 	return 1;
1037 }
1038 
1039 /** free memory from config */
1040 static void
1041 lz_freeup_cfg(struct config_file* cfg)
1042 {
1043 	config_deldblstrlist(cfg->local_zones);
1044 	cfg->local_zones = NULL;
1045 	config_delstrlist(cfg->local_zones_nodefault);
1046 	cfg->local_zones_nodefault = NULL;
1047 	config_delstrlist(cfg->local_data);
1048 	cfg->local_data = NULL;
1049 }
1050 
1051 int
1052 local_zones_apply_cfg(struct local_zones* zones, struct config_file* cfg)
1053 {
1054 	/* create zones from zone statements. */
1055 	if(!lz_enter_zones(zones, cfg)) {
1056 		return 0;
1057 	}
1058 	/* apply default zones+content (unless disabled, or overridden) */
1059 	if(!local_zone_enter_defaults(zones, cfg)) {
1060 		return 0;
1061 	}
1062 	/* enter local zone overrides */
1063 	if(!lz_enter_overrides(zones, cfg)) {
1064 		return 0;
1065 	}
1066 	/* create implicit transparent zone from data. */
1067 	if(!lz_setup_implicit(zones, cfg)) {
1068 		return 0;
1069 	}
1070 
1071 	/* setup parent ptrs for lookup during data entry */
1072 	init_parents(zones);
1073 	/* insert local zone tags */
1074 	if(!lz_enter_zone_tags(zones, cfg)) {
1075 		return 0;
1076 	}
1077 	/* insert local data */
1078 	if(!lz_enter_data(zones, cfg)) {
1079 		return 0;
1080 	}
1081 	/* freeup memory from cfg struct. */
1082 	lz_freeup_cfg(cfg);
1083 	return 1;
1084 }
1085 
1086 struct local_zone*
1087 local_zones_lookup(struct local_zones* zones,
1088         uint8_t* name, size_t len, int labs, uint16_t dclass, uint16_t dtype)
1089 {
1090 	return local_zones_tags_lookup(zones, name, len, labs,
1091 		dclass, dtype, NULL, 0, 1);
1092 }
1093 
1094 struct local_zone*
1095 local_zones_tags_lookup(struct local_zones* zones,
1096         uint8_t* name, size_t len, int labs, uint16_t dclass, uint16_t dtype,
1097 	uint8_t* taglist, size_t taglen, int ignoretags)
1098 {
1099 	rbnode_type* res = NULL;
1100 	struct local_zone *result;
1101 	struct local_zone key;
1102 	int m;
1103 	/* for type DS use a zone higher when on a zonecut */
1104 	if(dtype == LDNS_RR_TYPE_DS && !dname_is_root(name)) {
1105 		dname_remove_label(&name, &len);
1106 		labs--;
1107 	}
1108 	key.node.key = &key;
1109 	key.dclass = dclass;
1110 	key.name = name;
1111 	key.namelen = len;
1112 	key.namelabs = labs;
1113 	rbtree_find_less_equal(&zones->ztree, &key, &res);
1114 	result = (struct local_zone*)res;
1115 	/* exact or smaller element (or no element) */
1116 	if(!result || result->dclass != dclass)
1117 		return NULL;
1118 	/* count number of labels matched */
1119 	(void)dname_lab_cmp(result->name, result->namelabs, key.name,
1120 		key.namelabs, &m);
1121 	while(result) { /* go up until qname is zone or subdomain of zone */
1122 		if(result->namelabs <= m)
1123 			if(ignoretags || !result->taglist ||
1124 				taglist_intersect(result->taglist,
1125 				result->taglen, taglist, taglen))
1126 				break;
1127 		result = result->parent;
1128 	}
1129 	return result;
1130 }
1131 
1132 struct local_zone*
1133 local_zones_find(struct local_zones* zones,
1134         uint8_t* name, size_t len, int labs, uint16_t dclass)
1135 {
1136 	struct local_zone key;
1137 	key.node.key = &key;
1138 	key.dclass = dclass;
1139 	key.name = name;
1140 	key.namelen = len;
1141 	key.namelabs = labs;
1142 	/* exact */
1143 	return (struct local_zone*)rbtree_search(&zones->ztree, &key);
1144 }
1145 
1146 struct local_zone*
1147 local_zones_find_le(struct local_zones* zones,
1148         uint8_t* name, size_t len, int labs, uint16_t dclass,
1149 	int* exact)
1150 {
1151 	struct local_zone key;
1152 	rbnode_type *node;
1153 	key.node.key = &key;
1154 	key.dclass = dclass;
1155 	key.name = name;
1156 	key.namelen = len;
1157 	key.namelabs = labs;
1158 	*exact = rbtree_find_less_equal(&zones->ztree, &key, &node);
1159 	return (struct local_zone*)node;
1160 }
1161 
1162 /** print all RRsets in local zone */
1163 static void
1164 local_zone_out(struct local_zone* z)
1165 {
1166 	struct local_data* d;
1167 	struct local_rrset* p;
1168 	RBTREE_FOR(d, struct local_data*, &z->data) {
1169 		for(p = d->rrsets; p; p = p->next) {
1170 			log_nametypeclass(NO_VERBOSE, "rrset", d->name,
1171 				ntohs(p->rrset->rk.type),
1172 				ntohs(p->rrset->rk.rrset_class));
1173 		}
1174 	}
1175 }
1176 
1177 void local_zones_print(struct local_zones* zones)
1178 {
1179 	struct local_zone* z;
1180 	lock_rw_rdlock(&zones->lock);
1181 	log_info("number of auth zones %u", (unsigned)zones->ztree.count);
1182 	RBTREE_FOR(z, struct local_zone*, &zones->ztree) {
1183 		char buf[64];
1184 		lock_rw_rdlock(&z->lock);
1185 		snprintf(buf, sizeof(buf), "%s zone",
1186 			local_zone_type2str(z->type));
1187 		log_nametypeclass(NO_VERBOSE, buf, z->name, 0, z->dclass);
1188 		local_zone_out(z);
1189 		lock_rw_unlock(&z->lock);
1190 	}
1191 	lock_rw_unlock(&zones->lock);
1192 }
1193 
1194 /** encode answer consisting of 1 rrset */
1195 static int
1196 local_encode(struct query_info* qinfo, struct module_env* env,
1197 	struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
1198 	struct regional* temp, struct ub_packed_rrset_key* rrset, int ansec,
1199 	int rcode)
1200 {
1201 	struct reply_info rep;
1202 	uint16_t udpsize;
1203 	/* make answer with time=0 for fixed TTL values */
1204 	memset(&rep, 0, sizeof(rep));
1205 	rep.flags = (uint16_t)((BIT_QR | BIT_AA | BIT_RA) | rcode);
1206 	rep.qdcount = 1;
1207 	if(ansec)
1208 		rep.an_numrrsets = 1;
1209 	else	rep.ns_numrrsets = 1;
1210 	rep.rrset_count = 1;
1211 	rep.rrsets = &rrset;
1212 	udpsize = edns->udp_size;
1213 	edns->edns_version = EDNS_ADVERTISED_VERSION;
1214 	edns->udp_size = EDNS_ADVERTISED_SIZE;
1215 	edns->ext_rcode = 0;
1216 	edns->bits &= EDNS_DO;
1217 	if(!inplace_cb_reply_local_call(env, qinfo, NULL, &rep, rcode, edns,
1218 		repinfo, temp) || !reply_info_answer_encode(qinfo, &rep,
1219 		*(uint16_t*)sldns_buffer_begin(buf), sldns_buffer_read_u16_at(buf, 2),
1220 		buf, 0, 0, temp, udpsize, edns, (int)(edns->bits&EDNS_DO), 0)) {
1221 		error_encode(buf, (LDNS_RCODE_SERVFAIL|BIT_AA), qinfo,
1222 			*(uint16_t*)sldns_buffer_begin(buf),
1223 			sldns_buffer_read_u16_at(buf, 2), edns);
1224 	}
1225 	return 1;
1226 }
1227 
1228 /** encode local error answer */
1229 static void
1230 local_error_encode(struct query_info* qinfo, struct module_env* env,
1231 	struct edns_data* edns, struct comm_reply* repinfo, sldns_buffer* buf,
1232 	struct regional* temp, int rcode, int r)
1233 {
1234 	edns->edns_version = EDNS_ADVERTISED_VERSION;
1235 	edns->udp_size = EDNS_ADVERTISED_SIZE;
1236 	edns->ext_rcode = 0;
1237 	edns->bits &= EDNS_DO;
1238 
1239 	if(!inplace_cb_reply_local_call(env, qinfo, NULL, NULL,
1240 		rcode, edns, repinfo, temp))
1241 		edns->opt_list = NULL;
1242 	error_encode(buf, r, qinfo, *(uint16_t*)sldns_buffer_begin(buf),
1243 		sldns_buffer_read_u16_at(buf, 2), edns);
1244 }
1245 
1246 /** find local data tag string match for the given type in the list */
1247 int
1248 local_data_find_tag_datas(const struct query_info* qinfo,
1249 	struct config_strlist* list, struct ub_packed_rrset_key* r,
1250 	struct regional* temp)
1251 {
1252 	struct config_strlist* p;
1253 	char buf[65536];
1254 	uint8_t rr[LDNS_RR_BUF_SIZE];
1255 	size_t len;
1256 	int res;
1257 	struct packed_rrset_data* d;
1258 	for(p=list; p; p=p->next) {
1259 		uint16_t rdr_type;
1260 
1261 		len = sizeof(rr);
1262 		/* does this element match the type? */
1263 		snprintf(buf, sizeof(buf), ". %s", p->str);
1264 		res = sldns_str2wire_rr_buf(buf, rr, &len, NULL, 3600,
1265 			NULL, 0, NULL, 0);
1266 		if(res != 0)
1267 			/* parse errors are already checked before, in
1268 			 * acllist check_data, skip this for robustness */
1269 			continue;
1270 		if(len < 1 /* . */ + 8 /* typeclassttl*/ + 2 /*rdatalen*/)
1271 			continue;
1272 		rdr_type = sldns_wirerr_get_type(rr, len, 1);
1273 		if(rdr_type != qinfo->qtype && rdr_type != LDNS_RR_TYPE_CNAME)
1274 			continue;
1275 
1276 		/* do we have entries already? if not setup key */
1277 		if(r->rk.dname == NULL) {
1278 			r->entry.key = r;
1279 			r->rk.dname = qinfo->qname;
1280 			r->rk.dname_len = qinfo->qname_len;
1281 			r->rk.type = htons(rdr_type);
1282 			r->rk.rrset_class = htons(qinfo->qclass);
1283 			r->rk.flags = 0;
1284 			d = (struct packed_rrset_data*)regional_alloc_zero(
1285 				temp, sizeof(struct packed_rrset_data)
1286 				+ sizeof(size_t) + sizeof(uint8_t*) +
1287 				sizeof(time_t));
1288 			if(!d) return 0; /* out of memory */
1289 			r->entry.data = d;
1290 			d->ttl = sldns_wirerr_get_ttl(rr, len, 1);
1291 			d->rr_len = (size_t*)((uint8_t*)d +
1292 				sizeof(struct packed_rrset_data));
1293 			d->rr_data = (uint8_t**)&(d->rr_len[1]);
1294 			d->rr_ttl = (time_t*)&(d->rr_data[1]);
1295 		}
1296 		d = (struct packed_rrset_data*)r->entry.data;
1297 		/* add entry to the data */
1298 		if(d->count != 0) {
1299 			size_t* oldlen = d->rr_len;
1300 			uint8_t** olddata = d->rr_data;
1301 			time_t* oldttl = d->rr_ttl;
1302 			/* increase arrays for lookup */
1303 			/* this is of course slow for very many records,
1304 			 * but most redirects are expected with few records */
1305 			d->rr_len = (size_t*)regional_alloc_zero(temp,
1306 				(d->count+1)*sizeof(size_t));
1307 			d->rr_data = (uint8_t**)regional_alloc_zero(temp,
1308 				(d->count+1)*sizeof(uint8_t*));
1309 			d->rr_ttl = (time_t*)regional_alloc_zero(temp,
1310 				(d->count+1)*sizeof(time_t));
1311 			if(!d->rr_len || !d->rr_data || !d->rr_ttl)
1312 				return 0; /* out of memory */
1313 			/* first one was allocated after struct d, but new
1314 			 * ones get their own array increment alloc, so
1315 			 * copy old content */
1316 			memmove(d->rr_len, oldlen, d->count*sizeof(size_t));
1317 			memmove(d->rr_data, olddata, d->count*sizeof(uint8_t*));
1318 			memmove(d->rr_ttl, oldttl, d->count*sizeof(time_t));
1319 		}
1320 
1321 		d->rr_len[d->count] = sldns_wirerr_get_rdatalen(rr, len, 1)+2;
1322 		d->rr_ttl[d->count] = sldns_wirerr_get_ttl(rr, len, 1);
1323 		d->rr_data[d->count] = regional_alloc_init(temp,
1324 			sldns_wirerr_get_rdatawl(rr, len, 1),
1325 			d->rr_len[d->count]);
1326 		if(!d->rr_data[d->count])
1327 			return 0; /* out of memory */
1328 		d->count++;
1329 	}
1330 	if(r->rk.dname)
1331 		return 1;
1332 	return 0;
1333 }
1334 
1335 static int
1336 find_tag_datas(struct query_info* qinfo, struct config_strlist* list,
1337 	struct ub_packed_rrset_key* r, struct regional* temp)
1338 {
1339 	int result = local_data_find_tag_datas(qinfo, list, r, temp);
1340 
1341 	/* If we've found a non-exact alias type of local data, make a shallow
1342 	 * copy of the RRset and remember it in qinfo to complete the alias
1343 	 * chain later. */
1344 	if(result && qinfo->qtype != LDNS_RR_TYPE_CNAME &&
1345 		r->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
1346 		qinfo->local_alias =
1347 			regional_alloc_zero(temp, sizeof(struct local_rrset));
1348 		if(!qinfo->local_alias)
1349 			return 0; /* out of memory */
1350 		qinfo->local_alias->rrset =
1351 			regional_alloc_init(temp, r, sizeof(*r));
1352 		if(!qinfo->local_alias->rrset)
1353 			return 0; /* out of memory */
1354 	}
1355 	return result;
1356 }
1357 
1358 int
1359 local_data_answer(struct local_zone* z, struct module_env* env,
1360 	struct query_info* qinfo, struct edns_data* edns,
1361 	struct comm_reply* repinfo, sldns_buffer* buf,
1362 	struct regional* temp, int labs, struct local_data** ldp,
1363 	enum localzone_type lz_type, int tag, struct config_strlist** tag_datas,
1364 	size_t tag_datas_size, char** tagname, int num_tags)
1365 {
1366 	struct local_data key;
1367 	struct local_data* ld;
1368 	struct local_rrset* lr;
1369 	key.node.key = &key;
1370 	key.name = qinfo->qname;
1371 	key.namelen = qinfo->qname_len;
1372 	key.namelabs = labs;
1373 	if(lz_type == local_zone_redirect ||
1374 		lz_type == local_zone_inform_redirect) {
1375 		key.name = z->name;
1376 		key.namelen = z->namelen;
1377 		key.namelabs = z->namelabs;
1378 		if(tag != -1 && (size_t)tag<tag_datas_size && tag_datas[tag]) {
1379 			struct ub_packed_rrset_key r;
1380 			memset(&r, 0, sizeof(r));
1381 			if(find_tag_datas(qinfo, tag_datas[tag], &r, temp)) {
1382 				verbose(VERB_ALGO, "redirect with tag data [%d] %s",
1383 					tag, (tag<num_tags?tagname[tag]:"null"));
1384 
1385 				/* If we found a matching alias, we should
1386 				 * use it as part of the answer, but we can't
1387 				 * encode it until we complete the alias
1388 				 * chain. */
1389 				if(qinfo->local_alias)
1390 					return 1;
1391 				return local_encode(qinfo, env, edns, repinfo, buf, temp,
1392 					&r, 1, LDNS_RCODE_NOERROR);
1393 			}
1394 		}
1395 	}
1396 	ld = (struct local_data*)rbtree_search(&z->data, &key.node);
1397 	*ldp = ld;
1398 	if(!ld) {
1399 		return 0;
1400 	}
1401 	lr = local_data_find_type(ld, qinfo->qtype, 1);
1402 	if(!lr)
1403 		return 0;
1404 
1405 	/* Special case for alias matching.  See local_data_answer(). */
1406 	if((lz_type == local_zone_redirect ||
1407 		lz_type == local_zone_inform_redirect) &&
1408 		qinfo->qtype != LDNS_RR_TYPE_CNAME &&
1409 		lr->rrset->rk.type == htons(LDNS_RR_TYPE_CNAME)) {
1410 		uint8_t* ctarget;
1411 		size_t ctargetlen = 0;
1412 
1413 		qinfo->local_alias =
1414 			regional_alloc_zero(temp, sizeof(struct local_rrset));
1415 		if(!qinfo->local_alias)
1416 			return 0; /* out of memory */
1417 		qinfo->local_alias->rrset = regional_alloc_init(
1418 			temp, lr->rrset, sizeof(*lr->rrset));
1419 		if(!qinfo->local_alias->rrset)
1420 			return 0; /* out of memory */
1421 		qinfo->local_alias->rrset->rk.dname = qinfo->qname;
1422 		qinfo->local_alias->rrset->rk.dname_len = qinfo->qname_len;
1423 		get_cname_target(lr->rrset, &ctarget, &ctargetlen);
1424 		if(!ctargetlen)
1425 			return 0; /* invalid cname */
1426 		if(dname_is_wild(ctarget)) {
1427 			/* synthesize cname target */
1428 			struct packed_rrset_data* d;
1429 			/* -3 for wildcard label and root label from qname */
1430 			size_t newtargetlen = qinfo->qname_len + ctargetlen - 3;
1431 
1432 			log_assert(ctargetlen >= 3);
1433 			log_assert(qinfo->qname_len >= 1);
1434 
1435 			if(newtargetlen > LDNS_MAX_DOMAINLEN) {
1436 				qinfo->local_alias = NULL;
1437 				local_error_encode(qinfo, env, edns, repinfo,
1438 					buf, temp, LDNS_RCODE_YXDOMAIN,
1439 					(LDNS_RCODE_YXDOMAIN|BIT_AA));
1440 				return 1;
1441 			}
1442 			memset(&qinfo->local_alias->rrset->entry, 0,
1443 				sizeof(qinfo->local_alias->rrset->entry));
1444 			qinfo->local_alias->rrset->entry.key =
1445 				qinfo->local_alias->rrset;
1446 			qinfo->local_alias->rrset->entry.hash =
1447 				rrset_key_hash(&qinfo->local_alias->rrset->rk);
1448 			d = (struct packed_rrset_data*)regional_alloc_zero(temp,
1449 				sizeof(struct packed_rrset_data) + sizeof(size_t) +
1450 				sizeof(uint8_t*) + sizeof(time_t) + sizeof(uint16_t)
1451 				+ newtargetlen);
1452 			if(!d)
1453 				return 0; /* out of memory */
1454 			qinfo->local_alias->rrset->entry.data = d;
1455 			d->ttl = 0; /* 0 for synthesized CNAME TTL */
1456 			d->count = 1;
1457 			d->rrsig_count = 0;
1458 			d->trust = rrset_trust_ans_noAA;
1459 			d->rr_len = (size_t*)((uint8_t*)d +
1460 				sizeof(struct packed_rrset_data));
1461 			d->rr_len[0] = newtargetlen + sizeof(uint16_t);
1462 			packed_rrset_ptr_fixup(d);
1463 			d->rr_ttl[0] = d->ttl;
1464 			sldns_write_uint16(d->rr_data[0], newtargetlen);
1465 			/* write qname */
1466 			memmove(d->rr_data[0] + sizeof(uint16_t), qinfo->qname,
1467 				qinfo->qname_len - 1);
1468 			/* write cname target wilcard wildcard label */
1469 			memmove(d->rr_data[0] + sizeof(uint16_t) +
1470 				qinfo->qname_len - 1, ctarget + 2,
1471 				ctargetlen - 2);
1472 		}
1473 		return 1;
1474 	}
1475 	if(lz_type == local_zone_redirect ||
1476 		lz_type == local_zone_inform_redirect) {
1477 		/* convert rrset name to query name; like a wildcard */
1478 		struct ub_packed_rrset_key r = *lr->rrset;
1479 		r.rk.dname = qinfo->qname;
1480 		r.rk.dname_len = qinfo->qname_len;
1481 		return local_encode(qinfo, env, edns, repinfo, buf, temp, &r, 1,
1482 			LDNS_RCODE_NOERROR);
1483 	}
1484 	return local_encode(qinfo, env, edns, repinfo, buf, temp, lr->rrset, 1,
1485 		LDNS_RCODE_NOERROR);
1486 }
1487 
1488 /**
1489  * See if the local zone does not cover the name, eg. the name is not
1490  * in the zone and the zone is transparent */
1491 static int
1492 local_zone_does_not_cover(struct local_zone* z, struct query_info* qinfo,
1493 	int labs)
1494 {
1495 	struct local_data key;
1496 	struct local_data* ld = NULL;
1497 	struct local_rrset* lr = NULL;
1498 	if(z->type == local_zone_always_transparent)
1499 		return 1;
1500 	if(z->type != local_zone_transparent
1501 		&& z->type != local_zone_typetransparent
1502 		&& z->type != local_zone_inform)
1503 		return 0;
1504 	key.node.key = &key;
1505 	key.name = qinfo->qname;
1506 	key.namelen = qinfo->qname_len;
1507 	key.namelabs = labs;
1508 	ld = (struct local_data*)rbtree_search(&z->data, &key.node);
1509 	if(z->type == local_zone_transparent || z->type == local_zone_inform)
1510 		return (ld == NULL);
1511 	if(ld)
1512 		lr = local_data_find_type(ld, qinfo->qtype, 1);
1513 	/* local_zone_typetransparent */
1514 	return (lr == NULL);
1515 }
1516 
1517 int
1518 local_zones_zone_answer(struct local_zone* z, struct module_env* env,
1519 	struct query_info* qinfo, struct edns_data* edns,
1520 	struct comm_reply* repinfo, sldns_buffer* buf, struct regional* temp,
1521 	struct local_data* ld, enum localzone_type lz_type)
1522 {
1523 	if(lz_type == local_zone_deny ||
1524 		lz_type == local_zone_always_deny ||
1525 		lz_type == local_zone_inform_deny) {
1526 		/** no reply at all, signal caller by clearing buffer. */
1527 		sldns_buffer_clear(buf);
1528 		sldns_buffer_flip(buf);
1529 		return 1;
1530 	} else if(lz_type == local_zone_refuse
1531 		|| lz_type == local_zone_always_refuse) {
1532 		local_error_encode(qinfo, env, edns, repinfo, buf, temp,
1533 			LDNS_RCODE_REFUSED, (LDNS_RCODE_REFUSED|BIT_AA));
1534 		return 1;
1535 	} else if(lz_type == local_zone_static ||
1536 		lz_type == local_zone_redirect ||
1537 		lz_type == local_zone_inform_redirect ||
1538 		lz_type == local_zone_always_nxdomain ||
1539 		lz_type == local_zone_always_nodata) {
1540 		/* for static, reply nodata or nxdomain
1541 		 * for redirect, reply nodata */
1542 		/* no additional section processing,
1543 		 * cname, dname or wildcard processing,
1544 		 * or using closest match for NSEC.
1545 		 * or using closest match for returning delegation downwards
1546 		 */
1547 		int rcode = (ld || lz_type == local_zone_redirect ||
1548 			lz_type == local_zone_inform_redirect ||
1549 			lz_type == local_zone_always_nodata)?
1550 			LDNS_RCODE_NOERROR:LDNS_RCODE_NXDOMAIN;
1551 		if(z->soa)
1552 			return local_encode(qinfo, env, edns, repinfo, buf, temp,
1553 				z->soa, 0, rcode);
1554 		local_error_encode(qinfo, env, edns, repinfo, buf, temp, rcode,
1555 			(rcode|BIT_AA));
1556 		return 1;
1557 	} else if(lz_type == local_zone_typetransparent
1558 		|| lz_type == local_zone_always_transparent) {
1559 		/* no NODATA or NXDOMAINS for this zone type */
1560 		return 0;
1561 	}
1562 	/* else lz_type == local_zone_transparent */
1563 
1564 	/* if the zone is transparent and the name exists, but the type
1565 	 * does not, then we should make this noerror/nodata */
1566 	if(ld && ld->rrsets) {
1567 		int rcode = LDNS_RCODE_NOERROR;
1568 		if(z->soa)
1569 			return local_encode(qinfo, env, edns, repinfo, buf, temp,
1570 				z->soa, 0, rcode);
1571 		local_error_encode(qinfo, env, edns, repinfo, buf, temp, rcode,
1572 			(rcode|BIT_AA));
1573 		return 1;
1574 	}
1575 
1576 	/* stop here, and resolve further on */
1577 	return 0;
1578 }
1579 
1580 /** print log information for an inform zone query */
1581 static void
1582 lz_inform_print(struct local_zone* z, struct query_info* qinfo,
1583 	struct comm_reply* repinfo)
1584 {
1585 	char ip[128], txt[512];
1586 	char zname[LDNS_MAX_DOMAINLEN+1];
1587 	uint16_t port = ntohs(((struct sockaddr_in*)&repinfo->addr)->sin_port);
1588 	dname_str(z->name, zname);
1589 	addr_to_str(&repinfo->addr, repinfo->addrlen, ip, sizeof(ip));
1590 	snprintf(txt, sizeof(txt), "%s %s %s@%u", zname, local_zone_type2str(z->type), ip,
1591 		(unsigned)port);
1592 	log_nametypeclass(NO_VERBOSE, txt, qinfo->qname, qinfo->qtype, qinfo->qclass);
1593 }
1594 
1595 static enum localzone_type
1596 lz_type(uint8_t *taglist, size_t taglen, uint8_t *taglist2, size_t taglen2,
1597 	uint8_t *tagactions, size_t tagactionssize, enum localzone_type lzt,
1598 	struct comm_reply* repinfo, struct rbtree_type* override_tree,
1599 	int* tag, char** tagname, int num_tags)
1600 {
1601 	struct local_zone_override* lzo;
1602 	if(repinfo && override_tree) {
1603 		lzo = (struct local_zone_override*)addr_tree_lookup(
1604 			override_tree, &repinfo->addr, repinfo->addrlen);
1605 		if(lzo && lzo->type) {
1606 			verbose(VERB_ALGO, "local zone override to type %s",
1607 				local_zone_type2str(lzo->type));
1608 			return lzo->type;
1609 		}
1610 	}
1611 	if(!taglist || !taglist2)
1612 		return lzt;
1613 	return local_data_find_tag_action(taglist, taglen, taglist2, taglen2,
1614 		tagactions, tagactionssize, lzt, tag, tagname, num_tags);
1615 }
1616 
1617 enum localzone_type
1618 local_data_find_tag_action(const uint8_t* taglist, size_t taglen,
1619 	const uint8_t* taglist2, size_t taglen2, const uint8_t* tagactions,
1620 	size_t tagactionssize, enum localzone_type lzt, int* tag,
1621 	char* const* tagname, int num_tags)
1622 {
1623 	size_t i, j;
1624 	uint8_t tagmatch;
1625 
1626 	for(i=0; i<taglen && i<taglen2; i++) {
1627 		tagmatch = (taglist[i] & taglist2[i]);
1628 		for(j=0; j<8 && tagmatch>0; j++) {
1629 			if((tagmatch & 0x1)) {
1630 				*tag = (int)(i*8+j);
1631 				verbose(VERB_ALGO, "matched tag [%d] %s",
1632 					*tag, (*tag<num_tags?tagname[*tag]:"null"));
1633 				/* does this tag have a tag action? */
1634 				if(i*8+j < tagactionssize && tagactions
1635 				   && tagactions[i*8+j] != 0) {
1636 				  verbose(VERB_ALGO, "tag action [%d] %s to type %s",
1637 					*tag, (*tag<num_tags?tagname[*tag]:"null"),
1638 				  	local_zone_type2str(
1639 					(enum localzone_type)
1640 					tagactions[i*8+j]));
1641 				  return (enum localzone_type)tagactions[i*8+j];
1642 				}
1643 				return lzt;
1644 			}
1645 			tagmatch >>= 1;
1646 		}
1647 	}
1648 	return lzt;
1649 }
1650 
1651 int
1652 local_zones_answer(struct local_zones* zones, struct module_env* env,
1653 	struct query_info* qinfo, struct edns_data* edns, sldns_buffer* buf,
1654 	struct regional* temp, struct comm_reply* repinfo, uint8_t* taglist,
1655 	size_t taglen, uint8_t* tagactions, size_t tagactionssize,
1656 	struct config_strlist** tag_datas, size_t tag_datas_size,
1657 	char** tagname, int num_tags, struct view* view)
1658 {
1659 	/* see if query is covered by a zone,
1660 	 * 	if so:	- try to match (exact) local data
1661 	 * 		- look at zone type for negative response. */
1662 	int labs = dname_count_labels(qinfo->qname);
1663 	struct local_data* ld = NULL;
1664 	struct local_zone* z = NULL;
1665 	enum localzone_type lzt = local_zone_transparent;
1666 	int r, tag = -1;
1667 
1668 	if(view) {
1669 		lock_rw_rdlock(&view->lock);
1670 		if(view->local_zones &&
1671 			(z = local_zones_lookup(view->local_zones,
1672 			qinfo->qname, qinfo->qname_len, labs,
1673 			qinfo->qclass, qinfo->qtype))) {
1674 			lock_rw_rdlock(&z->lock);
1675 			lzt = z->type;
1676 		}
1677 		if(lzt == local_zone_noview) {
1678 			lock_rw_unlock(&z->lock);
1679 			z = NULL;
1680 		}
1681 		if(z && (lzt == local_zone_transparent ||
1682 			lzt == local_zone_typetransparent ||
1683 			lzt == local_zone_inform ||
1684 			lzt == local_zone_always_transparent) &&
1685 			local_zone_does_not_cover(z, qinfo, labs)) {
1686 			lock_rw_unlock(&z->lock);
1687 			z = NULL;
1688 		}
1689 		if(view->local_zones && !z && !view->isfirst){
1690 			lock_rw_unlock(&view->lock);
1691 			return 0;
1692 		}
1693 		if(z && verbosity >= VERB_ALGO) {
1694 			char zname[255+1];
1695 			dname_str(z->name, zname);
1696 			verbose(VERB_ALGO, "using localzone %s %s from view %s",
1697 				zname, local_zone_type2str(lzt), view->name);
1698 		}
1699 		lock_rw_unlock(&view->lock);
1700 	}
1701 	if(!z) {
1702 		/* try global local_zones tree */
1703 		lock_rw_rdlock(&zones->lock);
1704 		if(!(z = local_zones_tags_lookup(zones, qinfo->qname,
1705 			qinfo->qname_len, labs, qinfo->qclass, qinfo->qtype,
1706 			taglist, taglen, 0))) {
1707 			lock_rw_unlock(&zones->lock);
1708 			return 0;
1709 		}
1710 		lock_rw_rdlock(&z->lock);
1711 		lzt = lz_type(taglist, taglen, z->taglist, z->taglen,
1712 			tagactions, tagactionssize, z->type, repinfo,
1713 			z->override_tree, &tag, tagname, num_tags);
1714 		lock_rw_unlock(&zones->lock);
1715 		if(z && verbosity >= VERB_ALGO) {
1716 			char zname[255+1];
1717 			dname_str(z->name, zname);
1718 			verbose(VERB_ALGO, "using localzone %s %s", zname,
1719 				local_zone_type2str(lzt));
1720 		}
1721 	}
1722 	if((env->cfg->log_local_actions ||
1723 			lzt == local_zone_inform ||
1724 			lzt == local_zone_inform_deny ||
1725 			lzt == local_zone_inform_redirect)
1726 			&& repinfo)
1727 		lz_inform_print(z, qinfo, repinfo);
1728 
1729 	if(lzt != local_zone_always_refuse
1730 		&& lzt != local_zone_always_transparent
1731 		&& lzt != local_zone_always_nxdomain
1732 		&& lzt != local_zone_always_nodata
1733 		&& lzt != local_zone_always_deny
1734 		&& local_data_answer(z, env, qinfo, edns, repinfo, buf, temp, labs,
1735 			&ld, lzt, tag, tag_datas, tag_datas_size, tagname, num_tags)) {
1736 		lock_rw_unlock(&z->lock);
1737 		/* We should tell the caller that encode is deferred if we found
1738 		 * a local alias. */
1739 		return !qinfo->local_alias;
1740 	}
1741 	r = local_zones_zone_answer(z, env, qinfo, edns, repinfo, buf, temp, ld, lzt);
1742 	lock_rw_unlock(&z->lock);
1743 	return r && !qinfo->local_alias; /* see above */
1744 }
1745 
1746 const char* local_zone_type2str(enum localzone_type t)
1747 {
1748 	switch(t) {
1749 		case local_zone_unset: return "unset";
1750 		case local_zone_deny: return "deny";
1751 		case local_zone_refuse: return "refuse";
1752 		case local_zone_redirect: return "redirect";
1753 		case local_zone_transparent: return "transparent";
1754 		case local_zone_typetransparent: return "typetransparent";
1755 		case local_zone_static: return "static";
1756 		case local_zone_nodefault: return "nodefault";
1757 		case local_zone_inform: return "inform";
1758 		case local_zone_inform_deny: return "inform_deny";
1759 		case local_zone_inform_redirect: return "inform_redirect";
1760 		case local_zone_always_transparent: return "always_transparent";
1761 		case local_zone_always_refuse: return "always_refuse";
1762 		case local_zone_always_nxdomain: return "always_nxdomain";
1763 		case local_zone_always_nodata: return "always_nodata";
1764 		case local_zone_always_deny: return "always_deny";
1765 		case local_zone_noview: return "noview";
1766 		case local_zone_invalid: return "invalid";
1767 	}
1768 	return "badtyped";
1769 }
1770 
1771 int local_zone_str2type(const char* type, enum localzone_type* t)
1772 {
1773 	if(strcmp(type, "deny") == 0)
1774 		*t = local_zone_deny;
1775 	else if(strcmp(type, "refuse") == 0)
1776 		*t = local_zone_refuse;
1777 	else if(strcmp(type, "static") == 0)
1778 		*t = local_zone_static;
1779 	else if(strcmp(type, "transparent") == 0)
1780 		*t = local_zone_transparent;
1781 	else if(strcmp(type, "typetransparent") == 0)
1782 		*t = local_zone_typetransparent;
1783 	else if(strcmp(type, "redirect") == 0)
1784 		*t = local_zone_redirect;
1785 	else if(strcmp(type, "inform") == 0)
1786 		*t = local_zone_inform;
1787 	else if(strcmp(type, "inform_deny") == 0)
1788 		*t = local_zone_inform_deny;
1789 	else if(strcmp(type, "inform_redirect") == 0)
1790 		*t = local_zone_inform_redirect;
1791 	else if(strcmp(type, "always_transparent") == 0)
1792 		*t = local_zone_always_transparent;
1793 	else if(strcmp(type, "always_refuse") == 0)
1794 		*t = local_zone_always_refuse;
1795 	else if(strcmp(type, "always_nxdomain") == 0)
1796 		*t = local_zone_always_nxdomain;
1797 	else if(strcmp(type, "always_nodata") == 0)
1798 		*t = local_zone_always_nodata;
1799 	else if(strcmp(type, "always_deny") == 0)
1800 		*t = local_zone_always_deny;
1801 	else if(strcmp(type, "noview") == 0)
1802 		*t = local_zone_noview;
1803 	else if(strcmp(type, "nodefault") == 0)
1804 		*t = local_zone_nodefault;
1805 	else return 0;
1806 	return 1;
1807 }
1808 
1809 /** iterate over the kiddies of the given name and set their parent ptr */
1810 static void
1811 set_kiddo_parents(struct local_zone* z, struct local_zone* match,
1812 	struct local_zone* newp)
1813 {
1814 	/* both zones and z are locked already */
1815 	/* in the sorted rbtree, the kiddies of z are located after z */
1816 	/* z must be present in the tree */
1817 	struct local_zone* p = z;
1818 	p = (struct local_zone*)rbtree_next(&p->node);
1819 	while(p!=(struct local_zone*)RBTREE_NULL &&
1820 		p->dclass == z->dclass && dname_strict_subdomain(p->name,
1821 		p->namelabs, z->name, z->namelabs)) {
1822 		/* update parent ptr */
1823 		/* only when matches with existing parent pointer, so that
1824 		 * deeper child structures are not touched, i.e.
1825 		 * update of x, and a.x, b.x, f.b.x, g.b.x, c.x, y
1826 		 * gets to update a.x, b.x and c.x */
1827 		lock_rw_wrlock(&p->lock);
1828 		if(p->parent == match)
1829 			p->parent = newp;
1830 		lock_rw_unlock(&p->lock);
1831 		p = (struct local_zone*)rbtree_next(&p->node);
1832 	}
1833 }
1834 
1835 struct local_zone* local_zones_add_zone(struct local_zones* zones,
1836 	uint8_t* name, size_t len, int labs, uint16_t dclass,
1837 	enum localzone_type tp)
1838 {
1839 	/* create */
1840 	struct local_zone* z = local_zone_create(name, len, labs, tp, dclass);
1841 	if(!z) {
1842 		free(name);
1843 		return NULL;
1844 	}
1845 	lock_rw_wrlock(&z->lock);
1846 
1847 	/* find the closest parent */
1848 	z->parent = local_zones_find(zones, name, len, labs, dclass);
1849 
1850 	/* insert into the tree */
1851 	if(!rbtree_insert(&zones->ztree, &z->node)) {
1852 		/* duplicate entry! */
1853 		lock_rw_unlock(&z->lock);
1854 		local_zone_delete(z);
1855 		log_err("internal: duplicate entry in local_zones_add_zone");
1856 		return NULL;
1857 	}
1858 
1859 	/* set parent pointers right */
1860 	set_kiddo_parents(z, z->parent, z);
1861 
1862 	lock_rw_unlock(&z->lock);
1863 	return z;
1864 }
1865 
1866 void local_zones_del_zone(struct local_zones* zones, struct local_zone* z)
1867 {
1868 	/* fix up parents in tree */
1869 	lock_rw_wrlock(&z->lock);
1870 	set_kiddo_parents(z, z, z->parent);
1871 
1872 	/* remove from tree */
1873 	(void)rbtree_delete(&zones->ztree, z);
1874 
1875 	/* delete the zone */
1876 	lock_rw_unlock(&z->lock);
1877 	local_zone_delete(z);
1878 }
1879 
1880 int
1881 local_zones_add_RR(struct local_zones* zones, const char* rr)
1882 {
1883 	uint8_t* rr_name;
1884 	uint16_t rr_class, rr_type;
1885 	size_t len;
1886 	int labs;
1887 	struct local_zone* z;
1888 	int r;
1889 	if(!get_rr_nameclass(rr, &rr_name, &rr_class, &rr_type)) {
1890 		return 0;
1891 	}
1892 	labs = dname_count_size_labels(rr_name, &len);
1893 	/* could first try readlock then get writelock if zone does not exist,
1894 	 * but we do not add enough RRs (from multiple threads) to optimize */
1895 	lock_rw_wrlock(&zones->lock);
1896 	z = local_zones_lookup(zones, rr_name, len, labs, rr_class, rr_type);
1897 	if(!z) {
1898 		z = local_zones_add_zone(zones, rr_name, len, labs, rr_class,
1899 			local_zone_transparent);
1900 		if(!z) {
1901 			lock_rw_unlock(&zones->lock);
1902 			return 0;
1903 		}
1904 	} else {
1905 		free(rr_name);
1906 	}
1907 	lock_rw_wrlock(&z->lock);
1908 	lock_rw_unlock(&zones->lock);
1909 	r = lz_enter_rr_into_zone(z, rr);
1910 	lock_rw_unlock(&z->lock);
1911 	return r;
1912 }
1913 
1914 /** returns true if the node is terminal so no deeper domain names exist */
1915 static int
1916 is_terminal(struct local_data* d)
1917 {
1918 	/* for empty nonterminals, the deeper domain names are sorted
1919 	 * right after them, so simply check the next name in the tree
1920 	 */
1921 	struct local_data* n = (struct local_data*)rbtree_next(&d->node);
1922 	if(n == (struct local_data*)RBTREE_NULL)
1923 		return 1; /* last in tree, no deeper node */
1924 	if(dname_strict_subdomain(n->name, n->namelabs, d->name, d->namelabs))
1925 		return 0; /* there is a deeper node */
1926 	return 1;
1927 }
1928 
1929 /** delete empty terminals from tree when final data is deleted */
1930 static void
1931 del_empty_term(struct local_zone* z, struct local_data* d,
1932 	uint8_t* name, size_t len, int labs)
1933 {
1934 	while(d && d->rrsets == NULL && is_terminal(d)) {
1935 		/* is this empty nonterminal? delete */
1936 		/* note, no memory recycling in zone region */
1937 		(void)rbtree_delete(&z->data, d);
1938 
1939 		/* go up and to the next label */
1940 		if(dname_is_root(name))
1941 			return;
1942 		dname_remove_label(&name, &len);
1943 		labs--;
1944 		d = local_zone_find_data(z, name, len, labs);
1945 	}
1946 }
1947 
1948 /** find and remove type from list in domain struct */
1949 static void
1950 del_local_rrset(struct local_data* d, uint16_t dtype)
1951 {
1952 	struct local_rrset* prev=NULL, *p=d->rrsets;
1953 	while(p && ntohs(p->rrset->rk.type) != dtype) {
1954 		prev = p;
1955 		p = p->next;
1956 	}
1957 	if(!p)
1958 		return; /* rrset type not found */
1959 	/* unlink it */
1960 	if(prev) prev->next = p->next;
1961 	else d->rrsets = p->next;
1962 	/* no memory recycling for zone deletions ... */
1963 }
1964 
1965 void local_zones_del_data(struct local_zones* zones,
1966 	uint8_t* name, size_t len, int labs, uint16_t dclass)
1967 {
1968 	/* find zone */
1969 	struct local_zone* z;
1970 	struct local_data* d;
1971 
1972 	/* remove DS */
1973 	lock_rw_rdlock(&zones->lock);
1974 	z = local_zones_lookup(zones, name, len, labs, dclass, LDNS_RR_TYPE_DS);
1975 	if(z) {
1976 		lock_rw_wrlock(&z->lock);
1977 		d = local_zone_find_data(z, name, len, labs);
1978 		if(d) {
1979 			del_local_rrset(d, LDNS_RR_TYPE_DS);
1980 			del_empty_term(z, d, name, len, labs);
1981 		}
1982 		lock_rw_unlock(&z->lock);
1983 	}
1984 	lock_rw_unlock(&zones->lock);
1985 
1986 	/* remove other types */
1987 	lock_rw_rdlock(&zones->lock);
1988 	z = local_zones_lookup(zones, name, len, labs, dclass, 0);
1989 	if(!z) {
1990 		/* no such zone, we're done */
1991 		lock_rw_unlock(&zones->lock);
1992 		return;
1993 	}
1994 	lock_rw_wrlock(&z->lock);
1995 	lock_rw_unlock(&zones->lock);
1996 
1997 	/* find the domain */
1998 	d = local_zone_find_data(z, name, len, labs);
1999 	if(d) {
2000 		/* no memory recycling for zone deletions ... */
2001 		d->rrsets = NULL;
2002 		/* did we delete the soa record ? */
2003 		if(query_dname_compare(d->name, z->name) == 0)
2004 			z->soa = NULL;
2005 
2006 		/* cleanup the empty nonterminals for this name */
2007 		del_empty_term(z, d, name, len, labs);
2008 	}
2009 
2010 	lock_rw_unlock(&z->lock);
2011 }
2012