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 ((i != 0) && (sep_len > 0)) {
342 if (sep_len >= avail) {
343 /* prevent subsequent iterations from writing to the
349 memcpy(ptr, sep, sep_len);
355 if (field_len > avail)
358 memcpy(ptr, fields[i], field_len);
366 return (int)buffer_req;
369 int escape_string(char *buffer, size_t buffer_size) {
373 /* Check if we need to escape at all first */
374 temp = strpbrk(buffer, " \t\"\\");
381 temp = calloc(1, buffer_size);
388 for (size_t i = 0; i < buffer_size; i++) {
389 if (buffer[i] == 0) {
391 } else if ((buffer[i] == '"') || (buffer[i] == '\\')) {
392 if (j > (buffer_size - 4))
395 temp[j + 1] = buffer[i];
398 if (j > (buffer_size - 3))
405 assert((j + 1) < buffer_size);
409 sstrncpy(buffer, temp, buffer_size);
412 } /* int escape_string */
414 int strunescape(char *buf, size_t buf_len) {
415 for (size_t i = 0; (i < buf_len) && (buf[i] != '\0'); ++i) {
419 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
420 ERROR("string unescape: backslash found at end of string.");
421 /* Ensure null-byte at the end of the buffer. */
426 switch (buf[i + 1]) {
441 /* Move everything after the position one position to the left.
442 * Add a null-byte as last character in the buffer. */
443 memmove(buf + i + 1, buf + i + 2, buf_len - i - 2);
444 buf[buf_len - 1] = 0;
447 } /* int strunescape */
449 size_t strstripnewline(char *buffer) {
450 size_t buffer_len = strlen(buffer);
452 while (buffer_len > 0) {
453 if ((buffer[buffer_len - 1] != '\n') && (buffer[buffer_len - 1] != '\r'))
456 buffer[buffer_len] = 0;
460 } /* size_t strstripnewline */
462 int escape_slashes(char *buffer, size_t buffer_size) {
465 buffer_len = strlen(buffer);
467 if (buffer_len <= 1) {
468 if (strcmp("/", buffer) == 0) {
471 sstrncpy(buffer, "root", buffer_size);
476 /* Move one to the left */
477 if (buffer[0] == '/') {
478 memmove(buffer, buffer + 1, buffer_len);
482 for (size_t i = 0; i < buffer_len; i++) {
483 if (buffer[i] == '/')
488 } /* int escape_slashes */
490 void replace_special(char *buffer, size_t buffer_size) {
491 for (size_t i = 0; i < buffer_size; i++) {
494 if ((!isalnum((int)buffer[i])) && (buffer[i] != '-'))
497 } /* void replace_special */
499 int timeval_cmp(struct timeval tv0, struct timeval tv1, struct timeval *delta) {
500 struct timeval *larger;
501 struct timeval *smaller;
505 NORMALIZE_TIMEVAL(tv0);
506 NORMALIZE_TIMEVAL(tv1);
508 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec)) {
516 if ((tv0.tv_sec < tv1.tv_sec) ||
517 ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec))) {
528 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
530 if (smaller->tv_usec <= larger->tv_usec)
531 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
534 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
538 assert((delta == NULL) ||
539 ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
542 } /* int timeval_cmp */
544 int check_create_dir(const char *file_orig) {
554 int last_is_file = 1;
555 int path_is_absolute = 0;
559 * Sanity checks first
561 if (file_orig == NULL)
564 if ((len = strlen(file_orig)) < 1)
566 else if (len >= sizeof(file_copy))
570 * If `file_orig' ends in a slash the last component is a directory,
571 * otherwise it's a file. Act accordingly..
573 if (file_orig[len - 1] == '/')
575 if (file_orig[0] == '/')
576 path_is_absolute = 1;
579 * Create a copy for `strtok_r' to destroy
581 sstrncpy(file_copy, file_orig, sizeof(file_copy));
584 * Break into components. This will eat up several slashes in a row and
585 * remove leading and trailing slashes..
590 while ((fields[fields_num] = strtok_r(ptr, "/", &saveptr)) != NULL) {
594 if (fields_num >= 16)
599 * For each component, do..
601 for (int i = 0; i < (fields_num - last_is_file); i++) {
603 * Do not create directories that start with a dot. This
604 * prevents `../../' attacks and other likely malicious
607 if (fields[i][0] == '.') {
608 ERROR("Cowardly refusing to create a directory that "
609 "begins with a `.' (dot): `%s'",
615 * Join the components together again
618 if (strjoin(dir + path_is_absolute, (size_t)(dir_len - path_is_absolute),
619 fields, (size_t)(i + 1), "/") < 0) {
620 ERROR("strjoin failed: `%s', component #%i", file_orig, i);
625 if ((stat(dir, &statbuf) == -1) && (lstat(dir, &statbuf) == -1)) {
626 if (errno == ENOENT) {
627 if (mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
630 /* this might happen, if a different thread created
631 * the directory in the meantime
632 * => call stat() again to check for S_ISDIR() */
636 ERROR("check_create_dir: mkdir (%s): %s", dir, STRERRNO);
639 ERROR("check_create_dir: stat (%s): %s", dir, STRERRNO);
642 } else if (!S_ISDIR(statbuf.st_mode)) {
643 ERROR("check_create_dir: `%s' exists but is not "
653 } /* check_create_dir */
656 int get_kstat(kstat_t **ksp_ptr, char *module, int instance, char *name) {
664 snprintf(ident, sizeof(ident), "%s,%i,%s", module, instance, name);
666 *ksp_ptr = kstat_lookup(kc, module, instance, name);
667 if (*ksp_ptr == NULL) {
668 ERROR("get_kstat: Cound not find kstat %s", ident);
672 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
673 ERROR("get_kstat: kstat %s has wrong type", ident);
679 assert(*ksp_ptr != NULL);
680 assert((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
683 if (kstat_read(kc, *ksp_ptr, NULL) == -1) {
684 ERROR("get_kstat: kstat %s could not be read", ident);
688 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED) {
689 ERROR("get_kstat: kstat %s has wrong type", ident);
696 long long get_kstat_value(kstat_t *ksp, char *name) {
698 long long retval = -1LL;
701 ERROR("get_kstat_value (\"%s\"): ksp is NULL.", name);
703 } else if (ksp->ks_type != KSTAT_TYPE_NAMED) {
704 ERROR("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
705 "is not KSTAT_TYPE_NAMED (%#x).",
706 name, (unsigned int)ksp->ks_type, (unsigned int)KSTAT_TYPE_NAMED);
710 if ((kn = (kstat_named_t *)kstat_data_lookup(ksp, name)) == NULL)
713 if (kn->data_type == KSTAT_DATA_INT32)
714 retval = (long long)kn->value.i32;
715 else if (kn->data_type == KSTAT_DATA_UINT32)
716 retval = (long long)kn->value.ui32;
717 else if (kn->data_type == KSTAT_DATA_INT64)
719 (long long)kn->value.i64; /* According to ANSI C99 `long long' must hold
721 else if (kn->data_type == KSTAT_DATA_UINT64)
722 retval = (long long)kn->value.ui64; /* XXX: Might overflow! */
724 WARNING("get_kstat_value: Not a numeric value: %s", name);
728 #endif /* HAVE_LIBKSTAT */
731 unsigned long long ntohll(unsigned long long n) {
732 #if BYTE_ORDER == BIG_ENDIAN
735 return (((unsigned long long)ntohl(n)) << 32) + ntohl(n >> 32);
737 } /* unsigned long long ntohll */
739 unsigned long long htonll(unsigned long long n) {
740 #if BYTE_ORDER == BIG_ENDIAN
743 return (((unsigned long long)htonl(n)) << 32) + htonl(n >> 32);
745 } /* unsigned long long htonll */
746 #endif /* HAVE_HTONLL */
748 #if FP_LAYOUT_NEED_NOTHING
749 /* Well, we need nothing.. */
750 /* #endif FP_LAYOUT_NEED_NOTHING */
752 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
753 #if FP_LAYOUT_NEED_ENDIANFLIP
754 #define FP_CONVERT(A) \
755 ((((uint64_t)(A)&0xff00000000000000LL) >> 56) | \
756 (((uint64_t)(A)&0x00ff000000000000LL) >> 40) | \
757 (((uint64_t)(A)&0x0000ff0000000000LL) >> 24) | \
758 (((uint64_t)(A)&0x000000ff00000000LL) >> 8) | \
759 (((uint64_t)(A)&0x00000000ff000000LL) << 8) | \
760 (((uint64_t)(A)&0x0000000000ff0000LL) << 24) | \
761 (((uint64_t)(A)&0x000000000000ff00LL) << 40) | \
762 (((uint64_t)(A)&0x00000000000000ffLL) << 56))
764 #define FP_CONVERT(A) \
765 ((((uint64_t)(A)&0xffffffff00000000LL) >> 32) | \
766 (((uint64_t)(A)&0x00000000ffffffffLL) << 32))
769 double ntohd(double d) {
778 /* NAN in x86 byte order */
779 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00) && (ret.byte[2] == 0x00) &&
780 (ret.byte[3] == 0x00) && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00) &&
781 (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f)) {
787 ret.integer = FP_CONVERT(tmp);
792 double htond(double d) {
800 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
801 ret.byte[4] = ret.byte[5] = 0x00;
809 tmp = FP_CONVERT(ret.integer);
814 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
816 int format_name(char *ret, int ret_len, const char *hostname,
817 const char *plugin, const char *plugin_instance,
818 const char *type, const char *type_instance) {
823 buffer_size = (size_t)ret_len;
825 #define APPEND(str) \
827 size_t l = strlen(str); \
828 if (l >= buffer_size) \
830 memcpy(buffer, (str), l); \
835 assert(plugin != NULL);
836 assert(type != NULL);
841 if ((plugin_instance != NULL) && (plugin_instance[0] != 0)) {
843 APPEND(plugin_instance);
847 if ((type_instance != NULL) && (type_instance[0] != 0)) {
849 APPEND(type_instance);
851 assert(buffer_size > 0);
856 } /* int format_name */
858 int format_values(char *ret, size_t ret_len, /* {{{ */
859 const data_set_t *ds, const value_list_t *vl,
863 gauge_t *rates = NULL;
865 assert(0 == strcmp(ds->type, vl->type));
867 memset(ret, 0, ret_len);
869 #define BUFFER_ADD(...) \
871 status = snprintf(ret + offset, ret_len - offset, __VA_ARGS__); \
875 } else if (((size_t)status) >= (ret_len - offset)) { \
879 offset += ((size_t)status); \
882 BUFFER_ADD("%.3f", CDTIME_T_TO_DOUBLE(vl->time));
884 for (size_t i = 0; i < ds->ds_num; i++) {
885 if (ds->ds[i].type == DS_TYPE_GAUGE)
886 BUFFER_ADD(":" GAUGE_FORMAT, vl->values[i].gauge);
887 else if (store_rates) {
889 rates = uc_get_rate(ds, vl);
891 WARNING("format_values: uc_get_rate failed.");
894 BUFFER_ADD(":" GAUGE_FORMAT, rates[i]);
895 } else if (ds->ds[i].type == DS_TYPE_COUNTER)
896 BUFFER_ADD(":%" PRIu64, (uint64_t)vl->values[i].counter);
897 else if (ds->ds[i].type == DS_TYPE_DERIVE)
898 BUFFER_ADD(":%" PRIi64, vl->values[i].derive);
899 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
900 BUFFER_ADD(":%" PRIu64, vl->values[i].absolute);
902 ERROR("format_values: Unknown data source type: %i", ds->ds[i].type);
906 } /* for ds->ds_num */
912 } /* }}} int format_values */
914 int parse_identifier(char *str, char **ret_host, char **ret_plugin,
915 char **ret_plugin_instance, char **ret_type,
916 char **ret_type_instance, char *default_host) {
917 char *hostname = NULL;
919 char *plugin_instance = NULL;
921 char *type_instance = NULL;
924 if (hostname == NULL)
927 plugin = strchr(hostname, '/');
933 type = strchr(plugin, '/');
935 if (default_host == NULL)
937 /* else: no host specified; use default */
940 hostname = default_host;
946 plugin_instance = strchr(plugin, '-');
947 if (plugin_instance != NULL) {
948 *plugin_instance = '\0';
952 type_instance = strchr(type, '-');
953 if (type_instance != NULL) {
954 *type_instance = '\0';
958 *ret_host = hostname;
959 *ret_plugin = plugin;
960 *ret_plugin_instance = plugin_instance;
962 *ret_type_instance = type_instance;
964 } /* int parse_identifier */
966 int parse_identifier_vl(const char *str, value_list_t *vl) /* {{{ */
968 char str_copy[6 * DATA_MAX_NAME_LEN];
971 char *plugin_instance = NULL;
973 char *type_instance = NULL;
976 if ((str == NULL) || (vl == NULL))
979 sstrncpy(str_copy, str, sizeof(str_copy));
981 status = parse_identifier(str_copy, &host, &plugin, &plugin_instance, &type,
983 /* default_host = */ NULL);
987 sstrncpy(vl->host, host, sizeof(vl->host));
988 sstrncpy(vl->plugin, plugin, sizeof(vl->plugin));
989 sstrncpy(vl->plugin_instance,
990 (plugin_instance != NULL) ? plugin_instance : "",
991 sizeof(vl->plugin_instance));
992 sstrncpy(vl->type, type, sizeof(vl->type));
993 sstrncpy(vl->type_instance, (type_instance != NULL) ? type_instance : "",
994 sizeof(vl->type_instance));
997 } /* }}} int parse_identifier_vl */
999 int parse_value(const char *value_orig, value_t *ret_value, int ds_type) {
1001 char *endptr = NULL;
1004 if (value_orig == NULL)
1007 value = strdup(value_orig);
1010 value_len = strlen(value);
1012 while ((value_len > 0) && isspace((int)value[value_len - 1])) {
1013 value[value_len - 1] = 0;
1018 case DS_TYPE_COUNTER:
1019 ret_value->counter = (counter_t)strtoull(value, &endptr, 0);
1023 ret_value->gauge = (gauge_t)strtod(value, &endptr);
1026 case DS_TYPE_DERIVE:
1027 ret_value->derive = (derive_t)strtoll(value, &endptr, 0);
1030 case DS_TYPE_ABSOLUTE:
1031 ret_value->absolute = (absolute_t)strtoull(value, &endptr, 0);
1036 ERROR("parse_value: Invalid data source type: %i.", ds_type);
1040 if (value == endptr) {
1041 ERROR("parse_value: Failed to parse string as %s: \"%s\".",
1042 DS_TYPE_TO_STRING(ds_type), value);
1045 } else if ((NULL != endptr) && ('\0' != *endptr))
1046 INFO("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1047 "Input string was \"%s\".",
1048 endptr, DS_TYPE_TO_STRING(ds_type), value_orig);
1052 } /* int parse_value */
1054 int parse_values(char *buffer, value_list_t *vl, const data_set_t *ds) {
1060 if ((buffer == NULL) || (vl == NULL) || (ds == NULL))
1067 while ((ptr = strtok_r(dummy, ":", &saveptr)) != NULL) {
1070 if (i >= vl->values_len) {
1071 /* Make sure i is invalid. */
1076 if (vl->time == 0) {
1077 if (strcmp("N", ptr) == 0)
1078 vl->time = cdtime();
1080 char *endptr = NULL;
1084 tmp = strtod(ptr, &endptr);
1085 if ((errno != 0) /* Overflow */
1086 || (endptr == ptr) /* Invalid string */
1087 || (endptr == NULL) /* This should not happen */
1088 || (*endptr != 0)) /* Trailing chars */
1091 vl->time = DOUBLE_TO_CDTIME_T(tmp);
1097 if ((strcmp("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1098 vl->values[i].gauge = NAN;
1099 else if (0 != parse_value(ptr, &vl->values[i], ds->ds[i].type))
1103 } /* while (strtok_r) */
1105 if ((ptr != NULL) || (i == 0))
1108 } /* int parse_values */
1110 int parse_value_file(char const *path, value_t *ret_value, int ds_type) {
1114 fh = fopen(path, "r");
1118 if (fgets(buffer, sizeof(buffer), fh) == NULL) {
1125 strstripnewline(buffer);
1127 return parse_value(buffer, ret_value, ds_type);
1128 } /* int parse_value_file */
1130 #if !HAVE_GETPWNAM_R
1131 int getpwnam_r(const char *name, struct passwd *pwbuf, char *buf, size_t buflen,
1132 struct passwd **pwbufp) {
1136 memset(pwbuf, '\0', sizeof(struct passwd));
1138 pthread_mutex_lock(&getpwnam_r_lock);
1141 pw = getpwnam(name);
1143 status = (errno != 0) ? errno : ENOENT;
1147 #define GETPWNAM_COPY_MEMBER(member) \
1148 if (pw->member != NULL) { \
1149 int len = strlen(pw->member); \
1150 if (len >= buflen) { \
1154 sstrncpy(buf, pw->member, buflen); \
1155 pwbuf->member = buf; \
1157 buflen -= (len + 1); \
1159 GETPWNAM_COPY_MEMBER(pw_name);
1160 GETPWNAM_COPY_MEMBER(pw_passwd);
1161 GETPWNAM_COPY_MEMBER(pw_gecos);
1162 GETPWNAM_COPY_MEMBER(pw_dir);
1163 GETPWNAM_COPY_MEMBER(pw_shell);
1165 pwbuf->pw_uid = pw->pw_uid;
1166 pwbuf->pw_gid = pw->pw_gid;
1172 pthread_mutex_unlock(&getpwnam_r_lock);
1175 } /* int getpwnam_r */
1176 #endif /* !HAVE_GETPWNAM_R */
1178 int notification_init(notification_t *n, int severity, const char *message,
1179 const char *host, const char *plugin,
1180 const char *plugin_instance, const char *type,
1181 const char *type_instance) {
1182 memset(n, '\0', sizeof(notification_t));
1184 n->severity = severity;
1186 if (message != NULL)
1187 sstrncpy(n->message, message, sizeof(n->message));
1189 sstrncpy(n->host, host, sizeof(n->host));
1191 sstrncpy(n->plugin, plugin, sizeof(n->plugin));
1192 if (plugin_instance != NULL)
1193 sstrncpy(n->plugin_instance, plugin_instance, sizeof(n->plugin_instance));
1195 sstrncpy(n->type, type, sizeof(n->type));
1196 if (type_instance != NULL)
1197 sstrncpy(n->type_instance, type_instance, sizeof(n->type_instance));
1200 } /* int notification_init */
1202 int walk_directory(const char *dir, dirwalk_callback_f callback,
1203 void *user_data, int include_hidden) {
1212 if ((dh = opendir(dir)) == NULL) {
1213 ERROR("walk_directory: Cannot open '%s': %s", dir, STRERRNO);
1217 while ((ent = readdir(dh)) != NULL) {
1220 if (include_hidden) {
1221 if ((strcmp(".", ent->d_name) == 0) || (strcmp("..", ent->d_name) == 0))
1223 } else /* if (!include_hidden) */
1225 if (ent->d_name[0] == '.')
1229 status = (*callback)(dir, ent->d_name, user_data);
1238 if ((success == 0) && (failure > 0))
1243 ssize_t read_file_contents(const char *filename, char *buf, size_t bufsize) {
1247 fh = fopen(filename, "r");
1251 ret = (ssize_t)fread(buf, 1, bufsize, fh);
1252 if ((ret == 0) && (ferror(fh) != 0)) {
1253 ERROR("read_file_contents: Reading file \"%s\" failed.", filename);
1261 counter_t counter_diff(counter_t old_value, counter_t new_value) {
1264 if (old_value > new_value) {
1265 if (old_value <= 4294967295U)
1266 diff = (4294967295U - old_value) + new_value + 1;
1268 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1270 diff = new_value - old_value;
1274 } /* counter_t counter_diff */
1276 int rate_to_value(value_t *ret_value, gauge_t rate, /* {{{ */
1277 rate_to_value_state_t *state, int ds_type, cdtime_t t) {
1278 gauge_t delta_gauge;
1281 if (ds_type == DS_TYPE_GAUGE) {
1282 state->last_value.gauge = rate;
1283 state->last_time = t;
1285 *ret_value = state->last_value;
1289 /* Counter and absolute can't handle negative rates. Reset "last time"
1290 * to zero, so that the next valid rate will re-initialize the
1293 ((ds_type == DS_TYPE_COUNTER) || (ds_type == DS_TYPE_ABSOLUTE))) {
1294 memset(state, 0, sizeof(*state));
1298 /* Another invalid state: The time is not increasing. */
1299 if (t <= state->last_time) {
1300 memset(state, 0, sizeof(*state));
1304 delta_t = t - state->last_time;
1305 delta_gauge = (rate * CDTIME_T_TO_DOUBLE(delta_t)) + state->residual;
1307 /* Previous value is invalid. */
1308 if (state->last_time == 0) /* {{{ */
1310 if (ds_type == DS_TYPE_DERIVE) {
1311 state->last_value.derive = (derive_t)rate;
1312 state->residual = rate - ((gauge_t)state->last_value.derive);
1313 } else if (ds_type == DS_TYPE_COUNTER) {
1314 state->last_value.counter = (counter_t)rate;
1315 state->residual = rate - ((gauge_t)state->last_value.counter);
1316 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1317 state->last_value.absolute = (absolute_t)rate;
1318 state->residual = rate - ((gauge_t)state->last_value.absolute);
1323 state->last_time = t;
1327 if (ds_type == DS_TYPE_DERIVE) {
1328 derive_t delta_derive = (derive_t)delta_gauge;
1330 state->last_value.derive += delta_derive;
1331 state->residual = delta_gauge - ((gauge_t)delta_derive);
1332 } else if (ds_type == DS_TYPE_COUNTER) {
1333 counter_t delta_counter = (counter_t)delta_gauge;
1335 state->last_value.counter += delta_counter;
1336 state->residual = delta_gauge - ((gauge_t)delta_counter);
1337 } else if (ds_type == DS_TYPE_ABSOLUTE) {
1338 absolute_t delta_absolute = (absolute_t)delta_gauge;
1340 state->last_value.absolute = delta_absolute;
1341 state->residual = delta_gauge - ((gauge_t)delta_absolute);
1346 state->last_time = t;
1347 *ret_value = state->last_value;
1349 } /* }}} value_t rate_to_value */
1351 int value_to_rate(gauge_t *ret_rate, /* {{{ */
1352 value_t value, int ds_type, cdtime_t t,
1353 value_to_rate_state_t *state) {
1356 /* Another invalid state: The time is not increasing. */
1357 if (t <= state->last_time) {
1358 memset(state, 0, sizeof(*state));
1362 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1364 /* Previous value is invalid. */
1365 if (state->last_time == 0) {
1366 state->last_value = value;
1367 state->last_time = t;
1372 case DS_TYPE_DERIVE: {
1373 derive_t diff = value.derive - state->last_value.derive;
1374 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1377 case DS_TYPE_GAUGE: {
1378 *ret_rate = value.gauge;
1381 case DS_TYPE_COUNTER: {
1382 counter_t diff = counter_diff(state->last_value.counter, value.counter);
1383 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1386 case DS_TYPE_ABSOLUTE: {
1387 absolute_t diff = value.absolute;
1388 *ret_rate = ((gauge_t)diff) / ((gauge_t)interval);
1395 state->last_value = value;
1396 state->last_time = t;
1398 } /* }}} value_t rate_to_value */
1400 int service_name_to_port_number(const char *service_name) {
1401 struct addrinfo *ai_list;
1405 if (service_name == NULL)
1408 struct addrinfo ai_hints = {.ai_family = AF_UNSPEC};
1410 status = getaddrinfo(/* node = */ NULL, service_name, &ai_hints, &ai_list);
1412 ERROR("service_name_to_port_number: getaddrinfo failed: %s",
1413 gai_strerror(status));
1417 service_number = -1;
1418 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
1419 ai_ptr = ai_ptr->ai_next) {
1420 if (ai_ptr->ai_family == AF_INET) {
1421 struct sockaddr_in *sa;
1423 sa = (void *)ai_ptr->ai_addr;
1424 service_number = (int)ntohs(sa->sin_port);
1425 } else if (ai_ptr->ai_family == AF_INET6) {
1426 struct sockaddr_in6 *sa;
1428 sa = (void *)ai_ptr->ai_addr;
1429 service_number = (int)ntohs(sa->sin6_port);
1432 if ((service_number > 0) && (service_number <= 65535))
1436 freeaddrinfo(ai_list);
1438 if ((service_number > 0) && (service_number <= 65535))
1439 return service_number;
1441 } /* int service_name_to_port_number */
1443 void set_sock_opts(int sockfd) /* {{{ */
1448 status = getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &socktype,
1449 &(socklen_t){sizeof(socktype)});
1451 WARNING("set_sock_opts: failed to determine socket type");
1455 if (socktype == SOCK_STREAM) {
1457 setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &(int){1}, sizeof(int));
1459 WARNING("set_sock_opts: failed to set socket keepalive flag");
1462 int tcp_keepidle = ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 100 + 1);
1463 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &tcp_keepidle,
1464 sizeof(tcp_keepidle));
1466 WARNING("set_sock_opts: failed to set socket tcp keepalive time");
1469 #ifdef TCP_KEEPINTVL
1471 ((CDTIME_T_TO_MS(plugin_get_interval()) - 1) / 1000 + 1);
1472 status = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &tcp_keepintvl,
1473 sizeof(tcp_keepintvl));
1475 WARNING("set_sock_opts: failed to set socket tcp keepalive interval");
1478 } /* }}} void set_sock_opts */
1480 int strtoderive(const char *string, derive_t *ret_value) /* {{{ */
1485 if ((string == NULL) || (ret_value == NULL))
1490 tmp = (derive_t)strtoll(string, &endptr, /* base = */ 0);
1491 if ((endptr == string) || (errno != 0))
1496 } /* }}} int strtoderive */
1498 int strtogauge(const char *string, gauge_t *ret_value) /* {{{ */
1501 char *endptr = NULL;
1503 if ((string == NULL) || (ret_value == NULL))
1508 tmp = (gauge_t)strtod(string, &endptr);
1511 else if ((endptr == NULL) || (*endptr != 0))
1516 } /* }}} int strtogauge */
1518 int strarray_add(char ***ret_array, size_t *ret_array_len,
1519 char const *str) /* {{{ */
1522 size_t array_len = *ret_array_len;
1527 array = realloc(*ret_array, (array_len + 1) * sizeof(*array));
1532 array[array_len] = strdup(str);
1533 if (array[array_len] == NULL)
1537 *ret_array_len = array_len;
1539 } /* }}} int strarray_add */
1541 void strarray_free(char **array, size_t array_len) /* {{{ */
1543 for (size_t i = 0; i < array_len; i++)
1546 } /* }}} void strarray_free */
1549 int check_capability(int arg) /* {{{ */
1551 cap_value_t cap_value = (cap_value_t)arg;
1553 cap_flag_value_t cap_flag_value;
1555 if (!CAP_IS_SUPPORTED(cap_value))
1558 if (!(cap = cap_get_proc())) {
1559 ERROR("check_capability: cap_get_proc failed.");
1563 if (cap_get_flag(cap, cap_value, CAP_EFFECTIVE, &cap_flag_value) < 0) {
1564 ERROR("check_capability: cap_get_flag failed.");
1570 return cap_flag_value != CAP_SET;
1571 } /* }}} int check_capability */
1573 int check_capability(__attribute__((unused)) int arg) /* {{{ */
1575 WARNING("check_capability: unsupported capability implementation. "
1576 "Some plugin(s) may require elevated privileges to work properly.");
1578 } /* }}} int check_capability */
1579 #endif /* HAVE_CAPABILITY */