Merge branch 'collectd-5.4' into 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
291         for (i = 0; i < ci->children_num; ++i) {
292                 if (strcasecmp("Globals", ci->children[i].key) == 0)
293                         cf_util_get_flag (ci->children + i, &flags, PLUGIN_FLAGS_GLOBAL);
294                 else if (strcasecmp ("Interval", ci->children[i].key) == 0) {
295                         if (cf_util_get_cdtime (ci->children + i, &ctx.interval) != 0) {
296                                 /* cf_util_get_cdtime will log an error */
297                                 continue;
298                         }
299                 }
300                 else {
301                         WARNING("Ignoring unknown LoadPlugin option \"%s\" "
302                                         "for plugin \"%s\"",
303                                         ci->children[i].key, ci->values[0].value.string);
304                 }
305         }
306
307         old_ctx = plugin_set_ctx (ctx);
308         ret_val = plugin_load (name, (uint32_t) flags);
309         /* reset to the "global" context */
310         plugin_set_ctx (old_ctx);
311
312         return (ret_val);
313 } /* int dispatch_value_loadplugin */
314
315 static int dispatch_value_plugin (const char *plugin, oconfig_item_t *ci)
316 {
317         char  buffer[4096];
318         char *buffer_ptr;
319         int   buffer_free;
320         int i;
321
322         buffer_ptr = buffer;
323         buffer_free = sizeof (buffer);
324
325         for (i = 0; i < ci->values_num; i++)
326         {
327                 int status = -1;
328
329                 if (ci->values[i].type == OCONFIG_TYPE_STRING)
330                         status = ssnprintf (buffer_ptr, buffer_free, " %s",
331                                         ci->values[i].value.string);
332                 else if (ci->values[i].type == OCONFIG_TYPE_NUMBER)
333                         status = ssnprintf (buffer_ptr, buffer_free, " %lf",
334                                         ci->values[i].value.number);
335                 else if (ci->values[i].type == OCONFIG_TYPE_BOOLEAN)
336                         status = ssnprintf (buffer_ptr, buffer_free, " %s",
337                                         ci->values[i].value.boolean
338                                         ? "true" : "false");
339
340                 if ((status < 0) || (status >= buffer_free))
341                         return (-1);
342                 buffer_free -= status;
343                 buffer_ptr  += status;
344         }
345         /* skip the initial space */
346         buffer_ptr = buffer + 1;
347
348         return (cf_dispatch (plugin, ci->key, buffer_ptr));
349 } /* int dispatch_value_plugin */
350
351 static int dispatch_value (const oconfig_item_t *ci)
352 {
353         int ret = -2;
354         int i;
355
356         for (i = 0; i < cf_value_map_num; i++)
357                 if (strcasecmp (cf_value_map[i].key, ci->key) == 0)
358                 {
359                         ret = cf_value_map[i].func (ci);
360                         break;
361                 }
362
363         for (i = 0; i < cf_global_options_num; i++)
364                 if (strcasecmp (cf_global_options[i].key, ci->key) == 0)
365                 {
366                         ret = dispatch_global_option (ci);
367                         break;
368                 }
369
370         return (ret);
371 } /* int dispatch_value */
372
373 static int dispatch_block_plugin (oconfig_item_t *ci)
374 {
375         int i;
376         char *name;
377
378         cf_complex_callback_t *cb;
379
380         if (strcasecmp (ci->key, "Plugin") != 0)
381                 return (-1);
382         if (ci->values_num < 1)
383                 return (-1);
384         if (ci->values[0].type != OCONFIG_TYPE_STRING)
385                 return (-1);
386
387         name = ci->values[0].value.string;
388         if (strcmp ("libvirt", name) == 0)
389         {
390                 /* TODO(octo): Remove this legacy. */
391                 WARNING ("The \"libvirt\" plugin has been renamed to \"virt\" to avoid problems with the build system. "
392                                 "Your configuration is still using the old name. "
393                                 "Please change it to use \"virt\" as soon as possible. "
394                                 "This compatibility code will go away eventually.");
395                 name = "virt";
396         }
397
398         if (IS_TRUE (global_option_get ("AutoLoadPlugin")))
399         {
400                 plugin_ctx_t ctx;
401                 plugin_ctx_t old_ctx;
402                 int status;
403
404                 /* default to the global interval set before loading this plugin */
405                 memset (&ctx, 0, sizeof (ctx));
406                 ctx.interval = cf_get_default_interval ();
407
408                 old_ctx = plugin_set_ctx (ctx);
409                 status = plugin_load (name, /* flags = */ 0);
410                 /* reset to the "global" context */
411                 plugin_set_ctx (old_ctx);
412
413                 if (status != 0)
414                 {
415                         ERROR ("Automatically loading plugin \"%s\" failed "
416                                         "with status %i.", name, status);
417                         return (status);
418                 }
419         }
420
421         /* Check for a complex callback first */
422         for (cb = complex_callback_head; cb != NULL; cb = cb->next)
423         {
424                 if (strcasecmp (name, cb->type) == 0)
425                 {
426                         plugin_ctx_t old_ctx;
427                         int ret_val;
428
429                         old_ctx = plugin_set_ctx (cb->ctx);
430                         ret_val = (cb->callback (ci));
431                         plugin_set_ctx (old_ctx);
432                         return (ret_val);
433                 }
434         }
435
436         /* Hm, no complex plugin found. Dispatch the values one by one */
437         for (i = 0; i < ci->children_num; i++)
438         {
439                 if (ci->children[i].children == NULL)
440                         dispatch_value_plugin (name, ci->children + i);
441                 else
442                 {
443                         WARNING ("There is a `%s' block within the "
444                                         "configuration for the %s plugin. "
445                                         "The plugin either only expects "
446                                         "\"simple\" configuration statements "
447                                         "or wasn't loaded using `LoadPlugin'."
448                                         " Please check your configuration.",
449                                         ci->children[i].key, name);
450                 }
451         }
452
453         return (0);
454 }
455
456
457 static int dispatch_block (oconfig_item_t *ci)
458 {
459         if (strcasecmp (ci->key, "LoadPlugin") == 0)
460                 return (dispatch_loadplugin (ci));
461         else if (strcasecmp (ci->key, "Plugin") == 0)
462                 return (dispatch_block_plugin (ci));
463         else if (strcasecmp (ci->key, "Chain") == 0)
464                 return (fc_configure (ci));
465
466         return (0);
467 }
468
469 static int cf_ci_replace_child (oconfig_item_t *dst, oconfig_item_t *src,
470                 int offset)
471 {
472         oconfig_item_t *temp;
473         int i;
474
475         assert (offset >= 0);
476         assert (dst->children_num > offset);
477
478         /* Free the memory used by the replaced child. Usually that's the
479          * `Include "blah"' statement. */
480         temp = dst->children + offset;
481         for (i = 0; i < temp->values_num; i++)
482         {
483                 if (temp->values[i].type == OCONFIG_TYPE_STRING)
484                 {
485                         sfree (temp->values[i].value.string);
486                 }
487         }
488         sfree (temp->values);
489         temp = NULL;
490
491         /* If (src->children_num == 0) the array size is decreased. If offset
492          * is _not_ the last element, (offset < (dst->children_num - 1)), then
493          * we need to move the trailing elements before resizing the array. */
494         if ((src->children_num == 0) && (offset < (dst->children_num - 1)))
495         {
496                 int nmemb = dst->children_num - (offset + 1);
497                 memmove (dst->children + offset, dst->children + offset + 1,
498                                 sizeof (oconfig_item_t) * nmemb);
499         }
500
501         /* Resize the memory containing the children to be big enough to hold
502          * all children. */
503         if (dst->children_num + src->children_num - 1 == 0)
504         {
505                 dst->children_num = 0;
506                 return (0);
507         }
508
509         temp = (oconfig_item_t *) realloc (dst->children,
510                         sizeof (oconfig_item_t)
511                         * (dst->children_num + src->children_num - 1));
512         if (temp == NULL)
513         {
514                 ERROR ("configfile: realloc failed.");
515                 return (-1);
516         }
517         dst->children = temp;
518
519         /* If there are children behind the include statement, and they have
520          * not yet been moved because (src->children_num == 0), then move them
521          * to the end of the list, so that the new children have room before
522          * them. */
523         if ((src->children_num > 0)
524                         && ((dst->children_num - (offset + 1)) > 0))
525         {
526                 int nmemb = dst->children_num - (offset + 1);
527                 int old_offset = offset + 1;
528                 int new_offset = offset + src->children_num;
529
530                 memmove (dst->children + new_offset,
531                                 dst->children + old_offset,
532                                 sizeof (oconfig_item_t) * nmemb);
533         }
534
535         /* Last but not least: If there are new children, copy them to the
536          * memory reserved for them. */
537         if (src->children_num > 0)
538         {
539                 memcpy (dst->children + offset,
540                                 src->children,
541                                 sizeof (oconfig_item_t) * src->children_num);
542         }
543
544         /* Update the number of children. */
545         dst->children_num += (src->children_num - 1);
546
547         return (0);
548 } /* int cf_ci_replace_child */
549
550 static int cf_ci_append_children (oconfig_item_t *dst, oconfig_item_t *src)
551 {
552         oconfig_item_t *temp;
553
554         if ((src == NULL) || (src->children_num == 0))
555                 return (0);
556
557         temp = (oconfig_item_t *) realloc (dst->children,
558                         sizeof (oconfig_item_t)
559                         * (dst->children_num + src->children_num));
560         if (temp == NULL)
561         {
562                 ERROR ("configfile: realloc failed.");
563                 return (-1);
564         }
565         dst->children = temp;
566
567         memcpy (dst->children + dst->children_num,
568                         src->children,
569                         sizeof (oconfig_item_t)
570                         * src->children_num);
571         dst->children_num += src->children_num;
572
573         return (0);
574 } /* int cf_ci_append_children */
575
576 #define CF_MAX_DEPTH 8
577 static oconfig_item_t *cf_read_generic (const char *path,
578                 const char *pattern, int depth);
579
580 static int cf_include_all (oconfig_item_t *root, int depth)
581 {
582         int i;
583
584         for (i = 0; i < root->children_num; i++)
585         {
586                 oconfig_item_t *new;
587                 oconfig_item_t *old;
588
589                 char *pattern = NULL;
590
591                 int j;
592
593                 if (strcasecmp (root->children[i].key, "Include") != 0)
594                         continue;
595
596                 old = root->children + i;
597
598                 if ((old->values_num != 1)
599                                 || (old->values[0].type != OCONFIG_TYPE_STRING))
600                 {
601                         ERROR ("configfile: `Include' needs exactly one string argument.");
602                         continue;
603                 }
604
605                 for (j = 0; j < old->children_num; ++j)
606                 {
607                         oconfig_item_t *child = old->children + j;
608
609                         if (strcasecmp (child->key, "Filter") == 0)
610                                 cf_util_get_string (child, &pattern);
611                         else
612                                 ERROR ("configfile: Option `%s' not allowed in <Include> block.",
613                                                 child->key);
614                 }
615
616                 new = cf_read_generic (old->values[0].value.string, pattern, depth + 1);
617                 sfree (pattern);
618
619                 if (new == NULL)
620                         return (-1);
621
622                 /* Now replace the i'th child in `root' with `new'. */
623                 if (cf_ci_replace_child (root, new, i) < 0)
624                         return (-1);
625
626                 /* ... and go back to the new i'th child. */
627                 --i;
628
629                 sfree (new->values);
630                 sfree (new);
631         } /* for (i = 0; i < root->children_num; i++) */
632
633         return (0);
634 } /* int cf_include_all */
635
636 static oconfig_item_t *cf_read_file (const char *file,
637                 const char *pattern, int depth)
638 {
639         oconfig_item_t *root;
640         int status;
641
642         assert (depth < CF_MAX_DEPTH);
643
644         if (pattern != NULL) {
645 #if HAVE_FNMATCH_H && HAVE_LIBGEN_H
646                 char *tmp = sstrdup (file);
647                 char *filename = basename (tmp);
648
649                 if ((filename != NULL) && (fnmatch (pattern, filename, 0) != 0)) {
650                         DEBUG ("configfile: Not including `%s' because it "
651                                         "does not match pattern `%s'.",
652                                         filename, pattern);
653                         free (tmp);
654                         return (NULL);
655                 }
656
657                 free (tmp);
658 #else
659                 ERROR ("configfile: Cannot apply pattern filter '%s' "
660                                 "to file '%s': functions basename() and / or "
661                                 "fnmatch() not available.", pattern, file);
662 #endif /* HAVE_FNMATCH_H && HAVE_LIBGEN_H */
663         }
664
665         root = oconfig_parse_file (file);
666         if (root == NULL)
667         {
668                 ERROR ("configfile: Cannot read file `%s'.", file);
669                 return (NULL);
670         }
671
672         status = cf_include_all (root, depth);
673         if (status != 0)
674         {
675                 oconfig_free (root);
676                 return (NULL);
677         }
678
679         return (root);
680 } /* oconfig_item_t *cf_read_file */
681
682 static int cf_compare_string (const void *p1, const void *p2)
683 {
684         return strcmp (*(const char **) p1, *(const char **) p2);
685 }
686
687 static oconfig_item_t *cf_read_dir (const char *dir,
688                 const char *pattern, int depth)
689 {
690         oconfig_item_t *root = NULL;
691         DIR *dh;
692         struct dirent *de;
693         char **filenames = NULL;
694         int filenames_num = 0;
695         int status;
696         int i;
697
698         assert (depth < CF_MAX_DEPTH);
699
700         dh = opendir (dir);
701         if (dh == NULL)
702         {
703                 char errbuf[1024];
704                 ERROR ("configfile: opendir failed: %s",
705                                 sstrerror (errno, errbuf, sizeof (errbuf)));
706                 return (NULL);
707         }
708
709         root = (oconfig_item_t *) malloc (sizeof (oconfig_item_t));
710         if (root == NULL)
711         {
712                 ERROR ("configfile: malloc failed.");
713                 return (NULL);
714         }
715         memset (root, 0, sizeof (oconfig_item_t));
716
717         while ((de = readdir (dh)) != NULL)
718         {
719                 char   name[1024];
720                 char **tmp;
721
722                 if ((de->d_name[0] == '.') || (de->d_name[0] == 0))
723                         continue;
724
725                 status = ssnprintf (name, sizeof (name), "%s/%s",
726                                 dir, de->d_name);
727                 if ((status < 0) || ((size_t) status >= sizeof (name)))
728                 {
729                         ERROR ("configfile: Not including `%s/%s' because its"
730                                         " name is too long.",
731                                         dir, de->d_name);
732                         for (i = 0; i < filenames_num; ++i)
733                                 free (filenames[i]);
734                         free (filenames);
735                         free (root);
736                         return (NULL);
737                 }
738
739                 ++filenames_num;
740                 tmp = (char **) realloc (filenames,
741                                 filenames_num * sizeof (*filenames));
742                 if (tmp == NULL) {
743                         ERROR ("configfile: realloc failed.");
744                         for (i = 0; i < filenames_num - 1; ++i)
745                                 free (filenames[i]);
746                         free (filenames);
747                         free (root);
748                         return (NULL);
749                 }
750                 filenames = tmp;
751
752                 filenames[filenames_num - 1] = sstrdup (name);
753         }
754
755         qsort ((void *) filenames, filenames_num, sizeof (*filenames),
756                         cf_compare_string);
757
758         for (i = 0; i < filenames_num; ++i)
759         {
760                 oconfig_item_t *temp;
761                 char *name = filenames[i];
762
763                 temp = cf_read_generic (name, pattern, depth);
764                 if (temp == NULL)
765                 {
766                         /* An error should already have been reported. */
767                         sfree (name);
768                         continue;
769                 }
770
771                 cf_ci_append_children (root, temp);
772                 sfree (temp->children);
773                 sfree (temp);
774
775                 free (name);
776         }
777
778         free(filenames);
779         return (root);
780 } /* oconfig_item_t *cf_read_dir */
781
782 /* 
783  * cf_read_generic
784  *
785  * Path is stat'ed and either cf_read_file or cf_read_dir is called
786  * accordingly.
787  *
788  * There are two versions of this function: If `wordexp' exists shell wildcards
789  * will be expanded and the function will include all matches found. If
790  * `wordexp' (or, more precisely, it's header file) is not available the
791  * simpler function is used which does not do any such expansion.
792  */
793 #if HAVE_WORDEXP_H
794 static oconfig_item_t *cf_read_generic (const char *path,
795                 const char *pattern, int depth)
796 {
797         oconfig_item_t *root = NULL;
798         int status;
799         const char *path_ptr;
800         wordexp_t we;
801         size_t i;
802
803         if (depth >= CF_MAX_DEPTH)
804         {
805                 ERROR ("configfile: Not including `%s' because the maximum "
806                                 "nesting depth has been reached.", path);
807                 return (NULL);
808         }
809
810         status = wordexp (path, &we, WRDE_NOCMD);
811         if (status != 0)
812         {
813                 ERROR ("configfile: wordexp (%s) failed.", path);
814                 return (NULL);
815         }
816
817         root = (oconfig_item_t *) malloc (sizeof (oconfig_item_t));
818         if (root == NULL)
819         {
820                 ERROR ("configfile: malloc failed.");
821                 return (NULL);
822         }
823         memset (root, '\0', sizeof (oconfig_item_t));
824
825         /* wordexp() might return a sorted list already. That's not
826          * documented though, so let's make sure we get what we want. */
827         qsort ((void *) we.we_wordv, we.we_wordc, sizeof (*we.we_wordv),
828                         cf_compare_string);
829
830         for (i = 0; i < we.we_wordc; i++)
831         {
832                 oconfig_item_t *temp;
833                 struct stat statbuf;
834
835                 path_ptr = we.we_wordv[i];
836
837                 status = stat (path_ptr, &statbuf);
838                 if (status != 0)
839                 {
840                         char errbuf[1024];
841                         WARNING ("configfile: stat (%s) failed: %s",
842                                         path_ptr,
843                                         sstrerror (errno, errbuf, sizeof (errbuf)));
844                         continue;
845                 }
846
847                 if (S_ISREG (statbuf.st_mode))
848                         temp = cf_read_file (path_ptr, pattern, depth);
849                 else if (S_ISDIR (statbuf.st_mode))
850                         temp = cf_read_dir (path_ptr, pattern, depth);
851                 else
852                 {
853                         WARNING ("configfile: %s is neither a file nor a "
854                                         "directory.", path);
855                         continue;
856                 }
857
858                 if (temp == NULL) {
859                         oconfig_free (root);
860                         return (NULL);
861                 }
862
863                 cf_ci_append_children (root, temp);
864                 sfree (temp->children);
865                 sfree (temp);
866         }
867
868         wordfree (&we);
869
870         return (root);
871 } /* oconfig_item_t *cf_read_generic */
872 /* #endif HAVE_WORDEXP_H */
873
874 #else /* if !HAVE_WORDEXP_H */
875 static oconfig_item_t *cf_read_generic (const char *path,
876                 const char *pattern, int depth)
877 {
878         struct stat statbuf;
879         int status;
880
881         if (depth >= CF_MAX_DEPTH)
882         {
883                 ERROR ("configfile: Not including `%s' because the maximum "
884                                 "nesting depth has been reached.", path);
885                 return (NULL);
886         }
887
888         status = stat (path, &statbuf);
889         if (status != 0)
890         {
891                 char errbuf[1024];
892                 ERROR ("configfile: stat (%s) failed: %s",
893                                 path,
894                                 sstrerror (errno, errbuf, sizeof (errbuf)));
895                 return (NULL);
896         }
897
898         if (S_ISREG (statbuf.st_mode))
899                 return (cf_read_file (path, pattern, depth));
900         else if (S_ISDIR (statbuf.st_mode))
901                 return (cf_read_dir (path, pattern, depth));
902
903         ERROR ("configfile: %s is neither a file nor a directory.", path);
904         return (NULL);
905 } /* oconfig_item_t *cf_read_generic */
906 #endif /* !HAVE_WORDEXP_H */
907
908 /* 
909  * Public functions
910  */
911 int global_option_set (const char *option, const char *value)
912 {
913         int i;
914
915         DEBUG ("option = %s; value = %s;", option, value);
916
917         for (i = 0; i < cf_global_options_num; i++)
918                 if (strcasecmp (cf_global_options[i].key, option) == 0)
919                         break;
920
921         if (i >= cf_global_options_num)
922                 return (-1);
923
924         if (strcasecmp (option, "PIDFile") == 0 && pidfile_from_cli == 1)
925         {
926                 DEBUG ("Configfile: Ignoring `PIDFILE' option because "
927                         "command-line option `-P' take precedence.");
928                 return (0);
929         }
930
931         sfree (cf_global_options[i].value);
932
933         if (value != NULL)
934                 cf_global_options[i].value = strdup (value);
935         else
936                 cf_global_options[i].value = NULL;
937
938         return (0);
939 }
940
941 const char *global_option_get (const char *option)
942 {
943         int i;
944
945         for (i = 0; i < cf_global_options_num; i++)
946                 if (strcasecmp (cf_global_options[i].key, option) == 0)
947                         break;
948
949         if (i >= cf_global_options_num)
950                 return (NULL);
951         
952         return ((cf_global_options[i].value != NULL)
953                         ? cf_global_options[i].value
954                         : cf_global_options[i].def);
955 } /* char *global_option_get */
956
957 long global_option_get_long (const char *option, long default_value)
958 {
959         const char *str;
960         long value;
961
962         str = global_option_get (option);
963         if (NULL == str)
964                 return (default_value);
965
966         errno = 0;
967         value = strtol (str, /* endptr = */ NULL, /* base = */ 0);
968         if (errno != 0)
969                 return (default_value);
970
971         return (value);
972 } /* char *global_option_get_long */
973
974 cdtime_t global_option_get_time (const char *name, cdtime_t def) /* {{{ */
975 {
976         char const *optstr;
977         char *endptr = NULL;
978         double v;
979
980         optstr = global_option_get (name);
981         if (optstr == NULL)
982                 return (def);
983
984         errno = 0;
985         v = strtod (optstr, &endptr);
986         if ((endptr == NULL) || (*endptr != 0) || (errno != 0))
987                 return (def);
988         else if (v <= 0.0)
989                 return (def);
990
991         return (DOUBLE_TO_CDTIME_T (v));
992 } /* }}} cdtime_t global_option_get_time */
993
994 cdtime_t cf_get_default_interval (void)
995 {
996         return (global_option_get_time ("Interval",
997                                DOUBLE_TO_CDTIME_T (COLLECTD_DEFAULT_INTERVAL)));
998 }
999
1000 void cf_unregister (const char *type)
1001 {
1002         cf_callback_t *this, *prev;
1003
1004         for (prev = NULL, this = first_callback;
1005                         this != NULL;
1006                         prev = this, this = this->next)
1007                 if (strcasecmp (this->type, type) == 0)
1008                 {
1009                         if (prev == NULL)
1010                                 first_callback = this->next;
1011                         else
1012                                 prev->next = this->next;
1013
1014                         free (this);
1015                         break;
1016                 }
1017 } /* void cf_unregister */
1018
1019 void cf_unregister_complex (const char *type)
1020 {
1021         cf_complex_callback_t *this, *prev;
1022
1023         for (prev = NULL, this = complex_callback_head;
1024                         this != NULL;
1025                         prev = this, this = this->next)
1026                 if (strcasecmp (this->type, type) == 0)
1027                 {
1028                         if (prev == NULL)
1029                                 complex_callback_head = this->next;
1030                         else
1031                                 prev->next = this->next;
1032
1033                         sfree (this->type);
1034                         sfree (this);
1035                         break;
1036                 }
1037 } /* void cf_unregister */
1038
1039 void cf_register (const char *type,
1040                 int (*callback) (const char *, const char *),
1041                 const char **keys, int keys_num)
1042 {
1043         cf_callback_t *cf_cb;
1044
1045         /* Remove this module from the list, if it already exists */
1046         cf_unregister (type);
1047
1048         /* This pointer will be free'd in `cf_unregister' */
1049         if ((cf_cb = (cf_callback_t *) malloc (sizeof (cf_callback_t))) == NULL)
1050                 return;
1051
1052         cf_cb->type     = type;
1053         cf_cb->callback = callback;
1054         cf_cb->keys     = keys;
1055         cf_cb->keys_num = keys_num;
1056         cf_cb->ctx      = plugin_get_ctx ();
1057
1058         cf_cb->next = first_callback;
1059         first_callback = cf_cb;
1060 } /* void cf_register */
1061
1062 int cf_register_complex (const char *type, int (*callback) (oconfig_item_t *))
1063 {
1064         cf_complex_callback_t *new;
1065
1066         new = (cf_complex_callback_t *) malloc (sizeof (cf_complex_callback_t));
1067         if (new == NULL)
1068                 return (-1);
1069
1070         new->type = strdup (type);
1071         if (new->type == NULL)
1072         {
1073                 sfree (new);
1074                 return (-1);
1075         }
1076
1077         new->callback = callback;
1078         new->next = NULL;
1079
1080         new->ctx = plugin_get_ctx ();
1081
1082         if (complex_callback_head == NULL)
1083         {
1084                 complex_callback_head = new;
1085         }
1086         else
1087         {
1088                 cf_complex_callback_t *last = complex_callback_head;
1089                 while (last->next != NULL)
1090                         last = last->next;
1091                 last->next = new;
1092         }
1093
1094         return (0);
1095 } /* int cf_register_complex */
1096
1097 int cf_read (char *filename)
1098 {
1099         oconfig_item_t *conf;
1100         int i;
1101
1102         conf = cf_read_generic (filename, /* pattern = */ NULL, /* depth = */ 0);
1103         if (conf == NULL)
1104         {
1105                 ERROR ("Unable to read config file %s.", filename);
1106                 return (-1);
1107         }
1108         else if (conf->children_num == 0)
1109         {
1110                 ERROR ("Configuration file %s is empty.", filename);
1111                 oconfig_free (conf);
1112                 return (-1);
1113         }
1114
1115         for (i = 0; i < conf->children_num; i++)
1116         {
1117                 if (conf->children[i].children == NULL)
1118                         dispatch_value (conf->children + i);
1119                 else
1120                         dispatch_block (conf->children + i);
1121         }
1122
1123         oconfig_free (conf);
1124
1125         /* Read the default types.db if no `TypesDB' option was given. */
1126         if (cf_default_typesdb)
1127                 read_types_list (PKGDATADIR"/types.db");
1128
1129         return (0);
1130 } /* int cf_read */
1131
1132 /* Assures the config option is a string, duplicates it and returns the copy in
1133  * "ret_string". If necessary "*ret_string" is freed first. Returns zero upon
1134  * success. */
1135 int cf_util_get_string (const oconfig_item_t *ci, char **ret_string) /* {{{ */
1136 {
1137         char *string;
1138
1139         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
1140         {
1141                 ERROR ("cf_util_get_string: The %s option requires "
1142                                 "exactly one string argument.", ci->key);
1143                 return (-1);
1144         }
1145
1146         string = strdup (ci->values[0].value.string);
1147         if (string == NULL)
1148                 return (-1);
1149
1150         if (*ret_string != NULL)
1151                 sfree (*ret_string);
1152         *ret_string = string;
1153
1154         return (0);
1155 } /* }}} int cf_util_get_string */
1156
1157 /* Assures the config option is a string and copies it to the provided buffer.
1158  * Assures null-termination. */
1159 int cf_util_get_string_buffer (const oconfig_item_t *ci, char *buffer, /* {{{ */
1160                 size_t buffer_size)
1161 {
1162         if ((ci == NULL) || (buffer == NULL) || (buffer_size < 1))
1163                 return (EINVAL);
1164
1165         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING))
1166         {
1167                 ERROR ("cf_util_get_string_buffer: The %s option requires "
1168                                 "exactly one string argument.", ci->key);
1169                 return (-1);
1170         }
1171
1172         strncpy (buffer, ci->values[0].value.string, buffer_size);
1173         buffer[buffer_size - 1] = 0;
1174
1175         return (0);
1176 } /* }}} int cf_util_get_string_buffer */
1177
1178 /* Assures the config option is a number and returns it as an int. */
1179 int cf_util_get_int (const oconfig_item_t *ci, int *ret_value) /* {{{ */
1180 {
1181         if ((ci == NULL) || (ret_value == NULL))
1182                 return (EINVAL);
1183
1184         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
1185         {
1186                 ERROR ("cf_util_get_int: The %s option requires "
1187                                 "exactly one numeric argument.", ci->key);
1188                 return (-1);
1189         }
1190
1191         *ret_value = (int) ci->values[0].value.number;
1192
1193         return (0);
1194 } /* }}} int cf_util_get_int */
1195
1196 int cf_util_get_double (const oconfig_item_t *ci, double *ret_value) /* {{{ */
1197 {
1198         if ((ci == NULL) || (ret_value == NULL))
1199                 return (EINVAL);
1200
1201         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
1202         {
1203                 ERROR ("cf_util_get_double: The %s option requires "
1204                                 "exactly one numeric argument.", ci->key);
1205                 return (-1);
1206         }
1207
1208         *ret_value = ci->values[0].value.number;
1209
1210         return (0);
1211 } /* }}} int cf_util_get_double */
1212
1213 int cf_util_get_boolean (const oconfig_item_t *ci, _Bool *ret_bool) /* {{{ */
1214 {
1215         if ((ci == NULL) || (ret_bool == NULL))
1216                 return (EINVAL);
1217
1218         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_BOOLEAN))
1219         {
1220                 ERROR ("cf_util_get_boolean: The %s option requires "
1221                                 "exactly one boolean argument.", ci->key);
1222                 return (-1);
1223         }
1224
1225         *ret_bool = ci->values[0].value.boolean ? 1 : 0;
1226
1227         return (0);
1228 } /* }}} int cf_util_get_boolean */
1229
1230 int cf_util_get_flag (const oconfig_item_t *ci, /* {{{ */
1231                 unsigned int *ret_value, unsigned int flag)
1232 {
1233         int status;
1234         _Bool b;
1235
1236         if (ret_value == NULL)
1237                 return (EINVAL);
1238
1239         b = 0;
1240         status = cf_util_get_boolean (ci, &b);
1241         if (status != 0)
1242                 return (status);
1243
1244         if (b)
1245         {
1246                 *ret_value |= flag;
1247         }
1248         else
1249         {
1250                 *ret_value &= ~flag;
1251         }
1252
1253         return (0);
1254 } /* }}} int cf_util_get_flag */
1255
1256 /* Assures that the config option is a string or a number if the correct range
1257  * of 1-65535. The string is then converted to a port number using
1258  * `service_name_to_port_number' and returned.
1259  * Returns the port number in the range [1-65535] or less than zero upon
1260  * failure. */
1261 int cf_util_get_port_number (const oconfig_item_t *ci) /* {{{ */
1262 {
1263         int tmp;
1264
1265         if ((ci->values_num != 1)
1266                         || ((ci->values[0].type != OCONFIG_TYPE_STRING)
1267                                 && (ci->values[0].type != OCONFIG_TYPE_NUMBER)))
1268         {
1269                 ERROR ("cf_util_get_port_number: The \"%s\" option requires "
1270                                 "exactly one string argument.", ci->key);
1271                 return (-1);
1272         }
1273
1274         if (ci->values[0].type == OCONFIG_TYPE_STRING)
1275                 return (service_name_to_port_number (ci->values[0].value.string));
1276
1277         assert (ci->values[0].type == OCONFIG_TYPE_NUMBER);
1278         tmp = (int) (ci->values[0].value.number + 0.5);
1279         if ((tmp < 1) || (tmp > 65535))
1280         {
1281                 ERROR ("cf_util_get_port_number: The \"%s\" option requires "
1282                                 "a service name or a port number. The number "
1283                                 "you specified, %i, is not in the valid "
1284                                 "range of 1-65535.",
1285                                 ci->key, tmp);
1286                 return (-1);
1287         }
1288
1289         return (tmp);
1290 } /* }}} int cf_util_get_port_number */
1291
1292 int cf_util_get_service (const oconfig_item_t *ci, char **ret_string) /* {{{ */
1293 {
1294         int port;
1295         char *service;
1296         int status;
1297
1298         if (ci->values_num != 1)
1299         {
1300                 ERROR ("cf_util_get_service: The %s option requires exactly "
1301                                 "one argument.", ci->key);
1302                 return (-1);
1303         }
1304
1305         if (ci->values[0].type == OCONFIG_TYPE_STRING)
1306                 return (cf_util_get_string (ci, ret_string));
1307         if (ci->values[0].type != OCONFIG_TYPE_NUMBER)
1308         {
1309                 ERROR ("cf_util_get_service: The %s option requires "
1310                                 "exactly one string or numeric argument.",
1311                                 ci->key);
1312         }
1313
1314         port = 0;
1315         status = cf_util_get_int (ci, &port);
1316         if (status != 0)
1317                 return (status);
1318         else if ((port < 1) || (port > 65535))
1319         {
1320                 ERROR ("cf_util_get_service: The port number given "
1321                                 "for the %s option is out of "
1322                                 "range (%i).", ci->key, port);
1323                 return (-1);
1324         }
1325
1326         service = malloc (6);
1327         if (service == NULL)
1328         {
1329                 ERROR ("cf_util_get_service: Out of memory.");
1330                 return (-1);
1331         }
1332         ssnprintf (service, 6, "%i", port);
1333
1334         sfree (*ret_string);
1335         *ret_string = service;
1336
1337         return (0);
1338 } /* }}} int cf_util_get_service */
1339
1340 int cf_util_get_cdtime (const oconfig_item_t *ci, cdtime_t *ret_value) /* {{{ */
1341 {
1342         if ((ci == NULL) || (ret_value == NULL))
1343                 return (EINVAL);
1344
1345         if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER))
1346         {
1347                 ERROR ("cf_util_get_cdtime: The %s option requires "
1348                                 "exactly one numeric argument.", ci->key);
1349                 return (-1);
1350         }
1351
1352         if (ci->values[0].value.number < 0.0)
1353         {
1354                 ERROR ("cf_util_get_cdtime: The numeric argument of the %s "
1355                                 "option must not be negative.", ci->key);
1356                 return (-1);
1357         }
1358
1359         *ret_value = DOUBLE_TO_CDTIME_T (ci->values[0].value.number);
1360
1361         return (0);
1362 } /* }}} int cf_util_get_cdtime */
1363