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