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