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 char *ssnprintf_alloc(char const *format, ...) /* {{{ */
94 char static_buffer[1024] = "";
96 size_t alloc_buffer_size;
100 /* Try printing into the static buffer. In many cases it will be
101 * sufficiently large and we can simply return a strdup() of this
103 va_start(ap, format);
104 status = vsnprintf(static_buffer, sizeof(static_buffer), format, ap);
109 /* "status" does not include the null byte. */
110 alloc_buffer_size = (size_t)(status + 1);
111 if (alloc_buffer_size <= sizeof(static_buffer))
112 return strdup(static_buffer);
114 /* Allocate a buffer large enough to hold the string. */
115 alloc_buffer = calloc(1, alloc_buffer_size);
116 if (alloc_buffer == NULL)
119 /* Print again into this new buffer. */
120 va_start(ap, format);
121 status = vsnprintf(alloc_buffer, alloc_buffer_size, format, ap);
129 } /* }}} char *ssnprintf_alloc */
131 char *sstrdup(const char *s) {
138 /* Do not use `strdup' here, because it's not specified in POSIX. It's
139 * ``only'' an XSI extension. */
143 ERROR("sstrdup: Out of memory.");
149 } /* char *sstrdup */
151 /* Even though Posix requires "strerror_r" to return an "int",
152 * some systems (e.g. the GNU libc) return a "char *" _and_
153 * ignore the second argument ... -tokkee */
154 char *sstrerror(int errnum, char *buf, size_t buflen) {
161 pthread_mutex_lock(&strerror_r_lock);
163 temp = strerror(errnum);
164 sstrncpy(buf, temp, buflen);
166 pthread_mutex_unlock(&strerror_r_lock);
168 /* #endif !HAVE_STRERROR_R */
170 #elif STRERROR_R_CHAR_P
173 temp = strerror_r(errnum, buf, buflen);
174 if (buf[0] == '\0') {
175 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
176 sstrncpy(buf, temp, buflen);
178 sstrncpy(buf, "strerror_r did not return "
183 /* #endif STRERROR_R_CHAR_P */
186 if (strerror_r(errnum, buf, buflen) != 0) {
187 snprintf(buf, buflen, "Error #%i; "
188 "Additionally, strerror_r failed.",
191 #endif /* STRERROR_R_CHAR_P */
194 } /* char *sstrerror */
196 void *smalloc(size_t size) {
199 if ((r = malloc(size)) == NULL) {
200 ERROR("Not enough memory.");
205 } /* void *smalloc */
208 void sfree (void **ptr)
220 int sread(int fd, void *buf, size_t count) {
229 status = read(fd, (void *)ptr, nleft);
231 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
238 DEBUG("Received EOF from fd %i. ", fd);
242 assert((0 > status) || (nleft >= (size_t)status));
244 nleft = nleft - ((size_t)status);
245 ptr = ptr + ((size_t)status);
251 int swrite(int fd, const void *buf, size_t count) {
257 ptr = (const char *)buf;
265 /* checking for closed peer connection */
267 pfd.events = POLLIN | POLLHUP;
269 if (poll(&pfd, 1, 0) > 0) {
271 if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
272 /* if recv returns zero (even though poll() said there is data to be
273 * read), that means the connection has been closed */
280 status = write(fd, (const void *)ptr, nleft);
282 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
286 return errno ? errno : status;
288 nleft = nleft - ((size_t)status);
289 ptr = ptr + ((size_t)status);
295 int strsplit(char *string, char **fields, size_t size) {
303 while ((fields[i] = strtok_r(ptr, " \t\r\n", &saveptr)) != NULL) {
314 int strjoin(char *buffer, size_t buffer_size, char **fields, size_t fields_num,
320 size_t buffer_req = 0;
322 if (((fields_num != 0) && (fields == NULL)) ||
323 ((buffer_size != 0) && (buffer == NULL)))
329 if (buffer_size != 0)
330 avail = buffer_size - 1;
333 sep_len = strlen(sep);
335 for (size_t i = 0; i < fields_num; i++) {
336 size_t field_len = strlen(fields[i]);
339 buffer_req += sep_len;
340 buffer_req += field_len;
342 if (buffer_size == 0)
345 if ((i != 0) && (sep_len > 0)) {
346 if (sep_len >= avail) {
347 /* prevent subsequent iterations from writing to the
353 memcpy(ptr, sep, sep_len);
359 if (field_len > avail)
362 memcpy(ptr, fields[i], field_len);
370 return (int)buffer_req;
373 int escape_string(char *buffer, size_t buffer_size) {
377 /* Check if we need to escape at all first */
378 temp = strpbrk(buffer, " \t\"\\");
385 temp = calloc(1, buffer_size);
392 for (size_t i = 0; i < buffer_size; i++) {
393 if (buffer[i] == 0) {
395 } else if ((buffer[i] == '"') || (buffer[i] == '\\')) {
396 if (j > (buffer_size - 4))
399 temp[j + 1] = buffer[i];
402 if (j > (buffer_size - 3))
409 assert((j + 1) < buffer_size);
413 sstrncpy(buffer, temp, buffer_size);
416 } /* int escape_string */
418 int strunescape(char *buf, size_t buf_len) {
419 for (size_t i = 0; (i < buf_len) && (buf[i] != '\0'); ++i) {
423 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
424 P_ERROR("string unescape: backslash found at end of string.");
425 /* Ensure null-byte at the end of the buffer. */
430 switch (buf[i + 1]) {
445 /* Move everything after the position one position to the left.
446 * Add a null-byte as last character in the buffer. */
447 memmove(buf + i + 1, buf + i + 2, buf_len - i - 2);
448 buf[buf_len - 1] = '\0';
451 } /* int strunescape */
453 size_t strstripnewline(char *buffer) {
454 size_t buffer_len = strlen(buffer);
456 while (buffer_len > 0) {
457 if ((buffer[buffer_len - 1] != '\n') && (buffer[buffer_len - 1] != '\r'))
460 buffer[buffer_len] = 0;
464 } /* size_t strstripnewline */
466 int escape_slashes(char *buffer, size_t buffer_size) {
469 buffer_len = strlen(buffer);
471 if (buffer_len <= 1) {
472 if (strcmp("/", buffer) == 0) {
475 sstrncpy(buffer, "root", buffer_size);
480 /* Move one to the left */
481 if (buffer[0] == '/') {
482 memmove(buffer, buffer + 1, buffer_len);
486 for (size_t i = 0; i < buffer_len; i++) {
487 if (buffer[i] == '/')
492 } /* int escape_slashes */
494 void replace_special(char *buffer, size_t buffer_size) {
495 for (size_t i = 0; i < buffer_size; i++) {
498 if ((!isalnum((int)buffer[i])) && (buffer[i] != '-'))
501 } /* void replace_special */
503 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta) {
504 struct timeval *larger;
505 struct timeval *smaller;
509 NORMALIZE_TIMEVAL(tv0);
510 NORMALIZE_TIMEVAL(tv1);
512 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec)) {
520 if ((tv0.tv_sec < tv1.tv_sec) ||
521 ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec))) {
532 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
534 if (smaller->tv_usec <= larger->tv_usec)
535 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
538 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
542 assert((delta == NULL) ||
543 ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
546 } /* int timeval_cmp */
548 int check_create_dir(const char *file_orig) {
551 char file_copy[PATH_MAX];
557 int last_is_file = 1;
558 int path_is_absolute = 0;
562 * Sanity checks first
564 if (file_orig == NULL)
567 if ((len = strlen(file_orig)) < 1)
569 else if (len >= sizeof(file_copy)) {
570 ERROR("check_create_dir: name (%s) is too long.", file_orig);
575 * If `file_orig' ends in a slash the last component is a directory,
576 * otherwise it's a file. Act accordingly..
578 if (file_orig[len - 1] == '/')
580 if (file_orig[0] == '/')
581 path_is_absolute = 1;
584 * Create a copy for `strtok_r' to destroy
586 sstrncpy(file_copy, file_orig, sizeof(file_copy));
589 * Break into components. This will eat up several slashes in a row and
590 * remove leading and trailing slashes..
595 while ((fields[fields_num] = strtok_r(ptr, "/", &saveptr)) != NULL) {
599 if (fields_num >= 16)
604 * For each component, do..
606 for (int i = 0; i < (fields_num - last_is_file); i++) {
608 * Do not create directories that start with a dot. This
609 * prevents `../../' attacks and other likely malicious
612 if (fields[i][0] == '.') {
613 P_ERROR("Cowardly refusing to create a directory that "
614 "begins with a `.' (dot): `%s'",
620 * Join the components together again
623 if (strjoin(dir + path_is_absolute,
624 (size_t)(sizeof(dir) - path_is_absolute), fields,
625 (size_t)(i + 1), "/") < 0) {
626 P_ERROR("strjoin failed: `%s', component #%i", file_orig, i);
631 if ((stat(dir, &statbuf) == -1) && (lstat(dir, &statbuf) == -1)) {
632 if (errno == ENOENT) {
633 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
636 /* this might happen, if a different thread created
637 * the directory in the meantime
638 * => call stat() again to check for S_ISDIR() */
642 P_ERROR("check_create_dir: mkdir (%s): %s", dir, STRERRNO);
645 P_ERROR("check_create_dir: stat (%s): %s", dir, STRERRNO);
648 } else if (!S_ISDIR(statbuf.st_mode)) {
649 P_ERROR("check_create_dir: `%s' exists but is not "
659 } /* check_create_dir */
662 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name) {
670 snprintf(ident, sizeof(ident), "%s,%i,%s", module, instance, name);
672 *ksp_ptr = kstat_lookup(kc, module, instance, name);
673 if (*ksp_ptr == NULL) {
674 P_ERROR("get_kstat: Cound not find kstat %s", ident);
678 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
679 P_ERROR("get_kstat: kstat %s has wrong type", ident);
685 assert(*ksp_ptr != NULL);
686 assert((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
689 if (kstat_read(kc, *ksp_ptr, NULL) == -1) {
690 P_ERROR("get_kstat: kstat %s could not be read", ident);
694 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
695 P_ERROR("get_kstat: kstat %s has wrong type", ident);
702 long long get_kstat_value(kstat_t *ksp, char *name) {
704 long long retval = -1LL;
707 P_ERROR("get_kstat_value (\"%s\"): ksp is NULL.", name);
709 } else if (ksp->ks_type != KSTAT_TYPE_NAMED) {
710 P_ERROR("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
711 "is not KSTAT_TYPE_NAMED (%#x).",
712 name, (unsigned int)ksp->ks_type, (unsigned int)KSTAT_TYPE_NAMED);
716 if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, name)) == NULL)
719 if (kn->data_type == KSTAT_DATA_INT32)
720 retval = (long long)kn->value.i32;
721 else if (kn->data_type == KSTAT_DATA_UINT32)
722 retval = (long long)kn->value.ui32;
723 else if (kn->data_type == KSTAT_DATA_INT64)
725 (long long)kn->value.i64; /* According to ANSI C99 `long long' must hold
727 else if (kn->data_type == KSTAT_DATA_UINT64)
728 retval = (long long)kn->value.ui64; /* XXX: Might overflow! */
730 P_WARNING("get_kstat_value: Not a numeric value: %s", name);
734 #endif /* HAVE_LIBKSTAT */
737 unsigned long long ntohll(unsigned long long n) {
738 #if BYTE_ORDER == BIG_ENDIAN
741 return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
743 } /* unsigned long long ntohll */
745 unsigned long long htonll(unsigned long long n) {
746 #if BYTE_ORDER == BIG_ENDIAN
749 return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
751 } /* unsigned long long htonll */
752 #endif /* HAVE_HTONLL */
754 #if FP_LAYOUT_NEED_NOTHING
755 /* Well, we need nothing.. */
756 /* #endif FP_LAYOUT_NEED_NOTHING */
758 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
759 #if FP_LAYOUT_NEED_ENDIANFLIP
760 #define FP_CONVERT(A) \
761 ((((uint64_t)(A)&0xff00000000000000LL) >> 56) | \
762 (((uint64_t)(A)&0x00ff000000000000LL) >> 40) | \
763 (((uint64_t)(A)&0x0000ff0000000000LL) >> 24) | \
764 (((uint64_t)(A)&0x000000ff00000000LL) >> 8) | \
765 (((uint64_t)(A)&0x00000000ff000000LL) << 8) | \
766 (((uint64_t)(A)&0x0000000000ff0000LL) << 24) | \
767 (((uint64_t)(A)&0x000000000000ff00LL) << 40) | \
768 (((uint64_t)(A)&0x00000000000000ffLL) << 56))
770 #define FP_CONVERT(A) \
771 ((((uint64_t)(A)&0xffffffff00000000LL) >> 32) | \
772 (((uint64_t)(A)&0x00000000ffffffffLL) << 32))
775 double ntohd(double d) {
784 /* NAN in x86 byte order */
785 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00) && (ret.byte[2] == 0x00) &&
786 (ret.byte[3] == 0x00) && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00) &&
787 (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f)) {
793 ret.integer = FP_CONVERT(tmp);
798 double htond(double d) {
806 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
807 ret.byte[4] = ret.byte[5] = 0x00;
815 tmp = FP_CONVERT(ret.integer);
820 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
822 int format_name(char *ret, int ret_len, const char *hostname,
823 const char *plugin, const char *plugin_instance,
824 const char *type, const char *type_instance) {
829 buffer_size = (size_t)ret_len;
831 #define APPEND(str) \
833 size_t l = strlen(str); \
834 if (l >= buffer_size) \
836 memcpy(buffer, (str), l); \
841 assert(plugin != NULL);
842 assert(type != NULL);
847 if ((plugin_instance != NULL) && (plugin_instance[0] != 0)) {
849 APPEND(plugin_instance);
853 if ((type_instance != NULL) && (type_instance[0] != 0)) {
855 APPEND(type_instance);
857 assert(buffer_size > 0);
862 } /* int format_name */
864 int format_values(char *ret, size_t ret_len, /* {{{ */
865 const data_set_t *ds, const value_list_t *vl,
869 gauge_t *rates = NULL;
871 assert(0 == strcmp(ds->type, vl->type));
873 memset(ret, 0, ret_len);
875 #define BUFFER_ADD(...) \
877 status = snprintf(ret + offset, ret_len - offset, __VA_ARGS__); \
881 } else if (((size_t)status) >= (ret_len - offset)) { \
885 offset += ((size_t)status); \
888 BUFFER_ADD("%.3f", CDTIME_T_TO_DOUBLE(vl->time));
890 for (size_t i = 0; i < ds->ds_num; i++) {
891 if (ds->ds[i].type == DS_TYPE_GAUGE)
892 BUFFER_ADD(":" GAUGE_FORMAT, vl->values[i].gauge);
893 else if (store_rates) {
895 rates = uc_get_rate(ds, vl);
897 WARNING("format_values: uc_get_rate failed.");
900 BUFFER_ADD(":" GAUGE_FORMAT, rates[i]);
901 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
902 BUFFER_ADD(":%" PRIu64, (uint64_t)vl->values[i].counter);
903 else if (ds->ds[i].type == DS_TYPE_DERIVE)
904 BUFFER_ADD(":%" PRIi64, vl->values[i].derive);
905 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
906 BUFFER_ADD(":%" PRIu64, vl->values[i].absolute);
908 ERROR("format_values: Unknown data source type: %i", ds->ds[i].type);
912 } /* for ds->ds_num */
918 } /* }}} int format_values */
920 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
921 char **ret_plugin_instance, char **ret_type,
922 char **ret_type_instance, char *default_host) {
923 char *hostname = NULL;
925 char *plugin_instance = NULL;
927 char *type_instance = NULL;
930 if (hostname == NULL)
933 plugin = strchr(hostname, '/');
939 type = strchr(plugin, '/');
941 if (default_host == NULL)
943 /* else: no host specified; use default */
946 hostname = default_host;
952 plugin_instance = strchr(plugin, '-');
953 if (plugin_instance != NULL) {
954 *plugin_instance = '\0';
958 type_instance = strchr(type, '-');
959 if (type_instance != NULL) {
960 *type_instance = '\0';
964 *ret_host = hostname;
965 *ret_plugin = plugin;
966 *ret_plugin_instance = plugin_instance;
968 *ret_type_instance = type_instance;
970 } /* int parse_identifier */
972 int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
974 char str_copy[6 * DATA_MAX_NAME_LEN];
977 char *plugin_instance = NULL;
979 char *type_instance = NULL;
982 if ((str == NULL) || (vl == NULL))
985 sstrncpy(str_copy, str, sizeof(str_copy));
987 status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
989 /* default_host = */ NULL);
993 sstrncpy(vl->host, host, sizeof(vl->host));
994 sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
995 sstrncpy(vl->plugin_instance,
996 (plugin_instance != NULL) ? plugin_instance : "",
997 sizeof(vl->plugin_instance));
998 sstrncpy(vl->type, type, sizeof(vl->type));
999 sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
1000 sizeof(vl->type_instance));
1003 } /* }}} int parse_identifier_vl */
1005 int parse_value(const char *value_orig, value_t *ret_value, int ds_type) {
1007 char *endptr = NULL;
1010 if (value_orig == NULL)
1013 value = strdup(value_orig);
1016 value_len = strlen(value);
1018 while ((value_len > 0) && isspace((int)value[value_len - 1])) {
1019 value[value_len - 1] = '\0';
1024 case DS_TYPE_COUNTER:
1025 ret_value->counter = (counter_t)strtoull(value, &endptr, 0);
1029 ret_value->gauge = (gauge_t)strtod(value, &endptr);
1032 case DS_TYPE_DERIVE:
1033 ret_value->derive = (derive_t)strtoll(value, &endptr, 0);
1036 case DS_TYPE_ABSOLUTE:
1037 ret_value->absolute = (absolute_t)strtoull(value, &endptr, 0);
1042 P_ERROR("parse_value: Invalid data source type: %i.", ds_type);
1046 if (value == endptr) {
1047 P_ERROR("parse_value: Failed to parse string as %s: \"%s\".",
1048 DS_TYPE_TO_STRING(ds_type), value);
1051 } else if ((NULL != endptr) && ('\0' != *endptr))
1052 P_INFO("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1053 "Input string was \"%s\".",
1054 endptr, DS_TYPE_TO_STRING(ds_type), value_orig);
1058 } /* int parse_value */
1060 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds) {
1066 if ((buffer == NULL) || (vl == NULL) || (ds == NULL))
1073 while ((ptr = strtok_r(dummy, ":", &saveptr)) != NULL) {
1076 if (i >= vl->values_len) {
1077 /* Make sure i is invalid. */
1082 if (vl->time == 0) {
1083 if (strcmp("N", ptr) == 0)
1084 vl->time = cdtime();
1086 char *endptr = NULL;
1090 tmp = strtod(ptr, &endptr);
1091 if ((errno != 0) /* Overflow */
1092 || (endptr == ptr) /* Invalid string */
1093 || (endptr == NULL) /* This should not happen */
1094 || (*endptr != 0)) /* Trailing chars */
1097 vl->time = DOUBLE_TO_CDTIME_T(tmp);
1103 if ((strcmp("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1104 vl->values[i].gauge = NAN;
1105 else if (0 != parse_value(ptr, &vl->values[i], ds->ds[i].type))
1109 } /* while (strtok_r) */
1111 if ((ptr != NULL) || (i == 0))
1114 } /* int parse_values */
1116 int parse_value_file(char const *path, value_t *ret_value, int ds_type) {
1120 fh = fopen(path, "r");
1124 if (fgets(buffer, sizeof(buffer), fh) == NULL) {
1131 strstripnewline(buffer);
1133 return parse_value(buffer, ret_value, ds_type);
1134 } /* int parse_value_file */
1136 #if !HAVE_GETPWNAM_R
1137 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
1138 struct passwd **pwbufp) {
1139 #ifndef HAVE_GETPWNAM
1145 memset(pwbuf, '\0', sizeof(struct passwd));
1147 pthread_mutex_lock(&getpwnam_r_lock);
1150 pw = getpwnam(name);
1152 status = (errno != 0) ? errno : ENOENT;
1156 #define GETPWNAM_COPY_MEMBER(member) \
1157 if (pw->member != NULL) { \
1158 int len = strlen(pw->member); \
1159 if (len >= buflen) { \
1163 sstrncpy(buf, pw->member, buflen); \
1164 pwbuf->member = buf; \
1166 buflen -= (len + 1); \
1168 GETPWNAM_COPY_MEMBER(pw_name);
1169 GETPWNAM_COPY_MEMBER(pw_passwd);
1170 GETPWNAM_COPY_MEMBER(pw_gecos);
1171 GETPWNAM_COPY_MEMBER(pw_dir);
1172 GETPWNAM_COPY_MEMBER(pw_shell);
1174 pwbuf->pw_uid = pw->pw_uid;
1175 pwbuf->pw_gid = pw->pw_gid;
1181 pthread_mutex_unlock(&getpwnam_r_lock);
1184 #endif /* HAVE_GETPWNAM */
1185 } /* int getpwnam_r */
1186 #endif /* !HAVE_GETPWNAM_R */
1188 int notification_init(notification_t *n, int severity, const char *message,
1189 const char *host, const char *plugin,
1190 const char *plugin_instance, const char *type,
1191 const char *type_instance) {
1192 memset(n, '\0', sizeof(notification_t));
1194 n->severity = severity;
1196 if (message != NULL)
1197 sstrncpy(n->message, message, sizeof(n->message));
1199 sstrncpy(n->host, host, sizeof(n->host));
1201 sstrncpy(n->plugin, plugin, sizeof(n->plugin));
1202 if (plugin_instance != NULL)
1203 sstrncpy(n->plugin_instance, plugin_instance, sizeof(n->plugin_instance));
1205 sstrncpy(n->type, type, sizeof(n->type));
1206 if (type_instance != NULL)
1207 sstrncpy(n->type_instance, type_instance, sizeof(n->type_instance));
1210 } /* int notification_init */
1212 int walk_directory(const char *dir, dirwalk_callback_f callback,
1213 void *user_data, int include_hidden) {
1222 if ((dh = opendir(dir)) == NULL) {
1223 P_ERROR("walk_directory: Cannot open '%s': %s", dir, STRERRNO);
1227 while ((ent = readdir(dh)) != NULL) {
1230 if (include_hidden) {
1231 if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0))
1233 } else /* if (!include_hidden) */
1235 if (ent->d_name[0] == '.')
1239 status = (*callback)(dir, ent->d_name, user_data);
1248 if ((success == 0) && (failure > 0))
1253 ssize_t read_file_contents(const char *filename, char *buf, size_t bufsize) {
1257 fh = fopen(filename, "r");
1261 ret = (ssize_t)fread(buf, 1, bufsize, fh);
1262 if ((ret == 0) && (ferror(fh) != 0)) {
1263 P_ERROR("read_file_contents: Reading file \"%s\" failed.", filename);
1271 counter_t counter_diff(counter_t old_value, counter_t new_value) {
1274 if (old_value > new_value) {
1275 if (old_value <= 4294967295U)
1276 diff = (4294967295U - old_value) + new_value + 1;
1278 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1280 diff = new_value - old_value;
1284 } /* counter_t counter_diff */
1286 int rate_to_value(value_t *ret_value, gauge_t rate, /* {{{ */
1287 rate_to_value_state_t *state, int ds_type, cdtime_t t) {
1288 gauge_t delta_gauge;
1291 if (ds_type == DS_TYPE_GAUGE) {
1292 state->last_value.gauge = rate;
1293 state->last_time = t;
1295 *ret_value = state->last_value;
1299 /* Counter and absolute can't handle negative rates. Reset "last time"
1300 * to zero, so that the next valid rate will re-initialize the
1303 ((ds_type == DS_TYPE_COUNTER) || (ds_type == DS_TYPE_ABSOLUTE))) {
1304 memset(state, 0, sizeof(*state));
1308 /* Another invalid state: The time is not increasing. */
1309 if (t <= state->last_time) {
1310 memset(state, 0, sizeof(*state));
1314 delta_t = t - state->last_time;
1315 delta_gauge = (rate * CDTIME_T_TO_DOUBLE(delta_t)) + state->residual;
1317 /* Previous value is invalid. */
1318 if (state->last_time == 0) /* {{{ */
1320 if (ds_type == DS_TYPE_DERIVE) {
1321 state->last_value.derive = (derive_t)rate;
1322 state->residual = rate - ((gauge_t)state->last_value.derive);
1323 } else if (ds_type == DS_TYPE_COUNTER) {
1324 state->last_value.counter = (counter_t)rate;
1325 state->residual = rate - ((gauge_t)state->last_value.counter);
1326 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1327 state->last_value.absolute = (absolute_t)rate;
1328 state->residual = rate - ((gauge_t)state->last_value.absolute);
1333 state->last_time = t;
1337 if (ds_type == DS_TYPE_DERIVE) {
1338 derive_t delta_derive = (derive_t)delta_gauge;
1340 state->last_value.derive += delta_derive;
1341 state->residual = delta_gauge - ((gauge_t)delta_derive);
1342 } else if (ds_type == DS_TYPE_COUNTER) {
1343 counter_t delta_counter = (counter_t)delta_gauge;
1345 state->last_value.counter += delta_counter;
1346 state->residual = delta_gauge - ((gauge_t)delta_counter);
1347 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1348 absolute_t delta_absolute = (absolute_t)delta_gauge;
1350 state->last_value.absolute = delta_absolute;
1351 state->residual = delta_gauge - ((gauge_t)delta_absolute);
1356 state->last_time = t;
1357 *ret_value = state->last_value;
1359 } /* }}} value_t rate_to_value */
1361 int value_to_rate(gauge_t *ret_rate, /* {{{ */
1362 value_t value, int ds_type, cdtime_t t,
1363 value_to_rate_state_t *state) {
1366 /* Another invalid state: The time is not increasing. */
1367 if (t <= state->last_time) {
1368 memset(state, 0, sizeof(*state));
1372 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1374 /* Previous value is invalid. */
1375 if (state->last_time == 0) {
1376 state->last_value = value;
1377 state->last_time = t;
1382 case DS_TYPE_DERIVE: {
1383 derive_t diff = value.derive - state->last_value.derive;
1384 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1387 case DS_TYPE_GAUGE: {
1388 *ret_rate = value.gauge;
1391 case DS_TYPE_COUNTER: {
1392 counter_t diff = counter_diff(state->last_value.counter, value.counter);
1393 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1396 case DS_TYPE_ABSOLUTE: {
1397 absolute_t diff = value.absolute;
1398 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1405 state->last_value = value;
1406 state->last_time = t;
1408 } /* }}} value_t rate_to_value */
1410 int service_name_to_port_number(const char *service_name) {
1411 struct addrinfo *ai_list;
1415 if (service_name == NULL)
1418 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC};
1420 status = getaddrinfo(/* node = */ NULL, service_name, &ai_hints, &ai_list);
1422 P_ERROR("service_name_to_port_number: getaddrinfo failed: %s",
1423 gai_strerror(status));
1427 service_number = -1;
1428 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1429 ai_ptr = ai_ptr->ai_next) {
1430 if (ai_ptr->ai_family == AF_INET) {
1431 struct sockaddr_in *sa;
1433 sa = (void *)ai_ptr->ai_addr;
1434 service_number = (int)ntohs(sa->sin_port);
1435 } else if (ai_ptr->ai_family == AF_INET6) {
1436 struct sockaddr_in6 *sa;
1438 sa = (void *)ai_ptr->ai_addr;
1439 service_number = (int)ntohs(sa->sin6_port);
1442 if ((service_number > 0) && (service_number <= 65535))
1446 freeaddrinfo(ai_list);
1448 if ((service_number > 0) && (service_number <= 65535))
1449 return service_number;
1451 } /* int service_name_to_port_number */
1453 void set_sock_opts(int sockfd) /* {{{ */
1458 status = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &socktype,
1459 &(socklen_t){sizeof(socktype)});
1461 P_WARNING("set_sock_opts: failed to determine socket type");
1465 if (socktype == SOCK_STREAM) {
1467 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int));
1469 P_WARNING("set_sock_opts: failed to set socket keepalive flag");
1472 int tcp_keepidle = ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 100 + 1);
1473 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &tcp_keepidle,
1474 sizeof(tcp_keepidle));
1476 P_WARNING("set_sock_opts: failed to set socket tcp keepalive time");
1479 #ifdef TCP_KEEPINTVL
1481 ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 1000 + 1);
1482 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &tcp_keepintvl,
1483 sizeof(tcp_keepintvl));
1485 P_WARNING("set_sock_opts: failed to set socket tcp keepalive interval");
1488 } /* }}} void set_sock_opts */
1490 int strtoderive(const char *string, derive_t *ret_value) /* {{{ */
1495 if ((string == NULL) || (ret_value == NULL))
1500 tmp = (derive_t)strtoll(string, &endptr, /* base = */ 0);
1501 if ((endptr == string) || (errno != 0))
1506 } /* }}} int strtoderive */
1508 int strtogauge(const char *string, gauge_t *ret_value) /* {{{ */
1511 char *endptr = NULL;
1513 if ((string == NULL) || (ret_value == NULL))
1518 tmp = (gauge_t)strtod(string, &endptr);
1521 else if ((endptr == NULL) || (*endptr != 0))
1526 } /* }}} int strtogauge */
1528 int strarray_add(char ***ret_array, size_t *ret_array_len,
1529 char const *str) /* {{{ */
1532 size_t array_len = *ret_array_len;
1537 array = realloc(*ret_array, (array_len + 1) * sizeof(*array));
1542 array[array_len] = strdup(str);
1543 if (array[array_len] == NULL)
1547 *ret_array_len = array_len;
1549 } /* }}} int strarray_add */
1551 void strarray_free(char **array, size_t array_len) /* {{{ */
1553 for (size_t i = 0; i < array_len; i++)
1556 } /* }}} void strarray_free */
1559 int check_capability(int arg) /* {{{ */
1561 cap_value_t cap_value = (cap_value_t)arg;
1563 cap_flag_value_t cap_flag_value;
1565 if (!CAP_IS_SUPPORTED(cap_value))
1568 if (!(cap = cap_get_proc())) {
1569 P_ERROR("check_capability: cap_get_proc failed.");
1573 if (cap_get_flag(cap, cap_value, CAP_EFFECTIVE, &cap_flag_value) < 0) {
1574 P_ERROR("check_capability: cap_get_flag failed.");
1580 return cap_flag_value != CAP_SET;
1581 } /* }}} int check_capability */
1583 int check_capability(__attribute__((unused)) int arg) /* {{{ */
1585 P_WARNING("check_capability: unsupported capability implementation. "
1586 "Some plugin(s) may require elevated privileges to work properly.");
1588 } /* }}} int check_capability */
1589 #endif /* HAVE_CAPABILITY */