From: Florian Forster Date: Mon, 28 Nov 2016 21:16:04 +0000 (+0100) Subject: Merge branch 'collectd-5.6' X-Git-Tag: collectd-5.7.0~10 X-Git-Url: https://git.octo.it/?a=commitdiff_plain;h=facbb03bdd0c591344b1a81dd0437064cfcc24e5;hp=936c450a86c841eea89888c8550c9118fae90c25;p=collectd.git Merge branch 'collectd-5.6' --- diff --git a/ChangeLog b/ChangeLog index ff7ce70f..771ce9c6 100644 --- a/ChangeLog +++ b/ChangeLog @@ -180,6 +180,58 @@ * Zone plugin: This new plugin reads per-zone CPU usage on Solaris. Thanks to Mathijs Mohlmann and Dagobert Michelsen. +2016-11-28, Version 5.5.3 + * collectd: Write threads are stopped before shutdown callbacks are + called. Thanks to Florian Forster. #1110 + * collectd: A compile error on AIX has been fixed: "MSG_DONTWAIT" is not + available on AIX. Thanks to Chao Yang. + * libcollectdclient: Lines printed to "STDERR" are now guarded by the + environment variable "COLLECTD_TRACE". Thanks to Florian Forster. #105 + * collectd.conf(5): Various typos have been fixed. Thanks to Marc + Fournier. + * Build system: Detection of the Java environment has been made + deterministic to allow for reproducible builds. Thanks to Marc + Fournier. #1523 + * APC UPS plugin: Unavailable metrics are now skipped instead of + reported as 0 (zero). Thanks to Florian Forster. #2025 + * Battery plugin: The minimum value has been removed from the power type + to allow the plugin to report discharging batteries as negative power. + Thanks to Florian Forster. + * DBI, Oracle and PostgreSQL plugins: An error message when the type + instance is truncated has been added. Thanks to Florian Forster. #4 + * cURL-JSON plugin: A possible segmentation fault when parsing + unexpected JSON has been fixed. Thanks to Florian Forster. #1896 + * DF plugin: Compilation with xfsprogs ≥ 4.7.0 has been fixed. Thanks + to Thomas Deutschmann. #1877 + * Modbus plugin: Build issues on FreeBSD have been fixed. Thanks to + Florian Forster. + * Network plugin: An error message has been corrected. Thanks to Florian + Forster. + * Network plugin: Handling of errors form secure memory initialization + has been improved: the plugin fails gracefully now instead of calling + "abort()". Thanks to Sebastian Harl. + * Network plugin: The gcrypt library is only initialized when it is + actually required due to the network plugin's configuration. Thanks to + Florian Forster. #1902 + * Ping plugin: The init callback has been changed to be idempotent, + fixing errors being reported on Solaris. Thanks to Florian Forster. + #869 + * PostgreSQL plugin: The query_plans and query_plans_by_table queries + have been improved to return 0 (zero) instead of "NULL" when not + available. Thanks to Bernd Zeimetz. #1905 + * PowerDNS plugin: The "recursor command" has been fixed so PowerDNS can + correctly parse all requested fields. Thanks to Ruben Kerkhof. + * Python plugin: Handling of data sets with multiple data sources of + different type has been fixed. Thanks to Sebastian Harl. + * RRDCacheD plugin: Reconnection behavior after failed operations has + been added. Thanks to Sebastian Harl. Debian#657877 + * Write Graphite and AMQP plugins: A bug that could lead to a missing + null-termination has been fixed. Thanks to Markus Linnala. + * Write Kafka plugin: Support for librdkafka 0.9.0 has been added. + Thanks to Florian Forster. + * Write Riemann plugin: Build issues on Solaris have been fixed. Thanks + to Florian Forster. + 2016-07-25, Version 5.5.2 * collectd: A division by zero has been fixed in the "plugin_dispatch_multivalue()" function. Thanks to Corey Kosak. diff --git a/configure.ac b/configure.ac index fedb26f0..7f0dd5ca 100644 --- a/configure.ac +++ b/configure.ac @@ -2919,15 +2919,15 @@ fi if test "x$with_liblua" = "xyes" then - SAVE_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $LUA_CFLAGS" + SAVE_CPPFLAGS="$CPPFLAGS" + CPPFLAGS="$CPPFLAGS $LUA_CFLAGS" AC_CHECK_HEADERS([lua.h lauxlib.h lualib.h], [with_liblua="yes"], [with_liblua="no (header not found)"] ) - CFLAGS="$SAVE_CFLAGS" + CPPFLAGS="$SAVE_CPPFLAGS" fi if test "x$with_liblua" = "xyes" diff --git a/contrib/README b/contrib/README index 897d6197..5f401f09 100644 --- a/contrib/README +++ b/contrib/README @@ -17,6 +17,11 @@ collectd-network.py in pure Python. It currently supports to receive data and notifications from collectd. +collectd.service +---------------- + Service file for systemd. Please ship this file as + /lib/systemd/system/collectd.service in any linux package of collectd. + collectd-unixsock.py -------------------- This Python module by Clay Loveless provides an interface to collect's @@ -96,8 +101,3 @@ solaris-smf ----------- Manifest file for the Solaris SMF system and detailed information on how to register collectd as a service with this system. - -collectd.service ----------------- - Service file for systemd. Please ship this file as - /lib/systemd/system/collectd.service in any linux package of collectd. diff --git a/src/barometer.c b/src/barometer.c index b3f1b7f6..f698005c 100644 --- a/src/barometer.c +++ b/src/barometer.c @@ -368,19 +368,14 @@ static void temp_list_delete(temperature_list_t **list) { * Get reference temperature value * * First initially uc_get_rate_by_name is tried. At the startup due to - * nondeterministic - * order the temperature may not be read yet (then it fails and first measurment - * gives - * only absolute air pressure reading which is acceptable). Once it succedes - * (should be - * second measurement at the latest) we use average of few last readings from - * uc_get_history_by_name. It may take few readings to start filling so again we - * use - * uc_get_rate_by_name as a fallback. + * nondeterministic order the temperature may not be read yet (then it fails and + * first measurment gives only absolute air pressure reading which is + * acceptable). Once it succedes (should be second measurement at the latest) we + * use average of few last readings from uc_get_history_by_name. It may take few + * readings to start filling so again we use uc_get_rate_by_name as a fallback. * The idea is to use basic "noise" filtering (history averaging) across all the - * values - * which given sensor provides (up to given depth). Then we get minimum among - * the sensors. + * values which given sensor provides (up to given depth). Then we get minimum + * among the sensors. * * @param result where the result is stored. When not available NAN is stored. * @@ -405,9 +400,9 @@ static int get_reference_temperature(double *result) { avg_num = 0; /* First time need to read current rate to learn how many values are - there (typically for temperature it would be just one). - We do not expect dynamic changing of number of temperarure values - in runtime yet (are there any such cases?). */ + there (typically for temperature it would be just one). We do not expect + dynamic changing of number of temperarure values in runtime yet (are + there any such cases?). */ if (!list->initialized) { if (uc_get_rate_by_name(list->sensor_name, &values, &values_num)) { DEBUG( diff --git a/src/collectd-tg.c b/src/collectd-tg.c index 71f6040d..7ded64dd 100644 --- a/src/collectd-tg.c +++ b/src/collectd-tg.c @@ -388,11 +388,11 @@ int main(int argc, char **argv) /* {{{ */ double now = dtime(); while (now < vl->time) { - /* 1 / 100 second */ - struct timespec ts = {0, 10000000}; - - ts.tv_sec = (time_t)now; - ts.tv_nsec = (long)((now - ((double)ts.tv_sec)) * 1e9); + double diff = vl->time - now; + struct timespec ts = { + .tv_sec = (time_t)diff, + }; + ts.tv_nsec = (long)((diff - ((double)ts.tv_sec)) * 1e9); nanosleep(&ts, /* remaining = */ NULL); now = dtime(); diff --git a/src/utils_cmd_flush.h b/src/utils_cmd_flush.h index 9dbff20c..57b90853 100644 --- a/src/utils_cmd_flush.h +++ b/src/utils_cmd_flush.h @@ -31,15 +31,14 @@ #include "utils_cmds.h" -cmd_status_t cmd_parse_flush (size_t argc, char **argv, - cmd_flush_t *ret_flush, const cmd_options_t *opts, - cmd_error_handler_t *err); +cmd_status_t cmd_parse_flush(size_t argc, char **argv, cmd_flush_t *ret_flush, + const cmd_options_t *opts, + cmd_error_handler_t *err); -cmd_status_t cmd_handle_flush (FILE *fh, char *buffer); +cmd_status_t cmd_handle_flush(FILE *fh, char *buffer); -void cmd_destroy_flush (cmd_flush_t *flush); +void cmd_destroy_flush(cmd_flush_t *flush); #endif /* UTILS_CMD_FLUSH_H */ /* vim: set sw=4 ts=4 tw=78 noexpandtab : */ - diff --git a/src/utils_cmd_getthreshold.c b/src/utils_cmd_getthreshold.c index e6086f27..60363da5 100644 --- a/src/utils_cmd_getthreshold.c +++ b/src/utils_cmd_getthreshold.c @@ -30,20 +30,19 @@ #include "plugin.h" #include "utils_avltree.h" -#include "utils_threshold.h" -#include "utils_parse_option.h" /* for `parse_string' */ #include "utils_cmd_getthreshold.h" +#include "utils_parse_option.h" /* for `parse_string' */ +#include "utils_threshold.h" -#define print_to_socket(fh, ...) \ - if (fprintf (fh, __VA_ARGS__) < 0) { \ - char errbuf[1024]; \ - WARNING ("handle_getthreshold: failed to write to socket #%i: %s", \ - fileno (fh), sstrerror (errno, errbuf, sizeof (errbuf))); \ - return -1; \ +#define print_to_socket(fh, ...) \ + if (fprintf(fh, __VA_ARGS__) < 0) { \ + char errbuf[1024]; \ + WARNING("handle_getthreshold: failed to write to socket #%i: %s", \ + fileno(fh), sstrerror(errno, errbuf, sizeof(errbuf))); \ + return -1; \ } -int handle_getthreshold (FILE *fh, char *buffer) -{ +int handle_getthreshold(FILE *fh, char *buffer) { char *command; char *identifier; char *identifier_copy; @@ -56,131 +55,148 @@ int handle_getthreshold (FILE *fh, char *buffer) threshold_t threshold; - int status; + int status; size_t i; if ((fh == NULL) || (buffer == NULL)) return (-1); - DEBUG ("utils_cmd_getthreshold: handle_getthreshold (fh = %p, buffer = %s);", - (void *) fh, buffer); + DEBUG("utils_cmd_getthreshold: handle_getthreshold (fh = %p, buffer = %s);", + (void *)fh, buffer); command = NULL; - status = parse_string (&buffer, &command); - if (status != 0) - { - print_to_socket (fh, "-1 Cannot parse command.\n"); + status = parse_string(&buffer, &command); + if (status != 0) { + print_to_socket(fh, "-1 Cannot parse command.\n"); return (-1); } - assert (command != NULL); + assert(command != NULL); - if (strcasecmp ("GETTHRESHOLD", command) != 0) - { - print_to_socket (fh, "-1 Unexpected command: `%s'.\n", command); + if (strcasecmp("GETTHRESHOLD", command) != 0) { + print_to_socket(fh, "-1 Unexpected command: `%s'.\n", command); return (-1); } identifier = NULL; - status = parse_string (&buffer, &identifier); - if (status != 0) - { - print_to_socket (fh, "-1 Cannot parse identifier.\n"); + status = parse_string(&buffer, &identifier); + if (status != 0) { + print_to_socket(fh, "-1 Cannot parse identifier.\n"); return (-1); } - assert (identifier != NULL); + assert(identifier != NULL); - if (*buffer != 0) - { - print_to_socket (fh, "-1 Garbage after end of command: %s\n", buffer); + if (*buffer != 0) { + print_to_socket(fh, "-1 Garbage after end of command: %s\n", buffer); return (-1); } /* parse_identifier() modifies its first argument, * returning pointers into it */ - identifier_copy = sstrdup (identifier); - - status = parse_identifier (identifier_copy, &host, - &plugin, &plugin_instance, - &type, &type_instance, - /* default_host = */ NULL); - if (status != 0) - { - DEBUG ("handle_getthreshold: Cannot parse identifier `%s'.", identifier); - print_to_socket (fh, "-1 Cannot parse identifier `%s'.\n", identifier); - sfree (identifier_copy); + identifier_copy = sstrdup(identifier); + + status = parse_identifier(identifier_copy, &host, &plugin, &plugin_instance, + &type, &type_instance, + /* default_host = */ NULL); + if (status != 0) { + DEBUG("handle_getthreshold: Cannot parse identifier `%s'.", identifier); + print_to_socket(fh, "-1 Cannot parse identifier `%s'.\n", identifier); + sfree(identifier_copy); return (-1); } - value_list_t vl = { - .values = NULL - }; - sstrncpy (vl.host, host, sizeof (vl.host)); - sstrncpy (vl.plugin, plugin, sizeof (vl.plugin)); + value_list_t vl = {.values = NULL}; + sstrncpy(vl.host, host, sizeof(vl.host)); + sstrncpy(vl.plugin, plugin, sizeof(vl.plugin)); if (plugin_instance != NULL) - sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); - sstrncpy (vl.type, type, sizeof (vl.type)); + sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance)); + sstrncpy(vl.type, type, sizeof(vl.type)); if (type_instance != NULL) - sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); - sfree (identifier_copy); - - status = ut_search_threshold (&vl, &threshold); - if (status == ENOENT) - { - print_to_socket (fh, "-1 No threshold found for identifier %s\n", - identifier); + sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance)); + sfree(identifier_copy); + + status = ut_search_threshold(&vl, &threshold); + if (status == ENOENT) { + print_to_socket(fh, "-1 No threshold found for identifier %s\n", + identifier); return (0); - } - else if (status != 0) - { - print_to_socket (fh, "-1 Error while looking up threshold: %i\n", - status); + } else if (status != 0) { + print_to_socket(fh, "-1 Error while looking up threshold: %i\n", status); return (-1); } /* Lets count the number of lines we'll return. */ i = 0; - if (threshold.host[0] != 0) i++; - if (threshold.plugin[0] != 0) i++; - if (threshold.plugin_instance[0] != 0) i++; - if (threshold.type[0] != 0) i++; - if (threshold.type_instance[0] != 0) i++; - if (threshold.data_source[0] != 0) i++; - if (!isnan (threshold.warning_min)) i++; - if (!isnan (threshold.warning_max)) i++; - if (!isnan (threshold.failure_min)) i++; - if (!isnan (threshold.failure_max)) i++; - if (threshold.hysteresis > 0.0) i++; - if (threshold.hits > 1) i++; - - /* Print the response */ - print_to_socket (fh, "%zu Threshold found\n", i); - if (threshold.host[0] != 0) - print_to_socket (fh, "Host: %s\n", threshold.host) + i++; if (threshold.plugin[0] != 0) - print_to_socket (fh, "Plugin: %s\n", threshold.plugin) + i++; if (threshold.plugin_instance[0] != 0) - print_to_socket (fh, "Plugin Instance: %s\n", threshold.plugin_instance) + i++; if (threshold.type[0] != 0) - print_to_socket (fh, "Type: %s\n", threshold.type) + i++; if (threshold.type_instance[0] != 0) - print_to_socket (fh, "Type Instance: %s\n", threshold.type_instance) + i++; if (threshold.data_source[0] != 0) - print_to_socket (fh, "Data Source: %s\n", threshold.data_source) - if (!isnan (threshold.warning_min)) - print_to_socket (fh, "Warning Min: %g\n", threshold.warning_min) - if (!isnan (threshold.warning_max)) - print_to_socket (fh, "Warning Max: %g\n", threshold.warning_max) - if (!isnan (threshold.failure_min)) - print_to_socket (fh, "Failure Min: %g\n", threshold.failure_min) - if (!isnan (threshold.failure_max)) - print_to_socket (fh, "Failure Max: %g\n", threshold.failure_max) + i++; + if (!isnan(threshold.warning_min)) + i++; + if (!isnan(threshold.warning_max)) + i++; + if (!isnan(threshold.failure_min)) + i++; + if (!isnan(threshold.failure_max)) + i++; if (threshold.hysteresis > 0.0) - print_to_socket (fh, "Hysteresis: %g\n", threshold.hysteresis) + i++; if (threshold.hits > 1) - print_to_socket (fh, "Hits: %i\n", threshold.hits) + i++; - return (0); + /* Print the response */ + print_to_socket(fh, "%zu Threshold found\n", i); + + if (threshold.host[0] != 0) + print_to_socket(fh, "Host: %s\n", threshold.host) if ( + threshold.plugin[0] != + 0) print_to_socket(fh, "Plugin: %s\n", + threshold.plugin) if (threshold.plugin_instance[0] != + 0) + print_to_socket(fh, "Plugin Instance: %s\n", + threshold.plugin_instance) if (threshold.type[0] != 0) + print_to_socket(fh, "Type: %s\n", threshold.type) if ( + threshold.type_instance[0] != + 0) print_to_socket(fh, "Type Instance: %s\n", + threshold + .type_instance) if (threshold.data_source + [0] != 0) + print_to_socket( + fh, "Data Source: %s\n", + threshold.data_source) if (!isnan(threshold.warning_min)) + print_to_socket( + fh, "Warning Min: %g\n", + threshold + .warning_min) if (!isnan(threshold.warning_max)) + print_to_socket( + fh, "Warning Max: %g\n", + threshold + .warning_max) if (!isnan(threshold.failure_min)) + print_to_socket( + fh, "Failure Min: %g\n", + threshold + .failure_min) if (!isnan(threshold + .failure_max)) + print_to_socket( + fh, "Failure Max: %g\n", + threshold.failure_max) if (threshold + .hysteresis > + 0.0) + print_to_socket( + fh, "Hysteresis: %g\n", + threshold.hysteresis) if (threshold + .hits > 1) + print_to_socket(fh, "Hits: %i\n", + threshold.hits) + + return (0); } /* int handle_getthreshold */ /* vim: set sw=2 sts=2 ts=8 et : */ diff --git a/src/utils_cmd_getthreshold.h b/src/utils_cmd_getthreshold.h index 8d581c80..dd4e5cf8 100644 --- a/src/utils_cmd_getthreshold.h +++ b/src/utils_cmd_getthreshold.h @@ -29,7 +29,7 @@ #include -int handle_getthreshold (FILE *fh, char *buffer); +int handle_getthreshold(FILE *fh, char *buffer); #endif /* UTILS_CMD_GETTHRESHOLD_H */ diff --git a/src/utils_cmd_getval.c b/src/utils_cmd_getval.c index f29680a1..c23650b3 100644 --- a/src/utils_cmd_getval.c +++ b/src/utils_cmd_getval.c @@ -30,47 +30,44 @@ #include "plugin.h" #include "utils_cache.h" -#include "utils_parse_option.h" #include "utils_cmd_getval.h" +#include "utils_parse_option.h" -cmd_status_t cmd_parse_getval (size_t argc, char **argv, - cmd_getval_t *ret_getval, const cmd_options_t *opts, - cmd_error_handler_t *err) -{ +cmd_status_t cmd_parse_getval(size_t argc, char **argv, + cmd_getval_t *ret_getval, + const cmd_options_t *opts, + cmd_error_handler_t *err) { char *identifier_copy; int status; - if ((ret_getval == NULL) || (opts == NULL)) - { + if ((ret_getval == NULL) || (opts == NULL)) { errno = EINVAL; - cmd_error (CMD_ERROR, err, "Invalid arguments to cmd_parse_getval."); + cmd_error(CMD_ERROR, err, "Invalid arguments to cmd_parse_getval."); return (CMD_ERROR); } - if (argc != 1) - { + if (argc != 1) { if (argc == 0) - cmd_error (CMD_PARSE_ERROR, err, "Missing identifier."); + cmd_error(CMD_PARSE_ERROR, err, "Missing identifier."); else - cmd_error (CMD_PARSE_ERROR, err, - "Garbage after identifier: `%s'.", argv[1]); + cmd_error(CMD_PARSE_ERROR, err, "Garbage after identifier: `%s'.", + argv[1]); return (CMD_PARSE_ERROR); } /* parse_identifier() modifies its first argument, * returning pointers into it */ - identifier_copy = sstrdup (argv[0]); - - status = parse_identifier (argv[0], &ret_getval->identifier.host, - &ret_getval->identifier.plugin, &ret_getval->identifier.plugin_instance, - &ret_getval->identifier.type, &ret_getval->identifier.type_instance, - opts->identifier_default_host); - if (status != 0) - { - DEBUG ("cmd_parse_getval: Cannot parse identifier `%s'.", identifier_copy); - cmd_error (CMD_PARSE_ERROR, err, - "Cannot parse identifier `%s'.", identifier_copy); - sfree (identifier_copy); + identifier_copy = sstrdup(argv[0]); + + status = parse_identifier( + argv[0], &ret_getval->identifier.host, &ret_getval->identifier.plugin, + &ret_getval->identifier.plugin_instance, &ret_getval->identifier.type, + &ret_getval->identifier.type_instance, opts->identifier_default_host); + if (status != 0) { + DEBUG("cmd_parse_getval: Cannot parse identifier `%s'.", identifier_copy); + cmd_error(CMD_PARSE_ERROR, err, "Cannot parse identifier `%s'.", + identifier_copy); + sfree(identifier_copy); return (CMD_PARSE_ERROR); } @@ -78,20 +75,19 @@ cmd_status_t cmd_parse_getval (size_t argc, char **argv, return (CMD_OK); } /* cmd_status_t cmd_parse_getval */ -#define print_to_socket(fh, ...) \ - do { \ - if (fprintf (fh, __VA_ARGS__) < 0) { \ - char errbuf[1024]; \ - WARNING ("cmd_handle_getval: failed to write to socket #%i: %s", \ - fileno (fh), sstrerror (errno, errbuf, sizeof (errbuf))); \ - return -1; \ - } \ - fflush(fh); \ +#define print_to_socket(fh, ...) \ + do { \ + if (fprintf(fh, __VA_ARGS__) < 0) { \ + char errbuf[1024]; \ + WARNING("cmd_handle_getval: failed to write to socket #%i: %s", \ + fileno(fh), sstrerror(errno, errbuf, sizeof(errbuf))); \ + return -1; \ + } \ + fflush(fh); \ } while (0) -cmd_status_t cmd_handle_getval (FILE *fh, char *buffer) -{ - cmd_error_handler_t err = { cmd_error_fh, fh }; +cmd_status_t cmd_handle_getval(FILE *fh, char *buffer) { + cmd_error_handler_t err = {cmd_error_fh, fh}; cmd_status_t status; cmd_t cmd; @@ -100,82 +96,73 @@ cmd_status_t cmd_handle_getval (FILE *fh, char *buffer) const data_set_t *ds; - if ((fh == NULL) || (buffer == NULL)) return (-1); - DEBUG ("utils_cmd_getval: cmd_handle_getval (fh = %p, buffer = %s);", - (void *) fh, buffer); + DEBUG("utils_cmd_getval: cmd_handle_getval (fh = %p, buffer = %s);", + (void *)fh, buffer); - if ((status = cmd_parse (buffer, &cmd, NULL, &err)) != CMD_OK) + if ((status = cmd_parse(buffer, &cmd, NULL, &err)) != CMD_OK) return (status); - if (cmd.type != CMD_GETVAL) - { - cmd_error (CMD_UNKNOWN_COMMAND, &err, - "Unexpected command: `%s'.", CMD_TO_STRING (cmd.type)); - cmd_destroy (&cmd); + if (cmd.type != CMD_GETVAL) { + cmd_error(CMD_UNKNOWN_COMMAND, &err, "Unexpected command: `%s'.", + CMD_TO_STRING(cmd.type)); + cmd_destroy(&cmd); return (CMD_UNKNOWN_COMMAND); } - ds = plugin_get_ds (cmd.cmd.getval.identifier.type); - if (ds == NULL) - { - DEBUG ("cmd_handle_getval: plugin_get_ds (%s) == NULL;", - cmd.cmd.getval.identifier.type); - cmd_error (CMD_ERROR, &err, "Type `%s' is unknown.\n", - cmd.cmd.getval.identifier.type); - cmd_destroy (&cmd); + ds = plugin_get_ds(cmd.cmd.getval.identifier.type); + if (ds == NULL) { + DEBUG("cmd_handle_getval: plugin_get_ds (%s) == NULL;", + cmd.cmd.getval.identifier.type); + cmd_error(CMD_ERROR, &err, "Type `%s' is unknown.\n", + cmd.cmd.getval.identifier.type); + cmd_destroy(&cmd); return (-1); } values = NULL; values_num = 0; - status = uc_get_rate_by_name (cmd.cmd.getval.raw_identifier, &values, &values_num); - if (status != 0) - { - cmd_error (CMD_ERROR, &err, "No such value."); - cmd_destroy (&cmd); + status = + uc_get_rate_by_name(cmd.cmd.getval.raw_identifier, &values, &values_num); + if (status != 0) { + cmd_error(CMD_ERROR, &err, "No such value."); + cmd_destroy(&cmd); return (CMD_ERROR); } - if (ds->ds_num != values_num) - { - ERROR ("ds[%s]->ds_num = %zu, " - "but uc_get_rate_by_name returned %zu values.", - ds->type, ds->ds_num, values_num); - cmd_error (CMD_ERROR, &err, "Error reading value from cache."); - sfree (values); - cmd_destroy (&cmd); + if (ds->ds_num != values_num) { + ERROR("ds[%s]->ds_num = %zu, " + "but uc_get_rate_by_name returned %zu values.", + ds->type, ds->ds_num, values_num); + cmd_error(CMD_ERROR, &err, "Error reading value from cache."); + sfree(values); + cmd_destroy(&cmd); return (CMD_ERROR); } - print_to_socket (fh, "%zu Value%s found\n", values_num, - (values_num == 1) ? "" : "s"); - for (size_t i = 0; i < values_num; i++) - { - print_to_socket (fh, "%s=", ds->ds[i].name); - if (isnan (values[i])) - { - print_to_socket (fh, "NaN\n"); - } - else - { - print_to_socket (fh, "%12e\n", values[i]); + print_to_socket(fh, "%zu Value%s found\n", values_num, + (values_num == 1) ? "" : "s"); + for (size_t i = 0; i < values_num; i++) { + print_to_socket(fh, "%s=", ds->ds[i].name); + if (isnan(values[i])) { + print_to_socket(fh, "NaN\n"); + } else { + print_to_socket(fh, "%12e\n", values[i]); } } - sfree (values); - cmd_destroy (&cmd); + sfree(values); + cmd_destroy(&cmd); return (CMD_OK); } /* cmd_status_t cmd_handle_getval */ -void cmd_destroy_getval (cmd_getval_t *getval) -{ +void cmd_destroy_getval(cmd_getval_t *getval) { if (getval == NULL) return; - sfree (getval->raw_identifier); + sfree(getval->raw_identifier); } /* void cmd_destroy_getval */ /* vim: set sw=2 sts=2 ts=8 : */ diff --git a/src/utils_cmd_getval.h b/src/utils_cmd_getval.h index b0c64be1..8d488b31 100644 --- a/src/utils_cmd_getval.h +++ b/src/utils_cmd_getval.h @@ -31,13 +31,14 @@ #include "utils_cmds.h" -cmd_status_t cmd_parse_getval (size_t argc, char **argv, - cmd_getval_t *ret_getval, const cmd_options_t *opts, - cmd_error_handler_t *err); +cmd_status_t cmd_parse_getval(size_t argc, char **argv, + cmd_getval_t *ret_getval, + const cmd_options_t *opts, + cmd_error_handler_t *err); -cmd_status_t cmd_handle_getval (FILE *fh, char *buffer); +cmd_status_t cmd_handle_getval(FILE *fh, char *buffer); -void cmd_destroy_getval (cmd_getval_t *getval); +void cmd_destroy_getval(cmd_getval_t *getval); #endif /* UTILS_CMD_GETVAL_H */ diff --git a/src/utils_cmd_listval.c b/src/utils_cmd_listval.c index 27b88cbf..f8638893 100644 --- a/src/utils_cmd_listval.c +++ b/src/utils_cmd_listval.c @@ -29,49 +29,49 @@ #include "common.h" #include "plugin.h" -#include "utils_cmd_listval.h" #include "utils_cache.h" +#include "utils_cmd_listval.h" #include "utils_parse_option.h" -cmd_status_t cmd_parse_listval (size_t argc, char **argv, - cmd_listval_t *ret_listval __attribute__((unused)), - const cmd_options_t *opts __attribute__((unused)), - cmd_error_handler_t *err) -{ - if (argc != 0) - { - cmd_error (CMD_PARSE_ERROR, err, - "Garbage after end of command: `%s'.", argv[0]); +cmd_status_t cmd_parse_listval(size_t argc, char **argv, + cmd_listval_t *ret_listval + __attribute__((unused)), + const cmd_options_t *opts + __attribute__((unused)), + cmd_error_handler_t *err) { + if (argc != 0) { + cmd_error(CMD_PARSE_ERROR, err, "Garbage after end of command: `%s'.", + argv[0]); return (CMD_PARSE_ERROR); } return (CMD_OK); } /* cmd_status_t cmd_parse_listval */ -#define free_everything_and_return(status) do { \ - for (size_t j = 0; j < number; j++) { \ - sfree(names[j]); \ - names[j] = NULL; \ - } \ - sfree(names); \ - sfree(times); \ - return (status); \ +#define free_everything_and_return(status) \ + do { \ + for (size_t j = 0; j < number; j++) { \ + sfree(names[j]); \ + names[j] = NULL; \ + } \ + sfree(names); \ + sfree(times); \ + return (status); \ } while (0) -#define print_to_socket(fh, ...) \ - do { \ - if (fprintf (fh, __VA_ARGS__) < 0) { \ - char errbuf[1024]; \ - WARNING ("handle_listval: failed to write to socket #%i: %s", \ - fileno (fh), sstrerror (errno, errbuf, sizeof (errbuf))); \ - free_everything_and_return (CMD_ERROR); \ - } \ - fflush(fh); \ +#define print_to_socket(fh, ...) \ + do { \ + if (fprintf(fh, __VA_ARGS__) < 0) { \ + char errbuf[1024]; \ + WARNING("handle_listval: failed to write to socket #%i: %s", fileno(fh), \ + sstrerror(errno, errbuf, sizeof(errbuf))); \ + free_everything_and_return(CMD_ERROR); \ + } \ + fflush(fh); \ } while (0) -cmd_status_t cmd_handle_listval (FILE *fh, char *buffer) -{ - cmd_error_handler_t err = { cmd_error_fh, fh }; +cmd_status_t cmd_handle_listval(FILE *fh, char *buffer) { + cmd_error_handler_t err = {cmd_error_fh, fh}; cmd_status_t status; cmd_t cmd; @@ -79,37 +79,33 @@ cmd_status_t cmd_handle_listval (FILE *fh, char *buffer) cdtime_t *times = NULL; size_t number = 0; - DEBUG ("utils_cmd_listval: handle_listval (fh = %p, buffer = %s);", - (void *) fh, buffer); + DEBUG("utils_cmd_listval: handle_listval (fh = %p, buffer = %s);", (void *)fh, + buffer); - if ((status = cmd_parse (buffer, &cmd, NULL, &err)) != CMD_OK) + if ((status = cmd_parse(buffer, &cmd, NULL, &err)) != CMD_OK) return (status); - if (cmd.type != CMD_LISTVAL) - { - cmd_error (CMD_UNKNOWN_COMMAND, &err, - "Unexpected command: `%s'.", CMD_TO_STRING (cmd.type)); - free_everything_and_return (CMD_UNKNOWN_COMMAND); + if (cmd.type != CMD_LISTVAL) { + cmd_error(CMD_UNKNOWN_COMMAND, &err, "Unexpected command: `%s'.", + CMD_TO_STRING(cmd.type)); + free_everything_and_return(CMD_UNKNOWN_COMMAND); } - status = uc_get_names (&names, ×, &number); - if (status != 0) - { - DEBUG ("command listval: uc_get_names failed with status %i", status); - cmd_error (CMD_ERROR, &err, "uc_get_names failed."); - free_everything_and_return (CMD_ERROR); + status = uc_get_names(&names, ×, &number); + if (status != 0) { + DEBUG("command listval: uc_get_names failed with status %i", status); + cmd_error(CMD_ERROR, &err, "uc_get_names failed."); + free_everything_and_return(CMD_ERROR); } - print_to_socket (fh, "%i Value%s found\n", - (int) number, (number == 1) ? "" : "s"); + print_to_socket(fh, "%i Value%s found\n", (int)number, + (number == 1) ? "" : "s"); for (size_t i = 0; i < number; i++) - print_to_socket (fh, "%.3f %s\n", CDTIME_T_TO_DOUBLE (times[i]), - names[i]); + print_to_socket(fh, "%.3f %s\n", CDTIME_T_TO_DOUBLE(times[i]), names[i]); - free_everything_and_return (CMD_OK); + free_everything_and_return(CMD_OK); } /* cmd_status_t cmd_handle_listval */ -void cmd_destroy_listval (cmd_listval_t *listval __attribute__((unused))) -{ +void cmd_destroy_listval(cmd_listval_t *listval __attribute__((unused))) { /* nothing to do */ } /* void cmd_destroy_listval */ diff --git a/src/utils_cmd_listval.h b/src/utils_cmd_listval.h index 895878c0..8a4e8c8b 100644 --- a/src/utils_cmd_listval.h +++ b/src/utils_cmd_listval.h @@ -31,13 +31,14 @@ #include "utils_cmds.h" -cmd_status_t cmd_parse_listval (size_t argc, char **argv, - cmd_listval_t *ret_listval, const cmd_options_t *opts, - cmd_error_handler_t *err); +cmd_status_t cmd_parse_listval(size_t argc, char **argv, + cmd_listval_t *ret_listval, + const cmd_options_t *opts, + cmd_error_handler_t *err); -cmd_status_t cmd_handle_listval (FILE *fh, char *buffer); +cmd_status_t cmd_handle_listval(FILE *fh, char *buffer); -void cmd_destroy_listval (cmd_listval_t *listval); +void cmd_destroy_listval(cmd_listval_t *listval); #endif /* UTILS_CMD_LISTVAL_H */ diff --git a/src/utils_cmd_putnotif.c b/src/utils_cmd_putnotif.c index 669ef837..0edfbb86 100644 --- a/src/utils_cmd_putnotif.c +++ b/src/utils_cmd_putnotif.c @@ -29,27 +29,26 @@ #include "common.h" #include "plugin.h" -#include "utils_parse_option.h" #include "utils_cmd_putnotif.h" +#include "utils_parse_option.h" -#define print_to_socket(fh, ...) \ - do { \ - if (fprintf (fh, __VA_ARGS__) < 0) { \ - char errbuf[1024]; \ - WARNING ("handle_putnotif: failed to write to socket #%i: %s", \ - fileno (fh), sstrerror (errno, errbuf, sizeof (errbuf))); \ - return -1; \ - } \ - fflush(fh); \ +#define print_to_socket(fh, ...) \ + do { \ + if (fprintf(fh, __VA_ARGS__) < 0) { \ + char errbuf[1024]; \ + WARNING("handle_putnotif: failed to write to socket #%i: %s", \ + fileno(fh), sstrerror(errno, errbuf, sizeof(errbuf))); \ + return -1; \ + } \ + fflush(fh); \ } while (0) -static int set_option_severity (notification_t *n, const char *value) -{ - if (strcasecmp (value, "Failure") == 0) +static int set_option_severity(notification_t *n, const char *value) { + if (strcasecmp(value, "Failure") == 0) n->severity = NOTIF_FAILURE; - else if (strcasecmp (value, "Warning") == 0) + else if (strcasecmp(value, "Warning") == 0) n->severity = NOTIF_WARNING; - else if (strcasecmp (value, "Okay") == 0) + else if (strcasecmp(value, "Okay") == 0) n->severity = NOTIF_OKAY; else return (-1); @@ -57,31 +56,30 @@ static int set_option_severity (notification_t *n, const char *value) return (0); } /* int set_option_severity */ -static int set_option_time (notification_t *n, const char *value) -{ +static int set_option_time(notification_t *n, const char *value) { char *endptr = NULL; double tmp; errno = 0; - tmp = strtod (value, &endptr); + tmp = strtod(value, &endptr); if ((errno != 0) /* Overflow */ || (endptr == value) /* Invalid string */ || (endptr == NULL) /* This should not happen */ || (*endptr != 0)) /* Trailing chars */ return (-1); - n->time = DOUBLE_TO_CDTIME_T (tmp); + n->time = DOUBLE_TO_CDTIME_T(tmp); return (0); } /* int set_option_time */ -static int set_option (notification_t *n, const char *option, const char *value) -{ +static int set_option(notification_t *n, const char *option, + const char *value) { if ((n == NULL) || (option == NULL) || (value == NULL)) return (-1); - DEBUG ("utils_cmd_putnotif: set_option (option = %s, value = %s);", - option, value); + DEBUG("utils_cmd_putnotif: set_option (option = %s, value = %s);", option, + value); /* Add a meta option in the form: : */ if (option[0] != '\0' && option[1] == ':') { @@ -90,104 +88,94 @@ static int set_option (notification_t *n, const char *option, const char *value) return (1); if (option[0] == 's') - return plugin_notification_meta_add_string (n, option + 2, value); + return plugin_notification_meta_add_string(n, option + 2, value); else return (1); } - if (strcasecmp ("severity", option) == 0) - return (set_option_severity (n, value)); - else if (strcasecmp ("time", option) == 0) - return (set_option_time (n, value)); - else if (strcasecmp ("message", option) == 0) - sstrncpy (n->message, value, sizeof (n->message)); - else if (strcasecmp ("host", option) == 0) - sstrncpy (n->host, value, sizeof (n->host)); - else if (strcasecmp ("plugin", option) == 0) - sstrncpy (n->plugin, value, sizeof (n->plugin)); - else if (strcasecmp ("plugin_instance", option) == 0) - sstrncpy (n->plugin_instance, value, sizeof (n->plugin_instance)); - else if (strcasecmp ("type", option) == 0) - sstrncpy (n->type, value, sizeof (n->type)); - else if (strcasecmp ("type_instance", option) == 0) - sstrncpy (n->type_instance, value, sizeof (n->type_instance)); + if (strcasecmp("severity", option) == 0) + return (set_option_severity(n, value)); + else if (strcasecmp("time", option) == 0) + return (set_option_time(n, value)); + else if (strcasecmp("message", option) == 0) + sstrncpy(n->message, value, sizeof(n->message)); + else if (strcasecmp("host", option) == 0) + sstrncpy(n->host, value, sizeof(n->host)); + else if (strcasecmp("plugin", option) == 0) + sstrncpy(n->plugin, value, sizeof(n->plugin)); + else if (strcasecmp("plugin_instance", option) == 0) + sstrncpy(n->plugin_instance, value, sizeof(n->plugin_instance)); + else if (strcasecmp("type", option) == 0) + sstrncpy(n->type, value, sizeof(n->type)); + else if (strcasecmp("type_instance", option) == 0) + sstrncpy(n->type_instance, value, sizeof(n->type_instance)); else return (1); return (0); } /* int set_option */ -int handle_putnotif (FILE *fh, char *buffer) -{ +int handle_putnotif(FILE *fh, char *buffer) { char *command; - notification_t n = { 0 }; + notification_t n = {0}; int status; if ((fh == NULL) || (buffer == NULL)) return (-1); - DEBUG ("utils_cmd_putnotif: handle_putnotif (fh = %p, buffer = %s);", - (void *) fh, buffer); + DEBUG("utils_cmd_putnotif: handle_putnotif (fh = %p, buffer = %s);", + (void *)fh, buffer); command = NULL; - status = parse_string (&buffer, &command); - if (status != 0) - { - print_to_socket (fh, "-1 Cannot parse command.\n"); + status = parse_string(&buffer, &command); + if (status != 0) { + print_to_socket(fh, "-1 Cannot parse command.\n"); return (-1); } - assert (command != NULL); + assert(command != NULL); - if (strcasecmp ("PUTNOTIF", command) != 0) - { - print_to_socket (fh, "-1 Unexpected command: `%s'.\n", command); + if (strcasecmp("PUTNOTIF", command) != 0) { + print_to_socket(fh, "-1 Unexpected command: `%s'.\n", command); return (-1); } status = 0; - while (*buffer != 0) - { + while (*buffer != 0) { char *key; char *value; - status = parse_option (&buffer, &key, &value); - if (status != 0) - { - print_to_socket (fh, "-1 Malformed option.\n"); + status = parse_option(&buffer, &key, &value); + if (status != 0) { + print_to_socket(fh, "-1 Malformed option.\n"); break; } - status = set_option (&n, key, value); - if (status != 0) - { - print_to_socket (fh, "-1 Error parsing option `%s'\n", key); + status = set_option(&n, key, value); + if (status != 0) { + print_to_socket(fh, "-1 Error parsing option `%s'\n", key); break; } } /* for (i) */ /* Check for required fields and complain if anything is missing. */ - if ((status == 0) && (n.severity == 0)) - { - print_to_socket (fh, "-1 Option `severity' missing.\n"); + if ((status == 0) && (n.severity == 0)) { + print_to_socket(fh, "-1 Option `severity' missing.\n"); status = -1; } - if ((status == 0) && (n.time == 0)) - { - print_to_socket (fh, "-1 Option `time' missing.\n"); + if ((status == 0) && (n.time == 0)) { + print_to_socket(fh, "-1 Option `time' missing.\n"); status = -1; } - if ((status == 0) && (strlen (n.message) == 0)) - { - print_to_socket (fh, "-1 No message or message of length 0 given.\n"); + if ((status == 0) && (strlen(n.message) == 0)) { + print_to_socket(fh, "-1 No message or message of length 0 given.\n"); status = -1; } /* If status is still zero the notification is fine and we can finally * dispatch it. */ - if (status == 0) - { - plugin_dispatch_notification (&n); - print_to_socket (fh, "0 Success\n"); + if (status == 0) { + plugin_dispatch_notification(&n); + print_to_socket(fh, "0 Success\n"); } return (0); diff --git a/src/utils_cmd_putnotif.h b/src/utils_cmd_putnotif.h index 9d699eca..af0b93e0 100644 --- a/src/utils_cmd_putnotif.h +++ b/src/utils_cmd_putnotif.h @@ -29,7 +29,7 @@ #include -int handle_putnotif (FILE *fh, char *buffer); +int handle_putnotif(FILE *fh, char *buffer); /* vim: set shiftwidth=2 softtabstop=2 tabstop=8 : */ diff --git a/src/utils_cmd_putval.c b/src/utils_cmd_putval.c index 691f1f80..e0455335 100644 --- a/src/utils_cmd_putval.c +++ b/src/utils_cmd_putval.c @@ -31,283 +31,256 @@ #include "common.h" #include "plugin.h" -#include "utils_cmds.h" #include "utils_cmd_putval.h" -#include "utils_parse_option.h" #include "utils_cmd_putval.h" +#include "utils_cmds.h" +#include "utils_parse_option.h" /* * private helper functions */ -static int set_option (value_list_t *vl, const char *key, const char *value) -{ - if ((vl == NULL) || (key == NULL) || (value == NULL)) - return (-1); +static int set_option(value_list_t *vl, const char *key, const char *value) { + if ((vl == NULL) || (key == NULL) || (value == NULL)) + return (-1); - if (strcasecmp ("interval", key) == 0) - { - double tmp; - char *endptr; + if (strcasecmp("interval", key) == 0) { + double tmp; + char *endptr; - endptr = NULL; - errno = 0; - tmp = strtod (value, &endptr); + endptr = NULL; + errno = 0; + tmp = strtod(value, &endptr); - if ((errno == 0) && (endptr != NULL) - && (endptr != value) && (tmp > 0.0)) - vl->interval = DOUBLE_TO_CDTIME_T (tmp); - } - else - return (1); + if ((errno == 0) && (endptr != NULL) && (endptr != value) && (tmp > 0.0)) + vl->interval = DOUBLE_TO_CDTIME_T(tmp); + } else + return (1); - return (0); + return (0); } /* int set_option */ /* * public API */ -cmd_status_t cmd_parse_putval (size_t argc, char **argv, - cmd_putval_t *ret_putval, const cmd_options_t *opts, - cmd_error_handler_t *err) -{ - cmd_status_t result; - - char *identifier; - char *hostname; - char *plugin; - char *plugin_instance; - char *type; - char *type_instance; - int status; - - char *identifier_copy; - - const data_set_t *ds; - value_list_t vl = VALUE_LIST_INIT; - - if ((ret_putval == NULL) || (opts == NULL)) - { - errno = EINVAL; - cmd_error (CMD_ERROR, err, "Invalid arguments to cmd_parse_putval."); - return (CMD_ERROR); - } - - if (argc < 2) - { - cmd_error (CMD_PARSE_ERROR, err, - "Missing identifier and/or value-list."); - return (CMD_PARSE_ERROR); - } - - identifier = argv[0]; - - /* parse_identifier() modifies its first argument, returning pointers into - * it; retain the old value for later. */ - identifier_copy = sstrdup (identifier); - - status = parse_identifier (identifier, &hostname, - &plugin, &plugin_instance, - &type, &type_instance, - opts->identifier_default_host); - if (status != 0) - { - DEBUG ("cmd_handle_putval: Cannot parse identifier `%s'.", - identifier_copy); - cmd_error (CMD_PARSE_ERROR, err, "Cannot parse identifier `%s'.", - identifier_copy); - sfree (identifier_copy); - return (CMD_PARSE_ERROR); - } - - if ((strlen (hostname) >= sizeof (vl.host)) - || (strlen (plugin) >= sizeof (vl.plugin)) - || ((plugin_instance != NULL) - && (strlen (plugin_instance) >= sizeof (vl.plugin_instance))) - || ((type_instance != NULL) - && (strlen (type_instance) >= sizeof (vl.type_instance)))) - { - cmd_error (CMD_PARSE_ERROR, err, "Identifier too long."); - sfree (identifier_copy); - return (CMD_PARSE_ERROR); - } - - sstrncpy (vl.host, hostname, sizeof (vl.host)); - sstrncpy (vl.plugin, plugin, sizeof (vl.plugin)); - sstrncpy (vl.type, type, sizeof (vl.type)); - if (plugin_instance != NULL) - sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); - if (type_instance != NULL) - sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); - - ds = plugin_get_ds (type); - if (ds == NULL) - { - cmd_error (CMD_PARSE_ERROR, err, "1 Type `%s' isn't defined.", type); - sfree (identifier_copy); - return (CMD_PARSE_ERROR); - } - - hostname = NULL; - plugin = NULL; plugin_instance = NULL; - type = NULL; type_instance = NULL; - - vl.values_len = ds->ds_num; - vl.values = malloc (vl.values_len * sizeof (*vl.values)); - if (vl.values == NULL) - { - cmd_error (CMD_ERROR, err, "malloc failed."); - sfree (identifier_copy); - return (CMD_ERROR); - } - - ret_putval->raw_identifier = identifier_copy; - if (ret_putval->raw_identifier == NULL) - { - cmd_error (CMD_ERROR, err, "malloc failed."); - cmd_destroy_putval (ret_putval); - sfree (vl.values); - return (CMD_ERROR); - } - - /* All the remaining fields are part of the option list. */ - result = CMD_OK; - for (size_t i = 1; i < argc; ++i) - { - value_list_t *tmp; - - char *key = NULL; - char *value = NULL; - - status = cmd_parse_option (argv[i], &key, &value, err); - if (status == CMD_OK) - { - assert (key != NULL); - assert (value != NULL); - set_option (&vl, key, value); - continue; - } - else if (status != CMD_NO_OPTION) - { - /* parse_option failed, buffer has been modified. - * => we need to abort */ - result = status; - break; - } - /* else: cmd_parse_option did not find an option; treat this as a - * value list. */ - - status = parse_values (argv[i], &vl, ds); - if (status != 0) - { - cmd_error (CMD_PARSE_ERROR, err, "Parsing the values string failed."); - result = CMD_PARSE_ERROR; - break; - } - - tmp = (value_list_t *) realloc (ret_putval->vl, - (ret_putval->vl_num + 1) * sizeof(*ret_putval->vl)); - if (tmp == NULL) - { - cmd_error (CMD_ERROR, err, "realloc failed."); - cmd_destroy_putval (ret_putval); - result = CMD_ERROR; - break; - } - - ret_putval->vl = tmp; - ret_putval->vl_num++; - memcpy (&ret_putval->vl[ret_putval->vl_num - 1], &vl, sizeof (vl)); - } /* while (*buffer != 0) */ - /* Done parsing the options. */ - - if (result != CMD_OK) - { - if (ret_putval->vl_num == 0) - sfree (vl.values); - cmd_destroy_putval (ret_putval); - } - - return (result); +cmd_status_t cmd_parse_putval(size_t argc, char **argv, + cmd_putval_t *ret_putval, + const cmd_options_t *opts, + cmd_error_handler_t *err) { + cmd_status_t result; + + char *identifier; + char *hostname; + char *plugin; + char *plugin_instance; + char *type; + char *type_instance; + int status; + + char *identifier_copy; + + const data_set_t *ds; + value_list_t vl = VALUE_LIST_INIT; + + if ((ret_putval == NULL) || (opts == NULL)) { + errno = EINVAL; + cmd_error(CMD_ERROR, err, "Invalid arguments to cmd_parse_putval."); + return (CMD_ERROR); + } + + if (argc < 2) { + cmd_error(CMD_PARSE_ERROR, err, "Missing identifier and/or value-list."); + return (CMD_PARSE_ERROR); + } + + identifier = argv[0]; + + /* parse_identifier() modifies its first argument, returning pointers into + * it; retain the old value for later. */ + identifier_copy = sstrdup(identifier); + + status = + parse_identifier(identifier, &hostname, &plugin, &plugin_instance, &type, + &type_instance, opts->identifier_default_host); + if (status != 0) { + DEBUG("cmd_handle_putval: Cannot parse identifier `%s'.", identifier_copy); + cmd_error(CMD_PARSE_ERROR, err, "Cannot parse identifier `%s'.", + identifier_copy); + sfree(identifier_copy); + return (CMD_PARSE_ERROR); + } + + if ((strlen(hostname) >= sizeof(vl.host)) || + (strlen(plugin) >= sizeof(vl.plugin)) || + ((plugin_instance != NULL) && + (strlen(plugin_instance) >= sizeof(vl.plugin_instance))) || + ((type_instance != NULL) && + (strlen(type_instance) >= sizeof(vl.type_instance)))) { + cmd_error(CMD_PARSE_ERROR, err, "Identifier too long."); + sfree(identifier_copy); + return (CMD_PARSE_ERROR); + } + + sstrncpy(vl.host, hostname, sizeof(vl.host)); + sstrncpy(vl.plugin, plugin, sizeof(vl.plugin)); + sstrncpy(vl.type, type, sizeof(vl.type)); + if (plugin_instance != NULL) + sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance)); + if (type_instance != NULL) + sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance)); + + ds = plugin_get_ds(type); + if (ds == NULL) { + cmd_error(CMD_PARSE_ERROR, err, "1 Type `%s' isn't defined.", type); + sfree(identifier_copy); + return (CMD_PARSE_ERROR); + } + + hostname = NULL; + plugin = NULL; + plugin_instance = NULL; + type = NULL; + type_instance = NULL; + + vl.values_len = ds->ds_num; + vl.values = malloc(vl.values_len * sizeof(*vl.values)); + if (vl.values == NULL) { + cmd_error(CMD_ERROR, err, "malloc failed."); + sfree(identifier_copy); + return (CMD_ERROR); + } + + ret_putval->raw_identifier = identifier_copy; + if (ret_putval->raw_identifier == NULL) { + cmd_error(CMD_ERROR, err, "malloc failed."); + cmd_destroy_putval(ret_putval); + sfree(vl.values); + return (CMD_ERROR); + } + + /* All the remaining fields are part of the option list. */ + result = CMD_OK; + for (size_t i = 1; i < argc; ++i) { + value_list_t *tmp; + + char *key = NULL; + char *value = NULL; + + status = cmd_parse_option(argv[i], &key, &value, err); + if (status == CMD_OK) { + assert(key != NULL); + assert(value != NULL); + set_option(&vl, key, value); + continue; + } else if (status != CMD_NO_OPTION) { + /* parse_option failed, buffer has been modified. + * => we need to abort */ + result = status; + break; + } + /* else: cmd_parse_option did not find an option; treat this as a + * value list. */ + + status = parse_values(argv[i], &vl, ds); + if (status != 0) { + cmd_error(CMD_PARSE_ERROR, err, "Parsing the values string failed."); + result = CMD_PARSE_ERROR; + break; + } + + tmp = (value_list_t *)realloc(ret_putval->vl, (ret_putval->vl_num + 1) * + sizeof(*ret_putval->vl)); + if (tmp == NULL) { + cmd_error(CMD_ERROR, err, "realloc failed."); + cmd_destroy_putval(ret_putval); + result = CMD_ERROR; + break; + } + + ret_putval->vl = tmp; + ret_putval->vl_num++; + memcpy(&ret_putval->vl[ret_putval->vl_num - 1], &vl, sizeof(vl)); + } /* while (*buffer != 0) */ + /* Done parsing the options. */ + + if (result != CMD_OK) { + if (ret_putval->vl_num == 0) + sfree(vl.values); + cmd_destroy_putval(ret_putval); + } + + return (result); } /* cmd_status_t cmd_parse_putval */ -void cmd_destroy_putval (cmd_putval_t *putval) -{ - if (putval == NULL) - return; - - sfree (putval->raw_identifier); - - for (size_t i = 0; i < putval->vl_num; ++i) - { - if (i == 0) /* values is shared between all entries */ - sfree (putval->vl[i].values); - meta_data_destroy (putval->vl[i].meta); - putval->vl[i].meta = NULL; - } - sfree (putval->vl); - putval->vl = NULL; - putval->vl_num = 0; +void cmd_destroy_putval(cmd_putval_t *putval) { + if (putval == NULL) + return; + + sfree(putval->raw_identifier); + + for (size_t i = 0; i < putval->vl_num; ++i) { + if (i == 0) /* values is shared between all entries */ + sfree(putval->vl[i].values); + meta_data_destroy(putval->vl[i].meta); + putval->vl[i].meta = NULL; + } + sfree(putval->vl); + putval->vl = NULL; + putval->vl_num = 0; } /* void cmd_destroy_putval */ -cmd_status_t cmd_handle_putval (FILE *fh, char *buffer) -{ - cmd_error_handler_t err = { cmd_error_fh, fh }; - cmd_t cmd; +cmd_status_t cmd_handle_putval(FILE *fh, char *buffer) { + cmd_error_handler_t err = {cmd_error_fh, fh}; + cmd_t cmd; - int status; + int status; - DEBUG ("utils_cmd_putval: cmd_handle_putval (fh = %p, buffer = %s);", - (void *) fh, buffer); + DEBUG("utils_cmd_putval: cmd_handle_putval (fh = %p, buffer = %s);", + (void *)fh, buffer); - if ((status = cmd_parse (buffer, &cmd, NULL, &err)) != CMD_OK) - return (status); - if (cmd.type != CMD_PUTVAL) - { - cmd_error (CMD_UNKNOWN_COMMAND, &err, "Unexpected command: `%s'.", - CMD_TO_STRING (cmd.type)); - cmd_destroy (&cmd); - return (CMD_UNKNOWN_COMMAND); - } + if ((status = cmd_parse(buffer, &cmd, NULL, &err)) != CMD_OK) + return (status); + if (cmd.type != CMD_PUTVAL) { + cmd_error(CMD_UNKNOWN_COMMAND, &err, "Unexpected command: `%s'.", + CMD_TO_STRING(cmd.type)); + cmd_destroy(&cmd); + return (CMD_UNKNOWN_COMMAND); + } - for (size_t i = 0; i < cmd.cmd.putval.vl_num; ++i) - plugin_dispatch_values (&cmd.cmd.putval.vl[i]); + for (size_t i = 0; i < cmd.cmd.putval.vl_num; ++i) + plugin_dispatch_values(&cmd.cmd.putval.vl[i]); - if (fh != stdout) - cmd_error (CMD_OK, &err, "Success: %i %s been dispatched.", - (int)cmd.cmd.putval.vl_num, - (cmd.cmd.putval.vl_num == 1) ? "value has" : "values have"); + if (fh != stdout) + cmd_error(CMD_OK, &err, "Success: %i %s been dispatched.", + (int)cmd.cmd.putval.vl_num, + (cmd.cmd.putval.vl_num == 1) ? "value has" : "values have"); - cmd_destroy (&cmd); - return (CMD_OK); + cmd_destroy(&cmd); + return (CMD_OK); } /* int cmd_handle_putval */ -int cmd_create_putval (char *ret, size_t ret_len, /* {{{ */ - const data_set_t *ds, const value_list_t *vl) -{ - char buffer_ident[6 * DATA_MAX_NAME_LEN]; - char buffer_values[1024]; - int status; - - status = FORMAT_VL (buffer_ident, sizeof (buffer_ident), vl); - if (status != 0) - return (status); - escape_string (buffer_ident, sizeof (buffer_ident)); - - status = format_values (buffer_values, sizeof (buffer_values), - ds, vl, /* store rates = */ 0); - if (status != 0) - return (status); - escape_string (buffer_values, sizeof (buffer_values)); - - ssnprintf (ret, ret_len, - "PUTVAL %s interval=%.3f %s", - buffer_ident, - (vl->interval > 0) - ? CDTIME_T_TO_DOUBLE (vl->interval) - : CDTIME_T_TO_DOUBLE (plugin_get_interval ()), - buffer_values); - - return (0); +int cmd_create_putval(char *ret, size_t ret_len, /* {{{ */ + const data_set_t *ds, const value_list_t *vl) { + char buffer_ident[6 * DATA_MAX_NAME_LEN]; + char buffer_values[1024]; + int status; + + status = FORMAT_VL(buffer_ident, sizeof(buffer_ident), vl); + if (status != 0) + return (status); + escape_string(buffer_ident, sizeof(buffer_ident)); + + status = format_values(buffer_values, sizeof(buffer_values), ds, vl, + /* store rates = */ 0); + if (status != 0) + return (status); + escape_string(buffer_values, sizeof(buffer_values)); + + ssnprintf(ret, ret_len, "PUTVAL %s interval=%.3f %s", buffer_ident, + (vl->interval > 0) ? CDTIME_T_TO_DOUBLE(vl->interval) + : CDTIME_T_TO_DOUBLE(plugin_get_interval()), + buffer_values); + + return (0); } /* }}} int cmd_create_putval */ diff --git a/src/utils_cmd_putval.h b/src/utils_cmd_putval.h index bb0b227f..75cd190c 100644 --- a/src/utils_cmd_putval.h +++ b/src/utils_cmd_putval.h @@ -32,15 +32,16 @@ #include "plugin.h" #include "utils_cmds.h" -cmd_status_t cmd_parse_putval (size_t argc, char **argv, - cmd_putval_t *ret_putval, const cmd_options_t *opts, - cmd_error_handler_t *err); +cmd_status_t cmd_parse_putval(size_t argc, char **argv, + cmd_putval_t *ret_putval, + const cmd_options_t *opts, + cmd_error_handler_t *err); -cmd_status_t cmd_handle_putval (FILE *fh, char *buffer); +cmd_status_t cmd_handle_putval(FILE *fh, char *buffer); -void cmd_destroy_putval (cmd_putval_t *putval); +void cmd_destroy_putval(cmd_putval_t *putval); -int cmd_create_putval (char *ret, size_t ret_len, - const data_set_t *ds, const value_list_t *vl); +int cmd_create_putval(char *ret, size_t ret_len, const data_set_t *ds, + const value_list_t *vl); #endif /* UTILS_CMD_PUTVAL_H */ diff --git a/src/utils_crc32.c b/src/utils_crc32.c index 79d77a23..afc566a9 100644 --- a/src/utils_crc32.c +++ b/src/utils_crc32.c @@ -37,74 +37,71 @@ * polynomial $edb88320 */ -#include #include +#include -uint32_t crc32_buffer(const unsigned char *, size_t); -static unsigned int crc32_tab[] = { - 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, - 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, - 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, - 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, - 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, - 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, - 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, - 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, - 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, - 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, - 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, - 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, - 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, - 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, - 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, - 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, - 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, - 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, - 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, - 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, - 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, - 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, - 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, - 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, - 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, - 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, - 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, - 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, - 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, - 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, - 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, - 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, - 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, - 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, - 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, - 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, - 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, - 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, - 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, - 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, - 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, - 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, - 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, - 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, - 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, - 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, - 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, - 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, - 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, - 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, - 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, - 0x2d02ef8dL -}; +uint32_t crc32_buffer(const unsigned char *, size_t); +static unsigned int crc32_tab[] = { + 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, + 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, + 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, + 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, + 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, + 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, + 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, + 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, + 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, + 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, + 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, + 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, + 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, + 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, + 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, + 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, + 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, + 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, + 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, + 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, + 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, + 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, + 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, + 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, + 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, + 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, + 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, + 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, + 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, + 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, + 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, + 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, + 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, + 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, + 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, + 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, + 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, + 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, + 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, + 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, + 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, + 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, + 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, + 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, + 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, + 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, + 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, + 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, + 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, + 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, + 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, + 0x2d02ef8dL}; /* Return a 32-bit CRC of the contents of the buffer. */ -uint32_t -crc32_buffer(const unsigned char *s, size_t len) -{ - uint32_t ret; +uint32_t crc32_buffer(const unsigned char *s, size_t len) { + uint32_t ret; - ret = 0; - for (size_t i = 0; i < len; i++) - ret = crc32_tab[(ret ^ s[i]) & 0xff] ^ (ret >> 8); - return ret; + ret = 0; + for (size_t i = 0; i < len; i++) + ret = crc32_tab[(ret ^ s[i]) & 0xff] ^ (ret >> 8); + return ret; } diff --git a/src/utils_crc32.h b/src/utils_crc32.h index cf60d24d..8e2c2126 100644 --- a/src/utils_crc32.h +++ b/src/utils_crc32.h @@ -27,6 +27,6 @@ #ifndef UTILS_CRC32_H #define UTILS_CRC32_H 1 -uint32_t crc32_buffer(const unsigned char *, size_t); +uint32_t crc32_buffer(const unsigned char *, size_t); #endif diff --git a/src/utils_curl_stats.c b/src/utils_curl_stats.c index 0509ff43..2a426646 100644 --- a/src/utils_curl_stats.c +++ b/src/utils_curl_stats.c @@ -32,217 +32,221 @@ #include #include -struct curl_stats_s -{ - bool total_time; - bool namelookup_time; - bool connect_time; - bool pretransfer_time; - bool size_upload; - bool size_download; - bool speed_download; - bool speed_upload; - bool header_size; - bool request_size; - bool content_length_download; - bool content_length_upload; - bool starttransfer_time; - bool redirect_time; - bool redirect_count; - bool num_connects; - bool appconnect_time; +struct curl_stats_s { + bool total_time; + bool namelookup_time; + bool connect_time; + bool pretransfer_time; + bool size_upload; + bool size_download; + bool speed_download; + bool speed_upload; + bool header_size; + bool request_size; + bool content_length_download; + bool content_length_upload; + bool starttransfer_time; + bool redirect_time; + bool redirect_count; + bool num_connects; + bool appconnect_time; }; /* * Private functions */ -static int dispatch_gauge (CURL *curl, CURLINFO info, value_list_t *vl) -{ - CURLcode code; - value_t v; +static int dispatch_gauge(CURL *curl, CURLINFO info, value_list_t *vl) { + CURLcode code; + value_t v; - code = curl_easy_getinfo (curl, info, &v.gauge); - if (code != CURLE_OK) - return -1; + code = curl_easy_getinfo(curl, info, &v.gauge); + if (code != CURLE_OK) + return -1; - vl->values = &v; - vl->values_len = 1; + vl->values = &v; + vl->values_len = 1; - return plugin_dispatch_values (vl); + return plugin_dispatch_values(vl); } /* dispatch_gauge */ /* dispatch a speed, in bytes/second */ -static int dispatch_speed (CURL *curl, CURLINFO info, value_list_t *vl) -{ - CURLcode code; - value_t v; +static int dispatch_speed(CURL *curl, CURLINFO info, value_list_t *vl) { + CURLcode code; + value_t v; - code = curl_easy_getinfo (curl, info, &v.gauge); - if (code != CURLE_OK) - return -1; + code = curl_easy_getinfo(curl, info, &v.gauge); + if (code != CURLE_OK) + return -1; - v.gauge *= 8; + v.gauge *= 8; - vl->values = &v; - vl->values_len = 1; + vl->values = &v; + vl->values_len = 1; - return plugin_dispatch_values (vl); + return plugin_dispatch_values(vl); } /* dispatch_speed */ /* dispatch a size/count, reported as a long value */ -static int dispatch_size (CURL *curl, CURLINFO info, value_list_t *vl) -{ - CURLcode code; - value_t v; - long raw; +static int dispatch_size(CURL *curl, CURLINFO info, value_list_t *vl) { + CURLcode code; + value_t v; + long raw; - code = curl_easy_getinfo (curl, info, &raw); - if (code != CURLE_OK) - return -1; + code = curl_easy_getinfo(curl, info, &raw); + if (code != CURLE_OK) + return -1; - v.gauge = (double)raw; + v.gauge = (double)raw; - vl->values = &v; - vl->values_len = 1; + vl->values = &v; + vl->values_len = 1; - return plugin_dispatch_values (vl); + return plugin_dispatch_values(vl); } /* dispatch_size */ static struct { - const char *name; - const char *config_key; - size_t offset; + const char *name; + const char *config_key; + size_t offset; - int (*dispatcher)(CURL *, CURLINFO, value_list_t *); - const char *type; - CURLINFO info; + int (*dispatcher)(CURL *, CURLINFO, value_list_t *); + const char *type; + CURLINFO info; } field_specs[] = { -#define SPEC(name, config_key, dispatcher, type, info) \ - { #name, config_key, offsetof (curl_stats_t, name), dispatcher, type, info } - - SPEC (total_time, "TotalTime", dispatch_gauge, "duration", CURLINFO_TOTAL_TIME), - SPEC (namelookup_time, "NamelookupTime", dispatch_gauge, "duration", CURLINFO_NAMELOOKUP_TIME), - SPEC (connect_time, "ConnectTime", dispatch_gauge, "duration", CURLINFO_CONNECT_TIME), - SPEC (pretransfer_time, "PretransferTime", dispatch_gauge, "duration", CURLINFO_PRETRANSFER_TIME), - SPEC (size_upload, "SizeUpload", dispatch_gauge, "bytes", CURLINFO_SIZE_UPLOAD), - SPEC (size_download, "SizeDownload", dispatch_gauge, "bytes", CURLINFO_SIZE_DOWNLOAD), - SPEC (speed_download, "SpeedDownload", dispatch_speed, "bitrate", CURLINFO_SPEED_DOWNLOAD), - SPEC (speed_upload, "SpeedUpload", dispatch_speed, "bitrate", CURLINFO_SPEED_UPLOAD), - SPEC (header_size, "HeaderSize", dispatch_size, "bytes", CURLINFO_HEADER_SIZE), - SPEC (request_size, "RequestSize", dispatch_size, "bytes", CURLINFO_REQUEST_SIZE), - SPEC (content_length_download, "ContentLengthDownload", dispatch_gauge, "bytes", CURLINFO_CONTENT_LENGTH_DOWNLOAD), - SPEC (content_length_upload, "ContentLengthUpload", dispatch_gauge, "bytes", CURLINFO_CONTENT_LENGTH_UPLOAD), - SPEC (starttransfer_time, "StarttransferTime", dispatch_gauge, "duration", CURLINFO_STARTTRANSFER_TIME), - SPEC (redirect_time, "RedirectTime", dispatch_gauge, "duration", CURLINFO_REDIRECT_TIME), - SPEC (redirect_count, "RedirectCount", dispatch_size, "count", CURLINFO_REDIRECT_COUNT), - SPEC (num_connects, "NumConnects", dispatch_size, "count", CURLINFO_NUM_CONNECTS), +#define SPEC(name, config_key, dispatcher, type, info) \ + { #name, config_key, offsetof(curl_stats_t, name), dispatcher, type, info } + + SPEC(total_time, "TotalTime", dispatch_gauge, "duration", + CURLINFO_TOTAL_TIME), + SPEC(namelookup_time, "NamelookupTime", dispatch_gauge, "duration", + CURLINFO_NAMELOOKUP_TIME), + SPEC(connect_time, "ConnectTime", dispatch_gauge, "duration", + CURLINFO_CONNECT_TIME), + SPEC(pretransfer_time, "PretransferTime", dispatch_gauge, "duration", + CURLINFO_PRETRANSFER_TIME), + SPEC(size_upload, "SizeUpload", dispatch_gauge, "bytes", + CURLINFO_SIZE_UPLOAD), + SPEC(size_download, "SizeDownload", dispatch_gauge, "bytes", + CURLINFO_SIZE_DOWNLOAD), + SPEC(speed_download, "SpeedDownload", dispatch_speed, "bitrate", + CURLINFO_SPEED_DOWNLOAD), + SPEC(speed_upload, "SpeedUpload", dispatch_speed, "bitrate", + CURLINFO_SPEED_UPLOAD), + SPEC(header_size, "HeaderSize", dispatch_size, "bytes", + CURLINFO_HEADER_SIZE), + SPEC(request_size, "RequestSize", dispatch_size, "bytes", + CURLINFO_REQUEST_SIZE), + SPEC(content_length_download, "ContentLengthDownload", dispatch_gauge, + "bytes", CURLINFO_CONTENT_LENGTH_DOWNLOAD), + SPEC(content_length_upload, "ContentLengthUpload", dispatch_gauge, "bytes", + CURLINFO_CONTENT_LENGTH_UPLOAD), + SPEC(starttransfer_time, "StarttransferTime", dispatch_gauge, "duration", + CURLINFO_STARTTRANSFER_TIME), + SPEC(redirect_time, "RedirectTime", dispatch_gauge, "duration", + CURLINFO_REDIRECT_TIME), + SPEC(redirect_count, "RedirectCount", dispatch_size, "count", + CURLINFO_REDIRECT_COUNT), + SPEC(num_connects, "NumConnects", dispatch_size, "count", + CURLINFO_NUM_CONNECTS), #ifdef HAVE_CURLINFO_APPCONNECT_TIME - SPEC (appconnect_time, "AppconnectTime", dispatch_gauge, "duration", CURLINFO_APPCONNECT_TIME), + SPEC(appconnect_time, "AppconnectTime", dispatch_gauge, "duration", + CURLINFO_APPCONNECT_TIME), #endif #undef SPEC }; -static void enable_field (curl_stats_t *s, size_t offset) -{ - *(bool *)((char *)s + offset) = true; +static void enable_field(curl_stats_t *s, size_t offset) { + *(bool *)((char *)s + offset) = true; } /* enable_field */ -static bool field_enabled (curl_stats_t *s, size_t offset) -{ - return *(bool *)((char *)s + offset); +static bool field_enabled(curl_stats_t *s, size_t offset) { + return *(bool *)((char *)s + offset); } /* field_enabled */ /* * Public API */ -curl_stats_t *curl_stats_from_config (oconfig_item_t *ci) -{ - curl_stats_t *s; - - if (ci == NULL) - return NULL; - - s = calloc (1, sizeof (*s)); - if (s == NULL) - return NULL; - - for (int i = 0; i < ci->children_num; ++i) - { - oconfig_item_t *c = ci->children + i; - size_t field; - - _Bool enabled = 0; - - for (field = 0; field < STATIC_ARRAY_SIZE (field_specs); ++field) { - if (! strcasecmp (c->key, field_specs[field].config_key)) - break; - if (! strcasecmp (c->key, field_specs[field].name)) - break; - } - if (field >= STATIC_ARRAY_SIZE (field_specs)) - { - ERROR ("curl stats: Unknown field name %s", c->key); - free (s); - return NULL; - } - - - if (cf_util_get_boolean (c, &enabled) != 0) { - free (s); - return NULL; - } - if (enabled) - enable_field (s, field_specs[field].offset); - } - - return s; +curl_stats_t *curl_stats_from_config(oconfig_item_t *ci) { + curl_stats_t *s; + + if (ci == NULL) + return NULL; + + s = calloc(1, sizeof(*s)); + if (s == NULL) + return NULL; + + for (int i = 0; i < ci->children_num; ++i) { + oconfig_item_t *c = ci->children + i; + size_t field; + + _Bool enabled = 0; + + for (field = 0; field < STATIC_ARRAY_SIZE(field_specs); ++field) { + if (!strcasecmp(c->key, field_specs[field].config_key)) + break; + if (!strcasecmp(c->key, field_specs[field].name)) + break; + } + if (field >= STATIC_ARRAY_SIZE(field_specs)) { + ERROR("curl stats: Unknown field name %s", c->key); + free(s); + return NULL; + } + + if (cf_util_get_boolean(c, &enabled) != 0) { + free(s); + return NULL; + } + if (enabled) + enable_field(s, field_specs[field].offset); + } + + return s; } /* curl_stats_from_config */ -void curl_stats_destroy (curl_stats_t *s) -{ - if (s != NULL) - free (s); +void curl_stats_destroy(curl_stats_t *s) { + if (s != NULL) + free(s); } /* curl_stats_destroy */ -int curl_stats_dispatch (curl_stats_t *s, CURL *curl, - const char *hostname, const char *plugin, const char *plugin_instance) -{ - value_list_t vl = VALUE_LIST_INIT; - - if (s == NULL) - return 0; - if ((curl == NULL) || (hostname == NULL) || (plugin == NULL)) - { - ERROR ("curl stats: dispatch() called with missing arguments " - "(curl=%p; hostname=%s; plugin=%s)", curl, - hostname == NULL ? "" : hostname, - plugin == NULL ? "" : plugin); - return -1; - } - - sstrncpy (vl.host, hostname, sizeof (vl.host)); - sstrncpy (vl.plugin, plugin, sizeof (vl.plugin)); - if (plugin_instance != NULL) - sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); - - for (size_t field = 0; field < STATIC_ARRAY_SIZE (field_specs); ++field) - { - int status; - - if (! field_enabled (s, field_specs[field].offset)) - continue; - - sstrncpy (vl.type, field_specs[field].type, sizeof (vl.type)); - sstrncpy (vl.type_instance, field_specs[field].name, sizeof (vl.type_instance)); - - vl.values = NULL; - vl.values_len = 0; - status = field_specs[field].dispatcher (curl, field_specs[field].info, &vl); - if (status < 0) - return status; - } - - return 0; +int curl_stats_dispatch(curl_stats_t *s, CURL *curl, const char *hostname, + const char *plugin, const char *plugin_instance) { + value_list_t vl = VALUE_LIST_INIT; + + if (s == NULL) + return 0; + if ((curl == NULL) || (hostname == NULL) || (plugin == NULL)) { + ERROR("curl stats: dispatch() called with missing arguments " + "(curl=%p; hostname=%s; plugin=%s)", + curl, hostname == NULL ? "" : hostname, + plugin == NULL ? "" : plugin); + return -1; + } + + sstrncpy(vl.host, hostname, sizeof(vl.host)); + sstrncpy(vl.plugin, plugin, sizeof(vl.plugin)); + if (plugin_instance != NULL) + sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance)); + + for (size_t field = 0; field < STATIC_ARRAY_SIZE(field_specs); ++field) { + int status; + + if (!field_enabled(s, field_specs[field].offset)) + continue; + + sstrncpy(vl.type, field_specs[field].type, sizeof(vl.type)); + sstrncpy(vl.type_instance, field_specs[field].name, + sizeof(vl.type_instance)); + + vl.values = NULL; + vl.values_len = 0; + status = field_specs[field].dispatcher(curl, field_specs[field].info, &vl); + if (status < 0) + return status; + } + + return 0; } /* curl_stats_dispatch */ diff --git a/src/utils_curl_stats.h b/src/utils_curl_stats.h index b6d0bb4d..3f83aab9 100644 --- a/src/utils_curl_stats.h +++ b/src/utils_curl_stats.h @@ -42,15 +42,15 @@ typedef struct curl_stats_s curl_stats_t; * * See http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html */ -curl_stats_t *curl_stats_from_config (oconfig_item_t *ci); +curl_stats_t *curl_stats_from_config(oconfig_item_t *ci); -void curl_stats_destroy (curl_stats_t *s); +void curl_stats_destroy(curl_stats_t *s); /* * curl_stats_dispatch dispatches performance values from the the specified * cURL session to the daemon. */ -int curl_stats_dispatch (curl_stats_t *s, CURL *curl, - const char *hostname, const char *plugin, const char *plugin_instance); +int curl_stats_dispatch(curl_stats_t *s, CURL *curl, const char *hostname, + const char *plugin, const char *plugin_instance); #endif /* UTILS_CURL_STATS_H */ diff --git a/src/utils_db_query.c b/src/utils_db_query.c index bbee90ae..9a582272 100644 --- a/src/utils_db_query.c +++ b/src/utils_db_query.c @@ -35,16 +35,15 @@ */ struct udb_result_s; /* {{{ */ typedef struct udb_result_s udb_result_t; -struct udb_result_s -{ - char *type; - char *instance_prefix; - char **instances; - size_t instances_num; - char **values; - size_t values_num; - char **metadata; - size_t metadata_num; +struct udb_result_s { + char *type; + char *instance_prefix; + char **instances; + size_t instances_num; + char **values; + size_t values_num; + char **metadata; + size_t metadata_num; udb_result_t *next; }; /* }}} */ @@ -64,14 +63,14 @@ struct udb_query_s /* {{{ */ struct udb_result_preparation_area_s /* {{{ */ { - const data_set_t *ds; + const data_set_t *ds; size_t *instances_pos; size_t *values_pos; size_t *metadata_pos; - char **instances_buffer; - char **values_buffer; - char **metadata_buffer; - char *plugin_instance; + char **instances_buffer; + char **values_buffer; + char **metadata_buffer; + char *plugin_instance; struct udb_result_preparation_area_s *next; }; /* }}} */ @@ -93,72 +92,63 @@ struct udb_query_preparation_area_s /* {{{ */ /* * Config Private functions */ -static int udb_config_set_string (char **ret_string, /* {{{ */ - oconfig_item_t *ci) -{ +static int udb_config_set_string(char **ret_string, /* {{{ */ + oconfig_item_t *ci) { char *string; - if ((ci->values_num != 1) - || (ci->values[0].type != OCONFIG_TYPE_STRING)) - { - WARNING ("db query utils: The `%s' config option " - "needs exactly one string argument.", ci->key); + if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) { + WARNING("db query utils: The `%s' config option " + "needs exactly one string argument.", + ci->key); return (-1); } - string = strdup (ci->values[0].value.string); - if (string == NULL) - { - ERROR ("db query utils: strdup failed."); + string = strdup(ci->values[0].value.string); + if (string == NULL) { + ERROR("db query utils: strdup failed."); return (-1); } if (*ret_string != NULL) - free (*ret_string); + free(*ret_string); *ret_string = string; return (0); } /* }}} int udb_config_set_string */ -static int udb_config_add_string (char ***ret_array, /* {{{ */ - size_t *ret_array_len, oconfig_item_t *ci) -{ +static int udb_config_add_string(char ***ret_array, /* {{{ */ + size_t *ret_array_len, oconfig_item_t *ci) { char **array; size_t array_len; - if (ci->values_num < 1) - { - WARNING ("db query utils: The `%s' config option " - "needs at least one argument.", ci->key); + if (ci->values_num < 1) { + WARNING("db query utils: The `%s' config option " + "needs at least one argument.", + ci->key); return (-1); } - for (int i = 0; i < ci->values_num; i++) - { - if (ci->values[i].type != OCONFIG_TYPE_STRING) - { - WARNING ("db query utils: Argument %i to the `%s' option " - "is not a string.", i + 1, ci->key); + for (int i = 0; i < ci->values_num; i++) { + if (ci->values[i].type != OCONFIG_TYPE_STRING) { + WARNING("db query utils: Argument %i to the `%s' option " + "is not a string.", + i + 1, ci->key); return (-1); } } array_len = *ret_array_len; - array = realloc (*ret_array, - sizeof (char *) * (array_len + ci->values_num)); - if (array == NULL) - { - ERROR ("db query utils: realloc failed."); + array = realloc(*ret_array, sizeof(char *) * (array_len + ci->values_num)); + if (array == NULL) { + ERROR("db query utils: realloc failed."); return (-1); } *ret_array = array; - for (int i = 0; i < ci->values_num; i++) - { - array[array_len] = strdup (ci->values[i].value.string); - if (array[array_len] == NULL) - { - ERROR ("db query utils: strdup failed."); + for (int i = 0; i < ci->values_num; i++) { + array[array_len] = strdup(ci->values[i].value.string); + if (array[array_len] == NULL) { + ERROR("db query utils: strdup failed."); *ret_array_len = array_len; return (-1); } @@ -169,59 +159,54 @@ static int udb_config_add_string (char ***ret_array, /* {{{ */ return (0); } /* }}} int udb_config_add_string */ -static int udb_config_set_uint (unsigned int *ret_value, /* {{{ */ - oconfig_item_t *ci) -{ +static int udb_config_set_uint(unsigned int *ret_value, /* {{{ */ + oconfig_item_t *ci) { double tmp; - if ((ci->values_num != 1) - || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) - { - WARNING ("db query utils: The `%s' config option " - "needs exactly one numeric argument.", ci->key); + if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_NUMBER)) { + WARNING("db query utils: The `%s' config option " + "needs exactly one numeric argument.", + ci->key); return (-1); } tmp = ci->values[0].value.number; - if ((tmp < 0.0) || (tmp > ((double) UINT_MAX))) + if ((tmp < 0.0) || (tmp > ((double)UINT_MAX))) return (-ERANGE); - *ret_value = (unsigned int) (tmp + .5); + *ret_value = (unsigned int)(tmp + .5); return (0); } /* }}} int udb_config_set_uint */ /* * Result private functions */ -static int udb_result_submit (udb_result_t *r, /* {{{ */ - udb_result_preparation_area_t *r_area, - udb_query_t const *q, udb_query_preparation_area_t *q_area) -{ +static int udb_result_submit(udb_result_t *r, /* {{{ */ + udb_result_preparation_area_t *r_area, + udb_query_t const *q, + udb_query_preparation_area_t *q_area) { value_list_t vl = VALUE_LIST_INIT; - assert (r != NULL); - assert (r_area->ds != NULL); - assert (((size_t) r_area->ds->ds_num) == r->values_num); - assert (r->values_num > 0); + assert(r != NULL); + assert(r_area->ds != NULL); + assert(((size_t)r_area->ds->ds_num) == r->values_num); + assert(r->values_num > 0); - vl.values = calloc (r->values_num, sizeof (*vl.values)); - if (vl.values == NULL) - { - ERROR ("db query utils: calloc failed."); + vl.values = calloc(r->values_num, sizeof(*vl.values)); + if (vl.values == NULL) { + ERROR("db query utils: calloc failed."); return (-1); } vl.values_len = r_area->ds->ds_num; - for (size_t i = 0; i < r->values_num; i++) - { + for (size_t i = 0; i < r->values_num; i++) { char *value_str = r_area->values_buffer[i]; - if (0 != parse_value (value_str, &vl.values[i], r_area->ds->ds[i].type)) - { - ERROR ("db query utils: udb_result_submit: Parsing `%s' as %s failed.", - value_str, DS_TYPE_TO_STRING (r_area->ds->ds[i].type)); + if (0 != parse_value(value_str, &vl.values[i], r_area->ds->ds[i].type)) { + ERROR("db query utils: udb_result_submit: Parsing `%s' as %s failed.", + value_str, DS_TYPE_TO_STRING(r_area->ds->ds[i].type)); errno = EINVAL; - free (vl.values); + free(vl.values); return (-1); } } @@ -229,79 +214,69 @@ static int udb_result_submit (udb_result_t *r, /* {{{ */ if (q_area->interval > 0) vl.interval = q_area->interval; - sstrncpy (vl.host, q_area->host, sizeof (vl.host)); - sstrncpy (vl.plugin, q_area->plugin, sizeof (vl.plugin)); - sstrncpy (vl.type, r->type, sizeof (vl.type)); + sstrncpy(vl.host, q_area->host, sizeof(vl.host)); + sstrncpy(vl.plugin, q_area->plugin, sizeof(vl.plugin)); + sstrncpy(vl.type, r->type, sizeof(vl.type)); /* Set vl.plugin_instance */ if (q->plugin_instance_from != NULL) { - sstrncpy (vl.plugin_instance, r_area->plugin_instance, sizeof (vl.plugin_instance)); - } - else { - sstrncpy (vl.plugin_instance, q_area->db_name, sizeof (vl.plugin_instance)); + sstrncpy(vl.plugin_instance, r_area->plugin_instance, + sizeof(vl.plugin_instance)); + } else { + sstrncpy(vl.plugin_instance, q_area->db_name, sizeof(vl.plugin_instance)); } /* Set vl.type_instance {{{ */ - if (r->instances_num == 0) - { + if (r->instances_num == 0) { if (r->instance_prefix == NULL) vl.type_instance[0] = 0; else - sstrncpy (vl.type_instance, r->instance_prefix, - sizeof (vl.type_instance)); - } - else /* if ((r->instances_num > 0) */ + sstrncpy(vl.type_instance, r->instance_prefix, sizeof(vl.type_instance)); + } else /* if ((r->instances_num > 0) */ { - if (r->instance_prefix == NULL) - { - int status = strjoin (vl.type_instance, sizeof (vl.type_instance), - r_area->instances_buffer, r->instances_num, "-"); - if (status < 0) - { - ERROR ("udb_result_submit: creating type_instance failed with status %d.", + if (r->instance_prefix == NULL) { + int status = strjoin(vl.type_instance, sizeof(vl.type_instance), + r_area->instances_buffer, r->instances_num, "-"); + if (status < 0) { + ERROR( + "udb_result_submit: creating type_instance failed with status %d.", status); return (status); } - } - else - { + } else { char tmp[DATA_MAX_NAME_LEN]; - int status = strjoin (tmp, sizeof (tmp), r_area->instances_buffer, - r->instances_num, "-"); - if (status < 0) - { - ERROR ("udb_result_submit: creating type_instance failed with status %d.", + int status = strjoin(tmp, sizeof(tmp), r_area->instances_buffer, + r->instances_num, "-"); + if (status < 0) { + ERROR( + "udb_result_submit: creating type_instance failed with status %d.", status); return (status); } - tmp[sizeof (tmp) - 1] = 0; + tmp[sizeof(tmp) - 1] = 0; - snprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s", - r->instance_prefix, tmp); + snprintf(vl.type_instance, sizeof(vl.type_instance), "%s-%s", + r->instance_prefix, tmp); } } - vl.type_instance[sizeof (vl.type_instance) - 1] = 0; + vl.type_instance[sizeof(vl.type_instance) - 1] = 0; /* }}} */ /* Annotate meta data. {{{ */ - if (r->metadata_num > 0) - { - vl.meta = meta_data_create (); - if (vl.meta == NULL) - { - ERROR ("db query utils:: meta_data_create failed."); + if (r->metadata_num > 0) { + vl.meta = meta_data_create(); + if (vl.meta == NULL) { + ERROR("db query utils:: meta_data_create failed."); return (-ENOMEM); } - for (size_t i = 0; i < r->metadata_num; i++) - { - int status = meta_data_add_string (vl.meta, r->metadata[i], - r_area->metadata_buffer[i]); - if (status != 0) - { - ERROR ("db query utils:: meta_data_add_string failed."); - meta_data_destroy (vl.meta); + for (size_t i = 0; i < r->metadata_num; i++) { + int status = meta_data_add_string(vl.meta, r->metadata[i], + r_area->metadata_buffer[i]); + if (status != 0) { + ERROR("db query utils:: meta_data_add_string failed."); + meta_data_destroy(vl.meta); vl.meta = NULL; return (status); } @@ -309,38 +284,36 @@ static int udb_result_submit (udb_result_t *r, /* {{{ */ } /* }}} */ - plugin_dispatch_values (&vl); + plugin_dispatch_values(&vl); - if (r->metadata_num > 0) - { - meta_data_destroy (vl.meta); + if (r->metadata_num > 0) { + meta_data_destroy(vl.meta); vl.meta = NULL; } - sfree (vl.values); + sfree(vl.values); return (0); } /* }}} void udb_result_submit */ -static void udb_result_finish_result (udb_result_t const *r, /* {{{ */ - udb_result_preparation_area_t *prep_area) -{ +static void udb_result_finish_result(udb_result_t const *r, /* {{{ */ + udb_result_preparation_area_t *prep_area) { if ((r == NULL) || (prep_area == NULL)) return; prep_area->ds = NULL; - sfree (prep_area->instances_pos); - sfree (prep_area->values_pos); - sfree (prep_area->metadata_pos); - sfree (prep_area->instances_buffer); - sfree (prep_area->values_buffer); - sfree (prep_area->metadata_buffer); + sfree(prep_area->instances_pos); + sfree(prep_area->values_pos); + sfree(prep_area->metadata_pos); + sfree(prep_area->instances_buffer); + sfree(prep_area->values_buffer); + sfree(prep_area->metadata_buffer); } /* }}} void udb_result_finish_result */ -static int udb_result_handle_result (udb_result_t *r, /* {{{ */ - udb_query_preparation_area_t *q_area, - udb_result_preparation_area_t *r_area, - udb_query_t const *q, char **column_values) -{ - assert (r && q_area && r_area); +static int udb_result_handle_result(udb_result_t *r, /* {{{ */ + udb_query_preparation_area_t *q_area, + udb_result_preparation_area_t *r_area, + udb_query_t const *q, + char **column_values) { + assert(r && q_area && r_area); for (size_t i = 0; i < r->instances_num; i++) r_area->instances_buffer[i] = column_values[r_area->instances_pos[i]]; @@ -354,175 +327,147 @@ static int udb_result_handle_result (udb_result_t *r, /* {{{ */ if (q->plugin_instance_from) r_area->plugin_instance = column_values[q_area->plugin_instance_pos]; - return udb_result_submit (r, r_area, q, q_area); + return udb_result_submit(r, r_area, q, q_area); } /* }}} int udb_result_handle_result */ -static int udb_result_prepare_result (udb_result_t const *r, /* {{{ */ - udb_result_preparation_area_t *prep_area, - char **column_names, size_t column_num) -{ +static int udb_result_prepare_result(udb_result_t const *r, /* {{{ */ + udb_result_preparation_area_t *prep_area, + char **column_names, size_t column_num) { if ((r == NULL) || (prep_area == NULL)) return (-EINVAL); -#define BAIL_OUT(status) \ - prep_area->ds = NULL; \ - sfree (prep_area->instances_pos); \ - sfree (prep_area->values_pos); \ - sfree (prep_area->metadata_pos); \ - sfree (prep_area->instances_buffer); \ - sfree (prep_area->values_buffer); \ - sfree (prep_area->metadata_buffer); \ +#define BAIL_OUT(status) \ + prep_area->ds = NULL; \ + sfree(prep_area->instances_pos); \ + sfree(prep_area->values_pos); \ + sfree(prep_area->metadata_pos); \ + sfree(prep_area->instances_buffer); \ + sfree(prep_area->values_buffer); \ + sfree(prep_area->metadata_buffer); \ return (status) /* Make sure previous preparations are cleaned up. */ - udb_result_finish_result (r, prep_area); + udb_result_finish_result(r, prep_area); prep_area->instances_pos = NULL; prep_area->values_pos = NULL; prep_area->metadata_pos = NULL; /* Read `ds' and check number of values {{{ */ - prep_area->ds = plugin_get_ds (r->type); - if (prep_area->ds == NULL) - { - ERROR ("db query utils: udb_result_prepare_result: Type `%s' is not " - "known by the daemon. See types.db(5) for details.", - r->type); - BAIL_OUT (-1); + prep_area->ds = plugin_get_ds(r->type); + if (prep_area->ds == NULL) { + ERROR("db query utils: udb_result_prepare_result: Type `%s' is not " + "known by the daemon. See types.db(5) for details.", + r->type); + BAIL_OUT(-1); } - if (prep_area->ds->ds_num != r->values_num) - { - ERROR ("db query utils: udb_result_prepare_result: The type `%s' " - "requires exactly %zu value%s, but the configuration specifies %zu.", - r->type, - prep_area->ds->ds_num, (prep_area->ds->ds_num == 1) ? "" : "s", - r->values_num); - BAIL_OUT (-1); + if (prep_area->ds->ds_num != r->values_num) { + ERROR("db query utils: udb_result_prepare_result: The type `%s' " + "requires exactly %zu value%s, but the configuration specifies %zu.", + r->type, prep_area->ds->ds_num, + (prep_area->ds->ds_num == 1) ? "" : "s", r->values_num); + BAIL_OUT(-1); } /* }}} */ /* Allocate r->instances_pos, r->values_pos, r->metadata_post, * r->instances_buffer, r->values_buffer, and r->metadata_buffer {{{ */ - if (r->instances_num > 0) - { - prep_area->instances_pos - = (size_t *) calloc (r->instances_num, sizeof (size_t)); - if (prep_area->instances_pos == NULL) - { - ERROR ("db query utils: udb_result_prepare_result: calloc failed."); - BAIL_OUT (-ENOMEM); + if (r->instances_num > 0) { + prep_area->instances_pos = + (size_t *)calloc(r->instances_num, sizeof(size_t)); + if (prep_area->instances_pos == NULL) { + ERROR("db query utils: udb_result_prepare_result: calloc failed."); + BAIL_OUT(-ENOMEM); } - prep_area->instances_buffer - = (char **) calloc (r->instances_num, sizeof (char *)); - if (prep_area->instances_buffer == NULL) - { - ERROR ("db query utils: udb_result_prepare_result: calloc failed."); - BAIL_OUT (-ENOMEM); + prep_area->instances_buffer = + (char **)calloc(r->instances_num, sizeof(char *)); + if (prep_area->instances_buffer == NULL) { + ERROR("db query utils: udb_result_prepare_result: calloc failed."); + BAIL_OUT(-ENOMEM); } } /* if (r->instances_num > 0) */ - prep_area->values_pos - = (size_t *) calloc (r->values_num, sizeof (size_t)); - if (prep_area->values_pos == NULL) - { - ERROR ("db query utils: udb_result_prepare_result: calloc failed."); - BAIL_OUT (-ENOMEM); + prep_area->values_pos = (size_t *)calloc(r->values_num, sizeof(size_t)); + if (prep_area->values_pos == NULL) { + ERROR("db query utils: udb_result_prepare_result: calloc failed."); + BAIL_OUT(-ENOMEM); } - prep_area->values_buffer - = (char **) calloc (r->values_num, sizeof (char *)); - if (prep_area->values_buffer == NULL) - { - ERROR ("db query utils: udb_result_prepare_result: calloc failed."); - BAIL_OUT (-ENOMEM); + prep_area->values_buffer = (char **)calloc(r->values_num, sizeof(char *)); + if (prep_area->values_buffer == NULL) { + ERROR("db query utils: udb_result_prepare_result: calloc failed."); + BAIL_OUT(-ENOMEM); } - prep_area->metadata_pos - = (size_t *) calloc (r->metadata_num, sizeof (size_t)); - if (prep_area->metadata_pos == NULL) - { - ERROR ("db query utils: udb_result_prepare_result: calloc failed."); - BAIL_OUT (-ENOMEM); + prep_area->metadata_pos = (size_t *)calloc(r->metadata_num, sizeof(size_t)); + if (prep_area->metadata_pos == NULL) { + ERROR("db query utils: udb_result_prepare_result: calloc failed."); + BAIL_OUT(-ENOMEM); } - prep_area->metadata_buffer - = (char **) calloc (r->metadata_num, sizeof (char *)); - if (prep_area->metadata_buffer == NULL) - { - ERROR ("db query utils: udb_result_prepare_result: calloc failed."); - BAIL_OUT (-ENOMEM); + prep_area->metadata_buffer = (char **)calloc(r->metadata_num, sizeof(char *)); + if (prep_area->metadata_buffer == NULL) { + ERROR("db query utils: udb_result_prepare_result: calloc failed."); + BAIL_OUT(-ENOMEM); } /* }}} */ /* Determine the position of the plugin instance column {{{ */ - for (size_t i = 0; i < r->instances_num; i++) - { + for (size_t i = 0; i < r->instances_num; i++) { size_t j; - for (j = 0; j < column_num; j++) - { - if (strcasecmp (r->instances[i], column_names[j]) == 0) - { + for (j = 0; j < column_num; j++) { + if (strcasecmp(r->instances[i], column_names[j]) == 0) { prep_area->instances_pos[i] = j; break; } } - if (j >= column_num) - { - ERROR ("db query utils: udb_result_prepare_result: " - "Column `%s' could not be found.", - r->instances[i]); - BAIL_OUT (-ENOENT); + if (j >= column_num) { + ERROR("db query utils: udb_result_prepare_result: " + "Column `%s' could not be found.", + r->instances[i]); + BAIL_OUT(-ENOENT); } } /* }}} for (i = 0; i < r->instances_num; i++) */ - /* Determine the position of the value columns {{{ */ - for (size_t i = 0; i < r->values_num; i++) - { + for (size_t i = 0; i < r->values_num; i++) { size_t j; - for (j = 0; j < column_num; j++) - { - if (strcasecmp (r->values[i], column_names[j]) == 0) - { + for (j = 0; j < column_num; j++) { + if (strcasecmp(r->values[i], column_names[j]) == 0) { prep_area->values_pos[i] = j; break; } } - if (j >= column_num) - { - ERROR ("db query utils: udb_result_prepare_result: " - "Column `%s' could not be found.", - r->values[i]); - BAIL_OUT (-ENOENT); + if (j >= column_num) { + ERROR("db query utils: udb_result_prepare_result: " + "Column `%s' could not be found.", + r->values[i]); + BAIL_OUT(-ENOENT); } } /* }}} for (i = 0; i < r->values_num; i++) */ /* Determine the position of the metadata columns {{{ */ - for (size_t i = 0; i < r->metadata_num; i++) - { + for (size_t i = 0; i < r->metadata_num; i++) { size_t j; - for (j = 0; j < column_num; j++) - { - if (strcasecmp (r->metadata[i], column_names[j]) == 0) - { + for (j = 0; j < column_num; j++) { + if (strcasecmp(r->metadata[i], column_names[j]) == 0) { prep_area->metadata_pos[i] = j; break; } } - if (j >= column_num) - { - ERROR ("db query utils: udb_result_prepare_result: " - "Metadata column `%s' could not be found.", - r->values[i]); - BAIL_OUT (-ENOENT); + if (j >= column_num) { + ERROR("db query utils: udb_result_prepare_result: " + "Metadata column `%s' could not be found.", + r->values[i]); + BAIL_OUT(-ENOENT); } } /* }}} for (i = 0; i < r->metadata_num; i++) */ @@ -530,48 +475,45 @@ static int udb_result_prepare_result (udb_result_t const *r, /* {{{ */ return (0); } /* }}} int udb_result_prepare_result */ -static void udb_result_free (udb_result_t *r) /* {{{ */ +static void udb_result_free(udb_result_t *r) /* {{{ */ { if (r == NULL) return; - sfree (r->type); - sfree (r->instance_prefix); + sfree(r->type); + sfree(r->instance_prefix); for (size_t i = 0; i < r->instances_num; i++) - sfree (r->instances[i]); - sfree (r->instances); + sfree(r->instances[i]); + sfree(r->instances); for (size_t i = 0; i < r->values_num; i++) - sfree (r->values[i]); - sfree (r->values); + sfree(r->values[i]); + sfree(r->values); for (size_t i = 0; i < r->metadata_num; i++) - sfree (r->metadata[i]); - sfree (r->metadata); + sfree(r->metadata[i]); + sfree(r->metadata); - udb_result_free (r->next); + udb_result_free(r->next); - sfree (r); + sfree(r); } /* }}} void udb_result_free */ -static int udb_result_create (const char *query_name, /* {{{ */ - udb_result_t **r_head, oconfig_item_t *ci) -{ +static int udb_result_create(const char *query_name, /* {{{ */ + udb_result_t **r_head, oconfig_item_t *ci) { udb_result_t *r; int status; - if (ci->values_num != 0) - { - WARNING ("db query utils: The `Result' block doesn't accept " - "any arguments. Ignoring %i argument%s.", - ci->values_num, (ci->values_num == 1) ? "" : "s"); + if (ci->values_num != 0) { + WARNING("db query utils: The `Result' block doesn't accept " + "any arguments. Ignoring %i argument%s.", + ci->values_num, (ci->values_num == 1) ? "" : "s"); } - r = calloc (1, sizeof (*r)); - if (r == NULL) - { - ERROR ("db query utils: calloc failed."); + r = calloc(1, sizeof(*r)); + if (r == NULL) { + ERROR("db query utils: calloc failed."); return (-1); } r->type = NULL; @@ -583,24 +525,22 @@ static int udb_result_create (const char *query_name, /* {{{ */ /* Fill the `udb_result_t' structure.. */ status = 0; - for (int i = 0; i < ci->children_num; i++) - { + for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; - if (strcasecmp ("Type", child->key) == 0) - status = udb_config_set_string (&r->type, child); - else if (strcasecmp ("InstancePrefix", child->key) == 0) - status = udb_config_set_string (&r->instance_prefix, child); - else if (strcasecmp ("InstancesFrom", child->key) == 0) - status = udb_config_add_string (&r->instances, &r->instances_num, child); - else if (strcasecmp ("ValuesFrom", child->key) == 0) - status = udb_config_add_string (&r->values, &r->values_num, child); - else if (strcasecmp ("MetadataFrom", child->key) == 0) - status = udb_config_add_string (&r->metadata, &r->metadata_num, child); - else - { - WARNING ("db query utils: Query `%s': Option `%s' not allowed here.", - query_name, child->key); + if (strcasecmp("Type", child->key) == 0) + status = udb_config_set_string(&r->type, child); + else if (strcasecmp("InstancePrefix", child->key) == 0) + status = udb_config_set_string(&r->instance_prefix, child); + else if (strcasecmp("InstancesFrom", child->key) == 0) + status = udb_config_add_string(&r->instances, &r->instances_num, child); + else if (strcasecmp("ValuesFrom", child->key) == 0) + status = udb_config_add_string(&r->values, &r->values_num, child); + else if (strcasecmp("MetadataFrom", child->key) == 0) + status = udb_config_add_string(&r->metadata, &r->metadata_num, child); + else { + WARNING("db query utils: Query `%s': Option `%s' not allowed here.", + query_name, child->key); status = -1; } @@ -609,37 +549,32 @@ static int udb_result_create (const char *query_name, /* {{{ */ } /* Check that all necessary options have been given. */ - while (status == 0) - { - if (r->type == NULL) - { - WARNING ("db query utils: `Type' not given for " - "result in query `%s'", query_name); + while (status == 0) { + if (r->type == NULL) { + WARNING("db query utils: `Type' not given for " + "result in query `%s'", + query_name); status = -1; } - if (r->values == NULL) - { - WARNING ("db query utils: `ValuesFrom' not given for " - "result in query `%s'", query_name); + if (r->values == NULL) { + WARNING("db query utils: `ValuesFrom' not given for " + "result in query `%s'", + query_name); status = -1; } break; } /* while (status == 0) */ - if (status != 0) - { - udb_result_free (r); + if (status != 0) { + udb_result_free(r); return (-1); } /* If all went well, add this result to the list of results. */ - if (*r_head == NULL) - { + if (*r_head == NULL) { *r_head = r; - } - else - { + } else { udb_result_t *last; last = *r_head; @@ -655,50 +590,46 @@ static int udb_result_create (const char *query_name, /* {{{ */ /* * Query private functions */ -static void udb_query_free_one (udb_query_t *q) /* {{{ */ +static void udb_query_free_one(udb_query_t *q) /* {{{ */ { if (q == NULL) return; - sfree (q->name); - sfree (q->statement); - sfree (q->plugin_instance_from); + sfree(q->name); + sfree(q->statement); + sfree(q->plugin_instance_from); - udb_result_free (q->results); + udb_result_free(q->results); - sfree (q); + sfree(q); } /* }}} void udb_query_free_one */ /* * Query public functions */ -int udb_query_create (udb_query_t ***ret_query_list, /* {{{ */ - size_t *ret_query_list_len, oconfig_item_t *ci, - udb_query_create_callback_t cb) -{ +int udb_query_create(udb_query_t ***ret_query_list, /* {{{ */ + size_t *ret_query_list_len, oconfig_item_t *ci, + udb_query_create_callback_t cb) { udb_query_t **query_list; - size_t query_list_len; + size_t query_list_len; udb_query_t *q; int status; if ((ret_query_list == NULL) || (ret_query_list_len == NULL)) return (-EINVAL); - query_list = *ret_query_list; + query_list = *ret_query_list; query_list_len = *ret_query_list_len; - if ((ci->values_num != 1) - || (ci->values[0].type != OCONFIG_TYPE_STRING)) - { - WARNING ("db query utils: The `Query' block " - "needs exactly one string argument."); + if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) { + WARNING("db query utils: The `Query' block " + "needs exactly one string argument."); return (-1); } - q = calloc (1, sizeof (*q)); - if (q == NULL) - { - ERROR ("db query utils: calloc failed."); + q = calloc(1, sizeof(*q)); + if (q == NULL) { + ERROR("db query utils: calloc failed."); return (-1); } q->min_version = 0; @@ -707,43 +638,38 @@ int udb_query_create (udb_query_t ***ret_query_list, /* {{{ */ q->results = NULL; q->plugin_instance_from = NULL; - status = udb_config_set_string (&q->name, ci); - if (status != 0) - { - sfree (q); + status = udb_config_set_string(&q->name, ci); + if (status != 0) { + sfree(q); return (status); } /* Fill the `udb_query_t' structure.. */ - for (int i = 0; i < ci->children_num; i++) - { + for (int i = 0; i < ci->children_num; i++) { oconfig_item_t *child = ci->children + i; - if (strcasecmp ("Statement", child->key) == 0) - status = udb_config_set_string (&q->statement, child); - else if (strcasecmp ("Result", child->key) == 0) - status = udb_result_create (q->name, &q->results, child); - else if (strcasecmp ("MinVersion", child->key) == 0) - status = udb_config_set_uint (&q->min_version, child); - else if (strcasecmp ("MaxVersion", child->key) == 0) - status = udb_config_set_uint (&q->max_version, child); - else if (strcasecmp ("PluginInstanceFrom", child->key) == 0) - status = udb_config_set_string (&q->plugin_instance_from, child); + if (strcasecmp("Statement", child->key) == 0) + status = udb_config_set_string(&q->statement, child); + else if (strcasecmp("Result", child->key) == 0) + status = udb_result_create(q->name, &q->results, child); + else if (strcasecmp("MinVersion", child->key) == 0) + status = udb_config_set_uint(&q->min_version, child); + else if (strcasecmp("MaxVersion", child->key) == 0) + status = udb_config_set_uint(&q->max_version, child); + else if (strcasecmp("PluginInstanceFrom", child->key) == 0) + status = udb_config_set_string(&q->plugin_instance_from, child); /* Call custom callbacks */ - else if (cb != NULL) - { - status = (*cb) (q, child); - if (status != 0) - { - WARNING ("db query utils: The configuration callback failed " - "to handle `%s'.", child->key); + else if (cb != NULL) { + status = (*cb)(q, child); + if (status != 0) { + WARNING("db query utils: The configuration callback failed " + "to handle `%s'.", + child->key); } - } - else - { - WARNING ("db query utils: Query `%s': Option `%s' not allowed here.", - q->name, child->key); + } else { + WARNING("db query utils: Query `%s': Option `%s' not allowed here.", + q->name, child->key); status = -1; } @@ -752,94 +678,82 @@ int udb_query_create (udb_query_t ***ret_query_list, /* {{{ */ } /* Check that all necessary options have been given. */ - if (status == 0) - { - if (q->statement == NULL) - { - WARNING ("db query utils: Query `%s': No `Statement' given.", q->name); + if (status == 0) { + if (q->statement == NULL) { + WARNING("db query utils: Query `%s': No `Statement' given.", q->name); status = -1; } - if (q->results == NULL) - { - WARNING ("db query utils: Query `%s': No (valid) `Result' block given.", - q->name); + if (q->results == NULL) { + WARNING("db query utils: Query `%s': No (valid) `Result' block given.", + q->name); status = -1; } } /* if (status == 0) */ /* If all went well, add this query to the list of queries within the * database structure. */ - if (status == 0) - { + if (status == 0) { udb_query_t **temp; - temp = realloc (query_list, - sizeof (*query_list) * (query_list_len + 1)); - if (temp == NULL) - { - ERROR ("db query utils: realloc failed"); + temp = realloc(query_list, sizeof(*query_list) * (query_list_len + 1)); + if (temp == NULL) { + ERROR("db query utils: realloc failed"); status = -1; - } - else - { + } else { query_list = temp; query_list[query_list_len] = q; query_list_len++; } } - if (status != 0) - { - udb_query_free_one (q); + if (status != 0) { + udb_query_free_one(q); return (-1); } - *ret_query_list = query_list; + *ret_query_list = query_list; *ret_query_list_len = query_list_len; return (0); } /* }}} int udb_query_create */ -void udb_query_free (udb_query_t **query_list, size_t query_list_len) /* {{{ */ +void udb_query_free(udb_query_t **query_list, size_t query_list_len) /* {{{ */ { if (query_list == NULL) return; for (size_t i = 0; i < query_list_len; i++) - udb_query_free_one (query_list[i]); + udb_query_free_one(query_list[i]); - sfree (query_list); + sfree(query_list); } /* }}} void udb_query_free */ -int udb_query_pick_from_list_by_name (const char *name, /* {{{ */ - udb_query_t **src_list, size_t src_list_len, - udb_query_t ***dst_list, size_t *dst_list_len) -{ +int udb_query_pick_from_list_by_name(const char *name, /* {{{ */ + udb_query_t **src_list, + size_t src_list_len, + udb_query_t ***dst_list, + size_t *dst_list_len) { int num_added; - if ((name == NULL) || (src_list == NULL) || (dst_list == NULL) - || (dst_list_len == NULL)) - { - ERROR ("db query utils: udb_query_pick_from_list_by_name: " - "Invalid argument."); + if ((name == NULL) || (src_list == NULL) || (dst_list == NULL) || + (dst_list_len == NULL)) { + ERROR("db query utils: udb_query_pick_from_list_by_name: " + "Invalid argument."); return (-EINVAL); } num_added = 0; - for (size_t i = 0; i < src_list_len; i++) - { + for (size_t i = 0; i < src_list_len; i++) { udb_query_t **tmp_list; size_t tmp_list_len; - if (strcasecmp (name, src_list[i]->name) != 0) + if (strcasecmp(name, src_list[i]->name) != 0) continue; tmp_list_len = *dst_list_len; - tmp_list = realloc (*dst_list, (tmp_list_len + 1) - * sizeof (udb_query_t *)); - if (tmp_list == NULL) - { - ERROR ("db query utils: realloc failed."); + tmp_list = realloc(*dst_list, (tmp_list_len + 1) * sizeof(udb_query_t *)); + if (tmp_list == NULL) { + ERROR("db query utils: realloc failed."); return (-ENOMEM); } @@ -852,51 +766,43 @@ int udb_query_pick_from_list_by_name (const char *name, /* {{{ */ num_added++; } /* for (i = 0; i < src_list_len; i++) */ - if (num_added <= 0) - { - ERROR ("db query utils: Cannot find query `%s'. Make sure the " - "block is above the database definition!", - name); + if (num_added <= 0) { + ERROR("db query utils: Cannot find query `%s'. Make sure the " + "block is above the database definition!", + name); return (-ENOENT); - } - else - { - DEBUG ("db query utils: Added %i versions of query `%s'.", - num_added, name); + } else { + DEBUG("db query utils: Added %i versions of query `%s'.", num_added, name); } return (0); } /* }}} int udb_query_pick_from_list_by_name */ -int udb_query_pick_from_list (oconfig_item_t *ci, /* {{{ */ - udb_query_t **src_list, size_t src_list_len, - udb_query_t ***dst_list, size_t *dst_list_len) -{ +int udb_query_pick_from_list(oconfig_item_t *ci, /* {{{ */ + udb_query_t **src_list, size_t src_list_len, + udb_query_t ***dst_list, size_t *dst_list_len) { const char *name; - if ((ci == NULL) || (src_list == NULL) || (dst_list == NULL) - || (dst_list_len == NULL)) - { - ERROR ("db query utils: udb_query_pick_from_list: " - "Invalid argument."); + if ((ci == NULL) || (src_list == NULL) || (dst_list == NULL) || + (dst_list_len == NULL)) { + ERROR("db query utils: udb_query_pick_from_list: " + "Invalid argument."); return (-EINVAL); } - if ((ci->values_num != 1) - || (ci->values[0].type != OCONFIG_TYPE_STRING)) - { - ERROR ("db query utils: The `%s' config option " - "needs exactly one string argument.", ci->key); + if ((ci->values_num != 1) || (ci->values[0].type != OCONFIG_TYPE_STRING)) { + ERROR("db query utils: The `%s' config option " + "needs exactly one string argument.", + ci->key); return (-1); } name = ci->values[0].value.string; - return (udb_query_pick_from_list_by_name (name, - src_list, src_list_len, - dst_list, dst_list_len)); + return (udb_query_pick_from_list_by_name(name, src_list, src_list_len, + dst_list, dst_list_len)); } /* }}} int udb_query_pick_from_list */ -const char *udb_query_get_name (udb_query_t *q) /* {{{ */ +const char *udb_query_get_name(udb_query_t *q) /* {{{ */ { if (q == NULL) return (NULL); @@ -904,7 +810,7 @@ const char *udb_query_get_name (udb_query_t *q) /* {{{ */ return (q->name); } /* }}} const char *udb_query_get_name */ -const char *udb_query_get_statement (udb_query_t *q) /* {{{ */ +const char *udb_query_get_statement(udb_query_t *q) /* {{{ */ { if (q == NULL) return (NULL); @@ -912,7 +818,7 @@ const char *udb_query_get_statement (udb_query_t *q) /* {{{ */ return (q->statement); } /* }}} const char *udb_query_get_statement */ -void udb_query_set_user_data (udb_query_t *q, void *user_data) /* {{{ */ +void udb_query_set_user_data(udb_query_t *q, void *user_data) /* {{{ */ { if (q == NULL) return; @@ -920,7 +826,7 @@ void udb_query_set_user_data (udb_query_t *q, void *user_data) /* {{{ */ q->user_data = user_data; } /* }}} void udb_query_set_user_data */ -void *udb_query_get_user_data (udb_query_t *q) /* {{{ */ +void *udb_query_get_user_data(udb_query_t *q) /* {{{ */ { if (q == NULL) return (NULL); @@ -928,7 +834,7 @@ void *udb_query_get_user_data (udb_query_t *q) /* {{{ */ return (q->user_data); } /* }}} void *udb_query_get_user_data */ -int udb_query_check_version (udb_query_t *q, unsigned int version) /* {{{ */ +int udb_query_check_version(udb_query_t *q, unsigned int version) /* {{{ */ { if (q == NULL) return (-EINVAL); @@ -939,9 +845,8 @@ int udb_query_check_version (udb_query_t *q, unsigned int version) /* {{{ */ return (1); } /* }}} int udb_query_check_version */ -void udb_query_finish_result (udb_query_t const *q, /* {{{ */ - udb_query_preparation_area_t *prep_area) -{ +void udb_query_finish_result(udb_query_t const *q, /* {{{ */ + udb_query_preparation_area_t *prep_area) { udb_result_preparation_area_t *r_area; udb_result_t *r; @@ -949,25 +854,24 @@ void udb_query_finish_result (udb_query_t const *q, /* {{{ */ return; prep_area->column_num = 0; - sfree (prep_area->host); - sfree (prep_area->plugin); - sfree (prep_area->db_name); + sfree(prep_area->host); + sfree(prep_area->plugin); + sfree(prep_area->db_name); prep_area->interval = 0; - for (r = q->results, r_area = prep_area->result_prep_areas; - r != NULL; r = r->next, r_area = r_area->next) - { + for (r = q->results, r_area = prep_area->result_prep_areas; r != NULL; + r = r->next, r_area = r_area->next) { /* this may happen during error conditions of the caller */ if (r_area == NULL) break; - udb_result_finish_result (r, r_area); + udb_result_finish_result(r, r_area); } } /* }}} void udb_query_finish_result */ -int udb_query_handle_result (udb_query_t const *q, /* {{{ */ - udb_query_preparation_area_t *prep_area, char **column_values) -{ +int udb_query_handle_result(udb_query_t const *q, /* {{{ */ + udb_query_preparation_area_t *prep_area, + char **column_values) { udb_result_preparation_area_t *r_area; udb_result_t *r; int success; @@ -976,51 +880,47 @@ int udb_query_handle_result (udb_query_t const *q, /* {{{ */ if ((q == NULL) || (prep_area == NULL)) return (-EINVAL); - if ((prep_area->column_num < 1) || (prep_area->host == NULL) - || (prep_area->plugin == NULL) || (prep_area->db_name == NULL)) - { - ERROR ("db query utils: Query `%s': Query is not prepared; " - "can't handle result.", q->name); + if ((prep_area->column_num < 1) || (prep_area->host == NULL) || + (prep_area->plugin == NULL) || (prep_area->db_name == NULL)) { + ERROR("db query utils: Query `%s': Query is not prepared; " + "can't handle result.", + q->name); return (-EINVAL); } #if defined(COLLECT_DEBUG) && COLLECT_DEBUG /* {{{ */ - do - { - for (size_t i = 0; i < prep_area->column_num; i++) - { - DEBUG ("db query utils: udb_query_handle_result (%s, %s): " - "column[%zu] = %s;", - prep_area->db_name, q->name, i, column_values[i]); + do { + for (size_t i = 0; i < prep_area->column_num; i++) { + DEBUG("db query utils: udb_query_handle_result (%s, %s): " + "column[%zu] = %s;", + prep_area->db_name, q->name, i, column_values[i]); } } while (0); #endif /* }}} */ success = 0; - for (r = q->results, r_area = prep_area->result_prep_areas; - r != NULL; r = r->next, r_area = r_area->next) - { - status = udb_result_handle_result (r, prep_area, r_area, - q, column_values); + for (r = q->results, r_area = prep_area->result_prep_areas; r != NULL; + r = r->next, r_area = r_area->next) { + status = udb_result_handle_result(r, prep_area, r_area, q, column_values); if (status == 0) success++; } - if (success == 0) - { - ERROR ("db query utils: udb_query_handle_result (%s, %s): " - "All results failed.", prep_area->db_name, q->name); + if (success == 0) { + ERROR("db query utils: udb_query_handle_result (%s, %s): " + "All results failed.", + prep_area->db_name, q->name); return (-1); } return (0); } /* }}} int udb_query_handle_result */ -int udb_query_prepare_result (udb_query_t const *q, /* {{{ */ - udb_query_preparation_area_t *prep_area, - const char *host, const char *plugin, const char *db_name, - char **column_names, size_t column_num, cdtime_t interval) -{ +int udb_query_prepare_result(udb_query_t const *q, /* {{{ */ + udb_query_preparation_area_t *prep_area, + const char *host, const char *plugin, + const char *db_name, char **column_names, + size_t column_num, cdtime_t interval) { udb_result_preparation_area_t *r_area; udb_result_t *r; int status; @@ -1028,75 +928,67 @@ int udb_query_prepare_result (udb_query_t const *q, /* {{{ */ if ((q == NULL) || (prep_area == NULL)) return (-EINVAL); - udb_query_finish_result (q, prep_area); + udb_query_finish_result(q, prep_area); prep_area->column_num = column_num; - prep_area->host = strdup (host); - prep_area->plugin = strdup (plugin); - prep_area->db_name = strdup (db_name); + prep_area->host = strdup(host); + prep_area->plugin = strdup(plugin); + prep_area->db_name = strdup(db_name); prep_area->interval = interval; - if ((prep_area->host == NULL) || (prep_area->plugin == NULL) - || (prep_area->db_name == NULL)) - { - ERROR ("db query utils: Query `%s': Prepare failed: Out of memory.", q->name); - udb_query_finish_result (q, prep_area); + if ((prep_area->host == NULL) || (prep_area->plugin == NULL) || + (prep_area->db_name == NULL)) { + ERROR("db query utils: Query `%s': Prepare failed: Out of memory.", + q->name); + udb_query_finish_result(q, prep_area); return (-ENOMEM); } #if defined(COLLECT_DEBUG) && COLLECT_DEBUG - do - { - for (size_t i = 0; i < column_num; i++) - { - DEBUG ("db query utils: udb_query_prepare_result: " - "query = %s; column[%zu] = %s;", - q->name, i, column_names[i]); + do { + for (size_t i = 0; i < column_num; i++) { + DEBUG("db query utils: udb_query_prepare_result: " + "query = %s; column[%zu] = %s;", + q->name, i, column_names[i]); } } while (0); #endif /* Determine the position of the PluginInstance column {{{ */ - if (q->plugin_instance_from != NULL) - { + if (q->plugin_instance_from != NULL) { size_t i; - for (i = 0; i < column_num; i++) - { - if (strcasecmp (q->plugin_instance_from, column_names[i]) == 0) - { + for (i = 0; i < column_num; i++) { + if (strcasecmp(q->plugin_instance_from, column_names[i]) == 0) { prep_area->plugin_instance_pos = i; break; } } - if (i >= column_num) - { - ERROR ("db query utils: udb_query_prepare_result: " - "Column `%s' from `PluginInstanceFrom' could not be found.", - q->plugin_instance_from); - udb_query_finish_result (q, prep_area); + if (i >= column_num) { + ERROR("db query utils: udb_query_prepare_result: " + "Column `%s' from `PluginInstanceFrom' could not be found.", + q->plugin_instance_from); + udb_query_finish_result(q, prep_area); return (-ENOENT); } } /* }}} */ - for (r = q->results, r_area = prep_area->result_prep_areas; - r != NULL; r = r->next, r_area = r_area->next) - { - if (! r_area) - { - ERROR ("db query utils: Query `%s': Invalid number of result " - "preparation areas.", q->name); - udb_query_finish_result (q, prep_area); + for (r = q->results, r_area = prep_area->result_prep_areas; r != NULL; + r = r->next, r_area = r_area->next) { + if (!r_area) { + ERROR("db query utils: Query `%s': Invalid number of result " + "preparation areas.", + q->name); + udb_query_finish_result(q, prep_area); return (-EINVAL); } - status = udb_result_prepare_result (r, r_area, column_names, column_num); - if (status != 0) - { - udb_query_finish_result (q, prep_area); + status = udb_result_prepare_result(r, r_area, column_names, column_num); + if (status != 0) { + udb_query_finish_result(q, prep_area); return (status); } } @@ -1105,46 +997,43 @@ int udb_query_prepare_result (udb_query_t const *q, /* {{{ */ } /* }}} int udb_query_prepare_result */ udb_query_preparation_area_t * -udb_query_allocate_preparation_area (udb_query_t *q) /* {{{ */ +udb_query_allocate_preparation_area(udb_query_t *q) /* {{{ */ { - udb_query_preparation_area_t *q_area; + udb_query_preparation_area_t *q_area; udb_result_preparation_area_t **next_r_area; udb_result_t *r; - q_area = calloc (1, sizeof (*q_area)); + q_area = calloc(1, sizeof(*q_area)); if (q_area == NULL) return NULL; next_r_area = &q_area->result_prep_areas; - for (r = q->results; r != NULL; r = r->next) - { + for (r = q->results; r != NULL; r = r->next) { udb_result_preparation_area_t *r_area; - r_area = calloc (1, sizeof (*r_area)); - if (r_area == NULL) - { + r_area = calloc(1, sizeof(*r_area)); + if (r_area == NULL) { udb_result_preparation_area_t *a = q_area->result_prep_areas; - while (a != NULL) - { + while (a != NULL) { udb_result_preparation_area_t *next = a->next; - sfree (a); + sfree(a); a = next; } - free (q_area); + free(q_area); return NULL; } *next_r_area = r_area; - next_r_area = &r_area->next; + next_r_area = &r_area->next; } return (q_area); } /* }}} udb_query_preparation_area_t *udb_query_allocate_preparation_area */ -void -udb_query_delete_preparation_area (udb_query_preparation_area_t *q_area) /* {{{ */ +void udb_query_delete_preparation_area( + udb_query_preparation_area_t *q_area) /* {{{ */ { udb_result_preparation_area_t *r_area; @@ -1152,24 +1041,23 @@ udb_query_delete_preparation_area (udb_query_preparation_area_t *q_area) /* {{{ return; r_area = q_area->result_prep_areas; - while (r_area != NULL) - { + while (r_area != NULL) { udb_result_preparation_area_t *area = r_area; r_area = r_area->next; - sfree (area->instances_pos); - sfree (area->values_pos); - sfree (area->instances_buffer); - sfree (area->values_buffer); - free (area); + sfree(area->instances_pos); + sfree(area->values_pos); + sfree(area->instances_buffer); + sfree(area->values_buffer); + free(area); } - sfree (q_area->host); - sfree (q_area->plugin); - sfree (q_area->db_name); + sfree(q_area->host); + sfree(q_area->plugin); + sfree(q_area->db_name); - free (q_area); + free(q_area); } /* }}} void udb_query_delete_preparation_area */ /* vim: set sw=2 sts=2 et fdm=marker : */ diff --git a/src/utils_db_query.h b/src/utils_db_query.h index fe06de9e..8f069185 100644 --- a/src/utils_db_query.h +++ b/src/utils_db_query.h @@ -36,29 +36,28 @@ typedef struct udb_query_s udb_query_t; struct udb_query_preparation_area_s; typedef struct udb_query_preparation_area_s udb_query_preparation_area_t; -typedef int (*udb_query_create_callback_t) (udb_query_t *q, - oconfig_item_t *ci); +typedef int (*udb_query_create_callback_t)(udb_query_t *q, oconfig_item_t *ci); /* * Public functions */ -int udb_query_create (udb_query_t ***ret_query_list, - size_t *ret_query_list_len, oconfig_item_t *ci, - udb_query_create_callback_t cb); -void udb_query_free (udb_query_t **query_list, size_t query_list_len); +int udb_query_create(udb_query_t ***ret_query_list, size_t *ret_query_list_len, + oconfig_item_t *ci, udb_query_create_callback_t cb); +void udb_query_free(udb_query_t **query_list, size_t query_list_len); -int udb_query_pick_from_list_by_name (const char *name, - udb_query_t **src_list, size_t src_list_len, - udb_query_t ***dst_list, size_t *dst_list_len); -int udb_query_pick_from_list (oconfig_item_t *ci, - udb_query_t **src_list, size_t src_list_len, - udb_query_t ***dst_list, size_t *dst_list_len); +int udb_query_pick_from_list_by_name(const char *name, udb_query_t **src_list, + size_t src_list_len, + udb_query_t ***dst_list, + size_t *dst_list_len); +int udb_query_pick_from_list(oconfig_item_t *ci, udb_query_t **src_list, + size_t src_list_len, udb_query_t ***dst_list, + size_t *dst_list_len); -const char *udb_query_get_name (udb_query_t *q); -const char *udb_query_get_statement (udb_query_t *q); +const char *udb_query_get_name(udb_query_t *q); +const char *udb_query_get_statement(udb_query_t *q); -void udb_query_set_user_data (udb_query_t *q, void *user_data); -void *udb_query_get_user_data (udb_query_t *q); +void udb_query_set_user_data(udb_query_t *q, void *user_data); +void *udb_query_get_user_data(udb_query_t *q); /* * udb_query_check_version @@ -66,21 +65,22 @@ void *udb_query_get_user_data (udb_query_t *q); * Returns 0 if the query is NOT suitable for `version' and >0 if the * query IS suitable. */ -int udb_query_check_version (udb_query_t *q, unsigned int version); +int udb_query_check_version(udb_query_t *q, unsigned int version); -int udb_query_prepare_result (udb_query_t const *q, - udb_query_preparation_area_t *prep_area, - const char *host, const char *plugin, const char *db_name, - char **column_names, size_t column_num, cdtime_t interval); -int udb_query_handle_result (udb_query_t const *q, - udb_query_preparation_area_t *prep_area, char **column_values); -void udb_query_finish_result (udb_query_t const *q, - udb_query_preparation_area_t *prep_area); +int udb_query_prepare_result(udb_query_t const *q, + udb_query_preparation_area_t *prep_area, + const char *host, const char *plugin, + const char *db_name, char **column_names, + size_t column_num, cdtime_t interval); +int udb_query_handle_result(udb_query_t const *q, + udb_query_preparation_area_t *prep_area, + char **column_values); +void udb_query_finish_result(udb_query_t const *q, + udb_query_preparation_area_t *prep_area); udb_query_preparation_area_t * -udb_query_allocate_preparation_area (udb_query_t *q); -void -udb_query_delete_preparation_area (udb_query_preparation_area_t *q_area); +udb_query_allocate_preparation_area(udb_query_t *q); +void udb_query_delete_preparation_area(udb_query_preparation_area_t *q_area); #endif /* UTILS_DB_QUERY_H */ /* vim: set sw=2 sts=2 et : */ diff --git a/src/utils_dns.c b/src/utils_dns.c index 3e80e869..a4a5784b 100644 --- a/src/utils_dns.c +++ b/src/utils_dns.c @@ -38,60 +38,60 @@ #include "collectd.h" -#include "plugin.h" #include "common.h" +#include "plugin.h" #if HAVE_NET_IF_ARP_H -# include +#include #endif #if HAVE_NET_IF_H -# include +#include #endif #if HAVE_NET_PPP_DEFS_H -# include +#include #endif #if HAVE_NET_IF_PPP_H -# include +#include #endif #if HAVE_NETINET_IN_SYSTM_H -# include +#include #endif #if HAVE_NETINET_IN_H -# include +#include #endif #if HAVE_NETINET_IP6_H -# include +#include #endif #if HAVE_NETINET_IF_ETHER_H -# include +#include #endif #if HAVE_NETINET_IP_H -# include +#include #endif #ifdef HAVE_NETINET_IP_VAR_H -# include +#include #endif #if HAVE_NETINET_UDP_H -# include +#include #endif #if HAVE_ARPA_INET_H -# include +#include #endif #if HAVE_ARPA_NAMESER_H -# include +#include #endif #if HAVE_ARPA_NAMESER_COMPAT_H -# include +#include #endif #if HAVE_NETDB_H -# include +#include #endif #if HAVE_PCAP_H -# include +#include #endif #define PCAP_SNAPLEN 1460 @@ -101,31 +101,31 @@ #define ETHER_HDR_LEN (ETHER_ADDR_LEN * 2 + ETHER_TYPE_LEN) #endif #ifndef ETHERTYPE_8021Q -# define ETHERTYPE_8021Q 0x8100 +#define ETHERTYPE_8021Q 0x8100 #endif #ifndef ETHERTYPE_IPV6 -# define ETHERTYPE_IPV6 0x86DD +#define ETHERTYPE_IPV6 0x86DD #endif #ifndef PPP_ADDRESS_VAL -# define PPP_ADDRESS_VAL 0xff /* The address byte value */ +#define PPP_ADDRESS_VAL 0xff /* The address byte value */ #endif #ifndef PPP_CONTROL_VAL -# define PPP_CONTROL_VAL 0x03 /* The control byte value */ +#define PPP_CONTROL_VAL 0x03 /* The control byte value */ #endif #if HAVE_STRUCT_UDPHDR_UH_DPORT && HAVE_STRUCT_UDPHDR_UH_SPORT -# define UDP_DEST uh_dport -# define UDP_SRC uh_sport +#define UDP_DEST uh_dport +#define UDP_SRC uh_sport #elif HAVE_STRUCT_UDPHDR_DEST && HAVE_STRUCT_UDPHDR_SOURCE -# define UDP_DEST dest -# define UDP_SRC source +#define UDP_DEST dest +#define UDP_SRC source #else -# error "`struct udphdr' is unusable." +#error "`struct udphdr' is unusable." #endif #if HAVE_NETINET_IP6_H && HAVE_STRUCT_IP6_EXT -# define HAVE_IPV6 1 +#define HAVE_IPV6 1 #endif #include "utils_dns.h" @@ -133,15 +133,14 @@ /* * Type definitions */ -struct ip_list_s -{ - struct in6_addr addr; - void *data; - struct ip_list_s *next; +struct ip_list_s { + struct in6_addr addr; + void *data; + struct ip_list_s *next; }; typedef struct ip_list_s ip_list_t; -typedef int (printer)(const char *, ...); +typedef int(printer)(const char *, ...); /* * flags/features for non-interactive mode @@ -165,750 +164,843 @@ static pcap_t *pcap_obj = NULL; static ip_list_t *IgnoreList = NULL; #if HAVE_PCAP_H -static void (*Callback) (const rfc1035_header_t *) = NULL; +static void (*Callback)(const rfc1035_header_t *) = NULL; static int query_count_intvl = 0; static int query_count_total = 0; -# ifdef __OpenBSD__ +#ifdef __OpenBSD__ static struct bpf_timeval last_ts; -# else +#else static struct timeval last_ts; -# endif /* __OpenBSD__ */ +#endif /* __OpenBSD__ */ #endif /* HAVE_PCAP_H */ -static int cmp_in6_addr (const struct in6_addr *a, - const struct in6_addr *b) -{ - int i; +static int cmp_in6_addr(const struct in6_addr *a, const struct in6_addr *b) { + int i; - assert (sizeof (struct in6_addr) == 16); + assert(sizeof(struct in6_addr) == 16); - for (i = 0; i < 16; i++) - if (a->s6_addr[i] != b->s6_addr[i]) - break; + for (i = 0; i < 16; i++) + if (a->s6_addr[i] != b->s6_addr[i]) + break; - if (i >= 16) - return (0); + if (i >= 16) + return (0); - return (a->s6_addr[i] > b->s6_addr[i] ? 1 : -1); + return (a->s6_addr[i] > b->s6_addr[i] ? 1 : -1); } /* int cmp_addrinfo */ -static inline int ignore_list_match (const struct in6_addr *addr) -{ - for (ip_list_t *ptr = IgnoreList; ptr != NULL; ptr = ptr->next) - if (cmp_in6_addr (addr, &ptr->addr) == 0) - return (1); - return (0); +static inline int ignore_list_match(const struct in6_addr *addr) { + for (ip_list_t *ptr = IgnoreList; ptr != NULL; ptr = ptr->next) + if (cmp_in6_addr(addr, &ptr->addr) == 0) + return (1); + return (0); } /* int ignore_list_match */ -static void ignore_list_add (const struct in6_addr *addr) -{ - ip_list_t *new; +static void ignore_list_add(const struct in6_addr *addr) { + ip_list_t *new; - if (ignore_list_match (addr) != 0) - return; + if (ignore_list_match(addr) != 0) + return; - new = malloc (sizeof (*new)); - if (new == NULL) - { - perror ("malloc"); - return; - } + new = malloc(sizeof(*new)); + if (new == NULL) { + perror("malloc"); + return; + } - memcpy (&new->addr, addr, sizeof (struct in6_addr)); - new->next = IgnoreList; + memcpy(&new->addr, addr, sizeof(struct in6_addr)); + new->next = IgnoreList; - IgnoreList = new; + IgnoreList = new; } /* void ignore_list_add */ -void ignore_list_add_name (const char *name) -{ - struct addrinfo *ai_list; - struct in6_addr addr; - int status; - - status = getaddrinfo (name, NULL, NULL, &ai_list); - if (status != 0) - return; - - for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) - { - if (ai_ptr->ai_family == AF_INET) - { - memset (&addr, '\0', sizeof (addr)); - addr.s6_addr[10] = 0xFF; - addr.s6_addr[11] = 0xFF; - memcpy (addr.s6_addr + 12, &((struct sockaddr_in *) ai_ptr->ai_addr)->sin_addr, 4); - - ignore_list_add (&addr); - } - else - { - ignore_list_add (&((struct sockaddr_in6 *) ai_ptr->ai_addr)->sin6_addr); - } - } /* for */ +void ignore_list_add_name(const char *name) { + struct addrinfo *ai_list; + struct in6_addr addr; + int status; + + status = getaddrinfo(name, NULL, NULL, &ai_list); + if (status != 0) + return; + + for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; + ai_ptr = ai_ptr->ai_next) { + if (ai_ptr->ai_family == AF_INET) { + memset(&addr, '\0', sizeof(addr)); + addr.s6_addr[10] = 0xFF; + addr.s6_addr[11] = 0xFF; + memcpy(addr.s6_addr + 12, + &((struct sockaddr_in *)ai_ptr->ai_addr)->sin_addr, 4); + + ignore_list_add(&addr); + } else { + ignore_list_add(&((struct sockaddr_in6 *)ai_ptr->ai_addr)->sin6_addr); + } + } /* for */ - freeaddrinfo (ai_list); + freeaddrinfo(ai_list); } #if HAVE_PCAP_H -static void in6_addr_from_buffer (struct in6_addr *ia, - const void *buf, size_t buf_len, - int family) -{ - memset (ia, 0, sizeof (struct in6_addr)); - if ((AF_INET == family) && (sizeof (uint32_t) == buf_len)) - { - ia->s6_addr[10] = 0xFF; - ia->s6_addr[11] = 0xFF; - memcpy (ia->s6_addr + 12, buf, buf_len); - } - else if ((AF_INET6 == family) && (sizeof (struct in6_addr) == buf_len)) - { - memcpy (ia, buf, buf_len); - } +static void in6_addr_from_buffer(struct in6_addr *ia, const void *buf, + size_t buf_len, int family) { + memset(ia, 0, sizeof(struct in6_addr)); + if ((AF_INET == family) && (sizeof(uint32_t) == buf_len)) { + ia->s6_addr[10] = 0xFF; + ia->s6_addr[11] = 0xFF; + memcpy(ia->s6_addr + 12, buf, buf_len); + } else if ((AF_INET6 == family) && (sizeof(struct in6_addr) == buf_len)) { + memcpy(ia, buf, buf_len); + } } /* void in6_addr_from_buffer */ -void dnstop_set_pcap_obj (pcap_t *po) -{ - pcap_obj = po; -} +void dnstop_set_pcap_obj(pcap_t *po) { pcap_obj = po; } -void dnstop_set_callback (void (*cb) (const rfc1035_header_t *)) -{ - Callback = cb; +void dnstop_set_callback(void (*cb)(const rfc1035_header_t *)) { + Callback = cb; } #define RFC1035_MAXLABELSZ 63 -static int -rfc1035NameUnpack(const char *buf, size_t sz, off_t * off, char *name, size_t ns) -{ - off_t no = 0; - unsigned char c; - size_t len; - static int loop_detect = 0; - if (loop_detect > 2) - return 4; /* compression loop */ - if (ns == 0) - return 4; /* probably compression loop */ - do { - if ((*off) >= ((off_t) sz)) - break; - c = *(buf + (*off)); - if (c > 191) { - /* blasted compression */ - int rc; - unsigned short s; - off_t ptr; - memcpy(&s, buf + (*off), sizeof(s)); - s = ntohs(s); - (*off) += sizeof(s); - /* Sanity check */ - if ((*off) >= ((off_t) sz)) - return 1; /* message too short */ - ptr = s & 0x3FFF; - /* Make sure the pointer is inside this message */ - if (ptr >= ((off_t) sz)) - return 2; /* bad compression ptr */ - if (ptr < DNS_MSG_HDR_SZ) - return 2; /* bad compression ptr */ - loop_detect++; - rc = rfc1035NameUnpack(buf, sz, &ptr, name + no, ns - no); - loop_detect--; - return rc; - } else if (c > RFC1035_MAXLABELSZ) { - /* - * "(The 10 and 01 combinations are reserved for future use.)" - */ - return 3; /* reserved label/compression flags */ - } else { - (*off)++; - len = (size_t) c; - if (len == 0) - break; - if (len > (ns - 1)) - len = ns - 1; - if ((*off) + len > sz) - return 4; /* message is too short */ - if (no + len + 1 > ns) - return 5; /* qname would overflow name buffer */ - memcpy(name + no, buf + (*off), len); - (*off) += len; - no += len; - *(name + (no++)) = '.'; - } - } while (c > 0); - if (no > 0) - *(name + no - 1) = '\0'; - /* make sure we didn't allow someone to overflow the name buffer */ - assert(no <= ((off_t) ns)); - return 0; +static int rfc1035NameUnpack(const char *buf, size_t sz, off_t *off, char *name, + size_t ns) { + off_t no = 0; + unsigned char c; + size_t len; + static int loop_detect = 0; + if (loop_detect > 2) + return 4; /* compression loop */ + if (ns == 0) + return 4; /* probably compression loop */ + do { + if ((*off) >= ((off_t)sz)) + break; + c = *(buf + (*off)); + if (c > 191) { + /* blasted compression */ + int rc; + unsigned short s; + off_t ptr; + memcpy(&s, buf + (*off), sizeof(s)); + s = ntohs(s); + (*off) += sizeof(s); + /* Sanity check */ + if ((*off) >= ((off_t)sz)) + return 1; /* message too short */ + ptr = s & 0x3FFF; + /* Make sure the pointer is inside this message */ + if (ptr >= ((off_t)sz)) + return 2; /* bad compression ptr */ + if (ptr < DNS_MSG_HDR_SZ) + return 2; /* bad compression ptr */ + loop_detect++; + rc = rfc1035NameUnpack(buf, sz, &ptr, name + no, ns - no); + loop_detect--; + return rc; + } else if (c > RFC1035_MAXLABELSZ) { + /* + * "(The 10 and 01 combinations are reserved for future use.)" + */ + return 3; /* reserved label/compression flags */ + } else { + (*off)++; + len = (size_t)c; + if (len == 0) + break; + if (len > (ns - 1)) + len = ns - 1; + if ((*off) + len > sz) + return 4; /* message is too short */ + if (no + len + 1 > ns) + return 5; /* qname would overflow name buffer */ + memcpy(name + no, buf + (*off), len); + (*off) += len; + no += len; + *(name + (no++)) = '.'; + } + } while (c > 0); + if (no > 0) + *(name + no - 1) = '\0'; + /* make sure we didn't allow someone to overflow the name buffer */ + assert(no <= ((off_t)ns)); + return 0; } -static int -handle_dns(const char *buf, int len) -{ - rfc1035_header_t qh; - uint16_t us; - off_t offset; - char *t; - int status; - - /* The DNS header is 12 bytes long */ - if (len < DNS_MSG_HDR_SZ) - return 0; - - memcpy(&us, buf + 0, 2); - qh.id = ntohs(us); - - memcpy(&us, buf + 2, 2); - us = ntohs(us); - qh.qr = (us >> 15) & 0x01; - qh.opcode = (us >> 11) & 0x0F; - qh.aa = (us >> 10) & 0x01; - qh.tc = (us >> 9) & 0x01; - qh.rd = (us >> 8) & 0x01; - qh.ra = (us >> 7) & 0x01; - qh.z = (us >> 6) & 0x01; - qh.ad = (us >> 5) & 0x01; - qh.cd = (us >> 4) & 0x01; - qh.rcode = us & 0x0F; - - memcpy(&us, buf + 4, 2); - qh.qdcount = ntohs(us); - - memcpy(&us, buf + 6, 2); - qh.ancount = ntohs(us); - - memcpy(&us, buf + 8, 2); - qh.nscount = ntohs(us); - - memcpy(&us, buf + 10, 2); - qh.arcount = ntohs(us); - - offset = DNS_MSG_HDR_SZ; - memset(qh.qname, '\0', MAX_QNAME_SZ); - status = rfc1035NameUnpack(buf, len, &offset, qh.qname, MAX_QNAME_SZ); - if (status != 0) - { - INFO ("utils_dns: handle_dns: rfc1035NameUnpack failed " - "with status %i.", status); - return 0; - } - if ('\0' == qh.qname[0]) - sstrncpy (qh.qname, ".", sizeof (qh.qname)); - while ((t = strchr(qh.qname, '\n'))) - *t = ' '; - while ((t = strchr(qh.qname, '\r'))) - *t = ' '; - for (t = qh.qname; *t; t++) - *t = tolower((int) *t); - - memcpy(&us, buf + offset, 2); - qh.qtype = ntohs(us); - memcpy(&us, buf + offset + 2, 2); - qh.qclass = ntohs(us); - - qh.length = (uint16_t) len; - - if (Callback != NULL) - Callback (&qh); - - return 1; +static int handle_dns(const char *buf, int len) { + rfc1035_header_t qh; + uint16_t us; + off_t offset; + char *t; + int status; + + /* The DNS header is 12 bytes long */ + if (len < DNS_MSG_HDR_SZ) + return 0; + + memcpy(&us, buf + 0, 2); + qh.id = ntohs(us); + + memcpy(&us, buf + 2, 2); + us = ntohs(us); + qh.qr = (us >> 15) & 0x01; + qh.opcode = (us >> 11) & 0x0F; + qh.aa = (us >> 10) & 0x01; + qh.tc = (us >> 9) & 0x01; + qh.rd = (us >> 8) & 0x01; + qh.ra = (us >> 7) & 0x01; + qh.z = (us >> 6) & 0x01; + qh.ad = (us >> 5) & 0x01; + qh.cd = (us >> 4) & 0x01; + qh.rcode = us & 0x0F; + + memcpy(&us, buf + 4, 2); + qh.qdcount = ntohs(us); + + memcpy(&us, buf + 6, 2); + qh.ancount = ntohs(us); + + memcpy(&us, buf + 8, 2); + qh.nscount = ntohs(us); + + memcpy(&us, buf + 10, 2); + qh.arcount = ntohs(us); + + offset = DNS_MSG_HDR_SZ; + memset(qh.qname, '\0', MAX_QNAME_SZ); + status = rfc1035NameUnpack(buf, len, &offset, qh.qname, MAX_QNAME_SZ); + if (status != 0) { + INFO("utils_dns: handle_dns: rfc1035NameUnpack failed " + "with status %i.", + status); + return 0; + } + if ('\0' == qh.qname[0]) + sstrncpy(qh.qname, ".", sizeof(qh.qname)); + while ((t = strchr(qh.qname, '\n'))) + *t = ' '; + while ((t = strchr(qh.qname, '\r'))) + *t = ' '; + for (t = qh.qname; *t; t++) + *t = tolower((int)*t); + + memcpy(&us, buf + offset, 2); + qh.qtype = ntohs(us); + memcpy(&us, buf + offset + 2, 2); + qh.qclass = ntohs(us); + + qh.length = (uint16_t)len; + + if (Callback != NULL) + Callback(&qh); + + return 1; } -static int -handle_udp(const struct udphdr *udp, int len) -{ - char buf[PCAP_SNAPLEN]; - if ((ntohs (udp->UDP_DEST) != 53) - && (ntohs (udp->UDP_SRC) != 53)) - return 0; - memcpy(buf, udp + 1, len - sizeof(*udp)); - if (0 == handle_dns(buf, len - sizeof(*udp))) - return 0; - return 1; +static int handle_udp(const struct udphdr *udp, int len) { + char buf[PCAP_SNAPLEN]; + if ((ntohs(udp->UDP_DEST) != 53) && (ntohs(udp->UDP_SRC) != 53)) + return 0; + memcpy(buf, udp + 1, len - sizeof(*udp)); + if (0 == handle_dns(buf, len - sizeof(*udp))) + return 0; + return 1; } #if HAVE_IPV6 -static int -handle_ipv6 (struct ip6_hdr *ipv6, int len) -{ - char buf[PCAP_SNAPLEN]; - unsigned int offset; - int nexthdr; - - struct in6_addr c_src_addr; - uint16_t payload_len; - - if (0 > len) - return (0); - - offset = sizeof (struct ip6_hdr); - nexthdr = ipv6->ip6_nxt; - c_src_addr = ipv6->ip6_src; - payload_len = ntohs (ipv6->ip6_plen); - - if (ignore_list_match (&c_src_addr)) - return (0); - - /* Parse extension headers. This only handles the standard headers, as - * defined in RFC 2460, correctly. Fragments are discarded. */ - while ((IPPROTO_ROUTING == nexthdr) /* routing header */ - || (IPPROTO_HOPOPTS == nexthdr) /* Hop-by-Hop options. */ - || (IPPROTO_FRAGMENT == nexthdr) /* fragmentation header. */ - || (IPPROTO_DSTOPTS == nexthdr) /* destination options. */ - || (IPPROTO_AH == nexthdr) /* destination options. */ - || (IPPROTO_ESP == nexthdr)) /* encapsulating security payload. */ - { - struct ip6_ext ext_hdr; - uint16_t ext_hdr_len; - - /* Catch broken packets */ - if ((offset + sizeof (struct ip6_ext)) > (unsigned int)len) - return (0); - - /* Cannot handle fragments. */ - if (IPPROTO_FRAGMENT == nexthdr) - return (0); - - memcpy (&ext_hdr, (char *) ipv6 + offset, sizeof (struct ip6_ext)); - nexthdr = ext_hdr.ip6e_nxt; - ext_hdr_len = (8 * (ntohs (ext_hdr.ip6e_len) + 1)); - - /* This header is longer than the packets payload.. WTF? */ - if (ext_hdr_len > payload_len) - return (0); - - offset += ext_hdr_len; - payload_len -= ext_hdr_len; - } /* while */ - - /* Catch broken and empty packets */ - if (((offset + payload_len) > (unsigned int)len) - || (payload_len == 0) - || (payload_len > PCAP_SNAPLEN)) - return (0); - - if (IPPROTO_UDP != nexthdr) - return (0); - - memcpy (buf, (char *) ipv6 + offset, payload_len); - if (handle_udp ((struct udphdr *) buf, payload_len) == 0) - return (0); - - return (1); /* Success */ +static int handle_ipv6(struct ip6_hdr *ipv6, int len) { + char buf[PCAP_SNAPLEN]; + unsigned int offset; + int nexthdr; + + struct in6_addr c_src_addr; + uint16_t payload_len; + + if (0 > len) + return (0); + + offset = sizeof(struct ip6_hdr); + nexthdr = ipv6->ip6_nxt; + c_src_addr = ipv6->ip6_src; + payload_len = ntohs(ipv6->ip6_plen); + + if (ignore_list_match(&c_src_addr)) + return (0); + + /* Parse extension headers. This only handles the standard headers, as + * defined in RFC 2460, correctly. Fragments are discarded. */ + while ((IPPROTO_ROUTING == nexthdr) /* routing header */ + || (IPPROTO_HOPOPTS == nexthdr) /* Hop-by-Hop options. */ + || (IPPROTO_FRAGMENT == nexthdr) /* fragmentation header. */ + || (IPPROTO_DSTOPTS == nexthdr) /* destination options. */ + || (IPPROTO_AH == nexthdr) /* destination options. */ + || (IPPROTO_ESP == nexthdr)) /* encapsulating security payload. */ + { + struct ip6_ext ext_hdr; + uint16_t ext_hdr_len; + + /* Catch broken packets */ + if ((offset + sizeof(struct ip6_ext)) > (unsigned int)len) + return (0); + + /* Cannot handle fragments. */ + if (IPPROTO_FRAGMENT == nexthdr) + return (0); + + memcpy(&ext_hdr, (char *)ipv6 + offset, sizeof(struct ip6_ext)); + nexthdr = ext_hdr.ip6e_nxt; + ext_hdr_len = (8 * (ntohs(ext_hdr.ip6e_len) + 1)); + + /* This header is longer than the packets payload.. WTF? */ + if (ext_hdr_len > payload_len) + return (0); + + offset += ext_hdr_len; + payload_len -= ext_hdr_len; + } /* while */ + + /* Catch broken and empty packets */ + if (((offset + payload_len) > (unsigned int)len) || (payload_len == 0) || + (payload_len > PCAP_SNAPLEN)) + return (0); + + if (IPPROTO_UDP != nexthdr) + return (0); + + memcpy(buf, (char *)ipv6 + offset, payload_len); + if (handle_udp((struct udphdr *)buf, payload_len) == 0) + return (0); + + return (1); /* Success */ } /* int handle_ipv6 */ /* #endif HAVE_IPV6 */ -#else /* if !HAVE_IPV6 */ -static int -handle_ipv6 (__attribute__((unused)) void *pkg, - __attribute__((unused)) int len) -{ - return (0); +#else /* if !HAVE_IPV6 */ +static int handle_ipv6(__attribute__((unused)) void *pkg, + __attribute__((unused)) int len) { + return (0); } #endif /* !HAVE_IPV6 */ -static int -handle_ip(const struct ip *ip, int len) -{ - char buf[PCAP_SNAPLEN]; - int offset = ip->ip_hl << 2; - struct in6_addr c_src_addr; - struct in6_addr c_dst_addr; - - if (ip->ip_v == 6) - return (handle_ipv6 ((void *) ip, len)); - - in6_addr_from_buffer (&c_src_addr, &ip->ip_src.s_addr, sizeof (ip->ip_src.s_addr), AF_INET); - in6_addr_from_buffer (&c_dst_addr, &ip->ip_dst.s_addr, sizeof (ip->ip_dst.s_addr), AF_INET); - if (ignore_list_match (&c_src_addr)) - return (0); - if (IPPROTO_UDP != ip->ip_p) - return 0; - memcpy(buf, ((char *)ip) + offset, len - offset); - if (0 == handle_udp((struct udphdr *) buf, len - offset)) - return 0; - return 1; +static int handle_ip(const struct ip *ip, int len) { + char buf[PCAP_SNAPLEN]; + int offset = ip->ip_hl << 2; + struct in6_addr c_src_addr; + struct in6_addr c_dst_addr; + + if (ip->ip_v == 6) + return (handle_ipv6((void *)ip, len)); + + in6_addr_from_buffer(&c_src_addr, &ip->ip_src.s_addr, + sizeof(ip->ip_src.s_addr), AF_INET); + in6_addr_from_buffer(&c_dst_addr, &ip->ip_dst.s_addr, + sizeof(ip->ip_dst.s_addr), AF_INET); + if (ignore_list_match(&c_src_addr)) + return (0); + if (IPPROTO_UDP != ip->ip_p) + return 0; + memcpy(buf, ((char *)ip) + offset, len - offset); + if (0 == handle_udp((struct udphdr *)buf, len - offset)) + return 0; + return 1; } #if HAVE_NET_IF_PPP_H -static int -handle_ppp(const u_char * pkt, int len) -{ - char buf[PCAP_SNAPLEN]; - unsigned short us; - unsigned short proto; - if (len < 2) - return 0; - if (*pkt == PPP_ADDRESS_VAL && *(pkt + 1) == PPP_CONTROL_VAL) { - pkt += 2; /* ACFC not used */ - len -= 2; - } - if (len < 2) - return 0; - if (*pkt % 2) { - proto = *pkt; /* PFC is used */ - pkt++; - len--; - } else { - memcpy(&us, pkt, sizeof(us)); - proto = ntohs(us); - pkt += 2; - len -= 2; - } - if (ETHERTYPE_IP != proto && PPP_IP != proto) - return 0; - memcpy(buf, pkt, len); - return handle_ip((struct ip *) buf, len); +static int handle_ppp(const u_char *pkt, int len) { + char buf[PCAP_SNAPLEN]; + unsigned short us; + unsigned short proto; + if (len < 2) + return 0; + if (*pkt == PPP_ADDRESS_VAL && *(pkt + 1) == PPP_CONTROL_VAL) { + pkt += 2; /* ACFC not used */ + len -= 2; + } + if (len < 2) + return 0; + if (*pkt % 2) { + proto = *pkt; /* PFC is used */ + pkt++; + len--; + } else { + memcpy(&us, pkt, sizeof(us)); + proto = ntohs(us); + pkt += 2; + len -= 2; + } + if (ETHERTYPE_IP != proto && PPP_IP != proto) + return 0; + memcpy(buf, pkt, len); + return handle_ip((struct ip *)buf, len); } #endif /* HAVE_NET_IF_PPP_H */ -static int -handle_null(const u_char * pkt, int len) -{ - unsigned int family; - memcpy(&family, pkt, sizeof(family)); - if (AF_INET != family) - return 0; - return handle_ip((struct ip *) (pkt + 4), len - 4); +static int handle_null(const u_char *pkt, int len) { + unsigned int family; + memcpy(&family, pkt, sizeof(family)); + if (AF_INET != family) + return 0; + return handle_ip((struct ip *)(pkt + 4), len - 4); } #ifdef DLT_LOOP -static int -handle_loop(const u_char * pkt, int len) -{ - unsigned int family; - memcpy(&family, pkt, sizeof(family)); - if (AF_INET != ntohl(family)) - return 0; - return handle_ip((struct ip *) (pkt + 4), len - 4); +static int handle_loop(const u_char *pkt, int len) { + unsigned int family; + memcpy(&family, pkt, sizeof(family)); + if (AF_INET != ntohl(family)) + return 0; + return handle_ip((struct ip *)(pkt + 4), len - 4); } #endif #ifdef DLT_RAW -static int -handle_raw(const u_char * pkt, int len) -{ - return handle_ip((struct ip *) pkt, len); +static int handle_raw(const u_char *pkt, int len) { + return handle_ip((struct ip *)pkt, len); } #endif -static int -handle_ether(const u_char * pkt, int len) -{ - char buf[PCAP_SNAPLEN]; - struct ether_header *e = (void *) pkt; - unsigned short etype = ntohs(e->ether_type); - if (len < ETHER_HDR_LEN) - return 0; - pkt += ETHER_HDR_LEN; - len -= ETHER_HDR_LEN; - if (ETHERTYPE_8021Q == etype) { - etype = ntohs(*(unsigned short *) (pkt + 2)); - pkt += 4; - len -= 4; - } - if ((ETHERTYPE_IP != etype) - && (ETHERTYPE_IPV6 != etype)) - return 0; - memcpy(buf, pkt, len); - if (ETHERTYPE_IPV6 == etype) - return (handle_ipv6 ((void *) buf, len)); - else - return handle_ip((struct ip *) buf, len); +static int handle_ether(const u_char *pkt, int len) { + char buf[PCAP_SNAPLEN]; + struct ether_header *e = (void *)pkt; + unsigned short etype = ntohs(e->ether_type); + if (len < ETHER_HDR_LEN) + return 0; + pkt += ETHER_HDR_LEN; + len -= ETHER_HDR_LEN; + if (ETHERTYPE_8021Q == etype) { + etype = ntohs(*(unsigned short *)(pkt + 2)); + pkt += 4; + len -= 4; + } + if ((ETHERTYPE_IP != etype) && (ETHERTYPE_IPV6 != etype)) + return 0; + memcpy(buf, pkt, len); + if (ETHERTYPE_IPV6 == etype) + return (handle_ipv6((void *)buf, len)); + else + return handle_ip((struct ip *)buf, len); } #ifdef DLT_LINUX_SLL -static int -handle_linux_sll (const u_char *pkt, int len) -{ - struct sll_header - { - uint16_t pkt_type; - uint16_t dev_type; - uint16_t addr_len; - uint8_t addr[8]; - uint16_t proto_type; - } *hdr; - uint16_t etype; - - if ((0 > len) || ((unsigned int)len < sizeof (struct sll_header))) - return (0); - - hdr = (struct sll_header *) pkt; - pkt = (u_char *) (hdr + 1); - len -= sizeof (struct sll_header); - - etype = ntohs (hdr->proto_type); - - if ((ETHERTYPE_IP != etype) - && (ETHERTYPE_IPV6 != etype)) - return 0; - - if (ETHERTYPE_IPV6 == etype) - return (handle_ipv6 ((void *) pkt, len)); - else - return handle_ip((struct ip *) pkt, len); +static int handle_linux_sll(const u_char *pkt, int len) { + struct sll_header { + uint16_t pkt_type; + uint16_t dev_type; + uint16_t addr_len; + uint8_t addr[8]; + uint16_t proto_type; + } * hdr; + uint16_t etype; + + if ((0 > len) || ((unsigned int)len < sizeof(struct sll_header))) + return (0); + + hdr = (struct sll_header *)pkt; + pkt = (u_char *)(hdr + 1); + len -= sizeof(struct sll_header); + + etype = ntohs(hdr->proto_type); + + if ((ETHERTYPE_IP != etype) && (ETHERTYPE_IPV6 != etype)) + return 0; + + if (ETHERTYPE_IPV6 == etype) + return (handle_ipv6((void *)pkt, len)); + else + return handle_ip((struct ip *)pkt, len); } #endif /* DLT_LINUX_SLL */ /* public function */ -void handle_pcap(u_char *udata, const struct pcap_pkthdr *hdr, const u_char *pkt) -{ - int status; +void handle_pcap(u_char *udata, const struct pcap_pkthdr *hdr, + const u_char *pkt) { + int status; - if (hdr->caplen < ETHER_HDR_LEN) - return; + if (hdr->caplen < ETHER_HDR_LEN) + return; - switch (pcap_datalink (pcap_obj)) - { - case DLT_EN10MB: - status = handle_ether (pkt, hdr->caplen); - break; + switch (pcap_datalink(pcap_obj)) { + case DLT_EN10MB: + status = handle_ether(pkt, hdr->caplen); + break; #if HAVE_NET_IF_PPP_H - case DLT_PPP: - status = handle_ppp (pkt, hdr->caplen); - break; + case DLT_PPP: + status = handle_ppp(pkt, hdr->caplen); + break; #endif #ifdef DLT_LOOP - case DLT_LOOP: - status = handle_loop (pkt, hdr->caplen); - break; + case DLT_LOOP: + status = handle_loop(pkt, hdr->caplen); + break; #endif #ifdef DLT_RAW - case DLT_RAW: - status = handle_raw (pkt, hdr->caplen); - break; + case DLT_RAW: + status = handle_raw(pkt, hdr->caplen); + break; #endif #ifdef DLT_LINUX_SLL - case DLT_LINUX_SLL: - status = handle_linux_sll (pkt, hdr->caplen); - break; + case DLT_LINUX_SLL: + status = handle_linux_sll(pkt, hdr->caplen); + break; #endif - case DLT_NULL: - status = handle_null (pkt, hdr->caplen); - break; - - default: - ERROR ("handle_pcap: unsupported data link type %d", - pcap_datalink(pcap_obj)); - status = 0; - break; - } /* switch (pcap_datalink(pcap_obj)) */ - - if (0 == status) - return; - - query_count_intvl++; - query_count_total++; - last_ts = hdr->ts; + case DLT_NULL: + status = handle_null(pkt, hdr->caplen); + break; + + default: + ERROR("handle_pcap: unsupported data link type %d", + pcap_datalink(pcap_obj)); + status = 0; + break; + } /* switch (pcap_datalink(pcap_obj)) */ + + if (0 == status) + return; + + query_count_intvl++; + query_count_total++; + last_ts = hdr->ts; } #endif /* HAVE_PCAP_H */ -const char *qtype_str(int t) -{ - static char buf[32]; - switch (t) { -#if (defined (__NAMESER)) && (__NAMESER >= 19991001) - case ns_t_a: return ("A"); - case ns_t_ns: return ("NS"); - case ns_t_md: return ("MD"); - case ns_t_mf: return ("MF"); - case ns_t_cname: return ("CNAME"); - case ns_t_soa: return ("SOA"); - case ns_t_mb: return ("MB"); - case ns_t_mg: return ("MG"); - case ns_t_mr: return ("MR"); - case ns_t_null: return ("NULL"); - case ns_t_wks: return ("WKS"); - case ns_t_ptr: return ("PTR"); - case ns_t_hinfo: return ("HINFO"); - case ns_t_minfo: return ("MINFO"); - case ns_t_mx: return ("MX"); - case ns_t_txt: return ("TXT"); - case ns_t_rp: return ("RP"); - case ns_t_afsdb: return ("AFSDB"); - case ns_t_x25: return ("X25"); - case ns_t_isdn: return ("ISDN"); - case ns_t_rt: return ("RT"); - case ns_t_nsap: return ("NSAP"); - case ns_t_nsap_ptr: return ("NSAP-PTR"); - case ns_t_sig: return ("SIG"); - case ns_t_key: return ("KEY"); - case ns_t_px: return ("PX"); - case ns_t_gpos: return ("GPOS"); - case ns_t_aaaa: return ("AAAA"); - case ns_t_loc: return ("LOC"); - case ns_t_nxt: return ("NXT"); - case ns_t_eid: return ("EID"); - case ns_t_nimloc: return ("NIMLOC"); - case ns_t_srv: return ("SRV"); - case ns_t_atma: return ("ATMA"); - case ns_t_naptr: return ("NAPTR"); - case ns_t_opt: return ("OPT"); -# if __NAMESER >= 19991006 - case ns_t_kx: return ("KX"); - case ns_t_cert: return ("CERT"); - case ns_t_a6: return ("A6"); - case ns_t_dname: return ("DNAME"); - case ns_t_sink: return ("SINK"); - case ns_t_tsig: return ("TSIG"); -# endif -# if __NAMESER >= 20090302 - case ns_t_apl: return ("APL"); - case ns_t_ds: return ("DS"); - case ns_t_sshfp: return ("SSHFP"); - case ns_t_ipseckey: return ("IPSECKEY"); - case ns_t_rrsig: return ("RRSIG"); - case ns_t_nsec: return ("NSEC"); - case ns_t_dnskey: return ("DNSKEY"); - case ns_t_dhcid: return ("DHCID"); - case ns_t_nsec3: return ("NSEC3"); - case ns_t_nsec3param: return ("NSEC3PARAM"); - case ns_t_hip: return ("HIP"); - case ns_t_spf: return ("SPF"); - case ns_t_ixfr: return ("IXFR"); -# endif - case ns_t_axfr: return ("AXFR"); - case ns_t_mailb: return ("MAILB"); - case ns_t_maila: return ("MAILA"); - case ns_t_any: return ("ANY"); -# if __NAMESER >= 19991006 - case ns_t_zxfr: return ("ZXFR"); -# endif -# if __NAMESER >= 20090302 - case ns_t_dlv: return ("DLV"); -# endif +const char *qtype_str(int t) { + static char buf[32]; + switch (t) { +#if (defined(__NAMESER)) && (__NAMESER >= 19991001) + case ns_t_a: + return ("A"); + case ns_t_ns: + return ("NS"); + case ns_t_md: + return ("MD"); + case ns_t_mf: + return ("MF"); + case ns_t_cname: + return ("CNAME"); + case ns_t_soa: + return ("SOA"); + case ns_t_mb: + return ("MB"); + case ns_t_mg: + return ("MG"); + case ns_t_mr: + return ("MR"); + case ns_t_null: + return ("NULL"); + case ns_t_wks: + return ("WKS"); + case ns_t_ptr: + return ("PTR"); + case ns_t_hinfo: + return ("HINFO"); + case ns_t_minfo: + return ("MINFO"); + case ns_t_mx: + return ("MX"); + case ns_t_txt: + return ("TXT"); + case ns_t_rp: + return ("RP"); + case ns_t_afsdb: + return ("AFSDB"); + case ns_t_x25: + return ("X25"); + case ns_t_isdn: + return ("ISDN"); + case ns_t_rt: + return ("RT"); + case ns_t_nsap: + return ("NSAP"); + case ns_t_nsap_ptr: + return ("NSAP-PTR"); + case ns_t_sig: + return ("SIG"); + case ns_t_key: + return ("KEY"); + case ns_t_px: + return ("PX"); + case ns_t_gpos: + return ("GPOS"); + case ns_t_aaaa: + return ("AAAA"); + case ns_t_loc: + return ("LOC"); + case ns_t_nxt: + return ("NXT"); + case ns_t_eid: + return ("EID"); + case ns_t_nimloc: + return ("NIMLOC"); + case ns_t_srv: + return ("SRV"); + case ns_t_atma: + return ("ATMA"); + case ns_t_naptr: + return ("NAPTR"); + case ns_t_opt: + return ("OPT"); +#if __NAMESER >= 19991006 + case ns_t_kx: + return ("KX"); + case ns_t_cert: + return ("CERT"); + case ns_t_a6: + return ("A6"); + case ns_t_dname: + return ("DNAME"); + case ns_t_sink: + return ("SINK"); + case ns_t_tsig: + return ("TSIG"); +#endif +#if __NAMESER >= 20090302 + case ns_t_apl: + return ("APL"); + case ns_t_ds: + return ("DS"); + case ns_t_sshfp: + return ("SSHFP"); + case ns_t_ipseckey: + return ("IPSECKEY"); + case ns_t_rrsig: + return ("RRSIG"); + case ns_t_nsec: + return ("NSEC"); + case ns_t_dnskey: + return ("DNSKEY"); + case ns_t_dhcid: + return ("DHCID"); + case ns_t_nsec3: + return ("NSEC3"); + case ns_t_nsec3param: + return ("NSEC3PARAM"); + case ns_t_hip: + return ("HIP"); + case ns_t_spf: + return ("SPF"); + case ns_t_ixfr: + return ("IXFR"); +#endif + case ns_t_axfr: + return ("AXFR"); + case ns_t_mailb: + return ("MAILB"); + case ns_t_maila: + return ("MAILA"); + case ns_t_any: + return ("ANY"); +#if __NAMESER >= 19991006 + case ns_t_zxfr: + return ("ZXFR"); +#endif +#if __NAMESER >= 20090302 + case ns_t_dlv: + return ("DLV"); +#endif /* #endif __NAMESER >= 19991001 */ -#elif (defined (__BIND)) && (__BIND >= 19950621) - case T_A: return ("A"); /* 1 ... */ - case T_NS: return ("NS"); - case T_MD: return ("MD"); - case T_MF: return ("MF"); - case T_CNAME: return ("CNAME"); - case T_SOA: return ("SOA"); - case T_MB: return ("MB"); - case T_MG: return ("MG"); - case T_MR: return ("MR"); - case T_NULL: return ("NULL"); - case T_WKS: return ("WKS"); - case T_PTR: return ("PTR"); - case T_HINFO: return ("HINFO"); - case T_MINFO: return ("MINFO"); - case T_MX: return ("MX"); - case T_TXT: return ("TXT"); - case T_RP: return ("RP"); - case T_AFSDB: return ("AFSDB"); - case T_X25: return ("X25"); - case T_ISDN: return ("ISDN"); - case T_RT: return ("RT"); - case T_NSAP: return ("NSAP"); - case T_NSAP_PTR: return ("NSAP_PTR"); - case T_SIG: return ("SIG"); - case T_KEY: return ("KEY"); - case T_PX: return ("PX"); - case T_GPOS: return ("GPOS"); - case T_AAAA: return ("AAAA"); - case T_LOC: return ("LOC"); - case T_NXT: return ("NXT"); - case T_EID: return ("EID"); - case T_NIMLOC: return ("NIMLOC"); - case T_SRV: return ("SRV"); - case T_ATMA: return ("ATMA"); - case T_NAPTR: return ("NAPTR"); /* ... 35 */ +#elif (defined(__BIND)) && (__BIND >= 19950621) + case T_A: + return ("A"); /* 1 ... */ + case T_NS: + return ("NS"); + case T_MD: + return ("MD"); + case T_MF: + return ("MF"); + case T_CNAME: + return ("CNAME"); + case T_SOA: + return ("SOA"); + case T_MB: + return ("MB"); + case T_MG: + return ("MG"); + case T_MR: + return ("MR"); + case T_NULL: + return ("NULL"); + case T_WKS: + return ("WKS"); + case T_PTR: + return ("PTR"); + case T_HINFO: + return ("HINFO"); + case T_MINFO: + return ("MINFO"); + case T_MX: + return ("MX"); + case T_TXT: + return ("TXT"); + case T_RP: + return ("RP"); + case T_AFSDB: + return ("AFSDB"); + case T_X25: + return ("X25"); + case T_ISDN: + return ("ISDN"); + case T_RT: + return ("RT"); + case T_NSAP: + return ("NSAP"); + case T_NSAP_PTR: + return ("NSAP_PTR"); + case T_SIG: + return ("SIG"); + case T_KEY: + return ("KEY"); + case T_PX: + return ("PX"); + case T_GPOS: + return ("GPOS"); + case T_AAAA: + return ("AAAA"); + case T_LOC: + return ("LOC"); + case T_NXT: + return ("NXT"); + case T_EID: + return ("EID"); + case T_NIMLOC: + return ("NIMLOC"); + case T_SRV: + return ("SRV"); + case T_ATMA: + return ("ATMA"); + case T_NAPTR: + return ("NAPTR"); /* ... 35 */ #if (__BIND >= 19960801) - case T_KX: return ("KX"); /* 36 ... */ - case T_CERT: return ("CERT"); - case T_A6: return ("A6"); - case T_DNAME: return ("DNAME"); - case T_SINK: return ("SINK"); - case T_OPT: return ("OPT"); - case T_APL: return ("APL"); - case T_DS: return ("DS"); - case T_SSHFP: return ("SSHFP"); - case T_RRSIG: return ("RRSIG"); - case T_NSEC: return ("NSEC"); - case T_DNSKEY: return ("DNSKEY"); /* ... 48 */ - case T_TKEY: return ("TKEY"); /* 249 */ + case T_KX: + return ("KX"); /* 36 ... */ + case T_CERT: + return ("CERT"); + case T_A6: + return ("A6"); + case T_DNAME: + return ("DNAME"); + case T_SINK: + return ("SINK"); + case T_OPT: + return ("OPT"); + case T_APL: + return ("APL"); + case T_DS: + return ("DS"); + case T_SSHFP: + return ("SSHFP"); + case T_RRSIG: + return ("RRSIG"); + case T_NSEC: + return ("NSEC"); + case T_DNSKEY: + return ("DNSKEY"); /* ... 48 */ + case T_TKEY: + return ("TKEY"); /* 249 */ #endif /* __BIND >= 19960801 */ - case T_TSIG: return ("TSIG"); /* 250 ... */ - case T_IXFR: return ("IXFR"); - case T_AXFR: return ("AXFR"); - case T_MAILB: return ("MAILB"); - case T_MAILA: return ("MAILA"); - case T_ANY: return ("ANY"); /* ... 255 */ + case T_TSIG: + return ("TSIG"); /* 250 ... */ + case T_IXFR: + return ("IXFR"); + case T_AXFR: + return ("AXFR"); + case T_MAILB: + return ("MAILB"); + case T_MAILA: + return ("MAILA"); + case T_ANY: + return ("ANY"); /* ... 255 */ #endif /* __BIND >= 19950621 */ - default: - ssnprintf (buf, sizeof (buf), "#%i", t); - return (buf); - } /* switch (t) */ + default: + ssnprintf(buf, sizeof(buf), "#%i", t); + return (buf); + } /* switch (t) */ } -const char *opcode_str (int o) -{ - static char buf[30]; - switch (o) { - case 0: - return "Query"; - case 1: - return "Iquery"; - case 2: - return "Status"; - case 4: - return "Notify"; - case 5: - return "Update"; - default: - ssnprintf(buf, sizeof (buf), "Opcode%d", o); - return buf; - } +const char *opcode_str(int o) { + static char buf[30]; + switch (o) { + case 0: + return "Query"; + case 1: + return "Iquery"; + case 2: + return "Status"; + case 4: + return "Notify"; + case 5: + return "Update"; + default: + ssnprintf(buf, sizeof(buf), "Opcode%d", o); + return buf; + } } -const char *rcode_str (int rcode) -{ - static char buf[32]; - switch (rcode) - { -#if (defined (__NAMESER)) && (__NAMESER >= 19991006) - case ns_r_noerror: return ("NOERROR"); - case ns_r_formerr: return ("FORMERR"); - case ns_r_servfail: return ("SERVFAIL"); - case ns_r_nxdomain: return ("NXDOMAIN"); - case ns_r_notimpl: return ("NOTIMPL"); - case ns_r_refused: return ("REFUSED"); - case ns_r_yxdomain: return ("YXDOMAIN"); - case ns_r_yxrrset: return ("YXRRSET"); - case ns_r_nxrrset: return ("NXRRSET"); - case ns_r_notauth: return ("NOTAUTH"); - case ns_r_notzone: return ("NOTZONE"); - case ns_r_max: return ("MAX"); - case ns_r_badsig: return ("BADSIG"); - case ns_r_badkey: return ("BADKEY"); - case ns_r_badtime: return ("BADTIME"); +const char *rcode_str(int rcode) { + static char buf[32]; + switch (rcode) { +#if (defined(__NAMESER)) && (__NAMESER >= 19991006) + case ns_r_noerror: + return ("NOERROR"); + case ns_r_formerr: + return ("FORMERR"); + case ns_r_servfail: + return ("SERVFAIL"); + case ns_r_nxdomain: + return ("NXDOMAIN"); + case ns_r_notimpl: + return ("NOTIMPL"); + case ns_r_refused: + return ("REFUSED"); + case ns_r_yxdomain: + return ("YXDOMAIN"); + case ns_r_yxrrset: + return ("YXRRSET"); + case ns_r_nxrrset: + return ("NXRRSET"); + case ns_r_notauth: + return ("NOTAUTH"); + case ns_r_notzone: + return ("NOTZONE"); + case ns_r_max: + return ("MAX"); + case ns_r_badsig: + return ("BADSIG"); + case ns_r_badkey: + return ("BADKEY"); + case ns_r_badtime: + return ("BADTIME"); /* #endif __NAMESER >= 19991006 */ -#elif (defined (__BIND)) && (__BIND >= 19950621) - case NOERROR: return ("NOERROR"); - case FORMERR: return ("FORMERR"); - case SERVFAIL: return ("SERVFAIL"); - case NXDOMAIN: return ("NXDOMAIN"); - case NOTIMP: return ("NOTIMP"); - case REFUSED: return ("REFUSED"); -#if defined (YXDOMAIN) && defined (NXRRSET) - case YXDOMAIN: return ("YXDOMAIN"); - case YXRRSET: return ("YXRRSET"); - case NXRRSET: return ("NXRRSET"); - case NOTAUTH: return ("NOTAUTH"); - case NOTZONE: return ("NOTZONE"); -#endif /* RFC2136 rcodes */ +#elif (defined(__BIND)) && (__BIND >= 19950621) + case NOERROR: + return ("NOERROR"); + case FORMERR: + return ("FORMERR"); + case SERVFAIL: + return ("SERVFAIL"); + case NXDOMAIN: + return ("NXDOMAIN"); + case NOTIMP: + return ("NOTIMP"); + case REFUSED: + return ("REFUSED"); +#if defined(YXDOMAIN) && defined(NXRRSET) + case YXDOMAIN: + return ("YXDOMAIN"); + case YXRRSET: + return ("YXRRSET"); + case NXRRSET: + return ("NXRRSET"); + case NOTAUTH: + return ("NOTAUTH"); + case NOTZONE: + return ("NOTZONE"); +#endif /* RFC2136 rcodes */ #endif /* __BIND >= 19950621 */ - default: - ssnprintf (buf, sizeof (buf), "RCode%i", rcode); - return (buf); - } + default: + ssnprintf(buf, sizeof(buf), "RCode%i", rcode); + return (buf); + } } /* const char *rcode_str (int rcode) */ #if 0 diff --git a/src/utils_dns.h b/src/utils_dns.h index 5c547c61..9d9b75fd 100644 --- a/src/utils_dns.h +++ b/src/utils_dns.h @@ -42,7 +42,7 @@ #include #if HAVE_PCAP_H -# include +#include #endif #define DNS_MSG_HDR_SZ 12 @@ -51,40 +51,41 @@ #define MAX_QNAME_SZ 512 struct rfc1035_header_s { - uint16_t id; - unsigned int qr:1; - unsigned int opcode:4; - unsigned int aa:1; - unsigned int tc:1; - unsigned int rd:1; - unsigned int ra:1; - unsigned int z:1; - unsigned int ad:1; - unsigned int cd:1; - unsigned int rcode:4; - uint16_t qdcount; - uint16_t ancount; - uint16_t nscount; - uint16_t arcount; - uint16_t qtype; - uint16_t qclass; - char qname[MAX_QNAME_SZ]; - uint16_t length; + uint16_t id; + unsigned int qr : 1; + unsigned int opcode : 4; + unsigned int aa : 1; + unsigned int tc : 1; + unsigned int rd : 1; + unsigned int ra : 1; + unsigned int z : 1; + unsigned int ad : 1; + unsigned int cd : 1; + unsigned int rcode : 4; + uint16_t qdcount; + uint16_t ancount; + uint16_t nscount; + uint16_t arcount; + uint16_t qtype; + uint16_t qclass; + char qname[MAX_QNAME_SZ]; + uint16_t length; }; typedef struct rfc1035_header_s rfc1035_header_t; #if HAVE_PCAP_H -void dnstop_set_pcap_obj (pcap_t *po); +void dnstop_set_pcap_obj(pcap_t *po); #endif -void dnstop_set_callback (void (*cb) (const rfc1035_header_t *)); +void dnstop_set_callback(void (*cb)(const rfc1035_header_t *)); -void ignore_list_add_name (const char *name); +void ignore_list_add_name(const char *name); #if HAVE_PCAP_H -void handle_pcap (u_char * udata, const struct pcap_pkthdr *hdr, const u_char * pkt); +void handle_pcap(u_char *udata, const struct pcap_pkthdr *hdr, + const u_char *pkt); #endif const char *qtype_str(int t); const char *opcode_str(int o); -const char *rcode_str (int r); +const char *rcode_str(int r); #endif /* !COLLECTD_UTILS_DNS_H */ diff --git a/src/utils_fbhash.c b/src/utils_fbhash.c index 893bfbd4..ecc56740 100644 --- a/src/utils_fbhash.c +++ b/src/utils_fbhash.c @@ -28,11 +28,10 @@ #include "plugin.h" -#include "utils_fbhash.h" #include "utils_avltree.h" +#include "utils_fbhash.h" -struct fbhash_s -{ +struct fbhash_s { char *filename; time_t mtime; @@ -43,38 +42,37 @@ struct fbhash_s /* * Private functions */ -static void fbh_free_tree (c_avl_tree_t *tree) /* {{{ */ +static void fbh_free_tree(c_avl_tree_t *tree) /* {{{ */ { int status; if (tree == NULL) return; - while (42) - { + while (42) { char *key = NULL; char *value = NULL; - status = c_avl_pick (tree, (void *) &key, (void *) &value); + status = c_avl_pick(tree, (void *)&key, (void *)&value); if (status != 0) break; - free (key); - free (value); + free(key); + free(value); } - c_avl_destroy (tree); + c_avl_destroy(tree); } /* }}} void fbh_free_tree */ -static int fbh_read_file (fbhash_t *h) /* {{{ */ +static int fbh_read_file(fbhash_t *h) /* {{{ */ { FILE *fh; char buffer[4096]; - struct flock fl = { 0 }; + struct flock fl = {0}; c_avl_tree_t *tree; int status; - fh = fopen (h->filename, "r"); + fh = fopen(h->filename, "r"); if (fh == NULL) return (-1); @@ -82,22 +80,20 @@ static int fbh_read_file (fbhash_t *h) /* {{{ */ fl.l_whence = SEEK_SET; /* TODO: Lock file? -> fcntl */ - status = fcntl (fileno (fh), F_SETLK, &fl); - if (status != 0) - { - fclose (fh); + status = fcntl(fileno(fh), F_SETLK, &fl); + if (status != 0) { + fclose(fh); return (-1); } - tree = c_avl_create ((int (*) (const void *, const void *)) strcmp); - if (tree == NULL) - { - fclose (fh); + tree = c_avl_create((int (*)(const void *, const void *))strcmp); + if (tree == NULL) { + fclose(fh); return (-1); } /* Read `fh' into `tree' */ - while (fgets (buffer, sizeof (buffer), fh) != NULL) /* {{{ */ + while (fgets(buffer, sizeof(buffer), fh) != NULL) /* {{{ */ { size_t len; char *key; @@ -106,20 +102,19 @@ static int fbh_read_file (fbhash_t *h) /* {{{ */ char *key_copy; char *value_copy; - buffer[sizeof (buffer) - 1] = 0; - len = strlen (buffer); + buffer[sizeof(buffer) - 1] = 0; + len = strlen(buffer); /* Remove trailing newline characters. */ - while ((len > 0) - && ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r'))) - { + while ((len > 0) && + ((buffer[len - 1] == '\n') || (buffer[len - 1] == '\r'))) { len--; buffer[len] = 0; } /* Seek first non-space character */ key = buffer; - while ((*key != 0) && isspace ((int) *key)) + while ((*key != 0) && isspace((int)*key)) key++; /* Skip empty lines and comments */ @@ -127,7 +122,7 @@ static int fbh_read_file (fbhash_t *h) /* {{{ */ continue; /* Seek first colon */ - value = strchr (key, ':'); + value = strchr(key, ':'); if (value == NULL) continue; @@ -136,56 +131,53 @@ static int fbh_read_file (fbhash_t *h) /* {{{ */ value++; /* Skip leading whitespace */ - while ((*value != 0) && isspace ((int) *value)) + while ((*value != 0) && isspace((int)*value)) value++; /* Skip lines without value */ if (value[0] == 0) continue; - key_copy = strdup (key); - value_copy = strdup (value); + key_copy = strdup(key); + value_copy = strdup(value); - if ((key_copy == NULL) || (value_copy == NULL)) - { - free (key_copy); - free (value_copy); + if ((key_copy == NULL) || (value_copy == NULL)) { + free(key_copy); + free(value_copy); continue; } - status = c_avl_insert (tree, key_copy, value_copy); - if (status != 0) - { - free (key_copy); - free (value_copy); + status = c_avl_insert(tree, key_copy, value_copy); + if (status != 0) { + free(key_copy); + free(value_copy); continue; } - DEBUG ("utils_fbhash: fbh_read_file: key = %s; value = %s;", - key, value); + DEBUG("utils_fbhash: fbh_read_file: key = %s; value = %s;", key, value); } /* }}} while (fgets) */ - fclose (fh); + fclose(fh); - fbh_free_tree (h->tree); + fbh_free_tree(h->tree); h->tree = tree; return (0); } /* }}} int fbh_read_file */ -static int fbh_check_file (fbhash_t *h) /* {{{ */ +static int fbh_check_file(fbhash_t *h) /* {{{ */ { - struct stat statbuf = { 0 }; + struct stat statbuf = {0}; int status; - status = stat (h->filename, &statbuf); + status = stat(h->filename, &statbuf); if (status != 0) return (-1); if (h->mtime >= statbuf.st_mtime) return (0); - status = fbh_read_file (h); + status = fbh_read_file(h); if (status == 0) h->mtime = statbuf.st_mtime; @@ -195,7 +187,7 @@ static int fbh_check_file (fbhash_t *h) /* {{{ */ /* * Public functions */ -fbhash_t *fbh_create (const char *file) /* {{{ */ +fbhash_t *fbh_create(const char *file) /* {{{ */ { fbhash_t *h; int status; @@ -203,42 +195,40 @@ fbhash_t *fbh_create (const char *file) /* {{{ */ if (file == NULL) return (NULL); - h = calloc (1, sizeof (*h)); + h = calloc(1, sizeof(*h)); if (h == NULL) return (NULL); - h->filename = strdup (file); - if (h->filename == NULL) - { - free (h); + h->filename = strdup(file); + if (h->filename == NULL) { + free(h); return (NULL); } h->mtime = 0; - pthread_mutex_init (&h->lock, /* attr = */ NULL); + pthread_mutex_init(&h->lock, /* attr = */ NULL); - status = fbh_check_file (h); - if (status != 0) - { - fbh_destroy (h); - free (h); + status = fbh_check_file(h); + if (status != 0) { + fbh_destroy(h); + free(h); return (NULL); } return (h); } /* }}} fbhash_t *fbh_create */ -void fbh_destroy (fbhash_t *h) /* {{{ */ +void fbh_destroy(fbhash_t *h) /* {{{ */ { if (h == NULL) return; - pthread_mutex_destroy (&h->lock); - free (h->filename); - fbh_free_tree (h->tree); + pthread_mutex_destroy(&h->lock); + free(h->filename); + fbh_free_tree(h->tree); } /* }}} void fbh_destroy */ -char *fbh_get (fbhash_t *h, const char *key) /* {{{ */ +char *fbh_get(fbhash_t *h, const char *key) /* {{{ */ { char *value; char *value_copy; @@ -250,19 +240,18 @@ char *fbh_get (fbhash_t *h, const char *key) /* {{{ */ value = NULL; value_copy = NULL; - pthread_mutex_lock (&h->lock); + pthread_mutex_lock(&h->lock); /* TODO: Checking this every time may be a bit much..? */ - fbh_check_file (h); + fbh_check_file(h); - status = c_avl_get (h->tree, key, (void *) &value); - if (status == 0) - { - assert (value != NULL); - value_copy = strdup (value); + status = c_avl_get(h->tree, key, (void *)&value); + if (status == 0) { + assert(value != NULL); + value_copy = strdup(value); } - pthread_mutex_unlock (&h->lock); + pthread_mutex_unlock(&h->lock); return (value_copy); } /* }}} char *fbh_get */ diff --git a/src/utils_fbhash.h b/src/utils_fbhash.h index d9206a02..79e9c00f 100644 --- a/src/utils_fbhash.h +++ b/src/utils_fbhash.h @@ -40,12 +40,12 @@ struct fbhash_s; typedef struct fbhash_s fbhash_t; -fbhash_t *fbh_create (const char *file); -void fbh_destroy (fbhash_t *h); +fbhash_t *fbh_create(const char *file); +void fbh_destroy(fbhash_t *h); /* Returns the value as a newly allocated `char *'. It's the caller's * responsibility to free this memory. */ -char *fbh_get (fbhash_t *h, const char *key); +char *fbh_get(fbhash_t *h, const char *key); #endif /* UTILS_FBHASH_H */ diff --git a/src/utils_format_graphite.c b/src/utils_format_graphite.c index 85f5917c..4f509f4a 100644 --- a/src/utils_format_graphite.c +++ b/src/utils_format_graphite.c @@ -23,246 +23,219 @@ #include "collectd.h" -#include "plugin.h" #include "common.h" +#include "plugin.h" -#include "utils_format_graphite.h" #include "utils_cache.h" +#include "utils_format_graphite.h" #define GRAPHITE_FORBIDDEN " \t\"\\:!/()\n\r" /* Utils functions to format data sets in graphite format. * Largely taken from write_graphite.c as it remains the same formatting */ -static int gr_format_values (char *ret, size_t ret_len, - int ds_num, const data_set_t *ds, const value_list_t *vl, - gauge_t const *rates) -{ - size_t offset = 0; - int status; - - assert (0 == strcmp (ds->type, vl->type)); - - memset (ret, 0, ret_len); - -#define BUFFER_ADD(...) do { \ - status = ssnprintf (ret + offset, ret_len - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - { \ - return (-1); \ - } \ - else if (((size_t) status) >= (ret_len - offset)) \ - { \ - return (-1); \ - } \ - else \ - offset += ((size_t) status); \ -} while (0) - - if (ds->ds[ds_num].type == DS_TYPE_GAUGE) - BUFFER_ADD (GAUGE_FORMAT, vl->values[ds_num].gauge); - else if (rates != NULL) - BUFFER_ADD ("%f", rates[ds_num]); - else if (ds->ds[ds_num].type == DS_TYPE_COUNTER) - BUFFER_ADD ("%llu", vl->values[ds_num].counter); - else if (ds->ds[ds_num].type == DS_TYPE_DERIVE) - BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive); - else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE) - BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute); - else - { - ERROR ("gr_format_values plugin: Unknown data source type: %i", - ds->ds[ds_num].type); - return (-1); - } +static int gr_format_values(char *ret, size_t ret_len, int ds_num, + const data_set_t *ds, const value_list_t *vl, + gauge_t const *rates) { + size_t offset = 0; + int status; + + assert(0 == strcmp(ds->type, vl->type)); + + memset(ret, 0, ret_len); + +#define BUFFER_ADD(...) \ + do { \ + status = ssnprintf(ret + offset, ret_len - offset, __VA_ARGS__); \ + if (status < 1) { \ + return (-1); \ + } else if (((size_t)status) >= (ret_len - offset)) { \ + return (-1); \ + } else \ + offset += ((size_t)status); \ + } while (0) + + if (ds->ds[ds_num].type == DS_TYPE_GAUGE) + BUFFER_ADD(GAUGE_FORMAT, vl->values[ds_num].gauge); + else if (rates != NULL) + BUFFER_ADD("%f", rates[ds_num]); + else if (ds->ds[ds_num].type == DS_TYPE_COUNTER) + BUFFER_ADD("%llu", vl->values[ds_num].counter); + else if (ds->ds[ds_num].type == DS_TYPE_DERIVE) + BUFFER_ADD("%" PRIi64, vl->values[ds_num].derive); + else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE) + BUFFER_ADD("%" PRIu64, vl->values[ds_num].absolute); + else { + ERROR("gr_format_values plugin: Unknown data source type: %i", + ds->ds[ds_num].type); + return (-1); + } #undef BUFFER_ADD - return (0); + return (0); } -static void gr_copy_escape_part (char *dst, const char *src, size_t dst_len, - char escape_char, _Bool preserve_separator) -{ - memset (dst, 0, dst_len); - - if (src == NULL) - return; - - for (size_t i = 0; i < dst_len; i++) - { - if (src[i] == 0) - { - dst[i] = 0; - break; - } - - if ((!preserve_separator && (src[i] == '.')) - || isspace ((int) src[i]) - || iscntrl ((int) src[i])) - dst[i] = escape_char; - else - dst[i] = src[i]; +static void gr_copy_escape_part(char *dst, const char *src, size_t dst_len, + char escape_char, _Bool preserve_separator) { + memset(dst, 0, dst_len); + + if (src == NULL) + return; + + for (size_t i = 0; i < dst_len; i++) { + if (src[i] == 0) { + dst[i] = 0; + break; } + + if ((!preserve_separator && (src[i] == '.')) || isspace((int)src[i]) || + iscntrl((int)src[i])) + dst[i] = escape_char; + else + dst[i] = src[i]; + } } -static int gr_format_name (char *ret, int ret_len, - value_list_t const *vl, - char const *ds_name, - char const *prefix, - char const *postfix, - char const escape_char, - unsigned int flags) -{ - char n_host[DATA_MAX_NAME_LEN]; - char n_plugin[DATA_MAX_NAME_LEN]; - char n_plugin_instance[DATA_MAX_NAME_LEN]; - char n_type[DATA_MAX_NAME_LEN]; - char n_type_instance[DATA_MAX_NAME_LEN]; - - char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1]; - char tmp_type[2 * DATA_MAX_NAME_LEN + 1]; - - if (prefix == NULL) - prefix = ""; - - if (postfix == NULL) - postfix = ""; - - _Bool preserve_separator = (flags & GRAPHITE_PRESERVE_SEPARATOR) ? 1 : 0; - - gr_copy_escape_part (n_host, vl->host, - sizeof (n_host), escape_char, preserve_separator); - gr_copy_escape_part (n_plugin, vl->plugin, - sizeof (n_plugin), escape_char, preserve_separator); - gr_copy_escape_part (n_plugin_instance, vl->plugin_instance, - sizeof (n_plugin_instance), escape_char, preserve_separator); - gr_copy_escape_part (n_type, vl->type, - sizeof (n_type), escape_char, preserve_separator); - gr_copy_escape_part (n_type_instance, vl->type_instance, - sizeof (n_type_instance), escape_char, preserve_separator); - - if (n_plugin_instance[0] != '\0') - ssnprintf (tmp_plugin, sizeof (tmp_plugin), "%s%c%s", - n_plugin, - (flags & GRAPHITE_SEPARATE_INSTANCES) ? '.' : '-', - n_plugin_instance); +static int gr_format_name(char *ret, int ret_len, value_list_t const *vl, + char const *ds_name, char const *prefix, + char const *postfix, char const escape_char, + unsigned int flags) { + char n_host[DATA_MAX_NAME_LEN]; + char n_plugin[DATA_MAX_NAME_LEN]; + char n_plugin_instance[DATA_MAX_NAME_LEN]; + char n_type[DATA_MAX_NAME_LEN]; + char n_type_instance[DATA_MAX_NAME_LEN]; + + char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1]; + char tmp_type[2 * DATA_MAX_NAME_LEN + 1]; + + if (prefix == NULL) + prefix = ""; + + if (postfix == NULL) + postfix = ""; + + _Bool preserve_separator = (flags & GRAPHITE_PRESERVE_SEPARATOR) ? 1 : 0; + + gr_copy_escape_part(n_host, vl->host, sizeof(n_host), escape_char, + preserve_separator); + gr_copy_escape_part(n_plugin, vl->plugin, sizeof(n_plugin), escape_char, + preserve_separator); + gr_copy_escape_part(n_plugin_instance, vl->plugin_instance, + sizeof(n_plugin_instance), escape_char, + preserve_separator); + gr_copy_escape_part(n_type, vl->type, sizeof(n_type), escape_char, + preserve_separator); + gr_copy_escape_part(n_type_instance, vl->type_instance, + sizeof(n_type_instance), escape_char, preserve_separator); + + if (n_plugin_instance[0] != '\0') + ssnprintf(tmp_plugin, sizeof(tmp_plugin), "%s%c%s", n_plugin, + (flags & GRAPHITE_SEPARATE_INSTANCES) ? '.' : '-', + n_plugin_instance); + else + sstrncpy(tmp_plugin, n_plugin, sizeof(tmp_plugin)); + + if (n_type_instance[0] != '\0') { + if ((flags & GRAPHITE_DROP_DUPE_FIELDS) && strcmp(n_plugin, n_type) == 0) + sstrncpy(tmp_type, n_type_instance, sizeof(tmp_type)); else - sstrncpy (tmp_plugin, n_plugin, sizeof (tmp_plugin)); - - if (n_type_instance[0] != '\0') - { - if ((flags & GRAPHITE_DROP_DUPE_FIELDS) && strcmp(n_plugin, n_type) == 0) - sstrncpy (tmp_type, n_type_instance, sizeof (tmp_type)); - else - ssnprintf (tmp_type, sizeof (tmp_type), "%s%c%s", - n_type, + ssnprintf(tmp_type, sizeof(tmp_type), "%s%c%s", n_type, (flags & GRAPHITE_SEPARATE_INSTANCES) ? '.' : '-', n_type_instance); - } - else - sstrncpy (tmp_type, n_type, sizeof (tmp_type)); - - /* Assert always_append_ds -> ds_name */ - assert (!(flags & GRAPHITE_ALWAYS_APPEND_DS) || (ds_name != NULL)); - if (ds_name != NULL) - { - if ((flags & GRAPHITE_DROP_DUPE_FIELDS) && strcmp(tmp_plugin, tmp_type) == 0) - ssnprintf (ret, ret_len, "%s%s%s.%s.%s", - prefix, n_host, postfix, tmp_plugin, ds_name); - else - ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s", - prefix, n_host, postfix, tmp_plugin, tmp_type, ds_name); - } + } else + sstrncpy(tmp_type, n_type, sizeof(tmp_type)); + + /* Assert always_append_ds -> ds_name */ + assert(!(flags & GRAPHITE_ALWAYS_APPEND_DS) || (ds_name != NULL)); + if (ds_name != NULL) { + if ((flags & GRAPHITE_DROP_DUPE_FIELDS) && + strcmp(tmp_plugin, tmp_type) == 0) + ssnprintf(ret, ret_len, "%s%s%s.%s.%s", prefix, n_host, postfix, + tmp_plugin, ds_name); else - ssnprintf (ret, ret_len, "%s%s%s.%s.%s", - prefix, n_host, postfix, tmp_plugin, tmp_type); + ssnprintf(ret, ret_len, "%s%s%s.%s.%s.%s", prefix, n_host, postfix, + tmp_plugin, tmp_type, ds_name); + } else + ssnprintf(ret, ret_len, "%s%s%s.%s.%s", prefix, n_host, postfix, tmp_plugin, + tmp_type); - return (0); + return (0); } -static void escape_graphite_string (char *buffer, char escape_char) -{ - assert (strchr(GRAPHITE_FORBIDDEN, escape_char) == NULL); +static void escape_graphite_string(char *buffer, char escape_char) { + assert(strchr(GRAPHITE_FORBIDDEN, escape_char) == NULL); - for (char *head = buffer + strcspn(buffer, GRAPHITE_FORBIDDEN); - *head != '\0'; - head += strcspn(head, GRAPHITE_FORBIDDEN)) - *head = escape_char; + for (char *head = buffer + strcspn(buffer, GRAPHITE_FORBIDDEN); *head != '\0'; + head += strcspn(head, GRAPHITE_FORBIDDEN)) + *head = escape_char; } -int format_graphite (char *buffer, size_t buffer_size, - data_set_t const *ds, value_list_t const *vl, - char const *prefix, char const *postfix, char const escape_char, - unsigned int flags) -{ - int status = 0; - int buffer_pos = 0; - - gauge_t *rates = NULL; - if (flags & GRAPHITE_STORE_RATES) - rates = uc_get_rate (ds, vl); - - for (size_t i = 0; i < ds->ds_num; i++) - { - char const *ds_name = NULL; - char key[10*DATA_MAX_NAME_LEN]; - char values[512]; - size_t message_len; - char message[1024]; - - if ((flags & GRAPHITE_ALWAYS_APPEND_DS) - || (ds->ds_num > 1)) - ds_name = ds->ds[i].name; - - /* Copy the identifier to `key' and escape it. */ - status = gr_format_name (key, sizeof (key), vl, ds_name, - prefix, postfix, escape_char, flags); - if (status != 0) - { - ERROR ("format_graphite: error with gr_format_name"); - sfree (rates); - return (status); - } - - escape_graphite_string (key, escape_char); - /* Convert the values to an ASCII representation and put that into - * `values'. */ - status = gr_format_values (values, sizeof (values), i, ds, vl, rates); - if (status != 0) - { - ERROR ("format_graphite: error with gr_format_values"); - sfree (rates); - return (status); - } - - /* Compute the graphite command */ - message_len = (size_t) ssnprintf (message, sizeof (message), - "%s %s %u\r\n", - key, - values, - (unsigned int) CDTIME_T_TO_TIME_T (vl->time)); - if (message_len >= sizeof (message)) { - ERROR ("format_graphite: message buffer too small: " - "Need %zu bytes.", message_len + 1); - sfree (rates); - return (-ENOMEM); - } - - /* Append it in case we got multiple data set */ - if ((buffer_pos + message_len) >= buffer_size) - { - ERROR ("format_graphite: target buffer too small"); - sfree (rates); - return (-ENOMEM); - } - memcpy((void *) (buffer + buffer_pos), message, message_len); - buffer_pos += message_len; - buffer[buffer_pos] = '\0'; +int format_graphite(char *buffer, size_t buffer_size, data_set_t const *ds, + value_list_t const *vl, char const *prefix, + char const *postfix, char const escape_char, + unsigned int flags) { + int status = 0; + int buffer_pos = 0; + + gauge_t *rates = NULL; + if (flags & GRAPHITE_STORE_RATES) + rates = uc_get_rate(ds, vl); + + for (size_t i = 0; i < ds->ds_num; i++) { + char const *ds_name = NULL; + char key[10 * DATA_MAX_NAME_LEN]; + char values[512]; + size_t message_len; + char message[1024]; + + if ((flags & GRAPHITE_ALWAYS_APPEND_DS) || (ds->ds_num > 1)) + ds_name = ds->ds[i].name; + + /* Copy the identifier to `key' and escape it. */ + status = gr_format_name(key, sizeof(key), vl, ds_name, prefix, postfix, + escape_char, flags); + if (status != 0) { + ERROR("format_graphite: error with gr_format_name"); + sfree(rates); + return (status); + } + + escape_graphite_string(key, escape_char); + /* Convert the values to an ASCII representation and put that into + * `values'. */ + status = gr_format_values(values, sizeof(values), i, ds, vl, rates); + if (status != 0) { + ERROR("format_graphite: error with gr_format_values"); + sfree(rates); + return (status); + } + + /* Compute the graphite command */ + message_len = + (size_t)ssnprintf(message, sizeof(message), "%s %s %u\r\n", key, values, + (unsigned int)CDTIME_T_TO_TIME_T(vl->time)); + if (message_len >= sizeof(message)) { + ERROR("format_graphite: message buffer too small: " + "Need %zu bytes.", + message_len + 1); + sfree(rates); + return (-ENOMEM); + } + + /* Append it in case we got multiple data set */ + if ((buffer_pos + message_len) >= buffer_size) { + ERROR("format_graphite: target buffer too small"); + sfree(rates); + return (-ENOMEM); } - sfree (rates); - return (status); + memcpy((void *)(buffer + buffer_pos), message, message_len); + buffer_pos += message_len; + buffer[buffer_pos] = '\0'; + } + sfree(rates); + return (status); } /* int format_graphite */ /* vim: set sw=2 sts=2 et fdm=marker : */ diff --git a/src/utils_format_graphite.h b/src/utils_format_graphite.h index ebc50802..de90c44c 100644 --- a/src/utils_format_graphite.h +++ b/src/utils_format_graphite.h @@ -26,16 +26,15 @@ #include "plugin.h" -#define GRAPHITE_STORE_RATES 0x01 +#define GRAPHITE_STORE_RATES 0x01 #define GRAPHITE_SEPARATE_INSTANCES 0x02 -#define GRAPHITE_ALWAYS_APPEND_DS 0x04 -#define GRAPHITE_DROP_DUPE_FIELDS 0x08 +#define GRAPHITE_ALWAYS_APPEND_DS 0x04 +#define GRAPHITE_DROP_DUPE_FIELDS 0x08 #define GRAPHITE_PRESERVE_SEPARATOR 0x10 -int format_graphite (char *buffer, - size_t buffer_size, const data_set_t *ds, - const value_list_t *vl, const char *prefix, - const char *postfix, const char escape_char, - unsigned int flags); +int format_graphite(char *buffer, size_t buffer_size, const data_set_t *ds, + const value_list_t *vl, const char *prefix, + const char *postfix, const char escape_char, + unsigned int flags); #endif /* UTILS_FORMAT_GRAPHITE_H */ diff --git a/src/utils_format_json.c b/src/utils_format_json.c index 5b5fcdf0..0a95a86d 100644 --- a/src/utils_format_json.c +++ b/src/utils_format_json.c @@ -28,24 +28,23 @@ #include "utils_format_json.h" -#include "plugin.h" #include "common.h" +#include "plugin.h" #include "utils_cache.h" #if HAVE_LIBYAJL -# include -# include -# if HAVE_YAJL_YAJL_VERSION_H -# include -# endif -# if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1) -# define HAVE_YAJL_V2 1 -# endif +#include +#include +#if HAVE_YAJL_YAJL_VERSION_H +#include +#endif +#if defined(YAJL_MAJOR) && (YAJL_MAJOR > 1) +#define HAVE_YAJL_V2 1 +#endif #endif -static int json_escape_string (char *buffer, size_t buffer_size, /* {{{ */ - const char *string) -{ +static int json_escape_string(char *buffer, size_t buffer_size, /* {{{ */ + const char *string) { size_t dst_pos; if ((buffer == NULL) || (string == NULL)) @@ -56,31 +55,28 @@ static int json_escape_string (char *buffer, size_t buffer_size, /* {{{ */ dst_pos = 0; -#define BUFFER_ADD(c) do { \ - if (dst_pos >= (buffer_size - 1)) { \ - buffer[buffer_size - 1] = 0; \ - return (-ENOMEM); \ - } \ - buffer[dst_pos] = (c); \ - dst_pos++; \ -} while (0) +#define BUFFER_ADD(c) \ + do { \ + if (dst_pos >= (buffer_size - 1)) { \ + buffer[buffer_size - 1] = 0; \ + return (-ENOMEM); \ + } \ + buffer[dst_pos] = (c); \ + dst_pos++; \ + } while (0) /* Escape special characters */ - BUFFER_ADD ('"'); - for (size_t src_pos = 0; string[src_pos] != 0; src_pos++) - { - if ((string[src_pos] == '"') - || (string[src_pos] == '\\')) - { - BUFFER_ADD ('\\'); - BUFFER_ADD (string[src_pos]); - } - else if (string[src_pos] <= 0x001F) - BUFFER_ADD ('?'); + BUFFER_ADD('"'); + for (size_t src_pos = 0; string[src_pos] != 0; src_pos++) { + if ((string[src_pos] == '"') || (string[src_pos] == '\\')) { + BUFFER_ADD('\\'); + BUFFER_ADD(string[src_pos]); + } else if (string[src_pos] <= 0x001F) + BUFFER_ADD('?'); else - BUFFER_ADD (string[src_pos]); + BUFFER_ADD(string[src_pos]); } /* for */ - BUFFER_ADD ('"'); + BUFFER_ADD('"'); buffer[dst_pos] = 0; #undef BUFFER_ADD @@ -88,219 +84,192 @@ static int json_escape_string (char *buffer, size_t buffer_size, /* {{{ */ return (0); } /* }}} int json_escape_string */ -static int values_to_json (char *buffer, size_t buffer_size, /* {{{ */ - const data_set_t *ds, const value_list_t *vl, int store_rates) -{ +static int values_to_json(char *buffer, size_t buffer_size, /* {{{ */ + const data_set_t *ds, const value_list_t *vl, + int store_rates) { size_t offset = 0; gauge_t *rates = NULL; - memset (buffer, 0, buffer_size); - -#define BUFFER_ADD(...) do { \ - int status; \ - status = ssnprintf (buffer + offset, buffer_size - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - { \ - sfree(rates); \ - return (-1); \ - } \ - else if (((size_t) status) >= (buffer_size - offset)) \ - { \ - sfree(rates); \ - return (-ENOMEM); \ - } \ - else \ - offset += ((size_t) status); \ -} while (0) - - BUFFER_ADD ("["); - for (size_t i = 0; i < ds->ds_num; i++) - { + memset(buffer, 0, buffer_size); + +#define BUFFER_ADD(...) \ + do { \ + int status; \ + status = ssnprintf(buffer + offset, buffer_size - offset, __VA_ARGS__); \ + if (status < 1) { \ + sfree(rates); \ + return (-1); \ + } else if (((size_t)status) >= (buffer_size - offset)) { \ + sfree(rates); \ + return (-ENOMEM); \ + } else \ + offset += ((size_t)status); \ + } while (0) + + BUFFER_ADD("["); + for (size_t i = 0; i < ds->ds_num; i++) { if (i > 0) - BUFFER_ADD (","); + BUFFER_ADD(","); - if (ds->ds[i].type == DS_TYPE_GAUGE) - { - if(isfinite (vl->values[i].gauge)) - BUFFER_ADD (JSON_GAUGE_FORMAT, vl->values[i].gauge); + if (ds->ds[i].type == DS_TYPE_GAUGE) { + if (isfinite(vl->values[i].gauge)) + BUFFER_ADD(JSON_GAUGE_FORMAT, vl->values[i].gauge); else - BUFFER_ADD ("null"); - } - else if (store_rates) - { + BUFFER_ADD("null"); + } else if (store_rates) { if (rates == NULL) - rates = uc_get_rate (ds, vl); - if (rates == NULL) - { - WARNING ("utils_format_json: uc_get_rate failed."); + rates = uc_get_rate(ds, vl); + if (rates == NULL) { + WARNING("utils_format_json: uc_get_rate failed."); sfree(rates); return (-1); } - if(isfinite (rates[i])) - BUFFER_ADD (JSON_GAUGE_FORMAT, rates[i]); + if (isfinite(rates[i])) + BUFFER_ADD(JSON_GAUGE_FORMAT, rates[i]); else - BUFFER_ADD ("null"); - } - else if (ds->ds[i].type == DS_TYPE_COUNTER) - BUFFER_ADD ("%llu", vl->values[i].counter); + BUFFER_ADD("null"); + } else if (ds->ds[i].type == DS_TYPE_COUNTER) + BUFFER_ADD("%llu", vl->values[i].counter); else if (ds->ds[i].type == DS_TYPE_DERIVE) - BUFFER_ADD ("%"PRIi64, vl->values[i].derive); + BUFFER_ADD("%" PRIi64, vl->values[i].derive); else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) - BUFFER_ADD ("%"PRIu64, vl->values[i].absolute); - else - { - ERROR ("format_json: Unknown data source type: %i", - ds->ds[i].type); - sfree (rates); + BUFFER_ADD("%" PRIu64, vl->values[i].absolute); + else { + ERROR("format_json: Unknown data source type: %i", ds->ds[i].type); + sfree(rates); return (-1); } } /* for ds->ds_num */ - BUFFER_ADD ("]"); + BUFFER_ADD("]"); #undef BUFFER_ADD - DEBUG ("format_json: values_to_json: buffer = %s;", buffer); + DEBUG("format_json: values_to_json: buffer = %s;", buffer); sfree(rates); return (0); } /* }}} int values_to_json */ -static int dstypes_to_json (char *buffer, size_t buffer_size, /* {{{ */ - const data_set_t *ds) -{ +static int dstypes_to_json(char *buffer, size_t buffer_size, /* {{{ */ + const data_set_t *ds) { size_t offset = 0; - memset (buffer, 0, buffer_size); - -#define BUFFER_ADD(...) do { \ - int status; \ - status = ssnprintf (buffer + offset, buffer_size - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - return (-1); \ - else if (((size_t) status) >= (buffer_size - offset)) \ - return (-ENOMEM); \ - else \ - offset += ((size_t) status); \ -} while (0) - - BUFFER_ADD ("["); - for (size_t i = 0; i < ds->ds_num; i++) - { + memset(buffer, 0, buffer_size); + +#define BUFFER_ADD(...) \ + do { \ + int status; \ + status = ssnprintf(buffer + offset, buffer_size - offset, __VA_ARGS__); \ + if (status < 1) \ + return (-1); \ + else if (((size_t)status) >= (buffer_size - offset)) \ + return (-ENOMEM); \ + else \ + offset += ((size_t)status); \ + } while (0) + + BUFFER_ADD("["); + for (size_t i = 0; i < ds->ds_num; i++) { if (i > 0) - BUFFER_ADD (","); + BUFFER_ADD(","); - BUFFER_ADD ("\"%s\"", DS_TYPE_TO_STRING (ds->ds[i].type)); + BUFFER_ADD("\"%s\"", DS_TYPE_TO_STRING(ds->ds[i].type)); } /* for ds->ds_num */ - BUFFER_ADD ("]"); + BUFFER_ADD("]"); #undef BUFFER_ADD - DEBUG ("format_json: dstypes_to_json: buffer = %s;", buffer); + DEBUG("format_json: dstypes_to_json: buffer = %s;", buffer); return (0); } /* }}} int dstypes_to_json */ -static int dsnames_to_json (char *buffer, size_t buffer_size, /* {{{ */ - const data_set_t *ds) -{ +static int dsnames_to_json(char *buffer, size_t buffer_size, /* {{{ */ + const data_set_t *ds) { size_t offset = 0; - memset (buffer, 0, buffer_size); - -#define BUFFER_ADD(...) do { \ - int status; \ - status = ssnprintf (buffer + offset, buffer_size - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - return (-1); \ - else if (((size_t) status) >= (buffer_size - offset)) \ - return (-ENOMEM); \ - else \ - offset += ((size_t) status); \ -} while (0) - - BUFFER_ADD ("["); - for (size_t i = 0; i < ds->ds_num; i++) - { + memset(buffer, 0, buffer_size); + +#define BUFFER_ADD(...) \ + do { \ + int status; \ + status = ssnprintf(buffer + offset, buffer_size - offset, __VA_ARGS__); \ + if (status < 1) \ + return (-1); \ + else if (((size_t)status) >= (buffer_size - offset)) \ + return (-ENOMEM); \ + else \ + offset += ((size_t)status); \ + } while (0) + + BUFFER_ADD("["); + for (size_t i = 0; i < ds->ds_num; i++) { if (i > 0) - BUFFER_ADD (","); + BUFFER_ADD(","); - BUFFER_ADD ("\"%s\"", ds->ds[i].name); + BUFFER_ADD("\"%s\"", ds->ds[i].name); } /* for ds->ds_num */ - BUFFER_ADD ("]"); + BUFFER_ADD("]"); #undef BUFFER_ADD - DEBUG ("format_json: dsnames_to_json: buffer = %s;", buffer); + DEBUG("format_json: dsnames_to_json: buffer = %s;", buffer); return (0); } /* }}} int dsnames_to_json */ -static int meta_data_keys_to_json (char *buffer, size_t buffer_size, /* {{{ */ - meta_data_t *meta, char **keys, size_t keys_num) -{ +static int meta_data_keys_to_json(char *buffer, size_t buffer_size, /* {{{ */ + meta_data_t *meta, char **keys, + size_t keys_num) { size_t offset = 0; int status; buffer[0] = 0; -#define BUFFER_ADD(...) do { \ - status = ssnprintf (buffer + offset, buffer_size - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - return (-1); \ - else if (((size_t) status) >= (buffer_size - offset)) \ - return (-ENOMEM); \ - else \ - offset += ((size_t) status); \ -} while (0) - - for (size_t i = 0; i < keys_num; ++i) - { +#define BUFFER_ADD(...) \ + do { \ + status = ssnprintf(buffer + offset, buffer_size - offset, __VA_ARGS__); \ + if (status < 1) \ + return (-1); \ + else if (((size_t)status) >= (buffer_size - offset)) \ + return (-ENOMEM); \ + else \ + offset += ((size_t)status); \ + } while (0) + + for (size_t i = 0; i < keys_num; ++i) { int type; char *key = keys[i]; - type = meta_data_type (meta, key); - if (type == MD_TYPE_STRING) - { + type = meta_data_type(meta, key); + if (type == MD_TYPE_STRING) { char *value = NULL; - if (meta_data_get_string (meta, key, &value) == 0) - { + if (meta_data_get_string(meta, key, &value) == 0) { char temp[512] = ""; - status = json_escape_string (temp, sizeof (temp), value); - sfree (value); + status = json_escape_string(temp, sizeof(temp), value); + sfree(value); if (status != 0) return status; - BUFFER_ADD (",\"%s\":%s", key, temp); + BUFFER_ADD(",\"%s\":%s", key, temp); } - } - else if (type == MD_TYPE_SIGNED_INT) - { + } else if (type == MD_TYPE_SIGNED_INT) { int64_t value = 0; - if (meta_data_get_signed_int (meta, key, &value) == 0) - BUFFER_ADD (",\"%s\":%"PRIi64, key, value); - } - else if (type == MD_TYPE_UNSIGNED_INT) - { + if (meta_data_get_signed_int(meta, key, &value) == 0) + BUFFER_ADD(",\"%s\":%" PRIi64, key, value); + } else if (type == MD_TYPE_UNSIGNED_INT) { uint64_t value = 0; - if (meta_data_get_unsigned_int (meta, key, &value) == 0) - BUFFER_ADD (",\"%s\":%"PRIu64, key, value); - } - else if (type == MD_TYPE_DOUBLE) - { + if (meta_data_get_unsigned_int(meta, key, &value) == 0) + BUFFER_ADD(",\"%s\":%" PRIu64, key, value); + } else if (type == MD_TYPE_DOUBLE) { double value = 0.0; - if (meta_data_get_double (meta, key, &value) == 0) - BUFFER_ADD (",\"%s\":%f", key, value); - } - else if (type == MD_TYPE_BOOLEAN) - { + if (meta_data_get_double(meta, key, &value) == 0) + BUFFER_ADD(",\"%s\":%f", key, value); + } else if (type == MD_TYPE_BOOLEAN) { _Bool value = 0; - if (meta_data_get_boolean (meta, key, &value) == 0) - BUFFER_ADD (",\"%s\":%s", key, value ? "true" : "false"); + if (meta_data_get_boolean(meta, key, &value) == 0) + BUFFER_ADD(",\"%s\":%s", key, value ? "true" : "false"); } } /* for (keys) */ @@ -308,16 +277,15 @@ static int meta_data_keys_to_json (char *buffer, size_t buffer_size, /* {{{ */ return (ENOENT); buffer[0] = '{'; /* replace leading ',' */ - BUFFER_ADD ("}"); + BUFFER_ADD("}"); #undef BUFFER_ADD return (0); } /* }}} int meta_data_keys_to_json */ -static int meta_data_to_json (char *buffer, size_t buffer_size, /* {{{ */ - meta_data_t *meta) -{ +static int meta_data_to_json(char *buffer, size_t buffer_size, /* {{{ */ + meta_data_t *meta) { char **keys = NULL; size_t keys_num; int status; @@ -325,123 +293,124 @@ static int meta_data_to_json (char *buffer, size_t buffer_size, /* {{{ */ if ((buffer == NULL) || (buffer_size == 0) || (meta == NULL)) return (EINVAL); - status = meta_data_toc (meta, &keys); + status = meta_data_toc(meta, &keys); if (status <= 0) return (status); - keys_num = (size_t) status; + keys_num = (size_t)status; - status = meta_data_keys_to_json (buffer, buffer_size, meta, keys, keys_num); + status = meta_data_keys_to_json(buffer, buffer_size, meta, keys, keys_num); for (size_t i = 0; i < keys_num; ++i) - sfree (keys[i]); - sfree (keys); + sfree(keys[i]); + sfree(keys); return status; } /* }}} int meta_data_to_json */ -static int value_list_to_json (char *buffer, size_t buffer_size, /* {{{ */ - const data_set_t *ds, const value_list_t *vl, int store_rates) -{ +static int value_list_to_json(char *buffer, size_t buffer_size, /* {{{ */ + const data_set_t *ds, const value_list_t *vl, + int store_rates) { char temp[512]; size_t offset = 0; int status; - memset (buffer, 0, buffer_size); + memset(buffer, 0, buffer_size); -#define BUFFER_ADD(...) do { \ - status = ssnprintf (buffer + offset, buffer_size - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - return (-1); \ - else if (((size_t) status) >= (buffer_size - offset)) \ - return (-ENOMEM); \ - else \ - offset += ((size_t) status); \ -} while (0) +#define BUFFER_ADD(...) \ + do { \ + status = ssnprintf(buffer + offset, buffer_size - offset, __VA_ARGS__); \ + if (status < 1) \ + return (-1); \ + else if (((size_t)status) >= (buffer_size - offset)) \ + return (-ENOMEM); \ + else \ + offset += ((size_t)status); \ + } while (0) /* All value lists have a leading comma. The first one will be replaced with * a square bracket in `format_json_finalize'. */ - BUFFER_ADD (",{"); + BUFFER_ADD(",{"); - status = values_to_json (temp, sizeof (temp), ds, vl, store_rates); + status = values_to_json(temp, sizeof(temp), ds, vl, store_rates); if (status != 0) return (status); - BUFFER_ADD ("\"values\":%s", temp); + BUFFER_ADD("\"values\":%s", temp); - status = dstypes_to_json (temp, sizeof (temp), ds); + status = dstypes_to_json(temp, sizeof(temp), ds); if (status != 0) return (status); - BUFFER_ADD (",\"dstypes\":%s", temp); + BUFFER_ADD(",\"dstypes\":%s", temp); - status = dsnames_to_json (temp, sizeof (temp), ds); + status = dsnames_to_json(temp, sizeof(temp), ds); if (status != 0) return (status); - BUFFER_ADD (",\"dsnames\":%s", temp); - - BUFFER_ADD (",\"time\":%.3f", CDTIME_T_TO_DOUBLE (vl->time)); - BUFFER_ADD (",\"interval\":%.3f", CDTIME_T_TO_DOUBLE (vl->interval)); - -#define BUFFER_ADD_KEYVAL(key, value) do { \ - status = json_escape_string (temp, sizeof (temp), (value)); \ - if (status != 0) \ - return (status); \ - BUFFER_ADD (",\"%s\":%s", (key), temp); \ -} while (0) - - BUFFER_ADD_KEYVAL ("host", vl->host); - BUFFER_ADD_KEYVAL ("plugin", vl->plugin); - BUFFER_ADD_KEYVAL ("plugin_instance", vl->plugin_instance); - BUFFER_ADD_KEYVAL ("type", vl->type); - BUFFER_ADD_KEYVAL ("type_instance", vl->type_instance); - - if (vl->meta != NULL) - { + BUFFER_ADD(",\"dsnames\":%s", temp); + + BUFFER_ADD(",\"time\":%.3f", CDTIME_T_TO_DOUBLE(vl->time)); + BUFFER_ADD(",\"interval\":%.3f", CDTIME_T_TO_DOUBLE(vl->interval)); + +#define BUFFER_ADD_KEYVAL(key, value) \ + do { \ + status = json_escape_string(temp, sizeof(temp), (value)); \ + if (status != 0) \ + return (status); \ + BUFFER_ADD(",\"%s\":%s", (key), temp); \ + } while (0) + + BUFFER_ADD_KEYVAL("host", vl->host); + BUFFER_ADD_KEYVAL("plugin", vl->plugin); + BUFFER_ADD_KEYVAL("plugin_instance", vl->plugin_instance); + BUFFER_ADD_KEYVAL("type", vl->type); + BUFFER_ADD_KEYVAL("type_instance", vl->type_instance); + + if (vl->meta != NULL) { char meta_buffer[buffer_size]; - memset (meta_buffer, 0, sizeof (meta_buffer)); - status = meta_data_to_json (meta_buffer, sizeof (meta_buffer), vl->meta); + memset(meta_buffer, 0, sizeof(meta_buffer)); + status = meta_data_to_json(meta_buffer, sizeof(meta_buffer), vl->meta); if (status != 0) return (status); - BUFFER_ADD (",\"meta\":%s", meta_buffer); + BUFFER_ADD(",\"meta\":%s", meta_buffer); } /* if (vl->meta != NULL) */ - BUFFER_ADD ("}"); + BUFFER_ADD("}"); #undef BUFFER_ADD_KEYVAL #undef BUFFER_ADD - DEBUG ("format_json: value_list_to_json: buffer = %s;", buffer); + DEBUG("format_json: value_list_to_json: buffer = %s;", buffer); return (0); } /* }}} int value_list_to_json */ -static int format_json_value_list_nocheck (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free, - const data_set_t *ds, const value_list_t *vl, - int store_rates, size_t temp_size) -{ +static int format_json_value_list_nocheck(char *buffer, /* {{{ */ + size_t *ret_buffer_fill, + size_t *ret_buffer_free, + const data_set_t *ds, + const value_list_t *vl, + int store_rates, size_t temp_size) { char temp[temp_size]; int status; - status = value_list_to_json (temp, sizeof (temp), ds, vl, store_rates); + status = value_list_to_json(temp, sizeof(temp), ds, vl, store_rates); if (status != 0) return (status); - temp_size = strlen (temp); + temp_size = strlen(temp); - memcpy (buffer + (*ret_buffer_fill), temp, temp_size + 1); + memcpy(buffer + (*ret_buffer_fill), temp, temp_size + 1); (*ret_buffer_fill) += temp_size; (*ret_buffer_free) -= temp_size; return (0); } /* }}} int format_json_value_list_nocheck */ -int format_json_initialize (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free) -{ +int format_json_initialize(char *buffer, /* {{{ */ + size_t *ret_buffer_fill, size_t *ret_buffer_free) { size_t buffer_fill; size_t buffer_free; - if ((buffer == NULL) || (ret_buffer_fill == NULL) || (ret_buffer_free == NULL)) + if ((buffer == NULL) || (ret_buffer_fill == NULL) || + (ret_buffer_free == NULL)) return (-EINVAL); buffer_fill = *ret_buffer_fill; @@ -453,19 +422,19 @@ int format_json_initialize (char *buffer, /* {{{ */ if (buffer_free < 3) return (-ENOMEM); - memset (buffer, 0, buffer_free); + memset(buffer, 0, buffer_free); *ret_buffer_fill = buffer_fill; *ret_buffer_free = buffer_free; return (0); } /* }}} int format_json_initialize */ -int format_json_finalize (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free) -{ +int format_json_finalize(char *buffer, /* {{{ */ + size_t *ret_buffer_fill, size_t *ret_buffer_free) { size_t pos; - if ((buffer == NULL) || (ret_buffer_fill == NULL) || (ret_buffer_free == NULL)) + if ((buffer == NULL) || (ret_buffer_fill == NULL) || + (ret_buffer_free == NULL)) return (-EINVAL); if (*ret_buffer_free < 2) @@ -479,7 +448,7 @@ int format_json_finalize (char *buffer, /* {{{ */ pos = *ret_buffer_fill; buffer[pos] = ']'; - buffer[pos+1] = 0; + buffer[pos + 1] = 0; (*ret_buffer_fill)++; (*ret_buffer_free)--; @@ -487,152 +456,157 @@ int format_json_finalize (char *buffer, /* {{{ */ return (0); } /* }}} int format_json_finalize */ -int format_json_value_list (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free, - const data_set_t *ds, const value_list_t *vl, int store_rates) -{ - if ((buffer == NULL) - || (ret_buffer_fill == NULL) || (ret_buffer_free == NULL) - || (ds == NULL) || (vl == NULL)) +int format_json_value_list(char *buffer, /* {{{ */ + size_t *ret_buffer_fill, size_t *ret_buffer_free, + const data_set_t *ds, const value_list_t *vl, + int store_rates) { + if ((buffer == NULL) || (ret_buffer_fill == NULL) || + (ret_buffer_free == NULL) || (ds == NULL) || (vl == NULL)) return (-EINVAL); if (*ret_buffer_free < 3) return (-ENOMEM); - return (format_json_value_list_nocheck (buffer, - ret_buffer_fill, ret_buffer_free, ds, vl, - store_rates, (*ret_buffer_free) - 2)); + return (format_json_value_list_nocheck(buffer, ret_buffer_fill, + ret_buffer_free, ds, vl, store_rates, + (*ret_buffer_free) - 2)); } /* }}} int format_json_value_list */ #if HAVE_LIBYAJL -static int json_add_string (yajl_gen g, char const *str) /* {{{ */ +static int json_add_string(yajl_gen g, char const *str) /* {{{ */ { if (str == NULL) - return (int) yajl_gen_null (g); + return (int)yajl_gen_null(g); - return (int) yajl_gen_string (g, (unsigned char const *) str, (unsigned int) strlen (str)); + return (int)yajl_gen_string(g, (unsigned char const *)str, + (unsigned int)strlen(str)); } /* }}} int json_add_string */ -#define JSON_ADD(g, str) do { \ - yajl_gen_status status = json_add_string (g, str); \ - if (status != yajl_gen_status_ok) { return -1; } \ -} while (0) - -#define JSON_ADDF(g, format, ...) do { \ - char *str = ssnprintf_alloc (format, __VA_ARGS__); \ - yajl_gen_status status = json_add_string (g, str); \ - free (str); \ - if (status != yajl_gen_status_ok) { return -1; } \ -} while (0) - -static int format_json_meta (yajl_gen g, notification_meta_t *meta) /* {{{ */ +#define JSON_ADD(g, str) \ + do { \ + yajl_gen_status status = json_add_string(g, str); \ + if (status != yajl_gen_status_ok) { \ + return -1; \ + } \ + } while (0) + +#define JSON_ADDF(g, format, ...) \ + do { \ + char *str = ssnprintf_alloc(format, __VA_ARGS__); \ + yajl_gen_status status = json_add_string(g, str); \ + free(str); \ + if (status != yajl_gen_status_ok) { \ + return -1; \ + } \ + } while (0) + +static int format_json_meta(yajl_gen g, notification_meta_t *meta) /* {{{ */ { if (meta == NULL) return 0; - JSON_ADD (g, meta->name); - switch (meta->type) - { - case NM_TYPE_STRING: - JSON_ADD (g, meta->nm_value.nm_string); - break; - case NM_TYPE_SIGNED_INT: - JSON_ADDF (g, "%"PRIi64, meta->nm_value.nm_signed_int); - break; - case NM_TYPE_UNSIGNED_INT: - JSON_ADDF (g, "%"PRIu64, meta->nm_value.nm_unsigned_int); - break; - case NM_TYPE_DOUBLE: - JSON_ADDF (g, JSON_GAUGE_FORMAT, meta->nm_value.nm_double); - break; - case NM_TYPE_BOOLEAN: - JSON_ADD (g, meta->nm_value.nm_boolean ? "true" : "false"); - break; - default: - ERROR ("format_json_meta: unknown meta data type %d (name \"%s\")", meta->type, meta->name); - yajl_gen_null (g); + JSON_ADD(g, meta->name); + switch (meta->type) { + case NM_TYPE_STRING: + JSON_ADD(g, meta->nm_value.nm_string); + break; + case NM_TYPE_SIGNED_INT: + JSON_ADDF(g, "%" PRIi64, meta->nm_value.nm_signed_int); + break; + case NM_TYPE_UNSIGNED_INT: + JSON_ADDF(g, "%" PRIu64, meta->nm_value.nm_unsigned_int); + break; + case NM_TYPE_DOUBLE: + JSON_ADDF(g, JSON_GAUGE_FORMAT, meta->nm_value.nm_double); + break; + case NM_TYPE_BOOLEAN: + JSON_ADD(g, meta->nm_value.nm_boolean ? "true" : "false"); + break; + default: + ERROR("format_json_meta: unknown meta data type %d (name \"%s\")", + meta->type, meta->name); + yajl_gen_null(g); } - return format_json_meta (g, meta->next); + return format_json_meta(g, meta->next); } /* }}} int format_json_meta */ -static int format_time (yajl_gen g, cdtime_t t) /* {{{ */ +static int format_time(yajl_gen g, cdtime_t t) /* {{{ */ { char buffer[RFC3339NANO_SIZE] = ""; - if (rfc3339nano (buffer, sizeof (buffer), t) != 0) + if (rfc3339nano(buffer, sizeof(buffer), t) != 0) return -1; - JSON_ADD (g, buffer); + JSON_ADD(g, buffer); return 0; } /* }}} int format_time */ -static int format_alert (yajl_gen g, notification_t const *n) /* {{{ */ +static int format_alert(yajl_gen g, notification_t const *n) /* {{{ */ { - yajl_gen_array_open (g); - yajl_gen_map_open (g); /* BEGIN alert */ + yajl_gen_array_open(g); + yajl_gen_map_open(g); /* BEGIN alert */ /* * labels */ - JSON_ADD (g, "labels"); - yajl_gen_map_open (g); /* BEGIN labels */ + JSON_ADD(g, "labels"); + yajl_gen_map_open(g); /* BEGIN labels */ - JSON_ADD (g, "alertname"); - if (strncmp (n->plugin, n->type, strlen (n->plugin)) == 0) - JSON_ADDF (g, "collectd_%s", n->type); + JSON_ADD(g, "alertname"); + if (strncmp(n->plugin, n->type, strlen(n->plugin)) == 0) + JSON_ADDF(g, "collectd_%s", n->type); else - JSON_ADDF (g, "collectd_%s_%s", n->plugin, n->type); + JSON_ADDF(g, "collectd_%s_%s", n->plugin, n->type); - JSON_ADD (g, "instance"); - JSON_ADD (g, n->host); + JSON_ADD(g, "instance"); + JSON_ADD(g, n->host); /* mangling of plugin instance and type instance into labels is copied from * the Prometheus collectd exporter. */ - if (strlen (n->plugin_instance) > 0) - { - JSON_ADD (g, n->plugin); - JSON_ADD (g, n->plugin_instance); + if (strlen(n->plugin_instance) > 0) { + JSON_ADD(g, n->plugin); + JSON_ADD(g, n->plugin_instance); } - if (strlen (n->type_instance) > 0) - { - if (strlen (n->plugin_instance) > 0) - JSON_ADD (g, "type"); + if (strlen(n->type_instance) > 0) { + if (strlen(n->plugin_instance) > 0) + JSON_ADD(g, "type"); else - JSON_ADD (g, n->plugin); - JSON_ADD (g, n->type_instance); + JSON_ADD(g, n->plugin); + JSON_ADD(g, n->type_instance); } - JSON_ADD (g, "severity"); - JSON_ADD (g, (n->severity == NOTIF_FAILURE) ? "FAILURE" - : (n->severity == NOTIF_WARNING) ? "WARNING" - : (n->severity == NOTIF_OKAY) ? "OKAY" - : "UNKNOWN"); + JSON_ADD(g, "severity"); + JSON_ADD(g, (n->severity == NOTIF_FAILURE) + ? "FAILURE" + : (n->severity == NOTIF_WARNING) + ? "WARNING" + : (n->severity == NOTIF_OKAY) ? "OKAY" : "UNKNOWN"); - JSON_ADD (g, "service"); - JSON_ADD (g, "collectd"); + JSON_ADD(g, "service"); + JSON_ADD(g, "collectd"); - yajl_gen_map_close (g); /* END labels */ + yajl_gen_map_close(g); /* END labels */ /* * annotations */ - JSON_ADD (g, "annotations"); - yajl_gen_map_open (g); /* BEGIN annotations */ + JSON_ADD(g, "annotations"); + yajl_gen_map_open(g); /* BEGIN annotations */ - JSON_ADD (g, "summary"); - JSON_ADD (g, n->message); + JSON_ADD(g, "summary"); + JSON_ADD(g, n->message); - if (format_json_meta (g, n->meta) != 0) + if (format_json_meta(g, n->meta) != 0) return -1; - yajl_gen_map_close (g); /* END annotations */ + yajl_gen_map_close(g); /* END annotations */ - JSON_ADD (g, "startsAt"); - format_time (g, n->time); + JSON_ADD(g, "startsAt"); + format_time(g, n->time); - yajl_gen_map_close (g); /* END alert */ - yajl_gen_array_close (g); + yajl_gen_map_close(g); /* END alert */ + yajl_gen_array_close(g); return 0; } /* }}} format_alert */ @@ -657,9 +631,8 @@ static int format_alert (yajl_gen g, notification_t const *n) /* {{{ */ * "endsAt": , // not used * }] */ -int format_json_notification (char *buffer, size_t buffer_size, /* {{{ */ - notification_t const *n) -{ +int format_json_notification(char *buffer, size_t buffer_size, /* {{{ */ + notification_t const *n) { yajl_gen g; unsigned char const *out; #if HAVE_YAJL_V2 @@ -672,45 +645,43 @@ int format_json_notification (char *buffer, size_t buffer_size, /* {{{ */ return EINVAL; #if HAVE_YAJL_V2 - g = yajl_gen_alloc (NULL); + g = yajl_gen_alloc(NULL); if (g == NULL) return -1; -# if COLLECT_DEBUG - yajl_gen_config (g, yajl_gen_beautify, 1); - yajl_gen_config (g, yajl_gen_validate_utf8, 1); -# endif +#if COLLECT_DEBUG + yajl_gen_config(g, yajl_gen_beautify, 1); + yajl_gen_config(g, yajl_gen_validate_utf8, 1); +#endif #else /* !HAVE_YAJL_V2 */ - yajl_gen_config conf = { 0 }; -# if COLLECT_DEBUG + yajl_gen_config conf = {0}; +#if COLLECT_DEBUG conf.beautify = 1; conf.indentString = " "; -# endif - g = yajl_gen_alloc (&conf, NULL); +#endif + g = yajl_gen_alloc(&conf, NULL); if (g == NULL) return -1; #endif - if (format_alert (g, n) != 0) - { - yajl_gen_clear (g); - yajl_gen_free (g); + if (format_alert(g, n) != 0) { + yajl_gen_clear(g); + yajl_gen_free(g); return -1; } /* copy to output buffer */ - yajl_gen_get_buf (g, &out, &unused_out_len); - sstrncpy (buffer, (void *) out, buffer_size); + yajl_gen_get_buf(g, &out, &unused_out_len); + sstrncpy(buffer, (void *)out, buffer_size); - yajl_gen_clear (g); - yajl_gen_free (g); + yajl_gen_clear(g); + yajl_gen_free(g); return 0; } /* }}} format_json_notification */ #else -int format_json_notification (char *buffer, size_t buffer_size, /* {{{ */ - notification_t const *n) -{ - ERROR ("format_json_notification: Not available (requires libyajl)."); +int format_json_notification(char *buffer, size_t buffer_size, /* {{{ */ + notification_t const *n) { + ERROR("format_json_notification: Not available (requires libyajl)."); return ENOTSUP; } /* }}} int format_json_notification */ #endif diff --git a/src/utils_format_json.h b/src/utils_format_json.h index a3eda304..d3d02160 100644 --- a/src/utils_format_json.h +++ b/src/utils_format_json.h @@ -32,17 +32,17 @@ #include "plugin.h" #ifndef JSON_GAUGE_FORMAT -# define JSON_GAUGE_FORMAT GAUGE_FORMAT +#define JSON_GAUGE_FORMAT GAUGE_FORMAT #endif -int format_json_initialize (char *buffer, - size_t *ret_buffer_fill, size_t *ret_buffer_free); -int format_json_value_list (char *buffer, - size_t *ret_buffer_fill, size_t *ret_buffer_free, - const data_set_t *ds, const value_list_t *vl, int store_rates); -int format_json_finalize (char *buffer, - size_t *ret_buffer_fill, size_t *ret_buffer_free); -int format_json_notification (char *buffer, size_t buffer_size, - notification_t const *n); +int format_json_initialize(char *buffer, size_t *ret_buffer_fill, + size_t *ret_buffer_free); +int format_json_value_list(char *buffer, size_t *ret_buffer_fill, + size_t *ret_buffer_free, const data_set_t *ds, + const value_list_t *vl, int store_rates); +int format_json_finalize(char *buffer, size_t *ret_buffer_fill, + size_t *ret_buffer_free); +int format_json_notification(char *buffer, size_t buffer_size, + notification_t const *n); #endif /* UTILS_FORMAT_JSON_H */ diff --git a/src/utils_format_json_test.c b/src/utils_format_json_test.c index d13c932f..389004d3 100644 --- a/src/utils_format_json_test.c +++ b/src/utils_format_json_test.c @@ -30,57 +30,54 @@ #include "config.h" #if KERNEL_SOLARIS -# ifndef _POSIX_C_SOURCE -# define _POSIX_C_SOURCE 200112L -# endif -# undef __EXTENSIONS__ +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200112L +#endif +#undef __EXTENSIONS__ #endif #include "collectd.h" +#include "common.h" /* for STATIC_ARRAY_SIZE */ #include "testing.h" #include "utils_format_json.h" -#include "common.h" /* for STATIC_ARRAY_SIZE */ #include #include #if HAVE_YAJL_YAJL_VERSION_H -# include +#include #endif #if YAJL_MAJOR > 1 -# define HAVE_YAJL_V2 1 +#define HAVE_YAJL_V2 1 #endif -typedef struct -{ +typedef struct { char const *key; char const *value; } label_t; -typedef struct -{ +typedef struct { label_t *expected_labels; - size_t expected_labels_num; + size_t expected_labels_num; label_t *current_label; } test_case_t; #if HAVE_YAJL_V2 -static int test_map_key (void *ctx, unsigned char const *key, size_t key_len) +static int test_map_key(void *ctx, unsigned char const *key, size_t key_len) #else -static int test_map_key (void *ctx, unsigned char const *key, unsigned int key_len) +static int test_map_key(void *ctx, unsigned char const *key, + unsigned int key_len) #endif { test_case_t *c = ctx; size_t i; c->current_label = NULL; - for (i = 0; i < c->expected_labels_num; i++) - { + for (i = 0; i < c->expected_labels_num; i++) { label_t *l = c->expected_labels + i; - if ((strlen (l->key) == key_len) - && (strncmp (l->key, (char const *) key, key_len) == 0)) - { + if ((strlen(l->key) == key_len) && + (strncmp(l->key, (char const *)key, key_len) == 0)) { c->current_label = l; break; } @@ -89,41 +86,41 @@ static int test_map_key (void *ctx, unsigned char const *key, unsigned int key_l return 1; /* continue */ } -static int expect_label (char const *name, char const *got, char const *want) -{ - _Bool ok = (strcmp (got, want) == 0); +static int expect_label(char const *name, char const *got, char const *want) { + _Bool ok = (strcmp(got, want) == 0); char msg[1024]; if (ok) - snprintf (msg, sizeof (msg), "label[\"%s\"] = \"%s\"", name, got); + snprintf(msg, sizeof(msg), "label[\"%s\"] = \"%s\"", name, got); else - snprintf (msg, sizeof (msg), "label[\"%s\"] = \"%s\", want \"%s\"", name, got, want); + snprintf(msg, sizeof(msg), "label[\"%s\"] = \"%s\", want \"%s\"", name, got, + want); - OK1 (ok, msg); + OK1(ok, msg); return 0; } #if HAVE_YAJL_V2 -static int test_string (void *ctx, unsigned char const *value, size_t value_len) +static int test_string(void *ctx, unsigned char const *value, size_t value_len) #else -static int test_string (void *ctx, unsigned char const *value, unsigned int value_len) +static int test_string(void *ctx, unsigned char const *value, + unsigned int value_len) #endif { test_case_t *c = ctx; - if (c->current_label != NULL) - { + if (c->current_label != NULL) { label_t *l = c->current_label; char *got; int status; - got = malloc (value_len + 1); - memmove (got, value, value_len); + got = malloc(value_len + 1); + memmove(got, value, value_len); got[value_len] = 0; - status = expect_label (l->key, got, l->value); + status = expect_label(l->key, got, l->value); - free (got); + free(got); if (status != 0) return 0; /* abort */ @@ -132,50 +129,54 @@ static int test_string (void *ctx, unsigned char const *value, unsigned int valu return 1; /* continue */ } -static int expect_json_labels (char *json, label_t *labels, size_t labels_num) -{ +static int expect_json_labels(char *json, label_t *labels, size_t labels_num) { yajl_callbacks funcs = { - .yajl_string = test_string, - .yajl_map_key = test_map_key, + .yajl_string = test_string, .yajl_map_key = test_map_key, }; - test_case_t c = { labels, labels_num, NULL }; + test_case_t c = {labels, labels_num, NULL}; yajl_handle hndl; #if HAVE_YAJL_V2 - CHECK_NOT_NULL (hndl = yajl_alloc (&funcs, /* alloc = */ NULL, &c)); + CHECK_NOT_NULL(hndl = yajl_alloc(&funcs, /* alloc = */ NULL, &c)); #else - CHECK_NOT_NULL (hndl = yajl_alloc (&funcs, /* config = */ NULL, /* alloc = */ NULL, &c)); + CHECK_NOT_NULL( + hndl = yajl_alloc(&funcs, /* config = */ NULL, /* alloc = */ NULL, &c)); #endif - OK (yajl_parse (hndl, (unsigned char *) json, strlen (json)) == yajl_status_ok); + OK(yajl_parse(hndl, (unsigned char *)json, strlen(json)) == yajl_status_ok); - yajl_free (hndl); + yajl_free(hndl); return 0; } -DEF_TEST(notification) -{ +DEF_TEST(notification) { label_t labels[] = { - {"summary", "this is a message"}, - {"alertname", "collectd_unit_test"}, - {"instance", "example.com"}, - {"service", "collectd"}, - {"unit", "case"}, + {"summary", "this is a message"}, + {"alertname", "collectd_unit_test"}, + {"instance", "example.com"}, + {"service", "collectd"}, + {"unit", "case"}, }; /* 1448284606.125 ^= 1555083754651779072 */ - notification_t n = { NOTIF_WARNING, 1555083754651779072ULL, "this is a message", - "example.com", "unit", "", "test", "case", NULL }; + notification_t n = {NOTIF_WARNING, + 1555083754651779072ULL, + "this is a message", + "example.com", + "unit", + "", + "test", + "case", + NULL}; char got[1024]; - CHECK_ZERO (format_json_notification (got, sizeof (got), &n)); + CHECK_ZERO(format_json_notification(got, sizeof(got), &n)); // printf ("got = \"%s\";\n", got); - return expect_json_labels (got, labels, STATIC_ARRAY_SIZE (labels)); + return expect_json_labels(got, labels, STATIC_ARRAY_SIZE(labels)); } -int main (void) -{ +int main(void) { RUN_TEST(notification); END_TEST; diff --git a/src/utils_format_kairosdb.c b/src/utils_format_kairosdb.c index 41055c7b..4c25d188 100644 --- a/src/utils_format_kairosdb.c +++ b/src/utils_format_kairosdb.c @@ -24,16 +24,14 @@ * Aurelien beorn Rougemont **/ - #include "collectd.h" -#include "plugin.h" #include "common.h" +#include "plugin.h" #include "utils_cache.h" #include "utils_format_kairosdb.h" - /* This is the KAIROSDB format for write_http output * * Target format @@ -56,9 +54,8 @@ * ] */ -static int kairosdb_escape_string (char *buffer, size_t buffer_size, /* {{{ */ - const char *string) -{ +static int kairosdb_escape_string(char *buffer, size_t buffer_size, /* {{{ */ + const char *string) { size_t dst_pos; if ((buffer == NULL) || (string == NULL)) @@ -69,27 +66,25 @@ static int kairosdb_escape_string (char *buffer, size_t buffer_size, /* {{{ */ dst_pos = 0; -#define BUFFER_ADD(c) do { \ - if (dst_pos >= (buffer_size - 1)) { \ - buffer[buffer_size - 1] = 0; \ - return (-ENOMEM); \ - } \ - buffer[dst_pos] = (c); \ - dst_pos++; \ -} while (0) +#define BUFFER_ADD(c) \ + do { \ + if (dst_pos >= (buffer_size - 1)) { \ + buffer[buffer_size - 1] = 0; \ + return (-ENOMEM); \ + } \ + buffer[dst_pos] = (c); \ + dst_pos++; \ + } while (0) /* Escape special characters */ /* authorize -_. and alpha num but also escapes " */ - BUFFER_ADD ('"'); - for (size_t src_pos = 0; string[src_pos] != 0; src_pos++) - { - if (isalnum(string[src_pos]) || - 0x2d == string[src_pos] || - 0x2e == string[src_pos] || - 0x5f == string[src_pos]) - BUFFER_ADD (tolower(string[src_pos])); + BUFFER_ADD('"'); + for (size_t src_pos = 0; string[src_pos] != 0; src_pos++) { + if (isalnum(string[src_pos]) || 0x2d == string[src_pos] || + 0x2e == string[src_pos] || 0x5f == string[src_pos]) + BUFFER_ADD(tolower(string[src_pos])); } /* for */ - BUFFER_ADD ('"'); + BUFFER_ADD('"'); buffer[dst_pos] = 0; #undef BUFFER_ADD @@ -97,222 +92,190 @@ static int kairosdb_escape_string (char *buffer, size_t buffer_size, /* {{{ */ return (0); } /* }}} int kairosdb_escape_string */ -static int values_to_kairosdb (char *buffer, size_t buffer_size, /* {{{ */ - const data_set_t *ds, const value_list_t *vl, int store_rates, - size_t ds_idx) -{ +static int values_to_kairosdb(char *buffer, size_t buffer_size, /* {{{ */ + const data_set_t *ds, const value_list_t *vl, + int store_rates, size_t ds_idx) { size_t offset = 0; gauge_t *rates = NULL; - memset (buffer, 0, buffer_size); - -#define BUFFER_ADD(...) do { \ - int status; \ - status = ssnprintf (buffer + offset, buffer_size - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - { \ - sfree(rates); \ - return (-1); \ - } \ - else if (((size_t) status) >= (buffer_size - offset)) \ - { \ - sfree(rates); \ - return (-ENOMEM); \ - } \ - else \ - offset += ((size_t) status); \ -} while (0) - - if (ds->ds[ds_idx].type == DS_TYPE_GAUGE) - { - if (isfinite (vl->values[ds_idx].gauge)) - { - BUFFER_ADD ("[["); - BUFFER_ADD ("%"PRIu64, CDTIME_T_TO_MS (vl->time)); - BUFFER_ADD (","); - BUFFER_ADD (JSON_GAUGE_FORMAT, vl->values[ds_idx].gauge); - } - else - { - DEBUG ("utils_format_kairosdb: invalid vl->values[ds_idx].gauge for %s|%s|%s|%s|%s", - vl->plugin, - vl->plugin_instance, - vl->type, - vl->type_instance, - ds->ds[ds_idx].name); + memset(buffer, 0, buffer_size); + +#define BUFFER_ADD(...) \ + do { \ + int status; \ + status = ssnprintf(buffer + offset, buffer_size - offset, __VA_ARGS__); \ + if (status < 1) { \ + sfree(rates); \ + return (-1); \ + } else if (((size_t)status) >= (buffer_size - offset)) { \ + sfree(rates); \ + return (-ENOMEM); \ + } else \ + offset += ((size_t)status); \ + } while (0) + + if (ds->ds[ds_idx].type == DS_TYPE_GAUGE) { + if (isfinite(vl->values[ds_idx].gauge)) { + BUFFER_ADD("[["); + BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time)); + BUFFER_ADD(","); + BUFFER_ADD(JSON_GAUGE_FORMAT, vl->values[ds_idx].gauge); + } else { + DEBUG("utils_format_kairosdb: invalid vl->values[ds_idx].gauge for " + "%s|%s|%s|%s|%s", + vl->plugin, vl->plugin_instance, vl->type, vl->type_instance, + ds->ds[ds_idx].name); return (-1); } - } - else if (store_rates) - { + } else if (store_rates) { if (rates == NULL) - rates = uc_get_rate (ds, vl); - if (rates == NULL) - { - WARNING ("utils_format_kairosdb: uc_get_rate failed for %s|%s|%s|%s|%s", - vl->plugin, - vl->plugin_instance, - vl->type, - vl->type_instance, - ds->ds[ds_idx].name); + rates = uc_get_rate(ds, vl); + if (rates == NULL) { + WARNING("utils_format_kairosdb: uc_get_rate failed for %s|%s|%s|%s|%s", + vl->plugin, vl->plugin_instance, vl->type, vl->type_instance, + ds->ds[ds_idx].name); return (-1); } - if (isfinite (rates[ds_idx])) - { - BUFFER_ADD ("[["); - BUFFER_ADD ("%"PRIu64, CDTIME_T_TO_MS (vl->time)); - BUFFER_ADD (","); - BUFFER_ADD (JSON_GAUGE_FORMAT, rates[ds_idx]); - } - else - { - WARNING ("utils_format_kairosdb: invalid rates[ds_idx] for %s|%s|%s|%s|%s", - vl->plugin, - vl->plugin_instance, - vl->type, - vl->type_instance, - ds->ds[ds_idx].name); + if (isfinite(rates[ds_idx])) { + BUFFER_ADD("[["); + BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time)); + BUFFER_ADD(","); + BUFFER_ADD(JSON_GAUGE_FORMAT, rates[ds_idx]); + } else { + WARNING("utils_format_kairosdb: invalid rates[ds_idx] for %s|%s|%s|%s|%s", + vl->plugin, vl->plugin_instance, vl->type, vl->type_instance, + ds->ds[ds_idx].name); sfree(rates); return (-1); } - } - else if (ds->ds[ds_idx].type == DS_TYPE_COUNTER) - { - BUFFER_ADD ("[["); - BUFFER_ADD ("%"PRIu64, CDTIME_T_TO_MS (vl->time)); - BUFFER_ADD (","); - BUFFER_ADD ("%llu", vl->values[ds_idx].counter); - } - else if (ds->ds[ds_idx].type == DS_TYPE_DERIVE) - { - BUFFER_ADD ("[["); - BUFFER_ADD ("%"PRIu64, CDTIME_T_TO_MS (vl->time)); - BUFFER_ADD (","); - BUFFER_ADD ("%"PRIi64, vl->values[ds_idx].derive); - } - else if (ds->ds[ds_idx].type == DS_TYPE_ABSOLUTE) - { - BUFFER_ADD ("[["); - BUFFER_ADD ("%"PRIu64, CDTIME_T_TO_MS (vl->time)); - BUFFER_ADD (","); - BUFFER_ADD ("%"PRIu64, vl->values[ds_idx].absolute); - } - else - { - ERROR ("format_kairosdb: Unknown data source type: %i", - ds->ds[ds_idx].type); - sfree (rates); + } else if (ds->ds[ds_idx].type == DS_TYPE_COUNTER) { + BUFFER_ADD("[["); + BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time)); + BUFFER_ADD(","); + BUFFER_ADD("%llu", vl->values[ds_idx].counter); + } else if (ds->ds[ds_idx].type == DS_TYPE_DERIVE) { + BUFFER_ADD("[["); + BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time)); + BUFFER_ADD(","); + BUFFER_ADD("%" PRIi64, vl->values[ds_idx].derive); + } else if (ds->ds[ds_idx].type == DS_TYPE_ABSOLUTE) { + BUFFER_ADD("[["); + BUFFER_ADD("%" PRIu64, CDTIME_T_TO_MS(vl->time)); + BUFFER_ADD(","); + BUFFER_ADD("%" PRIu64, vl->values[ds_idx].absolute); + } else { + ERROR("format_kairosdb: Unknown data source type: %i", ds->ds[ds_idx].type); + sfree(rates); return (-1); } - BUFFER_ADD ("]]"); + BUFFER_ADD("]]"); #undef BUFFER_ADD - DEBUG ("format_kairosdb: values_to_kairosdb: buffer = %s;", buffer); + DEBUG("format_kairosdb: values_to_kairosdb: buffer = %s;", buffer); sfree(rates); return (0); } /* }}} int values_to_kairosdb */ -static int value_list_to_kairosdb (char *buffer, size_t buffer_size, /* {{{ */ - const data_set_t *ds, const value_list_t *vl, int store_rates) -{ +static int value_list_to_kairosdb(char *buffer, size_t buffer_size, /* {{{ */ + const data_set_t *ds, const value_list_t *vl, + int store_rates) { char temp[512]; size_t offset = 0; int status; - memset (buffer, 0, buffer_size); - -#define BUFFER_ADD(...) do { \ - status = ssnprintf (buffer + offset, buffer_size - offset, \ - __VA_ARGS__); \ - if (status < 1) \ - return (-1); \ - else if (((size_t) status) >= (buffer_size - offset)) \ - return (-ENOMEM); \ - else \ - offset += ((size_t) status); \ -} while (0) - -#define BUFFER_ADD_KEYVAL(key, value) do { \ - status = kairosdb_escape_string (temp, sizeof (temp), (value)); \ - if (status != 0) \ - return (status); \ - BUFFER_ADD (",\"%s\": %s", (key), temp); \ -} while (0) - - for (size_t i = 0; i < ds->ds_num; i++) - { + memset(buffer, 0, buffer_size); + +#define BUFFER_ADD(...) \ + do { \ + status = ssnprintf(buffer + offset, buffer_size - offset, __VA_ARGS__); \ + if (status < 1) \ + return (-1); \ + else if (((size_t)status) >= (buffer_size - offset)) \ + return (-ENOMEM); \ + else \ + offset += ((size_t)status); \ + } while (0) + +#define BUFFER_ADD_KEYVAL(key, value) \ + do { \ + status = kairosdb_escape_string(temp, sizeof(temp), (value)); \ + if (status != 0) \ + return (status); \ + BUFFER_ADD(",\"%s\": %s", (key), temp); \ + } while (0) + + for (size_t i = 0; i < ds->ds_num; i++) { /* All value lists have a leading comma. The first one will be replaced with * a square bracket in `format_kairosdb_finalize'. */ - BUFFER_ADD (",{"); + BUFFER_ADD(",{"); - BUFFER_ADD ("\"name\":\"collectd"); + BUFFER_ADD("\"name\":\"collectd"); - BUFFER_ADD (".%s", vl->plugin); + BUFFER_ADD(".%s", vl->plugin); - status = values_to_kairosdb (temp, sizeof (temp), ds, vl, store_rates, i); + status = values_to_kairosdb(temp, sizeof(temp), ds, vl, store_rates, i); if (status != 0) return (status); - BUFFER_ADD ("\", \"datapoints\": %s", temp); + BUFFER_ADD("\", \"datapoints\": %s", temp); /* * Now adds meta data to metric as tags */ - memset (temp, 0, sizeof(temp)); + memset(temp, 0, sizeof(temp)); - BUFFER_ADD (", \"tags\":\{"); + BUFFER_ADD(", \"tags\":\{"); - BUFFER_ADD ("\"host\": \"%s\"", vl->host); + BUFFER_ADD("\"host\": \"%s\"", vl->host); if (strlen(vl->plugin_instance)) - BUFFER_ADD_KEYVAL ("plugin_instance", vl->plugin_instance); - BUFFER_ADD_KEYVAL ("type", vl->type); + BUFFER_ADD_KEYVAL("plugin_instance", vl->plugin_instance); + BUFFER_ADD_KEYVAL("type", vl->type); if (strlen(vl->type_instance)) - BUFFER_ADD_KEYVAL ("type_instance", vl->type_instance); + BUFFER_ADD_KEYVAL("type_instance", vl->type_instance); if (ds->ds_num != 1) - BUFFER_ADD_KEYVAL ("ds", ds->ds[i].name); - BUFFER_ADD ("}}"); + BUFFER_ADD_KEYVAL("ds", ds->ds[i].name); + BUFFER_ADD("}}"); } /* for ds->ds_num */ #undef BUFFER_ADD_KEYVAL #undef BUFFER_ADD - DEBUG ("format_kairosdb: value_list_to_kairosdb: buffer = %s;", buffer); + DEBUG("format_kairosdb: value_list_to_kairosdb: buffer = %s;", buffer); return (0); } /* }}} int value_list_to_kairosdb */ -static int format_kairosdb_value_list_nocheck (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free, - const data_set_t *ds, const value_list_t *vl, - int store_rates, size_t temp_size) -{ +static int format_kairosdb_value_list_nocheck( + char *buffer, /* {{{ */ + size_t *ret_buffer_fill, size_t *ret_buffer_free, const data_set_t *ds, + const value_list_t *vl, int store_rates, size_t temp_size) { char temp[temp_size]; int status; - status = value_list_to_kairosdb (temp, sizeof (temp), ds, vl, store_rates); + status = value_list_to_kairosdb(temp, sizeof(temp), ds, vl, store_rates); if (status != 0) return (status); - temp_size = strlen (temp); + temp_size = strlen(temp); - memcpy (buffer + (*ret_buffer_fill), temp, temp_size + 1); + memcpy(buffer + (*ret_buffer_fill), temp, temp_size + 1); (*ret_buffer_fill) += temp_size; (*ret_buffer_free) -= temp_size; return (0); } /* }}} int format_kairosdb_value_list_nocheck */ -int format_kairosdb_initialize (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free) -{ +int format_kairosdb_initialize(char *buffer, /* {{{ */ + size_t *ret_buffer_fill, + size_t *ret_buffer_free) { size_t buffer_fill; size_t buffer_free; - if ((buffer == NULL) || (ret_buffer_fill == NULL) || (ret_buffer_free == NULL)) + if ((buffer == NULL) || (ret_buffer_fill == NULL) || + (ret_buffer_free == NULL)) return (-EINVAL); buffer_fill = *ret_buffer_fill; @@ -324,19 +287,19 @@ int format_kairosdb_initialize (char *buffer, /* {{{ */ if (buffer_free < 3) return (-ENOMEM); - memset (buffer, 0, buffer_free); + memset(buffer, 0, buffer_free); *ret_buffer_fill = buffer_fill; *ret_buffer_free = buffer_free; return (0); } /* }}} int format_kairosdb_initialize */ -int format_kairosdb_finalize (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free) -{ +int format_kairosdb_finalize(char *buffer, /* {{{ */ + size_t *ret_buffer_fill, size_t *ret_buffer_free) { size_t pos; - if ((buffer == NULL) || (ret_buffer_fill == NULL) || (ret_buffer_free == NULL)) + if ((buffer == NULL) || (ret_buffer_fill == NULL) || + (ret_buffer_free == NULL)) return (-EINVAL); if (*ret_buffer_free < 2) @@ -350,7 +313,7 @@ int format_kairosdb_finalize (char *buffer, /* {{{ */ pos = *ret_buffer_fill; buffer[pos] = ']'; - buffer[pos+1] = 0; + buffer[pos + 1] = 0; (*ret_buffer_fill)++; (*ret_buffer_free)--; @@ -358,21 +321,20 @@ int format_kairosdb_finalize (char *buffer, /* {{{ */ return (0); } /* }}} int format_kairosdb_finalize */ -int format_kairosdb_value_list (char *buffer, /* {{{ */ - size_t *ret_buffer_fill, size_t *ret_buffer_free, - const data_set_t *ds, const value_list_t *vl, int store_rates) -{ - if ((buffer == NULL) - || (ret_buffer_fill == NULL) || (ret_buffer_free == NULL) - || (ds == NULL) || (vl == NULL)) +int format_kairosdb_value_list(char *buffer, /* {{{ */ + size_t *ret_buffer_fill, size_t *ret_buffer_free, + const data_set_t *ds, const value_list_t *vl, + int store_rates) { + if ((buffer == NULL) || (ret_buffer_fill == NULL) || + (ret_buffer_free == NULL) || (ds == NULL) || (vl == NULL)) return (-EINVAL); if (*ret_buffer_free < 3) return (-ENOMEM); - return (format_kairosdb_value_list_nocheck (buffer, - ret_buffer_fill, ret_buffer_free, ds, vl, - store_rates, (*ret_buffer_free) - 2)); + return (format_kairosdb_value_list_nocheck( + buffer, ret_buffer_fill, ret_buffer_free, ds, vl, store_rates, + (*ret_buffer_free) - 2)); } /* }}} int format_kairosdb_value_list */ /* vim: set sw=2 sts=2 et fdm=marker : */ diff --git a/src/utils_format_kairosdb.h b/src/utils_format_kairosdb.h index 764b0b1e..9174318d 100644 --- a/src/utils_format_kairosdb.h +++ b/src/utils_format_kairosdb.h @@ -32,15 +32,15 @@ #include "plugin.h" #ifndef JSON_GAUGE_FORMAT -# define JSON_GAUGE_FORMAT GAUGE_FORMAT +#define JSON_GAUGE_FORMAT GAUGE_FORMAT #endif -int format_kairosdb_initialize (char *buffer, - size_t *ret_buffer_fill, size_t *ret_buffer_free); -int format_kairosdb_value_list (char *buffer, - size_t *ret_buffer_fill, size_t *ret_buffer_free, - const data_set_t *ds, const value_list_t *vl, int store_rates); -int format_kairosdb_finalize (char *buffer, - size_t *ret_buffer_fill, size_t *ret_buffer_free); +int format_kairosdb_initialize(char *buffer, size_t *ret_buffer_fill, + size_t *ret_buffer_free); +int format_kairosdb_value_list(char *buffer, size_t *ret_buffer_fill, + size_t *ret_buffer_free, const data_set_t *ds, + const value_list_t *vl, int store_rates); +int format_kairosdb_finalize(char *buffer, size_t *ret_buffer_fill, + size_t *ret_buffer_free); #endif /* UTILS_FORMAT_KAIROSDB_H */ diff --git a/src/utils_latency.c b/src/utils_latency.c index 5749f10d..f0311e84 100644 --- a/src/utils_latency.c +++ b/src/utils_latency.c @@ -26,24 +26,23 @@ #include "collectd.h" +#include "common.h" #include "plugin.h" #include "utils_latency.h" -#include "common.h" -#include #include +#include #ifndef LLONG_MAX -# define LLONG_MAX 9223372036854775807LL +#define LLONG_MAX 9223372036854775807LL #endif #ifndef HISTOGRAM_DEFAULT_BIN_WIDTH /* 1048576 = 2^20 ^= 1/1024 s */ -# define HISTOGRAM_DEFAULT_BIN_WIDTH 1048576 +#define HISTOGRAM_DEFAULT_BIN_WIDTH 1048576 #endif -struct latency_counter_s -{ +struct latency_counter_s { cdtime_t start_time; cdtime_t sum; @@ -73,7 +72,7 @@ struct latency_counter_s * So, if the required bin width is 300, then new bin width will be 512 as it is * the next nearest power of 2. */ -static void change_bin_width (latency_counter_t *lc, cdtime_t latency) /* {{{ */ +static void change_bin_width(latency_counter_t *lc, cdtime_t latency) /* {{{ */ { /* This function is called because the new value is above histogram's range. * First find the required bin width: @@ -81,9 +80,11 @@ static void change_bin_width (latency_counter_t *lc, cdtime_t latency) /* {{{ */ * then get the next nearest power of 2 * newBinWidth = 2^(ceil(log2(requiredBinWidth))) */ - double required_bin_width = ((double) (latency + 1)) / ((double) HISTOGRAM_NUM_BINS); - double required_bin_width_logbase2 = log (required_bin_width) / log (2.0); - cdtime_t new_bin_width = (cdtime_t) (pow (2.0, ceil (required_bin_width_logbase2)) + .5); + double required_bin_width = + ((double)(latency + 1)) / ((double)HISTOGRAM_NUM_BINS); + double required_bin_width_logbase2 = log(required_bin_width) / log(2.0); + cdtime_t new_bin_width = + (cdtime_t)(pow(2.0, ceil(required_bin_width_logbase2)) + .5); cdtime_t old_bin_width = lc->bin_width; lc->bin_width = new_bin_width; @@ -92,50 +93,49 @@ static void change_bin_width (latency_counter_t *lc, cdtime_t latency) /* {{{ */ * old bin's count to new bin. */ if (lc->num > 0) // if the histogram has data then iterate else skip { - double width_change_ratio = ((double) old_bin_width) / ((double) new_bin_width); - - for (size_t i = 0; i < HISTOGRAM_NUM_BINS; i++) - { - size_t new_bin = (size_t) (((double) i) * width_change_ratio); - if (i == new_bin) - continue; - assert (new_bin < i); - - lc->histogram[new_bin] += lc->histogram[i]; - lc->histogram[i] = 0; - } + double width_change_ratio = + ((double)old_bin_width) / ((double)new_bin_width); + + for (size_t i = 0; i < HISTOGRAM_NUM_BINS; i++) { + size_t new_bin = (size_t)(((double)i) * width_change_ratio); + if (i == new_bin) + continue; + assert(new_bin < i); + + lc->histogram[new_bin] += lc->histogram[i]; + lc->histogram[i] = 0; + } } DEBUG("utils_latency: change_bin_width: latency = %.3f; " - "old_bin_width = %.3f; new_bin_width = %.3f;", - CDTIME_T_TO_DOUBLE (latency), - CDTIME_T_TO_DOUBLE (old_bin_width), - CDTIME_T_TO_DOUBLE (new_bin_width)); + "old_bin_width = %.3f; new_bin_width = %.3f;", + CDTIME_T_TO_DOUBLE(latency), CDTIME_T_TO_DOUBLE(old_bin_width), + CDTIME_T_TO_DOUBLE(new_bin_width)); } /* }}} void change_bin_width */ -latency_counter_t *latency_counter_create (void) /* {{{ */ +latency_counter_t *latency_counter_create(void) /* {{{ */ { latency_counter_t *lc; - lc = calloc (1, sizeof (*lc)); + lc = calloc(1, sizeof(*lc)); if (lc == NULL) return (NULL); lc->bin_width = HISTOGRAM_DEFAULT_BIN_WIDTH; - latency_counter_reset (lc); + latency_counter_reset(lc); return (lc); } /* }}} latency_counter_t *latency_counter_create */ -void latency_counter_destroy (latency_counter_t *lc) /* {{{ */ +void latency_counter_destroy(latency_counter_t *lc) /* {{{ */ { - sfree (lc); + sfree(lc); } /* }}} void latency_counter_destroy */ -void latency_counter_add (latency_counter_t *lc, cdtime_t latency) /* {{{ */ +void latency_counter_add(latency_counter_t *lc, cdtime_t latency) /* {{{ */ { cdtime_t bin; - if ((lc == NULL) || (latency == 0) || (latency > ((cdtime_t) LLONG_MAX))) + if ((lc == NULL) || (latency == 0) || (latency > ((cdtime_t)LLONG_MAX))) return; lc->sum += latency; @@ -152,20 +152,18 @@ void latency_counter_add (latency_counter_t *lc, cdtime_t latency) /* {{{ */ * subtract one from the cdtime_t value so that exactly 1.0 ms get sorted * accordingly. */ bin = (latency - 1) / lc->bin_width; - if (bin >= HISTOGRAM_NUM_BINS) - { - change_bin_width (lc, latency); - bin = (latency - 1) / lc->bin_width; - if (bin >= HISTOGRAM_NUM_BINS) - { - ERROR ("utils_latency: latency_counter_add: Invalid bin: %"PRIu64, bin); - return; - } + if (bin >= HISTOGRAM_NUM_BINS) { + change_bin_width(lc, latency); + bin = (latency - 1) / lc->bin_width; + if (bin >= HISTOGRAM_NUM_BINS) { + ERROR("utils_latency: latency_counter_add: Invalid bin: %" PRIu64, bin); + return; + } } lc->histogram[bin]++; } /* }}} void latency_counter_add */ -void latency_counter_reset (latency_counter_t *lc) /* {{{ */ +void latency_counter_reset(latency_counter_t *lc) /* {{{ */ { if (lc == NULL) return; @@ -179,69 +177,65 @@ void latency_counter_reset (latency_counter_t *lc) /* {{{ */ Value of 4 is selected to reduce frequent changes of bin width. */ #define REDUCE_THRESHOLD 4 - if ((lc->num > 0) && (lc->bin_width >= HISTOGRAM_DEFAULT_BIN_WIDTH * 2) - && (max_bin < HISTOGRAM_NUM_BINS / REDUCE_THRESHOLD)) - { + if ((lc->num > 0) && (lc->bin_width >= HISTOGRAM_DEFAULT_BIN_WIDTH * 2) && + (max_bin < HISTOGRAM_NUM_BINS / REDUCE_THRESHOLD)) { /* new bin width will be the previous power of 2 */ bin_width = bin_width / 2; DEBUG("utils_latency: latency_counter_reset: max_latency = %.3f; " - "max_bin = %"PRIu64"; old_bin_width = %.3f; new_bin_width = %.3f;", - CDTIME_T_TO_DOUBLE (lc->max), - max_bin, - CDTIME_T_TO_DOUBLE (lc->bin_width), - CDTIME_T_TO_DOUBLE (bin_width)); + "max_bin = %" PRIu64 "; old_bin_width = %.3f; new_bin_width = %.3f;", + CDTIME_T_TO_DOUBLE(lc->max), max_bin, + CDTIME_T_TO_DOUBLE(lc->bin_width), CDTIME_T_TO_DOUBLE(bin_width)); } - memset (lc, 0, sizeof (*lc)); + memset(lc, 0, sizeof(*lc)); /* preserve bin width */ lc->bin_width = bin_width; - lc->start_time = cdtime (); + lc->start_time = cdtime(); } /* }}} void latency_counter_reset */ -cdtime_t latency_counter_get_min (latency_counter_t *lc) /* {{{ */ +cdtime_t latency_counter_get_min(latency_counter_t *lc) /* {{{ */ { if (lc == NULL) return (0); return (lc->min); } /* }}} cdtime_t latency_counter_get_min */ -cdtime_t latency_counter_get_max (latency_counter_t *lc) /* {{{ */ +cdtime_t latency_counter_get_max(latency_counter_t *lc) /* {{{ */ { if (lc == NULL) return (0); return (lc->max); } /* }}} cdtime_t latency_counter_get_max */ -cdtime_t latency_counter_get_sum (latency_counter_t *lc) /* {{{ */ +cdtime_t latency_counter_get_sum(latency_counter_t *lc) /* {{{ */ { if (lc == NULL) return (0); return (lc->sum); } /* }}} cdtime_t latency_counter_get_sum */ -size_t latency_counter_get_num (latency_counter_t *lc) /* {{{ */ +size_t latency_counter_get_num(latency_counter_t *lc) /* {{{ */ { if (lc == NULL) return (0); return (lc->num); } /* }}} size_t latency_counter_get_num */ -cdtime_t latency_counter_get_average (latency_counter_t *lc) /* {{{ */ +cdtime_t latency_counter_get_average(latency_counter_t *lc) /* {{{ */ { double average; if ((lc == NULL) || (lc->num == 0)) return (0); - average = CDTIME_T_TO_DOUBLE (lc->sum) / ((double) lc->num); - return (DOUBLE_TO_CDTIME_T (average)); + average = CDTIME_T_TO_DOUBLE(lc->sum) / ((double)lc->num); + return (DOUBLE_TO_CDTIME_T(average)); } /* }}} cdtime_t latency_counter_get_average */ -cdtime_t latency_counter_get_percentile (latency_counter_t *lc, /* {{{ */ - double percent) -{ +cdtime_t latency_counter_get_percentile(latency_counter_t *lc, /* {{{ */ + double percent) { double percent_upper; double percent_lower; double p; @@ -257,14 +251,13 @@ cdtime_t latency_counter_get_percentile (latency_counter_t *lc, /* {{{ */ percent_upper = 0.0; percent_lower = 0.0; sum = 0; - for (i = 0; i < HISTOGRAM_NUM_BINS; i++) - { + for (i = 0; i < HISTOGRAM_NUM_BINS; i++) { percent_lower = percent_upper; sum += lc->histogram[i]; if (sum == 0) percent_upper = 0.0; else - percent_upper = 100.0 * ((double) sum) / ((double) lc->num); + percent_upper = 100.0 * ((double)sum) / ((double)lc->num); if (percent_upper >= percent) break; @@ -273,20 +266,20 @@ cdtime_t latency_counter_get_percentile (latency_counter_t *lc, /* {{{ */ if (i >= HISTOGRAM_NUM_BINS) return (0); - assert (percent_upper >= percent); - assert (percent_lower < percent); + assert(percent_upper >= percent); + assert(percent_lower < percent); if (i == 0) return (lc->bin_width); - latency_lower = ((cdtime_t) i) * lc->bin_width; + latency_lower = ((cdtime_t)i) * lc->bin_width; p = (percent - percent_lower) / (percent_upper - percent_lower); - latency_interpolated = latency_lower - + DOUBLE_TO_CDTIME_T (p * CDTIME_T_TO_DOUBLE (lc->bin_width)); + latency_interpolated = + latency_lower + DOUBLE_TO_CDTIME_T(p * CDTIME_T_TO_DOUBLE(lc->bin_width)); - DEBUG ("latency_counter_get_percentile: latency_interpolated = %.3f", - CDTIME_T_TO_DOUBLE (latency_interpolated)); + DEBUG("latency_counter_get_percentile: latency_interpolated = %.3f", + CDTIME_T_TO_DOUBLE(latency_interpolated)); return (latency_interpolated); } /* }}} cdtime_t latency_counter_get_percentile */ diff --git a/src/utils_latency.h b/src/utils_latency.h index 8fdf0249..85493e1a 100644 --- a/src/utils_latency.h +++ b/src/utils_latency.h @@ -29,25 +29,24 @@ #include "utils_time.h" #ifndef HISTOGRAM_NUM_BINS -# define HISTOGRAM_NUM_BINS 1000 +#define HISTOGRAM_NUM_BINS 1000 #endif struct latency_counter_s; typedef struct latency_counter_s latency_counter_t; -latency_counter_t *latency_counter_create (void); -void latency_counter_destroy (latency_counter_t *lc); +latency_counter_t *latency_counter_create(void); +void latency_counter_destroy(latency_counter_t *lc); -void latency_counter_add (latency_counter_t *lc, cdtime_t latency); -void latency_counter_reset (latency_counter_t *lc); +void latency_counter_add(latency_counter_t *lc, cdtime_t latency); +void latency_counter_reset(latency_counter_t *lc); -cdtime_t latency_counter_get_min (latency_counter_t *lc); -cdtime_t latency_counter_get_max (latency_counter_t *lc); -cdtime_t latency_counter_get_sum (latency_counter_t *lc); -size_t latency_counter_get_num (latency_counter_t *lc); -cdtime_t latency_counter_get_average (latency_counter_t *lc); -cdtime_t latency_counter_get_percentile (latency_counter_t *lc, - double percent); +cdtime_t latency_counter_get_min(latency_counter_t *lc); +cdtime_t latency_counter_get_max(latency_counter_t *lc); +cdtime_t latency_counter_get_sum(latency_counter_t *lc); +size_t latency_counter_get_num(latency_counter_t *lc); +cdtime_t latency_counter_get_average(latency_counter_t *lc); +cdtime_t latency_counter_get_percentile(latency_counter_t *lc, double percent); /* * NAME @@ -60,7 +59,7 @@ cdtime_t latency_counter_get_percentile (latency_counter_t *lc, * When lower is zero, then the interval is (0, upper]. * When upper is zero, then the interval is (lower, infinity). */ -double latency_counter_get_rate (const latency_counter_t *lc, - cdtime_t lower, cdtime_t upper, const cdtime_t now); +double latency_counter_get_rate(const latency_counter_t *lc, cdtime_t lower, + cdtime_t upper, const cdtime_t now); /* vim: set sw=2 sts=2 et : */ diff --git a/src/utils_latency_test.c b/src/utils_latency_test.c index 01f194f1..ef29d8bd 100644 --- a/src/utils_latency_test.c +++ b/src/utils_latency_test.c @@ -30,11 +30,10 @@ #include "collectd.h" #include "testing.h" -#include "utils_time.h" #include "utils_latency.h" +#include "utils_time.h" -DEF_TEST(simple) -{ +DEF_TEST(simple) { struct { double val; double min; @@ -42,61 +41,67 @@ DEF_TEST(simple) double sum; double avg; } cases[] = { - /* val min max sum avg */ - {0.5, 0.5, 0.5, 0.5, 0.5}, - {0.3, 0.3, 0.5, 0.8, 0.4}, - {0.7, 0.3, 0.7, 1.5, 0.5}, - {2.5, 0.3, 2.5, 4.0, 1.0}, - { 99, 0.3, 99, 103, 20.6}, - /* { -1, 0.3, 99, 103, 20.6}, see issue #1139 */ + /* val min max sum avg */ + {0.5, 0.5, 0.5, 0.5, 0.5}, {0.3, 0.3, 0.5, 0.8, 0.4}, + {0.7, 0.3, 0.7, 1.5, 0.5}, {2.5, 0.3, 2.5, 4.0, 1.0}, + {99, 0.3, 99, 103, 20.6}, + /* { -1, 0.3, 99, 103, 20.6}, see issue #1139 */ }; latency_counter_t *l; - CHECK_NOT_NULL (l = latency_counter_create ()); + CHECK_NOT_NULL(l = latency_counter_create()); - for (size_t i = 0; i < STATIC_ARRAY_SIZE (cases); i++) { - printf ("# case %zu: DOUBLE_TO_CDTIME_T(%g) = %"PRIu64"\n", - i, cases[i].val, DOUBLE_TO_CDTIME_T (cases[i].val)); - latency_counter_add (l, DOUBLE_TO_CDTIME_T (cases[i].val)); - - EXPECT_EQ_DOUBLE (cases[i].min, CDTIME_T_TO_DOUBLE (latency_counter_get_min (l))); - EXPECT_EQ_DOUBLE (cases[i].max, CDTIME_T_TO_DOUBLE (latency_counter_get_max (l))); - EXPECT_EQ_DOUBLE (cases[i].sum, CDTIME_T_TO_DOUBLE (latency_counter_get_sum (l))); - EXPECT_EQ_DOUBLE (cases[i].avg, CDTIME_T_TO_DOUBLE (latency_counter_get_average (l))); + for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++) { + printf("# case %zu: DOUBLE_TO_CDTIME_T(%g) = %" PRIu64 "\n", i, + cases[i].val, DOUBLE_TO_CDTIME_T(cases[i].val)); + latency_counter_add(l, DOUBLE_TO_CDTIME_T(cases[i].val)); + + EXPECT_EQ_DOUBLE(cases[i].min, + CDTIME_T_TO_DOUBLE(latency_counter_get_min(l))); + EXPECT_EQ_DOUBLE(cases[i].max, + CDTIME_T_TO_DOUBLE(latency_counter_get_max(l))); + EXPECT_EQ_DOUBLE(cases[i].sum, + CDTIME_T_TO_DOUBLE(latency_counter_get_sum(l))); + EXPECT_EQ_DOUBLE(cases[i].avg, + CDTIME_T_TO_DOUBLE(latency_counter_get_average(l))); } - latency_counter_destroy (l); + latency_counter_destroy(l); return 0; } -DEF_TEST(percentile) -{ +DEF_TEST(percentile) { latency_counter_t *l; - CHECK_NOT_NULL (l = latency_counter_create ()); + CHECK_NOT_NULL(l = latency_counter_create()); for (size_t i = 0; i < 100; i++) { - latency_counter_add (l, TIME_T_TO_CDTIME_T (((time_t) i) + 1)); + latency_counter_add(l, TIME_T_TO_CDTIME_T(((time_t)i) + 1)); } - EXPECT_EQ_DOUBLE ( 1.0, CDTIME_T_TO_DOUBLE (latency_counter_get_min (l))); - EXPECT_EQ_DOUBLE (100.0, CDTIME_T_TO_DOUBLE (latency_counter_get_max (l))); - EXPECT_EQ_DOUBLE (100.0 * 101.0 / 2.0, CDTIME_T_TO_DOUBLE (latency_counter_get_sum (l))); - EXPECT_EQ_DOUBLE ( 50.5, CDTIME_T_TO_DOUBLE (latency_counter_get_average (l))); - - EXPECT_EQ_DOUBLE (50.0, CDTIME_T_TO_DOUBLE (latency_counter_get_percentile (l, 50.0))); - EXPECT_EQ_DOUBLE (80.0, CDTIME_T_TO_DOUBLE (latency_counter_get_percentile (l, 80.0))); - EXPECT_EQ_DOUBLE (95.0, CDTIME_T_TO_DOUBLE (latency_counter_get_percentile (l, 95.0))); - EXPECT_EQ_DOUBLE (99.0, CDTIME_T_TO_DOUBLE (latency_counter_get_percentile (l, 99.0))); - - CHECK_ZERO (latency_counter_get_percentile (l, -1.0)); - CHECK_ZERO (latency_counter_get_percentile (l, 101.0)); - - latency_counter_destroy (l); + EXPECT_EQ_DOUBLE(1.0, CDTIME_T_TO_DOUBLE(latency_counter_get_min(l))); + EXPECT_EQ_DOUBLE(100.0, CDTIME_T_TO_DOUBLE(latency_counter_get_max(l))); + EXPECT_EQ_DOUBLE(100.0 * 101.0 / 2.0, + CDTIME_T_TO_DOUBLE(latency_counter_get_sum(l))); + EXPECT_EQ_DOUBLE(50.5, CDTIME_T_TO_DOUBLE(latency_counter_get_average(l))); + + EXPECT_EQ_DOUBLE(50.0, + CDTIME_T_TO_DOUBLE(latency_counter_get_percentile(l, 50.0))); + EXPECT_EQ_DOUBLE(80.0, + CDTIME_T_TO_DOUBLE(latency_counter_get_percentile(l, 80.0))); + EXPECT_EQ_DOUBLE(95.0, + CDTIME_T_TO_DOUBLE(latency_counter_get_percentile(l, 95.0))); + EXPECT_EQ_DOUBLE(99.0, + CDTIME_T_TO_DOUBLE(latency_counter_get_percentile(l, 99.0))); + + CHECK_ZERO(latency_counter_get_percentile(l, -1.0)); + CHECK_ZERO(latency_counter_get_percentile(l, 101.0)); + + latency_counter_destroy(l); return 0; } -DEF_TEST (get_rate) { +DEF_TEST(get_rate) { /* We re-declare the struct here so we can inspect its content. */ struct { cdtime_t start_time; @@ -106,40 +111,40 @@ DEF_TEST (get_rate) { cdtime_t max; cdtime_t bin_width; int histogram[HISTOGRAM_NUM_BINS]; - } *peek; + } * peek; latency_counter_t *l; - CHECK_NOT_NULL (l = latency_counter_create ()); - peek = (void *) l; + CHECK_NOT_NULL(l = latency_counter_create()); + peek = (void *)l; for (time_t i = 1; i <= 125; i++) { - latency_counter_add (l, TIME_T_TO_CDTIME_T(i)); + latency_counter_add(l, TIME_T_TO_CDTIME_T(i)); } /* We expect a bucket width of 125ms. */ - EXPECT_EQ_UINT64 (DOUBLE_TO_CDTIME_T(0.125), peek->bin_width); + EXPECT_EQ_UINT64(DOUBLE_TO_CDTIME_T(0.125), peek->bin_width); struct { size_t index; int want; } bucket_cases[] = { - { 0, 0}, /* (0.000-0.125] */ - { 1, 0}, /* (0.125-0.250] */ - { 2, 0}, /* (0.250-0.375] */ - { 3, 0}, /* (0.375-0.500] */ - { 4, 0}, /* (0.500-0.625] */ - { 5, 0}, /* (0.625-0.750] */ - { 6, 0}, /* (0.750-0.875] */ - { 7, 1}, /* (0.875-1.000] */ - { 8, 0}, /* (1.000-1.125] */ - { 9, 0}, /* (1.125-1.250] */ - {10, 0}, /* (1.250-1.375] */ - {11, 0}, /* (1.375-1.500] */ - {12, 0}, /* (1.500-1.625] */ - {13, 0}, /* (1.625-1.750] */ - {14, 0}, /* (1.750-1.875] */ - {15, 1}, /* (1.875-2.000] */ - {16, 0}, /* (2.000-2.125] */ + {0, 0}, /* (0.000-0.125] */ + {1, 0}, /* (0.125-0.250] */ + {2, 0}, /* (0.250-0.375] */ + {3, 0}, /* (0.375-0.500] */ + {4, 0}, /* (0.500-0.625] */ + {5, 0}, /* (0.625-0.750] */ + {6, 0}, /* (0.750-0.875] */ + {7, 1}, /* (0.875-1.000] */ + {8, 0}, /* (1.000-1.125] */ + {9, 0}, /* (1.125-1.250] */ + {10, 0}, /* (1.250-1.375] */ + {11, 0}, /* (1.375-1.500] */ + {12, 0}, /* (1.500-1.625] */ + {13, 0}, /* (1.625-1.750] */ + {14, 0}, /* (1.750-1.875] */ + {15, 1}, /* (1.875-2.000] */ + {16, 0}, /* (2.000-2.125] */ }; for (size_t i = 0; i < STATIC_ARRAY_SIZE(bucket_cases); i++) { @@ -152,80 +157,75 @@ DEF_TEST (get_rate) { cdtime_t upper_bound; double want; } cases[] = { - { // bucket 6 is zero - DOUBLE_TO_CDTIME_T_STATIC(0.750), - DOUBLE_TO_CDTIME_T_STATIC(0.875), - 0.00, - }, - { // bucket 7 contains the t=1 update - DOUBLE_TO_CDTIME_T_STATIC(0.875), - DOUBLE_TO_CDTIME_T_STATIC(1.000), - 1.00, - }, - { // range: bucket 7 - bucket 15; contains the t=1 and t=2 updates - DOUBLE_TO_CDTIME_T_STATIC(0.875), - DOUBLE_TO_CDTIME_T_STATIC(2.000), - 2.00, - }, - { // lower bucket is only partially applied - DOUBLE_TO_CDTIME_T_STATIC(0.875 + (0.125 / 4)), - DOUBLE_TO_CDTIME_T_STATIC(2.000), - 1.75, - }, - { // upper bucket is only partially applied - DOUBLE_TO_CDTIME_T_STATIC(0.875), - DOUBLE_TO_CDTIME_T_STATIC(2.000 - (0.125 / 4)), - 1.75, - }, - { // both buckets are only partially applied - DOUBLE_TO_CDTIME_T_STATIC(0.875 + (0.125 / 4)), - DOUBLE_TO_CDTIME_T_STATIC(2.000 - (0.125 / 4)), - 1.50, - }, - { // lower bound is unspecified - 0, - DOUBLE_TO_CDTIME_T_STATIC(2.000), - 2.00, - }, - { // upper bound is unspecified - DOUBLE_TO_CDTIME_T_STATIC(125.000 - 0.125), - 0, - 1.00, - }, - { // overflow test: upper >> longest latency - DOUBLE_TO_CDTIME_T_STATIC(1.000), - DOUBLE_TO_CDTIME_T_STATIC(999999), - 124.00, - }, - { // overflow test: lower > longest latency - DOUBLE_TO_CDTIME_T_STATIC(130), - 0, - 0.00, - }, - { // lower > upper => error - DOUBLE_TO_CDTIME_T_STATIC(10), - DOUBLE_TO_CDTIME_T_STATIC(9), - NAN, - }, - { // lower == upper => zero - DOUBLE_TO_CDTIME_T_STATIC(9), - DOUBLE_TO_CDTIME_T_STATIC(9), - 0.00, - }, + { + // bucket 6 is zero + DOUBLE_TO_CDTIME_T_STATIC(0.750), DOUBLE_TO_CDTIME_T_STATIC(0.875), + 0.00, + }, + { + // bucket 7 contains the t=1 update + DOUBLE_TO_CDTIME_T_STATIC(0.875), DOUBLE_TO_CDTIME_T_STATIC(1.000), + 1.00, + }, + { + // range: bucket 7 - bucket 15; contains the t=1 and t=2 updates + DOUBLE_TO_CDTIME_T_STATIC(0.875), DOUBLE_TO_CDTIME_T_STATIC(2.000), + 2.00, + }, + { + // lower bucket is only partially applied + DOUBLE_TO_CDTIME_T_STATIC(0.875 + (0.125 / 4)), + DOUBLE_TO_CDTIME_T_STATIC(2.000), 1.75, + }, + { + // upper bucket is only partially applied + DOUBLE_TO_CDTIME_T_STATIC(0.875), + DOUBLE_TO_CDTIME_T_STATIC(2.000 - (0.125 / 4)), 1.75, + }, + { + // both buckets are only partially applied + DOUBLE_TO_CDTIME_T_STATIC(0.875 + (0.125 / 4)), + DOUBLE_TO_CDTIME_T_STATIC(2.000 - (0.125 / 4)), 1.50, + }, + { + // lower bound is unspecified + 0, DOUBLE_TO_CDTIME_T_STATIC(2.000), 2.00, + }, + { + // upper bound is unspecified + DOUBLE_TO_CDTIME_T_STATIC(125.000 - 0.125), 0, 1.00, + }, + { + // overflow test: upper >> longest latency + DOUBLE_TO_CDTIME_T_STATIC(1.000), DOUBLE_TO_CDTIME_T_STATIC(999999), + 124.00, + }, + { + // overflow test: lower > longest latency + DOUBLE_TO_CDTIME_T_STATIC(130), 0, 0.00, + }, + { + // lower > upper => error + DOUBLE_TO_CDTIME_T_STATIC(10), DOUBLE_TO_CDTIME_T_STATIC(9), NAN, + }, + { + // lower == upper => zero + DOUBLE_TO_CDTIME_T_STATIC(9), DOUBLE_TO_CDTIME_T_STATIC(9), 0.00, + }, }; for (size_t i = 0; i < STATIC_ARRAY_SIZE(cases); i++) { cdtime_t now = peek->start_time + TIME_T_TO_CDTIME_T(1); - EXPECT_EQ_DOUBLE (cases[i].want, - latency_counter_get_rate (l, cases[i].lower_bound, cases[i].upper_bound, now)); + EXPECT_EQ_DOUBLE(cases[i].want, + latency_counter_get_rate(l, cases[i].lower_bound, + cases[i].upper_bound, now)); } - latency_counter_destroy (l); + latency_counter_destroy(l); return 0; } -int main (void) -{ +int main(void) { RUN_TEST(simple); RUN_TEST(percentile); RUN_TEST(get_rate); diff --git a/src/utils_mount.h b/src/utils_mount.h index 0a5c980f..0ad7d020 100644 --- a/src/utils_mount.h +++ b/src/utils_mount.h @@ -27,153 +27,153 @@ #include #if HAVE_FS_INFO_H -# include +#include #endif #if HAVE_FSHELP_H -# include +#include #endif #if HAVE_PATHS_H -# include +#include #endif #if HAVE_MNTENT_H -# include +#include #endif #if HAVE_MNTTAB_H -# include +#include #endif #if HAVE_SYS_FSTYP_H -# include +#include #endif #if HAVE_SYS_FS_TYPES_H -# include +#include #endif #if HAVE_SYS_MNTENT_H -# include +#include #endif #if HAVE_SYS_MNTTAB_H -# include +#include #endif #if HAVE_SYS_MOUNT_H -# include +#include #endif #if HAVE_SYS_STATFS_H -# include +#include #endif #if HAVE_SYS_VFS_H -# include +#include #endif #if HAVE_SYS_VFSTAB_H -# include +#include #endif /* Collectd Utils Mount Type */ #define CUMT_UNKNOWN (0) -#define CUMT_EXT2 (1) -#define CUMT_EXT3 (2) -#define CUMT_XFS (3) -#define CUMT_UFS (4) -#define CUMT_VXFS (5) -#define CUMT_ZFS (6) +#define CUMT_EXT2 (1) +#define CUMT_EXT3 (2) +#define CUMT_XFS (3) +#define CUMT_UFS (4) +#define CUMT_VXFS (5) +#define CUMT_ZFS (6) typedef struct _cu_mount_t cu_mount_t; struct _cu_mount_t { - char *dir; /* "/sys" or "/" */ - char *spec_device; /* "LABEL=/" or "none" or "proc" or "/dev/hda1" */ - char *device; /* "none" or "proc" or "/dev/hda1" */ - char *type; /* "sysfs" or "ext3" */ - char *options; /* "rw,noatime,commit=600,quota,grpquota" */ - cu_mount_t *next; + char *dir; /* "/sys" or "/" */ + char *spec_device; /* "LABEL=/" or "none" or "proc" or "/dev/hda1" */ + char *device; /* "none" or "proc" or "/dev/hda1" */ + char *type; /* "sysfs" or "ext3" */ + char *options; /* "rw,noatime,commit=600,quota,grpquota" */ + cu_mount_t *next; }; cu_mount_t *cu_mount_getlist(cu_mount_t **list); /* DESCRIPTION - The cu_mount_getlist() function creates a list - of all mountpoints. + The cu_mount_getlist() function creates a list + of all mountpoints. - If *list is NULL, a new list is created and *list is - set to point to the first entry. + If *list is NULL, a new list is created and *list is + set to point to the first entry. - If *list is not NULL, the list of mountpoints is appended - and *list is not changed. + If *list is not NULL, the list of mountpoints is appended + and *list is not changed. RETURN VALUE - The cu_mount_getlist() function returns a pointer to - the last entry of the list, or NULL if an error has - occured. + The cu_mount_getlist() function returns a pointer to + the last entry of the list, or NULL if an error has + occured. NOTES - In case of an error, *list is not modified. + In case of an error, *list is not modified. */ void cu_mount_freelist(cu_mount_t *list); /* DESCRIPTION - The cu_mount_freelist() function free()s all memory - allocated by *list and *list itself as well. + The cu_mount_freelist() function free()s all memory + allocated by *list and *list itself as well. */ char *cu_mount_checkoption(char *line, const char *keyword, int full); /* DESCRIPTION - The cu_mount_checkoption() function is a replacement of - char *hasmntopt(const struct mntent *mnt, const char *opt). - In fact hasmntopt() just looks for the first occurrence of the - characters at opt in mnt->mnt_opts. cu_mount_checkoption() - checks for the *option* keyword in line, starting at the - first character of line or after a ','. + The cu_mount_checkoption() function is a replacement of + char *hasmntopt(const struct mntent *mnt, const char *opt). + In fact hasmntopt() just looks for the first occurrence of the + characters at opt in mnt->mnt_opts. cu_mount_checkoption() + checks for the *option* keyword in line, starting at the + first character of line or after a ','. - If full is not 0 then also the end of keyword has to match - either the end of line or a ',' after keyword. + If full is not 0 then also the end of keyword has to match + either the end of line or a ',' after keyword. RETURN VALUE - The cu_mount_checkoption() function returns a pointer into - string line if a match of keyword is found. If no match is - found cu_mount_checkoption() returns NULL. + The cu_mount_checkoption() function returns a pointer into + string line if a match of keyword is found. If no match is + found cu_mount_checkoption() returns NULL. NOTES - Do *not* try to free() the pointer which is returned! It is - just part of the string line. + Do *not* try to free() the pointer which is returned! It is + just part of the string line. - full should be set to 0 when matching options like: rw, quota, - noatime. Set full to 1 when matching options like: loop=, - gid=, commit=. + full should be set to 0 when matching options like: rw, quota, + noatime. Set full to 1 when matching options like: loop=, + gid=, commit=. EXAMPLES - If line is "rw,usrquota,grpquota", keyword is "quota", NULL - will be returned (independend of full). + If line is "rw,usrquota,grpquota", keyword is "quota", NULL + will be returned (independend of full). - If line is "rw,usrquota,grpquota", keyword is "usrquota", - a pointer to "usrquota,grpquota" is returned (independend - of full). + If line is "rw,usrquota,grpquota", keyword is "usrquota", + a pointer to "usrquota,grpquota" is returned (independend + of full). - If line is "rw,loop=/dev/loop1,quota", keyword is "loop=" - and full is 0, then a pointer to "loop=/dev/loop1,quota" - is returned. If full is not 0 then NULL is returned. But - maybe you might want to try cu_mount_getoptionvalue()... + If line is "rw,loop=/dev/loop1,quota", keyword is "loop=" + and full is 0, then a pointer to "loop=/dev/loop1,quota" + is returned. If full is not 0 then NULL is returned. But + maybe you might want to try cu_mount_getoptionvalue()... */ char *cu_mount_getoptionvalue(char *line, const char *keyword); /* DESCRIPTION - The cu_mount_getoptionvalue() function can be used to grab - a VALUE out of a mount option (line) like: - loop=VALUE - whereas "loop=" is the keyword. + The cu_mount_getoptionvalue() function can be used to grab + a VALUE out of a mount option (line) like: + loop=VALUE + whereas "loop=" is the keyword. RETURN VALUE - If the cu_mount_getoptionvalue() function can find the option - keyword in line, then memory is allocated for the value of - that option and a pointer to that value is returned. + If the cu_mount_getoptionvalue() function can find the option + keyword in line, then memory is allocated for the value of + that option and a pointer to that value is returned. - If the option keyword is not found, cu_mount_getoptionvalue() - returns NULL; + If the option keyword is not found, cu_mount_getoptionvalue() + returns NULL; NOTES - Internally it calls cu_mount_checkoption(), then it - allocates memory for VALUE and returns a pointer to that - string. So *do not forget* to free() the memory returned - after use!!! + Internally it calls cu_mount_checkoption(), then it + allocates memory for VALUE and returns a pointer to that + string. So *do not forget* to free() the memory returned + after use!!! */ int cu_mount_type(const char *type); @@ -183,6 +183,4 @@ int cu_mount_type(const char *type); RETURN VALUE */ - #endif /* !COLLECTD_UTILS_MOUNT_H */ -