]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/unbound/smallapp/unbound-control.c
Upgrade Unbound to 1.6.4. More to follow.
[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:  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("  view_list_local_zones view    list local-zones in view\n");
146         printf("  view_list_local_data  view    list local-data RRs in view\n");
147         printf("  view_local_zone view name type        add local-zone in view\n");
148         printf("  view_local_zone_remove view name      remove local-zone in view\n");
149         printf("  view_local_data view RR...            add local-data in view\n");
150         printf("  view_local_data_remove view name      remove local-data in view\n");
151         printf("Version %s\n", PACKAGE_VERSION);
152         printf("BSD licensed, see LICENSE in source package for details.\n");
153         printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
154         exit(1);
155 }
156
157 #ifdef HAVE_SHMGET
158 /** what to put on statistics lines between var and value, ": " or "=" */
159 #define SQ "="
160 /** if true, inhibits a lot of =0 lines from the stats output */
161 static const int inhibit_zero = 1;
162 /** divide sum of timers to get average */
163 static void
164 timeval_divide(struct timeval* avg, const struct timeval* sum, long long d)
165 {
166 #ifndef S_SPLINT_S
167         size_t leftover;
168         if(d == 0) {
169                 avg->tv_sec = 0;
170                 avg->tv_usec = 0;
171                 return;
172         }
173         avg->tv_sec = sum->tv_sec / d;
174         avg->tv_usec = sum->tv_usec / d;
175         /* handle fraction from seconds divide */
176         leftover = sum->tv_sec - avg->tv_sec*d;
177         avg->tv_usec += (leftover*1000000)/d;
178 #endif
179 }
180
181 /** print unsigned long stats value */
182 #define PR_UL_NM(str, var) printf("%s."str SQ"%lu\n", nm, (unsigned long)(var));
183 #define PR_UL(str, var) printf(str SQ"%lu\n", (unsigned long)(var));
184 #define PR_UL_SUB(str, nm, var) printf(str".%s"SQ"%lu\n", nm, (unsigned long)(var));
185 #define PR_TIMEVAL(str, var) printf(str SQ ARG_LL "d.%6.6d\n", \
186         (long long)var.tv_sec, (int)var.tv_usec);
187 #define PR_STATSTIME(str, var) printf(str SQ ARG_LL "d.%6.6d\n", \
188         (long long)var ## _sec, (int)var ## _usec);
189 #define PR_LL(str, var) printf(str SQ ARG_LL"d\n", (long long)(var));
190
191 /** print stat block */
192 static void pr_stats(const char* nm, struct ub_stats_info* s)
193 {
194         struct timeval sumwait, avg;
195         PR_UL_NM("num.queries", s->svr.num_queries);
196         PR_UL_NM("num.queries_ip_ratelimited", 
197                 s->svr.num_queries_ip_ratelimited);
198         PR_UL_NM("num.cachehits",
199                 s->svr.num_queries - s->svr.num_queries_missed_cache);
200         PR_UL_NM("num.cachemiss", s->svr.num_queries_missed_cache);
201         PR_UL_NM("num.prefetch", s->svr.num_queries_prefetch);
202         PR_UL_NM("num.zero_ttl", s->svr.zero_ttl_responses);
203         PR_UL_NM("num.recursivereplies", s->mesh_replies_sent);
204 #ifdef USE_DNSCRYPT
205     PR_UL_NM("num.dnscrypt.crypted", s->svr.num_query_dnscrypt_crypted);
206     PR_UL_NM("num.dnscrypt.cert", s->svr.num_query_dnscrypt_cert);
207     PR_UL_NM("num.dnscrypt.cleartext", s->svr.num_query_dnscrypt_cleartext);
208     PR_UL_NM("num.dnscrypt.malformed",
209              s->svr.num_query_dnscrypt_crypted_malformed);
210 #endif
211         printf("%s.requestlist.avg"SQ"%g\n", nm,
212                 (s->svr.num_queries_missed_cache+s->svr.num_queries_prefetch)?
213                         (double)s->svr.sum_query_list_size/
214                         (double)(s->svr.num_queries_missed_cache+
215                         s->svr.num_queries_prefetch) : 0.0);
216         PR_UL_NM("requestlist.max", s->svr.max_query_list_size);
217         PR_UL_NM("requestlist.overwritten", s->mesh_jostled);
218         PR_UL_NM("requestlist.exceeded", s->mesh_dropped);
219         PR_UL_NM("requestlist.current.all", s->mesh_num_states);
220         PR_UL_NM("requestlist.current.user", s->mesh_num_reply_states);
221 #ifndef S_SPLINT_S
222         sumwait.tv_sec = s->mesh_replies_sum_wait_sec;
223         sumwait.tv_usec = s->mesh_replies_sum_wait_usec;
224 #endif
225         timeval_divide(&avg, &sumwait, s->mesh_replies_sent);
226         printf("%s.", nm);
227         PR_TIMEVAL("recursion.time.avg", avg);
228         printf("%s.recursion.time.median"SQ"%g\n", nm, s->mesh_time_median);
229         PR_UL_NM("tcpusage", s->svr.tcp_accept_usage);
230 }
231
232 /** print uptime */
233 static void print_uptime(struct ub_shm_stat_info* shm_stat)
234 {
235         PR_STATSTIME("time.now", shm_stat->time.now);
236         PR_STATSTIME("time.up", shm_stat->time.up);
237         PR_STATSTIME("time.elapsed", shm_stat->time.elapsed);
238 }
239
240 /** print memory usage */
241 static void print_mem(struct ub_shm_stat_info* shm_stat)
242 {
243         PR_LL("mem.cache.rrset", shm_stat->mem.rrset);
244         PR_LL("mem.cache.message", shm_stat->mem.msg);
245         PR_LL("mem.mod.iterator", shm_stat->mem.iter);
246         PR_LL("mem.mod.validator", shm_stat->mem.val);
247         PR_LL("mem.mod.respip", shm_stat->mem.respip);
248 #ifdef CLIENT_SUBNET
249         PR_LL("mem.mod.subnet", shm_stat->mem.subnet);
250 #endif
251 #ifdef USE_IPSECMOD
252         PR_LL("mem.mod.ipsecmod", shm_stat->mem.ipsecmod);
253 #endif
254 }
255
256 /** print histogram */
257 static void print_hist(struct ub_stats_info* s)
258 {
259         struct timehist* hist;
260         size_t i;
261         hist = timehist_setup();
262         if(!hist)
263                 fatal_exit("out of memory");
264         timehist_import(hist, s->svr.hist, NUM_BUCKETS_HIST);
265         for(i=0; i<hist->num; i++) {
266                 printf("histogram.%6.6d.%6.6d.to.%6.6d.%6.6d=%lu\n",
267                         (int)hist->buckets[i].lower.tv_sec,
268                         (int)hist->buckets[i].lower.tv_usec,
269                         (int)hist->buckets[i].upper.tv_sec,
270                         (int)hist->buckets[i].upper.tv_usec,
271                         (unsigned long)hist->buckets[i].count);
272         }
273         timehist_delete(hist);
274 }
275
276 /** print extended */
277 static void print_extended(struct ub_stats_info* s)
278 {
279         int i;
280         char nm[16];
281
282         /* TYPE */
283         for(i=0; i<UB_STATS_QTYPE_NUM; i++) {
284                 if(inhibit_zero && s->svr.qtype[i] == 0)
285                         continue;
286                 sldns_wire2str_type_buf((uint16_t)i, nm, sizeof(nm));
287                 PR_UL_SUB("num.query.type", nm, s->svr.qtype[i]);
288         }
289         if(!inhibit_zero || s->svr.qtype_big) {
290                 PR_UL("num.query.type.other", s->svr.qtype_big);
291         }
292
293         /* CLASS */
294         for(i=0; i<UB_STATS_QCLASS_NUM; i++) {
295                 if(inhibit_zero && s->svr.qclass[i] == 0)
296                         continue;
297                 sldns_wire2str_class_buf((uint16_t)i, nm, sizeof(nm));
298                 PR_UL_SUB("num.query.class", nm, s->svr.qclass[i]);
299         }
300         if(!inhibit_zero || s->svr.qclass_big) {
301                 PR_UL("num.query.class.other", s->svr.qclass_big);
302         }
303
304         /* OPCODE */
305         for(i=0; i<UB_STATS_OPCODE_NUM; i++) {
306                 if(inhibit_zero && s->svr.qopcode[i] == 0)
307                         continue;
308                 sldns_wire2str_opcode_buf(i, nm, sizeof(nm));
309                 PR_UL_SUB("num.query.opcode", nm, s->svr.qopcode[i]);
310         }
311
312         /* transport */
313         PR_UL("num.query.tcp", s->svr.qtcp);
314         PR_UL("num.query.tcpout", s->svr.qtcp_outgoing);
315         PR_UL("num.query.ipv6", s->svr.qipv6);
316
317         /* flags */
318         PR_UL("num.query.flags.QR", s->svr.qbit_QR);
319         PR_UL("num.query.flags.AA", s->svr.qbit_AA);
320         PR_UL("num.query.flags.TC", s->svr.qbit_TC);
321         PR_UL("num.query.flags.RD", s->svr.qbit_RD);
322         PR_UL("num.query.flags.RA", s->svr.qbit_RA);
323         PR_UL("num.query.flags.Z", s->svr.qbit_Z);
324         PR_UL("num.query.flags.AD", s->svr.qbit_AD);
325         PR_UL("num.query.flags.CD", s->svr.qbit_CD);
326         PR_UL("num.query.edns.present", s->svr.qEDNS);
327         PR_UL("num.query.edns.DO", s->svr.qEDNS_DO);
328
329         /* RCODE */
330         for(i=0; i<UB_STATS_RCODE_NUM; i++) {
331                 /* Always include RCODEs 0-5 */
332                 if(inhibit_zero && i > LDNS_RCODE_REFUSED && s->svr.ans_rcode[i] == 0)
333                         continue;
334                 sldns_wire2str_rcode_buf(i, nm, sizeof(nm));
335                 PR_UL_SUB("num.answer.rcode", nm, s->svr.ans_rcode[i]);
336         }
337         if(!inhibit_zero || s->svr.ans_rcode_nodata) {
338                 PR_UL("num.answer.rcode.nodata", s->svr.ans_rcode_nodata);
339         }
340         /* validation */
341         PR_UL("num.answer.secure", s->svr.ans_secure);
342         PR_UL("num.answer.bogus", s->svr.ans_bogus);
343         PR_UL("num.rrset.bogus", s->svr.rrset_bogus);
344         /* threat detection */
345         PR_UL("unwanted.queries", s->svr.unwanted_queries);
346         PR_UL("unwanted.replies", s->svr.unwanted_replies);
347         /* cache counts */
348         PR_UL("msg.cache.count", s->svr.msg_cache_count);
349         PR_UL("rrset.cache.count", s->svr.rrset_cache_count);
350         PR_UL("infra.cache.count", s->svr.infra_cache_count);
351         PR_UL("key.cache.count", s->svr.key_cache_count);
352 }
353
354 /** print statistics out of memory structures */
355 static void do_stats_shm(struct config_file* cfg, struct ub_stats_info* stats,
356         struct ub_shm_stat_info* shm_stat)
357 {
358         int i;
359         char nm[16];
360         for(i=0; i<cfg->num_threads; i++) {
361                 snprintf(nm, sizeof(nm), "thread%d", i);
362                 pr_stats(nm, &stats[i+1]);
363         }
364         pr_stats("total", &stats[0]);
365         print_uptime(shm_stat);
366         if(cfg->stat_extended) {
367                 print_mem(shm_stat);
368                 print_hist(stats);
369                 print_extended(stats);
370         }
371 }
372 #endif /* HAVE_SHMGET */
373
374 /** print statistics from shm memory segment */
375 static void print_stats_shm(const char* cfgfile)
376 {
377 #ifdef HAVE_SHMGET
378         struct config_file* cfg;
379         struct ub_stats_info* stats;
380         struct ub_shm_stat_info* shm_stat;
381         int id_ctl, id_arr;
382         /* read config */
383         if(!(cfg = config_create()))
384                 fatal_exit("out of memory");
385         if(!config_read(cfg, cfgfile, NULL))
386                 fatal_exit("could not read config file");
387         /* get shm segments */
388         id_ctl = shmget(cfg->shm_key, sizeof(int), SHM_R|SHM_W);
389         if(id_ctl == -1) {
390                 fatal_exit("shmget(%d): %s", cfg->shm_key, strerror(errno));
391         }
392         id_arr = shmget(cfg->shm_key+1, sizeof(int), SHM_R|SHM_W);
393         if(id_arr == -1) {
394                 fatal_exit("shmget(%d): %s", cfg->shm_key+1, strerror(errno));
395         }
396         shm_stat = (struct ub_shm_stat_info*)shmat(id_ctl, NULL, 0);
397         if(shm_stat == (void*)-1) {
398                 fatal_exit("shmat(%d): %s", id_ctl, strerror(errno));
399         }
400         stats = (struct ub_stats_info*)shmat(id_arr, NULL, 0);
401         if(stats == (void*)-1) {
402                 fatal_exit("shmat(%d): %s", id_arr, strerror(errno));
403         }
404
405         /* print the stats */
406         do_stats_shm(cfg, stats, shm_stat);
407
408         /* shutdown */
409         shmdt(shm_stat);
410         shmdt(stats);
411         config_delete(cfg);
412 #else
413         (void)cfgfile;
414 #endif /* HAVE_SHMGET */
415 }
416
417 /** exit with ssl error */
418 static void ssl_err(const char* s)
419 {
420         fprintf(stderr, "error: %s\n", s);
421         ERR_print_errors_fp(stderr);
422         exit(1);
423 }
424
425 /** setup SSL context */
426 static SSL_CTX*
427 setup_ctx(struct config_file* cfg)
428 {
429         char* s_cert=NULL, *c_key=NULL, *c_cert=NULL;
430         SSL_CTX* ctx;
431
432         if(cfg->remote_control_use_cert) {
433                 s_cert = fname_after_chroot(cfg->server_cert_file, cfg, 1);
434                 c_key = fname_after_chroot(cfg->control_key_file, cfg, 1);
435                 c_cert = fname_after_chroot(cfg->control_cert_file, cfg, 1);
436                 if(!s_cert || !c_key || !c_cert)
437                         fatal_exit("out of memory");
438         }
439         ctx = SSL_CTX_new(SSLv23_client_method());
440         if(!ctx)
441                 ssl_err("could not allocate SSL_CTX pointer");
442         if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2) & SSL_OP_NO_SSLv2)
443                 != SSL_OP_NO_SSLv2)
444                 ssl_err("could not set SSL_OP_NO_SSLv2");
445         if(cfg->remote_control_use_cert) {
446                 if((SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3) & SSL_OP_NO_SSLv3)
447                         != SSL_OP_NO_SSLv3)
448                         ssl_err("could not set SSL_OP_NO_SSLv3");
449                 if(!SSL_CTX_use_certificate_chain_file(ctx,c_cert) ||
450                     !SSL_CTX_use_PrivateKey_file(ctx,c_key,SSL_FILETYPE_PEM)
451                     || !SSL_CTX_check_private_key(ctx))
452                         ssl_err("Error setting up SSL_CTX client key and cert");
453                 if (SSL_CTX_load_verify_locations(ctx, s_cert, NULL) != 1)
454                         ssl_err("Error setting up SSL_CTX verify, server cert");
455                 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
456
457                 free(s_cert);
458                 free(c_key);
459                 free(c_cert);
460         } else {
461                 /* Use ciphers that don't require authentication  */
462 #ifdef HAVE_SSL_CTX_SET_SECURITY_LEVEL
463                 SSL_CTX_set_security_level(ctx, 0);
464 #endif
465                 if(!SSL_CTX_set_cipher_list(ctx, "aNULL, eNULL"))
466                         ssl_err("Error setting NULL cipher!");
467         }
468         return ctx;
469 }
470
471 /** contact the server with TCP connect */
472 static int
473 contact_server(const char* svr, struct config_file* cfg, int statuscmd)
474 {
475         struct sockaddr_storage addr;
476         socklen_t addrlen;
477         int addrfamily = 0;
478         int fd;
479         /* use svr or the first config entry */
480         if(!svr) {
481                 if(cfg->control_ifs) {
482                         svr = cfg->control_ifs->str;
483                 } else if(cfg->do_ip4) {
484                         svr = "127.0.0.1";
485                 } else {
486                         svr = "::1";
487                 }
488                 /* config 0 addr (everything), means ask localhost */
489                 if(strcmp(svr, "0.0.0.0") == 0)
490                         svr = "127.0.0.1";
491                 else if(strcmp(svr, "::0") == 0 ||
492                         strcmp(svr, "0::0") == 0 ||
493                         strcmp(svr, "0::") == 0 ||
494                         strcmp(svr, "::") == 0)
495                         svr = "::1";
496         }
497         if(strchr(svr, '@')) {
498                 if(!extstrtoaddr(svr, &addr, &addrlen))
499                         fatal_exit("could not parse IP@port: %s", svr);
500 #ifdef HAVE_SYS_UN_H
501         } else if(svr[0] == '/') {
502                 struct sockaddr_un* usock = (struct sockaddr_un *) &addr;
503                 usock->sun_family = AF_LOCAL;
504 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
505                 usock->sun_len = (unsigned)sizeof(usock);
506 #endif
507                 (void)strlcpy(usock->sun_path, svr, sizeof(usock->sun_path));
508                 addrlen = (socklen_t)sizeof(struct sockaddr_un);
509                 addrfamily = AF_LOCAL;
510 #endif
511         } else {
512                 if(!ipstrtoaddr(svr, cfg->control_port, &addr, &addrlen))
513                         fatal_exit("could not parse IP: %s", svr);
514         }
515
516         if(addrfamily == 0)
517                 addrfamily = addr_is_ip6(&addr, addrlen)?AF_INET6:AF_INET;
518         fd = socket(addrfamily, SOCK_STREAM, 0);
519         if(fd == -1) {
520 #ifndef USE_WINSOCK
521                 fatal_exit("socket: %s", strerror(errno));
522 #else
523                 fatal_exit("socket: %s", wsa_strerror(WSAGetLastError()));
524 #endif
525         }
526         if(connect(fd, (struct sockaddr*)&addr, addrlen) < 0) {
527 #ifndef USE_WINSOCK
528                 log_err_addr("connect", strerror(errno), &addr, addrlen);
529                 if(errno == ECONNREFUSED && statuscmd) {
530                         printf("unbound is stopped\n");
531                         exit(3);
532                 }
533 #else
534                 log_err_addr("connect", wsa_strerror(WSAGetLastError()), &addr, addrlen);
535                 if(WSAGetLastError() == WSAECONNREFUSED && statuscmd) {
536                         printf("unbound is stopped\n");
537                         exit(3);
538                 }
539 #endif
540                 exit(1);
541         }
542         return fd;
543 }
544
545 /** setup SSL on the connection */
546 static SSL*
547 setup_ssl(SSL_CTX* ctx, int fd, struct config_file* cfg)
548 {
549         SSL* ssl;
550         X509* x;
551         int r;
552
553         ssl = SSL_new(ctx);
554         if(!ssl)
555                 ssl_err("could not SSL_new");
556         SSL_set_connect_state(ssl);
557         (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
558         if(!SSL_set_fd(ssl, fd))
559                 ssl_err("could not SSL_set_fd");
560         while(1) {
561                 ERR_clear_error();
562                 if( (r=SSL_do_handshake(ssl)) == 1)
563                         break;
564                 r = SSL_get_error(ssl, r);
565                 if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE)
566                         ssl_err("SSL handshake failed");
567                 /* wants to be called again */
568         }
569
570         /* check authenticity of server */
571         if(SSL_get_verify_result(ssl) != X509_V_OK)
572                 ssl_err("SSL verification failed");
573         if(cfg->remote_control_use_cert) {
574                 x = SSL_get_peer_certificate(ssl);
575                 if(!x)
576                         ssl_err("Server presented no peer certificate");
577                 X509_free(x);
578         }
579
580         return ssl;
581 }
582
583 /** send stdin to server */
584 static void
585 send_file(SSL* ssl, FILE* in, char* buf, size_t sz)
586 {
587         while(fgets(buf, (int)sz, in)) {
588                 if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0)
589                         ssl_err("could not SSL_write contents");
590         }
591 }
592
593 /** send end-of-file marker to server */
594 static void
595 send_eof(SSL* ssl)
596 {
597         char e[] = {0x04, 0x0a};
598         if(SSL_write(ssl, e, (int)sizeof(e)) <= 0)
599                 ssl_err("could not SSL_write end-of-file marker");
600 }
601
602 /** send command and display result */
603 static int
604 go_cmd(SSL* ssl, int quiet, int argc, char* argv[])
605 {
606         char pre[10];
607         const char* space=" ";
608         const char* newline="\n";
609         int was_error = 0, first_line = 1;
610         int r, i;
611         char buf[1024];
612         snprintf(pre, sizeof(pre), "UBCT%d ", UNBOUND_CONTROL_VERSION);
613         if(SSL_write(ssl, pre, (int)strlen(pre)) <= 0)
614                 ssl_err("could not SSL_write");
615         for(i=0; i<argc; i++) {
616                 if(SSL_write(ssl, space, (int)strlen(space)) <= 0)
617                         ssl_err("could not SSL_write");
618                 if(SSL_write(ssl, argv[i], (int)strlen(argv[i])) <= 0)
619                         ssl_err("could not SSL_write");
620         }
621         if(SSL_write(ssl, newline, (int)strlen(newline)) <= 0)
622                 ssl_err("could not SSL_write");
623
624         if(argc == 1 && strcmp(argv[0], "load_cache") == 0) {
625                 send_file(ssl, stdin, buf, sizeof(buf));
626         }
627         else if(argc == 1 && (strcmp(argv[0], "local_zones") == 0 ||
628                 strcmp(argv[0], "local_zones_remove") == 0 ||
629                 strcmp(argv[0], "local_datas") == 0 ||
630                 strcmp(argv[0], "local_datas_remove") == 0)) {
631                 send_file(ssl, stdin, buf, sizeof(buf));
632                 send_eof(ssl);
633         }
634
635         while(1) {
636                 ERR_clear_error();
637                 if((r = SSL_read(ssl, buf, (int)sizeof(buf)-1)) <= 0) {
638                         if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
639                                 /* EOF */
640                                 break;
641                         }
642                         ssl_err("could not SSL_read");
643                 }
644                 buf[r] = 0;
645                 if(first_line && strncmp(buf, "error", 5) == 0) {
646                         printf("%s", buf);
647                         was_error = 1;
648                 } else if (!quiet)
649                         printf("%s", buf);
650
651                 first_line = 0;
652         }
653         return was_error;
654 }
655
656 /** go ahead and read config, contact server and perform command and display */
657 static int
658 go(const char* cfgfile, char* svr, int quiet, int argc, char* argv[])
659 {
660         struct config_file* cfg;
661         int fd, ret;
662         SSL_CTX* ctx;
663         SSL* ssl;
664
665         /* read config */
666         if(!(cfg = config_create()))
667                 fatal_exit("out of memory");
668         if(!config_read(cfg, cfgfile, NULL))
669                 fatal_exit("could not read config file");
670         if(!cfg->remote_control_enable)
671                 log_warn("control-enable is 'no' in the config file.");
672 #ifdef UB_ON_WINDOWS
673         w_config_adjust_directory(cfg);
674 #endif
675         ctx = setup_ctx(cfg);
676
677         /* contact server */
678         fd = contact_server(svr, cfg, argc>0&&strcmp(argv[0],"status")==0);
679         ssl = setup_ssl(ctx, fd, cfg);
680
681         /* send command */
682         ret = go_cmd(ssl, quiet, argc, argv);
683
684         SSL_free(ssl);
685 #ifndef USE_WINSOCK
686         close(fd);
687 #else
688         closesocket(fd);
689 #endif
690         SSL_CTX_free(ctx);
691         config_delete(cfg);
692         return ret;
693 }
694
695 /** getopt global, in case header files fail to declare it. */
696 extern int optind;
697 /** getopt global, in case header files fail to declare it. */
698 extern char* optarg;
699
700 /** Main routine for unbound-control */
701 int main(int argc, char* argv[])
702 {
703         int c, ret;
704         int quiet = 0;
705         const char* cfgfile = CONFIGFILE;
706         char* svr = NULL;
707 #ifdef USE_WINSOCK
708         int r;
709         WSADATA wsa_data;
710 #endif
711 #ifdef USE_THREAD_DEBUG
712         /* stop the file output from unbound-control, overwites the servers */
713         extern int check_locking_order;
714         check_locking_order = 0;
715 #endif /* USE_THREAD_DEBUG */
716         log_ident_set("unbound-control");
717         log_init(NULL, 0, NULL);
718         checklock_start();
719 #ifdef USE_WINSOCK
720         /* use registry config file in preference to compiletime location */
721         if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
722                 cfgfile = CONFIGFILE;
723 #endif
724         /* parse the options */
725         while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
726                 switch(c) {
727                 case 'c':
728                         cfgfile = optarg;
729                         break;
730                 case 's':
731                         svr = optarg;
732                         break;
733                 case 'q':
734                         quiet = 1;
735                         break;
736                 case '?':
737                 case 'h':
738                 default:
739                         usage();
740                 }
741         }
742         argc -= optind;
743         argv += optind;
744         if(argc == 0)
745                 usage();
746         if(argc >= 1 && strcmp(argv[0], "start")==0) {
747                 if(execlp("unbound", "unbound", "-c", cfgfile, 
748                         (char*)NULL) < 0) {
749                         fatal_exit("could not exec unbound: %s",
750                                 strerror(errno));
751                 }
752         }
753         if(argc >= 1 && strcmp(argv[0], "stats_shm")==0) {
754                 print_stats_shm(cfgfile);
755                 return 0;
756         }
757
758 #ifdef USE_WINSOCK
759         if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
760                 fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
761 #endif
762
763 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
764         ERR_load_crypto_strings();
765 #endif
766         ERR_load_SSL_strings();
767 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
768         OpenSSL_add_all_algorithms();
769 #else
770         OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
771                 | OPENSSL_INIT_ADD_ALL_DIGESTS
772                 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
773 #endif
774 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
775         (void)SSL_library_init();
776 #else
777         (void)OPENSSL_init_ssl(0, NULL);
778 #endif
779
780         if(!RAND_status()) {
781                 /* try to seed it */
782                 unsigned char buf[256];
783                 unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
784                 unsigned int v = seed;
785                 size_t i;
786                 for(i=0; i<256/sizeof(v); i++) {
787                         memmove(buf+i*sizeof(v), &v, sizeof(v));
788                         v = v*seed + (unsigned int)i;
789                 }
790                 RAND_seed(buf, 256);
791                 log_warn("no entropy, seeding openssl PRNG with time\n");
792         }
793
794         ret = go(cfgfile, svr, quiet, argc, argv);
795
796 #ifdef USE_WINSOCK
797         WSACleanup();
798 #endif
799         checklock_stop();
800         return ret;
801 }