1 /**
2 * collectd - src/common.c
3 * Copyright (C) 2005-2008 Florian octo Forster
4 *
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.
8 *
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.
13 *
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
17 *
18 * Authors:
19 * Florian octo Forster <octo at verplant.org>
20 * Niki W. Waibel <niki.waibel@gmx.net>
21 **/
23 #if HAVE_CONFIG_H
24 # include "config.h"
25 #endif
27 #include "collectd.h"
28 #include "common.h"
29 #include "plugin.h"
31 #if HAVE_PTHREAD_H
32 # include <pthread.h>
33 #endif
35 #ifdef HAVE_MATH_H
36 # include <math.h>
37 #endif
39 /* for ntohl and htonl */
40 #if HAVE_ARPA_INET_H
41 # include <arpa/inet.h>
42 #endif
44 #ifdef HAVE_LIBKSTAT
45 extern kstat_ctl_t *kc;
46 #endif
48 #if !HAVE_GETPWNAM_R
49 static pthread_mutex_t getpwnam_r_lock = PTHREAD_MUTEX_INITIALIZER;
50 #endif
52 #if !HAVE_STRERROR_R
53 static pthread_mutex_t strerror_r_lock = PTHREAD_MUTEX_INITIALIZER;
54 #endif
56 char *sstrncpy (char *dest, const char *src, size_t n)
57 {
58 strncpy (dest, src, n);
59 dest[n - 1] = '\0';
61 return (dest);
62 } /* char *sstrncpy */
64 char *sstrdup (const char *s)
65 {
66 char *r;
68 if (s == NULL)
69 return (NULL);
71 if((r = strdup (s)) == NULL)
72 {
73 ERROR ("Not enough memory.");
74 exit (3);
75 }
77 return (r);
78 } /* char *sstrdup */
80 /* Even though Posix requires "strerror_r" to return an "int",
81 * some systems (e.g. the GNU libc) return a "char *" _and_
82 * ignore the second argument ... -tokkee */
83 char *sstrerror (int errnum, char *buf, size_t buflen)
84 {
85 buf[0] = '\0';
87 #if !HAVE_STRERROR_R
88 {
89 char *temp;
91 pthread_mutex_lock (&strerror_r_lock);
93 temp = strerror (errnum);
94 strncpy (buf, temp, buflen);
96 pthread_mutex_unlock (&strerror_r_lock);
97 }
98 /* #endif !HAVE_STRERROR_R */
100 #elif STRERROR_R_CHAR_P
101 {
102 char *temp;
103 temp = strerror_r (errnum, buf, buflen);
104 if (buf[0] == '\0')
105 {
106 if ((temp != NULL) && (temp != buf) && (temp[0] != '\0'))
107 strncpy (buf, temp, buflen);
108 else
109 strncpy (buf, "strerror_r did not return "
110 "an error message", buflen);
111 }
112 }
113 /* #endif STRERROR_R_CHAR_P */
115 #else
116 if (strerror_r (errnum, buf, buflen) != 0)
117 {
118 snprintf (buf, buflen, "Error #%i; "
119 "Additionally, strerror_r failed.",
120 errnum);
121 }
122 #endif /* STRERROR_R_CHAR_P */
124 buf[buflen - 1] = '\0';
125 return (buf);
126 } /* char *sstrerror */
128 void *smalloc (size_t size)
129 {
130 void *r;
132 if ((r = malloc (size)) == NULL)
133 {
134 ERROR ("Not enough memory.");
135 exit (3);
136 }
138 return (r);
139 } /* void *smalloc */
141 #if 0
142 void sfree (void **ptr)
143 {
144 if (ptr == NULL)
145 return;
147 if (*ptr != NULL)
148 free (*ptr);
150 *ptr = NULL;
151 }
152 #endif
154 ssize_t sread (int fd, void *buf, size_t count)
155 {
156 char *ptr;
157 size_t nleft;
158 ssize_t status;
160 ptr = (char *) buf;
161 nleft = count;
163 while (nleft > 0)
164 {
165 status = read (fd, (void *) ptr, nleft);
167 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
168 continue;
170 if (status < 0)
171 return (status);
173 if (status == 0)
174 {
175 DEBUG ("Received EOF from fd %i. "
176 "Closing fd and returning error.",
177 fd);
178 close (fd);
179 return (-1);
180 }
182 assert ((0 > status) || (nleft >= (size_t)status));
184 nleft = nleft - status;
185 ptr = ptr + status;
186 }
188 return (0);
189 }
192 ssize_t swrite (int fd, const void *buf, size_t count)
193 {
194 const char *ptr;
195 size_t nleft;
196 ssize_t status;
198 ptr = (const char *) buf;
199 nleft = count;
201 while (nleft > 0)
202 {
203 status = write (fd, (const void *) ptr, nleft);
205 if ((status < 0) && ((errno == EAGAIN) || (errno == EINTR)))
206 continue;
208 if (status < 0)
209 return (status);
211 nleft = nleft - status;
212 ptr = ptr + status;
213 }
215 return (0);
216 }
218 int strsplit (char *string, char **fields, size_t size)
219 {
220 size_t i;
221 char *ptr;
222 char *saveptr;
224 i = 0;
225 ptr = string;
226 saveptr = NULL;
227 while ((fields[i] = strtok_r (ptr, " \t\r\n", &saveptr)) != NULL)
228 {
229 ptr = NULL;
230 i++;
232 if (i >= size)
233 break;
234 }
236 return (i);
237 }
239 int strjoin (char *dst, size_t dst_len,
240 char **fields, size_t fields_num,
241 const char *sep)
242 {
243 size_t field_len;
244 size_t sep_len;
245 int i;
247 memset (dst, '\0', dst_len);
249 if (fields_num <= 0)
250 return (-1);
252 sep_len = 0;
253 if (sep != NULL)
254 sep_len = strlen (sep);
256 for (i = 0; i < (int)fields_num; i++)
257 {
258 if ((i > 0) && (sep_len > 0))
259 {
260 if (dst_len <= sep_len)
261 return (-1);
263 strncat (dst, sep, dst_len);
264 dst_len -= sep_len;
265 }
267 field_len = strlen (fields[i]);
269 if (dst_len <= field_len)
270 return (-1);
272 strncat (dst, fields[i], dst_len);
273 dst_len -= field_len;
274 }
276 return (strlen (dst));
277 }
279 int strsubstitute (char *str, char c_from, char c_to)
280 {
281 int ret;
283 if (str == NULL)
284 return (-1);
286 ret = 0;
287 while (*str != '\0')
288 {
289 if (*str == c_from)
290 {
291 *str = c_to;
292 ret++;
293 }
294 str++;
295 }
297 return (ret);
298 } /* int strsubstitute */
300 int escape_slashes (char *buf, int buf_len)
301 {
302 int i;
304 if (strcmp (buf, "/") == 0)
305 {
306 if (buf_len < 5)
307 return (-1);
309 strncpy (buf, "root", buf_len);
310 return (0);
311 }
313 if (buf_len <= 1)
314 return (0);
316 /* Move one to the left */
317 if (buf[0] == '/')
318 memmove (buf, buf + 1, buf_len - 1);
320 for (i = 0; i < buf_len - 1; i++)
321 {
322 if (buf[i] == '\0')
323 break;
324 else if (buf[i] == '/')
325 buf[i] = '_';
326 }
327 buf[i] = '\0';
329 return (0);
330 } /* int escape_slashes */
332 int timeval_sub_timespec (struct timeval *tv0, struct timeval *tv1, struct timespec *ret)
333 {
334 if ((tv0 == NULL) || (tv1 == NULL) || (ret == NULL))
335 return (-2);
337 if ((tv0->tv_sec < tv1->tv_sec)
338 || ((tv0->tv_sec == tv1->tv_sec) && (tv0->tv_usec < tv1->tv_usec)))
339 return (-1);
341 ret->tv_sec = tv0->tv_sec - tv1->tv_sec;
342 ret->tv_nsec = 1000 * ((long) (tv0->tv_usec - tv1->tv_usec));
344 if (ret->tv_nsec < 0)
345 {
346 assert (ret->tv_sec > 0);
348 ret->tv_nsec += 1000000000;
349 ret->tv_sec -= 1;
350 }
352 return (0);
353 }
355 int check_create_dir (const char *file_orig)
356 {
357 struct stat statbuf;
359 char file_copy[512];
360 char dir[512];
361 int dir_len = 512;
362 char *fields[16];
363 int fields_num;
364 char *ptr;
365 char *saveptr;
366 int last_is_file = 1;
367 int path_is_absolute = 0;
368 int len;
369 int i;
371 /*
372 * Sanity checks first
373 */
374 if (file_orig == NULL)
375 return (-1);
377 if ((len = strlen (file_orig)) < 1)
378 return (-1);
379 else if (len >= 512)
380 return (-1);
382 /*
383 * If `file_orig' ends in a slash the last component is a directory,
384 * otherwise it's a file. Act accordingly..
385 */
386 if (file_orig[len - 1] == '/')
387 last_is_file = 0;
388 if (file_orig[0] == '/')
389 path_is_absolute = 1;
391 /*
392 * Create a copy for `strtok_r' to destroy
393 */
394 strncpy (file_copy, file_orig, 512);
395 file_copy[511] = '\0';
397 /*
398 * Break into components. This will eat up several slashes in a row and
399 * remove leading and trailing slashes..
400 */
401 ptr = file_copy;
402 saveptr = NULL;
403 fields_num = 0;
404 while ((fields[fields_num] = strtok_r (ptr, "/", &saveptr)) != NULL)
405 {
406 ptr = NULL;
407 fields_num++;
409 if (fields_num >= 16)
410 break;
411 }
413 /*
414 * For each component, do..
415 */
416 for (i = 0; i < (fields_num - last_is_file); i++)
417 {
418 /*
419 * Do not create directories that start with a dot. This
420 * prevents `../../' attacks and other likely malicious
421 * behavior.
422 */
423 if (fields[i][0] == '.')
424 {
425 ERROR ("Cowardly refusing to create a directory that begins with a `.' (dot): `%s'", file_orig);
426 return (-2);
427 }
429 /*
430 * Join the components together again
431 */
432 dir[0] = '/';
433 if (strjoin (dir + path_is_absolute, dir_len - path_is_absolute,
434 fields, i + 1, "/") < 0)
435 {
436 ERROR ("strjoin failed: `%s', component #%i", file_orig, i);
437 return (-1);
438 }
440 if (stat (dir, &statbuf) == -1)
441 {
442 if (errno == ENOENT)
443 {
444 if (mkdir (dir, 0755) == -1)
445 {
446 char errbuf[1024];
447 ERROR ("check_create_dir: mkdir (%s): %s", dir,
448 sstrerror (errno,
449 errbuf, sizeof (errbuf)));
450 return (-1);
451 }
452 }
453 else
454 {
455 char errbuf[1024];
456 ERROR ("stat (%s): %s", dir,
457 sstrerror (errno, errbuf,
458 sizeof (errbuf)));
459 return (-1);
460 }
461 }
462 else if (!S_ISDIR (statbuf.st_mode))
463 {
464 ERROR ("stat (%s): Not a directory!", dir);
465 return (-1);
466 }
467 }
469 return (0);
470 } /* check_create_dir */
472 #ifdef HAVE_LIBKSTAT
473 int get_kstat (kstat_t **ksp_ptr, char *module, int instance, char *name)
474 {
475 char ident[128];
477 if (kc == NULL)
478 return (-1);
480 snprintf (ident, 128, "%s,%i,%s", module, instance, name);
481 ident[127] = '\0';
483 if (*ksp_ptr == NULL)
484 {
485 if ((*ksp_ptr = kstat_lookup (kc, module, instance, name)) == NULL)
486 {
487 ERROR ("Cound not find kstat %s", ident);
488 return (-1);
489 }
491 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
492 {
493 WARNING ("kstat %s has wrong type", ident);
494 *ksp_ptr = NULL;
495 return (-1);
496 }
497 }
499 #ifdef assert
500 assert (*ksp_ptr != NULL);
501 assert ((*ksp_ptr)->ks_type == KSTAT_TYPE_NAMED);
502 #endif
504 if (kstat_read (kc, *ksp_ptr, NULL) == -1)
505 {
506 WARNING ("kstat %s could not be read", ident);
507 return (-1);
508 }
510 if ((*ksp_ptr)->ks_type != KSTAT_TYPE_NAMED)
511 {
512 WARNING ("kstat %s has wrong type", ident);
513 return (-1);
514 }
516 return (0);
517 }
519 long long get_kstat_value (kstat_t *ksp, char *name)
520 {
521 kstat_named_t *kn;
522 long long retval = -1LL;
524 #ifdef assert
525 assert (ksp != NULL);
526 assert (ksp->ks_type == KSTAT_TYPE_NAMED);
527 #else
528 if (ksp == NULL)
529 {
530 fprintf (stderr, "ERROR: %s:%i: ksp == NULL\n", __FILE__, __LINE__);
531 return (-1LL);
532 }
533 else if (ksp->ks_type != KSTAT_TYPE_NAMED)
534 {
535 fprintf (stderr, "ERROR: %s:%i: ksp->ks_type != KSTAT_TYPE_NAMED\n", __FILE__, __LINE__);
536 return (-1LL);
537 }
538 #endif
540 if ((kn = (kstat_named_t *) kstat_data_lookup (ksp, name)) == NULL)
541 return (retval);
543 if (kn->data_type == KSTAT_DATA_INT32)
544 retval = (long long) kn->value.i32;
545 else if (kn->data_type == KSTAT_DATA_UINT32)
546 retval = (long long) kn->value.ui32;
547 else if (kn->data_type == KSTAT_DATA_INT64)
548 retval = (long long) kn->value.i64; /* According to ANSI C99 `long long' must hold at least 64 bits */
549 else if (kn->data_type == KSTAT_DATA_UINT64)
550 retval = (long long) kn->value.ui64; /* XXX: Might overflow! */
551 else
552 WARNING ("get_kstat_value: Not a numeric value: %s", name);
554 return (retval);
555 }
556 #endif /* HAVE_LIBKSTAT */
558 unsigned long long ntohll (unsigned long long n)
559 {
560 #if BYTE_ORDER == BIG_ENDIAN
561 return (n);
562 #else
563 return (((unsigned long long) ntohl (n)) << 32) + ntohl (n >> 32);
564 #endif
565 } /* unsigned long long ntohll */
567 unsigned long long htonll (unsigned long long n)
568 {
569 #if BYTE_ORDER == BIG_ENDIAN
570 return (n);
571 #else
572 return (((unsigned long long) htonl (n)) << 32) + htonl (n >> 32);
573 #endif
574 } /* unsigned long long htonll */
576 #if FP_LAYOUT_NEED_NOTHING
577 /* Well, we need nothing.. */
578 /* #endif FP_LAYOUT_NEED_NOTHING */
580 #elif FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP
581 # if FP_LAYOUT_NEED_ENDIANFLIP
582 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xff00000000000000LL) >> 56) | \
583 (((uint64_t)(A) & 0x00ff000000000000LL) >> 40) | \
584 (((uint64_t)(A) & 0x0000ff0000000000LL) >> 24) | \
585 (((uint64_t)(A) & 0x000000ff00000000LL) >> 8) | \
586 (((uint64_t)(A) & 0x00000000ff000000LL) << 8) | \
587 (((uint64_t)(A) & 0x0000000000ff0000LL) << 24) | \
588 (((uint64_t)(A) & 0x000000000000ff00LL) << 40) | \
589 (((uint64_t)(A) & 0x00000000000000ffLL) << 56))
590 # else
591 # define FP_CONVERT(A) ((((uint64_t)(A) & 0xffffffff00000000LL) >> 32) | \
592 (((uint64_t)(A) & 0x00000000ffffffffLL) << 32))
593 # endif
595 double ntohd (double d)
596 {
597 union
598 {
599 uint8_t byte[8];
600 uint64_t integer;
601 double floating;
602 } ret;
604 ret.floating = d;
606 /* NAN in x86 byte order */
607 if ((ret.byte[0] == 0x00) && (ret.byte[1] == 0x00)
608 && (ret.byte[2] == 0x00) && (ret.byte[3] == 0x00)
609 && (ret.byte[4] == 0x00) && (ret.byte[5] == 0x00)
610 && (ret.byte[6] == 0xf8) && (ret.byte[7] == 0x7f))
611 {
612 return (NAN);
613 }
614 else
615 {
616 uint64_t tmp;
618 tmp = ret.integer;
619 ret.integer = FP_CONVERT (tmp);
620 return (ret.floating);
621 }
622 } /* double ntohd */
624 double htond (double d)
625 {
626 union
627 {
628 uint8_t byte[8];
629 uint64_t integer;
630 double floating;
631 } ret;
633 if (isnan (d))
634 {
635 ret.byte[0] = ret.byte[1] = ret.byte[2] = ret.byte[3] = 0x00;
636 ret.byte[4] = ret.byte[5] = 0x00;
637 ret.byte[6] = 0xf8;
638 ret.byte[7] = 0x7f;
639 return (ret.floating);
640 }
641 else
642 {
643 uint64_t tmp;
645 ret.floating = d;
646 tmp = FP_CONVERT (ret.integer);
647 ret.integer = tmp;
648 return (ret.floating);
649 }
650 } /* double htond */
651 #endif /* FP_LAYOUT_NEED_ENDIANFLIP || FP_LAYOUT_NEED_INTSWAP */
653 int format_name (char *ret, int ret_len,
654 const char *hostname,
655 const char *plugin, const char *plugin_instance,
656 const char *type, const char *type_instance)
657 {
658 int status;
660 assert (plugin != NULL);
661 assert (type != NULL);
663 if ((plugin_instance == NULL) || (strlen (plugin_instance) == 0))
664 {
665 if ((type_instance == NULL) || (strlen (type_instance) == 0))
666 status = snprintf (ret, ret_len, "%s/%s/%s",
667 hostname, plugin, type);
668 else
669 status = snprintf (ret, ret_len, "%s/%s/%s-%s",
670 hostname, plugin, type,
671 type_instance);
672 }
673 else
674 {
675 if ((type_instance == NULL) || (strlen (type_instance) == 0))
676 status = snprintf (ret, ret_len, "%s/%s-%s/%s",
677 hostname, plugin, plugin_instance,
678 type);
679 else
680 status = snprintf (ret, ret_len, "%s/%s-%s/%s-%s",
681 hostname, plugin, plugin_instance,
682 type, type_instance);
683 }
685 if ((status < 1) || (status >= ret_len))
686 return (-1);
687 return (0);
688 } /* int format_name */
690 int parse_identifier (char *str, char **ret_host,
691 char **ret_plugin, char **ret_plugin_instance,
692 char **ret_type, char **ret_type_instance)
693 {
694 char *hostname = NULL;
695 char *plugin = NULL;
696 char *plugin_instance = NULL;
697 char *type = NULL;
698 char *type_instance = NULL;
700 hostname = str;
701 if (hostname == NULL)
702 return (-1);
704 plugin = strchr (hostname, '/');
705 if (plugin == NULL)
706 return (-1);
707 *plugin = '\0'; plugin++;
709 type = strchr (plugin, '/');
710 if (type == NULL)
711 return (-1);
712 *type = '\0'; type++;
714 plugin_instance = strchr (plugin, '-');
715 if (plugin_instance != NULL)
716 {
717 *plugin_instance = '\0';
718 plugin_instance++;
719 }
721 type_instance = strchr (type, '-');
722 if (type_instance != NULL)
723 {
724 *type_instance = '\0';
725 type_instance++;
726 }
728 *ret_host = hostname;
729 *ret_plugin = plugin;
730 *ret_plugin_instance = plugin_instance;
731 *ret_type = type;
732 *ret_type_instance = type_instance;
733 return (0);
734 } /* int parse_identifier */
736 int parse_values (char *buffer, value_list_t *vl, const data_set_t *ds)
737 {
738 int i;
739 char *dummy;
740 char *ptr;
741 char *saveptr;
743 i = -1;
744 dummy = buffer;
745 saveptr = NULL;
746 while ((ptr = strtok_r (dummy, ":", &saveptr)) != NULL)
747 {
748 dummy = NULL;
750 if (i >= vl->values_len)
751 break;
753 if (i == -1)
754 {
755 if (strcmp ("N", ptr) == 0)
756 vl->time = time (NULL);
757 else
758 vl->time = (time_t) atoi (ptr);
759 }
760 else
761 {
762 if (strcmp ("U", ptr) == 0)
763 vl->values[i].gauge = NAN;
764 else if (ds->ds[i].type == DS_TYPE_COUNTER)
765 vl->values[i].counter = atoll (ptr);
766 else if (ds->ds[i].type == DS_TYPE_GAUGE)
767 vl->values[i].gauge = atof (ptr);
768 }
770 i++;
771 } /* while (strtok_r) */
773 if ((ptr != NULL) || (i != vl->values_len))
774 return (-1);
775 return (0);
776 } /* int parse_values */
778 #if !HAVE_GETPWNAM_R
779 int getpwnam_r (const char *name, struct passwd *pwbuf, char *buf,
780 size_t buflen, struct passwd **pwbufp)
781 {
782 int status = 0;
783 struct passwd *pw;
785 memset (pwbuf, '\0', sizeof (struct passwd));
787 pthread_mutex_lock (&getpwnam_r_lock);
789 do
790 {
791 pw = getpwnam (name);
792 if (pw == NULL)
793 {
794 status = (errno != 0) ? errno : ENOENT;
795 break;
796 }
798 #define GETPWNAM_COPY_MEMBER(member) \
799 if (pw->member != NULL) \
800 { \
801 int len = strlen (pw->member); \
802 if (len >= buflen) \
803 { \
804 status = ENOMEM; \
805 break; \
806 } \
807 sstrncpy (buf, pw->member, buflen); \
808 pwbuf->member = buf; \
809 buf += (len + 1); \
810 buflen -= (len + 1); \
811 }
812 GETPWNAM_COPY_MEMBER(pw_name);
813 GETPWNAM_COPY_MEMBER(pw_passwd);
814 GETPWNAM_COPY_MEMBER(pw_gecos);
815 GETPWNAM_COPY_MEMBER(pw_dir);
816 GETPWNAM_COPY_MEMBER(pw_shell);
818 pwbuf->pw_uid = pw->pw_uid;
819 pwbuf->pw_gid = pw->pw_gid;
821 if (pwbufp != NULL)
822 *pwbufp = pwbuf;
823 } while (0);
825 pthread_mutex_unlock (&getpwnam_r_lock);
827 return (status);
828 } /* int getpwnam_r */
829 #endif /* !HAVE_GETPWNAM_R */
831 int notification_init (notification_t *n, int severity, const char *message,
832 const char *host,
833 const char *plugin, const char *plugin_instance,
834 const char *type, const char *type_instance)
835 {
836 memset (n, '\0', sizeof (notification_t));
838 n->severity = severity;
840 if (message != NULL)
841 strncpy (n->message, message, sizeof (n->message));
842 if (host != NULL)
843 strncpy (n->host, host, sizeof (n->host));
844 if (plugin != NULL)
845 strncpy (n->plugin, plugin, sizeof (n->plugin));
846 if (plugin_instance != NULL)
847 strncpy (n->plugin_instance, plugin_instance,
848 sizeof (n->plugin_instance));
849 if (type != NULL)
850 strncpy (n->type, type, sizeof (n->type));
851 if (type_instance != NULL)
852 strncpy (n->type_instance, type_instance,
853 sizeof (n->type_instance));
855 n->message[sizeof (n->message) - 1] = '\0';
856 n->host[sizeof (n->host) - 1] = '\0';
857 n->plugin[sizeof (n->plugin) - 1] = '\0';
858 n->plugin_instance[sizeof (n->plugin_instance) - 1] = '\0';
859 n->type[sizeof (n->type) - 1] = '\0';
860 n->type_instance[sizeof (n->type_instance) - 1] = '\0';
862 return (0);
863 } /* int notification_init */