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