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