2 * collectd - src/common.c
3 * Copyright (C) 2005-2009 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 #include <sys/types.h>
48 #include <sys/socket.h>
52 # include <netinet/in.h>
56 extern kstat_ctl_t *kc;
60 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
64 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
67 char *sstrncpy (char *dest, const char *src, size_t n)
69 strncpy (dest, src, n);
73 } /* char *sstrncpy */
75 int ssnprintf (char *dest, size_t n, const char *format, ...)
80 va_start (ap, format);
81 ret = vsnprintf (dest, n, format, ap);
88 char *sstrdup (const char *s)
96 /* Do not use `strdup' here, because it's not specified in POSIX. It's
97 * ``only'' an XSI extension. */
99 r = (char *) malloc (sizeof (char) * sz);
102 ERROR ("sstrdup: Out of memory.");
105 memcpy (r, s, sizeof (char) * sz);
108 } /* char *sstrdup */
110 /* Even though Posix requires "strerror_r" to return an "int",
111 * some systems (e.g. the GNU libc) return a "char *" _and_
112 * ignore the second argument ... -tokkee */
113 char *sstrerror (int errnum, char *buf, size_t buflen)
121 pthread_mutex_lock (&strerror_r_lock);
123 temp = strerror (errnum);
124 sstrncpy (buf, temp, buflen);
126 pthread_mutex_unlock (&strerror_r_lock);
128 /* #endif !HAVE_STRERROR_R */
130 #elif STRERROR_R_CHAR_P
133 temp = strerror_r (errnum, buf, buflen);
136 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
137 sstrncpy (buf, temp, buflen);
139 sstrncpy (buf, "strerror_r did not return "
140 "an error message", buflen);
143 /* #endif STRERROR_R_CHAR_P */
146 if (strerror_r (errnum, buf, buflen) != 0)
148 ssnprintf (buf, buflen, "Error #%i; "
149 "Additionally, strerror_r failed.",
152 #endif /* STRERROR_R_CHAR_P */
155 } /* char *sstrerror */
157 void *smalloc (size_t size)
161 if ((r = malloc (size)) == NULL)
163 ERROR ("Not enough memory.");
168 } /* void *smalloc */
171 void sfree (void **ptr)
183 ssize_t sread (int fd, void *buf, size_t count)
194 status = read (fd, (void *) ptr, nleft);
196 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
204 DEBUG ("Received EOF from fd %i. "
205 "Closing fd and returning error.",
211 assert ((0 > status) || (nleft >= (size_t)status));
213 nleft = nleft - status;
221 ssize_t swrite (int fd, const void *buf, size_t count)
227 ptr = (const char *) buf;
232 status = write (fd, (const void *) ptr, nleft);
234 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
240 nleft = nleft - status;
247 int strsplit (char *string, char **fields, size_t size)
256 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
268 int strjoin (char *dst, size_t dst_len,
269 char **fields, size_t fields_num,
276 memset (dst, '\0', dst_len);
283 sep_len = strlen (sep);
285 for (i = 0; i < (int)fields_num; i++)
287 if ((i > 0) && (sep_len > 0))
289 if (dst_len <= sep_len)
292 strncat (dst, sep, dst_len);
296 field_len = strlen (fields[i]);
298 if (dst_len <= field_len)
301 strncat (dst, fields[i], dst_len);
302 dst_len -= field_len;
305 return (strlen (dst));
308 int strsubstitute (char *str, char c_from, char c_to)
327 } /* int strsubstitute */
329 int strunescape (char *buf, size_t buf_len)
333 for (i = 0; (i < buf_len) && (buf[i] != '\0'); ++i)
338 if ((i >= buf_len) || (buf[i + 1] == '\0')) {
339 ERROR ("string unescape: backslash found at end of string.");
343 switch (buf[i + 1]) {
358 memmove (buf + i + 1, buf + i + 2, buf_len - i - 2);
361 } /* int strunescape */
363 int escape_slashes (char *buf, int buf_len)
367 if (strcmp (buf, "/") == 0)
372 strncpy (buf, "root", buf_len);
379 /* Move one to the left */
381 memmove (buf, buf + 1, buf_len - 1);
383 for (i = 0; i < buf_len - 1; i++)
387 else if (buf[i] == '/')
393 } /* int escape_slashes */
395 void replace_special (char *buffer, size_t buffer_size)
399 for (i = 0; i < buffer_size; i++)
403 if ((!isalnum ((int) buffer[i])) && (buffer[i] != '-'))
406 } /* void replace_special */
408 int timeval_cmp (struct timeval tv0, struct timeval tv1, struct timeval *delta)
410 struct timeval *larger;
411 struct timeval *smaller;
415 NORMALIZE_TIMEVAL (tv0);
416 NORMALIZE_TIMEVAL (tv1);
418 if ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec == tv1.tv_usec))
427 if ((tv0.tv_sec < tv1.tv_sec)
428 || ((tv0.tv_sec == tv1.tv_sec) && (tv0.tv_usec < tv1.tv_usec)))
442 delta->tv_sec = larger->tv_sec - smaller->tv_sec;
444 if (smaller->tv_usec <= larger->tv_usec)
445 delta->tv_usec = larger->tv_usec - smaller->tv_usec;
449 delta->tv_usec = 1000000 + larger->tv_usec - smaller->tv_usec;
453 assert ((delta == NULL)
454 || ((0 <= delta->tv_usec) && (delta->tv_usec < 1000000)));
457 } /* int timeval_cmp */
459 int check_create_dir (const char *file_orig)
470 int last_is_file = 1;
471 int path_is_absolute = 0;
476 * Sanity checks first
478 if (file_orig == NULL)
481 if ((len = strlen (file_orig)) < 1)
483 else if (len >= sizeof (file_copy))
487 * If `file_orig' ends in a slash the last component is a directory,
488 * otherwise it's a file. Act accordingly..
490 if (file_orig[len - 1] == '/')
492 if (file_orig[0] == '/')
493 path_is_absolute = 1;
496 * Create a copy for `strtok_r' to destroy
498 sstrncpy (file_copy, file_orig, sizeof (file_copy));
501 * Break into components. This will eat up several slashes in a row and
502 * remove leading and trailing slashes..
507 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
512 if (fields_num >= 16)
517 * For each component, do..
519 for (i = 0; i < (fields_num - last_is_file); i++)
522 * Do not create directories that start with a dot. This
523 * prevents `../../' attacks and other likely malicious
526 if (fields[i][0] == '.')
528 ERROR ("Cowardly refusing to create a directory that "
529 "begins with a `.' (dot): `%s'", file_orig);
534 * Join the components together again
537 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
538 fields, i + 1, "/") < 0)
540 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
545 if ((stat (dir, &statbuf) == -1)
546 && (lstat (dir, &statbuf) == -1))
550 if (mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO) == 0)
553 /* this might happen, if a different thread created
554 * the directory in the meantime
555 * => call stat() again to check for S_ISDIR() */
560 ERROR ("check_create_dir: mkdir (%s): %s", dir,
562 errbuf, sizeof (errbuf)));
568 ERROR ("check_create_dir: stat (%s): %s", dir,
569 sstrerror (errno, errbuf,
574 else if (!S_ISDIR (statbuf.st_mode))
576 ERROR ("check_create_dir: `%s' exists but is not "
577 "a directory!", dir);
585 } /* check_create_dir */
588 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
597 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
599 *ksp_ptr = kstat_lookup (kc, module, instance, name);
600 if (*ksp_ptr == NULL)
602 ERROR ("get_kstat: Cound not find kstat %s", ident);
606 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
608 ERROR ("get_kstat: kstat %s has wrong type", ident);
614 assert (*ksp_ptr != NULL);
615 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
618 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
620 ERROR ("get_kstat: kstat %s could not be read", ident);
624 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
626 ERROR ("get_kstat: kstat %s has wrong type", ident);
633 long long get_kstat_value (kstat_t *ksp, char *name)
636 long long retval = -1LL;
639 assert (ksp != NULL);
640 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
644 ERROR ("ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
647 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
649 ERROR ("ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
654 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
657 if (kn->data_type == KSTAT_DATA_INT32)
658 retval = (long long) kn->value.i32;
659 else if (kn->data_type == KSTAT_DATA_UINT32)
660 retval = (long long) kn->value.ui32;
661 else if (kn->data_type == KSTAT_DATA_INT64)
662 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
663 else if (kn->data_type == KSTAT_DATA_UINT64)
664 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
666 WARNING ("get_kstat_value: Not a numeric value: %s", name);
670 #endif /* HAVE_LIBKSTAT */
673 unsigned long long ntohll (unsigned long long n)
675 #if BYTE_ORDER == BIG_ENDIAN
678 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
680 } /* unsigned long long ntohll */
682 unsigned long long htonll (unsigned long long n)
684 #if BYTE_ORDER == BIG_ENDIAN
687 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
689 } /* unsigned long long htonll */
690 #endif /* HAVE_HTONLL */
692 #if FP_LAYOUT_NEED_NOTHING
693 /* Well, we need nothing.. */
694 /* #endif FP_LAYOUT_NEED_NOTHING */
696 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
697 # if FP_LAYOUT_NEED_ENDIANFLIP
698 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
699 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
700 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
701 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
702 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
703 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
704 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
705 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
707 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
708 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
711 double ntohd (double d)
722 /* NAN in x86 byte order */
723 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
724 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
725 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
726 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
735 ret.integer = FP_CONVERT (tmp);
736 return (ret.floating);
740 double htond (double d)
751 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
752 ret.byte[4] = ret.byte[5] = 0x00;
755 return (ret.floating);
762 tmp = FP_CONVERT (ret.integer);
764 return (ret.floating);
767 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
769 int format_name (char *ret, int ret_len,
770 const char *hostname,
771 const char *plugin, const char *plugin_instance,
772 const char *type, const char *type_instance)
776 assert (plugin != NULL);
777 assert (type != NULL);
779 if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
781 if ((type_instance == NULL) || (strlen (type_instance) == 0))
782 status = ssnprintf (ret, ret_len, "%s/%s/%s",
783 hostname, plugin, type);
785 status = ssnprintf (ret, ret_len, "%s/%s/%s-%s",
786 hostname, plugin, type,
791 if ((type_instance == NULL) || (strlen (type_instance) == 0))
792 status = ssnprintf (ret, ret_len, "%s/%s-%s/%s",
793 hostname, plugin, plugin_instance,
796 status = ssnprintf (ret, ret_len, "%s/%s-%s/%s-%s",
797 hostname, plugin, plugin_instance,
798 type, type_instance);
801 if ((status < 1) || (status >= ret_len))
804 } /* int format_name */
806 int parse_identifier (char *str, char **ret_host,
807 char **ret_plugin, char **ret_plugin_instance,
808 char **ret_type, char **ret_type_instance)
810 char *hostname = NULL;
812 char *plugin_instance = NULL;
814 char *type_instance = NULL;
817 if (hostname == NULL)
820 plugin = strchr (hostname, '/');
823 *plugin = '\0'; plugin++;
825 type = strchr (plugin, '/');
828 *type = '\0'; type++;
830 plugin_instance = strchr (plugin, '-');
831 if (plugin_instance != NULL)
833 *plugin_instance = '\0';
837 type_instance = strchr (type, '-');
838 if (type_instance != NULL)
840 *type_instance = '\0';
844 *ret_host = hostname;
845 *ret_plugin = plugin;
846 *ret_plugin_instance = plugin_instance;
848 *ret_type_instance = type_instance;
850 } /* int parse_identifier */
852 int parse_value (const char *value_orig, value_t *ret_value, int ds_type)
858 if (value_orig == NULL)
861 value = strdup (value_orig);
864 value_len = strlen (value);
866 while ((value_len > 0) && isspace ((int) value[value_len - 1]))
868 value[value_len - 1] = 0;
874 case DS_TYPE_COUNTER:
875 ret_value->counter = (counter_t) strtoull (value, &endptr, 0);
879 ret_value->gauge = (gauge_t) strtod (value, &endptr);
883 ret_value->derive = (derive_t) strtoll (value, &endptr, 0);
886 case DS_TYPE_ABSOLUTE:
887 ret_value->absolute = (absolute_t) strtoull (value, &endptr, 0);
892 ERROR ("parse_value: Invalid data source type: %i.", ds_type);
896 if (value == endptr) {
898 ERROR ("parse_value: Failed to parse string as %s: %s.",
899 DS_TYPE_TO_STRING (ds_type), value);
902 else if ((NULL != endptr) && ('\0' != *endptr))
903 INFO ("parse_value: Ignoring trailing garbage \"%s\" after %s value. "
904 "Input string was \"%s\".",
905 endptr, DS_TYPE_TO_STRING (ds_type), value_orig);
909 } /* int parse_value */
911 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
921 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
925 if (i >= vl->values_len)
927 /* Make sure i is invalid. */
928 i = vl->values_len + 1;
934 if (strcmp ("N", ptr) == 0)
935 vl->time = time (NULL);
937 vl->time = (time_t) atoi (ptr);
941 if ((strcmp ("U", ptr) == 0) && (ds->ds[i].type == DS_TYPE_GAUGE))
942 vl->values[i].gauge = NAN;
943 else if (0 != parse_value (ptr, &vl->values[i], ds->ds[i].type))
948 } /* while (strtok_r) */
950 if ((ptr != NULL) || (i != vl->values_len))
953 } /* int parse_values */
956 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
957 size_t buflen, struct passwd **pwbufp)
962 memset (pwbuf, '\0', sizeof (struct passwd));
964 pthread_mutex_lock (&getpwnam_r_lock);
968 pw = getpwnam (name);
971 status = (errno != 0) ? errno : ENOENT;
975 #define GETPWNAM_COPY_MEMBER(member) \
976 if (pw->member != NULL) \
978 int len = strlen (pw->member); \
984 sstrncpy (buf, pw->member, buflen); \
985 pwbuf->member = buf; \
987 buflen -= (len + 1); \
989 GETPWNAM_COPY_MEMBER(pw_name);
990 GETPWNAM_COPY_MEMBER(pw_passwd);
991 GETPWNAM_COPY_MEMBER(pw_gecos);
992 GETPWNAM_COPY_MEMBER(pw_dir);
993 GETPWNAM_COPY_MEMBER(pw_shell);
995 pwbuf->pw_uid = pw->pw_uid;
996 pwbuf->pw_gid = pw->pw_gid;
1002 pthread_mutex_unlock (&getpwnam_r_lock);
1005 } /* int getpwnam_r */
1006 #endif /* !HAVE_GETPWNAM_R */
1008 int notification_init (notification_t *n, int severity, const char *message,
1010 const char *plugin, const char *plugin_instance,
1011 const char *type, const char *type_instance)
1013 memset (n, '\0', sizeof (notification_t));
1015 n->severity = severity;
1017 if (message != NULL)
1018 sstrncpy (n->message, message, sizeof (n->message));
1020 sstrncpy (n->host, host, sizeof (n->host));
1022 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
1023 if (plugin_instance != NULL)
1024 sstrncpy (n->plugin_instance, plugin_instance,
1025 sizeof (n->plugin_instance));
1027 sstrncpy (n->type, type, sizeof (n->type));
1028 if (type_instance != NULL)
1029 sstrncpy (n->type_instance, type_instance,
1030 sizeof (n->type_instance));
1033 } /* int notification_init */
1035 int walk_directory (const char *dir, dirwalk_callback_f callback,
1036 void *user_data, int include_hidden)
1046 if ((dh = opendir (dir)) == NULL)
1049 ERROR ("walk_directory: Cannot open '%s': %s", dir,
1050 sstrerror (errno, errbuf, sizeof (errbuf)));
1054 while ((ent = readdir (dh)) != NULL)
1060 if ((strcmp (".", ent->d_name) == 0)
1061 || (strcmp ("..", ent->d_name) == 0))
1064 else /* if (!include_hidden) */
1066 if (ent->d_name[0]=='.')
1070 status = (*callback) (dir, ent->d_name, user_data);
1079 if ((success == 0) && (failure > 0))
1084 int read_file_contents (const char *filename, char *buf, int bufsize)
1089 if ((fh = fopen (filename, "r")) == NULL)
1092 n = fread(buf, 1, bufsize, fh);
1098 counter_t counter_diff (counter_t old_value, counter_t new_value)
1102 if (old_value > new_value)
1104 if (old_value <= 4294967295U)
1105 diff = (4294967295U - old_value) + new_value;
1107 diff = (18446744073709551615ULL - old_value)
1112 diff = new_value - old_value;
1116 } /* counter_t counter_to_gauge */
1118 int service_name_to_port_number (const char *service_name)
1120 struct addrinfo *ai_list;
1121 struct addrinfo *ai_ptr;
1122 struct addrinfo ai_hints;
1126 if (service_name == NULL)
1130 memset (&ai_hints, 0, sizeof (ai_hints));
1131 ai_hints.ai_family = AF_UNSPEC;
1133 status = getaddrinfo (/* node = */ NULL, service_name,
1134 &ai_hints, &ai_list);
1137 ERROR ("service_name_to_port_number: getaddrinfo failed: %s",
1138 gai_strerror (status));
1142 service_number = -1;
1143 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
1145 if (ai_ptr->ai_family == AF_INET)
1147 struct sockaddr_in *sa;
1149 sa = (void *) ai_ptr->ai_addr;
1150 service_number = (int) ntohs (sa->sin_port);
1152 else if (ai_ptr->ai_family == AF_INET6)
1154 struct sockaddr_in6 *sa;
1156 sa = (void *) ai_ptr->ai_addr;
1157 service_number = (int) ntohs (sa->sin6_port);
1160 if ((service_number > 0) && (service_number <= 65535))
1164 freeaddrinfo (ai_list);
1166 if ((service_number > 0) && (service_number <= 65535))
1167 return (service_number);
1169 } /* int service_name_to_port_number */
1171 int strtoderive (const char *string, derive_t *ret_value) /* {{{ */
1176 if ((string == NULL) || (ret_value == NULL))
1181 tmp = (derive_t) strtoll (string, &endptr, /* base = */ 0);
1182 if ((endptr == string) || (errno != 0))
1187 } /* }}} int strtoderive */