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