xref: /freebsd/contrib/unbound/util/config_file.c (revision 46d2f61818f594174cafe31ee338c6e083fa1876)
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 #include <errno.h>
46 #ifdef HAVE_TIME_H
47 #include <time.h>
48 #endif
49 #include "util/log.h"
50 #include "util/configyyrename.h"
51 #include "util/config_file.h"
52 #include "configparser.h"
53 #include "util/net_help.h"
54 #include "util/data/msgparse.h"
55 #include "util/module.h"
56 #include "util/regional.h"
57 #include "util/fptr_wlist.h"
58 #include "util/data/dname.h"
59 #include "util/random.h"
60 #include "util/rtt.h"
61 #include "services/cache/infra.h"
62 #include "sldns/wire2str.h"
63 #include "sldns/parseutil.h"
64 #include "iterator/iterator.h"
65 #ifdef HAVE_GLOB_H
66 # include <glob.h>
67 #endif
68 #ifdef CLIENT_SUBNET
69 #include "edns-subnet/edns-subnet.h"
70 #endif
71 #ifdef HAVE_PWD_H
72 #include <pwd.h>
73 #endif
74 
75 /** from cfg username, after daemonize setup performed */
76 uid_t cfg_uid = (uid_t)-1;
77 /** from cfg username, after daemonize setup performed */
78 gid_t cfg_gid = (gid_t)-1;
79 /** for debug allow small timeout values for fast rollovers */
80 int autr_permit_small_holddown = 0;
81 /** size (in bytes) of stream wait buffers max */
82 size_t stream_wait_max = 4 * 1024 * 1024;
83 size_t http2_query_buffer_max = 4 * 1024 * 1024;
84 size_t http2_response_buffer_max = 4 * 1024 * 1024;
85 
86 /** global config during parsing */
87 struct config_parser_state* cfg_parser = 0;
88 
89 /** init ports possible for use */
90 static void init_outgoing_availports(int* array, int num);
91 
92 /** init cookie with random data */
93 static void init_cookie_secret(uint8_t* cookie_secret, size_t cookie_secret_len);
94 
95 struct config_file*
config_create(void)96 config_create(void)
97 {
98 	struct config_file* cfg;
99 	cfg = (struct config_file*)calloc(1, sizeof(struct config_file));
100 	if(!cfg)
101 		return NULL;
102 	/* the defaults if no config is present */
103 	cfg->verbosity = 1;
104 	cfg->stat_interval = 0;
105 	cfg->stat_cumulative = 0;
106 	cfg->stat_extended = 0;
107 	cfg->stat_inhibit_zero = 1;
108 	cfg->num_threads = 1;
109 	cfg->port = UNBOUND_DNS_PORT;
110 	cfg->do_ip4 = 1;
111 	cfg->do_ip6 = 1;
112 	cfg->do_udp = 1;
113 	cfg->do_tcp = 1;
114 	cfg->tcp_reuse_timeout = 60 * 1000; /* 60s in milisecs */
115 	cfg->max_reuse_tcp_queries = 200;
116 	cfg->tcp_upstream = 0;
117 	cfg->udp_upstream_without_downstream = 0;
118 	cfg->tcp_mss = 0;
119 	cfg->outgoing_tcp_mss = 0;
120 	cfg->tcp_idle_timeout = 30 * 1000; /* 30s in millisecs */
121 	cfg->tcp_auth_query_timeout = 3 * 1000; /* 3s in millisecs */
122 	cfg->do_tcp_keepalive = 0;
123 	cfg->tcp_keepalive_timeout = 120 * 1000; /* 120s in millisecs */
124 	cfg->sock_queue_timeout = 0; /* do not check timeout */
125 	cfg->ssl_service_key = NULL;
126 	cfg->ssl_service_pem = NULL;
127 	cfg->ssl_port = UNBOUND_DNS_OVER_TLS_PORT;
128 	cfg->ssl_upstream = 0;
129 	cfg->tls_cert_bundle = NULL;
130 	cfg->tls_win_cert = 0;
131 	cfg->tls_use_sni = 1;
132 	cfg->https_port = UNBOUND_DNS_OVER_HTTPS_PORT;
133 	if(!(cfg->http_endpoint = strdup("/dns-query"))) goto error_exit;
134 	cfg->http_max_streams = 100;
135 	cfg->http_query_buffer_size = 4*1024*1024;
136 	cfg->http_response_buffer_size = 4*1024*1024;
137 	cfg->http_nodelay = 1;
138 	cfg->quic_port = UNBOUND_DNS_OVER_QUIC_PORT;
139 	cfg->quic_size = 8*1024*1024;
140 	cfg->use_syslog = 1;
141 	cfg->log_identity = NULL; /* changed later with argv[0] */
142 	cfg->log_time_ascii = 0;
143 	cfg->log_time_iso = 0;
144 	cfg->log_queries = 0;
145 	cfg->log_replies = 0;
146 	cfg->log_tag_queryreply = 0;
147 	cfg->log_local_actions = 0;
148 	cfg->log_servfail = 0;
149 	cfg->log_destaddr = 0;
150 #ifndef USE_WINSOCK
151 #  ifdef USE_MINI_EVENT
152 	/* select max 1024 sockets */
153 	cfg->outgoing_num_ports = 960;
154 	cfg->num_queries_per_thread = 512;
155 #  else
156 	/* libevent can use many sockets */
157 	cfg->outgoing_num_ports = 4096;
158 	cfg->num_queries_per_thread = 1024;
159 #  endif
160 	cfg->outgoing_num_tcp = 10;
161 	cfg->incoming_num_tcp = 10;
162 #else
163 	cfg->outgoing_num_ports = 48; /* windows is limited in num fds */
164 	cfg->num_queries_per_thread = 24;
165 	cfg->outgoing_num_tcp = 2; /* leaves 64-52=12 for: 4if,1stop,thread4 */
166 	cfg->incoming_num_tcp = 2;
167 #endif
168 	cfg->stream_wait_size = 4 * 1024 * 1024;
169 	cfg->edns_buffer_size = 1232; /* from DNS flagday recommendation */
170 	cfg->msg_buffer_size = 65552; /* 64 k + a small margin */
171 	cfg->msg_cache_size = 4 * 1024 * 1024;
172 	cfg->msg_cache_slabs = 4;
173 	cfg->jostle_time = 200;
174 	cfg->rrset_cache_size = 4 * 1024 * 1024;
175 	cfg->rrset_cache_slabs = 4;
176 	cfg->host_ttl = 900;
177 	cfg->bogus_ttl = 60;
178 	cfg->min_ttl = 0;
179 	cfg->max_ttl = 3600 * 24;
180 	cfg->max_negative_ttl = 3600;
181 	cfg->min_negative_ttl = 0;
182 	cfg->prefetch = 0;
183 	cfg->prefetch_key = 0;
184 	cfg->deny_any = 0;
185 	cfg->infra_cache_slabs = 4;
186 	cfg->infra_cache_numhosts = 10000;
187 	cfg->infra_cache_min_rtt = 50;
188 	cfg->infra_cache_max_rtt = 120000;
189 	cfg->infra_keep_probing = 0;
190 	cfg->delay_close = 0;
191 	cfg->udp_connect = 1;
192 	if(!(cfg->outgoing_avail_ports = (int*)calloc(65536, sizeof(int))))
193 		goto error_exit;
194 	init_outgoing_availports(cfg->outgoing_avail_ports, 65536);
195 	if(!(cfg->username = strdup(UB_USERNAME))) goto error_exit;
196 #ifdef HAVE_CHROOT
197 	if(!(cfg->chrootdir = strdup(CHROOT_DIR))) goto error_exit;
198 #endif
199 	if(!(cfg->directory = strdup(RUN_DIR))) goto error_exit;
200 	if(!(cfg->logfile = strdup(""))) goto error_exit;
201 	if(!(cfg->pidfile = strdup(PIDFILE))) goto error_exit;
202 	if(!(cfg->target_fetch_policy = strdup("3 2 1 0 0"))) goto error_exit;
203 	cfg->fast_server_permil = 0;
204 	cfg->fast_server_num = 3;
205 	cfg->donotqueryaddrs = NULL;
206 	cfg->donotquery_localhost = 1;
207 	cfg->root_hints = NULL;
208 	cfg->use_systemd = 0;
209 	cfg->do_daemonize = 1;
210 	cfg->if_automatic = 0;
211 	cfg->if_automatic_ports = NULL;
212 	cfg->so_rcvbuf = 0;
213 	cfg->so_sndbuf = 0;
214 	cfg->so_reuseport = REUSEPORT_DEFAULT;
215 	cfg->ip_transparent = 0;
216 	cfg->ip_freebind = 0;
217 	cfg->ip_dscp = 0;
218 	cfg->num_ifs = 0;
219 	cfg->ifs = NULL;
220 	cfg->num_out_ifs = 0;
221 	cfg->out_ifs = NULL;
222 	cfg->stubs = NULL;
223 	cfg->forwards = NULL;
224 	cfg->auths = NULL;
225 #ifdef CLIENT_SUBNET
226 	cfg->client_subnet = NULL;
227 	cfg->client_subnet_zone = NULL;
228 	cfg->client_subnet_opcode = LDNS_EDNS_CLIENT_SUBNET;
229 	cfg->client_subnet_always_forward = 0;
230 	cfg->max_client_subnet_ipv4 = 24;
231 	cfg->max_client_subnet_ipv6 = 56;
232 	cfg->min_client_subnet_ipv4 = 0;
233 	cfg->min_client_subnet_ipv6 = 0;
234 	cfg->max_ecs_tree_size_ipv4 = 100;
235 	cfg->max_ecs_tree_size_ipv6 = 100;
236 #endif
237 	cfg->views = NULL;
238 	cfg->acls = NULL;
239 	cfg->tcp_connection_limits = NULL;
240 	cfg->harden_short_bufsize = 1;
241 	cfg->harden_large_queries = 0;
242 	cfg->harden_glue = 1;
243 	cfg->harden_unverified_glue = 0;
244 	cfg->harden_dnssec_stripped = 1;
245 	cfg->harden_below_nxdomain = 1;
246 	cfg->harden_referral_path = 0;
247 	cfg->harden_algo_downgrade = 0;
248 	cfg->harden_unknown_additional = 0;
249 	cfg->use_caps_bits_for_id = 0;
250 	cfg->caps_whitelist = NULL;
251 	cfg->private_address = NULL;
252 	cfg->private_domain = NULL;
253 	cfg->unwanted_threshold = 0;
254 	cfg->hide_identity = 0;
255 	cfg->hide_version = 0;
256 	cfg->hide_trustanchor = 0;
257 	cfg->hide_http_user_agent = 0;
258 	cfg->identity = NULL;
259 	cfg->version = NULL;
260 	cfg->http_user_agent = NULL;
261 	cfg->nsid_cfg_str = NULL;
262 	cfg->nsid = NULL;
263 	cfg->nsid_len = 0;
264 	cfg->auto_trust_anchor_file_list = NULL;
265 	cfg->trust_anchor_file_list = NULL;
266 	cfg->trust_anchor_list = NULL;
267 	cfg->trusted_keys_file_list = NULL;
268 	cfg->trust_anchor_signaling = 1;
269 	cfg->root_key_sentinel = 1;
270 	cfg->domain_insecure = NULL;
271 	cfg->val_date_override = 0;
272 	cfg->val_sig_skew_min = 3600; /* at least daylight savings trouble */
273 	cfg->val_sig_skew_max = 86400; /* at most timezone settings trouble */
274 	cfg->val_max_restart = 5;
275 	cfg->val_clean_additional = 1;
276 	cfg->val_log_level = 0;
277 	cfg->val_log_squelch = 0;
278 	cfg->val_permissive_mode = 0;
279 	cfg->aggressive_nsec = 1;
280 	cfg->ignore_cd = 0;
281 	cfg->disable_edns_do = 0;
282 	cfg->serve_expired = 0;
283 	cfg->serve_expired_ttl = 0;
284 	cfg->serve_expired_ttl_reset = 0;
285 	cfg->serve_expired_reply_ttl = 30;
286 	cfg->serve_expired_client_timeout = 0;
287 	cfg->ede_serve_expired = 0;
288 	cfg->serve_original_ttl = 0;
289 	cfg->zonemd_permissive_mode = 0;
290 	cfg->add_holddown = 30*24*3600;
291 	cfg->del_holddown = 30*24*3600;
292 	cfg->keep_missing = 366*24*3600; /* one year plus a little leeway */
293 	cfg->permit_small_holddown = 0;
294 	cfg->key_cache_size = 4 * 1024 * 1024;
295 	cfg->key_cache_slabs = 4;
296 	cfg->neg_cache_size = 1 * 1024 * 1024;
297 	cfg->local_zones = NULL;
298 	cfg->local_zones_nodefault = NULL;
299 #ifdef USE_IPSET
300 	cfg->local_zones_ipset = NULL;
301 #endif
302 	cfg->local_zones_disable_default = 0;
303 	cfg->local_data = NULL;
304 	cfg->local_zone_overrides = NULL;
305 	cfg->unblock_lan_zones = 0;
306 	cfg->insecure_lan_zones = 0;
307 	cfg->python_script = NULL;
308 	cfg->dynlib_file = NULL;
309 	cfg->remote_control_enable = 0;
310 	cfg->control_ifs.first = NULL;
311 	cfg->control_ifs.last = NULL;
312 	cfg->control_port = UNBOUND_CONTROL_PORT;
313 	cfg->control_use_cert = 1;
314 	cfg->minimal_responses = 1;
315 	cfg->rrset_roundrobin = 1;
316 	cfg->unknown_server_time_limit = 376;
317 	cfg->discard_timeout = 1900; /* msec */
318 	cfg->wait_limit = 1000;
319 	cfg->wait_limit_cookie = 10000;
320 	cfg->wait_limit_netblock = NULL;
321 	cfg->wait_limit_cookie_netblock = NULL;
322 	cfg->max_udp_size = 1232; /* value taken from edns_buffer_size */
323 	if(!(cfg->server_key_file = strdup(RUN_DIR"/unbound_server.key")))
324 		goto error_exit;
325 	if(!(cfg->server_cert_file = strdup(RUN_DIR"/unbound_server.pem")))
326 		goto error_exit;
327 	if(!(cfg->control_key_file = strdup(RUN_DIR"/unbound_control.key")))
328 		goto error_exit;
329 	if(!(cfg->control_cert_file = strdup(RUN_DIR"/unbound_control.pem")))
330 		goto error_exit;
331 
332 #ifdef CLIENT_SUBNET
333 	if(!(cfg->module_conf = strdup("subnetcache validator iterator"))) goto error_exit;
334 #else
335 	if(!(cfg->module_conf = strdup("validator iterator"))) goto error_exit;
336 #endif
337 	if(!(cfg->val_nsec3_key_iterations =
338 		strdup("1024 150 2048 150 4096 150"))) goto error_exit;
339 #if defined(DNSTAP_SOCKET_PATH)
340 	if(!(cfg->dnstap_socket_path = strdup(DNSTAP_SOCKET_PATH)))
341 		goto error_exit;
342 #endif
343 	cfg->dnstap_bidirectional = 1;
344 	cfg->dnstap_tls = 1;
345 	cfg->disable_dnssec_lame_check = 0;
346 	cfg->ip_ratelimit_cookie = 0;
347 	cfg->ip_ratelimit = 0;
348 	cfg->ratelimit = 0;
349 	cfg->ip_ratelimit_slabs = 4;
350 	cfg->ratelimit_slabs = 4;
351 	cfg->ip_ratelimit_size = 4*1024*1024;
352 	cfg->ratelimit_size = 4*1024*1024;
353 	cfg->ratelimit_for_domain = NULL;
354 	cfg->ratelimit_below_domain = NULL;
355 	cfg->ip_ratelimit_factor = 10;
356 	cfg->ratelimit_factor = 10;
357 	cfg->ip_ratelimit_backoff = 0;
358 	cfg->ratelimit_backoff = 0;
359 	cfg->outbound_msg_retry = 5;
360 	cfg->max_sent_count = 32;
361 	cfg->max_query_restarts = 11;
362 	cfg->qname_minimisation = 1;
363 	cfg->qname_minimisation_strict = 0;
364 	cfg->shm_enable = 0;
365 	cfg->shm_key = 11777;
366 	cfg->edns_client_strings = NULL;
367 	cfg->edns_client_string_opcode = 65001;
368 	cfg->dnscrypt = 0;
369 	cfg->dnscrypt_port = 0;
370 	cfg->dnscrypt_provider = NULL;
371 	cfg->dnscrypt_provider_cert = NULL;
372 	cfg->dnscrypt_provider_cert_rotated = NULL;
373 	cfg->dnscrypt_secret_key = NULL;
374 	cfg->dnscrypt_shared_secret_cache_size = 4*1024*1024;
375 	cfg->dnscrypt_shared_secret_cache_slabs = 4;
376 	cfg->dnscrypt_nonce_cache_size = 4*1024*1024;
377 	cfg->dnscrypt_nonce_cache_slabs = 4;
378 	cfg->pad_responses = 1;
379 	cfg->pad_responses_block_size = 468; /* from RFC8467 */
380 	cfg->pad_queries = 1;
381 	cfg->pad_queries_block_size = 128; /* from RFC8467 */
382 #ifdef USE_IPSECMOD
383 	cfg->ipsecmod_enabled = 1;
384 	cfg->ipsecmod_ignore_bogus = 0;
385 	cfg->ipsecmod_hook = NULL;
386 	cfg->ipsecmod_max_ttl = 3600;
387 	cfg->ipsecmod_whitelist = NULL;
388 	cfg->ipsecmod_strict = 0;
389 #endif
390 	cfg->do_answer_cookie = 0;
391 	memset(cfg->cookie_secret, 0, sizeof(cfg->cookie_secret));
392 	cfg->cookie_secret_len = 16;
393 	init_cookie_secret(cfg->cookie_secret, cfg->cookie_secret_len);
394 	cfg->cookie_secret_file = NULL;
395 #ifdef USE_CACHEDB
396 	if(!(cfg->cachedb_backend = strdup("testframe"))) goto error_exit;
397 	if(!(cfg->cachedb_secret = strdup("default"))) goto error_exit;
398 	cfg->cachedb_no_store = 0;
399 	cfg->cachedb_check_when_serve_expired = 1;
400 #ifdef USE_REDIS
401 	if(!(cfg->redis_server_host = strdup("127.0.0.1"))) goto error_exit;
402 	cfg->redis_server_path = NULL;
403 	cfg->redis_server_password = NULL;
404 	cfg->redis_timeout = 100;
405 	cfg->redis_command_timeout = 0;
406 	cfg->redis_connect_timeout = 0;
407 	cfg->redis_server_port = 6379;
408 	cfg->redis_expire_records = 0;
409 	cfg->redis_logical_db = 0;
410 #endif  /* USE_REDIS */
411 #endif  /* USE_CACHEDB */
412 #ifdef USE_IPSET
413 	cfg->ipset_name_v4 = NULL;
414 	cfg->ipset_name_v6 = NULL;
415 #endif
416 	cfg->ede = 0;
417 	cfg->iter_scrub_ns = 20;
418 	cfg->iter_scrub_cname = 11;
419 	cfg->max_global_quota = 128;
420 	return cfg;
421 error_exit:
422 	config_delete(cfg);
423 	return NULL;
424 }
425 
config_create_forlib(void)426 struct config_file* config_create_forlib(void)
427 {
428 	struct config_file* cfg = config_create();
429 	if(!cfg) return NULL;
430 	/* modifications for library use, less verbose, less memory */
431 	free(cfg->chrootdir);
432 	cfg->chrootdir = NULL;
433 	cfg->verbosity = 0;
434 	cfg->outgoing_num_ports = 16; /* in library use, this is 'reasonable'
435 		and probably within the ulimit(maxfds) of the user */
436 	cfg->outgoing_num_tcp = 2;
437 	cfg->msg_cache_size = 1024*1024;
438 	cfg->msg_cache_slabs = 1;
439 	cfg->rrset_cache_size = 1024*1024;
440 	cfg->rrset_cache_slabs = 1;
441 	cfg->infra_cache_slabs = 1;
442 	cfg->use_syslog = 0;
443 	cfg->key_cache_size = 1024*1024;
444 	cfg->key_cache_slabs = 1;
445 	cfg->neg_cache_size = 100 * 1024;
446 	cfg->donotquery_localhost = 0; /* allow, so that you can ask a
447 		forward nameserver running on localhost */
448 	cfg->val_log_level = 2; /* to fill why_bogus with */
449 	cfg->val_log_squelch = 1;
450 	cfg->minimal_responses = 0;
451 	cfg->harden_short_bufsize = 1;
452 	return cfg;
453 }
454 
455 /** check that the value passed is >= 0 */
456 #define IS_NUMBER_OR_ZERO \
457 	if(atoi(val) == 0 && strcmp(val, "0") != 0) return 0
458 /** check that the value passed is > 0 */
459 #define IS_NONZERO_NUMBER \
460 	if(atoi(val) == 0) return 0
461 /** check that the value passed is not 0 and a power of 2 */
462 #define IS_POW2_NUMBER \
463 	if(atoi(val) == 0 || !is_pow2((size_t)atoi(val))) return 0
464 /** check that the value passed is yes or no */
465 #define IS_YES_OR_NO \
466 	if(strcmp(val, "yes") != 0 && strcmp(val, "no") != 0) return 0
467 /** put integer_or_zero into variable */
468 #define S_NUMBER_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
469 	{ IS_NUMBER_OR_ZERO; cfg->var = atoi(val); }
470 /** put integer_nonzero into variable */
471 #define S_NUMBER_NONZERO(str, var) if(strcmp(opt, str) == 0) \
472 	{ IS_NONZERO_NUMBER; cfg->var = atoi(val); }
473 /** put integer_or_zero into unsigned */
474 #define S_UNSIGNED_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
475 	{ IS_NUMBER_OR_ZERO; cfg->var = (unsigned)atoi(val); }
476 /** put integer_or_zero into size_t */
477 #define S_SIZET_OR_ZERO(str, var) if(strcmp(opt, str) == 0) \
478 	{ IS_NUMBER_OR_ZERO; cfg->var = (size_t)atoi(val); }
479 /** put integer_nonzero into size_t */
480 #define S_SIZET_NONZERO(str, var) if(strcmp(opt, str) == 0) \
481 	{ IS_NONZERO_NUMBER; cfg->var = (size_t)atoi(val); }
482 /** put yesno into variable */
483 #define S_YNO(str, var) if(strcmp(opt, str) == 0) \
484 	{ IS_YES_OR_NO; cfg->var = (strcmp(val, "yes") == 0); }
485 /** put memsize into variable */
486 #define S_MEMSIZE(str, var) if(strcmp(opt, str)==0) \
487 	{ return cfg_parse_memsize(val, &cfg->var); }
488 /** put pow2 number into variable */
489 #define S_POW2(str, var) if(strcmp(opt, str)==0) \
490 	{ IS_POW2_NUMBER; cfg->var = (size_t)atoi(val); }
491 /** put string into variable */
492 #define S_STR(str, var) if(strcmp(opt, str)==0) \
493 	{ free(cfg->var); return (cfg->var = strdup(val)) != NULL; }
494 /** put string into strlist */
495 #define S_STRLIST(str, var) if(strcmp(opt, str)==0) \
496 	{ return cfg_strlist_insert(&cfg->var, strdup(val)); }
497 /** put string into strlist if not present yet*/
498 #define S_STRLIST_UNIQ(str, var) if(strcmp(opt, str)==0) \
499 	{ if(cfg_strlist_find(cfg->var, val)) { return 0;} \
500 	  return cfg_strlist_insert(&cfg->var, strdup(val)); }
501 /** append string to strlist */
502 #define S_STRLIST_APPEND(str, var) if(strcmp(opt, str)==0) \
503 	{ return cfg_strlist_append(&cfg->var, strdup(val)); }
504 
config_set_option(struct config_file * cfg,const char * opt,const char * val)505 int config_set_option(struct config_file* cfg, const char* opt,
506 	const char* val)
507 {
508 	char buf[64];
509 	if(!opt) return 0;
510 	if(opt[strlen(opt)-1] != ':' && strlen(opt)+2<sizeof(buf)) {
511 		snprintf(buf, sizeof(buf), "%s:", opt);
512 		opt = buf;
513 	}
514 	S_NUMBER_OR_ZERO("verbosity:", verbosity)
515 	else if(strcmp(opt, "statistics-interval:") == 0) {
516 		if(strcmp(val, "0") == 0 || strcmp(val, "") == 0)
517 			cfg->stat_interval = 0;
518 		else if(atoi(val) == 0)
519 			return 0;
520 		else cfg->stat_interval = atoi(val);
521 	} else if(strcmp(opt, "num-threads:") == 0) {
522 		/* not supported, library must have 1 thread in bgworker */
523 		return 0;
524 	} else if(strcmp(opt, "outgoing-port-permit:") == 0) {
525 		return cfg_mark_ports(val, 1,
526 			cfg->outgoing_avail_ports, 65536);
527 	} else if(strcmp(opt, "outgoing-port-avoid:") == 0) {
528 		return cfg_mark_ports(val, 0,
529 			cfg->outgoing_avail_ports, 65536);
530 	} else if(strcmp(opt, "local-zone:") == 0) {
531 		return cfg_parse_local_zone(cfg, val);
532 	} else if(strcmp(opt, "val-override-date:") == 0) {
533 		if(strcmp(val, "") == 0 || strcmp(val, "0") == 0) {
534 			cfg->val_date_override = 0;
535 		} else if(strlen(val) == 14) {
536 			cfg->val_date_override = cfg_convert_timeval(val);
537 			return cfg->val_date_override != 0;
538 		} else {
539 			if(atoi(val) == 0) return 0;
540 			cfg->val_date_override = (uint32_t)atoi(val);
541 		}
542 	} else if(strcmp(opt, "local-data-ptr:") == 0) {
543 		char* ptr = cfg_ptr_reverse((char*)opt);
544 		return cfg_strlist_insert(&cfg->local_data, ptr);
545 	} else if(strcmp(opt, "logfile:") == 0) {
546 		cfg->use_syslog = 0;
547 		free(cfg->logfile);
548 		return (cfg->logfile = strdup(val)) != NULL;
549 	}
550 	else if(strcmp(opt, "log-time-ascii:") == 0)
551 	{ IS_YES_OR_NO; cfg->log_time_ascii = (strcmp(val, "yes") == 0);
552 	  log_set_time_asc(cfg->log_time_ascii); }
553 	else if(strcmp(opt, "log-time-iso:") == 0)
554 	{ IS_YES_OR_NO; cfg->log_time_iso = (strcmp(val, "yes") == 0);
555 	  log_set_time_iso(cfg->log_time_iso); }
556 	else S_SIZET_NONZERO("max-udp-size:", max_udp_size)
557 	else S_YNO("use-syslog:", use_syslog)
558 	else S_STR("log-identity:", log_identity)
559 	else S_YNO("extended-statistics:", stat_extended)
560 	else S_YNO("statistics-inhibit-zero:", stat_inhibit_zero)
561 	else S_YNO("statistics-cumulative:", stat_cumulative)
562 	else S_YNO("shm-enable:", shm_enable)
563 	else S_NUMBER_OR_ZERO("shm-key:", shm_key)
564 	else S_YNO("do-ip4:", do_ip4)
565 	else S_YNO("do-ip6:", do_ip6)
566 	else S_YNO("do-udp:", do_udp)
567 	else S_YNO("do-tcp:", do_tcp)
568 	else S_YNO("prefer-ip4:", prefer_ip4)
569 	else S_YNO("prefer-ip6:", prefer_ip6)
570 	else S_YNO("tcp-upstream:", tcp_upstream)
571 	else S_YNO("udp-upstream-without-downstream:",
572 		udp_upstream_without_downstream)
573 	else S_NUMBER_NONZERO("tcp-mss:", tcp_mss)
574 	else S_NUMBER_NONZERO("outgoing-tcp-mss:", outgoing_tcp_mss)
575 	else S_NUMBER_NONZERO("tcp-auth-query-timeout:", tcp_auth_query_timeout)
576 	else S_NUMBER_NONZERO("tcp-idle-timeout:", tcp_idle_timeout)
577 	else S_NUMBER_NONZERO("max-reuse-tcp-queries:", max_reuse_tcp_queries)
578 	else S_NUMBER_NONZERO("tcp-reuse-timeout:", tcp_reuse_timeout)
579 	else S_YNO("edns-tcp-keepalive:", do_tcp_keepalive)
580 	else S_NUMBER_NONZERO("edns-tcp-keepalive-timeout:", tcp_keepalive_timeout)
581 	else S_NUMBER_OR_ZERO("sock-queue-timeout:", sock_queue_timeout)
582 	else S_YNO("ssl-upstream:", ssl_upstream)
583 	else S_YNO("tls-upstream:", ssl_upstream)
584 	else S_STR("ssl-service-key:", ssl_service_key)
585 	else S_STR("tls-service-key:", ssl_service_key)
586 	else S_STR("ssl-service-pem:", ssl_service_pem)
587 	else S_STR("tls-service-pem:", ssl_service_pem)
588 	else S_NUMBER_NONZERO("ssl-port:", ssl_port)
589 	else S_NUMBER_NONZERO("tls-port:", ssl_port)
590 	else S_STR("ssl-cert-bundle:", tls_cert_bundle)
591 	else S_STR("tls-cert-bundle:", tls_cert_bundle)
592 	else S_YNO("tls-win-cert:", tls_win_cert)
593 	else S_YNO("tls-system-cert:", tls_win_cert)
594 	else S_STRLIST("additional-ssl-port:", tls_additional_port)
595 	else S_STRLIST("additional-tls-port:", tls_additional_port)
596 	else S_STRLIST("tls-additional-ports:", tls_additional_port)
597 	else S_STRLIST("tls-additional-port:", tls_additional_port)
598 	else S_STRLIST_APPEND("tls-session-ticket-keys:", tls_session_ticket_keys)
599 	else S_STR("tls-ciphers:", tls_ciphers)
600 	else S_STR("tls-ciphersuites:", tls_ciphersuites)
601 	else S_YNO("tls-use-sni:", tls_use_sni)
602 	else S_NUMBER_NONZERO("https-port:", https_port)
603 	else S_STR("http-endpoint:", http_endpoint)
604 	else S_NUMBER_NONZERO("http-max-streams:", http_max_streams)
605 	else S_MEMSIZE("http-query-buffer-size:", http_query_buffer_size)
606 	else S_MEMSIZE("http-response-buffer-size:", http_response_buffer_size)
607 	else S_YNO("http-nodelay:", http_nodelay)
608 	else S_YNO("http-notls-downstream:", http_notls_downstream)
609 	else S_NUMBER_NONZERO("quic-port:", quic_port)
610 	else S_MEMSIZE("quic-size:", quic_size)
611 	else S_YNO("interface-automatic:", if_automatic)
612 	else S_STR("interface-automatic-ports:", if_automatic_ports)
613 	else S_YNO("use-systemd:", use_systemd)
614 	else S_YNO("do-daemonize:", do_daemonize)
615 	else S_NUMBER_NONZERO("port:", port)
616 	else S_NUMBER_NONZERO("outgoing-range:", outgoing_num_ports)
617 	else S_SIZET_OR_ZERO("outgoing-num-tcp:", outgoing_num_tcp)
618 	else S_SIZET_OR_ZERO("incoming-num-tcp:", incoming_num_tcp)
619 	else S_MEMSIZE("stream-wait-size:", stream_wait_size)
620 	else S_SIZET_NONZERO("edns-buffer-size:", edns_buffer_size)
621 	else S_SIZET_NONZERO("msg-buffer-size:", msg_buffer_size)
622 	else S_MEMSIZE("msg-cache-size:", msg_cache_size)
623 	else S_POW2("msg-cache-slabs:", msg_cache_slabs)
624 	else S_SIZET_NONZERO("num-queries-per-thread:",num_queries_per_thread)
625 	else S_SIZET_OR_ZERO("jostle-timeout:", jostle_time)
626 	else S_MEMSIZE("so-rcvbuf:", so_rcvbuf)
627 	else S_MEMSIZE("so-sndbuf:", so_sndbuf)
628 	else S_YNO("so-reuseport:", so_reuseport)
629 	else S_YNO("ip-transparent:", ip_transparent)
630 	else S_YNO("ip-freebind:", ip_freebind)
631 	else S_NUMBER_OR_ZERO("ip-dscp:", ip_dscp)
632 	else S_MEMSIZE("rrset-cache-size:", rrset_cache_size)
633 	else S_POW2("rrset-cache-slabs:", rrset_cache_slabs)
634 	else S_YNO("prefetch:", prefetch)
635 	else S_YNO("prefetch-key:", prefetch_key)
636 	else S_YNO("deny-any:", deny_any)
637 	else if(strcmp(opt, "cache-max-ttl:") == 0)
638 	{ IS_NUMBER_OR_ZERO; cfg->max_ttl = atoi(val); MAX_TTL=(time_t)cfg->max_ttl;}
639 	else if(strcmp(opt, "cache-max-negative-ttl:") == 0)
640 	{ IS_NUMBER_OR_ZERO; cfg->max_negative_ttl = atoi(val); MAX_NEG_TTL=(time_t)cfg->max_negative_ttl;}
641 	else if(strcmp(opt, "cache-min-negative-ttl:") == 0)
642 	{ IS_NUMBER_OR_ZERO; cfg->min_negative_ttl = atoi(val); MIN_NEG_TTL=(time_t)cfg->min_negative_ttl;}
643 	else if(strcmp(opt, "cache-min-ttl:") == 0)
644 	{ IS_NUMBER_OR_ZERO; cfg->min_ttl = atoi(val); MIN_TTL=(time_t)cfg->min_ttl;}
645 	else if(strcmp(opt, "infra-cache-min-rtt:") == 0) {
646 	 	IS_NUMBER_OR_ZERO; cfg->infra_cache_min_rtt = atoi(val);
647 		RTT_MIN_TIMEOUT=cfg->infra_cache_min_rtt;
648 	}
649 	else if(strcmp(opt, "infra-cache-max-rtt:") == 0) {
650 		IS_NUMBER_OR_ZERO; cfg->infra_cache_max_rtt = atoi(val);
651 		RTT_MAX_TIMEOUT=cfg->infra_cache_max_rtt;
652 		USEFUL_SERVER_TOP_TIMEOUT = RTT_MAX_TIMEOUT;
653 		BLACKLIST_PENALTY = USEFUL_SERVER_TOP_TIMEOUT*4;
654 	}
655 	else S_YNO("infra-keep-probing:", infra_keep_probing)
656 	else S_NUMBER_OR_ZERO("infra-host-ttl:", host_ttl)
657 	else S_POW2("infra-cache-slabs:", infra_cache_slabs)
658 	else S_SIZET_NONZERO("infra-cache-numhosts:", infra_cache_numhosts)
659 	else S_NUMBER_OR_ZERO("delay-close:", delay_close)
660 	else S_YNO("udp-connect:", udp_connect)
661 	else S_STR("chroot:", chrootdir)
662 	else S_STR("username:", username)
663 	else S_STR("directory:", directory)
664 	else S_STR("pidfile:", pidfile)
665 	else S_YNO("hide-identity:", hide_identity)
666 	else S_YNO("hide-version:", hide_version)
667 	else S_YNO("hide-trustanchor:", hide_trustanchor)
668 	else S_YNO("hide-http-user-agent:", hide_http_user_agent)
669 	else S_STR("identity:", identity)
670 	else S_STR("version:", version)
671 	else S_STR("http-user-agent:", http_user_agent)
672 	else if(strcmp(opt, "nsid:") == 0) {
673 		free(cfg->nsid_cfg_str);
674 		if (!(cfg->nsid_cfg_str = strdup(val)))
675 			return 0;
676 		/* Empty string is just validly unsetting nsid */
677 		if (*val == 0) {
678 			free(cfg->nsid);
679 			cfg->nsid = NULL;
680 			cfg->nsid_len = 0;
681 			return 1;
682 		}
683 		cfg->nsid = cfg_parse_nsid(val, &cfg->nsid_len);
684 		return cfg->nsid != NULL;
685 	}
686 	else S_STRLIST("root-hints:", root_hints)
687 	else S_STR("target-fetch-policy:", target_fetch_policy)
688 	else S_YNO("harden-glue:", harden_glue)
689 	else S_YNO("harden-unverified-glue:", harden_unverified_glue)
690 	else S_YNO("harden-short-bufsize:", harden_short_bufsize)
691 	else S_YNO("harden-large-queries:", harden_large_queries)
692 	else S_YNO("harden-dnssec-stripped:", harden_dnssec_stripped)
693 	else S_YNO("harden-below-nxdomain:", harden_below_nxdomain)
694 	else S_YNO("harden-referral-path:", harden_referral_path)
695 	else S_YNO("harden-algo-downgrade:", harden_algo_downgrade)
696 	else S_YNO("harden-unknown-additional:", harden_unknown_additional)
697 	else S_YNO("use-caps-for-id:", use_caps_bits_for_id)
698 	else S_STRLIST("caps-whitelist:", caps_whitelist)
699 	else S_SIZET_OR_ZERO("unwanted-reply-threshold:", unwanted_threshold)
700 	else S_STRLIST("private-address:", private_address)
701 	else S_STRLIST("private-domain:", private_domain)
702 	else S_YNO("do-not-query-localhost:", donotquery_localhost)
703 	else S_STRLIST("do-not-query-address:", donotqueryaddrs)
704 	else S_STRLIST("auto-trust-anchor-file:", auto_trust_anchor_file_list)
705 	else S_STRLIST("trust-anchor-file:", trust_anchor_file_list)
706 	else S_STRLIST("trust-anchor:", trust_anchor_list)
707 	else S_STRLIST("trusted-keys-file:", trusted_keys_file_list)
708 	else S_YNO("trust-anchor-signaling:", trust_anchor_signaling)
709 	else S_YNO("root-key-sentinel:", root_key_sentinel)
710 	else S_STRLIST("domain-insecure:", domain_insecure)
711 	else S_NUMBER_OR_ZERO("val-bogus-ttl:", bogus_ttl)
712 	else S_YNO("val-clean-additional:", val_clean_additional)
713 	else S_NUMBER_OR_ZERO("val-log-level:", val_log_level)
714 	else S_YNO("val-log-squelch:", val_log_squelch)
715 	else S_YNO("log-queries:", log_queries)
716 	else S_YNO("log-replies:", log_replies)
717 	else S_YNO("log-tag-queryreply:", log_tag_queryreply)
718 	else S_YNO("log-local-actions:", log_local_actions)
719 	else S_YNO("log-servfail:", log_servfail)
720 	else S_YNO("log-destaddr:", log_destaddr)
721 	else S_YNO("val-permissive-mode:", val_permissive_mode)
722 	else S_YNO("aggressive-nsec:", aggressive_nsec)
723 	else S_YNO("ignore-cd-flag:", ignore_cd)
724 	else S_YNO("disable-edns-do:", disable_edns_do)
725 	else if(strcmp(opt, "serve-expired:") == 0)
726 	{ IS_YES_OR_NO; cfg->serve_expired = (strcmp(val, "yes") == 0);
727 	  SERVE_EXPIRED = cfg->serve_expired; }
728 	else if(strcmp(opt, "serve-expired-ttl:") == 0)
729 	{ IS_NUMBER_OR_ZERO; cfg->serve_expired_ttl = atoi(val); SERVE_EXPIRED_TTL=(time_t)cfg->serve_expired_ttl;}
730 	else if(strcmp(opt, "serve-expired-ttl-reset:") == 0)
731 	{ IS_YES_OR_NO; cfg->serve_expired_ttl_reset = (strcmp(val, "yes") == 0);
732 	  SERVE_EXPIRED_TTL_RESET = cfg->serve_expired_ttl_reset; }
733 	else if(strcmp(opt, "serve-expired-reply-ttl:") == 0)
734 	{ IS_NUMBER_OR_ZERO; cfg->serve_expired_reply_ttl = atoi(val); SERVE_EXPIRED_REPLY_TTL=(time_t)cfg->serve_expired_reply_ttl;}
735 	else S_NUMBER_OR_ZERO("serve-expired-client-timeout:", serve_expired_client_timeout)
736 	else S_YNO("ede:", ede)
737 	else S_YNO("ede-serve-expired:", ede_serve_expired)
738 	else S_NUMBER_OR_ZERO("iter-scrub-ns:", iter_scrub_ns)
739 	else S_NUMBER_OR_ZERO("iter-scrub-cname:", iter_scrub_cname)
740 	else S_NUMBER_OR_ZERO("max-global-quota:", max_global_quota)
741 	else S_YNO("serve-original-ttl:", serve_original_ttl)
742 	else S_STR("val-nsec3-keysize-iterations:", val_nsec3_key_iterations)
743 	else S_YNO("zonemd-permissive-mode:", zonemd_permissive_mode)
744 	else S_UNSIGNED_OR_ZERO("add-holddown:", add_holddown)
745 	else S_UNSIGNED_OR_ZERO("del-holddown:", del_holddown)
746 	else S_UNSIGNED_OR_ZERO("keep-missing:", keep_missing)
747 	else if(strcmp(opt, "permit-small-holddown:") == 0)
748 	{ IS_YES_OR_NO; cfg->permit_small_holddown = (strcmp(val, "yes") == 0);
749 	  autr_permit_small_holddown = cfg->permit_small_holddown; }
750 	else S_MEMSIZE("key-cache-size:", key_cache_size)
751 	else S_POW2("key-cache-slabs:", key_cache_slabs)
752 	else S_MEMSIZE("neg-cache-size:", neg_cache_size)
753 	else S_YNO("minimal-responses:", minimal_responses)
754 	else S_YNO("rrset-roundrobin:", rrset_roundrobin)
755 	else S_NUMBER_OR_ZERO("unknown-server-time-limit:", unknown_server_time_limit)
756 	else S_NUMBER_OR_ZERO("discard-timeout:", discard_timeout)
757 	else S_NUMBER_OR_ZERO("wait-limit:", wait_limit)
758 	else S_NUMBER_OR_ZERO("wait-limit-cookie:", wait_limit_cookie)
759 	else S_STRLIST("local-data:", local_data)
760 	else S_YNO("unblock-lan-zones:", unblock_lan_zones)
761 	else S_YNO("insecure-lan-zones:", insecure_lan_zones)
762 	else S_YNO("control-enable:", remote_control_enable)
763 	else S_STRLIST_APPEND("control-interface:", control_ifs)
764 	else S_NUMBER_NONZERO("control-port:", control_port)
765 	else S_STR("server-key-file:", server_key_file)
766 	else S_STR("server-cert-file:", server_cert_file)
767 	else S_STR("control-key-file:", control_key_file)
768 	else S_STR("control-cert-file:", control_cert_file)
769 	else S_STR("module-config:", module_conf)
770 	else S_STRLIST("python-script:", python_script)
771 	else S_STRLIST("dynlib-file:", dynlib_file)
772 	else S_YNO("disable-dnssec-lame-check:", disable_dnssec_lame_check)
773 #ifdef CLIENT_SUBNET
774 	/* Can't set max subnet prefix here, since that value is used when
775 	 * generating the address tree. */
776 	/* No client-subnet-always-forward here, module registration depends on
777 	 * this option. */
778 #endif
779 #ifdef USE_DNSTAP
780 	else S_YNO("dnstap-enable:", dnstap)
781 	else S_YNO("dnstap-bidirectional:", dnstap_bidirectional)
782 	else S_STR("dnstap-socket-path:", dnstap_socket_path)
783 	else S_STR("dnstap-ip:", dnstap_ip)
784 	else S_YNO("dnstap-tls:", dnstap_tls)
785 	else S_STR("dnstap-tls-server-name:", dnstap_tls_server_name)
786 	else S_STR("dnstap-tls-cert-bundle:", dnstap_tls_cert_bundle)
787 	else S_STR("dnstap-tls-client-key-file:", dnstap_tls_client_key_file)
788 	else S_STR("dnstap-tls-client-cert-file:",
789 		dnstap_tls_client_cert_file)
790 	else S_YNO("dnstap-send-identity:", dnstap_send_identity)
791 	else S_YNO("dnstap-send-version:", dnstap_send_version)
792 	else S_STR("dnstap-identity:", dnstap_identity)
793 	else S_STR("dnstap-version:", dnstap_version)
794 	else S_NUMBER_OR_ZERO("dnstap-sample-rate:", dnstap_sample_rate)
795 	else S_YNO("dnstap-log-resolver-query-messages:",
796 		dnstap_log_resolver_query_messages)
797 	else S_YNO("dnstap-log-resolver-response-messages:",
798 		dnstap_log_resolver_response_messages)
799 	else S_YNO("dnstap-log-client-query-messages:",
800 		dnstap_log_client_query_messages)
801 	else S_YNO("dnstap-log-client-response-messages:",
802 		dnstap_log_client_response_messages)
803 	else S_YNO("dnstap-log-forwarder-query-messages:",
804 		dnstap_log_forwarder_query_messages)
805 	else S_YNO("dnstap-log-forwarder-response-messages:",
806 		dnstap_log_forwarder_response_messages)
807 #endif
808 #ifdef USE_DNSCRYPT
809 	else S_YNO("dnscrypt-enable:", dnscrypt)
810 	else S_NUMBER_NONZERO("dnscrypt-port:", dnscrypt_port)
811 	else S_STR("dnscrypt-provider:", dnscrypt_provider)
812 	else S_STRLIST_UNIQ("dnscrypt-provider-cert:", dnscrypt_provider_cert)
813 	else S_STRLIST("dnscrypt-provider-cert-rotated:", dnscrypt_provider_cert_rotated)
814 	else S_STRLIST_UNIQ("dnscrypt-secret-key:", dnscrypt_secret_key)
815 	else S_MEMSIZE("dnscrypt-shared-secret-cache-size:",
816 		dnscrypt_shared_secret_cache_size)
817 	else S_POW2("dnscrypt-shared-secret-cache-slabs:",
818 		dnscrypt_shared_secret_cache_slabs)
819 	else S_MEMSIZE("dnscrypt-nonce-cache-size:",
820 		dnscrypt_nonce_cache_size)
821 	else S_POW2("dnscrypt-nonce-cache-slabs:",
822 		dnscrypt_nonce_cache_slabs)
823 #endif
824 	else if(strcmp(opt, "ip-ratelimit-cookie:") == 0) {
825 	    IS_NUMBER_OR_ZERO; cfg->ip_ratelimit_cookie = atoi(val);
826 	    infra_ip_ratelimit_cookie=cfg->ip_ratelimit_cookie;
827 	}
828 	else if(strcmp(opt, "ip-ratelimit:") == 0) {
829 	    IS_NUMBER_OR_ZERO; cfg->ip_ratelimit = atoi(val);
830 	    infra_ip_ratelimit=cfg->ip_ratelimit;
831 	}
832 	else if(strcmp(opt, "ratelimit:") == 0) {
833 	    IS_NUMBER_OR_ZERO; cfg->ratelimit = atoi(val);
834 	    infra_dp_ratelimit=cfg->ratelimit;
835 	}
836 	else S_MEMSIZE("ip-ratelimit-size:", ip_ratelimit_size)
837 	else S_MEMSIZE("ratelimit-size:", ratelimit_size)
838 	else S_POW2("ip-ratelimit-slabs:", ip_ratelimit_slabs)
839 	else S_POW2("ratelimit-slabs:", ratelimit_slabs)
840 	else S_NUMBER_OR_ZERO("ip-ratelimit-factor:", ip_ratelimit_factor)
841 	else S_NUMBER_OR_ZERO("ratelimit-factor:", ratelimit_factor)
842 	else S_YNO("ip-ratelimit-backoff:", ip_ratelimit_backoff)
843 	else S_YNO("ratelimit-backoff:", ratelimit_backoff)
844 	else S_NUMBER_NONZERO("outbound-msg-retry:", outbound_msg_retry)
845 	else S_NUMBER_NONZERO("max-sent-count:", max_sent_count)
846 	else S_NUMBER_NONZERO("max-query-restarts:", max_query_restarts)
847 	else S_SIZET_NONZERO("fast-server-num:", fast_server_num)
848 	else S_NUMBER_OR_ZERO("fast-server-permil:", fast_server_permil)
849 	else S_YNO("qname-minimisation:", qname_minimisation)
850 	else S_YNO("qname-minimisation-strict:", qname_minimisation_strict)
851 	else S_YNO("pad-responses:", pad_responses)
852 	else S_SIZET_NONZERO("pad-responses-block-size:", pad_responses_block_size)
853 	else S_YNO("pad-queries:", pad_queries)
854 	else S_SIZET_NONZERO("pad-queries-block-size:", pad_queries_block_size)
855 	else S_STRLIST("proxy-protocol-port:", proxy_protocol_port)
856 #ifdef USE_IPSECMOD
857 	else S_YNO("ipsecmod-enabled:", ipsecmod_enabled)
858 	else S_YNO("ipsecmod-ignore-bogus:", ipsecmod_ignore_bogus)
859 	else if(strcmp(opt, "ipsecmod-max-ttl:") == 0)
860 	{ IS_NUMBER_OR_ZERO; cfg->ipsecmod_max_ttl = atoi(val); }
861 	else S_YNO("ipsecmod-strict:", ipsecmod_strict)
862 #endif
863 	else S_YNO("answer-cookie:", do_answer_cookie)
864 	else S_STR("cookie-secret-file:", cookie_secret_file)
865 #ifdef USE_CACHEDB
866 	else S_YNO("cachedb-no-store:", cachedb_no_store)
867 	else S_YNO("cachedb-check-when-serve-expired:", cachedb_check_when_serve_expired)
868 #endif /* USE_CACHEDB */
869 	else if(strcmp(opt, "define-tag:") ==0) {
870 		return config_add_tag(cfg, val);
871 	/* val_sig_skew_min, max and val_max_restart are copied into val_env
872 	 * during init so this does not update val_env with set_option */
873 	} else if(strcmp(opt, "val-sig-skew-min:") == 0)
874 	{ IS_NUMBER_OR_ZERO; cfg->val_sig_skew_min = (int32_t)atoi(val); }
875 	else if(strcmp(opt, "val-sig-skew-max:") == 0)
876 	{ IS_NUMBER_OR_ZERO; cfg->val_sig_skew_max = (int32_t)atoi(val); }
877 	else if(strcmp(opt, "val-max-restart:") == 0)
878 	{ IS_NUMBER_OR_ZERO; cfg->val_max_restart = (int32_t)atoi(val); }
879 	else if (strcmp(opt, "outgoing-interface:") == 0) {
880 		char* d = strdup(val);
881 		char** oi =
882 		(char**)reallocarray(NULL, (size_t)cfg->num_out_ifs+1, sizeof(char*));
883 		if(!d || !oi) { free(d); free(oi); return -1; }
884 		if(cfg->out_ifs && cfg->num_out_ifs) {
885 			memmove(oi, cfg->out_ifs, cfg->num_out_ifs*sizeof(char*));
886 			free(cfg->out_ifs);
887 		}
888 		oi[cfg->num_out_ifs++] = d;
889 		cfg->out_ifs = oi;
890 	} else {
891 		/* unknown or unsupported (from the set_option interface):
892 		 * interface, outgoing-interface, access-control,
893 		 * stub-zone, name, stub-addr, stub-host, stub-prime
894 		 * forward-first, stub-first, forward-ssl-upstream,
895 		 * stub-ssl-upstream, forward-zone, auth-zone
896 		 * name, forward-addr, forward-host,
897 		 * ratelimit-for-domain, ratelimit-below-domain,
898 		 * local-zone-tag, access-control-view, interface-*,
899 		 * send-client-subnet, client-subnet-always-forward,
900 		 * max-client-subnet-ipv4, max-client-subnet-ipv6,
901 		 * min-client-subnet-ipv4, min-client-subnet-ipv6,
902 		 * max-ecs-tree-size-ipv4, max-ecs-tree-size-ipv6, ipsecmod_hook,
903 		 * ipsecmod_whitelist. */
904 		return 0;
905 	}
906 	return 1;
907 }
908 
config_print_func(char * line,void * arg)909 void config_print_func(char* line, void* arg)
910 {
911 	FILE* f = (FILE*)arg;
912 	(void)fprintf(f, "%s\n", line);
913 }
914 
915 /** collate func arg */
916 struct config_collate_arg {
917 	/** list of result items */
918 	struct config_strlist_head list;
919 	/** if a malloc error occurred, 0 is OK */
920 	int status;
921 };
922 
config_collate_func(char * line,void * arg)923 void config_collate_func(char* line, void* arg)
924 {
925 	struct config_collate_arg* m = (struct config_collate_arg*)arg;
926 	if(m->status)
927 		return;
928 	if(!cfg_strlist_append(&m->list, strdup(line)))
929 		m->status = 1;
930 }
931 
config_get_option_list(struct config_file * cfg,const char * opt,struct config_strlist ** list)932 int config_get_option_list(struct config_file* cfg, const char* opt,
933 	struct config_strlist** list)
934 {
935 	struct config_collate_arg m;
936 	memset(&m, 0, sizeof(m));
937 	*list = NULL;
938 	if(!config_get_option(cfg, opt, config_collate_func, &m))
939 		return 1;
940 	if(m.status) {
941 		config_delstrlist(m.list.first);
942 		return 2;
943 	}
944 	*list = m.list.first;
945 	return 0;
946 }
947 
948 int
config_get_option_collate(struct config_file * cfg,const char * opt,char ** str)949 config_get_option_collate(struct config_file* cfg, const char* opt, char** str)
950 {
951 	struct config_strlist* list = NULL;
952 	int r;
953 	*str = NULL;
954 	if((r = config_get_option_list(cfg, opt, &list)) != 0)
955 		return r;
956 	*str = config_collate_cat(list);
957 	config_delstrlist(list);
958 	if(!*str) return 2;
959 	return 0;
960 }
961 
962 char*
config_collate_cat(struct config_strlist * list)963 config_collate_cat(struct config_strlist* list)
964 {
965 	size_t total = 0, left;
966 	struct config_strlist* s;
967 	char *r, *w;
968 	if(!list) /* no elements */
969 		return strdup("");
970 	if(list->next == NULL) /* one element , no newline at end. */
971 		return strdup(list->str);
972 	/* count total length */
973 	for(s=list; s; s=s->next)
974 		total += strlen(s->str) + 1; /* len + newline */
975 	left = total+1; /* one extra for nul at end */
976 	r = malloc(left);
977 	if(!r)
978 		return NULL;
979 	w = r;
980 	for(s=list; s; s=s->next) {
981 		size_t this = strlen(s->str);
982 		if(this+2 > left) { /* sanity check */
983 			free(r);
984 			return NULL;
985 		}
986 		snprintf(w, left, "%s\n", s->str);
987 		this = strlen(w);
988 		w += this;
989 		left -= this;
990 	}
991 	return r;
992 }
993 
994 /** compare and print decimal option */
995 #define O_DEC(opt, str, var) if(strcmp(opt, str)==0) \
996 	{snprintf(buf, len, "%d", (int)cfg->var); \
997 	func(buf, arg);}
998 /** compare and print unsigned option */
999 #define O_UNS(opt, str, var) if(strcmp(opt, str)==0) \
1000 	{snprintf(buf, len, "%u", (unsigned)cfg->var); \
1001 	func(buf, arg);}
1002 /** compare and print yesno option */
1003 #define O_YNO(opt, str, var) if(strcmp(opt, str)==0) \
1004 	{func(cfg->var?"yes":"no", arg);}
1005 /** compare and print string option */
1006 #define O_STR(opt, str, var) if(strcmp(opt, str)==0) \
1007 	{func(cfg->var?cfg->var:"", arg);}
1008 /** compare and print array option */
1009 #define O_IFC(opt, str, num, arr) if(strcmp(opt, str)==0) \
1010 	{int i; for(i=0; i<cfg->num; i++) func(cfg->arr[i], arg);}
1011 /** compare and print memorysize option */
1012 #define O_MEM(opt, str, var) if(strcmp(opt, str)==0) { \
1013 	if(cfg->var > 1024*1024*1024) {	\
1014 	  size_t f=cfg->var/(size_t)1000000, b=cfg->var%(size_t)1000000; \
1015 	  snprintf(buf, len, "%u%6.6u", (unsigned)f, (unsigned)b); \
1016 	} else snprintf(buf, len, "%u", (unsigned)cfg->var); \
1017 	func(buf, arg);}
1018 /** compare and print list option */
1019 #define O_LST(opt, name, lst) if(strcmp(opt, name)==0) { \
1020 	struct config_strlist* p = cfg->lst; \
1021 	for(p = cfg->lst; p; p = p->next) \
1022 		func(p->str, arg); \
1023 	}
1024 /** compare and print list option */
1025 #define O_LS2(opt, name, lst) if(strcmp(opt, name)==0) { \
1026 	struct config_str2list* p = cfg->lst; \
1027 	for(p = cfg->lst; p; p = p->next) { \
1028 		snprintf(buf, len, "%s %s", p->str, p->str2); \
1029 		func(buf, arg); \
1030 	} \
1031 	}
1032 /** compare and print list option */
1033 #define O_LS3(opt, name, lst) if(strcmp(opt, name)==0) { \
1034 	struct config_str3list* p = cfg->lst; \
1035 	for(p = cfg->lst; p; p = p->next) { \
1036 		snprintf(buf, len, "%s %s %s", p->str, p->str2, p->str3); \
1037 		func(buf, arg); \
1038 	} \
1039 	}
1040 /** compare and print taglist option */
1041 #define O_LTG(opt, name, lst) if(strcmp(opt, name)==0) { \
1042 	char* tmpstr = NULL; \
1043 	struct config_strbytelist *p = cfg->lst; \
1044 	for(p = cfg->lst; p; p = p->next) {\
1045 		tmpstr = config_taglist2str(cfg, p->str2, p->str2len); \
1046 		if(tmpstr) {\
1047 			snprintf(buf, len, "%s %s", p->str, tmpstr); \
1048 			func(buf, arg); \
1049 			free(tmpstr); \
1050 		} \
1051 	} \
1052 	}
1053 
1054 int
config_get_option(struct config_file * cfg,const char * opt,void (* func)(char *,void *),void * arg)1055 config_get_option(struct config_file* cfg, const char* opt,
1056 	void (*func)(char*,void*), void* arg)
1057 {
1058 	char buf[1024], nopt[64];
1059 	size_t len = sizeof(buf);
1060 	if(!opt) return 0;
1061 	if(opt && opt[strlen(opt)-1] == ':' && strlen(opt)<sizeof(nopt)) {
1062 		memmove(nopt, opt, strlen(opt));
1063 		nopt[strlen(opt)-1] = 0;
1064 		opt = nopt;
1065 	}
1066 	fptr_ok(fptr_whitelist_print_func(func));
1067 	O_DEC(opt, "verbosity", verbosity)
1068 	else O_DEC(opt, "statistics-interval", stat_interval)
1069 	else O_YNO(opt, "statistics-cumulative", stat_cumulative)
1070 	else O_YNO(opt, "extended-statistics", stat_extended)
1071 	else O_YNO(opt, "statistics-inhibit-zero", stat_inhibit_zero)
1072 	else O_YNO(opt, "shm-enable", shm_enable)
1073 	else O_DEC(opt, "shm-key", shm_key)
1074 	else O_YNO(opt, "use-syslog", use_syslog)
1075 	else O_STR(opt, "log-identity", log_identity)
1076 	else O_YNO(opt, "log-time-ascii", log_time_ascii)
1077 	else O_YNO(opt, "log-time-iso", log_time_iso)
1078 	else O_DEC(opt, "num-threads", num_threads)
1079 	else O_IFC(opt, "interface", num_ifs, ifs)
1080 	else O_IFC(opt, "outgoing-interface", num_out_ifs, out_ifs)
1081 	else O_YNO(opt, "interface-automatic", if_automatic)
1082 	else O_STR(opt, "interface-automatic-ports", if_automatic_ports)
1083 	else O_DEC(opt, "port", port)
1084 	else O_DEC(opt, "outgoing-range", outgoing_num_ports)
1085 	else O_DEC(opt, "outgoing-num-tcp", outgoing_num_tcp)
1086 	else O_DEC(opt, "incoming-num-tcp", incoming_num_tcp)
1087 	else O_MEM(opt, "stream-wait-size", stream_wait_size)
1088 	else O_DEC(opt, "edns-buffer-size", edns_buffer_size)
1089 	else O_DEC(opt, "msg-buffer-size", msg_buffer_size)
1090 	else O_MEM(opt, "msg-cache-size", msg_cache_size)
1091 	else O_DEC(opt, "msg-cache-slabs", msg_cache_slabs)
1092 	else O_DEC(opt, "num-queries-per-thread", num_queries_per_thread)
1093 	else O_UNS(opt, "jostle-timeout", jostle_time)
1094 	else O_MEM(opt, "so-rcvbuf", so_rcvbuf)
1095 	else O_MEM(opt, "so-sndbuf", so_sndbuf)
1096 	else O_YNO(opt, "so-reuseport", so_reuseport)
1097 	else O_YNO(opt, "ip-transparent", ip_transparent)
1098 	else O_YNO(opt, "ip-freebind", ip_freebind)
1099 	else O_DEC(opt, "ip-dscp", ip_dscp)
1100 	else O_MEM(opt, "rrset-cache-size", rrset_cache_size)
1101 	else O_DEC(opt, "rrset-cache-slabs", rrset_cache_slabs)
1102 	else O_YNO(opt, "prefetch-key", prefetch_key)
1103 	else O_YNO(opt, "prefetch", prefetch)
1104 	else O_YNO(opt, "deny-any", deny_any)
1105 	else O_DEC(opt, "cache-max-ttl", max_ttl)
1106 	else O_DEC(opt, "cache-max-negative-ttl", max_negative_ttl)
1107 	else O_DEC(opt, "cache-min-negative-ttl", min_negative_ttl)
1108 	else O_DEC(opt, "cache-min-ttl", min_ttl)
1109 	else O_DEC(opt, "infra-host-ttl", host_ttl)
1110 	else O_DEC(opt, "infra-cache-slabs", infra_cache_slabs)
1111 	else O_DEC(opt, "infra-cache-min-rtt", infra_cache_min_rtt)
1112 	else O_UNS(opt, "infra-cache-max-rtt", infra_cache_max_rtt)
1113 	else O_YNO(opt, "infra-keep-probing", infra_keep_probing)
1114 	else O_MEM(opt, "infra-cache-numhosts", infra_cache_numhosts)
1115 	else O_UNS(opt, "delay-close", delay_close)
1116 	else O_YNO(opt, "udp-connect", udp_connect)
1117 	else O_YNO(opt, "do-ip4", do_ip4)
1118 	else O_YNO(opt, "do-ip6", do_ip6)
1119 	else O_YNO(opt, "do-udp", do_udp)
1120 	else O_YNO(opt, "do-tcp", do_tcp)
1121 	else O_YNO(opt, "prefer-ip4", prefer_ip4)
1122 	else O_YNO(opt, "prefer-ip6", prefer_ip6)
1123 	else O_YNO(opt, "tcp-upstream", tcp_upstream)
1124 	else O_YNO(opt, "udp-upstream-without-downstream", udp_upstream_without_downstream)
1125 	else O_DEC(opt, "tcp-mss", tcp_mss)
1126 	else O_DEC(opt, "outgoing-tcp-mss", outgoing_tcp_mss)
1127 	else O_DEC(opt, "tcp-auth-query-timeout", tcp_auth_query_timeout)
1128 	else O_DEC(opt, "tcp-idle-timeout", tcp_idle_timeout)
1129 	else O_DEC(opt, "max-reuse-tcp-queries", max_reuse_tcp_queries)
1130 	else O_DEC(opt, "tcp-reuse-timeout", tcp_reuse_timeout)
1131 	else O_YNO(opt, "edns-tcp-keepalive", do_tcp_keepalive)
1132 	else O_DEC(opt, "edns-tcp-keepalive-timeout", tcp_keepalive_timeout)
1133 	else O_DEC(opt, "sock-queue-timeout", sock_queue_timeout)
1134 	else O_YNO(opt, "ssl-upstream", ssl_upstream)
1135 	else O_YNO(opt, "tls-upstream", ssl_upstream)
1136 	else O_STR(opt, "ssl-service-key", ssl_service_key)
1137 	else O_STR(opt, "tls-service-key", ssl_service_key)
1138 	else O_STR(opt, "ssl-service-pem", ssl_service_pem)
1139 	else O_STR(opt, "tls-service-pem", ssl_service_pem)
1140 	else O_DEC(opt, "ssl-port", ssl_port)
1141 	else O_DEC(opt, "tls-port", ssl_port)
1142 	else O_STR(opt, "ssl-cert-bundle", tls_cert_bundle)
1143 	else O_STR(opt, "tls-cert-bundle", tls_cert_bundle)
1144 	else O_YNO(opt, "tls-win-cert", tls_win_cert)
1145 	else O_YNO(opt, "tls-system-cert", tls_win_cert)
1146 	else O_LST(opt, "additional-ssl-port", tls_additional_port)
1147 	else O_LST(opt, "additional-tls-port", tls_additional_port)
1148 	else O_LST(opt, "tls-additional-ports", tls_additional_port)
1149 	else O_LST(opt, "tls-additional-port", tls_additional_port)
1150 	else O_LST(opt, "tls-session-ticket-keys", tls_session_ticket_keys.first)
1151 	else O_STR(opt, "tls-ciphers", tls_ciphers)
1152 	else O_STR(opt, "tls-ciphersuites", tls_ciphersuites)
1153 	else O_YNO(opt, "tls-use-sni", tls_use_sni)
1154 	else O_DEC(opt, "https-port", https_port)
1155 	else O_STR(opt, "http-endpoint", http_endpoint)
1156 	else O_UNS(opt, "http-max-streams", http_max_streams)
1157 	else O_MEM(opt, "http-query-buffer-size", http_query_buffer_size)
1158 	else O_MEM(opt, "http-response-buffer-size", http_response_buffer_size)
1159 	else O_YNO(opt, "http-nodelay", http_nodelay)
1160 	else O_YNO(opt, "http-notls-downstream", http_notls_downstream)
1161 	else O_DEC(opt, "quic-port", quic_port)
1162 	else O_MEM(opt, "quic-size", quic_size)
1163 	else O_YNO(opt, "use-systemd", use_systemd)
1164 	else O_YNO(opt, "do-daemonize", do_daemonize)
1165 	else O_STR(opt, "chroot", chrootdir)
1166 	else O_STR(opt, "username", username)
1167 	else O_STR(opt, "directory", directory)
1168 	else O_STR(opt, "logfile", logfile)
1169 	else O_YNO(opt, "log-queries", log_queries)
1170 	else O_YNO(opt, "log-replies", log_replies)
1171 	else O_YNO(opt, "log-tag-queryreply", log_tag_queryreply)
1172 	else O_YNO(opt, "log-local-actions", log_local_actions)
1173 	else O_YNO(opt, "log-servfail", log_servfail)
1174 	else O_YNO(opt, "log-destaddr", log_destaddr)
1175 	else O_STR(opt, "pidfile", pidfile)
1176 	else O_YNO(opt, "hide-identity", hide_identity)
1177 	else O_YNO(opt, "hide-version", hide_version)
1178 	else O_YNO(opt, "hide-trustanchor", hide_trustanchor)
1179 	else O_YNO(opt, "hide-http-user-agent", hide_http_user_agent)
1180 	else O_STR(opt, "identity", identity)
1181 	else O_STR(opt, "version", version)
1182 	else O_STR(opt, "http-user-agent", http_user_agent)
1183 	else O_STR(opt, "nsid", nsid_cfg_str)
1184 	else O_STR(opt, "target-fetch-policy", target_fetch_policy)
1185 	else O_YNO(opt, "harden-short-bufsize", harden_short_bufsize)
1186 	else O_YNO(opt, "harden-large-queries", harden_large_queries)
1187 	else O_YNO(opt, "harden-glue", harden_glue)
1188 	else O_YNO(opt, "harden-unverified-glue", harden_unverified_glue)
1189 	else O_YNO(opt, "harden-dnssec-stripped", harden_dnssec_stripped)
1190 	else O_YNO(opt, "harden-below-nxdomain", harden_below_nxdomain)
1191 	else O_YNO(opt, "harden-referral-path", harden_referral_path)
1192 	else O_YNO(opt, "harden-algo-downgrade", harden_algo_downgrade)
1193 	else O_YNO(opt, "harden-unknown-additional", harden_unknown_additional)
1194 	else O_YNO(opt, "use-caps-for-id", use_caps_bits_for_id)
1195 	else O_LST(opt, "caps-whitelist", caps_whitelist)
1196 	else O_DEC(opt, "unwanted-reply-threshold", unwanted_threshold)
1197 	else O_YNO(opt, "do-not-query-localhost", donotquery_localhost)
1198 	else O_STR(opt, "module-config", module_conf)
1199 	else O_DEC(opt, "val-bogus-ttl", bogus_ttl)
1200 	else O_YNO(opt, "val-clean-additional", val_clean_additional)
1201 	else O_DEC(opt, "val-log-level", val_log_level)
1202 	else O_YNO(opt, "val-permissive-mode", val_permissive_mode)
1203 	else O_YNO(opt, "aggressive-nsec", aggressive_nsec)
1204 	else O_YNO(opt, "ignore-cd-flag", ignore_cd)
1205 	else O_YNO(opt, "disable-edns-do", disable_edns_do)
1206 	else O_YNO(opt, "serve-expired", serve_expired)
1207 	else O_DEC(opt, "serve-expired-ttl", serve_expired_ttl)
1208 	else O_YNO(opt, "serve-expired-ttl-reset", serve_expired_ttl_reset)
1209 	else O_DEC(opt, "serve-expired-reply-ttl", serve_expired_reply_ttl)
1210 	else O_DEC(opt, "serve-expired-client-timeout", serve_expired_client_timeout)
1211 	else O_YNO(opt, "ede", ede)
1212 	else O_YNO(opt, "ede-serve-expired", ede_serve_expired)
1213 	else O_DEC(opt, "iter-scrub-ns", iter_scrub_ns)
1214 	else O_DEC(opt, "iter-scrub-cname", iter_scrub_cname)
1215 	else O_DEC(opt, "max-global-quota", max_global_quota)
1216 	else O_YNO(opt, "serve-original-ttl", serve_original_ttl)
1217 	else O_STR(opt, "val-nsec3-keysize-iterations",val_nsec3_key_iterations)
1218 	else O_YNO(opt, "zonemd-permissive-mode", zonemd_permissive_mode)
1219 	else O_UNS(opt, "add-holddown", add_holddown)
1220 	else O_UNS(opt, "del-holddown", del_holddown)
1221 	else O_UNS(opt, "keep-missing", keep_missing)
1222 	else O_YNO(opt, "permit-small-holddown", permit_small_holddown)
1223 	else O_MEM(opt, "key-cache-size", key_cache_size)
1224 	else O_DEC(opt, "key-cache-slabs", key_cache_slabs)
1225 	else O_MEM(opt, "neg-cache-size", neg_cache_size)
1226 	else O_YNO(opt, "control-enable", remote_control_enable)
1227 	else O_DEC(opt, "control-port", control_port)
1228 	else O_STR(opt, "server-key-file", server_key_file)
1229 	else O_STR(opt, "server-cert-file", server_cert_file)
1230 	else O_STR(opt, "control-key-file", control_key_file)
1231 	else O_STR(opt, "control-cert-file", control_cert_file)
1232 	else O_LST(opt, "root-hints", root_hints)
1233 	else O_LS2(opt, "access-control", acls)
1234 	else O_LS2(opt, "tcp-connection-limit", tcp_connection_limits)
1235 	else O_LST(opt, "do-not-query-address", donotqueryaddrs)
1236 	else O_LST(opt, "private-address", private_address)
1237 	else O_LST(opt, "private-domain", private_domain)
1238 	else O_LST(opt, "auto-trust-anchor-file", auto_trust_anchor_file_list)
1239 	else O_LST(opt, "trust-anchor-file", trust_anchor_file_list)
1240 	else O_LST(opt, "trust-anchor", trust_anchor_list)
1241 	else O_LST(opt, "trusted-keys-file", trusted_keys_file_list)
1242 	else O_YNO(opt, "trust-anchor-signaling", trust_anchor_signaling)
1243 	else O_YNO(opt, "root-key-sentinel", root_key_sentinel)
1244 	else O_LST(opt, "control-interface", control_ifs.first)
1245 	else O_LST(opt, "domain-insecure", domain_insecure)
1246 	else O_UNS(opt, "val-override-date", val_date_override)
1247 	else O_YNO(opt, "minimal-responses", minimal_responses)
1248 	else O_YNO(opt, "rrset-roundrobin", rrset_roundrobin)
1249 	else O_DEC(opt, "unknown-server-time-limit", unknown_server_time_limit)
1250 	else O_DEC(opt, "discard-timeout", discard_timeout)
1251 	else O_DEC(opt, "wait-limit", wait_limit)
1252 	else O_DEC(opt, "wait-limit-cookie", wait_limit_cookie)
1253 	else O_LS2(opt, "wait-limit-netblock", wait_limit_netblock)
1254 	else O_LS2(opt, "wait-limit-cookie-netblock", wait_limit_cookie_netblock)
1255 #ifdef CLIENT_SUBNET
1256 	else O_LST(opt, "send-client-subnet", client_subnet)
1257 	else O_LST(opt, "client-subnet-zone", client_subnet_zone)
1258 	else O_DEC(opt, "max-client-subnet-ipv4", max_client_subnet_ipv4)
1259 	else O_DEC(opt, "max-client-subnet-ipv6", max_client_subnet_ipv6)
1260 	else O_DEC(opt, "min-client-subnet-ipv4", min_client_subnet_ipv4)
1261 	else O_DEC(opt, "min-client-subnet-ipv6", min_client_subnet_ipv6)
1262 	else O_DEC(opt, "max-ecs-tree-size-ipv4", max_ecs_tree_size_ipv4)
1263 	else O_DEC(opt, "max-ecs-tree-size-ipv6", max_ecs_tree_size_ipv6)
1264 	else O_YNO(opt, "client-subnet-always-forward:",
1265 		client_subnet_always_forward)
1266 #endif
1267 #ifdef USE_DNSTAP
1268 	else O_YNO(opt, "dnstap-enable", dnstap)
1269 	else O_YNO(opt, "dnstap-bidirectional", dnstap_bidirectional)
1270 	else O_STR(opt, "dnstap-socket-path", dnstap_socket_path)
1271 	else O_STR(opt, "dnstap-ip", dnstap_ip)
1272 	else O_YNO(opt, "dnstap-tls", dnstap_tls)
1273 	else O_STR(opt, "dnstap-tls-server-name", dnstap_tls_server_name)
1274 	else O_STR(opt, "dnstap-tls-cert-bundle", dnstap_tls_cert_bundle)
1275 	else O_STR(opt, "dnstap-tls-client-key-file",
1276 		dnstap_tls_client_key_file)
1277 	else O_STR(opt, "dnstap-tls-client-cert-file",
1278 		dnstap_tls_client_cert_file)
1279 	else O_YNO(opt, "dnstap-send-identity", dnstap_send_identity)
1280 	else O_YNO(opt, "dnstap-send-version", dnstap_send_version)
1281 	else O_STR(opt, "dnstap-identity", dnstap_identity)
1282 	else O_STR(opt, "dnstap-version", dnstap_version)
1283 	else O_UNS(opt, "dnstap-sample-rate", dnstap_sample_rate)
1284 	else O_YNO(opt, "dnstap-log-resolver-query-messages",
1285 		dnstap_log_resolver_query_messages)
1286 	else O_YNO(opt, "dnstap-log-resolver-response-messages",
1287 		dnstap_log_resolver_response_messages)
1288 	else O_YNO(opt, "dnstap-log-client-query-messages",
1289 		dnstap_log_client_query_messages)
1290 	else O_YNO(opt, "dnstap-log-client-response-messages",
1291 		dnstap_log_client_response_messages)
1292 	else O_YNO(opt, "dnstap-log-forwarder-query-messages",
1293 		dnstap_log_forwarder_query_messages)
1294 	else O_YNO(opt, "dnstap-log-forwarder-response-messages",
1295 		dnstap_log_forwarder_response_messages)
1296 #endif
1297 #ifdef USE_DNSCRYPT
1298 	else O_YNO(opt, "dnscrypt-enable", dnscrypt)
1299 	else O_DEC(opt, "dnscrypt-port", dnscrypt_port)
1300 	else O_STR(opt, "dnscrypt-provider", dnscrypt_provider)
1301 	else O_LST(opt, "dnscrypt-provider-cert", dnscrypt_provider_cert)
1302 	else O_LST(opt, "dnscrypt-provider-cert-rotated", dnscrypt_provider_cert_rotated)
1303 	else O_LST(opt, "dnscrypt-secret-key", dnscrypt_secret_key)
1304 	else O_MEM(opt, "dnscrypt-shared-secret-cache-size",
1305 		dnscrypt_shared_secret_cache_size)
1306 	else O_DEC(opt, "dnscrypt-shared-secret-cache-slabs",
1307 		dnscrypt_shared_secret_cache_slabs)
1308 	else O_MEM(opt, "dnscrypt-nonce-cache-size",
1309 		dnscrypt_nonce_cache_size)
1310 	else O_DEC(opt, "dnscrypt-nonce-cache-slabs",
1311 		dnscrypt_nonce_cache_slabs)
1312 #endif
1313 	else O_YNO(opt, "unblock-lan-zones", unblock_lan_zones)
1314 	else O_YNO(opt, "insecure-lan-zones", insecure_lan_zones)
1315 	else O_DEC(opt, "max-udp-size", max_udp_size)
1316 	else O_LST(opt, "python-script", python_script)
1317 	else O_LST(opt, "dynlib-file", dynlib_file)
1318 	else O_YNO(opt, "disable-dnssec-lame-check", disable_dnssec_lame_check)
1319 	else O_DEC(opt, "ip-ratelimit-cookie", ip_ratelimit_cookie)
1320 	else O_DEC(opt, "ip-ratelimit", ip_ratelimit)
1321 	else O_DEC(opt, "ratelimit", ratelimit)
1322 	else O_MEM(opt, "ip-ratelimit-size", ip_ratelimit_size)
1323 	else O_MEM(opt, "ratelimit-size", ratelimit_size)
1324 	else O_DEC(opt, "ip-ratelimit-slabs", ip_ratelimit_slabs)
1325 	else O_DEC(opt, "ratelimit-slabs", ratelimit_slabs)
1326 	else O_LS2(opt, "ratelimit-for-domain", ratelimit_for_domain)
1327 	else O_LS2(opt, "ratelimit-below-domain", ratelimit_below_domain)
1328 	else O_DEC(opt, "ip-ratelimit-factor", ip_ratelimit_factor)
1329 	else O_DEC(opt, "ratelimit-factor", ratelimit_factor)
1330 	else O_YNO(opt, "ip-ratelimit-backoff", ip_ratelimit_backoff)
1331 	else O_YNO(opt, "ratelimit-backoff", ratelimit_backoff)
1332 	else O_UNS(opt, "outbound-msg-retry", outbound_msg_retry)
1333 	else O_UNS(opt, "max-sent-count", max_sent_count)
1334 	else O_UNS(opt, "max-query-restarts", max_query_restarts)
1335 	else O_DEC(opt, "fast-server-num", fast_server_num)
1336 	else O_DEC(opt, "fast-server-permil", fast_server_permil)
1337 	else O_DEC(opt, "val-sig-skew-min", val_sig_skew_min)
1338 	else O_DEC(opt, "val-sig-skew-max", val_sig_skew_max)
1339 	else O_DEC(opt, "val-max-restart", val_max_restart)
1340 	else O_YNO(opt, "qname-minimisation", qname_minimisation)
1341 	else O_YNO(opt, "qname-minimisation-strict", qname_minimisation_strict)
1342 	else O_IFC(opt, "define-tag", num_tags, tagname)
1343 	else O_LTG(opt, "local-zone-tag", local_zone_tags)
1344 	else O_LTG(opt, "access-control-tag", acl_tags)
1345 	else O_LTG(opt, "response-ip-tag", respip_tags)
1346 	else O_LS3(opt, "local-zone-override", local_zone_overrides)
1347 	else O_LS3(opt, "access-control-tag-action", acl_tag_actions)
1348 	else O_LS3(opt, "access-control-tag-data", acl_tag_datas)
1349 	else O_LS2(opt, "access-control-view", acl_view)
1350 	else O_LS2(opt, "interface-action", interface_actions)
1351 	else O_LTG(opt, "interface-tag", interface_tags)
1352 	else O_LS3(opt, "interface-tag-action", interface_tag_actions)
1353 	else O_LS3(opt, "interface-tag-data", interface_tag_datas)
1354 	else O_LS2(opt, "interface-view", interface_view)
1355 	else O_YNO(opt, "pad-responses", pad_responses)
1356 	else O_DEC(opt, "pad-responses-block-size", pad_responses_block_size)
1357 	else O_YNO(opt, "pad-queries", pad_queries)
1358 	else O_DEC(opt, "pad-queries-block-size", pad_queries_block_size)
1359 	else O_LS2(opt, "edns-client-strings", edns_client_strings)
1360 	else O_LST(opt, "proxy-protocol-port", proxy_protocol_port)
1361 #ifdef USE_IPSECMOD
1362 	else O_YNO(opt, "ipsecmod-enabled", ipsecmod_enabled)
1363 	else O_YNO(opt, "ipsecmod-ignore-bogus", ipsecmod_ignore_bogus)
1364 	else O_STR(opt, "ipsecmod-hook", ipsecmod_hook)
1365 	else O_DEC(opt, "ipsecmod-max-ttl", ipsecmod_max_ttl)
1366 	else O_LST(opt, "ipsecmod-whitelist", ipsecmod_whitelist)
1367 	else O_YNO(opt, "ipsecmod-strict", ipsecmod_strict)
1368 #endif
1369 	else O_YNO(opt, "answer-cookie", do_answer_cookie)
1370 	else O_STR(opt, "cookie-secret-file", cookie_secret_file)
1371 #ifdef USE_CACHEDB
1372 	else O_STR(opt, "backend", cachedb_backend)
1373 	else O_STR(opt, "secret-seed", cachedb_secret)
1374 	else O_YNO(opt, "cachedb-no-store", cachedb_no_store)
1375 	else O_YNO(opt, "cachedb-check-when-serve-expired", cachedb_check_when_serve_expired)
1376 #ifdef USE_REDIS
1377 	else O_STR(opt, "redis-server-host", redis_server_host)
1378 	else O_DEC(opt, "redis-server-port", redis_server_port)
1379 	else O_STR(opt, "redis-server-path", redis_server_path)
1380 	else O_STR(opt, "redis-server-password", redis_server_password)
1381 	else O_DEC(opt, "redis-timeout", redis_timeout)
1382 	else O_DEC(opt, "redis-command-timeout", redis_command_timeout)
1383 	else O_DEC(opt, "redis-connect-timeout", redis_connect_timeout)
1384 	else O_YNO(opt, "redis-expire-records", redis_expire_records)
1385 	else O_DEC(opt, "redis-logical-db", redis_logical_db)
1386 #endif  /* USE_REDIS */
1387 #endif  /* USE_CACHEDB */
1388 #ifdef USE_IPSET
1389 	else O_STR(opt, "name-v4", ipset_name_v4)
1390 	else O_STR(opt, "name-v6", ipset_name_v6)
1391 #endif
1392 	/* not here:
1393 	 * outgoing-permit, outgoing-avoid - have list of ports
1394 	 * local-zone - zones and nodefault variables
1395 	 * local-data - see below
1396 	 * local-data-ptr - converted to local-data entries
1397 	 * stub-zone, name, stub-addr, stub-host, stub-prime
1398 	 * forward-zone, name, forward-addr, forward-host
1399 	 */
1400 	else return 0;
1401 	return 1;
1402 }
1403 
1404 /** initialize the global cfg_parser object */
1405 static void
create_cfg_parser(struct config_file * cfg,char * filename,const char * chroot)1406 create_cfg_parser(struct config_file* cfg, char* filename, const char* chroot)
1407 {
1408 	static struct config_parser_state st;
1409 	cfg_parser = &st;
1410 	cfg_parser->filename = filename;
1411 	cfg_parser->line = 1;
1412 	cfg_parser->errors = 0;
1413 	cfg_parser->cfg = cfg;
1414 	cfg_parser->chroot = chroot;
1415 	cfg_parser->started_toplevel = 0;
1416 	init_cfg_parse();
1417 }
1418 
1419 int
config_read(struct config_file * cfg,const char * filename,const char * chroot)1420 config_read(struct config_file* cfg, const char* filename, const char* chroot)
1421 {
1422 	FILE *in;
1423 	char *fname = (char*)filename;
1424 #ifdef HAVE_GLOB
1425 	glob_t g;
1426 	size_t i;
1427 	int r, flags;
1428 #endif
1429 	if(!fname)
1430 		return 1;
1431 
1432 	/* check for wildcards */
1433 #ifdef HAVE_GLOB
1434 	if(!(!strchr(fname, '*') && !strchr(fname, '?') && !strchr(fname, '[') &&
1435 		!strchr(fname, '{') && !strchr(fname, '~'))) {
1436 		verbose(VERB_QUERY, "wildcard found, processing %s", fname);
1437 		flags = 0
1438 #ifdef GLOB_ERR
1439 			| GLOB_ERR
1440 #endif
1441 #ifdef GLOB_NOSORT
1442 			| GLOB_NOSORT
1443 #endif
1444 #ifdef GLOB_BRACE
1445 			| GLOB_BRACE
1446 #endif
1447 #ifdef GLOB_TILDE
1448 			| GLOB_TILDE
1449 #endif
1450 		;
1451 		memset(&g, 0, sizeof(g));
1452 		r = glob(fname, flags, NULL, &g);
1453 		if(r) {
1454 			/* some error */
1455 			globfree(&g);
1456 			if(r == GLOB_NOMATCH) {
1457 				verbose(VERB_QUERY, "include: "
1458 				"no matches for %s", fname);
1459 				return 1;
1460 			} else if(r == GLOB_NOSPACE) {
1461 				log_err("include: %s: "
1462 					"fnametern out of memory", fname);
1463 			} else if(r == GLOB_ABORTED) {
1464 				log_err("wildcard include: %s: expansion "
1465 					"aborted (%s)", fname, strerror(errno));
1466 			} else {
1467 				log_err("wildcard include: %s: expansion "
1468 					"failed (%s)", fname, strerror(errno));
1469 			}
1470 			/* ignore globs that yield no files */
1471 			return 1;
1472 		}
1473 		/* process files found, if any */
1474 		for(i=0; i<(size_t)g.gl_pathc; i++) {
1475 			if(!config_read(cfg, g.gl_pathv[i], chroot)) {
1476 				log_err("error reading wildcard "
1477 					"include: %s", g.gl_pathv[i]);
1478 				globfree(&g);
1479 				return 0;
1480 			}
1481 		}
1482 		globfree(&g);
1483 		return 1;
1484 	}
1485 #endif /* HAVE_GLOB */
1486 
1487 	in = fopen(fname, "r");
1488 	if(!in) {
1489 		log_err("Could not open %s: %s", fname, strerror(errno));
1490 		return 0;
1491 	}
1492 	create_cfg_parser(cfg, fname, chroot);
1493 	ub_c_in = in;
1494 	ub_c_parse();
1495 	fclose(in);
1496 
1497 	if(!cfg->dnscrypt) cfg->dnscrypt_port = 0;
1498 
1499 	if(cfg_parser->errors != 0) {
1500 		fprintf(stderr, "read %s failed: %d errors in configuration file\n",
1501 			fname, cfg_parser->errors);
1502 		errno=EINVAL;
1503 		return 0;
1504 	}
1505 
1506 	return 1;
1507 }
1508 
cfg_stub_find(struct config_stub *** pp,const char * nm)1509 struct config_stub* cfg_stub_find(struct config_stub*** pp, const char* nm)
1510 {
1511 	struct config_stub* p = *(*pp);
1512 	while(p) {
1513 		if(strcmp(p->name, nm) == 0)
1514 			return p;
1515 		(*pp) = &p->next;
1516 		p = p->next;
1517 	}
1518 	return NULL;
1519 }
1520 
1521 void
config_delstrlist(struct config_strlist * p)1522 config_delstrlist(struct config_strlist* p)
1523 {
1524 	struct config_strlist *np;
1525 	while(p) {
1526 		np = p->next;
1527 		free(p->str);
1528 		free(p);
1529 		p = np;
1530 	}
1531 }
1532 
1533 void
config_deldblstrlist(struct config_str2list * p)1534 config_deldblstrlist(struct config_str2list* p)
1535 {
1536 	struct config_str2list *np;
1537 	while(p) {
1538 		np = p->next;
1539 		free(p->str);
1540 		free(p->str2);
1541 		free(p);
1542 		p = np;
1543 	}
1544 }
1545 
1546 void
config_deltrplstrlist(struct config_str3list * p)1547 config_deltrplstrlist(struct config_str3list* p)
1548 {
1549 	struct config_str3list *np;
1550 	while(p) {
1551 		np = p->next;
1552 		free(p->str);
1553 		free(p->str2);
1554 		free(p->str3);
1555 		free(p);
1556 		p = np;
1557 	}
1558 }
1559 
1560 void
config_delauth(struct config_auth * p)1561 config_delauth(struct config_auth* p)
1562 {
1563 	if(!p) return;
1564 	free(p->name);
1565 	config_delstrlist(p->masters);
1566 	config_delstrlist(p->urls);
1567 	config_delstrlist(p->allow_notify);
1568 	free(p->zonefile);
1569 	free(p->rpz_taglist);
1570 	free(p->rpz_action_override);
1571 	free(p->rpz_cname);
1572 	free(p->rpz_log_name);
1573 	free(p);
1574 }
1575 
1576 void
config_delauths(struct config_auth * p)1577 config_delauths(struct config_auth* p)
1578 {
1579 	struct config_auth* np;
1580 	while(p) {
1581 		np = p->next;
1582 		config_delauth(p);
1583 		p = np;
1584 	}
1585 }
1586 
1587 void
config_delstub(struct config_stub * p)1588 config_delstub(struct config_stub* p)
1589 {
1590 	if(!p) return;
1591 	free(p->name);
1592 	config_delstrlist(p->hosts);
1593 	config_delstrlist(p->addrs);
1594 	free(p);
1595 }
1596 
1597 void
config_delstubs(struct config_stub * p)1598 config_delstubs(struct config_stub* p)
1599 {
1600 	struct config_stub* np;
1601 	while(p) {
1602 		np = p->next;
1603 		config_delstub(p);
1604 		p = np;
1605 	}
1606 }
1607 
1608 void
config_delview(struct config_view * p)1609 config_delview(struct config_view* p)
1610 {
1611 	if(!p) return;
1612 	free(p->name);
1613 	config_deldblstrlist(p->local_zones);
1614 	config_delstrlist(p->local_zones_nodefault);
1615 #ifdef USE_IPSET
1616 	config_delstrlist(p->local_zones_ipset);
1617 #endif
1618 	config_delstrlist(p->local_data);
1619 	free(p);
1620 }
1621 
1622 void
config_delviews(struct config_view * p)1623 config_delviews(struct config_view* p)
1624 {
1625 	struct config_view* np;
1626 	while(p) {
1627 		np = p->next;
1628 		config_delview(p);
1629 		p = np;
1630 	}
1631 }
1632 
1633 void
config_del_strarray(char ** array,int num)1634 config_del_strarray(char** array, int num)
1635 {
1636 	int i;
1637 	if(!array)
1638 		return;
1639 	for(i=0; i<num; i++) {
1640 		free(array[i]);
1641 	}
1642 	free(array);
1643 }
1644 
1645 void
config_del_strbytelist(struct config_strbytelist * p)1646 config_del_strbytelist(struct config_strbytelist* p)
1647 {
1648 	struct config_strbytelist* np;
1649 	while(p) {
1650 		np = p->next;
1651 		free(p->str);
1652 		free(p->str2);
1653 		free(p);
1654 		p = np;
1655 	}
1656 }
1657 
1658 void
config_delete(struct config_file * cfg)1659 config_delete(struct config_file* cfg)
1660 {
1661 	if(!cfg) return;
1662 	free(cfg->username);
1663 	free(cfg->chrootdir);
1664 	free(cfg->directory);
1665 	free(cfg->logfile);
1666 	free(cfg->pidfile);
1667 	free(cfg->if_automatic_ports);
1668 	free(cfg->target_fetch_policy);
1669 	free(cfg->ssl_service_key);
1670 	free(cfg->ssl_service_pem);
1671 	free(cfg->tls_cert_bundle);
1672 	config_delstrlist(cfg->tls_additional_port);
1673 	config_delstrlist(cfg->tls_session_ticket_keys.first);
1674 	free(cfg->tls_ciphers);
1675 	free(cfg->tls_ciphersuites);
1676 	free(cfg->http_endpoint);
1677 	if(cfg->log_identity) {
1678 		log_ident_revert_to_default();
1679 		free(cfg->log_identity);
1680 	}
1681 	config_del_strarray(cfg->ifs, cfg->num_ifs);
1682 	config_del_strarray(cfg->out_ifs, cfg->num_out_ifs);
1683 	config_delstubs(cfg->stubs);
1684 	config_delstubs(cfg->forwards);
1685 	config_delauths(cfg->auths);
1686 	config_delviews(cfg->views);
1687 	config_delstrlist(cfg->donotqueryaddrs);
1688 	config_delstrlist(cfg->root_hints);
1689 #ifdef CLIENT_SUBNET
1690 	config_delstrlist(cfg->client_subnet);
1691 	config_delstrlist(cfg->client_subnet_zone);
1692 #endif
1693 	free(cfg->identity);
1694 	free(cfg->version);
1695 	free(cfg->http_user_agent);
1696 	free(cfg->nsid_cfg_str);
1697 	free(cfg->nsid);
1698 	free(cfg->module_conf);
1699 	free(cfg->outgoing_avail_ports);
1700 	config_delstrlist(cfg->caps_whitelist);
1701 	config_delstrlist(cfg->private_address);
1702 	config_delstrlist(cfg->private_domain);
1703 	config_delstrlist(cfg->auto_trust_anchor_file_list);
1704 	config_delstrlist(cfg->trust_anchor_file_list);
1705 	config_delstrlist(cfg->trusted_keys_file_list);
1706 	config_delstrlist(cfg->trust_anchor_list);
1707 	config_delstrlist(cfg->domain_insecure);
1708 	config_deldblstrlist(cfg->acls);
1709 	config_deldblstrlist(cfg->tcp_connection_limits);
1710 	free(cfg->val_nsec3_key_iterations);
1711 	config_deldblstrlist(cfg->local_zones);
1712 	config_delstrlist(cfg->local_zones_nodefault);
1713 #ifdef USE_IPSET
1714 	config_delstrlist(cfg->local_zones_ipset);
1715 #endif
1716 	config_delstrlist(cfg->local_data);
1717 	config_deltrplstrlist(cfg->local_zone_overrides);
1718 	config_del_strarray(cfg->tagname, cfg->num_tags);
1719 	config_del_strbytelist(cfg->local_zone_tags);
1720 	config_del_strbytelist(cfg->respip_tags);
1721 	config_deldblstrlist(cfg->acl_view);
1722 	config_del_strbytelist(cfg->acl_tags);
1723 	config_deltrplstrlist(cfg->acl_tag_actions);
1724 	config_deltrplstrlist(cfg->acl_tag_datas);
1725 	config_deldblstrlist(cfg->interface_actions);
1726 	config_deldblstrlist(cfg->interface_view);
1727 	config_del_strbytelist(cfg->interface_tags);
1728 	config_deltrplstrlist(cfg->interface_tag_actions);
1729 	config_deltrplstrlist(cfg->interface_tag_datas);
1730 	config_delstrlist(cfg->control_ifs.first);
1731 	config_deldblstrlist(cfg->wait_limit_netblock);
1732 	config_deldblstrlist(cfg->wait_limit_cookie_netblock);
1733 	free(cfg->server_key_file);
1734 	free(cfg->server_cert_file);
1735 	free(cfg->control_key_file);
1736 	free(cfg->control_cert_file);
1737 	free(cfg->nat64_prefix);
1738 	free(cfg->dns64_prefix);
1739 	config_delstrlist(cfg->dns64_ignore_aaaa);
1740 	free(cfg->dnstap_socket_path);
1741 	free(cfg->dnstap_ip);
1742 	free(cfg->dnstap_tls_server_name);
1743 	free(cfg->dnstap_tls_cert_bundle);
1744 	free(cfg->dnstap_tls_client_key_file);
1745 	free(cfg->dnstap_tls_client_cert_file);
1746 	free(cfg->dnstap_identity);
1747 	free(cfg->dnstap_version);
1748 	config_deldblstrlist(cfg->ratelimit_for_domain);
1749 	config_deldblstrlist(cfg->ratelimit_below_domain);
1750 	config_delstrlist(cfg->python_script);
1751 	config_delstrlist(cfg->dynlib_file);
1752 	config_deldblstrlist(cfg->edns_client_strings);
1753 	config_delstrlist(cfg->proxy_protocol_port);
1754 #ifdef USE_IPSECMOD
1755 	free(cfg->ipsecmod_hook);
1756 	config_delstrlist(cfg->ipsecmod_whitelist);
1757 #endif
1758 	free(cfg->cookie_secret_file);
1759 #ifdef USE_CACHEDB
1760 	free(cfg->cachedb_backend);
1761 	free(cfg->cachedb_secret);
1762 #ifdef USE_REDIS
1763 	free(cfg->redis_server_host);
1764 	free(cfg->redis_server_path);
1765 	free(cfg->redis_server_password);
1766 #endif  /* USE_REDIS */
1767 #endif  /* USE_CACHEDB */
1768 #ifdef USE_IPSET
1769 	free(cfg->ipset_name_v4);
1770 	free(cfg->ipset_name_v6);
1771 #endif
1772 	free(cfg);
1773 }
1774 
1775 static void
init_cookie_secret(uint8_t * cookie_secret,size_t cookie_secret_len)1776 init_cookie_secret(uint8_t* cookie_secret, size_t cookie_secret_len)
1777 {
1778 	struct ub_randstate *rand = ub_initstate(NULL);
1779 
1780 	if (!rand)
1781 		fatal_exit("could not init random generator");
1782 	while (cookie_secret_len) {
1783 		*cookie_secret++ = (uint8_t)ub_random(rand);
1784 		cookie_secret_len--;
1785 	}
1786 	ub_randfree(rand);
1787 }
1788 
1789 static void
init_outgoing_availports(int * a,int num)1790 init_outgoing_availports(int* a, int num)
1791 {
1792 	/* generated with make iana_update */
1793 	const int iana_assigned[] = {
1794 #include "util/iana_ports.inc"
1795 		-1 }; /* end marker to put behind trailing comma */
1796 
1797 	int i;
1798 	/* do not use <1024, that could be trouble with the system, privs */
1799 	for(i=1024; i<num; i++) {
1800 		a[i] = i;
1801 	}
1802 	/* create empty spot at 49152 to keep ephemeral ports available
1803 	 * to other programs */
1804 	for(i=49152; i<49152+256; i++)
1805 		a[i] = 0;
1806 	/* pick out all the IANA assigned ports */
1807 	for(i=0; iana_assigned[i]!=-1; i++) {
1808 		if(iana_assigned[i] < num)
1809 			a[iana_assigned[i]] = 0;
1810 	}
1811 }
1812 
1813 static int
extract_port_from_str(const char * str,int max_port)1814 extract_port_from_str(const char* str, int max_port) {
1815 	char* endptr;
1816 	long int value;
1817 	if (str == NULL || *str == '\0') {
1818 		log_err("str: '%s' is invalid", (str?str:"NULL"));
1819 		return -1;
1820 	}
1821 
1822 	value = strtol(str, &endptr, 10);
1823 	if ((endptr == str) || (*endptr != '\0'))  {
1824 		log_err("cannot parse port number '%s'", str);
1825 		return -1;
1826 	}
1827 
1828 	if (errno == ERANGE) {
1829                 log_err("overflow occurred when parsing '%s'", str);
1830 		return -1;
1831 	}
1832 
1833 	if (value == 0 && strcmp(str, "0") != 0) {
1834 		log_err("cannot parse port number '%s'", str);
1835 		return -1;
1836 	}
1837 
1838 	if (value < 0 || value >= max_port) {
1839 		log_err(" '%s' is out of bounds [0, %d)", str, max_port);
1840 		return -1;
1841 	}
1842 
1843 	return (int)value;
1844 }
1845 
1846 int
cfg_mark_ports(const char * str,int allow,int * avail,int num)1847 cfg_mark_ports(const char* str, int allow, int* avail, int num)
1848 {
1849 	char* mid = strchr(str, '-');
1850 #ifdef DISABLE_EXPLICIT_PORT_RANDOMISATION
1851 	log_warn("Explicit port randomisation disabled, ignoring "
1852 		"outgoing-port-permit and outgoing-port-avoid configuration "
1853 		"options");
1854 #endif
1855 	if(!mid) {
1856 		int port = extract_port_from_str(str, num);
1857 		if (port < 0) {
1858 			log_err("Failed to parse the port number");
1859 			return 0;
1860 		}
1861 		if(port < num)
1862 			avail[port] = (allow?port:0);
1863 	} else {
1864 		char buf[16];
1865 		int i, low;
1866 		int high = extract_port_from_str(mid+1, num);
1867 		if (high < 0) {
1868 			log_err("Failed to parse the port number");
1869 			return 0;
1870 		}
1871 
1872 		if( (int)(mid-str)+1 >= (int)sizeof(buf) ) {
1873 			log_err("cannot parse port number '%s'", str);
1874 			return 0;
1875 		}
1876 
1877 		if(mid > str)
1878 			memcpy(buf, str, (size_t)(mid-str));
1879 		buf[mid-str] = 0;
1880 		low = extract_port_from_str(buf, num);
1881 		if (low < 0) {
1882 			log_err("Failed to parse the port number");
1883 			return 0;
1884 		}
1885 
1886 		if (low > high) {
1887 			log_err("Low value is greater than high value");
1888 			return 0;
1889 		}
1890 
1891 		for(i=low; i<=high; i++) {
1892 			if(i < num)
1893 				avail[i] = (allow?i:0);
1894 		}
1895 	}
1896 	return 1;
1897 }
1898 
1899 int
cfg_scan_ports(int * avail,int num)1900 cfg_scan_ports(int* avail, int num)
1901 {
1902 	int i;
1903 	int count = 0;
1904 	for(i=0; i<num; i++) {
1905 		if(avail[i])
1906 			count++;
1907 	}
1908 	return count;
1909 }
1910 
cfg_condense_ports(struct config_file * cfg,int ** avail)1911 int cfg_condense_ports(struct config_file* cfg, int** avail)
1912 {
1913 	int num = cfg_scan_ports(cfg->outgoing_avail_ports, 65536);
1914 	int i, at = 0;
1915 	*avail = NULL;
1916 	if(num == 0)
1917 		return 0;
1918 	*avail = (int*)reallocarray(NULL, (size_t)num, sizeof(int));
1919 	if(!*avail)
1920 		return 0;
1921 	for(i=0; i<65536; i++) {
1922 		if(cfg->outgoing_avail_ports[i])
1923 			(*avail)[at++] = cfg->outgoing_avail_ports[i];
1924 	}
1925 	log_assert(at == num);
1926 	return num;
1927 }
1928 
cfg_apply_local_port_policy(struct config_file * cfg,int num)1929 void cfg_apply_local_port_policy(struct config_file* cfg, int num) {
1930 (void)cfg;
1931 (void)num;
1932 #ifdef USE_LINUX_IP_LOCAL_PORT_RANGE
1933 	{
1934 		int i = 0;
1935 		FILE* range_fd;
1936 		if ((range_fd = fopen(LINUX_IP_LOCAL_PORT_RANGE_PATH, "r")) != NULL) {
1937 			int min_port = 0;
1938 			int max_port = num - 1;
1939 			if (fscanf(range_fd, "%d %d", &min_port, &max_port) == 2) {
1940 				for(i=0; i<min_port; i++) {
1941 					cfg->outgoing_avail_ports[i] = 0;
1942 				}
1943 				for(i=max_port+1; i<num; i++) {
1944 					cfg->outgoing_avail_ports[i] = 0;
1945 				}
1946 			} else {
1947 				log_err("unexpected port range in %s",
1948 						LINUX_IP_LOCAL_PORT_RANGE_PATH);
1949 			}
1950 			fclose(range_fd);
1951 		} else {
1952 			log_err("failed to read from file: %s (%s)",
1953 					LINUX_IP_LOCAL_PORT_RANGE_PATH,
1954 					strerror(errno));
1955 		}
1956 	}
1957 #endif
1958 }
1959 
1960 /** print error with file and line number */
ub_c_error_va_list(const char * fmt,va_list args)1961 static void ub_c_error_va_list(const char *fmt, va_list args)
1962 {
1963 	cfg_parser->errors++;
1964 	fprintf(stderr, "%s:%d: error: ", cfg_parser->filename,
1965 	cfg_parser->line);
1966 	vfprintf(stderr, fmt, args);
1967 	fprintf(stderr, "\n");
1968 }
1969 
1970 /** print error with file and line number */
ub_c_error_msg(const char * fmt,...)1971 void ub_c_error_msg(const char* fmt, ...)
1972 {
1973 	va_list args;
1974 	va_start(args, fmt);
1975 	ub_c_error_va_list(fmt, args);
1976 	va_end(args);
1977 }
1978 
ub_c_error(const char * str)1979 void ub_c_error(const char *str)
1980 {
1981 	cfg_parser->errors++;
1982 	if(strcmp(str, "syntax error")==0 && cfg_parser->started_toplevel ==0)
1983 		str = "syntax error, is there no section start after an "
1984 			"include-toplevel directive perhaps.";
1985 	fprintf(stderr, "%s:%d: error: %s\n", cfg_parser->filename,
1986 		cfg_parser->line, str);
1987 }
1988 
ub_c_wrap(void)1989 int ub_c_wrap(void)
1990 {
1991 	return 1;
1992 }
1993 
cfg_strlist_append(struct config_strlist_head * list,char * item)1994 int cfg_strlist_append(struct config_strlist_head* list, char* item)
1995 {
1996 	struct config_strlist *s;
1997 	if(!item || !list) {
1998 		free(item);
1999 		return 0;
2000 	}
2001 	s = (struct config_strlist*)calloc(1, sizeof(struct config_strlist));
2002 	if(!s) {
2003 		free(item);
2004 		return 0;
2005 	}
2006 	s->str = item;
2007 	s->next = NULL;
2008 	if(list->last)
2009 		list->last->next = s;
2010 	else
2011 		list->first = s;
2012 	list->last = s;
2013 	return 1;
2014 }
2015 
2016 int
cfg_region_strlist_insert(struct regional * region,struct config_strlist ** head,char * item)2017 cfg_region_strlist_insert(struct regional* region,
2018 	struct config_strlist** head, char* item)
2019 {
2020 	struct config_strlist *s;
2021 	if(!item || !head)
2022 		return 0;
2023 	s = (struct config_strlist*)regional_alloc_zero(region,
2024 		sizeof(struct config_strlist));
2025 	if(!s)
2026 		return 0;
2027 	s->str = item;
2028 	s->next = *head;
2029 	*head = s;
2030 	return 1;
2031 }
2032 
2033 struct config_strlist*
cfg_strlist_find(struct config_strlist * head,const char * item)2034 cfg_strlist_find(struct config_strlist* head, const char *item)
2035 {
2036 	struct config_strlist *s = head;
2037 	if(!head){
2038 		return NULL;
2039 	}
2040 	while(s) {
2041 		if(strcmp(s->str, item) == 0) {
2042 			return s;
2043 		}
2044 		s = s->next;
2045 	}
2046 	return NULL;
2047 }
2048 
2049 int
cfg_strlist_insert(struct config_strlist ** head,char * item)2050 cfg_strlist_insert(struct config_strlist** head, char* item)
2051 {
2052 	struct config_strlist *s;
2053 	if(!item || !head) {
2054 		free(item);
2055 		return 0;
2056 	}
2057 	s = (struct config_strlist*)calloc(1, sizeof(struct config_strlist));
2058 	if(!s) {
2059 		free(item);
2060 		return 0;
2061 	}
2062 	s->str = item;
2063 	s->next = *head;
2064 	*head = s;
2065 	return 1;
2066 }
2067 
2068 int
cfg_strlist_append_ex(struct config_strlist ** head,char * item)2069 cfg_strlist_append_ex(struct config_strlist** head, char* item)
2070 {
2071 	struct config_strlist *s;
2072 	if(!item || !head)
2073 		return 0;
2074 	s = (struct config_strlist*)calloc(1, sizeof(struct config_strlist));
2075 	if(!s)
2076 		return 0;
2077 	s->str = item;
2078 	s->next = NULL;
2079 
2080 	if (*head==NULL) {
2081 		*head = s;
2082 	} else {
2083 		struct config_strlist *last = *head;
2084 		while (last->next!=NULL) {
2085 		    last = last->next;
2086 		}
2087 		last->next = s;
2088 	}
2089 
2090 	return 1;
2091 }
2092 
2093 int
cfg_str2list_insert(struct config_str2list ** head,char * item,char * i2)2094 cfg_str2list_insert(struct config_str2list** head, char* item, char* i2)
2095 {
2096 	struct config_str2list *s;
2097 	if(!item || !i2 || !head) {
2098 		free(item);
2099 		free(i2);
2100 		return 0;
2101 	}
2102 	s = (struct config_str2list*)calloc(1, sizeof(struct config_str2list));
2103 	if(!s) {
2104 		free(item);
2105 		free(i2);
2106 		return 0;
2107 	}
2108 	s->str = item;
2109 	s->str2 = i2;
2110 	s->next = *head;
2111 	*head = s;
2112 	return 1;
2113 }
2114 
2115 int
cfg_str3list_insert(struct config_str3list ** head,char * item,char * i2,char * i3)2116 cfg_str3list_insert(struct config_str3list** head, char* item, char* i2,
2117 	char* i3)
2118 {
2119 	struct config_str3list *s;
2120 	if(!item || !i2 || !i3 || !head)
2121 		return 0;
2122 	s = (struct config_str3list*)calloc(1, sizeof(struct config_str3list));
2123 	if(!s)
2124 		return 0;
2125 	s->str = item;
2126 	s->str2 = i2;
2127 	s->str3 = i3;
2128 	s->next = *head;
2129 	*head = s;
2130 	return 1;
2131 }
2132 
2133 int
cfg_strbytelist_insert(struct config_strbytelist ** head,char * item,uint8_t * i2,size_t i2len)2134 cfg_strbytelist_insert(struct config_strbytelist** head, char* item,
2135 	uint8_t* i2, size_t i2len)
2136 {
2137 	struct config_strbytelist* s;
2138 	if(!item || !i2 || !head)
2139 		return 0;
2140 	s = (struct config_strbytelist*)calloc(1, sizeof(*s));
2141 	if(!s)
2142 		return 0;
2143 	s->str = item;
2144 	s->str2 = i2;
2145 	s->str2len = i2len;
2146 	s->next = *head;
2147 	*head = s;
2148 	return 1;
2149 }
2150 
2151 time_t
cfg_convert_timeval(const char * str)2152 cfg_convert_timeval(const char* str)
2153 {
2154 	time_t t;
2155 	struct tm tm;
2156 	memset(&tm, 0, sizeof(tm));
2157 	if(strlen(str) < 14)
2158 		return 0;
2159 	if(sscanf(str, "%4d%2d%2d%2d%2d%2d", &tm.tm_year, &tm.tm_mon,
2160 		&tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6)
2161 		return 0;
2162 	tm.tm_year -= 1900;
2163 	tm.tm_mon--;
2164 	/* Check values */
2165 	if (tm.tm_year < 70)	return 0;
2166 	if (tm.tm_mon < 0 || tm.tm_mon > 11)	return 0;
2167 	if (tm.tm_mday < 1 || tm.tm_mday > 31) 	return 0;
2168 	if (tm.tm_hour < 0 || tm.tm_hour > 23)	return 0;
2169 	if (tm.tm_min < 0 || tm.tm_min > 59)	return 0;
2170 	if (tm.tm_sec < 0 || tm.tm_sec > 59)	return 0;
2171 	/* call ldns conversion function */
2172 	t = sldns_mktime_from_utc(&tm);
2173 	return t;
2174 }
2175 
2176 int
cfg_count_numbers(const char * s)2177 cfg_count_numbers(const char* s)
2178 {
2179 	/* format ::= (sp num)+ sp  */
2180 	/* num ::= [-](0-9)+        */
2181 	/* sp ::= (space|tab)*      */
2182 	int num = 0;
2183 	while(*s) {
2184 		while(*s && isspace((unsigned char)*s))
2185 			s++;
2186 		if(!*s) /* end of string */
2187 			break;
2188 		if(*s == '-')
2189 			s++;
2190 		if(!*s) /* only - not allowed */
2191 			return 0;
2192 		if(!isdigit((unsigned char)*s)) /* bad character */
2193 			return 0;
2194 		while(*s && isdigit((unsigned char)*s))
2195 			s++;
2196 		num++;
2197 	}
2198 	return num;
2199 }
2200 
2201 /** all digit number */
isalldigit(const char * str,size_t l)2202 static int isalldigit(const char* str, size_t l)
2203 {
2204 	size_t i;
2205 	for(i=0; i<l; i++)
2206 		if(!isdigit((unsigned char)str[i]))
2207 			return 0;
2208 	return 1;
2209 }
2210 
2211 int
cfg_parse_memsize(const char * str,size_t * res)2212 cfg_parse_memsize(const char* str, size_t* res)
2213 {
2214 	size_t len;
2215 	size_t mult = 1;
2216 	if(!str || (len=(size_t)strlen(str)) == 0) {
2217 		log_err("not a size: '%s'", str);
2218 		return 0;
2219 	}
2220 	if(isalldigit(str, len)) {
2221 		*res = (size_t)atol(str);
2222 		return 1;
2223 	}
2224 	/* check appended num */
2225 	while(len>0 && str[len-1]==' ')
2226 		len--;
2227 	if(len > 1 && str[len-1] == 'b')
2228 		len--;
2229 	else if(len > 1 && str[len-1] == 'B')
2230 		len--;
2231 
2232 	if(len > 1 && tolower((unsigned char)str[len-1]) == 'g')
2233 		mult = 1024*1024*1024;
2234 	else if(len > 1 && tolower((unsigned char)str[len-1]) == 'm')
2235 		mult = 1024*1024;
2236 	else if(len > 1 && tolower((unsigned char)str[len-1]) == 'k')
2237 		mult = 1024;
2238 	else if(len > 0 && isdigit((unsigned char)str[len-1]))
2239 		mult = 1;
2240 	else {
2241 		log_err("unknown size specifier: '%s'", str);
2242 		return 0;
2243 	}
2244 	while(len>1 && str[len-2]==' ')
2245 		len--;
2246 
2247 	if(!isalldigit(str, len-1)) {
2248 		log_err("unknown size specifier: '%s'", str);
2249 		return 0;
2250 	}
2251 	*res = ((size_t)atol(str)) * mult;
2252 	return 1;
2253 }
2254 
2255 int
find_tag_id(struct config_file * cfg,const char * tag)2256 find_tag_id(struct config_file* cfg, const char* tag)
2257 {
2258 	int i;
2259 	for(i=0; i<cfg->num_tags; i++) {
2260 		if(strcmp(cfg->tagname[i], tag) == 0)
2261 			return i;
2262 	}
2263 	return -1;
2264 }
2265 
2266 int
config_add_tag(struct config_file * cfg,const char * tag)2267 config_add_tag(struct config_file* cfg, const char* tag)
2268 {
2269 	char** newarray;
2270 	char* newtag;
2271 	if(find_tag_id(cfg, tag) != -1)
2272 		return 1; /* nothing to do */
2273 	newarray = (char**)malloc(sizeof(char*)*(cfg->num_tags+1));
2274 	if(!newarray)
2275 		return 0;
2276 	newtag = strdup(tag);
2277 	if(!newtag) {
2278 		free(newarray);
2279 		return 0;
2280 	}
2281 	if(cfg->tagname) {
2282 		memcpy(newarray, cfg->tagname, sizeof(char*)*cfg->num_tags);
2283 		free(cfg->tagname);
2284 	}
2285 	newarray[cfg->num_tags++] = newtag;
2286 	cfg->tagname = newarray;
2287 	return 1;
2288 }
2289 
2290 /** set a bit in a bit array */
2291 static void
cfg_set_bit(uint8_t * bitlist,size_t len,int id)2292 cfg_set_bit(uint8_t* bitlist, size_t len, int id)
2293 {
2294 	int pos = id/8;
2295 	log_assert((size_t)pos < len);
2296 	(void)len;
2297 	bitlist[pos] |= 1<<(id%8);
2298 }
2299 
config_parse_taglist(struct config_file * cfg,char * str,size_t * listlen)2300 uint8_t* config_parse_taglist(struct config_file* cfg, char* str,
2301         size_t* listlen)
2302 {
2303 	uint8_t* taglist = NULL;
2304 	size_t len = 0;
2305 	char* p, *s;
2306 
2307 	/* allocate */
2308 	if(cfg->num_tags == 0) {
2309 		log_err("parse taglist, but no tags defined");
2310 		return 0;
2311 	}
2312 	len = (size_t)(cfg->num_tags+7)/8;
2313 	taglist = calloc(1, len);
2314 	if(!taglist) {
2315 		log_err("out of memory");
2316 		return 0;
2317 	}
2318 
2319 	/* parse */
2320 	s = str;
2321 	while((p=strsep(&s, " \t\n")) != NULL) {
2322 		if(*p) {
2323 			int id = find_tag_id(cfg, p);
2324 			/* set this bit in the bitlist */
2325 			if(id == -1) {
2326 				log_err("unknown tag: %s", p);
2327 				free(taglist);
2328 				return 0;
2329 			}
2330 			cfg_set_bit(taglist, len, id);
2331 		}
2332 	}
2333 
2334 	*listlen = len;
2335 	return taglist;
2336 }
2337 
cfg_parse_nsid(const char * str,uint16_t * nsid_len)2338 uint8_t* cfg_parse_nsid(const char* str, uint16_t* nsid_len)
2339 {
2340 	uint8_t* nsid = NULL;
2341 
2342 	if (strncasecmp(str, "ascii_", 6) == 0) {
2343 		if ((nsid = (uint8_t *)strdup(str + 6)))
2344 			*nsid_len = strlen(str + 6);
2345 
2346 	} else if (strlen(str) % 2) {
2347 		; /* hex string has even number of characters */
2348 	}
2349 
2350 	else if (*str && (nsid = calloc(1, strlen(str) / 2))) {
2351 		const char *ch;
2352 		uint8_t *dp;
2353 
2354 		for ( ch = str, dp = nsid
2355 		    ; isxdigit((unsigned char)ch[0]) && isxdigit((unsigned char)ch[1])
2356 		    ; ch += 2, dp++) {
2357 			*dp  = (uint8_t)sldns_hexdigit_to_int(ch[0]) * 16;
2358 			*dp += (uint8_t)sldns_hexdigit_to_int(ch[1]);
2359 		}
2360 		if (*ch) {
2361 			free(nsid);
2362 			nsid = NULL;
2363 		} else
2364 			*nsid_len = strlen(str) / 2;
2365 	}
2366 	return nsid;
2367 }
2368 
2369 
config_taglist2str(struct config_file * cfg,uint8_t * taglist,size_t taglen)2370 char* config_taglist2str(struct config_file* cfg, uint8_t* taglist,
2371         size_t taglen)
2372 {
2373 	char buf[10240];
2374 	size_t i, j, len = 0;
2375 	buf[0] = 0;
2376 	for(i=0; i<taglen; i++) {
2377 		if(taglist[i] == 0)
2378 			continue;
2379 		for(j=0; j<8; j++) {
2380 			if((taglist[i] & (1<<j)) != 0) {
2381 				size_t id = i*8 + j;
2382 				snprintf(buf+len, sizeof(buf)-len, "%s%s",
2383 					(len==0?"":" "), cfg->tagname[id]);
2384 				len += strlen(buf+len);
2385 			}
2386 		}
2387 	}
2388 	return strdup(buf);
2389 }
2390 
taglist_intersect(uint8_t * list1,size_t list1len,const uint8_t * list2,size_t list2len)2391 int taglist_intersect(uint8_t* list1, size_t list1len, const uint8_t* list2,
2392 	size_t list2len)
2393 {
2394 	size_t i;
2395 	if(!list1 || !list2)
2396 		return 0;
2397 	for(i=0; i<list1len && i<list2len; i++) {
2398 		if((list1[i] & list2[i]) != 0)
2399 			return 1;
2400 	}
2401 	return 0;
2402 }
2403 
2404 void
config_apply(struct config_file * config)2405 config_apply(struct config_file* config)
2406 {
2407 	MAX_TTL = (time_t)config->max_ttl;
2408 	MIN_TTL = (time_t)config->min_ttl;
2409 	SERVE_EXPIRED = config->serve_expired;
2410 	SERVE_EXPIRED_TTL = (time_t)config->serve_expired_ttl;
2411 	SERVE_EXPIRED_TTL_RESET = config->serve_expired_ttl_reset;
2412 	SERVE_EXPIRED_REPLY_TTL = (time_t)config->serve_expired_reply_ttl;
2413 	SERVE_ORIGINAL_TTL = config->serve_original_ttl;
2414 	MAX_NEG_TTL = (time_t)config->max_negative_ttl;
2415 	MIN_NEG_TTL = (time_t)config->min_negative_ttl;
2416 	RTT_MIN_TIMEOUT = config->infra_cache_min_rtt;
2417 	RTT_MAX_TIMEOUT = config->infra_cache_max_rtt;
2418 	EDNS_ADVERTISED_SIZE = (uint16_t)config->edns_buffer_size;
2419 	MINIMAL_RESPONSES = config->minimal_responses;
2420 	RRSET_ROUNDROBIN = config->rrset_roundrobin;
2421 	LOG_TAG_QUERYREPLY = config->log_tag_queryreply;
2422 	MAX_GLOBAL_QUOTA = config->max_global_quota;
2423 	UNKNOWN_SERVER_NICENESS = config->unknown_server_time_limit;
2424 	USEFUL_SERVER_TOP_TIMEOUT = RTT_MAX_TIMEOUT;
2425 	BLACKLIST_PENALTY = USEFUL_SERVER_TOP_TIMEOUT*4;
2426 	log_set_time_asc(config->log_time_ascii);
2427 	log_set_time_iso(config->log_time_iso);
2428 	autr_permit_small_holddown = config->permit_small_holddown;
2429 	stream_wait_max = config->stream_wait_size;
2430 	http2_query_buffer_max = config->http_query_buffer_size;
2431 	http2_response_buffer_max = config->http_response_buffer_size;
2432 }
2433 
config_lookup_uid(struct config_file * cfg)2434 void config_lookup_uid(struct config_file* cfg)
2435 {
2436 #ifdef HAVE_GETPWNAM
2437 	/* translate username into uid and gid */
2438 	if(cfg->username && cfg->username[0]) {
2439 		struct passwd *pwd;
2440 		if((pwd = getpwnam(cfg->username)) != NULL) {
2441 			cfg_uid = pwd->pw_uid;
2442 			cfg_gid = pwd->pw_gid;
2443 		}
2444 	}
2445 #else
2446 	(void)cfg;
2447 #endif
2448 }
2449 
2450 /**
2451  * Calculate string length of full pathname in original filesys
2452  * @param fname: the path name to convert.
2453  * 	Must not be null or empty.
2454  * @param cfg: config struct for chroot and chdir (if set).
2455  * @param use_chdir: if false, only chroot is applied.
2456  * @return length of string.
2457  *	remember to allocate one more for 0 at end in mallocs.
2458  */
2459 static size_t
strlen_after_chroot(const char * fname,struct config_file * cfg,int use_chdir)2460 strlen_after_chroot(const char* fname, struct config_file* cfg, int use_chdir)
2461 {
2462 	size_t len = 0;
2463 	int slashit = 0;
2464 	if(cfg->chrootdir && cfg->chrootdir[0] &&
2465 		strncmp(cfg->chrootdir, fname, strlen(cfg->chrootdir)) == 0) {
2466 		/* already full pathname, return it */
2467 		return strlen(fname);
2468 	}
2469 	/* chroot */
2470 	if(cfg->chrootdir && cfg->chrootdir[0]) {
2471 		/* start with chrootdir */
2472 		len += strlen(cfg->chrootdir);
2473 		slashit = 1;
2474 	}
2475 	/* chdir */
2476 #ifdef UB_ON_WINDOWS
2477 	if(fname[0] != 0 && fname[1] == ':') {
2478 		/* full path, no chdir */
2479 	} else
2480 #endif
2481 	if(fname[0] == '/' || !use_chdir) {
2482 		/* full path, no chdir */
2483 	} else if(cfg->directory && cfg->directory[0]) {
2484 		/* prepend chdir */
2485 		if(slashit && cfg->directory[0] != '/')
2486 			len++;
2487 		if(cfg->chrootdir && cfg->chrootdir[0] &&
2488 			strncmp(cfg->chrootdir, cfg->directory,
2489 			strlen(cfg->chrootdir)) == 0)
2490 			len += strlen(cfg->directory)-strlen(cfg->chrootdir);
2491 		else	len += strlen(cfg->directory);
2492 		slashit = 1;
2493 	}
2494 	/* fname */
2495 	if(slashit && fname[0] != '/')
2496 		len++;
2497 	len += strlen(fname);
2498 	return len;
2499 }
2500 
2501 char*
fname_after_chroot(const char * fname,struct config_file * cfg,int use_chdir)2502 fname_after_chroot(const char* fname, struct config_file* cfg, int use_chdir)
2503 {
2504 	size_t len = strlen_after_chroot(fname, cfg, use_chdir)+1;
2505 	int slashit = 0;
2506 	char* buf = (char*)malloc(len);
2507 	if(!buf)
2508 		return NULL;
2509 	buf[0] = 0;
2510 	/* is fname already in chroot ? */
2511 	if(cfg->chrootdir && cfg->chrootdir[0] &&
2512 		strncmp(cfg->chrootdir, fname, strlen(cfg->chrootdir)) == 0) {
2513 		/* already full pathname, return it */
2514 		(void)strlcpy(buf, fname, len);
2515 		buf[len-1] = 0;
2516 		return buf;
2517 	}
2518 	/* chroot */
2519 	if(cfg->chrootdir && cfg->chrootdir[0]) {
2520 		/* start with chrootdir */
2521 		(void)strlcpy(buf, cfg->chrootdir, len);
2522 		slashit = 1;
2523 	}
2524 #ifdef UB_ON_WINDOWS
2525 	if(fname[0] != 0 && fname[1] == ':') {
2526 		/* full path, no chdir */
2527 	} else
2528 #endif
2529 	/* chdir */
2530 	if(fname[0] == '/' || !use_chdir) {
2531 		/* full path, no chdir */
2532 	} else if(cfg->directory && cfg->directory[0]) {
2533 		/* prepend chdir */
2534 		if(slashit && cfg->directory[0] != '/')
2535 			(void)strlcat(buf, "/", len);
2536 		/* is the directory already in the chroot? */
2537 		if(cfg->chrootdir && cfg->chrootdir[0] &&
2538 			strncmp(cfg->chrootdir, cfg->directory,
2539 			strlen(cfg->chrootdir)) == 0)
2540 			(void)strlcat(buf, cfg->directory+strlen(cfg->chrootdir),
2541 				   len);
2542 		else (void)strlcat(buf, cfg->directory, len);
2543 		slashit = 1;
2544 	}
2545 	/* fname */
2546 	if(slashit && fname[0] != '/')
2547 		(void)strlcat(buf, "/", len);
2548 	(void)strlcat(buf, fname, len);
2549 	buf[len-1] = 0;
2550 	return buf;
2551 }
2552 
2553 /** return next space character in string */
next_space_pos(const char * str)2554 static char* next_space_pos(const char* str)
2555 {
2556 	char* sp = strchr(str, ' ');
2557 	char* tab = strchr(str, '\t');
2558 	if(!tab && !sp)
2559 		return NULL;
2560 	if(!sp) return tab;
2561 	if(!tab) return sp;
2562 	return (sp<tab)?sp:tab;
2563 }
2564 
2565 /** return last space character in string */
last_space_pos(const char * str)2566 static char* last_space_pos(const char* str)
2567 {
2568 	char* sp = strrchr(str, ' ');
2569 	char* tab = strrchr(str, '\t');
2570 	if(!tab && !sp)
2571 		return NULL;
2572 	if(!sp) return tab;
2573 	if(!tab) return sp;
2574 	return (sp>tab)?sp:tab;
2575 }
2576 
2577 int
cfg_parse_local_zone(struct config_file * cfg,const char * val)2578 cfg_parse_local_zone(struct config_file* cfg, const char* val)
2579 {
2580 	const char *type, *name_end, *name;
2581 	char buf[256];
2582 
2583 	/* parse it as: [zone_name] [between stuff] [zone_type] */
2584 	name = val;
2585 	while(*name && isspace((unsigned char)*name))
2586 		name++;
2587 	if(!*name) {
2588 		log_err("syntax error: too short: %s", val);
2589 		return 0;
2590 	}
2591 	name_end = next_space_pos(name);
2592 	if(!name_end || !*name_end) {
2593 		log_err("syntax error: expected zone type: %s", val);
2594 		return 0;
2595 	}
2596 	if (name_end - name > 255) {
2597 		log_err("syntax error: bad zone name: %s", val);
2598 		return 0;
2599 	}
2600 	(void)strlcpy(buf, name, sizeof(buf));
2601 	buf[name_end-name] = '\0';
2602 
2603 	type = last_space_pos(name_end);
2604 	while(type && *type && isspace((unsigned char)*type))
2605 		type++;
2606 	if(!type || !*type) {
2607 		log_err("syntax error: expected zone type: %s", val);
2608 		return 0;
2609 	}
2610 
2611 	if(strcmp(type, "nodefault")==0) {
2612 		return cfg_strlist_insert(&cfg->local_zones_nodefault,
2613 			strdup(name));
2614 #ifdef USE_IPSET
2615 	} else if(strcmp(type, "ipset")==0) {
2616 		return cfg_strlist_insert(&cfg->local_zones_ipset,
2617 			strdup(name));
2618 #endif
2619 	} else {
2620 		return cfg_str2list_insert(&cfg->local_zones, strdup(buf),
2621 			strdup(type));
2622 	}
2623 }
2624 
cfg_ptr_reverse(char * str)2625 char* cfg_ptr_reverse(char* str)
2626 {
2627 	char* ip, *ip_end;
2628 	char* name;
2629 	char* result;
2630 	char buf[1024];
2631 	struct sockaddr_storage addr;
2632 	socklen_t addrlen;
2633 
2634 	/* parse it as: [IP] [between stuff] [name] */
2635 	ip = str;
2636 	while(*ip && isspace((unsigned char)*ip))
2637 		ip++;
2638 	if(!*ip) {
2639 		log_err("syntax error: too short: %s", str);
2640 		return NULL;
2641 	}
2642 	ip_end = next_space_pos(ip);
2643 	if(!ip_end || !*ip_end) {
2644 		log_err("syntax error: expected name: %s", str);
2645 		return NULL;
2646 	}
2647 
2648 	name = last_space_pos(ip_end);
2649 	if(!name || !*name) {
2650 		log_err("syntax error: expected name: %s", str);
2651 		return NULL;
2652 	}
2653 
2654 	sscanf(ip, "%100s", buf);
2655 	buf[sizeof(buf)-1]=0;
2656 
2657 	if(!ipstrtoaddr(buf, UNBOUND_DNS_PORT, &addr, &addrlen)) {
2658 		log_err("syntax error: cannot parse address: %s", str);
2659 		return NULL;
2660 	}
2661 
2662 	/* reverse IPv4:
2663 	 * ddd.ddd.ddd.ddd.in-addr-arpa.
2664 	 * IPv6: (h.){32}.ip6.arpa.  */
2665 
2666 	if(addr_is_ip6(&addr, addrlen)) {
2667 		uint8_t ad[16];
2668 		const char* hex = "0123456789abcdef";
2669 		char *p = buf;
2670 		int i;
2671 		memmove(ad, &((struct sockaddr_in6*)&addr)->sin6_addr,
2672 			sizeof(ad));
2673 		for(i=15; i>=0; i--) {
2674 			uint8_t b = ad[i];
2675 			*p++ = hex[ (b&0x0f) ];
2676 			*p++ = '.';
2677 			*p++ = hex[ (b&0xf0) >> 4 ];
2678 			*p++ = '.';
2679 		}
2680 		snprintf(buf+16*4, sizeof(buf)-16*4, "ip6.arpa. ");
2681 	} else {
2682 		uint8_t ad[4];
2683 		memmove(ad, &((struct sockaddr_in*)&addr)->sin_addr,
2684 			sizeof(ad));
2685 		snprintf(buf, sizeof(buf), "%u.%u.%u.%u.in-addr.arpa. ",
2686 			(unsigned)ad[3], (unsigned)ad[2],
2687 			(unsigned)ad[1], (unsigned)ad[0]);
2688 	}
2689 
2690 	/* printed the reverse address, now the between goop and name on end */
2691 	while(*ip_end && isspace((unsigned char)*ip_end))
2692 		ip_end++;
2693 	if(name>ip_end) {
2694 		snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), "%.*s",
2695 			(int)(name-ip_end), ip_end);
2696 	}
2697 	snprintf(buf+strlen(buf), sizeof(buf)-strlen(buf), " PTR %s", name);
2698 
2699 	result = strdup(buf);
2700 	if(!result) {
2701 		log_err("out of memory parsing %s", str);
2702 		return NULL;
2703 	}
2704 	return result;
2705 }
2706 
2707 #ifdef UB_ON_WINDOWS
2708 char*
w_lookup_reg_str(const char * key,const char * name)2709 w_lookup_reg_str(const char* key, const char* name)
2710 {
2711 	HKEY hk = NULL;
2712 	DWORD type = 0;
2713 	BYTE buf[1024];
2714 	DWORD len = (DWORD)sizeof(buf);
2715 	LONG ret;
2716 	char* result = NULL;
2717 	ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hk);
2718 	if(ret == ERROR_FILE_NOT_FOUND)
2719 		return NULL; /* key does not exist */
2720 	else if(ret != ERROR_SUCCESS) {
2721 		log_err("RegOpenKeyEx failed");
2722 		return NULL;
2723 	}
2724 	ret = RegQueryValueEx(hk, (LPCTSTR)name, 0, &type, buf, &len);
2725 	if(RegCloseKey(hk))
2726 		log_err("RegCloseKey");
2727 	if(ret == ERROR_FILE_NOT_FOUND)
2728 		return NULL; /* name does not exist */
2729 	else if(ret != ERROR_SUCCESS) {
2730 		log_err("RegQueryValueEx failed");
2731 		return NULL;
2732 	}
2733 	if(type == REG_SZ || type == REG_MULTI_SZ || type == REG_EXPAND_SZ) {
2734 		buf[sizeof(buf)-1] = 0;
2735 		buf[sizeof(buf)-2] = 0; /* for multi_sz */
2736 		result = strdup((char*)buf);
2737 		if(!result) log_err("out of memory");
2738 	}
2739 	return result;
2740 }
2741 
w_config_adjust_directory(struct config_file * cfg)2742 void w_config_adjust_directory(struct config_file* cfg)
2743 {
2744 	if(cfg->directory && cfg->directory[0]) {
2745 		TCHAR dirbuf[2*MAX_PATH+4];
2746 		if(strcmp(cfg->directory, "%EXECUTABLE%") == 0) {
2747 			/* get executable path, and if that contains
2748 			 * directories, snip off the filename part */
2749 			dirbuf[0] = 0;
2750 			if(!GetModuleFileName(NULL, dirbuf, MAX_PATH))
2751 				log_err("could not GetModuleFileName");
2752 			if(strrchr(dirbuf, '\\')) {
2753 				(strrchr(dirbuf, '\\'))[0] = 0;
2754 			} else log_err("GetModuleFileName had no path");
2755 			if(dirbuf[0]) {
2756 				/* adjust directory for later lookups to work*/
2757 				free(cfg->directory);
2758 				cfg->directory = memdup(dirbuf, strlen(dirbuf)+1);
2759 			}
2760 		}
2761 	}
2762 }
2763 #endif /* UB_ON_WINDOWS */
2764 
options_remote_is_address(struct config_file * cfg)2765 int options_remote_is_address(struct config_file* cfg)
2766 {
2767 	if(!cfg->remote_control_enable) return 0;
2768 	if(!cfg->control_ifs.first) return 1;
2769 	if(!cfg->control_ifs.first->str) return 1;
2770 	if(cfg->control_ifs.first->str[0] == 0) return 1;
2771 	return (cfg->control_ifs.first->str[0] != '/');
2772 }
2773 
2774 /** see if interface is https, its port number == the https port number */
2775 int
if_is_https(const char * ifname,const char * port,int https_port)2776 if_is_https(const char* ifname, const char* port, int https_port)
2777 {
2778 	char* p = strchr(ifname, '@');
2779 	if(!p && atoi(port) == https_port)
2780 		return 1;
2781 	if(p && atoi(p+1) == https_port)
2782 		return 1;
2783 	return 0;
2784 }
2785 
2786 /** see if config contains https turned on */
cfg_has_https(struct config_file * cfg)2787 int cfg_has_https(struct config_file* cfg)
2788 {
2789 	int i;
2790 	char portbuf[32];
2791 	snprintf(portbuf, sizeof(portbuf), "%d", cfg->port);
2792 	for(i = 0; i<cfg->num_ifs; i++) {
2793 		if(if_is_https(cfg->ifs[i], portbuf, cfg->https_port))
2794 			return 1;
2795 	}
2796 	return 0;
2797 }
2798 
2799 /** see if interface is PROXYv2, its port number == the proxy port number */
2800 int
if_is_pp2(const char * ifname,const char * port,struct config_strlist * proxy_protocol_port)2801 if_is_pp2(const char* ifname, const char* port,
2802 	struct config_strlist* proxy_protocol_port)
2803 {
2804 	struct config_strlist* s;
2805 	char* p = strchr(ifname, '@');
2806 	for(s = proxy_protocol_port; s; s = s->next) {
2807 		if(p && atoi(p+1) == atoi(s->str))
2808 			return 1;
2809 		if(!p && atoi(port) == atoi(s->str))
2810 			return 1;
2811 	}
2812 	return 0;
2813 }
2814 
2815 /** see if interface is DNSCRYPT, its port number == the dnscrypt port number */
2816 int
if_is_dnscrypt(const char * ifname,const char * port,int dnscrypt_port)2817 if_is_dnscrypt(const char* ifname, const char* port, int dnscrypt_port)
2818 {
2819 #ifdef USE_DNSCRYPT
2820 	return ((strchr(ifname, '@') &&
2821 		atoi(strchr(ifname, '@')+1) == dnscrypt_port) ||
2822 		(!strchr(ifname, '@') && atoi(port) == dnscrypt_port));
2823 #else
2824 	(void)ifname;
2825 	(void)port;
2826 	(void)dnscrypt_port;
2827 	return 0;
2828 #endif
2829 }
2830 
2831 /** see if interface is quic, its port number == the quic port number */
2832 int
if_is_quic(const char * ifname,const char * port,int quic_port)2833 if_is_quic(const char* ifname, const char* port, int quic_port)
2834 {
2835 #ifndef HAVE_NGTCP2
2836 	(void)ifname;
2837 	(void)port;
2838 	(void)quic_port;
2839 	return 0;
2840 #else
2841 	char* p = strchr(ifname, '@');
2842 	if(!p && atoi(port) == quic_port)
2843 		return 1;
2844 	if(p && atoi(p+1) == quic_port)
2845 		return 1;
2846 	return 0;
2847 #endif
2848 }
2849