2 * smallapp/unbound-control.c - remote control utility for unbound.
4 * Copyright (c) 2008, NLnet Labs. All rights reserved.
6 * This software is open source.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
12 * Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
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.
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.
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.
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.
48 #ifdef HAVE_OPENSSL_SSL_H
49 #include <openssl/ssl.h>
51 #ifdef HAVE_OPENSSL_ERR_H
52 #include <openssl/err.h>
54 #ifdef HAVE_OPENSSL_RAND_H
55 #include <openssl/rand.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"
79 #ifdef HAVE_TARGETCONDITIONALS_H
80 #include <TargetConditionals.h>
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;
87 /** timeout to wait for connection over stream, in msec */
88 #define UNBOUND_CONTROL_CONNECT_TIMEOUT 5000
90 /** Give unbound-control usage, and exit (1). */
94 printf("Usage: local-unbound-control [options] command\n");
95 printf(" Remote control utility for unbound server.\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");
115 printf(" stats_shm print statistics using shm\n");
117 printf(" status display status of server\n");
118 printf(" verbosity <number> change logging detail\n");
119 printf(" log_reopen close and open the logfile\n");
120 printf(" local_zone <name> <type> add new local zone\n");
121 printf(" local_zone_remove <name> remove local zone and its contents\n");
122 printf(" local_data <RR data...> add local data, for example\n");
123 printf(" local_data www.example.com A 192.0.2.1\n");
124 printf(" local_data_remove <name> remove local RR data from name\n");
125 printf(" local_zones, local_zones_remove, local_datas, local_datas_remove\n");
126 printf(" same, but read list from stdin\n");
127 printf(" (one entry per line).\n");
128 printf(" dump_cache print cache to stdout\n");
129 printf(" load_cache load cache from stdin\n");
130 printf(" lookup <name> print nameservers for name\n");
131 printf(" flush <name> flushes common types for name from cache\n");
132 printf(" types: A, AAAA, MX, PTR, NS,\n");
133 printf(" SOA, CNAME, DNAME, SRV, NAPTR\n");
134 printf(" flush_type <name> <type> flush name, type from cache\n");
135 printf(" flush_zone <name> flush everything at or under name\n");
136 printf(" from rr and dnssec caches\n");
137 printf(" flush_bogus flush all bogus data\n");
138 printf(" flush_negative flush all negative data\n");
139 printf(" flush_stats flush statistics, make zero\n");
140 printf(" flush_requestlist drop queries that are worked on\n");
141 printf(" dump_requestlist show what is worked on by first thread\n");
142 printf(" flush_infra [all | ip] remove ping, edns for one IP or all\n");
143 printf(" dump_infra show ping and edns entries\n");
144 printf(" set_option opt: val set option to value, no reload\n");
145 printf(" get_option opt get option value\n");
146 printf(" list_stubs list stub-zones and root hints in use\n");
147 printf(" list_forwards list forward-zones in use\n");
148 printf(" list_insecure list domain-insecure zones\n");
149 printf(" list_local_zones list local-zones in use\n");
150 printf(" list_local_data list local-data RRs in use\n");
151 printf(" insecure_add zone add domain-insecure zone\n");
152 printf(" insecure_remove zone remove domain-insecure zone\n");
153 printf(" forward_add [+i] zone addr.. add forward-zone with servers\n");
154 printf(" forward_remove [+i] zone remove forward zone\n");
155 printf(" stub_add [+ip] zone addr.. add stub-zone with servers\n");
156 printf(" stub_remove [+i] zone remove stub zone\n");
157 printf(" +i also do dnssec insecure point\n");
158 printf(" +p set stub to use priming\n");
159 printf(" forward [off | addr ...] without arg show forward setup\n");
160 printf(" or off to turn off root forwarding\n");
161 printf(" or give list of ip addresses\n");
162 printf(" ratelimit_list [+a] list ratelimited domains\n");
163 printf(" ip_ratelimit_list [+a] list ratelimited ip addresses\n");
164 printf(" +a list all, also not ratelimited\n");
165 printf(" list_auth_zones list auth zones (includes RPZ zones)\n");
166 printf(" auth_zone_reload zone reload auth zone (or RPZ zone) from zonefile\n");
167 printf(" auth_zone_transfer zone transfer auth zone (or RPZ zone) from master\n");
168 printf(" view_list_local_zones view list local-zones in view\n");
169 printf(" view_list_local_data view list local-data RRs in view\n");
170 printf(" view_local_zone view name type add local-zone in view\n");
171 printf(" view_local_zone_remove view name remove local-zone in view\n");
172 printf(" view_local_data view RR... add local-data in view\n");
173 printf(" view_local_datas view add list of local-data to view\n");
174 printf(" one entry per line read from stdin\n");
175 printf(" view_local_data_remove view name remove local-data in view\n");
176 printf(" view_local_datas_remove view remove list of local-data from view\n");
177 printf(" one entry per line read from stdin\n");
178 printf(" rpz_enable zone Enable the RPZ zone if it had previously\n");
179 printf(" been disabled\n");
180 printf(" rpz_disable zone Disable the RPZ zone\n");
181 printf("Version %s\n", PACKAGE_VERSION);
182 printf("BSD licensed, see LICENSE in source package for details.\n");
183 printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
188 /** what to put on statistics lines between var and value, ": " or "=" */
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));
200 /** print stat block */
201 static void pr_stats(const char* nm, struct ub_stats_info* s)
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.queries_cookie_valid",
208 s->svr.num_queries_cookie_valid);
209 PR_UL_NM("num.queries_cookie_client",
210 s->svr.num_queries_cookie_client);
211 PR_UL_NM("num.queries_cookie_invalid",
212 s->svr.num_queries_cookie_invalid);
213 PR_UL_NM("num.cachehits",
214 s->svr.num_queries - s->svr.num_queries_missed_cache);
215 PR_UL_NM("num.cachemiss", s->svr.num_queries_missed_cache);
216 PR_UL_NM("num.prefetch", s->svr.num_queries_prefetch);
217 PR_UL_NM("num.queries_timed_out", s->svr.num_queries_timed_out);
218 PR_UL_NM("query.queue_time_us.max", s->svr.max_query_time_us);
219 PR_UL_NM("num.expired", s->svr.ans_expired);
220 PR_UL_NM("num.recursivereplies", s->mesh_replies_sent);
222 PR_UL_NM("num.dnscrypt.crypted", s->svr.num_query_dnscrypt_crypted);
223 PR_UL_NM("num.dnscrypt.cert", s->svr.num_query_dnscrypt_cert);
224 PR_UL_NM("num.dnscrypt.cleartext", s->svr.num_query_dnscrypt_cleartext);
225 PR_UL_NM("num.dnscrypt.malformed",
226 s->svr.num_query_dnscrypt_crypted_malformed);
227 #endif /* USE_DNSCRYPT */
228 printf("%s.requestlist.avg"SQ"%g\n", nm,
229 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
230 (double)s->svr.sum_query_list_size/
231 (double)(s->svr.num_queries_missed_cache+
232 s->svr.num_queries_prefetch) : 0.0);
233 PR_UL_NM("requestlist.max", s->svr.max_query_list_size);
234 PR_UL_NM("requestlist.overwritten", s->mesh_jostled);
235 PR_UL_NM("requestlist.exceeded", s->mesh_dropped);
236 PR_UL_NM("requestlist.current.all", s->mesh_num_states);
237 PR_UL_NM("requestlist.current.user", s->mesh_num_reply_states);
239 sumwait.tv_sec = s->mesh_replies_sum_wait_sec;
240 sumwait.tv_usec = s->mesh_replies_sum_wait_usec;
242 timeval_divide(&avg, &sumwait, s->mesh_replies_sent);
244 PR_TIMEVAL("recursion.time.avg", avg);
245 printf("%s.recursion.time.median"SQ"%g\n", nm, s->mesh_time_median);
246 PR_UL_NM("tcpusage", s->svr.tcp_accept_usage);
250 static void print_uptime(struct ub_shm_stat_info* shm_stat)
252 PR_STATSTIME("time.now", shm_stat->time.now);
253 PR_STATSTIME("time.up", shm_stat->time.up);
254 PR_STATSTIME("time.elapsed", shm_stat->time.elapsed);
257 /** print memory usage */
258 static void print_mem(struct ub_shm_stat_info* shm_stat,
259 struct ub_stats_info* s)
261 PR_LL("mem.cache.rrset", shm_stat->mem.rrset);
262 PR_LL("mem.cache.message", shm_stat->mem.msg);
263 PR_LL("mem.mod.iterator", shm_stat->mem.iter);
264 PR_LL("mem.mod.validator", shm_stat->mem.val);
265 PR_LL("mem.mod.respip", shm_stat->mem.respip);
267 PR_LL("mem.mod.subnet", shm_stat->mem.subnet);
270 PR_LL("mem.mod.ipsecmod", shm_stat->mem.ipsecmod);
272 #ifdef WITH_DYNLIBMODULE
273 PR_LL("mem.mod.dynlib", shm_stat->mem.dynlib);
276 PR_LL("mem.cache.dnscrypt_shared_secret",
277 shm_stat->mem.dnscrypt_shared_secret);
278 PR_LL("mem.cache.dnscrypt_nonce",
279 shm_stat->mem.dnscrypt_nonce);
281 PR_LL("mem.streamwait", s->svr.mem_stream_wait);
282 PR_LL("mem.http.query_buffer", s->svr.mem_http2_query_buffer);
283 PR_LL("mem.http.response_buffer", s->svr.mem_http2_response_buffer);
286 /** print histogram */
287 static void print_hist(struct ub_stats_info* s)
289 struct timehist* hist;
291 hist = timehist_setup();
293 fatal_exit("out of memory");
294 timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
295 for(i=0; i<hist->num; i++) {
296 printf("histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
297 (int)hist->buckets[i].lower.tv_sec,
298 (int)hist->buckets[i].lower.tv_usec,
299 (int)hist->buckets[i].upper.tv_sec,
300 (int)hist->buckets[i].upper.tv_usec,
301 (unsigned long)hist->buckets[i].count);
303 timehist_delete(hist);
306 /** print extended */
307 static void print_extended(struct ub_stats_info* s, int inhibit_zero)
313 for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
314 if(inhibit_zero && s->svr.qtype[i] == 0)
316 sldns_wire2str_type_buf((uint16_t)i, nm, sizeof(nm));
317 PR_UL_SUB("num.query.type", nm, s->svr.qtype[i]);
319 if(!inhibit_zero || s->svr.qtype_big) {
320 PR_UL("num.query.type.other", s->svr.qtype_big);
324 for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
325 if(inhibit_zero && s->svr.qclass[i] == 0)
327 sldns_wire2str_class_buf((uint16_t)i, nm, sizeof(nm));
328 PR_UL_SUB("num.query.class", nm, s->svr.qclass[i]);
330 if(!inhibit_zero || s->svr.qclass_big) {
331 PR_UL("num.query.class.other", s->svr.qclass_big);
335 for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
336 if(inhibit_zero && s->svr.qopcode[i] == 0)
338 sldns_wire2str_opcode_buf(i, nm, sizeof(nm));
339 PR_UL_SUB("num.query.opcode", nm, s->svr.qopcode[i]);
343 PR_UL("num.query.tcp", s->svr.qtcp);
344 PR_UL("num.query.tcpout", s->svr.qtcp_outgoing);
345 PR_UL("num.query.udpout", s->svr.qudp_outgoing);
346 PR_UL("num.query.tls", s->svr.qtls);
347 PR_UL("num.query.tls_resume", s->svr.qtls_resume);
348 PR_UL("num.query.ipv6", s->svr.qipv6);
349 PR_UL("num.query.https", s->svr.qhttps);
352 PR_UL("num.query.flags.QR", s->svr.qbit_QR);
353 PR_UL("num.query.flags.AA", s->svr.qbit_AA);
354 PR_UL("num.query.flags.TC", s->svr.qbit_TC);
355 PR_UL("num.query.flags.RD", s->svr.qbit_RD);
356 PR_UL("num.query.flags.RA", s->svr.qbit_RA);
357 PR_UL("num.query.flags.Z", s->svr.qbit_Z);
358 PR_UL("num.query.flags.AD", s->svr.qbit_AD);
359 PR_UL("num.query.flags.CD", s->svr.qbit_CD);
360 PR_UL("num.query.edns.present", s->svr.qEDNS);
361 PR_UL("num.query.edns.DO", s->svr.qEDNS_DO);
364 for(i=0; i<UB_STATS_RCODE_NUM; i++) {
365 /* Always include RCODEs 0-5 */
366 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
368 sldns_wire2str_rcode_buf(i, nm, sizeof(nm));
369 PR_UL_SUB("num.answer.rcode", nm, s->svr.ans_rcode[i]);
371 if(!inhibit_zero || s->svr.ans_rcode_nodata) {
372 PR_UL("num.answer.rcode.nodata", s->svr.ans_rcode_nodata);
375 PR_UL("num.query.ratelimited", s->svr.queries_ratelimited);
377 PR_UL("num.answer.secure", s->svr.ans_secure);
378 PR_UL("num.answer.bogus", s->svr.ans_bogus);
379 PR_UL("num.rrset.bogus", s->svr.rrset_bogus);
380 PR_UL("num.query.aggressive.NOERROR", s->svr.num_neg_cache_noerror);
381 PR_UL("num.query.aggressive.NXDOMAIN", s->svr.num_neg_cache_nxdomain);
382 /* threat detection */
383 PR_UL("unwanted.queries", s->svr.unwanted_queries);
384 PR_UL("unwanted.replies", s->svr.unwanted_replies);
386 PR_UL("msg.cache.count", s->svr.msg_cache_count);
387 PR_UL("rrset.cache.count", s->svr.rrset_cache_count);
388 PR_UL("infra.cache.count", s->svr.infra_cache_count);
389 PR_UL("key.cache.count", s->svr.key_cache_count);
391 PR_UL("msg.cache.max_collisions", s->svr.msg_cache_max_collisions);
392 PR_UL("rrset.cache.max_collisions", s->svr.rrset_cache_max_collisions);
393 /* applied RPZ actions */
394 for(i=0; i<UB_STATS_RPZ_ACTION_NUM; i++) {
395 if(i == RPZ_NO_OVERRIDE_ACTION)
397 if(inhibit_zero && s->svr.rpz_action[i] == 0)
399 PR_UL_SUB("num.rpz.action", rpz_action_to_string(i), s->svr.rpz_action[i]);
402 PR_UL("dnscrypt_shared_secret.cache.count",
403 s->svr.shared_secret_cache_count);
404 PR_UL("num.query.dnscrypt.shared_secret.cachemiss",
405 s->svr.num_query_dnscrypt_secret_missed_cache);
406 PR_UL("dnscrypt_nonce.cache.count", s->svr.nonce_cache_count);
407 PR_UL("num.query.dnscrypt.replay",
408 s->svr.num_query_dnscrypt_replay);
409 #endif /* USE_DNSCRYPT */
410 PR_UL("num.query.authzone.up", s->svr.num_query_authzone_up);
411 PR_UL("num.query.authzone.down", s->svr.num_query_authzone_down);
413 PR_UL("num.query.subnet", s->svr.num_query_subnet);
414 PR_UL("num.query.subnet_cache", s->svr.num_query_subnet_cache);
417 PR_UL("num.query.cachedb", s->svr.num_query_cachedb);
421 /** print statistics out of memory structures */
422 static void do_stats_shm(struct config_file* cfg, struct ub_stats_info* stats,
423 struct ub_shm_stat_info* shm_stat)
427 for(i=0; i<cfg->num_threads; i++) {
428 snprintf(nm, sizeof(nm), "thread%d", i);
429 pr_stats(nm, &stats[i+1]);
431 pr_stats("total", &stats[0]);
432 print_uptime(shm_stat);
433 if(cfg->stat_extended) {
434 print_mem(shm_stat, &stats[0]);
436 print_extended(stats, cfg->stat_inhibit_zero);
439 #endif /* HAVE_SHMGET */
441 /** print statistics from shm memory segment */
442 static void print_stats_shm(const char* cfgfile, int quiet)
445 struct config_file* cfg;
446 struct ub_stats_info* stats;
447 struct ub_shm_stat_info* shm_stat;
450 if(!(cfg = config_create()))
451 fatal_exit("out of memory");
452 if(!config_read(cfg, cfgfile, NULL))
453 fatal_exit("could not read config file");
454 /* get shm segments */
455 id_ctl = shmget(cfg->shm_key, sizeof(int), SHM_R);
457 fatal_exit("shmget(%d): %s", cfg->shm_key, strerror(errno));
459 id_arr = shmget(cfg->shm_key+1, sizeof(int), SHM_R);
461 fatal_exit("shmget(%d): %s", cfg->shm_key+1, strerror(errno));
463 shm_stat = (struct ub_shm_stat_info*)shmat(id_ctl, NULL, SHM_RDONLY);
464 if(shm_stat == (void*)-1) {
465 fatal_exit("shmat(%d): %s", id_ctl, strerror(errno));
467 stats = (struct ub_stats_info*)shmat(id_arr, NULL, SHM_RDONLY);
468 if(stats == (void*)-1) {
469 fatal_exit("shmat(%d): %s", id_arr, strerror(errno));
474 /* print the stats */
475 do_stats_shm(cfg, stats, shm_stat);
485 #endif /* HAVE_SHMGET */
488 /** exit with ssl error */
489 static void ssl_err(const char* s)
491 fprintf(stderr, "error: %s\n", s);
492 ERR_print_errors_fp(stderr);
496 /** exit with ssl error related to a file path */
497 static void ssl_path_err(const char* s, const char *path)
500 err = ERR_peek_error();
501 if(ERR_GET_LIB(err) == ERR_LIB_SYS) {
502 fprintf(stderr, "error: %s\n%s: %s\n",
503 s, path, ERR_reason_error_string(err));
510 /** setup SSL context */
512 setup_ctx(struct config_file* cfg)
514 char* s_cert=NULL, *c_key=NULL, *c_cert=NULL;
517 if(!(options_remote_is_address(cfg) && cfg->control_use_cert))
519 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
520 c_key = fname_after_chroot(cfg->control_key_file, cfg, 1);
521 c_cert = fname_after_chroot(cfg->control_cert_file, cfg, 1);
522 if(!s_cert || !c_key || !c_cert)
523 fatal_exit("out of memory");
524 ctx = SSL_CTX_new(SSLv23_client_method());
526 ssl_err("could not allocate SSL_CTX pointer");
527 #if SSL_OP_NO_SSLv2 != 0
528 if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
530 ssl_err("could not set SSL_OP_NO_SSLv2");
532 if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
534 ssl_err("could not set SSL_OP_NO_SSLv3");
535 #if defined(SSL_OP_NO_RENEGOTIATION)
536 /* disable client renegotiation */
537 if((SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION) &
538 SSL_OP_NO_RENEGOTIATION) != SSL_OP_NO_RENEGOTIATION)
539 ssl_err("could not set SSL_OP_NO_RENEGOTIATION");
541 if(!SSL_CTX_use_certificate_chain_file(ctx,c_cert))
542 ssl_path_err("Error setting up SSL_CTX client cert", c_cert);
543 if(!SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM))
544 ssl_path_err("Error setting up SSL_CTX client key", c_key);
545 if(!SSL_CTX_check_private_key(ctx))
546 ssl_err("Error setting up SSL_CTX client key");
547 if(SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1)
548 ssl_path_err("Error setting up SSL_CTX verify, server cert",
550 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
558 /** check connect error */
560 checkconnecterr(int err, const char* svr, struct sockaddr_storage* addr,
561 socklen_t addrlen, int statuscmd, int useport)
564 if(!useport) log_err("connect: %s for %s", strerror(err), svr);
565 else log_err_addr("connect", strerror(err), addr, addrlen);
566 if(err == ECONNREFUSED && statuscmd) {
567 printf("unbound is stopped\n");
572 if(!useport) log_err("connect: %s for %s", wsa_strerror(wsaerr), svr);
573 else log_err_addr("connect", wsa_strerror(wsaerr), addr, addrlen);
574 if(wsaerr == WSAECONNREFUSED && statuscmd) {
575 printf("unbound is stopped\n");
582 /** contact the server with TCP connect */
584 contact_server(const char* svr, struct config_file* cfg, int statuscmd)
586 struct sockaddr_storage addr;
588 int addrfamily = 0, proto = IPPROTO_TCP;
592 /* use svr or the first config entry */
594 if(cfg->control_ifs.first) {
595 struct sockaddr_storage addr2;
597 if(extstrtoaddr(cfg->control_ifs.first->str, &addr2,
598 &addrlen2, UNBOUND_DNS_PORT)) {
599 svr = cfg->control_ifs.first->str;
601 if(!resolve_interface_names(NULL, 0,
602 cfg->control_ifs.first, &rcif,
604 fatal_exit("could not resolve interface names");
606 if(rcif == NULL || num_rcif == 0) {
607 fatal_exit("no control interfaces");
611 } else if(cfg->do_ip4) {
616 /* config 0 addr (everything), means ask localhost */
617 if(strcmp(svr, "0.0.0.0") == 0)
619 else if(strcmp(svr, "::0") == 0 ||
620 strcmp(svr, "0::0") == 0 ||
621 strcmp(svr, "0::") == 0 ||
622 strcmp(svr, "::") == 0)
625 if(strchr(svr, '@')) {
626 if(!extstrtoaddr(svr, &addr, &addrlen, UNBOUND_DNS_PORT))
627 fatal_exit("could not parse IP@port: %s", svr);
629 } else if(svr[0] == '/') {
630 struct sockaddr_un* usock = (struct sockaddr_un *) &addr;
631 usock->sun_family = AF_LOCAL;
632 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
633 usock->sun_len = (unsigned)sizeof(usock);
635 (void)strlcpy(usock->sun_path, svr, sizeof(usock->sun_path));
636 addrlen = (socklen_t)sizeof(struct sockaddr_un);
637 addrfamily = AF_LOCAL;
642 if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen))
643 fatal_exit("could not parse IP: %s", svr);
647 addrfamily = addr_is_ip6(&addr, addrlen)?PF_INET6:PF_INET;
648 fd = socket(addrfamily, SOCK_STREAM, proto);
650 fatal_exit("socket: %s", sock_strerror(errno));
653 if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) {
656 if(errno != EINPROGRESS) {
657 checkconnecterr(errno, svr, &addr,
658 addrlen, statuscmd, useport);
662 if(WSAGetLastError() != WSAEINPROGRESS &&
663 WSAGetLastError() != WSAEWOULDBLOCK) {
664 checkconnecterr(WSAGetLastError(), svr, &addr,
665 addrlen, statuscmd, useport);
670 fd_set rset, wset, eset;
673 FD_SET(FD_SET_T fd, &rset);
675 FD_SET(FD_SET_T fd, &wset);
677 FD_SET(FD_SET_T fd, &eset);
678 tv.tv_sec = UNBOUND_CONTROL_CONNECT_TIMEOUT/1000;
679 tv.tv_usec= (UNBOUND_CONTROL_CONNECT_TIMEOUT%1000)*1000;
680 if(select(fd+1, &rset, &wset, &eset, &tv) == -1) {
681 fatal_exit("select: %s", sock_strerror(errno));
683 if(!FD_ISSET(fd, &rset) && !FD_ISSET(fd, &wset) &&
684 !FD_ISSET(fd, &eset)) {
685 fatal_exit("timeout: could not connect to server");
687 /* check nonblocking connect error */
689 socklen_t len = (socklen_t)sizeof(error);
690 if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
693 error = errno; /* on solaris errno is error */
695 error = WSAGetLastError();
701 if(error == EINPROGRESS)
702 continue; /* try again later */
705 if(error == EWOULDBLOCK)
706 continue; /* try again later */
709 if(error == WSAEINPROGRESS)
710 continue; /* try again later */
711 if(error == WSAEWOULDBLOCK)
712 continue; /* try again later */
714 checkconnecterr(error, svr, &addr, addrlen,
721 config_del_strarray(rcif, num_rcif);
725 /** setup SSL on the connection */
727 setup_ssl(SSL_CTX* ctx, int fd)
733 if(!ctx) return NULL;
736 ssl_err("could not SSL_new");
737 SSL_set_connect_state(ssl);
738 (void)SSL_set_mode(ssl, (long)SSL_MODE_AUTO_RETRY);
739 if(!SSL_set_fd(ssl, fd))
740 ssl_err("could not SSL_set_fd");
743 if( (r=SSL_do_handshake(ssl)) == 1)
745 r = SSL_get_error(ssl, r);
746 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
747 ssl_err("SSL handshake failed");
748 /* wants to be called again */
751 /* check authenticity of server */
752 if(SSL_get_verify_result(ssl) != X509_V_OK)
753 ssl_err("SSL verification failed");
754 x = SSL_get_peer_certificate(ssl);
756 ssl_err("Server presented no peer certificate");
762 /** read from ssl or fd, fatalexit on error, 0 EOF, 1 success */
764 remote_read(SSL* ssl, int fd, char* buf, size_t len)
769 if((r = SSL_read(ssl, buf, (int)len-1)) <= 0) {
770 if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
774 ssl_err("could not SSL_read");
778 ssize_t rr = recv(fd, buf, len-1, 0);
784 fatal_exit("could not recv: %s", sock_strerror(errno));
791 /** write to ssl or fd, fatalexit on error */
793 remote_write(SSL* ssl, int fd, const char* buf, size_t len)
796 if(SSL_write(ssl, buf, (int)len) <= 0)
797 ssl_err("could not SSL_write");
799 if(send(fd, buf, len, 0) < (ssize_t)len) {
800 fatal_exit("could not send: %s", sock_strerror(errno));
805 /** check args, to see if too many args. Because when a file is sent it
806 * would wait for the terminal, and we can check for too many arguments,
807 * eg. user put arguments on the commandline. */
809 check_args_for_listcmd(int argc, char* argv[])
811 if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
812 strcmp(argv[0], "local_zones_remove") == 0 ||
813 strcmp(argv[0], "local_datas") == 0 ||
814 strcmp(argv[0], "local_datas_remove") == 0) &&
816 fatal_exit("too many arguments for command '%s', "
817 "content is piped in from stdin", argv[0]);
819 if(argc >= 1 && (strcmp(argv[0], "view_local_datas") == 0 ||
820 strcmp(argv[0], "view_local_datas_remove") == 0) &&
822 fatal_exit("too many arguments for command '%s', "
823 "content is piped in from stdin", argv[0]);
827 /** send stdin to server */
829 send_file(SSL* ssl, int fd, FILE* in, char* buf, size_t sz)
831 while(fgets(buf, (int)sz, in)) {
832 remote_write(ssl, fd, buf, strlen(buf));
836 /** send end-of-file marker to server */
838 send_eof(SSL* ssl, int fd)
840 char e[] = {0x04, 0x0a};
841 remote_write(ssl, fd, e, sizeof(e));
844 /** send command and display result */
846 go_cmd(SSL* ssl, int fd, int quiet, int argc, char* argv[])
849 const char* space=" ";
850 const char* newline="\n";
851 int was_error = 0, first_line = 1;
854 snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
855 remote_write(ssl, fd, pre, strlen(pre));
856 for(i=0; i<argc; i++) {
857 remote_write(ssl, fd, space, strlen(space));
858 remote_write(ssl, fd, argv[i], strlen(argv[i]));
860 remote_write(ssl, fd, newline, strlen(newline));
862 if(argc == 1 && strcmp(argv[0], "load_cache") == 0) {
863 send_file(ssl, fd, stdin, buf, sizeof(buf));
865 else if(argc >= 1 && (strcmp(argv[0], "local_zones") == 0 ||
866 strcmp(argv[0], "local_zones_remove") == 0 ||
867 strcmp(argv[0], "local_datas") == 0 ||
868 strcmp(argv[0], "view_local_datas") == 0 ||
869 strcmp(argv[0], "local_datas_remove") == 0 ||
870 strcmp(argv[0], "view_local_datas_remove") == 0)) {
871 send_file(ssl, fd, stdin, buf, sizeof(buf));
876 if(remote_read(ssl, fd, buf, sizeof(buf)) == 0) {
879 if(first_line && strncmp(buf, "error", 5) == 0) {
891 /** go ahead and read config, contact server and perform command and display */
893 go(const char* cfgfile, char* svr, int quiet, int argc, char* argv[])
895 struct config_file* cfg;
901 if(!(cfg = config_create()))
902 fatal_exit("out of memory");
903 if(!config_read(cfg, cfgfile, NULL))
904 fatal_exit("could not read config file");
905 if(!cfg->remote_control_enable)
906 log_warn("control-enable is 'no' in the config file.");
908 w_config_adjust_directory(cfg);
910 ctx = setup_ctx(cfg);
913 fd = contact_server(svr, cfg, argc>0&&strcmp(argv[0],"status")==0);
914 ssl = setup_ssl(ctx, fd);
917 ret = go_cmd(ssl, fd, quiet, argc, argv);
919 if(ssl) SSL_free(ssl);
921 if(ctx) SSL_CTX_free(ctx);
926 /** getopt global, in case header files fail to declare it. */
928 /** getopt global, in case header files fail to declare it. */
931 /** Main routine for unbound-control */
932 int main(int argc, char* argv[])
936 const char* cfgfile = CONFIGFILE;
942 #ifdef USE_THREAD_DEBUG
943 /* stop the file output from unbound-control, overwrites the servers */
944 extern int check_locking_order;
945 check_locking_order = 0;
946 #endif /* USE_THREAD_DEBUG */
948 log_ident_set("unbound-control");
949 log_init(NULL, 0, NULL);
951 /* use registry config file in preference to compiletime location */
952 if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
953 cfgfile = CONFIGFILE;
955 /* parse the options */
956 while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
977 if(argc >= 1 && strcmp(argv[0], "start")==0) {
978 #if (defined(TARGET_OS_TV) && TARGET_OS_TV) || (defined(TARGET_OS_WATCH) && TARGET_OS_WATCH)
979 fatal_exit("could not exec unbound: %s",
982 if(execlp("unbound", "unbound", "-c", cfgfile,
984 fatal_exit("could not exec unbound: %s",
989 if(argc >= 1 && strcmp(argv[0], "stats_shm")==0) {
990 print_stats_shm(cfgfile, quiet);
993 check_args_for_listcmd(argc, argv);
996 if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
997 fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
1000 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
1001 ERR_load_crypto_strings();
1003 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1004 ERR_load_SSL_strings();
1006 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
1008 OpenSSL_add_all_algorithms();
1011 OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
1012 | OPENSSL_INIT_ADD_ALL_DIGESTS
1013 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
1015 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
1016 (void)SSL_library_init();
1018 (void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
1021 if(!RAND_status()) {
1022 /* try to seed it */
1023 unsigned char buf[256];
1024 unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
1025 unsigned int v = seed;
1027 for(i=0; i<256/sizeof(v); i++) {
1028 memmove(buf+i*sizeof(v), &v, sizeof(v));
1029 v = v*seed + (unsigned int)i;
1031 RAND_seed(buf, 256);
1032 log_warn("no entropy, seeding openssl PRNG with time\n");
1035 ret = go(cfgfile, svr, quiet, argc, argv);