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