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