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>
39 /* for ntohl and htonl */
41 # include <arpa/inet.h>
45 extern kstat_ctl_t *kc;
49 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
53 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
56 char *sstrncpy (char *dest, const char *src, size_t n)
58 strncpy (dest, src, n);
62 } /* char *sstrncpy */
64 int ssnprintf (char *dest, size_t n, const char *format, ...)
69 va_start (ap, format);
70 ret = vsnprintf (dest, n, format, ap);
77 char *sstrdup (const char *s)
85 /* Do not use `strdup' here, because it's not specified in POSIX. It's
86 * ``only'' an XSI extension. */
88 r = (char *) malloc (sizeof (char) * sz);
91 ERROR ("sstrdup: Out of memory.");
94 memcpy (r, s, sizeof (char) * sz);
99 /* Even though Posix requires "strerror_r" to return an "int",
100 * some systems (e.g. the GNU libc) return a "char *" _and_
101 * ignore the second argument ... -tokkee */
102 char *sstrerror (int errnum, char *buf, size_t buflen)
110 pthread_mutex_lock (&strerror_r_lock);
112 temp = strerror (errnum);
113 sstrncpy (buf, temp, buflen);
115 pthread_mutex_unlock (&strerror_r_lock);
117 /* #endif !HAVE_STRERROR_R */
119 #elif STRERROR_R_CHAR_P
122 temp = strerror_r (errnum, buf, buflen);
125 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
126 sstrncpy (buf, temp, buflen);
128 sstrncpy (buf, "strerror_r did not return "
129 "an error message", buflen);
132 /* #endif STRERROR_R_CHAR_P */
135 if (strerror_r (errnum, buf, buflen) != 0)
137 ssnprintf (buf, buflen, "Error #%i; "
138 "Additionally, strerror_r failed.",
141 #endif /* STRERROR_R_CHAR_P */
144 } /* char *sstrerror */
146 void *smalloc (size_t size)
150 if ((r = malloc (size)) == NULL)
152 ERROR ("Not enough memory.");
157 } /* void *smalloc */
160 void sfree (void **ptr)
172 ssize_t sread (int fd, void *buf, size_t count)
183 status = read (fd, (void *) ptr, nleft);
185 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
193 DEBUG ("Received EOF from fd %i. "
194 "Closing fd and returning error.",
200 assert ((0 > status) || (nleft >= (size_t)status));
202 nleft = nleft - status;
210 ssize_t swrite (int fd, const void *buf, size_t count)
216 ptr = (const char *) buf;
221 status = write (fd, (const void *) ptr, nleft);
223 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
229 nleft = nleft - status;
236 int strsplit (char *string, char **fields, size_t size)
245 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
257 int strjoin (char *dst, size_t dst_len,
258 char **fields, size_t fields_num,
265 memset (dst, '\0', dst_len);
272 sep_len = strlen (sep);
274 for (i = 0; i < (int)fields_num; i++)
276 if ((i > 0) && (sep_len > 0))
278 if (dst_len <= sep_len)
281 strncat (dst, sep, dst_len);
285 field_len = strlen (fields[i]);
287 if (dst_len <= field_len)
290 strncat (dst, fields[i], dst_len);
291 dst_len -= field_len;
294 return (strlen (dst));
297 int strsubstitute (char *str, char c_from, char c_to)
316 } /* int strsubstitute */
318 int escape_slashes (char *buf, int buf_len)
322 if (strcmp (buf, "/") == 0)
327 strncpy (buf, "root", buf_len);
334 /* Move one to the left */
336 memmove (buf, buf + 1, buf_len - 1);
338 for (i = 0; i < buf_len - 1; i++)
342 else if (buf[i] == '/')
348 } /* int escape_slashes */
350 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
352 if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
355 if ((tv0->tv_sec < tv1->tv_sec)
356 || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
359 ret->tv_sec = tv0->tv_sec - tv1->tv_sec;
360 ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
362 if (ret->tv_nsec < 0)
364 assert (ret->tv_sec > 0);
366 ret->tv_nsec += 1000000000;
373 int check_create_dir (const char *file_orig)
384 int last_is_file = 1;
385 int path_is_absolute = 0;
390 * Sanity checks first
392 if (file_orig == NULL)
395 if ((len = strlen (file_orig)) < 1)
397 else if (len >= sizeof (file_copy))
401 * If `file_orig' ends in a slash the last component is a directory,
402 * otherwise it's a file. Act accordingly..
404 if (file_orig[len - 1] == '/')
406 if (file_orig[0] == '/')
407 path_is_absolute = 1;
410 * Create a copy for `strtok_r' to destroy
412 sstrncpy (file_copy, file_orig, sizeof (file_copy));
415 * Break into components. This will eat up several slashes in a row and
416 * remove leading and trailing slashes..
421 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
426 if (fields_num >= 16)
431 * For each component, do..
433 for (i = 0; i < (fields_num - last_is_file); i++)
436 * Do not create directories that start with a dot. This
437 * prevents `../../' attacks and other likely malicious
440 if (fields[i][0] == '.')
442 ERROR ("Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
447 * Join the components together again
450 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
451 fields, i + 1, "/") < 0)
453 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
457 if (stat (dir, &statbuf) == -1)
461 if (mkdir (dir, 0755) == -1)
464 ERROR ("check_create_dir: mkdir (%s): %s", dir,
466 errbuf, sizeof (errbuf)));
473 ERROR ("stat (%s): %s", dir,
474 sstrerror (errno, errbuf,
479 else if (!S_ISDIR (statbuf.st_mode))
481 ERROR ("stat (%s): Not a directory!", dir);
487 } /* check_create_dir */
490 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
497 ssnprintf (ident, sizeof (ident), "%s,%i,%s", module, instance, name);
499 if (*ksp_ptr == NULL)
501 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
503 ERROR ("Cound not find kstat %s", ident);
507 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
509 WARNING ("kstat %s has wrong type", ident);
516 assert (*ksp_ptr != NULL);
517 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
520 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
522 WARNING ("kstat %s could not be read", ident);
526 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
528 WARNING ("kstat %s has wrong type", ident);
535 long long get_kstat_value (kstat_t *ksp, char *name)
538 long long retval = -1LL;
541 assert (ksp != NULL);
542 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
546 ERROR ("ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
549 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
551 ERROR ("ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
556 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
559 if (kn->data_type == KSTAT_DATA_INT32)
560 retval = (long long) kn->value.i32;
561 else if (kn->data_type == KSTAT_DATA_UINT32)
562 retval = (long long) kn->value.ui32;
563 else if (kn->data_type == KSTAT_DATA_INT64)
564 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
565 else if (kn->data_type == KSTAT_DATA_UINT64)
566 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
568 WARNING ("get_kstat_value: Not a numeric value: %s", name);
572 #endif /* HAVE_LIBKSTAT */
574 unsigned long long ntohll (unsigned long long n)
576 #if BYTE_ORDER == BIG_ENDIAN
579 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
581 } /* unsigned long long ntohll */
583 unsigned long long htonll (unsigned long long n)
585 #if BYTE_ORDER == BIG_ENDIAN
588 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
590 } /* unsigned long long htonll */
592 #if FP_LAYOUT_NEED_NOTHING
593 /* Well, we need nothing.. */
594 /* #endif FP_LAYOUT_NEED_NOTHING */
596 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
597 # if FP_LAYOUT_NEED_ENDIANFLIP
598 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
599 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
600 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
601 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
602 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
603 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
604 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
605 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
607 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
608 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
611 double ntohd (double d)
622 /* NAN in x86 byte order */
623 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
624 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
625 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
626 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
635 ret.integer = FP_CONVERT (tmp);
636 return (ret.floating);
640 double htond (double d)
651 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
652 ret.byte[4] = ret.byte[5] = 0x00;
655 return (ret.floating);
662 tmp = FP_CONVERT (ret.integer);
664 return (ret.floating);
667 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
669 int format_name (char *ret, int ret_len,
670 const char *hostname,
671 const char *plugin, const char *plugin_instance,
672 const char *type, const char *type_instance)
676 assert (plugin != NULL);
677 assert (type != NULL);
679 if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
681 if ((type_instance == NULL) || (strlen (type_instance) == 0))
682 status = ssnprintf (ret, ret_len, "%s/%s/%s",
683 hostname, plugin, type);
685 status = ssnprintf (ret, ret_len, "%s/%s/%s-%s",
686 hostname, plugin, type,
691 if ((type_instance == NULL) || (strlen (type_instance) == 0))
692 status = ssnprintf (ret, ret_len, "%s/%s-%s/%s",
693 hostname, plugin, plugin_instance,
696 status = ssnprintf (ret, ret_len, "%s/%s-%s/%s-%s",
697 hostname, plugin, plugin_instance,
698 type, type_instance);
701 if ((status < 1) || (status >= ret_len))
704 } /* int format_name */
706 int parse_identifier (char *str, char **ret_host,
707 char **ret_plugin, char **ret_plugin_instance,
708 char **ret_type, char **ret_type_instance)
710 char *hostname = NULL;
712 char *plugin_instance = NULL;
714 char *type_instance = NULL;
717 if (hostname == NULL)
720 plugin = strchr (hostname, '/');
723 *plugin = '\0'; plugin++;
725 type = strchr (plugin, '/');
728 *type = '\0'; type++;
730 plugin_instance = strchr (plugin, '-');
731 if (plugin_instance != NULL)
733 *plugin_instance = '\0';
737 type_instance = strchr (type, '-');
738 if (type_instance != NULL)
740 *type_instance = '\0';
744 *ret_host = hostname;
745 *ret_plugin = plugin;
746 *ret_plugin_instance = plugin_instance;
748 *ret_type_instance = type_instance;
750 } /* int parse_identifier */
752 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
762 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
766 if (i >= vl->values_len)
771 if (strcmp ("N", ptr) == 0)
772 vl->time = time (NULL);
774 vl->time = (time_t) atoi (ptr);
778 if (strcmp ("U", ptr) == 0)
779 vl->values[i].gauge = NAN;
780 else if (ds->ds[i].type == DS_TYPE_COUNTER)
781 vl->values[i].counter = atoll (ptr);
782 else if (ds->ds[i].type == DS_TYPE_GAUGE)
783 vl->values[i].gauge = atof (ptr);
787 } /* while (strtok_r) */
789 if ((ptr != NULL) || (i != vl->values_len))
792 } /* int parse_values */
795 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
796 size_t buflen, struct passwd **pwbufp)
801 memset (pwbuf, '\0', sizeof (struct passwd));
803 pthread_mutex_lock (&getpwnam_r_lock);
807 pw = getpwnam (name);
810 status = (errno != 0) ? errno : ENOENT;
814 #define GETPWNAM_COPY_MEMBER(member) \
815 if (pw->member != NULL) \
817 int len = strlen (pw->member); \
823 sstrncpy (buf, pw->member, buflen); \
824 pwbuf->member = buf; \
826 buflen -= (len + 1); \
828 GETPWNAM_COPY_MEMBER(pw_name);
829 GETPWNAM_COPY_MEMBER(pw_passwd);
830 GETPWNAM_COPY_MEMBER(pw_gecos);
831 GETPWNAM_COPY_MEMBER(pw_dir);
832 GETPWNAM_COPY_MEMBER(pw_shell);
834 pwbuf->pw_uid = pw->pw_uid;
835 pwbuf->pw_gid = pw->pw_gid;
841 pthread_mutex_unlock (&getpwnam_r_lock);
844 } /* int getpwnam_r */
845 #endif /* !HAVE_GETPWNAM_R */
847 int notification_init (notification_t *n, int severity, const char *message,
849 const char *plugin, const char *plugin_instance,
850 const char *type, const char *type_instance)
852 memset (n, '\0', sizeof (notification_t));
854 n->severity = severity;
857 sstrncpy (n->message, message, sizeof (n->message));
859 sstrncpy (n->host, host, sizeof (n->host));
861 sstrncpy (n->plugin, plugin, sizeof (n->plugin));
862 if (plugin_instance != NULL)
863 sstrncpy (n->plugin_instance, plugin_instance,
864 sizeof (n->plugin_instance));
866 sstrncpy (n->type, type, sizeof (n->type));
867 if (type_instance != NULL)
868 sstrncpy (n->type_instance, type_instance,
869 sizeof (n->type_instance));
872 } /* int notification_init */
874 int walk_directory (const char *dir, dirwalk_callback_f callback,
885 if ((dh = opendir (dir)) == NULL)
888 ERROR ("walk_directory: Cannot open '%s': %s", dir,
889 sstrerror (errno, errbuf, sizeof (errbuf)));
893 while ((ent = readdir (dh)) != NULL)
897 if (ent->d_name[0] == '.')
900 status = (*callback) (dir, ent->d_name, user_data);
909 if ((success == 0) && (failure > 0))
914 int read_file_contents (const char *filename, char *buf, int bufsize)
919 if ((fh = fopen (filename, "r")) == NULL)
922 n = fread(buf, 1, bufsize, fh);
928 counter_t counter_diff (counter_t old_value, counter_t new_value)
932 if (old_value > new_value)
934 if (old_value <= 4294967295U)
935 diff = (4294967295U - old_value) + new_value;
937 diff = (18446744073709551615ULL - old_value)
942 diff = new_value - old_value;
946 } /* counter_t counter_to_gauge */