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