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