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