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