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