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