2 * collectd - src/common.c
3 * Copyright (C) 2005-2015 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>
37 #include "utils_cache.h"
48 #include <sys/types.h>
49 #include <sys/socket.h>
53 # include <netinet/in.h>
56 /* for ntohl and htonl */
58 # include <arpa/inet.h>
62 extern kstat_ctl_t *kc;
66 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
70 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
73 char *sstrncpy (char *dest, const char *src, size_t n)
75 strncpy (dest, src, n);
79 } /* char *sstrncpy */
81 int ssnprintf (char *dest, size_t n, const char *format, ...)
86 va_start (ap, format);
87 ret = vsnprintf (dest, n, format, ap);
94 char *ssnprintf_alloc (char const *format, ...) /* {{{ */
96 char static_buffer[1024] = "";
98 size_t alloc_buffer_size;
102 /* Try printing into the static buffer. In many cases it will be
103 * sufficiently large and we can simply return a strdup() of this
105 va_start (ap, format);
106 status = vsnprintf (static_buffer, sizeof (static_buffer), format, ap);
111 /* "status" does not include the null byte. */
112 alloc_buffer_size = (size_t) (status + 1);
113 if (alloc_buffer_size <= sizeof (static_buffer))
114 return (strdup (static_buffer));
116 /* Allocate a buffer large enough to hold the string. */
117 alloc_buffer = malloc (alloc_buffer_size);
118 if (alloc_buffer == NULL)
120 memset (alloc_buffer, 0, alloc_buffer_size);
122 /* Print again into this new buffer. */
123 va_start (ap, format);
124 status = vsnprintf (alloc_buffer, alloc_buffer_size, format, ap);
128 sfree (alloc_buffer);
132 return (alloc_buffer);
133 } /* }}} char *ssnprintf_alloc */
135 char *sstrdup (const char *s)
143 /* Do not use `strdup' here, because it's not specified in POSIX. It's
144 * ``only'' an XSI extension. */
146 r = (char *) malloc (sizeof (char) * sz);
149 ERROR ("sstrdup: Out of memory.");
152 memcpy (r, s, sizeof (char) * sz);
155 } /* char *sstrdup */
157 /* Even though Posix requires "strerror_r" to return an "int",
158 * some systems (e.g. the GNU libc) return a "char *" _and_
159 * ignore the second argument ... -tokkee */
160 char *sstrerror (int errnum, char *buf, size_t buflen)
168 pthread_mutex_lock (&strerror_r_lock);
170 temp = strerror (errnum);
171 sstrncpy (buf, temp, buflen);
173 pthread_mutex_unlock (&strerror_r_lock);
175 /* #endif !HAVE_STRERROR_R */
177 #elif STRERROR_R_CHAR_P
180 temp = strerror_r (errnum, buf, buflen);
183 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
184 sstrncpy (buf, temp, buflen);
186 sstrncpy (buf, "strerror_r did not return "
187 "an error message", buflen);
190 /* #endif STRERROR_R_CHAR_P */
193 if (strerror_r (errnum, buf, buflen) != 0)
195 ssnprintf (buf, buflen, "Error #%i; "
196 "Additionally, strerror_r failed.",
199 #endif /* STRERROR_R_CHAR_P */
202 } /* char *sstrerror */
204 void *smalloc (size_t size)
208 if ((r = malloc (size)) == NULL)
210 ERROR ("Not enough memory.");
215 } /* void *smalloc */
218 void sfree (void **ptr)
230 ssize_t sread (int fd, void *buf, size_t count)
241 status = read (fd, (void *) ptr, nleft);
243 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
251 DEBUG ("Received EOF from fd %i. "
252 "Closing fd and returning error.",
258 assert ((0 > status) || (nleft >= (size_t)status));
260 nleft = nleft - status;
267 int read_file (char const *file, void **ret_data, size_t *ret_data_size)
269 int fd = open (file, O_RDONLY);
273 struct stat statbuf = { 0 };
274 if (fstat (fd, &statbuf) == -1)
280 size_t data_size = (size_t) statbuf.st_size;
281 void *data = malloc (data_size);
288 if (sread (fd, data, data_size) != 0)
297 *ret_data_size = data_size;
299 } /* }}} int read_file */
301 ssize_t swrite (int fd, const void *buf, size_t count)
307 ptr = (const char *) buf;
312 status = write (fd, (const void *) ptr, nleft);
314 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
320 nleft = nleft - status;
327 int strsplit (char *string, char **fields, size_t size)
336 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
348 int strjoin (char *dst, size_t dst_len,
349 char **fields, size_t fields_num,
356 memset (dst, '\0', dst_len);
363 sep_len = strlen (sep);
365 for (i = 0; i < (int)fields_num; i++)
367 if ((i > 0) && (sep_len > 0))
369 if (dst_len <= sep_len)
372 strncat (dst, sep, dst_len);
376 field_len = strlen (fields[i]);
378 if (dst_len <= field_len)
381 strncat (dst, fields[i], dst_len);
382 dst_len -= field_len;
385 return (strlen (dst));
388 int strsubstitute (char *str, char c_from, char c_to)
407 } /* int strsubstitute */
409 int escape_string (char *buffer, size_t buffer_size)
415 /* Check if we need to escape at all first */
416 temp = strpbrk (buffer, " \t\"\\");
423 temp = (char *) malloc (buffer_size);
426 memset (temp, 0, buffer_size);
431 for (i = 0; i < buffer_size; i++)
437 else if ((buffer[i] == '"') || (buffer[i] == '\\'))
439 if (j > (buffer_size - 4))
442 temp[j + 1] = buffer[i];
447 if (j > (buffer_size - 3))
454 assert ((j + 1) < buffer_size);
458 sstrncpy (buffer, temp, buffer_size);
461 } /* int escape_string */
463 int strunescape (char *buf, size_t buf_len)
467 for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
472 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
473 ERROR ("string unescape: backslash found at end of string.");
474 /* Ensure null-byte at the end of the buffer. */
479 switch (buf[i + 1]) {
494 /* Move everything after the position one position to the left.
495 * Add a null-byte as last character in the buffer. */
496 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
497 buf[buf_len - 1] = 0;
500 } /* int strunescape */
502 size_t strstripnewline (char *buffer)
504 size_t buffer_len = strlen (buffer);
506 while (buffer_len > 0)
508 if ((buffer[buffer_len - 1] != '\n')
509 && (buffer[buffer_len - 1] != '\r'))
512 buffer[buffer_len] = 0;
516 } /* size_t strstripnewline */
518 int escape_slashes (char *buffer, size_t buffer_size)
523 buffer_len = strlen (buffer);
527 if (strcmp ("/", buffer) == 0)
531 sstrncpy (buffer, "root", buffer_size);
536 /* Move one to the left */
537 if (buffer[0] == '/')
539 memmove (buffer, buffer + 1, buffer_len);
543 for (i = 0; i < buffer_len - 1; i++)
545 if (buffer[i] == '/')
550 } /* int escape_slashes */
552 void replace_special (char *buffer, size_t buffer_size)
556 for (i = 0; i < buffer_size; i++)
560 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
563 } /* void replace_special */
565 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
567 struct timeval *larger;
568 struct timeval *smaller;
572 NORMALIZE_TIMEVAL (tv0);
573 NORMALIZE_TIMEVAL (tv1);
575 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
584 if ((tv0.tv_sec < tv1.tv_sec)
585 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
599 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
601 if (smaller->tv_usec <= larger->tv_usec)
602 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
606 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
610 assert ((delta == NULL)
611 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
614 } /* int timeval_cmp */
616 int check_create_dir (const char *file_orig)
627 int last_is_file = 1;
628 int path_is_absolute = 0;
633 * Sanity checks first
635 if (file_orig == NULL)
638 if ((len = strlen (file_orig)) < 1)
640 else if (len >= sizeof (file_copy))
644 * If `file_orig' ends in a slash the last component is a directory,
645 * otherwise it's a file. Act accordingly..
647 if (file_orig[len - 1] == '/')
649 if (file_orig[0] == '/')
650 path_is_absolute = 1;
653 * Create a copy for `strtok_r' to destroy
655 sstrncpy (file_copy, file_orig, sizeof (file_copy));
658 * Break into components. This will eat up several slashes in a row and
659 * remove leading and trailing slashes..
664 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
669 if (fields_num >= 16)
674 * For each component, do..
676 for (i = 0; i < (fields_num - last_is_file); i++)
679 * Do not create directories that start with a dot. This
680 * prevents `../../' attacks and other likely malicious
683 if (fields[i][0] == '.')
685 ERROR ("Cowardly refusing to create a directory that "
686 "begins with a `.' (dot): `%s'", file_orig);
691 * Join the components together again
694 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
695 fields, i + 1, "/") < 0)
697 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
702 if ((stat (dir, &statbuf) == -1)
703 && (lstat (dir, &statbuf) == -1))
707 if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
710 /* this might happen, if a different thread created
711 * the directory in the meantime
712 * => call stat() again to check for S_ISDIR() */
717 ERROR ("check_create_dir: mkdir (%s): %s", dir,
719 errbuf, sizeof (errbuf)));
725 ERROR ("check_create_dir: stat (%s): %s", dir,
726 sstrerror (errno, errbuf,
731 else if (!S_ISDIR (statbuf.st_mode))
733 ERROR ("check_create_dir: `%s' exists but is not "
734 "a directory!", dir);
742 } /* check_create_dir */
745 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
754 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
756 *ksp_ptr = kstat_lookup (kc, module, instance, name);
757 if (*ksp_ptr == NULL)
759 ERROR ("get_kstat: Cound not find kstat %s", ident);
763 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
765 ERROR ("get_kstat: kstat %s has wrong type", ident);
771 assert (*ksp_ptr != NULL);
772 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
775 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
777 ERROR ("get_kstat: kstat %s could not be read", ident);
781 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
783 ERROR ("get_kstat: kstat %s has wrong type", ident);
790 long long get_kstat_value (kstat_t *ksp, char *name)
793 long long retval = -1LL;
797 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
800 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
802 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
803 "is not KSTAT_TYPE_NAMED (%#x).",
805 (unsigned int) ksp->ks_type,
806 (unsigned int) KSTAT_TYPE_NAMED);
810 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
813 if (kn->data_type == KSTAT_DATA_INT32)
814 retval = (long long) kn->value.i32;
815 else if (kn->data_type == KSTAT_DATA_UINT32)
816 retval = (long long) kn->value.ui32;
817 else if (kn->data_type == KSTAT_DATA_INT64)
818 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
819 else if (kn->data_type == KSTAT_DATA_UINT64)
820 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
822 WARNING ("get_kstat_value: Not a numeric value: %s", name);
826 #endif /* HAVE_LIBKSTAT */
829 unsigned long long ntohll (unsigned long long n)
831 #if BYTE_ORDER == BIG_ENDIAN
834 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
836 } /* unsigned long long ntohll */
838 unsigned long long htonll (unsigned long long n)
840 #if BYTE_ORDER == BIG_ENDIAN
843 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
845 } /* unsigned long long htonll */
846 #endif /* HAVE_HTONLL */
848 #if FP_LAYOUT_NEED_NOTHING
849 /* Well, we need nothing.. */
850 /* #endif FP_LAYOUT_NEED_NOTHING */
852 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
853 # if FP_LAYOUT_NEED_ENDIANFLIP
854 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
855 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
856 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
857 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
858 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
859 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
860 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
861 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
863 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
864 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
867 double ntohd (double d)
878 /* NAN in x86 byte order */
879 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
880 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
881 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
882 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
891 ret.integer = FP_CONVERT (tmp);
892 return (ret.floating);
896 double htond (double d)
907 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
908 ret.byte[4] = ret.byte[5] = 0x00;
911 return (ret.floating);
918 tmp = FP_CONVERT (ret.integer);
920 return (ret.floating);
923 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
925 int format_name (char *ret, int ret_len,
926 const char *hostname,
927 const char *plugin, const char *plugin_instance,
928 const char *type, const char *type_instance)
934 buffer_size = (size_t) ret_len;
936 #define APPEND(str) do { \
937 size_t l = strlen (str); \
938 if (l >= buffer_size) \
940 memcpy (buffer, (str), l); \
941 buffer += l; buffer_size -= l; \
944 assert (plugin != NULL);
945 assert (type != NULL);
950 if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
953 APPEND (plugin_instance);
957 if ((type_instance != NULL) && (type_instance[0] != 0))
960 APPEND (type_instance);
962 assert (buffer_size > 0);
967 } /* int format_name */
969 int format_values (char *ret, size_t ret_len, /* {{{ */
970 const data_set_t *ds, const value_list_t *vl,
976 gauge_t *rates = NULL;
978 assert (0 == strcmp (ds->type, vl->type));
980 memset (ret, 0, ret_len);
982 #define BUFFER_ADD(...) do { \
983 status = ssnprintf (ret + offset, ret_len - offset, \
990 else if (((size_t) status) >= (ret_len - offset)) \
996 offset += ((size_t) status); \
999 BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
1001 for (i = 0; i < ds->ds_num; i++)
1003 if (ds->ds[i].type == DS_TYPE_GAUGE)
1004 BUFFER_ADD (":"GAUGE_FORMAT, vl->values[i].gauge);
1005 else if (store_rates)
1008 rates = uc_get_rate (ds, vl);
1011 WARNING ("format_values: uc_get_rate failed.");
1014 BUFFER_ADD (":"GAUGE_FORMAT, rates[i]);
1016 else if (ds->ds[i].type == DS_TYPE_COUNTER)
1017 BUFFER_ADD (":%llu", vl->values[i].counter);
1018 else if (ds->ds[i].type == DS_TYPE_DERIVE)
1019 BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
1020 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
1021 BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
1024 ERROR ("format_values: Unknown data source type: %i",
1029 } /* for ds->ds_num */
1035 } /* }}} int format_values */
1037 int parse_identifier (char *str, char **ret_host,
1038 char **ret_plugin, char **ret_plugin_instance,
1039 char **ret_type, char **ret_type_instance)
1041 char *hostname = NULL;
1042 char *plugin = NULL;
1043 char *plugin_instance = NULL;
1045 char *type_instance = NULL;
1048 if (hostname == NULL)
1051 plugin = strchr (hostname, '/');
1054 *plugin = '\0'; plugin++;
1056 type = strchr (plugin, '/');
1059 *type = '\0'; type++;
1061 plugin_instance = strchr (plugin, '-');
1062 if (plugin_instance != NULL)
1064 *plugin_instance = '\0';
1068 type_instance = strchr (type, '-');
1069 if (type_instance != NULL)
1071 *type_instance = '\0';
1075 *ret_host = hostname;
1076 *ret_plugin = plugin;
1077 *ret_plugin_instance = plugin_instance;
1079 *ret_type_instance = type_instance;
1081 } /* int parse_identifier */
1083 int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
1085 char str_copy[6 * DATA_MAX_NAME_LEN];
1087 char *plugin = NULL;
1088 char *plugin_instance = NULL;
1090 char *type_instance = NULL;
1093 if ((str == NULL) || (vl == NULL))
1096 sstrncpy (str_copy, str, sizeof (str_copy));
1098 status = parse_identifier (str_copy, &host,
1099 &plugin, &plugin_instance,
1100 &type, &type_instance);
1104 sstrncpy (vl->host, host, sizeof (vl->host));
1105 sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
1106 sstrncpy (vl->plugin_instance,
1107 (plugin_instance != NULL) ? plugin_instance : "",
1108 sizeof (vl->plugin_instance));
1109 sstrncpy (vl->type, type, sizeof (vl->type));
1110 sstrncpy (vl->type_instance,
1111 (type_instance != NULL) ? type_instance : "",
1112 sizeof (vl->type_instance));
1115 } /* }}} int parse_identifier_vl */
1117 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
1120 char *endptr = NULL;
1123 if (value_orig == NULL)
1126 value = strdup (value_orig);
1129 value_len = strlen (value);
1131 while ((value_len > 0) && isspace ((int) value[value_len - 1]))
1133 value[value_len - 1] = 0;
1139 case DS_TYPE_COUNTER:
1140 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
1144 ret_value->gauge = (gauge_t) strtod (value, &endptr);
1147 case DS_TYPE_DERIVE:
1148 ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
1151 case DS_TYPE_ABSOLUTE:
1152 ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
1157 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
1161 if (value == endptr) {
1162 ERROR ("parse_value: Failed to parse string as %s: %s.",
1163 DS_TYPE_TO_STRING (ds_type), value);
1167 else if ((NULL != endptr) && ('\0' != *endptr))
1168 INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1169 "Input string was \"%s\".",
1170 endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
1174 } /* int parse_value */
1176 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
1186 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
1190 if (i >= vl->values_len)
1192 /* Make sure i is invalid. */
1193 i = vl->values_len + 1;
1199 if (strcmp ("N", ptr) == 0)
1200 vl->time = cdtime ();
1203 char *endptr = NULL;
1207 tmp = strtod (ptr, &endptr);
1208 if ((errno != 0) /* Overflow */
1209 || (endptr == ptr) /* Invalid string */
1210 || (endptr == NULL) /* This should not happen */
1211 || (*endptr != 0)) /* Trailing chars */
1214 vl->time = DOUBLE_TO_CDTIME_T (tmp);
1219 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1220 vl->values[i].gauge = NAN;
1221 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
1226 } /* while (strtok_r) */
1228 if ((ptr != NULL) || (i != vl->values_len))
1231 } /* int parse_values */
1233 #if !HAVE_GETPWNAM_R
1234 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
1235 size_t buflen, struct passwd **pwbufp)
1240 memset (pwbuf, '\0', sizeof (struct passwd));
1242 pthread_mutex_lock (&getpwnam_r_lock);
1246 pw = getpwnam (name);
1249 status = (errno != 0) ? errno : ENOENT;
1253 #define GETPWNAM_COPY_MEMBER(member) \
1254 if (pw->member != NULL) \
1256 int len = strlen (pw->member); \
1257 if (len >= buflen) \
1262 sstrncpy (buf, pw->member, buflen); \
1263 pwbuf->member = buf; \
1265 buflen -= (len + 1); \
1267 GETPWNAM_COPY_MEMBER(pw_name);
1268 GETPWNAM_COPY_MEMBER(pw_passwd);
1269 GETPWNAM_COPY_MEMBER(pw_gecos);
1270 GETPWNAM_COPY_MEMBER(pw_dir);
1271 GETPWNAM_COPY_MEMBER(pw_shell);
1273 pwbuf->pw_uid = pw->pw_uid;
1274 pwbuf->pw_gid = pw->pw_gid;
1280 pthread_mutex_unlock (&getpwnam_r_lock);
1283 } /* int getpwnam_r */
1284 #endif /* !HAVE_GETPWNAM_R */
1286 int notification_init (notification_t *n, int severity, const char *message,
1288 const char *plugin, const char *plugin_instance,
1289 const char *type, const char *type_instance)
1291 memset (n, '\0', sizeof (notification_t));
1293 n->severity = severity;
1295 if (message != NULL)
1296 sstrncpy (n->message, message, sizeof (n->message));
1298 sstrncpy (n->host, host, sizeof (n->host));
1300 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1301 if (plugin_instance != NULL)
1302 sstrncpy (n->plugin_instance, plugin_instance,
1303 sizeof (n->plugin_instance));
1305 sstrncpy (n->type, type, sizeof (n->type));
1306 if (type_instance != NULL)
1307 sstrncpy (n->type_instance, type_instance,
1308 sizeof (n->type_instance));
1311 } /* int notification_init */
1313 int walk_directory (const char *dir, dirwalk_callback_f callback,
1314 void *user_data, int include_hidden)
1324 if ((dh = opendir (dir)) == NULL)
1327 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1328 sstrerror (errno, errbuf, sizeof (errbuf)));
1332 while ((ent = readdir (dh)) != NULL)
1338 if ((strcmp (".", ent->d_name) == 0)
1339 || (strcmp ("..", ent->d_name) == 0))
1342 else /* if (!include_hidden) */
1344 if (ent->d_name[0]=='.')
1348 status = (*callback) (dir, ent->d_name, user_data);
1357 if ((success == 0) && (failure > 0))
1362 ssize_t read_file_contents (const char *filename, char *buf, size_t bufsize)
1367 fh = fopen (filename, "r");
1371 ret = (ssize_t) fread (buf, 1, bufsize, fh);
1372 if ((ret == 0) && (ferror (fh) != 0))
1374 ERROR ("read_file_contents: Reading file \"%s\" failed.",
1383 counter_t counter_diff (counter_t old_value, counter_t new_value)
1387 if (old_value > new_value)
1389 if (old_value <= 4294967295U)
1390 diff = (4294967295U - old_value) + new_value;
1392 diff = (18446744073709551615ULL - old_value)
1397 diff = new_value - old_value;
1401 } /* counter_t counter_diff */
1403 int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
1404 rate_to_value_state_t *state,
1405 int ds_type, cdtime_t t)
1407 gauge_t delta_gauge;
1410 if (ds_type == DS_TYPE_GAUGE)
1412 state->last_value.gauge = rate;
1413 state->last_time = t;
1415 *ret_value = state->last_value;
1419 /* Counter and absolute can't handle negative rates. Reset "last time"
1420 * to zero, so that the next valid rate will re-initialize the
1423 && ((ds_type == DS_TYPE_COUNTER)
1424 || (ds_type == DS_TYPE_ABSOLUTE)))
1426 memset (state, 0, sizeof (*state));
1430 /* Another invalid state: The time is not increasing. */
1431 if (t <= state->last_time)
1433 memset (state, 0, sizeof (*state));
1437 delta_t = t - state->last_time;
1438 delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
1440 /* Previous value is invalid. */
1441 if (state->last_time == 0) /* {{{ */
1443 if (ds_type == DS_TYPE_DERIVE)
1445 state->last_value.derive = (derive_t) rate;
1446 state->residual = rate - ((gauge_t) state->last_value.derive);
1448 else if (ds_type == DS_TYPE_COUNTER)
1450 state->last_value.counter = (counter_t) rate;
1451 state->residual = rate - ((gauge_t) state->last_value.counter);
1453 else if (ds_type == DS_TYPE_ABSOLUTE)
1455 state->last_value.absolute = (absolute_t) rate;
1456 state->residual = rate - ((gauge_t) state->last_value.absolute);
1463 state->last_time = t;
1467 if (ds_type == DS_TYPE_DERIVE)
1469 derive_t delta_derive = (derive_t) delta_gauge;
1471 state->last_value.derive += delta_derive;
1472 state->residual = delta_gauge - ((gauge_t) delta_derive);
1474 else if (ds_type == DS_TYPE_COUNTER)
1476 counter_t delta_counter = (counter_t) delta_gauge;
1478 state->last_value.counter += delta_counter;
1479 state->residual = delta_gauge - ((gauge_t) delta_counter);
1481 else if (ds_type == DS_TYPE_ABSOLUTE)
1483 absolute_t delta_absolute = (absolute_t) delta_gauge;
1485 state->last_value.absolute = delta_absolute;
1486 state->residual = delta_gauge - ((gauge_t) delta_absolute);
1493 state->last_time = t;
1494 *ret_value = state->last_value;
1496 } /* }}} value_t rate_to_value */
1498 int value_to_rate (value_t *ret_rate, derive_t value, /* {{{ */
1499 value_to_rate_state_t *state,
1500 int ds_type, cdtime_t t)
1504 /* Another invalid state: The time is not increasing. */
1505 if (t <= state->last_time)
1507 memset (state, 0, sizeof (*state));
1511 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1513 /* Previous value is invalid. */
1514 if (state->last_time == 0) /* {{{ */
1516 if (ds_type == DS_TYPE_DERIVE)
1518 state->last_value.derive = value;
1520 else if (ds_type == DS_TYPE_COUNTER)
1522 state->last_value.counter = (counter_t) value;
1524 else if (ds_type == DS_TYPE_ABSOLUTE)
1526 state->last_value.absolute = (absolute_t) value;
1533 state->last_time = t;
1537 if (ds_type == DS_TYPE_DERIVE)
1539 ret_rate->gauge = (value - state->last_value.derive) / interval;
1540 state->last_value.derive = value;
1542 else if (ds_type == DS_TYPE_COUNTER)
1544 ret_rate->gauge = (((counter_t)value) - state->last_value.counter) / interval;
1545 state->last_value.counter = (counter_t) value;
1547 else if (ds_type == DS_TYPE_ABSOLUTE)
1549 ret_rate->gauge = (((absolute_t)value) - state->last_value.absolute) / interval;
1550 state->last_value.absolute = (absolute_t) value;
1557 state->last_time = t;
1559 } /* }}} value_t rate_to_value */
1561 int service_name_to_port_number (const char *service_name)
1563 struct addrinfo *ai_list;
1564 struct addrinfo *ai_ptr;
1565 struct addrinfo ai_hints;
1569 if (service_name == NULL)
1573 memset (&ai_hints, 0, sizeof (ai_hints));
1574 ai_hints.ai_family = AF_UNSPEC;
1576 status = getaddrinfo (/* node = */ NULL, service_name,
1577 &ai_hints, &ai_list);
1580 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1581 gai_strerror (status));
1585 service_number = -1;
1586 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1588 if (ai_ptr->ai_family == AF_INET)
1590 struct sockaddr_in *sa;
1592 sa = (void *) ai_ptr->ai_addr;
1593 service_number = (int) ntohs (sa->sin_port);
1595 else if (ai_ptr->ai_family == AF_INET6)
1597 struct sockaddr_in6 *sa;
1599 sa = (void *) ai_ptr->ai_addr;
1600 service_number = (int) ntohs (sa->sin6_port);
1603 if ((service_number > 0) && (service_number <= 65535))
1607 freeaddrinfo (ai_list);
1609 if ((service_number > 0) && (service_number <= 65535))
1610 return (service_number);
1612 } /* int service_name_to_port_number */
1614 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1619 if ((string == NULL) || (ret_value == NULL))
1624 tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1625 if ((endptr == string) || (errno != 0))
1630 } /* }}} int strtoderive */
1632 int strtogauge (const char *string, gauge_t *ret_value) /* {{{ */
1635 char *endptr = NULL;
1637 if ((string == NULL) || (ret_value == NULL))
1642 tmp = (gauge_t) strtod (string, &endptr);
1645 else if ((endptr == NULL) || (*endptr != 0))
1650 } /* }}} int strtogauge */
1652 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str) /* {{{ */
1655 size_t array_len = *ret_array_len;
1660 array = realloc (*ret_array,
1661 (array_len + 1) * sizeof (*array));
1666 array[array_len] = strdup (str);
1667 if (array[array_len] == NULL)
1671 *ret_array_len = array_len;
1673 } /* }}} int strarray_add */
1675 void strarray_free (char **array, size_t array_len) /* {{{ */
1679 for (i = 0; i < array_len; i++)
1682 } /* }}} void strarray_free */