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