2 * collectd - src/common.c
3 * Copyright (C) 2005-2008 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <octo at verplant.org>
20 * Niki W. Waibel <niki.waibel@gmx.net>
21 * Sebastian Harl <sh at tokkee.org>
22 * Michał Mirosław <mirq-linux at rere.qmqm.pl>
41 /* for ntohl and htonl */
43 # include <arpa/inet.h>
47 extern kstat_ctl_t *kc;
51 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
55 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
58 char *sstrncpy (char *dest, const char *src, size_t n)
60 strncpy (dest, src, n);
64 } /* char *sstrncpy */
66 int ssnprintf (char *dest, size_t n, const char *format, ...)
71 va_start (ap, format);
72 ret = vsnprintf (dest, n, format, ap);
79 char *sstrdup (const char *s)
87 /* Do not use `strdup' here, because it's not specified in POSIX. It's
88 * ``only'' an XSI extension. */
90 r = (char *) malloc (sizeof (char) * sz);
93 ERROR ("sstrdup: Out of memory.");
96 memcpy (r, s, sizeof (char) * sz);
101 /* Even though Posix requires "strerror_r" to return an "int",
102 * some systems (e.g. the GNU libc) return a "char *" _and_
103 * ignore the second argument ... -tokkee */
104 char *sstrerror (int errnum, char *buf, size_t buflen)
112 pthread_mutex_lock (&strerror_r_lock);
114 temp = strerror (errnum);
115 sstrncpy (buf, temp, buflen);
117 pthread_mutex_unlock (&strerror_r_lock);
119 /* #endif !HAVE_STRERROR_R */
121 #elif STRERROR_R_CHAR_P
124 temp = strerror_r (errnum, buf, buflen);
127 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
128 sstrncpy (buf, temp, buflen);
130 sstrncpy (buf, "strerror_r did not return "
131 "an error message", buflen);
134 /* #endif STRERROR_R_CHAR_P */
137 if (strerror_r (errnum, buf, buflen) != 0)
139 ssnprintf (buf, buflen, "Error #%i; "
140 "Additionally, strerror_r failed.",
143 #endif /* STRERROR_R_CHAR_P */
146 } /* char *sstrerror */
148 void *smalloc (size_t size)
152 if ((r = malloc (size)) == NULL)
154 ERROR ("Not enough memory.");
159 } /* void *smalloc */
162 void sfree (void **ptr)
174 ssize_t sread (int fd, void *buf, size_t count)
185 status = read (fd, (void *) ptr, nleft);
187 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
195 DEBUG ("Received EOF from fd %i. "
196 "Closing fd and returning error.",
202 assert ((0 > status) || (nleft >= (size_t)status));
204 nleft = nleft - status;
212 ssize_t swrite (int fd, const void *buf, size_t count)
218 ptr = (const char *) buf;
223 status = write (fd, (const void *) ptr, nleft);
225 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
231 nleft = nleft - status;
238 int strsplit (char *string, char **fields, size_t size)
247 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
259 int strjoin (char *dst, size_t dst_len,
260 char **fields, size_t fields_num,
267 memset (dst, '\0', dst_len);
274 sep_len = strlen (sep);
276 for (i = 0; i < (int)fields_num; i++)
278 if ((i > 0) && (sep_len > 0))
280 if (dst_len <= sep_len)
283 strncat (dst, sep, dst_len);
287 field_len = strlen (fields[i]);
289 if (dst_len <= field_len)
292 strncat (dst, fields[i], dst_len);
293 dst_len -= field_len;
296 return (strlen (dst));
299 int strsubstitute (char *str, char c_from, char c_to)
318 } /* int strsubstitute */
320 int strunescape (char *buf, size_t buf_len)
324 for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
329 if ((i >= buf_len) || (buf[i + 1] == '\0')) {
330 ERROR ("string unescape: backslash found at end of string.");
334 switch (buf[i + 1]) {
349 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
352 } /* int strunescape */
354 int escape_slashes (char *buf, int buf_len)
358 if (strcmp (buf, "/") == 0)
363 strncpy (buf, "root", buf_len);
370 /* Move one to the left */
372 memmove (buf, buf + 1, buf_len - 1);
374 for (i = 0; i < buf_len - 1; i++)
378 else if (buf[i] == '/')
384 } /* int escape_slashes */
386 void replace_special (char *buffer, size_t buffer_size)
390 for (i = 0; i < buffer_size; i++)
394 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
397 } /* void replace_special */
399 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
401 struct timeval *larger;
402 struct timeval *smaller;
406 NORMALIZE_TIMEVAL (tv0);
407 NORMALIZE_TIMEVAL (tv1);
409 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
418 if ((tv0.tv_sec < tv1.tv_sec)
419 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
433 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
435 if (smaller->tv_usec <= larger->tv_usec)
436 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
440 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
444 assert ((delta == NULL)
445 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
448 } /* int timeval_cmp */
450 int check_create_dir (const char *file_orig)
461 int last_is_file = 1;
462 int path_is_absolute = 0;
467 * Sanity checks first
469 if (file_orig == NULL)
472 if ((len = strlen (file_orig)) < 1)
474 else if (len >= sizeof (file_copy))
478 * If `file_orig' ends in a slash the last component is a directory,
479 * otherwise it's a file. Act accordingly..
481 if (file_orig[len - 1] == '/')
483 if (file_orig[0] == '/')
484 path_is_absolute = 1;
487 * Create a copy for `strtok_r' to destroy
489 sstrncpy (file_copy, file_orig, sizeof (file_copy));
492 * Break into components. This will eat up several slashes in a row and
493 * remove leading and trailing slashes..
498 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
503 if (fields_num >= 16)
508 * For each component, do..
510 for (i = 0; i < (fields_num - last_is_file); i++)
513 * Do not create directories that start with a dot. This
514 * prevents `../../' attacks and other likely malicious
517 if (fields[i][0] == '.')
519 ERROR ("Cowardly refusing to create a directory that "
520 "begins with a `.' (dot): `%s'", file_orig);
525 * Join the components together again
528 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
529 fields, i + 1, "/") < 0)
531 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
536 if (stat (dir, &statbuf) == -1)
540 if (mkdir (dir, 0755) == 0)
543 /* this might happen, if a different thread created
544 * the directory in the meantime
545 * => call stat() again to check for S_ISDIR() */
550 ERROR ("check_create_dir: mkdir (%s): %s", dir,
552 errbuf, sizeof (errbuf)));
558 ERROR ("check_create_dir: stat (%s): %s", dir,
559 sstrerror (errno, errbuf,
564 else if (!S_ISDIR (statbuf.st_mode))
566 ERROR ("check_create_dir: `%s' exists but is not "
567 "a directory!", dir);
575 } /* check_create_dir */
578 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
587 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
589 *ksp_ptr = kstat_lookup (kc, module, instance, name);
590 if (*ksp_ptr == NULL)
592 ERROR ("get_kstat: Cound not find kstat %s", ident);
596 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
598 ERROR ("get_kstat: kstat %s has wrong type", ident);
604 assert (*ksp_ptr != NULL);
605 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
608 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
610 ERROR ("get_kstat: kstat %s could not be read", ident);
614 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
616 ERROR ("get_kstat: kstat %s has wrong type", ident);
623 long long get_kstat_value (kstat_t *ksp, char *name)
626 long long retval = -1LL;
629 assert (ksp != NULL);
630 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
634 ERROR ("ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
637 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
639 ERROR ("ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
644 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
647 if (kn->data_type == KSTAT_DATA_INT32)
648 retval = (long long) kn->value.i32;
649 else if (kn->data_type == KSTAT_DATA_UINT32)
650 retval = (long long) kn->value.ui32;
651 else if (kn->data_type == KSTAT_DATA_INT64)
652 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
653 else if (kn->data_type == KSTAT_DATA_UINT64)
654 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
656 WARNING ("get_kstat_value: Not a numeric value: %s", name);
660 #endif /* HAVE_LIBKSTAT */
662 unsigned long long ntohll (unsigned long long n)
664 #if BYTE_ORDER == BIG_ENDIAN
667 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
669 } /* unsigned long long ntohll */
671 unsigned long long htonll (unsigned long long n)
673 #if BYTE_ORDER == BIG_ENDIAN
676 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
678 } /* unsigned long long htonll */
680 #if FP_LAYOUT_NEED_NOTHING
681 /* Well, we need nothing.. */
682 /* #endif FP_LAYOUT_NEED_NOTHING */
684 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
685 # if FP_LAYOUT_NEED_ENDIANFLIP
686 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
687 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
688 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
689 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
690 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
691 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
692 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
693 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
695 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
696 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
699 double ntohd (double d)
710 /* NAN in x86 byte order */
711 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
712 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
713 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
714 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
723 ret.integer = FP_CONVERT (tmp);
724 return (ret.floating);
728 double htond (double d)
739 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
740 ret.byte[4] = ret.byte[5] = 0x00;
743 return (ret.floating);
750 tmp = FP_CONVERT (ret.integer);
752 return (ret.floating);
755 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
757 int format_name (char *ret, int ret_len,
758 const char *hostname,
759 const char *plugin, const char *plugin_instance,
760 const char *type, const char *type_instance)
764 assert (plugin != NULL);
765 assert (type != NULL);
767 if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
769 if ((type_instance == NULL) || (strlen (type_instance) == 0))
770 status = ssnprintf (ret, ret_len, "%s/%s/%s",
771 hostname, plugin, type);
773 status = ssnprintf (ret, ret_len, "%s/%s/%s-%s",
774 hostname, plugin, type,
779 if ((type_instance == NULL) || (strlen (type_instance) == 0))
780 status = ssnprintf (ret, ret_len, "%s/%s-%s/%s",
781 hostname, plugin, plugin_instance,
784 status = ssnprintf (ret, ret_len, "%s/%s-%s/%s-%s",
785 hostname, plugin, plugin_instance,
786 type, type_instance);
789 if ((status < 1) || (status >= ret_len))
792 } /* int format_name */
794 int parse_identifier (char *str, char **ret_host,
795 char **ret_plugin, char **ret_plugin_instance,
796 char **ret_type, char **ret_type_instance)
798 char *hostname = NULL;
800 char *plugin_instance = NULL;
802 char *type_instance = NULL;
805 if (hostname == NULL)
808 plugin = strchr (hostname, '/');
811 *plugin = '\0'; plugin++;
813 type = strchr (plugin, '/');
816 *type = '\0'; type++;
818 plugin_instance = strchr (plugin, '-');
819 if (plugin_instance != NULL)
821 *plugin_instance = '\0';
825 type_instance = strchr (type, '-');
826 if (type_instance != NULL)
828 *type_instance = '\0';
832 *ret_host = hostname;
833 *ret_plugin = plugin;
834 *ret_plugin_instance = plugin_instance;
836 *ret_type_instance = type_instance;
838 } /* int parse_identifier */
840 int parse_value (const char *value, value_t *ret_value, int ds_type)
846 case DS_TYPE_COUNTER:
847 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
851 ret_value->gauge = (gauge_t) strtod (value, &endptr);
855 ret_value->counter = (derive_t) strtoll (value, &endptr, 0);
858 case DS_TYPE_ABSOLUTE:
859 ret_value->counter = (absolute_t) strtoull (value, &endptr, 0);
863 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
867 if (value == endptr) {
868 ERROR ("parse_value: Failed to parse string as number: %s.", value);
871 else if ((NULL != endptr) && ('\0' != *endptr))
872 WARNING ("parse_value: Ignoring trailing garbage after number: %s.",
875 } /* int parse_value */
877 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
887 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
891 if (i >= vl->values_len)
893 /* Make sure i is invalid. */
894 i = vl->values_len + 1;
900 if (strcmp ("N", ptr) == 0)
901 vl->time = time (NULL);
903 vl->time = (time_t) atoi (ptr);
907 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
908 vl->values[i].gauge = NAN;
909 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
914 } /* while (strtok_r) */
916 if ((ptr != NULL) || (i != vl->values_len))
919 } /* int parse_values */
922 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
923 size_t buflen, struct passwd **pwbufp)
928 memset (pwbuf, '\0', sizeof (struct passwd));
930 pthread_mutex_lock (&getpwnam_r_lock);
934 pw = getpwnam (name);
937 status = (errno != 0) ? errno : ENOENT;
941 #define GETPWNAM_COPY_MEMBER(member) \
942 if (pw->member != NULL) \
944 int len = strlen (pw->member); \
950 sstrncpy (buf, pw->member, buflen); \
951 pwbuf->member = buf; \
953 buflen -= (len + 1); \
955 GETPWNAM_COPY_MEMBER(pw_name);
956 GETPWNAM_COPY_MEMBER(pw_passwd);
957 GETPWNAM_COPY_MEMBER(pw_gecos);
958 GETPWNAM_COPY_MEMBER(pw_dir);
959 GETPWNAM_COPY_MEMBER(pw_shell);
961 pwbuf->pw_uid = pw->pw_uid;
962 pwbuf->pw_gid = pw->pw_gid;
968 pthread_mutex_unlock (&getpwnam_r_lock);
971 } /* int getpwnam_r */
972 #endif /* !HAVE_GETPWNAM_R */
974 int notification_init (notification_t *n, int severity, const char *message,
976 const char *plugin, const char *plugin_instance,
977 const char *type, const char *type_instance)
979 memset (n, '\0', sizeof (notification_t));
981 n->severity = severity;
984 sstrncpy (n->message, message, sizeof (n->message));
986 sstrncpy (n->host, host, sizeof (n->host));
988 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
989 if (plugin_instance != NULL)
990 sstrncpy (n->plugin_instance, plugin_instance,
991 sizeof (n->plugin_instance));
993 sstrncpy (n->type, type, sizeof (n->type));
994 if (type_instance != NULL)
995 sstrncpy (n->type_instance, type_instance,
996 sizeof (n->type_instance));
999 } /* int notification_init */
1001 int walk_directory (const char *dir, dirwalk_callback_f callback,
1012 if ((dh = opendir (dir)) == NULL)
1015 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1016 sstrerror (errno, errbuf, sizeof (errbuf)));
1020 while ((ent = readdir (dh)) != NULL)
1024 if (ent->d_name[0] == '.')
1027 status = (*callback) (dir, ent->d_name, user_data);
1036 if ((success == 0) && (failure > 0))
1041 int read_file_contents (const char *filename, char *buf, int bufsize)
1046 if ((fh = fopen (filename, "r")) == NULL)
1049 n = fread(buf, 1, bufsize, fh);
1055 counter_t counter_diff (counter_t old_value, counter_t new_value)
1059 if (old_value > new_value)
1061 if (old_value <= 4294967295U)
1062 diff = (4294967295U - old_value) + new_value;
1064 diff = (18446744073709551615ULL - old_value)
1069 diff = new_value - old_value;
1073 } /* counter_t counter_to_gauge */