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