bind plugin: modernize the code a bit
[collectd.git] / src / bind.c
1 /**
2  * collectd - src/bind.c
3  * Copyright (C) 2009       Bruno PrĂ©mont
4  * Copyright (C) 2009,2010  Florian Forster
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Bruno PrĂ©mont <bonbons at linux-vserver.org>
21  *   Florian Forster <octo at collectd.org>
22  **/
23
24 #include "config.h"
25
26 #if STRPTIME_NEEDS_STANDARDS
27 #ifndef _ISOC99_SOURCE
28 #define _ISOC99_SOURCE 1
29 #endif
30 #ifndef _POSIX_C_SOURCE
31 #define _POSIX_C_SOURCE 200112L
32 #endif
33 #ifndef _XOPEN_SOURCE
34 #define _XOPEN_SOURCE 500
35 #endif
36 #endif /* STRPTIME_NEEDS_STANDARDS */
37
38 #if TIMEGM_NEEDS_BSD
39 #ifndef _BSD_SOURCE
40 #define _BSD_SOURCE 1
41 #endif
42 #endif /* TIMEGM_NEEDS_BSD */
43
44 #include "collectd.h"
45
46 #include "common.h"
47 #include "plugin.h"
48
49 #include <time.h>
50
51 /* Some versions of libcurl don't include this themselves and then don't have
52  * fd_set available. */
53 #if HAVE_SYS_SELECT_H
54 #include <sys/select.h>
55 #endif
56
57 #include <curl/curl.h>
58 #include <libxml/parser.h>
59 #include <libxml/xpath.h>
60
61 #ifndef BIND_DEFAULT_URL
62 #define BIND_DEFAULT_URL "http://localhost:8053/"
63 #endif
64
65 /*
66  * Some types used for the callback functions. `translation_table_ptr_t' and
67  * `list_info_ptr_t' are passed to the callbacks in the `void *user_data'
68  * pointer.
69  */
70 typedef int (*list_callback_t)(const char *name, value_t value,
71                                time_t current_time, void *user_data);
72
73 struct cb_view_s {
74   char *name;
75
76   int qtypes;
77   int resolver_stats;
78   int cacherrsets;
79
80   char **zones;
81   size_t zones_num;
82 };
83 typedef struct cb_view_s cb_view_t;
84
85 struct translation_info_s {
86   const char *xml_name;
87   const char *type;
88   const char *type_instance;
89 };
90 typedef struct translation_info_s translation_info_t;
91
92 struct translation_table_ptr_s {
93   const translation_info_t *table;
94   size_t table_length;
95   const char *plugin_instance;
96 };
97 typedef struct translation_table_ptr_s translation_table_ptr_t;
98
99 struct list_info_ptr_s {
100   const char *plugin_instance;
101   const char *type;
102 };
103 typedef struct list_info_ptr_s list_info_ptr_t;
104
105 /* FIXME: Enabled by default for backwards compatibility. */
106 /* TODO: Remove time parsing code. */
107 static _Bool config_parse_time = 1;
108
109 static char *url = NULL;
110 static int global_opcodes = 1;
111 static int global_qtypes = 1;
112 static int global_server_stats = 1;
113 static int global_zone_maint_stats = 1;
114 static int global_resolver_stats = 0;
115 static int global_memory_stats = 1;
116 static int timeout = -1;
117
118 static cb_view_t *views = NULL;
119 static size_t views_num = 0;
120
121 static CURL *curl = NULL;
122
123 static char *bind_buffer = NULL;
124 static size_t bind_buffer_size = 0;
125 static size_t bind_buffer_fill = 0;
126 static char bind_curl_error[CURL_ERROR_SIZE];
127
128 /* Translation table for the `nsstats' values. */
129 static const translation_info_t nsstats_translation_table[] = /* {{{ */
130     {
131         /* Requests */
132         {"Requestv4", "dns_request", "IPv4"},
133         {"Requestv6", "dns_request", "IPv6"},
134         {"ReqEdns0", "dns_request", "EDNS0"},
135         {"ReqBadEDNSVer", "dns_request", "BadEDNSVer"},
136         {"ReqTSIG", "dns_request", "TSIG"},
137         {"ReqSIG0", "dns_request", "SIG0"},
138         {"ReqBadSIG", "dns_request", "BadSIG"},
139         {"ReqTCP", "dns_request", "TCP"},
140         /* Rejects */
141         {"AuthQryRej", "dns_reject", "authoritative"},
142         {"RecQryRej", "dns_reject", "recursive"},
143         {"XfrRej", "dns_reject", "transfer"},
144         {"UpdateRej", "dns_reject", "update"},
145         /* Responses */
146         {"Response", "dns_response", "normal"},
147         {"TruncatedResp", "dns_response", "truncated"},
148         {"RespEDNS0", "dns_response", "EDNS0"},
149         {"RespTSIG", "dns_response", "TSIG"},
150         {"RespSIG0", "dns_response", "SIG0"},
151         /* Queries */
152         {"QryAuthAns", "dns_query", "authoritative"},
153         {"QryNoauthAns", "dns_query", "nonauth"},
154         {"QryReferral", "dns_query", "referral"},
155         {"QryRecursion", "dns_query", "recursion"},
156         {"QryDuplicate", "dns_query", "duplicate"},
157         {"QryDropped", "dns_query", "dropped"},
158         {"QryFailure", "dns_query", "failure"},
159         /* Response codes */
160         {"QrySuccess", "dns_rcode", "tx-NOERROR"},
161         {"QryNxrrset", "dns_rcode", "tx-NXRRSET"},
162         {"QrySERVFAIL", "dns_rcode", "tx-SERVFAIL"},
163         {"QryFORMERR", "dns_rcode", "tx-FORMERR"},
164         {"QryNXDOMAIN", "dns_rcode", "tx-NXDOMAIN"}
165 #if 0
166   { "XfrReqDone",      "type",         "type_instance" },
167   { "UpdateReqFwd",    "type",         "type_instance" },
168   { "UpdateRespFwd",   "type",         "type_instance" },
169   { "UpdateFwdFail",   "type",         "type_instance" },
170   { "UpdateDone",      "type",         "type_instance" },
171   { "UpdateFail",      "type",         "type_instance" },
172   { "UpdateBadPrereq", "type",         "type_instance" },
173 #endif
174 };
175 static int nsstats_translation_table_length =
176     STATIC_ARRAY_SIZE(nsstats_translation_table);
177 /* }}} */
178
179 /* Translation table for the `zonestats' values. */
180 static const translation_info_t zonestats_translation_table[] = /* {{{ */
181     {
182         /* Notify's */
183         {"NotifyOutv4", "dns_notify", "tx-IPv4"},
184         {"NotifyOutv6", "dns_notify", "tx-IPv6"},
185         {"NotifyInv4", "dns_notify", "rx-IPv4"},
186         {"NotifyInv6", "dns_notify", "rx-IPv6"},
187         {"NotifyRej", "dns_notify", "rejected"},
188         /* SOA/AXFS/IXFS requests */
189         {"SOAOutv4", "dns_opcode", "SOA-IPv4"},
190         {"SOAOutv6", "dns_opcode", "SOA-IPv6"},
191         {"AXFRReqv4", "dns_opcode", "AXFR-IPv4"},
192         {"AXFRReqv6", "dns_opcode", "AXFR-IPv6"},
193         {"IXFRReqv4", "dns_opcode", "IXFR-IPv4"},
194         {"IXFRReqv6", "dns_opcode", "IXFR-IPv6"},
195         /* Domain transfers */
196         {"XfrSuccess", "dns_transfer", "success"},
197         {"XfrFail", "dns_transfer", "failure"}};
198 static int zonestats_translation_table_length =
199     STATIC_ARRAY_SIZE(zonestats_translation_table);
200 /* }}} */
201
202 /* Translation table for the `resstats' values. */
203 static const translation_info_t resstats_translation_table[] = /* {{{ */
204     {
205         /* Generic resolver information */
206         {"Queryv4", "dns_query", "IPv4"},
207         {"Queryv6", "dns_query", "IPv6"},
208         {"Responsev4", "dns_response", "IPv4"},
209         {"Responsev6", "dns_response", "IPv6"},
210         /* Received response codes */
211         {"NXDOMAIN", "dns_rcode", "rx-NXDOMAIN"},
212         {"SERVFAIL", "dns_rcode", "rx-SERVFAIL"},
213         {"FORMERR", "dns_rcode", "rx-FORMERR"},
214         {"OtherError", "dns_rcode", "rx-OTHER"},
215         {"EDNS0Fail", "dns_rcode", "rx-EDNS0Fail"},
216         /* Received responses */
217         {"Mismatch", "dns_response", "mismatch"},
218         {"Truncated", "dns_response", "truncated"},
219         {"Lame", "dns_response", "lame"},
220         {"Retry", "dns_query", "retry"},
221 #if 0
222   { "GlueFetchv4",     "type", "type_instance" },
223   { "GlueFetchv6",     "type", "type_instance" },
224   { "GlueFetchv4Fail", "type", "type_instance" },
225   { "GlueFetchv6Fail", "type", "type_instance" },
226 #endif
227         /* DNSSEC information */
228         {"ValAttempt", "dns_resolver", "DNSSEC-attempt"},
229         {"ValOk", "dns_resolver", "DNSSEC-okay"},
230         {"ValNegOk", "dns_resolver", "DNSSEC-negokay"},
231         {"ValFail", "dns_resolver", "DNSSEC-fail"}};
232 static int resstats_translation_table_length =
233     STATIC_ARRAY_SIZE(resstats_translation_table);
234 /* }}} */
235
236 /* Translation table for the `memory/summary' values. */
237 static const translation_info_t memsummary_translation_table[] = /* {{{ */
238     {{"TotalUse", "memory", "TotalUse"},
239      {"InUse", "memory", "InUse"},
240      {"BlockSize", "memory", "BlockSize"},
241      {"ContextSize", "memory", "ContextSize"},
242      {"Lost", "memory", "Lost"}};
243 static int memsummary_translation_table_length =
244     STATIC_ARRAY_SIZE(memsummary_translation_table);
245 /* }}} */
246
247 static void submit(time_t ts, const char *plugin_instance, /* {{{ */
248                    const char *type, const char *type_instance, value_t value) {
249   value_list_t vl = VALUE_LIST_INIT;
250
251   vl.values = &value;
252   vl.values_len = 1;
253   if (config_parse_time)
254     vl.time = TIME_T_TO_CDTIME_T(ts);
255   sstrncpy(vl.plugin, "bind", sizeof(vl.plugin));
256   if (plugin_instance) {
257     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
258     replace_special(vl.plugin_instance, sizeof(vl.plugin_instance));
259   }
260   sstrncpy(vl.type, type, sizeof(vl.type));
261   if (type_instance) {
262     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
263     replace_special(vl.type_instance, sizeof(vl.type_instance));
264   }
265   plugin_dispatch_values(&vl);
266 } /* }}} void submit */
267
268 static size_t bind_curl_callback(void *buf, size_t size, /* {{{ */
269                                  size_t nmemb,
270                                  void __attribute__((unused)) * stream) {
271   size_t len = size * nmemb;
272
273   if (len == 0)
274     return len;
275
276   if ((bind_buffer_fill + len) >= bind_buffer_size) {
277     char *temp = realloc(bind_buffer, bind_buffer_fill + len + 1);
278     if (temp == NULL) {
279       ERROR("bind plugin: realloc failed.");
280       return 0;
281     }
282     bind_buffer = temp;
283     bind_buffer_size = bind_buffer_fill + len + 1;
284   }
285
286   memcpy(bind_buffer + bind_buffer_fill, (char *)buf, len);
287   bind_buffer_fill += len;
288   bind_buffer[bind_buffer_fill] = 0;
289
290   return len;
291 } /* }}} size_t bind_curl_callback */
292
293 /*
294  * Callback, that's called with a translation table.
295  * (Plugin instance is fixed, type and type instance come from lookup table.)
296  */
297 static int bind_xml_table_callback(const char *name, value_t value, /* {{{ */
298                                    time_t current_time, void *user_data) {
299   translation_table_ptr_t *table = (translation_table_ptr_t *)user_data;
300
301   if (table == NULL)
302     return -1;
303
304   for (size_t i = 0; i < table->table_length; i++) {
305     if (strcmp(table->table[i].xml_name, name) != 0)
306       continue;
307
308     submit(current_time, table->plugin_instance, table->table[i].type,
309            table->table[i].type_instance, value);
310     break;
311   }
312
313   return 0;
314 } /* }}} int bind_xml_table_callback */
315
316 /*
317  * Callback, that's used for lists.
318  * (Plugin instance and type are fixed, xml name is used as type instance.)
319  */
320 static int bind_xml_list_callback(const char *name, /* {{{ */
321                                   value_t value, time_t current_time,
322                                   void *user_data) {
323   list_info_ptr_t *list_info = (list_info_ptr_t *)user_data;
324
325   if (list_info == NULL)
326     return -1;
327
328   submit(current_time, list_info->plugin_instance, list_info->type,
329          /* type instance = */ name, value);
330
331   return 0;
332 } /* }}} int bind_xml_list_callback */
333
334 static int bind_xml_read_derive(xmlDoc *doc, xmlNode *node, /* {{{ */
335                                 derive_t *ret_value) {
336   char *str_ptr = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
337   if (str_ptr == NULL) {
338     ERROR("bind plugin: bind_xml_read_derive: xmlNodeListGetString failed.");
339     return -1;
340   }
341
342   value_t value;
343
344   int status = parse_value(str_ptr, &value, DS_TYPE_DERIVE);
345   if (status != 0) {
346     ERROR("bind plugin: Parsing string \"%s\" to derive value failed.",
347           str_ptr);
348     xmlFree(str_ptr);
349     return -1;
350   }
351
352   xmlFree(str_ptr);
353   *ret_value = value.derive;
354   return 0;
355 } /* }}} int bind_xml_read_derive */
356
357 static int bind_xml_read_gauge(xmlDoc *doc, xmlNode *node, /* {{{ */
358                                gauge_t *ret_value) {
359   char *str_ptr = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
360   if (str_ptr == NULL) {
361     ERROR("bind plugin: bind_xml_read_gauge: xmlNodeListGetString failed.");
362     return -1;
363   }
364
365   char *end_ptr;
366   errno = 0;
367   double value = strtod(str_ptr, &end_ptr);
368   xmlFree(str_ptr);
369   if (str_ptr == end_ptr || errno) {
370     if (errno && (value < 0))
371       ERROR("bind plugin: bind_xml_read_gauge: strtod failed with underflow.");
372     else if (errno && (value > 0))
373       ERROR("bind plugin: bind_xml_read_gauge: strtod failed with overflow.");
374     else
375       ERROR("bind plugin: bind_xml_read_gauge: strtod failed.");
376     return -1;
377   }
378
379   *ret_value = (gauge_t)value;
380   return 0;
381 } /* }}} int bind_xml_read_gauge */
382
383 static int bind_xml_read_timestamp(const char *xpath_expression, /* {{{ */
384                                    xmlDoc *doc, xmlXPathContext *xpathCtx,
385                                    time_t *ret_value) {
386   xmlXPathObject *xpathObj = xmlXPathEvalExpression(BAD_CAST xpath_expression, xpathCtx);
387   if (xpathObj == NULL) {
388     ERROR("bind plugin: Unable to evaluate XPath expression `%s'.",
389           xpath_expression);
390     return -1;
391   }
392
393   if ((xpathObj->nodesetval == NULL) || (xpathObj->nodesetval->nodeNr < 1)) {
394     xmlXPathFreeObject(xpathObj);
395     return -1;
396   }
397
398   if (xpathObj->nodesetval->nodeNr != 1) {
399     NOTICE("bind plugin: Evaluating the XPath expression `%s' returned "
400            "%i nodes. Only handling the first one.",
401            xpath_expression, xpathObj->nodesetval->nodeNr);
402   }
403
404   xmlNode *node = xpathObj->nodesetval->nodeTab[0];
405
406   if (node->xmlChildrenNode == NULL) {
407     ERROR("bind plugin: bind_xml_read_timestamp: "
408           "node->xmlChildrenNode == NULL");
409     xmlXPathFreeObject(xpathObj);
410     return -1;
411   }
412
413
414   char *str_ptr = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
415   if (str_ptr == NULL) {
416     ERROR("bind plugin: bind_xml_read_timestamp: xmlNodeListGetString failed.");
417     xmlXPathFreeObject(xpathObj);
418     return -1;
419   }
420
421   struct tm tm = {0};
422   char *tmp = strptime(str_ptr, "%Y-%m-%dT%T", &tm);
423   xmlFree(str_ptr);
424   if (tmp == NULL) {
425     ERROR("bind plugin: bind_xml_read_timestamp: strptime failed.");
426     xmlXPathFreeObject(xpathObj);
427     return -1;
428   }
429
430 #if HAVE_TIMEGM
431   time_t t = timegm(&tm);
432   if (t == ((time_t)-1)) {
433     ERROR("bind plugin: timegm() failed: %s", STRERRNO);
434     return -1;
435   }
436   *ret_value = t;
437 #else
438   time_t t = mktime(&tm);
439   if (t == ((time_t)-1)) {
440     ERROR("bind plugin: mktime() failed: %s", STRERRNO);
441     return -1;
442   }
443   /* mktime assumes that tm is local time. Luckily, it also sets timezone to
444    * the offset used for the conversion, and we undo the conversion to convert
445    * back to UTC. */
446   *ret_value = t - timezone;
447 #endif
448
449   xmlXPathFreeObject(xpathObj);
450   return 0;
451 } /* }}} int bind_xml_read_timestamp */
452
453 /*
454  * bind_parse_generic_name_value
455  *
456  * Reads statistics in the form:
457  * <foo>
458  *   <name>QUERY</name>
459  *   <counter>123</counter>
460  * </foo>
461  */
462 static int bind_parse_generic_name_value(const char *xpath_expression, /* {{{ */
463                                          list_callback_t list_callback,
464                                          void *user_data, xmlDoc *doc,
465                                          xmlXPathContext *xpathCtx,
466                                          time_t current_time, int ds_type) {
467   xmlXPathObject *xpathObj = xmlXPathEvalExpression(BAD_CAST xpath_expression, xpathCtx);
468   if (xpathObj == NULL) {
469     ERROR("bind plugin: Unable to evaluate XPath expression `%s'.",
470           xpath_expression);
471     return -1;
472   }
473
474   int num_entries = 0;
475   /* Iterate over all matching nodes. */
476   for (int i = 0; xpathObj->nodesetval && (i < xpathObj->nodesetval->nodeNr);
477        i++) {
478
479     xmlNode *name_node = NULL;
480     xmlNode *counter = NULL;
481
482     xmlNode *parent = xpathObj->nodesetval->nodeTab[i];
483     DEBUG("bind plugin: bind_parse_generic_name_value: parent->name = %s;",
484           (char *)parent->name);
485
486     /* Iterate over all child nodes. */
487     for (xmlNode *child = parent->xmlChildrenNode; child != NULL;
488          child = child->next) {
489       if (child->type != XML_ELEMENT_NODE)
490         continue;
491
492       if (xmlStrcmp(BAD_CAST "name", child->name) == 0)
493         name_node = child;
494       else if (xmlStrcmp(BAD_CAST "counter", child->name) == 0)
495         counter = child;
496     }
497
498     if ((name_node != NULL) && (counter != NULL)) {
499       char *name =
500           (char *)xmlNodeListGetString(doc, name_node->xmlChildrenNode, 1);
501       value_t value;
502       int status;
503
504       if (ds_type == DS_TYPE_GAUGE)
505         status = bind_xml_read_gauge(doc, counter, &value.gauge);
506       else
507         status = bind_xml_read_derive(doc, counter, &value.derive);
508       if (status != 0) {
509         xmlFree(name);
510         continue;
511       }
512
513       status = (*list_callback)(name, value, current_time, user_data);
514       if (status == 0)
515         num_entries++;
516
517       xmlFree(name);
518     }
519   }
520
521   DEBUG("bind plugin: Found %d %s for XPath expression `%s'", num_entries,
522         (num_entries == 1) ? "entry" : "entries", xpath_expression);
523
524   xmlXPathFreeObject(xpathObj);
525
526   return 0;
527 } /* }}} int bind_parse_generic_name_value */
528
529 /*
530  * bind_parse_generic_value_list
531  *
532  * Reads statistics in the form:
533  * <foo>
534  *   <name0>123</name0>
535  *   <name1>234</name1>
536  *   <name2>345</name2>
537  *   :
538  * </foo>
539  */
540 static int bind_parse_generic_value_list(const char *xpath_expression, /* {{{ */
541                                          list_callback_t list_callback,
542                                          void *user_data, xmlDoc *doc,
543                                          xmlXPathContext *xpathCtx,
544                                          time_t current_time, int ds_type) {
545   xmlXPathObject *xpathObj = xmlXPathEvalExpression(BAD_CAST xpath_expression, xpathCtx);
546   if (xpathObj == NULL) {
547     ERROR("bind plugin: Unable to evaluate XPath expression `%s'.",
548           xpath_expression);
549     return -1;
550   }
551
552   int num_entries = 0;
553   /* Iterate over all matching nodes. */
554   for (int i = 0; xpathObj->nodesetval && (i < xpathObj->nodesetval->nodeNr);
555        i++) {
556     /* Iterate over all child nodes. */
557     for (xmlNode *child = xpathObj->nodesetval->nodeTab[i]->xmlChildrenNode;
558          child != NULL; child = child->next) {
559
560       if (child->type != XML_ELEMENT_NODE)
561         continue;
562
563       char *node_name = (char *)child->name;
564
565       value_t value;
566       int status;
567       if (ds_type == DS_TYPE_GAUGE)
568         status = bind_xml_read_gauge(doc, child, &value.gauge);
569       else
570         status = bind_xml_read_derive(doc, child, &value.derive);
571       if (status != 0)
572         continue;
573
574       status = (*list_callback)(node_name, value, current_time, user_data);
575       if (status == 0)
576         num_entries++;
577     }
578   }
579
580   DEBUG("bind plugin: Found %d %s for XPath expression `%s'", num_entries,
581         (num_entries == 1) ? "entry" : "entries", xpath_expression);
582
583   xmlXPathFreeObject(xpathObj);
584
585   return 0;
586 } /* }}} int bind_parse_generic_value_list */
587
588 /*
589  * bind_parse_generic_name_attr_value_list
590  *
591  * Reads statistics in the form:
592  * <foo>
593  *   <counter name="name0">123</counter>
594  *   <counter name="name1">234</counter>
595  *   <counter name="name2">345</counter>
596  *   :
597  * </foo>
598  */
599 static int bind_parse_generic_name_attr_value_list(
600     const char *xpath_expression, /* {{{ */
601     list_callback_t list_callback, void *user_data, xmlDoc *doc,
602     xmlXPathContext *xpathCtx, time_t current_time, int ds_type) {
603
604   xmlXPathObject *xpathObj = xmlXPathEvalExpression(BAD_CAST xpath_expression, xpathCtx);
605   if (xpathObj == NULL) {
606     ERROR("bind plugin: Unable to evaluate XPath expression `%s'.",
607           xpath_expression);
608     return -1;
609   }
610
611   int num_entries = 0;
612   /* Iterate over all matching nodes. */
613   for (int i = 0; xpathObj->nodesetval && (i < xpathObj->nodesetval->nodeNr);
614        i++) {
615     /* Iterate over all child nodes. */
616     for (xmlNode *child = xpathObj->nodesetval->nodeTab[i]->xmlChildrenNode;
617          child != NULL; child = child->next) {
618       if (child->type != XML_ELEMENT_NODE)
619         continue;
620
621       if (strncmp("counter", (char *)child->name, strlen("counter")) != 0)
622         continue;
623
624       char *attr_name = (char *)xmlGetProp(child, BAD_CAST "name");
625       if (attr_name == NULL) {
626         DEBUG("bind plugin: found <counter> without name.");
627         continue;
628       }
629
630       value_t value;
631       int status;
632
633       if (ds_type == DS_TYPE_GAUGE)
634         status = bind_xml_read_gauge(doc, child, &value.gauge);
635       else
636         status = bind_xml_read_derive(doc, child, &value.derive);
637       if (status != 0) {
638         xmlFree(attr_name);
639         continue;
640       }
641
642       status = (*list_callback)(attr_name, value, current_time, user_data);
643       if (status == 0)
644         num_entries++;
645
646       xmlFree(attr_name);
647     }
648   }
649
650   DEBUG("bind plugin: Found %d %s for XPath expression `%s'", num_entries,
651         (num_entries == 1) ? "entry" : "entries", xpath_expression);
652
653   xmlXPathFreeObject(xpathObj);
654
655   return 0;
656 } /* }}} int bind_parse_generic_name_attr_value_list */
657
658 static int bind_xml_stats_handle_zone(int version, xmlDoc *doc, /* {{{ */
659                                       xmlXPathContext *path_ctx, xmlNode *node,
660                                       cb_view_t *view, time_t current_time) {
661   char *zone_name = NULL;
662
663   if (version >= 3) {
664     char *n = (char *)xmlGetProp(node, BAD_CAST "name");
665     char *c = (char *)xmlGetProp(node, BAD_CAST "rdataclass");
666     if (n && c) {
667       zone_name = (char *)xmlMalloc(strlen(n) + strlen(c) + 2);
668       snprintf(zone_name, strlen(n) + strlen(c) + 2, "%s/%s", n, c);
669     }
670     xmlFree(n);
671     xmlFree(c);
672   } else {
673     xmlXPathObject *path_obj = xmlXPathEvalExpression(BAD_CAST "name", path_ctx);
674     if (path_obj == NULL) {
675       ERROR("bind plugin: xmlXPathEvalExpression failed.");
676       return -1;
677     }
678
679     for (int i = 0; path_obj->nodesetval && (i < path_obj->nodesetval->nodeNr);
680          i++) {
681       zone_name = (char *)xmlNodeListGetString(
682           doc, path_obj->nodesetval->nodeTab[i]->xmlChildrenNode, 1);
683       if (zone_name != NULL)
684         break;
685     }
686     xmlXPathFreeObject(path_obj);
687   }
688
689   if (zone_name == NULL) {
690     ERROR("bind plugin: Could not determine zone name.");
691     return -1;
692   }
693
694   size_t j;
695   for (j = 0; j < view->zones_num; j++) {
696     if (strcasecmp(zone_name, view->zones[j]) == 0)
697       break;
698   }
699
700   xmlFree(zone_name);
701
702   if (j >= view->zones_num)
703     return 0;
704
705   zone_name = view->zones[j];
706
707   DEBUG("bind plugin: bind_xml_stats_handle_zone: Found zone `%s'.", zone_name);
708
709   { /* Parse the <counters> tag {{{ */
710     char plugin_instance[DATA_MAX_NAME_LEN];
711     translation_table_ptr_t table_ptr = {nsstats_translation_table,
712                                          nsstats_translation_table_length,
713                                          plugin_instance};
714
715     snprintf(plugin_instance, sizeof(plugin_instance), "%s-zone-%s", view->name,
716              zone_name);
717
718     if (version == 3) {
719       list_info_ptr_t list_info = {plugin_instance,
720                                    /* type = */ "dns_qtype"};
721       bind_parse_generic_name_attr_value_list(
722           /* xpath = */ "counters[@type='rcode']",
723           /* callback = */ bind_xml_table_callback,
724           /* user_data = */ &table_ptr, doc, path_ctx, current_time,
725           DS_TYPE_COUNTER);
726       bind_parse_generic_name_attr_value_list(
727           /* xpath = */ "counters[@type='qtype']",
728           /* callback = */ bind_xml_list_callback,
729           /* user_data = */ &list_info, doc, path_ctx, current_time,
730           DS_TYPE_COUNTER);
731     } else {
732       bind_parse_generic_value_list(/* xpath = */ "counters",
733                                     /* callback = */ bind_xml_table_callback,
734                                     /* user_data = */ &table_ptr, doc, path_ctx,
735                                     current_time, DS_TYPE_COUNTER);
736     }
737   } /* }}} */
738
739   return 0;
740 } /* }}} int bind_xml_stats_handle_zone */
741
742 static int bind_xml_stats_search_zones(int version, xmlDoc *doc, /* {{{ */
743                                        xmlXPathContext *path_ctx, xmlNode *node,
744                                        cb_view_t *view, time_t current_time) {
745   xmlXPathContext *zone_path_context = xmlXPathNewContext(doc);
746   if (zone_path_context == NULL) {
747     ERROR("bind plugin: xmlXPathNewContext failed.");
748     return -1;
749   }
750
751   xmlXPathObject *zone_nodes = xmlXPathEvalExpression(BAD_CAST "zones/zone", path_ctx);
752   if (zone_nodes == NULL) {
753     ERROR("bind plugin: Cannot find any <view> tags.");
754     xmlXPathFreeContext(zone_path_context);
755     return -1;
756   }
757
758   for (int i = 0; i < zone_nodes->nodesetval->nodeNr; i++) {
759     node = zone_nodes->nodesetval->nodeTab[i];
760     assert(node != NULL);
761
762     zone_path_context->node = node;
763
764     bind_xml_stats_handle_zone(version, doc, zone_path_context, node, view,
765                                current_time);
766   }
767
768   xmlXPathFreeObject(zone_nodes);
769   xmlXPathFreeContext(zone_path_context);
770   return 0;
771 } /* }}} int bind_xml_stats_search_zones */
772
773 static int bind_xml_stats_handle_view(int version, xmlDoc *doc, /* {{{ */
774                                       xmlXPathContext *path_ctx, xmlNode *node,
775                                       time_t current_time) {
776   char *view_name = NULL;
777   cb_view_t *view;
778   size_t j;
779
780   if (version == 3) {
781     view_name = (char *)xmlGetProp(node, BAD_CAST "name");
782
783     if (view_name == NULL) {
784       ERROR("bind plugin: Could not determine view name.");
785       return -1;
786     }
787
788     for (j = 0; j < views_num; j++) {
789       if (strcasecmp(view_name, views[j].name) == 0)
790         break;
791     }
792
793     xmlFree(view_name);
794     view_name = NULL;
795   } else {
796     xmlXPathObject *path_obj = xmlXPathEvalExpression(BAD_CAST "name", path_ctx);
797     if (path_obj == NULL) {
798       ERROR("bind plugin: xmlXPathEvalExpression failed.");
799       return -1;
800     }
801
802     for (int i = 0; path_obj->nodesetval && (i < path_obj->nodesetval->nodeNr);
803          i++) {
804       view_name = (char *)xmlNodeListGetString(
805           doc, path_obj->nodesetval->nodeTab[i]->xmlChildrenNode, 1);
806       if (view_name != NULL)
807         break;
808     }
809
810     if (view_name == NULL) {
811       ERROR("bind plugin: Could not determine view name.");
812       xmlXPathFreeObject(path_obj);
813       return -1;
814     }
815
816     for (j = 0; j < views_num; j++) {
817       if (strcasecmp(view_name, views[j].name) == 0)
818         break;
819     }
820
821     xmlFree(view_name);
822     xmlXPathFreeObject(path_obj);
823
824     view_name = NULL;
825     path_obj = NULL;
826   }
827
828   if (j >= views_num)
829     return 0;
830
831   view = views + j;
832
833   DEBUG("bind plugin: bind_xml_stats_handle_view: Found view `%s'.",
834         view->name);
835
836   if (view->qtypes != 0) /* {{{ */
837   {
838     char plugin_instance[DATA_MAX_NAME_LEN];
839     list_info_ptr_t list_info = {plugin_instance,
840                                  /* type = */ "dns_qtype"};
841
842     snprintf(plugin_instance, sizeof(plugin_instance), "%s-qtypes", view->name);
843     if (version == 3) {
844       bind_parse_generic_name_attr_value_list(
845           /* xpath = */ "counters[@type='resqtype']",
846           /* callback = */ bind_xml_list_callback,
847           /* user_data = */ &list_info, doc, path_ctx, current_time,
848           DS_TYPE_COUNTER);
849     } else {
850       bind_parse_generic_name_value(/* xpath = */ "rdtype",
851                                     /* callback = */ bind_xml_list_callback,
852                                     /* user_data = */ &list_info, doc, path_ctx,
853                                     current_time, DS_TYPE_COUNTER);
854     }
855   } /* }}} */
856
857   if (view->resolver_stats != 0) /* {{{ */
858   {
859     char plugin_instance[DATA_MAX_NAME_LEN];
860     translation_table_ptr_t table_ptr = {resstats_translation_table,
861                                          resstats_translation_table_length,
862                                          plugin_instance};
863
864     snprintf(plugin_instance, sizeof(plugin_instance), "%s-resolver_stats",
865              view->name);
866     if (version == 3) {
867       bind_parse_generic_name_attr_value_list(
868           "counters[@type='resstats']",
869           /* callback = */ bind_xml_table_callback,
870           /* user_data = */ &table_ptr, doc, path_ctx, current_time,
871           DS_TYPE_COUNTER);
872     } else {
873       bind_parse_generic_name_value("resstat",
874                                     /* callback = */ bind_xml_table_callback,
875                                     /* user_data = */ &table_ptr, doc, path_ctx,
876                                     current_time, DS_TYPE_COUNTER);
877     }
878   } /* }}} */
879
880   /* Record types in the cache */
881   if (view->cacherrsets != 0) /* {{{ */
882   {
883     char plugin_instance[DATA_MAX_NAME_LEN];
884     list_info_ptr_t list_info = {plugin_instance,
885                                  /* type = */ "dns_qtype_cached"};
886
887     snprintf(plugin_instance, sizeof(plugin_instance), "%s-cache_rr_sets",
888              view->name);
889
890     bind_parse_generic_name_value(/* xpath = */ "cache/rrset",
891                                   /* callback = */ bind_xml_list_callback,
892                                   /* user_data = */ &list_info, doc, path_ctx,
893                                   current_time, DS_TYPE_GAUGE);
894   } /* }}} */
895
896   if (view->zones_num > 0)
897     bind_xml_stats_search_zones(version, doc, path_ctx, node, view,
898                                 current_time);
899
900   return 0;
901 } /* }}} int bind_xml_stats_handle_view */
902
903 static int bind_xml_stats_search_views(int version, xmlDoc *doc, /* {{{ */
904                                        xmlXPathContext *xpathCtx,
905                                        xmlNode *statsnode,
906                                        time_t current_time) {
907   xmlXPathContext *view_path_context = xmlXPathNewContext(doc);
908   if (view_path_context == NULL) {
909     ERROR("bind plugin: xmlXPathNewContext failed.");
910     return -1;
911   }
912
913   xmlXPathObject *view_nodes = xmlXPathEvalExpression(BAD_CAST "views/view", xpathCtx);
914   if (view_nodes == NULL) {
915     ERROR("bind plugin: Cannot find any <view> tags.");
916     xmlXPathFreeContext(view_path_context);
917     return -1;
918   }
919
920   for (int i = 0; i < view_nodes->nodesetval->nodeNr; i++) {
921     xmlNode *node = view_nodes->nodesetval->nodeTab[i];
922     assert(node != NULL);
923
924     view_path_context->node = node;
925
926     bind_xml_stats_handle_view(version, doc, view_path_context, node,
927                                current_time);
928   }
929
930   xmlXPathFreeObject(view_nodes);
931   xmlXPathFreeContext(view_path_context);
932   return 0;
933 } /* }}} int bind_xml_stats_search_views */
934
935 static void bind_xml_stats_v3(xmlDoc *doc, /* {{{ */
936                               xmlXPathContext *xpathCtx, xmlNode *statsnode,
937                               time_t current_time) {
938   /* XPath:     server/counters[@type='opcode']
939    * Variables: QUERY, IQUERY, NOTIFY, UPDATE, ...
940    * Layout v3:
941    *   <counters type="opcode">
942    *     <counter name="A">1</counter>
943    *     :
944    *   </counters>
945    */
946   if (global_opcodes != 0) {
947     list_info_ptr_t list_info = {/* plugin instance = */ "global-opcodes",
948                                  /* type = */ "dns_opcode"};
949     bind_parse_generic_name_attr_value_list(
950         /* xpath = */ "server/counters[@type='opcode']",
951         /* callback = */ bind_xml_list_callback,
952         /* user_data = */ &list_info, doc, xpathCtx, current_time,
953         DS_TYPE_COUNTER);
954   }
955
956   /* XPath:     server/counters[@type='qtype']
957    * Variables: RESERVED0, A, NS, CNAME, SOA, MR, PTR, HINFO, MX, TXT, RP,
958    *            X25, PX, AAAA, LOC, SRV, NAPTR, A6, DS, RRSIG, NSEC, DNSKEY,
959    *            SPF, TKEY, IXFR, AXFR, ANY, ..., Others
960    * Layout v3:
961    *   <counters type="opcode">
962    *     <counter name="A">1</counter>
963    *     :
964    *   </counters>
965    */
966   if (global_qtypes != 0) {
967     list_info_ptr_t list_info = {/* plugin instance = */ "global-qtypes",
968                                  /* type = */ "dns_qtype"};
969
970     bind_parse_generic_name_attr_value_list(
971         /* xpath = */ "server/counters[@type='qtype']",
972         /* callback = */ bind_xml_list_callback,
973         /* user_data = */ &list_info, doc, xpathCtx, current_time,
974         DS_TYPE_COUNTER);
975   }
976
977   /* XPath:     server/counters[@type='nsstat']
978    * Variables: Requestv4, Requestv6, ReqEdns0, ReqBadEDNSVer, ReqTSIG,
979    *            ReqSIG0, ReqBadSIG, ReqTCP, AuthQryRej, RecQryRej, XfrRej,
980    *            UpdateRej, Response, TruncatedResp, RespEDNS0, RespTSIG,
981    *            RespSIG0, QrySuccess, QryAuthAns, QryNoauthAns, QryReferral,
982    *            QryNxrrset, QrySERVFAIL, QryFORMERR, QryNXDOMAIN, QryRecursion,
983    *            QryDuplicate, QryDropped, QryFailure, XfrReqDone, UpdateReqFwd,
984    *            UpdateRespFwd, UpdateFwdFail, UpdateDone, UpdateFail,
985    *            UpdateBadPrereq
986    * Layout v3:
987    *   <counters type="nsstat"
988    *     <counter name="Requestv4">1</counter>
989    *     <counter name="Requestv6">0</counter>
990    *     :
991    *   </counter>
992    */
993   if (global_server_stats) {
994     translation_table_ptr_t table_ptr = {
995         nsstats_translation_table, nsstats_translation_table_length,
996         /* plugin_instance = */ "global-server_stats"};
997
998     bind_parse_generic_name_attr_value_list(
999         "server/counters[@type='nsstat']",
1000         /* callback = */ bind_xml_table_callback,
1001         /* user_data = */ &table_ptr, doc, xpathCtx, current_time,
1002         DS_TYPE_COUNTER);
1003   }
1004
1005   /* XPath:     server/zonestats, server/zonestat,
1006    * server/counters[@type='zonestat']
1007    * Variables: NotifyOutv4, NotifyOutv6, NotifyInv4, NotifyInv6, NotifyRej,
1008    *            SOAOutv4, SOAOutv6, AXFRReqv4, AXFRReqv6, IXFRReqv4, IXFRReqv6,
1009    *            XfrSuccess, XfrFail
1010    * Layout v3:
1011    *   <counters type="zonestat"
1012    *     <counter name="NotifyOutv4">0</counter>
1013    *     <counter name="NotifyOutv6">0</counter>
1014    *     :
1015    *   </counter>
1016    */
1017   if (global_zone_maint_stats) {
1018     translation_table_ptr_t table_ptr = {
1019         zonestats_translation_table, zonestats_translation_table_length,
1020         /* plugin_instance = */ "global-zone_maint_stats"};
1021
1022     bind_parse_generic_name_attr_value_list(
1023         "server/counters[@type='zonestat']",
1024         /* callback = */ bind_xml_table_callback,
1025         /* user_data = */ &table_ptr, doc, xpathCtx, current_time,
1026         DS_TYPE_COUNTER);
1027   }
1028
1029   /* XPath:     server/resstats, server/counters[@type='resstat']
1030    * Variables: Queryv4, Queryv6, Responsev4, Responsev6, NXDOMAIN, SERVFAIL,
1031    *            FORMERR, OtherError, EDNS0Fail, Mismatch, Truncated, Lame,
1032    *            Retry, GlueFetchv4, GlueFetchv6, GlueFetchv4Fail,
1033    *            GlueFetchv6Fail, ValAttempt, ValOk, ValNegOk, ValFail
1034    * Layout v3:
1035    *   <counters type="resstat"
1036    *     <counter name="Queryv4">0</counter>
1037    *     <counter name="Queryv6">0</counter>
1038    *     :
1039    *   </counter>
1040    */
1041   if (global_resolver_stats != 0) {
1042     translation_table_ptr_t table_ptr = {
1043         resstats_translation_table, resstats_translation_table_length,
1044         /* plugin_instance = */ "global-resolver_stats"};
1045
1046     bind_parse_generic_name_attr_value_list(
1047         "server/counters[@type='resstat']",
1048         /* callback = */ bind_xml_table_callback,
1049         /* user_data = */ &table_ptr, doc, xpathCtx, current_time,
1050         DS_TYPE_COUNTER);
1051   }
1052 } /* }}} bind_xml_stats_v3 */
1053
1054 static void bind_xml_stats_v1_v2(int version, xmlDoc *doc, /* {{{ */
1055                                  xmlXPathContext *xpathCtx, xmlNode *statsnode,
1056                                  time_t current_time) {
1057   /* XPath:     server/requests/opcode, server/counters[@type='opcode']
1058    * Variables: QUERY, IQUERY, NOTIFY, UPDATE, ...
1059    * Layout V1 and V2:
1060    *   <opcode>
1061    *     <name>A</name>
1062    *     <counter>1</counter>
1063    *   </opcode>
1064    *   :
1065    */
1066   if (global_opcodes != 0) {
1067     list_info_ptr_t list_info = {/* plugin instance = */ "global-opcodes",
1068                                  /* type = */ "dns_opcode"};
1069
1070     bind_parse_generic_name_value(/* xpath = */ "server/requests/opcode",
1071                                   /* callback = */ bind_xml_list_callback,
1072                                   /* user_data = */ &list_info, doc, xpathCtx,
1073                                   current_time, DS_TYPE_COUNTER);
1074   }
1075
1076   /* XPath:     server/queries-in/rdtype, server/counters[@type='qtype']
1077    * Variables: RESERVED0, A, NS, CNAME, SOA, MR, PTR, HINFO, MX, TXT, RP,
1078    *            X25, PX, AAAA, LOC, SRV, NAPTR, A6, DS, RRSIG, NSEC, DNSKEY,
1079    *            SPF, TKEY, IXFR, AXFR, ANY, ..., Others
1080    * Layout v1 or v2:
1081    *   <rdtype>
1082    *     <name>A</name>
1083    *     <counter>1</counter>
1084    *   </rdtype>
1085    *   :
1086    */
1087   if (global_qtypes != 0) {
1088     list_info_ptr_t list_info = {/* plugin instance = */ "global-qtypes",
1089                                  /* type = */ "dns_qtype"};
1090
1091     bind_parse_generic_name_value(/* xpath = */ "server/queries-in/rdtype",
1092                                   /* callback = */ bind_xml_list_callback,
1093                                   /* user_data = */ &list_info, doc, xpathCtx,
1094                                   current_time, DS_TYPE_COUNTER);
1095   }
1096
1097   /* XPath:     server/nsstats, server/nsstat, server/counters[@type='nsstat']
1098    * Variables: Requestv4, Requestv6, ReqEdns0, ReqBadEDNSVer, ReqTSIG,
1099    *            ReqSIG0, ReqBadSIG, ReqTCP, AuthQryRej, RecQryRej, XfrRej,
1100    *            UpdateRej, Response, TruncatedResp, RespEDNS0, RespTSIG,
1101    *            RespSIG0, QrySuccess, QryAuthAns, QryNoauthAns, QryReferral,
1102    *            QryNxrrset, QrySERVFAIL, QryFORMERR, QryNXDOMAIN, QryRecursion,
1103    *            QryDuplicate, QryDropped, QryFailure, XfrReqDone, UpdateReqFwd,
1104    *            UpdateRespFwd, UpdateFwdFail, UpdateDone, UpdateFail,
1105    *            UpdateBadPrereq
1106    * Layout v1:
1107    *   <nsstats>
1108    *     <Requestv4>1</Requestv4>
1109    *     <Requestv6>0</Requestv6>
1110    *     :
1111    *   </nsstats>
1112    * Layout v2:
1113    *   <nsstat>
1114    *     <name>Requestv4</name>
1115    *     <counter>1</counter>
1116    *   </nsstat>
1117    *   <nsstat>
1118    *     <name>Requestv6</name>
1119    *     <counter>0</counter>
1120    *   </nsstat>
1121    *   :
1122    */
1123   if (global_server_stats) {
1124     translation_table_ptr_t table_ptr = {
1125         nsstats_translation_table, nsstats_translation_table_length,
1126         /* plugin_instance = */ "global-server_stats"};
1127
1128     if (version == 1) {
1129       bind_parse_generic_value_list("server/nsstats",
1130                                     /* callback = */ bind_xml_table_callback,
1131                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1132                                     current_time, DS_TYPE_COUNTER);
1133     } else {
1134       bind_parse_generic_name_value("server/nsstat",
1135                                     /* callback = */ bind_xml_table_callback,
1136                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1137                                     current_time, DS_TYPE_COUNTER);
1138     }
1139   }
1140
1141   /* XPath:     server/zonestats, server/zonestat,
1142    * server/counters[@type='zonestat']
1143    * Variables: NotifyOutv4, NotifyOutv6, NotifyInv4, NotifyInv6, NotifyRej,
1144    *            SOAOutv4, SOAOutv6, AXFRReqv4, AXFRReqv6, IXFRReqv4, IXFRReqv6,
1145    *            XfrSuccess, XfrFail
1146    * Layout v1:
1147    *   <zonestats>
1148    *     <NotifyOutv4>0</NotifyOutv4>
1149    *     <NotifyOutv6>0</NotifyOutv6>
1150    *     :
1151    *   </zonestats>
1152    * Layout v2:
1153    *   <zonestat>
1154    *     <name>NotifyOutv4</name>
1155    *     <counter>0</counter>
1156    *   </zonestat>
1157    *   <zonestat>
1158    *     <name>NotifyOutv6</name>
1159    *     <counter>0</counter>
1160    *   </zonestat>
1161    *   :
1162    */
1163   if (global_zone_maint_stats) {
1164     translation_table_ptr_t table_ptr = {
1165         zonestats_translation_table, zonestats_translation_table_length,
1166         /* plugin_instance = */ "global-zone_maint_stats"};
1167
1168     if (version == 1) {
1169       bind_parse_generic_value_list("server/zonestats",
1170                                     /* callback = */ bind_xml_table_callback,
1171                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1172                                     current_time, DS_TYPE_COUNTER);
1173     } else {
1174       bind_parse_generic_name_value("server/zonestat",
1175                                     /* callback = */ bind_xml_table_callback,
1176                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1177                                     current_time, DS_TYPE_COUNTER);
1178     }
1179   }
1180
1181   /* XPath:     server/resstats, server/counters[@type='resstat']
1182    * Variables: Queryv4, Queryv6, Responsev4, Responsev6, NXDOMAIN, SERVFAIL,
1183    *            FORMERR, OtherError, EDNS0Fail, Mismatch, Truncated, Lame,
1184    *            Retry, GlueFetchv4, GlueFetchv6, GlueFetchv4Fail,
1185    *            GlueFetchv6Fail, ValAttempt, ValOk, ValNegOk, ValFail
1186    * Layout v1:
1187    *   <resstats>
1188    *     <Queryv4>0</Queryv4>
1189    *     <Queryv6>0</Queryv6>
1190    *     :
1191    *   </resstats>
1192    * Layout v2:
1193    *   <resstat>
1194    *     <name>Queryv4</name>
1195    *     <counter>0</counter>
1196    *   </resstat>
1197    *   <resstat>
1198    *     <name>Queryv6</name>
1199    *     <counter>0</counter>
1200    *   </resstat>
1201    *   :
1202    */
1203   if (global_resolver_stats != 0) {
1204     translation_table_ptr_t table_ptr = {
1205         resstats_translation_table, resstats_translation_table_length,
1206         /* plugin_instance = */ "global-resolver_stats"};
1207
1208     if (version == 1) {
1209       bind_parse_generic_value_list("server/resstats",
1210                                     /* callback = */ bind_xml_table_callback,
1211                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1212                                     current_time, DS_TYPE_COUNTER);
1213     } else {
1214       bind_parse_generic_name_value("server/resstat",
1215                                     /* callback = */ bind_xml_table_callback,
1216                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1217                                     current_time, DS_TYPE_COUNTER);
1218     }
1219   }
1220 } /* }}} bind_xml_stats_v1_v2 */
1221
1222 static int bind_xml_stats(int version, xmlDoc *doc, /* {{{ */
1223                           xmlXPathContext *xpathCtx, xmlNode *statsnode) {
1224   time_t current_time = 0;
1225
1226   xpathCtx->node = statsnode;
1227
1228   /* TODO: Check `server/boot-time' to recognize server restarts. */
1229
1230   int status = bind_xml_read_timestamp("server/current-time", doc, xpathCtx,
1231                                    &current_time);
1232   if (status != 0) {
1233     ERROR("bind plugin: Reading `server/current-time' failed.");
1234     return -1;
1235   }
1236   DEBUG("bind plugin: Current server time is %i.", (int)current_time);
1237
1238   if (version == 3) {
1239     bind_xml_stats_v3(doc, xpathCtx, statsnode, current_time);
1240   } else {
1241     bind_xml_stats_v1_v2(version, doc, xpathCtx, statsnode, current_time);
1242   }
1243
1244   /* XPath:  memory/summary
1245    * Variables: TotalUse, InUse, BlockSize, ContextSize, Lost
1246    * Layout: v2 and v3:
1247    *   <summary>
1248    *     <TotalUse>6587096</TotalUse>
1249    *     <InUse>1345424</InUse>
1250    *     <BlockSize>5505024</BlockSize>
1251    *     <ContextSize>3732456</ContextSize>
1252    *     <Lost>0</Lost>
1253    *   </summary>
1254    */
1255   if (global_memory_stats != 0) {
1256     translation_table_ptr_t table_ptr = {
1257         memsummary_translation_table, memsummary_translation_table_length,
1258         /* plugin_instance = */ "global-memory_stats"};
1259
1260     bind_parse_generic_value_list("memory/summary",
1261                                   /* callback = */ bind_xml_table_callback,
1262                                   /* user_data = */ &table_ptr, doc, xpathCtx,
1263                                   current_time, DS_TYPE_GAUGE);
1264   }
1265
1266   if (views_num > 0)
1267     bind_xml_stats_search_views(version, doc, xpathCtx, statsnode,
1268                                 current_time);
1269
1270   return 0;
1271 } /* }}} int bind_xml_stats */
1272
1273 static int bind_xml(const char *data) /* {{{ */
1274 {
1275   int ret = -1;
1276
1277   xmlDoc *doc = xmlParseMemory(data, strlen(data));
1278   if (doc == NULL) {
1279     ERROR("bind plugin: xmlParseMemory failed.");
1280     return -1;
1281   }
1282
1283   xmlXPathContext *xpathCtx = xmlXPathNewContext(doc);
1284   if (xpathCtx == NULL) {
1285     ERROR("bind plugin: xmlXPathNewContext failed.");
1286     xmlFreeDoc(doc);
1287     return -1;
1288   }
1289
1290   //
1291   // version 3.* of statistics XML (since BIND9.9)
1292   //
1293
1294   xmlXPathObject *xpathObj = xmlXPathEvalExpression(BAD_CAST "/statistics", xpathCtx);
1295   if (xpathObj == NULL || xpathObj->nodesetval == NULL ||
1296       xpathObj->nodesetval->nodeNr == 0) {
1297     DEBUG("bind plugin: Statistics appears not to be v3");
1298     // we will fallback to v1 or v2 detection
1299     if (xpathObj != NULL) {
1300       xmlXPathFreeObject(xpathObj);
1301     }
1302   } else {
1303     for (int i = 0; i < xpathObj->nodesetval->nodeNr; i++) {
1304       xmlNode *node;
1305       char *attr_version;
1306
1307       node = xpathObj->nodesetval->nodeTab[i];
1308       assert(node != NULL);
1309
1310       attr_version = (char *)xmlGetProp(node, BAD_CAST "version");
1311       if (attr_version == NULL) {
1312         NOTICE("bind plugin: Found <statistics> tag doesn't have a "
1313                "`version' attribute.");
1314         continue;
1315       }
1316       DEBUG("bind plugin: Found: <statistics version=\"%s\">", attr_version);
1317
1318       if (strncmp("3.", attr_version, strlen("3.")) != 0) {
1319         /* TODO: Use the complaint mechanism here. */
1320         NOTICE("bind plugin: Found <statistics> tag with version `%s'. "
1321                "Unfortunately I have no clue how to parse that. "
1322                "Please open a bug report for this.",
1323                attr_version);
1324         xmlFree(attr_version);
1325         continue;
1326       }
1327       ret = bind_xml_stats(3, doc, xpathCtx, node);
1328
1329       xmlFree(attr_version);
1330       /* One <statistics> node ought to be enough. */
1331       break;
1332     }
1333
1334     // we are finished, early-return
1335     xmlXPathFreeObject(xpathObj);
1336     xmlXPathFreeContext(xpathCtx);
1337     xmlFreeDoc(doc);
1338
1339     return ret;
1340   }
1341
1342   //
1343   // versions 1.* or 2.* of statistics XML
1344   //
1345
1346   xpathObj = xmlXPathEvalExpression(BAD_CAST "/isc/bind/statistics", xpathCtx);
1347   if (xpathObj == NULL) {
1348     ERROR("bind plugin: Cannot find the <statistics> tag.");
1349     xmlXPathFreeContext(xpathCtx);
1350     xmlFreeDoc(doc);
1351     return -1;
1352   } else if (xpathObj->nodesetval == NULL) {
1353     ERROR("bind plugin: xmlXPathEvalExpression failed.");
1354     xmlXPathFreeObject(xpathObj);
1355     xmlXPathFreeContext(xpathCtx);
1356     xmlFreeDoc(doc);
1357     return -1;
1358   }
1359
1360   for (int i = 0; i < xpathObj->nodesetval->nodeNr; i++) {
1361     xmlNode *node;
1362     char *attr_version;
1363     int parsed_version = 0;
1364
1365     node = xpathObj->nodesetval->nodeTab[i];
1366     assert(node != NULL);
1367
1368     attr_version = (char *)xmlGetProp(node, BAD_CAST "version");
1369     if (attr_version == NULL) {
1370       NOTICE("bind plugin: Found <statistics> tag doesn't have a "
1371              "`version' attribute.");
1372       continue;
1373     }
1374     DEBUG("bind plugin: Found: <statistics version=\"%s\">", attr_version);
1375
1376     /* At the time this plugin was written, version "1.0" was used by
1377      * BIND 9.5.0, version "2.0" was used by BIND 9.5.1 and 9.6.0. We assume
1378      * that "1.*" and "2.*" don't introduce structural changes, so we just
1379      * check for the first two characters here. */
1380     if (strncmp("1.", attr_version, strlen("1.")) == 0)
1381       parsed_version = 1;
1382     else if (strncmp("2.", attr_version, strlen("2.")) == 0)
1383       parsed_version = 2;
1384     else {
1385       /* TODO: Use the complaint mechanism here. */
1386       NOTICE("bind plugin: Found <statistics> tag with version `%s'. "
1387              "Unfortunately I have no clue how to parse that. "
1388              "Please open a bug report for this.",
1389              attr_version);
1390       xmlFree(attr_version);
1391       continue;
1392     }
1393
1394     ret = bind_xml_stats(parsed_version, doc, xpathCtx, node);
1395
1396     xmlFree(attr_version);
1397     /* One <statistics> node ought to be enough. */
1398     break;
1399   }
1400
1401   xmlXPathFreeObject(xpathObj);
1402   xmlXPathFreeContext(xpathCtx);
1403   xmlFreeDoc(doc);
1404
1405   return ret;
1406 } /* }}} int bind_xml */
1407
1408 static int bind_config_set_bool(const char *name, int *var, /* {{{ */
1409                                 oconfig_item_t *ci) {
1410   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN)) {
1411     WARNING("bind plugin: The `%s' option needs "
1412             "exactly one boolean argument.",
1413             name);
1414     return -1;
1415   }
1416
1417   if (ci->values[0].value.boolean)
1418     *var = 1;
1419   else
1420     *var = 0;
1421   return 0;
1422 } /* }}} int bind_config_set_bool */
1423
1424 static int bind_config_add_view_zone(cb_view_t *view, /* {{{ */
1425                                      oconfig_item_t *ci) {
1426   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1427     WARNING("bind plugin: The `Zone' option needs "
1428             "exactly one string argument.");
1429     return -1;
1430   }
1431
1432   char **tmp = realloc(view->zones, sizeof(char *) * (view->zones_num + 1));
1433   if (tmp == NULL) {
1434     ERROR("bind plugin: realloc failed.");
1435     return -1;
1436   }
1437   view->zones = tmp;
1438
1439   view->zones[view->zones_num] = strdup(ci->values[0].value.string);
1440   if (view->zones[view->zones_num] == NULL) {
1441     ERROR("bind plugin: strdup failed.");
1442     return -1;
1443   }
1444   view->zones_num++;
1445
1446   return 0;
1447 } /* }}} int bind_config_add_view_zone */
1448
1449 static int bind_config_add_view(oconfig_item_t *ci) /* {{{ */
1450 {
1451   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1452     WARNING("bind plugin: `View' blocks need exactly one string argument.");
1453     return -1;
1454   }
1455
1456   cb_view_t *tmp = realloc(views, sizeof(*views) * (views_num + 1));
1457   if (tmp == NULL) {
1458     ERROR("bind plugin: realloc failed.");
1459     return -1;
1460   }
1461   views = tmp;
1462   tmp = views + views_num;
1463
1464   memset(tmp, 0, sizeof(*tmp));
1465   tmp->qtypes = 1;
1466   tmp->resolver_stats = 1;
1467   tmp->cacherrsets = 1;
1468   tmp->zones = NULL;
1469   tmp->zones_num = 0;
1470
1471   tmp->name = strdup(ci->values[0].value.string);
1472   if (tmp->name == NULL) {
1473     ERROR("bind plugin: strdup failed.");
1474     sfree(views);
1475     return -1;
1476   }
1477
1478   for (int i = 0; i < ci->children_num; i++) {
1479     oconfig_item_t *child = ci->children + i;
1480
1481     if (strcasecmp("QTypes", child->key) == 0)
1482       bind_config_set_bool("QTypes", &tmp->qtypes, child);
1483     else if (strcasecmp("ResolverStats", child->key) == 0)
1484       bind_config_set_bool("ResolverStats", &tmp->resolver_stats, child);
1485     else if (strcasecmp("CacheRRSets", child->key) == 0)
1486       bind_config_set_bool("CacheRRSets", &tmp->cacherrsets, child);
1487     else if (strcasecmp("Zone", child->key) == 0)
1488       bind_config_add_view_zone(tmp, child);
1489     else {
1490       WARNING("bind plugin: Unknown configuration option "
1491               "`%s' in view `%s' will be ignored.",
1492               child->key, tmp->name);
1493     }
1494   } /* for (i = 0; i < ci->children_num; i++) */
1495
1496   views_num++;
1497   return 0;
1498 } /* }}} int bind_config_add_view */
1499
1500 static int bind_config(oconfig_item_t *ci) /* {{{ */
1501 {
1502   for (int i = 0; i < ci->children_num; i++) {
1503     oconfig_item_t *child = ci->children + i;
1504
1505     if (strcasecmp("Url", child->key) == 0) {
1506       if ((child->values_num != 1) ||
1507           (child->values[0].type != OCONFIG_TYPE_STRING)) {
1508         WARNING("bind plugin: The `Url' option needs "
1509                 "exactly one string argument.");
1510         return -1;
1511       }
1512
1513       sfree(url);
1514       url = strdup(child->values[0].value.string);
1515     } else if (strcasecmp("OpCodes", child->key) == 0)
1516       bind_config_set_bool("OpCodes", &global_opcodes, child);
1517     else if (strcasecmp("QTypes", child->key) == 0)
1518       bind_config_set_bool("QTypes", &global_qtypes, child);
1519     else if (strcasecmp("ServerStats", child->key) == 0)
1520       bind_config_set_bool("ServerStats", &global_server_stats, child);
1521     else if (strcasecmp("ZoneMaintStats", child->key) == 0)
1522       bind_config_set_bool("ZoneMaintStats", &global_zone_maint_stats, child);
1523     else if (strcasecmp("ResolverStats", child->key) == 0)
1524       bind_config_set_bool("ResolverStats", &global_resolver_stats, child);
1525     else if (strcasecmp("MemoryStats", child->key) == 0)
1526       bind_config_set_bool("MemoryStats", &global_memory_stats, child);
1527     else if (strcasecmp("View", child->key) == 0)
1528       bind_config_add_view(child);
1529     else if (strcasecmp("ParseTime", child->key) == 0)
1530       cf_util_get_boolean(child, &config_parse_time);
1531     else if (strcasecmp("Timeout", child->key) == 0)
1532       cf_util_get_int(child, &timeout);
1533     else {
1534       WARNING("bind plugin: Unknown configuration option "
1535               "`%s' will be ignored.",
1536               child->key);
1537     }
1538   }
1539
1540   return 0;
1541 } /* }}} int bind_config */
1542
1543 static int bind_init(void) /* {{{ */
1544 {
1545   if (curl != NULL)
1546     return 0;
1547
1548   curl = curl_easy_init();
1549   if (curl == NULL) {
1550     ERROR("bind plugin: bind_init: curl_easy_init failed.");
1551     return -1;
1552   }
1553
1554   curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
1555   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, bind_curl_callback);
1556   curl_easy_setopt(curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
1557   curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, bind_curl_error);
1558   curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
1559   curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
1560 #ifdef HAVE_CURLOPT_TIMEOUT_MS
1561   curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
1562                    (timeout >= 0) ? (long)timeout : (long)CDTIME_T_TO_MS(
1563                                                         plugin_get_interval()));
1564 #endif
1565
1566   return 0;
1567 } /* }}} int bind_init */
1568
1569 static int bind_read(void) /* {{{ */
1570 {
1571   if (curl == NULL) {
1572     ERROR("bind plugin: I don't have a CURL object.");
1573     return -1;
1574   }
1575
1576   bind_buffer_fill = 0;
1577
1578   curl_easy_setopt(curl, CURLOPT_URL, (url != NULL) ? url : BIND_DEFAULT_URL);
1579
1580   if (curl_easy_perform(curl) != CURLE_OK) {
1581     ERROR("bind plugin: curl_easy_perform failed: %s", bind_curl_error);
1582     return -1;
1583   }
1584
1585   int status = bind_xml(bind_buffer);
1586   if (status != 0)
1587     return -1;
1588   else
1589     return 0;
1590 } /* }}} int bind_read */
1591
1592 static int bind_shutdown(void) /* {{{ */
1593 {
1594   if (curl != NULL) {
1595     curl_easy_cleanup(curl);
1596     curl = NULL;
1597   }
1598
1599   return 0;
1600 } /* }}} int bind_shutdown */
1601
1602 void module_register(void) {
1603   plugin_register_complex_config("bind", bind_config);
1604   plugin_register_init("bind", bind_init);
1605   plugin_register_read("bind", bind_read);
1606   plugin_register_shutdown("bind", bind_shutdown);
1607 } /* void module_register */