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