Merge branch 'collectd-5.5'
[collectd.git] / src / daemon / configfile.c
1 /**
2  * collectd - src/configfile.c
3  * Copyright (C) 2005-2011  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  *   Sebastian tokkee Harl <sh at tokkee.org>
26  **/
27
28 #include "collectd.h"
29
30 #include "liboconfig/oconfig.h"
31
32 #include "common.h"
33 #include "plugin.h"
34 #include "configfile.h"
35 #include "types_list.h"
36 #include "filter_chain.h"
37
38 #if HAVE_WORDEXP_H
39 # include <wordexp.h>
40 #endif /* HAVE_WORDEXP_H */
41
42 #if HAVE_FNMATCH_H
43 # include <fnmatch.h>
44 #endif /* HAVE_FNMATCH_H */
45
46 #if HAVE_LIBGEN_H
47 # include <libgen.h>
48 #endif /* HAVE_LIBGEN_H */
49
50 #define ESCAPE_NULL(str) ((str) == NULL ? "(null)" : (str))
51
52 /*
53  * Private types
54  */
55 typedef struct cf_callback
56 {
57         const char  *type;
58         int  (*callback) (const char *, const char *);
59         const char **keys;
60         int    keys_num;
61         plugin_ctx_t ctx;
62         struct cf_callback *next;
63 } cf_callback_t;
64
65 typedef struct cf_complex_callback_s
66 {
67         char *type;
68         int (*callback) (oconfig_item_t *);
69         plugin_ctx_t ctx;
70         struct cf_complex_callback_s *next;
71 } cf_complex_callback_t;
72
73 typedef struct cf_value_map_s
74 {
75         char *key;
76         int (*func) (const oconfig_item_t *);
77 } cf_value_map_t;
78
79 typedef struct cf_global_option_s
80 {
81         char *key;
82         char *value;
83         char *def;
84 } cf_global_option_t;
85
86 /*
87  * Prototypes of callback functions
88  */
89 static int dispatch_value_typesdb (const oconfig_item_t *ci);
90 static int dispatch_value_plugindir (const oconfig_item_t *ci);
91 static int dispatch_loadplugin (const oconfig_item_t *ci);
92
93 /*
94  * Private variables
95  */
96 static cf_callback_t *first_callback = NULL;
97 static cf_complex_callback_t *complex_callback_head = NULL;
98
99 static cf_value_map_t cf_value_map[] =
100 {
101         {"TypesDB",    dispatch_value_typesdb},
102         {"PluginDir",  dispatch_value_plugindir},
103         {"LoadPlugin", dispatch_loadplugin}
104 };
105 static int cf_value_map_num = STATIC_ARRAY_SIZE (cf_value_map);
106
107 static cf_global_option_t cf_global_options[] =
108 {
109         {"BaseDir",     NULL, PKGLOCALSTATEDIR},
110         {"PIDFile",     NULL, PIDFILE},
111         {"Hostname",    NULL, NULL},
112         {"FQDNLookup",  NULL, "true"},
113         {"Interval",    NULL, NULL},
114         {"ReadThreads", NULL, "5"},
115         {"WriteThreads", NULL, "5"},
116         {"WriteQueueLimitHigh", NULL, NULL},
117         {"WriteQueueLimitLow", NULL, NULL},
118         {"Timeout",     NULL, "2"},
119         {"AutoLoadPlugin", NULL, "false"},
120         {"CollectInternalStats", NULL, "false"},
121         {"PreCacheChain",  NULL, "PreCache"},
122         {"PostCacheChain", NULL, "PostCache"},
123         {"MaxReadInterval", NULL, "86400"}
124 };
125 static int cf_global_options_num = STATIC_ARRAY_SIZE (cf_global_options);
126
127 static int cf_default_typesdb = 1;
128
129 /*
130  * Functions to handle register/unregister, search, and other plugin related
131  * stuff
132  */
133 static cf_callback_t *cf_search (const char *type)
134 {
135         cf_callback_t *cf_cb;
136
137         if (type == NULL)
138                 return (NULL);
139
140         for (cf_cb = first_callback; cf_cb != NULL; cf_cb = cf_cb->next)
141                 if (strcasecmp (cf_cb->type, type) == 0)
142                         break;
143
144         return (cf_cb);
145 }
146
147 static int cf_dispatch (const char *type, const char *orig_key,
148                 const char *orig_value)
149 {
150         cf_callback_t *cf_cb;
151         plugin_ctx_t old_ctx;
152         char *key;
153         char *value;
154         int ret;
155         int i;
156
157         DEBUG ("type = %s, key = %s, value = %s",
158                         ESCAPE_NULL(type),
159                         ESCAPE_NULL(orig_key),
160                         ESCAPE_NULL(orig_value));
161
162         if ((cf_cb = cf_search (type)) == NULL)
163         {
164                 WARNING ("Found a configuration for the `%s' plugin, but "
165                                 "the plugin isn't loaded or didn't register "
166                                 "a configuration callback.", type);
167                 return (-1);
168         }
169
170         if ((key = strdup (orig_key)) == NULL)
171                 return (1);
172         if ((value = strdup (orig_value)) == NULL)
173         {
174                 free (key);
175                 return (2);
176         }
177
178         ret = -1;
179
180         old_ctx = plugin_set_ctx (cf_cb->ctx);
181
182         for (i = 0; i < cf_cb->keys_num; i++)
183         {
184                 if ((cf_cb->keys[i] != NULL)
185                                 && (strcasecmp (cf_cb->keys[i], key) == 0))
186                 {
187                         ret = (*cf_cb->callback) (key, value);
188                         break;
189                 }
190         }
191
192         plugin_set_ctx (old_ctx);
193
194         if (i >= cf_cb->keys_num)
195                 WARNING ("Plugin `%s' did not register for value `%s'.", type, key);
196
197         free (key);
198         free (value);
199
200         DEBUG ("cf_dispatch: return (%i)", ret);
201
202         return (ret);
203 } /* int cf_dispatch */
204
205 static int dispatch_global_option (const oconfig_item_t *ci)
206 {
207         if (ci->values_num != 1)
208                 return (-1);
209         if (ci->values[0].type == OCONFIG_TYPE_STRING)
210                 return (global_option_set (ci->key, ci->values[0].value.string));
211         else if (ci->values[0].type == OCONFIG_TYPE_NUMBER)
212         {
213                 char tmp[128];
214                 ssnprintf (tmp, sizeof (tmp), "%lf", ci->values[0].value.number);
215                 return (global_option_set (ci->key, tmp));
216         }
217         else if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN)
218         {
219                 if (ci->values[0].value.boolean)
220                         return (global_option_set (ci->key, "true"));
221                 else
222                         return (global_option_set (ci->key, "false"));
223         }
224
225         return (-1);
226 } /* int dispatch_global_option */
227
228 static int dispatch_value_typesdb (const oconfig_item_t *ci)
229 {
230         int i = 0;
231
232         assert (strcasecmp (ci->key, "TypesDB") == 0);
233
234         cf_default_typesdb = 0;
235
236         if (ci->values_num < 1) {
237                 ERROR ("configfile: `TypesDB' needs at least one argument.");
238                 return (-1);
239         }
240
241         for (i = 0; i < ci->values_num; ++i)
242         {
243                 if (OCONFIG_TYPE_STRING != ci->values[i].type) {
244                         WARNING ("configfile: TypesDB: Skipping %i. argument which "
245                                         "is not a string.", i + 1);
246                         continue;
247                 }
248
249                 read_types_list (ci->values[i].value.string);
250         }
251         return (0);
252 } /* int dispatch_value_typesdb */
253
254 static int dispatch_value_plugindir (const oconfig_item_t *ci)
255 {
256         assert (strcasecmp (ci->key, "PluginDir") == 0);
257         
258         if (ci->values_num != 1)
259                 return (-1);
260         if (ci->values[0].type != OCONFIG_TYPE_STRING)
261                 return (-1);
262
263         plugin_set_dir (ci->values[0].value.string);
264         return (0);
265 }
266
267 static int dispatch_loadplugin (const oconfig_item_t *ci)
268 {
269         int i;
270         const char *name;
271         unsigned int flags = 0;
272         plugin_ctx_t ctx;
273         plugin_ctx_t old_ctx;
274         int ret_val;
275
276         assert (strcasecmp (ci->key, "LoadPlugin") == 0);
277
278         if (ci->values_num != 1)
279                 return (-1);
280         if (ci->values[0].type != OCONFIG_TYPE_STRING)
281                 return (-1);
282
283         name = ci->values[0].value.string;
284         if (strcmp ("libvirt", name) == 0)
285                 name = "virt";
286
287         /* default to the global interval set before loading this plugin */
288         memset (&ctx, 0, sizeof (ctx));
289         ctx.interval = cf_get_default_interval ();
290         ctx.flush_interval = 0;
291         ctx.flush_timeout = 0;
292
293         for (i = 0; i < ci->children_num; ++i)
294         {
295                 oconfig_item_t *child = ci->children + i;
296
297                 if (strcasecmp("Globals", child->key) == 0)
298                         cf_util_get_flag (child, &flags, PLUGIN_FLAGS_GLOBAL);
299                 else if (strcasecmp ("Interval", child->key) == 0)
300                         cf_util_get_cdtime (child, &ctx.interval);
301                 else if (strcasecmp ("FlushInterval", child->key) == 0)
302                         cf_util_get_cdtime (child, &ctx.flush_interval);
303                 else if (strcasecmp ("FlushTimeout", child->key) == 0)
304                         cf_util_get_cdtime (child, &ctx.flush_timeout);
305                 else {
306                         WARNING("Ignoring unknown LoadPlugin option \"%s\" "
307                                         "for plugin \"%s\"",
308                                         child->key, ci->values[0].value.string);
309                 }
310         }
311
312         old_ctx = plugin_set_ctx (ctx);
313         ret_val = plugin_load (name, (uint32_t) flags);
314         /* reset to the "global" context */
315         plugin_set_ctx (old_ctx);
316
317         return (ret_val);
318 } /* int dispatch_value_loadplugin */
319
320 static int dispatch_value_plugin (const char *plugin, oconfig_item_t *ci)
321 {
322         char  buffer[4096];
323         char *buffer_ptr;
324         int   buffer_free;
325         int i;
326
327         buffer_ptr = buffer;
328         buffer_free = sizeof (buffer);
329
330         for (i = 0; i < ci->values_num; i++)
331         {
332                 int status = -1;
333
334                 if (ci->values[i].type == OCONFIG_TYPE_STRING)
335                         status = ssnprintf (buffer_ptr, buffer_free, " %s",
336                                         ci->values[i].value.string);
337                 else if (ci->values[i].type == OCONFIG_TYPE_NUMBER)
338                         status = ssnprintf (buffer_ptr, buffer_free, " %lf",
339                                         ci->values[i].value.number);
340                 else if (ci->values[i].type == OCONFIG_TYPE_BOOLEAN)
341                         status = ssnprintf (buffer_ptr, buffer_free, " %s",
342                                         ci->values[i].value.boolean
343                                         ? "true" : "false");
344
345                 if ((status < 0) || (status >= buffer_free))
346                         return (-1);
347                 buffer_free -= status;
348                 buffer_ptr  += status;
349         }
350         /* skip the initial space */
351         buffer_ptr = buffer + 1;
352
353         return (cf_dispatch (plugin, ci->key, buffer_ptr));
354 } /* int dispatch_value_plugin */
355
356 static int dispatch_value (const oconfig_item_t *ci)
357 {
358         int ret = -2;
359         int i;
360
361         for (i = 0; i < cf_value_map_num; i++)
362                 if (strcasecmp (cf_value_map[i].key, ci->key) == 0)
363                 {
364                         ret = cf_value_map[i].func (ci);
365                         break;
366                 }
367
368         for (i = 0; i < cf_global_options_num; i++)
369                 if (strcasecmp (cf_global_options[i].key, ci->key) == 0)
370                 {
371                         ret = dispatch_global_option (ci);
372                         break;
373                 }
374
375         return (ret);
376 } /* int dispatch_value */
377
378 static int dispatch_block_plugin (oconfig_item_t *ci)
379 {
380         int i;
381         char *name;
382
383         cf_complex_callback_t *cb;
384
385         if (strcasecmp (ci->key, "Plugin") != 0)
386                 return (-1);
387         if (ci->values_num < 1)
388                 return (-1);
389         if (ci->values[0].type != OCONFIG_TYPE_STRING)
390                 return (-1);
391
392         name = ci->values[0].value.string;
393         if (strcmp ("libvirt", name) == 0)
394         {
395                 /* TODO(octo): Remove this legacy. */
396                 WARNING ("The \"libvirt\" plugin has been renamed to \"virt\" to avoid problems with the build system. "
397                                 "Your configuration is still using the old name. "
398                                 "Please change it to use \"virt\" as soon as possible. "
399                                 "This compatibility code will go away eventually.");
400                 name = "virt";
401         }
402
403         if (IS_TRUE (global_option_get ("AutoLoadPlugin")))
404         {
405                 plugin_ctx_t ctx;
406                 plugin_ctx_t old_ctx;
407                 int status;
408
409                 /* default to the global interval set before loading this plugin */
410                 memset (&ctx, 0, sizeof (ctx));
411                 ctx.interval = cf_get_default_interval ();
412
413                 old_ctx = plugin_set_ctx (ctx);
414                 status = plugin_load (name, /* flags = */ 0);
415                 /* reset to the "global" context */
416                 plugin_set_ctx (old_ctx);
417
418                 if (status != 0)
419                 {
420                         ERROR ("Automatically loading plugin \"%s\" failed "
421                                         "with status %i.", name, status);
422                         return (status);
423                 }
424         }
425
426         /* Check for a complex callback first */
427         for (cb = complex_callback_head; cb != NULL; cb = cb->next)
428         {
429                 if (strcasecmp (name, cb->type) == 0)
430                 {
431                         plugin_ctx_t old_ctx;
432                         int ret_val;
433
434                         old_ctx = plugin_set_ctx (cb->ctx);
435                         ret_val = (cb->callback (ci));
436                         plugin_set_ctx (old_ctx);
437                         return (ret_val);
438                 }
439         }
440
441         /* Hm, no complex plugin found. Dispatch the values one by one */
442         for (i = 0; i < ci->children_num; i++)
443         {
444                 if (ci->children[i].children == NULL)
445                         dispatch_value_plugin (name, ci->children + i);
446                 else
447                 {
448                         WARNING ("There is a `%s' block within the "
449                                         "configuration for the %s plugin. "
450                                         "The plugin either only expects "
451                                         "\"simple\" configuration statements "
452                                         "or wasn't loaded using `LoadPlugin'."
453                                         " Please check your configuration.",
454                                         ci->children[i].key, name);
455                 }
456         }
457
458         return (0);
459 }
460
461
462 static int dispatch_block (oconfig_item_t *ci)
463 {
464         if (strcasecmp (ci->key, "LoadPlugin") == 0)
465                 return (dispatch_loadplugin (ci));
466         else if (strcasecmp (ci->key, "Plugin") == 0)
467                 return (dispatch_block_plugin (ci));
468         else if (strcasecmp (ci->key, "Chain") == 0)
469                 return (fc_configure (ci));
470
471         return (0);
472 }
473
474 static int cf_ci_replace_child (oconfig_item_t *dst, oconfig_item_t *src,
475                 int offset)
476 {
477         oconfig_item_t *temp;
478         int i;
479
480         assert (offset >= 0);
481         assert (dst->children_num > offset);
482
483         /* Free the memory used by the replaced child. Usually that's the
484          * `Include "blah"' statement. */
485         temp = dst->children + offset;
486         for (i = 0; i < temp->values_num; i++)
487         {
488                 if (temp->values[i].type == OCONFIG_TYPE_STRING)
489                 {
490                         sfree (temp->values[i].value.string);
491                 }
492         }
493         sfree (temp->values);
494         temp = NULL;
495
496         /* If (src->children_num == 0) the array size is decreased. If offset
497          * is _not_ the last element, (offset < (dst->children_num - 1)), then
498          * we need to move the trailing elements before resizing the array. */
499         if ((src->children_num == 0) && (offset < (dst->children_num - 1)))
500         {
501                 int nmemb = dst->children_num - (offset + 1);
502                 memmove (dst->children + offset, dst->children + offset + 1,
503                                 sizeof (oconfig_item_t) * nmemb);
504         }
505
506         /* Resize the memory containing the children to be big enough to hold
507          * all children. */
508         if (dst->children_num + src->children_num - 1 == 0)
509         {
510                 dst->children_num = 0;
511                 return (0);
512         }
513
514         temp = (oconfig_item_t *) realloc (dst->children,
515                         sizeof (oconfig_item_t)
516                         * (dst->children_num + src->children_num - 1));
517         if (temp == NULL)
518         {
519                 ERROR ("configfile: realloc failed.");
520                 return (-1);
521         }
522         dst->children = temp;
523
524         /* If there are children behind the include statement, and they have
525          * not yet been moved because (src->children_num == 0), then move them
526          * to the end of the list, so that the new children have room before
527          * them. */
528         if ((src->children_num > 0)
529                         && ((dst->children_num - (offset + 1)) > 0))
530         {
531                 int nmemb = dst->children_num - (offset + 1);
532                 int old_offset = offset + 1;
533                 int new_offset = offset + src->children_num;
534
535                 memmove (dst->children + new_offset,
536                                 dst->children + old_offset,
537                                 sizeof (oconfig_item_t) * nmemb);
538         }
539
540         /* Last but not least: If there are new children, copy them to the
541          * memory reserved for them. */
542         if (src->children_num > 0)
543         {
544                 memcpy (dst->children + offset,
545                                 src->children,
546                                 sizeof (oconfig_item_t) * src->children_num);
547         }
548
549         /* Update the number of children. */
550         dst->children_num += (src->children_num - 1);
551
552         return (0);
553 } /* int cf_ci_replace_child */
554
555 static int cf_ci_append_children (oconfig_item_t *dst, oconfig_item_t *src)
556 {
557         oconfig_item_t *temp;
558
559         if ((src == NULL) || (src->children_num == 0))
560                 return (0);
561
562         temp = (oconfig_item_t *) realloc (dst->children,
563                         sizeof (oconfig_item_t)
564                         * (dst->children_num + src->children_num));
565         if (temp == NULL)
566         {
567                 ERROR ("configfile: realloc failed.");
568                 return (-1);
569         }
570         dst->children = temp;
571
572         memcpy (dst->children + dst->children_num,
573                         src->children,
574                         sizeof (oconfig_item_t)
575                         * src->children_num);
576         dst->children_num += src->children_num;
577
578         return (0);
579 } /* int cf_ci_append_children */
580
581 #define CF_MAX_DEPTH 8
582 static oconfig_item_t *cf_read_generic (const char *path,
583                 const char *pattern, int depth);
584
585 static int cf_include_all (oconfig_item_t *root, int depth)
586 {
587         int i;
588
589         for (i = 0; i < root->children_num; i++)
590         {
591                 oconfig_item_t *new;
592                 oconfig_item_t *old;
593
594                 char *pattern = NULL;
595
596                 int j;
597
598                 if (strcasecmp (root->children[i].key, "Include") != 0)
599                         continue;
600
601                 old = root->children + i;
602
603                 if ((old->values_num != 1)
604                                 || (old->values[0].type != OCONFIG_TYPE_STRING))
605                 {
606                         ERROR ("configfile: `Include' needs exactly one string argument.");
607                         continue;
608                 }
609
610                 for (j = 0; j < old->children_num; ++j)
611                 {
612                         oconfig_item_t *child = old->children + j;
613
614                         if (strcasecmp (child->key, "Filter") == 0)
615                                 cf_util_get_string (child, &pattern);
616                         else
617                                 ERROR ("configfile: Option `%s' not allowed in <Include> block.",
618                                                 child->key);
619                 }
620
621                 new = cf_read_generic (old->values[0].value.string, pattern, depth + 1);
622                 sfree (pattern);
623
624                 if (new == NULL)
625                         return (-1);
626
627                 /* Now replace the i'th child in `root' with `new'. */
628                 if (cf_ci_replace_child (root, new, i) < 0)
629                         return (-1);
630
631                 /* ... and go back to the new i'th child. */
632                 --i;
633
634                 sfree (new->values);
635                 sfree (new);
636         } /* for (i = 0; i < root->children_num; i++) */
637
638         return (0);
639 } /* int cf_include_all */
640
641 static oconfig_item_t *cf_read_file (const char *file,
642                 const char *pattern, int depth)
643 {
644         oconfig_item_t *root;
645         int status;
646
647         assert (depth < CF_MAX_DEPTH);
648
649         if (pattern != NULL) {
650 #if HAVE_FNMATCH_H && HAVE_LIBGEN_H
651                 char *tmp = sstrdup (file);
652                 char *filename = basename (tmp);
653
654                 if ((filename != NULL) && (fnmatch (pattern, filename, 0) != 0)) {
655                         DEBUG ("configfile: Not including `%s' because it "
656                                         "does not match pattern `%s'.",
657                                         filename, pattern);
658                         free (tmp);
659                         return (NULL);
660                 }
661
662                 free (tmp);
663 #else
664                 ERROR ("configfile: Cannot apply pattern filter '%s' "
665                                 "to file '%s': functions basename() and / or "
666                                 "fnmatch() not available.", pattern, file);
667 #endif /* HAVE_FNMATCH_H && HAVE_LIBGEN_H */
668         }
669
670         root = oconfig_parse_file (file);
671         if (root == NULL)
672         {
673                 ERROR ("configfile: Cannot read file `%s'.", file);
674                 return (NULL);
675         }
676
677         status = cf_include_all (root, depth);
678         if (status != 0)
679         {
680                 oconfig_free (root);
681                 return (NULL);
682         }
683
684         return (root);
685 } /* oconfig_item_t *cf_read_file */
686
687 static int cf_compare_string (const void *p1, const void *p2)
688 {
689         return strcmp (*(const char **) p1, *(const char **) p2);
690 }
691
692 static oconfig_item_t *cf_read_dir (const char *dir,
693                 const char *pattern, int depth)
694 {
695         oconfig_item_t *root = NULL;
696         DIR *dh;
697         struct dirent *de;
698         char **filenames = NULL;
699         int filenames_num = 0;
700         int status;
701         int i;
702
703         assert (depth < CF_MAX_DEPTH);
704
705         dh = opendir (dir);
706         if (dh == NULL)
707         {
708                 char errbuf[1024];
709                 ERROR ("configfile: opendir failed: %s",
710                                 sstrerror (errno, errbuf, sizeof (errbuf)));
711                 return (NULL);
712         }
713
714         root = (oconfig_item_t *) malloc (sizeof (oconfig_item_t));
715         if (root == NULL)
716         {
717                 ERROR ("configfile: malloc failed.");
718                 return (NULL);
719         }
720         memset (root, 0, sizeof (oconfig_item_t));
721
722         while ((de = readdir (dh)) != NULL)
723         {
724                 char   name[1024];
725                 char **tmp;
726
727                 if ((de->d_name[0] == '.') || (de->d_name[0] == 0))
728                         continue;
729
730                 status = ssnprintf (name, sizeof (name), "%s/%s",
731                                 dir, de->d_name);
732                 if ((status < 0) || ((size_t) status >= sizeof (name)))
733                 {
734                         ERROR ("configfile: Not including `%s/%s' because its"
735                                         " name is too long.",
736                                         dir, de->d_name);
737                         for (i = 0; i < filenames_num; ++i)
738                                 free (filenames[i]);
739                         free (filenames);
740                         free (root);
741                         return (NULL);
742                 }
743
744                 ++filenames_num;
745                 tmp = (char **) realloc (filenames,
746                                 filenames_num * sizeof (*filenames));
747                 if (tmp == NULL) {
748                         ERROR ("configfile: realloc failed.");
749                         for (i = 0; i < filenames_num - 1; ++i)
750                                 free (filenames[i]);
751                         free (filenames);
752                         free (root);
753                         return (NULL);
754                 }
755                 filenames = tmp;
756
757                 filenames[filenames_num - 1] = sstrdup (name);
758         }
759
760         qsort ((void *) filenames, filenames_num, sizeof (*filenames),
761                         cf_compare_string);
762
763         for (i = 0; i < filenames_num; ++i)
764         {
765                 oconfig_item_t *temp;
766                 char *name = filenames[i];
767
768                 temp = cf_read_generic (name, pattern, depth);
769                 if (temp == NULL)
770                 {
771                         /* An error should already have been reported. */
772                         sfree (name);
773                         continue;
774                 }
775
776                 cf_ci_append_children (root, temp);
777                 sfree (temp->children);
778                 sfree (temp);
779
780                 free (name);
781         }
782
783         free(filenames);
784         return (root);
785 } /* oconfig_item_t *cf_read_dir */
786
787 /* 
788  * cf_read_generic
789  *
790  * Path is stat'ed and either cf_read_file or cf_read_dir is called
791  * accordingly.
792  *
793  * There are two versions of this function: If `wordexp' exists shell wildcards
794  * will be expanded and the function will include all matches found. If
795  * `wordexp' (or, more precisely, it's header file) is not available the
796  * simpler function is used which does not do any such expansion.
797  */
798 #if HAVE_WORDEXP_H
799 static oconfig_item_t *cf_read_generic (const char *path,
800                 const char *pattern, int depth)
801 {
802         oconfig_item_t *root = NULL;
803         int status;
804         const char *path_ptr;
805         wordexp_t we;
806         size_t i;
807
808         if (depth >= CF_MAX_DEPTH)
809         {
810                 ERROR ("configfile: Not including `%s' because the maximum "
811                                 "nesting depth has been reached.", path);
812                 return (NULL);
813         }
814
815         status = wordexp (path, &we, WRDE_NOCMD);
816         if (status != 0)
817         {
818                 ERROR ("configfile: wordexp (%s) failed.", path);
819                 return (NULL);
820         }
821
822         root = (oconfig_item_t *) malloc (sizeof (oconfig_item_t));
823         if (root == NULL)
824         {
825                 ERROR ("configfile: malloc failed.");
826                 return (NULL);
827         }
828         memset (root, '\0', sizeof (oconfig_item_t));
829
830         /* wordexp() might return a sorted list already. That's not
831          * documented though, so let's make sure we get what we want. */
832         qsort ((void *) we.we_wordv, we.we_wordc, sizeof (*we.we_wordv),
833                         cf_compare_string);
834
835         for (i = 0; i < we.we_wordc; i++)
836         {
837                 oconfig_item_t *temp;
838                 struct stat statbuf;
839
840                 path_ptr = we.we_wordv[i];
841
842                 status = stat (path_ptr, &statbuf);
843                 if (status != 0)
844                 {
845                         char errbuf[1024];
846                         WARNING ("configfile: stat (%s) failed: %s",
847                                         path_ptr,
848                                         sstrerror (errno, errbuf, sizeof (errbuf)));
849                         continue;
850                 }
851
852                 if (S_ISREG (statbuf.st_mode))
853                         temp = cf_read_file (path_ptr, pattern, depth);
854                 else if (S_ISDIR (statbuf.st_mode))
855                         temp = cf_read_dir (path_ptr, pattern, depth);
856                 else
857                 {
858                         WARNING ("configfile: %s is neither a file nor a "
859                                         "directory.", path);
860                         continue;
861                 }
862
863                 if (temp == NULL) {
864                         oconfig_free (root);
865                         return (NULL);
866                 }
867
868                 cf_ci_append_children (root, temp);
869                 sfree (temp->children);
870                 sfree (temp);
871         }
872
873         wordfree (&we);
874
875         return (root);
876 } /* oconfig_item_t *cf_read_generic */
877 /* #endif HAVE_WORDEXP_H */
878
879 #else /* if !HAVE_WORDEXP_H */
880 static oconfig_item_t *cf_read_generic (const char *path,
881                 const char *pattern, int depth)
882 {
883         struct stat statbuf;
884         int status;
885
886         if (depth >= CF_MAX_DEPTH)
887         {
888                 ERROR ("configfile: Not including `%s' because the maximum "
889                                 "nesting depth has been reached.", path);
890                 return (NULL);
891         }
892
893         status = stat (path, &statbuf);
894         if (status != 0)
895         {
896                 char errbuf[1024];
897                 ERROR ("configfile: stat (%s) failed: %s",
898                                 path,
899                                 sstrerror (errno, errbuf, sizeof (errbuf)));
900                 return (NULL);
901         }
902
903         if (S_ISREG (statbuf.st_mode))
904                 return (cf_read_file (path, pattern, depth));
905         else if (S_ISDIR (statbuf.st_mode))
906                 return (cf_read_dir (path, pattern, depth));
907
908         ERROR ("configfile: %s is neither a file nor a directory.", path);
909         return (NULL);
910 } /* oconfig_item_t *cf_read_generic */
911 #endif /* !HAVE_WORDEXP_H */
912
913 /* 
914  * Public functions
915  */
916 int global_option_set (const char *option, const char *value)
917 {
918         int i;
919
920         DEBUG ("option = %s; value = %s;", option, value);
921
922         for (i = 0; i < cf_global_options_num; i++)
923                 if (strcasecmp (cf_global_options[i].key, option) == 0)
924                         break;
925
926         if (i >= cf_global_options_num)
927                 return (-1);
928
929         if (strcasecmp (option, "PIDFile") == 0 && pidfile_from_cli == 1)
930         {
931                 DEBUG ("Configfile: Ignoring `PIDFILE' option because "
932                         "command-line option `-P' take precedence.");
933                 return (0);
934         }
935
936         sfree (cf_global_options[i].value);
937
938         if (value != NULL)
939                 cf_global_options[i].value = strdup (value);
940         else
941                 cf_global_options[i].value = NULL;
942
943         return (0);
944 }
945
946 const char *global_option_get (const char *option)
947 {
948         int i;
949
950         for (i = 0; i < cf_global_options_num; i++)
951                 if (strcasecmp (cf_global_options[i].key, option) == 0)
952                         break;
953
954         if (i >= cf_global_options_num)
955                 return (NULL);
956         
957         return ((cf_global_options[i].value != NULL)
958                         ? cf_global_options[i].value
959                         : cf_global_options[i].def);
960 } /* char *global_option_get */
961
962 long global_option_get_long (const char *option, long default_value)
963 {
964         const char *str;
965         long value;
966
967         str = global_option_get (option);
968         if (NULL == str)
969                 return (default_value);
970
971         errno = 0;
972         value = strtol (str, /* endptr = */ NULL, /* base = */ 0);
973         if (errno != 0)
974                 return (default_value);
975
976         return (value);
977 } /* char *global_option_get_long */
978
979 cdtime_t global_option_get_time (const char *name, cdtime_t def) /* {{{ */
980 {
981         char const *optstr;
982         char *endptr = NULL;
983         double v;
984
985         optstr = global_option_get (name);
986         if (optstr == NULL)
987                 return (def);
988
989         errno = 0;
990         v = strtod (optstr, &endptr);
991         if ((endptr == NULL) || (*endptr != 0) || (errno != 0))
992                 return (def);
993         else if (v <= 0.0)
994                 return (def);
995
996         return (DOUBLE_TO_CDTIME_T (v));
997 } /* }}} cdtime_t global_option_get_time */
998
999 cdtime_t cf_get_default_interval (void)
1000 {
1001         return (global_option_get_time ("Interval",
1002                                DOUBLE_TO_CDTIME_T (COLLECTD_DEFAULT_INTERVAL)));
1003 }
1004
1005 void cf_unregister (const char *type)
1006 {
1007         cf_callback_t *this, *prev;
1008
1009         for (prev = NULL, this = first_callback;
1010                         this != NULL;
1011                         prev = this, this = this->next)
1012                 if (strcasecmp (this->type, type) == 0)
1013                 {
1014                         if (prev == NULL)
1015                                 first_callback = this->next;
1016                         else
1017                                 prev->next = this->next;
1018
1019                         free (this);
1020                         break;
1021                 }
1022 } /* void cf_unregister */
1023
1024 void cf_unregister_complex (const char *type)
1025 {
1026         cf_complex_callback_t *this, *prev;
1027
1028         for (prev = NULL, this = complex_callback_head;
1029                         this != NULL;
1030                         prev = this, this = this->next)
1031                 if (strcasecmp (this->type, type) == 0)
1032                 {
1033                         if (prev == NULL)
1034                                 complex_callback_head = this->next;
1035                         else
1036                                 prev->next = this->next;
1037
1038                         sfree (this->type);
1039                         sfree (this);
1040                         break;
1041                 }
1042 } /* void cf_unregister */
1043
1044 void cf_register (const char *type,
1045                 int (*callback) (const char *, const char *),
1046                 const char **keys, int keys_num)
1047 {
1048         cf_callback_t *cf_cb;
1049
1050         /* Remove this module from the list, if it already exists */
1051         cf_unregister (type);
1052
1053         /* This pointer will be free'd in `cf_unregister' */
1054         if ((cf_cb = (cf_callback_t *) malloc (sizeof (cf_callback_t))) == NULL)
1055                 return;
1056
1057         cf_cb->type     = type;
1058         cf_cb->callback = callback;
1059         cf_cb->keys     = keys;
1060         cf_cb->keys_num = keys_num;
1061         cf_cb->ctx      = plugin_get_ctx ();
1062
1063         cf_cb->next = first_callback;
1064         first_callback = cf_cb;
1065 } /* void cf_register */
1066
1067 int cf_register_complex (const char *type, int (*callback) (oconfig_item_t *))
1068 {
1069         cf_complex_callback_t *new;
1070
1071         new = (cf_complex_callback_t *) malloc (sizeof (cf_complex_callback_t));
1072         if (new == NULL)
1073                 return (-1);
1074
1075         new->type = strdup (type);
1076         if (new->type == NULL)
1077         {
1078                 sfree (new);
1079                 return (-1);
1080         }
1081
1082         new->callback = callback;
1083         new->next = NULL;
1084
1085         new->ctx = plugin_get_ctx ();
1086
1087         if (complex_callback_head == NULL)
1088         {
1089                 complex_callback_head = new;
1090         }
1091         else
1092         {
1093                 cf_complex_callback_t *last = complex_callback_head;
1094                 while (last->next != NULL)
1095                         last = last->next;
1096                 last->next = new;
1097         }
1098
1099         return (0);
1100 } /* int cf_register_complex */
1101
1102 int cf_read (char *filename)
1103 {
1104         oconfig_item_t *conf;
1105         int i;
1106
1107         conf = cf_read_generic (filename, /* pattern = */ NULL, /* depth = */ 0);
1108         if (conf == NULL)
1109         {
1110                 ERROR ("Unable to read config file %s.", filename);
1111                 return (-1);
1112         }
1113         else if (conf->children_num == 0)
1114         {
1115                 ERROR ("Configuration file %s is empty.", filename);
1116                 oconfig_free (conf);
1117                 return (-1);
1118         }
1119
1120         for (i = 0; i < conf->children_num; i++)
1121         {
1122                 if (conf->children[i].children == NULL)
1123                         dispatch_value (conf->children + i);
1124                 else
1125                         dispatch_block (conf->children + i);
1126         }
1127
1128         oconfig_free (conf);
1129
1130         /* Read the default types.db if no `TypesDB' option was given. */
1131         if (cf_default_typesdb)
1132                 read_types_list (PKGDATADIR"/types.db");
1133
1134         return (0);
1135 } /* int cf_read */
1136
1137 /* Assures the config option is a string, duplicates it and returns the copy in
1138  * "ret_string". If necessary "*ret_string" is freed first. Returns zero upon
1139  * success. */
1140 int cf_util_get_string (const oconfig_item_t *ci, char **ret_string) /* {{{ */
1141 {
1142         char *string;
1143
1144         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
1145         {
1146                 ERROR ("cf_util_get_string: The %s option requires "
1147                                 "exactly one string argument.", ci->key);
1148                 return (-1);
1149         }
1150
1151         string = strdup (ci->values[0].value.string);
1152         if (string == NULL)
1153                 return (-1);
1154
1155         if (*ret_string != NULL)
1156                 sfree (*ret_string);
1157         *ret_string = string;
1158
1159         return (0);
1160 } /* }}} int cf_util_get_string */
1161
1162 /* Assures the config option is a string and copies it to the provided buffer.
1163  * Assures null-termination. */
1164 int cf_util_get_string_buffer (const oconfig_item_t *ci, char *buffer, /* {{{ */
1165                 size_t buffer_size)
1166 {
1167         if ((ci == NULL) || (buffer == NULL) || (buffer_size < 1))
1168                 return (EINVAL);
1169
1170         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
1171         {
1172                 ERROR ("cf_util_get_string_buffer: The %s option requires "
1173                                 "exactly one string argument.", ci->key);
1174                 return (-1);
1175         }
1176
1177         strncpy (buffer, ci->values[0].value.string, buffer_size);
1178         buffer[buffer_size - 1] = 0;
1179
1180         return (0);
1181 } /* }}} int cf_util_get_string_buffer */
1182
1183 /* Assures the config option is a number and returns it as an int. */
1184 int cf_util_get_int (const oconfig_item_t *ci, int *ret_value) /* {{{ */
1185 {
1186         if ((ci == NULL) || (ret_value == NULL))
1187                 return (EINVAL);
1188
1189         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
1190         {
1191                 ERROR ("cf_util_get_int: The %s option requires "
1192                                 "exactly one numeric argument.", ci->key);
1193                 return (-1);
1194         }
1195
1196         *ret_value = (int) ci->values[0].value.number;
1197
1198         return (0);
1199 } /* }}} int cf_util_get_int */
1200
1201 int cf_util_get_double (const oconfig_item_t *ci, double *ret_value) /* {{{ */
1202 {
1203         if ((ci == NULL) || (ret_value == NULL))
1204                 return (EINVAL);
1205
1206         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
1207         {
1208                 ERROR ("cf_util_get_double: The %s option requires "
1209                                 "exactly one numeric argument.", ci->key);
1210                 return (-1);
1211         }
1212
1213         *ret_value = ci->values[0].value.number;
1214
1215         return (0);
1216 } /* }}} int cf_util_get_double */
1217
1218 int cf_util_get_boolean (const oconfig_item_t *ci, _Bool *ret_bool) /* {{{ */
1219 {
1220         if ((ci == NULL) || (ret_bool == NULL))
1221                 return (EINVAL);
1222
1223         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN))
1224         {
1225                 ERROR ("cf_util_get_boolean: The %s option requires "
1226                                 "exactly one boolean argument.", ci->key);
1227                 return (-1);
1228         }
1229
1230         *ret_bool = ci->values[0].value.boolean ? 1 : 0;
1231
1232         return (0);
1233 } /* }}} int cf_util_get_boolean */
1234
1235 int cf_util_get_flag (const oconfig_item_t *ci, /* {{{ */
1236                 unsigned int *ret_value, unsigned int flag)
1237 {
1238         int status;
1239         _Bool b;
1240
1241         if (ret_value == NULL)
1242                 return (EINVAL);
1243
1244         b = 0;
1245         status = cf_util_get_boolean (ci, &b);
1246         if (status != 0)
1247                 return (status);
1248
1249         if (b)
1250         {
1251                 *ret_value |= flag;
1252         }
1253         else
1254         {
1255                 *ret_value &= ~flag;
1256         }
1257
1258         return (0);
1259 } /* }}} int cf_util_get_flag */
1260
1261 /* Assures that the config option is a string or a number if the correct range
1262  * of 1-65535. The string is then converted to a port number using
1263  * `service_name_to_port_number' and returned.
1264  * Returns the port number in the range [1-65535] or less than zero upon
1265  * failure. */
1266 int cf_util_get_port_number (const oconfig_item_t *ci) /* {{{ */
1267 {
1268         int tmp;
1269
1270         if ((ci->values_num != 1)
1271                         || ((ci->values[0].type != OCONFIG_TYPE_STRING)
1272                                 && (ci->values[0].type != OCONFIG_TYPE_NUMBER)))
1273         {
1274                 ERROR ("cf_util_get_port_number: The \"%s\" option requires "
1275                                 "exactly one string argument.", ci->key);
1276                 return (-1);
1277         }
1278
1279         if (ci->values[0].type == OCONFIG_TYPE_STRING)
1280                 return (service_name_to_port_number (ci->values[0].value.string));
1281
1282         assert (ci->values[0].type == OCONFIG_TYPE_NUMBER);
1283         tmp = (int) (ci->values[0].value.number + 0.5);
1284         if ((tmp < 1) || (tmp > 65535))
1285         {
1286                 ERROR ("cf_util_get_port_number: The \"%s\" option requires "
1287                                 "a service name or a port number. The number "
1288                                 "you specified, %i, is not in the valid "
1289                                 "range of 1-65535.",
1290                                 ci->key, tmp);
1291                 return (-1);
1292         }
1293
1294         return (tmp);
1295 } /* }}} int cf_util_get_port_number */
1296
1297 int cf_util_get_service (const oconfig_item_t *ci, char **ret_string) /* {{{ */
1298 {
1299         int port;
1300         char *service;
1301         int status;
1302
1303         if (ci->values_num != 1)
1304         {
1305                 ERROR ("cf_util_get_service: The %s option requires exactly "
1306                                 "one argument.", ci->key);
1307                 return (-1);
1308         }
1309
1310         if (ci->values[0].type == OCONFIG_TYPE_STRING)
1311                 return (cf_util_get_string (ci, ret_string));
1312         if (ci->values[0].type != OCONFIG_TYPE_NUMBER)
1313         {
1314                 ERROR ("cf_util_get_service: The %s option requires "
1315                                 "exactly one string or numeric argument.",
1316                                 ci->key);
1317         }
1318
1319         port = 0;
1320         status = cf_util_get_int (ci, &port);
1321         if (status != 0)
1322                 return (status);
1323         else if ((port < 1) || (port > 65535))
1324         {
1325                 ERROR ("cf_util_get_service: The port number given "
1326                                 "for the %s option is out of "
1327                                 "range (%i).", ci->key, port);
1328                 return (-1);
1329         }
1330
1331         service = malloc (6);
1332         if (service == NULL)
1333         {
1334                 ERROR ("cf_util_get_service: Out of memory.");
1335                 return (-1);
1336         }
1337         ssnprintf (service, 6, "%i", port);
1338
1339         sfree (*ret_string);
1340         *ret_string = service;
1341
1342         return (0);
1343 } /* }}} int cf_util_get_service */
1344
1345 int cf_util_get_cdtime (const oconfig_item_t *ci, cdtime_t *ret_value) /* {{{ */
1346 {
1347         if ((ci == NULL) || (ret_value == NULL))
1348                 return (EINVAL);
1349
1350         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
1351         {
1352                 ERROR ("cf_util_get_cdtime: The %s option requires "
1353                                 "exactly one numeric argument.", ci->key);
1354                 return (-1);
1355         }
1356
1357         if (ci->values[0].value.number < 0.0)
1358         {
1359                 ERROR ("cf_util_get_cdtime: The numeric argument of the %s "
1360                                 "option must not be negative.", ci->key);
1361                 return (-1);
1362         }
1363
1364         *ret_value = DOUBLE_TO_CDTIME_T (ci->values[0].value.number);
1365
1366         return (0);
1367 } /* }}} int cf_util_get_cdtime */
1368