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