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