Fix compile time issues
[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 "plugin.h"
47 #include "utils/common/common.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   _Bool qtypes;
77   _Bool resolver_stats;
78   _Bool 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 = true;
108
109 static char *url;
110 static _Bool global_opcodes = 1;
111 static _Bool global_qtypes = 1;
112 static _Bool global_server_stats = 1;
113 static _Bool global_zone_maint_stats = 1;
114 static _Bool global_resolver_stats;
115 static _Bool global_memory_stats = 1;
116 static int timeout = -1;
117
118 static cb_view_t *views;
119 static size_t views_num;
120
121 static CURL *curl;
122
123 static char *bind_buffer;
124 static size_t bind_buffer_size;
125 static size_t bind_buffer_fill;
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     xmlFree(str_ptr);
347     return -1;
348   }
349
350   xmlFree(str_ptr);
351   *ret_value = value.derive;
352   return 0;
353 } /* }}} int bind_xml_read_derive */
354
355 static int bind_xml_read_gauge(xmlDoc *doc, xmlNode *node, /* {{{ */
356                                gauge_t *ret_value) {
357   char *str_ptr = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
358   if (str_ptr == NULL) {
359     ERROR("bind plugin: bind_xml_read_gauge: xmlNodeListGetString failed.");
360     return -1;
361   }
362
363   char *end_ptr;
364   errno = 0;
365   double value = strtod(str_ptr, &end_ptr);
366   xmlFree(str_ptr);
367   if (str_ptr == end_ptr || errno) {
368     if (errno && (value < 0))
369       ERROR("bind plugin: bind_xml_read_gauge: strtod failed with underflow.");
370     else if (errno && (value > 0))
371       ERROR("bind plugin: bind_xml_read_gauge: strtod failed with overflow.");
372     else
373       ERROR("bind plugin: bind_xml_read_gauge: strtod failed.");
374     return -1;
375   }
376
377   *ret_value = (gauge_t)value;
378   return 0;
379 } /* }}} int bind_xml_read_gauge */
380
381 static int bind_xml_read_timestamp(const char *xpath_expression, /* {{{ */
382                                    xmlDoc *doc, xmlXPathContext *xpathCtx,
383                                    time_t *ret_value) {
384   xmlXPathObject *xpathObj =
385       xmlXPathEvalExpression(BAD_CAST xpath_expression, xpathCtx);
386   if (xpathObj == NULL) {
387     ERROR("bind plugin: Unable to evaluate XPath expression `%s'.",
388           xpath_expression);
389     return -1;
390   }
391
392   if ((xpathObj->nodesetval == NULL) || (xpathObj->nodesetval->nodeNr < 1)) {
393     xmlXPathFreeObject(xpathObj);
394     return -1;
395   }
396
397   if (xpathObj->nodesetval->nodeNr != 1) {
398     NOTICE("bind plugin: Evaluating the XPath expression `%s' returned "
399            "%i nodes. Only handling the first one.",
400            xpath_expression, xpathObj->nodesetval->nodeNr);
401   }
402
403   xmlNode *node = xpathObj->nodesetval->nodeTab[0];
404
405   if (node->xmlChildrenNode == NULL) {
406     ERROR("bind plugin: bind_xml_read_timestamp: "
407           "node->xmlChildrenNode == NULL");
408     xmlXPathFreeObject(xpathObj);
409     return -1;
410   }
411
412   char *str_ptr = (char *)xmlNodeListGetString(doc, node->xmlChildrenNode, 1);
413   if (str_ptr == NULL) {
414     ERROR("bind plugin: bind_xml_read_timestamp: xmlNodeListGetString failed.");
415     xmlXPathFreeObject(xpathObj);
416     return -1;
417   }
418
419   struct tm tm = {0};
420   char *tmp = strptime(str_ptr, "%Y-%m-%dT%T", &tm);
421   xmlFree(str_ptr);
422   if (tmp == NULL) {
423     ERROR("bind plugin: bind_xml_read_timestamp: strptime failed.");
424     xmlXPathFreeObject(xpathObj);
425     return -1;
426   }
427
428 #if HAVE_TIMEGM
429   time_t t = timegm(&tm);
430   if (t == ((time_t)-1)) {
431     ERROR("bind plugin: timegm() failed: %s", STRERRNO);
432     return -1;
433   }
434   *ret_value = t;
435 #else
436   time_t t = mktime(&tm);
437   if (t == ((time_t)-1)) {
438     ERROR("bind plugin: mktime() failed: %s", STRERRNO);
439     return -1;
440   }
441   /* mktime assumes that tm is local time. Luckily, it also sets timezone to
442    * the offset used for the conversion, and we undo the conversion to convert
443    * back to UTC. */
444   *ret_value = t - timezone;
445 #endif
446
447   xmlXPathFreeObject(xpathObj);
448   return 0;
449 } /* }}} int bind_xml_read_timestamp */
450
451 /*
452  * bind_parse_generic_name_value
453  *
454  * Reads statistics in the form:
455  * <foo>
456  *   <name>QUERY</name>
457  *   <counter>123</counter>
458  * </foo>
459  */
460 static int bind_parse_generic_name_value(const char *xpath_expression, /* {{{ */
461                                          list_callback_t list_callback,
462                                          void *user_data, xmlDoc *doc,
463                                          xmlXPathContext *xpathCtx,
464                                          time_t current_time, int ds_type) {
465   xmlXPathObject *xpathObj =
466       xmlXPathEvalExpression(BAD_CAST xpath_expression, xpathCtx);
467   if (xpathObj == NULL) {
468     ERROR("bind plugin: Unable to evaluate XPath expression `%s'.",
469           xpath_expression);
470     return -1;
471   }
472
473   int num_entries = 0;
474   /* Iterate over all matching nodes. */
475   for (int i = 0; xpathObj->nodesetval && (i < xpathObj->nodesetval->nodeNr);
476        i++) {
477
478     xmlNode *name_node = NULL;
479     xmlNode *counter = NULL;
480
481     xmlNode *parent = xpathObj->nodesetval->nodeTab[i];
482     DEBUG("bind plugin: bind_parse_generic_name_value: parent->name = %s;",
483           (char *)parent->name);
484
485     /* Iterate over all child nodes. */
486     for (xmlNode *child = parent->xmlChildrenNode; child != NULL;
487          child = child->next) {
488       if (child->type != XML_ELEMENT_NODE)
489         continue;
490
491       if (xmlStrcmp(BAD_CAST "name", child->name) == 0)
492         name_node = child;
493       else if (xmlStrcmp(BAD_CAST "counter", child->name) == 0)
494         counter = child;
495     }
496
497     if ((name_node != NULL) && (counter != NULL)) {
498       char *name =
499           (char *)xmlNodeListGetString(doc, name_node->xmlChildrenNode, 1);
500       value_t value;
501       int status;
502
503       if (ds_type == DS_TYPE_GAUGE)
504         status = bind_xml_read_gauge(doc, counter, &value.gauge);
505       else
506         status = bind_xml_read_derive(doc, counter, &value.derive);
507       if (status != 0) {
508         xmlFree(name);
509         continue;
510       }
511
512       status = (*list_callback)(name, value, current_time, user_data);
513       if (status == 0)
514         num_entries++;
515
516       xmlFree(name);
517     }
518   }
519
520   DEBUG("bind plugin: Found %d %s for XPath expression `%s'", num_entries,
521         (num_entries == 1) ? "entry" : "entries", xpath_expression);
522
523   xmlXPathFreeObject(xpathObj);
524
525   return 0;
526 } /* }}} int bind_parse_generic_name_value */
527
528 /*
529  * bind_parse_generic_value_list
530  *
531  * Reads statistics in the form:
532  * <foo>
533  *   <name0>123</name0>
534  *   <name1>234</name1>
535  *   <name2>345</name2>
536  *   :
537  * </foo>
538  */
539 static int bind_parse_generic_value_list(const char *xpath_expression, /* {{{ */
540                                          list_callback_t list_callback,
541                                          void *user_data, xmlDoc *doc,
542                                          xmlXPathContext *xpathCtx,
543                                          time_t current_time, int ds_type) {
544   xmlXPathObject *xpathObj =
545       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 =
605       xmlXPathEvalExpression(BAD_CAST xpath_expression, xpathCtx);
606   if (xpathObj == NULL) {
607     ERROR("bind plugin: Unable to evaluate XPath expression `%s'.",
608           xpath_expression);
609     return -1;
610   }
611
612   int num_entries = 0;
613   /* Iterate over all matching nodes. */
614   for (int i = 0; xpathObj->nodesetval && (i < xpathObj->nodesetval->nodeNr);
615        i++) {
616     /* Iterate over all child nodes. */
617     for (xmlNode *child = xpathObj->nodesetval->nodeTab[i]->xmlChildrenNode;
618          child != NULL; child = child->next) {
619       if (child->type != XML_ELEMENT_NODE)
620         continue;
621
622       if (strncmp("counter", (char *)child->name, strlen("counter")) != 0)
623         continue;
624
625       char *attr_name = (char *)xmlGetProp(child, BAD_CAST "name");
626       if (attr_name == NULL) {
627         DEBUG("bind plugin: found <counter> without name.");
628         continue;
629       }
630
631       value_t value;
632       int status;
633
634       if (ds_type == DS_TYPE_GAUGE)
635         status = bind_xml_read_gauge(doc, child, &value.gauge);
636       else
637         status = bind_xml_read_derive(doc, child, &value.derive);
638       if (status != 0) {
639         xmlFree(attr_name);
640         continue;
641       }
642
643       status = (*list_callback)(attr_name, value, current_time, user_data);
644       if (status == 0)
645         num_entries++;
646
647       xmlFree(attr_name);
648     }
649   }
650
651   DEBUG("bind plugin: Found %d %s for XPath expression `%s'", num_entries,
652         (num_entries == 1) ? "entry" : "entries", xpath_expression);
653
654   xmlXPathFreeObject(xpathObj);
655
656   return 0;
657 } /* }}} int bind_parse_generic_name_attr_value_list */
658
659 static int bind_xml_stats_handle_zone(int version, xmlDoc *doc, /* {{{ */
660                                       xmlXPathContext *path_ctx, xmlNode *node,
661                                       cb_view_t *view, time_t current_time) {
662   char *zone_name = NULL;
663
664   if (version >= 3) {
665     char *n = (char *)xmlGetProp(node, BAD_CAST "name");
666     char *c = (char *)xmlGetProp(node, BAD_CAST "rdataclass");
667     if (n && c) {
668       zone_name = (char *)xmlMalloc(strlen(n) + strlen(c) + 2);
669       snprintf(zone_name, strlen(n) + strlen(c) + 2, "%s/%s", n, c);
670     }
671     xmlFree(n);
672     xmlFree(c);
673   } else {
674     xmlXPathObject *path_obj =
675         xmlXPathEvalExpression(BAD_CAST "name", path_ctx);
676     if (path_obj == NULL) {
677       ERROR("bind plugin: xmlXPathEvalExpression failed.");
678       return -1;
679     }
680
681     for (int i = 0; path_obj->nodesetval && (i < path_obj->nodesetval->nodeNr);
682          i++) {
683       zone_name = (char *)xmlNodeListGetString(
684           doc, path_obj->nodesetval->nodeTab[i]->xmlChildrenNode, 1);
685       if (zone_name != NULL)
686         break;
687     }
688     xmlXPathFreeObject(path_obj);
689   }
690
691   if (zone_name == NULL) {
692     ERROR("bind plugin: Could not determine zone name.");
693     return -1;
694   }
695
696   size_t j;
697   for (j = 0; j < view->zones_num; j++) {
698     if (strcasecmp(zone_name, view->zones[j]) == 0)
699       break;
700   }
701
702   xmlFree(zone_name);
703
704   if (j >= view->zones_num)
705     return 0;
706
707   zone_name = view->zones[j];
708
709   DEBUG("bind plugin: bind_xml_stats_handle_zone: Found zone `%s'.", zone_name);
710
711   { /* Parse the <counters> tag {{{ */
712     char plugin_instance[DATA_MAX_NAME_LEN];
713     translation_table_ptr_t table_ptr = {nsstats_translation_table,
714                                          nsstats_translation_table_length,
715                                          plugin_instance};
716
717     snprintf(plugin_instance, sizeof(plugin_instance), "%s-zone-%s", view->name,
718              zone_name);
719
720     if (version == 3) {
721       list_info_ptr_t list_info = {plugin_instance,
722                                    /* type = */ "dns_qtype"};
723       bind_parse_generic_name_attr_value_list(
724           /* xpath = */ "counters[@type='rcode']",
725           /* callback = */ bind_xml_table_callback,
726           /* user_data = */ &table_ptr, doc, path_ctx, current_time,
727           DS_TYPE_COUNTER);
728       bind_parse_generic_name_attr_value_list(
729           /* xpath = */ "counters[@type='qtype']",
730           /* callback = */ bind_xml_list_callback,
731           /* user_data = */ &list_info, doc, path_ctx, current_time,
732           DS_TYPE_COUNTER);
733     } else {
734       bind_parse_generic_value_list(/* xpath = */ "counters",
735                                     /* callback = */ bind_xml_table_callback,
736                                     /* user_data = */ &table_ptr, doc, path_ctx,
737                                     current_time, DS_TYPE_COUNTER);
738     }
739   } /* }}} */
740
741   return 0;
742 } /* }}} int bind_xml_stats_handle_zone */
743
744 static int bind_xml_stats_search_zones(int version, xmlDoc *doc, /* {{{ */
745                                        xmlXPathContext *path_ctx, xmlNode *node,
746                                        cb_view_t *view, time_t current_time) {
747   xmlXPathContext *zone_path_context = xmlXPathNewContext(doc);
748   if (zone_path_context == NULL) {
749     ERROR("bind plugin: xmlXPathNewContext failed.");
750     return -1;
751   }
752
753   xmlXPathObject *zone_nodes =
754       xmlXPathEvalExpression(BAD_CAST "zones/zone", path_ctx);
755   if (zone_nodes == NULL) {
756     ERROR("bind plugin: Cannot find any <view> tags.");
757     xmlXPathFreeContext(zone_path_context);
758     return -1;
759   }
760
761   for (int i = 0; i < zone_nodes->nodesetval->nodeNr; i++) {
762     node = zone_nodes->nodesetval->nodeTab[i];
763     assert(node != NULL);
764
765     zone_path_context->node = node;
766
767     bind_xml_stats_handle_zone(version, doc, zone_path_context, node, view,
768                                current_time);
769   }
770
771   xmlXPathFreeObject(zone_nodes);
772   xmlXPathFreeContext(zone_path_context);
773   return 0;
774 } /* }}} int bind_xml_stats_search_zones */
775
776 static int bind_xml_stats_handle_view(int version, xmlDoc *doc, /* {{{ */
777                                       xmlXPathContext *path_ctx, xmlNode *node,
778                                       time_t current_time) {
779   char *view_name = NULL;
780   cb_view_t *view;
781   size_t j;
782
783   if (version == 3) {
784     view_name = (char *)xmlGetProp(node, BAD_CAST "name");
785
786     if (view_name == NULL) {
787       ERROR("bind plugin: Could not determine view name.");
788       return -1;
789     }
790
791     for (j = 0; j < views_num; j++) {
792       if (strcasecmp(view_name, views[j].name) == 0)
793         break;
794     }
795
796     xmlFree(view_name);
797     view_name = NULL;
798   } else {
799     xmlXPathObject *path_obj =
800         xmlXPathEvalExpression(BAD_CAST "name", path_ctx);
801     if (path_obj == NULL) {
802       ERROR("bind plugin: xmlXPathEvalExpression failed.");
803       return -1;
804     }
805
806     for (int i = 0; path_obj->nodesetval && (i < path_obj->nodesetval->nodeNr);
807          i++) {
808       view_name = (char *)xmlNodeListGetString(
809           doc, path_obj->nodesetval->nodeTab[i]->xmlChildrenNode, 1);
810       if (view_name != NULL)
811         break;
812     }
813
814     if (view_name == NULL) {
815       ERROR("bind plugin: Could not determine view name.");
816       xmlXPathFreeObject(path_obj);
817       return -1;
818     }
819
820     for (j = 0; j < views_num; j++) {
821       if (strcasecmp(view_name, views[j].name) == 0)
822         break;
823     }
824
825     xmlFree(view_name);
826     xmlXPathFreeObject(path_obj);
827
828     view_name = NULL;
829     path_obj = NULL;
830   }
831
832   if (j >= views_num)
833     return 0;
834
835   view = views + j;
836
837   DEBUG("bind plugin: bind_xml_stats_handle_view: Found view `%s'.",
838         view->name);
839
840   if (view->qtypes != 0) /* {{{ */
841   {
842     char plugin_instance[DATA_MAX_NAME_LEN];
843     list_info_ptr_t list_info = {plugin_instance,
844                                  /* type = */ "dns_qtype"};
845
846     snprintf(plugin_instance, sizeof(plugin_instance), "%s-qtypes", view->name);
847     if (version == 3) {
848       bind_parse_generic_name_attr_value_list(
849           /* xpath = */ "counters[@type='resqtype']",
850           /* callback = */ bind_xml_list_callback,
851           /* user_data = */ &list_info, doc, path_ctx, current_time,
852           DS_TYPE_COUNTER);
853     } else {
854       bind_parse_generic_name_value(/* xpath = */ "rdtype",
855                                     /* callback = */ bind_xml_list_callback,
856                                     /* user_data = */ &list_info, doc, path_ctx,
857                                     current_time, DS_TYPE_COUNTER);
858     }
859   } /* }}} */
860
861   if (view->resolver_stats != 0) /* {{{ */
862   {
863     char plugin_instance[DATA_MAX_NAME_LEN];
864     translation_table_ptr_t table_ptr = {resstats_translation_table,
865                                          resstats_translation_table_length,
866                                          plugin_instance};
867
868     snprintf(plugin_instance, sizeof(plugin_instance), "%s-resolver_stats",
869              view->name);
870     if (version == 3) {
871       bind_parse_generic_name_attr_value_list(
872           "counters[@type='resstats']",
873           /* callback = */ bind_xml_table_callback,
874           /* user_data = */ &table_ptr, doc, path_ctx, current_time,
875           DS_TYPE_COUNTER);
876     } else {
877       bind_parse_generic_name_value("resstat",
878                                     /* callback = */ bind_xml_table_callback,
879                                     /* user_data = */ &table_ptr, doc, path_ctx,
880                                     current_time, DS_TYPE_COUNTER);
881     }
882   } /* }}} */
883
884   /* Record types in the cache */
885   if (view->cacherrsets != 0) /* {{{ */
886   {
887     char plugin_instance[DATA_MAX_NAME_LEN];
888     list_info_ptr_t list_info = {plugin_instance,
889                                  /* type = */ "dns_qtype_cached"};
890
891     snprintf(plugin_instance, sizeof(plugin_instance), "%s-cache_rr_sets",
892              view->name);
893
894     bind_parse_generic_name_value(/* xpath = */ "cache/rrset",
895                                   /* callback = */ bind_xml_list_callback,
896                                   /* user_data = */ &list_info, doc, path_ctx,
897                                   current_time, DS_TYPE_GAUGE);
898   } /* }}} */
899
900   if (view->zones_num > 0)
901     bind_xml_stats_search_zones(version, doc, path_ctx, node, view,
902                                 current_time);
903
904   return 0;
905 } /* }}} int bind_xml_stats_handle_view */
906
907 static int bind_xml_stats_search_views(int version, xmlDoc *doc, /* {{{ */
908                                        xmlXPathContext *xpathCtx,
909                                        time_t current_time) {
910   xmlXPathContext *view_path_context = xmlXPathNewContext(doc);
911   if (view_path_context == NULL) {
912     ERROR("bind plugin: xmlXPathNewContext failed.");
913     return -1;
914   }
915
916   xmlXPathObject *view_nodes =
917       xmlXPathEvalExpression(BAD_CAST "views/view", xpathCtx);
918   if (view_nodes == NULL) {
919     ERROR("bind plugin: Cannot find any <view> tags.");
920     xmlXPathFreeContext(view_path_context);
921     return -1;
922   }
923
924   for (int i = 0; i < view_nodes->nodesetval->nodeNr; i++) {
925     xmlNode *node = view_nodes->nodesetval->nodeTab[i];
926     assert(node != NULL);
927
928     view_path_context->node = node;
929
930     bind_xml_stats_handle_view(version, doc, view_path_context, node,
931                                current_time);
932   }
933
934   xmlXPathFreeObject(view_nodes);
935   xmlXPathFreeContext(view_path_context);
936   return 0;
937 } /* }}} int bind_xml_stats_search_views */
938
939 static void bind_xml_stats_v3(xmlDoc *doc, /* {{{ */
940                               xmlXPathContext *xpathCtx, time_t current_time) {
941   /* XPath:     server/counters[@type='opcode']
942    * Variables: QUERY, IQUERY, NOTIFY, UPDATE, ...
943    * Layout v3:
944    *   <counters type="opcode">
945    *     <counter name="A">1</counter>
946    *     :
947    *   </counters>
948    */
949   if (global_opcodes != 0) {
950     list_info_ptr_t list_info = {/* plugin instance = */ "global-opcodes",
951                                  /* type = */ "dns_opcode"};
952     bind_parse_generic_name_attr_value_list(
953         /* xpath = */ "server/counters[@type='opcode']",
954         /* callback = */ bind_xml_list_callback,
955         /* user_data = */ &list_info, doc, xpathCtx, current_time,
956         DS_TYPE_COUNTER);
957   }
958
959   /* XPath:     server/counters[@type='qtype']
960    * Variables: RESERVED0, A, NS, CNAME, SOA, MR, PTR, HINFO, MX, TXT, RP,
961    *            X25, PX, AAAA, LOC, SRV, NAPTR, A6, DS, RRSIG, NSEC, DNSKEY,
962    *            SPF, TKEY, IXFR, AXFR, ANY, ..., Others
963    * Layout v3:
964    *   <counters type="opcode">
965    *     <counter name="A">1</counter>
966    *     :
967    *   </counters>
968    */
969   if (global_qtypes != 0) {
970     list_info_ptr_t list_info = {/* plugin instance = */ "global-qtypes",
971                                  /* type = */ "dns_qtype"};
972
973     bind_parse_generic_name_attr_value_list(
974         /* xpath = */ "server/counters[@type='qtype']",
975         /* callback = */ bind_xml_list_callback,
976         /* user_data = */ &list_info, doc, xpathCtx, current_time,
977         DS_TYPE_COUNTER);
978   }
979
980   /* XPath:     server/counters[@type='nsstat']
981    * Variables: Requestv4, Requestv6, ReqEdns0, ReqBadEDNSVer, ReqTSIG,
982    *            ReqSIG0, ReqBadSIG, ReqTCP, AuthQryRej, RecQryRej, XfrRej,
983    *            UpdateRej, Response, TruncatedResp, RespEDNS0, RespTSIG,
984    *            RespSIG0, QrySuccess, QryAuthAns, QryNoauthAns, QryReferral,
985    *            QryNxrrset, QrySERVFAIL, QryFORMERR, QryNXDOMAIN, QryRecursion,
986    *            QryDuplicate, QryDropped, QryFailure, XfrReqDone, UpdateReqFwd,
987    *            UpdateRespFwd, UpdateFwdFail, UpdateDone, UpdateFail,
988    *            UpdateBadPrereq
989    * Layout v3:
990    *   <counters type="nsstat"
991    *     <counter name="Requestv4">1</counter>
992    *     <counter name="Requestv6">0</counter>
993    *     :
994    *   </counter>
995    */
996   if (global_server_stats) {
997     translation_table_ptr_t table_ptr = {
998         nsstats_translation_table, nsstats_translation_table_length,
999         /* plugin_instance = */ "global-server_stats"};
1000
1001     bind_parse_generic_name_attr_value_list(
1002         "server/counters[@type='nsstat']",
1003         /* callback = */ bind_xml_table_callback,
1004         /* user_data = */ &table_ptr, doc, xpathCtx, current_time,
1005         DS_TYPE_COUNTER);
1006   }
1007
1008   /* XPath:     server/zonestats, server/zonestat,
1009    * server/counters[@type='zonestat']
1010    * Variables: NotifyOutv4, NotifyOutv6, NotifyInv4, NotifyInv6, NotifyRej,
1011    *            SOAOutv4, SOAOutv6, AXFRReqv4, AXFRReqv6, IXFRReqv4, IXFRReqv6,
1012    *            XfrSuccess, XfrFail
1013    * Layout v3:
1014    *   <counters type="zonestat"
1015    *     <counter name="NotifyOutv4">0</counter>
1016    *     <counter name="NotifyOutv6">0</counter>
1017    *     :
1018    *   </counter>
1019    */
1020   if (global_zone_maint_stats) {
1021     translation_table_ptr_t table_ptr = {
1022         zonestats_translation_table, zonestats_translation_table_length,
1023         /* plugin_instance = */ "global-zone_maint_stats"};
1024
1025     bind_parse_generic_name_attr_value_list(
1026         "server/counters[@type='zonestat']",
1027         /* callback = */ bind_xml_table_callback,
1028         /* user_data = */ &table_ptr, doc, xpathCtx, current_time,
1029         DS_TYPE_COUNTER);
1030   }
1031
1032   /* XPath:     server/resstats, server/counters[@type='resstat']
1033    * Variables: Queryv4, Queryv6, Responsev4, Responsev6, NXDOMAIN, SERVFAIL,
1034    *            FORMERR, OtherError, EDNS0Fail, Mismatch, Truncated, Lame,
1035    *            Retry, GlueFetchv4, GlueFetchv6, GlueFetchv4Fail,
1036    *            GlueFetchv6Fail, ValAttempt, ValOk, ValNegOk, ValFail
1037    * Layout v3:
1038    *   <counters type="resstat"
1039    *     <counter name="Queryv4">0</counter>
1040    *     <counter name="Queryv6">0</counter>
1041    *     :
1042    *   </counter>
1043    */
1044   if (global_resolver_stats != 0) {
1045     translation_table_ptr_t table_ptr = {
1046         resstats_translation_table, resstats_translation_table_length,
1047         /* plugin_instance = */ "global-resolver_stats"};
1048
1049     bind_parse_generic_name_attr_value_list(
1050         "server/counters[@type='resstat']",
1051         /* callback = */ bind_xml_table_callback,
1052         /* user_data = */ &table_ptr, doc, xpathCtx, current_time,
1053         DS_TYPE_COUNTER);
1054   }
1055 } /* }}} bind_xml_stats_v3 */
1056
1057 static void bind_xml_stats_v1_v2(int version, xmlDoc *doc, /* {{{ */
1058                                  xmlXPathContext *xpathCtx,
1059                                  time_t current_time) {
1060   /* XPath:     server/requests/opcode, server/counters[@type='opcode']
1061    * Variables: QUERY, IQUERY, NOTIFY, UPDATE, ...
1062    * Layout V1 and V2:
1063    *   <opcode>
1064    *     <name>A</name>
1065    *     <counter>1</counter>
1066    *   </opcode>
1067    *   :
1068    */
1069   if (global_opcodes != 0) {
1070     list_info_ptr_t list_info = {/* plugin instance = */ "global-opcodes",
1071                                  /* type = */ "dns_opcode"};
1072
1073     bind_parse_generic_name_value(/* xpath = */ "server/requests/opcode",
1074                                   /* callback = */ bind_xml_list_callback,
1075                                   /* user_data = */ &list_info, doc, xpathCtx,
1076                                   current_time, DS_TYPE_COUNTER);
1077   }
1078
1079   /* XPath:     server/queries-in/rdtype, server/counters[@type='qtype']
1080    * Variables: RESERVED0, A, NS, CNAME, SOA, MR, PTR, HINFO, MX, TXT, RP,
1081    *            X25, PX, AAAA, LOC, SRV, NAPTR, A6, DS, RRSIG, NSEC, DNSKEY,
1082    *            SPF, TKEY, IXFR, AXFR, ANY, ..., Others
1083    * Layout v1 or v2:
1084    *   <rdtype>
1085    *     <name>A</name>
1086    *     <counter>1</counter>
1087    *   </rdtype>
1088    *   :
1089    */
1090   if (global_qtypes != 0) {
1091     list_info_ptr_t list_info = {/* plugin instance = */ "global-qtypes",
1092                                  /* type = */ "dns_qtype"};
1093
1094     bind_parse_generic_name_value(/* xpath = */ "server/queries-in/rdtype",
1095                                   /* callback = */ bind_xml_list_callback,
1096                                   /* user_data = */ &list_info, doc, xpathCtx,
1097                                   current_time, DS_TYPE_COUNTER);
1098   }
1099
1100   /* XPath:     server/nsstats, server/nsstat, server/counters[@type='nsstat']
1101    * Variables: Requestv4, Requestv6, ReqEdns0, ReqBadEDNSVer, ReqTSIG,
1102    *            ReqSIG0, ReqBadSIG, ReqTCP, AuthQryRej, RecQryRej, XfrRej,
1103    *            UpdateRej, Response, TruncatedResp, RespEDNS0, RespTSIG,
1104    *            RespSIG0, QrySuccess, QryAuthAns, QryNoauthAns, QryReferral,
1105    *            QryNxrrset, QrySERVFAIL, QryFORMERR, QryNXDOMAIN, QryRecursion,
1106    *            QryDuplicate, QryDropped, QryFailure, XfrReqDone, UpdateReqFwd,
1107    *            UpdateRespFwd, UpdateFwdFail, UpdateDone, UpdateFail,
1108    *            UpdateBadPrereq
1109    * Layout v1:
1110    *   <nsstats>
1111    *     <Requestv4>1</Requestv4>
1112    *     <Requestv6>0</Requestv6>
1113    *     :
1114    *   </nsstats>
1115    * Layout v2:
1116    *   <nsstat>
1117    *     <name>Requestv4</name>
1118    *     <counter>1</counter>
1119    *   </nsstat>
1120    *   <nsstat>
1121    *     <name>Requestv6</name>
1122    *     <counter>0</counter>
1123    *   </nsstat>
1124    *   :
1125    */
1126   if (global_server_stats) {
1127     translation_table_ptr_t table_ptr = {
1128         nsstats_translation_table, nsstats_translation_table_length,
1129         /* plugin_instance = */ "global-server_stats"};
1130
1131     if (version == 1) {
1132       bind_parse_generic_value_list("server/nsstats",
1133                                     /* callback = */ bind_xml_table_callback,
1134                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1135                                     current_time, DS_TYPE_COUNTER);
1136     } else {
1137       bind_parse_generic_name_value("server/nsstat",
1138                                     /* callback = */ bind_xml_table_callback,
1139                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1140                                     current_time, DS_TYPE_COUNTER);
1141     }
1142   }
1143
1144   /* XPath:     server/zonestats, server/zonestat,
1145    * server/counters[@type='zonestat']
1146    * Variables: NotifyOutv4, NotifyOutv6, NotifyInv4, NotifyInv6, NotifyRej,
1147    *            SOAOutv4, SOAOutv6, AXFRReqv4, AXFRReqv6, IXFRReqv4, IXFRReqv6,
1148    *            XfrSuccess, XfrFail
1149    * Layout v1:
1150    *   <zonestats>
1151    *     <NotifyOutv4>0</NotifyOutv4>
1152    *     <NotifyOutv6>0</NotifyOutv6>
1153    *     :
1154    *   </zonestats>
1155    * Layout v2:
1156    *   <zonestat>
1157    *     <name>NotifyOutv4</name>
1158    *     <counter>0</counter>
1159    *   </zonestat>
1160    *   <zonestat>
1161    *     <name>NotifyOutv6</name>
1162    *     <counter>0</counter>
1163    *   </zonestat>
1164    *   :
1165    */
1166   if (global_zone_maint_stats) {
1167     translation_table_ptr_t table_ptr = {
1168         zonestats_translation_table, zonestats_translation_table_length,
1169         /* plugin_instance = */ "global-zone_maint_stats"};
1170
1171     if (version == 1) {
1172       bind_parse_generic_value_list("server/zonestats",
1173                                     /* callback = */ bind_xml_table_callback,
1174                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1175                                     current_time, DS_TYPE_COUNTER);
1176     } else {
1177       bind_parse_generic_name_value("server/zonestat",
1178                                     /* callback = */ bind_xml_table_callback,
1179                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1180                                     current_time, DS_TYPE_COUNTER);
1181     }
1182   }
1183
1184   /* XPath:     server/resstats, server/counters[@type='resstat']
1185    * Variables: Queryv4, Queryv6, Responsev4, Responsev6, NXDOMAIN, SERVFAIL,
1186    *            FORMERR, OtherError, EDNS0Fail, Mismatch, Truncated, Lame,
1187    *            Retry, GlueFetchv4, GlueFetchv6, GlueFetchv4Fail,
1188    *            GlueFetchv6Fail, ValAttempt, ValOk, ValNegOk, ValFail
1189    * Layout v1:
1190    *   <resstats>
1191    *     <Queryv4>0</Queryv4>
1192    *     <Queryv6>0</Queryv6>
1193    *     :
1194    *   </resstats>
1195    * Layout v2:
1196    *   <resstat>
1197    *     <name>Queryv4</name>
1198    *     <counter>0</counter>
1199    *   </resstat>
1200    *   <resstat>
1201    *     <name>Queryv6</name>
1202    *     <counter>0</counter>
1203    *   </resstat>
1204    *   :
1205    */
1206   if (global_resolver_stats != 0) {
1207     translation_table_ptr_t table_ptr = {
1208         resstats_translation_table, resstats_translation_table_length,
1209         /* plugin_instance = */ "global-resolver_stats"};
1210
1211     if (version == 1) {
1212       bind_parse_generic_value_list("server/resstats",
1213                                     /* callback = */ bind_xml_table_callback,
1214                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1215                                     current_time, DS_TYPE_COUNTER);
1216     } else {
1217       bind_parse_generic_name_value("server/resstat",
1218                                     /* callback = */ bind_xml_table_callback,
1219                                     /* user_data = */ &table_ptr, doc, xpathCtx,
1220                                     current_time, DS_TYPE_COUNTER);
1221     }
1222   }
1223 } /* }}} bind_xml_stats_v1_v2 */
1224
1225 static int bind_xml_stats(int version, xmlDoc *doc, /* {{{ */
1226                           xmlXPathContext *xpathCtx, xmlNode *statsnode) {
1227   time_t current_time = 0;
1228
1229   xpathCtx->node = statsnode;
1230
1231   /* TODO: Check `server/boot-time' to recognize server restarts. */
1232
1233   int status = bind_xml_read_timestamp("server/current-time", doc, xpathCtx,
1234                                        &current_time);
1235   if (status != 0) {
1236     ERROR("bind plugin: Reading `server/current-time' failed.");
1237     return -1;
1238   }
1239   DEBUG("bind plugin: Current server time is %i.", (int)current_time);
1240
1241   if (version == 3) {
1242     bind_xml_stats_v3(doc, xpathCtx, current_time);
1243   } else {
1244     bind_xml_stats_v1_v2(version, doc, xpathCtx, current_time);
1245   }
1246
1247   /* XPath:  memory/summary
1248    * Variables: TotalUse, InUse, BlockSize, ContextSize, Lost
1249    * Layout: v2 and v3:
1250    *   <summary>
1251    *     <TotalUse>6587096</TotalUse>
1252    *     <InUse>1345424</InUse>
1253    *     <BlockSize>5505024</BlockSize>
1254    *     <ContextSize>3732456</ContextSize>
1255    *     <Lost>0</Lost>
1256    *   </summary>
1257    */
1258   if (global_memory_stats != 0) {
1259     translation_table_ptr_t table_ptr = {
1260         memsummary_translation_table, memsummary_translation_table_length,
1261         /* plugin_instance = */ "global-memory_stats"};
1262
1263     bind_parse_generic_value_list("memory/summary",
1264                                   /* callback = */ bind_xml_table_callback,
1265                                   /* user_data = */ &table_ptr, doc, xpathCtx,
1266                                   current_time, DS_TYPE_GAUGE);
1267   }
1268
1269   if (views_num > 0)
1270     bind_xml_stats_search_views(version, doc, xpathCtx, current_time);
1271
1272   return 0;
1273 } /* }}} int bind_xml_stats */
1274
1275 static int bind_xml(const char *data) /* {{{ */
1276 {
1277   int ret = -1;
1278
1279   xmlDoc *doc = xmlParseMemory(data, strlen(data));
1280   if (doc == NULL) {
1281     ERROR("bind plugin: xmlParseMemory failed.");
1282     return -1;
1283   }
1284
1285   xmlXPathContext *xpathCtx = xmlXPathNewContext(doc);
1286   if (xpathCtx == NULL) {
1287     ERROR("bind plugin: xmlXPathNewContext failed.");
1288     xmlFreeDoc(doc);
1289     return -1;
1290   }
1291
1292   //
1293   // version 3.* of statistics XML (since BIND9.9)
1294   //
1295
1296   xmlXPathObject *xpathObj =
1297       xmlXPathEvalExpression(BAD_CAST "/statistics", xpathCtx);
1298   if (xpathObj == NULL || xpathObj->nodesetval == NULL ||
1299       xpathObj->nodesetval->nodeNr == 0) {
1300     DEBUG("bind plugin: Statistics appears not to be v3");
1301     // we will fallback to v1 or v2 detection
1302     if (xpathObj != NULL) {
1303       xmlXPathFreeObject(xpathObj);
1304     }
1305   } else {
1306     for (int i = 0; i < xpathObj->nodesetval->nodeNr; i++) {
1307       xmlNode *node;
1308       char *attr_version;
1309
1310       node = xpathObj->nodesetval->nodeTab[i];
1311       assert(node != NULL);
1312
1313       attr_version = (char *)xmlGetProp(node, BAD_CAST "version");
1314       if (attr_version == NULL) {
1315         NOTICE("bind plugin: Found <statistics> tag doesn't have a "
1316                "`version' attribute.");
1317         continue;
1318       }
1319       DEBUG("bind plugin: Found: <statistics version=\"%s\">", attr_version);
1320
1321       if (strncmp("3.", attr_version, strlen("3.")) != 0) {
1322         /* TODO: Use the complaint mechanism here. */
1323         NOTICE("bind plugin: Found <statistics> tag with version `%s'. "
1324                "Unfortunately I have no clue how to parse that. "
1325                "Please open a bug report for this.",
1326                attr_version);
1327         xmlFree(attr_version);
1328         continue;
1329       }
1330       ret = bind_xml_stats(3, doc, xpathCtx, node);
1331
1332       xmlFree(attr_version);
1333       /* One <statistics> node ought to be enough. */
1334       break;
1335     }
1336
1337     // we are finished, early-return
1338     xmlXPathFreeObject(xpathObj);
1339     xmlXPathFreeContext(xpathCtx);
1340     xmlFreeDoc(doc);
1341
1342     return ret;
1343   }
1344
1345   //
1346   // versions 1.* or 2.* of statistics XML
1347   //
1348
1349   xpathObj = xmlXPathEvalExpression(BAD_CAST "/isc/bind/statistics", xpathCtx);
1350   if (xpathObj == NULL) {
1351     ERROR("bind plugin: Cannot find the <statistics> tag.");
1352     xmlXPathFreeContext(xpathCtx);
1353     xmlFreeDoc(doc);
1354     return -1;
1355   } else if (xpathObj->nodesetval == NULL) {
1356     ERROR("bind plugin: xmlXPathEvalExpression failed.");
1357     xmlXPathFreeObject(xpathObj);
1358     xmlXPathFreeContext(xpathCtx);
1359     xmlFreeDoc(doc);
1360     return -1;
1361   }
1362
1363   for (int i = 0; i < xpathObj->nodesetval->nodeNr; i++) {
1364     xmlNode *node;
1365     char *attr_version;
1366     int parsed_version = 0;
1367
1368     node = xpathObj->nodesetval->nodeTab[i];
1369     assert(node != NULL);
1370
1371     attr_version = (char *)xmlGetProp(node, BAD_CAST "version");
1372     if (attr_version == NULL) {
1373       NOTICE("bind plugin: Found <statistics> tag doesn't have a "
1374              "`version' attribute.");
1375       continue;
1376     }
1377     DEBUG("bind plugin: Found: <statistics version=\"%s\">", attr_version);
1378
1379     /* At the time this plugin was written, version "1.0" was used by
1380      * BIND 9.5.0, version "2.0" was used by BIND 9.5.1 and 9.6.0. We assume
1381      * that "1.*" and "2.*" don't introduce structural changes, so we just
1382      * check for the first two characters here. */
1383     if (strncmp("1.", attr_version, strlen("1.")) == 0)
1384       parsed_version = 1;
1385     else if (strncmp("2.", attr_version, strlen("2.")) == 0)
1386       parsed_version = 2;
1387     else {
1388       /* TODO: Use the complaint mechanism here. */
1389       NOTICE("bind plugin: Found <statistics> tag with version `%s'. "
1390              "Unfortunately I have no clue how to parse that. "
1391              "Please open a bug report for this.",
1392              attr_version);
1393       xmlFree(attr_version);
1394       continue;
1395     }
1396
1397     ret = bind_xml_stats(parsed_version, doc, xpathCtx, node);
1398
1399     xmlFree(attr_version);
1400     /* One <statistics> node ought to be enough. */
1401     break;
1402   }
1403
1404   xmlXPathFreeObject(xpathObj);
1405   xmlXPathFreeContext(xpathCtx);
1406   xmlFreeDoc(doc);
1407
1408   return ret;
1409 } /* }}} int bind_xml */
1410
1411 static int bind_config_add_view_zone(cb_view_t *view, /* {{{ */
1412                                      oconfig_item_t *ci) {
1413   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1414     WARNING("bind plugin: The `Zone' option needs "
1415             "exactly one string argument.");
1416     return -1;
1417   }
1418
1419   char **tmp = realloc(view->zones, sizeof(char *) * (view->zones_num + 1));
1420   if (tmp == NULL) {
1421     ERROR("bind plugin: realloc failed.");
1422     return -1;
1423   }
1424   view->zones = tmp;
1425
1426   view->zones[view->zones_num] = strdup(ci->values[0].value.string);
1427   if (view->zones[view->zones_num] == NULL) {
1428     ERROR("bind plugin: strdup failed.");
1429     return -1;
1430   }
1431   view->zones_num++;
1432
1433   return 0;
1434 } /* }}} int bind_config_add_view_zone */
1435
1436 static int bind_config_add_view(oconfig_item_t *ci) /* {{{ */
1437 {
1438   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) {
1439     WARNING("bind plugin: `View' blocks need exactly one string argument.");
1440     return -1;
1441   }
1442
1443   cb_view_t *tmp = realloc(views, sizeof(*views) * (views_num + 1));
1444   if (tmp == NULL) {
1445     ERROR("bind plugin: realloc failed.");
1446     return -1;
1447   }
1448   views = tmp;
1449   tmp = views + views_num;
1450
1451   memset(tmp, 0, sizeof(*tmp));
1452   tmp->qtypes = 1;
1453   tmp->resolver_stats = 1;
1454   tmp->cacherrsets = 1;
1455   tmp->zones = NULL;
1456   tmp->zones_num = 0;
1457
1458   tmp->name = strdup(ci->values[0].value.string);
1459   if (tmp->name == NULL) {
1460     ERROR("bind plugin: strdup failed.");
1461     sfree(views);
1462     return -1;
1463   }
1464
1465   for (int i = 0; i < ci->children_num; i++) {
1466     oconfig_item_t *child = ci->children + i;
1467
1468     if (strcasecmp("QTypes", child->key) == 0)
1469       cf_util_get_boolean(child, &tmp->qtypes);
1470     else if (strcasecmp("ResolverStats", child->key) == 0)
1471       cf_util_get_boolean(child, &tmp->resolver_stats);
1472     else if (strcasecmp("CacheRRSets", child->key) == 0)
1473       cf_util_get_boolean(child, &tmp->cacherrsets);
1474     else if (strcasecmp("Zone", child->key) == 0)
1475       bind_config_add_view_zone(tmp, child);
1476     else {
1477       WARNING("bind plugin: Unknown configuration option "
1478               "`%s' in view `%s' will be ignored.",
1479               child->key, tmp->name);
1480     }
1481   } /* for (i = 0; i < ci->children_num; i++) */
1482
1483   views_num++;
1484   return 0;
1485 } /* }}} int bind_config_add_view */
1486
1487 static int bind_config(oconfig_item_t *ci) /* {{{ */
1488 {
1489   for (int i = 0; i < ci->children_num; i++) {
1490     oconfig_item_t *child = ci->children + i;
1491
1492     if (strcasecmp("Url", child->key) == 0) {
1493       cf_util_get_string(child, &url);
1494     } else if (strcasecmp("OpCodes", child->key) == 0)
1495       cf_util_get_boolean(child, &global_opcodes);
1496     else if (strcasecmp("QTypes", child->key) == 0)
1497       cf_util_get_boolean(child, &global_qtypes);
1498     else if (strcasecmp("ServerStats", child->key) == 0)
1499       cf_util_get_boolean(child, &global_server_stats);
1500     else if (strcasecmp("ZoneMaintStats", child->key) == 0)
1501       cf_util_get_boolean(child, &global_zone_maint_stats);
1502     else if (strcasecmp("ResolverStats", child->key) == 0)
1503       cf_util_get_boolean(child, &global_resolver_stats);
1504     else if (strcasecmp("MemoryStats", child->key) == 0)
1505       cf_util_get_boolean(child, &global_memory_stats);
1506     else if (strcasecmp("View", child->key) == 0)
1507       bind_config_add_view(child);
1508     else if (strcasecmp("ParseTime", child->key) == 0)
1509       cf_util_get_boolean(child, &config_parse_time);
1510     else if (strcasecmp("Timeout", child->key) == 0)
1511       cf_util_get_int(child, &timeout);
1512     else {
1513       WARNING("bind plugin: Unknown configuration option "
1514               "`%s' will be ignored.",
1515               child->key);
1516     }
1517   }
1518
1519   return 0;
1520 } /* }}} int bind_config */
1521
1522 static int bind_init(void) /* {{{ */
1523 {
1524   if (curl != NULL)
1525     return 0;
1526
1527   curl = curl_easy_init();
1528   if (curl == NULL) {
1529     ERROR("bind plugin: bind_init: curl_easy_init failed.");
1530     return -1;
1531   }
1532
1533   curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
1534   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, bind_curl_callback);
1535   curl_easy_setopt(curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
1536   curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, bind_curl_error);
1537   curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
1538   curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
1539 #ifdef HAVE_CURLOPT_TIMEOUT_MS
1540   curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS,
1541                    (timeout >= 0)
1542                        ? (long)timeout
1543                        : (long)CDTIME_T_TO_MS(plugin_get_interval()));
1544 #endif
1545
1546   return 0;
1547 } /* }}} int bind_init */
1548
1549 static int bind_read(void) /* {{{ */
1550 {
1551   if (curl == NULL) {
1552     ERROR("bind plugin: I don't have a CURL object.");
1553     return -1;
1554   }
1555
1556   bind_buffer_fill = 0;
1557
1558   curl_easy_setopt(curl, CURLOPT_URL, (url != NULL) ? url : BIND_DEFAULT_URL);
1559
1560   if (curl_easy_perform(curl) != CURLE_OK) {
1561     ERROR("bind plugin: curl_easy_perform failed: %s", bind_curl_error);
1562     return -1;
1563   }
1564
1565   int status = bind_xml(bind_buffer);
1566   if (status != 0)
1567     return -1;
1568   else
1569     return 0;
1570 } /* }}} int bind_read */
1571
1572 static int bind_shutdown(void) /* {{{ */
1573 {
1574   if (curl != NULL) {
1575     curl_easy_cleanup(curl);
1576     curl = NULL;
1577   }
1578
1579   return 0;
1580 } /* }}} int bind_shutdown */
1581
1582 void module_register(void) {
1583   plugin_register_complex_config("bind", bind_config);
1584   plugin_register_init("bind", bind_init);
1585   plugin_register_read("bind", bind_read);
1586   plugin_register_shutdown("bind", bind_shutdown);
1587 } /* void module_register */