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