xref: /freebsd/contrib/unbound/util/config_file.c (revision d93a896ef95946b0bf1219866fcb324b78543444)
1 /*
2  * util/config_file.c - reads and stores the config file for unbound.
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 for the config file.
40  */
41 
42 #include "config.h"
43 #include <ctype.h>
44 #include <stdarg.h>
45 #ifdef HAVE_TIME_H
46 #include <time.h>
47 #endif
48 #include "util/log.h"
49 #include "util/configyyrename.h"
50 #include "util/config_file.h"
51 #include "configparser.h"
52 #include "util/net_help.h"
53 #include "util/data/msgparse.h"
54 #include "util/module.h"
55 #include "util/regional.h"
56 #include "util/fptr_wlist.h"
57 #include "util/data/dname.h"
58 #include "util/rtt.h"
59 #include "services/cache/infra.h"
60 #include "sldns/wire2str.h"
61 #include "sldns/parseutil.h"
62 #ifdef HAVE_GLOB_H
63 # include <glob.h>
64 #endif
65 #ifdef HAVE_PWD_H
66 #include <pwd.h>
67 #endif
68 
69 /** from cfg username, after daemonise setup performed */
70 uid_t cfg_uid = (uid_t)-1;
71 /** from cfg username, after daemonise setup performed */
72 gid_t cfg_gid = (gid_t)-1;
73 /** for debug allow small timeout values for fast rollovers */
74 int autr_permit_small_holddown = 0;
75 
76 /** global config during parsing */
77 struct config_parser_state* cfg_parser = 0;
78 
79 /** init ports possible for use */
80 static void init_outgoing_availports(int* array, int num);
81 
82 struct config_file*
83 config_create(void)
84 {
85 	struct config_file* cfg;
86 	cfg = (struct config_file*)calloc(1, sizeof(struct config_file));
87 	if(!cfg)
88 		return NULL;
89 	/* the defaults if no config is present */
90 	cfg->verbosity = 1;
91 	cfg->stat_interval = 0;
92 	cfg->stat_cumulative = 0;
93 	cfg->stat_extended = 0;
94 	cfg->num_threads = 1;
95 	cfg->port = UNBOUND_DNS_PORT;
96 	cfg->do_ip4 = 1;
97 	cfg->do_ip6 = 1;
98 	cfg->do_udp = 1;
99 	cfg->do_tcp = 1;
100 	cfg->tcp_upstream = 0;
101 	cfg->tcp_mss = 0;
102 	cfg->outgoing_tcp_mss = 0;
103 	cfg->ssl_service_key = NULL;
104 	cfg->ssl_service_pem = NULL;
105 	cfg->ssl_port = 853;
106 	cfg->ssl_upstream = 0;
107 	cfg->use_syslog = 1;
108 	cfg->log_time_ascii = 0;
109 	cfg->log_queries = 0;
110 #ifndef USE_WINSOCK
111 #  ifdef USE_MINI_EVENT
112 	/* select max 1024 sockets */
113 	cfg->outgoing_num_ports = 960;
114 	cfg->num_queries_per_thread = 512;
115 #  else
116 	/* libevent can use many sockets */
117 	cfg->outgoing_num_ports = 4096;
118 	cfg->num_queries_per_thread = 1024;
119 #  endif
120 	cfg->outgoing_num_tcp = 10;
121 	cfg->incoming_num_tcp = 10;
122 #else
123 	cfg->outgoing_num_ports = 48; /* windows is limited in num fds */
124 	cfg->num_queries_per_thread = 24;
125 	cfg->outgoing_num_tcp = 2; /* leaves 64-52=12 for: 4if,1stop,thread4 */
126 	cfg->incoming_num_tcp = 2;
127 #endif
128 	cfg->edns_buffer_size = 4096; /* 4k from rfc recommendation */
129 	cfg->msg_buffer_size = 65552; /* 64 k + a small margin */
130 	cfg->msg_cache_size = 4 * 1024 * 1024;
131 	cfg->msg_cache_slabs = 4;
132 	cfg->jostle_time = 200;
133 	cfg->rrset_cache_size = 4 * 1024 * 1024;
134 	cfg->rrset_cache_slabs = 4;
135 	cfg->host_ttl = 900;
136 	cfg->bogus_ttl = 60;
137 	cfg->min_ttl = 0;
138 	cfg->max_ttl = 3600 * 24;
139 	cfg->max_negative_ttl = 3600;
140 	cfg->prefetch = 0;
141 	cfg->prefetch_key = 0;
142 	cfg->infra_cache_slabs = 4;
143 	cfg->infra_cache_numhosts = 10000;
144 	cfg->infra_cache_min_rtt = 50;
145 	cfg->delay_close = 0;
146 	if(!(cfg->outgoing_avail_ports = (int*)calloc(65536, sizeof(int))))
147 		goto error_exit;
148 	init_outgoing_availports(cfg->outgoing_avail_ports, 65536);
149 	if(!(cfg->username = strdup(UB_USERNAME))) goto error_exit;
150 #ifdef HAVE_CHROOT
151 	if(!(cfg->chrootdir = strdup(CHROOT_DIR))) goto error_exit;
152 #endif
153 	if(!(cfg->directory = strdup(RUN_DIR))) goto error_exit;
154 	if(!(cfg->logfile = strdup(""))) goto error_exit;
155 	if(!(cfg->pidfile = strdup(PIDFILE))) goto error_exit;
156 	if(!(cfg->target_fetch_policy = strdup("3 2 1 0 0"))) goto error_exit;
157 	cfg->donotqueryaddrs = NULL;
158 	cfg->donotquery_localhost = 1;
159 	cfg->root_hints = NULL;
160 	cfg->do_daemonize = 1;
161 	cfg->if_automatic = 0;
162 	cfg->so_rcvbuf = 0;
163 	cfg->so_sndbuf = 0;
164 	cfg->so_reuseport = 0;
165 	cfg->ip_transparent = 0;
166 	cfg->ip_freebind = 0;
167 	cfg->num_ifs = 0;
168 	cfg->ifs = NULL;
169 	cfg->num_out_ifs = 0;
170 	cfg->out_ifs = NULL;
171 	cfg->stubs = NULL;
172 	cfg->forwards = NULL;
173 	cfg->acls = NULL;
174 	cfg->harden_short_bufsize = 0;
175 	cfg->harden_large_queries = 0;
176 	cfg->harden_glue = 1;
177 	cfg->harden_dnssec_stripped = 1;
178 	cfg->harden_below_nxdomain = 0;
179 	cfg->harden_referral_path = 0;
180 	cfg->harden_algo_downgrade = 0;
181 	cfg->use_caps_bits_for_id = 0;
182 	cfg->caps_whitelist = NULL;
183 	cfg->private_address = NULL;
184 	cfg->private_domain = NULL;
185 	cfg->unwanted_threshold = 0;
186 	cfg->hide_identity = 0;
187 	cfg->hide_version = 0;
188 	cfg->identity = NULL;
189 	cfg->version = NULL;
190 	cfg->auto_trust_anchor_file_list = NULL;
191 	cfg->trust_anchor_file_list = NULL;
192 	cfg->trust_anchor_list = NULL;
193 	cfg->trusted_keys_file_list = NULL;
194 	cfg->dlv_anchor_file = NULL;
195 	cfg->dlv_anchor_list = NULL;
196 	cfg->domain_insecure = NULL;
197 	cfg->val_date_override = 0;
198 	cfg->val_sig_skew_min = 3600; /* at least daylight savings trouble */
199 	cfg->val_sig_skew_max = 86400; /* at most timezone settings trouble */
200 	cfg->val_clean_additional = 1;
201 	cfg->val_log_level = 0;
202 	cfg->val_log_squelch = 0;
203 	cfg->val_permissive_mode = 0;
204 	cfg->ignore_cd = 0;
205 	cfg->add_holddown = 30*24*3600;
206 	cfg->del_holddown = 30*24*3600;
207 	cfg->keep_missing = 366*24*3600; /* one year plus a little leeway */
208 	cfg->permit_small_holddown = 0;
209 	cfg->key_cache_size = 4 * 1024 * 1024;
210 	cfg->key_cache_slabs = 4;
211 	cfg->neg_cache_size = 1 * 1024 * 1024;
212 	cfg->local_zones = NULL;
213 	cfg->local_zones_nodefault = NULL;
214 	cfg->local_data = NULL;
215 	cfg->local_zone_overrides = NULL;
216 	cfg->unblock_lan_zones = 0;
217 	cfg->insecure_lan_zones = 0;
218 	cfg->python_script = NULL;
219 	cfg->remote_control_enable = 0;
220 	cfg->control_ifs = NULL;
221 	cfg->control_port = UNBOUND_CONTROL_PORT;
222 	cfg->remote_control_use_cert = 1;
223 	cfg->minimal_responses = 0;
224 	cfg->rrset_roundrobin = 0;
225 	cfg->max_udp_size = 4096;
226 	if(!(cfg->server_key_file = strdup(RUN_DIR"/unbound_server.key")))
227 		goto error_exit;
228 	if(!(cfg->server_cert_file = strdup(RUN_DIR"/unbound_server.pem")))
229 		goto error_exit;
230 	if(!(cfg->control_key_file = strdup(RUN_DIR"/unbound_control.key")))
231 		goto error_exit;
232 	if(!(cfg->control_cert_file = strdup(RUN_DIR"/unbound_control.pem")))
233 		goto error_exit;
234 
235 	if(!(cfg->module_conf = strdup("validator iterator"))) goto error_exit;
236 	if(!(cfg->val_nsec3_key_iterations =
237 		strdup("1024 150 2048 500 4096 2500"))) goto error_exit;
238 #if defined(DNSTAP_SOCKET_PATH)
239 	if(!(cfg->dnstap_socket_path = strdup(DNSTAP_SOCKET_PATH)))
240 		goto error_exit;
241 #endif
242 	cfg->disable_dnssec_lame_check = 0;
243 	cfg->ratelimit = 0;
244 	cfg->ratelimit_slabs = 4;
245 	cfg->ratelimit_size = 4*1024*1024;
246 	cfg->ratelimit_for_domain = NULL;
247 	cfg->ratelimit_below_domain = NULL;
248 	cfg->ratelimit_factor = 10;
249 	cfg->qname_minimisation = 0;
250 	return cfg;
251 error_exit:
252 	config_delete(cfg);
253 	return NULL;
254 }
255 
256 struct config_file* config_create_forlib(void)
257 {
258 	struct config_file* cfg = config_create();
259 	if(!cfg) return NULL;
260 	/* modifications for library use, less verbose, less memory */
261 	free(cfg->chrootdir);
262 	cfg->chrootdir = NULL;
263 	cfg->verbosity = 0;
264 	cfg->outgoing_num_ports = 16; /* in library use, this is 'reasonable'
265 		and probably within the ulimit(maxfds) of the user */
266 	cfg->outgoing_num_tcp = 2;
267 	cfg->msg_cache_size = 1024*1024;
268 	cfg->msg_cache_slabs = 1;
269 	cfg->rrset_cache_size = 1024*1024;
270 	cfg->rrset_cache_slabs = 1;
271 	cfg->infra_cache_slabs = 1;
272 	cfg->use_syslog = 0;
273 	cfg->key_cache_size = 1024*1024;
274 	cfg->key_cache_slabs = 1;
275 	cfg->neg_cache_size = 100 * 1024;
276 	cfg->donotquery_localhost = 0; /* allow, so that you can ask a
277 		forward nameserver running on localhost */
278 	cfg->val_log_level = 2; /* to fill why_bogus with */
279 	cfg->val_log_squelch = 1;
280 	return cfg;
281 }
282 
283 /** check that the value passed is >= 0 */
284 #define IS_NUMBER_OR_ZERO \
285 	if(atoi(val) == 0 && strcmp(val, "0") != 0) return 0
286 /** check that the value passed is > 0 */
287 #define IS_NONZERO_NUMBER \
288 	if(atoi(val) == 0) return 0
289 /** check that the value passed is not 0 and a power of 2 */
290 #define IS_POW2_NUMBER \
291 	if(atoi(val) == 0 || !is_pow2((size_t)atoi(val))) return 0
292 /** check that the value passed is yes or no */
293 #define IS_YES_OR_NO \
294 	if(strcmp(val, "yes") != 0 && strcmp(val, "no") != 0) return 0
295 /** put integer_or_zero into variable */
296 #define S_NUMBER_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
297 	{ IS_NUMBER_OR_ZERO; cfg->var = atoi(val); }
298 /** put integer_nonzero into variable */
299 #define S_NUMBER_NONZERO(str, var) if(strcmp(opt, str) == 0) \
300 	{ IS_NONZERO_NUMBER; cfg->var = atoi(val); }
301 /** put integer_or_zero into unsigned */
302 #define S_UNSIGNED_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
303 	{ IS_NUMBER_OR_ZERO; cfg->var = (unsigned)atoi(val); }
304 /** put integer_or_zero into size_t */
305 #define S_SIZET_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
306 	{ IS_NUMBER_OR_ZERO; cfg->var = (size_t)atoi(val); }
307 /** put integer_nonzero into size_t */
308 #define S_SIZET_NONZERO(str, var) if(strcmp(opt, str) == 0) \
309 	{ IS_NONZERO_NUMBER; cfg->var = (size_t)atoi(val); }
310 /** put yesno into variable */
311 #define S_YNO(str, var) if(strcmp(opt, str) == 0) \
312 	{ IS_YES_OR_NO; cfg->var = (strcmp(val, "yes") == 0); }
313 /** put memsize into variable */
314 #define S_MEMSIZE(str, var) if(strcmp(opt, str)==0) \
315 	{ return cfg_parse_memsize(val, &cfg->var); }
316 /** put pow2 number into variable */
317 #define S_POW2(str, var) if(strcmp(opt, str)==0) \
318 	{ IS_POW2_NUMBER; cfg->var = (size_t)atoi(val); }
319 /** put string into variable */
320 #define S_STR(str, var) if(strcmp(opt, str)==0) \
321 	{ free(cfg->var); return (cfg->var = strdup(val)) != NULL; }
322 /** put string into strlist */
323 #define S_STRLIST(str, var) if(strcmp(opt, str)==0) \
324 	{ return cfg_strlist_insert(&cfg->var, strdup(val)); }
325 
326 int config_set_option(struct config_file* cfg, const char* opt,
327 	const char* val)
328 {
329 	S_NUMBER_OR_ZERO("verbosity:", verbosity)
330 	else if(strcmp(opt, "statistics-interval:") == 0) {
331 		if(strcmp(val, "0") == 0 || strcmp(val, "") == 0)
332 			cfg->stat_interval = 0;
333 		else if(atoi(val) == 0)
334 			return 0;
335 		else cfg->stat_interval = atoi(val);
336 	} else if(strcmp(opt, "num_threads:") == 0) {
337 		/* not supported, library must have 1 thread in bgworker */
338 		return 0;
339 	} else if(strcmp(opt, "outgoing-port-permit:") == 0) {
340 		return cfg_mark_ports(val, 1,
341 			cfg->outgoing_avail_ports, 65536);
342 	} else if(strcmp(opt, "outgoing-port-avoid:") == 0) {
343 		return cfg_mark_ports(val, 0,
344 			cfg->outgoing_avail_ports, 65536);
345 	} else if(strcmp(opt, "local-zone:") == 0) {
346 		return cfg_parse_local_zone(cfg, val);
347 	} else if(strcmp(opt, "val-override-date:") == 0) {
348 		if(strcmp(val, "") == 0 || strcmp(val, "0") == 0) {
349 			cfg->val_date_override = 0;
350 		} else if(strlen(val) == 14) {
351 			cfg->val_date_override = cfg_convert_timeval(val);
352 			return cfg->val_date_override != 0;
353 		} else {
354 			if(atoi(val) == 0) return 0;
355 			cfg->val_date_override = (uint32_t)atoi(val);
356 		}
357 	} else if(strcmp(opt, "local-data-ptr:") == 0) {
358 		char* ptr = cfg_ptr_reverse((char*)opt);
359 		return cfg_strlist_insert(&cfg->local_data, ptr);
360 	} else if(strcmp(opt, "logfile:") == 0) {
361 		cfg->use_syslog = 0;
362 		free(cfg->logfile);
363 		return (cfg->logfile = strdup(val)) != NULL;
364 	}
365 	else if(strcmp(opt, "log-time-ascii:") == 0)
366 	{ IS_YES_OR_NO; cfg->log_time_ascii = (strcmp(val, "yes") == 0);
367 	  log_set_time_asc(cfg->log_time_ascii); }
368 	else S_SIZET_NONZERO("max-udp-size:", max_udp_size)
369 	else S_YNO("use-syslog:", use_syslog)
370 	else S_YNO("extended-statistics:", stat_extended)
371 	else S_YNO("statistics-cumulative:", stat_cumulative)
372 	else S_YNO("do-ip4:", do_ip4)
373 	else S_YNO("do-ip6:", do_ip6)
374 	else S_YNO("do-udp:", do_udp)
375 	else S_YNO("do-tcp:", do_tcp)
376 	else S_YNO("tcp-upstream:", tcp_upstream)
377 	else S_NUMBER_NONZERO("tcp-mss:", tcp_mss)
378 	else S_NUMBER_NONZERO("outgoing-tcp-mss:", outgoing_tcp_mss)
379 	else S_YNO("ssl-upstream:", ssl_upstream)
380 	else S_STR("ssl-service-key:", ssl_service_key)
381 	else S_STR("ssl-service-pem:", ssl_service_pem)
382 	else S_NUMBER_NONZERO("ssl-port:", ssl_port)
383 	else S_YNO("interface-automatic:", if_automatic)
384 	else S_YNO("do-daemonize:", do_daemonize)
385 	else S_NUMBER_NONZERO("port:", port)
386 	else S_NUMBER_NONZERO("outgoing-range:", outgoing_num_ports)
387 	else S_SIZET_OR_ZERO("outgoing-num-tcp:", outgoing_num_tcp)
388 	else S_SIZET_OR_ZERO("incoming-num-tcp:", incoming_num_tcp)
389 	else S_SIZET_NONZERO("edns-buffer-size:", edns_buffer_size)
390 	else S_SIZET_NONZERO("msg-buffer-size:", msg_buffer_size)
391 	else S_MEMSIZE("msg-cache-size:", msg_cache_size)
392 	else S_POW2("msg-cache-slabs:", msg_cache_slabs)
393 	else S_SIZET_NONZERO("num-queries-per-thread:",num_queries_per_thread)
394 	else S_SIZET_OR_ZERO("jostle-timeout:", jostle_time)
395 	else S_MEMSIZE("so-rcvbuf:", so_rcvbuf)
396 	else S_MEMSIZE("so-sndbuf:", so_sndbuf)
397 	else S_YNO("so-reuseport:", so_reuseport)
398 	else S_YNO("ip-transparent:", ip_transparent)
399 	else S_YNO("ip-freebind:", ip_freebind)
400 	else S_MEMSIZE("rrset-cache-size:", rrset_cache_size)
401 	else S_POW2("rrset-cache-slabs:", rrset_cache_slabs)
402 	else S_YNO("prefetch:", prefetch)
403 	else S_YNO("prefetch-key:", prefetch_key)
404 	else if(strcmp(opt, "cache-max-ttl:") == 0)
405 	{ IS_NUMBER_OR_ZERO; cfg->max_ttl = atoi(val); MAX_TTL=(time_t)cfg->max_ttl;}
406 	else if(strcmp(opt, "cache-max-negative-ttl:") == 0)
407 	{ IS_NUMBER_OR_ZERO; cfg->max_negative_ttl = atoi(val); MAX_NEG_TTL=(time_t)cfg->max_negative_ttl;}
408 	else if(strcmp(opt, "cache-min-ttl:") == 0)
409 	{ IS_NUMBER_OR_ZERO; cfg->min_ttl = atoi(val); MIN_TTL=(time_t)cfg->min_ttl;}
410 	else if(strcmp(opt, "infra-cache-min-rtt:") == 0) {
411 	    IS_NUMBER_OR_ZERO; cfg->infra_cache_min_rtt = atoi(val);
412 	    RTT_MIN_TIMEOUT=cfg->infra_cache_min_rtt;
413 	}
414 	else S_NUMBER_OR_ZERO("infra-host-ttl:", host_ttl)
415 	else S_POW2("infra-cache-slabs:", infra_cache_slabs)
416 	else S_SIZET_NONZERO("infra-cache-numhosts:", infra_cache_numhosts)
417 	else S_NUMBER_OR_ZERO("delay-close:", delay_close)
418 	else S_STR("chroot:", chrootdir)
419 	else S_STR("username:", username)
420 	else S_STR("directory:", directory)
421 	else S_STR("pidfile:", pidfile)
422 	else S_YNO("hide-identity:", hide_identity)
423 	else S_YNO("hide-version:", hide_version)
424 	else S_STR("identity:", identity)
425 	else S_STR("version:", version)
426 	else S_STRLIST("root-hints:", root_hints)
427 	else S_STR("target-fetch-policy:", target_fetch_policy)
428 	else S_YNO("harden-glue:", harden_glue)
429 	else S_YNO("harden-short-bufsize:", harden_short_bufsize)
430 	else S_YNO("harden-large-queries:", harden_large_queries)
431 	else S_YNO("harden-dnssec-stripped:", harden_dnssec_stripped)
432 	else S_YNO("harden-below-nxdomain:", harden_below_nxdomain)
433 	else S_YNO("harden-referral-path:", harden_referral_path)
434 	else S_YNO("harden-algo-downgrade:", harden_algo_downgrade)
435 	else S_YNO("use-caps-for-id", use_caps_bits_for_id)
436 	else S_STRLIST("caps-whitelist:", caps_whitelist)
437 	else S_SIZET_OR_ZERO("unwanted-reply-threshold:", unwanted_threshold)
438 	else S_STRLIST("private-address:", private_address)
439 	else S_STRLIST("private-domain:", private_domain)
440 	else S_YNO("do-not-query-localhost:", donotquery_localhost)
441 	else S_STRLIST("do-not-query-address:", donotqueryaddrs)
442 	else S_STRLIST("auto-trust-anchor-file:", auto_trust_anchor_file_list)
443 	else S_STRLIST("trust-anchor-file:", trust_anchor_file_list)
444 	else S_STRLIST("trust-anchor:", trust_anchor_list)
445 	else S_STRLIST("trusted-keys-file:", trusted_keys_file_list)
446 	else S_STR("dlv-anchor-file:", dlv_anchor_file)
447 	else S_STRLIST("dlv-anchor:", dlv_anchor_list)
448 	else S_STRLIST("domain-insecure:", domain_insecure)
449 	else S_NUMBER_OR_ZERO("val-bogus-ttl:", bogus_ttl)
450 	else S_YNO("val-clean-additional:", val_clean_additional)
451 	else S_NUMBER_OR_ZERO("val-log-level:", val_log_level)
452 	else S_YNO("val-log-squelch:", val_log_squelch)
453 	else S_YNO("log-queries:", log_queries)
454 	else S_YNO("val-permissive-mode:", val_permissive_mode)
455 	else S_YNO("ignore-cd-flag:", ignore_cd)
456 	else S_STR("val-nsec3-keysize-iterations:", val_nsec3_key_iterations)
457 	else S_UNSIGNED_OR_ZERO("add-holddown:", add_holddown)
458 	else S_UNSIGNED_OR_ZERO("del-holddown:", del_holddown)
459 	else S_UNSIGNED_OR_ZERO("keep-missing:", keep_missing)
460 	else if(strcmp(opt, "permit-small-holddown:") == 0)
461 	{ IS_YES_OR_NO; cfg->permit_small_holddown = (strcmp(val, "yes") == 0);
462 	  autr_permit_small_holddown = cfg->permit_small_holddown; }
463 	else S_MEMSIZE("key-cache-size:", key_cache_size)
464 	else S_POW2("key-cache-slabs:", key_cache_slabs)
465 	else S_MEMSIZE("neg-cache-size:", neg_cache_size)
466 	else S_YNO("minimal-responses:", minimal_responses)
467 	else S_YNO("rrset-roundrobin:", rrset_roundrobin)
468 	else S_STRLIST("local-data:", local_data)
469 	else S_YNO("unblock-lan-zones:", unblock_lan_zones)
470 	else S_YNO("insecure-lan-zones:", insecure_lan_zones)
471 	else S_YNO("control-enable:", remote_control_enable)
472 	else S_STRLIST("control-interface:", control_ifs)
473 	else S_NUMBER_NONZERO("control-port:", control_port)
474 	else S_STR("server-key-file:", server_key_file)
475 	else S_STR("server-cert-file:", server_cert_file)
476 	else S_STR("control-key-file:", control_key_file)
477 	else S_STR("control-cert-file:", control_cert_file)
478 	else S_STR("module-config:", module_conf)
479 	else S_STR("python-script:", python_script)
480 	else S_YNO("disable-dnssec-lame-check:", disable_dnssec_lame_check)
481 	else if(strcmp(opt, "ratelimit:") == 0) {
482 	    IS_NUMBER_OR_ZERO; cfg->ratelimit = atoi(val);
483 	    infra_dp_ratelimit=cfg->ratelimit;
484 	}
485 	else S_MEMSIZE("ratelimit-size:", ratelimit_size)
486 	else S_POW2("ratelimit-slabs:", ratelimit_slabs)
487 	else S_NUMBER_OR_ZERO("ratelimit-factor:", ratelimit_factor)
488 	else S_YNO("qname-minimisation:", qname_minimisation)
489 	else if(strcmp(opt, "define-tag:") ==0) {
490 		return config_add_tag(cfg, val);
491 	/* val_sig_skew_min and max are copied into val_env during init,
492 	 * so this does not update val_env with set_option */
493 	} else if(strcmp(opt, "val-sig-skew-min:") == 0)
494 	{ IS_NUMBER_OR_ZERO; cfg->val_sig_skew_min = (int32_t)atoi(val); }
495 	else if(strcmp(opt, "val-sig-skew-max:") == 0)
496 	{ IS_NUMBER_OR_ZERO; cfg->val_sig_skew_max = (int32_t)atoi(val); }
497 	else if (strcmp(opt, "outgoing-interface:") == 0) {
498 		char* d = strdup(val);
499 		char** oi =
500 		(char**)reallocarray(NULL, (size_t)cfg->num_out_ifs+1, sizeof(char*));
501 		if(!d || !oi) { free(d); free(oi); return -1; }
502 		if(cfg->out_ifs && cfg->num_out_ifs) {
503 			memmove(oi, cfg->out_ifs, cfg->num_out_ifs*sizeof(char*));
504 			free(cfg->out_ifs);
505 		}
506 		oi[cfg->num_out_ifs++] = d;
507 		cfg->out_ifs = oi;
508 	} else {
509 		/* unknown or unsupported (from the set_option interface):
510 		 * interface, outgoing-interface, access-control,
511 		 * stub-zone, name, stub-addr, stub-host, stub-prime
512 		 * forward-first, stub-first,
513 		 * forward-zone, name, forward-addr, forward-host,
514 		 * ratelimit-for-domain, ratelimit-below-domain,
515 		 * local-zone-tag */
516 		return 0;
517 	}
518 	return 1;
519 }
520 
521 void config_print_func(char* line, void* arg)
522 {
523 	FILE* f = (FILE*)arg;
524 	(void)fprintf(f, "%s\n", line);
525 }
526 
527 /** collate func arg */
528 struct config_collate_arg {
529 	/** list of result items */
530 	struct config_strlist_head list;
531 	/** if a malloc error occurred, 0 is OK */
532 	int status;
533 };
534 
535 void config_collate_func(char* line, void* arg)
536 {
537 	struct config_collate_arg* m = (struct config_collate_arg*)arg;
538 	if(m->status)
539 		return;
540 	if(!cfg_strlist_append(&m->list, strdup(line)))
541 		m->status = 1;
542 }
543 
544 int config_get_option_list(struct config_file* cfg, const char* opt,
545 	struct config_strlist** list)
546 {
547 	struct config_collate_arg m;
548 	memset(&m, 0, sizeof(m));
549 	*list = NULL;
550 	if(!config_get_option(cfg, opt, config_collate_func, &m))
551 		return 1;
552 	if(m.status) {
553 		config_delstrlist(m.list.first);
554 		return 2;
555 	}
556 	*list = m.list.first;
557 	return 0;
558 }
559 
560 int
561 config_get_option_collate(struct config_file* cfg, const char* opt, char** str)
562 {
563 	struct config_strlist* list = NULL;
564 	int r;
565 	*str = NULL;
566 	if((r = config_get_option_list(cfg, opt, &list)) != 0)
567 		return r;
568 	*str = config_collate_cat(list);
569 	config_delstrlist(list);
570 	if(!*str) return 2;
571 	return 0;
572 }
573 
574 char*
575 config_collate_cat(struct config_strlist* list)
576 {
577 	size_t total = 0, left;
578 	struct config_strlist* s;
579 	char *r, *w;
580 	if(!list) /* no elements */
581 		return strdup("");
582 	if(list->next == NULL) /* one element , no newline at end. */
583 		return strdup(list->str);
584 	/* count total length */
585 	for(s=list; s; s=s->next)
586 		total += strlen(s->str) + 1; /* len + newline */
587 	left = total+1; /* one extra for nul at end */
588 	r = malloc(left);
589 	if(!r)
590 		return NULL;
591 	w = r;
592 	for(s=list; s; s=s->next) {
593 		size_t this = strlen(s->str);
594 		if(this+2 > left) { /* sanity check */
595 			free(r);
596 			return NULL;
597 		}
598 		snprintf(w, left, "%s\n", s->str);
599 		this = strlen(w);
600 		w += this;
601 		left -= this;
602 	}
603 	return r;
604 }
605 
606 /** compare and print decimal option */
607 #define O_DEC(opt, str, var) if(strcmp(opt, str)==0) \
608 	{snprintf(buf, len, "%d", (int)cfg->var); \
609 	func(buf, arg);}
610 /** compare and print unsigned option */
611 #define O_UNS(opt, str, var) if(strcmp(opt, str)==0) \
612 	{snprintf(buf, len, "%u", (unsigned)cfg->var); \
613 	func(buf, arg);}
614 /** compare and print yesno option */
615 #define O_YNO(opt, str, var) if(strcmp(opt, str)==0) \
616 	{func(cfg->var?"yes":"no", arg);}
617 /** compare and print string option */
618 #define O_STR(opt, str, var) if(strcmp(opt, str)==0) \
619 	{func(cfg->var?cfg->var:"", arg);}
620 /** compare and print array option */
621 #define O_IFC(opt, str, num, arr) if(strcmp(opt, str)==0) \
622 	{int i; for(i=0; i<cfg->num; i++) func(cfg->arr[i], arg);}
623 /** compare and print memorysize option */
624 #define O_MEM(opt, str, var) if(strcmp(opt, str)==0) { \
625 	if(cfg->var > 1024*1024*1024) {	\
626 	  size_t f=cfg->var/(size_t)1000000, b=cfg->var%(size_t)1000000; \
627 	  snprintf(buf, len, "%u%6.6u", (unsigned)f, (unsigned)b); \
628 	} else snprintf(buf, len, "%u", (unsigned)cfg->var); \
629 	func(buf, arg);}
630 /** compare and print list option */
631 #define O_LST(opt, name, lst) if(strcmp(opt, name)==0) { \
632 	struct config_strlist* p = cfg->lst; \
633 	for(p = cfg->lst; p; p = p->next) \
634 		func(p->str, arg); \
635 	}
636 /** compare and print list option */
637 #define O_LS2(opt, name, lst) if(strcmp(opt, name)==0) { \
638 	struct config_str2list* p = cfg->lst; \
639 	for(p = cfg->lst; p; p = p->next) { \
640 		snprintf(buf, len, "%s %s", p->str, p->str2); \
641 		func(buf, arg); \
642 	} \
643 	}
644 /** compare and print list option */
645 #define O_LS3(opt, name, lst) if(strcmp(opt, name)==0) { \
646 	struct config_str3list* p = cfg->lst; \
647 	for(p = cfg->lst; p; p = p->next) { \
648 		snprintf(buf, len, "%s %s %s", p->str, p->str2, p->str3); \
649 		func(buf, arg); \
650 	} \
651 	}
652 /** compare and print taglist option */
653 #define O_LTG(opt, name, lst) if(strcmp(opt, name)==0) { \
654 	char* tmpstr = NULL; \
655 	struct config_strbytelist *p = cfg->lst; \
656 	for(p = cfg->lst; p; p = p->next) {\
657 		tmpstr = config_taglist2str(cfg, p->str2, p->str2len); \
658 		if(tmpstr) {\
659 			snprintf(buf, len, "%s %s", p->str, tmpstr); \
660 			func(buf, arg); \
661 			free(tmpstr); \
662 		} \
663 	} \
664 	}
665 
666 int
667 config_get_option(struct config_file* cfg, const char* opt,
668 	void (*func)(char*,void*), void* arg)
669 {
670 	char buf[1024];
671 	size_t len = sizeof(buf);
672 	fptr_ok(fptr_whitelist_print_func(func));
673 	O_DEC(opt, "verbosity", verbosity)
674 	else O_DEC(opt, "statistics-interval", stat_interval)
675 	else O_YNO(opt, "statistics-cumulative", stat_cumulative)
676 	else O_YNO(opt, "extended-statistics", stat_extended)
677 	else O_YNO(opt, "use-syslog", use_syslog)
678 	else O_YNO(opt, "log-time-ascii", log_time_ascii)
679 	else O_DEC(opt, "num-threads", num_threads)
680 	else O_IFC(opt, "interface", num_ifs, ifs)
681 	else O_IFC(opt, "outgoing-interface", num_out_ifs, out_ifs)
682 	else O_YNO(opt, "interface-automatic", if_automatic)
683 	else O_DEC(opt, "port", port)
684 	else O_DEC(opt, "outgoing-range", outgoing_num_ports)
685 	else O_DEC(opt, "outgoing-num-tcp", outgoing_num_tcp)
686 	else O_DEC(opt, "incoming-num-tcp", incoming_num_tcp)
687 	else O_DEC(opt, "edns-buffer-size", edns_buffer_size)
688 	else O_DEC(opt, "msg-buffer-size", msg_buffer_size)
689 	else O_MEM(opt, "msg-cache-size", msg_cache_size)
690 	else O_DEC(opt, "msg-cache-slabs", msg_cache_slabs)
691 	else O_DEC(opt, "num-queries-per-thread", num_queries_per_thread)
692 	else O_UNS(opt, "jostle-timeout", jostle_time)
693 	else O_MEM(opt, "so-rcvbuf", so_rcvbuf)
694 	else O_MEM(opt, "so-sndbuf", so_sndbuf)
695 	else O_YNO(opt, "so-reuseport", so_reuseport)
696 	else O_YNO(opt, "ip-transparent", ip_transparent)
697 	else O_YNO(opt, "ip-freebind", ip_freebind)
698 	else O_MEM(opt, "rrset-cache-size", rrset_cache_size)
699 	else O_DEC(opt, "rrset-cache-slabs", rrset_cache_slabs)
700 	else O_YNO(opt, "prefetch-key", prefetch_key)
701 	else O_YNO(opt, "prefetch", prefetch)
702 	else O_DEC(opt, "cache-max-ttl", max_ttl)
703 	else O_DEC(opt, "cache-max-negative-ttl", max_negative_ttl)
704 	else O_DEC(opt, "cache-min-ttl", min_ttl)
705 	else O_DEC(opt, "infra-host-ttl", host_ttl)
706 	else O_DEC(opt, "infra-cache-slabs", infra_cache_slabs)
707 	else O_DEC(opt, "infra-cache-min-rtt", infra_cache_min_rtt)
708 	else O_MEM(opt, "infra-cache-numhosts", infra_cache_numhosts)
709 	else O_UNS(opt, "delay-close", delay_close)
710 	else O_YNO(opt, "do-ip4", do_ip4)
711 	else O_YNO(opt, "do-ip6", do_ip6)
712 	else O_YNO(opt, "do-udp", do_udp)
713 	else O_YNO(opt, "do-tcp", do_tcp)
714 	else O_YNO(opt, "tcp-upstream", tcp_upstream)
715 	else O_DEC(opt, "tcp-mss", tcp_mss)
716 	else O_DEC(opt, "outgoing-tcp-mss", outgoing_tcp_mss)
717 	else O_YNO(opt, "ssl-upstream", ssl_upstream)
718 	else O_STR(opt, "ssl-service-key", ssl_service_key)
719 	else O_STR(opt, "ssl-service-pem", ssl_service_pem)
720 	else O_DEC(opt, "ssl-port", ssl_port)
721 	else O_YNO(opt, "do-daemonize", do_daemonize)
722 	else O_STR(opt, "chroot", chrootdir)
723 	else O_STR(opt, "username", username)
724 	else O_STR(opt, "directory", directory)
725 	else O_STR(opt, "logfile", logfile)
726 	else O_YNO(opt, "log-queries", log_queries)
727 	else O_STR(opt, "pidfile", pidfile)
728 	else O_YNO(opt, "hide-identity", hide_identity)
729 	else O_YNO(opt, "hide-version", hide_version)
730 	else O_STR(opt, "identity", identity)
731 	else O_STR(opt, "version", version)
732 	else O_STR(opt, "target-fetch-policy", target_fetch_policy)
733 	else O_YNO(opt, "harden-short-bufsize", harden_short_bufsize)
734 	else O_YNO(opt, "harden-large-queries", harden_large_queries)
735 	else O_YNO(opt, "harden-glue", harden_glue)
736 	else O_YNO(opt, "harden-dnssec-stripped", harden_dnssec_stripped)
737 	else O_YNO(opt, "harden-below-nxdomain", harden_below_nxdomain)
738 	else O_YNO(opt, "harden-referral-path", harden_referral_path)
739 	else O_YNO(opt, "harden-algo-downgrade", harden_algo_downgrade)
740 	else O_YNO(opt, "use-caps-for-id", use_caps_bits_for_id)
741 	else O_LST(opt, "caps-whitelist", caps_whitelist)
742 	else O_DEC(opt, "unwanted-reply-threshold", unwanted_threshold)
743 	else O_YNO(opt, "do-not-query-localhost", donotquery_localhost)
744 	else O_STR(opt, "module-config", module_conf)
745 	else O_STR(opt, "dlv-anchor-file", dlv_anchor_file)
746 	else O_DEC(opt, "val-bogus-ttl", bogus_ttl)
747 	else O_YNO(opt, "val-clean-additional", val_clean_additional)
748 	else O_DEC(opt, "val-log-level", val_log_level)
749 	else O_YNO(opt, "val-permissive-mode", val_permissive_mode)
750 	else O_YNO(opt, "ignore-cd-flag", ignore_cd)
751 	else O_STR(opt, "val-nsec3-keysize-iterations",val_nsec3_key_iterations)
752 	else O_UNS(opt, "add-holddown", add_holddown)
753 	else O_UNS(opt, "del-holddown", del_holddown)
754 	else O_UNS(opt, "keep-missing", keep_missing)
755 	else O_YNO(opt, "permit-small-holddown", permit_small_holddown)
756 	else O_MEM(opt, "key-cache-size", key_cache_size)
757 	else O_DEC(opt, "key-cache-slabs", key_cache_slabs)
758 	else O_MEM(opt, "neg-cache-size", neg_cache_size)
759 	else O_YNO(opt, "control-enable", remote_control_enable)
760 	else O_DEC(opt, "control-port", control_port)
761 	else O_STR(opt, "server-key-file", server_key_file)
762 	else O_STR(opt, "server-cert-file", server_cert_file)
763 	else O_STR(opt, "control-key-file", control_key_file)
764 	else O_STR(opt, "control-cert-file", control_cert_file)
765 	else O_LST(opt, "root-hints", root_hints)
766 	else O_LS2(opt, "access-control", acls)
767 	else O_LST(opt, "do-not-query-address", donotqueryaddrs)
768 	else O_LST(opt, "private-address", private_address)
769 	else O_LST(opt, "private-domain", private_domain)
770 	else O_LST(opt, "auto-trust-anchor-file", auto_trust_anchor_file_list)
771 	else O_LST(opt, "trust-anchor-file", trust_anchor_file_list)
772 	else O_LST(opt, "trust-anchor", trust_anchor_list)
773 	else O_LST(opt, "trusted-keys-file", trusted_keys_file_list)
774 	else O_LST(opt, "dlv-anchor", dlv_anchor_list)
775 	else O_LST(opt, "control-interface", control_ifs)
776 	else O_LST(opt, "domain-insecure", domain_insecure)
777 	else O_UNS(opt, "val-override-date", val_date_override)
778 	else O_YNO(opt, "minimal-responses", minimal_responses)
779 	else O_YNO(opt, "rrset-roundrobin", rrset_roundrobin)
780 	else O_YNO(opt, "unblock-lan-zones", unblock_lan_zones)
781 	else O_YNO(opt, "insecure-lan-zones", insecure_lan_zones)
782 	else O_DEC(opt, "max-udp-size", max_udp_size)
783 	else O_STR(opt, "python-script", python_script)
784 	else O_YNO(opt, "disable-dnssec-lame-check", disable_dnssec_lame_check)
785 	else O_DEC(opt, "ratelimit", ratelimit)
786 	else O_MEM(opt, "ratelimit-size", ratelimit_size)
787 	else O_DEC(opt, "ratelimit-slabs", ratelimit_slabs)
788 	else O_LS2(opt, "ratelimit-for-domain", ratelimit_for_domain)
789 	else O_LS2(opt, "ratelimit-below-domain", ratelimit_below_domain)
790 	else O_DEC(opt, "ratelimit-factor", ratelimit_factor)
791 	else O_DEC(opt, "val-sig-skew-min", val_sig_skew_min)
792 	else O_DEC(opt, "val-sig-skew-max", val_sig_skew_max)
793 	else O_YNO(opt, "qname-minimisation", qname_minimisation)
794 	else O_IFC(opt, "define-tag", num_tags, tagname)
795 	else O_LTG(opt, "local-zone-tag", local_zone_tags)
796 	else O_LTG(opt, "access-control-tag", acl_tags)
797 	else O_LS3(opt, "local-zone-override", local_zone_overrides)
798 	else O_LS3(opt, "access-control-tag-action", acl_tag_actions)
799 	else O_LS3(opt, "access-control-tag-data", acl_tag_datas)
800 	/* not here:
801 	 * outgoing-permit, outgoing-avoid - have list of ports
802 	 * local-zone - zones and nodefault variables
803 	 * local-data - see below
804 	 * local-data-ptr - converted to local-data entries
805 	 * stub-zone, name, stub-addr, stub-host, stub-prime
806 	 * forward-zone, name, forward-addr, forward-host
807 	 */
808 	else return 0;
809 	return 1;
810 }
811 
812 /** initialize the global cfg_parser object */
813 static void
814 create_cfg_parser(struct config_file* cfg, char* filename, const char* chroot)
815 {
816 	static struct config_parser_state st;
817 	cfg_parser = &st;
818 	cfg_parser->filename = filename;
819 	cfg_parser->line = 1;
820 	cfg_parser->errors = 0;
821 	cfg_parser->cfg = cfg;
822 	cfg_parser->chroot = chroot;
823 	init_cfg_parse();
824 }
825 
826 int
827 config_read(struct config_file* cfg, const char* filename, const char* chroot)
828 {
829 	FILE *in;
830 	char *fname = (char*)filename;
831 #ifdef HAVE_GLOB
832 	glob_t g;
833 	size_t i;
834 	int r, flags;
835 #endif
836 	if(!fname)
837 		return 1;
838 
839 	/* check for wildcards */
840 #ifdef HAVE_GLOB
841 	if(!(!strchr(fname, '*') && !strchr(fname, '?') && !strchr(fname, '[') &&
842 		!strchr(fname, '{') && !strchr(fname, '~'))) {
843 		verbose(VERB_QUERY, "wildcard found, processing %s", fname);
844 		flags = 0
845 #ifdef GLOB_ERR
846 			| GLOB_ERR
847 #endif
848 #ifdef GLOB_NOSORT
849 			| GLOB_NOSORT
850 #endif
851 #ifdef GLOB_BRACE
852 			| GLOB_BRACE
853 #endif
854 #ifdef GLOB_TILDE
855 			| GLOB_TILDE
856 #endif
857 		;
858 		memset(&g, 0, sizeof(g));
859 		r = glob(fname, flags, NULL, &g);
860 		if(r) {
861 			/* some error */
862 			globfree(&g);
863 			if(r == GLOB_NOMATCH) {
864 				verbose(VERB_QUERY, "include: "
865 				"no matches for %s", fname);
866 				return 1;
867 			} else if(r == GLOB_NOSPACE) {
868 				log_err("include: %s: "
869 					"fnametern out of memory", fname);
870 			} else if(r == GLOB_ABORTED) {
871 				log_err("wildcard include: %s: expansion "
872 					"aborted (%s)", fname, strerror(errno));
873 			} else {
874 				log_err("wildcard include: %s: expansion "
875 					"failed (%s)", fname, strerror(errno));
876 			}
877 			/* ignore globs that yield no files */
878 			return 1;
879 		}
880 		/* process files found, if any */
881 		for(i=0; i<(size_t)g.gl_pathc; i++) {
882 			if(!config_read(cfg, g.gl_pathv[i], chroot)) {
883 				log_err("error reading wildcard "
884 					"include: %s", g.gl_pathv[i]);
885 				globfree(&g);
886 				return 0;
887 			}
888 		}
889 		globfree(&g);
890 		return 1;
891 	}
892 #endif /* HAVE_GLOB */
893 
894 	in = fopen(fname, "r");
895 	if(!in) {
896 		log_err("Could not open %s: %s", fname, strerror(errno));
897 		return 0;
898 	}
899 	create_cfg_parser(cfg, fname, chroot);
900 	ub_c_in = in;
901 	ub_c_parse();
902 	fclose(in);
903 
904 	if(cfg_parser->errors != 0) {
905 		fprintf(stderr, "read %s failed: %d errors in configuration file\n",
906 			fname, cfg_parser->errors);
907 		errno=EINVAL;
908 		return 0;
909 	}
910 
911 	return 1;
912 }
913 
914 struct config_stub* cfg_stub_find(struct config_stub*** pp, const char* nm)
915 {
916 	struct config_stub* p = *(*pp);
917 	while(p) {
918 		if(strcmp(p->name, nm) == 0)
919 			return p;
920 		(*pp) = &p->next;
921 		p = p->next;
922 	}
923 	return NULL;
924 }
925 
926 void
927 config_delstrlist(struct config_strlist* p)
928 {
929 	struct config_strlist *np;
930 	while(p) {
931 		np = p->next;
932 		free(p->str);
933 		free(p);
934 		p = np;
935 	}
936 }
937 
938 void
939 config_deldblstrlist(struct config_str2list* p)
940 {
941 	struct config_str2list *np;
942 	while(p) {
943 		np = p->next;
944 		free(p->str);
945 		free(p->str2);
946 		free(p);
947 		p = np;
948 	}
949 }
950 
951 void
952 config_deltrplstrlist(struct config_str3list* p)
953 {
954 	struct config_str3list *np;
955 	while(p) {
956 		np = p->next;
957 		free(p->str);
958 		free(p->str2);
959 		free(p->str3);
960 		free(p);
961 		p = np;
962 	}
963 }
964 
965 void
966 config_delstub(struct config_stub* p)
967 {
968 	if(!p) return;
969 	free(p->name);
970 	config_delstrlist(p->hosts);
971 	config_delstrlist(p->addrs);
972 	free(p);
973 }
974 
975 void
976 config_delstubs(struct config_stub* p)
977 {
978 	struct config_stub* np;
979 	while(p) {
980 		np = p->next;
981 		config_delstub(p);
982 		p = np;
983 	}
984 }
985 
986 /** delete string array */
987 static void
988 config_del_strarray(char** array, int num)
989 {
990 	int i;
991 	if(!array)
992 		return;
993 	for(i=0; i<num; i++) {
994 		free(array[i]);
995 	}
996 	free(array);
997 }
998 
999 void
1000 config_del_strbytelist(struct config_strbytelist* p)
1001 {
1002 	struct config_strbytelist* np;
1003 	while(p) {
1004 		np = p->next;
1005 		free(p->str);
1006 		free(p->str2);
1007 		free(p);
1008 		p = np;
1009 	}
1010 }
1011 
1012 void
1013 config_delete(struct config_file* cfg)
1014 {
1015 	if(!cfg) return;
1016 	free(cfg->username);
1017 	free(cfg->chrootdir);
1018 	free(cfg->directory);
1019 	free(cfg->logfile);
1020 	free(cfg->pidfile);
1021 	free(cfg->target_fetch_policy);
1022 	free(cfg->ssl_service_key);
1023 	free(cfg->ssl_service_pem);
1024 	config_del_strarray(cfg->ifs, cfg->num_ifs);
1025 	config_del_strarray(cfg->out_ifs, cfg->num_out_ifs);
1026 	config_delstubs(cfg->stubs);
1027 	config_delstubs(cfg->forwards);
1028 	config_delstrlist(cfg->donotqueryaddrs);
1029 	config_delstrlist(cfg->root_hints);
1030 	free(cfg->identity);
1031 	free(cfg->version);
1032 	free(cfg->module_conf);
1033 	free(cfg->outgoing_avail_ports);
1034 	config_delstrlist(cfg->caps_whitelist);
1035 	config_delstrlist(cfg->private_address);
1036 	config_delstrlist(cfg->private_domain);
1037 	config_delstrlist(cfg->auto_trust_anchor_file_list);
1038 	config_delstrlist(cfg->trust_anchor_file_list);
1039 	config_delstrlist(cfg->trusted_keys_file_list);
1040 	config_delstrlist(cfg->trust_anchor_list);
1041 	config_delstrlist(cfg->domain_insecure);
1042 	free(cfg->dlv_anchor_file);
1043 	config_delstrlist(cfg->dlv_anchor_list);
1044 	config_deldblstrlist(cfg->acls);
1045 	free(cfg->val_nsec3_key_iterations);
1046 	config_deldblstrlist(cfg->local_zones);
1047 	config_delstrlist(cfg->local_zones_nodefault);
1048 	config_delstrlist(cfg->local_data);
1049 	config_deltrplstrlist(cfg->local_zone_overrides);
1050 	config_del_strarray(cfg->tagname, cfg->num_tags);
1051 	config_del_strbytelist(cfg->local_zone_tags);
1052 	config_del_strbytelist(cfg->acl_tags);
1053 	config_deltrplstrlist(cfg->acl_tag_actions);
1054 	config_deltrplstrlist(cfg->acl_tag_datas);
1055 	config_delstrlist(cfg->control_ifs);
1056 	free(cfg->server_key_file);
1057 	free(cfg->server_cert_file);
1058 	free(cfg->control_key_file);
1059 	free(cfg->control_cert_file);
1060 	free(cfg->dns64_prefix);
1061 	free(cfg->dnstap_socket_path);
1062 	free(cfg->dnstap_identity);
1063 	free(cfg->dnstap_version);
1064 	config_deldblstrlist(cfg->ratelimit_for_domain);
1065 	config_deldblstrlist(cfg->ratelimit_below_domain);
1066 	free(cfg);
1067 }
1068 
1069 static void
1070 init_outgoing_availports(int* a, int num)
1071 {
1072 	/* generated with make iana_update */
1073 	const int iana_assigned[] = {
1074 #include "util/iana_ports.inc"
1075 		-1 }; /* end marker to put behind trailing comma */
1076 
1077 	int i;
1078 	/* do not use <1024, that could be trouble with the system, privs */
1079 	for(i=1024; i<num; i++) {
1080 		a[i] = i;
1081 	}
1082 	/* create empty spot at 49152 to keep ephemeral ports available
1083 	 * to other programs */
1084 	for(i=49152; i<49152+256; i++)
1085 		a[i] = 0;
1086 	/* pick out all the IANA assigned ports */
1087 	for(i=0; iana_assigned[i]!=-1; i++) {
1088 		if(iana_assigned[i] < num)
1089 			a[iana_assigned[i]] = 0;
1090 	}
1091 }
1092 
1093 int
1094 cfg_mark_ports(const char* str, int allow, int* avail, int num)
1095 {
1096 	char* mid = strchr(str, '-');
1097 	if(!mid) {
1098 		int port = atoi(str);
1099 		if(port == 0 && strcmp(str, "0") != 0) {
1100 			log_err("cannot parse port number '%s'", str);
1101 			return 0;
1102 		}
1103 		if(port < num)
1104 			avail[port] = (allow?port:0);
1105 	} else {
1106 		int i, low, high = atoi(mid+1);
1107 		char buf[16];
1108 		if(high == 0 && strcmp(mid+1, "0") != 0) {
1109 			log_err("cannot parse port number '%s'", mid+1);
1110 			return 0;
1111 		}
1112 		if( (int)(mid-str)+1 >= (int)sizeof(buf) ) {
1113 			log_err("cannot parse port number '%s'", str);
1114 			return 0;
1115 		}
1116 		if(mid > str)
1117 			memcpy(buf, str, (size_t)(mid-str));
1118 		buf[mid-str] = 0;
1119 		low = atoi(buf);
1120 		if(low == 0 && strcmp(buf, "0") != 0) {
1121 			log_err("cannot parse port number '%s'", buf);
1122 			return 0;
1123 		}
1124 		for(i=low; i<=high; i++) {
1125 			if(i < num)
1126 				avail[i] = (allow?i:0);
1127 		}
1128 		return 1;
1129 	}
1130 	return 1;
1131 }
1132 
1133 int
1134 cfg_scan_ports(int* avail, int num)
1135 {
1136 	int i;
1137 	int count = 0;
1138 	for(i=0; i<num; i++) {
1139 		if(avail[i])
1140 			count++;
1141 	}
1142 	return count;
1143 }
1144 
1145 int cfg_condense_ports(struct config_file* cfg, int** avail)
1146 {
1147 	int num = cfg_scan_ports(cfg->outgoing_avail_ports, 65536);
1148 	int i, at = 0;
1149 	*avail = NULL;
1150 	if(num == 0)
1151 		return 0;
1152 	*avail = (int*)reallocarray(NULL, (size_t)num, sizeof(int));
1153 	if(!*avail)
1154 		return 0;
1155 	for(i=0; i<65536; i++) {
1156 		if(cfg->outgoing_avail_ports[i])
1157 			(*avail)[at++] = cfg->outgoing_avail_ports[i];
1158 	}
1159 	log_assert(at == num);
1160 	return num;
1161 }
1162 
1163 /** print error with file and line number */
1164 static void ub_c_error_va_list(const char *fmt, va_list args)
1165 {
1166 	cfg_parser->errors++;
1167 	fprintf(stderr, "%s:%d: error: ", cfg_parser->filename,
1168 	cfg_parser->line);
1169 	vfprintf(stderr, fmt, args);
1170 	fprintf(stderr, "\n");
1171 }
1172 
1173 /** print error with file and line number */
1174 void ub_c_error_msg(const char* fmt, ...)
1175 {
1176 	va_list args;
1177 	va_start(args, fmt);
1178 	ub_c_error_va_list(fmt, args);
1179 	va_end(args);
1180 }
1181 
1182 void ub_c_error(const char *str)
1183 {
1184 	cfg_parser->errors++;
1185 	fprintf(stderr, "%s:%d: error: %s\n", cfg_parser->filename,
1186 		cfg_parser->line, str);
1187 }
1188 
1189 int ub_c_wrap(void)
1190 {
1191 	return 1;
1192 }
1193 
1194 int cfg_strlist_append(struct config_strlist_head* list, char* item)
1195 {
1196 	struct config_strlist *s;
1197 	if(!item || !list)
1198 		return 0;
1199 	s = (struct config_strlist*)calloc(1, sizeof(struct config_strlist));
1200 	if(!s)
1201 		return 0;
1202 	s->str = item;
1203 	s->next = NULL;
1204 	if(list->last)
1205 		list->last->next = s;
1206 	else
1207 		list->first = s;
1208 	list->last = s;
1209 	return 1;
1210 }
1211 
1212 int
1213 cfg_region_strlist_insert(struct regional* region,
1214 	struct config_strlist** head, char* item)
1215 {
1216 	struct config_strlist *s;
1217 	if(!item || !head)
1218 		return 0;
1219 	s = (struct config_strlist*)regional_alloc_zero(region,
1220 		sizeof(struct config_strlist));
1221 	if(!s)
1222 		return 0;
1223 	s->str = item;
1224 	s->next = *head;
1225 	*head = s;
1226 	return 1;
1227 }
1228 
1229 int
1230 cfg_strlist_insert(struct config_strlist** head, char* item)
1231 {
1232 	struct config_strlist *s;
1233 	if(!item || !head)
1234 		return 0;
1235 	s = (struct config_strlist*)calloc(1, sizeof(struct config_strlist));
1236 	if(!s)
1237 		return 0;
1238 	s->str = item;
1239 	s->next = *head;
1240 	*head = s;
1241 	return 1;
1242 }
1243 
1244 int
1245 cfg_str2list_insert(struct config_str2list** head, char* item, char* i2)
1246 {
1247 	struct config_str2list *s;
1248 	if(!item || !i2 || !head)
1249 		return 0;
1250 	s = (struct config_str2list*)calloc(1, sizeof(struct config_str2list));
1251 	if(!s)
1252 		return 0;
1253 	s->str = item;
1254 	s->str2 = i2;
1255 	s->next = *head;
1256 	*head = s;
1257 	return 1;
1258 }
1259 
1260 int
1261 cfg_str3list_insert(struct config_str3list** head, char* item, char* i2,
1262 	char* i3)
1263 {
1264 	struct config_str3list *s;
1265 	if(!item || !i2 || !i3 || !head)
1266 		return 0;
1267 	s = (struct config_str3list*)calloc(1, sizeof(struct config_str3list));
1268 	if(!s)
1269 		return 0;
1270 	s->str = item;
1271 	s->str2 = i2;
1272 	s->str3 = i3;
1273 	s->next = *head;
1274 	*head = s;
1275 	return 1;
1276 }
1277 
1278 int
1279 cfg_strbytelist_insert(struct config_strbytelist** head, char* item,
1280 	uint8_t* i2, size_t i2len)
1281 {
1282 	struct config_strbytelist* s;
1283 	if(!item || !i2 || !head)
1284 		return 0;
1285 	s = (struct config_strbytelist*)calloc(1, sizeof(*s));
1286 	if(!s)
1287 		return 0;
1288 	s->str = item;
1289 	s->str2 = i2;
1290 	s->str2len = i2len;
1291 	s->next = *head;
1292 	*head = s;
1293 	return 1;
1294 }
1295 
1296 time_t
1297 cfg_convert_timeval(const char* str)
1298 {
1299 	time_t t;
1300 	struct tm tm;
1301 	memset(&tm, 0, sizeof(tm));
1302 	if(strlen(str) < 14)
1303 		return 0;
1304 	if(sscanf(str, "%4d%2d%2d%2d%2d%2d", &tm.tm_year, &tm.tm_mon,
1305 		&tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6)
1306 		return 0;
1307 	tm.tm_year -= 1900;
1308 	tm.tm_mon--;
1309 	/* Check values */
1310 	if (tm.tm_year < 70)	return 0;
1311 	if (tm.tm_mon < 0 || tm.tm_mon > 11)	return 0;
1312 	if (tm.tm_mday < 1 || tm.tm_mday > 31) 	return 0;
1313 	if (tm.tm_hour < 0 || tm.tm_hour > 23)	return 0;
1314 	if (tm.tm_min < 0 || tm.tm_min > 59)	return 0;
1315 	if (tm.tm_sec < 0 || tm.tm_sec > 59)	return 0;
1316 	/* call ldns conversion function */
1317 	t = sldns_mktime_from_utc(&tm);
1318 	return t;
1319 }
1320 
1321 int
1322 cfg_count_numbers(const char* s)
1323 {
1324 	/* format ::= (sp num)+ sp  */
1325 	/* num ::= [-](0-9)+        */
1326 	/* sp ::= (space|tab)*      */
1327 	int num = 0;
1328 	while(*s) {
1329 		while(*s && isspace((unsigned char)*s))
1330 			s++;
1331 		if(!*s) /* end of string */
1332 			break;
1333 		if(*s == '-')
1334 			s++;
1335 		if(!*s) /* only - not allowed */
1336 			return 0;
1337 		if(!isdigit((unsigned char)*s)) /* bad character */
1338 			return 0;
1339 		while(*s && isdigit((unsigned char)*s))
1340 			s++;
1341 		num++;
1342 	}
1343 	return num;
1344 }
1345 
1346 /** all digit number */
1347 static int isalldigit(const char* str, size_t l)
1348 {
1349 	size_t i;
1350 	for(i=0; i<l; i++)
1351 		if(!isdigit((unsigned char)str[i]))
1352 			return 0;
1353 	return 1;
1354 }
1355 
1356 int
1357 cfg_parse_memsize(const char* str, size_t* res)
1358 {
1359 	size_t len;
1360 	size_t mult = 1;
1361 	if(!str || (len=(size_t)strlen(str)) == 0) {
1362 		log_err("not a size: '%s'", str);
1363 		return 0;
1364 	}
1365 	if(isalldigit(str, len)) {
1366 		*res = (size_t)atol(str);
1367 		return 1;
1368 	}
1369 	/* check appended num */
1370 	while(len>0 && str[len-1]==' ')
1371 		len--;
1372 	if(len > 1 && str[len-1] == 'b')
1373 		len--;
1374 	else if(len > 1 && str[len-1] == 'B')
1375 		len--;
1376 
1377 	if(len > 1 && tolower((unsigned char)str[len-1]) == 'g')
1378 		mult = 1024*1024*1024;
1379 	else if(len > 1 && tolower((unsigned char)str[len-1]) == 'm')
1380 		mult = 1024*1024;
1381 	else if(len > 1 && tolower((unsigned char)str[len-1]) == 'k')
1382 		mult = 1024;
1383 	else if(len > 0 && isdigit((unsigned char)str[len-1]))
1384 		mult = 1;
1385 	else {
1386 		log_err("unknown size specifier: '%s'", str);
1387 		return 0;
1388 	}
1389 	while(len>1 && str[len-2]==' ')
1390 		len--;
1391 
1392 	if(!isalldigit(str, len-1)) {
1393 		log_err("unknown size specifier: '%s'", str);
1394 		return 0;
1395 	}
1396 	*res = ((size_t)atol(str)) * mult;
1397 	return 1;
1398 }
1399 
1400 int
1401 find_tag_id(struct config_file* cfg, const char* tag)
1402 {
1403 	int i;
1404 	for(i=0; i<cfg->num_tags; i++) {
1405 		if(strcmp(cfg->tagname[i], tag) == 0)
1406 			return i;
1407 	}
1408 	return -1;
1409 }
1410 
1411 int
1412 config_add_tag(struct config_file* cfg, const char* tag)
1413 {
1414 	char** newarray;
1415 	char* newtag;
1416 	if(find_tag_id(cfg, tag) != -1)
1417 		return 1; /* nothing to do */
1418 	newarray = (char**)malloc(sizeof(char*)*(cfg->num_tags+1));
1419 	if(!newarray)
1420 		return 0;
1421 	newtag = strdup(tag);
1422 	if(!newtag) {
1423 		free(newarray);
1424 		return 0;
1425 	}
1426 	if(cfg->tagname) {
1427 		memcpy(newarray, cfg->tagname, sizeof(char*)*cfg->num_tags);
1428 		free(cfg->tagname);
1429 	}
1430 	newarray[cfg->num_tags++] = newtag;
1431 	cfg->tagname = newarray;
1432 	return 1;
1433 }
1434 
1435 /** set a bit in a bit array */
1436 static void
1437 cfg_set_bit(uint8_t* bitlist, size_t len, int id)
1438 {
1439 	int pos = id/8;
1440 	log_assert((size_t)pos < len);
1441 	(void)len;
1442 	bitlist[pos] |= 1<<(id%8);
1443 }
1444 
1445 uint8_t* config_parse_taglist(struct config_file* cfg, char* str,
1446         size_t* listlen)
1447 {
1448 	uint8_t* taglist = NULL;
1449 	size_t len = 0;
1450 	char* p, *s;
1451 
1452 	/* allocate */
1453 	if(cfg->num_tags == 0) {
1454 		log_err("parse taglist, but no tags defined");
1455 		return 0;
1456 	}
1457 	len = (size_t)(cfg->num_tags+7)/8;
1458 	taglist = calloc(1, len);
1459 	if(!taglist) {
1460 		log_err("out of memory");
1461 		return 0;
1462 	}
1463 
1464 	/* parse */
1465 	s = str;
1466 	while((p=strsep(&s, " \t\n")) != NULL) {
1467 		if(*p) {
1468 			int id = find_tag_id(cfg, p);
1469 			/* set this bit in the bitlist */
1470 			if(id == -1) {
1471 				log_err("unknown tag: %s", p);
1472 				free(taglist);
1473 				return 0;
1474 			}
1475 			cfg_set_bit(taglist, len, id);
1476 		}
1477 	}
1478 
1479 	*listlen = len;
1480 	return taglist;
1481 }
1482 
1483 char* config_taglist2str(struct config_file* cfg, uint8_t* taglist,
1484         size_t taglen)
1485 {
1486 	char buf[10240];
1487 	size_t i, j, len = 0;
1488 	buf[0] = 0;
1489 	for(i=0; i<taglen; i++) {
1490 		if(taglist[i] == 0)
1491 			continue;
1492 		for(j=0; j<8; j++) {
1493 			if((taglist[i] & (1<<j)) != 0) {
1494 				size_t id = i*8 + j;
1495 				snprintf(buf+len, sizeof(buf)-len, "%s%s",
1496 					(len==0?"":" "), cfg->tagname[id]);
1497 				len += strlen(buf+len);
1498 			}
1499 		}
1500 	}
1501 	return strdup(buf);
1502 }
1503 
1504 int taglist_intersect(uint8_t* list1, size_t list1len, uint8_t* list2,
1505 	size_t list2len)
1506 {
1507 	size_t i;
1508 	if(!list1 || !list2)
1509 		return 0;
1510 	for(i=0; i<list1len && i<list2len; i++) {
1511 		if((list1[i] & list2[i]) != 0)
1512 			return 1;
1513 	}
1514 	return 0;
1515 }
1516 
1517 void
1518 config_apply(struct config_file* config)
1519 {
1520 	MAX_TTL = (time_t)config->max_ttl;
1521 	MIN_TTL = (time_t)config->min_ttl;
1522 	MAX_NEG_TTL = (time_t)config->max_negative_ttl;
1523 	RTT_MIN_TIMEOUT = config->infra_cache_min_rtt;
1524 	EDNS_ADVERTISED_SIZE = (uint16_t)config->edns_buffer_size;
1525 	MINIMAL_RESPONSES = config->minimal_responses;
1526 	RRSET_ROUNDROBIN = config->rrset_roundrobin;
1527 	log_set_time_asc(config->log_time_ascii);
1528 	autr_permit_small_holddown = config->permit_small_holddown;
1529 }
1530 
1531 void config_lookup_uid(struct config_file* cfg)
1532 {
1533 #ifdef HAVE_GETPWNAM
1534 	/* translate username into uid and gid */
1535 	if(cfg->username && cfg->username[0]) {
1536 		struct passwd *pwd;
1537 		if((pwd = getpwnam(cfg->username)) != NULL) {
1538 			cfg_uid = pwd->pw_uid;
1539 			cfg_gid = pwd->pw_gid;
1540 		}
1541 	}
1542 #else
1543 	(void)cfg;
1544 #endif
1545 }
1546 
1547 /**
1548  * Calculate string length of full pathname in original filesys
1549  * @param fname: the path name to convert.
1550  * 	Must not be null or empty.
1551  * @param cfg: config struct for chroot and chdir (if set).
1552  * @param use_chdir: if false, only chroot is applied.
1553  * @return length of string.
1554  *	remember to allocate one more for 0 at end in mallocs.
1555  */
1556 static size_t
1557 strlen_after_chroot(const char* fname, struct config_file* cfg, int use_chdir)
1558 {
1559 	size_t len = 0;
1560 	int slashit = 0;
1561 	if(cfg->chrootdir && cfg->chrootdir[0] &&
1562 		strncmp(cfg->chrootdir, fname, strlen(cfg->chrootdir)) == 0) {
1563 		/* already full pathname, return it */
1564 		return strlen(fname);
1565 	}
1566 	/* chroot */
1567 	if(cfg->chrootdir && cfg->chrootdir[0]) {
1568 		/* start with chrootdir */
1569 		len += strlen(cfg->chrootdir);
1570 		slashit = 1;
1571 	}
1572 	/* chdir */
1573 #ifdef UB_ON_WINDOWS
1574 	if(fname[0] != 0 && fname[1] == ':') {
1575 		/* full path, no chdir */
1576 	} else
1577 #endif
1578 	if(fname[0] == '/' || !use_chdir) {
1579 		/* full path, no chdir */
1580 	} else if(cfg->directory && cfg->directory[0]) {
1581 		/* prepend chdir */
1582 		if(slashit && cfg->directory[0] != '/')
1583 			len++;
1584 		if(cfg->chrootdir && cfg->chrootdir[0] &&
1585 			strncmp(cfg->chrootdir, cfg->directory,
1586 			strlen(cfg->chrootdir)) == 0)
1587 			len += strlen(cfg->directory)-strlen(cfg->chrootdir);
1588 		else	len += strlen(cfg->directory);
1589 		slashit = 1;
1590 	}
1591 	/* fname */
1592 	if(slashit && fname[0] != '/')
1593 		len++;
1594 	len += strlen(fname);
1595 	return len;
1596 }
1597 
1598 char*
1599 fname_after_chroot(const char* fname, struct config_file* cfg, int use_chdir)
1600 {
1601 	size_t len = strlen_after_chroot(fname, cfg, use_chdir)+1;
1602 	int slashit = 0;
1603 	char* buf = (char*)malloc(len);
1604 	if(!buf)
1605 		return NULL;
1606 	buf[0] = 0;
1607 	/* is fname already in chroot ? */
1608 	if(cfg->chrootdir && cfg->chrootdir[0] &&
1609 		strncmp(cfg->chrootdir, fname, strlen(cfg->chrootdir)) == 0) {
1610 		/* already full pathname, return it */
1611 		(void)strlcpy(buf, fname, len);
1612 		buf[len-1] = 0;
1613 		return buf;
1614 	}
1615 	/* chroot */
1616 	if(cfg->chrootdir && cfg->chrootdir[0]) {
1617 		/* start with chrootdir */
1618 		(void)strlcpy(buf, cfg->chrootdir, len);
1619 		slashit = 1;
1620 	}
1621 #ifdef UB_ON_WINDOWS
1622 	if(fname[0] != 0 && fname[1] == ':') {
1623 		/* full path, no chdir */
1624 	} else
1625 #endif
1626 	/* chdir */
1627 	if(fname[0] == '/' || !use_chdir) {
1628 		/* full path, no chdir */
1629 	} else if(cfg->directory && cfg->directory[0]) {
1630 		/* prepend chdir */
1631 		if(slashit && cfg->directory[0] != '/')
1632 			(void)strlcat(buf, "/", len);
1633 		/* is the directory already in the chroot? */
1634 		if(cfg->chrootdir && cfg->chrootdir[0] &&
1635 			strncmp(cfg->chrootdir, cfg->directory,
1636 			strlen(cfg->chrootdir)) == 0)
1637 			(void)strlcat(buf, cfg->directory+strlen(cfg->chrootdir),
1638 				   len);
1639 		else (void)strlcat(buf, cfg->directory, len);
1640 		slashit = 1;
1641 	}
1642 	/* fname */
1643 	if(slashit && fname[0] != '/')
1644 		(void)strlcat(buf, "/", len);
1645 	(void)strlcat(buf, fname, len);
1646 	buf[len-1] = 0;
1647 	return buf;
1648 }
1649 
1650 /** return next space character in string */
1651 static char* next_space_pos(const char* str)
1652 {
1653 	char* sp = strchr(str, ' ');
1654 	char* tab = strchr(str, '\t');
1655 	if(!tab && !sp)
1656 		return NULL;
1657 	if(!sp) return tab;
1658 	if(!tab) return sp;
1659 	return (sp<tab)?sp:tab;
1660 }
1661 
1662 /** return last space character in string */
1663 static char* last_space_pos(const char* str)
1664 {
1665 	char* sp = strrchr(str, ' ');
1666 	char* tab = strrchr(str, '\t');
1667 	if(!tab && !sp)
1668 		return NULL;
1669 	if(!sp) return tab;
1670 	if(!tab) return sp;
1671 	return (sp>tab)?sp:tab;
1672 }
1673 
1674 int
1675 cfg_parse_local_zone(struct config_file* cfg, const char* val)
1676 {
1677 	const char *type, *name_end, *name;
1678 	char buf[256];
1679 
1680 	/* parse it as: [zone_name] [between stuff] [zone_type] */
1681 	name = val;
1682 	while(*name && isspace((unsigned char)*name))
1683 		name++;
1684 	if(!*name) {
1685 		log_err("syntax error: too short: %s", val);
1686 		return 0;
1687 	}
1688 	name_end = next_space_pos(name);
1689 	if(!name_end || !*name_end) {
1690 		log_err("syntax error: expected zone type: %s", val);
1691 		return 0;
1692 	}
1693 	if (name_end - name > 255) {
1694 		log_err("syntax error: bad zone name: %s", val);
1695 		return 0;
1696 	}
1697 	(void)strlcpy(buf, name, sizeof(buf));
1698 	buf[name_end-name] = '\0';
1699 
1700 	type = last_space_pos(name_end);
1701 	while(type && *type && isspace((unsigned char)*type))
1702 		type++;
1703 	if(!type || !*type) {
1704 		log_err("syntax error: expected zone type: %s", val);
1705 		return 0;
1706 	}
1707 
1708 	if(strcmp(type, "nodefault")==0) {
1709 		return cfg_strlist_insert(&cfg->local_zones_nodefault,
1710 			strdup(name));
1711 	} else {
1712 		return cfg_str2list_insert(&cfg->local_zones, strdup(buf),
1713 			strdup(type));
1714 	}
1715 }
1716 
1717 char* cfg_ptr_reverse(char* str)
1718 {
1719 	char* ip, *ip_end;
1720 	char* name;
1721 	char* result;
1722 	char buf[1024];
1723 	struct sockaddr_storage addr;
1724 	socklen_t addrlen;
1725 
1726 	/* parse it as: [IP] [between stuff] [name] */
1727 	ip = str;
1728 	while(*ip && isspace((unsigned char)*ip))
1729 		ip++;
1730 	if(!*ip) {
1731 		log_err("syntax error: too short: %s", str);
1732 		return NULL;
1733 	}
1734 	ip_end = next_space_pos(ip);
1735 	if(!ip_end || !*ip_end) {
1736 		log_err("syntax error: expected name: %s", str);
1737 		return NULL;
1738 	}
1739 
1740 	name = last_space_pos(ip_end);
1741 	if(!name || !*name) {
1742 		log_err("syntax error: expected name: %s", str);
1743 		return NULL;
1744 	}
1745 
1746 	sscanf(ip, "%100s", buf);
1747 	buf[sizeof(buf)-1]=0;
1748 
1749 	if(!ipstrtoaddr(buf, UNBOUND_DNS_PORT, &addr, &addrlen)) {
1750 		log_err("syntax error: cannot parse address: %s", str);
1751 		return NULL;
1752 	}
1753 
1754 	/* reverse IPv4:
1755 	 * ddd.ddd.ddd.ddd.in-addr-arpa.
1756 	 * IPv6: (h.){32}.ip6.arpa.  */
1757 
1758 	if(addr_is_ip6(&addr, addrlen)) {
1759 		uint8_t ad[16];
1760 		const char* hex = "0123456789abcdef";
1761 		char *p = buf;
1762 		int i;
1763 		memmove(ad, &((struct sockaddr_in6*)&addr)->sin6_addr,
1764 			sizeof(ad));
1765 		for(i=15; i>=0; i--) {
1766 			uint8_t b = ad[i];
1767 			*p++ = hex[ (b&0x0f) ];
1768 			*p++ = '.';
1769 			*p++ = hex[ (b&0xf0) >> 4 ];
1770 			*p++ = '.';
1771 		}
1772 		snprintf(buf+16*4, sizeof(buf)-16*4, "ip6.arpa. ");
1773 	} else {
1774 		uint8_t ad[4];
1775 		memmove(ad, &((struct sockaddr_in*)&addr)->sin_addr,
1776 			sizeof(ad));
1777 		snprintf(buf, sizeof(buf), "%u.%u.%u.%u.in-addr.arpa. ",
1778 			(unsigned)ad[3], (unsigned)ad[2],
1779 			(unsigned)ad[1], (unsigned)ad[0]);
1780 	}
1781 
1782 	/* printed the reverse address, now the between goop and name on end */
1783 	while(*ip_end && isspace((unsigned char)*ip_end))
1784 		ip_end++;
1785 	if(name>ip_end) {
1786 		snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%.*s",
1787 			(int)(name-ip_end), ip_end);
1788 	}
1789 	snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), " PTR %s", name);
1790 
1791 	result = strdup(buf);
1792 	if(!result) {
1793 		log_err("out of memory parsing %s", str);
1794 		return NULL;
1795 	}
1796 	return result;
1797 }
1798 
1799 #ifdef UB_ON_WINDOWS
1800 char*
1801 w_lookup_reg_str(const char* key, const char* name)
1802 {
1803 	HKEY hk = NULL;
1804 	DWORD type = 0;
1805 	BYTE buf[1024];
1806 	DWORD len = (DWORD)sizeof(buf);
1807 	LONG ret;
1808 	char* result = NULL;
1809 	ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hk);
1810 	if(ret == ERROR_FILE_NOT_FOUND)
1811 		return NULL; /* key does not exist */
1812 	else if(ret != ERROR_SUCCESS) {
1813 		log_err("RegOpenKeyEx failed");
1814 		return NULL;
1815 	}
1816 	ret = RegQueryValueEx(hk, (LPCTSTR)name, 0, &type, buf, &len);
1817 	if(RegCloseKey(hk))
1818 		log_err("RegCloseKey");
1819 	if(ret == ERROR_FILE_NOT_FOUND)
1820 		return NULL; /* name does not exist */
1821 	else if(ret != ERROR_SUCCESS) {
1822 		log_err("RegQueryValueEx failed");
1823 		return NULL;
1824 	}
1825 	if(type == REG_SZ || type == REG_MULTI_SZ || type == REG_EXPAND_SZ) {
1826 		buf[sizeof(buf)-1] = 0;
1827 		buf[sizeof(buf)-2] = 0; /* for multi_sz */
1828 		result = strdup((char*)buf);
1829 		if(!result) log_err("out of memory");
1830 	}
1831 	return result;
1832 }
1833 
1834 void w_config_adjust_directory(struct config_file* cfg)
1835 {
1836 	if(cfg->directory && cfg->directory[0]) {
1837 		TCHAR dirbuf[2*MAX_PATH+4];
1838 		if(strcmp(cfg->directory, "%EXECUTABLE%") == 0) {
1839 			/* get executable path, and if that contains
1840 			 * directories, snip off the filename part */
1841 			dirbuf[0] = 0;
1842 			if(!GetModuleFileName(NULL, dirbuf, MAX_PATH))
1843 				log_err("could not GetModuleFileName");
1844 			if(strrchr(dirbuf, '\\')) {
1845 				(strrchr(dirbuf, '\\'))[0] = 0;
1846 			} else log_err("GetModuleFileName had no path");
1847 			if(dirbuf[0]) {
1848 				/* adjust directory for later lookups to work*/
1849 				free(cfg->directory);
1850 				cfg->directory = memdup(dirbuf, strlen(dirbuf)+1);
1851 			}
1852 		}
1853 	}
1854 }
1855 #endif /* UB_ON_WINDOWS */
1856 
1857 void errinf(struct module_qstate* qstate, const char* str)
1858 {
1859 	struct config_strlist* p;
1860 	if(qstate->env->cfg->val_log_level < 2 || !str)
1861 		return;
1862 	p = (struct config_strlist*)regional_alloc(qstate->region, sizeof(*p));
1863 	if(!p) {
1864 		log_err("malloc failure in validator-error-info string");
1865 		return;
1866 	}
1867 	p->next = NULL;
1868 	p->str = regional_strdup(qstate->region, str);
1869 	if(!p->str) {
1870 		log_err("malloc failure in validator-error-info string");
1871 		return;
1872 	}
1873 	/* add at end */
1874 	if(qstate->errinf) {
1875 		struct config_strlist* q = qstate->errinf;
1876 		while(q->next)
1877 			q = q->next;
1878 		q->next = p;
1879 	} else	qstate->errinf = p;
1880 }
1881 
1882 void errinf_origin(struct module_qstate* qstate, struct sock_list *origin)
1883 {
1884 	struct sock_list* p;
1885 	if(qstate->env->cfg->val_log_level < 2)
1886 		return;
1887 	for(p=origin; p; p=p->next) {
1888 		char buf[256];
1889 		if(p == origin)
1890 			snprintf(buf, sizeof(buf), "from ");
1891 		else	snprintf(buf, sizeof(buf), "and ");
1892 		if(p->len == 0)
1893 			snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf),
1894 				"cache");
1895 		else
1896 			addr_to_str(&p->addr, p->len, buf+strlen(buf),
1897 				sizeof(buf)-strlen(buf));
1898 		errinf(qstate, buf);
1899 	}
1900 }
1901 
1902 char* errinf_to_str(struct module_qstate* qstate)
1903 {
1904 	char buf[20480];
1905 	char* p = buf;
1906 	size_t left = sizeof(buf);
1907 	struct config_strlist* s;
1908 	char dname[LDNS_MAX_DOMAINLEN+1];
1909 	char t[16], c[16];
1910 	sldns_wire2str_type_buf(qstate->qinfo.qtype, t, sizeof(t));
1911 	sldns_wire2str_class_buf(qstate->qinfo.qclass, c, sizeof(c));
1912 	dname_str(qstate->qinfo.qname, dname);
1913 	snprintf(p, left, "validation failure <%s %s %s>:", dname, t, c);
1914 	left -= strlen(p); p += strlen(p);
1915 	if(!qstate->errinf)
1916 		snprintf(p, left, " misc failure");
1917 	else for(s=qstate->errinf; s; s=s->next) {
1918 		snprintf(p, left, " %s", s->str);
1919 		left -= strlen(p); p += strlen(p);
1920 	}
1921 	p = strdup(buf);
1922 	if(!p)
1923 		log_err("malloc failure in errinf_to_str");
1924 	return p;
1925 }
1926 
1927 void errinf_rrset(struct module_qstate* qstate, struct ub_packed_rrset_key *rr)
1928 {
1929 	char buf[1024];
1930 	char dname[LDNS_MAX_DOMAINLEN+1];
1931 	char t[16], c[16];
1932 	if(qstate->env->cfg->val_log_level < 2 || !rr)
1933 		return;
1934 	sldns_wire2str_type_buf(ntohs(rr->rk.type), t, sizeof(t));
1935 	sldns_wire2str_class_buf(ntohs(rr->rk.rrset_class), c, sizeof(c));
1936 	dname_str(rr->rk.dname, dname);
1937 	snprintf(buf, sizeof(buf), "for <%s %s %s>", dname, t, c);
1938 	errinf(qstate, buf);
1939 }
1940 
1941 void errinf_dname(struct module_qstate* qstate, const char* str, uint8_t* dname)
1942 {
1943 	char b[1024];
1944 	char buf[LDNS_MAX_DOMAINLEN+1];
1945 	if(qstate->env->cfg->val_log_level < 2 || !str || !dname)
1946 		return;
1947 	dname_str(dname, buf);
1948 	snprintf(b, sizeof(b), "%s %s", str, buf);
1949 	errinf(qstate, b);
1950 }
1951