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