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