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>
38 #include "utils_cache.h"
42 #include <sys/types.h>
47 #include <netinet/in.h>
50 #if HAVE_NETINET_TCP_H
51 #include <netinet/tcp.h>
54 /* for ntohl and htonl */
56 #include <arpa/inet.h>
60 #include <sys/capability.h>
68 extern kstat_ctl_t *kc;
71 /* AIX doesn't have MSG_DONTWAIT */
73 #define MSG_DONTWAIT MSG_NONBLOCK
77 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
81 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
84 char *sstrncpy(char *dest, const char *src, size_t n) {
85 strncpy(dest, src, n);
89 } /* char *sstrncpy */
91 char *ssnprintf_alloc(char const *format, ...) /* {{{ */
93 char static_buffer[1024] = "";
95 size_t alloc_buffer_size;
99 /* Try printing into the static buffer. In many cases it will be
100 * sufficiently large and we can simply return a strdup() of this
102 va_start(ap, format);
103 status = vsnprintf(static_buffer, sizeof(static_buffer), format, ap);
108 /* "status" does not include the null byte. */
109 alloc_buffer_size = (size_t)(status + 1);
110 if (alloc_buffer_size <= sizeof(static_buffer))
111 return strdup(static_buffer);
113 /* Allocate a buffer large enough to hold the string. */
114 alloc_buffer = calloc(1, alloc_buffer_size);
115 if (alloc_buffer == NULL)
118 /* Print again into this new buffer. */
119 va_start(ap, format);
120 status = vsnprintf(alloc_buffer, alloc_buffer_size, format, ap);
128 } /* }}} char *ssnprintf_alloc */
130 char *sstrdup(const char *s) {
137 /* Do not use `strdup' here, because it's not specified in POSIX. It's
138 * ``only'' an XSI extension. */
142 ERROR("sstrdup: Out of memory.");
148 } /* char *sstrdup */
150 /* Even though Posix requires "strerror_r" to return an "int",
151 * some systems (e.g. the GNU libc) return a "char *" _and_
152 * ignore the second argument ... -tokkee */
153 char *sstrerror(int errnum, char *buf, size_t buflen) {
160 pthread_mutex_lock(&strerror_r_lock);
162 temp = strerror(errnum);
163 sstrncpy(buf, temp, buflen);
165 pthread_mutex_unlock(&strerror_r_lock);
167 /* #endif !HAVE_STRERROR_R */
169 #elif STRERROR_R_CHAR_P
172 temp = strerror_r(errnum, buf, buflen);
173 if (buf[0] == '\0') {
174 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
175 sstrncpy(buf, temp, buflen);
177 sstrncpy(buf, "strerror_r did not return "
182 /* #endif STRERROR_R_CHAR_P */
185 if (strerror_r(errnum, buf, buflen) != 0) {
186 snprintf(buf, buflen, "Error #%i; "
187 "Additionally, strerror_r failed.",
190 #endif /* STRERROR_R_CHAR_P */
193 } /* char *sstrerror */
195 void *smalloc(size_t size) {
198 if ((r = malloc(size)) == NULL) {
199 ERROR("Not enough memory.");
204 } /* void *smalloc */
207 void sfree (void **ptr)
219 int sread(int fd, void *buf, size_t count) {
228 status = read(fd, (void *)ptr, nleft);
230 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
237 DEBUG("Received EOF from fd %i. ", fd);
241 assert((0 > status) || (nleft >= (size_t)status));
243 nleft = nleft - ((size_t)status);
244 ptr = ptr + ((size_t)status);
250 int swrite(int fd, const void *buf, size_t count) {
256 ptr = (const char *)buf;
264 /* checking for closed peer connection */
266 pfd.events = POLLIN | POLLHUP;
268 if (poll(&pfd, 1, 0) > 0) {
270 if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
271 /* if recv returns zero (even though poll() said there is data to be
272 * read), that means the connection has been closed */
279 status = write(fd, (const void *)ptr, nleft);
281 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
285 return errno ? errno : status;
287 nleft = nleft - ((size_t)status);
288 ptr = ptr + ((size_t)status);
294 int strsplit(char *string, char **fields, size_t size) {
302 while ((fields[i] = strtok_r(ptr, " \t\r\n", &saveptr)) != NULL) {
313 int strjoin(char *buffer, size_t buffer_size, char **fields, size_t fields_num,
319 size_t buffer_req = 0;
321 if (((fields_num != 0) && (fields == NULL)) ||
322 ((buffer_size != 0) && (buffer == NULL)))
328 if (buffer_size != 0)
329 avail = buffer_size - 1;
332 sep_len = strlen(sep);
334 for (size_t i = 0; i < fields_num; i++) {
335 size_t field_len = strlen(fields[i]);
338 buffer_req += sep_len;
339 buffer_req += field_len;
341 if (buffer_size == 0)
344 if ((i != 0) && (sep_len > 0)) {
345 if (sep_len >= avail) {
346 /* prevent subsequent iterations from writing to the
352 memcpy(ptr, sep, sep_len);
358 if (field_len > avail)
361 memcpy(ptr, fields[i], field_len);
369 return (int)buffer_req;
372 int escape_string(char *buffer, size_t buffer_size) {
376 /* Check if we need to escape at all first */
377 temp = strpbrk(buffer, " \t\"\\");
384 temp = calloc(1, buffer_size);
391 for (size_t i = 0; i < buffer_size; i++) {
392 if (buffer[i] == 0) {
394 } else if ((buffer[i] == '"') || (buffer[i] == '\\')) {
395 if (j > (buffer_size - 4))
398 temp[j + 1] = buffer[i];
401 if (j > (buffer_size - 3))
408 assert((j + 1) < buffer_size);
412 sstrncpy(buffer, temp, buffer_size);
415 } /* int escape_string */
417 int strunescape(char *buf, size_t buf_len) {
418 for (size_t i = 0; (i < buf_len) && (buf[i] != '\0'); ++i) {
422 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
423 ERROR("string unescape: backslash found at end of string.");
424 /* Ensure null-byte at the end of the buffer. */
429 switch (buf[i + 1]) {
444 /* Move everything after the position one position to the left.
445 * Add a null-byte as last character in the buffer. */
446 memmove(buf + i + 1, buf + i + 2, buf_len - i - 2);
447 buf[buf_len - 1] = 0;
450 } /* int strunescape */
452 size_t strstripnewline(char *buffer) {
453 size_t buffer_len = strlen(buffer);
455 while (buffer_len > 0) {
456 if ((buffer[buffer_len - 1] != '\n') && (buffer[buffer_len - 1] != '\r'))
459 buffer[buffer_len] = 0;
463 } /* size_t strstripnewline */
465 int escape_slashes(char *buffer, size_t buffer_size) {
468 buffer_len = strlen(buffer);
470 if (buffer_len <= 1) {
471 if (strcmp("/", buffer) == 0) {
474 sstrncpy(buffer, "root", buffer_size);
479 /* Move one to the left */
480 if (buffer[0] == '/') {
481 memmove(buffer, buffer + 1, buffer_len);
485 for (size_t i = 0; i < buffer_len; i++) {
486 if (buffer[i] == '/')
491 } /* int escape_slashes */
493 void replace_special(char *buffer, size_t buffer_size) {
494 for (size_t i = 0; i < buffer_size; i++) {
497 if ((!isalnum((int)buffer[i])) && (buffer[i] != '-'))
500 } /* void replace_special */
502 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta) {
503 struct timeval *larger;
504 struct timeval *smaller;
508 NORMALIZE_TIMEVAL(tv0);
509 NORMALIZE_TIMEVAL(tv1);
511 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec)) {
519 if ((tv0.tv_sec < tv1.tv_sec) ||
520 ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec))) {
531 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
533 if (smaller->tv_usec <= larger->tv_usec)
534 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
537 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
541 assert((delta == NULL) ||
542 ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
545 } /* int timeval_cmp */
547 int check_create_dir(const char *file_orig) {
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))
573 * If `file_orig' ends in a slash the last component is a directory,
574 * otherwise it's a file. Act accordingly..
576 if (file_orig[len - 1] == '/')
578 if (file_orig[0] == '/')
579 path_is_absolute = 1;
582 * Create a copy for `strtok_r' to destroy
584 sstrncpy(file_copy, file_orig, sizeof(file_copy));
587 * Break into components. This will eat up several slashes in a row and
588 * remove leading and trailing slashes..
593 while ((fields[fields_num] = strtok_r(ptr, "/", &saveptr)) != NULL) {
597 if (fields_num >= 16)
602 * For each component, do..
604 for (int i = 0; i < (fields_num - last_is_file); i++) {
606 * Do not create directories that start with a dot. This
607 * prevents `../../' attacks and other likely malicious
610 if (fields[i][0] == '.') {
611 ERROR("Cowardly refusing to create a directory that "
612 "begins with a `.' (dot): `%s'",
618 * Join the components together again
621 if (strjoin(dir + path_is_absolute, (size_t)(dir_len - path_is_absolute),
622 fields, (size_t)(i + 1), "/") < 0) {
623 ERROR("strjoin failed: `%s', component #%i", file_orig, i);
628 if ((stat(dir, &statbuf) == -1) && (lstat(dir, &statbuf) == -1)) {
629 if (errno == ENOENT) {
630 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
633 /* this might happen, if a different thread created
634 * the directory in the meantime
635 * => call stat() again to check for S_ISDIR() */
640 ERROR("check_create_dir: mkdir (%s): %s", dir,
641 sstrerror(errno, errbuf, sizeof(errbuf)));
645 ERROR("check_create_dir: stat (%s): %s", dir,
646 sstrerror(errno, errbuf, sizeof(errbuf)));
649 } else if (!S_ISDIR(statbuf.st_mode)) {
650 ERROR("check_create_dir: `%s' exists but is not "
660 } /* check_create_dir */
663 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name) {
671 snprintf(ident, sizeof(ident), "%s,%i,%s", module, instance, name);
673 *ksp_ptr = kstat_lookup(kc, module, instance, name);
674 if (*ksp_ptr == NULL) {
675 ERROR("get_kstat: Cound not find kstat %s", ident);
679 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
680 ERROR("get_kstat: kstat %s has wrong type", ident);
686 assert(*ksp_ptr != NULL);
687 assert((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
690 if (kstat_read(kc, *ksp_ptr, NULL) == -1) {
691 ERROR("get_kstat: kstat %s could not be read", ident);
695 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
696 ERROR("get_kstat: kstat %s has wrong type", ident);
703 long long get_kstat_value(kstat_t *ksp, char *name) {
705 long long retval = -1LL;
708 ERROR("get_kstat_value (\"%s\"): ksp is NULL.", name);
710 } else if (ksp->ks_type != KSTAT_TYPE_NAMED) {
711 ERROR("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
712 "is not KSTAT_TYPE_NAMED (%#x).",
713 name, (unsigned int)ksp->ks_type, (unsigned int)KSTAT_TYPE_NAMED);
717 if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, name)) == NULL)
720 if (kn->data_type == KSTAT_DATA_INT32)
721 retval = (long long)kn->value.i32;
722 else if (kn->data_type == KSTAT_DATA_UINT32)
723 retval = (long long)kn->value.ui32;
724 else if (kn->data_type == KSTAT_DATA_INT64)
726 (long long)kn->value.i64; /* According to ANSI C99 `long long' must hold
728 else if (kn->data_type == KSTAT_DATA_UINT64)
729 retval = (long long)kn->value.ui64; /* XXX: Might overflow! */
731 WARNING("get_kstat_value: Not a numeric value: %s", name);
735 #endif /* HAVE_LIBKSTAT */
738 unsigned long long ntohll(unsigned long long n) {
739 #if BYTE_ORDER == BIG_ENDIAN
742 return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
744 } /* unsigned long long ntohll */
746 unsigned long long htonll(unsigned long long n) {
747 #if BYTE_ORDER == BIG_ENDIAN
750 return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
752 } /* unsigned long long htonll */
753 #endif /* HAVE_HTONLL */
755 #if FP_LAYOUT_NEED_NOTHING
756 /* Well, we need nothing.. */
757 /* #endif FP_LAYOUT_NEED_NOTHING */
759 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
760 #if FP_LAYOUT_NEED_ENDIANFLIP
761 #define FP_CONVERT(A) \
762 ((((uint64_t)(A)&0xff00000000000000LL) >> 56) | \
763 (((uint64_t)(A)&0x00ff000000000000LL) >> 40) | \
764 (((uint64_t)(A)&0x0000ff0000000000LL) >> 24) | \
765 (((uint64_t)(A)&0x000000ff00000000LL) >> 8) | \
766 (((uint64_t)(A)&0x00000000ff000000LL) << 8) | \
767 (((uint64_t)(A)&0x0000000000ff0000LL) << 24) | \
768 (((uint64_t)(A)&0x000000000000ff00LL) << 40) | \
769 (((uint64_t)(A)&0x00000000000000ffLL) << 56))
771 #define FP_CONVERT(A) \
772 ((((uint64_t)(A)&0xffffffff00000000LL) >> 32) | \
773 (((uint64_t)(A)&0x00000000ffffffffLL) << 32))
776 double ntohd(double d) {
785 /* NAN in x86 byte order */
786 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00) && (ret.byte[2] == 0x00) &&
787 (ret.byte[3] == 0x00) && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00) &&
788 (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f)) {
794 ret.integer = FP_CONVERT(tmp);
799 double htond(double d) {
807 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
808 ret.byte[4] = ret.byte[5] = 0x00;
816 tmp = FP_CONVERT(ret.integer);
821 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
823 int format_name(char *ret, int ret_len, const char *hostname,
824 const char *plugin, const char *plugin_instance,
825 const char *type, const char *type_instance) {
830 buffer_size = (size_t)ret_len;
832 #define APPEND(str) \
834 size_t l = strlen(str); \
835 if (l >= buffer_size) \
837 memcpy(buffer, (str), l); \
842 assert(plugin != NULL);
843 assert(type != NULL);
848 if ((plugin_instance != NULL) && (plugin_instance[0] != 0)) {
850 APPEND(plugin_instance);
854 if ((type_instance != NULL) && (type_instance[0] != 0)) {
856 APPEND(type_instance);
858 assert(buffer_size > 0);
863 } /* int format_name */
865 int format_values(char *ret, size_t ret_len, /* {{{ */
866 const data_set_t *ds, const value_list_t *vl,
870 gauge_t *rates = NULL;
872 assert(0 == strcmp(ds->type, vl->type));
874 memset(ret, 0, ret_len);
876 #define BUFFER_ADD(...) \
878 status = snprintf(ret + offset, ret_len - offset, __VA_ARGS__); \
882 } else if (((size_t)status) >= (ret_len - offset)) { \
886 offset += ((size_t)status); \
889 BUFFER_ADD("%.3f", CDTIME_T_TO_DOUBLE(vl->time));
891 for (size_t i = 0; i < ds->ds_num; i++) {
892 if (ds->ds[i].type == DS_TYPE_GAUGE)
893 BUFFER_ADD(":" GAUGE_FORMAT, vl->values[i].gauge);
894 else if (store_rates) {
896 rates = uc_get_rate(ds, vl);
898 WARNING("format_values: uc_get_rate failed.");
901 BUFFER_ADD(":" GAUGE_FORMAT, rates[i]);
902 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
903 BUFFER_ADD(":%llu", vl->values[i].counter);
904 else if (ds->ds[i].type == DS_TYPE_DERIVE)
905 BUFFER_ADD(":%" PRIi64, vl->values[i].derive);
906 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
907 BUFFER_ADD(":%" PRIu64, vl->values[i].absolute);
909 ERROR("format_values: Unknown data source type: %i", ds->ds[i].type);
913 } /* for ds->ds_num */
919 } /* }}} int format_values */
921 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
922 char **ret_plugin_instance, char **ret_type,
923 char **ret_type_instance, char *default_host) {
924 char *hostname = NULL;
926 char *plugin_instance = NULL;
928 char *type_instance = NULL;
931 if (hostname == NULL)
934 plugin = strchr(hostname, '/');
940 type = strchr(plugin, '/');
942 if (default_host == NULL)
944 /* else: no host specified; use default */
947 hostname = default_host;
953 plugin_instance = strchr(plugin, '-');
954 if (plugin_instance != NULL) {
955 *plugin_instance = '\0';
959 type_instance = strchr(type, '-');
960 if (type_instance != NULL) {
961 *type_instance = '\0';
965 *ret_host = hostname;
966 *ret_plugin = plugin;
967 *ret_plugin_instance = plugin_instance;
969 *ret_type_instance = type_instance;
971 } /* int parse_identifier */
973 int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
975 char str_copy[6 * DATA_MAX_NAME_LEN];
978 char *plugin_instance = NULL;
980 char *type_instance = NULL;
983 if ((str == NULL) || (vl == NULL))
986 sstrncpy(str_copy, str, sizeof(str_copy));
988 status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
990 /* default_host = */ NULL);
994 sstrncpy(vl->host, host, sizeof(vl->host));
995 sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
996 sstrncpy(vl->plugin_instance,
997 (plugin_instance != NULL) ? plugin_instance : "",
998 sizeof(vl->plugin_instance));
999 sstrncpy(vl->type, type, sizeof(vl->type));
1000 sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
1001 sizeof(vl->type_instance));
1004 } /* }}} int parse_identifier_vl */
1006 int parse_value(const char *value_orig, value_t *ret_value, int ds_type) {
1008 char *endptr = NULL;
1011 if (value_orig == NULL)
1014 value = strdup(value_orig);
1017 value_len = strlen(value);
1019 while ((value_len > 0) && isspace((int)value[value_len - 1])) {
1020 value[value_len - 1] = 0;
1025 case DS_TYPE_COUNTER:
1026 ret_value->counter = (counter_t)strtoull(value, &endptr, 0);
1030 ret_value->gauge = (gauge_t)strtod(value, &endptr);
1033 case DS_TYPE_DERIVE:
1034 ret_value->derive = (derive_t)strtoll(value, &endptr, 0);
1037 case DS_TYPE_ABSOLUTE:
1038 ret_value->absolute = (absolute_t)strtoull(value, &endptr, 0);
1043 ERROR("parse_value: Invalid data source type: %i.", ds_type);
1047 if (value == endptr) {
1048 ERROR("parse_value: Failed to parse string as %s: \"%s\".",
1049 DS_TYPE_TO_STRING(ds_type), value);
1052 } else if ((NULL != endptr) && ('\0' != *endptr))
1053 INFO("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1054 "Input string was \"%s\".",
1055 endptr, DS_TYPE_TO_STRING(ds_type), value_orig);
1059 } /* int parse_value */
1061 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds) {
1067 if ((buffer == NULL) || (vl == NULL) || (ds == NULL))
1074 while ((ptr = strtok_r(dummy, ":", &saveptr)) != NULL) {
1077 if (i >= vl->values_len) {
1078 /* Make sure i is invalid. */
1083 if (vl->time == 0) {
1084 if (strcmp("N", ptr) == 0)
1085 vl->time = cdtime();
1087 char *endptr = NULL;
1091 tmp = strtod(ptr, &endptr);
1092 if ((errno != 0) /* Overflow */
1093 || (endptr == ptr) /* Invalid string */
1094 || (endptr == NULL) /* This should not happen */
1095 || (*endptr != 0)) /* Trailing chars */
1098 vl->time = DOUBLE_TO_CDTIME_T(tmp);
1104 if ((strcmp("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1105 vl->values[i].gauge = NAN;
1106 else if (0 != parse_value(ptr, &vl->values[i], ds->ds[i].type))
1110 } /* while (strtok_r) */
1112 if ((ptr != NULL) || (i == 0))
1115 } /* int parse_values */
1117 int parse_value_file(char const *path, value_t *ret_value, int ds_type) {
1121 fh = fopen(path, "r");
1125 if (fgets(buffer, sizeof(buffer), fh) == NULL) {
1132 strstripnewline(buffer);
1134 return parse_value(buffer, ret_value, ds_type);
1135 } /* int parse_value_file */
1137 #if !HAVE_GETPWNAM_R
1138 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
1139 struct passwd **pwbufp) {
1143 memset(pwbuf, '\0', sizeof(struct passwd));
1145 pthread_mutex_lock(&getpwnam_r_lock);
1148 pw = getpwnam(name);
1150 status = (errno != 0) ? errno : ENOENT;
1154 #define GETPWNAM_COPY_MEMBER(member) \
1155 if (pw->member != NULL) { \
1156 int len = strlen(pw->member); \
1157 if (len >= buflen) { \
1161 sstrncpy(buf, pw->member, buflen); \
1162 pwbuf->member = buf; \
1164 buflen -= (len + 1); \
1166 GETPWNAM_COPY_MEMBER(pw_name);
1167 GETPWNAM_COPY_MEMBER(pw_passwd);
1168 GETPWNAM_COPY_MEMBER(pw_gecos);
1169 GETPWNAM_COPY_MEMBER(pw_dir);
1170 GETPWNAM_COPY_MEMBER(pw_shell);
1172 pwbuf->pw_uid = pw->pw_uid;
1173 pwbuf->pw_gid = pw->pw_gid;
1179 pthread_mutex_unlock(&getpwnam_r_lock);
1182 } /* int getpwnam_r */
1183 #endif /* !HAVE_GETPWNAM_R */
1185 int notification_init(notification_t *n, int severity, const char *message,
1186 const char *host, const char *plugin,
1187 const char *plugin_instance, const char *type,
1188 const char *type_instance) {
1189 memset(n, '\0', sizeof(notification_t));
1191 n->severity = severity;
1193 if (message != NULL)
1194 sstrncpy(n->message, message, sizeof(n->message));
1196 sstrncpy(n->host, host, sizeof(n->host));
1198 sstrncpy(n->plugin, plugin, sizeof(n->plugin));
1199 if (plugin_instance != NULL)
1200 sstrncpy(n->plugin_instance, plugin_instance, sizeof(n->plugin_instance));
1202 sstrncpy(n->type, type, sizeof(n->type));
1203 if (type_instance != NULL)
1204 sstrncpy(n->type_instance, type_instance, sizeof(n->type_instance));
1207 } /* int notification_init */
1209 int walk_directory(const char *dir, dirwalk_callback_f callback,
1210 void *user_data, int include_hidden) {
1219 if ((dh = opendir(dir)) == NULL) {
1221 ERROR("walk_directory: Cannot open '%s': %s", dir,
1222 sstrerror(errno, errbuf, sizeof(errbuf)));
1226 while ((ent = readdir(dh)) != NULL) {
1229 if (include_hidden) {
1230 if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0))
1232 } else /* if (!include_hidden) */
1234 if (ent->d_name[0] == '.')
1238 status = (*callback)(dir, ent->d_name, user_data);
1247 if ((success == 0) && (failure > 0))
1252 ssize_t read_file_contents(const char *filename, char *buf, size_t bufsize) {
1256 fh = fopen(filename, "r");
1260 ret = (ssize_t)fread(buf, 1, bufsize, fh);
1261 if ((ret == 0) && (ferror(fh) != 0)) {
1262 ERROR("read_file_contents: Reading file \"%s\" failed.", filename);
1270 counter_t counter_diff(counter_t old_value, counter_t new_value) {
1273 if (old_value > new_value) {
1274 if (old_value <= 4294967295U)
1275 diff = (4294967295U - old_value) + new_value + 1;
1277 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1279 diff = new_value - old_value;
1283 } /* counter_t counter_diff */
1285 int rate_to_value(value_t *ret_value, gauge_t rate, /* {{{ */
1286 rate_to_value_state_t *state, int ds_type, cdtime_t t) {
1287 gauge_t delta_gauge;
1290 if (ds_type == DS_TYPE_GAUGE) {
1291 state->last_value.gauge = rate;
1292 state->last_time = t;
1294 *ret_value = state->last_value;
1298 /* Counter and absolute can't handle negative rates. Reset "last time"
1299 * to zero, so that the next valid rate will re-initialize the
1302 ((ds_type == DS_TYPE_COUNTER) || (ds_type == DS_TYPE_ABSOLUTE))) {
1303 memset(state, 0, sizeof(*state));
1307 /* Another invalid state: The time is not increasing. */
1308 if (t <= state->last_time) {
1309 memset(state, 0, sizeof(*state));
1313 delta_t = t - state->last_time;
1314 delta_gauge = (rate * CDTIME_T_TO_DOUBLE(delta_t)) + state->residual;
1316 /* Previous value is invalid. */
1317 if (state->last_time == 0) /* {{{ */
1319 if (ds_type == DS_TYPE_DERIVE) {
1320 state->last_value.derive = (derive_t)rate;
1321 state->residual = rate - ((gauge_t)state->last_value.derive);
1322 } else if (ds_type == DS_TYPE_COUNTER) {
1323 state->last_value.counter = (counter_t)rate;
1324 state->residual = rate - ((gauge_t)state->last_value.counter);
1325 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1326 state->last_value.absolute = (absolute_t)rate;
1327 state->residual = rate - ((gauge_t)state->last_value.absolute);
1332 state->last_time = t;
1336 if (ds_type == DS_TYPE_DERIVE) {
1337 derive_t delta_derive = (derive_t)delta_gauge;
1339 state->last_value.derive += delta_derive;
1340 state->residual = delta_gauge - ((gauge_t)delta_derive);
1341 } else if (ds_type == DS_TYPE_COUNTER) {
1342 counter_t delta_counter = (counter_t)delta_gauge;
1344 state->last_value.counter += delta_counter;
1345 state->residual = delta_gauge - ((gauge_t)delta_counter);
1346 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1347 absolute_t delta_absolute = (absolute_t)delta_gauge;
1349 state->last_value.absolute = delta_absolute;
1350 state->residual = delta_gauge - ((gauge_t)delta_absolute);
1355 state->last_time = t;
1356 *ret_value = state->last_value;
1358 } /* }}} value_t rate_to_value */
1360 int value_to_rate(gauge_t *ret_rate, /* {{{ */
1361 value_t value, int ds_type, cdtime_t t,
1362 value_to_rate_state_t *state) {
1365 /* Another invalid state: The time is not increasing. */
1366 if (t <= state->last_time) {
1367 memset(state, 0, sizeof(*state));
1371 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1373 /* Previous value is invalid. */
1374 if (state->last_time == 0) {
1375 state->last_value = value;
1376 state->last_time = t;
1381 case DS_TYPE_DERIVE: {
1382 derive_t diff = value.derive - state->last_value.derive;
1383 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1386 case DS_TYPE_GAUGE: {
1387 *ret_rate = value.gauge;
1390 case DS_TYPE_COUNTER: {
1391 counter_t diff = counter_diff(state->last_value.counter, value.counter);
1392 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1395 case DS_TYPE_ABSOLUTE: {
1396 absolute_t diff = value.absolute;
1397 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1404 state->last_value = value;
1405 state->last_time = t;
1407 } /* }}} value_t rate_to_value */
1409 int service_name_to_port_number(const char *service_name) {
1410 struct addrinfo *ai_list;
1414 if (service_name == NULL)
1417 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC};
1419 status = getaddrinfo(/* node = */ NULL, service_name, &ai_hints, &ai_list);
1421 ERROR("service_name_to_port_number: getaddrinfo failed: %s",
1422 gai_strerror(status));
1426 service_number = -1;
1427 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1428 ai_ptr = ai_ptr->ai_next) {
1429 if (ai_ptr->ai_family == AF_INET) {
1430 struct sockaddr_in *sa;
1432 sa = (void *)ai_ptr->ai_addr;
1433 service_number = (int)ntohs(sa->sin_port);
1434 } else if (ai_ptr->ai_family == AF_INET6) {
1435 struct sockaddr_in6 *sa;
1437 sa = (void *)ai_ptr->ai_addr;
1438 service_number = (int)ntohs(sa->sin6_port);
1441 if ((service_number > 0) && (service_number <= 65535))
1445 freeaddrinfo(ai_list);
1447 if ((service_number > 0) && (service_number <= 65535))
1448 return service_number;
1450 } /* int service_name_to_port_number */
1452 void set_sock_opts(int sockfd) /* {{{ */
1457 status = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &socktype,
1458 &(socklen_t){sizeof(socktype)});
1460 WARNING("set_sock_opts: failed to determine socket type");
1464 if (socktype == SOCK_STREAM) {
1466 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int));
1468 WARNING("set_sock_opts: failed to set socket keepalive flag");
1471 int tcp_keepidle = ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 100 + 1);
1472 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &tcp_keepidle,
1473 sizeof(tcp_keepidle));
1475 WARNING("set_sock_opts: failed to set socket tcp keepalive time");
1478 #ifdef TCP_KEEPINTVL
1480 ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 1000 + 1);
1481 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &tcp_keepintvl,
1482 sizeof(tcp_keepintvl));
1484 WARNING("set_sock_opts: failed to set socket tcp keepalive interval");
1487 } /* }}} void set_sock_opts */
1489 int strtoderive(const char *string, derive_t *ret_value) /* {{{ */
1494 if ((string == NULL) || (ret_value == NULL))
1499 tmp = (derive_t)strtoll(string, &endptr, /* base = */ 0);
1500 if ((endptr == string) || (errno != 0))
1505 } /* }}} int strtoderive */
1507 int strtogauge(const char *string, gauge_t *ret_value) /* {{{ */
1510 char *endptr = NULL;
1512 if ((string == NULL) || (ret_value == NULL))
1517 tmp = (gauge_t)strtod(string, &endptr);
1520 else if ((endptr == NULL) || (*endptr != 0))
1525 } /* }}} int strtogauge */
1527 int strarray_add(char ***ret_array, size_t *ret_array_len,
1528 char const *str) /* {{{ */
1531 size_t array_len = *ret_array_len;
1536 array = realloc(*ret_array, (array_len + 1) * sizeof(*array));
1541 array[array_len] = strdup(str);
1542 if (array[array_len] == NULL)
1546 *ret_array_len = array_len;
1548 } /* }}} int strarray_add */
1550 void strarray_free(char **array, size_t array_len) /* {{{ */
1552 for (size_t i = 0; i < array_len; i++)
1555 } /* }}} void strarray_free */
1558 int check_capability(int arg) /* {{{ */
1560 cap_value_t cap_value = (cap_value_t)arg;
1562 cap_flag_value_t cap_flag_value;
1564 if (!CAP_IS_SUPPORTED(cap_value))
1567 if (!(cap = cap_get_proc())) {
1568 ERROR("check_capability: cap_get_proc failed.");
1572 if (cap_get_flag(cap, cap_value, CAP_EFFECTIVE, &cap_flag_value) < 0) {
1573 ERROR("check_capability: cap_get_flag failed.");
1579 return cap_flag_value != CAP_SET;
1580 } /* }}} int check_capability */
1582 int check_capability(__attribute__((unused)) int arg) /* {{{ */
1584 WARNING("check_capability: unsupported capability implementation. "
1585 "Some plugin(s) may require elevated privileges to work properly.");
1587 } /* }}} int check_capability */
1588 #endif /* HAVE_CAPABILITY */