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