Merge pull request #1829 from rubenk/clang-format
[collectd.git] / src / bind.c
1 /**
2  * collectd - src/bind.c
3  * Copyright (C) 2009       Bruno PrĂ©mont
4  * Copyright (C) 2009,2010  Florian Forster
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Bruno PrĂ©mont <bonbons at linux-vserver.org>
21  *   Florian Forster <octo at collectd.org>
22  **/
23
24 #include "config.h"
25
26 #if STRPTIME_NEEDS_STANDARDS
27 # ifndef _ISOC99_SOURCE
28 #  define _ISOC99_SOURCE 1
29 # endif
30 # ifndef _POSIX_C_SOURCE
31 #  define _POSIX_C_SOURCE 200112L
32 # endif
33 # ifndef _XOPEN_SOURCE
34 #  define _XOPEN_SOURCE 500
35 # endif
36 #endif /* STRPTIME_NEEDS_STANDARDS */
37
38 #include "collectd.h"
39 #include "common.h"
40 #include "plugin.h"
41 #include "configfile.h"
42
43 /* Some versions of libcurl don't include this themselves and then don't have
44  * fd_set available. */
45 #if HAVE_SYS_SELECT_H
46 # include <sys/select.h>
47 #endif
48
49 #include <curl/curl.h>
50 #include <libxml/parser.h>
51 #include <libxml/xpath.h>
52
53 #ifndef BIND_DEFAULT_URL
54 # define BIND_DEFAULT_URL "http://localhost:8053/"
55 #endif
56
57 /*
58  * Some types used for the callback functions. `translation_table_ptr_t' and
59  * `list_info_ptr_t' are passed to the callbacks in the `void *user_data'
60  * pointer.
61  */
62 typedef int (*list_callback_t) (const char *name, value_t value,
63     time_t current_time, void *user_data);
64
65 struct cb_view_s
66 {
67   char *name;
68
69   int qtypes;
70   int resolver_stats;
71   int cacherrsets;
72
73   char **zones;
74   size_t zones_num;
75 };
76 typedef struct cb_view_s cb_view_t;
77
78 struct translation_info_s
79 {
80   const char *xml_name;
81   const char *type;
82   const char *type_instance;
83 };
84 typedef struct translation_info_s translation_info_t;
85
86 struct translation_table_ptr_s
87 {
88   const translation_info_t *table;
89   size_t table_length;
90   const char *plugin_instance;
91 };
92 typedef struct translation_table_ptr_s translation_table_ptr_t;
93
94 struct list_info_ptr_s
95 {
96   const char *plugin_instance;
97   const char *type;
98 };
99 typedef struct list_info_ptr_s list_info_ptr_t;
100
101 /* FIXME: Enabled by default for backwards compatibility. */
102 /* TODO: Remove time parsing code. */
103 static _Bool config_parse_time = 1;
104
105 static char *url                   = NULL;
106 static int global_opcodes          = 1;
107 static int global_qtypes           = 1;
108 static int global_server_stats     = 1;
109 static int global_zone_maint_stats = 1;
110 static int global_resolver_stats   = 0;
111 static int global_memory_stats     = 1;
112 static int timeout                 = -1;
113
114 static cb_view_t *views = NULL;
115 static size_t     views_num = 0;
116
117 static CURL *curl = NULL;
118
119 static char  *bind_buffer = NULL;
120 static size_t bind_buffer_size = 0;
121 static size_t bind_buffer_fill = 0;
122 static char   bind_curl_error[CURL_ERROR_SIZE];
123
124 /* Translation table for the `nsstats' values. */
125 static const translation_info_t nsstats_translation_table[] = /* {{{ */
126 {
127   /* Requests */
128   { "Requestv4",       "dns_request",  "IPv4"        },
129   { "Requestv6",       "dns_request",  "IPv6"        },
130   { "ReqEdns0",        "dns_request",  "EDNS0"       },
131   { "ReqBadEDNSVer",   "dns_request",  "BadEDNSVer"  },
132   { "ReqTSIG",         "dns_request",  "TSIG"        },
133   { "ReqSIG0",         "dns_request",  "SIG0"        },
134   { "ReqBadSIG",       "dns_request",  "BadSIG"      },
135   { "ReqTCP",          "dns_request",  "TCP"         },
136   /* Rejects */
137   { "AuthQryRej",      "dns_reject",   "authorative" },
138   { "RecQryRej",       "dns_reject",   "recursive"   },
139   { "XfrRej",          "dns_reject",   "transfer"    },
140   { "UpdateRej",       "dns_reject",   "update"      },
141   /* Responses */
142   { "Response",        "dns_response", "normal"      },
143   { "TruncatedResp",   "dns_response", "truncated"   },
144   { "RespEDNS0",       "dns_response", "EDNS0"       },
145   { "RespTSIG",        "dns_response", "TSIG"        },
146   { "RespSIG0",        "dns_response", "SIG0"        },
147   /* Queries */
148   { "QryAuthAns",      "dns_query",    "authorative" },
149   { "QryNoauthAns",    "dns_query",    "nonauth"     },
150   { "QryReferral",     "dns_query",    "referral"    },
151   { "QryRecursion",    "dns_query",    "recursion"   },
152   { "QryDuplicate",    "dns_query",    "dupliate"    },
153   { "QryDropped",      "dns_query",    "dropped"     },
154   { "QryFailure",      "dns_query",    "failure"     },
155   /* Response codes */
156   { "QrySuccess",      "dns_rcode",    "tx-NOERROR"  },
157   { "QryNxrrset",      "dns_rcode",    "tx-NXRRSET"  },
158   { "QrySERVFAIL",     "dns_rcode",    "tx-SERVFAIL" },
159   { "QryFORMERR",      "dns_rcode",    "tx-FORMERR"  },
160   { "QryNXDOMAIN",     "dns_rcode",    "tx-NXDOMAIN" }
161 #if 0
162   { "XfrReqDone",      "type", "type_instance"       },
163   { "UpdateReqFwd",    "type", "type_instance"       },
164   { "UpdateRespFwd",   "type", "type_instance"       },
165   { "UpdateFwdFail",   "type", "type_instance"       },
166   { "UpdateDone",      "type", "type_instance"       },
167   { "UpdateFail",      "type", "type_instance"       },
168   { "UpdateBadPrereq", "type", "type_instance"       },
169 #endif
170 };
171 static int nsstats_translation_table_length =
172   STATIC_ARRAY_SIZE (nsstats_translation_table);
173 /* }}} */
174
175 /* Translation table for the `zonestats' values. */
176 static const translation_info_t zonestats_translation_table[] = /* {{{ */
177 {
178   /* Notify's */
179   { "NotifyOutv4",     "dns_notify",   "tx-IPv4"     },
180   { "NotifyOutv6",     "dns_notify",   "tx-IPv6"     },
181   { "NotifyInv4",      "dns_notify",   "rx-IPv4"     },
182   { "NotifyInv6",      "dns_notify",   "rx-IPv6"     },
183   { "NotifyRej",       "dns_notify",   "rejected"    },
184   /* SOA/AXFS/IXFS requests */
185   { "SOAOutv4",        "dns_opcode",   "SOA-IPv4"    },
186   { "SOAOutv6",        "dns_opcode",   "SOA-IPv6"    },
187   { "AXFRReqv4",       "dns_opcode",   "AXFR-IPv4"   },
188   { "AXFRReqv6",       "dns_opcode",   "AXFR-IPv6"   },
189   { "IXFRReqv4",       "dns_opcode",   "IXFR-IPv4"   },
190   { "IXFRReqv6",       "dns_opcode",   "IXFR-IPv6"   },
191   /* Domain transfers */
192   { "XfrSuccess",      "dns_transfer", "success"     },
193   { "XfrFail",         "dns_transfer", "failure"     }
194 };
195 static int zonestats_translation_table_length =
196   STATIC_ARRAY_SIZE (zonestats_translation_table);
197 /* }}} */
198
199 /* Translation table for the `resstats' values. */
200 static const translation_info_t resstats_translation_table[] = /* {{{ */
201 {
202   /* Generic resolver information */
203   { "Queryv4",         "dns_query",    "IPv4"        },
204   { "Queryv6",         "dns_query",    "IPv6"        },
205   { "Responsev4",      "dns_response", "IPv4"        },
206   { "Responsev6",      "dns_response", "IPv6"        },
207   /* Received response codes */
208   { "NXDOMAIN",        "dns_rcode",    "rx-NXDOMAIN" },
209   { "SERVFAIL",        "dns_rcode",    "rx-SERVFAIL" },
210   { "FORMERR",         "dns_rcode",    "rx-FORMERR"  },
211   { "OtherError",      "dns_rcode",    "rx-OTHER"    },
212   { "EDNS0Fail",       "dns_rcode",    "rx-EDNS0Fail"},
213   /* Received responses */
214   { "Mismatch",        "dns_response", "mismatch"    },
215   { "Truncated",       "dns_response", "truncated"   },
216   { "Lame",            "dns_response", "lame"        },
217   { "Retry",           "dns_query",    "retry"       },
218 #if 0
219   { "GlueFetchv4",     "type", "type_instance" },
220   { "GlueFetchv6",     "type", "type_instance" },
221   { "GlueFetchv4Fail", "type", "type_instance" },
222   { "GlueFetchv6Fail", "type", "type_instance" },
223 #endif
224   /* DNSSEC information */
225   { "ValAttempt",      "dns_resolver", "DNSSEC-attempt" },
226   { "ValOk",           "dns_resolver", "DNSSEC-okay"    },
227   { "ValNegOk",        "dns_resolver", "DNSSEC-negokay" },
228   { "ValFail",         "dns_resolver", "DNSSEC-fail"    }
229 };
230 static int resstats_translation_table_length =
231   STATIC_ARRAY_SIZE (resstats_translation_table);
232 /* }}} */
233
234 /* Translation table for the `memory/summary' values. */
235 static const translation_info_t memsummary_translation_table[] = /* {{{ */
236 {
237   { "TotalUse",        "memory",       "TotalUse"    },
238   { "InUse",           "memory",       "InUse"       },
239   { "BlockSize",       "memory",       "BlockSize"   },
240   { "ContextSize",     "memory",       "ContextSize" },
241   { "Lost",            "memory",       "Lost"        }
242 };
243 static int memsummary_translation_table_length =
244   STATIC_ARRAY_SIZE (memsummary_translation_table);
245 /* }}} */
246
247 static void submit (time_t ts, const char *plugin_instance, /* {{{ */
248     const char *type, const char *type_instance, value_t value)
249 {
250   value_t values[1];
251   value_list_t vl = VALUE_LIST_INIT;
252
253   values[0] = value;
254
255   vl.values = values;
256   vl.values_len = 1;
257   if (config_parse_time)
258     vl.time = TIME_T_TO_CDTIME_T (ts);
259   sstrncpy(vl.host, hostname_g, sizeof(vl.host));
260   sstrncpy(vl.plugin, "bind", sizeof(vl.plugin));
261   if (plugin_instance) {
262     sstrncpy(vl.plugin_instance, plugin_instance,
263         sizeof(vl.plugin_instance));
264     replace_special (vl.plugin_instance, sizeof (vl.plugin_instance));
265   }
266   sstrncpy(vl.type, type, sizeof(vl.type));
267   if (type_instance) {
268     sstrncpy(vl.type_instance, type_instance,
269         sizeof(vl.type_instance));
270     replace_special (vl.type_instance, sizeof (vl.type_instance));
271   }
272   plugin_dispatch_values(&vl);
273 } /* }}} void submit */
274
275 static size_t bind_curl_callback (void *buf, size_t size, /* {{{ */
276     size_t nmemb, void __attribute__((unused)) *stream)
277 {
278   size_t len = size * nmemb;
279
280   if (len == 0)
281     return (len);
282
283   if ((bind_buffer_fill + len) >= bind_buffer_size)
284   {
285     char *temp;
286
287     temp = realloc (bind_buffer, bind_buffer_fill + len + 1);
288     if (temp == NULL)
289     {
290       ERROR ("bind plugin: realloc failed.");
291       return (0);
292     }
293     bind_buffer = temp;
294     bind_buffer_size = bind_buffer_fill + len + 1;
295   }
296
297   memcpy (bind_buffer + bind_buffer_fill, (char *) buf, len);
298   bind_buffer_fill += len;
299   bind_buffer[bind_buffer_fill] = 0;
300
301   return (len);
302 } /* }}} size_t bind_curl_callback */
303
304 /*
305  * Callback, that's called with a translation table.
306  * (Plugin instance is fixed, type and type instance come from lookup table.)
307  */
308 static int bind_xml_table_callback (const char *name, value_t value, /* {{{ */
309     time_t current_time, void *user_data)
310 {
311   translation_table_ptr_t *table = (translation_table_ptr_t *) user_data;
312   size_t i;
313
314   if (table == NULL)
315     return (-1);
316
317   for (i = 0; i < table->table_length; i++)
318   {
319     if (strcmp (table->table[i].xml_name, name) != 0)
320       continue;
321
322     submit (current_time,
323         table->plugin_instance,
324         table->table[i].type,
325         table->table[i].type_instance,
326         value);
327     break;
328   }
329
330   return (0);
331 } /* }}} int bind_xml_table_callback */
332
333 /*
334  * Callback, that's used for lists.
335  * (Plugin instance and type are fixed, xml name is used as type instance.)
336  */
337 static int bind_xml_list_callback (const char *name, /* {{{ */
338     value_t value, time_t current_time, void *user_data)
339 {
340   list_info_ptr_t *list_info = (list_info_ptr_t *) user_data;
341
342   if (list_info == NULL)
343     return (-1);
344
345   submit (current_time,
346       list_info->plugin_instance,
347       list_info->type,
348       /* type instance = */ name,
349       value);
350
351   return (0);
352 } /* }}} int bind_xml_list_callback */
353
354 static int bind_xml_read_derive (xmlDoc *doc, xmlNode *node, /* {{{ */
355     derive_t *ret_value)
356 {
357   char *str_ptr;
358   value_t value;
359   int status;
360
361   str_ptr = (char *) xmlNodeListGetString (doc, node->xmlChildrenNode, 1);
362   if (str_ptr == NULL)
363   {
364     ERROR ("bind plugin: bind_xml_read_derive: xmlNodeListGetString failed.");
365     return (-1);
366   }
367
368   status = parse_value (str_ptr, &value, DS_TYPE_DERIVE);
369   if (status != 0)
370   {
371     ERROR ("bind plugin: Parsing string \"%s\" to derive value failed.",
372         str_ptr);
373     xmlFree(str_ptr);
374     return (-1);
375   }
376
377   xmlFree(str_ptr);
378   *ret_value = value.derive;
379   return (0);
380 } /* }}} int bind_xml_read_derive */
381
382 static int bind_xml_read_gauge (xmlDoc *doc, xmlNode *node, /* {{{ */
383     gauge_t *ret_value)
384 {
385   char *str_ptr, *end_ptr;
386   double value;
387
388   str_ptr = (char *) xmlNodeListGetString (doc, node->xmlChildrenNode, 1);
389   if (str_ptr == NULL)
390   {
391     ERROR ("bind plugin: bind_xml_read_gauge: xmlNodeListGetString failed.");
392     return (-1);
393   }
394
395   errno = 0;
396   value = strtod (str_ptr, &end_ptr);
397   xmlFree(str_ptr);
398   if (str_ptr == end_ptr || errno)
399   {
400     if (errno && (value < 0))
401       ERROR ("bind plugin: bind_xml_read_gauge: strtod failed with underflow.");
402     else if (errno && (value > 0))
403       ERROR ("bind plugin: bind_xml_read_gauge: strtod failed with overflow.");
404     else
405       ERROR ("bind plugin: bind_xml_read_gauge: strtod failed.");
406     return (-1);
407   }
408
409   *ret_value = (gauge_t) value;
410   return (0);
411 } /* }}} int bind_xml_read_gauge */
412
413 static int bind_xml_read_timestamp (const char *xpath_expression, /* {{{ */
414     xmlDoc *doc, xmlXPathContext *xpathCtx, time_t *ret_value)
415 {
416   xmlXPathObject *xpathObj = NULL;
417   xmlNode *node;
418   char *str_ptr;
419   char *tmp;
420   struct tm tm = { 0 };
421
422   xpathObj = xmlXPathEvalExpression (BAD_CAST xpath_expression, xpathCtx);
423   if (xpathObj == NULL)
424   {
425     ERROR ("bind plugin: Unable to evaluate XPath expression `%s'.",
426         xpath_expression);
427     return (-1);
428   }
429
430   if ((xpathObj->nodesetval == NULL) || (xpathObj->nodesetval->nodeNr < 1))
431   {
432     xmlXPathFreeObject (xpathObj);
433     return (-1);
434   }
435
436   if (xpathObj->nodesetval->nodeNr != 1)
437   {
438     NOTICE ("bind plugin: Evaluating the XPath expression `%s' returned "
439         "%i nodes. Only handling the first one.",
440         xpath_expression, xpathObj->nodesetval->nodeNr);
441   }
442
443   node = xpathObj->nodesetval->nodeTab[0];
444
445   if (node->xmlChildrenNode == NULL)
446   {
447     ERROR ("bind plugin: bind_xml_read_timestamp: "
448         "node->xmlChildrenNode == NULL");
449     xmlXPathFreeObject (xpathObj);
450     return (-1);
451   }
452
453   str_ptr = (char *) xmlNodeListGetString (doc, node->xmlChildrenNode, 1);
454   if (str_ptr == NULL)
455   {
456     ERROR ("bind plugin: bind_xml_read_timestamp: xmlNodeListGetString failed.");
457     xmlXPathFreeObject (xpathObj);
458     return (-1);
459   }
460
461   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 >= view->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     node = zone_nodes->nodesetval->nodeTab[i];
839     assert (node != NULL);
840
841     zone_path_context->node = node;
842
843     bind_xml_stats_handle_zone (version, doc, zone_path_context, node, view,
844         current_time);
845   }
846
847   xmlXPathFreeObject (zone_nodes);
848   xmlXPathFreeContext (zone_path_context);
849   return (0);
850 } /* }}} int bind_xml_stats_search_zones */
851
852 static int bind_xml_stats_handle_view (int version, xmlDoc *doc, /* {{{ */
853     xmlXPathContext *path_ctx, xmlNode *node, time_t current_time)
854 {
855   char *view_name = NULL;
856   cb_view_t *view;
857   int i;
858   size_t j;
859
860   if (version == 3)
861   {
862     view_name = (char*) xmlGetProp(node, BAD_CAST "name");
863
864     if (view_name == NULL)
865     {
866       ERROR ("bind plugin: Could not determine view name.");
867       return (-1);
868     }
869
870     for (j = 0; j < views_num; j++)
871     {
872       if (strcasecmp (view_name, views[j].name) == 0)
873         break;
874     }
875
876     xmlFree (view_name);
877     view_name = NULL;
878   }
879   else
880   {
881     xmlXPathObject *path_obj;
882     path_obj = xmlXPathEvalExpression (BAD_CAST "name", path_ctx);
883     if (path_obj == NULL)
884     {
885       ERROR ("bind plugin: xmlXPathEvalExpression failed.");
886       return (-1);
887     }
888
889     for (i = 0; path_obj->nodesetval && (i < path_obj->nodesetval->nodeNr); i++)
890     {
891       view_name = (char *) xmlNodeListGetString (doc,
892           path_obj->nodesetval->nodeTab[i]->xmlChildrenNode, 1);
893       if (view_name != NULL)
894         break;
895     }
896
897     if (view_name == NULL)
898     {
899       ERROR ("bind plugin: Could not determine view name.");
900       xmlXPathFreeObject (path_obj);
901       return (-1);
902     }
903
904     for (j = 0; j < views_num; j++)
905     {
906       if (strcasecmp (view_name, views[j].name) == 0)
907         break;
908     }
909
910     xmlFree (view_name);
911     xmlXPathFreeObject (path_obj);
912
913     view_name = NULL;
914     path_obj = NULL;
915   }
916
917
918   if (j >= views_num)
919     return (0);
920
921   view = views + j;
922
923   DEBUG ("bind plugin: bind_xml_stats_handle_view: Found view `%s'.",
924       view->name);
925
926   if (view->qtypes != 0) /* {{{ */
927   {
928     char plugin_instance[DATA_MAX_NAME_LEN];
929     list_info_ptr_t list_info =
930     {
931       plugin_instance,
932       /* type = */ "dns_qtype"
933     };
934
935     ssnprintf (plugin_instance, sizeof (plugin_instance), "%s-qtypes",
936         view->name);
937     if (version == 3)
938     {
939       bind_parse_generic_name_attr_value_list (/* xpath = */ "counters[@type='resqtype']",
940         /* callback = */ bind_xml_list_callback,
941         /* user_data = */ &list_info,
942         doc, path_ctx, current_time, DS_TYPE_COUNTER);
943     }
944     else
945     {
946       bind_parse_generic_name_value (/* xpath = */ "rdtype",
947         /* callback = */ bind_xml_list_callback,
948         /* user_data = */ &list_info,
949         doc, path_ctx, current_time, DS_TYPE_COUNTER);
950     }
951   } /* }}} */
952
953   if (view->resolver_stats != 0) /* {{{ */
954   {
955     char plugin_instance[DATA_MAX_NAME_LEN];
956     translation_table_ptr_t table_ptr =
957     {
958       resstats_translation_table,
959       resstats_translation_table_length,
960       plugin_instance
961     };
962
963     ssnprintf (plugin_instance, sizeof (plugin_instance),
964         "%s-resolver_stats", view->name);
965     if (version == 3)
966     {
967       bind_parse_generic_name_attr_value_list ("counters[@type='resstats']",
968           /* callback = */ bind_xml_table_callback,
969           /* user_data = */ &table_ptr,
970           doc, path_ctx, current_time, DS_TYPE_COUNTER);
971     }
972     else
973     {
974       bind_parse_generic_name_value ("resstat",
975           /* callback = */ bind_xml_table_callback,
976           /* user_data = */ &table_ptr,
977           doc, path_ctx, current_time, DS_TYPE_COUNTER);
978     }
979   } /* }}} */
980
981   /* Record types in the cache */
982   if (view->cacherrsets != 0) /* {{{ */
983   {
984     char plugin_instance[DATA_MAX_NAME_LEN];
985     list_info_ptr_t list_info =
986     {
987       plugin_instance,
988       /* type = */ "dns_qtype_cached"
989     };
990
991     ssnprintf (plugin_instance, sizeof (plugin_instance), "%s-cache_rr_sets",
992         view->name);
993
994     bind_parse_generic_name_value (/* xpath = */ "cache/rrset",
995         /* callback = */ bind_xml_list_callback,
996         /* user_data = */ &list_info,
997         doc, path_ctx, current_time, DS_TYPE_GAUGE);
998   } /* }}} */
999
1000   if (view->zones_num > 0)
1001     bind_xml_stats_search_zones (version, doc, path_ctx, node, view,
1002         current_time);
1003
1004   return (0);
1005 } /* }}} int bind_xml_stats_handle_view */
1006
1007 static int bind_xml_stats_search_views (int version, xmlDoc *doc, /* {{{ */
1008     xmlXPathContext *xpathCtx, xmlNode *statsnode, time_t current_time)
1009 {
1010   xmlXPathObject *view_nodes = NULL;
1011   xmlXPathContext *view_path_context;
1012   int i;
1013
1014   view_path_context = xmlXPathNewContext (doc);
1015   if (view_path_context == NULL)
1016   {
1017     ERROR ("bind plugin: xmlXPathNewContext failed.");
1018     return (-1);
1019   }
1020
1021   view_nodes = xmlXPathEvalExpression (BAD_CAST "views/view", xpathCtx);
1022   if (view_nodes == NULL)
1023   {
1024     ERROR ("bind plugin: Cannot find any <view> tags.");
1025     xmlXPathFreeContext (view_path_context);
1026     return (-1);
1027   }
1028
1029   for (i = 0; i < view_nodes->nodesetval->nodeNr; i++)
1030   {
1031     xmlNode *node;
1032
1033     node = view_nodes->nodesetval->nodeTab[i];
1034     assert (node != NULL);
1035
1036     view_path_context->node = node;
1037
1038     bind_xml_stats_handle_view (version, doc, view_path_context, node,
1039         current_time);
1040   }
1041
1042   xmlXPathFreeObject (view_nodes);
1043   xmlXPathFreeContext (view_path_context);
1044   return (0);
1045 } /* }}} int bind_xml_stats_search_views */
1046
1047 static void bind_xml_stats_v3 (xmlDoc *doc, /* {{{ */
1048     xmlXPathContext *xpathCtx, xmlNode *statsnode, time_t current_time)
1049 {
1050   /* XPath:     server/counters[@type='opcode']
1051    * Variables: QUERY, IQUERY, NOTIFY, UPDATE, ...
1052    * Layout v3:
1053    *   <counters type="opcode">
1054    *     <counter name="A">1</counter>
1055    *     :
1056    *   </counters>
1057    */
1058   if (global_opcodes != 0)
1059   {
1060     list_info_ptr_t list_info =
1061     {
1062       /* plugin instance = */ "global-opcodes",
1063       /* type = */ "dns_opcode"
1064     };
1065     bind_parse_generic_name_attr_value_list (/* xpath = */ "server/counters[@type='opcode']",
1066       /* callback = */ bind_xml_list_callback,
1067       /* user_data = */ &list_info,
1068       doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1069   }
1070
1071   /* XPath:     server/counters[@type='qtype']
1072    * Variables: RESERVED0, A, NS, CNAME, SOA, MR, PTR, HINFO, MX, TXT, RP,
1073    *            X25, PX, AAAA, LOC, SRV, NAPTR, A6, DS, RRSIG, NSEC, DNSKEY,
1074    *            SPF, TKEY, IXFR, AXFR, ANY, ..., Others
1075    * Layout v3:
1076    *   <counters type="opcode">
1077    *     <counter name="A">1</counter>
1078    *     :
1079    *   </counters>
1080    */
1081   if (global_qtypes != 0)
1082   {
1083     list_info_ptr_t list_info =
1084     {
1085       /* plugin instance = */ "global-qtypes",
1086       /* type = */ "dns_qtype"
1087     };
1088
1089     bind_parse_generic_name_attr_value_list (/* xpath = */ "server/counters[@type='qtype']",
1090         /* callback = */ bind_xml_list_callback,
1091         /* user_data = */ &list_info,
1092         doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1093   }
1094
1095   /* XPath:     server/counters[@type='nsstat']
1096    * Variables: Requestv4, Requestv6, ReqEdns0, ReqBadEDNSVer, ReqTSIG,
1097    *            ReqSIG0, ReqBadSIG, ReqTCP, AuthQryRej, RecQryRej, XfrRej,
1098    *            UpdateRej, Response, TruncatedResp, RespEDNS0, RespTSIG,
1099    *            RespSIG0, QrySuccess, QryAuthAns, QryNoauthAns, QryReferral,
1100    *            QryNxrrset, QrySERVFAIL, QryFORMERR, QryNXDOMAIN, QryRecursion,
1101    *            QryDuplicate, QryDropped, QryFailure, XfrReqDone, UpdateReqFwd,
1102    *            UpdateRespFwd, UpdateFwdFail, UpdateDone, UpdateFail,
1103    *            UpdateBadPrereq
1104    * Layout v3:
1105    *   <counters type="nsstat"
1106    *     <counter name="Requestv4">1</counter>
1107    *     <counter name="Requestv6">0</counter>
1108    *     :
1109    *   </counter>
1110    */
1111   if (global_server_stats)
1112   {
1113     translation_table_ptr_t table_ptr =
1114     {
1115       nsstats_translation_table,
1116       nsstats_translation_table_length,
1117       /* plugin_instance = */ "global-server_stats"
1118     };
1119
1120     bind_parse_generic_name_attr_value_list ("server/counters[@type='nsstat']",
1121         /* callback = */ bind_xml_table_callback,
1122         /* user_data = */ &table_ptr,
1123         doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1124   }
1125
1126   /* XPath:     server/zonestats, server/zonestat, server/counters[@type='zonestat']
1127    * Variables: NotifyOutv4, NotifyOutv6, NotifyInv4, NotifyInv6, NotifyRej,
1128    *            SOAOutv4, SOAOutv6, AXFRReqv4, AXFRReqv6, IXFRReqv4, IXFRReqv6,
1129    *            XfrSuccess, XfrFail
1130    * Layout v3:
1131    *   <counters type="zonestat"
1132    *     <counter name="NotifyOutv4">0</counter>
1133    *     <counter name="NotifyOutv6">0</counter>
1134    *     :
1135    *   </counter>
1136    */
1137   if (global_zone_maint_stats)
1138   {
1139     translation_table_ptr_t table_ptr =
1140     {
1141       zonestats_translation_table,
1142       zonestats_translation_table_length,
1143       /* plugin_instance = */ "global-zone_maint_stats"
1144     };
1145
1146     bind_parse_generic_name_attr_value_list ("server/counters[@type='zonestat']",
1147         /* callback = */ bind_xml_table_callback,
1148         /* user_data = */ &table_ptr,
1149         doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1150   }
1151
1152   /* XPath:     server/resstats, server/counters[@type='resstat']
1153    * Variables: Queryv4, Queryv6, Responsev4, Responsev6, NXDOMAIN, SERVFAIL,
1154    *            FORMERR, OtherError, EDNS0Fail, Mismatch, Truncated, Lame,
1155    *            Retry, GlueFetchv4, GlueFetchv6, GlueFetchv4Fail,
1156    *            GlueFetchv6Fail, ValAttempt, ValOk, ValNegOk, ValFail
1157    * Layout v3:
1158    *   <counters type="resstat"
1159    *     <counter name="Queryv4">0</counter>
1160    *     <counter name="Queryv6">0</counter>
1161    *     :
1162    *   </counter>
1163    */
1164   if (global_resolver_stats != 0)
1165   {
1166     translation_table_ptr_t table_ptr =
1167     {
1168       resstats_translation_table,
1169       resstats_translation_table_length,
1170       /* plugin_instance = */ "global-resolver_stats"
1171     };
1172
1173     bind_parse_generic_name_attr_value_list ("server/counters[@type='resstat']",
1174         /* callback = */ bind_xml_table_callback,
1175         /* user_data = */ &table_ptr,
1176         doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1177   }
1178 } /* }}} bind_xml_stats_v3 */
1179
1180 static void bind_xml_stats_v1_v2 (int version, xmlDoc *doc, /* {{{ */
1181     xmlXPathContext *xpathCtx, xmlNode *statsnode, time_t current_time)
1182 {
1183   /* XPath:     server/requests/opcode, server/counters[@type='opcode']
1184    * Variables: QUERY, IQUERY, NOTIFY, UPDATE, ...
1185    * Layout V1 and V2:
1186    *   <opcode>
1187    *     <name>A</name>
1188    *     <counter>1</counter>
1189    *   </opcode>
1190    *   :
1191    */
1192   if (global_opcodes != 0)
1193   {
1194     list_info_ptr_t list_info =
1195     {
1196       /* plugin instance = */ "global-opcodes",
1197       /* type = */ "dns_opcode"
1198     };
1199
1200     bind_parse_generic_name_value (/* xpath = */ "server/requests/opcode",
1201         /* callback = */ bind_xml_list_callback,
1202         /* user_data = */ &list_info,
1203         doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1204   }
1205
1206   /* XPath:     server/queries-in/rdtype, server/counters[@type='qtype']
1207    * Variables: RESERVED0, A, NS, CNAME, SOA, MR, PTR, HINFO, MX, TXT, RP,
1208    *            X25, PX, AAAA, LOC, SRV, NAPTR, A6, DS, RRSIG, NSEC, DNSKEY,
1209    *            SPF, TKEY, IXFR, AXFR, ANY, ..., Others
1210    * Layout v1 or v2:
1211    *   <rdtype>
1212    *     <name>A</name>
1213    *     <counter>1</counter>
1214    *   </rdtype>
1215    *   :
1216    */
1217   if (global_qtypes != 0)
1218   {
1219     list_info_ptr_t list_info =
1220     {
1221       /* plugin instance = */ "global-qtypes",
1222       /* type = */ "dns_qtype"
1223     };
1224
1225     bind_parse_generic_name_value (/* xpath = */ "server/queries-in/rdtype",
1226         /* callback = */ bind_xml_list_callback,
1227         /* user_data = */ &list_info,
1228         doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1229   }
1230
1231   /* XPath:     server/nsstats, server/nsstat, server/counters[@type='nsstat']
1232    * Variables: Requestv4, Requestv6, ReqEdns0, ReqBadEDNSVer, ReqTSIG,
1233    *            ReqSIG0, ReqBadSIG, ReqTCP, AuthQryRej, RecQryRej, XfrRej,
1234    *            UpdateRej, Response, TruncatedResp, RespEDNS0, RespTSIG,
1235    *            RespSIG0, QrySuccess, QryAuthAns, QryNoauthAns, QryReferral,
1236    *            QryNxrrset, QrySERVFAIL, QryFORMERR, QryNXDOMAIN, QryRecursion,
1237    *            QryDuplicate, QryDropped, QryFailure, XfrReqDone, UpdateReqFwd,
1238    *            UpdateRespFwd, UpdateFwdFail, UpdateDone, UpdateFail,
1239    *            UpdateBadPrereq
1240    * Layout v1:
1241    *   <nsstats>
1242    *     <Requestv4>1</Requestv4>
1243    *     <Requestv6>0</Requestv6>
1244    *     :
1245    *   </nsstats>
1246    * Layout v2:
1247    *   <nsstat>
1248    *     <name>Requestv4</name>
1249    *     <counter>1</counter>
1250    *   </nsstat>
1251    *   <nsstat>
1252    *     <name>Requestv6</name>
1253    *     <counter>0</counter>
1254    *   </nsstat>
1255    *   :
1256    */
1257   if (global_server_stats)
1258   {
1259     translation_table_ptr_t table_ptr =
1260     {
1261       nsstats_translation_table,
1262       nsstats_translation_table_length,
1263       /* plugin_instance = */ "global-server_stats"
1264     };
1265
1266     if (version == 1)
1267     {
1268       bind_parse_generic_value_list ("server/nsstats",
1269           /* callback = */ bind_xml_table_callback,
1270           /* user_data = */ &table_ptr,
1271           doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1272     }
1273     else
1274     {
1275       bind_parse_generic_name_value ("server/nsstat",
1276           /* callback = */ bind_xml_table_callback,
1277           /* user_data = */ &table_ptr,
1278           doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1279     }
1280   }
1281
1282   /* XPath:     server/zonestats, server/zonestat, server/counters[@type='zonestat']
1283    * Variables: NotifyOutv4, NotifyOutv6, NotifyInv4, NotifyInv6, NotifyRej,
1284    *            SOAOutv4, SOAOutv6, AXFRReqv4, AXFRReqv6, IXFRReqv4, IXFRReqv6,
1285    *            XfrSuccess, XfrFail
1286    * Layout v1:
1287    *   <zonestats>
1288    *     <NotifyOutv4>0</NotifyOutv4>
1289    *     <NotifyOutv6>0</NotifyOutv6>
1290    *     :
1291    *   </zonestats>
1292    * Layout v2:
1293    *   <zonestat>
1294    *     <name>NotifyOutv4</name>
1295    *     <counter>0</counter>
1296    *   </zonestat>
1297    *   <zonestat>
1298    *     <name>NotifyOutv6</name>
1299    *     <counter>0</counter>
1300    *   </zonestat>
1301    *   :
1302    */
1303   if (global_zone_maint_stats)
1304   {
1305     translation_table_ptr_t table_ptr =
1306     {
1307       zonestats_translation_table,
1308       zonestats_translation_table_length,
1309       /* plugin_instance = */ "global-zone_maint_stats"
1310     };
1311
1312     if (version == 1)
1313     {
1314       bind_parse_generic_value_list ("server/zonestats",
1315           /* callback = */ bind_xml_table_callback,
1316           /* user_data = */ &table_ptr,
1317           doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1318     }
1319     else
1320     {
1321       bind_parse_generic_name_value ("server/zonestat",
1322           /* callback = */ bind_xml_table_callback,
1323           /* user_data = */ &table_ptr,
1324           doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1325     }
1326   }
1327
1328   /* XPath:     server/resstats, server/counters[@type='resstat']
1329    * Variables: Queryv4, Queryv6, Responsev4, Responsev6, NXDOMAIN, SERVFAIL,
1330    *            FORMERR, OtherError, EDNS0Fail, Mismatch, Truncated, Lame,
1331    *            Retry, GlueFetchv4, GlueFetchv6, GlueFetchv4Fail,
1332    *            GlueFetchv6Fail, ValAttempt, ValOk, ValNegOk, ValFail
1333    * Layout v1:
1334    *   <resstats>
1335    *     <Queryv4>0</Queryv4>
1336    *     <Queryv6>0</Queryv6>
1337    *     :
1338    *   </resstats>
1339    * Layout v2:
1340    *   <resstat>
1341    *     <name>Queryv4</name>
1342    *     <counter>0</counter>
1343    *   </resstat>
1344    *   <resstat>
1345    *     <name>Queryv6</name>
1346    *     <counter>0</counter>
1347    *   </resstat>
1348    *   :
1349    */
1350   if (global_resolver_stats != 0)
1351   {
1352     translation_table_ptr_t table_ptr =
1353     {
1354       resstats_translation_table,
1355       resstats_translation_table_length,
1356       /* plugin_instance = */ "global-resolver_stats"
1357     };
1358
1359     if (version == 1)
1360     {
1361       bind_parse_generic_value_list ("server/resstats",
1362           /* callback = */ bind_xml_table_callback,
1363           /* user_data = */ &table_ptr,
1364           doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1365     }
1366     else
1367     {
1368       bind_parse_generic_name_value ("server/resstat",
1369           /* callback = */ bind_xml_table_callback,
1370           /* user_data = */ &table_ptr,
1371           doc, xpathCtx, current_time, DS_TYPE_COUNTER);
1372     }
1373   }
1374 } /* }}} bind_xml_stats_v1_v2 */
1375
1376 static int bind_xml_stats (int version, xmlDoc *doc, /* {{{ */
1377     xmlXPathContext *xpathCtx, xmlNode *statsnode)
1378 {
1379   time_t current_time = 0;
1380   int status;
1381
1382   xpathCtx->node = statsnode;
1383
1384   /* TODO: Check `server/boot-time' to recognize server restarts. */
1385
1386   status = bind_xml_read_timestamp ("server/current-time",
1387       doc, xpathCtx, &current_time);
1388   if (status != 0)
1389   {
1390     ERROR ("bind plugin: Reading `server/current-time' failed.");
1391     return (-1);
1392   }
1393   DEBUG ("bind plugin: Current server time is %i.", (int) current_time);
1394
1395   if (version == 3)
1396   {
1397     bind_xml_stats_v3(doc, xpathCtx, statsnode, current_time);
1398   }
1399   else
1400   {
1401     bind_xml_stats_v1_v2(version, doc, xpathCtx, statsnode, current_time);
1402   }
1403
1404   /* XPath:  memory/summary
1405    * Variables: TotalUse, InUse, BlockSize, ContextSize, Lost
1406    * Layout: v2 and v3:
1407    *   <summary>
1408    *     <TotalUse>6587096</TotalUse>
1409    *     <InUse>1345424</InUse>
1410    *     <BlockSize>5505024</BlockSize>
1411    *     <ContextSize>3732456</ContextSize>
1412    *     <Lost>0</Lost>
1413    *   </summary>
1414    */
1415   if (global_memory_stats != 0)
1416   {
1417     translation_table_ptr_t table_ptr =
1418     {
1419       memsummary_translation_table,
1420       memsummary_translation_table_length,
1421       /* plugin_instance = */ "global-memory_stats"
1422     };
1423
1424     bind_parse_generic_value_list ("memory/summary",
1425           /* callback = */ bind_xml_table_callback,
1426           /* user_data = */ &table_ptr,
1427           doc, xpathCtx, current_time, DS_TYPE_GAUGE);
1428   }
1429
1430   if (views_num > 0)
1431     bind_xml_stats_search_views (version, doc, xpathCtx, statsnode,
1432         current_time);
1433
1434   return 0;
1435 } /* }}} int bind_xml_stats */
1436
1437 static int bind_xml (const char *data) /* {{{ */
1438 {
1439   xmlDoc *doc = NULL;
1440   xmlXPathContext *xpathCtx = NULL;
1441   xmlXPathObject *xpathObj = NULL;
1442   int ret = -1;
1443   int i;
1444
1445   doc = xmlParseMemory (data, strlen (data));
1446   if (doc == NULL)
1447   {
1448     ERROR ("bind plugin: xmlParseMemory failed.");
1449     return (-1);
1450   }
1451
1452   xpathCtx = xmlXPathNewContext (doc);
1453   if (xpathCtx == NULL)
1454   {
1455     ERROR ("bind plugin: xmlXPathNewContext failed.");
1456     xmlFreeDoc (doc);
1457     return (-1);
1458   }
1459
1460   //
1461   // version 3.* of statistics XML (since BIND9.9)
1462   //
1463
1464   xpathObj = xmlXPathEvalExpression (BAD_CAST "/statistics", xpathCtx);
1465   if (xpathObj == NULL || xpathObj->nodesetval == NULL || xpathObj->nodesetval->nodeNr == 0)
1466   {
1467     DEBUG ("bind plugin: Statistics appears not to be v3");
1468     // we will fallback to v1 or v2 detection
1469     if (xpathObj != NULL) { xmlXPathFreeObject (xpathObj); }
1470   }
1471   else
1472   {
1473     for (i = 0; i < xpathObj->nodesetval->nodeNr; i++)
1474     {
1475       xmlNode *node;
1476       char *attr_version;
1477
1478       node = xpathObj->nodesetval->nodeTab[i];
1479       assert (node != NULL);
1480
1481       attr_version = (char *) xmlGetProp (node, BAD_CAST "version");
1482       if (attr_version == NULL)
1483       {
1484         NOTICE ("bind plugin: Found <statistics> tag doesn't have a "
1485             "`version' attribute.");
1486         continue;
1487       }
1488       DEBUG ("bind plugin: Found: <statistics version=\"%s\">", attr_version);
1489
1490       if (strncmp ("3.", attr_version, strlen ("3.")) != 0)
1491       {
1492         /* TODO: Use the complaint mechanism here. */
1493         NOTICE ("bind plugin: Found <statistics> tag with version `%s'. "
1494             "Unfortunately I have no clue how to parse that. "
1495             "Please open a bug report for this.", attr_version);
1496         xmlFree (attr_version);
1497         continue;
1498       }
1499       ret = bind_xml_stats (3, doc, xpathCtx, node);
1500
1501       xmlFree (attr_version);
1502       /* One <statistics> node ought to be enough. */
1503       break;
1504     }
1505
1506     // we are finished, early-return
1507     xmlXPathFreeObject (xpathObj);
1508     xmlXPathFreeContext (xpathCtx);
1509     xmlFreeDoc (doc);
1510
1511     return (ret);
1512   }
1513
1514   //
1515   // versions 1.* or 2.* of statistics XML
1516   //
1517
1518   xpathObj = xmlXPathEvalExpression (BAD_CAST "/isc/bind/statistics", xpathCtx);
1519   if (xpathObj == NULL)
1520   {
1521     ERROR ("bind plugin: Cannot find the <statistics> tag.");
1522     xmlXPathFreeContext (xpathCtx);
1523     xmlFreeDoc (doc);
1524     return (-1);
1525   }
1526   else if (xpathObj->nodesetval == NULL)
1527   {
1528     ERROR ("bind plugin: xmlXPathEvalExpression failed.");
1529     xmlXPathFreeObject (xpathObj);
1530     xmlXPathFreeContext (xpathCtx);
1531     xmlFreeDoc (doc);
1532     return (-1);
1533   }
1534
1535   for (i = 0; i < xpathObj->nodesetval->nodeNr; i++)
1536   {
1537     xmlNode *node;
1538     char *attr_version;
1539     int parsed_version = 0;
1540
1541     node = xpathObj->nodesetval->nodeTab[i];
1542     assert (node != NULL);
1543
1544     attr_version = (char *) xmlGetProp (node, BAD_CAST "version");
1545     if (attr_version == NULL)
1546     {
1547       NOTICE ("bind plugin: Found <statistics> tag doesn't have a "
1548           "`version' attribute.");
1549       continue;
1550     }
1551     DEBUG ("bind plugin: Found: <statistics version=\"%s\">", attr_version);
1552
1553     /* At the time this plugin was written, version "1.0" was used by
1554      * BIND 9.5.0, version "2.0" was used by BIND 9.5.1 and 9.6.0. We assume
1555      * that "1.*" and "2.*" don't introduce structural changes, so we just
1556      * check for the first two characters here. */
1557     if (strncmp ("1.", attr_version, strlen ("1.")) == 0)
1558       parsed_version = 1;
1559     else if (strncmp ("2.", attr_version, strlen ("2.")) == 0)
1560       parsed_version = 2;
1561     else
1562     {
1563       /* TODO: Use the complaint mechanism here. */
1564       NOTICE ("bind plugin: Found <statistics> tag with version `%s'. "
1565           "Unfortunately I have no clue how to parse that. "
1566           "Please open a bug report for this.", attr_version);
1567       xmlFree (attr_version);
1568       continue;
1569     }
1570
1571     ret = bind_xml_stats (parsed_version,
1572         doc, xpathCtx, node);
1573
1574     xmlFree (attr_version);
1575     /* One <statistics> node ought to be enough. */
1576     break;
1577   }
1578
1579   xmlXPathFreeObject (xpathObj);
1580   xmlXPathFreeContext (xpathCtx);
1581   xmlFreeDoc (doc);
1582
1583   return (ret);
1584 } /* }}} int bind_xml */
1585
1586 static int bind_config_set_bool (const char *name, int *var, /* {{{ */
1587     oconfig_item_t *ci)
1588 {
1589   if ((ci->values_num != 1) || ( ci->values[0].type != OCONFIG_TYPE_BOOLEAN))
1590   {
1591     WARNING ("bind plugin: The `%s' option needs "
1592         "exactly one boolean argument.", name);
1593     return (-1);
1594   }
1595
1596   if (ci->values[0].value.boolean)
1597     *var = 1;
1598   else
1599     *var = 0;
1600   return 0;
1601 } /* }}} int bind_config_set_bool */
1602
1603 static int bind_config_add_view_zone (cb_view_t *view, /* {{{ */
1604     oconfig_item_t *ci)
1605 {
1606   char **tmp;
1607
1608   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
1609   {
1610     WARNING ("bind plugin: The `Zone' option needs "
1611         "exactly one string argument.");
1612     return (-1);
1613   }
1614
1615   tmp = realloc (view->zones,
1616       sizeof (char *) * (view->zones_num + 1));
1617   if (tmp == NULL)
1618   {
1619     ERROR ("bind plugin: realloc failed.");
1620     return (-1);
1621   }
1622   view->zones = tmp;
1623
1624   view->zones[view->zones_num] = strdup (ci->values[0].value.string);
1625   if (view->zones[view->zones_num] == NULL)
1626   {
1627     ERROR ("bind plugin: strdup failed.");
1628     return (-1);
1629   }
1630   view->zones_num++;
1631
1632   return (0);
1633 } /* }}} int bind_config_add_view_zone */
1634
1635 static int bind_config_add_view (oconfig_item_t *ci) /* {{{ */
1636 {
1637   cb_view_t *tmp;
1638   int i;
1639
1640   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
1641   {
1642     WARNING ("bind plugin: `View' blocks need exactly one string argument.");
1643     return (-1);
1644   }
1645
1646   tmp = realloc (views, sizeof (*views) * (views_num + 1));
1647   if (tmp == NULL)
1648   {
1649     ERROR ("bind plugin: realloc failed.");
1650     return (-1);
1651   }
1652   views = tmp;
1653   tmp = views + views_num;
1654
1655   memset (tmp, 0, sizeof (*tmp));
1656   tmp->qtypes = 1;
1657   tmp->resolver_stats = 1;
1658   tmp->cacherrsets = 1;
1659   tmp->zones = NULL;
1660   tmp->zones_num = 0;
1661
1662   tmp->name = strdup (ci->values[0].value.string);
1663   if (tmp->name == NULL)
1664   {
1665     ERROR ("bind plugin: strdup failed.");
1666     sfree (views);
1667     return (-1);
1668   }
1669
1670   for (i = 0; i < ci->children_num; i++)
1671   {
1672     oconfig_item_t *child = ci->children + i;
1673
1674     if (strcasecmp ("QTypes", child->key) == 0)
1675       bind_config_set_bool ("QTypes", &tmp->qtypes, child);
1676     else if (strcasecmp ("ResolverStats", child->key) == 0)
1677       bind_config_set_bool ("ResolverStats", &tmp->resolver_stats, child);
1678     else if (strcasecmp ("CacheRRSets", child->key) == 0)
1679       bind_config_set_bool ("CacheRRSets", &tmp->cacherrsets, child);
1680     else if (strcasecmp ("Zone", child->key) == 0)
1681       bind_config_add_view_zone (tmp, child);
1682     else
1683     {
1684       WARNING ("bind plugin: Unknown configuration option "
1685           "`%s' in view `%s' will be ignored.", child->key, tmp->name);
1686     }
1687   } /* for (i = 0; i < ci->children_num; i++) */
1688
1689   views_num++;
1690   return (0);
1691 } /* }}} int bind_config_add_view */
1692
1693 static int bind_config (oconfig_item_t *ci) /* {{{ */
1694 {
1695   int i;
1696
1697   for (i = 0; i < ci->children_num; i++)
1698   {
1699     oconfig_item_t *child = ci->children + i;
1700
1701     if (strcasecmp ("Url", child->key) == 0) {
1702       if ((child->values_num != 1) || (child->values[0].type != OCONFIG_TYPE_STRING))
1703       {
1704         WARNING ("bind plugin: The `Url' option needs "
1705                  "exactly one string argument.");
1706         return (-1);
1707       }
1708
1709       sfree (url);
1710       url = strdup (child->values[0].value.string);
1711     } else if (strcasecmp ("OpCodes", child->key) == 0)
1712       bind_config_set_bool ("OpCodes", &global_opcodes, child);
1713     else if (strcasecmp ("QTypes", child->key) == 0)
1714       bind_config_set_bool ("QTypes", &global_qtypes, child);
1715     else if (strcasecmp ("ServerStats", child->key) == 0)
1716       bind_config_set_bool ("ServerStats", &global_server_stats, child);
1717     else if (strcasecmp ("ZoneMaintStats", child->key) == 0)
1718       bind_config_set_bool ("ZoneMaintStats", &global_zone_maint_stats, child);
1719     else if (strcasecmp ("ResolverStats", child->key) == 0)
1720       bind_config_set_bool ("ResolverStats", &global_resolver_stats, child);
1721     else if (strcasecmp ("MemoryStats", child->key) == 0)
1722       bind_config_set_bool ("MemoryStats", &global_memory_stats, child);
1723     else if (strcasecmp ("View", child->key) == 0)
1724       bind_config_add_view (child);
1725     else if (strcasecmp ("ParseTime", child->key) == 0)
1726       cf_util_get_boolean (child, &config_parse_time);
1727     else if (strcasecmp ("Timeout", child->key) == 0)
1728       cf_util_get_int (child, &timeout);
1729     else
1730     {
1731       WARNING ("bind plugin: Unknown configuration option "
1732           "`%s' will be ignored.", child->key);
1733     }
1734   }
1735
1736   return (0);
1737 } /* }}} int bind_config */
1738
1739 static int bind_init (void) /* {{{ */
1740 {
1741   if (curl != NULL)
1742     return (0);
1743
1744   curl = curl_easy_init ();
1745   if (curl == NULL)
1746   {
1747     ERROR ("bind plugin: bind_init: curl_easy_init failed.");
1748     return (-1);
1749   }
1750
1751   curl_easy_setopt (curl, CURLOPT_NOSIGNAL, 1L);
1752   curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, bind_curl_callback);
1753   curl_easy_setopt (curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
1754   curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, bind_curl_error);
1755   curl_easy_setopt (curl, CURLOPT_URL, (url != NULL) ? url : BIND_DEFAULT_URL);
1756   curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1L);
1757   curl_easy_setopt (curl, CURLOPT_MAXREDIRS, 50L);
1758 #ifdef HAVE_CURLOPT_TIMEOUT_MS
1759   curl_easy_setopt (curl, CURLOPT_TIMEOUT_MS, (timeout >= 0) ?
1760       (long) timeout : (long) CDTIME_T_TO_MS(plugin_get_interval()));
1761 #endif
1762
1763
1764   return (0);
1765 } /* }}} int bind_init */
1766
1767 static int bind_read (void) /* {{{ */
1768 {
1769   int status;
1770
1771   if (curl == NULL)
1772   {
1773     ERROR ("bind plugin: I don't have a CURL object.");
1774     return (-1);
1775   }
1776
1777   bind_buffer_fill = 0;
1778   if (curl_easy_perform (curl) != CURLE_OK)
1779   {
1780     ERROR ("bind plugin: curl_easy_perform failed: %s",
1781         bind_curl_error);
1782     return (-1);
1783   }
1784
1785   status = bind_xml (bind_buffer);
1786   if (status != 0)
1787     return (-1);
1788   else
1789     return (0);
1790 } /* }}} int bind_read */
1791
1792 static int bind_shutdown (void) /* {{{ */
1793 {
1794   if (curl != NULL)
1795   {
1796     curl_easy_cleanup (curl);
1797     curl = NULL;
1798   }
1799
1800   return (0);
1801 } /* }}} int bind_shutdown */
1802
1803 void module_register (void)
1804 {
1805   plugin_register_complex_config ("bind", bind_config);
1806   plugin_register_init ("bind", bind_init);
1807   plugin_register_read ("bind", bind_read);
1808   plugin_register_shutdown ("bind", bind_shutdown);
1809 } /* void module_register */
1810
1811 /* vim: set sw=2 sts=2 ts=8 et fdm=marker : */