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