xref: /freebsd/contrib/unbound/smallapp/unbound-control.c (revision 3c134670993bf525fcd6c4dfef84a3dfc3d4ed1b)
1 /*
2  * checkconf/unbound-control.c - remote control utility for unbound.
3  *
4  * Copyright (c) 2008, 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  * The remote control utility contacts the unbound server over ssl and
40  * sends the command, receives the answer, and displays the result
41  * from the commandline.
42  */
43 
44 #include "config.h"
45 #ifdef HAVE_GETOPT_H
46 #include <getopt.h>
47 #endif
48 #ifdef HAVE_OPENSSL_SSL_H
49 #include <openssl/ssl.h>
50 #endif
51 #ifdef HAVE_OPENSSL_ERR_H
52 #include <openssl/err.h>
53 #endif
54 #ifdef HAVE_OPENSSL_RAND_H
55 #include <openssl/rand.h>
56 #endif
57 #include "util/log.h"
58 #include "util/config_file.h"
59 #include "util/locks.h"
60 #include "util/net_help.h"
61 #include "util/shm_side/shm_main.h"
62 #include "daemon/stats.h"
63 #include "sldns/wire2str.h"
64 #include "sldns/pkthdr.h"
65 #include "services/rpz.h"
66 
67 #ifdef HAVE_SYS_IPC_H
68 #include "sys/ipc.h"
69 #endif
70 #ifdef HAVE_SYS_SHM_H
71 #include "sys/shm.h"
72 #endif
73 #ifdef HAVE_SYS_UN_H
74 #include <sys/un.h>
75 #endif
76 
77 #ifdef HAVE_TARGETCONDITIONALS_H
78 #include <TargetConditionals.h>
79 #endif
80 
81 static void usage(void) ATTR_NORETURN;
82 static void ssl_err(const char* s) ATTR_NORETURN;
83 static void ssl_path_err(const char* s, const char *path) ATTR_NORETURN;
84 
85 /** Give unbound-control usage, and exit (1). */
86 static void
87 usage(void)
88 {
89 	printf("Usage:	local-unbound-control [options] command\n");
90 	printf("	Remote control utility for unbound server.\n");
91 	printf("Options:\n");
92 	printf("  -c file	config file, default is %s\n", CONFIGFILE);
93 	printf("  -s ip[@port]	server address, if omitted config is used.\n");
94 	printf("  -q		quiet (don't print anything if it works ok).\n");
95 	printf("  -h		show this usage help.\n");
96 	printf("Commands:\n");
97 	printf("  start				start server; runs unbound(8)\n");
98 	printf("  stop				stops the server\n");
99 	printf("  reload			reloads the server\n");
100 	printf("  				(this flushes data, stats, requestlist)\n");
101 	printf("  stats				print statistics\n");
102 	printf("  stats_noreset			peek at statistics\n");
103 #ifdef HAVE_SHMGET
104 	printf("  stats_shm			print statistics using shm\n");
105 #endif
106 	printf("  status			display status of server\n");
107 	printf("  verbosity <number>		change logging detail\n");
108 	printf("  log_reopen			close and open the logfile\n");
109 	printf("  local_zone <name> <type>	add new local zone\n");
110 	printf("  local_zone_remove <name>	remove local zone and its contents\n");
111 	printf("  local_data <RR data...>	add local data, for example\n");
112 	printf("				local_data www.example.com A 192.0.2.1\n");
113 	printf("  local_data_remove <name>	remove local RR data from name\n");
114 	printf("  local_zones, local_zones_remove, local_datas, local_datas_remove\n");
115 	printf("  				same, but read list from stdin\n");
116 	printf("  				(one entry per line).\n");
117 	printf("  dump_cache			print cache to stdout\n");
118 	printf("  load_cache			load cache from stdin\n");
119 	printf("  lookup <name>			print nameservers for name\n");
120 	printf("  flush <name>			flushes common types for name from cache\n");
121 	printf("  				types:  A, AAAA, MX, PTR, NS,\n");
122 	printf("					SOA, CNAME, DNAME, SRV, NAPTR\n");
123 	printf("  flush_type <name> <type>	flush name, type from cache\n");
124 	printf("  flush_zone <name>		flush everything at or under name\n");
125 	printf("  				from rr and dnssec caches\n");
126 	printf("  flush_bogus			flush all bogus data\n");
127 	printf("  flush_negative		flush all negative data\n");
128 	printf("  flush_stats 			flush statistics, make zero\n");
129 	printf("  flush_requestlist 		drop queries that are worked on\n");
130 	printf("  dump_requestlist		show what is worked on by first thread\n");
131 	printf("  flush_infra [all | ip] 	remove ping, edns for one IP or all\n");
132 	printf("  dump_infra			show ping and edns entries\n");
133 	printf("  set_option opt: val		set option to value, no reload\n");
134 	printf("  get_option opt		get option value\n");
135 	printf("  list_stubs			list stub-zones and root hints in use\n");
136 	printf("  list_forwards			list forward-zones in use\n");
137 	printf("  list_insecure			list domain-insecure zones\n");
138 	printf("  list_local_zones		list local-zones in use\n");
139 	printf("  list_local_data		list local-data RRs in use\n");
140 	printf("  insecure_add zone 		add domain-insecure zone\n");
141 	printf("  insecure_remove zone		remove domain-insecure zone\n");
142 	printf("  forward_add [+i] zone addr..	add forward-zone with servers\n");
143 	printf("  forward_remove [+i] zone	remove forward zone\n");
144 	printf("  stub_add [+ip] zone addr..	add stub-zone with servers\n");
145 	printf("  stub_remove [+i] zone		remove stub zone\n");
146 	printf("		+i		also do dnssec insecure point\n");
147 	printf("		+p		set stub to use priming\n");
148 	printf("  forward [off | addr ...]	without arg show forward setup\n");
149 	printf("				or off to turn off root forwarding\n");
150 	printf("				or give list of ip addresses\n");
151 	printf("  ratelimit_list [+a]		list ratelimited domains\n");
152 	printf("  ip_ratelimit_list [+a]	list ratelimited ip addresses\n");
153 	printf("		+a		list all, also not ratelimited\n");
154 	printf("  list_auth_zones		list auth zones\n");
155 	printf("  auth_zone_reload zone		reload auth zone from zonefile\n");
156 	printf("  auth_zone_transfer zone	transfer auth zone from master\n");
157 	printf("  view_list_local_zones	view	list local-zones in view\n");
158 	printf("  view_list_local_data	view	list local-data RRs in view\n");
159 	printf("  view_local_zone view name type  	add local-zone in view\n");
160 	printf("  view_local_zone_remove view name  	remove local-zone in view\n");
161 	printf("  view_local_data view RR...		add local-data in view\n");
162 	printf("  view_local_datas view 		add list of local-data to view\n");
163 	printf("  					one entry per line read from stdin\n");
164 	printf("  view_local_data_remove view name  	remove local-data in view\n");
165 	printf("  view_local_datas_remove view 		remove list of local-data from view\n");
166 	printf("  					one entry per line read from stdin\n");
167 	printf("Version %s\n", PACKAGE_VERSION);
168 	printf("BSD licensed, see LICENSE in source package for details.\n");
169 	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
170 	exit(1);
171 }
172 
173 #ifdef HAVE_SHMGET
174 /** what to put on statistics lines between var and value, ": " or "=" */
175 #define SQ "="
176 /** if true, inhibits a lot of =0 lines from the stats output */
177 static const int inhibit_zero = 1;
178 /** divide sum of timers to get average */
179 static void
180 timeval_divide(struct timeval* avg, const struct timeval* sum, long long d)
181 {
182 #ifndef S_SPLINT_S
183 	size_t leftover;
184 	if(d == 0) {
185 		avg->tv_sec = 0;
186 		avg->tv_usec = 0;
187 		return;
188 	}
189 	avg->tv_sec = sum->tv_sec / d;
190 	avg->tv_usec = sum->tv_usec / d;
191 	/* handle fraction from seconds divide */
192 	leftover = sum->tv_sec - avg->tv_sec*d;
193 	avg->tv_usec += (leftover*1000000)/d;
194 #endif
195 }
196 
197 /** print unsigned long stats value */
198 #define PR_UL_NM(str, var) printf("%s."str SQ"%lu\n", nm, (unsigned long)(var));
199 #define PR_UL(str, var) printf(str SQ"%lu\n", (unsigned long)(var));
200 #define PR_UL_SUB(str, nm, var) printf(str".%s"SQ"%lu\n", nm, (unsigned long)(var));
201 #define PR_TIMEVAL(str, var) printf(str SQ ARG_LL "d.%6.6d\n", \
202 	(long long)var.tv_sec, (int)var.tv_usec);
203 #define PR_STATSTIME(str, var) printf(str SQ ARG_LL "d.%6.6d\n", \
204 	(long long)var ## _sec, (int)var ## _usec);
205 #define PR_LL(str, var) printf(str SQ ARG_LL"d\n", (long long)(var));
206 
207 /** print stat block */
208 static void pr_stats(const char* nm, struct ub_stats_info* s)
209 {
210 	struct timeval sumwait, avg;
211 	PR_UL_NM("num.queries", s->svr.num_queries);
212 	PR_UL_NM("num.queries_ip_ratelimited",
213 		s->svr.num_queries_ip_ratelimited);
214 	PR_UL_NM("num.cachehits",
215 		s->svr.num_queries - s->svr.num_queries_missed_cache);
216 	PR_UL_NM("num.cachemiss", s->svr.num_queries_missed_cache);
217 	PR_UL_NM("num.prefetch", s->svr.num_queries_prefetch);
218 	PR_UL_NM("num.expired", s->svr.ans_expired);
219 	PR_UL_NM("num.recursivereplies", s->mesh_replies_sent);
220 #ifdef USE_DNSCRYPT
221     PR_UL_NM("num.dnscrypt.crypted", s->svr.num_query_dnscrypt_crypted);
222     PR_UL_NM("num.dnscrypt.cert", s->svr.num_query_dnscrypt_cert);
223     PR_UL_NM("num.dnscrypt.cleartext", s->svr.num_query_dnscrypt_cleartext);
224     PR_UL_NM("num.dnscrypt.malformed",
225              s->svr.num_query_dnscrypt_crypted_malformed);
226 #endif /* USE_DNSCRYPT */
227 	printf("%s.requestlist.avg"SQ"%g\n", nm,
228 		(s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
229 			(double)s->svr.sum_query_list_size/
230 			(double)(s->svr.num_queries_missed_cache+
231 			s->svr.num_queries_prefetch) : 0.0);
232 	PR_UL_NM("requestlist.max", s->svr.max_query_list_size);
233 	PR_UL_NM("requestlist.overwritten", s->mesh_jostled);
234 	PR_UL_NM("requestlist.exceeded", s->mesh_dropped);
235 	PR_UL_NM("requestlist.current.all", s->mesh_num_states);
236 	PR_UL_NM("requestlist.current.user", s->mesh_num_reply_states);
237 #ifndef S_SPLINT_S
238 	sumwait.tv_sec = s->mesh_replies_sum_wait_sec;
239 	sumwait.tv_usec = s->mesh_replies_sum_wait_usec;
240 #endif
241 	timeval_divide(&avg, &sumwait, s->mesh_replies_sent);
242 	printf("%s.", nm);
243 	PR_TIMEVAL("recursion.time.avg", avg);
244 	printf("%s.recursion.time.median"SQ"%g\n", nm, s->mesh_time_median);
245 	PR_UL_NM("tcpusage", s->svr.tcp_accept_usage);
246 }
247 
248 /** print uptime */
249 static void print_uptime(struct ub_shm_stat_info* shm_stat)
250 {
251 	PR_STATSTIME("time.now", shm_stat->time.now);
252 	PR_STATSTIME("time.up", shm_stat->time.up);
253 	PR_STATSTIME("time.elapsed", shm_stat->time.elapsed);
254 }
255 
256 /** print memory usage */
257 static void print_mem(struct ub_shm_stat_info* shm_stat,
258 	struct ub_stats_info* s)
259 {
260 	PR_LL("mem.cache.rrset", shm_stat->mem.rrset);
261 	PR_LL("mem.cache.message", shm_stat->mem.msg);
262 	PR_LL("mem.mod.iterator", shm_stat->mem.iter);
263 	PR_LL("mem.mod.validator", shm_stat->mem.val);
264 	PR_LL("mem.mod.respip", shm_stat->mem.respip);
265 #ifdef CLIENT_SUBNET
266 	PR_LL("mem.mod.subnet", shm_stat->mem.subnet);
267 #endif
268 #ifdef USE_IPSECMOD
269 	PR_LL("mem.mod.ipsecmod", shm_stat->mem.ipsecmod);
270 #endif
271 #ifdef WITH_DYNLIBMODULE
272 	PR_LL("mem.mod.dynlib", shm_stat->mem.dynlib);
273 #endif
274 #ifdef USE_DNSCRYPT
275 	PR_LL("mem.cache.dnscrypt_shared_secret",
276 		shm_stat->mem.dnscrypt_shared_secret);
277 	PR_LL("mem.cache.dnscrypt_nonce",
278 		shm_stat->mem.dnscrypt_nonce);
279 #endif
280 	PR_LL("mem.streamwait", s->svr.mem_stream_wait);
281 }
282 
283 /** print histogram */
284 static void print_hist(struct ub_stats_info* s)
285 {
286 	struct timehist* hist;
287 	size_t i;
288 	hist = timehist_setup();
289 	if(!hist)
290 		fatal_exit("out of memory");
291 	timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
292 	for(i=0; i<hist->num; i++) {
293 		printf("histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
294 			(int)hist->buckets[i].lower.tv_sec,
295 			(int)hist->buckets[i].lower.tv_usec,
296 			(int)hist->buckets[i].upper.tv_sec,
297 			(int)hist->buckets[i].upper.tv_usec,
298 			(unsigned long)hist->buckets[i].count);
299 	}
300 	timehist_delete(hist);
301 }
302 
303 /** print extended */
304 static void print_extended(struct ub_stats_info* s)
305 {
306 	int i;
307 	char nm[16];
308 
309 	/* TYPE */
310 	for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
311 		if(inhibit_zero && s->svr.qtype[i] == 0)
312 			continue;
313 		sldns_wire2str_type_buf((uint16_t)i, nm, sizeof(nm));
314 		PR_UL_SUB("num.query.type", nm, s->svr.qtype[i]);
315 	}
316 	if(!inhibit_zero || s->svr.qtype_big) {
317 		PR_UL("num.query.type.other", s->svr.qtype_big);
318 	}
319 
320 	/* CLASS */
321 	for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
322 		if(inhibit_zero && s->svr.qclass[i] == 0)
323 			continue;
324 		sldns_wire2str_class_buf((uint16_t)i, nm, sizeof(nm));
325 		PR_UL_SUB("num.query.class", nm, s->svr.qclass[i]);
326 	}
327 	if(!inhibit_zero || s->svr.qclass_big) {
328 		PR_UL("num.query.class.other", s->svr.qclass_big);
329 	}
330 
331 	/* OPCODE */
332 	for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
333 		if(inhibit_zero && s->svr.qopcode[i] == 0)
334 			continue;
335 		sldns_wire2str_opcode_buf(i, nm, sizeof(nm));
336 		PR_UL_SUB("num.query.opcode", nm, s->svr.qopcode[i]);
337 	}
338 
339 	/* transport */
340 	PR_UL("num.query.tcp", s->svr.qtcp);
341 	PR_UL("num.query.tcpout", s->svr.qtcp_outgoing);
342 	PR_UL("num.query.tls", s->svr.qtls);
343 	PR_UL("num.query.tls_resume", s->svr.qtls_resume);
344 	PR_UL("num.query.ipv6", s->svr.qipv6);
345 
346 	/* flags */
347 	PR_UL("num.query.flags.QR", s->svr.qbit_QR);
348 	PR_UL("num.query.flags.AA", s->svr.qbit_AA);
349 	PR_UL("num.query.flags.TC", s->svr.qbit_TC);
350 	PR_UL("num.query.flags.RD", s->svr.qbit_RD);
351 	PR_UL("num.query.flags.RA", s->svr.qbit_RA);
352 	PR_UL("num.query.flags.Z", s->svr.qbit_Z);
353 	PR_UL("num.query.flags.AD", s->svr.qbit_AD);
354 	PR_UL("num.query.flags.CD", s->svr.qbit_CD);
355 	PR_UL("num.query.edns.present", s->svr.qEDNS);
356 	PR_UL("num.query.edns.DO", s->svr.qEDNS_DO);
357 
358 	/* RCODE */
359 	for(i=0; i<UB_STATS_RCODE_NUM; i++) {
360 		/* Always include RCODEs 0-5 */
361 		if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
362 			continue;
363 		sldns_wire2str_rcode_buf(i, nm, sizeof(nm));
364 		PR_UL_SUB("num.answer.rcode", nm, s->svr.ans_rcode[i]);
365 	}
366 	if(!inhibit_zero || s->svr.ans_rcode_nodata) {
367 		PR_UL("num.answer.rcode.nodata", s->svr.ans_rcode_nodata);
368 	}
369 	/* iteration */
370 	PR_UL("num.query.ratelimited", s->svr.queries_ratelimited);
371 	/* validation */
372 	PR_UL("num.answer.secure", s->svr.ans_secure);
373 	PR_UL("num.answer.bogus", s->svr.ans_bogus);
374 	PR_UL("num.rrset.bogus", s->svr.rrset_bogus);
375 	PR_UL("num.query.aggressive.NOERROR", s->svr.num_neg_cache_noerror);
376 	PR_UL("num.query.aggressive.NXDOMAIN", s->svr.num_neg_cache_nxdomain);
377 	/* threat detection */
378 	PR_UL("unwanted.queries", s->svr.unwanted_queries);
379 	PR_UL("unwanted.replies", s->svr.unwanted_replies);
380 	/* cache counts */
381 	PR_UL("msg.cache.count", s->svr.msg_cache_count);
382 	PR_UL("rrset.cache.count", s->svr.rrset_cache_count);
383 	PR_UL("infra.cache.count", s->svr.infra_cache_count);
384 	PR_UL("key.cache.count", s->svr.key_cache_count);
385 	/* applied RPZ actions */
386 	for(i=0; i<UB_STATS_RPZ_ACTION_NUM; i++) {
387 		if(i == RPZ_NO_OVERRIDE_ACTION)
388 			continue;
389 		if(inhibit_zero && s->svr.rpz_action[i] == 0)
390 			continue;
391 		PR_UL_SUB("num.rpz.action", rpz_action_to_string(i), s->svr.rpz_action[i]);
392 	}
393 #ifdef USE_DNSCRYPT
394 	PR_UL("dnscrypt_shared_secret.cache.count",
395 			 s->svr.shared_secret_cache_count);
396 	PR_UL("num.query.dnscrypt.shared_secret.cachemiss",
397 			 s->svr.num_query_dnscrypt_secret_missed_cache);
398 	PR_UL("dnscrypt_nonce.cache.count", s->svr.nonce_cache_count);
399 	PR_UL("num.query.dnscrypt.replay",
400 			 s->svr.num_query_dnscrypt_replay);
401 #endif /* USE_DNSCRYPT */
402 	PR_UL("num.query.authzone.up", s->svr.num_query_authzone_up);
403 	PR_UL("num.query.authzone.down", s->svr.num_query_authzone_down);
404 #ifdef CLIENT_SUBNET
405 	PR_UL("num.query.subnet", s->svr.num_query_subnet);
406 	PR_UL("num.query.subnet_cache", s->svr.num_query_subnet_cache);
407 #endif
408 }
409 
410 /** print statistics out of memory structures */
411 static void do_stats_shm(struct config_file* cfg, struct ub_stats_info* stats,
412 	struct ub_shm_stat_info* shm_stat)
413 {
414 	int i;
415 	char nm[32];
416 	for(i=0; i<cfg->num_threads; i++) {
417 		snprintf(nm, sizeof(nm), "thread%d", i);
418 		pr_stats(nm, &stats[i+1]);
419 	}
420 	pr_stats("total", &stats[0]);
421 	print_uptime(shm_stat);
422 	if(cfg->stat_extended) {
423 		print_mem(shm_stat, &stats[0]);
424 		print_hist(stats);
425 		print_extended(stats);
426 	}
427 }
428 #endif /* HAVE_SHMGET */
429 
430 /** print statistics from shm memory segment */
431 static void print_stats_shm(const char* cfgfile)
432 {
433 #ifdef HAVE_SHMGET
434 	struct config_file* cfg;
435 	struct ub_stats_info* stats;
436 	struct ub_shm_stat_info* shm_stat;
437 	int id_ctl, id_arr;
438 	/* read config */
439 	if(!(cfg = config_create()))
440 		fatal_exit("out of memory");
441 	if(!config_read(cfg, cfgfile, NULL))
442 		fatal_exit("could not read config file");
443 	/* get shm segments */
444 	id_ctl = shmget(cfg->shm_key, sizeof(int), SHM_R);
445 	if(id_ctl == -1) {
446 		fatal_exit("shmget(%d): %s", cfg->shm_key, strerror(errno));
447 	}
448 	id_arr = shmget(cfg->shm_key+1, sizeof(int), SHM_R);
449 	if(id_arr == -1) {
450 		fatal_exit("shmget(%d): %s", cfg->shm_key+1, strerror(errno));
451 	}
452 	shm_stat = (struct ub_shm_stat_info*)shmat(id_ctl, NULL, SHM_RDONLY);
453 	if(shm_stat == (void*)-1) {
454 		fatal_exit("shmat(%d): %s", id_ctl, strerror(errno));
455 	}
456 	stats = (struct ub_stats_info*)shmat(id_arr, NULL, SHM_RDONLY);
457 	if(stats == (void*)-1) {
458 		fatal_exit("shmat(%d): %s", id_arr, strerror(errno));
459 	}
460 
461 	/* print the stats */
462 	do_stats_shm(cfg, stats, shm_stat);
463 
464 	/* shutdown */
465 	shmdt(shm_stat);
466 	shmdt(stats);
467 	config_delete(cfg);
468 #else
469 	(void)cfgfile;
470 #endif /* HAVE_SHMGET */
471 }
472 
473 /** exit with ssl error */
474 static void ssl_err(const char* s)
475 {
476 	fprintf(stderr, "error: %s\n", s);
477 	ERR_print_errors_fp(stderr);
478 	exit(1);
479 }
480 
481 /** exit with ssl error related to a file path */
482 static void ssl_path_err(const char* s, const char *path)
483 {
484 	unsigned long err;
485 	err = ERR_peek_error();
486 	if (ERR_GET_LIB(err) == ERR_LIB_SYS &&
487 		(ERR_GET_FUNC(err) == SYS_F_FOPEN ||
488 		 ERR_GET_FUNC(err) == SYS_F_FREAD) ) {
489 		fprintf(stderr, "error: %s\n%s: %s\n",
490 			s, path, ERR_reason_error_string(err));
491 		exit(1);
492 	} else {
493 		ssl_err(s);
494 	}
495 }
496 
497 /** setup SSL context */
498 static SSL_CTX*
499 setup_ctx(struct config_file* cfg)
500 {
501 	char* s_cert=NULL, *c_key=NULL, *c_cert=NULL;
502 	SSL_CTX* ctx;
503 
504 	if(!(options_remote_is_address(cfg) && cfg->control_use_cert))
505 		return NULL;
506 	s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
507 	c_key = fname_after_chroot(cfg->control_key_file, cfg, 1);
508 	c_cert = fname_after_chroot(cfg->control_cert_file, cfg, 1);
509 	if(!s_cert || !c_key || !c_cert)
510 		fatal_exit("out of memory");
511 	ctx = SSL_CTX_new(SSLv23_client_method());
512 	if(!ctx)
513 		ssl_err("could not allocate SSL_CTX pointer");
514 #if SSL_OP_NO_SSLv2 != 0
515 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
516 		!= SSL_OP_NO_SSLv2)
517 		ssl_err("could not set SSL_OP_NO_SSLv2");
518 #endif
519 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
520 		!= SSL_OP_NO_SSLv3)
521 		ssl_err("could not set SSL_OP_NO_SSLv3");
522 #if defined(SSL_OP_NO_RENEGOTIATION)
523 	/* disable client renegotiation */
524 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
525 		SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION)
526 		ssl_err("could not set SSL_OP_NO_RENEGOTIATION");
527 #endif
528 	if(!SSL_CTX_use_certificate_chain_file(ctx,c_cert))
529 		ssl_path_err("Error setting up SSL_CTX client cert", c_cert);
530 	if (!SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM))
531 		ssl_path_err("Error setting up SSL_CTX client key", c_key);
532 	if (!SSL_CTX_check_private_key(ctx))
533 		ssl_err("Error setting up SSL_CTX client key");
534 	if (SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1)
535 		ssl_path_err("Error setting up SSL_CTX verify, server cert",
536 			     s_cert);
537 	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
538 
539 	free(s_cert);
540 	free(c_key);
541 	free(c_cert);
542 	return ctx;
543 }
544 
545 /** contact the server with TCP connect */
546 static int
547 contact_server(const char* svr, struct config_file* cfg, int statuscmd)
548 {
549 	struct sockaddr_storage addr;
550 	socklen_t addrlen;
551 	int addrfamily = 0, proto = IPPROTO_TCP;
552 	int fd, useport = 1;
553 	/* use svr or the first config entry */
554 	if(!svr) {
555 		if(cfg->control_ifs.first) {
556 			svr = cfg->control_ifs.first->str;
557 		} else if(cfg->do_ip4) {
558 			svr = "127.0.0.1";
559 		} else {
560 			svr = "::1";
561 		}
562 		/* config 0 addr (everything), means ask localhost */
563 		if(strcmp(svr, "0.0.0.0") == 0)
564 			svr = "127.0.0.1";
565 		else if(strcmp(svr, "::0") == 0 ||
566 			strcmp(svr, "0::0") == 0 ||
567 			strcmp(svr, "0::") == 0 ||
568 			strcmp(svr, "::") == 0)
569 			svr = "::1";
570 	}
571 	if(strchr(svr, '@')) {
572 		if(!extstrtoaddr(svr, &addr, &addrlen))
573 			fatal_exit("could not parse IP@port: %s", svr);
574 #ifdef HAVE_SYS_UN_H
575 	} else if(svr[0] == '/') {
576 		struct sockaddr_un* usock = (struct sockaddr_un *) &addr;
577 		usock->sun_family = AF_LOCAL;
578 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
579 		usock->sun_len = (unsigned)sizeof(usock);
580 #endif
581 		(void)strlcpy(usock->sun_path, svr, sizeof(usock->sun_path));
582 		addrlen = (socklen_t)sizeof(struct sockaddr_un);
583 		addrfamily = AF_LOCAL;
584 		useport = 0;
585 		proto = 0;
586 #endif
587 	} else {
588 		if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen))
589 			fatal_exit("could not parse IP: %s", svr);
590 	}
591 
592 	if(addrfamily == 0)
593 		addrfamily = addr_is_ip6(&addr, addrlen)?PF_INET6:PF_INET;
594 	fd = socket(addrfamily, SOCK_STREAM, proto);
595 	if(fd == -1) {
596 #ifndef USE_WINSOCK
597 		fatal_exit("socket: %s", strerror(errno));
598 #else
599 		fatal_exit("socket: %s", wsa_strerror(WSAGetLastError()));
600 #endif
601 	}
602 	if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) {
603 #ifndef USE_WINSOCK
604 		int err = errno;
605 		if(!useport) log_err("connect: %s for %s", strerror(err), svr);
606 		else log_err_addr("connect", strerror(err), &addr, addrlen);
607 		if(err == ECONNREFUSED && statuscmd) {
608 			printf("unbound is stopped\n");
609 			exit(3);
610 		}
611 #else
612 		int wsaerr = WSAGetLastError();
613 		if(!useport) log_err("connect: %s for %s", wsa_strerror(wsaerr), svr);
614 		else log_err_addr("connect", wsa_strerror(wsaerr), &addr, addrlen);
615 		if(wsaerr == WSAECONNREFUSED && statuscmd) {
616 			printf("unbound is stopped\n");
617 			exit(3);
618 		}
619 #endif
620 		exit(1);
621 	}
622 	return fd;
623 }
624 
625 /** setup SSL on the connection */
626 static SSL*
627 setup_ssl(SSL_CTX* ctx, int fd)
628 {
629 	SSL* ssl;
630 	X509* x;
631 	int r;
632 
633 	if(!ctx) return NULL;
634 	ssl = SSL_new(ctx);
635 	if(!ssl)
636 		ssl_err("could not SSL_new");
637 	SSL_set_connect_state(ssl);
638 	(void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
639 	if(!SSL_set_fd(ssl, fd))
640 		ssl_err("could not SSL_set_fd");
641 	while(1) {
642 		ERR_clear_error();
643 		if( (r=SSL_do_handshake(ssl)) == 1)
644 			break;
645 		r = SSL_get_error(ssl, r);
646 		if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
647 			ssl_err("SSL handshake failed");
648 		/* wants to be called again */
649 	}
650 
651 	/* check authenticity of server */
652 	if(SSL_get_verify_result(ssl) != X509_V_OK)
653 		ssl_err("SSL verification failed");
654 	x = SSL_get_peer_certificate(ssl);
655 	if(!x)
656 		ssl_err("Server presented no peer certificate");
657 	X509_free(x);
658 
659 	return ssl;
660 }
661 
662 /** read from ssl or fd, fatalexit on error, 0 EOF, 1 success */
663 static int
664 remote_read(SSL* ssl, int fd, char* buf, size_t len)
665 {
666 	if(ssl) {
667 		int r;
668 		ERR_clear_error();
669 		if((r = SSL_read(ssl, buf, (int)len-1)) <= 0) {
670 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
671 				/* EOF */
672 				return 0;
673 			}
674 			ssl_err("could not SSL_read");
675 		}
676 		buf[r] = 0;
677 	} else {
678 		ssize_t rr = recv(fd, buf, len-1, 0);
679 		if(rr <= 0) {
680 			if(rr == 0) {
681 				/* EOF */
682 				return 0;
683 			}
684 #ifndef USE_WINSOCK
685 			fatal_exit("could not recv: %s", strerror(errno));
686 #else
687 			fatal_exit("could not recv: %s", wsa_strerror(WSAGetLastError()));
688 #endif
689 		}
690 		buf[rr] = 0;
691 	}
692 	return 1;
693 }
694 
695 /** write to ssl or fd, fatalexit on error */
696 static void
697 remote_write(SSL* ssl, int fd, const char* buf, size_t len)
698 {
699 	if(ssl) {
700 		if(SSL_write(ssl, buf, (int)len) <= 0)
701 			ssl_err("could not SSL_write");
702 	} else {
703 		if(send(fd, buf, len, 0) < (ssize_t)len) {
704 #ifndef USE_WINSOCK
705 			fatal_exit("could not send: %s", strerror(errno));
706 #else
707 			fatal_exit("could not send: %s", wsa_strerror(WSAGetLastError()));
708 #endif
709 		}
710 	}
711 }
712 
713 /** check args, to see if too many args. Because when a file is sent it
714  * would wait for the terminal, and we can check for too many arguments,
715  * eg. user put arguments on the commandline. */
716 static void
717 check_args_for_listcmd(int argc, char* argv[])
718 {
719 	if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
720 		strcmp(argv[0], "local_zones_remove") == 0 ||
721 		strcmp(argv[0], "local_datas") == 0 ||
722 		strcmp(argv[0], "local_datas_remove") == 0) &&
723 		argc >= 2) {
724 		fatal_exit("too many arguments for command '%s', "
725 			"content is piped in from stdin", argv[0]);
726 	}
727 	if(argc >= 1 && (strcmp(argv[0], "view_local_datas") == 0 ||
728 		strcmp(argv[0], "view_local_datas_remove") == 0) &&
729 		argc >= 3) {
730 		fatal_exit("too many arguments for command '%s', "
731 			"content is piped in from stdin", argv[0]);
732 	}
733 }
734 
735 /** send stdin to server */
736 static void
737 send_file(SSL* ssl, int fd, FILE* in, char* buf, size_t sz)
738 {
739 	while(fgets(buf, (int)sz, in)) {
740 		remote_write(ssl, fd, buf, strlen(buf));
741 	}
742 }
743 
744 /** send end-of-file marker to server */
745 static void
746 send_eof(SSL* ssl, int fd)
747 {
748 	char e[] = {0x04, 0x0a};
749 	remote_write(ssl, fd, e, sizeof(e));
750 }
751 
752 /** send command and display result */
753 static int
754 go_cmd(SSL* ssl, int fd, int quiet, int argc, char* argv[])
755 {
756 	char pre[10];
757 	const char* space=" ";
758 	const char* newline="\n";
759 	int was_error = 0, first_line = 1;
760 	int i;
761 	char buf[1024];
762 	snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
763 	remote_write(ssl, fd, pre, strlen(pre));
764 	for(i=0; i<argc; i++) {
765 		remote_write(ssl, fd, space, strlen(space));
766 		remote_write(ssl, fd, argv[i], strlen(argv[i]));
767 	}
768 	remote_write(ssl, fd, newline, strlen(newline));
769 
770 	if(argc == 1 && strcmp(argv[0], "load_cache") == 0) {
771 		send_file(ssl, fd, stdin, buf, sizeof(buf));
772 	}
773 	else if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
774 		strcmp(argv[0], "local_zones_remove") == 0 ||
775 		strcmp(argv[0], "local_datas") == 0 ||
776 		strcmp(argv[0], "view_local_datas") == 0 ||
777 		strcmp(argv[0], "local_datas_remove") == 0 ||
778 		strcmp(argv[0], "view_local_datas_remove") == 0)) {
779 		send_file(ssl, fd, stdin, buf, sizeof(buf));
780 		send_eof(ssl, fd);
781 	}
782 
783 	while(1) {
784 		if(remote_read(ssl, fd, buf, sizeof(buf)) == 0) {
785 			break; /* EOF */
786 		}
787 		if(first_line && strncmp(buf, "error", 5) == 0) {
788 			printf("%s", buf);
789 			was_error = 1;
790 		} else if (!quiet)
791 			printf("%s", buf);
792 
793 		first_line = 0;
794 	}
795 	return was_error;
796 }
797 
798 /** go ahead and read config, contact server and perform command and display */
799 static int
800 go(const char* cfgfile, char* svr, int quiet, int argc, char* argv[])
801 {
802 	struct config_file* cfg;
803 	int fd, ret;
804 	SSL_CTX* ctx;
805 	SSL* ssl;
806 
807 	/* read config */
808 	if(!(cfg = config_create()))
809 		fatal_exit("out of memory");
810 	if(!config_read(cfg, cfgfile, NULL))
811 		fatal_exit("could not read config file");
812 	if(!cfg->remote_control_enable)
813 		log_warn("control-enable is 'no' in the config file.");
814 #ifdef UB_ON_WINDOWS
815 	w_config_adjust_directory(cfg);
816 #endif
817 	ctx = setup_ctx(cfg);
818 
819 	/* contact server */
820 	fd = contact_server(svr, cfg, argc>0&&strcmp(argv[0],"status")==0);
821 	ssl = setup_ssl(ctx, fd);
822 
823 	/* send command */
824 	ret = go_cmd(ssl, fd, quiet, argc, argv);
825 
826 	if(ssl) SSL_free(ssl);
827 #ifndef USE_WINSOCK
828 	close(fd);
829 #else
830 	closesocket(fd);
831 #endif
832 	if(ctx) SSL_CTX_free(ctx);
833 	config_delete(cfg);
834 	return ret;
835 }
836 
837 /** getopt global, in case header files fail to declare it. */
838 extern int optind;
839 /** getopt global, in case header files fail to declare it. */
840 extern char* optarg;
841 
842 /** Main routine for unbound-control */
843 int main(int argc, char* argv[])
844 {
845 	int c, ret;
846 	int quiet = 0;
847 	const char* cfgfile = CONFIGFILE;
848 	char* svr = NULL;
849 #ifdef USE_WINSOCK
850 	int r;
851 	WSADATA wsa_data;
852 #endif
853 #ifdef USE_THREAD_DEBUG
854 	/* stop the file output from unbound-control, overwrites the servers */
855 	extern int check_locking_order;
856 	check_locking_order = 0;
857 #endif /* USE_THREAD_DEBUG */
858 	log_ident_set("unbound-control");
859 	log_init(NULL, 0, NULL);
860 	checklock_start();
861 #ifdef USE_WINSOCK
862 	/* use registry config file in preference to compiletime location */
863 	if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
864 		cfgfile = CONFIGFILE;
865 #endif
866 	/* parse the options */
867 	while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
868 		switch(c) {
869 		case 'c':
870 			cfgfile = optarg;
871 			break;
872 		case 's':
873 			svr = optarg;
874 			break;
875 		case 'q':
876 			quiet = 1;
877 			break;
878 		case '?':
879 		case 'h':
880 		default:
881 			usage();
882 		}
883 	}
884 	argc -= optind;
885 	argv += optind;
886 	if(argc == 0)
887 		usage();
888 	if(argc >= 1 && strcmp(argv[0], "start")==0) {
889 #if defined(TARGET_OS_TV) || defined(TARGET_OS_WATCH)
890 		fatal_exit("could not exec unbound: %s",
891 			strerror(ENOSYS));
892 #else
893 		if(execlp("unbound", "unbound", "-c", cfgfile,
894 			(char*)NULL) < 0) {
895 			fatal_exit("could not exec unbound: %s",
896 				strerror(errno));
897 		}
898 #endif
899 	}
900 	if(argc >= 1 && strcmp(argv[0], "stats_shm")==0) {
901 		print_stats_shm(cfgfile);
902 		return 0;
903 	}
904 	check_args_for_listcmd(argc, argv);
905 
906 #ifdef USE_WINSOCK
907 	if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
908 		fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
909 #endif
910 
911 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
912 	ERR_load_crypto_strings();
913 #endif
914 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
915 	ERR_load_SSL_strings();
916 #endif
917 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
918 #  ifndef S_SPLINT_S
919 	OpenSSL_add_all_algorithms();
920 #  endif
921 #else
922 	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
923 		| OPENSSL_INIT_ADD_ALL_DIGESTS
924 		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
925 #endif
926 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
927 	(void)SSL_library_init();
928 #else
929 	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
930 #endif
931 
932 	if(!RAND_status()) {
933 		/* try to seed it */
934 		unsigned char buf[256];
935 		unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
936 		unsigned int v = seed;
937 		size_t i;
938 		for(i=0; i<256/sizeof(v); i++) {
939 			memmove(buf+i*sizeof(v), &v, sizeof(v));
940 			v = v*seed + (unsigned int)i;
941 		}
942 		RAND_seed(buf, 256);
943 		log_warn("no entropy, seeding openssl PRNG with time\n");
944 	}
945 
946 	ret = go(cfgfile, svr, quiet, argc, argv);
947 
948 #ifdef USE_WINSOCK
949 	WSACleanup();
950 #endif
951 	checklock_stop();
952 	return ret;
953 }
954