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