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