2 * collectd - src/common.c
3 * Copyright (C) 2005-2014 Florian octo Forster
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
24 * Florian octo Forster <octo at collectd.org>
25 * Niki W. Waibel <niki.waibel@gmx.net>
26 * Sebastian Harl <sh at tokkee.org>
27 * Michał Mirosław <mirq-linux at rere.qmqm.pl>
33 #include "utils/common/common.h"
34 #include "utils_cache.h"
38 #include <sys/types.h>
43 #include <netinet/in.h>
46 #if HAVE_NETINET_TCP_H
47 #include <netinet/tcp.h>
50 /* for ntohl and htonl */
52 #include <arpa/inet.h>
56 #include <sys/capability.h>
64 extern kstat_ctl_t *kc;
67 #if !defined(MSG_DONTWAIT)
68 #if defined(MSG_NONBLOCK)
69 /* AIX doesn't have MSG_DONTWAIT */
70 #define MSG_DONTWAIT MSG_NONBLOCK
72 /* Windows doesn't have MSG_DONTWAIT or MSG_NONBLOCK */
73 #define MSG_DONTWAIT 0
74 #endif /* defined(MSG_NONBLOCK) */
75 #endif /* !defined(MSG_DONTWAIT) */
77 #if !HAVE_GETPWNAM_R && defined(HAVE_GETPWNAM)
78 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
82 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
85 char *sstrncpy(char *dest, const char *src, size_t n) {
86 strncpy(dest, src, n);
90 } /* char *sstrncpy */
92 /* ssnprintf returns result from vsnprintf conistent with snprintf */
93 int ssnprintf(char *str, size_t sz, const char *format, ...) {
97 int ret = vsnprintf(str, sz, format, ap);
102 } /* int ssnprintf */
104 char *ssnprintf_alloc(char const *format, ...) /* {{{ */
106 char static_buffer[1024] = "";
108 size_t alloc_buffer_size;
112 /* Try printing into the static buffer. In many cases it will be
113 * sufficiently large and we can simply return a strdup() of this
115 va_start(ap, format);
116 status = vsnprintf(static_buffer, sizeof(static_buffer), format, ap);
121 /* "status" does not include the null byte. */
122 alloc_buffer_size = (size_t)(status + 1);
123 if (alloc_buffer_size <= sizeof(static_buffer))
124 return strdup(static_buffer);
126 /* Allocate a buffer large enough to hold the string. */
127 alloc_buffer = calloc(1, alloc_buffer_size);
128 if (alloc_buffer == NULL)
131 /* Print again into this new buffer. */
132 va_start(ap, format);
133 status = vsnprintf(alloc_buffer, alloc_buffer_size, format, ap);
141 } /* }}} char *ssnprintf_alloc */
143 char *sstrdup(const char *s) {
150 /* Do not use `strdup' here, because it's not specified in POSIX. It's
151 * ``only'' an XSI extension. */
155 ERROR("sstrdup: Out of memory.");
161 } /* char *sstrdup */
163 /* Even though Posix requires "strerror_r" to return an "int",
164 * some systems (e.g. the GNU libc) return a "char *" _and_
165 * ignore the second argument ... -tokkee */
166 char *sstrerror(int errnum, char *buf, size_t buflen) {
173 pthread_mutex_lock(&strerror_r_lock);
175 temp = strerror(errnum);
176 sstrncpy(buf, temp, buflen);
178 pthread_mutex_unlock(&strerror_r_lock);
180 /* #endif !HAVE_STRERROR_R */
182 #elif STRERROR_R_CHAR_P
185 temp = strerror_r(errnum, buf, buflen);
186 if (buf[0] == '\0') {
187 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
188 sstrncpy(buf, temp, buflen);
191 "strerror_r did not return "
196 /* #endif STRERROR_R_CHAR_P */
199 if (strerror_r(errnum, buf, buflen) != 0) {
200 snprintf(buf, buflen,
202 "Additionally, strerror_r failed.",
205 #endif /* STRERROR_R_CHAR_P */
208 } /* char *sstrerror */
210 void *smalloc(size_t size) {
213 if ((r = malloc(size)) == NULL) {
214 ERROR("Not enough memory.");
219 } /* void *smalloc */
222 void sfree (void **ptr)
234 int sread(int fd, void *buf, size_t count) {
243 status = read(fd, (void *)ptr, nleft);
245 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
252 DEBUG("Received EOF from fd %i. ", fd);
256 assert((0 > status) || (nleft >= (size_t)status));
258 nleft = nleft - ((size_t)status);
259 ptr = ptr + ((size_t)status);
265 int swrite(int fd, const void *buf, size_t count) {
271 ptr = (const char *)buf;
279 /* checking for closed peer connection */
281 pfd.events = POLLIN | POLLHUP;
283 if (poll(&pfd, 1, 0) > 0) {
285 if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
286 /* if recv returns zero (even though poll() said there is data to be
287 * read), that means the connection has been closed */
294 status = write(fd, (const void *)ptr, nleft);
296 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
300 return errno ? errno : status;
302 nleft = nleft - ((size_t)status);
303 ptr = ptr + ((size_t)status);
309 int strsplit(char *string, char **fields, size_t size) {
317 while ((fields[i] = strtok_r(ptr, " \t\r\n", &saveptr)) != NULL) {
328 int strjoin(char *buffer, size_t buffer_size, char **fields, size_t fields_num,
334 size_t buffer_req = 0;
336 if (((fields_num != 0) && (fields == NULL)) ||
337 ((buffer_size != 0) && (buffer == NULL)))
343 if (buffer_size != 0)
344 avail = buffer_size - 1;
347 sep_len = strlen(sep);
349 for (size_t i = 0; i < fields_num; i++) {
350 size_t field_len = strlen(fields[i]);
353 buffer_req += sep_len;
354 buffer_req += field_len;
356 if (buffer_size == 0)
359 if ((i != 0) && (sep_len > 0)) {
360 if (sep_len >= avail) {
361 /* prevent subsequent iterations from writing to the
367 memcpy(ptr, sep, sep_len);
373 if (field_len > avail)
376 memcpy(ptr, fields[i], field_len);
384 return (int)buffer_req;
387 int escape_string(char *buffer, size_t buffer_size) {
391 /* Check if we need to escape at all first */
392 temp = strpbrk(buffer, " \t\"\\");
399 temp = calloc(1, buffer_size);
406 for (size_t i = 0; i < buffer_size; i++) {
407 if (buffer[i] == 0) {
409 } else if ((buffer[i] == '"') || (buffer[i] == '\\')) {
410 if (j > (buffer_size - 4))
413 temp[j + 1] = buffer[i];
416 if (j > (buffer_size - 3))
423 assert((j + 1) < buffer_size);
427 sstrncpy(buffer, temp, buffer_size);
430 } /* int escape_string */
432 int strunescape(char *buf, size_t buf_len) {
433 for (size_t i = 0; (i < buf_len) && (buf[i] != '\0'); ++i) {
437 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
438 P_ERROR("string unescape: backslash found at end of string.");
439 /* Ensure null-byte at the end of the buffer. */
444 switch (buf[i + 1]) {
459 /* Move everything after the position one position to the left.
460 * Add a null-byte as last character in the buffer. */
461 memmove(buf + i + 1, buf + i + 2, buf_len - i - 2);
462 buf[buf_len - 1] = '\0';
465 } /* int strunescape */
467 size_t strstripnewline(char *buffer) {
468 size_t buffer_len = strlen(buffer);
470 while (buffer_len > 0) {
471 if ((buffer[buffer_len - 1] != '\n') && (buffer[buffer_len - 1] != '\r'))
474 buffer[buffer_len] = 0;
478 } /* size_t strstripnewline */
480 int escape_slashes(char *buffer, size_t buffer_size) {
483 buffer_len = strlen(buffer);
485 if (buffer_len <= 1) {
486 if (strcmp("/", buffer) == 0) {
489 sstrncpy(buffer, "root", buffer_size);
494 /* Move one to the left */
495 if (buffer[0] == '/') {
496 memmove(buffer, buffer + 1, buffer_len);
500 for (size_t i = 0; i < buffer_len; i++) {
501 if (buffer[i] == '/')
506 } /* int escape_slashes */
508 void replace_special(char *buffer, size_t buffer_size) {
509 for (size_t i = 0; i < buffer_size; i++) {
512 if ((!isalnum((int)buffer[i])) && (buffer[i] != '-'))
515 } /* void replace_special */
517 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta) {
518 struct timeval *larger;
519 struct timeval *smaller;
523 NORMALIZE_TIMEVAL(tv0);
524 NORMALIZE_TIMEVAL(tv1);
526 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec)) {
534 if ((tv0.tv_sec < tv1.tv_sec) ||
535 ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec))) {
546 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
548 if (smaller->tv_usec <= larger->tv_usec)
549 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
552 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
556 assert((delta == NULL) ||
557 ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
560 } /* int timeval_cmp */
562 int check_create_dir(const char *file_orig) {
565 char file_copy[PATH_MAX];
571 int last_is_file = 1;
572 int path_is_absolute = 0;
576 * Sanity checks first
578 if (file_orig == NULL)
581 if ((len = strlen(file_orig)) < 1)
583 else if (len >= sizeof(file_copy)) {
584 ERROR("check_create_dir: name (%s) is too long.", file_orig);
589 * If `file_orig' ends in a slash the last component is a directory,
590 * otherwise it's a file. Act accordingly..
592 if (file_orig[len - 1] == '/')
594 if (file_orig[0] == '/')
595 path_is_absolute = 1;
598 * Create a copy for `strtok_r' to destroy
600 sstrncpy(file_copy, file_orig, sizeof(file_copy));
603 * Break into components. This will eat up several slashes in a row and
604 * remove leading and trailing slashes..
609 while ((fields[fields_num] = strtok_r(ptr, "/", &saveptr)) != NULL) {
613 if (fields_num >= 16)
618 * For each component, do..
620 for (int i = 0; i < (fields_num - last_is_file); i++) {
622 * Do not create directories that start with a dot. This
623 * prevents `../../' attacks and other likely malicious
626 if (fields[i][0] == '.') {
627 P_ERROR("Cowardly refusing to create a directory that "
628 "begins with a `.' (dot): `%s'",
634 * Join the components together again
637 if (strjoin(dir + path_is_absolute,
638 (size_t)(sizeof(dir) - path_is_absolute), fields,
639 (size_t)(i + 1), "/") < 0) {
640 P_ERROR("strjoin failed: `%s', component #%i", file_orig, i);
645 if ((stat(dir, &statbuf) == -1) && (lstat(dir, &statbuf) == -1)) {
646 if (errno == ENOENT) {
647 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
650 /* this might happen, if a different thread created
651 * the directory in the meantime
652 * => call stat() again to check for S_ISDIR() */
656 P_ERROR("check_create_dir: mkdir (%s): %s", dir, STRERRNO);
659 P_ERROR("check_create_dir: stat (%s): %s", dir, STRERRNO);
662 } else if (!S_ISDIR(statbuf.st_mode)) {
663 P_ERROR("check_create_dir: `%s' exists but is not "
673 } /* check_create_dir */
676 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name) {
684 snprintf(ident, sizeof(ident), "%s,%i,%s", module, instance, name);
686 *ksp_ptr = kstat_lookup(kc, module, instance, name);
687 if (*ksp_ptr == NULL) {
688 P_ERROR("get_kstat: Cound not find kstat %s", ident);
692 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
693 P_ERROR("get_kstat: kstat %s has wrong type", ident);
699 assert(*ksp_ptr != NULL);
700 assert((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
703 if (kstat_read(kc, *ksp_ptr, NULL) == -1) {
704 P_ERROR("get_kstat: kstat %s could not be read", ident);
708 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
709 P_ERROR("get_kstat: kstat %s has wrong type", ident);
716 long long get_kstat_value(kstat_t *ksp, char *name) {
718 long long retval = -1LL;
721 P_ERROR("get_kstat_value (\"%s\"): ksp is NULL.", name);
723 } else if (ksp->ks_type != KSTAT_TYPE_NAMED) {
724 P_ERROR("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
725 "is not KSTAT_TYPE_NAMED (%#x).",
726 name, (unsigned int)ksp->ks_type, (unsigned int)KSTAT_TYPE_NAMED);
730 if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, name)) == NULL)
733 if (kn->data_type == KSTAT_DATA_INT32)
734 retval = (long long)kn->value.i32;
735 else if (kn->data_type == KSTAT_DATA_UINT32)
736 retval = (long long)kn->value.ui32;
737 else if (kn->data_type == KSTAT_DATA_INT64)
738 retval = (long long)kn->value.i64; /* According to ANSI C99 `long long' must
739 hold at least 64 bits */
740 else if (kn->data_type == KSTAT_DATA_UINT64)
741 retval = (long long)kn->value.ui64; /* XXX: Might overflow! */
743 P_WARNING("get_kstat_value: Not a numeric value: %s", name);
747 #endif /* HAVE_LIBKSTAT */
750 unsigned long long ntohll(unsigned long long n) {
751 #if BYTE_ORDER == BIG_ENDIAN
754 return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
756 } /* unsigned long long ntohll */
758 unsigned long long htonll(unsigned long long n) {
759 #if BYTE_ORDER == BIG_ENDIAN
762 return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
764 } /* unsigned long long htonll */
765 #endif /* HAVE_HTONLL */
767 #if FP_LAYOUT_NEED_NOTHING
768 /* Well, we need nothing.. */
769 /* #endif FP_LAYOUT_NEED_NOTHING */
771 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
772 #if FP_LAYOUT_NEED_ENDIANFLIP
773 #define FP_CONVERT(A) \
774 ((((uint64_t)(A)&0xff00000000000000LL) >> 56) | \
775 (((uint64_t)(A)&0x00ff000000000000LL) >> 40) | \
776 (((uint64_t)(A)&0x0000ff0000000000LL) >> 24) | \
777 (((uint64_t)(A)&0x000000ff00000000LL) >> 8) | \
778 (((uint64_t)(A)&0x00000000ff000000LL) << 8) | \
779 (((uint64_t)(A)&0x0000000000ff0000LL) << 24) | \
780 (((uint64_t)(A)&0x000000000000ff00LL) << 40) | \
781 (((uint64_t)(A)&0x00000000000000ffLL) << 56))
783 #define FP_CONVERT(A) \
784 ((((uint64_t)(A)&0xffffffff00000000LL) >> 32) | \
785 (((uint64_t)(A)&0x00000000ffffffffLL) << 32))
788 double ntohd(double d) {
797 /* NAN in x86 byte order */
798 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00) && (ret.byte[2] == 0x00) &&
799 (ret.byte[3] == 0x00) && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00) &&
800 (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f)) {
806 ret.integer = FP_CONVERT(tmp);
811 double htond(double d) {
819 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
820 ret.byte[4] = ret.byte[5] = 0x00;
828 tmp = FP_CONVERT(ret.integer);
833 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
835 int format_name(char *ret, int ret_len, const char *hostname,
836 const char *plugin, const char *plugin_instance,
837 const char *type, const char *type_instance) {
842 buffer_size = (size_t)ret_len;
844 #define APPEND(str) \
846 size_t l = strlen(str); \
847 if (l >= buffer_size) \
849 memcpy(buffer, (str), l); \
854 assert(plugin != NULL);
855 assert(type != NULL);
860 if ((plugin_instance != NULL) && (plugin_instance[0] != 0)) {
862 APPEND(plugin_instance);
866 if ((type_instance != NULL) && (type_instance[0] != 0)) {
868 APPEND(type_instance);
870 assert(buffer_size > 0);
875 } /* int format_name */
877 int format_values(char *ret, size_t ret_len, /* {{{ */
878 const data_set_t *ds, const value_list_t *vl,
882 gauge_t *rates = NULL;
884 assert(0 == strcmp(ds->type, vl->type));
886 memset(ret, 0, ret_len);
888 #define BUFFER_ADD(...) \
890 status = snprintf(ret + offset, ret_len - offset, __VA_ARGS__); \
894 } else if (((size_t)status) >= (ret_len - offset)) { \
898 offset += ((size_t)status); \
901 BUFFER_ADD("%.3f", CDTIME_T_TO_DOUBLE(vl->time));
903 for (size_t i = 0; i < ds->ds_num; i++) {
904 if (ds->ds[i].type == DS_TYPE_GAUGE)
905 BUFFER_ADD(":" GAUGE_FORMAT, vl->values[i].gauge);
906 else if (store_rates) {
908 rates = uc_get_rate(ds, vl);
910 WARNING("format_values: uc_get_rate failed.");
913 BUFFER_ADD(":" GAUGE_FORMAT, rates[i]);
914 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
915 BUFFER_ADD(":%" PRIu64, (uint64_t)vl->values[i].counter);
916 else if (ds->ds[i].type == DS_TYPE_DERIVE)
917 BUFFER_ADD(":%" PRIi64, vl->values[i].derive);
918 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
919 BUFFER_ADD(":%" PRIu64, vl->values[i].absolute);
921 ERROR("format_values: Unknown data source type: %i", ds->ds[i].type);
925 } /* for ds->ds_num */
931 } /* }}} int format_values */
933 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
934 char **ret_plugin_instance, char **ret_type,
935 char **ret_type_instance, char *default_host) {
936 char *hostname = NULL;
938 char *plugin_instance = NULL;
940 char *type_instance = NULL;
943 if (hostname == NULL)
946 plugin = strchr(hostname, '/');
952 type = strchr(plugin, '/');
954 if (default_host == NULL)
956 /* else: no host specified; use default */
959 hostname = default_host;
965 plugin_instance = strchr(plugin, '-');
966 if (plugin_instance != NULL) {
967 *plugin_instance = '\0';
971 type_instance = strchr(type, '-');
972 if (type_instance != NULL) {
973 *type_instance = '\0';
977 *ret_host = hostname;
978 *ret_plugin = plugin;
979 *ret_plugin_instance = plugin_instance;
981 *ret_type_instance = type_instance;
983 } /* int parse_identifier */
985 int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
987 char str_copy[6 * DATA_MAX_NAME_LEN];
990 char *plugin_instance = NULL;
992 char *type_instance = NULL;
995 if ((str == NULL) || (vl == NULL))
998 sstrncpy(str_copy, str, sizeof(str_copy));
1000 status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
1002 /* default_host = */ NULL);
1006 sstrncpy(vl->host, host, sizeof(vl->host));
1007 sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
1008 sstrncpy(vl->plugin_instance,
1009 (plugin_instance != NULL) ? plugin_instance : "",
1010 sizeof(vl->plugin_instance));
1011 sstrncpy(vl->type, type, sizeof(vl->type));
1012 sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
1013 sizeof(vl->type_instance));
1016 } /* }}} int parse_identifier_vl */
1018 int parse_value(const char *value_orig, value_t *ret_value, int ds_type) {
1020 char *endptr = NULL;
1023 if (value_orig == NULL)
1026 value = strdup(value_orig);
1029 value_len = strlen(value);
1031 while ((value_len > 0) && isspace((int)value[value_len - 1])) {
1032 value[value_len - 1] = '\0';
1037 case DS_TYPE_COUNTER:
1038 ret_value->counter = (counter_t)strtoull(value, &endptr, 0);
1042 ret_value->gauge = (gauge_t)strtod(value, &endptr);
1045 case DS_TYPE_DERIVE:
1046 ret_value->derive = (derive_t)strtoll(value, &endptr, 0);
1049 case DS_TYPE_ABSOLUTE:
1050 ret_value->absolute = (absolute_t)strtoull(value, &endptr, 0);
1055 P_ERROR("parse_value: Invalid data source type: %i.", ds_type);
1059 if (value == endptr) {
1060 P_ERROR("parse_value: Failed to parse string as %s: \"%s\".",
1061 DS_TYPE_TO_STRING(ds_type), value);
1064 } else if ((NULL != endptr) && ('\0' != *endptr))
1065 P_INFO("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1066 "Input string was \"%s\".",
1067 endptr, DS_TYPE_TO_STRING(ds_type), value_orig);
1071 } /* int parse_value */
1073 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds) {
1079 if ((buffer == NULL) || (vl == NULL) || (ds == NULL))
1086 while ((ptr = strtok_r(dummy, ":", &saveptr)) != NULL) {
1089 if (i >= vl->values_len) {
1090 /* Make sure i is invalid. */
1095 if (vl->time == 0) {
1096 if (strcmp("N", ptr) == 0)
1097 vl->time = cdtime();
1099 char *endptr = NULL;
1103 tmp = strtod(ptr, &endptr);
1104 if ((errno != 0) /* Overflow */
1105 || (endptr == ptr) /* Invalid string */
1106 || (endptr == NULL) /* This should not happen */
1107 || (*endptr != 0)) /* Trailing chars */
1110 vl->time = DOUBLE_TO_CDTIME_T(tmp);
1116 if ((strcmp("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1117 vl->values[i].gauge = NAN;
1118 else if (0 != parse_value(ptr, &vl->values[i], ds->ds[i].type))
1122 } /* while (strtok_r) */
1124 if ((ptr != NULL) || (i == 0))
1127 } /* int parse_values */
1129 int parse_value_file(char const *path, value_t *ret_value, int ds_type) {
1133 fh = fopen(path, "r");
1137 if (fgets(buffer, sizeof(buffer), fh) == NULL) {
1144 strstripnewline(buffer);
1146 return parse_value(buffer, ret_value, ds_type);
1147 } /* int parse_value_file */
1149 #if !HAVE_GETPWNAM_R
1150 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
1151 struct passwd **pwbufp) {
1152 #ifndef HAVE_GETPWNAM
1158 memset(pwbuf, '\0', sizeof(struct passwd));
1160 pthread_mutex_lock(&getpwnam_r_lock);
1163 pw = getpwnam(name);
1165 status = (errno != 0) ? errno : ENOENT;
1169 #define GETPWNAM_COPY_MEMBER(member) \
1170 if (pw->member != NULL) { \
1171 int len = strlen(pw->member); \
1172 if (len >= buflen) { \
1176 sstrncpy(buf, pw->member, buflen); \
1177 pwbuf->member = buf; \
1179 buflen -= (len + 1); \
1181 GETPWNAM_COPY_MEMBER(pw_name);
1182 GETPWNAM_COPY_MEMBER(pw_passwd);
1183 GETPWNAM_COPY_MEMBER(pw_gecos);
1184 GETPWNAM_COPY_MEMBER(pw_dir);
1185 GETPWNAM_COPY_MEMBER(pw_shell);
1187 pwbuf->pw_uid = pw->pw_uid;
1188 pwbuf->pw_gid = pw->pw_gid;
1194 pthread_mutex_unlock(&getpwnam_r_lock);
1197 #endif /* HAVE_GETPWNAM */
1198 } /* int getpwnam_r */
1199 #endif /* !HAVE_GETPWNAM_R */
1201 int notification_init(notification_t *n, int severity, const char *message,
1202 const char *host, const char *plugin,
1203 const char *plugin_instance, const char *type,
1204 const char *type_instance) {
1205 memset(n, '\0', sizeof(notification_t));
1207 n->severity = severity;
1209 if (message != NULL)
1210 sstrncpy(n->message, message, sizeof(n->message));
1212 sstrncpy(n->host, host, sizeof(n->host));
1214 sstrncpy(n->plugin, plugin, sizeof(n->plugin));
1215 if (plugin_instance != NULL)
1216 sstrncpy(n->plugin_instance, plugin_instance, sizeof(n->plugin_instance));
1218 sstrncpy(n->type, type, sizeof(n->type));
1219 if (type_instance != NULL)
1220 sstrncpy(n->type_instance, type_instance, sizeof(n->type_instance));
1223 } /* int notification_init */
1225 int walk_directory(const char *dir, dirwalk_callback_f callback,
1226 void *user_data, int include_hidden) {
1235 if ((dh = opendir(dir)) == NULL) {
1236 P_ERROR("walk_directory: Cannot open '%s': %s", dir, STRERRNO);
1240 while ((ent = readdir(dh)) != NULL) {
1243 if (include_hidden) {
1244 if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0))
1246 } else /* if (!include_hidden) */
1248 if (ent->d_name[0] == '.')
1252 status = (*callback)(dir, ent->d_name, user_data);
1261 if ((success == 0) && (failure > 0))
1266 ssize_t read_file_contents(const char *filename, char *buf, size_t bufsize) {
1270 fh = fopen(filename, "r");
1274 ret = (ssize_t)fread(buf, 1, bufsize, fh);
1275 if ((ret == 0) && (ferror(fh) != 0)) {
1276 P_ERROR("read_file_contents: Reading file \"%s\" failed.", filename);
1284 counter_t counter_diff(counter_t old_value, counter_t new_value) {
1287 if (old_value > new_value) {
1288 if (old_value <= 4294967295U)
1289 diff = (4294967295U - old_value) + new_value + 1;
1291 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1293 diff = new_value - old_value;
1297 } /* counter_t counter_diff */
1299 int rate_to_value(value_t *ret_value, gauge_t rate, /* {{{ */
1300 rate_to_value_state_t *state, int ds_type, cdtime_t t) {
1301 gauge_t delta_gauge;
1304 if (ds_type == DS_TYPE_GAUGE) {
1305 state->last_value.gauge = rate;
1306 state->last_time = t;
1308 *ret_value = state->last_value;
1312 /* Counter and absolute can't handle negative rates. Reset "last time"
1313 * to zero, so that the next valid rate will re-initialize the
1316 ((ds_type == DS_TYPE_COUNTER) || (ds_type == DS_TYPE_ABSOLUTE))) {
1317 memset(state, 0, sizeof(*state));
1321 /* Another invalid state: The time is not increasing. */
1322 if (t <= state->last_time) {
1323 memset(state, 0, sizeof(*state));
1327 delta_t = t - state->last_time;
1328 delta_gauge = (rate * CDTIME_T_TO_DOUBLE(delta_t)) + state->residual;
1330 /* Previous value is invalid. */
1331 if (state->last_time == 0) /* {{{ */
1333 if (ds_type == DS_TYPE_DERIVE) {
1334 state->last_value.derive = (derive_t)rate;
1335 state->residual = rate - ((gauge_t)state->last_value.derive);
1336 } else if (ds_type == DS_TYPE_COUNTER) {
1337 state->last_value.counter = (counter_t)rate;
1338 state->residual = rate - ((gauge_t)state->last_value.counter);
1339 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1340 state->last_value.absolute = (absolute_t)rate;
1341 state->residual = rate - ((gauge_t)state->last_value.absolute);
1346 state->last_time = t;
1350 if (ds_type == DS_TYPE_DERIVE) {
1351 derive_t delta_derive = (derive_t)delta_gauge;
1353 state->last_value.derive += delta_derive;
1354 state->residual = delta_gauge - ((gauge_t)delta_derive);
1355 } else if (ds_type == DS_TYPE_COUNTER) {
1356 counter_t delta_counter = (counter_t)delta_gauge;
1358 state->last_value.counter += delta_counter;
1359 state->residual = delta_gauge - ((gauge_t)delta_counter);
1360 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1361 absolute_t delta_absolute = (absolute_t)delta_gauge;
1363 state->last_value.absolute = delta_absolute;
1364 state->residual = delta_gauge - ((gauge_t)delta_absolute);
1369 state->last_time = t;
1370 *ret_value = state->last_value;
1372 } /* }}} value_t rate_to_value */
1374 int value_to_rate(gauge_t *ret_rate, /* {{{ */
1375 value_t value, int ds_type, cdtime_t t,
1376 value_to_rate_state_t *state) {
1379 /* Another invalid state: The time is not increasing. */
1380 if (t <= state->last_time) {
1381 memset(state, 0, sizeof(*state));
1385 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1387 /* Previous value is invalid. */
1388 if (state->last_time == 0) {
1389 state->last_value = value;
1390 state->last_time = t;
1395 case DS_TYPE_DERIVE: {
1396 derive_t diff = value.derive - state->last_value.derive;
1397 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1400 case DS_TYPE_GAUGE: {
1401 *ret_rate = value.gauge;
1404 case DS_TYPE_COUNTER: {
1405 counter_t diff = counter_diff(state->last_value.counter, value.counter);
1406 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1409 case DS_TYPE_ABSOLUTE: {
1410 absolute_t diff = value.absolute;
1411 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1418 state->last_value = value;
1419 state->last_time = t;
1421 } /* }}} value_t rate_to_value */
1423 int service_name_to_port_number(const char *service_name) {
1424 struct addrinfo *ai_list;
1428 if (service_name == NULL)
1431 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC};
1433 status = getaddrinfo(/* node = */ NULL, service_name, &ai_hints, &ai_list);
1435 P_ERROR("service_name_to_port_number: getaddrinfo failed: %s",
1436 gai_strerror(status));
1440 service_number = -1;
1441 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1442 ai_ptr = ai_ptr->ai_next) {
1443 if (ai_ptr->ai_family == AF_INET) {
1444 struct sockaddr_in *sa;
1446 sa = (void *)ai_ptr->ai_addr;
1447 service_number = (int)ntohs(sa->sin_port);
1448 } else if (ai_ptr->ai_family == AF_INET6) {
1449 struct sockaddr_in6 *sa;
1451 sa = (void *)ai_ptr->ai_addr;
1452 service_number = (int)ntohs(sa->sin6_port);
1455 if (service_number > 0)
1459 freeaddrinfo(ai_list);
1461 if (service_number > 0)
1462 return service_number;
1464 } /* int service_name_to_port_number */
1466 void set_sock_opts(int sockfd) /* {{{ */
1471 status = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &socktype,
1472 &(socklen_t){sizeof(socktype)});
1474 P_WARNING("set_sock_opts: failed to determine socket type");
1478 if (socktype == SOCK_STREAM) {
1480 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int));
1482 P_WARNING("set_sock_opts: failed to set socket keepalive flag");
1485 int tcp_keepidle = ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 100 + 1);
1486 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &tcp_keepidle,
1487 sizeof(tcp_keepidle));
1489 P_WARNING("set_sock_opts: failed to set socket tcp keepalive time");
1492 #ifdef TCP_KEEPINTVL
1494 ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 1000 + 1);
1495 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &tcp_keepintvl,
1496 sizeof(tcp_keepintvl));
1498 P_WARNING("set_sock_opts: failed to set socket tcp keepalive interval");
1501 } /* }}} void set_sock_opts */
1503 int strtoderive(const char *string, derive_t *ret_value) /* {{{ */
1508 if ((string == NULL) || (ret_value == NULL))
1513 tmp = (derive_t)strtoll(string, &endptr, /* base = */ 0);
1514 if ((endptr == string) || (errno != 0))
1519 } /* }}} int strtoderive */
1521 int strtogauge(const char *string, gauge_t *ret_value) /* {{{ */
1524 char *endptr = NULL;
1526 if ((string == NULL) || (ret_value == NULL))
1531 tmp = (gauge_t)strtod(string, &endptr);
1534 else if ((endptr == NULL) || (*endptr != 0))
1539 } /* }}} int strtogauge */
1541 int strarray_add(char ***ret_array, size_t *ret_array_len,
1542 char const *str) /* {{{ */
1545 size_t array_len = *ret_array_len;
1550 array = realloc(*ret_array, (array_len + 1) * sizeof(*array));
1555 array[array_len] = strdup(str);
1556 if (array[array_len] == NULL)
1560 *ret_array_len = array_len;
1562 } /* }}} int strarray_add */
1564 void strarray_free(char **array, size_t array_len) /* {{{ */
1566 for (size_t i = 0; i < array_len; i++)
1569 } /* }}} void strarray_free */
1572 int check_capability(int arg) /* {{{ */
1574 cap_value_t cap_value = (cap_value_t)arg;
1576 cap_flag_value_t cap_flag_value;
1578 if (!CAP_IS_SUPPORTED(cap_value))
1581 if (!(cap = cap_get_proc())) {
1582 P_ERROR("check_capability: cap_get_proc failed.");
1586 if (cap_get_flag(cap, cap_value, CAP_EFFECTIVE, &cap_flag_value) < 0) {
1587 P_ERROR("check_capability: cap_get_flag failed.");
1593 return cap_flag_value != CAP_SET;
1594 } /* }}} int check_capability */
1596 int check_capability(__attribute__((unused)) int arg) /* {{{ */
1598 P_WARNING("check_capability: unsupported capability implementation. "
1599 "Some plugin(s) may require elevated privileges to work properly.");
1601 } /* }}} int check_capability */
1602 #endif /* HAVE_CAPABILITY */