bind - Removed version tag from contrib directory and updated README.DRAGONFLY.
[dragonfly.git] / contrib / bind / bin / named / statschannel.c
1 /*
2  * Copyright (C) 2008, 2009  Internet Systems Consortium, Inc. ("ISC")
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
9  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
11  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
13  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14  * PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 /* $Id: statschannel.c,v 1.2.2.19 2009/02/17 03:47:27 marka Exp $ */
18
19 /*! \file */
20
21 #include <config.h>
22
23 #include <isc/buffer.h>
24 #include <isc/httpd.h>
25 #include <isc/mem.h>
26 #include <isc/once.h>
27 #include <isc/print.h>
28 #include <isc/socket.h>
29 #include <isc/stats.h>
30 #include <isc/task.h>
31
32 #include <dns/db.h>
33 #include <dns/opcode.h>
34 #include <dns/resolver.h>
35 #include <dns/rdataclass.h>
36 #include <dns/rdatatype.h>
37 #include <dns/stats.h>
38 #include <dns/view.h>
39 #include <dns/zt.h>
40
41 #include <named/log.h>
42 #include <named/server.h>
43 #include <named/statschannel.h>
44
45 #include "bind9.xsl.h"
46
47 struct ns_statschannel {
48         /* Unlocked */
49         isc_httpdmgr_t                          *httpdmgr;
50         isc_sockaddr_t                          address;
51         isc_mem_t                               *mctx;
52
53         /*
54          * Locked by channel lock: can be referenced and modified by both
55          * the server task and the channel task.
56          */
57         isc_mutex_t                             lock;
58         dns_acl_t                               *acl;
59
60         /* Locked by server task */
61         ISC_LINK(struct ns_statschannel)        link;
62 };
63
64 typedef enum { statsformat_file, statsformat_xml } statsformat_t;
65
66 typedef struct
67 stats_dumparg {
68         statsformat_t   type;
69         void            *arg;           /* type dependent argument */
70         int             ncounters;      /* used for general statistics */
71         int             *counterindices; /* used for general statistics */
72         isc_uint64_t    *countervalues;  /* used for general statistics */
73 } stats_dumparg_t;
74
75 static isc_once_t once = ISC_ONCE_INIT;
76
77 /*%
78  * Statistics descriptions.  These could be statistically initialized at
79  * compile time, but we configure them run time in the init_desc() function
80  * below so that they'll be less susceptible to counter name changes.
81  */
82 static const char *nsstats_desc[dns_nsstatscounter_max];
83 static const char *resstats_desc[dns_resstatscounter_max];
84 static const char *zonestats_desc[dns_zonestatscounter_max];
85 static const char *sockstats_desc[isc_sockstatscounter_max];
86 #ifdef HAVE_LIBXML2
87 static const char *nsstats_xmldesc[dns_nsstatscounter_max];
88 static const char *resstats_xmldesc[dns_resstatscounter_max];
89 static const char *zonestats_xmldesc[dns_zonestatscounter_max];
90 static const char *sockstats_xmldesc[isc_sockstatscounter_max];
91 #else
92 #define nsstats_xmldesc NULL
93 #define resstats_xmldesc NULL
94 #define zonestats_xmldesc NULL
95 #define sockstats_xmldesc NULL
96 #endif  /* HAVE_LIBXML2 */
97
98 /*%
99  * Mapping arrays to represent statistics counters in the order of our
100  * preference, regardless of the order of counter indices.  For example,
101  * nsstats_desc[nsstats_index[0]] will be the description that is shown first.
102  */
103 static int nsstats_index[dns_nsstatscounter_max];
104 static int resstats_index[dns_resstatscounter_max];
105 static int zonestats_index[dns_zonestatscounter_max];
106 static int sockstats_index[isc_sockstatscounter_max];
107
108 static inline void
109 set_desc(int counter, int maxcounter, const char *fdesc, const char **fdescs,
110          const char *xdesc, const char **xdescs)
111 {
112         REQUIRE(counter < maxcounter);
113         REQUIRE(fdescs[counter] == NULL);
114 #ifdef HAVE_LIBXML2
115         REQUIRE(xdescs[counter] == NULL);
116 #endif
117
118         fdescs[counter] = fdesc;
119 #ifdef HAVE_LIBXML2
120         xdescs[counter] = xdesc;
121 #else
122         UNUSED(xdesc);
123         UNUSED(xdescs);
124 #endif
125 }
126
127 static void
128 init_desc(void) {
129         int i;
130
131         /* Initialize name server statistics */
132         memset((void *)nsstats_desc, 0,
133                dns_nsstatscounter_max * sizeof(nsstats_desc[0]));
134 #ifdef HAVE_LIBXML2
135         memset((void *)nsstats_xmldesc, 0,
136                dns_nsstatscounter_max * sizeof(nsstats_xmldesc[0]));
137 #endif
138
139 #define SET_NSSTATDESC(counterid, desc, xmldesc) \
140         do { \
141                 set_desc(dns_nsstatscounter_ ## counterid, \
142                          dns_nsstatscounter_max, \
143                          desc, nsstats_desc, xmldesc, nsstats_xmldesc); \
144                 nsstats_index[i++] = dns_nsstatscounter_ ## counterid; \
145         } while (0)
146
147         i = 0;
148         SET_NSSTATDESC(requestv4, "IPv4 requests received", "Requestv4");
149         SET_NSSTATDESC(requestv6, "IPv6 requests received", "Requestv6");
150         SET_NSSTATDESC(edns0in, "requests with EDNS(0) received", "ReqEdns0");
151         SET_NSSTATDESC(badednsver,
152                        "requests with unsupported EDNS version received",
153                        "ReqBadEDNSVer");
154         SET_NSSTATDESC(tsigin, "requests with TSIG received", "ReqTSIG");
155         SET_NSSTATDESC(sig0in, "requests with SIG(0) received", "ReqSIG0");
156         SET_NSSTATDESC(invalidsig, "requests with invalid signature",
157                        "ReqBadSIG");
158         SET_NSSTATDESC(tcp, "TCP requests received", "ReqTCP");
159         SET_NSSTATDESC(authrej, "auth queries rejected", "AuthQryRej");
160         SET_NSSTATDESC(recurserej, "recursive queries rejected", "RecQryRej");
161         SET_NSSTATDESC(xfrrej, "transfer requests rejected", "XfrRej");
162         SET_NSSTATDESC(updaterej, "update requests rejected", "UpdateRej");
163         SET_NSSTATDESC(response, "responses sent", "Response");
164         SET_NSSTATDESC(truncatedresp, "truncated responses sent",
165                        "TruncatedResp");
166         SET_NSSTATDESC(edns0out, "responses with EDNS(0) sent", "RespEDNS0");
167         SET_NSSTATDESC(tsigout, "responses with TSIG sent", "RespTSIG");
168         SET_NSSTATDESC(sig0out, "responses with SIG(0) sent", "RespSIG0");
169         SET_NSSTATDESC(success, "queries resulted in successful answer",
170                        "QrySuccess");
171         SET_NSSTATDESC(authans, "queries resulted in authoritative answer",
172                        "QryAuthAns");
173         SET_NSSTATDESC(nonauthans,
174                        "queries resulted in non authoritative answer",
175                        "QryNoauthAns");
176         SET_NSSTATDESC(referral, "queries resulted in referral answer",
177                        "QryReferral");
178         SET_NSSTATDESC(nxrrset, "queries resulted in nxrrset", "QryNxrrset");
179         SET_NSSTATDESC(servfail, "queries resulted in SERVFAIL", "QrySERVFAIL");
180         SET_NSSTATDESC(formerr, "queries resulted in FORMERR", "QryFORMERR");
181         SET_NSSTATDESC(nxdomain, "queries resulted in NXDOMAIN", "QryNXDOMAIN");
182         SET_NSSTATDESC(recursion, "queries caused recursion","QryRecursion");
183         SET_NSSTATDESC(duplicate, "duplicate queries received", "QryDuplicate");
184         SET_NSSTATDESC(dropped, "queries dropped", "QryDropped");
185         SET_NSSTATDESC(failure, "other query failures", "QryFailure");
186         SET_NSSTATDESC(xfrdone, "requested transfers completed", "XfrReqDone");
187         SET_NSSTATDESC(updatereqfwd, "update requests forwarded",
188                        "UpdateReqFwd");
189         SET_NSSTATDESC(updaterespfwd, "update responses forwarded",
190                        "UpdateRespFwd");
191         SET_NSSTATDESC(updatefwdfail, "update forward failed", "UpdateFwdFail");
192         SET_NSSTATDESC(updatedone, "updates completed", "UpdateDone");
193         SET_NSSTATDESC(updatefail, "updates failed", "UpdateFail");
194         SET_NSSTATDESC(updatebadprereq,
195                        "updates rejected due to prerequisite failure",
196                        "UpdateBadPrereq");
197         INSIST(i == dns_nsstatscounter_max);
198
199         /* Initialize resolver statistics */
200         memset((void *)resstats_desc, 0,
201                dns_resstatscounter_max * sizeof(resstats_desc[0]));
202 #ifdef  HAVE_LIBXML2
203         memset((void *)resstats_xmldesc, 0,
204                dns_resstatscounter_max * sizeof(resstats_xmldesc[0]));
205 #endif
206
207 #define SET_RESSTATDESC(counterid, desc, xmldesc) \
208         do { \
209                 set_desc(dns_resstatscounter_ ## counterid, \
210                          dns_resstatscounter_max, \
211                          desc, resstats_desc, xmldesc, resstats_xmldesc); \
212                 resstats_index[i++] = dns_resstatscounter_ ## counterid; \
213         } while (0)
214
215         i = 0;
216         SET_RESSTATDESC(queryv4, "IPv4 queries sent", "Queryv4");
217         SET_RESSTATDESC(queryv6, "IPv6 queries sent", "Queryv6");
218         SET_RESSTATDESC(responsev4, "IPv4 responses received", "Responsev4");
219         SET_RESSTATDESC(responsev6, "IPv6 responses received", "Responsev6");
220         SET_RESSTATDESC(nxdomain, "NXDOMAIN received", "NXDOMAIN");
221         SET_RESSTATDESC(servfail, "SERVFAIL received", "SERVFAIL");
222         SET_RESSTATDESC(formerr, "FORMERR received", "FORMERR");
223         SET_RESSTATDESC(othererror, "other errors received", "OtherError");
224         SET_RESSTATDESC(edns0fail, "EDNS(0) query failures", "EDNS0Fail");
225         SET_RESSTATDESC(mismatch, "mismatch responses received", "Mismatch");
226         SET_RESSTATDESC(truncated, "truncated responses received", "Truncated");
227         SET_RESSTATDESC(lame, "lame delegations received", "Lame");
228         SET_RESSTATDESC(retry, "query retries", "Retry");
229         SET_RESSTATDESC(dispabort, "queries aborted due to quota",
230                         "QueryAbort");
231         SET_RESSTATDESC(dispsockfail, "failures in opening query sockets",
232                         "QuerySockFail");
233         SET_RESSTATDESC(querytimeout, "query timeouts", "QueryTimeout");
234         SET_RESSTATDESC(gluefetchv4, "IPv4 NS address fetches", "GlueFetchv4");
235         SET_RESSTATDESC(gluefetchv6, "IPv6 NS address fetches", "GlueFetchv6");
236         SET_RESSTATDESC(gluefetchv4fail, "IPv4 NS address fetch failed",
237                         "GlueFetchv4Fail");
238         SET_RESSTATDESC(gluefetchv6fail, "IPv6 NS address fetch failed",
239                         "GlueFetchv6Fail");
240         SET_RESSTATDESC(val, "DNSSEC validation attempted", "ValAttempt");
241         SET_RESSTATDESC(valsuccess, "DNSSEC validation succeeded", "ValOk");
242         SET_RESSTATDESC(valnegsuccess, "DNSSEC NX validation succeeded",
243                         "ValNegOk");
244         SET_RESSTATDESC(valfail, "DNSSEC validation failed", "ValFail");
245         SET_RESSTATDESC(queryrtt0, "queries with RTT < "
246                         DNS_RESOLVER_QRYRTTCLASS0STR "ms",
247                         "QryRTT" DNS_RESOLVER_QRYRTTCLASS0STR);
248         SET_RESSTATDESC(queryrtt1, "queries with RTT "
249                         DNS_RESOLVER_QRYRTTCLASS0STR "-"
250                         DNS_RESOLVER_QRYRTTCLASS1STR "ms",
251                         "QryRTT" DNS_RESOLVER_QRYRTTCLASS1STR);
252         SET_RESSTATDESC(queryrtt2, "queries with RTT "
253                         DNS_RESOLVER_QRYRTTCLASS1STR "-"
254                         DNS_RESOLVER_QRYRTTCLASS2STR "ms",
255                         "QryRTT" DNS_RESOLVER_QRYRTTCLASS2STR);
256         SET_RESSTATDESC(queryrtt3, "queries with RTT "
257                         DNS_RESOLVER_QRYRTTCLASS2STR "-"
258                         DNS_RESOLVER_QRYRTTCLASS3STR "ms",
259                         "QryRTT" DNS_RESOLVER_QRYRTTCLASS3STR);
260         SET_RESSTATDESC(queryrtt4, "queries with RTT "
261                         DNS_RESOLVER_QRYRTTCLASS3STR "-"
262                         DNS_RESOLVER_QRYRTTCLASS4STR "ms",
263                         "QryRTT" DNS_RESOLVER_QRYRTTCLASS4STR);
264         SET_RESSTATDESC(queryrtt5, "queries with RTT > "
265                         DNS_RESOLVER_QRYRTTCLASS4STR "ms",
266                         "QryRTT" DNS_RESOLVER_QRYRTTCLASS4STR "+");
267         INSIST(i == dns_resstatscounter_max);
268
269         /* Initialize zone statistics */
270         memset((void *)zonestats_desc, 0,
271                dns_zonestatscounter_max * sizeof(zonestats_desc[0]));
272 #ifdef  HAVE_LIBXML2
273         memset((void *)zonestats_xmldesc, 0,
274                dns_zonestatscounter_max * sizeof(zonestats_xmldesc[0]));
275 #endif
276
277 #define SET_ZONESTATDESC(counterid, desc, xmldesc) \
278         do { \
279                 set_desc(dns_zonestatscounter_ ## counterid, \
280                          dns_zonestatscounter_max, \
281                          desc, zonestats_desc, xmldesc, zonestats_xmldesc); \
282                 zonestats_index[i++] = dns_zonestatscounter_ ## counterid; \
283         } while (0)
284
285         i = 0;
286         SET_ZONESTATDESC(notifyoutv4, "IPv4 notifies sent", "NotifyOutv4");
287         SET_ZONESTATDESC(notifyoutv6, "IPv6 notifies sent", "NotifyOutv6");
288         SET_ZONESTATDESC(notifyinv4, "IPv4 notifies received", "NotifyInv4");
289         SET_ZONESTATDESC(notifyinv6, "IPv6 notifies received", "NotifyInv6");
290         SET_ZONESTATDESC(notifyrej, "notifies rejected", "NotifyRej");
291         SET_ZONESTATDESC(soaoutv4, "IPv4 SOA queries sent", "SOAOutv4");
292         SET_ZONESTATDESC(soaoutv6, "IPv6 SOA queries sent", "SOAOutv6");
293         SET_ZONESTATDESC(axfrreqv4, "IPv4 AXFR requested", "AXFRReqv4");
294         SET_ZONESTATDESC(axfrreqv6, "IPv6 AXFR requested", "AXFRReqv6");
295         SET_ZONESTATDESC(ixfrreqv4, "IPv4 IXFR requested", "IXFRReqv4");
296         SET_ZONESTATDESC(ixfrreqv6, "IPv6 IXFR requested", "IXFRReqv6");
297         SET_ZONESTATDESC(xfrsuccess, "transfer requests succeeded","XfrSuccess");
298         SET_ZONESTATDESC(xfrfail, "transfer requests failed", "XfrFail");
299         INSIST(i == dns_zonestatscounter_max);
300
301         /* Initialize socket statistics */
302         memset((void *)sockstats_desc, 0,
303                isc_sockstatscounter_max * sizeof(sockstats_desc[0]));
304 #ifdef  HAVE_LIBXML2
305         memset((void *)sockstats_xmldesc, 0,
306                isc_sockstatscounter_max * sizeof(sockstats_xmldesc[0]));
307 #endif
308
309 #define SET_SOCKSTATDESC(counterid, desc, xmldesc) \
310         do { \
311                 set_desc(isc_sockstatscounter_ ## counterid, \
312                          isc_sockstatscounter_max, \
313                          desc, sockstats_desc, xmldesc, sockstats_xmldesc); \
314                 sockstats_index[i++] = isc_sockstatscounter_ ## counterid; \
315         } while (0)
316
317         i = 0;
318         SET_SOCKSTATDESC(udp4open, "UDP/IPv4 sockets opened", "UDP4Open");
319         SET_SOCKSTATDESC(udp6open, "UDP/IPv6 sockets opened", "UDP6Open");
320         SET_SOCKSTATDESC(tcp4open, "TCP/IPv4 sockets opened", "TCP4Open");
321         SET_SOCKSTATDESC(tcp6open, "TCP/IPv6 sockets opened", "TCP6Open");
322         SET_SOCKSTATDESC(unixopen, "Unix domain sockets opened", "UnixOpen");
323         SET_SOCKSTATDESC(udp4openfail, "UDP/IPv4 socket open failures",
324                          "UDP4OpenFail");
325         SET_SOCKSTATDESC(udp6openfail, "UDP/IPv6 socket open failures",
326                          "UDP6OpenFail");
327         SET_SOCKSTATDESC(tcp4openfail, "TCP/IPv4 socket open failures",
328                          "TCP4OpenFail");
329         SET_SOCKSTATDESC(tcp6openfail, "TCP/IPv6 socket open failures",
330                          "TCP6OpenFail");
331         SET_SOCKSTATDESC(unixopenfail, "Unix domain socket open failures",
332                          "UnixOpenFail");
333         SET_SOCKSTATDESC(udp4close, "UDP/IPv4 sockets closed", "UDP4Close");
334         SET_SOCKSTATDESC(udp6close, "UDP/IPv6 sockets closed", "UDP6Close");
335         SET_SOCKSTATDESC(tcp4close, "TCP/IPv4 sockets closed", "TCP4Close");
336         SET_SOCKSTATDESC(tcp6close, "TCP/IPv6 sockets closed", "TCP6Close");
337         SET_SOCKSTATDESC(unixclose, "Unix domain sockets closed", "UnixClose");
338         SET_SOCKSTATDESC(fdwatchclose, "FDwatch sockets closed",
339                          "FDWatchClose");
340         SET_SOCKSTATDESC(udp4bindfail, "UDP/IPv4 socket bind failures",
341                          "UDP4BindFail");
342         SET_SOCKSTATDESC(udp6bindfail, "UDP/IPv6 socket bind failures",
343                          "UDP6BindFail");
344         SET_SOCKSTATDESC(tcp4bindfail, "TCP/IPv4 socket bind failures",
345                          "TCP4BindFail");
346         SET_SOCKSTATDESC(tcp6bindfail, "TCP/IPv6 socket bind failures",
347                          "TCP6BindFail");
348         SET_SOCKSTATDESC(unixbindfail, "Unix domain socket bind failures",
349                          "UnixBindFail");
350         SET_SOCKSTATDESC(fdwatchbindfail, "FDwatch socket bind failures",
351                          "FdwatchBindFail");
352         SET_SOCKSTATDESC(udp4connectfail, "UDP/IPv4 socket connect failures",
353                          "UDP4ConnFail");
354         SET_SOCKSTATDESC(udp6connectfail, "UDP/IPv6 socket connect failures",
355                          "UDP6ConnFail");
356         SET_SOCKSTATDESC(tcp4connectfail, "TCP/IPv4 socket connect failures",
357                          "TCP4ConnFail");
358         SET_SOCKSTATDESC(tcp6connectfail, "TCP/IPv6 socket connect failures",
359                          "TCP6ConnFail");
360         SET_SOCKSTATDESC(unixconnectfail, "Unix domain socket connect failures",
361                          "UnixConnFail");
362         SET_SOCKSTATDESC(fdwatchconnectfail, "FDwatch socket connect failures",
363                          "FDwatchConnFail");
364         SET_SOCKSTATDESC(udp4connect, "UDP/IPv4 connections established",
365                          "UDP4Conn");
366         SET_SOCKSTATDESC(udp6connect, "UDP/IPv6 connections established",
367                          "UDP6Conn");
368         SET_SOCKSTATDESC(tcp4connect, "TCP/IPv4 connections established",
369                          "TCP4Conn");
370         SET_SOCKSTATDESC(tcp6connect, "TCP/IPv6 connections established",
371                          "TCP6Conn");
372         SET_SOCKSTATDESC(unixconnect, "Unix domain connections established",
373                          "UnixConn");
374         SET_SOCKSTATDESC(fdwatchconnect,
375                          "FDwatch domain connections established",
376                          "FDwatchConn");
377         SET_SOCKSTATDESC(tcp4acceptfail, "TCP/IPv4 connection accept failures",
378                          "TCP4AcceptFail");
379         SET_SOCKSTATDESC(tcp6acceptfail, "TCP/IPv6 connection accept failures",
380                          "TCP6AcceptFail");
381         SET_SOCKSTATDESC(unixacceptfail,
382                          "Unix domain connection accept failures",
383                          "UnixAcceptFail");
384         SET_SOCKSTATDESC(tcp4accept, "TCP/IPv4 connections accepted",
385                          "TCP4Accept");
386         SET_SOCKSTATDESC(tcp6accept, "TCP/IPv6 connections accepted",
387                          "TCP6Accept");
388         SET_SOCKSTATDESC(unixaccept, "Unix domain connections accepted",
389                          "UnixAccept");
390         SET_SOCKSTATDESC(udp4sendfail, "UDP/IPv4 send errors", "UDP4SendErr");
391         SET_SOCKSTATDESC(udp6sendfail, "UDP/IPv6 send errors", "UDP6SendErr");
392         SET_SOCKSTATDESC(tcp4sendfail, "TCP/IPv4 send errors", "TCP4SendErr");
393         SET_SOCKSTATDESC(tcp6sendfail, "TCP/IPv6 send errors", "TCP6SendErr");
394         SET_SOCKSTATDESC(unixsendfail, "Unix domain send errors",
395                          "UnixSendErr");
396         SET_SOCKSTATDESC(fdwatchsendfail, "FDwatch send errors",
397                          "FDwatchSendErr");
398         SET_SOCKSTATDESC(udp4recvfail, "UDP/IPv4 recv errors", "UDP4RecvErr");
399         SET_SOCKSTATDESC(udp6recvfail, "UDP/IPv6 recv errors", "UDP6RecvErr");
400         SET_SOCKSTATDESC(tcp4recvfail, "TCP/IPv4 recv errors", "TCP4RecvErr");
401         SET_SOCKSTATDESC(tcp6recvfail, "TCP/IPv6 recv errors", "TCP6RecvErr");
402         SET_SOCKSTATDESC(unixrecvfail, "Unix domain recv errors",
403                          "UnixRecvErr");
404         SET_SOCKSTATDESC(fdwatchrecvfail, "FDwatch recv errors",
405                          "FDwatchRecvErr");
406         INSIST(i == isc_sockstatscounter_max);
407
408         /* Sanity check */
409         for (i = 0; i < dns_nsstatscounter_max; i++)
410                 INSIST(nsstats_desc[i] != NULL);
411         for (i = 0; i < dns_resstatscounter_max; i++)
412                 INSIST(resstats_desc[i] != NULL);
413         for (i = 0; i < dns_zonestatscounter_max; i++)
414                 INSIST(zonestats_desc[i] != NULL);
415         for (i = 0; i < isc_sockstatscounter_max; i++)
416                 INSIST(sockstats_desc[i] != NULL);
417 #ifdef  HAVE_LIBXML2
418         for (i = 0; i < dns_nsstatscounter_max; i++)
419                 INSIST(nsstats_xmldesc[i] != NULL);
420         for (i = 0; i < dns_resstatscounter_max; i++)
421                 INSIST(resstats_xmldesc[i] != NULL);
422         for (i = 0; i < dns_zonestatscounter_max; i++)
423                 INSIST(zonestats_xmldesc[i] != NULL);
424         for (i = 0; i < isc_sockstatscounter_max; i++)
425                 INSIST(sockstats_xmldesc[i] != NULL);
426 #endif
427 }
428
429 /*%
430  * Dump callback functions.
431  */
432 static void
433 generalstat_dump(isc_statscounter_t counter, isc_uint64_t val, void *arg) {
434         stats_dumparg_t *dumparg = arg;
435
436         REQUIRE(counter < dumparg->ncounters);
437         dumparg->countervalues[counter] = val;
438 }
439
440 static void
441 dump_counters(isc_stats_t *stats, statsformat_t type, void *arg,
442               const char *category, const char **desc, int ncounters,
443               int *indices, isc_uint64_t *values, int options)
444 {
445         int i, index;
446         isc_uint64_t value;
447         stats_dumparg_t dumparg;
448         FILE *fp;
449 #ifdef HAVE_LIBXML2
450         xmlTextWriterPtr writer;
451 #endif
452
453 #ifndef HAVE_LIBXML2
454         UNUSED(category);
455 #endif
456
457         dumparg.type = type;
458         dumparg.ncounters = ncounters;
459         dumparg.counterindices = indices;
460         dumparg.countervalues = values;
461
462         memset(values, 0, sizeof(values[0]) * ncounters);
463         isc_stats_dump(stats, generalstat_dump, &dumparg, options);
464
465         for (i = 0; i < ncounters; i++) {
466                 index = indices[i];
467                 value = values[index];
468
469                 if (value == 0 && (options & ISC_STATSDUMP_VERBOSE) == 0)
470                         continue;
471
472                 switch (dumparg.type) {
473                 case statsformat_file:
474                         fp = arg;
475                         fprintf(fp, "%20" ISC_PRINT_QUADFORMAT "u %s\n",
476                                 value, desc[index]);
477                         break;
478                 case statsformat_xml:
479 #ifdef HAVE_LIBXML2
480                         writer = arg;
481
482                         if (category != NULL) {
483                                 xmlTextWriterStartElement(writer,
484                                                           ISC_XMLCHAR
485                                                           category);
486                                 xmlTextWriterStartElement(writer,
487                                                           ISC_XMLCHAR "name");
488                                 xmlTextWriterWriteString(writer, ISC_XMLCHAR
489                                                         desc[index]);
490                                 xmlTextWriterEndElement(writer); /* name */
491
492                                 xmlTextWriterStartElement(writer, ISC_XMLCHAR
493                                                           "counter");
494                         } else {
495                                 xmlTextWriterStartElement(writer, ISC_XMLCHAR
496                                                           desc[index]);
497                         }
498                         xmlTextWriterWriteFormatString(writer,
499                                                        "%" ISC_PRINT_QUADFORMAT
500                                                        "u", value);
501                         xmlTextWriterEndElement(writer); /* counter */
502                         if (category != NULL)
503                                 xmlTextWriterEndElement(writer); /* category */
504 #endif
505                         break;
506                 }
507         }
508 }
509
510 static void
511 rdtypestat_dump(dns_rdatastatstype_t type, isc_uint64_t val, void *arg) {
512         char typebuf[64];
513         const char *typestr;
514         stats_dumparg_t *dumparg = arg;
515         FILE *fp;
516 #ifdef HAVE_LIBXML2
517         xmlTextWriterPtr writer;
518 #endif
519
520         if ((DNS_RDATASTATSTYPE_ATTR(type) & DNS_RDATASTATSTYPE_ATTR_OTHERTYPE)
521             == 0) {
522                 dns_rdatatype_format(DNS_RDATASTATSTYPE_BASE(type), typebuf,
523                                      sizeof(typebuf));
524                 typestr = typebuf;
525         } else
526                 typestr = "Others";
527
528         switch (dumparg->type) {
529         case statsformat_file:
530                 fp = dumparg->arg;
531                 fprintf(fp, "%20" ISC_PRINT_QUADFORMAT "u %s\n", val, typestr);
532                 break;
533         case statsformat_xml:
534 #ifdef HAVE_LIBXML2
535                 writer = dumparg->arg;
536
537                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "rdtype");
538
539                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "name");
540                 xmlTextWriterWriteString(writer, ISC_XMLCHAR typestr);
541                 xmlTextWriterEndElement(writer); /* name */
542
543                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "counter");
544                 xmlTextWriterWriteFormatString(writer,
545                                                "%" ISC_PRINT_QUADFORMAT "u",
546                                                val);
547                 xmlTextWriterEndElement(writer); /* counter */
548
549                 xmlTextWriterEndElement(writer); /* rdtype */
550 #endif
551                 break;
552         }
553 }
554
555 static void
556 rdatasetstats_dump(dns_rdatastatstype_t type, isc_uint64_t val, void *arg) {
557         stats_dumparg_t *dumparg = arg;
558         FILE *fp;
559         char typebuf[64];
560         const char *typestr;
561         isc_boolean_t nxrrset = ISC_FALSE;
562 #ifdef HAVE_LIBXML2
563         xmlTextWriterPtr writer;
564 #endif
565
566         if ((DNS_RDATASTATSTYPE_ATTR(type) & DNS_RDATASTATSTYPE_ATTR_NXDOMAIN)
567             != 0) {
568                 typestr = "NXDOMAIN";
569         } else if ((DNS_RDATASTATSTYPE_ATTR(type) &
570                     DNS_RDATASTATSTYPE_ATTR_OTHERTYPE) != 0) {
571                 typestr = "Others";
572         } else {
573                 dns_rdatatype_format(DNS_RDATASTATSTYPE_BASE(type), typebuf,
574                                      sizeof(typebuf));
575                 typestr = typebuf;
576         }
577
578         if ((DNS_RDATASTATSTYPE_ATTR(type) & DNS_RDATASTATSTYPE_ATTR_NXRRSET)
579             != 0)
580                 nxrrset = ISC_TRUE;
581
582         switch (dumparg->type) {
583         case statsformat_file:
584                 fp = dumparg->arg;
585                 fprintf(fp, "%20" ISC_PRINT_QUADFORMAT "u %s%s\n", val,
586                         nxrrset ? "!" : "", typestr);
587                 break;
588         case statsformat_xml:
589 #ifdef HAVE_LIBXML2
590                 writer = dumparg->arg;
591
592                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "rrset");
593                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "name");
594                 xmlTextWriterWriteFormatString(writer, "%s%s",
595                                                nxrrset ? "!" : "", typestr);
596                 xmlTextWriterEndElement(writer); /* name */
597
598                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "counter");
599                 xmlTextWriterWriteFormatString(writer,
600                                                "%" ISC_PRINT_QUADFORMAT "u",
601                                                val);
602                 xmlTextWriterEndElement(writer); /* counter */
603
604                 xmlTextWriterEndElement(writer); /* rrset */
605 #endif
606                 break;
607         }
608 }
609
610 static void
611 opcodestat_dump(dns_opcode_t code, isc_uint64_t val, void *arg) {
612         FILE *fp = arg;
613         isc_buffer_t b;
614         char codebuf[64];
615         stats_dumparg_t *dumparg = arg;
616 #ifdef HAVE_LIBXML2
617         xmlTextWriterPtr writer;
618 #endif
619
620         isc_buffer_init(&b, codebuf, sizeof(codebuf) - 1);
621         dns_opcode_totext(code, &b);
622         codebuf[isc_buffer_usedlength(&b)] = '\0';
623
624         switch (dumparg->type) {
625         case statsformat_file:
626                 fp = dumparg->arg;
627                 fprintf(fp, "%20" ISC_PRINT_QUADFORMAT "u %s\n", val, codebuf);
628                 break;
629         case statsformat_xml:
630 #ifdef HAVE_LIBXML2
631                 writer = dumparg->arg;
632
633                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "opcode");
634
635                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "name");
636                 xmlTextWriterWriteString(writer, ISC_XMLCHAR codebuf);
637                 xmlTextWriterEndElement(writer); /* name */
638
639                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "counter");
640                 xmlTextWriterWriteFormatString(writer,
641                                                "%" ISC_PRINT_QUADFORMAT "u",
642                                                val);
643                 xmlTextWriterEndElement(writer); /* counter */
644
645                 xmlTextWriterEndElement(writer); /* opcode */
646 #endif
647                 break;
648         }
649 }
650
651 #ifdef HAVE_LIBXML2
652
653 /* XXXMLG below here sucks. */
654
655 #define TRY(a) do { result = (a); INSIST(result == ISC_R_SUCCESS); } while(0);
656 #define TRY0(a) do { xmlrc = (a); INSIST(xmlrc >= 0); } while(0);
657
658 static isc_result_t
659 zone_xmlrender(dns_zone_t *zone, void *arg) {
660         char buf[1024 + 32];    /* sufficiently large for zone name and class */
661         dns_rdataclass_t rdclass;
662         isc_uint32_t serial;
663         xmlTextWriterPtr writer = arg;
664         isc_stats_t *zonestats;
665         isc_uint64_t nsstat_values[dns_nsstatscounter_max];
666
667         xmlTextWriterStartElement(writer, ISC_XMLCHAR "zone");
668
669         dns_zone_name(zone, buf, sizeof(buf));
670         xmlTextWriterStartElement(writer, ISC_XMLCHAR "name");
671         xmlTextWriterWriteString(writer, ISC_XMLCHAR buf);
672         xmlTextWriterEndElement(writer);
673
674         rdclass = dns_zone_getclass(zone);
675         dns_rdataclass_format(rdclass, buf, sizeof(buf));
676         xmlTextWriterStartElement(writer, ISC_XMLCHAR "rdataclass");
677         xmlTextWriterWriteString(writer, ISC_XMLCHAR buf);
678         xmlTextWriterEndElement(writer);
679
680         serial = dns_zone_getserial(zone);
681         xmlTextWriterStartElement(writer, ISC_XMLCHAR "serial");
682         xmlTextWriterWriteFormatString(writer, "%u", serial);
683         xmlTextWriterEndElement(writer);
684
685         zonestats = dns_zone_getrequeststats(zone);
686         if (zonestats != NULL) {
687                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "counters");
688                 dump_counters(zonestats, statsformat_xml, writer, NULL,
689                               nsstats_xmldesc, dns_nsstatscounter_max,
690                               nsstats_index, nsstat_values,
691                               ISC_STATSDUMP_VERBOSE);
692                 xmlTextWriterEndElement(writer); /* counters */
693         }
694
695         xmlTextWriterEndElement(writer); /* zone */
696
697         return (ISC_R_SUCCESS);
698 }
699
700 static void
701 generatexml(ns_server_t *server, int *buflen, xmlChar **buf) {
702         char boottime[sizeof "yyyy-mm-ddThh:mm:ssZ"];
703         char nowstr[sizeof "yyyy-mm-ddThh:mm:ssZ"];
704         isc_time_t now;
705         xmlTextWriterPtr writer;
706         xmlDocPtr doc;
707         int xmlrc;
708         dns_view_t *view;
709         stats_dumparg_t dumparg;
710         dns_stats_t *cachestats;
711         isc_uint64_t nsstat_values[dns_nsstatscounter_max];
712         isc_uint64_t resstat_values[dns_resstatscounter_max];
713         isc_uint64_t zonestat_values[dns_zonestatscounter_max];
714         isc_uint64_t sockstat_values[isc_sockstatscounter_max];
715
716         isc_time_now(&now);
717         isc_time_formatISO8601(&ns_g_boottime, boottime, sizeof boottime);
718         isc_time_formatISO8601(&now, nowstr, sizeof nowstr);
719
720         writer = xmlNewTextWriterDoc(&doc, 0);
721         TRY0(xmlTextWriterStartDocument(writer, NULL, "UTF-8", NULL));
722         TRY0(xmlTextWriterWritePI(writer, ISC_XMLCHAR "xml-stylesheet",
723                         ISC_XMLCHAR "type=\"text/xsl\" href=\"/bind9.xsl\""));
724         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "isc"));
725         TRY0(xmlTextWriterWriteAttribute(writer, ISC_XMLCHAR "version",
726                                          ISC_XMLCHAR "1.0"));
727
728         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "bind"));
729         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "statistics"));
730         TRY0(xmlTextWriterWriteAttribute(writer, ISC_XMLCHAR "version",
731                                          ISC_XMLCHAR "2.0"));
732
733         /* Set common fields for statistics dump */
734         dumparg.type = statsformat_xml;
735         dumparg.arg = writer;
736
737         /*
738          * Start by rendering the views we know of here.  For each view we
739          * know of, call its rendering function.
740          */
741         view = ISC_LIST_HEAD(server->viewlist);
742         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "views"));
743         while (view != NULL) {
744                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "view");
745
746                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "name");
747                 xmlTextWriterWriteString(writer, ISC_XMLCHAR view->name);
748                 xmlTextWriterEndElement(writer);
749
750                 xmlTextWriterStartElement(writer, ISC_XMLCHAR "zones");
751                 dns_zt_apply(view->zonetable, ISC_FALSE, zone_xmlrender,
752                              writer);
753                 xmlTextWriterEndElement(writer);
754
755                 if (view->resquerystats != NULL) {
756                         dns_rdatatypestats_dump(view->resquerystats,
757                                                 rdtypestat_dump, &dumparg, 0);
758                 }
759
760                 if (view->resstats != NULL) {
761                         dump_counters(view->resstats, statsformat_xml, writer,
762                                       "resstat", resstats_xmldesc,
763                                       dns_resstatscounter_max, resstats_index,
764                                       resstat_values, ISC_STATSDUMP_VERBOSE);
765                 }
766
767                 cachestats = dns_db_getrrsetstats(view->cachedb);
768                 if (cachestats != NULL) {
769                         xmlTextWriterStartElement(writer,
770                                                   ISC_XMLCHAR "cache");
771                         dns_rdatasetstats_dump(cachestats, rdatasetstats_dump,
772                                                &dumparg, 0);
773                         xmlTextWriterEndElement(writer); /* cache */
774                 }
775
776                 xmlTextWriterEndElement(writer); /* view */
777
778                 view = ISC_LIST_NEXT(view, link);
779         }
780         TRY0(xmlTextWriterEndElement(writer)); /* views */
781
782         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "socketmgr"));
783         isc_socketmgr_renderxml(ns_g_socketmgr, writer);
784         TRY0(xmlTextWriterEndElement(writer)); /* socketmgr */
785
786         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "taskmgr"));
787         isc_taskmgr_renderxml(ns_g_taskmgr, writer);
788         TRY0(xmlTextWriterEndElement(writer)); /* taskmgr */
789
790         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "server"));
791         xmlTextWriterStartElement(writer, ISC_XMLCHAR "boot-time");
792         xmlTextWriterWriteString(writer, ISC_XMLCHAR boottime);
793         xmlTextWriterEndElement(writer);
794         xmlTextWriterStartElement(writer, ISC_XMLCHAR "current-time");
795         xmlTextWriterWriteString(writer, ISC_XMLCHAR nowstr);
796         xmlTextWriterEndElement(writer);
797
798         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "requests"));
799         dns_opcodestats_dump(server->opcodestats, opcodestat_dump, &dumparg,
800                              0);
801         xmlTextWriterEndElement(writer); /* requests */
802
803         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "queries-in"));
804         dns_rdatatypestats_dump(server->rcvquerystats, rdtypestat_dump,
805                                 &dumparg, 0);
806         xmlTextWriterEndElement(writer); /* queries-in */
807
808         dump_counters(server->nsstats, statsformat_xml, writer,
809                       "nsstat", nsstats_xmldesc, dns_nsstatscounter_max,
810                       nsstats_index, nsstat_values, ISC_STATSDUMP_VERBOSE);
811
812         dump_counters(server->zonestats, statsformat_xml, writer, "zonestat",
813                       zonestats_xmldesc, dns_zonestatscounter_max,
814                       zonestats_index, zonestat_values, ISC_STATSDUMP_VERBOSE);
815
816         /*
817          * Most of the common resolver statistics entries are 0, so we don't
818          * use the verbose dump here.
819          */
820         dump_counters(server->resolverstats, statsformat_xml, writer, "resstat",
821                       resstats_xmldesc, dns_resstatscounter_max, resstats_index,
822                       resstat_values, 0);
823
824         dump_counters(server->sockstats, statsformat_xml, writer, "sockstat",
825                       sockstats_xmldesc, isc_sockstatscounter_max,
826                       sockstats_index, sockstat_values, ISC_STATSDUMP_VERBOSE);
827
828         xmlTextWriterEndElement(writer); /* server */
829
830         TRY0(xmlTextWriterStartElement(writer, ISC_XMLCHAR "memory"));
831         isc_mem_renderxml(writer);
832         TRY0(xmlTextWriterEndElement(writer)); /* memory */
833
834         TRY0(xmlTextWriterEndElement(writer)); /* statistics */
835         TRY0(xmlTextWriterEndElement(writer)); /* bind */
836         TRY0(xmlTextWriterEndElement(writer)); /* isc */
837
838         TRY0(xmlTextWriterEndDocument(writer));
839
840         xmlFreeTextWriter(writer);
841
842         xmlDocDumpFormatMemoryEnc(doc, buf, buflen, "UTF-8", 1);
843         xmlFreeDoc(doc);
844 }
845
846 static void
847 wrap_xmlfree(isc_buffer_t *buffer, void *arg) {
848         UNUSED(arg);
849
850         xmlFree(isc_buffer_base(buffer));
851 }
852
853 static isc_result_t
854 render_index(const char *url, const char *querystring, void *arg,
855              unsigned int *retcode, const char **retmsg, const char **mimetype,
856              isc_buffer_t *b, isc_httpdfree_t **freecb,
857              void **freecb_args)
858 {
859         unsigned char *msg;
860         int msglen;
861         ns_server_t *server = arg;
862
863         UNUSED(url);
864         UNUSED(querystring);
865
866         generatexml(server, &msglen, &msg);
867
868         *retcode = 200;
869         *retmsg = "OK";
870         *mimetype = "text/xml";
871         isc_buffer_reinit(b, msg, msglen);
872         isc_buffer_add(b, msglen);
873         *freecb = wrap_xmlfree;
874         *freecb_args = NULL;
875
876         return (ISC_R_SUCCESS);
877 }
878
879 #endif  /* HAVE_LIBXML2 */
880
881 static isc_result_t
882 render_xsl(const char *url, const char *querystring, void *args,
883            unsigned int *retcode, const char **retmsg, const char **mimetype,
884            isc_buffer_t *b, isc_httpdfree_t **freecb,
885            void **freecb_args)
886 {
887         UNUSED(url);
888         UNUSED(querystring);
889         UNUSED(args);
890
891         *retcode = 200;
892         *retmsg = "OK";
893         *mimetype = "text/xslt+xml";
894         isc_buffer_reinit(b, xslmsg, strlen(xslmsg));
895         isc_buffer_add(b, strlen(xslmsg));
896         *freecb = NULL;
897         *freecb_args = NULL;
898
899         return (ISC_R_SUCCESS);
900 }
901
902 static void
903 shutdown_listener(ns_statschannel_t *listener) {
904         char socktext[ISC_SOCKADDR_FORMATSIZE];
905         isc_sockaddr_format(&listener->address, socktext, sizeof(socktext));
906         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,NS_LOGMODULE_SERVER,
907                       ISC_LOG_NOTICE, "stopping statistics channel on %s",
908                       socktext);
909
910         isc_httpdmgr_shutdown(&listener->httpdmgr);
911 }
912
913 static isc_boolean_t
914 client_ok(const isc_sockaddr_t *fromaddr, void *arg) {
915         ns_statschannel_t *listener = arg;
916         isc_netaddr_t netaddr;
917         char socktext[ISC_SOCKADDR_FORMATSIZE];
918         int match;
919
920         REQUIRE(listener != NULL);
921
922         isc_netaddr_fromsockaddr(&netaddr, fromaddr);
923
924         LOCK(&listener->lock);
925         if (dns_acl_match(&netaddr, NULL, listener->acl, &ns_g_server->aclenv,
926                           &match, NULL) == ISC_R_SUCCESS && match > 0) {
927                 UNLOCK(&listener->lock);
928                 return (ISC_TRUE);
929         }
930         UNLOCK(&listener->lock);
931
932         isc_sockaddr_format(fromaddr, socktext, sizeof(socktext));
933         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
934                       NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
935                       "rejected statistics connection from %s", socktext);
936
937         return (ISC_FALSE);
938 }
939
940 static void
941 destroy_listener(void *arg) {
942         ns_statschannel_t *listener = arg;
943
944         REQUIRE(listener != NULL);
945         REQUIRE(!ISC_LINK_LINKED(listener, link));
946
947         /* We don't have to acquire the lock here since it's already unlinked */
948         dns_acl_detach(&listener->acl);
949
950         DESTROYLOCK(&listener->lock);
951         isc_mem_putanddetach(&listener->mctx, listener, sizeof(*listener));
952 }
953
954 static isc_result_t
955 add_listener(ns_server_t *server, ns_statschannel_t **listenerp,
956              const cfg_obj_t *listen_params, const cfg_obj_t *config,
957              isc_sockaddr_t *addr, cfg_aclconfctx_t *aclconfctx,
958              const char *socktext)
959 {
960         isc_result_t result;
961         ns_statschannel_t *listener;
962         isc_task_t *task = NULL;
963         isc_socket_t *sock = NULL;
964         const cfg_obj_t *allow;
965         dns_acl_t *new_acl = NULL;
966
967         listener = isc_mem_get(server->mctx, sizeof(*listener));
968         if (listener == NULL)
969                 return (ISC_R_NOMEMORY);
970
971         listener->httpdmgr = NULL;
972         listener->address = *addr;
973         listener->acl = NULL;
974         listener->mctx = NULL;
975         ISC_LINK_INIT(listener, link);
976
977         result = isc_mutex_init(&listener->lock);
978         if (result != ISC_R_SUCCESS) {
979                 isc_mem_put(server->mctx, listener, sizeof(*listener));
980                 return (ISC_R_FAILURE);
981         }
982
983         isc_mem_attach(server->mctx, &listener->mctx);
984
985         allow = cfg_tuple_get(listen_params, "allow");
986         if (allow != NULL && cfg_obj_islist(allow)) {
987                 result = cfg_acl_fromconfig(allow, config, ns_g_lctx,
988                                             aclconfctx, listener->mctx, 0,
989                                             &new_acl);
990         } else
991                 result = dns_acl_any(listener->mctx, &new_acl);
992         if (result != ISC_R_SUCCESS)
993                 goto cleanup;
994         dns_acl_attach(new_acl, &listener->acl);
995         dns_acl_detach(&new_acl);
996
997         result = isc_task_create(ns_g_taskmgr, 0, &task);
998         if (result != ISC_R_SUCCESS)
999                 goto cleanup;
1000         isc_task_setname(task, "statchannel", NULL);
1001
1002         result = isc_socket_create(ns_g_socketmgr, isc_sockaddr_pf(addr),
1003                                    isc_sockettype_tcp, &sock);
1004         if (result != ISC_R_SUCCESS)
1005                 goto cleanup;
1006         isc_socket_setname(sock, "statchannel", NULL);
1007
1008 #ifndef ISC_ALLOW_MAPPED
1009         isc_socket_ipv6only(sock, ISC_TRUE);
1010 #endif
1011
1012         result = isc_socket_bind(sock, addr, ISC_SOCKET_REUSEADDRESS);
1013         if (result != ISC_R_SUCCESS)
1014                 goto cleanup;
1015
1016         result = isc_httpdmgr_create(server->mctx, sock, task, client_ok,
1017                                      destroy_listener, listener, ns_g_timermgr,
1018                                      &listener->httpdmgr);
1019         if (result != ISC_R_SUCCESS)
1020                 goto cleanup;
1021
1022 #ifdef HAVE_LIBXML2
1023         isc_httpdmgr_addurl(listener->httpdmgr, "/", render_index, server);
1024 #endif
1025         isc_httpdmgr_addurl(listener->httpdmgr, "/bind9.xsl", render_xsl,
1026                             server);
1027
1028         *listenerp = listener;
1029         isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
1030                       NS_LOGMODULE_SERVER, ISC_LOG_NOTICE,
1031                       "statistics channel listening on %s", socktext);
1032
1033 cleanup:
1034         if (result != ISC_R_SUCCESS) {
1035                 if (listener->acl != NULL)
1036                         dns_acl_detach(&listener->acl);
1037                 DESTROYLOCK(&listener->lock);
1038                 isc_mem_putanddetach(&listener->mctx, listener,
1039                                      sizeof(*listener));
1040         }
1041         if (task != NULL)
1042                 isc_task_detach(&task);
1043         if (sock != NULL)
1044                 isc_socket_detach(&sock);
1045
1046         return (result);
1047 }
1048
1049 static void
1050 update_listener(ns_server_t *server, ns_statschannel_t **listenerp,
1051                 const cfg_obj_t *listen_params, const cfg_obj_t *config,
1052                 isc_sockaddr_t *addr, cfg_aclconfctx_t *aclconfctx,
1053                 const char *socktext)
1054 {
1055         ns_statschannel_t *listener;
1056         const cfg_obj_t *allow = NULL;
1057         dns_acl_t *new_acl = NULL;
1058         isc_result_t result = ISC_R_SUCCESS;
1059
1060         for (listener = ISC_LIST_HEAD(server->statschannels);
1061              listener != NULL;
1062              listener = ISC_LIST_NEXT(listener, link))
1063                 if (isc_sockaddr_equal(addr, &listener->address))
1064                         break;
1065
1066         if (listener == NULL) {
1067                 *listenerp = NULL;
1068                 return;
1069         }
1070
1071         /*
1072          * Now, keep the old access list unless a new one can be made.
1073          */
1074         allow = cfg_tuple_get(listen_params, "allow");
1075         if (allow != NULL && cfg_obj_islist(allow)) {
1076                 result = cfg_acl_fromconfig(allow, config, ns_g_lctx,
1077                                             aclconfctx, listener->mctx, 0,
1078                                             &new_acl);
1079         } else
1080                 result = dns_acl_any(listener->mctx, &new_acl);
1081
1082         if (result == ISC_R_SUCCESS) {
1083                 LOCK(&listener->lock);
1084
1085                 dns_acl_detach(&listener->acl);
1086                 dns_acl_attach(new_acl, &listener->acl);
1087                 dns_acl_detach(&new_acl);
1088
1089                 UNLOCK(&listener->lock);
1090         } else {
1091                 cfg_obj_log(listen_params, ns_g_lctx, ISC_LOG_WARNING,
1092                             "couldn't install new acl for "
1093                             "statistics channel %s: %s",
1094                             socktext, isc_result_totext(result));
1095         }
1096
1097         *listenerp = listener;
1098 }
1099
1100 isc_result_t
1101 ns_statschannels_configure(ns_server_t *server, const cfg_obj_t *config,
1102                          cfg_aclconfctx_t *aclconfctx)
1103 {
1104         ns_statschannel_t *listener, *listener_next;
1105         ns_statschannellist_t new_listeners;
1106         const cfg_obj_t *statschannellist = NULL;
1107         const cfg_listelt_t *element, *element2;
1108         char socktext[ISC_SOCKADDR_FORMATSIZE];
1109
1110         RUNTIME_CHECK(isc_once_do(&once, init_desc) == ISC_R_SUCCESS);
1111
1112         ISC_LIST_INIT(new_listeners);
1113
1114         /*
1115          * Get the list of named.conf 'statistics-channels' statements.
1116          */
1117         (void)cfg_map_get(config, "statistics-channels", &statschannellist);
1118
1119         /*
1120          * Run through the new address/port list, noting sockets that are
1121          * already being listened on and moving them to the new list.
1122          *
1123          * Identifying duplicate addr/port combinations is left to either
1124          * the underlying config code, or to the bind attempt getting an
1125          * address-in-use error.
1126          */
1127         if (statschannellist != NULL) {
1128 #ifndef HAVE_LIBXML2
1129                 isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL,
1130                               NS_LOGMODULE_SERVER, ISC_LOG_WARNING,
1131                               "statistics-channels specified but not effective "
1132                               "due to missing XML library");
1133 #endif
1134
1135                 for (element = cfg_list_first(statschannellist);
1136                      element != NULL;
1137                      element = cfg_list_next(element)) {
1138                         const cfg_obj_t *statschannel;
1139                         const cfg_obj_t *listenercfg = NULL;
1140
1141                         statschannel = cfg_listelt_value(element);
1142                         (void)cfg_map_get(statschannel, "inet",
1143                                           &listenercfg);
1144                         if (listenercfg == NULL)
1145                                 continue;
1146
1147                         for (element2 = cfg_list_first(listenercfg);
1148                              element2 != NULL;
1149                              element2 = cfg_list_next(element2)) {
1150                                 const cfg_obj_t *listen_params;
1151                                 const cfg_obj_t *obj;
1152                                 isc_sockaddr_t addr;
1153
1154                                 listen_params = cfg_listelt_value(element2);
1155
1156                                 obj = cfg_tuple_get(listen_params, "address");
1157                                 addr = *cfg_obj_assockaddr(obj);
1158                                 if (isc_sockaddr_getport(&addr) == 0)
1159                                         isc_sockaddr_setport(&addr, NS_STATSCHANNEL_HTTPPORT);
1160
1161                                 isc_sockaddr_format(&addr, socktext,
1162                                                     sizeof(socktext));
1163
1164                                 isc_log_write(ns_g_lctx,
1165                                               NS_LOGCATEGORY_GENERAL,
1166                                               NS_LOGMODULE_SERVER,
1167                                               ISC_LOG_DEBUG(9),
1168                                               "processing statistics "
1169                                               "channel %s",
1170                                               socktext);
1171
1172                                 update_listener(server, &listener,
1173                                                 listen_params, config, &addr,
1174                                                 aclconfctx, socktext);
1175
1176                                 if (listener != NULL) {
1177                                         /*
1178                                          * Remove the listener from the old
1179                                          * list, so it won't be shut down.
1180                                          */
1181                                         ISC_LIST_UNLINK(server->statschannels,
1182                                                         listener, link);
1183                                 } else {
1184                                         /*
1185                                          * This is a new listener.
1186                                          */
1187                                         isc_result_t r;
1188
1189                                         r = add_listener(server, &listener,
1190                                                          listen_params, config,
1191                                                          &addr, aclconfctx,
1192                                                          socktext);
1193                                         if (r != ISC_R_SUCCESS) {
1194                                                 cfg_obj_log(listen_params,
1195                                                             ns_g_lctx,
1196                                                             ISC_LOG_WARNING,
1197                                                             "couldn't allocate "
1198                                                             "statistics channel"
1199                                                             " %s: %s",
1200                                                             socktext,
1201                                                             isc_result_totext(r));
1202                                         }
1203                                 }
1204
1205                                 if (listener != NULL)
1206                                         ISC_LIST_APPEND(new_listeners, listener,
1207                                                         link);
1208                         }
1209                 }
1210         }
1211
1212         for (listener = ISC_LIST_HEAD(server->statschannels);
1213              listener != NULL;
1214              listener = listener_next) {
1215                 listener_next = ISC_LIST_NEXT(listener, link);
1216                 ISC_LIST_UNLINK(server->statschannels, listener, link);
1217                 shutdown_listener(listener);
1218         }
1219
1220         ISC_LIST_APPENDLIST(server->statschannels, new_listeners, link);
1221         return (ISC_R_SUCCESS);
1222 }
1223
1224 void
1225 ns_statschannels_shutdown(ns_server_t *server) {
1226         ns_statschannel_t *listener;
1227
1228         while ((listener = ISC_LIST_HEAD(server->statschannels)) != NULL) {
1229                 ISC_LIST_UNLINK(server->statschannels, listener, link);
1230                 shutdown_listener(listener);
1231         }
1232 }
1233
1234 isc_result_t
1235 ns_stats_dump(ns_server_t *server, FILE *fp) {
1236         isc_stdtime_t now;
1237         isc_result_t result;
1238         dns_view_t *view;
1239         dns_zone_t *zone, *next;
1240         stats_dumparg_t dumparg;
1241         isc_uint64_t nsstat_values[dns_nsstatscounter_max];
1242         isc_uint64_t resstat_values[dns_resstatscounter_max];
1243         isc_uint64_t zonestat_values[dns_zonestatscounter_max];
1244         isc_uint64_t sockstat_values[isc_sockstatscounter_max];
1245
1246         RUNTIME_CHECK(isc_once_do(&once, init_desc) == ISC_R_SUCCESS);
1247
1248         /* Set common fields */
1249         dumparg.type = statsformat_file;
1250         dumparg.arg = fp;
1251
1252         isc_stdtime_get(&now);
1253         fprintf(fp, "+++ Statistics Dump +++ (%lu)\n", (unsigned long)now);
1254
1255         fprintf(fp, "++ Incoming Requests ++\n");
1256         dns_opcodestats_dump(server->opcodestats, opcodestat_dump, &dumparg, 0);
1257
1258         fprintf(fp, "++ Incoming Queries ++\n");
1259         dns_rdatatypestats_dump(server->rcvquerystats, rdtypestat_dump,
1260                                 &dumparg, 0);
1261
1262         fprintf(fp, "++ Outgoing Queries ++\n");
1263         for (view = ISC_LIST_HEAD(server->viewlist);
1264              view != NULL;
1265              view = ISC_LIST_NEXT(view, link)) {
1266                 if (view->resquerystats == NULL)
1267                         continue;
1268                 if (strcmp(view->name, "_default") == 0)
1269                         fprintf(fp, "[View: default]\n");
1270                 else
1271                         fprintf(fp, "[View: %s]\n", view->name);
1272                 dns_rdatatypestats_dump(view->resquerystats, rdtypestat_dump,
1273                                         &dumparg, 0);
1274         }
1275
1276         fprintf(fp, "++ Name Server Statistics ++\n");
1277         dump_counters(server->nsstats, statsformat_file, fp, NULL,
1278                       nsstats_desc, dns_nsstatscounter_max, nsstats_index,
1279                       nsstat_values, 0);
1280
1281         fprintf(fp, "++ Zone Maintenance Statistics ++\n");
1282         dump_counters(server->zonestats, statsformat_file, fp, NULL,
1283                       zonestats_desc, dns_zonestatscounter_max,
1284                       zonestats_index, zonestat_values, 0);
1285
1286         fprintf(fp, "++ Resolver Statistics ++\n");
1287         fprintf(fp, "[Common]\n");
1288         dump_counters(server->resolverstats, statsformat_file, fp, NULL,
1289                       resstats_desc, dns_resstatscounter_max, resstats_index,
1290                       resstat_values, 0);
1291         for (view = ISC_LIST_HEAD(server->viewlist);
1292              view != NULL;
1293              view = ISC_LIST_NEXT(view, link)) {
1294                 if (view->resstats == NULL)
1295                         continue;
1296                 if (strcmp(view->name, "_default") == 0)
1297                         fprintf(fp, "[View: default]\n");
1298                 else
1299                         fprintf(fp, "[View: %s]\n", view->name);
1300                 dump_counters(view->resstats, statsformat_file, fp, NULL,
1301                               resstats_desc, dns_resstatscounter_max,
1302                               resstats_index, resstat_values, 0);
1303         }
1304
1305         fprintf(fp, "++ Cache DB RRsets ++\n");
1306         for (view = ISC_LIST_HEAD(server->viewlist);
1307              view != NULL;
1308              view = ISC_LIST_NEXT(view, link)) {
1309                 dns_stats_t *cachestats;
1310
1311                 cachestats = dns_db_getrrsetstats(view->cachedb);
1312                 if (cachestats == NULL)
1313                         continue;
1314                 if (strcmp(view->name, "_default") == 0)
1315                         fprintf(fp, "[View: default]\n");
1316                 else
1317                         fprintf(fp, "[View: %s]\n", view->name);
1318                 dns_rdatasetstats_dump(cachestats, rdatasetstats_dump, &dumparg,
1319                                        0);
1320         }
1321
1322         fprintf(fp, "++ Socket I/O Statistics ++\n");
1323         dump_counters(server->sockstats, statsformat_file, fp, NULL,
1324                       sockstats_desc, isc_sockstatscounter_max, sockstats_index,
1325                       sockstat_values, 0);
1326
1327         fprintf(fp, "++ Per Zone Query Statistics ++\n");
1328         zone = NULL;
1329         for (result = dns_zone_first(server->zonemgr, &zone);
1330              result == ISC_R_SUCCESS;
1331              next = NULL, result = dns_zone_next(zone, &next), zone = next)
1332         {
1333                 isc_stats_t *zonestats = dns_zone_getrequeststats(zone);
1334                 if (zonestats != NULL) {
1335                         char zonename[DNS_NAME_FORMATSIZE];
1336
1337                         dns_name_format(dns_zone_getorigin(zone),
1338                                         zonename, sizeof(zonename));
1339                         view = dns_zone_getview(zone);
1340
1341                         fprintf(fp, "[%s", zonename);
1342                         if (strcmp(view->name, "_default") != 0)
1343                                 fprintf(fp, " (view: %s)", view->name);
1344                         fprintf(fp, "]\n");
1345
1346                         dump_counters(zonestats, statsformat_file, fp, NULL,
1347                                       nsstats_desc, dns_nsstatscounter_max,
1348                                       nsstats_index, nsstat_values, 0);
1349                 }
1350         }
1351
1352         fprintf(fp, "--- Statistics Dump --- (%lu)\n", (unsigned long)now);
1353
1354         return (ISC_R_SUCCESS); /* this function currently always succeeds */
1355 }