]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/smallapp/unbound-control.c
Import mandoc 1.14.4
[FreeBSD/FreeBSD.git] / contrib / unbound / smallapp / unbound-control.c
1 /*
2  * checkconf/unbound-control.c - remote control utility for unbound.
3  *
4  * Copyright (c) 2008, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  * 
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  * 
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * The remote control utility contacts the unbound server over ssl and
40  * sends the command, receives the answer, and displays the result
41  * from the commandline.
42  */
43
44 #include "config.h"
45 #ifdef HAVE_GETOPT_H
46 #include <getopt.h>
47 #endif
48 #ifdef HAVE_OPENSSL_SSL_H
49 #include <openssl/ssl.h>
50 #endif
51 #ifdef HAVE_OPENSSL_ERR_H
52 #include <openssl/err.h>
53 #endif
54 #ifdef HAVE_OPENSSL_RAND_H
55 #include <openssl/rand.h>
56 #endif
57 #include "util/log.h"
58 #include "util/config_file.h"
59 #include "util/locks.h"
60 #include "util/net_help.h"
61 #include "util/shm_side/shm_main.h"
62 #include "daemon/stats.h"
63 #include "sldns/wire2str.h"
64 #include "sldns/pkthdr.h"
65
66 #ifdef HAVE_SYS_IPC_H
67 #include "sys/ipc.h"
68 #endif
69 #ifdef HAVE_SYS_SHM_H
70 #include "sys/shm.h"
71 #endif
72 #ifdef HAVE_SYS_UN_H
73 #include <sys/un.h>
74 #endif
75
76 /** Give unbound-control usage, and exit (1). */
77 static void
78 usage(void)
79 {
80         printf("Usage:  local-unbound-control [options] command\n");
81         printf("        Remote control utility for unbound server.\n");
82         printf("Options:\n");
83         printf("  -c file       config file, default is %s\n", CONFIGFILE);
84         printf("  -s ip[@port]  server address, if omitted config is used.\n");
85         printf("  -q            quiet (don't print anything if it works ok).\n");
86         printf("  -h            show this usage help.\n");
87         printf("Commands:\n");
88         printf("  start                         start server; runs unbound(8)\n");
89         printf("  stop                          stops the server\n");
90         printf("  reload                        reloads the server\n");
91         printf("                                (this flushes data, stats, requestlist)\n");
92         printf("  stats                         print statistics\n");
93         printf("  stats_noreset                 peek at statistics\n");
94 #ifdef HAVE_SHMGET
95         printf("  stats_shm                     print statistics using shm\n");
96 #endif
97         printf("  status                        display status of server\n");
98         printf("  verbosity <number>            change logging detail\n");
99         printf("  log_reopen                    close and open the logfile\n");
100         printf("  local_zone <name> <type>      add new local zone\n");
101         printf("  local_zone_remove <name>      remove local zone and its contents\n");
102         printf("  local_data <RR data...>       add local data, for example\n");
103         printf("                                local_data www.example.com A 192.0.2.1\n");
104         printf("  local_data_remove <name>      remove local RR data from name\n");
105         printf("  local_zones, local_zones_remove, local_datas, local_datas_remove\n");
106         printf("                                same, but read list from stdin\n");
107         printf("                                (one entry per line).\n");
108         printf("  dump_cache                    print cache to stdout\n");
109         printf("  load_cache                    load cache from stdin\n");
110         printf("  lookup <name>                 print nameservers for name\n");
111         printf("  flush <name>                  flushes common types for name from cache\n");
112         printf("                                types:  A, AAAA, MX, PTR, NS,\n");
113         printf("                                        SOA, CNAME, DNAME, SRV, NAPTR\n");
114         printf("  flush_type <name> <type>      flush name, type from cache\n");
115         printf("  flush_zone <name>             flush everything at or under name\n");
116         printf("                                from rr and dnssec caches\n");
117         printf("  flush_bogus                   flush all bogus data\n");
118         printf("  flush_negative                flush all negative data\n");
119         printf("  flush_stats                   flush statistics, make zero\n");
120         printf("  flush_requestlist             drop queries that are worked on\n");
121         printf("  dump_requestlist              show what is worked on by first thread\n");
122         printf("  flush_infra [all | ip]        remove ping, edns for one IP or all\n");
123         printf("  dump_infra                    show ping and edns entries\n");
124         printf("  set_option opt: val           set option to value, no reload\n");
125         printf("  get_option opt                get option value\n");
126         printf("  list_stubs                    list stub-zones and root hints in use\n");
127         printf("  list_forwards                 list forward-zones in use\n");
128         printf("  list_insecure                 list domain-insecure zones\n");
129         printf("  list_local_zones              list local-zones in use\n");
130         printf("  list_local_data               list local-data RRs in use\n");
131         printf("  insecure_add zone             add domain-insecure zone\n");
132         printf("  insecure_remove zone          remove domain-insecure zone\n");
133         printf("  forward_add [+i] zone addr..  add forward-zone with servers\n");
134         printf("  forward_remove [+i] zone      remove forward zone\n");
135         printf("  stub_add [+ip] zone addr..    add stub-zone with servers\n");
136         printf("  stub_remove [+i] zone         remove stub zone\n");
137         printf("                +i              also do dnssec insecure point\n");
138         printf("                +p              set stub to use priming\n");
139         printf("  forward [off | addr ...]      without arg show forward setup\n");
140         printf("                                or off to turn off root forwarding\n");
141         printf("                                or give list of ip addresses\n");
142         printf("  ratelimit_list [+a]           list ratelimited domains\n");
143         printf("  ip_ratelimit_list [+a]        list ratelimited ip addresses\n");
144         printf("                +a              list all, also not ratelimited\n");
145         printf("  list_auth_zones               list auth zones\n");
146         printf("  view_list_local_zones view    list local-zones in view\n");
147         printf("  view_list_local_data  view    list local-data RRs in view\n");
148         printf("  view_local_zone view name type        add local-zone in view\n");
149         printf("  view_local_zone_remove view name      remove local-zone in view\n");
150         printf("  view_local_data view RR...            add local-data in view\n");
151         printf("  view_local_data_remove view name      remove local-data in view\n");
152         printf("Version %s\n", PACKAGE_VERSION);
153         printf("BSD licensed, see LICENSE in source package for details.\n");
154         printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
155         exit(1);
156 }
157
158 #ifdef HAVE_SHMGET
159 /** what to put on statistics lines between var and value, ": " or "=" */
160 #define SQ "="
161 /** if true, inhibits a lot of =0 lines from the stats output */
162 static const int inhibit_zero = 1;
163 /** divide sum of timers to get average */
164 static void
165 timeval_divide(struct timeval* avg, const struct timeval* sum, long long d)
166 {
167 #ifndef S_SPLINT_S
168         size_t leftover;
169         if(d == 0) {
170                 avg->tv_sec = 0;
171                 avg->tv_usec = 0;
172                 return;
173         }
174         avg->tv_sec = sum->tv_sec / d;
175         avg->tv_usec = sum->tv_usec / d;
176         /* handle fraction from seconds divide */
177         leftover = sum->tv_sec - avg->tv_sec*d;
178         avg->tv_usec += (leftover*1000000)/d;
179 #endif
180 }
181
182 /** print unsigned long stats value */
183 #define PR_UL_NM(str, var) printf("%s."str SQ"%lu\n", nm, (unsigned long)(var));
184 #define PR_UL(str, var) printf(str SQ"%lu\n", (unsigned long)(var));
185 #define PR_UL_SUB(str, nm, var) printf(str".%s"SQ"%lu\n", nm, (unsigned long)(var));
186 #define PR_TIMEVAL(str, var) printf(str SQ ARG_LL "d.%6.6d\n", \
187         (long long)var.tv_sec, (int)var.tv_usec);
188 #define PR_STATSTIME(str, var) printf(str SQ ARG_LL "d.%6.6d\n", \
189         (long long)var ## _sec, (int)var ## _usec);
190 #define PR_LL(str, var) printf(str SQ ARG_LL"d\n", (long long)(var));
191
192 /** print stat block */
193 static void pr_stats(const char* nm, struct ub_stats_info* s)
194 {
195         struct timeval sumwait, avg;
196         PR_UL_NM("num.queries", s->svr.num_queries);
197         PR_UL_NM("num.queries_ip_ratelimited", 
198                 s->svr.num_queries_ip_ratelimited);
199         PR_UL_NM("num.cachehits",
200                 s->svr.num_queries - s->svr.num_queries_missed_cache);
201         PR_UL_NM("num.cachemiss", s->svr.num_queries_missed_cache);
202         PR_UL_NM("num.prefetch", s->svr.num_queries_prefetch);
203         PR_UL_NM("num.zero_ttl", s->svr.zero_ttl_responses);
204         PR_UL_NM("num.recursivereplies", s->mesh_replies_sent);
205 #ifdef USE_DNSCRYPT
206     PR_UL_NM("num.dnscrypt.crypted", s->svr.num_query_dnscrypt_crypted);
207     PR_UL_NM("num.dnscrypt.cert", s->svr.num_query_dnscrypt_cert);
208     PR_UL_NM("num.dnscrypt.cleartext", s->svr.num_query_dnscrypt_cleartext);
209     PR_UL_NM("num.dnscrypt.malformed",
210              s->svr.num_query_dnscrypt_crypted_malformed);
211 #endif /* USE_DNSCRYPT */
212         printf("%s.requestlist.avg"SQ"%g\n", nm,
213                 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
214                         (double)s->svr.sum_query_list_size/
215                         (double)(s->svr.num_queries_missed_cache+
216                         s->svr.num_queries_prefetch) : 0.0);
217         PR_UL_NM("requestlist.max", s->svr.max_query_list_size);
218         PR_UL_NM("requestlist.overwritten", s->mesh_jostled);
219         PR_UL_NM("requestlist.exceeded", s->mesh_dropped);
220         PR_UL_NM("requestlist.current.all", s->mesh_num_states);
221         PR_UL_NM("requestlist.current.user", s->mesh_num_reply_states);
222 #ifndef S_SPLINT_S
223         sumwait.tv_sec = s->mesh_replies_sum_wait_sec;
224         sumwait.tv_usec = s->mesh_replies_sum_wait_usec;
225 #endif
226         timeval_divide(&avg, &sumwait, s->mesh_replies_sent);
227         printf("%s.", nm);
228         PR_TIMEVAL("recursion.time.avg", avg);
229         printf("%s.recursion.time.median"SQ"%g\n", nm, s->mesh_time_median);
230         PR_UL_NM("tcpusage", s->svr.tcp_accept_usage);
231 }
232
233 /** print uptime */
234 static void print_uptime(struct ub_shm_stat_info* shm_stat)
235 {
236         PR_STATSTIME("time.now", shm_stat->time.now);
237         PR_STATSTIME("time.up", shm_stat->time.up);
238         PR_STATSTIME("time.elapsed", shm_stat->time.elapsed);
239 }
240
241 /** print memory usage */
242 static void print_mem(struct ub_shm_stat_info* shm_stat)
243 {
244         PR_LL("mem.cache.rrset", shm_stat->mem.rrset);
245         PR_LL("mem.cache.message", shm_stat->mem.msg);
246         PR_LL("mem.mod.iterator", shm_stat->mem.iter);
247         PR_LL("mem.mod.validator", shm_stat->mem.val);
248         PR_LL("mem.mod.respip", shm_stat->mem.respip);
249 #ifdef CLIENT_SUBNET
250         PR_LL("mem.mod.subnet", shm_stat->mem.subnet);
251 #endif
252 #ifdef USE_IPSECMOD
253         PR_LL("mem.mod.ipsecmod", shm_stat->mem.ipsecmod);
254 #endif
255 #ifdef USE_DNSCRYPT
256         PR_LL("mem.cache.dnscrypt_shared_secret",
257                 shm_stat->mem.dnscrypt_shared_secret);
258         PR_LL("mem.cache.dnscrypt_nonce",
259                 shm_stat->mem.dnscrypt_nonce);
260 #endif
261 }
262
263 /** print histogram */
264 static void print_hist(struct ub_stats_info* s)
265 {
266         struct timehist* hist;
267         size_t i;
268         hist = timehist_setup();
269         if(!hist)
270                 fatal_exit("out of memory");
271         timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
272         for(i=0; i<hist->num; i++) {
273                 printf("histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
274                         (int)hist->buckets[i].lower.tv_sec,
275                         (int)hist->buckets[i].lower.tv_usec,
276                         (int)hist->buckets[i].upper.tv_sec,
277                         (int)hist->buckets[i].upper.tv_usec,
278                         (unsigned long)hist->buckets[i].count);
279         }
280         timehist_delete(hist);
281 }
282
283 /** print extended */
284 static void print_extended(struct ub_stats_info* s)
285 {
286         int i;
287         char nm[16];
288
289         /* TYPE */
290         for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
291                 if(inhibit_zero && s->svr.qtype[i] == 0)
292                         continue;
293                 sldns_wire2str_type_buf((uint16_t)i, nm, sizeof(nm));
294                 PR_UL_SUB("num.query.type", nm, s->svr.qtype[i]);
295         }
296         if(!inhibit_zero || s->svr.qtype_big) {
297                 PR_UL("num.query.type.other", s->svr.qtype_big);
298         }
299
300         /* CLASS */
301         for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
302                 if(inhibit_zero && s->svr.qclass[i] == 0)
303                         continue;
304                 sldns_wire2str_class_buf((uint16_t)i, nm, sizeof(nm));
305                 PR_UL_SUB("num.query.class", nm, s->svr.qclass[i]);
306         }
307         if(!inhibit_zero || s->svr.qclass_big) {
308                 PR_UL("num.query.class.other", s->svr.qclass_big);
309         }
310
311         /* OPCODE */
312         for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
313                 if(inhibit_zero && s->svr.qopcode[i] == 0)
314                         continue;
315                 sldns_wire2str_opcode_buf(i, nm, sizeof(nm));
316                 PR_UL_SUB("num.query.opcode", nm, s->svr.qopcode[i]);
317         }
318
319         /* transport */
320         PR_UL("num.query.tcp", s->svr.qtcp);
321         PR_UL("num.query.tcpout", s->svr.qtcp_outgoing);
322         PR_UL("num.query.ipv6", s->svr.qipv6);
323
324         /* flags */
325         PR_UL("num.query.flags.QR", s->svr.qbit_QR);
326         PR_UL("num.query.flags.AA", s->svr.qbit_AA);
327         PR_UL("num.query.flags.TC", s->svr.qbit_TC);
328         PR_UL("num.query.flags.RD", s->svr.qbit_RD);
329         PR_UL("num.query.flags.RA", s->svr.qbit_RA);
330         PR_UL("num.query.flags.Z", s->svr.qbit_Z);
331         PR_UL("num.query.flags.AD", s->svr.qbit_AD);
332         PR_UL("num.query.flags.CD", s->svr.qbit_CD);
333         PR_UL("num.query.edns.present", s->svr.qEDNS);
334         PR_UL("num.query.edns.DO", s->svr.qEDNS_DO);
335
336         /* RCODE */
337         for(i=0; i<UB_STATS_RCODE_NUM; i++) {
338                 /* Always include RCODEs 0-5 */
339                 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
340                         continue;
341                 sldns_wire2str_rcode_buf(i, nm, sizeof(nm));
342                 PR_UL_SUB("num.answer.rcode", nm, s->svr.ans_rcode[i]);
343         }
344         if(!inhibit_zero || s->svr.ans_rcode_nodata) {
345                 PR_UL("num.answer.rcode.nodata", s->svr.ans_rcode_nodata);
346         }
347         /* iteration */
348         PR_UL("num.query.ratelimited", s->svr.queries_ratelimited);
349         /* validation */
350         PR_UL("num.answer.secure", s->svr.ans_secure);
351         PR_UL("num.answer.bogus", s->svr.ans_bogus);
352         PR_UL("num.rrset.bogus", s->svr.rrset_bogus);
353         PR_UL("num.query.aggressive.NOERROR", s->svr.num_neg_cache_noerror);
354         PR_UL("num.query.aggressive.NXDOMAIN", s->svr.num_neg_cache_nxdomain);
355         /* threat detection */
356         PR_UL("unwanted.queries", s->svr.unwanted_queries);
357         PR_UL("unwanted.replies", s->svr.unwanted_replies);
358         /* cache counts */
359         PR_UL("msg.cache.count", s->svr.msg_cache_count);
360         PR_UL("rrset.cache.count", s->svr.rrset_cache_count);
361         PR_UL("infra.cache.count", s->svr.infra_cache_count);
362         PR_UL("key.cache.count", s->svr.key_cache_count);
363 #ifdef USE_DNSCRYPT
364         PR_UL("dnscrypt_shared_secret.cache.count",
365                          s->svr.shared_secret_cache_count);
366         PR_UL("num.query.dnscrypt.shared_secret.cachemiss",
367                          s->svr.num_query_dnscrypt_secret_missed_cache);
368         PR_UL("dnscrypt_nonce.cache.count", s->svr.nonce_cache_count);
369         PR_UL("num.query.dnscrypt.replay",
370                          s->svr.num_query_dnscrypt_replay);
371 #endif /* USE_DNSCRYPT */
372         PR_UL("num.query.authzone.up", s->svr.num_query_authzone_up);
373         PR_UL("num.query.authzone.down", s->svr.num_query_authzone_down);
374 }
375
376 /** print statistics out of memory structures */
377 static void do_stats_shm(struct config_file* cfg, struct ub_stats_info* stats,
378         struct ub_shm_stat_info* shm_stat)
379 {
380         int i;
381         char nm[32];
382         for(i=0; i<cfg->num_threads; i++) {
383                 snprintf(nm, sizeof(nm), "thread%d", i);
384                 pr_stats(nm, &stats[i+1]);
385         }
386         pr_stats("total", &stats[0]);
387         print_uptime(shm_stat);
388         if(cfg->stat_extended) {
389                 print_mem(shm_stat);
390                 print_hist(stats);
391                 print_extended(stats);
392         }
393 }
394 #endif /* HAVE_SHMGET */
395
396 /** print statistics from shm memory segment */
397 static void print_stats_shm(const char* cfgfile)
398 {
399 #ifdef HAVE_SHMGET
400         struct config_file* cfg;
401         struct ub_stats_info* stats;
402         struct ub_shm_stat_info* shm_stat;
403         int id_ctl, id_arr;
404         /* read config */
405         if(!(cfg = config_create()))
406                 fatal_exit("out of memory");
407         if(!config_read(cfg, cfgfile, NULL))
408                 fatal_exit("could not read config file");
409         /* get shm segments */
410         id_ctl = shmget(cfg->shm_key, sizeof(int), SHM_R|SHM_W);
411         if(id_ctl == -1) {
412                 fatal_exit("shmget(%d): %s", cfg->shm_key, strerror(errno));
413         }
414         id_arr = shmget(cfg->shm_key+1, sizeof(int), SHM_R|SHM_W);
415         if(id_arr == -1) {
416                 fatal_exit("shmget(%d): %s", cfg->shm_key+1, strerror(errno));
417         }
418         shm_stat = (struct ub_shm_stat_info*)shmat(id_ctl, NULL, 0);
419         if(shm_stat == (void*)-1) {
420                 fatal_exit("shmat(%d): %s", id_ctl, strerror(errno));
421         }
422         stats = (struct ub_stats_info*)shmat(id_arr, NULL, 0);
423         if(stats == (void*)-1) {
424                 fatal_exit("shmat(%d): %s", id_arr, strerror(errno));
425         }
426
427         /* print the stats */
428         do_stats_shm(cfg, stats, shm_stat);
429
430         /* shutdown */
431         shmdt(shm_stat);
432         shmdt(stats);
433         config_delete(cfg);
434 #else
435         (void)cfgfile;
436 #endif /* HAVE_SHMGET */
437 }
438
439 /** exit with ssl error */
440 static void ssl_err(const char* s)
441 {
442         fprintf(stderr, "error: %s\n", s);
443         ERR_print_errors_fp(stderr);
444         exit(1);
445 }
446
447 /** setup SSL context */
448 static SSL_CTX*
449 setup_ctx(struct config_file* cfg)
450 {
451         char* s_cert=NULL, *c_key=NULL, *c_cert=NULL;
452         SSL_CTX* ctx;
453
454         if(!(options_remote_is_address(cfg) && cfg->control_use_cert))
455                 return NULL;
456         s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
457         c_key = fname_after_chroot(cfg->control_key_file, cfg, 1);
458         c_cert = fname_after_chroot(cfg->control_cert_file, cfg, 1);
459         if(!s_cert || !c_key || !c_cert)
460                 fatal_exit("out of memory");
461         ctx = SSL_CTX_new(SSLv23_client_method());
462         if(!ctx)
463                 ssl_err("could not allocate SSL_CTX pointer");
464         if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
465                 != SSL_OP_NO_SSLv2)
466                 ssl_err("could not set SSL_OP_NO_SSLv2");
467         if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
468                 != SSL_OP_NO_SSLv3)
469                 ssl_err("could not set SSL_OP_NO_SSLv3");
470         if(!SSL_CTX_use_certificate_chain_file(ctx,c_cert) ||
471             !SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM)
472             || !SSL_CTX_check_private_key(ctx))
473                 ssl_err("Error setting up SSL_CTX client key and cert");
474         if (SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1)
475                 ssl_err("Error setting up SSL_CTX verify, server cert");
476         SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
477
478         free(s_cert);
479         free(c_key);
480         free(c_cert);
481         return ctx;
482 }
483
484 /** contact the server with TCP connect */
485 static int
486 contact_server(const char* svr, struct config_file* cfg, int statuscmd)
487 {
488         struct sockaddr_storage addr;
489         socklen_t addrlen;
490         int addrfamily = 0, proto = IPPROTO_TCP;
491         int fd, useport = 1;
492         /* use svr or the first config entry */
493         if(!svr) {
494                 if(cfg->control_ifs.first) {
495                         svr = cfg->control_ifs.first->str;
496                 } else if(cfg->do_ip4) {
497                         svr = "127.0.0.1";
498                 } else {
499                         svr = "::1";
500                 }
501                 /* config 0 addr (everything), means ask localhost */
502                 if(strcmp(svr, "0.0.0.0") == 0)
503                         svr = "127.0.0.1";
504                 else if(strcmp(svr, "::0") == 0 ||
505                         strcmp(svr, "0::0") == 0 ||
506                         strcmp(svr, "0::") == 0 ||
507                         strcmp(svr, "::") == 0)
508                         svr = "::1";
509         }
510         if(strchr(svr, '@')) {
511                 if(!extstrtoaddr(svr, &addr, &addrlen))
512                         fatal_exit("could not parse IP@port: %s", svr);
513 #ifdef HAVE_SYS_UN_H
514         } else if(svr[0] == '/') {
515                 struct sockaddr_un* usock = (struct sockaddr_un *) &addr;
516                 usock->sun_family = AF_LOCAL;
517 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
518                 usock->sun_len = (unsigned)sizeof(usock);
519 #endif
520                 (void)strlcpy(usock->sun_path, svr, sizeof(usock->sun_path));
521                 addrlen = (socklen_t)sizeof(struct sockaddr_un);
522                 addrfamily = AF_LOCAL;
523                 useport = 0;
524                 proto = 0;
525 #endif
526         } else {
527                 if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen))
528                         fatal_exit("could not parse IP: %s", svr);
529         }
530
531         if(addrfamily == 0)
532                 addrfamily = addr_is_ip6(&addr, addrlen)?PF_INET6:PF_INET;
533         fd = socket(addrfamily, SOCK_STREAM, proto);
534         if(fd == -1) {
535 #ifndef USE_WINSOCK
536                 fatal_exit("socket: %s", strerror(errno));
537 #else
538                 fatal_exit("socket: %s", wsa_strerror(WSAGetLastError()));
539 #endif
540         }
541         if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) {
542 #ifndef USE_WINSOCK
543                 int err = errno;
544                 if(!useport) log_err("connect: %s for %s", strerror(err), svr);
545                 else log_err_addr("connect", strerror(err), &addr, addrlen);
546                 if(err == ECONNREFUSED && statuscmd) {
547                         printf("unbound is stopped\n");
548                         exit(3);
549                 }
550 #else
551                 int wsaerr = WSAGetLastError();
552                 if(!useport) log_err("connect: %s for %s", wsa_strerror(wsaerr), svr);
553                 else log_err_addr("connect", wsa_strerror(wsaerr), &addr, addrlen);
554                 if(wsaerr == WSAECONNREFUSED && statuscmd) {
555                         printf("unbound is stopped\n");
556                         exit(3);
557                 }
558 #endif
559                 exit(1);
560         }
561         return fd;
562 }
563
564 /** setup SSL on the connection */
565 static SSL*
566 setup_ssl(SSL_CTX* ctx, int fd)
567 {
568         SSL* ssl;
569         X509* x;
570         int r;
571
572         if(!ctx) return NULL;
573         ssl = SSL_new(ctx);
574         if(!ssl)
575                 ssl_err("could not SSL_new");
576         SSL_set_connect_state(ssl);
577         (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
578         if(!SSL_set_fd(ssl, fd))
579                 ssl_err("could not SSL_set_fd");
580         while(1) {
581                 ERR_clear_error();
582                 if( (r=SSL_do_handshake(ssl)) == 1)
583                         break;
584                 r = SSL_get_error(ssl, r);
585                 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
586                         ssl_err("SSL handshake failed");
587                 /* wants to be called again */
588         }
589
590         /* check authenticity of server */
591         if(SSL_get_verify_result(ssl) != X509_V_OK)
592                 ssl_err("SSL verification failed");
593         x = SSL_get_peer_certificate(ssl);
594         if(!x)
595                 ssl_err("Server presented no peer certificate");
596         X509_free(x);
597
598         return ssl;
599 }
600
601 /** read from ssl or fd, fatalexit on error, 0 EOF, 1 success */
602 static int
603 remote_read(SSL* ssl, int fd, char* buf, size_t len)
604 {
605         if(ssl) {
606                 int r;
607                 ERR_clear_error();
608                 if((r = SSL_read(ssl, buf, (int)len-1)) <= 0) {
609                         if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
610                                 /* EOF */
611                                 return 0;
612                         }
613                         ssl_err("could not SSL_read");
614                 }
615                 buf[r] = 0;
616         } else {
617                 ssize_t rr = recv(fd, buf, len-1, 0);
618                 if(rr <= 0) {
619                         if(rr == 0) {
620                                 /* EOF */
621                                 return 0;
622                         }
623 #ifndef USE_WINSOCK
624                         fatal_exit("could not recv: %s", strerror(errno));
625 #else
626                         fatal_exit("could not recv: %s", wsa_strerror(WSAGetLastError()));
627 #endif
628                 }
629                 buf[rr] = 0;
630         }
631         return 1;
632 }
633
634 /** write to ssl or fd, fatalexit on error */
635 static void
636 remote_write(SSL* ssl, int fd, const char* buf, size_t len)
637 {
638         if(ssl) {
639                 if(SSL_write(ssl, buf, (int)len) <= 0)
640                         ssl_err("could not SSL_write");
641         } else {
642                 if(send(fd, buf, len, 0) < (ssize_t)len) {
643 #ifndef USE_WINSOCK
644                         fatal_exit("could not send: %s", strerror(errno));
645 #else
646                         fatal_exit("could not send: %s", wsa_strerror(WSAGetLastError()));
647 #endif
648                 }
649         }
650 }
651
652 /** send stdin to server */
653 static void
654 send_file(SSL* ssl, int fd, FILE* in, char* buf, size_t sz)
655 {
656         while(fgets(buf, (int)sz, in)) {
657                 remote_write(ssl, fd, buf, strlen(buf));
658         }
659 }
660
661 /** send end-of-file marker to server */
662 static void
663 send_eof(SSL* ssl, int fd)
664 {
665         char e[] = {0x04, 0x0a};
666         remote_write(ssl, fd, e, sizeof(e));
667 }
668
669 /** send command and display result */
670 static int
671 go_cmd(SSL* ssl, int fd, int quiet, int argc, char* argv[])
672 {
673         char pre[10];
674         const char* space=" ";
675         const char* newline="\n";
676         int was_error = 0, first_line = 1;
677         int i;
678         char buf[1024];
679         snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
680         remote_write(ssl, fd, pre, strlen(pre));
681         for(i=0; i<argc; i++) {
682                 remote_write(ssl, fd, space, strlen(space));
683                 remote_write(ssl, fd, argv[i], strlen(argv[i]));
684         }
685         remote_write(ssl, fd, newline, strlen(newline));
686
687         if(argc == 1 && strcmp(argv[0], "load_cache") == 0) {
688                 send_file(ssl, fd, stdin, buf, sizeof(buf));
689         }
690         else if(argc == 1 && (strcmp(argv[0], "local_zones") == 0 ||
691                 strcmp(argv[0], "local_zones_remove") == 0 ||
692                 strcmp(argv[0], "local_datas") == 0 ||
693                 strcmp(argv[0], "local_datas_remove") == 0)) {
694                 send_file(ssl, fd, stdin, buf, sizeof(buf));
695                 send_eof(ssl, fd);
696         }
697
698         while(1) {
699                 if(remote_read(ssl, fd, buf, sizeof(buf)) == 0) {
700                         break; /* EOF */
701                 }
702                 if(first_line && strncmp(buf, "error", 5) == 0) {
703                         printf("%s", buf);
704                         was_error = 1;
705                 } else if (!quiet)
706                         printf("%s", buf);
707
708                 first_line = 0;
709         }
710         return was_error;
711 }
712
713 /** go ahead and read config, contact server and perform command and display */
714 static int
715 go(const char* cfgfile, char* svr, int quiet, int argc, char* argv[])
716 {
717         struct config_file* cfg;
718         int fd, ret;
719         SSL_CTX* ctx;
720         SSL* ssl;
721
722         /* read config */
723         if(!(cfg = config_create()))
724                 fatal_exit("out of memory");
725         if(!config_read(cfg, cfgfile, NULL))
726                 fatal_exit("could not read config file");
727         if(!cfg->remote_control_enable)
728                 log_warn("control-enable is 'no' in the config file.");
729 #ifdef UB_ON_WINDOWS
730         w_config_adjust_directory(cfg);
731 #endif
732         ctx = setup_ctx(cfg);
733
734         /* contact server */
735         fd = contact_server(svr, cfg, argc>0&&strcmp(argv[0],"status")==0);
736         ssl = setup_ssl(ctx, fd);
737
738         /* send command */
739         ret = go_cmd(ssl, fd, quiet, argc, argv);
740
741         if(ssl) SSL_free(ssl);
742 #ifndef USE_WINSOCK
743         close(fd);
744 #else
745         closesocket(fd);
746 #endif
747         if(ctx) SSL_CTX_free(ctx);
748         config_delete(cfg);
749         return ret;
750 }
751
752 /** getopt global, in case header files fail to declare it. */
753 extern int optind;
754 /** getopt global, in case header files fail to declare it. */
755 extern char* optarg;
756
757 /** Main routine for unbound-control */
758 int main(int argc, char* argv[])
759 {
760         int c, ret;
761         int quiet = 0;
762         const char* cfgfile = CONFIGFILE;
763         char* svr = NULL;
764 #ifdef USE_WINSOCK
765         int r;
766         WSADATA wsa_data;
767 #endif
768 #ifdef USE_THREAD_DEBUG
769         /* stop the file output from unbound-control, overwrites the servers */
770         extern int check_locking_order;
771         check_locking_order = 0;
772 #endif /* USE_THREAD_DEBUG */
773         log_ident_set("unbound-control");
774         log_init(NULL, 0, NULL);
775         checklock_start();
776 #ifdef USE_WINSOCK
777         /* use registry config file in preference to compiletime location */
778         if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
779                 cfgfile = CONFIGFILE;
780 #endif
781         /* parse the options */
782         while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
783                 switch(c) {
784                 case 'c':
785                         cfgfile = optarg;
786                         break;
787                 case 's':
788                         svr = optarg;
789                         break;
790                 case 'q':
791                         quiet = 1;
792                         break;
793                 case '?':
794                 case 'h':
795                 default:
796                         usage();
797                 }
798         }
799         argc -= optind;
800         argv += optind;
801         if(argc == 0)
802                 usage();
803         if(argc >= 1 && strcmp(argv[0], "start")==0) {
804                 if(execlp("unbound", "unbound", "-c", cfgfile, 
805                         (char*)NULL) < 0) {
806                         fatal_exit("could not exec unbound: %s",
807                                 strerror(errno));
808                 }
809         }
810         if(argc >= 1 && strcmp(argv[0], "stats_shm")==0) {
811                 print_stats_shm(cfgfile);
812                 return 0;
813         }
814
815 #ifdef USE_WINSOCK
816         if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
817                 fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
818 #endif
819
820 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
821         ERR_load_crypto_strings();
822 #endif
823 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
824         ERR_load_SSL_strings();
825 #endif
826 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
827         OpenSSL_add_all_algorithms();
828 #else
829         OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
830                 | OPENSSL_INIT_ADD_ALL_DIGESTS
831                 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
832 #endif
833 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
834         (void)SSL_library_init();
835 #else
836         (void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
837 #endif
838
839         if(!RAND_status()) {
840                 /* try to seed it */
841                 unsigned char buf[256];
842                 unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
843                 unsigned int v = seed;
844                 size_t i;
845                 for(i=0; i<256/sizeof(v); i++) {
846                         memmove(buf+i*sizeof(v), &v, sizeof(v));
847                         v = v*seed + (unsigned int)i;
848                 }
849                 RAND_seed(buf, 256);
850                 log_warn("no entropy, seeding openssl PRNG with time\n");
851         }
852
853         ret = go(cfgfile, svr, quiet, argc, argv);
854
855 #ifdef USE_WINSOCK
856         WSACleanup();
857 #endif
858         checklock_stop();
859         return ret;
860 }