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>
37 #include "utils_cache.h"
48 #include <sys/types.h>
54 # include <netinet/in.h>
57 /* for ntohl and htonl */
59 # include <arpa/inet.h>
63 extern kstat_ctl_t *kc;
67 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
71 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
74 char *sstrncpy (char *dest, const char *src, size_t n)
76 strncpy (dest, src, n);
80 } /* char *sstrncpy */
82 int ssnprintf (char *dest, size_t n, const char *format, ...)
87 va_start (ap, format);
88 ret = vsnprintf (dest, n, format, ap);
95 char *ssnprintf_alloc (char const *format, ...) /* {{{ */
97 char static_buffer[1024] = "";
99 size_t alloc_buffer_size;
103 /* Try printing into the static buffer. In many cases it will be
104 * sufficiently large and we can simply return a strdup() of this
106 va_start (ap, format);
107 status = vsnprintf (static_buffer, sizeof (static_buffer), format, ap);
112 /* "status" does not include the null byte. */
113 alloc_buffer_size = (size_t) (status + 1);
114 if (alloc_buffer_size <= sizeof (static_buffer))
115 return (strdup (static_buffer));
117 /* Allocate a buffer large enough to hold the string. */
118 alloc_buffer = malloc (alloc_buffer_size);
119 if (alloc_buffer == NULL)
121 memset (alloc_buffer, 0, alloc_buffer_size);
123 /* Print again into this new buffer. */
124 va_start (ap, format);
125 status = vsnprintf (alloc_buffer, alloc_buffer_size, format, ap);
129 sfree (alloc_buffer);
133 return (alloc_buffer);
134 } /* }}} char *ssnprintf_alloc */
136 char *sstrdup (const char *s)
144 /* Do not use `strdup' here, because it's not specified in POSIX. It's
145 * ``only'' an XSI extension. */
147 r = (char *) malloc (sizeof (char) * sz);
150 ERROR ("sstrdup: Out of memory.");
153 memcpy (r, s, sizeof (char) * sz);
156 } /* char *sstrdup */
158 /* Even though Posix requires "strerror_r" to return an "int",
159 * some systems (e.g. the GNU libc) return a "char *" _and_
160 * ignore the second argument ... -tokkee */
161 char *sstrerror (int errnum, char *buf, size_t buflen)
169 pthread_mutex_lock (&strerror_r_lock);
171 temp = strerror (errnum);
172 sstrncpy (buf, temp, buflen);
174 pthread_mutex_unlock (&strerror_r_lock);
176 /* #endif !HAVE_STRERROR_R */
178 #elif STRERROR_R_CHAR_P
181 temp = strerror_r (errnum, buf, buflen);
184 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
185 sstrncpy (buf, temp, buflen);
187 sstrncpy (buf, "strerror_r did not return "
188 "an error message", buflen);
191 /* #endif STRERROR_R_CHAR_P */
194 if (strerror_r (errnum, buf, buflen) != 0)
196 ssnprintf (buf, buflen, "Error #%i; "
197 "Additionally, strerror_r failed.",
200 #endif /* STRERROR_R_CHAR_P */
203 } /* char *sstrerror */
205 void *smalloc (size_t size)
209 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)
242 status = read (fd, (void *) ptr, nleft);
244 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
252 DEBUG ("Received EOF from fd %i. "
253 "Closing fd and returning error.",
259 assert ((0 > status) || (nleft >= (size_t)status));
261 nleft = nleft - ((size_t) status);
262 ptr = ptr + ((size_t) status);
269 ssize_t swrite (int fd, const void *buf, size_t count)
276 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 read),
287 // that means the connection has been closed
294 status = write (fd, (const void *) ptr, nleft);
296 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
302 nleft = nleft - ((size_t) status);
303 ptr = ptr + ((size_t) status);
309 int strsplit (char *string, char **fields, size_t size)
318 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
330 int strjoin (char *buffer, size_t buffer_size,
331 char **fields, size_t fields_num,
339 if ((buffer_size < 1) || (fields_num <= 0))
342 memset (buffer, 0, buffer_size);
344 avail = buffer_size - 1;
348 sep_len = strlen (sep);
350 for (i = 0; i < fields_num; i++)
354 if ((i > 0) && (sep_len > 0))
359 memcpy (ptr, sep, sep_len);
364 field_len = strlen (fields[i]);
365 if (avail < field_len)
368 memcpy (ptr, fields[i], field_len);
373 assert (buffer[buffer_size - 1] == 0);
374 return ((int) strlen (buffer));
377 int strsubstitute (char *str, char c_from, char c_to)
396 } /* int strsubstitute */
398 int escape_string (char *buffer, size_t buffer_size)
404 /* Check if we need to escape at all first */
405 temp = strpbrk (buffer, " \t\"\\");
412 temp = (char *) malloc (buffer_size);
415 memset (temp, 0, buffer_size);
420 for (i = 0; i < buffer_size; i++)
426 else if ((buffer[i] == '"') || (buffer[i] == '\\'))
428 if (j > (buffer_size - 4))
431 temp[j + 1] = buffer[i];
436 if (j > (buffer_size - 3))
443 assert ((j + 1) < buffer_size);
447 sstrncpy (buffer, temp, buffer_size);
450 } /* int escape_string */
452 int strunescape (char *buf, size_t buf_len)
456 for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
461 if (((i + 1) >= buf_len) || (buf[i + 1] == 0)) {
462 ERROR ("string unescape: backslash found at end of string.");
463 /* Ensure null-byte at the end of the buffer. */
468 switch (buf[i + 1]) {
483 /* Move everything after the position one position to the left.
484 * Add a null-byte as last character in the buffer. */
485 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
486 buf[buf_len - 1] = 0;
489 } /* int strunescape */
491 size_t strstripnewline (char *buffer)
493 size_t buffer_len = strlen (buffer);
495 while (buffer_len > 0)
497 if ((buffer[buffer_len - 1] != '\n')
498 && (buffer[buffer_len - 1] != '\r'))
501 buffer[buffer_len] = 0;
505 } /* size_t strstripnewline */
507 int escape_slashes (char *buffer, size_t buffer_size)
512 buffer_len = strlen (buffer);
516 if (strcmp ("/", buffer) == 0)
520 sstrncpy (buffer, "root", buffer_size);
525 /* Move one to the left */
526 if (buffer[0] == '/')
528 memmove (buffer, buffer + 1, buffer_len);
532 for (i = 0; i < buffer_len; i++)
534 if (buffer[i] == '/')
539 } /* int escape_slashes */
541 void replace_special (char *buffer, size_t buffer_size)
545 for (i = 0; i < buffer_size; i++)
549 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
552 } /* void replace_special */
554 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
556 struct timeval *larger;
557 struct timeval *smaller;
561 NORMALIZE_TIMEVAL (tv0);
562 NORMALIZE_TIMEVAL (tv1);
564 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
573 if ((tv0.tv_sec < tv1.tv_sec)
574 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
588 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
590 if (smaller->tv_usec <= larger->tv_usec)
591 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
595 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
599 assert ((delta == NULL)
600 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
603 } /* int timeval_cmp */
605 int check_create_dir (const char *file_orig)
616 int last_is_file = 1;
617 int path_is_absolute = 0;
622 * Sanity checks first
624 if (file_orig == NULL)
627 if ((len = strlen (file_orig)) < 1)
629 else if (len >= sizeof (file_copy))
633 * If `file_orig' ends in a slash the last component is a directory,
634 * otherwise it's a file. Act accordingly..
636 if (file_orig[len - 1] == '/')
638 if (file_orig[0] == '/')
639 path_is_absolute = 1;
642 * Create a copy for `strtok_r' to destroy
644 sstrncpy (file_copy, file_orig, sizeof (file_copy));
647 * Break into components. This will eat up several slashes in a row and
648 * remove leading and trailing slashes..
653 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
658 if (fields_num >= 16)
663 * For each component, do..
665 for (i = 0; i < (fields_num - last_is_file); i++)
668 * Do not create directories that start with a dot. This
669 * prevents `../../' attacks and other likely malicious
672 if (fields[i][0] == '.')
674 ERROR ("Cowardly refusing to create a directory that "
675 "begins with a `.' (dot): `%s'", file_orig);
680 * Join the components together again
683 if (strjoin (dir + path_is_absolute, (size_t) (dir_len - path_is_absolute),
684 fields, (size_t) (i + 1), "/") < 0)
686 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
691 if ((stat (dir, &statbuf) == -1)
692 && (lstat (dir, &statbuf) == -1))
696 if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
699 /* this might happen, if a different thread created
700 * the directory in the meantime
701 * => call stat() again to check for S_ISDIR() */
706 ERROR ("check_create_dir: mkdir (%s): %s", dir,
708 errbuf, sizeof (errbuf)));
714 ERROR ("check_create_dir: stat (%s): %s", dir,
715 sstrerror (errno, errbuf,
720 else if (!S_ISDIR (statbuf.st_mode))
722 ERROR ("check_create_dir: `%s' exists but is not "
723 "a directory!", dir);
731 } /* check_create_dir */
734 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
743 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
745 *ksp_ptr = kstat_lookup (kc, module, instance, name);
746 if (*ksp_ptr == NULL)
748 ERROR ("get_kstat: Cound not find kstat %s", ident);
752 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
754 ERROR ("get_kstat: kstat %s has wrong type", ident);
760 assert (*ksp_ptr != NULL);
761 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
764 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
766 ERROR ("get_kstat: kstat %s could not be read", ident);
770 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
772 ERROR ("get_kstat: kstat %s has wrong type", ident);
779 long long get_kstat_value (kstat_t *ksp, char *name)
782 long long retval = -1LL;
786 ERROR ("get_kstat_value (\"%s\"): ksp is NULL.", name);
789 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
791 ERROR ("get_kstat_value (\"%s\"): ksp->ks_type (%#x) "
792 "is not KSTAT_TYPE_NAMED (%#x).",
794 (unsigned int) ksp->ks_type,
795 (unsigned int) KSTAT_TYPE_NAMED);
799 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
802 if (kn->data_type == KSTAT_DATA_INT32)
803 retval = (long long) kn->value.i32;
804 else if (kn->data_type == KSTAT_DATA_UINT32)
805 retval = (long long) kn->value.ui32;
806 else if (kn->data_type == KSTAT_DATA_INT64)
807 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
808 else if (kn->data_type == KSTAT_DATA_UINT64)
809 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
811 WARNING ("get_kstat_value: Not a numeric value: %s", name);
815 #endif /* HAVE_LIBKSTAT */
818 unsigned long long ntohll (unsigned long long n)
820 #if BYTE_ORDER == BIG_ENDIAN
823 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
825 } /* unsigned long long ntohll */
827 unsigned long long htonll (unsigned long long n)
829 #if BYTE_ORDER == BIG_ENDIAN
832 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
834 } /* unsigned long long htonll */
835 #endif /* HAVE_HTONLL */
837 #if FP_LAYOUT_NEED_NOTHING
838 /* Well, we need nothing.. */
839 /* #endif FP_LAYOUT_NEED_NOTHING */
841 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
842 # if FP_LAYOUT_NEED_ENDIANFLIP
843 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
844 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
845 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
846 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
847 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
848 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
849 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
850 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
852 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
853 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
856 double ntohd (double d)
867 /* NAN in x86 byte order */
868 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
869 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
870 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
871 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
880 ret.integer = FP_CONVERT (tmp);
881 return (ret.floating);
885 double htond (double d)
896 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
897 ret.byte[4] = ret.byte[5] = 0x00;
900 return (ret.floating);
907 tmp = FP_CONVERT (ret.integer);
909 return (ret.floating);
912 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
914 int format_name (char *ret, int ret_len,
915 const char *hostname,
916 const char *plugin, const char *plugin_instance,
917 const char *type, const char *type_instance)
923 buffer_size = (size_t) ret_len;
925 #define APPEND(str) do { \
926 size_t l = strlen (str); \
927 if (l >= buffer_size) \
929 memcpy (buffer, (str), l); \
930 buffer += l; buffer_size -= l; \
933 assert (plugin != NULL);
934 assert (type != NULL);
939 if ((plugin_instance != NULL) && (plugin_instance[0] != 0))
942 APPEND (plugin_instance);
946 if ((type_instance != NULL) && (type_instance[0] != 0))
949 APPEND (type_instance);
951 assert (buffer_size > 0);
956 } /* int format_name */
958 int format_values (char *ret, size_t ret_len, /* {{{ */
959 const data_set_t *ds, const value_list_t *vl,
965 gauge_t *rates = NULL;
967 assert (0 == strcmp (ds->type, vl->type));
969 memset (ret, 0, ret_len);
971 #define BUFFER_ADD(...) do { \
972 status = ssnprintf (ret + offset, ret_len - offset, \
979 else if (((size_t) status) >= (ret_len - offset)) \
985 offset += ((size_t) status); \
988 BUFFER_ADD ("%.3f", CDTIME_T_TO_DOUBLE (vl->time));
990 for (i = 0; i < ds->ds_num; i++)
992 if (ds->ds[i].type == DS_TYPE_GAUGE)
993 BUFFER_ADD (":"GAUGE_FORMAT, vl->values[i].gauge);
994 else if (store_rates)
997 rates = uc_get_rate (ds, vl);
1000 WARNING ("format_values: uc_get_rate failed.");
1003 BUFFER_ADD (":"GAUGE_FORMAT, rates[i]);
1005 else if (ds->ds[i].type == DS_TYPE_COUNTER)
1006 BUFFER_ADD (":%llu", vl->values[i].counter);
1007 else if (ds->ds[i].type == DS_TYPE_DERIVE)
1008 BUFFER_ADD (":%"PRIi64, vl->values[i].derive);
1009 else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
1010 BUFFER_ADD (":%"PRIu64, vl->values[i].absolute);
1013 ERROR ("format_values: Unknown data source type: %i",
1018 } /* for ds->ds_num */
1024 } /* }}} int format_values */
1026 int parse_identifier (char *str, char **ret_host,
1027 char **ret_plugin, char **ret_plugin_instance,
1028 char **ret_type, char **ret_type_instance)
1030 char *hostname = NULL;
1031 char *plugin = NULL;
1032 char *plugin_instance = NULL;
1034 char *type_instance = NULL;
1037 if (hostname == NULL)
1040 plugin = strchr (hostname, '/');
1043 *plugin = '\0'; plugin++;
1045 type = strchr (plugin, '/');
1048 *type = '\0'; type++;
1050 plugin_instance = strchr (plugin, '-');
1051 if (plugin_instance != NULL)
1053 *plugin_instance = '\0';
1057 type_instance = strchr (type, '-');
1058 if (type_instance != NULL)
1060 *type_instance = '\0';
1064 *ret_host = hostname;
1065 *ret_plugin = plugin;
1066 *ret_plugin_instance = plugin_instance;
1068 *ret_type_instance = type_instance;
1070 } /* int parse_identifier */
1072 int parse_identifier_vl (const char *str, value_list_t *vl) /* {{{ */
1074 char str_copy[6 * DATA_MAX_NAME_LEN];
1076 char *plugin = NULL;
1077 char *plugin_instance = NULL;
1079 char *type_instance = NULL;
1082 if ((str == NULL) || (vl == NULL))
1085 sstrncpy (str_copy, str, sizeof (str_copy));
1087 status = parse_identifier (str_copy, &host,
1088 &plugin, &plugin_instance,
1089 &type, &type_instance);
1093 sstrncpy (vl->host, host, sizeof (vl->host));
1094 sstrncpy (vl->plugin, plugin, sizeof (vl->plugin));
1095 sstrncpy (vl->plugin_instance,
1096 (plugin_instance != NULL) ? plugin_instance : "",
1097 sizeof (vl->plugin_instance));
1098 sstrncpy (vl->type, type, sizeof (vl->type));
1099 sstrncpy (vl->type_instance,
1100 (type_instance != NULL) ? type_instance : "",
1101 sizeof (vl->type_instance));
1104 } /* }}} int parse_identifier_vl */
1106 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
1109 char *endptr = NULL;
1112 if (value_orig == NULL)
1115 value = strdup (value_orig);
1118 value_len = strlen (value);
1120 while ((value_len > 0) && isspace ((int) value[value_len - 1]))
1122 value[value_len - 1] = 0;
1128 case DS_TYPE_COUNTER:
1129 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
1133 ret_value->gauge = (gauge_t) strtod (value, &endptr);
1136 case DS_TYPE_DERIVE:
1137 ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
1140 case DS_TYPE_ABSOLUTE:
1141 ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
1146 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
1150 if (value == endptr) {
1151 ERROR ("parse_value: Failed to parse string as %s: %s.",
1152 DS_TYPE_TO_STRING (ds_type), value);
1156 else if ((NULL != endptr) && ('\0' != *endptr))
1157 INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
1158 "Input string was \"%s\".",
1159 endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
1163 } /* int parse_value */
1165 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
1176 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
1180 if (i >= vl->values_len)
1182 /* Make sure i is invalid. */
1189 if (strcmp ("N", ptr) == 0)
1190 vl->time = cdtime ();
1193 char *endptr = NULL;
1197 tmp = strtod (ptr, &endptr);
1198 if ((errno != 0) /* Overflow */
1199 || (endptr == ptr) /* Invalid string */
1200 || (endptr == NULL) /* This should not happen */
1201 || (*endptr != 0)) /* Trailing chars */
1204 vl->time = DOUBLE_TO_CDTIME_T (tmp);
1210 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
1211 vl->values[i].gauge = NAN;
1212 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
1216 } /* while (strtok_r) */
1218 if ((ptr != NULL) || (i == 0))
1221 } /* int parse_values */
1223 #if !HAVE_GETPWNAM_R
1224 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
1225 size_t buflen, struct passwd **pwbufp)
1230 memset (pwbuf, '\0', sizeof (struct passwd));
1232 pthread_mutex_lock (&getpwnam_r_lock);
1236 pw = getpwnam (name);
1239 status = (errno != 0) ? errno : ENOENT;
1243 #define GETPWNAM_COPY_MEMBER(member) \
1244 if (pw->member != NULL) \
1246 int len = strlen (pw->member); \
1247 if (len >= buflen) \
1252 sstrncpy (buf, pw->member, buflen); \
1253 pwbuf->member = buf; \
1255 buflen -= (len + 1); \
1257 GETPWNAM_COPY_MEMBER(pw_name);
1258 GETPWNAM_COPY_MEMBER(pw_passwd);
1259 GETPWNAM_COPY_MEMBER(pw_gecos);
1260 GETPWNAM_COPY_MEMBER(pw_dir);
1261 GETPWNAM_COPY_MEMBER(pw_shell);
1263 pwbuf->pw_uid = pw->pw_uid;
1264 pwbuf->pw_gid = pw->pw_gid;
1270 pthread_mutex_unlock (&getpwnam_r_lock);
1273 } /* int getpwnam_r */
1274 #endif /* !HAVE_GETPWNAM_R */
1276 int notification_init (notification_t *n, int severity, const char *message,
1278 const char *plugin, const char *plugin_instance,
1279 const char *type, const char *type_instance)
1281 memset (n, '\0', sizeof (notification_t));
1283 n->severity = severity;
1285 if (message != NULL)
1286 sstrncpy (n->message, message, sizeof (n->message));
1288 sstrncpy (n->host, host, sizeof (n->host));
1290 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1291 if (plugin_instance != NULL)
1292 sstrncpy (n->plugin_instance, plugin_instance,
1293 sizeof (n->plugin_instance));
1295 sstrncpy (n->type, type, sizeof (n->type));
1296 if (type_instance != NULL)
1297 sstrncpy (n->type_instance, type_instance,
1298 sizeof (n->type_instance));
1301 } /* int notification_init */
1303 int walk_directory (const char *dir, dirwalk_callback_f callback,
1304 void *user_data, int include_hidden)
1314 if ((dh = opendir (dir)) == NULL)
1317 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1318 sstrerror (errno, errbuf, sizeof (errbuf)));
1322 while ((ent = readdir (dh)) != NULL)
1328 if ((strcmp (".", ent->d_name) == 0)
1329 || (strcmp ("..", ent->d_name) == 0))
1332 else /* if (!include_hidden) */
1334 if (ent->d_name[0]=='.')
1338 status = (*callback) (dir, ent->d_name, user_data);
1347 if ((success == 0) && (failure > 0))
1352 ssize_t read_file_contents (const char *filename, char *buf, size_t bufsize)
1357 fh = fopen (filename, "r");
1361 ret = (ssize_t) fread (buf, 1, bufsize, fh);
1362 if ((ret == 0) && (ferror (fh) != 0))
1364 ERROR ("read_file_contents: Reading file \"%s\" failed.",
1373 counter_t counter_diff (counter_t old_value, counter_t new_value)
1377 if (old_value > new_value)
1379 if (old_value <= 4294967295U)
1380 diff = (4294967295U - old_value) + new_value + 1;
1382 diff = (18446744073709551615ULL - old_value) + new_value + 1;
1386 diff = new_value - old_value;
1390 } /* counter_t counter_diff */
1392 int rate_to_value (value_t *ret_value, gauge_t rate, /* {{{ */
1393 rate_to_value_state_t *state,
1394 int ds_type, cdtime_t t)
1396 gauge_t delta_gauge;
1399 if (ds_type == DS_TYPE_GAUGE)
1401 state->last_value.gauge = rate;
1402 state->last_time = t;
1404 *ret_value = state->last_value;
1408 /* Counter and absolute can't handle negative rates. Reset "last time"
1409 * to zero, so that the next valid rate will re-initialize the
1412 && ((ds_type == DS_TYPE_COUNTER)
1413 || (ds_type == DS_TYPE_ABSOLUTE)))
1415 memset (state, 0, sizeof (*state));
1419 /* Another invalid state: The time is not increasing. */
1420 if (t <= state->last_time)
1422 memset (state, 0, sizeof (*state));
1426 delta_t = t - state->last_time;
1427 delta_gauge = (rate * CDTIME_T_TO_DOUBLE (delta_t)) + state->residual;
1429 /* Previous value is invalid. */
1430 if (state->last_time == 0) /* {{{ */
1432 if (ds_type == DS_TYPE_DERIVE)
1434 state->last_value.derive = (derive_t) rate;
1435 state->residual = rate - ((gauge_t) state->last_value.derive);
1437 else if (ds_type == DS_TYPE_COUNTER)
1439 state->last_value.counter = (counter_t) rate;
1440 state->residual = rate - ((gauge_t) state->last_value.counter);
1442 else if (ds_type == DS_TYPE_ABSOLUTE)
1444 state->last_value.absolute = (absolute_t) rate;
1445 state->residual = rate - ((gauge_t) state->last_value.absolute);
1452 state->last_time = t;
1456 if (ds_type == DS_TYPE_DERIVE)
1458 derive_t delta_derive = (derive_t) delta_gauge;
1460 state->last_value.derive += delta_derive;
1461 state->residual = delta_gauge - ((gauge_t) delta_derive);
1463 else if (ds_type == DS_TYPE_COUNTER)
1465 counter_t delta_counter = (counter_t) delta_gauge;
1467 state->last_value.counter += delta_counter;
1468 state->residual = delta_gauge - ((gauge_t) delta_counter);
1470 else if (ds_type == DS_TYPE_ABSOLUTE)
1472 absolute_t delta_absolute = (absolute_t) delta_gauge;
1474 state->last_value.absolute = delta_absolute;
1475 state->residual = delta_gauge - ((gauge_t) delta_absolute);
1482 state->last_time = t;
1483 *ret_value = state->last_value;
1485 } /* }}} value_t rate_to_value */
1487 int value_to_rate (gauge_t *ret_rate, /* {{{ */
1488 value_t value, int ds_type, cdtime_t t, value_to_rate_state_t *state)
1492 /* Another invalid state: The time is not increasing. */
1493 if (t <= state->last_time)
1495 memset (state, 0, sizeof (*state));
1499 interval = CDTIME_T_TO_DOUBLE(t - state->last_time);
1501 /* Previous value is invalid. */
1502 if (state->last_time == 0)
1504 state->last_value = value;
1505 state->last_time = t;
1510 case DS_TYPE_DERIVE: {
1511 derive_t diff = value.derive - state->last_value.derive;
1512 *ret_rate = ((gauge_t) diff) / ((gauge_t) interval);
1515 case DS_TYPE_GAUGE: {
1516 *ret_rate = value.gauge;
1519 case DS_TYPE_COUNTER: {
1520 counter_t diff = counter_diff (state->last_value.counter, value.counter);
1521 *ret_rate = ((gauge_t) diff) / ((gauge_t) interval);
1524 case DS_TYPE_ABSOLUTE: {
1525 absolute_t diff = value.absolute;
1526 *ret_rate = ((gauge_t) diff) / ((gauge_t) interval);
1533 state->last_value = value;
1534 state->last_time = t;
1536 } /* }}} value_t rate_to_value */
1538 int service_name_to_port_number (const char *service_name)
1540 struct addrinfo *ai_list;
1541 struct addrinfo *ai_ptr;
1542 struct addrinfo ai_hints;
1546 if (service_name == NULL)
1550 memset (&ai_hints, 0, sizeof (ai_hints));
1551 ai_hints.ai_family = AF_UNSPEC;
1553 status = getaddrinfo (/* node = */ NULL, service_name,
1554 &ai_hints, &ai_list);
1557 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1558 gai_strerror (status));
1562 service_number = -1;
1563 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1565 if (ai_ptr->ai_family == AF_INET)
1567 struct sockaddr_in *sa;
1569 sa = (void *) ai_ptr->ai_addr;
1570 service_number = (int) ntohs (sa->sin_port);
1572 else if (ai_ptr->ai_family == AF_INET6)
1574 struct sockaddr_in6 *sa;
1576 sa = (void *) ai_ptr->ai_addr;
1577 service_number = (int) ntohs (sa->sin6_port);
1580 if ((service_number > 0) && (service_number <= 65535))
1584 freeaddrinfo (ai_list);
1586 if ((service_number > 0) && (service_number <= 65535))
1587 return (service_number);
1589 } /* int service_name_to_port_number */
1591 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1596 if ((string == NULL) || (ret_value == NULL))
1601 tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1602 if ((endptr == string) || (errno != 0))
1607 } /* }}} int strtoderive */
1609 int strtogauge (const char *string, gauge_t *ret_value) /* {{{ */
1612 char *endptr = NULL;
1614 if ((string == NULL) || (ret_value == NULL))
1619 tmp = (gauge_t) strtod (string, &endptr);
1622 else if ((endptr == NULL) || (*endptr != 0))
1627 } /* }}} int strtogauge */
1629 int strarray_add (char ***ret_array, size_t *ret_array_len, char const *str) /* {{{ */
1632 size_t array_len = *ret_array_len;
1637 array = realloc (*ret_array,
1638 (array_len + 1) * sizeof (*array));
1643 array[array_len] = strdup (str);
1644 if (array[array_len] == NULL)
1648 *ret_array_len = array_len;
1650 } /* }}} int strarray_add */
1652 void strarray_free (char **array, size_t array_len) /* {{{ */
1656 for (i = 0; i < array_len; i++)
1659 } /* }}} void strarray_free */