xref: /freebsd/contrib/unbound/smallapp/unbound-control.c (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
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 	PR_LL("mem.http.query_buffer", s->svr.mem_http2_query_buffer);
282 	PR_LL("mem.http.response_buffer", s->svr.mem_http2_response_buffer);
283 }
284 
285 /** print histogram */
286 static void print_hist(struct ub_stats_info* s)
287 {
288 	struct timehist* hist;
289 	size_t i;
290 	hist = timehist_setup();
291 	if(!hist)
292 		fatal_exit("out of memory");
293 	timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
294 	for(i=0; i<hist->num; i++) {
295 		printf("histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
296 			(int)hist->buckets[i].lower.tv_sec,
297 			(int)hist->buckets[i].lower.tv_usec,
298 			(int)hist->buckets[i].upper.tv_sec,
299 			(int)hist->buckets[i].upper.tv_usec,
300 			(unsigned long)hist->buckets[i].count);
301 	}
302 	timehist_delete(hist);
303 }
304 
305 /** print extended */
306 static void print_extended(struct ub_stats_info* s)
307 {
308 	int i;
309 	char nm[16];
310 
311 	/* TYPE */
312 	for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
313 		if(inhibit_zero && s->svr.qtype[i] == 0)
314 			continue;
315 		sldns_wire2str_type_buf((uint16_t)i, nm, sizeof(nm));
316 		PR_UL_SUB("num.query.type", nm, s->svr.qtype[i]);
317 	}
318 	if(!inhibit_zero || s->svr.qtype_big) {
319 		PR_UL("num.query.type.other", s->svr.qtype_big);
320 	}
321 
322 	/* CLASS */
323 	for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
324 		if(inhibit_zero && s->svr.qclass[i] == 0)
325 			continue;
326 		sldns_wire2str_class_buf((uint16_t)i, nm, sizeof(nm));
327 		PR_UL_SUB("num.query.class", nm, s->svr.qclass[i]);
328 	}
329 	if(!inhibit_zero || s->svr.qclass_big) {
330 		PR_UL("num.query.class.other", s->svr.qclass_big);
331 	}
332 
333 	/* OPCODE */
334 	for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
335 		if(inhibit_zero && s->svr.qopcode[i] == 0)
336 			continue;
337 		sldns_wire2str_opcode_buf(i, nm, sizeof(nm));
338 		PR_UL_SUB("num.query.opcode", nm, s->svr.qopcode[i]);
339 	}
340 
341 	/* transport */
342 	PR_UL("num.query.tcp", s->svr.qtcp);
343 	PR_UL("num.query.tcpout", s->svr.qtcp_outgoing);
344 	PR_UL("num.query.tls", s->svr.qtls);
345 	PR_UL("num.query.tls_resume", s->svr.qtls_resume);
346 	PR_UL("num.query.ipv6", s->svr.qipv6);
347 	PR_UL("num.query.https", s->svr.qhttps);
348 
349 	/* flags */
350 	PR_UL("num.query.flags.QR", s->svr.qbit_QR);
351 	PR_UL("num.query.flags.AA", s->svr.qbit_AA);
352 	PR_UL("num.query.flags.TC", s->svr.qbit_TC);
353 	PR_UL("num.query.flags.RD", s->svr.qbit_RD);
354 	PR_UL("num.query.flags.RA", s->svr.qbit_RA);
355 	PR_UL("num.query.flags.Z", s->svr.qbit_Z);
356 	PR_UL("num.query.flags.AD", s->svr.qbit_AD);
357 	PR_UL("num.query.flags.CD", s->svr.qbit_CD);
358 	PR_UL("num.query.edns.present", s->svr.qEDNS);
359 	PR_UL("num.query.edns.DO", s->svr.qEDNS_DO);
360 
361 	/* RCODE */
362 	for(i=0; i<UB_STATS_RCODE_NUM; i++) {
363 		/* Always include RCODEs 0-5 */
364 		if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
365 			continue;
366 		sldns_wire2str_rcode_buf(i, nm, sizeof(nm));
367 		PR_UL_SUB("num.answer.rcode", nm, s->svr.ans_rcode[i]);
368 	}
369 	if(!inhibit_zero || s->svr.ans_rcode_nodata) {
370 		PR_UL("num.answer.rcode.nodata", s->svr.ans_rcode_nodata);
371 	}
372 	/* iteration */
373 	PR_UL("num.query.ratelimited", s->svr.queries_ratelimited);
374 	/* validation */
375 	PR_UL("num.answer.secure", s->svr.ans_secure);
376 	PR_UL("num.answer.bogus", s->svr.ans_bogus);
377 	PR_UL("num.rrset.bogus", s->svr.rrset_bogus);
378 	PR_UL("num.query.aggressive.NOERROR", s->svr.num_neg_cache_noerror);
379 	PR_UL("num.query.aggressive.NXDOMAIN", s->svr.num_neg_cache_nxdomain);
380 	/* threat detection */
381 	PR_UL("unwanted.queries", s->svr.unwanted_queries);
382 	PR_UL("unwanted.replies", s->svr.unwanted_replies);
383 	/* cache counts */
384 	PR_UL("msg.cache.count", s->svr.msg_cache_count);
385 	PR_UL("rrset.cache.count", s->svr.rrset_cache_count);
386 	PR_UL("infra.cache.count", s->svr.infra_cache_count);
387 	PR_UL("key.cache.count", s->svr.key_cache_count);
388 	/* applied RPZ actions */
389 	for(i=0; i<UB_STATS_RPZ_ACTION_NUM; i++) {
390 		if(i == RPZ_NO_OVERRIDE_ACTION)
391 			continue;
392 		if(inhibit_zero && s->svr.rpz_action[i] == 0)
393 			continue;
394 		PR_UL_SUB("num.rpz.action", rpz_action_to_string(i), s->svr.rpz_action[i]);
395 	}
396 #ifdef USE_DNSCRYPT
397 	PR_UL("dnscrypt_shared_secret.cache.count",
398 			 s->svr.shared_secret_cache_count);
399 	PR_UL("num.query.dnscrypt.shared_secret.cachemiss",
400 			 s->svr.num_query_dnscrypt_secret_missed_cache);
401 	PR_UL("dnscrypt_nonce.cache.count", s->svr.nonce_cache_count);
402 	PR_UL("num.query.dnscrypt.replay",
403 			 s->svr.num_query_dnscrypt_replay);
404 #endif /* USE_DNSCRYPT */
405 	PR_UL("num.query.authzone.up", s->svr.num_query_authzone_up);
406 	PR_UL("num.query.authzone.down", s->svr.num_query_authzone_down);
407 #ifdef CLIENT_SUBNET
408 	PR_UL("num.query.subnet", s->svr.num_query_subnet);
409 	PR_UL("num.query.subnet_cache", s->svr.num_query_subnet_cache);
410 #endif
411 }
412 
413 /** print statistics out of memory structures */
414 static void do_stats_shm(struct config_file* cfg, struct ub_stats_info* stats,
415 	struct ub_shm_stat_info* shm_stat)
416 {
417 	int i;
418 	char nm[32];
419 	for(i=0; i<cfg->num_threads; i++) {
420 		snprintf(nm, sizeof(nm), "thread%d", i);
421 		pr_stats(nm, &stats[i+1]);
422 	}
423 	pr_stats("total", &stats[0]);
424 	print_uptime(shm_stat);
425 	if(cfg->stat_extended) {
426 		print_mem(shm_stat, &stats[0]);
427 		print_hist(stats);
428 		print_extended(stats);
429 	}
430 }
431 #endif /* HAVE_SHMGET */
432 
433 /** print statistics from shm memory segment */
434 static void print_stats_shm(const char* cfgfile)
435 {
436 #ifdef HAVE_SHMGET
437 	struct config_file* cfg;
438 	struct ub_stats_info* stats;
439 	struct ub_shm_stat_info* shm_stat;
440 	int id_ctl, id_arr;
441 	/* read config */
442 	if(!(cfg = config_create()))
443 		fatal_exit("out of memory");
444 	if(!config_read(cfg, cfgfile, NULL))
445 		fatal_exit("could not read config file");
446 	/* get shm segments */
447 	id_ctl = shmget(cfg->shm_key, sizeof(int), SHM_R);
448 	if(id_ctl == -1) {
449 		fatal_exit("shmget(%d): %s", cfg->shm_key, strerror(errno));
450 	}
451 	id_arr = shmget(cfg->shm_key+1, sizeof(int), SHM_R);
452 	if(id_arr == -1) {
453 		fatal_exit("shmget(%d): %s", cfg->shm_key+1, strerror(errno));
454 	}
455 	shm_stat = (struct ub_shm_stat_info*)shmat(id_ctl, NULL, SHM_RDONLY);
456 	if(shm_stat == (void*)-1) {
457 		fatal_exit("shmat(%d): %s", id_ctl, strerror(errno));
458 	}
459 	stats = (struct ub_stats_info*)shmat(id_arr, NULL, SHM_RDONLY);
460 	if(stats == (void*)-1) {
461 		fatal_exit("shmat(%d): %s", id_arr, strerror(errno));
462 	}
463 
464 	/* print the stats */
465 	do_stats_shm(cfg, stats, shm_stat);
466 
467 	/* shutdown */
468 	shmdt(shm_stat);
469 	shmdt(stats);
470 	config_delete(cfg);
471 #else
472 	(void)cfgfile;
473 #endif /* HAVE_SHMGET */
474 }
475 
476 /** exit with ssl error */
477 static void ssl_err(const char* s)
478 {
479 	fprintf(stderr, "error: %s\n", s);
480 	ERR_print_errors_fp(stderr);
481 	exit(1);
482 }
483 
484 /** exit with ssl error related to a file path */
485 static void ssl_path_err(const char* s, const char *path)
486 {
487 	unsigned long err;
488 	err = ERR_peek_error();
489 	if (ERR_GET_LIB(err) == ERR_LIB_SYS &&
490 		(ERR_GET_FUNC(err) == SYS_F_FOPEN ||
491 		 ERR_GET_FUNC(err) == SYS_F_FREAD) ) {
492 		fprintf(stderr, "error: %s\n%s: %s\n",
493 			s, path, ERR_reason_error_string(err));
494 		exit(1);
495 	} else {
496 		ssl_err(s);
497 	}
498 }
499 
500 /** setup SSL context */
501 static SSL_CTX*
502 setup_ctx(struct config_file* cfg)
503 {
504 	char* s_cert=NULL, *c_key=NULL, *c_cert=NULL;
505 	SSL_CTX* ctx;
506 
507 	if(!(options_remote_is_address(cfg) && cfg->control_use_cert))
508 		return NULL;
509 	s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
510 	c_key = fname_after_chroot(cfg->control_key_file, cfg, 1);
511 	c_cert = fname_after_chroot(cfg->control_cert_file, cfg, 1);
512 	if(!s_cert || !c_key || !c_cert)
513 		fatal_exit("out of memory");
514 	ctx = SSL_CTX_new(SSLv23_client_method());
515 	if(!ctx)
516 		ssl_err("could not allocate SSL_CTX pointer");
517 #if SSL_OP_NO_SSLv2 != 0
518 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
519 		!= SSL_OP_NO_SSLv2)
520 		ssl_err("could not set SSL_OP_NO_SSLv2");
521 #endif
522 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
523 		!= SSL_OP_NO_SSLv3)
524 		ssl_err("could not set SSL_OP_NO_SSLv3");
525 #if defined(SSL_OP_NO_RENEGOTIATION)
526 	/* disable client renegotiation */
527 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
528 		SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION)
529 		ssl_err("could not set SSL_OP_NO_RENEGOTIATION");
530 #endif
531 	if(!SSL_CTX_use_certificate_chain_file(ctx,c_cert))
532 		ssl_path_err("Error setting up SSL_CTX client cert", c_cert);
533 	if (!SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM))
534 		ssl_path_err("Error setting up SSL_CTX client key", c_key);
535 	if (!SSL_CTX_check_private_key(ctx))
536 		ssl_err("Error setting up SSL_CTX client key");
537 	if (SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1)
538 		ssl_path_err("Error setting up SSL_CTX verify, server cert",
539 			     s_cert);
540 	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
541 
542 	free(s_cert);
543 	free(c_key);
544 	free(c_cert);
545 	return ctx;
546 }
547 
548 /** contact the server with TCP connect */
549 static int
550 contact_server(const char* svr, struct config_file* cfg, int statuscmd)
551 {
552 	struct sockaddr_storage addr;
553 	socklen_t addrlen;
554 	int addrfamily = 0, proto = IPPROTO_TCP;
555 	int fd, useport = 1;
556 	/* use svr or the first config entry */
557 	if(!svr) {
558 		if(cfg->control_ifs.first) {
559 			svr = cfg->control_ifs.first->str;
560 		} else if(cfg->do_ip4) {
561 			svr = "127.0.0.1";
562 		} else {
563 			svr = "::1";
564 		}
565 		/* config 0 addr (everything), means ask localhost */
566 		if(strcmp(svr, "0.0.0.0") == 0)
567 			svr = "127.0.0.1";
568 		else if(strcmp(svr, "::0") == 0 ||
569 			strcmp(svr, "0::0") == 0 ||
570 			strcmp(svr, "0::") == 0 ||
571 			strcmp(svr, "::") == 0)
572 			svr = "::1";
573 	}
574 	if(strchr(svr, '@')) {
575 		if(!extstrtoaddr(svr, &addr, &addrlen))
576 			fatal_exit("could not parse IP@port: %s", svr);
577 #ifdef HAVE_SYS_UN_H
578 	} else if(svr[0] == '/') {
579 		struct sockaddr_un* usock = (struct sockaddr_un *) &addr;
580 		usock->sun_family = AF_LOCAL;
581 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
582 		usock->sun_len = (unsigned)sizeof(usock);
583 #endif
584 		(void)strlcpy(usock->sun_path, svr, sizeof(usock->sun_path));
585 		addrlen = (socklen_t)sizeof(struct sockaddr_un);
586 		addrfamily = AF_LOCAL;
587 		useport = 0;
588 		proto = 0;
589 #endif
590 	} else {
591 		if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen))
592 			fatal_exit("could not parse IP: %s", svr);
593 	}
594 
595 	if(addrfamily == 0)
596 		addrfamily = addr_is_ip6(&addr, addrlen)?PF_INET6:PF_INET;
597 	fd = socket(addrfamily, SOCK_STREAM, proto);
598 	if(fd == -1) {
599 		fatal_exit("socket: %s", sock_strerror(errno));
600 	}
601 	if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) {
602 #ifndef USE_WINSOCK
603 		int err = errno;
604 		if(!useport) log_err("connect: %s for %s", strerror(err), svr);
605 		else log_err_addr("connect", strerror(err), &addr, addrlen);
606 		if(err == ECONNREFUSED && statuscmd) {
607 			printf("unbound is stopped\n");
608 			exit(3);
609 		}
610 #else
611 		int wsaerr = WSAGetLastError();
612 		if(!useport) log_err("connect: %s for %s", wsa_strerror(wsaerr), svr);
613 		else log_err_addr("connect", wsa_strerror(wsaerr), &addr, addrlen);
614 		if(wsaerr == WSAECONNREFUSED && statuscmd) {
615 			printf("unbound is stopped\n");
616 			exit(3);
617 		}
618 #endif
619 		exit(1);
620 	}
621 	return fd;
622 }
623 
624 /** setup SSL on the connection */
625 static SSL*
626 setup_ssl(SSL_CTX* ctx, int fd)
627 {
628 	SSL* ssl;
629 	X509* x;
630 	int r;
631 
632 	if(!ctx) return NULL;
633 	ssl = SSL_new(ctx);
634 	if(!ssl)
635 		ssl_err("could not SSL_new");
636 	SSL_set_connect_state(ssl);
637 	(void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
638 	if(!SSL_set_fd(ssl, fd))
639 		ssl_err("could not SSL_set_fd");
640 	while(1) {
641 		ERR_clear_error();
642 		if( (r=SSL_do_handshake(ssl)) == 1)
643 			break;
644 		r = SSL_get_error(ssl, r);
645 		if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
646 			ssl_err("SSL handshake failed");
647 		/* wants to be called again */
648 	}
649 
650 	/* check authenticity of server */
651 	if(SSL_get_verify_result(ssl) != X509_V_OK)
652 		ssl_err("SSL verification failed");
653 	x = SSL_get_peer_certificate(ssl);
654 	if(!x)
655 		ssl_err("Server presented no peer certificate");
656 	X509_free(x);
657 
658 	return ssl;
659 }
660 
661 /** read from ssl or fd, fatalexit on error, 0 EOF, 1 success */
662 static int
663 remote_read(SSL* ssl, int fd, char* buf, size_t len)
664 {
665 	if(ssl) {
666 		int r;
667 		ERR_clear_error();
668 		if((r = SSL_read(ssl, buf, (int)len-1)) <= 0) {
669 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
670 				/* EOF */
671 				return 0;
672 			}
673 			ssl_err("could not SSL_read");
674 		}
675 		buf[r] = 0;
676 	} else {
677 		ssize_t rr = recv(fd, buf, len-1, 0);
678 		if(rr <= 0) {
679 			if(rr == 0) {
680 				/* EOF */
681 				return 0;
682 			}
683 			fatal_exit("could not recv: %s", sock_strerror(errno));
684 		}
685 		buf[rr] = 0;
686 	}
687 	return 1;
688 }
689 
690 /** write to ssl or fd, fatalexit on error */
691 static void
692 remote_write(SSL* ssl, int fd, const char* buf, size_t len)
693 {
694 	if(ssl) {
695 		if(SSL_write(ssl, buf, (int)len) <= 0)
696 			ssl_err("could not SSL_write");
697 	} else {
698 		if(send(fd, buf, len, 0) < (ssize_t)len) {
699 			fatal_exit("could not send: %s", sock_strerror(errno));
700 		}
701 	}
702 }
703 
704 /** check args, to see if too many args. Because when a file is sent it
705  * would wait for the terminal, and we can check for too many arguments,
706  * eg. user put arguments on the commandline. */
707 static void
708 check_args_for_listcmd(int argc, char* argv[])
709 {
710 	if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
711 		strcmp(argv[0], "local_zones_remove") == 0 ||
712 		strcmp(argv[0], "local_datas") == 0 ||
713 		strcmp(argv[0], "local_datas_remove") == 0) &&
714 		argc >= 2) {
715 		fatal_exit("too many arguments for command '%s', "
716 			"content is piped in from stdin", argv[0]);
717 	}
718 	if(argc >= 1 && (strcmp(argv[0], "view_local_datas") == 0 ||
719 		strcmp(argv[0], "view_local_datas_remove") == 0) &&
720 		argc >= 3) {
721 		fatal_exit("too many arguments for command '%s', "
722 			"content is piped in from stdin", argv[0]);
723 	}
724 }
725 
726 /** send stdin to server */
727 static void
728 send_file(SSL* ssl, int fd, FILE* in, char* buf, size_t sz)
729 {
730 	while(fgets(buf, (int)sz, in)) {
731 		remote_write(ssl, fd, buf, strlen(buf));
732 	}
733 }
734 
735 /** send end-of-file marker to server */
736 static void
737 send_eof(SSL* ssl, int fd)
738 {
739 	char e[] = {0x04, 0x0a};
740 	remote_write(ssl, fd, e, sizeof(e));
741 }
742 
743 /** send command and display result */
744 static int
745 go_cmd(SSL* ssl, int fd, int quiet, int argc, char* argv[])
746 {
747 	char pre[10];
748 	const char* space=" ";
749 	const char* newline="\n";
750 	int was_error = 0, first_line = 1;
751 	int i;
752 	char buf[1024];
753 	snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
754 	remote_write(ssl, fd, pre, strlen(pre));
755 	for(i=0; i<argc; i++) {
756 		remote_write(ssl, fd, space, strlen(space));
757 		remote_write(ssl, fd, argv[i], strlen(argv[i]));
758 	}
759 	remote_write(ssl, fd, newline, strlen(newline));
760 
761 	if(argc == 1 && strcmp(argv[0], "load_cache") == 0) {
762 		send_file(ssl, fd, stdin, buf, sizeof(buf));
763 	}
764 	else if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
765 		strcmp(argv[0], "local_zones_remove") == 0 ||
766 		strcmp(argv[0], "local_datas") == 0 ||
767 		strcmp(argv[0], "view_local_datas") == 0 ||
768 		strcmp(argv[0], "local_datas_remove") == 0 ||
769 		strcmp(argv[0], "view_local_datas_remove") == 0)) {
770 		send_file(ssl, fd, stdin, buf, sizeof(buf));
771 		send_eof(ssl, fd);
772 	}
773 
774 	while(1) {
775 		if(remote_read(ssl, fd, buf, sizeof(buf)) == 0) {
776 			break; /* EOF */
777 		}
778 		if(first_line && strncmp(buf, "error", 5) == 0) {
779 			printf("%s", buf);
780 			was_error = 1;
781 		} else if (!quiet)
782 			printf("%s", buf);
783 
784 		first_line = 0;
785 	}
786 	return was_error;
787 }
788 
789 /** go ahead and read config, contact server and perform command and display */
790 static int
791 go(const char* cfgfile, char* svr, int quiet, int argc, char* argv[])
792 {
793 	struct config_file* cfg;
794 	int fd, ret;
795 	SSL_CTX* ctx;
796 	SSL* ssl;
797 
798 	/* read config */
799 	if(!(cfg = config_create()))
800 		fatal_exit("out of memory");
801 	if(!config_read(cfg, cfgfile, NULL))
802 		fatal_exit("could not read config file");
803 	if(!cfg->remote_control_enable)
804 		log_warn("control-enable is 'no' in the config file.");
805 #ifdef UB_ON_WINDOWS
806 	w_config_adjust_directory(cfg);
807 #endif
808 	ctx = setup_ctx(cfg);
809 
810 	/* contact server */
811 	fd = contact_server(svr, cfg, argc>0&&strcmp(argv[0],"status")==0);
812 	ssl = setup_ssl(ctx, fd);
813 
814 	/* send command */
815 	ret = go_cmd(ssl, fd, quiet, argc, argv);
816 
817 	if(ssl) SSL_free(ssl);
818 	sock_close(fd);
819 	if(ctx) SSL_CTX_free(ctx);
820 	config_delete(cfg);
821 	return ret;
822 }
823 
824 /** getopt global, in case header files fail to declare it. */
825 extern int optind;
826 /** getopt global, in case header files fail to declare it. */
827 extern char* optarg;
828 
829 /** Main routine for unbound-control */
830 int main(int argc, char* argv[])
831 {
832 	int c, ret;
833 	int quiet = 0;
834 	const char* cfgfile = CONFIGFILE;
835 	char* svr = NULL;
836 #ifdef USE_WINSOCK
837 	int r;
838 	WSADATA wsa_data;
839 #endif
840 #ifdef USE_THREAD_DEBUG
841 	/* stop the file output from unbound-control, overwrites the servers */
842 	extern int check_locking_order;
843 	check_locking_order = 0;
844 #endif /* USE_THREAD_DEBUG */
845 	log_ident_set("unbound-control");
846 	log_init(NULL, 0, NULL);
847 	checklock_start();
848 #ifdef USE_WINSOCK
849 	/* use registry config file in preference to compiletime location */
850 	if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
851 		cfgfile = CONFIGFILE;
852 #endif
853 	/* parse the options */
854 	while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
855 		switch(c) {
856 		case 'c':
857 			cfgfile = optarg;
858 			break;
859 		case 's':
860 			svr = optarg;
861 			break;
862 		case 'q':
863 			quiet = 1;
864 			break;
865 		case '?':
866 		case 'h':
867 		default:
868 			usage();
869 		}
870 	}
871 	argc -= optind;
872 	argv += optind;
873 	if(argc == 0)
874 		usage();
875 	if(argc >= 1 && strcmp(argv[0], "start")==0) {
876 #if (defined(TARGET_OS_TV) && TARGET_OS_TV) || (defined(TARGET_OS_WATCH) && TARGET_OS_WATCH)
877 		fatal_exit("could not exec unbound: %s",
878 			strerror(ENOSYS));
879 #else
880 		if(execlp("unbound", "unbound", "-c", cfgfile,
881 			(char*)NULL) < 0) {
882 			fatal_exit("could not exec unbound: %s",
883 				strerror(errno));
884 		}
885 #endif
886 	}
887 	if(argc >= 1 && strcmp(argv[0], "stats_shm")==0) {
888 		print_stats_shm(cfgfile);
889 		return 0;
890 	}
891 	check_args_for_listcmd(argc, argv);
892 
893 #ifdef USE_WINSOCK
894 	if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
895 		fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
896 #endif
897 
898 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
899 	ERR_load_crypto_strings();
900 #endif
901 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
902 	ERR_load_SSL_strings();
903 #endif
904 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
905 #  ifndef S_SPLINT_S
906 	OpenSSL_add_all_algorithms();
907 #  endif
908 #else
909 	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
910 		| OPENSSL_INIT_ADD_ALL_DIGESTS
911 		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
912 #endif
913 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
914 	(void)SSL_library_init();
915 #else
916 	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
917 #endif
918 
919 	if(!RAND_status()) {
920 		/* try to seed it */
921 		unsigned char buf[256];
922 		unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
923 		unsigned int v = seed;
924 		size_t i;
925 		for(i=0; i<256/sizeof(v); i++) {
926 			memmove(buf+i*sizeof(v), &v, sizeof(v));
927 			v = v*seed + (unsigned int)i;
928 		}
929 		RAND_seed(buf, 256);
930 		log_warn("no entropy, seeding openssl PRNG with time\n");
931 	}
932 
933 	ret = go(cfgfile, svr, quiet, argc, argv);
934 
935 #ifdef USE_WINSOCK
936 	WSACleanup();
937 #endif
938 	checklock_stop();
939 	return ret;
940 }
941