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