xref: /netbsd-src/external/bsd/nsd/dist/options.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*
2  * options.c -- options functions.
3  *
4  * Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
5  *
6  * See LICENSE for the license.
7  *
8  */
9 #include "config.h"
10 #include <string.h>
11 #include <stdio.h>
12 #include <errno.h>
13 #include "options.h"
14 #include "query.h"
15 #include "tsig.h"
16 #include "difffile.h"
17 #include "rrl.h"
18 
19 #include "configyyrename.h"
20 #include "configparser.h"
21 config_parser_state_type* cfg_parser = 0;
22 extern FILE* c_in, *c_out;
23 int c_parse(void);
24 int c_lex(void);
25 int c_wrap(void);
26 void c_error(const char *message);
27 extern char* c_text;
28 
29 static int
30 rbtree_strcmp(const void* p1, const void* p2)
31 {
32 	if(p1 == NULL && p2 == NULL) return 0;
33 	if(p1 == NULL) return -1;
34 	if(p2 == NULL) return 1;
35 	return strcmp((const char*)p1, (const char*)p2);
36 }
37 
38 struct nsd_options*
39 nsd_options_create(region_type* region)
40 {
41 	struct nsd_options* opt;
42 	opt = (struct nsd_options*)region_alloc(region, sizeof(
43 		struct nsd_options));
44 	opt->region = region;
45 	opt->zone_options = rbtree_create(region,
46 		(int (*)(const void *, const void *)) dname_compare);
47 	opt->configfile = NULL;
48 	opt->zonestatnames = rbtree_create(opt->region, rbtree_strcmp);
49 	opt->patterns = rbtree_create(region, rbtree_strcmp);
50 	opt->keys = rbtree_create(region, rbtree_strcmp);
51 	opt->ip_addresses = NULL;
52 	opt->ip_transparent = 0;
53 	opt->ip_freebind = 0;
54 	opt->debug_mode = 0;
55 	opt->verbosity = 0;
56 	opt->hide_version = 0;
57 	opt->do_ip4 = 1;
58 	opt->do_ip6 = 1;
59 	opt->database = DBFILE;
60 	opt->identity = 0;
61 	opt->version = 0;
62 	opt->nsid = 0;
63 	opt->logfile = 0;
64 	opt->log_time_ascii = 1;
65 	opt->round_robin = 0; /* also packet.h::round_robin */
66 	opt->minimal_responses = 0; /* also packet.h::minimal_responses */
67 	opt->server_count = 1;
68 	opt->tcp_count = 100;
69 	opt->tcp_query_count = 0;
70 	opt->tcp_timeout = TCP_TIMEOUT;
71 	opt->tcp_mss = 0;
72 	opt->outgoing_tcp_mss = 0;
73 	opt->ipv4_edns_size = EDNS_MAX_MESSAGE_LEN;
74 	opt->ipv6_edns_size = EDNS_MAX_MESSAGE_LEN;
75 	opt->pidfile = PIDFILE;
76 	opt->port = UDP_PORT;
77 /* deprecated?	opt->port = TCP_PORT; */
78 	opt->reuseport = 0;
79 	opt->statistics = 0;
80 	opt->chroot = 0;
81 	opt->username = USER;
82 	opt->zonesdir = ZONESDIR;
83 	opt->xfrdfile = XFRDFILE;
84 	opt->xfrdir = XFRDIR;
85 	opt->zonelistfile = ZONELISTFILE;
86 #ifdef RATELIMIT
87 	opt->rrl_size = RRL_BUCKETS;
88 	opt->rrl_slip = RRL_SLIP;
89 	opt->rrl_ipv4_prefix_length = RRL_IPV4_PREFIX_LENGTH;
90 	opt->rrl_ipv6_prefix_length = RRL_IPV6_PREFIX_LENGTH;
91 #  ifdef RATELIMIT_DEFAULT_OFF
92 	opt->rrl_ratelimit = 0;
93 	opt->rrl_whitelist_ratelimit = 0;
94 #  else
95 	opt->rrl_ratelimit = RRL_LIMIT/2;
96 	opt->rrl_whitelist_ratelimit = RRL_WLIST_LIMIT/2;
97 #  endif
98 #endif
99 	opt->zonefiles_check = 1;
100 	if(opt->database == NULL || opt->database[0] == 0)
101 		opt->zonefiles_write = ZONEFILES_WRITE_INTERVAL;
102 	else	opt->zonefiles_write = 0;
103 	opt->xfrd_reload_timeout = 1;
104 	opt->control_enable = 0;
105 	opt->control_interface = NULL;
106 	opt->control_port = NSD_CONTROL_PORT;
107 	opt->server_key_file = CONFIGDIR"/nsd_server.key";
108 	opt->server_cert_file = CONFIGDIR"/nsd_server.pem";
109 	opt->control_key_file = CONFIGDIR"/nsd_control.key";
110 	opt->control_cert_file = CONFIGDIR"/nsd_control.pem";
111 	return opt;
112 }
113 
114 int
115 nsd_options_insert_zone(struct nsd_options* opt, struct zone_options* zone)
116 {
117 	/* create dname for lookup */
118 	const dname_type* dname = dname_parse(opt->region, zone->name);
119 	if(!dname)
120 		return 0;
121 	zone->node.key = dname;
122 	if(!rbtree_insert(opt->zone_options, (rbnode_type*)zone))
123 		return 0;
124 	return 1;
125 }
126 
127 int
128 nsd_options_insert_pattern(struct nsd_options* opt,
129 	struct pattern_options* pat)
130 {
131 	if(!pat->pname)
132 		return 0;
133 	pat->node.key = pat->pname;
134 	if(!rbtree_insert(opt->patterns, (rbnode_type*)pat))
135 		return 0;
136 	return 1;
137 }
138 
139 int
140 parse_options_file(struct nsd_options* opt, const char* file,
141 	void (*err)(void*,const char*), void* err_arg)
142 {
143 	FILE *in = 0;
144 	struct pattern_options* pat;
145 	struct acl_options* acl;
146 
147 	if(!cfg_parser) {
148 		cfg_parser = (config_parser_state_type*)region_alloc(
149 			opt->region, sizeof(config_parser_state_type));
150 		cfg_parser->chroot = 0;
151 	}
152 	cfg_parser->err = err;
153 	cfg_parser->err_arg = err_arg;
154 	cfg_parser->filename = (char*)file;
155 	cfg_parser->line = 1;
156 	cfg_parser->errors = 0;
157 	cfg_parser->server_settings_seen = 0;
158 	cfg_parser->opt = opt;
159 	cfg_parser->current_pattern = 0;
160 	cfg_parser->current_zone = 0;
161 	cfg_parser->current_key = 0;
162 	cfg_parser->current_ip_address_option = opt->ip_addresses;
163 	while(cfg_parser->current_ip_address_option && cfg_parser->current_ip_address_option->next)
164 		cfg_parser->current_ip_address_option = cfg_parser->current_ip_address_option->next;
165 	cfg_parser->current_allow_notify = 0;
166 	cfg_parser->current_request_xfr = 0;
167 	cfg_parser->current_notify = 0;
168 	cfg_parser->current_provide_xfr = 0;
169 
170 	in = fopen(cfg_parser->filename, "r");
171 	if(!in) {
172 		if(err) {
173 			char m[MAXSYSLOGMSGLEN];
174 			snprintf(m, sizeof(m), "Could not open %s: %s\n",
175 				file, strerror(errno));
176 			err(err_arg, m);
177 		} else {
178 			fprintf(stderr, "Could not open %s: %s\n",
179 				file, strerror(errno));
180 		}
181 		return 0;
182 	}
183 	c_in = in;
184 	c_parse();
185 	fclose(in);
186 
187 	opt->configfile = region_strdup(opt->region, file);
188 	if(cfg_parser->current_pattern) {
189 		if(!cfg_parser->current_pattern->pname)
190 			c_error("last pattern has no name");
191 		else {
192 			if(!nsd_options_insert_pattern(cfg_parser->opt,
193 				cfg_parser->current_pattern))
194 				c_error("duplicate pattern");
195 		}
196 	}
197 	if(cfg_parser->current_zone) {
198 		if(!cfg_parser->current_zone->name)
199 			c_error("last zone has no name");
200 		else {
201 			if(!nsd_options_insert_zone(opt,
202 				cfg_parser->current_zone))
203 				c_error("duplicate zone");
204 		}
205 		if(!cfg_parser->current_zone->pattern)
206 			c_error("last zone has no pattern");
207 	}
208 	if(cfg_parser->current_key)
209 	{
210 		if(!cfg_parser->current_key->name)
211 			c_error("last key has no name");
212 		if(!cfg_parser->current_key->algorithm)
213 			c_error("last key has no algorithm");
214 		if(!cfg_parser->current_key->secret)
215 			c_error("last key has no secret blob");
216 		key_options_insert(opt, cfg_parser->current_key);
217 	}
218 	RBTREE_FOR(pat, struct pattern_options*, opt->patterns)
219 	{
220 		/* lookup keys for acls */
221 		for(acl=pat->allow_notify; acl; acl=acl->next)
222 		{
223 			if(acl->nokey || acl->blocked)
224 				continue;
225 			acl->key_options = key_options_find(opt, acl->key_name);
226 			if(!acl->key_options)
227 				c_error_msg("key %s in pattern %s could not be found",
228 					acl->key_name, pat->pname);
229 		}
230 		for(acl=pat->notify; acl; acl=acl->next)
231 		{
232 			if(acl->nokey || acl->blocked)
233 				continue;
234 			acl->key_options = key_options_find(opt, acl->key_name);
235 			if(!acl->key_options)
236 				c_error_msg("key %s in pattern %s could not be found",
237 					acl->key_name, pat->pname);
238 		}
239 		for(acl=pat->request_xfr; acl; acl=acl->next)
240 		{
241 			if(acl->nokey || acl->blocked)
242 				continue;
243 			acl->key_options = key_options_find(opt, acl->key_name);
244 			if(!acl->key_options)
245 				c_error_msg("key %s in pattern %s could not be found",
246 					acl->key_name, pat->pname);
247 		}
248 		for(acl=pat->provide_xfr; acl; acl=acl->next)
249 		{
250 			if(acl->nokey || acl->blocked)
251 				continue;
252 			acl->key_options = key_options_find(opt, acl->key_name);
253 			if(!acl->key_options)
254 				c_error_msg("key %s in pattern %s could not be found",
255 					acl->key_name, pat->pname);
256 		}
257 	}
258 
259 	if(cfg_parser->errors > 0)
260 	{
261 		if(err) {
262 			char m[MAXSYSLOGMSGLEN];
263 			snprintf(m, sizeof(m), "read %s failed: %d errors in "
264 				"configuration file\n", file,
265 				cfg_parser->errors);
266 			err(err_arg, m);
267 		} else {
268 			fprintf(stderr, "read %s failed: %d errors in "
269 				"configuration file\n", file,
270 				cfg_parser->errors);
271 		}
272 		return 0;
273 	}
274 	return 1;
275 }
276 
277 void options_zonestatnames_create(struct nsd_options* opt)
278 {
279 	struct zone_options* zopt;
280 	/* allocate "" as zonestat 0, for zones without a zonestat */
281 	if(!rbtree_search(opt->zonestatnames, "")) {
282 		struct zonestatname* n;
283 		n = (struct zonestatname*)xalloc(sizeof(*n));
284 		memset(n, 0, sizeof(*n));
285 		n->node.key = strdup("");
286 		if(!n->node.key) {
287 			log_msg(LOG_ERR, "malloc failed: %s", strerror(errno));
288 			exit(1);
289 		}
290 		n->id = (unsigned)(opt->zonestatnames->count);
291 		rbtree_insert(opt->zonestatnames, (rbnode_type*)n);
292 	}
293 	RBTREE_FOR(zopt, struct zone_options*, opt->zone_options) {
294 		/* insert into tree, so that when read in later id exists */
295 		(void)getzonestatid(opt, zopt);
296 	}
297 }
298 
299 #define ZONELIST_HEADER "# NSD zone list\n# name pattern\n"
300 static int
301 comp_zonebucket(const void* a, const void* b)
302 {
303 	/* the line size is much smaller than max-int, and positive,
304 	 * so the subtraction works */
305 	return *(const int*)b - *(const int*)a;
306 }
307 
308 /* insert free entry into zonelist free buckets */
309 static void
310 zone_list_free_insert(struct nsd_options* opt, int linesize, off_t off)
311 {
312 	struct zonelist_free* e;
313 	struct zonelist_bucket* b = (struct zonelist_bucket*)rbtree_search(
314 		opt->zonefree, &linesize);
315 	if(!b) {
316 		b = region_alloc_zero(opt->region, sizeof(*b));
317 		b->linesize = linesize;
318 		b->node = *RBTREE_NULL;
319 		b->node.key = &b->linesize;
320 		rbtree_insert(opt->zonefree, &b->node);
321 	}
322 	e = (struct zonelist_free*)region_alloc_zero(opt->region, sizeof(*e));
323 	e->next = b->list;
324 	b->list = e;
325 	e->off = off;
326 	opt->zonefree_number++;
327 }
328 
329 struct zone_options*
330 zone_list_zone_insert(struct nsd_options* opt, const char* nm,
331 	const char* patnm, int linesize, off_t off)
332 {
333 	struct pattern_options* pat = pattern_options_find(opt, patnm);
334 	struct zone_options* zone;
335 	if(!pat) {
336 		log_msg(LOG_ERR, "pattern does not exist for zone %s "
337 			"pattern %s", nm, patnm);
338 		return NULL;
339 	}
340 	zone = zone_options_create(opt->region);
341 	zone->part_of_config = 0;
342 	zone->name = region_strdup(opt->region, nm);
343 	zone->linesize = linesize;
344 	zone->off = off;
345 	zone->pattern = pat;
346 	if(!nsd_options_insert_zone(opt, zone)) {
347 		log_msg(LOG_ERR, "bad domain name or duplicate zone '%s' "
348 			"pattern %s", nm, patnm);
349 		region_recycle(opt->region, (void*)zone->name, strlen(nm)+1);
350 		region_recycle(opt->region, zone, sizeof(*zone));
351 		return NULL;
352 	}
353 	return zone;
354 }
355 
356 int
357 parse_zone_list_file(struct nsd_options* opt)
358 {
359 	/* zonelist looks like this:
360 	# name pattern
361 	add example.com master
362 	del example.net slave
363 	add foo.bar.nl slave
364 	add rutabaga.uk config
365 	*/
366 	char buf[1024];
367 
368 	/* create empty data structures */
369 	opt->zonefree = rbtree_create(opt->region, comp_zonebucket);
370 	opt->zonelist = NULL;
371 	opt->zonefree_number = 0;
372 	opt->zonelist_off = 0;
373 
374 	/* try to open the zonelist file, an empty or nonexist file is OK */
375 	opt->zonelist = fopen(opt->zonelistfile, "r+");
376 	if(!opt->zonelist) {
377 		if(errno == ENOENT)
378 			return 1; /* file does not exist, it is created later */
379 		log_msg(LOG_ERR, "could not open zone list %s: %s", opt->zonelistfile,
380 			strerror(errno));
381 		return 0;
382 	}
383 	/* read header */
384 	buf[strlen(ZONELIST_HEADER)] = 0;
385 	if(fread(buf, 1, strlen(ZONELIST_HEADER), opt->zonelist) !=
386 		strlen(ZONELIST_HEADER) || strncmp(buf, ZONELIST_HEADER,
387 		strlen(ZONELIST_HEADER)) != 0) {
388 		log_msg(LOG_ERR, "zone list %s contains bad header\n", opt->zonelistfile);
389 		fclose(opt->zonelist);
390 		opt->zonelist = NULL;
391 		return 0;
392 	}
393 
394 	/* read entries in file */
395 	while(fgets(buf, sizeof(buf), opt->zonelist)) {
396 		/* skip comments and empty lines */
397 		if(buf[0] == 0 || buf[0] == '\n' || buf[0] == '#')
398 			continue;
399 		if(strncmp(buf, "add ", 4) == 0) {
400 			int linesize = strlen(buf);
401 			/* parse the 'add' line */
402 			/* pick last space on the line, so that the domain
403 			 * name can have a space in it (but not the pattern)*/
404 			char* space = strrchr(buf+4, ' ');
405 			char* nm, *patnm;
406 			if(!space) {
407 				/* parse error */
408 				log_msg(LOG_ERR, "parse error in %s: '%s'",
409 					opt->zonelistfile, buf);
410 				continue;
411 			}
412 			nm = buf+4;
413 			*space = 0;
414 			patnm = space+1;
415 			if(linesize && buf[linesize-1] == '\n')
416 				buf[linesize-1] = 0;
417 
418 			/* store offset and line size for zone entry */
419 			/* and create zone entry in zonetree */
420 			(void)zone_list_zone_insert(opt, nm, patnm, linesize,
421 				ftello(opt->zonelist)-linesize);
422 		} else if(strncmp(buf, "del ", 4) == 0) {
423 			/* store offset and line size for deleted entry */
424 			int linesize = strlen(buf);
425 			zone_list_free_insert(opt, linesize,
426 				ftello(opt->zonelist)-linesize);
427 		} else {
428 			log_msg(LOG_WARNING, "bad data in %s, '%s'", opt->zonelistfile,
429 				buf);
430 		}
431 	}
432 	/* store EOF offset */
433 	opt->zonelist_off = ftello(opt->zonelist);
434 	return 1;
435 }
436 
437 void
438 zone_options_delete(struct nsd_options* opt, struct zone_options* zone)
439 {
440 	rbtree_delete(opt->zone_options, zone->node.key);
441 	region_recycle(opt->region, (void*)zone->node.key, dname_total_size(
442 		(dname_type*)zone->node.key));
443 	region_recycle(opt->region, zone, sizeof(*zone));
444 }
445 
446 /* add a new zone to the zonelist */
447 struct zone_options*
448 zone_list_add(struct nsd_options* opt, const char* zname, const char* pname)
449 {
450 	int r;
451 	struct zonelist_free* e;
452 	struct zonelist_bucket* b;
453 	int linesize = 6 + strlen(zname) + strlen(pname);
454 	/* create zone entry */
455 	struct zone_options* zone = zone_list_zone_insert(opt, zname, pname,
456 		linesize, 0);
457 	if(!zone)
458 		return NULL;
459 
460 	/* use free entry or append to file or create new file */
461 	if(!opt->zonelist || opt->zonelist_off == 0) {
462 		/* create new file */
463 		if(opt->zonelist) fclose(opt->zonelist);
464 		opt->zonelist = fopen(opt->zonelistfile, "w+");
465 		if(!opt->zonelist) {
466 			log_msg(LOG_ERR, "could not create zone list %s: %s",
467 				opt->zonelistfile, strerror(errno));
468 			log_msg(LOG_ERR, "zone %s could not be added", zname);
469 			zone_options_delete(opt, zone);
470 			return NULL;
471 		}
472 		r = fprintf(opt->zonelist, ZONELIST_HEADER);
473 		if(r != strlen(ZONELIST_HEADER)) {
474 			if(r == -1)
475 				log_msg(LOG_ERR, "could not write to %s: %s",
476 					opt->zonelistfile, strerror(errno));
477 			else log_msg(LOG_ERR, "partial write to %s: disk full",
478 				opt->zonelistfile);
479 			log_msg(LOG_ERR, "zone %s could not be added", zname);
480 			zone_options_delete(opt, zone);
481 			return NULL;
482 		}
483 		zone->off = ftello(opt->zonelist);
484 		if(zone->off == -1)
485 			log_msg(LOG_ERR, "ftello(%s): %s", opt->zonelistfile, strerror(errno));
486 		r = fprintf(opt->zonelist, "add %s %s\n", zname, pname);
487 		if(r != zone->linesize) {
488 			if(r == -1)
489 				log_msg(LOG_ERR, "could not write to %s: %s",
490 					opt->zonelistfile, strerror(errno));
491 			else log_msg(LOG_ERR, "partial write to %s: disk full",
492 				opt->zonelistfile);
493 			log_msg(LOG_ERR, "zone %s could not be added", zname);
494 			zone_options_delete(opt, zone);
495 			return NULL;
496 		}
497 		opt->zonelist_off = ftello(opt->zonelist);
498 		if(opt->zonelist_off == -1)
499 			log_msg(LOG_ERR, "ftello(%s): %s", opt->zonelistfile, strerror(errno));
500 		if(fflush(opt->zonelist) != 0) {
501 			log_msg(LOG_ERR, "fflush %s: %s", opt->zonelistfile, strerror(errno));
502 		}
503 		return zone;
504 	}
505 	b = (struct zonelist_bucket*)rbtree_search(opt->zonefree,
506 		&zone->linesize);
507 	if(!b || b->list == NULL) {
508 		/* no empty place, append to file */
509 		zone->off = opt->zonelist_off;
510 		if(fseeko(opt->zonelist, zone->off, SEEK_SET) == -1) {
511 			log_msg(LOG_ERR, "fseeko(%s): %s", opt->zonelistfile, strerror(errno));
512 			log_msg(LOG_ERR, "zone %s could not be added", zname);
513 			zone_options_delete(opt, zone);
514 			return NULL;
515 		}
516 		r = fprintf(opt->zonelist, "add %s %s\n", zname, pname);
517 		if(r != zone->linesize) {
518 			if(r == -1)
519 				log_msg(LOG_ERR, "could not write to %s: %s",
520 					opt->zonelistfile, strerror(errno));
521 			else log_msg(LOG_ERR, "partial write to %s: disk full",
522 				opt->zonelistfile);
523 			log_msg(LOG_ERR, "zone %s could not be added", zname);
524 			zone_options_delete(opt, zone);
525 			return NULL;
526 		}
527 		opt->zonelist_off += linesize;
528 		if(fflush(opt->zonelist) != 0) {
529 			log_msg(LOG_ERR, "fflush %s: %s", opt->zonelistfile, strerror(errno));
530 		}
531 		return zone;
532 	}
533 	/* reuse empty spot */
534 	e = b->list;
535 	zone->off = e->off;
536 	if(fseeko(opt->zonelist, zone->off, SEEK_SET) == -1) {
537 		log_msg(LOG_ERR, "fseeko(%s): %s", opt->zonelistfile, strerror(errno));
538 		log_msg(LOG_ERR, "zone %s could not be added", zname);
539 		zone_options_delete(opt, zone);
540 		return NULL;
541 	}
542 	r = fprintf(opt->zonelist, "add %s %s\n", zname, pname);
543 	if(r != zone->linesize) {
544 		if(r == -1)
545 			log_msg(LOG_ERR, "could not write to %s: %s",
546 				opt->zonelistfile, strerror(errno));
547 		else log_msg(LOG_ERR, "partial write to %s: disk full",
548 			opt->zonelistfile);
549 		log_msg(LOG_ERR, "zone %s could not be added", zname);
550 		zone_options_delete(opt, zone);
551 		return NULL;
552 	}
553 	if(fflush(opt->zonelist) != 0) {
554 		log_msg(LOG_ERR, "fflush %s: %s", opt->zonelistfile, strerror(errno));
555 	}
556 
557 	/* snip off and recycle element */
558 	b->list = e->next;
559 	region_recycle(opt->region, e, sizeof(*e));
560 	if(b->list == NULL) {
561 		rbtree_delete(opt->zonefree, &b->linesize);
562 		region_recycle(opt->region, b, sizeof(*b));
563 	}
564 	opt->zonefree_number--;
565 	return zone;
566 }
567 
568 /* remove a zone on the zonelist */
569 void
570 zone_list_del(struct nsd_options* opt, struct zone_options* zone)
571 {
572 	/* put its space onto the free entry */
573 	if(fseeko(opt->zonelist, zone->off, SEEK_SET) == -1) {
574 		log_msg(LOG_ERR, "fseeko(%s): %s", opt->zonelistfile, strerror(errno));
575 		return;
576 	}
577 	fprintf(opt->zonelist, "del");
578 	zone_list_free_insert(opt, zone->linesize, zone->off);
579 
580 	/* remove zone_options */
581 	zone_options_delete(opt, zone);
582 
583 	/* see if we need to compact: it is going to halve the zonelist */
584 	if(opt->zonefree_number > opt->zone_options->count) {
585 		zone_list_compact(opt);
586 	} else {
587 		if(fflush(opt->zonelist) != 0) {
588 			log_msg(LOG_ERR, "fflush %s: %s", opt->zonelistfile, strerror(errno));
589 		}
590 	}
591 }
592 /* postorder delete of zonelist free space tree */
593 static void
594 delbucket(region_type* region, struct zonelist_bucket* b)
595 {
596 	struct zonelist_free* e, *f;
597 	if(!b || (rbnode_type*)b==RBTREE_NULL)
598 		return;
599 	delbucket(region, (struct zonelist_bucket*)b->node.left);
600 	delbucket(region, (struct zonelist_bucket*)b->node.right);
601 	e = b->list;
602 	while(e) {
603 		f = e->next;
604 		region_recycle(region, e, sizeof(*e));
605 		e = f;
606 	}
607 	region_recycle(region, b, sizeof(*b));
608 }
609 
610 /* compact zonelist file */
611 void
612 zone_list_compact(struct nsd_options* opt)
613 {
614 	char outname[1024];
615 	FILE* out;
616 	struct zone_options* zone;
617 	off_t off;
618 	int r;
619 	snprintf(outname, sizeof(outname), "%s~", opt->zonelistfile);
620 	/* useful, when : count-of-free > count-of-used */
621 	/* write zonelist to zonelist~ */
622 	out = fopen(outname, "w+");
623 	if(!out) {
624 		log_msg(LOG_ERR, "could not open %s: %s", outname, strerror(errno));
625 		return;
626 	}
627 	r = fprintf(out, ZONELIST_HEADER);
628 	if(r == -1) {
629 		log_msg(LOG_ERR, "write %s failed: %s", outname,
630 			strerror(errno));
631 		fclose(out);
632 		return;
633 	} else if(r != strlen(ZONELIST_HEADER)) {
634 		log_msg(LOG_ERR, "write %s was partial: disk full",
635 			outname);
636 		fclose(out);
637 		return;
638 	}
639 	off = ftello(out);
640 	if(off == -1) {
641 		log_msg(LOG_ERR, "ftello(%s): %s", outname, strerror(errno));
642 		fclose(out);
643 		return;
644 	}
645 	RBTREE_FOR(zone, struct zone_options*, opt->zone_options) {
646 		if(zone->part_of_config)
647 			continue;
648 		r = fprintf(out, "add %s %s\n", zone->name,
649 			zone->pattern->pname);
650 		if(r < 0) {
651 			log_msg(LOG_ERR, "write %s failed: %s", outname,
652 				strerror(errno));
653 			fclose(out);
654 			return;
655 		} else if(r != zone->linesize) {
656 			log_msg(LOG_ERR, "write %s was partial: disk full",
657 				outname);
658 			fclose(out);
659 			return;
660 		}
661 	}
662 	if(fflush(out) != 0) {
663 		log_msg(LOG_ERR, "fflush %s: %s", outname, strerror(errno));
664 	}
665 
666 	/* rename zonelist~ onto zonelist */
667 	if(rename(outname, opt->zonelistfile) == -1) {
668 		log_msg(LOG_ERR, "rename(%s to %s) failed: %s",
669 			outname, opt->zonelistfile, strerror(errno));
670 		fclose(out);
671 		return;
672 	}
673 	fclose(opt->zonelist);
674 	/* set offsets */
675 	RBTREE_FOR(zone, struct zone_options*, opt->zone_options) {
676 		if(zone->part_of_config)
677 			continue;
678 		zone->off = off;
679 		off += zone->linesize;
680 	}
681 	/* empty the free tree */
682 	delbucket(opt->region, (struct zonelist_bucket*)opt->zonefree->root);
683 	opt->zonefree->root = RBTREE_NULL;
684 	opt->zonefree->count = 0;
685 	opt->zonefree_number = 0;
686 	/* finish */
687 	opt->zonelist = out;
688 	opt->zonelist_off = off;
689 }
690 
691 /* close zonelist file */
692 void
693 zone_list_close(struct nsd_options* opt)
694 {
695 	fclose(opt->zonelist);
696 	opt->zonelist = NULL;
697 }
698 
699 void
700 c_error_va_list_pos(int showpos, const char* fmt, va_list args)
701 {
702 	char* at = NULL;
703 	cfg_parser->errors++;
704 	if(showpos && c_text && c_text[0]!=0) {
705 		at = c_text;
706 	}
707 	if(cfg_parser->err) {
708 		char m[MAXSYSLOGMSGLEN];
709 		snprintf(m, sizeof(m), "%s:%d: ", cfg_parser->filename,
710 			cfg_parser->line);
711 		(*cfg_parser->err)(cfg_parser->err_arg, m);
712 		if(at) {
713 			snprintf(m, sizeof(m), "at '%s': ", at);
714 			(*cfg_parser->err)(cfg_parser->err_arg, m);
715 		}
716 		(*cfg_parser->err)(cfg_parser->err_arg, "error: ");
717 		vsnprintf(m, sizeof(m), fmt, args);
718 		(*cfg_parser->err)(cfg_parser->err_arg, m);
719 		(*cfg_parser->err)(cfg_parser->err_arg, "\n");
720 		return;
721 	}
722         fprintf(stderr, "%s:%d: ", cfg_parser->filename, cfg_parser->line);
723 	if(at) fprintf(stderr, "at '%s': ", at);
724 	fprintf(stderr, "error: ");
725 	vfprintf(stderr, fmt, args);
726 	fprintf(stderr, "\n");
727 }
728 
729 void
730 c_error_msg_pos(int showpos, const char* fmt, ...)
731 {
732         va_list args;
733         va_start(args, fmt);
734         c_error_va_list_pos(showpos, fmt, args);
735         va_end(args);
736 }
737 
738 void
739 c_error_msg(const char* fmt, ...)
740 {
741         va_list args;
742         va_start(args, fmt);
743         c_error_va_list_pos(0, fmt, args);
744         va_end(args);
745 }
746 
747 void
748 c_error(const char* str)
749 {
750 	if((strcmp(str, "syntax error")==0 || strcmp(str, "parse error")==0))
751 		c_error_msg_pos(1, "%s", str);
752 	else	c_error_msg("%s", str);
753 }
754 
755 int
756 c_wrap()
757 {
758         return 1;
759 }
760 
761 struct zone_options*
762 zone_options_create(region_type* region)
763 {
764 	struct zone_options* zone;
765 	zone = (struct zone_options*)region_alloc(region, sizeof(
766 		struct zone_options));
767 	zone->node = *RBTREE_NULL;
768 	zone->name = 0;
769 	zone->pattern = 0;
770 	zone->part_of_config = 0;
771 	return zone;
772 }
773 
774 /* true is booleans are the same truth value */
775 #define booleq(x,y) ( ((x) && (y)) || (!(x) && !(y)) )
776 
777 int
778 acl_equal(struct acl_options* p, struct acl_options* q)
779 {
780 	if(!booleq(p->use_axfr_only, q->use_axfr_only)) return 0;
781 	if(!booleq(p->allow_udp, q->allow_udp)) return 0;
782 	if(strcmp(p->ip_address_spec, q->ip_address_spec)!=0) return 0;
783 	/* the ip6, port, addr, mask, type: are derived from the ip_address_spec */
784 	if(!booleq(p->nokey, q->nokey)) return 0;
785 	if(!booleq(p->blocked, q->blocked)) return 0;
786 	if(p->key_name && q->key_name) {
787 		if(strcmp(p->key_name, q->key_name)!=0) return 0;
788 	} else if(p->key_name && !q->key_name) return 0;
789 	else if(!p->key_name && q->key_name) return 0;
790 	/* key_options is derived from key_name */
791 	return 1;
792 }
793 
794 int
795 acl_list_equal(struct acl_options* p, struct acl_options* q)
796 {
797 	/* must be same and in same order */
798 	while(p && q) {
799 		if(!acl_equal(p, q))
800 			return 0;
801 		p = p->next;
802 		q = q->next;
803 	}
804 	if(!p && !q) return 1;
805 	/* different lengths */
806 	return 0;
807 }
808 
809 struct pattern_options*
810 pattern_options_create(region_type* region)
811 {
812 	struct pattern_options* p;
813 	p = (struct pattern_options*)region_alloc(region, sizeof(
814 		struct pattern_options));
815 	p->node = *RBTREE_NULL;
816 	p->pname = 0;
817 	p->zonefile = 0;
818 	p->zonestats = 0;
819 	p->allow_notify = 0;
820 	p->request_xfr = 0;
821 	p->size_limit_xfr = 0;
822 	p->notify = 0;
823 	p->provide_xfr = 0;
824 	p->outgoing_interface = 0;
825 	p->notify_retry = 5;
826 	p->notify_retry_is_default = 1;
827 	p->allow_axfr_fallback = 1;
828 	p->allow_axfr_fallback_is_default = 1;
829 	p->implicit = 0;
830 	p->xfrd_flags = 0;
831 	p->max_refresh_time = 2419200;	/* 4 weeks */
832 	p->max_refresh_time_is_default = 1;
833 	p->min_refresh_time = 0;
834 	p->min_refresh_time_is_default = 1;
835 	p->max_retry_time = 1209600;	/* 2 weeks */
836 	p->max_retry_time_is_default = 1;
837 	p->min_retry_time = 0;
838 	p->min_retry_time_is_default = 1;
839 #ifdef RATELIMIT
840 	p->rrl_whitelist = 0;
841 #endif
842 	p->multi_master_check = 0;
843 	return p;
844 }
845 
846 static void
847 acl_delete(region_type* region, struct acl_options* acl)
848 {
849 	if(acl->ip_address_spec)
850 		region_recycle(region, (void*)acl->ip_address_spec,
851 			strlen(acl->ip_address_spec)+1);
852 	if(acl->key_name)
853 		region_recycle(region, (void*)acl->key_name,
854 			strlen(acl->key_name)+1);
855 	/* key_options is a convenience pointer, not owned by the acl */
856 	region_recycle(region, acl, sizeof(*acl));
857 }
858 
859 static void
860 acl_list_delete(region_type* region, struct acl_options* list)
861 {
862 	struct acl_options* n;
863 	while(list) {
864 		n = list->next;
865 		acl_delete(region, list);
866 		list = n;
867 	}
868 }
869 
870 void
871 pattern_options_remove(struct nsd_options* opt, const char* name)
872 {
873 	struct pattern_options* p = (struct pattern_options*)rbtree_delete(
874 		opt->patterns, name);
875 	/* delete p and its contents */
876 	if (!p)
877 		return;
878 	if(p->pname)
879 		region_recycle(opt->region, (void*)p->pname,
880 			strlen(p->pname)+1);
881 	if(p->zonefile)
882 		region_recycle(opt->region, (void*)p->zonefile,
883 			strlen(p->zonefile)+1);
884 	if(p->zonestats)
885 		region_recycle(opt->region, (void*)p->zonestats,
886 			strlen(p->zonestats)+1);
887 	acl_list_delete(opt->region, p->allow_notify);
888 	acl_list_delete(opt->region, p->request_xfr);
889 	acl_list_delete(opt->region, p->notify);
890 	acl_list_delete(opt->region, p->provide_xfr);
891 	acl_list_delete(opt->region, p->outgoing_interface);
892 
893 	region_recycle(opt->region, p, sizeof(struct pattern_options));
894 }
895 
896 static struct acl_options*
897 copy_acl(region_type* region, struct acl_options* a)
898 {
899 	struct acl_options* b;
900 	if(!a) return NULL;
901 	b = (struct acl_options*)region_alloc(region, sizeof(*b));
902 	/* copy the whole lot */
903 	*b = *a;
904 	/* fix the pointers */
905 	if(a->ip_address_spec)
906 		b->ip_address_spec = region_strdup(region, a->ip_address_spec);
907 	if(a->key_name)
908 		b->key_name = region_strdup(region, a->key_name);
909 	b->next = NULL;
910 	b->key_options = NULL;
911 	return b;
912 }
913 
914 static struct acl_options*
915 copy_acl_list(struct nsd_options* opt, struct acl_options* a)
916 {
917 	struct acl_options* b, *blast = NULL, *blist = NULL;
918 	while(a) {
919 		b = copy_acl(opt->region, a);
920 		/* fixup key_options */
921 		if(b->key_name)
922 			b->key_options = key_options_find(opt, b->key_name);
923 		else	b->key_options = NULL;
924 
925 		/* link as last into list */
926 		b->next = NULL;
927 		if(!blist) blist = b;
928 		else blast->next = b;
929 		blast = b;
930 
931 		a = a->next;
932 	}
933 	return blist;
934 }
935 
936 static void
937 copy_changed_acl(struct nsd_options* opt, struct acl_options** orig,
938 	struct acl_options* anew)
939 {
940 	if(!acl_list_equal(*orig, anew)) {
941 		acl_list_delete(opt->region, *orig);
942 		*orig = copy_acl_list(opt, anew);
943 	}
944 }
945 
946 static void
947 copy_pat_fixed(region_type* region, struct pattern_options* orig,
948 	struct pattern_options* p)
949 {
950 	orig->allow_axfr_fallback = p->allow_axfr_fallback;
951 	orig->allow_axfr_fallback_is_default =
952 		p->allow_axfr_fallback_is_default;
953 	orig->notify_retry = p->notify_retry;
954 	orig->notify_retry_is_default = p->notify_retry_is_default;
955 	orig->implicit = p->implicit;
956 	if(p->zonefile)
957 		orig->zonefile = region_strdup(region, p->zonefile);
958 	else orig->zonefile = NULL;
959 	if(p->zonestats)
960 		orig->zonestats = region_strdup(region, p->zonestats);
961 	else orig->zonestats = NULL;
962 	orig->max_refresh_time = p->max_refresh_time;
963 	orig->max_refresh_time_is_default = p->max_refresh_time_is_default;
964 	orig->min_refresh_time = p->min_refresh_time;
965 	orig->min_refresh_time_is_default = p->min_refresh_time_is_default;
966 	orig->max_retry_time = p->max_retry_time;
967 	orig->max_retry_time_is_default = p->max_retry_time_is_default;
968 	orig->min_retry_time = p->min_retry_time;
969 	orig->min_retry_time_is_default = p->min_retry_time_is_default;
970 #ifdef RATELIMIT
971 	orig->rrl_whitelist = p->rrl_whitelist;
972 #endif
973 	orig->multi_master_check = p->multi_master_check;
974 }
975 
976 void
977 pattern_options_add_modify(struct nsd_options* opt, struct pattern_options* p)
978 {
979 	struct pattern_options* orig = pattern_options_find(opt, p->pname);
980 	if(!orig) {
981 		/* needs to be copied to opt region */
982 		orig = pattern_options_create(opt->region);
983 		orig->pname = region_strdup(opt->region, p->pname);
984 		copy_pat_fixed(opt->region, orig, p);
985 		orig->allow_notify = copy_acl_list(opt, p->allow_notify);
986 		orig->request_xfr = copy_acl_list(opt, p->request_xfr);
987 		orig->notify = copy_acl_list(opt, p->notify);
988 		orig->provide_xfr = copy_acl_list(opt, p->provide_xfr);
989 		orig->outgoing_interface = copy_acl_list(opt,
990 			p->outgoing_interface);
991 		nsd_options_insert_pattern(opt, orig);
992 	} else {
993 		/* modify in place so pointers stay valid (and copy
994 		   into region). Do not touch unchanged acls. */
995 		if(orig->zonefile)
996 			region_recycle(opt->region, (char*)orig->zonefile,
997 				strlen(orig->zonefile)+1);
998 		if(orig->zonestats)
999 			region_recycle(opt->region, (char*)orig->zonestats,
1000 				strlen(orig->zonestats)+1);
1001 		copy_pat_fixed(opt->region, orig, p);
1002 		copy_changed_acl(opt, &orig->allow_notify, p->allow_notify);
1003 		copy_changed_acl(opt, &orig->request_xfr, p->request_xfr);
1004 		copy_changed_acl(opt, &orig->notify, p->notify);
1005 		copy_changed_acl(opt, &orig->provide_xfr, p->provide_xfr);
1006 		copy_changed_acl(opt, &orig->outgoing_interface,
1007 			p->outgoing_interface);
1008 	}
1009 }
1010 
1011 struct pattern_options*
1012 pattern_options_find(struct nsd_options* opt, const char* name)
1013 {
1014 	return (struct pattern_options*)rbtree_search(opt->patterns, name);
1015 }
1016 
1017 int
1018 pattern_options_equal(struct pattern_options* p, struct pattern_options* q)
1019 {
1020 	if(strcmp(p->pname, q->pname) != 0) return 0;
1021 	if(!p->zonefile && q->zonefile) return 0;
1022 	else if(p->zonefile && !q->zonefile) return 0;
1023 	else if(p->zonefile && q->zonefile) {
1024 		if(strcmp(p->zonefile, q->zonefile) != 0) return 0;
1025 	}
1026 	if(!p->zonestats && q->zonestats) return 0;
1027 	else if(p->zonestats && !q->zonestats) return 0;
1028 	else if(p->zonestats && q->zonestats) {
1029 		if(strcmp(p->zonestats, q->zonestats) != 0) return 0;
1030 	}
1031 	if(!booleq(p->allow_axfr_fallback, q->allow_axfr_fallback)) return 0;
1032 	if(!booleq(p->allow_axfr_fallback_is_default,
1033 		q->allow_axfr_fallback_is_default)) return 0;
1034 	if(p->notify_retry != q->notify_retry) return 0;
1035 	if(!booleq(p->notify_retry_is_default,
1036 		q->notify_retry_is_default)) return 0;
1037 	if(!booleq(p->implicit, q->implicit)) return 0;
1038 	if(!acl_list_equal(p->allow_notify, q->allow_notify)) return 0;
1039 	if(!acl_list_equal(p->request_xfr, q->request_xfr)) return 0;
1040 	if(!acl_list_equal(p->notify, q->notify)) return 0;
1041 	if(!acl_list_equal(p->provide_xfr, q->provide_xfr)) return 0;
1042 	if(!acl_list_equal(p->outgoing_interface, q->outgoing_interface))
1043 		return 0;
1044 	if(p->max_refresh_time != q->max_refresh_time) return 0;
1045 	if(!booleq(p->max_refresh_time_is_default,
1046 		q->max_refresh_time_is_default)) return 0;
1047 	if(p->min_refresh_time != q->min_refresh_time) return 0;
1048 	if(!booleq(p->min_refresh_time_is_default,
1049 		q->min_refresh_time_is_default)) return 0;
1050 	if(p->max_retry_time != q->max_retry_time) return 0;
1051 	if(!booleq(p->max_retry_time_is_default,
1052 		q->max_retry_time_is_default)) return 0;
1053 	if(p->min_retry_time != q->min_retry_time) return 0;
1054 	if(!booleq(p->min_retry_time_is_default,
1055 		q->min_retry_time_is_default)) return 0;
1056 #ifdef RATELIMIT
1057 	if(p->rrl_whitelist != q->rrl_whitelist) return 0;
1058 #endif
1059 	if(!booleq(p->multi_master_check,q->multi_master_check)) return 0;
1060 	if(p->size_limit_xfr != q->size_limit_xfr) return 0;
1061 	return 1;
1062 }
1063 
1064 static void
1065 marshal_u8(struct buffer* b, uint8_t v)
1066 {
1067 	buffer_reserve(b, 1);
1068 	buffer_write_u8(b, v);
1069 }
1070 
1071 static uint8_t
1072 unmarshal_u8(struct buffer* b)
1073 {
1074 	return buffer_read_u8(b);
1075 }
1076 
1077 static void
1078 marshal_u64(struct buffer* b, uint64_t v)
1079 {
1080 	buffer_reserve(b, 8);
1081 	buffer_write_u64(b, v);
1082 }
1083 
1084 static uint64_t
1085 unmarshal_u64(struct buffer* b)
1086 {
1087 	return buffer_read_u64(b);
1088 }
1089 
1090 #ifdef RATELIMIT
1091 static void
1092 marshal_u16(struct buffer* b, uint16_t v)
1093 {
1094 	buffer_reserve(b, 2);
1095 	buffer_write_u16(b, v);
1096 }
1097 #endif
1098 
1099 #ifdef RATELIMIT
1100 static uint16_t
1101 unmarshal_u16(struct buffer* b)
1102 {
1103 	return buffer_read_u16(b);
1104 }
1105 #endif
1106 
1107 static void
1108 marshal_u32(struct buffer* b, uint32_t v)
1109 {
1110 	buffer_reserve(b, 4);
1111 	buffer_write_u32(b, v);
1112 }
1113 
1114 static uint32_t
1115 unmarshal_u32(struct buffer* b)
1116 {
1117 	return buffer_read_u32(b);
1118 }
1119 
1120 static void
1121 marshal_str(struct buffer* b, const char* s)
1122 {
1123 	if(!s) marshal_u8(b, 0);
1124 	else {
1125 		size_t len = strlen(s);
1126 		marshal_u8(b, 1);
1127 		buffer_reserve(b, len+1);
1128 		buffer_write(b, s, len+1);
1129 	}
1130 }
1131 
1132 static char*
1133 unmarshal_str(region_type* r, struct buffer* b)
1134 {
1135 	uint8_t nonnull = unmarshal_u8(b);
1136 	if(nonnull) {
1137 		char* result = region_strdup(r, (char*)buffer_current(b));
1138 		size_t len = strlen((char*)buffer_current(b));
1139 		buffer_skip(b, len+1);
1140 		return result;
1141 	} else return NULL;
1142 }
1143 
1144 static void
1145 marshal_acl(struct buffer* b, struct acl_options* acl)
1146 {
1147 	buffer_reserve(b, sizeof(*acl));
1148 	buffer_write(b, acl, sizeof(*acl));
1149 	marshal_str(b, acl->ip_address_spec);
1150 	marshal_str(b, acl->key_name);
1151 }
1152 
1153 static struct acl_options*
1154 unmarshal_acl(region_type* r, struct buffer* b)
1155 {
1156 	struct acl_options* acl = (struct acl_options*)region_alloc(r,
1157 		sizeof(*acl));
1158 	buffer_read(b, acl, sizeof(*acl));
1159 	acl->next = NULL;
1160 	acl->key_options = NULL;
1161 	acl->ip_address_spec = unmarshal_str(r, b);
1162 	acl->key_name = unmarshal_str(r, b);
1163 	return acl;
1164 }
1165 
1166 static void
1167 marshal_acl_list(struct buffer* b, struct acl_options* list)
1168 {
1169 	while(list) {
1170 		marshal_u8(b, 1); /* is there a next one marker */
1171 		marshal_acl(b, list);
1172 		list = list->next;
1173 	}
1174 	marshal_u8(b, 0); /* end of list marker */
1175 }
1176 
1177 static struct acl_options*
1178 unmarshal_acl_list(region_type* r, struct buffer* b)
1179 {
1180 	struct acl_options* a, *last=NULL, *list=NULL;
1181 	while(unmarshal_u8(b)) {
1182 		a = unmarshal_acl(r, b);
1183 		/* link in */
1184 		a->next = NULL;
1185 		if(!list) list = a;
1186 		else last->next = a;
1187 		last = a;
1188 	}
1189 	return list;
1190 }
1191 
1192 void
1193 pattern_options_marshal(struct buffer* b, struct pattern_options* p)
1194 {
1195 	marshal_str(b, p->pname);
1196 	marshal_str(b, p->zonefile);
1197 	marshal_str(b, p->zonestats);
1198 #ifdef RATELIMIT
1199 	marshal_u16(b, p->rrl_whitelist);
1200 #endif
1201 	marshal_u8(b, p->allow_axfr_fallback);
1202 	marshal_u8(b, p->allow_axfr_fallback_is_default);
1203 	marshal_u8(b, p->notify_retry);
1204 	marshal_u8(b, p->notify_retry_is_default);
1205 	marshal_u8(b, p->implicit);
1206 	marshal_u64(b, p->size_limit_xfr);
1207 	marshal_acl_list(b, p->allow_notify);
1208 	marshal_acl_list(b, p->request_xfr);
1209 	marshal_acl_list(b, p->notify);
1210 	marshal_acl_list(b, p->provide_xfr);
1211 	marshal_acl_list(b, p->outgoing_interface);
1212 	marshal_u32(b, p->max_refresh_time);
1213 	marshal_u8(b, p->max_refresh_time_is_default);
1214 	marshal_u32(b, p->min_refresh_time);
1215 	marshal_u8(b, p->min_refresh_time_is_default);
1216 	marshal_u32(b, p->max_retry_time);
1217 	marshal_u8(b, p->max_retry_time_is_default);
1218 	marshal_u32(b, p->min_retry_time);
1219 	marshal_u8(b, p->min_retry_time_is_default);
1220 	marshal_u8(b, p->multi_master_check);
1221 }
1222 
1223 struct pattern_options*
1224 pattern_options_unmarshal(region_type* r, struct buffer* b)
1225 {
1226 	struct pattern_options* p = pattern_options_create(r);
1227 	p->pname = unmarshal_str(r, b);
1228 	p->zonefile = unmarshal_str(r, b);
1229 	p->zonestats = unmarshal_str(r, b);
1230 #ifdef RATELIMIT
1231 	p->rrl_whitelist = unmarshal_u16(b);
1232 #endif
1233 	p->allow_axfr_fallback = unmarshal_u8(b);
1234 	p->allow_axfr_fallback_is_default = unmarshal_u8(b);
1235 	p->notify_retry = unmarshal_u8(b);
1236 	p->notify_retry_is_default = unmarshal_u8(b);
1237 	p->implicit = unmarshal_u8(b);
1238 	p->size_limit_xfr = unmarshal_u64(b);
1239 	p->allow_notify = unmarshal_acl_list(r, b);
1240 	p->request_xfr = unmarshal_acl_list(r, b);
1241 	p->notify = unmarshal_acl_list(r, b);
1242 	p->provide_xfr = unmarshal_acl_list(r, b);
1243 	p->outgoing_interface = unmarshal_acl_list(r, b);
1244 	p->max_refresh_time = unmarshal_u32(b);
1245 	p->max_refresh_time_is_default = unmarshal_u8(b);
1246 	p->min_refresh_time = unmarshal_u32(b);
1247 	p->min_refresh_time_is_default = unmarshal_u8(b);
1248 	p->max_retry_time = unmarshal_u32(b);
1249 	p->max_retry_time_is_default = unmarshal_u8(b);
1250 	p->min_retry_time = unmarshal_u32(b);
1251 	p->min_retry_time_is_default = unmarshal_u8(b);
1252 	p->multi_master_check = unmarshal_u8(b);
1253 	return p;
1254 }
1255 
1256 struct key_options*
1257 key_options_create(region_type* region)
1258 {
1259 	struct key_options* key;
1260 	key = (struct key_options*)region_alloc_zero(region,
1261 		sizeof(struct key_options));
1262 	return key;
1263 }
1264 
1265 void
1266 key_options_insert(struct nsd_options* opt, struct key_options* key)
1267 {
1268 	if(!key->name) return;
1269 	key->node.key = key->name;
1270 	(void)rbtree_insert(opt->keys, &key->node);
1271 }
1272 
1273 struct key_options*
1274 key_options_find(struct nsd_options* opt, const char* name)
1275 {
1276 	return (struct key_options*)rbtree_search(opt->keys, name);
1277 }
1278 
1279 /** remove tsig_key contents */
1280 void
1281 key_options_desetup(region_type* region, struct key_options* key)
1282 {
1283 	/* keep tsig_key pointer so that existing references keep valid */
1284 	if(!key->tsig_key)
1285 		return;
1286 	/* name stays the same */
1287 	if(key->tsig_key->data) {
1288 		/* wipe secret! */
1289 		memset(key->tsig_key->data, 0xdd, key->tsig_key->size);
1290 		region_recycle(region, key->tsig_key->data,
1291 			key->tsig_key->size);
1292 		key->tsig_key->data = NULL;
1293 		key->tsig_key->size = 0;
1294 	}
1295 }
1296 
1297 /** add tsig_key contents */
1298 void
1299 key_options_setup(region_type* region, struct key_options* key)
1300 {
1301 	uint8_t data[16384]; /* 16KB */
1302 	int size;
1303 	if(!key->tsig_key) {
1304 		/* create it */
1305 		key->tsig_key = (tsig_key_type *) region_alloc(region,
1306 			sizeof(tsig_key_type));
1307 		/* create name */
1308 		key->tsig_key->name = dname_parse(region, key->name);
1309 		if(!key->tsig_key->name) {
1310 			log_msg(LOG_ERR, "Failed to parse tsig key name %s",
1311 				key->name);
1312 			/* key and base64 were checked during syntax parse */
1313 			exit(1);
1314 		}
1315 		key->tsig_key->size = 0;
1316 		key->tsig_key->data = NULL;
1317 	}
1318 	size = b64_pton(key->secret, data, sizeof(data));
1319 	if(size == -1) {
1320 		log_msg(LOG_ERR, "Failed to parse tsig key data %s",
1321 			key->name);
1322 		/* key and base64 were checked during syntax parse */
1323 		exit(1);
1324 	}
1325 	key->tsig_key->size = size;
1326 	key->tsig_key->data = (uint8_t *)region_alloc_init(region, data, size);
1327 }
1328 
1329 void
1330 key_options_remove(struct nsd_options* opt, const char* name)
1331 {
1332 	struct key_options* k = key_options_find(opt, name);
1333 	if(!k) return;
1334 	(void)rbtree_delete(opt->keys, name);
1335 	if(k->name)
1336 		region_recycle(opt->region, k->name, strlen(k->name)+1);
1337 	if(k->algorithm)
1338 		region_recycle(opt->region, k->algorithm, strlen(k->algorithm)+1);
1339 	if(k->secret) {
1340 		memset(k->secret, 0xdd, strlen(k->secret)); /* wipe secret! */
1341 		region_recycle(opt->region, k->secret, strlen(k->secret)+1);
1342 	}
1343 	if(k->tsig_key) {
1344 		tsig_del_key(k->tsig_key);
1345 		if(k->tsig_key->name)
1346 			region_recycle(opt->region, (void*)k->tsig_key->name,
1347 				dname_total_size(k->tsig_key->name));
1348 		key_options_desetup(opt->region, k);
1349 		region_recycle(opt->region, k->tsig_key, sizeof(tsig_key_type));
1350 	}
1351 	region_recycle(opt->region, k, sizeof(struct key_options));
1352 }
1353 
1354 int
1355 key_options_equal(struct key_options* p, struct key_options* q)
1356 {
1357 	return strcmp(p->name, q->name)==0 && strcmp(p->algorithm,
1358 		q->algorithm)==0 && strcmp(p->secret, q->secret)==0;
1359 }
1360 
1361 void
1362 key_options_add_modify(struct nsd_options* opt, struct key_options* key)
1363 {
1364 	struct key_options* orig = key_options_find(opt, key->name);
1365 	if(!orig) {
1366 		/* needs to be copied to opt region */
1367 		orig = key_options_create(opt->region);
1368 		orig->name = region_strdup(opt->region, key->name);
1369 		orig->algorithm = region_strdup(opt->region, key->algorithm);
1370 		orig->secret = region_strdup(opt->region, key->secret);
1371 		key_options_setup(opt->region, orig);
1372 		tsig_add_key(orig->tsig_key);
1373 		key_options_insert(opt, orig);
1374 	} else {
1375 		/* modify entries in existing key, and copy to opt region */
1376 		key_options_desetup(opt->region, orig);
1377 		region_recycle(opt->region, orig->algorithm,
1378 			strlen(orig->algorithm)+1);
1379 		orig->algorithm = region_strdup(opt->region, key->algorithm);
1380 		region_recycle(opt->region, orig->secret,
1381 			strlen(orig->secret)+1);
1382 		orig->secret = region_strdup(opt->region, key->secret);
1383 		key_options_setup(opt->region, orig);
1384 	}
1385 }
1386 
1387 int
1388 acl_check_incoming(struct acl_options* acl, struct query* q,
1389 	struct acl_options** reason)
1390 {
1391 	/* check each acl element.
1392 	   if 1 blocked element matches - return -1.
1393 	   if any element matches - return number.
1394 	   else return -1. */
1395 	int found_match = -1;
1396 	int number = 0;
1397 	struct acl_options* match = 0;
1398 
1399 	if(reason)
1400 		*reason = NULL;
1401 
1402 	while(acl)
1403 	{
1404 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "testing acl %s %s",
1405 			acl->ip_address_spec, acl->nokey?"NOKEY":
1406 			(acl->blocked?"BLOCKED":acl->key_name)));
1407 		if(acl_addr_matches(acl, q) && acl_key_matches(acl, q)) {
1408 			if(!match)
1409 			{
1410 				match = acl; /* remember first match */
1411 				found_match=number;
1412 			}
1413 			if(acl->blocked) {
1414 				if(reason)
1415 					*reason = acl;
1416 				return -1;
1417 			}
1418 		}
1419 		number++;
1420 		acl = acl->next;
1421 	}
1422 
1423 	if(reason)
1424 		*reason = match;
1425 	return found_match;
1426 }
1427 
1428 #ifdef INET6
1429 int
1430 acl_addr_matches_ipv6host(struct acl_options* acl, struct sockaddr_storage* addr_storage, unsigned int port)
1431 {
1432 	struct sockaddr_in6* addr = (struct sockaddr_in6*)addr_storage;
1433 	if(acl->port != 0 && acl->port != port)
1434 		return 0;
1435 	switch(acl->rangetype) {
1436 	case acl_range_mask:
1437 	case acl_range_subnet:
1438 		if(!acl_addr_match_mask((uint32_t*)&acl->addr.addr6, (uint32_t*)&addr->sin6_addr,
1439 			(uint32_t*)&acl->range_mask.addr6, sizeof(struct in6_addr)))
1440 			return 0;
1441 		break;
1442 	case acl_range_minmax:
1443 		if(!acl_addr_match_range((uint32_t*)&acl->addr.addr6, (uint32_t*)&addr->sin6_addr,
1444 			(uint32_t*)&acl->range_mask.addr6, sizeof(struct in6_addr)))
1445 			return 0;
1446 		break;
1447 	case acl_range_single:
1448 	default:
1449 		if(memcmp(&addr->sin6_addr, &acl->addr.addr6,
1450 			sizeof(struct in6_addr)) != 0)
1451 			return 0;
1452 		break;
1453 	}
1454 	return 1;
1455 }
1456 #endif
1457 
1458 int
1459 acl_addr_matches_ipv4host(struct acl_options* acl, struct sockaddr_in* addr, unsigned int port)
1460 {
1461 	if(acl->port != 0 && acl->port != port)
1462 		return 0;
1463 	switch(acl->rangetype) {
1464 	case acl_range_mask:
1465 	case acl_range_subnet:
1466 		if(!acl_addr_match_mask((uint32_t*)&acl->addr.addr, (uint32_t*)&addr->sin_addr,
1467 			(uint32_t*)&acl->range_mask.addr, sizeof(struct in_addr)))
1468 			return 0;
1469 		break;
1470 	case acl_range_minmax:
1471 		if(!acl_addr_match_range((uint32_t*)&acl->addr.addr, (uint32_t*)&addr->sin_addr,
1472 			(uint32_t*)&acl->range_mask.addr, sizeof(struct in_addr)))
1473 			return 0;
1474 		break;
1475 	case acl_range_single:
1476 	default:
1477 		if(memcmp(&addr->sin_addr, &acl->addr.addr,
1478 			sizeof(struct in_addr)) != 0)
1479 			return 0;
1480 		break;
1481 	}
1482 	return 1;
1483 }
1484 
1485 int
1486 acl_addr_matches_host(struct acl_options* acl, struct acl_options* host)
1487 {
1488 	if(acl->is_ipv6)
1489 	{
1490 #ifdef INET6
1491 		struct sockaddr_storage* addr = (struct sockaddr_storage*)&host->addr;
1492 		if(!host->is_ipv6) return 0;
1493 		return acl_addr_matches_ipv6host(acl, addr, host->port);
1494 #else
1495 		return 0; /* no inet6, no match */
1496 #endif
1497 	}
1498 	else
1499 	{
1500 		struct sockaddr_in* addr = (struct sockaddr_in*)&host->addr;
1501 		if(host->is_ipv6) return 0;
1502 		return acl_addr_matches_ipv4host(acl, addr, host->port);
1503 	}
1504 	/* ENOTREACH */
1505 	return 0;
1506 }
1507 
1508 int
1509 acl_addr_matches(struct acl_options* acl, struct query* q)
1510 {
1511 	if(acl->is_ipv6)
1512 	{
1513 #ifdef INET6
1514 		struct sockaddr_storage* addr = (struct sockaddr_storage*)&q->addr;
1515 		if(addr->ss_family != AF_INET6)
1516 			return 0;
1517 		return acl_addr_matches_ipv6host(acl, addr, ntohs(((struct sockaddr_in6*)addr)->sin6_port));
1518 #else
1519 		return 0; /* no inet6, no match */
1520 #endif
1521 	}
1522 	else
1523 	{
1524 		struct sockaddr_in* addr = (struct sockaddr_in*)&q->addr;
1525 		if(addr->sin_family != AF_INET)
1526 			return 0;
1527 		return acl_addr_matches_ipv4host(acl, addr, ntohs(addr->sin_port));
1528 	}
1529 	/* ENOTREACH */
1530 	return 0;
1531 }
1532 
1533 int
1534 acl_addr_match_mask(uint32_t* a, uint32_t* b, uint32_t* mask, size_t sz)
1535 {
1536 	size_t i;
1537 #ifndef NDEBUG
1538 	assert(sz % 4 == 0);
1539 #endif
1540 	sz /= 4;
1541 	for(i=0; i<sz; ++i)
1542 	{
1543 		if(((*a++)&*mask) != ((*b++)&*mask))
1544 			return 0;
1545 		++mask;
1546 	}
1547 	return 1;
1548 }
1549 
1550 int
1551 acl_addr_match_range(uint32_t* minval, uint32_t* x, uint32_t* maxval, size_t sz)
1552 {
1553 	size_t i;
1554 	uint8_t checkmin = 1, checkmax = 1;
1555 #ifndef NDEBUG
1556 	assert(sz % 4 == 0);
1557 #endif
1558 	/* check treats x as one huge number */
1559 	sz /= 4;
1560 	for(i=0; i<sz; ++i)
1561 	{
1562 		/* if outside bounds, we are done */
1563 		if(checkmin)
1564 			if(minval[i] > x[i])
1565 				return 0;
1566 		if(checkmax)
1567 			if(maxval[i] < x[i])
1568 				return 0;
1569 		/* if x is equal to a bound, that bound needs further checks */
1570 		if(checkmin && minval[i]!=x[i])
1571 			checkmin = 0;
1572 		if(checkmax && maxval[i]!=x[i])
1573 			checkmax = 0;
1574 		if(!checkmin && !checkmax)
1575 			return 1; /* will always match */
1576 	}
1577 	return 1;
1578 }
1579 
1580 int
1581 acl_key_matches(struct acl_options* acl, struct query* q)
1582 {
1583 	if(acl->blocked)
1584 		return 1;
1585 	if(acl->nokey) {
1586 		if(q->tsig.status == TSIG_NOT_PRESENT)
1587 			return 1;
1588 		return 0;
1589 	}
1590 	/* check name of tsig key */
1591 	if(q->tsig.status != TSIG_OK) {
1592 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "keymatch fail query has no TSIG"));
1593 		return 0; /* query has no TSIG */
1594 	}
1595 	if(q->tsig.error_code != TSIG_ERROR_NOERROR) {
1596 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "keymatch fail, tsig has error"));
1597 		return 0; /* some tsig error */
1598 	}
1599 	if(!acl->key_options->tsig_key) {
1600 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "keymatch fail no config"));
1601 		return 0; /* key not properly configured */
1602 	}
1603 	if(dname_compare(q->tsig.key_name,
1604 		acl->key_options->tsig_key->name) != 0) {
1605 		DEBUG(DEBUG_XFRD,2, (LOG_INFO, "keymatch fail wrong key name"));
1606 		return 0; /* wrong key name */
1607 	}
1608 	if(tsig_strlowercmp(q->tsig.algorithm->short_name,
1609 		acl->key_options->algorithm) != 0 && (
1610 		strncmp("hmac-", q->tsig.algorithm->short_name, 5) != 0 ||
1611 		tsig_strlowercmp(q->tsig.algorithm->short_name+5,
1612 		acl->key_options->algorithm) != 0) ) {
1613 		DEBUG(DEBUG_XFRD,2, (LOG_ERR, "query tsig wrong algorithm"));
1614 		return 0; /* no such algo */
1615 	}
1616 	return 1;
1617 }
1618 
1619 int
1620 acl_same_host(struct acl_options* a, struct acl_options* b)
1621 {
1622 	if(a->is_ipv6 && !b->is_ipv6)
1623 		return 0;
1624 	if(!a->is_ipv6 && b->is_ipv6)
1625 		return 0;
1626 	if(a->port != b->port)
1627 		return 0;
1628 	if(a->rangetype != b->rangetype)
1629 		return 0;
1630 	if(!a->is_ipv6) {
1631 		if(memcmp(&a->addr.addr, &b->addr.addr,
1632 		   sizeof(struct in_addr)) != 0)
1633 			return 0;
1634 		if(a->rangetype != acl_range_single &&
1635 		   memcmp(&a->range_mask.addr, &b->range_mask.addr,
1636 		   sizeof(struct in_addr)) != 0)
1637 			return 0;
1638 	} else {
1639 #ifdef INET6
1640 		if(memcmp(&a->addr.addr6, &b->addr.addr6,
1641 		   sizeof(struct in6_addr)) != 0)
1642 			return 0;
1643 		if(a->rangetype != acl_range_single &&
1644 		   memcmp(&a->range_mask.addr6, &b->range_mask.addr6,
1645 		   sizeof(struct in6_addr)) != 0)
1646 			return 0;
1647 #else
1648 		return 0;
1649 #endif
1650 	}
1651 	return 1;
1652 }
1653 
1654 #if defined(HAVE_SSL)
1655 void
1656 key_options_tsig_add(struct nsd_options* opt)
1657 {
1658 	struct key_options* optkey;
1659 	RBTREE_FOR(optkey, struct key_options*, opt->keys) {
1660 		key_options_setup(opt->region, optkey);
1661 		tsig_add_key(optkey->tsig_key);
1662 	}
1663 }
1664 #endif
1665 
1666 int
1667 zone_is_slave(struct zone_options* opt)
1668 {
1669 	return opt && opt->pattern && opt->pattern->request_xfr != 0;
1670 }
1671 
1672 /* get a character in string (or replacement char if not long enough) */
1673 static const char*
1674 get_char(const char* str, size_t i)
1675 {
1676 	static char res[2];
1677 	if(i >= strlen(str))
1678 		return ".";
1679 	res[0] = str[i];
1680 	res[1] = 0;
1681 	return res;
1682 }
1683 /* get end label of the zone name (or .) */
1684 static const char*
1685 get_end_label(struct zone_options* zone, int i)
1686 {
1687 	const dname_type* d = (const dname_type*)zone->node.key;
1688 	if(i >= d->label_count) {
1689 		return ".";
1690 	}
1691 	return wirelabel2str(dname_label(d, i));
1692 }
1693 /* replace occurrences of one with two */
1694 void
1695 replace_str(char* str, size_t len, const char* one, const char* two)
1696 {
1697 	char* pos;
1698 	char* at = str;
1699 	while( (pos=strstr(at, one)) ) {
1700 		if(strlen(str)+strlen(two)-strlen(one) >= len)
1701 			return; /* no more space to replace */
1702 		/* stuff before pos is fine */
1703 		/* move the stuff after pos to make space for two, add
1704 		 * one to length of remainder to also copy the 0 byte end */
1705 		memmove(pos+strlen(two), pos+strlen(one),
1706 			strlen(pos+strlen(one))+1);
1707 		/* copy in two */
1708 		memmove(pos, two, strlen(two));
1709 		/* at is end of the newly inserted two (avoids recursion if
1710 		 * two contains one) */
1711 		at = pos+strlen(two);
1712 	}
1713 }
1714 
1715 const char*
1716 config_cook_string(struct zone_options* zone, const char* input)
1717 {
1718 	static char f[1024];
1719 	/* if not a template, return as-is */
1720 	if(!strchr(input, '%')) {
1721 		return input;
1722 	}
1723 	strlcpy(f, input, sizeof(f));
1724 	if(strstr(f, "%1"))
1725 		replace_str(f, sizeof(f), "%1", get_char(zone->name, 0));
1726 	if(strstr(f, "%2"))
1727 		replace_str(f, sizeof(f), "%2", get_char(zone->name, 1));
1728 	if(strstr(f, "%3"))
1729 		replace_str(f, sizeof(f), "%3", get_char(zone->name, 2));
1730 	if(strstr(f, "%z"))
1731 		replace_str(f, sizeof(f), "%z", get_end_label(zone, 1));
1732 	if(strstr(f, "%y"))
1733 		replace_str(f, sizeof(f), "%y", get_end_label(zone, 2));
1734 	if(strstr(f, "%x"))
1735 		replace_str(f, sizeof(f), "%x", get_end_label(zone, 3));
1736 	if(strstr(f, "%s"))
1737 		replace_str(f, sizeof(f), "%s", zone->name);
1738 	return f;
1739 }
1740 
1741 const char*
1742 config_make_zonefile(struct zone_options* zone, struct nsd* nsd)
1743 {
1744 	static char f[1024];
1745 	/* if not a template, return as-is */
1746 	if(!strchr(zone->pattern->zonefile, '%')) {
1747 		if (nsd->chrootdir && nsd->chrootdir[0] &&
1748 			zone->pattern->zonefile &&
1749 			zone->pattern->zonefile[0] == '/' &&
1750 			strncmp(zone->pattern->zonefile, nsd->chrootdir,
1751 			strlen(nsd->chrootdir)) == 0)
1752 			/* -1 because chrootdir ends in trailing slash */
1753 			return zone->pattern->zonefile + strlen(nsd->chrootdir) - 1;
1754 		return zone->pattern->zonefile;
1755 	}
1756 	strlcpy(f, zone->pattern->zonefile, sizeof(f));
1757 	if(strstr(f, "%1"))
1758 		replace_str(f, sizeof(f), "%1", get_char(zone->name, 0));
1759 	if(strstr(f, "%2"))
1760 		replace_str(f, sizeof(f), "%2", get_char(zone->name, 1));
1761 	if(strstr(f, "%3"))
1762 		replace_str(f, sizeof(f), "%3", get_char(zone->name, 2));
1763 	if(strstr(f, "%z"))
1764 		replace_str(f, sizeof(f), "%z", get_end_label(zone, 1));
1765 	if(strstr(f, "%y"))
1766 		replace_str(f, sizeof(f), "%y", get_end_label(zone, 2));
1767 	if(strstr(f, "%x"))
1768 		replace_str(f, sizeof(f), "%x", get_end_label(zone, 3));
1769 	if(strstr(f, "%s"))
1770 		replace_str(f, sizeof(f), "%s", zone->name);
1771 	if (nsd->chrootdir && nsd->chrootdir[0] && f[0] == '/' &&
1772 		strncmp(f, nsd->chrootdir, strlen(nsd->chrootdir)) == 0)
1773 		/* -1 because chrootdir ends in trailing slash */
1774 		return f + strlen(nsd->chrootdir) - 1;
1775 	return f;
1776 }
1777 
1778 struct zone_options*
1779 zone_options_find(struct nsd_options* opt, const struct dname* apex)
1780 {
1781 	return (struct zone_options*) rbtree_search(opt->zone_options, apex);
1782 }
1783 
1784 struct acl_options*
1785 acl_find_num(struct acl_options* acl, int num)
1786 {
1787 	int count = num;
1788 	if(num < 0)
1789 		return 0;
1790 	while(acl && count > 0) {
1791 		acl = acl->next;
1792 		count--;
1793 	}
1794 	if(count == 0)
1795 		return acl;
1796 	return 0;
1797 }
1798 
1799 /* true if ipv6 address, false if ipv4 */
1800 int
1801 parse_acl_is_ipv6(const char* p)
1802 {
1803 	/* see if addr is ipv6 or ipv4 -- by : and . */
1804 	while(*p) {
1805 		if(*p == '.') return 0;
1806 		if(*p == ':') return 1;
1807 		++p;
1808 	}
1809 	return 0;
1810 }
1811 
1812 /* returns range type. mask is the 2nd part of the range */
1813 int
1814 parse_acl_range_type(char* ip, char** mask)
1815 {
1816 	char *p;
1817 	if((p=strchr(ip, '&'))!=0) {
1818 		*p = 0;
1819 		*mask = p+1;
1820 		return acl_range_mask;
1821 	}
1822 	if((p=strchr(ip, '/'))!=0) {
1823 		*p = 0;
1824 		*mask = p+1;
1825 		return acl_range_subnet;
1826 	}
1827 	if((p=strchr(ip, '-'))!=0) {
1828 		*p = 0;
1829 		*mask = p+1;
1830 		return acl_range_minmax;
1831 	}
1832 	*mask = 0;
1833 	return acl_range_single;
1834 }
1835 
1836 /* parses subnet mask, fills 0 mask as well */
1837 void
1838 parse_acl_range_subnet(char* p, void* addr, int maxbits)
1839 {
1840 	int subnet_bits = atoi(p);
1841 	uint8_t* addr_bytes = (uint8_t*)addr;
1842 	if(subnet_bits == 0 && strcmp(p, "0")!=0) {
1843 		c_error_msg("bad subnet range '%s'", p);
1844 		return;
1845 	}
1846 	if(subnet_bits < 0 || subnet_bits > maxbits) {
1847 		c_error_msg("subnet of %d bits out of range [0..%d]", subnet_bits, maxbits);
1848 		return;
1849 	}
1850 	/* fill addr with n bits of 1s (struct has been zeroed) */
1851 	while(subnet_bits >= 8) {
1852 		*addr_bytes++ = 0xff;
1853 		subnet_bits -= 8;
1854 	}
1855 	if(subnet_bits > 0) {
1856 		uint8_t shifts[] = {0x0, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
1857 		*addr_bytes = shifts[subnet_bits];
1858 	}
1859 }
1860 
1861 struct acl_options*
1862 parse_acl_info(region_type* region, char* ip, const char* key)
1863 {
1864 	char* p;
1865 	struct acl_options* acl = (struct acl_options*)region_alloc(region,
1866 		sizeof(struct acl_options));
1867 	acl->next = 0;
1868 	/* ip */
1869 	acl->ip_address_spec = region_strdup(region, ip);
1870 	acl->use_axfr_only = 0;
1871 	acl->allow_udp = 0;
1872 	acl->ixfr_disabled = 0;
1873 	acl->bad_xfr_count = 0;
1874 	acl->key_options = 0;
1875 	acl->is_ipv6 = 0;
1876 	acl->port = 0;
1877 	memset(&acl->addr, 0, sizeof(union acl_addr_storage));
1878 	memset(&acl->range_mask, 0, sizeof(union acl_addr_storage));
1879 	if((p=strrchr(ip, '@'))!=0) {
1880 		if(atoi(p+1) == 0) c_error("expected port number after '@'");
1881 		else acl->port = atoi(p+1);
1882 		*p=0;
1883 	}
1884 	acl->rangetype = parse_acl_range_type(ip, &p);
1885 	if(parse_acl_is_ipv6(ip)) {
1886 		acl->is_ipv6 = 1;
1887 #ifdef INET6
1888 		if(inet_pton(AF_INET6, ip, &acl->addr.addr6) != 1)
1889 			c_error_msg("Bad ip6 address '%s'", ip);
1890 		if(acl->rangetype==acl_range_mask || acl->rangetype==acl_range_minmax)
1891 			if(inet_pton(AF_INET6, p, &acl->range_mask.addr6) != 1)
1892 				c_error_msg("Bad ip6 address mask '%s'", p);
1893 		if(acl->rangetype==acl_range_subnet)
1894 			parse_acl_range_subnet(p, &acl->range_mask.addr6, 128);
1895 #else
1896 		c_error_msg("encountered IPv6 address '%s'.", ip);
1897 #endif /* INET6 */
1898 	} else {
1899 		acl->is_ipv6 = 0;
1900 		if(inet_pton(AF_INET, ip, &acl->addr.addr) != 1)
1901 			c_error_msg("Bad ip4 address '%s'", ip);
1902 		if(acl->rangetype==acl_range_mask || acl->rangetype==acl_range_minmax)
1903 			if(inet_pton(AF_INET, p, &acl->range_mask.addr) != 1)
1904 				c_error_msg("Bad ip4 address mask '%s'", p);
1905 		if(acl->rangetype==acl_range_subnet)
1906 			parse_acl_range_subnet(p, &acl->range_mask.addr, 32);
1907 	}
1908 
1909 	/* key */
1910 	if(strcmp(key, "NOKEY")==0) {
1911 		acl->nokey = 1;
1912 		acl->blocked = 0;
1913 		acl->key_name = 0;
1914 	} else if(strcmp(key, "BLOCKED")==0) {
1915 		acl->nokey = 0;
1916 		acl->blocked = 1;
1917 		acl->key_name = 0;
1918 	} else {
1919 		acl->nokey = 0;
1920 		acl->blocked = 0;
1921 		acl->key_name = region_strdup(region, key);
1922 	}
1923 	return acl;
1924 }
1925 
1926 /* copy acl list at end of parser start, update current */
1927 static
1928 void append_acl(struct acl_options** start, struct acl_options** cur,
1929 	struct acl_options* list)
1930 {
1931 	while(list) {
1932 		struct acl_options* acl = copy_acl(cfg_parser->opt->region,
1933 			list);
1934 		acl->next = NULL;
1935 		if(*cur)
1936 			(*cur)->next = acl;
1937 		else	*start = acl;
1938 		*cur = acl;
1939 		list = list->next;
1940 	}
1941 }
1942 
1943 void
1944 config_apply_pattern(const char* name)
1945 {
1946 	/* find the pattern */
1947 	struct pattern_options* pat = pattern_options_find(cfg_parser->opt,
1948 		name);
1949 	struct pattern_options* a = cfg_parser->current_pattern;
1950 	if(!pat) {
1951 		c_error_msg("could not find pattern %s", name);
1952 		return;
1953 	}
1954 
1955 	/* apply settings */
1956 	if(pat->zonefile)
1957 		a->zonefile = region_strdup(cfg_parser->opt->region,
1958 			pat->zonefile);
1959 	if(pat->zonestats)
1960 		a->zonestats = region_strdup(cfg_parser->opt->region,
1961 			pat->zonestats);
1962 	if(!pat->allow_axfr_fallback_is_default) {
1963 		a->allow_axfr_fallback = pat->allow_axfr_fallback;
1964 		a->allow_axfr_fallback_is_default = 0;
1965 	}
1966 	if(!pat->notify_retry_is_default) {
1967 		a->notify_retry = pat->notify_retry;
1968 		a->notify_retry_is_default = 0;
1969 	}
1970 	if(!pat->max_refresh_time_is_default) {
1971 		a->max_refresh_time = pat->max_refresh_time;
1972 		a->max_refresh_time_is_default = 0;
1973 	}
1974 	if(!pat->min_refresh_time_is_default) {
1975 		a->min_refresh_time = pat->min_refresh_time;
1976 		a->min_refresh_time_is_default = 0;
1977 	}
1978 	if(!pat->max_retry_time_is_default) {
1979 		a->max_retry_time = pat->max_retry_time;
1980 		a->max_retry_time_is_default = 0;
1981 	}
1982 	if(!pat->min_retry_time_is_default) {
1983 		a->min_retry_time = pat->min_retry_time;
1984 		a->min_retry_time_is_default = 0;
1985 	}
1986 	a->size_limit_xfr = pat->size_limit_xfr;
1987 #ifdef RATELIMIT
1988 	a->rrl_whitelist |= pat->rrl_whitelist;
1989 #endif
1990 	/* append acl items */
1991 	append_acl(&a->allow_notify, &cfg_parser->current_allow_notify,
1992 		pat->allow_notify);
1993 	append_acl(&a->request_xfr, &cfg_parser->current_request_xfr,
1994 		pat->request_xfr);
1995 	append_acl(&a->notify, &cfg_parser->current_notify, pat->notify);
1996 	append_acl(&a->provide_xfr, &cfg_parser->current_provide_xfr,
1997 		pat->provide_xfr);
1998 	append_acl(&a->outgoing_interface, &cfg_parser->
1999 		current_outgoing_interface, pat->outgoing_interface);
2000 	if(pat->multi_master_check)
2001 		a->multi_master_check = pat->multi_master_check;
2002 }
2003 
2004 void
2005 nsd_options_destroy(struct nsd_options* opt)
2006 {
2007 	region_destroy(opt->region);
2008 }
2009 
2010 unsigned getzonestatid(struct nsd_options* opt, struct zone_options* zopt)
2011 {
2012 #ifdef USE_ZONE_STATS
2013 	const char* statname;
2014 	struct zonestatname* n;
2015 	rbnode_type* res;
2016 	/* try to find the instantiated zonestat name */
2017 	if(!zopt->pattern->zonestats || zopt->pattern->zonestats[0]==0)
2018 		return 0; /* no zone stats */
2019 	statname = config_cook_string(zopt, zopt->pattern->zonestats);
2020 	res = rbtree_search(opt->zonestatnames, statname);
2021 	if(res)
2022 		return ((struct zonestatname*)res)->id;
2023 	/* create it */
2024 	n = (struct zonestatname*)xalloc(sizeof(*n));
2025 	memset(n, 0, sizeof(*n));
2026 	n->node.key = strdup(statname);
2027 	if(!n->node.key) {
2028 		log_msg(LOG_ERR, "malloc failed: %s", strerror(errno));
2029 		exit(1);
2030 	}
2031 	n->id = (unsigned)(opt->zonestatnames->count);
2032 	rbtree_insert(opt->zonestatnames, (rbnode_type*)n);
2033 	return n->id;
2034 #else /* USE_ZONE_STATS */
2035 	(void)opt; (void)zopt;
2036 	return 0;
2037 #endif /* USE_ZONE_STATS */
2038 }
2039