write_redis: remove unused variable from wr_write()
[collectd.git] / src / powerdns.c
1 /**
2  * collectd - src/powerdns.c
3  * Copyright (C) 2007-2008  C-Ware, Inc.
4  * Copyright (C) 2008       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  * Author:
20  *   Luke Heberling <lukeh at c-ware.com>
21  *   Florian Forster <octo at verplant.org>
22  *
23  * DESCRIPTION
24  *   Queries a PowerDNS control socket for statistics
25  **/
26
27 #include "collectd.h"
28 #include "common.h"
29 #include "plugin.h"
30 #include "configfile.h"
31 #include "utils_llist.h"
32
33 #include <sys/stat.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <errno.h>
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <sys/un.h>
42
43 #ifndef UNIX_PATH_MAX
44 # define UNIX_PATH_MAX sizeof (((struct sockaddr_un *)0)->sun_path)
45 #endif
46 #define FUNC_ERROR(func) do { char errbuf[1024]; ERROR ("powerdns plugin: %s failed: %s", func, sstrerror (errno, errbuf, sizeof (errbuf))); } while (0)
47
48 #define SERVER_SOCKET  LOCALSTATEDIR"/run/pdns.controlsocket"
49 #define SERVER_COMMAND "SHOW * \n"
50
51 #define RECURSOR_SOCKET  LOCALSTATEDIR"/run/pdns_recursor.controlsocket"
52 #define RECURSOR_COMMAND "get noerror-answers nxdomain-answers " \
53   "servfail-answers sys-msec user-msec qa-latency cache-entries cache-hits " \
54   "cache-misses questions\n"
55
56 struct list_item_s;
57 typedef struct list_item_s list_item_t;
58
59 struct list_item_s
60 {
61   enum
62   {
63     SRV_AUTHORITATIVE,
64     SRV_RECURSOR
65   } server_type;
66   int (*func) (list_item_t *item);
67   char *instance;
68
69   char **fields;
70   int fields_num;
71   char *command;
72
73   struct sockaddr_un sockaddr;
74   int socktype;
75 };
76
77 struct statname_lookup_s
78 {
79   char *name;
80   char *type;
81   char *type_instance;
82 };
83 typedef struct statname_lookup_s statname_lookup_t;
84
85 /* Description of statistics returned by the recursor: {{{
86 all-outqueries      counts the number of outgoing UDP queries since starting
87 answers0-1          counts the number of queries answered within 1 millisecond
88 answers100-1000     counts the number of queries answered within 1 second
89 answers10-100       counts the number of queries answered within 100 milliseconds
90 answers1-10         counts the number of queries answered within 10 milliseconds
91 answers-slow        counts the number of queries answered after 1 second
92 cache-entries       shows the number of entries in the cache
93 cache-hits          counts the number of cache hits since starting
94 cache-misses        counts the number of cache misses since starting
95 chain-resends       number of queries chained to existing outstanding query
96 client-parse-errors counts number of client packets that could not be parsed
97 concurrent-queries  shows the number of MThreads currently running
98 dlg-only-drops      number of records dropped because of delegation only setting
99 negcache-entries    shows the number of entries in the Negative answer cache
100 noerror-answers     counts the number of times it answered NOERROR since starting
101 nsspeeds-entries    shows the number of entries in the NS speeds map
102 nsset-invalidations number of times an nsset was dropped because it no longer worked
103 nxdomain-answers    counts the number of times it answered NXDOMAIN since starting
104 outgoing-timeouts   counts the number of timeouts on outgoing UDP queries since starting
105 qa-latency          shows the current latency average
106 questions           counts all End-user initiated queries with the RD bit set
107 resource-limits     counts number of queries that could not be performed because of resource limits
108 server-parse-errors counts number of server replied packets that could not be parsed
109 servfail-answers    counts the number of times it answered SERVFAIL since starting
110 spoof-prevents      number of times PowerDNS considered itself spoofed, and dropped the data
111 sys-msec            number of CPU milliseconds spent in 'system' mode
112 tcp-client-overflow number of times an IP address was denied TCP access because it already had too many connections
113 tcp-outqueries      counts the number of outgoing TCP queries since starting
114 tcp-questions       counts all incoming TCP queries (since starting)
115 throttled-out       counts the number of throttled outgoing UDP queries since starting
116 throttle-entries    shows the number of entries in the throttle map
117 unauthorized-tcp    number of TCP questions denied because of allow-from restrictions
118 unauthorized-udp    number of UDP questions denied because of allow-from restrictions
119 unexpected-packets  number of answers from remote servers that were unexpected (might point to spoofing)
120 uptime              number of seconds process has been running (since 3.1.5)
121 user-msec           number of CPU milliseconds spent in 'user' mode
122 }}} */
123
124 const char* const default_server_fields[] = /* {{{ */
125 {
126   "latency"
127   "packetcache-hit",
128   "packetcache-miss",
129   "packetcache-size",
130   "query-cache-hit",
131   "query-cache-miss",
132   "recursing-answers",
133   "recursing-questions",
134   "tcp-answers",
135   "tcp-queries",
136   "udp-answers",
137   "udp-queries",
138 }; /* }}} */
139 int default_server_fields_num = STATIC_ARRAY_SIZE (default_server_fields);
140
141 statname_lookup_t lookup_table[] = /* {{{ */
142 {
143   /*********************
144    * Server statistics *
145    *********************/
146   /* Questions */
147   {"recursing-questions",    "dns_question", "recurse"},
148   {"tcp-queries",            "dns_question", "tcp"},
149   {"udp-queries",            "dns_question", "udp"},
150
151   /* Answers */
152   {"recursing-answers",      "dns_answer",   "recurse"},
153   {"tcp-answers",            "dns_answer",   "tcp"},
154   {"udp-answers",            "dns_answer",   "udp"},
155
156   /* Cache stuff */
157   {"packetcache-hit",        "cache_result", "packet-hit"},
158   {"packetcache-miss",       "cache_result", "packet-miss"},
159   {"packetcache-size",       "cache_size",   "packet"},
160   {"query-cache-hit",        "cache_result", "query-hit"},
161   {"query-cache-miss",       "cache_result", "query-miss"},
162
163   /* Latency */
164   {"latency",                "latency",      NULL},
165
166   /* Other stuff.. */
167   {"corrupt-packets",        "ipt_packets",  "corrupt"},
168   {"deferred-cache-inserts", "counter",      "cache-deferred_insert"},
169   {"deferred-cache-lookup",  "counter",      "cache-deferred_lookup"},
170   {"qsize-a",                "cache_size",   "answers"},
171   {"qsize-q",                "cache_size",   "questions"},
172   {"servfail-packets",       "ipt_packets",  "servfail"},
173   {"timedout-packets",       "ipt_packets",  "timeout"},
174   {"udp4-answers",           "dns_answer",   "udp4"},
175   {"udp4-queries",           "dns_question", "queries-udp4"},
176   {"udp6-answers",           "dns_answer",   "udp6"},
177   {"udp6-queries",           "dns_question", "queries-udp6"},
178
179   /***********************
180    * Recursor statistics *
181    ***********************/
182   /* Answers by return code */
183   {"noerror-answers",     "dns_rcode",    "NOERROR"},
184   {"nxdomain-answers",    "dns_rcode",    "NXDOMAIN"},
185   {"servfail-answers",    "dns_rcode",    "SERVFAIL"},
186
187   /* CPU utilization */
188   {"sys-msec",            "cpu",          "system"},
189   {"user-msec",           "cpu",          "user"},
190
191   /* Question-to-answer latency */
192   {"qa-latency",          "latency",      NULL},
193
194   /* Cache */
195   {"cache-entries",       "cache_size",   NULL},
196   {"cache-hits",          "cache_result", "hit"},
197   {"cache-misses",        "cache_result", "miss"},
198
199   /* Total number of questions.. */
200   {"questions",           "dns_qtype",    "total"},
201
202   /* All the other stuff.. */
203   {"all-outqueries",      "dns_question", "outgoing"},
204   {"answers0-1",          "dns_answer",   "0_1"},
205   {"answers1-10",         "dns_answer",   "1_10"},
206   {"answers10-100",       "dns_answer",   "10_100"},
207   {"answers100-1000",     "dns_answer",   "100_1000"},
208   {"answers-slow",        "dns_answer",   "slow"},
209   {"chain-resends",       "dns_question", "chained"},
210   {"client-parse-errors", "counter",      "drops-client_parse_error"},
211   {"concurrent-queries",  "dns_question", "concurrent"},
212   {"dlg-only-drops",      "counter",      "drops-delegation_only"},
213   {"negcache-entries",    "cache_size",   "negative"},
214   {"nsspeeds-entries",    "gauge",        "entries-ns_speeds"},
215   {"nsset-invalidations", "counter",      "ns_set_invalidation"},
216   {"outgoing-timeouts",   "counter",      "drops-timeout_outgoing"},
217   {"resource-limits",     "counter",      "drops-resource_limit"},
218   {"server-parse-errors", "counter",      "drops-server_parse_error"},
219   {"spoof-prevents",      "counter",      "drops-spoofed"},
220   {"tcp-client-overflow", "counter",      "denied-client_overflow_tcp"},
221   {"tcp-outqueries",      "dns_question", "outgoing-tcp"},
222   {"tcp-questions",       "dns_question", "incoming-tcp"},
223   {"throttled-out",       "dns_question", "outgoing-throttled"},
224   {"throttle-entries",    "gauge",        "entries-throttle"},
225   {"unauthorized-tcp",    "counter",      "denied-unauthorized_tcp"},
226   {"unauthorized-udp",    "counter",      "denied-unauthorized_udp"},
227   {"unexpected-packets",  "dns_answer",   "unexpected"}
228   /* {"uptime", "", ""} */
229 }; /* }}} */
230 int lookup_table_length = STATIC_ARRAY_SIZE (lookup_table);
231
232 static llist_t *list = NULL;
233
234 #define PDNS_LOCAL_SOCKPATH LOCALSTATEDIR"/run/"PACKAGE_NAME"-powerdns"
235 static char *local_sockpath = NULL;
236
237 /* TODO: Do this before 4.4:
238  * - Recursor:
239  *   - Complete list of known pdns -> collectd mappings.
240  * - Update the collectd.conf(5) manpage.
241  *
242  * -octo
243  */
244
245 /* <http://doc.powerdns.com/recursor-stats.html> */
246 static void submit (const char *plugin_instance, /* {{{ */
247     const char *pdns_type, const char *value)
248 {
249   value_list_t vl = VALUE_LIST_INIT;
250   value_t values[1];
251
252   const char *type = NULL;
253   const char *type_instance = NULL;
254   const data_set_t *ds;
255
256   int i;
257
258   for (i = 0; i < lookup_table_length; i++)
259     if (strcmp (lookup_table[i].name, pdns_type) == 0)
260       break;
261
262   if (i >= lookup_table_length)
263   {
264     INFO ("powerdns plugin: submit: Not found in lookup table: %s = %s;",
265         pdns_type, value);
266     return;
267   }
268
269   if (lookup_table[i].type == NULL)
270     return;
271
272   type = lookup_table[i].type;
273   type_instance = lookup_table[i].type_instance;
274
275   ds = plugin_get_ds (type);
276   if (ds == NULL)
277   {
278     ERROR ("powerdns plugin: The lookup table returned type `%s', "
279         "but I cannot find it via `plugin_get_ds'.",
280         type);
281     return;
282   }
283
284   if (ds->ds_num != 1)
285   {
286     ERROR ("powerdns plugin: type `%s' has %i data sources, "
287         "but I can only handle one.",
288         type, ds->ds_num);
289     return;
290   }
291
292   if (0 != parse_value (value, &values[0], ds->ds[0].type))
293   {
294     ERROR ("powerdns plugin: Cannot convert `%s' "
295         "to a number.", value);
296     return;
297   }
298
299   vl.values = values;
300   vl.values_len = 1;
301   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
302   sstrncpy (vl.plugin, "powerdns", sizeof (vl.plugin));
303   sstrncpy (vl.type, type, sizeof (vl.type));
304   if (type_instance != NULL)
305     sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
306   sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
307
308   plugin_dispatch_values (&vl);
309 } /* }}} static void submit */
310
311 static int powerdns_get_data_dgram (list_item_t *item, /* {{{ */
312     char **ret_buffer,
313     size_t *ret_buffer_size)
314 {
315   int sd;
316   int status;
317
318   char temp[4096];
319   char *buffer = NULL;
320   size_t buffer_size = 0;
321
322   struct sockaddr_un sa_unix;
323
324   struct timeval stv_timeout;
325   cdtime_t cdt_timeout;
326
327   sd = socket (PF_UNIX, item->socktype, 0);
328   if (sd < 0)
329   {
330     FUNC_ERROR ("socket");
331     return (-1);
332   }
333
334   memset (&sa_unix, 0, sizeof (sa_unix));
335   sa_unix.sun_family = AF_UNIX;
336   sstrncpy (sa_unix.sun_path,
337       (local_sockpath != NULL) ? local_sockpath : PDNS_LOCAL_SOCKPATH,
338       sizeof (sa_unix.sun_path));
339
340   status = unlink (sa_unix.sun_path);
341   if ((status != 0) && (errno != ENOENT))
342   {
343     FUNC_ERROR ("unlink");
344     close (sd);
345     return (-1);
346   }
347
348   do /* while (0) */
349   {
350     /* We need to bind to a specific path, because this is a datagram socket
351      * and otherwise the daemon cannot answer. */
352     status = bind (sd, (struct sockaddr *) &sa_unix, sizeof (sa_unix));
353     if (status != 0)
354     {
355       FUNC_ERROR ("bind");
356       break;
357     }
358
359     /* Make the socket writeable by the daemon.. */
360     status = chmod (sa_unix.sun_path, 0666);
361     if (status != 0)
362     {
363       FUNC_ERROR ("chmod");
364       break;
365     }
366
367     cdt_timeout = plugin_get_interval () * 3 / 4;
368     if (cdt_timeout < TIME_T_TO_CDTIME_T (2))
369       cdt_timeout = TIME_T_TO_CDTIME_T (2);
370
371     CDTIME_T_TO_TIMEVAL (cdt_timeout, &stv_timeout);
372
373     status = setsockopt (sd, SOL_SOCKET, SO_RCVTIMEO, &stv_timeout, sizeof (stv_timeout));
374     if (status != 0)
375     {
376       FUNC_ERROR ("setsockopt");
377       break;
378     }
379
380     status = connect (sd, (struct sockaddr *) &item->sockaddr,
381         sizeof (item->sockaddr));
382     if (status != 0)
383     {
384       FUNC_ERROR ("connect");
385       break;
386     }
387
388     status = send (sd, item->command, strlen (item->command), 0);
389     if (status < 0)
390     {
391       FUNC_ERROR ("send");
392       break;
393     }
394
395     status = recv (sd, temp, sizeof (temp), /* flags = */ 0);
396     if (status < 0)
397     {
398       FUNC_ERROR ("recv");
399       break;
400     }
401     buffer_size = status + 1;
402     status = 0;
403   } while (0);
404
405   close (sd);
406   unlink (sa_unix.sun_path);
407
408   if (status != 0)
409     return (-1);
410
411   assert (buffer_size > 0);
412   buffer = (char *) malloc (buffer_size);
413   if (buffer == NULL)
414   {
415     FUNC_ERROR ("malloc");
416     return (-1);
417   }
418
419   memcpy (buffer, temp, buffer_size - 1);
420   buffer[buffer_size - 1] = 0;
421
422   *ret_buffer = buffer;
423   *ret_buffer_size = buffer_size;
424
425   return (0);
426 } /* }}} int powerdns_get_data_dgram */
427
428 static int powerdns_get_data_stream (list_item_t *item, /* {{{ */
429     char **ret_buffer,
430     size_t *ret_buffer_size)
431 {
432   int sd;
433   int status;
434
435   char temp[4096];
436   char *buffer = NULL;
437   size_t buffer_size = 0;
438
439   sd = socket (PF_UNIX, item->socktype, 0);
440   if (sd < 0)
441   {
442     FUNC_ERROR ("socket");
443     return (-1);
444   }
445
446   struct timeval timeout;
447   timeout.tv_sec=5;
448   timeout.tv_usec=0;
449   status = setsockopt (sd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof (timeout));
450   if (status != 0)
451   {
452     FUNC_ERROR ("setsockopt");
453     close (sd);
454     return (-1);
455   }
456
457   status = connect (sd, (struct sockaddr *) &item->sockaddr,
458       sizeof (item->sockaddr));
459   if (status != 0)
460   {
461     FUNC_ERROR ("connect");
462     close (sd);
463     return (-1);
464   }
465
466   /* strlen + 1, because we need to send the terminating NULL byte, too. */
467   status = send (sd, item->command, strlen (item->command) + 1,
468       /* flags = */ 0);
469   if (status < 0)
470   {
471     FUNC_ERROR ("send");
472     close (sd);
473     return (-1);
474   }
475
476   while (42)
477   {
478     char *buffer_new;
479
480     status = recv (sd, temp, sizeof (temp), /* flags = */ 0);
481     if (status < 0)
482     {
483       FUNC_ERROR ("recv");
484       break;
485     }
486     else if (status == 0)
487       break;
488
489     buffer_new = (char *) realloc (buffer, buffer_size + status + 1);
490     if (buffer_new == NULL)
491     {
492       FUNC_ERROR ("realloc");
493       status = -1;
494       break;
495     }
496     buffer = buffer_new;
497
498     memcpy (buffer + buffer_size, temp, status);
499     buffer_size += status;
500     buffer[buffer_size] = 0;
501   } /* while (42) */
502   close (sd);
503
504   if (status < 0)
505   {
506     sfree (buffer);
507   }
508   else
509   {
510     assert (status == 0);
511     *ret_buffer = buffer;
512     *ret_buffer_size = buffer_size;
513   }
514
515   return (status);
516 } /* }}} int powerdns_get_data_stream */
517
518 static int powerdns_get_data (list_item_t *item, char **ret_buffer,
519     size_t *ret_buffer_size)
520 {
521   if (item->socktype == SOCK_DGRAM)
522     return (powerdns_get_data_dgram (item, ret_buffer, ret_buffer_size));
523   else if (item->socktype == SOCK_STREAM)
524     return (powerdns_get_data_stream (item, ret_buffer, ret_buffer_size));
525   else
526   {
527     ERROR ("powerdns plugin: Unknown socket type: %i", (int) item->socktype);
528     return (-1);
529   }
530 } /* int powerdns_get_data */
531
532 static int powerdns_read_server (list_item_t *item) /* {{{ */
533 {
534   char *buffer = NULL;
535   size_t buffer_size = 0;
536   int status;
537
538   char *dummy;
539   char *saveptr;
540
541   char *key;
542   char *value;
543
544   const char* const *fields;
545   int fields_num;
546
547   if (item->command == NULL)
548     item->command = strdup (SERVER_COMMAND);
549   if (item->command == NULL)
550   {
551     ERROR ("powerdns plugin: strdup failed.");
552     return (-1);
553   }
554
555   status = powerdns_get_data (item, &buffer, &buffer_size);
556   if (status != 0)
557     return (-1);
558
559   if (item->fields_num != 0)
560   {
561     fields = (const char* const *) item->fields;
562     fields_num = item->fields_num;
563   }
564   else
565   {
566     fields = default_server_fields;
567     fields_num = default_server_fields_num;
568   }
569
570   assert (fields != NULL);
571   assert (fields_num > 0);
572
573   /* corrupt-packets=0,deferred-cache-inserts=0,deferred-cache-lookup=0,latency=0,packetcache-hit=0,packetcache-miss=0,packetcache-size=0,qsize-q=0,query-cache-hit=0,query-cache-miss=0,recursing-answers=0,recursing-questions=0,servfail-packets=0,tcp-answers=0,tcp-queries=0,timedout-packets=0,udp-answers=0,udp-queries=0,udp4-answers=0,udp4-queries=0,udp6-answers=0,udp6-queries=0, */
574   dummy = buffer;
575   saveptr = NULL;
576   while ((key = strtok_r (dummy, ",", &saveptr)) != NULL)
577   {
578     int i;
579
580     dummy = NULL;
581
582     value = strchr (key, '=');
583     if (value == NULL)
584       break;
585
586     *value = '\0';
587     value++;
588
589     if (value[0] == '\0')
590       continue;
591
592     /* Check if this item was requested. */
593     for (i = 0; i < fields_num; i++)
594       if (strcasecmp (key, fields[i]) == 0)
595         break;
596     if (i >= fields_num)
597       continue;
598
599     submit (item->instance, key, value);
600   } /* while (strtok_r) */
601
602   sfree (buffer);
603
604   return (0);
605 } /* }}} int powerdns_read_server */
606
607 /*
608  * powerdns_update_recursor_command
609  *
610  * Creates a string that holds the command to be sent to the recursor. This
611  * string is stores in the `command' member of the `list_item_t' passed to the
612  * function. This function is called by `powerdns_read_recursor'.
613  */
614 static int powerdns_update_recursor_command (list_item_t *li) /* {{{ */
615 {
616   char buffer[4096];
617   int status;
618
619   if (li == NULL)
620     return (0);
621
622   if (li->fields_num < 1)
623   {
624     sstrncpy (buffer, RECURSOR_COMMAND, sizeof (buffer));
625   }
626   else
627   {
628     sstrncpy (buffer, "get ", sizeof (buffer));
629     status = strjoin (&buffer[strlen("get ")], sizeof (buffer) - strlen ("get "),
630         li->fields, li->fields_num,
631         /* seperator = */ " ");
632     if (status < 0)
633     {
634       ERROR ("powerdns plugin: strjoin failed.");
635       return (-1);
636     }
637     buffer[sizeof (buffer) - 1] = 0;
638     int i = strlen (buffer);
639     if (i < sizeof (buffer) - 2)
640     {
641       buffer[i++] = ' ';
642       buffer[i++] = '\n';
643       buffer[i++] = '\0';
644     }
645   }
646
647   buffer[sizeof (buffer) - 1] = 0;
648   li->command = strdup (buffer);
649   if (li->command == NULL)
650   {
651     ERROR ("powerdns plugin: strdup failed.");
652     return (-1);
653   }
654
655   return (0);
656 } /* }}} int powerdns_update_recursor_command */
657
658 static int powerdns_read_recursor (list_item_t *item) /* {{{ */
659 {
660   char *buffer = NULL;
661   size_t buffer_size = 0;
662   int status;
663
664   char *dummy;
665
666   char *keys_list;
667   char *key;
668   char *key_saveptr;
669   char *value;
670   char *value_saveptr;
671
672   if (item->command == NULL)
673   {
674     status = powerdns_update_recursor_command (item);
675     if (status != 0)
676     {
677       ERROR ("powerdns plugin: powerdns_update_recursor_command failed.");
678       return (-1);
679     }
680
681     DEBUG ("powerdns plugin: powerdns_read_recursor: item->command = %s;",
682         item->command);
683   }
684   assert (item->command != NULL);
685
686   status = powerdns_get_data (item, &buffer, &buffer_size);
687   if (status != 0)
688   {
689     ERROR ("powerdns plugin: powerdns_get_data failed.");
690     return (-1);
691   }
692
693   keys_list = strdup (item->command);
694   if (keys_list == NULL)
695   {
696     FUNC_ERROR ("strdup");
697     sfree (buffer);
698     return (-1);
699   }
700
701   key_saveptr = NULL;
702   value_saveptr = NULL;
703
704   /* Skip the `get' at the beginning */
705   strtok_r (keys_list, " \t", &key_saveptr);
706
707   dummy = buffer;
708   while ((value = strtok_r (dummy, " \t\n\r", &value_saveptr)) != NULL)
709   {
710     dummy = NULL;
711
712     key = strtok_r (NULL, " \t", &key_saveptr);
713     if (key == NULL)
714       break;
715
716     submit (item->instance, key, value);
717   } /* while (strtok_r) */
718
719   sfree (buffer);
720   sfree (keys_list);
721
722   return (0);
723 } /* }}} int powerdns_read_recursor */
724
725 static int powerdns_config_add_collect (list_item_t *li, /* {{{ */
726     oconfig_item_t *ci)
727 {
728   int i;
729   char **temp;
730
731   if (ci->values_num < 1)
732   {
733     WARNING ("powerdns plugin: The `Collect' option needs "
734         "at least one argument.");
735     return (-1);
736   }
737
738   for (i = 0; i < ci->values_num; i++)
739     if (ci->values[i].type != OCONFIG_TYPE_STRING)
740     {
741       WARNING ("powerdns plugin: Only string arguments are allowed to "
742           "the `Collect' option.");
743       return (-1);
744     }
745
746   temp = (char **) realloc (li->fields,
747       sizeof (char *) * (li->fields_num + ci->values_num));
748   if (temp == NULL)
749   {
750     WARNING ("powerdns plugin: realloc failed.");
751     return (-1);
752   }
753   li->fields = temp;
754
755   for (i = 0; i < ci->values_num; i++)
756   {
757     li->fields[li->fields_num] = strdup (ci->values[i].value.string);
758     if (li->fields[li->fields_num] == NULL)
759     {
760       WARNING ("powerdns plugin: strdup failed.");
761       continue;
762     }
763     li->fields_num++;
764   }
765
766   /* Invalidate a previously computed command */
767   sfree (li->command);
768
769   return (0);
770 } /* }}} int powerdns_config_add_collect */
771
772 static int powerdns_config_add_server (oconfig_item_t *ci) /* {{{ */
773 {
774   char *socket_temp;
775
776   list_item_t *item;
777   int status;
778   int i;
779
780   if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
781   {
782     WARNING ("powerdns plugin: `%s' needs exactly one string argument.",
783         ci->key);
784     return (-1);
785   }
786
787   item = (list_item_t *) malloc (sizeof (list_item_t));
788   if (item == NULL)
789   {
790     ERROR ("powerdns plugin: malloc failed.");
791     return (-1);
792   }
793   memset (item, '\0', sizeof (list_item_t));
794
795   item->instance = strdup (ci->values[0].value.string);
796   if (item->instance == NULL)
797   {
798     ERROR ("powerdns plugin: strdup failed.");
799     sfree (item);
800     return (-1);
801   }
802
803   /*
804    * Set default values for the members of list_item_t
805    */
806   if (strcasecmp ("Server", ci->key) == 0)
807   {
808     item->server_type = SRV_AUTHORITATIVE;
809     item->func = powerdns_read_server;
810     item->socktype = SOCK_STREAM;
811     socket_temp = strdup (SERVER_SOCKET);
812   }
813   else if (strcasecmp ("Recursor", ci->key) == 0)
814   {
815     item->server_type = SRV_RECURSOR;
816     item->func = powerdns_read_recursor;
817     item->socktype = SOCK_DGRAM;
818     socket_temp = strdup (RECURSOR_SOCKET);
819   }
820   else
821   {
822     /* We must never get here.. */
823     assert (0);
824     return (-1);
825   }
826
827   status = 0;
828   for (i = 0; i < ci->children_num; i++)
829   {
830     oconfig_item_t *option = ci->children + i;
831
832     if (strcasecmp ("Collect", option->key) == 0)
833       status = powerdns_config_add_collect (item, option);
834     else if (strcasecmp ("Socket", option->key) == 0)
835       status = cf_util_get_string (option, &socket_temp);
836     else
837     {
838       ERROR ("powerdns plugin: Option `%s' not allowed here.", option->key);
839       status = -1;
840     }
841
842     if (status != 0)
843       break;
844   }
845
846   while (status == 0)
847   {
848     llentry_t *e;
849
850     if (socket_temp == NULL)
851     {
852       ERROR ("powerdns plugin: socket_temp == NULL.");
853       status = -1;
854       break;
855     }
856
857     item->sockaddr.sun_family = AF_UNIX;
858     sstrncpy (item->sockaddr.sun_path, socket_temp,
859       sizeof (item->sockaddr.sun_path));
860
861     e = llentry_create (item->instance, item);
862     if (e == NULL)
863     {
864       ERROR ("powerdns plugin: llentry_create failed.");
865       status = -1;
866       break;
867     }
868     llist_append (list, e);
869
870     break;
871   }
872
873   if (status != 0)
874   {
875     sfree (socket_temp);
876     sfree (item);
877     return (-1);
878   }
879
880   DEBUG ("powerdns plugin: Add server: instance = %s;", item->instance);
881
882   sfree (socket_temp);
883   return (0);
884 } /* }}} int powerdns_config_add_server */
885
886 static int powerdns_config (oconfig_item_t *ci) /* {{{ */
887 {
888   int i;
889
890   DEBUG ("powerdns plugin: powerdns_config (ci = %p);", (void *) ci);
891
892   if (list == NULL)
893   {
894     list = llist_create ();
895
896     if (list == NULL)
897     {
898       ERROR ("powerdns plugin: `llist_create' failed.");
899       return (-1);
900     }
901   }
902
903   for (i = 0; i < ci->children_num; i++)
904   {
905     oconfig_item_t *option = ci->children + i;
906
907     if ((strcasecmp ("Server", option->key) == 0)
908         || (strcasecmp ("Recursor", option->key) == 0))
909       powerdns_config_add_server (option);
910     else if (strcasecmp ("LocalSocket", option->key) == 0)
911     {
912       if ((option->values_num != 1) || (option->values[0].type != OCONFIG_TYPE_STRING))
913       {
914         WARNING ("powerdns plugin: `%s' needs exactly one string argument.", option->key);
915       }
916       else
917       {
918         char *temp = strdup (option->values[0].value.string);
919         if (temp == NULL)
920           return (1);
921         sfree (local_sockpath);
922         local_sockpath = temp;
923       }
924     }
925     else
926     {
927       ERROR ("powerdns plugin: Option `%s' not allowed here.", option->key);
928     }
929   } /* for (i = 0; i < ci->children_num; i++) */
930
931   return (0);
932 } /* }}} int powerdns_config */
933
934 static int powerdns_read (void)
935 {
936   llentry_t *e;
937
938   for (e = llist_head (list); e != NULL; e = e->next)
939   {
940     list_item_t *item = e->value;
941     item->func (item);
942   }
943
944   return (0);
945 } /* static int powerdns_read */
946
947 static int powerdns_shutdown (void)
948 {
949   llentry_t *e;
950
951   if (list == NULL)
952     return (0);
953
954   for (e = llist_head (list); e != NULL; e = e->next)
955   {
956     list_item_t *item = (list_item_t *) e->value;
957     e->value = NULL;
958
959     sfree (item->instance);
960     sfree (item->command);
961     sfree (item);
962   }
963
964   llist_destroy (list);
965   list = NULL;
966
967   return (0);
968 } /* static int powerdns_shutdown */
969
970 void module_register (void)
971 {
972   plugin_register_complex_config ("powerdns", powerdns_config);
973   plugin_register_read ("powerdns", powerdns_read);
974   plugin_register_shutdown ("powerdns", powerdns_shutdown );
975 } /* void module_register */
976
977 /* vim: set sw=2 sts=2 ts=8 fdm=marker : */