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