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