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