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