From 97d77e3540972e60a3557382cefeb58a8b730191 Mon Sep 17 00:00:00 2001 From: Victor Julien Date: Tue, 13 Jan 2015 11:59:21 +0100 Subject: [PATCH] conf: add ConfYamlLoadFileWithPrefix Add function to load a yaml file and insert it into the conf tree at a specific prefix. Example YAML: somefile: myfile.txt If loaded using ConfYamlLoadFileWithPrefix with prefix "myprefix", it can be retrieved by the name of "myprefix.somefile". --- src/conf-yaml-loader.c | 65 ++++++++++++++++++++++++++++++++++++++++++ src/conf-yaml-loader.h | 2 ++ 2 files changed, 67 insertions(+) diff --git a/src/conf-yaml-loader.c b/src/conf-yaml-loader.c index 49ee6540d1..d61e495ce1 100644 --- a/src/conf-yaml-loader.c +++ b/src/conf-yaml-loader.c @@ -449,6 +449,71 @@ ConfYamlLoadString(const char *string, size_t len) return ret; } +/** + * \brief Load configuration from a YAML file, insert in tree at 'prefix' + * + * This function will load a configuration file and insert it into the + * config tree at 'prefix'. This means that if this is called with prefix + * "abc" and the file contains a parameter "def", it will be loaded as + * "abc.def". + * + * \param filename Filename of configuration file to load. + * \param prefix Name prefix to use. + * + * \retval 0 on success, -1 on failure. + */ +int +ConfYamlLoadFileWithPrefix(const char *filename, const char *prefix) +{ + FILE *infile; + yaml_parser_t parser; + int ret; + ConfNode *root = ConfGetNode(prefix); + + if (yaml_parser_initialize(&parser) != 1) { + SCLogError(SC_ERR_FATAL, "failed to initialize yaml parser."); + return -1; + } + + struct stat stat_buf; + if (stat(filename, &stat_buf) == 0) { + if (stat_buf.st_mode & S_IFDIR) { + SCLogError(SC_ERR_FATAL, "yaml argument is not a file but a directory: %s. " + "Please specify the yaml file in your -c option.", filename); + return -1; + } + } + + infile = fopen(filename, "r"); + if (infile == NULL) { + SCLogError(SC_ERR_FATAL, "failed to open file: %s: %s", filename, + strerror(errno)); + yaml_parser_delete(&parser); + return -1; + } + + if (conf_dirname == NULL) { + ConfYamlSetConfDirname(filename); + } + + if (root == NULL) { + /* if node at 'prefix' doesn't yet exist, add a place holder */ + ConfSet(prefix, ""); + root = ConfGetNode(prefix); + if (root == NULL) { + fclose(infile); + yaml_parser_delete(&parser); + return -1; + } + } + yaml_parser_set_input_file(&parser, infile); + ret = ConfYamlParse(&parser, root, 0); + yaml_parser_delete(&parser); + fclose(infile); + + return ret; +} + #ifdef UNITTESTS static int diff --git a/src/conf-yaml-loader.h b/src/conf-yaml-loader.h index 22dfb87773..6c599d0ac8 100644 --- a/src/conf-yaml-loader.h +++ b/src/conf-yaml-loader.h @@ -26,6 +26,8 @@ int ConfYamlLoadFile(const char *); int ConfYamlLoadString(const char *, size_t); +int ConfYamlLoadFileWithPrefix(const char *filename, const char *prefix); + void ConfYamlRegisterTests(void); #endif /* !__CONF_YAML_LOADER_H__ */