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 zero on success, one if truncation occurred
93 and a negative integer onerror. */
94 int ssnprintf(char *str, size_t sz, const char *format, ...) {
98 int ret = vsnprintf(str, sz, format, ap);
105 return (size_t)ret >= sz;
106 } /* int ssnprintf */
108 char *ssnprintf_alloc(char const *format, ...) /* {{{ */
110 char static_buffer[1024] = "";
112 size_t alloc_buffer_size;
116 /* Try printing into the static buffer. In many cases it will be
117 * sufficiently large and we can simply return a strdup() of this
119 va_start(ap, format);
120 status = vsnprintf(static_buffer, sizeof(static_buffer), format, ap);
125 /* "status" does not include the null byte. */
126 alloc_buffer_size = (size_t)(status + 1);
127 if (alloc_buffer_size <= sizeof(static_buffer))
128 return strdup(static_buffer);
130 /* Allocate a buffer large enough to hold the string. */
131 alloc_buffer = calloc(1, alloc_buffer_size);
132 if (alloc_buffer == NULL)
135 /* Print again into this new buffer. */
136 va_start(ap, format);
137 status = vsnprintf(alloc_buffer, alloc_buffer_size, format, ap);
145 } /* }}} char *ssnprintf_alloc */
147 char *sstrdup(const char *s) {
154 /* Do not use `strdup' here, because it's not specified in POSIX. It's
155 * ``only'' an XSI extension. */
159 ERROR("sstrdup: Out of memory.");
165 } /* char *sstrdup */
167 /* Even though Posix requires "strerror_r" to return an "int",
168 * some systems (e.g. the GNU libc) return a "char *" _and_
169 * ignore the second argument ... -tokkee */
170 char *sstrerror(int errnum, char *buf, size_t buflen) {
177 pthread_mutex_lock(&strerror_r_lock);
179 temp = strerror(errnum);
180 sstrncpy(buf, temp, buflen);
182 pthread_mutex_unlock(&strerror_r_lock);
184 /* #endif !HAVE_STRERROR_R */
186 #elif STRERROR_R_CHAR_P
189 temp = strerror_r(errnum, buf, buflen);
190 if (buf[0] == '\0') {
191 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
192 sstrncpy(buf, temp, buflen);
194 sstrncpy(buf, "strerror_r did not return "
199 /* #endif STRERROR_R_CHAR_P */
202 if (strerror_r(errnum, buf, buflen) != 0) {
203 snprintf(buf, buflen, "Error #%i; "
204 "Additionally, strerror_r failed.",
207 #endif /* STRERROR_R_CHAR_P */
210 } /* char *sstrerror */
212 void *smalloc(size_t size) {
215 if ((r = malloc(size)) == NULL) {
216 ERROR("Not enough memory.");
221 } /* void *smalloc */
224 void sfree (void **ptr)
236 int sread(int fd, void *buf, size_t count) {
245 status = read(fd, (void *)ptr, nleft);
247 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
254 DEBUG("Received EOF from fd %i. ", fd);
258 assert((0 > status) || (nleft >= (size_t)status));
260 nleft = nleft - ((size_t)status);
261 ptr = ptr + ((size_t)status);
267 int swrite(int fd, const void *buf, size_t count) {
273 ptr = (const char *)buf;
281 /* checking for closed peer connection */
283 pfd.events = POLLIN | POLLHUP;
285 if (poll(&pfd, 1, 0) > 0) {
287 if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
288 /* if recv returns zero (even though poll() said there is data to be
289 * read), that means the connection has been closed */
296 status = write(fd, (const void *)ptr, nleft);
298 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
302 return errno ? errno : status;
304 nleft = nleft - ((size_t)status);
305 ptr = ptr + ((size_t)status);
311 int strsplit(char *string, char **fields, size_t size) {
319 while ((fields[i] = strtok_r(ptr, " \t\r\n", &saveptr)) != NULL) {
330 int strjoin(char *buffer, size_t buffer_size, char **fields, size_t fields_num,
336 size_t buffer_req = 0;
338 if (((fields_num != 0) && (fields == NULL)) ||
339 ((buffer_size != 0) && (buffer == NULL)))
345 if (buffer_size != 0)
346 avail = buffer_size - 1;
349 sep_len = strlen(sep);
351 for (size_t i = 0; i < fields_num; i++) {
352 size_t field_len = strlen(fields[i]);
355 buffer_req += sep_len;
356 buffer_req += field_len;
358 if (buffer_size == 0)
361 if ((i != 0) && (sep_len > 0)) {
362 if (sep_len >= avail) {
363 /* prevent subsequent iterations from writing to the
369 memcpy(ptr, sep, sep_len);
375 if (field_len > avail)
378 memcpy(ptr, fields[i], field_len);
386 return (int)buffer_req;
389 int escape_string(char *buffer, size_t buffer_size) {
393 /* Check if we need to escape at all first */
394 temp = strpbrk(buffer, " \t\"\\");
401 temp = calloc(1, buffer_size);
408 for (size_t i = 0; i < buffer_size; i++) {
409 if (buffer[i] == 0) {
411 } else if ((buffer[i] == '"') || (buffer[i] == '\\')) {
412 if (j > (buffer_size - 4))
415 temp[j + 1] = buffer[i];
418 if (j > (buffer_size - 3))
425 assert((j + 1) < buffer_size);
429 sstrncpy(buffer, temp, buffer_size);
432 } /* int escape_string */
434 int strunescape(char *buf, size_t buf_len) {
435 for (size_t i = 0; (i < buf_len) && (buf[i] != '\0'); ++i) {
439 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
440 P_ERROR("string unescape: backslash found at end of string.");
441 /* Ensure null-byte at the end of the buffer. */
446 switch (buf[i + 1]) {
461 /* Move everything after the position one position to the left.
462 * Add a null-byte as last character in the buffer. */
463 memmove(buf + i + 1, buf + i + 2, buf_len - i - 2);
464 buf[buf_len - 1] = '\0';
467 } /* int strunescape */
469 size_t strstripnewline(char *buffer) {
470 size_t buffer_len = strlen(buffer);
472 while (buffer_len > 0) {
473 if ((buffer[buffer_len - 1] != '\n') && (buffer[buffer_len - 1] != '\r'))
476 buffer[buffer_len] = 0;
480 } /* size_t strstripnewline */
482 int escape_slashes(char *buffer, size_t buffer_size) {
485 buffer_len = strlen(buffer);
487 if (buffer_len <= 1) {
488 if (strcmp("/", buffer) == 0) {
491 sstrncpy(buffer, "root", buffer_size);
496 /* Move one to the left */
497 if (buffer[0] == '/') {
498 memmove(buffer, buffer + 1, buffer_len);
502 for (size_t i = 0; i < buffer_len; i++) {
503 if (buffer[i] == '/')
508 } /* int escape_slashes */
510 void replace_special(char *buffer, size_t buffer_size) {
511 for (size_t i = 0; i < buffer_size; i++) {
514 if ((!isalnum((int)buffer[i])) && (buffer[i] != '-'))
517 } /* void replace_special */
519 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta) {
520 struct timeval *larger;
521 struct timeval *smaller;
525 NORMALIZE_TIMEVAL(tv0);
526 NORMALIZE_TIMEVAL(tv1);
528 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec)) {
536 if ((tv0.tv_sec < tv1.tv_sec) ||
537 ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec))) {
548 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
550 if (smaller->tv_usec <= larger->tv_usec)
551 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
554 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
558 assert((delta == NULL) ||
559 ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
562 } /* int timeval_cmp */
564 int check_create_dir(const char *file_orig) {
567 char file_copy[PATH_MAX];
573 int last_is_file = 1;
574 int path_is_absolute = 0;
578 * Sanity checks first
580 if (file_orig == NULL)
583 if ((len = strlen(file_orig)) < 1)
585 else if (len >= sizeof(file_copy)) {
586 ERROR("check_create_dir: name (%s) is too long.", file_orig);
591 * If `file_orig' ends in a slash the last component is a directory,
592 * otherwise it's a file. Act accordingly..
594 if (file_orig[len - 1] == '/')
596 if (file_orig[0] == '/')
597 path_is_absolute = 1;
600 * Create a copy for `strtok_r' to destroy
602 sstrncpy(file_copy, file_orig, sizeof(file_copy));
605 * Break into components. This will eat up several slashes in a row and
606 * remove leading and trailing slashes..
611 while ((fields[fields_num] = strtok_r(ptr, "/", &saveptr)) != NULL) {
615 if (fields_num >= 16)
620 * For each component, do..
622 for (int i = 0; i < (fields_num - last_is_file); i++) {
624 * Do not create directories that start with a dot. This
625 * prevents `../../' attacks and other likely malicious
628 if (fields[i][0] == '.') {
629 P_ERROR("Cowardly refusing to create a directory that "
630 "begins with a `.' (dot): `%s'",
636 * Join the components together again
639 if (strjoin(dir + path_is_absolute,
640 (size_t)(sizeof(dir) - path_is_absolute), fields,
641 (size_t)(i + 1), "/") < 0) {
642 P_ERROR("strjoin failed: `%s', component #%i", file_orig, i);
647 if ((stat(dir, &statbuf) == -1) && (lstat(dir, &statbuf) == -1)) {
648 if (errno == ENOENT) {
649 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
652 /* this might happen, if a different thread created
653 * the directory in the meantime
654 * => call stat() again to check for S_ISDIR() */
658 P_ERROR("check_create_dir: mkdir (%s): %s", dir, STRERRNO);
661 P_ERROR("check_create_dir: stat (%s): %s", dir, STRERRNO);
664 } else if (!S_ISDIR(statbuf.st_mode)) {
665 P_ERROR("check_create_dir: `%s' exists but is not "
675 } /* check_create_dir */
678 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name) {
686 snprintf(ident, sizeof(ident), "%s,%i,%s", module, instance, name);
688 *ksp_ptr = kstat_lookup(kc, module, instance, name);
689 if (*ksp_ptr == NULL) {
690 P_ERROR("get_kstat: Cound not find kstat %s", ident);
694 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
695 P_ERROR("get_kstat: kstat %s has wrong type", ident);
701 assert(*ksp_ptr != NULL);
702 assert((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
705 if (kstat_read(kc, *ksp_ptr, NULL) == -1) {
706 P_ERROR("get_kstat: kstat %s could not be read", ident);
710 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
711 P_ERROR("get_kstat: kstat %s has wrong type", ident);
718 long long get_kstat_value(kstat_t *ksp, char *name) {
720 long long retval = -1LL;
723 P_ERROR("get_kstat_value (\"%s\"): ksp is NULL.", name);
725 } else if (ksp->ks_type != KSTAT_TYPE_NAMED) {
726 P_ERROR("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
727 "is not KSTAT_TYPE_NAMED (%#x).",
728 name, (unsigned int)ksp->ks_type, (unsigned int)KSTAT_TYPE_NAMED);
732 if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, name)) == NULL)
735 if (kn->data_type == KSTAT_DATA_INT32)
736 retval = (long long)kn->value.i32;
737 else if (kn->data_type == KSTAT_DATA_UINT32)
738 retval = (long long)kn->value.ui32;
739 else if (kn->data_type == KSTAT_DATA_INT64)
741 (long long)kn->value.i64; /* According to ANSI C99 `long long' must hold
743 else if (kn->data_type == KSTAT_DATA_UINT64)
744 retval = (long long)kn->value.ui64; /* XXX: Might overflow! */
746 P_WARNING("get_kstat_value: Not a numeric value: %s", name);
750 #endif /* HAVE_LIBKSTAT */
753 unsigned long long ntohll(unsigned long long n) {
754 #if BYTE_ORDER == BIG_ENDIAN
757 return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
759 } /* unsigned long long ntohll */
761 unsigned long long htonll(unsigned long long n) {
762 #if BYTE_ORDER == BIG_ENDIAN
765 return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
767 } /* unsigned long long htonll */
768 #endif /* HAVE_HTONLL */
770 #if FP_LAYOUT_NEED_NOTHING
771 /* Well, we need nothing.. */
772 /* #endif FP_LAYOUT_NEED_NOTHING */
774 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
775 #if FP_LAYOUT_NEED_ENDIANFLIP
776 #define FP_CONVERT(A) \
777 ((((uint64_t)(A)&0xff00000000000000LL) >> 56) | \
778 (((uint64_t)(A)&0x00ff000000000000LL) >> 40) | \
779 (((uint64_t)(A)&0x0000ff0000000000LL) >> 24) | \
780 (((uint64_t)(A)&0x000000ff00000000LL) >> 8) | \
781 (((uint64_t)(A)&0x00000000ff000000LL) << 8) | \
782 (((uint64_t)(A)&0x0000000000ff0000LL) << 24) | \
783 (((uint64_t)(A)&0x000000000000ff00LL) << 40) | \
784 (((uint64_t)(A)&0x00000000000000ffLL) << 56))
786 #define FP_CONVERT(A) \
787 ((((uint64_t)(A)&0xffffffff00000000LL) >> 32) | \
788 (((uint64_t)(A)&0x00000000ffffffffLL) << 32))
791 double ntohd(double d) {
800 /* NAN in x86 byte order */
801 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00) && (ret.byte[2] == 0x00) &&
802 (ret.byte[3] == 0x00) && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00) &&
803 (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f)) {
809 ret.integer = FP_CONVERT(tmp);
814 double htond(double d) {
822 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
823 ret.byte[4] = ret.byte[5] = 0x00;
831 tmp = FP_CONVERT(ret.integer);
836 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
838 int format_name(char *ret, int ret_len, const char *hostname,
839 const char *plugin, const char *plugin_instance,
840 const char *type, const char *type_instance) {
845 buffer_size = (size_t)ret_len;
847 #define APPEND(str) \
849 size_t l = strlen(str); \
850 if (l >= buffer_size) \
852 memcpy(buffer, (str), l); \
857 assert(plugin != NULL);
858 assert(type != NULL);
863 if ((plugin_instance != NULL) && (plugin_instance[0] != 0)) {
865 APPEND(plugin_instance);
869 if ((type_instance != NULL) && (type_instance[0] != 0)) {
871 APPEND(type_instance);
873 assert(buffer_size > 0);
878 } /* int format_name */
880 int format_values(char *ret, size_t ret_len, /* {{{ */
881 const data_set_t *ds, const value_list_t *vl,
885 gauge_t *rates = NULL;
887 assert(0 == strcmp(ds->type, vl->type));
889 memset(ret, 0, ret_len);
891 #define BUFFER_ADD(...) \
893 status = snprintf(ret + offset, ret_len - offset, __VA_ARGS__); \
897 } else if (((size_t)status) >= (ret_len - offset)) { \
901 offset += ((size_t)status); \
904 BUFFER_ADD("%.3f", CDTIME_T_TO_DOUBLE(vl->time));
906 for (size_t i = 0; i < ds->ds_num; i++) {
907 if (ds->ds[i].type == DS_TYPE_GAUGE)
908 BUFFER_ADD(":" GAUGE_FORMAT, vl->values[i].gauge);
909 else if (store_rates) {
911 rates = uc_get_rate(ds, vl);
913 WARNING("format_values: uc_get_rate failed.");
916 BUFFER_ADD(":" GAUGE_FORMAT, rates[i]);
917 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
918 BUFFER_ADD(":%" PRIu64, (uint64_t)vl->values[i].counter);
919 else if (ds->ds[i].type == DS_TYPE_DERIVE)
920 BUFFER_ADD(":%" PRIi64, vl->values[i].derive);
921 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
922 BUFFER_ADD(":%" PRIu64, vl->values[i].absolute);
924 ERROR("format_values: Unknown data source type: %i", ds->ds[i].type);
928 } /* for ds->ds_num */
934 } /* }}} int format_values */
936 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
937 char **ret_plugin_instance, char **ret_type,
938 char **ret_type_instance, char *default_host) {
939 char *hostname = NULL;
941 char *plugin_instance = NULL;
943 char *type_instance = NULL;
946 if (hostname == NULL)
949 plugin = strchr(hostname, '/');
955 type = strchr(plugin, '/');
957 if (default_host == NULL)
959 /* else: no host specified; use default */
962 hostname = default_host;
968 plugin_instance = strchr(plugin, '-');
969 if (plugin_instance != NULL) {
970 *plugin_instance = '\0';
974 type_instance = strchr(type, '-');
975 if (type_instance != NULL) {
976 *type_instance = '\0';
980 *ret_host = hostname;
981 *ret_plugin = plugin;
982 *ret_plugin_instance = plugin_instance;
984 *ret_type_instance = type_instance;
986 } /* int parse_identifier */
988 int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
990 char str_copy[6 * DATA_MAX_NAME_LEN];
993 char *plugin_instance = NULL;
995 char *type_instance = NULL;
998 if ((str == NULL) || (vl == NULL))
1001 sstrncpy(str_copy, str, sizeof(str_copy));
1003 status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
1005 /* default_host = */ NULL);
1009 sstrncpy(vl->host, host, sizeof(vl->host));
1010 sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
1011 sstrncpy(vl->plugin_instance,
1012 (plugin_instance != NULL) ? plugin_instance : "",
1013 sizeof(vl->plugin_instance));
1014 sstrncpy(vl->type, type, sizeof(vl->type));
1015 sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
1016 sizeof(vl->type_instance));
1019 } /* }}} int parse_identifier_vl */
1021 int parse_value(const char *value_orig, value_t *ret_value, int ds_type) {
1023 char *endptr = NULL;
1026 if (value_orig == NULL)
1029 value = strdup(value_orig);
1032 value_len = strlen(value);
1034 while ((value_len > 0) && isspace((int)value[value_len - 1])) {
1035 value[value_len - 1] = '\0';
1040 case DS_TYPE_COUNTER:
1041 ret_value->counter = (counter_t)strtoull(value, &endptr, 0);
1045 ret_value->gauge = (gauge_t)strtod(value, &endptr);
1048 case DS_TYPE_DERIVE:
1049 ret_value->derive = (derive_t)strtoll(value, &endptr, 0);
1052 case DS_TYPE_ABSOLUTE:
1053 ret_value->absolute = (absolute_t)strtoull(value, &endptr, 0);
1058 P_ERROR("parse_value: Invalid data source type: %i.", ds_type);
1062 if (value == endptr) {
1063 P_ERROR("parse_value: Failed to parse string as %s: \"%s\".",
1064 DS_TYPE_TO_STRING(ds_type), value);
1067 } else if ((NULL != endptr) && ('\0' != *endptr))
1068 P_INFO("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1069 "Input string was \"%s\".",
1070 endptr, DS_TYPE_TO_STRING(ds_type), value_orig);
1074 } /* int parse_value */
1076 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds) {
1082 if ((buffer == NULL) || (vl == NULL) || (ds == NULL))
1089 while ((ptr = strtok_r(dummy, ":", &saveptr)) != NULL) {
1092 if (i >= vl->values_len) {
1093 /* Make sure i is invalid. */
1098 if (vl->time == 0) {
1099 if (strcmp("N", ptr) == 0)
1100 vl->time = cdtime();
1102 char *endptr = NULL;
1106 tmp = strtod(ptr, &endptr);
1107 if ((errno != 0) /* Overflow */
1108 || (endptr == ptr) /* Invalid string */
1109 || (endptr == NULL) /* This should not happen */
1110 || (*endptr != 0)) /* Trailing chars */
1113 vl->time = DOUBLE_TO_CDTIME_T(tmp);
1119 if ((strcmp("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1120 vl->values[i].gauge = NAN;
1121 else if (0 != parse_value(ptr, &vl->values[i], ds->ds[i].type))
1125 } /* while (strtok_r) */
1127 if ((ptr != NULL) || (i == 0))
1130 } /* int parse_values */
1132 int parse_value_file(char const *path, value_t *ret_value, int ds_type) {
1136 fh = fopen(path, "r");
1140 if (fgets(buffer, sizeof(buffer), fh) == NULL) {
1147 strstripnewline(buffer);
1149 return parse_value(buffer, ret_value, ds_type);
1150 } /* int parse_value_file */
1152 #if !HAVE_GETPWNAM_R
1153 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
1154 struct passwd **pwbufp) {
1155 #ifndef HAVE_GETPWNAM
1161 memset(pwbuf, '\0', sizeof(struct passwd));
1163 pthread_mutex_lock(&getpwnam_r_lock);
1166 pw = getpwnam(name);
1168 status = (errno != 0) ? errno : ENOENT;
1172 #define GETPWNAM_COPY_MEMBER(member) \
1173 if (pw->member != NULL) { \
1174 int len = strlen(pw->member); \
1175 if (len >= buflen) { \
1179 sstrncpy(buf, pw->member, buflen); \
1180 pwbuf->member = buf; \
1182 buflen -= (len + 1); \
1184 GETPWNAM_COPY_MEMBER(pw_name);
1185 GETPWNAM_COPY_MEMBER(pw_passwd);
1186 GETPWNAM_COPY_MEMBER(pw_gecos);
1187 GETPWNAM_COPY_MEMBER(pw_dir);
1188 GETPWNAM_COPY_MEMBER(pw_shell);
1190 pwbuf->pw_uid = pw->pw_uid;
1191 pwbuf->pw_gid = pw->pw_gid;
1197 pthread_mutex_unlock(&getpwnam_r_lock);
1200 #endif /* HAVE_GETPWNAM */
1201 } /* int getpwnam_r */
1202 #endif /* !HAVE_GETPWNAM_R */
1204 int notification_init(notification_t *n, int severity, const char *message,
1205 const char *host, const char *plugin,
1206 const char *plugin_instance, const char *type,
1207 const char *type_instance) {
1208 memset(n, '\0', sizeof(notification_t));
1210 n->severity = severity;
1212 if (message != NULL)
1213 sstrncpy(n->message, message, sizeof(n->message));
1215 sstrncpy(n->host, host, sizeof(n->host));
1217 sstrncpy(n->plugin, plugin, sizeof(n->plugin));
1218 if (plugin_instance != NULL)
1219 sstrncpy(n->plugin_instance, plugin_instance, sizeof(n->plugin_instance));
1221 sstrncpy(n->type, type, sizeof(n->type));
1222 if (type_instance != NULL)
1223 sstrncpy(n->type_instance, type_instance, sizeof(n->type_instance));
1226 } /* int notification_init */
1228 int walk_directory(const char *dir, dirwalk_callback_f callback,
1229 void *user_data, int include_hidden) {
1238 if ((dh = opendir(dir)) == NULL) {
1239 P_ERROR("walk_directory: Cannot open '%s': %s", dir, STRERRNO);
1243 while ((ent = readdir(dh)) != NULL) {
1246 if (include_hidden) {
1247 if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0))
1249 } else /* if (!include_hidden) */
1251 if (ent->d_name[0] == '.')
1255 status = (*callback)(dir, ent->d_name, user_data);
1264 if ((success == 0) && (failure > 0))
1269 ssize_t read_file_contents(const char *filename, char *buf, size_t bufsize) {
1273 fh = fopen(filename, "r");
1277 ret = (ssize_t)fread(buf, 1, bufsize, fh);
1278 if ((ret == 0) && (ferror(fh) != 0)) {
1279 P_ERROR("read_file_contents: Reading file \"%s\" failed.", filename);
1287 counter_t counter_diff(counter_t old_value, counter_t new_value) {
1290 if (old_value > new_value) {
1291 if (old_value <= 4294967295U)
1292 diff = (4294967295U - old_value) + new_value + 1;
1294 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1296 diff = new_value - old_value;
1300 } /* counter_t counter_diff */
1302 int rate_to_value(value_t *ret_value, gauge_t rate, /* {{{ */
1303 rate_to_value_state_t *state, int ds_type, cdtime_t t) {
1304 gauge_t delta_gauge;
1307 if (ds_type == DS_TYPE_GAUGE) {
1308 state->last_value.gauge = rate;
1309 state->last_time = t;
1311 *ret_value = state->last_value;
1315 /* Counter and absolute can't handle negative rates. Reset "last time"
1316 * to zero, so that the next valid rate will re-initialize the
1319 ((ds_type == DS_TYPE_COUNTER) || (ds_type == DS_TYPE_ABSOLUTE))) {
1320 memset(state, 0, sizeof(*state));
1324 /* Another invalid state: The time is not increasing. */
1325 if (t <= state->last_time) {
1326 memset(state, 0, sizeof(*state));
1330 delta_t = t - state->last_time;
1331 delta_gauge = (rate * CDTIME_T_TO_DOUBLE(delta_t)) + state->residual;
1333 /* Previous value is invalid. */
1334 if (state->last_time == 0) /* {{{ */
1336 if (ds_type == DS_TYPE_DERIVE) {
1337 state->last_value.derive = (derive_t)rate;
1338 state->residual = rate - ((gauge_t)state->last_value.derive);
1339 } else if (ds_type == DS_TYPE_COUNTER) {
1340 state->last_value.counter = (counter_t)rate;
1341 state->residual = rate - ((gauge_t)state->last_value.counter);
1342 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1343 state->last_value.absolute = (absolute_t)rate;
1344 state->residual = rate - ((gauge_t)state->last_value.absolute);
1349 state->last_time = t;
1353 if (ds_type == DS_TYPE_DERIVE) {
1354 derive_t delta_derive = (derive_t)delta_gauge;
1356 state->last_value.derive += delta_derive;
1357 state->residual = delta_gauge - ((gauge_t)delta_derive);
1358 } else if (ds_type == DS_TYPE_COUNTER) {
1359 counter_t delta_counter = (counter_t)delta_gauge;
1361 state->last_value.counter += delta_counter;
1362 state->residual = delta_gauge - ((gauge_t)delta_counter);
1363 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1364 absolute_t delta_absolute = (absolute_t)delta_gauge;
1366 state->last_value.absolute = delta_absolute;
1367 state->residual = delta_gauge - ((gauge_t)delta_absolute);
1372 state->last_time = t;
1373 *ret_value = state->last_value;
1375 } /* }}} value_t rate_to_value */
1377 int value_to_rate(gauge_t *ret_rate, /* {{{ */
1378 value_t value, int ds_type, cdtime_t t,
1379 value_to_rate_state_t *state) {
1382 /* Another invalid state: The time is not increasing. */
1383 if (t <= state->last_time) {
1384 memset(state, 0, sizeof(*state));
1388 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1390 /* Previous value is invalid. */
1391 if (state->last_time == 0) {
1392 state->last_value = value;
1393 state->last_time = t;
1398 case DS_TYPE_DERIVE: {
1399 derive_t diff = value.derive - state->last_value.derive;
1400 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1403 case DS_TYPE_GAUGE: {
1404 *ret_rate = value.gauge;
1407 case DS_TYPE_COUNTER: {
1408 counter_t diff = counter_diff(state->last_value.counter, value.counter);
1409 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1412 case DS_TYPE_ABSOLUTE: {
1413 absolute_t diff = value.absolute;
1414 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1421 state->last_value = value;
1422 state->last_time = t;
1424 } /* }}} value_t rate_to_value */
1426 int service_name_to_port_number(const char *service_name) {
1427 struct addrinfo *ai_list;
1431 if (service_name == NULL)
1434 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC};
1436 status = getaddrinfo(/* node = */ NULL, service_name, &ai_hints, &ai_list);
1438 P_ERROR("service_name_to_port_number: getaddrinfo failed: %s",
1439 gai_strerror(status));
1443 service_number = -1;
1444 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1445 ai_ptr = ai_ptr->ai_next) {
1446 if (ai_ptr->ai_family == AF_INET) {
1447 struct sockaddr_in *sa;
1449 sa = (void *)ai_ptr->ai_addr;
1450 service_number = (int)ntohs(sa->sin_port);
1451 } else if (ai_ptr->ai_family == AF_INET6) {
1452 struct sockaddr_in6 *sa;
1454 sa = (void *)ai_ptr->ai_addr;
1455 service_number = (int)ntohs(sa->sin6_port);
1458 if ((service_number > 0) && (service_number <= 65535))
1462 freeaddrinfo(ai_list);
1464 if ((service_number > 0) && (service_number <= 65535))
1465 return service_number;
1467 } /* int service_name_to_port_number */
1469 void set_sock_opts(int sockfd) /* {{{ */
1474 status = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &socktype,
1475 &(socklen_t){sizeof(socktype)});
1477 P_WARNING("set_sock_opts: failed to determine socket type");
1481 if (socktype == SOCK_STREAM) {
1483 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int));
1485 P_WARNING("set_sock_opts: failed to set socket keepalive flag");
1488 int tcp_keepidle = ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 100 + 1);
1489 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &tcp_keepidle,
1490 sizeof(tcp_keepidle));
1492 P_WARNING("set_sock_opts: failed to set socket tcp keepalive time");
1495 #ifdef TCP_KEEPINTVL
1497 ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 1000 + 1);
1498 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &tcp_keepintvl,
1499 sizeof(tcp_keepintvl));
1501 P_WARNING("set_sock_opts: failed to set socket tcp keepalive interval");
1504 } /* }}} void set_sock_opts */
1506 int strtoderive(const char *string, derive_t *ret_value) /* {{{ */
1511 if ((string == NULL) || (ret_value == NULL))
1516 tmp = (derive_t)strtoll(string, &endptr, /* base = */ 0);
1517 if ((endptr == string) || (errno != 0))
1522 } /* }}} int strtoderive */
1524 int strtogauge(const char *string, gauge_t *ret_value) /* {{{ */
1527 char *endptr = NULL;
1529 if ((string == NULL) || (ret_value == NULL))
1534 tmp = (gauge_t)strtod(string, &endptr);
1537 else if ((endptr == NULL) || (*endptr != 0))
1542 } /* }}} int strtogauge */
1544 int strarray_add(char ***ret_array, size_t *ret_array_len,
1545 char const *str) /* {{{ */
1548 size_t array_len = *ret_array_len;
1553 array = realloc(*ret_array, (array_len + 1) * sizeof(*array));
1558 array[array_len] = strdup(str);
1559 if (array[array_len] == NULL)
1563 *ret_array_len = array_len;
1565 } /* }}} int strarray_add */
1567 void strarray_free(char **array, size_t array_len) /* {{{ */
1569 for (size_t i = 0; i < array_len; i++)
1572 } /* }}} void strarray_free */
1575 int check_capability(int arg) /* {{{ */
1577 cap_value_t cap_value = (cap_value_t)arg;
1579 cap_flag_value_t cap_flag_value;
1581 if (!CAP_IS_SUPPORTED(cap_value))
1584 if (!(cap = cap_get_proc())) {
1585 P_ERROR("check_capability: cap_get_proc failed.");
1589 if (cap_get_flag(cap, cap_value, CAP_EFFECTIVE, &cap_flag_value) < 0) {
1590 P_ERROR("check_capability: cap_get_flag failed.");
1596 return cap_flag_value != CAP_SET;
1597 } /* }}} int check_capability */
1599 int check_capability(__attribute__((unused)) int arg) /* {{{ */
1601 P_WARNING("check_capability: unsupported capability implementation. "
1602 "Some plugin(s) may require elevated privileges to work properly.");
1604 } /* }}} int check_capability */
1605 #endif /* HAVE_CAPABILITY */