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