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