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"
46 #include <sys/types.h>
51 #include <netinet/in.h>
54 #if HAVE_NETINET_TCP_H
55 #include <netinet/tcp.h>
58 /* for ntohl and htonl */
60 #include <arpa/inet.h>
64 #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 int ssnprintf(char *dest, size_t n, const char *format, ...) {
96 ret = vsnprintf(dest, n, format, ap);
101 } /* int ssnprintf */
103 char *ssnprintf_alloc(char const *format, ...) /* {{{ */
105 char static_buffer[1024] = "";
107 size_t alloc_buffer_size;
111 /* Try printing into the static buffer. In many cases it will be
112 * sufficiently large and we can simply return a strdup() of this
114 va_start(ap, format);
115 status = vsnprintf(static_buffer, sizeof(static_buffer), format, ap);
120 /* "status" does not include the null byte. */
121 alloc_buffer_size = (size_t)(status + 1);
122 if (alloc_buffer_size <= sizeof(static_buffer))
123 return (strdup(static_buffer));
125 /* Allocate a buffer large enough to hold the string. */
126 alloc_buffer = calloc(1, alloc_buffer_size);
127 if (alloc_buffer == NULL)
130 /* Print again into this new buffer. */
131 va_start(ap, format);
132 status = vsnprintf(alloc_buffer, alloc_buffer_size, format, ap);
139 return (alloc_buffer);
140 } /* }}} char *ssnprintf_alloc */
142 char *sstrdup(const char *s) {
149 /* Do not use `strdup' here, because it's not specified in POSIX. It's
150 * ``only'' an XSI extension. */
154 ERROR("sstrdup: Out of memory.");
157 memcpy(r, s, sizeof(char) * sz);
160 } /* char *sstrdup */
162 /* Even though Posix requires "strerror_r" to return an "int",
163 * some systems (e.g. the GNU libc) return a "char *" _and_
164 * ignore the second argument ... -tokkee */
165 char *sstrerror(int errnum, char *buf, size_t buflen) {
172 pthread_mutex_lock(&strerror_r_lock);
174 temp = strerror(errnum);
175 sstrncpy(buf, temp, buflen);
177 pthread_mutex_unlock(&strerror_r_lock);
179 /* #endif !HAVE_STRERROR_R */
181 #elif STRERROR_R_CHAR_P
184 temp = strerror_r(errnum, buf, buflen);
185 if (buf[0] == '\0') {
186 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
187 sstrncpy(buf, temp, buflen);
189 sstrncpy(buf, "strerror_r did not return "
194 /* #endif STRERROR_R_CHAR_P */
197 if (strerror_r(errnum, buf, buflen) != 0) {
198 ssnprintf(buf, buflen, "Error #%i; "
199 "Additionally, strerror_r failed.",
202 #endif /* STRERROR_R_CHAR_P */
205 } /* char *sstrerror */
207 void *smalloc(size_t size) {
210 if ((r = malloc(size)) == NULL) {
211 ERROR("Not enough memory.");
216 } /* void *smalloc */
219 void sfree (void **ptr)
231 ssize_t sread(int fd, void *buf, size_t count) {
240 status = read(fd, (void *)ptr, nleft);
242 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
249 DEBUG("Received EOF from fd %i. "
250 "Closing fd and returning error.",
256 assert((0 > status) || (nleft >= (size_t)status));
258 nleft = nleft - ((size_t)status);
259 ptr = ptr + ((size_t)status);
265 ssize_t swrite(int fd, const void *buf, size_t count) {
271 ptr = (const char *)buf;
279 /* checking for closed peer connection */
281 pfd.events = POLLIN | POLLHUP;
283 if (poll(&pfd, 1, 0) > 0) {
285 if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) {
286 /* if recv returns zero (even though poll() said there is data to be
287 * read), that means the connection has been closed */
288 return errno ? errno : -1;
293 status = write(fd, (const void *)ptr, nleft);
295 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
299 return errno ? errno : status;
301 nleft = nleft - ((size_t)status);
302 ptr = ptr + ((size_t)status);
308 int strsplit(char *string, char **fields, size_t size) {
316 while ((fields[i] = strtok_r(ptr, " \t\r\n", &saveptr)) != NULL) {
327 int strjoin(char *buffer, size_t buffer_size, char **fields, size_t fields_num,
333 size_t buffer_req = 0;
335 if (((fields_num != 0) && (fields == NULL)) ||
336 ((buffer_size != 0) && (buffer == NULL)))
342 if (buffer_size != 0)
343 avail = buffer_size - 1;
346 sep_len = strlen(sep);
348 for (size_t i = 0; i < fields_num; i++) {
349 size_t field_len = strlen(fields[i]);
352 buffer_req += sep_len;
353 buffer_req += field_len;
355 if (buffer_size == 0)
358 if ((i != 0) && (sep_len > 0)) {
359 if (sep_len >= avail) {
360 /* prevent subsequent iterations from writing to the
366 memcpy(ptr, sep, sep_len);
372 if (field_len > avail)
375 memcpy(ptr, fields[i], field_len);
383 return (int)buffer_req;
386 int escape_string(char *buffer, size_t buffer_size) {
390 /* Check if we need to escape at all first */
391 temp = strpbrk(buffer, " \t\"\\");
398 temp = calloc(1, buffer_size);
405 for (size_t i = 0; i < buffer_size; i++) {
406 if (buffer[i] == 0) {
408 } else if ((buffer[i] == '"') || (buffer[i] == '\\')) {
409 if (j > (buffer_size - 4))
412 temp[j + 1] = buffer[i];
415 if (j > (buffer_size - 3))
422 assert((j + 1) < buffer_size);
426 sstrncpy(buffer, temp, buffer_size);
429 } /* int escape_string */
431 int strunescape(char *buf, size_t buf_len) {
432 for (size_t i = 0; (i < buf_len) && (buf[i] != '\0'); ++i) {
436 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
437 ERROR("string unescape: backslash found at end of string.");
438 /* Ensure null-byte at the end of the buffer. */
443 switch (buf[i + 1]) {
458 /* Move everything after the position one position to the left.
459 * Add a null-byte as last character in the buffer. */
460 memmove(buf + i + 1, buf + i + 2, buf_len - i - 2);
461 buf[buf_len - 1] = 0;
464 } /* int strunescape */
466 size_t strstripnewline(char *buffer) {
467 size_t buffer_len = strlen(buffer);
469 while (buffer_len > 0) {
470 if ((buffer[buffer_len - 1] != '\n') && (buffer[buffer_len - 1] != '\r'))
473 buffer[buffer_len] = 0;
477 } /* size_t strstripnewline */
479 int escape_slashes(char *buffer, size_t buffer_size) {
482 buffer_len = strlen(buffer);
484 if (buffer_len <= 1) {
485 if (strcmp("/", buffer) == 0) {
488 sstrncpy(buffer, "root", buffer_size);
493 /* Move one to the left */
494 if (buffer[0] == '/') {
495 memmove(buffer, buffer + 1, buffer_len);
499 for (size_t i = 0; i < buffer_len; i++) {
500 if (buffer[i] == '/')
505 } /* int escape_slashes */
507 void replace_special(char *buffer, size_t buffer_size) {
508 for (size_t i = 0; i < buffer_size; i++) {
511 if ((!isalnum((int)buffer[i])) && (buffer[i] != '-'))
514 } /* void replace_special */
516 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta) {
517 struct timeval *larger;
518 struct timeval *smaller;
522 NORMALIZE_TIMEVAL(tv0);
523 NORMALIZE_TIMEVAL(tv1);
525 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec)) {
533 if ((tv0.tv_sec < tv1.tv_sec) ||
534 ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec))) {
545 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
547 if (smaller->tv_usec <= larger->tv_usec)
548 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
551 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
555 assert((delta == NULL) ||
556 ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
559 } /* int timeval_cmp */
561 int check_create_dir(const char *file_orig) {
571 int last_is_file = 1;
572 int path_is_absolute = 0;
576 * Sanity checks first
578 if (file_orig == NULL)
581 if ((len = strlen(file_orig)) < 1)
583 else if (len >= sizeof(file_copy))
587 * If `file_orig' ends in a slash the last component is a directory,
588 * otherwise it's a file. Act accordingly..
590 if (file_orig[len - 1] == '/')
592 if (file_orig[0] == '/')
593 path_is_absolute = 1;
596 * Create a copy for `strtok_r' to destroy
598 sstrncpy(file_copy, file_orig, sizeof(file_copy));
601 * Break into components. This will eat up several slashes in a row and
602 * remove leading and trailing slashes..
607 while ((fields[fields_num] = strtok_r(ptr, "/", &saveptr)) != NULL) {
611 if (fields_num >= 16)
616 * For each component, do..
618 for (int i = 0; i < (fields_num - last_is_file); i++) {
620 * Do not create directories that start with a dot. This
621 * prevents `../../' attacks and other likely malicious
624 if (fields[i][0] == '.') {
625 ERROR("Cowardly refusing to create a directory that "
626 "begins with a `.' (dot): `%s'",
632 * Join the components together again
635 if (strjoin(dir + path_is_absolute, (size_t)(dir_len - path_is_absolute),
636 fields, (size_t)(i + 1), "/") < 0) {
637 ERROR("strjoin failed: `%s', component #%i", file_orig, i);
642 if ((stat(dir, &statbuf) == -1) && (lstat(dir, &statbuf) == -1)) {
643 if (errno == ENOENT) {
644 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
647 /* this might happen, if a different thread created
648 * the directory in the meantime
649 * => call stat() again to check for S_ISDIR() */
654 ERROR("check_create_dir: mkdir (%s): %s", dir,
655 sstrerror(errno, errbuf, sizeof(errbuf)));
659 ERROR("check_create_dir: stat (%s): %s", dir,
660 sstrerror(errno, errbuf, sizeof(errbuf)));
663 } else if (!S_ISDIR(statbuf.st_mode)) {
664 ERROR("check_create_dir: `%s' exists but is not "
674 } /* check_create_dir */
677 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name) {
685 ssnprintf(ident, sizeof(ident), "%s,%i,%s", module, instance, name);
687 *ksp_ptr = kstat_lookup(kc, module, instance, name);
688 if (*ksp_ptr == NULL) {
689 ERROR("get_kstat: Cound not find kstat %s", ident);
693 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
694 ERROR("get_kstat: kstat %s has wrong type", ident);
700 assert(*ksp_ptr != NULL);
701 assert((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
704 if (kstat_read(kc, *ksp_ptr, NULL) == -1) {
705 ERROR("get_kstat: kstat %s could not be read", ident);
709 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
710 ERROR("get_kstat: kstat %s has wrong type", ident);
717 long long get_kstat_value(kstat_t *ksp, char *name) {
719 long long retval = -1LL;
722 ERROR("get_kstat_value (\"%s\"): ksp is NULL.", name);
724 } else if (ksp->ks_type != KSTAT_TYPE_NAMED) {
725 ERROR("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
726 "is not KSTAT_TYPE_NAMED (%#x).",
727 name, (unsigned int)ksp->ks_type, (unsigned int)KSTAT_TYPE_NAMED);
731 if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, name)) == NULL)
734 if (kn->data_type == KSTAT_DATA_INT32)
735 retval = (long long)kn->value.i32;
736 else if (kn->data_type == KSTAT_DATA_UINT32)
737 retval = (long long)kn->value.ui32;
738 else if (kn->data_type == KSTAT_DATA_INT64)
740 (long long)kn->value.i64; /* According to ANSI C99 `long long' must hold
742 else if (kn->data_type == KSTAT_DATA_UINT64)
743 retval = (long long)kn->value.ui64; /* XXX: Might overflow! */
745 WARNING("get_kstat_value: Not a numeric value: %s", name);
749 #endif /* HAVE_LIBKSTAT */
752 unsigned long long ntohll(unsigned long long n) {
753 #if BYTE_ORDER == BIG_ENDIAN
756 return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
758 } /* unsigned long long ntohll */
760 unsigned long long htonll(unsigned long long n) {
761 #if BYTE_ORDER == BIG_ENDIAN
764 return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
766 } /* unsigned long long htonll */
767 #endif /* HAVE_HTONLL */
769 #if FP_LAYOUT_NEED_NOTHING
770 /* Well, we need nothing.. */
771 /* #endif FP_LAYOUT_NEED_NOTHING */
773 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
774 #if FP_LAYOUT_NEED_ENDIANFLIP
775 #define FP_CONVERT(A) \
776 ((((uint64_t)(A)&0xff00000000000000LL) >> 56) | \
777 (((uint64_t)(A)&0x00ff000000000000LL) >> 40) | \
778 (((uint64_t)(A)&0x0000ff0000000000LL) >> 24) | \
779 (((uint64_t)(A)&0x000000ff00000000LL) >> 8) | \
780 (((uint64_t)(A)&0x00000000ff000000LL) << 8) | \
781 (((uint64_t)(A)&0x0000000000ff0000LL) << 24) | \
782 (((uint64_t)(A)&0x000000000000ff00LL) << 40) | \
783 (((uint64_t)(A)&0x00000000000000ffLL) << 56))
785 #define FP_CONVERT(A) \
786 ((((uint64_t)(A)&0xffffffff00000000LL) >> 32) | \
787 (((uint64_t)(A)&0x00000000ffffffffLL) << 32))
790 double ntohd(double d) {
799 /* NAN in x86 byte order */
800 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00) && (ret.byte[2] == 0x00) &&
801 (ret.byte[3] == 0x00) && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00) &&
802 (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f)) {
808 ret.integer = FP_CONVERT(tmp);
809 return (ret.floating);
813 double htond(double d) {
821 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
822 ret.byte[4] = ret.byte[5] = 0x00;
825 return (ret.floating);
830 tmp = FP_CONVERT(ret.integer);
832 return (ret.floating);
835 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
837 int format_name(char *ret, int ret_len, const char *hostname,
838 const char *plugin, const char *plugin_instance,
839 const char *type, const char *type_instance) {
844 buffer_size = (size_t)ret_len;
846 #define APPEND(str) \
848 size_t l = strlen(str); \
849 if (l >= buffer_size) \
851 memcpy(buffer, (str), l); \
856 assert(plugin != NULL);
857 assert(type != NULL);
862 if ((plugin_instance != NULL) && (plugin_instance[0] != 0)) {
864 APPEND(plugin_instance);
868 if ((type_instance != NULL) && (type_instance[0] != 0)) {
870 APPEND(type_instance);
872 assert(buffer_size > 0);
877 } /* int format_name */
879 int format_values(char *ret, size_t ret_len, /* {{{ */
880 const data_set_t *ds, const value_list_t *vl,
884 gauge_t *rates = NULL;
886 assert(0 == strcmp(ds->type, vl->type));
888 memset(ret, 0, ret_len);
890 #define BUFFER_ADD(...) \
892 status = ssnprintf(ret + offset, ret_len - offset, __VA_ARGS__); \
896 } else if (((size_t)status) >= (ret_len - offset)) { \
900 offset += ((size_t)status); \
903 BUFFER_ADD("%.3f", CDTIME_T_TO_DOUBLE(vl->time));
905 for (size_t i = 0; i < ds->ds_num; i++) {
906 if (ds->ds[i].type == DS_TYPE_GAUGE)
907 BUFFER_ADD(":" GAUGE_FORMAT, vl->values[i].gauge);
908 else if (store_rates) {
910 rates = uc_get_rate(ds, vl);
912 WARNING("format_values: uc_get_rate failed.");
915 BUFFER_ADD(":" GAUGE_FORMAT, rates[i]);
916 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
917 BUFFER_ADD(":%llu", vl->values[i].counter);
918 else if (ds->ds[i].type == DS_TYPE_DERIVE)
919 BUFFER_ADD(":%" PRIi64, vl->values[i].derive);
920 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
921 BUFFER_ADD(":%" PRIu64, vl->values[i].absolute);
923 ERROR("format_values: Unknown data source type: %i", ds->ds[i].type);
927 } /* for ds->ds_num */
933 } /* }}} int format_values */
935 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
936 char **ret_plugin_instance, char **ret_type,
937 char **ret_type_instance, char *default_host) {
938 char *hostname = NULL;
940 char *plugin_instance = NULL;
942 char *type_instance = NULL;
945 if (hostname == NULL)
948 plugin = strchr(hostname, '/');
954 type = strchr(plugin, '/');
956 if (default_host == NULL)
958 /* else: no host specified; use default */
961 hostname = default_host;
967 plugin_instance = strchr(plugin, '-');
968 if (plugin_instance != NULL) {
969 *plugin_instance = '\0';
973 type_instance = strchr(type, '-');
974 if (type_instance != NULL) {
975 *type_instance = '\0';
979 *ret_host = hostname;
980 *ret_plugin = plugin;
981 *ret_plugin_instance = plugin_instance;
983 *ret_type_instance = type_instance;
985 } /* int parse_identifier */
987 int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
989 char str_copy[6 * DATA_MAX_NAME_LEN];
992 char *plugin_instance = NULL;
994 char *type_instance = NULL;
997 if ((str == NULL) || (vl == NULL))
1000 sstrncpy(str_copy, str, sizeof(str_copy));
1002 status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
1004 /* default_host = */ NULL);
1008 sstrncpy(vl->host, host, sizeof(vl->host));
1009 sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
1010 sstrncpy(vl->plugin_instance,
1011 (plugin_instance != NULL) ? plugin_instance : "",
1012 sizeof(vl->plugin_instance));
1013 sstrncpy(vl->type, type, sizeof(vl->type));
1014 sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
1015 sizeof(vl->type_instance));
1018 } /* }}} int parse_identifier_vl */
1020 int parse_value(const char *value_orig, value_t *ret_value, int ds_type) {
1022 char *endptr = NULL;
1025 if (value_orig == NULL)
1028 value = strdup(value_orig);
1031 value_len = strlen(value);
1033 while ((value_len > 0) && isspace((int)value[value_len - 1])) {
1034 value[value_len - 1] = 0;
1039 case DS_TYPE_COUNTER:
1040 ret_value->counter = (counter_t)strtoull(value, &endptr, 0);
1044 ret_value->gauge = (gauge_t)strtod(value, &endptr);
1047 case DS_TYPE_DERIVE:
1048 ret_value->derive = (derive_t)strtoll(value, &endptr, 0);
1051 case DS_TYPE_ABSOLUTE:
1052 ret_value->absolute = (absolute_t)strtoull(value, &endptr, 0);
1057 ERROR("parse_value: Invalid data source type: %i.", ds_type);
1061 if (value == endptr) {
1062 ERROR("parse_value: Failed to parse string as %s: \"%s\".",
1063 DS_TYPE_TO_STRING(ds_type), value);
1066 } else if ((NULL != endptr) && ('\0' != *endptr))
1067 INFO("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1068 "Input string was \"%s\".",
1069 endptr, DS_TYPE_TO_STRING(ds_type), value_orig);
1073 } /* int parse_value */
1075 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds) {
1081 if ((buffer == NULL) || (vl == NULL) || (ds == NULL))
1088 while ((ptr = strtok_r(dummy, ":", &saveptr)) != NULL) {
1091 if (i >= vl->values_len) {
1092 /* Make sure i is invalid. */
1097 if (vl->time == 0) {
1098 if (strcmp("N", ptr) == 0)
1099 vl->time = cdtime();
1101 char *endptr = NULL;
1105 tmp = strtod(ptr, &endptr);
1106 if ((errno != 0) /* Overflow */
1107 || (endptr == ptr) /* Invalid string */
1108 || (endptr == NULL) /* This should not happen */
1109 || (*endptr != 0)) /* Trailing chars */
1112 vl->time = DOUBLE_TO_CDTIME_T(tmp);
1118 if ((strcmp("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1119 vl->values[i].gauge = NAN;
1120 else if (0 != parse_value(ptr, &vl->values[i], ds->ds[i].type))
1124 } /* while (strtok_r) */
1126 if ((ptr != NULL) || (i == 0))
1129 } /* int parse_values */
1131 int parse_value_file(char const *path, value_t *ret_value, int ds_type) {
1135 fh = fopen(path, "r");
1139 if (fgets(buffer, sizeof(buffer), fh) == NULL) {
1146 strstripnewline(buffer);
1148 return parse_value(buffer, ret_value, ds_type);
1149 } /* int parse_value_file */
1151 #if !HAVE_GETPWNAM_R
1152 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
1153 struct passwd **pwbufp) {
1157 memset(pwbuf, '\0', sizeof(struct passwd));
1159 pthread_mutex_lock(&getpwnam_r_lock);
1162 pw = getpwnam(name);
1164 status = (errno != 0) ? errno : ENOENT;
1168 #define GETPWNAM_COPY_MEMBER(member) \
1169 if (pw->member != NULL) { \
1170 int len = strlen(pw->member); \
1171 if (len >= buflen) { \
1175 sstrncpy(buf, pw->member, buflen); \
1176 pwbuf->member = buf; \
1178 buflen -= (len + 1); \
1180 GETPWNAM_COPY_MEMBER(pw_name);
1181 GETPWNAM_COPY_MEMBER(pw_passwd);
1182 GETPWNAM_COPY_MEMBER(pw_gecos);
1183 GETPWNAM_COPY_MEMBER(pw_dir);
1184 GETPWNAM_COPY_MEMBER(pw_shell);
1186 pwbuf->pw_uid = pw->pw_uid;
1187 pwbuf->pw_gid = pw->pw_gid;
1193 pthread_mutex_unlock(&getpwnam_r_lock);
1196 } /* int getpwnam_r */
1197 #endif /* !HAVE_GETPWNAM_R */
1199 int notification_init(notification_t *n, int severity, const char *message,
1200 const char *host, const char *plugin,
1201 const char *plugin_instance, const char *type,
1202 const char *type_instance) {
1203 memset(n, '\0', sizeof(notification_t));
1205 n->severity = severity;
1207 if (message != NULL)
1208 sstrncpy(n->message, message, sizeof(n->message));
1210 sstrncpy(n->host, host, sizeof(n->host));
1212 sstrncpy(n->plugin, plugin, sizeof(n->plugin));
1213 if (plugin_instance != NULL)
1214 sstrncpy(n->plugin_instance, plugin_instance, sizeof(n->plugin_instance));
1216 sstrncpy(n->type, type, sizeof(n->type));
1217 if (type_instance != NULL)
1218 sstrncpy(n->type_instance, type_instance, sizeof(n->type_instance));
1221 } /* int notification_init */
1223 int walk_directory(const char *dir, dirwalk_callback_f callback,
1224 void *user_data, int include_hidden) {
1233 if ((dh = opendir(dir)) == NULL) {
1235 ERROR("walk_directory: Cannot open '%s': %s", dir,
1236 sstrerror(errno, errbuf, sizeof(errbuf)));
1240 while ((ent = readdir(dh)) != NULL) {
1243 if (include_hidden) {
1244 if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0))
1246 } else /* if (!include_hidden) */
1248 if (ent->d_name[0] == '.')
1252 status = (*callback)(dir, ent->d_name, user_data);
1261 if ((success == 0) && (failure > 0))
1266 ssize_t read_file_contents(const char *filename, char *buf, size_t bufsize) {
1270 fh = fopen(filename, "r");
1274 ret = (ssize_t)fread(buf, 1, bufsize, fh);
1275 if ((ret == 0) && (ferror(fh) != 0)) {
1276 ERROR("read_file_contents: Reading file \"%s\" failed.", filename);
1284 counter_t counter_diff(counter_t old_value, counter_t new_value) {
1287 if (old_value > new_value) {
1288 if (old_value <= 4294967295U)
1289 diff = (4294967295U - old_value) + new_value + 1;
1291 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1293 diff = new_value - old_value;
1297 } /* counter_t counter_diff */
1299 int rate_to_value(value_t *ret_value, gauge_t rate, /* {{{ */
1300 rate_to_value_state_t *state, int ds_type, cdtime_t t) {
1301 gauge_t delta_gauge;
1304 if (ds_type == DS_TYPE_GAUGE) {
1305 state->last_value.gauge = rate;
1306 state->last_time = t;
1308 *ret_value = state->last_value;
1312 /* Counter and absolute can't handle negative rates. Reset "last time"
1313 * to zero, so that the next valid rate will re-initialize the
1316 ((ds_type == DS_TYPE_COUNTER) || (ds_type == DS_TYPE_ABSOLUTE))) {
1317 memset(state, 0, sizeof(*state));
1321 /* Another invalid state: The time is not increasing. */
1322 if (t <= state->last_time) {
1323 memset(state, 0, sizeof(*state));
1327 delta_t = t - state->last_time;
1328 delta_gauge = (rate * CDTIME_T_TO_DOUBLE(delta_t)) + state->residual;
1330 /* Previous value is invalid. */
1331 if (state->last_time == 0) /* {{{ */
1333 if (ds_type == DS_TYPE_DERIVE) {
1334 state->last_value.derive = (derive_t)rate;
1335 state->residual = rate - ((gauge_t)state->last_value.derive);
1336 } else if (ds_type == DS_TYPE_COUNTER) {
1337 state->last_value.counter = (counter_t)rate;
1338 state->residual = rate - ((gauge_t)state->last_value.counter);
1339 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1340 state->last_value.absolute = (absolute_t)rate;
1341 state->residual = rate - ((gauge_t)state->last_value.absolute);
1346 state->last_time = t;
1350 if (ds_type == DS_TYPE_DERIVE) {
1351 derive_t delta_derive = (derive_t)delta_gauge;
1353 state->last_value.derive += delta_derive;
1354 state->residual = delta_gauge - ((gauge_t)delta_derive);
1355 } else if (ds_type == DS_TYPE_COUNTER) {
1356 counter_t delta_counter = (counter_t)delta_gauge;
1358 state->last_value.counter += delta_counter;
1359 state->residual = delta_gauge - ((gauge_t)delta_counter);
1360 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1361 absolute_t delta_absolute = (absolute_t)delta_gauge;
1363 state->last_value.absolute = delta_absolute;
1364 state->residual = delta_gauge - ((gauge_t)delta_absolute);
1369 state->last_time = t;
1370 *ret_value = state->last_value;
1372 } /* }}} value_t rate_to_value */
1374 int value_to_rate(gauge_t *ret_rate, /* {{{ */
1375 value_t value, int ds_type, cdtime_t t,
1376 value_to_rate_state_t *state) {
1379 /* Another invalid state: The time is not increasing. */
1380 if (t <= state->last_time) {
1381 memset(state, 0, sizeof(*state));
1385 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1387 /* Previous value is invalid. */
1388 if (state->last_time == 0) {
1389 state->last_value = value;
1390 state->last_time = t;
1395 case DS_TYPE_DERIVE: {
1396 derive_t diff = value.derive - state->last_value.derive;
1397 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1400 case DS_TYPE_GAUGE: {
1401 *ret_rate = value.gauge;
1404 case DS_TYPE_COUNTER: {
1405 counter_t diff = counter_diff(state->last_value.counter, value.counter);
1406 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1409 case DS_TYPE_ABSOLUTE: {
1410 absolute_t diff = value.absolute;
1411 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1418 state->last_value = value;
1419 state->last_time = t;
1421 } /* }}} value_t rate_to_value */
1423 int service_name_to_port_number(const char *service_name) {
1424 struct addrinfo *ai_list;
1428 if (service_name == NULL)
1431 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC};
1433 status = getaddrinfo(/* node = */ NULL, service_name, &ai_hints, &ai_list);
1435 ERROR("service_name_to_port_number: getaddrinfo failed: %s",
1436 gai_strerror(status));
1440 service_number = -1;
1441 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1442 ai_ptr = ai_ptr->ai_next) {
1443 if (ai_ptr->ai_family == AF_INET) {
1444 struct sockaddr_in *sa;
1446 sa = (void *)ai_ptr->ai_addr;
1447 service_number = (int)ntohs(sa->sin_port);
1448 } else if (ai_ptr->ai_family == AF_INET6) {
1449 struct sockaddr_in6 *sa;
1451 sa = (void *)ai_ptr->ai_addr;
1452 service_number = (int)ntohs(sa->sin6_port);
1455 if ((service_number > 0) && (service_number <= 65535))
1459 freeaddrinfo(ai_list);
1461 if ((service_number > 0) && (service_number <= 65535))
1462 return (service_number);
1464 } /* int service_name_to_port_number */
1466 void set_sock_opts(int sockfd) /* {{{ */
1471 status = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &socktype,
1472 &(socklen_t){sizeof(socktype)});
1474 WARNING("set_sock_opts: failed to determine socket type");
1478 if (socktype == SOCK_STREAM) {
1480 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int));
1482 WARNING("set_sock_opts: failed to set socket keepalive flag");
1485 int tcp_keepidle = ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 100 + 1);
1486 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &tcp_keepidle,
1487 sizeof(tcp_keepidle));
1489 WARNING("set_sock_opts: failed to set socket tcp keepalive time");
1492 #ifdef TCP_KEEPINTVL
1494 ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 1000 + 1);
1495 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &tcp_keepintvl,
1496 sizeof(tcp_keepintvl));
1498 WARNING("set_sock_opts: failed to set socket tcp keepalive interval");
1501 } /* }}} void set_sock_opts */
1503 int strtoderive(const char *string, derive_t *ret_value) /* {{{ */
1508 if ((string == NULL) || (ret_value == NULL))
1513 tmp = (derive_t)strtoll(string, &endptr, /* base = */ 0);
1514 if ((endptr == string) || (errno != 0))
1519 } /* }}} int strtoderive */
1521 int strtogauge(const char *string, gauge_t *ret_value) /* {{{ */
1524 char *endptr = NULL;
1526 if ((string == NULL) || (ret_value == NULL))
1531 tmp = (gauge_t)strtod(string, &endptr);
1534 else if ((endptr == NULL) || (*endptr != 0))
1539 } /* }}} int strtogauge */
1541 int strarray_add(char ***ret_array, size_t *ret_array_len,
1542 char const *str) /* {{{ */
1545 size_t array_len = *ret_array_len;
1550 array = realloc(*ret_array, (array_len + 1) * sizeof(*array));
1555 array[array_len] = strdup(str);
1556 if (array[array_len] == NULL)
1560 *ret_array_len = array_len;
1562 } /* }}} int strarray_add */
1564 void strarray_free(char **array, size_t array_len) /* {{{ */
1566 for (size_t i = 0; i < array_len; i++)
1569 } /* }}} void strarray_free */
1572 int check_capability(int arg) /* {{{ */
1574 cap_value_t cap_value = (cap_value_t)arg;
1576 cap_flag_value_t cap_flag_value;
1578 if (!CAP_IS_SUPPORTED(cap_value))
1581 if (!(cap = cap_get_proc())) {
1582 ERROR("check_capability: cap_get_proc failed.");
1586 if (cap_get_flag(cap, cap_value, CAP_EFFECTIVE, &cap_flag_value) < 0) {
1587 ERROR("check_capability: cap_get_flag failed.");
1593 return (cap_flag_value != CAP_SET);
1594 } /* }}} int check_capability */
1596 int check_capability(__attribute__((unused)) int arg) /* {{{ */
1598 WARNING("check_capability: unsupported capability implementation. "
1599 "Some plugin(s) may require elevated privileges to work properly.");
1601 } /* }}} int check_capability */
1602 #endif /* HAVE_CAPABILITY */