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