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