xref: /freebsd/contrib/unbound/util/config_file.c (revision 8ef24a0d4b28fe230e20637f56869cc4148cd2ca)
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 HAVE_PWD_H
66 #include <pwd.h>
67 #endif
68 
69 /** from cfg username, after daemonise setup performed */
70 uid_t cfg_uid = (uid_t)-1;
71 /** from cfg username, after daemonise setup performed */
72 gid_t cfg_gid = (gid_t)-1;
73 /** for debug allow small timeout values for fast rollovers */
74 int autr_permit_small_holddown = 0;
75 
76 /** global config during parsing */
77 struct config_parser_state* cfg_parser = 0;
78 
79 /** init ports possible for use */
80 static void init_outgoing_availports(int* array, int num);
81 
82 struct config_file*
83 config_create(void)
84 {
85 	struct config_file* cfg;
86 	cfg = (struct config_file*)calloc(1, sizeof(struct config_file));
87 	if(!cfg)
88 		return NULL;
89 	/* the defaults if no config is present */
90 	cfg->verbosity = 1;
91 	cfg->stat_interval = 0;
92 	cfg->stat_cumulative = 0;
93 	cfg->stat_extended = 0;
94 	cfg->num_threads = 1;
95 	cfg->port = UNBOUND_DNS_PORT;
96 	cfg->do_ip4 = 1;
97 	cfg->do_ip6 = 1;
98 	cfg->do_udp = 1;
99 	cfg->do_tcp = 1;
100 	cfg->tcp_upstream = 0;
101 	cfg->tcp_mss = 0;
102 	cfg->outgoing_tcp_mss = 0;
103 	cfg->ssl_service_key = NULL;
104 	cfg->ssl_service_pem = NULL;
105 	cfg->ssl_port = 853;
106 	cfg->ssl_upstream = 0;
107 	cfg->use_syslog = 1;
108 	cfg->log_time_ascii = 0;
109 	cfg->log_queries = 0;
110 #ifndef USE_WINSOCK
111 #  ifdef USE_MINI_EVENT
112 	/* select max 1024 sockets */
113 	cfg->outgoing_num_ports = 960;
114 	cfg->num_queries_per_thread = 512;
115 #  else
116 	/* libevent can use many sockets */
117 	cfg->outgoing_num_ports = 4096;
118 	cfg->num_queries_per_thread = 1024;
119 #  endif
120 	cfg->outgoing_num_tcp = 10;
121 	cfg->incoming_num_tcp = 10;
122 #else
123 	cfg->outgoing_num_ports = 48; /* windows is limited in num fds */
124 	cfg->num_queries_per_thread = 24;
125 	cfg->outgoing_num_tcp = 2; /* leaves 64-52=12 for: 4if,1stop,thread4 */
126 	cfg->incoming_num_tcp = 2;
127 #endif
128 	cfg->edns_buffer_size = 4096; /* 4k from rfc recommendation */
129 	cfg->msg_buffer_size = 65552; /* 64 k + a small margin */
130 	cfg->msg_cache_size = 4 * 1024 * 1024;
131 	cfg->msg_cache_slabs = 4;
132 	cfg->jostle_time = 200;
133 	cfg->rrset_cache_size = 4 * 1024 * 1024;
134 	cfg->rrset_cache_slabs = 4;
135 	cfg->host_ttl = 900;
136 	cfg->bogus_ttl = 60;
137 	cfg->min_ttl = 0;
138 	cfg->max_ttl = 3600 * 24;
139 	cfg->max_negative_ttl = 3600;
140 	cfg->prefetch = 0;
141 	cfg->prefetch_key = 0;
142 	cfg->infra_cache_slabs = 4;
143 	cfg->infra_cache_numhosts = 10000;
144 	cfg->infra_cache_min_rtt = 50;
145 	cfg->delay_close = 0;
146 	if(!(cfg->outgoing_avail_ports = (int*)calloc(65536, sizeof(int))))
147 		goto error_exit;
148 	init_outgoing_availports(cfg->outgoing_avail_ports, 65536);
149 	if(!(cfg->username = strdup(UB_USERNAME))) goto error_exit;
150 #ifdef HAVE_CHROOT
151 	if(!(cfg->chrootdir = strdup(CHROOT_DIR))) goto error_exit;
152 #endif
153 	if(!(cfg->directory = strdup(RUN_DIR))) goto error_exit;
154 	if(!(cfg->logfile = strdup(""))) goto error_exit;
155 	if(!(cfg->pidfile = strdup(PIDFILE))) goto error_exit;
156 	if(!(cfg->target_fetch_policy = strdup("3 2 1 0 0"))) goto error_exit;
157 	cfg->donotqueryaddrs = NULL;
158 	cfg->donotquery_localhost = 1;
159 	cfg->root_hints = NULL;
160 	cfg->do_daemonize = 1;
161 	cfg->if_automatic = 0;
162 	cfg->so_rcvbuf = 0;
163 	cfg->so_sndbuf = 0;
164 	cfg->so_reuseport = 0;
165 	cfg->ip_transparent = 0;
166 	cfg->num_ifs = 0;
167 	cfg->ifs = NULL;
168 	cfg->num_out_ifs = 0;
169 	cfg->out_ifs = NULL;
170 	cfg->stubs = NULL;
171 	cfg->forwards = NULL;
172 	cfg->acls = NULL;
173 	cfg->harden_short_bufsize = 0;
174 	cfg->harden_large_queries = 0;
175 	cfg->harden_glue = 1;
176 	cfg->harden_dnssec_stripped = 1;
177 	cfg->harden_below_nxdomain = 0;
178 	cfg->harden_referral_path = 0;
179 	cfg->harden_algo_downgrade = 0;
180 	cfg->use_caps_bits_for_id = 0;
181 	cfg->caps_whitelist = NULL;
182 	cfg->private_address = NULL;
183 	cfg->private_domain = NULL;
184 	cfg->unwanted_threshold = 0;
185 	cfg->hide_identity = 0;
186 	cfg->hide_version = 0;
187 	cfg->identity = NULL;
188 	cfg->version = NULL;
189 	cfg->auto_trust_anchor_file_list = NULL;
190 	cfg->trust_anchor_file_list = NULL;
191 	cfg->trust_anchor_list = NULL;
192 	cfg->trusted_keys_file_list = NULL;
193 	cfg->dlv_anchor_file = NULL;
194 	cfg->dlv_anchor_list = NULL;
195 	cfg->domain_insecure = NULL;
196 	cfg->val_date_override = 0;
197 	cfg->val_sig_skew_min = 3600; /* at least daylight savings trouble */
198 	cfg->val_sig_skew_max = 86400; /* at most timezone settings trouble */
199 	cfg->val_clean_additional = 1;
200 	cfg->val_log_level = 0;
201 	cfg->val_log_squelch = 0;
202 	cfg->val_permissive_mode = 0;
203 	cfg->ignore_cd = 0;
204 	cfg->add_holddown = 30*24*3600;
205 	cfg->del_holddown = 30*24*3600;
206 	cfg->keep_missing = 366*24*3600; /* one year plus a little leeway */
207 	cfg->permit_small_holddown = 0;
208 	cfg->key_cache_size = 4 * 1024 * 1024;
209 	cfg->key_cache_slabs = 4;
210 	cfg->neg_cache_size = 1 * 1024 * 1024;
211 	cfg->local_zones = NULL;
212 	cfg->local_zones_nodefault = NULL;
213 	cfg->local_data = NULL;
214 	cfg->unblock_lan_zones = 0;
215 	cfg->insecure_lan_zones = 0;
216 	cfg->python_script = NULL;
217 	cfg->remote_control_enable = 0;
218 	cfg->control_ifs = NULL;
219 	cfg->control_port = UNBOUND_CONTROL_PORT;
220 	cfg->remote_control_use_cert = 1;
221 	cfg->minimal_responses = 0;
222 	cfg->rrset_roundrobin = 0;
223 	cfg->max_udp_size = 4096;
224 	if(!(cfg->server_key_file = strdup(RUN_DIR"/unbound_server.key")))
225 		goto error_exit;
226 	if(!(cfg->server_cert_file = strdup(RUN_DIR"/unbound_server.pem")))
227 		goto error_exit;
228 	if(!(cfg->control_key_file = strdup(RUN_DIR"/unbound_control.key")))
229 		goto error_exit;
230 	if(!(cfg->control_cert_file = strdup(RUN_DIR"/unbound_control.pem")))
231 		goto error_exit;
232 
233 	if(!(cfg->module_conf = strdup("validator iterator"))) goto error_exit;
234 	if(!(cfg->val_nsec3_key_iterations =
235 		strdup("1024 150 2048 500 4096 2500"))) goto error_exit;
236 #if defined(DNSTAP_SOCKET_PATH)
237 	if(!(cfg->dnstap_socket_path = strdup(DNSTAP_SOCKET_PATH)))
238 		goto error_exit;
239 #endif
240 	cfg->ratelimit = 0;
241 	cfg->ratelimit_slabs = 4;
242 	cfg->ratelimit_size = 4*1024*1024;
243 	cfg->ratelimit_for_domain = NULL;
244 	cfg->ratelimit_below_domain = NULL;
245 	cfg->ratelimit_factor = 10;
246 	cfg->qname_minimisation = 0;
247 	return cfg;
248 error_exit:
249 	config_delete(cfg);
250 	return NULL;
251 }
252 
253 struct config_file* config_create_forlib(void)
254 {
255 	struct config_file* cfg = config_create();
256 	if(!cfg) return NULL;
257 	/* modifications for library use, less verbose, less memory */
258 	free(cfg->chrootdir);
259 	cfg->chrootdir = NULL;
260 	cfg->verbosity = 0;
261 	cfg->outgoing_num_ports = 16; /* in library use, this is 'reasonable'
262 		and probably within the ulimit(maxfds) of the user */
263 	cfg->outgoing_num_tcp = 2;
264 	cfg->msg_cache_size = 1024*1024;
265 	cfg->msg_cache_slabs = 1;
266 	cfg->rrset_cache_size = 1024*1024;
267 	cfg->rrset_cache_slabs = 1;
268 	cfg->infra_cache_slabs = 1;
269 	cfg->use_syslog = 0;
270 	cfg->key_cache_size = 1024*1024;
271 	cfg->key_cache_slabs = 1;
272 	cfg->neg_cache_size = 100 * 1024;
273 	cfg->donotquery_localhost = 0; /* allow, so that you can ask a
274 		forward nameserver running on localhost */
275 	cfg->val_log_level = 2; /* to fill why_bogus with */
276 	cfg->val_log_squelch = 1;
277 	return cfg;
278 }
279 
280 /** check that the value passed is >= 0 */
281 #define IS_NUMBER_OR_ZERO \
282 	if(atoi(val) == 0 && strcmp(val, "0") != 0) return 0
283 /** check that the value passed is > 0 */
284 #define IS_NONZERO_NUMBER \
285 	if(atoi(val) == 0) return 0
286 /** check that the value passed is not 0 and a power of 2 */
287 #define IS_POW2_NUMBER \
288 	if(atoi(val) == 0 || !is_pow2((size_t)atoi(val))) return 0
289 /** check that the value passed is yes or no */
290 #define IS_YES_OR_NO \
291 	if(strcmp(val, "yes") != 0 && strcmp(val, "no") != 0) return 0
292 /** put integer_or_zero into variable */
293 #define S_NUMBER_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
294 	{ IS_NUMBER_OR_ZERO; cfg->var = atoi(val); }
295 /** put integer_nonzero into variable */
296 #define S_NUMBER_NONZERO(str, var) if(strcmp(opt, str) == 0) \
297 	{ IS_NONZERO_NUMBER; cfg->var = atoi(val); }
298 /** put integer_or_zero into unsigned */
299 #define S_UNSIGNED_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
300 	{ IS_NUMBER_OR_ZERO; cfg->var = (unsigned)atoi(val); }
301 /** put integer_or_zero into size_t */
302 #define S_SIZET_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
303 	{ IS_NUMBER_OR_ZERO; cfg->var = (size_t)atoi(val); }
304 /** put integer_nonzero into size_t */
305 #define S_SIZET_NONZERO(str, var) if(strcmp(opt, str) == 0) \
306 	{ IS_NONZERO_NUMBER; cfg->var = (size_t)atoi(val); }
307 /** put yesno into variable */
308 #define S_YNO(str, var) if(strcmp(opt, str) == 0) \
309 	{ IS_YES_OR_NO; cfg->var = (strcmp(val, "yes") == 0); }
310 /** put memsize into variable */
311 #define S_MEMSIZE(str, var) if(strcmp(opt, str)==0) \
312 	{ return cfg_parse_memsize(val, &cfg->var); }
313 /** put pow2 number into variable */
314 #define S_POW2(str, var) if(strcmp(opt, str)==0) \
315 	{ IS_POW2_NUMBER; cfg->var = (size_t)atoi(val); }
316 /** put string into variable */
317 #define S_STR(str, var) if(strcmp(opt, str)==0) \
318 	{ free(cfg->var); return (cfg->var = strdup(val)) != NULL; }
319 /** put string into strlist */
320 #define S_STRLIST(str, var) if(strcmp(opt, str)==0) \
321 	{ return cfg_strlist_insert(&cfg->var, strdup(val)); }
322 
323 int config_set_option(struct config_file* cfg, const char* opt,
324 	const char* val)
325 {
326 	S_NUMBER_OR_ZERO("verbosity:", verbosity)
327 	else if(strcmp(opt, "statistics-interval:") == 0) {
328 		if(strcmp(val, "0") == 0 || strcmp(val, "") == 0)
329 			cfg->stat_interval = 0;
330 		else if(atoi(val) == 0)
331 			return 0;
332 		else cfg->stat_interval = atoi(val);
333 	} else if(strcmp(opt, "num_threads:") == 0) {
334 		/* not supported, library must have 1 thread in bgworker */
335 		return 0;
336 	} else if(strcmp(opt, "outgoing-port-permit:") == 0) {
337 		return cfg_mark_ports(val, 1,
338 			cfg->outgoing_avail_ports, 65536);
339 	} else if(strcmp(opt, "outgoing-port-avoid:") == 0) {
340 		return cfg_mark_ports(val, 0,
341 			cfg->outgoing_avail_ports, 65536);
342 	} else if(strcmp(opt, "local-zone:") == 0) {
343 		return cfg_parse_local_zone(cfg, val);
344 	} else if(strcmp(opt, "val-override-date:") == 0) {
345 		if(strcmp(val, "") == 0 || strcmp(val, "0") == 0) {
346 			cfg->val_date_override = 0;
347 		} else if(strlen(val) == 14) {
348 			cfg->val_date_override = cfg_convert_timeval(val);
349 			return cfg->val_date_override != 0;
350 		} else {
351 			if(atoi(val) == 0) return 0;
352 			cfg->val_date_override = (uint32_t)atoi(val);
353 		}
354 	} else if(strcmp(opt, "local-data-ptr:") == 0) {
355 		char* ptr = cfg_ptr_reverse((char*)opt);
356 		return cfg_strlist_insert(&cfg->local_data, ptr);
357 	} else if(strcmp(opt, "logfile:") == 0) {
358 		cfg->use_syslog = 0;
359 		free(cfg->logfile);
360 		return (cfg->logfile = strdup(val)) != NULL;
361 	}
362 	else if(strcmp(opt, "log-time-ascii:") == 0)
363 	{ IS_YES_OR_NO; cfg->log_time_ascii = (strcmp(val, "yes") == 0);
364 	  log_set_time_asc(cfg->log_time_ascii); }
365 	else S_SIZET_NONZERO("max-udp-size:", max_udp_size)
366 	else S_YNO("use-syslog:", use_syslog)
367 	else S_YNO("extended-statistics:", stat_extended)
368 	else S_YNO("statistics-cumulative:", stat_cumulative)
369 	else S_YNO("do-ip4:", do_ip4)
370 	else S_YNO("do-ip6:", do_ip6)
371 	else S_YNO("do-udp:", do_udp)
372 	else S_YNO("do-tcp:", do_tcp)
373 	else S_YNO("tcp-upstream:", tcp_upstream)
374 	else S_NUMBER_NONZERO("tcp-mss:", tcp_mss)
375 	else S_NUMBER_NONZERO("outgoing-tcp-mss:", outgoing_tcp_mss)
376 	else S_YNO("ssl-upstream:", ssl_upstream)
377 	else S_STR("ssl-service-key:", ssl_service_key)
378 	else S_STR("ssl-service-pem:", ssl_service_pem)
379 	else S_NUMBER_NONZERO("ssl-port:", ssl_port)
380 	else S_YNO("interface-automatic:", if_automatic)
381 	else S_YNO("do-daemonize:", do_daemonize)
382 	else S_NUMBER_NONZERO("port:", port)
383 	else S_NUMBER_NONZERO("outgoing-range:", outgoing_num_ports)
384 	else S_SIZET_OR_ZERO("outgoing-num-tcp:", outgoing_num_tcp)
385 	else S_SIZET_OR_ZERO("incoming-num-tcp:", incoming_num_tcp)
386 	else S_SIZET_NONZERO("edns-buffer-size:", edns_buffer_size)
387 	else S_SIZET_NONZERO("msg-buffer-size:", msg_buffer_size)
388 	else S_MEMSIZE("msg-cache-size:", msg_cache_size)
389 	else S_POW2("msg-cache-slabs:", msg_cache_slabs)
390 	else S_SIZET_NONZERO("num-queries-per-thread:",num_queries_per_thread)
391 	else S_SIZET_OR_ZERO("jostle-timeout:", jostle_time)
392 	else S_MEMSIZE("so-rcvbuf:", so_rcvbuf)
393 	else S_MEMSIZE("so-sndbuf:", so_sndbuf)
394 	else S_YNO("so-reuseport:", so_reuseport)
395 	else S_YNO("ip-transparent:", ip_transparent)
396 	else S_MEMSIZE("rrset-cache-size:", rrset_cache_size)
397 	else S_POW2("rrset-cache-slabs:", rrset_cache_slabs)
398 	else S_YNO("prefetch:", prefetch)
399 	else S_YNO("prefetch-key:", prefetch_key)
400 	else if(strcmp(opt, "cache-max-ttl:") == 0)
401 	{ IS_NUMBER_OR_ZERO; cfg->max_ttl = atoi(val); MAX_TTL=(time_t)cfg->max_ttl;}
402 	else if(strcmp(opt, "cache-max-negative-ttl:") == 0)
403 	{ IS_NUMBER_OR_ZERO; cfg->max_negative_ttl = atoi(val); MAX_NEG_TTL=(time_t)cfg->max_negative_ttl;}
404 	else if(strcmp(opt, "cache-min-ttl:") == 0)
405 	{ IS_NUMBER_OR_ZERO; cfg->min_ttl = atoi(val); MIN_TTL=(time_t)cfg->min_ttl;}
406 	else if(strcmp(opt, "infra-cache-min-rtt:") == 0) {
407 	    IS_NUMBER_OR_ZERO; cfg->infra_cache_min_rtt = atoi(val);
408 	    RTT_MIN_TIMEOUT=cfg->infra_cache_min_rtt;
409 	}
410 	else S_NUMBER_OR_ZERO("infra-host-ttl:", host_ttl)
411 	else S_POW2("infra-cache-slabs:", infra_cache_slabs)
412 	else S_SIZET_NONZERO("infra-cache-numhosts:", infra_cache_numhosts)
413 	else S_NUMBER_OR_ZERO("delay-close:", delay_close)
414 	else S_STR("chroot:", chrootdir)
415 	else S_STR("username:", username)
416 	else S_STR("directory:", directory)
417 	else S_STR("pidfile:", pidfile)
418 	else S_YNO("hide-identity:", hide_identity)
419 	else S_YNO("hide-version:", hide_version)
420 	else S_STR("identity:", identity)
421 	else S_STR("version:", version)
422 	else S_STRLIST("root-hints:", root_hints)
423 	else S_STR("target-fetch-policy:", target_fetch_policy)
424 	else S_YNO("harden-glue:", harden_glue)
425 	else S_YNO("harden-short-bufsize:", harden_short_bufsize)
426 	else S_YNO("harden-large-queries:", harden_large_queries)
427 	else S_YNO("harden-dnssec-stripped:", harden_dnssec_stripped)
428 	else S_YNO("harden-below-nxdomain:", harden_below_nxdomain)
429 	else S_YNO("harden-referral-path:", harden_referral_path)
430 	else S_YNO("harden-algo-downgrade:", harden_algo_downgrade)
431 	else S_YNO("use-caps-for-id", use_caps_bits_for_id)
432 	else S_STRLIST("caps-whitelist:", caps_whitelist)
433 	else S_SIZET_OR_ZERO("unwanted-reply-threshold:", unwanted_threshold)
434 	else S_STRLIST("private-address:", private_address)
435 	else S_STRLIST("private-domain:", private_domain)
436 	else S_YNO("do-not-query-localhost:", donotquery_localhost)
437 	else S_STRLIST("do-not-query-address:", donotqueryaddrs)
438 	else S_STRLIST("auto-trust-anchor-file:", auto_trust_anchor_file_list)
439 	else S_STRLIST("trust-anchor-file:", trust_anchor_file_list)
440 	else S_STRLIST("trust-anchor:", trust_anchor_list)
441 	else S_STRLIST("trusted-keys-file:", trusted_keys_file_list)
442 	else S_STR("dlv-anchor-file:", dlv_anchor_file)
443 	else S_STRLIST("dlv-anchor:", dlv_anchor_list)
444 	else S_STRLIST("domain-insecure:", domain_insecure)
445 	else S_NUMBER_OR_ZERO("val-bogus-ttl:", bogus_ttl)
446 	else S_YNO("val-clean-additional:", val_clean_additional)
447 	else S_NUMBER_OR_ZERO("val-log-level:", val_log_level)
448 	else S_YNO("val-log-squelch:", val_log_squelch)
449 	else S_YNO("log-queries:", log_queries)
450 	else S_YNO("val-permissive-mode:", val_permissive_mode)
451 	else S_YNO("ignore-cd-flag:", ignore_cd)
452 	else S_STR("val-nsec3-keysize-iterations:", val_nsec3_key_iterations)
453 	else S_UNSIGNED_OR_ZERO("add-holddown:", add_holddown)
454 	else S_UNSIGNED_OR_ZERO("del-holddown:", del_holddown)
455 	else S_UNSIGNED_OR_ZERO("keep-missing:", keep_missing)
456 	else if(strcmp(opt, "permit-small-holddown:") == 0)
457 	{ IS_YES_OR_NO; cfg->permit_small_holddown = (strcmp(val, "yes") == 0);
458 	  autr_permit_small_holddown = cfg->permit_small_holddown; }
459 	else S_MEMSIZE("key-cache-size:", key_cache_size)
460 	else S_POW2("key-cache-slabs:", key_cache_slabs)
461 	else S_MEMSIZE("neg-cache-size:", neg_cache_size)
462 	else S_YNO("minimal-responses:", minimal_responses)
463 	else S_YNO("rrset-roundrobin:", rrset_roundrobin)
464 	else S_STRLIST("local-data:", local_data)
465 	else S_YNO("unblock-lan-zones:", unblock_lan_zones)
466 	else S_YNO("insecure-lan-zones:", insecure_lan_zones)
467 	else S_YNO("control-enable:", remote_control_enable)
468 	else S_STRLIST("control-interface:", control_ifs)
469 	else S_NUMBER_NONZERO("control-port:", control_port)
470 	else S_STR("server-key-file:", server_key_file)
471 	else S_STR("server-cert-file:", server_cert_file)
472 	else S_STR("control-key-file:", control_key_file)
473 	else S_STR("control-cert-file:", control_cert_file)
474 	else S_STR("module-config:", module_conf)
475 	else S_STR("python-script:", python_script)
476 	else if(strcmp(opt, "ratelimit:") == 0) {
477 	    IS_NUMBER_OR_ZERO; cfg->ratelimit = atoi(val);
478 	    infra_dp_ratelimit=cfg->ratelimit;
479 	}
480 	else S_MEMSIZE("ratelimit-size:", ratelimit_size)
481 	else S_POW2("ratelimit-slabs:", ratelimit_slabs)
482 	else S_NUMBER_OR_ZERO("ratelimit-factor:", ratelimit_factor)
483 	else S_YNO("qname-minimisation:", qname_minimisation)
484 	/* val_sig_skew_min and max are copied into val_env during init,
485 	 * so this does not update val_env with set_option */
486 	else if(strcmp(opt, "val-sig-skew-min:") == 0)
487 	{ IS_NUMBER_OR_ZERO; cfg->val_sig_skew_min = (int32_t)atoi(val); }
488 	else if(strcmp(opt, "val-sig-skew-max:") == 0)
489 	{ IS_NUMBER_OR_ZERO; cfg->val_sig_skew_max = (int32_t)atoi(val); }
490 	else if (strcmp(opt, "outgoing-interface:") == 0) {
491 		char* d = strdup(val);
492 		char** oi =
493 		(char**)reallocarray(NULL, (size_t)cfg->num_out_ifs+1, sizeof(char*));
494 		if(!d || !oi) { free(d); free(oi); return -1; }
495 		if(cfg->out_ifs && cfg->num_out_ifs) {
496 			memmove(oi, cfg->out_ifs, cfg->num_out_ifs*sizeof(char*));
497 			free(cfg->out_ifs);
498 		}
499 		oi[cfg->num_out_ifs++] = d;
500 		cfg->out_ifs = oi;
501 	} else {
502 		/* unknown or unsupported (from the set_option interface):
503 		 * interface, outgoing-interface, access-control,
504 		 * stub-zone, name, stub-addr, stub-host, stub-prime
505 		 * forward-first, stub-first,
506 		 * forward-zone, name, forward-addr, forward-host,
507 		 * ratelimit-for-domain, ratelimit-below-domain */
508 		return 0;
509 	}
510 	return 1;
511 }
512 
513 void config_print_func(char* line, void* arg)
514 {
515 	FILE* f = (FILE*)arg;
516 	(void)fprintf(f, "%s\n", line);
517 }
518 
519 /** collate func arg */
520 struct config_collate_arg {
521 	/** list of result items */
522 	struct config_strlist_head list;
523 	/** if a malloc error occurred, 0 is OK */
524 	int status;
525 };
526 
527 void config_collate_func(char* line, void* arg)
528 {
529 	struct config_collate_arg* m = (struct config_collate_arg*)arg;
530 	if(m->status)
531 		return;
532 	if(!cfg_strlist_append(&m->list, strdup(line)))
533 		m->status = 1;
534 }
535 
536 int config_get_option_list(struct config_file* cfg, const char* opt,
537 	struct config_strlist** list)
538 {
539 	struct config_collate_arg m;
540 	memset(&m, 0, sizeof(m));
541 	*list = NULL;
542 	if(!config_get_option(cfg, opt, config_collate_func, &m))
543 		return 1;
544 	if(m.status) {
545 		config_delstrlist(m.list.first);
546 		return 2;
547 	}
548 	*list = m.list.first;
549 	return 0;
550 }
551 
552 int
553 config_get_option_collate(struct config_file* cfg, const char* opt, char** str)
554 {
555 	struct config_strlist* list = NULL;
556 	int r;
557 	*str = NULL;
558 	if((r = config_get_option_list(cfg, opt, &list)) != 0)
559 		return r;
560 	*str = config_collate_cat(list);
561 	config_delstrlist(list);
562 	if(!*str) return 2;
563 	return 0;
564 }
565 
566 char*
567 config_collate_cat(struct config_strlist* list)
568 {
569 	size_t total = 0, left;
570 	struct config_strlist* s;
571 	char *r, *w;
572 	if(!list) /* no elements */
573 		return strdup("");
574 	if(list->next == NULL) /* one element , no newline at end. */
575 		return strdup(list->str);
576 	/* count total length */
577 	for(s=list; s; s=s->next)
578 		total += strlen(s->str) + 1; /* len + newline */
579 	left = total+1; /* one extra for nul at end */
580 	r = malloc(left);
581 	if(!r)
582 		return NULL;
583 	w = r;
584 	for(s=list; s; s=s->next) {
585 		size_t this = strlen(s->str);
586 		if(this+2 > left) { /* sanity check */
587 			free(r);
588 			return NULL;
589 		}
590 		snprintf(w, left, "%s\n", s->str);
591 		this = strlen(w);
592 		w += this;
593 		left -= this;
594 	}
595 	return r;
596 }
597 
598 /** compare and print decimal option */
599 #define O_DEC(opt, str, var) if(strcmp(opt, str)==0) \
600 	{snprintf(buf, len, "%d", (int)cfg->var); \
601 	func(buf, arg);}
602 /** compare and print unsigned option */
603 #define O_UNS(opt, str, var) if(strcmp(opt, str)==0) \
604 	{snprintf(buf, len, "%u", (unsigned)cfg->var); \
605 	func(buf, arg);}
606 /** compare and print yesno option */
607 #define O_YNO(opt, str, var) if(strcmp(opt, str)==0) \
608 	{func(cfg->var?"yes":"no", arg);}
609 /** compare and print string option */
610 #define O_STR(opt, str, var) if(strcmp(opt, str)==0) \
611 	{func(cfg->var?cfg->var:"", arg);}
612 /** compare and print array option */
613 #define O_IFC(opt, str, num, arr) if(strcmp(opt, str)==0) \
614 	{int i; for(i=0; i<cfg->num; i++) func(cfg->arr[i], arg);}
615 /** compare and print memorysize option */
616 #define O_MEM(opt, str, var) if(strcmp(opt, str)==0) { \
617 	if(cfg->var > 1024*1024*1024) {	\
618 	  size_t f=cfg->var/(size_t)1000000, b=cfg->var%(size_t)1000000; \
619 	  snprintf(buf, len, "%u%6.6u", (unsigned)f, (unsigned)b); \
620 	} else snprintf(buf, len, "%u", (unsigned)cfg->var); \
621 	func(buf, arg);}
622 /** compare and print list option */
623 #define O_LST(opt, name, lst) if(strcmp(opt, name)==0) { \
624 	struct config_strlist* p = cfg->lst; \
625 	for(p = cfg->lst; p; p = p->next) \
626 		func(p->str, arg); \
627 	}
628 /** compare and print list option */
629 #define O_LS2(opt, name, lst) if(strcmp(opt, name)==0) { \
630 	struct config_str2list* p = cfg->lst; \
631 	for(p = cfg->lst; p; p = p->next) \
632 		snprintf(buf, len, "%s %s\n", p->str, p->str2); \
633 		func(buf, arg); \
634 	}
635 
636 int
637 config_get_option(struct config_file* cfg, const char* opt,
638 	void (*func)(char*,void*), void* arg)
639 {
640 	char buf[1024];
641 	size_t len = sizeof(buf);
642 	fptr_ok(fptr_whitelist_print_func(func));
643 	O_DEC(opt, "verbosity", verbosity)
644 	else O_DEC(opt, "statistics-interval", stat_interval)
645 	else O_YNO(opt, "statistics-cumulative", stat_cumulative)
646 	else O_YNO(opt, "extended-statistics", stat_extended)
647 	else O_YNO(opt, "use-syslog", use_syslog)
648 	else O_YNO(opt, "log-time-ascii", log_time_ascii)
649 	else O_DEC(opt, "num-threads", num_threads)
650 	else O_IFC(opt, "interface", num_ifs, ifs)
651 	else O_IFC(opt, "outgoing-interface", num_out_ifs, out_ifs)
652 	else O_YNO(opt, "interface-automatic", if_automatic)
653 	else O_DEC(opt, "port", port)
654 	else O_DEC(opt, "outgoing-range", outgoing_num_ports)
655 	else O_DEC(opt, "outgoing-num-tcp", outgoing_num_tcp)
656 	else O_DEC(opt, "incoming-num-tcp", incoming_num_tcp)
657 	else O_DEC(opt, "edns-buffer-size", edns_buffer_size)
658 	else O_DEC(opt, "msg-buffer-size", msg_buffer_size)
659 	else O_MEM(opt, "msg-cache-size", msg_cache_size)
660 	else O_DEC(opt, "msg-cache-slabs", msg_cache_slabs)
661 	else O_DEC(opt, "num-queries-per-thread", num_queries_per_thread)
662 	else O_UNS(opt, "jostle-timeout", jostle_time)
663 	else O_MEM(opt, "so-rcvbuf", so_rcvbuf)
664 	else O_MEM(opt, "so-sndbuf", so_sndbuf)
665 	else O_YNO(opt, "so-reuseport", so_reuseport)
666 	else O_YNO(opt, "ip-transparent", ip_transparent)
667 	else O_MEM(opt, "rrset-cache-size", rrset_cache_size)
668 	else O_DEC(opt, "rrset-cache-slabs", rrset_cache_slabs)
669 	else O_YNO(opt, "prefetch-key", prefetch_key)
670 	else O_YNO(opt, "prefetch", prefetch)
671 	else O_DEC(opt, "cache-max-ttl", max_ttl)
672 	else O_DEC(opt, "cache-max-negative-ttl", max_negative_ttl)
673 	else O_DEC(opt, "cache-min-ttl", min_ttl)
674 	else O_DEC(opt, "infra-host-ttl", host_ttl)
675 	else O_DEC(opt, "infra-cache-slabs", infra_cache_slabs)
676 	else O_DEC(opt, "infra-cache-min-rtt", infra_cache_min_rtt)
677 	else O_MEM(opt, "infra-cache-numhosts", infra_cache_numhosts)
678 	else O_UNS(opt, "delay-close", delay_close)
679 	else O_YNO(opt, "do-ip4", do_ip4)
680 	else O_YNO(opt, "do-ip6", do_ip6)
681 	else O_YNO(opt, "do-udp", do_udp)
682 	else O_YNO(opt, "do-tcp", do_tcp)
683 	else O_YNO(opt, "tcp-upstream", tcp_upstream)
684 	else O_DEC(opt, "tcp-mss", tcp_mss)
685 	else O_DEC(opt, "outgoing-tcp-mss", outgoing_tcp_mss)
686 	else O_YNO(opt, "ssl-upstream", ssl_upstream)
687 	else O_STR(opt, "ssl-service-key", ssl_service_key)
688 	else O_STR(opt, "ssl-service-pem", ssl_service_pem)
689 	else O_DEC(opt, "ssl-port", ssl_port)
690 	else O_YNO(opt, "do-daemonize", do_daemonize)
691 	else O_STR(opt, "chroot", chrootdir)
692 	else O_STR(opt, "username", username)
693 	else O_STR(opt, "directory", directory)
694 	else O_STR(opt, "logfile", logfile)
695 	else O_YNO(opt, "log-queries", log_queries)
696 	else O_STR(opt, "pidfile", pidfile)
697 	else O_YNO(opt, "hide-identity", hide_identity)
698 	else O_YNO(opt, "hide-version", hide_version)
699 	else O_STR(opt, "identity", identity)
700 	else O_STR(opt, "version", version)
701 	else O_STR(opt, "target-fetch-policy", target_fetch_policy)
702 	else O_YNO(opt, "harden-short-bufsize", harden_short_bufsize)
703 	else O_YNO(opt, "harden-large-queries", harden_large_queries)
704 	else O_YNO(opt, "harden-glue", harden_glue)
705 	else O_YNO(opt, "harden-dnssec-stripped", harden_dnssec_stripped)
706 	else O_YNO(opt, "harden-below-nxdomain", harden_below_nxdomain)
707 	else O_YNO(opt, "harden-referral-path", harden_referral_path)
708 	else O_YNO(opt, "harden-algo-downgrade", harden_algo_downgrade)
709 	else O_YNO(opt, "use-caps-for-id", use_caps_bits_for_id)
710 	else O_LST(opt, "caps-whitelist", caps_whitelist)
711 	else O_DEC(opt, "unwanted-reply-threshold", unwanted_threshold)
712 	else O_YNO(opt, "do-not-query-localhost", donotquery_localhost)
713 	else O_STR(opt, "module-config", module_conf)
714 	else O_STR(opt, "dlv-anchor-file", dlv_anchor_file)
715 	else O_DEC(opt, "val-bogus-ttl", bogus_ttl)
716 	else O_YNO(opt, "val-clean-additional", val_clean_additional)
717 	else O_DEC(opt, "val-log-level", val_log_level)
718 	else O_YNO(opt, "val-permissive-mode", val_permissive_mode)
719 	else O_YNO(opt, "ignore-cd-flag", ignore_cd)
720 	else O_STR(opt, "val-nsec3-keysize-iterations",val_nsec3_key_iterations)
721 	else O_UNS(opt, "add-holddown", add_holddown)
722 	else O_UNS(opt, "del-holddown", del_holddown)
723 	else O_UNS(opt, "keep-missing", keep_missing)
724 	else O_YNO(opt, "permit-small-holddown", permit_small_holddown)
725 	else O_MEM(opt, "key-cache-size", key_cache_size)
726 	else O_DEC(opt, "key-cache-slabs", key_cache_slabs)
727 	else O_MEM(opt, "neg-cache-size", neg_cache_size)
728 	else O_YNO(opt, "control-enable", remote_control_enable)
729 	else O_DEC(opt, "control-port", control_port)
730 	else O_STR(opt, "server-key-file", server_key_file)
731 	else O_STR(opt, "server-cert-file", server_cert_file)
732 	else O_STR(opt, "control-key-file", control_key_file)
733 	else O_STR(opt, "control-cert-file", control_cert_file)
734 	else O_LST(opt, "root-hints", root_hints)
735 	else O_LS2(opt, "access-control", acls)
736 	else O_LST(opt, "do-not-query-address", donotqueryaddrs)
737 	else O_LST(opt, "private-address", private_address)
738 	else O_LST(opt, "private-domain", private_domain)
739 	else O_LST(opt, "auto-trust-anchor-file", auto_trust_anchor_file_list)
740 	else O_LST(opt, "trust-anchor-file", trust_anchor_file_list)
741 	else O_LST(opt, "trust-anchor", trust_anchor_list)
742 	else O_LST(opt, "trusted-keys-file", trusted_keys_file_list)
743 	else O_LST(opt, "dlv-anchor", dlv_anchor_list)
744 	else O_LST(opt, "control-interface", control_ifs)
745 	else O_LST(opt, "domain-insecure", domain_insecure)
746 	else O_UNS(opt, "val-override-date", val_date_override)
747 	else O_YNO(opt, "minimal-responses", minimal_responses)
748 	else O_YNO(opt, "rrset-roundrobin", rrset_roundrobin)
749 	else O_YNO(opt, "unblock-lan-zones", unblock_lan_zones)
750 	else O_YNO(opt, "insecure-lan-zones", insecure_lan_zones)
751 	else O_DEC(opt, "max-udp-size", max_udp_size)
752 	else O_STR(opt, "python-script", python_script)
753 	else O_DEC(opt, "ratelimit", ratelimit)
754 	else O_MEM(opt, "ratelimit-size", ratelimit_size)
755 	else O_DEC(opt, "ratelimit-slabs", ratelimit_slabs)
756 	else O_LS2(opt, "ratelimit-for-domain", ratelimit_for_domain)
757 	else O_LS2(opt, "ratelimit-below-domain", ratelimit_below_domain)
758 	else O_DEC(opt, "ratelimit-factor", ratelimit_factor)
759 	else O_DEC(opt, "val-sig-skew-min", val_sig_skew_min)
760 	else O_DEC(opt, "val-sig-skew-max", val_sig_skew_max)
761 	else O_YNO(opt, "qname-minimisation", qname_minimisation)
762 	/* not here:
763 	 * outgoing-permit, outgoing-avoid - have list of ports
764 	 * local-zone - zones and nodefault variables
765 	 * local-data - see below
766 	 * local-data-ptr - converted to local-data entries
767 	 * stub-zone, name, stub-addr, stub-host, stub-prime
768 	 * forward-zone, name, forward-addr, forward-host
769 	 */
770 	else return 0;
771 	return 1;
772 }
773 
774 /** initialize the global cfg_parser object */
775 static void
776 create_cfg_parser(struct config_file* cfg, char* filename, const char* chroot)
777 {
778 	static struct config_parser_state st;
779 	cfg_parser = &st;
780 	cfg_parser->filename = filename;
781 	cfg_parser->line = 1;
782 	cfg_parser->errors = 0;
783 	cfg_parser->cfg = cfg;
784 	cfg_parser->chroot = chroot;
785 	init_cfg_parse();
786 }
787 
788 int
789 config_read(struct config_file* cfg, const char* filename, const char* chroot)
790 {
791 	FILE *in;
792 	char *fname = (char*)filename;
793 #ifdef HAVE_GLOB
794 	glob_t g;
795 	size_t i;
796 	int r, flags;
797 #endif
798 	if(!fname)
799 		return 1;
800 
801 	/* check for wildcards */
802 #ifdef HAVE_GLOB
803 	if(!(!strchr(fname, '*') && !strchr(fname, '?') && !strchr(fname, '[') &&
804 		!strchr(fname, '{') && !strchr(fname, '~'))) {
805 		verbose(VERB_QUERY, "wildcard found, processing %s", fname);
806 		flags = 0
807 #ifdef GLOB_ERR
808 			| GLOB_ERR
809 #endif
810 #ifdef GLOB_NOSORT
811 			| GLOB_NOSORT
812 #endif
813 #ifdef GLOB_BRACE
814 			| GLOB_BRACE
815 #endif
816 #ifdef GLOB_TILDE
817 			| GLOB_TILDE
818 #endif
819 		;
820 		memset(&g, 0, sizeof(g));
821 		r = glob(fname, flags, NULL, &g);
822 		if(r) {
823 			/* some error */
824 			globfree(&g);
825 			if(r == GLOB_NOMATCH) {
826 				verbose(VERB_QUERY, "include: "
827 				"no matches for %s", fname);
828 				return 1;
829 			} else if(r == GLOB_NOSPACE) {
830 				log_err("include: %s: "
831 					"fnametern out of memory", fname);
832 			} else if(r == GLOB_ABORTED) {
833 				log_err("wildcard include: %s: expansion "
834 					"aborted (%s)", fname, strerror(errno));
835 			} else {
836 				log_err("wildcard include: %s: expansion "
837 					"failed (%s)", fname, strerror(errno));
838 			}
839 			/* ignore globs that yield no files */
840 			return 1;
841 		}
842 		/* process files found, if any */
843 		for(i=0; i<(size_t)g.gl_pathc; i++) {
844 			if(!config_read(cfg, g.gl_pathv[i], chroot)) {
845 				log_err("error reading wildcard "
846 					"include: %s", g.gl_pathv[i]);
847 				globfree(&g);
848 				return 0;
849 			}
850 		}
851 		globfree(&g);
852 		return 1;
853 	}
854 #endif /* HAVE_GLOB */
855 
856 	in = fopen(fname, "r");
857 	if(!in) {
858 		log_err("Could not open %s: %s", fname, strerror(errno));
859 		return 0;
860 	}
861 	create_cfg_parser(cfg, fname, chroot);
862 	ub_c_in = in;
863 	ub_c_parse();
864 	fclose(in);
865 
866 	if(cfg_parser->errors != 0) {
867 		fprintf(stderr, "read %s failed: %d errors in configuration file\n",
868 			fname, cfg_parser->errors);
869 		errno=EINVAL;
870 		return 0;
871 	}
872 
873 	return 1;
874 }
875 
876 struct config_stub* cfg_stub_find(struct config_stub*** pp, const char* nm)
877 {
878 	struct config_stub* p = *(*pp);
879 	while(p) {
880 		if(strcmp(p->name, nm) == 0)
881 			return p;
882 		(*pp) = &p->next;
883 		p = p->next;
884 	}
885 	return NULL;
886 }
887 
888 void
889 config_delstrlist(struct config_strlist* p)
890 {
891 	struct config_strlist *np;
892 	while(p) {
893 		np = p->next;
894 		free(p->str);
895 		free(p);
896 		p = np;
897 	}
898 }
899 
900 void
901 config_deldblstrlist(struct config_str2list* p)
902 {
903 	struct config_str2list *np;
904 	while(p) {
905 		np = p->next;
906 		free(p->str);
907 		free(p->str2);
908 		free(p);
909 		p = np;
910 	}
911 }
912 
913 void
914 config_delstub(struct config_stub* p)
915 {
916 	if(!p) return;
917 	free(p->name);
918 	config_delstrlist(p->hosts);
919 	config_delstrlist(p->addrs);
920 	free(p);
921 }
922 
923 void
924 config_delstubs(struct config_stub* p)
925 {
926 	struct config_stub* np;
927 	while(p) {
928 		np = p->next;
929 		config_delstub(p);
930 		p = np;
931 	}
932 }
933 
934 void
935 config_delete(struct config_file* cfg)
936 {
937 	if(!cfg) return;
938 	free(cfg->username);
939 	free(cfg->chrootdir);
940 	free(cfg->directory);
941 	free(cfg->logfile);
942 	free(cfg->pidfile);
943 	free(cfg->target_fetch_policy);
944 	free(cfg->ssl_service_key);
945 	free(cfg->ssl_service_pem);
946 	if(cfg->ifs) {
947 		int i;
948 		for(i=0; i<cfg->num_ifs; i++)
949 			free(cfg->ifs[i]);
950 		free(cfg->ifs);
951 	}
952 	if(cfg->out_ifs) {
953 		int i;
954 		for(i=0; i<cfg->num_out_ifs; i++)
955 			free(cfg->out_ifs[i]);
956 		free(cfg->out_ifs);
957 	}
958 	config_delstubs(cfg->stubs);
959 	config_delstubs(cfg->forwards);
960 	config_delstrlist(cfg->donotqueryaddrs);
961 	config_delstrlist(cfg->root_hints);
962 	free(cfg->identity);
963 	free(cfg->version);
964 	free(cfg->module_conf);
965 	free(cfg->outgoing_avail_ports);
966 	config_delstrlist(cfg->caps_whitelist);
967 	config_delstrlist(cfg->private_address);
968 	config_delstrlist(cfg->private_domain);
969 	config_delstrlist(cfg->auto_trust_anchor_file_list);
970 	config_delstrlist(cfg->trust_anchor_file_list);
971 	config_delstrlist(cfg->trusted_keys_file_list);
972 	config_delstrlist(cfg->trust_anchor_list);
973 	config_delstrlist(cfg->domain_insecure);
974 	free(cfg->dlv_anchor_file);
975 	config_delstrlist(cfg->dlv_anchor_list);
976 	config_deldblstrlist(cfg->acls);
977 	free(cfg->val_nsec3_key_iterations);
978 	config_deldblstrlist(cfg->local_zones);
979 	config_delstrlist(cfg->local_zones_nodefault);
980 	config_delstrlist(cfg->local_data);
981 	config_delstrlist(cfg->control_ifs);
982 	free(cfg->server_key_file);
983 	free(cfg->server_cert_file);
984 	free(cfg->control_key_file);
985 	free(cfg->control_cert_file);
986 	free(cfg->dns64_prefix);
987 	free(cfg->dnstap_socket_path);
988 	free(cfg->dnstap_identity);
989 	free(cfg->dnstap_version);
990 	config_deldblstrlist(cfg->ratelimit_for_domain);
991 	config_deldblstrlist(cfg->ratelimit_below_domain);
992 	free(cfg);
993 }
994 
995 static void
996 init_outgoing_availports(int* a, int num)
997 {
998 	/* generated with make iana_update */
999 	const int iana_assigned[] = {
1000 #include "util/iana_ports.inc"
1001 		-1 }; /* end marker to put behind trailing comma */
1002 
1003 	int i;
1004 	/* do not use <1024, that could be trouble with the system, privs */
1005 	for(i=1024; i<num; i++) {
1006 		a[i] = i;
1007 	}
1008 	/* create empty spot at 49152 to keep ephemeral ports available
1009 	 * to other programs */
1010 	for(i=49152; i<49152+256; i++)
1011 		a[i] = 0;
1012 	/* pick out all the IANA assigned ports */
1013 	for(i=0; iana_assigned[i]!=-1; i++) {
1014 		if(iana_assigned[i] < num)
1015 			a[iana_assigned[i]] = 0;
1016 	}
1017 }
1018 
1019 int
1020 cfg_mark_ports(const char* str, int allow, int* avail, int num)
1021 {
1022 	char* mid = strchr(str, '-');
1023 	if(!mid) {
1024 		int port = atoi(str);
1025 		if(port == 0 && strcmp(str, "0") != 0) {
1026 			log_err("cannot parse port number '%s'", str);
1027 			return 0;
1028 		}
1029 		if(port < num)
1030 			avail[port] = (allow?port:0);
1031 	} else {
1032 		int i, low, high = atoi(mid+1);
1033 		char buf[16];
1034 		if(high == 0 && strcmp(mid+1, "0") != 0) {
1035 			log_err("cannot parse port number '%s'", mid+1);
1036 			return 0;
1037 		}
1038 		if( (int)(mid-str)+1 >= (int)sizeof(buf) ) {
1039 			log_err("cannot parse port number '%s'", str);
1040 			return 0;
1041 		}
1042 		if(mid > str)
1043 			memcpy(buf, str, (size_t)(mid-str));
1044 		buf[mid-str] = 0;
1045 		low = atoi(buf);
1046 		if(low == 0 && strcmp(buf, "0") != 0) {
1047 			log_err("cannot parse port number '%s'", buf);
1048 			return 0;
1049 		}
1050 		for(i=low; i<=high; i++) {
1051 			if(i < num)
1052 				avail[i] = (allow?i:0);
1053 		}
1054 		return 1;
1055 	}
1056 	return 1;
1057 }
1058 
1059 int
1060 cfg_scan_ports(int* avail, int num)
1061 {
1062 	int i;
1063 	int count = 0;
1064 	for(i=0; i<num; i++) {
1065 		if(avail[i])
1066 			count++;
1067 	}
1068 	return count;
1069 }
1070 
1071 int cfg_condense_ports(struct config_file* cfg, int** avail)
1072 {
1073 	int num = cfg_scan_ports(cfg->outgoing_avail_ports, 65536);
1074 	int i, at = 0;
1075 	*avail = NULL;
1076 	if(num == 0)
1077 		return 0;
1078 	*avail = (int*)reallocarray(NULL, (size_t)num, sizeof(int));
1079 	if(!*avail)
1080 		return 0;
1081 	for(i=0; i<65536; i++) {
1082 		if(cfg->outgoing_avail_ports[i])
1083 			(*avail)[at++] = cfg->outgoing_avail_ports[i];
1084 	}
1085 	log_assert(at == num);
1086 	return num;
1087 }
1088 
1089 /** print error with file and line number */
1090 static void ub_c_error_va_list(const char *fmt, va_list args)
1091 {
1092 	cfg_parser->errors++;
1093 	fprintf(stderr, "%s:%d: error: ", cfg_parser->filename,
1094 	cfg_parser->line);
1095 	vfprintf(stderr, fmt, args);
1096 	fprintf(stderr, "\n");
1097 }
1098 
1099 /** print error with file and line number */
1100 void ub_c_error_msg(const char* fmt, ...)
1101 {
1102 	va_list args;
1103 	va_start(args, fmt);
1104 	ub_c_error_va_list(fmt, args);
1105 	va_end(args);
1106 }
1107 
1108 void ub_c_error(const char *str)
1109 {
1110 	cfg_parser->errors++;
1111 	fprintf(stderr, "%s:%d: error: %s\n", cfg_parser->filename,
1112 		cfg_parser->line, str);
1113 }
1114 
1115 int ub_c_wrap(void)
1116 {
1117 	return 1;
1118 }
1119 
1120 int cfg_strlist_append(struct config_strlist_head* list, char* item)
1121 {
1122 	struct config_strlist *s;
1123 	if(!item || !list)
1124 		return 0;
1125 	s = (struct config_strlist*)calloc(1, sizeof(struct config_strlist));
1126 	if(!s)
1127 		return 0;
1128 	s->str = item;
1129 	s->next = NULL;
1130 	if(list->last)
1131 		list->last->next = s;
1132 	else
1133 		list->first = s;
1134 	list->last = s;
1135 	return 1;
1136 }
1137 
1138 int
1139 cfg_strlist_insert(struct config_strlist** head, char* item)
1140 {
1141 	struct config_strlist *s;
1142 	if(!item || !head)
1143 		return 0;
1144 	s = (struct config_strlist*)calloc(1, sizeof(struct config_strlist));
1145 	if(!s)
1146 		return 0;
1147 	s->str = item;
1148 	s->next = *head;
1149 	*head = s;
1150 	return 1;
1151 }
1152 
1153 int
1154 cfg_str2list_insert(struct config_str2list** head, char* item, char* i2)
1155 {
1156 	struct config_str2list *s;
1157 	if(!item || !i2 || !head)
1158 		return 0;
1159 	s = (struct config_str2list*)calloc(1, sizeof(struct config_str2list));
1160 	if(!s)
1161 		return 0;
1162 	s->str = item;
1163 	s->str2 = i2;
1164 	s->next = *head;
1165 	*head = s;
1166 	return 1;
1167 }
1168 
1169 time_t
1170 cfg_convert_timeval(const char* str)
1171 {
1172 	time_t t;
1173 	struct tm tm;
1174 	memset(&tm, 0, sizeof(tm));
1175 	if(strlen(str) < 14)
1176 		return 0;
1177 	if(sscanf(str, "%4d%2d%2d%2d%2d%2d", &tm.tm_year, &tm.tm_mon,
1178 		&tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6)
1179 		return 0;
1180 	tm.tm_year -= 1900;
1181 	tm.tm_mon--;
1182 	/* Check values */
1183 	if (tm.tm_year < 70)	return 0;
1184 	if (tm.tm_mon < 0 || tm.tm_mon > 11)	return 0;
1185 	if (tm.tm_mday < 1 || tm.tm_mday > 31) 	return 0;
1186 	if (tm.tm_hour < 0 || tm.tm_hour > 23)	return 0;
1187 	if (tm.tm_min < 0 || tm.tm_min > 59)	return 0;
1188 	if (tm.tm_sec < 0 || tm.tm_sec > 59)	return 0;
1189 	/* call ldns conversion function */
1190 	t = sldns_mktime_from_utc(&tm);
1191 	return t;
1192 }
1193 
1194 int
1195 cfg_count_numbers(const char* s)
1196 {
1197 	/* format ::= (sp num)+ sp  */
1198 	/* num ::= [-](0-9)+        */
1199 	/* sp ::= (space|tab)*      */
1200 	int num = 0;
1201 	while(*s) {
1202 		while(*s && isspace((unsigned char)*s))
1203 			s++;
1204 		if(!*s) /* end of string */
1205 			break;
1206 		if(*s == '-')
1207 			s++;
1208 		if(!*s) /* only - not allowed */
1209 			return 0;
1210 		if(!isdigit((unsigned char)*s)) /* bad character */
1211 			return 0;
1212 		while(*s && isdigit((unsigned char)*s))
1213 			s++;
1214 		num++;
1215 	}
1216 	return num;
1217 }
1218 
1219 /** all digit number */
1220 static int isalldigit(const char* str, size_t l)
1221 {
1222 	size_t i;
1223 	for(i=0; i<l; i++)
1224 		if(!isdigit((unsigned char)str[i]))
1225 			return 0;
1226 	return 1;
1227 }
1228 
1229 int
1230 cfg_parse_memsize(const char* str, size_t* res)
1231 {
1232 	size_t len;
1233 	size_t mult = 1;
1234 	if(!str || (len=(size_t)strlen(str)) == 0) {
1235 		log_err("not a size: '%s'", str);
1236 		return 0;
1237 	}
1238 	if(isalldigit(str, len)) {
1239 		*res = (size_t)atol(str);
1240 		return 1;
1241 	}
1242 	/* check appended num */
1243 	while(len>0 && str[len-1]==' ')
1244 		len--;
1245 	if(len > 1 && str[len-1] == 'b')
1246 		len--;
1247 	else if(len > 1 && str[len-1] == 'B')
1248 		len--;
1249 
1250 	if(len > 1 && tolower((unsigned char)str[len-1]) == 'g')
1251 		mult = 1024*1024*1024;
1252 	else if(len > 1 && tolower((unsigned char)str[len-1]) == 'm')
1253 		mult = 1024*1024;
1254 	else if(len > 1 && tolower((unsigned char)str[len-1]) == 'k')
1255 		mult = 1024;
1256 	else if(len > 0 && isdigit((unsigned char)str[len-1]))
1257 		mult = 1;
1258 	else {
1259 		log_err("unknown size specifier: '%s'", str);
1260 		return 0;
1261 	}
1262 	while(len>1 && str[len-2]==' ')
1263 		len--;
1264 
1265 	if(!isalldigit(str, len-1)) {
1266 		log_err("unknown size specifier: '%s'", str);
1267 		return 0;
1268 	}
1269 	*res = ((size_t)atol(str)) * mult;
1270 	return 1;
1271 }
1272 
1273 void
1274 config_apply(struct config_file* config)
1275 {
1276 	MAX_TTL = (time_t)config->max_ttl;
1277 	MIN_TTL = (time_t)config->min_ttl;
1278 	MAX_NEG_TTL = (time_t)config->max_negative_ttl;
1279 	RTT_MIN_TIMEOUT = config->infra_cache_min_rtt;
1280 	EDNS_ADVERTISED_SIZE = (uint16_t)config->edns_buffer_size;
1281 	MINIMAL_RESPONSES = config->minimal_responses;
1282 	RRSET_ROUNDROBIN = config->rrset_roundrobin;
1283 	log_set_time_asc(config->log_time_ascii);
1284 	autr_permit_small_holddown = config->permit_small_holddown;
1285 }
1286 
1287 void config_lookup_uid(struct config_file* cfg)
1288 {
1289 #ifdef HAVE_GETPWNAM
1290 	/* translate username into uid and gid */
1291 	if(cfg->username && cfg->username[0]) {
1292 		struct passwd *pwd;
1293 		if((pwd = getpwnam(cfg->username)) != NULL) {
1294 			cfg_uid = pwd->pw_uid;
1295 			cfg_gid = pwd->pw_gid;
1296 		}
1297 	}
1298 #else
1299 	(void)cfg;
1300 #endif
1301 }
1302 
1303 /**
1304  * Calculate string length of full pathname in original filesys
1305  * @param fname: the path name to convert.
1306  * 	Must not be null or empty.
1307  * @param cfg: config struct for chroot and chdir (if set).
1308  * @param use_chdir: if false, only chroot is applied.
1309  * @return length of string.
1310  *	remember to allocate one more for 0 at end in mallocs.
1311  */
1312 static size_t
1313 strlen_after_chroot(const char* fname, struct config_file* cfg, int use_chdir)
1314 {
1315 	size_t len = 0;
1316 	int slashit = 0;
1317 	if(cfg->chrootdir && cfg->chrootdir[0] &&
1318 		strncmp(cfg->chrootdir, fname, strlen(cfg->chrootdir)) == 0) {
1319 		/* already full pathname, return it */
1320 		return strlen(fname);
1321 	}
1322 	/* chroot */
1323 	if(cfg->chrootdir && cfg->chrootdir[0]) {
1324 		/* start with chrootdir */
1325 		len += strlen(cfg->chrootdir);
1326 		slashit = 1;
1327 	}
1328 	/* chdir */
1329 #ifdef UB_ON_WINDOWS
1330 	if(fname[0] != 0 && fname[1] == ':') {
1331 		/* full path, no chdir */
1332 	} else
1333 #endif
1334 	if(fname[0] == '/' || !use_chdir) {
1335 		/* full path, no chdir */
1336 	} else if(cfg->directory && cfg->directory[0]) {
1337 		/* prepend chdir */
1338 		if(slashit && cfg->directory[0] != '/')
1339 			len++;
1340 		if(cfg->chrootdir && cfg->chrootdir[0] &&
1341 			strncmp(cfg->chrootdir, cfg->directory,
1342 			strlen(cfg->chrootdir)) == 0)
1343 			len += strlen(cfg->directory)-strlen(cfg->chrootdir);
1344 		else	len += strlen(cfg->directory);
1345 		slashit = 1;
1346 	}
1347 	/* fname */
1348 	if(slashit && fname[0] != '/')
1349 		len++;
1350 	len += strlen(fname);
1351 	return len;
1352 }
1353 
1354 char*
1355 fname_after_chroot(const char* fname, struct config_file* cfg, int use_chdir)
1356 {
1357 	size_t len = strlen_after_chroot(fname, cfg, use_chdir)+1;
1358 	int slashit = 0;
1359 	char* buf = (char*)malloc(len);
1360 	if(!buf)
1361 		return NULL;
1362 	buf[0] = 0;
1363 	/* is fname already in chroot ? */
1364 	if(cfg->chrootdir && cfg->chrootdir[0] &&
1365 		strncmp(cfg->chrootdir, fname, strlen(cfg->chrootdir)) == 0) {
1366 		/* already full pathname, return it */
1367 		(void)strlcpy(buf, fname, len);
1368 		buf[len-1] = 0;
1369 		return buf;
1370 	}
1371 	/* chroot */
1372 	if(cfg->chrootdir && cfg->chrootdir[0]) {
1373 		/* start with chrootdir */
1374 		(void)strlcpy(buf, cfg->chrootdir, len);
1375 		slashit = 1;
1376 	}
1377 #ifdef UB_ON_WINDOWS
1378 	if(fname[0] != 0 && fname[1] == ':') {
1379 		/* full path, no chdir */
1380 	} else
1381 #endif
1382 	/* chdir */
1383 	if(fname[0] == '/' || !use_chdir) {
1384 		/* full path, no chdir */
1385 	} else if(cfg->directory && cfg->directory[0]) {
1386 		/* prepend chdir */
1387 		if(slashit && cfg->directory[0] != '/')
1388 			(void)strlcat(buf, "/", len);
1389 		/* is the directory already in the chroot? */
1390 		if(cfg->chrootdir && cfg->chrootdir[0] &&
1391 			strncmp(cfg->chrootdir, cfg->directory,
1392 			strlen(cfg->chrootdir)) == 0)
1393 			(void)strlcat(buf, cfg->directory+strlen(cfg->chrootdir),
1394 				   len);
1395 		else (void)strlcat(buf, cfg->directory, len);
1396 		slashit = 1;
1397 	}
1398 	/* fname */
1399 	if(slashit && fname[0] != '/')
1400 		(void)strlcat(buf, "/", len);
1401 	(void)strlcat(buf, fname, len);
1402 	buf[len-1] = 0;
1403 	return buf;
1404 }
1405 
1406 /** return next space character in string */
1407 static char* next_space_pos(const char* str)
1408 {
1409 	char* sp = strchr(str, ' ');
1410 	char* tab = strchr(str, '\t');
1411 	if(!tab && !sp)
1412 		return NULL;
1413 	if(!sp) return tab;
1414 	if(!tab) return sp;
1415 	return (sp<tab)?sp:tab;
1416 }
1417 
1418 /** return last space character in string */
1419 static char* last_space_pos(const char* str)
1420 {
1421 	char* sp = strrchr(str, ' ');
1422 	char* tab = strrchr(str, '\t');
1423 	if(!tab && !sp)
1424 		return NULL;
1425 	if(!sp) return tab;
1426 	if(!tab) return sp;
1427 	return (sp>tab)?sp:tab;
1428 }
1429 
1430 int
1431 cfg_parse_local_zone(struct config_file* cfg, const char* val)
1432 {
1433 	const char *type, *name_end, *name;
1434 	char buf[256];
1435 
1436 	/* parse it as: [zone_name] [between stuff] [zone_type] */
1437 	name = val;
1438 	while(*name && isspace((unsigned char)*name))
1439 		name++;
1440 	if(!*name) {
1441 		log_err("syntax error: too short: %s", val);
1442 		return 0;
1443 	}
1444 	name_end = next_space_pos(name);
1445 	if(!name_end || !*name_end) {
1446 		log_err("syntax error: expected zone type: %s", val);
1447 		return 0;
1448 	}
1449 	if (name_end - name > 255) {
1450 		log_err("syntax error: bad zone name: %s", val);
1451 		return 0;
1452 	}
1453 	(void)strlcpy(buf, name, sizeof(buf));
1454 	buf[name_end-name] = '\0';
1455 
1456 	type = last_space_pos(name_end);
1457 	while(type && *type && isspace((unsigned char)*type))
1458 		type++;
1459 	if(!type || !*type) {
1460 		log_err("syntax error: expected zone type: %s", val);
1461 		return 0;
1462 	}
1463 
1464 	if(strcmp(type, "nodefault")==0) {
1465 		return cfg_strlist_insert(&cfg->local_zones_nodefault,
1466 			strdup(name));
1467 	} else {
1468 		return cfg_str2list_insert(&cfg->local_zones, strdup(buf),
1469 			strdup(type));
1470 	}
1471 }
1472 
1473 char* cfg_ptr_reverse(char* str)
1474 {
1475 	char* ip, *ip_end;
1476 	char* name;
1477 	char* result;
1478 	char buf[1024];
1479 	struct sockaddr_storage addr;
1480 	socklen_t addrlen;
1481 
1482 	/* parse it as: [IP] [between stuff] [name] */
1483 	ip = str;
1484 	while(*ip && isspace((unsigned char)*ip))
1485 		ip++;
1486 	if(!*ip) {
1487 		log_err("syntax error: too short: %s", str);
1488 		return NULL;
1489 	}
1490 	ip_end = next_space_pos(ip);
1491 	if(!ip_end || !*ip_end) {
1492 		log_err("syntax error: expected name: %s", str);
1493 		return NULL;
1494 	}
1495 
1496 	name = last_space_pos(ip_end);
1497 	if(!name || !*name) {
1498 		log_err("syntax error: expected name: %s", str);
1499 		return NULL;
1500 	}
1501 
1502 	sscanf(ip, "%100s", buf);
1503 	buf[sizeof(buf)-1]=0;
1504 
1505 	if(!ipstrtoaddr(buf, UNBOUND_DNS_PORT, &addr, &addrlen)) {
1506 		log_err("syntax error: cannot parse address: %s", str);
1507 		return NULL;
1508 	}
1509 
1510 	/* reverse IPv4:
1511 	 * ddd.ddd.ddd.ddd.in-addr-arpa.
1512 	 * IPv6: (h.){32}.ip6.arpa.  */
1513 
1514 	if(addr_is_ip6(&addr, addrlen)) {
1515 		uint8_t ad[16];
1516 		const char* hex = "0123456789abcdef";
1517 		char *p = buf;
1518 		int i;
1519 		memmove(ad, &((struct sockaddr_in6*)&addr)->sin6_addr,
1520 			sizeof(ad));
1521 		for(i=15; i>=0; i--) {
1522 			uint8_t b = ad[i];
1523 			*p++ = hex[ (b&0x0f) ];
1524 			*p++ = '.';
1525 			*p++ = hex[ (b&0xf0) >> 4 ];
1526 			*p++ = '.';
1527 		}
1528 		snprintf(buf+16*4, sizeof(buf)-16*4, "ip6.arpa. ");
1529 	} else {
1530 		uint8_t ad[4];
1531 		memmove(ad, &((struct sockaddr_in*)&addr)->sin_addr,
1532 			sizeof(ad));
1533 		snprintf(buf, sizeof(buf), "%u.%u.%u.%u.in-addr.arpa. ",
1534 			(unsigned)ad[3], (unsigned)ad[2],
1535 			(unsigned)ad[1], (unsigned)ad[0]);
1536 	}
1537 
1538 	/* printed the reverse address, now the between goop and name on end */
1539 	while(*ip_end && isspace((unsigned char)*ip_end))
1540 		ip_end++;
1541 	if(name>ip_end) {
1542 		snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%.*s",
1543 			(int)(name-ip_end), ip_end);
1544 	}
1545 	snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), " PTR %s", name);
1546 
1547 	result = strdup(buf);
1548 	if(!result) {
1549 		log_err("out of memory parsing %s", str);
1550 		return NULL;
1551 	}
1552 	return result;
1553 }
1554 
1555 #ifdef UB_ON_WINDOWS
1556 char*
1557 w_lookup_reg_str(const char* key, const char* name)
1558 {
1559 	HKEY hk = NULL;
1560 	DWORD type = 0;
1561 	BYTE buf[1024];
1562 	DWORD len = (DWORD)sizeof(buf);
1563 	LONG ret;
1564 	char* result = NULL;
1565 	ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hk);
1566 	if(ret == ERROR_FILE_NOT_FOUND)
1567 		return NULL; /* key does not exist */
1568 	else if(ret != ERROR_SUCCESS) {
1569 		log_err("RegOpenKeyEx failed");
1570 		return NULL;
1571 	}
1572 	ret = RegQueryValueEx(hk, (LPCTSTR)name, 0, &type, buf, &len);
1573 	if(RegCloseKey(hk))
1574 		log_err("RegCloseKey");
1575 	if(ret == ERROR_FILE_NOT_FOUND)
1576 		return NULL; /* name does not exist */
1577 	else if(ret != ERROR_SUCCESS) {
1578 		log_err("RegQueryValueEx failed");
1579 		return NULL;
1580 	}
1581 	if(type == REG_SZ || type == REG_MULTI_SZ || type == REG_EXPAND_SZ) {
1582 		buf[sizeof(buf)-1] = 0;
1583 		buf[sizeof(buf)-2] = 0; /* for multi_sz */
1584 		result = strdup((char*)buf);
1585 		if(!result) log_err("out of memory");
1586 	}
1587 	return result;
1588 }
1589 
1590 void w_config_adjust_directory(struct config_file* cfg)
1591 {
1592 	if(cfg->directory && cfg->directory[0]) {
1593 		TCHAR dirbuf[2*MAX_PATH+4];
1594 		if(strcmp(cfg->directory, "%EXECUTABLE%") == 0) {
1595 			/* get executable path, and if that contains
1596 			 * directories, snip off the filename part */
1597 			dirbuf[0] = 0;
1598 			if(!GetModuleFileName(NULL, dirbuf, MAX_PATH))
1599 				log_err("could not GetModuleFileName");
1600 			if(strrchr(dirbuf, '\\')) {
1601 				(strrchr(dirbuf, '\\'))[0] = 0;
1602 			} else log_err("GetModuleFileName had no path");
1603 			if(dirbuf[0]) {
1604 				/* adjust directory for later lookups to work*/
1605 				free(cfg->directory);
1606 				cfg->directory = memdup(dirbuf, strlen(dirbuf)+1);
1607 			}
1608 		}
1609 	}
1610 }
1611 #endif /* UB_ON_WINDOWS */
1612 
1613 void errinf(struct module_qstate* qstate, const char* str)
1614 {
1615 	struct config_strlist* p;
1616 	if(qstate->env->cfg->val_log_level < 2 || !str)
1617 		return;
1618 	p = (struct config_strlist*)regional_alloc(qstate->region, sizeof(*p));
1619 	if(!p) {
1620 		log_err("malloc failure in validator-error-info string");
1621 		return;
1622 	}
1623 	p->next = NULL;
1624 	p->str = regional_strdup(qstate->region, str);
1625 	if(!p->str) {
1626 		log_err("malloc failure in validator-error-info string");
1627 		return;
1628 	}
1629 	/* add at end */
1630 	if(qstate->errinf) {
1631 		struct config_strlist* q = qstate->errinf;
1632 		while(q->next)
1633 			q = q->next;
1634 		q->next = p;
1635 	} else	qstate->errinf = p;
1636 }
1637 
1638 void errinf_origin(struct module_qstate* qstate, struct sock_list *origin)
1639 {
1640 	struct sock_list* p;
1641 	if(qstate->env->cfg->val_log_level < 2)
1642 		return;
1643 	for(p=origin; p; p=p->next) {
1644 		char buf[256];
1645 		if(p == origin)
1646 			snprintf(buf, sizeof(buf), "from ");
1647 		else	snprintf(buf, sizeof(buf), "and ");
1648 		if(p->len == 0)
1649 			snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf),
1650 				"cache");
1651 		else
1652 			addr_to_str(&p->addr, p->len, buf+strlen(buf),
1653 				sizeof(buf)-strlen(buf));
1654 		errinf(qstate, buf);
1655 	}
1656 }
1657 
1658 char* errinf_to_str(struct module_qstate* qstate)
1659 {
1660 	char buf[20480];
1661 	char* p = buf;
1662 	size_t left = sizeof(buf);
1663 	struct config_strlist* s;
1664 	char dname[LDNS_MAX_DOMAINLEN+1];
1665 	char t[16], c[16];
1666 	sldns_wire2str_type_buf(qstate->qinfo.qtype, t, sizeof(t));
1667 	sldns_wire2str_class_buf(qstate->qinfo.qclass, c, sizeof(c));
1668 	dname_str(qstate->qinfo.qname, dname);
1669 	snprintf(p, left, "validation failure <%s %s %s>:", dname, t, c);
1670 	left -= strlen(p); p += strlen(p);
1671 	if(!qstate->errinf)
1672 		snprintf(p, left, " misc failure");
1673 	else for(s=qstate->errinf; s; s=s->next) {
1674 		snprintf(p, left, " %s", s->str);
1675 		left -= strlen(p); p += strlen(p);
1676 	}
1677 	p = strdup(buf);
1678 	if(!p)
1679 		log_err("malloc failure in errinf_to_str");
1680 	return p;
1681 }
1682 
1683 void errinf_rrset(struct module_qstate* qstate, struct ub_packed_rrset_key *rr)
1684 {
1685 	char buf[1024];
1686 	char dname[LDNS_MAX_DOMAINLEN+1];
1687 	char t[16], c[16];
1688 	if(qstate->env->cfg->val_log_level < 2 || !rr)
1689 		return;
1690 	sldns_wire2str_type_buf(ntohs(rr->rk.type), t, sizeof(t));
1691 	sldns_wire2str_class_buf(ntohs(rr->rk.rrset_class), c, sizeof(c));
1692 	dname_str(rr->rk.dname, dname);
1693 	snprintf(buf, sizeof(buf), "for <%s %s %s>", dname, t, c);
1694 	errinf(qstate, buf);
1695 }
1696 
1697 void errinf_dname(struct module_qstate* qstate, const char* str, uint8_t* dname)
1698 {
1699 	char b[1024];
1700 	char buf[LDNS_MAX_DOMAINLEN+1];
1701 	if(qstate->env->cfg->val_log_level < 2 || !str || !dname)
1702 		return;
1703 	dname_str(dname, buf);
1704 	snprintf(b, sizeof(b), "%s %s", str, buf);
1705 	errinf(qstate, b);
1706 }
1707