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