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