Home | History | Annotate | Line # | Download | only in smallapp
unbound-control.c revision 1.1.1.4.2.1
      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:	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);
    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);
    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, SHM_RDONLY);
    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, SHM_RDONLY);
    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 defined(SSL_OP_NO_RENEGOTIATION)
    503 	/* disable client renegotiation */
    504 	if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
    505 		SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION)
    506 		ssl_err("could not set SSL_OP_NO_RENEGOTIATION");
    507 #endif
    508 	if(!SSL_CTX_use_certificate_chain_file(ctx,c_cert))
    509 		ssl_path_err("Error setting up SSL_CTX client cert", c_cert);
    510 	if (!SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM))
    511 		ssl_path_err("Error setting up SSL_CTX client key", c_key);
    512 	if (!SSL_CTX_check_private_key(ctx))
    513 		ssl_err("Error setting up SSL_CTX client key");
    514 	if (SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1)
    515 		ssl_path_err("Error setting up SSL_CTX verify, server cert",
    516 			     s_cert);
    517 	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
    518 
    519 	free(s_cert);
    520 	free(c_key);
    521 	free(c_cert);
    522 	return ctx;
    523 }
    524 
    525 /** contact the server with TCP connect */
    526 static int
    527 contact_server(const char* svr, struct config_file* cfg, int statuscmd)
    528 {
    529 	struct sockaddr_storage addr;
    530 	socklen_t addrlen;
    531 	int addrfamily = 0, proto = IPPROTO_TCP;
    532 	int fd, useport = 1;
    533 	/* use svr or the first config entry */
    534 	if(!svr) {
    535 		if(cfg->control_ifs.first) {
    536 			svr = cfg->control_ifs.first->str;
    537 		} else if(cfg->do_ip4) {
    538 			svr = "127.0.0.1";
    539 		} else {
    540 			svr = "::1";
    541 		}
    542 		/* config 0 addr (everything), means ask localhost */
    543 		if(strcmp(svr, "0.0.0.0") == 0)
    544 			svr = "127.0.0.1";
    545 		else if(strcmp(svr, "::0") == 0 ||
    546 			strcmp(svr, "0::0") == 0 ||
    547 			strcmp(svr, "0::") == 0 ||
    548 			strcmp(svr, "::") == 0)
    549 			svr = "::1";
    550 	}
    551 	if(strchr(svr, '@')) {
    552 		if(!extstrtoaddr(svr, &addr, &addrlen))
    553 			fatal_exit("could not parse IP@port: %s", svr);
    554 #ifdef HAVE_SYS_UN_H
    555 	} else if(svr[0] == '/') {
    556 		struct sockaddr_un* usock = (struct sockaddr_un *) &addr;
    557 		usock->sun_family = AF_LOCAL;
    558 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
    559 		usock->sun_len = (unsigned)sizeof(usock);
    560 #endif
    561 		(void)strlcpy(usock->sun_path, svr, sizeof(usock->sun_path));
    562 		addrlen = (socklen_t)sizeof(struct sockaddr_un);
    563 		addrfamily = AF_LOCAL;
    564 		useport = 0;
    565 		proto = 0;
    566 #endif
    567 	} else {
    568 		if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen))
    569 			fatal_exit("could not parse IP: %s", svr);
    570 	}
    571 
    572 	if(addrfamily == 0)
    573 		addrfamily = addr_is_ip6(&addr, addrlen)?PF_INET6:PF_INET;
    574 	fd = socket(addrfamily, SOCK_STREAM, proto);
    575 	if(fd == -1) {
    576 #ifndef USE_WINSOCK
    577 		fatal_exit("socket: %s", strerror(errno));
    578 #else
    579 		fatal_exit("socket: %s", wsa_strerror(WSAGetLastError()));
    580 #endif
    581 	}
    582 	if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) {
    583 #ifndef USE_WINSOCK
    584 		int err = errno;
    585 		if(!useport) log_err("connect: %s for %s", strerror(err), svr);
    586 		else log_err_addr("connect", strerror(err), &addr, addrlen);
    587 		if(err == ECONNREFUSED && statuscmd) {
    588 			printf("unbound is stopped\n");
    589 			exit(3);
    590 		}
    591 #else
    592 		int wsaerr = WSAGetLastError();
    593 		if(!useport) log_err("connect: %s for %s", wsa_strerror(wsaerr), svr);
    594 		else log_err_addr("connect", wsa_strerror(wsaerr), &addr, addrlen);
    595 		if(wsaerr == WSAECONNREFUSED && statuscmd) {
    596 			printf("unbound is stopped\n");
    597 			exit(3);
    598 		}
    599 #endif
    600 		exit(1);
    601 	}
    602 	return fd;
    603 }
    604 
    605 /** setup SSL on the connection */
    606 static SSL*
    607 setup_ssl(SSL_CTX* ctx, int fd)
    608 {
    609 	SSL* ssl;
    610 	X509* x;
    611 	int r;
    612 
    613 	if(!ctx) return NULL;
    614 	ssl = SSL_new(ctx);
    615 	if(!ssl)
    616 		ssl_err("could not SSL_new");
    617 	SSL_set_connect_state(ssl);
    618 	(void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
    619 	if(!SSL_set_fd(ssl, fd))
    620 		ssl_err("could not SSL_set_fd");
    621 	while(1) {
    622 		ERR_clear_error();
    623 		if( (r=SSL_do_handshake(ssl)) == 1)
    624 			break;
    625 		r = SSL_get_error(ssl, r);
    626 		if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
    627 			ssl_err("SSL handshake failed");
    628 		/* wants to be called again */
    629 	}
    630 
    631 	/* check authenticity of server */
    632 	if(SSL_get_verify_result(ssl) != X509_V_OK)
    633 		ssl_err("SSL verification failed");
    634 	x = SSL_get_peer_certificate(ssl);
    635 	if(!x)
    636 		ssl_err("Server presented no peer certificate");
    637 	X509_free(x);
    638 
    639 	return ssl;
    640 }
    641 
    642 /** read from ssl or fd, fatalexit on error, 0 EOF, 1 success */
    643 static int
    644 remote_read(SSL* ssl, int fd, char* buf, size_t len)
    645 {
    646 	if(ssl) {
    647 		int r;
    648 		ERR_clear_error();
    649 		if((r = SSL_read(ssl, buf, (int)len-1)) <= 0) {
    650 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
    651 				/* EOF */
    652 				return 0;
    653 			}
    654 			ssl_err("could not SSL_read");
    655 		}
    656 		buf[r] = 0;
    657 	} else {
    658 		ssize_t rr = recv(fd, buf, len-1, 0);
    659 		if(rr <= 0) {
    660 			if(rr == 0) {
    661 				/* EOF */
    662 				return 0;
    663 			}
    664 #ifndef USE_WINSOCK
    665 			fatal_exit("could not recv: %s", strerror(errno));
    666 #else
    667 			fatal_exit("could not recv: %s", wsa_strerror(WSAGetLastError()));
    668 #endif
    669 		}
    670 		buf[rr] = 0;
    671 	}
    672 	return 1;
    673 }
    674 
    675 /** write to ssl or fd, fatalexit on error */
    676 static void
    677 remote_write(SSL* ssl, int fd, const char* buf, size_t len)
    678 {
    679 	if(ssl) {
    680 		if(SSL_write(ssl, buf, (int)len) <= 0)
    681 			ssl_err("could not SSL_write");
    682 	} else {
    683 		if(send(fd, buf, len, 0) < (ssize_t)len) {
    684 #ifndef USE_WINSOCK
    685 			fatal_exit("could not send: %s", strerror(errno));
    686 #else
    687 			fatal_exit("could not send: %s", wsa_strerror(WSAGetLastError()));
    688 #endif
    689 		}
    690 	}
    691 }
    692 
    693 /** check args, to see if too many args. Because when a file is sent it
    694  * would wait for the terminal, and we can check for too many arguments,
    695  * eg. user put arguments on the commandline. */
    696 static void
    697 check_args_for_listcmd(int argc, char* argv[])
    698 {
    699 	if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
    700 		strcmp(argv[0], "local_zones_remove") == 0 ||
    701 		strcmp(argv[0], "local_datas") == 0 ||
    702 		strcmp(argv[0], "local_datas_remove") == 0) &&
    703 		argc >= 2) {
    704 		fatal_exit("too many arguments for command '%s', "
    705 			"content is piped in from stdin", argv[0]);
    706 	}
    707 	if(argc >= 1 && strcmp(argv[0], "view_local_datas") == 0 &&
    708 		argc >= 3) {
    709 		fatal_exit("too many arguments for command '%s', "
    710 			"content is piped in from stdin", argv[0]);
    711 	}
    712 }
    713 
    714 /** send stdin to server */
    715 static void
    716 send_file(SSL* ssl, int fd, FILE* in, char* buf, size_t sz)
    717 {
    718 	while(fgets(buf, (int)sz, in)) {
    719 		remote_write(ssl, fd, buf, strlen(buf));
    720 	}
    721 }
    722 
    723 /** send end-of-file marker to server */
    724 static void
    725 send_eof(SSL* ssl, int fd)
    726 {
    727 	char e[] = {0x04, 0x0a};
    728 	remote_write(ssl, fd, e, sizeof(e));
    729 }
    730 
    731 /** send command and display result */
    732 static int
    733 go_cmd(SSL* ssl, int fd, int quiet, int argc, char* argv[])
    734 {
    735 	char pre[10];
    736 	const char* space=" ";
    737 	const char* newline="\n";
    738 	int was_error = 0, first_line = 1;
    739 	int i;
    740 	char buf[1024];
    741 	snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
    742 	remote_write(ssl, fd, pre, strlen(pre));
    743 	for(i=0; i<argc; i++) {
    744 		remote_write(ssl, fd, space, strlen(space));
    745 		remote_write(ssl, fd, argv[i], strlen(argv[i]));
    746 	}
    747 	remote_write(ssl, fd, newline, strlen(newline));
    748 
    749 	if(argc == 1 && strcmp(argv[0], "load_cache") == 0) {
    750 		send_file(ssl, fd, stdin, buf, sizeof(buf));
    751 	}
    752 	else if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
    753 		strcmp(argv[0], "local_zones_remove") == 0 ||
    754 		strcmp(argv[0], "local_datas") == 0 ||
    755 		strcmp(argv[0], "view_local_datas") == 0 ||
    756 		strcmp(argv[0], "local_datas_remove") == 0)) {
    757 		send_file(ssl, fd, stdin, buf, sizeof(buf));
    758 		send_eof(ssl, fd);
    759 	}
    760 
    761 	while(1) {
    762 		if(remote_read(ssl, fd, buf, sizeof(buf)) == 0) {
    763 			break; /* EOF */
    764 		}
    765 		if(first_line && strncmp(buf, "error", 5) == 0) {
    766 			printf("%s", buf);
    767 			was_error = 1;
    768 		} else if (!quiet)
    769 			printf("%s", buf);
    770 
    771 		first_line = 0;
    772 	}
    773 	return was_error;
    774 }
    775 
    776 /** go ahead and read config, contact server and perform command and display */
    777 static int
    778 go(const char* cfgfile, char* svr, int quiet, int argc, char* argv[])
    779 {
    780 	struct config_file* cfg;
    781 	int fd, ret;
    782 	SSL_CTX* ctx;
    783 	SSL* ssl;
    784 
    785 	/* read config */
    786 	if(!(cfg = config_create()))
    787 		fatal_exit("out of memory");
    788 	if(!config_read(cfg, cfgfile, NULL))
    789 		fatal_exit("could not read config file");
    790 	if(!cfg->remote_control_enable)
    791 		log_warn("control-enable is 'no' in the config file.");
    792 #ifdef UB_ON_WINDOWS
    793 	w_config_adjust_directory(cfg);
    794 #endif
    795 	ctx = setup_ctx(cfg);
    796 
    797 	/* contact server */
    798 	fd = contact_server(svr, cfg, argc>0&&strcmp(argv[0],"status")==0);
    799 	ssl = setup_ssl(ctx, fd);
    800 
    801 	/* send command */
    802 	ret = go_cmd(ssl, fd, quiet, argc, argv);
    803 
    804 	if(ssl) SSL_free(ssl);
    805 #ifndef USE_WINSOCK
    806 	close(fd);
    807 #else
    808 	closesocket(fd);
    809 #endif
    810 	if(ctx) SSL_CTX_free(ctx);
    811 	config_delete(cfg);
    812 	return ret;
    813 }
    814 
    815 /** getopt global, in case header files fail to declare it. */
    816 extern int optind;
    817 /** getopt global, in case header files fail to declare it. */
    818 extern char* optarg;
    819 
    820 /** Main routine for unbound-control */
    821 int main(int argc, char* argv[])
    822 {
    823 	int c, ret;
    824 	int quiet = 0;
    825 	const char* cfgfile = CONFIGFILE;
    826 	char* svr = NULL;
    827 #ifdef USE_WINSOCK
    828 	int r;
    829 	WSADATA wsa_data;
    830 #endif
    831 #ifdef USE_THREAD_DEBUG
    832 	/* stop the file output from unbound-control, overwrites the servers */
    833 	extern int check_locking_order;
    834 	check_locking_order = 0;
    835 #endif /* USE_THREAD_DEBUG */
    836 	log_ident_set("unbound-control");
    837 	log_init(NULL, 0, NULL);
    838 	checklock_start();
    839 #ifdef USE_WINSOCK
    840 	/* use registry config file in preference to compiletime location */
    841 	if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
    842 		cfgfile = CONFIGFILE;
    843 #endif
    844 	/* parse the options */
    845 	while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
    846 		switch(c) {
    847 		case 'c':
    848 			cfgfile = optarg;
    849 			break;
    850 		case 's':
    851 			svr = optarg;
    852 			break;
    853 		case 'q':
    854 			quiet = 1;
    855 			break;
    856 		case '?':
    857 		case 'h':
    858 		default:
    859 			usage();
    860 		}
    861 	}
    862 	argc -= optind;
    863 	argv += optind;
    864 	if(argc == 0)
    865 		usage();
    866 	if(argc >= 1 && strcmp(argv[0], "start")==0) {
    867 		if(execlp("unbound", "unbound", "-c", cfgfile,
    868 			(char*)NULL) < 0) {
    869 			fatal_exit("could not exec unbound: %s",
    870 				strerror(errno));
    871 		}
    872 	}
    873 	if(argc >= 1 && strcmp(argv[0], "stats_shm")==0) {
    874 		print_stats_shm(cfgfile);
    875 		return 0;
    876 	}
    877 	check_args_for_listcmd(argc, argv);
    878 
    879 #ifdef USE_WINSOCK
    880 	if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
    881 		fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
    882 #endif
    883 
    884 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
    885 	ERR_load_crypto_strings();
    886 #endif
    887 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
    888 	ERR_load_SSL_strings();
    889 #endif
    890 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
    891 #  ifndef S_SPLINT_S
    892 	OpenSSL_add_all_algorithms();
    893 #  endif
    894 #else
    895 	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
    896 		| OPENSSL_INIT_ADD_ALL_DIGESTS
    897 		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
    898 #endif
    899 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
    900 	(void)SSL_library_init();
    901 #else
    902 	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
    903 #endif
    904 
    905 	if(!RAND_status()) {
    906 		/* try to seed it */
    907 		unsigned char buf[256];
    908 		unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
    909 		unsigned int v = seed;
    910 		size_t i;
    911 		for(i=0; i<256/sizeof(v); i++) {
    912 			memmove(buf+i*sizeof(v), &v, sizeof(v));
    913 			v = v*seed + (unsigned int)i;
    914 		}
    915 		RAND_seed(buf, 256);
    916 		log_warn("no entropy, seeding openssl PRNG with time\n");
    917 	}
    918 
    919 	ret = go(cfgfile, svr, quiet, argc, argv);
    920 
    921 #ifdef USE_WINSOCK
    922 	WSACleanup();
    923 #endif
    924 	checklock_stop();
    925 	return ret;
    926 }
    927