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