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 /* ssnprintf2 returns zero on success, one if truncation occurred
105 and a negative integer on error. */
106 int ssnprintf2(char *str, size_t sz, const char *format, ...) {
108 va_start(ap, format);
110 int ret = vsnprintf(str, sz, format, ap);
117 return (size_t)ret >= sz;
118 } /* int ssnprintf2 */
120 char *ssnprintf_alloc(char const *format, ...) /* {{{ */
122 char static_buffer[1024] = "";
124 size_t alloc_buffer_size;
128 /* Try printing into the static buffer. In many cases it will be
129 * sufficiently large and we can simply return a strdup() of this
131 va_start(ap, format);
132 status = vsnprintf(static_buffer, sizeof(static_buffer), format, ap);
137 /* "status" does not include the null byte. */
138 alloc_buffer_size = (size_t)(status + 1);
139 if (alloc_buffer_size <= sizeof(static_buffer))
140 return strdup(static_buffer);
142 /* Allocate a buffer large enough to hold the string. */
143 alloc_buffer = calloc(1, alloc_buffer_size);
144 if (alloc_buffer == NULL)
147 /* Print again into this new buffer. */
148 va_start(ap, format);
149 status = vsnprintf(alloc_buffer, alloc_buffer_size, format, ap);
157 } /* }}} char *ssnprintf_alloc */
159 char *sstrdup(const char *s) {
166 /* Do not use `strdup' here, because it's not specified in POSIX. It's
167 * ``only'' an XSI extension. */
171 ERROR("sstrdup: Out of memory.");
177 } /* char *sstrdup */
179 /* Even though Posix requires "strerror_r" to return an "int",
180 * some systems (e.g. the GNU libc) return a "char *" _and_
181 * ignore the second argument ... -tokkee */
182 char *sstrerror(int errnum, char *buf, size_t buflen) {
189 pthread_mutex_lock(&strerror_r_lock);
191 temp = strerror(errnum);
192 sstrncpy(buf, temp, buflen);
194 pthread_mutex_unlock(&strerror_r_lock);
196 /* #endif !HAVE_STRERROR_R */
198 #elif STRERROR_R_CHAR_P
201 temp = strerror_r(errnum, buf, buflen);
202 if (buf[0] == '\0') {
203 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
204 sstrncpy(buf, temp, buflen);
207 "strerror_r did not return "
212 /* #endif STRERROR_R_CHAR_P */
215 if (strerror_r(errnum, buf, buflen) != 0) {
216 snprintf(buf, buflen,
218 "Additionally, strerror_r failed.",
221 #endif /* STRERROR_R_CHAR_P */
224 } /* char *sstrerror */
226 void *smalloc(size_t size) {
229 if ((r = malloc(size)) == NULL) {
230 ERROR("Not enough memory.");
235 } /* void *smalloc */
238 void sfree (void **ptr)
250 int sread(int fd, void *buf, size_t count) {
259 status = read(fd, (void *)ptr, nleft);
261 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
268 DEBUG("Received EOF from fd %i. ", fd);
272 assert((0 > status) || (nleft >= (size_t)status));
274 nleft = nleft - ((size_t)status);
275 ptr = ptr + ((size_t)status);
281 int swrite(int fd, const void *buf, size_t count) {
287 ptr = (const char *)buf;
295 /* checking for closed peer connection */
297 pfd.events = POLLIN | POLLHUP;
299 if (poll(&pfd, 1, 0) > 0) {
301 if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
302 /* if recv returns zero (even though poll() said there is data to be
303 * read), that means the connection has been closed */
310 status = write(fd, (const void *)ptr, nleft);
312 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
316 return errno ? errno : status;
318 nleft = nleft - ((size_t)status);
319 ptr = ptr + ((size_t)status);
325 int strsplit(char *string, char **fields, size_t size) {
333 while ((fields[i] = strtok_r(ptr, " \t\r\n", &saveptr)) != NULL) {
344 int strjoin(char *buffer, size_t buffer_size, char **fields, size_t fields_num,
350 size_t buffer_req = 0;
352 if (((fields_num != 0) && (fields == NULL)) ||
353 ((buffer_size != 0) && (buffer == NULL)))
359 if (buffer_size != 0)
360 avail = buffer_size - 1;
363 sep_len = strlen(sep);
365 for (size_t i = 0; i < fields_num; i++) {
366 size_t field_len = strlen(fields[i]);
369 buffer_req += sep_len;
370 buffer_req += field_len;
372 if (buffer_size == 0)
375 if ((i != 0) && (sep_len > 0)) {
376 if (sep_len >= avail) {
377 /* prevent subsequent iterations from writing to the
383 memcpy(ptr, sep, sep_len);
389 if (field_len > avail)
392 memcpy(ptr, fields[i], field_len);
400 return (int)buffer_req;
403 int escape_string(char *buffer, size_t buffer_size) {
407 /* Check if we need to escape at all first */
408 temp = strpbrk(buffer, " \t\"\\");
415 temp = calloc(1, buffer_size);
422 for (size_t i = 0; i < buffer_size; i++) {
423 if (buffer[i] == 0) {
425 } else if ((buffer[i] == '"') || (buffer[i] == '\\')) {
426 if (j > (buffer_size - 4))
429 temp[j + 1] = buffer[i];
432 if (j > (buffer_size - 3))
439 assert((j + 1) < buffer_size);
443 sstrncpy(buffer, temp, buffer_size);
446 } /* int escape_string */
448 int strunescape(char *buf, size_t buf_len) {
449 for (size_t i = 0; (i < buf_len) && (buf[i] != '\0'); ++i) {
453 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
454 P_ERROR("string unescape: backslash found at end of string.");
455 /* Ensure null-byte at the end of the buffer. */
460 switch (buf[i + 1]) {
475 /* Move everything after the position one position to the left.
476 * Add a null-byte as last character in the buffer. */
477 memmove(buf + i + 1, buf + i + 2, buf_len - i - 2);
478 buf[buf_len - 1] = '\0';
481 } /* int strunescape */
483 size_t strstripnewline(char *buffer) {
484 size_t buffer_len = strlen(buffer);
486 while (buffer_len > 0) {
487 if ((buffer[buffer_len - 1] != '\n') && (buffer[buffer_len - 1] != '\r'))
490 buffer[buffer_len] = 0;
494 } /* size_t strstripnewline */
496 int escape_slashes(char *buffer, size_t buffer_size) {
499 buffer_len = strlen(buffer);
501 if (buffer_len <= 1) {
502 if (strcmp("/", buffer) == 0) {
505 sstrncpy(buffer, "root", buffer_size);
510 /* Move one to the left */
511 if (buffer[0] == '/') {
512 memmove(buffer, buffer + 1, buffer_len);
516 for (size_t i = 0; i < buffer_len; i++) {
517 if (buffer[i] == '/')
522 } /* int escape_slashes */
524 void replace_special(char *buffer, size_t buffer_size) {
525 for (size_t i = 0; i < buffer_size; i++) {
528 if ((!isalnum((int)buffer[i])) && (buffer[i] != '-'))
531 } /* void replace_special */
533 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta) {
534 struct timeval *larger;
535 struct timeval *smaller;
539 NORMALIZE_TIMEVAL(tv0);
540 NORMALIZE_TIMEVAL(tv1);
542 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec)) {
550 if ((tv0.tv_sec < tv1.tv_sec) ||
551 ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec))) {
562 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
564 if (smaller->tv_usec <= larger->tv_usec)
565 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
568 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
572 assert((delta == NULL) ||
573 ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
576 } /* int timeval_cmp */
578 int check_create_dir(const char *file_orig) {
581 char file_copy[PATH_MAX];
587 int last_is_file = 1;
588 int path_is_absolute = 0;
592 * Sanity checks first
594 if (file_orig == NULL)
597 if ((len = strlen(file_orig)) < 1)
599 else if (len >= sizeof(file_copy)) {
600 ERROR("check_create_dir: name (%s) is too long.", file_orig);
605 * If `file_orig' ends in a slash the last component is a directory,
606 * otherwise it's a file. Act accordingly..
608 if (file_orig[len - 1] == '/')
610 if (file_orig[0] == '/')
611 path_is_absolute = 1;
614 * Create a copy for `strtok_r' to destroy
616 sstrncpy(file_copy, file_orig, sizeof(file_copy));
619 * Break into components. This will eat up several slashes in a row and
620 * remove leading and trailing slashes..
625 while ((fields[fields_num] = strtok_r(ptr, "/", &saveptr)) != NULL) {
629 if (fields_num >= 16)
634 * For each component, do..
636 for (int i = 0; i < (fields_num - last_is_file); i++) {
638 * Do not create directories that start with a dot. This
639 * prevents `../../' attacks and other likely malicious
642 if (fields[i][0] == '.') {
643 P_ERROR("Cowardly refusing to create a directory that "
644 "begins with a `.' (dot): `%s'",
650 * Join the components together again
653 if (strjoin(dir + path_is_absolute,
654 (size_t)(sizeof(dir) - path_is_absolute), fields,
655 (size_t)(i + 1), "/") < 0) {
656 P_ERROR("strjoin failed: `%s', component #%i", file_orig, i);
661 if ((stat(dir, &statbuf) == -1) && (lstat(dir, &statbuf) == -1)) {
662 if (errno == ENOENT) {
663 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
666 /* this might happen, if a different thread created
667 * the directory in the meantime
668 * => call stat() again to check for S_ISDIR() */
672 P_ERROR("check_create_dir: mkdir (%s): %s", dir, STRERRNO);
675 P_ERROR("check_create_dir: stat (%s): %s", dir, STRERRNO);
678 } else if (!S_ISDIR(statbuf.st_mode)) {
679 P_ERROR("check_create_dir: `%s' exists but is not "
689 } /* check_create_dir */
692 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name) {
700 snprintf(ident, sizeof(ident), "%s,%i,%s", module, instance, name);
702 *ksp_ptr = kstat_lookup(kc, module, instance, name);
703 if (*ksp_ptr == NULL) {
704 P_ERROR("get_kstat: Cound not find kstat %s", ident);
708 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
709 P_ERROR("get_kstat: kstat %s has wrong type", ident);
715 assert(*ksp_ptr != NULL);
716 assert((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
719 if (kstat_read(kc, *ksp_ptr, NULL) == -1) {
720 P_ERROR("get_kstat: kstat %s could not be read", ident);
724 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
725 P_ERROR("get_kstat: kstat %s has wrong type", ident);
732 long long get_kstat_value(kstat_t *ksp, char *name) {
734 long long retval = -1LL;
737 P_ERROR("get_kstat_value (\"%s\"): ksp is NULL.", name);
739 } else if (ksp->ks_type != KSTAT_TYPE_NAMED) {
740 P_ERROR("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
741 "is not KSTAT_TYPE_NAMED (%#x).",
742 name, (unsigned int)ksp->ks_type, (unsigned int)KSTAT_TYPE_NAMED);
746 if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, name)) == NULL)
749 if (kn->data_type == KSTAT_DATA_INT32)
750 retval = (long long)kn->value.i32;
751 else if (kn->data_type == KSTAT_DATA_UINT32)
752 retval = (long long)kn->value.ui32;
753 else if (kn->data_type == KSTAT_DATA_INT64)
754 retval = (long long)kn->value.i64; /* According to ANSI C99 `long long' must
755 hold at least 64 bits */
756 else if (kn->data_type == KSTAT_DATA_UINT64)
757 retval = (long long)kn->value.ui64; /* XXX: Might overflow! */
759 P_WARNING("get_kstat_value: Not a numeric value: %s", name);
763 #endif /* HAVE_LIBKSTAT */
766 unsigned long long ntohll(unsigned long long n) {
767 #if BYTE_ORDER == BIG_ENDIAN
770 return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
772 } /* unsigned long long ntohll */
774 unsigned long long htonll(unsigned long long n) {
775 #if BYTE_ORDER == BIG_ENDIAN
778 return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
780 } /* unsigned long long htonll */
781 #endif /* HAVE_HTONLL */
783 #if FP_LAYOUT_NEED_NOTHING
784 /* Well, we need nothing.. */
785 /* #endif FP_LAYOUT_NEED_NOTHING */
787 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
788 #if FP_LAYOUT_NEED_ENDIANFLIP
789 #define FP_CONVERT(A) \
790 ((((uint64_t)(A)&0xff00000000000000LL) >> 56) | \
791 (((uint64_t)(A)&0x00ff000000000000LL) >> 40) | \
792 (((uint64_t)(A)&0x0000ff0000000000LL) >> 24) | \
793 (((uint64_t)(A)&0x000000ff00000000LL) >> 8) | \
794 (((uint64_t)(A)&0x00000000ff000000LL) << 8) | \
795 (((uint64_t)(A)&0x0000000000ff0000LL) << 24) | \
796 (((uint64_t)(A)&0x000000000000ff00LL) << 40) | \
797 (((uint64_t)(A)&0x00000000000000ffLL) << 56))
799 #define FP_CONVERT(A) \
800 ((((uint64_t)(A)&0xffffffff00000000LL) >> 32) | \
801 (((uint64_t)(A)&0x00000000ffffffffLL) << 32))
804 double ntohd(double d) {
813 /* NAN in x86 byte order */
814 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00) && (ret.byte[2] == 0x00) &&
815 (ret.byte[3] == 0x00) && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00) &&
816 (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f)) {
822 ret.integer = FP_CONVERT(tmp);
827 double htond(double d) {
835 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
836 ret.byte[4] = ret.byte[5] = 0x00;
844 tmp = FP_CONVERT(ret.integer);
849 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
851 int format_name(char *ret, int ret_len, const char *hostname,
852 const char *plugin, const char *plugin_instance,
853 const char *type, const char *type_instance) {
858 buffer_size = (size_t)ret_len;
860 #define APPEND(str) \
862 size_t l = strlen(str); \
863 if (l >= buffer_size) \
865 memcpy(buffer, (str), l); \
870 assert(plugin != NULL);
871 assert(type != NULL);
876 if ((plugin_instance != NULL) && (plugin_instance[0] != 0)) {
878 APPEND(plugin_instance);
882 if ((type_instance != NULL) && (type_instance[0] != 0)) {
884 APPEND(type_instance);
886 assert(buffer_size > 0);
891 } /* int format_name */
893 int format_values(char *ret, size_t ret_len, /* {{{ */
894 const data_set_t *ds, const value_list_t *vl,
898 gauge_t *rates = NULL;
900 assert(0 == strcmp(ds->type, vl->type));
902 memset(ret, 0, ret_len);
904 #define BUFFER_ADD(...) \
906 status = snprintf(ret + offset, ret_len - offset, __VA_ARGS__); \
910 } else if (((size_t)status) >= (ret_len - offset)) { \
914 offset += ((size_t)status); \
917 BUFFER_ADD("%.3f", CDTIME_T_TO_DOUBLE(vl->time));
919 for (size_t i = 0; i < ds->ds_num; i++) {
920 if (ds->ds[i].type == DS_TYPE_GAUGE)
921 BUFFER_ADD(":" GAUGE_FORMAT, vl->values[i].gauge);
922 else if (store_rates) {
924 rates = uc_get_rate(ds, vl);
926 WARNING("format_values: uc_get_rate failed.");
929 BUFFER_ADD(":" GAUGE_FORMAT, rates[i]);
930 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
931 BUFFER_ADD(":%" PRIu64, (uint64_t)vl->values[i].counter);
932 else if (ds->ds[i].type == DS_TYPE_DERIVE)
933 BUFFER_ADD(":%" PRIi64, vl->values[i].derive);
934 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
935 BUFFER_ADD(":%" PRIu64, vl->values[i].absolute);
937 ERROR("format_values: Unknown data source type: %i", ds->ds[i].type);
941 } /* for ds->ds_num */
947 } /* }}} int format_values */
949 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
950 char **ret_plugin_instance, char **ret_type,
951 char **ret_type_instance, char *default_host) {
952 char *hostname = NULL;
954 char *plugin_instance = NULL;
956 char *type_instance = NULL;
959 if (hostname == NULL)
962 plugin = strchr(hostname, '/');
968 type = strchr(plugin, '/');
970 if (default_host == NULL)
972 /* else: no host specified; use default */
975 hostname = default_host;
981 plugin_instance = strchr(plugin, '-');
982 if (plugin_instance != NULL) {
983 *plugin_instance = '\0';
987 type_instance = strchr(type, '-');
988 if (type_instance != NULL) {
989 *type_instance = '\0';
993 *ret_host = hostname;
994 *ret_plugin = plugin;
995 *ret_plugin_instance = plugin_instance;
997 *ret_type_instance = type_instance;
999 } /* int parse_identifier */
1001 int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
1003 char str_copy[6 * DATA_MAX_NAME_LEN];
1005 char *plugin = NULL;
1006 char *plugin_instance = NULL;
1008 char *type_instance = NULL;
1011 if ((str == NULL) || (vl == NULL))
1014 sstrncpy(str_copy, str, sizeof(str_copy));
1016 status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
1018 /* default_host = */ NULL);
1022 sstrncpy(vl->host, host, sizeof(vl->host));
1023 sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
1024 sstrncpy(vl->plugin_instance,
1025 (plugin_instance != NULL) ? plugin_instance : "",
1026 sizeof(vl->plugin_instance));
1027 sstrncpy(vl->type, type, sizeof(vl->type));
1028 sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
1029 sizeof(vl->type_instance));
1032 } /* }}} int parse_identifier_vl */
1034 int parse_value(const char *value_orig, value_t *ret_value, int ds_type) {
1036 char *endptr = NULL;
1039 if (value_orig == NULL)
1042 value = strdup(value_orig);
1045 value_len = strlen(value);
1047 while ((value_len > 0) && isspace((int)value[value_len - 1])) {
1048 value[value_len - 1] = '\0';
1053 case DS_TYPE_COUNTER:
1054 ret_value->counter = (counter_t)strtoull(value, &endptr, 0);
1058 ret_value->gauge = (gauge_t)strtod(value, &endptr);
1061 case DS_TYPE_DERIVE:
1062 ret_value->derive = (derive_t)strtoll(value, &endptr, 0);
1065 case DS_TYPE_ABSOLUTE:
1066 ret_value->absolute = (absolute_t)strtoull(value, &endptr, 0);
1071 P_ERROR("parse_value: Invalid data source type: %i.", ds_type);
1075 if (value == endptr) {
1076 P_ERROR("parse_value: Failed to parse string as %s: \"%s\".",
1077 DS_TYPE_TO_STRING(ds_type), value);
1080 } else if ((NULL != endptr) && ('\0' != *endptr))
1081 P_INFO("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1082 "Input string was \"%s\".",
1083 endptr, DS_TYPE_TO_STRING(ds_type), value_orig);
1087 } /* int parse_value */
1089 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds) {
1095 if ((buffer == NULL) || (vl == NULL) || (ds == NULL))
1102 while ((ptr = strtok_r(dummy, ":", &saveptr)) != NULL) {
1105 if (i >= vl->values_len) {
1106 /* Make sure i is invalid. */
1111 if (vl->time == 0) {
1112 if (strcmp("N", ptr) == 0)
1113 vl->time = cdtime();
1115 char *endptr = NULL;
1119 tmp = strtod(ptr, &endptr);
1120 if ((errno != 0) /* Overflow */
1121 || (endptr == ptr) /* Invalid string */
1122 || (endptr == NULL) /* This should not happen */
1123 || (*endptr != 0)) /* Trailing chars */
1126 vl->time = DOUBLE_TO_CDTIME_T(tmp);
1132 if ((strcmp("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1133 vl->values[i].gauge = NAN;
1134 else if (0 != parse_value(ptr, &vl->values[i], ds->ds[i].type))
1138 } /* while (strtok_r) */
1140 if ((ptr != NULL) || (i == 0))
1143 } /* int parse_values */
1145 int parse_value_file(char const *path, value_t *ret_value, int ds_type) {
1149 fh = fopen(path, "r");
1153 if (fgets(buffer, sizeof(buffer), fh) == NULL) {
1160 strstripnewline(buffer);
1162 return parse_value(buffer, ret_value, ds_type);
1163 } /* int parse_value_file */
1165 #if !HAVE_GETPWNAM_R
1166 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
1167 struct passwd **pwbufp) {
1168 #ifndef HAVE_GETPWNAM
1174 memset(pwbuf, '\0', sizeof(struct passwd));
1176 pthread_mutex_lock(&getpwnam_r_lock);
1179 pw = getpwnam(name);
1181 status = (errno != 0) ? errno : ENOENT;
1185 #define GETPWNAM_COPY_MEMBER(member) \
1186 if (pw->member != NULL) { \
1187 int len = strlen(pw->member); \
1188 if (len >= buflen) { \
1192 sstrncpy(buf, pw->member, buflen); \
1193 pwbuf->member = buf; \
1195 buflen -= (len + 1); \
1197 GETPWNAM_COPY_MEMBER(pw_name);
1198 GETPWNAM_COPY_MEMBER(pw_passwd);
1199 GETPWNAM_COPY_MEMBER(pw_gecos);
1200 GETPWNAM_COPY_MEMBER(pw_dir);
1201 GETPWNAM_COPY_MEMBER(pw_shell);
1203 pwbuf->pw_uid = pw->pw_uid;
1204 pwbuf->pw_gid = pw->pw_gid;
1210 pthread_mutex_unlock(&getpwnam_r_lock);
1213 #endif /* HAVE_GETPWNAM */
1214 } /* int getpwnam_r */
1215 #endif /* !HAVE_GETPWNAM_R */
1217 int notification_init(notification_t *n, int severity, const char *message,
1218 const char *host, const char *plugin,
1219 const char *plugin_instance, const char *type,
1220 const char *type_instance) {
1221 memset(n, '\0', sizeof(notification_t));
1223 n->severity = severity;
1225 if (message != NULL)
1226 sstrncpy(n->message, message, sizeof(n->message));
1228 sstrncpy(n->host, host, sizeof(n->host));
1230 sstrncpy(n->plugin, plugin, sizeof(n->plugin));
1231 if (plugin_instance != NULL)
1232 sstrncpy(n->plugin_instance, plugin_instance, sizeof(n->plugin_instance));
1234 sstrncpy(n->type, type, sizeof(n->type));
1235 if (type_instance != NULL)
1236 sstrncpy(n->type_instance, type_instance, sizeof(n->type_instance));
1239 } /* int notification_init */
1241 int walk_directory(const char *dir, dirwalk_callback_f callback,
1242 void *user_data, int include_hidden) {
1251 if ((dh = opendir(dir)) == NULL) {
1252 P_ERROR("walk_directory: Cannot open '%s': %s", dir, STRERRNO);
1256 while ((ent = readdir(dh)) != NULL) {
1259 if (include_hidden) {
1260 if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0))
1262 } else /* if (!include_hidden) */
1264 if (ent->d_name[0] == '.')
1268 status = (*callback)(dir, ent->d_name, user_data);
1277 if ((success == 0) && (failure > 0))
1282 ssize_t read_file_contents(const char *filename, char *buf, size_t bufsize) {
1286 fh = fopen(filename, "r");
1290 ret = (ssize_t)fread(buf, 1, bufsize, fh);
1291 if ((ret == 0) && (ferror(fh) != 0)) {
1292 P_ERROR("read_file_contents: Reading file \"%s\" failed.", filename);
1300 counter_t counter_diff(counter_t old_value, counter_t new_value) {
1303 if (old_value > new_value) {
1304 if (old_value <= 4294967295U)
1305 diff = (4294967295U - old_value) + new_value + 1;
1307 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1309 diff = new_value - old_value;
1313 } /* counter_t counter_diff */
1315 int rate_to_value(value_t *ret_value, gauge_t rate, /* {{{ */
1316 rate_to_value_state_t *state, int ds_type, cdtime_t t) {
1317 gauge_t delta_gauge;
1320 if (ds_type == DS_TYPE_GAUGE) {
1321 state->last_value.gauge = rate;
1322 state->last_time = t;
1324 *ret_value = state->last_value;
1328 /* Counter and absolute can't handle negative rates. Reset "last time"
1329 * to zero, so that the next valid rate will re-initialize the
1332 ((ds_type == DS_TYPE_COUNTER) || (ds_type == DS_TYPE_ABSOLUTE))) {
1333 memset(state, 0, sizeof(*state));
1337 /* Another invalid state: The time is not increasing. */
1338 if (t <= state->last_time) {
1339 memset(state, 0, sizeof(*state));
1343 delta_t = t - state->last_time;
1344 delta_gauge = (rate * CDTIME_T_TO_DOUBLE(delta_t)) + state->residual;
1346 /* Previous value is invalid. */
1347 if (state->last_time == 0) /* {{{ */
1349 if (ds_type == DS_TYPE_DERIVE) {
1350 state->last_value.derive = (derive_t)rate;
1351 state->residual = rate - ((gauge_t)state->last_value.derive);
1352 } else if (ds_type == DS_TYPE_COUNTER) {
1353 state->last_value.counter = (counter_t)rate;
1354 state->residual = rate - ((gauge_t)state->last_value.counter);
1355 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1356 state->last_value.absolute = (absolute_t)rate;
1357 state->residual = rate - ((gauge_t)state->last_value.absolute);
1362 state->last_time = t;
1366 if (ds_type == DS_TYPE_DERIVE) {
1367 derive_t delta_derive = (derive_t)delta_gauge;
1369 state->last_value.derive += delta_derive;
1370 state->residual = delta_gauge - ((gauge_t)delta_derive);
1371 } else if (ds_type == DS_TYPE_COUNTER) {
1372 counter_t delta_counter = (counter_t)delta_gauge;
1374 state->last_value.counter += delta_counter;
1375 state->residual = delta_gauge - ((gauge_t)delta_counter);
1376 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1377 absolute_t delta_absolute = (absolute_t)delta_gauge;
1379 state->last_value.absolute = delta_absolute;
1380 state->residual = delta_gauge - ((gauge_t)delta_absolute);
1385 state->last_time = t;
1386 *ret_value = state->last_value;
1388 } /* }}} value_t rate_to_value */
1390 int value_to_rate(gauge_t *ret_rate, /* {{{ */
1391 value_t value, int ds_type, cdtime_t t,
1392 value_to_rate_state_t *state) {
1395 /* Another invalid state: The time is not increasing. */
1396 if (t <= state->last_time) {
1397 memset(state, 0, sizeof(*state));
1401 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1403 /* Previous value is invalid. */
1404 if (state->last_time == 0) {
1405 state->last_value = value;
1406 state->last_time = t;
1411 case DS_TYPE_DERIVE: {
1412 derive_t diff = value.derive - state->last_value.derive;
1413 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1416 case DS_TYPE_GAUGE: {
1417 *ret_rate = value.gauge;
1420 case DS_TYPE_COUNTER: {
1421 counter_t diff = counter_diff(state->last_value.counter, value.counter);
1422 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1425 case DS_TYPE_ABSOLUTE: {
1426 absolute_t diff = value.absolute;
1427 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1434 state->last_value = value;
1435 state->last_time = t;
1437 } /* }}} value_t rate_to_value */
1439 int service_name_to_port_number(const char *service_name) {
1440 struct addrinfo *ai_list;
1444 if (service_name == NULL)
1447 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC};
1449 status = getaddrinfo(/* node = */ NULL, service_name, &ai_hints, &ai_list);
1451 P_ERROR("service_name_to_port_number: getaddrinfo failed: %s",
1452 gai_strerror(status));
1456 service_number = -1;
1457 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1458 ai_ptr = ai_ptr->ai_next) {
1459 if (ai_ptr->ai_family == AF_INET) {
1460 struct sockaddr_in *sa;
1462 sa = (void *)ai_ptr->ai_addr;
1463 service_number = (int)ntohs(sa->sin_port);
1464 } else if (ai_ptr->ai_family == AF_INET6) {
1465 struct sockaddr_in6 *sa;
1467 sa = (void *)ai_ptr->ai_addr;
1468 service_number = (int)ntohs(sa->sin6_port);
1471 if (service_number > 0)
1475 freeaddrinfo(ai_list);
1477 if (service_number > 0)
1478 return service_number;
1480 } /* int service_name_to_port_number */
1482 void set_sock_opts(int sockfd) /* {{{ */
1487 status = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &socktype,
1488 &(socklen_t){sizeof(socktype)});
1490 P_WARNING("set_sock_opts: failed to determine socket type");
1494 if (socktype == SOCK_STREAM) {
1496 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int));
1498 P_WARNING("set_sock_opts: failed to set socket keepalive flag");
1501 int tcp_keepidle = ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 100 + 1);
1502 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &tcp_keepidle,
1503 sizeof(tcp_keepidle));
1505 P_WARNING("set_sock_opts: failed to set socket tcp keepalive time");
1508 #ifdef TCP_KEEPINTVL
1510 ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 1000 + 1);
1511 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &tcp_keepintvl,
1512 sizeof(tcp_keepintvl));
1514 P_WARNING("set_sock_opts: failed to set socket tcp keepalive interval");
1517 } /* }}} void set_sock_opts */
1519 int strtoderive(const char *string, derive_t *ret_value) /* {{{ */
1524 if ((string == NULL) || (ret_value == NULL))
1529 tmp = (derive_t)strtoll(string, &endptr, /* base = */ 0);
1530 if ((endptr == string) || (errno != 0))
1535 } /* }}} int strtoderive */
1537 int strtogauge(const char *string, gauge_t *ret_value) /* {{{ */
1540 char *endptr = NULL;
1542 if ((string == NULL) || (ret_value == NULL))
1547 tmp = (gauge_t)strtod(string, &endptr);
1550 else if ((endptr == NULL) || (*endptr != 0))
1555 } /* }}} int strtogauge */
1557 int strarray_add(char ***ret_array, size_t *ret_array_len,
1558 char const *str) /* {{{ */
1561 size_t array_len = *ret_array_len;
1566 array = realloc(*ret_array, (array_len + 1) * sizeof(*array));
1571 array[array_len] = strdup(str);
1572 if (array[array_len] == NULL)
1576 *ret_array_len = array_len;
1578 } /* }}} int strarray_add */
1580 void strarray_free(char **array, size_t array_len) /* {{{ */
1582 for (size_t i = 0; i < array_len; i++)
1585 } /* }}} void strarray_free */
1588 int check_capability(int arg) /* {{{ */
1590 cap_value_t cap_value = (cap_value_t)arg;
1592 cap_flag_value_t cap_flag_value;
1594 if (!CAP_IS_SUPPORTED(cap_value))
1597 if (!(cap = cap_get_proc())) {
1598 P_ERROR("check_capability: cap_get_proc failed.");
1602 if (cap_get_flag(cap, cap_value, CAP_EFFECTIVE, &cap_flag_value) < 0) {
1603 P_ERROR("check_capability: cap_get_flag failed.");
1609 return cap_flag_value != CAP_SET;
1610 } /* }}} int check_capability */
1612 int check_capability(__attribute__((unused)) int arg) /* {{{ */
1614 P_WARNING("check_capability: unsupported capability implementation. "
1615 "Some plugin(s) may require elevated privileges to work properly.");
1617 } /* }}} int check_capability */
1618 #endif /* HAVE_CAPABILITY */