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