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